import { readArtifactDocument } from "../artifact-read"; import { artifactOutputContent, artifactOutputState, artifactReadOutcome, consumableArtifactCompletion, type ArtifactReadResult, type ArtifactConsumption, } from "../artifact-read-model"; import { renderArtifactRead, MAX_ARTIFACT_PROVIDER_OUTPUT_BYTES, MAX_ARTIFACT_ERROR_SUMMARY_BYTES, } from "../artifact-read-rendering"; import { convertToLlm, serializeConversation, type ExtensionAPI, } from "@earendil-works/pi-coding-agent"; import { Text } from "@earendil-works/pi-tui"; import type { AgentToolResult } from "@earendil-works/pi-agent-core"; import { Type, type Static } from "typebox"; import isPathInside from "is-path-inside"; import { readdirSync, readFileSync, realpathSync, statSync } from "node:fs"; import { homedir } from "node:os"; import { basename, dirname, join } from "node:path"; import { artifactPath, removeInteractiveState, INTERACTIVE_ARTIFACT_OWNER_FILE, loadInteractiveStates, lastEvent, MAX_TURN_ID_LENGTH, updateInteractiveState, type SubagentArtifact, } from "../artifact"; import { assertCompletionGroupOpen, reserveCompletionGroup, releaseCompletionGroup, consumeCompletionSource, registerCompletionMember, type CompletionGroupReservation, type ResolvedCompletionPolicy, resolveCompletionPolicy, } from "../completion-coordinator"; import { cancelInteractiveSubagent, captureInteractiveSubagentCreatedTelemetry, captureInteractiveSpawnFailure, getCurrentPaneActivity, removeInteractiveSubagentState, formatInteractiveState, launchInteractiveSubagent, pruneDeadInteractiveSubagents, sendCommandToPane, tmuxSetupHint, type CurrentPaneActivity, type InteractiveSubagentState, } from "../interactive-tmux"; import { debugLog } from "../helpers"; import { isOrchestratorV2Enabled } from "../completion-turn"; import { completionDisplayLabel } from "../completion-presentation"; import { MAX_ORCHESTRATOR_ROUTING_ALIASES, MAX_ORCHESTRATOR_ROUTING_ALIAS_BYTES, MAX_ORCHESTRATOR_ROUTING_DESCRIPTION_BYTES, appendOrchestratorRoutingAuthorityEntry, isValidOrchestratorChildId, isWorkflowOwnedRuntimeBlocked, upsertOrchestratorRoutingEntry, type OrchestratorRoutingEntry, } from "../orchestrator-routing"; import { InteractiveParams, MAX_INTERACTIVE_CONTEXT_BYTES } from "../schemas"; import { registerToolWithDefaultGuidance } from "../tool-guidance"; import { updateRunningSubagentFooter } from "../artifact-poller"; import { findSessionScope, getStartedSessionScopes, resolveLiveSessionScope, resolveToolSessionScope, sessionOwner, type SessionOwnerToken, type SessionScope, type SessionToolToken, } from "../session-scope"; import { captureTelemetry, telemetryDepth, telemetryDepthBucket, type TelemetryCompletionPolicy, type TelemetryResultReadOutcome, type TelemetrySpawnFailureMux, type TelemetrySpawnFailureOperation, type TelemetrySpawnFailureStage, } from "../telemetry"; import { createLaunchResolutionReporter } from "../telemetry-launch"; function isValidSubagentId(id: string): boolean { return isValidOrchestratorChildId(id); } const MAX_FOLLOWUP_BYTES = 64 * 1024; const MAX_FOLLOWUP_PREVIEW_CHARS = 500; const MAX_INTERACTIVE_OUTPUT_NAME_CHARS = 100; const MAX_INTERACTIVE_TASK_PREVIEW_CHARS = 80; const MAX_ARTIFACT_ERROR_CHARS = MAX_ARTIFACT_ERROR_SUMMARY_BYTES; const MAX_STRUCTURED_ARTIFACT_OUTPUT_CHARS = MAX_ARTIFACT_PROVIDER_OUTPUT_BYTES; const CurrentPaneActivityOutputSchema = Type.Object({ status: Type.Union([ Type.Literal("active"), Type.Literal("inactive"), Type.Literal("unknown"), ]), mux: Type.Optional( Type.Union([ Type.Literal("tmux"), Type.Literal("zellij"), Type.Literal("herdr"), Type.Literal("rex"), Type.Literal("wezterm"), Type.Literal("herdr-core"), Type.Literal("cmux"), ]), ), paneId: Type.Optional(Type.String()), session: Type.Optional(Type.String()), }); const InteractiveStatusItemOutputSchema = Type.Object({ id: Type.String(), name: Type.String({ maxLength: MAX_INTERACTIVE_OUTPUT_NAME_CHARS }), status: Type.Union([ Type.Literal("running"), Type.Literal("idle"), Type.Literal("cancelled"), Type.Literal("exited"), Type.Literal("unknown"), ]), mux: Type.Union([ Type.Literal("tmux"), Type.Literal("zellij"), Type.Literal("herdr"), Type.Literal("rex"), Type.Literal("wezterm"), Type.Literal("herdr-core"), Type.Literal("cmux"), ]), paneId: Type.String(), startedAt: Type.Number(), elapsedSeconds: Type.Number(), taskPreview: Type.String({ maxLength: MAX_INTERACTIVE_TASK_PREVIEW_CHARS }), windowName: Type.Optional( Type.String({ maxLength: MAX_INTERACTIVE_OUTPUT_NAME_CHARS }), ), exitCode: Type.Optional(Type.Number()), artifactDir: Type.String(), attachCommand: Type.String(), selectPaneCommand: Type.String(), sessionFile: Type.String(), }); const InteractiveStatusOutputSchema = Type.Object({ status: Type.Union([Type.Literal("ok"), Type.Literal("not_found")]), jobId: Type.Optional(Type.String()), count: Type.Number(), subagents: Type.Array(InteractiveStatusItemOutputSchema), }); const SubagentArtifactListOutputSchema = Type.Object({ status: Type.Literal("ok"), count: Type.Number(), artifacts: Type.Array( Type.Object({ id: Type.String(), name: Type.String({ maxLength: MAX_INTERACTIVE_OUTPUT_NAME_CHARS }), status: Type.Union([ Type.Literal("running"), Type.Literal("idle"), Type.Literal("cancelled"), Type.Literal("exited"), Type.Literal("unknown"), ]), lastUpdate: Type.Optional(Type.Number()), }), ), }); const SubagentArtifactReadOutputSchema = Type.Object({ id: Type.String(), status: Type.Union([ Type.Literal("running"), Type.Literal("done"), Type.Literal("error"), Type.Literal("cancelled"), Type.Literal("not_found"), Type.Literal("invalid_id"), ]), eventCount: Type.Number(), outputState: Type.Union([ Type.Literal("not_requested"), Type.Literal("pending"), Type.Literal("missing"), Type.Literal("empty"), Type.Literal("available"), Type.Literal("unavailable"), ]), output: Type.Union([ Type.String({ maxLength: MAX_STRUCTURED_ARTIFACT_OUTPUT_CHARS }), Type.Null(), ]), outputTruncated: Type.Boolean(), lastEvent: Type.Optional( Type.Object({ type: Type.Union([ Type.Literal("turn_started"), Type.Literal("tool_activity"), Type.Literal("completion"), Type.Literal("process_exited"), ]), ts: Type.Number(), status: Type.Union([ Type.Literal("running"), Type.Literal("done"), Type.Literal("error"), Type.Literal("cancelled"), ]), turnId: Type.String({ maxLength: MAX_TURN_ID_LENGTH }), }), ), turnId: Type.Optional(Type.String({ maxLength: MAX_TURN_ID_LENGTH })), error: Type.Optional(Type.String({ maxLength: MAX_ARTIFACT_ERROR_CHARS })), }); type SubagentArtifactReadOutput = Static< typeof SubagentArtifactReadOutputSchema >; const FOLLOWUP_COMPLETION_REMINDER = ' [MANDATORY COMPLETION PROTOCOL FOR EVERY FOLLOW-UP TURN: Before sending your final assistant response, write the result to output.md; make "$ARTIFACT_DIR/cli.mjs" done 0 your final tool call and wait for success. If it fails, do not send the final response; fix the cause and retry until completion is recorded. Do not rely on the lifecycle hook. After completion is recorded, remain in the Pi REPL and wait for follow-up; do not intentionally exit or close the pane unless explicitly asked.]'; function formatFollowupPreview(message: string): string { if (message.length <= MAX_FOLLOWUP_PREVIEW_CHARS) return message; return `${message.slice(0, MAX_FOLLOWUP_PREVIEW_CHARS)}… [truncated; ${message.length} chars total]`; } type InitialRoutingMetadataResult = | { status: "persisted"; entry: OrchestratorRoutingEntry } | { status: "warning"; error: string }; function parentBranchEntries(ctx: unknown): readonly unknown[] { if (!ctx || typeof ctx !== "object") return []; const sessionManager = (ctx as { sessionManager?: unknown }).sessionManager; if (!sessionManager || typeof sessionManager !== "object") return []; const getBranch = (sessionManager as { getBranch?: unknown }).getBranch; if (typeof getBranch !== "function") return []; try { const branch = getBranch.call(sessionManager); return Array.isArray(branch) ? branch : []; } catch { return []; } } function persistInitialRoutingMetadata(params: { cwd: string; childId: string; description?: string; aliases?: string[]; authorityEntries?: readonly unknown[]; pi?: ExtensionAPI; }): InitialRoutingMetadataResult | undefined { if (params.description === undefined) return undefined; if (!isValidSubagentId(params.childId)) { return { status: "warning", error: `spawn returned invalid child id ${params.childId}`, }; } try { const overlay = upsertOrchestratorRoutingEntry( params.cwd, { childId: params.childId, description: params.description!, ...(params.aliases === undefined ? {} : { aliases: params.aliases }), provenance: "orchestratorv2", }, { authorityEntries: params.authorityEntries ?? [] }, ); const entry = overlay.records.find( (record) => record.childId === params.childId, ); if (!entry) throw new Error("routing metadata update was not persisted"); appendOrchestratorRoutingAuthorityEntry(params.pi ?? {}, params.cwd, entry); return { status: "persisted", entry }; } catch (error) { return { status: "warning", error: error instanceof Error ? error.message : String(error), }; } } function validateInitialRoutingMetadata( description: string | undefined, aliases: string[] | undefined, ): string | undefined { if (aliases !== undefined && description === undefined) { return "routingAliases requires routingDescription"; } if (description === undefined) return undefined; if (description.trim().length === 0) { return "description must be a non-empty string"; } const descriptionBytes = Buffer.byteLength(description, "utf8"); if (descriptionBytes > MAX_ORCHESTRATOR_ROUTING_DESCRIPTION_BYTES) { return `description exceeds ${MAX_ORCHESTRATOR_ROUTING_DESCRIPTION_BYTES} bytes`; } if (aliases === undefined) return undefined; if (aliases.length > MAX_ORCHESTRATOR_ROUTING_ALIASES) { return `aliases exceeds ${MAX_ORCHESTRATOR_ROUTING_ALIASES} entries`; } const seen = new Set(); for (const alias of aliases) { if (alias.trim().length === 0) return "alias must be a non-empty string"; if ( Buffer.byteLength(alias, "utf8") > MAX_ORCHESTRATOR_ROUTING_ALIAS_BYTES ) { return `alias exceeds ${MAX_ORCHESTRATOR_ROUTING_ALIAS_BYTES} bytes`; } if (seen.has(alias)) return `duplicate alias: ${alias}`; seen.add(alias); } return undefined; } function validateRoutingMetadataMode( topLevelOrchestratorV2: boolean, description: string | undefined, aliases: string[] | undefined, ): string | undefined { if (topLevelOrchestratorV2 && description === undefined) { return "routingDescription is required for a top-level Orchestratorv2 child"; } if (!topLevelOrchestratorV2 && (description !== undefined || aliases)) { return "routingDescription and routingAliases are reserved for a top-level Orchestratorv2 session"; } return undefined; } function persistInteractiveRollbackTombstone( state: InteractiveSubagentState, ): void { const tombstoneAt = Date.now(); if (!state.parentSessionId) return; try { updateInteractiveState(state.cwd, state.id, (entry) => { delete entry.completionPolicy; delete entry.completionGroupId; entry.completionTombstone = "failed"; entry.completionTombstoneAt = tombstoneAt; }); } catch (error) { debugLog("warn", "interactive_spawn_tombstone_failed", { id: state.id, error: error instanceof Error ? error.message : String(error), }); } } function rollbackInteractiveSpawn(state: InteractiveSubagentState): void { state.completionPolicy = undefined; state.completionGroupId = undefined; try { cancelInteractiveSubagent(state.id, "cancel_interactive_subagent", state); } catch { /* Registration failed; pane cleanup is best effort. */ } removeInteractiveSubagentState(state); if (state.parentSessionId) { try { removeInteractiveState(state.cwd, state.id); } catch { persistInteractiveRollbackTombstone(state); } } } export function findArtifactById(id: string): SubagentArtifact | null { // Sub-agent ids are historically 4 random bytes (8 hex chars) and currently // 8 random bytes (16 hex chars). Validate before joining into a path so that // an LLM-supplied id like "../../../etc" cannot escape the artifact root. // (path.join normalises "..", so a malicious id would otherwise resolve // to a sibling directory and get exfiltrated to the parent LLM via // read_subagent_artifact). if (!isValidSubagentId(id)) return null; const root = process.env.PI_CODING_AGENT_SESSION_DIR ?? join(homedir(), ".pi", "agent", "sessions"); // Resolve the root once, with symlinks followed, so the containment check below // is anchored on the real on-disk location. realpathSync throws if root doesn't // exist; in that case there's nothing for us to find. let realRoot: string; try { realRoot = realpathSync(root); } catch { return null; } let topLevel: string[]; try { topLevel = readdirSync(root); } catch { return null; } for (const entry of topLevel) { const candidate = join(root, entry, "artifacts", id); try { if (statSync(candidate).isDirectory()) { // statSync follows symlinks, so a symlink at // //artifacts/ pointing outside the artifact root // would otherwise be returned as a valid artifact. Resolve the // candidate with realpath and verify it is still inside the // resolved root. realpathSync is safe here because statSync // above already confirmed candidate exists as a directory. let realCandidate: string; try { realCandidate = realpathSync(candidate); } catch { continue; } if (!isPathInside(realCandidate, realRoot)) continue; return artifactPath(join(root, entry, "artifacts"), id); } } catch { /* not here */ } } return null; } function getArtifactForState( state: Pick, ): SubagentArtifact { return artifactPath(dirname(state.artifactDir), basename(state.artifactDir)); } function recordArtifactReadConsumption( pi: ExtensionAPI, sourceId: string, result: ArtifactReadResult, owner: SessionOwnerToken | undefined, ): ArtifactConsumption { const completion = consumableArtifactCompletion(result); if (!completion) return "not_applicable"; // Durable consumption must succeed before output is returned to the caller. const first = consumeCompletionSource( pi, { source: "interactive", sourceId, turnId: completion.turnId, }, owner, ); return first ? "consumed" : "already_consumed"; } function readLatencyFromTerminal( terminalTs: number | undefined, readAt: number, ): number | undefined { if ( terminalTs === undefined || !Number.isSafeInteger(terminalTs) || terminalTs < 0 || !Number.isSafeInteger(readAt) || terminalTs > readAt ) { return undefined; } return readAt - terminalTs; } function resolveInteractiveToolStates(token: SessionToolToken | undefined): | { scope: SessionScope; states: Map; } | undefined { const scope = resolveToolSessionScope(token); if (scope) return { scope, states: scope.interactiveStates }; return undefined; } function findOwnedDiskArtifact( cwd: string, id: string, scope: SessionScope | undefined, ): SubagentArtifact | null { if (!scope) return findArtifactById(id); let parentSessionId: string | undefined; try { parentSessionId = scope.sessionManager?.getSessionId?.(); } catch { return null; } if (!parentSessionId) return null; const artifact = findArtifactById(id); if (!artifact) return null; try { const persistedOwner = readFileSync( join(artifact.dir, INTERACTIVE_ARTIFACT_OWNER_FILE), "utf8", ); return persistedOwner === parentSessionId ? artifact : null; } catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") return null; // Older artifacts may still have exact evidence in the persisted state file. } const persisted = loadInteractiveStates(cwd)?.states[id]; if (!persisted || persisted.parentSessionId !== parentSessionId) return null; try { return realpathSync(persisted.artifactDir) === realpathSync(artifact.dir) ? artifact : null; } catch { return null; } } function formatCurrentPaneActivity(activity: CurrentPaneActivity): string { const location = [ activity.mux ? `Mux: ${activity.mux}.` : "No verified mux pane for this Pi process.", activity.paneId ? `Pane: ${activity.paneId}.` : "", activity.session ? `Session: ${activity.session}.` : "", ] .filter(Boolean) .join(" "); return `Current pane activity: ${activity.status}. ${location}`; } export function registerInteractiveSubagentTools( pi: ExtensionAPI, registrationScope?: SessionScope, isChild = false, ): void { const toolToken: SessionToolToken | undefined = registrationScope ? { id: registrationScope.id } : undefined; registerToolWithDefaultGuidance(pi, { name: "get_current_pane_activity", label: "Current Pane Activity", description: "Run a fresh check of which mux pane owns this Pi process and whether it is active in the user's current client. Activity is advisory, not launch authority. Herdr, Herdr Core, Rex, and cmux report unknown focus without public focused-client proof.", parameters: Type.Object({}), outputSchema: CurrentPaneActivityOutputSchema, async execute() { const activity = await getCurrentPaneActivity(); return { content: [ { type: "text", text: formatCurrentPaneActivity(activity), }, ], details: activity, structuredContent: { status: activity.status, ...(activity.mux === undefined ? {} : { mux: activity.mux }), ...(activity.paneId === undefined ? {} : { paneId: activity.paneId }), ...(activity.session === undefined ? {} : { session: activity.session }), }, }; }, }); // ── Tool 7: spawn an attachable mux-backed Pi session ────────────── registerToolWithDefaultGuidance(pi, { name: "subagent_interactive", label: "Interactive Subagent", description: [ "Spawn an attachable Pi child in a supported terminal and return immediately with attach or focus commands and its session file.", "Leave mux unset unless the user selects a backend. Auto uses the verified current terminal (tmux, Zellij, Herdr, Herdr Core, WezTerm, Rex, or cmux); it uses detached tmux only when no current host is detected, not when ownership is unclear.", "Use this when the user wants to attach to the sub-agent session and continue follow-ups there.", "This is intentionally separate from SDK subagents: it favors observability and attachability over in-process execution.", "By default, prefer the current/parent provider and model.", "Honor any provider or model explicitly requested by the user.", "If a requested model omits its provider, qualify it with the current/parent provider unless the user explicitly requested another provider.", "For example, 'anthropic/claude-sonnet-4-5'.", "Completion coordination defaults to each: every terminal turn creates one TUI-only notice, while safely-idle results are coalesced into a compact immutable-reference manifest that resumes the parent.", "Use completionPolicy=group with a shared completionGroupId for related agents; the parent resumes once the spawning turn settles and every registered member is terminal.", ].join("\n"), parameters: InteractiveParams, async execute(_toolCallId, params, signal, _onUpdate, ctx) { const spawnStartedAt = Date.now(); const registration = resolveInteractiveToolStates(toolToken); const staleScope = !registration && toolToken ? findSessionScope(toolToken.id) : undefined; const spawnTreeDepth = registration?.scope?.spawnTreeContext?.depth ?? staleScope?.spawnTreeContext?.depth; const launchDepth = spawnTreeDepth === undefined ? undefined : spawnTreeDepth + 1; const telemetry = registration?.scope?.telemetry ?? staleScope?.telemetry; const completionPolicy: TelemetryCompletionPolicy = params.completionPolicy ?? "each"; let lastFailure: | { stage: TelemetrySpawnFailureStage; mux?: TelemetrySpawnFailureMux; operation?: TelemetrySpawnFailureOperation; } | undefined; const launchResolution = createLaunchResolutionReporter( telemetry, { requested_execution: "interactive", requested_mux: params.mux ?? "auto", invocation_source: "interactive", async: true, depth: telemetryDepth(launchDepth), depth_bucket: telemetryDepthBucket(launchDepth), completion_policy: completionPolicy, }, spawnStartedAt, ); const resolveFailedLaunch = (outcome: "rejected" | "cancelled"): void => { launchResolution({ outcome, mux: lastFailure?.mux ?? "unknown", fallback_attempted: false, ...(lastFailure ? { final_failure_stage: lastFailure.stage, final_failure_operation: lastFailure.operation, } : {}), }); }; const reportSpawnFailure = ( stage: TelemetrySpawnFailureStage, mux?: TelemetrySpawnFailureMux, operation?: TelemetrySpawnFailureOperation, ): void => { lastFailure = { stage, mux, operation }; captureInteractiveSpawnFailure({ telemetry, stage, operation, startedAt: spawnStartedAt, mux, invocationSource: "interactive", async: true, depth: launchDepth, completionPolicy, model: params.model, }); resolveFailedLaunch( stage === "parent_shutdown" ? "cancelled" : "rejected", ); }; if (signal?.aborted) { resolveFailedLaunch("cancelled"); return { content: [ { type: "text", text: "Interactive sub-agent launch cancelled." }, ], details: { status: "cancelled" }, isError: true, }; } if (!registration) { reportSpawnFailure( staleScope?.lifecycle === "shutdown" ? "parent_shutdown" : "session_creation", ); return { content: [ { type: "text", text: "This interactive tool registration is no longer attached to a live session.", }, ], details: { status: "session_unavailable" }, isError: true, }; } if ( registration.scope?.lineageMode === "child" && !registration.scope.spawnTreeContext ) { reportSpawnFailure("context", undefined, "lineage_bootstrap_check"); return { content: [ { type: "text", text: "Recursive interactive spawning is disabled because this child has no explicit lineage bootstrap.", }, ], details: { status: "lineage_unavailable" }, isError: true, }; } const routingMetadataError = validateInitialRoutingMetadata( params.routingDescription, params.routingAliases, ); const topLevelOrchestratorV2 = registration.scope !== undefined && !isChild && isOrchestratorV2Enabled(pi); const routingModeError = validateRoutingMetadataMode( topLevelOrchestratorV2, params.routingDescription, params.routingAliases, ); if (routingMetadataError || routingModeError) { reportSpawnFailure("context", undefined, "routing_metadata_validation"); const error = routingMetadataError ?? routingModeError!; return { content: [ { type: "text", text: `Invalid initial routing metadata: ${error}`, }, ], details: { status: "invalid_routing_metadata", error, }, isError: true, }; } const contextParams = params as typeof params & { includeContext?: boolean; context?: string; }; if ( contextParams.context !== undefined && Buffer.byteLength(contextParams.context, "utf8") > MAX_INTERACTIVE_CONTEXT_BYTES ) { reportSpawnFailure("context", undefined, "explicit_context_limit"); return { content: [ { type: "text", text: `Explicit context exceeds ${MAX_INTERACTIVE_CONTEXT_BYTES} bytes.`, }, ], details: { status: "invalid_context", maxBytes: MAX_INTERACTIVE_CONTEXT_BYTES, }, isError: true, }; } let completion: ResolvedCompletionPolicy; try { if (!registration.scope) { throw new Error( "Interactive sub-agents require a live parent session scope", ); } completion = resolveCompletionPolicy(params); assertCompletionGroupOpen( completion.policy, completion.groupId, sessionOwner(registration.scope), ); } catch (error) { reportSpawnFailure( "context", undefined, "completion_policy_validation", ); const message = error instanceof Error ? error.message : String(error); return { content: [ { type: "text", text: `Sub-agent not started: ${message}` }, ], details: { status: "error", error: message }, isError: true, }; } const launchOwner = sessionOwner(registration.scope!); let completionReservation: CompletionGroupReservation | undefined; try { completionReservation = reserveCompletionGroup( completion.policy, completion.groupId, launchOwner, ); } catch (error) { reportSpawnFailure( "registration", undefined, "completion_registration", ); const msg = error instanceof Error ? error.message : String(error); return { content: [{ type: "text", text: `Sub-agent not started: ${msg}` }], details: { status: "error", error: msg }, isError: true, }; } debugLog("info", "tool_call", { toolName: "subagent_interactive", toolCallId: _toolCallId, taskLength: params.task?.length ?? 0, model: params.model ?? null, cwd: params.cwd ?? ctx.cwd, includeContext: contextParams.includeContext ?? false, completionPolicy: completion.policy, completionGroupId: completion.groupId ?? null, }); let contextText: string | null = contextParams.includeContext === false ? (contextParams.context ?? null) : null; let authorityEntries: readonly unknown[] | undefined; try { if (contextParams.includeContext === true) { const routingAuthorityEntries = params.routingDescription !== undefined ? ctx.sessionManager.getBranch() : undefined; authorityEntries = routingAuthorityEntries; const messages = ctx.sessionManager.buildSessionProjection().messages; contextText = serializeConversation(convertToLlm(messages)); } else if (topLevelOrchestratorV2) { authorityEntries = parentBranchEntries(ctx); } } catch (error) { reportSpawnFailure( "context", undefined, "parent_context_serialization", ); throw error; } let parentSessionId: string; try { parentSessionId = ctx.sessionManager.getSessionId(); } catch (error) { reportSpawnFailure("session_creation"); throw error; } const taskPreview = params.task.replace(/\s+/g, " ").slice(0, 48); const name = params.name ?? `Subagent: ${taskPreview || "interactive"}`; const targetCwd = params.cwd ?? ctx.cwd; try { const state = await launchInteractiveSubagent({ signal, name, task: params.task, persona: params.persona, model: params.model, cwd: targetCwd, contextText, background: params.background, // defaults to true (hidden) inside the helper completionPolicy: completion.policy, completionGroupId: completion.groupId, muxPreference: params.mux, // pass through user's mux preference parentCwd: ctx.cwd, parentSessionId, thinkingLevel: params.thinkingLevel, sessionScope: registration.scope, spawnTreeContext: registration.scope?.spawnTreeContext, requireActivePaneForUserAttention: topLevelOrchestratorV2, telemetryInvocationSource: "interactive", telemetryAsync: true, spawnRequestedAt: spawnStartedAt, deferAgentCreatedTelemetry: true, onSpawnFailure: (failure) => { lastFailure = failure; }, }); if (!resolveLiveSessionScope(launchOwner)) { reportSpawnFailure("parent_shutdown", state.mux); rollbackInteractiveSpawn(state); throw new Error( "Interactive launch cancelled: its parent session is no longer live", ); } if (registration.scope && completion.policy) { try { registerCompletionMember( "interactive", state.id, completion.policy, completion.groupId, launchOwner, completionReservation, ); } catch (error) { reportSpawnFailure( "registration", state.mux, "completion_registration", ); releaseCompletionGroup(completionReservation); rollbackInteractiveSpawn(state); return { content: [ { type: "text", text: `Failed to start interactive sub-agent: ${error instanceof Error ? error.message : String(error)}`, }, ], details: { status: "error", error: String(error) }, isError: true, }; } captureInteractiveSubagentCreatedTelemetry(state); } launchResolution({ outcome: "started", execution: "interactive", mux: state.mux, fallback_attempted: false, }); const routingMetadata = persistInitialRoutingMetadata({ cwd: ctx.cwd, childId: state.id, description: params.routingDescription, aliases: params.routingAliases, authorityEntries, pi, }); updateRunningSubagentFooter(ctx.ui, launchOwner); const displayMode = state.windowName ? "background (new window/tab)" : "visible split"; const locationLines = [`Artifact: ${state.artifactDir}`]; if (!(state.mux === "tmux" && process.env.TMUX)) { locationLines.push(`Attach: ${state.attachCommand}`); } locationLines.push(`Focus: ${state.selectPaneCommand}`); locationLines.push(`Session: ${state.sessionFile}`); if (routingMetadata?.status === "warning") { locationLines.push( `Warning: initial routing metadata was not persisted: ${routingMetadata.error}`, ); } return { content: [ { type: "text", text: `Interactive sub-agent ${state.id} started (${displayMode}) in ${state.mux} pane ${state.paneId}.\n\n` + `${ completion.policy === "group" ? `Completion will notify the user immediately and resume the parent once group ${completion.groupId} is sealed at parent settlement and all registered members finish.` : "Completion will notify the user immediately and resume the parent with immutable result references when safely idle." }\n\n` + locationLines.join("\n"), }, ], details: { ...state, status: routingMetadata?.status === "warning" ? "degraded" : "started", thinkingLevel: params.thinkingLevel, ...(routingMetadata === undefined ? {} : { routingMetadata }), }, }; } catch (error) { releaseCompletionGroup(completionReservation); lastFailure ??= { stage: "unknown" }; resolveFailedLaunch(signal?.aborted ? "cancelled" : "rejected"); const msg = error instanceof Error ? error.message : String(error); return { content: [ { type: "text", text: `Failed to start interactive sub-agent: ${msg}\n${tmuxSetupHint()}`, }, ], details: { status: "error", error: msg }, isError: true, }; } }, renderCall(args, theme) { const task = String(args.task ?? ""); const preview = task.length > 60 ? `${task.slice(0, 57)}…` : task; return new Text( theme.fg("toolTitle", theme.bold("subagent_interactive ")) + theme.fg("accent", String(args.name ?? preview)), 0, 0, ); }, renderResult(result, _options, theme, context) { const details = result.details as | (Partial & { thinkingLevel?: string }) | undefined; const id = details?.id ?? "unknown"; const paneId = details?.paneId ?? "unknown"; const thinking = details?.thinkingLevel ? ` · thinking: ${details.thinkingLevel}` : ""; if (context?.isError || result.isError) { const first = result.content?.[0]; const text = first?.type === "text" ? first.text : "Failed to start interactive sub-agent"; return new Text(theme.fg("error", text), 0, 0); } return new Text( theme.fg("accent", "⚡ ") + theme.fg("toolTitle", `Interactive sub-agent ${id}`) + theme.fg("dim", ` — pane ${paneId}${thinking}`), 0, 0, ); }, }); // ── Tool 8: inspect attachable tmux-backed sessions ──────────────── registerToolWithDefaultGuidance(pi, { name: "get_interactive_subagent_status", label: "Get Interactive Subagent Status", description: "Inspect tmux-backed interactive subagents. Omit jobId to list all tracked sessions. Returns attach/select commands and session paths without capturing pane output.", parameters: Type.Object({ jobId: Type.Optional( Type.String({ description: "Interactive sub-agent ID returned by subagent_interactive", }), ), }), outputSchema: InteractiveStatusOutputSchema, async execute(_toolCallId, params, _signal, _onUpdate, ctx) { const registration = resolveInteractiveToolStates(toolToken); const visibleStates = registration?.states; if (visibleStates) { pruneDeadInteractiveSubagents(visibleStates.values()); updateRunningSubagentFooter( ctx.ui, registration.scope ? sessionOwner(registration.scope) : undefined, ); } let states: InteractiveSubagentState[] = []; if (params.jobId) { const state = visibleStates?.get(params.jobId); if (state) states = [state]; } else if (visibleStates) { states = [...visibleStates.values()]; } if (states.length === 0) { return { content: [ { type: "text", text: params.jobId ? `Interactive sub-agent ${params.jobId} not found.` : "No interactive sub-agents are tracked.", }, ], details: { status: "not_found", jobId: params.jobId }, isError: Boolean(params.jobId), structuredContent: { status: "not_found", ...(params.jobId === undefined ? {} : { jobId: params.jobId }), count: 0, subagents: [], }, }; } const sections = states.map((state) => { return formatInteractiveState(state); }); return { content: [{ type: "text", text: sections.join("\n\n---\n\n") }], details: { count: states.length, subagents: states.map((state) => ({ ...state })), }, structuredContent: { status: "ok", ...(params.jobId === undefined ? {} : { jobId: params.jobId }), count: states.length, subagents: states.map((state) => ({ id: state.id, name: state.name.slice(0, MAX_INTERACTIVE_OUTPUT_NAME_CHARS), status: state.status, mux: state.mux, paneId: state.paneId, startedAt: state.startedAt, elapsedSeconds: Math.floor((Date.now() - state.startedAt) / 1000), taskPreview: state.task .replace(/\s+/g, " ") .slice(0, MAX_INTERACTIVE_TASK_PREVIEW_CHARS), ...(state.windowName === undefined ? {} : { windowName: state.windowName.slice( 0, MAX_INTERACTIVE_OUTPUT_NAME_CHARS, ), }), ...(state.exitCode === undefined ? {} : { exitCode: state.exitCode }), artifactDir: state.artifactDir, attachCommand: state.attachCommand, selectPaneCommand: state.selectPaneCommand, sessionFile: state.sessionFile, })), }, }; }, }); // ── Tool 9: cancel an attachable tmux-backed session ─────────────── registerToolWithDefaultGuidance(pi, { name: "cancel_interactive_subagent", label: "Cancel Interactive Subagent", description: "Kill an interactive sub-agent pane and retain its cancelled artifact. Coordinated delivery still emits one TUI-only terminal notice and may later add a compact cancellation selector; the tool result does not inject a duplicate full-output cancellation message.", parameters: Type.Object({ jobId: Type.String({ description: "Interactive sub-agent ID returned by subagent_interactive", }), }), async execute(_toolCallId, params, _signal, _onUpdate, ctx) { const registration = resolveInteractiveToolStates(toolToken); const ownedState = registration?.states.get(params.jobId); const state = ownedState ? cancelInteractiveSubagent( params.jobId, "cancel_interactive_subagent", ownedState, ) : undefined; let userNotification: string; if (!state) { return { content: [ { type: "text", text: `Interactive sub-agent ${params.jobId} not found.`, }, ], details: { jobId: params.jobId, status: "not_found" }, isError: true, }; } updateRunningSubagentFooter( ctx.ui, registration?.scope ? sessionOwner(registration.scope) : undefined, ); let snapshotText = ""; if (state.cancellationSnapshot?.path) { snapshotText = ` Snapshot ${state.cancellationSnapshot.status}: ${state.cancellationSnapshot.path}`; } else if (state.cancellationSnapshot?.error) { snapshotText = ` Snapshot error: ${state.cancellationSnapshot.error}`; } const snapshotDescription = snapshotText ? `${snapshotText}.` : ""; userNotification = `Interactive sub-agent ${params.jobId} cancelled; coordinated delivery will use one TUI notice and, when eligible, one compact cancellation selector. ` + `Artifacts retained at ${state.artifactDir}.${snapshotText}`; try { ctx.ui.notify(userNotification, "warning"); } catch { /* cancellation succeeded; a stale UI must not turn it into a tool failure */ } return { content: [ { type: "text", text: `Interactive sub-agent ${params.jobId} cancelled. ` + `Coordinated delivery will use one TUI notice and, when eligible, one compact cancellation selector. ` + `Artifacts retained at ${state.artifactDir}.` + snapshotDescription, }, ], details: { ...state }, }; }, }); // ── Tool: send a follow-up message to a live interactive sub-agent ────── // The child REPL stays open after `done` (see buildChildSubagentProtocol in // interactive-tmux.ts), so the parent can push a new prompt into the same // session via tmux send-keys. Model context is preserved across messages — // this is a true follow-up turn, not a fresh spawn. // // Caps: the message must be non-empty (an empty Enter in the REPL would submit a // blank prompt) and at most MAX_FOLLOWUP_BYTES UTF-8 bytes (symmetric with // MAX_PERSONA_BYTES in interactive-tmux.ts — 64 KiB is well above any realistic // follow-up prompt; larger values are rejected up-front with a structured error). registerToolWithDefaultGuidance(pi, { name: "send_interactive_subagent_message", label: "Send Interactive Subagent Message", description: [ "Send a follow-up prompt to a live interactive sub-agent. The message is delivered into the", "child's existing REPL via tmux send-keys, so the child's model context is preserved — this", "is a true follow-up turn, not a fresh spawn. A workflow-owned child can accept a follow-up", "only after its completed turn is idle and its workflow runner has consumed the result. It is", "promoted to standalone only after that follow-up is sent successfully. An idle follow-up resets", "future completion delivery to independent each; a source can satisfy a group only once, so later", "turns from that source/group are also independent. The child will run the new turn and (per its", "system prompt) call '$ARTIFACT_DIR/cli.mjs done 0' again when it finishes. Use", "get_interactive_subagent_status to check the pane state first if you're not sure it's still alive.", ].join("\n"), parameters: Type.Object({ id: Type.String({ description: "Interactive sub-agent ID returned by subagent_interactive", }), message: Type.String({ description: "The follow-up prompt text to send into the child's REPL (must be non-empty; max 64 KiB)", }), }), async execute( _toolCallId, params, ): Promise< AgentToolResult<{ id: string; status: | InteractiveSubagentState["status"] | "invalid_id" | "empty_message" | "message_too_large" | "not_found" | "workflow_owned" | "send_failed" | "sent"; messageLength?: number; maxBytes?: number; paneId?: string; error?: string; persistenceWarning?: string; messagePreview?: string; messageTruncated?: boolean; }> > { // Validate the id shape first for a precise error. if (!isValidSubagentId(params.id)) { return { content: [ { type: "text", text: `Invalid sub-agent id ${JSON.stringify(params.id)}; expected 8 or 16 lowercase hex chars.`, }, ], details: { id: params.id, status: "invalid_id" }, isError: true, }; } // Content validation (no registry I/O): fail fast on empty / oversized messages. // An empty message would submit a blank Enter in the child REPL; an oversized message // is more than the child can usefully consume and risks blowing the REPL history. if (params.message.trim().length === 0) { return { content: [ { type: "text", text: "Message is empty; send a non-empty follow-up prompt.", }, ], details: { id: params.id, status: "empty_message", messageLength: 0 }, isError: true, }; } const messageBytes = Buffer.byteLength(params.message, "utf8"); if (messageBytes > MAX_FOLLOWUP_BYTES) { return { content: [ { type: "text", text: `Message too large: ${messageBytes} bytes (max ${MAX_FOLLOWUP_BYTES}). Shorten the prompt and try again.`, }, ], details: { id: params.id, status: "message_too_large", messageLength: messageBytes, maxBytes: MAX_FOLLOWUP_BYTES, }, isError: true, }; } const registration = resolveInteractiveToolStates(toolToken); const state = registration?.states.get(params.id); if (!state) { return { content: [ { type: "text", text: `Interactive sub-agent ${params.id} not found.`, }, ], details: { id: params.id, status: "not_found" }, isError: true, }; } if (isWorkflowOwnedRuntimeBlocked(state)) { return { content: [ { type: "text", text: `Interactive sub-agent ${params.id} is still under workflow ownership; its workflow must consume the current result and the pane must be idle before a follow-up can be sent.`, }, ], details: { id: params.id, status: "workflow_owned" }, isError: true, }; } // Standalone panes accept follow-ups while running or idle. Workflow ownership has two // independent release conditions: artifact polling folded the completion into idle, and the // workflow runner acknowledged returning that result. if (state.status !== "running" && state.status !== "idle") { return { content: [ { type: "text", text: `Interactive sub-agent ${params.id} is ${state.status}; follow-up messages can only be sent to running or idle sub-agents. Spawn a new one if needed.`, }, ], details: { id: params.id, status: state.status }, isError: true, }; } // sendCommandToPane uses send-keys + Enter; it throws synchronously if the // pane is gone (e.g. the child exited between the status check and now). // Wrap so the parent gets a structured error instead of an exception trace. const startsNewTurn = state.status === "idle"; try { sendCommandToPane(state, params.message + FOLLOWUP_COMPLETION_REMINDER); } catch (err) { const msg = err instanceof Error ? err.message : String(err); return { content: [ { type: "text", text: `Failed to send message to interactive sub-agent ${params.id}: ${msg}`, }, ], details: { id: params.id, status: "send_failed", paneId: state.paneId, error: msg, }, isError: true, }; } captureTelemetry( registration?.scope?.telemetry, { event: "interactive_message_sent", direction: "parent_to_child", count: 1, }, // Without a usable tool-call id every send collapses onto one constant // key and only the first is ever recorded. Retry protection is worth // having when the id exists and is worth losing when it does not. _toolCallId ? { dedupeKey: `interactive-message:${_toolCallId}` } : {}, ); // Reaching the send proves both workflow release conditions held at the guard above. if ( state.completionOwner === "workflow" && state.workflowResultConsumed && state.status === "idle" ) { state.completionOwner = "standalone"; state.workflowId = undefined; } let persistenceWarning: string | undefined; if (startsNewTurn) { state.completionPolicy = "each"; // `state.telemetryCompletionPolicy` is deliberately left alone. It is an // agent-creation dimension already reported by `agent_created`, and // re-stamping it here would make one agent id report two values across // its own lifecycle events. state.completionGroupId = undefined; if (state.parentSessionId) { try { updateInteractiveState(state.cwd, state.id, (entry) => { entry.completionPolicy = "each"; delete entry.completionGroupId; }); } catch (error) { persistenceWarning = "The message was sent, but the new completion policy could not be persisted; reload may require manual recovery."; debugLog("warn", "interactive_followup_policy_persist_failed", { id: state.id, error: error instanceof Error ? error.message : String(error), }); } } } const messagePreview = formatFollowupPreview(params.message); const messageTruncated = params.message.length > MAX_FOLLOWUP_PREVIEW_CHARS; const recipientLabel = isOrchestratorV2Enabled(pi) ? completionDisplayLabel(state.name, "interactive sub-agent") : `interactive sub-agent ${params.id}`; return { content: [ { type: "text", text: `Sent follow-up to ${recipientLabel} (${params.message.length} chars) in pane ${state.paneId}.` + `\n\nMessage sent:\n${messagePreview}` + (persistenceWarning ? `\n\nWarning: ${persistenceWarning}` : ""), }, ], details: { id: params.id, ...(persistenceWarning ? { persistenceWarning } : {}), paneId: state.paneId, messageLength: params.message.length, messagePreview, messageTruncated, status: "sent", }, }; }, }); // ── Tool: read an interactive sub-agent's artifact ─────────────── // Protocol-v2 completion events and immutable snapshots are authoritative. registerToolWithDefaultGuidance(pi, { name: "read_subagent_artifact", label: "Read Subagent Artifact", description: [ "Read a protocol-v2 interactive sub-agent's artifact. By default, returns output for the latest established turn:", "staging output while it is active, or its immutable snapshot after completion. Use `turnId` to select a specific Pi turn.", "A selected terminal error also includes a bounded, explicitly untrusted diagnostic; credentials are not redacted.", "Use `since` (unix ms) to filter only the returned events; it does not change output selection. Reading a terminal output records", "consumption so it is not delivered again automatically.", ].join("\n"), parameters: Type.Object({ id: Type.String({ description: "Interactive sub-agent ID returned by subagent_interactive", }), since: Type.Optional( Type.Number({ description: "Only return events with ts >= this unix-ms timestamp", }), ), includeOutput: Type.Optional( Type.Boolean({ description: "Include the output (default true). Set false to fetch only events.", }), ), turnId: Type.Optional( Type.String({ maxLength: MAX_TURN_ID_LENGTH, description: "Read a protocol-v2 immutable output by its Pi-derived turnId (max 256 characters).", }), ), }), outputSchema: SubagentArtifactReadOutputSchema, async execute(_toolCallId, params, _signal, _onUpdate, ctx) { const registration = resolveInteractiveToolStates(toolToken); const staleScope = !registration && toolToken ? findSessionScope(toolToken.id) : undefined; const captureResultRead = ( outcome: TelemetryResultReadOutcome, terminalTs?: number, ): void => { const readAt = Date.now(); captureTelemetry( registration?.scope?.telemetry ?? staleScope?.telemetry, { event: "result_read", source: "interactive", outcome, read_latency_ms: readLatencyFromTerminal(terminalTs, readAt), }, ); }; // Validate the id shape FIRST so a malformed id gets a precise error // instead of being collapsed into the generic "not found" message. if (!isValidSubagentId(params.id)) { captureResultRead("unavailable"); return { content: [ { type: "text", text: `Invalid sub-agent id ${JSON.stringify(params.id)}; expected 8 or 16 lowercase hex chars.`, }, ], details: { id: params.id, status: "invalid_id" }, isError: true, structuredContent: { id: params.id, status: "invalid_id", eventCount: 0, outputState: "unavailable", output: null, outputTruncated: false, error: "invalid sub-agent id", }, }; } const state = registration?.states.get(params.id); // A persisted parent id can be shared by different live extension scopes. const foreignInMemoryState = registration !== undefined && !state && getStartedSessionScopes().some( (scope) => scope !== registration.scope && scope.interactiveStates.has(params.id), ); let art: SubagentArtifact | null = null; if (state) { art = getArtifactForState(state); } else if (registration && !foreignInMemoryState) { art = findOwnedDiskArtifact(ctx.cwd, params.id, registration.scope); } if (!art) { captureResultRead("unavailable"); return { content: [ { type: "text", text: `No artifact found for sub-agent ${params.id}.`, }, ], details: { id: params.id, status: "not_found" }, isError: true, structuredContent: { id: params.id, status: "not_found", eventCount: 0, outputState: "unavailable", output: null, outputTruncated: false, error: "artifact not found", }, }; } try { const document = readArtifactDocument(art, params); const { result, events, outputHistory } = document; const consumption = recordArtifactReadConsumption( pi, params.id, result, registration?.scope ? sessionOwner(registration.scope) : undefined, ); const view = renderArtifactRead(params.id, document, params); captureResultRead( artifactReadOutcome(result, consumption), result.plan.selection.completion?.terminalTs, ); const output = artifactOutputContent(result.output); const outputError = result.output.kind === "read_error" ? result.output.error : undefined; const lastEventValue = events.at(-1) ?? null; return { content: [{ type: "text", text: view.text }], details: { id: params.id, artifactDir: art.dir, events, output, lastEvent: lastEventValue, outputHistory, ...(outputError === undefined ? {} : { outputError }), }, ...(outputError === undefined ? {} : { isError: true }), structuredContent: { id: params.id, status: result.status, eventCount: events.length, outputState: artifactOutputState(result.output), output: view.output.text, outputTruncated: view.output.truncated, ...(lastEventValue === null ? {} : { lastEvent: { type: lastEventValue.type, ts: lastEventValue.ts, status: lastEventValue.status, turnId: lastEventValue.turnId, }, }), ...(result.turnId === undefined ? {} : { turnId: result.turnId }), ...(view.error === undefined ? {} : { error: view.error }), } satisfies SubagentArtifactReadOutput, }; } catch (error) { captureResultRead("error"); throw error; } }, }); // ── Tool: list known interactive sub-agent artifacts ───────────── registerToolWithDefaultGuidance(pi, { name: "list_subagent_artifacts", label: "List Subagent Artifacts", description: [ "List interactive sub-agent artifacts visible to this parent session.", "Returns id, name, status, and last-update time. Use read_subagent_artifact", "to fetch a specific one.", ].join("\n"), parameters: Type.Object({}), outputSchema: SubagentArtifactListOutputSchema, async execute(_toolCallId, _params, _signal, _onUpdate, ctx) { const registration = resolveInteractiveToolStates(toolToken); const visibleStates = registration?.states; if (visibleStates) { pruneDeadInteractiveSubagents(visibleStates.values()); updateRunningSubagentFooter( ctx.ui, registration.scope ? sessionOwner(registration.scope) : undefined, ); } const states = visibleStates ? [...visibleStates.values()] : []; const summary = states.map((s) => { const art = getArtifactForState(s); const last = lastEvent(art); return { id: s.id, name: s.name, task: s.task, status: s.status, lastEvent: last, lastUpdate: last?.ts, artifactDir: s.artifactDir, }; }); if (summary.length === 0) { return { content: [ { type: "text", text: "No interactive sub-agents are tracked." }, ], details: { count: 0, subagents: [] }, structuredContent: { status: "ok", count: 0, artifacts: [] }, }; } const lines = summary.map((s) => { const ev = s.lastEvent; const taskPreview = (s.task ?? "").replace(/\s+/g, " ").slice(0, 60); let eventSummary = "no events yet"; if (ev) { const messagePreview = ev.message ? ` (${ev.message.slice(0, 60)})` : ""; eventSummary = `last: ${ev.type}${messagePreview}`; } return `${s.id} ${s.name} [${s.status}] ${taskPreview} — ${eventSummary}`; }); return { content: [{ type: "text", text: lines.join("\n") }], structuredContent: { status: "ok", count: summary.length, artifacts: summary.map((artifact) => ({ id: artifact.id, name: artifact.name.slice(0, MAX_INTERACTIVE_OUTPUT_NAME_CHARS), status: artifact.status, ...(artifact.lastUpdate === undefined ? {} : { lastUpdate: artifact.lastUpdate }), })), }, details: { count: summary.length, subagents: summary }, }; }, }); }