Repository navigation
feat(mcp): add tools to deliver input to, wait on, and close agent sessions - #422
Merged
Merged
Conversation
The notification listener read right after accept() and closed the connection on EWOULDBLOCK, so a hook client that had connected but not yet written lost its notification. The hook clients swallow send errors, so a lost done/awaiting_approval was silent. Read with a deadline until newline or EOF instead.
…ssions architect-mcp gains list_sessions, send_input, wait_for_session, and terminate_session next to spawn_session, so an orchestrator can drive interactive agents turn by turn without polling. - app/agent_state.zig: hook-driven per-session agent state with an app-wide sequence number, read by the control listener - app/control.zig: op/arguments wire format shared with architect-mcp; the listener parks wait_for_session connections and answers them from the agent-state board, so pending waits never wake the main loop - app/agent_control.zig: main-thread list and send_input handlers; require_idle checks and writes atomically - terminate_session reuses the tile-close despawn path, deferred until after the frame's UI actions - control.zig tests now run in the exe test binary (they were not collected by any test binary before) Design and rejected alternatives: docs/superpowers/specs/2026-11-04-mcp-agent-control-design.md
…ompts A new session stayed unknown until the agent's first Stop hook, so an orchestrator could not deliver the first message after spawn_session. Add a ready notification state: architect hook claude now installs SessionStart -> ready, which moves only an unknown agent to idle (it also fires on /clear and compaction, which must not override a later state), and UserPromptSubmit -> start, so prompts a human types into the tile mark the agent working. The design doc records the chosen readiness signal and why treating unknown as deliverable was rejected, and lists graceful terminate, re-attach labels, and Codex/Gemini lifecycle hooks as follow-ups.
spawn_session types its command into the new shell, often while the terminal is still in canonical mode, where macOS keeps at most 1024 bytes per line and drops the rest including the newline. A 1195-byte command never ran while a 1495-byte one happened to arrive after zsh switched to raw mode. Limit command to 1023 bytes with an explicit error and point clients at a script. Also add a test that a second require_idle send right after a delivery is refused without any hook event, and record the real Claude Code and Codex end-to-end results in the design doc.
There was a problem hiding this comment.
🟡 Changes recommended
Control requests run before queued hook notifications, allowing deliveries to busy agents and stale completion signals to falsely satisfy waits for a new turn.
7 open issues
Apply queued hooks before control requests · New Keep agent state unchanged for unsubmitted drafts · New Preserve parked waits after request-side EOF · New Mark tiles running after a submitted delivery · New Reconcile sessions before processing hook notifications · New Reject oversized input sent through canonical-mode PTYs · New Install startup hooks without filtered matchers · New
What changed in this PR
Extends Architect’s MCP interface from session creation to turn-by-turn agent control, allowing external orchestrators to send input, wait for agent state changes, and close sessions.
Changes:
- Adds four MCP tools, a shared control protocol, and hook-driven agent-state tracking with listener-managed waits.
- Integrates input delivery and termination into the runtime, adds Claude lifecycle hooks, and fixes delayed notification reads.
- Expands tests and their registration, limits startup command length, and documents the new tools and architecture.
Build, tests, and lint were not run in this review environment.
| File | Description |
|---|---|
src/shell.zig |
Installs Claude ready and start hooks. |
src/session/notify.zig |
Waits for delayed notification data and recognizes ready signals. |
src/mcp/main.zig |
Exposes all five control tools and their schemas. |
src/main.zig |
Registers control and agent-module tests. |
src/env.zig |
Exposes environment initialization for tests. |
src/app/terminal_actions.zig |
Adds paste payloads with optional submission. |
src/app/runtime.zig |
Handles control requests, hook updates, and deferred termination. |
src/app/control.zig |
Implements shared validation, replies, and parked waits. |
src/app/agent_state.zig |
Adds the agent-state board and sequence-based wait evaluation. |
src/app/agent_control.zig |
Implements session listing, input delivery, and board reconciliation. |
scripts/perf/spawn_session.py |
Uses the updated control request format. |
scripts/check-test-registry.sh |
Requires explicit registration of control tests. |
scripts/architect_notify.py |
Accepts the ready notification state. |
README.md |
Introduces the expanded MCP capabilities. |
docs/superpowers/specs/2026-11-04-mcp-agent-control-design.md |
Records design decisions, verification notes, and follow-ups. |
docs/perf-debugging.md |
Updates the control-socket request example. |
docs/ARCHITECTURE.md |
Documents agent-state modules and control flows. |
docs/ai-integration.md |
Defines tool contracts and agent orchestration workflows. |
CLAUDE.md |
Documents control-channel and notification-handling invariants. |
Review effort: Balanced
Copilot review of the PR found ordering and edge-case gaps: - Control requests ran before the frame's hook notifications, so a require_idle delivery could ignore a queued start and an older done could overwrite the delivery. Reconcile sessions first, then apply hooks, then run control requests. - An unsubmitted draft marked the agent working although no turn starts, leaving it busy forever. Only submitted deliveries change the state. - A client that half-closes after its request was treated as gone. On macOS that is indistinguishable from a full close, so keep the wait parked and stop polling it; a vanished client shows up as a failed reply write. - Submitted deliveries now mark the tile running and clear attention, like a start hook, for agents without one. - Without bracketed paste a single line above 1023 bytes could be lost to the canonical-mode line limit; reject it as input_not_ready. - architect hook claude reused the first group, inheriting a matcher such as SessionStart "resume". Install into an unfiltered group and only count unfiltered groups as installed.
…at shutdown Review found two defects: - Without bracketed paste only LF was rejected, but CR submits a line too, so an unsubmitted draft like "echo one\recho two" could run its first line at a shell prompt. Reject both CR and LF in either submit mode. - The listener could queue a request after shutdown had already failed the queue (a request still being read when stop was set), then block forever on its completion while the runtime joined the thread. The queue now has a closed flag set under its lock by closeAndFail, and push refuses with app_not_running once it is set.
…oks off the tile Review found two more defects: - Session ids restart at 0 in every app, but architect-mcp resolved the newest discovery entry on every call, so opening a second Architect could route send_input or terminate_session for session 0 to an unrelated terminal. Each app now generates an instance_id (pid plus a random 64-bit value) at startup, publishes it in its discovery file, and returns it from every tool. send_input, wait_for_session, and terminate_session require it; the helper routes only to that instance and fails with instance_not_found instead of trying another, and the app rejects requests naming a different instance. spawn_session and list_sessions still default to the newest instance. - Hook signals the agent board ignored still changed the tile, so a SessionStart during a mid-turn compaction showed the agent idle. applyHook now reports its outcome and the tile only follows accepted signals, except Claude's idle reminder, which keeps its existing attention highlight while the agent state stays idle.
…p is running With no discovery file left (the only app shut down cleanly), a request naming an instance returned app_not_running, while the same request returned instance_not_found when the app left a stale file or another instance was running. Targeted requests now fail with instance_not_found in every case; untargeted spawn and list keep app_not_running.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.


