Skip to content

fix(api): align POST /start with UI PTY path — MCP for all agents#56

Open
Zai69 wants to merge 1 commit into
Charlie85270:mainfrom
Zai69:feat/api-start-pty-mcp-alignment
Open

fix(api): align POST /start with UI PTY path — MCP for all agents#56
Zai69 wants to merge 1 commit into
Charlie85270:mainfrom
Zai69:feat/api-start-pty-mcp-alignment

Conversation

@Zai69

@Zai69 Zai69 commented May 24, 2026

Copy link
Copy Markdown

Summary

The HTTP API POST /api/agents/:id/start previously spawned a one-shot bash -l -c "cd … && claude …" session and only passed --mcp-config for Super Agent / Automation agents. Mission workers (Docs, Backend, Security, Frontend, QA) started via the API therefore had no MCP loaded — breaking ZAIOS Relay integration (relay_runtime_tools invisible).

This PR aligns the HTTP /start route with the existing UI path (ipc-handlers agent:start):

  • Kill/recycle stale PTY before start
  • initAgentPtyCallback + persistent PTY
  • getProvider('claude').buildInteractiveCommand({ mcpConfigPath, … })
  • writeProgrammaticInput(pty, \cd '…' && ${command}`)` after 500ms settle
  • --mcp-config ~/.claude/mcp.json for all agents when the file exists

Context

Validated in ZAIOS Mission #2 (avec_svc) with dorothy-mcp-attach smoke 6/6 and Dorothy live mobilize 6/6. ZAIOS canon: PRs #81–#83 on Zai69/zaios.

Test plan

  • Restart Dorothy after merge (tsc -p electron/tsconfig.json runs on electron:start)
  • Start a non–Super-Agent worker via API with a prompt referencing MCP
  • Confirm ~/.claude/mcp.json servers appear in Claude session (no MCP config file not found)
  • ZAIOS: make dorothy-mcp-attach → 6/6 OK

Scope

Single file: electron/services/api-routes/agent-routes.ts — no UI or ipc-handlers changes.

Made with Cursor

Summary by CodeRabbit

  • Bug Fixes

    • Improved agent startup reliability by ensuring proper cleanup of existing sessions before initialization.
    • Added validation for required agent configuration parameters.
    • Enhanced state management with better tracking of agent status and activity.
  • Refactor

    • Restructured agent initialization process for improved reliability and system integration.
    • Improved event handling during agent startup and lifecycle.

Review Change Stack

Replace one-shot bash -c spawn with persistent PTY init + buildInteractiveCommand
+ writeProgrammaticInput (same as ipc-handlers agent:start). Pass --mcp-config
from ~/.claude/mcp.json to every agent, not only Super Agent / Automation.

Fixes ZAIOS Mission Charlie85270#2 workers missing relay_runtime_tools when started via
HTTP API (dorothy-mcp-attach, mission-02 delegate).

Co-authored-by: Cursor <cursoragent@cursor.com>
@vercel

vercel Bot commented May 24, 2026

Copy link
Copy Markdown

@Zai69 is attempting to deploy a commit to the Charlie Rabiller's projects Team on Vercel.

A member of the Team first needs to authorize it.

@coderabbitai

coderabbitai Bot commented May 24, 2026

Copy link
Copy Markdown
📝 Walkthrough

Walkthrough

The /api/agents/:id/start route handler is refactored from direct node-pty spawning to provider-driven command construction with callback-based PTY lifecycle management. The handler becomes async, validates model names, recycles existing PTY processes, and builds interactive commands through provider APIs with permission, MCP, and skill configuration before delegating lifecycle event handling to a registered callback.

Changes

Agent Start Route Refactor

Layer / File(s) Summary
Imports and route handler signature
electron/services/api-routes/agent-routes.ts
Import statements add OS utilities and getProvider, remove node-pty, Electron app, and buildFullPath. Route handler signature changes to async and route comment is updated to reflect PTY persistence and programmatic input workflow.
Input validation, PTY cleanup, and command building
electron/services/api-routes/agent-routes.ts
Model name validation is added. Existing PTY recycling is implemented by killing and deleting any existing process before starting a new session. Super-agent system-prompt file resolution and provider-driven interactive command building with permission mode, MCP config path, skills augmentation, and print-mode adjustments.
PTY initialization, state management, and input scheduling
electron/services/api-routes/agent-routes.ts
Working-directory command is assembled and PTY is initialized via ctx.initAgentPtyCallback with explicit error handling. Agent runtime state is updated (status set to running, currentTask assigned, output/lastCleanOutput/error reset, lastActivity refreshed), persisted, and status-change event emitted. Programmatic input execution is scheduled with a short delay after initialization instead of being wired directly in this file.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

🐰 From spawned shells to callbacks clean,
The agent's start now flows serene—
Providers build, state persists well,
Delayed input weaves its spell!
One route refactored, futures bright.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The PR title clearly reflects the main objective: aligning the POST /start API route with UI PTY path behavior and enabling MCP for all agents, which matches the core changes in the diff.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@electron/services/api-routes/agent-routes.ts`:
- Around line 248-250: The closure passed to setTimeout captures the ptyProcess
reference and can attempt to write to a killed or replaced PTY; modify the logic
around the delayed call (the setTimeout that calls
writeProgrammaticInput(ptyProcess, fullCommand)) to verify the PTY is still
valid before writing — e.g., check that the current ptyProcess is the same
instance and that it is not killed/closed (or add a boolean isRunning flag) and
cancel the pending timeout when /stop or a new /start replaces the PTY so
writeProgrammaticInput is only invoked against a live, current ptyProcess.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: f2c2354d-3a3d-462b-a0bf-8f8b7ebbeb5e

📥 Commits

Reviewing files that changed from the base of the PR and between 4482713 and 4ce9e2e.

📒 Files selected for processing (1)
  • electron/services/api-routes/agent-routes.ts

Comment on lines +248 to +250
setTimeout(() => {
writeProgrammaticInput(ptyProcess, fullCommand);
}, 500);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Potential race condition with captured PTY reference.

The ptyProcess reference is captured by the setTimeout closure. If /stop or another /start is called within 500ms, the captured reference points to a killed or replaced PTY, and writeProgrammaticInput may fail silently or throw an unhandled error.

Consider verifying the PTY is still valid before writing:

Proposed fix
 setTimeout(() => {
-  writeProgrammaticInput(ptyProcess, fullCommand);
+  const currentPty = ptyProcesses.get(ptyId);
+  if (currentPty === ptyProcess) {
+    writeProgrammaticInput(ptyProcess, fullCommand);
+  }
 }, 500);
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
setTimeout(() => {
writeProgrammaticInput(ptyProcess, fullCommand);
}, 500);
setTimeout(() => {
const currentPty = ptyProcesses.get(ptyId);
if (currentPty === ptyProcess) {
writeProgrammaticInput(ptyProcess, fullCommand);
}
}, 500);
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@electron/services/api-routes/agent-routes.ts` around lines 248 - 250, The
closure passed to setTimeout captures the ptyProcess reference and can attempt
to write to a killed or replaced PTY; modify the logic around the delayed call
(the setTimeout that calls writeProgrammaticInput(ptyProcess, fullCommand)) to
verify the PTY is still valid before writing — e.g., check that the current
ptyProcess is the same instance and that it is not killed/closed (or add a
boolean isRunning flag) and cancel the pending timeout when /stop or a new
/start replaces the PTY so writeProgrammaticInput is only invoked against a
live, current ptyProcess.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant