Skip to content

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

Rust

make daemon mismatches self-healing (#466)

kt10a5de8f4595
diff --git a/AGENTS.md b/AGENTS.md
index f01366be55..d8c18dd87e 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -32,6 +32,15 @@
- For `packages/coding-agent/test/suite/`, use `test/suite/harness.ts` plus the faux provider. Do not use real provider APIs, real API keys, or paid tokens.
- Put issue-specific regressions under `packages/coding-agent/test/suite/regressions/` and name them `<issue-number>-<short-slug>.test.ts`.
+## Daemon Protocol Changes
+
+- Classify every daemon command, event, and response-shape change as backward-compatible, capability-gated, or incompatible.
+- Add optional features behind a negotiated server capability. Clients must check the capability before sending the command or depending on the event.
+- Bump `DAEMON_PROTOCOL_VERSION` for incompatible changes or when startup begins requiring behavior an older daemon cannot provide.
+- Update `DAEMON_SCHEMA_REVISION`, the command/event compatibility maps, and both new-client/old-daemon and old-client/new-daemon tests for every wire change.
+- Optional daemon metadata and UI features must degrade locally. They must not prevent the agent, session attachment, or interactive startup from working.
+- Never make a new daemon command part of startup without a protocol or capability gate.
+
## Dependencies
- A 7-day minimum release age applies to all dependency updates: `.npmrc` sets `min-release-age=7` and `.github/dependabot.yml` uses a matching `cooldown`. Never bypass it for routine updates.
diff --git a/packages/coding-agent/CHANGELOG.md b/packages/coding-agent/CHANGELOG.md
index 12a0cc62bd..4169c52fcf 100644
--- a/packages/coding-agent/CHANGELOG.md
+++ b/packages/coding-agent/CHANGELOG.md
@@ -2,6 +2,7 @@
## [Unreleased]
+- Fixed incompatible daemon builds crashing startup or respawning after shutdown, with capability negotiation, verified provenance, and convergent force shutdown ([ENG-4687](https://linear.app/primeintellect/issue/ENG-4687/make-daemon-version-mismatches-self-healing)).
- Changed top-level CLI help to show concise common options and commands without loading runtime resources ([ENG-4688](https://linear.app/primeintellect/issue/ENG-4688/help-command-is-obscenely-verbose)).
- Fixed completed subagents cancelling their RLM heartbeats before the first run ([ENG-4652](https://linear.app/primeintellect/issue/ENG-4652/subagent-heartbeats-dont-work)).
- Changed the fullscreen follow shortcut from `Alt+Down` to `Ctrl+Shift+Down` for more reliable terminal input ([ENG-4684](https://linear.app/primeintellect/issue/ENG-4684/altdown-doesnt-work)).
diff --git a/packages/coding-agent/scripts/bundle.mjs b/packages/coding-agent/scripts/bundle.mjs
index d28e641588..8d4155f8f2 100644
--- a/packages/coding-agent/scripts/bundle.mjs
+++ b/packages/coding-agent/scripts/bundle.mjs
@@ -11,13 +11,23 @@
* compiled Bun binary), keyed off the __PI_BUNDLED__ define below, so extension
* imports of pi packages share the bundle's module instances.
*/
-import { chmodSync, rmSync } from "node:fs";
+import { chmodSync, readFileSync, rmSync } from "node:fs";
+import { execFileSync } from "node:child_process";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
import { build } from "esbuild";
const packageDir = dirname(dirname(fileURLToPath(import.meta.url)));
const outdir = join(packageDir, "dist", "bundle");
+let buildId;
+try {
+ buildId = execFileSync("git", ["describe", "--tags", "--always", "--dirty"], {
+ cwd: dirname(packageDir),
+ encoding: "utf8",
+ }).trim();
+} catch {
+ buildId = `release-${JSON.parse(readFileSync(join(packageDir, "package.json"), "utf8")).version}`;
+}
rmSync(outdir, { recursive: true, force: true });
@@ -31,7 +41,7 @@ await build({
// Native or interop-sensitive packages stay external; they resolve from
// node_modules at runtime (and are loaded via createRequire/lazily anyway).
external: ["zeromq", "koffi", "undici", "@silvia-odwyer/photon-node", "@mariozechner/clipboard"],
- define: { __PI_BUNDLED__: "true" },
+ define: { __PI_BUNDLED__: "true", __PI_BUILD_ID__: JSON.stringify(buildId) },
banner: {
js: "import { createRequire as __piBundleCreateRequire } from 'node:module'; const require = __piBundleCreateRequire(import.meta.url);",
},
diff --git a/packages/coding-agent/src/cli/daemon-launch.ts b/packages/coding-agent/src/cli/daemon-launch.ts
index 7266dcfa56..f50a6d9785 100644
--- a/packages/coding-agent/src/cli/daemon-launch.ts
+++ b/packages/coding-agent/src/cli/daemon-launch.ts
@@ -13,10 +13,12 @@ import { resolve } from "node:path";
import { appendRotatingLog, expandTildePath, getClientErrorLogPath, VERSION } from "../config.js";
import { getProcessStartId } from "../core/session-lease.js";
import { DaemonClient, type DaemonHello } from "../modes/daemon/daemon-client.js";
-import { DAEMON_PROTOCOL_VERSION } from "../modes/daemon/daemon-protocol.js";
+import { DAEMON_PROTOCOL_VERSION, DAEMON_SCHEMA_ID } from "../modes/daemon/daemon-protocol.js";
+import { getDaemonRuntimeIdentity } from "../modes/daemon/daemon-runtime-identity.js";
import type { SessionSummary } from "../modes/daemon/daemon-session-list.js";
import { defaultDaemonSocketPath } from "../modes/daemon/daemon-socket.js";
import { isHelpCommandRequest, PUBLIC_COMMAND_NAMES, REMOVED_COMMAND_NAMES } from "./command-registry.js";
+import { formatCurrentCliCommand } from "./subprocess-launch.js";
export function isDaemonSessionSummary(value: unknown): value is SessionSummary {
if (!value || typeof value !== "object") {
@@ -49,31 +51,52 @@ async function canConnectToDaemon(socketPath: string, timeoutMs: number): Promis
}
}
-type DaemonVersionProbe = "absent" | "current" | "stale";
+type DaemonVersionProbe =
+ | { status: "absent" }
+ | { status: "current"; hello: DaemonHello }
+ | { status: "stale"; hello?: DaemonHello; compatible: boolean };
/** Connect to a running daemon and check whether it matches this client's protocol and app version. */
-async function probeDaemonVersion(socketPath: string): Promise<DaemonVersionProbe> {
- const client = new DaemonClient(socketPath);
- try {
- await client.connect(250);
- } catch {
- client.close();
- return "absent";
+export async function probeDaemonVersion(socketPath: string): Promise<DaemonVersionProbe> {
+ let client: DaemonClient | undefined;
+ for (const timeoutMs of [250, 2000]) {
+ const candidate = new DaemonClient(socketPath);
+ try {
+ await candidate.connect(timeoutMs);
+ client = candidate;
+ break;
+ } catch {
+ candidate.close();
+ }
+ }
+ if (!client) {
+ return { status: "absent" };
}
try {
const hello = await client.waitForHello(2000);
- const current = hello.protocol.version === DAEMON_PROTOCOL_VERSION && hello.appVersion === VERSION;
+ const current =
+ hello.protocol.version === DAEMON_PROTOCOL_VERSION &&
+ hello.schemaId === DAEMON_SCHEMA_ID &&
+ hello.appVersion === VERSION;
if (!current) {
logDaemonLaunch(
- `running daemon on ${socketPath} is stale: daemon v${hello.appVersion}/proto${hello.protocol.version} ` +
- `vs client v${VERSION}/proto${DAEMON_PROTOCOL_VERSION}`,
+ `running daemon on ${socketPath} is stale: daemon v${hello.appVersion}/proto${hello.protocol.version}` +
+ `/schema ${hello.schemaId ?? "legacy"}/build ${hello.runtime?.buildId ?? "unknown"} vs client ` +
+ `v${VERSION}/proto${DAEMON_PROTOCOL_VERSION}/schema ${DAEMON_SCHEMA_ID}/build ${getDaemonRuntimeIdentity().buildId}`,
);
}
- return current ? "current" : "stale";
+ if (current) {
+ return { status: "current", hello };
+ }
+ return {
+ status: "stale",
+ hello,
+ compatible: hello.protocol.version === 3,
+ };
} catch {
// Connected but no recognizable greeting: assume a stale daemon.
logDaemonLaunch(`running daemon on ${socketPath} sent no recognizable hello; treating as stale`);
- return "stale";
+ return { status: "stale", compatible: false };
} finally {
client.close();
}
@@ -104,10 +127,21 @@ export async function listActiveDaemonSessionSummaries(client: DaemonClient): Pr
/** Thrown when a stale-version daemon can't be replaced. The message is user-facing. */
export class StaleDaemonError extends Error {
- constructor(readonly socketPath: string) {
+ constructor(
+ readonly socketPath: string,
+ hello?: DaemonHello,
+ ) {
+ const daemonIdentity = hello
+ ? `Daemon: v${hello.appVersion ?? "unknown"}, protocol ${hello.protocol.version}, schema ${hello.schemaId ?? "legacy"}, ` +
+ `build ${hello.runtime?.buildId ?? "unknown"}, PID ${hello.supervisorPid ?? "unknown"}, ` +
+ `executable ${hello.runtime?.launcherPath ?? hello.runtime?.entrypointPath ?? hello.runtime?.executablePath ?? "unknown"}`
+ : `Daemon: unknown build on ${socketPath}`;
+ const client = getDaemonRuntimeIdentity();
super(
- `A background service from a different Prime Agent version is running on ${socketPath} and can't be driven by ` +
- `this version. Run "prime-agent shutdown" to stop it, then retry.`,
+ `An incompatible Prime Agent daemon is running.\n\n${daemonIdentity}\n` +
+ `Client: v${VERSION}, protocol ${DAEMON_PROTOCOL_VERSION}, schema ${DAEMON_SCHEMA_ID}, build ${client.buildId}, ` +
+ `executable ${client.launcherPath ?? client.entrypointPath ?? client.executablePath}\n\nRun:\n` +
+ `${formatCurrentCliCommand(["shutdown", "--force"])}\n\nThen retry the original command.`,
);
this.name = "StaleDaemonError";
}
@@ -287,13 +321,17 @@ async function shutdownStaleDaemonIfNotBusy(socketPath: string): Promise<boolean
async function ensureDaemonRunning(socketPath: string, spawnCwd?: string): Promise<void> {
const probe = await probeDaemonVersion(socketPath);
- if (probe === "current") {
+ if (probe.status === "current") {
return;
}
- if (probe === "stale") {
+ if (probe.status === "stale") {
const stopped = await shutdownStaleDaemonIfNotBusy(socketPath);
if (!stopped) {
- throw new StaleDaemonError(socketPath);
+ if (probe.compatible) {
+ logDaemonLaunch(`using compatible legacy daemon on ${socketPath} while busy work completes`);
+ return;
+ }
+ throw new StaleDaemonError(socketPath, probe.hello);
}
}
@@ -318,7 +356,8 @@ async function ensureDaemonRunning(socketPath: string, spawnCwd?: string): Promi
const deadline = Date.now() + 10000;
while (Date.now() < deadline) {
- if (await canConnectToDaemon(socketPath, 250)) {
+ const started = await probeDaemonVersion(socketPath);
+ if (started.status === "current") {
return;
}
await delay(25);
diff --git a/packages/coding-agent/src/cli/daemon-ps.ts b/packages/coding-agent/src/cli/daemon-ps.ts
index 1d3dd86193..6f22f823e4 100644
--- a/packages/coding-agent/src/cli/daemon-ps.ts
+++ b/packages/coding-agent/src/cli/daemon-ps.ts
@@ -6,7 +6,11 @@ import { APP_NAME, getAgentDir, VERSION } from "../config.js";
import { isOrphanProcessIdentityCurrent, readActiveOrphanProcesses } from "../core/orphan-process-journal.js";
import { getProcessStartId } from "../core/session-lease.js";
import { DaemonClient } from "../modes/daemon/daemon-client.js";
-import { DAEMON_PROTOCOL_VERSION } from "../modes/daemon/daemon-protocol.js";
+import {
+ DAEMON_PROTOCOL_VERSION,
+ DAEMON_SCHEMA_ID,
+ type DaemonRuntimeIdentity,
+} from "../modes/daemon/daemon-protocol.js";
import { defaultDaemonSocketDir, defaultDaemonSocketPath } from "../modes/daemon/daemon-socket.js";
import { acquireDaemonShutdownAdmission } from "../modes/daemon/daemon-supervisor-ownership.js";
import type { DaemonWorkerDescriptor } from "../modes/daemon/daemon-worker-protocol.js";
@@ -46,6 +50,10 @@ export interface DaemonInfo {
uptimeSeconds?: number;
version?: string;
protocolVersion?: number;
+ schemaId?: string;
+ buildId?: string;
+ executablePath?: string;
+ pidSource?: "listener" | "hello";
sessionCount?: number;
status: DaemonStatus;
isDefault: boolean;
@@ -58,6 +66,15 @@ const STATUS_ORDER: Record<DaemonStatus, number> = {
unreachable: 2,
"orphan-file": 3,
};
+const SHUTDOWN_QUIET_PERIOD_MS = 1000;
+const SHUTDOWN_CONVERGENCE_TIMEOUT_MS = 10_000;
+
+export function evaluateShutdownQuietPeriod(now: number, quietSince: number | undefined): "complete" | "waiting" {
+ if (quietSince !== undefined && now - quietSince >= SHUTDOWN_QUIET_PERIOD_MS) {
+ return "complete";
+ }
+ return "waiting";
+}
// Linux comm names (and thus the process name ss reports) are capped at 15 chars.
const MAX_COMM_LENGTH = 15;
@@ -117,6 +134,34 @@ export function parseLsofListeners(stdout: string): DiscoveredDaemonProcess[] {
return daemons;
}
+export function parsePrimeAgentProcessIds(stdout: string, appName: string): number[] {
+ const pids: number[] = [];
+ for (const line of stdout.split("\n")) {
+ const match = line.trim().match(/^(\d+)\s+(\S+)(?:\s+(.*))?$/);
+ if (!match) {
+ continue;
+ }
+ const command = basename(match[2]!);
+ const argv0 = basename(match[3]?.trim().split(/\s+/, 1)[0] ?? "");
+ if (processNameMatches(command, appName) || processNameMatches(argv0, appName)) {
+ pids.push(Number.parseInt(match[1]!, 10));
+ }
+ }
+ return pids;
+}
+
+export function mergeDiscoveredDaemonProcesses(
+ ...groups: readonly DiscoveredDaemonProcess[][]
+): DiscoveredDaemonProcess[] {
+ const byIdentity = new Map<string, DiscoveredDaemonProcess>();
+ for (const group of groups) {
+ for (const daemon of group) {
+ byIdentity.set(`${daemon.pid}:${daemon.socketPath}`, daemon);
+ }
+ }
+ return [...byIdentity.values()];
+}
+
/** Parse `ps -o pid=,etimes=` output into a pid → uptime-seconds map. */
export function parsePsEtimes(stdout: string): Map<number, number> {
const uptimes = new Map<number, number>();
@@ -138,10 +183,21 @@ function scanListeningDaemons(): DiscoveredDaemonProcess[] {
return enrichUptimes(parseSsListeners(ss.stdout, APP_NAME));
}
const lsof = spawnSync("lsof", ["-nP", "-F", "pn", "-U", "-a", "-c", APP_NAME], { encoding: "utf8" });
- if (!lsof.error && typeof lsof.stdout === "string") {
- return enrichUptimes(parseLsofListeners(lsof.stdout));
+ const byName = !lsof.error && typeof lsof.stdout === "string" ? parseLsofListeners(lsof.stdout) : [];
+ let byPid: DiscoveredDaemonProcess[] = [];
+ const ps = spawnSync("ps", ["-axo", "pid=,comm=,args="], { encoding: "utf8" });
+ if (!ps.error && ps.status === 0 && typeof ps.stdout === "string") {
+ const pids = parsePrimeAgentProcessIds(ps.stdout, APP_NAME);
+ if (pids.length > 0) {
+ const lsofByPid = spawnSync("lsof", ["-nP", "-F", "pn", "-U", "-a", "-p", pids.join(",")], {
+ encoding: "utf8",
+ });
+ if (!lsofByPid.error && typeof lsofByPid.stdout === "string") {
+ byPid = parseLsofListeners(lsofByPid.stdout);
+ }
+ }
}
- return [];
+ return enrichUptimes(mergeDiscoveredDaemonProcesses(byName, byPid));
}
function isDaemonProcessListening(pid: number, socketPath: string): boolean {
@@ -188,8 +244,11 @@ function scanSocketDir(): string[] {
interface ProbeResult {
version?: string;
protocolVersion?: number;
+ schemaId?: string;
+ runtime?: DaemonRuntimeIdentity;
sessionCount?: number;
supervisorPid?: number;
+ supervisorProcessStartId?: string;
reachable: boolean;
}
@@ -204,13 +263,19 @@ async function probeDaemon(socketPath: string): Promise<ProbeResult> {
try {
let version: string | undefined;
let protocolVersion: number | undefined;
+ let schemaId: string | undefined;
+ let runtime: DaemonRuntimeIdentity | undefined;
let supervisorPid: number | undefined;
+ let supervisorProcessStartId: string | undefined;
let greeted = false;
try {
const hello = await client.waitForHello(1500);
version = hello.appVersion;
protocolVersion = hello.protocol.version;
+ schemaId = hello.schemaId;
+ runtime = hello.runtime;
supervisorPid = hello.supervisorPid;
+ supervisorProcessStartId = hello.supervisorProcessStartId;
greeted = true;
} catch {
// Connected but no recognizable greeting: an old/foreign daemon.
@@ -227,19 +292,55 @@ async function probeDaemon(socketPath: string): Promise<ProbeResult> {
} catch {
// Leave sessionCount undefined when the daemon will not answer list.
}
- return { version, protocolVersion, sessionCount, supervisorPid, reachable: true };
+ return {
+ version,
+ protocolVersion,
+ schemaId,
+ runtime,
+ sessionCount,
+ supervisorPid,
+ supervisorProcessStartId,
+ reachable: true,
+ };
} finally {
client.close();
}
}
function classifyReachable(probe: ProbeResult): DaemonStatus {
- if (probe.protocolVersion === DAEMON_PROTOCOL_VERSION && probe.version === VERSION) {
+ if (
+ probe.protocolVersion === DAEMON_PROTOCOL_VERSION &&
+ probe.schemaId === DAEMON_SCHEMA_ID &&
+ probe.version === VERSION
+ ) {
return "current";
}
return "stale";
}
+export function verifyHelloSupervisorPid(
+ pid: number | undefined,
+ expectedProcessStartId: string | undefined,
+): number | undefined {
+ if (!Number.isInteger(pid) || pid === undefined || pid <= 0) {
+ return undefined;
+ }
+ try {
+ process.kill(pid, 0);
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== "EPERM") {
+ return undefined;
+ }
+ }
+ if (expectedProcessStartId) {
+ const observedStartId = getProcessStartId(pid);
+ if (observedStartId !== expectedProcessStartId) {
+ return undefined;
+ }
+ }
+ return pid;
+}
+
/** Discover every daemon on the machine and probe each for version + session count. */
export async function discoverDaemons(): Promise<DaemonInfo[]> {
const processBySocket = new Map<string, DiscoveredDaemonProcess>();
@@ -264,6 +365,7 @@ export async function discoverDaemons(): Promise<DaemonInfo[]> {
[...sockets].map(async (socketPath): Promise<DaemonInfo> => {
const proc = processBySocket.get(socketPath);
const probe = await probeDaemon(socketPath);
+ const pid = proc?.pid ?? verifyHelloSupervisorPid(probe.supervisorPid, probe.supervisorProcessStartId);
const hasTrackedWorkers = workerSockets.has(socketPath);
const status: DaemonStatus = probe.reachable
? classifyReachable(probe)
@@ -272,10 +374,15 @@ export async function discoverDaemons(): Promise<DaemonInfo[]> {
: "orphan-file";
return {
socketPath,
- pid: proc?.pid,
+ pid,
uptimeSeconds: proc?.uptimeSeconds,
version: probe.version,
protocolVersion: probe.protocolVersion,
+ schemaId: probe.schemaId,
+ buildId: probe.runtime?.buildId,
+ executablePath:
+ probe.runtime?.launcherPath ?? probe.runtime?.entrypointPath ?? probe.runtime?.executablePath,
+ ...(pid !== undefined ? { pidSource: proc ? ("listener" as const) : ("hello" as const) } : {}),
sessionCount: probe.sessionCount,
status,
isDefault: socketPath === defaultSocket,
@@ -632,24 +739,30 @@ async function terminateVerifiedResiduals(
assertAdmission: () => Promise<void>,
): Promise<void> {
let previousSignature: string | undefined;
+ let quietSince: number | undefined;
+ const deadline = Date.now() + SHUTDOWN_CONVERGENCE_TIMEOUT_MS;
while (true) {
+ await assertAdmission();
const listeners = scanListeningDaemons();
+ const now = Date.now();
if (listeners.length === 0) {
- return;
+ previousSignature = undefined;
+ quietSince ??= now;
+ const quietPeriod = evaluateShutdownQuietPeriod(now, quietSince);
+ if (quietPeriod === "complete") {
+ return;
+ }
+ await delay(100);
+ continue;
}
+ quietSince = undefined;
const signature = daemonListenerSignature(listeners);
+ if (now >= deadline) {
+ recordResidualListenerFailures(listeners, failed, reportedFailures, "kept respawning during shutdown");
+ return;
+ }
if (signature === previousSignature) {
- for (const listener of listeners) {
- const processStartId = getProcessStartId(listener.pid);
- if (processStartId && getProcessStartId(listener.pid) === processStartId) {
- recordShutdownFailure(
- failed,
- reportedFailures,
- listener.socketPath,
- `daemon process remained after shutdown (pid ${listener.pid}, start ${processStartId})`,
- );
- }
- }
+ recordResidualListenerFailures(listeners, failed, reportedFailures, "remained after shutdown");
return;
}
previousSignature = signature;
@@ -673,6 +786,37 @@ async function terminateVerifiedResiduals(
}
}
+function recordResidualListenerFailures(
+ listeners: readonly DiscoveredDaemonProcess[],
+ failed: Array<{ socketPath: string; reason: string }>,
+ reportedFailures: Set<string>,
+ reason: string,
+): void {
+ for (const listener of listeners) {
+ const processStartId = getProcessStartId(listener.pid);
+ const identity = processStartId
+ ? `pid ${listener.pid}, start ${processStartId}`
+ : `pid ${listener.pid}, process identity unavailable`;
+ recordShutdownFailure(
+ failed,
+ reportedFailures,
+ listener.socketPath,
+ `daemon ${reason} (${identity})${describeDaemonParent(listener.pid)}`,
+ );
+ }
+}
+function describeDaemonParent(pid: number): string {
+ const result = spawnSync("ps", ["-o", "ppid=,tty=,command=", "-p", String(pid)], { encoding: "utf8" });
+ if (result.error || result.status !== 0 || typeof result.stdout !== "string") {
+ return "";
+ }
+ const match = result.stdout.trim().match(/^(\d+)\s+(\S+)\s+(.+)$/);
+ if (!match) {
+ return "";
+ }
+ return `; close parent PID ${match[1]} on ${match[2]} (${match[3]}) and retry shutdown`;
+}
+
async function terminateVerifiedListener(
listener: DiscoveredDaemonProcess,
failed: Array<{ socketPath: string; reason: string }>,
diff --git a/packages/coding-agent/src/cli/subprocess-launch.ts b/packages/coding-agent/src/cli/subprocess-launch.ts
index a8b62bd1d4..1a24214863 100644
--- a/packages/coding-agent/src/cli/subprocess-launch.ts
+++ b/packages/coding-agent/src/cli/subprocess-launch.ts
@@ -5,6 +5,19 @@ export interface CliSubprocessLaunchSpec {
args: string[];
}
+function quoteCommandArgument(value: string): string {
+ return /^[A-Za-z0-9_./:@%+=,-]+$/.test(value) ? value : `'${value.replaceAll("'", `'"'"'`)}'`;
+}
+
+export function formatCurrentCliCommand(args: readonly string[], environment: NodeJS.ProcessEnv = process.env): string {
+ const launcherPath = environment.PRIME_AGENT_LAUNCHER_PATH;
+ if (launcherPath) {
+ return [launcherPath, ...args].map(quoteCommandArgument).join(" ");
+ }
+ const launch = createCliSubprocessLaunchSpec(args);
+ return [launch.command, ...launch.args].map(quoteCommandArgument).join(" ");
+}
+
export function createCliSubprocessLaunchSpec(
args: readonly string[],
executable = process.execPath,
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 d52adf4ca7..5a4519992f 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
@@ -1,7 +1,7 @@
import { randomUUID } from "node:crypto";
import type { AgentMessage, ThinkingLevel } from "@earendil-works/pi-agent-core";
import type { ImageContent, ServiceTier, Transport } from "@earendil-works/pi-ai";
-import { getAgentLogPath, getDaemonLogPath } from "../../config.js";
+import { appendRotatingLog, 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";
@@ -190,7 +190,16 @@ export class DaemonAgentConnection implements AgentConnection {
this.client.enableRequestRecovery();
}
this.unsubscribeDaemonMessages = this.client.onMessage((message) => {
- void this.handleDaemonMessage(message);
+ void this.handleDaemonMessage(message).catch((error: unknown) => {
+ try {
+ appendRotatingLog(
+ getAgentLogPath(),
+ `[${new Date().toISOString()}] daemon-message: ignored ${message.type} failure: ${String(error)}`,
+ );
+ } catch {
+ // Logging failure must not turn an isolated message error into a connection failure.
+ }
+ });
});
this.captureDaemonLogPath();
this.unsubscribeDaemonClose = this.client.onClose((error) => {
@@ -464,8 +473,22 @@ export class DaemonAgentConnection implements AgentConnection {
}
async listHeartbeats(): Promise<AgentConnectionHeartbeat[]> {
- const data = await this.requestData<{ heartbeats: AgentConnectionHeartbeat[] }>({ type: "heartbeats_list" });
- return data.heartbeats;
+ const hasCapability = this.client.supportsServerCapability("heartbeat_catalog");
+ if (!hasCapability && this.client.hello?.protocol.version !== 3) {
+ return [];
+ }
+ try {
+ const command = { type: "heartbeats_list" } as const;
+ const data = hasCapability
+ ? await this.requestData<{ heartbeats: AgentConnectionHeartbeat[] }>(command)
+ : await this.requestLegacyData<{ heartbeats: AgentConnectionHeartbeat[] }>(command);
+ return data.heartbeats;
+ } catch (error) {
+ if (isUnknownDaemonCommandError(error, "heartbeats_list")) {
+ return [];
+ }
+ throw error;
+ }
}
async manageHeartbeat(
@@ -473,13 +496,27 @@ export class DaemonAgentConnection implements AgentConnection {
jobId: string,
action: AgentHeartbeatManagementAction,
): Promise<AgentCronJob> {
- const data = await this.requestData<{ heartbeat: AgentCronJob }>({
- type: "heartbeat_manage",
- activeSessionId,
- jobId,
- action,
- });
- return data.heartbeat;
+ const hasCapability = this.client.supportsServerCapability("heartbeat_management");
+ if (!hasCapability && this.client.hello?.protocol.version !== 3) {
+ throw new Error("Heartbeat management requires a newer Prime Agent daemon.");
+ }
+ try {
+ const command = {
+ type: "heartbeat_manage",
+ activeSessionId,
+ jobId,
+ action,
+ } as const;
+ const data = hasCapability
+ ? await this.requestData<{ heartbeat: AgentCronJob }>(command)
+ : await this.requestLegacyData<{ heartbeat: AgentCronJob }>(command);
+ return data.heartbeat;
+ } catch (error) {
+ if (isUnknownDaemonCommandError(error, "heartbeat_manage")) {
+ throw new Error("Heartbeat management requires a newer Prime Agent daemon.");
+ }
+ throw error;
+ }
}
async addCronJob(schedule: string, prompt: string): Promise<AgentCronJob> {
@@ -980,7 +1017,7 @@ export class DaemonAgentConnection implements AgentConnection {
return this.reconnectPromise;
}
this.reconnectPromise = (async () => {
- await this.emit({ type: "connection_status", status: "reconnecting", error: cause.message });
+ void 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;
@@ -995,8 +1032,8 @@ export class DaemonAgentConnection implements AgentConnection {
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" });
+ void this.emit({ type: "session_resynced", snapshot });
+ void this.emit({ type: "connection_status", status: "connected" });
}
return;
} catch (error) {
@@ -1028,6 +1065,14 @@ export class DaemonAgentConnection implements AgentConnection {
await this.requestData<unknown>(command);
}
+ private async requestLegacyData<T>(command: DaemonCommandBody, timeoutMs?: number): Promise<T> {
+ const response = await this.client.requestLegacy(command, timeoutMs);
+ if (!response.success) {
+ throw deserializeDaemonError(response);
+ }
+ return response.data as T;
+ }
+
private async requestData<T>(command: DaemonCommandBody, timeoutMs?: number): Promise<T> {
const response = await this.client.request(command, timeoutMs);
if (!response.success) {
@@ -1221,8 +1266,18 @@ export class DaemonAgentConnection implements AgentConnection {
if (this.updateReconnectPromise) {
return this.updateReconnectPromise;
}
+ void this.emit({
+ type: "connection_status",
+ status: "reconnecting",
+ error: "The Prime Agent daemon is restarting for an update.",
+ });
const reconnectPromise = reconnectDaemonTransportAfterUpdate(this.client)
.then(() => this.restoreConnectionAfterUpdate())
+ .then(() => {
+ if (!this.disposed) {
+ void this.emit({ type: "connection_status", status: "connected" });
+ }
+ })
.catch(async (error: unknown) => {
this.updateRestartPending = false;
this.updateReconnectFailed = true;
@@ -1288,7 +1343,7 @@ export class DaemonAgentConnection implements AgentConnection {
return;
}
this.updateRestartPending = false;
- await this.emit({ type: "session_resynced", snapshot });
+ void this.emit({ type: "session_resynced", snapshot });
return;
}
} catch (error) {
@@ -1569,13 +1624,15 @@ export class DaemonAgentConnection implements AgentConnection {
}
private async emit(event: AgentConnectionEvent): Promise<void> {
+ const deliveries: Promise<void>[] = [];
for (const listener of [...this.listeners]) {
try {
- await listener(event);
+ deliveries.push(Promise.resolve(listener(event)));
} catch {
// One attachment must not interrupt delivery or transport recovery for the others.
}
}
+ await Promise.allSettled(deliveries);
}
private observeSideQuestionEvent(event: AgentConnectionSideQuestionEvent): void {
diff --git a/packages/coding-agent/src/modes/daemon/daemon-client.ts b/packages/coding-agent/src/modes/daemon/daemon-client.ts
index d4f72b00b9..112a2ca829 100644
--- a/packages/coding-agent/src/modes/daemon/daemon-client.ts
+++ b/packages/coding-agent/src/modes/daemon/daemon-client.ts
@@ -4,6 +4,7 @@ import { getDaemonLogPath } from "../../config.js";
import { attachJsonlLineReader, serializeJsonLine } from "../rpc/jsonl.js";
import {
createDaemonCommandEnvelope,
+ DAEMON_COMMAND_COMPATIBILITY,
DAEMON_COMMAND_ENVELOPE_MIN_PROTOCOL_VERSION,
DAEMON_PROTOCOL_VERSION,
type DaemonClosingReason,
@@ -14,6 +15,7 @@ import {
type DaemonRequestProgress,
type DaemonResponse,
type DaemonSavedSessionInfo,
+ type DaemonServerCapability,
isDaemonMutatingCommand,
} from "./daemon-protocol.js";
import type { DaemonWorkerCommand, DaemonWorkerCommandBody } from "./daemon-worker-protocol.js";
@@ -64,6 +66,20 @@ export class DaemonSocketClosedError extends Error {
}
}
+export class DaemonCapabilityUnavailableError extends Error {
+ constructor(
+ readonly command: DaemonCommand["type"],
+ readonly capability: DaemonServerCapability | undefined,
+ ) {
+ super(
+ capability
+ ? `The running Prime Agent daemon does not support ${capability}.`
+ : `The running Prime Agent daemon does not support ${command}.`,
+ );
+ this.name = "DaemonCapabilityUnavailableError";
+ }
+}
+
export function getDaemonSocketCloseReason(error: Error): DaemonClosingReason | undefined {
return error instanceof DaemonSocketClosedError ? error.daemonClosingReason : undefined;
}
@@ -115,6 +131,10 @@ export class DaemonClient {
return this.socket !== undefined && !this.socket.destroyed;
}
+ supportsServerCapability(capability: DaemonServerCapability): boolean {
+ return this.helloMessage?.serverCapabilities?.includes(capability) === true;
+ }
+
/** Wait for the daemon_hello greeting sent on connect. */
async waitForHello(timeoutMs = 3000): Promise<DaemonHello> {
if (this.helloMessage) {
@@ -277,6 +297,16 @@ export class DaemonClient {
);
}
const hello = this.helloMessage ?? (await this.waitForHello());
+ const compatibility = DAEMON_COMMAND_COMPATIBILITY[command.type];
+ if (
+ hello.protocol.version < compatibility.minProtocol ||
+ ("capability" in compatibility && !this.supportsServerCapability(compatibility.capability))
+ ) {
+ throw new DaemonCapabilityUnavailableError(
+ command.type,
+ "capability" in compatibility ? compatibility.capability : undefined,
+ );
+ }
const envelopeProtocolVersion = Math.min(hello.protocol.version, DAEMON_PROTOCOL_VERSION);
return this.requestWire(
command,
@@ -438,7 +468,11 @@ export class DaemonClient {
}
for (const listener of this.listeners) {
- listener(message as DaemonOutbound);
+ try {
+ listener(message as DaemonOutbound);
+ } catch {
+ // A consumer failure must not interrupt protocol parsing for other clients.
+ }
}
}
diff --git a/packages/coding-agent/src/modes/daemon/daemon-mode.ts b/packages/coding-agent/src/modes/daemon/daemon-mode.ts
index 380b5b734b..385e47e6cf 100644
--- a/packages/coding-agent/src/modes/daemon/daemon-mode.ts
+++ b/packages/coding-agent/src/modes/daemon/daemon-mode.ts
@@ -125,7 +125,10 @@ import {
createDaemonEventMeta,
createDaemonReplayInfo,
DAEMON_DEFAULT_CLIENT_CAPABILITIES,
+ DAEMON_DEFAULT_SERVER_CAPABILITIES,
DAEMON_PROTOCOL_INFO,
+ DAEMON_SCHEMA_ID,
+ DAEMON_SUPPORTED_CLIENT_CAPABILITIES,
type DaemonAttachResult,
type DaemonClientCapability,
type DaemonClosingReason,
@@ -142,6 +145,7 @@ import {
isDaemonDialogExtensionUiRequest,
success,
} from "./daemon-protocol.js";
+import { getDaemonRuntimeIdentity } from "./daemon-runtime-identity.js";
import {
buildRlmChildSnapshots,
buildSessionList,
@@ -280,15 +284,7 @@ const DAEMON_COMMAND_TYPES: ReadonlySet<string> = new Set([
"shutdown",
]);
-const DAEMON_SERVER_CAPABILITIES: readonly DaemonClientCapability[] = [
- "attach_snapshot",
- "event_sequence",
- "extension_ui",
- "slim_attach",
- "chunked_snapshot",
-];
-
-const DAEMON_CLIENT_CAPABILITY_SET: ReadonlySet<string> = new Set(DAEMON_SERVER_CAPABILITIES);
+const DAEMON_CLIENT_CAPABILITY_SET: ReadonlySet<string> = new Set(DAEMON_SUPPORTED_CLIENT_CAPABILITIES);
const UPDATE_RESTART_ABORT_BASH_TIMEOUT_MS = 5000;
const SUPERVISOR_FENCE_POLL_MS = 250;
const UPDATE_RESTART_MARKER =
@@ -2267,9 +2263,11 @@ export class AgentDaemon {
type: "daemon_hello",
socketPath: this.socketPath,
protocol: DAEMON_PROTOCOL_INFO,
+ schemaId: DAEMON_SCHEMA_ID,
appVersion: VERSION,
+ runtime: getDaemonRuntimeIdentity(),
clientId: client.id,
- serverCapabilities: DAEMON_SERVER_CAPABILITIES,
+ serverCapabilities: DAEMON_DEFAULT_SERVER_CAPABILITIES,
});
if (client.transport === "private-framed") {
diff --git a/packages/coding-agent/src/modes/daemon/daemon-protocol.ts b/packages/coding-agent/src/modes/daemon/daemon-protocol.ts
index 9fbc48d385..e363db2e9a 100644
--- a/packages/coding-agent/src/modes/daemon/daemon-protocol.ts
+++ b/packages/coding-agent/src/modes/daemon/daemon-protocol.ts
@@ -43,8 +43,10 @@ import type { SessionSummary } from "./daemon-session-list.js";
*/
export const DAEMON_PROTOCOL_NAME = "prime-agent.daemon";
-export const DAEMON_PROTOCOL_VERSION = 3;
+export const DAEMON_PROTOCOL_VERSION = 4;
export const DAEMON_COMMAND_ENVELOPE_MIN_PROTOCOL_VERSION = 2;
+export const DAEMON_SCHEMA_REVISION = 1;
+export const DAEMON_SCHEMA_ID = "protocol-4-schema-1-07ce10c7f10a";
export type DaemonProtocolName = typeof DAEMON_PROTOCOL_NAME;
export type DaemonProtocolVersion = number;
@@ -62,6 +64,7 @@ export type DaemonClientCapability =
| "extension_ui"
| "slim_attach"
| "chunked_snapshot";
+export type DaemonServerCapability = DaemonClientCapability | "heartbeat_catalog" | "heartbeat_management";
export type DaemonReplayStatus = "complete" | "partial" | "unavailable";
export interface DaemonProtocolInfo {
@@ -79,6 +82,27 @@ export const DAEMON_DEFAULT_CLIENT_CAPABILITIES: readonly DaemonClientCapability
"event_sequence",
];
+export const DAEMON_SUPPORTED_CLIENT_CAPABILITIES: readonly DaemonClientCapability[] = [
+ "attach_snapshot",
+ "event_sequence",
+ "extension_ui",
+ "slim_attach",
+ "chunked_snapshot",
+];
+
+export const DAEMON_DEFAULT_SERVER_CAPABILITIES: readonly DaemonServerCapability[] = [
+ ...DAEMON_SUPPORTED_CLIENT_CAPABILITIES,
+ "heartbeat_catalog",
+ "heartbeat_management",
+];
+
+export interface DaemonRuntimeIdentity {
+ buildId: string;
+ executablePath: string;
+ entrypointPath?: string;
+ launcherPath?: string;
+}
+
export type DaemonResumeCursor =
| ({ activeSessionId?: string } & DaemonEventCursor)
| { activeSessionId?: string; eventSequence: DaemonEventSequence };
@@ -477,6 +501,100 @@ export type DaemonCommand =
type DaemonCommandName = DaemonCommand["type"];
+export interface DaemonCommandCompatibility {
+ minProtocol: number;
+ capability?: DaemonServerCapability;
+}
+
+const LEGACY_DAEMON_COMMAND = { minProtocol: 1 } as const;
+
+export const DAEMON_COMMAND_COMPATIBILITY = {
+ ack_result: LEGACY_DAEMON_COMMAND,
+ list: LEGACY_DAEMON_COMMAND,
+ list_saved_sessions: LEGACY_DAEMON_COMMAND,
+ create: LEGACY_DAEMON_COMMAND,
+ attach: LEGACY_DAEMON_COMMAND,
+ reattach: LEGACY_DAEMON_COMMAND,
+ detach: LEGACY_DAEMON_COMMAND,
+ kill: LEGACY_DAEMON_COMMAND,
+ rename: LEGACY_DAEMON_COMMAND,
+ prompt: LEGACY_DAEMON_COMMAND,
+ steer: LEGACY_DAEMON_COMMAND,
+ follow_up: LEGACY_DAEMON_COMMAND,
+ restore_next_turn: LEGACY_DAEMON_COMMAND,
+ append_custom_message: LEGACY_DAEMON_COMMAND,
+ resume_queue: LEGACY_DAEMON_COMMAND,
+ send_message: LEGACY_DAEMON_COMMAND,
+ agent_messages_status: LEGACY_DAEMON_COMMAND,
+ agent_messages_pause: LEGACY_DAEMON_COMMAND,
+ agent_messages_resume: LEGACY_DAEMON_COMMAND,
+ agent_messages_clear: LEGACY_DAEMON_COMMAND,
+ abort: LEGACY_DAEMON_COMMAND,
+ start_side_question: LEGACY_DAEMON_COMMAND,
+ abort_side_question: LEGACY_DAEMON_COMMAND,
+ execute_bash: LEGACY_DAEMON_COMMAND,
+ abort_bash: LEGACY_DAEMON_COMMAND,
+ cancel_rlm_child: LEGACY_DAEMON_COMMAND,
+ wait_for_idle: LEGACY_DAEMON_COMMAND,
+ get_state: LEGACY_DAEMON_COMMAND,
+ get_connection_state: LEGACY_DAEMON_COMMAND,
+ get_messages: LEGACY_DAEMON_COMMAND,
+ get_session_stats: LEGACY_DAEMON_COMMAND,
+ get_context_tree: LEGACY_DAEMON_COMMAND,
+ get_commands: LEGACY_DAEMON_COMMAND,
+ get_resource_snapshot: LEGACY_DAEMON_COMMAND,
+ get_available_models: LEGACY_DAEMON_COMMAND,
+ get_queue: LEGACY_DAEMON_COMMAND,
+ clear_queue: LEGACY_DAEMON_COMMAND,
+ abort_and_clear_queue: LEGACY_DAEMON_COMMAND,
+ cron_list: LEGACY_DAEMON_COMMAND,
+ heartbeats_list: { minProtocol: 3, capability: "heartbeat_catalog" },
+ heartbeat_manage: { minProtocol: 3, capability: "heartbeat_management" },
+ cron_add: LEGACY_DAEMON_COMMAND,
+ cron_cancel: LEGACY_DAEMON_COMMAND,
+ heartbeat_get: LEGACY_DAEMON_COMMAND,
+ heartbeat_set: LEGACY_DAEMON_COMMAND,
+ heartbeat_update: LEGACY_DAEMON_COMMAND,
+ set_model: LEGACY_DAEMON_COMMAND,
+ cycle_model: LEGACY_DAEMON_COMMAND,
+ set_scoped_models: LEGACY_DAEMON_COMMAND,
+ set_thinking_level: LEGACY_DAEMON_COMMAND,
+ set_service_tier: LEGACY_DAEMON_COMMAND,
+ cycle_thinking_level: LEGACY_DAEMON_COMMAND,
+ set_transport: LEGACY_DAEMON_COMMAND,
+ set_steering_mode: LEGACY_DAEMON_COMMAND,
+ set_follow_up_mode: LEGACY_DAEMON_COMMAND,
+ set_auto_compaction: LEGACY_DAEMON_COMMAND,
+ compact: LEGACY_DAEMON_COMMAND,
+ refine: LEGACY_DAEMON_COMMAND,
+ abort_compaction: LEGACY_DAEMON_COMMAND,
+ abort_branch_summary: LEGACY_DAEMON_COMMAND,
+ abort_retry: LEGACY_DAEMON_COMMAND,
+ reload: LEGACY_DAEMON_COMMAND,
+ new_session: LEGACY_DAEMON_COMMAND,
+ switch_session: LEGACY_DAEMON_COMMAND,
+ fork: LEGACY_DAEMON_COMMAND,
+ navigate_tree: LEGACY_DAEMON_COMMAND,
+ import_jsonl: LEGACY_DAEMON_COMMAND,
+ export_html: LEGACY_DAEMON_COMMAND,
+ export_jsonl: LEGACY_DAEMON_COMMAND,
+ set_session_name: LEGACY_DAEMON_COMMAND,
+ rename_saved_session: LEGACY_DAEMON_COMMAND,
+ delete_saved_session: LEGACY_DAEMON_COMMAND,
+ get_session_context: LEGACY_DAEMON_COMMAND,
+ get_session_tree: LEGACY_DAEMON_COMMAND,
+ get_user_messages_for_forking: LEGACY_DAEMON_COMMAND,
+ get_last_assistant_text: LEGACY_DAEMON_COMMAND,
+ get_system_prompt: LEGACY_DAEMON_COMMAND,
+ get_tool_definition: LEGACY_DAEMON_COMMAND,
+ set_session_entry_label: LEGACY_DAEMON_COMMAND,
+ extension_ui_response: LEGACY_DAEMON_COMMAND,
+ prepare_update_restart: LEGACY_DAEMON_COMMAND,
+ retry_worker: LEGACY_DAEMON_COMMAND,
+ restart: LEGACY_DAEMON_COMMAND,
+ shutdown: LEGACY_DAEMON_COMMAND,
+} as const satisfies Record<DaemonCommandName, DaemonCommandCompatibility>;
+
export type DaemonResponse =
| { id?: string; type: "response"; command: string; success: true; data?: unknown }
| {
@@ -559,8 +677,10 @@ export type DaemonOutbound =
type: "daemon_hello";
socketPath: string;
protocol: DaemonProtocolInfo;
+ schemaId?: string;
/** App version of the daemon process, used to detect stale daemons after self-update. */
appVersion?: string;
+ runtime?: DaemonRuntimeIdentity;
/** Changes whenever the public supervisor process is replaced. */
supervisorGeneration?: string;
/** Diagnostic process identity for attributing supervisor replacement. */
@@ -572,7 +692,7 @@ export type DaemonOutbound =
/** Normalized socket identity stored in the durable owner record. */
supervisorSocketPath?: string;
clientId: DaemonClientId;
- serverCapabilities: readonly DaemonClientCapability[];
+ serverCapabilities: readonly DaemonServerCapability[];
}
| { type: "daemon_closing"; reason: DaemonClosingReason }
| { type: "heartbeats_changed" }
@@ -651,6 +771,29 @@ export type DaemonOutbound =
meta?: DaemonEventMeta;
};
+export const DAEMON_OUTBOUND_COMPATIBILITY = {
+ response: LEGACY_DAEMON_COMMAND,
+ session_list_progress: LEGACY_DAEMON_COMMAND,
+ session_list_item: LEGACY_DAEMON_COMMAND,
+ daemon_hello: LEGACY_DAEMON_COMMAND,
+ daemon_closing: LEGACY_DAEMON_COMMAND,
+ heartbeats_changed: { minProtocol: 3, capability: "heartbeat_catalog" },
+ session_event: LEGACY_DAEMON_COMMAND,
+ side_question_event: LEGACY_DAEMON_COMMAND,
+ session_status: LEGACY_DAEMON_COMMAND,
+ session_replaced: LEGACY_DAEMON_COMMAND,
+ session_resynced: LEGACY_DAEMON_COMMAND,
+ session_attached: LEGACY_DAEMON_COMMAND,
+ session_snapshot_begin: LEGACY_DAEMON_COMMAND,
+ session_snapshot_chunk: LEGACY_DAEMON_COMMAND,
+ session_snapshot_end: LEGACY_DAEMON_COMMAND,
+ session_snapshot_failed: LEGACY_DAEMON_COMMAND,
+ session_detached: LEGACY_DAEMON_COMMAND,
+ session_closed: LEGACY_DAEMON_COMMAND,
+ extension_ui_request: LEGACY_DAEMON_COMMAND,
+ extension_error: LEGACY_DAEMON_COMMAND,
+} as const satisfies Record<DaemonOutbound["type"], DaemonCommandCompatibility>;
+
export function createDaemonCommandEnvelope<TCommand extends DaemonCommand>(
command: TCommand,
id: DaemonCommandId,
diff --git a/packages/coding-agent/src/modes/daemon/daemon-runtime-identity.ts b/packages/coding-agent/src/modes/daemon/daemon-runtime-identity.ts
new file mode 100644
index 0000000000..6f286b7bbb
--- /dev/null
+++ b/packages/coding-agent/src/modes/daemon/daemon-runtime-identity.ts
@@ -0,0 +1,23 @@
+import { resolve } from "node:path";
+import { VERSION } from "../../config.js";
+import type { DaemonRuntimeIdentity } from "./daemon-protocol.js";
+
+declare const __PI_BUILD_ID__: string | undefined;
+
+export const PRIME_AGENT_BUILD_ID_ENV = "PRIME_AGENT_BUILD_ID";
+export const PRIME_AGENT_LAUNCHER_PATH_ENV = "PRIME_AGENT_LAUNCHER_PATH";
+
+function bundledBuildId(): string | undefined {
+ return typeof __PI_BUILD_ID__ === "undefined" ? undefined : __PI_BUILD_ID__;
+}
+
+export function getDaemonRuntimeIdentity(environment: NodeJS.ProcessEnv = process.env): DaemonRuntimeIdentity {
+ const entrypoint = process.argv[1];
+ const launcher = environment[PRIME_AGENT_LAUNCHER_PATH_ENV];
+ return {
+ buildId: environment[PRIME_AGENT_BUILD_ID_ENV] ?? bundledBuildId() ?? `release-${VERSION}`,
+ executablePath: resolve(process.execPath),
+ ...(entrypoint ? { entrypointPath: resolve(entrypoint) } : {}),
+ ...(launcher ? { launcherPath: resolve(launcher) } : {}),
+ };
+}
diff --git a/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts b/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts
index 141bbce2f7..46da081dce 100644
--- a/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts
+++ b/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts
@@ -42,9 +42,12 @@ import {
collectDaemonClientEnv,
createDaemonEventMeta,
DAEMON_DEFAULT_CLIENT_CAPABILITIES,
+ DAEMON_DEFAULT_SERVER_CAPABILITIES,
DAEMON_PROTOCOL_INFO,
+ DAEMON_SCHEMA_ID,
type DaemonAttachResult,
type DaemonClientCapability,
+ type DaemonClosingReason,
type DaemonCommand,
type DaemonOutbound,
type DaemonResponse,
@@ -55,6 +58,7 @@ import {
isDaemonMutatingCommand,
success,
} from "./daemon-protocol.js";
+import { getDaemonRuntimeIdentity } from "./daemon-runtime-identity.js";
import { matchesSessionIdSuffix } from "./daemon-session-id.js";
import { type SessionSummary, summaryForInactiveSession } from "./daemon-session-list.js";
import {
@@ -795,20 +799,16 @@ export class DaemonSupervisor {
type: "daemon_hello",
socketPath: this.socketPath,
protocol: DAEMON_PROTOCOL_INFO,
+ schemaId: DAEMON_SCHEMA_ID,
appVersion: VERSION,
+ runtime: getDaemonRuntimeIdentity(),
supervisorGeneration: this.generation,
supervisorOwnerToken: this.ownership?.record.token,
supervisorPid: process.pid,
supervisorProcessStartId: this.ownership?.record.processStartId,
supervisorSocketPath: this.ownership?.record.socketPath,
clientId: client.id,
- serverCapabilities: [
- "attach_snapshot",
- "event_sequence",
- "extension_ui",
- "slim_attach",
- "chunked_snapshot",
- ],
+ serverCapabilities: DAEMON_DEFAULT_SERVER_CAPABILITIES,
});
}
},
@@ -1052,10 +1052,10 @@ export class DaemonSupervisor {
return success(command.id, command.type, summary ? this.publicSummary(worker, summary) : undefined);
}
case "restart":
- setImmediate(() => void this.shutdown(0, false, true));
+ setImmediate(() => void this.shutdown(0, false, true, false, "update"));
return success(command.id, command.type);
case "shutdown":
- setImmediate(() => void this.shutdown(0, true, false, command.force === true));
+ setImmediate(() => void this.shutdown(0, true, false, command.force === true, "shutdown"));
return success(command.id, "shutdown");
case "prepare_update_restart": {
const manifest = await this.prepareUpdateRestart();
@@ -3685,11 +3685,17 @@ export class DaemonSupervisor {
stopWorkers: boolean,
relaunch = false,
forceWorkers = false,
+ closingReason?: DaemonClosingReason,
): Promise<never> {
if (this.shuttingDown) {
process.exit(exitCode);
}
this.shuttingDown = true;
+ if (closingReason) {
+ for (const client of this.clients) {
+ this.write(client, { type: "daemon_closing", reason: closingReason });
+ }
+ }
for (const cleanup of this.signalCleanupHandlers) {
cleanup();
}
diff --git a/packages/coding-agent/src/modes/interactive/interactive-mode.ts b/packages/coding-agent/src/modes/interactive/interactive-mode.ts
index ca36b71c8a..ff3696d0cc 100644
--- a/packages/coding-agent/src/modes/interactive/interactive-mode.ts
+++ b/packages/coding-agent/src/modes/interactive/interactive-mode.ts
@@ -2577,7 +2577,7 @@ export class InteractiveMode {
this.showLoadedResources({ force: false, showDiagnosticsWhenQuiet: true });
}
this.subscribeToAgent();
- await Promise.all([this.refreshConnectionQueue(), this.refreshHeartbeatCatalog()]);
+ await Promise.all([this.refreshConnectionQueue(), this.refreshHeartbeatCatalog().catch(() => undefined)]);
await this.updateAvailableProviderCount();
this.updateEditorBorderColor();
this.updateTerminalTitle();
diff --git a/packages/coding-agent/src/package-manager-cli.ts b/packages/coding-agent/src/package-manager-cli.ts
index 5df6a7aae8..e3ced746e8 100644
--- a/packages/coding-agent/src/package-manager-cli.ts
+++ b/packages/coding-agent/src/package-manager-cli.ts
@@ -49,6 +49,7 @@ import { SettingsManager } from "./core/settings-manager.js";
import { DaemonClient, type DaemonHello } from "./modes/daemon/daemon-client.js";
import {
DAEMON_PROTOCOL_VERSION,
+ DAEMON_SCHEMA_ID,
type DaemonUpdateRestartManifest,
type DaemonUpdateRestartQueuedMessage,
type DaemonUpdateRestartSession,
@@ -1240,9 +1241,14 @@ function validateReplacementDaemon(
hello: DaemonHello,
predecessor: DaemonUpdateRestartProcessIdentity | undefined,
): DaemonUpdateRestartProcessIdentity {
- if (hello.protocol.version !== DAEMON_PROTOCOL_VERSION || hello.appVersion !== VERSION) {
+ if (
+ hello.protocol.version !== DAEMON_PROTOCOL_VERSION ||
+ hello.schemaId !== DAEMON_SCHEMA_ID ||
+ hello.appVersion !== VERSION
+ ) {
throw new Error(
- `Replacement daemon is v${hello.appVersion}/proto${hello.protocol.version}, expected v${VERSION}/proto${DAEMON_PROTOCOL_VERSION}`,
+ `Replacement daemon is v${hello.appVersion}/proto${hello.protocol.version}/schema ${hello.schemaId ?? "legacy"}, ` +
+ `expected v${VERSION}/proto${DAEMON_PROTOCOL_VERSION}/schema ${DAEMON_SCHEMA_ID}`,
);
}
if (
diff --git a/packages/coding-agent/test/agent-connection-daemon.test.ts b/packages/coding-agent/test/agent-connection-daemon.test.ts
index a180d9af8e..83e8c7f8a0 100644
--- a/packages/coding-agent/test/agent-connection-daemon.test.ts
+++ b/packages/coding-agent/test/agent-connection-daemon.test.ts
@@ -18,6 +18,7 @@ import {
type DaemonClientCloseListener,
type DaemonClientMessageListener,
type DaemonClientRequestOptions,
+ type DaemonHello,
DaemonSocketClosedError,
} from "../src/modes/daemon/daemon-client.js";
import {
@@ -45,7 +46,10 @@ class FakeDaemonClient {
connectionStateFactory: ((activeSessionId: string) => AgentConnectionState) | undefined;
abortBashUnknownCommand = false;
abortAndClearQueueUnknownCommand = false;
+ legacyHeartbeatCommandsSupported = false;
+ serverCapabilities = new Set<string>();
updateRestartSessions: Array<Record<string, unknown>> = [];
+ hello: DaemonHello | undefined;
private readonly messageListeners = new Set<DaemonClientMessageListener>();
private readonly closeListeners = new Set<DaemonClientCloseListener>();
@@ -218,6 +222,29 @@ class FakeDaemonClient {
success: true,
data: { steering: ["aborted"], followUp: ["cleared"] },
};
+ case "heartbeats_list":
+ return this.legacyHeartbeatCommandsSupported
+ ? { type: "response", command: command.type, success: true, data: { heartbeats: [] } }
+ : {
+ type: "response",
+ command: command.type,
+ success: false,
+ error: "Unknown daemon command: heartbeats_list",
+ };
+ case "heartbeat_manage":
+ return this.legacyHeartbeatCommandsSupported
+ ? {
+ type: "response",
+ command: command.type,
+ success: true,
+ data: { heartbeat: { id: command.jobId } },
+ }
+ : {
+ type: "response",
+ command: command.type,
+ success: false,
+ error: "Unknown daemon command: heartbeat_manage",
+ };
case "list_saved_sessions": {
const activeSessionId = "activeSessionId" in command ? command.activeSessionId : undefined;
options.onProgress?.({
@@ -367,6 +394,18 @@ class FakeDaemonClient {
}
}
+ async requestLegacy(
+ command: DaemonCommand,
+ timeoutMs = 30000,
+ options: DaemonClientRequestOptions = {},
+ ): Promise<DaemonResponse> {
+ return this.request(command, timeoutMs, options);
+ }
+
+ supportsServerCapability(capability: string): boolean {
+ return this.serverCapabilities.has(capability);
+ }
+
onMessage(listener: DaemonClientMessageListener): () => void {
this.messageListeners.add(listener);
return () => {
@@ -591,6 +630,55 @@ function emitSequencedQueueUpdate(client: FakeDaemonClient, activeSessionId: str
}
describe("DaemonAgentConnection", () => {
+ it("degrades an unavailable heartbeat catalog without sending an unsupported command", async () => {
+ const fakeClient = new FakeDaemonClient();
+ const connection = new DaemonAgentConnection(asDaemonClient(fakeClient), "active-original");
+
+ await expect(connection.listHeartbeats()).resolves.toEqual([]);
+ expect(fakeClient.requests).toEqual([]);
+ await expect(connection.manageHeartbeat("active-original", "job-1", "pause")).rejects.toThrow(
+ "requires a newer Prime Agent daemon",
+ );
+ expect(fakeClient.requests).toEqual([]);
+ });
+
+ it("uses heartbeat commands supported by a retained protocol-3 daemon", async () => {
+ const fakeClient = new FakeDaemonClient();
+ fakeClient.hello = {
+ type: "daemon_hello",
+ socketPath: "/tmp/prime-agent.sock",
+ protocol: { ...DAEMON_PROTOCOL_INFO, version: 3 },
+ clientId: "legacy-client",
+ serverCapabilities: [],
+ };
+ fakeClient.legacyHeartbeatCommandsSupported = true;
+ const connection = new DaemonAgentConnection(asDaemonClient(fakeClient), "active-original");
+
+ await expect(connection.listHeartbeats()).resolves.toEqual([]);
+ await expect(connection.manageHeartbeat("active-original", "job-1", "pause")).resolves.toMatchObject({
+ id: "job-1",
+ });
+ expect(fakeClient.requests.map((request) => request.type)).toEqual(["heartbeats_list", "heartbeat_manage"]);
+ });
+
+ it("degrades heartbeat commands missing from an older protocol-3 daemon", async () => {
+ const fakeClient = new FakeDaemonClient();
+ fakeClient.hello = {
+ type: "daemon_hello",
+ socketPath: "/tmp/prime-agent.sock",
+ protocol: { ...DAEMON_PROTOCOL_INFO, version: 3 },
+ clientId: "legacy-client",
+ serverCapabilities: [],
+ };
+ const connection = new DaemonAgentConnection(asDaemonClient(fakeClient), "active-original");
+
+ await expect(connection.listHeartbeats()).resolves.toEqual([]);
+ await expect(connection.manageHeartbeat("active-original", "job-1", "pause")).rejects.toThrow(
+ "Heartbeat management requires a newer Prime Agent daemon.",
+ );
+ expect(fakeClient.requests.map((request) => request.type)).toEqual(["heartbeats_list", "heartbeat_manage"]);
+ });
+
it("reattaches an open window to its restored session after an update restart", async () => {
const fakeClient = new FakeDaemonClient();
fakeClient.emitCloseOnClose = true;
@@ -625,9 +713,10 @@ describe("DaemonAgentConnection", () => {
activeSessionId: "active-original",
reason: "update",
});
- await Promise.resolve();
- expect(fakeClient.closeCount).toBe(1);
- expect(fakeClient.reconnectCount).toBe(1);
+ await vi.waitFor(() => {
+ expect(fakeClient.closeCount).toBe(1);
+ expect(fakeClient.reconnectCount).toBe(1);
+ });
await expect(restored).resolves.toMatchObject({
type: "session_resynced",
@@ -643,14 +732,18 @@ describe("DaemonAgentConnection", () => {
activeSessionId: "active-restored",
resumeCursor: undefined,
});
- expect(events).toEqual([
- expect.objectContaining({
- type: "session_resynced",
- snapshot: expect.objectContaining({
- state: expect.objectContaining({ activeSessionId: "active-restored" }),
+ await vi.waitFor(() => {
+ expect(events).toEqual([
+ expect.objectContaining({ type: "connection_status", status: "reconnecting" }),
+ expect.objectContaining({
+ type: "session_resynced",
+ snapshot: expect.objectContaining({
+ state: expect.objectContaining({ activeSessionId: "active-restored" }),
+ }),
}),
- }),
- ]);
+ { type: "connection_status", status: "connected" },
+ ]);
+ });
});
it("reattaches when an update socket close arrives before the session notice", async () => {
@@ -914,7 +1007,7 @@ describe("DaemonAgentConnection", () => {
await Promise.resolve();
}
- expect(events).toEqual([]);
+ expect(events).toEqual([expect.objectContaining({ type: "connection_status", status: "reconnecting" })]);
expect(fakeClient.requests.at(-1)).toMatchObject({ type: "detach", activeSessionId: "active-restored" });
});
@@ -1725,6 +1818,35 @@ describe("DaemonAgentConnection", () => {
expect(fakeClient.reconnectCount).toBe(1);
});
+ it("does not let a stalled subscriber block update recovery", async () => {
+ const fakeClient = new FakeDaemonClient();
+ fakeClient.updateRestartSessions = [
+ {
+ id: "active-restored",
+ activeSessionId: "active-restored",
+ sessionId: "session-current",
+ sessionFile: "/tmp/session-current.jsonl",
+ },
+ ];
+ const connection = new DaemonAgentConnection(asDaemonClient(fakeClient), "active-original");
+ const statuses: string[] = [];
+ connection.subscribe(() => new Promise<void>(() => undefined));
+ connection.subscribe((event) => {
+ if (event.type === "connection_status") {
+ statuses.push(event.status);
+ }
+ });
+ await connection.attach();
+
+ fakeClient.emitClose(new DaemonSocketClosedError("/tmp/prime-agent.sock", "update"));
+
+ await vi.waitFor(() => expect(statuses).toEqual(["reconnecting", "connected"]));
+ expect(fakeClient.requests.at(-1)).toMatchObject({
+ type: "attach",
+ activeSessionId: "active-restored",
+ });
+ });
+
it("refreshes initial snapshots after live events make the cached snapshot stale", async () => {
const fakeClient = new FakeDaemonClient();
fakeClient.attachResultFactory = (command) =>
diff --git a/packages/coding-agent/test/daemon-client.test.ts b/packages/coding-agent/test/daemon-client.test.ts
index 77b488fe13..086ab4acec 100644
--- a/packages/coding-agent/test/daemon-client.test.ts
+++ b/packages/coding-agent/test/daemon-client.test.ts
@@ -191,6 +191,38 @@ describe("DaemonClient", () => {
client.close();
});
+ it("rejects unsupported optional commands without writing them to an older daemon", 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, 3);
+
+ expect(client.supportsServerCapability("heartbeat_catalog")).toBe(false);
+ await expect(client.request({ type: "heartbeats_list" })).rejects.toThrow("does not support heartbeat_catalog");
+ expect(socket.writes).toEqual([]);
+ client.close();
+ });
+
+ it("isolates a message consumer failure from the rest of the client", 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);
+ let delivered = 0;
+ client.onMessage(() => {
+ throw new Error("broken optional consumer");
+ });
+ client.onMessage(() => delivered++);
+
+ expect(() => socket.emit("data", `${JSON.stringify({ type: "heartbeats_changed" })}\n`)).not.toThrow();
+ expect(delivered).toBe(1);
+ client.close();
+ });
+
it("serializes activeSessionId for session commands", async () => {
const client = new DaemonClient("/tmp/prime-agent.sock");
diff --git a/packages/coding-agent/test/daemon-launch.test.ts b/packages/coding-agent/test/daemon-launch.test.ts
index af3b063e1f..2afac0fff6 100644
--- a/packages/coding-agent/test/daemon-launch.test.ts
+++ b/packages/coding-agent/test/daemon-launch.test.ts
@@ -5,10 +5,14 @@ import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, describe, expect, it } from "vitest";
import {
+ ensureInteractiveDaemonRunning,
+ probeDaemonVersion,
probeRunningDaemonSessions,
shouldStartInteractiveDaemonEarly,
shutdownDaemonAndWait,
} from "../src/cli/daemon-launch.js";
+import { VERSION } from "../src/config.js";
+import { DAEMON_PROTOCOL_VERSION, DAEMON_SCHEMA_ID } from "../src/modes/daemon/daemon-protocol.js";
interface FakeDaemonOptions {
/** Sessions returned for a `list` command. */
@@ -17,6 +21,10 @@ interface FakeDaemonOptions {
failList?: boolean;
/** When false, the server ignores `shutdown` and stays up. */
respondToShutdown?: boolean;
+ protocolVersion?: number;
+ appVersion?: string;
+ schemaId?: string;
+ onCommand?: (command: { type: string }) => void;
}
interface FakeDaemon {
@@ -32,7 +40,16 @@ async function startFakeDaemon(options: FakeDaemonOptions = {}): Promise<FakeDae
const dir = mkdtempSync(join(tmpdir(), "pa-launch-"));
const socketPath = join(dir, "d.sock");
const server: Server = createServer((socket) => {
- send(socket, { type: "daemon_hello", socketPath, protocol: { name: "prime-agent-daemon", version: 1 } });
+ socket.on("error", () => undefined);
+ send(socket, {
+ type: "daemon_hello",
+ socketPath,
+ protocol: { name: "prime-agent-daemon", version: options.protocolVersion ?? 1 },
+ appVersion: options.appVersion,
+ schemaId: options.schemaId,
+ clientId: "fake-client",
+ serverCapabilities: [],
+ });
let buffer = "";
socket.on("data", (chunk) => {
buffer += chunk.toString();
@@ -44,7 +61,13 @@ async function startFakeDaemon(options: FakeDaemonOptions = {}): Promise<FakeDae
if (!line.trim()) {
continue;
}
- const command = JSON.parse(line) as { type: string; id: string };
+ const wire = JSON.parse(line) as {
+ type: string;
+ id: string;
+ command?: { type: string; id: string };
+ };
+ const command = wire.type === "command" && wire.command ? wire.command : wire;
+ options.onCommand?.(command);
if (command.type === "list") {
send(socket, {
type: "response",
@@ -192,6 +215,42 @@ describe("shouldStartInteractiveDaemonEarly", () => {
});
});
+describe("ensureInteractiveDaemonRunning", () => {
+ const cleanups: Array<() => Promise<void>> = [];
+ afterEach(async () => {
+ await Promise.all(cleanups.splice(0).map((fn) => fn()));
+ });
+
+ it("keeps a compatible protocol-3 daemon serving busy work instead of bricking startup", async () => {
+ const commands: string[] = [];
+ const daemon = await startFakeDaemon({
+ protocolVersion: 3,
+ appVersion: VERSION,
+ sessions: [{ id: "active-1", activeSessionId: "active-1", isStreaming: true }],
+ onCommand: (command) => commands.push(command.type),
+ });
+ cleanups.push(daemon.close);
+
+ await expect(ensureInteractiveDaemonRunning(daemon.socketPath)).resolves.toBeUndefined();
+ expect(commands).toContain("list");
+ expect(commands).not.toContain("shutdown");
+ });
+
+ it("does not treat a live daemon as absent when cold startup delays the first connection", async () => {
+ const daemon = await startFakeDaemon({
+ protocolVersion: DAEMON_PROTOCOL_VERSION,
+ appVersion: VERSION,
+ schemaId: DAEMON_SCHEMA_ID,
+ });
+ cleanups.push(daemon.close);
+
+ const probe = probeDaemonVersion(daemon.socketPath);
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 300);
+
+ await expect(probe).resolves.toMatchObject({ status: "current" });
+ });
+});
+
describe("shutdownDaemonAndWait", () => {
const cleanups: Array<() => Promise<void>> = [];
afterEach(async () => {
diff --git a/packages/coding-agent/test/daemon-protocol.test.ts b/packages/coding-agent/test/daemon-protocol.test.ts
index b9cd8c65a9..fc99b52891 100644
--- a/packages/coding-agent/test/daemon-protocol.test.ts
+++ b/packages/coding-agent/test/daemon-protocol.test.ts
@@ -1,16 +1,59 @@
+import { createHash } from "node:crypto";
+import { readFileSync } from "node:fs";
+import { resolve } from "node:path";
import { describe, expect, it } from "vitest";
import {
createDaemonCommandEnvelope,
createDaemonEventEnvelope,
createDaemonEventMeta,
createDaemonReplayInfo,
+ DAEMON_COMMAND_COMPATIBILITY,
+ DAEMON_DEFAULT_SERVER_CAPABILITIES,
+ DAEMON_OUTBOUND_COMPATIBILITY,
DAEMON_PROTOCOL_INFO,
+ DAEMON_PROTOCOL_VERSION,
+ DAEMON_SCHEMA_ID,
+ DAEMON_SCHEMA_REVISION,
type DaemonOutbound,
isDaemonCommandEnvelope,
isDaemonMutatingCommand,
} from "../src/modes/daemon/daemon-protocol.js";
describe("daemon protocol helpers", () => {
+ it("keeps the advertised schema identity synchronized with wire type shapes", () => {
+ const source = readFileSync(resolve(__dirname, "../src/modes/daemon/daemon-protocol.ts"), "utf8");
+ const commandSource = source.slice(
+ source.indexOf("export type DaemonCommand ="),
+ source.indexOf("type DaemonCommandName"),
+ );
+ const outboundSource = source.slice(
+ source.indexOf("export type DaemonOutbound ="),
+ source.indexOf("export const DAEMON_OUTBOUND_COMPATIBILITY"),
+ );
+ const digest = createHash("sha256").update(`${commandSource}\n${outboundSource}`).digest("hex").slice(0, 12);
+ expect(DAEMON_SCHEMA_ID).toBe(`protocol-${DAEMON_PROTOCOL_VERSION}-schema-${DAEMON_SCHEMA_REVISION}-${digest}`);
+ });
+
+ it("requires compatibility metadata for the heartbeat protocol surface", () => {
+ expect(DAEMON_PROTOCOL_VERSION).toBe(4);
+ expect(DAEMON_SCHEMA_ID).toContain(`protocol-${DAEMON_PROTOCOL_VERSION}`);
+ expect(DAEMON_COMMAND_COMPATIBILITY.heartbeats_list).toEqual({
+ minProtocol: 3,
+ capability: "heartbeat_catalog",
+ });
+ expect(DAEMON_COMMAND_COMPATIBILITY.heartbeat_manage).toEqual({
+ minProtocol: 3,
+ capability: "heartbeat_management",
+ });
+ expect(DAEMON_OUTBOUND_COMPATIBILITY.heartbeats_changed).toEqual({
+ minProtocol: 3,
+ capability: "heartbeat_catalog",
+ });
+ expect(DAEMON_DEFAULT_SERVER_CAPABILITIES).toEqual(
+ expect.arrayContaining(["heartbeat_catalog", "heartbeat_management"]),
+ );
+ });
+
it("creates versioned command and event envelopes", () => {
const command = { id: "cmd-1", type: "attach", activeSessionId: "active-1" } as const;
const commandEnvelope = createDaemonCommandEnvelope(command, "cmd-1", "client-1");
diff --git a/packages/coding-agent/test/daemon-ps.test.ts b/packages/coding-agent/test/daemon-ps.test.ts
index ca20129d12..6233a9353e 100644
--- a/packages/coding-agent/test/daemon-ps.test.ts
+++ b/packages/coding-agent/test/daemon-ps.test.ts
@@ -2,15 +2,20 @@ import { join } from "node:path";
import { describe, expect, it } from "vitest";
import {
type DaemonInfo,
+ evaluateShutdownQuietPeriod,
isWorkerSocketPath,
+ mergeDiscoveredDaemonProcesses,
parseLsofListeners,
+ parsePrimeAgentProcessIds,
parsePsEtimes,
parseSsListeners,
planReap,
planShutdownAll,
planShutdownConfirmation,
sortDaemons,
+ verifyHelloSupervisorPid,
} from "../src/cli/daemon-ps.js";
+import { getProcessStartId } from "../src/core/session-lease.js";
import { defaultDaemonSocketDir } from "../src/modes/daemon/daemon-socket.js";
describe("worker socket classification", () => {
@@ -60,6 +65,57 @@ describe("parseLsofListeners", () => {
});
});
+describe("parsePrimeAgentProcessIds", () => {
+ it("finds process.title names even when lsof reports the executable as node", () => {
+ const stdout = [
+ " 123 node prime-agent --mode daemon",
+ " 456 prime-agent prime-agent",
+ " 789 /usr/local/bin/prime-agent prime-agent",
+ " 900 node unrelated.js",
+ "",
+ ].join("\n");
+ expect(parsePrimeAgentProcessIds(stdout, "prime-agent")).toEqual([123, 456, 789]);
+ });
+});
+
+describe("mergeDiscoveredDaemonProcesses", () => {
+ it("keeps process-title discoveries when lsof by name returned only a partial set", () => {
+ expect(
+ mergeDiscoveredDaemonProcesses(
+ [
+ { pid: 123, socketPath: "/tmp/by-name.sock" },
+ { pid: 456, socketPath: "/tmp/shared.sock" },
+ ],
+ [
+ { pid: 456, socketPath: "/tmp/shared.sock" },
+ { pid: 789, socketPath: "/tmp/by-pid.sock" },
+ ],
+ ),
+ ).toEqual([
+ { pid: 123, socketPath: "/tmp/by-name.sock" },
+ { pid: 456, socketPath: "/tmp/shared.sock" },
+ { pid: 789, socketPath: "/tmp/by-pid.sock" },
+ ]);
+ });
+});
+
+describe("evaluateShutdownQuietPeriod", () => {
+ it("requires a full quiet period independently of the convergence window", () => {
+ expect(evaluateShutdownQuietPeriod(10_500, 10_000)).toBe("waiting");
+ expect(evaluateShutdownQuietPeriod(11_000, 10_000)).toBe("complete");
+ });
+});
+
+describe("verifyHelloSupervisorPid", () => {
+ it("accepts the hello pid only while its process identity still matches", () => {
+ const processStartId = getProcessStartId(process.pid);
+ expect(verifyHelloSupervisorPid(process.pid, processStartId)).toBe(process.pid);
+ if (processStartId) {
+ expect(verifyHelloSupervisorPid(process.pid, `${processStartId}-stale`)).toBeUndefined();
+ }
+ });
+});
+
describe("parsePsEtimes", () => {
it("maps pid to elapsed seconds", () => {
const uptimes = parsePsEtimes(" 1234 86400\n 5678 42\n");
diff --git a/packages/coding-agent/test/daemon-supervisor-process.test.ts b/packages/coding-agent/test/daemon-supervisor-process.test.ts
index 1bf85f35a2..fab69f118c 100644
--- a/packages/coding-agent/test/daemon-supervisor-process.test.ts
+++ b/packages/coding-agent/test/daemon-supervisor-process.test.ts
@@ -14,7 +14,7 @@ import {
} 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 { DaemonClient, getDaemonSocketCloseReason } 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";
@@ -489,9 +489,13 @@ describe("daemon supervisor resident workers", () => {
const heartbeat = (heartbeatResponse.data as { heartbeat: { id: string } }).heartbeat;
const cronStore = AgentCronJobStore.forSessionArtifacts();
cronStore.registerSessionArtifact(summary.sessionId, sessionManager.getSessionArtifactDir()!);
+ const observer = await connectEventually(socketPath, supervisor);
+ const observerClosed = new Promise<Error>((resolveClose) => observer.onClose(resolveClose));
expect((await client.request({ type: "shutdown" })).success).toBe(true);
client.close();
+ expect(getDaemonSocketCloseReason(await observerClosed)).toBe("shutdown");
+ observer.close();
await waitForSocketGone(socketPath);
await waitForProcessGone(summary.workerPid);
workerPids.delete(summary.workerPid);
diff --git a/packages/coding-agent/test/interactive-mode-status.test.ts b/packages/coding-agent/test/interactive-mode-status.test.ts
index 1b8c0f7a17..045781f82f 100644
--- a/packages/coding-agent/test/interactive-mode-status.test.ts
+++ b/packages/coding-agent/test/interactive-mode-status.test.ts
@@ -678,6 +678,56 @@ describe("InteractiveMode pending bash components", () => {
});
describe("InteractiveMode connection events", () => {
+ test("degrades heartbeat refresh failures without hiding queue refresh failures during rebind", async () => {
+ const rebindCurrentSession = (
+ InteractiveMode.prototype as unknown as { rebindCurrentSession(this: InteractiveMode): Promise<void> }
+ ).rebindCurrentSession;
+ const createHarness = (
+ refreshConnectionQueue: () => Promise<void>,
+ refreshHeartbeatCatalog: () => Promise<void>,
+ ) =>
+ ({
+ unsubscribe: undefined,
+ localSessionHost: undefined,
+ toolDefinitionCache: { clear: vi.fn() },
+ applyRuntimeSettings: vi.fn(),
+ bindLocalSessionExtensions: true,
+ bindCurrentSessionExtensions: vi.fn(async () => {}),
+ subscribeToAgent: vi.fn(),
+ refreshConnectionQueue,
+ refreshHeartbeatCatalog,
+ updateAvailableProviderCount: vi.fn(async () => {}),
+ updateEditorBorderColor: vi.fn(),
+ updateTerminalTitle: vi.fn(),
+ setGoalAnnouncementBaseline: vi.fn(),
+ syncGoalTray: vi.fn(),
+ syncWorkingLoader: vi.fn(),
+ getGoalState: () => emptyGoalState(),
+ }) as unknown as InteractiveMode;
+
+ await expect(
+ rebindCurrentSession.call(
+ createHarness(
+ vi.fn(async () => {}),
+ vi.fn(async () => {
+ throw new Error("heartbeat unavailable");
+ }),
+ ),
+ ),
+ ).resolves.toBeUndefined();
+
+ await expect(
+ rebindCurrentSession.call(
+ createHarness(
+ vi.fn(async () => {
+ throw new Error("queue unavailable");
+ }),
+ vi.fn(async () => {}),
+ ),
+ ),
+ ).rejects.toThrow("queue unavailable");
+ });
+
test("restores in-flight assistant state on every session render", async () => {
const streamingMessage = {
role: "assistant",
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 cfe9783242..d80d3d3c1d 100644
--- a/packages/coding-agent/test/package-self-update-daemon.test.ts
+++ b/packages/coding-agent/test/package-self-update-daemon.test.ts
@@ -19,7 +19,7 @@ import {
VERSION,
} from "../src/config.js";
import type { AgentSessionRuntimeMetadata } from "../src/core/agent-session-runtime.js";
-import { DAEMON_PROTOCOL_VERSION } from "../src/modes/daemon/daemon-protocol.js";
+import { DAEMON_PROTOCOL_VERSION, DAEMON_SCHEMA_ID } from "../src/modes/daemon/daemon-protocol.js";
import type * as DaemonSocketModule from "../src/modes/daemon/daemon-socket.js";
import {
handlePackageCommand,
@@ -108,6 +108,7 @@ const mockState = vi.hoisted(() => ({
globalPackageRoot: "",
hello: { protocol: { version: 0 } } as {
protocol: { version: number };
+ schemaId?: string;
supervisorGeneration?: string;
supervisorOwnerToken?: string;
supervisorPid?: number;
@@ -140,6 +141,7 @@ const mockState = vi.hoisted(() => ({
function useFixedOwnerHello(): void {
mockState.hello = {
protocol: { version: DAEMON_PROTOCOL_VERSION },
+ schemaId: DAEMON_SCHEMA_ID,
supervisorGeneration: "fixed-owner",
supervisorOwnerToken: "owner-token",
supervisorPid: process.pid,
@@ -269,6 +271,7 @@ vi.mock("../src/modes/daemon/daemon-client.js", () => ({
async waitForHello(): Promise<{
protocol: { version: number };
+ schemaId?: string;
appVersion: string;
supervisorGeneration?: string;
supervisorOwnerToken?: string;
@@ -289,6 +292,7 @@ vi.mock("../src/modes/daemon/daemon-client.js", () => ({
}
: {
protocol: { version: DAEMON_PROTOCOL_VERSION },
+ schemaId: DAEMON_SCHEMA_ID,
appVersion: VERSION,
supervisorPid: 1002,
supervisorGeneration: "replacement-generation",
@@ -390,7 +394,7 @@ describe("self-update daemon restart", () => {
projectDir = join(tempDir, "project");
packageDir = join(tempDir, "global-prefix", "lib", "node_modules", PACKAGE_NAME);
mockState.globalPackageRoot = join(tempDir, "global-prefix", "lib", "node_modules");
- mockState.hello = { protocol: { version: DAEMON_PROTOCOL_VERSION } };
+ mockState.hello = { protocol: { version: DAEMON_PROTOCOL_VERSION }, schemaId: DAEMON_SCHEMA_ID };
mockState.helloCount = 0;
mockState.lastCoordinatorStatus = undefined;
mockState.listResponse = undefined;
diff --git a/prime-agent.sh b/prime-agent.sh
index f2ca65dd9e..8baf90081f 100755
--- a/prime-agent.sh
+++ b/prime-agent.sh
@@ -2,6 +2,10 @@
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+export PRIME_AGENT_LAUNCHER_PATH="$SCRIPT_DIR/prime-agent.sh"
+if BUILD_ID="$(git -C "$SCRIPT_DIR" describe --tags --always --dirty 2>/dev/null)"; then
+ export PRIME_AGENT_BUILD_ID="$BUILD_ID"
+fi
# Check for --no-env / --dist flags
NO_ENV=false