The Open Framework for Building Agents
feat(selfmod): open registry setup in the TUI (#2641)
prhae09c721b732a
diff --git a/.changeset/selfmod-registry-add.md b/.changeset/selfmod-registry-add.mdindex 20de73336..8d63c74bb 100644--- a/.changeset/selfmod-registry-add.md+++ b/.changeset/selfmod-registry-add.md@@ -10,6 +10,7 @@ pausing the authored-source watcher for the whole install and reporting theitem's declared environment variables that are still unset. Failed dependencyinstalls restore tracked project files and return a sanitized, structured reasoninstead of implying the project was untouched. Items that declare a setup flow-or multiple components are never partially installed: they are reported back-untouched with the command that finishes them, so no setup question is ever-answered by the model.+or multiple components are never partially installed: the local dev TUI now+opens their existing setup panel automatically, while headless development+reports the command that finishes them, so no setup question is answered by the+model.diff --git a/packages/eve-self-modification/README.md b/packages/eve-self-modification/README.mdindex a0fc7a646..4de4b68f1 100644--- a/packages/eve-self-modification/README.md+++ b/packages/eve-self-modification/README.md@@ -43,6 +43,6 @@ The extension also provides `selfmod__search_registry` to search the eve registr`selfmod__registry_add` installs an item from the configured eve registry — `eve add <address> --non-interactive --skip-setup` in the application root — so the subagent can add an existing integration instead of hand-writing one. It runs only under `eve dev`, requires approval the first time per session, and holds the authored-source watcher suspended for the whole install.-It installs only items that declare no setup command and no components. An item that declares either is reported back untouched, with the command that completes it: setup flows ask for credentials and open browser authorizations, and neither can be answered from a chat turn. No setup question ever reaches the model, and no secret ever enters the transcript.+It installs only items that declare no setup command and no components. An item that declares either is reported back untouched: in the local dev TUI, the result opens the existing `/add <address>` setup panel automatically; headless development reports the shell command instead. Setup flows ask for credentials and open browser authorizations, and neither can be answered from a chat turn. No setup question ever reaches the model, and no secret ever enters the transcript.An installed item's result names the environment variables it declares that are not set, so an item that installed cleanly but cannot yet work is reported as such rather than as bare success.diff --git a/packages/eve-self-modification/extension/instructions.ts b/packages/eve-self-modification/extension/instructions.tsindex 212e5b57b..36e733f9f 100644--- a/packages/eve-self-modification/extension/instructions.ts+++ b/packages/eve-self-modification/extension/instructions.ts@@ -7,11 +7,11 @@ The source code of the eve agent is mounted read-write at /source. Use bash onlyUse selfmod__edit_file for precise changes to existing files; every edits[].oldText must match exactly. When changing multiple separate locations in one file, use one call with multiple entries in edits[]. Each oldText is matched against the original file, not after earlier edits are applied. Do not emit overlapping or nested edits; merge nearby changes into one edit. Keep oldText as small as possible while still being unique. Use write_file only for new files or complete rewrites.-Before writing an integration by hand, check whether the eve registry already ships it, and install it with selfmod__registry_add using the exact item address (for example \`channel/slack\`). The tool installs only items that need no setup. When it reports \`needs-terminal\`, nothing was installed: relay its message and the command it names, and do not attempt to reproduce the item's setup by editing files. Never ask the developer for a credential and never repeat one; report the names of unset environment variables and stop there.+Before writing an integration by hand, check whether the eve registry already ships it with selfmod__search_registry, then install an exact match with selfmod__registry_add using its address (for example \`channel/slack\`). The tool installs items that need no setup. In the local dev TUI, a \`needs-terminal\` result automatically opens the existing setup panel; tell the developer to continue there, and do not ask them to retype the command. In headless development, relay the terminal command the tool names. Never reproduce a registry item's setup by editing files, ask the developer for a credential, or repeat one. Report the names of unset environment variables and stop there. Say when the project already has an item. Write an integration yourself only when the registry has nothing that fits, or the developer asks for a custom implementation.Group independent calls, including bash and reads, in one response.-Registry installation is outside the source sandbox. When the developer asks what this agent can integrate with, or asks for a capability an existing integration may already provide, call selfmod__search_registry before writing anything by hand. Prefer a registry item. When you find an exact item, install it with selfmod__registry_add unless the project already has it. Write an integration yourself only when the registry has nothing that fits, or the developer asks for a custom implementation.+Registry installation is outside the source sandbox.The eve framework documentation is mounted read-only at /eve-docs. Read the eve guide directly relevant to an unfamiliar public API. Prefer an existing local implementation pattern over broad documentation research.diff --git a/packages/eve-self-modification/extension/tools/registry_add.ts b/packages/eve-self-modification/extension/tools/registry_add.tsindex d30715467..a270fb682 100644--- a/packages/eve-self-modification/extension/tools/registry_add.ts+++ b/packages/eve-self-modification/extension/tools/registry_add.ts@@ -100,24 +100,25 @@ export function unsetEnvVars(/*** Builds the handoff a `needs-terminal` item carries.*- * `/add <address>` (`runRegistryFlow`'s `initialAddress`) skips the category- * and search screens and opens that item's confirmation directly, so an- * interactive client is offered the address-specific command rather than bare- * `/add`, which would make the developer re-find the item in the category- * browser. Headless `eve dev` has no TUI to dispatch a slash command into, so- * the shell command is the only honest answer there.+ * The interactive TUI consumes `status` and `address` to open the existing+ * address-specific setup flow itself, so its model-facing result deliberately+ * carries no command for the model to repeat. Headless `eve dev` has no TUI to+ * dispatch into, so the shell command is the only honest answer there.*/export function handoffMessage(input: {readonly address: string;readonly interactiveClient: boolean;readonly reason: string;readonly title: string;-}): { readonly message: string; readonly nextCommand: string } {- const nextCommand = input.interactiveClient- ? `/add ${input.address}`- : `eve add ${input.address}`;+}): { readonly message: string; readonly nextCommand?: string } {+ if (input.interactiveClient) {+ return {+ message: `${input.title} was not installed by this tool. ${input.reason} Continue in the setup panel that opens here; do not ask the developer to run another command.`,+ };+ }+ const nextCommand = `eve add ${input.address}`;return {- message: `${input.title} was not installed. ${input.reason} Run \`${nextCommand}\` ${input.interactiveClient ? "here" : "in a terminal"} to finish it.`,+ message: `${input.title} was not installed. ${input.reason} Run \`${nextCommand}\` in a terminal to finish it.`,nextCommand,};}diff --git a/packages/eve-self-modification/extension/tools/search_registry.ts b/packages/eve-self-modification/extension/tools/search_registry.tsindex 1dc2ed975..54962ddee 100644--- a/packages/eve-self-modification/extension/tools/search_registry.ts+++ b/packages/eve-self-modification/extension/tools/search_registry.ts@@ -496,7 +496,7 @@ async function annotateInstalled(input: {export default defineTool({description:- "Search the eve registry for integrations this project can add: channels, MCP connections, extensions, and observability. Read-only — it installs nothing. Call it before writing an integration by hand, then pass an exact result address (for example `channel/slack`) to selfmod__registry_add.",+ "Search the eve registry for integrations this project can add: channels, MCP connections, extensions, and observability. Read-only — it installs nothing. Call it before writing an integration by hand, then pass an exact item address (for example `channel/slack`) to selfmod__registry_add.",inputSchema,outputSchema,async execute(input, ctx) {diff --git a/packages/eve-self-modification/src/registry-add.test.ts b/packages/eve-self-modification/src/registry-add.test.tsindex 9ff98ce0f..cd69f3347 100644--- a/packages/eve-self-modification/src/registry-add.test.ts+++ b/packages/eve-self-modification/src/registry-add.test.ts@@ -143,16 +143,14 @@ describe("addRegistryItem", () => {expect(calls).toHaveLength(0);});- it("offers the address-specific /add command when an interactive client owns the terminal", async () => {+ it("leaves the automatically queued setup to an interactive client", async () => {const result = await addRegistryItem("channel/slack", {getCapability: () => capability({ interactiveClient: true }),});- // `/add <address>` (runRegistryFlow's initialAddress) jumps straight to- // that item's confirmation screen, skipping the category browser bare- // `/add` would otherwise require.- expect(result.nextCommand).toBe("/add channel/slack");- expect(result.message).toContain("/add channel/slack");+ expect(result.nextCommand).toBeUndefined();+ expect(result.message).toContain("setup panel");+ expect(result.message).toContain("do not ask the developer to run another command");});it("installs an exact item from a configured registry without restricting its address", async () => {@@ -339,7 +337,7 @@ describe("handoffMessage", () => {});});- it("names the address-specific /add command with an interactive client", () => {+ it("directs an interactive client to the automatically opened setup panel", () => {expect(handoffMessage({address: "channel/slack",@@ -348,8 +346,7 @@ describe("handoffMessage", () => {title: "Slack",}),).toEqual({- message: expect.stringContaining("`/add channel/slack`"),- nextCommand: "/add channel/slack",+ message: expect.stringContaining("setup panel"),});});});diff --git a/packages/eve/src/cli/dev/tui/runner.test.ts b/packages/eve/src/cli/dev/tui/runner.test.tsindex 5110a414c..81c9c33a4 100644--- a/packages/eve/src/cli/dev/tui/runner.test.ts+++ b/packages/eve/src/cli/dev/tui/runner.test.ts@@ -19,10 +19,12 @@ import type { VercelDeploymentResolution } from "#setup/vercel-deployment.js";import {EveTUIRunner,parsePromptCommand,+ registryHandoffAddress,type AgentTUIAgentHeader,type AgentTUIRenderer,type AgentTUISessionOptions,type AgentTUIStreamEvent,+ type PromptCommand,type PromptCommandOutcome,} from "./runner.js";import { createPromptCommandHandler } from "./prompt-command-handler.js";@@ -44,6 +46,372 @@ const REMOTE_VERIFIED_TARGET = await resolveTestVercelTarget({const VERCEL_SSO_URL ="https://vercel.com/sso-api?url=https%3A%2F%2Fvpoke.playground-vercel.tools&nonce=test";+describe("registryHandoffAddress", () => {+ it("accepts only a terminal handoff from the self-modification registry tool", () => {+ expect(+ registryHandoffAddress("selfmod__registry_add", {+ status: "needs-terminal",+ address: "channel/slack",+ }),+ ).toBe("channel/slack");+ expect(+ registryHandoffAddress("selfmod__registry_add", {+ status: "installed",+ address: "extension/browserbase",+ }),+ ).toBeUndefined();+ expect(+ registryHandoffAddress("other_tool", {+ status: "needs-terminal",+ address: "channel/slack",+ }),+ ).toBeUndefined();+ });++ it("opens every distinct registry handoff in result order", async () => {+ const handledCommands: Array<Extract<PromptCommand, { type: "extension" }>> = [];+ const handle = vi.fn(async (command: Extract<PromptCommand, { type: "extension" }>) => {+ handledCommands.push(command);+ return { message: "done" };+ });+ const renderer = fakeRenderer({+ readPrompt: vi+ .fn()+ .mockResolvedValueOnce("add integrations")+ .mockResolvedValueOnce(undefined),+ renderStream: vi.fn(async (result) => {+ for await (const _event of result.events as AsyncIterable<AgentTUIStreamEvent>) {+ // Consume the turn so both handoffs reach the runner queue.+ }+ }),+ });++ await new EveTUIRunner({+ session: sessionYielding([+ {+ type: "actions.requested",+ data: {+ actions: [+ {+ callId: "slack-add",+ input: { address: "channel/slack" },+ kind: "tool-call",+ toolName: "selfmod__registry_add",+ },+ {+ callId: "linear-add",+ input: { address: "connection/linear" },+ kind: "tool-call",+ toolName: "selfmod__registry_add",+ },+ ],+ },+ },+ {+ type: "action.result",+ data: {+ result: {+ callId: "slack-add",+ kind: "tool-result",+ output: { status: "needs-terminal", address: "channel/slack" },+ },+ status: "completed",+ },+ },+ {+ type: "action.result",+ data: {+ result: {+ callId: "linear-add",+ kind: "tool-result",+ output: { status: "needs-terminal", address: "connection/linear" },+ },+ status: "completed",+ },+ },+ { type: "session.completed" },+ ]),+ renderer,+ name: "Weather Agent",+ appRoot: "/tmp/weather-agent",+ bootDetections: [],+ detectProjectIdentity: vi.fn(async () => undefined),+ promptCommandHandler: { handle },+ }).run();++ expect(handledCommands).toEqual([+ { type: "extension", name: "add", argument: "channel/slack" },+ { type: "extension", name: "add", argument: "connection/linear" },+ ]);+ });++ it("submits a parallel approval response before opening queued setup", async () => {+ const order: string[] = [];+ const session = stubSession();+ vi.spyOn(session, "send").mockResolvedValueOnce(+ messageResponseOf([+ {+ type: "actions.requested",+ data: {+ actions: [+ {+ callId: "registry-add",+ input: { address: "channel/slack" },+ kind: "tool-call",+ toolName: "selfmod__registry_add",+ },+ ],+ },+ },+ {+ type: "action.result",+ data: {+ result: {+ callId: "registry-add",+ kind: "tool-result",+ output: { status: "needs-terminal", address: "channel/slack" },+ },+ status: "completed",+ },+ },+ {+ type: "input.requested",+ data: {+ requests: [+ {+ action: {+ callId: "write-file",+ input: { path: "agent.ts" },+ kind: "tool-call",+ toolName: "write_file",+ },+ display: "confirmation",+ kind: "tool-approval",+ options: [+ { id: "approve", label: "Approve" },+ { id: "cancel", label: "Cancel" },+ ],+ prompt: "Approve write_file",+ requestId: "approval-1",+ },+ ],+ },+ },+ { type: "session.waiting" },+ ]),+ );+ vi.spyOn(session, "respond").mockImplementationOnce(async () => {+ order.push("respond");+ return messageResponseOf([{ type: "session.completed" }]);+ });+ const handle = vi.fn(async () => {+ order.push("setup");+ return { message: "done" };+ });++ await new EveTUIRunner({+ session,+ renderer: fakeRenderer({+ readPrompt: vi.fn().mockResolvedValueOnce("add slack").mockResolvedValueOnce(undefined),+ readToolApproval: vi.fn(async () => ({ approved: true })),+ renderStream: vi.fn(async (result) => {+ for await (const _event of result.events as AsyncIterable<AgentTUIStreamEvent>) {+ // Consume each continuation to its boundary.+ }+ }),+ }),+ name: "Weather Agent",+ appRoot: "/tmp/weather-agent",+ bootDetections: [],+ detectProjectIdentity: vi.fn(async () => undefined),+ promptCommandHandler: { handle },+ }).run();++ expect(order).toEqual(["respond", "setup"]);+ expect(session.respond).toHaveBeenCalledWith(+ [{ requestId: "approval-1", optionId: "approve" }],+ expect.any(Object),+ );+ });++ it("suspends the idle prompt before opening a subagent registry handoff", async () => {+ const idlePromptStarted = createDeferred<void>();+ const promptSuspended = createDeferred<void>();+ const handle = vi.fn(async () => ({+ message: "Slack setup completed.",+ tone: "success" as const,+ }));+ const client = stubClient();+ const fetchChild = vi+ .spyOn(client, "fetch")+ .mockResolvedValueOnce(+ messageStreamResponseOf([+ stampTestEvent(+ {+ type: "actions.requested",+ data: {+ actions: [+ {+ callId: "registry-add",+ input: { address: "channel/slack" },+ kind: "tool-call",+ toolName: "selfmod__registry_add",+ },+ ],+ sequence: 1,+ stepIndex: 0,+ turnId: "child-turn",+ },+ } as UnstampedMessageStreamEvent,+ 0,+ ),+ stampTestEvent(+ {+ type: "input.requested",+ data: {+ requests: [+ {+ action: {+ callId: "registry-add",+ input: { address: "channel/slack" },+ kind: "tool-call",+ toolName: "selfmod__registry_add",+ },+ display: "confirmation",+ kind: "tool-approval",+ options: [+ { id: "approve", label: "Approve" },+ { id: "cancel", label: "Cancel" },+ ],+ prompt: "Approve tool call: selfmod__registry_add",+ requestId: "approval-1",+ },+ ],+ sequence: 2,+ stepIndex: 0,+ turnId: "child-turn",+ },+ } as UnstampedMessageStreamEvent,+ 1,+ ),+ stampTestEvent(+ {+ type: "session.waiting",+ data: { continuationToken: "child-session", wait: "next-user-message" },+ } as UnstampedMessageStreamEvent,+ 2,+ ),+ ]),+ )+ .mockImplementationOnce(async () => {+ await idlePromptStarted.promise;+ return messageStreamResponseOf([+ stampTestEvent(+ {+ type: "actions.requested",+ data: {+ actions: [+ {+ callId: "registry-add",+ input: { address: "channel/slack" },+ kind: "tool-call",+ toolName: "selfmod__registry_add",+ },+ ],+ sequence: 3,+ stepIndex: 0,+ turnId: "child-turn",+ },+ } as UnstampedMessageStreamEvent,+ 3,+ ),+ stampTestEvent(+ {+ type: "action.result",+ data: {+ result: {+ callId: "registry-add",+ kind: "tool-result",+ output: { status: "needs-terminal", address: "channel/slack" },+ toolName: "selfmod__registry_add",+ },+ sequence: 4,+ status: "completed",+ stepIndex: 0,+ turnId: "child-turn",+ },+ } as UnstampedMessageStreamEvent,+ 4,+ ),+ stampTestEvent({ type: "session.completed" } as UnstampedMessageStreamEvent, 5),+ ]);+ });+ const renderer = fakeRenderer({+ readPrompt: vi+ .fn()+ .mockResolvedValueOnce("add slack")+ .mockImplementationOnce(async () => {+ idlePromptStarted.resolve();+ await promptSuspended.promise;+ return undefined;+ }),+ renderStream: vi.fn(async (result) => {+ for await (const _event of result.events as AsyncIterable<AgentTUIStreamEvent>) {+ // Consume the parent stream while the child pump follows its session.+ }+ }),+ suspendPromptForInput: () => promptSuspended.resolve(),+ subagents: {+ begin: vi.fn(),+ background: vi.fn(),+ upsertStep: vi.fn(),+ upsertTool: vi.fn(),+ removeTool: vi.fn(),+ complete: vi.fn(),+ markChildToolCallId: vi.fn(),+ },+ });++ await new EveTUIRunner({+ client,+ session: sessionYielding([+ {+ type: "subagent.called",+ data: {+ callId: "selfmod-call",+ childSessionId: "child-session",+ childStreamPath: "/eve/v1/session/child-session/stream",+ name: "self-modification",+ sequence: 0,+ turnId: "parent-turn",+ },+ },+ { type: "turn.completed", data: { sequence: 1, turnId: "parent-turn" } },+ {+ type: "session.waiting",+ data: { continuationToken: "parent-session", wait: "next-user-message" },+ },+ ]),+ renderer,+ name: "Weather Agent",+ appRoot: "/tmp/weather-agent",+ bootDetections: [],+ detectProjectIdentity: vi.fn(async () => undefined),+ promptCommandHandler: { handle },+ }).run();++ expect(fetchChild).toHaveBeenNthCalledWith(+ 2,+ "/eve/v1/session/child-session/stream?startIndex=3",+ expect.objectContaining({ signal: expect.any(AbortSignal) }),+ );+ expect(handle).toHaveBeenCalledWith(+ { type: "extension", name: "add", argument: "channel/slack" },+ expect.objectContaining({ title: "Add to your agent" }),+ );+ });+});+/*** Real `Client` whose network-touching methods are replaced by vi spies.* Keeps the runner's option types honest (no double casts) while stilldiff --git a/packages/eve/src/cli/dev/tui/runner.ts b/packages/eve/src/cli/dev/tui/runner.tsindex 76cb6d8cf..930093c8e 100644--- a/packages/eve/src/cli/dev/tui/runner.ts+++ b/packages/eve/src/cli/dev/tui/runner.ts@@ -546,6 +546,11 @@ export class EveTUIRunner {readonly #pendingInputRequests = new Map<string, InputRequest>();/** Idle wake result handed from the prompt follower into the normal HITL response loop. */#idleInputResult?: AgentTUIStreamResult;+ /** Registry setups queued by tool results on root or child streams. */+ readonly #pendingRegistrySetups: string[] = [];+ #activeRegistrySetup?: string;+ /** True only while the idle prompt owns terminal input. */+ #readingPrompt = false;/*** callId → live state for one subagent dispatch. Persists across turn* boundaries because a subagent dispatched in one turn may not emit@@ -591,6 +596,12 @@ export class EveTUIRunner {const pumpOptions: SubagentPumpOptions = { formatActionResultError };if (this.#client !== undefined) pumpOptions.client = this.#client;if (this.#renderer.subagents !== undefined) pumpOptions.view = this.#renderer.subagents;+ if (options.appRoot !== undefined) {+ pumpOptions.onToolCompleted = async (toolName, output) => {+ const address = registryHandoffAddress(toolName, output);+ if (address !== undefined) this.#queueRegistrySetup(address);+ };+ }this.#subagentPump = new SubagentPump(pumpOptions);this.#name = options.name ?? "eve";this.#headerTip = options.startup?.headerTip ?? pickAgentHeaderTip();@@ -774,6 +785,24 @@ export class EveTUIRunner {if (this.#lifecycle?.signal.aborted === true || this.#renderer.exitRequested?.() === true) {return;}+ const pendingRegistrySetup = this.#pendingRegistrySetups[0];+ if (+ pendingRegistrySetup !== undefined &&+ pendingInputResponses === undefined &&+ this.#idleInputResult === undefined+ ) {+ this.#pendingRegistrySetups.shift();+ this.#activeRegistrySetup = pendingRegistrySetup;+ try {+ await this.#openRegistrySetup(pendingRegistrySetup);+ } finally {+ this.#activeRegistrySetup = undefined;+ }+ followCurrentSession = false;+ streamWithoutPrompt = false;+ prompt = undefined;+ continue;+ }if (!streamWithoutPrompt) {if (prompt == null) {if (!this.#renderer.readPrompt) {@@ -793,17 +822,26 @@ export class EveTUIRunner {}try {+ this.#readingPrompt = true;prompt = await this.#readPromptFollowingSession(promptOptions);} catch (error) {if (isInterruptedError(error)) {- if (this.#idleInputResult === undefined) return;+ if (this.#idleInputResult === undefined && this.#pendingRegistrySetups.length === 0) {+ return;+ }streamWithoutPrompt = true;prompt = "";} else {throw error;}+ } finally {+ this.#readingPrompt = false;}+ if (this.#pendingRegistrySetups.length > 0 && this.#idleInputResult === undefined) {+ prompt = undefined;+ continue;+ }if (prompt == null && this.#idleInputResult === undefined) {return;}@@ -1511,6 +1549,10 @@ export class EveTUIRunner {onTurnCancelled: (turnId) => this.#subagentPump.settleCancelledTurn(turnId),onConnectionAuthRequired: (event) => this.#handleConnectionAuthRequired(event),onConnectionAuthCompleted: (event) => this.#handleConnectionAuthCompleted(event),+ onRegistryHandoff:+ this.#appRoot === undefined+ ? undefined+ : async (address) => this.#queueRegistrySetup(address),onTerminalFailure: () => {this.#failedSession = sourceSession;},@@ -1520,6 +1562,22 @@ export class EveTUIRunner {};}+ #queueRegistrySetup(address: string): void {+ if (this.#activeRegistrySetup === address || this.#pendingRegistrySetups.includes(address)) {+ return;+ }+ this.#pendingRegistrySetups.push(address);+ if (this.#readingPrompt) this.#renderer.suspendPromptForInput?.();+ }++ async #openRegistrySetup(address: string): Promise<void> {+ await this.#executeExtensionCommand(+ { type: "extension", name: "add", argument: address },+ "Add to your agent",+ { trigger: "command" },+ );+ }+async #renderSetupIssues(info: AgentInfoResult | undefined): Promise<void> {if (this.#appRoot === undefined) return;const context: BootDetectionContext = {@@ -1977,6 +2035,8 @@ type EveStreamTranslatorInput = {onTurnCancelled?: (turnId: string) => void;onConnectionAuthRequired?: (event: AuthorizationRequiredStreamEvent) => void;onConnectionAuthCompleted?: (event: AuthorizationCompletedStreamEvent) => void;+ /** Opens a setup-bearing registry item in the existing `/add` flow. */+ onRegistryHandoff?: (address: string) => Promise<void>;onTerminalFailure?: (event: SessionFailedStreamEvent) => void;/*** Replaces a failure's structured hint with a surface-local one (the@@ -1986,6 +2046,22 @@ type EveStreamTranslatorInput = {failureHintOverride?: (event: FailureStreamEvent) => string | undefined;};+const SELFMOD_REGISTRY_ADD_TOOL = "selfmod__registry_add";++/** Returns the registry address carried by a self-modification terminal handoff. */+export function registryHandoffAddress(+ toolName: string | undefined,+ output: unknown,+): string | undefined {+ if (toolName !== SELFMOD_REGISTRY_ADD_TOOL || typeof output !== "object" || output === null) {+ return undefined;+ }+ const result = output as { address?: unknown; status?: unknown };+ return result.status === "needs-terminal" && typeof result.address === "string"+ ? result.address+ : undefined;+}+/*** Reduces one eve session-stream turn into renderer-native TUI events.* eve events name assistant/reasoning sections by `turnId` + `stepIndex`;@@ -2004,11 +2080,13 @@ async function* eveEventsToTUIStream(onTurnCancelled,onConnectionAuthRequired,onConnectionAuthCompleted,+ onRegistryHandoff,onTerminalFailure,failureHintOverride,} = input;const textParts = new Map<string, StreamPartState>();const reasoningParts = new Map<string, StreamPartState>();+ const toolNames = new Map<string, string>();// Dropping re-delivered events here means every case below is a new emission.const seenEvents = createEventDeduper();// Counts `step.started` events. The harness reuses `stepIndex` across the@@ -2196,6 +2274,7 @@ async function* eveEventsToTUIStream(if (actions.length === 0) break;for (const action of actions) {+ toolNames.set(action.callId, action.toolName);if (knownToolCalls.has(action.callId)) continue;knownToolCalls.add(action.callId);yield {@@ -2215,6 +2294,7 @@ async function* eveEventsToTUIStream(for (const request of requests) {const toolCallId = request.action.callId;+ toolNames.set(toolCallId, request.action.toolName);// The session-limit continuation is harness-authored — no model// tool call exists behind it, so fabricating a transcript entry@@ -2262,13 +2342,17 @@ async function* eveEventsToTUIStream(break;}switch (resultEvent.data.status) {- case "completed":+ case "completed": {+ const output = resultEvent.data.result.output;yield {type: "tool-result",toolCallId: callId,- output: resultEvent.data.result.output,+ output,};+ const address = registryHandoffAddress(toolNames.get(callId), output);+ if (address !== undefined) await onRegistryHandoff?.(address);break;+ }case "failed":yield {type: "tool-error",diff --git a/packages/eve/src/cli/dev/tui/subagent-pump.test.ts b/packages/eve/src/cli/dev/tui/subagent-pump.test.tsindex 5c8235b7c..bebf34d99 100644--- a/packages/eve/src/cli/dev/tui/subagent-pump.test.ts+++ b/packages/eve/src/cli/dev/tui/subagent-pump.test.ts@@ -272,6 +272,127 @@ describe("SubagentPump background receipts", () => {});describe("SubagentPump child stream transport", () => {+ it("resumes from the prior cursor when a conversation subagent is called again", async () => {+ const client = new Client({ host: "http://localhost:3000" });+ const fetch = vi+ .spyOn(client, "fetch")+ .mockResolvedValueOnce(responseOf([boundaryEvent(0)]))+ .mockResolvedValueOnce(+ responseOf([+ stampTestEvent(+ {+ type: "actions.requested",+ data: {+ actions: [+ {+ callId: "registry-add",+ input: { address: "channel/slack" },+ kind: "tool-call",+ toolName: "selfmod__registry_add",+ },+ ],+ sequence: 1,+ stepIndex: 0,+ turnId: "child-turn-2",+ },+ } as UnstampedMessageStreamEvent,+ 1,+ ),+ stampTestEvent(+ {+ type: "action.result",+ data: {+ result: {+ callId: "registry-add",+ kind: "tool-result",+ output: { status: "needs-terminal", address: "channel/slack" },+ toolName: "selfmod__registry_add",+ },+ sequence: 2,+ status: "completed",+ stepIndex: 0,+ turnId: "child-turn-2",+ },+ } as UnstampedMessageStreamEvent,+ 2,+ ),+ stampTestEvent({ type: "session.completed" } as UnstampedMessageStreamEvent, 3),+ ]),+ );+ const onToolCompleted = vi.fn(async () => {});+ const view = fakeView();+ const pump = new SubagentPump({+ client,+ view,+ formatActionResultError: () => "failed",+ onToolCompleted,+ });+ const first = subagentCalled("call-1");+ first.data.childSessionId = "conversation-child";+ const second = subagentCalled("call-2", "turn-2");+ second.data.childSessionId = "conversation-child";++ pump.begin(first);+ await vi.waitFor(() =>+ expect(view.complete).toHaveBeenCalledWith({ authoritative: true, callId: "call-1" }),+ );+ pump.begin(second);+ await vi.waitFor(() => expect(onToolCompleted).toHaveBeenCalledOnce());++ expect(fetch).toHaveBeenNthCalledWith(+ 2,+ "/eve/v1/children/call-2/stream?startIndex=1",+ expect.objectContaining({ signal: expect.any(AbortSignal) }),+ );+ expect(onToolCompleted).toHaveBeenCalledWith("selfmod__registry_add", {+ status: "needs-terminal",+ address: "channel/slack",+ });+ });++ it("does not let a repeated call consume the previous call's trailing boundary", async () => {+ const firstStream = pushableChildStream();+ const client = new Client({ host: "http://localhost:3000" });+ const fetch = vi+ .spyOn(client, "fetch")+ .mockImplementationOnce(async (_path, init) =>+ firstStream.response(init?.signal ?? undefined),+ )+ .mockResolvedValueOnce(+ responseOf([+ reasoningEvent("second turn", 1),+ stampTestEvent({ type: "session.completed" } as UnstampedMessageStreamEvent, 2),+ ]),+ );+ const view = fakeView();+ const pump = new SubagentPump({ client, view, formatActionResultError: () => "failed" });+ const first = subagentCalled("call-1");+ first.data.childSessionId = "conversation-child";+ const second = subagentCalled("call-2", "turn-2");+ second.data.childSessionId = "conversation-child";++ pump.begin(first);+ await settleAsyncWork();+ pump.settle("call-1");+ pump.begin(second);+ await settleAsyncWork();++ expect(fetch).toHaveBeenCalledOnce();++ firstStream.push(boundaryEvent(0));+ await vi.waitFor(() => expect(fetch).toHaveBeenCalledTimes(2));+ await vi.waitFor(() =>+ expect(view.upsertStep).toHaveBeenCalledWith(+ expect.objectContaining({ callId: "call-2", reasoning: "second turn" }),+ ),+ );+ expect(fetch).toHaveBeenNthCalledWith(+ 2,+ "/eve/v1/children/call-2/stream?startIndex=1",+ expect.objectContaining({ signal: expect.any(AbortSignal) }),+ );+ });+it("leaves connection authorization events to the parent runner", async () => {const client = new Client({ host: "http://localhost:3000" });vi.spyOn(client, "fetch").mockResolvedValue(diff --git a/packages/eve/src/cli/dev/tui/subagent-pump.ts b/packages/eve/src/cli/dev/tui/subagent-pump.tsindex d04702e40..2673aa4e5 100644--- a/packages/eve/src/cli/dev/tui/subagent-pump.ts+++ b/packages/eve/src/cli/dev/tui/subagent-pump.ts@@ -65,6 +65,7 @@ type SubagentToolState = {export type SubagentRun = {name: string;+ childSessionId: string;/** Parent turn that originated this dispatch; cancellation is scoped to it. */parentTurnId: string;/** A receipt-returned task survives cancellation of its originating turn. */@@ -123,19 +124,28 @@ export interface SubagentPumpOptions {client?: Client;view?: SubagentView;formatActionResultError: (event: ActionResultStreamEvent) => string;+ /** Runs TUI-owned handling after a child tool result becomes visible. */+ onToolCompleted?: (toolName: string, output: unknown) => Promise<void>;}export class SubagentPump {readonly #client: Client | undefined;readonly #view: SubagentView | undefined;readonly #formatActionResultError: (event: ActionResultStreamEvent) => string;+ readonly #onToolCompleted: ((toolName: string, output: unknown) => Promise<void>) | undefined;readonly #runs = new Map<string, SubagentRun>();readonly #pumps = new Map<string, AbortController>();+ /** Durable child cursor shared by repeated calls into one conversation subagent. */+ readonly #childStreamIndices = new Map<string, number>();+ /** One stream follower owns a conversation child session through its boundary. */+ readonly #activeChildCalls = new Map<string, string>();+ readonly #queuedChildCalls = new Map<string, string[]>();constructor(options: SubagentPumpOptions) {this.#client = options.client;this.#view = options.view;this.#formatActionResultError = options.formatActionResultError;+ this.#onToolCompleted = options.onToolCompleted;}/**@@ -153,11 +163,12 @@ export class SubagentPump {if (existing === undefined) {this.#runs.set(callId, {name: called.data.name,+ childSessionId: called.data.childSessionId,parentTurnId: called.data.turnId,background: false,status: "open",childStreamPath: called.data.childStreamPath,- childStreamIndex: 0,+ childStreamIndex: this.#childStreamIndices.get(called.data.childSessionId) ?? 0,steps: new Map(),currentSectionKey: null,nextSectionKey: 0,@@ -170,7 +181,8 @@ export class SubagentPump {this.#view?.markChildToolCallId(callId);if (existing !== undefined && existing.status !== "open") return;this.#view?.begin({ callId, name: called.data.name });- this.#startPump(called);+ if (existing !== undefined) return;+ this.#activateOrQueue(callId);}/**@@ -201,6 +213,9 @@ export class SubagentPump {}this.#pumps.clear();this.#runs.clear();+ this.#childStreamIndices.clear();+ this.#activeChildCalls.clear();+ this.#queuedChildCalls.clear();}/**@@ -228,8 +243,23 @@ export class SubagentPump {* times out. Pumps stay open across HITL prompts and resume rendering when* the subagent unparks; they end on the child's own boundary or via abort.*/- #startPump(called: SubagentCalledStreamEvent) {- const callId = called.data.callId;+ #activateOrQueue(callId: string): void {+ const run = this.#runs.get(callId);+ if (run === undefined || run.status === "authoritative") return;+ const activeCallId = this.#activeChildCalls.get(run.childSessionId);+ if (activeCallId === undefined) {+ run.childStreamIndex = this.#childStreamIndices.get(run.childSessionId) ?? 0;+ this.#activeChildCalls.set(run.childSessionId, callId);+ this.#startPump(callId);+ return;+ }+ if (activeCallId === callId) return;+ const queued = this.#queuedChildCalls.get(run.childSessionId) ?? [];+ if (!queued.includes(callId)) queued.push(callId);+ this.#queuedChildCalls.set(run.childSessionId, queued);+ }++ #startPump(callId: string) {if (this.#pumps.has(callId)) return;const client = this.#client;if (!client) return;@@ -261,8 +291,14 @@ export class SubagentPump {if (controller.signal.aborted) return;deliveredEvent = true;run.childStreamIndex += 1;- this.#applyChildEvent(callId, event);+ this.#childStreamIndices.set(run.childSessionId, run.childStreamIndex);+ const childEventWork = this.#applyChildEvent(callId, event);+ if (childEventWork !== undefined) await childEventWork;if (isCurrentTurnBoundaryEvent(event)) {+ // A proxied child approval parks at an intermediate+ // `session.waiting`. Keep following from this cursor so the+ // approved tool result can still update the nested view.+ if (event.type === "session.waiting" && hasPendingChildApproval(run)) continue;this.#finalizeRun(callId, true);return;}@@ -299,19 +335,26 @@ export class SubagentPump {status: request.status,};if (existing) {- // Promote status only when the new status is "stronger" — e.g.- // approval-requested → executing once the parent approves, but- // never demote from done/failed back to executing.- const priority: Record<SubagentToolState["status"], number> = {- preparing: 0,- "approval-requested": 1,- executing: 2,- done: 3,- failed: 3,- rejected: 3,- };- if (priority[request.status] > priority[existing.status]) {+ const terminal =+ existing.status === "done" ||+ existing.status === "failed" ||+ existing.status === "rejected";+ if (request.status === "approval-requested" && !terminal) {+ // Some providers announce the action before eve parks it for+ // approval. The later input request is the live state, not a demotion.existing.status = request.status;+ } else {+ const priority: Record<SubagentToolState["status"], number> = {+ preparing: 0,+ "approval-requested": 1,+ executing: 2,+ done: 3,+ failed: 3,+ rejected: 3,+ };+ if (priority[request.status] > priority[existing.status]) {+ existing.status = request.status;+ }}// A late `preparing` announcement must not wipe input the full call// already delivered.@@ -360,6 +403,31 @@ export class SubagentPump {run.currentSectionKey = null;this.#sweepPreparingTools(callId, run);this.#view?.complete({ authoritative, callId });+ if (authoritative) this.#releaseChildSession(callId, run.childSessionId);+ }++ #releaseChildSession(callId: string, childSessionId: string): void {+ const queued = this.#queuedChildCalls.get(childSessionId) ?? [];+ const remaining = queued.filter((queuedCallId) => queuedCallId !== callId);+ if (this.#activeChildCalls.get(childSessionId) !== callId) {+ if (remaining.length === 0) this.#queuedChildCalls.delete(childSessionId);+ else this.#queuedChildCalls.set(childSessionId, remaining);+ return;+ }++ this.#activeChildCalls.delete(childSessionId);+ while (remaining.length > 0) {+ const nextCallId = remaining.shift()!;+ const nextRun = this.#runs.get(nextCallId);+ if (nextRun === undefined || nextRun.status === "authoritative") continue;+ if (remaining.length === 0) this.#queuedChildCalls.delete(childSessionId);+ else this.#queuedChildCalls.set(childSessionId, remaining);+ nextRun.childStreamIndex = this.#childStreamIndices.get(childSessionId) ?? 0;+ this.#activeChildCalls.set(childSessionId, nextCallId);+ this.#startPump(nextCallId);+ return;+ }+ this.#queuedChildCalls.delete(childSessionId);}/**@@ -376,7 +444,7 @@ export class SubagentPump {}}- #applyChildEvent(callId: string, event: MessageStreamEvent) {+ #applyChildEvent(callId: string, event: MessageStreamEvent): Promise<void> | undefined {const run = this.#runs.get(callId);if (!run) return;if (!run.seenChildEvents.admit(event)) return;@@ -511,6 +579,9 @@ export class SubagentPump {if (tool.output !== undefined) update.output = tool.output;if (tool.errorText !== undefined) update.errorText = tool.errorText;view?.upsertTool(update);+ if (event.data.status === "completed") {+ return this.#onToolCompleted?.(tool.toolName, result.output);+ }break;}default:@@ -521,6 +592,10 @@ export class SubagentPump {}}+function hasPendingChildApproval(run: SubagentRun): boolean {+ return [...run.tools.values()].some((tool) => tool.status === "approval-requested");+}+function streamPathAt(path: string, startIndex: number): string {if (startIndex === 0) return path;return `${path}${path.includes("?") ? "&" : "?"}startIndex=${startIndex}`;