A self-improving RLM agent for coding workflows and long-running autonomous tasks.
Rust
fix(coding-agent): show why the daemon crashed instead of a generic timeout (#608)
Sebastian Müller315420208447
diff --git a/packages/coding-agent/CHANGELOG.md b/packages/coding-agent/CHANGELOG.mdindex fa23bb517a..b697beb8a8 100644--- a/packages/coding-agent/CHANGELOG.md+++ b/packages/coding-agent/CHANGELOG.md@@ -2,6 +2,8 @@## [Unreleased]+- Fixed daemon startup crashes hiding their exit status and daemon log until the startup timeout.+## [0.6.0] - 2026-08-04### Breaking Changesdiff --git a/packages/coding-agent/src/cli/daemon-launch.ts b/packages/coding-agent/src/cli/daemon-launch.tsindex c8c45b56b9..6de9285e90 100644--- a/packages/coding-agent/src/cli/daemon-launch.ts+++ b/packages/coding-agent/src/cli/daemon-launch.ts@@ -6,9 +6,9 @@*/import { spawn } from "node:child_process";-import { existsSync } from "node:fs";+import { existsSync, readFileSync, statSync } from "node:fs";import { resolve } from "node:path";-import { appendRotatingLog, expandTildePath, getClientErrorLogPath, VERSION } from "../config.js";+import { appendRotatingLog, expandTildePath, getClientErrorLogPath, getDaemonLogPath, VERSION } from "../config.js";import { ORPHAN_PROCESS_JOURNAL_ENV } from "../core/orphan-process-journal.js";import { getProcessStartId, SESSION_LEASE_OWNER_ID_ENV, SESSION_LEASES_ENABLED_ENV } from "../core/session-lease.js";import { DaemonClient, type DaemonHello } from "../modes/daemon/daemon-client.js";@@ -27,6 +27,8 @@ import { isHelpCommandRequest, PUBLIC_COMMAND_NAMES, REMOVED_COMMAND_NAMES } froimport { createCliSubprocessEnv, formatCurrentCliCommand } from "./subprocess-launch.js";const DAEMON_STARTUP_TIMEOUT_MS = 30_000;+const DAEMON_STARTUP_LOG_TAIL_BYTES = 4 * 1024;+const DAEMON_STARTUP_EXIT_GRACE_MS = 2_000;export function isDaemonSessionSummary(value: unknown): value is SessionSummary {if (!value || typeof value !== "object") {@@ -365,6 +367,7 @@ async function ensureDaemonRunning(socketPath: string, spawnCwd?: string): Promidelete env[SESSION_LEASES_ENABLED_ENV];delete env[SESSION_LEASE_OWNER_ID_ENV];+ const logOffset = currentDaemonLogSize(socketPath);const child = spawn(process.execPath,[...process.execArgv, entrypoint, "--mode", "daemon", "--daemon-socket", socketPath],@@ -372,23 +375,84 @@ async function ensureDaemonRunning(socketPath: string, spawnCwd?: string): Promicwd: spawnCwd ?? process.cwd(),detached: true,env,- // The daemon writes its own rotating log (see daemon-mode); nothing here- // needs its stdout/stderr, so leave them detached.+ // A pipe would tie the daemon's stderr to this short-lived CLI+ // (EPIPE once it exits); crash details come from the daemon log,+ // which the supervisor writes to before rethrowing startup errors.stdio: "ignore",},);+ let childFailure:+ | { type: "error"; error: Error }+ | { type: "exit"; code: number | null; signal: NodeJS.Signals | null }+ | undefined;+ child.once("error", (error) => {+ childFailure ??= { type: "error", error };+ });+ child.once("exit", (code, signal) => {+ childFailure ??= { type: "exit", code, signal };+ });child.unref();+ const throwIfFailed = () => {+ if (!childFailure) {+ return;+ }+ const logTail = readDaemonLogTail(socketPath, logOffset);+ if (childFailure.type === "error") {+ throw new Error(`Failed to spawn Prime Agent daemon: ${childFailure.error.message}.${logTail}`);+ }+ const signal = childFailure.signal ? `, signal ${childFailure.signal}` : "";+ throw new Error(+ `Prime Agent daemon exited during startup (code ${childFailure.code ?? "unknown"}${signal}).${logTail}`,+ );+ };++ // A child exit is not immediately fatal: it may have lost the socket to a+ // concurrent launcher whose daemon is still booting. Keep probing for a+ // short grace window before attributing the failure to the exit.const deadline = Date.now() + DAEMON_STARTUP_TIMEOUT_MS;- while (Date.now() < deadline) {+ let exitDeadline: number | undefined;+ while (Date.now() < Math.min(deadline, exitDeadline ?? Number.POSITIVE_INFINITY)) {const started = await probeDaemonVersion(socketPath);if (started.status === "current") {return;}+ if (childFailure) {+ exitDeadline ??= Date.now() + DAEMON_STARTUP_EXIT_GRACE_MS;+ }await delay(25);}- throw new Error(`Timed out waiting for daemon to start on ${socketPath}`);+ throwIfFailed();+ throw new Error(+ `Timed out waiting for daemon to start on ${socketPath}.${readDaemonLogTail(socketPath, logOffset)}`,+ );+}++function currentDaemonLogSize(socketPath: string): number {+ try {+ return statSync(getDaemonLogPath(socketPath)).size;+ } catch {+ return 0;+ }+}++/** Reads only log content written after `offset`, so stale content from earlier daemon runs is not misattributed to this startup attempt. */+function readDaemonLogTail(socketPath: string, offset: number): string {+ const logPath = getDaemonLogPath(socketPath);+ let tail = "";+ try {+ const content = readFileSync(logPath);+ // A rotation may have shrunk the file below the pre-spawn byte offset.+ tail = content+ .subarray(content.length < offset ? 0 : offset)+ .subarray(-DAEMON_STARTUP_LOG_TAIL_BYTES)+ .toString("utf8")+ .trim();+ } catch {+ // Missing log means the daemon crashed before logging was set up.+ }+ return tail ? ` Recent daemon log (${logPath}):\n${tail}` : ` The daemon wrote nothing to its log (${logPath}).`;}const ensurePromises = new Map<string, Promise<void>>();diff --git a/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts b/packages/coding-agent/src/modes/daemon/daemon-supervisor.tsindex 846d5d5193..8e37b21083 100644--- a/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts+++ b/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts@@ -709,6 +709,7 @@ export class DaemonSupervisor {this.markReady();} catch (error) {const startupError = error instanceof Error ? error : new Error(String(error));+ this.log(`Daemon supervisor startup failed: ${startupError.stack ?? startupError.message}`);await this.cleanupSupervisorResources();this.rejectReady(startupError);throw startupError;diff --git a/packages/coding-agent/test/daemon-launch.test.ts b/packages/coding-agent/test/daemon-launch.test.tsindex 634864a4e0..1a649d6cc6 100644--- a/packages/coding-agent/test/daemon-launch.test.ts+++ b/packages/coding-agent/test/daemon-launch.test.ts@@ -1,8 +1,8 @@import { spawn } from "node:child_process";-import { existsSync, mkdtempSync, rmSync } from "node:fs";+import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";import { createServer, type Server, type Socket } from "node:net";import { tmpdir } from "node:os";-import { join } from "node:path";+import { dirname, join } from "node:path";import { afterEach, describe, expect, it } from "vitest";import {ensureInteractiveDaemonRunning,@@ -11,7 +11,7 @@ import {shouldStartDaemonEarly,shutdownDaemonAndWait,} from "../src/cli/daemon-launch.js";-import { VERSION } from "../src/config.js";+import { ENV_AGENT_DIR, getDaemonLogPath, VERSION } from "../src/config.js";import { DAEMON_PROTOCOL_VERSION, DAEMON_SCHEMA_ID } from "../src/modes/daemon/daemon-protocol.js";interface FakeDaemonOptions {@@ -272,6 +272,135 @@ describe("ensureInteractiveDaemonRunning", () => {await expect(probe).resolves.toMatchObject({ status: "current" });});++ it("fails fast with the daemon log tail when the spawned daemon exits during startup", async () => {+ const dir = mkdtempSync(join(tmpdir(), "pa-launch-startup-crash-"));+ const entrypoint = join(dir, "crash.mjs");+ const socketPath = join(dir, "d.sock");+ const originalAgentDir = process.env[ENV_AGENT_DIR];+ process.env[ENV_AGENT_DIR] = join(dir, "agent");+ const logPath = getDaemonLogPath(socketPath);+ mkdirSync(dirname(logPath), { recursive: true });+ const script = `import { appendFileSync } from "node:fs"; appendFileSync(${JSON.stringify(logPath)}, "supervisor: fatal startup failure\\n"); process.exit(23);`;+ writeFileSync(entrypoint, script);+ const originalEntrypoint = process.argv[1]!;+ process.argv[1] = entrypoint;+ const startedAt = Date.now();++ try {+ await expect(ensureInteractiveDaemonRunning(socketPath)).rejects.toThrow(+ /Prime Agent daemon exited during startup \(code 23\)\.[\s\S]*fatal startup failure/,+ );+ expect(Date.now() - startedAt).toBeLessThan(10_000);+ } finally {+ process.argv[1] = originalEntrypoint;+ if (originalAgentDir === undefined) delete process.env[ENV_AGENT_DIR];+ else process.env[ENV_AGENT_DIR] = originalAgentDir;+ rmSync(dir, { recursive: true, force: true });+ }+ });++ it("names the missing daemon log when the daemon crashes before logging", async () => {+ const dir = mkdtempSync(join(tmpdir(), "pa-launch-startup-silent-"));+ const entrypoint = join(dir, "crash.mjs");+ const socketPath = join(dir, "d.sock");+ const originalAgentDir = process.env[ENV_AGENT_DIR];+ process.env[ENV_AGENT_DIR] = join(dir, "agent");+ writeFileSync(entrypoint, "process.exit(7);");+ const originalEntrypoint = process.argv[1]!;+ process.argv[1] = entrypoint;++ try {+ await expect(ensureInteractiveDaemonRunning(socketPath)).rejects.toThrow(+ /exited during startup \(code 7\)\. The daemon wrote nothing to its log/,+ );+ } finally {+ process.argv[1] = originalEntrypoint;+ if (originalAgentDir === undefined) delete process.env[ENV_AGENT_DIR];+ else process.env[ENV_AGENT_DIR] = originalAgentDir;+ rmSync(dir, { recursive: true, force: true });+ }+ });++ it("surfaces a spawn error when the child never emits exit", async () => {+ const dir = mkdtempSync(join(tmpdir(), "pa-launch-spawn-error-"));+ const socketPath = join(dir, "d.sock");+ const originalAgentDir = process.env[ENV_AGENT_DIR];+ process.env[ENV_AGENT_DIR] = join(dir, "agent");++ try {+ await expect(ensureInteractiveDaemonRunning(socketPath, join(dir, "missing-cwd"))).rejects.toThrow(+ /Failed to spawn Prime Agent daemon: .*ENOENT/,+ );+ } finally {+ if (originalAgentDir === undefined) delete process.env[ENV_AGENT_DIR];+ else process.env[ENV_AGENT_DIR] = originalAgentDir;+ rmSync(dir, { recursive: true, force: true });+ }+ });++ it("succeeds when the spawned child loses the race to an already-serving daemon", async () => {+ const dir = mkdtempSync(join(tmpdir(), "pa-launch-startup-race-"));+ const entrypoint = join(dir, "loser.mjs");+ const socketPath = join(dir, "d.sock");+ const originalAgentDir = process.env[ENV_AGENT_DIR];+ process.env[ENV_AGENT_DIR] = join(dir, "agent");+ writeFileSync(entrypoint, "process.exit(7);");+ const originalEntrypoint = process.argv[1]!;+ process.argv[1] = entrypoint;+ const server: Server = createServer((socket) => {+ socket.on("error", () => undefined);+ send(socket, {+ type: "daemon_hello",+ socketPath,+ protocol: { name: "prime-agent.daemon", version: DAEMON_PROTOCOL_VERSION },+ appVersion: VERSION,+ schemaId: DAEMON_SCHEMA_ID,+ clientId: "fake-client",+ serverCapabilities: [],+ });+ });++ try {+ const ensurePromise = ensureInteractiveDaemonRunning(socketPath);+ // Let the child exit first, then bring up the winning daemon inside+ // the exit grace window.+ await new Promise((resolve) => setTimeout(resolve, 300));+ await new Promise<void>((resolve) => server.listen(socketPath, resolve));+ await expect(ensurePromise).resolves.toBeUndefined();+ } finally {+ process.argv[1] = originalEntrypoint;+ if (originalAgentDir === undefined) delete process.env[ENV_AGENT_DIR];+ else process.env[ENV_AGENT_DIR] = originalAgentDir;+ await new Promise<void>((resolve) => server.close(() => resolve()));+ rmSync(dir, { recursive: true, force: true });+ }+ });++ it("does not attribute a previous run's log to a daemon that crashed before logging", async () => {+ const dir = mkdtempSync(join(tmpdir(), "pa-launch-startup-stale-"));+ const entrypoint = join(dir, "crash.mjs");+ const socketPath = join(dir, "d.sock");+ const originalAgentDir = process.env[ENV_AGENT_DIR];+ process.env[ENV_AGENT_DIR] = join(dir, "agent");+ const logPath = getDaemonLogPath(socketPath);+ mkdirSync(dirname(logPath), { recursive: true });+ writeFileSync(logPath, "supervisor: error from an earlier run in /tmp/\u00fcml\u00e4ut-p\u00e4th\n");+ writeFileSync(entrypoint, "process.exit(7);");+ const originalEntrypoint = process.argv[1]!;+ process.argv[1] = entrypoint;++ try {+ await expect(ensureInteractiveDaemonRunning(socketPath)).rejects.toThrow(+ /exited during startup \(code 7\)\. The daemon wrote nothing to its log/,+ );+ } finally {+ process.argv[1] = originalEntrypoint;+ if (originalAgentDir === undefined) delete process.env[ENV_AGENT_DIR];+ else process.env[ENV_AGENT_DIR] = originalAgentDir;+ rmSync(dir, { recursive: true, force: true });+ }+ });});describe("shutdownDaemonAndWait", () => {