Skip to content

A self-improving RLM agent for coding workflows and long-running autonomous tasks.

Rust

isolate daemon sessions in worker processes (#383)

kt4d19005d4a25
diff --git a/packages/coding-agent/CHANGELOG.md b/packages/coding-agent/CHANGELOG.md
index 10a2275a84..1e169d6c93 100644
--- a/packages/coding-agent/CHANGELOG.md
+++ b/packages/coding-agent/CHANGELOG.md
@@ -4,6 +4,7 @@
- Added autonomous mode with host-side continuations, configurable limits, and quality gates for evaluator-controlled runs ([#278](https://github.com/PrimeIntellect-ai/prime-agent/pull/278) by [@sethkarten](https://github.com/sethkarten)).
- Fixed Prime Inference credential and team-header precedence to prefer `PRIME_API_KEY`, then the Prime CLI config, then `auth.json`.
+- Fixed aborted autonomous gates leaving detached process trees and supervisor recovery retaining intentionally stopped workers after stale scheduler locks.
## [0.2.9] - 2026-07-13
@@ -15,18 +16,23 @@
- Added `/btw` and `/side` for one-turn inline side questions that use the current context without changing the main session ([ENG-4509](https://linear.app/primeintellect/issue/ENG-4509/add-btw-and-side-side-question-flows)).
- Changed scheduled heartbeat prompts to steer (interrupt the current turn) by default, with a `steer`/`follow_up` delivery mode selectable via `/heartbeat --steer|--follow-up` and the `rlm_heartbeat` skill's `delivery_mode` argument.
- Changed the new-chat splash to show only version, model, and cwd metadata and rotate among five example prompts.
+- Changed daemon and headless execution to isolate each root session tree in a recoverable worker process, with protocol-v2 chunked snapshots, compact streaming, attachment-local backpressure, session leases, and unchanged print, JSON, and RPC interfaces.
- Fixed self-updates losing restored daemon sessions to a socket cleanup race and leaving open session or agents-view windows disconnected.
+- Fixed supervisor replacement surfacing fatal socket errors or recovering roots that were intentionally stopped ([ENG-4526](https://linear.app/primeintellect/issue/ENG-4526/reconnect-daemon-clients-transparently-after-supervisor-replacement)).
- Changed daemon connection errors to report the failed operation, session identity, recovery steps, socket, and diagnostic log instead of raw protocol reasons.
- Changed the Agents View and new-chat splashes to keep one blank row above the butterfly.
- Fixed Agents View retrying after an intentional daemon shutdown instead of stopping with restart guidance.
-- Fixed stale heartbeat jobs reopening archived, deleted, or concurrently terminated sessions ([ENG-4519](https://linear.app/primeintellect/issue/ENG-4519/heartbeats-rebirth-sessions-that-were-previously-killed)).
+- Fixed daemon catch-up snapshots being disposed mid-transfer or triggering resets that cleared drafts, local queues, dialogs, active UI state, or in-flight reasoning traces.
+- Fixed compact daemon streams occasionally duplicating the first token of an assistant response.
+- Fixed subagent prompts and usage counters flickering or disappearing during daemon resyncs and large parallel runs, and added compact fixed-width recap rows.
+- Fixed stale heartbeat jobs reopening sessions after they were archived, deleted, explicitly shut down, concurrently terminated, or lost resident worker ownership ([ENG-4519](https://linear.app/primeintellect/issue/ENG-4519/heartbeats-rebirth-sessions-that-were-previously-killed)).
+- Fixed heartbeat starvation by moving durable schedules into per-session artifacts and running them concurrently in their owning resident workers, independent of supervisor replacement ([ENG-4527](https://linear.app/primeintellect/issue/ENG-4527/dispatch-heartbeats-concurrently-across-isolated-session-workers)).
- Fixed onboarding blocking normal TUI use by reopening login or model selection after startup ([ENG-4537](https://linear.app/primeintellect/issue/ENG-4537/stop-onboarding-from-gating-normal-tui-use)).
- Fixed IPython Bash cells with leading blank lines being labeled and previewed as Python ([ENG-4529](https://linear.app/primeintellect/issue/ENG-4529/leading-newline-before-percentpercentbash-names-tool-call-as-python)).
- Fixed recap layout shifts by keeping the previous recap visible until its replacement arrives ([ENG-4533](https://linear.app/primeintellect/issue/ENG-4533/reserve-space-for-recap-to-prevent-layout-shift)).
- Changed the new-chat tray to hide shortcut guidance while typing and keep the `agents` link visible.
## [0.2.8] - 2026-07-09
-
- Added built-in Herdr integration that reports agent lifecycle state to Herdr panes automatically, without requiring `herdr integration install pi`.
- Changed Escape to interrupt active work with a visible abort notice, double Escape to open the session tree from an empty prompt or clear an idle draft, and `?` to show shortcuts ([ENG-4489](https://linear.app/primeintellect/issue/ENG-4489/rewire-prime-agent-shortcuts-to-match-claude-code-flow)).
- Changed new-chat guidance to show concise shell, command, file, and shortcut hints, with Agents View first and `? for shortcuts` after the model and effort ([ENG-4489](https://linear.app/primeintellect/issue/ENG-4489/rewire-prime-agent-shortcuts-to-match-claude-code-flow)).
diff --git a/packages/coding-agent/docs/daemon-implementation-summary.md b/packages/coding-agent/docs/daemon-implementation-summary.md
index c087ab852d..7c12f8f071 100644
--- a/packages/coding-agent/docs/daemon-implementation-summary.md
+++ b/packages/coding-agent/docs/daemon-implementation-summary.md
@@ -1,167 +1,159 @@
-# Daemon Implementation Summary
+# Daemon and Session Worker Architecture
-This branch adds a tmux-like daemon mode for Prime Agent. The daemon is a background process that listens on a Unix socket and owns active agent sessions. CLI clients connect to that socket to create, attach, detach, prompt, rename, kill, and list sessions.
+Prime Agent isolates each persistent root session tree in its own process. Process isolation is internal: interactive, print, JSON, RPC, piped-stdin, and `--no-session` invocations keep their existing commands and public I/O contracts.
-## User Flow
+## Process Topology
-The main entrypoint is:
-
-```sh
-prime-agent daemon
+```text
+interactive clients
+ |
+ v
+detached supervisor
+ |- catalog subprocess
+ |- resident worker: root A + RLM descendants + kernels
+ `- resident worker: root B + RLM descendants + kernels
+
+print / JSON / RPC / interactive --no-session
+ |
+ v
+frontend process --private owner channel--> owned worker + root tree
```
-That command:
+The supervisor owns public sockets, client attachments, routing, global agent-message routing, worker health, and update coordination. Each resident worker owns scheduling and execution for its root tree. The supervisor does not execute providers, tools, compaction, bash, kernels, session schedules, or session-history scans.
-1. Starts the background daemon if it is not already running.
-2. Creates a new active session.
-3. Attaches the terminal to that new session.
+Each worker owns one root `AgentSessionRuntime` and every RLM descendant below it. New, switch, fork, and import operations replace the root runtime inside that worker while preserving the root active-session ID.
-Explicit daemon commands are also available:
+The catalog subprocess owns saved-session scans and inactive-session file operations. A catalog failure can make a catalog request fail, but cannot interrupt active workers.
-```sh
-prime-agent daemon start
-prime-agent daemon list
-prime-agent daemon list -a
-prime-agent daemon create scratch
-prime-agent daemon attach <session>
-prime-agent daemon prompt <session> "Say hello"
-prime-agent daemon rename <session> scratch
-prime-agent daemon kill <session>
-prime-agent daemon shutdown
-```
+## Resident Workers
-`prime-agent daemon start` launches a detached background daemon and returns. `prime-agent daemon start --foreground` keeps the daemon attached to the current terminal for debugging.
+Normal interactive sessions use resident workers:
-## Session Identity
+- The supervisor dynamically starts one detached process group per root tree.
+- Closing the TUI detaches the client; it does not stop the worker.
+- Worker descriptors, authentication tokens, active-session IDs, session paths, and recovery journals are stored with mode `0600` below the agent directory.
+- Workers monitor the public supervisor socket. If it disappears, one worker acquires an atomic launch lease and starts a replacement supervisor.
+- A replacement supervisor adopts the existing worker PIDs and active-session IDs.
+- A worker crash affects only its root tree. Recovery retries after 250 ms, 1 second, and 5 seconds; three failed attempts mark that root failed.
+- `prime-agent daemon retry <session>` retries a failed root.
+- `prime-agent daemon restart` replaces only the supervisor and adopts workers.
+- `prime-agent daemon shutdown` stops workers before the supervisor; `--force` sends `SIGKILL` to workers that do not stop gracefully.
-There are two session identifiers:
+There are no session, worker, client, or workload caps in this layer.
-- `activeSessionId`: daemon-local live handle for a currently active session.
-- `sessionId`: persisted JSONL session id.
+## Owned Workers
-The `activeSessionId` exists because one persisted session can be attached to a running daemon process and needs a socket-level live handle. The `sessionId` is the durable id stored in the JSONL header.
+Headless and ephemeral modes use the same process isolation without joining the resident daemon registry:
-The list table displays 12-character suffix ids. Commands accept suffix matches and report an error if the suffix is ambiguous.
+- `prime-agent -p`, piped stdin, and JSON mode proxy stdin/stdout/stderr through an owned worker and return its existing exit status.
+- RPC keeps stdin/stdout in the frontend. It forwards strict LF-delimited JSONL to the worker and preserves every public command, response, event, and extension-UI shape.
+- If a persisted RPC worker crashes, the frontend reports an ordinary failure for commands whose result is uncertain, reopens the exact persisted session, and continues accepting commands. It never replays an uncertain command.
+- RPC EOF and frontend `SIGTERM`/`SIGHUP` stop only the owned worker and its subprocesses.
+- Interactive `--no-session` uses an owned in-memory worker and creates no recovery descriptor.
+- Owned workers never appear in the agents view and never require the global daemon.
+- Direct SDK calls to `runPrintMode(runtime, ...)` and `runRpcMode(runtime)` remain in-process and source-compatible. Non-serializable extension factories therefore continue to work for embedders.
-## Per-Session Config
+An inherited, unreferenced IPC owner channel links the worker to its frontend. Frontend loss disconnects the channel and terminates the worker, which reaps its kernels and detached children; the unreferenced channel does not prevent clean RPC EOF or print completion.
-The daemon has default session config from the command that started it. Each created session can override that config.
+## Session Ownership
-Examples of per-session config:
+Persisted sessions use process-safe leases keyed by canonical JSONL path. Resident and owned workers both acquire leases.
-- `cwd`
-- model/provider
-- tools
-- thinking level
-- extensions, skills, prompts, themes
-- context/settings flags
+- Resident workers acquire a target lease before opening an existing session. Owned CLI workers acquire it before runtime writes, and all workers acquire the replacement lease before switching runtimes.
+- The previous lease is released only after replacement succeeds.
+- Concurrent opens return `session_already_active` with the owning active-session ID.
+- Concurrent daemon creates for the same path share one worker launch.
-This means one daemon can own sessions with different models, working directories, and tool sets.
+This prevents a script and resident daemon worker from writing the same session concurrently.
-## Persistence Layout
+## Scheduled Jobs
-Session JSONL files are stored flat:
+Each resident worker runs one scheduler for the root and RLM descendant sessions it owns. Schedule state is persisted per session at `session-artifacts/<session-id>/scheduled-jobs.json`; workers never scan or write a shared global cron file.
-```text
-~/.prime/agent/sessions/<sessionId>.jsonl
-```
+- Creating or changing a heartbeat writes its session store and wakes the same worker's scheduler.
+- Due ticks are claimed and advanced durably before prompt delivery, so a crash never replays an uncertain prompt.
+- The timer loop dispatches different target sessions independently and does not wait for complete model or tool turns before scheduling its next pass.
+- A still-active claim coalesces later missed ticks instead of accumulating a backlog.
+- Supervisor replacement does not pause timers or scheduled work because resident workers remain alive.
+- Worker recovery marks uncertain claims interrupted, preserves the advanced schedule, and resumes only future ticks.
+- The supervisor routes cron commands to workers and merges their job summaries for global listing.
-The session root can be overridden with:
+The first worker-owned release migrates the legacy global `cron-jobs.json` into the corresponding session artifact directories before adopting workers. Archived, deleted, or descriptorless sessions are cancelled rather than revived.
-```sh
-PRIME_AGENT_SESSION_DIR=/path/to/sessions
-```
+## Public Protocol v2
-Session artifacts are stored separately:
+The public daemon socket remains JSONL-framed. Version 2 adds:
-```text
-~/.prime/agent/session-artifacts/<sessionId>/...
-```
+- stable command envelopes carrying protocol version, client ID, and command ID;
+- generation-aware event cursors `{ generation, sequence }`;
+- worker states `starting`, `ready`, `recovering`, and `failed` in session summaries;
+- reconnectable clients that retain their stable identity and cursor;
+- attach acknowledgement followed by `session_snapshot_begin`, `session_snapshot_chunk`, and `session_snapshot_end`;
+- 512 KiB target transcript chunks;
+- file-backed transcript caches above 4 MiB.
-The current concrete use of `session-artifacts` is RLM/subagent child session storage. A parent session can have child session directories under its artifact directory.
+The one-release v1 update handoff uses raw v1 requests only to prepare and stop the old daemon. Busy older daemons that cannot produce a recovery manifest are left running.
-## Session Metadata
+JSON mode and RPC never expose daemon greetings, envelopes, lifecycle messages, snapshot records, or connection metadata.
-Metadata that is not inferable from messages is stored as typed append-only JSONL entries in the session file.
+## Private Worker Transport
-Examples:
+Supervisor-worker traffic uses a binary frame:
-```json
-{"type":"session_info","name":"scratch"}
-{"type":"session_state","state":{"status":"sleep"}}
-{"type":"model_change","provider":"openai","modelId":"gpt-4o-mini"}
-{"type":"thinking_level_change","thinkingLevel":"off"}
+```text
+4-byte JSON header length
+4-byte payload length
+small JSON routing header
+opaque payload bytes
```
-Current rules:
-
-- Immutable session facts live in the JSONL header: `id`, `timestamp`, `cwd`, `parentSession`.
-- Mutable metadata is appended as typed entries.
-- The latest matching metadata entry wins during reconstruction.
-- Metadata/control entries are ignored by LLM context unless they are explicitly context-bearing, such as `custom_message`.
-
-Daemon inactive state is persisted with `session_state`. It is not guessed from file paths.
+Workers serialize an outbound public event once. The supervisor reads the routing header and writes the same payload buffer to every eligible client.
-## List Behavior
+Assistant streaming uses compact start/delta/end payloads on the private channel. The supervisor reconstructs the existing full public `message_update` once per delta. A growing assistant message is therefore not serialized or transferred in full for every token.
-`prime-agent daemon list` shows active and idle sessions.
+Transcript snapshots are encoded in the worker, not the supervisor. The worker streams opaque chunks to a bounded supervisor cache. The supervisor forwards chunks while they arrive and never parses a history-sized JSON object.
-`prime-agent daemon list -a` includes inactive saved sessions as well.
+## Backpressure
-Table columns:
+Backpressure is attachment-local:
-```text
-name id status age model messages clients
-```
+- A blocked client stops receiving incremental events.
+- Other clients and workers continue normally.
+- The supervisor retains no unbounded per-client event queue.
+- On drain, that attachment receives a cursor catch-up or a new chunked snapshot.
+- Finalized transcript caching is separate from live partial-message reconstruction.
-The `cwd` column is intentionally omitted. `age` is based on the JSONL modified time.
+## Recovery and Idempotency
-Statuses are sorted in this order:
+Mutating commands are keyed by `clientId + commandId` and recorded before dispatch in an append-only journal.
-1. `user`
-2. `idle`
-3. `tool`
-4. `model`
-5. `sleep`
-6. `crash`
+- A repeated completed command returns its stored result.
+- A received command with no durable result is reported as uncertain and is not replayed.
+- Read and mutation envelopes survive transient supervisor reconnects with the same command ID.
+- Clients durably acknowledge completed mutations, allowing acknowledged journal entries to be compacted away.
-Only the status text is colored.
+Workers journal operation transitions and detached subprocess identities. After a crash, the supervisor reaps the old process group plus tracked detached bash trees, appends a visible recovery marker to the persisted transcript, restores the root under the same active-session ID, and holds uncertain side effects rather than replaying them.
-Status meaning:
+## Coordinated Updates
-- `user`: active session has an attached client and is waiting for user input.
-- `idle`: active session has no attached client and is not currently streaming.
-- `tool`: active session is streaming and currently has pending tool calls.
-- `model`: active session is streaming model output.
-- `sleep`: inactive persisted session that was cleanly killed or shut down.
-- `crash`: inactive persisted session marked as crashed.
+Update preparation is two-phase:
-## Protocol Shape
+1. Every resident worker creates a non-destructive checkpoint in parallel.
+2. The supervisor validates and atomically persists the aggregate manifest.
+3. Only after all prepares and validation succeed does it commit and stop workers.
-CLI clients send JSON commands over the daemon socket. Commands include an optional request `id`, which is only used to correlate command responses.
+If any prepare or manifest validation fails, prepared workers are released and all roots keep running.
-Example command shape:
+## Performance Benchmark
-```json
-{"id":"request-1","type":"create","name":"scratch"}
-```
+Run from `packages/coding-agent`:
-Example response shape:
-
-```json
-{"id":"request-1","type":"response","command":"create","success":true,"data":{"session":{}}}
+```sh
+npx tsx test/daemon-multiclient-bench.ts
+npx tsx test/daemon-multiclient-bench.ts --generated-session-mib 100
+npx tsx test/daemon-multiclient-bench.ts --generated-session-mib 500
+npx tsx test/daemon-multiclient-bench.ts --session-file /path/to/session.jsonl
+PRIME_AGENT_STRESS_WORKERS=50 npx tsx ../../node_modules/vitest/dist/cli.js --run test/daemon-supervisor-process.test.ts -t "hosts resident roots"
```
-Attach is event-oriented. The daemon sends an initial `session_attached` event with state and historical messages, then streams subsequent `session_event` messages for new activity.
-
-## Tests
-
-Tests were added or updated around:
-
-- daemon list table output
-- daemon id suffix matching and ambiguity handling
-- persisted session state
-- flat session storage
-- `PRIME_AGENT_SESSION_DIR`
-- session artifact directory behavior
-- RLM/subagent child session placement
+The benchmark reports legacy and v2 fanout/attach paths side by side, including serialization count, elapsed time, throughput, and sampled RSS growth. The process stress case starts the requested number of resident roots, gives every root a simultaneous heartbeat while its own session is busy, and verifies that all schedules advance independently.
diff --git a/packages/coding-agent/src/cli.ts b/packages/coding-agent/src/cli.ts
index 2a8b49d3e7..4262a6ec93 100644
--- a/packages/coding-agent/src/cli.ts
+++ b/packages/coding-agent/src/cli.ts
@@ -7,6 +7,11 @@
*/
import { enableCompileCache } from "node:module";
import { maybeStartInteractiveDaemonEarly } from "./cli/daemon-launch.js";
+import {
+ closeOwnedSessionWorkerOwnerWatch,
+ installOwnedSessionWorkerOwnerWatch,
+ maybeRunOwnedSessionWorkerFrontend,
+} from "./cli/owned-session-worker.js";
import { APP_NAME } from "./config.js";
// Persist V8 compile caches across runs (~10-15% off module-graph load time).
@@ -25,15 +30,24 @@ process.emitWarning = (() => {}) as typeof process.emitWarning;
// process's own imports instead of serially after them.
maybeStartInteractiveDaemonEarly(process.argv.slice(2));
-const [{ EnvHttpProxyAgent, setGlobalDispatcher }, { main }] = await Promise.all([
- import("undici"),
- import("./main.js"),
-]);
+installOwnedSessionWorkerOwnerWatch();
-// bodyTimeout/headersTimeout default to 300s in undici; long local-LLM stalls
-// (e.g. vLLM buffering a large tool call) exceed that and abort the SSE stream
-// with UND_ERR_BODY_TIMEOUT. Disable both — provider SDKs enforce their own
-// AbortController-based deadlines via retry.provider.timeoutMs.
-setGlobalDispatcher(new EnvHttpProxyAgent({ bodyTimeout: 0, headersTimeout: 0 }));
+const handledByOwnedWorker = await maybeRunOwnedSessionWorkerFrontend(process.argv.slice(2));
+if (!handledByOwnedWorker) {
+ const [{ EnvHttpProxyAgent, setGlobalDispatcher }, { main }] = await Promise.all([
+ import("undici"),
+ import("./main.js"),
+ ]);
-await main(process.argv.slice(2));
+ // bodyTimeout/headersTimeout default to 300s in undici; long local-LLM stalls
+ // (e.g. vLLM buffering a large tool call) exceed that and abort the SSE stream
+ // with UND_ERR_BODY_TIMEOUT. Disable both — provider SDKs enforce their own
+ // AbortController-based deadlines via retry.provider.timeoutMs.
+ setGlobalDispatcher(new EnvHttpProxyAgent({ bodyTimeout: 0, headersTimeout: 0 }));
+
+ try {
+ await main(process.argv.slice(2));
+ } finally {
+ closeOwnedSessionWorkerOwnerWatch();
+ }
+}
diff --git a/packages/coding-agent/src/cli/daemon-command.ts b/packages/coding-agent/src/cli/daemon-command.ts
index 05bc70313e..082899e568 100644
--- a/packages/coding-agent/src/cli/daemon-command.ts
+++ b/packages/coding-agent/src/cli/daemon-command.ts
@@ -44,6 +44,8 @@ const DAEMON_CLIENT_COMMANDS = new Set([
"stats",
"commands",
"cron",
+ "retry",
+ "restart",
"shutdown",
]);
@@ -252,8 +254,24 @@ async function runDaemonClientCommand(parsed: ParsedDaemonClientCommand): Promis
case "cron":
await runCron(client, parsed.positionals, parsed.json);
return;
+ case "retry":
+ if (parsed.positionals.length !== 1) {
+ throw new Error("Usage: daemon retry <session>");
+ }
+ await printResponseData(
+ client,
+ { type: "retry_worker", activeSessionId: parsed.positionals[0]! },
+ parsed.json,
+ );
+ return;
+ case "restart":
+ if (parsed.positionals.length !== 0) {
+ throw new Error("Usage: daemon restart");
+ }
+ await printResponseData(client, { type: "restart" }, parsed.json);
+ return;
case "shutdown":
- await printResponseData(client, { type: "shutdown" }, parsed.json);
+ await runShutdown(client, parsed.positionals, parsed.json);
return;
}
} finally {
@@ -261,6 +279,18 @@ async function runDaemonClientCommand(parsed: ParsedDaemonClientCommand): Promis
}
}
+async function runShutdown(client: DaemonClient, args: string[], json: boolean): Promise<void> {
+ let force = false;
+ for (const arg of args) {
+ if (arg === "--force" || arg === "-f") {
+ force = true;
+ continue;
+ }
+ throw new Error(`Unknown shutdown option: ${arg}`);
+ }
+ await printResponseData(client, { type: "shutdown", force }, json);
+}
+
async function runOpen(parsed: ParsedDaemonClientCommand): Promise<void> {
const sessionArgs = parseSessionArgs(parsed.positionals);
if (!(await canConnectToDaemon(parsed.socketPath, 250))) {
@@ -1336,6 +1366,17 @@ class DaemonAttachTerminal {
}
this.rl?.prompt();
return;
+ case "session_resynced":
+ this.isStreaming = message.snapshot.state.isStreaming;
+ this.writeLine(
+ chalk.dim(`Session resynchronized: ${message.snapshot.state.sessionName ?? message.activeSessionId}`),
+ );
+ if (message.snapshot.messages.length > 0) {
+ this.writeLine(chalk.bold("Transcript"));
+ this.printTranscript(message.snapshot.messages);
+ }
+ this.rl?.prompt();
+ return;
case "session_detached":
return;
case "session_closed":
@@ -1648,7 +1689,9 @@ ${chalk.bold("Commands:")}
cron add <session> <schedule> -- <message>
Schedule a prompt for a session
cron cancel <job-id> Cancel a scheduled cron job
- shutdown [--all] Stop the daemon; --all force-stops every daemon on this machine
+ retry <session> Retry a root worker marked failed
+ restart Restart only the supervisor and adopt existing workers
+ shutdown [--force|--all] Stop workers and the daemon; --force kills unresponsive workers
${chalk.bold("Options:")}
--socket <path> Socket path (default: ${defaultDaemonSocketPath()})
diff --git a/packages/coding-agent/src/cli/daemon-launch.ts b/packages/coding-agent/src/cli/daemon-launch.ts
index 31cdbed1c1..6f605fcde2 100644
--- a/packages/coding-agent/src/cli/daemon-launch.ts
+++ b/packages/coding-agent/src/cli/daemon-launch.ts
@@ -78,7 +78,11 @@ async function probeDaemonVersion(socketPath: string): Promise<DaemonVersionProb
}
export async function listActiveDaemonSessionSummaries(client: DaemonClient): Promise<SessionSummary[]> {
- const response = await client.request({ type: "list" });
+ const hello = await client.waitForHello(2000).catch(() => undefined);
+ const response =
+ hello && hello.protocol.version < DAEMON_PROTOCOL_VERSION
+ ? await client.requestLegacy({ type: "list" })
+ : await client.request({ type: "list" });
if (!response.success) {
throw new Error(response.error);
}
@@ -129,8 +133,13 @@ export async function shutdownDaemonAndWait(socketPath: string, timeoutMs = 5000
let shutdownAccepted = false;
try {
await client.connect(1000);
- const response = await client.request({ type: "shutdown" });
- shutdownAccepted = response.success;
+ const hello = await client.waitForHello(2000).catch(() => undefined);
+ const request =
+ hello && hello.protocol.version < DAEMON_PROTOCOL_VERSION
+ ? client.requestLegacy.bind(client)
+ : client.request.bind(client);
+ const response = await request({ type: "shutdown" }).catch(() => undefined);
+ shutdownAccepted = response?.success === true;
} catch {
// A connect failure isn't treated as "gone"; waitForDaemonGone is the source of truth.
} finally {
@@ -265,9 +274,12 @@ export function ensureInteractiveDaemonRunning(socketPath: string, spawnCwd?: st
if (!promise) {
promise = ensureDaemonRunning(socketPath, spawnCwd);
ensurePromises.set(socketPath, promise);
- promise.catch(() => {
- ensurePromises.delete(socketPath);
- });
+ const clear = () => {
+ if (ensurePromises.get(socketPath) === promise) {
+ ensurePromises.delete(socketPath);
+ }
+ };
+ promise.then(clear, clear);
}
return promise;
}
diff --git a/packages/coding-agent/src/cli/owned-session-worker.ts b/packages/coding-agent/src/cli/owned-session-worker.ts
new file mode 100644
index 0000000000..b35a5505d6
--- /dev/null
+++ b/packages/coding-agent/src/cli/owned-session-worker.ts
@@ -0,0 +1,536 @@
+import { type ChildProcess, type StdioOptions, spawn } from "node:child_process";
+import { randomUUID } from "node:crypto";
+import { chmodSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import type { AgentSession } from "../core/agent-session.js";
+import type { AgentSessionRuntime } from "../core/agent-session-runtime.js";
+import {
+ clearOrphanProcessJournal,
+ isOrphanProcessIdentityCurrent,
+ ORPHAN_PROCESS_JOURNAL_ENV,
+ readActiveOrphanProcesses,
+} from "../core/orphan-process-journal.js";
+import { SESSION_LEASE_OWNER_ID_ENV, SESSION_LEASES_ENABLED_ENV } from "../core/session-lease.js";
+import { attachJsonlLineReader, serializeJsonLine } from "../modes/rpc/jsonl.js";
+import { type CliSubprocessLaunchSpec, createCliSubprocessLaunchSpec } from "./subprocess-launch.js";
+
+const OWNED_WORKER_ENV = "PRIME_AGENT_INTERNAL_OWNED_WORKER";
+const OWNED_RECOVERY_DESCRIPTOR_ENV = "PRIME_AGENT_INTERNAL_OWNED_RECOVERY_DESCRIPTOR";
+const OWNED_PROFILE_ENV = "PRIME_AGENT_INTERNAL_OWNED_PROFILE";
+
+let closeOwnerWatch: (() => void) | undefined;
+
+export type OwnedSessionWorkerProfile = "print" | "json" | "rpc" | "interactive-ephemeral";
+
+interface OwnedSessionRecoveryDescriptor {
+ version: 1;
+ profile: OwnedSessionWorkerProfile;
+ sessionId: string;
+ sessionFile?: string;
+ cwd: string;
+ updatedAt: string;
+}
+
+const NON_SESSION_FLAGS = new Set(["--help", "-h", "--version", "-v", "--list-models", "--export"]);
+
+const NON_SESSION_COMMANDS = new Set([
+ "agents",
+ "manage",
+ "daemon",
+ "install",
+ "remove",
+ "uninstall",
+ "update",
+ "list",
+ "config",
+]);
+
+function valueAfter(args: readonly string[], flag: string): string | undefined {
+ const index = args.indexOf(flag);
+ return index === -1 ? undefined : args[index + 1];
+}
+
+function hasNonSessionOperation(args: readonly string[]): boolean {
+ if (args.some((arg) => NON_SESSION_FLAGS.has(arg) || arg.startsWith("--export="))) {
+ return true;
+ }
+ const first = args[0];
+ return first !== undefined && NON_SESSION_COMMANDS.has(first);
+}
+
+function isStartupBenchmark(environment: NodeJS.ProcessEnv): boolean {
+ const value = environment.PI_STARTUP_BENCHMARK?.toLowerCase();
+ return value === "1" || value === "true" || value === "yes";
+}
+
+export function classifyOwnedSessionWorkerInvocation(
+ args: readonly string[],
+ stdinIsTTY: boolean | undefined,
+ environment: NodeJS.ProcessEnv = process.env,
+): OwnedSessionWorkerProfile | undefined {
+ if (environment[OWNED_WORKER_ENV] === "1" || hasNonSessionOperation(args)) {
+ return undefined;
+ }
+
+ const mode = valueAfter(args, "--mode");
+ if (mode === "daemon") {
+ return undefined;
+ }
+ if (mode === "rpc") {
+ return "rpc";
+ }
+ if (mode === "json") {
+ return "json";
+ }
+ if (args.includes("--print") || args.includes("-p") || stdinIsTTY === false) {
+ return "print";
+ }
+ if (args.includes("--no-session") || isStartupBenchmark(environment)) {
+ return "interactive-ephemeral";
+ }
+ return undefined;
+}
+
+export type OwnedWorkerLaunchSpec = CliSubprocessLaunchSpec;
+
+export function createOwnedWorkerLaunchSpec(
+ args: readonly string[],
+ executable = process.execPath,
+ execArgs: readonly string[] = process.execArgv,
+ entrypoint = process.argv[1],
+): OwnedWorkerLaunchSpec {
+ return createCliSubprocessLaunchSpec(args, executable, execArgs, entrypoint);
+}
+
+function readOwnedRecoveryDescriptor(path: string): OwnedSessionRecoveryDescriptor | undefined {
+ try {
+ const value = JSON.parse(readFileSync(path, "utf8")) as Partial<OwnedSessionRecoveryDescriptor>;
+ if (
+ value.version === 1 &&
+ typeof value.sessionId === "string" &&
+ typeof value.cwd === "string" &&
+ (value.sessionFile === undefined || typeof value.sessionFile === "string")
+ ) {
+ return value as OwnedSessionRecoveryDescriptor;
+ }
+ } catch {
+ // The worker may have stopped before creating a recoverable session.
+ }
+ return undefined;
+}
+
+function writeOwnedRecoveryDescriptor(path: string, profile: OwnedSessionWorkerProfile, session: AgentSession): void {
+ const descriptor: OwnedSessionRecoveryDescriptor = {
+ version: 1,
+ profile,
+ sessionId: session.sessionId,
+ ...(session.sessionFile ? { sessionFile: session.sessionFile } : {}),
+ cwd: session.sessionManager.getCwd(),
+ updatedAt: new Date().toISOString(),
+ };
+ const tempPath = `${path}.${process.pid}.tmp`;
+ writeFileSync(tempPath, `${JSON.stringify(descriptor)}\n`, { mode: 0o600 });
+ chmodSync(tempPath, 0o600);
+ renameSync(tempPath, path);
+}
+
+export function installOwnedSessionRecoveryTracking(runtime: AgentSessionRuntime): void {
+ const path = process.env[OWNED_RECOVERY_DESCRIPTOR_ENV];
+ const profile = process.env[OWNED_PROFILE_ENV] as OwnedSessionWorkerProfile | undefined;
+ if (!path || !profile) {
+ return;
+ }
+ let unsubscribeSession: (() => void) | undefined;
+ const bind = (session: AgentSession) => {
+ unsubscribeSession?.();
+ writeOwnedRecoveryDescriptor(path, profile, session);
+ let lastSessionFile = session.sessionFile;
+ unsubscribeSession = session.subscribe((event) => {
+ if (event.type !== "message_start" && event.type !== "session_info_changed") {
+ return;
+ }
+ if (session.sessionFile !== lastSessionFile) {
+ lastSessionFile = session.sessionFile;
+ writeOwnedRecoveryDescriptor(path, profile, session);
+ }
+ });
+ };
+ bind(runtime.session);
+ runtime.onSessionReplaced(bind);
+}
+
+export function createRpcRecoveryArgs(args: readonly string[], sessionPath: string): string[] {
+ const recovered: string[] = [];
+ for (let index = 0; index < args.length; index++) {
+ const arg = args[index]!;
+ if (arg === "--resume" || arg === "-r" || arg === "--fork") {
+ index++;
+ continue;
+ }
+ if (arg.startsWith("--resume=")) {
+ continue;
+ }
+ if (arg === "--continue" || arg === "-c") {
+ continue;
+ }
+ recovered.push(arg);
+ }
+ return [...recovered, "--resume", sessionPath];
+}
+
+function exitCodeForSignal(signal: NodeJS.Signals | null): number {
+ if (signal === "SIGHUP") {
+ return 129;
+ }
+ if (signal === "SIGINT") {
+ return 130;
+ }
+ if (signal === "SIGTERM") {
+ return 143;
+ }
+ return 1;
+}
+
+function forwardSignal(child: ChildProcess, signal: NodeJS.Signals): void {
+ if (child.exitCode === null && child.signalCode === null) {
+ child.kill(signal);
+ }
+}
+
+export async function runOwnedSessionWorkerFrontend(
+ args: readonly string[],
+ profile: OwnedSessionWorkerProfile,
+): Promise<number> {
+ const interactive = profile === "interactive-ephemeral";
+ const recoveryDescriptorPath = join(tmpdir(), `prime-agent-owned-${process.pid}-${randomUUID().slice(0, 12)}.json`);
+ const orphanProcessJournalPath = `${recoveryDescriptorPath}.orphans.jsonl`;
+ let currentChild: ChildProcess | undefined;
+ let terminating = false;
+ let terminationSignal: NodeJS.Signals | undefined;
+ let stdinEnded = false;
+ let currentRpcInput: NodeJS.WritableStream | undefined;
+ let currentRpcOutput: NodeJS.ReadableStream | undefined;
+ let rpcStdoutPaused = false;
+ let detachRpcInput: (() => void) | undefined;
+ let detachRpcOutput: (() => void) | undefined;
+ const bufferedRpcInput: string[] = [];
+ const pendingRpcCommands = new Map<string, { publicId?: string; command: string }>();
+ const anonymousRpcIdPrefix = `prime-agent-owned-${randomUUID()}`;
+ let anonymousRpcCommandId = 0;
+
+ const prepareRpcInput = (line: string): string => {
+ try {
+ const command = JSON.parse(line) as { id?: unknown; type?: unknown } | null;
+ if (
+ !command ||
+ Array.isArray(command) ||
+ typeof command.type !== "string" ||
+ command.type === "extension_ui_response" ||
+ command.type === "ack_result"
+ ) {
+ return `${line}\n`;
+ }
+ const publicId = typeof command.id === "string" ? command.id : undefined;
+ const internalId = publicId ?? `${anonymousRpcIdPrefix}-${++anonymousRpcCommandId}`;
+ pendingRpcCommands.set(internalId, { publicId, command: command.type });
+ return publicId !== undefined ? `${line}\n` : serializeJsonLine({ ...command, id: internalId });
+ } catch {
+ // The worker preserves the existing parse-error response contract.
+ return `${line}\n`;
+ }
+ };
+ const observeRpcOutput = (line: string) => {
+ let parsed: unknown;
+ try {
+ parsed = JSON.parse(line) as unknown;
+ } catch {
+ return;
+ }
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
+ return;
+ }
+ const response = parsed as { id?: unknown; type?: unknown; command?: unknown };
+ const id = typeof response.id === "string" ? response.id : undefined;
+ const pending = id !== undefined ? pendingRpcCommands.get(id) : undefined;
+ let framed = `${line}\n`;
+ if (response.type === "response" && pending?.publicId === undefined) {
+ const { id: _internalId, ...publicResponse } = response;
+ framed = serializeJsonLine(publicResponse);
+ }
+ if (!process.stdout.write(framed) && !rpcStdoutPaused) {
+ rpcStdoutPaused = true;
+ currentRpcOutput?.pause();
+ process.stdout.once("drain", () => {
+ rpcStdoutPaused = false;
+ currentRpcOutput?.resume();
+ });
+ }
+ if (response.type !== "response" || typeof response.command !== "string") {
+ return;
+ }
+ if (id !== undefined && pending?.command === response.command) {
+ pendingRpcCommands.delete(id);
+ }
+ };
+ const failPendingRpcCommands = () => {
+ for (const pending of pendingRpcCommands.values()) {
+ process.stdout.write(
+ serializeJsonLine({
+ ...(pending.publicId !== undefined ? { id: pending.publicId } : {}),
+ type: "response",
+ command: pending.command,
+ success: false,
+ error: "The isolated session worker stopped during this command; its result is uncertain and was not replayed",
+ }),
+ );
+ }
+ pendingRpcCommands.clear();
+ };
+ const reapWorkerResources = (workerPid: number | undefined) => {
+ if (!workerPid) {
+ return;
+ }
+ if (process.platform !== "win32") {
+ try {
+ process.kill(-workerPid, "SIGKILL");
+ } catch {
+ // The worker process group may already be fully reaped.
+ }
+ }
+ for (const orphan of readActiveOrphanProcesses(orphanProcessJournalPath, workerPid)) {
+ if (!isOrphanProcessIdentityCurrent(orphan)) {
+ continue;
+ }
+ const { pid } = orphan;
+ try {
+ process.kill(process.platform === "win32" ? pid : -pid, "SIGKILL");
+ } catch {
+ try {
+ process.kill(pid, "SIGKILL");
+ } catch {
+ // The detached resource may already have exited.
+ }
+ }
+ }
+ clearOrphanProcessJournal(orphanProcessJournalPath);
+ };
+
+ if (profile === "rpc") {
+ detachRpcInput = attachJsonlLineReader(process.stdin, (line) => {
+ const framed = prepareRpcInput(line);
+ const input = currentRpcInput;
+ if (input?.writable) {
+ if (!input.write(framed)) {
+ process.stdin.pause();
+ input.once("drain", () => {
+ if (currentRpcInput === input && !stdinEnded) {
+ process.stdin.resume();
+ }
+ });
+ }
+ } else {
+ bufferedRpcInput.push(framed);
+ }
+ });
+ process.stdin.once("end", () => {
+ stdinEnded = true;
+ currentRpcInput?.end();
+ });
+ }
+
+ const spawnWorker = (workerArgs: readonly string[]): ChildProcess => {
+ const launch = createOwnedWorkerLaunchSpec(workerArgs);
+ const bridgeStdin = profile === "rpc" || process.stdin.isTTY !== true;
+ const stdio: StdioOptions = interactive
+ ? ["inherit", "inherit", "inherit", "ipc"]
+ : [bridgeStdin ? "pipe" : "inherit", "pipe", "pipe", "ipc"];
+ const child = spawn(launch.command, launch.args, {
+ cwd: process.cwd(),
+ detached: process.platform !== "win32",
+ env: {
+ ...process.env,
+ [OWNED_WORKER_ENV]: "1",
+ [OWNED_RECOVERY_DESCRIPTOR_ENV]: recoveryDescriptorPath,
+ [OWNED_PROFILE_ENV]: profile,
+ [ORPHAN_PROCESS_JOURNAL_ENV]: orphanProcessJournalPath,
+ [SESSION_LEASES_ENABLED_ENV]: "1",
+ [SESSION_LEASE_OWNER_ID_ENV]: `owned-${randomUUID()}`,
+ },
+ stdio,
+ });
+ currentChild = child;
+ if (!interactive) {
+ const childInput = child.stdin ?? undefined;
+ const childOutput = child.stdout ?? undefined;
+ const childError = child.stderr ?? undefined;
+ if ((bridgeStdin && !childInput) || !childOutput || !childError) {
+ child.kill("SIGTERM");
+ throw new Error("Owned session worker did not expose bridged stdio");
+ }
+ childError.pipe(process.stderr, { end: false });
+ if (profile === "rpc") {
+ if (!childInput) {
+ throw new Error("Owned RPC worker did not expose stdin");
+ }
+ currentRpcInput = childInput;
+ currentRpcOutput = childOutput;
+ if (rpcStdoutPaused) {
+ childOutput.pause();
+ }
+ detachRpcOutput = attachJsonlLineReader(childOutput, observeRpcOutput);
+ for (const buffered of bufferedRpcInput.splice(0)) {
+ childInput.write(buffered);
+ }
+ if (stdinEnded) {
+ childInput.end();
+ }
+ } else {
+ if (childInput) {
+ process.stdin.pipe(childInput);
+ }
+ childOutput.pipe(process.stdout, { end: false });
+ }
+ }
+ return child;
+ };
+
+ const signals: NodeJS.Signals[] = ["SIGINT", "SIGTERM"];
+ if (process.platform !== "win32") {
+ signals.push("SIGHUP");
+ }
+ const signalHandlers = signals.map((signal) => {
+ const handler = () => {
+ terminating = true;
+ terminationSignal ??= signal;
+ if (currentChild) {
+ forwardSignal(currentChild, signal);
+ }
+ };
+ process.on(signal, handler);
+ return { signal, handler };
+ });
+
+ try {
+ let workerArgs = [...args];
+ let recoveryAttempt = 0;
+ while (true) {
+ if (terminating) {
+ return exitCodeForSignal(terminationSignal ?? null);
+ }
+ const workerStartedAt = Date.now();
+ const child = spawnWorker(workerArgs);
+ const workerPid = child.pid;
+ const exit = await new Promise<{ code: number; signal: NodeJS.Signals | null }>((resolveExit, reject) => {
+ child.once("error", reject);
+ child.once("close", (code, signal) => resolveExit({ code: code ?? exitCodeForSignal(signal), signal }));
+ });
+ currentChild = undefined;
+ currentRpcInput = undefined;
+ currentRpcOutput = undefined;
+ if (profile === "rpc" && !stdinEnded) {
+ process.stdin.resume();
+ }
+ detachRpcOutput?.();
+ detachRpcOutput = undefined;
+ if (!interactive && profile !== "rpc" && child.stdin) {
+ process.stdin.unpipe(child.stdin);
+ }
+ if (child.connected) {
+ child.disconnect();
+ }
+ reapWorkerResources(workerPid);
+ const rpcCrashed =
+ profile === "rpc" &&
+ !terminating &&
+ (exit.code !== 0 || exit.signal !== null || pendingRpcCommands.size > 0);
+ const workerExitCode = rpcCrashed && exit.code === 0 ? 1 : exit.code;
+ if (Date.now() - workerStartedAt >= 60_000) {
+ recoveryAttempt = 0;
+ }
+ if (rpcCrashed) {
+ failPendingRpcCommands();
+ }
+ const shouldRecover = rpcCrashed && !stdinEnded && recoveryAttempt < 3;
+ if (!shouldRecover) {
+ return terminationSignal ? exitCodeForSignal(terminationSignal) : workerExitCode;
+ }
+ const descriptor = readOwnedRecoveryDescriptor(recoveryDescriptorPath);
+ if (!descriptor?.sessionFile) {
+ return terminationSignal ? exitCodeForSignal(terminationSignal) : workerExitCode;
+ }
+ workerArgs = createRpcRecoveryArgs(args, descriptor.sessionFile);
+ const retryDelay = [250, 1000, 5000][recoveryAttempt] ?? 5000;
+ recoveryAttempt++;
+ await new Promise((resolveDelay) => setTimeout(resolveDelay, retryDelay));
+ if (terminating) {
+ return exitCodeForSignal(terminationSignal ?? null);
+ }
+ }
+ } finally {
+ for (const { signal, handler } of signalHandlers) {
+ process.off(signal, handler);
+ }
+ detachRpcInput?.();
+ detachRpcOutput?.();
+ rmSync(recoveryDescriptorPath, { force: true });
+ clearOrphanProcessJournal(orphanProcessJournalPath);
+ }
+}
+
+export async function maybeRunOwnedSessionWorkerFrontend(args: readonly string[]): Promise<boolean> {
+ const profile = classifyOwnedSessionWorkerInvocation(args, process.stdin.isTTY);
+ if (!profile) {
+ return false;
+ }
+ process.exitCode = await runOwnedSessionWorkerFrontend(args, profile);
+ return true;
+}
+
+export function installOwnedSessionWorkerOwnerWatch(): void {
+ if (process.env[OWNED_WORKER_ENV] !== "1") {
+ return;
+ }
+ if (!process.channel) {
+ throw new Error("Owned session worker is missing its owner channel");
+ }
+
+ let ownerGone = false;
+ const terminate = () => {
+ if (ownerGone) {
+ return;
+ }
+ ownerGone = true;
+ closeOwnerWatch = undefined;
+ const forceTimer = setTimeout(() => {
+ if (process.platform !== "win32") {
+ try {
+ process.kill(-process.pid, "SIGKILL");
+ return;
+ } catch {
+ // Fall through to terminating only this process.
+ }
+ }
+ process.exit(143);
+ }, 5000);
+ forceTimer.unref();
+ process.kill(process.pid, "SIGTERM");
+ };
+ process.once("disconnect", terminate);
+ process.channel.unref();
+ closeOwnerWatch = () => {
+ if (ownerGone) {
+ return;
+ }
+ ownerGone = true;
+ process.off("disconnect", terminate);
+ if (process.connected) {
+ process.disconnect();
+ }
+ closeOwnerWatch = undefined;
+ };
+}
+
+export function closeOwnedSessionWorkerOwnerWatch(): void {
+ closeOwnerWatch?.();
+}
diff --git a/packages/coding-agent/src/cli/subprocess-launch.ts b/packages/coding-agent/src/cli/subprocess-launch.ts
new file mode 100644
index 0000000000..a8b62bd1d4
--- /dev/null
+++ b/packages/coding-agent/src/cli/subprocess-launch.ts
@@ -0,0 +1,21 @@
+import { isBunBinary } from "../config.js";
+
+export interface CliSubprocessLaunchSpec {
+ command: string;
+ args: string[];
+}
+
+export function createCliSubprocessLaunchSpec(
+ args: readonly string[],
+ executable = process.execPath,
+ execArgs: readonly string[] = process.execArgv,
+ entrypoint = process.argv[1],
+): CliSubprocessLaunchSpec {
+ if (isBunBinary) {
+ return { command: executable, args: [...args] };
+ }
+ if (!entrypoint) {
+ throw new Error("Cannot determine current CLI entrypoint for subprocess launch");
+ }
+ return { command: executable, args: [...execArgs, entrypoint, ...args] };
+}
diff --git a/packages/coding-agent/src/core/agent-session-runtime.ts b/packages/coding-agent/src/core/agent-session-runtime.ts
index d06948c81b..3c3e1fa0e4 100644
--- a/packages/coding-agent/src/core/agent-session-runtime.ts
+++ b/packages/coding-agent/src/core/agent-session-runtime.ts
@@ -20,6 +20,7 @@ import type {
import type { CreateAgentSessionResult } from "./sdk.js";
import { assertSessionCwdExists } from "./session-cwd.js";
import { SessionImportFileNotFoundError } from "./session-import-errors.js";
+import { acquireSessionLease, canonicalSessionPath, type SessionLease } from "./session-lease.js";
import { SessionManager } from "./session-manager.js";
export { SessionImportFileNotFoundError } from "./session-import-errors.js";
@@ -87,6 +88,7 @@ function extractUserMessageText(content: string | Array<{ type: string; text?: s
*/
export class AgentSessionRuntime implements SubagentRuntimeHost {
private rebindSession?: (session: AgentSession) => Promise<void>;
+ private readonly sessionReplacedListeners = new Set<(session: AgentSession) => void | Promise<void>>();
private runtimeEnvScope?: <T>(fn: () => Promise<T>) => Promise<T>;
private beforeSessionInvalidate?: () => void;
private subagentRuntimeHost?: SubagentRuntimeHost;
@@ -101,6 +103,7 @@ export class AgentSessionRuntime implements SubagentRuntimeHost {
private _modelFallbackMessage?: string,
private readonly sessionConfig?: AgentSessionRuntimeConfig,
private readonly _metadata: AgentSessionRuntimeMetadata = { kind: "top-level", createdAt: Date.now() },
+ private _sessionLease?: SessionLease,
) {
this.bindRuntimeHost();
}
@@ -143,6 +146,11 @@ export class AgentSessionRuntime implements SubagentRuntimeHost {
this.rebindSession = rebindSession;
}
+ onSessionReplaced(listener: (session: AgentSession) => void | Promise<void>): () => void {
+ this.sessionReplacedListeners.add(listener);
+ return () => this.sessionReplacedListeners.delete(listener);
+ }
+
/**
* Host-installed scope wrapping every runtime rebuild (new/switch/fork/
* import and subagent creation), during which extensions re-load. The
@@ -232,6 +240,70 @@ export class AgentSessionRuntime implements SubagentRuntimeHost {
this.bindRuntimeHost();
}
+ private acquireReplacementLease(sessionPath: string | undefined): SessionLease | undefined {
+ if (sessionPath && this._sessionLease?.sessionPath === canonicalSessionPath(sessionPath)) {
+ return this._sessionLease;
+ }
+ return acquireSessionLease(sessionPath, this.services.agentDir);
+ }
+
+ private releaseUncommittedLease(lease: SessionLease | undefined): void {
+ if (lease !== this._sessionLease) {
+ lease?.release();
+ }
+ }
+
+ private releaseSessionLease(): void {
+ this._sessionLease?.release();
+ this._sessionLease = undefined;
+ }
+
+ private transferSessionLeaseToSession(): void {
+ const lease = this._sessionLease;
+ if (!lease) {
+ return;
+ }
+ this._sessionLease = undefined;
+ this.session.registerDisposeCallback(() => lease.release());
+ }
+
+ private commitReplacementLease(lease: SessionLease | undefined): void {
+ if (lease === this._sessionLease) {
+ return;
+ }
+ const previous = this._sessionLease;
+ this._sessionLease = lease;
+ previous?.release();
+ }
+
+ private async buildAndApplyReplacement(
+ build: () => Promise<CreateAgentSessionRuntimeResult>,
+ lease: SessionLease | undefined,
+ ): Promise<void> {
+ let result: CreateAgentSessionRuntimeResult;
+ try {
+ result = await build();
+ } catch (error) {
+ this.releaseUncommittedLease(lease);
+ throw error;
+ }
+ this.apply(result);
+ this.commitReplacementLease(lease);
+ }
+
+ private async teardownForReplacement(
+ reason: SessionShutdownEvent["reason"],
+ targetSessionFile: string | undefined,
+ lease: SessionLease | undefined,
+ ): Promise<void> {
+ try {
+ await this.teardownCurrent(reason, targetSessionFile);
+ } catch (error) {
+ this.releaseUncommittedLease(lease);
+ throw error;
+ }
+ }
+
private async disposeSubagentRuntimes(): Promise<void> {
const runtimes = [...this.subagentRuntimes.values()];
this.subagentRuntimes.clear();
@@ -333,6 +405,9 @@ export class AgentSessionRuntime implements SubagentRuntimeHost {
if (status === "done") {
// Flush traces now since the runtime's own shutdown path is skipped while retained.
await flushAgentTraceUpload(runtime.session.sessionManager).catch(() => undefined);
+ if (runtime instanceof AgentSessionRuntime) {
+ runtime.transferSessionLeaseToSession();
+ }
// Retention can decline if the parent is already tearing down; if so, fall
// through and dispose the runtime instead of leaving it dangling.
if (options.parentSession.retainFinishedRlmChildSession(options.id, runtime.session)) {
@@ -350,6 +425,9 @@ export class AgentSessionRuntime implements SubagentRuntimeHost {
if (this.rebindSession) {
await this.rebindSession(this.session);
}
+ for (const listener of this.sessionReplacedListeners) {
+ await listener(this.session);
+ }
if (withSession) {
await withSession(this.session.createReplacedSessionContext());
}
@@ -365,19 +443,28 @@ export class AgentSessionRuntime implements SubagentRuntimeHost {
}
const previousSessionFile = this.session.sessionFile;
- const sessionManager = SessionManager.open(sessionPath, undefined, options?.cwdOverride);
- assertSessionCwdExists(sessionManager, this.cwd);
- await this.teardownCurrent("resume", sessionManager.getSessionFile());
- this.apply(
- await this.scopedBuild(() =>
- this.createRuntime({
- cwd: sessionManager.getCwd(),
- agentDir: this.services.agentDir,
- sessionManager,
- sessionStartEvent: { type: "session_start", reason: "resume", previousSessionFile },
- sessionConfig: this.sessionConfig,
- }),
- ),
+ const lease = this.acquireReplacementLease(sessionPath);
+ let sessionManager: SessionManager;
+ try {
+ sessionManager = SessionManager.open(sessionPath, undefined, options?.cwdOverride);
+ assertSessionCwdExists(sessionManager, this.cwd);
+ } catch (error) {
+ this.releaseUncommittedLease(lease);
+ throw error;
+ }
+ await this.teardownForReplacement("resume", sessionManager.getSessionFile(), lease);
+ await this.buildAndApplyReplacement(
+ () =>
+ this.scopedBuild(() =>
+ this.createRuntime({
+ cwd: sessionManager.getCwd(),
+ agentDir: this.services.agentDir,
+ sessionManager,
+ sessionStartEvent: { type: "session_start", reason: "resume", previousSessionFile },
+ sessionConfig: this.sessionConfig,
+ }),
+ ),
+ lease,
);
await this.finishSessionReplacement(options?.withSession);
return { cancelled: false };
@@ -399,18 +486,21 @@ export class AgentSessionRuntime implements SubagentRuntimeHost {
if (options?.parentSession) {
sessionManager.newSession({ parentSession: options.parentSession });
}
+ const lease = this.acquireReplacementLease(sessionManager.getSessionFile());
- await this.teardownCurrent("new", sessionManager.getSessionFile());
- this.apply(
- await this.scopedBuild(() =>
- this.createRuntime({
- cwd: this.cwd,
- agentDir: this.services.agentDir,
- sessionManager,
- sessionStartEvent: { type: "session_start", reason: "new", previousSessionFile },
- sessionConfig: this.sessionConfig,
- }),
- ),
+ await this.teardownForReplacement("new", sessionManager.getSessionFile(), lease);
+ await this.buildAndApplyReplacement(
+ () =>
+ this.scopedBuild(() =>
+ this.createRuntime({
+ cwd: this.cwd,
+ agentDir: this.services.agentDir,
+ sessionManager,
+ sessionStartEvent: { type: "session_start", reason: "new", previousSessionFile },
+ sessionConfig: this.sessionConfig,
+ }),
+ ),
+ lease,
);
if (options?.setup) {
await options.setup(this.session.sessionManager);
@@ -457,17 +547,20 @@ export class AgentSessionRuntime implements SubagentRuntimeHost {
if (!targetLeafId) {
const sessionManager = SessionManager.create(this.cwd, sessionDir);
sessionManager.newSession({ parentSession: currentSessionFile });
- await this.teardownCurrent("fork", sessionManager.getSessionFile());
- this.apply(
- await this.scopedBuild(() =>
- this.createRuntime({
- cwd: this.cwd,
- agentDir: this.services.agentDir,
- sessionManager,
- sessionStartEvent: { type: "session_start", reason: "fork", previousSessionFile },
- sessionConfig: this.sessionConfig,
- }),
- ),
+ const lease = this.acquireReplacementLease(sessionManager.getSessionFile());
+ await this.teardownForReplacement("fork", sessionManager.getSessionFile(), lease);
+ await this.buildAndApplyReplacement(
+ () =>
+ this.scopedBuild(() =>
+ this.createRuntime({
+ cwd: this.cwd,
+ agentDir: this.services.agentDir,
+ sessionManager,
+ sessionStartEvent: { type: "session_start", reason: "fork", previousSessionFile },
+ sessionConfig: this.sessionConfig,
+ }),
+ ),
+ lease,
);
await this.finishSessionReplacement(options?.withSession);
return { cancelled: false, selectedText };
@@ -479,17 +572,20 @@ export class AgentSessionRuntime implements SubagentRuntimeHost {
throw new Error("Failed to create forked session");
}
const sessionManager = SessionManager.open(forkedSessionPath, sessionDir);
- await this.teardownCurrent("fork", sessionManager.getSessionFile());
- this.apply(
- await this.scopedBuild(() =>
- this.createRuntime({
- cwd: sessionManager.getCwd(),
- agentDir: this.services.agentDir,
- sessionManager,
- sessionStartEvent: { type: "session_start", reason: "fork", previousSessionFile },
- sessionConfig: this.sessionConfig,
- }),
- ),
+ const lease = this.acquireReplacementLease(sessionManager.getSessionFile());
+ await this.teardownForReplacement("fork", sessionManager.getSessionFile(), lease);
+ await this.buildAndApplyReplacement(
+ () =>
+ this.scopedBuild(() =>
+ this.createRuntime({
+ cwd: sessionManager.getCwd(),
+ agentDir: this.services.agentDir,
+ sessionManager,
+ sessionStartEvent: { type: "session_start", reason: "fork", previousSessionFile },
+ sessionConfig: this.sessionConfig,
+ }),
+ ),
+ lease,
);
await this.finishSessionReplacement(options?.withSession);
return { cancelled: false, selectedText };
@@ -501,17 +597,20 @@ export class AgentSessionRuntime implements SubagentRuntimeHost {
} else {
sessionManager.createBranchedSession(targetLeafId);
}
- await this.teardownCurrent("fork", sessionManager.getSessionFile());
- this.apply(
- await this.scopedBuild(() =>
- this.createRuntime({
- cwd: this.cwd,
- agentDir: this.services.agentDir,
- sessionManager,
- sessionStartEvent: { type: "session_start", reason: "fork", previousSessionFile },
- sessionConfig: this.sessionConfig,
- }),
- ),
+ const lease = this.acquireReplacementLease(sessionManager.getSessionFile());
+ await this.teardownForReplacement("fork", sessionManager.getSessionFile(), lease);
+ await this.buildAndApplyReplacement(
+ () =>
+ this.scopedBuild(() =>
+ this.createRuntime({
+ cwd: this.cwd,
+ agentDir: this.services.agentDir,
+ sessionManager,
+ sessionStartEvent: { type: "session_start", reason: "fork", previousSessionFile },
+ sessionConfig: this.sessionConfig,
+ }),
+ ),
+ lease,
);
await this.finishSessionReplacement(options?.withSession);
return { cancelled: false, selectedText };
@@ -542,23 +641,32 @@ export class AgentSessionRuntime implements SubagentRuntimeHost {
}
const previousSessionFile = this.session.sessionFile;
- if (resolve(destinationPath) !== resolvedPath) {
- copyFileSync(resolvedPath, destinationPath);
- }
-
- const sessionManager = SessionManager.open(destinationPath, sessionDir, cwdOverride);
- assertSessionCwdExists(sessionManager, this.cwd);
- await this.teardownCurrent("resume", sessionManager.getSessionFile());
- this.apply(
- await this.scopedBuild(() =>
- this.createRuntime({
- cwd: sessionManager.getCwd(),
- agentDir: this.services.agentDir,
- sessionManager,
- sessionStartEvent: { type: "session_start", reason: "resume", previousSessionFile },
- sessionConfig: this.sessionConfig,
- }),
- ),
+ const lease = this.acquireReplacementLease(destinationPath);
+ let sessionManager: SessionManager;
+ try {
+ if (resolve(destinationPath) !== resolvedPath) {
+ copyFileSync(resolvedPath, destinationPath);
+ }
+
+ sessionManager = SessionManager.open(destinationPath, sessionDir, cwdOverride);
+ assertSessionCwdExists(sessionManager, this.cwd);
+ } catch (error) {
+ this.releaseUncommittedLease(lease);
+ throw error;
+ }
+ await this.teardownForReplacement("resume", sessionManager.getSessionFile(), lease);
+ await this.buildAndApplyReplacement(
+ () =>
+ this.scopedBuild(() =>
+ this.createRuntime({
+ cwd: sessionManager.getCwd(),
+ agentDir: this.services.agentDir,
+ sessionManager,
+ sessionStartEvent: { type: "session_start", reason: "resume", previousSessionFile },
+ sessionConfig: this.sessionConfig,
+ }),
+ ),
+ lease,
);
await this.finishSessionReplacement();
return { cancelled: false };
@@ -595,8 +703,12 @@ export class AgentSessionRuntime implements SubagentRuntimeHost {
} catch (error) {
disposeError ??= error;
}
- if (disposeError) {
- throw disposeError;
+ try {
+ if (disposeError) {
+ throw disposeError;
+ }
+ } finally {
+ this.releaseSessionLease();
}
}
@@ -624,19 +736,29 @@ export async function createAgentSessionRuntime(
sessionConfig?: AgentSessionRuntimeConfig;
sessionOptions?: AgentSessionCreationOptions;
runtimeMetadata?: AgentSessionRuntimeMetadata;
+ sessionLease?: SessionLease;
},
): Promise<AgentSessionRuntime> {
- assertSessionCwdExists(options.sessionManager, options.cwd);
- const result = await createRuntime(options);
- return new AgentSessionRuntime(
- result.session,
- result.services,
- createRuntime,
- result.diagnostics,
- result.modelFallbackMessage,
- options.sessionConfig,
- options.runtimeMetadata,
- );
+ const { sessionLease, ...runtimeOptions } = options;
+ const lease =
+ sessionLease ?? acquireSessionLease(runtimeOptions.sessionManager.getSessionFile(), runtimeOptions.agentDir);
+ try {
+ assertSessionCwdExists(runtimeOptions.sessionManager, runtimeOptions.cwd);
+ const result = await createRuntime(runtimeOptions);
+ return new AgentSessionRuntime(
+ result.session,
+ result.services,
+ createRuntime,
+ result.diagnostics,
+ result.modelFallbackMessage,
+ runtimeOptions.sessionConfig,
+ runtimeOptions.runtimeMetadata,
+ lease,
+ );
+ } catch (error) {
+ lease?.release();
+ throw error;
+ }
}
export {
diff --git a/packages/coding-agent/src/core/agent-session.ts b/packages/coding-agent/src/core/agent-session.ts
index 308b40164f..182be7e4da 100644
--- a/packages/coding-agent/src/core/agent-session.ts
+++ b/packages/coding-agent/src/core/agent-session.ts
@@ -838,6 +838,7 @@ export class AgentSession {
private _extensionErrorListener?: ExtensionErrorListener;
private _extensionErrorUnsubscriber?: () => void;
private _disposed = false;
+ private readonly _disposeCallbacks = new Set<() => void>();
// Set at the start of async teardown so a child finishing mid-disposeAsync doesn't
// re-populate the retained map after it's been cleared.
private _disposing = false;
@@ -1625,7 +1626,10 @@ export class AgentSession {
return queuedMessage;
}
const snapshot = this._snapshotAutonomousRuntimeState();
- const autonomousMessage = await nextAutonomousContinuation(this._autonomousState, message, { cwd: this._cwd });
+ const autonomousMessage = await nextAutonomousContinuation(this._autonomousState, message, {
+ cwd: this._cwd,
+ signal: this.agent.signal,
+ });
if (!autonomousMessage) {
return undefined;
}
@@ -2003,6 +2007,7 @@ export class AgentSession {
}
const autonomousMessage = await nextAutonomousContinuation(this._autonomousState, context.message, {
cwd: this._cwd,
+ signal,
});
return autonomousMessage ? [autonomousMessage] : [];
}
@@ -2535,32 +2540,51 @@ export class AgentSession {
return;
}
this._disposed = true;
- // Invalidate scheduled timers and abort any in-flight review so a late
- // resolution cannot write harness state or re-subscribe handlers.
- this._autoRefineReviewAbort?.abort();
- this._refineAbortController?.abort();
- this._discardPendingAutoRefine({ cancelPostCompactionContinue: true });
- this._autoRefineBranchVersion++;
- this._cancelActiveRlmChildRuns("Parent session disposed");
- for (const unsubscribe of this._retainedRlmChildUnsubscribes.values()) {
- unsubscribe();
+ try {
+ // Invalidate scheduled timers and abort any in-flight review so a late
+ // resolution cannot write harness state or re-subscribe handlers.
+ this._autoRefineReviewAbort?.abort();
+ this._refineAbortController?.abort();
+ this._discardPendingAutoRefine({ cancelPostCompactionContinue: true });
+ this._autoRefineBranchVersion++;
+ this._cancelActiveRlmChildRuns("Parent session disposed");
+ for (const unsubscribe of this._retainedRlmChildUnsubscribes.values()) {
+ unsubscribe();
+ }
+ this._retainedRlmChildUnsubscribes.clear();
+ for (const session of this._retainedRlmChildSessions.values()) {
+ session.dispose();
+ }
+ this._retainedRlmChildSessions.clear();
+ this._pendingNextTurnMessages = [];
+ this._rejectQueuedAgentMessageDeliveries(new Error("Queued agent message was cleared before delivery."));
+ this._steeringMessages = [];
+ this._followUpMessages = [];
+ this.agent.clearAllQueues();
+ this._extensionRunner.invalidate(
+ "This extension ctx is stale after session replacement or reload. Do not use a captured pi or command ctx after ctx.newSession(), ctx.fork(), ctx.switchSession(), or ctx.reload(). For newSession, fork, and switchSession, move post-replacement work into withSession and use the ctx passed to withSession. For reload, do not use the old ctx after await ctx.reload().",
+ );
+ this._disconnectFromAgent();
+ this._eventListeners = [];
+ cleanupSessionResources(this.sessionId);
+ } finally {
+ for (const callback of this._disposeCallbacks) {
+ try {
+ callback();
+ } catch {
+ // Disposal remains best-effort; one owner must not block the rest.
+ }
+ }
+ this._disposeCallbacks.clear();
}
- this._retainedRlmChildUnsubscribes.clear();
- for (const session of this._retainedRlmChildSessions.values()) {
- session.dispose();
+ }
+
+ registerDisposeCallback(callback: () => void): void {
+ if (this._disposed) {
+ callback();
+ return;
}
- this._retainedRlmChildSessions.clear();
- this._pendingNextTurnMessages = [];
- this._rejectQueuedAgentMessageDeliveries(new Error("Queued agent message was cleared before delivery."));
- this._steeringMessages = [];
- this._followUpMessages = [];
- this.agent.clearAllQueues();
- this._extensionRunner.invalidate(
- "This extension ctx is stale after session replacement or reload. Do not use a captured pi or command ctx after ctx.newSession(), ctx.fork(), ctx.switchSession(), or ctx.reload(). For newSession, fork, and switchSession, move post-replacement work into withSession and use the ctx passed to withSession. For reload, do not use the old ctx after await ctx.reload().",
- );
- this._disconnectFromAgent();
- this._eventListeners = [];
- cleanupSessionResources(this.sessionId);
+ this._disposeCallbacks.add(callback);
}
// =========================================================================
diff --git a/packages/coding-agent/src/core/autonomous.ts b/packages/coding-agent/src/core/autonomous.ts
index c9be6a4ac2..75930d415c 100644
--- a/packages/coding-agent/src/core/autonomous.ts
+++ b/packages/coding-agent/src/core/autonomous.ts
@@ -96,6 +96,11 @@ interface GitWorktreeSnapshot {
untrackedHash: string;
}
+interface AutonomousOperationOptions {
+ cwd?: string;
+ signal?: AbortSignal;
+}
+
type GateFailure = AgentAutonomousGateFailure;
export function createAutonomousRuntimeState(
@@ -191,13 +196,15 @@ function autonomousTokenDelta(usage: Usage | undefined): number {
export async function nextAutonomousContinuation(
state: AutonomousRuntimeState,
message: AssistantMessage,
- options: { cwd?: string } = {},
+ options: AutonomousOperationOptions = {},
now = Date.now(),
): Promise<UserMessage | undefined> {
+ options.signal?.throwIfAborted();
if (!state.enabled) {
return undefined;
}
const decision = await shouldAutonomouslyContinue(state, message, options, now);
+ options.signal?.throwIfAborted();
if (!decision.shouldContinue) {
return undefined;
}
@@ -220,13 +227,15 @@ export async function nextAutonomousContinuation(
export async function shouldAutonomouslyContinue(
state: AutonomousRuntimeState,
message: AssistantMessage,
- options: { cwd?: string } = {},
+ options: AutonomousOperationOptions = {},
now = Date.now(),
): Promise<AutonomousDecision> {
+ options.signal?.throwIfAborted();
if (!state.enabled || message.stopReason === "error" || message.stopReason === "aborted") {
return { shouldContinue: false, reason: "not_needed" };
}
const gateResult = await refreshAutonomousQualityGates(state, options);
+ options.signal?.throwIfAborted();
if (gateResult) {
if (gateResult === "passed") {
return { shouldContinue: false, reason: "not_needed" };
@@ -263,23 +272,27 @@ export function autonomousLimitReason(
export async function refreshAutonomousQualityGates(
state: AutonomousRuntimeState,
- options: { cwd?: string } = {},
+ options: AutonomousOperationOptions = {},
): Promise<AutonomousGateResult | undefined> {
+ options.signal?.throwIfAborted();
if (!state.enabled || state.gates.commands.length === 0) {
return undefined;
}
- return await runAutonomousQualityGates(state, options.cwd);
+ return await runAutonomousQualityGates(state, options.cwd, options.signal);
}
async function runAutonomousQualityGates(
state: AutonomousRuntimeState,
cwd: string | undefined,
+ signal: AbortSignal | undefined,
): Promise<AutonomousGateResult> {
+ signal?.throwIfAborted();
if (!cwd) {
return "failed";
}
for (const command of state.gates.commands) {
- const currentSnapshot = await captureGitWorktreeSnapshot(cwd);
+ const currentSnapshot = await captureGitWorktreeSnapshot(cwd, signal);
+ signal?.throwIfAborted();
if (
state.lastGateFailure?.command === command &&
state.lastGateFailureSnapshot &&
@@ -301,8 +314,11 @@ async function runAutonomousQualityGates(
shell: true,
timeoutMs: state.gates.timeoutMs,
maxOutputChars: MAX_GATE_OUTPUT_CHARS,
+ signal,
});
- const postRunSnapshot = await captureGitWorktreeSnapshot(cwd);
+ signal?.throwIfAborted();
+ const postRunSnapshot = await captureGitWorktreeSnapshot(cwd, signal);
+ signal?.throwIfAborted();
if (result.status === 0 && !result.error && !result.timedOut) {
state.gateAttempts[command] = 0;
if (state.lastGateFailure?.command === command) {
@@ -331,23 +347,35 @@ async function runAutonomousQualityGates(
return "passed";
}
+export function buildAutonomousGateFailureContinuation(
+ failure: AgentAutonomousGateFailure,
+ maxRetries: number,
+ timestamp = Date.now(),
+): string {
+ return (
+ `Autonomous quality gate failed (attempt ${failure.attempt}/${maxRetries}): \`${failure.command}\` ${failure.exitText}.\n` +
+ (failure.output ? `\nOutput:\n${failure.output}\n` : "\n") +
+ `\nContinue working. Fix the failure, then produce terminal evidence. Timestamp: ${new Date(timestamp).toISOString()}.`
+ );
+}
+
function buildGateFailureContinuation(state: AutonomousRuntimeState, timestamp: number): string | undefined {
const failure = state.lastGateFailure;
if (!failure) {
return undefined;
}
- return (
- `Autonomous quality gate failed (attempt ${failure.attempt}/${state.gates.maxRetries}): \`${failure.command}\` ${failure.exitText}.\n` +
- (failure.output ? `\nOutput:\n${failure.output}\n` : "\n") +
- `\nContinue working. Fix the failure, then produce terminal evidence. Timestamp: ${new Date(timestamp).toISOString()}.`
- );
+ return buildAutonomousGateFailureContinuation(failure, state.gates.maxRetries, timestamp);
}
function gitWorktreeSnapshotsEqual(a: GitWorktreeSnapshot | undefined, b: GitWorktreeSnapshot | undefined): boolean {
return !!a && !!b && a.status === b.status && a.diff === b.diff && a.untrackedHash === b.untrackedHash;
}
-async function captureGitWorktreeSnapshot(cwd: string | undefined): Promise<GitWorktreeSnapshot | undefined> {
+async function captureGitWorktreeSnapshot(
+ cwd: string | undefined,
+ signal?: AbortSignal,
+): Promise<GitWorktreeSnapshot | undefined> {
+ signal?.throwIfAborted();
if (!cwd) {
return undefined;
}
@@ -367,8 +395,10 @@ async function captureGitWorktreeSnapshot(cwd: string | undefined): Promise<GitW
{
cwd,
timeoutMs: 10_000,
+ signal,
},
);
+ signal?.throwIfAborted();
if (status.status !== 0 || status.error || status.timedOut || status.outputTruncated) {
return undefined;
}
@@ -378,15 +408,17 @@ async function captureGitWorktreeSnapshot(cwd: string | undefined): Promise<GitW
{
cwd,
timeoutMs: 10_000,
+ signal,
},
);
+ signal?.throwIfAborted();
if (diff.status !== 0 || diff.error || diff.timedOut || diff.outputTruncated) {
return undefined;
}
return {
status: status.stdout,
diff: diff.stdout,
- untrackedHash: await hashUntrackedFiles(cwd, status.stdout),
+ untrackedHash: await hashUntrackedFiles(cwd, status.stdout, signal),
};
}
@@ -398,32 +430,40 @@ function untrackedPathsFromStatus(status: string): string[] {
.sort();
}
-async function hashUntrackedFiles(cwd: string, status: string): Promise<string> {
+async function hashUntrackedFiles(cwd: string, status: string, signal?: AbortSignal): Promise<string> {
const aggregate = createHash("sha256");
for (const path of untrackedPathsFromStatus(status)) {
+ signal?.throwIfAborted();
aggregate.update(path);
aggregate.update("\0");
- aggregate.update(await hashUntrackedPath(resolve(cwd, path)));
+ aggregate.update(await hashUntrackedPath(resolve(cwd, path), signal));
aggregate.update("\0");
}
+ signal?.throwIfAborted();
return aggregate.digest("hex");
}
-async function hashUntrackedPath(path: string): Promise<string> {
+async function hashUntrackedPath(path: string, signal?: AbortSignal): Promise<string> {
try {
+ signal?.throwIfAborted();
const stat = await lstat(path);
+ signal?.throwIfAborted();
if (stat.isSymbolicLink()) {
- return `symlink:${await readlink(path)}`;
+ const target = await readlink(path);
+ signal?.throwIfAborted();
+ return `symlink:${target}`;
}
if (!stat.isFile()) {
return `other:${stat.mode}:${stat.size}:${stat.mtimeMs}`;
}
const hash = createHash("sha256");
- for await (const chunk of createReadStream(path)) {
+ for await (const chunk of createReadStream(path, { signal })) {
hash.update(chunk);
}
+ signal?.throwIfAborted();
return `file:${hash.digest("hex")}`;
} catch (error) {
+ signal?.throwIfAborted();
return `error:${error instanceof Error ? error.message : String(error)}`;
}
}
@@ -441,8 +481,15 @@ interface ChildProcessResult {
function runChildProcess(
command: string,
args: string[],
- options: { cwd?: string; shell?: boolean; timeoutMs?: number; maxOutputChars?: number } = {},
+ options: {
+ cwd?: string;
+ shell?: boolean;
+ timeoutMs?: number;
+ maxOutputChars?: number;
+ signal?: AbortSignal;
+ } = {},
): Promise<ChildProcessResult> {
+ options.signal?.throwIfAborted();
return new Promise((resolve) => {
const child = spawn(command, args, {
cwd: options.cwd,
@@ -468,6 +515,7 @@ function runChildProcess(
if (timer) {
clearTimeout(timer);
}
+ options.signal?.removeEventListener("abort", abort);
if (child.pid) {
untrackDetachedChildPid(child.pid);
}
@@ -483,6 +531,17 @@ function runChildProcess(
}
}, options.timeoutMs)
: undefined;
+ const abort = () => {
+ if (child.pid) {
+ killProcessTree(child.pid);
+ } else {
+ child.kill("SIGKILL");
+ }
+ };
+ options.signal?.addEventListener("abort", abort, { once: true });
+ if (options.signal?.aborted) {
+ abort();
+ }
child.stdout?.setEncoding("utf8");
child.stderr?.setEncoding("utf8");
child.stdout?.on("data", (chunk: string) => {
diff --git a/packages/coding-agent/src/core/cron-jobs.ts b/packages/coding-agent/src/core/cron-jobs.ts
index 50c7a34bda..5e5717ba58 100644
--- a/packages/coding-agent/src/core/cron-jobs.ts
+++ b/packages/coding-agent/src/core/cron-jobs.ts
@@ -1,6 +1,16 @@
import { randomUUID } from "node:crypto";
-import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
-import { dirname, resolve } from "node:path";
+import {
+ closeSync,
+ existsSync,
+ fsyncSync,
+ mkdirSync,
+ openSync,
+ readFileSync,
+ renameSync,
+ writeFileSync,
+} from "node:fs";
+import { dirname, join, resolve } from "node:path";
+import { lockSync } from "proper-lockfile";
import { Type } from "typebox";
import type { ToolDefinition } from "./extensions/types.js";
@@ -61,6 +71,11 @@ export interface CreateAgentCronJobInput {
export type AgentCronJobRunResult = "ran" | "skipped";
+export interface AgentCronDispatch {
+ id: string;
+ job: AgentCronJob;
+}
+
export interface AgentCronSchedulerHooks {
runJob: (job: AgentCronJob) => Promise<AgentCronJobRunResult | undefined>;
now?: () => Date;
@@ -78,8 +93,23 @@ export interface HeartbeatCronSessionActivity {
interface CronJobsFile {
jobs?: unknown;
+ dispatches?: unknown;
}
+interface AgentCronDispatchRecord {
+ id: string;
+ jobId: string;
+ claimedAt: string;
+ scheduledFor: string;
+}
+
+interface CronJobsState {
+ jobs: AgentCronJob[];
+ dispatches: AgentCronDispatchRecord[];
+}
+
+export const SESSION_SCHEDULED_JOBS_FILENAME = "scheduled-jobs.json";
+
const MAX_TIMEOUT_MS = 2_147_483_647;
const ONE_SECOND_MS = 1000;
const ONE_MINUTE_MS = 60_000;
@@ -117,7 +147,48 @@ export interface AgentRlmHeartbeatController {
}
export class AgentCronJobStore {
- constructor(private readonly filePath: string) {}
+ private readonly sessionArtifactFiles = new Map<string, string>();
+
+ constructor(
+ private readonly filePath?: string,
+ private readonly sessionArtifactMode = false,
+ ) {
+ if (!filePath && !sessionArtifactMode) {
+ throw new Error("Cron job store requires a file path");
+ }
+ }
+
+ static forSessionArtifacts(): AgentCronJobStore {
+ return new AgentCronJobStore(undefined, true);
+ }
+
+ registerSessionArtifact(sessionId: string, artifactDir: string): boolean {
+ if (!this.sessionArtifactMode) {
+ return false;
+ }
+ const path = join(artifactDir, SESSION_SCHEDULED_JOBS_FILENAME);
+ if (this.sessionArtifactFiles.get(sessionId) === path) {
+ return false;
+ }
+ this.sessionArtifactFiles.set(sessionId, path);
+ return true;
+ }
+
+ recoverSessionArtifact(sessionId: string, now = new Date()): AgentCronJob[] {
+ const path = this.sessionArtifactFiles.get(sessionId);
+ if (!path) {
+ return [];
+ }
+ return withCronJobsStateLocks([path], () => {
+ const state = readJobsState(path);
+ const recovered: AgentCronJob[] = [];
+ if (state.dispatches.length > 0) {
+ recoverInterruptedInState(state, now, recovered);
+ writeJobsState(path, state);
+ }
+ return recovered;
+ });
+ }
list(): AgentCronJob[] {
return this.readJobs().sort((a, b) => compareOptionalIso(a.nextRunAt, b.nextRunAt));
@@ -562,6 +633,71 @@ export class AgentCronJobStore {
return this.readJobs().filter((job) => isDueJob(job, now));
}
+ claimDue(dueAt = new Date(), claimedAt = dueAt): AgentCronDispatch[] {
+ return this.mutateStates((state) => claimDueInState(state, dueAt, claimedAt));
+ }
+
+ getClaimedJob(id: string): AgentCronJob | undefined {
+ for (const state of this.readStates()) {
+ if (!state.dispatches.some((dispatch) => dispatch.jobId === id)) {
+ continue;
+ }
+ return state.jobs.find((job) => job.id === id && job.status === "active");
+ }
+ return undefined;
+ }
+
+ recordDispatchResult(
+ dispatchId: string,
+ result: { now?: Date; outcome: AgentCronJobRunResult; error?: unknown },
+ ): AgentCronJob | undefined {
+ let updated: AgentCronJob | undefined;
+ this.mutateStates((state) => {
+ const dispatch = state.dispatches.find((candidate) => candidate.id === dispatchId);
+ if (!dispatch) {
+ return [];
+ }
+ const now = result.now ?? new Date();
+ state.dispatches = state.dispatches.filter((candidate) => candidate.id !== dispatchId);
+ state.jobs = state.jobs.map((job) => {
+ if (job.id !== dispatch.jobId || job.status !== "active") {
+ return job;
+ }
+ if (result.outcome === "skipped" && result.error === undefined) {
+ const nextRunAt = nextRunAtForSchedule(job.schedule, now);
+ updated = {
+ ...job,
+ status: job.schedule.kind === "once" ? "completed" : job.status,
+ nextRunAt: nextRunAt?.toISOString(),
+ lastSkippedAt: now.toISOString(),
+ updatedAt: now.toISOString(),
+ };
+ return updated;
+ }
+ updated = {
+ ...job,
+ status: job.schedule.kind === "once" ? "completed" : job.status,
+ lastRunAt: now.toISOString(),
+ lastError: result.error === undefined ? undefined : errorMessage(result.error),
+ runCount: job.runCount + 1,
+ updatedAt: now.toISOString(),
+ };
+ return updated;
+ });
+ return [];
+ });
+ return updated;
+ }
+
+ recoverInterruptedDispatches(now = new Date()): AgentCronJob[] {
+ const recovered: AgentCronJob[] = [];
+ this.mutateStates((state) => {
+ recoverInterruptedInState(state, now, recovered);
+ return [];
+ });
+ return recovered;
+ }
+
getDueJob(id: string, now = new Date()): AgentCronJob | undefined {
return this.readJobs().find((job) => job.id === id && isDueJob(job, now));
}
@@ -576,29 +712,135 @@ export class AgentCronJobStore {
}
private readJobs(): AgentCronJob[] {
- if (!existsSync(this.filePath)) {
- return [];
- }
- const parsed = JSON.parse(readFileSync(this.filePath, "utf-8")) as CronJobsFile;
- if (!Array.isArray(parsed.jobs)) {
- return [];
+ return this.readStates().flatMap((state) => state.jobs);
+ }
+
+ private readStates(): CronJobsState[] {
+ if (this.sessionArtifactMode) {
+ return [...this.sessionArtifactFiles.values()].map((path) => readJobsState(path));
}
- return parsed.jobs.filter(isAgentCronJob);
+ return [readJobsState(this.requireFilePath())];
+ }
+
+ private mutateStates(mutator: (state: CronJobsState) => AgentCronDispatch[]): AgentCronDispatch[] {
+ const paths = this.sessionArtifactMode ? [...this.sessionArtifactFiles.values()] : [this.requireFilePath()];
+ return withCronJobsStateLocks(paths, () => {
+ const dispatches: AgentCronDispatch[] = [];
+ for (const path of paths) {
+ const state = readJobsState(path);
+ const before = JSON.stringify(state);
+ dispatches.push(...mutator(state));
+ if (JSON.stringify(state) !== before) {
+ writeJobsState(path, state);
+ }
+ }
+ return dispatches;
+ });
}
private writeJobs(jobs: readonly AgentCronJob[]): void {
- mkdirSync(dirname(this.filePath), { recursive: true });
- const mergedJobs = mergeFreshJobs(this.readJobs(), jobs);
- const tempPath = `${this.filePath}.tmp`;
- writeFileSync(tempPath, `${JSON.stringify({ jobs: mergedJobs }, null, 2)}\n`, "utf-8");
- renameSync(tempPath, this.filePath);
+ if (this.sessionArtifactMode) {
+ const registeredSessionIds = new Set(this.sessionArtifactFiles.keys());
+ const unregistered = jobs.find((job) => !registeredSessionIds.has(job.sessionId));
+ if (unregistered) {
+ throw new Error(`Cron job ${unregistered.id} targets an unregistered session artifact`);
+ }
+ const paths = [...this.sessionArtifactFiles.values()];
+ withCronJobsStateLocks(paths, () => {
+ const currentBySessionId = new Map(
+ [...this.sessionArtifactFiles].map(([sessionId, path]) => [sessionId, readJobsState(path)]),
+ );
+ const incomingById = new Map(jobs.map((job) => [job.id, job]));
+ const mergedJobsBySessionId = new Map<string, AgentCronJob[]>();
+ for (const [sessionId, current] of currentBySessionId) {
+ const retained = current.jobs.filter((job) => {
+ const incoming = incomingById.get(job.id);
+ return incoming === undefined || incoming.sessionId === sessionId;
+ });
+ mergedJobsBySessionId.set(
+ sessionId,
+ mergeFreshJobs(
+ retained,
+ jobs.filter((job) => job.sessionId === sessionId),
+ ),
+ );
+ }
+ const sessionIdByJobId = new Map(
+ [...mergedJobsBySessionId].flatMap(([sessionId, sessionJobs]) =>
+ sessionJobs.map((job) => [job.id, sessionId] as const),
+ ),
+ );
+ const dispatches = [...currentBySessionId.values()].flatMap((state) => state.dispatches);
+ for (const [sessionId, path] of this.sessionArtifactFiles) {
+ const current = currentBySessionId.get(sessionId) ?? { jobs: [], dispatches: [] };
+ const nextState = {
+ jobs: mergedJobsBySessionId.get(sessionId) ?? [],
+ dispatches: dispatches.filter((dispatch) => sessionIdByJobId.get(dispatch.jobId) === sessionId),
+ };
+ if (JSON.stringify(current) !== JSON.stringify(nextState)) {
+ writeJobsState(path, nextState);
+ }
+ }
+ });
+ return;
+ }
+ const path = this.requireFilePath();
+ withCronJobsStateLocks([path], () => writeJobsFile(path, jobs, true));
+ }
+
+ private requireFilePath(): string {
+ if (!this.filePath) {
+ throw new Error("Cron job store does not have a legacy file path");
+ }
+ return this.filePath;
}
}
+export function migrateLegacyCronJobsToSessionArtifacts(
+ filePath: string,
+ options: { isSessionOwned?: (job: AgentCronJob) => boolean; now?: Date } = {},
+): number {
+ const now = options.now ?? new Date();
+ const legacyState = readJobsState(filePath);
+ recoverInterruptedInState(legacyState, now, []);
+ const jobs = legacyState.jobs.map((job) => {
+ if (
+ !options.isSessionOwned ||
+ options.isSessionOwned(job) ||
+ (job.status !== "active" && job.status !== "paused")
+ ) {
+ return job;
+ }
+ return withoutNextRunAt({ ...job, status: "cancelled", updatedAt: now.toISOString() });
+ });
+ if (jobs.length === 0) {
+ return 0;
+ }
+ const jobsByArtifact = new Map<string, AgentCronJob[]>();
+ for (const job of jobs) {
+ const artifactPath = join(
+ dirname(dirname(resolve(job.sessionFile))),
+ "session-artifacts",
+ job.sessionId,
+ SESSION_SCHEDULED_JOBS_FILENAME,
+ );
+ const grouped = jobsByArtifact.get(artifactPath) ?? [];
+ grouped.push(job);
+ jobsByArtifact.set(artifactPath, grouped);
+ }
+ for (const [artifactPath, artifactJobs] of jobsByArtifact) {
+ writeJobsFile(artifactPath, artifactJobs, true);
+ }
+ renameSync(filePath, `${filePath}.migrated-${Date.now()}`);
+ return jobs.length;
+}
+
export class AgentCronScheduler {
private timer: ReturnType<typeof setTimeout> | undefined;
private running = false;
private stopped = true;
+ private hasStarted = false;
+ private readonly dispatchLanes = new Map<string, Promise<void>>();
constructor(
private readonly store: AgentCronJobStore,
@@ -607,6 +849,10 @@ export class AgentCronScheduler {
start(): void {
this.stopped = false;
+ if (!this.hasStarted) {
+ this.hasStarted = true;
+ this.store.recoverInterruptedDispatches(this.now());
+ }
this.scheduleNext();
}
@@ -630,12 +876,29 @@ export class AgentCronScheduler {
return 0;
}
this.running = true;
- let handled = 0;
+ let dispatches: AgentCronDispatch[] = [];
try {
- for (const dueJob of this.store.due(now)) {
- const job = this.store.getDueJob(dueJob.id, now);
+ dispatches = this.store.claimDue(now, this.now());
+ } finally {
+ this.running = false;
+ if (!this.stopped) {
+ this.scheduleNext();
+ }
+ }
+ const results = await Promise.all(dispatches.map((dispatch) => this.queueDispatch(dispatch)));
+ return results.filter((result) => result !== "skipped").length;
+ }
+
+ private queueDispatch(dispatch: AgentCronDispatch): Promise<AgentCronJobRunResult | undefined> {
+ const laneKey = dispatch.job.activeSessionId;
+ const previous = this.dispatchLanes.get(laneKey) ?? Promise.resolve();
+ const task = previous
+ .catch(() => undefined)
+ .then(async (): Promise<AgentCronJobRunResult | undefined> => {
+ const job = this.store.getClaimedJob(dispatch.job.id);
if (!job) {
- continue;
+ this.store.recordDispatchResult(dispatch.id, { now: this.now(), outcome: "skipped" });
+ return "skipped";
}
let runResult: AgentCronJobRunResult | undefined;
let error: unknown;
@@ -645,20 +908,24 @@ export class AgentCronScheduler {
error = runError;
this.hooks.onError?.(job, runError);
}
- if (runResult === "skipped" && error === undefined) {
- this.store.recordSkipResult(job.id, { now: this.now() });
- continue;
- }
- handled++;
- this.store.recordRunResult(job.id, { now: this.now(), error });
- }
- } finally {
- this.running = false;
- if (!this.stopped) {
- this.scheduleNext();
+ this.store.recordDispatchResult(dispatch.id, {
+ now: this.now(),
+ outcome: runResult === "skipped" && error === undefined ? "skipped" : "ran",
+ error,
+ });
+ return runResult;
+ });
+ const lane = task.then(
+ () => undefined,
+ () => undefined,
+ );
+ this.dispatchLanes.set(laneKey, lane);
+ void lane.finally(() => {
+ if (this.dispatchLanes.get(laneKey) === lane) {
+ this.dispatchLanes.delete(laneKey);
}
- }
- return handled;
+ });
+ return task;
}
private scheduleNext(delayMs?: number): void {
@@ -1131,6 +1398,132 @@ function isDueJob(job: AgentCronJob, now: Date): boolean {
return job.status === "active" && job.nextRunAt !== undefined && Date.parse(job.nextRunAt) <= now.getTime();
}
+function withCronJobsStateLocks<T>(paths: readonly string[], action: () => T): T {
+ const releases: Array<() => void> = [];
+ try {
+ for (const path of [...new Set(paths)].sort()) {
+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
+ let release: (() => void) | undefined;
+ for (let attempt = 0; attempt < 100; attempt++) {
+ try {
+ release = lockSync(path, {
+ realpath: false,
+ lockfilePath: `${path}.lock`,
+ stale: 30_000,
+ });
+ break;
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== "ELOCKED" || attempt === 99) {
+ throw error;
+ }
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 10);
+ }
+ }
+ if (!release) {
+ throw new Error(`Could not coordinate scheduled jobs: ${path}`);
+ }
+ releases.push(release);
+ }
+ return action();
+ } finally {
+ for (const release of releases.reverse()) {
+ release();
+ }
+ }
+}
+
+function readJobsState(path: string): CronJobsState {
+ if (!existsSync(path)) {
+ return { jobs: [], dispatches: [] };
+ }
+ const parsed = JSON.parse(readFileSync(path, "utf-8")) as CronJobsFile;
+ return {
+ jobs: Array.isArray(parsed.jobs) ? parsed.jobs.filter(isAgentCronJob) : [],
+ dispatches: Array.isArray(parsed.dispatches) ? parsed.dispatches.filter(isAgentCronDispatchRecord) : [],
+ };
+}
+
+function writeJobsFile(path: string, jobs: readonly AgentCronJob[], mergeCurrent: boolean): void {
+ const current = readJobsState(path);
+ writeJobsState(path, {
+ jobs: mergeCurrent ? mergeFreshJobs(current.jobs, jobs) : [...jobs],
+ dispatches: current.dispatches,
+ });
+}
+
+function writeJobsState(path: string, state: CronJobsState): void {
+ const directory = dirname(path);
+ mkdirSync(directory, { recursive: true, mode: 0o700 });
+ const tempPath = `${path}.${process.pid}.${randomUUID()}.tmp`;
+ const descriptor = openSync(tempPath, "w", 0o600);
+ try {
+ writeFileSync(descriptor, `${JSON.stringify(state, null, 2)}\n`, "utf-8");
+ fsyncSync(descriptor);
+ } finally {
+ closeSync(descriptor);
+ }
+ renameSync(tempPath, path);
+ try {
+ const directoryDescriptor = openSync(directory, "r");
+ try {
+ fsyncSync(directoryDescriptor);
+ } finally {
+ closeSync(directoryDescriptor);
+ }
+ } catch {
+ // Directory fsync is unavailable on some platforms; the atomic rename still protects readers.
+ }
+}
+
+function claimDueInState(state: CronJobsState, dueAt: Date, claimedAt: Date): AgentCronDispatch[] {
+ const dispatches: AgentCronDispatch[] = [];
+ const claimedJobIds = new Set(state.dispatches.map((dispatch) => dispatch.jobId));
+ state.jobs = state.jobs.map((job) => {
+ if (!isDueJob(job, dueAt)) {
+ return job;
+ }
+ const scheduledFor = job.nextRunAt!;
+ const nextRunAt = nextRunAtForSchedule(job.schedule, claimedAt)?.toISOString();
+ const advanced = nextRunAt
+ ? { ...job, nextRunAt, updatedAt: claimedAt.toISOString() }
+ : withoutNextRunAt({ ...job, updatedAt: claimedAt.toISOString() });
+ if (claimedJobIds.has(job.id)) {
+ return { ...advanced, lastSkippedAt: claimedAt.toISOString() };
+ }
+ const dispatch: AgentCronDispatchRecord = {
+ id: randomUUID(),
+ jobId: job.id,
+ claimedAt: claimedAt.toISOString(),
+ scheduledFor,
+ };
+ state.dispatches.push(dispatch);
+ dispatches.push({ id: dispatch.id, job: advanced });
+ return advanced;
+ });
+ return dispatches;
+}
+
+function recoverInterruptedInState(state: CronJobsState, now: Date, recovered: AgentCronJob[]): void {
+ if (state.dispatches.length === 0) {
+ return;
+ }
+ const interruptedIds = new Set(state.dispatches.map((dispatch) => dispatch.jobId));
+ state.dispatches = [];
+ state.jobs = state.jobs.map((job) => {
+ if (!interruptedIds.has(job.id) || job.status !== "active") {
+ return job;
+ }
+ const next = {
+ ...job,
+ status: job.schedule.kind === "once" ? ("completed" as const) : job.status,
+ lastError: "Interrupted before scheduled operation completion",
+ updatedAt: now.toISOString(),
+ };
+ recovered.push(next);
+ return next;
+ });
+}
+
function mergeFreshJobs(currentJobs: readonly AgentCronJob[], nextJobs: readonly AgentCronJob[]): AgentCronJob[] {
const merged = new Map<string, AgentCronJob>();
for (const job of currentJobs) {
@@ -1224,3 +1617,16 @@ function isAgentCronJob(value: unknown): value is AgentCronJob {
typeof candidate.runCount === "number"
);
}
+
+function isAgentCronDispatchRecord(value: unknown): value is AgentCronDispatchRecord {
+ if (!value || typeof value !== "object") {
+ return false;
+ }
+ const candidate = value as Partial<AgentCronDispatchRecord>;
+ return (
+ typeof candidate.id === "string" &&
+ typeof candidate.jobId === "string" &&
+ typeof candidate.claimedAt === "string" &&
+ typeof candidate.scheduledFor === "string"
+ );
+}
diff --git a/packages/coding-agent/src/core/orphan-process-journal.ts b/packages/coding-agent/src/core/orphan-process-journal.ts
new file mode 100644
index 0000000000..bb9c5e4a46
--- /dev/null
+++ b/packages/coding-agent/src/core/orphan-process-journal.ts
@@ -0,0 +1,92 @@
+import { closeSync, fsyncSync, openSync, readFileSync, rmSync, writeSync } from "node:fs";
+import { getProcessStartId } from "./session-lease.js";
+
+export const ORPHAN_PROCESS_JOURNAL_ENV = "PRIME_AGENT_INTERNAL_ORPHAN_PROCESS_JOURNAL";
+
+interface OrphanProcessRecord {
+ version: 1;
+ pid: number;
+ ownerPid: number;
+ processStartId?: string;
+ active: boolean;
+ recordedAt: string;
+}
+
+export interface ActiveOrphanProcess {
+ pid: number;
+ processStartId: string;
+}
+
+export function recordOrphanProcessState(pid: number, active: boolean): void {
+ const path = process.env[ORPHAN_PROCESS_JOURNAL_ENV];
+ if (!path || !Number.isInteger(pid) || pid <= 0) {
+ return;
+ }
+ const processStartId = active ? getProcessStartId(pid) : undefined;
+ const record: OrphanProcessRecord = {
+ version: 1,
+ pid,
+ ownerPid: process.pid,
+ ...(processStartId ? { processStartId } : {}),
+ active,
+ recordedAt: new Date().toISOString(),
+ };
+ try {
+ const descriptor = openSync(path, "a", 0o600);
+ try {
+ writeSync(descriptor, `${JSON.stringify(record)}\n`);
+ fsyncSync(descriptor);
+ } finally {
+ closeSync(descriptor);
+ }
+ } catch {
+ // Process tracking must not make a successfully spawned command fail.
+ }
+}
+
+export function readActiveOrphanProcesses(path: string, ownerPid: number): ActiveOrphanProcess[] {
+ let contents: string;
+ try {
+ contents = readFileSync(path, "utf8");
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") {
+ return [];
+ }
+ throw error;
+ }
+ const latest = new Map<number, OrphanProcessRecord>();
+ for (const line of contents.split("\n")) {
+ if (!line) {
+ continue;
+ }
+ try {
+ const record = JSON.parse(line) as Partial<OrphanProcessRecord>;
+ if (
+ record.version === 1 &&
+ Number.isInteger(record.pid) &&
+ (record.pid ?? 0) > 0 &&
+ record.ownerPid === ownerPid &&
+ typeof record.active === "boolean" &&
+ typeof record.recordedAt === "string"
+ ) {
+ latest.set(record.pid!, record as OrphanProcessRecord);
+ }
+ } catch {
+ // A crash can truncate only the final append.
+ }
+ }
+ return [...latest.values()]
+ .filter(
+ (record): record is OrphanProcessRecord & { processStartId: string } =>
+ record.active && typeof record.processStartId === "string",
+ )
+ .map((record) => ({ pid: record.pid, processStartId: record.processStartId }));
+}
+
+export function isOrphanProcessIdentityCurrent(orphan: ActiveOrphanProcess): boolean {
+ return getProcessStartId(orphan.pid) === orphan.processStartId;
+}
+
+export function clearOrphanProcessJournal(path: string): void {
+ rmSync(path, { force: true });
+}
diff --git a/packages/coding-agent/src/core/session-file-actions.ts b/packages/coding-agent/src/core/session-file-actions.ts
index 7bd537cb1f..adcec4c012 100644
--- a/packages/coding-agent/src/core/session-file-actions.ts
+++ b/packages/coding-agent/src/core/session-file-actions.ts
@@ -10,8 +10,9 @@ export interface DeleteSessionFileOptions {
}
/**
- * Permanently remove a session's artifact directory (kernel state snapshot, rlm
- * scratch files, …), which lives at `<dirname(sessionDir)>/session-artifacts/<id>`.
+ * Permanently remove a session's artifact directory (durable schedule state,
+ * kernel snapshot, RLM scratch files, …), which lives at
+ * `<dirname(sessionDir)>/session-artifacts/<id>`.
* Only invoked on delete, never on deactivation.
*/
async function deleteSessionArtifacts(sessionPath: string): Promise<void> {
@@ -56,7 +57,7 @@ async function removeSessionFile(sessionPath: string): Promise<DeleteSessionFile
/**
* Delete a session file, trying the `trash` CLI first, then falling back to unlink.
- * Also permanently removes the session's artifact directory (derived data), but only
+ * Also permanently removes the session's artifact directory, but only
* once the session file itself is gone — otherwise a failed delete would orphan a
* session whose kernel snapshot has already been destroyed.
*/
diff --git a/packages/coding-agent/src/core/session-lease.ts b/packages/coding-agent/src/core/session-lease.ts
new file mode 100644
index 0000000000..67ca5df058
--- /dev/null
+++ b/packages/coding-agent/src/core/session-lease.ts
@@ -0,0 +1,246 @@
+import { execFileSync } from "node:child_process";
+import { createHash, randomUUID } from "node:crypto";
+import { existsSync, mkdirSync, readFileSync, realpathSync, renameSync, rmSync, writeFileSync } from "node:fs";
+import { basename, dirname, join, resolve } from "node:path";
+import { lockSync } from "proper-lockfile";
+
+export const SESSION_LEASES_ENABLED_ENV = "PRIME_AGENT_INTERNAL_SESSION_LEASES";
+export const SESSION_LEASE_OWNER_ID_ENV = "PRIME_AGENT_INTERNAL_SESSION_LEASE_OWNER_ID";
+
+interface SessionLeaseOwner {
+ version: 1;
+ token: string;
+ pid: number;
+ processStartId?: string;
+ activeSessionId?: string;
+ sessionPath: string;
+ createdAt: string;
+}
+
+export class SessionAlreadyActiveError extends Error {
+ readonly code = "session_already_active" as const;
+
+ constructor(
+ readonly sessionPath: string,
+ readonly activeSessionId?: string,
+ ) {
+ super(
+ activeSessionId
+ ? `Session is already active in ${activeSessionId}: ${sessionPath}`
+ : `Session is already active in another process: ${sessionPath}`,
+ );
+ this.name = "SessionAlreadyActiveError";
+ }
+}
+
+export class SessionLease {
+ private released = false;
+
+ constructor(
+ readonly sessionPath: string,
+ private readonly directory: string,
+ private readonly token: string,
+ ) {}
+
+ release(): void {
+ if (this.released) {
+ return;
+ }
+ this.released = true;
+ try {
+ withLeaseGuard(this.directory, () => {
+ const owner = readLeaseOwner(this.directory);
+ if (owner?.token === this.token) {
+ rmSync(this.directory, { recursive: true, force: true });
+ }
+ });
+ } catch {
+ // Lease cleanup is best-effort. A stale owner is reclaimed by the next process.
+ }
+ }
+}
+
+function leasesEnabled(environment: NodeJS.ProcessEnv): boolean {
+ const value = environment[SESSION_LEASES_ENABLED_ENV]?.toLowerCase();
+ return value === "1" || value === "true" || value === "yes";
+}
+
+function leaseDirectory(agentDir: string, sessionPath: string): string {
+ const key = createHash("sha256").update(sessionPath).digest("hex");
+ return join(agentDir, "session-leases", `${key}.lock`);
+}
+
+export function canonicalSessionPath(sessionPath: string): string {
+ const resolvedPath = resolve(sessionPath);
+ try {
+ return realpathSync(resolvedPath);
+ } catch {
+ try {
+ return join(realpathSync(dirname(resolvedPath)), basename(resolvedPath));
+ } catch {
+ return resolvedPath;
+ }
+ }
+}
+
+function readLeaseOwner(directory: string): SessionLeaseOwner | undefined {
+ try {
+ const parsed = JSON.parse(readFileSync(join(directory, "owner.json"), "utf8")) as Partial<SessionLeaseOwner>;
+ if (
+ parsed.version !== 1 ||
+ typeof parsed.token !== "string" ||
+ typeof parsed.pid !== "number" ||
+ typeof parsed.sessionPath !== "string" ||
+ typeof parsed.createdAt !== "string"
+ ) {
+ return undefined;
+ }
+ return parsed as SessionLeaseOwner;
+ } catch {
+ return undefined;
+ }
+}
+
+function isProcessAlive(pid: number): boolean {
+ try {
+ process.kill(pid, 0);
+ return true;
+ } catch (error) {
+ return (error as NodeJS.ErrnoException).code === "EPERM";
+ }
+}
+
+export function getProcessStartId(pid: number): string | undefined {
+ try {
+ const stat = readFileSync(`/proc/${pid}/stat`, "utf8");
+ const commandEnd = stat.lastIndexOf(")");
+ const fields = stat.slice(commandEnd + 2).split(" ");
+ const startTime = fields[19];
+ if (startTime) {
+ return `proc:${startTime}`;
+ }
+ } catch {
+ // Fall through to the portable process listing used on macOS and BSD.
+ }
+ try {
+ const startTime = execFileSync("ps", ["-p", String(pid), "-o", "lstart="], {
+ encoding: "utf8",
+ stdio: ["ignore", "pipe", "ignore"],
+ }).trim();
+ return startTime ? `ps:${startTime}` : undefined;
+ } catch {
+ return undefined;
+ }
+}
+
+const CURRENT_PROCESS_START_ID = getProcessStartId(process.pid);
+
+function isLeaseOwnerAlive(owner: SessionLeaseOwner): boolean {
+ if (!isProcessAlive(owner.pid)) {
+ return false;
+ }
+ if (!owner.processStartId) {
+ return true;
+ }
+ const currentStartId = getProcessStartId(owner.pid);
+ return currentStartId === undefined || currentStartId === owner.processStartId;
+}
+
+function withLeaseGuard<T>(directory: string, action: () => T): T {
+ let release: (() => void) | undefined;
+ for (let attempt = 0; attempt < 100; attempt++) {
+ try {
+ release = lockSync(directory, {
+ realpath: false,
+ lockfilePath: `${directory}.guard`,
+ stale: 5000,
+ });
+ break;
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== "ELOCKED") {
+ throw error;
+ }
+ if (attempt === 99) {
+ throw new Error(`Could not coordinate session lease: ${directory}`);
+ }
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 10);
+ }
+ }
+ if (!release) {
+ throw new Error(`Could not coordinate session lease: ${directory}`);
+ }
+ try {
+ return action();
+ } finally {
+ release();
+ }
+}
+
+function reclaimStaleLease(directory: string): boolean {
+ const stalePath = `${directory}.stale-${process.pid}-${randomUUID()}`;
+ try {
+ renameSync(directory, stalePath);
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") {
+ return true;
+ }
+ return false;
+ }
+ rmSync(stalePath, { recursive: true, force: true });
+ return true;
+}
+
+export function acquireSessionLease(
+ sessionPath: string | undefined,
+ agentDir: string,
+ environment: NodeJS.ProcessEnv = process.env,
+): SessionLease | undefined {
+ if (!sessionPath || !leasesEnabled(environment)) {
+ return undefined;
+ }
+ const canonicalPath = canonicalSessionPath(sessionPath);
+ const root = join(agentDir, "session-leases");
+ mkdirSync(root, { recursive: true, mode: 0o700 });
+ const directory = leaseDirectory(agentDir, canonicalPath);
+
+ return withLeaseGuard(directory, () => {
+ for (let attempt = 0; attempt < 3; attempt++) {
+ const token = randomUUID();
+ const candidateDirectory = `${directory}.candidate-${process.pid}-${token}`;
+ const owner: SessionLeaseOwner = {
+ version: 1,
+ token,
+ pid: process.pid,
+ processStartId: CURRENT_PROCESS_START_ID,
+ activeSessionId: environment[SESSION_LEASE_OWNER_ID_ENV],
+ sessionPath: canonicalPath,
+ createdAt: new Date().toISOString(),
+ };
+ mkdirSync(candidateDirectory, { mode: 0o700 });
+ writeFileSync(join(candidateDirectory, "owner.json"), `${JSON.stringify(owner, null, 2)}\n`, {
+ mode: 0o600,
+ });
+ try {
+ renameSync(candidateDirectory, directory);
+ return new SessionLease(canonicalPath, directory, token);
+ } catch (error) {
+ rmSync(candidateDirectory, { recursive: true, force: true });
+ const code = (error as NodeJS.ErrnoException).code;
+ if (code !== "EEXIST" && code !== "ENOTEMPTY") {
+ throw error;
+ }
+ const existingOwner = readLeaseOwner(directory);
+ if (existingOwner && isLeaseOwnerAlive(existingOwner)) {
+ throw new SessionAlreadyActiveError(canonicalPath, existingOwner.activeSessionId);
+ }
+ reclaimStaleLease(directory);
+ }
+ }
+
+ const owner = existsSync(directory) ? readLeaseOwner(directory) : undefined;
+ if (owner && isLeaseOwnerAlive(owner)) {
+ throw new SessionAlreadyActiveError(canonicalPath, owner.activeSessionId);
+ }
+ throw new Error(`Could not acquire session lease: ${canonicalPath}`);
+ });
+}
diff --git a/packages/coding-agent/src/main.ts b/packages/coding-agent/src/main.ts
index b4bcec74f1..3b359fa36c 100644
--- a/packages/coding-agent/src/main.ts
+++ b/packages/coding-agent/src/main.ts
@@ -25,6 +25,7 @@ import { confirmDaemonSessionLoss, type DaemonSessionLossCopy, pluralizeSessions
import { processFileArguments } from "./cli/file-processor.js";
import { buildInitialMessage } from "./cli/initial-message.js";
import { listModels } from "./cli/list-models.js";
+import { installOwnedSessionRecoveryTracking } from "./cli/owned-session-worker.js";
import { selectSession } from "./cli/session-picker.js";
import { expandTildePath, getAgentDir, getSessionDirEnvOverride, VERSION } from "./config.js";
import {
@@ -32,7 +33,11 @@ import {
mergeAgentSessionRuntimeConfig,
mergeAutonomousConfig,
} from "./core/agent-session-config.js";
-import { type CreateAgentSessionRuntimeFactory, createAgentSessionRuntime } from "./core/agent-session-runtime.js";
+import {
+ type AgentSessionRuntime,
+ type CreateAgentSessionRuntimeFactory,
+ createAgentSessionRuntime,
+} from "./core/agent-session-runtime.js";
import {
type AgentSessionRuntimeDiagnostic,
type AgentSessionServices,
@@ -55,11 +60,18 @@ import {
MissingSessionCwdError,
type SessionCwdIssue,
} from "./core/session-cwd.js";
+import { SessionAlreadyActiveError } from "./core/session-lease.js";
import { SessionManager } from "./core/session-manager.js";
import { SettingsManager } from "./core/settings-manager.js";
import { printTimings, resetTimings, time } from "./core/timings.js";
import { runMigrations, showDeprecationWarnings } from "./migrations.js";
+import { isDaemonCatalogProcess, runDaemonCatalogProcess } from "./modes/daemon/daemon-catalog-process.js";
import { collectDaemonClientEnv } from "./modes/daemon/daemon-protocol.js";
+import {
+ DAEMON_WORKER_ACTIVE_SESSION_ID_ENV,
+ isDaemonWorkerProcess,
+ requireDaemonWorkerAuthenticationToken,
+} from "./modes/daemon/daemon-worker-protocol.js";
import {
type AgentConnection,
createInteractiveModeLocalSessionHost,
@@ -72,6 +84,7 @@ import {
resolveAttachModelFallbackMessage,
runAgentsViewMode,
runDaemonMode,
+ runDaemonSupervisorMode,
runPrintMode,
runRpcMode,
type SessionSummary,
@@ -1017,6 +1030,7 @@ async function createDaemonInteractiveConnection(options: {
const connection = await DaemonAgentConnection.attach(client, getDaemonSummaryActiveSessionId(summary), {
closeClientOnDispose: true,
sendClientEnv: true,
+ recoverDaemon: () => ensureInteractiveDaemonRunning(options.socketPath),
});
return { connection, summary };
};
@@ -1078,6 +1092,10 @@ export interface MainOptions {
export async function main(args: string[], options?: MainOptions) {
resetTimings();
installFileLogSink();
+ if (isDaemonCatalogProcess()) {
+ await runDaemonCatalogProcess();
+ return;
+ }
// Client and daemon are separate processes; both need these in their registry.
registerBuiltinMcpOAuthProviders();
args = normalizeDaemonStartArgs(args) ?? args;
@@ -1293,11 +1311,22 @@ export async function main(args: string[], options?: MainOptions) {
// --help/--list-models still take the full path to print and exit.
if (appMode === "daemon" && !parsed.help && parsed.listModels === undefined) {
printTimings();
- await runDaemonMode({
- socketPath: parsed.daemonSocket,
- defaultSessionConfig,
- createRuntime,
- });
+ if (isDaemonWorkerProcess()) {
+ await runDaemonMode({
+ socketPath: parsed.daemonSocket,
+ defaultSessionConfig,
+ createRuntime,
+ worker: {
+ authenticationToken: requireDaemonWorkerAuthenticationToken(),
+ restoreActiveSessionId: process.env[DAEMON_WORKER_ACTIVE_SESSION_ID_ENV],
+ },
+ });
+ } else {
+ await runDaemonSupervisorMode({
+ socketPath: parsed.daemonSocket,
+ defaultSessionConfig,
+ });
+ }
return;
}
if (useDaemonInteractive) {
@@ -1355,6 +1384,7 @@ export async function main(args: string[], options?: MainOptions) {
socketPath: daemonSocketPath,
config: defaultSessionConfig,
uiServices: daemonUiServices,
+ recoverDaemon: () => ensureInteractiveDaemonRunning(daemonSocketPath),
createUiServicesForSession: async (summary) => {
const attachedSessionManager = createSessionManagerForActiveDaemonSummary(
summary,
@@ -1445,13 +1475,23 @@ export async function main(args: string[], options?: MainOptions) {
return;
}
- const runtime = await createAgentSessionRuntime(createRuntime, {
- cwd: sessionManager.getCwd(),
- agentDir,
- sessionManager,
- sessionConfig: defaultSessionConfig,
- });
+ let runtime: AgentSessionRuntime;
+ try {
+ runtime = await createAgentSessionRuntime(createRuntime, {
+ cwd: sessionManager.getCwd(),
+ agentDir,
+ sessionManager,
+ sessionConfig: defaultSessionConfig,
+ });
+ } catch (error) {
+ if (error instanceof SessionAlreadyActiveError) {
+ console.error(chalk.red(`Error: ${error.message}`));
+ process.exit(1);
+ }
+ throw error;
+ }
const { services, session, modelFallbackMessage } = runtime;
+ installOwnedSessionRecoveryTracking(runtime);
const { settingsManager, modelRegistry, resourceLoader } = services;
if (parsed.help) {
diff --git a/packages/coding-agent/src/modes/agent-connection/daemon-agent-connection.ts b/packages/coding-agent/src/modes/agent-connection/daemon-agent-connection.ts
index 3158a314e7..202e0546e4 100644
--- a/packages/coding-agent/src/modes/agent-connection/daemon-agent-connection.ts
+++ b/packages/coding-agent/src/modes/agent-connection/daemon-agent-connection.ts
@@ -2,6 +2,7 @@ import { randomUUID } from "node:crypto";
import type { AgentMessage, ThinkingLevel } from "@earendil-works/pi-agent-core";
import type { ImageContent, Transport } from "@earendil-works/pi-ai";
import { getAgentLogPath, getDaemonLogPath } from "../../config.js";
+import type { AgentSessionEvent } from "../../core/agent-session.js";
import type { CompactionResult } from "../../core/compaction/index.js";
import type { ContextTreeNode } from "../../core/context-tree.js";
import type { AgentCronJob, AgentHeartbeatDeliveryMode, AgentHeartbeatUpdateAction } from "../../core/cron-jobs.js";
@@ -14,6 +15,7 @@ import {
collectDaemonClientEnv,
type DaemonAttachResult,
type DaemonCommand,
+ type DaemonEventCursor,
type DaemonOutbound,
type DaemonReplayInfo,
type DaemonSessionClosedReason,
@@ -61,8 +63,21 @@ import type {
type DistributiveOmit<T, K extends keyof T> = T extends unknown ? Omit<T, K> : never;
type DaemonCommandBody = DistributiveOmit<DaemonCommand, "id">;
+type DaemonSnapshotBegin = Extract<DaemonOutbound, { type: "session_snapshot_begin" }>;
+
+interface DaemonSnapshotAssembly {
+ begin?: DaemonSnapshotBegin;
+ chunks: Map<number, AgentMessage[]>;
+ promise: Promise<DaemonSessionSnapshot>;
+ resolve: (snapshot: DaemonSessionSnapshot) => void;
+ reject: (error: Error) => void;
+ timeout: ReturnType<typeof setTimeout>;
+}
export const DAEMON_REFINE_REQUEST_TIMEOUT_MS = 10 * 60 * 1000;
+export const DAEMON_RECONNECT_TIMEOUT_MS = 60_000;
+export const DAEMON_SNAPSHOT_TIMEOUT_MS = 30_000;
+const MAX_IGNORED_SNAPSHOT_IDS = 128;
const UPDATE_RECONNECT_TIMEOUT_MS = 120000;
const UPDATE_RECONNECT_RETRY_MS = 100;
const updateTransportReconnects = new WeakMap<DaemonClient, Promise<void>>();
@@ -111,6 +126,12 @@ function reconnectDaemonTransportAfterUpdate(client: DaemonClient): Promise<void
export interface DaemonAgentConnectionOptions {
closeClientOnDispose?: boolean;
+ /** Restart/probe the detached supervisor after a transient socket loss. */
+ recoverDaemon?: () => Promise<void>;
+ /** Bound supervisor recovery before surfacing a fatal connection error. */
+ reconnectTimeoutMs?: number;
+ /** Bound an incomplete streamed snapshot before failing the attach or resync. */
+ snapshotTimeoutMs?: number;
/**
* Send this client's allowlisted env (herdr pane identity) with attach so
* an env-less session (e.g. cron-created) adopts it. Set only by the
@@ -131,6 +152,8 @@ export class DaemonAgentConnection implements AgentConnection {
private readonly unsubscribeDaemonMessages: () => void;
private readonly unsubscribeDaemonClose: () => void;
private readonly clientId = `daemon-agent-connection:${randomUUID()}`;
+ private lastEventCursor: DaemonEventCursor | undefined;
+ private readonly retiredEventGenerations = new Set<string>();
private lastEventSequence: number | undefined;
private latestSnapshot: AgentConnectionSnapshot | undefined;
private latestSnapshotIsFresh = false;
@@ -141,19 +164,26 @@ export class DaemonAgentConnection implements AgentConnection {
private updateReconnectFailed = false;
private terminalCloseEmitted = false;
private updateReconnectPromise?: Promise<void>;
- private disposed = false;
private readonly activeSideQuestionIds = new Set<string>();
+ private readonly snapshotAssemblies = new Map<string, DaemonSnapshotAssembly>();
+ private readonly ignoredSnapshotIds = new Set<string>();
+ private reconnectPromise?: Promise<void>;
+ private disposed = false;
constructor(
private readonly client: DaemonClient,
private activeSessionId: string,
private readonly options: DaemonAgentConnectionOptions = {},
) {
+ if (options.recoverDaemon) {
+ this.client.enableRequestRecovery();
+ }
this.unsubscribeDaemonMessages = this.client.onMessage((message) => {
void this.handleDaemonMessage(message);
});
this.captureDaemonLogPath();
this.unsubscribeDaemonClose = this.client.onClose((error) => {
+ this.rejectSnapshotAssemblies(error);
if (this.disposed || this.terminalCloseEmitted) {
return;
}
@@ -168,6 +198,10 @@ export class DaemonAgentConnection implements AgentConnection {
void this.reconnectAfterUpdate();
return;
}
+ if (this.options.recoverDaemon) {
+ void this.reconnect(error);
+ return;
+ }
this.terminalCloseEmitted = true;
void this.emit({ type: "closed", error: this.formatDaemonConnectionClosedError(error) });
});
@@ -194,14 +228,14 @@ export class DaemonAgentConnection implements AgentConnection {
activeSessionId: this.activeSessionId,
supportsExtensionUi: true,
clientId: this.clientId,
- capabilities: ["attach_snapshot", "event_sequence", "extension_ui", "slim_attach"],
+ capabilities: ["attach_snapshot", "event_sequence", "extension_ui", "slim_attach", "chunked_snapshot"],
env: this.options.sendClientEnv ? collectDaemonClientEnv() : undefined,
resumeCursor:
- this.lastEventSequence === undefined
+ this.lastEventCursor === undefined
? undefined
: {
activeSessionId: this.activeSessionId,
- eventSequence: this.lastEventSequence,
+ ...this.lastEventCursor,
},
});
this.activeSessionId = getAttachActiveSessionId(result);
@@ -212,12 +246,22 @@ export class DaemonAgentConnection implements AgentConnection {
this.captureDaemonLogPath();
this.updateReconnectFailed = false;
this.terminalCloseEmitted = false;
+ const attachCursor = getAttachLastEventCursor(result);
+ if (attachCursor) {
+ this.observeEventCursor(attachCursor);
+ }
this.lastEventSequence = maxEventSequence(this.lastEventSequence, getAttachLastEventSequence(result));
if ("snapshot" in result) {
- this.latestSnapshot = mapDaemonAttachSnapshot(result);
+ const snapshot = result.snapshotStream
+ ? await this.waitForSnapshot(result.snapshotStream.id)
+ : result.snapshot;
+ this.latestSnapshot = mapDaemonSessionSnapshot(snapshot, result.replay);
if (this.lastEventSequence !== undefined) {
this.latestSnapshot.lastEventSequence = this.lastEventSequence;
}
+ if (this.lastEventCursor) {
+ this.latestSnapshot.lastEventCursor = this.lastEventCursor;
+ }
this.latestSnapshotIsFresh = true;
} else {
this.latestSnapshot = undefined;
@@ -253,6 +297,8 @@ export class DaemonAgentConnection implements AgentConnection {
// The session tree is intentionally not fetched here: it is large on long
// sessions and only needed when the user opens the tree/branch selector.
// getSessionTree() fetches it lazily via get_session_tree on first use.
+ const snapshotCursor = this.lastEventCursor;
+ const snapshotSequence = this.lastEventSequence;
const [state, messagesData, sessionContextData] = await Promise.all([
this.requestData<AgentConnectionState>({
type: "get_connection_state",
@@ -272,16 +318,24 @@ export class DaemonAgentConnection implements AgentConnection {
// roster is still the best seed available (live rlm_child_update events
// overwrite each entry anyway).
const children = this.latestSnapshot?.children;
+ const streamingMessage = this.latestSnapshot?.streamingMessage;
this.latestSnapshot = {
state,
messages: messagesData.messages,
sessionContext: sessionContextData.context,
...(children ? { children } : {}),
+ ...(streamingMessage ? { streamingMessage } : {}),
};
- if (this.lastEventSequence !== undefined) {
- this.latestSnapshot.lastEventSequence = this.lastEventSequence;
+ if (snapshotSequence !== undefined) {
+ this.latestSnapshot.lastEventSequence = snapshotSequence;
}
- this.latestSnapshotIsFresh = true;
+ if (snapshotCursor) {
+ this.latestSnapshot.lastEventCursor = snapshotCursor;
+ }
+ this.latestSnapshotIsFresh =
+ snapshotSequence === this.lastEventSequence &&
+ snapshotCursor?.generation === this.lastEventCursor?.generation &&
+ snapshotCursor?.sequence === this.lastEventCursor?.sequence;
return this.latestSnapshot;
}
@@ -805,6 +859,56 @@ export class DaemonAgentConnection implements AgentConnection {
if (this.options.closeClientOnDispose) {
this.client.close();
}
+ this.rejectSnapshotAssemblies(new Error("Daemon connection disposed during snapshot transfer"));
+ }
+
+ private async reconnect(cause: Error): Promise<void> {
+ if (this.reconnectPromise) {
+ return this.reconnectPromise;
+ }
+ this.reconnectPromise = (async () => {
+ await this.emit({ type: "connection_status", status: "reconnecting", error: cause.message });
+ const deadline = Date.now() + (this.options.reconnectTimeoutMs ?? DAEMON_RECONNECT_TIMEOUT_MS);
+ let attempt = 0;
+ let lastError: Error = cause;
+ while (!this.disposed && Date.now() < deadline) {
+ try {
+ await this.options.recoverDaemon?.();
+ if (this.disposed) {
+ return;
+ }
+ await this.client.connect(1000);
+ await this.client.waitForHello(3000);
+ await this.attach();
+ if (!this.disposed) {
+ const snapshot = await this.getInitialSnapshot();
+ await this.emit({ type: "session_resynced", snapshot });
+ await this.emit({ type: "connection_status", status: "connected" });
+ }
+ return;
+ } catch (error) {
+ lastError = error instanceof Error ? error : new Error(String(error));
+ if (this.disposed) {
+ return;
+ }
+ this.client.resetTransportForReconnect();
+ const remainingMs = deadline - Date.now();
+ if (remainingMs <= 0) {
+ break;
+ }
+ const delayMs = Math.min(remainingMs, 2000, 100 * 2 ** Math.min(attempt, 5));
+ attempt++;
+ await new Promise((resolveDelay) => setTimeout(resolveDelay, delayMs));
+ }
+ }
+ if (!this.disposed) {
+ this.client.close();
+ await this.emit({ type: "closed", error: `Daemon reconnection failed: ${lastError.message}` });
+ }
+ })().finally(() => {
+ this.reconnectPromise = undefined;
+ });
+ return this.reconnectPromise;
}
private async requestOk(command: DaemonCommandBody): Promise<void> {
@@ -826,12 +930,32 @@ export class DaemonAgentConnection implements AgentConnection {
if (!this.isMessageForActiveSession(message)) {
return;
}
+ if ("snapshotId" in message && this.ignoredSnapshotIds.has(message.snapshotId)) {
+ if (message.type === "session_snapshot_end") {
+ this.ignoredSnapshotIds.delete(message.snapshotId);
+ }
+ return;
+ }
+ if (message.type === "session_snapshot_begin") {
+ const assembly = this.getSnapshotAssembly(message.snapshotId);
+ assembly.begin = message;
+ return;
+ }
+ if (message.type === "session_snapshot_chunk") {
+ this.getSnapshotAssembly(message.snapshotId).chunks.set(message.index, message.messages);
+ return;
+ }
+ if (message.type === "session_snapshot_end") {
+ await this.completeSnapshotAssembly(message);
+ return;
+ }
if (this.isStaleSequencedMessage(message)) {
return;
}
this.observeDaemonEventSequence(message);
if (message.type === "session_event") {
+ this.observeStreamingMessage(message.event);
this.latestSnapshotIsFresh = false;
await this.emit({ type: "session_event", event: message.event });
return;
@@ -852,9 +976,27 @@ export class DaemonAgentConnection implements AgentConnection {
await this.emit({ type: "session_status", recap: message.recap });
return;
}
+ if (message.type === "session_resynced") {
+ this.attachedSessionId = message.snapshot.state.sessionId;
+ this.attachedSessionFile = message.snapshot.state.sessionFile;
+ this.latestSnapshot = mapDaemonSessionSnapshot(message.snapshot);
+ if (this.lastEventSequence !== undefined) {
+ this.latestSnapshot.lastEventSequence = this.lastEventSequence;
+ }
+ if (this.lastEventCursor) {
+ this.latestSnapshot.lastEventCursor = this.lastEventCursor;
+ }
+ this.latestSnapshotIsFresh = true;
+ await this.emit({ type: "session_resynced", snapshot: this.latestSnapshot });
+ return;
+ }
if (message.type === "session_replaced") {
this.attachedSessionId = message.state.sessionId;
this.attachedSessionFile = message.state.sessionFile;
+ if (message.snapshotFollows) {
+ this.latestSnapshotIsFresh = false;
+ return;
+ }
const latestSnapshot: AgentConnectionSnapshot = {
state: message.state,
messages: message.messages,
@@ -862,6 +1004,9 @@ export class DaemonAgentConnection implements AgentConnection {
if (this.lastEventSequence !== undefined) {
latestSnapshot.lastEventSequence = this.lastEventSequence;
}
+ if (this.lastEventCursor) {
+ latestSnapshot.lastEventCursor = this.lastEventCursor;
+ }
this.latestSnapshot = latestSnapshot;
this.latestSnapshotIsFresh = true;
await this.emit({ type: "session_replaced", state: message.state, messages: message.messages });
@@ -993,6 +1138,8 @@ export class DaemonAgentConnection implements AgentConnection {
}
this.activeSessionId = restored.activeSessionId;
this.lastEventSequence = undefined;
+ this.lastEventCursor = undefined;
+ this.retiredEventGenerations.clear();
await this.attach();
if (this.disposed) {
return;
@@ -1002,7 +1149,7 @@ export class DaemonAgentConnection implements AgentConnection {
return;
}
this.updateRestartPending = false;
- await this.emit({ type: "session_replaced", state: snapshot.state, messages: snapshot.messages });
+ await this.emit({ type: "session_resynced", snapshot });
return;
}
} catch (error) {
@@ -1016,6 +1163,162 @@ export class DaemonAgentConnection implements AgentConnection {
throw lastError ?? new Error("the restored session did not become available");
}
+ private getSnapshotAssembly(snapshotId: string): DaemonSnapshotAssembly {
+ const existing = this.snapshotAssemblies.get(snapshotId);
+ if (existing) {
+ return existing;
+ }
+ let resolveSnapshot!: (snapshot: DaemonSessionSnapshot) => void;
+ let rejectSnapshot!: (error: Error) => void;
+ const promise = new Promise<DaemonSessionSnapshot>((resolve, reject) => {
+ resolveSnapshot = resolve;
+ rejectSnapshot = reject;
+ });
+ void promise.catch(() => undefined);
+ const timeout = setTimeout(() => {
+ const current = this.snapshotAssemblies.get(snapshotId);
+ if (current) {
+ current.reject(new Error(`Timed out waiting for snapshot ${snapshotId}`));
+ this.snapshotAssemblies.delete(snapshotId);
+ this.ignoreSnapshotId(snapshotId);
+ }
+ }, this.options.snapshotTimeoutMs ?? DAEMON_SNAPSHOT_TIMEOUT_MS);
+ timeout.unref();
+ const assembly: DaemonSnapshotAssembly = {
+ chunks: new Map(),
+ promise,
+ resolve: resolveSnapshot,
+ reject: rejectSnapshot,
+ timeout,
+ };
+ this.snapshotAssemblies.set(snapshotId, assembly);
+ return assembly;
+ }
+
+ private rejectSnapshotAssemblies(error: Error): void {
+ for (const assembly of this.snapshotAssemblies.values()) {
+ clearTimeout(assembly.timeout);
+ assembly.reject(error);
+ }
+ this.snapshotAssemblies.clear();
+ this.ignoredSnapshotIds.clear();
+ }
+
+ private ignoreSnapshotId(snapshotId: string): void {
+ this.ignoredSnapshotIds.add(snapshotId);
+ while (this.ignoredSnapshotIds.size > MAX_IGNORED_SNAPSHOT_IDS) {
+ const oldest = this.ignoredSnapshotIds.values().next().value;
+ if (oldest === undefined) {
+ break;
+ }
+ this.ignoredSnapshotIds.delete(oldest);
+ }
+ }
+
+ private rejectSnapshotAssembly(snapshotId: string, assembly: DaemonSnapshotAssembly, error: Error): void {
+ assembly.reject(error);
+ clearTimeout(assembly.timeout);
+ if (assembly.begin?.purpose && assembly.begin.purpose !== "attach") {
+ this.snapshotAssemblies.delete(snapshotId);
+ }
+ }
+
+ private async waitForSnapshot(snapshotId: string): Promise<DaemonSessionSnapshot> {
+ const assembly = this.getSnapshotAssembly(snapshotId);
+ try {
+ return await assembly.promise;
+ } finally {
+ clearTimeout(assembly.timeout);
+ this.snapshotAssemblies.delete(snapshotId);
+ }
+ }
+
+ private async completeSnapshotAssembly(
+ message: Extract<DaemonOutbound, { type: "session_snapshot_end" }>,
+ ): Promise<void> {
+ const assembly = this.getSnapshotAssembly(message.snapshotId);
+ if (!assembly.begin) {
+ this.rejectSnapshotAssembly(
+ message.snapshotId,
+ assembly,
+ new Error(`Snapshot ${message.snapshotId} ended before it began`),
+ );
+ return;
+ }
+ if (assembly.chunks.size !== message.chunkCount) {
+ this.rejectSnapshotAssembly(
+ message.snapshotId,
+ assembly,
+ new Error(
+ `Snapshot ${message.snapshotId} ended with ${assembly.chunks.size} of ${message.chunkCount} chunks`,
+ ),
+ );
+ return;
+ }
+ const messages: AgentMessage[] = [];
+ for (let index = 0; index < message.chunkCount; index++) {
+ const chunk = assembly.chunks.get(index);
+ if (!chunk) {
+ this.rejectSnapshotAssembly(
+ message.snapshotId,
+ assembly,
+ new Error(`Snapshot ${message.snapshotId} is missing chunk ${index}`),
+ );
+ return;
+ }
+ messages.push(...chunk);
+ }
+ if (messages.length !== assembly.begin.messageCount) {
+ this.rejectSnapshotAssembly(
+ message.snapshotId,
+ assembly,
+ new Error(
+ `Snapshot ${message.snapshotId} contained ${messages.length} of ${assembly.begin.messageCount} messages`,
+ ),
+ );
+ return;
+ }
+ const snapshot: DaemonSessionSnapshot = {
+ ...assembly.begin.snapshot,
+ messages,
+ lastEventSequence: message.lastEventSequence,
+ lastEventCursor: message.lastEventCursor,
+ };
+ if (message.lastEventCursor) {
+ this.observeEventCursor(message.lastEventCursor);
+ }
+ this.lastEventSequence = maxEventSequence(this.lastEventSequence, message.lastEventSequence);
+ this.attachedSessionId = snapshot.state.sessionId;
+ this.attachedSessionFile = snapshot.state.sessionFile;
+ this.latestSnapshot = mapDaemonSessionSnapshot(snapshot);
+ this.latestSnapshotIsFresh = true;
+ assembly.resolve(snapshot);
+ const purpose = assembly.begin.purpose ?? "attach";
+ clearTimeout(assembly.timeout);
+ if (purpose !== "attach") {
+ this.snapshotAssemblies.delete(message.snapshotId);
+ }
+ if (purpose === "replacement") {
+ await this.emit({ type: "session_replaced", state: snapshot.state, messages });
+ } else if (purpose === "resync") {
+ await this.emit({ type: "session_resynced", snapshot: this.latestSnapshot });
+ }
+ }
+
+ private observeStreamingMessage(event: AgentSessionEvent): void {
+ if (!this.latestSnapshot) {
+ return;
+ }
+ if ((event.type === "message_start" || event.type === "message_update") && event.message.role === "assistant") {
+ this.latestSnapshot = { ...this.latestSnapshot, streamingMessage: event.message };
+ return;
+ }
+ if ((event.type === "message_end" && event.message.role === "assistant") || event.type === "agent_end") {
+ const { streamingMessage: _streamingMessage, ...snapshot } = this.latestSnapshot;
+ this.latestSnapshot = snapshot;
+ }
+ }
+
private isMessageForActiveSession(message: DaemonOutbound): boolean {
if (!("activeSessionId" in message)) {
return false;
@@ -1024,22 +1327,57 @@ export class DaemonAgentConnection implements AgentConnection {
}
private isStaleSequencedMessage(message: DaemonOutbound): boolean {
+ const cursor = getDaemonMessageCursor(message);
+ if (cursor) {
+ if (this.retiredEventGenerations.has(cursor.generation)) {
+ return true;
+ }
+ return (
+ this.lastEventCursor?.generation === cursor.generation && cursor.sequence <= this.lastEventCursor.sequence
+ );
+ }
const sequence = getDaemonMessageSequence(message);
return sequence !== undefined && this.lastEventSequence !== undefined && sequence <= this.lastEventSequence;
}
private observeDaemonEventSequence(message: DaemonOutbound): void {
+ const cursor = getDaemonMessageCursor(message);
+ if (cursor) {
+ this.observeEventCursor(cursor);
+ this.lastEventSequence = cursor.sequence;
+ return;
+ }
const sequence = getDaemonMessageSequence(message);
if (sequence === undefined) {
return;
}
this.lastEventSequence =
this.lastEventSequence === undefined ? sequence : Math.max(this.lastEventSequence, sequence);
+ if (this.lastEventCursor) {
+ this.lastEventCursor = {
+ ...this.lastEventCursor,
+ sequence: Math.max(this.lastEventCursor.sequence, sequence),
+ };
+ }
+ }
+
+ private observeEventCursor(cursor: DaemonEventCursor): void {
+ const current = this.lastEventCursor;
+ if (current && current.generation !== cursor.generation) {
+ this.retiredEventGenerations.add(current.generation);
+ }
+ if (!current || current.generation !== cursor.generation || cursor.sequence > current.sequence) {
+ this.lastEventCursor = cursor;
+ }
}
private async emit(event: AgentConnectionEvent): Promise<void> {
for (const listener of [...this.listeners]) {
- await listener(event);
+ try {
+ await listener(event);
+ } catch {
+ // One attachment must not interrupt delivery or transport recovery for the others.
+ }
}
}
@@ -1071,6 +1409,13 @@ function getAttachLastEventSequence(result: SessionSummary | DaemonAttachResult)
return undefined;
}
+function getAttachLastEventCursor(result: SessionSummary | DaemonAttachResult): DaemonEventCursor | undefined {
+ if ("lastEventCursor" in result) {
+ return result.lastEventCursor;
+ }
+ return undefined;
+}
+
function maxEventSequence(current: number | undefined, observed: number | undefined): number | undefined {
if (current === undefined) {
return observed;
@@ -1081,15 +1426,13 @@ function maxEventSequence(current: number | undefined, observed: number | undefi
return Math.max(current, observed);
}
-function mapDaemonAttachSnapshot(result: DaemonAttachResult): AgentConnectionSnapshot {
- return mapDaemonSessionSnapshot(result.snapshot, result.replay);
-}
-
function mapDaemonSessionSnapshot(snapshot: DaemonSessionSnapshot, replay?: DaemonReplayInfo): AgentConnectionSnapshot {
const connectionSnapshot: AgentConnectionSnapshot = {
state: snapshot.state,
messages: snapshot.messages,
+ ...(snapshot.summary.streamingMessage ? { streamingMessage: snapshot.summary.streamingMessage } : {}),
lastEventSequence: snapshot.lastEventSequence,
+ lastEventCursor: snapshot.lastEventCursor,
};
if (snapshot.sessionContext) {
connectionSnapshot.sessionContext = snapshot.sessionContext;
@@ -1116,6 +1459,13 @@ function getDaemonMessageSequence(message: DaemonOutbound): number | undefined {
return message.meta?.sequence;
}
+function getDaemonMessageCursor(message: DaemonOutbound): DaemonEventCursor | undefined {
+ if (!("meta" in message)) {
+ return undefined;
+ }
+ return message.meta?.cursor;
+}
+
function invalidatesCachedSnapshot(commandType: DaemonCommandBody["type"]): boolean {
switch (commandType) {
case "attach":
diff --git a/packages/coding-agent/src/modes/agent-connection/snapshot.ts b/packages/coding-agent/src/modes/agent-connection/snapshot.ts
index 511ae2d3da..82136e4a30 100644
--- a/packages/coding-agent/src/modes/agent-connection/snapshot.ts
+++ b/packages/coding-agent/src/modes/agent-connection/snapshot.ts
@@ -67,6 +67,7 @@ export function createAgentConnectionSnapshot(
return {
state: createAgentConnectionState(runtime, activeSessionId),
messages: [...session.messages],
+ ...(session.state?.streamingMessage ? { streamingMessage: session.state.streamingMessage } : {}),
sessionContext: session.buildSessionContext(),
sessionTree: {
tree: sessionManager.getTree(),
diff --git a/packages/coding-agent/src/modes/agent-connection/types.ts b/packages/coding-agent/src/modes/agent-connection/types.ts
index 5d7398a128..e419b2bf36 100644
--- a/packages/coding-agent/src/modes/agent-connection/types.ts
+++ b/packages/coding-agent/src/modes/agent-connection/types.ts
@@ -230,9 +230,16 @@ export interface AgentConnectionReplayInfo {
status: AgentConnectionReplayStatus;
fromSequence?: number;
toSequence: number;
+ fromCursor?: AgentConnectionEventCursor;
+ toCursor?: AgentConnectionEventCursor;
reason?: string;
}
+export interface AgentConnectionEventCursor {
+ generation: string;
+ sequence: number;
+}
+
export interface AgentConnectionParentMetadata {
activeSessionId?: string;
sessionId?: string;
@@ -243,12 +250,15 @@ export interface AgentConnectionParentMetadata {
export interface AgentConnectionSnapshot {
state: AgentConnectionState;
messages: AgentMessage[];
+ /** In-flight assistant message, kept separate from finalized transcript messages. */
+ streamingMessage?: AgentMessage;
sessionContext?: AgentConnectionSessionContext;
sessionTree?: { tree: AgentConnectionSessionTreeNode[]; leafId: string | null };
parent?: AgentConnectionParentMetadata;
/** Live RLM child agents (including grandchildren) known to the host at snapshot time. */
children?: AgentConnectionRlmChildAgentSnapshot[];
lastEventSequence?: number;
+ lastEventCursor?: AgentConnectionEventCursor;
replay?: AgentConnectionReplayInfo;
}
@@ -511,8 +521,10 @@ export type AgentConnectionEvent =
| { type: "session_event"; event: AgentConnectionSessionEvent }
| { type: "side_question_event"; event: AgentConnectionSideQuestionEvent }
| { type: "session_replaced"; state: AgentConnectionState; messages: AgentMessage[] }
+ | { type: "session_resynced"; snapshot: AgentConnectionSnapshot }
| { type: "session_status"; recap?: string }
| { type: "extension_ui_request"; request: AgentConnectionExtensionUiRequest }
+ | { type: "connection_status"; status: "reconnecting" | "connected"; error?: string }
| { type: "closed"; error?: string };
export type AgentConnectionEventListener = (event: AgentConnectionEvent) => void | Promise<void>;
diff --git a/packages/coding-agent/src/modes/agents-view/agents-view-mode.ts b/packages/coding-agent/src/modes/agents-view/agents-view-mode.ts
index 44a3fd6bfa..cee65fa30a 100644
--- a/packages/coding-agent/src/modes/agents-view/agents-view-mode.ts
+++ b/packages/coding-agent/src/modes/agents-view/agents-view-mode.ts
@@ -113,6 +113,8 @@ export interface AgentsViewModeOptions {
initialImages?: ImageContent[];
initialMessages?: string[];
verbose?: boolean;
+ recoverDaemon?: () => Promise<void>;
+ reconnectTimeoutMs?: number;
}
type AgentsViewRunResult =
@@ -254,6 +256,8 @@ async function openAgentsViewSession(
try {
const connection = await DaemonAgentConnection.attach(client, summary.activeSessionId, {
closeClientOnDispose: true,
+ recoverDaemon: options.recoverDaemon,
+ reconnectTimeoutMs: options.reconnectTimeoutMs,
});
return { connection, summary };
} catch (error) {
@@ -281,6 +285,8 @@ async function openAgentsViewSession(
const activeSessionId = getRequiredActiveSessionId(createdSummary);
const connection = await DaemonAgentConnection.attach(client, activeSessionId, {
closeClientOnDispose: true,
+ recoverDaemon: options.recoverDaemon,
+ reconnectTimeoutMs: options.reconnectTimeoutMs,
});
return { connection, summary: createdSummary, cwdFallbackNotice: notice };
} catch (error) {
@@ -788,7 +794,7 @@ class AgentsViewMode implements Component, Focusable {
/** Sticky messages (e.g. billing warnings) stay until the user acknowledges them with any keypress. */
private clearStickyStatusMessage(): void {
- if (!this.statusMessageSticky || this.daemonShutdownReceived) {
+ if (!this.statusMessageSticky || this.daemonShutdownReceived || this.reconnectPromise) {
return;
}
this.statusMessageSticky = false;
@@ -1890,7 +1896,7 @@ class AgentsViewMode implements Component, Focusable {
return;
}
if (!this.reconnectTimedOut) {
- this.setStatusMessage("Daemon restarted; reconnecting...", { sticky: true });
+ this.setStatusMessage("Daemon connection lost; reconnecting…", { tone: "warning", sticky: true });
}
const reconnectPromise = this.reconnectClient(client, error).finally(() => {
if (this.reconnectPromise === reconnectPromise) {
@@ -1901,17 +1907,18 @@ class AgentsViewMode implements Component, Focusable {
}
private async reconnectClient(client: DaemonClient, initialError: unknown): Promise<void> {
- const deadline = Date.now() + RECONNECT_TIMEOUT_MS;
+ const deadline = Date.now() + (this.options.reconnectTimeoutMs ?? RECONNECT_TIMEOUT_MS);
let lastError = initialError;
while (!this.stopped && !this.daemonShutdownReceived && client === this.client && Date.now() < deadline) {
try {
+ await this.options.recoverDaemon?.();
await client.reconnect(1000);
const response = await client.request(createAgentsViewListCommand());
const data = requireDaemonData(response);
const sessions = expectSessionList(data);
this.daemonShutdownReceived = false;
this.reconnectTimedOut = false;
- this.setStatusMessage("Reconnected after daemon restart", { render: false });
+ this.setStatusMessage("Daemon reconnected", { render: false });
this.applySessionList(sessions);
await this.sendInitialPrompts();
return;
diff --git a/packages/coding-agent/src/modes/daemon/active-session-state.ts b/packages/coding-agent/src/modes/daemon/active-session-state.ts
index b55ad1900b..098aa7987a 100644
--- a/packages/coding-agent/src/modes/daemon/active-session-state.ts
+++ b/packages/coding-agent/src/modes/daemon/active-session-state.ts
@@ -9,9 +9,20 @@ export interface DaemonSocketClient {
id: string;
socket: Socket;
attachedActiveSessionIds: Set<string>;
+ /** Session events are dropped while the socket is blocked and replaced with one catch-up snapshot on drain. */
+ catchupActiveSessionIds?: Set<string>;
+ /** A real runtime replacement takes precedence over an ordinary resync for the same queued catch-up. */
+ catchupPurposes?: Map<string, "replacement" | "resync">;
+ backpressured?: boolean;
+ authenticated?: boolean;
+ transport?: "jsonl" | "private-framed";
+ snapshotStreaming?: boolean;
+ snapshotActiveSessionIds?: Set<string>;
+ snapshotActiveSessionCounts?: Map<string, number>;
detachInput: () => void;
supportsExtensionUi: boolean;
capabilities: Set<DaemonClientCapability>;
+ capabilitiesByActiveSessionId?: Map<string, Set<DaemonClientCapability>>;
}
export interface ActiveSessionState {
@@ -19,6 +30,7 @@ export interface ActiveSessionState {
runtime: AgentSessionRuntime;
clients: Set<DaemonSocketClient>;
extensionUiRequests: Map<string, ActiveSessionExtensionUiRequest>;
+ eventGeneration: string;
lastEventSequence: DaemonEventSequence;
unsubscribe?: () => void;
/** Latest background status summary, surfaced in the agents view. */
diff --git a/packages/coding-agent/src/modes/daemon/command-recovery-journal.ts b/packages/coding-agent/src/modes/daemon/command-recovery-journal.ts
new file mode 100644
index 0000000000..88d22cf6a6
--- /dev/null
+++ b/packages/coding-agent/src/modes/daemon/command-recovery-journal.ts
@@ -0,0 +1,211 @@
+import { chmodSync, closeSync, fsyncSync, mkdirSync, openSync, readFileSync, renameSync, writeSync } from "node:fs";
+import { dirname } from "node:path";
+import type { DaemonClientId, DaemonCommandId, DaemonResponse } from "./daemon-protocol.js";
+
+interface ReceivedRecord {
+ version: 1;
+ type: "received";
+ key: string;
+ clientId: DaemonClientId;
+ commandId: DaemonCommandId;
+ commandType: string;
+ recordedAt: string;
+}
+
+interface ResultRecord {
+ version: 1;
+ type: "result";
+ key: string;
+ response: DaemonResponse;
+ recordedAt: string;
+}
+
+interface AcknowledgedRecord {
+ version: 1;
+ type: "acknowledged";
+ key: string;
+ recordedAt: string;
+}
+
+type JournalRecord = ReceivedRecord | ResultRecord | AcknowledgedRecord;
+
+interface JournalEntry {
+ received: ReceivedRecord;
+ response?: DaemonResponse;
+}
+
+export type CommandJournalBeginResult =
+ | { status: "new" }
+ | { status: "pending" }
+ | { status: "complete"; response: DaemonResponse };
+
+const COMPACT_AFTER_RECORDS = 4096;
+
+export function createCommandIdempotencyKey(clientId: DaemonClientId, commandId: DaemonCommandId): string {
+ return JSON.stringify([clientId, commandId]);
+}
+
+/**
+ * Append-only command journal used at the supervisor boundary. A received
+ * record is durable before a mutating command is dispatched; a missing result
+ * after a crash is therefore treated as uncertain and is never replayed.
+ */
+export class CommandRecoveryJournal {
+ private readonly entries = new Map<string, JournalEntry>();
+ private recordCount = 0;
+
+ constructor(private readonly path: string) {
+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
+ this.load();
+ }
+
+ begin(clientId: DaemonClientId, commandId: DaemonCommandId, commandType: string): CommandJournalBeginResult {
+ const key = createCommandIdempotencyKey(clientId, commandId);
+ const existing = this.entries.get(key);
+ if (existing?.response) {
+ return { status: "complete", response: existing.response };
+ }
+ if (existing) {
+ return { status: "pending" };
+ }
+ const received: ReceivedRecord = {
+ version: 1,
+ type: "received",
+ key,
+ clientId,
+ commandId,
+ commandType,
+ recordedAt: new Date().toISOString(),
+ };
+ this.append(received);
+ this.entries.set(key, { received });
+ return { status: "new" };
+ }
+
+ recordResult(clientId: DaemonClientId, commandId: DaemonCommandId, response: DaemonResponse): void {
+ const key = createCommandIdempotencyKey(clientId, commandId);
+ const entry = this.entries.get(key);
+ if (!entry) {
+ throw new Error(`Cannot record a result before command receipt: ${key}`);
+ }
+ const record: ResultRecord = {
+ version: 1,
+ type: "result",
+ key,
+ response,
+ recordedAt: new Date().toISOString(),
+ };
+ this.append(record);
+ entry.response = response;
+ if (this.recordCount >= COMPACT_AFTER_RECORDS) {
+ this.compact();
+ }
+ }
+
+ acknowledge(clientId: DaemonClientId, commandId: DaemonCommandId): void {
+ const key = createCommandIdempotencyKey(clientId, commandId);
+ if (!this.entries.has(key)) {
+ return;
+ }
+ this.append({
+ version: 1,
+ type: "acknowledged",
+ key,
+ recordedAt: new Date().toISOString(),
+ });
+ this.entries.delete(key);
+ if (this.entries.size === 0 || this.recordCount >= COMPACT_AFTER_RECORDS) {
+ this.compact();
+ }
+ }
+
+ private load(): void {
+ let contents: string;
+ try {
+ contents = readFileSync(this.path, "utf8");
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") {
+ return;
+ }
+ throw error;
+ }
+ for (const line of contents.split("\n")) {
+ if (!line) {
+ continue;
+ }
+ let record: JournalRecord;
+ try {
+ record = JSON.parse(line) as JournalRecord;
+ } catch {
+ // A crash may leave only the final append truncated.
+ continue;
+ }
+ if (record.version !== 1 || typeof record.key !== "string") {
+ continue;
+ }
+ this.recordCount++;
+ if (record.type === "received") {
+ if (
+ typeof record.clientId === "string" &&
+ typeof record.commandId === "string" &&
+ typeof record.commandType === "string"
+ ) {
+ this.entries.set(record.key, { received: record });
+ }
+ continue;
+ }
+ if (record.type === "acknowledged") {
+ this.entries.delete(record.key);
+ continue;
+ }
+ const entry = this.entries.get(record.key);
+ if (entry && record.response?.type === "response") {
+ entry.response = record.response;
+ }
+ }
+ }
+
+ private append(record: JournalRecord): void {
+ const descriptor = openSync(this.path, "a", 0o600);
+ try {
+ writeSync(descriptor, `${JSON.stringify(record)}\n`);
+ fsyncSync(descriptor);
+ } finally {
+ closeSync(descriptor);
+ }
+ chmodSync(this.path, 0o600);
+ this.recordCount++;
+ }
+
+ private compact(): void {
+ const tempPath = `${this.path}.${process.pid}.tmp`;
+ const records: JournalRecord[] = [];
+ for (const [key, entry] of this.entries) {
+ records.push(entry.received);
+ if (entry.response) {
+ records.push({
+ version: 1,
+ type: "result",
+ key,
+ response: entry.response,
+ recordedAt: new Date().toISOString(),
+ });
+ }
+ }
+ const descriptor = openSync(tempPath, "w", 0o600);
+ try {
+ writeSync(descriptor, `${records.map((record) => JSON.stringify(record)).join("\n")}\n`);
+ fsyncSync(descriptor);
+ } finally {
+ closeSync(descriptor);
+ }
+ renameSync(tempPath, this.path);
+ const directoryDescriptor = openSync(dirname(this.path), "r");
+ try {
+ fsyncSync(directoryDescriptor);
+ } finally {
+ closeSync(directoryDescriptor);
+ }
+ this.recordCount = records.length;
+ }
+}
diff --git a/packages/coding-agent/src/modes/daemon/compact-session-stream.ts b/packages/coding-agent/src/modes/daemon/compact-session-stream.ts
new file mode 100644
index 0000000000..d8e5cb2b86
--- /dev/null
+++ b/packages/coding-agent/src/modes/daemon/compact-session-stream.ts
@@ -0,0 +1,213 @@
+import { type AssistantMessage, type AssistantMessageEvent, parseStreamingJson } from "@earendil-works/pi-ai";
+import type { DaemonEventMeta, DaemonOutbound } from "./daemon-protocol.js";
+
+type SessionEvent = Extract<DaemonOutbound, { type: "session_event" }>["event"];
+type MessageUpdateEvent = Extract<SessionEvent, { type: "message_update" }>;
+type WithoutPartial<T> = T extends { partial: AssistantMessage } ? Omit<T, "partial"> : T;
+type CompactAssistantMessageEvent = WithoutPartial<MessageUpdateEvent["assistantMessageEvent"]>;
+
+export interface CompactAssistantDelta {
+ type: "assistant_stream_delta";
+ activeSessionId: string;
+ assistantMessageEvent: CompactAssistantMessageEvent;
+ contentStart?: AssistantMessage["content"][number];
+ toolCallArguments?: Record<string, unknown>;
+ meta?: DaemonEventMeta;
+}
+
+export function createCompactAssistantDelta(message: DaemonOutbound): CompactAssistantDelta | undefined {
+ if (message.type !== "session_event" || message.event.type !== "message_update") {
+ return undefined;
+ }
+ if (message.event.message.role !== "assistant") {
+ return undefined;
+ }
+ const { partial: _partial, ...assistantMessageEvent } = message.event
+ .assistantMessageEvent as AssistantMessageEvent & {
+ partial?: AssistantMessage;
+ };
+ const contentStart = compactContentStart(message.event.message, assistantMessageEvent);
+ const toolCallArguments = compactToolCallArguments(message.event.message, assistantMessageEvent);
+ return {
+ type: "assistant_stream_delta",
+ activeSessionId: message.activeSessionId,
+ assistantMessageEvent: assistantMessageEvent as CompactAssistantMessageEvent,
+ ...(contentStart ? { contentStart } : {}),
+ ...(toolCallArguments ? { toolCallArguments } : {}),
+ ...(message.meta ? { meta: message.meta } : {}),
+ };
+}
+
+function compactToolCallArguments(
+ message: AssistantMessage,
+ event: CompactAssistantMessageEvent,
+): Record<string, unknown> | undefined {
+ if (event.type !== "toolcall_delta") {
+ return undefined;
+ }
+ const content = message.content[event.contentIndex];
+ return content?.type === "toolCall" ? content.arguments : undefined;
+}
+
+function compactContentStart(
+ message: AssistantMessage,
+ event: CompactAssistantMessageEvent,
+): AssistantMessage["content"][number] | undefined {
+ if (event.type !== "text_start" && event.type !== "thinking_start" && event.type !== "toolcall_start") {
+ return undefined;
+ }
+ const content = message.content[event.contentIndex];
+ if (event.type === "text_start" && content?.type === "text") {
+ return { ...content, text: "" };
+ }
+ if (event.type === "thinking_start" && content?.type === "thinking") {
+ return { ...content, thinking: "" };
+ }
+ if (event.type === "toolcall_start" && content?.type === "toolCall") {
+ return { ...content, arguments: {} };
+ }
+ return undefined;
+}
+
+export class CompactAssistantStreamReconstructor {
+ private readonly partialMessages = new Map<string, AssistantMessage>();
+ private readonly toolCallJson = new Map<string, string>();
+
+ seed(activeSessionId: string, message: AssistantMessage): void {
+ this.partialMessages.set(activeSessionId, message);
+ }
+
+ observe(message: DaemonOutbound): void {
+ if (message.type !== "session_event") {
+ if (
+ message.type === "session_replaced" ||
+ message.type === "session_resynced" ||
+ message.type === "session_closed"
+ ) {
+ this.clear(message.activeSessionId);
+ }
+ return;
+ }
+ if (message.event.type === "message_start" && message.event.message.role === "assistant") {
+ this.partialMessages.set(message.activeSessionId, message.event.message);
+ return;
+ }
+ if (message.event.type === "message_end") {
+ this.clear(message.activeSessionId);
+ }
+ }
+
+ reconstruct(delta: CompactAssistantDelta): DaemonOutbound | undefined {
+ const partial = this.partialMessages.get(delta.activeSessionId);
+ if (!partial) {
+ return undefined;
+ }
+ const event = delta.assistantMessageEvent;
+ switch (event.type) {
+ case "text_start":
+ partial.content[event.contentIndex] = delta.contentStart ?? { type: "text", text: "" };
+ break;
+ case "text_delta": {
+ const content = partial.content[event.contentIndex];
+ if (content?.type !== "text") {
+ return undefined;
+ }
+ content.text += event.delta;
+ break;
+ }
+ case "text_end": {
+ const content = partial.content[event.contentIndex];
+ if (content?.type !== "text") {
+ return undefined;
+ }
+ content.text = event.content;
+ break;
+ }
+ case "thinking_start":
+ partial.content[event.contentIndex] = delta.contentStart ?? { type: "thinking", thinking: "" };
+ break;
+ case "thinking_delta": {
+ const content = partial.content[event.contentIndex];
+ if (content?.type !== "thinking") {
+ return undefined;
+ }
+ content.thinking += event.delta;
+ break;
+ }
+ case "thinking_end": {
+ const content = partial.content[event.contentIndex];
+ if (content?.type !== "thinking") {
+ return undefined;
+ }
+ content.thinking = event.content;
+ break;
+ }
+ case "toolcall_start":
+ if (!delta.contentStart || delta.contentStart.type !== "toolCall") {
+ return undefined;
+ }
+ partial.content[event.contentIndex] = delta.contentStart;
+ this.toolCallJson.set(this.toolCallKey(delta.activeSessionId, event.contentIndex), "");
+ break;
+ case "toolcall_delta": {
+ const content = partial.content[event.contentIndex];
+ if (content?.type !== "toolCall") {
+ return undefined;
+ }
+ if (delta.toolCallArguments) {
+ content.arguments = delta.toolCallArguments;
+ } else {
+ const key = this.toolCallKey(delta.activeSessionId, event.contentIndex);
+ const partialJson = `${this.toolCallJson.get(key) ?? ""}${event.delta}`;
+ this.toolCallJson.set(key, partialJson);
+ content.arguments = parseStreamingJson<Record<string, unknown>>(partialJson);
+ }
+ break;
+ }
+ case "toolcall_end":
+ partial.content[event.contentIndex] = event.toolCall;
+ this.toolCallJson.delete(this.toolCallKey(delta.activeSessionId, event.contentIndex));
+ break;
+ case "start":
+ case "done":
+ case "error":
+ return undefined;
+ }
+ return {
+ type: "session_event",
+ activeSessionId: delta.activeSessionId,
+ event: {
+ type: "message_update",
+ message: { ...partial, content: [...partial.content] },
+ assistantMessageEvent: event as MessageUpdateEvent["assistantMessageEvent"],
+ },
+ ...(delta.meta ? { meta: delta.meta } : {}),
+ };
+ }
+
+ clear(activeSessionId: string): void {
+ this.partialMessages.delete(activeSessionId);
+ for (const key of this.toolCallJson.keys()) {
+ if (key.startsWith(`${activeSessionId}:`)) {
+ this.toolCallJson.delete(key);
+ }
+ }
+ }
+
+ private toolCallKey(activeSessionId: string, contentIndex: number): string {
+ return `${activeSessionId}:${contentIndex}`;
+ }
+}
+
+export function isCompactAssistantDelta(value: unknown): value is CompactAssistantDelta {
+ if (!value || typeof value !== "object") {
+ return false;
+ }
+ const candidate = value as { type?: unknown; activeSessionId?: unknown; assistantMessageEvent?: unknown };
+ return (
+ candidate.type === "assistant_stream_delta" &&
+ typeof candidate.activeSessionId === "string" &&
+ typeof candidate.assistantMessageEvent === "object" &&
+ candidate.assistantMessageEvent !== null
+ );
+}
diff --git a/packages/coding-agent/src/modes/daemon/daemon-catalog-process.ts b/packages/coding-agent/src/modes/daemon/daemon-catalog-process.ts
new file mode 100644
index 0000000000..9b5362d29b
--- /dev/null
+++ b/packages/coding-agent/src/modes/daemon/daemon-catalog-process.ts
@@ -0,0 +1,432 @@
+import { type ChildProcess, spawn } from "node:child_process";
+import { randomUUID } from "node:crypto";
+import { createCliSubprocessLaunchSpec } from "../../cli/subprocess-launch.js";
+import type { DeleteSessionFileResult } from "../../core/session-file-actions.js";
+import { deleteSessionFile } from "../../core/session-file-actions.js";
+import { readSessionInfo, type SessionInfo, SessionManager } from "../../core/session-manager.js";
+
+export const DAEMON_CATALOG_ROLE_ENV = "PRIME_AGENT_INTERNAL_DAEMON_CATALOG";
+
+interface SessionInfoWire extends Omit<SessionInfo, "created" | "modified"> {
+ created: string;
+ modified: string;
+}
+
+type CatalogRequest =
+ | { type: "request"; id: string; command: "list"; cwd?: string; sessionDir?: string }
+ | { type: "request"; id: string; command: "resolve"; selector: string; cwd: string; sessionDir?: string }
+ | { type: "request"; id: string; command: "rename"; sessionPath: string; name: string }
+ | { type: "request"; id: string; command: "delete"; sessionPath: string }
+ | { type: "request"; id: string; command: "archive"; sessionPath: string; sessionId: string }
+ | {
+ type: "request";
+ id: string;
+ command: "mark_interrupted";
+ sessionPath: string;
+ activeSessionId: string;
+ operations: string[];
+ }
+ | { type: "request"; id: string; command: "shutdown" };
+
+type CatalogOutbound =
+ | { type: "ready" }
+ | { type: "progress"; id: string; loaded: number; total: number }
+ | { type: "session"; id: string; session: SessionInfoWire }
+ | { type: "response"; id: string; success: true; data?: unknown }
+ | { type: "response"; id: string; success: false; error: string };
+
+interface CatalogListCallbacks {
+ onProgress?: (loaded: number, total: number) => void;
+ onSession?: (session: SessionInfo) => void;
+}
+
+function serializeSessionInfo(session: SessionInfo): SessionInfoWire {
+ return {
+ ...session,
+ created: session.created.toISOString(),
+ modified: session.modified.toISOString(),
+ };
+}
+
+function deserializeSessionInfo(session: SessionInfoWire): SessionInfo {
+ return {
+ ...session,
+ created: new Date(session.created),
+ modified: new Date(session.modified),
+ };
+}
+
+function isCatalogOutbound(value: unknown): value is CatalogOutbound {
+ if (!value || typeof value !== "object") {
+ return false;
+ }
+ const candidate = value as { type?: unknown; id?: unknown };
+ return (
+ candidate.type === "ready" ||
+ ((candidate.type === "progress" || candidate.type === "session" || candidate.type === "response") &&
+ typeof candidate.id === "string")
+ );
+}
+
+function isCatalogRequest(value: unknown): value is CatalogRequest {
+ if (!value || typeof value !== "object") {
+ return false;
+ }
+ const candidate = value as { type?: unknown; id?: unknown; command?: unknown };
+ return (
+ candidate.type === "request" &&
+ typeof candidate.id === "string" &&
+ (candidate.command === "list" ||
+ candidate.command === "resolve" ||
+ candidate.command === "rename" ||
+ candidate.command === "delete" ||
+ candidate.command === "archive" ||
+ candidate.command === "mark_interrupted" ||
+ candidate.command === "shutdown")
+ );
+}
+
+function sendCatalogMessage(message: CatalogOutbound): void {
+ if (process.send) {
+ process.send(message);
+ }
+}
+
+export function isDaemonCatalogProcess(environment: NodeJS.ProcessEnv = process.env): boolean {
+ return environment[DAEMON_CATALOG_ROLE_ENV] === "1";
+}
+
+export async function runDaemonCatalogProcess(): Promise<never> {
+ process.on("disconnect", () => process.exit(0));
+ process.on("message", (value: unknown) => {
+ if (!isCatalogRequest(value)) {
+ return;
+ }
+ void handleCatalogRequest(value);
+ });
+ sendCatalogMessage({ type: "ready" });
+ return new Promise(() => {});
+}
+
+async function handleCatalogRequest(request: CatalogRequest): Promise<void> {
+ try {
+ switch (request.command) {
+ case "list": {
+ const callbacks = {
+ onProgress: (loaded: number, total: number) =>
+ sendCatalogMessage({ type: "progress", id: request.id, loaded, total }),
+ onSession: (session: SessionInfo) =>
+ sendCatalogMessage({ type: "session", id: request.id, session: serializeSessionInfo(session) }),
+ };
+ const sessions = request.cwd
+ ? await SessionManager.list(request.cwd, request.sessionDir, callbacks)
+ : await SessionManager.listAll(callbacks, request.sessionDir);
+ sendCatalogMessage({
+ type: "response",
+ id: request.id,
+ success: true,
+ data: { sessions: sessions.map(serializeSessionInfo) },
+ });
+ return;
+ }
+ case "resolve": {
+ const localMatches = (await SessionManager.list(request.cwd, request.sessionDir)).filter((session) =>
+ session.id.startsWith(request.selector),
+ );
+ if (localMatches.length === 1) {
+ sendCatalogMessage({
+ type: "response",
+ id: request.id,
+ success: true,
+ data: { sessionPath: localMatches[0]!.path },
+ });
+ return;
+ }
+ if (localMatches.length > 1) {
+ throw new Error(`Ambiguous session selector "${request.selector}"`);
+ }
+ const globalMatches = (await SessionManager.listAll(undefined, request.sessionDir)).filter((session) =>
+ session.id.startsWith(request.selector),
+ );
+ if (globalMatches.length === 1) {
+ sendCatalogMessage({
+ type: "response",
+ id: request.id,
+ success: true,
+ data: { sessionPath: globalMatches[0]!.path },
+ });
+ return;
+ }
+ if (globalMatches.length > 1) {
+ throw new Error(`Ambiguous session selector "${request.selector}"`);
+ }
+ throw new Error(`No session found matching '${request.selector}'`);
+ }
+ case "rename":
+ SessionManager.open(request.sessionPath).appendSessionInfo(request.name.trim());
+ sendCatalogMessage({ type: "response", id: request.id, success: true });
+ return;
+ case "delete":
+ sendCatalogMessage({
+ type: "response",
+ id: request.id,
+ success: true,
+ data: await deleteSessionFile(request.sessionPath),
+ });
+ return;
+ case "archive": {
+ const session = await readSessionInfo(request.sessionPath);
+ if (!session || session.id !== request.sessionId) {
+ sendCatalogMessage({
+ type: "response",
+ id: request.id,
+ success: true,
+ data: { archived: false },
+ });
+ return;
+ }
+ if (session.state?.status !== "archived") {
+ SessionManager.open(request.sessionPath).appendSessionState({ status: "archived" });
+ }
+ sendCatalogMessage({
+ type: "response",
+ id: request.id,
+ success: true,
+ data: { archived: true },
+ });
+ return;
+ }
+ case "mark_interrupted":
+ SessionManager.open(request.sessionPath).appendCustomMessageEntry(
+ "prime-agent.worker_recovery",
+ "<prime_agent_worker_interrupted>\nThe isolated session worker stopped during in-flight work. The saved transcript was recovered, but uncertain model, tool, bash, or child-agent work was not replayed. Inspect external side effects before continuing.\n</prime_agent_worker_interrupted>",
+ false,
+ {
+ activeSessionId: request.activeSessionId,
+ operations: request.operations,
+ },
+ );
+ sendCatalogMessage({ type: "response", id: request.id, success: true });
+ return;
+ case "shutdown":
+ sendCatalogMessage({ type: "response", id: request.id, success: true });
+ setImmediate(() => process.exit(0));
+ return;
+ }
+ } catch (error) {
+ sendCatalogMessage({
+ type: "response",
+ id: request.id,
+ success: false,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ }
+}
+
+export class DaemonCatalogClient {
+ private child?: ChildProcess;
+ private starting?: Promise<void>;
+ private readonly pending = new Map<
+ string,
+ {
+ resolve: (data: unknown) => void;
+ reject: (error: Error) => void;
+ callbacks?: CatalogListCallbacks;
+ timeout: ReturnType<typeof setTimeout>;
+ }
+ >();
+
+ constructor(private readonly onDiagnostic: (message: string) => void) {}
+
+ async start(): Promise<void> {
+ if (this.child?.connected) {
+ return;
+ }
+ if (this.starting) {
+ return this.starting;
+ }
+ this.starting = this.spawnCatalog().finally(() => {
+ this.starting = undefined;
+ });
+ return this.starting;
+ }
+
+ async list(cwd?: string, sessionDir?: string, callbacks?: CatalogListCallbacks): Promise<SessionInfo[]> {
+ const data = await this.request<{ sessions: SessionInfoWire[] }>(
+ { type: "request", id: randomUUID(), command: "list", cwd, sessionDir },
+ callbacks,
+ );
+ return data.sessions.map(deserializeSessionInfo);
+ }
+
+ async rename(sessionPath: string, name: string): Promise<void> {
+ await this.request({ type: "request", id: randomUUID(), command: "rename", sessionPath, name });
+ }
+
+ async resolve(selector: string, cwd: string, sessionDir?: string): Promise<string> {
+ const data = await this.request<{ sessionPath: string }>({
+ type: "request",
+ id: randomUUID(),
+ command: "resolve",
+ selector,
+ cwd,
+ sessionDir,
+ });
+ return data.sessionPath;
+ }
+
+ delete(sessionPath: string): Promise<DeleteSessionFileResult> {
+ return this.request({ type: "request", id: randomUUID(), command: "delete", sessionPath });
+ }
+
+ async archive(sessionPath: string, sessionId: string): Promise<boolean> {
+ const data = await this.request<{ archived: boolean }>({
+ type: "request",
+ id: randomUUID(),
+ command: "archive",
+ sessionPath,
+ sessionId,
+ });
+ return data.archived;
+ }
+
+ async markInterrupted(sessionPath: string, activeSessionId: string, operations: string[]): Promise<void> {
+ await this.request({
+ type: "request",
+ id: randomUUID(),
+ command: "mark_interrupted",
+ sessionPath,
+ activeSessionId,
+ operations,
+ });
+ }
+
+ async stop(): Promise<void> {
+ const child = this.child;
+ if (!child) {
+ return;
+ }
+ await this.request({ type: "request", id: randomUUID(), command: "shutdown" }).catch(() => undefined);
+ child.disconnect();
+ this.child = undefined;
+ }
+
+ private async spawnCatalog(): Promise<void> {
+ const launch = createCliSubprocessLaunchSpec(["--version"]);
+ const child = spawn(launch.command, launch.args, {
+ cwd: process.cwd(),
+ env: { ...process.env, [DAEMON_CATALOG_ROLE_ENV]: "1" },
+ stdio: ["ignore", "ignore", "ignore", "ipc"],
+ });
+ this.child = child;
+ child.on("message", (value: unknown) => this.handleMessage(value));
+ child.on("error", (error) => this.handleClose(child, error));
+ child.on("exit", (code, signal) =>
+ this.handleClose(child, new Error(`Daemon catalog exited (${signal ?? code ?? "unknown"})`)),
+ );
+ await new Promise<void>((resolveReady, rejectReady) => {
+ const timeout = setTimeout(() => {
+ cleanup();
+ const error = new Error("Timed out starting daemon catalog");
+ this.handleClose(child, error);
+ if (child.connected) {
+ child.disconnect();
+ }
+ child.kill("SIGKILL");
+ rejectReady(error);
+ }, 5000);
+ const cleanup = () => {
+ clearTimeout(timeout);
+ child.off("message", onMessage);
+ child.off("error", onError);
+ };
+ const onMessage = (value: unknown) => {
+ if (isCatalogOutbound(value) && value.type === "ready") {
+ cleanup();
+ resolveReady();
+ }
+ };
+ const onError = (error: Error) => {
+ cleanup();
+ rejectReady(error);
+ };
+ child.on("message", onMessage);
+ child.once("error", onError);
+ });
+ }
+
+ private async request<T = void>(request: CatalogRequest, callbacks?: CatalogListCallbacks): Promise<T> {
+ await this.start();
+ const child = this.child;
+ if (!child?.connected) {
+ throw new Error("Daemon catalog is not connected");
+ }
+ return new Promise<T>((resolveRequest, rejectRequest) => {
+ const timeout = setTimeout(
+ () => {
+ if (!this.pending.delete(request.id)) {
+ return;
+ }
+ child.kill("SIGKILL");
+ rejectRequest(new Error(`Timed out waiting for daemon catalog ${request.command}`));
+ },
+ 5 * 60 * 1000,
+ );
+ this.pending.set(request.id, {
+ resolve: (data) => resolveRequest(data as T),
+ reject: rejectRequest,
+ callbacks,
+ timeout,
+ });
+ child.send(request, (error) => {
+ if (!error) {
+ return;
+ }
+ const pending = this.pending.get(request.id);
+ if (pending) {
+ clearTimeout(pending.timeout);
+ this.pending.delete(request.id);
+ }
+ rejectRequest(error);
+ });
+ });
+ }
+
+ private handleMessage(value: unknown): void {
+ if (!isCatalogOutbound(value) || value.type === "ready") {
+ return;
+ }
+ const pending = this.pending.get(value.id);
+ if (!pending) {
+ return;
+ }
+ if (value.type === "progress") {
+ pending.callbacks?.onProgress?.(value.loaded, value.total);
+ return;
+ }
+ if (value.type === "session") {
+ pending.callbacks?.onSession?.(deserializeSessionInfo(value.session));
+ return;
+ }
+ this.pending.delete(value.id);
+ clearTimeout(pending.timeout);
+ if (value.success) {
+ pending.resolve(value.data);
+ } else {
+ pending.reject(new Error(value.error));
+ }
+ }
+
+ private handleClose(child: ChildProcess, error: Error): void {
+ if (this.child !== child) {
+ return;
+ }
+ this.child = undefined;
+ this.onDiagnostic(error.message);
+ for (const [id, pending] of this.pending) {
+ clearTimeout(pending.timeout);
+ pending.reject(error);
+ this.pending.delete(id);
+ }
+ }
+}
diff --git a/packages/coding-agent/src/modes/daemon/daemon-client.ts b/packages/coding-agent/src/modes/daemon/daemon-client.ts
index 96787fd78d..b51a8de475 100644
--- a/packages/coding-agent/src/modes/daemon/daemon-client.ts
+++ b/packages/coding-agent/src/modes/daemon/daemon-client.ts
@@ -1,18 +1,26 @@
+import { randomUUID } from "node:crypto";
import { createConnection, type Socket } from "node:net";
import { getDaemonLogPath } from "../../config.js";
import { attachJsonlLineReader, serializeJsonLine } from "../rpc/jsonl.js";
-import type {
- DaemonClosingReason,
- DaemonCommand,
- DaemonOutbound,
- DaemonRequestProgress,
- DaemonResponse,
- DaemonSavedSessionInfo,
+import {
+ createDaemonCommandEnvelope,
+ DAEMON_PROTOCOL_VERSION,
+ type DaemonClosingReason,
+ type DaemonCommand,
+ type DaemonCommandEnvelope,
+ type DaemonOutbound,
+ type DaemonRequestProgress,
+ type DaemonResponse,
+ type DaemonSavedSessionInfo,
+ isDaemonMutatingCommand,
} from "./daemon-protocol.js";
+import type { DaemonWorkerCommand, DaemonWorkerCommandBody } from "./daemon-worker-protocol.js";
type DistributiveOmit<T, K extends keyof T> = T extends unknown ? Omit<T, K> : never;
type DaemonCommandBody = DistributiveOmit<DaemonCommand, "id">;
+type DaemonWireCommandBody = DaemonCommandBody | DaemonWorkerCommandBody;
+
export type DaemonHello = Extract<DaemonOutbound, { type: "daemon_hello" }>;
export type DaemonClientMessageListener = (message: DaemonOutbound) => void;
@@ -23,6 +31,18 @@ export interface DaemonClientRequestOptions {
onProgress?: DaemonClientProgressListener;
}
+interface PendingDaemonRequest {
+ resolve: (response: DaemonResponse) => void;
+ reject: (error: Error) => void;
+ timeout?: ReturnType<typeof setTimeout>;
+ timeoutMs: number;
+ commandType: string;
+ onProgress?: DaemonClientProgressListener;
+ wireData: string;
+ awaitingReconnect: boolean;
+ acknowledgeResult: boolean;
+}
+
function daemonEndpointDetails(socketPath: string): string {
return `Socket: ${socketPath}. Daemon log: ${getDaemonLogPath(socketPath)}.`;
}
@@ -46,21 +66,34 @@ export function getDaemonSocketCloseReason(error: Error): DaemonClosingReason |
return error instanceof DaemonSocketClosedError ? error.daemonClosingReason : undefined;
}
+export type DaemonClientReconnectStatus =
+ | { status: "reconnecting"; error: string }
+ | { status: "connected" }
+ | { status: "failed"; error: string };
+
+export interface DaemonClientReconnectOptions {
+ recoverDaemon: () => Promise<void>;
+ timeoutMs?: number;
+ onStatus?: (status: DaemonClientReconnectStatus) => void;
+}
+
+const DEFAULT_RECONNECT_TIMEOUT_MS = 60_000;
+const RECONNECT_CONNECT_TIMEOUT_MS = 1000;
+const RECONNECT_HELLO_TIMEOUT_MS = 3000;
+const MAX_RECONNECT_DELAY_MS = 2000;
+
export class DaemonClient {
private socket?: Socket;
private detachReader?: () => void;
private readonly listeners = new Set<DaemonClientMessageListener>();
private readonly closeListeners = new Set<DaemonClientCloseListener>();
- private readonly pendingRequests = new Map<
- string,
- {
- resolve: (response: DaemonResponse) => void;
- reject: (error: Error) => void;
- timeout: ReturnType<typeof setTimeout>;
- onProgress?: DaemonClientProgressListener;
- }
- >();
+ private readonly pendingRequests = new Map<string, PendingDaemonRequest>();
private requestId = 0;
+ private readonly protocolClientId = `daemon-client:${randomUUID()}`;
+ private requestRecoveryEnabled = false;
+ private reconnectOptions?: DaemonClientReconnectOptions;
+ private autoReconnectPromise?: Promise<void>;
+ private closed = false;
private helloMessage?: DaemonHello;
private daemonClosingReason?: DaemonClosingReason;
private reconnectPromise?: Promise<void>;
@@ -111,7 +144,6 @@ export class DaemonClient {
if (this.socket) {
throw new Error(`Prime Agent daemon client is already connected. ${daemonEndpointDetails(this.socketPath)}`);
}
-
this.helloMessage = undefined;
this.daemonClosingReason = undefined;
const socket = createConnection(this.socketPath);
@@ -193,6 +225,20 @@ export class DaemonClient {
socket.destroy();
}
+ /** Discard a partially recovered transport so the next retry can reconnect cleanly. */
+ resetTransportForReconnect(): void {
+ const socket = this.socket;
+ if (!socket) {
+ return;
+ }
+ this.clearSocketReference(socket);
+ this.rejectAll(
+ new DaemonSocketClosedError(this.socketPath, undefined, "reconnect attempt did not complete"),
+ this.requestRecoveryEnabled,
+ );
+ socket.destroy();
+ }
+
onMessage(listener: DaemonClientMessageListener): () => void {
this.listeners.add(listener);
return () => {
@@ -207,6 +253,17 @@ export class DaemonClient {
};
}
+ /** Keep in-flight command promises alive and resend their stable envelopes after reconnect. */
+ enableRequestRecovery(): void {
+ this.requestRecoveryEnabled = true;
+ }
+
+ /** Reconnect a global/raw daemon client after supervisor replacement. */
+ enableAutoReconnect(options: DaemonClientReconnectOptions): void {
+ this.requestRecoveryEnabled = true;
+ this.reconnectOptions = options;
+ }
+
async request(
command: DaemonCommandBody,
timeoutMs = 30000,
@@ -217,26 +274,81 @@ export class DaemonClient {
`Cannot send daemon command "${command.type}" because the Prime Agent daemon is not connected. ${daemonEndpointDetails(this.socketPath)}`,
);
}
+ const hello = this.helloMessage ?? (await this.waitForHello());
+ return this.requestWire(command, timeoutMs, options, hello.protocol.version >= DAEMON_PROTOCOL_VERSION);
+ }
+
+ /** One-release compatibility path for preparing and stopping a v1 daemon. */
+ async requestLegacy(
+ command: DaemonCommandBody,
+ timeoutMs = 30000,
+ options: DaemonClientRequestOptions = {},
+ ): Promise<DaemonResponse> {
+ return this.requestWire(command, timeoutMs, options, false);
+ }
+
+ async authenticateWorker(token: string, timeoutMs = 3000): Promise<void> {
+ const response = await this.requestWire({ type: "worker_auth", token }, timeoutMs, {}, false);
+ if (!response.success) {
+ throw new Error(response.error);
+ }
+ }
+
+ async requestWorker(command: DaemonWorkerCommandBody, timeoutMs = 30000): Promise<DaemonResponse> {
+ return this.requestWire(command, timeoutMs, {}, false);
+ }
+
+ private async requestWire(
+ command: DaemonWireCommandBody,
+ timeoutMs: number,
+ options: DaemonClientRequestOptions = {},
+ usePublicEnvelope: boolean,
+ ): Promise<DaemonResponse> {
+ if (!this.socket || this.socket.destroyed) {
+ throw new Error(
+ `Cannot send daemon command "${command.type}" because the Prime Agent daemon is not connected. ${daemonEndpointDetails(this.socketPath)}`,
+ );
+ }
const id = `daemon_${++this.requestId}`;
- const fullCommand = { ...command, id } as DaemonCommand;
+ const fullCommand = { ...command, id } as DaemonCommand | DaemonWorkerCommand;
+ const wireCommand: DaemonCommand | DaemonWorkerCommand | DaemonCommandEnvelope = usePublicEnvelope
+ ? createDaemonCommandEnvelope(fullCommand as DaemonCommand, id, this.protocolClientId)
+ : fullCommand;
+ const wireData = serializeJsonLine(wireCommand);
+ const acknowledgeResult = usePublicEnvelope && isDaemonMutatingCommand(fullCommand as DaemonCommand);
return new Promise((resolve, reject) => {
- const timeout = setTimeout(() => {
- this.pendingRequests.delete(id);
- reject(
- new Error(
- `Timed out after ${timeoutMs}ms waiting for the Prime Agent daemon response to "${command.type}". ${daemonEndpointDetails(this.socketPath)}`,
- ),
- );
- }, timeoutMs);
-
- this.pendingRequests.set(id, { resolve, reject, timeout, onProgress: options.onProgress });
- this.socket!.write(serializeJsonLine(fullCommand));
+ const pending: PendingDaemonRequest = {
+ resolve,
+ reject,
+ timeoutMs,
+ commandType: command.type,
+ onProgress: options.onProgress,
+ wireData,
+ awaitingReconnect: false,
+ acknowledgeResult,
+ };
+ this.pendingRequests.set(id, pending);
+ this.armPendingRequestTimeout(id, pending);
+ this.socket!.write(wireData);
});
}
+ private armPendingRequestTimeout(id: string, pending: PendingDaemonRequest): void {
+ pending.timeout = setTimeout(() => {
+ this.pendingRequests.delete(id);
+ pending.reject(
+ new Error(
+ `Timed out after ${pending.timeoutMs}ms waiting for the Prime Agent daemon response to "${pending.commandType}". ${daemonEndpointDetails(this.socketPath)}`,
+ ),
+ );
+ }, pending.timeoutMs);
+ }
+
close(): void {
+ this.closed = true;
+ this.reconnectOptions = undefined;
this.detachReader?.();
this.detachReader = undefined;
this.rejectAll(
@@ -273,6 +385,16 @@ export class DaemonClient {
this.helloWaiters.delete(waiter);
waiter.resolve(message);
}
+ if (this.socket && !this.socket.destroyed) {
+ for (const [id, pending] of this.pendingRequests) {
+ if (!pending.awaitingReconnect) {
+ continue;
+ }
+ pending.awaitingReconnect = false;
+ this.armPendingRequestTimeout(id, pending);
+ this.socket.write(pending.wireData);
+ }
+ }
}
if (isDaemonClosing(message)) {
this.daemonClosingReason = message.reason;
@@ -281,9 +403,14 @@ export class DaemonClient {
if (isDaemonResponse(message) && message.id) {
const pending = this.pendingRequests.get(message.id);
if (pending) {
- clearTimeout(pending.timeout);
+ if (pending.timeout) {
+ clearTimeout(pending.timeout);
+ }
this.pendingRequests.delete(message.id);
pending.resolve(message);
+ if (pending.acknowledgeResult) {
+ this.acknowledgeCommandResult(message.id);
+ }
return;
}
}
@@ -300,9 +427,28 @@ export class DaemonClient {
}
}
- private rejectAll(error: Error): void {
+ private acknowledgeCommandResult(commandId: string): void {
+ if (!this.socket || this.socket.destroyed || (this.helloMessage?.protocol.version ?? 0) < 2) {
+ return;
+ }
+ const id = `daemon_ack_${++this.requestId}`;
+ const command: DaemonCommand = { id, type: "ack_result", commandId };
+ this.socket.write(serializeJsonLine(createDaemonCommandEnvelope(command, id, this.protocolClientId)));
+ }
+
+ private rejectAll(error: Error, preservePendingRequests = false): void {
for (const [id, pending] of this.pendingRequests) {
- clearTimeout(pending.timeout);
+ if (preservePendingRequests) {
+ if (pending.timeout) {
+ clearTimeout(pending.timeout);
+ pending.timeout = undefined;
+ }
+ pending.awaitingReconnect = true;
+ continue;
+ }
+ if (pending.timeout) {
+ clearTimeout(pending.timeout);
+ }
pending.reject(error);
this.pendingRequests.delete(id);
}
@@ -318,13 +464,76 @@ export class DaemonClient {
return;
}
this.clearSocketReference(socket);
- this.rejectAll(error);
+ this.rejectAll(error, this.requestRecoveryEnabled);
for (const listener of [...this.closeListeners]) {
listener(error);
}
+ if (this.reconnectOptions && !this.closed) {
+ void this.autoReconnect(error);
+ }
+ }
+
+ private async autoReconnect(cause: Error): Promise<void> {
+ if (this.autoReconnectPromise) {
+ return this.autoReconnectPromise;
+ }
+ const options = this.reconnectOptions;
+ if (!options || this.closed) {
+ return;
+ }
+ this.emitReconnectStatus({ status: "reconnecting", error: cause.message });
+ this.autoReconnectPromise = (async () => {
+ const deadline = Date.now() + (options.timeoutMs ?? DEFAULT_RECONNECT_TIMEOUT_MS);
+ let attempt = 0;
+ let lastError: Error = cause;
+ while (!this.closed && this.reconnectOptions === options && Date.now() < deadline) {
+ try {
+ await options.recoverDaemon();
+ if (this.closed || this.reconnectOptions !== options) {
+ return;
+ }
+ await this.connect(RECONNECT_CONNECT_TIMEOUT_MS);
+ await this.waitForHello(RECONNECT_HELLO_TIMEOUT_MS);
+ this.emitReconnectStatus({ status: "connected" });
+ return;
+ } catch (error) {
+ lastError = error instanceof Error ? error : new Error(String(error));
+ this.resetTransportForReconnect();
+ const remainingMs = deadline - Date.now();
+ if (remainingMs <= 0) {
+ break;
+ }
+ const delayMs = Math.min(remainingMs, MAX_RECONNECT_DELAY_MS, 100 * 2 ** Math.min(attempt, 5));
+ attempt++;
+ await delay(delayMs);
+ }
+ }
+ if (this.closed || this.reconnectOptions !== options) {
+ return;
+ }
+ const failure = new Error(`Daemon reconnection failed: ${lastError.message}`);
+ this.rejectAll(failure);
+ this.emitReconnectStatus({ status: "failed", error: failure.message });
+ this.reconnectOptions = undefined;
+ })().finally(() => {
+ this.autoReconnectPromise = undefined;
+ });
+ return this.autoReconnectPromise;
+ }
+
+ private emitReconnectStatus(status: DaemonClientReconnectStatus): void {
+ try {
+ this.reconnectOptions?.onStatus?.(status);
+ } catch {
+ // UI status callbacks must never interrupt transport recovery.
+ }
}
}
+function delay(ms: number): Promise<void> {
+ return new Promise((resolveDelay) => setTimeout(resolveDelay, ms));
+}
+
function isDaemonClosing(value: unknown): value is Extract<DaemonOutbound, { type: "daemon_closing" }> {
if (!value || typeof value !== "object") {
return false;
diff --git a/packages/coding-agent/src/modes/daemon/daemon-errors.ts b/packages/coding-agent/src/modes/daemon/daemon-errors.ts
index 16dee57630..207f8e15a8 100644
--- a/packages/coding-agent/src/modes/daemon/daemon-errors.ts
+++ b/packages/coding-agent/src/modes/daemon/daemon-errors.ts
@@ -1,5 +1,6 @@
import { MissingSessionCwdError } from "../../core/session-cwd.js";
import { SessionImportFileNotFoundError } from "../../core/session-import-errors.js";
+import { SessionAlreadyActiveError } from "../../core/session-lease.js";
import type { DaemonErrorInfo, DaemonResponse } from "./daemon-protocol.js";
export function serializeDaemonError(error: unknown): DaemonErrorInfo | undefined {
@@ -9,6 +10,13 @@ export function serializeDaemonError(error: unknown): DaemonErrorInfo | undefine
if (error instanceof SessionImportFileNotFoundError) {
return { code: "session_import_file_not_found", filePath: error.filePath };
}
+ if (error instanceof SessionAlreadyActiveError) {
+ return {
+ code: "session_already_active",
+ sessionPath: error.sessionPath,
+ activeSessionId: error.activeSessionId,
+ };
+ }
return undefined;
}
@@ -20,5 +28,8 @@ export function deserializeDaemonError(response: Extract<DaemonResponse, { succe
if (errorInfo?.code === "session_import_file_not_found") {
return new SessionImportFileNotFoundError(errorInfo.filePath);
}
+ if (errorInfo?.code === "session_already_active") {
+ return new SessionAlreadyActiveError(errorInfo.sessionPath, errorInfo.activeSessionId);
+ }
return new Error(response.error);
}
diff --git a/packages/coding-agent/src/modes/daemon/daemon-mode.ts b/packages/coding-agent/src/modes/daemon/daemon-mode.ts
index 68ac8258b1..5c9dda98bb 100644
--- a/packages/coding-agent/src/modes/daemon/daemon-mode.ts
+++ b/packages/coding-agent/src/modes/daemon/daemon-mode.ts
@@ -6,10 +6,13 @@
* disposing the underlying agent loop.
*/
-import { mkdirSync, writeFileSync } from "node:fs";
-import { createServer, type Server, type Socket } from "node:net";
-import { dirname, resolve } from "node:path";
+import { spawn } from "node:child_process";
+import { createHash, randomUUID } from "node:crypto";
+import { mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
+import { createConnection, createServer, type Server, type Socket } from "node:net";
+import { dirname, join, resolve } from "node:path";
import { getLogger } from "@earendil-works/pi-ai";
+import { createCliSubprocessLaunchSpec } from "../../cli/subprocess-launch.js";
import {
appendRotatingLog,
getCronJobsPath,
@@ -74,12 +77,14 @@ import {
resolveHeartbeatStreamingBehavior,
shouldDeferHeartbeatCronJob,
} from "../../core/cron-jobs.js";
+import { ORPHAN_PROCESS_JOURNAL_ENV } from "../../core/orphan-process-journal.js";
import type {
CreateRlmSubagentRuntimeOptions,
RlmSubagentRuntime,
SubagentRuntimeHost,
} from "../../core/rlm-runtime.js";
import { deleteSessionFile } from "../../core/session-file-actions.js";
+import { acquireSessionLease, type SessionLease } from "../../core/session-lease.js";
import { readSessionInfo, type SessionInfo, SessionManager } from "../../core/session-manager.js";
import type { SessionStats } from "../../core/session-stats.js";
import { type SideQuestionRun, startSideQuestion } from "../../core/side-question.js";
@@ -91,14 +96,17 @@ import {
} from "../agent-connection/snapshot.js";
import { createAgentConnectionToolDefinition } from "../agent-connection/tool-definition.js";
import { attachJsonlLineReader, serializeJsonLine } from "../rpc/jsonl.js";
+import { encodePrivateFrame, PrivateFrameDecoder } from "../session-worker/private-framing.js";
import {
type ActiveSessionState,
createActiveSessionId,
type DaemonSocketClient,
resolveActiveSessionState,
} from "./active-session-state.js";
+import { createCompactAssistantDelta } from "./compact-session-stream.js";
+import { DaemonClient } from "./daemon-client.js";
import { filterClientEnv, withClientEnv } from "./daemon-client-env.js";
-import { serializeDaemonError } from "./daemon-errors.js";
+import { deserializeDaemonError, serializeDaemonError } from "./daemon-errors.js";
import { bindActiveSessionState } from "./daemon-extension-binding.js";
import {
createDaemonEventMeta,
@@ -117,6 +125,7 @@ import {
type DaemonUpdateRestartManifest,
type DaemonUpdateRestartSession,
failure,
+ isDaemonCommandEnvelope,
isDaemonDialogExtensionUiRequest,
success,
} from "./daemon-protocol.js";
@@ -135,11 +144,29 @@ import {
prepareDaemonSocketPath,
restrictDaemonSocketPath,
} from "./daemon-socket.js";
+import {
+ DAEMON_WORKER_ACTIVE_SESSION_ID_ENV,
+ DAEMON_WORKER_RECOVERY_JOURNAL_ENV,
+ DAEMON_WORKER_ROLE_ENV,
+ DAEMON_WORKER_SUPERVISOR_SOCKET_ENV,
+ DAEMON_WORKER_TOKEN_ENV,
+ type DaemonWorkerCommand,
+ type DaemonWorkerFrameHeader,
+ isDaemonWorkerFrameHeader,
+ SESSION_LEASE_OWNER_ID_ENV,
+ SESSION_LEASES_ENABLED_ENV,
+} from "./daemon-worker-protocol.js";
+import { SNAPSHOT_TARGET_CHUNK_BYTES, SnapshotTranscriptCache } from "./snapshot-transcript-cache.js";
+import { WorkerRecoveryJournal } from "./worker-recovery-journal.js";
export interface DaemonModeOptions {
socketPath?: string;
defaultSessionConfig: AgentSessionRuntimeConfig;
createRuntime: CreateAgentSessionRuntimeFactory;
+ worker?: {
+ authenticationToken: string;
+ restoreActiveSessionId?: string;
+ };
}
export type { DaemonCommand, DaemonOutbound, DaemonResponse } from "./daemon-protocol.js";
@@ -149,6 +176,7 @@ export { defaultDaemonSocketPath } from "./daemon-socket.js";
const structuredLog = getLogger("coding-agent.daemon");
const DAEMON_COMMAND_TYPES: ReadonlySet<string> = new Set([
+ "ack_result",
"list",
"list_saved_sessions",
"create",
@@ -224,6 +252,8 @@ const DAEMON_COMMAND_TYPES: ReadonlySet<string> = new Set([
"set_session_entry_label",
"extension_ui_response",
"prepare_update_restart",
+ "retry_worker",
+ "restart",
"shutdown",
]);
@@ -232,6 +262,7 @@ const DAEMON_SERVER_CAPABILITIES: readonly DaemonClientCapability[] = [
"event_sequence",
"extension_ui",
"slim_attach",
+ "chunked_snapshot",
];
const DAEMON_CLIENT_CAPABILITY_SET: ReadonlySet<string> = new Set(DAEMON_SERVER_CAPABILITIES);
@@ -240,6 +271,24 @@ const UPDATE_RESTART_MARKER =
"<prime_agent_update_interrupted>\n" +
"Prime Agent was updated and intentionally interrupted this session. Continue from the saved transcript and restored tool/kernel state. Any running model, tool, bash, or child-agent work may have been partially completed.\n" +
"</prime_agent_update_interrupted>";
+const RECOVERY_CHECKPOINT_EVENTS: ReadonlySet<string> = new Set([
+ "agent_start",
+ "agent_end",
+ "turn_start",
+ "turn_end",
+ "message_start",
+ "message_end",
+ "tool_execution_start",
+ "tool_execution_end",
+ "compaction_start",
+ "compaction_end",
+ "auto_retry_start",
+ "auto_retry_end",
+ "bash_start",
+ "bash_end",
+ "queue_update",
+ "rlm_child_update",
+]);
function delay(ms: number): Promise<void> {
return new Promise((resolveDelay) => setTimeout(resolveDelay, ms));
@@ -260,6 +309,7 @@ export class AgentDaemon {
private server?: Server;
private shuttingDown = false;
private updateRestartPreparing = false;
+ private preparedUpdateRestartManifest?: DaemonUpdateRestartManifest;
private ownsSocketPath = false;
private socketIdentity?: DaemonSocketIdentity;
private readonly clients = new Set<DaemonSocketClient>();
@@ -272,8 +322,10 @@ export class AgentDaemon {
>();
private readonly signalCleanupHandlers: Array<() => void> = [];
private readonly cronStore: AgentCronJobStore;
+ private readonly agentDir: string;
private readonly cronScheduler: AgentCronScheduler;
private readonly agentMessageRateLimiter = new AgentSessionMessageRateLimiter();
+ private readonly remoteAgentPeers = new Map<string, AgentSessionMessageAgentSummary>();
private readonly agentMessagePendingReservations = new Map<string, number>();
private readonly agentMessageTargetLocks = new Map<string, Promise<void>>();
private readonly agentMessageAcceptingTargets = new Set<string>();
@@ -283,6 +335,9 @@ export class AgentDaemon {
// Sessions inserted into `sessions` but still awaiting extension binding;
// visible to host controllers during bind, excluded from targeting.
private readonly bindingSessions = new Set<string>();
+ private restoreActiveSessionId: string | undefined;
+ private supervisorMonitorTimer?: ReturnType<typeof setTimeout>;
+ private supervisorLaunchInProgress = false;
private agentMessagesPaused = false;
private readonly summarizer = new DaemonSessionSummarizer(
() => [...this.sessions.values()],
@@ -299,6 +354,7 @@ export class AgentDaemon {
});
},
);
+ private readonly recoveryJournal?: WorkerRecoveryJournal;
constructor(
private readonly socketPath: string,
@@ -307,7 +363,15 @@ export class AgentDaemon {
if (!options.defaultSessionConfig.agentDir) {
throw new Error("Daemon config is missing agentDir");
}
- this.cronStore = new AgentCronJobStore(getCronJobsPath(options.defaultSessionConfig.agentDir));
+ this.agentDir = options.defaultSessionConfig.agentDir;
+ this.cronStore = options.worker
+ ? AgentCronJobStore.forSessionArtifacts()
+ : new AgentCronJobStore(getCronJobsPath(this.agentDir));
+ this.restoreActiveSessionId = options.worker?.restoreActiveSessionId;
+ const recoveryJournalPath = process.env[DAEMON_WORKER_RECOVERY_JOURNAL_ENV];
+ if (options.worker && recoveryJournalPath) {
+ this.recoveryJournal = new WorkerRecoveryJournal(recoveryJournalPath);
+ }
this.cronScheduler = new AgentCronScheduler(this.cronStore, {
runJob: (job) => this.runCronJob(job),
onError: (job, error) => {
@@ -383,6 +447,166 @@ export class AgentDaemon {
if (!this.shuttingDown) {
this.cronScheduler.start();
}
+ this.startSupervisorMonitor();
+ }
+
+ private startSupervisorMonitor(): void {
+ const supervisorSocketPath = process.env[DAEMON_WORKER_SUPERVISOR_SOCKET_ENV];
+ if (!this.options.worker || !supervisorSocketPath) {
+ return;
+ }
+ this.scheduleSupervisorAvailabilityCheck(supervisorSocketPath, 1500);
+ }
+
+ private scheduleSupervisorAvailabilityCheck(supervisorSocketPath: string, delayMs: number): void {
+ if (this.shuttingDown || this.hasAuthenticatedSupervisorConnection()) {
+ return;
+ }
+ if (this.supervisorMonitorTimer) {
+ clearTimeout(this.supervisorMonitorTimer);
+ }
+ this.supervisorMonitorTimer = setTimeout(() => {
+ this.supervisorMonitorTimer = undefined;
+ void this.checkSupervisorAvailability(supervisorSocketPath);
+ }, delayMs);
+ }
+
+ private async checkSupervisorAvailability(supervisorSocketPath: string): Promise<void> {
+ if (this.shuttingDown || this.hasAuthenticatedSupervisorConnection()) {
+ return;
+ }
+ if (await this.canConnectToSupervisor(supervisorSocketPath)) {
+ return;
+ }
+ await this.launchReplacementSupervisor(supervisorSocketPath);
+ if (!this.shuttingDown && !this.hasAuthenticatedSupervisorConnection()) {
+ this.scheduleSupervisorAvailabilityCheck(supervisorSocketPath, 5000);
+ }
+ }
+
+ private hasAuthenticatedSupervisorConnection(): boolean {
+ return [...this.clients].some((client) => client.authenticated === true);
+ }
+
+ private clearSupervisorAvailabilityCheck(): void {
+ if (this.supervisorMonitorTimer) {
+ clearTimeout(this.supervisorMonitorTimer);
+ this.supervisorMonitorTimer = undefined;
+ }
+ }
+
+ private canConnectToSupervisor(socketPath: string): Promise<boolean> {
+ return new Promise((resolveConnect) => {
+ const socket = createConnection(socketPath);
+ let settled = false;
+ const finish = (connected: boolean) => {
+ if (settled) {
+ return;
+ }
+ settled = true;
+ clearTimeout(timeout);
+ socket.removeAllListeners();
+ socket.destroy();
+ resolveConnect(connected);
+ };
+ const timeout = setTimeout(() => finish(false), 250);
+ socket.once("connect", () => finish(true));
+ socket.once("error", () => finish(false));
+ });
+ }
+
+ private async launchReplacementSupervisor(supervisorSocketPath: string): Promise<void> {
+ if (this.supervisorLaunchInProgress || this.shuttingDown) {
+ return;
+ }
+ this.supervisorLaunchInProgress = true;
+ const key = createHash("sha256").update(supervisorSocketPath).digest("hex").slice(0, 12);
+ const lockDirectory = join(dirname(supervisorSocketPath), `.supervisor-launch-${key}.lock`);
+ let ownsLock = false;
+ try {
+ for (let attempt = 0; attempt < 3 && !ownsLock; attempt++) {
+ const token = randomUUID();
+ const candidateDirectory = `${lockDirectory}.candidate-${process.pid}-${token}`;
+ mkdirSync(candidateDirectory, { mode: 0o700 });
+ writeFileSync(join(candidateDirectory, "pid"), `${process.pid}\n`, { mode: 0o600 });
+ try {
+ renameSync(candidateDirectory, lockDirectory);
+ ownsLock = true;
+ break;
+ } catch (error) {
+ rmSync(candidateDirectory, { recursive: true, force: true });
+ const code = (error as NodeJS.ErrnoException).code;
+ if (code !== "EEXIST" && code !== "ENOTEMPTY") {
+ throw error;
+ }
+ let ownerPid: number | undefined;
+ try {
+ ownerPid = Number(readFileSync(join(lockDirectory, "pid"), "utf8").trim());
+ } catch {
+ // An invalid owner is reclaimed atomically below.
+ }
+ if (ownerPid && this.isProcessAlive(ownerPid)) {
+ return;
+ }
+ const staleDirectory = `${lockDirectory}.stale-${process.pid}-${token}`;
+ try {
+ renameSync(lockDirectory, staleDirectory);
+ rmSync(staleDirectory, { recursive: true, force: true });
+ } catch (reclaimError) {
+ if ((reclaimError as NodeJS.ErrnoException).code !== "ENOENT") {
+ throw reclaimError;
+ }
+ }
+ }
+ }
+ if (!ownsLock) {
+ return;
+ }
+ if (await this.canConnectToSupervisor(supervisorSocketPath)) {
+ return;
+ }
+ const launch = createCliSubprocessLaunchSpec(["--mode", "daemon", "--daemon-socket", supervisorSocketPath]);
+ const environment = { ...process.env };
+ delete environment[DAEMON_WORKER_ROLE_ENV];
+ delete environment[DAEMON_WORKER_TOKEN_ENV];
+ delete environment[DAEMON_WORKER_ACTIVE_SESSION_ID_ENV];
+ delete environment[DAEMON_WORKER_RECOVERY_JOURNAL_ENV];
+ delete environment[DAEMON_WORKER_SUPERVISOR_SOCKET_ENV];
+ delete environment[ORPHAN_PROCESS_JOURNAL_ENV];
+ delete environment[SESSION_LEASES_ENABLED_ENV];
+ delete environment[SESSION_LEASE_OWNER_ID_ENV];
+ const child = spawn(launch.command, launch.args, {
+ cwd: this.options.defaultSessionConfig.cwd ?? process.cwd(),
+ detached: true,
+ env: environment,
+ stdio: "ignore",
+ });
+ child.unref();
+ const deadline = Date.now() + 10_000;
+ while (!this.shuttingDown && Date.now() < deadline) {
+ if (await this.canConnectToSupervisor(supervisorSocketPath)) {
+ this.log(`launched replacement supervisor on ${supervisorSocketPath}`);
+ return;
+ }
+ await delay(50);
+ }
+ } catch (error) {
+ this.log(`failed to launch replacement supervisor: ${String(error)}`);
+ } finally {
+ if (ownsLock) {
+ rmSync(lockDirectory, { recursive: true, force: true });
+ }
+ this.supervisorLaunchInProgress = false;
+ }
+ }
+
+ private isProcessAlive(pid: number): boolean {
+ try {
+ process.kill(pid, 0);
+ return true;
+ } catch (error) {
+ return (error as NodeJS.ErrnoException).code === "EPERM";
+ }
}
private cleanupSocketPath(): void {
@@ -420,11 +644,19 @@ export class AgentDaemon {
onStateCreated?: (state: ActiveSessionState) => void,
runtimeOpenGuard?: RuntimeOpenGuard,
): Promise<ActiveSessionState> {
+ const restoredActiveSessionId = runtime.metadata.kind === "top-level" ? this.restoreActiveSessionId : undefined;
+ if (restoredActiveSessionId) {
+ this.restoreActiveSessionId = undefined;
+ }
const state: ActiveSessionState = {
- activeSessionId: createActiveSessionId(this.sessions),
+ activeSessionId:
+ restoredActiveSessionId && !this.sessions.has(restoredActiveSessionId)
+ ? restoredActiveSessionId
+ : createActiveSessionId(this.sessions),
runtime,
clients: new Set(),
extensionUiRequests: new Map(),
+ eventGeneration: createActiveSessionId(),
lastEventSequence: 0,
clientEnv,
};
@@ -455,6 +687,7 @@ export class AgentDaemon {
} finally {
this.bindingSessions.delete(state.activeSessionId);
}
+ this.registerCronStoreForState(state);
this.rebindCronJobsToState(state);
if (runtime.metadata.kind !== "subagent") {
// Mark the session as daemon-resident so a restarted daemon can
@@ -468,6 +701,7 @@ export class AgentDaemon {
}
// Restore the last persisted status so it shows before the first sweep.
this.summarizer.seed(state);
+ this.recordWorkerRecoveryState(state, "ready");
return state;
}
@@ -483,9 +717,24 @@ export class AgentDaemon {
const summaryState = state.summaryState as ActiveSessionState["summaryState"];
state.runtime.session.setCurrentRecap(summaryState?.summary);
}
+ this.registerCronStoreForState(state);
this.rebindCronJobsToState(state);
}
+ private registerCronStoreForState(state: ActiveSessionState): void {
+ if (!this.options.worker) {
+ return;
+ }
+ const session = state.runtime.session;
+ const artifactDir = session.sessionManager.getSessionArtifactDir();
+ if (!artifactDir) {
+ return;
+ }
+ if (this.cronStore.registerSessionArtifact(session.sessionId, artifactDir)) {
+ this.cronStore.recoverSessionArtifact(session.sessionId);
+ }
+ }
+
private async createRuntime(
command: Extract<DaemonCommand, { type: "create" }>,
runtimeOpenGuard?: RuntimeOpenGuard,
@@ -505,17 +754,27 @@ export class AgentDaemon {
const sessionPath = command.sessionPath
? await resolveDaemonSessionPath(command.sessionPath, cwd, config.sessionDir)
: undefined;
- const sessionManager = sessionPath
- ? await SessionManager.openAsync(sessionPath, config.sessionDir, cwdOverride)
- : command.continueRecent
- ? SessionManager.continueRecent(cwd, config.sessionDir)
- : SessionManager.create(cwd, config.sessionDir);
+ let sessionLease: SessionLease | undefined;
+ let sessionManager: SessionManager;
+ try {
+ sessionLease = acquireSessionLease(sessionPath, agentDir);
+ sessionManager = sessionPath
+ ? await SessionManager.openAsync(sessionPath, config.sessionDir, cwdOverride)
+ : command.continueRecent
+ ? SessionManager.continueRecent(cwd, config.sessionDir)
+ : SessionManager.create(cwd, config.sessionDir);
+ } catch (error) {
+ sessionLease?.release();
+ throw error;
+ }
const createState = async (): Promise<ActiveSessionState> => {
if (runtimeOpenGuard && !(await runtimeOpenGuard())) {
+ sessionLease?.release();
throw new RuntimeOpenCancelledError();
}
const existing = this.findSessionBySessionFile(sessionManager.getSessionFile());
if (existing) {
+ sessionLease?.release();
// A live runtime already owns this session file; reuse it instead of
// starting a second runtime that would interleave writes to one file.
// clientEnv adopts the first offered identity (e.g. a pane opening a
@@ -540,6 +799,7 @@ export class AgentDaemon {
sessionManager,
sessionConfig: config,
runtimeMetadata: command.runtimeMetadata,
+ sessionLease,
sessionOptions: {
customTools: [
...createAgentHeartbeatToolDefinitions({
@@ -623,6 +883,7 @@ export class AgentDaemon {
const sessionKey = resolve(sessionFile);
const pending = this.openingSessions.get(sessionKey);
if (pending) {
+ sessionLease?.release();
// Same as the reuse path above: adopt-if-absent, never overwrite the
// identity the racing creator's extensions already captured.
let state: ActiveSessionState;
@@ -663,12 +924,12 @@ export class AgentDaemon {
return "skipped";
}
const requirePersistedJob = this.cronStore.list().some((candidate) => candidate.id === job.id);
- const dueJob = requirePersistedJob ? this.cronStore.getDueJob(job.id) : job;
+ const dueJob = requirePersistedJob ? this.getRunnableCronJob(job.id) : job;
if (!dueJob) {
return "skipped";
}
const state = await this.getOrCreateCronJobSession(dueJob, requirePersistedJob);
- const runnableJob = requirePersistedJob ? this.cronStore.getDueJob(job.id) : dueJob;
+ const runnableJob = requirePersistedJob ? this.getRunnableCronJob(job.id) : dueJob;
if (
!state ||
!runnableJob ||
@@ -703,7 +964,7 @@ export class AgentDaemon {
return;
}
const getRunnableJob = (): AgentCronJob | undefined => {
- const current = requirePersistedJob ? this.cronStore.getDueJob(job.id) : runnableJob;
+ const current = requirePersistedJob ? this.getRunnableCronJob(job.id) : runnableJob;
return current && this.isCronJobRunnableForState(current, state, requirePersistedJob) ? current : undefined;
};
if (isHeartbeatCronJob(runnableJob)) {
@@ -733,6 +994,10 @@ export class AgentDaemon {
return didPrompt ? undefined : "skipped";
}
+ private getRunnableCronJob(jobId: string): AgentCronJob | undefined {
+ return this.cronStore.getClaimedJob(jobId) ?? this.cronStore.getDueJob(jobId);
+ }
+
// Wraps session.prompt so the target counts as "preparing" until the turn
// starts streaming (or the prompt settles); concurrent agent messages queue
// instead of racing agent.prompt during the preflight awaits. Refcounted so
@@ -1040,7 +1305,7 @@ export class AgentDaemon {
if (this.updateRestartPreparing) {
return undefined;
}
- const dueJob = requirePersistedJob ? this.cronStore.getDueJob(job.id) : job;
+ const dueJob = requirePersistedJob ? this.getRunnableCronJob(job.id) : job;
if (!dueJob) {
return undefined;
}
@@ -1054,7 +1319,7 @@ export class AgentDaemon {
// pending create for the same session file instead of prompting mid-bind.
if (current && !this.bindingSessions.has(current.activeSessionId)) {
this.rebindCronJobsToState(current);
- const reboundJob = requirePersistedJob ? this.cronStore.getDueJob(job.id) : dueJob;
+ const reboundJob = requirePersistedJob ? this.getRunnableCronJob(job.id) : dueJob;
return reboundJob && this.isCronJobRunnableForState(reboundJob, current, requirePersistedJob)
? current
: undefined;
@@ -1087,13 +1352,13 @@ export class AgentDaemon {
private async isPersistedCronJobRunnable(jobId: string): Promise<boolean> {
for (let attempt = 0; attempt < 2; attempt++) {
- const job = this.cronStore.getDueJob(jobId);
+ const job = this.getRunnableCronJob(jobId);
if (!job) {
return false;
}
const sessionFile = resolve(job.sessionFile);
const sessionInfo = await readSessionInfo(sessionFile);
- const current = this.cronStore.getDueJob(jobId);
+ const current = this.getRunnableCronJob(jobId);
if (!current) {
return false;
}
@@ -1120,7 +1385,7 @@ export class AgentDaemon {
if (!requirePersistedJob) {
return job.status === "active" && job.activeSessionId === state.activeSessionId;
}
- const current = this.cronStore.getDueJob(job.id);
+ const current = this.getRunnableCronJob(job.id);
const sessionFile = state.runtime.session.sessionFile;
return (
current !== undefined &&
@@ -1387,6 +1652,10 @@ export class AgentDaemon {
id: createActiveSessionId(),
socket,
attachedActiveSessionIds: new Set(),
+ catchupActiveSessionIds: new Set(),
+ backpressured: false,
+ authenticated: this.options.worker === undefined,
+ transport: this.options.worker ? "private-framed" : "jsonl",
detachInput: () => {},
supportsExtensionUi: false,
capabilities: new Set(DAEMON_DEFAULT_CLIENT_CAPABILITIES),
@@ -1401,9 +1670,37 @@ export class AgentDaemon {
serverCapabilities: DAEMON_SERVER_CAPABILITIES,
});
- client.detachInput = attachJsonlLineReader(socket, (line) => {
- void this.handleLine(client, line);
- });
+ if (client.transport === "private-framed") {
+ const decoder = new PrivateFrameDecoder(isDaemonWorkerFrameHeader);
+ const onData = (chunk: Buffer) => {
+ try {
+ for (const frame of decoder.push(chunk)) {
+ if (frame.header.kind === "command") {
+ void this.handleLine(client, frame.payload.toString("utf8"));
+ }
+ }
+ } catch (error) {
+ socket.destroy(error instanceof Error ? error : new Error(String(error)));
+ }
+ };
+ const onEnd = () => {
+ try {
+ decoder.finish();
+ } catch (error) {
+ socket.destroy(error instanceof Error ? error : new Error(String(error)));
+ }
+ };
+ socket.on("data", onData);
+ socket.on("end", onEnd);
+ client.detachInput = () => {
+ socket.off("data", onData);
+ socket.off("end", onEnd);
+ };
+ } else {
+ client.detachInput = attachJsonlLineReader(socket, (line) => {
+ void this.handleLine(client, line);
+ });
+ }
let cleanedUp = false;
const cleanup = () => {
@@ -1416,15 +1713,54 @@ export class AgentDaemon {
this.detachClient(client);
client.detachInput();
this.clients.delete(client);
+ const supervisorSocketPath = process.env[DAEMON_WORKER_SUPERVISOR_SOCKET_ENV];
+ if (this.options.worker && client.authenticated === true && supervisorSocketPath) {
+ this.scheduleSupervisorAvailabilityCheck(supervisorSocketPath, 100);
+ }
};
socket.on("close", cleanup);
socket.on("error", cleanup);
+ socket.on("drain", () => {
+ if (!client.snapshotStreaming) {
+ void this.catchUpBackpressuredClient(client);
+ }
+ });
}
private async handleLine(client: DaemonSocketClient, line: string): Promise<void> {
let command: DaemonCommand;
try {
- const parsed = JSON.parse(line) as { id?: unknown; type?: unknown };
+ const wireValue = JSON.parse(line) as unknown;
+ const parsed = (
+ isDaemonCommandEnvelope(wireValue) ? { ...wireValue.command, id: wireValue.id } : wireValue
+ ) as {
+ id?: unknown;
+ type?: unknown;
+ token?: unknown;
+ activeSessionId?: unknown;
+ capabilities?: unknown;
+ supportsExtensionUi?: unknown;
+ job?: unknown;
+ };
+ if (isDaemonCommandEnvelope(wireValue) && wireValue.clientId) {
+ client.id = wireValue.clientId;
+ }
+ if (this.options.worker && client.authenticated !== true) {
+ const commandId = typeof parsed.id === "string" ? parsed.id : undefined;
+ if (parsed.type !== "worker_auth" || parsed.token !== this.options.worker.authenticationToken) {
+ this.write(client, failure(commandId, "worker_auth", "Worker authentication failed"));
+ client.socket.end();
+ return;
+ }
+ client.authenticated = true;
+ this.clearSupervisorAvailabilityCheck();
+ this.write(client, { id: commandId, type: "response", command: "worker_auth", success: true });
+ return;
+ }
+ if (this.options.worker && typeof parsed.type === "string" && parsed.type.startsWith("worker_")) {
+ await this.handleWorkerCommand(client, parsed as DaemonWorkerCommand);
+ return;
+ }
if (typeof parsed.type !== "string" || !DAEMON_COMMAND_TYPES.has(parsed.type)) {
const commandName = typeof parsed.type === "string" ? parsed.type : "unknown";
const commandId = typeof parsed.id === "string" ? parsed.id : undefined;
@@ -1453,14 +1789,120 @@ export class AgentDaemon {
}
}
+ private async handleWorkerCommand(client: DaemonSocketClient, command: DaemonWorkerCommand): Promise<void> {
+ try {
+ switch (command.type) {
+ case "worker_auth":
+ this.write(client, failure(command.id, command.type, "Worker is already authenticated"));
+ return;
+ case "worker_subscribe": {
+ const state = this.getBoundSessionState(command.activeSessionId);
+ setDaemonClientSessionCapabilities(
+ client,
+ state.activeSessionId,
+ normalizeClientCapabilities(command.capabilities, command.supportsExtensionUi),
+ );
+ state.clients.add(client);
+ client.attachedActiveSessionIds.add(state.activeSessionId);
+ this.write(client, success(command.id, "attach", summaryForActiveSession(state)));
+ return;
+ }
+ case "worker_unsubscribe": {
+ const state = this.getSessionState(command.activeSessionId);
+ this.detachClientFromSession(client, state);
+ this.write(client, success(command.id, "detach"));
+ return;
+ }
+ case "worker_sync_agent_peers":
+ this.remoteAgentPeers.clear();
+ for (const peer of command.peers) {
+ this.remoteAgentPeers.set(peer.activeSessionId, peer);
+ }
+ this.write(client, {
+ id: command.id,
+ type: "response",
+ command: command.type,
+ success: true,
+ });
+ return;
+ case "worker_archive_and_shutdown": {
+ for (const state of [...this.sessions.values()]) {
+ await this.closeSession(state, "killed");
+ }
+ this.write(client, {
+ id: command.id,
+ type: "response",
+ command: command.type,
+ success: true,
+ });
+ setImmediate(() => void this.shutdown(0));
+ return;
+ }
+ case "worker_deliver_message": {
+ const receipt = await this.sendAgentSessionMessage({
+ targetSelector: command.targetActiveSessionId,
+ message: command.message,
+ sender: command.sender,
+ senderKey: command.sender.activeSessionId ?? `client:${command.sender.clientId}`,
+ deliveryMode: command.deliveryMode,
+ origin: "agent",
+ });
+ this.write(client, {
+ id: command.id,
+ type: "response",
+ command: command.type,
+ success: true,
+ data: receipt,
+ });
+ return;
+ }
+ case "worker_prepare_update": {
+ const manifest = this.prepareUpdateRestartCheckpoint();
+ this.write(client, {
+ id: command.id,
+ type: "response",
+ command: command.type,
+ success: true,
+ data: manifest,
+ });
+ return;
+ }
+ case "worker_commit_update": {
+ const manifest = await this.commitPreparedUpdateRestart();
+ this.write(client, {
+ id: command.id,
+ type: "response",
+ command: command.type,
+ success: true,
+ data: manifest,
+ });
+ return;
+ }
+ case "worker_cancel_update":
+ this.cancelPreparedUpdateRestart();
+ this.write(client, {
+ id: command.id,
+ type: "response",
+ command: command.type,
+ success: true,
+ });
+ return;
+ }
+ } catch (error) {
+ this.write(client, failure(command.id, command.type, error, serializeDaemonError(error)));
+ }
+ }
+
private async handleCommand(
client: DaemonSocketClient,
command: DaemonCommand,
): Promise<DaemonResponse | undefined> {
- if (this.updateRestartPreparing && command.type !== "shutdown") {
+ if (this.updateRestartPreparing && command.type !== "shutdown" && command.type !== "ack_result") {
throw new Error("Daemon is preparing an update restart");
}
switch (command.type) {
+ case "ack_result":
+ return undefined;
case "list": {
const activeSessions = Array.from(this.sessions.values());
if (!command.all) {
@@ -1540,12 +1982,62 @@ export class AgentDaemon {
if (command.clientId) {
client.id = command.clientId;
}
- client.capabilities = normalizeClientCapabilities(command.capabilities, command.supportsExtensionUi);
- client.supportsExtensionUi = client.capabilities.has("extension_ui");
+ setDaemonClientSessionCapabilities(
+ client,
+ state.activeSessionId,
+ normalizeClientCapabilities(command.capabilities, command.supportsExtensionUi),
+ );
+ const streamsSnapshot =
+ client.transport === "private-framed" &&
+ daemonClientCapabilitiesForSession(client, state.activeSessionId).has("chunked_snapshot");
this.adoptClientEnv(state, filterClientEnv(command.env));
+ if (streamsSnapshot) {
+ markClientSnapshotStreaming(client, state.activeSessionId);
+ }
state.clients.add(client);
client.attachedActiveSessionIds.add(state.activeSessionId);
- const result = this.createAttachResult(client, state, command);
+ let result: DaemonAttachResult;
+ try {
+ result = this.createAttachResult(client, state, command);
+ } catch (error) {
+ state.clients.delete(client);
+ client.attachedActiveSessionIds.delete(state.activeSessionId);
+ removeDaemonClientSessionCapabilities(client, state.activeSessionId);
+ if (streamsSnapshot) {
+ finishClientSnapshotStreaming(client, state.activeSessionId);
+ }
+ throw error;
+ }
+ if (streamsSnapshot) {
+ let transcript: SnapshotTranscriptCache;
+ try {
+ transcript = new SnapshotTranscriptCache({
+ activeSessionId: state.activeSessionId,
+ snapshotId: `${state.activeSessionId}-${state.eventGeneration}-${state.lastEventSequence}`,
+ messages: result.snapshot.messages,
+ cacheRoot: join(this.agentDir, "worker-snapshot-cache"),
+ targetChunkBytes: SNAPSHOT_TARGET_CHUNK_BYTES,
+ });
+ } catch (error) {
+ state.clients.delete(client);
+ client.attachedActiveSessionIds.delete(state.activeSessionId);
+ removeDaemonClientSessionCapabilities(client, state.activeSessionId);
+ finishClientSnapshotStreaming(client, state.activeSessionId);
+ throw error;
+ }
+ const streamedResult: DaemonAttachResult = {
+ ...result,
+ messages: result.messages ? [] : undefined,
+ snapshot: { ...result.snapshot, messages: [] },
+ snapshotStream: {
+ id: transcript.snapshotId,
+ messageCount: result.snapshot.messages.length,
+ targetChunkBytes: transcript.targetChunkBytes,
+ },
+ };
+ setImmediate(() => void this.streamWorkerSnapshot(client, streamedResult, transcript, "attach", true));
+ return success(command.id, "attach", streamedResult);
+ }
// Slim clients consume only the command response; legacy clients (e.g.
// the plain daemon attach REPL) read state/messages off this event.
// Skipping it for slim clients halves the attach payload.
@@ -1642,6 +2134,7 @@ export class AgentDaemon {
source: "rpc",
preflightResult: (didSucceed) => {
if (didSucceed) {
+ this.recordWorkerRecoveryState(state, "prompt_accepted", true);
sendSuccessResponse();
}
},
@@ -1675,6 +2168,7 @@ export class AgentDaemon {
agentMessageId: command.agentMessageId,
});
}
+ this.recordWorkerRecoveryState(state, "steer_queued", true);
return success(command.id, "steer");
}
@@ -1695,6 +2189,9 @@ export class AgentDaemon {
agentMessageId: command.agentMessageId,
});
}
+ if (queued) {
+ this.recordWorkerRecoveryState(state, "follow_up_queued", true);
+ }
return success(command.id, "follow_up", { queued });
}
@@ -2219,6 +2716,15 @@ export class AgentDaemon {
);
return success(command.id, "prepare_update_restart", await this.prepareUpdateRestart());
+ case "retry_worker":
+ throw new Error("Worker retry is only available through the daemon supervisor");
+
+ case "restart":
+ setImmediate(() => {
+ void this.shutdown(0);
+ });
+ return success(command.id, command.type);
+
case "shutdown":
this.log(`shutdown command received over socket; ${this.sessions.size} active session(s) will be closed`);
setImmediate(() => {
@@ -2238,14 +2744,19 @@ export class AgentDaemon {
command.resumeCursor?.activeSessionId && command.resumeCursor.activeSessionId !== state.activeSessionId
? {
status: "unavailable" as const,
- fromSequence: command.resumeCursor.eventSequence,
+ fromSequence:
+ "sequence" in command.resumeCursor
+ ? command.resumeCursor.sequence
+ : command.resumeCursor.eventSequence,
toSequence: state.lastEventSequence,
+ toCursor: { generation: state.eventGeneration, sequence: state.lastEventSequence },
reason: "resume_cursor_session_mismatch",
}
- : createDaemonReplayInfo(command.resumeCursor, state.lastEventSequence);
+ : createDaemonReplayInfo(command.resumeCursor, state.lastEventSequence, state.eventGeneration);
// Slim clients read summary/messages from the snapshot; duplicating them at
// the top level would serialize the full history twice more per attach.
- const slim = client.capabilities.has("slim_attach");
+ const capabilities = daemonClientCapabilitiesForSession(client, state.activeSessionId);
+ const slim = capabilities.has("slim_attach");
return {
protocol: DAEMON_PROTOCOL_INFO,
activeSessionId: state.activeSessionId,
@@ -2253,9 +2764,10 @@ export class AgentDaemon {
snapshot,
replay,
lastEventSequence: state.lastEventSequence,
+ lastEventCursor: { generation: state.eventGeneration, sequence: state.lastEventSequence },
client: {
id: client.id,
- capabilities: [...client.capabilities],
+ capabilities: [...capabilities],
},
};
}
@@ -2282,11 +2794,127 @@ export class AgentDaemon {
// context from messages + state, and fetch the full session tree lazily
// when the tree/branch selector opens.
lastEventSequence: state.lastEventSequence,
+ lastEventCursor: { generation: state.eventGeneration, sequence: state.lastEventSequence },
...(parent ? { parent } : {}),
...(children.length > 0 ? { children } : {}),
};
}
+ private async streamWorkerSnapshot(
+ client: DaemonSocketClient,
+ result: DaemonAttachResult,
+ transcript: SnapshotTranscriptCache,
+ purpose: "attach" | "replacement" | "catchup" = "attach",
+ snapshotAlreadyMarked = false,
+ ): Promise<void> {
+ const stream = result.snapshotStream;
+ if (!stream) {
+ if (snapshotAlreadyMarked) {
+ finishClientSnapshotStreaming(client, result.activeSessionId);
+ }
+ transcript.dispose();
+ return;
+ }
+ if (!snapshotAlreadyMarked) {
+ markClientSnapshotStreaming(client, result.activeSessionId);
+ }
+ if (client.socket.destroyed) {
+ finishClientSnapshotStreaming(client, result.activeSessionId);
+ transcript.dispose();
+ return;
+ }
+ const { messages: _messages, ...snapshot } = result.snapshot;
+ try {
+ if (
+ !(await this.writeWorkerSnapshotRecord(
+ client,
+ {
+ type: "session_snapshot_begin",
+ activeSessionId: result.activeSessionId,
+ snapshotId: stream.id,
+ snapshot,
+ messageCount: stream.messageCount,
+ targetChunkBytes: stream.targetChunkBytes,
+ purpose: purpose === "catchup" ? "resync" : purpose,
+ },
+ purpose,
+ ))
+ ) {
+ return;
+ }
+ for (let index = 0; index < transcript.chunkCount; index++) {
+ const headerMessage: DaemonOutbound = {
+ type: "session_snapshot_chunk",
+ activeSessionId: result.activeSessionId,
+ snapshotId: stream.id,
+ index,
+ messages: [],
+ };
+ if (!(await this.writeWorkerSnapshotBuffer(client, transcript.readChunk(index), headerMessage, purpose))) {
+ return;
+ }
+ }
+ await this.writeWorkerSnapshotRecord(
+ client,
+ {
+ type: "session_snapshot_end",
+ activeSessionId: result.activeSessionId,
+ snapshotId: stream.id,
+ chunkCount: transcript.chunkCount,
+ lastEventSequence: result.lastEventSequence,
+ lastEventCursor: result.lastEventCursor,
+ },
+ purpose,
+ );
+ } finally {
+ finishClientSnapshotStreaming(client, result.activeSessionId);
+ transcript.dispose();
+ if (!client.snapshotStreaming && client.catchupActiveSessionIds?.size) {
+ void this.catchUpBackpressuredClient(client);
+ }
+ }
+ }
+
+ private writeWorkerSnapshotRecord(
+ client: DaemonSocketClient,
+ message: DaemonOutbound,
+ purpose: "attach" | "replacement" | "catchup",
+ ): Promise<boolean> {
+ return this.writeWorkerSnapshotBuffer(client, Buffer.from(serializeJsonLine(message)), message, purpose);
+ }
+
+ private async writeWorkerSnapshotBuffer(
+ client: DaemonSocketClient,
+ buffer: Buffer,
+ message: DaemonOutbound,
+ purpose: "attach" | "replacement" | "catchup",
+ ): Promise<boolean> {
+ if (client.socket.destroyed) {
+ return false;
+ }
+ if (this.writeSerialized(client, buffer, message, "jsonl", purpose)) {
+ return true;
+ }
+ return new Promise<boolean>((resolveDrain) => {
+ let settled = false;
+ const finish = (value: boolean) => {
+ if (settled) {
+ return;
+ }
+ settled = true;
+ client.socket.off("drain", onDrain);
+ client.socket.off("close", onClose);
+ client.socket.off("error", onClose);
+ resolveDrain(value);
+ };
+ const onDrain = () => finish(true);
+ const onClose = () => finish(false);
+ client.socket.once("drain", onDrain);
+ client.socket.once("close", onClose);
+ client.socket.once("error", onClose);
+ });
+ }
+
private createConnectionState(state: ActiveSessionState): ReturnType<typeof createAgentConnectionState> {
const connectionState = createAgentConnectionState(state.runtime, state.activeSessionId);
connectionState.heartbeat = this.cronStore.getLatestHeartbeat(state.activeSessionId) ?? null;
@@ -2333,9 +2961,16 @@ export class AgentDaemon {
}
private createAgentMessageListResult(current: ActiveSessionState): AgentSessionMessageListResult {
+ const localAgents = this.listTargetableSessionStates(current).map((state) =>
+ this.createAgentMessageAgentSummary(state),
+ );
+ const localIds = new Set(localAgents.map((agent) => agent.activeSessionId));
return {
current: this.createAgentSessionMessageEndpoint(current),
- agents: this.listTargetableSessionStates(current).map((state) => this.createAgentMessageAgentSummary(state)),
+ agents: [
+ ...localAgents,
+ ...[...this.remoteAgentPeers.values()].filter((peer) => !localIds.has(peer.activeSessionId)),
+ ],
};
}
@@ -2422,6 +3057,7 @@ export class AgentDaemon {
targetSelector: string;
message: string;
fromState?: ActiveSessionState;
+ sender?: AgentSessionMessageSender;
clientId?: string;
senderKey?: string;
deliveryMode?: AgentSessionMessagePayload["deliveryMode"];
@@ -2431,7 +3067,20 @@ export class AgentDaemon {
throw new Error("Agent messaging is paused");
}
const targetSelector = assertDirectAgentMessageTarget(options.targetSelector);
- const targetState = this.getBoundSessionState(targetSelector);
+ let targetState: ActiveSessionState;
+ try {
+ targetState = this.getBoundSessionState(targetSelector);
+ } catch (error) {
+ if (this.options.worker && options.fromState) {
+ return this.sendRemoteAgentSessionMessage(
+ options.fromState,
+ targetSelector,
+ options.message,
+ options.deliveryMode,
+ );
+ }
+ throw error;
+ }
if (options.fromState?.activeSessionId === targetState.activeSessionId) {
throw new Error("Agent messaging cannot target the sending session");
}
@@ -2449,7 +3098,9 @@ export class AgentDaemon {
id: createAgentSessionMessageId(),
source: AGENT_MESSAGE_SOURCE,
message,
- from: this.createAgentSessionMessageSender(options.fromState, options.clientId ?? options.origin),
+ from:
+ options.sender ??
+ this.createAgentSessionMessageSender(options.fromState, options.clientId ?? options.origin),
target: this.createAgentSessionMessageEndpoint(targetState),
deliveryMode: options.deliveryMode ?? "auto",
};
@@ -2479,6 +3130,50 @@ export class AgentDaemon {
}
}
+ private async sendRemoteAgentSessionMessage(
+ fromState: ActiveSessionState,
+ targetSelector: string,
+ message: string,
+ deliveryMode?: AgentSessionMessagePayload["deliveryMode"],
+ ): Promise<AgentSessionMessageReceipt> {
+ const supervisorSocketPath = process.env[DAEMON_WORKER_SUPERVISOR_SOCKET_ENV];
+ if (!supervisorSocketPath) {
+ throw new Error(`Unknown active session: ${targetSelector}`);
+ }
+ const deadline = Date.now() + 30_000;
+ let lastError: unknown;
+ while (Date.now() < deadline && !this.shuttingDown) {
+ const client = new DaemonClient(supervisorSocketPath);
+ try {
+ await client.connect(1000);
+ await client.waitForHello(1000);
+ const response = await client.request(
+ {
+ type: "send_message",
+ targetActiveSessionId: targetSelector,
+ message,
+ fromActiveSessionId: fromState.activeSessionId,
+ deliveryMode,
+ },
+ 30_000,
+ );
+ if (!response.success) {
+ throw deserializeDaemonError(response);
+ }
+ if (!response.data || typeof response.data !== "object") {
+ throw new Error("Supervisor returned an invalid agent-message receipt");
+ }
+ return response.data as AgentSessionMessageReceipt;
+ } catch (error) {
+ lastError = error;
+ } finally {
+ client.close();
+ }
+ await new Promise((resolveDelay) => setTimeout(resolveDelay, 250));
+ }
+ throw lastError instanceof Error ? lastError : new Error(`Unknown active session: ${targetSelector}`);
+ }
+
private async acceptAgentSessionMessage(
targetState: ActiveSessionState,
payload: AgentSessionMessagePayload,
@@ -2565,6 +3260,9 @@ export class AgentDaemon {
}
private isDiscardableDraft(state: ActiveSessionState): boolean {
+ if (this.options.worker) {
+ return false;
+ }
if (state.clients.size > 0) {
return false;
}
@@ -2705,7 +3403,7 @@ export class AgentDaemon {
}
private writeUpdateRestartManifest(manifest: DaemonUpdateRestartManifest): void {
- const path = getDaemonUpdateRestartManifestPath(this.options.defaultSessionConfig.agentDir);
+ const path = getDaemonUpdateRestartManifestPath(this.agentDir);
mkdirSync(dirname(path), { recursive: true });
writeFileSync(path, `${JSON.stringify(manifest)}\n`);
}
@@ -2726,52 +3424,77 @@ export class AgentDaemon {
return depth;
}
- private async prepareUpdateRestart(): Promise<DaemonUpdateRestartManifest> {
+ private prepareUpdateRestartCheckpoint(): DaemonUpdateRestartManifest {
if (this.updateRestartPreparing) {
throw new Error("Daemon is already preparing an update restart");
}
this.updateRestartPreparing = true;
- // Keep persisted jobs for the replacement daemon, but stop this daemon from firing them after sessions detach.
+ // Keep persisted jobs for the replacement daemon, but stop this process
+ // from accepting another scheduled mutation while its checkpoint is held.
this.cronScheduler.stop();
try {
const states = [...this.sessions.values()];
const restartSessions = states
- .map((state) => [state, this.createUpdateRestartSession(state)] as const)
- .filter(
- (entry): entry is readonly [ActiveSessionState, DaemonUpdateRestartSession] => entry[1] !== undefined,
- )
+ .map((state) => this.createUpdateRestartSession(state))
+ .filter((session): session is DaemonUpdateRestartSession => session !== undefined)
.sort(
- ([left], [right]) => this.getUpdateRestartSessionDepth(left) - this.getUpdateRestartSessionDepth(right),
+ (left, right) =>
+ this.getUpdateRestartSessionDepth(this.getSessionState(left.activeSessionId)) -
+ this.getUpdateRestartSessionDepth(this.getSessionState(right.activeSessionId)),
);
const manifest = {
createdAt: new Date().toISOString(),
- sessions: restartSessions.map(([, restartSession]) => restartSession),
+ sessions: restartSessions,
};
+ this.preparedUpdateRestartManifest = manifest;
+ return manifest;
+ } catch (error) {
+ this.cancelPreparedUpdateRestart();
+ throw error;
+ }
+ }
- this.writeUpdateRestartManifest(manifest);
-
- for (const [state, restartSession] of restartSessions) {
+ private async commitPreparedUpdateRestart(): Promise<DaemonUpdateRestartManifest> {
+ const manifest = this.preparedUpdateRestartManifest;
+ if (!this.updateRestartPreparing || !manifest) {
+ throw new Error("Daemon has no prepared update checkpoint");
+ }
+ const restartByActiveSessionId = new Map(manifest.sessions.map((session) => [session.activeSessionId, session]));
+ for (const state of this.sessions.values()) {
+ const restartSession = restartByActiveSessionId.get(state.activeSessionId);
+ if (restartSession) {
this.appendUpdateRestartMarker(state, restartSession);
}
- const restoredActiveSessionIds = new Set(restartSessions.map(([state]) => state.activeSessionId));
- const closeStates = [...states].sort(
- (left, right) => this.getUpdateRestartSessionDepth(right) - this.getUpdateRestartSessionDepth(left),
- );
- for (const state of closeStates) {
- if (this.sessions.has(state.activeSessionId)) {
- await this.closeSession(
- state,
- restoredActiveSessionIds.has(state.activeSessionId) ? "update" : "killed",
- );
- }
- }
- for (const state of [...this.sessions.values()]) {
- await this.closeSession(state, "killed");
+ }
+ const closeStates = [...this.sessions.values()].sort(
+ (left, right) => this.getUpdateRestartSessionDepth(right) - this.getUpdateRestartSessionDepth(left),
+ );
+ for (const state of closeStates) {
+ if (this.sessions.has(state.activeSessionId)) {
+ await this.closeSession(state, restartByActiveSessionId.has(state.activeSessionId) ? "update" : "killed");
}
+ }
+ for (const state of [...this.sessions.values()]) {
+ await this.closeSession(state, "killed");
+ }
+ return manifest;
+ }
- return manifest;
+ private cancelPreparedUpdateRestart(): void {
+ this.preparedUpdateRestartManifest = undefined;
+ this.updateRestartPreparing = false;
+ if (!this.shuttingDown) {
+ this.cronScheduler.start();
+ }
+ }
+
+ private async prepareUpdateRestart(): Promise<DaemonUpdateRestartManifest> {
+ const manifest = this.prepareUpdateRestartCheckpoint();
+ try {
+ this.writeUpdateRestartManifest(manifest);
+ return await this.commitPreparedUpdateRestart();
} catch (error) {
- this.updateRestartPreparing = false;
+ this.cancelPreparedUpdateRestart();
throw error;
}
}
@@ -2871,11 +3594,13 @@ export class AgentDaemon {
if (reason === "killed" || reason === "shutdown" || reason === "replaced") {
await state.runtime.session.abort().catch(() => undefined);
}
+ this.recordWorkerRecoveryState(state, `closed:${reason}`, false);
state.unsubscribe?.();
await state.runtime.dispose();
this.broadcastToSession(state, { type: "session_closed", activeSessionId: state.activeSessionId, reason });
for (const client of state.clients) {
client.attachedActiveSessionIds.delete(state.activeSessionId);
+ removeDaemonClientSessionCapabilities(client, state.activeSessionId);
}
state.clients.clear();
this.sessions.delete(state.activeSessionId);
@@ -2924,14 +3649,238 @@ export class AgentDaemon {
) {
void this.closeSession(state, "killed");
}
+ if (RECOVERY_CHECKPOINT_EVENTS.has(eventType)) {
+ this.recordWorkerRecoveryState(state, eventType);
+ }
}
this.stampRlmChildActiveSessionId(message);
const sequencedMessage = this.addSessionEventMeta(state, message);
+ let serialized: string | undefined;
for (const client of state.clients) {
if (!shouldSendDaemonOutboundToClient(client, sequencedMessage)) {
continue;
}
- this.write(client, sequencedMessage);
+ if (sequencedMessage.type === "session_closed") {
+ client.catchupActiveSessionIds?.delete(state.activeSessionId);
+ client.catchupPurposes?.delete(state.activeSessionId);
+ this.write(client, sequencedMessage);
+ continue;
+ }
+ if (client.snapshotActiveSessionIds?.has(state.activeSessionId)) {
+ this.queueClientCatchup(
+ client,
+ state.activeSessionId,
+ sequencedMessage.type === "session_replaced" ? "replacement" : "resync",
+ );
+ continue;
+ }
+ if (client.backpressured === true) {
+ this.queueClientCatchup(
+ client,
+ state.activeSessionId,
+ sequencedMessage.type === "session_replaced" ? "replacement" : "resync",
+ );
+ continue;
+ }
+ if (
+ sequencedMessage.type === "session_replaced" &&
+ client.transport === "private-framed" &&
+ daemonClientCapabilitiesForSession(client, state.activeSessionId).has("chunked_snapshot")
+ ) {
+ try {
+ const result = this.createAttachResult(client, state, {
+ type: "attach",
+ activeSessionId: state.activeSessionId,
+ });
+ const transcript = new SnapshotTranscriptCache({
+ activeSessionId: state.activeSessionId,
+ snapshotId: `${state.activeSessionId}-${state.eventGeneration}-${state.lastEventSequence}`,
+ messages: result.snapshot.messages,
+ cacheRoot: join(this.agentDir, "worker-snapshot-cache"),
+ targetChunkBytes: SNAPSHOT_TARGET_CHUNK_BYTES,
+ });
+ const accepted = this.write(client, {
+ ...sequencedMessage,
+ messages: [],
+ snapshotFollows: true,
+ });
+ if (!accepted) {
+ transcript.dispose();
+ this.queueClientCatchup(client, state.activeSessionId, "replacement");
+ continue;
+ }
+ void this.streamWorkerSnapshot(
+ client,
+ {
+ ...result,
+ messages: result.messages ? [] : undefined,
+ snapshot: { ...result.snapshot, messages: [] },
+ snapshotStream: {
+ id: transcript.snapshotId,
+ messageCount: result.snapshot.messages.length,
+ targetChunkBytes: transcript.targetChunkBytes,
+ },
+ },
+ transcript,
+ "replacement",
+ ).catch((error) => {
+ this.log(`could not stream replacement snapshot: ${String(error)}`);
+ this.queueClientCatchup(client, state.activeSessionId, "replacement");
+ if (!client.snapshotStreaming) {
+ void this.catchUpBackpressuredClient(client).catch((catchupError) =>
+ this.log(`could not catch up replacement snapshot: ${String(catchupError)}`),
+ );
+ }
+ });
+ } catch (error) {
+ this.log(`could not prepare replacement snapshot: ${String(error)}`);
+ // Continue below with the complete replacement event.
+ let accepted: boolean;
+ if (client.transport === "private-framed") {
+ accepted = this.write(client, sequencedMessage);
+ } else {
+ serialized ??= serializeJsonLine(sequencedMessage);
+ accepted = this.writeSerialized(client, serialized, sequencedMessage);
+ }
+ if (!accepted) {
+ this.queueClientCatchup(client, state.activeSessionId, "replacement");
+ }
+ }
+ continue;
+ }
+ let accepted: boolean;
+ if (client.transport === "private-framed") {
+ accepted = this.write(client, sequencedMessage);
+ } else {
+ serialized ??= serializeJsonLine(sequencedMessage);
+ accepted = this.writeSerialized(client, serialized, sequencedMessage);
+ }
+ if (!accepted) {
+ this.queueClientCatchup(
+ client,
+ state.activeSessionId,
+ sequencedMessage.type === "session_replaced" ? "replacement" : "resync",
+ );
+ }
+ }
+ }
+
+ private recordWorkerRecoveryState(state: ActiveSessionState, operation: string, busyOverride?: boolean): void {
+ if (!this.recoveryJournal) {
+ return;
+ }
+ const session = state.runtime.session;
+ const busy =
+ busyOverride ?? (isActiveSessionBusy(state) || session.isRetrying || session.hasAcceptedPromptInFlight);
+ try {
+ this.recoveryJournal.record({
+ activeSessionId: state.activeSessionId,
+ sessionId: session.sessionId,
+ ...(session.sessionFile ? { sessionFile: session.sessionFile } : {}),
+ busy,
+ operation,
+ });
+ } catch (error) {
+ this.log(`could not checkpoint worker operation state: ${String(error)}`);
+ }
+ }
+
+ private async catchUpBackpressuredClient(client: DaemonSocketClient): Promise<void> {
+ if (client.socket.destroyed) {
+ return;
+ }
+ client.backpressured = false;
+ const pending = [...(client.catchupActiveSessionIds ?? [])].map((activeSessionId) => ({
+ activeSessionId,
+ purpose: client.catchupPurposes?.get(activeSessionId) ?? ("resync" as const),
+ }));
+ client.catchupActiveSessionIds?.clear();
+ client.catchupPurposes?.clear();
+ for (let index = 0; index < pending.length; index++) {
+ const { activeSessionId, purpose } = pending[index]!;
+ const state = this.sessions.get(activeSessionId);
+ if (!state || !state.clients.has(client)) {
+ continue;
+ }
+ const result = this.createAttachResult(client, state, {
+ type: "attach",
+ activeSessionId,
+ });
+ if (
+ client.transport === "private-framed" &&
+ daemonClientCapabilitiesForSession(client, activeSessionId).has("chunked_snapshot")
+ ) {
+ if (purpose === "replacement") {
+ this.write(client, {
+ type: "session_replaced",
+ activeSessionId,
+ state: result.snapshot.state,
+ messages: [],
+ snapshotFollows: true,
+ meta: createDaemonEventMeta(
+ activeSessionId,
+ state.lastEventSequence,
+ undefined,
+ state.eventGeneration,
+ ),
+ });
+ }
+ const transcript = new SnapshotTranscriptCache({
+ activeSessionId,
+ snapshotId: `${activeSessionId}-${state.eventGeneration}-${state.lastEventSequence}`,
+ messages: result.snapshot.messages,
+ cacheRoot: join(this.agentDir, "worker-snapshot-cache"),
+ targetChunkBytes: SNAPSHOT_TARGET_CHUNK_BYTES,
+ });
+ await this.streamWorkerSnapshot(
+ client,
+ {
+ ...result,
+ messages: result.messages ? [] : undefined,
+ snapshot: { ...result.snapshot, messages: [] },
+ snapshotStream: {
+ id: transcript.snapshotId,
+ messageCount: result.snapshot.messages.length,
+ targetChunkBytes: transcript.targetChunkBytes,
+ },
+ },
+ transcript,
+ purpose === "replacement" ? "replacement" : "catchup",
+ );
+ continue;
+ }
+ const meta = createDaemonEventMeta(activeSessionId, state.lastEventSequence, undefined, state.eventGeneration);
+ const catchup: DaemonOutbound =
+ purpose === "replacement"
+ ? {
+ type: "session_replaced",
+ activeSessionId,
+ state: result.snapshot.state,
+ messages: result.snapshot.messages,
+ meta,
+ }
+ : { type: "session_resynced", activeSessionId, snapshot: result.snapshot, meta };
+ if (!this.write(client, catchup)) {
+ for (const remaining of pending.slice(index + 1)) {
+ this.queueClientCatchup(client, remaining.activeSessionId, remaining.purpose);
+ }
+ return;
+ }
+ }
+ }
+
+ private queueClientCatchup(
+ client: DaemonSocketClient,
+ activeSessionId: string,
+ purpose: "replacement" | "resync" = "resync",
+ ): void {
+ if (!client.catchupActiveSessionIds) {
+ client.catchupActiveSessionIds = new Set();
+ }
+ client.catchupActiveSessionIds.add(activeSessionId);
+ client.catchupPurposes ??= new Map();
+ if (purpose === "replacement" || !client.catchupPurposes.has(activeSessionId)) {
+ client.catchupPurposes.set(activeSessionId, purpose);
}
}
@@ -2957,16 +3906,56 @@ export class AgentDaemon {
if (!isSequencedSessionOutbound(message) || message.meta) {
return message;
}
- const meta = createDaemonEventMeta(state.activeSessionId, state.lastEventSequence + 1);
+ const meta = createDaemonEventMeta(
+ state.activeSessionId,
+ state.lastEventSequence + 1,
+ undefined,
+ state.eventGeneration,
+ );
state.lastEventSequence = meta.sequence ?? state.lastEventSequence;
return { ...message, meta };
}
- private write(client: DaemonSocketClient, message: DaemonOutbound): void {
+ private write(client: DaemonSocketClient, message: DaemonOutbound): boolean {
+ const compactDelta = client.transport === "private-framed" ? createCompactAssistantDelta(message) : undefined;
+ return this.writeSerialized(
+ client,
+ serializeJsonLine(compactDelta ?? message),
+ message,
+ compactDelta ? "assistant-delta" : "jsonl",
+ );
+ }
+
+ private writeSerialized(
+ client: DaemonSocketClient,
+ line: string | Buffer,
+ message: DaemonOutbound,
+ payloadEncoding: "jsonl" | "assistant-delta" = "jsonl",
+ snapshotPurpose?: "attach" | "replacement" | "catchup",
+ ): boolean {
if (client.socket.destroyed) {
- return;
+ return false;
}
- client.socket.write(serializeJsonLine(message));
+ const wireData =
+ client.transport === "private-framed"
+ ? encodePrivateFrame<DaemonWorkerFrameHeader>(
+ {
+ kind: "outbound",
+ outboundType: message.type,
+ ...("id" in message && typeof message.id === "string" ? { requestId: message.id } : {}),
+ ...(hasDaemonOutboundActiveSessionId(message) ? { activeSessionId: message.activeSessionId } : {}),
+ ...(message.type === "session_event" ? { sessionEventType: message.event.type } : {}),
+ payloadEncoding,
+ ...(snapshotPurpose ? { snapshotPurpose } : {}),
+ },
+ typeof line === "string" ? Buffer.from(line) : line,
+ )
+ : line;
+ const accepted = client.socket.write(wireData);
+ if (!accepted) {
+ client.backpressured = true;
+ }
+ return accepted;
}
private abortSideQuestionsFor(client: DaemonSocketClient, activeSessionId: string): void {
@@ -3012,6 +4001,10 @@ export class AgentDaemon {
process.exit(exitCode);
}
this.shuttingDown = true;
+ if (this.supervisorMonitorTimer) {
+ clearTimeout(this.supervisorMonitorTimer);
+ this.supervisorMonitorTimer = undefined;
+ }
this.log(`shutting down (exit ${exitCode}); closing ${this.sessions.size} active session(s)`);
const closingReason: DaemonClosingReason = this.updateRestartPreparing ? "update" : "shutdown";
for (const client of this.clients) {
@@ -3042,6 +4035,12 @@ export class AgentDaemon {
}
}
+function hasDaemonOutboundActiveSessionId(
+ message: DaemonOutbound,
+): message is DaemonOutbound & { activeSessionId: string } {
+ return "activeSessionId" in message && typeof message.activeSessionId === "string";
+}
+
function serializeSavedSessionInfo(session: SessionInfo): DaemonSavedSessionInfo {
return {
path: session.path,
@@ -3073,11 +4072,67 @@ export function getChildActiveSessionStates(
export function detachClientFromActiveSession(client: DaemonSocketClient, state: ActiveSessionState): void {
state.clients.delete(client);
client.attachedActiveSessionIds.delete(state.activeSessionId);
+ removeDaemonClientSessionCapabilities(client, state.activeSessionId);
if (state.clients.size === 0) {
cancelPendingExtensionUiRequests(state);
}
}
+export function setDaemonClientSessionCapabilities(
+ client: DaemonSocketClient,
+ activeSessionId: string,
+ capabilities: ReadonlySet<DaemonClientCapability>,
+): void {
+ client.capabilitiesByActiveSessionId ??= new Map();
+ client.capabilitiesByActiveSessionId.set(activeSessionId, new Set(capabilities));
+ client.supportsExtensionUi = [...client.capabilitiesByActiveSessionId.values()].some((value) =>
+ value.has("extension_ui"),
+ );
+}
+
+function removeDaemonClientSessionCapabilities(client: DaemonSocketClient, activeSessionId: string): void {
+ client.capabilitiesByActiveSessionId?.delete(activeSessionId);
+ client.supportsExtensionUi = [...(client.capabilitiesByActiveSessionId?.values() ?? [])].some((value) =>
+ value.has("extension_ui"),
+ );
+}
+
+function daemonClientCapabilitiesForSession(
+ client: DaemonSocketClient,
+ activeSessionId: string,
+): ReadonlySet<DaemonClientCapability> {
+ return client.capabilitiesByActiveSessionId?.get(activeSessionId) ?? client.capabilities;
+}
+
+function daemonClientSupportsExtensionUi(client: DaemonSocketClient, activeSessionId: string): boolean {
+ return client.capabilitiesByActiveSessionId?.get(activeSessionId)?.has("extension_ui") ?? client.supportsExtensionUi;
+}
+
+export function markClientSnapshotStreaming(client: DaemonSocketClient, activeSessionId: string): void {
+ client.snapshotStreaming = true;
+ client.snapshotActiveSessionIds ??= new Set();
+ client.snapshotActiveSessionIds.add(activeSessionId);
+ client.snapshotActiveSessionCounts ??= new Map();
+ client.snapshotActiveSessionCounts.set(
+ activeSessionId,
+ (client.snapshotActiveSessionCounts.get(activeSessionId) ?? 0) + 1,
+ );
+}
+
+export function finishClientSnapshotStreaming(client: DaemonSocketClient, activeSessionId: string): void {
+ const count = client.snapshotActiveSessionCounts?.get(activeSessionId) ?? 1;
+ if (count > 1) {
+ client.snapshotActiveSessionCounts?.set(activeSessionId, count - 1);
+ } else {
+ client.snapshotActiveSessionCounts?.delete(activeSessionId);
+ client.snapshotActiveSessionIds?.delete(activeSessionId);
+ }
+ client.snapshotStreaming = (client.snapshotActiveSessionIds?.size ?? 0) > 0;
+ if (!client.snapshotStreaming) {
+ client.backpressured = false;
+ }
+}
+
export function cancelPendingExtensionUiRequests(state: ActiveSessionState): void {
const pendingRequests = [...state.extensionUiRequests.values()];
state.extensionUiRequests.clear();
@@ -3109,6 +4164,7 @@ type SequencedDaemonOutbound = Extract<
| "session_event"
| "session_status"
| "session_replaced"
+ | "session_resynced"
| "session_closed"
| "extension_ui_request"
| "extension_error";
@@ -3120,6 +4176,7 @@ function isSequencedSessionOutbound(message: DaemonOutbound): message is Sequenc
message.type === "session_event" ||
message.type === "session_status" ||
message.type === "session_replaced" ||
+ message.type === "session_resynced" ||
message.type === "session_closed" ||
message.type === "extension_ui_request" ||
message.type === "extension_error"
@@ -3130,7 +4187,7 @@ export function shouldSendDaemonOutboundToClient(client: DaemonSocketClient, mes
return (
message.type !== "extension_ui_request" ||
!isDaemonDialogExtensionUiRequest(message.method) ||
- client.supportsExtensionUi
+ daemonClientSupportsExtensionUi(client, message.activeSessionId)
);
}
diff --git a/packages/coding-agent/src/modes/daemon/daemon-protocol.ts b/packages/coding-agent/src/modes/daemon/daemon-protocol.ts
index d08b246312..212eddbafa 100644
--- a/packages/coding-agent/src/modes/daemon/daemon-protocol.ts
+++ b/packages/coding-agent/src/modes/daemon/daemon-protocol.ts
@@ -44,8 +44,17 @@ export type DaemonProtocolVersion = typeof DAEMON_PROTOCOL_VERSION;
export type DaemonCommandId = string;
export type DaemonEventId = string;
export type DaemonEventSequence = number;
+export interface DaemonEventCursor {
+ generation: string;
+ sequence: DaemonEventSequence;
+}
export type DaemonClientId = string;
-export type DaemonClientCapability = "attach_snapshot" | "event_sequence" | "extension_ui" | "slim_attach";
+export type DaemonClientCapability =
+ | "attach_snapshot"
+ | "event_sequence"
+ | "extension_ui"
+ | "slim_attach"
+ | "chunked_snapshot";
export type DaemonReplayStatus = "complete" | "partial" | "unavailable";
export interface DaemonProtocolInfo {
@@ -63,10 +72,9 @@ export const DAEMON_DEFAULT_CLIENT_CAPABILITIES: readonly DaemonClientCapability
"event_sequence",
];
-export interface DaemonResumeCursor {
- activeSessionId?: string;
- eventSequence: DaemonEventSequence;
-}
+export type DaemonResumeCursor =
+ | ({ activeSessionId?: string } & DaemonEventCursor)
+ | { activeSessionId?: string; eventSequence: DaemonEventSequence };
export interface DaemonAttachClientMetadata {
clientId?: DaemonClientId;
@@ -115,6 +123,8 @@ export interface DaemonReplayInfo {
status: DaemonReplayStatus;
fromSequence?: DaemonEventSequence;
toSequence: DaemonEventSequence;
+ fromCursor?: DaemonEventCursor;
+ toCursor?: DaemonEventCursor;
reason?: string;
}
@@ -123,6 +133,7 @@ export interface DaemonEventMeta {
protocol: DaemonProtocolInfo;
activeSessionId?: string;
sequence?: DaemonEventSequence;
+ cursor?: DaemonEventCursor;
emittedAt: string;
replayed?: boolean;
}
@@ -135,12 +146,15 @@ export interface DaemonCommandEnvelope<TCommand extends DaemonCommand = DaemonCo
command: TCommand;
}
+export type DaemonCommandWire = DaemonCommand | DaemonCommandEnvelope;
+
export interface DaemonEventEnvelope<TEvent extends DaemonOutbound = DaemonOutbound> {
type: "event";
id: DaemonEventId;
protocol: DaemonProtocolInfo;
activeSessionId?: string;
sequence?: DaemonEventSequence;
+ cursor?: DaemonEventCursor;
emittedAt: string;
event: TEvent;
}
@@ -163,6 +177,7 @@ export interface DaemonSessionSnapshot {
sessionContext?: AgentConnectionSessionContext;
sessionTree?: { tree: AgentConnectionSessionTreeNode[]; leafId: string | null };
lastEventSequence: DaemonEventSequence;
+ lastEventCursor?: DaemonEventCursor;
parent?: {
activeSessionId?: string;
sessionId?: string;
@@ -183,6 +198,12 @@ export interface DaemonAttachResult {
snapshot: DaemonSessionSnapshot;
replay: DaemonReplayInfo;
lastEventSequence: DaemonEventSequence;
+ lastEventCursor?: DaemonEventCursor;
+ snapshotStream?: {
+ id: string;
+ messageCount: number;
+ targetChunkBytes: number;
+ };
client: {
id: DaemonClientId;
capabilities: DaemonClientCapability[];
@@ -418,8 +439,11 @@ export type DaemonCommand =
requestId: string;
response: DaemonExtensionUIResponse;
}
+ | { id?: string; type: "ack_result"; commandId: string }
| { id?: string; type: "prepare_update_restart" }
- | { id?: string; type: "shutdown" };
+ | { id?: string; type: "retry_worker"; activeSessionId: string }
+ | { id?: string; type: "restart" }
+ | { id?: string; type: "shutdown"; force?: boolean };
type DaemonCommandName = DaemonCommand["type"];
@@ -436,7 +460,9 @@ export type DaemonResponse =
export type DaemonErrorInfo =
| { code: "missing_session_cwd"; issue: SessionCwdIssue }
- | { code: "session_import_file_not_found"; filePath: string };
+ | { code: "session_import_file_not_found"; filePath: string }
+ | { code: "session_already_active"; sessionPath: string; activeSessionId?: string }
+ | { code: "command_result_uncertain"; clientId: DaemonClientId; commandId: DaemonCommandId };
export type DaemonSessionClosedReason = "killed" | "shutdown" | "completed" | "replaced" | "update";
export type DaemonClosingReason = "shutdown" | "update";
@@ -504,6 +530,10 @@ export type DaemonOutbound =
protocol: DaemonProtocolInfo;
/** App version of the daemon process, used to detect stale daemons after self-update. */
appVersion?: string;
+ /** Changes whenever the public supervisor process is replaced. */
+ supervisorGeneration?: string;
+ /** Diagnostic process identity for attributing supervisor replacement. */
+ supervisorPid?: number;
clientId: DaemonClientId;
serverCapabilities: readonly DaemonClientCapability[];
}
@@ -516,6 +546,13 @@ export type DaemonOutbound =
activeSessionId: string;
state: AgentConnectionState;
messages: AgentMessage[];
+ snapshotFollows?: boolean;
+ meta?: DaemonEventMeta;
+ }
+ | {
+ type: "session_resynced";
+ activeSessionId: string;
+ snapshot: DaemonSessionSnapshot;
meta?: DaemonEventMeta;
}
| {
@@ -527,6 +564,30 @@ export type DaemonOutbound =
replay?: DaemonReplayInfo;
lastEventSequence?: DaemonEventSequence;
}
+ | {
+ type: "session_snapshot_begin";
+ activeSessionId: string;
+ snapshotId: string;
+ snapshot: Omit<DaemonSessionSnapshot, "messages">;
+ messageCount: number;
+ targetChunkBytes: number;
+ purpose?: "attach" | "replacement" | "resync";
+ }
+ | {
+ type: "session_snapshot_chunk";
+ activeSessionId: string;
+ snapshotId: string;
+ index: number;
+ messages: AgentMessage[];
+ }
+ | {
+ type: "session_snapshot_end";
+ activeSessionId: string;
+ snapshotId: string;
+ chunkCount: number;
+ lastEventSequence: DaemonEventSequence;
+ lastEventCursor?: DaemonEventCursor;
+ }
| { type: "session_detached"; activeSessionId: string }
| { type: "session_closed"; activeSessionId: string; reason: DaemonSessionClosedReason; meta?: DaemonEventMeta }
| {
@@ -560,6 +621,58 @@ export function createDaemonCommandEnvelope<TCommand extends DaemonCommand>(
};
}
+export function isDaemonCommandEnvelope(value: unknown): value is DaemonCommandEnvelope {
+ if (!value || typeof value !== "object") {
+ return false;
+ }
+ const candidate = value as {
+ type?: unknown;
+ id?: unknown;
+ protocol?: { name?: unknown; version?: unknown };
+ clientId?: unknown;
+ command?: unknown;
+ };
+ return (
+ candidate.type === "command" &&
+ typeof candidate.id === "string" &&
+ candidate.protocol?.name === DAEMON_PROTOCOL_NAME &&
+ candidate.protocol.version === DAEMON_PROTOCOL_VERSION &&
+ (candidate.clientId === undefined || typeof candidate.clientId === "string") &&
+ typeof candidate.command === "object" &&
+ candidate.command !== null
+ );
+}
+
+const READ_ONLY_DAEMON_COMMANDS: ReadonlySet<DaemonCommand["type"]> = new Set([
+ "ack_result",
+ "list",
+ "list_saved_sessions",
+ "attach",
+ "agent_messages_status",
+ "wait_for_idle",
+ "get_state",
+ "get_connection_state",
+ "get_messages",
+ "get_session_stats",
+ "get_context_tree",
+ "get_commands",
+ "get_resource_snapshot",
+ "get_available_models",
+ "get_queue",
+ "cron_list",
+ "heartbeat_get",
+ "get_session_context",
+ "get_session_tree",
+ "get_user_messages_for_forking",
+ "get_last_assistant_text",
+ "get_system_prompt",
+ "get_tool_definition",
+]);
+
+export function isDaemonMutatingCommand(command: Pick<DaemonCommand, "type">): boolean {
+ return !READ_ONLY_DAEMON_COMMANDS.has(command.type);
+}
+
export function createDaemonEventEnvelope<TEvent extends DaemonOutbound>(
event: TEvent,
meta: DaemonEventMeta,
@@ -570,6 +683,7 @@ export function createDaemonEventEnvelope<TEvent extends DaemonOutbound>(
protocol: meta.protocol,
...(meta.activeSessionId ? { activeSessionId: meta.activeSessionId } : {}),
...(meta.sequence !== undefined ? { sequence: meta.sequence } : {}),
+ ...(meta.cursor ? { cursor: meta.cursor } : {}),
emittedAt: meta.emittedAt,
event,
};
@@ -579,12 +693,14 @@ export function createDaemonEventMeta(
activeSessionId: string,
sequence: DaemonEventSequence,
emittedAt = new Date().toISOString(),
+ generation = activeSessionId,
): DaemonEventMeta {
return {
id: `${activeSessionId}:${sequence}`,
protocol: DAEMON_PROTOCOL_INFO,
activeSessionId,
sequence,
+ cursor: { generation, sequence },
emittedAt,
};
}
@@ -592,35 +708,59 @@ export function createDaemonEventMeta(
export function createDaemonReplayInfo(
resumeCursor: DaemonResumeCursor | undefined,
lastEventSequence: DaemonEventSequence,
+ generation = "legacy",
): DaemonReplayInfo {
+ const toCursor = { generation, sequence: lastEventSequence };
if (!resumeCursor) {
return {
status: "complete",
toSequence: lastEventSequence,
+ toCursor,
+ };
+ }
+ const resumeSequence = "sequence" in resumeCursor ? resumeCursor.sequence : resumeCursor.eventSequence;
+ const fromCursor =
+ "generation" in resumeCursor
+ ? { generation: resumeCursor.generation, sequence: resumeCursor.sequence }
+ : undefined;
+ if (fromCursor && fromCursor.generation !== generation) {
+ return {
+ status: "unavailable",
+ fromSequence: resumeSequence,
+ toSequence: lastEventSequence,
+ fromCursor,
+ toCursor,
+ reason: "event_generation_changed",
};
}
- if (resumeCursor.eventSequence > lastEventSequence) {
+ if (resumeSequence > lastEventSequence) {
return {
status: "unavailable",
- fromSequence: resumeCursor.eventSequence,
+ fromSequence: resumeSequence,
toSequence: lastEventSequence,
+ ...(fromCursor ? { fromCursor } : {}),
+ toCursor,
reason: "resume_cursor_ahead_of_session",
};
}
- if (resumeCursor.eventSequence === lastEventSequence) {
+ if (resumeSequence === lastEventSequence) {
return {
status: "complete",
- fromSequence: resumeCursor.eventSequence,
+ fromSequence: resumeSequence,
toSequence: lastEventSequence,
+ ...(fromCursor ? { fromCursor } : {}),
+ toCursor,
};
}
return {
status: "unavailable",
- fromSequence: resumeCursor.eventSequence,
+ fromSequence: resumeSequence,
toSequence: lastEventSequence,
+ ...(fromCursor ? { fromCursor } : {}),
+ toCursor,
reason: "event_replay_not_available",
};
}
diff --git a/packages/coding-agent/src/modes/daemon/daemon-session-list.ts b/packages/coding-agent/src/modes/daemon/daemon-session-list.ts
index beafb8f5be..e219d80abb 100644
--- a/packages/coding-agent/src/modes/daemon/daemon-session-list.ts
+++ b/packages/coding-agent/src/modes/daemon/daemon-session-list.ts
@@ -2,7 +2,7 @@ import { statSync } from "node:fs";
import { resolve } from "node:path";
import type { AgentMessage, ThinkingLevel } from "@earendil-works/pi-agent-core";
import type { Api, Model } from "@earendil-works/pi-ai";
-import { compactRlmText } from "../../core/agent-session.js";
+import { compactRlmText, rlmChildLabel } from "../../core/agent-session.js";
import type { AgentSessionRuntimeMetadata } from "../../core/agent-session-runtime.js";
import type { AgentSessionRuntimeDiagnostic } from "../../core/agent-session-services.js";
import type { AgentTaskState, SessionInfo } from "../../core/session-manager.js";
@@ -61,6 +61,10 @@ export interface SessionSummary {
summary?: string;
/** Completion verdict for an idle session; absent while working or unjudged. */
taskState?: AgentTaskState;
+ /** Resident session-host process state, populated by the global supervisor. */
+ workerState?: "starting" | "ready" | "recovering" | "failed";
+ /** Diagnostic process identity; clients must not use this as a stable session identifier. */
+ workerPid?: number;
}
/**
@@ -258,12 +262,18 @@ function rlmChildSnapshotForActiveSession(
): AgentConnectionRlmChildAgentSnapshot {
const session = activeSession.runtime.session;
let answerPreview: string | undefined;
- for (const message of session.messages) {
+ let toolUseCount = 0;
+ const messages =
+ session.state.streamingMessage?.role === "assistant"
+ ? [...session.messages, session.state.streamingMessage]
+ : session.messages;
+ for (const message of messages) {
if (message.role === "assistant") {
const text = compactRlmText(readMessageText(message.content));
if (text) {
answerPreview = text;
}
+ toolUseCount += message.content.filter((block) => block.type === "toolCall").length;
}
}
// The parent session's run tracker is the source of truth for child status;
@@ -278,9 +288,11 @@ function rlmChildSnapshotForActiveSession(
id: metadata.rlmChildId ?? activeSession.activeSessionId,
parentId: parentNodeId,
activeSessionId: activeSession.activeSessionId,
- label: compactRlmText(metadata.prompt ?? "", 80) || "child agent",
+ label: rlmChildLabel(metadata.prompt ?? ""),
status,
answerPreview,
+ toolUseCount: toolUseCount > 0 ? toolUseCount : undefined,
+ tokenCount: session._contextTokensForCurrentMessages(),
recap: session.getCurrentRecap(),
sessionDir: metadata.sessionDir ?? session.sessionManager.getSessionDir(),
activity: status === "running" ? { kind: session.isStreaming ? "writing" : "waiting" } : undefined,
diff --git a/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts b/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts
new file mode 100644
index 0000000000..4913dab3cc
--- /dev/null
+++ b/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts
@@ -0,0 +1,2496 @@
+import { type ChildProcess, spawn } from "node:child_process";
+import { createHash, randomBytes, randomUUID } from "node:crypto";
+import { chmodSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
+import { createServer, type Server, type Socket } from "node:net";
+import { dirname, isAbsolute, join, resolve } from "node:path";
+import { getLogger } from "@earendil-works/pi-ai";
+import { createCliSubprocessLaunchSpec } from "../../cli/subprocess-launch.js";
+import {
+ appendRotatingLog,
+ getCronJobsPath,
+ getDaemonLogPath,
+ getDaemonUpdateRestartManifestPath,
+ VERSION,
+} from "../../config.js";
+import type { AgentSessionMessageAgentSummary } from "../../core/agent-messages.js";
+import { type AgentSessionRuntimeConfig, mergeAgentSessionRuntimeConfig } from "../../core/agent-session-config.js";
+import {
+ type AgentCronJob,
+ AgentCronJobStore,
+ migrateLegacyCronJobsToSessionArtifacts,
+ SESSION_SCHEDULED_JOBS_FILENAME,
+} from "../../core/cron-jobs.js";
+import {
+ clearOrphanProcessJournal,
+ isOrphanProcessIdentityCurrent,
+ ORPHAN_PROCESS_JOURNAL_ENV,
+ readActiveOrphanProcesses,
+} from "../../core/orphan-process-journal.js";
+import { getProcessStartId } from "../../core/session-lease.js";
+import type { SessionInfo } from "../../core/session-manager.js";
+import { attachJsonlLineReader, serializeJsonLine } from "../rpc/jsonl.js";
+import type { PrivateFrame } from "../session-worker/private-framing.js";
+import { createActiveSessionId, type DaemonSocketClient } from "./active-session-state.js";
+import { CommandRecoveryJournal, createCommandIdempotencyKey } from "./command-recovery-journal.js";
+import { CompactAssistantStreamReconstructor, isCompactAssistantDelta } from "./compact-session-stream.js";
+import { DAEMON_CATALOG_ROLE_ENV, DaemonCatalogClient } from "./daemon-catalog-process.js";
+import { deserializeDaemonError, serializeDaemonError } from "./daemon-errors.js";
+import {
+ collectDaemonClientEnv,
+ createDaemonEventMeta,
+ DAEMON_DEFAULT_CLIENT_CAPABILITIES,
+ DAEMON_PROTOCOL_INFO,
+ type DaemonAttachResult,
+ type DaemonClientCapability,
+ type DaemonCommand,
+ type DaemonOutbound,
+ type DaemonResponse,
+ type DaemonSavedSessionInfo,
+ type DaemonUpdateRestartManifest,
+ failure,
+ isDaemonCommandEnvelope,
+ isDaemonMutatingCommand,
+ success,
+} from "./daemon-protocol.js";
+import { matchesSessionIdSuffix } from "./daemon-session-id.js";
+import { type SessionSummary, summaryForInactiveSession } from "./daemon-session-list.js";
+import {
+ cleanupDaemonSocketPath,
+ defaultDaemonSocketDir,
+ defaultDaemonSocketPath,
+ prepareDaemonSocketPath,
+ restrictDaemonSocketPath,
+} from "./daemon-socket.js";
+import { DaemonWorkerClient } from "./daemon-worker-client.js";
+import {
+ DAEMON_WORKER_ACTIVE_SESSION_ID_ENV,
+ DAEMON_WORKER_RECOVERY_JOURNAL_ENV,
+ DAEMON_WORKER_ROLE_ENV,
+ DAEMON_WORKER_SUPERVISOR_SOCKET_ENV,
+ DAEMON_WORKER_TOKEN_ENV,
+ type DaemonCreateCommand,
+ type DaemonWorkerDescriptor,
+ type DaemonWorkerFrameHeader,
+ SESSION_LEASE_OWNER_ID_ENV,
+ SESSION_LEASES_ENABLED_ENV,
+} from "./daemon-worker-protocol.js";
+import { SNAPSHOT_TARGET_CHUNK_BYTES, SnapshotTranscriptCache } from "./snapshot-transcript-cache.js";
+import { WorkerRecoveryJournal } from "./worker-recovery-journal.js";
+
+type DistributiveOmit<T, K extends keyof T> = T extends unknown ? Omit<T, K> : never;
+type DaemonCommandBody = DistributiveOmit<DaemonCommand, "id">;
+
+const structuredLog = getLogger("coding-agent.daemon-supervisor");
+const WORKER_CONNECT_TIMEOUT_MS = 30_000;
+const WORKER_REQUEST_TIMEOUT_MS = 24 * 60 * 60 * 1000;
+const WORKER_RETRY_DELAYS_MS = [250, 1000, 5000] as const;
+const SUPERVISOR_CONFIG_FILE_NAME = "supervisor-config";
+
+const DAEMON_COMMAND_TYPES: ReadonlySet<string> = new Set([
+ "ack_result",
+ "list",
+ "list_saved_sessions",
+ "create",
+ "attach",
+ "detach",
+ "kill",
+ "rename",
+ "prompt",
+ "steer",
+ "follow_up",
+ "restore_next_turn",
+ "resume_queue",
+ "send_message",
+ "agent_messages_status",
+ "agent_messages_pause",
+ "agent_messages_resume",
+ "agent_messages_clear",
+ "abort",
+ "start_side_question",
+ "abort_side_question",
+ "execute_bash",
+ "abort_bash",
+ "cancel_rlm_child",
+ "wait_for_idle",
+ "get_state",
+ "get_connection_state",
+ "get_messages",
+ "get_session_stats",
+ "get_context_tree",
+ "get_commands",
+ "get_resource_snapshot",
+ "get_available_models",
+ "get_queue",
+ "clear_queue",
+ "abort_and_clear_queue",
+ "cron_list",
+ "cron_add",
+ "cron_cancel",
+ "heartbeat_get",
+ "heartbeat_set",
+ "heartbeat_update",
+ "set_model",
+ "cycle_model",
+ "set_scoped_models",
+ "set_thinking_level",
+ "cycle_thinking_level",
+ "set_transport",
+ "set_steering_mode",
+ "set_follow_up_mode",
+ "set_auto_compaction",
+ "compact",
+ "refine",
+ "abort_compaction",
+ "abort_branch_summary",
+ "abort_retry",
+ "reload",
+ "new_session",
+ "switch_session",
+ "fork",
+ "navigate_tree",
+ "import_jsonl",
+ "export_html",
+ "export_jsonl",
+ "set_session_name",
+ "rename_saved_session",
+ "delete_saved_session",
+ "get_session_context",
+ "get_session_tree",
+ "get_user_messages_for_forking",
+ "get_last_assistant_text",
+ "get_system_prompt",
+ "get_tool_definition",
+ "set_session_entry_label",
+ "extension_ui_response",
+ "prepare_update_restart",
+ "retry_worker",
+ "restart",
+ "shutdown",
+]);
+
+interface ResidentWorker {
+ descriptor: DaemonWorkerDescriptor;
+ descriptorPath: string;
+ client?: DaemonWorkerClient;
+ summaries: Map<string, SessionSummary>;
+ snapshotCache: Map<string, DaemonAttachResult>;
+ transcriptCaches: Map<string, SnapshotTranscriptCache>;
+ incomingTranscriptActiveSessionIds: Set<string>;
+ snapshotLoads: Map<string, Promise<DaemonAttachResult>>;
+ recovery?: Promise<void>;
+ intentionalStop: boolean;
+ stopRevision: number;
+}
+
+interface DaemonSupervisorOptions {
+ socketPath?: string;
+ defaultSessionConfig: AgentSessionRuntimeConfig;
+ descriptorDir?: string;
+}
+
+interface PersistedSupervisorConfig {
+ version: 1;
+ socketPath: string;
+ defaultSessionConfig: AgentSessionRuntimeConfig;
+}
+
+interface WorkerMatch {
+ worker: ResidentWorker;
+ summary: SessionSummary;
+}
+
+interface WorkerAttachData {
+ result: DaemonAttachResult;
+ worker: ResidentWorker;
+}
+
+function delay(ms: number): Promise<void> {
+ return new Promise((resolveDelay) => setTimeout(resolveDelay, ms));
+}
+
+function withoutCommandId(command: DaemonCommand): DaemonCommandBody {
+ const { id: _id, ...body } = command;
+ return body as DaemonCommandBody;
+}
+
+function responseWithId(response: DaemonResponse, id: string | undefined): DaemonResponse {
+ return { ...response, id };
+}
+
+function isSessionSummary(value: unknown): value is SessionSummary {
+ if (!value || typeof value !== "object") {
+ return false;
+ }
+ const candidate = value as { id?: unknown; sessionId?: unknown; cwd?: unknown };
+ return (
+ typeof candidate.id === "string" && typeof candidate.sessionId === "string" && typeof candidate.cwd === "string"
+ );
+}
+
+function isDaemonWorkerDescriptor(value: unknown, socketPath: string): value is DaemonWorkerDescriptor {
+ if (!value || typeof value !== "object") {
+ return false;
+ }
+ const descriptor = value as Partial<DaemonWorkerDescriptor>;
+ return (
+ descriptor.version === 1 &&
+ descriptor.supervisorSocketPath === socketPath &&
+ typeof descriptor.workerId === "string" &&
+ Number.isInteger(descriptor.pid) &&
+ (descriptor.pid ?? 0) > 0 &&
+ (descriptor.processStartId === undefined || typeof descriptor.processStartId === "string") &&
+ typeof descriptor.socketPath === "string" &&
+ typeof descriptor.authenticationToken === "string" &&
+ typeof descriptor.rootActiveSessionId === "string" &&
+ typeof descriptor.createdAt === "string" &&
+ typeof descriptor.updatedAt === "string" &&
+ Number.isInteger(descriptor.consecutiveFailures) &&
+ descriptor.createCommand !== undefined &&
+ typeof descriptor.createCommand === "object" &&
+ descriptor.createCommand.type === "create"
+ );
+}
+
+function sessionSummariesFromResponse(response: DaemonResponse): SessionSummary[] {
+ if (!response.success || !response.data || typeof response.data !== "object" || !("sessions" in response.data)) {
+ throw new Error("Session worker returned an invalid list response");
+ }
+ const sessions = (response.data as { sessions: unknown }).sessions;
+ if (!Array.isArray(sessions) || !sessions.every(isSessionSummary)) {
+ throw new Error("Session worker returned an invalid list response");
+ }
+ return sessions;
+}
+
+function attachResultFromResponse(response: DaemonResponse): DaemonAttachResult {
+ if (!response.success || !response.data || typeof response.data !== "object") {
+ throw new Error(response.success ? "Session worker returned an invalid attach response" : response.error);
+ }
+ const candidate = response.data as Partial<DaemonAttachResult>;
+ if (typeof candidate.activeSessionId !== "string" || !candidate.snapshot || !candidate.client) {
+ throw new Error("Session worker returned an invalid attach response");
+ }
+ return candidate as DaemonAttachResult;
+}
+
+function cronJobsFromResponse(response: DaemonResponse): AgentCronJob[] {
+ if (!response.success || !response.data || typeof response.data !== "object") {
+ return [];
+ }
+ const jobs = (response.data as { jobs?: unknown }).jobs;
+ return Array.isArray(jobs) ? (jobs as AgentCronJob[]) : [];
+}
+
+function sortCronJobs(jobs: AgentCronJob[]): AgentCronJob[] {
+ return jobs.sort((left, right) => {
+ if (left.nextRunAt === right.nextRunAt) {
+ return 0;
+ }
+ if (left.nextRunAt === undefined) {
+ return 1;
+ }
+ if (right.nextRunAt === undefined) {
+ return -1;
+ }
+ return Date.parse(left.nextRunAt) - Date.parse(right.nextRunAt);
+ });
+}
+
+function serializeSavedSessionInfo(session: SessionInfo): DaemonSavedSessionInfo {
+ return {
+ path: session.path,
+ id: session.id,
+ cwd: session.cwd,
+ name: session.name,
+ state: session.state,
+ parentSessionPath: session.parentSessionPath,
+ created: session.created.toISOString(),
+ modified: session.modified.toISOString(),
+ messageCount: session.messageCount,
+ firstMessage: session.firstMessage,
+ allMessagesText: session.allMessagesText,
+ agentStatus: session.agentStatus,
+ };
+}
+
+function descriptorKey(socketPath: string): string {
+ return createHash("sha256").update(socketPath).digest("hex").slice(0, 12);
+}
+
+function defaultWorkerDescriptorDir(agentDir: string, socketPath: string): string {
+ return join(agentDir, "daemon-workers", descriptorKey(socketPath));
+}
+
+function workerSocketPath(supervisorSocketPath: string, workerId: string): string {
+ const key = descriptorKey(supervisorSocketPath);
+ if (process.platform === "win32") {
+ return `\\\\.\\pipe\\prime-agent-worker-${key}-${workerId.slice(0, 12)}`;
+ }
+ return join(defaultDaemonSocketDir(), `worker-${key}-${workerId.slice(0, 12)}.sock`);
+}
+
+function looksLikeSessionPath(selector: string): boolean {
+ return isAbsolute(selector) || selector.endsWith(".jsonl") || selector.includes("/") || selector.includes("\\");
+}
+
+function isProcessAlive(pid: number): boolean {
+ try {
+ process.kill(pid, 0);
+ return true;
+ } catch (error) {
+ return (error as NodeJS.ErrnoException).code === "EPERM";
+ }
+}
+
+function signalProcessGroupOrProcess(pid: number, signal: NodeJS.Signals): void {
+ try {
+ process.kill(-pid, signal);
+ return;
+ } catch {
+ // Fall back when process groups are unavailable or the group already exited.
+ }
+ try {
+ process.kill(pid, signal);
+ } catch {
+ // The process may already be fully reaped.
+ }
+}
+
+function isFinalizedTranscriptEvent(eventType: string | undefined): boolean {
+ return (
+ eventType === "message_end" ||
+ eventType === "turn_end" ||
+ eventType === "compaction_end" ||
+ eventType === "bash_end"
+ );
+}
+
+function normalizeCapabilities(
+ capabilities: readonly DaemonClientCapability[] | undefined,
+ supportsExtensionUi: boolean | undefined,
+): Set<DaemonClientCapability> {
+ const normalized = new Set(capabilities ?? DAEMON_DEFAULT_CLIENT_CAPABILITIES);
+ if (supportsExtensionUi) {
+ normalized.add("extension_ui");
+ }
+ return normalized;
+}
+
+function mergeSessionLists(active: readonly SessionSummary[], saved: readonly SessionInfo[]): SessionSummary[] {
+ const activeByFile = new Map<string, SessionSummary>();
+ for (const summary of active) {
+ if (summary.sessionFile) {
+ activeByFile.set(resolve(summary.sessionFile), summary);
+ }
+ }
+ const merged: SessionSummary[] = [];
+ const seenActiveIds = new Set<string>();
+ for (const session of saved) {
+ const resident = activeByFile.get(resolve(session.path));
+ if (resident) {
+ merged.push({
+ ...resident,
+ created: resident.created ?? session.created.toISOString(),
+ modified: resident.modified ?? session.modified.toISOString(),
+ firstMessage: resident.firstMessage ?? session.firstMessage,
+ });
+ seenActiveIds.add(resident.activeSessionId ?? resident.id);
+ } else {
+ merged.push(summaryForInactiveSession(session));
+ }
+ }
+ for (const summary of active) {
+ if (!seenActiveIds.has(summary.activeSessionId ?? summary.id)) {
+ merged.push(summary);
+ }
+ }
+ return merged;
+}
+
+export async function runDaemonSupervisorMode(options: DaemonSupervisorOptions): Promise<never> {
+ const socketPath = options.socketPath ?? defaultDaemonSocketPath();
+ const supervisor = new DaemonSupervisor(socketPath, options);
+ await supervisor.start();
+ return new Promise(() => {});
+}
+
+export class DaemonSupervisor {
+ private server?: Server;
+ private readonly ready: Promise<void>;
+ private markReady: () => void = () => {};
+ private ownsSocketPath = false;
+ private shuttingDown = false;
+ private readonly clients = new Set<DaemonSocketClient>();
+ private readonly workers = new Map<string, ResidentWorker>();
+ private readonly openingWorkers = new Map<string, Promise<ResidentWorker>>();
+ private readonly signalCleanupHandlers: Array<() => void> = [];
+ private readonly descriptorDir: string;
+ private readonly generation = randomUUID();
+ private readonly supervisorConfigPath: string;
+ private readonly defaultSessionConfig: AgentSessionRuntimeConfig;
+ private readonly snapshotCacheRoot: string;
+ private readonly commandJournal: CommandRecoveryJournal;
+ private readonly streamReconstructor = new CompactAssistantStreamReconstructor();
+ private readonly compactCatchupInProgress = new Set<string>();
+ private agentPeerSyncQueue: Promise<void> = Promise.resolve();
+ private readonly catalog: DaemonCatalogClient;
+
+ constructor(
+ private readonly socketPath: string,
+ options: DaemonSupervisorOptions,
+ ) {
+ this.ready = new Promise<void>((resolveReady) => {
+ this.markReady = resolveReady;
+ });
+ const agentDir = options.defaultSessionConfig.agentDir;
+ if (!agentDir) {
+ throw new Error("Daemon supervisor config is missing agentDir");
+ }
+ this.descriptorDir = options.descriptorDir ?? defaultWorkerDescriptorDir(agentDir, socketPath);
+ this.supervisorConfigPath = join(this.descriptorDir, SUPERVISOR_CONFIG_FILE_NAME);
+ this.defaultSessionConfig = this.loadPersistedSupervisorConfig() ?? options.defaultSessionConfig;
+ this.snapshotCacheRoot = join(this.descriptorDir, "snapshot-cache");
+ this.commandJournal = new CommandRecoveryJournal(join(this.descriptorDir, "command-journal.jsonl"));
+ this.catalog = new DaemonCatalogClient((message) => this.log(message));
+ }
+
+ async start(): Promise<void> {
+ await prepareDaemonSocketPath(this.socketPath);
+ mkdirSync(this.descriptorDir, { recursive: true, mode: 0o700 });
+ chmodSync(this.descriptorDir, 0o700);
+ this.persistSupervisorConfig();
+ rmSync(this.snapshotCacheRoot, { recursive: true, force: true });
+ mkdirSync(this.snapshotCacheRoot, { recursive: true, mode: 0o700 });
+ this.loadWorkerDescriptors();
+ const workersToAdopt = [...this.workers.values()];
+
+ this.server = createServer((socket) => this.handleConnection(socket));
+ await new Promise<void>((resolveListen, rejectListen) => {
+ const onError = (error: Error) => {
+ this.server?.off("listening", onListening);
+ rejectListen(error);
+ };
+ const onListening = () => {
+ this.server?.off("error", onError);
+ try {
+ this.ownsSocketPath = true;
+ if (process.platform !== "win32") {
+ restrictDaemonSocketPath(this.socketPath);
+ }
+ resolveListen();
+ } catch (error) {
+ rejectListen(error);
+ }
+ };
+ this.server?.once("error", onError);
+ this.server?.once("listening", onListening);
+ this.server?.listen(this.socketPath);
+ });
+
+ this.registerSignalHandlers();
+ const agentDir = this.defaultSessionConfig.agentDir;
+ if (!agentDir) {
+ throw new Error("Daemon supervisor config is missing agentDir");
+ }
+ const ownedSessionFiles = new Set(
+ [...this.workers.values()]
+ .flatMap((worker) => [worker.descriptor.sessionFile, worker.descriptor.createCommand.sessionPath])
+ .filter((path): path is string => typeof path === "string")
+ .map((path) => resolve(path)),
+ );
+ const migratedJobs = migrateLegacyCronJobsToSessionArtifacts(getCronJobsPath(agentDir), {
+ isSessionOwned: (job) => ownedSessionFiles.has(resolve(job.sessionFile)),
+ });
+ if (migratedJobs > 0) {
+ this.log(`Migrated ${migratedJobs} scheduled jobs into session artifacts`);
+ }
+ await this.catalog.start().catch((error) => this.log(`Could not start daemon catalog: ${String(error)}`));
+ await Promise.all(workersToAdopt.map((worker) => this.adoptOrRecoverWorker(worker)));
+ await this.syncAgentPeers().catch((error) => this.log(`Could not synchronize agent peers: ${String(error)}`));
+ this.markReady();
+ this.log(`Prime Agent daemon supervisor ${this.generation} listening on ${this.socketPath}`);
+ }
+
+ private log(message: string): void {
+ console.error(message);
+ structuredLog.warn(message, { socketPath: this.socketPath });
+ appendRotatingLog(getDaemonLogPath(this.socketPath), `[${new Date().toISOString()}] supervisor: ${message}`);
+ }
+
+ private loadWorkerDescriptors(): void {
+ for (const name of readdirSync(this.descriptorDir)) {
+ if (name === SUPERVISOR_CONFIG_FILE_NAME || !name.endsWith(".json")) {
+ continue;
+ }
+ const path = join(this.descriptorDir, name);
+ try {
+ const descriptor: unknown = JSON.parse(readFileSync(path, "utf8"));
+ if (!isDaemonWorkerDescriptor(descriptor, this.socketPath)) {
+ continue;
+ }
+ descriptor.lifecycle = "recovering";
+ descriptor.recoveryJournalPath ??= join(this.descriptorDir, `${descriptor.workerId}.recovery.jsonl`);
+ descriptor.orphanProcessJournalPath ??= join(this.descriptorDir, `${descriptor.workerId}.orphans.jsonl`);
+ this.workers.set(descriptor.workerId, {
+ descriptor,
+ descriptorPath: path,
+ summaries: new Map(),
+ snapshotCache: new Map(),
+ transcriptCaches: new Map(),
+ incomingTranscriptActiveSessionIds: new Set(),
+ snapshotLoads: new Map(),
+ intentionalStop: descriptor.stopRequestedAt !== undefined,
+ stopRevision: 0,
+ });
+ } catch (error) {
+ this.log(`Ignoring invalid worker descriptor ${path}: ${String(error)}`);
+ }
+ }
+ }
+
+ private loadPersistedSupervisorConfig(): AgentSessionRuntimeConfig | undefined {
+ try {
+ const parsed = JSON.parse(
+ readFileSync(this.supervisorConfigPath, "utf8"),
+ ) as Partial<PersistedSupervisorConfig>;
+ if (
+ parsed.version !== 1 ||
+ parsed.socketPath !== this.socketPath ||
+ !parsed.defaultSessionConfig ||
+ typeof parsed.defaultSessionConfig !== "object" ||
+ typeof parsed.defaultSessionConfig.agentDir !== "string"
+ ) {
+ return undefined;
+ }
+ return parsed.defaultSessionConfig;
+ } catch {
+ return undefined;
+ }
+ }
+
+ private persistSupervisorConfig(): void {
+ const persisted: PersistedSupervisorConfig = {
+ version: 1,
+ socketPath: this.socketPath,
+ defaultSessionConfig: this.defaultSessionConfig,
+ };
+ const tempPath = `${this.supervisorConfigPath}.${process.pid}.tmp`;
+ writeFileSync(tempPath, `${JSON.stringify(persisted, null, 2)}\n`, { mode: 0o600 });
+ chmodSync(tempPath, 0o600);
+ renameSync(tempPath, this.supervisorConfigPath);
+ }
+
+ private hasPersistedWorkerDescriptors(): boolean {
+ return readdirSync(this.descriptorDir).some(
+ (name) => name !== SUPERVISOR_CONFIG_FILE_NAME && name.endsWith(".json"),
+ );
+ }
+
+ private persistWorker(worker: ResidentWorker): void {
+ worker.descriptor.updatedAt = new Date().toISOString();
+ const tempPath = `${worker.descriptorPath}.${process.pid}.tmp`;
+ writeFileSync(tempPath, `${JSON.stringify(worker.descriptor, null, 2)}\n`, { mode: 0o600 });
+ chmodSync(tempPath, 0o600);
+ renameSync(tempPath, worker.descriptorPath);
+ }
+
+ private deleteWorkerDescriptor(worker: ResidentWorker): void {
+ try {
+ rmSync(worker.descriptorPath, { force: true });
+ rmSync(worker.descriptor.recoveryJournalPath, { force: true });
+ if (worker.descriptor.orphanProcessJournalPath) {
+ rmSync(worker.descriptor.orphanProcessJournalPath, { force: true });
+ }
+ } catch (error) {
+ this.log(`Failed to remove worker descriptor ${worker.descriptorPath}: ${String(error)}`);
+ }
+ }
+
+ private handleConnection(socket: Socket): void {
+ const client: DaemonSocketClient = {
+ id: createActiveSessionId(),
+ socket,
+ attachedActiveSessionIds: new Set(),
+ catchupActiveSessionIds: new Set(),
+ backpressured: false,
+ authenticated: true,
+ snapshotActiveSessionIds: new Set(),
+ detachInput: () => {},
+ supportsExtensionUi: false,
+ capabilities: new Set(DAEMON_DEFAULT_CLIENT_CAPABILITIES),
+ };
+ this.clients.add(client);
+ void this.ready.then(() => {
+ if (!client.socket.destroyed && this.clients.has(client)) {
+ this.write(client, {
+ type: "daemon_hello",
+ socketPath: this.socketPath,
+ protocol: DAEMON_PROTOCOL_INFO,
+ appVersion: VERSION,
+ supervisorGeneration: this.generation,
+ supervisorPid: process.pid,
+ clientId: client.id,
+ serverCapabilities: [
+ "attach_snapshot",
+ "event_sequence",
+ "extension_ui",
+ "slim_attach",
+ "chunked_snapshot",
+ ],
+ });
+ }
+ });
+
+ client.detachInput = attachJsonlLineReader(socket, (line) => void this.handleLine(client, line));
+ let cleaned = false;
+ const cleanup = () => {
+ if (cleaned) {
+ return;
+ }
+ cleaned = true;
+ client.detachInput();
+ this.clients.delete(client);
+ for (const activeSessionId of [...client.attachedActiveSessionIds]) {
+ client.attachedActiveSessionIds.delete(activeSessionId);
+ void this.syncWorkerExtensionUi(activeSessionId);
+ }
+ };
+ socket.on("close", cleanup);
+ socket.on("error", cleanup);
+ socket.on("drain", () => {
+ if (!client.snapshotStreaming) {
+ void this.catchUpClient(client);
+ }
+ });
+ }
+
+ private async handleLine(client: DaemonSocketClient, line: string): Promise<void> {
+ await this.ready;
+ let command: DaemonCommand;
+ let envelopeClientId: string | undefined;
+ try {
+ const parsed = JSON.parse(line) as unknown;
+ const candidate = isDaemonCommandEnvelope(parsed)
+ ? { ...parsed.command, id: parsed.id }
+ : (parsed as { id?: unknown; type?: unknown });
+ if (isDaemonCommandEnvelope(parsed)) {
+ envelopeClientId = parsed.clientId ?? client.id;
+ client.id = envelopeClientId;
+ }
+ if (typeof candidate.type !== "string" || !DAEMON_COMMAND_TYPES.has(candidate.type)) {
+ const commandName = typeof candidate.type === "string" ? candidate.type : "unknown";
+ this.write(
+ client,
+ failure(
+ typeof candidate.id === "string" ? candidate.id : undefined,
+ commandName,
+ `Unknown daemon command: ${commandName}`,
+ ),
+ );
+ return;
+ }
+ command = candidate as DaemonCommand;
+ } catch (error) {
+ this.write(client, failure(undefined, "parse", error));
+ return;
+ }
+
+ const journalIdentity =
+ envelopeClientId && command.id && isDaemonMutatingCommand(command)
+ ? { clientId: envelopeClientId, commandId: command.id }
+ : undefined;
+ if (journalIdentity) {
+ const existing = this.commandJournal.begin(journalIdentity.clientId, journalIdentity.commandId, command.type);
+ if (existing.status === "complete") {
+ this.write(client, existing.response);
+ return;
+ }
+ if (existing.status === "pending") {
+ this.write(
+ client,
+ failure(command.id, command.type, "The previous command result is uncertain and was not replayed", {
+ code: "command_result_uncertain",
+ ...journalIdentity,
+ }),
+ );
+ return;
+ }
+ }
+
+ try {
+ const response = await this.handleCommand(client, command);
+ if (response) {
+ if (journalIdentity) {
+ this.commandJournal.recordResult(journalIdentity.clientId, journalIdentity.commandId, response);
+ }
+ this.write(client, response);
+ }
+ } catch (error) {
+ this.log(`Supervisor command ${command.type} failed: ${error instanceof Error ? error.stack : String(error)}`);
+ const response = failure(command.id, command.type, error, serializeDaemonError(error));
+ if (journalIdentity) {
+ this.commandJournal.recordResult(journalIdentity.clientId, journalIdentity.commandId, response);
+ }
+ this.write(client, response);
+ }
+ }
+
+ private async handleCommand(
+ client: DaemonSocketClient,
+ command: DaemonCommand,
+ ): Promise<DaemonResponse | undefined> {
+ switch (command.type) {
+ case "ack_result":
+ this.commandJournal.acknowledge(client.id, command.commandId);
+ return undefined;
+ case "list":
+ return this.handleList(command);
+ case "list_saved_sessions":
+ return this.handleSavedSessionList(client, command);
+ case "create": {
+ const worker = await this.createOrReuseWorker(client.id, command);
+ const summary = worker.summaries.get(worker.descriptor.rootActiveSessionId);
+ if (!summary) {
+ throw new Error("Session worker started without a root session");
+ }
+ return success(command.id, "create", this.publicSummary(worker, summary));
+ }
+ case "attach": {
+ const attached = await this.attachClient(client, command);
+ if (client.capabilities.has("chunked_snapshot")) {
+ const transcript = this.getOrCreateTranscriptCache(attached.worker, attached.result);
+ const streamedResult = this.createStreamedAttachResult(attached.result, transcript);
+ this.write(client, success(command.id, "attach", streamedResult));
+ void this.streamSnapshot(client, streamedResult, transcript).catch((error) =>
+ this.log(`Failed to stream attach snapshot for ${streamedResult.activeSessionId}: ${String(error)}`),
+ );
+ return undefined;
+ }
+ return success(command.id, "attach", attached.result);
+ }
+ case "detach":
+ this.detachClient(client, command.activeSessionId);
+ return success(command.id, "detach");
+ case "retry_worker": {
+ const direct = [...this.workers.values()].find(
+ (worker) =>
+ worker.descriptor.rootActiveSessionId === command.activeSessionId ||
+ worker.descriptor.rootSessionId === command.activeSessionId,
+ );
+ const worker = direct ?? (await this.findWorker(command.activeSessionId)).worker;
+ worker.intentionalStop = false;
+ worker.descriptor.lifecycle = "recovering";
+ worker.descriptor.consecutiveFailures = 0;
+ this.persistWorker(worker);
+ await this.recoverWorker(worker);
+ if (this.workers.get(worker.descriptor.workerId)?.descriptor.lifecycle !== "ready") {
+ throw new Error(worker.descriptor.lastError ?? "Session worker recovery failed");
+ }
+ const summary = worker.summaries.get(worker.descriptor.rootActiveSessionId);
+ return success(command.id, command.type, summary ? this.publicSummary(worker, summary) : undefined);
+ }
+ case "restart":
+ setImmediate(() => void this.shutdown(0, false, true));
+ return success(command.id, command.type);
+ case "shutdown":
+ setImmediate(() => void this.shutdown(0, true, false, command.force === true));
+ return success(command.id, "shutdown");
+ case "prepare_update_restart": {
+ const manifest = await this.prepareUpdateRestart();
+ return success(command.id, "prepare_update_restart", manifest);
+ }
+ case "agent_messages_status": {
+ const first = [...this.workers.values()].find((worker) => worker.client);
+ if (!first) {
+ return success(command.id, command.type, { paused: false, limits: {} });
+ }
+ return this.forwardToWorker(first, command);
+ }
+ case "agent_messages_pause":
+ case "agent_messages_resume": {
+ const responses = await Promise.all(
+ [...this.workers.values()]
+ .filter((worker) => worker.client)
+ .map((worker) => this.forwardToWorker(worker, command)),
+ );
+ const failed = responses.find((response) => !response.success);
+ return failed ?? success(command.id, command.type, responses.find((response) => response.success)?.data);
+ }
+ case "cron_list": {
+ if (command.activeSessionId) {
+ const match = await this.findWorker(command.activeSessionId);
+ return this.forwardToWorker(match.worker, command);
+ }
+ const jobs = new Map<string, AgentCronJob>();
+ const responses = await Promise.all(
+ [...this.workers.values()]
+ .filter((worker) => worker.client && worker.descriptor.lifecycle === "ready")
+ .map((worker) =>
+ this.forwardToWorker(worker, command, 5000).catch((error: unknown) =>
+ failure(command.id, command.type, error, serializeDaemonError(error)),
+ ),
+ ),
+ );
+ for (const response of responses) {
+ if (!response.success) {
+ this.log(`Could not list scheduled jobs from a worker: ${response.error}`);
+ continue;
+ }
+ for (const job of cronJobsFromResponse(response)) {
+ jobs.set(job.id, job);
+ }
+ }
+ return success(command.id, "cron_list", { jobs: sortCronJobs([...jobs.values()]) });
+ }
+ case "cron_add": {
+ const match = await this.findWorker(command.activeSessionId);
+ return this.forwardToWorker(match.worker, command);
+ }
+ case "cron_cancel": {
+ const listed = await Promise.all(
+ [...this.workers.values()]
+ .filter((worker) => worker.client && worker.descriptor.lifecycle === "ready")
+ .map(async (worker) => ({
+ worker,
+ response: await this.forwardToWorker(
+ worker,
+ { type: "cron_list", includeInactive: true },
+ 5000,
+ ).catch(() => undefined),
+ })),
+ );
+ for (const candidate of listed) {
+ if (
+ candidate.response?.success &&
+ cronJobsFromResponse(candidate.response).some((job) => job.id === command.jobId)
+ ) {
+ return this.forwardToWorker(candidate.worker, command);
+ }
+ }
+ throw new Error(`No cron job found: ${command.jobId}`);
+ }
+ case "heartbeat_get": {
+ const match = await this.findWorker(command.activeSessionId);
+ return this.forwardToWorker(match.worker, command);
+ }
+ case "heartbeat_set": {
+ const match = await this.findWorker(command.activeSessionId);
+ return this.forwardToWorker(match.worker, command);
+ }
+ case "heartbeat_update": {
+ const match = await this.findWorker(command.activeSessionId);
+ return this.forwardToWorker(match.worker, command);
+ }
+ case "rename_saved_session":
+ if (!command.activeSessionId) {
+ await this.catalog.rename(command.sessionPath, command.name);
+ return success(command.id, command.type);
+ }
+ break;
+ case "delete_saved_session":
+ if (!command.activeSessionId) {
+ const active = this.findWorkerBySessionFile(command.sessionPath);
+ if (active) {
+ throw new Error("Cannot delete the currently active session");
+ }
+ const result = await this.catalog.delete(command.sessionPath);
+ return success(command.id, command.type, result);
+ }
+ break;
+ }
+
+ if (command.type === "send_message") {
+ const target = await this.findWorker(command.targetActiveSessionId);
+ const source = command.fromActiveSessionId ? await this.findWorker(command.fromActiveSessionId) : undefined;
+ if (source && source.worker !== target.worker) {
+ if (!target.worker.client) {
+ throw new Error("Target session worker is not connected");
+ }
+ const response = await target.worker.client.requestWorker(
+ {
+ type: "worker_deliver_message",
+ targetActiveSessionId: target.summary.activeSessionId ?? target.summary.id,
+ message: command.message,
+ sender: {
+ activeSessionId: source.summary.activeSessionId ?? source.summary.id,
+ sessionId: source.summary.sessionId,
+ ...(source.summary.sessionName ? { sessionName: source.summary.sessionName } : {}),
+ runtimeKind: source.summary.runtimeKind ?? "top-level",
+ clientId: client.id,
+ },
+ deliveryMode: command.deliveryMode,
+ },
+ WORKER_REQUEST_TIMEOUT_MS,
+ );
+ return { ...response, id: command.id, command: command.type };
+ }
+ return this.forwardToWorker(target.worker, command);
+ }
+
+ if (!("activeSessionId" in command) || typeof command.activeSessionId !== "string") {
+ throw new Error(`Supervisor cannot route daemon command: ${command.type}`);
+ }
+ const match = await this.findWorker(command.activeSessionId);
+ const resolvedCommand = {
+ ...command,
+ activeSessionId: match.summary.activeSessionId ?? match.summary.id,
+ } as DaemonCommand;
+ const isRootKill =
+ command.type === "kill" &&
+ (match.summary.activeSessionId ?? match.summary.id) === match.worker.descriptor.rootActiveSessionId;
+ if (!isRootKill) {
+ return this.forwardToWorker(match.worker, resolvedCommand);
+ }
+ this.persistWorkerStopTombstone(match.worker, true);
+ let response: DaemonResponse;
+ try {
+ response = await this.forwardToWorker(match.worker, resolvedCommand);
+ } finally {
+ await this.stopWorker(match.worker, true, false, true);
+ }
+ return response;
+ }
+
+ private async handleList(command: Extract<DaemonCommand, { type: "list" }>): Promise<DaemonResponse> {
+ await Promise.all(
+ [...this.workers.values()].map((worker) => this.refreshWorkerSummaries(worker).catch(() => undefined)),
+ );
+ await this.syncAgentPeers().catch((error) => this.log(`Could not synchronize agent peers: ${String(error)}`));
+ const active = [...this.workers.values()].flatMap((worker) =>
+ [...worker.summaries.values()].map((summary) => this.publicSummary(worker, summary)),
+ );
+ if (!command.all) {
+ return success(command.id, "list", { sessions: active });
+ }
+ const sessionDir = command.sessionDir ?? this.defaultSessionConfig.sessionDir;
+ const saved = await this.catalog.list(command.cwd ? resolve(command.cwd) : undefined, sessionDir);
+ return success(command.id, "list", { sessions: mergeSessionLists(active, saved) });
+ }
+
+ private async handleSavedSessionList(
+ client: DaemonSocketClient,
+ command: Extract<DaemonCommand, { type: "list_saved_sessions" }>,
+ ): Promise<DaemonResponse> {
+ let cwd: string;
+ let sessionDir: string | undefined;
+ let activeSessionId: string | undefined;
+ if ("activeSessionId" in command) {
+ const match = await this.findWorker(command.activeSessionId);
+ cwd = match.summary.cwd;
+ sessionDir = this.defaultSessionConfig.sessionDir;
+ activeSessionId = match.summary.activeSessionId ?? match.summary.id;
+ } else {
+ cwd = resolve(command.cwd);
+ sessionDir = command.sessionDir;
+ }
+ const callbacks = command.id
+ ? {
+ onProgress: (loaded: number, total: number) =>
+ this.write(client, {
+ id: command.id,
+ type: "session_list_progress",
+ command: "list_saved_sessions",
+ ...(activeSessionId ? { activeSessionId } : {}),
+ loaded,
+ total,
+ }),
+ onSession: (session: SessionInfo) =>
+ this.write(client, {
+ id: command.id,
+ type: "session_list_item",
+ command: "list_saved_sessions",
+ ...(activeSessionId ? { activeSessionId } : {}),
+ session: serializeSavedSessionInfo(session),
+ }),
+ }
+ : undefined;
+ const saved = await this.catalog.list(command.scope === "current" ? cwd : undefined, sessionDir, callbacks);
+ return success(command.id, "list_saved_sessions", { sessions: saved.map(serializeSavedSessionInfo) });
+ }
+
+ private async createOrReuseWorker(clientId: string, command: DaemonCreateCommand): Promise<ResidentWorker> {
+ let createCommand = command;
+ if (command.sessionPath) {
+ const activeMatches = this.matchWorkers(command.sessionPath);
+ if (activeMatches.length === 1) {
+ return activeMatches[0]!.worker;
+ }
+ if (activeMatches.length > 1) {
+ throw new Error(`Ambiguous active session "${command.sessionPath}"`);
+ }
+ const config = mergeAgentSessionRuntimeConfig(this.defaultSessionConfig, command.config);
+ const sessionPath = looksLikeSessionPath(command.sessionPath)
+ ? resolve(command.sessionPath)
+ : await this.catalog.resolve(command.sessionPath, config.cwd ?? process.cwd(), config.sessionDir);
+ createCommand = { ...command, sessionPath };
+ const existing = this.findWorkerBySessionFile(sessionPath);
+ if (existing) {
+ return existing.worker;
+ }
+ }
+ const key = createCommand.sessionPath
+ ? resolve(createCommand.sessionPath)
+ : `new:${command.id ? createCommandIdempotencyKey(clientId, command.id) : createActiveSessionId()}`;
+ const pending = this.openingWorkers.get(key);
+ if (pending) {
+ return pending;
+ }
+ const opening = this.launchWorker(createCommand);
+ this.openingWorkers.set(key, opening);
+ try {
+ return await opening;
+ } finally {
+ if (this.openingWorkers.get(key) === opening) {
+ this.openingWorkers.delete(key);
+ }
+ }
+ }
+
+ private async launchWorker(command: DaemonCreateCommand, existing?: ResidentWorker): Promise<ResidentWorker> {
+ if (existing && this.isWorkerRecoveryCancelled(existing)) {
+ throw new Error(`Session worker ${existing.descriptor.workerId} recovery was cancelled`);
+ }
+ const recoveryStopRevision = existing?.stopRevision;
+ const createCommand: DaemonCreateCommand = {
+ ...command,
+ config: mergeAgentSessionRuntimeConfig(this.defaultSessionConfig, command.config),
+ };
+ const workerId = existing?.descriptor.workerId ?? createActiveSessionId();
+ const rootActiveSessionId = existing?.descriptor.rootActiveSessionId ?? createActiveSessionId();
+ const socketPath = existing?.descriptor.socketPath ?? workerSocketPath(this.socketPath, workerId);
+ const token = existing?.descriptor.authenticationToken ?? randomBytes(32).toString("base64url");
+ const now = new Date().toISOString();
+ const descriptorPath = existing?.descriptorPath ?? join(this.descriptorDir, `${workerId}.json`);
+ const recoveryJournalPath =
+ existing?.descriptor.recoveryJournalPath ?? join(this.descriptorDir, `${workerId}.recovery.jsonl`);
+ const orphanProcessJournalPath =
+ existing?.descriptor.orphanProcessJournalPath ?? join(this.descriptorDir, `${workerId}.orphans.jsonl`);
+ const launch = createCliSubprocessLaunchSpec(["--mode", "daemon", "--daemon-socket", socketPath]);
+ const child: ChildProcess = spawn(launch.command, launch.args, {
+ cwd: createCommand.config?.cwd ?? process.cwd(),
+ detached: true,
+ env: {
+ ...process.env,
+ [DAEMON_WORKER_ROLE_ENV]: "1",
+ [DAEMON_WORKER_TOKEN_ENV]: token,
+ [DAEMON_WORKER_ACTIVE_SESSION_ID_ENV]: rootActiveSessionId,
+ [DAEMON_WORKER_SUPERVISOR_SOCKET_ENV]: this.socketPath,
+ [DAEMON_WORKER_RECOVERY_JOURNAL_ENV]: recoveryJournalPath,
+ [ORPHAN_PROCESS_JOURNAL_ENV]: orphanProcessJournalPath,
+ [SESSION_LEASES_ENABLED_ENV]: "1",
+ [SESSION_LEASE_OWNER_ID_ENV]: rootActiveSessionId,
+ },
+ stdio: "ignore",
+ });
+ child.on("error", (error) => {
+ this.log(
+ `Session worker ${workerId} process error: ${error instanceof Error ? error.message : String(error)}`,
+ );
+ });
+ if (!child.pid) {
+ throw new Error("Failed to obtain daemon session worker pid");
+ }
+ const childProcessStartId = getProcessStartId(child.pid);
+ child.unref();
+
+ const descriptor: DaemonWorkerDescriptor = {
+ version: 1,
+ workerId,
+ pid: child.pid,
+ ...(childProcessStartId ? { processStartId: childProcessStartId } : {}),
+ socketPath,
+ recoveryJournalPath,
+ orphanProcessJournalPath,
+ supervisorSocketPath: this.socketPath,
+ authenticationToken: token,
+ rootActiveSessionId,
+ createdAt: existing?.descriptor.createdAt ?? now,
+ updatedAt: now,
+ lifecycle: "starting",
+ createCommand: { ...createCommand, id: undefined },
+ consecutiveFailures: existing?.descriptor.consecutiveFailures ?? 0,
+ };
+ const worker = existing ?? {
+ descriptor,
+ descriptorPath,
+ summaries: new Map(),
+ snapshotCache: new Map(),
+ transcriptCaches: new Map(),
+ incomingTranscriptActiveSessionIds: new Set(),
+ snapshotLoads: new Map(),
+ intentionalStop: false,
+ stopRevision: 0,
+ };
+ worker.descriptor = descriptor;
+ worker.intentionalStop = false;
+ this.workers.set(workerId, worker);
+ this.persistWorker(worker);
+
+ try {
+ const client = await this.connectWorker(worker, WORKER_CONNECT_TIMEOUT_MS);
+ const response = await client.request(withoutCommandId(createCommand), WORKER_REQUEST_TIMEOUT_MS);
+ if (!response.success) {
+ throw deserializeDaemonError(response);
+ }
+ if (!isSessionSummary(response.data)) {
+ throw new Error("Session worker returned an invalid create response");
+ }
+ const summary = response.data;
+ if ((summary.activeSessionId ?? summary.id) !== rootActiveSessionId) {
+ throw new Error("Session worker did not preserve its assigned active session id");
+ }
+ worker.summaries.set(rootActiveSessionId, summary);
+ worker.descriptor.rootSessionId = summary.sessionId;
+ worker.descriptor.sessionFile = summary.sessionFile;
+ await this.subscribeWorker(worker, rootActiveSessionId);
+ await this.refreshWorkerSummaries(worker);
+ if (existing && (this.isWorkerRecoveryCancelled(worker) || worker.stopRevision !== recoveryStopRevision)) {
+ throw new Error(`Session worker ${workerId} recovery was cancelled`);
+ }
+ worker.descriptor.lifecycle = "ready";
+ worker.descriptor.consecutiveFailures = 0;
+ worker.descriptor.lastError = undefined;
+ this.persistWorker(worker);
+ await this.syncAgentPeers();
+ return worker;
+ } catch (error) {
+ const shouldResumeRecovery =
+ existing !== undefined &&
+ !this.shuttingDown &&
+ worker.descriptor.stopRequestedAt === undefined &&
+ worker.stopRevision === recoveryStopRevision;
+ await this.stopWorker(worker, existing === undefined, true, false, existing !== undefined).catch((stopError) =>
+ this.log(`Could not stop failed worker ${workerId}: ${String(stopError)}`),
+ );
+ if (
+ shouldResumeRecovery &&
+ !this.shuttingDown &&
+ worker.descriptor.stopRequestedAt === undefined &&
+ worker.stopRevision === recoveryStopRevision
+ ) {
+ worker.intentionalStop = false;
+ worker.descriptor.lifecycle = "recovering";
+ this.workers.set(workerId, worker);
+ this.persistWorker(worker);
+ }
+ throw error;
+ }
+ }
+
+ private async connectWorker(worker: ResidentWorker, timeoutMs: number): Promise<DaemonWorkerClient> {
+ const deadline = Date.now() + timeoutMs;
+ let lastError: unknown;
+ while (Date.now() < deadline) {
+ const client = new DaemonWorkerClient(worker.descriptor.socketPath);
+ try {
+ await client.connect(Math.min(500, Math.max(50, deadline - Date.now())));
+ await client.waitForHello(1000);
+ await client.authenticateWorker(worker.descriptor.authenticationToken, 1000);
+ client.onFrame((frame) => this.handleWorkerFrame(worker, frame));
+ client.onClose((error) => this.handleWorkerClose(worker, client, error));
+ worker.client?.close();
+ worker.client = client;
+ return client;
+ } catch (error) {
+ lastError = error;
+ client.close();
+ await delay(25);
+ }
+ }
+ throw new Error(`Timed out connecting to daemon session worker: ${String(lastError)}`);
+ }
+
+ private async subscribeWorker(worker: ResidentWorker, activeSessionId: string): Promise<void> {
+ if (!worker.client) {
+ throw new Error("Session worker is not connected");
+ }
+ const supportsExtensionUi = [...this.clients].some(
+ (client) => client.attachedActiveSessionIds.has(activeSessionId) && client.supportsExtensionUi,
+ );
+ const response = await worker.client.requestWorker({
+ type: "worker_subscribe",
+ activeSessionId,
+ capabilities: supportsExtensionUi
+ ? ["attach_snapshot", "event_sequence", "extension_ui", "slim_attach", "chunked_snapshot"]
+ : ["attach_snapshot", "event_sequence", "slim_attach", "chunked_snapshot"],
+ supportsExtensionUi,
+ });
+ if (!response.success) {
+ throw new Error(response.error);
+ }
+ }
+
+ private async adoptOrRecoverWorker(worker: ResidentWorker): Promise<void> {
+ if (worker.descriptor.stopRequestedAt) {
+ try {
+ // A tombstoned worker must not run long enough to elect another
+ // supervisor while its intentional stop is being adopted.
+ signalProcessGroupOrProcess(worker.descriptor.pid, "SIGKILL");
+ await this.stopWorker(worker, true, true, worker.descriptor.archiveOnStop === true);
+ this.log(`Completed intentional stop for worker ${worker.descriptor.workerId} during supervisor adoption`);
+ } catch (error) {
+ worker.descriptor.lifecycle = "failed";
+ worker.descriptor.lastError = error instanceof Error ? error.message : String(error);
+ this.persistWorker(worker);
+ this.log(`Could not complete intentional stop for worker ${worker.descriptor.workerId}: ${String(error)}`);
+ }
+ return;
+ }
+ try {
+ if (!isProcessAlive(worker.descriptor.pid)) {
+ throw new Error("Session worker process is no longer running");
+ }
+ const observedProcessStartId = getProcessStartId(worker.descriptor.pid);
+ await this.connectWorker(worker, 2000);
+ await this.subscribeWorker(worker, worker.descriptor.rootActiveSessionId);
+ await this.refreshWorkerSummaries(worker);
+ if (worker.descriptor.processStartId === undefined && observedProcessStartId) {
+ worker.descriptor.processStartId = observedProcessStartId;
+ }
+ worker.descriptor.lifecycle = "ready";
+ worker.descriptor.consecutiveFailures = 0;
+ this.persistWorker(worker);
+ } catch (error) {
+ this.log(`Could not adopt worker ${worker.descriptor.workerId}: ${String(error)}`);
+ await this.recoverWorker(worker);
+ }
+ }
+
+ private handleWorkerClose(worker: ResidentWorker, client: DaemonWorkerClient, error: Error): void {
+ if (worker.client !== client) {
+ return;
+ }
+ worker.client = undefined;
+ for (const activeSessionId of worker.incomingTranscriptActiveSessionIds) {
+ worker.transcriptCaches
+ .get(activeSessionId)
+ ?.markFailed(new Error("Session worker disconnected during snapshot transfer"));
+ }
+ worker.incomingTranscriptActiveSessionIds.clear();
+ if (this.shuttingDown || worker.intentionalStop) {
+ return;
+ }
+ worker.descriptor.lifecycle = "recovering";
+ worker.descriptor.lastError = error.message;
+ this.persistWorker(worker);
+ void this.syncAgentPeers().catch(() => undefined);
+ void this.recoverWorker(worker);
+ }
+
+ private async recoverWorker(worker: ResidentWorker): Promise<void> {
+ if (this.isWorkerRecoveryCancelled(worker)) {
+ return;
+ }
+ if (worker.recovery) {
+ return worker.recovery;
+ }
+ worker.recovery = (async () => {
+ for (const [retryIndex, retryDelay] of WORKER_RETRY_DELAYS_MS.entries()) {
+ await delay(retryDelay);
+ if (this.isWorkerRecoveryCancelled(worker)) {
+ return;
+ }
+ try {
+ const processAlive = isProcessAlive(worker.descriptor.pid);
+ const observedProcessStartId = processAlive ? getProcessStartId(worker.descriptor.pid) : undefined;
+ const processIdentityMatches =
+ worker.descriptor.processStartId === undefined ||
+ observedProcessStartId === worker.descriptor.processStartId;
+ if (processAlive && processIdentityMatches) {
+ try {
+ await this.connectWorker(worker, 1500);
+ await this.subscribeWorker(worker, worker.descriptor.rootActiveSessionId);
+ await this.refreshWorkerSummaries(worker);
+ if (this.isWorkerRecoveryCancelled(worker)) {
+ return;
+ }
+ if (worker.descriptor.processStartId === undefined && observedProcessStartId) {
+ worker.descriptor.processStartId = observedProcessStartId;
+ }
+ worker.descriptor.lifecycle = "ready";
+ worker.descriptor.consecutiveFailures = 0;
+ this.persistWorker(worker);
+ await this.syncAgentPeers().catch((error) =>
+ this.log(`Could not synchronize agent peers after worker recovery: ${String(error)}`),
+ );
+ return;
+ } catch (error) {
+ worker.client?.close();
+ worker.client = undefined;
+ if (retryIndex < WORKER_RETRY_DELAYS_MS.length - 1) {
+ throw error;
+ }
+ }
+ }
+ if (
+ processAlive &&
+ (worker.descriptor.processStartId === undefined || observedProcessStartId === undefined)
+ ) {
+ throw new Error(
+ `Cannot safely replace live session worker ${worker.descriptor.workerId} without a verified process identity`,
+ );
+ }
+ const safeToKillWorkerProcess =
+ processAlive && processIdentityMatches && worker.descriptor.processStartId !== undefined;
+ await this.recoverUncertainWorkerOperations(worker, safeToKillWorkerProcess);
+ if (this.isWorkerRecoveryCancelled(worker)) {
+ return;
+ }
+ await this.launchWorker(worker.descriptor.createCommand, worker);
+ return;
+ } catch (error) {
+ if (this.isWorkerRecoveryCancelled(worker)) {
+ return;
+ }
+ worker.client?.close();
+ worker.client = undefined;
+ worker.descriptor.consecutiveFailures++;
+ worker.descriptor.lastFailureAt = new Date().toISOString();
+ worker.descriptor.lastError = error instanceof Error ? error.message : String(error);
+ this.persistWorker(worker);
+ }
+ }
+ worker.descriptor.lifecycle = "failed";
+ this.persistWorker(worker);
+ await this.syncAgentPeers().catch(() => undefined);
+ this.log(`Worker ${worker.descriptor.workerId} failed after three recovery attempts`);
+ })().finally(() => {
+ worker.recovery = undefined;
+ });
+ return worker.recovery;
+ }
+
+ private isWorkerRecoveryCancelled(worker: ResidentWorker): boolean {
+ return (
+ this.shuttingDown ||
+ worker.intentionalStop ||
+ worker.descriptor.stopRequestedAt !== undefined ||
+ this.workers.get(worker.descriptor.workerId) !== worker
+ );
+ }
+
+ private async recoverUncertainWorkerOperations(worker: ResidentWorker, killWorkerProcess = true): Promise<void> {
+ if (killWorkerProcess) {
+ signalProcessGroupOrProcess(worker.descriptor.pid, "SIGKILL");
+ }
+ const orphanProcessJournalPath = worker.descriptor.orphanProcessJournalPath;
+ if (orphanProcessJournalPath) {
+ try {
+ for (const orphan of readActiveOrphanProcesses(orphanProcessJournalPath, worker.descriptor.pid)) {
+ if (!isOrphanProcessIdentityCurrent(orphan)) {
+ continue;
+ }
+ const { pid } = orphan;
+ try {
+ process.kill(-pid, "SIGKILL");
+ } catch {
+ try {
+ process.kill(pid, "SIGKILL");
+ } catch {
+ // The detached resource may already have exited.
+ }
+ }
+ }
+ clearOrphanProcessJournal(orphanProcessJournalPath);
+ } catch (error) {
+ this.log(`Could not reap orphaned worker resources: ${String(error)}`);
+ }
+ }
+ const journal = new WorkerRecoveryJournal(worker.descriptor.recoveryJournalPath);
+ const latest = journal.getLatest();
+ const uncertain = latest.filter((record) => record.busy);
+ if (uncertain.length === 0) {
+ return;
+ }
+ const interruptedSessions = new Map<
+ string,
+ { activeSessionId: string; sessionFile: string; operations: Set<string> }
+ >();
+ for (const record of uncertain) {
+ const sessionFile =
+ record.sessionFile ??
+ (record.activeSessionId === worker.descriptor.rootActiveSessionId
+ ? worker.descriptor.sessionFile
+ : undefined);
+ if (!sessionFile) {
+ continue;
+ }
+ const key = `${record.activeSessionId}\0${sessionFile}`;
+ let interrupted = interruptedSessions.get(key);
+ if (!interrupted) {
+ interrupted = { activeSessionId: record.activeSessionId, sessionFile, operations: new Set() };
+ interruptedSessions.set(key, interrupted);
+ }
+ interrupted.operations.add(record.operation);
+ }
+ await Promise.all(
+ [...interruptedSessions.values()].map((interrupted) =>
+ this.catalog.markInterrupted(interrupted.sessionFile, interrupted.activeSessionId, [
+ ...interrupted.operations,
+ ]),
+ ),
+ );
+ for (const record of latest) {
+ journal.record({
+ activeSessionId: record.activeSessionId,
+ sessionId: record.sessionId,
+ ...(record.sessionFile ? { sessionFile: record.sessionFile } : {}),
+ busy: false,
+ operation: "recovery_hold",
+ });
+ }
+ this.log(
+ `Recovered worker ${worker.descriptor.workerId} without replaying uncertain operations: ${uncertain
+ .map((record) => record.operation)
+ .join(", ")}`,
+ );
+ }
+
+ private async refreshWorkerSummaries(worker: ResidentWorker): Promise<void> {
+ if (!worker.client) {
+ throw new Error("Session worker is not connected");
+ }
+ const response = await worker.client.request({ type: "list" }, 5000);
+ const summaries = sessionSummariesFromResponse(response);
+ worker.summaries = new Map(summaries.map((summary) => [summary.activeSessionId ?? summary.id, summary]));
+ for (const summary of summaries) {
+ const activeSessionId = summary.activeSessionId ?? summary.id;
+ if (summary.streamingMessage?.role === "assistant") {
+ this.streamReconstructor.seed(activeSessionId, summary.streamingMessage);
+ } else if (!summary.isStreaming) {
+ this.streamReconstructor.clear(activeSessionId);
+ }
+ }
+ const root = worker.summaries.get(worker.descriptor.rootActiveSessionId);
+ if (root) {
+ worker.descriptor.rootSessionId = root.sessionId;
+ worker.descriptor.sessionFile = root.sessionFile;
+ worker.descriptor.createCommand = {
+ ...worker.descriptor.createCommand,
+ sessionPath: root.sessionFile,
+ continueRecent: false,
+ config: {
+ ...worker.descriptor.createCommand.config,
+ cwd: root.cwd,
+ },
+ };
+ this.persistWorker(worker);
+ }
+ }
+
+ private syncAgentPeers(): Promise<void> {
+ const sync = this.agentPeerSyncQueue
+ .catch(() => undefined)
+ .then(async () => {
+ const readyWorkers = [...this.workers.values()].filter(
+ (worker): worker is ResidentWorker & { client: DaemonWorkerClient } =>
+ worker.descriptor.lifecycle === "ready" && worker.client !== undefined,
+ );
+ await Promise.all(
+ readyWorkers.map(async (worker) => {
+ const peers = readyWorkers
+ .filter((candidate) => candidate !== worker)
+ .flatMap((candidate) =>
+ [...candidate.summaries.values()].map((summary) => this.agentPeerSummary(summary)),
+ );
+ const response = await worker.client.requestWorker({ type: "worker_sync_agent_peers", peers }, 5000);
+ if (!response.success) {
+ throw new Error(response.error);
+ }
+ }),
+ );
+ });
+ this.agentPeerSyncQueue = sync;
+ return sync;
+ }
+
+ private agentPeerSummary(summary: SessionSummary): AgentSessionMessageAgentSummary {
+ return {
+ activeSessionId: summary.activeSessionId ?? summary.id,
+ sessionId: summary.sessionId,
+ ...(summary.sessionName ? { sessionName: summary.sessionName } : {}),
+ runtimeKind: summary.runtimeKind ?? "top-level",
+ cwd: summary.cwd,
+ isStreaming: summary.isStreaming,
+ pendingMessageCount: summary.pendingMessageCount,
+ ...(summary.parentActiveSessionId ? { parentActiveSessionId: summary.parentActiveSessionId } : {}),
+ ...(summary.rlmChildId ? { rlmChildId: summary.rlmChildId } : {}),
+ };
+ }
+
+ private publicSummary(worker: ResidentWorker, summary: SessionSummary): SessionSummary {
+ const activeSessionId = summary.activeSessionId ?? summary.id;
+ return {
+ ...summary,
+ attachedClients: [...this.clients].filter((client) => client.attachedActiveSessionIds.has(activeSessionId))
+ .length,
+ workerState: worker.descriptor.lifecycle,
+ workerPid: worker.descriptor.pid,
+ };
+ }
+
+ private async findWorker(selector: string): Promise<WorkerMatch> {
+ let matches = this.matchWorkers(selector);
+ if (matches.length === 0) {
+ await Promise.all(
+ [...this.workers.values()].map((worker) => this.refreshWorkerSummaries(worker).catch(() => undefined)),
+ );
+ matches = this.matchWorkers(selector);
+ }
+ if (matches.length === 1) {
+ return matches[0]!;
+ }
+ if (matches.length > 1) {
+ throw new Error(`Ambiguous active session "${selector}"`);
+ }
+ throw new Error(`Unknown active session: ${selector}`);
+ }
+
+ private matchWorkers(selector: string): WorkerMatch[] {
+ const exact: WorkerMatch[] = [];
+ const suffix: WorkerMatch[] = [];
+ for (const worker of this.workers.values()) {
+ for (const summary of worker.summaries.values()) {
+ const activeSessionId = summary.activeSessionId ?? summary.id;
+ const match = { worker, summary };
+ if (activeSessionId === selector || summary.sessionId === selector || summary.sessionName === selector) {
+ exact.push(match);
+ } else if (
+ matchesSessionIdSuffix(activeSessionId, selector) ||
+ matchesSessionIdSuffix(summary.sessionId, selector)
+ ) {
+ suffix.push(match);
+ }
+ }
+ }
+ return exact.length > 0 ? exact : suffix;
+ }
+
+ private findWorkerBySessionFile(sessionFile: string): WorkerMatch | undefined {
+ const target = resolve(sessionFile);
+ for (const worker of this.workers.values()) {
+ for (const summary of worker.summaries.values()) {
+ if (summary.sessionFile && resolve(summary.sessionFile) === target) {
+ return { worker, summary };
+ }
+ }
+ }
+ return undefined;
+ }
+
+ private async forwardToWorker(
+ worker: ResidentWorker,
+ command: DaemonCommand,
+ timeoutMs = WORKER_REQUEST_TIMEOUT_MS,
+ ): Promise<DaemonResponse> {
+ if (!worker.client || worker.descriptor.lifecycle !== "ready") {
+ throw new Error(`Session worker is ${worker.descriptor.lifecycle}`);
+ }
+ const response = await worker.client.request(withoutCommandId(command), timeoutMs);
+ if (command.type === "get_state" && response.success && isSessionSummary(response.data)) {
+ return { ...response, id: command.id, data: this.publicSummary(worker, response.data) };
+ }
+ if (command.type === "rename" && response.success && isSessionSummary(response.data)) {
+ await this.refreshWorkerSummaries(worker);
+ return { ...response, id: command.id, data: this.publicSummary(worker, response.data) };
+ }
+ return responseWithId(response, command.id);
+ }
+
+ private async attachClient(
+ client: DaemonSocketClient,
+ command: Extract<DaemonCommand, { type: "attach" }>,
+ ): Promise<WorkerAttachData> {
+ const match = await this.findWorker(command.activeSessionId);
+ const activeSessionId = match.summary.activeSessionId ?? match.summary.id;
+ if (command.clientId) {
+ client.id = command.clientId;
+ }
+ client.capabilities = normalizeCapabilities(command.capabilities, command.supportsExtensionUi);
+ client.supportsExtensionUi = client.capabilities.has("extension_ui");
+
+ let result = match.worker.snapshotCache.get(activeSessionId);
+ if (
+ result &&
+ !client.capabilities.has("chunked_snapshot") &&
+ result.snapshot.messages.length < result.snapshot.summary.messageCount
+ ) {
+ result = undefined;
+ }
+ if (!result) {
+ const snapshotLoadKey = `${activeSessionId}:${client.capabilities.has("chunked_snapshot") ? "chunked" : "full"}`;
+ let loading = match.worker.snapshotLoads.get(snapshotLoadKey);
+ if (!loading) {
+ loading = (async () => {
+ if (!match.worker.client) {
+ throw new Error("Session worker is not connected");
+ }
+ const response = await match.worker.client.request({
+ type: "attach",
+ activeSessionId,
+ capabilities: client.capabilities.has("chunked_snapshot")
+ ? ["attach_snapshot", "event_sequence", "slim_attach", "chunked_snapshot"]
+ : ["attach_snapshot", "event_sequence", "slim_attach"],
+ supportsExtensionUi: false,
+ env: command.env ?? collectDaemonClientEnv(),
+ });
+ const loaded = attachResultFromResponse(response);
+ if (loaded.snapshotStream) {
+ let transcript = match.worker.transcriptCaches.get(activeSessionId);
+ if (transcript && transcript.snapshotId !== loaded.snapshotStream.id) {
+ transcript.dispose();
+ transcript = undefined;
+ }
+ if (!transcript) {
+ transcript = new SnapshotTranscriptCache({
+ activeSessionId,
+ snapshotId: loaded.snapshotStream.id,
+ cacheRoot: this.snapshotCacheRoot,
+ targetChunkBytes: loaded.snapshotStream.targetChunkBytes,
+ });
+ match.worker.transcriptCaches.set(activeSessionId, transcript);
+ }
+ match.worker.incomingTranscriptActiveSessionIds.add(activeSessionId);
+ }
+ match.worker.snapshotCache.set(activeSessionId, loaded);
+ return loaded;
+ })().finally(() => {
+ match.worker.snapshotLoads.delete(snapshotLoadKey);
+ });
+ match.worker.snapshotLoads.set(snapshotLoadKey, loading);
+ }
+ result = await loading;
+ }
+ client.attachedActiveSessionIds.add(activeSessionId);
+ try {
+ const publicSummary = this.publicSummary(match.worker, result.snapshot.summary);
+ if (publicSummary.streamingMessage?.role === "assistant") {
+ this.streamReconstructor.seed(activeSessionId, publicSummary.streamingMessage);
+ } else {
+ for (let index = result.snapshot.messages.length - 1; index >= 0; index--) {
+ const latestMessage = result.snapshot.messages[index];
+ if (latestMessage?.role === "assistant") {
+ this.streamReconstructor.seed(activeSessionId, latestMessage);
+ break;
+ }
+ }
+ }
+ const publicResult: DaemonAttachResult = {
+ ...result,
+ state: result.state ? publicSummary : undefined,
+ snapshot: { ...result.snapshot, summary: publicSummary },
+ client: { id: client.id, capabilities: [...client.capabilities] },
+ };
+ if (publicResult.state && publicResult.messages) {
+ this.write(client, {
+ type: "session_attached",
+ activeSessionId,
+ state: publicResult.state,
+ messages: publicResult.messages,
+ snapshot: publicResult.snapshot,
+ replay: publicResult.replay,
+ lastEventSequence: publicResult.lastEventSequence,
+ });
+ }
+ await this.syncWorkerExtensionUi(activeSessionId);
+ return { result: publicResult, worker: match.worker };
+ } catch (error) {
+ client.attachedActiveSessionIds.delete(activeSessionId);
+ throw error;
+ }
+ }
+
+ private getOrCreateTranscriptCache(worker: ResidentWorker, result: DaemonAttachResult): SnapshotTranscriptCache {
+ const activeSessionId = result.activeSessionId;
+ const existing = worker.transcriptCaches.get(activeSessionId);
+ if (existing) {
+ return existing;
+ }
+ if (result.snapshot.messages.length < result.snapshot.summary.messageCount) {
+ throw new Error("Session worker returned snapshot metadata without a transcript cache");
+ }
+ const revision = createHash("sha256")
+ .update(
+ `${activeSessionId}:${result.snapshot.summary.sessionId}:${result.lastEventSequence}:${result.snapshot.messages.length}`,
+ )
+ .digest("hex")
+ .slice(0, 16);
+ const transcript = new SnapshotTranscriptCache({
+ activeSessionId,
+ snapshotId: `${activeSessionId}-${revision}`,
+ messages: result.snapshot.messages,
+ cacheRoot: this.snapshotCacheRoot,
+ targetChunkBytes: SNAPSHOT_TARGET_CHUNK_BYTES,
+ });
+ worker.transcriptCaches.set(activeSessionId, transcript);
+ worker.snapshotCache.set(activeSessionId, {
+ ...result,
+ messages: result.messages ? [] : undefined,
+ snapshot: { ...result.snapshot, messages: [] },
+ });
+ return transcript;
+ }
+
+ private createStreamedAttachResult(
+ result: DaemonAttachResult,
+ transcript: SnapshotTranscriptCache,
+ ): DaemonAttachResult {
+ return {
+ ...result,
+ messages: result.messages ? [] : undefined,
+ snapshot: { ...result.snapshot, messages: [] },
+ snapshotStream: {
+ id: transcript.snapshotId,
+ messageCount: result.snapshot.summary.messageCount,
+ targetChunkBytes: transcript.targetChunkBytes,
+ },
+ };
+ }
+
+ private async streamSnapshot(
+ client: DaemonSocketClient,
+ result: DaemonAttachResult,
+ transcript: SnapshotTranscriptCache,
+ purpose: "attach" | "replacement" | "resync" = "attach",
+ ): Promise<void> {
+ const stream = result.snapshotStream;
+ if (!stream || client.socket.destroyed) {
+ return;
+ }
+ const releaseTranscript = transcript.retain();
+ client.snapshotStreaming = true;
+ if (!client.snapshotActiveSessionIds) {
+ client.snapshotActiveSessionIds = new Set();
+ }
+ client.snapshotActiveSessionIds.add(result.activeSessionId);
+ const { messages: _messages, ...snapshotHeader } = result.snapshot;
+ try {
+ if (
+ !(await this.writeSnapshotRecord(client, {
+ type: "session_snapshot_begin",
+ activeSessionId: result.activeSessionId,
+ snapshotId: stream.id,
+ snapshot: snapshotHeader,
+ messageCount: stream.messageCount,
+ targetChunkBytes: stream.targetChunkBytes,
+ purpose,
+ }))
+ ) {
+ return;
+ }
+ let chunkCount = 0;
+ while (true) {
+ const chunk = await transcript.waitForChunk(chunkCount);
+ if (!chunk) {
+ break;
+ }
+ if (!(await this.writeSnapshotBuffer(client, chunk))) {
+ return;
+ }
+ chunkCount++;
+ }
+ await this.writeSnapshotRecord(client, {
+ type: "session_snapshot_end",
+ activeSessionId: result.activeSessionId,
+ snapshotId: stream.id,
+ chunkCount,
+ lastEventSequence: result.lastEventSequence,
+ lastEventCursor: result.lastEventCursor,
+ });
+ } finally {
+ client.snapshotActiveSessionIds?.delete(result.activeSessionId);
+ client.snapshotStreaming = (client.snapshotActiveSessionIds?.size ?? 0) > 0;
+ if (!client.snapshotStreaming) {
+ client.backpressured = false;
+ }
+ releaseTranscript();
+ if (!client.snapshotStreaming && client.catchupActiveSessionIds?.size) {
+ void this.catchUpClient(client);
+ }
+ }
+ }
+
+ private writeSnapshotRecord(client: DaemonSocketClient, message: DaemonOutbound): Promise<boolean> {
+ return this.writeSnapshotBuffer(client, Buffer.from(serializeJsonLine(message)));
+ }
+
+ private async writeSnapshotBuffer(client: DaemonSocketClient, buffer: Uint8Array): Promise<boolean> {
+ if (client.socket.destroyed) {
+ return false;
+ }
+ if (this.writeSerialized(client, buffer)) {
+ return true;
+ }
+ return new Promise<boolean>((resolveDrain) => {
+ let settled = false;
+ const finish = (value: boolean) => {
+ if (settled) {
+ return;
+ }
+ settled = true;
+ client.socket.off("drain", onDrain);
+ client.socket.off("close", onClose);
+ client.socket.off("error", onClose);
+ resolveDrain(value);
+ };
+ const onDrain = () => finish(true);
+ const onClose = () => finish(false);
+ client.socket.once("drain", onDrain);
+ client.socket.once("close", onClose);
+ client.socket.once("error", onClose);
+ });
+ }
+
+ private detachClient(client: DaemonSocketClient, activeSessionId?: string): void {
+ const targets = activeSessionId ? [activeSessionId] : [...client.attachedActiveSessionIds];
+ for (const selector of targets) {
+ const match = this.matchWorkers(selector)[0];
+ const resolvedId = match ? (match.summary.activeSessionId ?? match.summary.id) : selector;
+ if (!client.attachedActiveSessionIds.delete(resolvedId)) {
+ continue;
+ }
+ this.write(client, { type: "session_detached", activeSessionId: resolvedId });
+ void this.syncWorkerExtensionUi(resolvedId);
+ }
+ }
+
+ private async syncWorkerExtensionUi(activeSessionId: string): Promise<void> {
+ const match = this.matchWorkers(activeSessionId)[0];
+ if (!match?.worker.client) {
+ return;
+ }
+ await this.subscribeWorker(match.worker, match.summary.activeSessionId ?? match.summary.id).catch(
+ () => undefined,
+ );
+ }
+
+ private handleWorkerFrame(worker: ResidentWorker, frame: PrivateFrame<DaemonWorkerFrameHeader>): void {
+ if (frame.header.kind !== "outbound") {
+ return;
+ }
+ const { outboundType, activeSessionId, sessionEventType, payloadEncoding, snapshotPurpose } = frame.header;
+ if (outboundType === "session_snapshot_begin" && activeSessionId) {
+ try {
+ const begin = JSON.parse(frame.payload.toString("utf8")) as Extract<
+ DaemonOutbound,
+ { type: "session_snapshot_begin" }
+ >;
+ if (
+ begin.type !== "session_snapshot_begin" ||
+ begin.activeSessionId !== activeSessionId ||
+ typeof begin.snapshotId !== "string" ||
+ typeof begin.targetChunkBytes !== "number" ||
+ !begin.snapshot ||
+ !isSessionSummary(begin.snapshot.summary)
+ ) {
+ throw new Error("Worker returned an invalid snapshot begin frame");
+ }
+ const existing = worker.transcriptCaches.get(activeSessionId);
+ let transcript = existing;
+ if (!existing || existing.snapshotId !== begin.snapshotId) {
+ existing?.dispose();
+ transcript = new SnapshotTranscriptCache({
+ activeSessionId,
+ snapshotId: begin.snapshotId,
+ cacheRoot: this.snapshotCacheRoot,
+ targetChunkBytes: begin.targetChunkBytes,
+ });
+ worker.transcriptCaches.set(activeSessionId, transcript);
+ }
+ if (!transcript) {
+ throw new Error("Worker snapshot cache could not be initialized");
+ }
+ const publicSummary = this.publicSummary(worker, begin.snapshot.summary);
+ const snapshot = {
+ ...begin.snapshot,
+ summary: publicSummary,
+ messages: [],
+ };
+ const result: DaemonAttachResult = {
+ protocol: DAEMON_PROTOCOL_INFO,
+ activeSessionId,
+ snapshot,
+ replay: {
+ status: "complete",
+ toSequence: snapshot.lastEventSequence,
+ ...(snapshot.lastEventCursor ? { toCursor: snapshot.lastEventCursor } : {}),
+ },
+ lastEventSequence: snapshot.lastEventSequence,
+ ...(snapshot.lastEventCursor ? { lastEventCursor: snapshot.lastEventCursor } : {}),
+ snapshotStream: {
+ id: begin.snapshotId,
+ messageCount: begin.messageCount,
+ targetChunkBytes: begin.targetChunkBytes,
+ },
+ client: { id: "supervisor", capabilities: ["chunked_snapshot"] },
+ };
+ worker.snapshotCache.set(activeSessionId, result);
+ worker.incomingTranscriptActiveSessionIds.add(activeSessionId);
+ if (snapshotPurpose === "replacement") {
+ for (const client of this.clients) {
+ if (
+ !client.attachedActiveSessionIds.has(activeSessionId) ||
+ !client.capabilities.has("chunked_snapshot")
+ ) {
+ continue;
+ }
+ void this.streamSnapshot(client, result, transcript, "replacement").catch((error) =>
+ this.log(`Failed to stream replacement snapshot for ${activeSessionId}: ${String(error)}`),
+ );
+ }
+ }
+ } catch (error) {
+ this.log(`Invalid worker snapshot begin frame: ${String(error)}`);
+ }
+ return;
+ }
+ if (outboundType === "session_snapshot_chunk" && activeSessionId) {
+ const transcript = worker.transcriptCaches.get(activeSessionId);
+ if (transcript && worker.incomingTranscriptActiveSessionIds.has(activeSessionId)) {
+ try {
+ transcript.appendEncodedChunk(Buffer.from(frame.payload));
+ } catch (error) {
+ transcript.markFailed(error instanceof Error ? error : new Error(String(error)));
+ worker.incomingTranscriptActiveSessionIds.delete(activeSessionId);
+ }
+ }
+ return;
+ }
+ if (outboundType === "session_snapshot_end" && activeSessionId) {
+ worker.transcriptCaches.get(activeSessionId)?.markComplete();
+ worker.incomingTranscriptActiveSessionIds.delete(activeSessionId);
+ if (snapshotPurpose === "replacement" || snapshotPurpose === "catchup") {
+ for (const client of this.clients) {
+ if (!client.attachedActiveSessionIds.has(activeSessionId)) continue;
+ if (snapshotPurpose === "replacement" && client.capabilities.has("chunked_snapshot")) continue;
+ this.queueCatchup(client, activeSessionId, snapshotPurpose === "replacement" ? "replacement" : "resync");
+ void this.catchUpClient(client);
+ }
+ }
+ return;
+ }
+ if (
+ outboundType === "daemon_hello" ||
+ outboundType === "response" ||
+ outboundType === "session_list_progress" ||
+ outboundType === "session_list_item" ||
+ outboundType === "session_attached" ||
+ outboundType === "session_detached" ||
+ !activeSessionId
+ ) {
+ return;
+ }
+ let publicPayload = frame.payload;
+ let decodedOutbound: DaemonOutbound | undefined;
+ if (payloadEncoding === "assistant-delta") {
+ let compactValue: unknown;
+ try {
+ compactValue = JSON.parse(frame.payload.toString("utf8"));
+ } catch {
+ this.scheduleCompactCatchup(worker, activeSessionId);
+ return;
+ }
+ if (!isCompactAssistantDelta(compactValue)) {
+ this.scheduleCompactCatchup(worker, activeSessionId);
+ return;
+ }
+ const reconstructed = this.streamReconstructor.reconstruct(compactValue);
+ if (!reconstructed) {
+ this.scheduleCompactCatchup(worker, activeSessionId);
+ return;
+ }
+ publicPayload = Buffer.from(serializeJsonLine(reconstructed));
+ } else if (
+ sessionEventType === "message_start" ||
+ sessionEventType === "message_end" ||
+ outboundType === "session_replaced" ||
+ outboundType === "session_resynced" ||
+ outboundType === "session_closed"
+ ) {
+ try {
+ decodedOutbound = JSON.parse(frame.payload.toString("utf8")) as DaemonOutbound;
+ this.streamReconstructor.observe(decodedOutbound);
+ } catch {
+ // A malformed worker event is still isolated to this worker connection.
+ }
+ }
+ const replacementSnapshotFollows =
+ decodedOutbound?.type === "session_replaced" && decodedOutbound.snapshotFollows === true;
+ this.invalidateWorkerSnapshot(
+ worker,
+ activeSessionId,
+ outboundType === "session_replaced" ||
+ outboundType === "session_closed" ||
+ isFinalizedTranscriptEvent(sessionEventType),
+ );
+ for (const client of this.clients) {
+ if (!client.attachedActiveSessionIds.has(activeSessionId)) {
+ continue;
+ }
+ if (replacementSnapshotFollows && !client.capabilities.has("chunked_snapshot")) {
+ continue;
+ }
+ if (outboundType === "extension_ui_request" && !client.supportsExtensionUi) {
+ continue;
+ }
+ if (client.snapshotActiveSessionIds?.has(activeSessionId)) {
+ this.queueCatchup(client, activeSessionId, outboundType === "session_replaced" ? "replacement" : "resync");
+ continue;
+ }
+ if (client.backpressured === true) {
+ this.queueCatchup(client, activeSessionId, outboundType === "session_replaced" ? "replacement" : "resync");
+ continue;
+ }
+ if (!this.writeSerialized(client, publicPayload)) {
+ this.queueCatchup(client, activeSessionId, outboundType === "session_replaced" ? "replacement" : "resync");
+ }
+ }
+ if (outboundType === "session_replaced" || outboundType === "session_closed") {
+ void this.refreshWorkerSummaries(worker)
+ .then(() => this.syncAgentPeers())
+ .catch(() => undefined);
+ } else if (
+ sessionEventType === "turn_start" ||
+ sessionEventType === "turn_end" ||
+ sessionEventType === "rlm_child_update"
+ ) {
+ void this.refreshWorkerSummaries(worker)
+ .then(() => this.syncAgentPeers())
+ .catch(() => undefined);
+ }
+ if (
+ decodedOutbound?.type === "session_closed" &&
+ decodedOutbound.reason === "shutdown" &&
+ activeSessionId === worker.descriptor.rootActiveSessionId &&
+ !this.shuttingDown
+ ) {
+ worker.intentionalStop = true;
+ this.workers.delete(worker.descriptor.workerId);
+ this.deleteWorkerDescriptor(worker);
+ void this.syncAgentPeers().catch(() => undefined);
+ }
+ }
+
+ private invalidateWorkerSnapshot(worker: ResidentWorker, activeSessionId: string, transcriptChanged = true): void {
+ worker.snapshotCache.delete(activeSessionId);
+ if (!transcriptChanged) {
+ return;
+ }
+ const transcript = worker.transcriptCaches.get(activeSessionId);
+ if (transcript) {
+ transcript.dispose();
+ worker.transcriptCaches.delete(activeSessionId);
+ }
+ worker.incomingTranscriptActiveSessionIds.delete(activeSessionId);
+ }
+
+ private scheduleCompactCatchup(worker: ResidentWorker, activeSessionId: string): void {
+ if (this.compactCatchupInProgress.has(activeSessionId)) {
+ return;
+ }
+ this.compactCatchupInProgress.add(activeSessionId);
+ this.invalidateWorkerSnapshot(worker, activeSessionId);
+ const clients = [...this.clients].filter((client) => client.attachedActiveSessionIds.has(activeSessionId));
+ for (const client of clients) {
+ this.queueCatchup(client, activeSessionId);
+ }
+ void Promise.all(clients.map((client) => this.catchUpClient(client))).finally(() => {
+ this.compactCatchupInProgress.delete(activeSessionId);
+ });
+ }
+
+ private queueCatchup(
+ client: DaemonSocketClient,
+ activeSessionId: string,
+ purpose: "replacement" | "resync" = "resync",
+ ): void {
+ if (!client.catchupActiveSessionIds) {
+ client.catchupActiveSessionIds = new Set();
+ }
+ client.catchupActiveSessionIds.add(activeSessionId);
+ client.catchupPurposes ??= new Map();
+ if (purpose === "replacement" || !client.catchupPurposes.has(activeSessionId)) {
+ client.catchupPurposes.set(activeSessionId, purpose);
+ }
+ }
+
+ private async catchUpClient(client: DaemonSocketClient): Promise<void> {
+ if (client.socket.destroyed) {
+ return;
+ }
+ client.backpressured = false;
+ const pending = [...(client.catchupActiveSessionIds ?? [])].map((activeSessionId) => ({
+ activeSessionId,
+ purpose: client.catchupPurposes?.get(activeSessionId) ?? ("resync" as const),
+ }));
+ client.catchupActiveSessionIds?.clear();
+ client.catchupPurposes?.clear();
+ for (let index = 0; index < pending.length; index++) {
+ const { activeSessionId, purpose } = pending[index]!;
+ try {
+ const attached = await this.attachClient(client, {
+ type: "attach",
+ activeSessionId,
+ capabilities: [...client.capabilities],
+ supportsExtensionUi: client.supportsExtensionUi,
+ });
+ if (client.capabilities.has("chunked_snapshot")) {
+ const transcript = this.getOrCreateTranscriptCache(attached.worker, attached.result);
+ if (purpose === "replacement") {
+ this.write(client, {
+ type: "session_replaced",
+ activeSessionId,
+ state: attached.result.snapshot.state,
+ messages: [],
+ snapshotFollows: true,
+ meta: createDaemonEventMeta(
+ activeSessionId,
+ attached.result.lastEventSequence,
+ undefined,
+ attached.result.lastEventCursor?.generation,
+ ),
+ });
+ }
+ await this.streamSnapshot(
+ client,
+ this.createStreamedAttachResult(attached.result, transcript),
+ transcript,
+ purpose,
+ );
+ continue;
+ }
+ const meta = createDaemonEventMeta(
+ activeSessionId,
+ attached.result.lastEventSequence,
+ undefined,
+ attached.result.lastEventCursor?.generation,
+ );
+ const catchup: DaemonOutbound =
+ purpose === "replacement"
+ ? {
+ type: "session_replaced",
+ activeSessionId,
+ state: attached.result.snapshot.state,
+ messages: attached.result.snapshot.messages,
+ meta,
+ }
+ : {
+ type: "session_resynced",
+ activeSessionId,
+ snapshot: attached.result.snapshot,
+ meta,
+ };
+ if (!this.write(client, catchup)) {
+ for (const remaining of pending.slice(index + 1)) {
+ this.queueCatchup(client, remaining.activeSessionId, remaining.purpose);
+ }
+ return;
+ }
+ } catch (error) {
+ this.log(`Failed to catch up client ${client.id} for ${activeSessionId}: ${String(error)}`);
+ }
+ }
+ }
+
+ private async prepareUpdateRestart(): Promise<DaemonUpdateRestartManifest> {
+ const workers = [...this.workers.values()].filter(
+ (worker): worker is ResidentWorker & { client: DaemonWorkerClient } => worker.client !== undefined,
+ );
+ const prepared: Array<ResidentWorker & { client: DaemonWorkerClient }> = [];
+ const preparationResults = await Promise.allSettled(
+ workers.map(async (worker) => {
+ const response = await worker.client.requestWorker(
+ { type: "worker_prepare_update" },
+ WORKER_REQUEST_TIMEOUT_MS,
+ );
+ if (!response.success || !response.data || typeof response.data !== "object") {
+ throw new Error(response.success ? "Worker returned an invalid update manifest" : response.error);
+ }
+ return { worker, manifest: response.data as DaemonUpdateRestartManifest };
+ }),
+ );
+ for (const result of preparationResults) {
+ if (result.status === "fulfilled") {
+ prepared.push(result.value.worker);
+ }
+ }
+ const preparationFailure = preparationResults.find(
+ (result): result is PromiseRejectedResult => result.status === "rejected",
+ );
+ if (preparationFailure) {
+ await Promise.all(
+ prepared.map((worker) =>
+ worker.client.requestWorker({ type: "worker_cancel_update" }, 5000).catch(() => undefined),
+ ),
+ );
+ throw preparationFailure.reason;
+ }
+ const responses = preparationResults.flatMap((result) =>
+ result.status === "fulfilled" ? [result.value.manifest] : [],
+ );
+ const manifest = {
+ createdAt: new Date().toISOString(),
+ sessions: responses.flatMap((manifest) => manifest.sessions),
+ };
+ try {
+ this.validateAndPersistUpdateManifest(manifest);
+ } catch (error) {
+ await Promise.all(
+ prepared.map((worker) =>
+ worker.client.requestWorker({ type: "worker_cancel_update" }, 5000).catch(() => undefined),
+ ),
+ );
+ throw error;
+ }
+ await Promise.all(
+ prepared.map(async (worker) => {
+ const response = await worker.client.requestWorker(
+ { type: "worker_commit_update" },
+ WORKER_REQUEST_TIMEOUT_MS,
+ );
+ if (!response.success) {
+ throw new Error(response.error);
+ }
+ }),
+ );
+ await Promise.all(prepared.map((worker) => this.stopWorker(worker, false)));
+ return manifest;
+ }
+
+ private validateAndPersistUpdateManifest(manifest: DaemonUpdateRestartManifest): void {
+ const activeSessionIds = new Set<string>();
+ const sessionFiles = new Set<string>();
+ for (const session of manifest.sessions) {
+ if (!session.activeSessionId || !session.sessionFile) {
+ throw new Error("Update manifest contains an incomplete session checkpoint");
+ }
+ if (activeSessionIds.has(session.activeSessionId)) {
+ throw new Error(`Update manifest contains duplicate active session ${session.activeSessionId}`);
+ }
+ const sessionFile = resolve(session.sessionFile);
+ if (sessionFiles.has(sessionFile)) {
+ throw new Error(`Update manifest contains duplicate session file ${sessionFile}`);
+ }
+ activeSessionIds.add(session.activeSessionId);
+ sessionFiles.add(sessionFile);
+ }
+ const agentDir = this.defaultSessionConfig.agentDir;
+ if (!agentDir) {
+ throw new Error("Daemon supervisor config is missing agentDir");
+ }
+ const path = getDaemonUpdateRestartManifestPath(agentDir);
+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
+ const tempPath = `${path}.${process.pid}.tmp`;
+ writeFileSync(tempPath, `${JSON.stringify(manifest)}\n`, { mode: 0o600 });
+ chmodSync(tempPath, 0o600);
+ const validated = JSON.parse(readFileSync(tempPath, "utf8")) as DaemonUpdateRestartManifest;
+ if (!Array.isArray(validated.sessions) || validated.sessions.length !== manifest.sessions.length) {
+ throw new Error("Could not validate aggregate update manifest");
+ }
+ renameSync(tempPath, path);
+ }
+
+ private async stopWorker(
+ worker: ResidentWorker,
+ removeDescriptor: boolean,
+ force = false,
+ archiveSession = false,
+ recoveryCleanup = false,
+ ): Promise<void> {
+ if (!recoveryCleanup) {
+ worker.stopRevision++;
+ }
+ if (removeDescriptor) {
+ this.persistWorkerStopTombstone(worker, archiveSession);
+ } else {
+ worker.intentionalStop = true;
+ worker.descriptor.lifecycle = "recovering";
+ this.persistWorker(worker);
+ }
+ for (const transcript of worker.transcriptCaches.values()) {
+ transcript.dispose();
+ }
+ worker.transcriptCaches.clear();
+ worker.snapshotCache.clear();
+ if (worker.client) {
+ if (archiveSession) {
+ await worker.client
+ .requestWorker({ type: "worker_archive_and_shutdown" }, force ? 1000 : 5000)
+ .catch(() => undefined);
+ } else {
+ await worker.client.request({ type: "shutdown" }, force ? 1000 : 5000).catch(() => undefined);
+ }
+ worker.client.close();
+ worker.client = undefined;
+ } else if (isProcessAlive(worker.descriptor.pid)) {
+ signalProcessGroupOrProcess(worker.descriptor.pid, "SIGTERM");
+ }
+ const gracefulDeadline = Date.now() + (force ? 500 : 2000);
+ while (isProcessAlive(worker.descriptor.pid) && Date.now() < gracefulDeadline) {
+ await delay(25);
+ }
+ if (force && isProcessAlive(worker.descriptor.pid)) {
+ signalProcessGroupOrProcess(worker.descriptor.pid, "SIGKILL");
+ const forceDeadline = Date.now() + 1000;
+ while (isProcessAlive(worker.descriptor.pid) && Date.now() < forceDeadline) {
+ await delay(25);
+ }
+ }
+ if (isProcessAlive(worker.descriptor.pid)) {
+ worker.intentionalStop = worker.descriptor.stopRequestedAt !== undefined;
+ throw new Error(`Session worker ${worker.descriptor.workerId} did not stop${force ? " after SIGKILL" : ""}`);
+ }
+ if (removeDescriptor && worker.descriptor.archiveOnStop) {
+ if (force) {
+ this.reclaimStoppedWorkerCronLock(worker);
+ }
+ await this.finalizeArchivedWorkerStop(worker);
+ }
+ this.workers.delete(worker.descriptor.workerId);
+ if (removeDescriptor) {
+ this.deleteWorkerDescriptor(worker);
+ }
+ if (!this.shuttingDown) {
+ void this.syncAgentPeers().catch(() => undefined);
+ }
+ }
+
+ private async finalizeArchivedWorkerStop(worker: ResidentWorker): Promise<void> {
+ const context = this.workerSessionArtifactContext(worker);
+ if (!context) {
+ return;
+ }
+ if (worker.descriptor.rootSessionId) {
+ const cronStore = AgentCronJobStore.forSessionArtifacts();
+ cronStore.registerSessionArtifact(worker.descriptor.rootSessionId, context.artifactDir);
+ cronStore.cancelJobsForSession({
+ sessionId: worker.descriptor.rootSessionId,
+ sessionFile: context.sessionFile,
+ });
+ await this.catalog.archive(context.sessionFile, worker.descriptor.rootSessionId);
+ }
+ }
+
+ private reclaimStoppedWorkerCronLock(worker: ResidentWorker): void {
+ const context = this.workerSessionArtifactContext(worker);
+ if (!context) {
+ return;
+ }
+ rmSync(join(context.artifactDir, `${SESSION_SCHEDULED_JOBS_FILENAME}.lock`), { recursive: true, force: true });
+ }
+
+ private workerSessionArtifactContext(
+ worker: ResidentWorker,
+ ): { sessionFile: string; artifactDir: string } | undefined {
+ const sessionFile = worker.descriptor.sessionFile ?? worker.descriptor.createCommand.sessionPath;
+ if (!sessionFile || !worker.descriptor.rootSessionId) {
+ return undefined;
+ }
+ return {
+ sessionFile,
+ artifactDir: join(dirname(dirname(sessionFile)), "session-artifacts", worker.descriptor.rootSessionId),
+ };
+ }
+
+ private persistWorkerStopTombstone(worker: ResidentWorker, archiveSession = false): void {
+ worker.intentionalStop = true;
+ worker.descriptor.stopRequestedAt ??= new Date().toISOString();
+ worker.descriptor.archiveOnStop ||= archiveSession;
+ this.persistWorker(worker);
+ }
+
+ private write(client: DaemonSocketClient, message: DaemonOutbound): boolean {
+ return this.writeSerialized(client, serializeJsonLine(message));
+ }
+
+ private writeSerialized(client: DaemonSocketClient, line: string | Uint8Array): boolean {
+ if (client.socket.destroyed) {
+ return false;
+ }
+ const accepted = client.socket.write(line);
+ if (!accepted) {
+ client.backpressured = true;
+ }
+ return accepted;
+ }
+
+ private registerSignalHandlers(): void {
+ const signals: NodeJS.Signals[] = ["SIGINT", "SIGTERM"];
+ if (process.platform !== "win32") {
+ signals.push("SIGHUP");
+ }
+ for (const signal of signals) {
+ const handler = () => void this.shutdown(signal === "SIGINT" ? 130 : signal === "SIGHUP" ? 129 : 143, false);
+ process.on(signal, handler);
+ this.signalCleanupHandlers.push(() => process.off(signal, handler));
+ }
+ const exitHandler = () => this.cleanupSocket();
+ process.on("exit", exitHandler);
+ this.signalCleanupHandlers.push(() => process.off("exit", exitHandler));
+ }
+
+ private cleanupSocket(): void {
+ if (!this.ownsSocketPath) {
+ return;
+ }
+ this.ownsSocketPath = false;
+ cleanupDaemonSocketPath(this.socketPath);
+ }
+
+ private async shutdown(
+ exitCode: number,
+ stopWorkers: boolean,
+ relaunch = false,
+ forceWorkers = false,
+ ): Promise<never> {
+ if (this.shuttingDown) {
+ process.exit(exitCode);
+ }
+ this.shuttingDown = true;
+ for (const cleanup of this.signalCleanupHandlers) {
+ cleanup();
+ }
+ if (stopWorkers) {
+ await Promise.all(
+ [...this.workers.values()].map((worker) => this.stopWorker(worker, true, forceWorkers, true)),
+ );
+ if (!this.hasPersistedWorkerDescriptors()) {
+ rmSync(this.supervisorConfigPath, { force: true });
+ }
+ } else {
+ for (const worker of this.workers.values()) {
+ worker.intentionalStop = true;
+ worker.client?.close();
+ worker.client = undefined;
+ }
+ }
+ await this.catalog.stop();
+ for (const client of this.clients) {
+ client.detachInput();
+ client.socket.end();
+ }
+ await new Promise<void>((resolveClose) => this.server?.close(() => resolveClose()) ?? resolveClose());
+ this.cleanupSocket();
+ if (relaunch) {
+ const launch = createCliSubprocessLaunchSpec(["--mode", "daemon", "--daemon-socket", this.socketPath]);
+ const environment = { ...process.env };
+ delete environment[DAEMON_CATALOG_ROLE_ENV];
+ delete environment[DAEMON_WORKER_ROLE_ENV];
+ delete environment[DAEMON_WORKER_TOKEN_ENV];
+ delete environment[DAEMON_WORKER_ACTIVE_SESSION_ID_ENV];
+ delete environment[DAEMON_WORKER_SUPERVISOR_SOCKET_ENV];
+ delete environment[DAEMON_WORKER_RECOVERY_JOURNAL_ENV];
+ delete environment[ORPHAN_PROCESS_JOURNAL_ENV];
+ delete environment[SESSION_LEASES_ENABLED_ENV];
+ delete environment[SESSION_LEASE_OWNER_ID_ENV];
+ const replacement = spawn(launch.command, launch.args, {
+ cwd: this.defaultSessionConfig.cwd ?? process.cwd(),
+ detached: true,
+ env: environment,
+ stdio: "ignore",
+ });
+ replacement.unref();
+ }
+ process.exit(exitCode);
+ }
+}
diff --git a/packages/coding-agent/src/modes/daemon/daemon-worker-client.ts b/packages/coding-agent/src/modes/daemon/daemon-worker-client.ts
new file mode 100644
index 0000000000..6a54cd3f24
--- /dev/null
+++ b/packages/coding-agent/src/modes/daemon/daemon-worker-client.ts
@@ -0,0 +1,240 @@
+import { createConnection, type Socket } from "node:net";
+import { serializeJsonLine } from "../rpc/jsonl.js";
+import { type PrivateFrame, PrivateFramedChannel } from "../session-worker/private-framing.js";
+import type { DaemonCommand, DaemonOutbound, DaemonResponse } from "./daemon-protocol.js";
+import {
+ type DaemonWorkerCommand,
+ type DaemonWorkerCommandBody,
+ type DaemonWorkerFrameHeader,
+ isDaemonWorkerFrameHeader,
+} from "./daemon-worker-protocol.js";
+
+type DistributiveOmit<T, K extends keyof T> = T extends unknown ? Omit<T, K> : never;
+type DaemonCommandBody = DistributiveOmit<DaemonCommand, "id">;
+type DaemonWorkerWireCommandBody = DaemonCommandBody | DaemonWorkerCommandBody;
+type DaemonWorkerWireCommand = DaemonCommand | DaemonWorkerCommand;
+
+export type DaemonWorkerFrameListener = (frame: PrivateFrame<DaemonWorkerFrameHeader>) => void;
+export type DaemonWorkerCloseListener = (error: Error) => void;
+type DaemonHello = Extract<DaemonOutbound, { type: "daemon_hello" }>;
+
+export class DaemonWorkerClient {
+ private socket?: Socket;
+ private channel?: PrivateFramedChannel<DaemonWorkerFrameHeader>;
+ private readonly frameListeners = new Set<DaemonWorkerFrameListener>();
+ private readonly closeListeners = new Set<DaemonWorkerCloseListener>();
+ private readonly pending = new Map<
+ string,
+ {
+ resolve: (response: DaemonResponse) => void;
+ reject: (error: Error) => void;
+ timeout: ReturnType<typeof setTimeout>;
+ }
+ >();
+ private requestId = 0;
+ private hello?: DaemonHello;
+ private readonly helloWaiters = new Set<{
+ resolve: (hello: DaemonHello) => void;
+ reject: (error: Error) => void;
+ timeout: ReturnType<typeof setTimeout>;
+ }>();
+
+ constructor(private readonly socketPath: string) {}
+
+ async connect(timeoutMs = 3000): Promise<void> {
+ if (this.socket) {
+ throw new Error("Daemon worker client is already connected");
+ }
+ const socket = createConnection(this.socketPath);
+ this.socket = socket;
+ this.channel = new PrivateFramedChannel(socket, isDaemonWorkerFrameHeader);
+ this.channel.onFrame((frame) => this.handleFrame(frame));
+
+ await new Promise<void>((resolve, reject) => {
+ const timeout = setTimeout(() => {
+ cleanup();
+ socket.destroy();
+ reject(new Error(`Timed out connecting to daemon worker socket: ${this.socketPath}`));
+ }, timeoutMs);
+ const cleanup = () => {
+ clearTimeout(timeout);
+ socket.off("connect", onConnect);
+ socket.off("error", onError);
+ };
+ const onConnect = () => {
+ cleanup();
+ resolve();
+ };
+ const onError = (error: Error) => {
+ cleanup();
+ reject(error);
+ };
+ socket.once("connect", onConnect);
+ socket.once("error", onError);
+ });
+
+ socket.on("error", (error) => this.notifyClosed(socket, error));
+ socket.on("close", () => this.notifyClosed(socket, new Error("Daemon worker socket closed")));
+ }
+
+ waitForHello(timeoutMs = 3000): Promise<DaemonHello> {
+ if (this.hello) {
+ return Promise.resolve(this.hello);
+ }
+ if (!this.socket || this.socket.destroyed) {
+ return Promise.reject(new Error("Daemon worker client is not connected"));
+ }
+ return new Promise((resolve, reject) => {
+ const waiter = {
+ resolve,
+ reject,
+ timeout: setTimeout(() => {
+ this.helloWaiters.delete(waiter);
+ reject(new Error("Timed out waiting for daemon worker hello"));
+ }, timeoutMs),
+ };
+ this.helloWaiters.add(waiter);
+ });
+ }
+
+ onFrame(listener: DaemonWorkerFrameListener): () => void {
+ this.frameListeners.add(listener);
+ return () => this.frameListeners.delete(listener);
+ }
+
+ onClose(listener: DaemonWorkerCloseListener): () => void {
+ this.closeListeners.add(listener);
+ return () => this.closeListeners.delete(listener);
+ }
+
+ request(command: DaemonCommandBody, timeoutMs = 30_000): Promise<DaemonResponse> {
+ return this.requestWire(command, timeoutMs);
+ }
+
+ requestWorker(command: DaemonWorkerCommandBody, timeoutMs = 30_000): Promise<DaemonResponse> {
+ return this.requestWire(command, timeoutMs);
+ }
+
+ async authenticateWorker(token: string, timeoutMs = 3000): Promise<void> {
+ const response = await this.requestWorker({ type: "worker_auth", token }, timeoutMs);
+ if (!response.success) {
+ throw new Error(response.error);
+ }
+ }
+
+ close(): void {
+ this.rejectAll(new Error("Daemon worker client closed"));
+ this.channel?.close();
+ this.channel = undefined;
+ this.socket?.destroy();
+ this.socket = undefined;
+ }
+
+ private async requestWire(command: DaemonWorkerWireCommandBody, timeoutMs: number): Promise<DaemonResponse> {
+ if (!this.channel || !this.socket || this.socket.destroyed) {
+ throw new Error("Daemon worker client is not connected");
+ }
+ const id = `worker_${++this.requestId}`;
+ const fullCommand = { ...command, id } as DaemonWorkerWireCommand;
+ const response = new Promise<DaemonResponse>((resolve, reject) => {
+ const timeout = setTimeout(() => {
+ this.pending.delete(id);
+ reject(new Error(`Timed out waiting for daemon worker response to ${command.type}`));
+ }, timeoutMs);
+ this.pending.set(id, { resolve, reject, timeout });
+ });
+ try {
+ await this.channel.send(
+ { kind: "command", requestId: id, commandType: command.type },
+ Buffer.from(serializeJsonLine(fullCommand)),
+ );
+ } catch (error) {
+ const pending = this.pending.get(id);
+ if (pending) {
+ clearTimeout(pending.timeout);
+ this.pending.delete(id);
+ pending.reject(error instanceof Error ? error : new Error(String(error)));
+ }
+ }
+ return response;
+ }
+
+ private handleFrame(frame: PrivateFrame<DaemonWorkerFrameHeader>): void {
+ if (frame.header.kind !== "outbound") {
+ return;
+ }
+ if (frame.header.outboundType === "response" && frame.header.requestId) {
+ const pending = this.pending.get(frame.header.requestId);
+ if (pending) {
+ let response: unknown;
+ try {
+ response = JSON.parse(frame.payload.toString("utf8"));
+ } catch (error) {
+ clearTimeout(pending.timeout);
+ this.pending.delete(frame.header.requestId);
+ pending.reject(new Error(`Invalid daemon worker response: ${String(error)}`));
+ return;
+ }
+ if (isDaemonResponse(response)) {
+ clearTimeout(pending.timeout);
+ this.pending.delete(frame.header.requestId);
+ pending.resolve(response);
+ return;
+ }
+ }
+ }
+ if (frame.header.outboundType === "daemon_hello") {
+ try {
+ const parsed = JSON.parse(frame.payload.toString("utf8")) as DaemonOutbound;
+ if (parsed.type === "daemon_hello") {
+ this.hello = parsed;
+ for (const waiter of [...this.helloWaiters]) {
+ clearTimeout(waiter.timeout);
+ this.helloWaiters.delete(waiter);
+ waiter.resolve(parsed);
+ }
+ }
+ } catch {
+ // The malformed frame eventually fails the hello timeout.
+ }
+ }
+ for (const listener of this.frameListeners) {
+ listener(frame);
+ }
+ }
+
+ private rejectAll(error: Error): void {
+ for (const [id, pending] of this.pending) {
+ clearTimeout(pending.timeout);
+ pending.reject(error);
+ this.pending.delete(id);
+ }
+ for (const waiter of [...this.helloWaiters]) {
+ clearTimeout(waiter.timeout);
+ this.helloWaiters.delete(waiter);
+ waiter.reject(error);
+ }
+ }
+
+ private notifyClosed(socket: Socket, error: Error): void {
+ if (this.socket !== socket) {
+ return;
+ }
+ this.socket = undefined;
+ this.channel = undefined;
+ this.rejectAll(error);
+ for (const listener of [...this.closeListeners]) {
+ listener(error);
+ }
+ }
+}
+
+function isDaemonResponse(value: unknown): value is DaemonResponse {
+ if (!value || typeof value !== "object") {
+ return false;
+ }
+ const candidate = value as { type?: unknown; command?: unknown; success?: unknown };
+ return (
+ candidate.type === "response" && typeof candidate.command === "string" && typeof candidate.success === "boolean"
+ );
+}
diff --git a/packages/coding-agent/src/modes/daemon/daemon-worker-protocol.ts b/packages/coding-agent/src/modes/daemon/daemon-worker-protocol.ts
new file mode 100644
index 0000000000..0e8e0549ae
--- /dev/null
+++ b/packages/coding-agent/src/modes/daemon/daemon-worker-protocol.ts
@@ -0,0 +1,126 @@
+import type {
+ AgentSessionMessageAgentSummary,
+ AgentSessionMessageDeliveryMode,
+ AgentSessionMessageSender,
+} from "../../core/agent-messages.js";
+
+export { SESSION_LEASE_OWNER_ID_ENV, SESSION_LEASES_ENABLED_ENV } from "../../core/session-lease.js";
+
+import type { DaemonClientCapability, DaemonCommand, DaemonOutbound } from "./daemon-protocol.js";
+
+export const DAEMON_WORKER_ROLE_ENV = "PRIME_AGENT_INTERNAL_DAEMON_WORKER";
+export const DAEMON_WORKER_TOKEN_ENV = "PRIME_AGENT_INTERNAL_DAEMON_WORKER_TOKEN";
+export const DAEMON_WORKER_ACTIVE_SESSION_ID_ENV = "PRIME_AGENT_INTERNAL_DAEMON_WORKER_ACTIVE_SESSION_ID";
+export const DAEMON_WORKER_SUPERVISOR_SOCKET_ENV = "PRIME_AGENT_INTERNAL_DAEMON_SUPERVISOR_SOCKET";
+export const DAEMON_WORKER_RECOVERY_JOURNAL_ENV = "PRIME_AGENT_INTERNAL_DAEMON_WORKER_RECOVERY_JOURNAL";
+export type DaemonWorkerLifecycle = "starting" | "ready" | "recovering" | "failed";
+
+export type DaemonWorkerFrameHeader =
+ | {
+ kind: "command";
+ requestId: string;
+ commandType: string;
+ }
+ | {
+ kind: "outbound";
+ requestId?: string;
+ outboundType: DaemonOutbound["type"];
+ activeSessionId?: string;
+ sessionEventType?: string;
+ payloadEncoding?: "jsonl" | "assistant-delta";
+ snapshotPurpose?: "attach" | "replacement" | "catchup";
+ };
+
+export type DaemonCreateCommand = Extract<DaemonCommand, { type: "create" }>;
+
+export type DaemonWorkerCommand =
+ | { id?: string; type: "worker_auth"; token: string }
+ | {
+ id?: string;
+ type: "worker_subscribe";
+ activeSessionId: string;
+ capabilities?: readonly DaemonClientCapability[];
+ supportsExtensionUi?: boolean;
+ }
+ | { id?: string; type: "worker_unsubscribe"; activeSessionId: string }
+ | { id?: string; type: "worker_sync_agent_peers"; peers: AgentSessionMessageAgentSummary[] }
+ | { id?: string; type: "worker_archive_and_shutdown" }
+ | {
+ id?: string;
+ type: "worker_deliver_message";
+ targetActiveSessionId: string;
+ message: string;
+ sender: AgentSessionMessageSender;
+ deliveryMode?: AgentSessionMessageDeliveryMode;
+ }
+ | { id?: string; type: "worker_prepare_update" }
+ | { id?: string; type: "worker_commit_update" }
+ | { id?: string; type: "worker_cancel_update" };
+
+export type DaemonWorkerCommandBody = DaemonWorkerCommand extends infer TCommand
+ ? TCommand extends { id?: string }
+ ? Omit<TCommand, "id">
+ : never
+ : never;
+
+export interface DaemonWorkerDescriptor {
+ version: 1;
+ workerId: string;
+ pid: number;
+ processStartId?: string;
+ socketPath: string;
+ recoveryJournalPath: string;
+ orphanProcessJournalPath?: string;
+ supervisorSocketPath: string;
+ authenticationToken: string;
+ rootActiveSessionId: string;
+ rootSessionId?: string;
+ sessionFile?: string;
+ createdAt: string;
+ updatedAt: string;
+ lifecycle: DaemonWorkerLifecycle;
+ createCommand: DaemonCreateCommand;
+ consecutiveFailures: number;
+ /** Durable intent written before root termination so replacement supervisors never recover it. */
+ stopRequestedAt?: string;
+ /** Complete the root's archived lifecycle state after its process has stopped. */
+ archiveOnStop?: boolean;
+ lastFailureAt?: string;
+ lastError?: string;
+}
+
+export function isDaemonWorkerProcess(environment: NodeJS.ProcessEnv = process.env): boolean {
+ return environment[DAEMON_WORKER_ROLE_ENV] === "1";
+}
+
+export function requireDaemonWorkerAuthenticationToken(environment: NodeJS.ProcessEnv = process.env): string {
+ const token = environment[DAEMON_WORKER_TOKEN_ENV];
+ if (!token) {
+ throw new Error("Daemon session worker is missing its authentication token");
+ }
+ return token;
+}
+
+export function isDaemonWorkerFrameHeader(value: unknown): value is DaemonWorkerFrameHeader {
+ if (!value || typeof value !== "object") {
+ return false;
+ }
+ const candidate = value as Record<string, unknown>;
+ if (candidate.kind === "command") {
+ return typeof candidate.requestId === "string" && typeof candidate.commandType === "string";
+ }
+ return (
+ candidate.kind === "outbound" &&
+ typeof candidate.outboundType === "string" &&
+ (candidate.requestId === undefined || typeof candidate.requestId === "string") &&
+ (candidate.activeSessionId === undefined || typeof candidate.activeSessionId === "string") &&
+ (candidate.sessionEventType === undefined || typeof candidate.sessionEventType === "string") &&
+ (candidate.snapshotPurpose === undefined ||
+ candidate.snapshotPurpose === "attach" ||
+ candidate.snapshotPurpose === "replacement" ||
+ candidate.snapshotPurpose === "catchup") &&
+ (candidate.payloadEncoding === undefined ||
+ candidate.payloadEncoding === "jsonl" ||
+ candidate.payloadEncoding === "assistant-delta")
+ );
+}
diff --git a/packages/coding-agent/src/modes/daemon/snapshot-transcript-cache.ts b/packages/coding-agent/src/modes/daemon/snapshot-transcript-cache.ts
new file mode 100644
index 0000000000..e51c9c649b
--- /dev/null
+++ b/packages/coding-agent/src/modes/daemon/snapshot-transcript-cache.ts
@@ -0,0 +1,219 @@
+import { mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { join } from "node:path";
+import type { AgentMessage } from "@earendil-works/pi-agent-core";
+
+export const SNAPSHOT_TARGET_CHUNK_BYTES = 512 * 1024;
+export const SNAPSHOT_MEMORY_CACHE_BYTES = 4 * 1024 * 1024;
+
+interface SnapshotTranscriptChunk {
+ buffer?: Buffer;
+ path?: string;
+}
+
+export interface SnapshotTranscriptCacheOptions {
+ activeSessionId: string;
+ snapshotId: string;
+ messages?: readonly AgentMessage[];
+ cacheRoot: string;
+ targetChunkBytes?: number;
+ memoryCacheBytes?: number;
+}
+
+export class SnapshotTranscriptCache {
+ private readonly chunks: SnapshotTranscriptChunk[] = [];
+ private cacheDirectory?: string;
+ private totalBytes = 0;
+ private completed = false;
+ private readers = 0;
+ private disposeRequested = false;
+ private disposed = false;
+ private failure?: Error;
+ private readonly chunkWaiters = new Map<
+ number,
+ Array<{ resolve: (buffer: Buffer | undefined) => void; reject: (error: Error) => void }>
+ >();
+ readonly targetChunkBytes: number;
+ readonly snapshotId: string;
+ readonly activeSessionId: string;
+
+ constructor(private readonly options: SnapshotTranscriptCacheOptions) {
+ this.targetChunkBytes = options.targetChunkBytes ?? SNAPSHOT_TARGET_CHUNK_BYTES;
+ this.snapshotId = options.snapshotId;
+ this.activeSessionId = options.activeSessionId;
+ if (options.messages) {
+ this.encodeMessages(options.messages);
+ this.completed = true;
+ }
+ }
+
+ get chunkCount(): number {
+ return this.chunks.length;
+ }
+
+ get bytes(): number {
+ return this.totalBytes;
+ }
+
+ get fileBacked(): boolean {
+ return this.cacheDirectory !== undefined;
+ }
+
+ readChunk(index: number): Buffer {
+ const chunk = this.chunks[index];
+ if (!chunk) {
+ throw new Error(`Unknown snapshot transcript chunk: ${index}`);
+ }
+ if (chunk.buffer) {
+ return chunk.buffer;
+ }
+ if (!chunk.path) {
+ throw new Error(`Snapshot transcript chunk ${index} has no backing storage`);
+ }
+ return readFileSync(chunk.path);
+ }
+
+ appendEncodedChunk(buffer: Buffer): void {
+ if (this.completed) {
+ throw new Error(`Snapshot transcript ${this.snapshotId} is already complete`);
+ }
+ this.storeChunk(buffer);
+ }
+
+ markComplete(): void {
+ this.completed = true;
+ for (const [index, waiters] of this.chunkWaiters) {
+ if (index < this.chunks.length) {
+ continue;
+ }
+ for (const waiter of waiters) {
+ waiter.resolve(undefined);
+ }
+ this.chunkWaiters.delete(index);
+ }
+ }
+
+ markFailed(error: Error): void {
+ this.failure = error;
+ for (const waiters of this.chunkWaiters.values()) {
+ for (const waiter of waiters) {
+ waiter.reject(error);
+ }
+ }
+ this.chunkWaiters.clear();
+ }
+
+ waitForChunk(index: number): Promise<Buffer | undefined> {
+ if (index < this.chunks.length) {
+ return Promise.resolve(this.readChunk(index));
+ }
+ if (this.failure) {
+ return Promise.reject(this.failure);
+ }
+ if (this.completed) {
+ return Promise.resolve(undefined);
+ }
+ return new Promise((resolve, reject) => {
+ const waiters = this.chunkWaiters.get(index) ?? [];
+ waiters.push({ resolve, reject });
+ this.chunkWaiters.set(index, waiters);
+ });
+ }
+
+ retain(): () => void {
+ if (this.disposed) {
+ throw new Error(`Snapshot transcript ${this.snapshotId} was disposed`);
+ }
+ this.readers++;
+ let released = false;
+ return () => {
+ if (released) return;
+ released = true;
+ this.readers--;
+ if (this.readers === 0 && this.disposeRequested) {
+ this.disposeNow();
+ }
+ };
+ }
+
+ dispose(): void {
+ if (this.disposed || this.disposeRequested) return;
+ this.disposeRequested = true;
+ if (this.readers > 0) return;
+ this.disposeNow();
+ }
+
+ private disposeNow(): void {
+ if (this.disposed) return;
+ this.disposed = true;
+ this.markFailed(new Error(`Snapshot transcript ${this.snapshotId} was disposed`));
+ if (this.cacheDirectory) {
+ rmSync(this.cacheDirectory, { recursive: true, force: true });
+ this.cacheDirectory = undefined;
+ }
+ this.chunks.length = 0;
+ }
+
+ private encodeMessages(messages: readonly AgentMessage[]): void {
+ let serializedMessages: string[] = [];
+ let serializedBytes = 0;
+ const flush = () => {
+ if (serializedMessages.length === 0) {
+ return;
+ }
+ const index = this.chunks.length;
+ const prefix =
+ `{"type":"session_snapshot_chunk","activeSessionId":${JSON.stringify(this.options.activeSessionId)},` +
+ `"snapshotId":${JSON.stringify(this.options.snapshotId)},"index":${index},"messages":[`;
+ const line = Buffer.from(`${prefix}${serializedMessages.join(",")}]}\n`);
+ this.storeChunk(line);
+ serializedMessages = [];
+ serializedBytes = 0;
+ };
+
+ for (const message of messages) {
+ const serialized = JSON.stringify(message);
+ const bytes = Buffer.byteLength(serialized) + (serializedMessages.length > 0 ? 1 : 0);
+ if (serializedMessages.length > 0 && serializedBytes + bytes > this.targetChunkBytes) {
+ flush();
+ }
+ serializedMessages.push(serialized);
+ serializedBytes += bytes;
+ }
+ flush();
+ }
+
+ private storeChunk(buffer: Buffer): void {
+ this.totalBytes += buffer.length;
+ const memoryLimit = this.options.memoryCacheBytes ?? SNAPSHOT_MEMORY_CACHE_BYTES;
+ if (!this.cacheDirectory && this.totalBytes > memoryLimit) {
+ this.cacheDirectory = join(this.options.cacheRoot, this.options.snapshotId.replaceAll(/[^a-zA-Z0-9_-]/g, "_"));
+ mkdirSync(this.cacheDirectory, { recursive: true, mode: 0o700 });
+ for (let index = 0; index < this.chunks.length; index++) {
+ const existing = this.chunks[index]!;
+ if (!existing.buffer) {
+ continue;
+ }
+ const path = join(this.cacheDirectory, `${index}.jsonl`);
+ writeFileSync(path, existing.buffer, { mode: 0o600 });
+ this.chunks[index] = { path };
+ }
+ }
+
+ if (this.cacheDirectory) {
+ const path = join(this.cacheDirectory, `${this.chunks.length}.jsonl`);
+ writeFileSync(path, buffer, { mode: 0o600 });
+ this.chunks.push({ path });
+ } else {
+ this.chunks.push({ buffer });
+ }
+ const index = this.chunks.length - 1;
+ const waiters = this.chunkWaiters.get(index);
+ if (waiters) {
+ const stored = this.readChunk(index);
+ for (const waiter of waiters) {
+ waiter.resolve(stored);
+ }
+ this.chunkWaiters.delete(index);
+ }
+ }
+}
diff --git a/packages/coding-agent/src/modes/daemon/worker-recovery-journal.ts b/packages/coding-agent/src/modes/daemon/worker-recovery-journal.ts
new file mode 100644
index 0000000000..a159968074
--- /dev/null
+++ b/packages/coding-agent/src/modes/daemon/worker-recovery-journal.ts
@@ -0,0 +1,114 @@
+import {
+ chmodSync,
+ closeSync,
+ fsyncSync,
+ mkdirSync,
+ openSync,
+ readFileSync,
+ renameSync,
+ writeFileSync,
+ writeSync,
+} from "node:fs";
+import { dirname } from "node:path";
+
+export interface WorkerRecoveryRecord {
+ version: 1;
+ activeSessionId: string;
+ sessionId: string;
+ sessionFile?: string;
+ busy: boolean;
+ operation: string;
+ recordedAt: string;
+}
+
+function parseRecords(path: string): Map<string, WorkerRecoveryRecord> {
+ const latest = new Map<string, WorkerRecoveryRecord>();
+ let contents: string;
+ try {
+ contents = readFileSync(path, "utf8");
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") {
+ return latest;
+ }
+ throw error;
+ }
+ for (const line of contents.split("\n")) {
+ if (!line) {
+ continue;
+ }
+ let record: WorkerRecoveryRecord;
+ try {
+ record = JSON.parse(line) as WorkerRecoveryRecord;
+ } catch {
+ continue;
+ }
+ if (
+ record.version === 1 &&
+ typeof record.activeSessionId === "string" &&
+ typeof record.sessionId === "string" &&
+ typeof record.busy === "boolean" &&
+ typeof record.operation === "string"
+ ) {
+ latest.set(record.activeSessionId, record);
+ }
+ }
+ return latest;
+}
+
+export class WorkerRecoveryJournal {
+ private readonly latest: Map<string, WorkerRecoveryRecord>;
+
+ constructor(private readonly path: string) {
+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
+ this.latest = parseRecords(path);
+ }
+
+ record(input: Omit<WorkerRecoveryRecord, "version" | "recordedAt">): void {
+ const previous = this.latest.get(input.activeSessionId);
+ if (
+ previous?.busy === input.busy &&
+ previous.operation === input.operation &&
+ previous.sessionFile === input.sessionFile
+ ) {
+ return;
+ }
+ const record: WorkerRecoveryRecord = {
+ version: 1,
+ ...input,
+ recordedAt: new Date().toISOString(),
+ };
+ this.append(record);
+ this.latest.set(record.activeSessionId, record);
+ if ([...this.latest.values()].every((entry) => !entry.busy)) {
+ this.compact();
+ }
+ }
+
+ getLatest(): WorkerRecoveryRecord[] {
+ return [...this.latest.values()];
+ }
+
+ static readLatest(path: string): WorkerRecoveryRecord[] {
+ return [...parseRecords(path).values()];
+ }
+
+ private append(record: WorkerRecoveryRecord): void {
+ const descriptor = openSync(this.path, "a", 0o600);
+ try {
+ writeSync(descriptor, `${JSON.stringify(record)}\n`);
+ fsyncSync(descriptor);
+ } finally {
+ closeSync(descriptor);
+ }
+ chmodSync(this.path, 0o600);
+ }
+
+ private compact(): void {
+ const tempPath = `${this.path}.${process.pid}.tmp`;
+ writeFileSync(tempPath, `${[...this.latest.values()].map((record) => JSON.stringify(record)).join("\n")}\n`, {
+ mode: 0o600,
+ });
+ chmodSync(tempPath, 0o600);
+ renameSync(tempPath, this.path);
+ }
+}
diff --git a/packages/coding-agent/src/modes/index.ts b/packages/coding-agent/src/modes/index.ts
index 1ca9ff4810..2c3d54b2fd 100644
--- a/packages/coding-agent/src/modes/index.ts
+++ b/packages/coding-agent/src/modes/index.ts
@@ -63,6 +63,7 @@ export {
export type { SessionActivity, SessionLifecycle, SessionSummary } from "./daemon/daemon-session-list.js";
export { resolveAttachModelFallbackMessage } from "./daemon/daemon-session-list.js";
export { defaultDaemonSocketPath } from "./daemon/daemon-socket.js";
+export { runDaemonSupervisorMode } from "./daemon/daemon-supervisor.js";
export {
InteractiveMode,
type InteractiveModeOptions,
diff --git a/packages/coding-agent/src/modes/interactive/components/child-agent-inspector.ts b/packages/coding-agent/src/modes/interactive/components/child-agent-inspector.ts
index c134fa1d0c..4e67583a54 100644
--- a/packages/coding-agent/src/modes/interactive/components/child-agent-inspector.ts
+++ b/packages/coding-agent/src/modes/interactive/components/child-agent-inspector.ts
@@ -8,7 +8,7 @@ import {
truncateToWidth,
visibleWidth,
} from "@earendil-works/pi-tui";
-import { AGENT_ACTIVITY_LABELS } from "../agent-activity.js";
+import { AGENT_ACTIVITY_LABELS, formatTokenCount } from "../agent-activity.js";
import { theme } from "../theme/theme.js";
import { getWorkingPulseFrame, workingIconFrame } from "../theme/working-icon.js";
import { keyText } from "./keybinding-hints.js";
@@ -43,7 +43,6 @@ export interface ChildAgentDetailOptions {
interface FlatChildAgentNode {
node: ChildAgentInspectorNode;
- depth: number;
}
interface DetailSections {
@@ -66,14 +65,14 @@ function childAgentSortRank(status: ChildAgentStatus): number {
function flattenChildAgentNodes(nodes: readonly ChildAgentInspectorNode[]): FlatChildAgentNode[] {
const result: FlatChildAgentNode[] = [];
- const walk = (items: readonly ChildAgentInspectorNode[], depth: number): void => {
+ const walk = (items: readonly ChildAgentInspectorNode[]): void => {
const ordered = [...items].sort((a, b) => childAgentSortRank(a.status) - childAgentSortRank(b.status));
for (const node of ordered) {
- result.push({ node, depth });
- walk(node.children ?? [], depth + 1);
+ result.push({ node });
+ walk(node.children ?? []);
}
};
- walk(nodes, 0);
+ walk(nodes);
return result;
}
@@ -180,21 +179,35 @@ function formatChildAgentDuration(durationMs: number | undefined): string {
return `${Math.floor(minutes / 60)}h`;
}
-function padTableCell(value: string, width: number): string {
- const truncated = truncateToWidth(value, width, "");
+function childAgentRecap(node: ChildAgentInspectorNode): string {
+ const recap = node.recap?.replace(/\s+/g, " ").trim();
+ return recap || nodeActivityLabel(node);
+}
+
+function padTableCell(value: string, width: number, ellipsis = ""): string {
+ // truncateToWidth emits full ANSI resets around its marker even for plain text.
+ // Strip those generated resets before applying foreground/background styling.
+ const truncated = truncateToWidth(value, width, ellipsis).replaceAll("\x1b[0m", "");
return truncated + " ".repeat(Math.max(0, width - visibleWidth(truncated)));
}
// Rows shown at once in the inline list below the prompt; extras scroll.
const SUMMARY_VISIBLE_ROWS = 5;
-const SUMMARY_LIST_INDENT = 1;
+const SUMMARY_LIST_INDENT = 0;
const SHARED_PREFIX_MIN = 12;
-// Gap between the "Subagent N" column and the prompt.
-const SUMMARY_LABEL_GAP = 4;
+const SUMMARY_COLUMN_GAP = 2;
+const SUMMARY_PROMPT_MAX_WIDTH = 24;
+const SUMMARY_RECAP_MIN_WIDTH = 12;
+const SUMMARY_TOOLS_WIDTH = 7;
+const SUMMARY_TOKENS_WIDTH = 8;
+const SUMMARY_DURATION_WIDTH = 4;
+const SUMMARY_TOKEN_TIME_GAP = 2;
+const SUMMARY_METRICS_WIDTH =
+ SUMMARY_TOOLS_WIDTH + 1 + SUMMARY_TOKENS_WIDTH + SUMMARY_TOKEN_TIME_GAP + SUMMARY_DURATION_WIDTH;
// Opening chars of the prompt kept for context before eliding a shared prefix.
-const PROMPT_LEADING_CONTEXT = 14;
+const PROMPT_LEADING_CONTEXT = 6;
// Words of context kept on each side of the divergence.
-const PROMPT_DIFF_CONTEXT_WORDS = 2;
+const PROMPT_DIFF_CONTEXT_WORDS = 1;
export class ChildAgentSummaryComponent implements Component, Focusable {
focused = false;
@@ -223,8 +236,10 @@ export class ChildAgentSummaryComponent implements Component, Focusable {
this.selectedId = undefined;
return;
}
- if (!this.selectedId || !flat.some((entry) => entry.node.id === this.selectedId)) {
- this.selectedId = flat.find((entry) => entry.node.status === "running")?.node.id ?? flat[0]?.node.id;
+ if (!this.focused || !this.selectedId || !flat.some((entry) => entry.node.id === this.selectedId)) {
+ this.selectedId =
+ flat.find((entry) => entry.node.status === "running" || entry.node.status === "queued")?.node.id ??
+ flat[0]?.node.id;
}
}
@@ -334,14 +349,19 @@ export class ChildAgentSummaryComponent implements Component, Focusable {
0,
flat.findIndex((entry) => entry.node.id === this.selectedId),
);
- const start = Math.max(
- 0,
- Math.min(selectedIndex - (SUMMARY_VISIBLE_ROWS - 1), flat.length - SUMMARY_VISIBLE_ROWS),
- );
+ const start = this.focused
+ ? Math.max(0, Math.min(selectedIndex - (SUMMARY_VISIBLE_ROWS - 1), flat.length - SUMMARY_VISIBLE_ROWS))
+ : 0;
const clampedStart = Math.max(0, start);
const window = flat.slice(clampedStart, clampedStart + SUMMARY_VISIBLE_ROWS);
- const labelWidth = `Subagent ${flat.length}`.length;
+ const agentWidth = `S${flat.length}`.length;
+ const fixedWidth = SUMMARY_LIST_INDENT + 2 + agentWidth + SUMMARY_COLUMN_GAP * 3 + SUMMARY_METRICS_WIDTH;
+ const flexibleWidth = Math.max(0, contentWidth - fixedWidth);
+ const recapMinimum = Math.min(SUMMARY_RECAP_MIN_WIDTH, Math.floor(flexibleWidth / 2));
+ const promptTarget = Math.min(SUMMARY_PROMPT_MAX_WIDTH, Math.max(10, Math.floor(flexibleWidth * 0.34)));
+ const promptWidth = Math.max(0, Math.min(promptTarget, flexibleWidth - recapMinimum));
+ const recapWidth = Math.max(0, flexibleWidth - promptWidth);
const promptPrefix = this.sharedPromptPrefix(window);
const promptSuffix = this.sharedPromptSuffix(window, promptPrefix);
@@ -351,7 +371,7 @@ export class ChildAgentSummaryComponent implements Component, Focusable {
const number = flat.indexOf(entry) + 1;
lines.push(
this.panelLine(
- this.renderListEntry(entry, number, labelWidth, promptPrefix, promptSuffix, contentWidth),
+ this.renderListEntry(entry, number, agentWidth, promptPrefix, promptSuffix, promptWidth, recapWidth),
width,
selected,
),
@@ -412,52 +432,47 @@ export class ChildAgentSummaryComponent implements Component, Focusable {
private renderListEntry(
entry: FlatChildAgentNode,
number: number,
- labelWidth: number,
+ agentWidth: number,
sharedPrefix: string,
sharedSuffix: string,
- width: number,
+ promptWidth: number,
+ recapWidth: number,
): string {
- const indent = " ".repeat(SUMMARY_LIST_INDENT + Math.min(6, entry.depth * 2));
+ const indent = " ".repeat(SUMMARY_LIST_INDENT);
// Running rows pulse the shared working glyph; other states stay static.
const rawIcon =
entry.node.status === "running"
? workingIconFrame(getWorkingPulseFrame())
: childAgentStatusIcon(entry.node.status);
const icon = formatChildAgentStatusIcon(entry.node.status, rawIcon);
- const numberCell = theme.fg("muted", padTableCell(`Subagent ${number}`, labelWidth));
- const time = formatChildAgentDuration(entry.node.durationMs);
- const timeWidth = 6;
- // Fixed columns consume: icon + space, the label gap, and a space before time.
- const fixed = visibleWidth(indent) + visibleWidth(rawIcon) + 1 + labelWidth + SUMMARY_LABEL_GAP + 1 + timeWidth;
- // The prompt may use all remaining space; the elision keeps it short and the
- // gap fill still right-aligns the time.
- const promptWidth = Math.max(0, width - fixed);
- const prompt = this.elidePrompt(entry.node.label, sharedPrefix, sharedSuffix, promptWidth);
- const promptCell = theme.fg("dim", prompt);
- const labelGap = " ".repeat(SUMMARY_LABEL_GAP);
- const fillWidth = Math.max(
- 0,
- width -
- visibleWidth(indent) -
- visibleWidth(rawIcon) -
- 1 -
- labelWidth -
- SUMMARY_LABEL_GAP -
- visibleWidth(prompt) -
- visibleWidth(time) -
- 1,
- );
- const fill = " ".repeat(fillWidth);
- const timeCell = theme.fg("muted", time);
- return `${indent}${icon} ${numberCell}${labelGap}${promptCell}${fill} ${timeCell}`;
+ const agentLabel = `S${number}`;
+ const agentCell = theme.fg("muted", padTableCell(agentLabel, agentWidth));
+ const promptCell = this.elidePrompt(entry.node.label, sharedPrefix, sharedSuffix, promptWidth);
+ const recapCell = theme.fg("muted", padTableCell(childAgentRecap(entry.node), recapWidth, "…"));
+ const tools =
+ entry.node.toolUseCount === undefined
+ ? ""
+ : `${entry.node.toolUseCount} ${entry.node.toolUseCount === 1 ? "tool" : "tools"}`;
+ const tokens = entry.node.tokenCount === undefined ? "" : `${formatTokenCount(entry.node.tokenCount)} tok`;
+ const duration = formatChildAgentDuration(entry.node.durationMs);
+ const toolsCell = padTableCell(tools, SUMMARY_TOOLS_WIDTH, "…");
+ const tokensCell = padTableCell(tokens, SUMMARY_TOKENS_WIDTH, "…");
+ const durationCell = padTableCell(duration, SUMMARY_DURATION_WIDTH, "…");
+ const metrics = `${toolsCell} ${tokensCell}${" ".repeat(SUMMARY_TOKEN_TIME_GAP)}${durationCell}`;
+ const gap = " ".repeat(SUMMARY_COLUMN_GAP);
+ return `${indent}${icon} ${agentCell}${gap}${promptCell}${gap}${recapCell}${gap}${theme.fg("muted", metrics)}`;
}
- // Coloring is applied by the caller so the trailing ellipsis matches the text.
private elidePrompt(label: string, sharedPrefix: string, sharedSuffix: string, width: number): string {
const text = this.elideAroundDiff(label, sharedPrefix, sharedSuffix);
- // Column-aware truncation (handles wide/combining chars), with the ellipsis
- // reserved inside the budget rather than appended past it.
- return truncateToWidth(text, Math.max(0, width), "…");
+ const safeWidth = Math.max(0, width);
+ const truncated =
+ visibleWidth(text) > safeWidth
+ ? `${truncateToWidth(text, Math.max(0, safeWidth - 1), "")
+ .replaceAll("\x1b[0m", "")
+ .trimEnd()}…`
+ : text;
+ return theme.fg("dim", padTableCell(truncated, safeWidth));
}
// Window the prompt around its divergence: "<leading context>…<~2 words before
diff --git a/packages/coding-agent/src/modes/interactive/components/index.ts b/packages/coding-agent/src/modes/interactive/components/index.ts
index 8ba2745fb9..191c950f13 100644
--- a/packages/coding-agent/src/modes/interactive/components/index.ts
+++ b/packages/coding-agent/src/modes/interactive/components/index.ts
@@ -39,7 +39,6 @@ export { SessionSelectorComponent } from "./session-selector.js";
export { type SettingsCallbacks, type SettingsConfig, SettingsSelectorComponent } from "./settings-selector.js";
export { ShowImagesSelectorComponent } from "./show-images-selector.js";
export { SkillInvocationMessageComponent } from "./skill-invocation-message.js";
-export { SubagentTreeView } from "./subagent-tree-view.js";
export { ThemeSelectorComponent } from "./theme-selector.js";
export { ThinkingSelectorComponent } from "./thinking-selector.js";
export { ToolExecutionComponent, type ToolExecutionOptions } from "./tool-execution.js";
diff --git a/packages/coding-agent/src/modes/interactive/components/subagent-tree-view.ts b/packages/coding-agent/src/modes/interactive/components/subagent-tree-view.ts
deleted file mode 100644
index 93105d1456..0000000000
--- a/packages/coding-agent/src/modes/interactive/components/subagent-tree-view.ts
+++ /dev/null
@@ -1,125 +0,0 @@
-import { type Component, truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
-import { formatTokenCount } from "../agent-activity.js";
-import { theme } from "../theme/theme.js";
-import { getWorkingPulseFrame, workingIconFrame } from "../theme/working-icon.js";
-import { type ChildAgentInspectorNode, nodeActivityLabel } from "./child-agent-inspector.js";
-
-/** Left padding so the tree aligns with the loader message / tool-call text. */
-const PAD = " ";
-/** How many subagents to show before collapsing the rest into a "+N more" line. */
-const MAX_VISIBLE = 5;
-/** Keep each node's label to the first few words so the row stays scannable. */
-const LABEL_MAX_WORDS = 4;
-const LABEL_MAX_CHARS = 32;
-
-/**
- * Live, render-only tree of the current turn's in-flight subagents, shown above the
- * working loader and in addition to the inline list below the prompt bar. Each node is
- * two lines — label + tool-use/token counts, then its current recap — with an animated
- * working icon. Subagents drop out of the tree as soon as they finish.
- */
-export class SubagentTreeView implements Component {
- private nodes: readonly ChildAgentInspectorNode[] = [];
-
- setNodes(nodes: readonly ChildAgentInspectorNode[]): void {
- // Flatten the whole inspector tree — nested subagents live under `children` —
- // and keep only the in-flight ones; finished subagents disappear.
- const flat: ChildAgentInspectorNode[] = [];
- const walk = (list: readonly ChildAgentInspectorNode[]): void => {
- for (const node of list) {
- if (node.status === "running" || node.status === "queued") {
- flat.push(node);
- }
- if (node.children) {
- walk(node.children);
- }
- }
- };
- walk(nodes);
- this.nodes = flat;
- }
-
- hasNodes(): boolean {
- return this.nodes.length > 0;
- }
-
- invalidate(): void {
- // Rendering is derived from the nodes set above.
- }
-
- render(width: number): string[] {
- if (this.nodes.length === 0) {
- return [];
- }
- const safeWidth = Math.max(1, width);
- const visible = this.nodes.slice(0, MAX_VISIBLE);
- const hidden = this.nodes.length - visible.length;
- const icon = theme.fg("accent", workingIconFrame(getWorkingPulseFrame()));
-
- // Leading blank line so the tree doesn't hug the tool call/output above it.
- const lines: string[] = [""];
- lines.push(truncateToWidth(`${PAD}${this.header()}`, safeWidth));
- for (const [index, node] of visible.entries()) {
- const isLast = index === visible.length - 1 && hidden === 0;
- this.renderNode(lines, node, isLast, icon, safeWidth);
- }
- if (hidden > 0) {
- lines.push(truncateToWidth(`${PAD} ${theme.fg("muted", `+${hidden} more`)}`, safeWidth));
- }
- return lines;
- }
-
- private header(): string {
- const count = this.nodes.length;
- const noun = count === 1 ? "agent" : "agents";
- return theme.fg("text", `Running ${count} ${noun}…`);
- }
-
- private renderNode(
- lines: string[],
- node: ChildAgentInspectorNode,
- isLast: boolean,
- icon: string,
- width: number,
- ): void {
- const edge = theme.fg("text", `${isLast ? "└" : "├"} `);
- lines.push(truncateToWidth(`${PAD}${edge}${icon} ${this.nodeSummary(node)}`, width));
-
- // Always a second line: the recap once we have it, else a live activity label
- // (mirroring the main agent's "Writing code" / "Executing" status) so the row
- // is never blank while we wait for the recap.
- const childEdge = theme.fg("text", isLast ? " " : "│ ");
- const connector = theme.fg("dim", "└ ");
- const prefix = `${PAD}${childEdge}${connector}`;
- const detail = node.recap?.trim() || nodeActivityLabel(node);
- const text = truncateToWidth(detail, Math.max(1, width - visibleWidth(prefix)));
- lines.push(`${prefix}${theme.fg("dim", text)}`);
- }
-
- private nodeSummary(node: ChildAgentInspectorNode): string {
- const parts = [theme.fg("text", compactLabel(node.label))];
- const meta: string[] = [];
- if (node.toolUseCount && node.toolUseCount > 0) {
- meta.push(`${node.toolUseCount} ${node.toolUseCount === 1 ? "tool use" : "tool uses"}`);
- }
- if (node.tokenCount && node.tokenCount > 0) {
- meta.push(`${formatTokenCount(node.tokenCount)} tokens`);
- }
- if (meta.length > 0) {
- parts.push(theme.fg("muted", `· ${meta.join(" · ")}`));
- }
- return parts.join(" ");
- }
-}
-
-/** First few words of the prompt, clipped to a sensible width with an ellipsis. */
-function compactLabel(label: string): string {
- const words = label.trim().split(/\s+/);
- let compact = words.slice(0, LABEL_MAX_WORDS).join(" ");
- const clipped = words.length > LABEL_MAX_WORDS;
- if (compact.length > LABEL_MAX_CHARS) {
- compact = compact.slice(0, LABEL_MAX_CHARS).trimEnd();
- return `${compact}…`;
- }
- return clipped ? `${compact}…` : compact;
-}
diff --git a/packages/coding-agent/src/modes/interactive/interactive-mode.ts b/packages/coding-agent/src/modes/interactive/interactive-mode.ts
index 9ff6a820b8..11bc19c84e 100644
--- a/packages/coding-agent/src/modes/interactive/interactive-mode.ts
+++ b/packages/coding-agent/src/modes/interactive/interactive-mode.ts
@@ -181,7 +181,6 @@ import { SessionSelectorComponent } from "./components/session-selector.js";
import { SettingsSelectorComponent } from "./components/settings-selector.js";
import { SideQuestionComponent } from "./components/side-question.js";
import { SkillInvocationMessageComponent } from "./components/skill-invocation-message.js";
-import { SubagentTreeView } from "./components/subagent-tree-view.js";
import { ToolExecutionComponent, type ToolExecutionDefinition } from "./components/tool-execution.js";
import { TreeSelectorComponent } from "./components/tree-selector.js";
import { UserMessageComponent } from "./components/user-message.js";
@@ -290,6 +289,48 @@ export function formatSplashCwd(cwd: string): string {
return normalized;
}
+export function mergeChildAgentSnapshots(
+ previous: AgentConnectionRlmChildAgentSnapshot,
+ incoming: AgentConnectionRlmChildAgentSnapshot,
+): AgentConnectionRlmChildAgentSnapshot {
+ const active = incoming.status === "running" || incoming.status === "queued";
+ return {
+ ...previous,
+ ...incoming,
+ parentId: incoming.parentId ?? previous.parentId,
+ activeSessionId: incoming.activeSessionId ?? previous.activeSessionId,
+ durationMs: incoming.durationMs ?? previous.durationMs,
+ answerPreview: incoming.answerPreview ?? previous.answerPreview,
+ toolUseCount:
+ incoming.toolUseCount === undefined
+ ? previous.toolUseCount
+ : Math.max(previous.toolUseCount ?? 0, incoming.toolUseCount),
+ tokenCount: incoming.tokenCount ?? previous.tokenCount,
+ recap: incoming.recap ?? previous.recap,
+ activity: active ? (incoming.activity ?? previous.activity) : undefined,
+ error: incoming.status === "error" ? (incoming.error ?? previous.error) : undefined,
+ };
+}
+
+function childAgentSummaryChanged(
+ previous: AgentConnectionRlmChildAgentSnapshot,
+ next: AgentConnectionRlmChildAgentSnapshot,
+): boolean {
+ const previousTokens = previous.tokenCount === undefined ? undefined : formatTokenCount(previous.tokenCount);
+ const nextTokens = next.tokenCount === undefined ? undefined : formatTokenCount(next.tokenCount);
+ return (
+ previous.parentId !== next.parentId ||
+ previous.label !== next.label ||
+ previous.status !== next.status ||
+ previous.durationMs !== next.durationMs ||
+ previous.toolUseCount !== next.toolUseCount ||
+ previousTokens !== nextTokens ||
+ previous.recap !== next.recap ||
+ previous.activity?.kind !== next.activity?.kind ||
+ previous.activity?.toolName !== next.activity?.toolName
+ );
+}
+
export function truncatePathMiddle(value: string, width: number): string {
if (visibleWidth(value) <= width) {
return value;
@@ -704,9 +745,6 @@ export class InteractiveMode {
// RLM child-agent tray: inline list below the editor, full-screen detail on open.
private childAgentSummary: ChildAgentSummaryComponent;
- // Live tree of the current turn's subagents, drawn above the working loader.
- // Shown in addition to the inline list below the prompt bar.
- private subagentTree = new SubagentTreeView();
private childAgentDetail: ChildAgentDetailComponent;
private childAgentSnapshots = new Map<string, AgentConnectionRlmChildAgentSnapshot>();
private childAgentNodes: ChildAgentInspectorNode[] = [];
@@ -737,7 +775,6 @@ export class InteractiveMode {
private connectionModelsRefreshInFlight: { version: number; promise: Promise<AgentConnectionModel[]> } | undefined;
private connectionState: AgentConnectionState | undefined;
private connectionResourceSnapshot: AgentConnectionResourceSnapshot | undefined;
- private initialConnectionSnapshotConsumed = false;
private sessionHasMessages = false;
// Registry of images pasted this session, keyed by the `[image #N]` marker
@@ -2449,6 +2486,35 @@ export class InteractiveMode {
this.syncWorkingLoader();
}
+ private async renderResyncedSession(snapshot: AgentConnectionSnapshot): Promise<void> {
+ const compactionFinished = this.isAgentCompacting() && !snapshot.state.isCompacting;
+ const bashFinished = this.isBashRunning() && !snapshot.state.isBashRunning;
+ this.applyConnectionStateSnapshot(snapshot.state);
+ this.streamingComponent = undefined;
+ this.streamingMessage = undefined;
+ this.replaceChildAgentInspector(snapshot.children);
+ await this.renderSessionContext(this.getSessionContextFromConnectionSnapshot(snapshot), {
+ clearChat: true,
+ updateFooter: true,
+ });
+ await this.restoreStreamingMessageFromSnapshot(snapshot.streamingMessage);
+ await this.refreshConnectionQueue();
+ if (compactionFinished) {
+ await this.flushCompactionQueue({ willRetry: false });
+ }
+ if (bashFinished && this.activeBashComponent) {
+ this.activeBashComponent.setComplete(undefined, false);
+ this.activeBashComponent = undefined;
+ if (!snapshot.state.isStreaming) {
+ this.flushPendingBashComponents();
+ }
+ }
+ this.updateTerminalTitle();
+ this.setGoalAnnouncementBaseline(this.getGoalState());
+ this.syncGoalTray(this.getGoalState());
+ this.syncWorkingLoader();
+ }
+
private getCachedToolDefinition(toolName: string): ToolExecutionDefinition | undefined {
return this.toolDefinitionCache.get(toolName);
}
@@ -4094,6 +4160,11 @@ export class InteractiveMode {
await this.rebindCurrentSession();
await this.renderInitialMessages();
this.ui.requestRender();
+ } else if (event.type === "session_resynced") {
+ const run = this.sessionEventQueue.then(() => this.renderResyncedSession(event.snapshot));
+ this.sessionEventQueue = run.catch(() => {});
+ await run;
+ this.ui.requestRender();
} else if (event.type === "session_status") {
this.sessionRecap = event.recap;
this.patchConnectionState({ recap: event.recap });
@@ -4102,6 +4173,11 @@ export class InteractiveMode {
this.handleSideQuestionEvent(event.event);
} else if (event.type === "extension_ui_request") {
await this.handleConnectionExtensionUiRequest(event.request);
+ } else if (event.type === "connection_status") {
+ this.showStatus(
+ event.status === "connected" ? "Daemon reconnected" : "Daemon connection lost; reconnecting…",
+ event.status === "reconnecting" ? "warning" : "dim",
+ );
} else if (event.type === "closed") {
this.showError(event.error ?? "Agent connection closed");
}
@@ -4823,13 +4899,31 @@ export class InteractiveMode {
if (!children?.length) {
return;
}
+ let changed = false;
for (const child of children) {
// Live rlm_child_update events are richer than the snapshot; never
// clobber state that already arrived from the event stream.
- if (!this.childAgentSnapshots.has(child.id)) {
- this.updateChildAgentInspector(child);
+ if (!this.childAgentSnapshots.has(child.id) && child.status !== "cancelled") {
+ this.childAgentSnapshots.set(child.id, child);
+ changed = true;
}
}
+ if (changed) {
+ this.refreshChildAgentInspector();
+ }
+ }
+
+ private replaceChildAgentInspector(children: readonly AgentConnectionRlmChildAgentSnapshot[] | undefined): void {
+ const next = new Map<string, AgentConnectionRlmChildAgentSnapshot>();
+ for (const child of children ?? []) {
+ if (child.status === "cancelled") {
+ continue;
+ }
+ const previous = this.childAgentSnapshots.get(child.id);
+ next.set(child.id, previous ? mergeChildAgentSnapshots(previous, child) : child);
+ }
+ this.childAgentSnapshots = next;
+ this.refreshChildAgentInspector();
}
private updateChildAgentInspector(child: AgentConnectionRlmChildAgentSnapshot): void {
@@ -4837,12 +4931,20 @@ export class InteractiveMode {
// viewer instead of keeping a dead row around.
if (child.status === "cancelled") {
this.removeChildAgentSnapshot(child.id);
- } else {
- this.childAgentSnapshots.set(child.id, child);
+ this.refreshChildAgentInspector();
+ return;
}
+ const previous = this.childAgentSnapshots.get(child.id);
+ const next = previous ? mergeChildAgentSnapshots(previous, child) : child;
+ this.childAgentSnapshots.set(child.id, next);
+ if (!previous || childAgentSummaryChanged(previous, next) || this.childAgentDetailNodeId === child.id) {
+ this.refreshChildAgentInspector();
+ }
+ }
+
+ private refreshChildAgentInspector(): void {
this.childAgentNodes = this.buildChildAgentInspectorNodes();
this.childAgentSummary.setNodes(this.childAgentNodes);
- this.subagentTree.setNodes(this.childAgentNodes);
this.updateWorkingPulse();
this.syncWorkingLoader();
this.updateWorkingLoaderMessage();
@@ -4872,8 +4974,6 @@ export class InteractiveMode {
this.mainViewContainer.addChild(this.chatContainer);
this.mainViewContainer.addChild(this.shortcutGuideContainer);
this.mainViewContainer.addChild(this.pendingMessagesContainer);
- // Subagent tree sits directly above the loader, mirroring Claude's layout.
- this.mainViewContainer.addChild(this.subagentTree);
this.mainViewContainer.addChild(this.statusContainer);
}
@@ -4881,7 +4981,6 @@ export class InteractiveMode {
this.childAgentSnapshots.clear();
this.childAgentNodes = [];
this.childAgentSummary.setNodes([]);
- this.subagentTree.setNodes([]);
this.childAgentSummary.setHidden(false);
this.childAgentDetail.setNode(undefined);
this.childAgentDetailNodeId = undefined;
@@ -5082,6 +5181,10 @@ export class InteractiveMode {
}
private openChildAgentDetail(nodeId: string): boolean {
+ // Live text deltas are stored without redrawing the summary on every token.
+ // Rebuild once here so the detail opens with the latest preview and recap.
+ this.childAgentNodes = this.buildChildAgentInspectorNodes();
+ this.childAgentSummary.setNodes(this.childAgentNodes);
const node = this.findChildAgentInspectorNode(nodeId);
if (!node) {
return false;
@@ -5132,8 +5235,8 @@ export class InteractiveMode {
if (token !== this.childAgentWatcherToken) {
return;
}
- // session_replaced carries a fresh messages array; both need a rebuild.
- if (event.type === "session_event" || event.type === "session_replaced") {
+ // Replacement and resync snapshots both carry authoritative messages.
+ if (event.type === "session_event" || event.type === "session_replaced" || event.type === "session_resynced") {
void this.refreshChildAgentWatch(token, watcher);
}
});
@@ -5352,19 +5455,19 @@ export class InteractiveMode {
* If multiple status messages are emitted back-to-back (without anything else being added to the chat),
* we update the previous status line instead of appending new ones to avoid log spam.
*/
- private showStatus(message: string): void {
+ private showStatus(message: string, tone: "dim" | "warning" = "dim"): void {
const children = this.chatContainer.children;
const last = children.length > 0 ? children[children.length - 1] : undefined;
const secondLast = children.length > 1 ? children[children.length - 2] : undefined;
if (last && secondLast && last === this.lastStatusText && secondLast === this.lastStatusSpacer) {
- this.lastStatusText.setText(theme.fg("dim", message));
+ this.lastStatusText.setText(theme.fg(tone, message));
this.ui.requestRender();
return;
}
const spacer = new Spacer(1);
- const text = new Text(theme.fg("dim", message), 1, 0);
+ const text = new Text(theme.fg(tone, message), 1, 0);
this.chatContainer.addChild(spacer);
this.chatContainer.addChild(text);
this.lastStatusSpacer = spacer;
@@ -5602,26 +5705,18 @@ export class InteractiveMode {
}
async renderInitialMessages(): Promise<void> {
- let context: AgentConnectionSessionContext;
- let state: AgentConnectionState;
- if (this.initialConnectionSnapshotConsumed) {
- [context, state] = await Promise.all([
- this.agentConnection.getSessionContext(),
- this.agentConnection.getState(),
- ]);
- } else {
- const snapshot = await this.agentConnection.getInitialSnapshot();
- this.initialConnectionSnapshotConsumed = true;
- context = this.getSessionContextFromConnectionSnapshot(snapshot);
- state = snapshot.state;
- this.seedChildAgentInspector(snapshot.children);
- }
+ const snapshot = await this.agentConnection.getInitialSnapshot();
+ const context = this.getSessionContextFromConnectionSnapshot(snapshot);
+ const state = snapshot.state;
+ const streamingMessage = snapshot.streamingMessage;
+ this.seedChildAgentInspector(snapshot.children);
this.setSessionHasMessages(context.messages.length > 0);
this.applyConnectionStateSnapshot(state);
await this.renderSessionContext(context, {
updateFooter: true,
populateHistory: true,
});
+ await this.restoreStreamingMessageFromSnapshot(streamingMessage);
// Show compaction info if session was compacted
const compactionCount = state.compactionCount;
@@ -5631,6 +5726,18 @@ export class InteractiveMode {
}
}
+ private async restoreStreamingMessageFromSnapshot(message: AgentMessage | undefined): Promise<void> {
+ if (message?.role === "assistant") {
+ this.startAssistantStreamingMessage(message);
+ for (const content of message.content) {
+ if (content.type === "toolCall") {
+ this.startedToolCalls.add(content.id);
+ await this.getOrCreatePendingToolComponent(content);
+ }
+ }
+ }
+ }
+
private getSessionContextFromConnectionSnapshot(snapshot: AgentConnectionSnapshot): AgentConnectionSessionContext {
if (snapshot.sessionContext) {
return snapshot.sessionContext;
diff --git a/packages/coding-agent/src/modes/print-mode.ts b/packages/coding-agent/src/modes/print-mode.ts
index 49b7059135..efa8214021 100644
--- a/packages/coding-agent/src/modes/print-mode.ts
+++ b/packages/coding-agent/src/modes/print-mode.ts
@@ -9,10 +9,10 @@
import type { AssistantMessage, ImageContent } from "@earendil-works/pi-ai";
import type { AgentSessionRuntime } from "../core/agent-session-runtime.js";
import {
- type AgentAutonomousGateFailure,
type AgentAutonomousStatus,
type AutonomousLimitReason,
autonomousLimitReason,
+ buildAutonomousGateFailureContinuation,
} from "../core/autonomous.js";
import { flushRawStdout, writeRawStdout } from "../core/output-guard.js";
import { killTrackedDetachedChildren } from "../utils/shell.js";
@@ -59,18 +59,6 @@ function shouldContinuePrintModeAutonomousGates(status: AgentAutonomousStatus):
);
}
-function buildPrintModeGateContinuation(
- failure: AgentAutonomousGateFailure,
- attempt: number,
- maxRetries: number,
-): string {
- return (
- `Autonomous quality gate failed (attempt ${attempt}/${maxRetries}): \`${failure.command}\` ${failure.exitText}.\n` +
- (failure.output ? `\nOutput:\n${failure.output}\n` : "\n") +
- `\nContinue working. Fix the failure, then produce terminal evidence. Timestamp: ${new Date().toISOString()}.`
- );
-}
-
function printModeAutonomousProgressKey(status: AgentAutonomousStatus): string {
return [
latestGateAttempt(status),
@@ -111,7 +99,10 @@ async function waitForPrintModeIdleWithAutonomousGates(
}
session.recordHostAutonomousContinuation();
await session.prompt(
- buildPrintModeGateContinuation(status.lastGateFailure, latestGateAttempt(status), status.gates.maxRetries),
+ buildAutonomousGateFailureContinuation(
+ { ...status.lastGateFailure, attempt: latestGateAttempt(status) },
+ status.gates.maxRetries,
+ ),
{
streamingBehavior: "followUp",
internalPrompt: true,
diff --git a/packages/coding-agent/src/modes/session-worker/private-framing.ts b/packages/coding-agent/src/modes/session-worker/private-framing.ts
new file mode 100644
index 0000000000..4caf143f6a
--- /dev/null
+++ b/packages/coding-agent/src/modes/session-worker/private-framing.ts
@@ -0,0 +1,200 @@
+import type { Duplex } from "node:stream";
+
+const FRAME_PREFIX_BYTES = 8;
+
+export interface PrivateFrameLimits {
+ maxHeaderBytes: number;
+ maxPayloadBytes: number;
+}
+
+export const DEFAULT_PRIVATE_FRAME_LIMITS: PrivateFrameLimits = {
+ maxHeaderBytes: 1024 * 1024,
+ maxPayloadBytes: 1024 * 1024 * 1024,
+};
+
+export interface PrivateFrame<THeader extends object> {
+ header: THeader;
+ payload: Buffer;
+}
+
+export type PrivateFrameHeaderValidator<THeader extends object> = (value: unknown) => value is THeader;
+
+function assertFrameLength(name: string, value: number, maximum: number): void {
+ if (!Number.isSafeInteger(value) || value < 0 || value > maximum) {
+ throw new Error(`Invalid private frame ${name}: ${value}`);
+ }
+}
+
+function isObjectHeader(value: unknown): value is object {
+ return typeof value === "object" && value !== null && !Array.isArray(value);
+}
+
+export function encodePrivateFrame<THeader extends object>(
+ header: THeader,
+ payload: Uint8Array = Buffer.alloc(0),
+ limits: PrivateFrameLimits = DEFAULT_PRIVATE_FRAME_LIMITS,
+): Buffer {
+ const headerBuffer = Buffer.from(JSON.stringify(header), "utf8");
+ const payloadBuffer = Buffer.isBuffer(payload) ? payload : Buffer.from(payload);
+ assertFrameLength("header length", headerBuffer.length, limits.maxHeaderBytes);
+ assertFrameLength("payload length", payloadBuffer.length, limits.maxPayloadBytes);
+ if (headerBuffer.length === 0) {
+ throw new Error("Private frame header cannot be empty");
+ }
+
+ const frame = Buffer.allocUnsafe(FRAME_PREFIX_BYTES + headerBuffer.length + payloadBuffer.length);
+ frame.writeUInt32BE(headerBuffer.length, 0);
+ frame.writeUInt32BE(payloadBuffer.length, 4);
+ headerBuffer.copy(frame, FRAME_PREFIX_BYTES);
+ payloadBuffer.copy(frame, FRAME_PREFIX_BYTES + headerBuffer.length);
+ return frame;
+}
+
+export class PrivateFrameDecoder<THeader extends object> {
+ private buffered: Buffer<ArrayBufferLike> = Buffer.alloc(0);
+
+ constructor(
+ private readonly validateHeader: PrivateFrameHeaderValidator<THeader>,
+ private readonly limits: PrivateFrameLimits = DEFAULT_PRIVATE_FRAME_LIMITS,
+ ) {}
+
+ get bufferedBytes(): number {
+ return this.buffered.length;
+ }
+
+ push(chunk: Uint8Array): PrivateFrame<THeader>[] {
+ if (chunk.length > 0) {
+ const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
+ this.buffered = this.buffered.length === 0 ? buffer : Buffer.concat([this.buffered, buffer]);
+ }
+
+ const frames: PrivateFrame<THeader>[] = [];
+ let offset = 0;
+ while (this.buffered.length - offset >= FRAME_PREFIX_BYTES) {
+ const headerLength = this.buffered.readUInt32BE(offset);
+ const payloadLength = this.buffered.readUInt32BE(offset + 4);
+ assertFrameLength("header length", headerLength, this.limits.maxHeaderBytes);
+ assertFrameLength("payload length", payloadLength, this.limits.maxPayloadBytes);
+ if (headerLength === 0) {
+ throw new Error("Private frame header cannot be empty");
+ }
+
+ const frameLength = FRAME_PREFIX_BYTES + headerLength + payloadLength;
+ if (this.buffered.length - offset < frameLength) {
+ break;
+ }
+
+ const headerStart = offset + FRAME_PREFIX_BYTES;
+ const payloadStart = headerStart + headerLength;
+ let decoded: unknown;
+ try {
+ decoded = JSON.parse(this.buffered.toString("utf8", headerStart, payloadStart));
+ } catch (error) {
+ throw new Error(
+ `Invalid private frame header JSON: ${error instanceof Error ? error.message : String(error)}`,
+ );
+ }
+ if (!isObjectHeader(decoded) || !this.validateHeader(decoded)) {
+ throw new Error("Invalid private frame routing header");
+ }
+
+ frames.push({
+ header: decoded,
+ payload: Buffer.from(this.buffered.subarray(payloadStart, payloadStart + payloadLength)),
+ });
+ offset += frameLength;
+ }
+
+ if (offset > 0) {
+ this.buffered = Buffer.from(this.buffered.subarray(offset));
+ }
+ return frames;
+ }
+
+ finish(): void {
+ if (this.buffered.length !== 0) {
+ throw new Error(`Private frame channel ended with ${this.buffered.length} incomplete bytes`);
+ }
+ }
+}
+
+export type PrivateFrameListener<THeader extends object> = (frame: PrivateFrame<THeader>) => void;
+
+export class PrivateFramedChannel<THeader extends object> {
+ private readonly decoder: PrivateFrameDecoder<THeader>;
+ private readonly listeners = new Set<PrivateFrameListener<THeader>>();
+ private closed = false;
+
+ constructor(
+ private readonly stream: Duplex,
+ validateHeader: PrivateFrameHeaderValidator<THeader>,
+ private readonly limits: PrivateFrameLimits = DEFAULT_PRIVATE_FRAME_LIMITS,
+ ) {
+ this.decoder = new PrivateFrameDecoder(validateHeader, limits);
+ stream.on("data", this.handleData);
+ stream.on("end", this.handleEnd);
+ stream.on("close", this.handleClose);
+ }
+
+ onFrame(listener: PrivateFrameListener<THeader>): () => void {
+ this.listeners.add(listener);
+ return () => this.listeners.delete(listener);
+ }
+
+ async send(header: THeader, payload?: Uint8Array): Promise<void> {
+ if (this.closed || this.stream.destroyed) {
+ throw new Error("Private frame channel is closed");
+ }
+ const frame = encodePrivateFrame(header, payload, this.limits);
+ await new Promise<void>((resolve, reject) => {
+ this.stream.write(frame, (error?: Error | null) => {
+ if (error) {
+ reject(error);
+ } else {
+ resolve();
+ }
+ });
+ });
+ }
+
+ close(): void {
+ if (this.closed) {
+ return;
+ }
+ this.closed = true;
+ this.detach();
+ this.stream.end();
+ }
+
+ private readonly handleData = (chunk: Buffer): void => {
+ try {
+ for (const frame of this.decoder.push(chunk)) {
+ for (const listener of this.listeners) {
+ listener(frame);
+ }
+ }
+ } catch (error) {
+ this.stream.destroy(error instanceof Error ? error : new Error(String(error)));
+ }
+ };
+
+ private readonly handleEnd = (): void => {
+ try {
+ this.decoder.finish();
+ } catch (error) {
+ this.stream.destroy(error instanceof Error ? error : new Error(String(error)));
+ }
+ };
+
+ private readonly handleClose = (): void => {
+ this.closed = true;
+ this.detach();
+ };
+
+ private detach(): void {
+ this.stream.off("data", this.handleData);
+ this.stream.off("end", this.handleEnd);
+ this.stream.off("close", this.handleClose);
+ this.listeners.clear();
+ }
+}
diff --git a/packages/coding-agent/src/package-manager-cli.ts b/packages/coding-agent/src/package-manager-cli.ts
index c428bd07b6..7987688258 100644
--- a/packages/coding-agent/src/package-manager-cli.ts
+++ b/packages/coding-agent/src/package-manager-cli.ts
@@ -31,6 +31,7 @@ import { DefaultPackageManager } from "./core/package-manager.js";
import { SettingsManager } from "./core/settings-manager.js";
import { DaemonClient } from "./modes/daemon/daemon-client.js";
import {
+ DAEMON_PROTOCOL_VERSION,
type DaemonUpdateRestartManifest,
type DaemonUpdateRestartQueuedMessage,
type DaemonUpdateRestartSession,
@@ -704,15 +705,21 @@ export async function prepareDaemonUpdateRestart(
try {
await client.connect(1000);
connected = true;
+ const hello = await client.waitForHello(2000).catch(() => undefined);
+ const useLegacyProtocol = hello !== undefined && hello.protocol.version < DAEMON_PROTOCOL_VERSION;
if (pendingManifest && pendingManifest.sessions.length > 0) {
- const listResponse = await client.request({ type: "list" }, 30000);
+ const listResponse = useLegacyProtocol
+ ? await client.requestLegacy({ type: "list" }, 30000)
+ : await client.request({ type: "list" }, 30000);
if (listResponse.success && !responseHasActiveDaemonSessions(listResponse.data)) {
return pendingManifest;
}
}
clearPreparedDaemonUpdateRestartManifest(agentDir);
startedAt = Date.now();
- const response = await client.request({ type: "prepare_update_restart" }, 120000);
+ const response = useLegacyProtocol
+ ? await client.requestLegacy({ type: "prepare_update_restart" }, 120000)
+ : await client.request({ type: "prepare_update_restart" }, 120000);
if (!response.success) {
throw new Error(response.error);
}
diff --git a/packages/coding-agent/src/utils/shell.ts b/packages/coding-agent/src/utils/shell.ts
index 1c235802b5..cbf289d86a 100644
--- a/packages/coding-agent/src/utils/shell.ts
+++ b/packages/coding-agent/src/utils/shell.ts
@@ -2,6 +2,7 @@ import { existsSync } from "node:fs";
import { delimiter } from "node:path";
import { spawn, spawnSync } from "child_process";
import { getBinDir } from "../config.js";
+import { recordOrphanProcessState } from "../core/orphan-process-journal.js";
export interface ShellConfig {
shell: string;
@@ -167,15 +168,18 @@ const trackedDetachedChildPids = new Set<number>();
export function trackDetachedChildPid(pid: number): void {
trackedDetachedChildPids.add(pid);
+ recordOrphanProcessState(pid, true);
}
export function untrackDetachedChildPid(pid: number): void {
trackedDetachedChildPids.delete(pid);
+ recordOrphanProcessState(pid, false);
}
export function killTrackedDetachedChildren(): void {
for (const pid of trackedDetachedChildPids) {
killProcessTree(pid);
+ recordOrphanProcessState(pid, false);
}
trackedDetachedChildPids.clear();
}
diff --git a/packages/coding-agent/test/agent-connection-daemon.test.ts b/packages/coding-agent/test/agent-connection-daemon.test.ts
index 0b903530aa..eba3fd2d9b 100644
--- a/packages/coding-agent/test/agent-connection-daemon.test.ts
+++ b/packages/coding-agent/test/agent-connection-daemon.test.ts
@@ -38,7 +38,10 @@ class FakeDaemonClient {
emitCloseOnClose = false;
connected = true;
reconnectCount = 0;
+ resetTransportCount = 0;
reconnectError: Error | undefined;
+ attachFailures = 0;
+ connectionStateGate: Promise<void> | undefined;
abortBashUnknownCommand = false;
abortAndClearQueueUnknownCommand = false;
updateRestartSessions: Array<Record<string, unknown>> = [];
@@ -61,6 +64,10 @@ class FakeDaemonClient {
data: { sessions: this.updateRestartSessions },
};
case "attach":
+ if (this.attachFailures > 0) {
+ this.attachFailures--;
+ throw new Error("attach failed");
+ }
if (command.activeSessionId === "active-restored" && this.restoredAttachGate) {
await this.restoredAttachGate;
this.restoredAttachCompleted++;
@@ -89,6 +96,7 @@ class FakeDaemonClient {
data: { steering: ["steer"], followUp: ["follow"] },
};
case "get_connection_state":
+ await this.connectionStateGate;
return {
type: "response",
command: command.type,
@@ -382,6 +390,26 @@ class FakeDaemonClient {
}
}
+ enableRequestRecovery(): void {}
+
+ async connect(): Promise<void> {
+ if (this.connected) {
+ throw new Error("Prime Agent daemon client is already connected");
+ }
+ this.reconnectCount++;
+ if (this.reconnectError) {
+ throw this.reconnectError;
+ }
+ this.connected = true;
+ }
+
+ async waitForHello(): Promise<void> {}
+
+ resetTransportForReconnect(): void {
+ this.resetTransportCount++;
+ this.connected = false;
+ }
+
async reconnect(): Promise<void> {
if (this.connected) {
return;
@@ -458,6 +486,7 @@ function createConnectionState(activeSessionId: string, sessionId: string): Agen
interface CreateAttachResultOptions {
state?: AgentConnectionState;
messages?: AgentMessage[];
+ streamingMessage?: AgentMessage;
sessionContext?: DaemonAttachResult["snapshot"]["sessionContext"];
omitSessionContext?: boolean;
sessionTree?: DaemonAttachResult["snapshot"]["sessionTree"];
@@ -474,6 +503,7 @@ function createAttachResult(
): DaemonAttachResult {
const state = options.state ?? createConnectionState(activeSessionId, "session-current");
const messages = options.messages ?? [];
+ const lastEventCursor = { generation: `generation-${activeSessionId}`, sequence: lastEventSequence };
const summary = {
id: activeSessionId,
activeSessionId,
@@ -481,11 +511,12 @@ function createAttachResult(
activity: "idle" as const,
sessionId: state.sessionId,
cwd: "/tmp/project",
- isStreaming: false,
+ isStreaming: state.isStreaming,
isCompacting: false,
attachedClients: 1,
messageCount: messages.length,
pendingMessageCount: 0,
+ ...(options.streamingMessage ? { streamingMessage: options.streamingMessage } : {}),
};
// Slim shape: the daemon omits top-level state/messages for clients with the
// "slim_attach" capability, which DaemonAgentConnection always advertises.
@@ -510,13 +541,16 @@ function createAttachResult(
}),
sessionTree: options.sessionTree ?? { tree: [], leafId: state.leafId },
lastEventSequence,
+ lastEventCursor,
...(options.parent ? { parent: options.parent } : {}),
},
replay: options.replay ?? {
status: "complete",
toSequence: lastEventSequence,
+ toCursor: lastEventCursor,
},
lastEventSequence,
+ lastEventCursor,
client: {
id: clientId ?? "client-1",
capabilities: (capabilities ?? ["attach_snapshot", "event_sequence"]).filter(
@@ -524,7 +558,8 @@ function createAttachResult(
capability === "attach_snapshot" ||
capability === "event_sequence" ||
capability === "extension_ui" ||
- capability === "slim_attach",
+ capability === "slim_attach" ||
+ capability === "chunked_snapshot",
),
},
};
@@ -544,6 +579,7 @@ function emitSequencedQueueUpdate(client: FakeDaemonClient, activeSessionId: str
protocol: DAEMON_PROTOCOL_INFO,
activeSessionId,
sequence,
+ cursor: { generation: `generation-${activeSessionId}`, sequence },
emittedAt: "2026-01-01T00:00:00.000Z",
},
});
@@ -572,7 +608,7 @@ describe("DaemonAgentConnection", () => {
const restored = new Promise<AgentConnectionEvent>((resolve) => {
connection.subscribe((event) => {
events.push(event);
- if (event.type === "session_replaced") {
+ if (event.type === "session_resynced") {
resolve(event);
}
});
@@ -589,9 +625,11 @@ describe("DaemonAgentConnection", () => {
expect(fakeClient.reconnectCount).toBe(1);
await expect(restored).resolves.toMatchObject({
- type: "session_replaced",
- state: { activeSessionId: "active-restored", sessionId: "session-current" },
- messages: restoredMessages,
+ type: "session_resynced",
+ snapshot: {
+ state: { activeSessionId: "active-restored", sessionId: "session-current" },
+ messages: restoredMessages,
+ },
});
expect(fakeClient.reconnectCount).toBe(1);
expect(fakeClient.requests.map((request) => request.type)).toEqual(["attach", "list", "attach"]);
@@ -602,8 +640,10 @@ describe("DaemonAgentConnection", () => {
});
expect(events).toEqual([
expect.objectContaining({
- type: "session_replaced",
- state: expect.objectContaining({ activeSessionId: "active-restored" }),
+ type: "session_resynced",
+ snapshot: expect.objectContaining({
+ state: expect.objectContaining({ activeSessionId: "active-restored" }),
+ }),
}),
]);
});
@@ -627,7 +667,7 @@ describe("DaemonAgentConnection", () => {
const connection = new DaemonAgentConnection(asDaemonClient(fakeClient), "active-original");
const restored = new Promise<AgentConnectionEvent>((resolve) => {
connection.subscribe((event) => {
- if (event.type === "session_replaced") {
+ if (event.type === "session_resynced") {
resolve(event);
}
});
@@ -637,9 +677,11 @@ describe("DaemonAgentConnection", () => {
fakeClient.emitClose(new DaemonSocketClosedError("/tmp/prime-agent.sock", "update"));
await expect(restored).resolves.toMatchObject({
- type: "session_replaced",
- state: { activeSessionId: "active-restored", sessionId: "session-current" },
- messages: restoredMessages,
+ type: "session_resynced",
+ snapshot: {
+ state: { activeSessionId: "active-restored", sessionId: "session-current" },
+ messages: restoredMessages,
+ },
});
expect(fakeClient.reconnectCount).toBe(1);
expect(fakeClient.requests.map((request) => request.type)).toEqual(["attach", "list", "attach"]);
@@ -678,14 +720,14 @@ describe("DaemonAgentConnection", () => {
await connectionB.attach();
const restoredA = new Promise<AgentConnectionEvent>((resolve) => {
connectionA.subscribe((event) => {
- if (event.type === "session_replaced") {
+ if (event.type === "session_resynced") {
resolve(event);
}
});
});
const restoredB = new Promise<AgentConnectionEvent>((resolve) => {
connectionB.subscribe((event) => {
- if (event.type === "session_replaced") {
+ if (event.type === "session_resynced") {
resolve(event);
}
});
@@ -695,12 +737,16 @@ describe("DaemonAgentConnection", () => {
await expect(Promise.all([restoredA, restoredB])).resolves.toEqual([
expect.objectContaining({
- type: "session_replaced",
- state: expect.objectContaining({ sessionId: "session-a" }),
+ type: "session_resynced",
+ snapshot: expect.objectContaining({
+ state: expect.objectContaining({ sessionId: "session-a" }),
+ }),
}),
expect.objectContaining({
- type: "session_replaced",
- state: expect.objectContaining({ sessionId: "session-b" }),
+ type: "session_resynced",
+ snapshot: expect.objectContaining({
+ state: expect.objectContaining({ sessionId: "session-b" }),
+ }),
}),
]);
expect(fakeClient.closeCount).toBe(1);
@@ -939,7 +985,7 @@ describe("DaemonAgentConnection", () => {
const restored = new Promise<AgentConnectionEvent>((resolve) => {
connection.subscribe((event) => {
- if (event.type === "session_replaced") {
+ if (event.type === "session_resynced") {
resolve(event);
}
});
@@ -952,9 +998,11 @@ describe("DaemonAgentConnection", () => {
fakeClient.emitClose(new Error("Daemon socket closed"));
await expect(restored).resolves.toMatchObject({
- type: "session_replaced",
- state: { activeSessionId: "active-restored", sessionId: "session-next" },
- messages: restoredMessages,
+ type: "session_resynced",
+ snapshot: {
+ state: { activeSessionId: "active-restored", sessionId: "session-next" },
+ messages: restoredMessages,
+ },
});
expect(fakeClient.requests.map((request) => request.type)).toEqual(["attach", "list", "attach"]);
expect(fakeClient.requests.at(-1)).toMatchObject({
@@ -1008,6 +1056,52 @@ describe("DaemonAgentConnection", () => {
]);
});
+ it("forwards catch-up snapshots as non-destructive resync events", async () => {
+ const fakeClient = new FakeDaemonClient();
+ const connection = new DaemonAgentConnection(asDaemonClient(fakeClient), "active-1");
+ const events: AgentConnectionEvent[] = [];
+ connection.subscribe((event) => {
+ events.push(event);
+ });
+ await connection.attach();
+ const messages: AgentMessage[] = [{ role: "user", content: "caught up", timestamp: 2 }];
+ const streamingMessage = {
+ role: "assistant",
+ content: [{ type: "thinking", thinking: "Still reasoning" }],
+ } as AgentMessage;
+ const snapshot = createAttachResult("active-1", "client-1", undefined, 13, {
+ state: { ...createConnectionState("active-1", "session-current"), isStreaming: true },
+ messages,
+ streamingMessage,
+ }).snapshot;
+
+ fakeClient.emitMessage({
+ type: "session_resynced",
+ activeSessionId: "active-1",
+ snapshot,
+ meta: {
+ id: "active-1:13",
+ protocol: DAEMON_PROTOCOL_INFO,
+ activeSessionId: "active-1",
+ sequence: 13,
+ cursor: { generation: "generation-active-1", sequence: 13 },
+ emittedAt: "2026-01-01T00:00:00.000Z",
+ },
+ });
+
+ expect(events).toEqual([
+ {
+ type: "session_resynced",
+ snapshot: expect.objectContaining({
+ state: expect.objectContaining({ sessionId: "session-current" }),
+ messages,
+ streamingMessage,
+ lastEventSequence: 13,
+ }),
+ },
+ ]);
+ });
+
it("exposes attach snapshots as the initial connection snapshot", async () => {
const fakeClient = new FakeDaemonClient();
const snapshotMessage: AgentMessage = { role: "user", content: "snapshot prompt", timestamp: 1 };
@@ -1080,6 +1174,238 @@ describe("DaemonAgentConnection", () => {
expect(fakeClient.requests.map((request) => request.type)).toEqual(["attach"]);
});
+ it("preserves the in-flight assistant message when refreshing a stale snapshot", async () => {
+ const fakeClient = new FakeDaemonClient();
+ const connection = new DaemonAgentConnection(asDaemonClient(fakeClient), "active-1");
+ await connection.attach();
+ const streamingMessage: AgentMessage = {
+ role: "assistant",
+ content: [{ type: "text", text: "partial response" }],
+ api: "test-api",
+ provider: "test-provider",
+ model: "test-model",
+ usage: {
+ input: 0,
+ output: 0,
+ cacheRead: 0,
+ cacheWrite: 0,
+ totalTokens: 0,
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
+ },
+ stopReason: "stop",
+ timestamp: 2,
+ };
+ fakeClient.emitMessage({
+ type: "session_event",
+ activeSessionId: "active-1",
+ event: { type: "message_start", message: streamingMessage },
+ meta: {
+ id: "active-1:13",
+ protocol: DAEMON_PROTOCOL_INFO,
+ activeSessionId: "active-1",
+ sequence: 13,
+ cursor: { generation: "generation-active-1", sequence: 13 },
+ emittedAt: "2026-01-01T00:00:00.000Z",
+ },
+ });
+
+ await expect(connection.getInitialSnapshot()).resolves.toMatchObject({ streamingMessage });
+ expect(fakeClient.requests.map((request) => request.type)).toEqual([
+ "attach",
+ "get_connection_state",
+ "get_messages",
+ "get_session_context",
+ ]);
+ });
+
+ it("does not stamp independently fetched snapshot data with an event cursor observed mid-fetch", async () => {
+ const fakeClient = new FakeDaemonClient();
+ const connection = new DaemonAgentConnection(asDaemonClient(fakeClient), "active-1");
+ await connection.attach();
+ emitSequencedQueueUpdate(fakeClient, "active-1", 13);
+ let releaseState!: () => void;
+ fakeClient.connectionStateGate = new Promise<void>((resolveState) => {
+ releaseState = resolveState;
+ });
+
+ const snapshotPromise = connection.getInitialSnapshot();
+ await Promise.resolve();
+ emitSequencedQueueUpdate(fakeClient, "active-1", 14);
+ releaseState();
+ const snapshot = await snapshotPromise;
+
+ expect(snapshot.lastEventCursor).toEqual({ generation: "generation-active-1", sequence: 13 });
+ await connection.getState();
+ expect(fakeClient.requests.filter((request) => request.type === "get_connection_state")).toHaveLength(2);
+ });
+
+ it("times out an attach whose streamed snapshot never completes", async () => {
+ const fakeClient = new FakeDaemonClient();
+ fakeClient.attachResultFactory = (command) => {
+ const result = createAttachResult(command.activeSessionId, command.clientId, command.capabilities, 12);
+ return {
+ ...result,
+ snapshotStream: { id: "snapshot-stalled", messageCount: 0, targetChunkBytes: 512 * 1024 },
+ };
+ };
+ const connection = new DaemonAgentConnection(asDaemonClient(fakeClient), "active-1", {
+ snapshotTimeoutMs: 10,
+ });
+
+ await expect(connection.attach()).rejects.toThrow("Timed out waiting for snapshot snapshot-stalled");
+ fakeClient.emitMessage({
+ type: "session_snapshot_begin",
+ activeSessionId: "active-1",
+ snapshotId: "snapshot-stalled",
+ snapshot: createAttachResult("active-1", "client-1", undefined, 12).snapshot,
+ messageCount: 0,
+ targetChunkBytes: 512 * 1024,
+ });
+ fakeClient.emitMessage({
+ type: "session_snapshot_end",
+ activeSessionId: "active-1",
+ snapshotId: "snapshot-stalled",
+ chunkCount: 0,
+ lastEventSequence: 12,
+ });
+ expect((connection as unknown as { snapshotAssemblies: Map<string, unknown> }).snapshotAssemblies.size).toBe(0);
+ });
+
+ it("assembles chunked attach snapshots even when chunks arrive before the attach response continuation", async () => {
+ const fakeClient = new FakeDaemonClient();
+ const messages: AgentMessage[] = [
+ { role: "user", content: "first", timestamp: 1 },
+ { role: "user", content: "second", timestamp: 2 },
+ ];
+ fakeClient.attachResultFactory = (command) => {
+ const full = createAttachResult(command.activeSessionId, command.clientId, command.capabilities, 23, {
+ state: createConnectionState(command.activeSessionId, "session-streamed"),
+ messages,
+ });
+ const { messages: _messages, ...snapshotHeader } = full.snapshot;
+ queueMicrotask(() => {
+ fakeClient.emitMessage({
+ type: "session_snapshot_begin",
+ activeSessionId: command.activeSessionId,
+ snapshotId: "snapshot-streamed",
+ snapshot: snapshotHeader,
+ messageCount: messages.length,
+ targetChunkBytes: 512 * 1024,
+ });
+ fakeClient.emitMessage({
+ type: "session_snapshot_chunk",
+ activeSessionId: command.activeSessionId,
+ snapshotId: "snapshot-streamed",
+ index: 0,
+ messages: [messages[0]!],
+ });
+ fakeClient.emitMessage({
+ type: "session_snapshot_chunk",
+ activeSessionId: command.activeSessionId,
+ snapshotId: "snapshot-streamed",
+ index: 1,
+ messages: [messages[1]!],
+ });
+ fakeClient.emitMessage({
+ type: "session_snapshot_end",
+ activeSessionId: command.activeSessionId,
+ snapshotId: "snapshot-streamed",
+ chunkCount: 2,
+ lastEventSequence: 23,
+ });
+ });
+ return {
+ ...full,
+ snapshot: { ...full.snapshot, messages: [] },
+ snapshotStream: {
+ id: "snapshot-streamed",
+ messageCount: messages.length,
+ targetChunkBytes: 512 * 1024,
+ },
+ };
+ };
+ const connection = new DaemonAgentConnection(asDaemonClient(fakeClient), "active-1");
+ const events: AgentConnectionEvent[] = [];
+ connection.subscribe((event) => {
+ events.push(event);
+ });
+
+ await connection.attach();
+
+ await expect(connection.getInitialSnapshot()).resolves.toMatchObject({
+ state: { sessionId: "session-streamed" },
+ messages,
+ lastEventSequence: 23,
+ });
+ expect(events).toEqual([]);
+ });
+
+ it("distinguishes chunked catch-up snapshots from runtime replacements", async () => {
+ const fakeClient = new FakeDaemonClient();
+ const connection = new DaemonAgentConnection(asDaemonClient(fakeClient), "active-1");
+ await connection.attach();
+ const events: AgentConnectionEvent[] = [];
+ connection.subscribe((event) => {
+ events.push(event);
+ });
+
+ const emitSnapshot = (
+ purpose: "replacement" | "resync",
+ snapshotId: string,
+ sequence: number,
+ sessionId: string,
+ ) => {
+ const messages: AgentMessage[] = [{ role: "user", content: purpose, timestamp: sequence }];
+ const full = createAttachResult("active-1", "client-1", undefined, sequence, {
+ state: createConnectionState("active-1", sessionId),
+ messages,
+ });
+ const { messages: _messages, ...snapshot } = full.snapshot;
+ fakeClient.emitMessage({
+ type: "session_snapshot_begin",
+ activeSessionId: "active-1",
+ snapshotId,
+ snapshot,
+ messageCount: messages.length,
+ targetChunkBytes: 512 * 1024,
+ purpose,
+ });
+ fakeClient.emitMessage({
+ type: "session_snapshot_chunk",
+ activeSessionId: "active-1",
+ snapshotId,
+ index: 0,
+ messages,
+ });
+ fakeClient.emitMessage({
+ type: "session_snapshot_end",
+ activeSessionId: "active-1",
+ snapshotId,
+ chunkCount: 1,
+ lastEventSequence: sequence,
+ lastEventCursor: { generation: "generation-active-1", sequence },
+ });
+ };
+
+ emitSnapshot("resync", "snapshot-resync", 13, "session-current");
+ emitSnapshot("replacement", "snapshot-replacement", 14, "session-next");
+ await vi.waitFor(() => expect(events).toHaveLength(2));
+
+ expect(events).toEqual([
+ expect.objectContaining({
+ type: "session_resynced",
+ snapshot: expect.objectContaining({
+ state: expect.objectContaining({ sessionId: "session-current" }),
+ }),
+ }),
+ expect.objectContaining({
+ type: "session_replaced",
+ state: expect.objectContaining({ sessionId: "session-next" }),
+ }),
+ ]);
+ expect((connection as unknown as { snapshotAssemblies: Map<string, unknown> }).snapshotAssemblies.size).toBe(0);
+ });
+
it("keeps attach snapshots usable when the daemon omits duplicate session context", async () => {
const fakeClient = new FakeDaemonClient();
const messages: AgentMessage[] = [{ role: "user", content: "snapshot prompt", timestamp: 1 }];
@@ -1147,10 +1473,11 @@ describe("DaemonAgentConnection", () => {
expect(fakeClient.requests.at(-1)).toMatchObject({
type: "attach",
activeSessionId: "active-1",
- capabilities: ["attach_snapshot", "event_sequence", "extension_ui", "slim_attach"],
+ capabilities: ["attach_snapshot", "event_sequence", "extension_ui", "slim_attach", "chunked_snapshot"],
resumeCursor: {
activeSessionId: "active-1",
- eventSequence: 14,
+ generation: "generation-active-1",
+ sequence: 14,
},
});
await expect(connection.getInitialSnapshot()).resolves.toMatchObject({
@@ -1173,6 +1500,83 @@ describe("DaemonAgentConnection", () => {
expect(fakeClient.requests.map((request) => request.type)).toEqual(["attach", "attach"]);
});
+ it("resets a connected transport when reattach fails during supervisor recovery", async () => {
+ const fakeClient = new FakeDaemonClient();
+ const recoverDaemon = vi.fn(async () => undefined);
+ const connection = new DaemonAgentConnection(asDaemonClient(fakeClient), "active-1", {
+ recoverDaemon,
+ reconnectTimeoutMs: 2000,
+ });
+ const statuses: string[] = [];
+ connection.subscribe((event) => {
+ if (event.type === "connection_status") {
+ statuses.push(event.status);
+ }
+ });
+ await connection.attach();
+
+ fakeClient.attachFailures = 1;
+ fakeClient.connected = false;
+ fakeClient.emitClose(new Error("Daemon socket closed"));
+
+ await vi.waitFor(() => expect(statuses).toEqual(["reconnecting", "connected"]));
+ expect(recoverDaemon).toHaveBeenCalledTimes(2);
+ expect(fakeClient.reconnectCount).toBe(2);
+ expect(fakeClient.resetTransportCount).toBe(1);
+ expect(fakeClient.requests.filter((request) => request.type === "attach")).toHaveLength(3);
+ });
+
+ it("does not reconnect after disposal while daemon recovery is pending", async () => {
+ const fakeClient = new FakeDaemonClient();
+ let finishRecovery: (() => void) | undefined;
+ const recoverDaemon = vi.fn(
+ () =>
+ new Promise<void>((resolve) => {
+ finishRecovery = resolve;
+ }),
+ );
+ const connection = new DaemonAgentConnection(asDaemonClient(fakeClient), "active-1", {
+ recoverDaemon,
+ reconnectTimeoutMs: 2000,
+ });
+ await connection.attach();
+
+ fakeClient.connected = false;
+ fakeClient.emitClose(new Error("Daemon socket closed"));
+ await vi.waitFor(() => expect(recoverDaemon).toHaveBeenCalledOnce());
+ await connection.dispose();
+ finishRecovery?.();
+ for (let flush = 0; flush < 5; flush++) {
+ await Promise.resolve();
+ }
+
+ expect(fakeClient.reconnectCount).toBe(0);
+ });
+
+ it("isolates subscriber failures during transport recovery", async () => {
+ const fakeClient = new FakeDaemonClient();
+ const connection = new DaemonAgentConnection(asDaemonClient(fakeClient), "active-1", {
+ recoverDaemon: async () => undefined,
+ reconnectTimeoutMs: 2000,
+ });
+ const statuses: string[] = [];
+ connection.subscribe(async () => {
+ throw new Error("broken subscriber");
+ });
+ connection.subscribe((event) => {
+ if (event.type === "connection_status") {
+ statuses.push(event.status);
+ }
+ });
+ await connection.attach();
+
+ fakeClient.connected = false;
+ fakeClient.emitClose(new Error("Daemon socket closed"));
+
+ await vi.waitFor(() => expect(statuses).toEqual(["reconnecting", "connected"]));
+ expect(fakeClient.reconnectCount).toBe(1);
+ });
+
it("refreshes initial snapshots after live events make the cached snapshot stale", async () => {
const fakeClient = new FakeDaemonClient();
fakeClient.attachResultFactory = (command) =>
@@ -1509,10 +1913,11 @@ describe("DaemonAgentConnection", () => {
type: "attach",
activeSessionId: "active-1",
clientId: expect.any(String),
- capabilities: ["attach_snapshot", "event_sequence", "extension_ui", "slim_attach"],
+ capabilities: ["attach_snapshot", "event_sequence", "extension_ui", "slim_attach", "chunked_snapshot"],
resumeCursor: {
activeSessionId: "active-1",
- eventSequence: 14,
+ generation: "generation-active-1",
+ sequence: 14,
},
});
@@ -1520,14 +1925,52 @@ describe("DaemonAgentConnection", () => {
expect(fakeClient.requests.at(-1)).toMatchObject({
type: "attach",
activeSessionId: "active-1",
- capabilities: ["attach_snapshot", "event_sequence", "extension_ui", "slim_attach"],
+ capabilities: ["attach_snapshot", "event_sequence", "extension_ui", "slim_attach", "chunked_snapshot"],
resumeCursor: {
activeSessionId: "active-1",
- eventSequence: 14,
+ generation: "generation-active-1",
+ sequence: 14,
},
});
});
+ it("ignores delayed events from a retired daemon generation", async () => {
+ const fakeClient = new FakeDaemonClient();
+ const connection = new DaemonAgentConnection(asDaemonClient(fakeClient), "active-1");
+ const steeringUpdates: Array<readonly string[]> = [];
+ connection.subscribe((event) => {
+ if (event.type === "session_event" && event.event.type === "queue_update") {
+ steeringUpdates.push(event.event.steering);
+ }
+ });
+ await connection.attach();
+ const emitQueue = (generation: string, sequence: number, steering: string) => {
+ fakeClient.emitMessage({
+ type: "session_event",
+ activeSessionId: "active-1",
+ event: { type: "queue_update", steering: [steering], followUp: [] },
+ meta: {
+ id: `${generation}:${sequence}`,
+ protocol: DAEMON_PROTOCOL_INFO,
+ activeSessionId: "active-1",
+ sequence,
+ cursor: { generation, sequence },
+ emittedAt: "2026-01-01T00:00:00.000Z",
+ },
+ });
+ };
+
+ emitQueue("generation-new", 1, "new");
+ emitQueue("generation-active-1", 13, "old");
+ await vi.waitFor(() => expect(steeringUpdates).toEqual([["new"]]));
+
+ await connection.attach();
+ expect(fakeClient.requests.at(-1)).toMatchObject({
+ type: "attach",
+ resumeCursor: { generation: "generation-new", sequence: 1 },
+ });
+ });
+
it("forwards extension UI requests and responses", async () => {
const fakeClient = new FakeDaemonClient();
const connection = new DaemonAgentConnection(asDaemonClient(fakeClient), "active-1");
@@ -1541,7 +1984,7 @@ describe("DaemonAgentConnection", () => {
activeSessionId: "active-1",
supportsExtensionUi: true,
clientId: expect.any(String),
- capabilities: ["attach_snapshot", "event_sequence", "extension_ui", "slim_attach"],
+ capabilities: ["attach_snapshot", "event_sequence", "extension_ui", "slim_attach", "chunked_snapshot"],
});
fakeClient.emitMessage({
diff --git a/packages/coding-agent/test/agent-session-runtime-events.test.ts b/packages/coding-agent/test/agent-session-runtime-events.test.ts
index bbb107c64b..6e77eb2430 100644
--- a/packages/coding-agent/test/agent-session-runtime-events.test.ts
+++ b/packages/coding-agent/test/agent-session-runtime-events.test.ts
@@ -1,8 +1,8 @@
-import { existsSync, mkdirSync, rmSync } from "node:fs";
+import { existsSync, mkdirSync, readdirSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { fauxAssistantMessage, registerFauxProvider } from "@earendil-works/pi-ai";
-import { afterEach, describe, expect, it } from "vitest";
+import { afterEach, describe, expect, it, vi } from "vitest";
import {
type CreateAgentSessionRuntimeFactory,
createAgentSessionFromServices,
@@ -10,6 +10,7 @@ import {
createAgentSessionServices,
} from "../src/core/agent-session-runtime.js";
import { AuthStorage } from "../src/core/auth-storage.js";
+import { SESSION_LEASE_OWNER_ID_ENV, SESSION_LEASES_ENABLED_ENV } from "../src/core/session-lease.js";
import { SessionManager } from "../src/core/session-manager.js";
import type {
ExtensionFactory,
@@ -32,6 +33,7 @@ describe("AgentSessionRuntime session lifecycle events", () => {
while (cleanups.length > 0) {
await cleanups.pop()?.();
}
+ vi.unstubAllEnvs();
});
async function createRuntimeHost(extensionFactory: ExtensionFactory) {
@@ -183,6 +185,20 @@ describe("AgentSessionRuntime session lifecycle events", () => {
runtimeHost.setRebindSession(undefined);
});
+ it("releases a replacement lease when current-session teardown fails", async () => {
+ vi.stubEnv(SESSION_LEASES_ENABLED_ENV, "1");
+ vi.stubEnv(SESSION_LEASE_OWNER_ID_ENV, "runtime-events");
+ const { runtimeHost } = await createRuntimeHost(() => undefined);
+ runtimeHost.setBeforeSessionInvalidate(() => {
+ throw new Error("teardown failed");
+ });
+
+ await expect(runtimeHost.newSession()).rejects.toThrow("teardown failed");
+ runtimeHost.setBeforeSessionInvalidate(undefined);
+ const leaseRoot = join(runtimeHost.services.agentDir, "session-leases");
+ expect(readdirSync(leaseRoot).filter((entry) => entry.endsWith(".lock"))).toHaveLength(1);
+ });
+
it("emits session_before_fork and session_start and honors cancellation", async () => {
const events: RecordedSessionEvent[] = [];
let cancelNextFork = false;
diff --git a/packages/coding-agent/test/agents-view-missing-cwd.test.ts b/packages/coding-agent/test/agents-view-missing-cwd.test.ts
index a84ce57d02..c122551ca7 100644
--- a/packages/coding-agent/test/agents-view-missing-cwd.test.ts
+++ b/packages/coding-agent/test/agents-view-missing-cwd.test.ts
@@ -1,9 +1,10 @@
import { mkdirSync, mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
-import { describe, expect, it } from "vitest";
+import { describe, expect, it, vi } from "vitest";
import { createAgentSessionRuntime } from "../src/core/agent-session-runtime.js";
import { MissingSessionCwdError } from "../src/core/session-cwd.js";
+import { SessionLease } from "../src/core/session-lease.js";
import { SessionManager } from "../src/core/session-manager.js";
import { createAgentsViewResumeConfig, resolveAgentsViewOpenCwd } from "../src/modes/agents-view/agents-view-mode.js";
import type { SessionSummary } from "../src/modes/daemon/daemon-session-list.js";
@@ -31,13 +32,17 @@ describe("agents view open with a missing session cwd", () => {
// With cwd stripped, the session resolves against its deleted cwd and throws.
const stripped = await SessionManager.openAsync(sessionFile, sessionDir);
+ const suppliedLease = new SessionLease(sessionFile, join(root, "missing-cwd-lease"), "lease-token");
+ const releaseLease = vi.spyOn(suppliedLease, "release");
await expect(
createAgentSessionRuntime(factory, {
cwd: stripped.getCwd(),
agentDir,
sessionManager: stripped,
+ sessionLease: suppliedLease,
}),
).rejects.toThrowError(MissingSessionCwdError);
+ expect(releaseLease).toHaveBeenCalledOnce();
const summary: SessionSummary = {
id: session.getSessionId(),
diff --git a/packages/coding-agent/test/child-agent-summary-list.test.ts b/packages/coding-agent/test/child-agent-summary-list.test.ts
index 215c6a41f3..e1f4859536 100644
--- a/packages/coding-agent/test/child-agent-summary-list.test.ts
+++ b/packages/coding-agent/test/child-agent-summary-list.test.ts
@@ -4,7 +4,7 @@ import {
type ChildAgentInspectorNode,
ChildAgentSummaryComponent,
} from "../src/modes/interactive/components/child-agent-inspector.js";
-import { initTheme } from "../src/modes/interactive/theme/theme.js";
+import { initTheme, theme } from "../src/modes/interactive/theme/theme.js";
import { setWorkingPulseFrame, workingIconFrame } from "../src/modes/interactive/theme/working-icon.js";
function stripAnsi(text: string): string {
@@ -39,6 +39,38 @@ describe("ChildAgentSummaryComponent inline list", () => {
expect(lines.join("\n")).toContain("2 below");
});
+ it("keeps the active agents visible when a previously selected agent finishes", () => {
+ const summary = new ChildAgentSummaryComponent();
+ summary.setNodes([node("a"), node("b"), node("c"), node("d"), node("e"), node("f")]);
+ summary.selectNode("a");
+ summary.setNodes([node("a", "done"), node("b"), node("c"), node("d"), node("e"), node("f")]);
+ const out = summary.render(80).map(stripAnsi).join("\n");
+ expect(out).toContain("b");
+ expect(out).toContain("f");
+ expect(out).not.toContain(" a ");
+ });
+
+ it("shows tool and token usage beside each subagent", () => {
+ const summary = new ChildAgentSummaryComponent();
+ summary.setNodes([{ ...node("a"), toolUseCount: 3, tokenCount: 41_000 }]);
+ const out = stripAnsi(summary.render(80).join("\n"));
+ expect(out).toContain("3 tools");
+ expect(out).toContain("41k tok");
+ });
+
+ it("shows recaps in a fixed column and falls back to activity", () => {
+ const summary = new ChildAgentSummaryComponent();
+ summary.setNodes([
+ { ...node("short"), recap: "Inspecting the scheduler queue" },
+ { ...node("a much longer starting prompt"), activity: { kind: "executing", toolName: "ipython" } },
+ ]);
+ const lines = summary.render(100).map(stripAnsi);
+ expect(lines.join("\n")).toContain("Inspecting the scheduler queue");
+ expect(lines.join("\n")).toContain("Executing ipython");
+ expect(lines[0]?.indexOf("Inspecting")).toBe(lines[1]?.indexOf("Executing"));
+ expect(lines.join("\n")).not.toContain("│");
+ });
+
it("scrolls the window and updates the indicator as selection moves down", () => {
const summary = new ChildAgentSummaryComponent();
summary.focused = true;
@@ -77,18 +109,77 @@ describe("ChildAgentSummaryComponent inline list", () => {
expect(opened).toBe("c");
});
- it("prefixes rows with a fixed-width Subagent N column", () => {
+ it("uses compact fixed-width S-number labels", () => {
const summary = new ChildAgentSummaryComponent();
summary.setNodes([node("first task"), node("second task")]);
const out = stripAnsi(summary.render(80).join("\n"));
- expect(out).toContain("Subagent 1");
- expect(out).toContain("Subagent 2");
+ expect(out).toContain("S1");
+ expect(out).toContain("S2");
+ expect(out).not.toContain("Subagent");
+ expect(out).not.toContain("↳");
+ });
+
+ it("aligns the row icon and label with the agents-view tray hint", () => {
+ const summary = new ChildAgentSummaryComponent(() => "← agents view");
+ summary.setNodes([node("task", "done")]);
+ const [infoLine = "", row = ""] = summary.render(80).map(stripAnsi);
+ expect(row.indexOf("✓")).toBe(infoLine.indexOf("←"));
+ expect(row.indexOf("S1")).toBe(infoLine.indexOf("agents"));
+ });
+
+ it("keeps truncation ellipses in the prompt color", () => {
+ const summary = new ChildAgentSummaryComponent();
+ summary.setNodes([{ ...node("a"), label: "A starting prompt that is much too long for its fixed column" }]);
+ const out = summary.render(80).join("\n");
+ const ellipsisIndex = out.indexOf("…");
+ const beforeEllipsis = out.slice(0, ellipsisIndex);
+ const dimStart = theme.fg("dim", "").replace("\x1b[39m", "");
+ expect(ellipsisIndex).toBeGreaterThan(0);
+ expect(beforeEllipsis.lastIndexOf(dimStart)).toBeGreaterThan(beforeEllipsis.lastIndexOf("\x1b[39m"));
+ expect(out[ellipsisIndex - 1]).not.toBe(" ");
+ });
+
+ it("keeps the selected background active across the entire row", () => {
+ const summary = new ChildAgentSummaryComponent();
+ summary.focused = true;
+ summary.setNodes([
+ {
+ ...node("a"),
+ label: "A starting prompt that is much too long for its fixed column",
+ recap: "A recap that is also much too long for its fixed column and must be truncated",
+ toolUseCount: 3,
+ tokenCount: 41_000,
+ durationMs: 5_000,
+ },
+ ]);
+ const [line] = summary.render(80);
+ const backgroundStart = theme.bg("selectedBg", "").replace("\x1b[49m", "");
+ expect(line?.startsWith(backgroundStart)).toBe(true);
+ expect(line?.endsWith("\x1b[49m")).toBe(true);
+ expect(line).not.toContain("\x1b[0m");
+ });
+
+ it("adds extra space between token count and duration", () => {
+ const summary = new ChildAgentSummaryComponent();
+ summary.setNodes([{ ...node("a"), tokenCount: 41_000, durationMs: 5_000 }]);
+ const out = stripAnsi(summary.render(80).join("\n"));
+ expect(out).toMatch(/41k tok\s{3}5s/);
+ });
+
+ it("keeps the starting prompt compact so the recap gets more room", () => {
+ const summary = new ChildAgentSummaryComponent();
+ const prompt = "Investigate every scheduler dispatch path and identify all possible starvation conditions";
+ summary.setNodes([{ ...node("a"), label: prompt, recap: "Found an unfair queue rotation" }]);
+ const out = stripAnsi(summary.render(100).join("\n"));
+ expect(out).not.toContain(prompt);
+ expect(out).toContain("Investigate every");
+ expect(out).toContain("Found an unfair queue rotation");
});
it("never exceeds the row width with wide (CJK) characters", () => {
const wide = "実行するタスクは非常に長い説明を含んでいてこれは折り返しのテストです".repeat(3);
const summary = new ChildAgentSummaryComponent();
- summary.setNodes([{ ...node("a"), label: wide }]);
+ summary.setNodes([{ ...node("a"), label: wide, recap: wide, toolUseCount: 12, tokenCount: 912_000 }]);
for (const width of [40, 60, 80]) {
for (const line of summary.render(width)) {
expect(visibleWidth(line)).toBeLessThanOrEqual(width);
@@ -116,8 +207,8 @@ describe("ChildAgentSummaryComponent inline list", () => {
{ ...node("b"), label: `${prefix}120 seconds then report done` },
]);
const out = stripAnsi(summary.render(130).join("\n"));
- expect(out).toContain("30 seconds");
- expect(out).toContain("120 seconds");
+ expect(out).toContain("exactly 30");
+ expect(out).toContain("exactly 120");
});
it("windows tightly around the diff when prompts share a head and tail", () => {
diff --git a/packages/coding-agent/test/command-recovery-journal.test.ts b/packages/coding-agent/test/command-recovery-journal.test.ts
new file mode 100644
index 0000000000..6c1686333f
--- /dev/null
+++ b/packages/coding-agent/test/command-recovery-journal.test.ts
@@ -0,0 +1,82 @@
+import { appendFileSync, mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterEach, describe, expect, it } from "vitest";
+import { CommandRecoveryJournal } from "../src/modes/daemon/command-recovery-journal.js";
+
+describe("CommandRecoveryJournal", () => {
+ const roots: string[] = [];
+
+ afterEach(() => {
+ for (const root of roots.splice(0)) {
+ rmSync(root, { recursive: true, force: true });
+ }
+ });
+
+ function createPath(): string {
+ const root = mkdtempSync(join(tmpdir(), "prime-agent-command-journal-"));
+ roots.push(root);
+ return join(root, "commands.jsonl");
+ }
+
+ it("marks received commands uncertain instead of replaying them", () => {
+ const journal = new CommandRecoveryJournal(createPath());
+ expect(journal.begin("client-a", "command-a", "prompt")).toEqual({ status: "new" });
+ expect(journal.begin("client-a", "command-a", "prompt")).toEqual({ status: "pending" });
+ });
+
+ it("does not collide when client and command ids contain separators", () => {
+ const journal = new CommandRecoveryJournal(createPath());
+ expect(journal.begin("client:a", "command", "prompt")).toEqual({ status: "new" });
+ expect(journal.begin("client", "a:command", "prompt")).toEqual({ status: "new" });
+ });
+
+ it("returns a durable stored result for a repeated idempotency key", () => {
+ const path = createPath();
+ const journal = new CommandRecoveryJournal(path);
+ journal.begin("client-a", "command-a", "prompt");
+ journal.recordResult("client-a", "command-a", {
+ id: "command-a",
+ type: "response",
+ command: "prompt",
+ success: true,
+ });
+
+ const restored = new CommandRecoveryJournal(path);
+ expect(restored.begin("client-a", "command-a", "prompt")).toEqual({
+ status: "complete",
+ response: {
+ id: "command-a",
+ type: "response",
+ command: "prompt",
+ success: true,
+ },
+ });
+ });
+
+ it("ignores a truncated final append", () => {
+ const path = createPath();
+ const journal = new CommandRecoveryJournal(path);
+ journal.begin("client-a", "command-a", "prompt");
+ appendFileSync(path, '{"version":1,"type":"result"');
+
+ const restored = new CommandRecoveryJournal(path);
+ expect(restored.begin("client-a", "command-a", "prompt")).toEqual({ status: "pending" });
+ });
+
+ it("durably removes acknowledged results", () => {
+ const path = createPath();
+ const journal = new CommandRecoveryJournal(path);
+ journal.begin("client-a", "command-a", "prompt");
+ journal.recordResult("client-a", "command-a", {
+ id: "command-a",
+ type: "response",
+ command: "prompt",
+ success: true,
+ });
+ journal.acknowledge("client-a", "command-a");
+
+ const restored = new CommandRecoveryJournal(path);
+ expect(restored.begin("client-a", "command-a", "prompt")).toEqual({ status: "new" });
+ });
+});
diff --git a/packages/coding-agent/test/compact-session-stream.test.ts b/packages/coding-agent/test/compact-session-stream.test.ts
new file mode 100644
index 0000000000..dcdd524af1
--- /dev/null
+++ b/packages/coding-agent/test/compact-session-stream.test.ts
@@ -0,0 +1,173 @@
+import type { AssistantMessage } from "@earendil-works/pi-ai";
+import { describe, expect, it } from "vitest";
+import {
+ CompactAssistantStreamReconstructor,
+ createCompactAssistantDelta,
+} from "../src/modes/daemon/compact-session-stream.js";
+import { DAEMON_PROTOCOL_INFO, type DaemonOutbound } from "../src/modes/daemon/daemon-protocol.js";
+
+function assistant(content: AssistantMessage["content"]): AssistantMessage {
+ return {
+ role: "assistant",
+ content,
+ api: "openai-completions",
+ provider: "test",
+ model: "test",
+ usage: {
+ input: 0,
+ output: 0,
+ cacheRead: 0,
+ cacheWrite: 0,
+ totalTokens: 0,
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
+ },
+ stopReason: "stop",
+ timestamp: 1,
+ };
+}
+
+describe("compact daemon assistant streaming", () => {
+ it("reconstructs the legacy full message_update from start and delta frames", () => {
+ const reconstructor = new CompactAssistantStreamReconstructor();
+ reconstructor.observe({
+ type: "session_event",
+ activeSessionId: "active-1",
+ event: { type: "message_start", message: assistant([]) },
+ });
+
+ const started = assistant([{ type: "text", text: "" }]);
+ const startFrame = createCompactAssistantDelta({
+ type: "session_event",
+ activeSessionId: "active-1",
+ event: {
+ type: "message_update",
+ message: started,
+ assistantMessageEvent: { type: "text_start", contentIndex: 0, partial: started },
+ },
+ });
+ expect(startFrame).toBeDefined();
+ expect(reconstructor.reconstruct(startFrame!)).toMatchObject({
+ event: { type: "message_update", message: { content: [{ type: "text", text: "" }] } },
+ });
+
+ const updated = assistant([{ type: "text", text: "hello" }]);
+ const deltaFrame = createCompactAssistantDelta({
+ type: "session_event",
+ activeSessionId: "active-1",
+ event: {
+ type: "message_update",
+ message: updated,
+ assistantMessageEvent: { type: "text_delta", contentIndex: 0, delta: "hello", partial: updated },
+ },
+ meta: {
+ id: "active-1:2",
+ protocol: DAEMON_PROTOCOL_INFO,
+ activeSessionId: "active-1",
+ sequence: 2,
+ cursor: { generation: "generation-1", sequence: 2 },
+ emittedAt: "2026-01-01T00:00:00.000Z",
+ },
+ });
+ if (!deltaFrame) {
+ throw new Error("Expected a compact delta frame");
+ }
+ const reconstructed = reconstructor.reconstruct(deltaFrame);
+ expect(reconstructed).toMatchObject({
+ type: "session_event",
+ activeSessionId: "active-1",
+ event: {
+ type: "message_update",
+ message: { content: [{ type: "text", text: "hello" }] },
+ assistantMessageEvent: { type: "text_delta", contentIndex: 0, delta: "hello" },
+ },
+ meta: { cursor: { generation: "generation-1", sequence: 2 } },
+ });
+ expect((reconstructed as Extract<DaemonOutbound, { type: "session_event" }>).event).not.toHaveProperty(
+ "assistantMessageEvent.partial",
+ );
+ });
+
+ it("keeps delta payload size independent of the growing assistant message", () => {
+ const text = "x".repeat(1024 * 1024);
+ const partial = assistant([{ type: "text", text }]);
+ const full: DaemonOutbound = {
+ type: "session_event",
+ activeSessionId: "active-large",
+ event: {
+ type: "message_update",
+ message: partial,
+ assistantMessageEvent: { type: "text_delta", contentIndex: 0, delta: "x", partial },
+ },
+ };
+ const compact = createCompactAssistantDelta(full);
+ expect(compact).toBeDefined();
+ expect(Buffer.byteLength(JSON.stringify(compact))).toBeLessThan(1024);
+ expect(Buffer.byteLength(JSON.stringify(full))).toBeGreaterThan(2 * 1024 * 1024);
+ });
+
+ it("does not duplicate text already present on a provider start event", () => {
+ const reconstructor = new CompactAssistantStreamReconstructor();
+ reconstructor.observe({
+ type: "session_event",
+ activeSessionId: "active-start-text",
+ event: { type: "message_start", message: assistant([]) },
+ });
+ const started = assistant([{ type: "text", text: "Hello" }]);
+ const startFrame = createCompactAssistantDelta({
+ type: "session_event",
+ activeSessionId: "active-start-text",
+ event: {
+ type: "message_update",
+ message: started,
+ assistantMessageEvent: { type: "text_start", contentIndex: 0, partial: started },
+ },
+ });
+ const deltaFrame = createCompactAssistantDelta({
+ type: "session_event",
+ activeSessionId: "active-start-text",
+ event: {
+ type: "message_update",
+ message: started,
+ assistantMessageEvent: { type: "text_delta", contentIndex: 0, delta: "Hello", partial: started },
+ },
+ });
+
+ expect(reconstructor.reconstruct(startFrame!)).toMatchObject({
+ event: { message: { content: [{ type: "text", text: "" }] } },
+ });
+ expect(reconstructor.reconstruct(deltaFrame!)).toMatchObject({
+ event: { message: { content: [{ type: "text", text: "Hello" }] } },
+ });
+ });
+
+ it("continues tool arguments after reconstructing from a snapshot", () => {
+ const reconstructor = new CompactAssistantStreamReconstructor();
+ reconstructor.seed(
+ "active-tool",
+ assistant([{ type: "toolCall", id: "tool-1", name: "search", arguments: { query: "hel" } }]),
+ );
+ const updated = assistant([{ type: "toolCall", id: "tool-1", name: "search", arguments: { query: "hello" } }]);
+ const delta = createCompactAssistantDelta({
+ type: "session_event",
+ activeSessionId: "active-tool",
+ event: {
+ type: "message_update",
+ message: updated,
+ assistantMessageEvent: {
+ type: "toolcall_delta",
+ contentIndex: 0,
+ delta: 'lo"}',
+ partial: updated,
+ },
+ },
+ });
+
+ expect(reconstructor.reconstruct(delta!)).toMatchObject({
+ event: {
+ message: {
+ content: [{ type: "toolCall", id: "tool-1", name: "search", arguments: { query: "hello" } }],
+ },
+ },
+ });
+ });
+});
diff --git a/packages/coding-agent/test/cron-jobs.test.ts b/packages/coding-agent/test/cron-jobs.test.ts
index add488b48e..f926b18bcd 100644
--- a/packages/coding-agent/test/cron-jobs.test.ts
+++ b/packages/coding-agent/test/cron-jobs.test.ts
@@ -1,4 +1,4 @@
-import { mkdtempSync, rmSync } from "node:fs";
+import { existsSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, describe, expect, it } from "vitest";
@@ -7,10 +7,12 @@ import {
AgentCronJobStore,
AgentCronScheduler,
createAgentHeartbeatToolDefinitions,
+ migrateLegacyCronJobsToSessionArtifacts,
normalizeHeartbeatDeliveryMode,
parseAgentCronSchedule,
parseHeartbeatCommand,
resolveHeartbeatStreamingBehavior,
+ SESSION_SCHEDULED_JOBS_FILENAME,
shouldDeferHeartbeatCronJob,
} from "../src/core/cron-jobs.js";
@@ -192,6 +194,139 @@ describe("AgentCronJobStore", () => {
expect(store.list()[0]).not.toHaveProperty("nextRunAt");
});
+ it("isolates worker-owned jobs in registered session artifact stores", () => {
+ const root = makeTempDir(tempDirs);
+ const firstArtifactDir = join(root, "session-artifacts", "session-1");
+ const secondArtifactDir = join(root, "session-artifacts", "session-2");
+ const store = AgentCronJobStore.forSessionArtifacts();
+ store.registerSessionArtifact("session-1", firstArtifactDir);
+ store.registerSessionArtifact("session-2", secondArtifactDir);
+ const first = store.createHeartbeat({
+ activeSessionId: "active-1",
+ sessionId: "session-1",
+ sessionFile: join(root, "sessions", "session-1.jsonl"),
+ cwd: root,
+ scheduleText: "every 5m",
+ prompt: "first heartbeat",
+ now: start,
+ });
+ const second = store.createHeartbeat({
+ activeSessionId: "active-2",
+ sessionId: "session-2",
+ sessionFile: join(root, "sessions", "session-2.jsonl"),
+ cwd: root,
+ scheduleText: "every 5m",
+ prompt: "second heartbeat",
+ now: start,
+ });
+
+ const firstOnly = AgentCronJobStore.forSessionArtifacts();
+ firstOnly.registerSessionArtifact("session-1", firstArtifactDir);
+ expect(firstOnly.list().map((job) => job.id)).toEqual([first.id]);
+ expect(firstOnly.list().map((job) => job.id)).not.toContain(second.id);
+ expect(existsSync(join(firstArtifactDir, SESSION_SCHEDULED_JOBS_FILENAME))).toBe(true);
+ expect(existsSync(join(secondArtifactDir, SESSION_SCHEDULED_JOBS_FILENAME))).toBe(true);
+ expect(join(firstArtifactDir, SESSION_SCHEDULED_JOBS_FILENAME)).not.toBe(
+ join(secondArtifactDir, SESSION_SCHEDULED_JOBS_FILENAME),
+ );
+ });
+
+ it("moves active-session jobs to the replacement session artifact store", () => {
+ const root = makeTempDir(tempDirs);
+ const firstArtifactDir = join(root, "session-artifacts", "session-1");
+ const secondArtifactDir = join(root, "session-artifacts", "session-2");
+ const store = AgentCronJobStore.forSessionArtifacts();
+ store.registerSessionArtifact("session-1", firstArtifactDir);
+ store.registerSessionArtifact("session-2", secondArtifactDir);
+ const heartbeat = store.createHeartbeat({
+ activeSessionId: "active-1",
+ sessionId: "session-1",
+ sessionFile: join(root, "sessions", "session-1.jsonl"),
+ cwd: root,
+ scheduleText: "every 5m",
+ prompt: "follow the active root",
+ now: start,
+ });
+
+ store.rebindSessionJobs({
+ activeSessionId: "active-1",
+ sessionId: "session-2",
+ sessionFile: join(root, "sessions", "session-2.jsonl"),
+ cwd: root,
+ });
+
+ const firstOnly = AgentCronJobStore.forSessionArtifacts();
+ firstOnly.registerSessionArtifact("session-1", firstArtifactDir);
+ expect(firstOnly.list()).toEqual([]);
+ const secondOnly = AgentCronJobStore.forSessionArtifacts();
+ secondOnly.registerSessionArtifact("session-2", secondArtifactDir);
+ expect(secondOnly.list()).toEqual([
+ expect.objectContaining({ id: heartbeat.id, sessionId: "session-2", activeSessionId: "active-1" }),
+ ]);
+ });
+
+ it("migrates the legacy global store into per-session artifact stores", () => {
+ const root = makeTempDir(tempDirs);
+ const legacyPath = join(root, "cron-jobs.json");
+ const legacy = new AgentCronJobStore(legacyPath);
+ const first = legacy.create({
+ activeSessionId: "active-1",
+ sessionId: "session-1",
+ sessionFile: join(root, "sessions", "session-1.jsonl"),
+ cwd: root,
+ scheduleText: "in 1h",
+ prompt: "first migrated job",
+ now: start,
+ });
+ const second = legacy.create({
+ activeSessionId: "active-2",
+ sessionId: "session-2",
+ sessionFile: join(root, "sessions", "session-2.jsonl"),
+ cwd: root,
+ scheduleText: "in 2h",
+ prompt: "second migrated job",
+ now: start,
+ });
+
+ expect(migrateLegacyCronJobsToSessionArtifacts(legacyPath)).toBe(2);
+ expect(existsSync(legacyPath)).toBe(false);
+ const migrated = AgentCronJobStore.forSessionArtifacts();
+ migrated.registerSessionArtifact("session-1", join(root, "session-artifacts", "session-1"));
+ migrated.registerSessionArtifact("session-2", join(root, "session-artifacts", "session-2"));
+ expect(migrated.list().map((job) => job.id)).toEqual(expect.arrayContaining([first.id, second.id]));
+ });
+
+ it("marks in-flight legacy dispatches interrupted during migration", () => {
+ const root = makeTempDir(tempDirs);
+ const legacyPath = join(root, "cron-jobs.json");
+ const legacy = new AgentCronJobStore(legacyPath);
+ const heartbeat = legacy.createHeartbeat({
+ activeSessionId: "active-1",
+ sessionId: "session-1",
+ sessionFile: join(root, "sessions", "session-1.jsonl"),
+ cwd: root,
+ scheduleText: "every 10s",
+ prompt: "migrated heartbeat",
+ now: start,
+ });
+ legacy.claimDue(new Date("2026-01-01T12:34:10.000Z"));
+
+ expect(
+ migrateLegacyCronJobsToSessionArtifacts(legacyPath, {
+ now: new Date("2026-01-01T12:34:11.000Z"),
+ }),
+ ).toBe(1);
+ const migrated = AgentCronJobStore.forSessionArtifacts();
+ migrated.registerSessionArtifact("session-1", join(root, "session-artifacts", "session-1"));
+ expect(migrated.list()).toEqual([
+ expect.objectContaining({
+ id: heartbeat.id,
+ lastError: "Interrupted before scheduled operation completion",
+ nextRunAt: "2026-01-01T12:34:20.000Z",
+ }),
+ ]);
+ });
+
it("keeps overdue jobs eligible for the scheduler after restart", () => {
const store = new AgentCronJobStore(makeStorePath(tempDirs));
store.create({
@@ -261,6 +396,41 @@ describe("AgentCronJobStore", () => {
});
});
+ it("preserves session-artifact dispatches when a stale snapshot is written", () => {
+ const root = makeTempDir(tempDirs);
+ const artifactDir = join(root, "session-artifacts", "session-1");
+ const artifactPath = join(artifactDir, SESSION_SCHEDULED_JOBS_FILENAME);
+ const writer = AgentCronJobStore.forSessionArtifacts();
+ const dispatcher = AgentCronJobStore.forSessionArtifacts();
+ writer.registerSessionArtifact("session-1", artifactDir);
+ dispatcher.registerSessionArtifact("session-1", artifactDir);
+ const heartbeat = writer.createHeartbeat({
+ activeSessionId: "active-1",
+ sessionId: "session-1",
+ sessionFile: join(root, "sessions", "session-1.jsonl"),
+ cwd: root,
+ scheduleText: "every 10s",
+ prompt: "check progress",
+ now: start,
+ });
+ const staleCancellation = {
+ ...heartbeat,
+ status: "cancelled" as const,
+ nextRunAt: undefined,
+ updatedAt: "2026-01-01T12:34:20.000Z",
+ };
+
+ expect(dispatcher.claimDue(new Date("2026-01-01T12:34:10.000Z"))).toHaveLength(1);
+ writeJobsForTest(writer, [staleCancellation]);
+
+ const state = JSON.parse(readFileSync(artifactPath, "utf8")) as {
+ jobs: AgentCronJob[];
+ dispatches: Array<{ jobId: string }>;
+ };
+ expect(state.jobs).toContainEqual(expect.objectContaining({ id: heartbeat.id, status: "cancelled" }));
+ expect(state.dispatches).toContainEqual(expect.objectContaining({ jobId: heartbeat.id }));
+ });
+
it("keeps one persistent heartbeat per active session", () => {
const store = new AgentCronJobStore(makeStorePath(tempDirs));
const first = store.createHeartbeat({
@@ -940,6 +1110,151 @@ describe("AgentCronScheduler", () => {
]),
);
});
+
+ it("dispatches different sessions concurrently and advances their schedules before completion", async () => {
+ const store = new AgentCronJobStore(makeStorePath(tempDirs));
+ for (const index of [1, 2]) {
+ store.createHeartbeat({
+ activeSessionId: `active-${index}`,
+ sessionId: `session-${index}`,
+ sessionFile: `/tmp/session-${index}.jsonl`,
+ cwd: "/tmp/project",
+ scheduleText: "every 10s",
+ prompt: `heartbeat ${index}`,
+ now: start,
+ });
+ }
+ const started: string[] = [];
+ const releases = new Map<string, () => void>();
+ const scheduler = new AgentCronScheduler(store, {
+ now: () => new Date("2026-01-01T12:34:10.000Z"),
+ runJob: async (job) => {
+ started.push(job.activeSessionId);
+ await new Promise<void>((resolve) => releases.set(job.activeSessionId, resolve));
+ return undefined;
+ },
+ });
+
+ const run = scheduler.runDue(new Date("2026-01-01T12:34:10.000Z"));
+ await new Promise<void>((resolve) => setImmediate(resolve));
+
+ expect(started).toEqual(expect.arrayContaining(["active-1", "active-2"]));
+ expect(store.list().map((job) => job.nextRunAt)).toEqual([
+ "2026-01-01T12:34:20.000Z",
+ "2026-01-01T12:34:20.000Z",
+ ]);
+ for (const release of releases.values()) {
+ release();
+ }
+ await run;
+ });
+
+ it("serializes simultaneous jobs that target the same session", async () => {
+ const store = new AgentCronJobStore(makeStorePath(tempDirs));
+ for (const prompt of ["first", "second"]) {
+ store.create({
+ activeSessionId: "active-1",
+ sessionId: "session-1",
+ sessionFile: "/tmp/session.jsonl",
+ cwd: "/tmp/project",
+ scheduleText: "in 1m",
+ prompt,
+ now: start,
+ });
+ }
+ const started: string[] = [];
+ let releaseFirst: () => void = () => {};
+ const scheduler = new AgentCronScheduler(store, {
+ now: () => new Date("2026-01-01T12:35:00.000Z"),
+ runJob: async (job) => {
+ started.push(job.prompt);
+ if (job.prompt === "first") {
+ await new Promise<void>((resolve) => {
+ releaseFirst = resolve;
+ });
+ }
+ return undefined;
+ },
+ });
+
+ const run = scheduler.runDue(new Date("2026-01-01T12:35:00.000Z"));
+ await new Promise<void>((resolve) => setImmediate(resolve));
+ expect(started).toEqual(["first"]);
+ releaseFirst();
+ await run;
+ expect(started).toEqual(["first", "second"]);
+ });
+
+ it("coalesces a missed interval while its previous dispatch is still active", () => {
+ const store = new AgentCronJobStore(makeStorePath(tempDirs));
+ const heartbeat = store.createHeartbeat({
+ activeSessionId: "active-1",
+ sessionId: "session-1",
+ sessionFile: "/tmp/session.jsonl",
+ cwd: "/tmp/project",
+ scheduleText: "every 10s",
+ prompt: "check progress",
+ now: start,
+ });
+
+ expect(store.claimDue(new Date("2026-01-01T12:34:10.000Z"))).toHaveLength(1);
+ expect(store.claimDue(new Date("2026-01-01T12:34:20.000Z"))).toEqual([]);
+ expect(store.list().find((job) => job.id === heartbeat.id)).toMatchObject({
+ nextRunAt: "2026-01-01T12:34:30.000Z",
+ lastSkippedAt: "2026-01-01T12:34:20.000Z",
+ runCount: 0,
+ });
+ });
+
+ it("reschedules a skipped dispatch from the skip time", () => {
+ const store = new AgentCronJobStore(makeStorePath(tempDirs));
+ const heartbeat = store.createHeartbeat({
+ activeSessionId: "active-1",
+ sessionId: "session-1",
+ sessionFile: "/tmp/session.jsonl",
+ cwd: "/tmp/project",
+ scheduleText: "every 10s",
+ prompt: "check progress",
+ now: start,
+ });
+ const [dispatch] = store.claimDue(new Date("2026-01-01T12:34:10.000Z"));
+ if (!dispatch) {
+ throw new Error("Expected heartbeat dispatch");
+ }
+
+ store.recordDispatchResult(dispatch.id, {
+ now: new Date("2026-01-01T12:34:17.000Z"),
+ outcome: "skipped",
+ });
+
+ expect(store.list().find((job) => job.id === heartbeat.id)).toMatchObject({
+ nextRunAt: "2026-01-01T12:34:27.000Z",
+ lastSkippedAt: "2026-01-01T12:34:17.000Z",
+ runCount: 0,
+ });
+ });
+
+ it("does not replay an uncertain claimed dispatch after recovery", () => {
+ const storePath = makeStorePath(tempDirs);
+ const store = new AgentCronJobStore(storePath);
+ const heartbeat = store.createHeartbeat({
+ activeSessionId: "active-1",
+ sessionId: "session-1",
+ sessionFile: "/tmp/session.jsonl",
+ cwd: "/tmp/project",
+ scheduleText: "every 10s",
+ prompt: "check progress",
+ now: start,
+ });
+ store.claimDue(new Date("2026-01-01T12:34:10.000Z"));
+
+ const recovered = new AgentCronJobStore(storePath);
+ expect(recovered.recoverInterruptedDispatches(new Date("2026-01-01T12:34:11.000Z"))).toEqual([
+ expect.objectContaining({ id: heartbeat.id, lastError: "Interrupted before scheduled operation completion" }),
+ ]);
+ expect(recovered.getClaimedJob(heartbeat.id)).toBeUndefined();
+ expect(recovered.getDueJob(heartbeat.id, new Date("2026-01-01T12:34:11.000Z"))).toBeUndefined();
+ });
});
describe("shouldDeferHeartbeatCronJob", () => {
@@ -1132,7 +1447,12 @@ function writeJobsForTest(store: AgentCronJobStore, jobs: readonly AgentCronJob[
}
function makeStorePath(tempDirs: string[]): string {
+ const dir = makeTempDir(tempDirs);
+ return join(dir, "cron-jobs.json");
+}
+
+function makeTempDir(tempDirs: string[]): string {
const dir = mkdtempSync(join(tmpdir(), "prime-agent-cron-"));
tempDirs.push(dir);
- return join(dir, "cron-jobs.json");
+ return dir;
}
diff --git a/packages/coding-agent/test/daemon-client.test.ts b/packages/coding-agent/test/daemon-client.test.ts
index 507b95a874..15be3b12c6 100644
--- a/packages/coding-agent/test/daemon-client.test.ts
+++ b/packages/coding-agent/test/daemon-client.test.ts
@@ -85,6 +85,20 @@ vi.mock("node:net", () => ({
createConnection: netMock.createConnection,
}));
+function emitHello(socket: (typeof netMock.sockets)[number], version = 2): void {
+ socket.emit(
+ "data",
+ `${JSON.stringify({
+ type: "daemon_hello",
+ socketPath: "/tmp/prime-agent.sock",
+ protocol: { name: "prime-agent.daemon", version },
+ appVersion: "9.9.9",
+ clientId: "client-1",
+ serverCapabilities: [],
+ })}\n`,
+ );
+}
+
describe("DaemonClient", () => {
beforeEach(() => {
netMock.sockets.length = 0;
@@ -184,24 +198,31 @@ describe("DaemonClient", () => {
const socket = netMock.sockets[0]!;
socket.emit("connect");
await connect;
+ emitHello(socket);
const response = client.request({ type: "attach", activeSessionId: "active-1" });
expect(socket.writes).toHaveLength(1);
- const command = JSON.parse(socket.writes[0]!.trim()) as {
+ const envelope = JSON.parse(socket.writes[0]!.trim()) as {
id?: string;
type?: string;
- activeSessionId?: string;
- daemonSessionId?: unknown;
+ clientId?: string;
+ protocol?: { name?: string; version?: number };
+ command?: { type?: string; activeSessionId?: string; daemonSessionId?: unknown };
};
- expect(command).toMatchObject({ type: "attach", activeSessionId: "active-1" });
- expect(command).not.toHaveProperty("daemonSessionId");
+ expect(envelope).toMatchObject({
+ type: "command",
+ clientId: expect.any(String),
+ protocol: { name: "prime-agent.daemon", version: 2 },
+ command: { type: "attach", activeSessionId: "active-1" },
+ });
+ expect(envelope.command).not.toHaveProperty("daemonSessionId");
socket.emit(
"data",
- `${JSON.stringify({ id: command.id, type: "response", command: "attach", success: true })}\n`,
+ `${JSON.stringify({ id: envelope.id, type: "response", command: "attach", success: true })}\n`,
);
- await expect(response).resolves.toMatchObject({ id: command.id, success: true });
+ await expect(response).resolves.toMatchObject({ id: envelope.id, success: true });
client.close();
});
@@ -214,19 +235,20 @@ describe("DaemonClient", () => {
const socket = netMock.sockets[0]!;
socket.emit("connect");
await connect;
+ emitHello(socket);
const response = client.request({ type: "list", all: true });
expect(socket.writes).toHaveLength(1);
- const command = JSON.parse(socket.writes[0]!.trim()) as {
+ const envelope = JSON.parse(socket.writes[0]!.trim()) as {
id?: string;
type?: string;
- all?: boolean;
+ command?: { type?: string; all?: boolean };
};
- expect(command).toMatchObject({ type: "list", all: true });
+ expect(envelope).toMatchObject({ type: "command", command: { type: "list", all: true } });
- socket.emit("data", `${JSON.stringify({ id: command.id, type: "response", command: "list", success: true })}\n`);
- await expect(response).resolves.toMatchObject({ id: command.id, success: true });
+ socket.emit("data", `${JSON.stringify({ id: envelope.id, type: "response", command: "list", success: true })}\n`);
+ await expect(response).resolves.toMatchObject({ id: envelope.id, success: true });
client.close();
});
@@ -249,6 +271,45 @@ describe("DaemonClient", () => {
});
});
+ it("keeps a raw one-release request path for v1 daemon handoff", async () => {
+ const client = new DaemonClient("/tmp/prime-agent.sock");
+ const connect = client.connect();
+ const socket = netMock.sockets[0]!;
+ socket.emit("connect");
+ await connect;
+
+ const response = client.requestLegacy({ type: "prepare_update_restart" });
+ const command = JSON.parse(socket.writes[0]!.trim()) as { id: string; type: string };
+ expect(command.type).toBe("prepare_update_restart");
+ expect(command).not.toHaveProperty("protocol");
+ socket.emit(
+ "data",
+ `${JSON.stringify({ id: command.id, type: "response", command: command.type, success: true })}\n`,
+ );
+ await expect(response).resolves.toMatchObject({ success: true });
+ client.close();
+ });
+
+ it("uses legacy framing automatically after a v1 daemon hello", async () => {
+ const client = new DaemonClient("/tmp/prime-agent.sock");
+ const connect = client.connect();
+ const socket = netMock.sockets[0]!;
+ socket.emit("connect");
+ await connect;
+ emitHello(socket, 1);
+
+ const response = client.request({ type: "create" });
+ const command = JSON.parse(socket.writes[0]!.trim()) as { id: string; type: string };
+ expect(command.type).toBe("create");
+ expect(command).not.toHaveProperty("protocol");
+ socket.emit(
+ "data",
+ `${JSON.stringify({ id: command.id, type: "response", command: command.type, success: true })}\n`,
+ );
+ await expect(response).resolves.toMatchObject({ success: true });
+ client.close();
+ });
+
it("routes request progress by response id without notifying general listeners", async () => {
const client = new DaemonClient("/tmp/prime-agent.sock");
@@ -257,6 +318,7 @@ describe("DaemonClient", () => {
const socket = netMock.sockets[0]!;
socket.emit("connect");
await connect;
+ emitHello(socket);
const progress: Array<[number, number]> = [];
const discovered: string[] = [];
@@ -280,17 +342,16 @@ describe("DaemonClient", () => {
},
);
expect(socket.writes).toHaveLength(1);
- const command = JSON.parse(socket.writes[0]!.trim()) as {
+ const envelope = JSON.parse(socket.writes[0]!.trim()) as {
id?: string;
type?: string;
- activeSessionId?: string;
- scope?: string;
+ command?: { activeSessionId?: string; scope?: string };
};
socket.emit(
"data",
`${JSON.stringify({
- id: command.id,
+ id: envelope.id,
type: "session_list_progress",
command: "list_saved_sessions",
activeSessionId: "active-1",
@@ -301,7 +362,7 @@ describe("DaemonClient", () => {
socket.emit(
"data",
`${JSON.stringify({
- id: command.id,
+ id: envelope.id,
type: "session_list_item",
command: "list_saved_sessions",
activeSessionId: "active-1",
@@ -325,7 +386,7 @@ describe("DaemonClient", () => {
socket.emit(
"data",
`${JSON.stringify({
- id: command.id,
+ id: envelope.id,
type: "response",
command: "list_saved_sessions",
success: true,
@@ -333,7 +394,7 @@ describe("DaemonClient", () => {
})}\n`,
);
- await expect(response).resolves.toMatchObject({ id: command.id, success: true });
+ await expect(response).resolves.toMatchObject({ id: envelope.id, success: true });
expect(progress).toEqual([[1, 2]]);
expect(discovered).toEqual(["session-a"]);
expect(discoveredStatus).toEqual({
@@ -355,6 +416,7 @@ describe("DaemonClient", () => {
const socket = netMock.sockets[0]!;
socket.emit("connect");
await connect;
+ emitHello(socket);
const response = client.request({
type: "create",
@@ -366,37 +428,67 @@ describe("DaemonClient", () => {
},
});
expect(socket.writes).toHaveLength(1);
- const command = JSON.parse(socket.writes[0]!.trim()) as {
+ const envelope = JSON.parse(socket.writes[0]!.trim()) as {
id?: string;
type?: string;
- name?: string;
- config?: {
- cwd?: string;
- model?: string;
- tools?: string[];
+ command?: {
+ type?: string;
+ name?: string;
+ config?: {
+ cwd?: string;
+ model?: string;
+ tools?: string[];
+ };
+ cwd?: unknown;
+ model?: unknown;
};
- cwd?: unknown;
- model?: unknown;
};
- expect(command).toMatchObject({
- type: "create",
- name: "configured",
- config: {
- cwd: "/tmp/project",
- model: "openai/gpt-4o-mini",
- tools: ["bash"],
+ expect(envelope).toMatchObject({
+ type: "command",
+ command: {
+ type: "create",
+ name: "configured",
+ config: {
+ cwd: "/tmp/project",
+ model: "openai/gpt-4o-mini",
+ tools: ["bash"],
+ },
},
});
- expect(command).not.toHaveProperty("cwd");
- expect(command).not.toHaveProperty("model");
+ expect(envelope.command).not.toHaveProperty("cwd");
+ expect(envelope.command).not.toHaveProperty("model");
+
+ socket.emit(
+ "data",
+ `${JSON.stringify({ id: envelope.id, type: "response", command: "create", success: true })}\n`,
+ );
+ await expect(response).resolves.toMatchObject({ id: envelope.id, success: true });
+
+ client.close();
+ });
+
+ it("acknowledges durable mutating-command results on protocol v2", async () => {
+ const client = new DaemonClient("/tmp/prime-agent.sock");
+ const connect = client.connect();
+ const socket = netMock.sockets[0]!;
+ socket.emit("connect");
+ await connect;
+ emitHello(socket);
+ const response = client.request({ type: "create" });
+ const request = JSON.parse(socket.writes[0]!.trim()) as { id: string };
socket.emit(
"data",
- `${JSON.stringify({ id: command.id, type: "response", command: "create", success: true })}\n`,
+ `${JSON.stringify({ id: request.id, type: "response", command: "create", success: true })}\n`,
);
- await expect(response).resolves.toMatchObject({ id: command.id, success: true });
+ await response;
+ expect(socket.writes).toHaveLength(2);
+ expect(JSON.parse(socket.writes[1]!.trim())).toMatchObject({
+ type: "command",
+ command: { type: "ack_result", commandId: request.id },
+ });
client.close();
});
@@ -507,7 +599,6 @@ describe("DaemonClient", () => {
it("shares one reconnect attempt across concurrent callers", async () => {
const client = new DaemonClient("/tmp/prime-agent.sock");
-
const firstConnect = client.connect();
const firstSocket = netMock.sockets[0]!;
firstSocket.emit("connect");
@@ -523,6 +614,130 @@ describe("DaemonClient", () => {
await expect(Promise.all([reconnectA, reconnectB])).resolves.toEqual([undefined, undefined]);
client.close();
});
+
+ it("resends the same command envelope after a recoverable disconnect", async () => {
+ const client = new DaemonClient("/tmp/prime-agent.sock");
+ client.enableRequestRecovery();
+ const firstConnect = client.connect();
+ const firstSocket = netMock.sockets[0]!;
+ firstSocket.emit("connect");
+ await firstConnect;
+ emitHello(firstSocket);
+
+ const response = client.request({ type: "prompt", activeSessionId: "active-1", message: "hello" });
+ const firstWireData = firstSocket.writes[0]!;
+ const firstEnvelope = JSON.parse(firstWireData) as { id: string };
+ firstSocket.emit("close");
+
+ const secondConnect = client.connect();
+ const secondSocket = netMock.sockets[1]!;
+ secondSocket.emit("connect");
+ await secondConnect;
+ expect(secondSocket.writes).toEqual([]);
+ secondSocket.emit(
+ "data",
+ `${JSON.stringify({
+ type: "daemon_hello",
+ socketPath: "/tmp/prime-agent.sock",
+ protocol: { name: "prime-agent.daemon", version: 2 },
+ clientId: "server-client-2",
+ serverCapabilities: [],
+ })}\n`,
+ );
+ expect(secondSocket.writes).toEqual([firstWireData]);
+
+ secondSocket.emit(
+ "data",
+ `${JSON.stringify({ id: firstEnvelope.id, type: "response", command: "prompt", success: true })}\n`,
+ );
+ await expect(response).resolves.toMatchObject({ id: firstEnvelope.id, success: true });
+ client.close();
+ });
+
+ it("pauses request timeouts while a recoverable connection is disconnected", async () => {
+ vi.useFakeTimers();
+ const client = new DaemonClient("/tmp/prime-agent.sock");
+ client.enableRequestRecovery();
+ const firstConnect = client.connect();
+ const firstSocket = netMock.sockets[0]!;
+ firstSocket.emit("connect");
+ await firstConnect;
+ emitHello(firstSocket);
+
+ const response = client.request({ type: "list" }, 50);
+ let settled = false;
+ void response.then(
+ () => {
+ settled = true;
+ },
+ () => {
+ settled = true;
+ },
+ );
+ const firstEnvelope = JSON.parse(firstSocket.writes[0]!) as { id: string };
+ firstSocket.emit("close");
+ await vi.advanceTimersByTimeAsync(500);
+ expect(settled).toBe(false);
+
+ const secondConnect = client.connect();
+ const secondSocket = netMock.sockets[1]!;
+ secondSocket.emit("connect");
+ await secondConnect;
+ emitHello(secondSocket);
+ secondSocket.emit(
+ "data",
+ `${JSON.stringify({ id: firstEnvelope.id, type: "response", command: "list", success: true })}\n`,
+ );
+
+ await expect(response).resolves.toMatchObject({ id: firstEnvelope.id, success: true });
+ client.close();
+ });
+
+ it("reconnects raw clients and replays pending commands after supervisor replacement", async () => {
+ const client = new DaemonClient("/tmp/prime-agent.sock");
+ const firstConnect = client.connect();
+ const firstSocket = netMock.sockets[0]!;
+ firstSocket.emit("connect");
+ await firstConnect;
+ emitHello(firstSocket);
+
+ const statuses: string[] = [];
+ const recoverDaemon = vi.fn(async () => {});
+ client.enableAutoReconnect({
+ recoverDaemon,
+ onStatus: (status) => statuses.push(status.status),
+ });
+ const response = client.request({ type: "list" });
+ const firstWireData = firstSocket.writes[0]!;
+ const firstEnvelope = JSON.parse(firstWireData) as { id: string };
+
+ firstSocket.emit("close");
+ await vi.waitFor(() => expect(netMock.sockets).toHaveLength(2));
+ const secondSocket = netMock.sockets[1]!;
+ secondSocket.emit("connect");
+ await Promise.resolve();
+ secondSocket.emit(
+ "data",
+ `${JSON.stringify({
+ type: "daemon_hello",
+ socketPath: "/tmp/prime-agent.sock",
+ protocol: { name: "prime-agent.daemon", version: 2 },
+ clientId: "server-client-2",
+ serverCapabilities: [],
+ })}\n`,
+ );
+
+ await vi.waitFor(() => expect(statuses).toEqual(["reconnecting", "connected"]));
+ expect(recoverDaemon).toHaveBeenCalledOnce();
+ expect(secondSocket.writes).toEqual([firstWireData]);
+
+ secondSocket.emit(
+ "data",
+ `${JSON.stringify({ id: firstEnvelope.id, type: "response", command: "list", success: true })}\n`,
+ );
+ await expect(response).resolves.toMatchObject({ id: firstEnvelope.id, success: true });
+ client.close();
+ });
});
async function captureRejection(promise: Promise<void>): Promise<Error> {
diff --git a/packages/coding-agent/test/daemon-extension-binding.test.ts b/packages/coding-agent/test/daemon-extension-binding.test.ts
index c9536d0b24..182ff24116 100644
--- a/packages/coding-agent/test/daemon-extension-binding.test.ts
+++ b/packages/coding-agent/test/daemon-extension-binding.test.ts
@@ -121,6 +121,7 @@ describe("daemon extension binding", () => {
runtime,
clients: new Set(),
extensionUiRequests: new Map(),
+ eventGeneration: "generation-slim",
lastEventSequence: 0,
};
await bindActiveSessionState(state, {
@@ -193,6 +194,7 @@ describe("daemon extension binding", () => {
runtime,
clients: new Set(),
extensionUiRequests: new Map(),
+ eventGeneration: "generation-test",
lastEventSequence: 0,
summaryState: { summary: "old recap", taskState: "completed", basedOnMessageCount: 2 },
};
diff --git a/packages/coding-agent/test/daemon-mode.test.ts b/packages/coding-agent/test/daemon-mode.test.ts
index 5ca64e320d..8ebef4bc3e 100644
--- a/packages/coding-agent/test/daemon-mode.test.ts
+++ b/packages/coding-agent/test/daemon-mode.test.ts
@@ -1,4 +1,4 @@
-import { mkdtempSync, rmSync } from "node:fs";
+import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
import type { Socket } from "node:net";
import { tmpdir } from "node:os";
import { join } from "node:path";
@@ -12,10 +12,13 @@ import {
AgentDaemon,
cancelPendingExtensionUiRequests,
detachClientFromActiveSession,
+ finishClientSnapshotStreaming,
getChildActiveSessionStates,
+ markClientSnapshotStreaming,
+ setDaemonClientSessionCapabilities,
shouldSendDaemonOutboundToClient,
} from "../src/modes/daemon/daemon-mode.js";
-import type { DaemonCommand } from "../src/modes/daemon/daemon-protocol.js";
+import type { DaemonAttachResult, DaemonCommand } from "../src/modes/daemon/daemon-protocol.js";
describe("daemon mode helpers", () => {
it("finds only direct child active sessions", () => {
@@ -243,6 +246,73 @@ describe("daemon mode helpers", () => {
expect(acceptAgentMessagePrompt.mock.calls[0]?.[0]).toContain("report current progress");
});
+ it("lists and routes agent messages to peers hosted by another worker", async () => {
+ const daemon = new AgentDaemon("/tmp/prime-agent-worker-test.sock", {
+ defaultSessionConfig: { agentDir: "/tmp/prime-agent-test-agent", cwd: "/tmp" },
+ createRuntime: async () => {
+ throw new Error("unexpected runtime creation");
+ },
+ worker: { authenticationToken: "worker-token" },
+ });
+ const source = makeState("source");
+ source.runtime = {
+ ...source.runtime,
+ cwd: "/tmp",
+ session: {
+ sessionId: "session-source",
+ sessionName: "Source",
+ isStreaming: false,
+ pendingMessageCount: 0,
+ },
+ } as never;
+ const receipt = {
+ id: "agentmsg-remote",
+ source: "agent_message",
+ target: { activeSessionId: "remote", sessionId: "session-remote" },
+ message: "continue remotely",
+ deliveryStatus: "delivered",
+ deliveredAt: "2026-01-01T00:00:00.000Z",
+ deliveryMode: "auto",
+ };
+ const sendRemoteAgentSessionMessage = vi.fn().mockResolvedValue(receipt);
+ const internals = daemon as unknown as {
+ sessions: Map<string, ActiveSessionState>;
+ remoteAgentPeers: Map<string, Record<string, unknown>>;
+ createAgentMessageListResult(current: ActiveSessionState): { agents: Array<{ activeSessionId: string }> };
+ sendRemoteAgentSessionMessage: typeof sendRemoteAgentSessionMessage;
+ sendAgentSessionMessage(options: {
+ targetSelector: string;
+ message: string;
+ fromState: ActiveSessionState;
+ origin: "agent";
+ }): Promise<unknown>;
+ };
+ internals.sessions.set(source.activeSessionId, source);
+ internals.remoteAgentPeers.set("remote", {
+ activeSessionId: "remote",
+ sessionId: "session-remote",
+ sessionName: "Remote",
+ runtimeKind: "top-level",
+ cwd: "/tmp/remote",
+ isStreaming: false,
+ pendingMessageCount: 0,
+ });
+ internals.sendRemoteAgentSessionMessage = sendRemoteAgentSessionMessage;
+
+ expect(internals.createAgentMessageListResult(source).agents).toContainEqual(
+ expect.objectContaining({ activeSessionId: "remote" }),
+ );
+ await expect(
+ internals.sendAgentSessionMessage({
+ targetSelector: "remote",
+ message: "continue remotely",
+ fromState: source,
+ origin: "agent",
+ }),
+ ).resolves.toEqual(receipt);
+ expect(sendRemoteAgentSessionMessage).toHaveBeenCalledWith(source, "remote", "continue remotely", undefined);
+ });
+
it("reports queued status when a direct accept races into the queue", async () => {
const daemon = new AgentDaemon("/tmp/prime-agent-test.sock", {
defaultSessionConfig: { agentDir: "/tmp/prime-agent-test-agent", cwd: "/tmp" },
@@ -2224,6 +2294,161 @@ describe("daemon mode helpers", () => {
method: "notify",
}),
).toBe(true);
+
+ setDaemonClientSessionCapabilities(uiClient, "active", new Set(["extension_ui"]));
+ setDaemonClientSessionCapabilities(uiClient, "other", new Set());
+ expect(shouldSendDaemonOutboundToClient(uiClient, dialogRequest)).toBe(true);
+ expect(
+ shouldSendDaemonOutboundToClient(uiClient, {
+ ...dialogRequest,
+ activeSessionId: "other",
+ }),
+ ).toBe(false);
+ });
+
+ it("delivers session closure while a client is snapshotting and backpressured", () => {
+ const daemon = new AgentDaemon("/tmp/prime-agent-test.sock", {
+ defaultSessionConfig: { agentDir: "/tmp/prime-agent-test-agent", cwd: "/tmp" },
+ createRuntime: async () => {
+ throw new Error("unexpected runtime creation");
+ },
+ });
+ const state = makeState("active");
+ state.eventGeneration = "generation-1";
+ const write = vi.fn((_data: unknown) => false);
+ const client = makeClient("client-1", state.activeSessionId);
+ client.socket = { destroyed: false, write } as unknown as Socket;
+ client.snapshotActiveSessionIds = new Set([state.activeSessionId]);
+ client.snapshotStreaming = true;
+ client.backpressured = true;
+ client.catchupActiveSessionIds = new Set([state.activeSessionId]);
+ state.clients.add(client);
+ const internals = daemon as unknown as {
+ broadcastToSession(
+ state: ActiveSessionState,
+ message: { type: "session_closed"; activeSessionId: string; reason: "killed" },
+ ): void;
+ };
+
+ internals.broadcastToSession(state, {
+ type: "session_closed",
+ activeSessionId: state.activeSessionId,
+ reason: "killed",
+ });
+
+ expect(write).toHaveBeenCalledOnce();
+ expect(String(write.mock.calls[0]?.[0])).toContain('"type":"session_closed"');
+ expect(client.catchupActiveSessionIds).not.toContain(state.activeSessionId);
+ });
+
+ it("marks a chunked attach as snapshotting before deferred streaming", async () => {
+ const tempDir = mkdtempSync(join(tmpdir(), "prime-agent-daemon-snapshot-order-"));
+ try {
+ const daemon = new AgentDaemon(join(tempDir, "daemon.sock"), {
+ defaultSessionConfig: { agentDir: tempDir, cwd: tempDir },
+ createRuntime: async () => {
+ throw new Error("unexpected runtime creation");
+ },
+ });
+ const state = makeState("active");
+ state.eventGeneration = "generation-1";
+ const client = makeClient("client-1", state.activeSessionId);
+ client.transport = "private-framed";
+ const result = {
+ activeSessionId: state.activeSessionId,
+ snapshot: { summary: {}, state: {}, messages: [] },
+ lastEventSequence: 0,
+ } as unknown as DaemonAttachResult;
+ const streamWorkerSnapshot = vi.fn(async () => undefined);
+ const internals = daemon as unknown as {
+ sessions: Map<string, ActiveSessionState>;
+ createAttachResult: () => DaemonAttachResult;
+ streamWorkerSnapshot: typeof streamWorkerSnapshot;
+ handleCommand(client: DaemonSocketClient, command: DaemonCommand): Promise<unknown>;
+ };
+ internals.sessions.set(state.activeSessionId, state);
+ internals.createAttachResult = () => result;
+ internals.streamWorkerSnapshot = streamWorkerSnapshot;
+
+ await internals.handleCommand(client, {
+ type: "attach",
+ activeSessionId: state.activeSessionId,
+ capabilities: ["attach_snapshot", "event_sequence", "slim_attach", "chunked_snapshot"],
+ });
+
+ expect(client.snapshotActiveSessionIds).toContain(state.activeSessionId);
+ expect(client.snapshotStreaming).toBe(true);
+ await new Promise<void>((resolve) => setImmediate(resolve));
+ expect(streamWorkerSnapshot).toHaveBeenCalledOnce();
+ } finally {
+ rmSync(tempDir, { recursive: true, force: true });
+ }
+ });
+
+ it("keeps overlapping snapshots active until every stream finishes", () => {
+ const client = makeClient("client-1", "active");
+
+ markClientSnapshotStreaming(client, "active");
+ markClientSnapshotStreaming(client, "active");
+ finishClientSnapshotStreaming(client, "active");
+
+ expect(client.snapshotStreaming).toBe(true);
+ expect(client.snapshotActiveSessionIds).toContain("active");
+ expect(client.snapshotActiveSessionCounts?.get("active")).toBe(1);
+
+ finishClientSnapshotStreaming(client, "active");
+ expect(client.snapshotStreaming).toBe(false);
+ expect(client.snapshotActiveSessionIds).not.toContain("active");
+ });
+
+ it("falls back to a full replacement when snapshot cache creation fails", () => {
+ const root = mkdtempSync(join(tmpdir(), "prime-agent-daemon-replacement-fallback-"));
+ try {
+ const invalidAgentDir = join(root, "not-a-directory");
+ writeFileSync(invalidAgentDir, "file");
+ const daemon = new AgentDaemon(join(root, "daemon.sock"), {
+ defaultSessionConfig: { agentDir: invalidAgentDir, cwd: root },
+ createRuntime: async () => {
+ throw new Error("unexpected runtime creation");
+ },
+ });
+ const state = makeState("active");
+ state.eventGeneration = "generation-1";
+ const write = vi.fn((_data: unknown) => true);
+ const client = makeClient("client-1", state.activeSessionId);
+ client.socket = { destroyed: false, write } as unknown as Socket;
+ client.transport = "private-framed";
+ setDaemonClientSessionCapabilities(client, state.activeSessionId, new Set(["chunked_snapshot"]));
+ state.clients.add(client);
+ const result = {
+ activeSessionId: state.activeSessionId,
+ snapshot: {
+ summary: {},
+ state: {},
+ messages: [{ role: "user", content: "x".repeat(4 * 1024 * 1024 + 1), timestamp: 0 }],
+ },
+ lastEventSequence: 0,
+ } as unknown as DaemonAttachResult;
+ const internals = daemon as unknown as {
+ createAttachResult: () => DaemonAttachResult;
+ broadcastToSession(state: ActiveSessionState, message: unknown): void;
+ };
+ internals.createAttachResult = () => result;
+
+ internals.broadcastToSession(state, {
+ type: "session_replaced",
+ activeSessionId: state.activeSessionId,
+ state: {},
+ messages: [],
+ });
+
+ expect(write).toHaveBeenCalledTimes(1);
+ const replacementFrame = String(write.mock.calls[0]?.[0]);
+ expect(replacementFrame).toContain('"type":"session_replaced"');
+ expect(replacementFrame).not.toContain('"snapshotFollows":true');
+ } finally {
+ rmSync(root, { recursive: true, force: true });
+ }
});
it("deduplicates concurrent creates for the same session file", async () => {
diff --git a/packages/coding-agent/test/daemon-multiclient-bench.ts b/packages/coding-agent/test/daemon-multiclient-bench.ts
new file mode 100644
index 0000000000..03526faeeb
--- /dev/null
+++ b/packages/coding-agent/test/daemon-multiclient-bench.ts
@@ -0,0 +1,814 @@
+/**
+ * Benchmark: daemon fan-out and attach serialization with many clients.
+ *
+ * This uses real local sockets but no providers or agent runtimes. It compares
+ * the legacy per-recipient serialization/full-history attach paths with v2's
+ * compact encode-once deltas and one cached, chunked transcript encoding.
+ *
+ * Run from packages/coding-agent:
+ *
+ * npx tsx test/daemon-multiclient-bench.ts
+ * npx tsx test/daemon-multiclient-bench.ts --session-file /path/to/session.jsonl
+ * npx tsx test/daemon-multiclient-bench.ts --generated-session-mib 100
+ * npx tsx test/daemon-multiclient-bench.ts --generated-session-mib 500
+ */
+import { randomUUID } from "node:crypto";
+import { createWriteStream } from "node:fs";
+import { copyFile, mkdtemp, rm, stat, unlink } from "node:fs/promises";
+import { createConnection, createServer, type Server, type Socket } from "node:net";
+import { tmpdir } from "node:os";
+import { basename, join } from "node:path";
+import { performance } from "node:perf_hooks";
+import type { AgentMessage } from "@earendil-works/pi-agent-core";
+import type { AssistantMessage } from "@earendil-works/pi-ai";
+import { SessionManager } from "../src/core/session-manager.js";
+import { createCompactAssistantDelta } from "../src/modes/daemon/compact-session-stream.js";
+import type { DaemonOutbound } from "../src/modes/daemon/daemon-protocol.js";
+import { SnapshotTranscriptCache } from "../src/modes/daemon/snapshot-transcript-cache.js";
+import { serializeJsonLine } from "../src/modes/rpc/jsonl.js";
+
+const CLIENT_COUNTS = [1, 10, 50, 100, 250] as const;
+const SESSION_CLIENT_COUNTS = [1, 2, 5, 10] as const;
+const STREAM_CHARS = 8192;
+const STREAM_CHUNK_CHARS = 128;
+const ATTACH_HISTORY_MESSAGES = 256;
+const ATTACH_MESSAGE_CHARS = 1024;
+const MEBIBYTE = 1024 * 1024;
+
+interface Counters {
+ serializations: number;
+ serializationMs: number;
+ maxSerializationMs: number;
+ writes: number;
+ writtenBytes: number;
+}
+
+interface BenchmarkResult extends Counters {
+ scenario: "fanout" | "fanout-v2" | "attach" | "attach-v2" | "session-attach" | "session-attach-v2";
+ clients: number;
+ elapsedMs: number;
+ throughputMiBPerSecond: number;
+ heapDeltaMiB: number;
+ rssDeltaMiB: number;
+ externalDeltaMiB: number;
+ peakRssDeltaMiB: number;
+}
+
+interface GeneratedSessionFixture {
+ file: string;
+ directory: string;
+ bytes: number;
+ messageCount: number;
+}
+
+interface SessionLoadResult {
+ fileBytes: number;
+ loadMs: number;
+ contextMs: number;
+ messageCount: number;
+ heapDeltaMiB: number;
+ rssDeltaMiB: number;
+ externalDeltaMiB: number;
+ peakRssDeltaMiB: number;
+}
+
+interface Receiver {
+ readonly done: Promise<void>;
+ setExpectedBytes(bytes: number): void;
+}
+
+interface SocketHarness {
+ readonly server: Server;
+ readonly senders: Socket[];
+ readonly receivers: Receiver[];
+ readonly receiverSockets: Socket[];
+ readonly socketPath: string;
+ close(): Promise<void>;
+}
+
+let socketCounter = 0;
+
+function socketPathForRun(): string {
+ socketCounter++;
+ if (process.platform === "win32") {
+ return `\\\\.\\pipe\\prime-agent-multiclient-bench-${process.pid}-${socketCounter}`;
+ }
+ return `/tmp/prime-agent-multiclient-${process.pid}-${socketCounter}.sock`;
+}
+
+async function removeSocketPath(socketPath: string): Promise<void> {
+ if (process.platform === "win32") {
+ return;
+ }
+ try {
+ await unlink(socketPath);
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") {
+ throw error;
+ }
+ }
+}
+
+function createReceiver(socket: Socket): Receiver {
+ let receivedBytes = 0;
+ let expectedBytes: number | undefined;
+ let settled = false;
+ let resolveDone!: () => void;
+ let rejectDone!: (error: Error) => void;
+ const done = new Promise<void>((resolve, reject) => {
+ resolveDone = resolve;
+ rejectDone = reject;
+ });
+
+ const checkComplete = () => {
+ if (!settled && expectedBytes !== undefined && receivedBytes >= expectedBytes) {
+ settled = true;
+ resolveDone();
+ }
+ };
+ socket.on("data", (chunk: Buffer) => {
+ receivedBytes += chunk.length;
+ checkComplete();
+ });
+ socket.on("error", (error) => {
+ if (!settled) {
+ settled = true;
+ rejectDone(error);
+ }
+ });
+ socket.on("close", () => {
+ if (!settled && expectedBytes !== undefined && receivedBytes < expectedBytes) {
+ settled = true;
+ rejectDone(new Error(`Socket closed after ${receivedBytes} of ${expectedBytes} expected bytes`));
+ }
+ });
+
+ return {
+ done,
+ setExpectedBytes(bytes: number): void {
+ if (expectedBytes !== undefined) {
+ throw new Error("Expected byte count was already set");
+ }
+ expectedBytes = bytes;
+ checkComplete();
+ },
+ };
+}
+
+async function createSocketHarness(clientCount: number): Promise<SocketHarness> {
+ const socketPath = socketPathForRun();
+ await removeSocketPath(socketPath);
+
+ const senders: Socket[] = [];
+ let resolveAccepted!: () => void;
+ const accepted = new Promise<void>((resolve) => {
+ resolveAccepted = resolve;
+ });
+ const server = createServer((socket) => {
+ senders.push(socket);
+ if (senders.length === clientCount) {
+ resolveAccepted();
+ }
+ });
+ await new Promise<void>((resolve, reject) => {
+ server.once("error", reject);
+ server.listen(socketPath, () => {
+ server.off("error", reject);
+ resolve();
+ });
+ });
+
+ // Connection setup is outside the measured region. Open sequentially so the
+ // benchmark itself works on hosts with a small Unix-socket accept backlog.
+ const receiverSockets: Socket[] = [];
+ for (let index = 0; index < clientCount; index++) {
+ const socket = createConnection(socketPath);
+ await new Promise<void>((resolve, reject) => {
+ const onConnect = () => {
+ socket.off("error", reject);
+ resolve();
+ };
+ socket.once("connect", onConnect);
+ socket.once("error", reject);
+ });
+ receiverSockets.push(socket);
+ }
+ await accepted;
+ const receivers = receiverSockets.map(createReceiver);
+
+ return {
+ server,
+ senders,
+ receivers,
+ receiverSockets,
+ socketPath,
+ async close(): Promise<void> {
+ for (const socket of [...senders, ...receiverSockets]) {
+ socket.destroy();
+ }
+ await new Promise<void>((resolve) => server.close(() => resolve()));
+ await removeSocketPath(socketPath);
+ },
+ };
+}
+
+function createAssistantMessage(text: string): AssistantMessage {
+ return {
+ role: "assistant",
+ content: [{ type: "text", text }],
+ api: "openai-responses",
+ provider: "openai",
+ model: "benchmark-model",
+ usage: {
+ input: 0,
+ output: 0,
+ cacheRead: 0,
+ cacheWrite: 0,
+ totalTokens: 0,
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
+ },
+ stopReason: "stop",
+ timestamp: 1_700_000_000_000,
+ };
+}
+
+function createStreamingEvent(text: string, delta: string, sequence: number): object {
+ const activeSessionId = "active-benchmark";
+ return {
+ type: "session_event",
+ activeSessionId,
+ event: {
+ type: "message_update",
+ message: createAssistantMessage(text),
+ assistantMessageEvent: { type: "text_delta", contentIndex: 0, delta },
+ },
+ meta: {
+ id: `${activeSessionId}:${sequence}`,
+ protocol: { name: "prime-agent.daemon", version: 1 },
+ activeSessionId,
+ sequence,
+ emittedAt: "2026-01-01T00:00:00.000Z",
+ },
+ };
+}
+
+function repeatedText(length: number, seed: string): string {
+ return seed.repeat(Math.ceil(length / seed.length)).slice(0, length);
+}
+
+const streamCorpus = repeatedText(STREAM_CHARS, "Prime Agent daemon multi-client streaming benchmark. ");
+const attachMessages = Array.from({ length: ATTACH_HISTORY_MESSAGES }, (_, index) => {
+ const text = repeatedText(ATTACH_MESSAGE_CHARS, `history-message-${index} `);
+ return index % 2 === 0
+ ? { role: "user", content: text, timestamp: 1_700_000_000_000 + index }
+ : createAssistantMessage(text);
+});
+
+function createAttachResponse(clientIndex: number): object {
+ return createAttachResponseForMessages(attachMessages, clientIndex);
+}
+
+function createAttachResponseForMessages(
+ messages: readonly AgentMessage[] | readonly object[],
+ clientIndex: number,
+): object {
+ const activeSessionId = "active-benchmark";
+ const summary = {
+ id: activeSessionId,
+ lifecycle: "live",
+ activity: "idle",
+ runtimeKind: "top-level",
+ activeSessionId,
+ sessionId: "session-benchmark",
+ cwd: "/tmp/prime-agent-benchmark",
+ isStreaming: false,
+ isCompacting: false,
+ attachedClients: clientIndex + 1,
+ messageCount: messages.length,
+ pendingMessageCount: 0,
+ };
+ const state = {
+ activeSessionId,
+ cwd: summary.cwd,
+ isStreaming: false,
+ isCompacting: false,
+ isBashRunning: false,
+ retryAttempt: 0,
+ steeringMode: "one-at-a-time",
+ followUpMode: "one-at-a-time",
+ sessionId: summary.sessionId,
+ sessionDir: "/tmp/prime-agent-benchmark/sessions",
+ leafId: "leaf-benchmark",
+ autoCompactionEnabled: true,
+ messageCount: messages.length,
+ pendingMessageCount: 0,
+ compactionCount: 0,
+ scopedModels: [],
+ activeToolNames: ["read", "bash", "edit"],
+ };
+ return {
+ id: `attach-${clientIndex}`,
+ type: "response",
+ command: "attach",
+ success: true,
+ data: {
+ protocol: { name: "prime-agent.daemon", version: 1 },
+ activeSessionId,
+ snapshot: {
+ activeSessionId,
+ summary,
+ state,
+ messages,
+ lastEventSequence: 0,
+ },
+ replay: { status: "complete", toSequence: 0 },
+ lastEventSequence: 0,
+ client: {
+ id: `client-${clientIndex}`,
+ capabilities: ["attach_snapshot", "event_sequence", "extension_ui", "slim_attach"],
+ },
+ },
+ };
+}
+
+function writeToRecipient(socket: Socket, message: object, counters: Counters): number {
+ // Intentionally matches AgentDaemon.write(): serialization occurs for every recipient.
+ const serializationStart = performance.now();
+ const line = serializeJsonLine(message);
+ const serializationMs = performance.now() - serializationStart;
+ const bytes = Buffer.byteLength(line);
+ counters.serializations++;
+ counters.serializationMs += serializationMs;
+ counters.maxSerializationMs = Math.max(counters.maxSerializationMs, serializationMs);
+ counters.writes++;
+ counters.writtenBytes += bytes;
+ socket.write(line);
+ return bytes;
+}
+
+function writeBufferToRecipient(socket: Socket, buffer: string | Buffer, counters: Counters): number {
+ const bytes = typeof buffer === "string" ? Buffer.byteLength(buffer) : buffer.length;
+ counters.writes++;
+ counters.writtenBytes += bytes;
+ socket.write(buffer);
+ return bytes;
+}
+
+async function runScenario(
+ scenario: BenchmarkResult["scenario"],
+ clientCount: number,
+ work: (harness: SocketHarness, counters: Counters, expectedBytes: number[]) => void,
+): Promise<BenchmarkResult> {
+ const harness = await createSocketHarness(clientCount);
+ try {
+ const counters: Counters = {
+ serializations: 0,
+ serializationMs: 0,
+ maxSerializationMs: 0,
+ writes: 0,
+ writtenBytes: 0,
+ };
+ const expectedBytes = Array.from({ length: clientCount }, () => 0);
+ const memoryBefore = process.memoryUsage();
+ let peakRss = memoryBefore.rss;
+ const sampler = setInterval(() => {
+ peakRss = Math.max(peakRss, process.memoryUsage().rss);
+ }, 1);
+ try {
+ const start = performance.now();
+ work(harness, counters, expectedBytes);
+ for (let index = 0; index < harness.receivers.length; index++) {
+ harness.receivers[index]!.setExpectedBytes(expectedBytes[index]!);
+ }
+ await Promise.all(harness.receivers.map((receiver) => receiver.done));
+ const elapsedMs = performance.now() - start;
+ const memoryAfter = process.memoryUsage();
+ peakRss = Math.max(peakRss, memoryAfter.rss);
+ return {
+ scenario,
+ clients: clientCount,
+ ...counters,
+ elapsedMs,
+ throughputMiBPerSecond: counters.writtenBytes / MEBIBYTE / (elapsedMs / 1000),
+ heapDeltaMiB: memoryDeltaMiB(memoryAfter, memoryBefore, "heapUsed"),
+ rssDeltaMiB: memoryDeltaMiB(memoryAfter, memoryBefore, "rss"),
+ externalDeltaMiB: memoryDeltaMiB(memoryAfter, memoryBefore, "external"),
+ peakRssDeltaMiB: (peakRss - memoryBefore.rss) / MEBIBYTE,
+ };
+ } finally {
+ clearInterval(sampler);
+ }
+ } finally {
+ await harness.close();
+ }
+}
+
+async function runFanout(clientCount: number): Promise<BenchmarkResult> {
+ return runScenario("fanout", clientCount, (harness, counters, expectedBytes) => {
+ for (let offset = 0, sequence = 1; offset < streamCorpus.length; sequence++) {
+ const nextOffset = Math.min(offset + STREAM_CHUNK_CHARS, streamCorpus.length);
+ const delta = streamCorpus.slice(offset, nextOffset);
+ const message = createStreamingEvent(streamCorpus.slice(0, nextOffset), delta, sequence);
+ for (let index = 0; index < harness.senders.length; index++) {
+ expectedBytes[index]! += writeToRecipient(harness.senders[index]!, message, counters);
+ }
+ offset = nextOffset;
+ }
+ });
+}
+
+async function runFanoutV2(clientCount: number): Promise<BenchmarkResult> {
+ return runScenario("fanout-v2", clientCount, (harness, counters, expectedBytes) => {
+ for (let offset = 0, sequence = 1; offset < streamCorpus.length; sequence++) {
+ const nextOffset = Math.min(offset + STREAM_CHUNK_CHARS, streamCorpus.length);
+ const delta = streamCorpus.slice(offset, nextOffset);
+ const partial = createAssistantMessage(streamCorpus.slice(0, nextOffset));
+ const compact = createCompactAssistantDelta({
+ type: "session_event",
+ activeSessionId: "active-benchmark",
+ event: {
+ type: "message_update",
+ message: partial,
+ assistantMessageEvent: { type: "text_delta", contentIndex: 0, delta, partial },
+ },
+ meta: {
+ id: `active-benchmark:${sequence}`,
+ protocol: { name: "prime-agent.daemon", version: 2 },
+ activeSessionId: "active-benchmark",
+ sequence,
+ cursor: { generation: "benchmark-generation", sequence },
+ emittedAt: "2026-01-01T00:00:00.000Z",
+ },
+ } satisfies DaemonOutbound);
+ if (!compact) {
+ throw new Error("Expected compact assistant delta");
+ }
+ const serializationStart = performance.now();
+ const line = serializeJsonLine(compact);
+ const serializationMs = performance.now() - serializationStart;
+ counters.serializations++;
+ counters.serializationMs += serializationMs;
+ counters.maxSerializationMs = Math.max(counters.maxSerializationMs, serializationMs);
+ for (let index = 0; index < harness.senders.length; index++) {
+ expectedBytes[index]! += writeBufferToRecipient(harness.senders[index]!, line, counters);
+ }
+ offset = nextOffset;
+ }
+ });
+}
+
+async function runAttach(clientCount: number): Promise<BenchmarkResult> {
+ return runScenario("attach", clientCount, (harness, counters, expectedBytes) => {
+ for (let index = 0; index < harness.senders.length; index++) {
+ // The daemon constructs and serializes a fresh attach response per client.
+ expectedBytes[index]! += writeToRecipient(harness.senders[index]!, createAttachResponse(index), counters);
+ }
+ });
+}
+
+async function runAttachV2(
+ messages: readonly AgentMessage[],
+ clientCount: number,
+ scenario: "attach-v2" | "session-attach-v2",
+): Promise<BenchmarkResult> {
+ const cacheRoot = await mkdtemp(join(tmpdir(), "prime-agent-attach-v2-bench-"));
+ const transcript = new SnapshotTranscriptCache({
+ activeSessionId: "active-benchmark",
+ snapshotId: `snapshot-${randomUUID()}`,
+ messages,
+ cacheRoot,
+ });
+ try {
+ return await runScenario(scenario, clientCount, (harness, counters, expectedBytes) => {
+ const begin = serializeJsonLine({
+ type: "session_snapshot_begin",
+ activeSessionId: "active-benchmark",
+ snapshotId: transcript.snapshotId,
+ snapshot: {
+ activeSessionId: "active-benchmark",
+ summary: { sessionId: "session-benchmark", messageCount: messages.length },
+ state: { sessionId: "session-benchmark", messageCount: messages.length },
+ lastEventSequence: 0,
+ lastEventCursor: { generation: "benchmark-generation", sequence: 0 },
+ },
+ messageCount: messages.length,
+ targetChunkBytes: transcript.targetChunkBytes,
+ });
+ const end = serializeJsonLine({
+ type: "session_snapshot_end",
+ activeSessionId: "active-benchmark",
+ snapshotId: transcript.snapshotId,
+ chunkCount: transcript.chunkCount,
+ lastEventSequence: 0,
+ lastEventCursor: { generation: "benchmark-generation", sequence: 0 },
+ });
+ counters.serializations += 2;
+ for (let clientIndex = 0; clientIndex < harness.senders.length; clientIndex++) {
+ const sender = harness.senders[clientIndex]!;
+ const acknowledgement = {
+ id: `attach-${clientIndex}`,
+ type: "response",
+ command: "attach",
+ success: true,
+ data: {
+ activeSessionId: "active-benchmark",
+ snapshotStream: {
+ id: transcript.snapshotId,
+ messageCount: messages.length,
+ targetChunkBytes: transcript.targetChunkBytes,
+ },
+ },
+ };
+ expectedBytes[clientIndex]! += writeToRecipient(sender, acknowledgement, counters);
+ expectedBytes[clientIndex]! += writeBufferToRecipient(sender, begin, counters);
+ for (let chunkIndex = 0; chunkIndex < transcript.chunkCount; chunkIndex++) {
+ expectedBytes[clientIndex]! += writeBufferToRecipient(
+ sender,
+ transcript.readChunk(chunkIndex),
+ counters,
+ );
+ }
+ expectedBytes[clientIndex]! += writeBufferToRecipient(sender, end, counters);
+ }
+ });
+ } finally {
+ transcript.dispose();
+ await rm(cacheRoot, { recursive: true, force: true });
+ }
+}
+
+async function runSessionAttach(messages: readonly AgentMessage[], clientCount: number): Promise<BenchmarkResult> {
+ return runScenario("session-attach", clientCount, (harness, counters, expectedBytes) => {
+ for (let index = 0; index < harness.senders.length; index++) {
+ expectedBytes[index]! += writeToRecipient(
+ harness.senders[index]!,
+ createAttachResponseForMessages(messages, index),
+ counters,
+ );
+ }
+ });
+}
+
+function memoryDeltaMiB(
+ after: NodeJS.MemoryUsage,
+ before: NodeJS.MemoryUsage,
+ field: keyof NodeJS.MemoryUsage,
+): number {
+ return (after[field] - before[field]) / MEBIBYTE;
+}
+
+async function loadSessionFixture(sessionFile: string): Promise<{
+ messages: AgentMessage[];
+ load: SessionLoadResult;
+ cleanup(): Promise<void>;
+}> {
+ const sourceStats = await stat(sessionFile);
+ if (!sourceStats.isFile()) {
+ throw new Error(`Session path is not a file: ${sessionFile}`);
+ }
+
+ // Work on a private copy: SessionManager may rewrite old session versions during
+ // migration, and a live daemon may append to the source while this benchmark runs.
+ const tempDir = await mkdtemp(join(tmpdir(), "prime-agent-session-bench-"));
+ const fixturePath = join(tempDir, "session.jsonl");
+ await copyFile(sessionFile, fixturePath);
+
+ try {
+ const memoryBefore = process.memoryUsage();
+ let peakRss = memoryBefore.rss;
+ const sampler = setInterval(() => {
+ peakRss = Math.max(peakRss, process.memoryUsage().rss);
+ }, 1);
+ let sessionManager: SessionManager;
+ let loadMs: number;
+ try {
+ const loadStart = performance.now();
+ sessionManager = await SessionManager.openAsync(fixturePath, tempDir, process.cwd());
+ loadMs = performance.now() - loadStart;
+ } finally {
+ clearInterval(sampler);
+ }
+
+ const contextStart = performance.now();
+ const context = sessionManager.buildSessionContext();
+ const contextMs = performance.now() - contextStart;
+ const memoryAfter = process.memoryUsage();
+ peakRss = Math.max(peakRss, memoryAfter.rss);
+
+ return {
+ messages: context.messages,
+ load: {
+ fileBytes: sourceStats.size,
+ loadMs,
+ contextMs,
+ messageCount: context.messages.length,
+ heapDeltaMiB: memoryDeltaMiB(memoryAfter, memoryBefore, "heapUsed"),
+ rssDeltaMiB: memoryDeltaMiB(memoryAfter, memoryBefore, "rss"),
+ externalDeltaMiB: memoryDeltaMiB(memoryAfter, memoryBefore, "external"),
+ peakRssDeltaMiB: (peakRss - memoryBefore.rss) / MEBIBYTE,
+ },
+ cleanup: () => rm(tempDir, { recursive: true, force: true }),
+ };
+ } catch (error) {
+ await rm(tempDir, { recursive: true, force: true });
+ throw error;
+ }
+}
+
+function printResults(
+ results: BenchmarkResult[],
+ details = `stream=${STREAM_CHARS} chars/${STREAM_CHUNK_CHARS}-char chunks; attach=${ATTACH_HISTORY_MESSAGES} messages x ${ATTACH_MESSAGE_CHARS} chars`,
+): void {
+ console.log("Prime Agent daemon multi-client benchmark");
+ console.log(details);
+ console.table(
+ results.map((result) => ({
+ scenario: result.scenario,
+ clients: result.clients,
+ serializations: result.serializations,
+ "serialize ms": result.serializationMs.toFixed(1),
+ "max serialize ms": result.maxSerializationMs.toFixed(1),
+ writes: result.writes,
+ MiB: (result.writtenBytes / MEBIBYTE).toFixed(2),
+ "elapsed ms": result.elapsedMs.toFixed(1),
+ "MiB/s": result.throughputMiBPerSecond.toFixed(1),
+ "heap delta MiB": result.heapDeltaMiB.toFixed(1),
+ "RSS delta MiB": result.rssDeltaMiB.toFixed(1),
+ "external delta MiB": result.externalDeltaMiB.toFixed(1),
+ "peak RSS delta MiB": result.peakRssDeltaMiB.toFixed(1),
+ })),
+ );
+}
+
+function printSessionLoad(sessionFile: string, result: SessionLoadResult): void {
+ console.log("Prime Agent real-session benchmark");
+ console.log(`fixture: ${basename(sessionFile)} (${(result.fileBytes / MEBIBYTE).toFixed(2)} MiB)`);
+ console.table([
+ {
+ "load ms": result.loadMs.toFixed(1),
+ "context ms": result.contextMs.toFixed(1),
+ messages: result.messageCount,
+ "heap delta MiB": result.heapDeltaMiB.toFixed(1),
+ "RSS delta MiB": result.rssDeltaMiB.toFixed(1),
+ "external delta MiB": result.externalDeltaMiB.toFixed(1),
+ "sampled peak RSS delta MiB": result.peakRssDeltaMiB.toFixed(1),
+ },
+ ]);
+}
+
+function sessionFileArg(args: readonly string[]): string | undefined {
+ const flagIndex = args.indexOf("--session-file");
+ if (flagIndex === -1) {
+ return undefined;
+ }
+ const value = args[flagIndex + 1];
+ if (!value || value.startsWith("--")) {
+ throw new Error("--session-file requires a path");
+ }
+ return value;
+}
+
+function generatedSessionMiBArg(args: readonly string[]): number | undefined {
+ const flagIndex = args.indexOf("--generated-session-mib");
+ if (flagIndex === -1) {
+ return undefined;
+ }
+ const value = args[flagIndex + 1];
+ if (!value || value.startsWith("--")) {
+ throw new Error("--generated-session-mib requires 100 or 500");
+ }
+ const parsed = Number(value);
+ if (parsed !== 100 && parsed !== 500) {
+ throw new Error("--generated-session-mib must be 100 or 500");
+ }
+ return parsed;
+}
+
+function writeStreamChunk(stream: NodeJS.WritableStream, chunk: string): Promise<void> {
+ return new Promise((resolve, reject) => {
+ const onError = (error: Error) => {
+ stream.off("error", onError);
+ reject(error);
+ };
+ stream.once("error", onError);
+ stream.write(chunk, () => {
+ stream.off("error", onError);
+ resolve();
+ });
+ });
+}
+
+function closeWriteStream(stream: NodeJS.WritableStream): Promise<void> {
+ return new Promise((resolve, reject) => {
+ stream.once("error", reject);
+ stream.end(() => resolve());
+ });
+}
+
+async function generateSessionFixture(sizeMiB: number): Promise<GeneratedSessionFixture> {
+ const directory = await mkdtemp(join(tmpdir(), `prime-agent-generated-${sizeMiB}mib-`));
+ const file = join(directory, `generated-${sizeMiB}mib.jsonl`);
+ const targetBytes = sizeMiB * MEBIBYTE;
+ const stream = createWriteStream(file, { encoding: "utf8" });
+ const timestamp = new Date(1_700_000_000_000).toISOString();
+ const sessionId = randomUUID();
+ const header = `${JSON.stringify({
+ type: "session",
+ version: 3,
+ id: sessionId,
+ timestamp,
+ cwd: process.cwd(),
+ })}\n`;
+ let bytes = Buffer.byteLength(header);
+ let messageCount = 0;
+ let parentId: string | null = null;
+
+ try {
+ await writeStreamChunk(stream, header);
+ while (bytes < targetBytes) {
+ const entryId = randomUUID();
+ const remaining = targetBytes - bytes;
+ const payloadChars = Math.max(1, Math.min(512 * 1024, remaining - 512));
+ const text = repeatedText(payloadChars, `generated-session-${messageCount} `);
+ const role = messageCount % 2 === 0 ? "user" : "assistant";
+ const message =
+ role === "user"
+ ? { role, content: text, timestamp: 1_700_000_000_000 + messageCount }
+ : createAssistantMessage(text);
+ const line = `${JSON.stringify({
+ type: "message",
+ id: entryId,
+ parentId,
+ timestamp,
+ message,
+ })}\n`;
+ await writeStreamChunk(stream, line);
+ bytes += Buffer.byteLength(line);
+ messageCount++;
+ parentId = entryId;
+ }
+ await closeWriteStream(stream);
+ return { file, directory, bytes, messageCount };
+ } catch (error) {
+ stream.destroy();
+ await rm(directory, { recursive: true, force: true });
+ throw error;
+ }
+}
+
+async function runRealSessionBenchmark(sessionFile: string): Promise<void> {
+ const fixture = await loadSessionFixture(sessionFile);
+ try {
+ printSessionLoad(sessionFile, fixture.load);
+ const results: BenchmarkResult[] = [];
+ for (const clientCount of SESSION_CLIENT_COUNTS) {
+ results.push(await runSessionAttach(fixture.messages, clientCount));
+ results.push(await runAttachV2(fixture.messages, clientCount, "session-attach-v2"));
+ }
+ console.log("Attach snapshot fan-out for the resolved active message path");
+ printResults(results, `session messages=${fixture.load.messageCount}`);
+ } finally {
+ await fixture.cleanup();
+ }
+}
+
+async function main(): Promise<void> {
+ const args = process.argv.slice(2);
+ const sessionFile = sessionFileArg(args);
+ const generatedSessionMiB = generatedSessionMiBArg(args);
+ if (sessionFile && generatedSessionMiB !== undefined) {
+ throw new Error("Use either --session-file or --generated-session-mib, not both");
+ }
+ if (sessionFile) {
+ await runRealSessionBenchmark(sessionFile);
+ return;
+ }
+ if (generatedSessionMiB !== undefined) {
+ const fixture = await generateSessionFixture(generatedSessionMiB);
+ try {
+ console.log(
+ `Generated ${generatedSessionMiB} MiB fixture with ${fixture.messageCount} messages ` +
+ `(${(fixture.bytes / MEBIBYTE).toFixed(2)} MiB on disk)`,
+ );
+ await runRealSessionBenchmark(fixture.file);
+ } finally {
+ await rm(fixture.directory, { recursive: true, force: true });
+ }
+ return;
+ }
+ const results: BenchmarkResult[] = [];
+ for (const clientCount of CLIENT_COUNTS) {
+ results.push(await runFanout(clientCount));
+ results.push(await runFanoutV2(clientCount));
+ }
+ for (const clientCount of CLIENT_COUNTS) {
+ results.push(await runAttach(clientCount));
+ results.push(await runAttachV2(attachMessages as AgentMessage[], clientCount, "attach-v2"));
+ }
+ printResults(results);
+}
+
+main().catch((error: unknown) => {
+ console.error(error);
+ process.exitCode = 1;
+});
diff --git a/packages/coding-agent/test/daemon-protocol.test.ts b/packages/coding-agent/test/daemon-protocol.test.ts
index 7e718df8bc..d3720142f0 100644
--- a/packages/coding-agent/test/daemon-protocol.test.ts
+++ b/packages/coding-agent/test/daemon-protocol.test.ts
@@ -33,32 +33,53 @@ describe("daemon protocol helpers", () => {
protocol: DAEMON_PROTOCOL_INFO,
activeSessionId: "active-1",
sequence: 3,
+ cursor: { generation: "active-1", sequence: 3 },
emittedAt: "2026-01-01T00:00:00.000Z",
event,
});
+ expect(eventMeta.cursor).toEqual({ generation: "active-1", sequence: 3 });
});
it("reports replay availability from resume cursors", () => {
- expect(createDaemonReplayInfo(undefined, 5)).toEqual({
+ expect(createDaemonReplayInfo(undefined, 5, "generation-1")).toEqual({
status: "complete",
toSequence: 5,
+ toCursor: { generation: "generation-1", sequence: 5 },
});
- expect(createDaemonReplayInfo({ activeSessionId: "active-1", eventSequence: 5 }, 5)).toEqual({
+ expect(
+ createDaemonReplayInfo(
+ { activeSessionId: "active-1", generation: "generation-1", sequence: 5 },
+ 5,
+ "generation-1",
+ ),
+ ).toEqual({
status: "complete",
fromSequence: 5,
toSequence: 5,
+ fromCursor: { generation: "generation-1", sequence: 5 },
+ toCursor: { generation: "generation-1", sequence: 5 },
});
- expect(createDaemonReplayInfo({ activeSessionId: "active-1", eventSequence: 10 }, 5)).toEqual({
+ expect(createDaemonReplayInfo({ generation: "generation-1", sequence: 10 }, 5, "generation-1")).toEqual({
status: "unavailable",
fromSequence: 10,
toSequence: 5,
+ fromCursor: { generation: "generation-1", sequence: 10 },
+ toCursor: { generation: "generation-1", sequence: 5 },
reason: "resume_cursor_ahead_of_session",
});
- expect(createDaemonReplayInfo({ activeSessionId: "active-1", eventSequence: 2 }, 5)).toEqual({
+ expect(createDaemonReplayInfo({ generation: "generation-1", sequence: 2 }, 5, "generation-1")).toEqual({
status: "unavailable",
fromSequence: 2,
toSequence: 5,
+ fromCursor: { generation: "generation-1", sequence: 2 },
+ toCursor: { generation: "generation-1", sequence: 5 },
reason: "event_replay_not_available",
});
+ expect(createDaemonReplayInfo({ generation: "old", sequence: 5 }, 0, "new")).toMatchObject({
+ status: "unavailable",
+ reason: "event_generation_changed",
+ fromCursor: { generation: "old", sequence: 5 },
+ toCursor: { generation: "new", sequence: 0 },
+ });
});
});
diff --git a/packages/coding-agent/test/daemon-runtime-lease.test.ts b/packages/coding-agent/test/daemon-runtime-lease.test.ts
new file mode 100644
index 0000000000..6555d1a3f2
--- /dev/null
+++ b/packages/coding-agent/test/daemon-runtime-lease.test.ts
@@ -0,0 +1,53 @@
+import { mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import {
+ acquireSessionLease,
+ SESSION_LEASE_OWNER_ID_ENV,
+ SESSION_LEASES_ENABLED_ENV,
+} from "../src/core/session-lease.js";
+import { SessionManager } from "../src/core/session-manager.js";
+import type { ActiveSessionState } from "../src/modes/daemon/active-session-state.js";
+import { AgentDaemon } from "../src/modes/daemon/daemon-mode.js";
+import type { DaemonCommand } from "../src/modes/daemon/daemon-protocol.js";
+import { userMsg } from "./utilities.js";
+
+describe("daemon runtime session leases", () => {
+ afterEach(() => {
+ vi.unstubAllEnvs();
+ });
+
+ it("releases an acquired lease when the runtime open guard cancels", async () => {
+ const root = mkdtempSync(join(tmpdir(), "prime-daemon-runtime-lease-"));
+ try {
+ vi.stubEnv(SESSION_LEASES_ENABLED_ENV, "1");
+ vi.stubEnv(SESSION_LEASE_OWNER_ID_ENV, "daemon-test");
+ const sessionDir = join(root, "sessions");
+ const sessionManager = SessionManager.create(root, sessionDir);
+ sessionManager.appendMessage(userMsg("persist session"));
+ const sessionPath = sessionManager.getSessionFile()!;
+ const daemon = new AgentDaemon(join(root, "daemon.sock"), {
+ defaultSessionConfig: { agentDir: root, cwd: root, sessionDir },
+ createRuntime: async () => {
+ throw new Error("runtime factory should not be reached");
+ },
+ });
+ const createRuntime = (
+ daemon as unknown as {
+ createRuntime(
+ command: Extract<DaemonCommand, { type: "create" }>,
+ guard: () => Promise<boolean>,
+ ): Promise<ActiveSessionState>;
+ }
+ ).createRuntime.bind(daemon);
+
+ await expect(createRuntime({ type: "create", sessionPath }, async () => false)).rejects.toThrow();
+ const reopened = acquireSessionLease(sessionPath, root);
+ expect(reopened).toBeDefined();
+ reopened?.release();
+ } finally {
+ rmSync(root, { recursive: true, force: true });
+ }
+ });
+});
diff --git a/packages/coding-agent/test/daemon-session-list.test.ts b/packages/coding-agent/test/daemon-session-list.test.ts
index c747d91c9d..426ad95d15 100644
--- a/packages/coding-agent/test/daemon-session-list.test.ts
+++ b/packages/coding-agent/test/daemon-session-list.test.ts
@@ -321,8 +321,15 @@ describe("buildRlmChildSnapshots", () => {
},
messages: [
{ role: "user", content: "Summarize the repo layout" },
- { role: "assistant", content: [{ type: "text", text: "The repo is an npm workspace." }] },
+ {
+ role: "assistant",
+ content: [
+ { type: "text", text: "The repo is an npm workspace." },
+ { type: "toolCall", id: "tool-1", name: "ipython", arguments: {} },
+ ],
+ },
] as AgentMessage[],
+ contextTokens: 41_000,
});
const grandchild = makeState({
activeSessionId: "grandchild",
@@ -355,6 +362,8 @@ describe("buildRlmChildSnapshots", () => {
expect(snapshots[0]).toMatchObject({
label: "Summarize the repo layout",
answerPreview: "The repo is an npm workspace.",
+ toolUseCount: 1,
+ tokenCount: 41_000,
sessionDir: "/tmp/artifacts/sub-aaa",
activeSessionId: "child",
});
@@ -387,6 +396,32 @@ describe("buildRlmChildSnapshots", () => {
expect(snapshots.map((snapshot) => [snapshot.id, snapshot.status])).toEqual([["sub-aaa", "running"]]);
});
+ it("includes in-flight assistant output in child snapshots", () => {
+ const parent = makeState({ activeSessionId: "parent" });
+ const child = makeState({
+ activeSessionId: "child",
+ isStreaming: true,
+ metadata: {
+ kind: "subagent",
+ createdAt: 1,
+ parentActiveSessionId: "parent",
+ rlmChildId: "sub-aaa",
+ },
+ streamingMessage: {
+ role: "assistant",
+ content: [
+ { type: "text", text: "Still investigating" },
+ { type: "toolCall", id: "tool-1", name: "search", arguments: {} },
+ ],
+ } as AgentMessage,
+ });
+
+ expect(buildRlmChildSnapshots("parent", [parent, child])[0]).toMatchObject({
+ answerPreview: "Still investigating",
+ toolUseCount: 1,
+ });
+ });
+
it("returns no snapshots for sessions without children", () => {
const solo = makeState({ activeSessionId: "solo" });
expect(buildRlmChildSnapshots("solo", [solo])).toEqual([]);
@@ -442,6 +477,8 @@ interface StateOptions {
childRunStatuses?: Record<string, "queued" | "running" | "done" | "error" | "cancelled">;
hasRunningRlmChildren?: boolean;
hasAcceptedPromptInFlight?: boolean;
+ contextTokens?: number;
+ streamingMessage?: AgentMessage;
metadata?: {
kind: "top-level" | "subagent";
createdAt: number;
@@ -487,9 +524,10 @@ function makeState(options: StateOptions): ActiveSessionState {
hasRunningRlmChildren: () => options.hasRunningRlmChildren ?? false,
hasAcceptedPromptInFlight: options.hasAcceptedPromptInFlight ?? false,
getCurrentRecap: () => undefined,
+ _contextTokensForCurrentMessages: () => options.contextTokens,
pendingMessageCount: 0,
state: {
- streamingMessage: undefined,
+ streamingMessage: options.streamingMessage,
pendingToolCalls: new Set(options.pendingToolCalls ?? []),
},
},
diff --git a/packages/coding-agent/test/daemon-supervisor-monitor.test.ts b/packages/coding-agent/test/daemon-supervisor-monitor.test.ts
new file mode 100644
index 0000000000..269cb2860d
--- /dev/null
+++ b/packages/coding-agent/test/daemon-supervisor-monitor.test.ts
@@ -0,0 +1,522 @@
+import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import type { AgentMessage } from "@earendil-works/pi-agent-core";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { AgentDaemon } from "../src/modes/daemon/daemon-mode.js";
+import type { DaemonAttachResult } from "../src/modes/daemon/daemon-protocol.js";
+import type { SessionSummary } from "../src/modes/daemon/daemon-session-list.js";
+import { DaemonSupervisor } from "../src/modes/daemon/daemon-supervisor.js";
+import { WorkerRecoveryJournal } from "../src/modes/daemon/worker-recovery-journal.js";
+
+interface SupervisorMonitorHarness {
+ options: { worker: object };
+ clients: Set<{ authenticated: boolean }>;
+ shuttingDown: boolean;
+ supervisorMonitorTimer?: ReturnType<typeof setTimeout>;
+ canConnectToSupervisor: (socketPath: string) => Promise<boolean>;
+ launchReplacementSupervisor: (socketPath: string) => Promise<void>;
+ scheduleSupervisorAvailabilityCheck: (socketPath: string, delayMs: number) => void;
+}
+
+function createHarness(canConnect: () => Promise<boolean>): SupervisorMonitorHarness {
+ return Object.assign(Object.create(AgentDaemon.prototype), {
+ options: { worker: {} },
+ clients: new Set<{ authenticated: boolean }>(),
+ shuttingDown: false,
+ canConnectToSupervisor: vi.fn(canConnect),
+ launchReplacementSupervisor: vi.fn(async () => undefined),
+ }) as SupervisorMonitorHarness;
+}
+
+describe("daemon worker supervisor monitoring", () => {
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ it("does not poll a healthy supervisor after the startup check", async () => {
+ vi.useFakeTimers();
+ const daemon = createHarness(async () => true);
+
+ daemon.scheduleSupervisorAvailabilityCheck("/tmp/supervisor.sock", 1500);
+ await vi.advanceTimersByTimeAsync(1500);
+ expect(daemon.canConnectToSupervisor).toHaveBeenCalledOnce();
+
+ await vi.advanceTimersByTimeAsync(60_000);
+ expect(daemon.canConnectToSupervisor).toHaveBeenCalledOnce();
+ expect(daemon.supervisorMonitorTimer).toBeUndefined();
+ });
+
+ it("skips socket probes while an authenticated supervisor connection is active", async () => {
+ vi.useFakeTimers();
+ const daemon = createHarness(async () => true);
+ daemon.clients.add({ authenticated: true });
+
+ daemon.scheduleSupervisorAvailabilityCheck("/tmp/supervisor.sock", 0);
+ await vi.runAllTimersAsync();
+
+ expect(daemon.canConnectToSupervisor).not.toHaveBeenCalled();
+ });
+
+ it("cancels an in-flight recovery after an intentional stop tombstone", async () => {
+ vi.useFakeTimers();
+ type RecoveryWorker = {
+ descriptor: {
+ workerId: string;
+ pid: number;
+ rootActiveSessionId: string;
+ stopRequestedAt?: string;
+ };
+ intentionalStop: boolean;
+ recovery?: Promise<void>;
+ };
+ type RecoveryHarness = {
+ workers: Map<string, RecoveryWorker>;
+ shuttingDown: boolean;
+ recoverWorker(worker: RecoveryWorker): Promise<void>;
+ };
+ const worker: RecoveryWorker = {
+ descriptor: { workerId: "worker-1", pid: process.pid, rootActiveSessionId: "active-1" },
+ intentionalStop: false,
+ };
+ const supervisor = Object.assign(Object.create(DaemonSupervisor.prototype), {
+ workers: new Map([[worker.descriptor.workerId, worker]]),
+ shuttingDown: false,
+ }) as RecoveryHarness;
+
+ const recovery = supervisor.recoverWorker(worker);
+ worker.intentionalStop = true;
+ worker.descriptor.stopRequestedAt = new Date().toISOString();
+ await vi.advanceTimersByTimeAsync(250);
+ await recovery;
+
+ expect(worker.recovery).toBeUndefined();
+ });
+
+ it("relaunches a worker instead of reconnecting to a reused pid", async () => {
+ vi.useFakeTimers();
+ type RecoveryWorker = {
+ descriptor: {
+ workerId: string;
+ pid: number;
+ processStartId: string;
+ rootActiveSessionId: string;
+ createCommand: { type: "create" };
+ };
+ intentionalStop: boolean;
+ stopRevision: number;
+ recovery?: Promise<void>;
+ };
+ type RecoveryHarness = {
+ workers: Map<string, RecoveryWorker>;
+ shuttingDown: boolean;
+ connectWorker: ReturnType<typeof vi.fn>;
+ recoverUncertainWorkerOperations: ReturnType<typeof vi.fn>;
+ launchWorker: ReturnType<typeof vi.fn>;
+ recoverWorker(worker: RecoveryWorker): Promise<void>;
+ };
+ const worker: RecoveryWorker = {
+ descriptor: {
+ workerId: "worker-reused-pid",
+ pid: process.pid,
+ processStartId: "different-process-start",
+ rootActiveSessionId: "active-1",
+ createCommand: { type: "create" },
+ },
+ intentionalStop: false,
+ stopRevision: 0,
+ };
+ const supervisor = Object.assign(Object.create(DaemonSupervisor.prototype), {
+ workers: new Map([[worker.descriptor.workerId, worker]]),
+ shuttingDown: false,
+ connectWorker: vi.fn(),
+ recoverUncertainWorkerOperations: vi.fn(async () => {}),
+ launchWorker: vi.fn(async () => worker),
+ }) as RecoveryHarness;
+
+ const recovery = supervisor.recoverWorker(worker);
+ await vi.advanceTimersByTimeAsync(250);
+ await recovery;
+
+ expect(supervisor.connectWorker).not.toHaveBeenCalled();
+ expect(supervisor.recoverUncertainWorkerOperations).toHaveBeenCalledWith(worker, false);
+ expect(supervisor.launchWorker).toHaveBeenCalledWith(worker.descriptor.createCommand, worker);
+ });
+
+ it("does not relaunch a live worker whose process identity is unknown", async () => {
+ vi.useFakeTimers();
+ type RecoveryWorker = {
+ descriptor: {
+ workerId: string;
+ pid: number;
+ rootActiveSessionId: string;
+ createCommand: { type: "create" };
+ lifecycle?: string;
+ consecutiveFailures: number;
+ lastFailureAt?: string;
+ lastError?: string;
+ };
+ intentionalStop: boolean;
+ stopRevision: number;
+ recovery?: Promise<void>;
+ client?: { close(): void };
+ };
+ type RecoveryHarness = {
+ workers: Map<string, RecoveryWorker>;
+ shuttingDown: boolean;
+ connectWorker: ReturnType<typeof vi.fn>;
+ recoverUncertainWorkerOperations: ReturnType<typeof vi.fn>;
+ launchWorker: ReturnType<typeof vi.fn>;
+ persistWorker: ReturnType<typeof vi.fn>;
+ syncAgentPeers: ReturnType<typeof vi.fn>;
+ log: ReturnType<typeof vi.fn>;
+ recoverWorker(worker: RecoveryWorker): Promise<void>;
+ };
+ const worker: RecoveryWorker = {
+ descriptor: {
+ workerId: "worker-unknown-identity",
+ pid: process.pid,
+ rootActiveSessionId: "active-1",
+ createCommand: { type: "create" },
+ consecutiveFailures: 0,
+ },
+ intentionalStop: false,
+ stopRevision: 0,
+ };
+ const supervisor = Object.assign(Object.create(DaemonSupervisor.prototype), {
+ workers: new Map([[worker.descriptor.workerId, worker]]),
+ shuttingDown: false,
+ connectWorker: vi.fn(async () => {
+ throw new Error("worker socket unavailable");
+ }),
+ recoverUncertainWorkerOperations: vi.fn(async () => {}),
+ launchWorker: vi.fn(async () => worker),
+ persistWorker: vi.fn(),
+ syncAgentPeers: vi.fn(async () => {}),
+ log: vi.fn(),
+ }) as RecoveryHarness;
+
+ const recovery = supervisor.recoverWorker(worker);
+ await vi.runAllTimersAsync();
+ await recovery;
+
+ expect(supervisor.connectWorker).toHaveBeenCalledTimes(3);
+ expect(supervisor.recoverUncertainWorkerOperations).not.toHaveBeenCalled();
+ expect(supervisor.launchWorker).not.toHaveBeenCalled();
+ expect(worker.descriptor.lifecycle).toBe("failed");
+ });
+
+ it("keeps a recovered worker ready when peer synchronization fails", async () => {
+ vi.useFakeTimers();
+ type RecoveryWorker = {
+ descriptor: {
+ workerId: string;
+ pid: number;
+ processStartId?: string;
+ rootActiveSessionId: string;
+ createCommand: { type: "create" };
+ lifecycle?: string;
+ consecutiveFailures: number;
+ };
+ intentionalStop: boolean;
+ stopRevision: number;
+ recovery?: Promise<void>;
+ };
+ type RecoveryHarness = {
+ workers: Map<string, RecoveryWorker>;
+ shuttingDown: boolean;
+ connectWorker: ReturnType<typeof vi.fn>;
+ subscribeWorker: ReturnType<typeof vi.fn>;
+ refreshWorkerSummaries: ReturnType<typeof vi.fn>;
+ recoverUncertainWorkerOperations: ReturnType<typeof vi.fn>;
+ launchWorker: ReturnType<typeof vi.fn>;
+ persistWorker: ReturnType<typeof vi.fn>;
+ syncAgentPeers: ReturnType<typeof vi.fn>;
+ log: ReturnType<typeof vi.fn>;
+ recoverWorker(worker: RecoveryWorker): Promise<void>;
+ };
+ const worker: RecoveryWorker = {
+ descriptor: {
+ workerId: "worker-peer-sync-failure",
+ pid: process.pid,
+ rootActiveSessionId: "active-1",
+ createCommand: { type: "create" },
+ consecutiveFailures: 1,
+ },
+ intentionalStop: false,
+ stopRevision: 0,
+ };
+ const supervisor = Object.assign(Object.create(DaemonSupervisor.prototype), {
+ workers: new Map([[worker.descriptor.workerId, worker]]),
+ shuttingDown: false,
+ connectWorker: vi.fn(async () => ({})),
+ subscribeWorker: vi.fn(async () => {}),
+ refreshWorkerSummaries: vi.fn(async () => {}),
+ recoverUncertainWorkerOperations: vi.fn(async () => {}),
+ launchWorker: vi.fn(async () => worker),
+ persistWorker: vi.fn(),
+ syncAgentPeers: vi.fn(async () => {
+ throw new Error("peer unavailable");
+ }),
+ log: vi.fn(),
+ }) as RecoveryHarness;
+
+ const recovery = supervisor.recoverWorker(worker);
+ await vi.advanceTimersByTimeAsync(250);
+ await recovery;
+
+ expect(supervisor.connectWorker).toHaveBeenCalledOnce();
+ expect(supervisor.recoverUncertainWorkerOperations).not.toHaveBeenCalled();
+ expect(supervisor.launchWorker).not.toHaveBeenCalled();
+ expect(worker.descriptor.lifecycle).toBe("ready");
+ expect(worker.descriptor.consecutiveFailures).toBe(0);
+ });
+
+ it("ignores malformed persisted worker descriptors", () => {
+ const descriptorDir = mkdtempSync(join(tmpdir(), "prime-supervisor-descriptor-test-"));
+ try {
+ writeFileSync(
+ join(descriptorDir, "malformed.json"),
+ `${JSON.stringify({
+ version: 1,
+ supervisorSocketPath: "/tmp/supervisor.sock",
+ workerId: "worker-1",
+ rootActiveSessionId: "active-1",
+ })}\n`,
+ );
+ const supervisor = Object.assign(Object.create(DaemonSupervisor.prototype), {
+ descriptorDir,
+ socketPath: "/tmp/supervisor.sock",
+ workers: new Map(),
+ log: vi.fn(),
+ }) as {
+ workers: Map<string, unknown>;
+ loadWorkerDescriptors(): void;
+ };
+
+ supervisor.loadWorkerDescriptors();
+
+ expect(supervisor.workers.size).toBe(0);
+ } finally {
+ rmSync(descriptorDir, { recursive: true, force: true });
+ }
+ });
+
+ it("seeds compact attach streaming from the in-flight assistant message", async () => {
+ const assistant = (text: string): AgentMessage => ({
+ role: "assistant",
+ content: [{ type: "text", text }],
+ api: "test-api",
+ provider: "test-provider",
+ model: "test-model",
+ usage: {
+ input: 0,
+ output: 0,
+ cacheRead: 0,
+ cacheWrite: 0,
+ totalTokens: 0,
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
+ },
+ stopReason: "stop",
+ timestamp: 1,
+ });
+ const activeSessionId = "active-1";
+ const finalizedMessage = assistant("finalized");
+ const streamingMessage = assistant("in flight");
+ const summary: SessionSummary = {
+ id: activeSessionId,
+ activeSessionId,
+ lifecycle: "live",
+ activity: "working",
+ sessionId: "session-1",
+ cwd: "/tmp/project",
+ isStreaming: true,
+ isCompacting: false,
+ attachedClients: 0,
+ messageCount: 1,
+ pendingMessageCount: 0,
+ streamingMessage,
+ };
+ const result = {
+ activeSessionId,
+ snapshot: { summary, messages: [finalizedMessage] },
+ } as unknown as DaemonAttachResult;
+ const worker = {
+ descriptor: { workerId: "worker-1", lifecycle: "ready", pid: 1234 },
+ summaries: new Map([[activeSessionId, summary]]),
+ snapshotCache: new Map([[activeSessionId, result]]),
+ snapshotLoads: new Map(),
+ };
+ const client = {
+ id: "client-1",
+ capabilities: new Set<string>(),
+ supportsExtensionUi: false,
+ attachedActiveSessionIds: new Set<string>(),
+ };
+ const seed = vi.fn();
+ const supervisor = Object.assign(Object.create(DaemonSupervisor.prototype), {
+ workers: new Map([[worker.descriptor.workerId, worker]]),
+ clients: new Set([client]),
+ streamReconstructor: { seed },
+ syncWorkerExtensionUi: vi.fn(async () => {}),
+ }) as {
+ attachClient(
+ client: {
+ id: string;
+ capabilities: Set<string>;
+ supportsExtensionUi: boolean;
+ attachedActiveSessionIds: Set<string>;
+ },
+ command: { type: "attach"; activeSessionId: string },
+ ): Promise<unknown>;
+ };
+
+ await supervisor.attachClient(client, { type: "attach", activeSessionId });
+
+ expect(seed).toHaveBeenCalledWith(activeSessionId, streamingMessage);
+ });
+
+ it("subscribes to worker updates with chunked snapshots", async () => {
+ type SubscriptionWorker = {
+ client: { requestWorker: (command: unknown) => Promise<{ success: boolean }> };
+ };
+ const requestWorker = vi.fn(async () => ({ success: true }));
+ const worker: SubscriptionWorker = { client: { requestWorker } };
+ const supervisor = Object.assign(Object.create(DaemonSupervisor.prototype), {
+ clients: new Set(),
+ }) as {
+ subscribeWorker(worker: SubscriptionWorker, activeSessionId: string): Promise<void>;
+ };
+
+ await supervisor.subscribeWorker(worker, "active-1");
+
+ expect(requestWorker).toHaveBeenCalledWith({
+ type: "worker_subscribe",
+ activeSessionId: "active-1",
+ capabilities: ["attach_snapshot", "event_sequence", "slim_attach", "chunked_snapshot"],
+ supportsExtensionUi: false,
+ });
+ });
+
+ it("does not retain an attachment when snapshot loading fails", async () => {
+ type AttachClient = {
+ id: string;
+ capabilities: Set<string>;
+ supportsExtensionUi: boolean;
+ attachedActiveSessionIds: Set<string>;
+ };
+ const activeSessionId = "active-failed-attach";
+ const summary = {
+ id: activeSessionId,
+ activeSessionId,
+ lifecycle: "live",
+ activity: "idle",
+ sessionId: "session-failed-attach",
+ cwd: "/tmp/project",
+ isStreaming: false,
+ isCompacting: false,
+ attachedClients: 0,
+ messageCount: 0,
+ pendingMessageCount: 0,
+ } satisfies SessionSummary;
+ const worker = {
+ descriptor: { workerId: "worker-1", lifecycle: "ready", pid: 1234 },
+ client: {
+ request: vi.fn(async () => {
+ throw new Error("snapshot failed");
+ }),
+ },
+ summaries: new Map([[activeSessionId, summary]]),
+ snapshotCache: new Map(),
+ transcriptCaches: new Map(),
+ incomingTranscriptActiveSessionIds: new Set(),
+ snapshotLoads: new Map(),
+ };
+ const client: AttachClient = {
+ id: "client-1",
+ capabilities: new Set<string>(),
+ supportsExtensionUi: false,
+ attachedActiveSessionIds: new Set<string>(),
+ };
+ const supervisor = Object.assign(Object.create(DaemonSupervisor.prototype), {
+ workers: new Map([[worker.descriptor.workerId, worker]]),
+ clients: new Set([client]),
+ }) as {
+ attachClient(client: AttachClient, command: { type: "attach"; activeSessionId: string }): Promise<unknown>;
+ };
+
+ await expect(supervisor.attachClient(client, { type: "attach", activeSessionId })).rejects.toThrow(
+ "snapshot failed",
+ );
+ expect(client.attachedActiveSessionIds).toEqual(new Set());
+ });
+
+ it("marks each busy worker session interrupted independently", async () => {
+ type RecoveryWorker = {
+ descriptor: {
+ workerId: string;
+ pid: number;
+ rootActiveSessionId: string;
+ recoveryJournalPath: string;
+ orphanProcessJournalPath: string;
+ };
+ };
+ const root = mkdtempSync(join(tmpdir(), "prime-supervisor-recovery-test-"));
+ const journalPath = join(root, "worker.recovery.jsonl");
+ const orphanJournalPath = join(root, "worker.orphans.jsonl");
+ writeFileSync(
+ orphanJournalPath,
+ `${JSON.stringify({
+ version: 1,
+ pid: 987_654,
+ ownerPid: process.pid,
+ processStartId: "reused-process",
+ active: true,
+ recordedAt: new Date().toISOString(),
+ })}\n`,
+ );
+ const journal = new WorkerRecoveryJournal(journalPath);
+ journal.record({
+ activeSessionId: "root-active",
+ sessionId: "root-session",
+ sessionFile: "/tmp/root.jsonl",
+ busy: true,
+ operation: "model_stream",
+ });
+ journal.record({
+ activeSessionId: "child-active",
+ sessionId: "child-session",
+ sessionFile: "/tmp/child.jsonl",
+ busy: true,
+ operation: "tool_execution",
+ });
+ const worker: RecoveryWorker = {
+ descriptor: {
+ workerId: "worker-1",
+ pid: process.pid,
+ rootActiveSessionId: "root-active",
+ recoveryJournalPath: journalPath,
+ orphanProcessJournalPath: orphanJournalPath,
+ },
+ };
+ const markInterrupted = vi.fn(async () => undefined);
+ const kill = vi.spyOn(process, "kill").mockReturnValue(true);
+ const supervisor = Object.assign(Object.create(DaemonSupervisor.prototype), {
+ catalog: { markInterrupted },
+ log: vi.fn(),
+ }) as {
+ recoverUncertainWorkerOperations(worker: RecoveryWorker, killWorkerProcess: boolean): Promise<void>;
+ };
+
+ try {
+ await supervisor.recoverUncertainWorkerOperations(worker, false);
+ expect(kill).not.toHaveBeenCalled();
+ expect(markInterrupted).toHaveBeenCalledTimes(2);
+ expect(markInterrupted).toHaveBeenCalledWith("/tmp/root.jsonl", "root-active", ["model_stream"]);
+ expect(markInterrupted).toHaveBeenCalledWith("/tmp/child.jsonl", "child-active", ["tool_execution"]);
+ } finally {
+ kill.mockRestore();
+ rmSync(root, { recursive: true, force: true });
+ }
+ });
+});
diff --git a/packages/coding-agent/test/daemon-supervisor-process.test.ts b/packages/coding-agent/test/daemon-supervisor-process.test.ts
new file mode 100644
index 0000000000..443e50e755
--- /dev/null
+++ b/packages/coding-agent/test/daemon-supervisor-process.test.ts
@@ -0,0 +1,961 @@
+import { type ChildProcess, spawn } from "node:child_process";
+import { randomUUID } from "node:crypto";
+import { mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { dirname, join, resolve } from "node:path";
+import { afterEach, describe, expect, it } from "vitest";
+import { ENV_AGENT_DIR, getCronJobsPath } from "../src/config.js";
+import { AgentCronJobStore } from "../src/core/cron-jobs.js";
+import { readActiveOrphanProcesses } from "../src/core/orphan-process-journal.js";
+import {
+ acquireSessionLease,
+ SESSION_LEASE_OWNER_ID_ENV,
+ SESSION_LEASES_ENABLED_ENV,
+} from "../src/core/session-lease.js";
+import { readSessionInfo, SessionManager } from "../src/core/session-manager.js";
+import { DaemonAgentConnection } from "../src/modes/agent-connection/daemon-agent-connection.js";
+import { DaemonClient } from "../src/modes/daemon/daemon-client.js";
+import type { SessionSummary } from "../src/modes/daemon/daemon-session-list.js";
+import type { DaemonWorkerDescriptor } from "../src/modes/daemon/daemon-worker-protocol.js";
+
+const cliPath = resolve(__dirname, "../src/cli.ts");
+const tsxPath = resolve(__dirname, "../../../node_modules/tsx/dist/cli.mjs");
+const tempDirs: string[] = [];
+const children = new Set<ChildProcess>();
+const workerPids = new Set<number>();
+const daemonSockets = new Set<string>();
+const childDiagnostics = new WeakMap<ChildProcess, { stdout: string; stderr: string }>();
+const PROCESS_STRESS_WORKERS = Number.parseInt(process.env.PRIME_AGENT_STRESS_WORKERS ?? "10", 10);
+
+afterEach(async () => {
+ for (const socketPath of daemonSockets) {
+ const client = new DaemonClient(socketPath);
+ try {
+ await client.connect(250);
+ await client.request({ type: "shutdown" }, 2000);
+ } catch {
+ // Already gone.
+ } finally {
+ client.close();
+ }
+ }
+ daemonSockets.clear();
+ for (const child of children) {
+ if (child.exitCode === null && child.signalCode === null) {
+ child.kill("SIGTERM");
+ }
+ }
+ children.clear();
+ for (const pid of workerPids) {
+ try {
+ process.kill(pid, "SIGCONT");
+ } catch {
+ // Already gone.
+ }
+ try {
+ process.kill(-pid, "SIGTERM");
+ } catch {
+ try {
+ process.kill(pid, "SIGTERM");
+ } catch {
+ // Already gone.
+ }
+ }
+ }
+ workerPids.clear();
+ for (const directory of tempDirs.splice(0)) {
+ rmSync(directory, { recursive: true, force: true });
+ }
+});
+
+function tempDir(): string {
+ const directory = mkdtempSync(join(tmpdir(), "prime-daemon-supervisor-test-"));
+ tempDirs.push(directory);
+ return directory;
+}
+
+function spawnSupervisor(
+ agentDir: string,
+ socketPath: string,
+ cwd: string,
+ extraArgs: readonly string[] = [],
+): ChildProcess {
+ daemonSockets.add(socketPath);
+ const child = spawn(
+ process.execPath,
+ [tsxPath, cliPath, "--mode", "daemon", "--daemon-socket", socketPath, "--offline", ...extraArgs],
+ {
+ cwd,
+ env: {
+ ...process.env,
+ [ENV_AGENT_DIR]: agentDir,
+ PI_OFFLINE: "1",
+ TSX_TSCONFIG_PATH: resolve(__dirname, "../../../tsconfig.json"),
+ },
+ stdio: ["ignore", "pipe", "pipe"],
+ },
+ );
+ children.add(child);
+ const diagnostics = { stdout: "", stderr: "" };
+ childDiagnostics.set(child, diagnostics);
+ child.stdout?.on("data", (chunk: Buffer) => {
+ diagnostics.stdout += chunk.toString("utf8");
+ });
+ child.stderr?.on("data", (chunk: Buffer) => {
+ diagnostics.stderr += chunk.toString("utf8");
+ });
+ return child;
+}
+
+function readDaemonLogs(agentDir: string): string {
+ const logsDir = join(agentDir, "logs");
+ try {
+ return readdirSync(logsDir)
+ .map((name) => `${name}:\n${readFileSync(join(logsDir, name), "utf8")}`)
+ .join("\n");
+ } catch {
+ return "no daemon logs";
+ }
+}
+
+function readWorkerDescriptor(agentDir: string): DaemonWorkerDescriptor {
+ const workersRoot = join(agentDir, "daemon-workers");
+ for (const directory of readdirSync(workersRoot)) {
+ const descriptorDirectory = join(workersRoot, directory);
+ for (const name of readdirSync(descriptorDirectory)) {
+ if (name.endsWith(".json")) {
+ return JSON.parse(readFileSync(join(descriptorDirectory, name), "utf8")) as DaemonWorkerDescriptor;
+ }
+ }
+ }
+ throw new Error("Worker descriptor was not persisted");
+}
+
+function countWorkerDescriptors(agentDir: string): number {
+ const workersRoot = join(agentDir, "daemon-workers");
+ try {
+ return readdirSync(workersRoot).reduce((count, directory) => {
+ return count + readdirSync(join(workersRoot, directory)).filter((name) => name.endsWith(".json")).length;
+ }, 0);
+ } catch {
+ return 0;
+ }
+}
+
+async function waitForWorkerStopTombstone(agentDir: string): Promise<DaemonWorkerDescriptor> {
+ const deadline = Date.now() + 5000;
+ while (Date.now() < deadline) {
+ try {
+ const descriptor = readWorkerDescriptor(agentDir);
+ if (descriptor.stopRequestedAt) {
+ return descriptor;
+ }
+ } catch {
+ // The descriptor directory may still be appearing.
+ }
+ await new Promise((resolveDelay) => setTimeout(resolveDelay, 10));
+ }
+ throw new Error("Worker stop tombstone was not persisted");
+}
+
+function readSupervisorConfig(agentDir: string): { defaultSessionConfig?: { sessionDir?: string; noTools?: boolean } } {
+ const workersRoot = join(agentDir, "daemon-workers");
+ for (const directory of readdirSync(workersRoot)) {
+ const path = join(workersRoot, directory, "supervisor-config");
+ try {
+ return JSON.parse(readFileSync(path, "utf8")) as {
+ defaultSessionConfig?: { sessionDir?: string; noTools?: boolean };
+ };
+ } catch {
+ // Continue looking for the descriptor directory for this daemon socket.
+ }
+ }
+ throw new Error("Supervisor config was not persisted");
+}
+
+async function connectEventually(socketPath: string, child?: ChildProcess): Promise<DaemonClient> {
+ const deadline = Date.now() + 15_000;
+ let lastError: unknown;
+ while (Date.now() < deadline) {
+ if (child && (child.exitCode !== null || child.signalCode !== null)) {
+ throw new Error(
+ `Supervisor exited before becoming ready (code ${child.exitCode}, signal ${child.signalCode})`,
+ );
+ }
+ const client = new DaemonClient(socketPath);
+ try {
+ await client.connect(250);
+ await client.waitForHello(1000);
+ return client;
+ } catch (error) {
+ lastError = error;
+ client.close();
+ await new Promise((resolveDelay) => setTimeout(resolveDelay, 25));
+ }
+ }
+ throw new Error(`Timed out waiting for supervisor: ${String(lastError)}`);
+}
+
+async function waitForSocketGone(socketPath: string): Promise<void> {
+ const deadline = Date.now() + 10_000;
+ while (Date.now() < deadline) {
+ const client = new DaemonClient(socketPath);
+ try {
+ await client.connect(100);
+ } catch {
+ client.close();
+ return;
+ }
+ client.close();
+ await new Promise((resolveDelay) => setTimeout(resolveDelay, 25));
+ }
+ throw new Error("Daemon supervisor socket remained available after shutdown");
+}
+
+function requireSummary(responseData: unknown): SessionSummary {
+ if (!responseData || typeof responseData !== "object") {
+ throw new Error("Missing daemon session summary");
+ }
+ return responseData as SessionSummary;
+}
+
+function requireSessionList(responseData: unknown): SessionSummary[] {
+ if (!responseData || typeof responseData !== "object" || !("sessions" in responseData)) {
+ throw new Error("Missing daemon session list");
+ }
+ const sessions = (responseData as { sessions: unknown }).sessions;
+ if (!Array.isArray(sessions)) {
+ throw new Error("Invalid daemon session list");
+ }
+ return sessions as SessionSummary[];
+}
+
+async function waitForExit(child: ChildProcess): Promise<void> {
+ if (child.exitCode !== null || child.signalCode !== null) {
+ return;
+ }
+ await new Promise<void>((resolveExit, reject) => {
+ const timeout = setTimeout(() => reject(new Error("Timed out waiting for process exit")), 10_000);
+ child.once("exit", () => {
+ clearTimeout(timeout);
+ resolveExit();
+ });
+ });
+}
+
+async function waitForProcessGone(pid: number): Promise<void> {
+ const deadline = Date.now() + 10_000;
+ while (Date.now() < deadline) {
+ try {
+ process.kill(pid, 0);
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === "ESRCH") {
+ return;
+ }
+ }
+ await new Promise((resolveDelay) => setTimeout(resolveDelay, 25));
+ }
+ throw new Error(`Worker ${pid} remained alive after daemon shutdown`);
+}
+
+async function waitForCondition(predicate: () => boolean, failureMessage: string, timeoutMs = 10_000): Promise<void> {
+ const deadline = Date.now() + timeoutMs;
+ while (Date.now() < deadline) {
+ if (predicate()) {
+ return;
+ }
+ await new Promise((resolveDelay) => setTimeout(resolveDelay, 25));
+ }
+ throw new Error(failureMessage);
+}
+
+describe("daemon supervisor resident workers", () => {
+ it("cancels an archived session heartbeat without spawning a worker", async () => {
+ const root = tempDir();
+ const agentDir = join(root, "agent");
+ const projectDir = join(root, "project");
+ const sessionDir = join(agentDir, "sessions");
+ const socketPath = join(
+ tmpdir(),
+ `prime-supervisor-archived-cron-${process.pid}-${randomUUID().slice(0, 8)}.sock`,
+ );
+ mkdirSync(projectDir, { recursive: true });
+ const sessionManager = SessionManager.create(projectDir, sessionDir);
+ sessionManager.appendMessage({ role: "user", content: "do not revive me", timestamp: 1 });
+ sessionManager.appendSessionState({ status: "active" });
+ sessionManager.appendSessionState({ status: "archived" });
+ const sessionFile = sessionManager.getSessionFile();
+ if (!sessionFile) {
+ throw new Error("Fixture session did not persist");
+ }
+ const cronStore = new AgentCronJobStore(getCronJobsPath(agentDir));
+ const heartbeat = cronStore.createHeartbeat({
+ activeSessionId: "old-active-session",
+ sessionId: sessionManager.getSessionId(),
+ sessionFile,
+ cwd: projectDir,
+ scheduleText: "every 10s",
+ prompt: "continue old work",
+ now: new Date(Date.now() - 20_000),
+ });
+
+ const supervisor = spawnSupervisor(agentDir, socketPath, projectDir);
+ const client = await connectEventually(socketPath, supervisor);
+ const migratedStore = AgentCronJobStore.forSessionArtifacts();
+ migratedStore.registerSessionArtifact(sessionManager.getSessionId(), sessionManager.getSessionArtifactDir()!);
+ await waitForCondition(
+ () => migratedStore.list().find((job) => job.id === heartbeat.id)?.status === "cancelled",
+ "Archived heartbeat was not cancelled",
+ );
+
+ expect(countWorkerDescriptors(agentDir)).toBe(0);
+ const listed = await client.request({ type: "list" });
+ expect(listed.success).toBe(true);
+ expect(
+ requireSessionList(listed.success ? listed.data : undefined).filter(
+ (session) => session.activeSessionId || session.workerPid,
+ ),
+ ).toEqual([]);
+ expect((await readSessionInfo(sessionFile))?.state).toEqual({ status: "archived" });
+
+ await client.request({ type: "shutdown" });
+ client.close();
+ await waitForSocketGone(socketPath);
+ }, 30_000);
+
+ it("cancels an orphan heartbeat instead of recreating a descriptorless active session", async () => {
+ const root = tempDir();
+ const agentDir = join(root, "agent");
+ const projectDir = join(root, "project");
+ const sessionDir = join(agentDir, "sessions");
+ const socketPath = join(tmpdir(), `prime-supervisor-orphan-cron-${process.pid}-${randomUUID().slice(0, 8)}.sock`);
+ mkdirSync(projectDir, { recursive: true });
+ const sessionManager = SessionManager.create(projectDir, sessionDir);
+ sessionManager.appendMessage({ role: "user", content: "old scheduled work", timestamp: 1 });
+ sessionManager.appendSessionState({ status: "active" });
+ const sessionFile = sessionManager.getSessionFile();
+ if (!sessionFile) {
+ throw new Error("Fixture session did not persist");
+ }
+ const cronStore = new AgentCronJobStore(getCronJobsPath(agentDir));
+ const heartbeat = cronStore.createHeartbeat({
+ activeSessionId: "deleted-worker",
+ sessionId: sessionManager.getSessionId(),
+ sessionFile,
+ cwd: projectDir,
+ scheduleText: "every 10s",
+ prompt: "continue old work",
+ now: new Date(Date.now() - 20_000),
+ });
+
+ const supervisor = spawnSupervisor(agentDir, socketPath, projectDir);
+ const client = await connectEventually(socketPath, supervisor);
+ const migratedStore = AgentCronJobStore.forSessionArtifacts();
+ migratedStore.registerSessionArtifact(sessionManager.getSessionId(), sessionManager.getSessionArtifactDir()!);
+ await waitForCondition(
+ () => migratedStore.list().find((job) => job.id === heartbeat.id)?.status === "cancelled",
+ "Orphan heartbeat was not cancelled",
+ );
+
+ expect(countWorkerDescriptors(agentDir)).toBe(0);
+ const listed = await client.request({ type: "list" });
+ expect(listed.success).toBe(true);
+ expect(
+ requireSessionList(listed.success ? listed.data : undefined).filter(
+ (session) => session.activeSessionId || session.workerPid,
+ ),
+ ).toEqual([]);
+
+ await client.request({ type: "shutdown" });
+ client.close();
+ await waitForSocketGone(socketPath);
+ }, 30_000);
+
+ it("restarts an empty supervisor without requiring a resident worker", async () => {
+ const root = tempDir();
+ const agentDir = join(root, "agent");
+ const projectDir = join(root, "project");
+ const sessionDir = join(root, "custom-sessions");
+ const socketPath = join(tmpdir(), `prime-supervisor-restart-${process.pid}-${randomUUID().slice(0, 8)}.sock`);
+ mkdirSync(projectDir, { recursive: true });
+
+ const supervisor = spawnSupervisor(agentDir, socketPath, projectDir, ["--session-dir", sessionDir, "--no-tools"]);
+ const client = await connectEventually(socketPath, supervisor);
+ const restarted = await client.request({ type: "restart" });
+ expect(restarted.success).toBe(true);
+ client.close();
+ await waitForExit(supervisor);
+ children.delete(supervisor);
+
+ const replacementClient = await connectEventually(socketPath);
+ const listed = await replacementClient.request({ type: "list" });
+ expect(listed.success).toBe(true);
+ expect(readSupervisorConfig(agentDir)).toMatchObject({
+ defaultSessionConfig: { sessionDir, noTools: true },
+ });
+ await replacementClient.request({ type: "shutdown" });
+ replacementClient.close();
+ await waitForSocketGone(socketPath);
+ });
+
+ it("survives a worker process spawn error", async () => {
+ const root = tempDir();
+ const agentDir = join(root, "agent");
+ const projectDir = join(root, "project");
+ const missingCwd = join(root, "missing-project");
+ const socketPath = join(tmpdir(), `prime-supervisor-spawn-error-${process.pid}-${randomUUID().slice(0, 8)}.sock`);
+ mkdirSync(projectDir, { recursive: true });
+
+ const supervisor = spawnSupervisor(agentDir, socketPath, projectDir);
+ const client = await connectEventually(socketPath, supervisor);
+ const failed = await client.request({
+ type: "create",
+ config: { cwd: missingCwd, agentDir, noTools: true, noExtensions: true },
+ });
+
+ expect(failed).toMatchObject({ success: false });
+ expect(supervisor.exitCode).toBeNull();
+ const listed = await client.request({ type: "list" });
+ expect(listed.success).toBe(true);
+ expect(requireSessionList(listed.success ? listed.data : undefined)).toEqual([]);
+
+ await client.request({ type: "shutdown" });
+ client.close();
+ await waitForSocketGone(socketPath);
+ });
+
+ it("archives resident roots and cancels their heartbeats on explicit daemon shutdown", async () => {
+ const root = tempDir();
+ const agentDir = join(root, "agent");
+ const projectDir = join(root, "project");
+ const sessionDir = join(agentDir, "sessions");
+ const socketPath = join(tmpdir(), `prime-supervisor-shutdown-${process.pid}-${randomUUID().slice(0, 8)}.sock`);
+ mkdirSync(projectDir, { recursive: true });
+ const sessionManager = SessionManager.create(projectDir, sessionDir);
+ sessionManager.appendMessage({ role: "user", content: "stop with daemon", timestamp: 1 });
+ sessionManager.appendSessionState({ status: "active" });
+ const sessionFile = sessionManager.getSessionFile();
+ if (!sessionFile) {
+ throw new Error("Fixture session did not persist");
+ }
+
+ const supervisor = spawnSupervisor(agentDir, socketPath, projectDir);
+ const client = await connectEventually(socketPath, supervisor);
+ const created = await client.request({
+ type: "create",
+ sessionPath: sessionFile,
+ config: { cwd: projectDir, agentDir, sessionDir, noTools: true, noExtensions: true },
+ });
+ if (!created.success) {
+ throw new Error(created.error);
+ }
+ const summary = requireSummary(created.data);
+ if (!summary.workerPid) {
+ throw new Error("Resident worker did not expose its pid");
+ }
+ workerPids.add(summary.workerPid);
+ const heartbeatResponse = await client.request({
+ type: "heartbeat_set",
+ activeSessionId: summary.activeSessionId ?? summary.id,
+ schedule: "every 1h",
+ prompt: "continue old work",
+ });
+ if (!heartbeatResponse.success || !heartbeatResponse.data || typeof heartbeatResponse.data !== "object") {
+ throw new Error(heartbeatResponse.success ? "Heartbeat response was missing data" : heartbeatResponse.error);
+ }
+ const heartbeat = (heartbeatResponse.data as { heartbeat: { id: string } }).heartbeat;
+ const cronStore = AgentCronJobStore.forSessionArtifacts();
+ cronStore.registerSessionArtifact(summary.sessionId, sessionManager.getSessionArtifactDir()!);
+
+ expect((await client.request({ type: "shutdown" })).success).toBe(true);
+ client.close();
+ await waitForSocketGone(socketPath);
+ await waitForProcessGone(summary.workerPid);
+ workerPids.delete(summary.workerPid);
+ expect(countWorkerDescriptors(agentDir)).toBe(0);
+ expect((await readSessionInfo(sessionFile))?.state).toEqual({ status: "archived" });
+ expect(cronStore.list().find((job) => job.id === heartbeat.id)).toMatchObject({ status: "cancelled" });
+
+ const replacement = spawnSupervisor(agentDir, socketPath, projectDir);
+ const replacementClient = await connectEventually(socketPath, replacement);
+ const listed = await replacementClient.request({ type: "list" });
+ expect(listed.success).toBe(true);
+ expect(
+ requireSessionList(listed.success ? listed.data : undefined).filter(
+ (session) => session.activeSessionId || session.workerPid,
+ ),
+ ).toEqual([]);
+ await replacementClient.request({ type: "shutdown" });
+ replacementClient.close();
+ await waitForSocketGone(socketPath);
+ }, 30_000);
+
+ it("does not resurrect an intentionally stopped root when the supervisor dies during kill", async () => {
+ const root = tempDir();
+ const agentDir = join(root, "agent");
+ const projectDir = join(root, "project");
+ const sessionDir = join(agentDir, "sessions");
+ const socketPath = join(tmpdir(), `prime-supervisor-stop-race-${process.pid}-${randomUUID().slice(0, 8)}.sock`);
+ mkdirSync(projectDir, { recursive: true });
+ const sessionManager = SessionManager.create(projectDir, sessionDir);
+ sessionManager.appendMessage({ role: "user", content: "stop me", timestamp: 1 });
+ sessionManager.appendSessionState({ status: "active" });
+ const sessionFile = sessionManager.getSessionFile();
+ if (!sessionFile) {
+ throw new Error("Fixture session did not persist");
+ }
+
+ const firstSupervisor = spawnSupervisor(agentDir, socketPath, projectDir);
+ const client = await connectEventually(socketPath, firstSupervisor);
+ const firstSupervisorPid = client.hello?.supervisorPid;
+ if (!firstSupervisorPid) {
+ throw new Error("Daemon hello did not expose its supervisor pid");
+ }
+ const created = await client.request({
+ type: "create",
+ sessionPath: sessionFile,
+ config: { cwd: projectDir, agentDir, sessionDir, noTools: true, noExtensions: true },
+ });
+ if (!created.success) {
+ throw new Error(created.error);
+ }
+ const summary = requireSummary(created.data);
+ if (!summary.workerPid) {
+ throw new Error("Resident worker did not expose its pid");
+ }
+ workerPids.add(summary.workerPid);
+ const activeSessionId = summary.activeSessionId ?? summary.id;
+ const heartbeatResponse = await client.request({
+ type: "heartbeat_set",
+ activeSessionId,
+ schedule: "every 1h",
+ prompt: "continue old work",
+ });
+ if (!heartbeatResponse.success || !heartbeatResponse.data || typeof heartbeatResponse.data !== "object") {
+ throw new Error(heartbeatResponse.success ? "Heartbeat response was missing data" : heartbeatResponse.error);
+ }
+ const heartbeat = (heartbeatResponse.data as { heartbeat: { id: string } }).heartbeat;
+ const cronStore = AgentCronJobStore.forSessionArtifacts();
+ cronStore.registerSessionArtifact(summary.sessionId, sessionManager.getSessionArtifactDir()!);
+ process.kill(summary.workerPid, "SIGSTOP");
+ const killResult = client.request({ type: "kill", activeSessionId }).catch((error: unknown) => error);
+ const tombstone = await waitForWorkerStopTombstone(agentDir);
+ expect(tombstone.stopRequestedAt).toEqual(expect.any(String));
+ expect(tombstone.archiveOnStop).toBe(true);
+
+ process.kill(firstSupervisorPid, "SIGKILL");
+ await waitForExit(firstSupervisor);
+ children.delete(firstSupervisor);
+ client.close();
+ await expect(killResult).resolves.toBeInstanceOf(Error);
+
+ const replacementSupervisor = spawnSupervisor(agentDir, socketPath, projectDir);
+ const replacementClient = await connectEventually(socketPath, replacementSupervisor);
+ const listed = await replacementClient.request({ type: "list" });
+ expect(listed.success).toBe(true);
+ const sessions = requireSessionList(listed.success ? listed.data : undefined);
+ expect(sessions.filter((session) => session.activeSessionId || session.workerPid)).toEqual([]);
+ await waitForProcessGone(summary.workerPid);
+ workerPids.delete(summary.workerPid);
+ await waitForCondition(
+ () => countWorkerDescriptors(agentDir) === 0,
+ "Intentional worker stop descriptor was not removed",
+ );
+ expect(countWorkerDescriptors(agentDir)).toBe(0);
+ expect((await readSessionInfo(sessionFile))?.state).toEqual({ status: "archived" });
+ expect(cronStore.list().find((job) => job.id === heartbeat.id)).toMatchObject({ status: "cancelled" });
+
+ await replacementClient.request({ type: "shutdown" });
+ replacementClient.close();
+ await waitForSocketGone(socketPath);
+ }, 30_000);
+
+ it("hosts resident roots in isolated worker processes without a session cap", async () => {
+ const root = tempDir();
+ const agentDir = join(root, "agent");
+ const projectDir = join(root, "project");
+ const sessionDir = join(agentDir, "sessions");
+ const socketPath = join(tmpdir(), `prime-supervisor-many-roots-${process.pid}-${randomUUID().slice(0, 8)}.sock`);
+ mkdirSync(projectDir, { recursive: true });
+ const sessionFiles = Array.from({ length: PROCESS_STRESS_WORKERS }, (_, index) => {
+ const manager = SessionManager.create(projectDir, sessionDir);
+ manager.appendMessage({ role: "user", content: `root ${index}`, timestamp: index + 1 });
+ const sessionFile = manager.getSessionFile();
+ if (!sessionFile) {
+ throw new Error("Fixture session did not persist");
+ }
+ return sessionFile;
+ });
+
+ const supervisor = spawnSupervisor(agentDir, socketPath, projectDir);
+ const client = await connectEventually(socketPath, supervisor);
+ const externalLease = acquireSessionLease(sessionFiles[0], agentDir, {
+ [SESSION_LEASES_ENABLED_ENV]: "1",
+ [SESSION_LEASE_OWNER_ID_ENV]: "external-owner",
+ });
+ const conflict = await client.request({
+ type: "create",
+ sessionPath: sessionFiles[0],
+ config: { cwd: projectDir, agentDir, sessionDir, noTools: true, noExtensions: true },
+ });
+ expect(conflict).toMatchObject({
+ success: false,
+ errorInfo: { code: "session_already_active", activeSessionId: "external-owner" },
+ });
+ const emptyAfterConflict = await client.request({ type: "list" });
+ expect(requireSessionList(emptyAfterConflict.success ? emptyAfterConflict.data : undefined)).toHaveLength(0);
+ externalLease?.release();
+ const created = await Promise.all(
+ sessionFiles.map((sessionPath) =>
+ client.request({
+ type: "create",
+ sessionPath,
+ config: { cwd: projectDir, agentDir, sessionDir, noTools: true, noExtensions: true },
+ }),
+ ),
+ );
+ const summaries = created.map((response) => {
+ if (!response.success) {
+ throw new Error(response.error);
+ }
+ return requireSummary(response.data);
+ });
+ const pids = summaries.map((summary) => summary.workerPid);
+ expect(new Set(pids).size).toBe(PROCESS_STRESS_WORKERS);
+ expect(pids).not.toContain(supervisor.pid);
+ for (const pid of pids) {
+ if (!pid) {
+ throw new Error("Resident root did not expose a worker pid");
+ }
+ workerPids.add(pid);
+ }
+ const firstActiveSessionId = summaries[0]!.activeSessionId ?? summaries[0]!.id;
+ const addedCron = await client.request({
+ type: "cron_add",
+ activeSessionId: firstActiveSessionId,
+ schedule: "every 1h",
+ prompt: "check status",
+ });
+ expect(addedCron.success).toBe(true);
+ const cronJob = (addedCron.success ? addedCron.data : undefined) as { job?: { id?: string } } | undefined;
+ if (!cronJob?.job?.id) {
+ throw new Error("Supervisor did not persist the cron job");
+ }
+ const listedCron = await client.request({ type: "cron_list", activeSessionId: firstActiveSessionId });
+ expect(listedCron).toMatchObject({ success: true, data: { jobs: [{ id: cronJob.job.id }] } });
+ const cancelledCron = await client.request({ type: "cron_cancel", jobId: cronJob.job.id });
+ expect(cancelledCron.success).toBe(true);
+ const activeSessionIds = summaries.map((summary) => summary.activeSessionId ?? summary.id);
+ await Promise.all(
+ activeSessionIds.map((activeSessionId) =>
+ client.request({ type: "execute_bash", activeSessionId, command: "sleep 30" }),
+ ),
+ );
+ const heartbeats = await Promise.all(
+ activeSessionIds.map((activeSessionId, index) =>
+ client.request({
+ type: "heartbeat_set",
+ activeSessionId,
+ schedule: "every 10s",
+ prompt: `heartbeat ${index}`,
+ }),
+ ),
+ );
+ expect(heartbeats.every((response) => response.success)).toBe(true);
+ await waitForCondition(
+ () => {
+ const stores = summaries.map((summary, index) => {
+ const store = AgentCronJobStore.forSessionArtifacts();
+ store.registerSessionArtifact(
+ summary.sessionId,
+ join(dirname(dirname(sessionFiles[index]!)), "session-artifacts", summary.sessionId),
+ );
+ return store;
+ });
+ return stores.every((store) => store.list().some((job) => job.lastSkippedAt !== undefined));
+ },
+ "Session workers did not advance their heartbeats independently",
+ 15_000,
+ );
+
+ const listed = await client.request({ type: "list" });
+ expect(listed.success).toBe(true);
+ expect(requireSessionList(listed.success ? listed.data : undefined)).toHaveLength(PROCESS_STRESS_WORKERS);
+ supervisor.kill("SIGTERM");
+ await waitForExit(supervisor);
+ children.delete(supervisor);
+ client.close();
+ const replacementClient = await connectEventually(socketPath);
+ const adopted = await replacementClient.request({ type: "list" });
+ expect(adopted.success).toBe(true);
+ expect(
+ new Set(requireSessionList(adopted.success ? adopted.data : undefined).map((summary) => summary.workerPid)),
+ ).toEqual(new Set(pids));
+ await replacementClient.request({ type: "shutdown" });
+ replacementClient.close();
+ await waitForSocketGone(socketPath);
+ await Promise.all(
+ pids.map(async (pid) => {
+ if (pid) {
+ await waitForProcessGone(pid);
+ workerPids.delete(pid);
+ }
+ }),
+ );
+ }, 180_000);
+
+ it("isolates a root, streams a chunked snapshot, and adopts the same worker after restart", async () => {
+ const root = tempDir();
+ const agentDir = join(root, "agent");
+ const projectDir = join(root, "project");
+ const sessionDir = join(agentDir, "sessions");
+ const socketPath = join(tmpdir(), `prime-supervisor-${process.pid}-${randomUUID().slice(0, 8)}.sock`);
+ mkdirSync(projectDir, { recursive: true });
+ const sessionManager = SessionManager.create(projectDir, sessionDir);
+ const largePrompt = `large:${"x".repeat(600 * 1024)}`;
+ sessionManager.appendMessage({ role: "user", content: largePrompt, timestamp: 1 });
+ sessionManager.appendMessage({
+ role: "assistant",
+ content: [{ type: "text", text: "done" }],
+ api: "openai-responses",
+ provider: "faux",
+ model: "faux",
+ usage: {
+ input: 0,
+ output: 0,
+ cacheRead: 0,
+ cacheWrite: 0,
+ totalTokens: 0,
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
+ },
+ stopReason: "stop",
+ timestamp: 2,
+ });
+ const sessionFile = sessionManager.getSessionFile();
+ if (!sessionFile) {
+ throw new Error("Fixture session did not persist");
+ }
+
+ const firstSupervisor = spawnSupervisor(agentDir, socketPath, projectDir);
+ const client = await connectEventually(socketPath, firstSupervisor);
+ const created = await client.request({
+ type: "create",
+ sessionPath: sessionFile,
+ config: {
+ cwd: projectDir,
+ agentDir,
+ sessionDir,
+ noTools: true,
+ noExtensions: true,
+ },
+ });
+ if (!created.success) {
+ const diagnostics = childDiagnostics.get(firstSupervisor);
+ throw new Error(
+ `${created.error}\nsupervisor stdout:\n${diagnostics?.stdout ?? ""}\nsupervisor stderr:\n${diagnostics?.stderr ?? ""}\n${readDaemonLogs(agentDir)}`,
+ );
+ }
+ expect(created.success).toBe(true);
+ const createdSummary = requireSummary(created.data);
+ expect(createdSummary.workerState).toBe("ready");
+ expect(createdSummary.workerPid).not.toBe(firstSupervisor.pid);
+ if (!createdSummary.workerPid) {
+ throw new Error("Resident worker did not expose its pid");
+ }
+ workerPids.add(createdSummary.workerPid);
+
+ const connection = await DaemonAgentConnection.attach(
+ client,
+ createdSummary.activeSessionId ?? createdSummary.id,
+ { recoverDaemon: async () => {} },
+ );
+ const connectionEvents: string[] = [];
+ const replacementMessageCounts: number[] = [];
+ connection.subscribe((event) => {
+ connectionEvents.push(event.type === "connection_status" ? `${event.type}:${event.status}` : event.type);
+ if (event.type === "session_replaced") {
+ replacementMessageCounts.push(event.messages.length);
+ }
+ });
+ const snapshot = await connection.getInitialSnapshot();
+ expect(snapshot.messages).toHaveLength(2);
+ expect(snapshot.messages[0]).toMatchObject({ role: "user", content: largePrompt });
+
+ const activeSessionId = createdSummary.activeSessionId ?? createdSummary.id;
+ const createdNew = await client.request({ type: "new_session", activeSessionId });
+ expect(createdNew.success).toBe(true);
+ const emptyReplacementDeadline = Date.now() + 5000;
+ while (!replacementMessageCounts.includes(0) && Date.now() < emptyReplacementDeadline) {
+ await new Promise((resolveDelay) => setTimeout(resolveDelay, 10));
+ }
+ expect(replacementMessageCounts).toContain(0);
+ const switchedBack = await client.request({ type: "switch_session", activeSessionId, sessionPath: sessionFile });
+ expect(switchedBack.success).toBe(true);
+ const restoredReplacementDeadline = Date.now() + 5000;
+ while (replacementMessageCounts.at(-1) !== 2 && Date.now() < restoredReplacementDeadline) {
+ await new Promise((resolveDelay) => setTimeout(resolveDelay, 10));
+ }
+ expect(replacementMessageCounts.at(-1)).toBe(2);
+
+ firstSupervisor.kill("SIGTERM");
+ await waitForExit(firstSupervisor);
+ children.delete(firstSupervisor);
+
+ const reconnectDeadline = Date.now() + 15_000;
+ while (!connectionEvents.includes("connection_status:connected") && Date.now() < reconnectDeadline) {
+ await new Promise((resolveDelay) => setTimeout(resolveDelay, 25));
+ }
+ expect(connectionEvents).toContain("connection_status:reconnecting");
+ expect(connectionEvents).toContain("session_resynced");
+ expect(connectionEvents).toContain("connection_status:connected");
+ expect(connectionEvents).not.toContain("closed");
+ await expect(connection.getState()).resolves.toMatchObject({
+ activeSessionId: createdSummary.activeSessionId,
+ sessionId: createdSummary.sessionId,
+ });
+ const listed = await client.request({ type: "list", all: true, sessionDir });
+ expect(listed.success).toBe(true);
+ if (!listed.success) {
+ throw new Error(listed.error);
+ }
+ const adopted = requireSessionList(listed.data).find(
+ (summary) => (summary.activeSessionId ?? summary.id) === (createdSummary.activeSessionId ?? createdSummary.id),
+ );
+ expect(adopted).toMatchObject({
+ workerState: "ready",
+ workerPid: createdSummary.workerPid,
+ });
+
+ const descriptor = readWorkerDescriptor(agentDir);
+ const bashStarted = await client.request({
+ type: "execute_bash",
+ activeSessionId,
+ command: "sleep 60",
+ });
+ expect(bashStarted.success).toBe(true);
+ if (!descriptor.orphanProcessJournalPath) {
+ throw new Error("Resident worker did not persist its orphan-process journal path");
+ }
+ let orphanPids: number[] = [];
+ const orphanDeadline = Date.now() + 5000;
+ while (orphanPids.length === 0 && Date.now() < orphanDeadline) {
+ orphanPids = readActiveOrphanProcesses(descriptor.orphanProcessJournalPath, descriptor.pid).map(
+ (orphan) => orphan.pid,
+ );
+ if (orphanPids.length === 0) {
+ await new Promise((resolveDelay) => setTimeout(resolveDelay, 10));
+ }
+ }
+ expect(orphanPids.length).toBeGreaterThan(0);
+ for (const pid of orphanPids) {
+ workerPids.add(pid);
+ }
+ process.kill(createdSummary.workerPid, "SIGKILL");
+ await waitForProcessGone(createdSummary.workerPid);
+ workerPids.delete(createdSummary.workerPid);
+ await Promise.all(orphanPids.map((pid) => waitForProcessGone(pid)));
+ for (const pid of orphanPids) {
+ workerPids.delete(pid);
+ }
+
+ let recovered: SessionSummary | undefined;
+ const recoveryDeadline = Date.now() + 20_000;
+ while (Date.now() < recoveryDeadline) {
+ const response = await client.request({ type: "list" });
+ if (response.success) {
+ recovered = requireSessionList(response.data).find(
+ (summary) =>
+ (summary.activeSessionId ?? summary.id) === (createdSummary.activeSessionId ?? createdSummary.id),
+ );
+ if (recovered?.workerState === "ready" && recovered.workerPid !== createdSummary.workerPid) {
+ break;
+ }
+ }
+ await new Promise((resolveDelay) => setTimeout(resolveDelay, 50));
+ }
+ expect(recovered).toMatchObject({ workerState: "ready", activeSessionId: createdSummary.activeSessionId });
+ if (!recovered?.workerPid) {
+ throw new Error("Recovered worker did not expose its pid");
+ }
+ workerPids.add(recovered.workerPid);
+ expect(readFileSync(sessionFile, "utf8")).toContain("prime-agent.worker_recovery");
+ await expect(connection.getState()).resolves.toMatchObject({ sessionId: createdSummary.sessionId });
+
+ await connection.dispose();
+ await client.request({ type: "shutdown" });
+ client.close();
+ await waitForSocketGone(socketPath);
+ await waitForProcessGone(recovered.workerPid);
+ workerPids.delete(recovered.workerPid);
+ });
+
+ it("runs a session-artifact cron job while the supervisor is being replaced", async () => {
+ const root = tempDir();
+ const agentDir = join(root, "agent");
+ const projectDir = join(root, "project");
+ const sessionDir = join(agentDir, "sessions");
+ const socketPath = join(tmpdir(), `prime-worker-cron-${process.pid}-${randomUUID().slice(0, 8)}.sock`);
+ mkdirSync(projectDir, { recursive: true });
+ const sessionManager = SessionManager.create(projectDir, sessionDir);
+ sessionManager.appendMessage({ role: "user", content: "scheduled work", timestamp: 1 });
+ sessionManager.appendSessionState({ status: "active" });
+ const sessionFile = sessionManager.getSessionFile();
+ const artifactDir = sessionManager.getSessionArtifactDir();
+ if (!sessionFile || !artifactDir) {
+ throw new Error("Fixture session did not persist");
+ }
+
+ const supervisor = spawnSupervisor(agentDir, socketPath, projectDir);
+ const client = await connectEventually(socketPath, supervisor);
+ const created = await client.request({
+ type: "create",
+ sessionPath: sessionFile,
+ config: { cwd: projectDir, agentDir, sessionDir, noTools: true, noExtensions: true },
+ });
+ if (!created.success) {
+ throw new Error(created.error);
+ }
+ const summary = requireSummary(created.data);
+ if (!summary.workerPid) {
+ throw new Error("Resident worker did not expose its pid");
+ }
+ workerPids.add(summary.workerPid);
+ const bashStarted = await client.request({
+ type: "execute_bash",
+ activeSessionId: summary.activeSessionId ?? summary.id,
+ command: "sleep 30",
+ });
+ expect(bashStarted.success).toBe(true);
+ const scheduled = await client.request({
+ type: "heartbeat_set",
+ activeSessionId: summary.activeSessionId ?? summary.id,
+ schedule: "every 10s",
+ prompt: "continue without the supervisor",
+ });
+ if (!scheduled.success || !scheduled.data || typeof scheduled.data !== "object") {
+ throw new Error(scheduled.success ? "Heartbeat response was missing its job" : scheduled.error);
+ }
+ const job = (scheduled.data as { heartbeat: { id: string } }).heartbeat;
+
+ client.close();
+ supervisor.kill("SIGKILL");
+ await waitForExit(supervisor);
+ children.delete(supervisor);
+
+ const store = AgentCronJobStore.forSessionArtifacts();
+ store.registerSessionArtifact(sessionManager.getSessionId(), artifactDir);
+ await waitForCondition(
+ () => store.list().find((candidate) => candidate.id === job.id)?.lastSkippedAt !== undefined,
+ "Resident worker did not advance its heartbeat without the supervisor",
+ 15_000,
+ );
+ expect(store.list().find((candidate) => candidate.id === job.id)).toBeDefined();
+
+ const replacement = await connectEventually(socketPath);
+ await replacement.request({ type: "shutdown" });
+ replacement.close();
+ await waitForSocketGone(socketPath);
+ await waitForProcessGone(summary.workerPid);
+ workerPids.delete(summary.workerPid);
+ }, 30_000);
+});
diff --git a/packages/coding-agent/test/daemon-supervisor-side-question.test.ts b/packages/coding-agent/test/daemon-supervisor-side-question.test.ts
new file mode 100644
index 0000000000..a52c8e028a
--- /dev/null
+++ b/packages/coding-agent/test/daemon-supervisor-side-question.test.ts
@@ -0,0 +1,54 @@
+import { describe, expect, it, vi } from "vitest";
+import type { DaemonSocketClient } from "../src/modes/daemon/active-session-state.js";
+import type { DaemonCommand, DaemonResponse } from "../src/modes/daemon/daemon-protocol.js";
+import { DaemonSupervisor } from "../src/modes/daemon/daemon-supervisor.js";
+
+interface SupervisorHarness {
+ handleLine(client: DaemonSocketClient, line: string): Promise<void>;
+}
+
+describe("daemon supervisor side-question routing", () => {
+ it("accepts start and abort commands before forwarding them to a worker", async () => {
+ const handleCommand = vi.fn(
+ async (_client: DaemonSocketClient, command: DaemonCommand): Promise<DaemonResponse> => ({
+ id: command.id,
+ type: "response",
+ command: command.type,
+ success: true,
+ }),
+ );
+ const write = vi.fn();
+ const supervisor = Object.assign(Object.create(DaemonSupervisor.prototype), {
+ ready: Promise.resolve(),
+ handleCommand,
+ write,
+ log: vi.fn(),
+ }) as SupervisorHarness;
+ const client = { id: "client-1" } as DaemonSocketClient;
+ const commands = [
+ {
+ id: "start-1",
+ type: "start_side_question",
+ activeSessionId: "active-1",
+ sideQuestionId: "question-1",
+ question: "What changed?",
+ },
+ {
+ id: "abort-1",
+ type: "abort_side_question",
+ activeSessionId: "active-1",
+ sideQuestionId: "question-1",
+ },
+ ] satisfies DaemonCommand[];
+
+ for (const command of commands) {
+ await supervisor.handleLine(client, JSON.stringify(command));
+ }
+
+ expect(handleCommand.mock.calls.map((call) => call[1])).toEqual(commands);
+ expect(write.mock.calls.map((call) => call[1])).toEqual([
+ expect.objectContaining({ command: "start_side_question", success: true }),
+ expect.objectContaining({ command: "abort_side_question", success: true }),
+ ]);
+ });
+});
diff --git a/packages/coding-agent/test/fixtures/owned-session-worker-fixture.ts b/packages/coding-agent/test/fixtures/owned-session-worker-fixture.ts
new file mode 100644
index 0000000000..c80f51a74c
--- /dev/null
+++ b/packages/coding-agent/test/fixtures/owned-session-worker-fixture.ts
@@ -0,0 +1,95 @@
+import { existsSync, writeFileSync } from "node:fs";
+import {
+ closeOwnedSessionWorkerOwnerWatch,
+ installOwnedSessionWorkerOwnerWatch,
+ maybeRunOwnedSessionWorkerFrontend,
+} from "../../src/cli/owned-session-worker.js";
+import { attachJsonlLineReader, serializeJsonLine } from "../../src/modes/rpc/jsonl.js";
+
+const args = process.argv.slice(2);
+const pidPath = process.env.PRIME_AGENT_TEST_OWNED_PID_PATH;
+installOwnedSessionWorkerOwnerWatch();
+
+if (process.env.PRIME_AGENT_INTERNAL_OWNED_WORKER === "1") {
+ if (pidPath) {
+ writeFileSync(pidPath, `${process.pid}\n`);
+ writeFileSync(`${pidPath}.ppid`, `${process.ppid}\n`);
+ process.once("SIGTERM", () => {
+ writeFileSync(`${pidPath}.terminated`, "terminated\n");
+ process.exit(0);
+ });
+ }
+ if (process.env.PRIME_AGENT_TEST_KEEP_ALIVE === "1") {
+ setInterval(() => {}, 1000);
+ }
+ if (args.includes("--mode") && args.includes("rpc")) {
+ const reversedCommands: Array<{ id?: string; type: string; marker?: string }> = [];
+ const outputResponse = (command: { id?: string; type: string; marker?: string }) => {
+ process.stdout.write(
+ serializeJsonLine({
+ ...(command.id ? { id: command.id } : {}),
+ type: "response",
+ command: command.type,
+ success: true,
+ ...(command.marker ? { marker: command.marker } : {}),
+ }),
+ );
+ };
+ attachJsonlLineReader(process.stdin, (line) => {
+ const command = JSON.parse(line) as { id?: string; type: string; marker?: string };
+ if (process.env.PRIME_AGENT_TEST_EXIT_ZERO_ON_COMMAND === command.type) {
+ process.exit(0);
+ }
+ if (process.env.PRIME_AGENT_TEST_CRASH_ON_COMMAND === command.type) {
+ process.exit(1);
+ }
+ if (command.type === "ack_result") {
+ if (process.env.PRIME_AGENT_TEST_CRASH_ON_ACK === "1" && pidPath && !existsSync(`${pidPath}.crashed`)) {
+ writeFileSync(`${pidPath}.crashed`, "crashed\n");
+ const recoveryPath = process.env.PRIME_AGENT_INTERNAL_OWNED_RECOVERY_DESCRIPTOR;
+ if (recoveryPath) {
+ writeFileSync(
+ recoveryPath,
+ `${JSON.stringify({
+ version: 1,
+ profile: "rpc",
+ sessionId: "fixture-session",
+ sessionFile: `${pidPath}.jsonl`,
+ cwd: process.cwd(),
+ updatedAt: new Date().toISOString(),
+ })}\n`,
+ );
+ }
+ process.exit(1);
+ }
+ return;
+ }
+ if (process.env.PRIME_AGENT_TEST_INVALID_RPC_OUTPUT === "1") {
+ process.stdout.write("truncated-json\n");
+ process.stdout.write("null\n");
+ }
+ if (process.env.PRIME_AGENT_TEST_REVERSE_RPC_RESPONSES === "1") {
+ reversedCommands.push(command);
+ if (reversedCommands.length === 2) {
+ for (const pending of reversedCommands.reverse()) {
+ outputResponse(pending);
+ }
+ }
+ return;
+ }
+ outputResponse(command);
+ });
+ process.stdin.once("end", closeOwnedSessionWorkerOwnerWatch);
+ process.stdin.resume();
+ } else {
+ process.stdin.pipe(process.stdout);
+ if (process.env.PRIME_AGENT_TEST_KEEP_ALIVE !== "1") {
+ process.stdin.once("end", closeOwnedSessionWorkerOwnerWatch);
+ }
+ }
+} else {
+ if (pidPath) {
+ writeFileSync(`${pidPath}.frontend`, `${process.pid}\n`);
+ }
+ await maybeRunOwnedSessionWorkerFrontend(args);
+}
diff --git a/packages/coding-agent/test/interactive-mode-status.test.ts b/packages/coding-agent/test/interactive-mode-status.test.ts
index 2dc494cb47..cb511d8da2 100644
--- a/packages/coding-agent/test/interactive-mode-status.test.ts
+++ b/packages/coding-agent/test/interactive-mode-status.test.ts
@@ -24,7 +24,9 @@ import type {
AgentConnectionModel,
AgentConnectionResourceDiagnostic,
AgentConnectionResourceSnapshot,
+ AgentConnectionRlmChildAgentSnapshot,
AgentConnectionSessionEvent,
+ AgentConnectionSnapshot,
AgentConnectionSourceInfo,
AgentConnectionState,
} from "../src/modes/agent-connection/types.js";
@@ -32,7 +34,12 @@ import { AgentActivityTracker } from "../src/modes/interactive/agent-activity.js
import { BashExecutionComponent } from "../src/modes/interactive/components/bash-execution.js";
import type { ModelSelectorComponent } from "../src/modes/interactive/components/model-selector.js";
import type { ToolExecutionComponent } from "../src/modes/interactive/components/tool-execution.js";
-import { formatSplashCwd, InteractiveMode, truncatePathMiddle } from "../src/modes/interactive/interactive-mode.js";
+import {
+ formatSplashCwd,
+ InteractiveMode,
+ mergeChildAgentSnapshots,
+ truncatePathMiddle,
+} from "../src/modes/interactive/interactive-mode.js";
import { initTheme } from "../src/modes/interactive/theme/theme.js";
function renderLastLine(container: Container, width = 120): string {
@@ -99,6 +106,54 @@ function createConnectionState(overrides: Partial<AgentConnectionState> = {}): A
};
}
+describe("mergeChildAgentSnapshots", () => {
+ const rich: AgentConnectionRlmChildAgentSnapshot = {
+ id: "child-1",
+ activeSessionId: "active-child-1",
+ label: "Inspect the scheduler",
+ status: "running",
+ durationMs: 5_000,
+ answerPreview: "Reading the queue",
+ toolUseCount: 4,
+ tokenCount: 41_000,
+ recap: "Tracing dispatch",
+ sessionDir: "/tmp/child-1",
+ activity: { kind: "executing", toolName: "ipython" },
+ };
+
+ test("preserves rich live fields when a daemon resync is sparse", () => {
+ const merged = mergeChildAgentSnapshots(rich, {
+ id: "child-1",
+ label: "Inspect the scheduler",
+ status: "running",
+ sessionDir: "/tmp/child-1",
+ });
+
+ expect(merged).toMatchObject({
+ activeSessionId: "active-child-1",
+ durationMs: 5_000,
+ answerPreview: "Reading the queue",
+ toolUseCount: 4,
+ tokenCount: 41_000,
+ recap: "Tracing dispatch",
+ activity: { kind: "executing", toolName: "ipython" },
+ });
+ });
+
+ test("clears transient activity when the child finishes", () => {
+ const merged = mergeChildAgentSnapshots(rich, {
+ id: "child-1",
+ label: "Inspect the scheduler",
+ status: "done",
+ sessionDir: "/tmp/child-1",
+ });
+
+ expect(merged.activity).toBeUndefined();
+ expect(merged.toolUseCount).toBe(4);
+ expect(merged.tokenCount).toBe(41_000);
+ });
+});
+
describe("InteractiveMode update notifications", () => {
beforeAll(() => {
initTheme("dark");
@@ -612,6 +667,45 @@ describe("InteractiveMode pending bash components", () => {
});
describe("InteractiveMode connection events", () => {
+ test("restores in-flight assistant state on every session render", async () => {
+ const streamingMessage = {
+ role: "assistant",
+ content: [{ type: "text", text: "still streaming" }],
+ } as AgentConnectionSnapshot["streamingMessage"];
+ const snapshots: AgentConnectionSnapshot[] = [
+ { state: createConnectionState(), messages: [] },
+ { state: createConnectionState({ isStreaming: true }), messages: [], streamingMessage },
+ ];
+ const restoreStreamingMessageFromSnapshot = vi.fn(async () => {});
+ const fakeThis = {
+ agentConnection: { getInitialSnapshot: vi.fn(async () => snapshots.shift()!) },
+ getSessionContextFromConnectionSnapshot: vi.fn(() => ({
+ messages: [],
+ thinkingLevel: "medium",
+ model: null,
+ })),
+ seedChildAgentInspector: vi.fn(),
+ setSessionHasMessages: vi.fn(),
+ applyConnectionStateSnapshot: vi.fn(),
+ renderSessionContext: vi.fn(async () => {}),
+ restoreStreamingMessageFromSnapshot,
+ showStatus: vi.fn(),
+ } as unknown as InteractiveMode;
+
+ const renderInitialMessages = (
+ InteractiveMode.prototype as unknown as { renderInitialMessages(this: InteractiveMode): Promise<void> }
+ ).renderInitialMessages;
+ await renderInitialMessages.call(fakeThis);
+ await renderInitialMessages.call(fakeThis);
+
+ expect(
+ (fakeThis as unknown as { agentConnection: { getInitialSnapshot: ReturnType<typeof vi.fn> } }).agentConnection
+ .getInitialSnapshot,
+ ).toHaveBeenCalledTimes(2);
+ expect(restoreStreamingMessageFromSnapshot).toHaveBeenNthCalledWith(1, undefined);
+ expect(restoreStreamingMessageFromSnapshot).toHaveBeenNthCalledWith(2, streamingMessage);
+ });
+
test("clears extension UI when a connection-backed session is replaced", async () => {
type SessionReplacedEvent = { type: "session_replaced"; state: AgentConnectionState; messages: [] };
let listener: ((event: SessionReplacedEvent) => Promise<void> | void) | undefined;
@@ -651,10 +745,160 @@ describe("InteractiveMode connection events", () => {
expect(resetRenderOrder).toBeLessThan(rebindOrder);
expect(rebindOrder).toBeLessThan(renderMessagesOrder);
expect(fakeThis.applyConnectionStateSnapshot).toHaveBeenCalledWith(state);
+ expect(fakeThis.resetCurrentSessionRenderState).toHaveBeenCalledWith({ clearPromptStash: true });
expect(fakeThis.rebindCurrentSession).toHaveBeenCalledWith();
expect(fakeThis.renderInitialMessages).toHaveBeenCalledWith();
expect(fakeThis.ui.requestRender).toHaveBeenCalledWith();
});
+
+ test("resynchronizes transcript state without destructive session teardown", async () => {
+ type SessionResyncedEvent = {
+ type: "session_resynced";
+ snapshot: { state: AgentConnectionState; messages: [] };
+ };
+ let listener: ((event: SessionResyncedEvent) => Promise<void> | void) | undefined;
+ const fakeThis = {
+ agentConnection: {
+ subscribe: vi.fn((callback) => {
+ listener = callback;
+ return vi.fn();
+ }),
+ },
+ sessionEventQueue: Promise.resolve(),
+ renderResyncedSession: vi.fn(async () => {}),
+ resetSideQuestion: vi.fn(),
+ resetExtensionUI: vi.fn(),
+ resetCurrentSessionRenderState: vi.fn(),
+ rebindCurrentSession: vi.fn(),
+ ui: { requestRender: vi.fn() },
+ handleEvent: vi.fn(),
+ handleConnectionExtensionUiRequest: vi.fn(),
+ showError: vi.fn(),
+ };
+
+ (InteractiveMode.prototype as unknown as { subscribeToAgent(this: typeof fakeThis): void }).subscribeToAgent.call(
+ fakeThis,
+ );
+
+ const snapshot = { state: createConnectionState(), messages: [] as [] };
+ await listener?.({ type: "session_resynced", snapshot });
+
+ expect(fakeThis.renderResyncedSession).toHaveBeenCalledWith(snapshot);
+ expect(fakeThis.resetSideQuestion).not.toHaveBeenCalled();
+ expect(fakeThis.resetExtensionUI).not.toHaveBeenCalled();
+ expect(fakeThis.resetCurrentSessionRenderState).not.toHaveBeenCalled();
+ expect(fakeThis.rebindCurrentSession).not.toHaveBeenCalled();
+ });
+
+ test("preserves client-local work while rendering a resynchronized snapshot", async () => {
+ const compactionQueue = [{ text: "send after compaction", mode: "followUp" as const }];
+ const sideQuestion = { id: "side-1", status: "running" };
+ const extensionRequests = new Map([["request-1", { cancelLocal: vi.fn() }]]);
+ const activeBashComponent = {};
+ const streamingMessage = {
+ role: "assistant",
+ content: [{ type: "thinking", thinking: "Still reasoning" }],
+ } as AgentConnectionSnapshot["streamingMessage"];
+ const snapshot: AgentConnectionSnapshot = {
+ state: createConnectionState({ isCompacting: true, isBashRunning: true, isStreaming: true }),
+ messages: [],
+ streamingMessage,
+ };
+ const startAssistantStreamingMessage = vi.fn();
+ const restoreStreamingMessageFromSnapshot = vi.fn((message: AgentConnectionSnapshot["streamingMessage"]) => {
+ if (message?.role === "assistant") {
+ startAssistantStreamingMessage(message);
+ }
+ });
+ const fakeThis = {
+ compactionQueuedMessages: compactionQueue,
+ sideQuestionEvent: sideQuestion,
+ activeConnectionExtensionUiRequests: extensionRequests,
+ activeBashComponent,
+ isAgentCompacting: () => true,
+ isBashRunning: () => true,
+ streamingComponent: {},
+ streamingMessage: {},
+ applyConnectionStateSnapshot: vi.fn(),
+ replaceChildAgentInspector: vi.fn(),
+ getSessionContextFromConnectionSnapshot: vi.fn(() => ({
+ messages: [],
+ thinkingLevel: "medium",
+ model: null,
+ })),
+ renderSessionContext: vi.fn(async () => {}),
+ restoreStreamingMessageFromSnapshot,
+ refreshConnectionQueue: vi.fn(async () => {}),
+ flushCompactionQueue: vi.fn(async () => {}),
+ flushPendingBashComponents: vi.fn(),
+ updateTerminalTitle: vi.fn(),
+ setGoalAnnouncementBaseline: vi.fn(),
+ syncGoalTray: vi.fn(),
+ syncWorkingLoader: vi.fn(),
+ getGoalState: () => emptyGoalState(),
+ } as unknown as InteractiveMode;
+
+ await (
+ InteractiveMode.prototype as unknown as {
+ renderResyncedSession(this: unknown, value: AgentConnectionSnapshot): Promise<void>;
+ }
+ ).renderResyncedSession.call(fakeThis, snapshot);
+
+ expect((fakeThis as unknown as { compactionQueuedMessages: unknown }).compactionQueuedMessages).toBe(
+ compactionQueue,
+ );
+ expect((fakeThis as unknown as { sideQuestionEvent: unknown }).sideQuestionEvent).toBe(sideQuestion);
+ expect(
+ (fakeThis as unknown as { activeConnectionExtensionUiRequests: unknown }).activeConnectionExtensionUiRequests,
+ ).toBe(extensionRequests);
+ expect((fakeThis as unknown as { activeBashComponent: unknown }).activeBashComponent).toBe(activeBashComponent);
+ expect(startAssistantStreamingMessage).toHaveBeenCalledWith(streamingMessage);
+ });
+
+ test("finishes local compaction and bash UI when a resync proves the operations ended", async () => {
+ const bashComponent = { setComplete: vi.fn() };
+ const flushCompactionQueue = vi.fn(async () => {});
+ const flushPendingBashComponents = vi.fn();
+ const snapshot: AgentConnectionSnapshot = {
+ state: createConnectionState({ isCompacting: false, isBashRunning: false, isStreaming: false }),
+ messages: [],
+ };
+ const fakeThis = {
+ activeBashComponent: bashComponent,
+ streamingComponent: {},
+ streamingMessage: {},
+ isAgentCompacting: () => true,
+ isBashRunning: () => true,
+ applyConnectionStateSnapshot: vi.fn(),
+ replaceChildAgentInspector: vi.fn(),
+ getSessionContextFromConnectionSnapshot: vi.fn(() => ({
+ messages: [],
+ thinkingLevel: "medium",
+ model: null,
+ })),
+ renderSessionContext: vi.fn(async () => {}),
+ restoreStreamingMessageFromSnapshot: vi.fn(),
+ refreshConnectionQueue: vi.fn(async () => {}),
+ flushCompactionQueue,
+ flushPendingBashComponents,
+ updateTerminalTitle: vi.fn(),
+ setGoalAnnouncementBaseline: vi.fn(),
+ syncGoalTray: vi.fn(),
+ syncWorkingLoader: vi.fn(),
+ getGoalState: () => emptyGoalState(),
+ } as unknown as InteractiveMode;
+
+ await (
+ InteractiveMode.prototype as unknown as {
+ renderResyncedSession(this: unknown, value: AgentConnectionSnapshot): Promise<void>;
+ }
+ ).renderResyncedSession.call(fakeThis, snapshot);
+
+ expect(flushCompactionQueue).toHaveBeenCalledWith({ willRetry: false });
+ expect(bashComponent.setComplete).toHaveBeenCalledWith(undefined, false);
+ expect((fakeThis as unknown as { activeBashComponent: unknown }).activeBashComponent).toBeUndefined();
+ expect(flushPendingBashComponents).toHaveBeenCalledOnce();
+ });
});
describe("InteractiveMode connection extension UI", () => {
diff --git a/packages/coding-agent/test/marquee-components.test.ts b/packages/coding-agent/test/marquee-components.test.ts
index 5a1d3bfbce..b2e374defc 100644
--- a/packages/coding-agent/test/marquee-components.test.ts
+++ b/packages/coding-agent/test/marquee-components.test.ts
@@ -455,8 +455,8 @@ describe("marquee TUI components", () => {
const summaryText = summaryLines.join("\n");
expect(summaryText).toContain("agents-sidebar");
expect(summaryText).toContain("37% context left");
- expect(summaryText).toContain("Subagent 1");
- expect(summaryText).toContain("inspect training logs");
+ expect(summaryText).toContain("S1");
+ expect(summaryText).toContain("inspect training l…");
const infoRow = summary.render(90)[0] ?? "";
expect(visibleWidth(infoRow)).toBe(90);
@@ -563,7 +563,7 @@ describe("marquee TUI components", () => {
expect(visibleWidth(infoRow)).toBe(32);
expect(stripAnsi(infoRow)).toContain("Pursuing goal");
// The subagent itself renders as a list row below the info line.
- expect(stripAnsi(lines.join("\n"))).toContain("Subagent 1");
+ expect(stripAnsi(lines.join("\n"))).toContain("S1");
});
test("renders full child agent detail without internal scroll controls", () => {
diff --git a/packages/coding-agent/test/orphan-process-journal.test.ts b/packages/coding-agent/test/orphan-process-journal.test.ts
new file mode 100644
index 0000000000..af60218b25
--- /dev/null
+++ b/packages/coding-agent/test/orphan-process-journal.test.ts
@@ -0,0 +1,47 @@
+import { existsSync, mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterEach, describe, expect, it } from "vitest";
+import {
+ clearOrphanProcessJournal,
+ isOrphanProcessIdentityCurrent,
+ ORPHAN_PROCESS_JOURNAL_ENV,
+ readActiveOrphanProcesses,
+ recordOrphanProcessState,
+} from "../src/core/orphan-process-journal.js";
+
+const tempDirs: string[] = [];
+const originalJournalPath = process.env[ORPHAN_PROCESS_JOURNAL_ENV];
+
+afterEach(() => {
+ if (originalJournalPath === undefined) {
+ delete process.env[ORPHAN_PROCESS_JOURNAL_ENV];
+ } else {
+ process.env[ORPHAN_PROCESS_JOURNAL_ENV] = originalJournalPath;
+ }
+ for (const directory of tempDirs.splice(0)) {
+ rmSync(directory, { recursive: true, force: true });
+ }
+});
+
+describe("orphan process journal", () => {
+ it("retains only detached processes still active for the crashed owner", () => {
+ const directory = mkdtempSync(join(tmpdir(), "prime-orphan-journal-test-"));
+ tempDirs.push(directory);
+ const path = join(directory, "orphans.jsonl");
+ process.env[ORPHAN_PROCESS_JOURNAL_ENV] = path;
+
+ recordOrphanProcessState(process.pid, true);
+
+ const active = readActiveOrphanProcesses(path, process.pid);
+ expect(active).toHaveLength(1);
+ expect(active[0]?.pid).toBe(process.pid);
+ expect(active[0] && isOrphanProcessIdentityCurrent(active[0])).toBe(true);
+ expect(readActiveOrphanProcesses(path, process.pid + 1)).toEqual([]);
+
+ recordOrphanProcessState(process.pid, false);
+ expect(readActiveOrphanProcesses(path, process.pid)).toEqual([]);
+ clearOrphanProcessJournal(path);
+ expect(existsSync(path)).toBe(false);
+ });
+});
diff --git a/packages/coding-agent/test/owned-session-worker-process.test.ts b/packages/coding-agent/test/owned-session-worker-process.test.ts
new file mode 100644
index 0000000000..caa81149fb
--- /dev/null
+++ b/packages/coding-agent/test/owned-session-worker-process.test.ts
@@ -0,0 +1,296 @@
+import { type ChildProcess, spawn } from "node:child_process";
+import { existsSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join, resolve } from "node:path";
+import { afterEach, describe, expect, it } from "vitest";
+
+const fixturePath = resolve(__dirname, "fixtures/owned-session-worker-fixture.ts");
+const tsxPath = resolve(__dirname, "../../../node_modules/tsx/dist/cli.mjs");
+const tempDirs: string[] = [];
+const children = new Set<ChildProcess>();
+const workerPids = new Set<number>();
+const frontendPids = new Set<number>();
+
+afterEach(async () => {
+ for (const child of children) {
+ if (child.exitCode === null && child.signalCode === null) {
+ child.kill("SIGKILL");
+ }
+ }
+ children.clear();
+ for (const pid of frontendPids) {
+ try {
+ process.kill(pid, "SIGKILL");
+ } catch {
+ // Already gone.
+ }
+ }
+ frontendPids.clear();
+ for (const pid of workerPids) {
+ try {
+ process.kill(pid, "SIGKILL");
+ } catch {
+ // Already gone.
+ }
+ }
+ workerPids.clear();
+ for (const directory of tempDirs.splice(0)) {
+ rmSync(directory, { recursive: true, force: true });
+ }
+});
+
+function spawnFrontend(
+ args: string[],
+ pidPath: string,
+ keepAlive = false,
+ environment: NodeJS.ProcessEnv = {},
+): ChildProcess {
+ const child = spawn(process.execPath, [tsxPath, fixturePath, ...args], {
+ env: {
+ ...process.env,
+ ...environment,
+ PRIME_AGENT_TEST_OWNED_PID_PATH: pidPath,
+ ...(keepAlive ? { PRIME_AGENT_TEST_KEEP_ALIVE: "1" } : {}),
+ TSX_TSCONFIG_PATH: resolve(__dirname, "../../../tsconfig.json"),
+ },
+ stdio: ["pipe", "pipe", "pipe"],
+ });
+ children.add(child);
+ return child;
+}
+
+async function waitForWorkerPid(path: string): Promise<number> {
+ const deadline = Date.now() + 10_000;
+ while (Date.now() < deadline) {
+ if (existsSync(path)) {
+ const pid = Number(readFileSync(path, "utf8").trim());
+ if (Number.isInteger(pid) && pid > 0) {
+ workerPids.add(pid);
+ return pid;
+ }
+ }
+ await new Promise((resolveDelay) => setTimeout(resolveDelay, 10));
+ }
+ throw new Error("Owned worker did not publish its pid");
+}
+
+async function waitForReplacementWorkerPid(path: string, previousPid: number): Promise<number> {
+ const deadline = Date.now() + 10_000;
+ while (Date.now() < deadline) {
+ if (existsSync(path)) {
+ const pid = Number(readFileSync(path, "utf8").trim());
+ if (Number.isInteger(pid) && pid > 0 && pid !== previousPid) {
+ workerPids.add(pid);
+ return pid;
+ }
+ }
+ await new Promise((resolveDelay) => setTimeout(resolveDelay, 10));
+ }
+ throw new Error("Owned replacement worker did not publish its pid");
+}
+
+async function waitForExit(child: ChildProcess): Promise<{ code: number | null; signal: NodeJS.Signals | null }> {
+ if (child.exitCode !== null || child.signalCode !== null) {
+ return { code: child.exitCode, signal: child.signalCode as NodeJS.Signals | null };
+ }
+ return new Promise((resolveExit, reject) => {
+ const timeout = setTimeout(() => reject(new Error("Timed out waiting for frontend exit")), 10_000);
+ child.once("exit", (code, signal) => {
+ clearTimeout(timeout);
+ resolveExit({ code, signal });
+ });
+ });
+}
+
+async function waitForProcessGone(pid: number): Promise<void> {
+ const deadline = Date.now() + 10_000;
+ while (Date.now() < deadline) {
+ try {
+ process.kill(pid, 0);
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === "ESRCH") {
+ workerPids.delete(pid);
+ return;
+ }
+ }
+ await new Promise((resolveDelay) => setTimeout(resolveDelay, 10));
+ }
+ throw new Error(`Owned worker ${pid} remained alive`);
+}
+
+describe("owned session worker processes", () => {
+ it("keeps RPC framing in the frontend and exits its worker on stdin EOF", async () => {
+ const root = mkdtempSync(join(tmpdir(), "prime-owned-worker-test-"));
+ tempDirs.push(root);
+ const pidPath = join(root, "worker.pid");
+ const frontend = spawnFrontend(["--mode", "rpc"], pidPath);
+ let stdout = "";
+ frontend.stdout?.on("data", (chunk: Buffer) => {
+ stdout += chunk.toString("utf8");
+ });
+ frontend.stdin?.end(`${JSON.stringify({ id: "request-1", type: "get_state" })}\n`);
+ const workerPid = await waitForWorkerPid(pidPath);
+ const exit = await waitForExit(frontend);
+ children.delete(frontend);
+
+ expect(exit).toEqual({ code: 0, signal: null });
+ expect(stdout).toBe(
+ `${JSON.stringify({ id: "request-1", type: "response", command: "get_state", success: true })}\n`,
+ );
+ await waitForProcessGone(workerPid);
+ });
+
+ it("correlates overlapping anonymous RPC commands without exposing internal ids", async () => {
+ const root = mkdtempSync(join(tmpdir(), "prime-owned-worker-test-"));
+ tempDirs.push(root);
+ const pidPath = join(root, "worker.pid");
+ const frontend = spawnFrontend(["--mode", "rpc"], pidPath, false, {
+ PRIME_AGENT_TEST_REVERSE_RPC_RESPONSES: "1",
+ });
+ let stdout = "";
+ frontend.stdout?.on("data", (chunk: Buffer) => {
+ stdout += chunk.toString("utf8");
+ });
+ frontend.stdin?.end(
+ `${JSON.stringify({ type: "get_state", marker: "first" })}\n${JSON.stringify({ type: "get_state", marker: "second" })}\n`,
+ );
+ const workerPid = await waitForWorkerPid(pidPath);
+ const exit = await waitForExit(frontend);
+ children.delete(frontend);
+
+ expect(exit).toEqual({ code: 0, signal: null });
+ expect(stdout).toBe(
+ `${JSON.stringify({ type: "response", command: "get_state", success: true, marker: "second" })}\n${JSON.stringify({ type: "response", command: "get_state", success: true, marker: "first" })}\n`,
+ );
+ await waitForProcessGone(workerPid);
+ });
+
+ it("drops malformed worker output instead of corrupting public RPC JSONL", async () => {
+ const root = mkdtempSync(join(tmpdir(), "prime-owned-worker-test-"));
+ tempDirs.push(root);
+ const pidPath = join(root, "worker.pid");
+ const frontend = spawnFrontend(["--mode", "rpc"], pidPath, false, {
+ PRIME_AGENT_TEST_INVALID_RPC_OUTPUT: "1",
+ });
+ let stdout = "";
+ frontend.stdout?.on("data", (chunk: Buffer) => {
+ stdout += chunk.toString("utf8");
+ });
+ frontend.stdin?.end(`${JSON.stringify({ id: "request-1", type: "get_state" })}\n`);
+ const workerPid = await waitForWorkerPid(pidPath);
+ const exit = await waitForExit(frontend);
+ children.delete(frontend);
+
+ expect(exit).toEqual({ code: 0, signal: null });
+ expect(stdout).toBe(
+ `${JSON.stringify({ id: "request-1", type: "response", command: "get_state", success: true })}\n`,
+ );
+ await waitForProcessGone(workerPid);
+ });
+
+ it("does not fabricate a recovery response for response-less acknowledgements", async () => {
+ const root = mkdtempSync(join(tmpdir(), "prime-owned-worker-test-"));
+ tempDirs.push(root);
+ const pidPath = join(root, "worker.pid");
+ const frontend = spawnFrontend(["--mode", "rpc"], pidPath, false, {
+ PRIME_AGENT_TEST_CRASH_ON_ACK: "1",
+ });
+ let stdout = "";
+ frontend.stdout?.on("data", (chunk: Buffer) => {
+ stdout += chunk.toString("utf8");
+ });
+ const workerPid = await waitForWorkerPid(pidPath);
+ frontend.stdin?.write(`${JSON.stringify({ type: "ack_result", commandId: "command-1" })}\n`);
+ const replacementPid = await waitForReplacementWorkerPid(pidPath, workerPid);
+ frontend.stdin?.end(`${JSON.stringify({ id: "request-1", type: "get_state" })}\n`);
+ const exit = await waitForExit(frontend);
+ children.delete(frontend);
+
+ expect(exit).toEqual({ code: 0, signal: null });
+ expect(stdout).toBe(
+ `${JSON.stringify({ id: "request-1", type: "response", command: "get_state", success: true })}\n`,
+ );
+ await waitForProcessGone(workerPid);
+ await waitForProcessGone(replacementPid);
+ });
+
+ it("fails pending RPC commands when stdin closes before the worker crashes", async () => {
+ const root = mkdtempSync(join(tmpdir(), "prime-owned-worker-test-"));
+ tempDirs.push(root);
+ const pidPath = join(root, "worker.pid");
+ const frontend = spawnFrontend(["--mode", "rpc"], pidPath, false, {
+ PRIME_AGENT_TEST_CRASH_ON_COMMAND: "get_state",
+ });
+ let stdout = "";
+ frontend.stdout?.on("data", (chunk: Buffer) => {
+ stdout += chunk.toString("utf8");
+ });
+ frontend.stdin?.end(`${JSON.stringify({ id: "request-1", type: "get_state" })}\n`);
+ const workerPid = await waitForWorkerPid(pidPath);
+ const exit = await waitForExit(frontend);
+ children.delete(frontend);
+
+ expect(exit).toEqual({ code: 1, signal: null });
+ expect(stdout).toBe(
+ `${JSON.stringify({
+ id: "request-1",
+ type: "response",
+ command: "get_state",
+ success: false,
+ error: "The isolated session worker stopped during this command; its result is uncertain and was not replayed",
+ })}\n`,
+ );
+ await waitForProcessGone(workerPid);
+ });
+
+ it("fails pending RPC commands when the worker exits successfully without responding", async () => {
+ const root = mkdtempSync(join(tmpdir(), "prime-owned-worker-test-"));
+ tempDirs.push(root);
+ const pidPath = join(root, "worker.pid");
+ const frontend = spawnFrontend(["--mode", "rpc"], pidPath, false, {
+ PRIME_AGENT_TEST_EXIT_ZERO_ON_COMMAND: "get_state",
+ });
+ let stdout = "";
+ frontend.stdout?.on("data", (chunk: Buffer) => {
+ stdout += chunk.toString("utf8");
+ });
+ frontend.stdin?.end(`${JSON.stringify({ id: "request-1", type: "get_state" })}\n`);
+ const workerPid = await waitForWorkerPid(pidPath);
+ const exit = await waitForExit(frontend);
+ children.delete(frontend);
+
+ expect(exit).toEqual({ code: 1, signal: null });
+ expect(stdout).toBe(
+ `${JSON.stringify({
+ id: "request-1",
+ type: "response",
+ command: "get_state",
+ success: false,
+ error: "The isolated session worker stopped during this command; its result is uncertain and was not replayed",
+ })}\n`,
+ );
+ await waitForProcessGone(workerPid);
+ });
+
+ it("terminates the owned worker when its frontend is killed", async () => {
+ const root = mkdtempSync(join(tmpdir(), "prime-owned-worker-test-"));
+ tempDirs.push(root);
+ const pidPath = join(root, "worker.pid");
+ const frontend = spawnFrontend(["-p", "hello"], pidPath, true);
+ const workerPid = await waitForWorkerPid(pidPath);
+ const frontendPid = Number(readFileSync(`${pidPath}.frontend`, "utf8").trim());
+ frontendPids.add(frontendPid);
+ expect(Number(readFileSync(`${pidPath}.ppid`, "utf8").trim())).toBe(frontendPid);
+
+ process.kill(frontendPid, "SIGKILL");
+ await waitForExit(frontend);
+ children.delete(frontend);
+ frontendPids.delete(frontendPid);
+ const terminationDeadline = Date.now() + 5000;
+ while (!existsSync(`${pidPath}.terminated`) && Date.now() < terminationDeadline) {
+ await new Promise((resolveDelay) => setTimeout(resolveDelay, 10));
+ }
+ expect(existsSync(`${pidPath}.terminated`)).toBe(true);
+ await waitForProcessGone(workerPid);
+ });
+});
diff --git a/packages/coding-agent/test/owned-session-worker.test.ts b/packages/coding-agent/test/owned-session-worker.test.ts
new file mode 100644
index 0000000000..68318a17a3
--- /dev/null
+++ b/packages/coding-agent/test/owned-session-worker.test.ts
@@ -0,0 +1,50 @@
+import { describe, expect, it } from "vitest";
+import {
+ classifyOwnedSessionWorkerInvocation,
+ createOwnedWorkerLaunchSpec,
+ createRpcRecoveryArgs,
+} from "../src/cli/owned-session-worker.js";
+
+describe("owned session worker CLI routing", () => {
+ it("routes every headless surface to an owned worker", () => {
+ expect(classifyOwnedSessionWorkerInvocation(["-p", "hello"], true, {})).toBe("print");
+ expect(classifyOwnedSessionWorkerInvocation([], false, {})).toBe("print");
+ expect(classifyOwnedSessionWorkerInvocation(["--mode", "json", "hello"], true, {})).toBe("json");
+ expect(classifyOwnedSessionWorkerInvocation(["--mode", "rpc"], true, {})).toBe("rpc");
+ expect(classifyOwnedSessionWorkerInvocation(["--no-session"], true, {})).toBe("interactive-ephemeral");
+ });
+
+ it("leaves resident interactive and non-session operations in the frontend", () => {
+ expect(classifyOwnedSessionWorkerInvocation([], true, {})).toBeUndefined();
+ expect(classifyOwnedSessionWorkerInvocation(["--mode", "daemon"], false, {})).toBeUndefined();
+ expect(classifyOwnedSessionWorkerInvocation(["--help"], false, {})).toBeUndefined();
+ expect(classifyOwnedSessionWorkerInvocation(["--version"], false, {})).toBeUndefined();
+ expect(classifyOwnedSessionWorkerInvocation(["--list-models"], false, {})).toBeUndefined();
+ expect(classifyOwnedSessionWorkerInvocation(["--export", "session.jsonl"], false, {})).toBeUndefined();
+ expect(classifyOwnedSessionWorkerInvocation(["daemon", "list"], false, {})).toBeUndefined();
+ });
+
+ it("does not recursively route an owned worker", () => {
+ expect(
+ classifyOwnedSessionWorkerInvocation(["--mode", "rpc"], true, {
+ PRIME_AGENT_INTERNAL_OWNED_WORKER: "1",
+ }),
+ ).toBeUndefined();
+ });
+
+ it("preserves the current runtime flags and CLI entrypoint", () => {
+ expect(createOwnedWorkerLaunchSpec(["--mode", "rpc"], "/node", ["--loader", "tsx"], "/cli.ts")).toEqual({
+ command: "/node",
+ args: ["--loader", "tsx", "/cli.ts", "--mode", "rpc"],
+ });
+ });
+
+ it("restarts RPC against the exact persisted session without changing public flags", () => {
+ expect(
+ createRpcRecoveryArgs(
+ ["--mode", "rpc", "--continue", "--resume", "/old.jsonl", "--model", "openai/gpt-5"],
+ "/current.jsonl",
+ ),
+ ).toEqual(["--mode", "rpc", "--model", "openai/gpt-5", "--resume", "/current.jsonl"]);
+ });
+});
diff --git a/packages/coding-agent/test/package-self-update-daemon.test.ts b/packages/coding-agent/test/package-self-update-daemon.test.ts
index 10420350c3..0323c75aca 100644
--- a/packages/coding-agent/test/package-self-update-daemon.test.ts
+++ b/packages/coding-agent/test/package-self-update-daemon.test.ts
@@ -160,6 +160,10 @@ vi.mock("../src/modes/daemon/daemon-client.js", () => ({
mockState.calls.push(`daemon-connect:${this.socketPath}`);
}
+ async waitForHello(): Promise<{ protocol: { version: number } }> {
+ return { protocol: { version: 2 } };
+ }
+
async request(request: MockDaemonRequest): Promise<MockDaemonResponse> {
mockState.calls.push(`daemon-request:${request.type}`);
mockState.requestPayloads.push(request);
diff --git a/packages/coding-agent/test/session-artifacts-delete.test.ts b/packages/coding-agent/test/session-artifacts-delete.test.ts
index 10be78ac3f..2f2a370c50 100644
--- a/packages/coding-agent/test/session-artifacts-delete.test.ts
+++ b/packages/coding-agent/test/session-artifacts-delete.test.ts
@@ -27,6 +27,7 @@ describe("deleteSessionFile removes the session artifact directory", () => {
mkdirSync(artifactDir, { recursive: true });
writeFileSync(join(artifactDir, "kernel-state.dill"), "payload");
writeFileSync(join(artifactDir, "kernel-state.json"), "{}");
+ writeFileSync(join(artifactDir, "scheduled-jobs.json"), '{"jobs":[],"dispatches":[]}\n');
const result = await deleteSessionFile(sessionPath);
diff --git a/packages/coding-agent/test/session-lease.test.ts b/packages/coding-agent/test/session-lease.test.ts
new file mode 100644
index 0000000000..9b232243a9
--- /dev/null
+++ b/packages/coding-agent/test/session-lease.test.ts
@@ -0,0 +1,154 @@
+import { createHash } from "node:crypto";
+import { mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join, resolve } from "node:path";
+import { lockSync } from "proper-lockfile";
+import { afterEach, describe, expect, it } from "vitest";
+import {
+ acquireSessionLease,
+ canonicalSessionPath,
+ SESSION_LEASE_OWNER_ID_ENV,
+ SESSION_LEASES_ENABLED_ENV,
+ SessionAlreadyActiveError,
+} from "../src/core/session-lease.js";
+
+const tempDirs: string[] = [];
+
+afterEach(() => {
+ for (const directory of tempDirs.splice(0)) {
+ rmSync(directory, { recursive: true, force: true });
+ }
+});
+
+function createTempDir(): string {
+ const directory = mkdtempSync(join(tmpdir(), "prime-session-lease-test-"));
+ tempDirs.push(directory);
+ return directory;
+}
+
+function enabledEnvironment(owner: string): NodeJS.ProcessEnv {
+ return {
+ [SESSION_LEASES_ENABLED_ENV]: "1",
+ [SESSION_LEASE_OWNER_ID_ENV]: owner,
+ };
+}
+
+describe("session leases", () => {
+ it("rejects a second live owner with a typed active-session error", () => {
+ const agentDir = createTempDir();
+ const sessionPath = join(agentDir, "session.jsonl");
+ const first = acquireSessionLease(sessionPath, agentDir, enabledEnvironment("resident-a"));
+
+ expect(() => acquireSessionLease(sessionPath, agentDir, enabledEnvironment("owned-b"))).toThrow(
+ SessionAlreadyActiveError,
+ );
+ try {
+ acquireSessionLease(sessionPath, agentDir, enabledEnvironment("owned-b"));
+ } catch (error) {
+ expect(error).toMatchObject({
+ code: "session_already_active",
+ activeSessionId: "resident-a",
+ sessionPath: canonicalSessionPath(sessionPath),
+ });
+ }
+
+ first?.release();
+ const second = acquireSessionLease(sessionPath, agentDir, enabledEnvironment("owned-b"));
+ expect(second?.sessionPath).toBe(canonicalSessionPath(sessionPath));
+ second?.release();
+ });
+
+ it("reclaims a lease whose owner process is gone", () => {
+ const agentDir = createTempDir();
+ const sessionPath = canonicalSessionPath(resolve(agentDir, "stale.jsonl"));
+ const key = createHash("sha256").update(sessionPath).digest("hex");
+ const lockDirectory = join(agentDir, "session-leases", `${key}.lock`);
+ mkdirSync(lockDirectory, { recursive: true });
+ writeFileSync(
+ join(lockDirectory, "owner.json"),
+ JSON.stringify({
+ version: 1,
+ token: "stale",
+ pid: 2_147_483_647,
+ activeSessionId: "dead-owner",
+ sessionPath,
+ createdAt: new Date(0).toISOString(),
+ }),
+ );
+
+ const lease = acquireSessionLease(sessionPath, agentDir, enabledEnvironment("replacement"));
+ expect(lease?.sessionPath).toBe(sessionPath);
+ lease?.release();
+ });
+
+ it("reports guard contention as a coordination failure", () => {
+ const agentDir = createTempDir();
+ const sessionPath = canonicalSessionPath(join(agentDir, "session.jsonl"));
+ const key = createHash("sha256").update(sessionPath).digest("hex");
+ const leaseRoot = join(agentDir, "session-leases");
+ const lockDirectory = join(leaseRoot, `${key}.lock`);
+ mkdirSync(leaseRoot, { recursive: true });
+ const release = lockSync(lockDirectory, {
+ realpath: false,
+ lockfilePath: `${lockDirectory}.guard`,
+ stale: 5000,
+ });
+
+ try {
+ let thrown: unknown;
+ try {
+ acquireSessionLease(sessionPath, agentDir, enabledEnvironment("resident-a"));
+ } catch (error) {
+ thrown = error;
+ }
+ expect(thrown).toBeInstanceOf(Error);
+ expect(thrown).not.toBeInstanceOf(SessionAlreadyActiveError);
+ expect((thrown as Error).message).toContain("Could not coordinate session lease");
+ } finally {
+ release();
+ }
+ });
+
+ it("treats symlink aliases as the same persisted session", () => {
+ const agentDir = createTempDir();
+ const sessionPath = join(agentDir, "session.jsonl");
+ const aliasPath = join(agentDir, "session-alias.jsonl");
+ writeFileSync(sessionPath, "");
+ symlinkSync(sessionPath, aliasPath);
+ const first = acquireSessionLease(sessionPath, agentDir, enabledEnvironment("resident-a"));
+
+ expect(() => acquireSessionLease(aliasPath, agentDir, enabledEnvironment("owned-b"))).toThrow(
+ SessionAlreadyActiveError,
+ );
+ first?.release();
+ });
+
+ it("reclaims a lease after its pid has been reused", () => {
+ const agentDir = createTempDir();
+ const sessionPath = canonicalSessionPath(resolve(agentDir, "reused-pid.jsonl"));
+ const key = createHash("sha256").update(sessionPath).digest("hex");
+ const lockDirectory = join(agentDir, "session-leases", `${key}.lock`);
+ mkdirSync(lockDirectory, { recursive: true });
+ writeFileSync(
+ join(lockDirectory, "owner.json"),
+ JSON.stringify({
+ version: 1,
+ token: "stale",
+ pid: process.pid,
+ processStartId: "different-process",
+ activeSessionId: "old-owner",
+ sessionPath,
+ createdAt: new Date(0).toISOString(),
+ }),
+ );
+
+ const lease = acquireSessionLease(sessionPath, agentDir, enabledEnvironment("replacement"));
+ expect(lease?.sessionPath).toBe(sessionPath);
+ lease?.release();
+ });
+
+ it("is inert for direct SDK runtimes unless worker isolation enables it", () => {
+ const agentDir = createTempDir();
+ expect(acquireSessionLease(join(agentDir, "session.jsonl"), agentDir, {})).toBeUndefined();
+ });
+});
diff --git a/packages/coding-agent/test/session-worker-private-framing.test.ts b/packages/coding-agent/test/session-worker-private-framing.test.ts
new file mode 100644
index 0000000000..ebb6116f3a
--- /dev/null
+++ b/packages/coding-agent/test/session-worker-private-framing.test.ts
@@ -0,0 +1,84 @@
+import { PassThrough } from "node:stream";
+import { describe, expect, it } from "vitest";
+import {
+ encodePrivateFrame,
+ PrivateFrameDecoder,
+ PrivateFramedChannel,
+ type PrivateFrameHeaderValidator,
+} from "../src/modes/session-worker/private-framing.js";
+
+interface TestHeader {
+ type: string;
+ requestId?: string;
+}
+
+const isTestHeader: PrivateFrameHeaderValidator<TestHeader> = (value: unknown): value is TestHeader => {
+ if (!value || typeof value !== "object") {
+ return false;
+ }
+ const candidate = value as { type?: unknown; requestId?: unknown };
+ return (
+ typeof candidate.type === "string" &&
+ (candidate.requestId === undefined || typeof candidate.requestId === "string")
+ );
+};
+
+describe("private worker framing", () => {
+ it("decodes headers and opaque payloads across arbitrary chunk boundaries", () => {
+ const first = encodePrivateFrame({ type: "event", requestId: "one" }, Buffer.from([0, 1, 2, 255]));
+ const second = encodePrivateFrame({ type: "response", requestId: "two" }, Buffer.from("payload"));
+ const combined = Buffer.concat([first, second]);
+ const decoder = new PrivateFrameDecoder(isTestHeader);
+ const frames = [];
+
+ for (let offset = 0; offset < combined.length; offset += 3) {
+ frames.push(...decoder.push(combined.subarray(offset, offset + 3)));
+ }
+ decoder.finish();
+
+ expect(frames).toEqual([
+ { header: { type: "event", requestId: "one" }, payload: Buffer.from([0, 1, 2, 255]) },
+ { header: { type: "response", requestId: "two" }, payload: Buffer.from("payload") },
+ ]);
+ });
+
+ it("rejects invalid lengths, JSON, and routing headers", () => {
+ const oversized = Buffer.alloc(8);
+ oversized.writeUInt32BE(1025, 0);
+ expect(() =>
+ new PrivateFrameDecoder(isTestHeader, { maxHeaderBytes: 1024, maxPayloadBytes: 1024 }).push(oversized),
+ ).toThrow("Invalid private frame header length");
+
+ const invalidJson = Buffer.concat([Buffer.from([0, 0, 0, 1, 0, 0, 0, 0]), Buffer.from("{")]);
+ expect(() => new PrivateFrameDecoder(isTestHeader).push(invalidJson)).toThrow(
+ "Invalid private frame header JSON",
+ );
+
+ const invalidHeader = encodePrivateFrame({ missing: "type" }, Buffer.alloc(0));
+ expect(() => new PrivateFrameDecoder(isTestHeader).push(invalidHeader)).toThrow(
+ "Invalid private frame routing header",
+ );
+ });
+
+ it("reports an incomplete trailing frame", () => {
+ const decoder = new PrivateFrameDecoder(isTestHeader);
+ decoder.push(encodePrivateFrame({ type: "event" }, Buffer.from("body")).subarray(0, 9));
+ expect(() => decoder.finish()).toThrow("incomplete bytes");
+ });
+
+ it("sends frames through a duplex channel without interpreting payload bytes", async () => {
+ const stream = new PassThrough();
+ const channel = new PrivateFramedChannel(stream, isTestHeader);
+ const received = new Promise<{ header: TestHeader; payload: Buffer }>((resolve) => {
+ channel.onFrame(resolve);
+ });
+
+ await channel.send({ type: "snapshot", requestId: "request" }, Buffer.from([9, 8, 7]));
+
+ await expect(received).resolves.toEqual({
+ header: { type: "snapshot", requestId: "request" },
+ payload: Buffer.from([9, 8, 7]),
+ });
+ channel.close();
+ });
+});
diff --git a/packages/coding-agent/test/snapshot-transcript-cache.test.ts b/packages/coding-agent/test/snapshot-transcript-cache.test.ts
new file mode 100644
index 0000000000..02b102d3fc
--- /dev/null
+++ b/packages/coding-agent/test/snapshot-transcript-cache.test.ts
@@ -0,0 +1,100 @@
+import { mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import type { AgentMessage } from "@earendil-works/pi-agent-core";
+import { afterEach, describe, expect, it } from "vitest";
+import { SnapshotTranscriptCache } from "../src/modes/daemon/snapshot-transcript-cache.js";
+
+const tempDirs: string[] = [];
+
+afterEach(() => {
+ for (const directory of tempDirs.splice(0)) {
+ rmSync(directory, { recursive: true, force: true });
+ }
+});
+
+function tempDir(): string {
+ const directory = mkdtempSync(join(tmpdir(), "snapshot-cache-test-"));
+ tempDirs.push(directory);
+ return directory;
+}
+
+function messages(count: number, chars: number): AgentMessage[] {
+ return Array.from({ length: count }, (_, index) => ({
+ role: "user" as const,
+ content: `${index}:${"x".repeat(chars)}`,
+ timestamp: index,
+ }));
+}
+
+describe("snapshot transcript cache", () => {
+ it("encodes transcript chunks as directly forwardable JSONL", () => {
+ const cache = new SnapshotTranscriptCache({
+ activeSessionId: "active-a",
+ snapshotId: "snapshot-a",
+ messages: messages(5, 80),
+ cacheRoot: tempDir(),
+ targetChunkBytes: 200,
+ });
+
+ expect(cache.chunkCount).toBeGreaterThan(1);
+ const decoded = Array.from({ length: cache.chunkCount }, (_, index) =>
+ JSON.parse(cache.readChunk(index).toString("utf8")),
+ );
+ expect(decoded.flatMap((chunk) => chunk.messages)).toEqual(messages(5, 80));
+ expect(decoded.map((chunk) => chunk.index)).toEqual(decoded.map((_, index) => index));
+ cache.dispose();
+ });
+
+ it("moves caches above the memory threshold to files", () => {
+ const cache = new SnapshotTranscriptCache({
+ activeSessionId: "active-b",
+ snapshotId: "snapshot-b",
+ messages: messages(6, 100),
+ cacheRoot: tempDir(),
+ targetChunkBytes: 180,
+ memoryCacheBytes: 300,
+ });
+
+ expect(cache.fileBacked).toBe(true);
+ expect(cache.readChunk(0).toString("utf8")).toContain('"session_snapshot_chunk"');
+ cache.dispose();
+ });
+
+ it("streams opaque worker chunks to waiting attachments", async () => {
+ const cache = new SnapshotTranscriptCache({
+ activeSessionId: "active-c",
+ snapshotId: "snapshot-c",
+ cacheRoot: tempDir(),
+ });
+ const firstChunk = cache.waitForChunk(0);
+ const encoded = Buffer.from(
+ '{"type":"session_snapshot_chunk","activeSessionId":"active-c","snapshotId":"snapshot-c","index":0,"messages":[]}\n',
+ );
+ cache.appendEncodedChunk(encoded);
+ await expect(firstChunk).resolves.toEqual(encoded);
+
+ const end = cache.waitForChunk(1);
+ cache.markComplete();
+ await expect(end).resolves.toBeUndefined();
+ cache.dispose();
+ });
+
+ it("defers disposal until active snapshot readers finish", () => {
+ const cache = new SnapshotTranscriptCache({
+ activeSessionId: "active-d",
+ snapshotId: "snapshot-d",
+ messages: messages(3, 80),
+ cacheRoot: tempDir(),
+ targetChunkBytes: 150,
+ });
+ const release = cache.retain();
+ const firstChunk = cache.readChunk(0);
+
+ cache.dispose();
+
+ expect(cache.readChunk(0)).toEqual(firstChunk);
+ release();
+ expect(() => cache.readChunk(0)).toThrow("Unknown snapshot transcript chunk");
+ });
+});
diff --git a/packages/coding-agent/test/subagent-tree-view.test.ts b/packages/coding-agent/test/subagent-tree-view.test.ts
deleted file mode 100644
index bccfece5e3..0000000000
--- a/packages/coding-agent/test/subagent-tree-view.test.ts
+++ /dev/null
@@ -1,185 +0,0 @@
-import { setKeybindings } from "@earendil-works/pi-tui";
-import stripAnsi from "strip-ansi";
-import { beforeAll, describe, expect, test } from "vitest";
-import { KeybindingsManager } from "../src/core/keybindings.js";
-import type { ChildAgentInspectorNode } from "../src/modes/interactive/components/child-agent-inspector.js";
-import { SubagentTreeView } from "../src/modes/interactive/components/subagent-tree-view.js";
-import { initTheme } from "../src/modes/interactive/theme/theme.js";
-
-function node(overrides: Partial<ChildAgentInspectorNode> & { id: string }): ChildAgentInspectorNode {
- return {
- label: overrides.id,
- status: "running",
- sessionDir: `/tmp/${overrides.id}`,
- ...overrides,
- };
-}
-
-function renderText(view: SubagentTreeView, width = 100): string {
- return stripAnsi(view.render(width).join("\n"));
-}
-
-describe("SubagentTreeView", () => {
- beforeAll(() => {
- initTheme("dark");
- setKeybindings(new KeybindingsManager());
- });
-
- test("renders nothing when there are no live subagents", () => {
- const view = new SubagentTreeView();
- expect(view.render(100)).toEqual([]);
- expect(view.hasNodes()).toBe(false);
- });
-
- test("only in-flight subagents show; finished ones disappear", () => {
- const view = new SubagentTreeView();
- view.setNodes([
- node({ id: "a", status: "running" }),
- node({ id: "b", status: "queued" }),
- node({ id: "done", status: "done" }),
- node({ id: "err", status: "error" }),
- ]);
- expect(view.hasNodes()).toBe(true);
- const text = renderText(view);
- // running + queued counted; done/error dropped entirely.
- expect(text).toContain("Running 2 agents…");
- expect(text).not.toContain("done");
- expect(text).not.toContain("err");
- });
-
- test("includes in-flight nested subagents from the children tree", () => {
- const view = new SubagentTreeView();
- view.setNodes([
- node({
- id: "parent",
- label: "parent",
- status: "running",
- children: [
- node({ id: "child-run", label: "nested running", status: "running" }),
- node({ id: "child-done", label: "nested done", status: "done" }),
- ],
- }),
- ]);
- const text = renderText(view);
- // parent + nested running counted; nested done dropped.
- expect(text).toContain("Running 2 agents…");
- expect(text).toContain("nested running");
- expect(text).not.toContain("nested done");
- });
-
- test("shows a running nested subagent even when its parent has finished", () => {
- const view = new SubagentTreeView();
- view.setNodes([
- node({
- id: "parent",
- label: "parent",
- status: "done",
- children: [node({ id: "child-run", label: "nested running", status: "running" })],
- }),
- ]);
- const text = renderText(view);
- expect(text).toContain("Running 1 agent…");
- expect(text).toContain("nested running");
- expect(text).not.toContain("parent");
- });
-
- test("disappears once every subagent is done", () => {
- const view = new SubagentTreeView();
- view.setNodes([node({ id: "a", status: "done" }), node({ id: "b", status: "cancelled" })]);
- expect(view.render(100)).toEqual([]);
- });
-
- test("header pluralizes on the live count", () => {
- const view = new SubagentTreeView();
- view.setNodes([node({ id: "a" })]);
- expect(renderText(view)).toContain("Running 1 agent…");
- view.setNodes([node({ id: "a" }), node({ id: "b" })]);
- expect(renderText(view)).toContain("Running 2 agents…");
- });
-
- test("opens with a blank line and a single-space left pad", () => {
- const view = new SubagentTreeView();
- view.setNodes([node({ id: "x", label: "scout", recap: "looking" })]);
- const lines = view.render(100).map((line) => stripAnsi(line));
- expect(lines[0]).toBe(""); // spacing above so it doesn't hug the tool call
- expect(lines[1]).toBe(" Running 1 agent…"); // one-space left padding
- expect(lines.slice(2).every((line) => line.startsWith(" "))).toBe(true);
- });
-
- test("every node is two lines: summary then recap", () => {
- const view = new SubagentTreeView();
- view.setNodes([
- node({
- id: "x",
- label: "Angle A scan",
- toolUseCount: 22,
- tokenCount: 41000,
- recap: "Searching for 6 patterns",
- }),
- ]);
- const text = renderText(view);
- expect(text).toContain("Angle A scan · 22 tool uses · 41k tokens");
- expect(text).toContain("Searching for 6 patterns");
- });
-
- test("falls back to a live activity label until the recap lands", () => {
- const view = new SubagentTreeView();
- // No activity yet -> Waiting.
- view.setNodes([node({ id: "x", label: "scout" })]);
- // header + blank + 2 node lines = 4
- expect(view.render(100)).toHaveLength(4);
- expect(renderText(view)).toContain("Waiting");
-
- // A tool still running -> Executing <tool>.
- view.setNodes([node({ id: "x", label: "scout", activity: { kind: "executing", toolName: "Bash" } })]);
- expect(renderText(view)).toContain("Executing Bash");
-
- // Assistant text streaming -> Writing.
- view.setNodes([node({ id: "x", label: "scout", activity: { kind: "writing" } })]);
- expect(renderText(view)).toContain("Writing");
-
- // Queued -> Waiting regardless of activity.
- view.setNodes([
- node({ id: "x", label: "scout", status: "queued", activity: { kind: "executing", toolName: "Bash" } }),
- ]);
- expect(renderText(view)).toContain("Waiting");
- });
-
- test("the recap wins over the activity label once present", () => {
- const view = new SubagentTreeView();
- view.setNodes([
- node({
- id: "x",
- label: "scout",
- recap: "Searching for 6 patterns",
- activity: { kind: "executing", toolName: "Bash" },
- }),
- ]);
- const text = renderText(view);
- expect(text).toContain("Searching for 6 patterns");
- expect(text).not.toContain("Executing");
- });
-
- test("animates the working icon — frames differ as the pulse advances", () => {
- const view = new SubagentTreeView();
- view.setNodes([node({ id: "x", label: "scout" })]);
- // The icon is read from the process-wide pulse frame at render time; the
- // summary line carries one of the working icon glyphs.
- const summaryLine = stripAnsi(view.render(100)[2] ?? "");
- expect(summaryLine).toMatch(/[◇◈◆]/);
- });
-
- test("caps the label to a few words", () => {
- const view = new SubagentTreeView();
- view.setNodes([node({ id: "x", label: "find every place the parser touches the old config schema" })]);
- const text = renderText(view);
- expect(text).toContain("find every place the…");
- expect(text).not.toContain("schema");
- });
-
- test("caps at five nodes with a +N more line", () => {
- const view = new SubagentTreeView();
- view.setNodes(Array.from({ length: 7 }, (_, i) => node({ id: `run-${i}`, label: `run-${i}` })));
- expect(renderText(view)).toContain("+2 more"); // 7 live, 5 shown
- });
-});
diff --git a/packages/coding-agent/test/suite/agent-session-autonomous.test.ts b/packages/coding-agent/test/suite/agent-session-autonomous.test.ts
index 92668e17b0..a9299e03c0 100644
--- a/packages/coding-agent/test/suite/agent-session-autonomous.test.ts
+++ b/packages/coding-agent/test/suite/agent-session-autonomous.test.ts
@@ -1,5 +1,5 @@
import { execFileSync } from "node:child_process";
-import { readFileSync, rmSync, writeFileSync } from "node:fs";
+import { existsSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { fauxAssistantMessage } from "@earendil-works/pi-ai";
import { afterEach, describe, expect, it } from "vitest";
@@ -30,6 +30,17 @@ async function waitForProcessExit(pid: number, timeoutMs = 2000): Promise<boolea
return !isProcessRunning(pid);
}
+async function waitForPidFile(path: string, timeoutMs = 2000): Promise<number> {
+ const deadline = Date.now() + timeoutMs;
+ while (!existsSync(path) && Date.now() < deadline) {
+ await new Promise<void>((resolve) => setTimeout(resolve, 25));
+ }
+ if (!existsSync(path)) {
+ throw new Error(`Timed out waiting for process ID file: ${path}`);
+ }
+ return Number.parseInt(readFileSync(path, "utf8"), 10);
+}
+
describe("AgentSession autonomous mode", () => {
const harnesses: Harness[] = [];
@@ -451,6 +462,40 @@ describe("AgentSession autonomous mode", () => {
}
});
+ it("terminates an autonomous gate without mutating retry state when the session is aborted", async () => {
+ const gate = `${process.execPath} -e "const fs=require('fs'); fs.writeFileSync('gate.pid', String(process.pid)); setTimeout(() => {}, 60000)"`;
+ const harness = await createHarness({
+ autonomous: {
+ enabled: true,
+ maxContinuations: 1,
+ gates: { commands: [gate], maxRetries: 1 },
+ },
+ });
+ harnesses.push(harness);
+ execFileSync("git", ["init"], { cwd: harness.tempDir, stdio: "ignore" });
+ const pidFile = join(harness.tempDir, "gate.pid");
+ let gatePid: number | undefined;
+ try {
+ harness.setResponses([fauxAssistantMessage("Done.")]);
+
+ const prompt = harness.session.prompt("make the change");
+ gatePid = await waitForPidFile(pidFile);
+ await harness.session.abort();
+ await prompt;
+
+ expect(await waitForProcessExit(gatePid)).toBe(true);
+ expect(harness.session.getAutonomousStatus()).toMatchObject({
+ continuationsUsed: 0,
+ gateAttempts: {},
+ lastGateFailure: undefined,
+ });
+ } finally {
+ if (gatePid && isProcessRunning(gatePid)) {
+ process.kill(gatePid, "SIGKILL");
+ }
+ }
+ });
+
it("stops autonomous continuation once gate retries are exhausted", async () => {
const state = createAutonomousRuntimeState({
enabled: true,
diff --git a/packages/coding-agent/test/suite/regressions/3885-subagent-runtime-host.test.ts b/packages/coding-agent/test/suite/regressions/3885-subagent-runtime-host.test.ts
index f73435cce5..eec8f415c4 100644
--- a/packages/coding-agent/test/suite/regressions/3885-subagent-runtime-host.test.ts
+++ b/packages/coding-agent/test/suite/regressions/3885-subagent-runtime-host.test.ts
@@ -3,7 +3,7 @@ import { tmpdir } from "node:os";
import { join } from "node:path";
import { setTimeout as sleep } from "node:timers/promises";
import { fauxAssistantMessage, registerFauxProvider } from "@earendil-works/pi-ai";
-import { afterEach, describe, expect, it } from "vitest";
+import { afterEach, describe, expect, it, vi } from "vitest";
import {
AgentSessionRuntime,
type CreateAgentSessionRuntimeFactory,
@@ -13,6 +13,12 @@ import {
} from "../../../src/core/agent-session-runtime.js";
import { AuthStorage } from "../../../src/core/auth-storage.js";
import { ModelRegistry } from "../../../src/core/model-registry.js";
+import {
+ acquireSessionLease,
+ SESSION_LEASE_OWNER_ID_ENV,
+ SESSION_LEASES_ENABLED_ENV,
+ SessionAlreadyActiveError,
+} from "../../../src/core/session-lease.js";
import { SessionManager } from "../../../src/core/session-manager.js";
async function waitFor(condition: () => boolean): Promise<void> {
@@ -32,11 +38,14 @@ describe("ENG-3885 subagent runtime host", () => {
while (cleanups.length > 0) {
await cleanups.pop()?.();
}
+ vi.unstubAllEnvs();
});
it("creates running RLM children as tracked AgentSessionRuntime instances", async () => {
const tempDir = join(tmpdir(), `pi-3885-subagent-runtime-${Date.now()}-${Math.random().toString(36).slice(2)}`);
mkdirSync(tempDir, { recursive: true });
+ vi.stubEnv(SESSION_LEASES_ENABLED_ENV, "1");
+ vi.stubEnv(SESSION_LEASE_OWNER_ID_ENV, "test-parent");
const faux = registerFauxProvider({
models: [
@@ -160,6 +169,10 @@ describe("ENG-3885 subagent runtime host", () => {
expect(result.session_dir).not.toBeNull();
const childSessions = await SessionManager.list(tempDir, result.session_dir!);
expect(childSessions.some((session) => session.parentSessionPath === runtime.session.sessionFile)).toBe(true);
+ expect(() => acquireSessionLease(childSessions[0]!.path, tempDir)).toThrow(SessionAlreadyActiveError);
+ await runtime.dispose();
+ const retainedChildLease = acquireSessionLease(childSessions[0]!.path, tempDir);
+ retainedChildLease?.release();
expect(runtime.listSubagentRuntimes()).toEqual([]);
});
diff --git a/packages/coding-agent/test/suite/regressions/4257-update-restart-resume.test.ts b/packages/coding-agent/test/suite/regressions/4257-update-restart-resume.test.ts
index 9d4bd15e56..fd17cd323e 100644
--- a/packages/coding-agent/test/suite/regressions/4257-update-restart-resume.test.ts
+++ b/packages/coding-agent/test/suite/regressions/4257-update-restart-resume.test.ts
@@ -78,6 +78,7 @@ function createState(
runtime,
clients: new Set(),
extensionUiRequests: new Map(),
+ eventGeneration: `generation-${activeSessionId}`,
lastEventSequence: 0,
...(options.clientEnv ? { clientEnv: options.clientEnv } : {}),
};
diff --git a/packages/coding-agent/test/suite/regressions/4509-side-questions.test.ts b/packages/coding-agent/test/suite/regressions/4509-side-questions.test.ts
index cd0d77932a..aa0d8f0f90 100644
--- a/packages/coding-agent/test/suite/regressions/4509-side-questions.test.ts
+++ b/packages/coding-agent/test/suite/regressions/4509-side-questions.test.ts
@@ -178,6 +178,7 @@ describe("ENG-4509 side questions", () => {
const abortSideQuestionsFor = vi.fn();
const fakeThis = Object.assign(Object.create(AgentDaemon.prototype), {
abortSideQuestionsFor,
+ options: { worker: false },
summarizer: { forget: vi.fn(), seed: vi.fn() },
rebindCronJobsToState: vi.fn(),
});
diff --git a/packages/coding-agent/test/suite/regressions/4527-worker-heartbeat-scheduling.test.ts b/packages/coding-agent/test/suite/regressions/4527-worker-heartbeat-scheduling.test.ts
new file mode 100644
index 0000000000..063289217f
--- /dev/null
+++ b/packages/coding-agent/test/suite/regressions/4527-worker-heartbeat-scheduling.test.ts
@@ -0,0 +1,86 @@
+import { join } from "node:path";
+import { fauxAssistantMessage } from "@earendil-works/pi-ai";
+import { afterEach, describe, expect, it } from "vitest";
+import { AgentCronJobStore, AgentCronScheduler } from "../../../src/core/cron-jobs.js";
+import { createHarness, type Harness } from "../harness.js";
+
+describe("ENG-4527 worker heartbeat scheduling", () => {
+ const harnesses: Harness[] = [];
+
+ afterEach(() => {
+ while (harnesses.length > 0) {
+ harnesses.pop()?.cleanup();
+ }
+ });
+
+ it("starts 50 independently owned heartbeats while one worker is blocked", async () => {
+ const workerCount = 50;
+ const harness = await createHarness({ persistSession: true });
+ harnesses.push(harness);
+ harness.setResponses([fauxAssistantMessage("blocked worker completed")]);
+ let releaseBlockedWorker: () => void = () => {};
+ const blockedWorker = new Promise<void>((resolve) => {
+ releaseBlockedWorker = resolve;
+ });
+ const started = new Set<number>();
+ const stores: AgentCronJobStore[] = [];
+ const runs: Array<Promise<number>> = [];
+ const now = new Date();
+
+ for (let index = 0; index < workerCount; index++) {
+ const sessionId = `session-${index}`;
+ const artifactDir = join(harness.tempDir, "session-artifacts", sessionId);
+ const sessionFile = join(harness.tempDir, "sessions", `${sessionId}.jsonl`);
+ const store = AgentCronJobStore.forSessionArtifacts();
+ store.registerSessionArtifact(sessionId, artifactDir);
+ store.createHeartbeat({
+ activeSessionId: `worker-${index}`,
+ sessionId,
+ sessionFile,
+ cwd: harness.tempDir,
+ scheduleText: "every 10s",
+ prompt: `heartbeat ${index}`,
+ now: new Date(now.getTime() - 20_000),
+ });
+ stores.push(store);
+ const scheduler = new AgentCronScheduler(store, {
+ runJob: async (job) => {
+ started.add(index);
+ if (index === 0) {
+ await blockedWorker;
+ await harness.session.promptHeartbeat(job, { source: "rpc" });
+ }
+ return undefined;
+ },
+ });
+ runs.push(scheduler.runDue(now));
+ }
+
+ await waitFor(
+ () => started.size === workerCount,
+ () => `${started.size}/${workerCount} workers started`,
+ );
+ expect(started.size).toBe(workerCount);
+ for (const store of stores) {
+ expect(store.nextActiveRunAt()?.getTime()).toBeGreaterThan(now.getTime());
+ }
+
+ releaseBlockedWorker();
+ await Promise.all(runs);
+ expect(stores.every((store) => store.list()[0]?.runCount === 1)).toBe(true);
+ }, 60_000);
+});
+
+async function waitFor(predicate: () => boolean, describe: () => string): Promise<void> {
+ const deadline = Date.now() + 15_000;
+ while (Date.now() < deadline) {
+ if (predicate()) {
+ return;
+ }
+ await new Promise<void>((resolve) => setImmediate(resolve));
+ }
+ if (predicate()) {
+ return;
+ }
+ throw new Error(`Timed out waiting for heartbeat fanout: ${describe()}`);
+}
diff --git a/packages/coding-agent/test/worker-recovery-journal.test.ts b/packages/coding-agent/test/worker-recovery-journal.test.ts
new file mode 100644
index 0000000000..a4dd00be9d
--- /dev/null
+++ b/packages/coding-agent/test/worker-recovery-journal.test.ts
@@ -0,0 +1,68 @@
+import { appendFileSync, mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterEach, describe, expect, it } from "vitest";
+import { WorkerRecoveryJournal } from "../src/modes/daemon/worker-recovery-journal.js";
+
+describe("WorkerRecoveryJournal", () => {
+ const roots: string[] = [];
+
+ afterEach(() => {
+ for (const root of roots.splice(0)) {
+ rmSync(root, { recursive: true, force: true });
+ }
+ });
+
+ function createPath(): string {
+ const root = mkdtempSync(join(tmpdir(), "prime-agent-worker-recovery-"));
+ roots.push(root);
+ return join(root, "worker.recovery.jsonl");
+ }
+
+ it("restores the latest operation state per session", () => {
+ const path = createPath();
+ const journal = new WorkerRecoveryJournal(path);
+ journal.record({
+ activeSessionId: "active-1",
+ sessionId: "session-1",
+ sessionFile: "/tmp/session-1.jsonl",
+ busy: true,
+ operation: "prompt_accepted",
+ });
+ journal.record({
+ activeSessionId: "active-2",
+ sessionId: "session-2",
+ busy: false,
+ operation: "ready",
+ });
+
+ expect(WorkerRecoveryJournal.readLatest(path)).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({ activeSessionId: "active-1", busy: true, operation: "prompt_accepted" }),
+ expect.objectContaining({ activeSessionId: "active-2", busy: false, operation: "ready" }),
+ ]),
+ );
+ });
+
+ it("compacts stable checkpoints and ignores a truncated final record", () => {
+ const path = createPath();
+ const journal = new WorkerRecoveryJournal(path);
+ journal.record({
+ activeSessionId: "active-1",
+ sessionId: "session-1",
+ busy: true,
+ operation: "bash_start",
+ });
+ journal.record({
+ activeSessionId: "active-1",
+ sessionId: "session-1",
+ busy: false,
+ operation: "bash_end",
+ });
+ appendFileSync(path, "{truncated");
+
+ expect(WorkerRecoveryJournal.readLatest(path)).toEqual([
+ expect.objectContaining({ activeSessionId: "active-1", busy: false, operation: "bash_end" }),
+ ]);
+ });
+});
diff --git a/packages/tui/CHANGELOG.md b/packages/tui/CHANGELOG.md
index 90f5a8fd36..bb0f5c5a56 100644
--- a/packages/tui/CHANGELOG.md
+++ b/packages/tui/CHANGELOG.md
@@ -2,6 +2,8 @@
## [Unreleased]
+- Fixed fullscreen TUI handoffs temporarily releasing raw input and leaking keyboard-protocol timers, which caused flicker and echoed arrow escape sequences while opening sessions.
+
## [0.2.9] - 2026-07-13
- Fixed fullscreen dock selection so prompt text can be copied ([#342](https://github.com/PrimeIntellect-ai/prime-agent/pull/342)).
diff --git a/packages/tui/src/terminal.ts b/packages/tui/src/terminal.ts
index 71702e1785..c770eacee3 100644
--- a/packages/tui/src/terminal.ts
+++ b/packages/tui/src/terminal.ts
@@ -20,6 +20,18 @@ const TERMINAL_PROGRESS_CLEAR_SEQUENCE = "\x1b]9;4;0;\x07";
// A preserved alternate screen is adopted by the next ProcessTerminal during in-process handoff.
let pendingAltScreenHandoff: symbol | undefined;
+interface PendingInputHandoff {
+ token: symbol;
+ wasRaw: boolean;
+ discardHandler: (data: string) => void;
+}
+
+// Keep stdin raw and drain input while a preserved fullscreen frame waits for
+// the next in-process TUI. Worker-backed session attach can make this handoff
+// noticeably longer; restoring cooked mode during the gap makes arrow escape
+// sequences echo into the preserved frame.
+let pendingInputHandoff: PendingInputHandoff | undefined;
+
function consumeAltScreenHandoff(): boolean {
if (!pendingAltScreenHandoff) {
return false;
@@ -28,6 +40,40 @@ function consumeAltScreenHandoff(): boolean {
return true;
}
+function beginInputHandoff(token: symbol, wasRaw: boolean): void {
+ const inheritedWasRaw = pendingInputHandoff?.wasRaw ?? wasRaw;
+ if (pendingInputHandoff) {
+ process.stdin.removeListener("data", pendingInputHandoff.discardHandler);
+ }
+ const discardHandler = (_data: string) => {};
+ pendingInputHandoff = { token, wasRaw: inheritedWasRaw, discardHandler };
+ process.stdin.on("data", discardHandler);
+ process.stdin.resume();
+}
+
+function consumeInputHandoff(): boolean | undefined {
+ const handoff = pendingInputHandoff;
+ if (!handoff) {
+ return undefined;
+ }
+ process.stdin.removeListener("data", handoff.discardHandler);
+ pendingInputHandoff = undefined;
+ return handoff.wasRaw;
+}
+
+function cancelInputHandoff(token: symbol): void {
+ const handoff = pendingInputHandoff;
+ if (!handoff || handoff.token !== token) {
+ return;
+ }
+ process.stdin.removeListener("data", handoff.discardHandler);
+ pendingInputHandoff = undefined;
+ process.stdin.pause();
+ if (process.stdin.setRawMode) {
+ process.stdin.setRawMode(handoff.wasRaw);
+ }
+}
+
/**
* Minimal terminal interface for TUI
*/
@@ -96,6 +142,7 @@ export interface TerminalStopOptions {
*/
export class ProcessTerminal implements Terminal {
private wasRaw = false;
+ private started = false;
private inputHandler?: (data: string) => void;
private resizeHandler?: () => void;
private _kittyProtocolActive = false;
@@ -105,6 +152,7 @@ export class ProcessTerminal implements Terminal {
private _mouseTrackingActive = false;
private stdinBuffer?: StdinBuffer;
private stdinDataHandler?: (data: string) => void;
+ private keyboardProtocolFallbackTimer?: ReturnType<typeof setTimeout>;
private progressInterval?: ReturnType<typeof setInterval>;
private defaultColorProbe?: {
foreground?: Rgb;
@@ -131,11 +179,12 @@ export class ProcessTerminal implements Terminal {
}
start(onInput: (data: string) => void, onResize: () => void): void {
+ this.started = true;
this.inputHandler = onInput;
this.resizeHandler = onResize;
// Save previous state and enable raw mode
- this.wasRaw = process.stdin.isRaw || false;
+ this.wasRaw = consumeInputHandoff() ?? process.stdin.isRaw ?? false;
if (process.stdin.setRawMode) {
process.stdin.setRawMode(true);
}
@@ -190,6 +239,7 @@ export class ProcessTerminal implements Terminal {
if (!this._kittyProtocolActive) {
const match = sequence.match(kittyResponsePattern);
if (match) {
+ this.clearKeyboardProtocolFallbackTimer();
this._kittyProtocolActive = true;
setKittyProtocolActive(true);
@@ -240,7 +290,9 @@ export class ProcessTerminal implements Terminal {
process.stdin.on("data", this.stdinDataHandler!);
this.queryDefaultTerminalColors();
process.stdout.write("\x1b[?u");
- setTimeout(() => {
+ this.clearKeyboardProtocolFallbackTimer();
+ this.keyboardProtocolFallbackTimer = setTimeout(() => {
+ this.keyboardProtocolFallbackTimer = undefined;
if (!this._kittyProtocolActive && !this._modifyOtherKeysActive) {
process.stdout.write("\x1b[>4;2m");
this._modifyOtherKeysActive = true;
@@ -248,6 +300,14 @@ export class ProcessTerminal implements Terminal {
}, 150);
}
+ private clearKeyboardProtocolFallbackTimer(): void {
+ if (!this.keyboardProtocolFallbackTimer) {
+ return;
+ }
+ clearTimeout(this.keyboardProtocolFallbackTimer);
+ this.keyboardProtocolFallbackTimer = undefined;
+ }
+
private queryDefaultTerminalColors(): void {
if (process.stdin.isTTY !== true || process.stdout.isTTY !== true) {
return;
@@ -358,7 +418,10 @@ export class ProcessTerminal implements Terminal {
}
stop(options: TerminalStopOptions = {}): void {
+ const wasStarted = this.started;
+ this.started = false;
this.finishDefaultColorProbe();
+ this.clearKeyboardProtocolFallbackTimer();
if (this.clearProgressInterval()) {
process.stdout.write(TERMINAL_PROGRESS_CLEAR_SEQUENCE);
@@ -410,14 +473,18 @@ export class ProcessTerminal implements Terminal {
this.resizeHandler = undefined;
}
- // Pause stdin to prevent any buffered input (e.g., Ctrl+D) from being
- // re-interpreted after raw mode is disabled. This fixes a race condition
- // where Ctrl+D could close the parent shell over SSH.
- process.stdin.pause();
-
- // Restore raw mode state
- if (process.stdin.setRawMode) {
- process.stdin.setRawMode(this.wasRaw);
+ if (options.preserveAltScreen && wasStarted) {
+ beginInputHandoff(this.altScreenHandoffToken, this.wasRaw);
+ } else {
+ // Pause stdin to prevent any buffered input (e.g., Ctrl+D) from being
+ // re-interpreted after raw mode is disabled. This fixes a race condition
+ // where Ctrl+D could close the parent shell over SSH.
+ process.stdin.pause();
+
+ // Restore raw mode state
+ if (process.stdin.setRawMode) {
+ process.stdin.setRawMode(this.wasRaw);
+ }
}
}
@@ -492,6 +559,7 @@ export class ProcessTerminal implements Terminal {
this._altScreenActive = false;
if (ownsPendingHandoff) {
pendingAltScreenHandoff = undefined;
+ cancelInputHandoff(this.altScreenHandoffToken);
}
this.write("\x1b[?1049l");
}
diff --git a/packages/tui/test/terminal.test.ts b/packages/tui/test/terminal.test.ts
index 7af3dbb7e6..59d1f92132 100644
--- a/packages/tui/test/terminal.test.ts
+++ b/packages/tui/test/terminal.test.ts
@@ -45,6 +45,70 @@ describe("ProcessTerminal dimensions", () => {
});
describe("ProcessTerminal alternate screen handoff", () => {
+ it("keeps raw input active and discards keys until the next fullscreen TUI starts", () => {
+ const originalWrite = process.stdout.write;
+ const originalIsRaw = Object.getOwnPropertyDescriptor(process.stdin, "isRaw");
+ const originalSetRawMode = Object.getOwnPropertyDescriptor(process.stdin, "setRawMode");
+ const originalResume = Object.getOwnPropertyDescriptor(process.stdin, "resume");
+ const originalPause = Object.getOwnPropertyDescriptor(process.stdin, "pause");
+ let isRaw = false;
+ const rawModeChanges: boolean[] = [];
+ const firstInputs: string[] = [];
+ const secondInputs: string[] = [];
+
+ Object.defineProperty(process.stdin, "isRaw", { configurable: true, get: () => isRaw });
+ Object.defineProperty(process.stdin, "setRawMode", {
+ configurable: true,
+ value: (enabled: boolean) => {
+ isRaw = enabled;
+ rawModeChanges.push(enabled);
+ return process.stdin;
+ },
+ });
+ Object.defineProperty(process.stdin, "resume", { configurable: true, value: () => process.stdin });
+ Object.defineProperty(process.stdin, "pause", { configurable: true, value: () => process.stdin });
+ process.stdout.write = ((...args: Parameters<typeof process.stdout.write>): boolean => {
+ const callback = args.find((arg): arg is (error?: Error | null) => void => typeof arg === "function");
+ callback?.();
+ return true;
+ }) as typeof process.stdout.write;
+
+ try {
+ const first = new ProcessTerminal();
+ first.start(
+ (data) => firstInputs.push(data),
+ () => {},
+ );
+ process.stdin.emit("data", "\x1b[?1u");
+ first.enterAltScreen();
+ first.stop({ preserveAltScreen: true });
+
+ assert.equal(isRaw, true);
+ process.stdin.emit("data", "\x1b[B");
+ assert.deepEqual(firstInputs, []);
+
+ const second = new ProcessTerminal();
+ second.start(
+ (data) => secondInputs.push(data),
+ () => {},
+ );
+ process.stdin.emit("data", "\x1b[?1u");
+ process.stdin.emit("data", "x");
+
+ assert.equal(isRaw, true);
+ assert.deepEqual(secondInputs, ["x"]);
+ second.stop();
+ assert.equal(isRaw, false);
+ assert.deepEqual(rawModeChanges, [true, true, false]);
+ } finally {
+ process.stdout.write = originalWrite;
+ restoreProperty(process.stdin, "isRaw", originalIsRaw);
+ restoreProperty(process.stdin, "setRawMode", originalSetRawMode);
+ restoreProperty(process.stdin, "resume", originalResume);
+ restoreProperty(process.stdin, "pause", originalPause);
+ }
+ });
+
it("does not inherit an active alternate screen before it is preserved", () => {
const originalWrite = process.stdout.write;
const writes: string[] = [];
@@ -177,3 +241,11 @@ describe("ProcessTerminal alternate screen handoff", () => {
}
});
});
+
+function restoreProperty(object: object, key: PropertyKey, descriptor: PropertyDescriptor | undefined): void {
+ if (descriptor) {
+ Object.defineProperty(object, key, descriptor);
+ } else {
+ Reflect.deleteProperty(object, key);
+ }
+}