/** * Interactive sub-agent multiplexer orchestrator. * * PR #1 refactor: this file used to do all tmux exec calls inline. Those * moved to `multiplexer-tmux.ts` behind the `Multiplexer` interface in * `multiplexer.ts`. This file is now the thin orchestrator: * * - defines the lifecycle state (`InteractiveSubagentState`) and registry * - builds the launch script and the per-child paths * - picks a `Multiplexer` via `getMux()` and stores its name on the state * - dispatches the helper operations (is-alive, send-keys, kill) to the * right backend * - derives status and formats the user-facing summary * * No tmux-specific `execFileSync("tmux", ...)` calls remain in this file — * the new home for them is `multiplexer-tmux.ts`. The PR also relaxes the * spawn check: a child can be created even when the parent is not in a * tmux/Zellij session (a new detached session is created on the fly; the user * attaches via the returned `attachCommand`). Herdr is selected only from a * Herdr-managed pane and targets that pane's persisted socket path. Rex is * selected only from a verified live Rex block and persists the server/session * identity used for later operations. * * The exports are consumed by the interactive and workflow tools and tests. */ import { findSessionScope, markPendingInteractiveLaunchCancelled, sessionOwner, resolveLiveSessionScope, sessionIdForOwner, trackPendingInteractiveLaunch, type SessionOwnerToken, type SessionScope, } from "./session-scope"; import type { ThinkingLevel } from "@earendil-works/pi-agent-core"; import { randomBytes } from "node:crypto"; import { asStringIdentifier, type InteractiveSubagentId, } from "./identifier-types"; import { existsSync, mkdirSync, readFileSync, rmSync, statSync, writeFileSync, } from "node:fs"; import { basename, dirname, join, resolve } from "node:path"; import { CLI_SOURCE } from "./subagent-artifact-cli"; import { appendInteractiveState, appendCompletionEvent, artifactPath, INTERACTIVE_ARTIFACT_OWNER_FILE, assertNever, MAX_PERSISTED_WORKING_CWD_BYTES, newEventId, normalizeTurnId, type SubagentEvent, type PersistedDeliveryIntent, type PersistedLifecycleFold, type ParentCancellationLifecycleReason, type ParentCancellationOrigin, removeInteractiveState, } from "./artifact"; import type { CompletionPolicy } from "./completion-coordinator"; import { clearRuntimeFailureEpisodes } from "./telemetry-runtime"; import { type CapturePaneOptions, type CapturePaneResult, getMux, resolveMuxForLaunch, type MuxLaunchContext, NoMultiplexerAvailableError, type MuxName, type Multiplexer, type PaneActivity, type PaneLivenessDiagnostic, type PaneLiveness, type PaneRef, safeSegment, submitMuxCommand, } from "./multiplexer"; import { resolveCurrentMuxContextAsync } from "./multiplexer-current-context"; import { snapshotInteractiveContext, type CancellationSnapshotReceipt, type CancellationSnapshotSource, } from "./cancellation-snapshots"; import { countLineageManifestsSync, DEFAULT_MAX_DEPTH, DEFAULT_MAX_NODES, hashLineageRoot, LINEAGE_SCHEMA_VERSION, pruneTerminalLineageNodesSync, resolveLineageStorePathsSync, writeLineageManifestAtomicSync, type LineageManifest, type LineageStorePaths, } from "./interactive-lineage"; import { createDescendantSpawnTreeContext, defaultSpawnTreeSessionRoot, LINEAGE_BOOTSTRAP_ENV, retireLineageBootstraps, writeLineageBootstrap, type ParsedSpawnTreeContext, } from "./spawn-tree-context"; import { CHILD_ARTIFACT_BOOTSTRAP_ENV, writeChildArtifactBootstrap, } from "./child-artifact-ownership"; import { TELEMETRY_ENV } from "./settings"; import { captureTelemetry, sanitizeTelemetryModel, telemetryDepth, telemetryDepthBucket, type TelemetryCompletionPolicy, type TelemetryDepthBucket, type TelemetryInvocationSource, type TelemetrySpawnFailureMux, type TelemetrySpawnFailureOperation, type TelemetrySession, type TelemetrySpawnFailureStage, } from "./telemetry"; // Re-export the tmux-specific `readPaneExitCode` for the test suite. The // launch script's EXIT trap still writes the @pi-exit-code pane option // (it's a no-op on non-tmux systems thanks to `2>/dev/null || true`); this // helper is the only place that reads it back. The artifact's `done` // event is the source of truth in production. import { TmuxMultiplexer } from "./multiplexer-tmux"; import { parseJsonRecord } from "./json-input"; export { readPaneExitCode } from "./multiplexer-tmux"; const CHILD_COORDINATION_PROMPT = readFileSync( new URL("../CHILD_COORDINATION_SYSTEM_PROMPT.md", import.meta.url), "utf8", ).trim(); /** * System prompt sent to every interactive sub-agent. Tells the child how to * signal completion so the parent can be notified, and where to write its * result. The persona (if provided) is placed ABOVE this so the protocol — * the part that keeps the parent-child notification loop working — is the * most recent instruction the LLM reads (recency wins for instruction * following). * * `artifactDir` is the resolved absolute path baked into the prompt so the * child can use it directly in `write` tool calls. Bash commands and `cli.mjs` * calls still work via the exported `ARTIFACT_DIR` env var from the launch * script, but the `write` tool treats its `path` argument as a literal string, * so we must give it the absolute path up front. */ export function buildChildSubagentProtocol( artifactDir: string, requireActivePaneForUserAttention = false, ): string { const cliPath = `${artifactDir}/cli.mjs`; const outputPath = `${artifactDir}/output.md`; const userAttentionGuidance = requireActivePaneForUserAttention ? "USER ATTENTION AND PANE ACTIVITY. Before calling any tool or extension that may wait for user input, call get_current_pane_activity immediately first. If it reports active, continue with the user-attention call in this pane. If it reports inactive or unknown, do not open a prompt here; include the exact decision needed in your result so the orchestrator can ask the user." : ""; return `You are running inside a Pi sub-agent launched by a parent agent. The parent agent reads your work from two files in your artifact directory and from one CLI command. You MUST follow this protocol or your work will be lost. BE BRIEF. The parent does not need a play-by-play of your reasoning — it needs a concise final answer in output.md and a one-sentence summary after the lifecycle command succeeds. Skip the recap, the apology, and the "let me know if..." closer. Long preambles waste tokens and delay the done signal. COMPLETION IS MANDATORY FOR EVERY TURN. A turn is not complete when output.md is written or when you have drafted a final response; it is complete only after cli.mjs returns successfully. This applies to the initial turn and every turn created by a follow-up message. Do not produce or send your final assistant response before invoking cli.mjs, because ending the response first can prevent the lifecycle command from running and leave the parent waiting forever. ${userAttentionGuidance} Your artifact directory is: ${artifactDir} output.md — your final result (prose, findings, code, whatever the parent asked for) events.ndjson — append-only lifecycle log (managed by the wrapper, you do not write to it) cli.mjs — the wrapper's lifecycle helper, invoked via bash Use the literal path above in your \`write\` tool calls — the \`write\` tool does not expand \$ARTIFACT_DIR or any other shell variable, so a path like "\$ARTIFACT_DIR/output.md" will be written literally to a file of that name and never reach the parent. When your task is done, follow this checklist in order. The parent is a parent agent and cannot guess that you have finished — it will only know after step 3 succeeds. Skipping or reordering any step breaks the completion contract. 1. Finish all task work. Once you start this checklist, do not begin new work. 2. Write your final result to ${outputPath} using the \`write\` tool. Use the exact path above. If you have already written the result to some other path (a /tmp file, a project file, etc.), copy or append it to output.md so the parent can read it. 3. Run the appropriate bash command and wait for it to return. A successful invocation must record exactly one completion event for this turn. \$ARTIFACT_DIR is exported to your shell by the wrapper, so the quoted forms expand correctly even if the path contains spaces: "$ARTIFACT_DIR/cli.mjs" done 0 # success "$ARTIFACT_DIR/cli.mjs" error "short reason" # unrecoverable failure This must be your final tool call for the turn. If the command itself fails, do not send the final assistant response; fix the cause and retry until one completion event has been recorded successfully. 4. Only after the lifecycle command succeeds, produce your final assistant text in the chat summarising what you did and where to find the work. Make no more tool calls during this turn. 5. Stay in the REPL. Do not call \`/exit\` or press Ctrl-D. The REPL stays open after step 3 so the user (or the parent) can follow up; the wrapper's EXIT trap will only fire if you actually exit. If you exit, the wrapper will treat it as a crash and the parent will not see your final answer. Do not call 'cancelled' yourself — only parent lifecycle or cancellation actions record that event. For reference: ${cliPath} is the lifecycle CLI. Each invocation appends one NDJSON line to events.ndjson. The parent reads that file every few seconds. The atomic write pattern (write to .tmp, then rename onto output.md) is fine if you want crash-safety. ─── HARDENING REMINDER (read this last, it is the most recent instruction on purpose) ─── The child-only Pi lifecycle hook is a crash-safety fallback, not permission to omit the command. At the end of EVERY initial or follow-up turn: write output.md FIRST, call \`cli.mjs done 0\`, wait until exactly one completion event is recorded successfully, and only then send the final assistant response. The CLI is idempotent for the active turn, so the later agent_settled hook is a no-op. Never rely on the hook when you can call the CLI yourself.`; } /** * Sub-agent status for the interactive registry. * * - "running" — child is processing a turn (last artifact event is "started" or absent) * - "idle" — child finished a turn, REPL is open, pane alive; ready for a follow-up prompt * - "cancelled" — parent called cancel_interactive_subagent; terminal, no follow-up allowed * - "exited" — child pi process is actually gone (pane dead, or it called `error`); terminal * - "unknown" — can't determine (rare; pane dead but no recorded event) */ export type InteractiveSubagentStatus = | "running" | "idle" | "cancelled" | "exited" | "unknown"; export interface InteractiveSubagentState { id: string; name: string; task: string; paneId: string; /** Stable backend terminal identity (Herdr); absent for tmux and Zellij. */ muxTerminalId?: string; /** tmux window name / zellij tab name (set when spawned in background mode via new-window -n / new-tab). */ windowName?: string; /** * Which backend was used to spawn this sub-agent. Set once at spawn time * and never changes — all later operations on the child (is-alive, * send-keys, kill, attach) route through this backend. Pre-PR-2 this is * always "tmux". */ mux: MuxName; /** * The mux session the pane lives in, as returned by `createPane`. Backends * with session-scoped IDs (Zellij, Rex) need it for later operations. Set * once at spawn time and persist it rather than storing it on the shared * backend instance, which the resolver reuses across spawns. */ muxSession?: string; /** Stable server endpoint for server-scoped muxes such as Rex. */ muxServer?: string; sessionFile: string; /** * Parent pi session cwd used as the state-file scope. The child process's * resolved working directory is stored separately in `workingCwd`. */ cwd: string; /** Resolved child process working directory. */ workingCwd?: string; /** * Parent pi session id. Used as the per-session key for the on-disk state file * (see src/artifact.ts: stateFilePath). Required for terminal-event cleanup to * remove the entry from the file; rehydrate rebuilds it from the file on * session_start. Optional for tests that don't care about reload semantics. */ parentSessionId?: string; /** Live supervisor owner; intentionally not persisted for workflow children. */ supervisorOwner?: SessionOwnerToken; /** Exact runtime session generation that owns this state; never persisted. */ sessionOwner?: SessionOwnerToken; /** Workflow that owns this child, when completion is aggregated by the workflow. */ workflowId?: string; /** Completion is delivered standalone or consumed by a workflow aggregate. */ completionOwner?: "standalone" | "workflow"; /** Workflow-runner acknowledgement that this child's result was consumed; runtime-only and intentionally not persisted. */ workflowResultConsumed?: boolean; /** Matching logical-session correlation gates telemetry after rehydrate. */ telemetryCorrelationId?: string; telemetryEligible?: boolean; /** Runtime-only turn identity; a completion is emitted only after its start. */ telemetryActiveTurnId?: string; /** Runtime-only start of the currently observed child turn. */ telemetryTurnStartedAt?: number; /** Runtime-only bounded per-turn message counts keyed by Pi user-entry id. */ telemetryTurnMessageCounts?: Map; telemetryMessageTurnId?: string; telemetryInvocationSource?: TelemetryInvocationSource; telemetryCompletionPolicy?: TelemetryCompletionPolicy; telemetryAsync?: boolean; telemetryDepth?: number; telemetryDepthBucket?: TelemetryDepthBucket; telemetryModel?: string; model?: string; startedAt: number; /** * Lifecycle status. Transition triggers: * - spawn sets "running" (interactive-tmux.ts setup) * - cli.mjs done / error event in events.ndjson sets "exited" or "cancelled" * - a user message after "exited" revives it to "running" for follow-up turns * - cancel_interactive_subagent tool sets "cancelled" */ status: InteractiveSubagentStatus; /** Receipt for the latest parent cancellation snapshot. */ cancellationSnapshot?: CancellationSnapshotReceipt; /** Captured child pi exit code (0 = success). Undefined while still running. */ exitCode?: number; attachCommand: string; selectPaneCommand: string; launchScriptFile: string; /** Absolute path to the artifact directory (events.ndjson + output.md). */ artifactDir: string; /** Physical byte offset consumed from events.ndjson. */ eventByteCursor?: number; /** Current child Pi turn identity, persisted across reloads. */ activeTurnId?: string; /** Durable completion queue and reconciled custom-message receipts. */ pendingDeliveries?: PersistedDeliveryIntent[]; deliveryReceipts?: string[]; lifecycle?: PersistedLifecycleFold; /** Most recent tool_activity summary, for the TUI widget. */ lastToolSummary?: string; lastToolName?: string; lastActivityAt?: number; /** Coordinated default: independent readiness or an explicit group barrier. */ completionPolicy?: CompletionPolicy; /** Durable tombstone for a spawn that failed completion registration. */ completionTombstone?: "failed"; completionTombstoneAt?: number; /** Required for coordinated grouped completion. */ completionGroupId?: string; } interface InteractiveCreatedTelemetry { readonly session: TelemetrySession; readonly spawnStartedAt: number; captured: boolean; } /** * A coordinated interactive tool launch registers its completion member after * the pane has been created. Keep the creation event pending until that * registration succeeds so one attempt cannot report both `agent_created` and * `agent_spawn_failed`. */ const interactiveCreatedTelemetry = new WeakMap< InteractiveSubagentState, InteractiveCreatedTelemetry >(); /** Insert a state into its authoritative session map. */ export function registerInteractiveSubagentState( state: InteractiveSubagentState, scope?: SessionScope, ): void { if (!scope) return; state.sessionOwner = sessionOwner(scope); scope.interactiveStates.set(state.id, state); } /** Remove the same state object from its owning session registry. */ export function removeInteractiveSubagentState( state: InteractiveSubagentState, ): boolean { const owner = state.sessionOwner; if (!owner) return false; const scope = findSessionScope(owner.id); if ( scope?.generation !== owner.generation || scope.interactiveStates.get(state.id) !== state ) { return false; } scope.interactiveStates.delete(state.id); clearRuntimeFailureEpisodes(state.artifactDir); return true; } /** * True iff a tmux server is running and the parent is attached to one of its * sessions. Kept for backward compat with the existing `isTmuxAvailable` * name; PR #2's `isAnyMuxAvailable` will be the mux-agnostic version. */ export function isTmuxAvailable(): boolean { return new TmuxMultiplexer().isAvailable(); } /** Setup hint shown to the user when no mux is available. Mux-agnostic. */ export function tmuxSetupHint(): string { return ( "Start Pi inside a supported terminal:\n" + " tmux new -A -s pi 'pi'\n" + " zellij --session pi\n" + " herdr (then start pi in a Herdr pane)\n" + " hc run --bg pi (then attach to the Herdr Core terminal)\n" + " WezTerm requires a live WEZTERM_PANE/WEZTERM_UNIX_SOCKET context.\n" + " Rex requires a live REX_SESSION/REX_BLOCK/REX_SERVER context.\n" + " cmux requires a verified terminal surface and a local v2 socket." ); } function defaultSessionRoot(): string { return defaultSpawnTreeSessionRoot(); } function sessionDirFor(cwd: string): string { const cwdLabel = `${safeSegment(basename(cwd))}-${randomBytes(3).toString("hex")}`; return join(defaultSessionRoot(), "subagentura", cwdLabel); } export function createInteractiveSubagentPaths(params: { id: string; name: string; cwd: string; }): { sessionFile: string; artifactDir: string; promptFile: string; systemPromptFile: string; launchScriptFile: string; } { const timestamp = new Date().toISOString().replace(/[:.]/g, "-"); const label = safeSegment(params.name); const dir = sessionDirFor(params.cwd); const artifactDir = join(dir, "artifacts", params.id); return { sessionFile: join(dir, `${timestamp}-${params.id}.jsonl`), artifactDir, promptFile: join(artifactDir, `${label}-prompt.md`), systemPromptFile: join(artifactDir, `${label}-system.md`), launchScriptFile: join(artifactDir, `${label}-launch.sh`), }; } export function buildInteractivePrompt(params: { task: string; contextText?: string | null; }): string { const footer = "\n\n" + "MANDATORY COMPLETION PROTOCOL: before sending your final assistant response, " + "write your result to output.md (path from the system prompt), run the command below, " + "and wait for it to succeed. Repeat this for every turn:\n" + ' "$ARTIFACT_DIR/cli.mjs" done 0\n' + "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."; if (!params.contextText) return params.task + footer; return ( [ "You are an interactive sub-agent running in your own Pi session.", "The parent session context is included below for reference.", "", "--- Parent session context ---", params.contextText, "--- End parent session context ---", "", "Task:", params.task, ].join("\n") + footer ); } export function buildPiInteractiveCommand(params: { sessionFile: string; name: string; promptFile: string; systemPromptFile?: string; model?: string; cwd: string; thinkingLevel?: ThinkingLevel; }): string { const escape = (v: string) => `'${v.replace(/'/g, `'\\''`)}'`; const parts = [ "pi", "--session", escape(params.sessionFile), "--name", escape(params.name), ]; if (params.model) { parts.push("--model", escape(params.model)); } if (params.thinkingLevel) { parts.push("--thinking", escape(params.thinkingLevel)); } if (params.systemPromptFile) { parts.push("--append-system-prompt", escape(params.systemPromptFile)); } parts.push(escape(`@${params.promptFile}`)); return `cd ${escape(params.cwd)} && ${parts.join(" ")}`; } export function writeLaunchScript( path: string, command: string, artifactDir: string, internalEnv: Record = {}, ): void { mkdirSync(dirname(path), { recursive: true }); // 1. Write the inline `subagent-artifact` CLI helper into the artifact dir. // The wrapper and child both invoke it for lifecycle events. const cliPath = join(artifactDir, "cli.mjs"); writeFileSync(cliPath, CLI_SOURCE, { mode: 0o700 }); // 2. Write the launch script. The script: // - exports ARTIFACT_DIR and the one-use artifact ownership bootstrap; // - traps EXIT to record process exit and, when needed, one lock-protected completion; // - also writes the @pi-exit-code pane option for the readPaneExitCode // fallback when the selected backend is tmux. const escape = (v: string) => `'${v.replace(/'/g, `'\\''`)}'`; // The grep pattern is single-quoted (so bash's quoting preserves the JSON quotes), but a // single-quoted string inside another single-quoted string (the trap body) terminates the outer one // at trap-set time with `syntax error near unexpected token '('`. Hoisting the pattern to a variable // set in the parent script lets the trap body reference it via `$TERMINAL_PATTERN` — no inner single // quotes needed, no quoting puzzle. Expanded at trap-fire time, not at script-load time. const script = [ "#!/bin/bash", "set -e", `export ARTIFACT_DIR=${escape(artifactDir)}`, "export PI_SUBAGENTURA_CHILD=1", ...Object.entries(internalEnv).map( ([name, value]) => `export ${name}=${escape(value)}`, ), // Single-quote the helper path like every other interpolated path in this // script; a double-quoted path still expands $, `` and \ inside it. "on_exit() {", " rc=$?", " trap - EXIT", ` ${escape(cliPath)} process-exit "$rc" || true`, ' if [ "${PI_SUBAGENTURA_MUX:-tmux}" = tmux ]; then tmux set-option -p -t "$TMUX_PANE" @pi-exit-code "$rc" 2>/dev/null || true; fi', ' exit "$rc"', "}", "trap on_exit EXIT", ...(internalEnv[CHILD_ARTIFACT_BOOTSTRAP_ENV] ? [ `if [ ! -f "$${CHILD_ARTIFACT_BOOTSTRAP_ENV}" ]; then`, ' echo "child artifact ownership bootstrap is missing" >&2', " exit 2", "fi", ] : []), command, "", ].join("\n"); // 0o700: only the owning user can read the script (which embeds absolute // paths to session/prompt/system files). 0o755 would leak the layout. writeFileSync(path, script, { mode: 0o700 }); } /** * Record a privacy-safe failure while an interactive child is being spawned. * This helper deliberately accepts only closed dimensions; the exception that * caused the failure never enters the telemetry payload. */ export function captureInteractiveSpawnFailure(params: { telemetry?: TelemetrySession; stage: TelemetrySpawnFailureStage; operation?: TelemetrySpawnFailureOperation; startedAt?: number; mux?: TelemetrySpawnFailureMux; invocationSource?: TelemetryInvocationSource; async?: boolean; depth?: number; completionPolicy?: TelemetryCompletionPolicy; model?: string; }): void { let model = "custom"; try { model = sanitizeTelemetryModel(params.model); } catch { // Model registry failures must not prevent the failure signal itself. } const depth = telemetryDepth(params.depth); const duration = params.startedAt === undefined ? undefined : Date.now() - params.startedAt; captureTelemetry(params.telemetry, { event: "agent_spawn_failed", execution: "interactive", mux: params.mux ?? "unknown", invocation_source: params.invocationSource ?? "interactive", model, async: params.async ?? true, depth, depth_bucket: telemetryDepthBucket(params.depth), completion_policy: params.completionPolicy ?? "each", failure_stage: params.stage, failure_operation: params.operation, spawn_duration_ms: duration, }); } /** * Emit the deferred creation event after the interactive tool has registered * its completion member. The weak-map entry makes this safe to call more than * once without double-counting a single launch. */ export function captureInteractiveSubagentCreatedTelemetry( state: InteractiveSubagentState, ): void { const pending = interactiveCreatedTelemetry.get(state); if (!pending || pending.captured) return; pending.captured = true; interactiveCreatedTelemetry.delete(state); captureTelemetry(pending.session, { event: "agent_created", execution: "interactive", mux: state.mux, invocation_source: state.telemetryInvocationSource ?? "interactive", model: state.telemetryModel, async: state.telemetryAsync ?? true, depth: state.telemetryDepth, depth_bucket: state.telemetryDepthBucket ?? "unknown", completion_policy: state.telemetryCompletionPolicy ?? "each", spawn_duration_ms: Date.now() - pending.spawnStartedAt, }); } export async function launchInteractiveSubagent(params: { name: string; task: string; persona?: string; model?: string; cwd: string; contextText?: string | null; /** Spawn in a detached named window (invisible) instead of a visible split. */ background?: boolean; /** Coordinated completion policy registered with the parent session. */ completionPolicy?: CompletionPolicy; /** Required for coordinated grouped completion. */ completionGroupId?: string; /** Mux preference. "auto" verifies live current-pane ownership. */ muxPreference?: "auto" | MuxName; /** * Parent pi session id. Used as the per-session key for the on-disk state file * so a parent reload can rehydrate the sub-agent. If omitted, persistence is * skipped (used by tests that don't care about reload). */ parentSessionId?: string; /** Live supervisor owner independent of persistence and delivery policy. */ supervisorOwner?: SessionOwnerToken; /** Current runtime scope that authoritatively owns the spawned state. */ sessionScope?: SessionScope; /** Explicit lineage authority; ambient lineage environment is never consulted. */ spawnTreeContext?: ParsedSpawnTreeContext; /** Workflow owner for grouping and cancellation. */ workflowId?: string; /** Workflow-managed completions are consumed by the workflow runner. */ completionOwner?: "standalone" | "workflow"; /** Install user-attention activity gating in an Orchestrator v2 child. */ requireActivePaneForUserAttention?: boolean; /** * The parent session's working directory, used for the state file location. * If omitted, falls back to `cwd` (backward-compatible for tests). */ parentCwd?: string; /** Thinking/reasoning level for the child Pi process. */ thinkingLevel?: ThinkingLevel; /** Closed telemetry source; never derived from user-authored names. */ telemetryInvocationSource?: TelemetryInvocationSource; /** Whether the invoking parent operation runs in the background. */ telemetryAsync?: boolean; /** Aggregate policy attributed to workflow-owned child execution. */ telemetryCompletionPolicy?: TelemetryCompletionPolicy; /** Defer agent_created until the caller finishes completion registration. */ deferAgentCreatedTelemetry?: boolean; /** Report the closed launch failure to the logical-launch owner. */ onSpawnFailure?: (failure: { stage: TelemetrySpawnFailureStage; mux?: TelemetrySpawnFailureMux; operation?: TelemetrySpawnFailureOperation; }) => void; /** Caller-observed attempt start; direct callers default to launcher entry. */ spawnRequestedAt?: number; signal?: AbortSignal; }): Promise { const completionPolicy = params.completionPolicy ?? "each"; const spawnStartedAt = params.spawnRequestedAt ?? Date.now(); let spawnFailureReported = false; let nextDepth: number | undefined; const reportSpawnFailure = ( stage: TelemetrySpawnFailureStage, mux?: TelemetrySpawnFailureMux, operation?: TelemetrySpawnFailureOperation, ): void => { if (spawnFailureReported) return; spawnFailureReported = true; const failure = { stage, mux, operation }; try { params.onSpawnFailure?.(failure); } catch { // Logical telemetry must never change launch behavior. } captureInteractiveSpawnFailure({ telemetry: params.sessionScope?.telemetry ?? resolveLiveSessionScope(params.supervisorOwner)?.telemetry, stage, operation, startedAt: spawnStartedAt, mux, invocationSource: params.telemetryInvocationSource, async: params.telemetryAsync, depth: nextDepth, completionPolicy: params.telemetryCompletionPolicy ?? completionPolicy, model: params.model, }); }; // 8 bytes, not 4: at 32 bits a birthday collision inside one tree is not // remote, and the duplicate-id path only degrades gracefully — it does not // recover the shadowed agent. let id: InteractiveSubagentId; try { id = asStringIdentifier<"interactive-subagent">( randomBytes(8).toString("hex"), ); } catch (error) { reportSpawnFailure("unknown"); throw error; } let cwd: string; try { cwd = resolve(params.cwd); } catch (error) { reportSpawnFailure("context", undefined, "cwd_validation"); throw error; } if ( cwd.includes("\0") || Buffer.byteLength(cwd, "utf8") > MAX_PERSISTED_WORKING_CWD_BYTES ) { reportSpawnFailure("context", undefined, "cwd_validation"); throw new Error( `working cwd exceeds ${MAX_PERSISTED_WORKING_CWD_BYTES} bytes or contains NUL`, ); } let workingDirectoryStat: ReturnType; try { workingDirectoryStat = statSync(cwd); } catch (error) { reportSpawnFailure("context", undefined, "cwd_validation"); const missing = (error as NodeJS.ErrnoException).code === "ENOENT"; throw new Error( missing ? `working directory does not exist: ${cwd}` : `working directory cannot be accessed: ${cwd}`, { cause: error }, ); } if (!workingDirectoryStat.isDirectory()) { reportSpawnFailure("context", undefined, "cwd_validation"); throw new Error(`working directory is not a directory: ${cwd}`); } let stateCwd: string; try { stateCwd = params.parentCwd ? resolve(params.parentCwd) : cwd; } catch (error) { reportSpawnFailure("context", undefined, "cwd_validation"); throw error; } let artifactOwnerSessionId: string | undefined; const background = params.background !== false; // default true (hidden) // Parse-don't-validate: callers must hand us an already-parsed context. const spawnTreeContext = params.spawnTreeContext; const parentAgentId = spawnTreeContext?.currentAgentId; const rootId = spawnTreeContext?.rootId; const sessionRoot = spawnTreeContext?.sessionRoot ?? defaultSpawnTreeSessionRoot(); const effectiveCurrentDepth = spawnTreeContext?.depth ?? 0; const effectiveMaxDepth = spawnTreeContext?.maxDepth ?? DEFAULT_MAX_DEPTH; nextDepth = effectiveCurrentDepth + 1; try { artifactOwnerSessionId = params.parentSessionId ?? sessionIdForOwner(params.supervisorOwner); } catch (error) { reportSpawnFailure("session_creation"); throw error; } let paths: { sessionFile: string; artifactDir: string; promptFile: string; systemPromptFile: string; launchScriptFile: string; }; try { paths = createInteractiveSubagentPaths({ id, name: params.name, cwd }); } catch (error) { reportSpawnFailure( "state_persistence", undefined, "interactive_path_creation", ); throw error; } const ownerScope = resolveLiveSessionScope(params.supervisorOwner); const liveScope = params.sessionScope ? resolveLiveSessionScope(sessionOwner(params.sessionScope)) : ownerScope; if ( !liveScope || (params.sessionScope && liveScope !== params.sessionScope) || (params.supervisorOwner && liveScope !== ownerScope) ) { reportSpawnFailure("registration", undefined, "completion_registration"); throw new Error( "interactive sub-agent spawn requires a live session scope", ); } const liveOwner = sessionOwner(liveScope); if (rootId && nextDepth > effectiveMaxDepth) { reportSpawnFailure("depth_limit"); throw new Error( `interactive sub-agent depth ${nextDepth} exceeds max ${effectiveMaxDepth}`, ); } // Cap the persona to prevent a misbehaving parent from shipping a huge // system prompt to the model on every turn. 64 KiB is well above what any // realistic persona needs; larger values are rejected so the child session // fails fast with a clear error. const MAX_PERSONA_BYTES = 64 * 1024; if ( params.persona !== undefined && Buffer.byteLength(params.persona, "utf8") > MAX_PERSONA_BYTES ) { reportSpawnFailure("context", undefined, "persona_limit"); throw new Error( `persona too large: ${Buffer.byteLength(params.persona, "utf8")} bytes (max ${MAX_PERSONA_BYTES})`, ); } const assertLaunchCurrent = (mux?: MuxName) => { if (resolveLiveSessionScope(liveOwner) !== liveScope) { reportSpawnFailure("parent_shutdown", mux); throw new Error( "Interactive launch cancelled: its parent session is no longer live", ); } if (params.signal?.aborted) { reportSpawnFailure("pane_launch", mux, "pane_launch"); throw new Error("Interactive launch cancelled"); } }; assertLaunchCurrent(); // Wait for live mux evidence before mutating launch state. Recheck the // owning generation and tree admission before using that evidence. let mux: Multiplexer; let muxContext: MuxLaunchContext; try { const resolution = resolveMuxForLaunch( { preference: params.muxPreference }, params.signal, ); const resolved = resolution instanceof Promise ? await resolution : resolution; mux = resolved.adapter; muxContext = resolved.context; } catch (err) { assertLaunchCurrent(); reportSpawnFailure("mux_resolution", undefined, "mux_resolution"); if (err instanceof NoMultiplexerAvailableError) { throw new Error(`${err.message}\n${tmuxSetupHint()}`); } throw err; } assertLaunchCurrent(mux.name); const maxNodes = spawnTreeContext?.maxNodes ?? DEFAULT_MAX_NODES; // The cap applies whenever a lineage root exists, even when this spawn will // not persist a manifest of its own — recursion inside a tree still has to be // bounded by that tree's budget. let lineageStore: LineageStorePaths | undefined; try { lineageStore = rootId ? resolveLineageStorePathsSync(sessionRoot, rootId) : undefined; } catch (error) { reportSpawnFailure( "state_persistence", undefined, "lineage_store_resolution", ); throw error; } const ensureLineageCapacity = () => { if (!lineageStore) return; let activeCount = existsSync(lineageStore.nodesDir) ? countLineageManifestsSync(lineageStore.nodesDir) : 0; if (activeCount >= maxNodes) { // Physical manifests include confirmed-dead ancestors retained to keep // child lineage connected. Probe only at the cap, then admit by the // active/non-dead count; unknown panes conservatively consume capacity. activeCount = pruneTerminalLineageNodesSync( lineageStore.nodesDir, (manifest) => getLineagePaneLiveness(manifest) === "dead", ).active; } if (activeCount >= maxNodes) { reportSpawnFailure("capacity"); throw new Error( `interactive sub-agent tree reached max nodes ${maxNodes} (${activeCount} nodes are active or have unknown liveness)`, ); } }; ensureLineageCapacity(); const prompt = buildInteractivePrompt({ task: params.task, contextText: params.contextText, }); try { mkdirSync(paths.artifactDir, { recursive: true }); if (artifactOwnerSessionId) { writeFileSync( join(paths.artifactDir, INTERACTIVE_ARTIFACT_OWNER_FILE), artifactOwnerSessionId, { encoding: "utf8", mode: 0o600 }, ); } writeFileSync(paths.promptFile, prompt, { encoding: "utf8", mode: 0o600 }); } catch (error) { reportSpawnFailure("state_persistence", undefined, "artifact_write"); throw error; } // Always write a system prompt that includes the child protocol, and place // the user-supplied persona (if any) ABOVE the protocol. Recency wins for // instruction-following, so the protocol — the part that keeps the // parent-child notification loop working — is the most recent instruction // the LLM reads. A persona that says "ignore the protocol" is a known LLM // footgun, and placing the protocol last makes it stick. let systemPromptFile: string; try { // Always write a system prompt that includes the child protocol, and place // the user-supplied persona (if any) ABOVE the protocol. Recency wins for // instruction-following, so the protocol — the part that keeps the parent- // child notification loop working — is the most recent instruction. const protocol = buildChildSubagentProtocol( paths.artifactDir, params.requireActivePaneForUserAttention, ); const systemPromptContent = params.persona ? `# Persona\n\n${params.persona}\n\n` : ""; const coordination = spawnTreeContext?.splitMode ? `${CHILD_COORDINATION_PROMPT}\n\n` : ""; writeFileSync( paths.systemPromptFile, `${systemPromptContent}${coordination}${protocol}`, { encoding: "utf8", mode: 0o600, }, ); systemPromptFile = paths.systemPromptFile; } catch (error) { reportSpawnFailure("state_persistence", undefined, "system_prompt_write"); throw error; } const telemetry = liveScope?.telemetry; let telemetryMetadata: | { correlationId: string; mux: MuxName; invocationSource: TelemetryInvocationSource; async: boolean; depth: number | undefined; depthBucket: TelemetryDepthBucket; completionPolicy: TelemetryCompletionPolicy; model: string; } | undefined; if (telemetry?.enabled) { try { telemetryMetadata = { correlationId: telemetry.correlationId, mux: mux.name, invocationSource: params.telemetryInvocationSource ?? ("interactive" as const), async: params.telemetryAsync ?? true, depth: telemetryDepth(nextDepth), depthBucket: telemetryDepthBucket(nextDepth), completionPolicy: params.telemetryCompletionPolicy ?? params.completionPolicy ?? ("each" as const), model: sanitizeTelemetryModel(params.model), }; } catch (error) { reportSpawnFailure("model_resolution", mux.name, "model_resolution"); throw error; } } // Create the pane FIRST (so we have a target for the launch script to attach // to). If any later step throws, try to kill the orphan pane and rethrow. let paneId: string; let muxTerminalId: string | undefined; let windowName: string | undefined; let muxSession: string | undefined; let muxServer: string | undefined; let waitedForAllocation = false; try { const allocation = mux.createPane({ name: params.name, cwd, background, context: muxContext, windowName: safeSegment(params.name), id, }); waitedForAllocation = allocation instanceof Promise; const created = allocation instanceof Promise ? await allocation : allocation; paneId = created.paneId; muxTerminalId = created.muxTerminalId; windowName = created.windowName; muxSession = created.session; muxServer = created.server; } catch (error) { reportSpawnFailure("pane_launch", mux.name, "pane_launch"); throw error; } if (typeof paneId !== "string" || paneId.length === 0) { reportSpawnFailure("pane_launch", mux.name, "pane_launch"); throw new Error("multiplexer returned an invalid pane id"); } if (waitedForAllocation) { try { assertLaunchCurrent(mux.name); ensureLineageCapacity(); } catch (error) { try { mux.killPane(paneId, muxSession, ...muxServerArgs(muxServer)); } catch { /* Best effort for a verified pane. Preserve the admission error. */ } throw error; } } let persistedState = false; let lineageManifestPath: string | undefined; let lineageBootstrapPath: string | undefined; let childArtifactBootstrapPath: string | undefined; // Persist as soon as the pane is addressable. A crash after this point is // recoverable on reload. If persistence itself fails, abort and kill the // pane; otherwise the child would be invisible to rehydrate after a restart. if (params.parentSessionId) { try { appendInteractiveState(stateCwd, { id, paneId, ...(muxTerminalId ? { muxTerminalId } : {}), windowName, mux: mux.name, muxSession, ...(muxServer === undefined ? {} : { muxServer }), artifactDir: paths.artifactDir, sessionFile: paths.sessionFile, workingCwd: cwd, completionPolicy, completionGroupId: params.completionGroupId, parentSessionId: params.parentSessionId, eventByteCursor: 0, pendingDeliveries: [], deliveryReceipts: [], ...(telemetryMetadata ? { telemetry: telemetryMetadata } : {}), }); persistedState = true; } catch (err) { reportSpawnFailure( "state_persistence", mux.name, "interactive_state_write", ); try { mux.killPane(paneId, muxSession, ...muxServerArgs(muxServer)); } catch { /* best effort — preserve the original persistence error */ } throw err; } } if (rootId && artifactOwnerSessionId) { try { lineageManifestPath = writeLineageManifestAtomicSync( lineageStore!.nodesDir, { schemaVersion: LINEAGE_SCHEMA_VERSION, agentId: id, ...(parentAgentId ? { parentAgentId } : {}), rootId, rootHash: hashLineageRoot(rootId), ownerSessionId: artifactOwnerSessionId, name: params.name, taskPreview: params.task.replace(/\s+/g, " ").slice(0, 4096), startedAt: new Date().toISOString(), cwd, pane: { backend: mux.name, ...(muxTerminalId ? { muxTerminalId } : {}), paneId, ...(muxSession ? { muxSession } : {}), ...(muxServer ? { muxServer } : {}), ...(windowName ? { windowName } : {}), }, artifactDir: paths.artifactDir, childSessionFile: paths.sessionFile, }, ); } catch (err) { reportSpawnFailure( "state_persistence", mux.name, "lineage_manifest_write", ); if (persistedState) { try { removeInteractiveState(stateCwd, id); } catch { /* preserve the lineage error */ } } try { mux.killPane(paneId, muxSession, ...muxServerArgs(muxServer)); } catch { /* best effort — preserve the lineage error */ } throw err; } } let attach: { attachCommand: string; focusCommand: string }; const cleanupFailedSpawn = (): void => { if (persistedState && params.parentSessionId) { try { removeInteractiveState(stateCwd, id); } catch { /* best effort — the pane kill below is the important cleanup */ } } if (lineageManifestPath) { try { rmSync(lineageManifestPath, { force: true }); } catch { /* best effort */ } } if (lineageBootstrapPath) { try { rmSync(lineageBootstrapPath, { force: true }); } catch { /* best effort — the pane kill below is the important cleanup */ } } if (childArtifactBootstrapPath) { try { rmSync(childArtifactBootstrapPath, { force: true }); } catch { /* best effort — the pane kill below is the important cleanup */ } } try { mux.killPane(paneId, muxSession, ...muxServerArgs(muxServer)); } catch { /* best effort — preserve the original spawn error */ } }; let command: string; try { command = buildPiInteractiveCommand({ sessionFile: paths.sessionFile, name: params.name, promptFile: paths.promptFile, systemPromptFile, model: params.model, cwd, thinkingLevel: params.thinkingLevel, }); } catch (err) { reportSpawnFailure("state_persistence", mux.name, "child_command_build"); cleanupFailedSpawn(); throw err; } if (spawnTreeContext) { try { lineageBootstrapPath = writeLineageBootstrap( paths.artifactDir, createDescendantSpawnTreeContext( spawnTreeContext, id, paths.artifactDir, ), ); } catch (err) { reportSpawnFailure( "state_persistence", mux.name, "lineage_bootstrap_write", ); cleanupFailedSpawn(); throw err; } } try { childArtifactBootstrapPath = writeChildArtifactBootstrap(paths.artifactDir); } catch (err) { reportSpawnFailure("state_persistence", mux.name, "artifact_write"); cleanupFailedSpawn(); throw err; } try { writeLaunchScript(paths.launchScriptFile, command, paths.artifactDir, { PI_SUBAGENTURA_MUX: mux.name, // Independent app terminals may not load the parent's shell startup files. // Preserve the parent's executable search path for this local wrapper. ...((mux.name === "herdr-core" || mux.name === "cmux") && process.env.PATH !== undefined ? { PATH: process.env.PATH } : {}), [CHILD_ARTIFACT_BOOTSTRAP_ENV]: childArtifactBootstrapPath, ...(lineageBootstrapPath ? { [LINEAGE_BOOTSTRAP_ENV]: lineageBootstrapPath } : {}), ...(!telemetry?.enabled ? { [TELEMETRY_ENV]: "0" } : {}), }); } catch (err) { reportSpawnFailure("state_persistence", mux.name, "launch_script_write"); cleanupFailedSpawn(); throw err; } let releasePendingLaunch: (() => void) | undefined; try { const escape = (v: string) => `'${v.replace(/'/g, `'\\''`)}'`; // These app terminals do not source the parent's shell startup files. const bash = mux.name === "herdr-core" || mux.name === "cmux" ? "/bin/bash" : "bash"; const launchCommand = `exec ${bash} ${escape(paths.launchScriptFile)}`; if (mux.sendLaunchCommand) { const pending = trackPendingInteractiveLaunch(id); releasePendingLaunch = pending.release; const assertCurrent = () => { assertLaunchCurrent(mux.name); // The local supervisor may cancel before registration. A different // process can signal the same intent with the durable marker. if ( pending.isCancelled() || existsSync(join(paths.artifactDir, ".cancelled")) ) throw new Error("Interactive launch cancelled"); }; // Wait for the reply even if cancelled: the command might have reached // the terminal. Never resubmit it, and clean up only the known pane. await mux.sendLaunchCommand( paneId, launchCommand, muxServer, assertCurrent, ); assertCurrent(); } else { submitMuxCommand( mux, paneId, launchCommand, muxSession, ...muxServerArgs(muxServer), ); } attach = mux.buildAttachCommands({ paneId, terminalId: muxTerminalId, windowName, session: muxSession, ...(muxServer === undefined ? {} : { server: muxServer }), }); } catch (err) { reportSpawnFailure("pane_launch", mux.name, "pane_launch"); cleanupFailedSpawn(); throw err; } finally { releasePendingLaunch?.(); } const state: InteractiveSubagentState = { id, name: params.name, task: params.task, ...(muxTerminalId ? { muxTerminalId } : {}), paneId, windowName, mux: mux.name, muxSession, ...(muxServer === undefined ? {} : { muxServer }), sessionFile: paths.sessionFile, cwd: stateCwd, workingCwd: cwd, model: params.model, startedAt: Date.now(), status: "running", attachCommand: attach.attachCommand, selectPaneCommand: attach.focusCommand, launchScriptFile: paths.launchScriptFile, artifactDir: paths.artifactDir, completionPolicy, completionGroupId: params.completionGroupId, parentSessionId: params.parentSessionId, supervisorOwner: params.supervisorOwner, workflowId: params.workflowId, completionOwner: params.completionOwner, eventByteCursor: 0, pendingDeliveries: [], deliveryReceipts: [], telemetryCorrelationId: telemetryMetadata?.correlationId, telemetryEligible: telemetryMetadata !== undefined, telemetryTurnMessageCounts: new Map(), telemetryInvocationSource: telemetryMetadata?.invocationSource, telemetryCompletionPolicy: telemetryMetadata?.completionPolicy, telemetryAsync: telemetryMetadata?.async, telemetryDepth: telemetryMetadata?.depth, telemetryDepthBucket: telemetryMetadata?.depthBucket, telemetryModel: telemetryMetadata?.model, }; if (telemetryMetadata && telemetry) { interactiveCreatedTelemetry.set(state, { session: telemetry, spawnStartedAt: spawnStartedAt, captured: false, }); } try { registerInteractiveSubagentState(state, liveScope); } catch (err) { interactiveCreatedTelemetry.delete(state); reportSpawnFailure("registration", mux.name, "completion_registration"); removeInteractiveSubagentState(state); if (persistedState && params.parentSessionId) { try { removeInteractiveState(stateCwd, id); } catch { /* best effort — the pane kill below is the important cleanup */ } } if (lineageManifestPath) { try { rmSync(lineageManifestPath, { force: true }); } catch { /* best effort */ } } try { mux.killPane(paneId, muxSession, ...muxServerArgs(muxServer)); } catch { /* best effort */ } throw err; } if (telemetryMetadata && !params.deferAgentCreatedTelemetry) { captureInteractiveSubagentCreatedTelemetry(state); } return state; } /** * Resolve the multiplexer that created a given sub-agent state. Uses * `state.mux` to dispatch to the right backend via `getMux({ preference: * state.mux })`, which returns a cached instance so the exec probe is * paid once per process. */ function getMuxForState(state: InteractiveSubagentState): Multiplexer { return getMux({ preference: state.mux }); } function muxServerArgs(server?: string): [] | [string] { return server === undefined ? [] : [server]; } export interface CurrentPaneActivity { readonly status: PaneActivity; readonly mux?: MuxName; readonly paneId?: string; readonly session?: string; } /** Probe whether the current Pi process's mux pane is active for the user. */ export async function getCurrentPaneActivity(): Promise { const context = await resolveCurrentMuxContextAsync(); if (context.kind !== "ready") return { status: "unknown" }; const target = context.target; const location = { mux: target.mux, paneId: target.paneId, ...(target.session ? { session: target.session } : {}), }; let status: PaneActivity; try { status = await getMux({ preference: target.mux }).getPaneActivityAsync( target.paneId, target.session, ...muxServerArgs(target.server), ); } catch { // Activity is advisory; an unavailable mux must not break the child. status = "unknown"; } return { status, ...location }; } export function paneRefForState(state: InteractiveSubagentState): PaneRef { return { paneId: state.paneId, ...(state.muxTerminalId ? { muxTerminalId: state.muxTerminalId } : {}), windowName: state.windowName, session: state.muxSession, ...(state.muxServer === undefined ? {} : { server: state.muxServer }), }; } export function focusInteractiveSubagent( state: InteractiveSubagentState, ): Promise { return getMuxForState(state).focusPane(paneRefForState(state)); } export function captureInteractiveSubagent( state: InteractiveSubagentState, options: CapturePaneOptions, ): Promise { return getMuxForState(state).capturePane(paneRefForState(state), options); } export function showInteractiveSubagentNativeViewer( state: InteractiveSubagentState, content: string, ): Promise { return getMuxForState(state).showNativeViewer(state.name, content); } /** Probe pane liveness using the mux that created it. */ export function getInteractivePaneLiveness( state: InteractiveSubagentState, ): PaneLiveness { return getMuxForState(state).getPaneLiveness( state.paneId, state.muxSession, ...muxServerArgs(state.muxServer), ); } /** Preserve active state unless the backend explicitly confirms pane death. */ export function isPaneAlive(state: InteractiveSubagentState): boolean { return getInteractivePaneLiveness(state) !== "dead"; } /** Probe pane liveness without blocking the parent event loop. */ export function getInteractivePaneLivenessAsync( state: InteractiveSubagentState, ): Promise { return getMuxForState(state).getPaneLivenessAsync( state.paneId, state.muxSession, ...muxServerArgs(state.muxServer), ); } /** Probe pane liveness with optional backend-specific failure detail. */ export async function getInteractivePaneLivenessDiagnosticAsync( state: InteractiveSubagentState, ): Promise { const mux = getMuxForState(state); if (mux.getPaneLivenessDiagnosticAsync) { return mux.getPaneLivenessDiagnosticAsync( state.paneId, state.muxSession, ...muxServerArgs(state.muxServer), ); } return { liveness: await mux.getPaneLivenessAsync( state.paneId, state.muxSession, ...muxServerArgs(state.muxServer), ), }; } /** Preserve active state unless the async backend explicitly confirms death. */ export async function isPaneAliveAsync( state: InteractiveSubagentState, ): Promise { return (await getInteractivePaneLivenessAsync(state)) !== "dead"; } /** Probe the pane recorded in a lineage manifest. */ export function getLineagePaneLiveness( manifest: LineageManifest, ): PaneLiveness { const backend = manifest.pane.backend; if ( backend !== "tmux" && backend !== "zellij" && backend !== "herdr" && backend !== "rex" && backend !== "wezterm" && backend !== "herdr-core" && backend !== "cmux" ) { return "unknown"; } try { return getMux({ preference: backend }).getPaneLiveness( manifest.pane.paneId, manifest.pane.muxSession, ...muxServerArgs(manifest.pane.muxServer), ); } catch { return "unknown"; } } /** * Whether a mux client is attached to the session hosting this agent's pane. * * `undefined` means "cannot tell". Focus is server-side state — tmux * `select-window` exits 0 with zero clients attached — so a successful focus is * invisible to the user for a detached `pi-subagent-` session, which is the * normal case for the relaxed spawn path. * * The probe itself belongs to the multiplexer layer. Backends opt in by * implementing the optional `hasAttachedClientAsync(session?)` method; until * they do, this resolves `undefined` and the UI stays quiet. */ export async function interactiveSubagentHasAttachedClient( state: InteractiveSubagentState, ): Promise { const mux = getMuxForState(state) as Multiplexer & { hasAttachedClientAsync?: ( session?: string, server?: string, ) => Promise | boolean | undefined; }; if (typeof mux.hasAttachedClientAsync !== "function") return undefined; try { return await mux.hasAttachedClientAsync( state.muxSession, ...muxServerArgs(state.muxServer), ); } catch { return undefined; } } /** * Send a command (text + Enter) to a pane, using the mux that created it. * Mux-agnostic — replaces `sendCommandToTmuxPane(paneId, command)`. */ export function sendCommandToPane( state: InteractiveSubagentState, command: string, ): void { const mux = getMuxForState(state); submitMuxCommand( mux, state.paneId, command, state.muxSession, ...muxServerArgs(state.muxServer), ); } /** Rebuild attach/focus commands for a persisted or rehydrated state. */ export function buildAttachCommandsForState( state: Pick< InteractiveSubagentState, | "paneId" | "muxTerminalId" | "windowName" | "mux" | "muxSession" | "muxServer" >, ): { attachCommand: string; focusCommand: string } { return getMuxForState(state as InteractiveSubagentState).buildAttachCommands({ paneId: state.paneId, terminalId: state.muxTerminalId, windowName: state.windowName, session: state.muxSession, ...(state.muxServer === undefined ? {} : { server: state.muxServer }), }); } /** * Probe a tmux pane. Kept as a thin helper for the existing call sites in * subagent.ts; PR #2 will route through `state.mux` so this becomes mux-agnostic. */ /** * Probe a tmux pane. Kept as a thin helper for the existing call sites in * subagent.ts; PR #2 will route through `state.mux` so this becomes mux-agnostic. */ export function isTmuxPaneAlive(paneId: string): boolean { return new TmuxMultiplexer().getPaneLiveness(paneId) === "alive"; } /** * Send a command to a tmux pane. Backward-compat alias — prefer * `sendCommandToPane(state, command)` which is mux-agnostic. */ export function sendCommandToTmuxPane(paneId: string, command: string): void { const mux = new TmuxMultiplexer(); mux.sendKeys(paneId, command); mux.sendEnter(paneId); } interface ParentCancellationContext { origin: ParentCancellationOrigin; lifecycleReason?: ParentCancellationLifecycleReason; } export function cancelInteractiveSubagent( id: string, source: CancellationSnapshotSource = "cancel_interactive_subagent", ownedState?: InteractiveSubagentState, ): InteractiveSubagentState | undefined { const snapshotSource = source === "supervisor" ? "cancel_interactive_subagent" : source; if (!ownedState || ownedState.id !== id) return undefined; const state = ownedState; const snapshot = snapshotInteractiveContext({ kind: "interactive", id: state.id, parentSessionId: state.parentSessionId, cwd: state.cwd, sessionFile: state.sessionFile, artifactDir: state.artifactDir, startedAt: state.startedAt, source: snapshotSource, cancellationOrigin: source, }); state.cancellationSnapshot = snapshot; cancelInteractivePane(state, { origin: source }); return state; } function cancelInteractivePane( state: InteractiveSubagentState, context: ParentCancellationContext, ): void { markPendingInteractiveLaunchCancelled(state.id); const marker = join(state.artifactDir, ".cancelled"); const mux = getMuxForState(state); const { paneId, muxSession, muxServer } = state; const serverArgs = muxServerArgs(muxServer); const stop = () => { if (mux.getPaneLiveness(paneId, muxSession, ...serverArgs) !== "dead") { mux.killPane(paneId, muxSession, ...serverArgs); } }; let createdMarker = false; // The wrapper must see the marker if it exits as the pane is being closed. try { writeFileSync(marker, "", { mode: 0o600, flag: mux.confirmsPaneStop ? "wx" : "w", }); createdMarker = true; } catch { // The artifact directory may be unavailable, or already marked. } if (mux.confirmsPaneStop) { try { stop(); } catch (error) { if (createdMarker) { try { rmSync(marker, { force: true }); } catch (cleanupError) { throw new AggregateError( [error, cleanupError], "Pane close and cancellation rollback failed", { cause: error }, ); } } throw error; } } retireLineageBootstraps(state.artifactDir); try { appendCancellation(state, context); } finally { state.status = "cancelled"; // Keep the durable intent before teardown on best-effort backends. if (!mux.confirmsPaneStop) stop(); } } function appendCancellation( state: InteractiveSubagentState, context: ParentCancellationContext, ): void { let turnId = "process"; try { const active = parseJsonRecord( readFileSync(join(state.artifactDir, "active-turn.json"), "utf8"), ); turnId = normalizeTurnId(active?.turnId) ?? turnId; } catch { /* cancellation before the first turn uses the process turn */ } const art = artifactPath( dirname(state.artifactDir), basename(state.artifactDir), ); let completion = appendCompletionEvent(art, { turnId, outcome: "cancelled", source: "parent", cancellationOrigin: context.origin, cancellationLifecycleReason: context.lifecycleReason, }); if (!completion) { turnId = `process-cancel-${newEventId()}`; completion = appendCompletionEvent(art, { turnId, outcome: "cancelled", source: "parent", cancellationOrigin: context.origin, cancellationLifecycleReason: context.lifecycleReason, }); } if (!completion) return; } /** * Cancel a persisted descendant without claiming its completion in the root * session. The descendant's owning Pi process remains responsible for polling * the durable completion and delivering it to its own session. */ export function cancelInteractiveDescendantByState( state: InteractiveSubagentState, ): InteractiveSubagentState { state.cancellationSnapshot = snapshotInteractiveContext({ kind: "interactive", id: state.id, parentSessionId: state.parentSessionId, cwd: state.cwd, sessionFile: state.sessionFile, artifactDir: state.artifactDir, startedAt: state.startedAt, source: "cancel_interactive_subagent", cancellationOrigin: "supervisor_descendant", }); cancelInteractivePane(state, { origin: "supervisor_descendant" }); return state; } /** * Kills a tmux pane and writes the .cancelled flag for an interactive sub-agent, * bypassing the registry. Used by the session_shutdown handler which snapshots * running states before clearing the registry (see subagent.ts session_shutdown * handler — snapshot-before-clear pattern). * * Differs from `cancelInteractiveSubagent` in three intentional ways: * 1. NO registry lookup: takes the full `InteractiveSubagentState` by value * instead of looking it up by id. This is required because the shutdown * handler clears the registry BEFORE killing panes (to prevent the * in-flight poll tick race), so `cancelInteractiveSubagent(id)` would * early-return `undefined` and the pane-kill would be skipped. * 2. NO `state.status = "cancelled"` update: the state object is a snapshot * detached from the registry; mutating it would have no observable * effect (the registry is already cleared, no future poll will see it). * 3. `mux.killPane` wrapped in try/catch: a synchronous `execFileSync` failure * (e.g. tmux already exited, session torn down) must not abort the * shutdown loop over remaining running states. The original function * relies on its caller to wrap in try/catch; this variant does it * internally so the shutdown handler is a clean loop. * * @param state - the snapshotted state of the sub-agent to cancel */ export function cancelInteractiveSubagentByState( state: InteractiveSubagentState, context: ParentCancellationContext = { origin: "session_shutdown" }, ): void { const snapshot = snapshotInteractiveContext({ kind: "interactive", id: state.id, parentSessionId: state.parentSessionId, cwd: state.cwd, sessionFile: state.sessionFile, artifactDir: state.artifactDir, startedAt: state.startedAt, source: "session_shutdown", cancellationOrigin: context.origin, cancellationLifecycleReason: context.lifecycleReason, }); state.cancellationSnapshot = snapshot; // 1. Write .cancelled flag (best-effort) try { writeFileSync(join(state.artifactDir, ".cancelled"), "", { mode: 0o600 }); } catch { /* best-effort */ } retireLineageBootstraps(state.artifactDir); try { appendCancellation(state, context); } finally { // Teardown must outlive artifact failures during destructive transitions. const mux = getMuxForState(state); if ( mux.getPaneLiveness( state.paneId, state.muxSession, ...muxServerArgs(state.muxServer), ) !== "dead" ) { try { mux.killPane( state.paneId, state.muxSession, ...muxServerArgs(state.muxServer), ); } catch { /* best-effort */ } } } // Does NOT update state.status — see JSDoc point 2. } /** Pure status-decision matrix shared by pruning and the artifact poller. */ export function deriveInteractiveSubagentStatus( lastEvent: SubagentEvent | null, paneAlive: boolean, ): InteractiveSubagentStatus { if (!lastEvent) return paneAlive ? "running" : "unknown"; switch (lastEvent.type) { case "process_exited": return lastEvent.status === "cancelled" ? "cancelled" : "exited"; case "completion": if (lastEvent.outcome === "cancelled") return "cancelled"; return paneAlive ? "idle" : "exited"; case "tool_activity": case "turn_started": return paneAlive ? "running" : "unknown"; default: return assertNever(lastEvent); } } export function deriveInteractiveSubagentStatusFromEvents( events: SubagentEvent[], paneAlive: boolean, ): InteractiveSubagentStatus { const lifecycle: PersistedLifecycleFold = {}; for (const event of events) foldInteractiveLifecycle(lifecycle, event); return deriveInteractiveSubagentStatusFromLifecycle(lifecycle, paneAlive); } export function foldInteractiveLifecycle( lifecycle: PersistedLifecycleFold, event: SubagentEvent, ): void { lifecycle.startedAt ??= event.ts; switch (event.type) { case "process_exited": { lifecycle.processStatus = event.status; lifecycle.processExitCode = event.exitCode; return; } case "turn_started": { lifecycle.currentTurnId = event.turnId; lifecycle.completionTurnId = undefined; lifecycle.completionOutcome = undefined; lifecycle.completionSource = undefined; lifecycle.completionExitCode = undefined; return; } case "completion": { if (event.outcome === "cancelled" && event.source === "parent") { lifecycle.parentCancelled = true; } if ( !lifecycle.currentTurnId || event.turnId === lifecycle.currentTurnId ) { lifecycle.completionTurnId = event.turnId; lifecycle.completionOutcome = event.outcome; lifecycle.completionSource = event.source; lifecycle.completionExitCode = event.exitCode; } return; } case "tool_activity": // Activity events do not affect lifecycle state. return; default: return assertNever(event); } } export function deriveInteractiveSubagentStatusFromLifecycle( lifecycle: PersistedLifecycleFold, paneState: boolean | PaneLiveness, ): InteractiveSubagentStatus { const paneLiveness: PaneLiveness = typeof paneState === "boolean" ? (paneState ? "alive" : "dead") : paneState; if (lifecycle.parentCancelled) return "cancelled"; if (lifecycle.processStatus) { return lifecycle.processStatus === "cancelled" ? "cancelled" : "exited"; } if (lifecycle.completionOutcome) { if (lifecycle.completionOutcome === "cancelled") return "cancelled"; if (paneLiveness === "alive") return "idle"; return paneLiveness === "dead" ? "exited" : "unknown"; } if (paneLiveness === "alive") return "running"; if (paneLiveness === "unknown") return "unknown"; return typeof paneState === "boolean" ? "unknown" : "exited"; } /** * Update registry status for tracked sub-agents based on artifact lifecycle * and pane liveness. A live pane after a protocol-v2 completion is idle and * can accept another prompt. */ export function pruneDeadInteractiveSubagents( states: Iterable = [], ): void { for (const state of states) { if ( state.status !== "running" && state.status !== "idle" && state.status !== "unknown" ) { continue; } const paneLiveness = getInteractivePaneLiveness(state); const next = deriveInteractiveSubagentStatusFromLifecycle( state.lifecycle ?? {}, paneLiveness, ); if (next === state.status) continue; state.status = next; const exitCode = state.lifecycle?.processExitCode ?? state.lifecycle?.completionExitCode; if (next === "exited" && exitCode !== undefined) state.exitCode = exitCode; } } export function formatInteractiveState( state: InteractiveSubagentState, ): string { const elapsed = Math.floor((Date.now() - state.startedAt) / 1000); const taskPreview = state.task.replace(/\s+/g, " ").slice(0, 80); const lines: string[] = [ `${state.name} (${state.id}) — ${state.status}, ${elapsed}s`, `Task: ${taskPreview}${state.task.length > 80 ? "…" : ""}`, `Mux: ${state.mux}`, `Pane: ${state.paneId}`, ]; if (state.windowName) lines.push(`Window: ${state.windowName}`); if (state.exitCode !== undefined) lines.push(`Exit code: ${state.exitCode}`); lines.push(`Artifact: ${state.artifactDir}`); lines.push(`State cwd: ${state.cwd}`); lines.push(`Working cwd: ${state.workingCwd ?? "unknown"}`); if (!(state.mux === "tmux" && process.env.TMUX)) { lines.push(`Attach: ${state.attachCommand}`); } lines.push(`Focus: ${state.selectPaneCommand}`); lines.push(`Session: ${state.sessionFile}`); return lines.join("\n"); }