TLDR
External tools can now control AI agents that run in Architect terminals. A tool can send a message to an agent, wait until the agent finishes its turn, and close the terminal. Before this change, a tool could only open a terminal.
Issue
architect-mcpexposed onlyspawn_session. An orchestrator that runs interactive Claude Code or Codex agents in Architect terminals (for example Mu, which today starts oneclaude -p/codex execprocess per chat message) had no way to:Building and testing this against real agents also exposed three existing bugs:
accept()and dropped the connection when the hook client had not written yet. The hooks ignore send errors, sodone/awaiting_approvalnotifications could be lost without any sign.spawn_sessiontypes itscommandinto the new shell, often while the terminal is still in canonical mode, where macOS keeps only 1024 bytes per line. Longer commands could be silently dropped (a 1195-byte command never ran).app/control.zigdeclared tests that no test binary collected.Solution
spawn_session:list_sessions,send_input,wait_for_session,terminate_session. They are generic, with no knowledge of any orchestrator.instance_id,session_id). Each app generates aninstance_id(pid plus a random 64-bit value) at startup, publishes it in its discovery file, and returns it from every tool.send_input,wait_for_session, andterminate_sessionrequireinstance_id;architect-mcproutes them only to that instance and fails with the new errorinstance_not_foundwhen it is not running (stale file, clean shutdown, or no app at all), never falling back to another app. The app also rejects a request that names a different instance.spawn_sessionandlist_sessionstake an optionalinstance_idand otherwise use the newest instance.app/agent_state.zig): each session hasunknown | working | awaiting_approval | idle | exitedplus an app-widestate_seq. Agent hooks drive it (ready,start,done,awaiting_approval).send_inputsetsworkingin the same main-thread step as the write, so delivery does not depend on any agent's hook. Withrequire_idle, the check and the write are atomic. Claude's idle-reminder notification is ignored while the agent is idle. Unsubmitted drafts (submit: false) do not change the state. Within a frame, sessions are reconciled, then hook notifications applied, then control requests run, sorequire_idlesees every signal that arrived before it.readyduring a mid-turn compaction) leaves the tile unchanged; the idle reminder keeps its existing attention highlight while the state staysidle. A submitted delivery marks the tile running.wait_for_sessionconnections in itspoll(2)set and answers them from the board when it changes, the deadline passes, or the client goes away. A pending wait never wakes the frame loop (measured: same CPU as fully idle).architect hook claudenow also installsSessionStart → ready(only movesunknown → idle) andUserPromptSubmit → start. Agents without areadyhook start with their first message on the command line.{"op","arguments"}→{"ok","result"}, validated by the same parser in the app and inarchitect-mcp.app_not_runninginstead of blocking the listener while the runtime joins it. Parked waits survive a client that half-closes its socket after sending the request.spawn_sessionrejects commands over 1023 bytes with an explicit error;control.zigtests are registered.Per-conversation context stays on the orchestrator side: one Architect session per (agent, conversation), started with the agent's own session id (
claude --session-id/--resume,codex resume).Context
docs/superpowers/specs/2026-11-04-mcp-agent-control-design.mddocs/ai-integration.mdready, two turns) and Codex 0.166.0 (first message on the command line, a second turn viasend_input,session_busyon an early second send, terminate).architect-mcpwithinvalid_request. Upgrade both together.send_input,wait_for_session, andterminate_sessionrequire theinstance_idreturned byspawn_sessionorlist_sessions; store it with thesession_id.ready/starthooks (Codex 0.166 hooks need user review before they run).architect hook claudeto get the two new hooks.Test plan
architect hook claudein an Architect terminal on a machine with existing hooks; confirmSessionStartandUserPromptSubmitentries are added once and existing hooks are kept.architect-mcpand close it withterminate_sessionin both grid and full view; confirm the grid compacts and focus moves like closing the tile by hand.