Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

feat(daemon): wire Pi in-process SDK runtime, harden spawn/stop lifecycle

Gus1872b6d905e0
diff --git a/src/daemon/src/daemon/createDaemon.ts b/src/daemon/src/daemon/createDaemon.ts
index 96fa5cd24..2f1e029e8 100644
--- a/src/daemon/src/daemon/createDaemon.ts
+++ b/src/daemon/src/daemon/createDaemon.ts
@@ -28,6 +28,7 @@ import { AgentProcessManager, AgentRouter } from "../manager/index.js";
import { UnknownBotError, BotEnrollFailedError, UnknownRuntimeError } from "../manager/agentRouter.js";
import { createTimelineRecorder } from "../timeline/index.js";
import { resolveAlookCliPathWithFallback } from "../discovery.js";
+import { createPiSdkDriverDeps } from "../drivers/piSdkDeps.js";
import { createLogger, type Logger } from "../logger.js";
import type { Driver, LaunchContext } from "../types.js";
import type { RuntimeConfig } from "../runtimeConfig.js";
@@ -324,6 +325,9 @@ export async function createDaemon(opts: CreateDaemonOptions): Promise<RunningDa
},
tickIntervalMs: opts.tickIntervalMs ?? 2000,
onAgentSession: (info) => void channel.reportAgentSession(info),
+ // Only the "pi" runtime declares `Driver.createSession` today (in-process
+ // SDK, no child process) — this is only ever consulted for that case.
+ sdkDriverDepsFor: (ctx) => createPiSdkDriverDeps(ctx),
timeline,
wakePromptFooter: "Use `alook inbox pull` to read your messages, then reply with `alook message send`.",
logger: log.child("manager"),
diff --git a/src/daemon/src/discovery.test.ts b/src/daemon/src/discovery.test.ts
index d8a5461ae..559d4cfe0 100644
--- a/src/daemon/src/discovery.test.ts
+++ b/src/daemon/src/discovery.test.ts
@@ -1,4 +1,6 @@
-import { describe, it, expect, beforeAll } from "vitest";
+import { describe, it, expect, beforeAll, afterEach } from "vitest";
+import * as fs from "fs";
+import * as os from "os";
import * as path from "path";
import { fileURLToPath } from "url";
import {
@@ -9,15 +11,79 @@ import {
getAvailableRuntimes,
} from "./discovery";
+const tmpDirs: string[] = [];
+function mkTmp(): string {
+ const d = fs.mkdtempSync(path.join(os.tmpdir(), "discovery-"));
+ tmpDirs.push(d);
+ return d;
+}
+afterEach(() => {
+ for (const d of tmpDirs.splice(0)) fs.rmSync(d, { recursive: true, force: true });
+});
+
describe("resolveAlookCliPath", () => {
- it("finds the source CLI entry from the src directory", () => {
- // When running from src/, the source .ts entry should exist
+ it("finds the dev shim from the real src directory (never the raw .ts entry)", () => {
+ // The real discovery.ts lives in src/, so this always exercises the dev
+ // branch. It must resolve to the shim, never the raw cli/index.ts.
const thisDir = path.dirname(fileURLToPath(import.meta.url));
const result = resolveAlookCliPath(thisDir);
- // cli/index.ts should exist relative to src/
expect(result).not.toBeNull();
- expect(result!).toContain("cli");
- expect(result!).toContain("index");
+ expect(fs.existsSync(result!)).toBe(true);
+ expect(result!.endsWith("alook-shim.mjs")).toBe(true);
+ });
+
+ it("dev shape (moduleDir named `src`): resolves to the sibling scripts/alook-shim.mjs", () => {
+ const root = mkTmp();
+ const srcDir = path.join(root, "src");
+ const scriptsDir = path.join(root, "scripts");
+ fs.mkdirSync(srcDir, { recursive: true });
+ fs.mkdirSync(scriptsDir, { recursive: true });
+ const shim = path.join(scriptsDir, "alook-shim.mjs");
+ fs.writeFileSync(shim, "#!/usr/bin/env node\n", { mode: 0o755 });
+
+ const result = resolveAlookCliPath(srcDir);
+ expect(result).toBe(shim);
+ // Must be a real, executable-looking entrypoint — not a raw .ts file
+ // that would throw ERR_MODULE_NOT_FOUND when exec'd directly.
+ expect(result!.endsWith(".ts")).toBe(false);
+ expect(fs.readFileSync(result!, "utf8")).toMatch(/^#!/);
+ });
+
+ it("dev shape: does NOT fall back to a prebuilt dist/cli/index.js even if one exists", () => {
+ // A stale dist/ sitting next to src/ must never be picked while running
+ // unbuilt — that would silently serve old CLI behavior after source
+ // edits. Only the always-fresh dev shim is a valid target in this shape.
+ const root = mkTmp();
+ const srcDir = path.join(root, "src");
+ const distCliDir = path.join(root, "dist", "cli");
+ fs.mkdirSync(srcDir, { recursive: true });
+ fs.mkdirSync(distCliDir, { recursive: true });
+ fs.writeFileSync(path.join(distCliDir, "index.js"), "#!/usr/bin/env node\n", { mode: 0o755 });
+ // No scripts/alook-shim.mjs created — the dev target genuinely doesn't exist.
+
+ const result = resolveAlookCliPath(srcDir);
+ expect(result).toBeNull();
+ });
+
+ it("production shape (moduleDir named `dist`): resolves to the sibling cli/index.js", () => {
+ const root = mkTmp();
+ const distDir = path.join(root, "dist");
+ const cliDir = path.join(distDir, "cli");
+ fs.mkdirSync(cliDir, { recursive: true });
+ const entry = path.join(cliDir, "index.js");
+ fs.writeFileSync(entry, "#!/usr/bin/env node\n", { mode: 0o755 });
+
+ const result = resolveAlookCliPath(distDir);
+ expect(result).toBe(entry);
+ });
+
+ it("production shape: returns null (not a different guess) when cli/index.js is missing", () => {
+ const root = mkTmp();
+ const distDir = path.join(root, "dist");
+ fs.mkdirSync(distDir, { recursive: true });
+
+ const result = resolveAlookCliPath(distDir);
+ expect(result).toBeNull();
});
it("returns null for a nonexistent directory", () => {
diff --git a/src/daemon/src/discovery.ts b/src/daemon/src/discovery.ts
index 4c0e79e65..3200fee52 100644
--- a/src/daemon/src/discovery.ts
+++ b/src/daemon/src/discovery.ts
@@ -17,29 +17,38 @@ import type { ProbeResult } from "./types.js";
/**
* Locate the Alook agent CLI entry point.
*
- * Search order (first existing wins):
- * 1. Bundled: `<daemon-pkg>/dist/cli/index.js`
- * 2. Workspace sibling: `<monorepo>/src/daemon/dist/cli/index.js` (pnpm workspace)
- * 3. Source (dev): `<monorepo>/src/daemon/src/cli/index.ts` (for tsx usage)
+ * This path gets symlinked (POSIX) or `.cmd`-wrapped (Windows) straight into
+ * every spawned agent's PATH as `alook` (see `cliLink.ts`) — on POSIX the OS
+ * execs it directly, so it MUST be a self-executable entrypoint. The raw TS
+ * source (`cli/index.ts`) does NOT qualify: even with a shebang, executing it
+ * without `tsx` leaves Node's ESM resolver looking for literal `./*.js`
+ * sibling files that only exist once built, throwing `ERR_MODULE_NOT_FOUND`.
*
- * Returns null if no candidate exists (caller should log a warning).
+ * Deliberately NOT a multi-candidate existence probe — this module always
+ * compiles `src/discovery.ts` → `dist/discovery.js` (see tsconfig
+ * `rootDir`/`outDir`), so `thisDir` unambiguously tells us which of the two
+ * real deployment shapes we're in; there is exactly one correct answer per
+ * shape, not a list of guesses to try:
+ * - running from `dist/` (built/published): the CLI entry is the sibling
+ * `dist/cli/index.js` — if it's missing, that's a real packaging bug.
+ * - running from `src/` (dev, via `tsx`): the CLI entry is the dev shim
+ * `scripts/alook-shim.mjs`, which execs the TS source through `tsx` so
+ * relative `.js` import specifiers resolve to their `.ts` siblings.
+ * (Deliberately never falls back to a possibly-stale prebuilt `dist/` —
+ * that would silently serve old CLI behavior after source edits.)
+ *
+ * Returns null if the one expected entry doesn't exist (caller should log a
+ * warning) — never silently substitutes a different candidate.
*/
export function resolveAlookCliPath(moduleDir?: string): string | null {
const thisDir = moduleDir ?? path.dirname(fileURLToPath(import.meta.url));
- const candidates = [
- // 1. Bundled dist CLI (production: daemon built + CLI entry in same dist)
- path.resolve(thisDir, "cli", "index.js"),
- // 2. Dist from package root (built but running from src via tsx)
- path.resolve(thisDir, "..", "dist", "cli", "index.js"),
- // 3. Source entry (dev: running unbuilt via tsx)
- path.resolve(thisDir, "cli", "index.ts"),
- ];
+ const target =
+ path.basename(thisDir) === "dist"
+ ? path.resolve(thisDir, "cli", "index.js")
+ : path.resolve(thisDir, "..", "scripts", "alook-shim.mjs");
- for (const candidate of candidates) {
- if (fs.existsSync(candidate)) return candidate;
- }
- return null;
+ return fs.existsSync(target) ? target : null;
}
/**
diff --git a/src/daemon/src/drivers/antigravity.ts b/src/daemon/src/drivers/antigravity.ts
index 5474dbf21..b4a449cb4 100644
--- a/src/daemon/src/drivers/antigravity.ts
+++ b/src/daemon/src/drivers/antigravity.ts
@@ -10,7 +10,7 @@ import { spawn } from "child_process";
import { randomUUID } from "crypto";
import type { Driver, LaunchConfig, LaunchContext, ParsedEvent, SpawnResult } from "../types.js";
import { prepareCliTransport, buildCliTransportSystemPrompt } from "./cliTransport.js";
-import { resolveCommandOnPath, probeCliRuntime } from "./probe.js";
+import { probeCliRuntime, resolveSpawnSpec } from "./probe.js";
const ERROR_LINE_PATTERNS: RegExp[] = [/^error[:\s]/i, /\bfatal\b/i, /\bpanic\b/i, /unable to/i];
@@ -57,11 +57,14 @@ export class AntigravityDriver implements Driver {
SSH_CONNECTION: "",
SSH_TTY: "",
});
- const command = resolveCommandOnPath("agy") ?? "agy";
- const proc = spawn(command, buildAntigravityArgs(ctx), {
+ // 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 proc = spawn(spec.command, spec.args, {
cwd: ctx.workingDirectory,
stdio: ["pipe", "pipe", "pipe"],
env: spawnEnv,
+ shell: spec.shell,
});
proc.stdin?.end(ctx.prompt);
return { process: proc };
diff --git a/src/daemon/src/drivers/copilot.ts b/src/daemon/src/drivers/copilot.ts
index 196c864b5..04dfe002b 100644
--- a/src/daemon/src/drivers/copilot.ts
+++ b/src/daemon/src/drivers/copilot.ts
@@ -8,7 +8,7 @@
import { spawn } from "child_process";
import type { Driver, LaunchConfig, LaunchContext, ParsedEvent, SpawnResult } from "../types.js";
import { prepareCliTransport, buildCliTransportSystemPrompt } from "./cliTransport.js";
-import { resolveCommandOnPath, probeCliRuntime } from "./probe.js";
+import { probeCliRuntime, resolveSpawnSpec } from "./probe.js";
import { resolveLaunchFieldsOrDefault } from "../runtimeConfig.js";
export class CopilotDriver implements Driver {
@@ -43,11 +43,14 @@ export class CopilotDriver implements Driver {
if (f.reasoningEffort) args.push("--effort", f.reasoningEffort);
if (ctx.config.sessionId) args.push(`--resume=${ctx.config.sessionId}`);
- const command = resolveCommandOnPath("copilot") ?? "copilot";
- const proc = spawn(command, args, {
+ // 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 proc = spawn(spec.command, spec.args, {
cwd: ctx.workingDirectory,
stdio: ["pipe", "pipe", "pipe"],
env: spawnEnv,
+ shell: spec.shell,
});
return { process: proc };
}
diff --git a/src/daemon/src/drivers/cursor.ts b/src/daemon/src/drivers/cursor.ts
index abcea971f..d8883cadf 100644
--- a/src/daemon/src/drivers/cursor.ts
+++ b/src/daemon/src/drivers/cursor.ts
@@ -8,7 +8,7 @@
import { spawn } from "child_process";
import type { Driver, LaunchConfig, LaunchContext, ParsedEvent, SpawnResult } from "../types.js";
import { prepareCliTransport, buildCliTransportSystemPrompt } from "./cliTransport.js";
-import { resolveCommandOnPath, probeCliRuntime } from "./probe.js";
+import { probeCliRuntime, resolveSpawnSpec } from "./probe.js";
import { resolveLaunchFieldsOrDefault } from "../runtimeConfig.js";
export class CursorDriver implements Driver {
@@ -43,11 +43,14 @@ export class CursorDriver implements Driver {
if (ctx.config.sessionId) args.push("--resume", ctx.config.sessionId);
args.push(ctx.prompt);
- const command = resolveCommandOnPath("cursor-agent") ?? "cursor-agent";
- const proc = spawn(command, args, {
+ // 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 proc = spawn(spec.command, spec.args, {
cwd: ctx.workingDirectory,
stdio: ["pipe", "pipe", "pipe"],
env: spawnEnv,
+ shell: spec.shell,
});
return { process: proc };
}
diff --git a/src/daemon/src/drivers/kimi.ts b/src/daemon/src/drivers/kimi.ts
index e883afe13..fa43f4207 100644
--- a/src/daemon/src/drivers/kimi.ts
+++ b/src/daemon/src/drivers/kimi.ts
@@ -11,7 +11,7 @@ import { spawn } from "child_process";
import { randomUUID } from "crypto";
import type { Driver, EncodeOpts, LaunchConfig, LaunchContext, ParsedEvent, SpawnResult } from "../types.js";
import { prepareCliTransport, buildCliTransportSystemPrompt } from "./cliTransport.js";
-import { resolveCommandOnPath, probeCliRuntime } from "./probe.js";
+import { probeCliRuntime, resolveSpawnSpec } from "./probe.js";
import { resolveLaunchFieldsOrDefault } from "../runtimeConfig.js";
function parseToolArguments(args: unknown): unknown {
@@ -55,11 +55,14 @@ export class KimiDriver implements Driver {
const args = ["--wire", "--yolo", "--session", this.sessionId];
if (f.model) args.push("--model", f.model);
- const command = resolveCommandOnPath("kimi") ?? "kimi";
- const proc = spawn(command, args, {
+ // 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 proc = spawn(spec.command, spec.args, {
cwd: ctx.workingDirectory,
stdio: ["pipe", "pipe", "pipe"],
env: spawnEnv,
+ shell: spec.shell,
});
proc.stdin?.write(
diff --git a/src/daemon/src/drivers/opencode.test.ts b/src/daemon/src/drivers/opencode.test.ts
new file mode 100644
index 000000000..057fd5752
--- /dev/null
+++ b/src/daemon/src/drivers/opencode.test.ts
@@ -0,0 +1,49 @@
+import { describe, it, expect, beforeEach } from "vitest";
+import { OpenCodeDriver } from "./opencode";
+
+describe("OpenCodeDriver.parseLine — step_finish turn-end timing", () => {
+ let driver: OpenCodeDriver;
+
+ beforeEach(() => {
+ driver = new OpenCodeDriver();
+ });
+
+ function line(obj: unknown): string {
+ return JSON.stringify(obj);
+ }
+
+ it("does NOT end the turn on an intermediate step_finish (reason: tool-calls)", () => {
+ const events = driver.parseLine(
+ line({ type: "step_finish", sessionID: "ses_1", part: { type: "step-finish", reason: "tool-calls" } }),
+ );
+ expect(events.some((e) => e.kind === "turn_end")).toBe(false);
+ });
+
+ it("ends the turn on the final step_finish (reason: stop)", () => {
+ const events = driver.parseLine(
+ line({ type: "step_finish", sessionID: "ses_1", part: { type: "step-finish", reason: "stop" } }),
+ );
+ expect(events.some((e) => e.kind === "turn_end")).toBe(true);
+ });
+
+ it("a multi-step turn (tool-calls step, then a stop step) emits turn_end exactly once, after the final step", () => {
+ const afterToolCallStep = driver.parseLine(
+ line({ type: "step_finish", sessionID: "ses_1", part: { type: "step-finish", reason: "tool-calls" } }),
+ );
+ const afterFinalStep = driver.parseLine(
+ line({ type: "step_finish", sessionID: "ses_1", part: { type: "step-finish", reason: "stop" } }),
+ );
+
+ expect(afterToolCallStep.filter((e) => e.kind === "turn_end")).toHaveLength(0);
+ expect(afterFinalStep.filter((e) => e.kind === "turn_end")).toHaveLength(1);
+ });
+
+ it("does not throw on a step_finish with no part (defensive)", () => {
+ expect(() => driver.parseLine(line({ type: "step_finish", sessionID: "ses_1" }))).not.toThrow();
+ // Missing `part.reason` is treated as "not tool-calls" -> turn ends, which
+ // is the safe default (never getting stuck waiting for a turn_end that
+ // never comes).
+ const events = driver.parseLine(line({ type: "step_finish", sessionID: "ses_1" }));
+ expect(events.some((e) => e.kind === "turn_end")).toBe(true);
+ });
+});
diff --git a/src/daemon/src/drivers/opencode.ts b/src/daemon/src/drivers/opencode.ts
index 00416d753..6439cd8a0 100644
--- a/src/daemon/src/drivers/opencode.ts
+++ b/src/daemon/src/drivers/opencode.ts
@@ -11,7 +11,7 @@
import { spawn } from "child_process";
import type { Driver, LaunchConfig, LaunchContext, ParsedEvent, SpawnResult } from "../types.js";
import { prepareCliTransport, buildCliTransportSystemPrompt } from "./cliTransport.js";
-import { resolveCommandOnPath, probeCliRuntime } from "./probe.js";
+import { probeCliRuntime, resolveSpawnSpec } from "./probe.js";
import { resolveLaunchFieldsOrDefault } from "../runtimeConfig.js";
export class OpenCodeDriver implements Driver {
@@ -57,11 +57,14 @@ export class OpenCodeDriver implements Driver {
const promptArg = ctx.prompt === ctx.standingPrompt ? "No new messages are pending. Stop now." : ctx.prompt;
args.push("--", promptArg);
- const command = resolveCommandOnPath("opencode") ?? "opencode";
- const proc = spawn(command, args, {
+ // 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 proc = spawn(spec.command, spec.args, {
cwd: ctx.workingDirectory,
stdio: ["pipe", "pipe", "pipe"],
env: spawnEnv,
+ shell: spec.shell,
});
proc.stdin?.end();
return { process: proc };
@@ -91,7 +94,11 @@ export class OpenCodeDriver implements Driver {
out.push({ kind: "tool_call", name: event.part?.tool ?? "unknown_tool", input: event.part?.state?.input });
break;
case "step_finish":
- if (event.reason !== "tool-calls") out.push({ kind: "turn_end", sessionId: this.sessionId ?? undefined });
+ // `reason` lives under `part` (e.g. `part: { reason: "stop" | "tool-calls" | ... }`),
+ // not at the top level — reading `event.reason` directly is always
+ // `undefined`, which made every step (including intermediate
+ // tool-call steps) look like the final one.
+ if (event.part?.reason !== "tool-calls") out.push({ kind: "turn_end", sessionId: this.sessionId ?? undefined });
break;
case "error":
out.push({
diff --git a/src/daemon/src/drivers/pi.test.ts b/src/daemon/src/drivers/pi.test.ts
index 149fdb854..1ab9db76e 100644
--- a/src/daemon/src/drivers/pi.test.ts
+++ b/src/daemon/src/drivers/pi.test.ts
@@ -2,7 +2,7 @@ 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 } from "./pi";
+import { PiDriver, resolvePiSdkVersionFromPath, resolvePiSdkPackageDir } from "./pi";
import { CANONICAL_FILE, SYMLINK_ALIASES } from "./agentFile";
import type { LaunchContext } from "../types";
@@ -81,3 +81,115 @@ describe("PiDriver.createSession — AGENTS.md packing", () => {
expect(fs.readFileSync(path.join(notYetCreated, CANONICAL_FILE), "utf-8")).toBe("You are Pi.");
});
});
+
+describe("PiDriver.createSession — does not fire the initial prompt itself", () => {
+ it("returns without calling session.prompt — the caller (SdkManagedSession) sends the first turn", async () => {
+ const driver = new PiDriver();
+ const deps = fakeDeps();
+
+ const runtimeSession = await driver.createSession(baseCtx(), deps);
+
+ expect(deps.session.prompt).not.toHaveBeenCalled();
+ expect(runtimeSession.currentSessionId).toBe("sess_1");
+ });
+
+ it("wires session.subscribe before returning, so events fired by a later prompt() call are not lost", async () => {
+ const driver = new PiDriver();
+ const deps = fakeDeps();
+
+ const runtimeSession = await driver.createSession(baseCtx(), deps);
+ const received: unknown[] = [];
+ runtimeSession.on("runtime_event", (e) => received.push(e));
+
+ // Simulate the SDK emitting a text_delta while handling a prompt sent
+ // later, via the subscribe callback deps.session.subscribe captured.
+ const subscribeCb = deps.session.subscribe.mock.calls[0][0];
+ subscribeCb({ type: "message_update", delta: { type: "text_delta", delta: "hi" } });
+
+ expect(received).toEqual([
+ { kind: "session_init", sessionId: "sess_1" },
+ { kind: "text", text: "hi" },
+ ]);
+ });
+});
+
+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:
+ // <root>/lib/node_modules/@earendil-works/pi-coding-agent/{package.json,dist/cli.js}
+ // <root>/bin/pi -> ../lib/node_modules/@earendil-works/pi-coding-agent/dist/cli.js
+ const pkgDir = path.join(tmpDir, "lib", "node_modules", "@earendil-works", "pi-coding-agent");
+ fs.mkdirSync(path.join(pkgDir, "dist"), { recursive: true });
+ fs.writeFileSync(
+ path.join(pkgDir, "package.json"),
+ JSON.stringify({ name: "@earendil-works/pi-coding-agent", version: "0.80.3" }),
+ );
+ const entryFile = path.join(pkgDir, "dist", "cli.js");
+ fs.writeFileSync(entryFile, "#!/usr/bin/env node\n");
+
+ const binDir = path.join(tmpDir, "bin");
+ fs.mkdirSync(binDir, { recursive: true });
+ const binPath = path.join(binDir, "pi");
+ fs.symlinkSync(entryFile, binPath);
+
+ const version = resolvePiSdkVersionFromPath({ which: (cmd) => (cmd === "pi" ? binPath : null) });
+ expect(version).toBe("0.80.3");
+ });
+
+ it("returns undefined when `pi` is not on PATH", () => {
+ const version = resolvePiSdkVersionFromPath({ which: () => null });
+ expect(version).toBeUndefined();
+ });
+
+ it("returns undefined (does not throw) when the resolved binary isn't part of the pi-coding-agent package", () => {
+ const otherDir = path.join(tmpDir, "some-other-tool");
+ fs.mkdirSync(otherDir, { recursive: true });
+ fs.writeFileSync(path.join(otherDir, "package.json"), JSON.stringify({ name: "unrelated-tool", version: "1.0.0" }));
+ const binPath = path.join(otherDir, "pi");
+ fs.writeFileSync(binPath, "#!/usr/bin/env node\n");
+
+ const version = resolvePiSdkVersionFromPath({ which: (cmd) => (cmd === "pi" ? binPath : null) });
+ expect(version).toBeUndefined();
+ });
+
+ it("returns undefined (does not throw) when the resolved path doesn't exist on disk", () => {
+ const version = resolvePiSdkVersionFromPath({ which: () => path.join(tmpDir, "nonexistent", "pi") });
+ expect(version).toBeUndefined();
+ });
+
+ // Regression test: on Windows, npm writes the `.cmd` shim as a real file
+ // directly in the global prefix root (e.g. `%AppData%\npm`) — NOT a
+ // symlink into the package like POSIX — so `realpathSync` never walks us
+ // inside it. The package instead sits in a SIBLING `node_modules` folder
+ // at that same level, never an ancestor of the shim's own directory.
+ it("finds the SDK version via a sibling node_modules dir (simulates a Windows npm global install, where the shim is a real file next to node_modules, not a symlink into it)", () => {
+ // Simulate: %AppData%\npm\pi.cmd (a real file, not a symlink) and
+ // %AppData%\npm\node_modules\@earendil-works\pi-coding-agent\
+ const npmRoot = path.join(tmpDir, "AppData", "npm");
+ const pkgDir = path.join(npmRoot, "node_modules", "@earendil-works", "pi-coding-agent");
+ fs.mkdirSync(pkgDir, { recursive: true });
+ fs.writeFileSync(
+ path.join(pkgDir, "package.json"),
+ JSON.stringify({ name: "@earendil-works/pi-coding-agent", version: "0.90.1" }),
+ );
+ const binPath = path.join(npmRoot, "pi.cmd");
+ fs.writeFileSync(binPath, "@echo off\r\n"); // a real file, not a symlink
+
+ const version = resolvePiSdkVersionFromPath({ which: (cmd) => (cmd === "pi" ? binPath : null) });
+ expect(version).toBe("0.90.1");
+ });
+
+ it("resolvePiSdkPackageDir returns the sibling package dir itself, not the shim's own directory", () => {
+ const npmRoot = path.join(tmpDir, "AppData", "npm");
+ const pkgDir = path.join(npmRoot, "node_modules", "@earendil-works", "pi-coding-agent");
+ fs.mkdirSync(pkgDir, { recursive: true });
+ fs.writeFileSync(path.join(pkgDir, "package.json"), JSON.stringify({ name: "@earendil-works/pi-coding-agent", version: "0.90.1" }));
+ const binPath = path.join(npmRoot, "pi.cmd");
+ fs.writeFileSync(binPath, "@echo off\r\n");
+
+ const dir = resolvePiSdkPackageDir({ which: (cmd) => (cmd === "pi" ? binPath : null) });
+ // Compare via realpath — on macOS, tmpdir() itself sits behind a
+ // `/var` -> `/private/var` symlink unrelated to the thing under test.
+ expect(dir && fs.realpathSync(dir)).toBe(fs.realpathSync(pkgDir));
+ });
+});
diff --git a/src/daemon/src/drivers/pi.ts b/src/daemon/src/drivers/pi.ts
index adc737c0c..538e3881d 100644
--- a/src/daemon/src/drivers/pi.ts
+++ b/src/daemon/src/drivers/pi.ts
@@ -11,28 +11,133 @@
* 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).
+ *
+ * `createSession` only builds and wires the session — it does not send the
+ * first turn. `SdkManagedSession` (the `ManagedSession` adapter that drives
+ * this from `managerRuntime.ts`) attaches its `"runtime_event"` listener to
+ * the returned session first, then sends the initial prompt, so nothing
+ * fires into an unlistened `EventEmitter` and gets dropped.
*/
import { createRequire } from "module";
-import { mkdirSync } from "fs";
-import type { Driver, LaunchConfig, LaunchContext, ParsedEvent, SpawnResult } from "../types.js";
+import { mkdirSync, existsSync, readFileSync, realpathSync } from "fs";
+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";
+
+const PI_SDK_PACKAGE_NAME = "@earendil-works/pi-coding-agent";
+
+/** Minimal shape of the vendor SDK's `AgentSession` this driver actually calls. */
+export interface PiSdkAgentSession {
+ prompt(text: string, options?: { streamingBehavior?: "steer" | "followUp" }): Promise<void>;
+ steer(text: string): Promise<void>;
+ abort(): Promise<void>;
+ dispose(): void;
+ readonly isStreaming: boolean;
+ subscribe(listener: (event: unknown) => void): () => void;
+}
+
+/** True if `pkgJsonPath` exists and is the pi SDK's own `package.json`. */
+function isPiSdkPackageJson(pkgJsonPath: string): boolean {
+ if (!existsSync(pkgJsonPath)) return false;
+ try {
+ const pkg = JSON.parse(readFileSync(pkgJsonPath, "utf-8")) as { name?: string };
+ return pkg.name === PI_SDK_PACKAGE_NAME;
+ } catch {
+ // Malformed package.json — treat as "not this package"; the caller
+ // keeps walking, it may just be an unrelated file that happens to sit
+ // alongside the binary.
+ return false;
+ }
+}
/**
- * Read the bundled Pi SDK's package version. Optional — the SDK isn't a hard
- * dep of the daemon, so we return undefined when it isn't installed on the
- * host, and the runtime chip renders without a version.
+ * Fallback SDK detection for a globally-installed `pi` (e.g. `npm install -g
+ * @earendil-works/pi-coding-agent`, a Homebrew formula, or a pnpm/yarn/nvm
+ * global install). `require()` from the daemon's own file location can never
+ * see a global install — it lives in a completely separate `node_modules`
+ * tree — even though `pi --version` works fine in a shell. So instead we
+ * resolve the `pi` binary on `PATH` (same as every other driver's `probe()`)
+ * and walk upward from it looking for the package's own `package.json`,
+ * checking two shapes at each level:
+ * 1. `dir` itself IS inside the package — true on POSIX, where the PATH
+ * resolution follows a symlink through `realpathSync` into the
+ * package's real install directory (npm/Homebrew/pnpm/yarn/nvm all do
+ * this).
+ * 2. `dir/node_modules/@earendil-works/pi-coding-agent` — true on Windows,
+ * where npm writes the `.cmd` shim as a real file directly in the
+ * global prefix root (e.g. `%AppData%\npm`) rather than a symlink INTO
+ * the package, so `realpathSync` never gets us inside it; the actual
+ * package instead sits in a SIBLING `node_modules` folder at that same
+ * level, never an ancestor.
+ * This is package-manager-agnostic: it doesn't assume npm specifically (no
+ * `npm root -g` shell-out), so it keeps working no matter how the global
+ * install actually got there.
+ *
+ * Also used by `piSdkDeps.ts::loadPiSdkModule` to find the real install
+ * directory to `import()` when the SDK isn't a bundled dependency.
+ */
+export function resolvePiSdkPackageDir(deps: ProbeDeps = {}): string | undefined {
+ const binPath = resolveCommandOnPath("pi", deps);
+ if (!binPath) return undefined;
+
+ try {
+ let dir = path.dirname(realpathSync(binPath));
+ const MAX_DEPTH = 8;
+ for (let i = 0; i < MAX_DEPTH; i++) {
+ if (isPiSdkPackageJson(path.join(dir, "package.json"))) return dir;
+
+ const siblingDir = path.join(dir, "node_modules", PI_SDK_PACKAGE_NAME);
+ if (isPiSdkPackageJson(path.join(siblingDir, "package.json"))) return siblingDir;
+
+ const parent = path.dirname(dir);
+ if (parent === dir) break; // hit filesystem root
+ dir = parent;
+ }
+ } catch {
+ // Broken symlink, permission error, etc. — treat as not found.
+ }
+ return undefined;
+}
+
+/** Read just the version out of the package.json `resolvePiSdkPackageDir` finds. */
+export function resolvePiSdkVersionFromPath(deps: ProbeDeps = {}): string | undefined {
+ const dir = resolvePiSdkPackageDir(deps);
+ if (!dir) return undefined;
+ try {
+ const pkg = JSON.parse(readFileSync(path.join(dir, "package.json"), "utf-8")) as { version?: string };
+ return pkg.version;
+ } catch {
+ return undefined;
+ }
+}
+
+/**
+ * Read the installed Pi SDK's package version. Optional — the SDK isn't a
+ * hard dep of the daemon, so we return undefined when it isn't installed on
+ * the host, and the runtime chip renders without a version.
+ *
+ * Two detection paths, tried in order:
+ * 1. `require()` resolution relative to this file — succeeds when Pi is a
+ * real dependency somewhere up the daemon's own `node_modules` tree
+ * (e.g. a future packaged build that bundles it).
+ * 2. `resolvePiSdkVersionFromPath()` — succeeds when `pi` is installed
+ * globally and only reachable via `PATH`, which is how most users
+ * actually install it.
*/
function readPiSdkVersion(): string | undefined {
try {
const req = createRequire(import.meta.url);
const pkg = req("@earendil-works/pi-coding-agent/package.json") as { version?: string };
- return pkg.version;
+ if (pkg.version) return pkg.version;
} catch {
- return undefined;
+ // Not resolvable as a normal Node dependency — fall through to the
+ // PATH-based fallback below.
}
+ return resolvePiSdkVersionFromPath();
}
/** Map a Pi SDK event to zero or more normalized events. */
@@ -104,15 +209,17 @@ export class PiDriver implements Driver {
/**
* In-process session factory. `deps` carries the Pi SDK constructors so this
- * file is dependency-free; the daemon injects the real implementations.
+ * file is dependency-free; the daemon injects the real implementations
+ * (see `piSdkDeps.ts`).
+ *
+ * Builds and wires the session but deliberately does NOT fire the initial
+ * prompt — `SdkRuntimeSession.emitEvents` fires on a plain `EventEmitter`,
+ * which drops events fired before any listener is attached (unlike a child
+ * process's buffered stdout pipe). The caller (`SdkManagedSession.start`)
+ * attaches its own `"runtime_event"` listener to the session this returns
+ * BEFORE sending the first turn via `.send()`, so nothing is lost.
*/
- async createSession(
- ctx: LaunchContext,
- deps: {
- buildSpawnEnv: () => Promise<NodeJS.ProcessEnv>;
- createAgentSession: (opts: any) => Promise<{ session: any; sessionId: string }>;
- },
- ): Promise<SdkRuntimeSession> {
+ 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
@@ -124,18 +231,23 @@ export class PiDriver implements Driver {
writeAgentFile(ctx.workingDirectory, ctx.standingPrompt);
}
const f = resolveLaunchFieldsOrDefault(ctx.config.runtimeConfig);
- const { session, sessionId } = await deps.createAgentSession({
+ const { session, sessionId } = (await deps.createAgentSession({
cwd: ctx.workingDirectory,
sessionId: ctx.config.sessionId,
model: f.model,
thinkingLevel: f.reasoningEffort,
spawnEnv, // injected into the custom bash tool
- });
+ })) as { session: PiSdkAgentSession; sessionId: string };
this.sessionId = sessionId;
const state = { sawTextDelta: false };
const handle: SdkSessionHandle = {
- prompt: (t: string) => session.prompt(t),
+ // `session.prompt()` throws "Agent is already processing" if a prior
+ // turn is still streaming (SdkManagedSession's fire-and-forget send is
+ // the primary defense — this is a belt-and-suspenders guard against
+ // any remaining window between our own turn_end detection and the SDK
+ // flipping `isStreaming`): queue as a follow-up instead of throwing.
+ prompt: (t: string) => session.prompt(t, session.isStreaming ? { streamingBehavior: "followUp" } : undefined),
steer: (t: string) => session.steer(t),
abort: () => session.abort(),
dispose: () => session.dispose(),
@@ -144,11 +256,10 @@ export class PiDriver implements Driver {
},
};
const runtimeSession = new SdkRuntimeSession(handle, this.sessionId!);
- session.subscribe((event: any) =>
+ session.subscribe((event: unknown) =>
runtimeSession.emitEvents(mapPiSdkEventToParsedEvents(event, this.sessionId!, state)),
);
- await session.prompt(ctx.prompt);
return runtimeSession;
}
diff --git a/src/daemon/src/drivers/piSdkDeps.test.ts b/src/daemon/src/drivers/piSdkDeps.test.ts
new file mode 100644
index 000000000..a76404934
--- /dev/null
+++ b/src/daemon/src/drivers/piSdkDeps.test.ts
@@ -0,0 +1,250 @@
+import { describe, it, expect, vi, afterEach } from "vitest";
+import * as fs from "fs";
+import * as os from "os";
+import * as path from "path";
+import { createPiSdkDriverDeps, loadPiSdkModule, type PiSdkModule, type PiSdkLoader } from "./piSdkDeps.js";
+import { CredentialBroker } from "../credentials/credentialProxy.js";
+import type { LaunchContext } from "../types.js";
+import { makeRuntimeConfig } from "../runtimeConfig.js";
+
+const tmpDirs: string[] = [];
+function mkTmp(): string {
+ const d = fs.mkdtempSync(path.join(os.tmpdir(), "pi-sdk-deps-"));
+ tmpDirs.push(d);
+ return d;
+}
+afterEach(() => {
+ for (const d of tmpDirs.splice(0)) fs.rmSync(d, { recursive: true, force: true });
+});
+
+function baseCtx(overrides: Partial<LaunchContext> = {}): LaunchContext {
+ return {
+ agentId: "agent_1",
+ launchId: "launch_1",
+ workingDirectory: mkTmp(),
+ standingPrompt: "",
+ prompt: "",
+ credentialProxy: {
+ broker: new CredentialBroker({ upstreamBaseUrl: "https://upstream.test", voucherDir: mkTmp() }),
+ proxyUrl: "http://127.0.0.1:9/proxy",
+ runnerKey: "sk_agent_test",
+ },
+ config: {},
+ ...overrides,
+ };
+}
+
+/** A fake SDK module — never touches the real @earendil-works/pi-coding-agent. */
+function fakeSdk(): {
+ loader: PiSdkLoader;
+ setRuntimeApiKey: ReturnType<typeof vi.fn>;
+ findModel: ReturnType<typeof vi.fn>;
+ sessionManagerCreate: ReturnType<typeof vi.fn>;
+ sessionManagerContinueRecent: 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 sessionManagerContinueRecent = vi.fn().mockReturnValue({ tag: "continued" });
+ 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 },
+ createBashToolDefinition,
+ createAgentSession,
+ };
+ return {
+ loader: async () => sdk,
+ setRuntimeApiKey,
+ findModel,
+ sessionManagerCreate,
+ sessionManagerContinueRecent,
+ createBashToolDefinition,
+ createAgentSession,
+ };
+}
+
+describe("createPiSdkDriverDeps — buildSpawnEnv", () => {
+ it("delegates to prepareCliTransport: credential voucher present, PATH includes the link dir", async () => {
+ const ctx = baseCtx();
+ const deps = createPiSdkDriverDeps(ctx, fakeSdk().loader);
+
+ const env = await deps.buildSpawnEnv();
+
+ expect(env.ALOOK_PROXY_URL).toBe("http://127.0.0.1:9/proxy");
+ expect(env.ALOOK_PROXY_TOKEN_FILE).toBeTruthy();
+ expect((env.PATH ?? "").split(path.delimiter)[0]).toContain(path.join(".alook", "bin"));
+ });
+});
+
+describe("createPiSdkDriverDeps — createAgentSession", () => {
+ it("sets the runtime API key when the runtime config carries a pi-builtin provider", async () => {
+ const fake = fakeSdk();
+ const ctx = baseCtx({
+ config: { runtimeConfig: makeRuntimeConfig({ runtime: "pi", provider: { kind: "pi-builtin", providerId: "google", apiKey: "key-123" } }) },
+ });
+ const deps = createPiSdkDriverDeps(ctx, fake.loader);
+
+ await deps.createAgentSession({ cwd: ctx.workingDirectory, spawnEnv: {} });
+
+ expect(fake.setRuntimeApiKey).toHaveBeenCalledWith("google", "key-123");
+ });
+
+ it("does not set a runtime API key when there is no pi-builtin provider", async () => {
+ const fake = fakeSdk();
+ const ctx = baseCtx();
+ const deps = createPiSdkDriverDeps(ctx, fake.loader);
+
+ await deps.createAgentSession({ cwd: ctx.workingDirectory, spawnEnv: {} });
+
+ expect(fake.setRuntimeApiKey).not.toHaveBeenCalled();
+ });
+
+ it("resolves a 'provider/id' model string via modelRegistry.find", async () => {
+ const fake = fakeSdk();
+ const ctx = baseCtx();
+ const deps = createPiSdkDriverDeps(ctx, fake.loader);
+
+ await deps.createAgentSession({ cwd: ctx.workingDirectory, model: "google/gemini-2.5-pro", spawnEnv: {} });
+
+ expect(fake.findModel).toHaveBeenCalledWith("google", "gemini-2.5-pro");
+ expect(fake.createAgentSession).toHaveBeenCalledWith(
+ expect.objectContaining({ model: { provider: "google", id: "gemini-2.5-pro" } }),
+ );
+ });
+
+ it("omits model (lets the SDK pick its own default) for an unparsable model string", async () => {
+ const fake = fakeSdk();
+ const ctx = baseCtx();
+ const deps = createPiSdkDriverDeps(ctx, fake.loader);
+
+ await deps.createAgentSession({ cwd: ctx.workingDirectory, model: "not-a-provider-id-pair", spawnEnv: {} });
+
+ expect(fake.findModel).not.toHaveBeenCalled();
+ expect(fake.createAgentSession).toHaveBeenCalledWith(expect.objectContaining({ model: undefined }));
+ });
+
+ it("uses SessionManager.continueRecent when a sessionId is provided", async () => {
+ const fake = fakeSdk();
+ 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.sessionManagerCreate).not.toHaveBeenCalled();
+ });
+
+ it("uses SessionManager.create for a fresh session when no sessionId is provided", async () => {
+ const fake = fakeSdk();
+ const ctx = baseCtx();
+ const deps = createPiSdkDriverDeps(ctx, fake.loader);
+
+ await deps.createAgentSession({ cwd: ctx.workingDirectory, spawnEnv: {} });
+
+ expect(fake.sessionManagerCreate).toHaveBeenCalledWith(ctx.workingDirectory);
+ expect(fake.sessionManagerContinueRecent).not.toHaveBeenCalled();
+ });
+
+ it("passes a customTools bash tool whose spawnHook merges the given spawnEnv on top of the base env", async () => {
+ const fake = fakeSdk();
+ const ctx = baseCtx();
+ const deps = createPiSdkDriverDeps(ctx, fake.loader);
+ const spawnEnv = { ALOOK_PROXY_URL: "http://proxy" };
+
+ await deps.createAgentSession({ cwd: ctx.workingDirectory, spawnEnv });
+
+ expect(fake.createBashToolDefinition).toHaveBeenCalledWith(
+ ctx.workingDirectory,
+ expect.objectContaining({ spawnHook: expect.any(Function) }),
+ );
+ const { spawnHook } = fake.createBashToolDefinition.mock.calls[0][1] as {
+ spawnHook: (c: { command: string; cwd: string; env: NodeJS.ProcessEnv }) => { env: NodeJS.ProcessEnv };
+ };
+ const result = spawnHook({ command: "ls", cwd: "/tmp", env: { PATH: "/usr/bin" } });
+ expect(result.env).toEqual({ PATH: "/usr/bin", ALOOK_PROXY_URL: "http://proxy" });
+ });
+
+ it("returns the sessionId from session.sessionId when createAgentSession doesn't return one directly", async () => {
+ const fake = fakeSdk();
+ const ctx = baseCtx();
+ const deps = createPiSdkDriverDeps(ctx, fake.loader);
+
+ const result = await deps.createAgentSession({ cwd: ctx.workingDirectory, spawnEnv: {} });
+
+ expect(result.sessionId).toBe("sess-from-sdk");
+ });
+
+ it("throws a clear error when the SDK produces no sessionId at all", async () => {
+ const fake = fakeSdk();
+ fake.createAgentSession.mockResolvedValue({ session: {} });
+ const ctx = baseCtx();
+ const deps = createPiSdkDriverDeps(ctx, fake.loader);
+
+ await expect(deps.createAgentSession({ cwd: ctx.workingDirectory, spawnEnv: {} })).rejects.toThrow(/sessionId/);
+ });
+});
+
+describe("loadPiSdkModule — global-install fallback", () => {
+ it("falls back to resolving + import()-ing the real install dir when the bare specifier isn't resolvable (never true in this test env)", async () => {
+ // The package is never a real dependency of this workspace (see the
+ // sibling detection tests in pi.test.ts), so `import("@earendil-works/
+ // pi-coding-agent")` genuinely rejects here — this exercises the real
+ // fallback path, not a mocked one.
+ const pkgDir = path.join(mkTmp(), "lib", "node_modules", "@earendil-works", "pi-coding-agent");
+ fs.mkdirSync(path.join(pkgDir, "dist"), { recursive: true });
+ fs.writeFileSync(path.join(pkgDir, "package.json"), JSON.stringify({ name: "@earendil-works/pi-coding-agent", main: "./dist/index.js" }));
+ fs.writeFileSync(path.join(pkgDir, "dist", "index.js"), "export const MARKER = 'loaded-from-global-install';\n");
+
+ vi.resetModules();
+ vi.doMock("./pi.js", () => ({ resolvePiSdkPackageDir: () => pkgDir }));
+ const fresh = await import("./piSdkDeps.js");
+
+ const sdk = (await fresh.loadPiSdkModule()) as unknown as { MARKER: string };
+ expect(sdk.MARKER).toBe("loaded-from-global-install");
+
+ vi.doUnmock("./pi.js");
+ vi.resetModules();
+ });
+
+ it("throws a clear error when pi isn't found on PATH either", async () => {
+ vi.resetModules();
+ vi.doMock("./pi.js", () => ({ resolvePiSdkPackageDir: () => undefined }));
+ const fresh = await import("./piSdkDeps.js");
+
+ await expect(fresh.loadPiSdkModule()).rejects.toThrow(/pi-coding-agent/);
+
+ vi.doUnmock("./pi.js");
+ vi.resetModules();
+ });
+
+ // Regression test: a failed load must NOT be memoized forever — a daemon
+ // that started before the SDK was installed (or before PATH was fixed)
+ // should be able to launch a pi agent on a later attempt without a
+ // restart, once `resolvePiSdkPackageDir` starts succeeding.
+ it("retries from scratch after a failed load instead of replaying the same rejection forever", async () => {
+ const pkgDir = path.join(mkTmp(), "lib", "node_modules", "@earendil-works", "pi-coding-agent");
+ fs.mkdirSync(path.join(pkgDir, "dist"), { recursive: true });
+ fs.writeFileSync(path.join(pkgDir, "package.json"), JSON.stringify({ name: "@earendil-works/pi-coding-agent", main: "./dist/index.js" }));
+ fs.writeFileSync(path.join(pkgDir, "dist", "index.js"), "export const MARKER = 'loaded-from-global-install-retry';\n");
+
+ vi.resetModules();
+ let resolvable = false;
+ vi.doMock("./pi.js", () => ({ resolvePiSdkPackageDir: () => (resolvable ? pkgDir : undefined) }));
+ const fresh = await import("./piSdkDeps.js");
+
+ await expect(fresh.loadPiSdkModule()).rejects.toThrow(/pi-coding-agent/);
+
+ resolvable = true;
+ const sdk = (await fresh.loadPiSdkModule()) as unknown as { MARKER: string };
+ expect(sdk.MARKER).toBe("loaded-from-global-install-retry");
+
+ vi.doUnmock("./pi.js");
+ vi.resetModules();
+ });
+});
diff --git a/src/daemon/src/drivers/piSdkDeps.ts b/src/daemon/src/drivers/piSdkDeps.ts
new file mode 100644
index 000000000..dcda497d6
--- /dev/null
+++ b/src/daemon/src/drivers/piSdkDeps.ts
@@ -0,0 +1,157 @@
+/**
+ * Real `SdkDriverDeps` implementation for `PiDriver` — the only piece that
+ * actually talks to `@earendil-works/pi-coding-agent`. Kept out of `pi.ts` so
+ * that file stays free of a hard SDK import (mirrors the "deps carry the
+ * constructors" design already documented there); this module is where the
+ * daemon actually loads and drives the vendor package.
+ */
+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 { prepareCliTransport, DEFAULT_CLI_CONFIG } from "./cliTransport.js";
+
+const PI_SDK_PACKAGE_NAME = "@earendil-works/pi-coding-agent";
+
+/** The slice of the vendor SDK's module exports this file actually calls. */
+export interface PiSdkModule {
+ AuthStorage: { create(authPath?: string): PiAuthStorage };
+ ModelRegistry: { create(authStorage: PiAuthStorage, modelsPath?: string): PiModelRegistry };
+ SessionManager: {
+ create(cwd: string): unknown;
+ continueRecent(cwd: string): unknown;
+ };
+ createBashToolDefinition(cwd: string, options?: PiBashToolOptions): unknown;
+ createAgentSession(options: Record<string, unknown>): Promise<{ session: unknown; sessionId?: string }>;
+}
+export interface PiAuthStorage {
+ setRuntimeApiKey(provider: string, apiKey: string): void;
+}
+export interface PiModelRegistry {
+ find(provider: string, modelId: string): unknown | undefined;
+}
+interface PiBashSpawnContext {
+ command: string;
+ cwd: string;
+ env: NodeJS.ProcessEnv;
+}
+interface PiBashToolOptions {
+ spawnHook?: (context: PiBashSpawnContext) => PiBashSpawnContext;
+}
+
+/** Injectable loader for tests — never actually imports the real package. */
+export type PiSdkLoader = () => Promise<PiSdkModule>;
+
+let cachedSdkPromise: Promise<PiSdkModule> | null = null;
+
+async function importPiSdkFromGlobalInstall(): Promise<PiSdkModule> {
+ const dir = resolvePiSdkPackageDir();
+ if (!dir) {
+ throw new Error(
+ `${PI_SDK_PACKAGE_NAME} not found — install it (e.g. \`npm install -g ${PI_SDK_PACKAGE_NAME}\`) before launching a pi agent`,
+ );
+ }
+ const pkg = JSON.parse(readFileSync(path.join(dir, "package.json"), "utf-8")) as {
+ main?: string;
+ exports?: { "."?: { import?: string } };
+ };
+ const entry = pkg.exports?.["."]?.import ?? pkg.main ?? "./dist/index.js";
+ const entryPath = path.join(dir, entry);
+ return import(pathToFileURL(entryPath).href) as Promise<PiSdkModule>;
+}
+
+/**
+ * Loads (and memoizes for the life of the daemon process) the pi SDK module.
+ * Two-path detection mirroring `readPiSdkVersion`: try the bare specifier
+ * first (works if it's ever a real bundled dependency), then fall back to
+ * resolving the real global-install directory and `import()`-ing its entry
+ * file directly.
+ *
+ * Only a SUCCESSFUL load is memoized. A failure (SDK not installed yet, a
+ * transient fs error, `pi` not on PATH at daemon startup) clears the cache
+ * before rethrowing, so the next spawn attempt re-resolves from scratch
+ * instead of replaying the same rejected promise forever — otherwise a user
+ * who installs/fixes the SDK after the daemon's first failed attempt would
+ * need to restart the daemon before any pi agent could ever launch again.
+ */
+export function loadPiSdkModule(): Promise<PiSdkModule> {
+ if (!cachedSdkPromise) {
+ cachedSdkPromise = (async () => {
+ try {
+ return (await import(PI_SDK_PACKAGE_NAME)) as PiSdkModule;
+ } catch {
+ return importPiSdkFromGlobalInstall();
+ }
+ })().catch((err: unknown) => {
+ cachedSdkPromise = null;
+ throw err;
+ });
+ }
+ return cachedSdkPromise;
+}
+
+/** Parse a `"provider/id"` model string; undefined pieces mean "use the SDK's own default". */
+function parseModelString(model: string | undefined): { provider: string; id: string } | undefined {
+ if (!model) return undefined;
+ const idx = model.indexOf("/");
+ if (idx <= 0 || idx === model.length - 1) return undefined;
+ return { provider: model.slice(0, idx), id: model.slice(idx + 1) };
+}
+
+/**
+ * Build the real `SdkDriverDeps` for a Pi launch. Closes over `ctx` so
+ * `buildSpawnEnv` needs no arguments (matches `PiDriver.createSession`'s
+ * existing contract) — a fresh instance is built per launch, so nothing here
+ * is process-global mutable state (safe for concurrent agents with different
+ * credentials).
+ */
+export function createPiSdkDriverDeps(ctx: LaunchContext, loadSdk: PiSdkLoader = loadPiSdkModule): SdkDriverDeps {
+ return {
+ async buildSpawnEnv(): Promise<NodeJS.ProcessEnv> {
+ // Pi has no child process of its own, but its bash tool does — reuse the
+ // exact same credential-voucher + PATH-link machinery every CLI driver
+ // gets via `prepareCliTransport`, so the agent's `alook` bash calls
+ // authenticate the same zero-trust way.
+ const cliConfig = ctx.agentCliPath ? { ...DEFAULT_CLI_CONFIG, hostCliPath: ctx.agentCliPath } : DEFAULT_CLI_CONFIG;
+ const { spawnEnv } = await prepareCliTransport(ctx, {}, cliConfig);
+ return spawnEnv;
+ },
+
+ async createAgentSession(opts: Record<string, unknown>): Promise<{ session: unknown; sessionId: string }> {
+ const sdk = await loadSdk();
+ const authStorage = sdk.AuthStorage.create();
+ const provider = ctx.config.runtimeConfig?.provider;
+ if (provider?.kind === "pi-builtin") {
+ authStorage.setRuntimeApiKey(provider.providerId, provider.apiKey);
+ }
+ const modelRegistry = sdk.ModelRegistry.create(authStorage);
+
+ const parsed = parseModelString(opts.model as string | undefined);
+ 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);
+
+ const spawnEnv = opts.spawnEnv as NodeJS.ProcessEnv;
+ const bashTool = sdk.createBashToolDefinition(cwd, {
+ spawnHook: (spawnCtx) => ({ ...spawnCtx, env: { ...spawnCtx.env, ...spawnEnv } }),
+ });
+
+ const { session, sessionId } = await sdk.createAgentSession({
+ cwd,
+ model,
+ thinkingLevel: opts.thinkingLevel,
+ authStorage,
+ modelRegistry,
+ sessionManager,
+ customTools: [bashTool],
+ });
+ // The SDK returns the id on the session itself (`session.sessionId`),
+ // not on the createAgentSession result — fall back to that.
+ const resolvedSessionId = sessionId ?? (session as { sessionId?: string }).sessionId;
+ if (!resolvedSessionId) throw new Error("pi SDK createAgentSession did not produce a sessionId");
+ return { session, sessionId: resolvedSessionId };
+ },
+ };
+}
diff --git a/src/daemon/src/drivers/probe.test.ts b/src/daemon/src/drivers/probe.test.ts
new file mode 100644
index 000000000..fdd0eeea6
--- /dev/null
+++ b/src/daemon/src/drivers/probe.test.ts
@@ -0,0 +1,95 @@
+import { describe, it, expect, vi } from "vitest";
+import { execFileSync } from "child_process";
+import { resolveSpawnSpec, probeCommandVersion } from "./probe";
+
+vi.mock("child_process", () => ({ execFileSync: vi.fn() }));
+
+/**
+ * `resolveSpawnSpec` is what makes Cursor/Copilot/Antigravity/Kimi/OpenCode
+ * (and Codex/Gemini) spawnable on Windows when the CLI resolves to a
+ * `.cmd`/`.bat` shim, which `child_process.spawn` can only exec through a
+ * shell. See plans/other-drivers-audit-fixes.md finding #2.
+ */
+describe("resolveSpawnSpec", () => {
+ it("sets shell: true on win32 when the resolved binary is a .cmd shim", () => {
+ const spec = resolveSpawnSpec(
+ "cursor-agent",
+ ["--print"],
+ { which: () => "C:\\Users\\me\\AppData\\Roaming\\npm\\cursor-agent.cmd" },
+ "win32",
+ );
+ expect(spec).toEqual({
+ command: "C:\\Users\\me\\AppData\\Roaming\\npm\\cursor-agent.cmd",
+ args: ["--print"],
+ shell: true,
+ });
+ });
+
+ it("sets shell: true on win32 when the resolved binary is a .bat shim", () => {
+ const spec = resolveSpawnSpec("kimi", [], { 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");
+ 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");
+ 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");
+ expect(spec).toEqual({ command: "opencode", args: ["run"], shell: false });
+ });
+});
+
+/**
+ * Regression tests: `probeCommandVersion` — used by every non-Pi driver's
+ * `probe()` via `probeCliRuntime`/`probeClaude` — must agree with
+ * `resolveSpawnSpec` about whether a resolved binary needs a shell. Before
+ * this fix, a `.cmd`/`.bat` shim spawned fine (via `resolveSpawnSpec`) but
+ * still failed its own health probe on Windows (`execFileSync` with no
+ * `shell` option can't exec a `.cmd`/`.bat` directly), which reported the
+ * runtime as `unhealthy` and hid it from the UI even though it actually
+ * worked.
+ */
+describe("probeCommandVersion — Windows shim shell parity with resolveSpawnSpec", () => {
+ it("runs .cmd shims through a shell on win32", () => {
+ vi.mocked(execFileSync).mockReturnValue("1.2.3\n");
+
+ probeCommandVersion("C:\\Users\\me\\AppData\\Roaming\\npm\\cursor-agent.cmd", [], {}, "win32");
+
+ expect(execFileSync).toHaveBeenCalledWith(
+ "C:\\Users\\me\\AppData\\Roaming\\npm\\cursor-agent.cmd",
+ ["--version"],
+ expect.objectContaining({ shell: true }),
+ );
+ });
+
+ it("runs .bat shims through a shell on win32", () => {
+ vi.mocked(execFileSync).mockReturnValue("1.2.3\n");
+
+ probeCommandVersion("C:\\tools\\kimi.bat", [], {}, "win32");
+
+ expect(execFileSync).toHaveBeenCalledWith("C:\\tools\\kimi.bat", ["--version"], expect.objectContaining({ shell: true }));
+ });
+
+ it("does not use a shell for a native .exe on win32", () => {
+ vi.mocked(execFileSync).mockReturnValue("1.2.3\n");
+
+ probeCommandVersion("C:\\tools\\copilot.exe", [], {}, "win32");
+
+ expect(execFileSync).toHaveBeenCalledWith("C:\\tools\\copilot.exe", ["--version"], expect.objectContaining({ shell: false }));
+ });
+
+ it("never uses a shell on POSIX, even for a path that looks like a shim", () => {
+ vi.mocked(execFileSync).mockReturnValue("1.2.3\n");
+
+ probeCommandVersion("/usr/local/bin/agy.cmd", [], {}, "darwin");
+
+ expect(execFileSync).toHaveBeenCalledWith("/usr/local/bin/agy.cmd", ["--version"], expect.objectContaining({ shell: false }));
+ });
+});
diff --git a/src/daemon/src/drivers/probe.ts b/src/daemon/src/drivers/probe.ts
index 7fcb7de48..cc7a8b0f0 100644
--- a/src/daemon/src/drivers/probe.ts
+++ b/src/daemon/src/drivers/probe.ts
@@ -44,6 +44,15 @@ export type VersionProbeResult =
| { ok: true; version: string }
| { ok: false; error: string };
+/** True when `command` needs a shell to exec on this platform — Windows
+ * can't run a `.cmd`/`.bat` shim (which is what most npm global installs
+ * resolve to) directly via `CreateProcess`. Shared by `resolveSpawnSpec`
+ * (actual agent spawn) and `probeCommandVersion` (health-check spawn) so the
+ * two never disagree about whether a given resolved path is runnable. */
+function needsWindowsShimShell(command: string, platform: NodeJS.Platform): boolean {
+ return platform === "win32" && /\.(cmd|bat)$/i.test(command);
+}
+
/**
* Actually spawn `<command> --version` and read stdout. Returns `ok: true`
* only when the child exits 0 AND emits a non-empty first line. A spawn
@@ -55,15 +64,23 @@ export type VersionProbeResult =
* npm packages sometimes ship a JS wrapper whose `which` succeeds but whose
* vendored native binary is broken. Requiring `--version` to actually run
* catches that class of failure at startup instead of at first spawn.
+ *
+ * Runs through a shell on Windows when `command` is a `.cmd`/`.bat` shim —
+ * same detection `resolveSpawnSpec` uses for the real agent spawn. Without
+ * this, a runtime whose actual `spawn()` succeeds (because it already
+ * routes through `resolveSpawnSpec`) would still probe as `unhealthy` here,
+ * hiding an available runtime from the UI.
*/
export function probeCommandVersion(
command: string,
args: string[] = [],
- deps: ProbeDeps = {}
+ deps: ProbeDeps = {},
+ platform: NodeJS.Platform = process.platform,
): VersionProbeResult {
void deps;
try {
- const out = execFileSync(command, [...args, "--version"], { encoding: "utf8", timeout: 5000 });
+ const shell = needsWindowsShimShell(command, platform);
+ const out = execFileSync(command, [...args, "--version"], { encoding: "utf8", timeout: 5000, shell });
const line = out.split("\n")[0]?.trim();
if (!line) return { ok: false, error: "empty_version_output" };
return { ok: true, version: line };
@@ -113,8 +130,7 @@ export function resolveSpawnSpec(
platform: NodeJS.Platform = process.platform,
): SpawnSpec {
const resolved = resolveCommandOnPath(command, deps) ?? command;
- const shell = platform === "win32" && /\.(cmd|bat)$/i.test(resolved);
- return { command: resolved, args, shell };
+ return { command: resolved, args, shell: needsWindowsShimShell(resolved, platform) };
}
/** Detect the Claude Code CLI, including macOS app-bundle fallbacks. */
diff --git a/src/daemon/src/manager/managerCapabilityContract.test.ts b/src/daemon/src/manager/managerCapabilityContract.test.ts
new file mode 100644
index 000000000..50daedf3f
--- /dev/null
+++ b/src/daemon/src/manager/managerCapabilityContract.test.ts
@@ -0,0 +1,238 @@
+/**
+ * Driver-agnostic contract tests for `AgentProcessManager`'s busy/idle
+ * delivery orchestration — see plans/manager-persistent-direct-contract-test.md.
+ *
+ * These tests don't target one driver file; they group the REAL drivers from
+ * `drivers/index.ts` by their declared `AgentRuntimeCaps`-relevant profile
+ * (`lifecycle.kind`/`stdin`/`inFlightWake`, `supportsStdinNotification`,
+ * `busyDeliveryMode`) and drive `AgentProcessManager` itself (via a
+ * `sessionFactory`, bypassing real process/SDK spawning) to assert the
+ * orchestration contract each profile is supposed to get.
+ *
+ * Why this exists: `PiDriver` and `CodexDriver` both declare
+ * `{kind: "persistent", stdin: "direct", inFlightWake: "steer"}` +
+ * `busyDeliveryMode: "direct"`. A real production bug shipped because
+ * `SdkManagedSession.start()` (Pi's session adapter) used to await the
+ * ENTIRE first turn before resolving, which delayed `AgentProcessManager`
+ * dispatching `{type: "spawned"}` (the thing that makes it treat the agent
+ * as busy) until the turn was already over — so a wake that arrived mid-turn
+ * was queued instead of steered, then misrouted as an `idle` send right
+ * after `turn_end`, racing the vendor SDK's own "already processing" guard.
+ * That fix lives in `sdkManagedSession.ts`/`pi.ts` and is regression-tested
+ * in `sdkManagedSession.test.ts` — but that only protects Pi. This file
+ * protects the *manager's* half of the contract for EVERY driver sharing
+ * that capability profile today (Pi, Codex) and any future one, without
+ * needing driver-specific test plumbing.
+ */
+import { describe, it, expect } from "vitest";
+import { AgentProcessManager, type ManagedSession, type SessionFactory } from "./managerRuntime.js";
+import { listRuntimeIds, getDriver } from "../drivers/index.js";
+import type { Driver, LaunchContext } from "../types.js";
+
+interface CapabilityProfile {
+ lifecycleKind: "persistent" | "per_turn";
+ stdin?: "direct" | "gated";
+ inFlightWake: string;
+ supportsStdinNotification: boolean;
+ busyDeliveryMode: "direct" | "gated" | "none";
+}
+
+function profileOf(driver: Driver): CapabilityProfile {
+ const lifecycle = driver.lifecycle;
+ return {
+ lifecycleKind: lifecycle.kind,
+ stdin: lifecycle.kind === "persistent" ? lifecycle.stdin : undefined,
+ inFlightWake: lifecycle.inFlightWake,
+ supportsStdinNotification: driver.supportsStdinNotification,
+ busyDeliveryMode: driver.busyDeliveryMode,
+ };
+}
+
+/** Group every registered driver by its capability profile (dedup key). */
+function capabilityBuckets(): Array<{ profile: CapabilityProfile; driverIds: string[]; sample: Driver }> {
+ const buckets = new Map<string, { profile: CapabilityProfile; driverIds: string[]; sample: Driver }>();
+ for (const id of listRuntimeIds()) {
+ const driver = getDriver(id);
+ const profile = profileOf(driver);
+ const key = JSON.stringify(profile);
+ const existing = buckets.get(key);
+ if (existing) existing.driverIds.push(id);
+ else buckets.set(key, { profile, driverIds: [id], sample: driver });
+ }
+ return [...buckets.values()];
+}
+
+function isDirectSteerProfile(p: CapabilityProfile): boolean {
+ return (
+ p.lifecycleKind === "persistent" &&
+ p.stdin === "direct" &&
+ p.inFlightWake === "steer" &&
+ p.supportsStdinNotification &&
+ p.busyDeliveryMode === "direct"
+ );
+}
+
+function isGatedQueueProfile(p: CapabilityProfile): boolean {
+ return (
+ p.lifecycleKind === "persistent" &&
+ p.stdin === "gated" &&
+ p.inFlightWake === "queue" &&
+ p.supportsStdinNotification &&
+ p.busyDeliveryMode === "gated"
+ );
+}
+
+/** Controllable fake `ManagedSession` — records every `send()` call and lets
+ * the test decide exactly when `.start()` resolves, independent of whether
+ * any "turn_end" has fired. This is what lets these tests exercise the
+ * manager's contract without a real child process or SDK. */
+interface FakeSession extends ManagedSession {
+ fire(evt: string, ...args: unknown[]): void;
+ startResolver?: () => void;
+ sendCalls: Array<{ text: string; mode: "busy" | "idle" }>;
+}
+
+function fakeSession(): FakeSession {
+ const listeners = new Map<string, Array<(...args: unknown[]) => void>>();
+ const s: FakeSession = {
+ sendCalls: [],
+ on(event, cb) {
+ const arr = listeners.get(event) ?? [];
+ arr.push(cb);
+ listeners.set(event, arr);
+ },
+ start() {
+ return new Promise<void>((resolve) => {
+ s.startResolver = resolve;
+ });
+ },
+ send(input) {
+ s.sendCalls.push(input);
+ },
+ stop() { },
+ get currentSessionId() {
+ return "sess_1";
+ },
+ fire(evt, ...args) {
+ for (const cb of listeners.get(evt) ?? []) cb(...args);
+ },
+ };
+ return s;
+}
+
+function makeManager(driver: Driver, session: FakeSession) {
+ const factory: SessionFactory = () => session;
+ const mgr = new AgentProcessManager({
+ driverFor: () => driver,
+ baseContextFor: () => ({
+ workingDirectory: "/tmp/agent_1",
+ agentId: "a1",
+ standingPrompt: "",
+ config: {} as LaunchContext["config"],
+ }),
+ sessionFactory: factory,
+ });
+ mgr.register("a1");
+ return mgr;
+}
+
+const buckets = capabilityBuckets();
+const directSteerBuckets = buckets.filter((b) => isDirectSteerProfile(b.profile));
+const gatedQueueBuckets = buckets.filter((b) => isGatedQueueProfile(b.profile));
+
+describe("AgentProcessManager capability contract — persistent/direct/steer runtimes", () => {
+ if (directSteerBuckets.length === 0) {
+ it.skip("no driver currently declares this profile", () => { });
+ }
+
+ for (const bucket of directSteerBuckets) {
+ const label = bucket.driverIds.join(", ");
+
+ it(`[${label}] a wake delivered after the session is running (start() resolved, no turn_end yet) is steered immediately as mode:"busy" — not queued until turn_end`, async () => {
+ const session = fakeSession();
+ const mgr = makeManager(bucket.sample, session);
+
+ mgr.deliver("a1", { seq: 1, text: "first" });
+ // Simulate the FIXED contract: start() resolves once the turn is
+ // accepted, well before the underlying turn (whatever it does) is
+ // actually done. No "turn_end" runtime_event fires in this test.
+ session.startResolver?.();
+ await Promise.resolve();
+
+ mgr.deliver("a1", { seq: 2, text: "mid-turn wake" });
+
+ expect(session.sendCalls).toEqual([{ text: "mid-turn wake", mode: "busy" }]);
+ });
+
+ it(`[${label}] a wake delivered before start() resolves is queued (not sent early) and is coalesced into exactly one delivery once running`, async () => {
+ const session = fakeSession();
+ const mgr = makeManager(bucket.sample, session);
+
+ mgr.deliver("a1", { seq: 1, text: "first" }); // triggers spawn; status -> "starting"
+ mgr.deliver("a1", { seq: 2, text: "queued while starting" }); // status still "starting" -> queued, no send yet
+ expect(session.sendCalls).toEqual([]);
+
+ session.startResolver?.();
+ await Promise.resolve();
+ // Now running. A further wake should coalesce with the queued one into
+ // a single busy send, not one send per queued message.
+ mgr.deliver("a1", { seq: 3, text: "after running" });
+
+ expect(session.sendCalls).toEqual([
+ { text: "queued while starting\nafter running", mode: "busy" },
+ ]);
+ });
+ }
+});
+
+describe("AgentProcessManager capability contract — persistent/gated/queue runtimes", () => {
+ if (gatedQueueBuckets.length === 0) {
+ it.skip("no driver currently declares this profile", () => { });
+ }
+
+ for (const bucket of gatedQueueBuckets) {
+ const label = bucket.driverIds.join(", ");
+
+ /**
+ * KNOWN GAP — not the bug this plan set out to fix, but found while
+ * writing a contract test that assumed `lifecycle.stdin: "gated"` /
+ * `inFlightWake: "queue"` changed the manager's delivery timing the way
+ * Claude's own doc comment implies ("held until a safe boundary — see
+ * runtime/apmStateMachine and runtime/turnState"). It doesn't:
+ * `managerPolicy.ts::onWake`'s "running" branch only checks
+ * `lifecycleKind === "persistent" && supportsStdinNotification` — it
+ * never reads `inFlightWake` or `busyDeliveryMode` — so a gated driver's
+ * mid-turn wake is sent exactly as immediately as a direct/steer one.
+ * `ChildProcessRuntimeSession.send()` also writes to stdin unconditionally,
+ * regardless of mode. `apmStateMachine.ts`/`turnState.ts` exist in this
+ * package (exported from `index.ts`) but have ZERO call sites in
+ * `managerRuntime.ts`/`runtimeSession.ts` — they're a real, tested reducer
+ * that's wired up in the OTHER daemon implementation
+ * (`src/cli/daemon/session-runner.ts` branches on `busyMode === "gated"`
+ * and drives `apmStateMachine`/`turnState` for real) but were never
+ * connected here. This test asserts what ACTUALLY happens today (not
+ * what the naming implies) precisely so it breaks loudly — instead of
+ * silently drifting further — if/when gating is either wired up for
+ * real or intentionally dropped from the type model.
+ */
+ it(`[${label}] TODAY sends a mid-turn wake immediately (mode:"busy"), identically to a direct/steer runtime — "gated" delivery is declared but not wired up in this package's ManagedSession path`, async () => {
+ const session = fakeSession();
+ const mgr = makeManager(bucket.sample, session);
+
+ mgr.deliver("a1", { seq: 1, text: "first" });
+ session.startResolver?.();
+ await Promise.resolve();
+
+ mgr.deliver("a1", { seq: 2, text: "mid-turn wake" });
+
+ expect(session.sendCalls).toEqual([{ text: "mid-turn wake", mode: "busy" }]);
+ });
+ }
+});
+
+describe("AgentProcessManager capability contract — bucket sanity", () => {
+ it("the registered drivers still contain at least one direct/steer profile and one gated/queue profile (catches an accidental capability drift silently disabling the contracts above)", () => {
+ expect(directSteerBuckets.length).toBeGreaterThan(0);
+ expect(gatedQueueBuckets.length).toBeGreaterThan(0);
+ });
+});
\ No newline at end of file
diff --git a/src/daemon/src/manager/managerRuntime.test.ts b/src/daemon/src/manager/managerRuntime.test.ts
index f5ca7d30c..45a412f09 100644
--- a/src/daemon/src/manager/managerRuntime.test.ts
+++ b/src/daemon/src/manager/managerRuntime.test.ts
@@ -1,6 +1,7 @@
import { describe, it, expect, vi } from "vitest";
import { AgentProcessManager, type ManagedSession, type SessionFactory } from "./managerRuntime.js";
-import type { Driver, LaunchContext } from "../types.js";
+import { SdkRuntimeSession, type SdkSessionHandle } from "../runtime/sdkRuntimeSession.js";
+import type { Driver, LaunchContext, SdkDriverDeps } from "../types.js";
import type { Logger } from "../logger.js";
/** Stub logger — records calls per level for assertions. */
@@ -60,8 +61,8 @@ function fakeSession(): FakeSession {
s.startRejector = reject;
});
},
- send() {},
- stop() {},
+ send() { },
+ stop() { },
get currentSessionId() {
return null;
},
@@ -259,6 +260,56 @@ describe("AgentProcessManager — logging", () => {
expect((ended[0]![1][0] as any).reason).toBe("turn_end");
});
+ // Regression test: a `stop()`/`terminate_stalled` effect can race a
+ // still-in-flight `session.start()` and win — its `exit` handler runs
+ // first, deleting the session from the manager's map and dispatching
+ // `{type: "exit"}` (FSM → idle) — all BEFORE the original `start()` call
+ // finally resolves. Without an identity check, `doSpawn`'s `.then()`
+ // would still unconditionally dispatch `{type: "spawned"}` afterward,
+ // reviving the FSM into "running" for a session nobody tracks anymore —
+ // any later wake would then just queue forever behind a dead spawn
+ // instead of triggering a fresh one.
+ it("a stop that races and wins against an in-flight start() does not let start()'s later resolution revive the FSM into 'running'", async () => {
+ const logger = stubLogger();
+ const sessions: FakeSession[] = [];
+ const factory: SessionFactory = () => {
+ const s = fakeSession();
+ sessions.push(s);
+ return s;
+ };
+ const mgr = new AgentProcessManager({
+ driverFor: () => fakeDriver("codex"),
+ baseContextFor: () => ({
+ workingDirectory: "/tmp",
+ agentId: "a1",
+ standingPrompt: "",
+ config: {} as LaunchContext["config"],
+ credentialProxy: {} as LaunchContext["credentialProxy"],
+ }),
+ sessionFactory: factory,
+ logger,
+ });
+ mgr.register("a1");
+
+ mgr.deliver("a1", { seq: 1, text: "hello" }); // spawns sessions[0]; start() left pending
+ const session1 = sessions[0]!;
+
+ // The race: exit fires (as it would from a stop()/terminate_stalled
+ // effect) WHILE start() is still pending.
+ session1.fire("exit");
+ // Only now does the slow start() finally resolve.
+ session1.startResolver?.();
+ await Promise.resolve();
+ await Promise.resolve();
+
+ // A later wake must trigger a genuinely fresh spawn.
+ mgr.deliver("a1", { seq: 2, text: "are you there" });
+
+ expect(sessions).toHaveLength(2);
+ const spawnLogs = logger.calls.info.filter(([m]) => m === "spawning agent");
+ expect(spawnLogs).toHaveLength(2);
+ });
+
it("does NOT double-log session-ended when the process exit follows an explicit stop/terminate_stalled", async () => {
vi.useFakeTimers();
try {
@@ -361,3 +412,90 @@ describe("AgentProcessManager — logging", () => {
}
});
});
+
+// A driver in the shape of PiDriver — declares `createSession` instead of a
+// usable `spawn`, mirroring the real "in-process SDK" contract.
+function fakeSdkDriver(id: string): { driver: Driver & { createSession: NonNullable<Driver["createSession"]> }; createSession: ReturnType<typeof vi.fn> } {
+ let session: SdkRuntimeSession;
+ const handle: SdkSessionHandle = {
+ prompt: (text: string) => {
+ session.emitEvents([{ kind: "text", text }]);
+ },
+ steer: () => { },
+ };
+ const createSession = vi.fn(async () => {
+ session = new SdkRuntimeSession(handle, "sdk-sess-1");
+ return session;
+ });
+ const driver = {
+ ...fakeDriver(id),
+ spawn: async () => {
+ throw new Error("in-process SDK driver — spawn unsupported");
+ },
+ createSession,
+ } as unknown as Driver & { createSession: NonNullable<Driver["createSession"]> };
+ return { driver, createSession };
+}
+
+describe("AgentProcessManager — in-process SDK driver dispatch (Driver.createSession)", () => {
+ it("throws a clear error when a driver declares createSession but no sessionFactory/sdkDriverDepsFor was configured", () => {
+ const { driver } = fakeSdkDriver("pi");
+ const mgr = new AgentProcessManager({
+ driverFor: () => driver,
+ baseContextFor: () => ({
+ workingDirectory: "/tmp",
+ agentId: "a1",
+ standingPrompt: "",
+ config: {} as LaunchContext["config"],
+ credentialProxy: {} as LaunchContext["credentialProxy"],
+ }),
+ });
+ mgr.register("a1");
+ expect(() => mgr.deliver("a1", { seq: 1, text: "hello" })).toThrow(/sdkDriverDepsFor/);
+ });
+
+ it("dispatches through SdkManagedSession (not a child process) when sdkDriverDepsFor is configured, and streams runtime_events normally", async () => {
+ const { driver, createSession } = fakeSdkDriver("pi");
+ const onRuntimeSessionEstablished = vi.fn();
+ const sdkDeps: SdkDriverDeps = {
+ buildSpawnEnv: vi.fn().mockResolvedValue({}),
+ createAgentSession: vi.fn(),
+ };
+ const mgr = new AgentProcessManager({
+ driverFor: () => driver,
+ baseContextFor: () => ({
+ workingDirectory: "/tmp",
+ agentId: "a1",
+ standingPrompt: "",
+ config: {} as LaunchContext["config"],
+ }),
+ sdkDriverDepsFor: () => sdkDeps,
+ onRuntimeSessionEstablished,
+ });
+ mgr.register("a1");
+ mgr.deliver("a1", { seq: 1, text: "hello" });
+ // createSession is async — let its microtasks (and the subsequent send()) drain.
+ await new Promise((r) => setTimeout(r, 0));
+
+ expect(createSession).toHaveBeenCalledTimes(1);
+ expect(onRuntimeSessionEstablished).toHaveBeenCalledWith("pi");
+ });
+
+ it("does NOT require a credentialProxy for an in-process SDK driver (that guard is child-process-only)", () => {
+ const { driver } = fakeSdkDriver("pi");
+ const sdkDeps: SdkDriverDeps = { buildSpawnEnv: vi.fn().mockResolvedValue({}), createAgentSession: vi.fn() };
+ const mgr = new AgentProcessManager({
+ driverFor: () => driver,
+ baseContextFor: () => ({
+ workingDirectory: "/tmp",
+ agentId: "a1",
+ standingPrompt: "",
+ config: {} as LaunchContext["config"],
+ // no credentialProxy on purpose
+ }),
+ sdkDriverDepsFor: () => sdkDeps,
+ });
+ mgr.register("a1");
+ expect(() => mgr.deliver("a1", { seq: 1, text: "hello" })).not.toThrow();
+ });
+});
diff --git a/src/daemon/src/manager/managerRuntime.ts b/src/daemon/src/manager/managerRuntime.ts
index 236b414ba..0bb8ad35a 100644
--- a/src/daemon/src/manager/managerRuntime.ts
+++ b/src/daemon/src/manager/managerRuntime.ts
@@ -19,9 +19,10 @@ import {
type AgentRuntimeCaps,
type AgentMsg,
} from "./managerPolicy.js";
-import type { Driver, LaunchContext } from "../types.js";
+import type { Driver, LaunchContext, SdkDriverDeps } from "../types.js";
import type { RuntimeConfig } from "../runtimeConfig.js";
import { createChildProcessRuntimeSession, type ChildProcessRuntimeSession } from "../runtime/runtimeSession.js";
+import { SdkManagedSession } from "../runtime/sdkManagedSession.js";
import { createLogger, type Logger } from "../logger.js";
/** Minimal shape the executor needs from a runtime session. */
@@ -62,6 +63,14 @@ export interface ManagerRuntimeOpts {
* runtime without it (no plaintext fallback). Threaded into each LaunchContext.
*/
credentialProxy?: LaunchContext["credentialProxy"];
+ /**
+ * Builds the `SdkDriverDeps` for an in-process SDK driver's `createSession`
+ * (see `types.ts`). Required when NOT using a `sessionFactory` AND a
+ * resolved driver declares `createSession` (Pi today) — mirrors the
+ * `credentialProxy` requirement for child-process drivers. Called once per
+ * spawn with the same base `ctx` a `ChildProcessRuntimeSession` would get.
+ */
+ sdkDriverDepsFor?: (ctx: LaunchContext) => SdkDriverDeps;
staleThresholdMs?: number;
/** Idle hibernation timeout (ms): stop a persistent process idle this long. */
idleTimeoutMs?: number;
@@ -156,6 +165,7 @@ export class AgentProcessManager {
| "sessionFactory"
| "now"
| "credentialProxy"
+ | "sdkDriverDepsFor"
| "onAgentSession"
| "timeline"
| "wakePromptFooter"
@@ -169,6 +179,7 @@ export class AgentProcessManager {
| "sessionFactory"
| "now"
| "credentialProxy"
+ | "sdkDriverDepsFor"
| "onAgentSession"
| "timeline"
| "wakePromptFooter"
@@ -331,16 +342,28 @@ export class AgentProcessManager {
config,
};
- if (!this.opts.sessionFactory && !ctx.credentialProxy) {
+ if (!this.opts.sessionFactory && driver.createSession && !this.opts.sdkDriverDepsFor) {
+ throw new Error(
+ `AgentProcessManager: real spawn of "${agentId}" on in-process SDK runtime "${driver.id}" needs ` +
+ "sdkDriverDepsFor — set ManagerRuntimeOpts.sdkDriverDepsFor, or pass a sessionFactory for tests.",
+ );
+ }
+ if (!this.opts.sessionFactory && !driver.createSession && !ctx.credentialProxy) {
throw new Error(
`AgentProcessManager: real spawn of "${agentId}" needs a credentialProxy — ` +
- "set ManagerRuntimeOpts.credentialProxy (or baseContextFor's), or pass a sessionFactory for tests.",
+ "set ManagerRuntimeOpts.credentialProxy (or baseContextFor's), or pass a sessionFactory for tests.",
);
}
const session: ManagedSession = this.opts.sessionFactory
? this.opts.sessionFactory({ agentId, driver, ctx })
- : (createChildProcessRuntimeSession(driver, ctx) as ChildProcessRuntimeSession);
+ : driver.createSession
+ ? new SdkManagedSession(
+ driver as Driver & { createSession: NonNullable<Driver["createSession"]> },
+ ctx,
+ this.opts.sdkDriverDepsFor!(ctx),
+ )
+ : (createChildProcessRuntimeSession(driver, ctx) as ChildProcessRuntimeSession);
this.sessions.set(agentId, session);
@@ -417,6 +440,14 @@ export class AgentProcessManager {
void Promise.resolve(session.start({ text: prompt, sessionId: ctx.config.sessionId }))
.then(() => {
+ // A concurrent stop()/terminate_stalled can race this in-flight
+ // start() and finish first — its `exit` handler above already
+ // deleted this session from `this.sessions` and dispatched
+ // `{type: "exit"}`. If that happened, don't ALSO dispatch `spawned`:
+ // that would revive the FSM into "running" for a session nobody
+ // tracks anymore, wedging the agent (its inbox already drained into
+ // this now-dead spawn) until the daemon restarts.
+ if (this.sessions.get(agentId) !== session) return;
this.dispatch({ type: "spawned", agentId, nowMs: this.now() });
})
.catch((err: unknown) => {
@@ -427,7 +458,7 @@ export class AgentProcessManager {
(err as { code?: string } | undefined)?.code ??
"spawn_threw";
reportSpawnFailure(String(code));
- this.sessions.delete(agentId);
+ if (this.sessions.get(agentId) === session) this.sessions.delete(agentId);
this.dispatch({ type: "exit", agentId });
});
}
diff --git a/src/daemon/src/runtime/sdkManagedSession.test.ts b/src/daemon/src/runtime/sdkManagedSession.test.ts
new file mode 100644
index 000000000..1e7cc297f
--- /dev/null
+++ b/src/daemon/src/runtime/sdkManagedSession.test.ts
@@ -0,0 +1,423 @@
+import { describe, it, expect, vi } from "vitest";
+import { SdkManagedSession } from "./sdkManagedSession.js";
+import { SdkRuntimeSession, type SdkSessionHandle } from "./sdkRuntimeSession.js";
+import type { Driver, LaunchContext, SdkDriverDeps } from "../types.js";
+
+function baseCtx(overrides: Partial<LaunchContext> = {}): LaunchContext {
+ return {
+ agentId: "agent_1",
+ workingDirectory: "/tmp/agent_1",
+ standingPrompt: "You are Pi.",
+ prompt: "",
+ config: {},
+ ...overrides,
+ };
+}
+
+function fakeDeps(): SdkDriverDeps {
+ return {
+ buildSpawnEnv: vi.fn().mockResolvedValue({}),
+ createAgentSession: vi.fn(),
+ };
+}
+
+/**
+ * A driver whose `createSession` mirrors `PiDriver`'s real contract: it wires
+ * `handle.prompt` to push events through the returned `SdkRuntimeSession`
+ * (via a real `subscribe`-style callback), and does NOT itself await/send
+ * the prompt — the caller must do that via `.send()`.
+ */
+function fakeSdkDriver(): { driver: Driver & { createSession: NonNullable<Driver["createSession"]> }; createSession: ReturnType<typeof vi.fn> } {
+ let session: SdkRuntimeSession;
+ const handle: SdkSessionHandle = {
+ prompt: (text: string) => {
+ session.emitEvents([{ kind: "text", text }]);
+ },
+ steer: (text: string) => {
+ session.emitEvents([{ kind: "text", text: `steer:${text}` }]);
+ },
+ abort: vi.fn(),
+ dispose: vi.fn(),
+ };
+ const createSession = vi.fn(async (_ctx: LaunchContext, _deps: SdkDriverDeps) => {
+ session = new SdkRuntimeSession(handle, "sess_1");
+ return session;
+ });
+ const driver = {
+ id: "fake-sdk",
+ lifecycle: { kind: "persistent", stdin: "direct", inFlightWake: "steer" } as const,
+ session: { recovery: "resume_or_fresh" } as const,
+ model: { detectedModelsVerifiedAs: "launchable", toLaunchSpec: () => ({ params: {} }) } as const,
+ supportsStdinNotification: true,
+ busyDeliveryMode: "direct" as const,
+ probe: () => ({ status: "healthy" as const }),
+ spawn: async () => {
+ throw new Error("unsupported");
+ },
+ createSession,
+ parseLine: () => [],
+ currentSessionId: null,
+ encodeStdinMessage: () => null,
+ buildSystemPrompt: () => "",
+ } as unknown as Driver & { createSession: NonNullable<Driver["createSession"]> };
+ return { driver, createSession };
+}
+
+describe("SdkManagedSession", () => {
+ it("delivers events from the initial prompt to a listener attached before start() — the event-loss regression test", async () => {
+ const { driver } = fakeSdkDriver();
+ const adapter = new SdkManagedSession(driver, baseCtx(), fakeDeps());
+
+ const received: unknown[] = [];
+ // Attached BEFORE start(), same as managerRuntime.doSpawn does.
+ adapter.on("runtime_event", (e) => received.push(e));
+
+ await adapter.start({ text: "hello" });
+
+ expect(received).toEqual([
+ { kind: "session_init", sessionId: "sess_1" },
+ { kind: "text", text: "hello" },
+ ]);
+ expect(adapter.currentSessionId).toBe("sess_1");
+ });
+
+ it("builds the launch ctx from start()'s input, overriding the base ctx's prompt/sessionId", async () => {
+ const { driver, createSession } = fakeSdkDriver();
+ const adapter = new SdkManagedSession(driver, baseCtx({ config: { sessionId: "base-session" } }), fakeDeps());
+
+ await adapter.start({ text: "steer this", sessionId: "resumed-session" });
+
+ const [launchCtx] = createSession.mock.calls[0] as [LaunchContext, SdkDriverDeps];
+ expect(launchCtx.prompt).toBe("steer this");
+ expect(launchCtx.config.sessionId).toBe("resumed-session");
+ });
+
+ it("falls back to the base ctx's sessionId when start() doesn't supply one", async () => {
+ const { driver, createSession } = fakeSdkDriver();
+ const adapter = new SdkManagedSession(driver, baseCtx({ config: { sessionId: "base-session" } }), fakeDeps());
+
+ await adapter.start({ text: "hi" });
+
+ const [launchCtx] = createSession.mock.calls[0] as [LaunchContext, SdkDriverDeps];
+ expect(launchCtx.config.sessionId).toBe("base-session");
+ });
+
+ it("send() delegates busy/idle mode to the inner session once started", async () => {
+ const { driver } = fakeSdkDriver();
+ const adapter = new SdkManagedSession(driver, baseCtx(), fakeDeps());
+ const received: unknown[] = [];
+ adapter.on("runtime_event", (e) => received.push(e));
+
+ await adapter.start({ text: "hello" });
+ adapter.send({ text: "follow up", mode: "busy" });
+ // steer's handle callback emits synchronously.
+ await Promise.resolve();
+
+ expect(received).toContainEqual({ kind: "text", text: "steer:follow up" });
+ });
+
+ it("send() before start() returns not_started instead of throwing", () => {
+ const { driver } = fakeSdkDriver();
+ const adapter = new SdkManagedSession(driver, baseCtx(), fakeDeps());
+ expect(adapter.send({ text: "too early", mode: "idle" })).toEqual({ ok: false, reason: "not_started" });
+ });
+
+ it("stop() delegates to the inner session's stop", async () => {
+ const { driver } = fakeSdkDriver();
+ const adapter = new SdkManagedSession(driver, baseCtx(), fakeDeps());
+ await adapter.start({ text: "hello" });
+ await expect(adapter.stop()).resolves.toBeUndefined();
+ });
+
+ it("stop() before start() is a safe no-op", async () => {
+ const { driver } = fakeSdkDriver();
+ const adapter = new SdkManagedSession(driver, baseCtx(), fakeDeps());
+ await expect(adapter.stop()).resolves.toBeUndefined();
+ });
+
+ // Regression test: unlike ChildProcessRuntimeSession (where killing the
+ // process makes the OS emit its own "exit"), there's no process here to do
+ // that for us — SdkManagedSession must fire "exit" itself, or
+ // managerRuntime.ts's `session.on("exit", ...)` listener never runs and the
+ // agent's session is never removed from the manager's map / FSM.
+ it("stop() emits \"exit\" so the manager's session-cleanup listener runs", async () => {
+ const { driver } = fakeSdkDriver();
+ const adapter = new SdkManagedSession(driver, baseCtx(), fakeDeps());
+ const exited = vi.fn();
+ adapter.on("exit", exited);
+
+ await adapter.start({ text: "hello" });
+ await adapter.stop();
+
+ expect(exited).toHaveBeenCalledTimes(1);
+ });
+
+ it("stop() emits \"exit\" exactly once even when called multiple times", async () => {
+ const { driver } = fakeSdkDriver();
+ const adapter = new SdkManagedSession(driver, baseCtx(), fakeDeps());
+ const exited = vi.fn();
+ adapter.on("exit", exited);
+
+ await adapter.start({ text: "hello" });
+ await adapter.stop();
+ await adapter.stop();
+
+ expect(exited).toHaveBeenCalledTimes(1);
+ });
+
+ it("stop() before start() still emits \"exit\" (no inner session to dispose)", async () => {
+ const { driver } = fakeSdkDriver();
+ const adapter = new SdkManagedSession(driver, baseCtx(), fakeDeps());
+ const exited = vi.fn();
+ adapter.on("exit", exited);
+
+ await adapter.stop();
+
+ expect(exited).toHaveBeenCalledTimes(1);
+ });
+
+ it("stop() emits \"exit\" even when the inner session's dispose rejects", async () => {
+ const { driver } = fakeSdkDriver();
+ const adapter = new SdkManagedSession(driver, baseCtx(), fakeDeps());
+ const exited = vi.fn();
+ adapter.on("exit", exited);
+ await adapter.start({ text: "hello" });
+
+ // Force the inner session's own stop() to reject — the manager must
+ // still be notified via "exit" so the agent doesn't get stuck in
+ // "stopping" forever just because disposal failed.
+ const inner = (adapter as unknown as { inner: SdkRuntimeSession }).inner;
+ vi.spyOn(inner, "stop").mockRejectedValueOnce(new Error("dispose failed"));
+
+ await expect(adapter.stop()).rejects.toThrow("dispose failed");
+ expect(exited).toHaveBeenCalledTimes(1);
+ });
+
+ // Regression test: `managerRuntime.ts::doSpawn` registers the session in
+ // its map (and a `stop`/`terminate_stalled` effect can look it up and call
+ // `.stop()`) BEFORE `start()`'s `driver.createSession()` has resolved. If
+ // `stop()` disposed nothing and emitted "exit" immediately in that window,
+ // the still in-flight `start()` would go on to wire up the SDK session and
+ // fire the first prompt into it — an orphaned session the manager already
+ // believes has exited.
+ it("a stop() that races an in-flight start() disposes the session instead of leaving it orphaned, and skips the first prompt", async () => {
+ let resolveCreateSession!: (session: SdkRuntimeSession) => void;
+ const disposed = vi.fn();
+ const promptSent = vi.fn();
+ const handle: SdkSessionHandle = {
+ prompt: (text: string) => promptSent(text),
+ steer: vi.fn(),
+ dispose: disposed,
+ };
+ const createSession = vi.fn(
+ () =>
+ new Promise<SdkRuntimeSession>((resolve) => {
+ resolveCreateSession = (session) => resolve(session);
+ }),
+ );
+ const driver = {
+ id: "fake-sdk",
+ lifecycle: { kind: "persistent", stdin: "direct", inFlightWake: "steer" } as const,
+ session: { recovery: "resume_or_fresh" } as const,
+ model: { detectedModelsVerifiedAs: "launchable", toLaunchSpec: () => ({ params: {} }) } as const,
+ supportsStdinNotification: true,
+ busyDeliveryMode: "direct" as const,
+ probe: () => ({ status: "healthy" as const }),
+ spawn: async () => {
+ throw new Error("unsupported");
+ },
+ createSession,
+ parseLine: () => [],
+ currentSessionId: null,
+ encodeStdinMessage: () => null,
+ buildSystemPrompt: () => "",
+ } as unknown as Driver & { createSession: NonNullable<Driver["createSession"]> };
+
+ const adapter = new SdkManagedSession(driver, baseCtx(), fakeDeps());
+ const exited = vi.fn();
+ adapter.on("exit", exited);
+
+ const startPromise = adapter.start({ text: "hello" }); // createSession() still pending
+ const stopPromise = adapter.stop(); // races the in-flight start()
+
+ // Let `driver.createSession()` resolve now that both calls are in flight.
+ resolveCreateSession(new SdkRuntimeSession(handle, "sess_1"));
+ await Promise.all([startPromise, stopPromise]);
+
+ expect(disposed).toHaveBeenCalledTimes(1); // the session got cleaned up, not orphaned
+ expect(promptSent).not.toHaveBeenCalled(); // no turn fired into a stopped session
+ expect(exited).toHaveBeenCalledTimes(1);
+ });
+
+ // Regression test: it's not enough for the racing stop() to eventually
+ // dispose and emit "exit" — `start()` must not resolve "successfully"
+ // BEFORE that happens. `doSpawn` dispatches `{type: "spawned"}` the
+ // instant `start()` resolves; if that happened while `stop()`'s own
+ // disposal (e.g. a slow vendor `dispose()`) was still pending, the manager
+ // would see a session still in its map and (correctly, per its own
+ // identity check) dispatch `spawned` — a real, if brief, "running" state
+ // for a session that's already mid-teardown and never ran a turn.
+ it("start() does not resolve until a racing stop()'s disposal has fully finished (exit fires strictly before start() resolves)", async () => {
+ let resolveCreateSession!: (session: SdkRuntimeSession) => void;
+ let resolveDispose!: () => void;
+ const order: string[] = [];
+ const handle: SdkSessionHandle = {
+ prompt: vi.fn(),
+ steer: vi.fn(),
+ dispose: () =>
+ new Promise<void>((resolve) => {
+ resolveDispose = () => {
+ order.push("dispose-settled");
+ resolve();
+ };
+ }),
+ };
+ const createSession = vi.fn(
+ () =>
+ new Promise<SdkRuntimeSession>((resolve) => {
+ resolveCreateSession = (session) => resolve(session);
+ }),
+ );
+ const driver = {
+ id: "fake-sdk",
+ lifecycle: { kind: "persistent", stdin: "direct", inFlightWake: "steer" } as const,
+ session: { recovery: "resume_or_fresh" } as const,
+ model: { detectedModelsVerifiedAs: "launchable", toLaunchSpec: () => ({ params: {} }) } as const,
+ supportsStdinNotification: true,
+ busyDeliveryMode: "direct" as const,
+ probe: () => ({ status: "healthy" as const }),
+ spawn: async () => {
+ throw new Error("unsupported");
+ },
+ createSession,
+ parseLine: () => [],
+ currentSessionId: null,
+ encodeStdinMessage: () => null,
+ buildSystemPrompt: () => "",
+ } as unknown as Driver & { createSession: NonNullable<Driver["createSession"]> };
+
+ const adapter = new SdkManagedSession(driver, baseCtx(), fakeDeps());
+ adapter.on("exit", () => order.push("exit-emitted"));
+
+ const startPromise = adapter.start({ text: "hello" }).then(() => order.push("start-resolved"));
+ const stopPromise = adapter.stop();
+ resolveCreateSession(new SdkRuntimeSession(handle, "sess_1"));
+
+ // Give both chains plenty of microtasks to progress WITHOUT resolving
+ // dispose() yet — start() must still be pending at this point.
+ for (let i = 0; i < 10; i++) await Promise.resolve();
+ expect(order).toEqual([]); // neither exit nor start-resolved yet — dispose() is still pending
+
+ resolveDispose();
+ await Promise.all([startPromise, stopPromise]);
+
+ expect(order).toEqual(["dispose-settled", "exit-emitted", "start-resolved"]);
+ });
+});
+
+describe("SdkManagedSession — start() does not block on the whole first turn", () => {
+ /**
+ * Regression test for the production crash:
+ * Error: Agent is already processing. Specify streamingBehavior
+ * ('steer' or 'followUp') to queue the message.
+ *
+ * `start()` used to `await` the whole first `send()` (a vendor SDK's
+ * `prompt()` doesn't resolve until the entire turn, including tool calls,
+ * finishes). That meant `AgentProcessManager` didn't dispatch
+ * `{type: "spawned"}` — and so didn't consider the agent "busy" — until
+ * long after the turn had actually started, so a wake that arrived mid-turn
+ * got queued instead of routed as an immediate "steer", then misrouted as
+ * an `idle` send once the turn finally ended.
+ */
+ function fakeSdkDriverWithSlowFirstTurn(): {
+ driver: Driver & { createSession: NonNullable<Driver["createSession"]> };
+ resolveFirstTurn: () => void;
+ rejectFirstTurn: (err: unknown) => void;
+ steerCalls: string[];
+ } {
+ let session: SdkRuntimeSession;
+ const steerCalls: string[] = [];
+ let resolveFirstTurn!: () => void;
+ let rejectFirstTurn!: (err: unknown) => void;
+ const handle: SdkSessionHandle = {
+ prompt: () =>
+ new Promise<void>((resolve, reject) => {
+ resolveFirstTurn = resolve;
+ rejectFirstTurn = reject;
+ }),
+ steer: (text: string) => {
+ steerCalls.push(text);
+ },
+ };
+ const createSession = vi.fn(async () => {
+ session = new SdkRuntimeSession(handle, "sess_1");
+ return session;
+ });
+ const driver = {
+ id: "fake-sdk",
+ lifecycle: { kind: "persistent", stdin: "direct", inFlightWake: "steer" } as const,
+ session: { recovery: "resume_or_fresh" } as const,
+ model: { detectedModelsVerifiedAs: "launchable", toLaunchSpec: () => ({ params: {} }) } as const,
+ supportsStdinNotification: true,
+ busyDeliveryMode: "direct" as const,
+ probe: () => ({ status: "healthy" as const }),
+ spawn: async () => {
+ throw new Error("unsupported");
+ },
+ createSession,
+ parseLine: () => [],
+ currentSessionId: null,
+ encodeStdinMessage: () => null,
+ buildSystemPrompt: () => "",
+ } as unknown as Driver & { createSession: NonNullable<Driver["createSession"]> };
+ return {
+ driver,
+ resolveFirstTurn: () => resolveFirstTurn(),
+ rejectFirstTurn: (err) => rejectFirstTurn(err),
+ steerCalls,
+ };
+ }
+
+ it("start() resolves before the first turn's prompt() promise settles", async () => {
+ const { driver } = fakeSdkDriverWithSlowFirstTurn();
+ const adapter = new SdkManagedSession(driver, baseCtx(), fakeDeps());
+
+ // If start() awaited the whole turn, this would hang forever (the turn's
+ // prompt() promise is never resolved in this test) — the fact it resolves
+ // at all is the assertion.
+ await adapter.start({ text: "hello" });
+ });
+
+ it("a wake that arrives while the first turn is still in flight is delivered as a real steer, not queued until turn_end", async () => {
+ const { driver, steerCalls } = fakeSdkDriverWithSlowFirstTurn();
+ const adapter = new SdkManagedSession(driver, baseCtx(), fakeDeps());
+
+ await adapter.start({ text: "hello" }); // first turn still pending underneath
+ const result = adapter.send({ text: "mid-turn wake", mode: "busy" });
+
+ expect(result).toEqual({ ok: true });
+ expect(steerCalls).toEqual(["mid-turn wake"]);
+ });
+
+ it("a first-turn rejection surfaces as a runtime_event error instead of an unhandled rejection", async () => {
+ // As of plans/sdk-runtime-session-live-isstreaming-guard.md,
+ // SdkRuntimeSession.send() itself catches a vendor SDK rejection and
+ // reports it as a normal `runtime_event: {kind: "error"}` — visible on
+ // the agent's own event stream — rather than rejecting and relying on
+ // this adapter's `.catch()` → `"error"` EventEmitter event (that path
+ // still exists as a last-resort net, but no longer fires for this case).
+ const { driver, rejectFirstTurn } = fakeSdkDriverWithSlowFirstTurn();
+ const adapter = new SdkManagedSession(driver, baseCtx(), fakeDeps());
+ const events: unknown[] = [];
+ const errors: unknown[] = [];
+ adapter.on("runtime_event", (e) => events.push(e));
+ adapter.on("error", (e) => errors.push(e));
+
+ await adapter.start({ text: "hello" });
+ rejectFirstTurn(new Error("Agent is already processing"));
+ await new Promise((r) => setTimeout(r, 0));
+
+ expect(errors).toEqual([]);
+ expect(events).toContainEqual({ kind: "error", message: "Agent is already processing" });
+ });
+});
diff --git a/src/daemon/src/runtime/sdkManagedSession.ts b/src/daemon/src/runtime/sdkManagedSession.ts
new file mode 100644
index 000000000..7688acc2f
--- /dev/null
+++ b/src/daemon/src/runtime/sdkManagedSession.ts
@@ -0,0 +1,147 @@
+/**
+ * SdkManagedSession — bridges an in-process SDK driver's `createSession` into
+ * the `ManagedSession` contract `AgentProcessManager.doSpawn` drives, the same
+ * way `ChildProcessRuntimeSession` does for CLI drivers.
+ *
+ * The manager subscribes to `"runtime_event"`/`"error"`/`"exit"` right after
+ * construction, BEFORE calling `.start()` (see `managerRuntime.ts::doSpawn`).
+ * This class's own `EventEmitter` exists from construction for exactly that
+ * reason: `.on()` calls made before `.start()` resolves are never missed.
+ *
+ * `.start()` then does, in order: (1) call `driver.createSession()` — which
+ * builds and wires the vendor SDK session but does NOT fire the first turn —
+ * (2) proxy the returned session's events through to this adapter's emitter,
+ * (3) only THEN send the first turn via `.send(text, "idle")`. That ordering
+ * is what fixes the event-loss bug a driver could otherwise hit: a plain
+ * `EventEmitter.emit()` (unlike a child process's buffered stdout pipe) drops
+ * events fired before any listener is attached.
+ *
+ * `.start()` does NOT await that first `.send()` to completion — it resolves
+ * as soon as the turn is ACCEPTED, mirroring `ChildProcessRuntimeSession`
+ * (whose `.start()` resolves once the process is spawned, not once it exits).
+ * `AgentProcessManager` only dispatches `{type: "spawned"}` after `.start()`
+ * resolves, and only *that* dispatch makes the manager treat the agent as
+ * "busy" for the duration of the turn. Awaiting the whole turn here — a
+ * vendor SDK's `prompt()` doesn't resolve until the turn (incl. tool calls)
+ * finishes — delayed that dispatch by the entire turn length, so a wake that
+ * arrived mid-turn wasn't recognized as "steer a running agent" and instead
+ * got queued until turn_end, where it was misrouted as an `idle` send into an
+ * agent the vendor SDK still considered mid-turn — throwing "Agent is
+ * already processing". A rejected first turn is reported via the `"error"`
+ * event instead (same path `doSpawn`'s pre-handshake `error` listener uses).
+ */
+import { EventEmitter } from "events";
+import type { Driver, LaunchContext, SdkDriverDeps } from "../types.js";
+import type { SdkRuntimeSession } from "./sdkRuntimeSession.js";
+
+type SdkCapableDriver = Driver & { createSession: NonNullable<Driver["createSession"]> };
+
+export class SdkManagedSession {
+ private readonly events = new EventEmitter();
+ private inner: SdkRuntimeSession | null = null;
+ private startedSessionId: string | null = null;
+ private exited = false;
+ // Set synchronously (before any `await`) by `start()`. `stop()` awaits
+ // this so it never disposes/exits while `driver.createSession()` is still
+ // in flight — see `stop()`'s doc comment for why that matters.
+ private starting: Promise<void> | null = null;
+ private stopRequested = false;
+ // Set synchronously (before any `await`) by `stop()`. `start()` awaits
+ // this — when it sees `stopRequested` — before resolving, so it can never
+ // resolve "successfully" in the gap between a racing `stop()` skipping the
+ // first turn and that same `stop()` actually finishing disposal + emitting
+ // `"exit"`. Without this, `doSpawn`'s `.then()` would see `start()`
+ // resolve WHILE the session is still tracked in the manager's map (`stop()`
+ // hasn't reached `emitExit()`'s synchronous `this.sessions.delete()` yet)
+ // and dispatch `{type: "spawned"}` — a real, if brief, "running" state for
+ // a session that never actually ran a turn and is already being torn down.
+ private stopping: Promise<void> | null = null;
+
+ constructor(
+ private readonly driver: SdkCapableDriver,
+ private readonly ctx: LaunchContext,
+ private readonly deps: SdkDriverDeps,
+ ) { }
+
+ on(event: string, cb: (...args: unknown[]) => void): void {
+ this.events.on(event, cb);
+ }
+
+ async start(input: { text: string; sessionId?: string }): Promise<{ ok: boolean }> {
+ const launchCtx: LaunchContext = {
+ ...this.ctx,
+ prompt: input.text,
+ config: { ...this.ctx.config, sessionId: input.sessionId ?? this.ctx.config.sessionId },
+ };
+ // `managerRuntime.ts::doSpawn` puts this session into its map BEFORE
+ // this promise settles, so a `stop()` (effect-driven or the public
+ // `AgentProcessManager.stop()`) can legitimately race a still-in-flight
+ // `driver.createSession()`. Stashing the promise lets `stop()` wait for
+ // `this.inner` to actually exist instead of disposing nothing and
+ // leaving this call free to wire up and prompt a session nobody tracks
+ // anymore.
+ this.starting = (async () => {
+ const inner = await this.driver.createSession(launchCtx, this.deps);
+ this.inner = inner;
+ this.startedSessionId = inner.currentSessionId;
+ inner.on("runtime_event", (...args: unknown[]) => this.events.emit("runtime_event", ...args));
+ })();
+ await this.starting;
+ if (this.stopRequested) {
+ // A stop() raced this start() — don't fire a turn into a session
+ // that's already being torn down, and don't resolve until that
+ // teardown (disposal + `"exit"`) has fully finished (see `stopping`'s
+ // doc comment above for why resolving any earlier is unsafe).
+ if (this.stopping) await this.stopping.catch(() => { });
+ return { ok: true };
+ }
+ // Fire-and-forget — see the class doc comment for why this must NOT be
+ // awaited. A rejection (e.g. the vendor SDK throwing before any
+ // runtime_event ever fires) surfaces as an "error" event instead.
+ void this.inner!.send(input.text, "idle").catch((err: unknown) => this.events.emit("error", err));
+ return { ok: true };
+ }
+
+ send(input: { text: string; mode: "busy" | "idle" }): { ok: boolean; reason?: string } {
+ if (!this.inner) return { ok: false, reason: "not_started" };
+ void this.inner.send(input.text, input.mode).catch((err: unknown) => this.events.emit("error", err));
+ return { ok: true };
+ }
+
+ /**
+ * Unlike `ChildProcessRuntimeSession` — where killing the process makes the
+ * OS emit its own `exit` shortly after, which is what actually notifies
+ * `managerRuntime.ts`'s `session.on("exit", ...)` listener — there's no
+ * underlying process here to do that for us. `inner.dispose()` just frees
+ * SDK resources; it doesn't fire anything on `this.events`. So `stop()`
+ * must emit `"exit"` itself once disposal settles (even if it throws),
+ * or the manager's exit listener never runs: the session is never removed
+ * from `AgentProcessManager`'s map and the FSM never leaves "stopping".
+ *
+ * `stopRequested` is set synchronously (before awaiting `starting`) so a
+ * `start()` that's still mid-flight sees it as soon as `driver.createSession()`
+ * resolves and skips firing the first turn (see `start()`).
+ */
+ async stop(): Promise<void> {
+ this.stopRequested = true;
+ this.stopping = (async () => {
+ try {
+ if (this.starting) await this.starting.catch(() => { });
+ await this.inner?.stop();
+ } finally {
+ this.emitExit();
+ }
+ })();
+ await this.stopping;
+ }
+
+ private emitExit(): void {
+ if (this.exited) return;
+ this.exited = true;
+ this.events.emit("exit");
+ }
+
+ get currentSessionId(): string | null {
+ return this.inner?.currentSessionId ?? this.startedSessionId;
+ }
+}
diff --git a/src/daemon/src/runtime/sdkRuntimeSession.test.ts b/src/daemon/src/runtime/sdkRuntimeSession.test.ts
new file mode 100644
index 000000000..2c05b839a
--- /dev/null
+++ b/src/daemon/src/runtime/sdkRuntimeSession.test.ts
@@ -0,0 +1,173 @@
+import { describe, it, expect, vi } from "vitest";
+import { SdkRuntimeSession, type SdkSessionHandle } from "./sdkRuntimeSession.js";
+
+/**
+ * See plans/sdk-runtime-session-live-isstreaming-guard.md — `send()`'s idle
+ * path is a second, independent line of defense against "Agent is already
+ * processing": it re-checks the vendor SDK's live `isStreaming` at the
+ * moment of delivery instead of trusting the caller's `mode: "idle"` at face
+ * value, and degrades to `steer()` instead of ever calling `prompt()` on a
+ * session that's actually still busy.
+ */
+function fakeHandle(isStreaming = false) {
+ return {
+ isStreaming,
+ prompt: vi.fn().mockResolvedValue(undefined),
+ steer: vi.fn().mockResolvedValue(undefined),
+ } as SdkSessionHandle & { isStreaming: boolean; prompt: ReturnType<typeof vi.fn>; steer: ReturnType<typeof vi.fn> };
+}
+
+describe("SdkRuntimeSession.send", () => {
+ it("idle send while not streaming calls prompt() directly, no wait", async () => {
+ const handle = fakeHandle(false);
+ const session = new SdkRuntimeSession(handle, "s1");
+
+ await session.send("hi", "idle");
+
+ expect(handle.prompt).toHaveBeenCalledWith("hi");
+ expect(handle.steer).not.toHaveBeenCalled();
+ });
+
+ it('busy send always steers, even while not streaming (mode: "busy" never calls prompt)', async () => {
+ const handle = fakeHandle(false);
+ const session = new SdkRuntimeSession(handle, "s1");
+
+ await session.send("hi", "busy");
+
+ expect(handle.steer).toHaveBeenCalledWith("hi");
+ expect(handle.prompt).not.toHaveBeenCalled();
+ });
+
+ it("idle send while streaming waits, then calls prompt() once it clears", async () => {
+ vi.useFakeTimers();
+ try {
+ const handle = fakeHandle(true);
+ const session = new SdkRuntimeSession(handle, "s1");
+
+ const pending = session.send("hi", "idle");
+ await vi.advanceTimersByTimeAsync(50);
+ // Still streaming for the first couple of polls — must not have prompted yet.
+ expect(handle.prompt).not.toHaveBeenCalled();
+
+ handle.isStreaming = false; // clears mid-wait
+ await vi.advanceTimersByTimeAsync(25);
+ await pending;
+
+ expect(handle.prompt).toHaveBeenCalledWith("hi");
+ expect(handle.steer).not.toHaveBeenCalled();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it("idle send while streaming that never clears falls back to steer() after the wait window, and never calls prompt()", async () => {
+ vi.useFakeTimers();
+ try {
+ const handle = fakeHandle(true); // stays streaming forever
+ const session = new SdkRuntimeSession(handle, "s1");
+
+ const pending = session.send("hi", "idle");
+ await vi.advanceTimersByTimeAsync(1100);
+ await pending;
+
+ expect(handle.steer).toHaveBeenCalledWith("hi");
+ expect(handle.prompt).not.toHaveBeenCalled();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it("a handle with no isStreaming getter goes straight to prompt() for idle sends (backward compatible)", async () => {
+ const handle = { prompt: vi.fn().mockResolvedValue(undefined), steer: vi.fn().mockResolvedValue(undefined) };
+ const session = new SdkRuntimeSession(handle, "s1");
+
+ await session.send("hi", "idle");
+
+ expect(handle.prompt).toHaveBeenCalledWith("hi");
+ });
+
+ it("a thrown prompt() surfaces as a runtime_event error instead of rejecting send()", async () => {
+ const handle = fakeHandle(false);
+ handle.prompt.mockRejectedValue(new Error("boom"));
+ const session = new SdkRuntimeSession(handle, "s1");
+ const received: unknown[] = [];
+ session.on("runtime_event", (e) => received.push(e));
+
+ await expect(session.send("hi", "idle")).resolves.toEqual({ ok: true });
+
+ expect(received).toContainEqual({ kind: "error", message: "boom" });
+ });
+
+ // Regression test: a failed prompt() IS the attempted turn — nothing else
+ // will ever say it's over, unlike a failed steer() (see below), which
+ // injects into an already-running turn that still emits its own real
+ // turn_end later. Without this synthetic turn_end, the caller (e.g.
+ // `SdkManagedSession.start()`, which fires the very first turn this way)
+ // keeps the agent looking busy/running until the stall watchdog eventually
+ // notices and terminates it, minutes later.
+ it("a thrown prompt() also emits a synthetic turn_end right after the error, so the caller doesn't stay stuck 'running'", async () => {
+ const handle = fakeHandle(false);
+ handle.prompt.mockRejectedValue(new Error("boom"));
+ const session = new SdkRuntimeSession(handle, "s1");
+ const received: unknown[] = [];
+ session.on("runtime_event", (e) => received.push(e));
+
+ await session.send("hi", "idle");
+
+ expect(received).toEqual([
+ { kind: "session_init", sessionId: "s1" },
+ { kind: "error", message: "boom" },
+ { kind: "turn_end", sessionId: "s1" },
+ ]);
+ });
+
+ it("a thrown steer() surfaces as a runtime_event error instead of rejecting send()", async () => {
+ const handle = fakeHandle(false);
+ handle.steer.mockRejectedValue(new Error("nope"));
+ const session = new SdkRuntimeSession(handle, "s1");
+ const received: unknown[] = [];
+ session.on("runtime_event", (e) => received.push(e));
+
+ await expect(session.send("hi", "busy")).resolves.toEqual({ ok: true });
+
+ expect(received).toContainEqual({ kind: "error", message: "nope" });
+ });
+
+ // A failed steer() (mode "busy") does NOT mean the turn it was steering
+ // ended — that turn is still running independently and will emit its own
+ // real turn_end later. Emitting a synthetic one here would end it early.
+ it("a thrown steer() does NOT emit a synthetic turn_end (the underlying turn is still running)", async () => {
+ const handle = fakeHandle(false);
+ handle.steer.mockRejectedValue(new Error("nope"));
+ const session = new SdkRuntimeSession(handle, "s1");
+ const received: unknown[] = [];
+ session.on("runtime_event", (e) => received.push(e));
+
+ await session.send("hi", "busy");
+
+ expect(received).not.toContainEqual(expect.objectContaining({ kind: "turn_end" }));
+ });
+
+ // Same reasoning as above for the idle-but-still-streaming fallback path
+ // (see "falls back to steer() after the wait window" above): it's steering
+ // into an existing turn, not attempting a new one.
+ it("a thrown steer() from the idle-still-streaming fallback does NOT emit a synthetic turn_end", async () => {
+ vi.useFakeTimers();
+ try {
+ const handle = fakeHandle(true); // stays streaming forever
+ handle.steer.mockRejectedValue(new Error("nope"));
+ const session = new SdkRuntimeSession(handle, "s1");
+ const received: unknown[] = [];
+ session.on("runtime_event", (e) => received.push(e));
+
+ const pending = session.send("hi", "idle");
+ await vi.advanceTimersByTimeAsync(1100);
+ await pending;
+
+ expect(received).toContainEqual({ kind: "error", message: "nope" });
+ expect(received).not.toContainEqual(expect.objectContaining({ kind: "turn_end" }));
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+});
diff --git a/src/daemon/src/runtime/sdkRuntimeSession.ts b/src/daemon/src/runtime/sdkRuntimeSession.ts
index fcc006650..4719bdc4f 100644
--- a/src/daemon/src/runtime/sdkRuntimeSession.ts
+++ b/src/daemon/src/runtime/sdkRuntimeSession.ts
@@ -7,6 +7,17 @@
* are delegated to the SDK session. The daemon consumes the same `runtime_event`
* stream it gets from child-process sessions, so the rest of the system is
* transport-agnostic.
+ *
+ * `send()`'s idle path is a second, independent line of defense against
+ * "Agent is already processing" (the manager's own busy/idle bookkeeping in
+ * `managerPolicy.ts` is the first — see `plans/wire-pi-runtime-execution.md`'s
+ * follow-up section). It doesn't trust the caller's `mode: "idle"` at face
+ * value; it re-checks the vendor SDK's live `isStreaming` at the moment of
+ * delivery and degrades to a `steer()` instead of ever calling `prompt()` on
+ * a session that's actually still busy. That way a future FSM bug (a
+ * different driver, a race we haven't hit yet) can't reach the vendor SDK's
+ * own throw — worst case it steers instead of prompting, which is always a
+ * legal call. See plans/sdk-runtime-session-live-isstreaming-guard.md.
*/
import { EventEmitter } from "events";
import type { ParsedEvent, StdinMode } from "../types.js";
@@ -20,6 +31,19 @@ export interface SdkSessionHandle {
readonly isStreaming?: boolean;
}
+/** How long, and how often, to poll `isStreaming` before giving up and
+ * steering instead of prompting a still-busy session. */
+const IDLE_PROMPT_RETRY_MS = 25;
+const IDLE_PROMPT_MAX_WAIT_MS = 1000;
+
+function delay(ms: number): Promise<void> {
+ return new Promise((resolve) => setTimeout(resolve, ms));
+}
+
+function errorMessage(err: unknown): string {
+ return err instanceof Error ? err.message : String(err);
+}
+
export class SdkRuntimeSession {
private readonly events = new EventEmitter();
private sentInit = false;
@@ -42,13 +66,59 @@ export class SdkRuntimeSession {
for (const e of events) this.events.emit("runtime_event", e);
}
- /** idle → SDK prompt; busy → SDK steer. */
+ /**
+ * busy → SDK steer, always. idle → SDK prompt, UNLESS the handle reports
+ * it's still streaming right now, in which case wait briefly for it to
+ * clear and fall back to steer() if it doesn't — see the class doc comment.
+ * Never rejects: a vendor SDK exception is reported as a normal
+ * `runtime_event` (`{kind: "error"}`) instead, so callers can treat
+ * `send()` as fire-and-forget without an unhandled rejection.
+ *
+ * A failed `prompt()` also gets a synthetic `turn_end` right behind its
+ * `error` event — unlike a failed `steer()` (which injects into an
+ * *already-running* turn that will still emit its own real `turn_end`
+ * later regardless of whether the steer landed), a `prompt()` call IS the
+ * attempted turn: if it throws, no turn ever started and nothing else
+ * will ever say this one is over. Without this, the caller (see
+ * `SdkManagedSession.start()`, which fires the first turn this way) keeps
+ * treating the agent as busy/running until the stall watchdog eventually
+ * notices no progress and terminates it minutes later.
+ */
async send(text: string, mode: StdinMode): Promise<{ ok: boolean }> {
- if (mode === "busy") await this.handle.steer(text);
- else await this.handle.prompt(text);
+ try {
+ if (mode === "busy") {
+ await this.handle.steer(text);
+ return { ok: true };
+ }
+ const stillStreaming = this.handle.isStreaming && !(await this.waitForStreamingToClear());
+ if (stillStreaming) {
+ await this.handle.steer(text);
+ return { ok: true };
+ }
+ try {
+ await this.handle.prompt(text);
+ } catch (err) {
+ this.emitEvents([
+ { kind: "error", message: errorMessage(err) },
+ { kind: "turn_end", sessionId: this.sessionId },
+ ]);
+ }
+ } catch (err) {
+ this.emitEvents([{ kind: "error", message: errorMessage(err) }]);
+ }
return { ok: true };
}
+ /** Polls `handle.isStreaming` until it clears or the deadline passes. Returns true once cleared. */
+ private async waitForStreamingToClear(): Promise<boolean> {
+ const deadline = Date.now() + IDLE_PROMPT_MAX_WAIT_MS;
+ while (this.handle.isStreaming) {
+ if (Date.now() >= deadline) return false;
+ await delay(IDLE_PROMPT_RETRY_MS);
+ }
+ return true;
+ }
+
async stop(): Promise<void> {
if (this.handle.isStreaming && this.handle.abort) await this.handle.abort();
await this.handle.dispose?.();
diff --git a/src/daemon/src/types.ts b/src/daemon/src/types.ts
index db58d4b12..ce47d4d2d 100644
--- a/src/daemon/src/types.ts
+++ b/src/daemon/src/types.ts
@@ -29,31 +29,31 @@
*/
export type DriverLifecycle =
| {
- kind: "persistent";
- /**
- * How busy-time stdin writes are timed:
- * - `direct`: write immediately (runtime tolerates injection any time).
- * - `gated`: hold writes until a safe stream boundary (Claude — avoids
- * colliding with in-flight signed thinking blocks).
- */
- stdin: "direct" | "gated";
- /** What to do if a message arrives while a turn is in flight. */
- inFlightWake: "steer" | "queue";
- }
+ kind: "persistent";
+ /**
+ * How busy-time stdin writes are timed:
+ * - `direct`: write immediately (runtime tolerates injection any time).
+ * - `gated`: hold writes until a safe stream boundary (Claude — avoids
+ * colliding with in-flight signed thinking blocks).
+ */
+ stdin: "direct" | "gated";
+ /** What to do if a message arrives while a turn is in flight. */
+ inFlightWake: "steer" | "queue";
+ }
| {
- kind: "per_turn";
- /**
- * When to spawn:
- * - `immediate`: spawn as soon as woken.
- * - `defer_until_concrete_message`: don't spawn for bookkeeping-only
- * wakes (e.g. a system task event); wait for a real message.
- */
- start: "immediate" | "defer_until_concrete_message";
- /** How the per-turn process ends. */
- exit: "natural" | "terminate_on_turn_end";
- /** A wake mid-turn either starts a new process or folds into the pending run. */
- inFlightWake: "spawn_new" | "coalesce_into_pending";
- };
+ kind: "per_turn";
+ /**
+ * When to spawn:
+ * - `immediate`: spawn as soon as woken.
+ * - `defer_until_concrete_message`: don't spawn for bookkeeping-only
+ * wakes (e.g. a system task event); wait for a real message.
+ */
+ start: "immediate" | "defer_until_concrete_message";
+ /** How the per-turn process ends. */
+ exit: "natural" | "terminate_on_turn_end";
+ /** A wake mid-turn either starts a new process or folds into the pending run. */
+ inFlightWake: "spawn_new" | "coalesce_into_pending";
+ };
/** Session recovery strategy across restarts. */
export interface DriverSession {
@@ -109,12 +109,12 @@ export type ParsedEvent =
| { kind: "turn_end"; sessionId?: string }
| { kind: "error"; message: string }
| {
- kind: "telemetry";
- name: "token_usage" | "rate_limits";
- source: string;
- usageKind?: string;
- attrs: Record<string, unknown>;
- };
+ kind: "telemetry";
+ name: "token_usage" | "rate_limits";
+ source: string;
+ usageKind?: string;
+ attrs: Record<string, unknown>;
+ };
/* ------------------------------------------------------------------ */
/* Launch context & stdin encoding */
@@ -204,6 +204,21 @@ export interface SpawnResult {
process: import("child_process").ChildProcess;
}
+/**
+ * What an in-process SDK driver's `createSession` needs injected, so the
+ * driver file itself stays dependency-free (no hard dep on the vendor SDK
+ * package) — the host builds the real implementations per-launch (they close
+ * over the `LaunchContext`) and passes them in. See
+ * `drivers/piSdkDeps.ts::createPiSdkDriverDeps` for the only real
+ * implementation today.
+ */
+export interface SdkDriverDeps {
+ /** Build the per-launch spawn env (credential voucher, PATH link, …). */
+ buildSpawnEnv: () => Promise<NodeJS.ProcessEnv>;
+ /** Create the vendor SDK's session object. Shape is driver-specific. */
+ createAgentSession: (opts: Record<string, unknown>) => Promise<{ session: unknown; sessionId: string }>;
+}
+
/**
* The contract every runtime adapter implements. Child-process drivers
* implement `spawn`; in-process SDK drivers implement `createSession` instead
@@ -234,6 +249,15 @@ export interface Driver {
/** Spawn the child process (child-process drivers). */
spawn(ctx: LaunchContext): Promise<SpawnResult>;
+ /**
+ * Create the runtime session for in-process SDK drivers (Pi). Builds and
+ * wires the session but does NOT fire the initial prompt — the caller
+ * (`SdkManagedSession.start`) attaches its own `"runtime_event"` listener
+ * to the returned session first, then sends the first turn, so no early
+ * events are lost. Absent on child-process drivers.
+ */
+ createSession?(ctx: LaunchContext, deps: SdkDriverDeps): Promise<import("./runtime/sdkRuntimeSession.js").SdkRuntimeSession>;
+
/** Parse one stdout line into zero or more normalized events. */
parseLine(line: string): ParsedEvent[];