A personal assistant that lives on your desktop, remembers what matters, and can use your Mac for you.
TypeScript
feat(daemon): supervise the agent process with strict JSONL framing and crash recovery
Alan Buscagliac199feff7f0f
diff --git a/packages/daemon/src/jsonl.ts b/packages/daemon/src/jsonl.tsnew file mode 100644index 0000000..f597d98--- /dev/null+++ b/packages/daemon/src/jsonl.ts@@ -0,0 +1,43 @@+/**+ * Strict JSONL framing for the Pi RPC protocol: records are split on LF bytes+ * only. Node's `readline` is deliberately avoided because it also splits on+ * U+2028 and U+2029, which are valid inside JSON strings.+ */+export class JsonlDecoder {+ private pending: Buffer = Buffer.alloc(0);+ private readonly onRecord: (record: unknown) => void;+ private readonly onMalformed: (line: string) => void;++ constructor(onRecord: (record: unknown) => void, onMalformed: (line: string) => void = () => {}) {+ this.onRecord = onRecord;+ this.onMalformed = onMalformed;+ }++ push(chunk: Buffer): void {+ this.pending = this.pending.length === 0 ? chunk : Buffer.concat([this.pending, chunk]);+ let newline = this.pending.indexOf(0x0a);+ while (newline >= 0) {+ let end = newline;+ if (end > 0 && this.pending[end - 1] === 0x0d) end -= 1;+ const line = this.pending.subarray(0, end).toString("utf8");+ this.pending = this.pending.subarray(newline + 1);+ if (line.trim() !== "") this.emit(line);+ newline = this.pending.indexOf(0x0a);+ }+ }++ private emit(line: string): void {+ let record: unknown;+ try {+ record = JSON.parse(line);+ } catch {+ this.onMalformed(line);+ return;+ }+ this.onRecord(record);+ }+}++export function encodeRecord(record: unknown): string {+ return `${JSON.stringify(record)}\n`;+}diff --git a/packages/daemon/src/supervisor.ts b/packages/daemon/src/supervisor.tsnew file mode 100644index 0000000..12d07b2--- /dev/null+++ b/packages/daemon/src/supervisor.ts@@ -0,0 +1,305 @@+import { type ChildProcess, spawn } from "node:child_process";+import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";+import { join } from "node:path";+import { encodeRecord, JsonlDecoder } from "./jsonl.ts";++/** A record the agent wrote to stdout that is not a command response. */+export type AgentRecord = { type: string; [key: string]: unknown };++export type RpcResponse = {+ type: "response";+ id?: string;+ command: string;+ success: boolean;+ data?: unknown;+ error?: string;+};++export type SupervisorState = "stopped" | "starting" | "ready" | "restarting";++export type SupervisorEvent =+ | AgentRecord+ | { type: "supervisor_state"; state: SupervisorState }+ | { type: "interrupted" };++export interface SupervisorOptions {+ /** Executable to run, for example `gentle-shell`. */+ command: string;+ /** Arguments placed before the RPC arguments (used to run a script with node). */+ args?: string[];+ /** Arguments placed after the RPC arguments. */+ extraArgs?: string[];+ cwd: string;+ /** Directory for `sessions/` and `state.json`. */+ dataDir: string;+ env?: NodeJS.ProcessEnv;+ /** Respawn delays; the last value repeats. Default 1s, 2s, 4s, 8s, 16s, 30s. */+ backoffMs?: number[];+ /** Uptime after which the backoff starts over. Default 30s. */+ stableMs?: number;+ /** Deadline for one command response. Default 5 minutes. */+ requestTimeoutMs?: number;+ /** Deadline for the agent to answer its first `get_state`. Default 60s. */+ startTimeoutMs?: number;+ /** Grace period after closing stdin before SIGTERM. Default 5s. */+ stopTimeoutMs?: number;+ log?: (line: string) => void;+}++type Pending = {+ resolve: (response: RpcResponse) => void;+ reject: (error: Error) => void;+ timer: NodeJS.Timeout;+};++const DEFAULT_BACKOFF_MS = [1000, 2000, 4000, 8000, 16000, 30000];++/**+ * Runs the agent (`gentle-shell --mode rpc`) as a child process, correlates+ * commands with responses, forwards session events, and respawns the agent+ * after an unexpected exit, reopening the same conversation.+ */+export class AgentSupervisor {+ state: SupervisorState = "stopped";+ busy = false;+ sessionFile: string | undefined;+ sessionId: string | undefined;+ model: string | undefined;++ private child: ChildProcess | undefined;+ private readonly pending = new Map<string, Pending>();+ private readonly listeners = new Set<(event: SupervisorEvent) => void>();+ private nextId = 0;+ private attempts = 0;+ private spawnedAt = 0;+ private stopping = false;+ private interrupted = false;+ private restartTimer: NodeJS.Timeout | undefined;+ private closeWaiters: (() => void)[] = [];+ private readonly sessionDir: string;+ private readonly stateFile: string;+ private readonly options: SupervisorOptions;++ constructor(options: SupervisorOptions) {+ this.options = options;+ this.sessionDir = join(options.dataDir, "sessions");+ this.stateFile = join(options.dataDir, "state.json");+ this.sessionFile = this.readPersistedSession();+ }++ get pid(): number | undefined {+ return this.child?.pid;+ }++ onEvent(listener: (event: SupervisorEvent) => void): () => void {+ this.listeners.add(listener);+ return () => this.listeners.delete(listener);+ }++ /** Spawns the agent and resolves once it answered `get_state`. */+ async start(): Promise<void> {+ this.stopping = false;+ mkdirSync(this.sessionDir, { recursive: true });+ this.setState("starting");+ await this.spawnAndInitialize();+ }++ /** Sends a command and resolves with its successful response. */+ async request(command: AgentRecord): Promise<RpcResponse> {+ if (this.state !== "ready") throw new Error("Agent is not ready");+ const response = await this.rawRequest(command, this.options.requestTimeoutMs ?? 300_000);+ if (+ command.type === "prompt" &&+ (response.data as { disposition?: string } | undefined)?.disposition === "started"+ ) {+ this.busy = true;+ }+ if (command.type === "new_session" || command.type === "switch_session") await this.refreshSession();+ return response;+ }++ /** Writes a record that has no response, such as `extension_ui_response`. */+ send(record: AgentRecord): void {+ if (this.state !== "ready" || !this.child?.stdin?.writable) throw new Error("Agent is not ready");+ this.child.stdin.write(encodeRecord(record));+ }++ async stop(): Promise<void> {+ this.stopping = true;+ clearTimeout(this.restartTimer);+ const child = this.child;+ if (!child) {+ this.setState("stopped");+ return;+ }+ const closed = new Promise<void>((resolve) => this.closeWaiters.push(resolve));+ child.stdin?.end();+ const term = setTimeout(() => child.kill("SIGTERM"), this.options.stopTimeoutMs ?? 5000);+ const kill = setTimeout(() => child.kill("SIGKILL"), (this.options.stopTimeoutMs ?? 5000) + 2000);+ await closed;+ clearTimeout(term);+ clearTimeout(kill);+ }++ private async spawnAndInitialize(): Promise<void> {+ const wanted = this.sessionFile;+ const child = this.spawnChild();+ try {+ const state = await this.rawRequest({ type: "get_state" }, this.options.startTimeoutMs ?? 60_000);+ const current = (state.data as { sessionFile?: string } | undefined)?.sessionFile;+ if (wanted && wanted !== current && existsSync(wanted)) {+ await this.rawRequest({ type: "switch_session", sessionPath: wanted }, 30_000);+ }+ await this.refreshSession();+ } catch (error) {+ if (this.child === child) child.kill("SIGKILL");+ throw error;+ }+ if (this.child !== child) throw new Error("Agent exited during startup");+ this.spawnedAt = Date.now();+ this.setState("ready");+ if (this.interrupted) {+ this.interrupted = false;+ this.emit({ type: "interrupted" });+ }+ }++ private spawnChild(): ChildProcess {+ const { command, args = [], extraArgs = [], cwd, env } = this.options;+ const child = spawn(command, [...args, "--mode", "rpc", "--session-dir", this.sessionDir, ...extraArgs], {+ cwd,+ env: env ?? process.env,+ stdio: ["pipe", "pipe", "pipe"],+ });+ this.child = child;+ const decoder = new JsonlDecoder(+ (record) => this.handleRecord(record as AgentRecord),+ (line) => this.log(`agent wrote a malformed record: ${line.slice(0, 200)}`),+ );+ child.stdout?.on("data", (chunk: Buffer) => decoder.push(chunk));+ child.stderr?.on("data", (chunk: Buffer) => this.log(chunk.toString("utf8").trimEnd()));+ child.stdin?.on("error", () => {});+ child.on("error", (error) => this.log(`agent process error: ${error.message}`));+ child.on("close", (code, signal) => this.handleClose(child, code, signal));+ return child;+ }++ private rawRequest(command: AgentRecord, timeoutMs: number): Promise<RpcResponse> {+ const child = this.child;+ if (!child?.stdin?.writable) return Promise.reject(new Error("Agent is not ready"));+ const id = `d${++this.nextId}`;+ return new Promise<RpcResponse>((resolve, reject) => {+ const timer = setTimeout(() => {+ this.pending.delete(id);+ reject(new Error(`Agent did not answer ${command.type} within ${timeoutMs} ms`));+ }, timeoutMs);+ this.pending.set(id, { resolve, reject, timer });+ child.stdin?.write(encodeRecord({ ...command, id }));+ });+ }++ private handleRecord(record: AgentRecord): void {+ if (record.type === "response") {+ const response = record as unknown as RpcResponse;+ const pending = response.id === undefined ? undefined : this.pending.get(response.id);+ if (!pending || response.id === undefined) return;+ this.pending.delete(response.id);+ clearTimeout(pending.timer);+ if (response.success) pending.resolve(response);+ else pending.reject(new Error(response.error ?? `${response.command} failed`));+ return;+ }+ if (record.type === "agent_start") this.busy = true;+ if (record.type === "agent_settled") {+ this.busy = false;+ void this.refreshSession().catch(() => {});+ }+ this.emit(record);+ }++ private handleClose(child: ChildProcess, code: number | null, signal: NodeJS.Signals | null): void {+ if (child !== this.child) return;+ this.child = undefined;+ const reason = new Error(`Agent exited (${signal ?? `code ${code}`})`);+ for (const [id, pending] of this.pending) {+ clearTimeout(pending.timer);+ pending.reject(reason);+ this.pending.delete(id);+ }+ const wasBusy = this.busy;+ this.busy = false;+ for (const resolve of this.closeWaiters.splice(0)) resolve();+ if (this.stopping) {+ this.setState("stopped");+ return;+ }+ this.log(`agent exited unexpectedly (${signal ?? `code ${code}`})`);+ if (wasBusy) this.interrupted = true;+ this.scheduleRestart();+ }++ private scheduleRestart(): void {+ const backoff = this.options.backoffMs ?? DEFAULT_BACKOFF_MS;+ if (this.spawnedAt && Date.now() - this.spawnedAt > (this.options.stableMs ?? 30_000)) this.attempts = 0;+ const delay = backoff[Math.min(this.attempts, backoff.length - 1)] ?? 1000;+ this.attempts += 1;+ this.setState("restarting");+ this.restartTimer = setTimeout(() => {+ if (this.stopping) return;+ this.spawnAndInitialize().catch((error: Error) => {+ this.log(`agent restart failed: ${error.message}`);+ // A child that is still alive will close and schedule the next attempt.+ if (!this.child && !this.stopping) this.scheduleRestart();+ });+ }, delay);+ }++ private async refreshSession(): Promise<void> {+ const response = await this.rawRequest({ type: "get_state" }, 30_000);+ this.applyState(response.data);+ }++ private applyState(data: unknown): void {+ const state = (data ?? {}) as {+ sessionFile?: string;+ sessionId?: string;+ model?: { name?: string; id?: string };+ };+ if (state.model) this.model = state.model.name ?? state.model.id;+ if (state.sessionId) this.sessionId = state.sessionId;+ if (state.sessionFile && state.sessionFile !== this.sessionFile) {+ this.sessionFile = state.sessionFile;+ }+ if (this.sessionFile) this.persistSession(this.sessionFile);+ }++ private readPersistedSession(): string | undefined {+ try {+ const saved = JSON.parse(readFileSync(this.stateFile, "utf8")) as { sessionFile?: string };+ return typeof saved.sessionFile === "string" ? saved.sessionFile : undefined;+ } catch {+ return undefined;+ }+ }++ private persistSession(sessionFile: string): void {+ mkdirSync(this.options.dataDir, { recursive: true });+ const temp = `${this.stateFile}.${process.pid}.tmp`;+ writeFileSync(temp, `${JSON.stringify({ sessionFile })}\n`, { mode: 0o600 });+ renameSync(temp, this.stateFile);+ }++ private setState(state: SupervisorState): void {+ if (this.state === state) return;+ this.state = state;+ this.emit({ type: "supervisor_state", state });+ }++ private emit(event: SupervisorEvent): void {+ for (const listener of this.listeners) listener(event);+ }++ private log(line: string): void {+ if (line) this.options.log?.(line);+ }+}diff --git a/packages/daemon/test/fixtures/fake-agent.ts b/packages/daemon/test/fixtures/fake-agent.tsnew file mode 100644index 0000000..9ce59fb--- /dev/null+++ b/packages/daemon/test/fixtures/fake-agent.ts@@ -0,0 +1,229 @@+#!/usr/bin/env node+// A deterministic stand-in for `gentle-shell --mode rpc`. It speaks the same JSONL+// records the daemon relies on, persists messages per session file, and has+// scripted prompts for tests:+// "tool:<name>" runs one fake tool call+// "ask:select" asks a select dialog and echoes the answer+// "ask:confirm" asks a confirm dialog and echoes the answer+// "hang" starts a run that only ends on abort+// "crash" starts a run and exits with code 1+// The "noreply" command is never answered.+// Environment:+// FAKE_AGENT_ARGS_FILE write argv as JSON to this file+// FAKE_AGENT_BRANDING emit branded startup UI records+import { randomUUID } from "node:crypto";+import { appendFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";+import { join } from "node:path";++type Rec = Record<string, unknown>;+type Message = { role: "user" | "assistant"; content: string };++const argv = process.argv.slice(2);+if (process.env.FAKE_AGENT_ARGS_FILE) writeFileSync(process.env.FAKE_AGENT_ARGS_FILE, JSON.stringify(argv));+const sessionDir = argValue("--session-dir") ?? join(process.cwd(), ".fake-sessions");+mkdirSync(sessionDir, { recursive: true });++let sessionId = "";+let sessionFile = "";+let messages: Message[] = [];+let busy = false;+let hanging: (() => void) | undefined;+const pendingUi = new Map<string, (rec: Rec) => void>();+newSession();++function argValue(name: string): string | undefined {+ const i = argv.indexOf(name);+ return i >= 0 ? argv[i + 1] : undefined;+}++function out(rec: Rec): void {+ process.stdout.write(`${JSON.stringify(rec)}\n`);+}++function newSession(): void {+ sessionId = randomUUID();+ sessionFile = join(sessionDir, `${sessionId}.jsonl`);+ messages = [];+ writeFileSync(sessionFile, "");+}++function loadSession(path: string): boolean {+ if (!existsSync(path)) return false;+ sessionFile = path;+ sessionId =+ path+ .split("/")+ .pop()+ ?.replace(/\.jsonl$/, "") ?? "";+ messages = readFileSync(path, "utf8")+ .split("\n")+ .filter(Boolean)+ .map((line) => JSON.parse(line) as Message);+ return true;+}++function remember(message: Message): void {+ messages.push(message);+ appendFileSync(sessionFile, `${JSON.stringify(message)}\n`);+}++function respond(id: unknown, command: string, data?: unknown, error?: string): void {+ const rec: Rec = { type: "response", command, success: !error };+ if (id !== undefined) rec.id = id;+ if (data !== undefined) rec.data = data;+ if (error) rec.error = error;+ out(rec);+}++function askUi(request: Rec): Promise<Rec> {+ const id = randomUUID();+ out({ type: "extension_ui_request", id, ...request });+ return new Promise((resolve) => pendingUi.set(id, resolve));+}++function assistantText(text: string): void {+ const message = { role: "assistant", content: [{ type: "text", text }] };+ out({ type: "message_start", message });+ for (const delta of text.match(/.{1,8}/gs) ?? []) {+ out({ type: "message_update", assistantMessageEvent: { type: "text_delta", contentIndex: 0, delta } });+ }+ out({ type: "message_end", message });+ remember({ role: "assistant", content: text });+}++function endRun(): void {+ out({ type: "agent_end", messages: [], willRetry: false });+ busy = false;+ out({ type: "agent_settled" });+}++async function run(text: string) {+ busy = true;+ remember({ role: "user", content: text });+ out({ type: "agent_start" });+ out({ type: "message_start", message: { role: "user", content: text } });+ out({ type: "message_end", message: { role: "user", content: text } });+ if (text === "crash") {+ // Give the pipe time to flush; macOS pipes are asynchronous.+ setTimeout(() => process.exit(1), 50);+ return;+ }+ if (text === "hang") {+ await new Promise<void>((resolve) => {+ hanging = resolve;+ });+ return endRun();+ }+ if (text.startsWith("tool:")) {+ const toolName = text.slice(5);+ const toolCallId = randomUUID();+ out({ type: "tool_execution_start", toolCallId, toolName, args: { path: "README.md" } });+ out({ type: "tool_execution_end", toolCallId, toolName, result: { content: [] }, isError: false });+ assistantText(`Ran ${toolName}`);+ return endRun();+ }+ if (text === "ask:select") {+ const answer = await askUi({ method: "select", title: "Pick a color", options: ["Red", "Blue"] });+ assistantText(answer.cancelled ? "Cancelled" : `You chose ${String(answer.value)}`);+ return endRun();+ }+ if (text === "ask:confirm") {+ const answer = await askUi({+ method: "confirm",+ title: "Proceed?",+ message: "Gentle Shell wants to continue",+ });+ assistantText(answer.confirmed ? "Confirmed" : "Declined");+ return endRun();+ }+ assistantText(`Echo: ${text}`);+ endRun();+}++function handle(rec: Rec) {+ const { id, type } = rec;+ switch (type) {+ case "get_state":+ return respond(id, "get_state", {+ model: { id: "fake-model", name: "Fake Model", provider: "fake" },+ thinkingLevel: "medium",+ isStreaming: busy,+ sessionFile,+ sessionId,+ messageCount: messages.length,+ });+ case "get_messages":+ return respond(id, "get_messages", {+ messages: messages.map((m) =>+ m.role === "user"+ ? { role: "user", content: m.content }+ : { role: "assistant", content: [{ type: "text", text: m.content }] },+ ),+ });+ case "get_commands":+ return respond(id, "get_commands", { commands: [{ name: "gentle:status" }, { name: "history" }] });+ case "prompt": {+ if (busy && !rec.streamingBehavior) return respond(id, "prompt", undefined, "Agent is streaming");+ if (busy) return respond(id, "prompt", { disposition: "queued" });+ respond(id, "prompt", { disposition: "started" });+ void run(String(rec.message));+ return;+ }+ case "steer":+ case "follow_up":+ return respond(id, type, { disposition: "queued" });+ case "abort":+ hanging?.();+ hanging = undefined;+ return respond(id, "abort");+ case "new_session":+ newSession();+ return respond(id, "new_session", { cancelled: false });+ case "switch_session":+ if (!loadSession(String(rec.sessionPath))) {+ return respond(id, "switch_session", undefined, "Session not found");+ }+ return respond(id, "switch_session", { cancelled: false });+ case "noreply":+ return;+ case "extension_ui_response": {+ const resolve = pendingUi.get(String(id));+ pendingUi.delete(String(id));+ resolve?.(rec);+ return;+ }+ default:+ return respond(id, String(type), undefined, `Unknown command: ${String(type)}`);+ }+}++if (process.env.FAKE_AGENT_BRANDING) {+ out({+ type: "extension_ui_request",+ id: randomUUID(),+ method: "setStatus",+ statusKey: "gentle",+ statusText: "Gentle Shell ready",+ });+ out({+ type: "extension_ui_request",+ id: randomUUID(),+ method: "notify",+ message: "el Gentleman loaded ODD",+ notifyType: "info",+ });+}++let buffer = "";+process.stdin.setEncoding("utf8");+process.stdin.on("data", (chunk: string) => {+ buffer += chunk;+ let newline = buffer.indexOf("\n");+ while (newline >= 0) {+ const line = buffer.slice(0, newline).replace(/\r$/, "");+ buffer = buffer.slice(newline + 1);+ if (line) handle(JSON.parse(line) as Rec);+ newline = buffer.indexOf("\n");+ }+});+process.stdin.on("end", () => process.exit(0));diff --git a/packages/daemon/test/helpers.ts b/packages/daemon/test/helpers.tsnew file mode 100644index 0000000..ca8b800--- /dev/null+++ b/packages/daemon/test/helpers.ts@@ -0,0 +1,36 @@+import { mkdtempSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { fileURLToPath } from "node:url";+import { AgentSupervisor, type SupervisorEvent, type SupervisorOptions } from "../src/supervisor.ts";++export const FAKE_AGENT = fileURLToPath(new URL("./fixtures/fake-agent.ts", import.meta.url));++export function tempDir(): string {+ return mkdtempSync(join(tmpdir(), "gentle-dot-test-"));+}++export function fakeSupervisor(overrides: Partial<SupervisorOptions> = {}) {+ const dataDir = overrides.dataDir ?? tempDir();+ const supervisor = new AgentSupervisor({+ command: process.execPath,+ args: [FAKE_AGENT],+ cwd: dataDir,+ dataDir,+ backoffMs: [50, 100, 200],+ ...overrides,+ });+ const events: SupervisorEvent[] = [];+ supervisor.onEvent((event) => events.push(event));+ return { supervisor, events, dataDir };+}++export async function waitFor<T>(probe: () => T | undefined | false, timeoutMs = 5000): Promise<T> {+ const started = Date.now();+ for (;;) {+ const value = probe();+ if (value) return value;+ if (Date.now() - started > timeoutMs) throw new Error("waitFor timed out");+ await new Promise((resolve) => setTimeout(resolve, 10));+ }+}diff --git a/packages/daemon/test/jsonl.test.ts b/packages/daemon/test/jsonl.test.tsnew file mode 100644index 0000000..d349dba--- /dev/null+++ b/packages/daemon/test/jsonl.test.ts@@ -0,0 +1,42 @@+import { describe, expect, it } from "vitest";+import { encodeRecord, JsonlDecoder } from "../src/jsonl.ts";++function decodeAll(chunks: Buffer[]) {+ const records: unknown[] = [];+ const errors: string[] = [];+ const decoder = new JsonlDecoder(+ (record) => records.push(record),+ (line) => errors.push(line),+ );+ for (const chunk of chunks) decoder.push(chunk);+ return { records, errors };+}++describe("JsonlDecoder", () => {+ it("splits records only on LF and keeps U+2028/U+2029 inside strings", () => {+ const text = `${JSON.stringify({ a: "x\u2028y\u2029z" })}\n${JSON.stringify({ b: 1 })}\n`;+ const { records } = decodeAll([Buffer.from(text)]);+ expect(records).toEqual([{ a: "x\u2028y\u2029z" }, { b: 1 }]);+ });++ it("joins records split across chunks, including inside a multi-byte character", () => {+ const bytes = Buffer.from(`${JSON.stringify({ text: "año ✓" })}\n`);+ const { records } = decodeAll([bytes.subarray(0, 12), bytes.subarray(12)]);+ expect(records).toEqual([{ text: "año ✓" }]);+ });++ it("accepts CRLF and ignores blank lines", () => {+ const { records } = decodeAll([Buffer.from('{"a":1}\r\n\n{"b":2}\n')]);+ expect(records).toEqual([{ a: 1 }, { b: 2 }]);+ });++ it("reports malformed lines without stopping", () => {+ const { records, errors } = decodeAll([Buffer.from('not json\n{"ok":true}\n')]);+ expect(errors).toEqual(["not json"]);+ expect(records).toEqual([{ ok: true }]);+ });++ it("encodes one record per line", () => {+ expect(encodeRecord({ type: "get_state" })).toBe('{"type":"get_state"}\n');+ });+});diff --git a/packages/daemon/test/supervisor.test.ts b/packages/daemon/test/supervisor.test.tsnew file mode 100644index 0000000..b5ddec3--- /dev/null+++ b/packages/daemon/test/supervisor.test.ts@@ -0,0 +1,120 @@+import { readFileSync } from "node:fs";+import { join } from "node:path";+import { afterEach, describe, expect, it } from "vitest";+import type { AgentSupervisor } from "../src/supervisor.ts";+import { fakeSupervisor, tempDir, waitFor } from "./helpers.ts";++const running: AgentSupervisor[] = [];+afterEach(async () => {+ await Promise.all(running.splice(0).map((s) => s.stop()));+});++function track<T extends { supervisor: AgentSupervisor }>(value: T): T {+ running.push(value.supervisor);+ return value;+}++describe("AgentSupervisor", () => {+ it("spawns the agent in RPC mode with the session dir and extra args", async () => {+ const argsFile = join(tempDir(), "argv.json");+ const { supervisor, dataDir } = track(+ fakeSupervisor({ env: { ...process.env, FAKE_AGENT_ARGS_FILE: argsFile }, extraArgs: ["--x", "1"] }),+ );+ await supervisor.start();+ const argv = JSON.parse(readFileSync(argsFile, "utf8")) as string[];+ expect(argv).toEqual(["--mode", "rpc", "--session-dir", join(dataDir, "sessions"), "--x", "1"]);+ expect(supervisor.state).toBe("ready");+ });++ it("correlates responses by id across concurrent commands", async () => {+ const { supervisor } = track(fakeSupervisor());+ await supervisor.start();+ const [state, commands] = await Promise.all([+ supervisor.request({ type: "get_state" }),+ supervisor.request({ type: "get_commands" }),+ ]);+ expect(state.command).toBe("get_state");+ expect(commands.command).toBe("get_commands");+ });++ it("rejects a failed command with the agent's error", async () => {+ const { supervisor } = track(fakeSupervisor());+ await supervisor.start();+ await expect(supervisor.request({ type: "switch_session", sessionPath: "/nope.jsonl" })).rejects.toThrow(+ "Session not found",+ );+ });++ it("forwards session events and tracks busy until agent_settled", async () => {+ const { supervisor, events } = track(fakeSupervisor());+ await supervisor.start();+ await supervisor.request({ type: "prompt", message: "hello" });+ await waitFor(() => events.some((e) => e.type === "agent_settled"));+ expect(events.map((e) => e.type)).toContain("message_update");+ expect(supervisor.busy).toBe(false);+ });++ it("respawns after a crash, reopens the same conversation, and reports the interruption", async () => {+ const { supervisor, events } = track(fakeSupervisor());+ await supervisor.start();+ await supervisor.request({ type: "prompt", message: "first" });+ await waitFor(() => events.some((e) => e.type === "agent_settled"));+ const sessionBefore = supervisor.sessionFile;+ const pidBefore = supervisor.pid;++ await supervisor.request({ type: "prompt", message: "crash" });+ await waitFor(() => events.some((e) => e.type === "interrupted"));++ expect(supervisor.state).toBe("ready");+ expect(supervisor.pid).not.toBe(pidBefore);+ expect(supervisor.sessionFile).toBe(sessionBefore);+ const states = events.flatMap((e) => (e.type === "supervisor_state" && "state" in e ? [e.state] : []));+ expect(states).toContain("restarting");+ const history = await supervisor.request({ type: "get_messages" });+ const texts = (history.data as { messages: { content: unknown }[] }).messages.map((m) => m.content);+ expect(texts[0]).toBe("first");+ });++ it("does not report an interruption when the agent dies while idle", async () => {+ const { supervisor, events } = track(fakeSupervisor());+ await supervisor.start();+ process.kill(supervisor.pid ?? 0, "SIGKILL");+ await waitFor(+ () =>+ events.filter((e) => e.type === "supervisor_state" && "state" in e && e.state === "ready").length >=+ 2,+ );+ expect(events.some((e) => e.type === "interrupted")).toBe(false);+ });++ it("rejects pending commands when the agent exits", async () => {+ const { supervisor } = track(fakeSupervisor());+ await supervisor.start();+ const pending = supervisor.request({ type: "noreply" });+ process.kill(supervisor.pid ?? 0, "SIGKILL");+ await expect(pending).rejects.toThrow(/agent exited/i);+ });++ it("reopens the last conversation after the daemon itself restarts", async () => {+ const dataDir = tempDir();+ const first = track(fakeSupervisor({ dataDir }));+ await first.supervisor.start();+ await first.supervisor.request({ type: "prompt", message: "remember me" });+ await waitFor(() => first.events.some((e) => e.type === "agent_settled"));+ await waitFor(() => first.supervisor.sessionFile && first.supervisor.sessionFile);+ const session = first.supervisor.sessionFile;+ await first.supervisor.stop();++ const second = track(fakeSupervisor({ dataDir }));+ await second.supervisor.start();+ expect(second.supervisor.sessionFile).toBe(session);+ });++ it("stops cleanly and reports the stopped state", async () => {+ const { supervisor } = track(fakeSupervisor());+ await supervisor.start();+ await supervisor.stop();+ expect(supervisor.state).toBe("stopped");+ await expect(supervisor.request({ type: "get_state" })).rejects.toThrow(/not ready/i);+ });+});