// Session registry and wrapper for live sessions: each one is a `pi --mode rpc` child (with lib/pi/tau-extension.ts) // started by its host's daemon and driven through RpcProcess (lib/pi/rpc-process.ts) over an RpcTransport. import { createHash, randomUUID } from "crypto"; import { validateAgentImages } from "./image-attachments"; import { hasVisibleAssistantContent } from "./assistant-response"; import { applyMessageDelta, isDeltaUpdate, withStreamedArguments } from "./message-delta"; import { invalidateModelsCache } from "./models-cache"; import { RpcCommandError, RpcCommandTimeoutError, RpcProcess, type RpcFrame } from "./pi/rpc-process"; import type { RpcTransport } from "./pi/rpc-transport"; import { cacheSessionPath } from "./session-reader"; import { allowFileRoot } from "./file-access"; import { loadWebServerSettings } from "./web-settings"; import { AGENT_TOOL_DEFINITIONS, AGENT_TOOL_NAMES, AgentToolGuard, executeAgentTool, type AgentToolContext, type AgentToolDeliverInput, type AgentToolDeliverResult, type AgentToolSessionOps, } from "./agent-tools"; import type { AgentToolHost } from "./agent-tool-hosts"; import { createGithubToolOps, GITHUB_REPLAY_SAFE_TOOLS, GITHUB_TOOL_NAMES } from "./github/tools"; import { markShuttingDown, recordRunningSessions, resumeOnHostLink, takeInterruptedSessions, type InterruptibleSession } from "./session-resume"; import { RESUME_PROMPT } from "./hosts/host-resume"; import { samePath } from "./paths"; import { isRecord } from "./type-guards"; import type { MessageOrigin } from "./message-origin"; import { isClientMessageId, readQueueSnapshot } from "./client-message-ids"; import { createNotificationDetector, DIALOG_UI_METHODS, isNotificationAnswerable } from "./notification-events"; import { publishNotification, publishNotificationDismiss, publishNotificationForgotten } from "./notification-hub"; import { eventWithToolResultImageUrls } from "./media-cache"; import type { BashResultInfo, PiModel, ExtensionUiResponse, RpcAskDialogQuestion, RpcAvailableSlashCommand, RpcSessionState, SessionStatsInfo, WebSessionState, } from "./pi-types"; import type { AgentConfirmPayload, AgentMessage, CrossSessionHostToolCall, CrossSessionHostToolEvent, ExitedRpcSession, ExtensionWidgetItem } from "./types"; import { isLinkUp, type Host, type HostStatus, type SpawnRequest } from "./hosts/host"; import { freezeHostLinks, getHost, hostOwnsLifecycle, isNotifier, lastUplinkAt, listHosts, orphanExit } from "./hosts/hub"; import { CREATION_ID_RE, HISTORY_MUTATING_COMMANDS, HostOpError, PEER_MESSAGE_FRAME } from "./hosts/link-protocol"; import { LOCAL_HOST_ID } from "./hosts/registry"; import type { OpResult } from "./hosts/session-ops"; import { hostForSessionId, invalidateHostSessionList, listSessionsAllHosts, sessionSpawnTarget } from "./hosts/session-index"; import { loadPools, poolProjectBindings } from "./hosts/pools"; import { PoolStartError, requireProviderLogin, startPooledSession } from "./hosts/pool-starts"; import { comparableProjectPath } from "./comparable-path"; import type { SessionLiveSnapshot, SessionLiveToolEvent, SessionStreamCursor } from "./session-sync"; // ============================================================================ // Types // ============================================================================ /** The `/tau_edit` result: the leaf moved to just before the edited user message. */ export interface SessionEditResult { sessionId: string; cancelled: boolean; leafId: string | null; } export interface AgentEvent { type: string; web: SessionStreamCursor; [key: string]: unknown; } type EventListener = (event: AgentEvent) => void; type UnsequencedAgentEvent = { type: string; [key: string]: unknown }; interface CompactionResultLike { summary?: string; tokensBefore?: number; estimatedTokensAfter?: number; } const IDLE_DESTROY_MS = 10 * 60 * 1000; /** * How long a session may sit with **no web UI attached** before its pi child is * torn down. IDLE_DESTROY_MS (10min) is the backstop for a session that keeps * receiving traffic; this is the much faster path for "the user closed the tab * and walked away", so abandoned children don't hold a slot for 10 minutes. * * The floor is set by the *client*, not the server: when an SSE stream dies the * browser retries with capped backoff (`EVENT_STREAM_RETRY_MAX_MS` = 30s in * `hooks/useAgentSession-stream.ts`), and a backgrounded tab clamps its timers * to ~1/min. A window anywhere near 60s therefore races the reconnect and turns * a returning tab into a 409 "Session is not managed by tau" plus a cold * respawn. 120s keeps ~2x the retry ceiling and still reclaims 5x faster than * the idle backstop. Set `TAU_DISCONNECT_DESTROY_MS=0` to disable reaping * and fall back to IDLE_DESTROY_MS alone. */ const DISCONNECT_DESTROY_MS = process.env.TAU_DISCONNECT_DESTROY_MS !== undefined ? Math.max(0, Number(process.env.TAU_DISCONNECT_DESTROY_MS) || 0) : 120_000; const READY_TIMEOUT_MS = 120_000; const GET_STATE_TIMEOUT_MS = 5_000; /** The handshake of a just-started or rejoined child: pi's post-`ready` startup work (model refresh, plugin and * marketplace updates, hooks) can hold its first answers well past GET_STATE_TIMEOUT_MS. */ const STARTUP_COMMAND_TIMEOUT_MS = 30_000; const EDIT_TIMEOUT_MS = 15_000; /** Cap on the *acknowledgement* of a prompt frame — not on model execution. * pi acks a prompt as soon as it accepts it and the run then reports through * events (agent_start/agent_end), so an ack that never arrives means the child * is wedged: without this the API request (and the UI spinner behind it) would * stay pending forever. Generous enough to cover slow local startup work the * child does before acking. Finite pooled model/thinking/name setup shares * this budget; ordinary commands keep their existing semantics. */ const PROMPT_ACK_TIMEOUT_MS = 30_000; const NON_TERMINAL_CONTINUATION_GRACE_MS = 2_000; const AWAITING_AGENT_START_TIMEOUT_MS = 10_000; const RESTARTING_MESSAGE = "This session is restarting — retry in a moment."; /** Answer to a replayed server agent tool call that changes things: it may have run before the restart. */ const AGENT_TOOL_UNKNOWN_OUTCOME = "tau restarted while this ran; the outcome is unknown, check with list_sessions before retrying"; const GITHUB_UNKNOWN_OUTCOME = "tau restarted while this ran; the outcome is unknown. Inspect workflow runs with github_run_list or github_read; inspect comments or threads with github_read for other writes. Do not automatically repeat a dispatch or rerun."; /** A GitHub write is checked on GitHub, not in the session list. */ const unknownOutcome = (toolName: unknown) => (typeof toolName === "string" && GITHUB_TOOL_NAMES.has(toolName) ? GITHUB_UNKNOWN_OUTCOME : AGENT_TOOL_UNKNOWN_OUTCOME); /** * Failure raised by tau itself (not by pi) carrying a stable snake_case * code. API routes forward `{ error, code }` so the client dictionary can * localize it via `errors.` while unknown codes fall back to the text. */ export class WebRpcError extends Error { readonly code: string; /** `host_offline` only: "refused" when nothing was sent, "unknown" when the * link dropped after the command left, so it may still run on the host. */ readonly delivery?: "refused" | "unknown"; constructor(message: string, code: string, delivery?: "refused" | "unknown") { super(message); this.name = "WebRpcError"; this.code = code; if (delivery) this.delivery = delivery; } } /** Shape check for an ask-dialog `answers` payload. */ export function isAskAnswers(value: unknown): boolean { return Array.isArray(value) && value.every((answer: unknown) => isRecord(answer) && typeof answer.id === "string" && Array.isArray(answer.selectedOptions) && answer.selectedOptions.every((option: unknown) => typeof option === "string") && (answer.customInput === undefined || typeof answer.customInput === "string")); } /** * Convert a notification answer to the `ui_response` command the desktop * dialog sends, checking it against the pending dialog's own arguments. A * cancel carries no `value` (a missing value is a cancel). */ function uiResponseCommand( pending: { type: string; [key: string]: unknown }, response: ExtensionUiResponse, ): { type: "ui_response"; id: number | string; value?: unknown } { const id = pending.id as number | string; const method = typeof pending.method === "string" ? pending.method : ""; const args = Array.isArray(pending.args) ? pending.args : []; if ("cancelled" in response) return { type: "ui_response", id }; if (method === "askDialog") { if (!("answers" in response) || !isAskAnswers(response.answers)) { throw new WebRpcError("Invalid ask dialog answers", "invalid_ask_answers"); } const questions = Array.isArray(args[0]) ? args[0] as RpcAskDialogQuestion[] : []; const problem = askAnswersProblem(response.answers, questions); if (problem) throw new WebRpcError(`Invalid ask dialog answers: ${problem}`, "invalid_ask_answers"); return { type: "ui_response", id, value: { kind: "submit", results: response.answers.map((answer, index) => { const question = questions[index]; return { id: answer.id, question: question.question, options: Array.isArray(question.options) ? question.options.map((option) => option.label) : [], multi: question.multi === true, selectedOptions: answer.selectedOptions, ...(answer.customInput !== undefined ? { customInput: answer.customInput } : {}), }; }), }, }; } if ("answers" in response) throw new WebRpcError("This dialog does not take answers", "invalid_ask_answers"); if (method === "confirm") { if (!("confirmed" in response)) throw new WebRpcError("This dialog takes a confirmation", "invalid_dialog_answer"); return { type: "ui_response", id, value: response.confirmed }; } if (method === "select") { const items = Array.isArray(args[1]) ? args[1] : []; const labels = items .map((item) => (typeof item === "string" ? item : isRecord(item) && typeof item.label === "string" ? item.label : undefined)) .filter((label): label is string => label !== undefined); if (!("value" in response) || !labels.includes(response.value)) { throw new WebRpcError("The selected option is not offered by this dialog", "invalid_dialog_answer"); } return { type: "ui_response", id, value: response.value }; } if (!("value" in response)) throw new WebRpcError("This dialog takes a text answer", "invalid_dialog_answer"); return { type: "ui_response", id, value: response.value }; } /** * Why `answers` cannot answer `questions`, or null when they can. Mirrors the ask * dialog's own parsing, which rejects any mismatch: one * answer per question in request order, each naming its own question, only * labels that question offers, no label twice, and a single-select question * takes either one option or free text, never both. `customInput` is trimmed, so * blank free text counts as absent. Checking here keeps a rejected payload from * consuming the pending dialog, which would leave the ask tool failed. */ export function askAnswersProblem(answers: unknown, questions: unknown): string | null { if (!Array.isArray(questions)) return "the pending ask carries no questions"; if (!Array.isArray(answers)) return "answers must be an array"; if (answers.length !== questions.length) return `answers must carry ${questions.length} entries in question order`; for (const [index, raw] of questions.entries()) { const question = isRecord(raw) ? raw : {}; const id = typeof question.id === "string" ? question.id : ""; const answer = answers[index]; if (!isRecord(answer)) return `answer ${index} must be an object`; if (answer.id !== id) return `answer ${index} must have id ${JSON.stringify(id)}`; const options = Array.isArray(question.options) ? question.options : []; const labels = options.flatMap((option) => (isRecord(option) && typeof option.label === "string" ? [option.label] : [])); const selected = answer.selectedOptions; if (!Array.isArray(selected)) return `answer ${JSON.stringify(id)} must carry a selectedOptions array`; const chosen: string[] = []; for (const label of selected) { if (typeof label !== "string" || !labels.includes(label)) return `answer ${JSON.stringify(id)} selected unknown option ${JSON.stringify(label)}`; if (chosen.includes(label)) return `answer ${JSON.stringify(id)} selected ${JSON.stringify(label)} twice`; chosen.push(label); } const custom = answer.customInput; if (custom !== undefined && typeof custom !== "string") return `answer ${JSON.stringify(id)} customInput must be a string`; const text = typeof custom === "string" ? custom.trim() : ""; if (question.multi !== true && (chosen.length > 1 || (chosen.length > 0 && text !== ""))) { return `answer ${JSON.stringify(id)} is single-select but carries more than one answer`; } } return null; } // Commands forwarded to pi verbatim (request shape already matches rpc-types). const PASSTHROUGH_COMMANDS = new Set([ "abort", "set_thinking_level", "cycle_thinking_level", "cycle_model", "get_available_models", "set_auto_compaction", "set_auto_retry", "abort_retry", "abort_bash", "set_steering_mode", "set_follow_up_mode", "get_messages", "export_html", ]); // Commands that can carry user-attached images to the model. All of them must // pass the same server-side per-image/count/aggregate validation before the // payload reaches pi — a client is free to POST any of them directly. const IMAGE_BEARING_COMMANDS = new Set(["prompt", "steer", "follow_up"]); // pi-web commands with no pi RPC equivalent. The UI tolerates these failing. const UNSUPPORTED_COMMANDS: Record = { navigate_tree: "Branch navigation is not supported over the pi RPC protocol", get_tools: "Per-session tool listing is not supported over the pi RPC protocol", set_tools: "Changing tools on a running session is not supported over the pi RPC protocol; tool presets apply to new sessions", }; function toImageContents(value: unknown): Array<{ type: "image"; data: string; mimeType: string }> | undefined { const images = value as Array<{ type: "image"; data: string; mimeType: string }> | undefined; return images?.length ? images : undefined; } /** pi's CompactionResult has no post-compaction token count; approximate it * from the summary so the compaction banner can show savings instead of * "→ 0 tokens". */ function patchEstimatedTokensAfter(result: unknown): void { if (!result || typeof result !== "object") return; const compaction = result as CompactionResultLike; if (compaction.estimatedTokensAfter === undefined) { compaction.estimatedTokensAfter = Math.round((compaction.summary?.length ?? 0) / 4); } } // ============================================================================ // AgentSessionWrapper // Wraps one session's pi process (`pi --mode rpc` with lib/pi/tau-extension.ts) with the interface the rest of // the app expects (same command surface pi-web's in-process wrapper offered). // ============================================================================ /** No replacing frame after a successful prompt reply: expose uncertainty rather than leave it delivering. */ export const HANDOFF_FALLBACK_MS = 2 * 60_000; type HandOff = { error?: string; mayHaveBeenSent?: boolean }; export interface MessageReplacementWatch { handOff(): Promise; /** pi answered `command` under wire `id`: its `prompt_result` can settle the hand-off. */ replied(command: object, id: string): void; stop(): void; } const CHILD_EXITED: HandOff = { error: "pi exited before it showed the message", mayHaveBeenSent: true }; function queueTexts(value: unknown): string[] { if (!isRecord(value)) return []; return [value.steering, value.followUp].flatMap((list) => Array.isArray(list) ? list.filter((text): text is string => typeof text === "string") : []); } function messageText(message: Record): string { if (typeof message.content === "string") return message.content; return Array.isArray(message.content) ? message.content.flatMap((part) => isRecord(part) && part.type === "text" && typeof part.text === "string" ? [part.text] : []).join("") : ""; } /** Current native skill echoes carry the original draft in details.prompt; older echoes retain native skill name and * argument metadata. Only used by the active command watcher, never to settle an uncertain stored row. */ function matchesNativeSkill(message: Record, submitted: string): boolean { if (message.role !== "custom" || message.customType !== "skill-prompt" || message.attribution !== "user") return false; const details = isRecord(message.details) ? message.details : {}; if (typeof details.prompt === "string") return details.prompt.trim() === submitted.trim(); const invocation = /^\/skill:([^\s]+)(?:\s+([\s\S]*))?$/.exec(submitted.trim()); if (!invocation) return false; const content = messageText(message); const name = typeof details.name === "string" ? details.name : /User invoked the "([^"]+)" skill/.exec(content)?.[1]; const parts = content.split(/\nUser:\s*/); const args = typeof details.args === "string" ? details.args : parts.length > 1 ? parts[parts.length - 1] : ""; return name === invocation[1] && args.trim() === (invocation[2] ?? "").trim(); } /** Every mode requires both its command reply and a replacing frame. Baseline occurrence counts distinguish a new * identical queue chip from a stale one; pre-existing identical messages must echo before this one can claim an echo. * The command is shared with attachment preparation, so comparison uses the final text, never an empty prefix. */ function watchReplacement(wrapper: AgentSessionWrapper, command: Record, baseline: unknown, generation: number, competingPending: boolean, previousEntryIds?: string[]): MessageReplacementWatch { const { promise, resolve } = Promise.withResolvers(); const ambiguous: HandOff = { error: "Another message was dispatched while this message's native replacement was being confirmed", mayHaveBeenSent: true }; const clientMessageId = isClientMessageId(command.clientMessageId) ? command.clientMessageId : null; // A peer server's admission (the daemon's marker) also contends: its identical echo is not this command's proof. An // exact ID names this command's message whoever else writes meanwhile, so only text inference needs the sole window. const peers = wrapper.peerMessageCommands; const ownsWindow = () => clientMessageId !== null || (!competingPending && wrapper.getMessageCommandGeneration() === generation + 1 && wrapper.peerMessageCommands === peers); // The text rules need pi's user attribution. An exact ID identifies a native custom message by itself, but only a // displayed one: the browser never shows a hidden message, so it cannot replace the pending row there. const isUserInput = (message: Record) => message.role === "user" || (message.role === "custom" && (clientMessageId !== null ? message.display !== false : message.attribution === "user")); const initialQueue = clientMessageId ? [] : queueTexts(baseline); let priorQueue = initialQueue; let echoDebt: number | undefined; let seen = false; let stopped = false; let checkingExpansion = false; const boundary = previousEntryIds ? new Set(previousEntryIds) : null; const openedUserMessages = new Set(); let userMessageSeen = false; const gapsAtStart = wrapper.getFrameGaps(); let timer: NodeJS.Timeout | undefined; let commandId: string | undefined; let expansionRetry: NodeJS.Timeout | undefined; let retryPending = false; /** This command's `prompt_result` came while a slash template's context check still had to decide. */ let resultArrived = false; const unshown: HandOff = { error: "pi finished this message without showing it", mayHaveBeenSent: true }; const expectedText = () => typeof command.message === "string" && command.message ? command.message : Array.isArray(command.images) && command.images.length ? "[Image]" : ""; const finish = (outcome: HandOff) => { if (seen || stopped) return; seen = true; clearTimeout(expansionRetry); // Every channel receives the replacement before the removal, even if this listener was registered first. queueMicrotask(() => resolve(!outcome.error && !ownsWindow() ? ambiguous : outcome)); }; // Ordinary native templates don't echo their original slash token. While this idle claim is active, correlate its // new native user lifecycle to the sole new persisted user entry beyond the pre-dispatch boundary; the caller still // waits for THIS command's successful reply. Ambiguous/missing persisted context proves nothing. const checkExpandedUser = async (message: Record) => { if (checkingExpansion || stopped || seen || !boundary || initialQueue.length || command.type !== "prompt" || command.streamingBehavior || !expectedText().trimStart().startsWith("/")) return; checkingExpansion = true; clearTimeout(expansionRetry); retryPending = false; let retry = false; try { const context = await wrapper.withPendingCommand(() => wrapper.host.sessionOps.readContext(wrapper.sessionId, undefined, { boundary: false, deferThinking: true, deferMedia: true, includePreCompaction: false, sync: null, })); if (!context.ok || !isRecord(context.value)) { retry = !context.ok && context.status >= 500; return; } const { entryIds, messages } = context.value; if (!Array.isArray(entryIds) || !Array.isArray(messages)) return; const added = messages.filter((item, index) => typeof entryIds[index] === "string" && !boundary.has(entryIds[index]) && isRecord(item) && item.role === "user"); if (added.length === 1 && isRecord(added[0]) && messageText(added[0]) === messageText(message)) finish({}); // Native echo can precede the file flush. Re-read only this active candidate, never infer a missing entry. retry = added.length === 0; } catch { // No post-dispatch state is guessed from a failed read; keep waiting for a proven replacement. retry = true; } finally { checkingExpansion = false; if (retry && !stopped && !seen) { retryPending = true; expansionRetry = setTimeout(() => { void checkExpandedUser(message); }, 100); expansionRetry.unref?.(); } else if (resultArrived) finish(unshown); } }; const detach = wrapper.onEvent((event) => { if (seen) return; if (!clientMessageId && (competingPending || wrapper.getMessageCommandGeneration() > generation + 1 || wrapper.peerMessageCommands !== peers)) { finish(ambiguous); return; } if (!ownsWindow() && event.type !== "process_exit") return; const text = expectedText(); if (!clientMessageId && echoDebt === undefined) echoDebt = initialQueue.filter((item) => item === text).length; if ((event.type === "message_start" || event.type === "message_end") && isRecord(event.message) && isUserInput(event.message) && (!clientMessageId || event.clientMessageId === clientMessageId)) userMessageSeen = true; if (event.type === "message_start" && typeof event.messageId === "string" && isRecord(event.message) && event.message.role === "user") { openedUserMessages.add(event.messageId); } else if (event.type === "queue_update") { if (clientMessageId) { const ids = readQueueSnapshot(event)?.clientMessageIds; if (ids?.steering.includes(clientMessageId) || ids?.followUp.includes(clientMessageId)) finish({}); return; } const next = queueTexts(event); const counts = new Map(); for (const item of priorQueue) counts.set(item, (counts.get(item) ?? 0) + 1); const added: string[] = []; for (const item of next) { const remaining = counts.get(item) ?? 0; if (remaining) counts.set(item, remaining - 1); else added.push(item); } if (text && (added.includes(text) || (command.type === "prompt" && text.trimStart().startsWith("/") && added.length === 1))) finish({}); priorQueue = next; } else if (event.type === "message_end" && isRecord(event.message) && isUserInput(event.message)) { if (clientMessageId) { if (event.clientMessageId === clientMessageId) finish({}); } else if (text && (messageText(event.message) === text || matchesNativeSkill(event.message, text))) { const debt = echoDebt ?? 0; if (debt > 0) echoDebt = debt - 1; else finish({}); } else if (event.message.role === "user" && (typeof event.messageId !== "string" || openedUserMessages.has(event.messageId))) { void checkExpandedUser(event.message); } } else if (event.type === "process_exit") finish(CHILD_EXITED); else if (event.type === "prompt_result" && commandId !== undefined && event.id === commandId) { // pi finished this prompt with no echo, so none will come. An expanded slash template's context check decides // first; once it has nothing left to try, the message may still be in the transcript. if (userMessageSeen && text.trimStart().startsWith("/")) { resultArrived = true; if (!checkingExpansion && !retryPending) finish(unshown); return; } // It reached no transcript when pi showed no user message (an input hook may rewrite the text) and ran no turn // for it: Stop or a refusal during setup, an aborted or failed run. A slash command may have acted on its own, and // frames lost meanwhile (a link drop, a daemon `resync`) may have carried the echo. const dropped = !userMessageSeen && !text.trimStart().startsWith("/") && wrapper.getFrameGaps() === gapsAtStart && (event.agentInvoked === false || event.status === "aborted" || event.status === "error"); // A failed hand-off needs a non-empty error: callers treat an empty one as delivered. const reason = isRecord(event.error) && typeof event.error.message === "string" && event.error.message.trim() ? event.error.message : dropped ? "Stopped before pi showed it" : unshown.error; finish({ error: reason, mayHaveBeenSent: !dropped }); } else if (event.type === "agent_end" && event.isTerminal !== false && !wrapper.isAlive()) finish(CHILD_EXITED); // Session-wide prompt failures may belong to an older run; only this command's reply can prove rejection. }, { internal: true }); return { async handOff() { if (!ownsWindow()) return ambiguous; timer = setTimeout(() => finish({ error: "pi acknowledged this message but has not shown it yet", mayHaveBeenSent: true }), HANDOFF_FALLBACK_MS); timer.unref?.(); const outcome = await promise; return ownsWindow() ? outcome : ambiguous; }, replied(watched, id) { if (watched === command) commandId = id; }, stop() { stopped = true; clearTimeout(timer); clearTimeout(expansionRetry); detach(); }, }; } export class AgentSessionWrapper { private listeners: EventListener[] = []; private pendingUiRequests = new Map(); private uiExpiryTimers = new Map>(); /** Session id each `input` notification was published under, keyed by request id: the wrapper's session id can change before the dialog settles, and the retraction tag must still match. */ private inputNotificationSessions = new Map(); /** Dialogs tau itself raised (confirmFromServer): answered here, never forwarded to pi. */ private serverUiRequests = new Map void>(); private extensionStatuses = new Map(); private extensionWidgets = new Map(); private promptRunning = false; private promptDispatchPendingCount = 0; private historyMutationPendingCount = 0; private messageCommandGeneration = 0; /** Times this child's frames may have been lost (`reconcileAfterGap`). */ private frameGaps = 0; private confirmedMessageCommandGeneration = 0; private pendingMessageCommands = 0; /** The settle read in flight (clearMessageProofTaintIfSettled): a send during it joins it instead of seeing it as busy. */ private taintRead: Promise | null = null; private nativeQueuedMessages: unknown = { steering: [], followUp: [] }; private readonly startedEmpty: boolean; private messageReplacement: MessageReplacementWatch | null = null; private historyEditInFlight = false; private awaitingAgentStart = false; private awaitingAgentStartDeadline = 0; private continuationGraceUntil = 0; private bashRunning = false; private streaming = false; private compacting = false; private streamId = randomUUID(); private streamSequence = 0; private streamingMessage: Partial | null = null; private streamingMessageId: string | null = null; /** Assistant messages pi is streaming, by messageId: what its delta updates apply to (lib/message-delta.ts). */ private openMessages = new Map>(); /** A delta found no message to apply to: a resync is asked for until the message ends. */ private recoveringUpdates = false; private liveToolEvents = new Map(); /** Calls that returned: pi keeps sending `tool_execution_update` for a backgrounded job with no later end. */ private endedToolCalls = new Set(); /** Positive evidence for this run, retained after native completion but before disk append. */ private responseObserved = false; private responseRunActive = false; /** agent_start frames seen: a prompt acknowledged after one arrived knows its run already started. */ private runStarts = 0; private idleTimer: ReturnType | null = null; /** Lazily-armed deadline for tearing down a session nobody is watching. */ private reapTimer: ReturnType | null = null; private reapDeadline = 0; private lastActivityAt = 0; /** In-flight `send()` calls: the reaper must never dispose the child out from * under a command that is still awaiting its response. */ private pendingCommands = 0; /** The start handshake (ready + protocol negotiation + get_state) is in flight. */ private handshaking = false; private readonly disconnectDestroyMs: number; private onDestroyCallback: (() => void) | null = null; private onIdentityChangeCallback: ((oldId: string, newId: string) => void) | null = null; private unsubscribeFrames: (() => void) | null = null; private readonly detectNotification = createNotificationDetector(); /** Agent activity since the last `session_settled`: background work may still run after the turn ended. */ private unsettled = false; private initPromise: Promise | null = null; /** Retained until native adoption has replayed pending requests and released live frames. */ private adoptionReplay?: string[]; private restarting = false; private restartingProc: RpcProcess | null = null; private _alive = true; /** Host tools the web UI registered via set_host_tools (agent-callable). */ private hostToolNames: Set = new Set(); /** Accepted browser definitions only: registered again, with server tools under the current enablement policy, when a shared child is restarted or adopted. */ private registeredHostTools: Array<{ name?: unknown; [key: string]: unknown }> | null = null; /** Feeding an adopted child's open requests (see adopt): server agent tools there may already have run. */ private replaying = false; /** Adopted, and no tab has registered host tools since: pi may call tools the * wrapper a restart lost registered, so every call routes as registered. */ private hostToolsUnknown = false; private _adopted = false; /** host_tool_call ids awaiting a host_tool_result from the browser. */ private pendingHostTools = new Map(); /** Server-side agent tool calls in flight (answerServerAgentTool); host_tool_cancel aborts them. */ private serverToolCalls = new Map(); /** Own host calls no tab has seen yet (see parkHostTool), with their deadlines. */ private parkedHostTools = new Map>(); /** Listeners tau attaches itself (waitForTurnEnd), not tabs: a parked host call waits for a tab. */ private readonly internalListeners = new WeakSet(); /** Callback delivery is not permission to repeat an action after a snapshot/reconnect. */ private deliveredCallbacks = new Set(); /** Message commands other servers wrote to this shared child (PEER_MESSAGE_FRAME markers). */ peerMessageCommands = 0; /** Resolves once an in-flight destroyAndWait finishes; null when idle. Read * by startRpcSession so a replacement spawn awaits the old child's exit. */ destroyPromise: Promise | null = null; private _sessionId = ""; private _sessionFile = ""; private _sessionName: string | undefined; private proc: RpcProcess; /** Process whose exit is expected because reload is deliberately disposing it. */ private expectedExitProc: RpcProcess | null = null; /** A reload gave up waiting for the old child behind a dropped link; it may still run, so commands answer host_offline until it exits. */ private oldChildExiting = false; readonly cwd: string; /** Machine the child runs on; every machine-local action goes through it. */ readonly host: Host; /** The cwd recorded in the session file header; null for brand-new sessions * or when the header lacks one. A restart asks the host to start there again. */ private readonly recordedCwd: string | null; /** The host could not start the child in its directory and used another * one (spawn fallback): a notice warns the user once it is ready. */ private readonly fellBack: boolean; private unsubscribeHostStatus: (() => void) | null = null; // Plain field assignments (not TS parameter properties) keep this module // runnable under Node's strip-only TypeScript mode for probes/tests. constructor( proc: RpcProcess, cwd: string, recordedCwd?: string | null, expectedSessionId = "", /** Test seam: the real value is DISCONNECT_DESTROY_MS (120s), far too long * for a unit test. 0 disables reaping for that wrapper. */ disconnectDestroyMs: number = DISCONNECT_DESTROY_MS, host: Host = getHost(LOCAL_HOST_ID), fellBack = false, ) { this.proc = proc; this.cwd = cwd; this.recordedCwd = recordedCwd ?? null; this._sessionId = expectedSessionId; this.startedEmpty = expectedSessionId === ""; this.disconnectDestroyMs = disconnectDestroyMs; this.host = host; this.fellBack = fellBack; } get sessionId(): string { return this._sessionId; } get sessionFile(): string { return this._sessionFile; } get hostOwnedLifecycle(): boolean { return this.proc.transport?.hostOwnedLifecycle === true; } private reportInterest(): void { this.proc.transport?.setInterest?.(this._alive && (this.hasSubscribers() || this.pendingCommands > 0 || this.handshaking)); } isAlive(): boolean { return this._alive && this.proc.isAlive; } /** `ignoreShell`: leave out tau's `!!` shell command, which pi runs beside a prompt. */ isRunning(ignoreShell = false): boolean { // A human/host response can outlive the current streaming turn. Reaping it // ends the pi child and aborts that request, even without a Stop. return this.isAlive() && (this.promptRunning || this.streaming || this.compacting || (!ignoreShell && this.bashRunning) || this.pendingUiRequests.size > 0 || this.pendingHostTools.size > 0); } isAwaitingInput(): boolean { return this.pendingUiRequests.size > 0; } /** Local history navigation is busy control work, not an interruptible model turn. */ isEditingHistory(): boolean { return this.historyEditInFlight; } /** Any event observer is attached, including internal work that protects the session lifetime. */ hasSubscribers(): boolean { return this.listeners.length > 0; } private hasBrowserSubscribers(): boolean { return this.listeners.some((listener) => !this.internalListeners.has(listener)); } /** * Any real use of the session: an attached UI, a command from an API route, or * a frame from the child. `resetIdleTimer()` is the single choke point for all * three (start(), handleFrame(), send()), so driving reaping from here means * the deadline can never drift away from what the session is actually doing. * * Deliberately does NOT touch a timer: only the *deadline* moves, and * `armReap` keeps at most one timer alive, so a 100fps token stream costs a * timestamp write instead of clearTimeout/setTimeout churn. */ private noteActivity(): void { if (this.hostOwnedLifecycle) return; this.lastActivityAt = Date.now(); this.reapDeadline = this.lastActivityAt + this.disconnectDestroyMs; this.armReap(); } private armReap(): void { if (this.hostOwnedLifecycle) return; if (this.reapTimer || this.disconnectDestroyMs <= 0) return; if (this.hasSubscribers() || !this.isAlive()) return; this.reapTimer = setTimeout(() => { this.reapTimer = null; this.reapIfDisconnected(); }, Math.max(0, this.reapDeadline - Date.now())); // Never pin the event loop for a cleanup deadline (cf. the MCP waiter and // lib/session-resume.ts): an unref'd reap must not delay process exit. this.reapTimer.unref?.(); } /** * Tear the child down only when nobody can observe the loss. Every condition * here is a hard invariant, not a heuristic: * - a subscriber means an open HTTP 200 stream that `destroy()` would leave * half-open (the route holds its own detach + heartbeat), so the run would * vanish silently and the tab would only notice via a later 409; * - isRunning() covers an in-flight turn that no listener is watching; * - handshaking covers a spawn that has not finished its startup handshake; * - pendingCommands covers command preparation and dispatch, including a * response the child still owes us; * - the deadline check absorbs activity that landed while this fired. * Anything else keeps the session and re-arms for the remaining window. */ private reapIfDisconnected(): void { if (this.hostOwnedLifecycle) return; if (!this.isAlive() || this.hasSubscribers() || this.isRunning() || this.handshaking || this.pendingCommands > 0 || this.hostDown()) { // A paused human dialog produces no frames. Do not spin a zero-delay // timer once the old deadline has passed while protected work remains. this.reapDeadline = Math.max(this.reapDeadline, Date.now() + this.disconnectDestroyMs); this.armReap(); return; } if (Date.now() < this.reapDeadline) { this.reapDeadline = this.lastActivityAt + this.disconnectDestroyMs; this.armReap(); return; } console.info("[tau] automatic-session-cleanup", JSON.stringify({ sessionId: this._sessionId, reason: "disconnected-idle", at: new Date().toISOString() })); this.destroy("disconnected-idle"); } /** NDJSON messages are fresh snapshots; copy containers, not token payloads. */ getStreamSnapshot(): SessionLiveSnapshot { return { cursor: { streamId: this.streamId, sequence: this.streamSequence }, isStreaming: this.streaming, isPromptRunning: this.promptRunning, isCompacting: this.compacting, responseObserved: this.responseObserved, streamingMessage: this.streamingMessage ? { ...withStreamedArguments(this.streamingMessage) } : null, streamingMessageId: this.streamingMessageId, toolEvents: Array.from(this.liveToolEvents.values(), (event) => ({ ...event })), }; } private clearLiveSnapshots(): void { this.streamingMessage = null; this.streamingMessageId = null; this.openMessages.clear(); this.liveToolEvents.clear(); this.streamSequence += 1; } private resetStream(): void { this.clearLiveSnapshots(); this.responseObserved = false; this.responseRunActive = false; this.endedToolCalls.clear(); this.streamId = randomUUID(); this.streamSequence = 0; } private endTool(toolCallId: string): void { this.liveToolEvents.delete(toolCallId); this.endedToolCalls.add(toolCallId); } start(): void { const proc = this.proc; this.unsubscribeFrames = proc.onFrame((frame) => this.handleFrame(frame, proc)); this.watchResync(proc); this.unsubscribeHostStatus = this.host.onStatus((status) => this.handleHostStatus(status)); this.reportInterest(); this.resetIdleTimer(); notifyRunningChange(); } /** The host's link is down ("transport down", never "exited"): the child runs on, unreachable. */ private hostDown(): boolean { return !isLinkUp(this.host.status()); } private hostOfflineError(delivery: "refused" | "unknown"): WebRpcError { return new WebRpcError(`${this.host.label} is offline. The run continues there; it reconnects automatically.`, "host_offline", delivery); } /** The command timed out because its host's link went quiet, not because pi * wedged: the child runs on there, so it is not recycled (the kill would wait * for the link anyway), and the reconcile on reconnect settles the run. */ private linkLostDuring(timeout: RpcCommandTimeoutError): boolean { const lastUplink = lastUplinkAt(this.host.id); // A linked host that sent anything after the command went down has a live // link: pi itself is wedged, and the caller recycles the child as before. return lastUplink !== null && (this.hostDown() || lastUplink <= timeout.dispatchedAt); } /** A remote link that dropped this child's buffered output asks for a reconcile. * Duck-typed: a `bun --hot` re-evaluation can leave live transports on an older class. */ private watchResync(proc: RpcProcess): void { proc.transport?.onResync?.(() => { if (this.proc !== proc) return; if (this.hostOwnedLifecycle) { this.clearLiveSnapshots(); this.recoveringUpdates = false; for (const [id, event] of [...this.pendingUiRequests]) { if (this.serverUiRequests.has(id)) continue; // The frames that were lost may have answered a dialog, and the replay // that follows may restore it: forget it now (its notification must not // keep offering an answer this server no longer holds), but as a // *forgotten* settlement, so the replayed request is published again. this.settlePendingUiRequest(id, "forgotten"); this.emit({ type: "ui_end", id: event.id }); } } void this.reconcileAfterGap(); }); } private handleHostStatus(status: HostStatus): void { if (!this._alive) return; this.emit({ type: "host_status", hostId: this.host.id, status }); if (!isLinkUp(status)) return; if (this.hostOwnedLifecycle) return; // The hub reopens at an ordered snapshot boundary. // The idle and disconnect timers held off while the link was down; give them a full window again. this.resetIdleTimer(true); void this.reconcileAfterGap(); } /** Frames may have been lost (link down, `resync`): re-read pi's state, as the client's get_state reconcile does. */ private async reconcileAfterGap(): Promise { this.frameGaps += 1; // A lost delta would corrupt its message silently: rebuild from the next full update instead. this.openMessages.clear(); try { const state = await this.getStateWithTimeout(); if (!this._alive) return; const wasRunning = this.streaming || this.promptRunning; const oldId = this._sessionId; // A shared reopen can install the new identity's snapshot while this read is in flight (cleared when it started). const live = this.hostOwnedLifecycle ? { open: new Map(this.openMessages), message: this.streamingMessage, id: this.streamingMessageId } : null; this.applyIdentity(state); if (oldId && oldId !== this._sessionId) { if (live) { for (const [messageId, message] of live.open) this.openMessages.set(messageId, message); this.streamingMessage = live.message; this.streamingMessageId = live.id; } this.onIdentityChangeCallback?.(oldId, this._sessionId); } // The run ended while its frames were lost: end it for clients, as on exit. if (wasRunning && !state.isStreaming && !state.isCompacting && !this.awaitingAgentStart && this.promptDispatchPendingCount === 0) { this.emit({ type: "agent_end", isTerminal: true, messages: [] }); } notifyRunningChange({ refreshSessionList: true }); } catch { // The client's own reconcile poll catches up. } } /** Resolves once the child announced readiness and identity is known. */ waitUntilReady(): Promise { if (!this.initPromise) this.initPromise = this.initialize(); return this.initPromise; } private async initialize(): Promise { // READY_TIMEOUT_MS and the reap window are the same order of magnitude, so // the handshake itself counts as in-flight work: a child that is slow to // announce itself must be torn down by its own startup timeout (which // reports a real error), never by the reaper. this.handshaking = true; this.reportInterest(); try { if (!this.hostOwnedLifecycle) { await this.proc.waitReady(READY_TIMEOUT_MS); } const state = await this.getStateWithTimeout(STARTUP_COMMAND_TIMEOUT_MS); this.applyIdentity(state); // Warn when the spawn cwd differs from the session's recorded directory. // This happens when the recorded cwd was deleted (removed worktree, moved // repo, different machine): resolveSpawnCwd silently substituted a live // directory so pi can spawn, but without a notice the user would see the // sidebar/header still advertise the (gone) recorded path while file tool // calls operate on a different tree. if (this.fellBack) { this.emit({ type: "notice", level: "warning", message: `This session's working directory no longer exists; the agent is running in ${this.cwd}.`, }); } } finally { this.handshaking = false; this.reportInterest(); // The handshake is real activity, so the reap clock restarts from here // rather than from spawn (a slow start must not eat the whole window). this.noteActivity(); } } /** A delta found no message to apply to (attached mid-message, frames lost on the link): the host's snapshot rebuilds it. */ private loseDeltaBase(): void { if (!this.hostOwnedLifecycle || this.recoveringUpdates) return; this.recoveringUpdates = true; void this.proc.transport.resync?.(); } /** * Re-sync a child that outlived the server that spawned it (adoptRpcSession): * the startup handshake minus the ready wait, every command bounded so a * wedged child fails the adoption, then the daemon's lines of its open requests. * `joined`: false when this open started the shared child, so no other server's history precedes it. */ async adopt(replay?: string[], joined = true): Promise { if (replay !== undefined) this.adoptionReplay = replay; this.handshaking = true; this.reportInterest(); this._adopted = joined; this.hostToolsUnknown = true; // A refusal is tolerated, as at startup; a timeout or an exit fails the adoption. const optional = (command: { type: string; [key: string]: unknown }, timeoutMs = STARTUP_COMMAND_TIMEOUT_MS) => this.proc.sendCommand(command, timeoutMs).then(() => {}, (error) => { if (!(error instanceof RpcCommandError)) throw error; }); try { if (!this.hostOwnedLifecycle) { await this.proc.waitReady(); } // pi's state has no shell-command flag: a `!!` command the lost server started // leaves bashRunning false, and its result arrives as an unsolicited response. this.applyIdentity(await this.getStateWithTimeout(STARTUP_COMMAND_TIMEOUT_MS)); // The wrapper keeps neither (a tab reads both when it attaches): a child that cannot answer them fails here instead. // get_state answered, so pi's startup work is over: these reads keep the status-poll budget. await optional({ type: "get_subagents" }, GET_STATE_TIMEOUT_MS); await optional({ type: "get_btw_history" }, GET_STATE_TIMEOUT_MS); this.replaying = true; try { this.proc.replay(this.adoptionReplay ?? []); } finally { this.replaying = false; } // Frames pi sent during the handshake are live: its agent tool calls there run normally. this.proc.release(); this.adoptionReplay = undefined; if (this.hostOwnedLifecycle && loadWebServerSettings().agentToolsEnabled) { await this.dispatchCommand({ type: "set_host_tools", tools: this.registeredHostTools ?? [] }); } } finally { this.handshaking = false; this.reportInterest(); this.noteActivity(); } } /** Joined an existing protocol endpoint. */ get adopted(): boolean { return this._adopted; } private applyIdentity(state: RpcSessionState): void { if (state.queuedMessages !== undefined) this.nativeQueuedMessages = state.queuedMessages; const oldId = this._sessionId; const identityChanged = Boolean(oldId) && (state.sessionId !== oldId || (state.sessionFile && state.sessionFile !== this._sessionFile)); if (identityChanged) { this.abortServerToolCalls(); this.resetStream(); this.promptRunning = false; this.awaitingAgentStart = false; this.awaitingAgentStartDeadline = 0; this.continuationGraceUntil = 0; } this._sessionId = state.sessionId; this._sessionFile = state.sessionFile ?? ""; this._sessionName = state.sessionName; this.streaming = state.isStreaming; this.compacting = state.isCompacting; // The path cache resolves ids to files on this machine only (file authorization). if (this._sessionFile && this.host.id === LOCAL_HOST_ID) cacheSessionPath(this._sessionId, this._sessionFile); } handleProcessExit( { code, signal, stderrTail }: { code: number | null; signal: NodeJS.Signals | null; stderrTail: string }, sourceProc: RpcProcess = this.proc, ): void { if (!this._alive || sourceProc === this.expectedExitProc) return; // The shared host stopped it on purpose (abandoned, idle, another server's request): not a crash. const planned = this.hostOwnedLifecycle ? sourceProc.transport?.stopReason : undefined; if (planned) { if (this.streaming || this.promptRunning) this.emit({ type: "agent_end", isTerminal: true, messages: [] }); this.destroy(`host-${planned}`); return; } const detail = (stderrTail.trim().split("\n").pop() ?? "").slice(-500); const status = signal ? `signal ${signal}` : `code ${code ?? "null"}`; // Spec Rules → Reattach: a run whose child vanished while its host link was // down starts again on that host, like a local run after a restart. const resume: InterruptibleSession | null = !this.hostOwnedLifecycle && sourceProc.transport?.lost === true && this._sessionId && (this.streaming || this.promptRunning) ? { id: this._sessionId, hostId: this.host.id } : null; // Recorded before destroy(): its running-change broadcast must carry the // record so sidebars that missed the notice below still see the exit. if (this._sessionId) getExitedMap().set(this._sessionId, { id: this._sessionId, cwd: this.cwd, ...(this.host.id === LOCAL_HOST_ID ? {} : { hostId: this.host.id }), at: Date.now(), code, signal, detail }); this.emit({ type: "notice", level: "error", message: `The pi process for this session exited unexpectedly (${status})${detail ? `: ${detail}` : "."}`, }); // Terminal agent_end so a client mid-stream stops spinning immediately // instead of waiting for the reconcile poll. if (this.streaming || this.promptRunning) this.emit({ type: "agent_end", isTerminal: true, messages: [] }); if (this.streaming || this.promptRunning || this.unsettled) { this.publishNotifications({ type: "process_exit", detail: detail || status }); } this.destroy(); if (resume && loadWebServerSettings().autoResumeSessions) void resumeSession(resume); } private publishNotifications(frame: Record): void { const session = { sessionId: this._sessionId, sessionName: this._sessionName || this.cwd.split(/[\\/]/).filter(Boolean).pop() || null, }; const notifications = this.detectNotification(frame, session); if (this.hostOwnedLifecycle && !isNotifier(this.host.id)) return; for (const notification of notifications) { // Remember the id it is published under: a later identity change moves // `_sessionId`, and the retraction must still name the same tag. if (notification.type === "input" && notification.requestId) { this.inputNotificationSessions.set(notification.requestId, notification.sessionId); } publishNotification(notification); } } private handleFrame(frame: RpcFrame, sourceProc: RpcProcess = this.proc): void { this.resetIdleTimer(); const event = frame; if (event.type === PEER_MESSAGE_FRAME) { this.peerMessageCommands += 1; return; } if (this.hostOwnedLifecycle && event.type === "host_tool_call" && typeof event.id === "string") { const key = `${event.type}:${event.id}`; if (this.deliveredCallbacks.has(key)) return; this.deliveredCallbacks.add(key); // Only the read-only listing and the idempotent GitHub tools run again (handled below); anything else may already have run. if (this.replaying && !(typeof event.toolName === "string" && (event.toolName === "list_sessions" || GITHUB_REPLAY_SAFE_TOOLS.has(event.toolName)))) { this.proc.sendFrame({ type: "host_tool_result", id: event.id, isError: true, result: { content: [{ type: "text", text: unknownOutcome(event.toolName) }] } }); return; } } let refreshSessionList = false; switch (event.type) { case "agent_start": this.runStarts += 1; this.unsettled = true; this.promptRunning = true; this.streaming = true; this.awaitingAgentStart = false; this.awaitingAgentStartDeadline = 0; this.continuationGraceUntil = 0; // The session file can appear just after the prompt acknowledgement. // Invalidate and signal the sidebar now rather than waiting for the // agent's first reply or terminal event. this.invalidateSessionLists(); refreshSessionList = true; // If the file is not on disk yet, the sidebar refresh above may walk // the sessions dir before it exists — and the mtime-keyed walk cache // then stays stale (NTFS does not bump the sessions-root mtime for // files added inside a project subdirectory), hiding the running // session from the list until the next invalidation (agent_end). // Re-signal once the file actually lands. if (this._sessionFile) { void this.host.sessionFileExists(this._sessionFile).then((exists) => { if (!exists && this._alive) this.signalWhenSessionFileAppears(); }, () => {}); } break; case "agent_end": if (event.isTerminal !== false) { // A server dialog belongs to a tool call of this run; nobody can answer it after the run. this.dropServerUiRequests(); this.streaming = false; this.promptRunning = false; this.awaitingAgentStart = false; this.awaitingAgentStartDeadline = 0; this.continuationGraceUntil = 0; this.invalidateSessionLists(); } else { this.continuationGraceUntil = Date.now() + NON_TERMINAL_CONTINUATION_GRACE_MS; } break; case "queue_update": this.nativeQueuedMessages = event; break; case "session_settled": this.unsettled = false; this.deliveredCallbacks.clear(); // Each run's end may lift the taint, so a user who only sends during runs is not stuck with it. if (this.hasPendingMessageCommands()) { void this.clearMessageProofTaintIfSettled().catch((error) => { console.warn(`[tau] could not read whether session ${this._sessionId} settled: ${error instanceof Error ? error.message : String(error)}`); }); } break; case "prompt_result": // Local-only prompt (builtin/extension slash command) — no agent run. this.promptRunning = false; this.awaitingAgentStart = false; this.awaitingAgentStartDeadline = 0; break; case "auto_compaction_start": this.compacting = true; break; case "auto_compaction_end": this.compacting = false; // Same patch the manual `compact` path applies — the client reads // event.result.estimatedTokensAfter for the banner. patchEstimatedTokensAfter(event.result); this.invalidateSessionLists(); break; case "session_info_update": if (typeof event.title === "string") this._sessionName = event.title; this.invalidateSessionLists(); refreshSessionList = true; break; case "prompt_error": { // An async prompt failure: terminal, no agent_end follows. Tabs and notifications read `errorMessage`. this.promptRunning = false; this.awaitingAgentStart = false; this.awaitingAgentStartDeadline = 0; const promptError = { ...event, errorMessage: typeof event.error === "string" ? event.error : "Prompt failed" }; this.publishNotifications(promptError); this.emit(promptError); notifyRunningChange(); return; } case "ui_request": this.trackUiRequest(event); break; case "ui_end": this.settlePendingUiRequest(String(event.id)); break; case "ui": this.trackPresentation(event); break; case "host_tool_call": { const id = typeof event.id === "string" ? event.id : ""; const toolName = typeof event.toolName === "string" ? event.toolName : ""; // Server-side agent tools (#275) are answered here, before any // browser routing, so they work with no tab open. A disabled gate // is an explicit error, not a silent hang and not a browser call. if (id && toolName && AGENT_TOOL_NAMES.has(toolName)) { // Independent pooled creations have durable native-request identity; other mutations stay unknown. if (this.replaying && toolName !== "list_sessions" && !GITHUB_REPLAY_SAFE_TOOLS.has(toolName) && (toolName !== "new_session" || !loadWebServerSettings().agentToolsEnabled)) { this.proc.sendFrame({ type: "host_tool_result", id, isError: true, result: { content: [{ type: "text", text: unknownOutcome(toolName) }] }, }); } else if (loadWebServerSettings().agentToolsEnabled) { void this.answerServerAgentTool(event, sourceProc); } else { this.proc.sendFrame({ type: "host_tool_result", id, isError: true, result: { content: [{ type: "text", text: "Agent tools are disabled. Enable \"Agent tools\" in tau Settings (System) first.", }], }, }); this.emit({ type: "notice", level: "warning", message: `Rejected disabled agent tool: ${toolName}` }); } return; } // Route REGISTERED host tools to an attached UI (the browser answers // via host_tool_result). With no tab on this session, hand the call to // any open tau tab (the user switched sessions mid-run). Otherwise // reject immediately so the agent never hangs on a tool nobody will // answer. if (id && toolName && (this.hostToolNames.has(toolName) || this.hostToolsUnknown)) { const ownTab = this.hasBrowserSubscribers(); if (ownTab) { this.pendingHostTools.set(id, { event }); this.emit(event); notifyRunningChange(); return; } const otherTabs = getHostToolListeners(); if (otherTabs.size > 0) { this.pendingHostTools.set(id, { event, crossSessionId: this.sessionId }); const args = event.arguments && typeof event.arguments === "object" ? event.arguments as Record : {}; const call: CrossSessionHostToolCall = { sessionId: this.sessionId, hostId: this.host.id, cwd: this.cwd, id, toolName, arguments: args }; for (const listener of otherTabs) { try { listener(call); } catch { /* ignore listener errors */ } } notifyRunningChange(); return; } // Adopted with every tab gone with the old server: the next tab to attach answers it. if (this.hostToolsUnknown) { this.parkHostTool(id, event); notifyRunningChange(); return; } } // Unregistered tool / no listener: reject (emits a notice) and do NOT // re-emit the frame — the UI must not answer a call nobody routed. this.rejectUnexpectedHostTool(event); return; } case "host_tool_cancel": { const targetId = typeof event.targetId === "string" ? event.targetId : ""; this.serverToolCalls.get(targetId)?.abort(); if (targetId && this.cancelPendingHostTool(targetId)) { notifyRunningChange(); return; } break; } } this.publishNotifications(event); this.emit(event); notifyRunningChange({ refreshSessionList }); } /** Forget a pending dialog, its expiry timer and the id its notification was published under. */ private forgetPendingUiRequest(id: string): void { this.inputNotificationSessions.delete(id); // An answered or expired dialog no longer waits on the user: the sidebar follows. if (this.pendingUiRequests.delete(id)) notifyRunningChange(); const timer = this.uiExpiryTimers.get(id); if (timer) { clearTimeout(timer); this.uiExpiryTimers.delete(id); } } /** * A pending dialog is settled (answered, cancelled, expired or its child is * gone): forget it and retract the `input` notification it produced, so no * other tab or device keeps offering an answer to a question that is gone. * * `forgotten` is the same for a dialog this server only *dropped*: a resync * lost it, and the frames the host replays can restore the very same request * id. The notification is retracted now (nothing on screen may keep offering * an answer to a question this server no longer holds), but the retraction is * temporary, so a replay of that request announces and pushes it again * instead of being suppressed for the retraction TTL. */ /** A dialog past its deadline: settled, and closed in every attached tab (the browser does not time it out itself). */ private expirePendingUiRequest(id: string): void { const event = this.pendingUiRequests.get(id); if (event && this.settlePendingUiRequest(id)) this.emit({ type: "ui_end", id: event.id }); } private settlePendingUiRequest(id: string, reason: "settled" | "forgotten" = "settled"): boolean { if (!this.pendingUiRequests.has(id)) return false; // Read before forgetting: the tag is the one the notification went out with. const publishedSession = this.inputNotificationSessions.get(id); this.forgetPendingUiRequest(id); // One server publishes a notification and its retraction: a former // notifier must not close what the elected one still owns. if (publishedSession && (!this.hostOwnedLifecycle || isNotifier(this.host.id))) { if (reason === "forgotten") publishNotificationForgotten(publishedSession, id); else publishNotificationDismiss(publishedSession, id); } return true; } /** * Answer a blocking dialog from a notification action. The answer is checked * against the pending dialog first (a select takes one of its own options, a * confirm takes a confirmation, an ask takes answers), then it goes through * the same `ui_response` command the desktop dialog sends: that path resolves * a server-owned confirm and applies the offline/restarting gate, so an * answer is never reported when it could not be delivered. */ async answerExtensionUiRequest(id: string, response: ExtensionUiResponse): Promise<"answered" | "alreadySettled"> { const pending = this.pendingUiRequests.get(id); if (!pending) return "alreadySettled"; // A deadline that passed while its timer could not run (a suspended process) already expired the dialog. const expiresAt = pending.expiresAt as number | undefined; if (expiresAt !== undefined && expiresAt <= Date.now()) { this.expirePendingUiRequest(id); return "alreadySettled"; } const method = typeof pending.method === "string" ? pending.method : ""; // Some requests are stored as pending only so they are replayed; pi // registers no resolver for them, so an "answer" would be dropped there // while this server reported success and retracted the notification. if (!DIALOG_UI_METHODS.has(method)) { throw new WebRpcError("This request does not take an answer", "invalid_dialog_answer"); } // Keep the route in step with what the notification promised: a dialog the // push had to omit (over-long confirm message, ask question or title, an // oversized payload) is not answerable through the notification route. if (!isNotificationAnswerable(pending)) { throw new WebRpcError("This dialog cannot be answered from a notification", "invalid_dialog_answer"); } await this.send(uiResponseCommand(pending, response)); return "answered"; } private clearPendingUiRequests(reason: "settled" | "forgotten" = "settled"): void { this.dropServerUiRequests(); for (const timer of this.uiExpiryTimers.values()) clearTimeout(timer); this.uiExpiryTimers.clear(); // The child is going away (restart, destroy, process exit): every dialog it // waited on is settled, and its notification must not outlive it. When this // server only leaves a shared child that keeps running, its dialogs are // still waiting there: forgotten, so the next server to hold them announces // them again instead of finding them suppressed. for (const id of [...this.pendingUiRequests.keys()]) this.settlePendingUiRequest(id, reason); } /** Settle every server dialog as declined and close it in attached tabs. */ private dropServerUiRequests(): void { for (const [id, resolve] of this.serverUiRequests) { this.serverUiRequests.delete(id); this.settlePendingUiRequest(id); this.emit({ type: "ui_end", id }); resolve(false); } } /** * Ask this session's user to confirm, as a pi dialog would: same tabs, * replay and input-needed notification. Resolves false when declined, when * the run ends, or when the session stops. */ confirmFromServer(title: string, payload?: AgentConfirmPayload, signal?: AbortSignal): Promise { if (!this._alive || signal?.aborted) return Promise.resolve(false); const id = `tau:${randomUUID()}`; const { promise, resolve } = Promise.withResolvers(); const finish = (confirmed: boolean) => { signal?.removeEventListener("abort", abort); resolve(confirmed); }; const abort = () => { if (!this.serverUiRequests.delete(id)) return; this.settlePendingUiRequest(id); this.emit({ type: "ui_end", id }); finish(false); }; this.serverUiRequests.set(id, finish); signal?.addEventListener("abort", abort, { once: true }); if (signal?.aborted) abort(); else this.handleFrame({ type: "ui_request", id, method: "confirm", args: [title, ""], ...(payload ? { serverPayload: payload } : {}) }); return promise; } /** Records a runner dialog as pending. */ private trackUiRequest(event: UnsequencedAgentEvent): void { const id = String(event.id); if (!this.serverUiRequests.has(id) && "serverPayload" in event) delete event.serverPayload; const args = Array.isArray(event.args) ? event.args : []; // Pending until answered or ended (replayed to newly-attached SSE listeners so dialogs survive reconnects). this.forgetPendingUiRequest(id); // The dialog options are the last positional argument: (questions|html|prompt, options) or (title, x, options). const options = args[event.method === "askDialog" ? 1 : 2]; const timeout = isRecord(options) && typeof options.timeout === "number" ? options.timeout : undefined; if (timeout && timeout > 0) { event.expiresAt = Date.now() + timeout; const timer = setTimeout(() => this.expirePendingUiRequest(id), timeout); timer.unref?.(); this.uiExpiryTimers.set(id, timer); } this.pendingUiRequests.set(id, event); } /** Keeps the extension status/widget state a newly attached tab is sent. */ private trackPresentation(event: UnsequencedAgentEvent): void { const method = event.method; if (method === "setStatus") { const key = event.statusKey as string; const text = event.statusText as string | undefined; if (text === undefined) this.extensionStatuses.delete(key); else this.extensionStatuses.set(key, text); } else if (method === "setWidget") { const key = event.widgetKey as string; const lines = event.widgetLines as string[] | undefined; if (lines === undefined) { this.extensionWidgets.delete(key); } else { this.extensionWidgets.set(key, { key, lines, placement: (event.widgetPlacement as "aboveEditor" | "belowEditor" | undefined) ?? "aboveEditor", }); } } } /** * Settle a host_tool_call the UI did not register (or arrived with no * attached listener) with an explicit error so its agent turn cannot hang * forever waiting for a response. Registered host tools are routed to * listeners in handleFrame (see the host_tool_call case). */ private rejectUnexpectedHostTool(event: UnsequencedAgentEvent): void { const id = typeof event.id === "string" ? event.id : ""; if (!id) return; const toolName = typeof event.toolName === "string" ? event.toolName : "unknown"; this.proc.sendFrame({ type: "host_tool_result", id, isError: true, result: { content: [{ type: "text", text: `Host tool \"${toolName}\" is not available in tau. Use pi's built-in tools within the selected workspace.`, }], }, }); this.emit({ type: "notice", level: "warning", message: `Rejected unavailable host tool: ${toolName}` }); } /** Withdraw the browser operation using the identity under which it was delivered. */ private cancelPendingHostTool(id: string): boolean { const pending = this.pendingHostTools.get(id); if (!pending) return false; this.pendingHostTools.delete(id); this.unparkHostTool(id); const event = { type: "host_tool_cancel", targetId: id }; this.emit(event); if (pending.crossSessionId !== undefined) { for (const listener of getHostToolListeners()) { try { listener({ type: "host_tool_cancel", targetId: id, sessionId: pending.crossSessionId }); } catch { /* ignore listener errors */ } } } return true; } /** * Reject outstanding host tool calls (browser disconnected / destroy): "own" ones went to this session's * stream, "cross" ones to other open tabs (see subscribeHostToolCalls). */ private rejectPendingHostTools(message: string, which: "all" | "own" | "cross" = "all"): void { for (const [id, pending] of this.pendingHostTools) { const cross = pending.crossSessionId !== undefined; if ((which === "own" && cross) || (which === "cross" && !cross)) continue; // No tab ever received it: its own deadline settles it (see parkHostTool). if (which === "own" && this.parkedHostTools.has(id)) continue; this.cancelPendingHostTool(id); this.proc.sendFrame({ type: "host_tool_result", id, isError: true, result: { content: [{ type: "text", text: message }] }, }); } } /** * Hold an own host call no tab can answer yet (adopted: every tab went with * the old server) for the next tab to attach (see onEvent). If none attaches * within the disconnect window it is settled, so the agent never waits forever. */ private parkHostTool(id: string, event: UnsequencedAgentEvent): void { this.pendingHostTools.set(id, { event }); const timer = setTimeout(() => { this.parkedHostTools.delete(id); if (!this.pendingHostTools.delete(id)) return; this.proc.sendFrame({ type: "host_tool_result", id, isError: true, result: { content: [{ type: "text", text: "No tau tab reconnected to answer this host tool" }] }, }); notifyRunningChange(); }, this.disconnectDestroyMs); timer.unref?.(); this.parkedHostTools.set(id, timer); } private unparkHostTool(id: string): void { clearTimeout(this.parkedHostTools.get(id)); this.parkedHostTools.delete(id); } /** The last other tab left: settle calls routed to other tabs. */ rejectCrossSessionHostTools(): void { this.rejectPendingHostTools("The web UI disconnected while the agent was waiting for this host tool", "cross"); } private emit(nativeEvent: UnsequencedAgentEvent): void { // Tool-result images go out (and into the replay snapshot) as media URLs: // big screenshots must never sit in the browser's chat state as base64. const event = eventWithToolResultImageUrls(nativeEvent); // `web` belongs to this wrapper, never to native/extension-supplied frames. // Strip it before caching tool snapshots as well as before wire emission. delete event.web; switch (event.type) { case "agent_start": this.responseObserved = false; this.responseRunActive = true; this.clearLiveSnapshots(); break; case "agent_end": if (event.isTerminal === false) break; this.responseRunActive = false; this.streaming = false; this.promptRunning = false; this.compacting = false; this.clearLiveSnapshots(); this.recoveringUpdates = false; break; case "prompt_error": case "prompt_result": this.responseRunActive = false; this.streaming = false; this.compacting = false; this.promptRunning = false; this.clearLiveSnapshots(); this.recoveringUpdates = false; break; case "message_start": case "message_update": { let message = event.message as Partial | undefined; const messageId = typeof event.messageId === "string" ? event.messageId : null; if (isDeltaUpdate(event)) { const base = messageId === null ? undefined : this.openMessages.get(messageId); const rebuilt = applyMessageDelta(base, event.assistantMessageEvent); // Never forward a delta nobody can apply: the message's end carries it whole. if (!rebuilt) { this.loseDeltaBase(); return; } message = rebuilt; } // Daemon snapshots are ordered delta bases (including partialJson); legacy full updates are not. if (messageId !== null && message?.role === "assistant") { if (this.hostOwnedLifecycle || event.type === "message_start" || isDeltaUpdate(event)) this.openMessages.set(messageId, message); else this.openMessages.delete(messageId); } if (message && message.role !== "user") { this.streamingMessage = message; this.streamingMessageId = messageId; } if (this.responseRunActive && hasVisibleAssistantContent(message)) this.responseObserved = true; break; } case "message_end": { const message = event.message as Partial | undefined; if (this.responseRunActive && hasVisibleAssistantContent(message)) this.responseObserved = true; if (typeof event.messageId === "string") this.openMessages.delete(event.messageId); if (message?.role && message.role === this.streamingMessage?.role) { this.streamingMessage = null; this.streamingMessageId = null; } if (message?.role === "toolResult" && message.toolCallId) this.endTool(message.toolCallId); if (message?.role === "assistant") this.recoveringUpdates = false; break; } case "tool_execution_start": case "tool_execution_update": if (typeof event.toolCallId !== "string") break; // A start is always a new execution, even of a reused id. A returned call's updates are stale: its row // shows the committed result, so tabs and the snapshot both drop them (a tab would show it running again). // shortcut: a wrapper adopted after a server restart never saw the ends and still passes those updates; filter against committed results if adopted chats show them. if (event.type === "tool_execution_start") this.endedToolCalls.delete(event.toolCallId); else if (this.endedToolCalls.has(event.toolCallId)) return; this.liveToolEvents.set(event.toolCallId, { ...this.liveToolEvents.get(event.toolCallId), ...event, type: event.type, toolCallId: event.toolCallId, }); break; case "tool_execution_end": if (typeof event.toolCallId === "string") this.endTool(event.toolCallId); break; } event.web = { streamId: this.streamId, sequence: ++this.streamSequence }; for (const l of this.listeners) { try { l(event as AgentEvent); } catch { // A throwing subscriber (SSE encode failure, UI handler bug) must not // starve the remaining subscribers — same isolation RpcProcess and // notifyRunningChange apply to their listener sets. } } for (const tap of globalThis.__tauFrameTaps ?? []) { try { tap(this, event as AgentEvent); } catch { // Same isolation as the listeners above. } } } private sessionFileSignalTimer: NodeJS.Timeout | null = null; /** Invalidate session-list metadata plus ONLY this session's parse caches * when the file path is known, else fall back to the full invalidation. * Use this on the hot event paths (agent_end, auto_compaction_end, * session_info_update, …) so a busy session does not flush every other * open session's parsed-entry cache. List metadata (sidebar order/counts) * still always refreshes. */ private invalidateSessionLists(): void { this.host.invalidateSessionLists(this._sessionFile || undefined); invalidateHostSessionList(this.host.id); } /** Poll briefly for the session file to appear after agent_start, then * invalidate the session-list caches and re-signal the sidebar so the * running session shows up even though the file landed after the first * refresh (see the agent_start case). Bounded (max ~10s) and stops on * destroy. */ private signalWhenSessionFileAppears(): void { if (this.sessionFileSignalTimer) return; let attempts = 0; const check = () => { const sessionFile = this._sessionFile; if (!this._alive || !sessionFile) { this.sessionFileSignalTimer = null; return; } // The fired handle stays set across the async check so a re-entrant // call cannot start a second poll; destroy() still clears it. void this.host.sessionFileExists(sessionFile).then((exists) => { if (!this._alive) return; this.sessionFileSignalTimer = null; if (!exists) { attempts += 1; if (attempts < 40) { this.sessionFileSignalTimer = setTimeout(check, 250); } return; } this.invalidateSessionLists(); notifyRunningChange({ refreshSessionList: true }); }, () => { this.sessionFileSignalTimer = null; }); }; this.sessionFileSignalTimer = setTimeout(check, 250); } private lastIdleReset = 0; private resetIdleTimer(force = false): void { if (this.hostOwnedLifecycle) return; // The single activity choke point: start(), every child frame, and every // send() land here, so this is where "someone is using this session" is // observed. Tracked before the throttle below, which only limits timer // churn — it must never hide activity from the reaper. this.noteActivity(); const now = Date.now(); if (!force && this.idleTimer && now - this.lastIdleReset < 5000) { return; } this.lastIdleReset = now; if (this.idleTimer) clearTimeout(this.idleTimer); this.idleTimer = setTimeout(() => { if (this.isRunning() || this.handshaking || this.pendingCommands > 0 || this.hostDown()) { this.resetIdleTimer(true); return; } console.info("[tau] automatic-session-cleanup", JSON.stringify({ sessionId: this._sessionId, reason: "idle-timeout", at: new Date().toISOString() })); this.destroy("idle-timeout"); }, IDLE_DESTROY_MS); // A cleanup deadline must not keep the process alive; the registry's // process-exit handler disposes every child anyway. this.idleTimer.unref?.(); } /** `internal`: tau's own listener (waitForTurnEnd), never handed a parked host call. */ onEvent(listener: EventListener, { internal = false }: { internal?: boolean } = {}): () => void { if (internal) this.internalListeners.add(listener); this.listeners.push(listener); this.reportInterest(); this.noteActivity(); const now = Date.now(); // A tab attaching mid-message needs the whole message before pi's next delta. if (!internal && this.streamingMessage?.role === "assistant" && this.streamingMessageId !== null) { listener({ type: "message_update", messageId: this.streamingMessageId, message: withStreamedArguments(this.streamingMessage), web: { streamId: this.streamId, sequence: this.streamSequence }, }); } for (const [id, event] of this.pendingUiRequests) { const expiresAt = event.expiresAt as number | undefined; if (expiresAt !== undefined && expiresAt <= now) { this.expirePendingUiRequest(id); continue; } listener({ ...event, web: { streamId: this.streamId, sequence: ++this.streamSequence } }); } // Own host calls parked while no tab could answer go to the first tab that attaches, once. for (const id of internal ? [] : [...this.parkedHostTools.keys()]) { this.unparkHostTool(id); const event = this.pendingHostTools.get(id)?.event; if (event) listener({ ...event, web: { streamId: this.streamId, sequence: ++this.streamSequence } }); } return () => { const i = this.listeners.indexOf(listener); if (i !== -1) this.listeners.splice(i, 1); this.reportInterest(); // No UI attached anymore: reject outstanding host tool calls so the // agent never waits forever on a tool nobody will answer. if (!this.hasBrowserSubscribers()) { this.rejectPendingHostTools("The web UI disconnected while the agent was waiting for this host tool", "own"); // The last tab left. Start (not extend) the reap clock, so a session // that was never watched at all — /api/agent/new — is // cleaned up on the same schedule as one whose tab just closed. this.reapDeadline = Date.now() + this.disconnectDestroyMs; this.armReap(); } }; } onDestroy(cb: () => void): void { this.onDestroyCallback = cb; } /** * Wait for the next `terminalEndsNeeded` terminal turn ends after this * call (terminal agent_end, prompt_result, or prompt_error). The caller * registers the waiter BEFORE sending the prompt/steer/follow_up, so a * fast turn cannot end before the waiter exists. Rejects on timeout; * the target is left running (never aborted by a waiter timeout). * A follow_up sent to a running target needs two ends: the running * turn ends first, then the queued message's own turn ends. */ waitForTurnEnd(timeoutMs: number, terminalEndsNeeded = 1): Promise { return new Promise((resolve, reject) => { let done = false; let endsSeen = 0; const timer = setTimeout(() => finish(new Error("Timed out waiting for the target session's response.")), timeoutMs); timer.unref?.(); const detach = this.onEvent((event) => { if (event.type === "agent_end" && event.isTerminal === false) return; if (event.type === "agent_end" || event.type === "prompt_result") { endsSeen += 1; if (endsSeen >= terminalEndsNeeded) finish(null); } else if (event.type === "prompt_error") { finish(new Error(typeof event.errorMessage === "string" ? event.errorMessage : "Target session turn failed.")); } }, { internal: true }); const finish = (error: Error | null) => { if (done) return; done = true; clearTimeout(timer); detach(); if (error) reject(error); else resolve(); }; }); } /** * Answer a server-side agent tool call (#275) from this wrapper's child. * Runs on the server, with no browser involved, and answers directly * with host_tool_result — never via pendingHostTools, so a later tab * disconnect cannot settle it as a UI call. */ private async answerServerAgentTool(event: UnsequencedAgentEvent, sourceProc: RpcProcess): Promise { const id = typeof event.id === "string" ? event.id : ""; const toolName = typeof event.toolName === "string" ? event.toolName : ""; if (!id) return; const proc = sourceProc; const sendResult = (text: string, isError = false) => { proc.sendFrame({ type: "host_tool_result", id, isError, result: { content: [{ type: "text", text }] }, }); }; if (!this._alive || sourceProc === this.restartingProc) { sendResult(this._alive ? RESTARTING_MESSAGE : "Session is no longer running", true); return; } const sourceSessionId = this.sessionId; const sourceSessionFile = this._sessionFile; const cancel = new AbortController(); const sendToolResult = (text: string, isError = false) => { if (cancel.signal.aborted && (this.sessionId !== sourceSessionId || this._sessionFile !== sourceSessionFile)) return; sendResult(text, isError); }; this.serverToolCalls.set(id, cancel); try { const args = event.arguments && typeof event.arguments === "object" ? event.arguments as Record : {}; const getSessionId = () => this.sessionId; const context: AgentToolContext = { get sourceSessionId() { return getSessionId(); }, sourceSessionName: this._sessionName ?? null, sourceRequestId: id, sourceCwd: this.cwd, sourceHostId: this.host.id, sourceHostLabel: this.host.label, enabled: loadWebServerSettings().agentToolsEnabled, guard: getAgentToolGuard(), confirm: (title, payload) => this.confirmFromServer(title, payload, cancel.signal), signal: cancel.signal, }; if (this.replaying && toolName === "new_session" && ( args.shareWorkspace === true || args.host != null || !poolProjectBindings(loadPools()).get(this.host.id)?.size )) throw new Error(AGENT_TOOL_UNKNOWN_OUTCOME); const result = await executeAgentTool(toolName, args, createAgentToolOps(context, this.replaying), context); sendToolResult(typeof result === "string" ? result : JSON.stringify(result)); } catch (error) { if (error instanceof PoolStartError) { sendToolResult(JSON.stringify({ error: error.message.slice(0, 1024), code: error.code.slice(0, 128), sessionId: error.sessionId, hostId: error.hostId, cwd: error.cwd, delivery: error.delivery, }), true); } else { sendToolResult(error instanceof Error ? error.message : String(error), true); } } finally { if (this.serverToolCalls.get(id) === cancel) this.serverToolCalls.delete(id); } } private abortServerToolCalls(): void { for (const controller of this.serverToolCalls.values()) controller.abort(); } /** Called when a session-changing command re-keyed this wrapper (branch/new_session/switch_session). */ onIdentityChange(cb: (oldId: string, newId: string) => void): void { this.onIdentityChangeCallback = cb; } private async withFinalRunningNotification(operation: () => Promise): Promise { try { return await operation(); } finally { notifyRunningChange(); } } private buildWebState(state: RpcSessionState, includeSystemPrompt = true): WebSessionState { const wasRunning = this.isRunning(); // Reconcile process-side flags with authoritative child state. this.applyIdentity({ ...state, sessionFile: state.sessionFile ?? this._sessionFile }); this.streamSequence += 1; const awaitingExpired = !this.awaitingAgentStart || Date.now() >= this.awaitingAgentStartDeadline; const hasPendingWork = this.promptDispatchPendingCount > 0 || this.historyEditInFlight || (this.awaitingAgentStart && !awaitingExpired) || this.pendingUiRequests.size > 0 || this.pendingHostTools.size > 0; if ( state.isStreaming === false && state.isCompacting === false && !hasPendingWork && Date.now() >= this.continuationGraceUntil ) { this.promptRunning = false; this.awaitingAgentStart = false; this.awaitingAgentStartDeadline = 0; this.clearLiveSnapshots(); } if (wasRunning && !this.isRunning()) { notifyRunningChange(); } return { sessionId: state.sessionId, sessionFile: state.sessionFile ?? "", sessionName: state.sessionName, isStreaming: state.isStreaming, isPromptRunning: this.promptRunning, isBashRunning: this.bashRunning, responseObserved: this.responseObserved, isCompacting: state.isCompacting, autoCompactionEnabled: state.autoCompactionEnabled, autoRetryEnabled: state.autoRetryEnabled, steeringMode: state.steeringMode, followUpMode: state.followUpMode, model: state.model ? { id: state.model.id, provider: state.model.provider, name: state.model.name, reasoning: state.model.reasoning, thinkingLevelMap: state.model.thinkingLevelMap, } : undefined, messageCount: state.messageCount, queuedMessageCount: state.queuedMessageCount, queuedMessages: state.queuedMessages ?? { steering: [], followUp: [] }, ...(state.supportsClientMessageIds === true ? { supportsClientMessageIds: true } : {}), contextUsage: state.contextUsage ?? null, // `?systemPrompt=0` drops the ~13 KB prompt from the 15 s state poll. ...(includeSystemPrompt ? { systemPrompt: state.systemPrompt?.join("\n\n") ?? "" } : {}), thinkingLevel: state.thinkingLevel ?? "off", todoPhases: state.todoPhases ?? [], extensionStatuses: Array.from(this.extensionStatuses, ([key, text]) => ({ key, text })), extensionWidgets: Array.from(this.extensionWidgets.values()), }; } private async getStateWithTimeout(timeoutMs = GET_STATE_TIMEOUT_MS): Promise { return this.proc.sendCommand({ type: "get_state" }, timeoutMs); } /** After branch/new_session/switch_session the child is on a different * session file — re-read identity and re-register in the registry. */ private async refreshIdentityAfterSessionChange(): Promise { const oldId = this._sessionId; const state = await this.getStateWithTimeout(); this.applyIdentity(state); if (oldId && oldId !== this._sessionId) { this.onIdentityChangeCallback?.(oldId, this._sessionId); } this.invalidateSessionLists(); return this._sessionId; } private async editMessage(entryId: unknown): Promise { if (typeof entryId !== "string" || !entryId.trim()) { throw new WebRpcError("The edit target must be a user message", "invalid_edit_target"); } if (this.isRunning() || this.historyMutationPendingCount > 1) { throw new WebRpcError("Wait for the current operation to finish before editing", "session_busy"); } // Set synchronously, before the first native query: a second tab must not // send a prompt, fork, or switch the process during either preflight await. this.historyEditInFlight = true; const proc = this.proc; // Other web apps sharing the child are fenced by the host's lease, acquired before preflight and held through postflight. let leased = false; const sessionId = this._sessionId; const sessionFile = this._sessionFile; notifyRunningChange(); try { if (proc.transport?.setEditing) { leased = await proc.transport.setEditing(true).then(() => true, (error: unknown) => { if (error instanceof HostOpError && error.code === "session_busy") throw new WebRpcError(error.message, "session_busy"); throw error; }); } const before = await this.getStateWithTimeout(); if (before.sessionId !== sessionId || before.sessionFile !== sessionFile || this._sessionId !== sessionId || this._sessionFile !== sessionFile) { throw new WebRpcError("The session changed before the history edit", "session_changed"); } if (typeof before.isSettled !== "boolean") { throw new WebRpcError("Editing history requires a newer pi that reports full session settlement", "session_edit_unsupported"); } if (!before.isSettled || before.hasPendingAsyncWork === true || before.isStreaming || before.isCompacting || before.queuedMessageCount > 0 || this.promptRunning || this.streaming || this.compacting || this.bashRunning) { throw new WebRpcError("Wait for the current run to finish before editing", "session_busy"); } // pi moves the leaf only from an extension command (`/tau_edit`, lib/pi/tau-extension.ts): navigateTree. const result = await proc.callExtension("tau_edit", { entryId }, EDIT_TIMEOUT_MS); if (!isRecord(result) || typeof result.sessionId !== "string" || !result.sessionId.trim() || typeof result.cancelled !== "boolean" || (result.leafId !== null && typeof result.leafId !== "string")) { throw new Error("pi returned an invalid history edit result"); } const after = await this.getStateWithTimeout(); // pi never moves a session to a new id: any other conversation means the session changed. if (!this.isAlive() || this.proc !== proc || result.sessionId !== sessionId || after.sessionId !== sessionId || after.sessionFile !== sessionFile || this._sessionId !== sessionId || this._sessionFile !== sessionFile) { throw new WebRpcError("The session changed during the history edit", "session_changed"); } if (result.cancelled) return result; this.clearLiveSnapshots(); this.responseObserved = false; this.responseRunActive = false; this.awaitingAgentStart = false; this.awaitingAgentStartDeadline = 0; this.continuationGraceUntil = 0; // Invalidate the confirmed edited conversation, not its preserved source. this.invalidateSessionLists(); this.emit({ type: "session_history_changed", leafId: result.leafId }); notifyRunningChange({ refreshSessionList: true }); return result; } catch (error) { if (error instanceof RpcCommandTimeoutError) { if (this.linkLostDuring(error)) throw this.hostOfflineError("unknown"); // A timed-out navigation may still be running in a hook. Do not let a // later mutation race it once the web-side fence is released. await this.destroyAndWait("session-unresponsive", true); throw new WebRpcError("The pi session stopped responding and was reset.", "session_unresponsive"); } throw error; } finally { this.historyEditInFlight = false; if (leased) void proc.transport?.setEditing?.(false).catch(() => {}); // A lost release ends when this link drops. notifyRunningChange(); } } /** Full restart of the child process against the same session file. This is * tau's `reload`: extensions, skills, prompts, and tools are rediscovered * on boot, matching a fresh CLI launch. */ private async restart(): Promise { if (this.restarting) throw new WebRpcError(RESTARTING_MESSAGE, "session_restarting"); const sessionFile = this._sessionFile; const old = this.proc; // Stays true for the whole restart so send() rejects commands that would // otherwise hit the disposed or half-built child. this.restarting = true; this.restartingProc = old; this.abortServerToolCalls(); let resumable: boolean; try { // Asked before touching the live child: a remote host can be offline, // and the child must then keep running with its frames still read. resumable = !!sessionFile && await this.host.sessionFileExists(sessionFile); } catch (error) { this.restarting = false; this.restartingProc = null; throw error; } this.resetStream(); this.streaming = false; this.promptRunning = false; this.compacting = false; this.unsubscribeFrames?.(); try { this.expectedExitProc = old; let exited = false; const disposing = old.dispose(5_000, true).then(() => { exited = true; }); // Behind a dropped link the old child's exit arrives only when the link // returns: the reload must not hold `restarting` through the outage. await untilHostDown(this.host, disposing); if (!exited) { // It may still run there, so nothing starts beside it: commands answer // host_offline until its exit (via the link, or `lost` on the next hello) // ends this wrapper, and the next request then spawns afresh. this.oldChildExiting = true; void disposing.then(() => { if (this.proc === old) this.destroy("reload-old-child-exited"); }); throw this.hostOfflineError("unknown"); } if (this.expectedExitProc === old) this.expectedExitProc = null; if (!this._alive) return; this.extensionStatuses.clear(); this.extensionWidgets.clear(); this.clearPendingUiRequests(); this.promptRunning = false; this.promptDispatchPendingCount = 0; this.awaitingAgentStart = false; this.awaitingAgentStartDeadline = 0; this.continuationGraceUntil = 0; this.bashRunning = false; this.streaming = false; this.compacting = false; const spawned = await this.host.spawnRpc({ cwd: this.cwd, recordedCwd: this.recordedCwd, sessionFile: resumable ? sessionFile : "", toolNames: undefined, }, resumable ? this._sessionId : null); const proc = new RpcProcess({ cwd: spawned.cwd, transport: spawned.transport, ...(spawned.transport.hostOwnedLifecycle ? { adopted: true as const } : {}), onExit: (info) => { if (this.proc === proc) this.handleProcessExit(info, proc); }, }); // Destroyed while the host was spawning: nobody will ever read this child. if (!this._alive) { void proc.dispose(); return; } this.proc = proc; // Callback ids belong to the old child; the replacement's must not be suppressed. this.deliveredCallbacks.clear(); this.messageCommandGeneration += 1; this.confirmedMessageCommandGeneration = this.messageCommandGeneration; this.unsubscribeFrames = proc.onFrame((frame) => this.handleFrame(frame, proc)); this.watchResync(proc); this.reportInterest(); try { if (this.hostOwnedLifecycle) { await this.adopt([...(spawned.pending ?? []), ...(spawned.streaming ? [spawned.streaming] : [])]); } else { await proc.waitReady(READY_TIMEOUT_MS); } const state = await proc.sendCommand({ type: "get_state" }, STARTUP_COMMAND_TIMEOUT_MS); this.applyIdentity(state); // Same fresh-spawn guard as startRpcSession: a sessionless wrapper // restarts bare and must never land on an existing session. An on-disk session file is the resume // signal (fresh children report a not-yet-created path). if (!resumable && this._sessionFile && await this.host.sessionFileExists(this._sessionFile)) { await proc.sendCommand({ type: "new_session" }); this.applyIdentity(await proc.sendCommand({ type: "get_state" }, GET_STATE_TIMEOUT_MS)); } if (this.hostOwnedLifecycle) { if (this.registeredHostTools !== null) { await this.dispatchCommand({ type: "set_host_tools", tools: this.registeredHostTools }); } else if (loadWebServerSettings().agentToolsEnabled) { // Like initial startup, a runtime that never accepted host tools may reject this optional registration. await this.dispatchCommand({ type: "set_host_tools", tools: [] }).catch(() => {}); } } } catch (error) { // Never leave the replacement running with nobody reading its frames. this.unsubscribeFrames?.(); this.unsubscribeFrames = null; void proc.dispose(); // The wrapper has no usable child left; drop it from the registry so the // next request starts a fresh session instead of reusing a corpse. this.destroy(); throw error; } } finally { this.restartingProc = null; this.restarting = false; } notifyRunningChange(); } /** Protect submitted command work, including route preparation, from both idle reapers. * `takeOverOpen`: this is the command its open requested a preparation lease for. */ async withPendingCommand(callback: () => Promise, takeOverOpen = false): Promise { this.resetIdleTimer(); this.pendingCommands += 1; this.reportInterest(); const preparing = this.proc.transport; preparing?.setPreparing?.(true, takeOverOpen); try { return await callback(); } finally { this.pendingCommands -= 1; preparing?.setPreparing?.(false); this.reportInterest(); } } /** Process-local admission only, not a native message id: overlapping writes make echo inference uncertain. */ getMessageCommandGeneration(): number { return this.messageCommandGeneration; } /** Changes whenever frames may have been lost, so a missing echo then proves nothing. */ getFrameGaps(): number { return this.frameGaps; } /** ACKs and settlement events aren't command-specific echo receipts: earlier writes need an uncontended replacement * proof, or a settled native read after every one of them was answered (clearMessageProofTaintIfSettled). */ hasPendingMessageCommands(): boolean { return this.pendingMessageCommands > 0 || this.confirmedMessageCommandGeneration !== this.messageCommandGeneration; } /** Only advance a contiguous, uncontended admission after its replacing frame (or a no-agent builtin receipt). */ confirmMessageCommandGeneration(generation: number): void { if (generation === this.messageCommandGeneration && generation === this.confirmedMessageCommandGeneration + 1) { this.confirmedMessageCommandGeneration = generation; } } private messageBoundaryBusy(ownedPendingCommands = 0): boolean { return this.isRunning() || this.historyEditInFlight || this.historyMutationPendingCount > 0 || this.pendingCommands > ownedPendingCommands || this.pendingMessageCommands > 0 || this.pendingUiRequests.size > 0 || this.pendingHostTools.size > 0; } /** Lifts the taint of OLD uncertain admissions once none can echo any more; never confirms or replays them. Settlement * events and elapsed time alone never clear it: only a get_state read after every admission was answered, reporting * no live, admitted or scheduled run, queued message or background work (pi's isSettled). One read at a time: a * caller arriving while it runs gets the same answer. True only when the taint is gone. */ clearMessageProofTaintIfSettled(): Promise { if (this.taintRead) return this.taintRead; if (!this.hasPendingMessageCommands() || this.restarting || this.hostDown() || this.messageBoundaryBusy()) return Promise.resolve(false); const read = this.withPendingCommand(async () => { // A restart (the only child swap) advances the generation, so it needs no separate check. An admission // completed during the read advances it too; the taint then remains and the answer must be false. const generation = this.messageCommandGeneration; const peers = this.peerMessageCommands; const state = await this.getStateWithTimeout(); if (state.isSettled !== true || state.hasPendingAsyncWork === true || state.isStreaming !== false || state.isCompacting !== false || state.queuedMessageCount > 0 || queueTexts(state.queuedMessages).length > 0 || state.sessionId !== this._sessionId || state.sessionFile !== this._sessionFile || this.messageCommandGeneration !== generation || this.peerMessageCommands !== peers || this.restarting || this.messageBoundaryBusy(1) || !this.hasPendingMessageCommands()) return false; this.confirmedMessageCommandGeneration = generation; return true; }).finally(() => { this.taintRead = null; }); this.taintRead = read; return read; } /** The outbox supplies its persisted pre-dispatch boundary; direct writes reuse this same proof below. */ watchMessageReplacement(command: Record, baseline: unknown, generation: number, competingPending: boolean, previousEntryIds?: string[]): MessageReplacementWatch { const proof = watchReplacement(this, command, baseline, generation, competingPending, previousEntryIds); this.messageReplacement = proof; return { handOff: proof.handOff, replied: proof.replied, stop: () => { proof.stop(); if (this.messageReplacement === proof) this.messageReplacement = null; }, }; } /** `correlationKey`: the command a caller submitted through `send`; marked once its native message write begins. */ /** pi's queue was taken back: the extension's names for it will never start (best effort; it journals them withdrawn). */ private forgetQueuedNames(): void { if (this.proc.tauExtension) void this.proc.callExtension("tau_meta", { action: "clear" }, GET_STATE_TIMEOUT_MS).catch(() => {}); } private async sendNativeMessageCommand(command: { type: string; [key: string]: unknown }, timeoutMs?: number, correlationKey?: object): Promise { const message = IMAGE_BEARING_COMMANDS.has(command.type); const proof = message && !this.messageReplacement && !this.hasPendingMessageCommands() ? watchReplacement(this, command, this.nativeQueuedMessages, this.messageCommandGeneration, false, this.startedEmpty && !this.adopted && this.messageCommandGeneration === 0 ? [] : undefined) : null; if (message) { this.messageCommandGeneration += 1; this.pendingMessageCommands += 1; if (correlationKey) nativeWrites().add(correlationKey); } const generation = this.messageCommandGeneration; try { // pi keeps no client ids: the companion extension binds this name to the message pi admits next with this text. if (message && this.proc.tauExtension && isClientMessageId(command.clientMessageId) && typeof command.message === "string") { await this.proc.callExtension("tau_meta", { action: "name", clientMessageId: command.clientMessageId, text: command.message, ...(isRecord(command.origin) ? { origin: command.origin } : {}), }, GET_STATE_TIMEOUT_MS).catch(() => {}); } const replacement = proof ?? this.messageReplacement; const result = await this.proc.sendCommand(command, timeoutMs, message && replacement ? (_ok, id) => replacement.replied(proof ? command : correlationKey ?? command, id) : undefined); if (message && isRecord(result) && result.agentInvoked === false) { this.confirmMessageCommandGeneration(generation); proof?.stop(); } else if (proof) { void proof.handOff().then((outcome) => { if (!outcome.error || outcome.mayHaveBeenSent === false) this.confirmMessageCommandGeneration(generation); }).finally(proof.stop); } return result; } catch (error) { proof?.stop(); if (message && error instanceof RpcCommandError) this.confirmMessageCommandGeneration(generation); throw error; } finally { if (message) this.pendingMessageCommands -= 1; } } async send(command: Record, options?: { preserveUnknownDelivery?: boolean; origin?: MessageOrigin }): Promise { if (this.restarting) throw new WebRpcError(RESTARTING_MESSAGE, "session_restarting"); if (!this.isAlive()) throw new Error("Session is no longer running"); if (this.hostDown() || this.oldChildExiting) throw this.hostOfflineError("refused"); if (command.origin !== undefined) throw new WebRpcError("Message origin is server-owned.", "origin_not_allowed"); // tau's extension commands are tau's own (callExtension): a message must not name, rewind or log in as tau. if ((command.type === "prompt" || command.type === "steer" || command.type === "follow_up") && typeof command.message === "string" && /^\s*\/tau_/.test(command.message)) { throw new WebRpcError("Messages cannot run tau's own /tau_* commands.", "tau_command_not_allowed"); } const trustedCommand = options?.origin ? { ...command, origin: options.origin } : command; if (typeof command.type === "string" && command.type.startsWith("abort")) { console.info("[tau] cancellation-command", JSON.stringify({ sessionId: this._sessionId, type: command.type, at: new Date().toISOString() })); } const mutatesHistory = HISTORY_MUTATING_COMMANDS.has(command.type as string); if (mutatesHistory && this.historyEditInFlight) { throw new WebRpcError("Wait for the history edit to finish", "session_busy"); } if (mutatesHistory) this.historyMutationPendingCount += 1; try { return await this.withPendingCommand(() => this.dispatchCommand(trustedCommand, options?.preserveUnknownDelivery === true, command)); } finally { if (mutatesHistory) this.historyMutationPendingCount -= 1; } } /** A failed prompt's last word: `promptRunning` with no run, compaction, pending start, continuation window or other * prompt in flight belongs to nobody (two prompts refused in turn leave it so), and would keep the session running. */ private settleOrphanedPrompt(ownDispatches: number): void { if (!this.promptRunning || this.streaming || this.compacting || this.awaitingAgentStart || this.promptDispatchPendingCount > ownDispatches || Date.now() < this.continuationGraceUntil) return; this.promptRunning = false; notifyRunningChange(); } private async dispatchCommand(command: Record, preserveUnknownDelivery = false, correlationKey: object = command): Promise { const type = command.type as string; if (IMAGE_BEARING_COMMANDS.has(type)) { const imageError = validateAgentImages(command.images); if (imageError) throw new Error(imageError); } const unsupported = UNSUPPORTED_COMMANDS[type]; if (unsupported) throw new RpcCommandError(type, unsupported, "unsupported"); switch (type) { case "prompt": { const streamingBehavior = command.streamingBehavior as "steer" | "followUp" | undefined; // pi refuses a bare prompt during a run ("already processing"). Sent while a run, compaction or another // prompt is active, the prompt leaves that state alone; only pi taking it (the run had ended) starts its own. const joinsRun = !streamingBehavior && (this.streaming || this.promptRunning || this.compacting); const runStarts = this.runStarts; if (!streamingBehavior) this.promptDispatchPendingCount += 1; if (!streamingBehavior && !joinsRun) { this.responseObserved = false; this.responseRunActive = false; if (!this.isRunning()) this.clearLiveSnapshots(); this.streamSequence += 1; this.promptRunning = true; this.awaitingAgentStart = false; this.awaitingAgentStartDeadline = 0; this.continuationGraceUntil = 0; notifyRunningChange(); } try { // pi acks immediately; agent output streams as events, completion is // agent_end (agent runs) or prompt_result (local-only slash commands). const ack = await this.sendNativeMessageCommand<{ agentInvoked?: boolean } | undefined>({ type: "prompt", message: command.message as string, ...(toImageContents(command.images) ? { images: toImageContents(command.images) } : {}), ...(streamingBehavior ? { streamingBehavior } : {}), ...(isClientMessageId(command.clientMessageId) ? { clientMessageId: command.clientMessageId } : {}), ...(isRecord(command.origin) ? { origin: command.origin } : {}), }, PROMPT_ACK_TIMEOUT_MS, correlationKey); if (joinsRun) { // An extension command ran beside the run (agentInvoked:false), or a run already started: nothing to start. if (ack?.agentInvoked !== false && this.runStarts === runStarts) { this.responseObserved = false; this.responseRunActive = false; this.promptRunning = true; this.awaitingAgentStart = true; this.awaitingAgentStartDeadline = Date.now() + AWAITING_AGENT_START_TIMEOUT_MS; this.continuationGraceUntil = 0; notifyRunningChange(); } if (ack?.agentInvoked !== false) return null; // A command that ran beside a prompt which failed meanwhile is the last one out of a promptRunning nobody owns. this.settleOrphanedPrompt(1); return ack; } // Slash commands fully consumed by a builtin report agentInvoked:false // in the ack itself — no prompt_result frame follows. if (ack?.agentInvoked === false && !streamingBehavior) { this.promptRunning = false; this.awaitingAgentStart = false; this.awaitingAgentStartDeadline = 0; this.emit({ type: "prompt_result", agentInvoked: false }); notifyRunningChange(); } else if (!streamingBehavior && ack?.agentInvoked !== false) { // pi acked but agent hasn't started yet — keep promptRunning alive // until agent_start arrives (or a timeout expires). this.awaitingAgentStart = true; this.awaitingAgentStartDeadline = Date.now() + AWAITING_AGENT_START_TIMEOUT_MS; } if (ack?.agentInvoked === false) return ack; } catch (error) { if (preserveUnknownDelivery && error instanceof RpcCommandTimeoutError) { throw new WebRpcError("The initial prompt may have reached its session; check that session before sending it again.", "host_offline", "unknown"); } if (!(error instanceof RpcCommandTimeoutError)) { // A prompt that joined a run never touched its state. An idle prompt leaves the state to a run that started // meanwhile (another tab or server), a compaction, or a prompt still in flight or awaiting its agent_start. const inFlight = streamingBehavior ? 0 : 1; if (streamingBehavior || joinsRun || this.streaming || this.compacting || this.awaitingAgentStart || this.promptDispatchPendingCount > inFlight) { this.settleOrphanedPrompt(inFlight); throw error; } } this.promptRunning = false; this.awaitingAgentStart = false; this.awaitingAgentStartDeadline = 0; this.streaming = false; this.clearLiveSnapshots(); notifyRunningChange(); if (error instanceof RpcCommandTimeoutError) { if (this.linkLostDuring(error)) throw this.hostOfflineError("unknown"); // The child took the frame but never acked it, so nothing will ever // report this run: recycle the unacknowledged prompt. A read-only // get_state timeout deliberately does not take this destructive path. await this.destroyAndWait("session-unresponsive", true); throw new WebRpcError("The pi session stopped responding and was reset.", "session_unresponsive"); } throw error; } finally { if (!streamingBehavior) { this.promptDispatchPendingCount = Math.max(0, this.promptDispatchPendingCount - 1); } } return null; } case "steer": case "follow_up": { await this.sendNativeMessageCommand({ type, message: command.message as string, ...(toImageContents(command.images) ? { images: toImageContents(command.images) } : {}), ...(isClientMessageId(command.clientMessageId) ? { clientMessageId: command.clientMessageId } : {}), ...(isRecord(command.origin) ? { origin: command.origin } : {}), }, undefined, correlationKey); return null; } // pi takes the queue back only whole: clear_queue returns every queued text (never images). // Like a control read, expiry must not abort unrelated work or replay a possibly applied mutation. case "clear_queue": { const result = await this.proc.sendCommand({ type: "clear_queue" }, GET_STATE_TIMEOUT_MS); this.forgetQueuedNames(); return result ?? null; } // The extension journals which messages pi persisted, queued or withdrew (`/tau_meta` status). case "get_client_message_status": return await this.proc.callExtension("tau_meta", { action: "status", clientMessageIds: command.clientMessageIds }, GET_STATE_TIMEOUT_MS); // abort_and_restore_queue is the TUI's Esc: clear_queue before abort (pi runs a queued // message as soon as an abort lands), then report the withdrawn texts as entries. case "abort": case "abort_and_restore_queue": { this.responseObserved = false; this.responseRunActive = false; const result = await this.withFinalRunningNotification(async () => { const withdrawn = type === "abort" ? null : await this.proc.sendCommand<{ steering?: unknown; followUp?: unknown }>({ type: "clear_queue" }, GET_STATE_TIMEOUT_MS); if (withdrawn) this.forgetQueuedNames(); try { await this.proc.sendCommand({ type: "abort" }); } catch (error) { // The withdrawn texts exist only in this answer: return them, and let state reconciliation show the run. if (!withdrawn) throw error; console.warn(`[tau] abort after clear_queue failed for ${this._sessionId}: ${error instanceof Error ? error.message : String(error)}`); } const entries = (texts: unknown) => (Array.isArray(texts) ? texts : []).filter((text) => typeof text === "string").map((text) => ({ text })); const response = withdrawn && { steering: entries(withdrawn.steering), followUp: entries(withdrawn.followUp) }; // If the prompt was aborted before the agent loop started, no // agent_end will arrive to clear the flag; the streaming flag still // tracks a live turn that ends with its own agent_end. this.promptRunning = false; // Clear the pending-start bookkeeping too: hasPendingWork would // otherwise suppress stale-state reconciliation for the full // AWAITING_AGENT_START_TIMEOUT_MS, leaving the UI showing "running" // after an early abort. this.awaitingAgentStart = false; this.awaitingAgentStartDeadline = 0; this.continuationGraceUntil = 0; this.clearLiveSnapshots(); return response; }); return type === "abort" ? null : result ?? null; } case "get_state": { try { const state = await this.proc.sendCommand({ type: "get_state" }, GET_STATE_TIMEOUT_MS); return this.buildWebState(state, command.systemPrompt !== false); } catch (error) { if (error instanceof RpcCommandTimeoutError) { // This is only an observer poll. A busy event loop or delayed RPC // response is not authority to stop generation or a pending tool. console.warn("[tau] status-query-timeout", JSON.stringify({ sessionId: this._sessionId, timeoutMs: GET_STATE_TIMEOUT_MS, running: this.isRunning(), action: "preserved", at: new Date().toISOString() })); throw new WebRpcError("The pi status query timed out. The session was left running; retry shortly.", "session_state_timeout"); } throw error; } } case "set_model": { const { provider, modelId } = command as { provider: string; modelId: string }; const model = await this.proc.sendCommand({ type: "set_model", provider, modelId }, preserveUnknownDelivery ? PROMPT_ACK_TIMEOUT_MS : undefined); invalidateModelsCache(); this.invalidateSessionLists(); return { id: model.id, provider: model.provider }; } case "edit_message": return this.editMessage(command.entryId); case "fork": { // pi's `fork` creates a session file holding the history before the // entry and switches this live process onto it (entryId must be a user // message entry, matching the web UI's fork buttons). if (this.bashRunning) { throw new Error("Cannot fork while a shell command is running"); } const result = await this.proc.sendCommand<{ text: string; cancelled: boolean }>({ type: "fork", entryId: command.entryId as string, }); if (result.cancelled) return { cancelled: true }; const newSessionId = await this.refreshIdentityAfterSessionChange(); // `text` is the forked-at prompt pi hands back for edit-and-resend. return { cancelled: false, newSessionId, text: result.text }; } case "new_session": case "switch_session": { const result = await this.proc.sendCommand<{ cancelled: boolean }>(command as { type: string }); if (!result.cancelled) { const newSessionId = await this.refreshIdentityAfterSessionChange(); return { cancelled: false, newSessionId }; } return result; } case "compact": { try { return await this.withFinalRunningNotification(async () => { this.compacting = true; this.streamSequence += 1; notifyRunningChange(); try { const result = await this.proc.sendCommand({ type: "compact", ...(command.customInstructions ? { customInstructions: command.customInstructions } : {}), }); patchEstimatedTokensAfter(result); return result; } finally { this.compacting = false; this.streamSequence += 1; } }); } finally { this.invalidateSessionLists(); } } case "abort_compaction": // No dedicated RPC command; a plain abort cancels the in-flight turn // including compaction work. await this.withFinalRunningNotification(() => this.proc.sendCommand({ type: "abort" })); return null; case "set_session_name": { const name = (command.name as string | undefined)?.trim(); if (!name) throw new Error("Session name cannot be empty"); await this.proc.sendCommand({ type: "set_session_name", name }, preserveUnknownDelivery ? PROMPT_ACK_TIMEOUT_MS : undefined); this._sessionName = name; this.invalidateSessionLists(); return null; } case "get_session_stats": { const stats = await this.proc.sendCommand>({ type: "get_session_stats" }); return { ...stats, sessionName: this._sessionName }; } case "get_last_assistant_text": { const data = await this.proc.sendCommand<{ text: string | null }>({ type: "get_last_assistant_text" }); return { text: data.text ?? "" }; } case "get_commands": { return this.proc.sendCommand<{ commands: RpcAvailableSlashCommand[] }>({ type: "get_available_commands" }); } case "reload": { await this.restart(); return { success: true }; } case "ui_response": { const { id, value } = command; if (typeof id !== "number" && typeof id !== "string") throw new WebRpcError("Invalid dialog id", "invalid_ui_response"); const key = String(id); const serverRequest = this.serverUiRequests.get(key); // A host tool call is answered with host_tool_result: its bookkeeping must see the answer. if (!serverRequest && this.pendingHostTools.has(key)) throw new WebRpcError("Invalid dialog id", "invalid_ui_response"); const pending = this.pendingUiRequests.get(key); const method = pending?.method; // A malformed answer would drop the dialog from reconnect replay while pi rejects it. if (value !== undefined && method === "askDialog" && !isRecord(value)) { throw new WebRpcError("Invalid dialog answer", "invalid_ui_response"); } // The ask dialog parses the submitted results exactly: one answer per // question, only offered labels, no duplicate on a single-select. Refuse // a payload it would reject before the dialog is consumed. if (value !== undefined && method === "askDialog" && isRecord(value) && value.kind === "submit") { const questions = pending && Array.isArray(pending.args) ? (pending.args as unknown[])[0] : undefined; const problem = askAnswersProblem(value.results, questions); if (problem) throw new WebRpcError(`Invalid ask dialog answers: ${problem}`, "invalid_ask_answers"); } const wasPending = this.settlePendingUiRequest(key); if (serverRequest) { this.serverUiRequests.delete(key); serverRequest(value === true); } else { // pi names its dialogs with UUIDs; RpcProcess answers by that string id. this.proc.sendFrame({ type: "ui_response", id: key, value }); } // pi sends no ui_end for a dialog the host answered; other tabs on this // session would keep showing it, so settle it for them here. if (wasPending) this.emit({ type: "ui_end", id }); return null; } case "bash": { const proc = this.proc; if (command.excludeFromContext !== undefined && typeof command.excludeFromContext !== "boolean") { throw new Error("excludeFromContext must be a boolean"); } // A turn may be running: pi runs the command beside it and, as its // terminal does, records the result only when the next prompt starts. if (this.bashRunning) { throw new Error("A shell command is already running"); } this.bashRunning = true; notifyRunningChange(); try { // pi holds the result back while it streams; frames and the reply // share stdout, so `streaming` when the reply is read is pi's own // `isStreaming`. Read it then: an agent_end in the same batch is // applied before this await resumes. let deferred = this.streaming; const result = await proc.sendCommand({ type: "bash", command: command.command as string, ...(command.excludeFromContext === true ? { excludeFromContext: true } : {}), }, undefined, () => { deferred = this.streaming; }); return { ...result, deferred }; } finally { this.bashRunning = false; this.invalidateSessionLists(); notifyRunningChange(); } } case "set_host_tools": { const tools = Array.isArray(command.tools) ? command.tools as Array<{ name?: unknown; [key: string]: unknown }> : []; const valid = tools.filter((t) => typeof t.name === "string" && t.name); // Merge the server agent tools (#275) into every registration when // the gate is on, so a later UI registration cannot drop them and // a no-tab session keeps them after its startup registration. // With the gate off the registration is exactly what the caller // asked for, so existing behavior and tests are unchanged. const merged = loadWebServerSettings().agentToolsEnabled ? [...valid, ...AGENT_TOOL_DEFINITIONS.filter((t) => !valid.some((v) => v.name === t.name))] : valid; if (this.hostOwnedLifecycle) { const previousNames = this.hostToolNames; this.hostToolNames = new Set(merged.map((t) => t.name as string)); try { await this.proc.transport.setHostTools!(merged); } catch (error) { this.hostToolNames = previousNames; throw error; } this.registeredHostTools = valid.filter((tool) => !AGENT_TOOL_NAMES.has(tool.name as string)); this.hostToolsUnknown = false; return null; } // Applied as the successful reply is read, before a call in the same host-link batch is routed. await this.proc.sendCommand({ type: "set_host_tools", tools: merged }, undefined, (success) => { if (!success) return; this.hostToolNames = new Set(merged.map((t) => t.name as string)); this.registeredHostTools = valid.filter((tool) => !AGENT_TOOL_NAMES.has(tool.name as string)); // pi now knows exactly these: an adopted child's lost registration is replaced. this.hostToolsUnknown = false; }); return null; } case "host_tool_result": { if (typeof command.id === "string") { this.pendingHostTools.delete(command.id); this.unparkHostTool(command.id); } this.proc.sendFrame(command as { type: string; [key: string]: unknown }); return null; } // pi-subagents' running children, as RpcProcess's bridge last saw them (pi has no such command). case "get_subagents": return { subagents: this.proc.subagents?.running() ?? [] }; // pi has no side questions: the companion extension answers them (`/tau_btw`, lib/pi/tau-extension.ts) and // streams btw_record / btw_delta frames. case "btw": return await this.proc.callExtension("tau_btw", { action: "ask", question: command.question, ...(typeof command.recordId === "string" ? { recordId: command.recordId } : {}), }); case "btw_cancel": return await this.proc.callExtension("tau_btw", { action: "cancel", recordId: command.recordId }); case "get_btw_history": return await this.proc.callExtension("tau_btw", { action: "history" }, GET_STATE_TIMEOUT_MS); default: { if (PASSTHROUGH_COMMANDS.has(type)) { const result: unknown = await this.sendNativeMessageCommand( command as { type: string }, preserveUnknownDelivery && type === "set_thinking_level" ? PROMPT_ACK_TIMEOUT_MS : undefined, correlationKey, ); if (type === "set_thinking_level") this.invalidateSessionLists(); return result ?? null; } throw new Error(`Unsupported command: ${type}`); } } } destroy(reason = "unspecified"): void { void this.destroyAndWait(reason); } /** Destroy and resolve only after the pi child has fully exited. Callers * that delete the session file afterwards must await this — a pi still * running could append an entry and recreate the file. */ async destroyAndWait(reason = "unspecified", stopShared = false): Promise { // Re-entrant calls join the in-flight dispose; without this a new spawn // can overlap the old child's shutdown (see startRpcSession). if (this.destroyPromise) return untilHostDown(this.host, this.destroyPromise); if (!this._alive) return; console.info("[tau] session-dispose", JSON.stringify({ sessionId: this._sessionId, reason, running: this.isRunning(), pendingDialogs: this.pendingUiRequests.size, at: new Date().toISOString(), caller: new Error().stack?.split("\n").slice(2, 5).map((line) => line.trim()) })); this.abortServerToolCalls(); this._alive = false; this.reportInterest(); this.deliveredCallbacks.clear(); this.emit({ type: "process_exit", reason }); this.streaming = false; this.promptRunning = false; this.compacting = false; this.responseObserved = false; this.responseRunActive = false; this.clearLiveSnapshots(); if (this.idleTimer) clearTimeout(this.idleTimer); if (this.reapTimer) { clearTimeout(this.reapTimer); this.reapTimer = null; } if (this.sessionFileSignalTimer) { clearTimeout(this.sessionFileSignalTimer); this.sessionFileSignalTimer = null; } this.unsubscribeFrames?.(); this.unsubscribeHostStatus?.(); this.unsubscribeHostStatus = null; this.clearPendingUiRequests(this.hostOwnedLifecycle && !stopShared && this.proc.isAlive ? "forgotten" : "settled"); this.promptDispatchPendingCount = 0; this.awaitingAgentStart = false; this.awaitingAgentStartDeadline = 0; this.continuationGraceUntil = 0; // The registry drops this wrapper only once the child has really exited. const disposed = this.proc.dispose(5_000, stopShared).catch(() => {}).then(() => this.onDestroyCallback?.()); this.destroyPromise = disposed; for (const id of this.pendingHostTools.keys()) this.cancelPendingHostTool(id); for (const timer of this.parkedHostTools.values()) clearTimeout(timer); this.parkedHostTools.clear(); this.hostToolNames.clear(); this.registeredHostTools = null; notifyRunningChange(); await untilHostDown(this.host, disposed); } } /** `promise`, or sooner once `host`'s link is down: a child behind a dropped * link exits only when it returns, and nothing may wait that long. */ function untilHostDown(host: Host, promise: Promise): Promise { if (!isLinkUp(host.status())) return Promise.resolve(); const { promise: settled, resolve } = Promise.withResolvers(); const unsubscribe = host.onStatus((status) => { if (!isLinkUp(status)) resolve(); }); void promise.then(resolve); return settled.finally(unsubscribe); } // ============================================================================ // Session registry // ============================================================================ export interface RunningRpcSession { id: string; cwd: string; /** Absent on this machine, as on `SessionInfo`: the sidebar groups a placeholder under it. */ hostId?: string; /** A blocking dialog (ask, confirm, input, …) waits for the user. */ awaitingInput?: true; } export interface RunningSessionUpdate { ids: string[]; runningSessions: RunningRpcSession[]; exitedSessions: ExitedRpcSession[]; refreshSessionList: boolean; } declare global { var __tauSessions: Map | undefined; var __tauStartLocks: Map> | undefined; var __tauRunningListeners: Set<(update: RunningSessionUpdate) => void> | undefined; var __tauHostToolListeners: Set<(call: CrossSessionHostToolEvent) => void> | undefined; var __tauExitedSessions: Map | undefined; var __tauFrameTaps: Set<(wrapper: AgentSessionWrapper, event: AgentEvent) => void> | undefined; var __tauNativeWrites: WeakSet | undefined; } function nativeWrites(): WeakSet { return (globalThis.__tauNativeWrites ??= new WeakSet()); } /** True once some wrapper began writing this submitted command to pi's stdin; never before. */ export function nativeWriteStarted(command: object): boolean { return nativeWrites().has(command); } function getExitedMap(): Map { if (!globalThis.__tauExitedSessions) globalThis.__tauExitedSessions = new Map(); return globalThis.__tauExitedSessions; } export function getExitedRpcSessions(): ExitedRpcSession[] { return [...getExitedMap().values()]; } export function getExitedRpcSession(sessionId: string): ExitedRpcSession | undefined { return getExitedMap().get(sessionId); } /** Clear the visible crash state once a replacement child is ready. */ export function clearExitedRpcSession(sessionId: string): boolean { const cleared = getExitedMap().delete(sessionId); if (cleared) notifyRunningChange(); return cleared; } function getRegistry(): Map { if (!globalThis.__tauSessions) { globalThis.__tauSessions = new Map(); const cleanup = () => { // Children dying from here on are the shutdown, not finished runs. markShuttingDown(); // Every child runs under a host daemon: nothing more reaches it (no kill, no // host tool rejection as tabs close on the way out), and the next server adopts them. freezeHostLinks(); }; process.once("exit", cleanup); process.once("SIGINT", cleanup); process.once("SIGTERM", cleanup); } return globalThis.__tauSessions; } function getLocks(): Map> { if (!globalThis.__tauStartLocks) globalThis.__tauStartLocks = new Map(); return globalThis.__tauStartLocks; } export function getRpcSession(sessionId: string): AgentSessionWrapper | undefined { return getRegistry().get(sessionId); } /** Every registry key of the wrapper under `sessionId` (its id and any requested alias), else `[sessionId]`. */ export function getRpcSessionKeys(sessionId: string): string[] { const wrapper = getRegistry().get(sessionId); if (!wrapper) return [sessionId]; return [...getRegistry()].flatMap(([key, live]) => (live === wrapper ? [key] : [])); } export function getRunningRpcSessions(): RunningRpcSession[] { const map = new Map(); for (const [sessionId, session] of getRegistry()) { if (session.isRunning()) { const id = session.sessionId || sessionId; map.set(id, { id, cwd: session.cwd, ...(session.host.id === LOCAL_HOST_ID ? {} : { hostId: session.host.id }), ...(session.isAwaitingInput() ? { awaitingInput: true as const } : {}), }); } } return [...map.values()]; } export function getRunningRpcSessionIds(): string[] { return getRunningRpcSessions().map((s) => s.id); } /** Ids of sessions with a live pi process (turn running or idle). */ export function getLiveRpcSessionIds(): string[] { return [...getRegistry()].filter(([, session]) => session.isAlive?.()).map(([sessionId]) => sessionId); } // ---------------------------------------------------------------------------- // Running-status broadcaster // // Pushes the current set of running session ids to subscribers whenever any // session's running state may have changed. This lets the sidebar receive live // updates over SSE instead of polling. Listeners live on globalThis so they // survive a `bun --hot` re-evaluation. // ---------------------------------------------------------------------------- function getRunningListeners(): Set<(update: RunningSessionUpdate) => void> { if (!globalThis.__tauRunningListeners) globalThis.__tauRunningListeners = new Set(); return globalThis.__tauRunningListeners; } /** Subscribe to running-session-id changes and session-list refreshes. */ export function subscribeRunningSessions(listener: (update: RunningSessionUpdate) => void): () => void { const listeners = getRunningListeners(); listeners.add(listener); return () => { listeners.delete(listener); }; } /** See every wrapper's frames after its listeners, without counting as a subscriber (the reapers ignore it): * server bookkeeping such as the message outbox's late hand-off. */ export function tapSessionFrames(tap: (wrapper: AgentSessionWrapper, event: AgentEvent) => void): () => void { const taps = (globalThis.__tauFrameTaps ??= new Set()); taps.add(tap); return () => { taps.delete(tap); }; } // ---------------------------------------------------------------------------- // Cross-session host tool calls // // A registered host tool called while no tab watches its session goes to every // open tau tab (over the `host-tools` event-stream channel) instead of being rejected. // ---------------------------------------------------------------------------- function getHostToolListeners(): Set<(call: CrossSessionHostToolEvent) => void> { if (!globalThis.__tauHostToolListeners) globalThis.__tauHostToolListeners = new Set(); return globalThis.__tauHostToolListeners; } /** Subscribe to host tool calls for sessions no tab is currently watching. */ export function subscribeHostToolCalls(listener: (call: CrossSessionHostToolEvent) => void): () => void { const listeners = getHostToolListeners(); listeners.add(listener); return () => { listeners.delete(listener); if (listeners.size === 0) { for (const session of getRegistry().values()) session.rejectCrossSessionHostTools(); } }; } // Starts at the empty state so an idle server never broadcasts "nothing changed". let lastRunningSnapshot = "[[],[]]"; /** * Recompute the running-session-id set and, when it changes, broadcast it. * A session file may first appear after its id starts running, so callers can * force one otherwise-identical update to refresh sidebar session metadata. */ export function notifyRunningChange({ refreshSessionList = false }: { refreshSessionList?: boolean } = {}): void { const runningSessions = getRunningRpcSessions(); const exitedSessions = getExitedRpcSessions(); const ids = runningSessions.map((s) => s.id); const byId = (a: { id: string }, b: { id: string }) => a.id.localeCompare(b.id); const snapshot = JSON.stringify([runningSessions.slice().sort(byId), exitedSessions.slice().sort(byId)]); if (snapshot === lastRunningSnapshot && !refreshSessionList) return; lastRunningSnapshot = snapshot; syncInterruptibleSessions(); const update: RunningSessionUpdate = { ids, runningSessions, exitedSessions, refreshSessionList }; for (const listener of getRunningListeners()) { try { listener(update); } catch { /* ignore listener errors */ } } } /** Record which sessions are mid-run, for resume after a restart. */ export function syncInterruptibleSessions(): void { const registry = getRegistry(); const running = new Map(); for (const session of registry.values()) { if (!session.hostOwnedLifecycle && session.sessionId && session.isRunning()) running.set(session.sessionId, { id: session.sessionId, hostId: session.host.id }); } recordRunningSessions([...running.values()], (id) => registry.get(id)?.isAlive() === true); } /** * Restart the sessions that were mid-run when tau last stopped and ask * each to continue. Only runs when the auto-resume setting is on. Each session, * this machine's included, waits for its host's hello: a child its daemon still * runs is adopted there, and only a dead one resumes, after its orphan's exit. */ export async function resumeInterruptedSessions(): Promise { resumeOnHostLink(takeInterruptedSessions(), resumeSession); } /** Start an interrupted session again on its host and ask it to continue. Never rejects. */ async function resumeSession({ id, hostId }: InterruptibleSession): Promise { try { const host = getHost(hostId); if (hostOwnsLifecycle(hostId)) return; const target = host && await sessionSpawnTarget(id, host); if (!host || !target) return; const { session } = await startRpcSession(id, target.sessionFile, target.cwd, undefined, target.recordedCwd, host); await session.send({ type: "prompt", message: RESUME_PROMPT }); console.log(`[tau] resumed interrupted session ${id}`); } catch (error) { console.warn(`[tau] could not resume session ${id}: ${error instanceof Error ? error.message : String(error)}`); } } /** * Get or create the pi RPC process for the given session. * For new sessions (sessionFile === ""), pi generates its own id. * Pass toolNames to pre-configure the builtin toolset of a NEW session * (empty array = all tools disabled); ignored when resuming. */ declare global { var __tauAgentToolGuard: AgentToolGuard | undefined; } /** Process-wide loop/spam guard for server agent tools (#275). Stored on * globalThis like the session registry so a hot reload does not silently * reset the chain depths mid-loop. */ function getAgentToolGuard(): AgentToolGuard { if (!globalThis.__tauAgentToolGuard) globalThis.__tauAgentToolGuard = new AgentToolGuard(); return globalThis.__tauAgentToolGuard; } /** pi's command for each agent-tool delivery; the `Record` makes a new delivery fail to compile until it is mapped. */ const DELIVERY_COMMAND: Record = { prompt: "prompt", steer: "steer", followUp: "follow_up" }; /** * Real session operations behind lib/agent-tools executeAgentTool. * Reuses the existing spawn/resume and message-send paths (startRpcSession, * wrapper.send) instead of a second session engine. Delivery rules, kept * explicit because pi's commands do not all make sense in every state: * - prompt: only when the target is idle (starts a new turn); * - steer: only when the target is running (steers that turn); * - followUp: any state (queues behind a running turn, or starts one * when idle — pi owns the queue, as with the UI's follow-ups). * A waited delivery registers its turn-end waiter BEFORE sending, then * reads the turn's final text with get_last_assistant_text. */ function createAgentToolOps(source: AgentToolContext, replaying: boolean): AgentToolSessionOps { const hosts = (): AgentToolHost[] => { const local = getHost(LOCAL_HOST_ID); return [ { id: local.id, label: local.label, online: isLinkUp(local.status()), allowAgentStart: true }, ...listHosts().map((h) => ({ id: h.id, label: h.label, online: isLinkUp(h.status), allowAgentStart: h.allowAgentStart })), ]; }; return { github: createGithubToolOps(hosts), async listSessions() { const running = new Set(getRunningRpcSessionIds()); const sessions = await listSessionsAllHosts(); return sessions.map((s) => ({ id: s.id, name: s.name, cwd: s.cwd, running: running.has(s.id), hostId: s.hostId ?? LOCAL_HOST_ID })); }, listHosts: hosts, async createSession(input, authorize) { const authorizeHost = (host: Host) => { const configured = this.listHosts().find((candidate) => candidate.id === host.id); if (!configured) throw new Error(`Unknown host: ${host.id}`); return authorize(configured); }; const initialize = async (session: AgentSessionWrapper, preserveUnknownDelivery: boolean, promptId = input.clientMessageId) => { if (input.provider && input.modelId) { await session.send({ type: "set_model", provider: input.provider, modelId: input.modelId }, { preserveUnknownDelivery }); } if (input.name) await session.send({ type: "set_session_name", name: input.name }, { preserveUnknownDelivery }); if (input.prompt) await session.send({ type: "prompt", message: input.prompt, ...(promptId ? { clientMessageId: promptId } : {}), }, { preserveUnknownDelivery, origin: input.origin }); }; if (!input.shareWorkspace && !input.explicitHost && input.hostId === source.sourceHostId) { const sessions = await listSessionsAllHosts(); const origin = sessions.find((session) => session.id === source.sourceSessionId && (session.hostId ?? LOCAL_HOST_ID) === source.sourceHostId); const bindings = poolProjectBindings(loadPools()).get(source.sourceHostId); const binding = bindings?.get(comparableProjectPath(input.cwd === source.sourceCwd ? origin?.projectRoot ?? origin?.cwd ?? source.sourceCwd : input.cwd)); if (binding) { const creationId = createHash("sha256").update("tau:agent-creation:v1:") .update(JSON.stringify([source.sourceSessionId, source.sourceRequestId])).digest("hex"); const result = await startPooledSession({ creationId, poolId: binding.pool.id, projectId: binding.project.id, intent: { ...input, clientMessageId: undefined, origin: undefined }, }, async (host, prepared, id, onStarted) => { const started = await startNewRpcSession(host, prepared.cwd, undefined, true, id); if (!started.ok) throw new HostOpError(started.status, started.code, started.error); const { session, realSessionId } = started.value; await onStarted(realSessionId); const promptId = input.prompt ? createHash("sha256").update(`tau:agent-prompt:v1:${creationId}`).digest("hex") : undefined; await session.withPendingCommand(() => initialize(session, true, promptId), true); return { sessionId: realSessionId, sessionName: input.name ?? null }; }, authorizeHost); const placedHost = getHost(result.hostId); return { sessionId: result.sessionId, sessionName: input.name ?? null, session: { id: result.sessionId, name: input.name ?? null, hostId: result.hostId, hostLabel: placedHost?.label ?? result.hostId, cwd: result.cwd, }, }; } } // Standalone/shared creations have no durable admission identity and cannot safely be replayed. if (replaying) throw new Error(AGENT_TOOL_UNKNOWN_OUTCOME); const host = getHost(input.hostId); if (!host) throw new Error(`Unknown host: ${input.hostId}`); if (!(await authorizeHost(host))) throw new Error(`The user declined to start a session on ${host.label}.`); await requireProviderLogin(host, input.provider); const preparing = !!(input.prompt || input.name || (input.provider && input.modelId)); const started = await startNewRpcSession(host, input.cwd, undefined, preparing); if (!started.ok) throw new Error(started.error); const { session, realSessionId } = started.value; try { const run = () => initialize(session, false); if (preparing) await session.withPendingCommand(run, true); else await run(); } catch (error) { // As /api/agent/new: behind a dropped link the prompt may be running there, so the wrapper stays. if (!(error instanceof WebRpcError && error.code === "host_offline")) await session.destroyAndWait(); throw error; } return { sessionId: realSessionId, sessionName: input.name ?? null, session: { id: realSessionId, name: input.name ?? null, hostId: host.id, hostLabel: host.label, cwd: input.cwd }, }; }, async deliver(input): Promise { const live = getRpcSession(input.sessionId); let wrapper = live?.isAlive() ? live : undefined; let cold = false; if (!wrapper) { const host = await hostForSessionId(input.sessionId); const target = host && await sessionSpawnTarget(input.sessionId, host); if (!host || !target) throw new Error(`Session not found: ${input.sessionId}`); // The open's preparation lease keeps an idle shared child until the message is sent. const started = await startRpcSession(input.sessionId, target.sessionFile, target.cwd, undefined, target.recordedCwd, host, true); wrapper = started.session; cold = true; } const target = wrapper; const delivery = input.delivery; const send = async () => { const wasRunning = target.isRunning(); if (input.delivery === "prompt" && wasRunning) { throw new Error("Target session is running; use delivery \"steer\" or \"followUp\" for a running target."); } if (input.delivery === "steer" && !wasRunning) { throw new Error("Target session is not running; use delivery \"prompt\" to start a turn."); } const terminalEndsNeeded = delivery === "followUp" && wasRunning ? 2 : 1; const waiter = input.wait ? target.waitForTurnEnd(input.waitTimeoutMs, terminalEndsNeeded) : null; await target.send({ type: DELIVERY_COMMAND[delivery], message: input.message, clientMessageId: input.clientMessageId, }, { origin: input.origin }); return { waiter }; // Boxed: the lease ends at delivery, not at the turn's end. }; const { waiter } = cold ? await wrapper.withPendingCommand(send, true) : await send(); if (!input.wait || !waiter) { return { accepted: true, targetSessionId: input.sessionId, delivery, waited: false, responseText: null }; } await waiter; const last = (await wrapper.send({ type: "get_last_assistant_text" })) as { text?: unknown } | null; return { accepted: true, targetSessionId: input.sessionId, delivery, waited: true, responseText: typeof last?.text === "string" ? last.text : null, }; }, async sessionHostId(sessionId) { const live = getRpcSession(sessionId); if (live?.isAlive()) return live.host.id; return (await hostForSessionId(sessionId))?.id ?? null; }, }; } /** A creation uses the existing startup locks/registry, including a child whose handshake was interrupted. */ export function getRpcCreationSession(creationId: string): Promise<{ session: AgentSessionWrapper; realSessionId: string }> | null { const key = `__new__${creationId}`; const locks = getLocks(); const pending = locks.get(key); if (pending) return pending; const session = getRegistry().get(key); if (!session?.isAlive()) return null; if (session.sessionId && getRegistry().get(session.sessionId) === session) return Promise.resolve({ session, realSessionId: session.sessionId }); const recovering = session.adopt().then(() => { registerSession(session); getRegistry().set(key, session); return { session, realSessionId: session.sessionId }; }).finally(() => { if (locks.get(key) === recovering) locks.delete(key); }); locks.set(key, recovering); return recovering; } /** * Spawn a brand-new session on `host` in `cwd`, checked where it lives: the * host answers with the path it will use. Registers this machine's cwd with * its file routes, and refreshes the host's session list. */ export async function startNewRpcSession( host: Host, cwd: string, toolNames?: string[], preparingCommand = false, creationId?: string, ): Promise> { if (creationId !== undefined && !CREATION_ID_RE.test(creationId)) { return { ok: false, status: 400, code: "invalid_creation_id", error: "Invalid creation identity" }; } if (creationId !== undefined) { const existing = getRpcCreationSession(creationId); if (existing) { const value = await existing; if (value.session.host.id !== host.id || value.session.cwd !== cwd) { return { ok: false, status: 409, code: "creation_conflict", error: "Creation identity belongs to a different host or worktree" }; } return { ok: true, value }; } } const validated = await host.sessionOps.validateCwd(cwd); if (!validated.ok) return validated; const spawnCwd = validated.value.cwd; if (creationId !== undefined && spawnCwd !== cwd) { return { ok: false, status: 409, code: "prepared_cwd_changed", error: "The prepared worktree is no longer available" }; } const tempKey = `__new__${creationId ?? randomUUID()}`; const started = await startRpcSession(tempKey, "", spawnCwd, toolNames, undefined, host, preparingCommand, creationId); // Without this a file request under a brand-new cwd would 403 for up to the allowed-roots cache TTL. // Never for another host: its paths do not exist on this machine. if (host.id === LOCAL_HOST_ID) allowFileRoot(spawnCwd); invalidateHostSessionList(host.id); return { ok: true, value: started }; } export async function startRpcSession( sessionId: string, sessionFile: string, cwd: string, toolNames?: string[], /** The cwd recorded in the session file header, used to detect a spawn * fallback (recorded dir gone) and warn the user. Omit for new sessions. */ recordedCwd?: string | null, host: Host = getHost(LOCAL_HOST_ID), preparingCommand = false, /** Stable independent creation; never set for ordinary standalone starts or resumes. */ creationId?: string, ): Promise<{ session: AgentSessionWrapper; realSessionId: string }> { const registry = getRegistry(); const locks = getLocks(); const launch: SpawnRequest = { cwd, recordedCwd: recordedCwd ?? null, sessionFile, toolNames, ...(creationId === undefined ? {} : { creationId }) }; // A child of this session the host still ran from before a restart of this // server is being adopted or killed. Waiting here, before the registry and // the lock, lets a start join an adopted child; a killed one must exit first: // two children must never write one session file. A live wrapper is past that. if (sessionFile && !registry.get(sessionId)?.isAlive()) await orphanExit(host.id, sessionId); const existing = registry.get(sessionId); if (existing?.isAlive()) return { session: existing, realSessionId: existing.sessionId }; // A wrapper whose pi child is still flushing/exiting must fully dispose // before a replacement spawns — two children touching the same .jsonl would // race on resume/delete/archive. if (existing?.destroyPromise) await untilHostDown(existing.host, existing.destroyPromise); // Two pi processes appending to one session file would interleave their // entry trees. Reuse the live wrapper that already reports this file. if (sessionFile && !existing) { for (const candidate of new Set(registry.values())) { if (candidate.isAlive() && candidate.sessionFile && samePath(candidate.sessionFile, sessionFile)) { registry.set(sessionId, candidate); notifyRunningChange({ refreshSessionList: true }); return { session: candidate, realSessionId: candidate.sessionId }; } } } const inflight = locks.get(sessionId); if (inflight) return inflight; const starting = (async () => { // The wrapper needs the process and the process's onExit needs the wrapper; // the holder breaks that cycle (onExit only fires once the child dies). const holder: { wrapper?: AgentSessionWrapper } = {}; const spawned = await host.spawnRpc(launch, sessionFile ? sessionId : null, { preparing: preparingCommand }); const proc = new RpcProcess({ cwd: spawned.cwd, transport: spawned.transport, ...(spawned.transport.hostOwnedLifecycle ? { adopted: true as const } : {}), onExit: (info) => holder.wrapper?.handleProcessExit(info, proc), }); const created = new AgentSessionWrapper( proc, spawned.cwd, recordedCwd, sessionFile ? sessionId : "", DISCONNECT_DESTROY_MS, host, spawned.fellBack, ); holder.wrapper = created; created.start(); try { if (spawned.transport.hostOwnedLifecycle) { await created.adopt([...(spawned.pending ?? []), ...(spawned.streaming ? [spawned.streaming] : [])], spawned.joined !== false); } else { await created.waitUntilReady(); } // A fresh spawn (no --session) must never land in an existing conversation, // which would silently send the first prompt into an old .jsonl (a guard: // pi starts a new session without --session). The child's reported session file // existing on disk is the resume signal — a genuinely fresh child reports // a path it has not created yet (session files are written lazily on the // first message), so this never fires for a real new session. if (!sessionFile && created.sessionFile && await host.sessionFileExists(created.sessionFile)) { await created.send({ type: "new_session" }); } // Register server agent tools (#275) at startup when the gate is on, // so a session works for agent-to-agent calls even when no browser // tab ever registers host tools for it. send() merges these with any // later UI registration, so this never drops the UI tools. A failed // registration is ignored the way the UI registration ignores it. if (!created.hostOwnedLifecycle && loadWebServerSettings().agentToolsEnabled) { await created.send({ type: "set_host_tools", tools: AGENT_TOOL_DEFINITIONS }).catch(() => {}); } } catch (error) { if (creationId !== undefined) { // Its daemon may still own the child: reconciliation reuses this native wrapper, never a replacement spawn. registry.set(`__new__${creationId}`, created); throw error; } // Await the child's full exit before the `finally` releases the startup // lock: a fire-and-forget destroy() would let a retry spawn a second // pi child while the failed one is still flushing/exiting, and // concurrent resume/delete/archive paths could race that old child. const disposing = created.destroyAndWait(); // That wait ends early once the host is offline, with the child still // exiting there. A resume stays registered until it really exits, so a // retry awaits its destroyPromise instead of starting a second // `--resume` child beside it. Chained on destroyPromise (set by the call // above), not onDestroy: a child that already exited ran no callback. if (sessionFile) { registry.set(sessionId, created); void created.destroyPromise?.then(() => { if (registry.get(sessionId) === created) registry.delete(sessionId); }); } await disposing; throw error; } const realSessionId = created.sessionId; registerSession(created); if (creationId !== undefined) registry.set(`__new__${creationId}`, created); // A resumed child can report another id than the one requested; keep the requested id routable. if (sessionFile && realSessionId !== sessionId) { registry.set(sessionId, created); } // A successful respawn supersedes the crash record. clearExitedRpcSession(sessionId); if (realSessionId !== sessionId) clearExitedRpcSession(realSessionId); return { session: created, realSessionId }; })().finally(() => locks.delete(sessionId)); locks.set(sessionId, starting); return starting; } /** Key a ready wrapper under its real id and keep its keys current as it switches sessions. */ function registerSession(created: AgentSessionWrapper): void { const registry = getRegistry(); created.onDestroy(() => { // Drop every key (current id, original id, moved-from aliases). for (const [key, wrapper] of registry) if (wrapper === created) registry.delete(key); notifyRunningChange({ refreshSessionList: true }); }); created.onIdentityChange((_oldId, newId) => { // A branch/new/switch serves another conversation, so every old key goes. for (const [key, wrapper] of registry) if (wrapper === created) registry.delete(key); registry.set(newId, created); notifyRunningChange({ refreshSessionList: true }); }); registry.set(created.sessionId, created); notifyRunningChange({ refreshSessionList: true }); } /** * Take over a pi child that outlived the server that spawned it (its host * listed it in `hello`): no spawn and no ready wait. `replay` holds the host's * raw stdout lines of the child's still-open blocking requests. Legacy failed * adoptions kill their child; a durable creation is retained for owner-only * reconciliation, including a sessionless child with an interrupted handshake. */ export async function adoptRpcSession({ host, transport, sessionId, cwd, replay, creationId }: { host: Host; transport: RpcTransport; sessionId: string; cwd: string; replay: string[]; creationId?: string; }): Promise { const registry = getRegistry(); const locks = getLocks(); const creationKey = creationId === undefined ? undefined : `__new__${creationId}`; const keys = creationKey === undefined ? [sessionId] : sessionId ? [creationKey, sessionId] : [creationKey]; if (keys.some((key) => locks.has(key) || registry.has(key))) { if (transport.hostOwnedLifecycle) transport.close?.(); else if (creationId === undefined) transport.killTree(false); throw new Error(`Session ${sessionId || creationId} is already started on this server`); } const holder: { wrapper?: AgentSessionWrapper } = {}; const proc = new RpcProcess({ cwd, transport, adopted: true, onExit: (info) => holder.wrapper?.handleProcessExit(info, proc) }); const created = new AgentSessionWrapper(proc, cwd, cwd, sessionId, DISCONNECT_DESTROY_MS, host); holder.wrapper = created; created.start(); const adopting = (async () => { try { await created.adopt(replay); // The host names a child by the session it last reported; one that has since moved // to a session this server already runs would be its second writer. if (created.sessionId !== sessionId && (locks.has(created.sessionId) || registry.has(created.sessionId))) { throw new Error(`Session ${created.sessionId} is already started on this server`); } } catch (error) { if (creationKey !== undefined) { // An uncertain creation is never an orphan to destroy; a later owner retry can re-sync this same child. registry.set(creationKey, created); throw error; } const disposing = created.destroyAndWait("adoption-failed"); // As for a failed resume: until the child really exits, a start for this // session waits for it (destroyAndWait returns early behind a dropped link). registry.set(sessionId, created); void created.destroyPromise?.then(() => { if (registry.get(sessionId) === created) registry.delete(sessionId); }); await disposing; throw error; } registerSession(created); if (creationKey !== undefined) registry.set(creationKey, created); // The run goes on: any crash record for the session is stale. clearExitedRpcSession(sessionId); if (created.sessionId !== sessionId) clearExitedRpcSession(created.sessionId); notifyRunningChange(); return { session: created, realSessionId: created.sessionId }; })().finally(() => { for (const key of keys) if (locks.get(key) === adopting) locks.delete(key); }); // A start for this session meanwhile joins the adoption instead of spawning a second child beside it. for (const key of keys) locks.set(key, adopting); return (await adopting).session; }