Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

refactor(daemon): unify driver launch paths, extract constants, fix resume/stop bugs

Gus3144300c2c58
diff --git a/src/daemon/scripts/preview-system-prompt.ts b/src/daemon/scripts/preview-system-prompt.ts
index 16b302c0f..27a6dfb51 100644
--- a/src/daemon/scripts/preview-system-prompt.ts
+++ b/src/daemon/scripts/preview-system-prompt.ts
@@ -19,9 +19,7 @@ const mockConfig: LaunchConfig = {
const outDir = join(tmpdir(), "alook-sysprompt");
mkdirSync(outDir, { recursive: true });
-for (const lifecycleKind of ["persistent", "per_turn"] as const) {
- const prompt = buildCliSystemPrompt(mockConfig, { lifecycleKind });
- const file = join(outDir, `system-prompt.${lifecycleKind}.md`);
- writeFileSync(file, prompt, "utf8");
- console.log(`${lifecycleKind.padEnd(10)} → ${file}`);
-}
+const prompt = buildCliSystemPrompt(mockConfig);
+const file = join(outDir, "system-prompt.md");
+writeFileSync(file, prompt, "utf8");
+console.log(`system-prompt → ${file}`);
diff --git a/src/daemon/src/cli/daemonStart.ts b/src/daemon/src/cli/daemonStart.ts
index e25fd735f..2dc0f8049 100644
--- a/src/daemon/src/cli/daemonStart.ts
+++ b/src/daemon/src/cli/daemonStart.ts
@@ -11,25 +11,29 @@ import * as crypto from "crypto";
import * as os from "os";
import { homedir } from "os";
import { WebSocket } from "ws";
-import { createRequire } from "module";
import { createDaemon } from "../daemon/createDaemon.js";
import { getDriver } from "../drivers/index.js";
import { resolveAlookCliPathWithFallback, detectRuntimes, type RuntimeInfo } from "../discovery.js";
import { createLogger } from "../logger.js";
import { UnknownRuntimeError } from "../manager/agentRouter.js";
-
-const requireFromHere = createRequire(import.meta.url);
-function readDaemonVersion(): string {
- try {
- const pkg = requireFromHere("../../package.json") as { version?: string };
- return pkg.version ?? "";
- } catch {
- return "";
- }
-}
+import { readDaemonVersion } from "../version.js";
const CAPABILITIES = ["send", "read", "mentions", "tasks", "reactions", "server", "channels", "knowledge", "attach"];
+/**
+ * Grace window for a daemon to exit on SIGTERM before we escalate to SIGKILL.
+ * Must stay strictly above `SESSION_STOP_GRACE_MS` — the daemon's own SIGTERM
+ * handler awaits every agent session's kill (each with its own grace), so this
+ * window has to contain those.
+ */
+const STOP_GRACE_MS = 5000;
+/** How often `daemonStop` polls `isProcessAlive` while waiting on SIGTERM. */
+const POLL_MS = 100;
+/** How many hex chars of the machine-key SHA-256 make up the pidfile name. */
+const MACHINE_KEY_HASH_PREFIX_LEN = 12;
+/** How many chars of the pasted machine key `daemonList` shows as the "keyPrefix". */
+const MACHINE_KEY_DISPLAY_PREFIX_LEN = 20;
+
function resolveDefaultBaseDir(): string {
const root = process.env.ALOOK_PROJECT_ROOT || path.join(homedir(), ".alook");
return path.join(root, "daemon");
@@ -44,7 +48,7 @@ const log = createLogger({ header: "@alook/daemon" });
/* ------------------------------------------------------------------ */
function keyHash(machineKey: string): string {
- return crypto.createHash("sha256").update(machineKey).digest("hex").slice(0, 12);
+ return crypto.createHash("sha256").update(machineKey).digest("hex").slice(0, MACHINE_KEY_HASH_PREFIX_LEN);
}
function daemonsDir(baseDir: string): string {
@@ -132,7 +136,7 @@ export function daemonList(opts: DaemonListOpts): DaemonInfo[] {
}
results.push({
keyHash: file.replace(".pid", ""),
- keyPrefix: data.key.slice(0, 20) + "…",
+ keyPrefix: data.key.slice(0, MACHINE_KEY_DISPLAY_PREFIX_LEN) + "…",
pid: data.pid,
alive,
});
@@ -150,7 +154,7 @@ export interface DaemonStopOpts {
baseDir?: string;
}
-export function daemonStop(opts: DaemonStopOpts): void {
+export async function daemonStop(opts: DaemonStopOpts): Promise<void> {
const baseDir = opts.baseDir || process.env.ALOOK_DATA_DIR || DEFAULT_BASE_DIR;
const pf = pidfilePath(baseDir, opts.machineKey);
const data = readPidFile(pf);
@@ -168,14 +172,13 @@ export function daemonStop(opts: DaemonStopOpts): void {
log.info(`sending SIGTERM to daemon (pid ${data.pid})…`);
process.kill(data.pid, "SIGTERM");
- const deadline = Date.now() + 5000;
+ const deadline = Date.now() + STOP_GRACE_MS;
while (Date.now() < deadline && isProcessAlive(data.pid)) {
- const start = Date.now();
- while (Date.now() - start < 100) { /* spin */ }
+ await new Promise((r) => setTimeout(r, POLL_MS));
}
if (isProcessAlive(data.pid)) {
- log.error(`daemon (pid ${data.pid}) did not exit in 5s — sending SIGKILL`);
+ log.error(`daemon (pid ${data.pid}) did not exit in ${STOP_GRACE_MS / 1000}s — sending SIGKILL`);
process.kill(data.pid, "SIGKILL");
} else {
log.info("daemon stopped");
@@ -204,11 +207,6 @@ export function credentialFilePathByMachineId(baseDir: string, machineId: string
return path.join(daemonsDir(baseDir), `${machineId}.credential.json`);
}
-/** Legacy accessor kept for the boot-time index scan; not used to write. */
-function credentialFilesDir(baseDir: string): string {
- return daemonsDir(baseDir);
-}
-
function readCredentialFile(filePath: string): { credential: string; machineId: string } | null {
if (!fs.existsSync(filePath)) return null;
try {
@@ -238,7 +236,7 @@ function findExistingCredentialForBearer(
baseDir: string,
bearer: string
): { credential: string; machineId: string } | null {
- const dir = credentialFilesDir(baseDir);
+ const dir = daemonsDir(baseDir);
if (!fs.existsSync(dir)) return null;
for (const file of fs.readdirSync(dir)) {
if (!file.endsWith(".credential.json")) continue;
@@ -426,17 +424,13 @@ export async function daemonStart(opts: DaemonStartOpts): Promise<void> {
log.info(`daemon up — proxy at ${daemon.proxyUrl}, dialing ${wsUrl}`);
- const readyTimer = setInterval(() => {
- if (daemon.isOpen()) {
- clearInterval(readyTimer);
- log.info("control plane OPEN");
- }
- }, 200);
- readyTimer.unref?.();
+ // Event-driven "control plane OPEN" — was previously a 200ms setInterval
+ // polling `daemon.isOpen()`. `onOpen` fires on every (re)connect including
+ // the first one, so we log on subsequent reconnects too.
+ daemon.onOpen(() => log.info("control plane OPEN"));
const shutdown = async () => {
log.info("shutting down…");
- clearInterval(readyTimer);
releaseLock(pf);
await daemon.stop();
process.exit(0);
diff --git a/src/daemon/src/cli/daemonStop.test.ts b/src/daemon/src/cli/daemonStop.test.ts
new file mode 100644
index 000000000..91de590ee
--- /dev/null
+++ b/src/daemon/src/cli/daemonStop.test.ts
@@ -0,0 +1,49 @@
+import { describe, it, expect, beforeEach, afterEach } from "vitest";
+import * as fs from "fs";
+import * as os from "os";
+import * as path from "path";
+import { spawn } from "child_process";
+import { daemonStop } from "./daemonStart";
+
+/**
+ * daemonStop went from spinning (`while (Date.now() - start < 100) {}` busy
+ * loop) to async setTimeout polling. This test asserts the *behavior* — a
+ * live child receives SIGTERM and exits inside the grace window — and, as a
+ * side effect, that the function actually awaits (it returns a Promise now).
+ */
+describe("daemonStop — event-loop friendly (no spin loop)", () => {
+ let baseDir: string;
+ let pidfile: string;
+
+ beforeEach(() => {
+ baseDir = fs.mkdtempSync(path.join(os.tmpdir(), "alook-daemonstop-"));
+ });
+ afterEach(() => {
+ fs.rmSync(baseDir, { recursive: true, force: true });
+ });
+
+ it("SIGTERMs the daemon and cleans up the pidfile once it exits", async () => {
+ // Spawn a real child so we can send SIGTERM at it. `node -e` picks the
+ // ambient node binary — no PATH assumptions.
+ const child = spawn(process.execPath, ["-e", "setInterval(()=>{}, 1000)"], { stdio: "ignore" });
+ const machineKey = "cmk_test_key";
+ const daemonsDir = path.join(baseDir, "daemons");
+ fs.mkdirSync(daemonsDir, { recursive: true });
+ // pidfile name is <sha256(machineKey).slice(0,12)>.pid — we don't care
+ // about the exact hash here; just create one that daemonStop will find
+ // by re-computing the same hash.
+ const crypto = await import("crypto");
+ const hash = crypto.createHash("sha256").update(machineKey).digest("hex").slice(0, 12);
+ pidfile = path.join(daemonsDir, `${hash}.pid`);
+ fs.writeFileSync(pidfile, JSON.stringify({ pid: child.pid, key: machineKey }));
+
+ const stopPromise = daemonStop({ machineKey, baseDir });
+ expect(stopPromise).toBeInstanceOf(Promise);
+ await stopPromise;
+
+ expect(fs.existsSync(pidfile)).toBe(false);
+ // The child should have received the SIGTERM — Node's own exit signal
+ // handling terminates cleanly on SIGTERM.
+ expect(child.killed || child.exitCode !== null || child.signalCode !== null).toBe(true);
+ }, 15_000);
+});
diff --git a/src/daemon/src/cli/index.ts b/src/daemon/src/cli/index.ts
index e4d15336f..052a5120c 100755
--- a/src/daemon/src/cli/index.ts
+++ b/src/daemon/src/cli/index.ts
@@ -600,9 +600,9 @@ function buildProgram(): Command {
.option("--base-dir <path>", "data directory (or ALOOK_DATA_DIR env)")
.exitOverride()
.configureOutput({ writeOut: () => {}, writeErr: () => {} })
- .action(function (this: Command) {
+ .action(async function (this: Command) {
const localOpts = this.opts();
- daemonStop({
+ await daemonStop({
machineKey: localOpts.machineKey as string,
baseDir: localOpts.baseDir as string | undefined,
});
diff --git a/src/daemon/src/constants.test.ts b/src/daemon/src/constants.test.ts
new file mode 100644
index 000000000..0b60c0caf
--- /dev/null
+++ b/src/daemon/src/constants.test.ts
@@ -0,0 +1,113 @@
+import { describe, it, expect } from "vitest";
+import * as fs from "fs";
+import * as path from "path";
+import { fileURLToPath } from "url";
+import { SESSION_STOP_GRACE_MS } from "./runtime/killTree";
+
+/**
+ * Structural pins for extracted constants. We assert *magnitudes*, not
+ * literal spellings — a rename is fine, a value drift is not (the drivers
+ * across the daemon lean on these being stable).
+ *
+ * Constants that are exported are pinned by import. Constants that are file-
+ * local get checked via a lightweight source grep so a copy-paste drift
+ * (someone bumps `PROBE_TIMEOUT_MS = 5000` to 10000 without updating the
+ * "why so short" comment or its tests) is loud in CI.
+ */
+const HERE = path.dirname(fileURLToPath(import.meta.url));
+
+function readSrc(rel: string): string {
+ return fs.readFileSync(path.join(HERE, rel), "utf-8");
+}
+
+describe("magic-number extractions", () => {
+ it("SESSION_STOP_GRACE_MS === 2000 (unified across manager + session stop)", () => {
+ expect(SESSION_STOP_GRACE_MS).toBe(2000);
+ });
+
+ it("SESSION_STOP_GRACE_MS stays strictly below the daemon's own STOP_GRACE_MS", () => {
+ // `daemonStop` SIGKILLs the daemon after STOP_GRACE_MS; the daemon's
+ // SIGTERM handler awaits per-session kills that each wait
+ // SESSION_STOP_GRACE_MS. Equal windows orphan detached agent processes.
+ const daemonStartSrc = readSrc("cli/daemonStart.ts");
+ const match = daemonStartSrc.match(/const STOP_GRACE_MS\s*=\s*(\d+)/);
+ expect(match).not.toBeNull();
+ expect(SESSION_STOP_GRACE_MS).toBeLessThan(Number(match![1]));
+ });
+
+ it("PROBE_TIMEOUT_MS is set to 5000 in drivers/probe.ts", () => {
+ expect(readSrc("drivers/probe.ts")).toMatch(/PROBE_TIMEOUT_MS\s*=\s*5000\b/);
+ });
+
+ it("STDERR_LOG_MAX_LEN is set to 2000 in manager/managerRuntime.ts", () => {
+ expect(readSrc("manager/managerRuntime.ts")).toMatch(/STDERR_LOG_MAX_LEN\s*=\s*2000\b/);
+ });
+
+ it("ERROR_EXCERPT_MAX_BYTES is set to 4000 in runtime/errorDiagnostics.ts", () => {
+ expect(readSrc("runtime/errorDiagnostics.ts")).toMatch(/ERROR_EXCERPT_MAX_BYTES\s*=\s*4000\b/);
+ });
+
+ it("ERROR_FINGERPRINT_LEN is set to 16 in runtime/errorDiagnostics.ts", () => {
+ expect(readSrc("runtime/errorDiagnostics.ts")).toMatch(/ERROR_FINGERPRINT_LEN\s*=\s*16\b/);
+ });
+
+ it("DEFAULT_PING_INTERVAL_MS is set to 15_000 in server/wsControlChannel.ts", () => {
+ expect(readSrc("server/wsControlChannel.ts")).toMatch(/DEFAULT_PING_INTERVAL_MS\s*=\s*15_?000\b/);
+ });
+
+ it("DEFAULT_PONG_TIMEOUT_MS is set to 30_000 in server/wsControlChannel.ts", () => {
+ expect(readSrc("server/wsControlChannel.ts")).toMatch(/DEFAULT_PONG_TIMEOUT_MS\s*=\s*30_?000\b/);
+ });
+
+ it("KIMI_WIRE_PROTOCOL_VERSION is '1.3' in drivers/kimi.ts", () => {
+ expect(readSrc("drivers/kimi.ts")).toMatch(/KIMI_WIRE_PROTOCOL_VERSION\s*=\s*["']1\.3["']/);
+ });
+
+ it("MESSAGE_ID_SHORT_LEN is set to 8 in inbox/projection.ts", () => {
+ expect(readSrc("inbox/projection.ts")).toMatch(/MESSAGE_ID_SHORT_LEN\s*=\s*8\b/);
+ });
+
+ it("MACHINE_KEY_HASH_PREFIX_LEN is set to 12 in cli/daemonStart.ts", () => {
+ expect(readSrc("cli/daemonStart.ts")).toMatch(/MACHINE_KEY_HASH_PREFIX_LEN\s*=\s*12\b/);
+ });
+
+ it("MACHINE_KEY_DISPLAY_PREFIX_LEN is set to 20 in cli/daemonStart.ts", () => {
+ expect(readSrc("cli/daemonStart.ts")).toMatch(/MACHINE_KEY_DISPLAY_PREFIX_LEN\s*=\s*20\b/);
+ });
+});
+
+describe("deleted symbols stay deleted", () => {
+ it("readCommandVersion is no longer exported by drivers/probe.ts", () => {
+ expect(readSrc("drivers/probe.ts")).not.toMatch(/\breadCommandVersion\b/);
+ });
+
+ it("credentialFilesDir is no longer defined in cli/daemonStart.ts", () => {
+ expect(readSrc("cli/daemonStart.ts")).not.toMatch(/\bcredentialFilesDir\b/);
+ });
+
+ it("SystemPromptOpts is no longer defined in drivers/systemPrompt.ts", () => {
+ expect(readSrc("drivers/systemPrompt.ts")).not.toMatch(/\bSystemPromptOpts\b/);
+ });
+
+ it("DEFAULT_CLAUDE_MODEL is no longer defined in drivers/claudeLaunch.ts", () => {
+ expect(readSrc("drivers/claudeLaunch.ts")).not.toMatch(/\bDEFAULT_CLAUDE_MODEL\b/);
+ });
+
+ it("agent-backend / 1.0.0 identity string no longer appears in daemon source", () => {
+ // Walk every .ts under src/ (excluding tests) and assert the legacy string
+ // is gone. Cheap, but catches a future regression.
+ const walk = (dir: string): string[] => {
+ const out: string[] = [];
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
+ const p = path.join(dir, entry.name);
+ if (entry.isDirectory()) out.push(...walk(p));
+ else if (entry.isFile() && p.endsWith(".ts") && !p.endsWith(".test.ts")) out.push(p);
+ }
+ return out;
+ };
+ for (const file of walk(HERE)) {
+ const text = fs.readFileSync(file, "utf-8");
+ expect(text, `${file} contained "agent-backend"`).not.toMatch(/"agent-backend"/);
+ }
+ });
+});
diff --git a/src/daemon/src/daemon/createDaemon.ts b/src/daemon/src/daemon/createDaemon.ts
index 523080ba5..e6077f2f4 100644
--- a/src/daemon/src/daemon/createDaemon.ts
+++ b/src/daemon/src/daemon/createDaemon.ts
@@ -148,6 +148,18 @@ export interface CreateDaemonOptions {
export interface RunningDaemon {
/** True once the control plane is open (machine key accepted). */
isOpen(): boolean;
+ /**
+ * Register a hook fired after every (re)connect once the resync completes —
+ * including the first open. Delegates to `channel.onOpen` (see
+ * `WsControlChannel.onOpen`). Lets callers switch off event-driven signals
+ * instead of polling `isOpen()`.
+ *
+ * The channel is already connecting by the time a caller can reach this, so
+ * if the socket is ALREADY open at registration time the hook also fires
+ * once immediately — otherwise a hook registered a tick too late would never
+ * run for the connection it was meant to observe.
+ */
+ onOpen(hook: () => void): void;
proxyUrl: string;
stop(): Promise<void>;
}
@@ -614,6 +626,15 @@ export async function createDaemon(opts: CreateDaemonOptions): Promise<RunningDa
return {
isOpen: () => channel.status === "open",
+ // `channel.connect()` already ran above, so a caller registering here is
+ // racing the first open: if the socket won that race the hook would never
+ // fire at all. Fire it once immediately in that case (on a microtask, so
+ // registration itself stays side-effect-free for the caller) and still
+ // register it for every subsequent reconnect.
+ onOpen: (hook: () => void) => {
+ channel.onOpen(hook);
+ if (channel.status === "open") queueMicrotask(hook);
+ },
proxyUrl: proxy.url,
stop: async () => {
// Clear all bot-typing heartbeat intervals and emit final stops for
diff --git a/src/daemon/src/drivers/antigravity.ts b/src/daemon/src/drivers/antigravity.ts
index b9854a776..76f9e2002 100644
--- a/src/daemon/src/drivers/antigravity.ts
+++ b/src/daemon/src/drivers/antigravity.ts
@@ -10,15 +10,27 @@ import { randomUUID } from "crypto";
import type { Driver, LaunchConfig, LaunchContext, ParsedEvent, SpawnResult } from "../types.js";
import { prepareCliTransport, buildCliTransportSystemPrompt } from "./cliTransport.js";
import { probeCliRuntime, resolveSpawnSpec } from "./probe.js";
+import { resolveLaunchFieldsOrDefault } from "../runtimeConfig.js";
import { spawnAgentProcess } from "../runtime/killTree.js";
+import { writeToStdinAndDetach } from "./utils.js";
const ERROR_LINE_PATTERNS: RegExp[] = [/^error[:\s]/i, /\bfatal\b/i, /\bpanic\b/i, /unable to/i];
-/** Wall-clock cap for a single Antigravity print run. */
+/**
+ * Wall-clock cap for a single Antigravity print run — chosen high because the
+ * `agy` binary uses per-turn spawn and its own long-form reasoning routinely
+ * runs many minutes on heavy inputs; 30m is the ceiling we're comfortable
+ * letting a single turn hold before we assume it's wedged.
+ */
const ANTIGRAVITY_PRINT_TIMEOUT = "30m";
export function buildAntigravityArgs(ctx: LaunchContext): string[] {
const args = ["--print", "--print-timeout", ANTIGRAVITY_PRINT_TIMEOUT, "--dangerously-skip-permissions"];
+ // `agy` has no by-id resume — the only resume flag is `--continue`, which
+ // follows the most recent session in cwd. We compensate by stashing
+ // `ctx.config.sessionId` in `this.sessionId` so the daemon still records the
+ // logical id, but the CLI itself will re-attach to whatever ran last.
+ // Reflected in `capabilities.sessionResumeMode = "most-recent"`.
if (ctx.config.sessionId) args.push("--continue");
return args;
}
@@ -40,6 +52,14 @@ export class AntigravityDriver implements Driver {
readonly supportsStdinNotification = false;
readonly busyDeliveryMode = "none" as const;
+ readonly capabilities = {
+ reasoningEffort: false,
+ fastMode: false,
+ disallowedTools: false,
+ command: true,
+ sessionResumeMode: "most-recent",
+ } as const;
+
private sessionId: string | null = null;
private sentInit = false;
@@ -51,7 +71,6 @@ export class AntigravityDriver implements Driver {
this.sessionId = ctx.config.sessionId ?? randomUUID();
this.sentInit = false;
const { spawnEnv } = await prepareCliTransport(ctx, {
- NO_COLOR: "1",
// Antigravity is sensitive to inherited SSH context — clear it.
SSH_CLIENT: "",
SSH_CONNECTION: "",
@@ -59,13 +78,14 @@ export class AntigravityDriver implements Driver {
});
// Cross-platform spawn: on Windows the agy entry is often a `.cmd`
// shim, which `child_process.spawn` can't exec without a shell.
- const spec = resolveSpawnSpec("agy", buildAntigravityArgs(ctx));
+ const override = resolveLaunchFieldsOrDefault(ctx.config.runtimeConfig).command;
+ const spec = resolveSpawnSpec("agy", buildAntigravityArgs(ctx), override);
const proc = spawnAgentProcess(spec.command, spec.args, {
cwd: ctx.workingDirectory,
env: spawnEnv,
shell: spec.shell,
});
- proc.stdin?.end(ctx.prompt);
+ writeToStdinAndDetach(proc, ctx.prompt);
return { process: proc };
}
@@ -91,6 +111,6 @@ export class AntigravityDriver implements Driver {
}
buildSystemPrompt(config: LaunchConfig): string {
- return buildCliTransportSystemPrompt(config, { lifecycleKind: this.lifecycle.kind });
+ return buildCliTransportSystemPrompt(config);
}
}
diff --git a/src/daemon/src/drivers/capabilities.test.ts b/src/daemon/src/drivers/capabilities.test.ts
new file mode 100644
index 000000000..3cac0acdc
--- /dev/null
+++ b/src/daemon/src/drivers/capabilities.test.ts
@@ -0,0 +1,28 @@
+import { describe, it, expect } from "vitest";
+import { getDriver, listRuntimeIds, type RuntimeId } from "./index";
+import type { DriverCapabilities } from "../types";
+
+/**
+ * Every driver declares which `RuntimeConfig` fields it actually consumes,
+ * per the plan's capability matrix. This test pins that declaration so a
+ * silent drift (e.g. someone adds `reasoningEffort` to a driver's `buildArgs`
+ * without updating `capabilities`) trips CI.
+ */
+const EXPECTED: Record<RuntimeId, DriverCapabilities> = {
+ claude: { reasoningEffort: true, fastMode: true, disallowedTools: true, command: true, sessionResumeMode: "by-id" },
+ codex: { reasoningEffort: true, fastMode: true, disallowedTools: false, command: true, sessionResumeMode: "by-id" },
+ kimi: { reasoningEffort: false, fastMode: false, disallowedTools: false, command: true, sessionResumeMode: "by-id" },
+ gemini: { reasoningEffort: false, fastMode: false, disallowedTools: false, command: true, sessionResumeMode: "by-id" },
+ copilot: { reasoningEffort: true, fastMode: false, disallowedTools: false, command: true, sessionResumeMode: "by-id" },
+ cursor: { reasoningEffort: false, fastMode: false, disallowedTools: false, command: true, sessionResumeMode: "by-id" },
+ opencode: { reasoningEffort: false, fastMode: false, disallowedTools: false, command: true, sessionResumeMode: "by-id" },
+ antigravity: { reasoningEffort: false, fastMode: false, disallowedTools: false, command: true, sessionResumeMode: "most-recent" },
+ pi: { reasoningEffort: true, fastMode: false, disallowedTools: false, command: true, sessionResumeMode: "by-id" },
+};
+
+describe("driver.capabilities", () => {
+ it.each(listRuntimeIds())("%s declares the expected capability record", (id) => {
+ const driver = getDriver(id);
+ expect(driver.capabilities).toEqual(EXPECTED[id]);
+ });
+});
diff --git a/src/daemon/src/drivers/claude.ts b/src/daemon/src/drivers/claude.ts
index 231a6fc79..96a9563a0 100644
--- a/src/daemon/src/drivers/claude.ts
+++ b/src/daemon/src/drivers/claude.ts
@@ -11,13 +11,10 @@
import type { Driver, EncodeOpts, LaunchConfig, LaunchContext, ParsedEvent, SpawnResult } from "../types.js";
import { prepareCliTransport, buildCliTransportSystemPrompt, DEFAULT_CLI_CONFIG } from "./cliTransport.js";
import { buildClaudeProviderIsolationEnv } from "./claudeProviderIsolation.js";
-import {
- buildClaudeArgs,
- resolveClaudeLaunchCommand,
- buildClaudeSpawnSpec,
-} from "./claudeLaunch.js";
+import { buildClaudeArgs } from "./claudeLaunch.js";
import { ClaudeEventNormalizer } from "./claudeEventNormalizer.js";
-import { probeClaude } from "./probe.js";
+import { probeClaude, resolveSpawnSpec, resolveClaudeCommand } from "./probe.js";
+import { resolveLaunchFieldsOrDefault } from "../runtimeConfig.js";
import { spawnAgentProcess } from "../runtime/killTree.js";
export class ClaudeDriver implements Driver {
@@ -33,6 +30,14 @@ export class ClaudeDriver implements Driver {
readonly busyDeliveryMode = "gated" as const;
readonly supportsNativeStandingPrompt = true;
+ readonly capabilities = {
+ reasoningEffort: true,
+ fastMode: true,
+ disallowedTools: true,
+ command: true,
+ sessionResumeMode: "by-id",
+ } as const;
+
private readonly eventNormalizer = new ClaudeEventNormalizer();
probe() {
@@ -52,12 +57,26 @@ export class ClaudeDriver implements Driver {
// Let Claude detect it is NOT nested in another Claude Code session.
delete spawnEnv.CLAUDECODE;
- const claudeCommand = resolveClaudeLaunchCommand(ctx.config);
- const spawnSpec = buildClaudeSpawnSpec(claudeCommand);
- const proc = spawnAgentProcess(spawnSpec.command, args, {
+ // Claude has an extra bespoke discovery step (macOS `.app` bundle
+ // fallback via `resolveClaudeCommand`) that no other driver needs, but
+ // the spawn spec itself is the same as everyone else's. `runtimeConfig.command`
+ // wins over the discovered path when set (uniform across drivers).
+ //
+ // The discovery probe stays lazy: `resolveClaudeCommand` shells out to
+ // `which`/`where` (up to PROBE_TIMEOUT_MS), so when the user pinned an
+ // explicit `command` we must not pay for — or block on — a lookup whose
+ // result `resolveSpawnSpec` would immediately discard.
+ //
+ // Both branches feed the chosen path through `resolveSpawnSpec`'s override
+ // slot, whose "already looks like a path → don't re-resolve" rule keeps us
+ // from PATH-probing a path `resolveClaudeCommand` just resolved.
+ const override = resolveLaunchFieldsOrDefault(ctx.config.runtimeConfig).command?.trim();
+ const claudeCommand = override || resolveClaudeCommand() || "claude";
+ const spec = resolveSpawnSpec("claude", args, claudeCommand);
+ const proc = spawnAgentProcess(spec.command, spec.args, {
cwd: ctx.workingDirectory,
env: spawnEnv,
- shell: spawnSpec.shell,
+ shell: spec.shell,
});
// Deliver the initial prompt as the first stream-json line.
@@ -89,6 +108,6 @@ export class ClaudeDriver implements Driver {
}
buildSystemPrompt(config: LaunchConfig): string {
- return buildCliTransportSystemPrompt(config, { lifecycleKind: this.lifecycle.kind });
+ return buildCliTransportSystemPrompt(config);
}
}
diff --git a/src/daemon/src/drivers/claudeEventNormalizer.ts b/src/daemon/src/drivers/claudeEventNormalizer.ts
index e84c36ff6..a4aaad1c2 100644
--- a/src/daemon/src/drivers/claudeEventNormalizer.ts
+++ b/src/daemon/src/drivers/claudeEventNormalizer.ts
@@ -14,6 +14,7 @@
* The `session_id` on any line keeps `currentSessionId` fresh for resume.
*/
import type { ParsedEvent } from "../types.js";
+import { tryParseJsonLine } from "./utils.js";
const API_ERROR_RE = /API Error:.*(?:Connection error|\b[45]\d{2}\b)/i;
@@ -25,12 +26,8 @@ export class ClaudeEventNormalizer {
}
normalizeLine(line: string): ParsedEvent[] {
- let event: any;
- try {
- event = JSON.parse(line);
- } catch {
- return [];
- }
+ const event = tryParseJsonLine(line) as any;
+ if (!event) return [];
if (event?.session_id) this.currentSession = event.session_id;
const out: ParsedEvent[] = [];
diff --git a/src/daemon/src/drivers/claudeLaunch.test.ts b/src/daemon/src/drivers/claudeLaunch.test.ts
new file mode 100644
index 000000000..8c1618970
--- /dev/null
+++ b/src/daemon/src/drivers/claudeLaunch.test.ts
@@ -0,0 +1,38 @@
+import { describe, it, expect } from "vitest";
+import { buildClaudeArgs } from "./claudeLaunch";
+import { makeRuntimeConfig } from "../runtimeConfig";
+import type { LaunchConfig } from "../types";
+
+/**
+ * Consistent-drivers plan: Claude no longer hard-codes `--model sonnet` when
+ * the caller didn't pick one. `{kind:"default"}` finally means "let the CLI
+ * decide" across every driver, matching every non-claude driver's behavior.
+ */
+describe("buildClaudeArgs — model flag is conditional", () => {
+ it("omits --model when runtimeConfig.model.kind === 'default'", () => {
+ const config: LaunchConfig = { runtimeConfig: makeRuntimeConfig({ runtime: "claude" }) };
+ const args = buildClaudeArgs(config);
+ expect(args).not.toContain("--model");
+ });
+
+ it("emits --model <name> when a named model is set", () => {
+ const config: LaunchConfig = {
+ runtimeConfig: makeRuntimeConfig({ runtime: "claude", model: { kind: "named", name: "opus" } }),
+ };
+ const args = buildClaudeArgs(config);
+ const modelIdx = args.indexOf("--model");
+ expect(modelIdx).toBeGreaterThan(-1);
+ expect(args[modelIdx + 1]).toBe("opus");
+ });
+
+ it("passes --resume <sessionId> when resuming", () => {
+ const config: LaunchConfig = {
+ sessionId: "sess-42",
+ runtimeConfig: makeRuntimeConfig({ runtime: "claude" }),
+ };
+ const args = buildClaudeArgs(config);
+ const idx = args.indexOf("--resume");
+ expect(idx).toBeGreaterThan(-1);
+ expect(args[idx + 1]).toBe("sess-42");
+ });
+});
diff --git a/src/daemon/src/drivers/claudeLaunch.ts b/src/daemon/src/drivers/claudeLaunch.ts
index c2c4701e9..ef8ebfa5e 100644
--- a/src/daemon/src/drivers/claudeLaunch.ts
+++ b/src/daemon/src/drivers/claudeLaunch.ts
@@ -8,15 +8,11 @@
*/
import type { LaunchConfig } from "../types.js";
import { resolveLaunchFieldsOrDefault } from "../runtimeConfig.js";
-import { resolveClaudeCommand } from "./probe.js";
-
-/** Default Claude model when the launch config doesn't specify one. */
-export const DEFAULT_CLAUDE_MODEL = "sonnet";
/** Tools the host disables by default — runtime-native scheduling/plan tools that
* would bypass the host's reminder/task model. Overridable via
* `launchRuntimeFields.disallowedTools`. */
-export const CLAUDE_DISALLOWED_TOOLS = "EnterPlanMode,ExitPlanMode,ScheduleWakeup,CronCreate,CronList,CronDelete";
+const CLAUDE_DISALLOWED_TOOLS = "EnterPlanMode,ExitPlanMode,ScheduleWakeup,CronCreate,CronList,CronDelete";
export function buildClaudeArgs(config: LaunchConfig): string[] {
const f = resolveLaunchFieldsOrDefault(config.runtimeConfig);
@@ -31,33 +27,13 @@ export function buildClaudeArgs(config: LaunchConfig): string[] {
"--input-format",
"stream-json",
"--include-partial-messages",
- "--model",
- f.model || DEFAULT_CLAUDE_MODEL,
"--disallowed-tools",
f.disallowedTools || CLAUDE_DISALLOWED_TOOLS,
];
+ if (f.model) args.push("--model", f.model);
if (f.reasoningEffort) args.push("--effort", f.reasoningEffort);
if (f.fastMode) args.push("--settings", '{"fastMode":true}');
if (config.sessionId) args.push("--resume", config.sessionId);
return args;
}
-export function resolveClaudeLaunchCommand(config: LaunchConfig): string {
- const override = resolveLaunchFieldsOrDefault(config.runtimeConfig).command?.trim();
- return override || resolveClaudeCommand() || "claude";
-}
-
-export interface ClaudeSpawnSpec {
- command: string;
- shell: boolean;
-}
-
-export function buildClaudeSpawnSpec(
- claudeCommand: string,
- platform: NodeJS.Platform = process.platform,
-): ClaudeSpawnSpec {
- const command = claudeCommand ?? "claude";
- const shell = platform === "win32" && (!command || /\.(cmd|bat)$/i.test(command));
- return { command, shell };
-}
-
diff --git a/src/daemon/src/drivers/cliTransport.test.ts b/src/daemon/src/drivers/cliTransport.test.ts
index 45cc219c6..ed8a59db5 100644
--- a/src/daemon/src/drivers/cliTransport.test.ts
+++ b/src/daemon/src/drivers/cliTransport.test.ts
@@ -131,6 +131,12 @@ describe("prepareCliTransport — layered spawn env", () => {
expect(spawnEnv.NO_COLOR).toBe("1");
});
+ it("sets NO_COLOR=1 and FORCE_COLOR=0 by default, even without a driver setting them", async () => {
+ const { spawnEnv } = await prepareCliTransport(baseCtx(mkTmp()), {}, undefined, "linux");
+ expect(spawnEnv.NO_COLOR).toBe("1");
+ expect(spawnEnv.FORCE_COLOR).toBe("0");
+ });
+
it("sets NO_PROXY for loopback", async () => {
const { spawnEnv } = await prepareCliTransport(baseCtx(mkTmp()), {}, undefined, "linux");
expect(spawnEnv.NO_PROXY).toContain("127.0.0.1");
diff --git a/src/daemon/src/drivers/cliTransport.ts b/src/daemon/src/drivers/cliTransport.ts
index 6b90dd660..121f2913c 100644
--- a/src/daemon/src/drivers/cliTransport.ts
+++ b/src/daemon/src/drivers/cliTransport.ts
@@ -44,7 +44,7 @@
import * as fs from "fs";
import * as path from "path";
import type { LaunchContext, LaunchConfig } from "../types.js";
-import { buildCliSystemPrompt, type SystemPromptOpts } from "./systemPrompt.js";
+import { buildCliSystemPrompt } from "./systemPrompt.js";
import { resolveLaunchFieldsOrDefault } from "../runtimeConfig.js";
import { writeCliLink } from "./cliLink.js";
import { mergeEnvLayers, platformEnv, runtimeContextEnv, type EnvLayer } from "./spawnEnv.js";
@@ -213,7 +213,19 @@ export async function prepareCliTransport(
launchId: ctx.launchId,
traceDir: ctx.cliTransportTraceDir,
}),
+ // Baseline color-off for every runtime CLI: ANSI escapes have no
+ // meaning to the stream-json / JSON-RPC parsers on the other side and
+ // routinely corrupt event boundaries. Every driver used to hand-set
+ // NO_COLOR here — now it's a default all runtimes (including Claude)
+ // inherit.
+ //
+ // A driver CANNOT opt out via its own `extraEnv`: that layer sits at
+ // precedence 30, below this one (40), so a driver-supplied value is
+ // overwritten here. If some future CLI genuinely misreads NO_COLOR,
+ // opt it out by making these two keys conditional on a driver flag —
+ // not by setting them in `extraEnv`, which silently does nothing.
FORCE_COLOR: "0",
+ NO_COLOR: "1",
},
},
{ name: "runtimeContext", precedence: 50, vars: runtimeContextEnv(E, ctx.config.runtimeContext) },
@@ -240,6 +252,6 @@ export async function prepareCliTransport(
}
/** Shared system-prompt entry point for CLI drivers. */
-export function buildCliTransportSystemPrompt(config: LaunchConfig, opts: SystemPromptOpts): string {
- return buildCliSystemPrompt(config, opts);
+export function buildCliTransportSystemPrompt(config: LaunchConfig): string {
+ return buildCliSystemPrompt(config);
}
diff --git a/src/daemon/src/drivers/codex.test.ts b/src/daemon/src/drivers/codex.test.ts
new file mode 100644
index 000000000..25100479a
--- /dev/null
+++ b/src/daemon/src/drivers/codex.test.ts
@@ -0,0 +1,61 @@
+import { describe, it, expect, vi } from "vitest";
+import { EventEmitter } from "events";
+import * as fs from "fs";
+import * as os from "os";
+import * as path from "path";
+import { CodexDriver } from "./codex";
+import type { LaunchContext } from "../types";
+import { CredentialBroker } from "../credentials/credentialProxy";
+import { readDaemonVersion } from "../version";
+
+vi.mock("../runtime/killTree", async () => {
+ const actual = await vi.importActual<typeof import("../runtime/killTree")>("../runtime/killTree");
+ return {
+ ...actual,
+ spawnAgentProcess: () => {
+ const proc = new EventEmitter() as EventEmitter & { stdin: { write: ReturnType<typeof vi.fn> } };
+ proc.stdin = { write: vi.fn() };
+ return proc as never;
+ },
+ };
+});
+
+function mkTmp(): string {
+ return fs.mkdtempSync(path.join(os.tmpdir(), "codex-test-"));
+}
+
+function baseCtx(): LaunchContext {
+ const tmp = mkTmp();
+ return {
+ agentId: "agent_1",
+ launchId: "launch_1",
+ workingDirectory: tmp,
+ standingPrompt: "You are Codex.",
+ prompt: "hi",
+ credentialProxy: {
+ broker: new CredentialBroker({ upstreamBaseUrl: "https://u.test", voucherDir: mkTmp() }),
+ proxyUrl: "http://127.0.0.1:9/proxy",
+ runnerKey: "sk_agent_test",
+ capabilities: ["send", "read"],
+ },
+ config: {},
+ };
+}
+
+describe("CodexDriver initialize payload", () => {
+ it("sends alook-daemon identity via clientInfo (matches Codex's schema)", async () => {
+ const driver = new CodexDriver();
+ const ctx = baseCtx();
+ const { process: proc } = await driver.spawn(ctx);
+ // Codex writes on queueMicrotask — flush.
+ await Promise.resolve();
+
+ const stdin = (proc as unknown as { stdin: { write: ReturnType<typeof vi.fn> } }).stdin;
+ const firstCall = stdin.write.mock.calls[0][0] as string;
+ const initPayload = JSON.parse(firstCall.trim());
+
+ expect(initPayload.jsonrpc).toBe("2.0");
+ expect(initPayload.method).toBe("initialize");
+ expect(initPayload.params.clientInfo).toEqual({ name: "alook-daemon", version: readDaemonVersion() });
+ });
+});
diff --git a/src/daemon/src/drivers/codex.ts b/src/daemon/src/drivers/codex.ts
index fe2cab617..88bc6e1eb 100644
--- a/src/daemon/src/drivers/codex.ts
+++ b/src/daemon/src/drivers/codex.ts
@@ -20,6 +20,8 @@ import { probeCliRuntime, resolveSpawnSpec } from "./probe.js";
import { resolveCodexHomeRootFromEnv } from "./codexHome.js";
import { resolveLaunchFieldsOrDefault } from "../runtimeConfig.js";
import { spawnAgentProcess } from "../runtime/killTree.js";
+import { jsonRpcRequest } from "./utils.js";
+import { getDaemonClientInfo } from "../version.js";
/** True if a resume error means the prior thread rollout is gone. */
export function isCodexMissingRolloutError(message: string): boolean {
@@ -57,6 +59,14 @@ export class CodexDriver implements Driver {
readonly busyDeliveryMode = "gated" as const;
readonly supportsNativeStandingPrompt = true;
+ readonly capabilities = {
+ reasoningEffort: true,
+ fastMode: true,
+ disallowedTools: false,
+ command: true,
+ sessionResumeMode: "by-id",
+ } as const;
+
private readonly eventNormalizer = new CodexEventNormalizer();
private requestId = 0;
/** Resolved Codex home root (CODEX_HOME or ~/.codex); set on spawn. */
@@ -79,12 +89,13 @@ export class CodexDriver implements Driver {
}
async spawn(ctx: LaunchContext): Promise<SpawnResult> {
- const { spawnEnv } = await prepareCliTransport(ctx, { NO_COLOR: "1" });
+ const { spawnEnv } = await prepareCliTransport(ctx);
// Resolve the Codex home so resume can find its session rollout (and so a
// host could surface "missing rollout" recovery — see classifyCodexResumeError).
this.codexHomeRoot = resolveCodexHomeRootFromEnv(spawnEnv, { cwd: ctx.workingDirectory });
// Cross-platform spawn: on Windows the codex entry is often a `.cmd` shim.
- const spec = resolveSpawnSpec("codex", ["app-server", "--listen", "stdio://"]);
+ const override = resolveLaunchFieldsOrDefault(ctx.config.runtimeConfig).command;
+ const spec = resolveSpawnSpec("codex", ["app-server", "--listen", "stdio://"], override);
const proc = spawnAgentProcess(spec.command, spec.args, {
cwd: ctx.workingDirectory,
env: spawnEnv,
@@ -94,15 +105,11 @@ export class CodexDriver implements Driver {
// Async handshake: initialize, then thread/start|resume with the prompt.
queueMicrotask(() => {
proc.stdin?.write(
- JSON.stringify({
- jsonrpc: "2.0",
- id: this.nextRequestId(),
- method: "initialize",
- params: {
- clientInfo: { name: "agent-backend", version: "1.0.0" },
- capabilities: { experimentalApi: true },
- },
- }) + "\n",
+ jsonRpcRequest(
+ "initialize",
+ { clientInfo: getDaemonClientInfo(), capabilities: { experimentalApi: true } },
+ this.nextRequestId(),
+ ) + "\n",
);
const f = resolveLaunchFieldsOrDefault(ctx.config.runtimeConfig);
@@ -123,12 +130,7 @@ export class CodexDriver implements Driver {
if (f.fastMode) params.serviceTier = "fast";
proc.stdin?.write(
- JSON.stringify({
- jsonrpc: "2.0",
- id: this.nextRequestId(),
- method: resuming ? "thread/resume" : "thread/start",
- params,
- }) + "\n",
+ jsonRpcRequest(resuming ? "thread/resume" : "thread/start", params, this.nextRequestId()) + "\n",
);
});
@@ -148,23 +150,11 @@ export class CodexDriver implements Driver {
const threadId = sessionId ?? this.eventNormalizer.currentSessionId;
if (!threadId) return null;
const input = [{ type: "text", text }];
- if (opts?.mode === "idle") {
- return JSON.stringify({
- jsonrpc: "2.0",
- id: this.nextRequestId(),
- method: "turn/start",
- params: { threadId, input },
- });
- }
- return JSON.stringify({
- jsonrpc: "2.0",
- id: this.nextRequestId(),
- method: "turn/steer",
- params: { threadId, input },
- });
+ const method = opts?.mode === "idle" ? "turn/start" : "turn/steer";
+ return jsonRpcRequest(method, { threadId, input }, this.nextRequestId());
}
buildSystemPrompt(config: LaunchConfig): string {
- return buildCliTransportSystemPrompt(config, { lifecycleKind: this.lifecycle.kind });
+ return buildCliTransportSystemPrompt(config);
}
}
diff --git a/src/daemon/src/drivers/codexEventNormalizer.ts b/src/daemon/src/drivers/codexEventNormalizer.ts
index 2e7e8c996..a65548ed8 100644
--- a/src/daemon/src/drivers/codexEventNormalizer.ts
+++ b/src/daemon/src/drivers/codexEventNormalizer.ts
@@ -13,6 +13,7 @@
*/
import type { ParsedEvent } from "../types.js";
import { mapCodexTelemetry } from "./codexTelemetrySidecar.js";
+import { tryParseJsonLine } from "./utils.js";
export class CodexEventNormalizer {
private threadId: string | null = null;
@@ -26,12 +27,8 @@ export class CodexEventNormalizer {
}
normalizeLine(line: string): ParsedEvent[] {
- let msg: any;
- try {
- msg = JSON.parse(line);
- } catch {
- return [];
- }
+ const msg = tryParseJsonLine(line) as any;
+ if (!msg) return [];
// JSON-RPC error response.
if (msg?.error && msg.id !== undefined) {
diff --git a/src/daemon/src/drivers/copilot.ts b/src/daemon/src/drivers/copilot.ts
index 4fc44de25..3597d50db 100644
--- a/src/daemon/src/drivers/copilot.ts
+++ b/src/daemon/src/drivers/copilot.ts
@@ -10,6 +10,7 @@ import { prepareCliTransport, buildCliTransportSystemPrompt } from "./cliTranspo
import { probeCliRuntime, resolveSpawnSpec } from "./probe.js";
import { resolveLaunchFieldsOrDefault } from "../runtimeConfig.js";
import { spawnAgentProcess } from "../runtime/killTree.js";
+import { tryParseJsonLine } from "./utils.js";
export class CopilotDriver implements Driver {
readonly id = "copilot";
@@ -28,6 +29,14 @@ export class CopilotDriver implements Driver {
readonly supportsStdinNotification = false;
readonly busyDeliveryMode = "none" as const;
+ readonly capabilities = {
+ reasoningEffort: true,
+ fastMode: false,
+ disallowedTools: false,
+ command: true,
+ sessionResumeMode: "by-id",
+ } as const;
+
private sessionId: string | null = null;
probe() {
@@ -44,7 +53,7 @@ export class CopilotDriver implements Driver {
async spawn(ctx: LaunchContext): Promise<SpawnResult> {
this.sessionId = ctx.config.sessionId ?? null;
- const { spawnEnv } = await prepareCliTransport(ctx, { NO_COLOR: "1" });
+ const { spawnEnv } = await prepareCliTransport(ctx);
const f = resolveLaunchFieldsOrDefault(ctx.config.runtimeConfig);
const args = ["--output-format", "json", "--allow-all-tools", "--allow-all-paths", "-p", ctx.prompt];
if (f.model) args.push("--model", f.model);
@@ -53,7 +62,7 @@ export class CopilotDriver implements Driver {
// Cross-platform spawn: on Windows the copilot entry is often a `.cmd`
// shim, which `child_process.spawn` can't exec without a shell.
- const spec = resolveSpawnSpec("copilot", args);
+ const spec = resolveSpawnSpec("copilot", args, f.command);
const proc = spawnAgentProcess(spec.command, spec.args, {
cwd: ctx.workingDirectory,
env: spawnEnv,
@@ -63,12 +72,8 @@ export class CopilotDriver implements Driver {
}
parseLine(line: string): ParsedEvent[] {
- let event: any;
- try {
- event = JSON.parse(line);
- } catch {
- return [];
- }
+ const event = tryParseJsonLine(line) as any;
+ if (!event) return [];
switch (event?.type) {
case "assistant.turn_start":
if (event.sessionId) this.sessionId = event.sessionId;
@@ -106,6 +111,6 @@ export class CopilotDriver implements Driver {
}
buildSystemPrompt(config: LaunchConfig): string {
- return buildCliTransportSystemPrompt(config, { lifecycleKind: this.lifecycle.kind });
+ return buildCliTransportSystemPrompt(config);
}
}
diff --git a/src/daemon/src/drivers/cursor.ts b/src/daemon/src/drivers/cursor.ts
index 064d3136a..8f463f4fe 100644
--- a/src/daemon/src/drivers/cursor.ts
+++ b/src/daemon/src/drivers/cursor.ts
@@ -10,6 +10,7 @@ import { prepareCliTransport, buildCliTransportSystemPrompt } from "./cliTranspo
import { probeCliRuntime, resolveSpawnSpec } from "./probe.js";
import { resolveLaunchFieldsOrDefault } from "../runtimeConfig.js";
import { spawnAgentProcess } from "../runtime/killTree.js";
+import { tryParseJsonLine } from "./utils.js";
export class CursorDriver implements Driver {
readonly id = "cursor";
@@ -28,6 +29,14 @@ export class CursorDriver implements Driver {
readonly supportsStdinNotification = false;
readonly busyDeliveryMode = "none" as const;
+ readonly capabilities = {
+ reasoningEffort: false,
+ fastMode: false,
+ disallowedTools: false,
+ command: true,
+ sessionResumeMode: "by-id",
+ } as const;
+
private sessionId: string | null = null;
probe() {
@@ -36,7 +45,7 @@ export class CursorDriver implements Driver {
async spawn(ctx: LaunchContext): Promise<SpawnResult> {
this.sessionId = ctx.config.sessionId ?? null;
- const { spawnEnv } = await prepareCliTransport(ctx, { NO_COLOR: "1" });
+ const { spawnEnv } = await prepareCliTransport(ctx);
const f = resolveLaunchFieldsOrDefault(ctx.config.runtimeConfig);
const args = ["--print", "--output-format", "stream-json", "--yolo", "--approve-mcps", "--trust"];
if (f.model) args.push("--model", f.model);
@@ -45,7 +54,7 @@ export class CursorDriver implements Driver {
// Cross-platform spawn: on Windows the cursor-agent entry is often a
// `.cmd` shim, which `child_process.spawn` can't exec without a shell.
- const spec = resolveSpawnSpec("cursor-agent", args);
+ const spec = resolveSpawnSpec("cursor-agent", args, f.command);
const proc = spawnAgentProcess(spec.command, spec.args, {
cwd: ctx.workingDirectory,
env: spawnEnv,
@@ -55,12 +64,8 @@ export class CursorDriver implements Driver {
}
parseLine(line: string): ParsedEvent[] {
- let event: any;
- try {
- event = JSON.parse(line);
- } catch {
- return [];
- }
+ const event = tryParseJsonLine(line) as any;
+ if (!event) return [];
if (event?.type === "system") {
if (event.subtype === "init") {
this.sessionId = event.session_id ?? this.sessionId;
@@ -102,6 +107,6 @@ export class CursorDriver implements Driver {
}
buildSystemPrompt(config: LaunchConfig): string {
- return buildCliTransportSystemPrompt(config, { lifecycleKind: this.lifecycle.kind });
+ return buildCliTransportSystemPrompt(config);
}
}
diff --git a/src/daemon/src/drivers/gemini.test.ts b/src/daemon/src/drivers/gemini.test.ts
new file mode 100644
index 000000000..983f32aaa
--- /dev/null
+++ b/src/daemon/src/drivers/gemini.test.ts
@@ -0,0 +1,29 @@
+import { describe, it, expect } from "vitest";
+import { buildGeminiArgs, GeminiDriver } from "./gemini";
+import { makeRuntimeConfig } from "../runtimeConfig";
+import type { LaunchConfig } from "../types";
+
+describe("GeminiDriver", () => {
+ it("declares detectedModelsVerifiedAs 'launchable' (its --model flag actually launches)", () => {
+ const driver = new GeminiDriver();
+ expect(driver.model.detectedModelsVerifiedAs).toBe("launchable");
+ });
+});
+
+describe("buildGeminiArgs — model flag is conditional on f.model", () => {
+ it("omits --model when the runtime config leaves it default", () => {
+ const config: LaunchConfig = { runtimeConfig: makeRuntimeConfig({ runtime: "gemini" }) };
+ const args = buildGeminiArgs(config);
+ expect(args).not.toContain("--model");
+ });
+
+ it("pushes --model <name> when a named model is set", () => {
+ const config: LaunchConfig = {
+ runtimeConfig: makeRuntimeConfig({ runtime: "gemini", model: { kind: "named", name: "gemini-2.5-pro" } }),
+ };
+ const args = buildGeminiArgs(config);
+ const idx = args.indexOf("--model");
+ expect(idx).toBeGreaterThan(-1);
+ expect(args[idx + 1]).toBe("gemini-2.5-pro");
+ });
+});
diff --git a/src/daemon/src/drivers/gemini.ts b/src/daemon/src/drivers/gemini.ts
index 6b7aba033..d0b1a3f6b 100644
--- a/src/daemon/src/drivers/gemini.ts
+++ b/src/daemon/src/drivers/gemini.ts
@@ -12,6 +12,7 @@ import { prepareCliTransport, buildCliTransportSystemPrompt } from "./cliTranspo
import { probeCliRuntime, resolveSpawnSpec } from "./probe.js";
import { resolveLaunchFieldsOrDefault } from "../runtimeConfig.js";
import { spawnAgentProcess } from "../runtime/killTree.js";
+import { tryParseJsonLine, writeToStdinAndDetach } from "./utils.js";
export function buildGeminiArgs(config: LaunchConfig): string[] {
const f = resolveLaunchFieldsOrDefault(config.runtimeConfig);
@@ -36,14 +37,22 @@ export class GeminiDriver implements Driver {
} as const;
readonly session = { recovery: "resume_or_fresh" } as const;
readonly model = {
- detectedModelsVerifiedAs: "suggestion_only",
+ detectedModelsVerifiedAs: "launchable",
toLaunchSpec: (modelId: string) =>
- modelId && modelId !== "default" ? { args: ["--model", modelId] } : { args: [] },
+ modelId ? { args: ["--model", modelId] } : { args: [] },
} as const;
readonly supportsStdinNotification = false;
readonly busyDeliveryMode = "none" as const;
+ readonly capabilities = {
+ reasoningEffort: false,
+ fastMode: false,
+ disallowedTools: false,
+ command: true,
+ sessionResumeMode: "by-id",
+ } as const;
+
private sessionId: string | null = null;
probe() {
@@ -52,29 +61,30 @@ export class GeminiDriver implements Driver {
async spawn(ctx: LaunchContext): Promise<SpawnResult> {
this.sessionId = ctx.config.sessionId ?? null;
- const { spawnEnv } = await prepareCliTransport(ctx, { NO_COLOR: "1" });
+ const { spawnEnv } = await prepareCliTransport(ctx);
+ // Gemini refuses to run in a workspace it doesn't "trust" — an interactive
+ // gate that has no meaning for a headless spawn. Force-trust the workdir
+ // unconditionally; the sandboxing that gate is intended to provide is
+ // already covered by the credential proxy + capability scope.
spawnEnv.GEMINI_CLI_TRUST_WORKSPACE ??= "true";
if (process.platform === "win32") spawnEnv.GEMINI_PTY_INFO ??= "child_process";
// Cross-platform spawn: on Windows the gemini entry is often a `.cmd` shim.
- const spec = resolveSpawnSpec("gemini", buildGeminiArgs(ctx.config));
+ const override = resolveLaunchFieldsOrDefault(ctx.config.runtimeConfig).command;
+ const spec = resolveSpawnSpec("gemini", buildGeminiArgs(ctx.config), override);
const proc = spawnAgentProcess(spec.command, spec.args, {
cwd: ctx.workingDirectory,
env: spawnEnv,
shell: spec.shell,
});
// Prompt in, then close stdin — one-shot.
- proc.stdin?.end(ctx.prompt);
+ writeToStdinAndDetach(proc, ctx.prompt);
return { process: proc };
}
parseLine(line: string): ParsedEvent[] {
- let event: any;
- try {
- event = JSON.parse(line);
- } catch {
- return [];
- }
+ const event = tryParseJsonLine(line) as any;
+ if (!event) return [];
switch (event?.type) {
case "init":
this.sessionId = event.session_id ?? this.sessionId;
@@ -104,6 +114,6 @@ export class GeminiDriver implements Driver {
}
buildSystemPrompt(config: LaunchConfig): string {
- return buildCliTransportSystemPrompt(config, { lifecycleKind: this.lifecycle.kind });
+ return buildCliTransportSystemPrompt(config);
}
}
diff --git a/src/daemon/src/drivers/kimi.test.ts b/src/daemon/src/drivers/kimi.test.ts
new file mode 100644
index 000000000..91571f2bc
--- /dev/null
+++ b/src/daemon/src/drivers/kimi.test.ts
@@ -0,0 +1,61 @@
+import { describe, it, expect, vi } from "vitest";
+import { EventEmitter } from "events";
+import * as fs from "fs";
+import * as os from "os";
+import * as path from "path";
+import { KimiDriver, KIMI_WIRE_PROTOCOL_VERSION } from "./kimi";
+import type { LaunchContext } from "../types";
+import { CredentialBroker } from "../credentials/credentialProxy";
+import { readDaemonVersion } from "../version";
+
+vi.mock("../runtime/killTree", async () => {
+ const actual = await vi.importActual<typeof import("../runtime/killTree")>("../runtime/killTree");
+ return {
+ ...actual,
+ spawnAgentProcess: () => {
+ const proc = new EventEmitter() as EventEmitter & { stdin: { write: ReturnType<typeof vi.fn> } };
+ proc.stdin = { write: vi.fn() };
+ return proc as never;
+ },
+ };
+});
+
+function mkTmp(): string {
+ return fs.mkdtempSync(path.join(os.tmpdir(), "kimi-test-"));
+}
+
+function baseCtx(): LaunchContext {
+ const tmp = mkTmp();
+ return {
+ agentId: "agent_1",
+ launchId: "launch_1",
+ workingDirectory: tmp,
+ standingPrompt: "You are Kimi.",
+ prompt: "hi",
+ credentialProxy: {
+ broker: new CredentialBroker({ upstreamBaseUrl: "https://u.test", voucherDir: mkTmp() }),
+ proxyUrl: "http://127.0.0.1:9/proxy",
+ runnerKey: "sk_agent_test",
+ capabilities: ["send", "read"],
+ },
+ config: {},
+ };
+}
+
+describe("KimiDriver initialize payload", () => {
+ it("sends alook-daemon identity and the named protocol version", async () => {
+ const driver = new KimiDriver();
+ const ctx = baseCtx();
+ const { process: proc } = await driver.spawn(ctx);
+ const stdin = (proc as unknown as { stdin: { write: ReturnType<typeof vi.fn> } }).stdin;
+
+ // First stdin write is `initialize`.
+ const firstCall = stdin.write.mock.calls[0][0] as string;
+ const initPayload = JSON.parse(firstCall.trim());
+
+ expect(initPayload.jsonrpc).toBe("2.0");
+ expect(initPayload.method).toBe("initialize");
+ expect(initPayload.params.protocol_version).toBe(KIMI_WIRE_PROTOCOL_VERSION);
+ expect(initPayload.params.client).toEqual({ name: "alook-daemon", version: readDaemonVersion() });
+ });
+});
diff --git a/src/daemon/src/drivers/kimi.ts b/src/daemon/src/drivers/kimi.ts
index 173299ae5..1405f68a8 100644
--- a/src/daemon/src/drivers/kimi.ts
+++ b/src/daemon/src/drivers/kimi.ts
@@ -13,6 +13,11 @@ import { prepareCliTransport, buildCliTransportSystemPrompt } from "./cliTranspo
import { probeCliRuntime, resolveSpawnSpec } from "./probe.js";
import { resolveLaunchFieldsOrDefault } from "../runtimeConfig.js";
import { spawnAgentProcess } from "../runtime/killTree.js";
+import { jsonRpcRequest, tryParseJsonLine } from "./utils.js";
+import { getDaemonClientInfo } from "../version.js";
+
+/** Kimi `--wire` handshake protocol version. Bump when the vendor CLI does. */
+export const KIMI_WIRE_PROTOCOL_VERSION = "1.3";
function parseToolArguments(args: unknown): unknown {
if (typeof args !== "string") return args ?? {};
@@ -35,6 +40,17 @@ export class KimiDriver implements Driver {
readonly supportsStdinNotification = true;
readonly busyDeliveryMode = "direct" as const;
+ readonly capabilities = {
+ reasoningEffort: false,
+ fastMode: false,
+ disallowedTools: false,
+ command: true,
+ sessionResumeMode: "by-id",
+ } as const;
+
+ // Kimi's `--wire` handshake requires the client to supply the session id up
+ // front (there's no "server picks the id" path). We accept the caller's id
+ // when resuming and mint a fresh UUID otherwise; the id is the resume key.
private sessionId = "";
private sentInit = false;
private promptRequestId = randomUUID();
@@ -49,7 +65,7 @@ export class KimiDriver implements Driver {
// The standing prompt reaches Kimi via the AGENTS.md that prepareCliTransport
// writes into the workdir (unified packing — see cliTransport.ts) — Kimi
// auto-reads it from cwd, no --agent-file flag needed.
- const { spawnEnv } = await prepareCliTransport(ctx, { NO_COLOR: "1" });
+ const { spawnEnv } = await prepareCliTransport(ctx);
const f = resolveLaunchFieldsOrDefault(ctx.config.runtimeConfig);
const args = ["--wire", "--yolo", "--session", this.sessionId];
@@ -57,7 +73,7 @@ export class KimiDriver implements Driver {
// Cross-platform spawn: on Windows the kimi entry is often a `.cmd`
// shim, which `child_process.spawn` can't exec without a shell.
- const spec = resolveSpawnSpec("kimi", args);
+ const spec = resolveSpawnSpec("kimi", args, f.command);
const proc = spawnAgentProcess(spec.command, spec.args, {
cwd: ctx.workingDirectory,
env: spawnEnv,
@@ -65,40 +81,30 @@ export class KimiDriver implements Driver {
});
proc.stdin?.write(
- JSON.stringify({
- jsonrpc: "2.0",
- id: randomUUID(),
- method: "initialize",
- params: {
- protocol_version: "1.3",
- client: { name: "agent-backend", version: "1.0.0" },
- capabilities: { supports_question: false, supports_plan_mode: false },
- },
+ jsonRpcRequest("initialize", {
+ protocol_version: KIMI_WIRE_PROTOCOL_VERSION,
+ client: getDaemonClientInfo(),
+ capabilities: { supports_question: false, supports_plan_mode: false },
}) + "\n",
);
proc.stdin?.write(
- JSON.stringify({
- jsonrpc: "2.0",
- id: this.promptRequestId,
- method: "prompt",
- params: {
+ jsonRpcRequest(
+ "prompt",
+ {
user_input: isResume
? ctx.prompt
: "Your system prompt contains your standing instructions. Follow it now and begin listening for messages.",
},
- }) + "\n",
+ this.promptRequestId,
+ ) + "\n",
);
return { process: proc };
}
parseLine(line: string): ParsedEvent[] {
- let msg: any;
- try {
- msg = JSON.parse(line);
- } catch {
- return [];
- }
+ const msg = tryParseJsonLine(line) as any;
+ if (!msg) return [];
const out: ParsedEvent[] = [];
if (!this.sentInit) {
this.sentInit = true;
@@ -152,10 +158,10 @@ export class KimiDriver implements Driver {
/** idle → `prompt`; busy → `steer`. */
encodeStdinMessage(text: string, _sessionId: string | null, opts?: EncodeOpts): string | null {
const method = opts?.mode === "idle" ? "prompt" : "steer";
- return JSON.stringify({ jsonrpc: "2.0", id: randomUUID(), method, params: { user_input: text } });
+ return jsonRpcRequest(method, { user_input: text });
}
buildSystemPrompt(config: LaunchConfig): string {
- return buildCliTransportSystemPrompt(config, { lifecycleKind: this.lifecycle.kind });
+ return buildCliTransportSystemPrompt(config);
}
}
diff --git a/src/daemon/src/drivers/opencode.ts b/src/daemon/src/drivers/opencode.ts
index 8f4215f96..9893f43b7 100644
--- a/src/daemon/src/drivers/opencode.ts
+++ b/src/daemon/src/drivers/opencode.ts
@@ -13,6 +13,7 @@ import { prepareCliTransport, buildCliTransportSystemPrompt } from "./cliTranspo
import { probeCliRuntime, resolveSpawnSpec } from "./probe.js";
import { resolveLaunchFieldsOrDefault } from "../runtimeConfig.js";
import { spawnAgentProcess } from "../runtime/killTree.js";
+import { tryParseJsonLine } from "./utils.js";
export class OpenCodeDriver implements Driver {
readonly id = "opencode";
@@ -33,6 +34,14 @@ export class OpenCodeDriver implements Driver {
readonly terminateProcessOnTurnEnd = true;
readonly deferSpawnUntilMessage = true;
+ readonly capabilities = {
+ reasoningEffort: false,
+ fastMode: false,
+ disallowedTools: false,
+ command: true,
+ sessionResumeMode: "by-id",
+ } as const;
+
private sessionId: string | null = null;
/** System task wakes (first-message bookkeeping) should not spawn a process. */
@@ -49,7 +58,7 @@ export class OpenCodeDriver implements Driver {
const f = resolveLaunchFieldsOrDefault(ctx.config.runtimeConfig);
// prepareCliTransport writes AGENTS.md into the workdir (unified packing) —
// OpenCode auto-reads it from cwd, no custom `host` agent config needed.
- const { spawnEnv } = await prepareCliTransport(ctx, { NO_COLOR: "1" });
+ const { spawnEnv } = await prepareCliTransport(ctx);
const args = ["run", "--format", "json", "--dangerously-skip-permissions", "--pure", "--dir", ctx.workingDirectory];
if (f.model) args.push("--model", f.model);
@@ -59,7 +68,7 @@ export class OpenCodeDriver implements Driver {
// Cross-platform spawn: on Windows the opencode entry is often a `.cmd`
// shim, which `child_process.spawn` can't exec without a shell.
- const spec = resolveSpawnSpec("opencode", args);
+ const spec = resolveSpawnSpec("opencode", args, f.command);
const proc = spawnAgentProcess(spec.command, spec.args, {
cwd: ctx.workingDirectory,
env: spawnEnv,
@@ -70,12 +79,8 @@ export class OpenCodeDriver implements Driver {
}
parseLine(line: string): ParsedEvent[] {
- let event: any;
- try {
- event = JSON.parse(line);
- } catch {
- return [];
- }
+ const event = tryParseJsonLine(line) as any;
+ if (!event) return [];
const out: ParsedEvent[] = [];
if (event?.sessionID && this.sessionId !== event.sessionID) {
this.sessionId = event.sessionID;
@@ -119,6 +124,6 @@ export class OpenCodeDriver implements Driver {
}
buildSystemPrompt(config: LaunchConfig): string {
- return buildCliTransportSystemPrompt(config, { lifecycleKind: this.lifecycle.kind });
+ return buildCliTransportSystemPrompt(config);
}
}
diff --git a/src/daemon/src/drivers/pi.test.ts b/src/daemon/src/drivers/pi.test.ts
index 1ab9db76e..c0b0e3e33 100644
--- a/src/daemon/src/drivers/pi.test.ts
+++ b/src/daemon/src/drivers/pi.test.ts
@@ -2,8 +2,8 @@ import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
import * as fs from "fs";
import * as os from "os";
import * as path from "path";
-import { PiDriver, resolvePiSdkVersionFromPath, resolvePiSdkPackageDir } from "./pi";
-import { CANONICAL_FILE, SYMLINK_ALIASES } from "./agentFile";
+import { PiDriver, resolvePiSdkVersionFromPath, resolvePiSdkPackageDir, findPiSessionFile } from "./pi";
+import { CANONICAL_FILE } from "./agentFile";
import type { LaunchContext } from "../types";
let tmpDir: string;
@@ -42,44 +42,19 @@ function fakeDeps() {
}
describe("PiDriver.createSession — AGENTS.md packing", () => {
- it("writes AGENTS.md into the workdir instead of passing standingPrompt to the SDK", async () => {
+ it("does not write AGENTS.md itself — prepareCliTransport (inside piSdkDeps.buildSpawnEnv) is the single packing point", async () => {
const driver = new PiDriver();
const deps = fakeDeps();
await driver.createSession(baseCtx(), deps);
- expect(fs.readFileSync(path.join(tmpDir, CANONICAL_FILE), "utf-8")).toBe("You are Pi.");
- expect(fs.lstatSync(path.join(tmpDir, SYMLINK_ALIASES[0])).isSymbolicLink()).toBe(true);
+ // The driver no longer writes AGENTS.md — buildSpawnEnv already did, and
+ // duplicating the write here would risk hash-dedup drift.
+ expect(fs.existsSync(path.join(tmpDir, CANONICAL_FILE))).toBe(false);
const sessionOpts = deps.createAgentSession.mock.calls[0][0];
expect(sessionOpts).not.toHaveProperty("standingPrompt");
});
-
- it("does not rewrite AGENTS.md when the standing prompt is unchanged (hash dedup)", async () => {
- const driver = new PiDriver();
- await driver.createSession(baseCtx(), fakeDeps());
- const firstMtime = fs.statSync(path.join(tmpDir, CANONICAL_FILE)).mtimeMs;
-
- // Second session, identical standingPrompt — file content must be untouched.
- await new Promise((r) => setTimeout(r, 5));
- await driver.createSession(baseCtx(), fakeDeps());
- const secondMtime = fs.statSync(path.join(tmpDir, CANONICAL_FILE)).mtimeMs;
-
- expect(secondMtime).toBe(firstMtime);
- });
-
- it("skips the write when standingPrompt is empty", async () => {
- const driver = new PiDriver();
- await driver.createSession(baseCtx({ standingPrompt: "" }), fakeDeps());
- expect(fs.existsSync(path.join(tmpDir, CANONICAL_FILE))).toBe(false);
- });
-
- it("creates the workdir first when it doesn't exist yet (unlike prepareCliTransport's stateDir mkdir, nothing else guarantees this for Pi)", async () => {
- const driver = new PiDriver();
- const notYetCreated = path.join(tmpDir, "not-yet-created", "agent_1");
- await driver.createSession(baseCtx({ workingDirectory: notYetCreated }), fakeDeps());
- expect(fs.readFileSync(path.join(notYetCreated, CANONICAL_FILE), "utf-8")).toBe("You are Pi.");
- });
});
describe("PiDriver.createSession — does not fire the initial prompt itself", () => {
@@ -113,6 +88,31 @@ describe("PiDriver.createSession — does not fire the initial prompt itself", (
});
});
+describe("findPiSessionFile", () => {
+ it("matches an entry ending in `_${sessionId}.jsonl`", () => {
+ const sessionDir = path.join(tmpDir, "sessions");
+ fs.mkdirSync(sessionDir, { recursive: true });
+ fs.writeFileSync(path.join(sessionDir, "2026-01-01_someone-else.jsonl"), "");
+ fs.writeFileSync(path.join(sessionDir, "2026-05-01_target-id.jsonl"), "");
+
+ expect(findPiSessionFile(sessionDir, "target-id")).toBe(
+ path.join(sessionDir, "2026-05-01_target-id.jsonl"),
+ );
+ });
+
+ it("returns null when no entry matches the id", () => {
+ const sessionDir = path.join(tmpDir, "sessions");
+ fs.mkdirSync(sessionDir, { recursive: true });
+ fs.writeFileSync(path.join(sessionDir, "2026-01-01_someone-else.jsonl"), "");
+
+ expect(findPiSessionFile(sessionDir, "target-id")).toBeNull();
+ });
+
+ it("returns null when the session directory is unreadable / missing", () => {
+ expect(findPiSessionFile(path.join(tmpDir, "does-not-exist"), "target-id")).toBeNull();
+ });
+});
+
describe("resolvePiSdkVersionFromPath — globally-installed pi fallback detection", () => {
it("finds the SDK version by following the `pi` binary's symlink up to its package.json (simulates npm/Homebrew/pnpm global installs)", () => {
// Simulate a global install layout:
diff --git a/src/daemon/src/drivers/pi.ts b/src/daemon/src/drivers/pi.ts
index 538e3881d..41cdb80ab 100644
--- a/src/daemon/src/drivers/pi.ts
+++ b/src/daemon/src/drivers/pi.ts
@@ -7,10 +7,11 @@
* JSONL; a custom bash tool is injected so shell calls inherit the CLI-transport
* env. Steering is `direct` (guarded by `session.isStreaming`).
*
- * The standing prompt is delivered via `AGENTS.md` written directly into the
- * workdir (Pi never calls `prepareCliTransport`, so it can't get the file for
- * free the way child-process drivers do — it writes it itself, same file,
- * same convention).
+ * The standing prompt is delivered via `AGENTS.md` written into the workdir
+ * by `prepareCliTransport` inside `piSdkDeps.buildSpawnEnv` — Pi is unusual in
+ * that it has no child process of its own, but its bash tool still goes
+ * through the same transport, so the AGENTS.md packing happens exactly once
+ * (in `buildSpawnEnv`) and this file doesn't need to re-write it.
*
* `createSession` only builds and wires the session — it does not send the
* first turn. `SdkManagedSession` (the `ManagedSession` adapter that drives
@@ -19,11 +20,11 @@
* fires into an unlistened `EventEmitter` and gets dropped.
*/
import { createRequire } from "module";
-import { mkdirSync, existsSync, readFileSync, realpathSync } from "fs";
+import { existsSync, readdirSync, readFileSync, realpathSync } from "fs";
+import { homedir } from "os";
import * as path from "path";
import type { Driver, LaunchConfig, LaunchContext, ParsedEvent, SdkDriverDeps, SpawnResult } from "../types.js";
import { buildCliTransportSystemPrompt } from "./cliTransport.js";
-import { writeAgentFile } from "./agentFile.js";
import { SdkRuntimeSession, type SdkSessionHandle } from "../runtime/sdkRuntimeSession.js";
import { resolveLaunchFieldsOrDefault } from "../runtimeConfig.js";
import { resolveCommandOnPath, type ProbeDeps } from "./probe.js";
@@ -86,6 +87,11 @@ export function resolvePiSdkPackageDir(deps: ProbeDeps = {}): string | undefined
try {
let dir = path.dirname(realpathSync(binPath));
+ // 8 levels is enough to cover every layout we've seen: npm/pnpm globals
+ // resolve within 2-4 hops, nvm adds ~1, Homebrew Cellar adds ~2, and
+ // Windows `.cmd` shims sit alongside a sibling `node_modules` at the same
+ // root (0 hops upward, checked as the second shape below). Higher would
+ // wander into unrelated ancestor trees; lower would miss nvm-under-brew.
const MAX_DEPTH = 8;
for (let i = 0; i < MAX_DEPTH; i++) {
if (isPiSdkPackageJson(path.join(dir, "package.json"))) return dir;
@@ -103,6 +109,54 @@ export function resolvePiSdkPackageDir(deps: ProbeDeps = {}): string | undefined
return undefined;
}
+/**
+ * Locate the Pi SDK session-rollout file for `sessionId` in `sessionDir`.
+ *
+ * Pi persists each session as `<isoDate>_<sessionId>.jsonl` inside its session
+ * directory (`--<encoded-cwd>--`). To resume a specific session we need the
+ * actual file path — not just the id — because `SessionManager.open` takes a
+ * path. Returns null if the directory is unreadable or no matching file exists
+ * (the caller falls back to `create` in that case).
+ *
+ * Pure enough to unit-test without touching the SDK: read a directory, filter
+ * by suffix, return the first match.
+ */
+export function findPiSessionFile(sessionDir: string, sessionId: string): string | null {
+ let entries: string[];
+ try {
+ entries = readdirSync(sessionDir);
+ } catch {
+ return null;
+ }
+ const suffix = `_${sessionId}.jsonl`;
+ const match = entries.find((entry) => entry.endsWith(suffix));
+ return match ? path.join(sessionDir, match) : null;
+}
+
+/**
+ * Resolve the Pi SDK's session directory for `cwd`.
+ *
+ * Prefers the SDK's own `getDefaultSessionDir` when the loaded module actually
+ * exposes it. It is NOT part of the vendor package's top-level exports (the
+ * barrel re-exports only `SessionManager` from `core/session-manager.js`), so
+ * calling it unconditionally throws `sdk.getDefaultSessionDir is not a
+ * function` and takes down every Pi resume. When it's absent we reproduce the
+ * SDK's own rule (`core/session-manager.js`): `<agentDir>/sessions/--<cwd with
+ * the leading separator stripped and remaining separators/colons turned into
+ * dashes>--`, rooted at the exported `getAgentDir()` (or `~/.pi/agent`).
+ */
+export function resolvePiSessionDir(
+ sdk: { getDefaultSessionDir?: (cwd: string) => string; getAgentDir?: () => string },
+ cwd: string,
+): string {
+ if (typeof sdk.getDefaultSessionDir === "function") return sdk.getDefaultSessionDir(cwd);
+ const agentDir = typeof sdk.getAgentDir === "function"
+ ? sdk.getAgentDir()
+ : path.join(homedir(), ".pi", "agent");
+ const encoded = `--${path.resolve(cwd).replace(/^[/\\]/, "").replace(/[/\\:]/g, "-")}--`;
+ return path.join(agentDir, "sessions", encoded);
+}
+
/** Read just the version out of the package.json `resolvePiSdkPackageDir` finds. */
export function resolvePiSdkVersionFromPath(deps: ProbeDeps = {}): string | undefined {
const dir = resolvePiSdkPackageDir(deps);
@@ -190,6 +244,14 @@ export class PiDriver implements Driver {
readonly busyDeliveryMode = "direct" as const;
readonly supportsNativeStandingPrompt = true;
+ readonly capabilities = {
+ reasoningEffort: true,
+ fastMode: false,
+ disallowedTools: false,
+ command: true,
+ sessionResumeMode: "by-id",
+ } as const;
+
private sessionId: string | null = null;
probe() {
@@ -221,15 +283,6 @@ export class PiDriver implements Driver {
*/
async createSession(ctx: LaunchContext, deps: SdkDriverDeps): Promise<SdkRuntimeSession> {
const spawnEnv = await deps.buildSpawnEnv();
- // Pi has no child process, so it never goes through prepareCliTransport —
- // write AGENTS.md here directly (same unified packing every other driver
- // gets); Pi's SDK auto-reads it from cwd, same as the CLI drivers. Unlike
- // prepareCliTransport (which creates the workdir via its stateDir mkdir),
- // nothing guarantees ctx.workingDirectory exists yet, so create it first.
- if (ctx.standingPrompt) {
- mkdirSync(ctx.workingDirectory, { recursive: true });
- writeAgentFile(ctx.workingDirectory, ctx.standingPrompt);
- }
const f = resolveLaunchFieldsOrDefault(ctx.config.runtimeConfig);
const { session, sessionId } = (await deps.createAgentSession({
cwd: ctx.workingDirectory,
@@ -276,6 +329,6 @@ export class PiDriver implements Driver {
}
buildSystemPrompt(config: LaunchConfig): string {
- return buildCliTransportSystemPrompt(config, { lifecycleKind: this.lifecycle.kind });
+ return buildCliTransportSystemPrompt(config);
}
}
diff --git a/src/daemon/src/drivers/piSdkDeps.test.ts b/src/daemon/src/drivers/piSdkDeps.test.ts
index f9d22564c..82e590add 100644
--- a/src/daemon/src/drivers/piSdkDeps.test.ts
+++ b/src/daemon/src/drivers/piSdkDeps.test.ts
@@ -36,26 +36,48 @@ function baseCtx(overrides: Partial<LaunchContext> = {}): LaunchContext {
}
/** A fake SDK module — never touches the real @earendil-works/pi-coding-agent. */
-function fakeSdk(): {
+function fakeSdk(opts: {
+ sessionDir?: string;
+ sessionDirEntries?: string[];
+ /** Simulate the real vendor barrel, which does NOT export getDefaultSessionDir. */
+ omitGetDefaultSessionDir?: boolean;
+ agentDir?: string;
+} = {}): {
loader: PiSdkLoader;
setRuntimeApiKey: ReturnType<typeof vi.fn>;
findModel: ReturnType<typeof vi.fn>;
sessionManagerCreate: ReturnType<typeof vi.fn>;
+ sessionManagerOpen: ReturnType<typeof vi.fn>;
sessionManagerContinueRecent: ReturnType<typeof vi.fn>;
+ getDefaultSessionDir: ReturnType<typeof vi.fn>;
createBashToolDefinition: ReturnType<typeof vi.fn>;
createAgentSession: ReturnType<typeof vi.fn>;
} {
const setRuntimeApiKey = vi.fn();
const findModel = vi.fn().mockReturnValue({ provider: "google", id: "gemini-2.5-pro" });
const sessionManagerCreate = vi.fn().mockReturnValue({ tag: "fresh" });
+ const sessionManagerOpen = vi.fn().mockReturnValue({ tag: "opened" });
const sessionManagerContinueRecent = vi.fn().mockReturnValue({ tag: "continued" });
+ const sessionDir = opts.sessionDir ?? mkTmp();
+ if (opts.sessionDirEntries) {
+ for (const entry of opts.sessionDirEntries) {
+ fs.writeFileSync(path.join(sessionDir, entry), "");
+ }
+ }
+ const getDefaultSessionDir = vi.fn().mockReturnValue(sessionDir);
const createBashToolDefinition = vi.fn().mockReturnValue({ name: "bash" });
const createAgentSession = vi.fn().mockResolvedValue({ session: { sessionId: "sess-from-sdk" } });
const sdk: PiSdkModule = {
AuthStorage: { create: () => ({ setRuntimeApiKey }) },
ModelRegistry: { create: () => ({ find: findModel }) },
- SessionManager: { create: sessionManagerCreate, continueRecent: sessionManagerContinueRecent },
+ SessionManager: {
+ create: sessionManagerCreate,
+ open: sessionManagerOpen,
+ continueRecent: sessionManagerContinueRecent,
+ },
+ ...(opts.omitGetDefaultSessionDir ? {} : { getDefaultSessionDir }),
+ ...(opts.agentDir ? { getAgentDir: () => opts.agentDir! } : {}),
createBashToolDefinition,
createAgentSession,
};
@@ -64,7 +86,9 @@ function fakeSdk(): {
setRuntimeApiKey,
findModel,
sessionManagerCreate,
+ sessionManagerOpen,
sessionManagerContinueRecent,
+ getDefaultSessionDir,
createBashToolDefinition,
createAgentSession,
};
@@ -130,18 +154,59 @@ describe("createPiSdkDriverDeps — createAgentSession", () => {
expect(fake.createAgentSession).toHaveBeenCalledWith(expect.objectContaining({ model: undefined }));
});
- it("uses SessionManager.continueRecent when a sessionId is provided", async () => {
- const fake = fakeSdk();
+ it("resumes by id: sessionId + matching rollout file → SessionManager.open(file, sessionDir, cwd)", async () => {
+ const sessionDir = mkTmp();
+ const fake = fakeSdk({
+ sessionDir,
+ sessionDirEntries: ["2026-05-01_resume-me.jsonl", "2026-01-01_someone-else.jsonl"],
+ });
const ctx = baseCtx();
const deps = createPiSdkDriverDeps(ctx, fake.loader);
await deps.createAgentSession({ cwd: ctx.workingDirectory, sessionId: "resume-me", spawnEnv: {} });
- expect(fake.sessionManagerContinueRecent).toHaveBeenCalledWith(ctx.workingDirectory);
+ expect(fake.getDefaultSessionDir).toHaveBeenCalledWith(ctx.workingDirectory);
+ expect(fake.sessionManagerOpen).toHaveBeenCalledWith(
+ path.join(sessionDir, "2026-05-01_resume-me.jsonl"),
+ sessionDir,
+ ctx.workingDirectory,
+ );
expect(fake.sessionManagerCreate).not.toHaveBeenCalled();
+ expect(fake.sessionManagerContinueRecent).not.toHaveBeenCalled();
+ });
+
+ it("no matching file: sessionId + empty session dir → create(cwd, sessionDir, { id })", async () => {
+ const sessionDir = mkTmp();
+ const fake = fakeSdk({ sessionDir });
+ const ctx = baseCtx();
+ const deps = createPiSdkDriverDeps(ctx, fake.loader);
+
+ await deps.createAgentSession({ cwd: ctx.workingDirectory, sessionId: "brand-new-id", spawnEnv: {} });
+
+ expect(fake.sessionManagerCreate).toHaveBeenCalledWith(ctx.workingDirectory, sessionDir, { id: "brand-new-id" });
+ expect(fake.sessionManagerOpen).not.toHaveBeenCalled();
+ expect(fake.sessionManagerContinueRecent).not.toHaveBeenCalled();
+ });
+
+ it("resumes without throwing when the SDK barrel omits getDefaultSessionDir (the real vendor shape)", async () => {
+ // The vendor package's top-level entry re-exports only `SessionManager`
+ // from core/session-manager.js — `getDefaultSessionDir` is NOT exported.
+ // Calling it unconditionally threw "is not a function" and broke every
+ // Pi resume, so the deps must fall back to deriving the dir themselves.
+ const agentDir = mkTmp();
+ const fake = fakeSdk({ omitGetDefaultSessionDir: true, agentDir });
+ const ctx = baseCtx();
+ const deps = createPiSdkDriverDeps(ctx, fake.loader);
+
+ await deps.createAgentSession({ cwd: ctx.workingDirectory, sessionId: "resume-me", spawnEnv: {} });
+
+ const encoded = `--${path.resolve(ctx.workingDirectory).replace(/^[/\\]/, "").replace(/[/\\:]/g, "-")}--`;
+ const expectedDir = path.join(agentDir, "sessions", encoded);
+ // No rollout file exists there, so it pins the id on a fresh session.
+ expect(fake.sessionManagerCreate).toHaveBeenCalledWith(ctx.workingDirectory, expectedDir, { id: "resume-me" });
});
- it("uses SessionManager.create for a fresh session when no sessionId is provided", async () => {
+ it("no sessionId: uses SessionManager.create(cwd) — a fresh session, unchanged from prior behavior", async () => {
const fake = fakeSdk();
const ctx = baseCtx();
const deps = createPiSdkDriverDeps(ctx, fake.loader);
@@ -149,6 +214,7 @@ describe("createPiSdkDriverDeps — createAgentSession", () => {
await deps.createAgentSession({ cwd: ctx.workingDirectory, spawnEnv: {} });
expect(fake.sessionManagerCreate).toHaveBeenCalledWith(ctx.workingDirectory);
+ expect(fake.sessionManagerOpen).not.toHaveBeenCalled();
expect(fake.sessionManagerContinueRecent).not.toHaveBeenCalled();
});
diff --git a/src/daemon/src/drivers/piSdkDeps.ts b/src/daemon/src/drivers/piSdkDeps.ts
index dcda497d6..f4a461c87 100644
--- a/src/daemon/src/drivers/piSdkDeps.ts
+++ b/src/daemon/src/drivers/piSdkDeps.ts
@@ -9,7 +9,7 @@ import { readFileSync } from "fs";
import * as path from "path";
import { pathToFileURL } from "url";
import type { LaunchContext, SdkDriverDeps } from "../types.js";
-import { resolvePiSdkPackageDir } from "./pi.js";
+import { findPiSessionFile, resolvePiSdkPackageDir, resolvePiSessionDir } from "./pi.js";
import { prepareCliTransport, DEFAULT_CLI_CONFIG } from "./cliTransport.js";
const PI_SDK_PACKAGE_NAME = "@earendil-works/pi-coding-agent";
@@ -19,9 +19,21 @@ export interface PiSdkModule {
AuthStorage: { create(authPath?: string): PiAuthStorage };
ModelRegistry: { create(authStorage: PiAuthStorage, modelsPath?: string): PiModelRegistry };
SessionManager: {
- create(cwd: string): unknown;
- continueRecent(cwd: string): unknown;
+ create(cwd: string, sessionDir?: string, options?: { id?: string }): unknown;
+ open(path: string, sessionDir?: string, cwdOverride?: string): unknown;
+ continueRecent(cwd: string, sessionDir?: string): unknown;
};
+ /**
+ * The SDK's own path-substitution rule for `<sessionDir>` — mirrors
+ * `--${cwd.replace(/^[/\\]/,"").replace(/[/\\:]/g,"-")}--` in
+ * `session-manager.js`. Preferred when present, but NOT part of the vendor
+ * package's top-level exports (it lives in `core/session-manager.js`, which
+ * the barrel re-exports only `SessionManager` from) — hence optional, with
+ * `resolvePiSessionDir` falling back to `getAgentDir` + the same rule.
+ */
+ getDefaultSessionDir?(cwd: string, agentDir?: string): string;
+ /** Root of the SDK's own config dir (`~/.pi/agent`) — this one IS exported. */
+ getAgentDir?(): string;
createBashToolDefinition(cwd: string, options?: PiBashToolOptions): unknown;
createAgentSession(options: Record<string, unknown>): Promise<{ session: unknown; sessionId?: string }>;
}
@@ -131,7 +143,25 @@ export function createPiSdkDriverDeps(ctx: LaunchContext, loadSdk: PiSdkLoader =
const model = parsed ? modelRegistry.find(parsed.provider, parsed.id) : undefined;
const cwd = opts.cwd as string;
- const sessionManager = opts.sessionId ? sdk.SessionManager.continueRecent(cwd) : sdk.SessionManager.create(cwd);
+ // Three-branch session acquisition — see the plan's Designs section:
+ // (i) sessionId + matching rollout file → SessionManager.open(...)
+ // (ii) sessionId + no matching file → create(cwd, sessionDir, { id })
+ // (iii) no sessionId → create(cwd) (fresh)
+ // We intentionally do NOT call continueRecent() for the no-id path —
+ // that would silently inherit whichever session ran last in this cwd,
+ // producing a real regression (wrong session on any workdir that has
+ // hosted more than one session).
+ const requestedSessionId = opts.sessionId as string | undefined;
+ let sessionManager: unknown;
+ if (requestedSessionId) {
+ const sessionDir = resolvePiSessionDir(sdk, cwd);
+ const existingFile = findPiSessionFile(sessionDir, requestedSessionId);
+ sessionManager = existingFile
+ ? sdk.SessionManager.open(existingFile, sessionDir, cwd)
+ : sdk.SessionManager.create(cwd, sessionDir, { id: requestedSessionId });
+ } else {
+ sessionManager = sdk.SessionManager.create(cwd);
+ }
const spawnEnv = opts.spawnEnv as NodeJS.ProcessEnv;
const bashTool = sdk.createBashToolDefinition(cwd, {
diff --git a/src/daemon/src/drivers/probe.test.ts b/src/daemon/src/drivers/probe.test.ts
index b9d76479b..2f8212363 100644
--- a/src/daemon/src/drivers/probe.test.ts
+++ b/src/daemon/src/drivers/probe.test.ts
@@ -15,6 +15,7 @@ describe("resolveSpawnSpec", () => {
const spec = resolveSpawnSpec(
"cursor-agent",
["--print"],
+ undefined,
{ which: () => "C:\\Users\\me\\AppData\\Roaming\\npm\\cursor-agent.cmd" },
"win32",
);
@@ -26,24 +27,45 @@ describe("resolveSpawnSpec", () => {
});
it("sets shell: true on win32 when the resolved binary is a .bat shim", () => {
- const spec = resolveSpawnSpec("kimi", [], { which: () => "C:\\tools\\kimi.bat" }, "win32");
+ const spec = resolveSpawnSpec("kimi", [], undefined, { which: () => "C:\\tools\\kimi.bat" }, "win32");
expect(spec.shell).toBe(true);
});
it("does not set shell when the resolved binary is a native .exe on win32", () => {
- const spec = resolveSpawnSpec("copilot", [], { which: () => "C:\\tools\\copilot.exe" }, "win32");
+ const spec = resolveSpawnSpec("copilot", [], undefined, { which: () => "C:\\tools\\copilot.exe" }, "win32");
expect(spec.shell).toBe(false);
});
it("never sets shell on POSIX, even for a path that looks like a shim", () => {
- const spec = resolveSpawnSpec("agy", [], { which: () => "/usr/local/bin/agy.cmd" }, "darwin");
+ const spec = resolveSpawnSpec("agy", [], undefined, { which: () => "/usr/local/bin/agy.cmd" }, "darwin");
expect(spec.shell).toBe(false);
});
it("falls back to the bare command name when PATH resolution fails, without a shell on POSIX", () => {
- const spec = resolveSpawnSpec("opencode", ["run"], { which: () => null }, "linux");
+ const spec = resolveSpawnSpec("opencode", ["run"], undefined, { which: () => null }, "linux");
expect(spec).toEqual({ command: "opencode", args: ["run"], shell: false });
});
+
+ it("honors an absolute-path override without re-resolving via PATH", () => {
+ const which = vi.fn(() => "/should/not/be/called");
+ const spec = resolveSpawnSpec("codex", ["run"], "/custom/bin/codex", { which }, "linux");
+ expect(spec.command).toBe("/custom/bin/codex");
+ expect(which).not.toHaveBeenCalled();
+ });
+
+ it("resolves a bare-name override via PATH (so a user can point at a differently-named binary)", () => {
+ const which = vi.fn(() => "/opt/kimi-custom/bin/kimi-alt");
+ const spec = resolveSpawnSpec("kimi", [], "kimi-alt", { which }, "linux");
+ expect(spec.command).toBe("/opt/kimi-custom/bin/kimi-alt");
+ expect(which).toHaveBeenCalledWith("kimi-alt");
+ });
+
+ it("treats empty or whitespace-only override as absent (falls back to command)", () => {
+ const which = vi.fn(() => "/usr/local/bin/codex");
+ const spec = resolveSpawnSpec("codex", [], " ", { which }, "linux");
+ expect(spec.command).toBe("/usr/local/bin/codex");
+ expect(which).toHaveBeenCalledWith("codex");
+ });
});
/**
diff --git a/src/daemon/src/drivers/probe.ts b/src/daemon/src/drivers/probe.ts
index a702cefc5..6150e3103 100644
--- a/src/daemon/src/drivers/probe.ts
+++ b/src/daemon/src/drivers/probe.ts
@@ -7,6 +7,14 @@ import * as fs from "fs";
import * as path from "path";
import type { ProbeResult } from "../types.js";
+/**
+ * Wall-clock cap for every `--version`/`where`/`which` probe. Kept short: a
+ * healthy CLI answers in tens of milliseconds, and each unresponsive driver
+ * blocks daemon startup this long — with ~9 runtimes probed sequentially,
+ * every second here is a second of user-visible wait.
+ */
+const PROBE_TIMEOUT_MS = 5000;
+
export interface ProbeDeps {
homeDir?: string;
which?: (cmd: string) => string | null;
@@ -22,11 +30,11 @@ export function resolveCommandOnPath(command: string, deps: ProbeDeps = {}): str
// `powershell -Command` here instead cost 1-3s of interpreter cold-start
// PER call — with ~9 runtimes probed sequentially at daemon startup /
// in `detectRuntimes()` tests, that added up to 30s+ wall time.
- const out = execFileSync("where", [command], { encoding: "utf8", timeout: 5000 });
+ const out = execFileSync("where", [command], { encoding: "utf8", timeout: PROBE_TIMEOUT_MS });
const first = out.split(/\r?\n/).find((line) => line.trim().length > 0);
return first?.trim() || null;
}
- const out = execFileSync("which", [command], { encoding: "utf8", timeout: 5000 });
+ const out = execFileSync("which", [command], { encoding: "utf8", timeout: PROBE_TIMEOUT_MS });
return out.trim() || null;
} catch {
return null;
@@ -104,7 +112,7 @@ export function probeCommandVersion(
// `looksLikeVersion` validation below.
const out = execFileSync(command, [...args, "--version"], {
encoding: "utf8",
- timeout: 5000,
+ timeout: PROBE_TIMEOUT_MS,
shell,
input: "",
env: { ...process.env, CI: "1" },
@@ -122,17 +130,6 @@ export function probeCommandVersion(
}
}
-/**
- * @deprecated Use `probeCommandVersion` instead — it returns explicit
- * success/failure so callers can distinguish "binary not runnable" from
- * "binary runs but has no version output" and report `status: "unhealthy"`.
- * Retained as a thin shim for a couple of legacy call sites during rollout.
- */
-export function readCommandVersion(command: string, args: string[] = [], deps: ProbeDeps = {}): string | null {
- const r = probeCommandVersion(command, args, deps);
- return r.ok ? r.version : null;
-}
-
export function resolveHomePath(relativePath: string, deps: ProbeDeps = {}): string {
return path.join(deps.homeDir || process.env.HOME || ".", relativePath);
}
@@ -151,14 +148,25 @@ export interface SpawnSpec {
* spawn through a shell; we resolve the real path (PowerShell `Get-Command`,
* which returns the `.cmd`) and set `shell: true` when it looks like a shim.
* On POSIX, we resolve via `which` and never need a shell.
+ *
+ * When `override` is a non-empty string, it takes precedence over the default
+ * `command` — that's how `runtimeConfig.command` is honoured uniformly across
+ * every driver. If the override looks like an absolute path (or contains a
+ * separator) we don't re-resolve via PATH — the caller pointed us at a
+ * specific binary and we respect that; otherwise it's still a bare name that
+ * needs PATH resolution.
*/
export function resolveSpawnSpec(
command: string,
args: string[],
+ override?: string,
deps: ProbeDeps = {},
platform: NodeJS.Platform = process.platform,
): SpawnSpec {
- const resolved = resolveCommandOnPath(command, deps) ?? command;
+ const trimmed = override?.trim();
+ const target = trimmed && trimmed.length > 0 ? trimmed : command;
+ const looksLikePath = trimmed !== undefined && trimmed.length > 0 && /[\\/]/.test(trimmed);
+ const resolved = looksLikePath ? target : (resolveCommandOnPath(target, deps) ?? target);
return { command: resolved, args, shell: needsWindowsShimShell(resolved, platform) };
}
diff --git a/src/daemon/src/drivers/systemPrompt.test.ts b/src/daemon/src/drivers/systemPrompt.test.ts
index c3a7e20ae..d1ac93cb2 100644
--- a/src/daemon/src/drivers/systemPrompt.test.ts
+++ b/src/daemon/src/drivers/systemPrompt.test.ts
@@ -21,57 +21,41 @@ const baseConfig: LaunchConfig = {
* phrasing) changes constantly. Asserting on that content is worthless
* regression protection and turns every copy edit into a test-fixing chore.
* - Only test the INPUT → OUTPUT contract: values that come in via
- * `LaunchConfig` / `SystemPromptOpts` must round-trip verbatim into the
- * output, and their absence must NOT leak into the output.
+ * `LaunchConfig` must round-trip verbatim into the output, and their
+ * absence must NOT leak into the output.
* - DO NOT ADD tests that assert on specific prompt content (section headings,
* command names, feature strings, tone words). If you find yourself writing
* `expect(prompt).toContain("some english phrase")` for a phrase that isn't
* a value the caller passed in, stop — that test does not belong here.
*/
describe("buildCliSystemPrompt", () => {
- it("returns non-empty content for both lifecycle kinds", () => {
- expect(buildCliSystemPrompt(baseConfig, { lifecycleKind: "persistent" }).length).toBeGreaterThan(0);
- expect(buildCliSystemPrompt(baseConfig, { lifecycleKind: "per_turn" }).length).toBeGreaterThan(0);
- });
-
- it("produces the same content for persistent vs per_turn lifecycles (messageNotificationSection removed)", () => {
- const persistent = buildCliSystemPrompt(baseConfig, { lifecycleKind: "persistent" });
- const perTurn = buildCliSystemPrompt(baseConfig, { lifecycleKind: "per_turn" });
- expect(persistent).toBe(perTurn);
+ it("returns non-empty content", () => {
+ expect(buildCliSystemPrompt(baseConfig).length).toBeGreaterThan(0);
});
it("round-trips agentName and agentHandle verbatim, and omits them when absent", () => {
- const withIdentity = buildCliSystemPrompt(
- { ...baseConfig, agentName: "Nova", agentHandle: "@nova#7392" },
- { lifecycleKind: "persistent" },
- );
+ const withIdentity = buildCliSystemPrompt({ ...baseConfig, agentName: "Nova", agentHandle: "@nova#7392" });
expect(withIdentity).toContain("Nova");
expect(withIdentity).toContain("@nova#7392");
- const without = buildCliSystemPrompt(baseConfig, { lifecycleKind: "persistent" });
+ const without = buildCliSystemPrompt(baseConfig);
expect(without).not.toContain("Nova");
expect(without).not.toContain("#7392");
});
it("round-trips ownerHandle verbatim, and omits it when absent", () => {
- const withOwner = buildCliSystemPrompt(
- { ...baseConfig, ownerHandle: "@gustavo#5150" },
- { lifecycleKind: "persistent" },
- );
+ const withOwner = buildCliSystemPrompt({ ...baseConfig, ownerHandle: "@gustavo#5150" });
expect(withOwner).toContain("@gustavo#5150");
- const without = buildCliSystemPrompt(baseConfig, { lifecycleKind: "persistent" });
+ const without = buildCliSystemPrompt(baseConfig);
expect(without).not.toContain("#5150");
});
it("round-trips config.description verbatim, and omits it when absent", () => {
- const withRole = buildCliSystemPrompt(
- { ...baseConfig, description: "You are the onboarding assistant." },
- { lifecycleKind: "persistent" },
- );
+ const withRole = buildCliSystemPrompt({ ...baseConfig, description: "You are the onboarding assistant." });
expect(withRole).toContain("You are the onboarding assistant.");
- const withoutRole = buildCliSystemPrompt(baseConfig, { lifecycleKind: "persistent" });
+ const withoutRole = buildCliSystemPrompt(baseConfig);
expect(withoutRole).not.toContain("You are the onboarding assistant.");
});
});
diff --git a/src/daemon/src/drivers/systemPrompt.ts b/src/daemon/src/drivers/systemPrompt.ts
index 71112c5d0..abed5ce50 100644
--- a/src/daemon/src/drivers/systemPrompt.ts
+++ b/src/daemon/src/drivers/systemPrompt.ts
@@ -6,17 +6,6 @@ import type { LaunchConfig } from "../types.js";
const CLI = "alook";
-export interface SystemPromptOpts {
- /**
- * Drives the auto-generated `## Message notifications` section: whether
- * this runtime's process stays alive across turns (`"persistent"`) or
- * handles exactly one turn and exits (`"per_turn"`). Pass
- * `driver.lifecycle.kind` directly — do not hand-write reminder text per
- * driver.
- */
- lifecycleKind: "persistent" | "per_turn";
-}
-
/* ------------------------------------------------------------------ */
/* Section builders */
/* ------------------------------------------------------------------ */
@@ -401,17 +390,6 @@ function workspaceMemorySection(): string {
].join("\n");
}
-/**
- * The ONE place that decides what an agent needs to know about message
- * delivery, derived entirely from `lifecycleKind` — no driver hand-types this.
- *
- * - `persistent`: the process stays alive across turns, so busy-time inbox
- * notices can arrive mid-turn; the agent pulls bodies at a natural
- * breakpoint instead of blocking.
- * - `per_turn`: the process handles exactly one turn and exits; there is
- * nothing to poll for mid-turn — finish the current wake, then stop, and
- * the host spawns a fresh process for the next message.
- */
/* ------------------------------------------------------------------ */
/* Main builder */
/* ------------------------------------------------------------------ */
@@ -422,12 +400,11 @@ function workspaceMemorySection(): string {
* Asserts what's universally true for any Alook agent workspace — identity,
* CLI command reference, messaging mechanics, critical rules, startup
* sequence, communication style, channel awareness, workspace/memory model,
- * and notification handling. The only per-driver input is `lifecycleKind`.
+ * and utilities. Uniform across drivers — the returned string does not
+ * depend on which runtime is about to be spawned (see
+ * `systemPrompt.test.ts`).
*/
-export function buildCliSystemPrompt(
- config: LaunchConfig,
- _opts: SystemPromptOpts,
-): string {
+export function buildCliSystemPrompt(config: LaunchConfig): string {
const sections: string[] = [
identitySection(config),
cliCommandsSection(),
diff --git a/src/daemon/src/drivers/utils.test.ts b/src/daemon/src/drivers/utils.test.ts
new file mode 100644
index 000000000..0f6437484
--- /dev/null
+++ b/src/daemon/src/drivers/utils.test.ts
@@ -0,0 +1,60 @@
+import { describe, it, expect, vi } from "vitest";
+import { EventEmitter } from "events";
+import { jsonRpcRequest, tryParseJsonLine, writeToStdinAndDetach } from "./utils";
+
+describe("jsonRpcRequest", () => {
+ it("produces a valid JSON-RPC 2.0 envelope with the given method and params", () => {
+ const line = jsonRpcRequest("thread/start", { cwd: "/tmp" }, 7);
+ const parsed = JSON.parse(line);
+ expect(parsed).toEqual({ jsonrpc: "2.0", id: 7, method: "thread/start", params: { cwd: "/tmp" } });
+ });
+
+ it("mints a unique id when omitted", () => {
+ const a = JSON.parse(jsonRpcRequest("m", {}));
+ const b = JSON.parse(jsonRpcRequest("m", {}));
+ expect(a.id).toBeTruthy();
+ expect(b.id).toBeTruthy();
+ expect(a.id).not.toBe(b.id);
+ });
+
+ it("honours a caller-supplied id", () => {
+ const parsed = JSON.parse(jsonRpcRequest("m", {}, "kept"));
+ expect(parsed.id).toBe("kept");
+ });
+});
+
+describe("tryParseJsonLine", () => {
+ it("round-trips valid JSON", () => {
+ expect(tryParseJsonLine('{"a":1}')).toEqual({ a: 1 });
+ });
+
+ it("returns null (no throw) for invalid JSON", () => {
+ expect(tryParseJsonLine("not json")).toBeNull();
+ });
+
+ it("returns null for an empty line", () => {
+ expect(tryParseJsonLine("")).toBeNull();
+ });
+});
+
+describe("writeToStdinAndDetach", () => {
+ it("defers the write to a microtask and closes stdin exactly once after", async () => {
+ const stdin = { write: vi.fn(), end: vi.fn() };
+ const proc = Object.assign(new EventEmitter(), { stdin });
+ writeToStdinAndDetach(proc as never, "hello");
+
+ // Not written yet — microtask hasn't run.
+ expect(stdin.write).not.toHaveBeenCalled();
+ expect(stdin.end).not.toHaveBeenCalled();
+
+ await Promise.resolve();
+
+ expect(stdin.write).toHaveBeenCalledTimes(1);
+ expect(stdin.write).toHaveBeenCalledWith("hello");
+ expect(stdin.end).toHaveBeenCalledTimes(1);
+ // write is called before end within the same microtask flush.
+ const writeOrder = stdin.write.mock.invocationCallOrder[0];
+ const endOrder = stdin.end.mock.invocationCallOrder[0];
+ expect(writeOrder).toBeLessThan(endOrder);
+ });
+});
diff --git a/src/daemon/src/drivers/utils.ts b/src/daemon/src/drivers/utils.ts
new file mode 100644
index 000000000..7d821bae3
--- /dev/null
+++ b/src/daemon/src/drivers/utils.ts
@@ -0,0 +1,46 @@
+/**
+ * Small helpers shared across driver files. Each kills a duplication pattern
+ * that had multiple drivers copy-pasting the same 3-4 lines.
+ */
+import type { ChildProcess } from "child_process";
+import { randomUUID } from "crypto";
+
+/**
+ * Write `payload` (already includes any trailing newline) to a child's stdin
+ * on the next microtask, then close stdin. Used by drivers whose runtime is
+ * one-shot: they spawn, deliver the prompt, and the runtime exits when
+ * stdin closes.
+ *
+ * `queueMicrotask` mirrors codex's original pattern — it lets the caller
+ * finish attaching stdout/stderr listeners before the write is scheduled, so
+ * the child can never emit its first line into a listener-less pipe.
+ */
+export function writeToStdinAndDetach(proc: ChildProcess, payload: string): void {
+ queueMicrotask(() => {
+ proc.stdin?.write(payload);
+ proc.stdin?.end();
+ });
+}
+
+/**
+ * Build a JSON-RPC 2.0 request string (no trailing newline — the caller
+ * appends one when writing to stdin). Both Codex and Kimi speak JSON-RPC over
+ * stdio and every request they send follows this exact shape; centralize the
+ * envelope so `id` defaulting and `jsonrpc` version live in one place.
+ */
+export function jsonRpcRequest(method: string, params: unknown, id?: string | number): string {
+ return JSON.stringify({ jsonrpc: "2.0", id: id ?? randomUUID(), method, params });
+}
+
+/**
+ * Parse a single NDJSON line. Every event normalizer that reads a JSON stream
+ * needs the same `try/catch → null on parse error` idiom; use this instead of
+ * scattering `let msg: any` + try/catch through 8 files.
+ */
+export function tryParseJsonLine(line: string): unknown | null {
+ try {
+ return JSON.parse(line);
+ } catch {
+ return null;
+ }
+}
diff --git a/src/daemon/src/inbox/projection.ts b/src/daemon/src/inbox/projection.ts
index 31a347c30..4fb0ac7c7 100644
--- a/src/daemon/src/inbox/projection.ts
+++ b/src/daemon/src/inbox/projection.ts
@@ -10,7 +10,7 @@
* buckets sorted by most-recent activity. The summary is metadata only — it
* never carries message bodies; the agent pulls those with `alook inbox pull`.
*
- * Generic agent-backend abstraction (host-neutral).
+ * Generic daemon-side abstraction (host-neutral).
*/
export interface InboxMessage {
@@ -119,8 +119,11 @@ function messageSeq(message: InboxMessage | undefined): number | undefined {
return Math.floor(message.seq);
}
+/** How many chars of a message id form the inbox's compact `messageId#…` display. */
+const MESSAGE_ID_SHORT_LEN = 8;
+
function shortMessageId(value: string): string {
- return value.slice(0, 8);
+ return value.slice(0, MESSAGE_ID_SHORT_LEN);
}
function normalizeSenderType(value: string | undefined): "human" | "agent" | "system" | undefined {
diff --git a/src/daemon/src/index.ts b/src/daemon/src/index.ts
index dc38b7cd3..544d4152e 100644
--- a/src/daemon/src/index.ts
+++ b/src/daemon/src/index.ts
@@ -1,5 +1,5 @@
/**
- * Public entry point for the agent-backend layer.
+ * Public entry point for the daemon's driver layer.
*
* Typical use:
* import { getDriver, createChildProcessRuntimeSession } from "@alook/daemon";
diff --git a/src/daemon/src/manager/managerRuntime.ts b/src/daemon/src/manager/managerRuntime.ts
index d1ab27ada..c64f3ad4c 100644
--- a/src/daemon/src/manager/managerRuntime.ts
+++ b/src/daemon/src/manager/managerRuntime.ts
@@ -23,7 +23,9 @@ import {
import type { Driver, LaunchContext, SdkDriverDeps } from "../types.js";
import type { RuntimeConfig } from "../runtimeConfig.js";
import { createChildProcessRuntimeSession, type ChildProcessRuntimeSession } from "../runtime/runtimeSession.js";
+import { SESSION_STOP_GRACE_MS } from "../runtime/killTree.js";
import { SdkManagedSession } from "../runtime/sdkManagedSession.js";
+import { DEFAULT_CLI_CONFIG } from "../drivers/cliTransport.js";
import { createLogger, type Logger } from "../logger.js";
import { nowLocalISO } from "../util/localTime.js";
@@ -208,6 +210,9 @@ export interface TimelineRecorder {
/** Max UTF-8 byte budget for `thinking` text in the audit log. */
const THINKING_MAX_BYTES = 4096;
+/** Max length of a runtime-stderr line the daemon logs verbatim (with an ellipsis when cut). */
+const STDERR_LOG_MAX_LEN = 2000;
+
/**
* Max UTF-16 code units for a tool_call's `target` field. The wire schema
* caps `target` at 240 (see `AuditLogToolCallPayloadSchema`) and Zod's
@@ -370,9 +375,11 @@ function pickFallthroughTarget(input: unknown): string | undefined {
* echo, `bash -lc "alook …"` — the outer shell is real work) is user
* intent and must surface.
*/
+const ALOOK_SHELL_INVOCATION_RE = new RegExp(`^${DEFAULT_CLI_CONFIG.cliName}(\\s|$)`);
+
export function isAlookShellInvocation(command: string | undefined): boolean {
if (!command) return false;
- return /^alook(\s|$)/.test(command.trimStart());
+ return ALOOK_SHELL_INVOCATION_RE.test(command.trimStart());
}
/**
@@ -667,7 +674,7 @@ export class AgentProcessManager {
async stop(agentId: string): Promise<void> {
const session = this.sessions.get(agentId);
if (!session) return;
- await Promise.resolve(session.stop({ reason: "requested", forceAfterMs: 5_000 }));
+ await Promise.resolve(session.stop({ reason: "requested", forceAfterMs: SESSION_STOP_GRACE_MS }));
this.sessions.delete(agentId);
}
@@ -676,7 +683,11 @@ export class AgentProcessManager {
clearInterval(this.tickTimer);
this.tickTimer = null;
}
- await Promise.all([...this.sessions.values()].map((s) => Promise.resolve(s.stop({ reason: "shutdown" }))));
+ await Promise.all(
+ [...this.sessions.values()].map((s) =>
+ Promise.resolve(s.stop({ reason: "shutdown", forceAfterMs: SESSION_STOP_GRACE_MS })),
+ ),
+ );
this.sessions.clear();
}
@@ -788,7 +799,7 @@ export class AgentProcessManager {
case "stop":
case "terminate_stalled": {
const session = this.sessions.get(effect.agentId);
- void Promise.resolve(session?.stop({ reason: effect.type, forceAfterMs: 5_000 }));
+ void Promise.resolve(session?.stop({ reason: effect.type, forceAfterMs: SESSION_STOP_GRACE_MS }));
// The stop we just issued will make the underlying process emit its
// own `exit` shortly after — suppress that follow-up log so a single
// termination doesn't produce two contradictory "session ended" lines.
@@ -933,7 +944,7 @@ export class AgentProcessManager {
// the next incident is diagnosable.
session.on("stderr", (...args: unknown[]) => {
const raw = typeof args[0] === "string" ? args[0] : String(args[0] ?? "");
- const text = raw.length > 2000 ? raw.slice(0, 2000) + "…" : raw;
+ const text = raw.length > STDERR_LOG_MAX_LEN ? raw.slice(0, STDERR_LOG_MAX_LEN) + "…" : raw;
this.log.warn("runtime stderr", { agentId, runtime: driver.id, text });
});
// Child-process `error` (ENOENT etc.) — Node EE emits this before or in
@@ -1016,7 +1027,11 @@ export class AgentProcessManager {
sessionId: this.liveSessions.get(agentId) ?? null,
launchId: this.launchIds.get(agentId) ?? null,
});
- } catch { /* observational */ }
+ } catch (err) {
+ // Observational path (audit emit) — never re-throw, but leave a trail so
+ // a silent failure isn't invisible if the emitter starts throwing.
+ this.log.debug("audit emit failed (thinking)", { agentId, err: String(err) });
+ }
}
private onRuntimeEvent(agentId: string, e: unknown, runtimeId: string): void {
@@ -1054,7 +1069,9 @@ export class AgentProcessManager {
sessionId: this.liveSessions.get(agentId) ?? null,
launchId: this.launchIds.get(agentId) ?? null,
});
- } catch { /* observational */ }
+ } catch (err) {
+ this.log.debug("audit emit failed (tool_call)", { agentId, err: String(err) });
+ }
}
}
}
diff --git a/src/daemon/src/runtime/errorDiagnostics.ts b/src/daemon/src/runtime/errorDiagnostics.ts
index 9bbbdb6d9..42f6e7a5c 100644
--- a/src/daemon/src/runtime/errorDiagnostics.ts
+++ b/src/daemon/src/runtime/errorDiagnostics.ts
@@ -11,6 +11,27 @@
*/
import { createHash } from "crypto";
+/** Excerpt cap for the runtime-error diagnostic envelope's `runtime_error_message_excerpt`. */
+const ERROR_EXCERPT_MAX_BYTES = 4000;
+/** How many hex chars of the scrubbed-message SHA-256 form the `runtime_error_fingerprint`. */
+const ERROR_FINGERPRINT_LEN = 16;
+
+/**
+ * Buckets for the `runtime_error_message_length_bucket` telemetry dimension.
+ * Label and threshold live in the SAME entry on purpose: they must never drift
+ * apart (a bucket whose label says "1k-4k" while its boundary moved to 8k
+ * silently corrupts every dashboard built on this dimension). Deliberately
+ * NOT derived from `ERROR_EXCERPT_MAX_BYTES` — the excerpt cap is a payload
+ * budget and these are analytics boundaries; coupling them means tuning one
+ * silently relabels the other.
+ */
+const ERROR_LEN_BUCKETS: readonly { readonly under: number; readonly label: string }[] = [
+ { under: 1000, label: "<1k" },
+ { under: 4000, label: "1k-4k" },
+ { under: 16000, label: "4k-16k" },
+];
+const ERROR_LEN_OVERFLOW_LABEL = "16k+";
+
export type RuntimeErrorClass =
| "RateLimitError"
| "AuthError"
@@ -123,10 +144,10 @@ export function scrubRuntimeErrorDiagnosticText(value: string): string {
function messageLengthBucket(len: number): string {
if (len === 0) return "0";
- if (len < 1000) return "<1k";
- if (len < 4000) return "1k-4k";
- if (len < 16000) return "4k-16k";
- return "16k+";
+ for (const bucket of ERROR_LEN_BUCKETS) {
+ if (len < bucket.under) return bucket.label;
+ }
+ return ERROR_LEN_OVERFLOW_LABEL;
}
export interface RuntimeErrorDiagnosticEnvelope {
@@ -139,7 +160,7 @@ export function buildRuntimeErrorDiagnosticEnvelope(message: string): RuntimeErr
const runtimeErrorClass = classifyRuntimeError(message, httpStatus);
const runtimeErrorAction = classifyRuntimeErrorAction(message, runtimeErrorClass);
const scrubbed = scrubRuntimeErrorDiagnosticText(message);
- const fingerprint = createHash("sha256").update(scrubbed).digest("hex").slice(0, 16);
+ const fingerprint = createHash("sha256").update(scrubbed).digest("hex").slice(0, ERROR_FINGERPRINT_LEN);
const spanAttrs: Record<string, unknown> = {
turn_outcome: "failed",
@@ -151,12 +172,12 @@ export function buildRuntimeErrorDiagnosticEnvelope(message: string): RuntimeErr
runtime_error_fingerprint: fingerprint,
runtime_error_message_present: message.length > 0,
runtime_error_message_length_bucket: messageLengthBucket(message.length),
- runtime_error_message_truncated: scrubbed.length > 4000,
+ runtime_error_message_truncated: scrubbed.length > ERROR_EXCERPT_MAX_BYTES,
};
if (httpStatus !== null) spanAttrs.runtime_error_http_status = httpStatus;
return {
spanAttrs,
- eventAttrs: { ...spanAttrs, runtime_error_message_excerpt: scrubbed.slice(0, 4000) },
+ eventAttrs: { ...spanAttrs, runtime_error_message_excerpt: scrubbed.slice(0, ERROR_EXCERPT_MAX_BYTES) },
};
}
diff --git a/src/daemon/src/runtime/killTree.ts b/src/daemon/src/runtime/killTree.ts
index d22eb8e98..f28c49e2c 100644
--- a/src/daemon/src/runtime/killTree.ts
+++ b/src/daemon/src/runtime/killTree.ts
@@ -18,7 +18,22 @@
import { spawn, type ChildProcess } from "child_process";
const POLL_MS = 100;
-const DEFAULT_GRACE_MS = 2000;
+/**
+ * Standard grace before SIGKILL when the manager stops a running session.
+ * Every session-level stop path (`ManagedSession.stop`, `SdkManagedSession.stop`,
+ * `ChildProcessRuntimeSession.stop`'s fallback) shares this so the "how long
+ * before we kill it hard" answer is one number, not three drifting ones.
+ *
+ * MUST stay strictly below `daemonStart.ts`'s `STOP_GRACE_MS` (the window
+ * `alook daemon stop` gives the DAEMON before SIGKILLing it). The daemon's
+ * SIGTERM handler awaits `manager.stopAll()`, which awaits these per-session
+ * kills — so if the two windows were equal, an agent CLI that ignores SIGTERM
+ * would still be inside its own grace when the outer SIGKILL lands, killing
+ * the daemon before it ever escalates to SIGKILL on the child. The child is
+ * detached (its own process group), so it would survive as an orphan.
+ */
+export const SESSION_STOP_GRACE_MS = 2000;
+const DEFAULT_GRACE_MS = SESSION_STOP_GRACE_MS;
const isPosix = process.platform !== "win32";
export interface AgentSpawnOptions {
diff --git a/src/daemon/src/runtime/runtimeSession.ts b/src/daemon/src/runtime/runtimeSession.ts
index 641594e9e..88e0c1715 100644
--- a/src/daemon/src/runtime/runtimeSession.ts
+++ b/src/daemon/src/runtime/runtimeSession.ts
@@ -12,7 +12,7 @@
import { EventEmitter } from "events";
import type { ChildProcess } from "child_process";
import type { Driver, LaunchContext, StdinMode } from "../types.js";
-import { killProcessTree } from "./killTree.js";
+import { killProcessTree, SESSION_STOP_GRACE_MS } from "./killTree.js";
/**
* A flattened, daemon-facing description of how a runtime behaves, derived
@@ -136,7 +136,7 @@ export class ChildProcessRuntimeSession {
this.requestedStopReason = opts?.reason;
const pid = proc.pid;
if (pid) {
- await killProcessTree(pid, { graceMs: opts?.forceAfterMs ?? 2000 });
+ await killProcessTree(pid, { graceMs: opts?.forceAfterMs ?? SESSION_STOP_GRACE_MS });
} else {
proc.kill(opts?.signal ?? "SIGTERM");
}
diff --git a/src/daemon/src/runtime/sdkRuntimeSession.ts b/src/daemon/src/runtime/sdkRuntimeSession.ts
index 4719bdc4f..7e112f7ba 100644
--- a/src/daemon/src/runtime/sdkRuntimeSession.ts
+++ b/src/daemon/src/runtime/sdkRuntimeSession.ts
@@ -32,7 +32,16 @@ export interface SdkSessionHandle {
}
/** How long, and how often, to poll `isStreaming` before giving up and
- * steering instead of prompting a still-busy session. */
+ * steering instead of prompting a still-busy session.
+ *
+ * `IDLE_PROMPT_RETRY_MS = 25` is short enough that a session which finishes
+ * within one turn boundary (~100-300ms) is caught on the first or second
+ * poll, and small enough that the busy-wait cost is negligible.
+ * `IDLE_PROMPT_MAX_WAIT_MS = 1000` is the ceiling before we accept the
+ * session is "genuinely still working" and fall through to `steer` — anything
+ * higher measurably delays first-token latency without changing outcomes in
+ * the traces we've captured.
+ */
const IDLE_PROMPT_RETRY_MS = 25;
const IDLE_PROMPT_MAX_WAIT_MS = 1000;
diff --git a/src/daemon/src/server/wsControlChannel.ts b/src/daemon/src/server/wsControlChannel.ts
index dda4d9480..856e5dea9 100644
--- a/src/daemon/src/server/wsControlChannel.ts
+++ b/src/daemon/src/server/wsControlChannel.ts
@@ -40,6 +40,15 @@ export type { WebSocketLike, WebSocketFactory } from "./contract.js";
export type ControlChannelStatus = "idle" | "connecting" | "open" | "reconnecting" | "closed";
+/** Heartbeat: how often we ping the server WebSocket. */
+const DEFAULT_PING_INTERVAL_MS = 15_000;
+/** Heartbeat: how long we wait for a pong before declaring the socket dead. */
+const DEFAULT_PONG_TIMEOUT_MS = 30_000;
+/** Reconnect: initial backoff after a drop, doubling each attempt up to the max. */
+const DEFAULT_RECONNECT_BASE_MS = 500;
+/** Reconnect: ceiling on the exponential backoff. */
+const DEFAULT_RECONNECT_MAX_MS = 30_000;
+
export interface WsControlChannelOpts {
url: string;
/** Auth headers (e.g. Authorization, X-Agent-Id) — host-supplied. */
@@ -325,7 +334,7 @@ export class WsControlChannel implements HostControlChannel {
ws.on("message", (data: unknown) => this.onMessage(data));
ws.on("pong", () => {
this.attempt = 0;
- this.pongDeadline = this.now() + (this.opts.heartbeat?.pongTimeoutMs ?? 30_000);
+ this.pongDeadline = this.now() + (this.opts.heartbeat?.pongTimeoutMs ?? DEFAULT_PONG_TIMEOUT_MS);
this.log.debug("heartbeat pong");
});
ws.on("close", (code?: number, reason?: unknown) => this.onSocketClosed(code, reason));
@@ -385,8 +394,8 @@ export class WsControlChannel implements HostControlChannel {
}
private scheduleReconnect(): void {
- const base = this.opts.reconnect?.baseMs ?? 500;
- const max = this.opts.reconnect?.maxMs ?? 30_000;
+ const base = this.opts.reconnect?.baseMs ?? DEFAULT_RECONNECT_BASE_MS;
+ const max = this.opts.reconnect?.maxMs ?? DEFAULT_RECONNECT_MAX_MS;
const maxAttempts = this.opts.reconnect?.maxAttempts ?? Infinity;
if (this.attempt >= maxAttempts) {
this.statusValue = "closed";
@@ -404,8 +413,8 @@ export class WsControlChannel implements HostControlChannel {
}
private startHeartbeat(): void {
- const interval = this.opts.heartbeat?.pingIntervalMs ?? 15_000;
- const timeout = this.opts.heartbeat?.pongTimeoutMs ?? 30_000;
+ const interval = this.opts.heartbeat?.pingIntervalMs ?? DEFAULT_PING_INTERVAL_MS;
+ const timeout = this.opts.heartbeat?.pongTimeoutMs ?? DEFAULT_PONG_TIMEOUT_MS;
this.pongDeadline = this.now() + timeout;
this.pingTimer = setInterval(() => {
if (this.now() > this.pongDeadline) {
diff --git a/src/daemon/src/types.ts b/src/daemon/src/types.ts
index 5098a6d08..b8391f4b3 100644
--- a/src/daemon/src/types.ts
+++ b/src/daemon/src/types.ts
@@ -1,5 +1,5 @@
/**
- * Core types for the agent-backend ("driver") layer.
+ * Core types for the daemon's driver layer.
*
* A *driver* adapts one AI coding runtime (Claude Code, Codex, Gemini, Kimi,
* Pi, …) to a single uniform interface the daemon drives. The daemon never
@@ -86,6 +86,30 @@ export interface DriverModel {
*/
export type BusyDeliveryMode = "direct" | "gated" | "none";
+/**
+ * Declarative description of which `RuntimeConfig` fields a driver actually
+ * consumes at launch. Enables the platform to render accurate per-driver
+ * config surfaces and (in a follow-up) warn on ignored fields.
+ *
+ * `sessionResumeMode`:
+ * - `by-id`: resume the specific `sessionId` the caller asked for.
+ * - `most-recent`: driver has no by-id resume — falls back to the CLI's
+ * "continue most recent" (see AntigravityDriver).
+ * - `none`: no resume support at all.
+ *
+ * `model` is intentionally omitted here because every driver either uses the
+ * model field or explicitly suppresses it; the flag would be trivially true
+ * for all drivers except antigravity — a special case documented in comments
+ * on that driver's `capabilities` const.
+ */
+export interface DriverCapabilities {
+ readonly reasoningEffort: boolean;
+ readonly fastMode: boolean;
+ readonly disallowedTools: boolean;
+ readonly command: boolean;
+ readonly sessionResumeMode: "by-id" | "most-recent" | "none";
+}
+
/* ------------------------------------------------------------------ */
/* Normalized runtime events */
/* ------------------------------------------------------------------ */
@@ -267,6 +291,9 @@ export interface Driver {
/** True if the runtime takes the standing prompt natively (vs. inline). */
readonly supportsNativeStandingPrompt?: boolean;
+ /** Which `RuntimeConfig` fields this driver actually consumes at launch. */
+ readonly capabilities: DriverCapabilities;
+
/** Per-turn runtimes only: terminate the process when the turn ends. */
readonly terminateProcessOnTurnEnd?: boolean;
/** Persistent runtimes only: close stdin (rather than keep-alive) on turn end. */
diff --git a/src/daemon/src/version.test.ts b/src/daemon/src/version.test.ts
new file mode 100644
index 000000000..f35d081c2
--- /dev/null
+++ b/src/daemon/src/version.test.ts
@@ -0,0 +1,14 @@
+import { describe, it, expect } from "vitest";
+import { getDaemonClientInfo, readDaemonVersion } from "./version";
+
+describe("getDaemonClientInfo", () => {
+ it("returns the daemon's real name and package.json version", () => {
+ const info = getDaemonClientInfo();
+ expect(info.name).toBe("alook-daemon");
+ // Version is whatever `readDaemonVersion()` reports at test time — we
+ // don't assert a specific string (that would rot at every version bump),
+ // only that the two shapes agree.
+ expect(info.version).toBe(readDaemonVersion());
+ expect(info.version.length).toBeGreaterThan(0);
+ });
+});
diff --git a/src/daemon/src/version.ts b/src/daemon/src/version.ts
new file mode 100644
index 000000000..c481d5ee3
--- /dev/null
+++ b/src/daemon/src/version.ts
@@ -0,0 +1,37 @@
+/**
+ * Daemon version + client-info helpers.
+ *
+ * These are read from `@alook/daemon`'s own `package.json` (the file loaded
+ * via `createRequire` at `../package.json`, i.e. this workspace's package
+ * manifest). Everything on the wire that identifies the daemon to a remote
+ * runtime CLI (Kimi's `initialize.client`, Codex's `initialize.clientInfo`)
+ * flows through `getDaemonClientInfo()` so nobody hand-types the pre-alook
+ * daemon-identity strings anymore.
+ */
+import { createRequire } from "module";
+
+const requireFromHere = createRequire(import.meta.url);
+
+export function readDaemonVersion(): string {
+ try {
+ const pkg = requireFromHere("../package.json") as { version?: string };
+ return pkg.version ?? "";
+ } catch {
+ return "";
+ }
+}
+
+export interface DaemonClientInfo {
+ name: string;
+ version: string;
+}
+
+/**
+ * Identity the daemon reports to a remote runtime CLI's `initialize` frame.
+ * Read the version at call-time so bumping `package.json` doesn't require a
+ * daemon restart to update in-flight identify frames (there aren't any right
+ * now, but the freshness is essentially free).
+ */
+export function getDaemonClientInfo(): DaemonClientInfo {
+ return { name: "alook-daemon", version: readDaemonVersion() };
+}