import type { ModelOverrideSelection } from "./registry-types.ts"; import { isNativeModelToken } from "./model-token.ts"; import { buildPiLaunch } from "../pi/launch.ts"; import { randomUUID } from "node:crypto"; import { existsSync, mkdirSync } from "node:fs"; import { join, resolve } from "node:path"; import { spawn, type ChildProcess, type ChildProcessWithoutNullStreams } from "node:child_process"; import { renderDigest, remoteEnvelope, replyAudience, replyParent, type Envelope, type PeerId } from "../hub/envelope.ts"; import { BasePeer, type SessionTitleResult } from "../hub/peers.ts"; import type { DeliveryFailureCause } from "../hub/delivery-failure.ts"; import { peerChildEnv, stopOwnedProcess, trackGroup } from "../hub/child-process.ts"; import { assessVersion, COMPAT, type CompatVerdict } from "./compat.ts"; import { processLiveness, processSignature } from "../pi/process-signature.ts"; import { PiSessionBookmarkMismatch, validatePiSession } from "../pi/session.ts"; import { ApprovalWaitStop, toolResultFailed, type ApprovalProvenance } from "../local/tools.ts"; import { piToolStepCeiling, type PiToolStepCeiling } from "../pi/ceiling.ts"; import type { ExecutionBudgetDecision, ExecutionUnit } from "../hub/execution-budget.ts"; import { QuestionWaitDetached } from "../hub/question-detach.ts"; import type { StartForm } from "./registry-types.ts"; import { stateModelId } from "./pi-state-model.ts"; import type { ModelObservation } from "../hub/events.ts"; export interface PiModelDescriptor { id: string; name?: string; contextWindow?: number; maxTokens?: number; reasoning?: boolean; } export interface PiToolSchema { name: string; description?: string; parameters: Record; } export interface PiRelay { url: string; token: string; models: PiModelDescriptor[]; } export interface PiExit { cause: "process_exit" | "spawn_error" | "session_shutdown" | "owner_lost" | "owner_stopped"; code: number | null; signal: NodeJS.Signals | null; expected: boolean; started: boolean; turnActive: boolean; toolActive: boolean; lastToolName?: string; } export interface PiToolContext { userBash: boolean; isCurrent: () => boolean; onApproval: (provenance: ApprovalProvenance) => void; } export interface PiToolResult { text: string; exitCode: number | null; } class PiToolSettlementFailure extends Error {} class PiPromptNotStarted extends Error { constructor(readonly promptId: string) { super("Pi native session changed before prompt insertion; reverify its retained terminal before retrying"); } } class PiPromptUncertain extends Error {} export interface PiOptions { /** stateDir owns this native instance; hubStateDir retains the canonical daemon binding. */ hubStateDir?: string; cwd: string; stateDir: string; cmd?: string[]; mode: "headless" | "tui"; backend: "auto" | "dgx" | "mlx"; sessionFile?: string; sessionId?: string; model?: string; /** Host-only choice sampled once at the next turn/review boundary. */ getModelOverride?: () => ModelOverrideSelection; relay: PiRelay; executeTool: (name: string, args: unknown, toolCallId: string, sessionId?: string, signal?: AbortSignal, context?: PiToolContext) => Promise; tools: PiToolSchema[]; preamble?: string; /** Host-owned conditional instruction, sampled once per delivered turn. */ titlePreface?: () => string | undefined; selectModel?: (envs: Envelope[]) => Promise; maxSteps?: number; /** Atomic task/run admission immediately before provider requests or tool execution. */ admitBudget?: (envs: Envelope[], unit: ExecutionUnit) => Promise; /** Reported message usage as increments, before agent_settled releases the turn. */ onTokens?: (added: number) => void; /** Current-session prompt occupancy; unknown observations invalidate stale readings. */ onContext?: (value: unknown, sessionId: string) => void; /** `ceiling` is the validated, session/turn-bound tool-step ceiling signal (#179), present only when the trusted extension emitted one for this turn. */ onTurnFailure?: (envs: Envelope[], reason: string, ceiling?: PiToolStepCeiling, settledCeiling?: boolean) => Promise; /** Observation only: cancelled/stopped logical turns never request failure handoff. */ onTurnAborted?: (envs: Envelope[]) => void; /** Observation only: a real successful turn resets the host's continuation count. */ onTurnSuccess?: (envs: Envelope[]) => void; watchdogMs?: number; log?: (line: string) => void; /** Once per owner, after it is offline; a TUI owner may have unknown OS exit status. */ onExit?: (exit: PiExit) => void; onApprovalStop?: (reason: string) => void; /** How long stop() waits for a graceful TUI owner exit before verified teardown. Tests shrink this. */ stopGraceMs?: number; /** Host process-identity reader; never supplied by bridge events or peer config. */ signature?: typeof processSignature; } export interface PiTuiLaunch { cmd: string; args: string[]; env: NodeJS.ProcessEnv; } /** Only the host's parsed version verdict may cross the generic startup-error boundary. */ export class PiVersionRefusal extends Error { constructor(verdict: Extract) { super(verdict.reason); } } /** Bounded, non-blocking probe of the exact configured native command, including wrapper arguments. */ export function piVersionAsync(command: readonly string[], cwd: string, timeoutMs = 10_000): Promise { const [bin, ...prefix] = command; if (!bin) return Promise.resolve(assessVersion("pi", undefined)); return new Promise(resolve => { let proc: ChildProcess; try { proc = spawn(bin, [...prefix, "--version"], { cwd, env: peerChildEnv("pi"), detached: true, stdio: ["ignore", "pipe", "ignore"] }); } catch { resolve(assessVersion("pi", undefined)); return; } let output = "", bytes = 0, done = false; const finish = async (code: number | null) => { if (done) return; done = true; clearTimeout(timer); try { await stopOwnedProcess(proc, { group: true }); } catch { resolve(assessVersion("pi", undefined)); return; } resolve(assessVersion("pi", code === 0 && bytes <= 64 * 1024 ? COMPAT.pi.parse(output) : undefined)); }; const timer = setTimeout(() => { void finish(null); }, timeoutMs); proc.once("spawn", () => trackGroup(proc)); proc.stdout!.on("data", (chunk: Buffer) => { if (done) return; bytes += chunk.length; if (bytes > 64 * 1024) { void finish(null); return; } output += chunk.toString("utf8"); }); proc.once("error", () => { void finish(null); }); proc.once("close", code => { void finish(code); }); }); } type RpcMessage = { type?: string; id?: string | number; command?: string; success?: boolean; data?: any; [key: string]: any }; type VerifiedEmptyResume = { sessionId: string }; type TerminalOwnerObservation = { pid: number; signature: string; sessionId: string; sessionFile: string; ownerToken: string; checkedAt: number }; const TERMINAL_OWNER_MAX_AGE_MS = 1_000; function ownerStillAlive(pid: number, signature: string | undefined): boolean { const current = processSignature(pid); if (current !== undefined) return current === signature; try { process.kill(pid, 0); return true; } catch { return false; } } export class PiPeer extends BasePeer { private sessionModel: string | undefined; readonly hubNative = true; readonly hubOwned: boolean = true; private proc?: ChildProcessWithoutNullStreams; private server?: ReturnType; private buffer = ""; private seq = 0; private readonly pending = new Map void; reject: (e: Error) => void }>(); private readonly usageSeen = new Set(); private settledText = ""; private settledError = ""; private settledCancelled = false; private currentReply?: Envelope; private sessionId = ""; private sessionFile = ""; /** A read-only observation of Pi's native slot, never a second writable title store. */ private observedTitle: string | undefined; private titleRevision = -1; private titleEpoch = 0; private nativeTitleEpoch: string | undefined; get sessionTitle(): string | undefined { return this.acceptingTools && this.verifiedOwner() ? this.observedTitle : undefined; } get titleSession(): string | undefined { return this.nativeSession; } async setSessionTitle(title: string, onlyIfUnnamed: boolean, current?: () => boolean): Promise { const invalid = (error: string, mayHaveApplied = false): SessionTitleResult => ({ ok: false, reason: "invalid", error, ...(mayHaveApplied ? { mayHaveApplied: true as const } : {}) }); if (typeof title !== "string" || !title.trim() || [...title].length > 80 || typeof onlyIfUnnamed !== "boolean") return invalid("Session title must contain 1-80 normalized characters and use a conditional-write flag; correct the title request and try again."); if (this.stopping || this.state === "offline") return invalid("Pi session is offline or stopped; start or reconnect Pi and check ahub status before naming it."); const session = this.sessionId, generation = this.budgetGeneration, owner = this.sessionGeneration, epoch = this.titleEpoch; if (!owner || !this.verifiedOwner()) return invalid("Pi native session owner is unverified; reconnect the retained Pi session and check ahub status before naming it."); if (!this.acceptingTools) return invalid("Pi session is detached or running a personal turn; reconnect its current hub session and check ahub status before naming it."); const valid = () => { try { return this.acceptingTools && this.verifiedOwner() && this.sessionGeneration === owner && this.sessionId === session && this.budgetGeneration === generation && this.titleEpoch === epoch && current?.() !== false; } catch { return false; } }; if (!valid()) return invalid("Pi session, turn or title admission changed before dispatch; check ahub status before retrying in the current public session."); let dispatched = false; try { const result = await this.sendTui({ type: "set_session_title", title, onlyIfUnnamed, sessionId: session, generation, ...(this.nativeTitleEpoch ? { titleEpoch: this.nativeTitleEpoch } : {}) }, valid, () => { dispatched = true; }); if (!valid()) return invalid("Pi session, turn or title admission changed after dispatch; the title may have been applied; check ahub status before retrying.", true); if (result?.ok === false && result.reason === "invalid") { if (result.cause === "session") return invalid("Pi native session changed before the title write; check ahub status and reconnect the current session before retrying."); if (result.cause === "generation") return invalid("Pi native turn changed before the title write; wait for the current turn and check ahub status before retrying."); if (result.cause === "arguments") return invalid("Pi rejected invalid title command arguments; use a 1-80 character normalized title and retry in the current session."); if (result.cause === "native_unavailable") return invalid("Pi native title API is unavailable; restart Pi with the supported hub extension and check ahub status before retrying."); if (result.cause === "native_failed") return invalid("Pi native title API failed without confirming the write; the title may have been applied; check ahub status before retrying.", true); if (result.cause === "native_readback") return invalid("Pi native title readback did not confirm the write; the title may have been applied; check ahub status before retrying.", true); } if (result?.sessionId !== session || typeof result.sessionName !== "string" || this.nativeTitleEpoch !== undefined && result.titleEpoch !== this.nativeTitleEpoch) return invalid("Pi title acknowledgement did not confirm the current native slot; the title may have been applied; check ahub status before retrying.", true); this.observeTitle(result.sessionName, result.titleRevision, result.titleEpoch); if (result.ok === false && result.reason === "already_named") return { ok: false, reason: "already_named", error: "This session already has a title; keep it or ask the person to rename it with ahub title." }; if (result.ok === true && result.sessionName === title) return { ok: true }; return invalid("Pi native title write or readback was not confirmed; the title may have been applied; check ahub status before retrying.", true); } catch (error) { const timeout = error instanceof Error && error.message.includes("acknowledgement timed out"); if (dispatched) return invalid(`Pi title ${timeout ? "acknowledgement timed out" : "bridge command failed after dispatch"}; the title may have been applied; check ahub status before retrying.`, true); return invalid(`Pi title ${timeout ? "command expired" : "admission changed or bridge failed"} before dispatch; check ahub status before retrying in the current session.`); } } private observeTitle(value: unknown, revision?: unknown, epoch?: unknown): void { if (this.nativeTitleEpoch !== undefined && epoch !== this.nativeTitleEpoch) return; if (typeof revision === "number" && Number.isSafeInteger(revision) && revision >= 0) { if (revision < this.titleRevision) return; this.titleRevision = revision; } if (value === undefined) value = ""; // A verified native session omits its name while unnamed. if (typeof value !== "string") return; if (value) this.noteActivity(); // Native session_info is history even before Pi creates its session file. if (this.observedTitle !== value) { this.observedTitle = value; this.onDoing?.("title", value); } } private observeSnapshotTitle(snapshot: { sessionName?: unknown; titleRevision?: unknown; titleEpoch?: unknown }, before: number, beforeEpoch: number): boolean { if (this.titleEpoch !== beforeEpoch || snapshot.titleEpoch !== undefined && snapshot.titleEpoch !== this.nativeTitleEpoch) return false; if (snapshot.titleRevision === undefined && this.titleRevision !== before) return false; if (typeof snapshot.titleRevision === "number" && snapshot.titleRevision < this.titleRevision) return false; this.observeTitle(snapshot.sessionName, snapshot.titleRevision, snapshot.titleEpoch ?? this.nativeTitleEpoch); return true; } private executionBudgetTimer?: ReturnType; private executionAbort?: AbortController; private readonly budgetStops = new Map(); private readonly ceilingStops = new Map(); private ceilingUnsafe = false; private turnObserved = false; private readonly idleBashReservations = new Map(); private budgetGeneration = 0; private settledGeneration: number | undefined; private modelStep = 0; private readonly observationScope = randomUUID(); private emptyResumeVerified = false; private verifiedEmptyResume?: VerifiedEmptyResume; private activityObserved = false; private persistedOnce = false; private activeEnvs: Envelope[] = []; private activeTools = 0; private readonly pendingToolGenerations = new Map }>(); private readonly abortedToolIds = new Set(); private abortIdsOverflow = false; private readonly activeDeliveryIds = new Set(); private agentRunning = false; private approvalExpiries = 0; private approvalAnswerEpoch: number | undefined; private approvalTurnAbort = false; private approvalAbortSent = false; private approvalStopReason = ""; private requestedStopReason: string | undefined; private stopCause: "aborted" | "failure" | undefined; private owner = randomUUID(); private _tuiLaunch?: PiTuiLaunch; private requestedModel = ""; /** #1402: what the turn that is running, or just ended, was on: the `get_state` model (`session`), else the model the hub set (`configured`). Read once at the turn end; never invented. */ private turnModel: ModelObservation | undefined; private baselineRequestedModel = ""; private runtimeModelSelected = false; private starting?: Promise; private ownerClaimed = false; private ownerToken = ""; private stopping = true; private rosterDetached = false; private rosterEpoch = 0; private rosterLifecycleRevision = 0; private fencedPrompt = false; private hubPromptId: string | undefined; private hubPromptGeneration: number | undefined; private pendingPromptId: string | undefined; /** A personal native turn observed on reattach has no hub reply audience. */ private rosterUnownedRun = false; private exitReported = false; private started = false; private lastToolName?: string; private shutdownExit?: PiExit; private ownerPid?: number; private ownerSignature?: string; private ownerMonitor?: ReturnType; private terminalOwnerObservation?: TerminalOwnerObservation; private tuiExit?: Promise; private resolveTuiExit?: () => void; private tuiCommands = new Map; current?: () => boolean; onDispatch?: () => void; resolve: (value: any) => void; reject: (error: Error) => void }>(); private tuiQueue: Record[] = []; private tuiWaiters: Array<{ resolve: (command: Record | undefined) => void; timer: ReturnType }> = []; /** The fixed production factory supplies preflight separately, preserving transport option identity. */ constructor(id: PeerId, private readonly opts: PiOptions, private readonly preflight?: () => Promise) { super(id, opts.watchdogMs); this.baselineRequestedModel = opts.model ?? ""; } get tuiLaunch(): PiTuiLaunch | undefined { return this._tuiLaunch; } get pendingResume(): { sessionId?: string; sessionFile?: string } { if (this.canReuseVerifiedEmptyResume()) return { sessionId: this.verifiedEmptyResume!.sessionId }; return { sessionId: this.opts.sessionId, sessionFile: this.opts.sessionFile }; } get acceptingTools(): boolean { return !this.stopping && !this.rosterDetached && !this.rosterUnownedRun; } /** Failure handoff may follow a verified internal teardown; it never grants tool execution. */ get failureHandoffAllowed(): boolean { return !this.rosterDetached && !this.rosterUnownedRun && this.stopCause !== "aborted" && (!this.stopping || this.state === "offline" && this.stopCause === "failure"); } /** Idle verified owners can be stopped; uncertain live owners and pending launches stay fenced. */ get recoveryReady(): boolean { if (this.state === "busy" || this.starting || this.activeTools) return false; if (this.sessionFile && !existsSync(this.sessionFile) && (this.activityObserved || this.persistedOnce)) return false; if (this.opts.mode === "headless") return this.state === "idle" || !this.proc || this.proc.exitCode !== null || this.proc.signalCode !== null; if (this.state === "idle") return this.ownerClaimed && !!this.ownerPid && this.readOwnerSignature(this.ownerPid) === this.ownerSignature; return this.stopping && !this.ownerClaimed && (!this.ownerPid || !ownerStillAlive(this.ownerPid, this.ownerSignature)); } /** Explicit replacement may retain an unpersisted identity, but never a live/unknown owner or active effects. */ get replacementReady(): boolean { if (this.state !== "offline" || this.starting || this.activeTools || this.pendingToolGenerations.size || this.pending.size || this.tuiCommands.size) return false; if (this.opts.mode === "headless") return !this.proc || this.proc.exitCode !== null || this.proc.signalCode !== null; return this.stopping && !this.ownerClaimed && !!this.ownerPid && processLiveness(this.ownerPid, this.ownerSignature) === "gone"; } /** Stable across turns, invalidated when the verified native owner/session changes. Not caller supplied. */ get sessionGeneration(): string | undefined { return this.ownerClaimed && this.ownerPid && this.ownerSignature ? `${this.ownerPid}:${this.ownerSignature}:${this.sessionId ?? ""}` : undefined; } // ponytail: retain Pi's owner/session-only checkpoint fence in this slice; a later native-proof port can strengthen it. readonly checkpointUsesSessionGeneration = false; recoveryMetadata(): Record { const exists = !!this.sessionFile && existsSync(this.sessionFile); if (exists) { this.persistedOnce = true; this.verifiedEmptyResume = undefined; } const empty = this.emptyResumeVerified && !this.activityObserved && !this.persistedOnce; const file = this.sessionFile && (exists || !empty) ? this.sessionFile : undefined; return { launch: { kind: "pi", cwd: this.opts.cwd, mode: this.opts.mode, backend: this.opts.backend, ...(this.opts.model ? { model: this.opts.model } : {}), ...(file ? { sessionFile: file } : {}) }, ...(this.sessionId ? { sessionId: this.sessionId } : {}), ...(file ? { sessionFile: file } : {}) }; } get nativeSession(): string | undefined { const session = this.recoveryMetadata().sessionId; return typeof session === "string" ? session : undefined; } get verifiedRecordSession(): string | undefined { return this.verifiedOwner() ? this.nativeSession : undefined; } /** Verify the live source before choosing ID-only restoration. Never infer emptiness from a missing file. */ async captureResume(): Promise> { if (this.state === "offline") { if (this.canReuseVerifiedEmptyResume()) return this.recoveryMetadata(); if (this.recoveryReady && this.sessionFile && existsSync(this.sessionFile)) return this.recoveryMetadata(); throw new Error("Pi source session is offline and has no verified persisted resume state; inspect preserved history, then a person may run ahub pi --replace-session --session-file "); } this.emptyResumeVerified = false; if (this.state !== "idle" || this.stopping || this.activeTools) throw new Error("Pi must settle before session capture"); if (this.sessionFile && existsSync(this.sessionFile)) return this.recoveryMetadata(); const titleRevisionBefore = this.titleRevision, titleEpochBefore = this.titleEpoch; const snapshot = this.opts.mode === "headless" ? (await this.waitRpc("get_state", 15_000)).data : await this.sendTui({ type: "get_session_state" }); if (this.state !== "idle" || this.activeTools || snapshot?.sessionId !== this.sessionId || snapshot?.sessionFile !== this.sessionFile) throw new Error("Pi source session changed during capture"); if (this.opts.mode === "tui" && this.verifiedOwner() && this.sessionId) { this.sessionModel = stateModelId(snapshot); this.opts.onContext?.(snapshot.context, this.sessionId); } if (!this.observeSnapshotTitle(snapshot, titleRevisionBefore, titleEpochBefore)) throw new Error("Pi source session title changed during capture; retry with a fresh native session snapshot"); const empty = this.opts.mode === "headless" ? snapshot.messageCount === 0 && snapshot.pendingMessageCount === 0 && snapshot.isStreaming === false && snapshot.isCompacting !== true && !snapshot.sessionName : snapshot.empty === true && snapshot.idle === true; if (!empty || this.activityObserved || this.persistedOnce) throw new Error("Pi session history is not persisted; refusing to recreate it. Exchange one message or start a new session, then retry"); this.emptyResumeVerified = true; const captured = this.recoveryMetadata(); if (typeof captured.sessionId === "string" && !captured.sessionFile) this.verifiedEmptyResume = { sessionId: captured.sessionId }; return captured; } private canReuseVerifiedEmptyResume(): boolean { return !!this.verifiedEmptyResume && this.recoveryReady && !this.activityObserved && !this.persistedOnce && this.sessionId === this.verifiedEmptyResume.sessionId && (!this.sessionFile || !existsSync(this.sessionFile)); } private noteActivity(): void { this.activityObserved = true; this.emptyResumeVerified = false; this.verifiedEmptyResume = undefined; } /** Envelopes belonging to the currently executing Pi turn, for relay-side model-call admission. */ /** One id per admitted provider request; parallel tools share its assistant step. */ get observationTurn(): string | undefined { return this.acceptingTools && this.agentRunning && this.modelStep ? `${this.observationScope}.${this.budgetGeneration}.${this.modelStep}` : undefined; } get budgetEnvelopes(): Envelope[] { return this.acceptingTools && this.agentRunning && this.state === "busy" ? this.activeEnvs.slice() : []; } /** Mark an authoritative relay admission stop against the current Pi turn, never a later turn. */ recordBudgetStop(decision: ExecutionBudgetDecision): { generation: number; reason: string } | undefined { if (!this.acceptingTools || !this.agentRunning || this.state !== "busy") return undefined; const generation = this.budgetGeneration; const reason = `execution budget ${decision.reason ?? "exhausted"}: ${decision.scope} ${decision.unit} used ${decision.used}${decision.limit === null ? "" : ` of ${decision.limit}`}; ${decision.remaining === null ? "remaining unknown" : `${decision.remaining} remaining`}`; this.budgetStops.set(generation, reason); this.executionAbort?.abort(); for (const old of this.budgetStops.keys()) if (old < generation - 8) this.budgetStops.delete(old); return { generation, reason }; } async start(): Promise { if (this.starting) return this.starting; this.starting = this.startImpl(); try { await this.starting; } finally { this.starting = undefined; } } /** The keepalive period of a long tool reply; well under every timer between the hub and Pi's runtime (60 s Bun idle, 300 s undici). A test shortens it. */ toolKeepaliveMs = 15_000; /** * A tool reply that may take minutes (`hub_ask`): the status line and headers go out at once, a space is written every `toolKeepaliveMs`, and the JSON body * follows when the call settles. Whitespace before a JSON value is valid JSON, so the extension's `response.json()` reads it unchanged. When the client goes away * the stream is cancelled and the call is aborted through its own signal with `QuestionWaitDetached`, so the wait ends `pending` and the row stays open for the late envelope; * nothing else about `handleToolRequest` changes. */ private streamedToolResponse(body: any, clientGone: AbortSignal): Response { const encoder = new TextEncoder(); let timer: ReturnType | undefined, closed = false; const stop = () => { closed = true; if (timer) clearInterval(timer); timer = undefined; }; return new Response(new ReadableStream({ start: controller => { timer = setInterval(() => { if (!closed) try { controller.enqueue(encoder.encode(" ")); } catch { stop(); } }, this.toolKeepaliveMs); timer.unref?.(); const abort = () => { stop(); this.pendingToolGenerations.get(String(body?.toolCallId ?? ""))?.abort.abort(new QuestionWaitDetached()); }; clientGone.addEventListener("abort", abort, { once: true }); void this.handleToolRequest(body).then(async response => { const text = await response.text(); if (closed) return; stop(); try { controller.enqueue(encoder.encode(text)); controller.close(); } catch { /* the client already left */ } }, () => { if (closed) return; stop(); try { controller.enqueue(encoder.encode(JSON.stringify({ text: "error: Pi tool call failed", failed: true }))); controller.close(); } catch { /* the client already left */ } }); }, cancel: () => { stop(); this.pendingToolGenerations.get(String(body?.toolCallId ?? ""))?.abort.abort(new QuestionWaitDetached()); }, }), { headers: { "content-type": "application/json" } }); } private async handleToolRequest(body: any): Promise { if (!this.acceptingTools || this.state === "offline") return Response.json({ text: this.rosterDetached ? "error: Pi is off roster" : this.rosterUnownedRun ? "error: Pi native turn is pending" : "error: Pi owner is stopped" }, { status: 409 }); if (!this.verifiedOwner() || typeof body.sessionId !== "string" || !body.sessionId || body.sessionId !== this.sessionId || !Number.isSafeInteger(body.generation) || body.generation !== this.budgetGeneration) { const text = "error: Pi tool lineage is missing, stale or unverified; restart Pi with the current hub extension before retrying"; this.opts.log?.(`[${this.id}] ${text}`); return Response.json({ text, failed: true }, { status: 409 }); } if (this.abortIdsOverflow || this.abortedToolIds.has(String(body.toolCallId))) return Response.json({ text: "error: tool call cancelled before execution", failed: true }); if (this.pendingToolGenerations.has(String(body.toolCallId ?? ""))) return Response.json({ text: "error: this Pi tool call is already in progress", failed: true }, { status: 409 }); let executionSignal = this.executionAbort?.signal; let idleBashTimer: ReturnType | undefined; if (body.purpose === "idle_user_bash") { const reservation = typeof body.reservation === "string" ? this.idleBashReservations.get(body.reservation) : undefined; if (this.opts.mode !== "tui" || !this.verifiedOwner() || !reservation || reservation.expiresAt < Date.now() || reservation.generation !== body.generation || !this.ownerClaimed || this.ownerPid === undefined || this.state !== "idle" || this.agentRunning || this.activeTools > 0 || this.activeEnvs.length > 0 || !Number.isSafeInteger(body.generation) || body.generation !== this.budgetGeneration) return Response.json({ text: "error: stale or non-idle Pi user shell request" }, { status: 409 }); if (reservation.deadlineAt !== undefined && reservation.deadlineAt <= Date.now()) { this.idleBashReservations.delete(String(body.reservation)); return Response.json({ text: "error: Pi user shell execution budget expired" }, { status: 409 }); } this.idleBashReservations.delete(String(body.reservation)); const idleBashAbort = new AbortController(); executionSignal = idleBashAbort.signal; if (reservation.deadlineAt !== undefined) idleBashTimer = setTimeout(() => idleBashAbort.abort(), Math.max(0, reservation.deadlineAt - Date.now())); } this.noteActivity(); const generation = this.budgetGeneration; const turnSignal = this.executionAbort?.signal; const parentSignal = executionSignal; const toolAbort = new AbortController(); const abortTool = () => toolAbort.abort(); parentSignal?.addEventListener("abort", abortTool, { once: true }); if (parentSignal?.aborted) abortTool(); executionSignal = toolAbort.signal; const callId = String(body.toolCallId ?? ""); let settled!: () => void; const settlement = new Promise((resolve) => { settled = resolve; }); this.pendingToolGenerations.set(callId, { generation, abort: toolAbort, settled: settlement }); const name = String(body.name); this.lastToolName = this.opts.tools.some((tool) => tool.name === name) && /^[a-zA-Z0-9_.-]{1,128}$/.test(name) ? name : "unknown"; this.activeTools++; if (this.state === "idle") this.setState("busy"); if (this.state === "busy") this.touch(); // `failed` is the managed-tool failure verdict (toolResultFailed, the one contract): Pi 1.0.1 // classifies a native tool result by isError === true alone, so the extension needs the flag, // not just the text (#181). An older extension simply ignores the extra field. try { const result = await this.opts.executeTool(name, body.args, callId, this.sessionId, executionSignal, { userBash: body.purpose === "idle_user_bash", isCurrent: () => generation === this.budgetGeneration && this.acceptingTools && this.state !== "offline" && !executionSignal?.aborted && !this.approvalStopReason && this.verifiedOwner() && (body.purpose === "idle_user_bash" ? this.opts.mode === "tui" : turnSignal === this.executionAbort?.signal), onApproval: (provenance) => { if (!this.acceptingTools || !this.agentRunning || generation !== this.budgetGeneration || turnSignal !== this.executionAbort?.signal || this.approvalStopReason) return; if (this.approvalAnswerEpoch !== provenance.answerEpoch) { this.approvalExpiries = 0; this.approvalAnswerEpoch = provenance.answerEpoch; } if (provenance.source === "person") this.approvalExpiries = 0; if (provenance.source === "expired" && provenance.eligibleExpiry !== false && ++this.approvalExpiries >= 2) { this.approvalStopReason = "Pi turn stopped after two unanswered approvals; no person answered. Do not retry the calls; inspect prior work before handoff or stopping."; try { this.opts.onApprovalStop?.(this.approvalStopReason); } catch { /* stop remains authoritative */ } } }, }); const text = typeof result === "string" ? result : result.text; return Response.json({ text, failed: typeof result !== "string" && result.exitCode !== null ? result.exitCode !== 0 : toolResultFailed(name, text), ...(typeof result === "string" ? {} : { exitCode: result.exitCode }) }); } catch (error) { return Response.json({ text: `error: ${(error as Error).message}`, failed: true }, { status: 200 }); } finally { clearTimeout(idleBashTimer); this.activeTools--; parentSignal?.removeEventListener("abort", abortTool); if (this.pendingToolGenerations.get(callId)?.abort === toolAbort) this.pendingToolGenerations.delete(callId); settled(); if (this.approvalStopReason && !this.approvalAbortSent) { this.approvalAbortSent = true; const reason = this.approvalStopReason; // Finish this request's expiry reply before withdrawing siblings and aborting the native turn. setTimeout(() => { if (this.agentRunning && generation === this.budgetGeneration && this.approvalStopReason === reason && !this.stopping) void this.endApprovalTurn(generation, reason); }, 10); } if (this.state === "busy" && this.acceptingTools) { if (!this.activeTools && !this.agentRunning && !this.activeEnvs.length) this.setState("idle"); else this.touch(); } } } private async handleBudgetRequest(body: any): Promise { if (this.rosterDetached || this.rosterUnownedRun) return Response.json({ error: this.rosterDetached ? "Pi is off roster" : "Pi native turn is pending" }, { status: 409 }); if (!["model_calls", "tool_calls"].includes(String(body.unit))) return Response.json({ error: "invalid Pi budget unit" }, { status: 400 }); const idleUserBash = body.idleUserBash === true; const generation = body.generation, controller = this.executionAbort, session = this.sessionId, ownerPid = this.ownerPid, ownerSignature = this.ownerSignature; const current = () => Number.isSafeInteger(generation) && generation === this.budgetGeneration && controller === this.executionAbort && session === this.sessionId && ownerPid === this.ownerPid && ownerSignature === this.ownerSignature && this.acceptingTools && this.verifiedOwner(); const idleOwner = this.opts.mode === "tui" && this.acceptingTools && this.verifiedOwner() && this.state === "idle" && !this.agentRunning && this.activeTools === 0 && this.activeEnvs.length === 0; if (!current() || (idleUserBash ? !idleOwner : !this.agentRunning || this.state !== "busy")) return Response.json({ error: "stale Pi budget request" }, { status: 409 }); // An interactive user shell has no task delivery. It may spend an eligible run budget only. const envs = idleUserBash ? [] : this.budgetEnvelopes; const decisions = this.opts.admitBudget ? await this.opts.admitBudget(envs, body.unit as ExecutionUnit) : []; if (!current() || (idleUserBash ? this.state !== "idle" || this.agentRunning || this.activeTools > 0 || this.activeEnvs.length > 0 : !this.agentRunning || this.state !== "busy")) return Response.json({ error: "Pi owner or turn changed during admission" }, { status: 409 }); const denied = decisions.find((decision) => !decision.allowed); const remaining = decisions.filter((decision) => decision.unit === "elapsed_ms" && decision.remaining !== null).reduce((min, decision) => min === undefined ? decision.remaining! : Math.min(min, decision.remaining!), undefined); let reservation: string | undefined; if (idleUserBash && !denied) { for (const [key, value] of this.idleBashReservations) if (value.expiresAt < Date.now()) this.idleBashReservations.delete(key); reservation = randomUUID(); this.idleBashReservations.set(reservation, { generation: body.generation, expiresAt: Date.now() + 30_000, ...(remaining === undefined ? {} : { deadlineAt: Date.now() + remaining }) }); } clearTimeout(this.executionBudgetTimer); if (!denied && remaining !== undefined && this.state === "busy") { const generation = this.budgetGeneration; const controller = this.executionAbort; this.executionBudgetTimer = setTimeout(() => { if (!this.agentRunning || generation !== this.budgetGeneration || controller !== this.executionAbort) return; controller?.abort(); void this.sendTui({ type: "abort_budget", generation }).catch((error) => this.opts.log?.(`[${this.id}] elapsed budget stop could not reach Pi: ${(error as Error).message}`)); }, Math.max(0, remaining)); } if (!denied && body.unit === "model_calls") this.modelStep++; return Response.json({ decisions, ...(reservation ? { reservation } : {}) }); } private async startImpl(): Promise { if (this.preflight) await this.preflight(); this.terminalOwnerObservation = undefined; this.stopping = false; this.observedTitle = undefined; this.titleRevision = -1; this.nativeTitleEpoch = undefined; this.onDoing?.("reset"); this.rosterDetached = false; this.rosterUnownedRun = false; this.requestedStopReason = undefined; this.stopCause = undefined; this.settledGeneration = undefined; this.approvalTurnAbort = false; this.fencedPrompt = false; this.hubPromptId = undefined; this.hubPromptGeneration = undefined; this.pendingPromptId = undefined; this.exitReported = false; this.started = false; this.lastToolName = undefined; this.shutdownExit = undefined; this.approvalExpiries = 0; this.approvalAnswerEpoch = undefined; this.approvalStopReason = ""; this.approvalAbortSent = false; mkdirSync(this.opts.stateDir, { recursive: true }); const sessions = join(this.opts.stateDir, "pi-sessions"); mkdirSync(sessions, { recursive: true, mode: 0o700 }); if (this.opts.sessionFile) { try { validatePiSession(this.opts.stateDir, this.opts.cwd, this.opts.sessionFile, this.opts.sessionId); } catch (error) { if (error instanceof PiSessionBookmarkMismatch) throw new PiSessionBookmarkMismatch("Pi session header id does not match the requested session", { cause: error }); throw error; } } const token = randomUUID(); this.tuiExit = new Promise((resolvePromise) => { this.resolveTuiExit = resolvePromise; }); const bridge = Bun.serve({ hostname: "127.0.0.1", port: 0, idleTimeout: 60, maxRequestBodySize: 2_000_000, fetch: async (request) => { const origin = request.headers.get("origin"); if (origin) return new Response("forbidden", { status: 403 }); if (request.headers.get("authorization") !== `Bearer ${token}`) return new Response("forbidden", { status: 403 }); const url = new URL(request.url); if (url.pathname === "/commands" && request.method === "GET") { const command = await this.nextTuiCommand(25_000); return Response.json(command ? { command } : { command: null }); } if (request.method !== "POST") return new Response("method not allowed", { status: 405 }); const body = await request.json() as any; if (url.pathname === "/event") { if (body.type === "session_start" && this.stopping) return Response.json({ ok: false, error: "Pi launch has ended" }, { status: 409 }); if (body.type === "session_start" && (typeof body.sessionId !== "string" || !body.sessionId || typeof body.sessionFile !== "string" || !body.sessionFile)) return Response.json({ ok: false, error: "Pi session identity is missing" }, { status: 400 }); if (body.type === "session_start" && this.ownerClaimed && (body.ownerToken !== this.ownerToken || body.pid !== this.ownerPid || body.signature !== this.ownerSignature || (this.sessionId && body.sessionId !== this.sessionId) || (this.sessionFile && body.sessionFile !== this.sessionFile))) return Response.json({ ok: false, error: "Pi session owner or identity already claimed" }, { status: 409 }); if (body.type === "session_start" && (!Number.isInteger(body.pid) || !body.signature || this.readOwnerSignature(body.pid) !== body.signature)) return Response.json({ ok: false, error: "Pi process identity is not verified" }, { status: 409 }); this.handleBridgeEvent(body); return Response.json({ ok: true }); } if (url.pathname === "/ack") { const pending = this.tuiCommands.get(String(body.id)); if (!pending) return Response.json({ ok: false }, { status: 404 }); this.tuiCommands.delete(String(body.id)); const refusal = body.refusal; const boundRefusal = this.fencedPrompt && this.verifiedOwner() && pending.command.type === "prompt" && pending.command.sessionId === this.sessionId && refusal?.promptId === pending.command.id && refusal.sessionId === this.sessionId && Number.isSafeInteger(refusal.generation) && refusal.generation >= Number(pending.command.generation); body.ok ? pending.resolve(body.result) : pending.reject(boundRefusal && refusal.kind === "prompt_not_started" ? new PiPromptNotStarted(String(body.id)) : boundRefusal && refusal.kind === "prompt_uncertain" ? new PiPromptUncertain("Pi native prompt insertion is uncertain; inspect its retained terminal before retrying") : new Error(String(body.error ?? "Pi TUI command failed"))); return Response.json({ ok: true }); } if (url.pathname === "/tool") { // #1053: `hub_ask` holds this request open for the person's wait window. Two timers would cut it: Bun's 60 s bridge idle timeout (lifted for this one call with // `timeout(request, 0)`) and the extension's own fetch, whose undici dispatcher Pi installs with headersTimeout and bodyTimeout of 300 s (Pi 1.4.0 // `configureHttpDispatcher`, measured: UND_ERR_HEADERS_TIMEOUT). So the reply is streamed: headers go out at once and a space every 15 s keeps both timers // quiet, then the JSON follows (`response.json()` ignores leading whitespace). A client that gives up anyway cancels the stream, which aborts the call; the // question row stays open and its answer takes the late-envelope path. if (body?.name === "hub_ask") { bridge.timeout(request, 0); return this.streamedToolResponse(body, request.signal); } return this.handleToolRequest(body); } if (url.pathname === "/budget") return this.handleBudgetRequest(body); return new Response("not found", { status: 404 }); } }); this.server = bridge; const extension = resolve(join(import.meta.dir, "../pi/extension.ts")); const inherited: NodeJS.ProcessEnv = {}; for (const key of ["PATH", "HOME", "USER", "SHELL", "TMPDIR", "TERM", "TERM_PROGRAM", "LANG", "LC_ALL", "LC_CTYPE", "NO_COLOR", "CODEX_HOME"]) if (process.env[key]) inherited[key] = process.env[key]; this._tuiLaunch = buildPiLaunch({ ...this.opts, instance: this.id }, inherited, extension, bridge.port!, token); const { cmd: bin, args, env } = this._tuiLaunch; if (this.opts.mode === "tui") { return; } // Its own process group, stopped as a whole (#115, as Codex's in #113). this.proc = spawn(bin, args, { cwd: this.opts.cwd, env, stdio: ["pipe", "pipe", "pipe"], detached: true }); trackGroup(this.proc); this.proc.stdout.on("data", (chunk) => this.onOutput(String(chunk))); this.proc.stderr.on("data", (chunk) => this.opts.log?.(`[${this.id}] ${String(chunk).trimEnd()}`)); const proc = this.proc; proc.on("error", (error) => { const exit = this.exitMetadata("spawn_error"); this.fail(error); this.reportExit(exit); }); proc.on("exit", (code, signal) => { const exit = { ...(this.shutdownExit ?? this.exitMetadata("process_exit")), code, signal }; this.fail(new Error(`pi exited with ${signal ? `signal ${signal}` : `code ${code}`}`)); this.reportExit(exit); }); const titleRevisionBefore = this.titleRevision, titleEpochBefore = this.titleEpoch; const state = await this.waitRpc("get_state", 15_000); if (state.success !== true || typeof state.data?.sessionId !== "string" || typeof state.data?.sessionFile !== "string" || !state.data.sessionId || !state.data.sessionFile) throw new Error("Pi get_state did not prove session identity"); if ((this.opts.sessionId && state.data.sessionId !== this.opts.sessionId) || (this.opts.sessionFile && state.data.sessionFile !== this.opts.sessionFile)) { throw new Error("Pi get_state session identity does not match the requested recovery session"); } this.sessionId = state.data.sessionId; this.sessionFile = state.data.sessionFile; // The hub spawned this headless owner and get_state proved its session. Pin the same // identity a native extension claim uses, including fakes that do not load the extension. if (!this.ownerClaimed) { const pid = this.proc?.pid, signature = pid ? this.readOwnerSignature(pid) : undefined; if (!pid || !signature) throw new Error("Pi headless owner process identity is not verified"); this.ownerPid = pid; this.ownerSignature = signature; this.ownerToken = String(this._tuiLaunch?.env.AGENTHUB_PI_OWNER_TOKEN ?? ""); this.ownerClaimed = true; } this.persistedOnce = existsSync(this.sessionFile); if ((this.opts.sessionId && this.sessionId !== this.opts.sessionId) || (this.opts.sessionFile && this.sessionFile !== this.opts.sessionFile)) throw new Error("Pi startup session identity mismatch"); this.observeSnapshotTitle(state.data, titleRevisionBefore, titleEpochBefore); this.started = true; this.setState("idle"); } private readOwnerSignature(pid: number): string | undefined { return (this.opts.signature ?? processSignature)(pid); } private verifiedOwner(): boolean { return this.ownerClaimed && !!this.ownerPid && !!this.ownerSignature && this.readOwnerSignature(this.ownerPid) === this.ownerSignature; } private rememberTerminalOwner(): void { if (!this.ownerClaimed || !this.ownerPid || !this.ownerSignature) return; this.terminalOwnerObservation = { pid: this.ownerPid, signature: this.ownerSignature, sessionId: this.sessionId, sessionFile: this.sessionFile, ownerToken: this.ownerToken, checkedAt: performance.now() }; } terminalOwner(_launchId: string): { generation: string; nativePid: number } | undefined { const observed = this.terminalOwnerObservation; // Reconciliation reads the monitor's bounded observation, never spawning ps on its 1 s tick. // Effect admission and teardown keep their fresh process-identity checks. if (this.opts.mode !== "tui" || !this.started || this.stopping || this.rosterDetached || this.state === "offline" || !this.ownerClaimed || !observed || performance.now() - observed.checkedAt > TERMINAL_OWNER_MAX_AGE_MS || observed.pid !== this.ownerPid || observed.signature !== this.ownerSignature || observed.sessionId !== this.sessionId || observed.sessionFile !== this.sessionFile || observed.ownerToken !== this.ownerToken || !this.sessionId || !this.sessionFile || this.opts.sessionId && this.opts.sessionId !== this.sessionId || this.opts.sessionFile && this.opts.sessionFile !== this.sessionFile) return undefined; const generation = this.sessionGeneration; return generation && this.ownerPid ? { generation, nativePid: this.ownerPid } : undefined; } private abortTools(): Promise[] { this.executionAbort?.abort(); this.idleBashReservations.clear(); const pending = [...this.pendingToolGenerations.values()]; for (const call of pending) call.abort.abort(); return pending.map((call) => call.settled); } get mode(): "headless" | "tui" { return this.opts.mode; } get form(): StartForm { return this.opts.mode; } private observeTurn(outcome: "aborted" | "success"): void { if (this.turnObserved || !this.agentRunning && !this.activeEnvs.length) return; this.turnObserved = true; try { if (outcome === "aborted") this.opts.onTurnAborted?.(this.activeEnvs.slice()); else this.opts.onTurnSuccess?.(this.activeEnvs.slice()); } catch { /* observation cannot change delivery settlement */ } } /** Withdraw hub admission without shutting down a person's Pi TUI or its bridge. */ async detachForRoster(): Promise { if (this.opts.mode !== "tui") throw new Error("Pi roster detach requires a personal TUI"); this.observeTurn("aborted"); this.terminalOwnerObservation = undefined; this.rosterDetached = true; this.rosterEpoch++; this.setState("offline"); clearTimeout(this.executionBudgetTimer); this.executionBudgetTimer = undefined; const ids = [...this.activeDeliveryIds]; this.activeDeliveryIds.clear(); this.activeEnvs = []; this.currentReply = undefined; this.settledText = ""; this.settledError = ""; this.settledCancelled = false; for (const id of ids) this.delivery({ id, state: "needs_review", reason: "Pi removed from roster before settlement; inspect the native session before retrying" }); const settling = this.abortTools(); // Revoke hub commands not yet consumed, and fence an ACK already in flight by rosterEpoch. for (const [id, pending] of this.tuiCommands) { if (!["prompt", "steer", "set_model"].includes(String(pending.command.type))) continue; this.tuiCommands.delete(id); this.tuiQueue = this.tuiQueue.filter((command) => command.id !== id); pending.reject(new Error("Pi is off roster")); } if (settling.length) { let timer: ReturnType | undefined; try { await Promise.race([Promise.all(settling), new Promise((_, reject) => { timer = setTimeout(() => reject(new PiToolSettlementFailure("Pi managed tools did not settle after roster detach")), this.opts.stopGraceMs ?? 5_000); })]); } finally { clearTimeout(timer); } } } /** A return reuses only the same verified native owner and a fresh, truthful snapshot. */ async resumeFromRoster(): Promise { if (!this.rosterDetached) return; if (this.opts.mode !== "tui" || this.stopping || !this.rosterDetached || !this.server || !this.verifiedOwner()) throw new Error("Pi roster return has no verified live TUI owner"); if (!this.fencedPrompt) throw new Error("Pi roster return needs a fenced-prompt extension; restart the retained terminal with the current hub extension"); if (this.pendingPromptId) throw new Error("Pi prompt admission is still pending; wait before reverifying the retained terminal"); const epoch = this.rosterEpoch, lifecycle = this.rosterLifecycleRevision, session = this.sessionId, file = this.sessionFile; const titleRevisionBefore = this.titleRevision, titleEpochBefore = this.titleEpoch; const snapshot = await this.sendTui({ type: "get_session_state" }); if (epoch !== this.rosterEpoch || this.stopping || !this.verifiedOwner() || this.activeTools || snapshot?.sessionId !== session || snapshot?.sessionFile !== file || typeof snapshot?.idle !== "boolean") throw new Error("Pi roster return could not verify the current native session"); if (lifecycle !== this.rosterLifecycleRevision) throw new Error("Pi native activity changed during roster return; retry with a fresh session snapshot"); if (session) { this.sessionModel = stateModelId(snapshot); this.opts.onContext?.(snapshot.context, session); } this.observeSnapshotTitle(snapshot, titleRevisionBefore, titleEpochBefore); this.rosterDetached = false; this.hubPromptId = undefined; this.hubPromptGeneration = undefined; this.rosterUnownedRun = !snapshot.idle; this.agentRunning = !snapshot.idle; this.setState(snapshot.idle ? "idle" : "busy"); if (!snapshot.idle) this.clearWatchdog(); } async stop(reason?: string, failureCause?: DeliveryFailureCause, cause: "aborted" | "failure" = "aborted"): Promise { if (cause === "aborted" || this.stopCause === undefined) this.stopCause = cause; if (cause === "aborted") this.observeTurn("aborted"); if (reason !== undefined) this.requestedStopReason = reason; this.rosterEpoch++; this.terminalOwnerObservation = undefined; this.stopping = true; // fence new calls before withdrawing both turn and idle-shell execution for (const id of this.activeDeliveryIds) this.delivery({ id, state: "needs_review", reason: reason ?? "Pi session stopped before settlement", ...(failureCause ? { failureCause } : {}) }); this.activeDeliveryIds.clear(); const settling = this.abortTools(); let unsettled: unknown; if (settling.length) { let timer: ReturnType | undefined; try { await Promise.race([Promise.all(settling), new Promise((_, reject) => { timer = setTimeout(() => reject(new PiToolSettlementFailure("Pi managed tools did not settle after cancellation")), this.opts.stopGraceMs ?? 5_000); })]); } catch (error) { unsettled = error; } // a tool past its grace must not block the teardown (#253): stop reports it at the end finally { clearTimeout(timer); } } const tuiExit = this.opts.mode === "tui" && this.ownerClaimed && this.ownerPid && this.ownerSignature ? { ...this.exitMetadata("owner_stopped"), expected: true } : undefined; this.stopping = true; this.clearOwnerMonitor(); if (this.opts.mode === "tui") { const grace = this.opts.stopGraceMs ?? 5_000; const alive = () => !!this.ownerPid && ownerStillAlive(this.ownerPid, this.ownerSignature); if (this.ownerClaimed && alive()) { try { await Promise.race([this.sendTui({ type: "shutdown" }), (async () => { const deadline = Date.now() + grace; while (alive() && Date.now() < deadline) await Bun.sleep(50); if (alive()) throw new Error("Pi TUI shutdown was not acknowledged"); })()]); } catch (error) { // A lost shutdown acknowledgement is not a reason to leave a native owner running // next to its replacement: tear it down by verified identity, or fail stop (#56). if (alive() && !(await this.stopSurvivingOwner())) { this.setState("busy"); this.startOwnerMonitor(); throw error; } } } const deadline = Date.now() + grace; while (alive() && Date.now() < deadline) await Bun.sleep(50); if (alive() && !(await this.stopSurvivingOwner()) && alive()) { this.setState("busy"); this.startOwnerMonitor(); throw new Error("Pi TUI owner process did not exit"); } this.ownerClaimed = false; this.resolveTuiExit?.(); this.resolveTuiExit = undefined; } const proc = this.proc; // Also when it exited: what it left in its group fails the stop. The rest of the teardown runs either way; a process // that could not be stopped stays recorded, so a later stop tries it again. let failed: unknown; if (proc) await stopOwnedProcess(proc, { group: true }).then(() => { if (this.proc === proc) this.proc = undefined; }, (error: unknown) => { failed = error; }); for (const waiter of this.tuiWaiters) { clearTimeout(waiter.timer); waiter.resolve(undefined); } this.tuiWaiters = []; for (const pending of this.tuiCommands.values()) pending.reject(new Error("Pi owner stopped")); this.tuiCommands.clear(); this.tuiQueue = []; for (const pending of this.pending.values()) pending.reject(new Error("Pi owner stopped")); this.pending.clear(); this.server?.stop(true); this.server = undefined; this.setState("offline"); if (failed) throw failed; if (tuiExit) this.reportExit(tuiExit); // the verified owner is gone; never invent an exit for an unclaimed launch if (unsettled) throw unsettled; } /** * Terminate a verified TUI owner that outlived its graceful shutdown. Every signal is * guarded by ownerStillAlive, which re-reads the process signature on each poll, so a * reused PID is never signaled. True once the owner is confirmed gone. */ private async stopSurvivingOwner(): Promise { const pid = this.ownerPid; const signature = this.ownerSignature; const gone = () => !pid || !ownerStillAlive(pid, signature); if (!pid || !signature || gone()) return true; try { process.kill(pid, "SIGTERM"); } catch { return gone(); } let deadline = Date.now() + 2_000; while (!gone() && Date.now() < deadline) await Bun.sleep(50); if (gone()) return true; try { process.kill(pid, "SIGKILL"); } catch { return gone(); } deadline = Date.now() + 2_000; while (!gone() && Date.now() < deadline) await Bun.sleep(50); return gone(); } async deliver(envs: Envelope[], deliveryId?: string): Promise { if (this.state !== "idle" || !this.acceptingTools) { const reason = `${this.id} is not ready${this.rosterDetached ? ": off roster" : this.rosterUnownedRun ? ": native turn pending" : ""}`; if (deliveryId) this.delivery({ id: deliveryId, state: "failed_safe", reason }); throw new Error(reason); } // ponytail: host turn starts at busy before async model preflight. Later workflow // notices wait for the following turn; closing that window needs an ACK-safe prepare/commit port. this.turnObserved = false; this.setState("busy"); this.activeEnvs = envs; this.currentReply = replyParent(envs); this.settledText = ""; const rosterEpoch = this.rosterEpoch; let attempted = false; let promptId: string | undefined; try { const selection = this.opts.getModelOverride?.(); if (selection?.model !== undefined && !isNativeModelToken(selection.model)) throw new Error("runtime model must be one bounded native token"); const baseline = await this.opts.selectModel?.(envs); const requested = selection?.model ?? baseline ?? (this.baselineRequestedModel || undefined); if (selection && selection.model === undefined && this.runtimeModelSelected && !requested) throw new Error(`baseline model unavailable; restore the peer model configuration and run ahub restart ${this.id} before retrying`); if (rosterEpoch !== this.rosterEpoch || !this.acceptingTools) throw new Error("Pi is off roster or stopped"); if (requested) { if (selection?.model !== undefined) await this.applyRequestedModel(requested); else await this.setRequestedModel(requested); this.runtimeModelSelected = selection?.model !== undefined; } if (rosterEpoch !== this.rosterEpoch || !this.acceptingTools) throw new Error("Pi is off roster or stopped"); await this.captureTurnModel(requested); if (rosterEpoch !== this.rosterEpoch || !this.acceptingTools) throw new Error("Pi is off roster or stopped"); this.noteActivity(); attempted = true; if (deliveryId) this.activeDeliveryIds.add(deliveryId); const recordPrompt = this.turnRecordPrompt(""); const message = [recordPrompt, envs.some(env => env.private || remoteEnvelope(env)) ? undefined : this.opts.titlePreface?.(), renderDigest(envs, true)].filter(Boolean).join("\n"); if (this.opts.mode === "tui") { const pending = this.sendTui({ type: "prompt", message }); promptId = this.pendingPromptId; await pending; } else await this.sendRpc({ type: "prompt", message }); if (promptId !== undefined && promptId !== this.pendingPromptId) return; if (this.fencedPrompt && this.rosterDetached) { if (deliveryId && this.activeDeliveryIds.delete(deliveryId)) this.delivery({ id: deliveryId, state: "needs_review", reason: "Pi native activity changed before prompt acceptance was confirmed" }); this.setState("offline"); return; } if (rosterEpoch !== this.rosterEpoch || !this.acceptingTools) throw new Error("Pi is off roster or stopped"); try { selection?.applied(); } catch { /* Only prompt acceptance proves this turn used the selected model or unchanged native default. */ } if (deliveryId && this.activeDeliveryIds.has(deliveryId)) this.delivery({ id: deliveryId, state: "accepted" }); } catch (error) { if (promptId !== undefined && promptId !== this.pendingPromptId) return; if (error instanceof PiPromptUncertain) { this.pendingPromptId = undefined; await this.detachForRoster(); return; } if (error instanceof PiPromptNotStarted && error.promptId === this.pendingPromptId) { this.pendingPromptId = undefined; if (deliveryId) this.activeDeliveryIds.delete(deliveryId); if (deliveryId) this.delivery({ id: deliveryId, state: "failed_safe", reason: error.message }); else this.onFailed?.(envs); await this.detachForRoster(); return; } if (this.fencedPrompt && this.pendingPromptId && this.rosterDetached) { this.pendingPromptId = undefined; if (deliveryId && this.activeDeliveryIds.delete(deliveryId)) this.delivery({ id: deliveryId, state: "needs_review", reason: "Pi prompt acknowledgement is uncertain after personal native activity" }); this.setState("offline"); return; } if (rosterEpoch !== this.rosterEpoch) { if (!attempted && deliveryId) this.delivery({ id: deliveryId, state: "failed_safe", reason: "Pi withdrawn before native dispatch" }); return; } if (!attempted) { this.activeEnvs = []; this.setState("idle"); if (deliveryId) this.delivery({ id: deliveryId, state: "failed_safe", reason: error instanceof Error ? error.message : String(error) }); throw error; } // The prompt may have reached Pi even if its acknowledgement was lost. // Fence the owner before reporting failure; never return it to the bus for replay. const reason = error instanceof Error ? error.message : String(error); if (deliveryId && /process is not running/i.test(reason)) { this.activeDeliveryIds.delete(deliveryId); this.delivery({ id: deliveryId, state: "failed_safe", reason }); } await this.terminateFailedTurn(error instanceof Error ? error : new Error(reason)); } finally { if (promptId !== undefined && this.pendingPromptId === promptId) this.pendingPromptId = undefined; } } async steer(envs: Envelope[], deliveryId?: string): Promise { if (this.state !== "busy" || !this.acceptingTools || (this.fencedPrompt && this.pendingPromptId && this.hubPromptGeneration === undefined) || envs.some((e) => e.kind !== "chat" || e.private || e.priority !== "important")) { const reason = `Pi workflow/private messages must queue${this.rosterDetached ? ": off roster" : this.rosterUnownedRun ? ": native turn pending" : ""}`; if (deliveryId) this.delivery({ id: deliveryId, state: "failed_safe", reason }); throw new Error(reason); } const rosterEpoch = this.rosterEpoch; const reply = replyParent([...this.activeEnvs, ...envs]); this.activeEnvs.push(...envs); this.currentReply = reply; try { if (deliveryId) this.activeDeliveryIds.add(deliveryId); if (this.opts.mode === "tui") await this.sendTui({ type: "steer", message: renderDigest(envs, true) }); else await this.sendRpc({ type: "steer", message: renderDigest(envs, true) }); if (deliveryId && this.activeDeliveryIds.has(deliveryId)) this.delivery({ id: deliveryId, state: "accepted" }); } catch (error) { if (rosterEpoch !== this.rosterEpoch) return; await this.terminateFailedTurn(error instanceof Error ? error : new Error(String(error))); } } /** * Pi's current native session model is session evidence; a failed or placeholder read leaves the acknowledged configured model. */ private async captureTurnModel(requested: string | undefined): Promise { this.turnModel = undefined; if (this.opts.mode !== "tui") { try { const state = await this.waitRpc("get_state", 5_000); const id = state.success === true ? stateModelId(state.data) : undefined; if (id) { this.turnModel = { model: id, evidence: "session" }; return; } } catch { /* optional metadata: the turn goes on without it */ } } else { if (this.verifiedOwner() && this.sessionModel) { this.turnModel = { model: this.sessionModel, evidence: "session" }; return; } } if (requested) this.turnModel = { model: requested, evidence: "configured" }; } observedModel(): ModelObservation | undefined { const model = this.turnModel; this.turnModel = undefined; return model; } getRequestedModel(): string { return this.requestedModel; } getBaselineRequestedModel(): string { return this.baselineRequestedModel; } async setRequestedModel(model: string): Promise { await this.applyRequestedModel(model); this.baselineRequestedModel = model; } private async applyRequestedModel(model: string): Promise { if (!this.acceptingTools) throw new Error("Pi is off roster or stopped"); const slash = model.indexOf("/"); const provider = "agent-hub-local"; const modelId = model; if (this.opts.mode === "tui") { if (this.sessionModel !== modelId) this.sessionModel = undefined; await this.sendTui({ type: "set_model", provider, modelId }); } else await this.sendRpc({ type: "set_model", provider, modelId }); this.requestedModel = model; } private handleBridgeEvent(event: any): void { if (this.fencedPrompt && this.opts.mode === "tui" && !this.rosterUnownedRun && ["agent_start", "agent_end", "agent_settled"].includes(event.type) && typeof event.promptId === "string" && event.promptId !== this.hubPromptId) return; if (this.fencedPrompt && this.opts.mode === "tui" && (this.activeEnvs.length > 0 || this.pendingPromptId || this.hubPromptId) && !this.rosterDetached && !this.rosterUnownedRun && !this.stopping && ["agent_start", "agent_end", "agent_settled"].includes(event.type)) { const bound = this.verifiedOwner() && (event.sessionId === undefined || event.sessionId === this.sessionId); if (!bound || !Number.isSafeInteger(event.generation) || event.generation < this.budgetGeneration) return; const owned = this.hubPromptId !== undefined && event.promptId === this.hubPromptId; if (event.type === "agent_start" && event.generation > this.budgetGeneration) { if (owned) this.hubPromptGeneration = event.generation; else { if (this.pendingPromptId || this.activeEnvs.length) { // Await the prompt's exact ACK before deciding whether its effect was absent or uncertain. this.observeTurn("aborted"); this.rosterDetached = true; this.rosterEpoch++; this.clearWatchdog(); this.activeEnvs = []; this.currentReply = undefined; this.settledText = ""; this.settledError = ""; this.abortTools(); if (!this.pendingPromptId) { for (const id of this.activeDeliveryIds) this.delivery({ id, state: "needs_review", reason: "Pi personal native activity replaced the accepted hub turn" }); this.activeDeliveryIds.clear(); this.setState("offline"); } } else { this.rosterUnownedRun = true; this.setState("busy"); this.clearWatchdog(); } } } else if (!this.rosterUnownedRun && (!owned || event.generation !== this.hubPromptGeneration)) return; } if (this.rosterDetached || this.rosterUnownedRun) { // The shipped extension's legacy agent_start omits sessionId. Its authenticated bridge // and still-verified owner bind that event to this session; an explicit mismatch never does. const bound = !this.stopping && this.verifiedOwner() && (event.sessionId === undefined || event.sessionId === this.sessionId); if (bound && event.type === "agent_start" && Number.isSafeInteger(event.generation) && event.generation > this.budgetGeneration) { this.rosterLifecycleRevision++; this.budgetGeneration = event.generation; this.noteActivity(); // personal native activity also revokes an earlier ID-only empty-resume proof } // Snapshot ACKs and lifecycle events use separate requests, so their arrival order is not native state order. if (bound && event.type === "agent_settled" && (event.generation === undefined || event.generation === this.budgetGeneration)) this.rosterLifecycleRevision++; if (!bound && event.type !== "session_shutdown") return; } if (this.rosterDetached && event.type !== "session_shutdown") return; if (this.rosterUnownedRun && event.type !== "session_shutdown") { if (event.type === "agent_settled" && (event.generation === undefined || event.generation === this.budgetGeneration)) { this.rosterUnownedRun = false; this.agentRunning = false; if (!this.stopping && this.verifiedOwner() && !this.activeTools) this.setState("idle"); } return; } if (this.stopping && ["agent_start", "agent_end", "agent_settled"].includes(event.type)) return; // Settled generation replay cannot become a failure of the next delivered prompt. if (["agent_end", "agent_settled"].includes(event.type) && Number.isSafeInteger(event.generation) && event.generation === this.settledGeneration) return; if (event.type === "session_start") { if (!this.ownerClaimed) { this.ownerClaimed = true; this.ownerToken = String(event.ownerToken ?? ""); } this.approvalTurnAbort = event.approvalTurnAbort === true; this.fencedPrompt ||= event.fencedPrompt === true; this.sessionId = String(event.sessionId ?? ""); this.sessionFile = String(event.sessionFile ?? ""); this.ownerPid = Number.isInteger(event.pid) ? event.pid : undefined; this.ownerSignature = typeof event.signature === "string" ? event.signature : undefined; if ((this.opts.sessionId && this.sessionId !== this.opts.sessionId) || (this.opts.sessionFile && this.sessionFile !== this.opts.sessionFile)) { this.opts.log?.(`[${this.id}] Pi session identity mismatch`); return; } this.sessionModel = stateModelId(event); this.titleRevision = -1; this.titleEpoch++; this.nativeTitleEpoch = typeof event.titleEpoch === "string" && event.titleEpoch ? event.titleEpoch : undefined; this.observeTitle(event.sessionName, event.titleRevision, event.titleEpoch); this.rememberTerminalOwner(); this.startOwnerMonitor(); if (this.opts.mode === "tui") { this.started = true; this.setState("idle"); } } if ((event.type === "session_title" || event.type === "agent_start" && Object.hasOwn(event, "sessionName")) && event.sessionId === this.sessionId && this.verifiedOwner()) this.observeTitle(event.sessionName, event.titleRevision, event.titleEpoch); if (event.type === "session_shutdown") { this.observedTitle = undefined; this.titleRevision = -1; this.nativeTitleEpoch = undefined; this.onDoing?.("reset"); if (this.stopCause === undefined) this.stopCause = "failure"; const exit = this.exitMetadata("session_shutdown"); this.shutdownExit ??= exit; // headless waits for the OS exit, retaining the pre-cleanup turn and stop facts this.stopping = true; this.ownerClaimed = false; this.clearOwnerMonitor(); this.resolveTuiExit?.(); this.resolveTuiExit = undefined; this.fail(new Error("Pi session shut down before settlement")); if (this.opts.mode === "tui") this.reportExit(exit); } if (event.type === "tool_abort" && this.agentRunning && this.ownerClaimed && this.ownerPid && this.ownerSignature && this.readOwnerSignature(this.ownerPid) === this.ownerSignature && event.sessionId === this.sessionId && event.generation === this.budgetGeneration && typeof event.toolCallId === "string" && event.toolCallId.length > 0 && event.toolCallId.length <= 512) { const pending = this.pendingToolGenerations.get(event.toolCallId); if (pending && pending.generation === event.generation) pending.abort.abort(); else { // a native abort may arrive before its HTTP tool request; fence that call in this generation // ponytail: 64 early aborts per turn; fence further calls rather than forget a cancellation. // A native per-call acknowledgement would replace this bounded early-arrival cache. if (this.abortedToolIds.size >= 64 && !this.abortedToolIds.has(event.toolCallId)) this.abortIdsOverflow = true; else this.abortedToolIds.add(event.toolCallId); } } if (event.type === "agent_start") { const generation = Number.isSafeInteger(event.generation) ? event.generation : this.budgetGeneration + 1; if (generation <= this.budgetGeneration) return; if (this.opts.mode === "tui" && this.sessionModel && this.verifiedOwner() && (event.sessionId === undefined || event.sessionId === this.sessionId)) this.turnModel = { model: this.sessionModel, evidence: "session" }; this.modelStep = 0; this.ceilingUnsafe = false; this.turnObserved = false; this.approvalExpiries = 0; this.approvalAnswerEpoch = undefined; this.approvalStopReason = ""; this.approvalAbortSent = false; this.abortedToolIds.clear(); this.abortIdsOverflow = false; this.usageSeen.clear(); this.ceilingStops.clear(); this.abortTools(); this.executionAbort = new AbortController(); this.budgetGeneration = generation; this.noteActivity(); this.agentRunning = true; this.setState("busy"); } // #179: the extension's tool-step ceiling signal. Only a schema-valid event bound to THIS session, // THIS turn generation and a running turn is stored; the first signal of a turn stands. Anything // else (stale, cross-session, free text) is dropped and the failure stays unclassified. if (event.type === "ceiling") { const ceiling = piToolStepCeiling(event); if (ceiling && ceiling.sessionId === this.sessionId && ceiling.generation === this.budgetGeneration && this.agentRunning && this.state === "busy" && !this.ceilingStops.has(ceiling.generation)) { this.ceilingStops.set(ceiling.generation, ceiling); // Tools may settle before agent_settled; that cannot erase uncertainty at the ceiling. this.ceilingUnsafe = this.activeTools > 0 || this.pendingToolGenerations.size > 0; for (const old of this.ceilingStops.keys()) if (old < ceiling.generation - 8) this.ceilingStops.delete(old); } } if (event.type === "activity" && this.state === "busy") this.touch(); if (event.type === "pi_model" && event.sessionId === this.sessionId && this.verifiedOwner() && this.sessionId) { this.sessionModel = stateModelId(event); this.opts.onContext?.(undefined, this.sessionId); } if (event.type === "pi_usage" && this.agentRunning && this.state === "busy" && event.sessionId === this.sessionId && event.generation === this.budgetGeneration && this.verifiedOwner() && this.sessionId) { this.sessionModel = stateModelId(event); this.opts.onContext?.(event.context, this.sessionId); } if (event.type === "tokens" && this.state === "busy" && typeof event.id === "string" && event.id.length <= 100 && Number.isSafeInteger(event.tokens) && event.tokens >= 0 && !this.usageSeen.has(event.id)) { this.usageSeen.add(event.id); if (this.usageSeen.size > 1000) this.usageSeen.delete(this.usageSeen.values().next().value!); if (event.tokens > 0) this.opts.onTokens?.(event.tokens); } if (event.type === "agent_end") { if (Number.isSafeInteger(event.generation) && event.generation !== this.budgetGeneration) return; clearTimeout(this.executionBudgetTimer); this.executionBudgetTimer = undefined; const generation = Number.isSafeInteger(event.generation) ? event.generation : this.budgetGeneration; const budgetStop = this.budgetStops.get(generation); if (budgetStop) this.executionAbort?.abort(); this.settledText = typeof event.text === "string" ? event.text : ""; this.settledCancelled = !budgetStop && event.cancelled === true; this.settledError = budgetStop ?? (event.failed ? String(event.error ?? "Pi agent run failed") : ""); } if (event.type === "agent_settled") { if (Number.isSafeInteger(event.generation) && event.generation !== this.budgetGeneration) return; this.settledGeneration = this.budgetGeneration; clearTimeout(this.executionBudgetTimer); this.executionBudgetTimer = undefined; this.agentRunning = false; if (typeof event.text === "string" && event.text.trim()) this.settledText = event.text; const generation = Number.isSafeInteger(event.generation) ? event.generation : this.budgetGeneration; const approvalStopReason = this.approvalStopReason; const text = this.settledText.trim(); const error = approvalStopReason || this.budgetStops.get(generation) || this.settledError; const cancelled = this.settledCancelled; const ceiling = this.ceilingStops.get(generation); const settledCeiling = !!ceiling && !!error && !cancelled && !approvalStopReason && !this.budgetStops.has(generation) && !this.ceilingUnsafe && !this.activeTools && !this.pendingToolGenerations.size && this.acceptingTools; const ceilingReason = settledCeiling && ceiling ? `ceiling steps ${ceiling.count}/${ceiling.limit}` : undefined; this.budgetStops.delete(generation); this.ceilingStops.delete(generation); this.settledText = ""; this.settledError = ""; this.settledCancelled = false; // Answer the peers this turn was for, not every peer on the bus (issue #29). activeEnvs still holds the // whole delivery here, steered additions included. const reply = { inReplyTo: this.currentReply, to: replyAudience(this.activeEnvs) }; if (cancelled) { this.observeTurn("aborted"); this.onMessage?.("Pi turn cancelled; inspect any partial effects before continuing.", reply); } else if (error?.startsWith("execution budget")) { this.observeTurn("aborted"); this.onMessage?.(`Pi stopped at the execution budget: ${error}. Inspect partial work before continuing.`, reply); } else if (approvalStopReason) { this.observeTurn("aborted"); this.onMessage?.(approvalStopReason, reply); } else if (error && !this.turnObserved) { this.turnObserved = true; void this.opts.onTurnFailure?.(this.activeEnvs, error, ceiling, settledCeiling); } else if (error) { /* This logical turn was already observed, including legacy unnumbered replays. */ } else { this.observeTurn("success"); if (text) this.finalAnswer(text, reply); } for (const id of this.activeDeliveryIds) this.delivery({ id, state: approvalStopReason || settledCeiling ? "completed" : error || cancelled ? "needs_review" : "completed", ...(ceilingReason ? { reason: ceilingReason } : error || cancelled ? { reason: error || "Pi turn cancelled; partial effects are possible" } : {}) }); this.activeDeliveryIds.clear(); this.currentReply = undefined; this.activeEnvs = []; this.hubPromptId = undefined; this.hubPromptGeneration = undefined; this.executionAbort?.abort(); this.executionAbort = undefined; this.approvalExpiries = 0; this.approvalAnswerEpoch = undefined; this.approvalStopReason = ""; this.approvalAbortSent = false; this.abortedToolIds.clear(); this.abortIdsOverflow = false; if (this.state === "busy" && !this.activeTools) this.setState("idle"); } } private onOutput(chunk: string): void { this.buffer += chunk; let index: number; while ((index = this.buffer.indexOf("\n")) >= 0) { const line = this.buffer.slice(0, index).replace(/\r$/, ""); this.buffer = this.buffer.slice(index + 1); if (!line) continue; try { this.handleRpc(JSON.parse(line) as RpcMessage); } catch (error) { this.opts.log?.(`[${this.id}] invalid Pi RPC output: ${(error as Error).message}`); } } } private nextTuiCommand(timeout: number): Promise | undefined> { let next = this.tuiQueue.shift(); while (next) { const pending = this.tuiCommands.get(String(next.id)); if (pending && pending.current?.() !== false) { pending.onDispatch?.(); return Promise.resolve(next); } if (pending) { this.tuiCommands.delete(String(next.id)); pending.reject(new Error("Pi session title admission changed before dispatch")); } next = this.tuiQueue.shift(); } return new Promise((resolvePromise) => { const entry = { resolve: resolvePromise, timer: setTimeout(() => { const i = this.tuiWaiters.indexOf(entry); if (i >= 0) this.tuiWaiters.splice(i, 1); resolvePromise(undefined); }, timeout) }; this.tuiWaiters.push(entry); }); } private sendTui(command: Record, current?: () => boolean, onDispatch?: () => void): Promise { if (current?.() === false) return Promise.reject(new Error("Pi session title admission changed before dispatch")); const id = `ahub-${++this.seq}`; const fenced = this.fencedPrompt && command.type === "prompt"; if (fenced) { this.pendingPromptId = id; this.hubPromptId = id; this.hubPromptGeneration = undefined; } const wire = { id, ...command, ...(fenced ? { sessionId: this.sessionId, generation: this.budgetGeneration } : {}) }; return new Promise((resolvePromise, reject) => { const timer = setTimeout(() => { this.tuiCommands.delete(id); this.tuiQueue = this.tuiQueue.filter((queued) => queued.id !== id); reject(new Error(`Pi TUI ${String(command.type)} acknowledgement timed out`)); }, 30_000); this.tuiCommands.set(id, { command: wire, current, onDispatch, resolve: (value) => { clearTimeout(timer); resolvePromise(value); }, reject: (error) => { clearTimeout(timer); reject(error); } }); const waiter = this.tuiWaiters.shift(); if (waiter) { clearTimeout(waiter.timer); onDispatch?.(); waiter.resolve(wire); } else this.tuiQueue.push(wire); }); } private handleRpc(message: RpcMessage): void { if (this.acceptingTools && ["message_update", "tool_execution_update"].includes(message.type ?? "") && this.state === "busy") this.touch(); if (message.type === "agent_settled") return; // The authenticated extension is the single lifecycle source. if (message.id !== undefined) { const pending = this.pending.get(String(message.id)); if (pending) { this.pending.delete(String(message.id)); message.success === false ? pending.reject(new Error(message.error ?? "Pi RPC command failed")) : pending.resolve(message); } } } private sendRpc(command: Record): Promise { if (!this.proc?.stdin.writable) return Promise.reject(new Error("Pi process is not running")); const id = `ahub-${++this.seq}`; return new Promise((resolvePromise, reject) => { const timer = setTimeout(() => { this.pending.delete(id); reject(new Error(`Pi RPC ${String(command.type)} timed out`)); }, 30_000); this.pending.set(id, { resolve: (m) => { clearTimeout(timer); resolvePromise(m); }, reject: (e) => { clearTimeout(timer); reject(e); } }); this.proc!.stdin.write(`${JSON.stringify({ id, ...command })}\n`); }); } private async waitRpc(command: string, timeout: number): Promise { let timer: ReturnType | undefined; try { return await Promise.race([this.sendRpc({ type: command }), new Promise((_, reject) => { timer = setTimeout(() => reject(new Error(`Pi ${command} timed out`)), timeout); })]); } finally { clearTimeout(timer); } } private exitMetadata(cause: PiExit["cause"]): PiExit { return { cause, code: null, signal: null, expected: this.stopping, started: this.started, turnActive: this.agentRunning || this.activeEnvs.length > 0, toolActive: this.activeTools > 0, ...(this.lastToolName ? { lastToolName: this.lastToolName } : {}) }; } private reportExit(exit: PiExit): void { if (this.exitReported) return; this.exitReported = true; const line = `[${this.id}] Pi exit: cause=${exit.cause} code=${exit.code ?? "unknown"} signal=${exit.signal ?? "unknown"} expected=${exit.expected} started=${exit.started} turnActive=${exit.turnActive} toolActive=${exit.toolActive} lastTool=${exit.lastToolName ?? "none"}`; try { this.opts.log?.(line); } catch { /* reporting must not prevent owner settlement */ } try { this.opts.onExit?.(exit); } catch { /* the owner is already offline */ } } private fail(error: Error): void { this.terminalOwnerObservation = undefined; const approvalStopReason = this.approvalStopReason; this.abortTools(); this.agentRunning = false; this.approvalExpiries = 0; this.approvalAnswerEpoch = undefined; this.approvalStopReason = ""; this.approvalAbortSent = false; this.abortedToolIds.clear(); this.abortIdsOverflow = false; for (const pending of this.pending.values()) pending.reject(error); this.pending.clear(); const envs = this.activeEnvs; this.activeEnvs = []; for (const id of this.activeDeliveryIds) this.delivery({ id, state: "needs_review", reason: error.message }); this.activeDeliveryIds.clear(); if (envs.length && !this.requestedStopReason && !this.rosterDetached && !this.turnObserved) { this.turnObserved = true; this.onMessage?.(approvalStopReason ? `${approvalStopReason} Pi is offline because its extension could not abort the turn; restart with ahub pi and settle the held delivery after inspecting prior work.` : "Pi turn failed; inspect its session and any partial effects before continuing.", { inReplyTo: this.currentReply }); if (!approvalStopReason && !(error instanceof ApprovalWaitStop)) void this.opts.onTurnFailure?.(envs, error.message).catch(() => this.opts.log?.("Pi failure handoff could not be completed")); } this.currentReply = undefined; this.setState("offline"); } private startOwnerMonitor(): void { this.clearOwnerMonitor(); if (this.opts.mode !== "tui" || !this.ownerPid || !this.ownerSignature) return; this.ownerMonitor = setInterval(() => this.checkOwner(), 500); this.ownerMonitor.unref?.(); } private checkOwner(): void { if (!this.ownerPid) { this.terminalOwnerObservation = undefined; return; } const current = this.readOwnerSignature(this.ownerPid); if (current !== undefined && current === this.ownerSignature) { this.rememberTerminalOwner(); return; } this.terminalOwnerObservation = undefined; // Unknown process identity retains the existing live-owner fence, but is never terminal proof. if (current === undefined) { try { process.kill(this.ownerPid, 0); return; } catch { /* positively gone */ } } const exit = this.exitMetadata("owner_lost"); this.stopping = true; this.ownerClaimed = false; this.clearOwnerMonitor(); this.resolveTuiExit?.(); this.resolveTuiExit = undefined; for (const pending of this.tuiCommands.values()) pending.reject(new Error("Pi owner exited")); this.tuiCommands.clear(); this.tuiQueue = []; this.fail(new Error("Pi owner process exited without session_shutdown")); this.reportExit(exit); } private clearOwnerMonitor(): void { if (this.ownerMonitor) clearInterval(this.ownerMonitor); this.ownerMonitor = undefined; } private async endApprovalTurn(generation: number, reason: string): Promise { if (!this.agentRunning || generation !== this.budgetGeneration || this.approvalStopReason !== reason || !this.acceptingTools || this.state === "offline") return; this.executionAbort?.abort(); if (this.approvalTurnAbort) { try { await this.sendTui({ type: "abort_budget", generation, cause: "approval", reason }); return; } catch { if (generation !== this.budgetGeneration || !this.agentRunning) return; } } this.opts.log?.(`[${this.id}] approval turn abort unsupported; Pi goes offline. Restart with ahub pi and settle the held delivery after inspecting prior work.`); await this.terminateFailedTurn(new ApprovalWaitStop(reason)); } private async terminateFailedTurn(error: Error, failureCause?: DeliveryFailureCause): Promise { const envs = this.activeEnvs.slice(), reply = this.currentReply; this.stopping = true; try { await this.stop(undefined, failureCause, "failure"); // The process exit handler may already have reported this failure. if (this.activeEnvs.length) this.fail(error); } catch (stopError) { if (stopError instanceof PiToolSettlementFailure && this.state === "offline") { this.opts.log?.(`Pi teardown completed with a managed-tool settlement failure: ${(stopError as Error).message}`); if (this.activeEnvs.length) this.fail(error); return; } this.activeEnvs = envs; this.currentReply = reply; this.stopping = true; this.setState("busy"); this.opts.log?.("Pi owner could not be stopped; session remains fenced, no automatic escalation"); } } protected override onWatchdog(): void { if (this.stopping || this.rosterDetached || this.rosterUnownedRun) return; if (this.activeTools) { this.touch(); return; } void this.terminateFailedTurn(new Error("Pi run became inactive before agent_settled"), "timeout"); } } export function isPiPeer(value: unknown): value is PiPeer { return value instanceof PiPeer; }