Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

daemon(drivers): fix codex/cursor drivers, shim, $ALOOK_CLI, runtime whitelist, reset-audit dedup

Gus2b92193c5532
diff --git a/src/daemon/src/cli/daemonStart.ts b/src/daemon/src/cli/daemonStart.ts
index 322b6cf5d..a8ab6b8db 100644
--- a/src/daemon/src/cli/daemonStart.ts
+++ b/src/daemon/src/cli/daemonStart.ts
@@ -13,7 +13,7 @@ import { homedir } from "os";
import { WebSocket } from "ws";
import { createDaemon } from "../daemon/createDaemon.js";
import type { DaemonStatusSnapshot } from "../util/statusFile.js";
-import { getDriver } from "../drivers/index.js";
+import { getDriver, listRuntimeIds } from "../drivers/index.js";
import { resolveAlookCliPathWithFallback, detectRuntimes, type RuntimeInfo } from "../discovery.js";
import { createLogger } from "../logger.js";
import { UnknownRuntimeError } from "../manager/agentRouter.js";
@@ -633,13 +633,18 @@ export async function daemonStart(opts: DaemonStartOpts): Promise<void> {
// and surface as bot_runtime_missing + runtime_not_available.
driverFor: (_agentId, runtimeConfig) => {
const requested = runtimeConfig?.runtime;
- const known: string[] = runtimeReport.map((r) => r.id);
+ // Validate against the FULL registry, NOT the advertised subset:
+ // `runtimeReport`/`detectRuntimes` now advertises only SELECTABLE_RUNTIMES
+ // (what a user may pick when creating a bot), but a bot created BEFORE a
+ // runtime was hidden must still resolve its driver on wake (hide, not
+ // delete). "Can this run" (registry) and "can a user select it"
+ // (advertised) are different questions — this gate is the former.
+ const known: string[] = listRuntimeIds();
if (!requested || !known.includes(requested)) {
throw new UnknownRuntimeError(requested, healthyRuntimeIds);
}
- // `known` is derived from listRuntimeIds() via detectRuntimes(), so
- // `requested` (checked to be in `known` above) is guaranteed to be a
- // valid RuntimeId — cast to satisfy the typed factory map.
+ // `requested` was just checked to be in the registry, so it's a valid
+ // RuntimeId — cast to satisfy the typed factory map.
return getDriver(requested as Parameters<typeof getDriver>[0]);
},
capabilities: CAPABILITIES,
diff --git a/src/daemon/src/discovery.test.ts b/src/daemon/src/discovery.test.ts
index 559d4cfe0..8a5b7639f 100644
--- a/src/daemon/src/discovery.test.ts
+++ b/src/daemon/src/discovery.test.ts
@@ -10,6 +10,11 @@ import {
detectRuntimes,
getAvailableRuntimes,
} from "./discovery";
+import { listRuntimeIds, getDriver } from "./drivers/index";
+
+// The advertised (selectable) set — kept as a policy in discovery.ts, so assert
+// against the literal expectation here rather than importing a private const.
+const EXPECTED_SELECTABLE = ["claude", "codex", "opencode", "pi", "cursor"];
const tmpDirs: string[] = [];
function mkTmp(): string {
@@ -170,6 +175,31 @@ describe("detectRuntimes", () => {
}
}
});
+
+ it("advertises ONLY the selectable runtimes — hidden ones are not offered", () => {
+ const advertised = runtimes.map((r) => r.id).sort();
+ expect(advertised).toEqual([...EXPECTED_SELECTABLE].sort());
+ // The hidden drivers exist in the registry but must not be advertised.
+ for (const hidden of ["antigravity", "copilot", "gemini", "kimi"]) {
+ expect(advertised).not.toContain(hidden);
+ }
+ });
+});
+
+describe("driver allowlist (hide, not delete)", () => {
+ it("the advertised set is a strict subset of the full registry", () => {
+ const all = listRuntimeIds();
+ for (const id of EXPECTED_SELECTABLE) expect(all).toContain(id);
+ expect(EXPECTED_SELECTABLE.length).toBeLessThan(all.length);
+ });
+
+ it("getDriver STILL resolves a hidden runtime — existing bots on it keep working on resume", () => {
+ // The whole point of hide-not-delete: a bot created on gemini/kimi/etc.
+ // before the shrink must still get a driver when it wakes.
+ for (const hidden of ["antigravity", "copilot", "gemini", "kimi"]) {
+ expect(() => getDriver(hidden)).not.toThrow();
+ }
+ });
});
describe("getAvailableRuntimes", () => {
diff --git a/src/daemon/src/discovery.ts b/src/daemon/src/discovery.ts
index 3200fee52..d66abbd65 100644
--- a/src/daemon/src/discovery.ts
+++ b/src/daemon/src/discovery.ts
@@ -10,6 +10,17 @@ import { fileURLToPath } from "url";
import { getDriver, listRuntimeIds, type RuntimeId } from "./drivers/index.js";
import type { ProbeResult } from "./types.js";
+/**
+ * Runtimes offered for NEW bot creation. A registered driver NOT in this set
+ * stays fully functional (getDriver resolves it, existing bots keep running) —
+ * it's just not advertised, so it can't be picked in the create-bot UI/API.
+ * This is a POLICY (what's open to selection), deliberately kept separate from
+ * the driver registry (what exists) in drivers/index.ts. Filtering happens at
+ * the single advertise point, `detectRuntimes`.
+ * Hidden 2026-08-05 (Gus): antigravity/copilot/gemini/kimi unverified.
+ */
+const SELECTABLE_RUNTIMES: ReadonlySet<RuntimeId> = new Set(["claude", "codex", "opencode", "pi", "cursor"]);
+
/* ------------------------------------------------------------------ */
/* Agent CLI path resolution */
/* ------------------------------------------------------------------ */
@@ -110,7 +121,10 @@ export interface RuntimeInfo {
* plans/community-machine-presence-fix.md.
*/
export async function detectRuntimes(): Promise<RuntimeInfo[]> {
- const ids = listRuntimeIds();
+ // Advertise only the selectable subset (SELECTABLE_RUNTIMES). Hidden runtimes
+ // stay registered (getDriver resolves them for existing bots on resume) but
+ // are never advertised, so the create-bot UI + API won't offer/accept them.
+ const ids = listRuntimeIds().filter((id) => SELECTABLE_RUNTIMES.has(id));
const results: RuntimeInfo[] = [];
const nowIso = new Date().toISOString();
diff --git a/src/daemon/src/drivers/cliTransport.test.ts b/src/daemon/src/drivers/cliTransport.test.ts
index 2ec102342..8c56611ef 100644
--- a/src/daemon/src/drivers/cliTransport.test.ts
+++ b/src/daemon/src/drivers/cliTransport.test.ts
@@ -46,6 +46,10 @@ function baseCtx(workingDirectory: string, overrides: Partial<LaunchContext> = {
prompt: "",
credentialProxy: { broker: broker(), proxyUrl: "http://127.0.0.1:9/proxy", runnerKey: "sk_agent_test", capabilities: ["send", "read"] },
config: {},
+ // These transport tests aren't exercising the agent-CLI shim (no
+ // agentCliPath), so opt into the mock path — otherwise prepareCliTransport
+ // now fails loud on a real launch with no resolvable host CLI.
+ mockCliTransport: true,
...overrides,
};
}
@@ -210,6 +214,44 @@ describe("prepareCliTransport — layered spawn env", () => {
expect(fs.lstatSync(link).isSymbolicLink()).toBe(true);
});
+ it("defaults hostCliPath from ctx.agentCliPath — the shim works with the default cli config (no per-driver plumbing)", async () => {
+ const wd = mkTmp();
+ const host = path.join(wd, "agent-cli.js");
+ fs.writeFileSync(host, "#!/usr/bin/env node\n", { mode: 0o755 });
+ // No explicit cli.hostCliPath; agentCliPath on the ctx is the only source —
+ // this is the path codex/cursor/opencode/etc. now get for free.
+ const { stateDir } = await prepareCliTransport(
+ baseCtx(wd, { agentCliPath: host, mockCliTransport: false }),
+ {},
+ undefined,
+ "linux",
+ );
+ const link = path.join(stateDir, "bin", "alook");
+ expect(fs.lstatSync(link).isSymbolicLink()).toBe(true);
+ expect(fs.realpathSync(link)).toBe(fs.realpathSync(host));
+ });
+
+ it("FAILS LOUD on a real launch with no resolvable host CLI (not a silent empty bin)", async () => {
+ // The bug shape: a real launch (not mock) whose agentCliPath didn't resolve.
+ // Must throw, not silently leave an empty bin that PATH-falls-through to the
+ // host `alook` (which lacks the agent subcommands).
+ await expect(
+ prepareCliTransport(baseCtx(mkTmp(), { agentCliPath: undefined, mockCliTransport: false }), {}, undefined, "linux"),
+ ).rejects.toThrow(/no host CLI path/);
+ });
+
+ it("mock launch (mockCliTransport) stays silent — bin dir, no link, no throw", async () => {
+ const { stateDir } = await prepareCliTransport(
+ baseCtx(mkTmp(), { agentCliPath: undefined, mockCliTransport: true }),
+ {},
+ undefined,
+ "linux",
+ );
+ const binDir = path.join(stateDir, "bin");
+ expect(fs.existsSync(binDir)).toBe(true);
+ expect(fs.existsSync(path.join(binDir, "alook"))).toBe(false);
+ });
+
it("revokes the agent's previous voucher before minting a new one on respawn", async () => {
// Without this, every stop+respawn of the same agent leaves the OLD
// voucher registered forever — an unbounded leak in the broker's map,
diff --git a/src/daemon/src/drivers/cliTransport.ts b/src/daemon/src/drivers/cliTransport.ts
index c7ad694b0..85faeef1c 100644
--- a/src/daemon/src/drivers/cliTransport.ts
+++ b/src/daemon/src/drivers/cliTransport.ts
@@ -141,9 +141,33 @@ export async function prepareCliTransport(
// it from cwd picks it up, with no driver-specific plumbing required.
if (ctx.standingPrompt) writeAgentFile(ctx.workingDirectory, ctx.standingPrompt);
+ // Resolve the host CLI the agent-facing `cliName` links to. A caller may set
+ // `cli.hostCliPath` explicitly (claude/pi do); otherwise default it from
+ // `ctx.agentCliPath` — the daemon threads the resolved agent-CLI path there
+ // for EVERY launch, so this one fallback gives all child-process drivers the
+ // shim without each repeating claude's construction (the omission that left
+ // codex/cursor/opencode/… invoking the HOST `alook`, which lacks the agent
+ // subcommands). Explicit `cli.hostCliPath` still wins.
+ const hostCliPath = cli.hostCliPath ?? ctx.agentCliPath;
+
+ // Fail loud when a REAL launch can't resolve a host CLI. Silently leaving an
+ // empty bin dir lets the agent's `alook` fall through to the host CLI on
+ // PATH — the agent looks like it runs but uses the wrong binary, which is
+ // very hard to trace. Only an explicit `mockCliTransport` opt-in may skip the
+ // shim (test harnesses); the ABSENCE of a path is the bug shape, so it can't
+ // double as the mock signal.
+ if (!hostCliPath && !ctx.mockCliTransport) {
+ throw new Error(
+ "prepareCliTransport: no host CLI path — set ctx.agentCliPath (or cli.hostCliPath) " +
+ "so the agent's `alook` resolves to the injected agent CLI, not the host binary. " +
+ "For an intentional no-CLI test launch, set ctx.mockCliTransport = true.",
+ );
+ }
+
// Decouple the agent-facing `cliName` from the host binary via a filesystem
// link in a PATH-prepended bin dir (symlink on POSIX, .cmd shim on Windows).
- const binDir = writeCliLink(stateDir, cli.cliName, cli.hostCliPath, platform);
+ // With no hostCliPath (mock launch) writeCliLink creates only the bin dir.
+ const binDir = writeCliLink(stateDir, cli.cliName, hostCliPath, platform);
// Zero-trust credential handoff (no plaintext fallback). The broker mints a
// per-launch voucher (writing the 0600 voucher file and keeping the real key);
@@ -226,6 +250,11 @@ export async function prepareCliTransport(
stateHome,
agentId: ctx.agentId,
cliName: cli.cliName,
+ // Absolute path to the injected shim (present iff we wrote a link, i.e.
+ // hostCliPath resolved). `<PREFIX>_CLI` points here so the agent calls
+ // the CLI by absolute path, never a bare name PATH could resolve to a
+ // host binary. On a mock launch (no shim) it stays undefined → bare name.
+ cliPath: hostCliPath ? path.join(binDir, cli.cliName) : undefined,
serverUrl: ctx.config.serverUrl,
capabilities,
launchId: ctx.launchId,
diff --git a/src/daemon/src/drivers/codex.test.ts b/src/daemon/src/drivers/codex.test.ts
index 25100479a..3a1bec5fb 100644
--- a/src/daemon/src/drivers/codex.test.ts
+++ b/src/daemon/src/drivers/codex.test.ts
@@ -39,6 +39,7 @@ function baseCtx(): LaunchContext {
capabilities: ["send", "read"],
},
config: {},
+ mockCliTransport: true,
};
}
@@ -59,3 +60,179 @@ describe("CodexDriver initialize payload", () => {
expect(initPayload.params.clientInfo).toEqual({ name: "alook-daemon", version: readDaemonVersion() });
});
});
+
+// The `thread/start` (or resume) RESULT line carries the new thread id and is
+// what the normalizer adopts as the session — feeding it to parseLine is what
+// triggers the deferred initial-prompt delivery.
+function threadStartResult(threadId: string): string {
+ return JSON.stringify({ jsonrpc: "2.0", id: 2, result: { thread: { id: threadId } } });
+}
+// The `thread/started` NOTIFICATION — Codex emits this too, so parseLine sees a
+// SECOND session_init for the same thread.
+function threadStartedNotif(threadId: string): string {
+ return JSON.stringify({ jsonrpc: "2.0", method: "thread/started", params: { thread: { id: threadId } } });
+}
+
+function stdinWrites(proc: unknown): string[] {
+ const stdin = (proc as { stdin: { write: ReturnType<typeof vi.fn> } }).stdin;
+ return stdin.write.mock.calls.map((c) => c[0] as string);
+}
+function turnStarts(writes: string[]): any[] {
+ return writes
+ .map((w) => JSON.parse(w.trim()))
+ .filter((m) => m.method === "turn/start");
+}
+
+describe("CodexDriver initial-prompt delivery", () => {
+ it("submits the initial prompt as a turn/start once the thread id is adopted", async () => {
+ const driver = new CodexDriver();
+ const ctx = baseCtx(); // prompt: "hi"
+ const { process: proc } = await driver.spawn(ctx);
+ await Promise.resolve(); // flush handshake microtask
+
+ // Before the thread is adopted, no turn/start yet — only the handshake.
+ expect(turnStarts(stdinWrites(proc))).toHaveLength(0);
+
+ // Feed the thread/start result → thread adopted → prompt delivered.
+ driver.parseLine(threadStartResult("th_abc"));
+
+ const turns = turnStarts(stdinWrites(proc));
+ expect(turns).toHaveLength(1);
+ expect(turns[0].params.threadId).toBe("th_abc");
+ expect(turns[0].params.input).toEqual([{ type: "text", text: "hi" }]);
+ });
+
+ it("delivers the prompt exactly once despite the double session_init (result + thread/started)", async () => {
+ const driver = new CodexDriver();
+ const { process: proc } = await driver.spawn(baseCtx());
+ await Promise.resolve();
+
+ driver.parseLine(threadStartResult("th_abc")); // session_init #1
+ driver.parseLine(threadStartedNotif("th_abc")); // session_init #2 (same thread)
+
+ expect(turnStarts(stdinWrites(proc))).toHaveLength(1);
+ });
+
+ it("delivers the prompt on resume too (thread/resume result yields session_init)", async () => {
+ const driver = new CodexDriver();
+ const ctx = baseCtx();
+ ctx.config = { sessionId: "th_prior" }; // resuming
+ const { process: proc } = await driver.spawn(ctx);
+ await Promise.resolve();
+
+ // resume result carries the (same) thread id.
+ driver.parseLine(threadStartResult("th_prior"));
+
+ const turns = turnStarts(stdinWrites(proc));
+ expect(turns).toHaveLength(1);
+ expect(turns[0].params.threadId).toBe("th_prior");
+ expect(turns[0].params.input).toEqual([{ type: "text", text: "hi" }]);
+ });
+
+ it("does not start a turn when the prompt is empty (a bare wake)", async () => {
+ const driver = new CodexDriver();
+ const ctx = baseCtx();
+ ctx.prompt = " "; // whitespace-only → treated as no prompt
+ const { process: proc } = await driver.spawn(ctx);
+ await Promise.resolve();
+
+ driver.parseLine(threadStartResult("th_abc"));
+
+ expect(turnStarts(stdinWrites(proc))).toHaveLength(0);
+ });
+});
+
+// A JSON-RPC error response to thread/resume — the prior thread's rollout is gone.
+function missingRolloutError(): string {
+ return JSON.stringify({ jsonrpc: "2.0", id: 2, error: { message: "no rollout found for thread id th_prior" } });
+}
+function threadStarts(writes: string[]): any[] {
+ return writes.map((w) => JSON.parse(w.trim())).filter((m) => m.method === "thread/start");
+}
+
+describe("CodexDriver missing-rollout resume recovery", () => {
+ it("on a 'no rollout found' resume error, re-issues a FRESH thread/start (no threadId) and swallows the error", async () => {
+ const driver = new CodexDriver();
+ const ctx = baseCtx();
+ ctx.config = { sessionId: "th_prior" }; // resuming a now-dead thread
+ const { process: proc } = await driver.spawn(ctx);
+ await Promise.resolve(); // flush handshake (writes thread/resume)
+
+ const returned = driver.parseLine(missingRolloutError());
+
+ // The resume error is swallowed — not surfaced to the manager as a fault.
+ expect(returned.some((e: any) => e.kind === "error")).toBe(false);
+ // A fresh thread/start was issued, with NO threadId (fresh, not resume).
+ const starts = threadStarts(stdinWrites(proc));
+ expect(starts).toHaveLength(1);
+ expect(starts[0].params.threadId).toBeUndefined();
+ });
+
+ it("after the fallback fresh-thread's session_init, the held prompt is still delivered", async () => {
+ const driver = new CodexDriver();
+ const ctx = baseCtx();
+ ctx.config = { sessionId: "th_prior" };
+ const { process: proc } = await driver.spawn(ctx);
+ await Promise.resolve();
+
+ driver.parseLine(missingRolloutError()); // → fresh thread/start, prompt still pending
+ driver.parseLine(threadStartResult("th_fresh")); // fresh thread adopted
+
+ const turns = turnStarts(stdinWrites(proc));
+ expect(turns).toHaveLength(1);
+ expect(turns[0].params.threadId).toBe("th_fresh");
+ expect(turns[0].params.input).toEqual([{ type: "text", text: "hi" }]);
+ });
+
+ it("a successful resume does NOT trigger the fallback (no spurious fresh thread/start)", async () => {
+ const driver = new CodexDriver();
+ const ctx = baseCtx();
+ ctx.config = { sessionId: "th_prior" };
+ const { process: proc } = await driver.spawn(ctx);
+ await Promise.resolve();
+
+ // Resume succeeds → session_init for the resumed thread.
+ driver.parseLine(threadStartResult("th_prior"));
+
+ // No fallback thread/start — only the handshake's thread/resume happened.
+ expect(threadStarts(stdinWrites(proc))).toHaveLength(0);
+ // And the prompt was delivered on the resumed thread.
+ expect(turnStarts(stdinWrites(proc))).toHaveLength(1);
+ });
+});
+
+describe("CodexDriver encodeStdinMessage — turn/steer expectedTurnId", () => {
+ it("busy steer includes expectedTurnId = the active turn id (codex requires it)", () => {
+ const driver = new CodexDriver();
+ // Adopt a thread + observe a turn/started so the normalizer has both ids.
+ driver.parseLine(threadStartResult("th_1"));
+ driver.parseLine(JSON.stringify({ jsonrpc: "2.0", method: "turn/started", params: { threadId: "th_1", turn: { id: "turn_9" } } }));
+
+ const encoded = driver.encodeStdinMessage("hang on", "th_1", { mode: "busy" });
+ const msg = JSON.parse(encoded!);
+ expect(msg.method).toBe("turn/steer");
+ expect(msg.params.threadId).toBe("th_1");
+ expect(msg.params.expectedTurnId).toBe("turn_9");
+ expect(msg.params.input).toEqual([{ type: "text", text: "hang on" }]);
+ });
+
+ it("falls back to a fresh turn/start when there is no live turn to steer", () => {
+ const driver = new CodexDriver();
+ driver.parseLine(threadStartResult("th_1")); // thread but no active turn
+ const encoded = driver.encodeStdinMessage("hi", "th_1", { mode: "busy" });
+ const msg = JSON.parse(encoded!);
+ // No turn id → don't send an invalid steer; start a fresh turn instead.
+ expect(msg.method).toBe("turn/start");
+ expect(msg.params.expectedTurnId).toBeUndefined();
+ });
+
+ it("idle message is always a fresh turn/start (no expectedTurnId)", () => {
+ const driver = new CodexDriver();
+ driver.parseLine(threadStartResult("th_1"));
+ driver.parseLine(JSON.stringify({ jsonrpc: "2.0", method: "turn/started", params: { threadId: "th_1", turn: { id: "turn_9" } } }));
+ const encoded = driver.encodeStdinMessage("new topic", "th_1", { mode: "idle" });
+ const msg = JSON.parse(encoded!);
+ expect(msg.method).toBe("turn/start");
+ expect(msg.params.expectedTurnId).toBeUndefined();
+ });
+});
diff --git a/src/daemon/src/drivers/codex.ts b/src/daemon/src/drivers/codex.ts
index 88262f486..752958e77 100644
--- a/src/daemon/src/drivers/codex.ts
+++ b/src/daemon/src/drivers/codex.ts
@@ -69,6 +69,29 @@ export class CodexDriver implements Driver {
private requestId = 0;
/** Resolved Codex home root (CODEX_HOME or ~/.codex); set on spawn. */
private codexHomeRoot: string | null = null;
+ /**
+ * The spawned process, retained so the initial-prompt `turn/start` can be
+ * written once the thread id is adopted (see `parseLine`). Null until spawn.
+ */
+ private proc: SpawnResult["process"] | null = null;
+ /**
+ * The initial user message drained into `ctx.prompt` at spawn, held until the
+ * first `session_init` (thread adopted) lets us submit it as a `turn/start`.
+ * Codex can't deliver it in the spawn handshake like Claude does: `turn/start`
+ * needs a threadId, which only arrives in the `thread/start`|`thread/resume`
+ * RESPONSE. Cleared after the one-time submit (submit-once latch). Null when
+ * there is no prompt (a bare wake) — we don't start an empty turn.
+ */
+ private pendingInitialPrompt: string | null = null;
+ /**
+ * When spawn issued a `thread/resume`, the `thread/start` params to fall back
+ * to if that resume fails with "no rollout found" (the prior thread's rollout
+ * is gone). Null once we're not resuming, or once the fallback has fired. This
+ * powers the missing-rollout recovery in `parseLine`: re-issue a FRESH
+ * `thread/start` (no threadId) on the same live process, keeping
+ * `pendingInitialPrompt` so the fresh thread's `session_init` still delivers it.
+ */
+ private pendingResumeFallbackParams: Record<string, unknown> | null = null;
private nextRequestId(): number {
return ++this.requestId;
}
@@ -99,8 +122,18 @@ export class CodexDriver implements Driver {
env: spawnEnv,
shell: spec.shell,
});
+ this.proc = proc;
+ // Hold the initial user message until the thread id is adopted; `parseLine`
+ // submits it as a `turn/start` on the first `session_init`. Empty/whitespace
+ // (a bare wake with no message) → no pending prompt, so no empty turn.
+ const initialPrompt = ctx.prompt?.trim() ? ctx.prompt : null;
+ this.pendingInitialPrompt = initialPrompt;
- // Async handshake: initialize, then thread/start|resume with the prompt.
+ // Async handshake: initialize, then thread/start|resume. This ONLY sets up
+ // the thread — the user prompt is delivered later (see `parseLine`), because
+ // `turn/start` needs the threadId that arrives in this call's response. (The
+ // standing/system prompt is separate: it reaches Codex via the AGENTS.md
+ // that prepareCliTransport writes into the workdir, auto-read from cwd.)
queueMicrotask(() => {
proc.stdin?.write(
jsonRpcRequest(
@@ -112,44 +145,116 @@ export class CodexDriver implements Driver {
const f = resolveLaunchFieldsOrDefault(ctx.config.runtimeConfig);
const resuming = Boolean(ctx.config.sessionId);
- // The standing prompt reaches Codex via the AGENTS.md that
- // prepareCliTransport writes into the workdir (unified packing) —
- // Codex auto-reads it from cwd, no developerInstructions param needed.
- const params: Record<string, unknown> = {
+ // Fresh-thread params (no threadId) — used directly for a fresh spawn, and
+ // stashed as the resume fallback so a "no rollout found" resume can retry
+ // as a fresh thread (see parseLine).
+ const freshParams: Record<string, unknown> = {
cwd: ctx.workingDirectory,
approvalPolicy: "never",
sandbox: "danger-full-access",
sandbox_mode: "danger-full-access",
experimentalRawEvents: true,
};
- if (resuming) params.threadId = ctx.config.sessionId;
- if (f.model) params.model = f.model;
- if (f.reasoningEffort) params.config = { model_reasoning_effort: f.reasoningEffort };
- if (f.fastMode) params.serviceTier = "fast";
+ if (f.model) freshParams.model = f.model;
+ if (f.reasoningEffort) freshParams.config = { model_reasoning_effort: f.reasoningEffort };
+ if (f.fastMode) freshParams.serviceTier = "fast";
- proc.stdin?.write(
- jsonRpcRequest(resuming ? "thread/resume" : "thread/start", params, this.nextRequestId()) + "\n",
- );
+ if (resuming) {
+ this.pendingResumeFallbackParams = freshParams;
+ proc.stdin?.write(
+ jsonRpcRequest("thread/resume", { ...freshParams, threadId: ctx.config.sessionId }, this.nextRequestId()) + "\n",
+ );
+ } else {
+ proc.stdin?.write(jsonRpcRequest("thread/start", freshParams, this.nextRequestId()) + "\n");
+ }
});
return { process: proc };
}
+ /**
+ * Parse a stdout line AND, as a one-time side-effect, deliver the initial
+ * prompt. This is NOT a pure parser: on the FIRST `session_init` (the thread
+ * id is now known) it writes the held `pendingInitialPrompt` as a `turn/start`
+ * to stdin, then clears it (submit-once latch). This is where the initial user
+ * message actually reaches Codex — the spawn handshake only starts the thread.
+ *
+ * The latch also makes the double `session_init` harmless: `thread/start`
+ * emits one from its result and one from the `thread/started` notification, so
+ * without the latch we'd submit the prompt twice. Resume takes the same path
+ * (thread/resume's result also yields `session_init`), so no separate branch.
+ *
+ * SECOND side-effect — missing-rollout recovery: if a `thread/resume` fails
+ * with "no rollout found" (the prior thread's rollout is gone), Codex emits an
+ * `error` event and NO `session_init`. We re-issue a FRESH `thread/start` on
+ * the same live process and swallow the error so the manager doesn't fault the
+ * turn. `pendingInitialPrompt` is deliberately kept, so the fresh thread's
+ * `session_init` delivers it via the latch above. Without this, a stale
+ * sessionId wedges the bot: resume errors out, no turn ever runs.
+ */
parseLine(line: string): ParsedEvent[] {
- return this.eventNormalizer.normalizeLine(line);
+ const events = this.eventNormalizer.normalizeLine(line);
+
+ // Missing-rollout resume recovery — before any session_init is adopted.
+ if (this.pendingResumeFallbackParams && this.proc?.stdin && !this.proc.stdin.destroyed) {
+ const rolloutErr = events.find(
+ (e) => e.kind === "error" && isCodexMissingRolloutError(e.message),
+ );
+ if (rolloutErr) {
+ const fallback = this.pendingResumeFallbackParams;
+ this.pendingResumeFallbackParams = null;
+ // Fresh thread/start (no threadId). Keep pendingInitialPrompt so the new
+ // thread's session_init delivers it. Swallow the resume error so it's
+ // not surfaced as a runtime_error fault.
+ this.proc.stdin.write(jsonRpcRequest("thread/start", fallback, this.nextRequestId()) + "\n");
+ return events.filter((e) => e !== rolloutErr);
+ }
+ }
+
+ if (this.pendingInitialPrompt !== null && events.some((e) => e.kind === "session_init")) {
+ const threadId = this.eventNormalizer.currentSessionId;
+ // Defensive: the process is normally alive when its own stdout is being
+ // parsed, but guard the write so a mid-teardown line can't throw.
+ if (threadId && this.proc?.stdin && !this.proc.stdin.destroyed) {
+ this.proc.stdin.write(this.buildTurnStart(threadId, this.pendingInitialPrompt) + "\n");
+ this.pendingInitialPrompt = null;
+ }
+ }
+
+ // A successful thread adoption means resume didn't fail — drop the fallback.
+ if (events.some((e) => e.kind === "session_init")) {
+ this.pendingResumeFallbackParams = null;
+ }
+
+ return events;
}
get currentSessionId(): string | null {
return this.eventNormalizer.currentSessionId;
}
+ /** A `turn/start` RPC — the sole encoder for starting a fresh Codex turn. */
+ private buildTurnStart(threadId: string, text: string): string {
+ return jsonRpcRequest("turn/start", { threadId, input: [{ type: "text", text }] }, this.nextRequestId());
+ }
+
/** busy → `turn/steer` against the active turn; idle → fresh `turn/start`. */
encodeStdinMessage(text: string, sessionId: string | null, opts?: EncodeOpts): string | null {
const threadId = sessionId ?? this.eventNormalizer.currentSessionId;
if (!threadId) return null;
- const input = [{ type: "text", text }];
- const method = opts?.mode === "idle" ? "turn/start" : "turn/steer";
- return jsonRpcRequest(method, { threadId, input }, this.nextRequestId());
+ if (opts?.mode === "idle") return this.buildTurnStart(threadId, text);
+ // Steer the in-flight turn. Codex requires `expectedTurnId` = the active
+ // turn's id (from turn/started's params.turn.id); without it it rejects the
+ // steer with "missing field expectedTurnId". If we somehow have no live turn
+ // id (raced past turn/completed), fall back to a fresh turn/start rather than
+ // send an invalid steer.
+ const turnId = this.eventNormalizer.currentTurnId;
+ if (!turnId) return this.buildTurnStart(threadId, text);
+ return jsonRpcRequest(
+ "turn/steer",
+ { threadId, expectedTurnId: turnId, input: [{ type: "text", text }] },
+ this.nextRequestId(),
+ );
}
buildSystemPrompt(config: LaunchConfig): string {
diff --git a/src/daemon/src/drivers/codexEventNormalizer.test.ts b/src/daemon/src/drivers/codexEventNormalizer.test.ts
index 552efea35..9d262811e 100644
--- a/src/daemon/src/drivers/codexEventNormalizer.test.ts
+++ b/src/daemon/src/drivers/codexEventNormalizer.test.ts
@@ -67,3 +67,55 @@ describe("CodexEventNormalizer — tool_call/tool_output symmetry", () => {
expect((n as unknown as { turnState?: unknown }).turnState).toBeUndefined();
});
});
+
+describe("CodexEventNormalizer — turn id tracking (for turn/steer expectedTurnId)", () => {
+ it("captures params.turn.id on turn/started and exposes it via currentTurnId", () => {
+ const n = new CodexEventNormalizer();
+ expect(n.currentTurnId).toBeNull();
+ n.normalizeLine(notify("turn/started", { threadId: "th_1", turn: { id: "turn_abc", status: "inProgress" } }));
+ expect(n.currentTurnId).toBe("turn_abc");
+ });
+
+ it("clears the turn id on turn/completed (no live turn to steer after)", () => {
+ const n = new CodexEventNormalizer();
+ n.normalizeLine(notify("turn/started", { threadId: "th_1", turn: { id: "turn_abc" } }));
+ expect(n.currentTurnId).toBe("turn_abc");
+ n.normalizeLine(notify("turn/completed", { status: "completed" }));
+ expect(n.currentTurnId).toBeNull();
+ });
+
+ it("clears the turn id on an interrupted/failed turn too", () => {
+ const n = new CodexEventNormalizer();
+ n.normalizeLine(notify("turn/started", { threadId: "th_1", turn: { id: "turn_x" } }));
+ n.normalizeLine(notify("turn/completed", { status: "failed" }));
+ expect(n.currentTurnId).toBeNull();
+ });
+});
+
+describe("CodexEventNormalizer — session_init dedup (result + thread/started notification)", () => {
+ function result(id: string): string {
+ return JSON.stringify({ jsonrpc: "2.0", id: 2, result: { thread: { id } } });
+ }
+ it("emits session_init ONCE for a thread announced twice (result then notification)", () => {
+ const n = new CodexEventNormalizer();
+ const a = n.normalizeLine(result("th_1"));
+ const b = n.normalizeLine(notify("thread/started", { thread: { id: "th_1" } }));
+ expect(a.filter((e) => e.kind === "session_init")).toHaveLength(1);
+ expect(b.filter((e) => e.kind === "session_init")).toHaveLength(0); // deduped
+ // but the id is still adopted regardless of which arrived.
+ expect(n.currentSessionId).toBe("th_1");
+ });
+ it("emits session_init again for a DIFFERENT thread (fresh-thread fallback)", () => {
+ const n = new CodexEventNormalizer();
+ n.normalizeLine(result("th_1"));
+ const fresh = n.normalizeLine(result("th_2")); // e.g. missing-rollout fallback fresh thread
+ expect(fresh.filter((e) => e.kind === "session_init")).toHaveLength(1);
+ expect(n.currentSessionId).toBe("th_2");
+ });
+ it("adopts the id from the notification even when the result never emitted it (notification first)", () => {
+ const n = new CodexEventNormalizer();
+ const b = n.normalizeLine(notify("thread/started", { thread: { id: "th_x" } }));
+ expect(b.filter((e) => e.kind === "session_init")).toHaveLength(1);
+ expect(n.currentSessionId).toBe("th_x");
+ });
+});
diff --git a/src/daemon/src/drivers/codexEventNormalizer.ts b/src/daemon/src/drivers/codexEventNormalizer.ts
index a65548ed8..9a773c362 100644
--- a/src/daemon/src/drivers/codexEventNormalizer.ts
+++ b/src/daemon/src/drivers/codexEventNormalizer.ts
@@ -17,15 +17,52 @@ import { tryParseJsonLine } from "./utils.js";
export class CodexEventNormalizer {
private threadId: string | null = null;
+ /**
+ * The active turn's id, from `turn/started`'s `params.turn.id`. Codex requires
+ * it as `expectedTurnId` on a `turn/steer` (a busy-steer against the in-flight
+ * turn) — without it codex rejects the steer ("missing field expectedTurnId").
+ * Set on `turn/started`, cleared on `turn/completed`. Null when no turn is live
+ * (then a message is a fresh `turn/start`, which takes no expectedTurnId).
+ */
+ private turnId: string | null = null;
+ /**
+ * The threadId we've already emitted `session_init` for — dedups codex's
+ * double thread announcement (result + notification). See `adoptAndInit`.
+ */
+ private sessionInitEmittedFor: string | null = null;
get currentSessionId(): string | null {
return this.threadId;
}
+ /** The in-flight turn's id, or null when no turn is active. */
+ get currentTurnId(): string | null {
+ return this.turnId;
+ }
+
adoptThreadId(threadId: string | null): void {
this.threadId = threadId;
}
+ /**
+ * Emit `session_init` for `threadId` ONLY the first time this thread is seen.
+ * Codex announces a thread TWICE — the `thread/start` RESULT and the
+ * `thread/started` NOTIFICATION — both carrying the same id. Both must adopt
+ * the id (so `currentSessionId` is set no matter which arrives first), but
+ * only ONE should surface `session_init`: downstream consumers that RECORD on
+ * session_init (the timeline/reset-audit recorder) would otherwise log the
+ * event twice — the "two identical reset records for codex only" bug. Other
+ * runtimes emit session_init once, hence codex-only. The submit-once prompt
+ * latch never needed the duplicate; this dedups at the source.
+ */
+ private adoptAndInit(threadId: string): ParsedEvent[] {
+ const firstSight = threadId !== this.sessionInitEmittedFor;
+ this.threadId = threadId;
+ if (!firstSight) return [];
+ this.sessionInitEmittedFor = threadId;
+ return [{ kind: "session_init", sessionId: threadId }];
+ }
+
normalizeLine(line: string): ParsedEvent[] {
const msg = tryParseJsonLine(line) as any;
if (!msg) return [];
@@ -37,8 +74,7 @@ export class CodexEventNormalizer {
// Result of thread/start | thread/resume carries the thread id.
if (msg?.result?.thread?.id) {
- this.threadId = msg.result.thread.id;
- return [{ kind: "session_init", sessionId: this.threadId! }];
+ return this.adoptAndInit(msg.result.thread.id);
}
if (msg?.method) return this.handleNotification(msg.method, msg.params ?? {});
@@ -48,10 +84,12 @@ export class CodexEventNormalizer {
private handleNotification(method: string, params: any): ParsedEvent[] {
switch (method) {
case "thread/started":
- if (params?.thread?.id) this.threadId = params.thread.id;
- return this.threadId ? [{ kind: "session_init", sessionId: this.threadId }] : [];
+ return params?.thread?.id ? this.adoptAndInit(params.thread.id) : [];
case "turn/started":
+ // Capture the turn id — codex needs it back as `expectedTurnId` on a
+ // `turn/steer` against this turn (see CodexDriver.encodeStdinMessage).
+ if (params?.turn?.id) this.turnId = params.turn.id;
return [{ kind: "thinking", text: "" }];
case "item/reasoning/textDelta":
@@ -81,6 +119,8 @@ export class CodexEventNormalizer {
];
case "turn/completed":
+ // Turn is over — no live turn to steer against anymore.
+ this.turnId = null;
if (params?.status === "failed") return [{ kind: "error", message: "Codex turn failed" }];
if (params?.status === "interrupted") {
return [{ kind: "error", message: "Codex turn interrupted" }, { kind: "turn_end", sessionId: this.threadId ?? undefined }];
diff --git a/src/daemon/src/drivers/cursor.test.ts b/src/daemon/src/drivers/cursor.test.ts
new file mode 100644
index 000000000..b91faf648
--- /dev/null
+++ b/src/daemon/src/drivers/cursor.test.ts
@@ -0,0 +1,88 @@
+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 { CursorDriver } from "./cursor";
+import type { LaunchContext } from "../types";
+import { CredentialBroker } from "../credentials/credentialProxy";
+
+// Capture the argv the driver spawns with, so we can assert the flag set the
+// cursor-agent CLI actually accepts today (the `--yolo/--approve-mcps/--trust`
+// trio was removed — passing them fails arg-parse → pre_handshake_exit).
+let lastSpawn: { command: string; args: string[]; opts: any } | null = null;
+
+vi.mock("../runtime/killTree", async () => {
+ const actual = await vi.importActual<typeof import("../runtime/killTree")>("../runtime/killTree");
+ return {
+ ...actual,
+ spawnAgentProcess: (command: string, args: string[], opts: any) => {
+ lastSpawn = { command, args, opts };
+ 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(), "cursor-test-"));
+}
+
+function baseCtx(): LaunchContext {
+ const tmp = mkTmp();
+ return {
+ agentId: "agent_1",
+ launchId: "launch_1",
+ workingDirectory: tmp,
+ standingPrompt: "You are Cursor.",
+ prompt: "say 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: {},
+ mockCliTransport: true,
+ };
+}
+
+describe("CursorDriver spawn args", () => {
+ it("launches with --force and NOT the removed --yolo/--approve-mcps/--trust flags", async () => {
+ lastSpawn = null;
+ const driver = new CursorDriver();
+ await driver.spawn(baseCtx());
+
+ expect(lastSpawn).not.toBeNull();
+ const args = lastSpawn!.args;
+ // The current cursor-agent permission posture.
+ expect(args).toContain("--force");
+ expect(args).toEqual(expect.arrayContaining(["--print", "--output-format", "stream-json"]));
+ // The removed flags must be gone — any of them makes cursor-agent exit at
+ // arg-parse ("unknown option") before the handshake (pre_handshake_exit).
+ expect(args).not.toContain("--yolo");
+ expect(args).not.toContain("--approve-mcps");
+ expect(args).not.toContain("--trust");
+ // Prompt is passed as the trailing arg (per-turn, no stdin).
+ expect(args[args.length - 1]).toBe("say hi");
+ // stdin MUST be "ignore" — cursor-agent hangs on a piped stdin (emits
+ // nothing → handshake_timeout) even with the prompt in a positional arg.
+ expect(lastSpawn!.opts.stdin).toBe("ignore");
+ });
+
+ it("appends --resume when resuming, still with --force and no removed flags", async () => {
+ lastSpawn = null;
+ const driver = new CursorDriver();
+ const ctx = baseCtx();
+ ctx.config = { sessionId: "chat_42" };
+ await driver.spawn(ctx);
+
+ const args = lastSpawn!.args;
+ expect(args).toContain("--force");
+ expect(args).toEqual(expect.arrayContaining(["--resume", "chat_42"]));
+ expect(args).not.toContain("--yolo");
+ expect(args).not.toContain("--approve-mcps");
+ expect(args).not.toContain("--trust");
+ });
+});
diff --git a/src/daemon/src/drivers/cursor.ts b/src/daemon/src/drivers/cursor.ts
index 19b26fa33..630ec0bd3 100644
--- a/src/daemon/src/drivers/cursor.ts
+++ b/src/daemon/src/drivers/cursor.ts
@@ -1,9 +1,17 @@
/**
* Cursor driver — per-turn, stream-json, no steering.
*
- * `cursor-agent --print --output-format stream-json --yolo --approve-mcps
- * --trust <prompt>` is launched per wake. Emits Anthropic-style stream-json
- * (system/assistant/result envelopes) and exits.
+ * `cursor-agent --print --output-format stream-json --force <prompt>` is
+ * launched per wake. Emits Anthropic-style stream-json (system/assistant/result
+ * envelopes) and exits.
+ *
+ * Flag note: the older `--yolo --approve-mcps --trust` trio was removed when the
+ * cursor-agent CLI changed — passing them now fails arg-parse ("unknown option
+ * '--yolo'"), so the process exits before the handshake (pre_handshake_exit).
+ * The auto-approve execution posture is now `--force` ("allow commands unless
+ * explicitly denied") on top of `--print` (which already grants full tool
+ * access, write+bash). MCP approval moved out of the CLI into config
+ * (`.cursor/mcp.json` + `cursor-agent mcp login`), so it has no launch flag.
*/
import type { Driver, LaunchConfig, LaunchContext, ParsedEvent, SpawnResult } from "../types.js";
import { prepareCliTransport, buildCliTransportSystemPrompt } from "./cliTransport.js";
@@ -45,7 +53,7 @@ export class CursorDriver implements Driver {
this.sessionId = ctx.config.sessionId ?? null;
const { spawnEnv } = await prepareCliTransport(ctx);
const f = resolveLaunchFieldsOrDefault(ctx.config.runtimeConfig);
- const args = ["--print", "--output-format", "stream-json", "--yolo", "--approve-mcps", "--trust"];
+ const args = ["--print", "--output-format", "stream-json", "--force"];
if (f.model) args.push("--model", f.model);
if (ctx.config.sessionId) args.push("--resume", ctx.config.sessionId);
args.push(ctx.prompt);
@@ -57,6 +65,10 @@ export class CursorDriver implements Driver {
cwd: ctx.workingDirectory,
env: spawnEnv,
shell: spec.shell,
+ // cursor-agent blocks waiting on a piped stdin even with the prompt in a
+ // positional arg — it emits nothing and the daemon times out. It never
+ // reads stdin (per-turn, encodeStdinMessage returns null), so ignore it.
+ stdin: "ignore",
});
return { process: proc };
}
diff --git a/src/daemon/src/drivers/kimi.test.ts b/src/daemon/src/drivers/kimi.test.ts
index 91571f2bc..77a0a04a4 100644
--- a/src/daemon/src/drivers/kimi.test.ts
+++ b/src/daemon/src/drivers/kimi.test.ts
@@ -39,6 +39,7 @@ function baseCtx(): LaunchContext {
capabilities: ["send", "read"],
},
config: {},
+ mockCliTransport: true,
};
}
diff --git a/src/daemon/src/drivers/piSdkDeps.test.ts b/src/daemon/src/drivers/piSdkDeps.test.ts
index d00ee044a..8b9da91ab 100644
--- a/src/daemon/src/drivers/piSdkDeps.test.ts
+++ b/src/daemon/src/drivers/piSdkDeps.test.ts
@@ -31,6 +31,7 @@ function baseCtx(overrides: Partial<LaunchContext> = {}): LaunchContext {
capabilities: ["send", "read"],
},
config: {},
+ mockCliTransport: true,
...overrides,
};
}
diff --git a/src/daemon/src/drivers/spawnEnv.test.ts b/src/daemon/src/drivers/spawnEnv.test.ts
index b6fd76b38..1be988f35 100644
--- a/src/daemon/src/drivers/spawnEnv.test.ts
+++ b/src/daemon/src/drivers/spawnEnv.test.ts
@@ -74,6 +74,7 @@ describe("platformEnv", () => {
});
expect(v.ALOOK_HOME).toBe("/home/.alook");
expect(v.ALOOK_ID).toBe("agent_1");
+ // No cliPath → <PREFIX>_CLI falls back to the bare name.
expect(v.ALOOK_CLI).toBe("alook");
expect(v.ALOOK_SERVER_URL).toBe("ws://x");
expect(v.ALOOK_ACTIVE_CAPABILITIES).toBe("send,read");
@@ -81,6 +82,19 @@ describe("platformEnv", () => {
expect(v.ALOOK_CLI_TRANSPORT_TRACE_DIR).toBe("/trace");
});
+ it("sets <PREFIX>_CLI to the ABSOLUTE cliPath when given (agent invokes by path, not bare name)", () => {
+ const v = platformEnv("ALOOK", {
+ stateHome: "/home/.alook",
+ agentId: "agent_1",
+ cliName: "alook",
+ cliPath: "/work/.alook/bin/alook",
+ capabilities: [],
+ });
+ // The whole point: ALOOK_CLI is the absolute shim path, so `$ALOOK_CLI …`
+ // dodges PATH and always hits the injected CLI (never a host `alook`).
+ expect(v.ALOOK_CLI).toBe("/work/.alook/bin/alook");
+ });
+
it("swaps the prefix", () => {
const v = platformEnv("MOCK_CLI", {
stateHome: "/h",
diff --git a/src/daemon/src/drivers/spawnEnv.ts b/src/daemon/src/drivers/spawnEnv.ts
index 23c1e6071..86dcff4a8 100644
--- a/src/daemon/src/drivers/spawnEnv.ts
+++ b/src/daemon/src/drivers/spawnEnv.ts
@@ -72,6 +72,17 @@ export interface PlatformEnvFields {
stateHome: string;
agentId: string;
cliName: string;
+ /**
+ * ABSOLUTE path to the injected agent-CLI link. `<PREFIX>_CLI` is set to this
+ * (not the bare `cliName`) so the agent invokes the CLI by a path that PATH
+ * resolution can't shadow — the host may have its OWN `<cliName>` binary
+ * earlier in PATH (a different package, possibly a third party's), and a
+ * re-sourced shell rc can reorder PATH out from under us. An absolute path
+ * doesn't go through PATH at all, so it always hits the daemon-injected CLI
+ * regardless of the host. Undefined only on a mock launch (no shim) — then
+ * `<PREFIX>_CLI` falls back to the bare name.
+ */
+ cliPath?: string;
serverUrl?: string;
capabilities: string[];
launchId?: string;
@@ -83,7 +94,7 @@ export function platformEnv(prefix: string, f: PlatformEnvFields): Record<string
return {
[`${E}_HOME`]: f.stateHome,
[`${E}_ID`]: f.agentId,
- [`${E}_CLI`]: f.cliName,
+ [`${E}_CLI`]: f.cliPath ?? f.cliName,
[`${E}_SERVER_URL`]: f.serverUrl,
[`${E}_ACTIVE_CAPABILITIES`]: f.capabilities.join(","),
[`${E}_LAUNCH_ID`]: f.launchId,
diff --git a/src/daemon/src/drivers/systemPrompt.ts b/src/daemon/src/drivers/systemPrompt.ts
index b6a2d54a8..66e669d41 100644
--- a/src/daemon/src/drivers/systemPrompt.ts
+++ b/src/daemon/src/drivers/systemPrompt.ts
@@ -4,7 +4,13 @@
*/
import type { LaunchConfig } from "../types.js";
-const CLI = "alook";
+// The agent invokes the CLI via the `$ALOOK_CLI` env var, NOT a bare `alook`.
+// `$ALOOK_CLI` is an ABSOLUTE path the daemon injects (see spawnEnv
+// `<PREFIX>_CLI` / cliTransport), so it always resolves to the daemon-injected
+// agent CLI — never the host's own `alook` on PATH (a different package we don't
+// control, and PATH order a re-sourced shell rc can reorder). The `$`-form
+// expands in the agent's shell; the daemon exports the var into the process env.
+const CLI = "$ALOOK_CLI";
/* ------------------------------------------------------------------ */
/* Section builders */
diff --git a/src/daemon/src/manager/managerRuntime.test.ts b/src/daemon/src/manager/managerRuntime.test.ts
index edc6ab694..7624ee4d0 100644
--- a/src/daemon/src/manager/managerRuntime.test.ts
+++ b/src/daemon/src/manager/managerRuntime.test.ts
@@ -1707,10 +1707,18 @@ describe("isAlookShellInvocation", () => {
expect(isAlookShellInvocation("alook inbox pull")).toBe(true);
expect(isAlookShellInvocation(" alook message send")).toBe(true);
});
+ it("matches the `$ALOOK_CLI` env-var form the system prompt now teaches", () => {
+ expect(isAlookShellInvocation("$ALOOK_CLI inbox pull")).toBe(true);
+ expect(isAlookShellInvocation("${ALOOK_CLI} message send")).toBe(true);
+ expect(isAlookShellInvocation("$ALOOK_CLI")).toBe(true);
+ expect(isAlookShellInvocation(" $ALOOK_CLI nap")).toBe(true);
+ });
it("does NOT match commands that merely mention alook", () => {
expect(isAlookShellInvocation("rm alook.log")).toBe(false);
expect(isAlookShellInvocation("echo alook")).toBe(false);
expect(isAlookShellInvocation("alookalike")).toBe(false);
+ // A different env var that merely starts with the same prefix must not match.
+ expect(isAlookShellInvocation("$ALOOK_CLIENT foo")).toBe(false);
});
it("returns false for missing input", () => {
expect(isAlookShellInvocation(undefined)).toBe(false);
diff --git a/src/daemon/src/manager/managerRuntime.ts b/src/daemon/src/manager/managerRuntime.ts
index a629d4700..a6733cdba 100644
--- a/src/daemon/src/manager/managerRuntime.ts
+++ b/src/daemon/src/manager/managerRuntime.ts
@@ -471,7 +471,17 @@ 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|$)`);
+// The agent invokes the CLI two ways, both authoritative-`cli_invocation`
+// sources the tool_call must suppress:
+// - the injected env var: `$ALOOK_CLI …` / `${ALOOK_CLI} …` (the form the
+// system prompt now teaches — an absolute path that dodges PATH; see
+// spawnEnv `<PREFIX>_CLI` / systemPrompt), and
+// - the bare name `alook …` (legacy / any agent that still types it).
+// `<PREFIX>_CLI` is `${DEFAULT_CLI_CONFIG.envPrefix}_CLI` = `ALOOK_CLI`.
+const ALOOK_CLI_ENV_VAR = `${DEFAULT_CLI_CONFIG.envPrefix}_CLI`;
+const ALOOK_SHELL_INVOCATION_RE = new RegExp(
+ `^(?:${DEFAULT_CLI_CONFIG.cliName}|\\$\\{?${ALOOK_CLI_ENV_VAR}\\}?)(\\s|$)`,
+);
export function isAlookShellInvocation(command: string | undefined): boolean {
if (!command) return false;
diff --git a/src/daemon/src/runtime/killTree.ts b/src/daemon/src/runtime/killTree.ts
index f28c49e2c..1e242d7c1 100644
--- a/src/daemon/src/runtime/killTree.ts
+++ b/src/daemon/src/runtime/killTree.ts
@@ -41,6 +41,16 @@ export interface AgentSpawnOptions {
env: NodeJS.ProcessEnv;
/** Run through a shell — needed on Windows for `.cmd`/`.bat` shims. */
shell?: boolean;
+ /**
+ * stdin disposition. Default `"pipe"` — codex/claude/pi write to stdin
+ * (initial prompt, `turn/steer`), so they need it. A per-turn driver that
+ * never writes stdin (cursor: prompt is a positional arg, `encodeStdinMessage`
+ * returns null) must use `"ignore"`: cursor-agent BLOCKS waiting on a piped
+ * stdin even though the prompt is already supplied, emitting nothing →
+ * handshake_timeout. `"ignore"` lets it detect there's no interactive input
+ * and run. stdout/stderr stay piped regardless (we always read stream-json).
+ */
+ stdin?: "pipe" | "ignore";
}
/**
@@ -54,7 +64,10 @@ export interface AgentSpawnOptions {
export function spawnAgentProcess(command: string, args: string[], opts: AgentSpawnOptions): ChildProcess {
return spawn(command, args, {
cwd: opts.cwd,
- stdio: ["pipe", "pipe", "pipe"],
+ // stdout/stderr always piped (we read the runtime's stream-json/JSON-RPC);
+ // stdin defaults to pipe (writers: codex/claude/pi) but a no-stdin driver
+ // (cursor) opts into "ignore" — see AgentSpawnOptions.stdin.
+ stdio: [opts.stdin ?? "pipe", "pipe", "pipe"],
env: opts.env,
shell: opts.shell ?? false,
detached: isPosix,
diff --git a/src/daemon/src/types.ts b/src/daemon/src/types.ts
index 05ca0f875..9d91d7120 100644
--- a/src/daemon/src/types.ts
+++ b/src/daemon/src/types.ts
@@ -188,6 +188,16 @@ export interface LaunchContext {
prompt: string;
/** Path to the injected Alook CLI wrapper (host-supplied; see cliTransport). */
agentCliPath?: string;
+ /**
+ * Positive opt-in for a launch that has NO host CLI on purpose (test / mock
+ * harness): `prepareCliTransport` then skips the agent-CLI shim silently
+ * instead of failing loud. Real launches MUST NOT set this — a real launch
+ * with no resolvable CLI path is a hard fault (the agent's `alook` would fall
+ * through to the host CLI, which lacks the agent subcommands). The flag, not
+ * "agentCliPath is empty", is the mock signal: an empty path is exactly the
+ * bug shape we want to catch, so it can't also mean "mock".
+ */
+ mockCliTransport?: boolean;
daemonApiKey?: string;
cliTransportTraceDir?: string;
/**
diff --git a/src/ws-do/src/ws-durable.test.ts b/src/ws-do/src/ws-durable.test.ts
index 7722d4843..15a2f97cc 100644
--- a/src/ws-do/src/ws-durable.test.ts
+++ b/src/ws-do/src/ws-durable.test.ts
@@ -2027,6 +2027,20 @@ describe("WebSocketDurableObject", () => {
})
})
+ it("two agent_session frames for the same launch write the reset audit ONCE (claim-first evict, no double record)", async () => {
+ const { durable, store } = createDO()
+ seedIdentity(store)
+ await pushFrame(durable, { type: "agent:reset", agentId: "bot_1", config: {}, launchId: "l_reset" })
+ // Two agent_session frames arrive back-to-back for the SAME launch (e.g. a
+ // runtime that announces its session twice). The pending trigger must be
+ // consumed by the first → the second finds nothing → only ONE audit row.
+ const frame = JSON.stringify({ type: "agent_session", agentId: "bot_1", sessionId: "s_new", launchId: "l_reset" })
+ await durable.webSocketMessage(machineWs() as any, frame)
+ await durable.webSocketMessage(machineWs() as any, frame)
+
+ expect(mockInsertBotAuditSessionReset).toHaveBeenCalledTimes(1)
+ })
+
it("batch reset: each agent's agent_session writes session_reset with trigger reset_all", async () => {
const { durable, store } = createDO()
seedIdentity(store)
diff --git a/src/ws-do/src/ws-durable.ts b/src/ws-do/src/ws-durable.ts
index 5c34c7924..4a57cf663 100644
--- a/src/ws-do/src/ws-durable.ts
+++ b/src/ws-do/src/ws-durable.ts
@@ -941,8 +941,19 @@ export class WebSocketDurableObject extends DurableObject<Env> {
const sessionParse = AgentSessionMessageSchema.safeParse(parsed)
if (sessionParse.success) {
const { agentId, launchId } = sessionParse.data
+ // CLAIM-then-write: read the pending trigger AND consume it up front, in
+ // one turn before any `await` on the write path. Two `agent_session`
+ // frames for the same launch can arrive back-to-back (e.g. codex used to
+ // announce a thread twice → two frames); the OLD order (get → await
+ // write → evict) let both read a non-null trigger before either evicted →
+ // both wrote the reset audit (the "two identical reset records" bug).
+ // Deleting immediately after the get makes the claim atomic within this
+ // object's single-threaded turn: the second frame reads null and returns.
+ // (normalizer dedup removes the double-frame SOURCE; this makes the
+ // consume race-proof for any future double-frame, cross-runtime.)
const trigger = await this.ctx.storage.get<ResetTrigger>(resetPendingKey(launchId))
if (!trigger) return // not a reset/nap launch, or already consumed
+ await this.evictPendingReset(launchId)
const db = createDb(this.env.DB)
await this.handleFrameForBoundBot({
frameType: "agent_session",
@@ -985,11 +996,7 @@ export class WebSocketDurableObject extends DurableObject<Env> {
}).catch(() => { })
},
})
- // Consume the pending entry regardless of the write's fate: a replayed
- // agent_session must never re-write, and the audit row (if it landed) is
- // the durable record. A failed write (binding gone) also clears — the
- // launch is done either way.
- await this.evictPendingReset(launchId)
+ // (pending entry already consumed above, before the write — claim-first.)
return
}