import type { RecoveryLaunchFailure } from "./recovery-launch.ts"; import { shellQuote } from "./shell-quote.ts"; export { shellQuote } from "./shell-quote.ts"; import { createProjectAdapterCatalog, definitionOf, type ProjectAdapterCatalog, type KindMap } from "../adapters/registry.ts"; import { readInstanceConfig, readInstanceRoleConfig } from "../hub/instance-config.ts"; import { effectiveInstanceRoles } from "../hub/instances.ts"; import { resolveInstanceExecutionCwd } from "../hub/instance-execution.ts"; import { isAbsolute, join, resolve } from "node:path"; import { fileURLToPath } from "node:url"; import { existsSync, mkdirSync, readFileSync } from "node:fs"; import { randomUUID } from "node:crypto"; import { processLiveness, processSignature } from "../pi/process-signature.ts"; import { atomicPrivateJSON } from "../hub/recovery-store.ts"; import type { ControlClient } from "../hub/control-client.ts"; /** The only terminal commands used by this adapter. Keep this list in sync with Orca's public CLI. */ export type OrcaTerminalCommand = "list" | "show" | "wait" | "close" | "create"; export interface CommandResult { /** Bun's name for the process exit status. */ status?: number; /** Alternate name used by small test runners and child-process wrappers. */ exitCode?: number; stdout?: string | Uint8Array; stderr?: string | Uint8Array; /** A runner may return the already-decoded JSON response. */ result?: unknown; } /** Runs one argv vector. The adapter never passes a shell command to this function. */ export type CommandRunner = (argv: readonly string[]) => Promise; /** Stable process identity hook. It returns a digest, never raw process metadata. */ export type ProcessIdentity = (pid: number) => string | undefined | Promise; export type TerminalPeer = string; export interface SessionRef { sessionId: string; sessionFile?: string; backend?: string; model?: string; } export interface LaunchMetadata { /** Absolute entrypoint of the package which owns the resumed session. */ packageEntrypoint: string; /** Complete command string passed to Orca's supported `terminal create --command` flag. */ command: string; /** The parsed argv represented by `command`, useful to a journal and tests. */ argv: string[]; /** Only these two variables can cross a recovery boundary. */ env: Partial, "CODEX_HOME" | "CLAUDE_CONFIG_DIR">>; } export interface TerminalBinding { peer: TerminalPeer; handle: string; incarnationId: string; worktreeId: string; projectRoot: string; /** Authenticated declared-extra execution root; canonical projectRoot remains the authority. */ executionCwd?: string; /** Verified Orca grouping root, only canonical project or the authorized execution worktree. */ terminalRoot?: string; sessionId: string; sessionFile?: string; backend?: string; model?: string; launch: LaunchMetadata; /** Alias retained for callers that use the wire name. */ launchMetadata: LaunchMetadata; } export interface RecoveryBlocker { code: | "project-root-mismatch" | "stale-terminal" | "missing-terminal" | "missing-session" | "ownership-unknown" | "ambiguous-terminal" | "terminal-unready" | "terminal-orphaned" | "command-error" | "ambiguous-create" | "launch-failed" | "launcher-exited" | "terminal-gone"; message: string; failure?: RecoveryLaunchFailure; peer?: TerminalPeer; handle?: string; /** Stable terminal reference when Orca supplied one, for operator reconciliation. */ terminalReference?: string; /** Human action that can resolve the blocker without guessing or retrying an effect. */ nextAction?: string; } /** Read-only evidence for one already recorded terminal, never a session-selection result. */ export interface SavedTerminalInspection { state: "present" | "orphaned" | "missing" | "changed" | "unknown"; blocker?: RecoveryBlocker; } export interface TerminalInspection { bindings: TerminalBinding[]; /** A map is convenient for callers recovering both peers at once. */ byPeer: Partial>; blockers: RecoveryBlocker[]; manualRequired: boolean; /** #1246: terminals whose identity was verified (handle, incarnation, worktree, root, peer) and that read orphaned but still connected: the only ones a person may have switched back. */ orphaned?: OrphanedTerminal[]; } /** #1246: one verified orphaned-but-connected terminal, as the plan records it. Never a session or a launch. */ export interface OrphanedTerminal { peer: TerminalPeer; handle: string; incarnationId: string; worktreeId: string; /** The terminal's worktree root as Orca reported it and the plan matched it. */ root: string; } export interface IdleResult { satisfied: boolean; manualRequired: boolean; blockers: RecoveryBlocker[]; } export type RestorationStatus = "restored" | "manual-required"; export interface RestorationResult { status: RestorationStatus; manualRequired: boolean; peer: TerminalPeer; oldHandle: string; newBinding?: TerminalBinding; blockers: RecoveryBlocker[]; } export interface TerminalCloseResult { closed: boolean; manualRequired: boolean; binding: TerminalBinding; blockers: RecoveryBlocker[]; } export interface TerminalCreateResult { created: boolean; ready: boolean; manualRequired: boolean; binding?: TerminalBinding; /** Compatibility name used by the coordinator journal. */ newBinding?: TerminalBinding; blockers: RecoveryBlocker[]; } export interface TerminalRecoveryOptions { /** Host-owned per-attempt exit observation; diagnostic only, never a readiness proof. */ launchFailure?: () => RecoveryLaunchFailure | undefined; runner?: CommandRunner; /** Exact execution root returned by authenticated extra startup; checked against the current declaration. */ executionCwd?: string; /** Defaults to `orca`; callers in a managed session may pin another executable. */ orcaExecutable?: string; /** Absolute path to this package's JS entrypoint. */ packageEntrypoint?: string; /** Private state directory used to authenticate terminals launched by this ahub instance. */ stateDir?: string; /** Daemon instance fence for a recorded launch. */ instanceId?: string; /** Injectable process-start identity used to reject stale or reused launcher PIDs. */ processIdentity?: ProcessIdentity; /** * #228: the identity as releases up to 0.12.12 computed it (unpinned `ps`, the reader's TZ and locale). It defaults * to that read only when `processIdentity` is the default, so an injected identity is never second-guessed by a * real `ps` read of the same pid. */ legacyIdentity?: ProcessIdentity; } export interface RecordedTerminalLaunch { peer: TerminalPeer; projectRoot: string; executionCwd?: string; terminalRoot?: string; stateDir: string; instanceId: string; launcherPid: number; launcherSignature: string; /** Per-launch fence inherited by the native agent and Claude statusline. */ launchId: string; handle: string; incarnationId: string; worktreeId: string; env: Partial>; } const MAX_WAIT_MS = 10 * 60 * 1000; export const MAX_COMMAND_MS = 30_000; /** #215: a replacement's readiness is awaited in slices this long, checking between them whether its launcher still runs. */ const EXIT_SLICE_MS = 5_000; /** #599: after the replacement reads idle, its session mapping is re-read this often until the deadline. */ const MAP_POLL_MS = 1_000; const ALLOWED_ENV = ["CODEX_HOME", "CLAUDE_CONFIG_DIR"] as const; type AllowedEnvName = (typeof ALLOWED_ENV)[number]; const defaultEntrypoint = resolve(fileURLToPath(new URL("./main.js", import.meta.url))); function bytes(value: string | Uint8Array | undefined): string { if (value === undefined) return ""; return typeof value === "string" ? value : new TextDecoder().decode(value); } function commandStatus(result: CommandResult): number { return result.status ?? result.exitCode ?? 0; } function decoded(result: CommandResult): unknown { if (result.result !== undefined) return result.result; const text = bytes(result.stdout).trim(); if (!text) return undefined; try { return JSON.parse(text) as unknown; } catch { return undefined; } } /** Orca's structured error, from the JSON it prints on stdout or stderr. */ function orcaError(result: CommandResult): Record { const fromStdout = object(object(decoded(result)).error); if (fromStdout.code !== undefined) return fromStdout; try { return object(object(JSON.parse(bytes(result.stderr))).error); } catch { return {}; } } function errorCode(result: CommandResult): unknown { return orcaError(result).code; } /** #1233: Orca prints its error as JSON on stdout with an empty stderr, so its code comes before the exit-status fallback. */ function errorText(result: CommandResult): string { const { code, message } = orcaError(result); if (typeof code === "string") return typeof message === "string" && message !== code ? `${code}: ${message.slice(0, 200)}` : code; const stderr = bytes(result.stderr).trim(); return stderr || `exit status ${commandStatus(result)}`; } /** * Orca 1.4.250 answers a terminal it can no longer reach with one of these codes, and its own CLI groups all four as * gone (docs/verification/2026-11-06-orca-1.4.250-cli-contract.md). A wait on a pane whose process ended throws * terminal_exited, so restoration must read it as gone and check the launcher, not stop on a command error (#1233). */ const GONE_CODES = new Set(["terminal_handle_stale", "terminal_exited", "terminal_gone", "no_connected_pty"]); const GONE_STATES: Record = { terminal_handle_stale: "no longer exists", terminal_exited: "exited (terminal_exited)" }; function runnerFailure(argv: readonly string[], result: CommandResult): RecoveryBlocker { return { code: "command-error", message: `Orca ${argv.slice(0, 2).join(" ")} failed: ${errorText(result)}` }; } async function run(runner: CommandRunner, argv: readonly string[]): Promise { const result = await runner(argv); if (commandStatus(result) !== 0) { // Orca 1.4.223 and, rechecked read-only, 1.4.245 (docs/verification/2026-11-02-orca-1.4.245-cli-contract.md) answer a handle whose terminal was removed with `{"ok":false,"error":{"code":"terminal_handle_stale"}}`. const code = errorCode(result); if (typeof code === "string" && GONE_CODES.has(code)) { const handle = argv.includes("--terminal") ? argv[argv.indexOf("--terminal") + 1] : undefined; const state = GONE_STATES[code] ?? `is gone (${code})`; throw new OrcaCommandError({ code: "terminal-gone", message: `the Orca terminal${handle ? ` ${handle}` : ""} ${state}` }); } throw new OrcaCommandError(runnerFailure(argv, result)); } const value = decoded(result); const root = object(value); const payload = responseResult(value); if (root.ok === false || payload.ok === false) { const error = root.error ?? payload.error; const detail = typeof error === "string" ? error : object(error).code; throw new OrcaCommandError({ code: "command-error", message: `Orca ${argv.slice(0, 2).join(" ")} returned ok:false${typeof detail === "string" && detail ? `: ${detail}` : ""}` }); } return value; } export class OrcaCommandError extends Error { constructor(public readonly blocker: RecoveryBlocker) { super(blocker.message); this.name = "OrcaCommandError"; } } /** POSIX quoting for the single command-string argument accepted by Orca. */ function normalizeOptions(options?: CommandRunner | TerminalRecoveryOptions): Required { const config: TerminalRecoveryOptions = typeof options === "function" ? { runner: options } : options ?? {}; const orcaExecutable = config.orcaExecutable ?? resolveOrcaExecutable(); return { launchFailure: config.launchFailure ?? (() => undefined), runner: config.runner ?? defaultRunner(orcaExecutable), orcaExecutable, packageEntrypoint: config.packageEntrypoint ?? defaultEntrypoint, executionCwd: config.executionCwd ?? "", stateDir: config.stateDir ?? "", instanceId: config.instanceId ?? "", processIdentity: config.processIdentity ?? defaultProcessIdentity, legacyIdentity: config.legacyIdentity ?? (config.processIdentity ? () => undefined : unpinnedProcessIdentity), }; } /** Resolve the same binary selection as the Orca CLI skill, once per operation. */ function resolveOrcaExecutable(): string { if (process.env.ORCA_CLI_COMMAND) return process.env.ORCA_CLI_COMMAND; if (process.env.ORCA_DEV_REPO_ROOT) return "orca-dev"; if (process.platform === "linux") return "orca-ide"; return "orca"; } function defaultProcessIdentity(pid: number): string | undefined { if (!Number.isInteger(pid) || pid <= 0) return undefined; return processSignature(pid); } function defaultRunner(executable: string): CommandRunner { return async (argv) => { const child = Bun.spawn([executable, ...argv], { stdout: "pipe", stderr: "pipe" }); let timer: ReturnType | undefined; try { const result = Promise.all([child.stdout.text(), child.stderr.text(), child.exited]); const timeout = new Promise((_, reject) => { timer = setTimeout(() => { child.kill(); reject(new Error(`orca command timed out after ${MAX_COMMAND_MS}ms`)); }, MAX_COMMAND_MS); }); const [stdout, stderr, status] = await Promise.race([result, timeout]); return { stdout, stderr, status }; } finally { if (timer) clearTimeout(timer); } }; } /** The Orca executable a start or a recovery would run (`orca`, or what the environment pins). */ export const orcaExecutable = (): string => resolveOrcaExecutable(); /** * #269: whether Orca is in play for this project: this process runs in an Orca terminal, or an earlier `ahub ` * launch of this project recorded a worktree. It is only a hint for a synchronous "could a start open a terminal" * answer. It is never the worktree a terminal is opened in: the environment names the worktree of whatever terminal * this process was started from, which is another project's when `ahub --project`, the dashboard manager or an upgrade * brought this project up (#1089). `resolveStartTerminalWorktree` names the worktree. */ export function startTerminalCandidate(projectRoot: string, stateDir: string, env: NodeJS.ProcessEnv = process.env): boolean { if (env.ORCA_WORKTREE_ID) return true; const records = launchRecords(stateDir); return records !== "unreadable" && records.rows.some((row) => row.projectRoot === projectRoot && typeof row.worktreeId === "string"); } /** #1089: how many worktrees one `orca worktree list` asks for; a longer list is reported as truncated and never read as "none". */ const WORKTREE_LIST_LIMIT = 500; /** * #1089: the Orca worktree whose root is exactly this project's root, asked of Orca and never taken from the caller's * environment. The match is exact because `ahub ` compares the terminal's worktree root with the project root by * equality and refuses on a difference: a terminal opened in any other worktree would only fail later. The refusal names * the cause and the next step and carries no path; Orca's own words go in `detail` for the hub log. */ export async function resolveStartTerminalWorktree(projectRoot: string, options?: CommandRunner | TerminalRecoveryOptions): Promise<{ ok: true; worktreeId: string } | { ok: false; why: string; detail?: string }> { const config = normalizeOptions(options); let value: unknown; try { value = await run(config.runner, ["worktree", "list", "--limit", String(WORKTREE_LIST_LIMIT), "--json"]); } catch (error) { return { ok: false, why: "Orca could not list its worktrees, so no terminal was opened. Check that Orca is running (orca worktree list), then start the peer again, or set terminal.open", detail: (error as Error).message }; } const payload = responseResult(value); const rows = Array.isArray(payload.worktrees) ? payload.worktrees.map(object) : []; const matches = rows.filter((row) => row.isArchived !== true && rootMatches(row.path, projectRoot) && typeof row.id === "string" && row.id.length > 0); if (matches.length === 1) return { ok: true, worktreeId: String(matches[0]!.id) }; if (matches.length > 1) return { ok: false, why: "more than one Orca worktree has this project's root, so no terminal was opened. Archive the extra entry in Orca, or set terminal.open" }; if (payload.truncated === true) return { ok: false, why: `Orca's worktree list was cut off at ${WORKTREE_LIST_LIMIT} rows before one with this project's root appeared, so no terminal was opened. Archive worktrees you no longer use in Orca, or set terminal.open` }; return { ok: false, why: "Orca has no worktree whose root is this project's root, so no terminal was opened. Open this project in Orca (add it as a repository or worktree), then start the peer again, or set terminal.open" }; } /** #269: a new Orca terminal running `command` (a complete, already quoted command line); the terminal's handle. */ export async function openStartTerminal(worktreeId: string, command: string, title: string, options?: CommandRunner | TerminalRecoveryOptions): Promise { const config = normalizeOptions(options); const selector = worktreeId.startsWith("id:") ? worktreeId : `id:${worktreeId}`; const handle = nestedString(terminalObject(await run(config.runner, ["terminal", "create", "--worktree", selector, "--command", command, "--title", title, "--json"])), ["handle"]); if (!handle) throw new Error("Orca create returned no terminal handle"); return handle; } const RECORD_FILE = "terminal-recovery.json"; export function recordPath(stateDir: string): string { return join(stateDir, RECORD_FILE); } /** Resolve declared terminal roots without treating a launch candidate as daemon ownership proof. */ function executionRoot(peer: string, projectRoot: string, captured?: string): string { const builtin = definitionOf(peer); if (builtin?.session.launchRecord) return projectRoot; const { instances: declarations, roles, catalog } = readInstanceRoleConfig(projectRoot); const definition = catalog.definitionOf(peer, declarations); if (!definition?.session.launchRecord) throw new Error(`${peer}: no managed terminal recovery adapter`); if (!declarations?.[peer] || definition.transport !== "codex-appserver" && definition.transport !== "claude-channel") throw new Error(`${peer}: extra instance has no managed terminal support`); const expected = resolveInstanceExecutionCwd(projectRoot, peer, declarations, effectiveInstanceRoles(peer, declarations, roles, catalog), catalog); if (captured !== undefined && captured !== expected) throw new Error(`${peer}: declared execution worktree changed; manual recovery required`); return expected; } function savedTerminalRoot(binding: Pick): string { const expected = executionRoot(binding.peer, binding.projectRoot, binding.executionCwd ?? binding.projectRoot); if (definitionOf(binding.peer)) return binding.projectRoot; const root = binding.terminalRoot ?? binding.projectRoot; if (root !== binding.projectRoot && root !== expected) throw new Error(`${binding.peer}: recorded Orca grouping root is not authorized`); return root; } function validRecord(item: unknown): item is RecordedTerminalLaunch { const row = object(item); return typeof row.peer === "string" && typeof row.projectRoot === "string" && (row.executionCwd === undefined || typeof row.executionCwd === "string") && (row.terminalRoot === undefined || typeof row.terminalRoot === "string") && typeof row.instanceId === "string" && typeof row.handle === "string" && typeof row.incarnationId === "string" && typeof row.worktreeId === "string" && typeof row.launcherPid === "number" && typeof row.launcherSignature === "string" && row.launcherSignature.length > 0 && typeof row.launchId === "string" && row.launchId.length > 0; } /** * #215: "unreadable" (a corrupt or unreadable file) says nothing about launchers, so it must never read as "none". * #228: a row that fails validation is kept apart (`invalid`), never dropped: whatever it would answer is unknown, and * `all` is the file as read, so a writer puts every such row back unchanged. */ type LaunchRecords = { rows: RecordedTerminalLaunch[]; invalid: unknown[]; all: unknown[] }; function launchRecords(stateDir: string): LaunchRecords | "unreadable" { const none = { rows: [], invalid: [], all: [] }; if (!stateDir || !existsSync(recordPath(stateDir))) return none; try { const value: unknown = JSON.parse(readFileSync(recordPath(stateDir), "utf8")); if (!Array.isArray(value)) return "unreadable"; return { rows: value.filter(validRecord), invalid: value.filter((item) => !validRecord(item)), all: value }; } catch (error) { return (error as NodeJS.ErrnoException).code === "ENOENT" ? none : "unreadable"; } } /** * #228: whether a row that cannot be evaluated may answer a question about this peer, project and instance: it does * unless one of its fields is a readable string that names another one (a row for another peer or an older instance). */ function concerns(raw: unknown, query: { peer?: string; projectRoot: string; instanceId: string }): boolean { const row = object(raw); const other = (value: unknown, wanted?: string) => wanted !== undefined && typeof value === "string" && value !== wanted; return !other(row.peer, query.peer) && !other(row.projectRoot, query.projectRoot) && !other(row.instanceId, query.instanceId); } function writeLaunchRecords(stateDir: string, rows: unknown[]): void { mkdirSync(stateDir, { recursive: true }); atomicPrivateJSON(recordPath(stateDir), rows); // temp + rename: a reader never sees half a file } /** * #215: live when the recorded process signature matches; gone when the pid no longer exists (ESRCH) or another * process holds it now; unknown when the pid exists but its identity cannot be read. Unknown is never gone. */ export type LauncherState = "live" | "gone" | "unknown"; async function launcherState(row: RecordedTerminalLaunch, identity: ProcessIdentity, legacy: ProcessIdentity): Promise { let current: string | undefined; try { current = await identity(row.launcherPid) || undefined; } catch { /* unreadable: decided by the pid probe */ } // #228: a launcher recorded by 0.12.12 or older hashed `ps` in its own TZ and locale (#177 pinned it in 0.12.13). Read // the same unpinned way in this reader's environment, a match is that launcher; anything else stays gone (pid reuse). if (current && current !== row.launcherSignature) { let old: string | undefined; try { old = await legacy(row.launcherPid) || undefined; } catch { /* no legacy reading: the pinned one decides */ } if (old === row.launcherSignature) return "live"; } return processLiveness(row.launcherPid, row.launcherSignature, () => current); } /** The launcher signature as releases up to 0.12.12 computed it: `ps` in the caller's own TZ and locale, unpinned. */ function unpinnedProcessIdentity(pid: number): string | undefined { try { const result = Bun.spawnSync(["ps", "-p", String(pid), "-o", "lstart=,comm="], { stdout: "pipe", stderr: "pipe" }); const text = result.exitCode === 0 ? result.stdout.toString().trim() : ""; return text ? new Bun.CryptoHasher("sha256").update(text).digest("hex") : undefined; } catch { return undefined; } } /** * This instance's launch records whose launcher is live, those whose launcher cannot be identified (never gone), and * the rows that cannot be evaluated and may be this project's and instance's (#228: unknown for their peer). */ async function recordsByState(records: LaunchRecords, projectRoot: string, instanceId: string, identity: ProcessIdentity, legacy: ProcessIdentity): Promise<{ live: RecordedTerminalLaunch[]; unknown: RecordedTerminalLaunch[]; invalid: unknown[] }> { if (!instanceId) return { live: [], unknown: [], invalid: [] }; const candidates = records.rows.filter((item) => item.projectRoot === projectRoot && item.instanceId === instanceId); const states = await Promise.all(candidates.map((item) => launcherState(item, identity, legacy))); return { live: candidates.filter((_, i) => states[i] === "live"), unknown: candidates.filter((_, i) => states[i] === "unknown"), invalid: records.invalid.filter((raw) => concerns(raw, { projectRoot, instanceId })) }; } /** #215: the launcher recorded for `peer` on this instance (one row per peer and instance) and its state; managed means live. */ export async function launcherOf(peer: TerminalPeer, projectRoot: string, options?: TerminalRecoveryOptions): Promise<{ record?: RecordedTerminalLaunch; state: LauncherState; invalidRow?: true } | undefined> { const config = normalizeOptions(options); if (!config.stateDir || !config.instanceId) return undefined; const records = launchRecords(config.stateDir); if (records === "unreadable") return { state: "unknown" }; // #228: a row that cannot be evaluated and may be this launcher's is unknown, never "no launcher". if (records.invalid.some((raw) => concerns(raw, { peer, projectRoot, instanceId: config.instanceId }))) return { state: "unknown", invalidRow: true }; const record = records.rows.find((row) => row.peer === peer && row.projectRoot === projectRoot && row.instanceId === config.instanceId); return record ? { record, state: await launcherState(record, config.processIdentity, config.legacyIdentity) } : undefined; } /** * Capture the Orca terminal handed to an ahub launcher. This is the authenticated * identity source for legacy Orca payloads that omit agent/session metadata. */ export async function prepareTerminalLaunch(peer: TerminalPeer, projectRoot: string, stateDir: string, instanceId: string, options?: CommandRunner | TerminalRecoveryOptions): Promise { const config = normalizeOptions(options); const handle = process.env.ORCA_TERMINAL_HANDLE; const worktreeIdFromEnv = process.env.ORCA_WORKTREE_ID; if (!handle || !worktreeIdFromEnv) return undefined; if (!definitionOf(peer) && !config.executionCwd) throw new Error(`${peer}: recording an extra terminal requires its authenticated startup execution root`); const expectedRoot = executionRoot(peer, projectRoot, config.executionCwd || undefined); const value = await run(config.runner, ["terminal", "show", "--terminal", handle, "--json"]); const terminal = terminalObject(value); const actualRoot = nestedString(terminal, ["worktreePath", "projectRoot"]); const actualHandle = nestedString(terminal, ["handle"]); const actualWorktree = nestedString(terminal, ["worktreeId"]); const incarnationId = nestedString(terminal, ["incarnationId"]); if (actualHandle !== handle || !actualRoot || !(rootMatches(actualRoot, projectRoot) || !definitionOf(peer) && rootMatches(actualRoot, expectedRoot)) || actualWorktree !== worktreeIdFromEnv || !incarnationId) { throw new OrcaCommandError(blocker("project-root-mismatch", "Orca launch terminal failed canonical root/worktree readback", peer, handle)); } const launcherSignature = await config.processIdentity(process.pid); if (!launcherSignature) throw new OrcaCommandError(blocker("command-error", "cannot prove launcher process identity; refusing to record terminal", peer, handle)); const launchId = randomUUID(); process.env.AGENTHUB_LAUNCH_ID = launchId; process.env.AGENTHUB_INSTANCE_ID = instanceId; const row: RecordedTerminalLaunch = { peer, projectRoot, ...(!definitionOf(peer) ? { executionCwd: expectedRoot, terminalRoot: actualRoot } : {}), stateDir, instanceId, launcherPid: process.pid, launcherSignature, launchId, handle, incarnationId, worktreeId: actualWorktree, env: allowedEnv({ env: process.env }) }; return row; } /** Decode a console candidate against this daemon, never against paths supplied by that candidate. */ export function terminalLaunchCandidate(value: unknown, projectRoot: string, stateDir: string, instanceId: string): RecordedTerminalLaunch | undefined { if (!validRecord(value) || JSON.stringify(value).length > 32 * 1024 || value.projectRoot !== projectRoot || value.stateDir !== stateDir || value.instanceId !== instanceId || !Number.isSafeInteger(value.launcherPid) || value.launcherPid <= 0 || value.launchId.length > 128 || value.launcherSignature.length > 256) return undefined; try { const expected = executionRoot(value.peer, projectRoot, value.executionCwd); if (value.executionCwd !== undefined && value.executionCwd !== expected || value.terminalRoot !== undefined && value.terminalRoot !== projectRoot && value.terminalRoot !== expected) return undefined; return { peer: value.peer, projectRoot, stateDir, instanceId, launcherPid: value.launcherPid, launcherSignature: value.launcherSignature, launchId: value.launchId, handle: value.handle, incarnationId: value.incarnationId, worktreeId: value.worktreeId, ...(value.executionCwd ? { executionCwd: value.executionCwd } : {}), ...(value.terminalRoot ? { terminalRoot: value.terminalRoot } : {}), env: allowedEnv({ env: object(value.env) }) }; } catch { return undefined; } } /** Old daemons may launch the TUI, but cannot turn a pre-attach candidate into recovery authority. */ export async function registerTerminalLaunch(client: Pick, row: RecordedTerminalLaunch, operationId?: string): Promise { if (!client.features.includes("terminal_owner")) { console.error("terminal launcher is unrecorded; upgrade the running hub for managed terminal recovery"); return; } const result = await client.request({ t: "terminal_launch", launch: row, ...(operationId ? { operationId } : {}) }); if (result.ok !== true) throw new Error("terminal launch registration failed; inspect ahub status before launching again"); } /** Capture alone is not ownership: a refused native child must leave the live row untouched. */ export async function recordTerminalLaunch(peer: TerminalPeer, projectRoot: string, stateDir: string, instanceId: string, options?: CommandRunner | TerminalRecoveryOptions, isCurrentOwner?: (row: RecordedTerminalLaunch) => boolean): Promise { const row = await prepareTerminalLaunch(peer, projectRoot, stateDir, instanceId, options); if (!row || !isCurrentOwner) return undefined; return await publishTerminalLaunch(stateDir, row, () => isCurrentOwner(row), options) ? row : undefined; } /** Only the daemon's current native-owner proof may publish a captured candidate. No await after its final fence. */ export async function publishTerminalLaunch(stateDir: string, row: RecordedTerminalLaunch, isCurrent: () => boolean, options?: CommandRunner | TerminalRecoveryOptions): Promise { const config = normalizeOptions(options); if (!isCurrent() || await launcherState(row, config.processIdentity, config.legacyIdentity) !== "live") return false; const terminal = terminalObject(await run(config.runner, ["terminal", "show", "--terminal", row.handle, "--json"])); const expectedRoot = executionRoot(row.peer, row.projectRoot, row.executionCwd); if (nestedString(terminal, ["handle"]) !== row.handle || nestedString(terminal, ["incarnationId"]) !== row.incarnationId || nestedString(terminal, ["worktreeId"]) !== row.worktreeId || nestedString(terminal, ["worktreePath", "projectRoot"]) !== (row.terminalRoot ?? expectedRoot)) return false; if (await launcherState(row, config.processIdentity, config.legacyIdentity) !== "live" || !terminalLaunchCandidate(row, row.projectRoot, stateDir, row.instanceId) || !isCurrent()) return false; const existing = launchRecords(stateDir); // #215: rewriting an unreadable file would replace every other launcher's record with this one, and recovery would // then read those launchers as gone. if (existing === "unreadable") { throw new OrcaCommandError(blocker("command-error", `${recordPath(stateDir)} cannot be read, so recording this launch would erase every other launcher's record; next action: inspect that file and move it aside (recovery then treats sessions it recorded as unmanaged), then launch again`, row.peer, row.handle)); } // #228: every row that cannot be evaluated goes back unchanged; only this peer's valid row for this instance is replaced. const rows = existing.all.filter((item) => !(validRecord(item) && item.peer === row.peer && item.projectRoot === row.projectRoot && item.instanceId === row.instanceId)); rows.push(row); writeLaunchRecords(stateDir, rows); return true; } function rootMatches(actual: unknown, expected: string): boolean { return typeof actual === "string" && actual === expected; } function object(value: unknown): Record { return value && typeof value === "object" ? (value as Record) : {}; } function responseResult(value: unknown): Record { const root = object(value); return object(root.result ?? root); } function terminalObject(value: unknown): Record { const root = responseResult(value); return object(root.terminal ?? root); } function nestedString(source: Record, names: string[]): string | undefined { for (const name of names) { const direct = source[name]; if (typeof direct === "string" && direct.length > 0) return direct; } return undefined; } function sessionFrom(terminal: Record): string | undefined { const wait = object(terminal.agentWait); const session = object(terminal.session); return nestedString(terminal, ["sessionId", "agentSessionId", "resumeSessionId"]) ?? nestedString(wait, ["sessionId", "agentSessionId", "resumeSessionId", "session", "agentSession"]) ?? nestedString(session, ["id", "sessionId"]); } function identityFrom(terminal: Record, instances: KindMap | undefined, catalog: ProjectAdapterCatalog): TerminalPeer | undefined { const wait = object(terminal.agentWait); const session = object(terminal.session); const candidates = [terminal.agentIdentity, terminal.agent, wait.agentIdentity, wait.agent, session.agentIdentity, session.agent]; for (const candidate of candidates) { if (typeof candidate === "string" && catalog.definitionOf(candidate, instances)?.session.launchRecord) return candidate as TerminalPeer; } return undefined; } function allowedEnv(terminal: Record): Partial> { const env: Partial> = {}; const candidates = [terminal.env, terminal.environment, terminal.launchEnv, object(terminal.launch).env]; for (const candidate of candidates) { const source = object(candidate); for (const name of ALLOWED_ENV) { if (env[name] === undefined && typeof source[name] === "string") env[name] = source[name] as string; } } return env; } function listTerminals(value: unknown): Record[] { const root = responseResult(value); const list = root.terminals ?? root.items; return Array.isArray(list) ? list.map(object) : []; } function requireAbsoluteEntrypoint(value: string): string { if (!isAbsolute(value)) throw new Error(`package entrypoint must be absolute: ${value}`); return value; } function launchFor(peer: TerminalPeer, projectRoot: string, sessionId: string, options: Required, source: Record, recorded?: RecordedTerminalLaunch, ref?: SessionRef): LaunchMetadata { const packageEntrypoint = requireAbsoluteEntrypoint(options.packageEntrypoint); const env = { ...allowedEnv(source), ...(recorded?.env ?? {}) }; const prefix = ALLOWED_ENV.filter((name) => env[name] !== undefined).map((name) => `${name}=${shellQuote(env[name]!)}`); const launch: LaunchMetadata = { packageEntrypoint, argv: ["bun", packageEntrypoint, "--project", projectRoot], env, command: "" }; launch.command = [...prefix, ...launch.argv.map(shellQuote)].join(" "); // Identity and environment were independently verified before this pure two-phase launch construction. const binding: TerminalBinding = { peer, projectRoot, sessionId, handle: nestedString(source, ["handle"])!, incarnationId: nestedString(source, ["incarnationId"])!, worktreeId: nestedString(source, ["worktreeId"])!, ...(ref?.sessionFile ? { sessionFile: ref.sessionFile } : {}), ...(ref?.backend ? { backend: ref.backend } : {}), ...(ref?.model ? { model: ref.model } : {}), launch, launchMetadata: launch }; const scope = definitionOf(peer) ? undefined : readInstanceConfig(projectRoot); const adapter = definitionOf(peer) ?? scope!.catalog.definitionOf(peer, scope!.instances); const nativeTail = adapter?.session.resumeArgv?.(binding, false); const tail = nativeTail && adapter ? [nativeTail[0]!, ...(peer !== adapter.kind ? ["--as", peer] : []), ...nativeTail.slice(1)] : undefined; if (!tail) throw new Error(`${peer}: no recorded terminal resume adapter`); const argv = [...launch.argv, ...tail]; const command = [...prefix, ...argv.map(shellQuote)].join(" "); return { packageEntrypoint, command, argv, env }; } function blocker(code: RecoveryBlocker["code"], message: string, peer?: TerminalPeer, handle?: string): RecoveryBlocker { const nextAction = code === "missing-session" ? "reconnect the original native session and rerun recovery" : code === "ownership-unknown" ? "confirm the terminal owner in Orca, then resume recovery" : code === "ambiguous-terminal" ? "close or identify the duplicate terminal, then resume recovery" : code === "ambiguous-create" ? "inspect the existing terminal and attach the original session before resuming" : code === "terminal-orphaned" ? `reattach the pane with orca terminal switch --terminal ${shellQuote(handle!)}; then refresh in ahub upgrade ([r] on the plan, [s] on an open operation), or rerun it` : code === "terminal-unready" ? "finish or cancel the active terminal turn, then resume recovery" : code === "launch-failed" ? "fix the launch refusal, then resume this recovery operation" : code === "launcher-exited" ? "the session was not restored; the coordinator's error names the choices" : code === "terminal-gone" ? "the terminal was closed; inspect the project's terminals in Orca before resuming recovery" : "inspect the named terminal and resume recovery after the identity is verified"; return { code, message, ...(peer ? { peer } : {}), ...(handle ? { handle, terminalReference: handle } : {}), nextAction }; } /** #1246: how long a switched pane is re-read before it still counts as orphaned. Orca's `terminal show` can lag a switch by a moment. */ export const REATTACH_BOUND_MS = 5_000; const REATTACH_POLL_MS = 250; /** * #1246: the one mutation the upgrade menu offers for an orphaned-but-connected pane: `orca terminal switch` for exactly * this handle, after reading it again and finding the identity the plan verified (handle, incarnation, worktree, root) * still orphaned and connected. It then re-reads the pane until `orphaned` is false, at most `boundMs`. A pane that is * already not orphaned is `reattached` with no switch. A changed identity, a disconnected pane or any failed Orca call is * `unavailable` (nothing, or nothing more, was done); a pane still orphaned at the bound stays `still-orphaned`. */ export async function reattachOrphanedTerminal(terminal: OrphanedTerminal, options?: CommandRunner | TerminalRecoveryOptions, boundMs = REATTACH_BOUND_MS): Promise<"reattached" | "still-orphaned" | "unavailable"> { const config = normalizeOptions(options); const read = async (): Promise | undefined> => { const shown = terminalObject(await run(config.runner, ["terminal", "show", "--terminal", terminal.handle, "--json"])); const same = nestedString(shown, ["handle"]) === terminal.handle && nestedString(shown, ["incarnationId"]) === terminal.incarnationId && nestedString(shown, ["worktreeId"]) === terminal.worktreeId && rootMatches(shown.worktreePath ?? shown.projectRoot, terminal.root); return same ? shown : undefined; }; // The runner is also bounded by its caller; this race keeps a runner that ignores its timeout from holding the screen past the bound. const within = async (work: Promise, ms: number): Promise => { let timer: ReturnType | undefined; try { return await Promise.race([work, new Promise((_, reject) => { timer = setTimeout(() => reject(new Error("reattach bound exceeded")), ms); })]); } finally { if (timer) clearTimeout(timer); } }; try { const before = await within(read(), boundMs); if (!before) return "unavailable"; if (before.orphaned === false) return "reattached"; if (before.orphaned !== true || before.connected !== true) return "unavailable"; await within(run(config.runner, ["terminal", "switch", "--terminal", terminal.handle, "--json"]), boundMs); const deadline = Date.now() + boundMs; for (;;) { const shown = await within(read(), deadline - Date.now()); if (!shown) return "unavailable"; if (shown.orphaned === false) return "reattached"; if (Date.now() >= deadline) return "still-orphaned"; await Bun.sleep(Math.min(REATTACH_POLL_MS, deadline - Date.now())); } } catch { return "unavailable"; } } function verifyBindingData(actual: Record, binding: TerminalBinding): RecoveryBlocker | undefined { const handle = nestedString(actual, ["handle"]); const incarnation = nestedString(actual, ["incarnationId"]); const root = nestedString(actual, ["worktreePath", "projectRoot"]); const worktree = nestedString(actual, ["worktreeId"]); if (handle !== binding.handle || incarnation !== binding.incarnationId || worktree !== binding.worktreeId) return blocker("stale-terminal", "captured terminal identity changed; refusing to mutate it", binding.peer, binding.handle); let expectedRoot: string; try { expectedRoot = savedTerminalRoot(binding); } catch { return blocker("project-root-mismatch", "declared terminal execution root changed or is unavailable; refusing to mutate it", binding.peer, binding.handle); } if (!rootMatches(root, expectedRoot)) return blocker("project-root-mismatch", "terminal belongs to a different project root; refusing to mutate it", binding.peer, binding.handle); return undefined; } async function showBinding(binding: TerminalBinding, options: Required): Promise> { const value = await run(options.runner, ["terminal", "show", "--terminal", binding.handle, "--json"]); const actual = terminalObject(value); const issue = verifyBindingData(actual, binding); if (issue) throw new OrcaCommandError(issue); return actual; } /** * Judge only the saved terminal identity. The caller separately fences the peer's current/restarted launchers. * A failed read is unknown; only a typed stale handle plus a complete inventory can prove absence. */ export async function inspectSavedTerminal(binding: TerminalBinding, options?: CommandRunner | TerminalRecoveryOptions): Promise { const config = normalizeOptions(options); const unknown = (): SavedTerminalInspection => ({ state: "unknown", blocker: blocker("command-error", "saved terminal evidence is unavailable or inconsistent", binding.peer, binding.handle) }); const completeIdentity = (value: Record) => [nestedString(value, ["handle"]), nestedString(value, ["incarnationId"]), nestedString(value, ["worktreeId"]), nestedString(value, ["worktreePath", "projectRoot"])].every(Boolean); try { savedTerminalRoot(binding); const shown = terminalObject(await run(config.runner, ["terminal", "show", "--terminal", binding.handle, "--json"])); if (!completeIdentity(shown)) return unknown(); const issue = verifyBindingData(shown, binding); if (issue) return { state: "changed", blocker: issue }; if (shown.orphaned === true && shown.connected === true) return { state: "unknown", blocker: blocker("terminal-orphaned", "the saved terminal is orphaned but still connected", binding.peer, binding.handle) }; if (shown.orphaned === true) return { state: "orphaned", blocker: blocker("terminal-gone", "the saved terminal is orphaned", binding.peer, binding.handle) }; if (shown.connected === false) return unknown(); return { state: "present" }; } catch (error) { if (!(error instanceof OrcaCommandError) || error.blocker.code !== "terminal-gone") return unknown(); } try { const result = responseResult(await run(config.runner, ["terminal", "list", "--json"])); const rows = result.terminals ?? result.items; if (result.truncated === true || !Array.isArray(rows)) return unknown(); const handles = new Set(), incarnations = new Set(); for (const raw of rows) { if (!raw || typeof raw !== "object" || Array.isArray(raw)) return unknown(); const row = raw as Record; if (!completeIdentity(row)) return unknown(); const handle = nestedString(row, ["handle"])!, incarnation = nestedString(row, ["incarnationId"])!; if (handles.has(handle) || incarnations.has(incarnation)) return unknown(); handles.add(handle); incarnations.add(incarnation); } const retained = (rows as Record[]).find(row => row.handle === binding.handle || row.incarnationId === binding.incarnationId); if (retained) { const issue = verifyBindingData(retained, binding); return issue ? { state: "changed", blocker: issue } : unknown(); } return { state: "missing", blocker: blocker("terminal-gone", "the saved terminal handle and incarnation are absent from the complete inventory", binding.peer, binding.handle) }; } catch { return unknown(); } } /** * Read Orca's authoritative terminal inventory and bind only exact agent/session identities. * Titles, previews, pty ids and process names are deliberately never used as identity. */ export async function inspectTerminals(projectRoot: string, sessions: Partial>, options?: CommandRunner | TerminalRecoveryOptions): Promise { const config = normalizeOptions(options); const blockers: RecoveryBlocker[] = []; const bindings: TerminalBinding[] = []; const orphaned: OrphanedTerminal[] = []; const byPeer: Partial> = {}; const requested = (Object.entries(sessions) as [TerminalPeer, string | SessionRef | undefined][]).map(([peer, value]) => [peer, typeof value === "string" ? { sessionId: value } : value] as const).filter((entry): entry is [TerminalPeer, SessionRef] => !!entry[1]?.sessionId); if (!requested.length) return { bindings, byPeer, blockers, manualRequired: false }; const scope = requested.some(([peer]) => definitionOf(peer) === undefined) ? readInstanceConfig(projectRoot) : { instances: undefined, catalog: createProjectAdapterCatalog() }; const { instances, catalog } = scope; // #215: without the records a terminal could be bound from Orca metadata alone, losing the launch's captured // CODEX_HOME or CLAUDE_CONFIG_DIR: an unreadable file blocks the binding, never reads as "no records". const rows = launchRecords(config.stateDir); if (rows === "unreadable") return { bindings, byPeer, blockers: [blocker("command-error", `${recordPath(config.stateDir)} cannot be read, so no terminal can be bound to its launch; inspect or move it aside, then plan or resume again`)], manualRequired: true }; const { live: records, unknown, invalid } = await recordsByState(rows, projectRoot, config.instanceId, config.processIdentity, config.legacyIdentity); let listed: Record[]; try { listed = listTerminals(await run(config.runner, ["terminal", "list", "--json"])); } catch (error) { const commandBlocker = error instanceof OrcaCommandError ? error.blocker : blocker("command-error", String(error)); return { bindings, byPeer, blockers: [commandBlocker], manualRequired: true }; } for (const [peer, ref] of requested) { const sessionId = ref.sessionId; const adapter = catalog.definitionOf(peer, instances), extra = definitionOf(peer) === undefined; if (!adapter?.session.launchRecord || extra && adapter.transport !== "codex-appserver" && adapter.transport !== "claude-channel") { blockers.push(blocker("ownership-unknown", `${peer}: no declared managed-terminal recovery adapter`, peer)); continue; } const ownRecord = records.find(item => item.peer === peer); let expectedRoot: string, expectedTerminalRoot: string; try { expectedRoot = executionRoot(peer, projectRoot, ownRecord?.executionCwd ?? projectRoot); expectedTerminalRoot = savedTerminalRoot({ peer, projectRoot, executionCwd: ownRecord?.executionCwd, terminalRoot: ownRecord?.terminalRoot }); } catch { blockers.push(blocker("ownership-unknown", `${peer}: declared execution worktree changed or is unverified`, peer)); continue; } // #215: a launcher whose identity cannot be read may be this peer's: binding from Orca metadata would lose its launch. const unread = unknown.find((item) => item.peer === peer); if (unread) { blockers.push(blocker("ownership-unknown", `the ${peer} launcher recorded for terminal ${unread.handle} (pid ${unread.launcherPid}) cannot be identified, so no terminal can be bound to its launch; wait until it exits or end it, then plan or resume again`, peer, unread.handle)); continue; } if (invalid.some((raw) => concerns(raw, { peer, projectRoot, instanceId: config.instanceId }))) { blockers.push(blocker("ownership-unknown", `${recordPath(config.stateDir)} holds a launch record that cannot be evaluated and may be this ${peer} launcher's, so no terminal can be bound to its launch; next action: inspect that row and fix it, or end that launcher and remove its row, then plan or resume again`, peer)); continue; } const candidates = listed.filter((terminal) => rootMatches(terminal.worktreePath ?? terminal.projectRoot, expectedTerminalRoot)); const peerCandidates: Record[] = []; for (const listedTerminal of candidates) { const handle = nestedString(listedTerminal, ["handle"]); if (!handle) continue; let terminal: Record; try { terminal = terminalObject(await run(config.runner, ["terminal", "show", "--terminal", handle, "--json"])); } catch (error) { blockers.push(error instanceof OrcaCommandError ? { ...error.blocker, peer, handle } : blocker("command-error", String(error), peer, handle)); continue; } // A show readback is required; list can be stale between recovery steps. if (!rootMatches(terminal.worktreePath ?? terminal.projectRoot, expectedTerminalRoot)) continue; const identity = identityFrom(terminal, instances, catalog); const terminalSession = sessionFrom(terminal); const recorded = records.find((item) => item.peer === peer && item.handle === handle && item.worktreeId === terminal.worktreeId && item.incarnationId === terminal.incarnationId); // A recorded launcher proves ownership; the daemon's supplied session id is the // authoritative session id when Orca omits it from terminal metadata. if ((!extra && identity === peer && terminalSession === sessionId) || (recorded !== undefined && (identity === undefined || identity === peer || extra && identity === adapter.kind) && (terminalSession === undefined || terminalSession === sessionId))) peerCandidates.push(terminal); } if (!peerCandidates.length) { const ownershipUnknown = candidates.some((terminal) => identityFrom(terminal, instances, catalog) === undefined && !records.some((item) => item.handle === terminal.handle)); blockers.push(ownershipUnknown ? blocker("ownership-unknown", `cannot prove ${peer} terminal ownership from Orca metadata`, peer) : blocker("missing-terminal", `no ${peer} terminal with session ${sessionId} in ${projectRoot}`, peer)); continue; } if (peerCandidates.length > 1) { blockers.push(blocker("ambiguous-terminal", `multiple ${peer} terminals match session ${sessionId}; refusing to choose`, peer)); continue; } const terminal = peerCandidates[0]!; const handle = nestedString(terminal, ["handle"]); const incarnationId = nestedString(terminal, ["incarnationId"]); const worktreeId = nestedString(terminal, ["worktreeId"]); if (!handle || !incarnationId || !worktreeId) { blockers.push(blocker("stale-terminal", `terminal metadata lacks a stable handle, incarnation or worktree id`, peer, handle)); continue; } if (terminal.orphaned === true && terminal.connected === true) { blockers.push(blocker("terminal-orphaned", `the ${peer} terminal ${handle} in ${projectRoot} is orphaned but still connected`, peer, handle)); orphaned.push({ peer, handle, incarnationId, worktreeId, root: expectedTerminalRoot }); continue; } if (terminal.orphaned === true || terminal.connected === false) { blockers.push(blocker("terminal-unready", `terminal ${handle} is orphaned or disconnected`, peer, handle)); continue; } const recorded = records.find((item) => item.peer === peer && item.handle === handle && item.worktreeId === terminal.worktreeId && item.incarnationId === terminal.incarnationId); // Orca observation supplies file identity; launch arguments are not observed native session-file evidence. const { args: _launchArgs, ...observedTerminal } = terminal; const sessionFile = catalog.definitionOf(peer, instances)?.session.crashIdentity?.(observedTerminal).sessionFile; const launch = launchFor(peer, projectRoot, sessionId, config, terminal, recorded, { ...ref, ...(sessionFile ? { sessionFile } : {}) }); const binding: TerminalBinding = { peer, handle, incarnationId, worktreeId, projectRoot, ...(extra ? { executionCwd: expectedRoot, terminalRoot: expectedTerminalRoot } : {}), sessionId, ...(sessionFile ? { sessionFile } : {}), ...(ref.backend ? { backend: ref.backend } : {}), ...(ref.model ? { model: ref.model } : {}), launch, launchMetadata: launch }; bindings.push(binding); byPeer[peer] = binding; } return { bindings, byPeer, blockers, manualRequired: blockers.length > 0, ...(orphaned.length ? { orphaned } : {}) }; } /** * One bounded Orca wait. Orca 1.4.223 and, rechecked read-only, 1.4.245 (docs/verification/2026-11-02-orca-1.4.245-cli-contract.md) answer a wait that timed out with exit 1 and `{"ok":false,"error":{"code":"timeout"}}`: * that is "not satisfied", not a failure. Any other failure still throws. 1.4.250 also answers ok with `satisfied: false` * and a `blockedReason` (seen: `agent-update-prompt`) when the TUI waits on a prompt; the reason is passed on (#1233). */ async function waitSatisfied(runner: CommandRunner, handle: string, timeoutMs: number): Promise<{ satisfied: boolean; blockedReason?: string }> { const argv = ["terminal", "wait", "--terminal", handle, "--for", "tui-idle", "--timeout-ms", String(timeoutMs), "--json"]; const result = await runner(argv); if (commandStatus(result) !== 0 && errorCode(result) === "timeout") return { satisfied: false }; const root = responseResult(await run(async () => result, argv)); if (root.satisfied === true || object(root.wait).satisfied === true) return { satisfied: true }; const reason = root.blockedReason ?? object(root.wait).blockedReason; return typeof reason === "string" ? { satisfied: false, blockedReason: reason.slice(0, 100) } : { satisfied: false }; } /** Wait only on the captured terminal and only for Orca's supported TUI-idle condition. */ export async function waitForIdle(binding: TerminalBinding, timeoutMs: number, options?: CommandRunner | TerminalRecoveryOptions): Promise { const config = normalizeOptions(options); const timeout = Number.isFinite(timeoutMs) && timeoutMs >= 0 ? Math.min(Math.floor(timeoutMs), MAX_WAIT_MS) : 0; try { await showBinding(binding, config); const { satisfied, blockedReason } = await waitSatisfied(config.runner, binding.handle, timeout); const blockers = satisfied ? [] : [blocker("terminal-unready", `terminal ${binding.handle} did not become idle before the bounded wait${blockedReason ? ` (Orca: blocked by ${blockedReason})` : ""}`, binding.peer, binding.handle)]; return { satisfied, manualRequired: !satisfied, blockers }; } catch (error) { const item = error instanceof OrcaCommandError ? error.blocker : blocker("command-error", String(error), binding.peer, binding.handle); return { satisfied: false, manualRequired: true, blockers: [item] }; } } function restoration(peer: TerminalPeer, oldHandle: string, blockers: RecoveryBlocker[]): RestorationResult { return { status: "manual-required", manualRequired: true, peer, oldHandle, blockers }; } function closeFailure(binding: TerminalBinding, blockers: RecoveryBlocker[]): TerminalCloseResult { return { closed: false, manualRequired: true, binding, blockers }; } /** Quiesce and close exactly the captured terminal. This is a separately journalable effect. */ export async function closeTerminal(binding: TerminalBinding, timeoutMs = 600_000, options?: CommandRunner | TerminalRecoveryOptions): Promise { const config = normalizeOptions(options); // The coordinator passes zero after its explicit quiesce/wait step. The show // readback below still proves the captured identity before the close mutation. const idle = timeoutMs === 0 ? { satisfied: true, manualRequired: false, blockers: [] as RecoveryBlocker[] } : await waitForIdle(binding, timeoutMs, config); if (!idle.satisfied) return closeFailure(binding, idle.blockers); try { await showBinding(binding, config); await run(config.runner, ["terminal", "close", "--terminal", binding.handle, "--json"]); const deadline = Date.now() + 5000; do { const afterClose = listTerminals(await run(config.runner, ["terminal", "list", "--json"])); if (!afterClose.some((terminal) => terminal.handle === binding.handle || terminal.incarnationId === binding.incarnationId)) return { closed: true, manualRequired: false, binding, blockers: [] }; await Bun.sleep(100); } while (Date.now() < deadline); return closeFailure(binding, [blocker("ambiguous-create", `close of terminal ${binding.handle} was not confirmed`, binding.peer, binding.handle)]); } catch (error) { return closeFailure(binding, [error instanceof OrcaCommandError ? error.blocker : blocker("command-error", String(error), binding.peer, binding.handle)]); } } /** * Create a replacement in the captured worktree, then prove TUI readiness and session mapping. `anySession` maps a * fresh session the operator chose (#215): the terminal must still be this launch's, under any new session id. */ export async function createTerminal(binding: TerminalBinding, options?: CommandRunner | TerminalRecoveryOptions, timeoutMs = 600_000, anySession = false): Promise { const config = normalizeOptions(options); let made: string | undefined; // a later failure must still report the terminal it created try { savedTerminalRoot(binding); const worktreeSelector = binding.worktreeId.startsWith("id:") ? binding.worktreeId : `id:${binding.worktreeId}`; // The coordinator journals a pending creation before this call and reconciles // it on resume. Other agents in the worktree do not imply a prior create. const value = await run(config.runner, ["terminal", "create", "--worktree", worktreeSelector, "--command", binding.launch.command, "--title", `${binding.peer} recovery`, "--json"]); let created = terminalObject(value); const createdHandle = nestedString(created, ["handle"]); made = createdHandle; if (!createdHandle) return { created: false, ready: false, manualRequired: true, blockers: [blocker("ambiguous-create", "Orca create returned no terminal handle", binding.peer)] }; const incarnationId = nestedString(created, ["incarnationId"]); const worktreeId = nestedString(created, ["worktreeId"]) ?? binding.worktreeId; if (!incarnationId) { const listed = listTerminals(await run(config.runner, ["terminal", "list", "--json"])).filter((terminal) => terminal.handle === createdHandle); if (listed.length !== 1) return { created: false, ready: false, manualRequired: true, blockers: [blocker("ambiguous-create", `created terminal ${createdHandle} lacks stable identity`, binding.peer, createdHandle)] }; created = listed[0]!; } let replacement: TerminalBinding = { ...binding, handle: createdHandle, incarnationId: nestedString(created, ["incarnationId"])!, worktreeId, launch: binding.launch, launchMetadata: binding.launch }; // The launch record `ahub ` writes in the new terminal: live, gone (all recorded launchers), or neither. const launches = async () => { const rows = launchRecords(config.stateDir); if (rows === "unreadable") return { live: undefined, gone: false, mayRun: true }; // unknown, never gone // #228: a row that cannot be evaluated and may be this launch's is unknown too. if (rows.invalid.some((raw) => concerns(raw, { peer: binding.peer, projectRoot: binding.projectRoot, instanceId: config.instanceId }))) return { live: undefined, gone: false, mayRun: true }; const possible = rows.rows.filter((item) => item.instanceId === config.instanceId && item.peer === binding.peer && item.projectRoot === binding.projectRoot && item.handle === createdHandle && item.worktreeId === replacement.worktreeId && item.incarnationId === replacement.incarnationId); const states = await Promise.all(possible.map(async (item) => ({ item, state: await launcherState(item, config.processIdentity, config.legacyIdentity) }))); return { live: states.find((entry) => entry.state === "live")?.item, gone: states.length > 0 && states.every((entry) => entry.state === "gone"), mayRun: states.some((entry) => entry.state !== "gone") }; }; // #215: Orca types the command into a login shell that outlives it, so the terminal never exits with the launcher. // Readiness is awaited in slices, and between them the launcher's own record says whether it still runs: one that // recorded itself and is gone failed. A stale handle is gone only when Orca no longer lists the terminal's // incarnation and no recorded launcher may still run. One that never recorded itself is left to the readiness // bound and to the coordinator's reconciliation of its pending receipt. const exited = (why: string) => ({ created: true, ready: false, manualRequired: true, blockers: [blocker("launcher-exited", `the ${binding.peer} restoration launcher in terminal ${createdHandle} ${why} before its TUI was ready`, binding.peer, createdHandle)] }); const failed = () => { const failure = config.launchFailure(); return failure ? { created: true, ready: false, manualRequired: true, blockers: [{ ...blocker("launch-failed", `restoration command exited ${failure.exitCode}: ${failure.firstLine}; fix the cause, then resume this recovery operation`, binding.peer, createdHandle), failure }] } : undefined; }; const deadline = Date.now() + Math.min(timeoutMs, MAX_WAIT_MS); const slice = () => Math.max(1, Math.min(EXIT_SLICE_MS, deadline - Date.now())); // Orca refuses --timeout-ms 0 const earlyFailure = failed(); if (earlyFailure) return earlyFailure; let idle = await waitForIdle(replacement, slice(), config); for (;;) { const failure = failed(); if (failure) return failure; if (idle.blockers[0]?.code === "terminal-gone") { const launch = await launches(); if (launch.gone) return exited("exited"); if (launch.mayRun) break; const inventory = await run(config.runner, ["terminal", "list", "--json"]); // A truncated inventory cannot show that the terminal is no longer listed. const listed = responseResult(inventory).truncated === true || listTerminals(inventory).some((terminal) => terminal.incarnationId === replacement.incarnationId); if (!listed) return exited("lost its terminal"); break; } if (idle.satisfied || idle.blockers[0]?.code !== "terminal-unready") break; if ((await launches()).gone) return exited("exited"); if (Date.now() >= deadline) break; idle = await waitForIdle(replacement, slice(), config); } if (!idle.satisfied) return { created: true, ready: false, manualRequired: true, blockers: idle.blockers }; const same = (value: string | undefined) => anySession || value === binding.sessionId; let session: string | undefined; // An idle terminal may be the login shell the launcher returned to, or a TUI that has not yet recorded its // launch or been identified by Orca (#599): poll until it maps, contradicts, or the deadline passes. for (;;) { const failure = failed(); if (failure) return failure; const launch = await launches(); if (launch.gone) return exited("exited"); const shown = await showBinding(replacement, config); const scope = definitionOf(binding.peer) ? { instances: undefined, catalog: createProjectAdapterCatalog() } : readInstanceConfig(binding.projectRoot); const identity = identityFrom(shown, scope.instances, scope.catalog); session = sessionFrom(shown); const recorded = launch.live; if ((identity === binding.peer && same(session)) || (recorded && (identity === undefined || identity === binding.peer) && (session === undefined || same(session)))) break; const contradicts = (identity !== undefined && identity !== binding.peer) || (session !== undefined && !same(session)); if (contradicts || Date.now() >= deadline) { return { created: true, ready: true, manualRequired: true, blockers: [blocker("ambiguous-create", `created terminal ${createdHandle} cannot be mapped to the original ${binding.peer} session`, binding.peer, createdHandle)] }; } await Bun.sleep(Math.max(1, Math.min(MAP_POLL_MS, deadline - Date.now()))); } if (anySession && session) replacement = { ...replacement, sessionId: session }; return { created: true, ready: true, manualRequired: false, binding: replacement, newBinding: replacement, blockers: [] }; } catch (error) { return { created: made !== undefined, ready: false, manualRequired: true, blockers: [error instanceof OrcaCommandError ? error.blocker : blocker("command-error", String(error), binding.peer, made ?? binding.handle)] }; } } /** * Close one verified terminal and recreate it in the same Orca worktree. Every mutation is * preceded by a show readback and no ambiguous close/create outcome is retried. */ export async function restoreTerminal(binding: TerminalBinding, timeoutMs = 600_000, options?: CommandRunner | TerminalRecoveryOptions): Promise { const closed = await closeTerminal(binding, timeoutMs, options); if (!closed.closed) return restoration(binding.peer, binding.handle, closed.blockers); const created = await createTerminal(binding, options, timeoutMs); if (!created.binding) return restoration(binding.peer, binding.handle, created.blockers); return { status: "restored", manualRequired: false, peer: binding.peer, oldHandle: binding.handle, newBinding: created.binding, blockers: [] }; }