Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

feat: improve cli steering

Gus9161a8febb0e
diff --git a/src/cli/daemon/agent/__tests__/claude.parseLine.test.ts b/src/cli/daemon/agent/__tests__/claude.parseLine.test.ts
new file mode 100644
index 000000000..262e2fc2b
--- /dev/null
+++ b/src/cli/daemon/agent/__tests__/claude.parseLine.test.ts
@@ -0,0 +1,167 @@
+import { describe, it, expect } from "vitest";
+import { ClaudeBackend } from "../claude.js";
+
+const backend = new ClaudeBackend("claude");
+
+describe("ClaudeBackend.parseLine", () => {
+ it("empty line returns empty", () => {
+ expect(backend.parseLine("")).toEqual([]);
+ expect(backend.parseLine(" ")).toEqual([]);
+ });
+
+ it("invalid JSON returns log event", () => {
+ const events = backend.parseLine("not json");
+ expect(events).toHaveLength(1);
+ expect(events[0].kind).toBe("log");
+ });
+
+ it("system init → session_init", () => {
+ const line = JSON.stringify({ type: "system", subtype: "init", session_id: "sess-123" });
+ const events = backend.parseLine(line);
+ expect(events).toEqual([{ kind: "session_init", sessionId: "sess-123" }]);
+ });
+
+ it("assistant text → text", () => {
+ const line = JSON.stringify({
+ type: "assistant",
+ message: { content: [{ type: "text", text: "hello world" }] },
+ });
+ const events = backend.parseLine(line);
+ expect(events).toEqual([{ kind: "text", text: "hello world" }]);
+ });
+
+ it("assistant thinking → thinking", () => {
+ const line = JSON.stringify({
+ type: "assistant",
+ message: { content: [{ type: "thinking", text: "let me think" }] },
+ });
+ const events = backend.parseLine(line);
+ expect(events).toEqual([{ kind: "thinking", text: "let me think" }]);
+ });
+
+ it("assistant tool_use → tool_call", () => {
+ const line = JSON.stringify({
+ type: "assistant",
+ message: { content: [{ type: "tool_use", name: "Bash", id: "tc-1", input: { command: "ls" } }] },
+ });
+ const events = backend.parseLine(line);
+ expect(events).toEqual([{
+ kind: "tool_call",
+ name: "Bash",
+ callId: "tc-1",
+ input: { command: "ls" },
+ }]);
+ });
+
+ it("tool_result → tool_output", () => {
+ const line = JSON.stringify({ type: "tool_result", tool_use_id: "tc-1", content: "file.txt" });
+ const events = backend.parseLine(line);
+ expect(events).toEqual([{ kind: "tool_output", callId: "tc-1", output: "file.txt" }]);
+ });
+
+ it("result → turn_end with sessionId + enriched telemetry", () => {
+ const line = JSON.stringify({
+ type: "result",
+ result: "done",
+ session_id: "s1",
+ usage: {
+ input_tokens: 100,
+ output_tokens: 50,
+ cache_read_input_tokens: 20,
+ cache_creation_input_tokens: 10,
+ service_tier: "default",
+ },
+ total_cost_usd: 0.005,
+ duration_ms: 1200,
+ });
+ const events = backend.parseLine(line);
+ expect(events).toHaveLength(2);
+ expect(events[0]).toEqual({ kind: "turn_end", sessionId: "s1" });
+ expect(events[1].kind).toBe("telemetry");
+ const telemetry = events[1] as { kind: "telemetry"; attrs: Record<string, unknown>; source?: string };
+ expect(telemetry.source).toBe("claude_result_usage");
+ expect(telemetry.attrs.cachedInputTokens).toBe(20);
+ expect(telemetry.attrs.cacheCreationInputTokens).toBe(10);
+ expect(telemetry.attrs.totalCostUsd).toBe(0.005);
+ expect(telemetry.attrs.serviceTier).toBe("default");
+ });
+
+ it("result with is_error → error + turn_end", () => {
+ const line = JSON.stringify({ type: "result", result: "something broke", is_error: true });
+ const events = backend.parseLine(line);
+ expect(events[0]).toEqual({ kind: "error", message: "something broke" });
+ expect(events[1].kind).toBe("turn_end");
+ });
+
+ it("turn_end carries sessionId from result", () => {
+ const line = JSON.stringify({ type: "result", result: "ok", session_id: "s42" });
+ const events = backend.parseLine(line);
+ const turnEnd = events.find((e) => e.kind === "turn_end") as { kind: "turn_end"; sessionId?: string };
+ expect(turnEnd.sessionId).toBe("s42");
+ });
+
+ it("control_request → permission_request", () => {
+ const line = JSON.stringify({ type: "control_request", request_id: "req-1", payload: { tool: "Bash" } });
+ const events = backend.parseLine(line);
+ expect(events).toEqual([{
+ kind: "permission_request",
+ requestId: "req-1",
+ payload: { tool: "Bash" },
+ }]);
+ });
+
+ it("system compaction → compaction_started", () => {
+ const line = JSON.stringify({ type: "system", subtype: "compaction" });
+ const events = backend.parseLine(line);
+ expect(events).toEqual([{ kind: "compaction_started" }]);
+ });
+
+ it("system context_pruning → compaction_started", () => {
+ const line = JSON.stringify({ type: "system", subtype: "context_pruning" });
+ const events = backend.parseLine(line);
+ expect(events).toEqual([{ kind: "compaction_started" }]);
+ });
+
+ it("system compaction_finished → compaction_finished", () => {
+ const line = JSON.stringify({ type: "system", subtype: "compaction_finished" });
+ const events = backend.parseLine(line);
+ expect(events).toEqual([{ kind: "compaction_finished" }]);
+ });
+
+ it("system status → internal_progress with source and itemType", () => {
+ const line = JSON.stringify({ type: "system", subtype: "status", status: "something" });
+ const events = backend.parseLine(line);
+ expect(events).toHaveLength(1);
+ expect(events[0].kind).toBe("internal_progress");
+ const ip = events[0] as { kind: "internal_progress"; source?: string; itemType?: string };
+ expect(ip.source).toBe("claude_system");
+ expect(ip.itemType).toBe("status");
+ });
+
+ it("system stream_event → internal_progress", () => {
+ const line = JSON.stringify({ type: "system", subtype: "stream_event", data: {} });
+ const events = backend.parseLine(line);
+ expect(events).toHaveLength(1);
+ expect(events[0].kind).toBe("internal_progress");
+ const ip = events[0] as { kind: "internal_progress"; source?: string; itemType?: string };
+ expect(ip.source).toBe("claude_system");
+ expect(ip.itemType).toBe("stream_event");
+ });
+});
+
+describe("ClaudeBackend.encodeStdinMessage", () => {
+ it("encodes a user message", () => {
+ const encoded = backend.encodeStdinMessage("hello", "idle");
+ expect(encoded).not.toBeNull();
+ const parsed = JSON.parse(encoded!);
+ expect(parsed.type).toBe("user");
+ expect(parsed.message.role).toBe("user");
+ expect(parsed.message.content[0].text).toBe("hello");
+ });
+
+ it("includes session_id when provided", () => {
+ const encoded = backend.encodeStdinMessage("hi", "busy", { sessionId: "s1" });
+ const parsed = JSON.parse(encoded!);
+ expect(parsed.session_id).toBe("s1");
+ });
+});
diff --git a/src/cli/daemon/agent/__tests__/codex.parseLine.test.ts b/src/cli/daemon/agent/__tests__/codex.parseLine.test.ts
new file mode 100644
index 000000000..d94fdddb9
--- /dev/null
+++ b/src/cli/daemon/agent/__tests__/codex.parseLine.test.ts
@@ -0,0 +1,182 @@
+import { describe, it, expect } from "vitest";
+import { CodexBackend } from "../codex.js";
+
+const backend = new CodexBackend("codex");
+
+describe("CodexBackend.parseLine — raw protocol", () => {
+ it("empty line returns empty", () => {
+ expect(backend.parseLine("")).toEqual([]);
+ });
+
+ it("invalid JSON returns log event", () => {
+ const events = backend.parseLine("not json");
+ expect(events[0].kind).toBe("log");
+ });
+
+ it("turn/completed → turn_end", () => {
+ const line = JSON.stringify({ jsonrpc: "2.0", method: "turn/completed", params: { turn: { status: "completed" } } });
+ const events = backend.parseLine(line);
+ expect(events).toEqual([{ kind: "turn_end" }]);
+ });
+
+ it("turn/completed with error → error + turn_end", () => {
+ const line = JSON.stringify({ jsonrpc: "2.0", method: "turn/completed", params: { turn: { status: "failed", error: { message: "oops" } } } });
+ const events = backend.parseLine(line);
+ expect(events[0]).toEqual({ kind: "error", message: "oops" });
+ expect(events[1]).toEqual({ kind: "turn_end" });
+ });
+
+ it("item/completed agentMessage → text", () => {
+ const line = JSON.stringify({ jsonrpc: "2.0", method: "item/completed", params: { item: { type: "agentMessage", text: "answer" } } });
+ const events = backend.parseLine(line);
+ expect(events).toEqual([{ kind: "text", text: "answer" }]);
+ });
+
+ it("item/started commandExecution → tool_call", () => {
+ const line = JSON.stringify({ jsonrpc: "2.0", method: "item/started", params: { item: { type: "commandExecution", id: "cmd-1" } } });
+ const events = backend.parseLine(line);
+ expect(events[0].kind).toBe("tool_call");
+ expect((events[0] as { callId: string }).callId).toBe("cmd-1");
+ });
+
+ it("item/completed commandExecution → tool_output", () => {
+ const line = JSON.stringify({ jsonrpc: "2.0", method: "item/completed", params: { item: { type: "commandExecution", id: "cmd-1", aggregatedOutput: "result" } } });
+ const events = backend.parseLine(line);
+ expect(events[0].kind).toBe("tool_output");
+ expect((events[0] as { output: string }).output).toBe("result");
+ });
+
+ it("error notification → error", () => {
+ const line = JSON.stringify({ jsonrpc: "2.0", method: "error", params: { error: { message: "bad things" }, willRetry: false } });
+ const events = backend.parseLine(line);
+ expect(events).toEqual([{ kind: "error", message: "bad things" }]);
+ });
+
+ it("error with willRetry=true emits nothing", () => {
+ const line = JSON.stringify({ jsonrpc: "2.0", method: "error", params: { error: { message: "transient" }, willRetry: true } });
+ const events = backend.parseLine(line);
+ expect(events).toHaveLength(0);
+ });
+
+ it("thread/status/changed idle → turn_end", () => {
+ const line = JSON.stringify({ jsonrpc: "2.0", method: "thread/status/changed", params: { status: { type: "idle" } } });
+ const events = backend.parseLine(line);
+ expect(events).toEqual([{ kind: "turn_end" }]);
+ });
+
+ it("response (has id, no method) returns empty", () => {
+ const line = JSON.stringify({ jsonrpc: "2.0", id: 1, result: {} });
+ expect(backend.parseLine(line)).toEqual([]);
+ });
+
+ it("server request (has id AND method) returns empty", () => {
+ const line = JSON.stringify({ jsonrpc: "2.0", id: 1, method: "item/commandExecution/requestApproval", params: {} });
+ expect(backend.parseLine(line)).toEqual([]);
+ });
+
+ // --- New event mappings ---
+
+ it("item/started mcpToolCall → tool_call with mcp_ prefix", () => {
+ const line = JSON.stringify({ jsonrpc: "2.0", method: "item/started", params: { item: { type: "mcpToolCall", name: "readFile", id: "mcp-1" } } });
+ const events = backend.parseLine(line);
+ expect(events).toHaveLength(1);
+ expect(events[0].kind).toBe("tool_call");
+ expect((events[0] as { name: string }).name).toBe("mcp_readFile");
+ });
+
+ it("item/started webSearch → tool_call web_search", () => {
+ const line = JSON.stringify({ jsonrpc: "2.0", method: "item/started", params: { item: { type: "webSearch", id: "ws-1" } } });
+ const events = backend.parseLine(line);
+ expect(events).toHaveLength(1);
+ expect(events[0].kind).toBe("tool_call");
+ expect((events[0] as { name: string }).name).toBe("web_search");
+ });
+
+ it("item/started collabAgentToolCall → tool_call collab_agent", () => {
+ const line = JSON.stringify({ jsonrpc: "2.0", method: "item/started", params: { item: { type: "collabAgentToolCall", id: "ca-1" } } });
+ const events = backend.parseLine(line);
+ expect(events).toHaveLength(1);
+ expect(events[0].kind).toBe("tool_call");
+ expect((events[0] as { name: string }).name).toBe("collab_agent");
+ });
+
+ it("item/started contextCompaction → compaction_started", () => {
+ const line = JSON.stringify({ jsonrpc: "2.0", method: "item/started", params: { item: { type: "contextCompaction" } } });
+ const events = backend.parseLine(line);
+ expect(events).toEqual([{ kind: "compaction_started" }]);
+ });
+
+ it("item/completed reasoning → thinking", () => {
+ const line = JSON.stringify({ jsonrpc: "2.0", method: "item/completed", params: { item: { type: "reasoning", text: "I think..." } } });
+ const events = backend.parseLine(line);
+ expect(events).toEqual([{ kind: "thinking", text: "I think..." }]);
+ });
+
+ it("item/completed mcpToolCall → tool_output", () => {
+ const line = JSON.stringify({ jsonrpc: "2.0", method: "item/completed", params: { item: { type: "mcpToolCall", name: "readFile", id: "mcp-1", output: "file contents" } } });
+ const events = backend.parseLine(line);
+ expect(events).toHaveLength(1);
+ expect(events[0].kind).toBe("tool_output");
+ expect((events[0] as { name: string }).name).toBe("mcp_readFile");
+ });
+
+ it("item/completed contextCompaction → compaction_finished", () => {
+ const line = JSON.stringify({ jsonrpc: "2.0", method: "item/completed", params: { item: { type: "contextCompaction" } } });
+ const events = backend.parseLine(line);
+ expect(events).toEqual([{ kind: "compaction_finished" }]);
+ });
+
+ it("item/agentMessage/delta → text (not internal_progress)", () => {
+ const line = JSON.stringify({ jsonrpc: "2.0", method: "item/agentMessage/delta", params: { delta: "streaming..." } });
+ const events = backend.parseLine(line);
+ expect(events).toHaveLength(1);
+ expect(events[0].kind).toBe("text");
+ expect((events[0] as { text: string }).text).toBe("streaming...");
+ });
+});
+
+describe("CodexBackend.parseLine — legacy protocol", () => {
+ it("codex/event agent_message → text", () => {
+ const line = JSON.stringify({ jsonrpc: "2.0", method: "codex/event", params: { type: "agent_message", text: "hello" } });
+ const events = backend.parseLine(line);
+ expect(events).toEqual([{ kind: "text", text: "hello" }]);
+ });
+
+ it("codex/event task_complete → turn_end", () => {
+ const line = JSON.stringify({ jsonrpc: "2.0", method: "codex/event", params: { type: "task_complete" } });
+ const events = backend.parseLine(line);
+ expect(events).toEqual([{ kind: "turn_end" }]);
+ });
+
+ it("codex/event exec_command_begin → tool_call", () => {
+ const line = JSON.stringify({ jsonrpc: "2.0", method: "codex/event", params: { type: "exec_command_begin", id: "c1" } });
+ const events = backend.parseLine(line);
+ expect(events[0].kind).toBe("tool_call");
+ });
+
+ it("codex/event exec_command_end → tool_output", () => {
+ const line = JSON.stringify({ jsonrpc: "2.0", method: "codex/event", params: { type: "exec_command_end", id: "c1", output: "done" } });
+ const events = backend.parseLine(line);
+ expect(events[0].kind).toBe("tool_output");
+ });
+});
+
+describe("CodexBackend.encodeStdinMessage", () => {
+ it("returns null without threadId", () => {
+ expect(backend.encodeStdinMessage("hi", "idle")).toBeNull();
+ });
+
+ it("encodes idle mode as turn/start", () => {
+ const encoded = backend.encodeStdinMessage("hi", "idle", { threadId: "t1", requestId: 5 });
+ const parsed = JSON.parse(encoded!);
+ expect(parsed.method).toBe("turn/start");
+ expect(parsed.params.threadId).toBe("t1");
+ expect(parsed.params.input[0].text).toBe("hi");
+ });
+
+ it("encodes busy mode as turn/steer", () => {
+ const encoded = backend.encodeStdinMessage("hi", "busy", { threadId: "t1", requestId: 6 });
+ const parsed = JSON.parse(encoded!);
+ expect(parsed.method).toBe("turn/steer");
+ });
+});
diff --git a/src/cli/daemon/agent/__tests__/opencode.parseLine.test.ts b/src/cli/daemon/agent/__tests__/opencode.parseLine.test.ts
new file mode 100644
index 000000000..82798db20
--- /dev/null
+++ b/src/cli/daemon/agent/__tests__/opencode.parseLine.test.ts
@@ -0,0 +1,100 @@
+import { describe, it, expect } from "vitest";
+import { OpenCodeBackend } from "../opencode.js";
+
+const backend = new OpenCodeBackend("opencode");
+
+describe("OpenCodeBackend.parseLine", () => {
+ it("empty line returns empty", () => {
+ expect(backend.parseLine("")).toEqual([]);
+ });
+
+ it("invalid JSON returns log event", () => {
+ const events = backend.parseLine("not json");
+ expect(events[0].kind).toBe("log");
+ });
+
+ it("session → session_init", () => {
+ const line = JSON.stringify({ type: "session", session_id: "oc-1" });
+ const events = backend.parseLine(line);
+ expect(events).toEqual([{ kind: "session_init", sessionId: "oc-1" }]);
+ });
+
+ it("text with part → text", () => {
+ const line = JSON.stringify({ type: "text", part: { text: "answer" } });
+ const events = backend.parseLine(line);
+ expect(events).toContainEqual({ kind: "text", text: "answer" });
+ });
+
+ it("thinking → thinking", () => {
+ const line = JSON.stringify({ type: "thinking", part: { thinking: "hmm" } });
+ const events = backend.parseLine(line);
+ expect(events).toContainEqual({ kind: "thinking", text: "hmm" });
+ });
+
+ it("tool_call → tool_call", () => {
+ const line = JSON.stringify({ type: "tool_call", name: "Bash", call_id: "tc-1", input: { cmd: "ls" } });
+ const events = backend.parseLine(line);
+ expect(events).toContainEqual({
+ kind: "tool_call",
+ name: "Bash",
+ callId: "tc-1",
+ input: { cmd: "ls" },
+ });
+ });
+
+ it("tool_result → tool_output", () => {
+ const line = JSON.stringify({ type: "tool_result", call_id: "tc-1", output: "files" });
+ const events = backend.parseLine(line);
+ expect(events).toContainEqual({
+ kind: "tool_output",
+ callId: "tc-1",
+ output: "files",
+ });
+ });
+
+ it("done → turn_end", () => {
+ const line = JSON.stringify({ type: "done", output: "result", session_id: "s1" });
+ const events = backend.parseLine(line);
+ const turnEnds = events.filter((e) => e.kind === "turn_end");
+ expect(turnEnds.length).toBeGreaterThanOrEqual(1);
+ });
+
+ it("complete with error status → error + turn_end", () => {
+ const line = JSON.stringify({ type: "complete", status: "error", output: "failed" });
+ const events = backend.parseLine(line);
+ expect(events).toContainEqual({ kind: "error", message: "failed" });
+ expect(events).toContainEqual({ kind: "turn_end" });
+ });
+
+ it("step_finish reason=stop → turn_end", () => {
+ const line = JSON.stringify({ type: "step_finish", part: { reason: "stop" } });
+ const events = backend.parseLine(line);
+ expect(events).toContainEqual({ kind: "turn_end" });
+ });
+
+ it("step_finish reason=end_turn → turn_end", () => {
+ const line = JSON.stringify({ type: "step_finish", part: { reason: "end_turn" } });
+ const events = backend.parseLine(line);
+ expect(events).toContainEqual({ kind: "turn_end" });
+ });
+
+ it("error → error + turn_end", () => {
+ const line = JSON.stringify({ type: "error", message: "boom" });
+ const events = backend.parseLine(line);
+ expect(events).toContainEqual({ kind: "error", message: "boom" });
+ expect(events).toContainEqual({ kind: "turn_end" });
+ });
+
+ it("message with role=assistant → text", () => {
+ const line = JSON.stringify({ type: "message", role: "assistant", content: "hello" });
+ const events = backend.parseLine(line);
+ expect(events).toContainEqual({ kind: "text", text: "hello" });
+ });
+});
+
+describe("OpenCodeBackend.encodeStdinMessage", () => {
+ it("always returns null", () => {
+ expect(backend.encodeStdinMessage("hi", "idle")).toBeNull();
+ expect(backend.encodeStdinMessage("hi", "busy")).toBeNull();
+ });
+});
diff --git a/src/cli/daemon/agent/claude.ts b/src/cli/daemon/agent/claude.ts
index 214e252d9..e36760c67 100644
--- a/src/cli/daemon/agent/claude.ts
+++ b/src/cli/daemon/agent/claude.ts
@@ -1,24 +1,170 @@
import { spawn, type ChildProcess } from "child_process";
import { createInterface } from "readline";
import type { AgentBackend, AgentSession } from "./index.js";
-import type { ExecOptions, AgentMessage, AgentResult } from "../types.js";
+import type {
+ ExecOptions,
+ AgentMessage,
+ AgentResult,
+ ParsedEvent,
+ StdinMode,
+ DriverLifecycle,
+ BusyDeliveryMode,
+ EncodeOpts,
+} from "../types.js";
import { killProcessTree } from "../kill-tree.js";
export class ClaudeBackend implements AgentBackend {
name = "claude";
+ lifecycle: DriverLifecycle = { kind: "persistent", stdin: "gated", inFlightWake: "queue" };
+ busyDeliveryMode: BusyDeliveryMode = "gated";
+ supportsStdinNotification = true;
constructor(private cliPath: string) {}
+ parseLine(line: string): ParsedEvent[] {
+ if (!line.trim()) return [];
+ let event: Record<string, unknown>;
+ try {
+ event = JSON.parse(line);
+ } catch {
+ return [{ kind: "log", content: line, level: "debug" }];
+ }
+
+ const events: ParsedEvent[] = [];
+ const eventType = event.type as string | undefined;
+
+ switch (eventType) {
+ case "assistant": {
+ const message = event.message as Record<string, unknown> | undefined;
+ if (!message) break;
+ const content = message.content as
+ | { type: string; text?: string; name?: string; id?: string; input?: Record<string, unknown> }[]
+ | undefined;
+ if (!Array.isArray(content)) break;
+
+ for (const block of content) {
+ if (block.type === "text") {
+ events.push({ kind: "text", text: block.text || "" });
+ } else if (block.type === "thinking") {
+ events.push({ kind: "thinking", text: block.text || "" });
+ } else if (block.type === "tool_use") {
+ events.push({ kind: "tool_call", name: block.name || "", input: block.input, callId: block.id });
+ }
+ }
+ break;
+ }
+
+ case "result": {
+ const result = event.result as string | undefined;
+ const isError = event.is_error as boolean | undefined;
+ if (isError) {
+ events.push({ kind: "error", message: result || "unknown error" });
+ }
+ const resultSessionId = event.session_id as string | undefined;
+ events.push({ kind: "turn_end", sessionId: resultSessionId || undefined });
+ const usage = event.usage as Record<string, unknown> | undefined;
+ if (usage || event.total_cost_usd != null) {
+ events.push({
+ kind: "telemetry",
+ name: "token_usage",
+ source: "claude_result_usage",
+ usageKind: "per_turn",
+ attrs: {
+ inputTokens: usage?.input_tokens,
+ outputTokens: usage?.output_tokens,
+ cachedInputTokens: usage?.cache_read_input_tokens,
+ cacheCreationInputTokens: usage?.cache_creation_input_tokens,
+ totalCostUsd: event.total_cost_usd,
+ durationMs: event.duration_ms,
+ durationApiMs: event.duration_api_ms,
+ numTurns: event.num_turns,
+ resultSubtype: event.subtype,
+ resultIsError: event.is_error,
+ serviceTier: usage?.service_tier,
+ },
+ });
+ }
+ break;
+ }
+
+ case "tool_result": {
+ const toolUseId = event.tool_use_id as string | undefined;
+ const content = event.content as string | undefined;
+ events.push({ kind: "tool_output", callId: toolUseId, output: content });
+ break;
+ }
+
+ case "system": {
+ const subtype = event.subtype as string | undefined;
+ if (subtype === "init") {
+ const sid = event.session_id as string | undefined;
+ events.push({ kind: "session_init", sessionId: sid || "" });
+ } else if (subtype === "context_pruning" || subtype === "compaction") {
+ events.push({ kind: "compaction_started" });
+ } else if (subtype === "compaction_finished" || subtype === "context_pruning_finished") {
+ events.push({ kind: "compaction_finished" });
+ } else if (subtype === "status" || subtype === "stream_event") {
+ events.push({
+ kind: "internal_progress",
+ source: "claude_system",
+ itemType: subtype,
+ payloadBytes: line.length,
+ });
+ }
+ break;
+ }
+
+ case "control_request": {
+ const requestId = event.request_id as string | undefined;
+ if (requestId) {
+ events.push({ kind: "permission_request", requestId, payload: event.payload });
+ }
+ break;
+ }
+
+ default: {
+ events.push({ kind: "log", content: line, level: "debug" });
+ }
+ }
+
+ return events;
+ }
+
+ encodeStdinMessage(text: string, mode: StdinMode, opts?: EncodeOpts): string | null {
+ const msg: Record<string, unknown> = {
+ type: "user",
+ message: {
+ role: "user",
+ content: [{ type: "text", text }],
+ },
+ };
+ if (opts?.sessionId) {
+ msg.session_id = opts.sessionId;
+ }
+ return JSON.stringify(msg);
+ }
+
execute(prompt: string, options: ExecOptions): AgentSession {
- const args = [
- "-p",
- prompt,
+ // When steering is enabled, use --input-format stream-json and deliver
+ // the initial prompt via stdin JSON write instead of -p. This allows
+ // mid-turn message injection on the same stdin pipe. Without steering,
+ // use the normal -p flag (--input-format stream-json + -p causes a hang).
+ const useStdinPrompt = options.steeringEnabled === true;
+
+ const args: string[] = [];
+ if (!useStdinPrompt) {
+ args.push("-p", prompt);
+ }
+ args.push(
"--output-format",
"stream-json",
"--verbose",
"--permission-mode",
"bypassPermissions",
- ];
+ );
+ if (useStdinPrompt) {
+ args.push("--input-format", "stream-json");
+ }
if (options.model) {
args.push("--model", options.model);
@@ -82,6 +228,44 @@ export class ClaudeBackend implements AgentBackend {
}
};
+ // ParsedEvent queue — parallel stream for steering layer observation
+ const parsedEventQueue: ParsedEvent[] = [];
+ let parsedEventResolve: (() => void) | null = null;
+ let parsedEventDone = false;
+
+ const pushParsedEvent = (evt: ParsedEvent) => {
+ parsedEventQueue.push(evt);
+ if (parsedEventResolve) {
+ const r = parsedEventResolve;
+ parsedEventResolve = null;
+ r();
+ }
+ };
+
+ // Serialized stdin write queue — prevents interleaved writes
+ // from concurrent control_response and steering messages.
+ const stdinWriteQueue: string[] = [];
+ let stdinDraining = false;
+
+ const enqueueStdinWrite = (data: string) => {
+ stdinWriteQueue.push(data);
+ drainStdinQueue();
+ };
+
+ const drainStdinQueue = () => {
+ if (stdinDraining) return;
+ stdinDraining = true;
+ while (stdinWriteQueue.length > 0) {
+ const line = stdinWriteQueue.shift()!;
+ try {
+ proc.stdin?.write(line + "\n");
+ } catch {
+ // stdin closed
+ }
+ }
+ stdinDraining = false;
+ };
+
const resultPromise = new Promise<AgentResult>((resolve) => {
const stderrChunks: string[] = [];
@@ -91,9 +275,25 @@ export class ClaudeBackend implements AgentBackend {
const rl = createInterface({ input: proc.stdout! });
+ // When steering mode, deliver the initial prompt via stdin JSON
+ if (useStdinPrompt) {
+ const initialMsg = JSON.stringify({
+ type: "user",
+ message: {
+ role: "user",
+ content: [{ type: "text", text: prompt }],
+ },
+ });
+ enqueueStdinWrite(initialMsg);
+ }
+
rl.on("line", (line: string) => {
if (!line.trim()) return;
+ // Emit ParsedEvents for steering layer
+ const parsed = this.parseLine(line);
+ for (const pe of parsed) pushParsedEvent(pe);
+
let event: Record<string, unknown>;
try {
event = JSON.parse(line);
@@ -169,7 +369,7 @@ export class ClaudeBackend implements AgentBackend {
}
case "control_request": {
- handleControlRequest(proc, event);
+ handleControlRequest(proc, event, enqueueStdinWrite);
break;
}
@@ -188,11 +388,17 @@ export class ClaudeBackend implements AgentBackend {
lastError = `spawn error: ${err.message}`;
resolveSessionId(lastSessionId);
messageDone = true;
+ parsedEventDone = true;
if (messageResolve) {
const r = messageResolve;
messageResolve = null;
r();
}
+ if (parsedEventResolve) {
+ const r = parsedEventResolve;
+ parsedEventResolve = null;
+ r();
+ }
resolve({
status: "failed",
output: "",
@@ -220,11 +426,17 @@ export class ClaudeBackend implements AgentBackend {
resolveSessionId(lastSessionId);
messageDone = true;
+ parsedEventDone = true;
if (messageResolve) {
const r = messageResolve;
messageResolve = null;
r();
}
+ if (parsedEventResolve) {
+ const r = parsedEventResolve;
+ parsedEventResolve = null;
+ r();
+ }
resolve({
status: resultStatus,
@@ -254,18 +466,50 @@ export class ClaudeBackend implements AgentBackend {
},
};
- return { pid: proc.pid, messages, sessionId: sessionIdPromise, result: resultPromise };
+ const parsedEvents: AsyncIterable<ParsedEvent> = {
+ [Symbol.asyncIterator]() {
+ return {
+ async next(): Promise<IteratorResult<ParsedEvent>> {
+ while (parsedEventQueue.length === 0 && !parsedEventDone) {
+ await new Promise<void>((resolve) => {
+ parsedEventResolve = resolve;
+ });
+ }
+ if (parsedEventQueue.length > 0) {
+ return { value: parsedEventQueue.shift()!, done: false };
+ }
+ return { value: undefined as unknown as ParsedEvent, done: true };
+ },
+ };
+ },
+ };
+
+ const send = (text: string, mode: StdinMode): { ok: boolean; reason?: string } => {
+ const encoded = this.encodeStdinMessage(text, mode, { sessionId: lastSessionId || undefined });
+ if (!encoded) return { ok: false, reason: "encoding failed" };
+ if (!proc.stdin || proc.stdin.destroyed) return { ok: false, reason: "stdin closed" };
+ enqueueStdinWrite(encoded);
+ return { ok: true };
+ };
+
+ const descriptor = {
+ lifecycle: this.lifecycle,
+ busyDeliveryMode: this.busyDeliveryMode,
+ supportsStdinNotification: this.supportsStdinNotification,
+ };
+
+ return { pid: proc.pid, messages, parsedEvents, sessionId: sessionIdPromise, result: resultPromise, send, descriptor };
}
}
function handleControlRequest(
proc: ChildProcess,
event: Record<string, unknown>,
+ enqueueStdinWrite?: (data: string) => void,
): void {
const requestId = event.request_id as string | undefined;
if (!requestId) return;
- // Parse input from the control request payload
let updatedInput: unknown = undefined;
const payload = event.payload as Record<string, unknown> | undefined;
if (payload) {
@@ -293,9 +537,13 @@ function handleControlRequest(
},
});
- try {
- proc.stdin?.write(approval + "\n");
- } catch {
- // stdin may be closed
+ if (enqueueStdinWrite) {
+ enqueueStdinWrite(approval);
+ } else {
+ try {
+ proc.stdin?.write(approval + "\n");
+ } catch {
+ // stdin may be closed
+ }
}
}
diff --git a/src/cli/daemon/agent/codex.ts b/src/cli/daemon/agent/codex.ts
index bc4334712..047cca71a 100644
--- a/src/cli/daemon/agent/codex.ts
+++ b/src/cli/daemon/agent/codex.ts
@@ -1,7 +1,16 @@
import { spawn } from "child_process";
import { createInterface } from "readline";
import type { AgentBackend, AgentSession } from "./index.js";
-import type { ExecOptions, AgentMessage, AgentResult } from "../types.js";
+import type {
+ ExecOptions,
+ AgentMessage,
+ AgentResult,
+ ParsedEvent,
+ StdinMode,
+ DriverLifecycle,
+ BusyDeliveryMode,
+ EncodeOpts,
+} from "../types.js";
import { killProcessTree } from "../kill-tree.js";
interface JsonRpcMessage {
@@ -43,9 +52,211 @@ export function extractThreadID(response: unknown): string {
export class CodexBackend implements AgentBackend {
name = "codex";
+ lifecycle: DriverLifecycle = { kind: "persistent", stdin: "direct", inFlightWake: "steer" };
+ busyDeliveryMode: BusyDeliveryMode = "direct";
+ supportsStdinNotification = true;
+
+ private _rpcId = 0;
constructor(private cliPath: string) {}
+ parseLine(line: string): ParsedEvent[] {
+ if (!line.trim()) return [];
+ let msg: JsonRpcMessage;
+ try {
+ msg = JSON.parse(line);
+ } catch {
+ return [{ kind: "log", content: line, level: "debug" }];
+ }
+
+ // Response (has id, no method) — not a parseable event
+ if (msg.id !== undefined && !msg.method) return [];
+
+ // Server request (has both id AND method) — not a parseable event
+ if (msg.id !== undefined && msg.method) return [];
+
+ // Notification (has method, no id)
+ if (!msg.method) return [{ kind: "log", content: line, level: "debug" }];
+
+ const method = msg.method;
+ const params = msg.params || {};
+
+ // Legacy protocol
+ if (method === "codex/event") {
+ return this.parseLegacyEvent(params);
+ }
+
+ // Raw protocol
+ const events: ParsedEvent[] = [];
+ switch (method) {
+ case "turn/started":
+ break;
+
+ case "turn/completed": {
+ const turn = params.turn as Record<string, unknown> | undefined;
+ const status = (turn?.status as string) || (params.status as string) || "";
+ if (status === "error" || status === "failed") {
+ const turnErr = turn?.error as Record<string, unknown> | undefined;
+ events.push({ kind: "error", message: (turnErr?.message as string) || "codex turn failed" });
+ }
+ events.push({ kind: "turn_end" });
+ break;
+ }
+
+ case "error": {
+ const errObj = params.error as Record<string, unknown> | undefined;
+ const errMsg = (errObj?.message as string) || (params.message as string) || "";
+ const willRetry = params.willRetry === true;
+ if (errMsg && !willRetry) {
+ events.push({ kind: "error", message: errMsg });
+ }
+ break;
+ }
+
+ case "thread/status/changed": {
+ const statusObj = params.status as Record<string, unknown> | string | undefined;
+ const statusType = typeof statusObj === "object" && statusObj !== null
+ ? (statusObj.type as string) || ""
+ : (statusObj as string) || "";
+ if (statusType === "idle") {
+ events.push({ kind: "turn_end" });
+ }
+ break;
+ }
+
+ case "item/started": {
+ const item = params.item as Record<string, unknown> | undefined;
+ if (!item) break;
+ const itemType = item.type as string | undefined;
+ if (itemType === "commandExecution" || itemType === "fileChange") {
+ events.push({
+ kind: "tool_call",
+ name: itemType === "commandExecution" ? "exec_command" : "patch_apply",
+ callId: item.id as string,
+ input: item as Record<string, unknown>,
+ });
+ } else if (itemType === "mcpToolCall") {
+ events.push({
+ kind: "tool_call",
+ name: `mcp_${(item.name as string) || "tool"}`,
+ callId: item.id as string,
+ input: item as Record<string, unknown>,
+ });
+ } else if (itemType === "webSearch") {
+ events.push({
+ kind: "tool_call",
+ name: "web_search",
+ callId: item.id as string,
+ input: item as Record<string, unknown>,
+ });
+ } else if (itemType === "collabAgentToolCall") {
+ events.push({
+ kind: "tool_call",
+ name: "collab_agent",
+ callId: item.id as string,
+ input: item as Record<string, unknown>,
+ });
+ } else if (itemType === "contextCompaction") {
+ events.push({ kind: "compaction_started" });
+ }
+ break;
+ }
+
+ case "item/completed": {
+ const item = params.item as Record<string, unknown> | undefined;
+ if (!item) break;
+ const itemType = item.type as string | undefined;
+ if (itemType === "commandExecution") {
+ events.push({ kind: "tool_output", callId: item.id as string, output: (item.aggregatedOutput as string) || "" });
+ } else if (itemType === "fileChange") {
+ events.push({ kind: "tool_output", callId: item.id as string, output: "" });
+ } else if (itemType === "mcpToolCall") {
+ events.push({ kind: "tool_output", callId: item.id as string, name: `mcp_${(item.name as string) || "tool"}`, output: (item.output as string) || "" });
+ } else if (itemType === "agentMessage") {
+ const flatText = item.text as string | undefined;
+ if (flatText) {
+ events.push({ kind: "text", text: flatText });
+ } else {
+ const content = item.content as { type: string; text?: string }[] | undefined;
+ if (Array.isArray(content)) {
+ for (const block of content) {
+ if ((block.type === "output_text" || block.type === "text") && block.text) {
+ events.push({ kind: "text", text: block.text });
+ }
+ }
+ }
+ }
+ } else if (itemType === "reasoning") {
+ events.push({ kind: "thinking", text: (item.text as string) || "" });
+ } else if (itemType === "contextCompaction") {
+ events.push({ kind: "compaction_finished" });
+ }
+ break;
+ }
+
+ case "item/agentMessage/delta": {
+ const delta = params.delta as string | undefined;
+ if (delta) events.push({ kind: "text", text: delta });
+ break;
+ }
+
+ default:
+ events.push({ kind: "log", content: JSON.stringify(msg), level: "debug" });
+ }
+ return events;
+ }
+
+ private parseLegacyEvent(params: Record<string, unknown>): ParsedEvent[] {
+ const eventType = params.type as string | undefined;
+ if (!eventType) return [];
+
+ const events: ParsedEvent[] = [];
+ switch (eventType) {
+ case "agent_message": {
+ const text = (params.text as string) || (params.message as string) || "";
+ if (text) events.push({ kind: "text", text });
+ break;
+ }
+ case "exec_command_begin":
+ events.push({ kind: "tool_call", name: "exec_command", callId: params.id as string, input: params as Record<string, unknown> });
+ break;
+ case "exec_command_end":
+ events.push({ kind: "tool_output", callId: params.id as string, output: (params.output as string) || "" });
+ break;
+ case "patch_apply_begin":
+ events.push({ kind: "tool_call", name: "patch_apply", callId: params.id as string, input: params as Record<string, unknown> });
+ break;
+ case "patch_apply_end":
+ events.push({ kind: "tool_output", callId: params.id as string, output: (params.output as string) || "" });
+ break;
+ case "task_complete":
+ events.push({ kind: "turn_end" });
+ break;
+ case "turn_aborted":
+ events.push({ kind: "turn_end" });
+ break;
+ default:
+ break;
+ }
+ return events;
+ }
+
+ encodeStdinMessage(text: string, mode: StdinMode, opts?: EncodeOpts): string | null {
+ const threadId = opts?.threadId;
+ if (!threadId) return null;
+ const id = opts?.requestId ?? ++this._rpcId;
+ const method = mode === "busy" ? "turn/steer" : "turn/start";
+ return JSON.stringify({
+ jsonrpc: "2.0",
+ id,
+ method,
+ params: {
+ threadId,
+ input: [{ type: "text", text }],
+ },
+ });
+ }
+
execute(prompt: string, options: ExecOptions): AgentSession {
const proc = spawn(this.cliPath, ["app-server", "--listen", "stdio://", "--config", "sandbox_mode=danger-full-access"], {
cwd: options.cwd,
@@ -107,6 +318,10 @@ export class CodexBackend implements AgentBackend {
let messageResolve: (() => void) | null = null;
let messageDone = false;
+ const parsedEventQueue: ParsedEvent[] = [];
+ let parsedEventResolve: (() => void) | null = null;
+ let parsedEventDone = false;
+
const pushMessage = (msg: AgentMessage) => {
messageQueue.push(msg);
if (messageResolve) {
@@ -116,6 +331,15 @@ export class CodexBackend implements AgentBackend {
}
};
+ const pushParsedEvent = (evt: ParsedEvent) => {
+ parsedEventQueue.push(evt);
+ if (parsedEventResolve) {
+ const r = parsedEventResolve;
+ parsedEventResolve = null;
+ r();
+ }
+ };
+
const writeStdin = (data: string) => {
try {
proc.stdin?.write(data + "\n");
@@ -158,12 +382,16 @@ export class CodexBackend implements AgentBackend {
if (msg && !turnError) turnError = msg;
};
+ const steeringKeepAlive = options.steeringEnabled === true;
+
const triggerTurnDone = (aborted: boolean) => {
if (turnDoneTriggered) return;
turnDoneTriggered = true;
resultStatus = aborted ? "aborted" : "completed";
- try { proc.stdin?.end(); } catch { /* already closed */ }
- try { proc.kill("SIGTERM"); } catch { /* already dead */ }
+ if (!steeringKeepAlive) {
+ try { proc.stdin?.end(); } catch { /* already closed */ }
+ try { proc.kill("SIGTERM"); } catch { /* already dead */ }
+ }
};
const handleServerRequest = (msg: JsonRpcMessage) => {
@@ -414,6 +642,10 @@ export class CodexBackend implements AgentBackend {
rl.on("line", (line: string) => {
if (!line.trim()) return;
+ // Emit ParsedEvents for steering layer
+ const parsed = this.parseLine(line);
+ for (const pe of parsed) pushParsedEvent(pe);
+
let msg: JsonRpcMessage;
try {
msg = JSON.parse(line);
@@ -523,11 +755,17 @@ export class CodexBackend implements AgentBackend {
closeAllPending("spawn error");
resolveSessionId(sessionId);
messageDone = true;
+ parsedEventDone = true;
if (messageResolve) {
const r = messageResolve;
messageResolve = null;
r();
}
+ if (parsedEventResolve) {
+ const r = parsedEventResolve;
+ parsedEventResolve = null;
+ r();
+ }
resolve({
status: "failed",
output: "",
@@ -566,11 +804,17 @@ export class CodexBackend implements AgentBackend {
resolveSessionId(sessionId);
messageDone = true;
+ parsedEventDone = true;
if (messageResolve) {
const r = messageResolve;
messageResolve = null;
r();
}
+ if (parsedEventResolve) {
+ const r = parsedEventResolve;
+ parsedEventResolve = null;
+ r();
+ }
resolve({
status: resultStatus,
@@ -600,6 +844,38 @@ export class CodexBackend implements AgentBackend {
},
};
- return { pid: proc.pid, messages, sessionId: sessionIdPromise, result: resultPromise };
+ const parsedEvents: AsyncIterable<ParsedEvent> = {
+ [Symbol.asyncIterator]() {
+ return {
+ async next(): Promise<IteratorResult<ParsedEvent>> {
+ while (parsedEventQueue.length === 0 && !parsedEventDone) {
+ await new Promise<void>((resolve) => {
+ parsedEventResolve = resolve;
+ });
+ }
+ if (parsedEventQueue.length > 0) {
+ return { value: parsedEventQueue.shift()!, done: false };
+ }
+ return { value: undefined as unknown as ParsedEvent, done: true };
+ },
+ };
+ },
+ };
+
+ const send = (text: string, mode: StdinMode): { ok: boolean; reason?: string } => {
+ if (!proc.stdin || proc.stdin.destroyed) return { ok: false, reason: "stdin closed" };
+ const encoded = this.encodeStdinMessage(text, mode, { threadId: sessionId, requestId: ++requestId });
+ if (!encoded) return { ok: false, reason: "encoding failed (no threadId)" };
+ writeStdin(encoded);
+ return { ok: true };
+ };
+
+ const descriptor = {
+ lifecycle: this.lifecycle,
+ busyDeliveryMode: this.busyDeliveryMode,
+ supportsStdinNotification: this.supportsStdinNotification,
+ };
+
+ return { pid: proc.pid, messages, parsedEvents, sessionId: sessionIdPromise, result: resultPromise, send, descriptor };
}
}
diff --git a/src/cli/daemon/agent/index.ts b/src/cli/daemon/agent/index.ts
index 6f02ea0ff..2a936d76b 100644
--- a/src/cli/daemon/agent/index.ts
+++ b/src/cli/daemon/agent/index.ts
@@ -1,4 +1,14 @@
-import type { ExecOptions, AgentMessage, AgentResult } from "../types.js";
+import type {
+ ExecOptions,
+ AgentMessage,
+ AgentResult,
+ ParsedEvent,
+ StdinMode,
+ RuntimeSessionDescriptor,
+ DriverLifecycle,
+ BusyDeliveryMode,
+ EncodeOpts,
+} from "../types.js";
import { ClaudeBackend } from "./claude.js";
import { CodexBackend } from "./codex.js";
import { OpenCodeBackend } from "./opencode.js";
@@ -7,13 +17,29 @@ import { execSync } from "child_process";
export interface AgentSession {
pid: number | undefined;
messages: AsyncIterable<AgentMessage>;
+ parsedEvents?: AsyncIterable<ParsedEvent>;
sessionId: Promise<string>;
result: Promise<AgentResult>;
+ send?(text: string, mode: StdinMode): { ok: boolean; reason?: string };
+ descriptor?: RuntimeSessionDescriptor;
}
export interface AgentBackend {
name: string;
execute(prompt: string, options: ExecOptions): AgentSession;
+ lifecycle?: DriverLifecycle;
+ busyDeliveryMode?: BusyDeliveryMode;
+ supportsStdinNotification?: boolean;
+ parseLine?(line: string): ParsedEvent[];
+ encodeStdinMessage?(text: string, mode: StdinMode, opts?: EncodeOpts): string | null;
+}
+
+export function descriptorFromDriver(backend: AgentBackend): RuntimeSessionDescriptor {
+ return {
+ lifecycle: backend.lifecycle ?? { kind: "per_turn" },
+ busyDeliveryMode: backend.busyDeliveryMode ?? "none",
+ supportsStdinNotification: backend.supportsStdinNotification ?? false,
+ };
}
export function createBackend(
diff --git a/src/cli/daemon/agent/opencode.ts b/src/cli/daemon/agent/opencode.ts
index a041a2f7f..4c253c973 100644
--- a/src/cli/daemon/agent/opencode.ts
+++ b/src/cli/daemon/agent/opencode.ts
@@ -1,14 +1,129 @@
import { spawn } from "child_process";
import { createInterface } from "readline";
import type { AgentBackend, AgentSession } from "./index.js";
-import type { ExecOptions, AgentMessage, AgentResult } from "../types.js";
+import type {
+ ExecOptions,
+ AgentMessage,
+ AgentResult,
+ ParsedEvent,
+ DriverLifecycle,
+ BusyDeliveryMode,
+} from "../types.js";
import { killProcessTree } from "../kill-tree.js";
export class OpenCodeBackend implements AgentBackend {
name = "opencode";
+ lifecycle: DriverLifecycle = { kind: "per_turn", inFlightWake: "coalesce_into_pending" };
+ busyDeliveryMode: BusyDeliveryMode = "none";
+ supportsStdinNotification = false;
constructor(private cliPath: string) {}
+ parseLine(line: string): ParsedEvent[] {
+ if (!line.trim()) return [];
+ let event: Record<string, unknown>;
+ try {
+ event = JSON.parse(line);
+ } catch {
+ return [{ kind: "log", content: line, level: "debug" }];
+ }
+
+ const events: ParsedEvent[] = [];
+ const eventType = event.type as string | undefined;
+ const part = event.part as Record<string, unknown> | undefined;
+
+ const eventSessionId = (event.sessionID as string) || (event.session_id as string);
+
+ switch (eventType) {
+ case "session": {
+ const sessionId = event.session_id as string | undefined;
+ if (sessionId) events.push({ kind: "session_init", sessionId });
+ break;
+ }
+
+ case "message": {
+ const role = event.role as string | undefined;
+ const content = event.content as string | undefined;
+ if (role === "assistant" && content) {
+ events.push({ kind: "text", text: content });
+ }
+ break;
+ }
+
+ case "text": {
+ const text = (part?.text as string) || (event.content as string) || "";
+ if (text) events.push({ kind: "text", text });
+ break;
+ }
+
+ case "thinking": {
+ const content = (part?.thinking as string) || (event.content as string) || "";
+ events.push({ kind: "thinking", text: content });
+ break;
+ }
+
+ case "tool_call":
+ events.push({
+ kind: "tool_call",
+ name: (event.name as string) || (part?.name as string) || "",
+ callId: (event.call_id as string) || (part?.id as string) || "",
+ input: (event.input as Record<string, unknown>) || (part?.input as Record<string, unknown>),
+ });
+ break;
+
+ case "tool_result":
+ events.push({
+ kind: "tool_output",
+ callId: (event.call_id as string) || (part?.id as string) || "",
+ output: (event.output as string) || (part?.output as string) || "",
+ });
+ break;
+
+ case "error": {
+ const content = (event.message as string) || (event.content as string) || (part?.error as string) || "";
+ events.push({ kind: "error", message: content });
+ events.push({ kind: "turn_end" });
+ break;
+ }
+
+ case "step_start":
+ break;
+
+ case "step_finish": {
+ const reason = part?.reason as string | undefined;
+ if (reason === "stop" || reason === "end_turn") {
+ events.push({ kind: "turn_end" });
+ }
+ break;
+ }
+
+ case "done":
+ case "complete": {
+ const status = event.status as string | undefined;
+ if (status === "error" || status === "failed") {
+ const output = event.output as string | undefined;
+ events.push({ kind: "error", message: output || "task failed" });
+ }
+ events.push({ kind: "turn_end" });
+ break;
+ }
+
+ default:
+ events.push({ kind: "log", content: line, level: "debug" });
+ }
+
+ // Attach session info if available as first event
+ if (eventSessionId && events.length > 0 && events[0].kind !== "session_init") {
+ events.unshift({ kind: "session_init", sessionId: eventSessionId });
+ }
+
+ return events;
+ }
+
+ encodeStdinMessage(): string | null {
+ return null;
+ }
+
execute(prompt: string, options: ExecOptions): AgentSession {
const args = ["run", "--format", "json", "--dir", options.cwd];
@@ -72,6 +187,10 @@ export class OpenCodeBackend implements AgentBackend {
let messageResolve: (() => void) | null = null;
let messageDone = false;
+ const parsedEventQueue: ParsedEvent[] = [];
+ let parsedEventResolve: (() => void) | null = null;
+ let parsedEventDone = false;
+
const pushMessage = (msg: AgentMessage) => {
messageQueue.push(msg);
if (messageResolve) {
@@ -81,6 +200,15 @@ export class OpenCodeBackend implements AgentBackend {
}
};
+ const pushParsedEvent = (evt: ParsedEvent) => {
+ parsedEventQueue.push(evt);
+ if (parsedEventResolve) {
+ const r = parsedEventResolve;
+ parsedEventResolve = null;
+ r();
+ }
+ };
+
const resultPromise = new Promise<AgentResult>((resolve) => {
const stderrChunks: string[] = [];
@@ -93,6 +221,10 @@ export class OpenCodeBackend implements AgentBackend {
rl.on("line", (line: string) => {
if (!line.trim()) return;
+ // Emit ParsedEvents for steering layer
+ const parsed = this.parseLine(line);
+ for (const pe of parsed) pushParsedEvent(pe);
+
let event: Record<string, unknown>;
try {
event = JSON.parse(line);
@@ -224,11 +356,17 @@ export class OpenCodeBackend implements AgentBackend {
lastError = `spawn error: ${err.message}`;
resolveSessionId(lastSessionId);
messageDone = true;
+ parsedEventDone = true;
if (messageResolve) {
const r = messageResolve;
messageResolve = null;
r();
}
+ if (parsedEventResolve) {
+ const r = parsedEventResolve;
+ parsedEventResolve = null;
+ r();
+ }
resolve({
status: "failed",
output: "",
@@ -258,11 +396,17 @@ export class OpenCodeBackend implements AgentBackend {
resolveSessionId(lastSessionId);
messageDone = true;
+ parsedEventDone = true;
if (messageResolve) {
const r = messageResolve;
messageResolve = null;
r();
}
+ if (parsedEventResolve) {
+ const r = parsedEventResolve;
+ parsedEventResolve = null;
+ r();
+ }
resolve({
status: resultStatus,
@@ -292,6 +436,34 @@ export class OpenCodeBackend implements AgentBackend {
},
};
- return { pid: proc.pid, messages, sessionId: sessionIdPromise, result: resultPromise };
+ const parsedEvents: AsyncIterable<ParsedEvent> = {
+ [Symbol.asyncIterator]() {
+ return {
+ async next(): Promise<IteratorResult<ParsedEvent>> {
+ while (parsedEventQueue.length === 0 && !parsedEventDone) {
+ await new Promise<void>((resolve) => {
+ parsedEventResolve = resolve;
+ });
+ }
+ if (parsedEventQueue.length > 0) {
+ return { value: parsedEventQueue.shift()!, done: false };
+ }
+ return { value: undefined as unknown as ParsedEvent, done: true };
+ },
+ };
+ },
+ };
+
+ const send = (): { ok: boolean; reason?: string } => {
+ return { ok: false, reason: "unsupported" };
+ };
+
+ const descriptor = {
+ lifecycle: this.lifecycle,
+ busyDeliveryMode: this.busyDeliveryMode,
+ supportsStdinNotification: this.supportsStdinNotification,
+ };
+
+ return { pid: proc.pid, messages, parsedEvents, sessionId: sessionIdPromise, result: resultPromise, send, descriptor };
}
}
diff --git a/src/cli/daemon/config.ts b/src/cli/daemon/config.ts
index 01470527b..31fbcb547 100644
--- a/src/cli/daemon/config.ts
+++ b/src/cli/daemon/config.ts
@@ -76,6 +76,7 @@ export interface DaemonConfig {
agentTimeout: number;
messageInactivityTimeout: number;
maxConcurrentTasks: number;
+ enableSteering: boolean;
daemonId: string;
deviceName: string;
workspacesRoot: string;
@@ -114,6 +115,7 @@ export function loadDaemonConfig(profile?: string): DaemonConfig {
maxConcurrentTasks: parseInt(
process.env.ALOOK_DAEMON_MAX_CONCURRENT_TASKS || "20",
),
+ enableSteering: process.env.ALOOK_ENABLE_STEERING !== "0",
daemonId,
deviceName: process.env.ALOOK_DAEMON_DEVICE_NAME || h,
workspacesRoot,
diff --git a/src/cli/daemon/daemon.test.ts b/src/cli/daemon/daemon.test.ts
index 89e7c43b0..fd6765c21 100644
--- a/src/cli/daemon/daemon.test.ts
+++ b/src/cli/daemon/daemon.test.ts
@@ -70,6 +70,7 @@ vi.mock("./ws-client.js", () => {
vi.mock("./agent/index.js", () => ({
detectVersion: vi.fn(async () => "1.0.0"),
+ createBackend: vi.fn(() => ({ lifecycle: { kind: "per_turn" }, busyDeliveryMode: "none", supportsStdinNotification: false })),
}));
vi.mock("../lib/config.js", () => ({
@@ -133,6 +134,13 @@ vi.mock("./execenv/steering.js", () => ({
cleanupStaleIntents: (...args: any[]) => mockCleanupStaleIntents(...(args as any[])),
}));
+vi.mock("./steering/mailbox.js", () => ({
+ ensureMailboxDirs: vi.fn(),
+ writeSteerMessage: vi.fn(() => "000001"),
+ waitForAck: vi.fn(async () => ({ acked: false, nackReason: "mock" })),
+ inboxDir: vi.fn(() => "/tmp/mock-inbox"),
+}));
+
// Track spawned children
interface MockChild extends EventEmitter {
pid: number;
diff --git a/src/cli/daemon/daemon.ts b/src/cli/daemon/daemon.ts
index a88a63547..5eb302695 100644
--- a/src/cli/daemon/daemon.ts
+++ b/src/cli/daemon/daemon.ts
@@ -1,7 +1,7 @@
import { DaemonClient } from "./client.js";
import { type DaemonConfig, loadDaemonConfig, sessionRunnerLogDir, daemonLogFilePath } from "./config.js";
import { createHealthServer } from "./health.js";
-import { detectVersion } from "./agent/index.js";
+import { detectVersion, createBackend } from "./agent/index.js";
import { type Task, type Attachment, type SessionRunnerInput, fromApiTask } from "./types.js";
import { type MarkerData, writeMarkerFile, downloadAttachments } from "./session-runner.js";
import { buildPrompt, buildMergedPrompt } from "./prompt.js";
@@ -24,6 +24,12 @@ import {
releaseSteeringLock,
cleanupStaleIntents,
} from "./execenv/steering.js";
+import {
+ ensureMailboxDirs,
+ writeSteerMessage,
+ waitForAck,
+ inboxDir as steeringInboxDir,
+} from "./steering/mailbox.js";
import { TASK_TYPES } from "@alook/shared";
import { readDirectoryTree, readFileContent, validatePath } from "./workspace-files.js";
import { startSkillScanner, stopSkillScanner } from "./skill-scanner.js";
@@ -1118,6 +1124,49 @@ async function handleTask(
// Supersede predecessor if found.
if (predecessor && predecessor.task_id !== task.id) {
+ // Steering-first: try mailbox injection for persistent backends
+ const backendInst = createBackend(provider, "");
+ const isPersistent = backendInst.lifecycle?.kind === "persistent";
+
+ if (config.enableSteering && isPersistent && predecessor.pid != null) {
+ log.info(`Steering: task ${task.id} steering into predecessor ${predecessor.task_id} via mailbox (context_key=${ctxKey})`);
+ try {
+ ensureMailboxDirs(agentBaseDir, ctxKey);
+
+ // Download attachments for the steered task
+ const attachmentIds = (task.context?.attachment_ids as string[]) ?? [];
+ let steerAttachments: { localPath: string; filename: string; contentType: string }[] = [];
+ if (attachmentIds.length > 0) {
+ try {
+ const downloaded = await downloadAttachments(client, token, task.workspaceId, task.id, attachmentIds);
+ steerAttachments = downloaded.map((a) => ({ localPath: a.path, filename: a.filename, contentType: a.content_type }));
+ } catch (e) {
+ log.warn(`Steering mailbox: failed to download attachments for ${task.id}`, e);
+ }
+ }
+
+ const seq = writeSteerMessage(agentBaseDir, ctxKey, {
+ taskId: task.id,
+ text: buildPrompt(task),
+ attachments: steerAttachments,
+ createdAt: new Date().toISOString(),
+ });
+
+ const ackResult = await waitForAck(agentBaseDir, ctxKey, seq);
+ if (ackResult.acked) {
+ log.info(`Steering: task ${task.id} steered into predecessor ${predecessor.task_id} (acked)`);
+ try { await client.startTask(token, task.id); } catch { /* best effort — already started above */ }
+ pendingSteer.delete(ctxKey);
+ activeTasks.delete(task.id);
+ return;
+ }
+ log.info(`Steering: mailbox delivery failed for ${task.id} (${ackResult.nackReason}), falling back to kill-and-respawn`);
+ } catch (e) {
+ log.warn(`Steering: mailbox error for ${task.id}, falling back to kill-and-respawn`, e);
+ }
+ }
+
+ // Fallback: kill-and-respawn (existing behavior)
log.info(`Steering: task ${task.id} supersedes predecessor ${predecessor.task_id} (context_key=${ctxKey})`);
if (predecessor.pid != null) {
writeKillIntent(agentBaseDir, { reason: "superseded", targetTaskId: predecessor.task_id, expectedPid: predecessor.pid, successorTaskId: task.id });
@@ -1196,6 +1245,16 @@ async function handleTask(
const agentModel = task.agent?.runtimeConfig?.model;
const model = (typeof agentModel === "string" && agentModel) ? agentModel : configModel;
+ // Determine if this session-runner should watch the steering mailbox
+ const backendForInput = createBackend(provider, "");
+ const steeringEligible = config.enableSteering && backendForInput.lifecycle?.kind === "persistent" && !!task.contextKey;
+ let steeringMailboxDir: string | undefined;
+ if (steeringEligible) {
+ const agentBaseDirForSteering = join(config.workspacesRoot, task.workspaceId, task.agentId, "workdir");
+ ensureMailboxDirs(agentBaseDirForSteering, task.contextKey!);
+ steeringMailboxDir = steeringInboxDir(agentBaseDirForSteering, task.contextKey!);
+ }
+
const input: SessionRunnerInput = {
task,
provider,
@@ -1207,6 +1266,8 @@ async function handleTask(
agentTimeout: config.agentTimeout,
messageInactivityTimeout: config.messageInactivityTimeout,
...(promptOverride && { promptOverride }),
+ ...(steeringEligible && { steeringEnabled: true }),
+ ...(steeringMailboxDir && { steeringMailboxDir }),
};
const child = spawnSessionRunner(input);
diff --git a/src/cli/daemon/session-runner.ts b/src/cli/daemon/session-runner.ts
index cf524bb25..51f6b6215 100644
--- a/src/cli/daemon/session-runner.ts
+++ b/src/cli/daemon/session-runner.ts
@@ -19,6 +19,23 @@ import {
findResumableSessionByContextKey,
} from "./execenv/timeline.js";
import { readKillIntent, clearKillIntent } from "./execenv/steering.js";
+import { watchInbox, writeAck, writeNack, cleanupInboxFile, cleanupSteeringDir, type MailboxWatcher } from "./steering/mailbox.js";
+import { RuntimeTurnState } from "./steering/turnState.js";
+import {
+ createInitialApmState,
+ reduceApmGatedToolUse,
+ reduceApmGatedCompaction,
+ reduceApmGatedEnqueue,
+ reduceApmGatedTurnEnd,
+ reduceApmGatedError,
+ reduceApmGatedFlushReadiness,
+ reduceApmGatedRecentEvent,
+ reduceApmStalledRecoveryTermination,
+ reduceApmStartupTimeoutTermination,
+} from "./steering/apmStateMachine.js";
+import { RuntimeNotificationState } from "./steering/notificationState.js";
+import { RuntimeProgressState } from "./steering/progressState.js";
+import { classifyRuntimeError, scrubDiagnosticText } from "./steering/errorDiagnostics.js";
import { killProcessTree } from "./kill-tree.js";
import { buildPrompt } from "./prompt.js";
import { createLogger } from "../lib/logger.js";
@@ -214,6 +231,9 @@ export async function runSession(input: SessionRunnerInput): Promise<void> {
}
};
+ let mailboxWatcher: MailboxWatcher | null = null;
+ let stalledRecoveryTimer: ReturnType<typeof setInterval> | undefined;
+
// --- Single SIGTERM/SIGINT handler, registered ONCE for the whole lifetime.
// Every field it touches is guarded for the "not yet initialized" window
// (kill arriving before the agent is spawned / batching has started). ---
@@ -222,6 +242,10 @@ export async function runSession(input: SessionRunnerInput): Promise<void> {
killed = true;
log.info(`killed by signal (messages=${seq}, tools=${toolCount})`);
+ // 0. Stop mailbox watcher and stalled recovery timer (if running)
+ if (mailboxWatcher) mailboxWatcher.stop();
+ if (stalledRecoveryTimer) clearInterval(stalledRecoveryTimer);
+
// 1. Kill the inner agent process group (CLI + tool/MCP subprocesses),
// escalating to SIGKILL if it ignores SIGTERM. No-op if not yet spawned.
if (agentPid !== undefined) {
@@ -331,6 +355,7 @@ export async function runSession(input: SessionRunnerInput): Promise<void> {
env,
timeout: agentTimeout,
resumeSessionId,
+ steeringEnabled: input.steeringEnabled,
});
// Capture agent PID so the handler can reap it. backend.execute() spawns
@@ -364,6 +389,246 @@ export async function runSession(input: SessionRunnerInput): Promise<void> {
flushTimer = setInterval(flushMessages, FLUSH_INTERVAL_MS);
+ // --- Steering: mailbox watcher + state machines ---
+ const turnState = new RuntimeTurnState();
+ let apmState = createInitialApmState();
+ const notificationState = new RuntimeNotificationState();
+ const progressState = new RuntimeProgressState();
+ const pendingSteeredTasks = new Set<string>();
+ let hasReceivedProgressEvent = false;
+
+ if (input.steeringEnabled && input.steeringMailboxDir && task.contextKey) {
+ const descriptor = session.descriptor;
+ const STALLED_THRESHOLD_MS = 120_000; // 2 minutes
+ const STALLED_CHECK_INTERVAL_MS = 30_000; // 30 seconds
+
+ // Start a background ParsedEvent consumer for steering state machine updates
+ if (session.parsedEvents) {
+ const parsedIter = session.parsedEvents[Symbol.asyncIterator]();
+ const consumeParsedEvents = async () => {
+ try {
+ while (!killed) {
+ const { value: event, done } = await parsedIter.next();
+ if (done) break;
+
+ hasReceivedProgressEvent = true;
+
+ // Track progress for granular liveness detection
+ progressState.processEvent(event);
+
+ // Record recent event for diagnostics
+ const recentResult = reduceApmGatedRecentEvent(apmState, { event: event.kind });
+ apmState = recentResult.nextState;
+
+ // Classify errors for structured diagnostics + update APM state
+ if (event.kind === "error") {
+ const classified = classifyRuntimeError(event.message);
+ log.info(`steering: error classified as ${classified.errorClass}: ${scrubDiagnosticText(event.message)}`);
+ const errResult = reduceApmGatedError(apmState, { disableToolBoundaryFlush: true });
+ apmState = errResult.nextState;
+ }
+
+ // turnState gate transitions — BEFORE reducer calls
+ switch (event.kind) {
+ case "tool_call":
+ case "thinking":
+ case "compaction_started":
+ turnState.markToolBoundary();
+ break;
+ case "text":
+ case "tool_output":
+ case "compaction_finished":
+ turnState.markProgress();
+ break;
+ }
+
+ switch (event.kind) {
+ case "session_init":
+ turnState.markTurnStarted(event.sessionId);
+ break;
+ case "text":
+ if (!turnState.isInTurn) turnState.markTurnStarted();
+ break;
+ case "tool_call": {
+ if (!turnState.isInTurn) turnState.markTurnStarted();
+ const result = reduceApmGatedToolUse(apmState, { kind: "tool_call" });
+ apmState = result.nextState;
+ break;
+ }
+ case "tool_output": {
+ const result = reduceApmGatedToolUse(apmState, { kind: "tool_output" });
+ apmState = result.nextState;
+ if (result.shouldFlushToolBatch && session.send && apmState.pendingMessages.length > 0) {
+ const readiness = reduceApmGatedFlushReadiness(apmState, {
+ isGated: descriptor?.busyDeliveryMode === "gated",
+ hasSession: !!earlySessionId,
+ inboxLength: apmState.pendingMessages.length,
+ reason: "tool_batch_complete",
+ });
+ if (readiness.shouldNotify) {
+ for (const msg of apmState.pendingMessages) {
+ session.send(msg, "busy");
+ }
+ apmState = { ...apmState, pendingMessages: [] };
+ }
+ }
+ break;
+ }
+ case "compaction_started":
+ case "compaction_finished": {
+ const result = reduceApmGatedCompaction(apmState, { kind: event.kind });
+ apmState = result.nextState;
+ if (event.kind === "compaction_finished" && session.send && apmState.pendingMessages.length > 0) {
+ const readiness = reduceApmGatedFlushReadiness(apmState, {
+ isGated: descriptor?.busyDeliveryMode === "gated",
+ hasSession: !!earlySessionId,
+ inboxLength: apmState.pendingMessages.length,
+ reason: "compaction_finished",
+ });
+ if (readiness.shouldNotify) {
+ for (const msg of apmState.pendingMessages) {
+ session.send(msg, "busy");
+ }
+ apmState = { ...apmState, pendingMessages: [] };
+ }
+ }
+ break;
+ }
+ case "turn_end": {
+ const result = reduceApmGatedTurnEnd(apmState, {
+ inboxLength: apmState.pendingMessages.length,
+ supportsStdinNotification: descriptor?.supportsStdinNotification,
+ hasSession: !!earlySessionId,
+ });
+ apmState = result.nextState;
+ for (const eff of result.effects) {
+ if (eff.kind === "deliver_stdin" && session.send) {
+ for (const msg of apmState.pendingMessages) {
+ session.send(msg, eff.stdinMode);
+ }
+ apmState = { ...apmState, pendingMessages: [] };
+ }
+ }
+ // Complete any pending steered tasks
+ for (const steeredId of pendingSteeredTasks) {
+ client.completeTask(token, steeredId, { output: "" }).catch((e) => {
+ log.debug(`steering: failed to complete steered task ${steeredId}`, e);
+ });
+ }
+ pendingSteeredTasks.clear();
+ turnState.markTurnCompleted();
+ break;
+ }
+ }
+ }
+ } catch { /* stream ended */ }
+ };
+ consumeParsedEvents();
+ }
+
+ // Stalled recovery + startup timeout timer
+ stalledRecoveryTimer = setInterval(() => {
+ if (killed) return;
+
+ // Startup timeout check on first tick
+ if (!hasReceivedProgressEvent) {
+ const startupResult = reduceApmStartupTimeoutTermination(apmState, {
+ hasRuntimeProgressEvent: hasReceivedProgressEvent,
+ });
+ apmState = startupResult.nextState;
+ if (startupResult.shouldTerminate) {
+ log.warn("steering: startup timeout — no progress events received, killing agent");
+ if (agentPid !== undefined) void killProcessTree(agentPid);
+ return;
+ }
+ }
+
+ // Stalled recovery check
+ const staleForMs = progressState.ageMs();
+ if (staleForMs > STALLED_THRESHOLD_MS && !progressState.isStale) {
+ progressState.markStale();
+ }
+ const stalledResult = reduceApmStalledRecoveryTermination(apmState, {
+ inboxLength: apmState.pendingMessages.length,
+ staleForMs,
+ staleThresholdMs: STALLED_THRESHOLD_MS,
+ runtimeProgressIsStale: progressState.isStale,
+ hasSession: !!earlySessionId,
+ busyDeliveryMode: descriptor?.busyDeliveryMode ?? "none",
+ hasDirectStdinRecoveryEvidence: false,
+ });
+ apmState = stalledResult.nextState;
+ if (stalledResult.shouldTerminate) {
+ log.warn(`steering: stalled recovery — agent stale for ${(staleForMs / 1000).toFixed(1)}s with ${apmState.pendingMessages.length} pending messages, killing`);
+ if (agentPid !== undefined) void killProcessTree(agentPid);
+ }
+ }, STALLED_CHECK_INTERVAL_MS);
+
+ // Start watching the mailbox for steered messages from daemon
+ mailboxWatcher = watchInbox(
+ agentBaseDir,
+ task.contextKey,
+ (seq, message) => {
+ const sessionId = earlySessionId || "";
+ if (notificationState.isDuplicateNotice(String(seq), sessionId)) {
+ writeAck(agentBaseDir, task.contextKey!, seq);
+ cleanupInboxFile(agentBaseDir, task.contextKey!, seq);
+ return;
+ }
+
+ const busyMode = session.descriptor?.busyDeliveryMode;
+ let delivered = false;
+
+ if (busyMode === "direct" && session.send) {
+ const result = session.send(message.text, turnState.isInTurn ? "busy" : "idle");
+ if (result.ok) {
+ notificationState.recordNoticeWritten(String(seq), sessionId, [{ id: String(seq) }]);
+ writeAck(agentBaseDir, task.contextKey!, seq);
+ delivered = true;
+ } else {
+ writeNack(agentBaseDir, task.contextKey!, seq, result.reason || "send failed");
+ }
+ } else if (busyMode === "gated") {
+ const enqueueResult = reduceApmGatedEnqueue(apmState, message.text);
+ apmState = enqueueResult.nextState;
+
+ // Check if we can flush immediately
+ if (turnState.canSteerBusy && session.send && apmState.pendingMessages.length > 0) {
+ const readiness = reduceApmGatedFlushReadiness(apmState, {
+ isGated: true,
+ hasSession: !!earlySessionId,
+ inboxLength: apmState.pendingMessages.length,
+ reason: "enqueue",
+ });
+ if (readiness.shouldNotify) {
+ for (const msg of apmState.pendingMessages) {
+ session.send(msg, "busy");
+ }
+ apmState = { ...apmState, pendingMessages: [] };
+ }
+ }
+
+ notificationState.recordNoticeWritten(String(seq), sessionId, [{ id: String(seq) }]);
+ writeAck(agentBaseDir, task.contextKey!, seq);
+ delivered = true;
+ } else {
+ writeNack(agentBaseDir, task.contextKey!, seq, "unsupported backend");
+ }
+
+ // Report steered task lifecycle to server
+ if (delivered && message.taskId) {
+ pendingSteeredTasks.add(message.taskId);
+ client.startTask(token, message.taskId).catch((e) => {
+ log.debug(`steering: failed to start steered task ${message.taskId}`, e);
+ });
+ }
+
+ cleanupInboxFile(agentBaseDir, task.contextKey!, seq);
+ },
+ );
+
+ }
+
// Message inactivity timeout — kill hung agent if no messages arrive within the window
const INACTIVITY_TIMEOUT_MS = messageInactivityTimeout ?? 5 * 60 * 1000;
let inactivityTimedOut = false;
@@ -454,6 +719,13 @@ export async function runSession(input: SessionRunnerInput): Promise<void> {
result.error = `message inactivity timeout (no messages for ${INACTIVITY_TIMEOUT_MS / 1000}s)`;
}
+ // Stop steering timers and clean up
+ if (stalledRecoveryTimer) clearInterval(stalledRecoveryTimer);
+ if (mailboxWatcher) {
+ mailboxWatcher.stop();
+ if (task.contextKey) cleanupSteeringDir(agentBaseDir, task.contextKey);
+ }
+
// Cleanup attachments after task completion
await cleanupAttachments(task.id);
diff --git a/src/cli/daemon/steering/__tests__/apmStateMachine.test.ts b/src/cli/daemon/steering/__tests__/apmStateMachine.test.ts
new file mode 100644
index 000000000..834b27cc3
--- /dev/null
+++ b/src/cli/daemon/steering/__tests__/apmStateMachine.test.ts
@@ -0,0 +1,334 @@
+import { describe, it, expect } from "vitest";
+import {
+ createInitialApmState,
+ reduceApmGatedToolUse,
+ reduceApmGatedCompaction,
+ reduceApmGatedEnqueue,
+ reduceApmGatedTurnEnd,
+ reduceApmGatedError,
+ reduceApmGatedFlushReadiness,
+ reduceApmGatedRecentEvent,
+ reduceApmStalledRecoveryTermination,
+ reduceApmStartupTimeoutTermination,
+ reduceApmIdleState,
+ reduceApmGatedAssistantContinuation,
+ reduceApmGatedFlush,
+ MAX_APM_GATED_STEERING_EVENTS,
+} from "../apmStateMachine.js";
+
+describe("ApmGatedSteeringState", () => {
+ describe("createInitialApmState", () => {
+ it("returns default state", () => {
+ const state = createInitialApmState();
+ expect(state.isIdle).toBe(false);
+ expect(state.phase).toBe("idle");
+ expect(state.outstandingToolUses).toBe(0);
+ expect(state.compacting).toBe(false);
+ expect(state.toolBoundaryFlushDisabled).toBe(false);
+ expect(state.pendingMessages).toEqual([]);
+ expect(state.recentEvents).toEqual([]);
+ });
+ });
+
+ describe("reduceApmIdleState", () => {
+ it("sets isIdle", () => {
+ const state = createInitialApmState();
+ const r = reduceApmIdleState(state, { isIdle: true });
+ expect(r.nextState.isIdle).toBe(true);
+ });
+ });
+
+ describe("reduceApmGatedToolUse", () => {
+ it("tool_call increments outstanding and enters tool_wait", () => {
+ const state = createInitialApmState();
+ const r = reduceApmGatedToolUse(state, { kind: "tool_call" });
+ expect(r.nextState.outstandingToolUses).toBe(1);
+ expect(r.nextState.phase).toBe("tool_wait");
+ expect(r.hadOutstandingToolUse).toBe(false);
+ expect(r.shouldFlushToolBatch).toBe(false);
+ });
+
+ it("tool_output decrements and enters tool_boundary", () => {
+ let state = createInitialApmState();
+ state = reduceApmGatedToolUse(state, { kind: "tool_call" }).nextState;
+ const r = reduceApmGatedToolUse(state, { kind: "tool_output" });
+ expect(r.nextState.outstandingToolUses).toBe(0);
+ expect(r.nextState.phase).toBe("tool_boundary");
+ expect(r.hadOutstandingToolUse).toBe(true);
+ expect(r.shouldFlushToolBatch).toBe(true);
+ });
+
+ it("3 overlapping tool_calls, flush only after 3rd tool_output", () => {
+ let state = createInitialApmState();
+ for (let i = 0; i < 3; i++) {
+ state = reduceApmGatedToolUse(state, { kind: "tool_call" }).nextState;
+ }
+ expect(state.outstandingToolUses).toBe(3);
+
+ for (let i = 0; i < 2; i++) {
+ const r = reduceApmGatedToolUse(state, { kind: "tool_output" });
+ state = r.nextState;
+ expect(r.shouldFlushToolBatch).toBe(false);
+ }
+ const r = reduceApmGatedToolUse(state, { kind: "tool_output" });
+ expect(r.shouldFlushToolBatch).toBe(true);
+ });
+
+ it("tool_output never goes below 0", () => {
+ const state = createInitialApmState();
+ const r = reduceApmGatedToolUse(state, { kind: "tool_output" });
+ expect(r.nextState.outstandingToolUses).toBe(0);
+ });
+ });
+
+ describe("reduceApmGatedCompaction", () => {
+ it("compaction_started sets compacting and phase", () => {
+ const state = createInitialApmState();
+ const r = reduceApmGatedCompaction(state, { kind: "compaction_started" });
+ expect(r.nextState.compacting).toBe(true);
+ expect(r.nextState.phase).toBe("compacting");
+ });
+
+ it("compaction_finished clears compacting, enters assistant_continuation", () => {
+ let state = createInitialApmState();
+ state = reduceApmGatedCompaction(state, { kind: "compaction_started" }).nextState;
+ const r = reduceApmGatedCompaction(state, { kind: "compaction_finished" });
+ expect(r.nextState.compacting).toBe(false);
+ expect(r.nextState.phase).toBe("assistant_continuation");
+ });
+
+ it("compaction_interrupted resets compacting without changing phase to assistant_continuation", () => {
+ let state = createInitialApmState();
+ state = reduceApmGatedCompaction(state, { kind: "compaction_started" }).nextState;
+ const r = reduceApmGatedCompaction(state, { kind: "compaction_interrupted" });
+ expect(r.nextState.compacting).toBe(false);
+ expect(r.nextState.phase).not.toBe("assistant_continuation");
+ });
+ });
+
+ describe("reduceApmGatedAssistantContinuation", () => {
+ it("sets phase to assistant_continuation", () => {
+ const state = createInitialApmState();
+ const r = reduceApmGatedAssistantContinuation(state);
+ expect(r.nextState.phase).toBe("assistant_continuation");
+ expect(r.nextState.isIdle).toBe(false);
+ });
+ });
+
+ describe("reduceApmGatedFlushReadiness", () => {
+ it("blocks when not gated", () => {
+ const state = createInitialApmState();
+ const r = reduceApmGatedFlushReadiness(state, { isGated: false, hasSession: true, inboxLength: 1, reason: "test" });
+ expect(r.shouldNotify).toBe(false);
+ expect(r.blockedReason).toBe("non_gated");
+ });
+
+ it("blocks when no session", () => {
+ const state = createInitialApmState();
+ const r = reduceApmGatedFlushReadiness(state, { isGated: true, hasSession: false, inboxLength: 1, reason: "test" });
+ expect(r.shouldNotify).toBe(false);
+ expect(r.blockedReason).toBe("missing_session");
+ });
+
+ it("blocks when inbox empty", () => {
+ const state = createInitialApmState();
+ const r = reduceApmGatedFlushReadiness(state, { isGated: true, hasSession: true, inboxLength: 0, reason: "test" });
+ expect(r.shouldNotify).toBe(false);
+ expect(r.blockedReason).toBe("empty_inbox");
+ });
+
+ it("blocks when tool_boundary_flush_disabled", () => {
+ let state = createInitialApmState();
+ state = reduceApmGatedError(state, { disableToolBoundaryFlush: true }).nextState;
+ const r = reduceApmGatedFlushReadiness(state, { isGated: true, hasSession: true, inboxLength: 1, reason: "test" });
+ expect(r.shouldNotify).toBe(false);
+ expect(r.blockedReason).toBe("tool_boundary_flush_disabled");
+ });
+
+ it("blocks when compacting", () => {
+ let state = createInitialApmState();
+ state = reduceApmGatedCompaction(state, { kind: "compaction_started" }).nextState;
+ const r = reduceApmGatedFlushReadiness(state, { isGated: true, hasSession: true, inboxLength: 1, reason: "test" });
+ expect(r.shouldNotify).toBe(false);
+ expect(r.blockedReason).toBe("compacting");
+ });
+
+ it("blocks when outstanding tool uses", () => {
+ let state = createInitialApmState();
+ state = reduceApmGatedToolUse(state, { kind: "tool_call" }).nextState;
+ const r = reduceApmGatedFlushReadiness(state, { isGated: true, hasSession: true, inboxLength: 1, reason: "test" });
+ expect(r.shouldNotify).toBe(false);
+ expect(r.blockedReason).toBe("outstanding_tool_uses");
+ });
+
+ it("notifies when all conditions met", () => {
+ const state = createInitialApmState();
+ const r = reduceApmGatedFlushReadiness(state, { isGated: true, hasSession: true, inboxLength: 2, reason: "test" });
+ expect(r.shouldNotify).toBe(true);
+ expect(r.blockedReason).toBeNull();
+ expect(r.effects).toHaveLength(1);
+ expect(r.effects[0].kind).toBe("notify_stdin");
+ expect(r.effects[0].stdinMode).toBe("busy");
+ expect(r.effects[0].clauseId).toBe("SMR-002");
+ });
+ });
+
+ describe("reduceApmGatedTurnEnd", () => {
+ it("with pending messages and conditions met → deliver_stdin", () => {
+ let state = createInitialApmState();
+ state = reduceApmGatedEnqueue(state, "msg1").nextState;
+ const r = reduceApmGatedTurnEnd(state, { inboxLength: 1, supportsStdinNotification: true, hasSession: true });
+ expect(r.effects).toHaveLength(1);
+ expect(r.effects[0].kind).toBe("deliver_stdin");
+ expect(r.effects[0].stdinMode).toBe("idle");
+ expect(r.nextState.isIdle).toBe(false);
+ expect(r.nextState.phase).toBe("idle");
+ });
+
+ it("with no inbox → idle, no effects", () => {
+ const state = createInitialApmState();
+ const r = reduceApmGatedTurnEnd(state, { inboxLength: 0, supportsStdinNotification: true, hasSession: true });
+ expect(r.effects).toHaveLength(0);
+ expect(r.nextState.isIdle).toBe(true);
+ });
+
+ it("with no defaults → idle, no effects", () => {
+ const state = createInitialApmState();
+ const r = reduceApmGatedTurnEnd(state);
+ expect(r.effects).toHaveLength(0);
+ expect(r.nextState.isIdle).toBe(true);
+ });
+
+ it("resets tool counts and compaction", () => {
+ let state = createInitialApmState();
+ state = reduceApmGatedToolUse(state, { kind: "tool_call" }).nextState;
+ state = reduceApmGatedCompaction(state, { kind: "compaction_started" }).nextState;
+ const r = reduceApmGatedTurnEnd(state);
+ expect(r.nextState.outstandingToolUses).toBe(0);
+ expect(r.nextState.compacting).toBe(false);
+ });
+ });
+
+ describe("reduceApmGatedError", () => {
+ it("sets phase to error", () => {
+ const state = createInitialApmState();
+ const r = reduceApmGatedError(state);
+ expect(r.nextState.phase).toBe("error");
+ });
+
+ it("disableToolBoundaryFlush sets flag", () => {
+ const state = createInitialApmState();
+ const r = reduceApmGatedError(state, { disableToolBoundaryFlush: true });
+ expect(r.nextState.toolBoundaryFlushDisabled).toBe(true);
+ expect(r.shouldDisableToolBoundaryFlush).toBe(true);
+ });
+
+ it("toolBoundaryFlushDisabled is sticky", () => {
+ let state = createInitialApmState();
+ state = reduceApmGatedError(state, { disableToolBoundaryFlush: true }).nextState;
+ const r = reduceApmGatedError(state);
+ expect(r.nextState.toolBoundaryFlushDisabled).toBe(true);
+ });
+ });
+
+ describe("reduceApmGatedFlush", () => {
+ it("records lastFlushReason", () => {
+ const state = createInitialApmState();
+ const r = reduceApmGatedFlush(state, { reason: "tool_boundary" });
+ expect(r.nextState.lastFlushReason).toBe("tool_boundary");
+ });
+ });
+
+ describe("reduceApmGatedRecentEvent", () => {
+ it("appends event summary", () => {
+ const state = createInitialApmState();
+ const r = reduceApmGatedRecentEvent(state, { event: "tool_call" });
+ expect(r.nextState.recentEvents).toHaveLength(1);
+ expect(r.nextState.recentEvents[0]).toContain("tool_call");
+ });
+
+ it("caps at MAX_APM_GATED_STEERING_EVENTS", () => {
+ let state = createInitialApmState();
+ for (let i = 0; i < MAX_APM_GATED_STEERING_EVENTS + 5; i++) {
+ state = reduceApmGatedRecentEvent(state, { event: `e${i}` }).nextState;
+ }
+ expect(state.recentEvents).toHaveLength(MAX_APM_GATED_STEERING_EVENTS);
+ });
+ });
+
+ describe("reduceApmGatedEnqueue", () => {
+ it("appends message to pendingMessages", () => {
+ const state = createInitialApmState();
+ const r = reduceApmGatedEnqueue(state, "hello");
+ expect(r.nextState.pendingMessages).toEqual(["hello"]);
+ });
+
+ it("accumulates messages", () => {
+ let state = createInitialApmState();
+ state = reduceApmGatedEnqueue(state, "a").nextState;
+ state = reduceApmGatedEnqueue(state, "b").nextState;
+ expect(state.pendingMessages).toEqual(["a", "b"]);
+ });
+ });
+
+ describe("reduceApmStalledRecoveryTermination", () => {
+ const baseInput = {
+ inboxLength: 1,
+ staleForMs: 200_000,
+ staleThresholdMs: 120_000,
+ runtimeProgressIsStale: true,
+ hasSession: true,
+ busyDeliveryMode: "none",
+ hasDirectStdinRecoveryEvidence: false,
+ };
+
+ it("terminates when stale with inbox", () => {
+ const state = createInitialApmState();
+ const r = reduceApmStalledRecoveryTermination(state, baseInput);
+ expect(r.shouldTerminate).toBe(true);
+ expect(r.nextState.expectedTerminationReason).toBe("stalled_recovery");
+ });
+
+ it("does not terminate with empty inbox", () => {
+ const state = createInitialApmState();
+ const r = reduceApmStalledRecoveryTermination(state, { ...baseInput, inboxLength: 0 });
+ expect(r.shouldTerminate).toBe(false);
+ expect(r.blockedReason).toBe("empty_inbox");
+ });
+
+ it("does not terminate when not stale", () => {
+ const state = createInitialApmState();
+ const r = reduceApmStalledRecoveryTermination(state, {
+ ...baseInput,
+ staleForMs: 10_000,
+ runtimeProgressIsStale: false,
+ });
+ expect(r.shouldTerminate).toBe(false);
+ expect(r.blockedReason).toBe("runtime_progress_recent");
+ });
+
+ it("already recovering returns alreadyRecovering", () => {
+ let state = createInitialApmState();
+ state = reduceApmStalledRecoveryTermination(state, baseInput).nextState;
+ const r = reduceApmStalledRecoveryTermination(state, baseInput);
+ expect(r.shouldTerminate).toBe(false);
+ expect(r.alreadyRecovering).toBe(true);
+ });
+ });
+
+ describe("reduceApmStartupTimeoutTermination", () => {
+ it("terminates when no progress events", () => {
+ const state = createInitialApmState();
+ const r = reduceApmStartupTimeoutTermination(state, { hasRuntimeProgressEvent: false });
+ expect(r.shouldTerminate).toBe(true);
+ expect(r.nextState.expectedTerminationReason).toBe("startup_timeout");
+ });
+
+ it("does not terminate when has progress events", () => {
+ const state = createInitialApmState();
+ const r = reduceApmStartupTimeoutTermination(state, { hasRuntimeProgressEvent: true });
+ expect(r.shouldTerminate).toBe(false);
+ expect(r.blockedReason).toBe("runtime_progress_started");
+ });
+ });
+});
diff --git a/src/cli/daemon/steering/__tests__/errorDiagnostics.test.ts b/src/cli/daemon/steering/__tests__/errorDiagnostics.test.ts
new file mode 100644
index 000000000..bc402e3ff
--- /dev/null
+++ b/src/cli/daemon/steering/__tests__/errorDiagnostics.test.ts
@@ -0,0 +1,186 @@
+import { describe, it, expect } from "vitest";
+import {
+ classifyRuntimeError,
+ extractHttpStatus,
+ scrubDiagnosticText,
+} from "../errorDiagnostics.js";
+
+describe("extractHttpStatus", () => {
+ it("extracts from 'HTTP 429'", () => {
+ expect(extractHttpStatus("HTTP 429 Too Many Requests")).toBe(429);
+ });
+
+ it("extracts from 'status: 401'", () => {
+ expect(extractHttpStatus("status: 401")).toBe(401);
+ });
+
+ it("extracts from 'API Error: 500'", () => {
+ expect(extractHttpStatus("API Error: 500")).toBe(500);
+ });
+
+ it("extracts from semantic '404 Not Found'", () => {
+ expect(extractHttpStatus("404 Not Found")).toBe(404);
+ });
+
+ it("returns null for no status", () => {
+ expect(extractHttpStatus("something went wrong")).toBeNull();
+ });
+
+ it("does not extract bare numbers without context", () => {
+ expect(extractHttpStatus("processed 429 records")).toBeNull();
+ });
+});
+
+describe("classifyRuntimeError", () => {
+ it("explicit RateLimitError token → RateLimitError", () => {
+ const r = classifyRuntimeError("RateLimitError: try again later");
+ expect(r.errorClass).toBe("RateLimitError");
+ expect(r.action).toBe("retry_backoff");
+ });
+
+ it("explicit AuthenticationError token → AuthError", () => {
+ const r = classifyRuntimeError("AuthenticationError: invalid credentials");
+ expect(r.errorClass).toBe("AuthError");
+ });
+
+ it("HTTP 429 → RateLimitError", () => {
+ const r = classifyRuntimeError("HTTP 429 Too Many Requests");
+ expect(r.errorClass).toBe("RateLimitError");
+ expect(r.action).toBe("retry_backoff");
+ });
+
+ it("status: 401 → AuthError", () => {
+ const r = classifyRuntimeError("status: 401 Unauthorized");
+ expect(r.errorClass).toBe("AuthError");
+ expect(r.action).toBe("abort");
+ });
+
+ it("HTTP 404 → NotFoundError", () => {
+ const r = classifyRuntimeError("HTTP 404 Not Found");
+ expect(r.errorClass).toBe("NotFoundError");
+ expect(r.action).toBe("report");
+ });
+
+ it("HTTP 500 → ProviderServerError", () => {
+ const r = classifyRuntimeError("HTTP 500 Internal Server Error");
+ expect(r.errorClass).toBe("ProviderServerError");
+ expect(r.action).toBe("retry");
+ });
+
+ it("rate limit text → RateLimitError", () => {
+ const r = classifyRuntimeError("API rate limit exceeded, please slow down");
+ expect(r.errorClass).toBe("RateLimitError");
+ });
+
+ it("overloaded → RateLimitError", () => {
+ const r = classifyRuntimeError("Service overloaded, try again later");
+ expect(r.errorClass).toBe("RateLimitError");
+ });
+
+ it("token revoked → AuthError (expanded pattern)", () => {
+ const r = classifyRuntimeError("your token revoked by admin");
+ expect(r.errorClass).toBe("AuthError");
+ });
+
+ it("refresh token expired → AuthError (expanded pattern)", () => {
+ const r = classifyRuntimeError("refresh token expired, please re-authenticate");
+ expect(r.errorClass).toBe("AuthError");
+ });
+
+ it("session expired → AuthError", () => {
+ const r = classifyRuntimeError("Your session expired");
+ expect(r.errorClass).toBe("AuthError");
+ });
+
+ it("credentials not found → AuthError", () => {
+ const r = classifyRuntimeError("credentials not found in keychain");
+ expect(r.errorClass).toBe("AuthError");
+ });
+
+ it("invalid api key → AuthError", () => {
+ const r = classifyRuntimeError("Invalid API key provided");
+ expect(r.errorClass).toBe("AuthError");
+ });
+
+ it("model not supported → ModelConfigError", () => {
+ const r = classifyRuntimeError("model not supported: gpt-99");
+ expect(r.errorClass).toBe("ModelConfigError");
+ expect(r.action).toBe("abort");
+ });
+
+ it("ETIMEDOUT → TimeoutError", () => {
+ const r = classifyRuntimeError("connect ETIMEDOUT 1.2.3.4:443");
+ expect(r.errorClass).toBe("TimeoutError");
+ expect(r.action).toBe("retry");
+ });
+
+ it("ECONNREFUSED → ProviderConnectionError", () => {
+ const r = classifyRuntimeError("connect ECONNREFUSED 127.0.0.1:8080");
+ expect(r.errorClass).toBe("ProviderConnectionError");
+ expect(r.action).toBe("retry_jitter");
+ });
+
+ it("ECONNRESET → ProviderConnectionError", () => {
+ const r = classifyRuntimeError("read ECONNRESET");
+ expect(r.errorClass).toBe("ProviderConnectionError");
+ });
+
+ it("Unable to connect to API → ProviderConnectionError", () => {
+ const r = classifyRuntimeError("Unable to connect to API endpoint");
+ expect(r.errorClass).toBe("ProviderConnectionError");
+ });
+
+ it("unknown error → RuntimeError", () => {
+ const r = classifyRuntimeError("something completely unknown happened");
+ expect(r.errorClass).toBe("RuntimeError");
+ expect(r.action).toBe("report");
+ });
+
+ it("httpStatus override via parameter", () => {
+ const r = classifyRuntimeError("some generic message", 429);
+ expect(r.errorClass).toBe("RateLimitError");
+ });
+
+ it("explicit token takes priority over HTTP status", () => {
+ const r = classifyRuntimeError("TimeoutError: HTTP 429 rate limited", 429);
+ expect(r.errorClass).toBe("TimeoutError");
+ });
+});
+
+describe("scrubDiagnosticText", () => {
+ it("redacts sk-ant tokens", () => {
+ const result = scrubDiagnosticText("key=sk-ant-abc123-xyz789 failed");
+ expect(result).toContain("sk-ant-***");
+ expect(result).not.toContain("abc123");
+ });
+
+ it("redacts sk-proj tokens", () => {
+ const result = scrubDiagnosticText("token: sk-proj-longtoken123");
+ expect(result).toContain("sk-proj-***");
+ expect(result).not.toContain("longtoken123");
+ });
+
+ it("redacts Bearer tokens", () => {
+ const result = scrubDiagnosticText("Authorization: Bearer eyJhbGciOiJIUzI1Ni.token");
+ expect(result).toContain("Bearer ***");
+ expect(result).not.toContain("eyJhbGciOiJIUzI1Ni");
+ });
+
+ it("redacts email addresses", () => {
+ const result = scrubDiagnosticText("user [email protected] failed");
+ expect(result).toContain("***@***.***");
+ expect(result).not.toContain("[email protected]");
+ });
+
+ it("redacts URL credentials", () => {
+ const result = scrubDiagnosticText("https://admin:[email protected]/api");
+ expect(result).toContain("://***:***@");
+ expect(result).not.toContain("admin:secret");
+ });
+
+ it("redacts home directory paths", () => {
+ const result = scrubDiagnosticText("file at /Users/john/.config/app.json");
+ expect(result).toContain("/***");
+ expect(result).not.toContain("/Users/john");
+ });
+});
diff --git a/src/cli/daemon/steering/__tests__/notificationState.test.ts b/src/cli/daemon/steering/__tests__/notificationState.test.ts
new file mode 100644
index 000000000..de4c5e09a
--- /dev/null
+++ b/src/cli/daemon/steering/__tests__/notificationState.test.ts
@@ -0,0 +1,155 @@
+import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
+import {
+ RuntimeNotificationState,
+ inboxNoticeMessageIdentity,
+ computeInboxNoticeFingerprint,
+} from "../notificationState.js";
+
+describe("inboxNoticeMessageIdentity", () => {
+ it("numeric seq gets s: prefix", () => {
+ expect(inboxNoticeMessageIdentity({ seq: 42 })).toBe("s:42");
+ });
+
+ it("string message_id gets m: prefix", () => {
+ expect(inboxNoticeMessageIdentity({ message_id: "abc" })).toBe("m:abc");
+ });
+
+ it("string id gets m: prefix", () => {
+ expect(inboxNoticeMessageIdentity({ id: "xyz" })).toBe("m:xyz");
+ });
+
+ it("empty fields return empty string", () => {
+ expect(inboxNoticeMessageIdentity({})).toBe("");
+ });
+
+ it("invalid seq (NaN) falls through to id", () => {
+ expect(inboxNoticeMessageIdentity({ seq: NaN as unknown as number, id: "fallback" })).toBe("m:fallback");
+ });
+
+ it("negative seq falls through", () => {
+ expect(inboxNoticeMessageIdentity({ seq: -1, message_id: "mid" })).toBe("m:mid");
+ });
+
+ it("seq priority over message_id", () => {
+ expect(inboxNoticeMessageIdentity({ seq: 5, message_id: "mid" })).toBe("s:5");
+ });
+});
+
+describe("computeInboxNoticeFingerprint", () => {
+ it("empty messages → empty fingerprint", () => {
+ expect(computeInboxNoticeFingerprint([])).toBe("");
+ });
+
+ it("sorted keys joined by comma", () => {
+ const fp = computeInboxNoticeFingerprint([{ seq: 2 }, { seq: 1 }]);
+ expect(fp).toBe("s:1,s:2");
+ });
+
+ it("skips messages with no identity", () => {
+ const fp = computeInboxNoticeFingerprint([{ seq: 1 }, {}]);
+ expect(fp).toBe("s:1");
+ });
+});
+
+describe("RuntimeNotificationState", () => {
+ beforeEach(() => { vi.useFakeTimers(); });
+ afterEach(() => { vi.useRealTimers(); });
+
+ describe("isDuplicateNotice", () => {
+ it("same fingerprint + same session → duplicate", () => {
+ const ns = new RuntimeNotificationState();
+ ns.recordNoticeWritten("fp1", "sess1");
+ expect(ns.isDuplicateNotice("fp1", "sess1")).toBe(true);
+ });
+
+ it("same fingerprint + different session → not duplicate", () => {
+ const ns = new RuntimeNotificationState();
+ ns.recordNoticeWritten("fp1", "sess1");
+ expect(ns.isDuplicateNotice("fp1", "sess2")).toBe(false);
+ });
+
+ it("empty fingerprint → never duplicate", () => {
+ const ns = new RuntimeNotificationState();
+ ns.recordNoticeWritten("", "sess1");
+ expect(ns.isDuplicateNotice("", "sess1")).toBe(false);
+ });
+ });
+
+ describe("session boundary resets contribution tracking", () => {
+ it("filterUncontributedMessages returns all on new session", () => {
+ const ns = new RuntimeNotificationState();
+ ns.recordNoticeWritten("fp1", "sess1", [{ seq: 1 }]);
+ const result = ns.filterUncontributedMessages([{ seq: 1 }], "sess2");
+ expect(result).toHaveLength(1);
+ });
+
+ it("filterUncontributedMessages filters contributed in same session", () => {
+ const ns = new RuntimeNotificationState();
+ ns.recordNoticeWritten("fp1", "sess1", [{ seq: 1 }, { seq: 2 }]);
+ const result = ns.filterUncontributedMessages([{ seq: 1 }, { seq: 3 }], "sess1");
+ expect(result).toHaveLength(1);
+ expect(result[0].seq).toBe(3);
+ });
+ });
+
+ describe("debounce timer", () => {
+ it("schedule fires after delay", () => {
+ const ns = new RuntimeNotificationState();
+ let called = false;
+ ns.schedule(() => { called = true; }, 100);
+ expect(called).toBe(false);
+ vi.advanceTimersByTime(100);
+ expect(called).toBe(true);
+ });
+
+ it("second schedule returns false while armed", () => {
+ const ns = new RuntimeNotificationState();
+ expect(ns.schedule(() => {}, 100)).toBe(true);
+ expect(ns.schedule(() => {}, 100)).toBe(false);
+ });
+
+ it("takePendingAndClearTimer cancels timer", () => {
+ const ns = new RuntimeNotificationState();
+ ns.add(3);
+ let called = false;
+ ns.schedule(() => { called = true; }, 100);
+ const count = ns.takePendingAndClearTimer();
+ expect(count).toBe(3);
+ vi.advanceTimersByTime(200);
+ expect(called).toBe(false);
+ });
+ });
+
+ describe("encode failure tracking", () => {
+ it("recordNoticeEncodeFailed caches failure", () => {
+ const ns = new RuntimeNotificationState();
+ ns.recordNoticeEncodeFailed("fp1", "sess1");
+ expect(ns.isDuplicateEncodeFailedNotice("fp1", "sess1")).toBe(true);
+ });
+
+ it("successful write clears encode failure", () => {
+ const ns = new RuntimeNotificationState();
+ ns.recordNoticeEncodeFailed("fp1", "sess1");
+ ns.recordNoticeWritten("fp1", "sess1");
+ expect(ns.isDuplicateEncodeFailedNotice("fp1", "sess1")).toBe(false);
+ });
+
+ it("empty fingerprint not cached", () => {
+ const ns = new RuntimeNotificationState();
+ ns.recordNoticeEncodeFailed("", "sess1");
+ expect(ns.isDuplicateEncodeFailedNotice("", "sess1")).toBe(false);
+ });
+ });
+
+ describe("pending count", () => {
+ it("add increments, takePending resets", () => {
+ const ns = new RuntimeNotificationState();
+ ns.add(1);
+ ns.add(2);
+ expect(ns.pendingCount).toBe(3);
+ const count = ns.takePendingAndClearTimer();
+ expect(count).toBe(3);
+ expect(ns.pendingCount).toBe(0);
+ });
+ });
+});
diff --git a/src/cli/daemon/steering/__tests__/progressState.test.ts b/src/cli/daemon/steering/__tests__/progressState.test.ts
new file mode 100644
index 000000000..686190560
--- /dev/null
+++ b/src/cli/daemon/steering/__tests__/progressState.test.ts
@@ -0,0 +1,120 @@
+import { describe, it, expect } from "vitest";
+import { RuntimeProgressState } from "../progressState.js";
+
+describe("RuntimeProgressState", () => {
+ it("starts with isStale=false", () => {
+ const ps = new RuntimeProgressState(1000);
+ expect(ps.isStale).toBe(false);
+ expect(ps.staleSince).toBeNull();
+ });
+
+ describe("ageMs", () => {
+ it("returns elapsed time since last event", () => {
+ const ps = new RuntimeProgressState(1000);
+ expect(ps.ageMs(3000)).toBe(2000);
+ });
+
+ it("resets after recordRealEvent", () => {
+ const ps = new RuntimeProgressState(1000);
+ ps.recordRealEvent("text", 5000);
+ expect(ps.ageMs(6000)).toBe(1000);
+ });
+
+ it("resets after recordInternalProgress", () => {
+ const ps = new RuntimeProgressState(1000);
+ ps.recordInternalProgress("internal_progress", 5000);
+ expect(ps.ageMs(6000)).toBe(1000);
+ });
+ });
+
+ describe("shouldMarkStale", () => {
+ it("returns true when elapsed > threshold", () => {
+ const ps = new RuntimeProgressState(1000);
+ expect(ps.shouldMarkStale(2000, 5000)).toBe(true);
+ });
+
+ it("returns false when elapsed < threshold", () => {
+ const ps = new RuntimeProgressState(1000);
+ expect(ps.shouldMarkStale(2000, 2500)).toBe(false);
+ });
+
+ it("returns false when already stale", () => {
+ const ps = new RuntimeProgressState(1000);
+ ps.markStale(2000);
+ expect(ps.shouldMarkStale(500, 5000)).toBe(false);
+ });
+
+ it("uses ageMs internally", () => {
+ const ps = new RuntimeProgressState(1000);
+ ps.recordRealEvent("text", 4000);
+ expect(ps.shouldMarkStale(2000, 5000)).toBe(false);
+ expect(ps.shouldMarkStale(2000, 7000)).toBe(true);
+ });
+ });
+
+ describe("markStale", () => {
+ it("sets isStale and staleSince", () => {
+ const ps = new RuntimeProgressState(1000);
+ ps.markStale(5000);
+ expect(ps.isStale).toBe(true);
+ expect(ps.staleSince).toBe(5000);
+ });
+
+ it("is idempotent — second call does not reset staleSince", () => {
+ const ps = new RuntimeProgressState(1000);
+ ps.markStale(5000);
+ ps.markStale(9000);
+ expect(ps.staleSince).toBe(5000);
+ });
+ });
+
+ describe("recordRealEvent", () => {
+ it("clears stale flag", () => {
+ const ps = new RuntimeProgressState(1000);
+ ps.markStale(5000);
+ expect(ps.isStale).toBe(true);
+ ps.recordRealEvent("text", 6000);
+ expect(ps.isStale).toBe(false);
+ expect(ps.staleSince).toBeNull();
+ });
+ });
+
+ describe("recordInternalProgress", () => {
+ it("does NOT clear stale flag", () => {
+ const ps = new RuntimeProgressState(1000);
+ ps.markStale(5000);
+ ps.recordInternalProgress("internal_progress", 6000);
+ expect(ps.isStale).toBe(true);
+ });
+ });
+
+ describe("processEvent", () => {
+ it("text → recordRealEvent", () => {
+ const ps = new RuntimeProgressState(1000);
+ ps.markStale(2000);
+ ps.processEvent({ kind: "text", text: "hi" }, 3000);
+ expect(ps.isStale).toBe(false);
+ });
+
+ it("tool_call → recordRealEvent", () => {
+ const ps = new RuntimeProgressState(1000);
+ ps.markStale(2000);
+ ps.processEvent({ kind: "tool_call", name: "Bash" }, 3000);
+ expect(ps.isStale).toBe(false);
+ });
+
+ it("internal_progress → recordInternalProgress", () => {
+ const ps = new RuntimeProgressState(1000);
+ ps.markStale(2000);
+ ps.processEvent({ kind: "internal_progress" }, 3000);
+ expect(ps.isStale).toBe(true);
+ });
+
+ it("compaction_started → recordInternalProgress", () => {
+ const ps = new RuntimeProgressState(1000);
+ ps.markStale(2000);
+ ps.processEvent({ kind: "compaction_started" }, 3000);
+ expect(ps.isStale).toBe(true);
+ });
+ });
+});
diff --git a/src/cli/daemon/steering/__tests__/turnState.test.ts b/src/cli/daemon/steering/__tests__/turnState.test.ts
new file mode 100644
index 000000000..7ff510b17
--- /dev/null
+++ b/src/cli/daemon/steering/__tests__/turnState.test.ts
@@ -0,0 +1,113 @@
+import { describe, it, expect } from "vitest";
+import { RuntimeTurnState } from "../turnState.js";
+
+describe("RuntimeTurnState", () => {
+ it("starts with isInTurn=false and canSteerBusy=false", () => {
+ const ts = new RuntimeTurnState();
+ expect(ts.isInTurn).toBe(false);
+ expect(ts.turnId).toBeNull();
+ expect(ts.canSteerBusy).toBe(false);
+ });
+
+ it("markTurnStarted sets isInTurn=true and canSteerBusy=true", () => {
+ const ts = new RuntimeTurnState();
+ ts.markTurnStarted("turn-1");
+ expect(ts.isInTurn).toBe(true);
+ expect(ts.turnId).toBe("turn-1");
+ expect(ts.canSteerBusy).toBe(true);
+ });
+
+ it("markTurnCompleted sets isInTurn=false, canSteerBusy=false", () => {
+ const ts = new RuntimeTurnState();
+ ts.markTurnStarted("turn-1");
+ ts.markTurnCompleted();
+ expect(ts.isInTurn).toBe(false);
+ expect(ts.turnId).toBeNull();
+ expect(ts.canSteerBusy).toBe(false);
+ });
+
+ it("markTurnStarted without turnId preserves null turnId", () => {
+ const ts = new RuntimeTurnState();
+ ts.markTurnStarted();
+ expect(ts.isInTurn).toBe(false);
+ expect(ts.turnId).toBeNull();
+ expect(ts.canSteerBusy).toBe(false);
+ });
+
+ it("canSteerBusy=false after markToolBoundary", () => {
+ const ts = new RuntimeTurnState();
+ ts.markTurnStarted("t1");
+ expect(ts.canSteerBusy).toBe(true);
+ ts.markToolBoundary();
+ expect(ts.canSteerBusy).toBe(false);
+ });
+
+ it("canSteerBusy=true after markProgress", () => {
+ const ts = new RuntimeTurnState();
+ ts.markTurnStarted("t1");
+ ts.markToolBoundary();
+ expect(ts.canSteerBusy).toBe(false);
+ ts.markProgress();
+ expect(ts.canSteerBusy).toBe(true);
+ });
+
+ it("markToolBoundary → markProgress cycle", () => {
+ const ts = new RuntimeTurnState();
+ ts.markTurnStarted("t1");
+ ts.markToolBoundary();
+ expect(ts.canSteerBusy).toBe(false);
+ ts.markProgress();
+ expect(ts.canSteerBusy).toBe(true);
+ ts.markToolBoundary();
+ expect(ts.canSteerBusy).toBe(false);
+ });
+
+ it("thinking event closes gate", () => {
+ const ts = new RuntimeTurnState();
+ ts.markTurnStarted("t1");
+ ts.markToolBoundary(); // thinking
+ expect(ts.canSteerBusy).toBe(false);
+ });
+
+ it("compaction closes gate, compaction_finished reopens", () => {
+ const ts = new RuntimeTurnState();
+ ts.markTurnStarted("t1");
+ ts.markToolBoundary(); // compaction_started
+ expect(ts.canSteerBusy).toBe(false);
+ ts.markProgress(); // compaction_finished
+ expect(ts.canSteerBusy).toBe(true);
+ });
+
+ it("adoptTurnId updates turnId without touching gate", () => {
+ const ts = new RuntimeTurnState();
+ ts.markTurnStarted("t1");
+ ts.markToolBoundary();
+ expect(ts.canSteerBusy).toBe(false);
+ ts.adoptTurnId("t2");
+ expect(ts.turnId).toBe("t2");
+ expect(ts.canSteerBusy).toBe(false); // gate still closed
+ });
+
+ it("reset clears all state", () => {
+ const ts = new RuntimeTurnState();
+ ts.markTurnStarted("t1");
+ ts.markToolBoundary();
+ ts.reset();
+ expect(ts.isInTurn).toBe(false);
+ expect(ts.turnId).toBeNull();
+ expect(ts.canSteerBusy).toBe(false);
+ });
+
+ it("multiple start/complete cycles work", () => {
+ const ts = new RuntimeTurnState();
+ ts.markTurnStarted("t1");
+ expect(ts.isInTurn).toBe(true);
+ expect(ts.canSteerBusy).toBe(true);
+ ts.markTurnCompleted();
+ expect(ts.isInTurn).toBe(false);
+ ts.markTurnStarted("t2");
+ expect(ts.isInTurn).toBe(true);
+ expect(ts.turnId).toBe("t2");
+ expect(ts.canSteerBusy).toBe(true);
+ });
+});
diff --git a/src/cli/daemon/steering/apmStateMachine.ts b/src/cli/daemon/steering/apmStateMachine.ts
new file mode 100644
index 000000000..6c12200da
--- /dev/null
+++ b/src/cli/daemon/steering/apmStateMachine.ts
@@ -0,0 +1,302 @@
+/**
+ * APM (Agent Process Manager) gated-steering state machine.
+ *
+ * Where `RuntimeTurnState` answers "is it safe *right now*?", this reducer set
+ * is the coarse-grained policy layer that decides WHEN to flush queued inbox
+ * notices into a `gated` runtime, and emits the concrete delivery effects
+ * (`notify_stdin` / `deliver_stdin`).
+ *
+ * It is a pure reducer: `(state, input) -> { nextState?, effects?, ... }`. The
+ * orchestrator owns the mutable copy and applies the effects.
+ *
+ * Phases: idle → tool_wait → tool_boundary → assistant_continuation →
+ * compacting → error → idle. Notices flush only at safe phases.
+ *
+ * Clause `SMR-002` tags every stdin-delivery effect (a stable marker used in
+ * telemetry to identify the steering-message rule).
+ */
+
+export const MAX_APM_GATED_STEERING_EVENTS = 12;
+
+export type ApmPhase =
+ | "idle"
+ | "tool_wait"
+ | "tool_boundary"
+ | "assistant_continuation"
+ | "compacting"
+ | "error";
+
+export interface ApmGatedSteeringState {
+ isIdle: boolean;
+ expectedTerminationReason: string | null;
+ phase: ApmPhase;
+ outstandingToolUses: number;
+ compacting: boolean;
+ toolBoundaryFlushDisabled: boolean;
+ lastFlushReason: string | null;
+ recentEvents: string[];
+ pendingMessages: string[];
+}
+
+export type StdinDeliveryEffect = {
+ kind: "notify_stdin" | "deliver_stdin";
+ reason: string;
+ stdinMode: "busy" | "idle";
+ clauseId: "SMR-002";
+};
+
+export function createInitialApmState(): ApmGatedSteeringState {
+ return {
+ isIdle: false,
+ expectedTerminationReason: null,
+ phase: "idle",
+ outstandingToolUses: 0,
+ compacting: false,
+ toolBoundaryFlushDisabled: false,
+ lastFlushReason: null,
+ recentEvents: [],
+ pendingMessages: [],
+ };
+}
+
+/* ------------------------------------------------------------------ */
+/* Phase transitions */
+/* ------------------------------------------------------------------ */
+
+export function reduceApmIdleState(
+ state: ApmGatedSteeringState,
+ input: { isIdle: boolean },
+): { nextState: ApmGatedSteeringState } {
+ return { nextState: { ...state, isIdle: input.isIdle } };
+}
+
+export function reduceApmGatedToolUse(
+ state: ApmGatedSteeringState,
+ input: { kind: string },
+): {
+ nextState: ApmGatedSteeringState;
+ hadOutstandingToolUse: boolean;
+ shouldFlushToolBatch: boolean;
+} {
+ if (input.kind === "tool_call") {
+ return {
+ nextState: {
+ ...state,
+ isIdle: false,
+ phase: "tool_wait",
+ outstandingToolUses: state.outstandingToolUses + 1,
+ },
+ hadOutstandingToolUse: state.outstandingToolUses > 0,
+ shouldFlushToolBatch: false,
+ };
+ }
+ const hadOutstandingToolUse = state.outstandingToolUses > 0;
+ const outstandingToolUses = Math.max(0, state.outstandingToolUses - 1);
+ return {
+ nextState: {
+ ...state,
+ isIdle: false,
+ phase: "tool_boundary",
+ outstandingToolUses,
+ },
+ hadOutstandingToolUse,
+ shouldFlushToolBatch: hadOutstandingToolUse && outstandingToolUses === 0,
+ };
+}
+
+export function reduceApmGatedCompaction(
+ state: ApmGatedSteeringState,
+ input: { kind: "compaction_started" | "compaction_interrupted" | string },
+): { nextState: ApmGatedSteeringState } {
+ if (input.kind === "compaction_started") {
+ return { nextState: { ...state, isIdle: false, phase: "compacting", compacting: true } };
+ }
+ if (input.kind === "compaction_interrupted") {
+ return { nextState: { ...state, isIdle: false, compacting: false } };
+ }
+ // compaction_finished
+ return {
+ nextState: { ...state, isIdle: false, phase: "assistant_continuation", compacting: false },
+ };
+}
+
+export function reduceApmGatedAssistantContinuation(state: ApmGatedSteeringState): {
+ nextState: ApmGatedSteeringState;
+} {
+ return { nextState: { ...state, isIdle: false, phase: "assistant_continuation" } };
+}
+
+/* ------------------------------------------------------------------ */
+/* Delivery decisions (emit effects) */
+/* ------------------------------------------------------------------ */
+
+export function reduceApmGatedFlushReadiness(
+ state: ApmGatedSteeringState,
+ input: { isGated: boolean; hasSession: boolean; inboxLength: number; reason: string },
+): { shouldNotify: boolean; blockedReason: string | null; effects: StdinDeliveryEffect[] } {
+ if (!input.isGated) return { shouldNotify: false, blockedReason: "non_gated", effects: [] };
+ if (!input.hasSession) return { shouldNotify: false, blockedReason: "missing_session", effects: [] };
+ if (input.inboxLength === 0) return { shouldNotify: false, blockedReason: "empty_inbox", effects: [] };
+ if (state.toolBoundaryFlushDisabled) {
+ return { shouldNotify: false, blockedReason: "tool_boundary_flush_disabled", effects: [] };
+ }
+ if (state.compacting) return { shouldNotify: false, blockedReason: "compacting", effects: [] };
+ if (state.outstandingToolUses > 0) {
+ return { shouldNotify: false, blockedReason: "outstanding_tool_uses", effects: [] };
+ }
+ return {
+ shouldNotify: true,
+ blockedReason: null,
+ effects: [{ kind: "notify_stdin", reason: input.reason, stdinMode: "busy", clauseId: "SMR-002" }],
+ };
+}
+
+export function reduceApmGatedTurnEnd(
+ state: ApmGatedSteeringState,
+ input: {
+ inboxLength?: number;
+ supportsStdinNotification?: boolean;
+ hasSession?: boolean;
+ } = {},
+): { nextState: ApmGatedSteeringState; effects: StdinDeliveryEffect[] } {
+ const shouldDeliverQueuedMessages = Boolean(
+ input.inboxLength && input.inboxLength > 0 && input.supportsStdinNotification && input.hasSession,
+ );
+ return {
+ nextState: {
+ ...state,
+ isIdle: !shouldDeliverQueuedMessages,
+ phase: "idle",
+ outstandingToolUses: 0,
+ compacting: false,
+ pendingMessages: shouldDeliverQueuedMessages ? state.pendingMessages : [],
+ },
+ effects: shouldDeliverQueuedMessages
+ ? [{ kind: "deliver_stdin", reason: "turn_end", stdinMode: "idle", clauseId: "SMR-002" }]
+ : [],
+ };
+}
+
+export function reduceApmGatedError(
+ state: ApmGatedSteeringState,
+ input: { disableToolBoundaryFlush?: boolean } = {},
+): { nextState: ApmGatedSteeringState; shouldDisableToolBoundaryFlush: boolean } {
+ const shouldDisableToolBoundaryFlush = input.disableToolBoundaryFlush === true;
+ return {
+ nextState: {
+ ...state,
+ phase: "error",
+ compacting: false,
+ toolBoundaryFlushDisabled: state.toolBoundaryFlushDisabled || shouldDisableToolBoundaryFlush,
+ },
+ shouldDisableToolBoundaryFlush,
+ };
+}
+
+export function reduceApmGatedFlush(
+ state: ApmGatedSteeringState,
+ input: { reason: string },
+): { nextState: ApmGatedSteeringState } {
+ return { nextState: { ...state, lastFlushReason: input.reason } };
+}
+
+export function reduceApmGatedRecentEvent(
+ state: ApmGatedSteeringState,
+ input: { event: string },
+): { nextState: ApmGatedSteeringState } {
+ const summary = `${input.event}:${state.phase}:tools=${state.outstandingToolUses}:compact=${state.compacting}`;
+ return {
+ nextState: {
+ ...state,
+ recentEvents: [...state.recentEvents, summary].slice(-MAX_APM_GATED_STEERING_EVENTS),
+ },
+ };
+}
+
+/* ------------------------------------------------------------------ */
+/* Alook-specific: enqueue pending messages */
+/* ------------------------------------------------------------------ */
+
+export function reduceApmGatedEnqueue(
+ state: ApmGatedSteeringState,
+ message: string,
+): { nextState: ApmGatedSteeringState } {
+ return {
+ nextState: {
+ ...state,
+ pendingMessages: [...state.pendingMessages, message],
+ },
+ };
+}
+
+/* ------------------------------------------------------------------ */
+/* Recovery / termination */
+/* ------------------------------------------------------------------ */
+
+export function reduceApmStalledRecoveryTermination(
+ state: ApmGatedSteeringState,
+ input: {
+ inboxLength: number;
+ staleForMs: number;
+ staleThresholdMs: number;
+ runtimeProgressIsStale: boolean;
+ hasSession: boolean;
+ busyDeliveryMode: string;
+ hasDirectStdinRecoveryEvidence: boolean;
+ },
+): {
+ nextState: ApmGatedSteeringState;
+ shouldTerminate: boolean;
+ alreadyRecovering: boolean;
+ blockedReason: string | null;
+} {
+ if (input.inboxLength === 0) {
+ return { nextState: state, shouldTerminate: false, alreadyRecovering: false, blockedReason: "empty_inbox" };
+ }
+ if (state.expectedTerminationReason === "stalled_recovery") {
+ return { nextState: state, shouldTerminate: false, alreadyRecovering: true, blockedReason: null };
+ }
+ const supportsStdinNotification = input.busyDeliveryMode !== "none";
+ const directStdinRuntime = supportsStdinNotification && input.busyDeliveryMode === "direct";
+ const canRestartDirectStdinProcess =
+ directStdinRuntime &&
+ input.hasSession &&
+ (state.outstandingToolUses === 0 || input.hasDirectStdinRecoveryEvidence);
+ const canRestartStalledProcess = !supportsStdinNotification || canRestartDirectStdinProcess;
+ if (!canRestartStalledProcess) {
+ return {
+ nextState: state,
+ shouldTerminate: false,
+ alreadyRecovering: false,
+ blockedReason: "runtime_not_restartable",
+ };
+ }
+ if (input.staleForMs < input.staleThresholdMs && !input.runtimeProgressIsStale) {
+ return {
+ nextState: state,
+ shouldTerminate: false,
+ alreadyRecovering: false,
+ blockedReason: "runtime_progress_recent",
+ };
+ }
+ return {
+ nextState: { ...state, expectedTerminationReason: "stalled_recovery" },
+ shouldTerminate: true,
+ alreadyRecovering: false,
+ blockedReason: null,
+ };
+}
+
+export function reduceApmStartupTimeoutTermination(
+ state: ApmGatedSteeringState,
+ input: { hasRuntimeProgressEvent: boolean },
+): { nextState: ApmGatedSteeringState; shouldTerminate: boolean; blockedReason: string | null } {
+ if (input.hasRuntimeProgressEvent) {
+ return { nextState: state, shouldTerminate: false, blockedReason: "runtime_progress_started" };
+ }
+ return {
+ nextState: { ...state, isIdle: false, expectedTerminationReason: "startup_timeout" },
+ shouldTerminate: true,
+ blockedReason: null,
+ };
+}
diff --git a/src/cli/daemon/steering/errorDiagnostics.ts b/src/cli/daemon/steering/errorDiagnostics.ts
new file mode 100644
index 000000000..379d70fc2
--- /dev/null
+++ b/src/cli/daemon/steering/errorDiagnostics.ts
@@ -0,0 +1,237 @@
+/**
+ * Runtime error diagnostics — classify a runtime failure into a stable class
+ * and reason, decide whether it needs user action (re-auth), and build a
+ * scrubbed telemetry envelope.
+ *
+ * Classification priority:
+ * 1. An explicit `XxxError` / `XxxException` token in the message.
+ * 2. HTTP status code (429/401/403/404/5xx/other 4xx).
+ * 3. Text-pattern regexes (rate limit, timeout, connection, …).
+ * 4. Fallback: `RuntimeError`.
+ */
+
+export type ErrorClass =
+ | "RateLimitError"
+ | "AuthError"
+ | "NotFoundError"
+ | "ModelConfigError"
+ | "TimeoutError"
+ | "ProviderConnectionError"
+ | "ProviderStreamError"
+ | "ProviderServerError"
+ | "ProviderApiError"
+ | "RuntimeError";
+
+export type ErrorAction = "retry" | "retry_backoff" | "retry_jitter" | "abort" | "report";
+
+export interface ClassifiedError {
+ errorClass: ErrorClass;
+ action: ErrorAction;
+ reason: string;
+}
+
+const ACTION_BY_CLASS: Record<ErrorClass, ErrorAction> = {
+ RateLimitError: "retry_backoff",
+ AuthError: "abort",
+ NotFoundError: "report",
+ ModelConfigError: "abort",
+ TimeoutError: "retry",
+ ProviderConnectionError: "retry_jitter",
+ ProviderStreamError: "retry",
+ ProviderServerError: "retry",
+ ProviderApiError: "report",
+ RuntimeError: "report",
+};
+
+const EXPLICIT_TOKEN_RE = /\b([A-Z][A-Za-z0-9_]*(?:Error|Exception))\b/;
+
+const EXPLICIT_TOKEN_MAP: Record<string, ErrorClass> = {
+ RateLimitError: "RateLimitError",
+ TooManyRequestsError: "RateLimitError",
+ AuthenticationError: "AuthError",
+ AuthorizationError: "AuthError",
+ PermissionError: "AuthError",
+ NotFoundError: "NotFoundError",
+ ModelNotFoundError: "ModelConfigError",
+ TimeoutError: "TimeoutError",
+ ConnectionError: "ProviderConnectionError",
+ APIConnectionError: "ProviderConnectionError",
+ StreamError: "ProviderStreamError",
+ InternalServerError: "ProviderServerError",
+ APIError: "ProviderApiError",
+ BadRequestError: "ProviderApiError",
+};
+
+export function extractHttpStatus(message: string): number | null {
+ const labeled = /\b(?:HTTP|status(?:\s+code)?|API\s+Error)[:\s]+([45]\d{2})\b/i.exec(message);
+ if (labeled) return Number(labeled[1]);
+ const semantic = /\b([45]\d{2})\s+(?:Unauthorized|Forbidden|Not Found|Too Many Requests|Internal Server Error|Bad Gateway|Service Unavailable|Gateway Timeout)\b/i.exec(
+ message,
+ );
+ return semantic ? Number(semantic[1]) : null;
+}
+
+export const AUTH_ACTION_REQUIRED_PATTERNS: RegExp[] = [
+ /access token could not be refreshed/i,
+ /\btoken_(?:revoked|invalidated)\b/i,
+ /refresh token was already used/i,
+ /access token.*invalidated/i,
+ /authentication token has been invalidated/i,
+ /logged out or signed in to another account/i,
+ /not logged in/i,
+ /not signed in/i,
+ /login required/i,
+ /log in first/i,
+ /please log in/i,
+ /authentication failed/i,
+ /auth(?:entication)? failed/i,
+ /authentication timed out/i,
+ /missing (?:api )?token/i,
+ /no (?:api )?token/i,
+ /missing credentials/i,
+ /credentials? not found/i,
+ /invalid api key/i,
+ /api key (?:is )?not set/i,
+ /token revoked/i,
+ /refresh token expired/i,
+ /session expired/i,
+ /unauthorized/i,
+ /forbidden/i,
+ /invalid.?token/i,
+];
+
+const RATE_LIMIT_PATTERNS = [
+ /too many requests/i,
+ /rate.?limit/i,
+ /quota.?exceeded/i,
+ /overloaded/i,
+];
+
+const MODEL_CONFIG_PATTERNS = [
+ /model.?not.?(?:found|supported|available)/i,
+ /invalid.?model/i,
+ /does not exist/i,
+];
+
+const TIMEOUT_PATTERNS = [
+ /timeout/i,
+ /ETIMEDOUT/,
+ /timed.?out/i,
+ /deadline.?exceeded/i,
+];
+
+const CONNECTION_PATTERNS = [
+ /ECONNREFUSED/,
+ /ECONNRESET/,
+ /ENETUNREACH/,
+ /EHOSTUNREACH/,
+ /EAI_AGAIN/,
+ /ENOTFOUND/,
+ /connection.?refused/i,
+ /connection.?reset/i,
+ /network.?error/i,
+ /Unable to connect to API/i,
+];
+
+const STREAM_PATTERNS = [
+ /stream.?error/i,
+ /stream closed before response/i,
+ /error decoding response body/i,
+ /premature.?close/i,
+ /aborted/i,
+];
+
+const SERVER_PATTERNS = [
+ /internal.?server/i,
+ /bad.?gateway/i,
+ /service.?unavailable/i,
+];
+
+function classifyByExplicitToken(message: string): ErrorClass | null {
+ const match = EXPLICIT_TOKEN_RE.exec(message);
+ if (!match) return null;
+ const token = match[1];
+ return EXPLICIT_TOKEN_MAP[token] ?? null;
+}
+
+function classifyByHttpStatus(httpStatus: number): ErrorClass {
+ if (httpStatus === 429) return "RateLimitError";
+ if (httpStatus === 401 || httpStatus === 403) return "AuthError";
+ if (httpStatus === 404) return "NotFoundError";
+ if (httpStatus >= 500) return "ProviderServerError";
+ return "ProviderApiError";
+}
+
+function classifyByTextPatterns(message: string): ErrorClass | null {
+ for (const pat of RATE_LIMIT_PATTERNS) {
+ if (pat.test(message)) return "RateLimitError";
+ }
+ for (const pat of AUTH_ACTION_REQUIRED_PATTERNS) {
+ if (pat.test(message)) return "AuthError";
+ }
+ for (const pat of MODEL_CONFIG_PATTERNS) {
+ if (pat.test(message)) return "ModelConfigError";
+ }
+ for (const pat of TIMEOUT_PATTERNS) {
+ if (pat.test(message)) return "TimeoutError";
+ }
+ for (const pat of CONNECTION_PATTERNS) {
+ if (pat.test(message)) return "ProviderConnectionError";
+ }
+ for (const pat of STREAM_PATTERNS) {
+ if (pat.test(message)) return "ProviderStreamError";
+ }
+ for (const pat of SERVER_PATTERNS) {
+ if (pat.test(message)) return "ProviderServerError";
+ }
+ return null;
+}
+
+export function classifyRuntimeError(message: string, httpStatus?: number | null): ClassifiedError {
+ // 1. Explicit Error/Exception token
+ const byToken = classifyByExplicitToken(message);
+ if (byToken) {
+ return { errorClass: byToken, action: ACTION_BY_CLASS[byToken], reason: message };
+ }
+
+ // 2. HTTP status code
+ const status = httpStatus ?? extractHttpStatus(message);
+ if (status !== null && status !== undefined) {
+ const cls = classifyByHttpStatus(status);
+ return { errorClass: cls, action: ACTION_BY_CLASS[cls], reason: message };
+ }
+
+ // 3. Text patterns
+ const byPattern = classifyByTextPatterns(message);
+ if (byPattern) {
+ return { errorClass: byPattern, action: ACTION_BY_CLASS[byPattern], reason: message };
+ }
+
+ // 4. Fallback
+ return { errorClass: "RuntimeError", action: "report", reason: message };
+}
+
+/**
+ * Redact sensitive data from diagnostic text for safe logging/telemetry.
+ * Redacts: API tokens, emails, URL credentials, file paths with home dirs.
+ */
+export function scrubDiagnosticText(text: string): string {
+ let scrubbed = text;
+
+ // API tokens
+ scrubbed = scrubbed.replace(/sk-ant-[a-zA-Z0-9_-]+/g, "sk-ant-***");
+ scrubbed = scrubbed.replace(/sk-proj-[a-zA-Z0-9_-]+/g, "sk-proj-***");
+ scrubbed = scrubbed.replace(/sk-[a-zA-Z0-9_-]{20,}/g, "sk-***");
+ scrubbed = scrubbed.replace(/Bearer\s+[a-zA-Z0-9._-]+/gi, "Bearer ***");
+
+ // Email addresses
+ scrubbed = scrubbed.replace(/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g, "***@***.***");
+
+ // URL credentials (user:pass@host)
+ scrubbed = scrubbed.replace(/:\/\/[^:@\s]+:[^@\s]+@/g, "://***:***@");
+
+ // Home directory paths
+ scrubbed = scrubbed.replace(/\/(?:Users|home)\/[a-zA-Z0-9._-]+/g, "/***");
+
+ return scrubbed;
+}
diff --git a/src/cli/daemon/steering/mailbox.ts b/src/cli/daemon/steering/mailbox.ts
new file mode 100644
index 000000000..a22a88ca4
--- /dev/null
+++ b/src/cli/daemon/steering/mailbox.ts
@@ -0,0 +1,224 @@
+/**
+ * Filesystem Mailbox — IPC between daemon and session-runner for steering.
+ *
+ * Protocol:
+ * 1. Daemon atomically writes <seq>.json.tmp → renames to <seq>.json
+ * 2. Session-runner watches inbox via fs.watch() + polling fallback
+ * 3. Session-runner reads file, delivers to agent stdin
+ * 4. Session-runner writes <seq>.ack (or <seq>.nack with reason)
+ * 5. Daemon polls for ack within timeout, falls back on nack/timeout
+ */
+
+import { mkdirSync, writeFileSync, readFileSync, renameSync, readdirSync, unlinkSync, rmSync, existsSync, watch, type FSWatcher } from "fs";
+import { join } from "path";
+import { createLogger } from "../../lib/logger.js";
+
+const log = createLogger({ module: "mailbox" });
+
+export interface SteerMessage {
+ taskId: string;
+ text: string;
+ attachments: { localPath: string; filename: string; contentType: string }[];
+ createdAt: string;
+}
+
+export interface NackPayload {
+ reason: string;
+}
+
+// --- Directory structure helpers ---
+
+export function inboxDir(baseDir: string, contextKey: string): string {
+ const safeKey = contextKey.replace(/[^a-zA-Z0-9_:-]/g, "_");
+ return join(baseDir, ".steering", safeKey, "inbox");
+}
+
+export function ackDir(baseDir: string, contextKey: string): string {
+ const safeKey = contextKey.replace(/[^a-zA-Z0-9_:-]/g, "_");
+ return join(baseDir, ".steering", safeKey, "ack");
+}
+
+export function steeringDir(baseDir: string, contextKey: string): string {
+ const safeKey = contextKey.replace(/[^a-zA-Z0-9_:-]/g, "_");
+ return join(baseDir, ".steering", safeKey);
+}
+
+// --- Daemon side (writer) ---
+
+export function ensureMailboxDirs(baseDir: string, contextKey: string): void {
+ const inbox = inboxDir(baseDir, contextKey);
+ const ack = ackDir(baseDir, contextKey);
+ mkdirSync(inbox, { recursive: true });
+ mkdirSync(ack, { recursive: true });
+}
+
+let seqCounter = 0;
+
+export function writeSteerMessage(baseDir: string, contextKey: string, message: SteerMessage): string {
+ const inbox = inboxDir(baseDir, contextKey);
+ const seq = String(++seqCounter).padStart(6, "0");
+ const tmpPath = join(inbox, `${seq}.json.tmp`);
+ const finalPath = join(inbox, `${seq}.json`);
+ writeFileSync(tmpPath, JSON.stringify(message));
+ renameSync(tmpPath, finalPath);
+ return seq;
+}
+
+export function waitForAck(
+ baseDir: string,
+ contextKey: string,
+ seq: string,
+ timeoutMs: number = 3000,
+): Promise<{ acked: boolean; nackReason?: string }> {
+ const ackPath = join(ackDir(baseDir, contextKey), `${seq}.ack`);
+ const nackPath = join(ackDir(baseDir, contextKey), `${seq}.nack`);
+
+ return new Promise((resolve) => {
+ const deadline = Date.now() + timeoutMs;
+ const pollInterval = 100;
+
+ const check = () => {
+ try {
+ if (existsSync(ackPath)) {
+ resolve({ acked: true });
+ return;
+ }
+ if (existsSync(nackPath)) {
+ let reason = "unknown";
+ try {
+ const content = readFileSync(nackPath, "utf-8");
+ const parsed = JSON.parse(content) as NackPayload;
+ reason = parsed.reason || "unknown";
+ } catch { /* best-effort */ }
+ resolve({ acked: false, nackReason: reason });
+ return;
+ }
+ } catch { /* best-effort */ }
+
+ if (Date.now() >= deadline) {
+ resolve({ acked: false, nackReason: "timeout" });
+ return;
+ }
+ setTimeout(check, pollInterval);
+ };
+ check();
+ });
+}
+
+// --- Session-runner side (reader) ---
+
+export function readSteerMessage(filePath: string): SteerMessage | null {
+ try {
+ const content = readFileSync(filePath, "utf-8");
+ return JSON.parse(content) as SteerMessage;
+ } catch {
+ return null;
+ }
+}
+
+export function writeAck(baseDir: string, contextKey: string, seq: string): void {
+ const ack = ackDir(baseDir, contextKey);
+ mkdirSync(ack, { recursive: true });
+ writeFileSync(join(ack, `${seq}.ack`), "");
+}
+
+export function writeNack(baseDir: string, contextKey: string, seq: string, reason: string): void {
+ const ack = ackDir(baseDir, contextKey);
+ mkdirSync(ack, { recursive: true });
+ writeFileSync(join(ack, `${seq}.nack`), JSON.stringify({ reason }));
+}
+
+export function cleanupInboxFile(baseDir: string, contextKey: string, seq: string): void {
+ try {
+ unlinkSync(join(inboxDir(baseDir, contextKey), `${seq}.json`));
+ } catch { /* best-effort */ }
+}
+
+export function cleanupSteeringDir(baseDir: string, contextKey: string): void {
+ const dir = steeringDir(baseDir, contextKey);
+ try {
+ rmSync(dir, { recursive: true, force: true });
+ } catch { /* best-effort */ }
+}
+
+export interface MailboxWatcher {
+ stop(): void;
+}
+
+/**
+ * Watch the inbox directory for new steer messages.
+ * Calls onMessage for each new .json file detected.
+ * Uses fs.watch + polling fallback for reliability.
+ */
+export function watchInbox(
+ baseDir: string,
+ contextKey: string,
+ onMessage: (seq: string, message: SteerMessage) => void,
+): MailboxWatcher {
+ const inbox = inboxDir(baseDir, contextKey);
+ mkdirSync(inbox, { recursive: true });
+
+ const seen = new Set<string>();
+ let stopped = false;
+
+ const scan = () => {
+ if (stopped) return;
+ try {
+ const files = readdirSync(inbox).filter((f) => f.endsWith(".json") && !f.endsWith(".tmp")).sort();
+ for (const file of files) {
+ if (seen.has(file)) continue;
+ seen.add(file);
+ const seq = file.replace(/\.json$/, "");
+ const msg = readSteerMessage(join(inbox, file));
+ if (msg) {
+ onMessage(seq, msg);
+ }
+ }
+ } catch { /* best-effort */ }
+ };
+
+ // Initial scan for any pre-existing messages
+ scan();
+
+ // fs.watch for real-time detection
+ let watcher: FSWatcher | null = null;
+ try {
+ watcher = watch(inbox, () => {
+ if (!stopped) scan();
+ });
+ } catch {
+ log.debug("fs.watch failed, relying on polling only");
+ }
+
+ // Polling fallback (200ms)
+ const pollTimer = setInterval(scan, 200);
+
+ return {
+ stop() {
+ stopped = true;
+ clearInterval(pollTimer);
+ watcher?.close();
+ },
+ };
+}
+
+// --- Daemon restart: stale message detection ---
+
+export function findStaleInboxMessages(baseDir: string, contextKey: string, maxAgeMs: number = 30_000): string[] {
+ const inbox = inboxDir(baseDir, contextKey);
+ const stale: string[] = [];
+ try {
+ const files = readdirSync(inbox).filter((f) => f.endsWith(".json") && !f.endsWith(".tmp"));
+ const now = Date.now();
+ for (const file of files) {
+ try {
+ const content = readFileSync(join(inbox, file), "utf-8");
+ const msg = JSON.parse(content) as SteerMessage;
+ if (msg.createdAt && now - Date.parse(msg.createdAt) > maxAgeMs) {
+ stale.push(file.replace(/\.json$/, ""));
+ }
+ } catch { /* skip malformed */ }
+ }
+ } catch { /* inbox doesn't exist */ }
+ return stale;
+}
diff --git a/src/cli/daemon/steering/notificationState.ts b/src/cli/daemon/steering/notificationState.ts
new file mode 100644
index 000000000..15e5b98b2
--- /dev/null
+++ b/src/cli/daemon/steering/notificationState.ts
@@ -0,0 +1,129 @@
+/**
+ * RuntimeNotificationState — inbox-notice de-duplication and batching.
+ *
+ * When the daemon injects "you have N unread messages" notices into a running
+ * agent, it must avoid re-sending the same notice set within a session (which
+ * would spam the agent). This tracks a per-(session) fingerprint of the last
+ * notice written, which message identities have already been contributed, and a
+ * one-shot debounce timer for batching bursts.
+ *
+ * Identity priority: positive `seq` → `message_id` → `id`. Fingerprint = sorted,
+ * comma-joined identities. Empty fingerprint ⇒ never a duplicate (fail toward
+ * sending).
+ */
+
+export interface InboxMessageLike {
+ seq?: number;
+ message_id?: string;
+ id?: string;
+}
+
+export function inboxNoticeMessageIdentity(message: InboxMessageLike): string {
+ const seq =
+ typeof message.seq === "number" && Number.isFinite(message.seq) && message.seq > 0
+ ? Math.floor(message.seq)
+ : null;
+ if (seq !== null) return `s:${seq}`;
+ const id =
+ typeof message.message_id === "string" && message.message_id.length > 0
+ ? message.message_id
+ : typeof message.id === "string" && message.id.length > 0
+ ? message.id
+ : "";
+ return id.length > 0 ? `m:${id}` : "";
+}
+
+export function computeInboxNoticeFingerprint(messages: InboxMessageLike[]): string {
+ const keys: string[] = [];
+ for (const m of messages) {
+ const key = inboxNoticeMessageIdentity(m);
+ if (key.length > 0) keys.push(key);
+ }
+ if (keys.length === 0) return "";
+ keys.sort();
+ return keys.join(",");
+}
+
+export class RuntimeNotificationState {
+ private pendingCountValue = 0;
+ private timerValue: ReturnType<typeof setTimeout> | null = null;
+
+ private lastNoticeFingerprint: string | null = null;
+ private lastNoticeSessionId: string | null = null;
+ private lastEncodeFailedFingerprint: string | null = null;
+ private lastEncodeFailedSessionId: string | null = null;
+
+ private contributedIdentities = new Set<string>();
+ private contributionSessionId: string | null = null;
+
+ get pendingCount(): number {
+ return this.pendingCountValue;
+ }
+
+ isDuplicateNotice(fingerprint: string, sessionId: string): boolean {
+ if (fingerprint.length === 0) return false;
+ return this.lastNoticeFingerprint === fingerprint && this.lastNoticeSessionId === sessionId;
+ }
+
+ recordNoticeWritten(fingerprint: string, sessionId: string, messages: InboxMessageLike[] = []): void {
+ this.lastNoticeFingerprint = fingerprint;
+ this.lastNoticeSessionId = sessionId;
+ this.lastEncodeFailedFingerprint = null;
+ this.lastEncodeFailedSessionId = null;
+ this.ensureContributionSession(sessionId);
+ for (const message of messages) {
+ const identity = inboxNoticeMessageIdentity(message);
+ if (identity.length > 0) this.contributedIdentities.add(identity);
+ }
+ }
+
+ recordNoticeEncodeFailed(fingerprint: string, sessionId: string): void {
+ if (fingerprint.length === 0) return;
+ this.lastEncodeFailedFingerprint = fingerprint;
+ this.lastEncodeFailedSessionId = sessionId;
+ }
+
+ isDuplicateEncodeFailedNotice(fingerprint: string, sessionId: string): boolean {
+ if (fingerprint.length === 0) return false;
+ return this.lastEncodeFailedFingerprint === fingerprint && this.lastEncodeFailedSessionId === sessionId;
+ }
+
+ filterUncontributedMessages(messages: InboxMessageLike[], sessionId: string): InboxMessageLike[] {
+ if (this.contributionSessionId !== sessionId) return messages;
+ return messages.filter((m) => {
+ const identity = inboxNoticeMessageIdentity(m);
+ return identity.length === 0 || !this.contributedIdentities.has(identity);
+ });
+ }
+
+ add(count = 1): void {
+ this.pendingCountValue += count;
+ }
+
+ schedule(callback: () => void, delayMs: number): boolean {
+ if (this.timerValue) return false;
+ this.timerValue = setTimeout(() => {
+ this.timerValue = null;
+ callback();
+ }, delayMs);
+ this.timerValue.unref?.();
+ return true;
+ }
+
+ takePendingAndClearTimer(): number {
+ const count = this.pendingCountValue;
+ this.pendingCountValue = 0;
+ if (this.timerValue) {
+ clearTimeout(this.timerValue);
+ this.timerValue = null;
+ }
+ return count;
+ }
+
+ private ensureContributionSession(sessionId: string): void {
+ if (this.contributionSessionId !== sessionId) {
+ this.contributionSessionId = sessionId;
+ this.contributedIdentities = new Set();
+ }
+ }
+}
diff --git a/src/cli/daemon/steering/progressState.ts b/src/cli/daemon/steering/progressState.ts
new file mode 100644
index 000000000..f3e3c41a2
--- /dev/null
+++ b/src/cli/daemon/steering/progressState.ts
@@ -0,0 +1,99 @@
+/**
+ * RuntimeProgressState — granular liveness detection.
+ *
+ * Distinguishes real events (tool_call, text, tool_output, turn_end) from
+ * internal progress (streaming deltas, compaction). Real events reset clock
+ * AND clear stale flag. Internal progress resets clock but does NOT clear stale.
+ * markStale() is idempotent: second call does not reset staleSince.
+ */
+
+import type { ParsedEvent } from "../types.js";
+
+export class RuntimeProgressState {
+ private lastEventAt: number;
+ private lastEventKind: string | null = null;
+ private _staleSince: number | null = null;
+ private _isStale = false;
+
+ constructor(now: number = Date.now()) {
+ this.lastEventAt = now;
+ }
+
+ get isStale(): boolean {
+ return this._isStale;
+ }
+
+ get staleSince(): number | null {
+ return this._staleSince;
+ }
+
+ get lastActivity(): number {
+ return this.lastEventAt;
+ }
+
+ ageMs(nowMs: number = Date.now()): number {
+ return nowMs - this.lastEventAt;
+ }
+
+ /**
+ * Record a real event — resets clock AND clears stale flag.
+ * Real events: text, tool_call, tool_output, turn_end
+ */
+ recordRealEvent(kind: string, now: number = Date.now()): void {
+ this.lastEventAt = now;
+ this.lastEventKind = kind;
+ this._isStale = false;
+ this._staleSince = null;
+ }
+
+ /**
+ * Record internal progress — resets clock but does NOT clear stale flag.
+ * Internal: internal_progress, compaction events, telemetry
+ */
+ recordInternalProgress(kind: string, now: number = Date.now()): void {
+ this.lastEventAt = now;
+ this.lastEventKind = kind;
+ }
+
+ /**
+ * Mark as stale. Idempotent: second call does not reset staleSince.
+ */
+ markStale(now: number = Date.now()): void {
+ if (this._isStale) return;
+ this._isStale = true;
+ this._staleSince = now;
+ }
+
+ /**
+ * Check if the agent should be considered stale given a threshold.
+ */
+ shouldMarkStale(thresholdMs: number, now: number = Date.now()): boolean {
+ if (this._isStale) return false; // already stale
+ return this.ageMs(now) > thresholdMs;
+ }
+
+ /**
+ * Convenience: process a ParsedEvent and record it appropriately.
+ */
+ processEvent(event: ParsedEvent, now: number = Date.now()): void {
+ switch (event.kind) {
+ case "text":
+ case "tool_call":
+ case "tool_output":
+ case "turn_end":
+ case "session_init":
+ case "error":
+ this.recordRealEvent(event.kind, now);
+ break;
+ case "internal_progress":
+ case "compaction_started":
+ case "compaction_finished":
+ case "telemetry":
+ case "thinking":
+ this.recordInternalProgress(event.kind, now);
+ break;
+ default:
+ this.recordInternalProgress(event.kind, now);
+ }
+ }
+}
diff --git a/src/cli/daemon/steering/turnState.ts b/src/cli/daemon/steering/turnState.ts
new file mode 100644
index 000000000..1be99e214
--- /dev/null
+++ b/src/cli/daemon/steering/turnState.ts
@@ -0,0 +1,60 @@
+/**
+ * RuntimeTurnState — the fine-grained steering gate.
+ *
+ * For `busyDeliveryMode: "gated"` runtimes (Claude), the daemon may NOT inject a
+ * busy message at an arbitrary instant: a raw stdin write mid-stream can collide
+ * with an active signed thinking block. This tiny state machine tracks whether
+ * we're currently at a safe point.
+ *
+ * turn starts → gate OPEN (canSteerBusy = true)
+ * tool boundary hit → gate SHUT (hold writes)
+ * progress observed → gate OPEN
+ * turn completes → idle, gate OPEN
+ *
+ * `canSteerBusy` is the single question the delivery path asks before writing.
+ */
+export class RuntimeTurnState {
+ private currentTurnId: string | null = null;
+ private steeringGateActive = false;
+
+ get isInTurn(): boolean {
+ return this.currentTurnId !== null;
+ }
+
+ get turnId(): string | null {
+ return this.currentTurnId;
+ }
+
+ get canSteerBusy(): boolean {
+ return Boolean(this.currentTurnId && !this.steeringGateActive);
+ }
+
+ markTurnStarted(turnId?: string | null): void {
+ if (turnId !== undefined && turnId !== null) {
+ this.currentTurnId = turnId;
+ }
+ this.steeringGateActive = false;
+ }
+
+ adoptTurnId(turnId: string | null): void {
+ this.currentTurnId = turnId;
+ }
+
+ markToolBoundary(): void {
+ this.steeringGateActive = true;
+ }
+
+ markProgress(): void {
+ this.steeringGateActive = false;
+ }
+
+ markTurnCompleted(): void {
+ this.currentTurnId = null;
+ this.steeringGateActive = false;
+ }
+
+ reset(): void {
+ this.currentTurnId = null;
+ this.steeringGateActive = false;
+ }
+}
diff --git a/src/cli/daemon/types.ts b/src/cli/daemon/types.ts
index 04bb157cb..b9760c6c2 100644
--- a/src/cli/daemon/types.ts
+++ b/src/cli/daemon/types.ts
@@ -88,6 +88,7 @@ export interface ExecOptions {
maxTurns?: number;
timeout?: number;
resumeSessionId?: string;
+ steeringEnabled?: boolean;
}
/** Serialized input passed from daemon to the detached session-runner process. */
@@ -103,6 +104,49 @@ export interface SessionRunnerInput {
messageInactivityTimeout: number;
logFilePath?: string;
promptOverride?: string;
+ steeringEnabled?: boolean;
+ steeringMailboxDir?: string;
+}
+
+// --- Steering & ParsedEvent types ---
+
+export type DriverLifecycleKind = "persistent" | "per_turn";
+
+export type BusyDeliveryMode = "gated" | "direct" | "none";
+
+export type StdinMode = "idle" | "busy";
+
+export interface DriverLifecycle {
+ kind: DriverLifecycleKind;
+ stdin?: "gated" | "direct" | "ignore";
+ inFlightWake?: "queue" | "steer" | "coalesce_into_pending";
+}
+
+export interface EncodeOpts {
+ sessionId?: string;
+ threadId?: string;
+ requestId?: number;
+}
+
+export type ParsedEvent =
+ | { kind: "session_init"; sessionId: string }
+ | { kind: "text"; text: string }
+ | { kind: "thinking"; text: string }
+ | { kind: "tool_call"; name: string; input?: unknown; callId?: string }
+ | { kind: "tool_output"; name?: string; callId?: string; output?: string }
+ | { kind: "turn_end"; sessionId?: string }
+ | { kind: "telemetry"; name: string; source?: string; usageKind?: string; attrs: Record<string, unknown> }
+ | { kind: "compaction_started" }
+ | { kind: "compaction_finished" }
+ | { kind: "permission_request"; requestId: string; payload: unknown }
+ | { kind: "error"; message: string }
+ | { kind: "internal_progress"; detail?: string; source?: string; itemType?: string; payloadBytes?: number }
+ | { kind: "log"; content: string; level?: string };
+
+export interface RuntimeSessionDescriptor {
+ lifecycle: DriverLifecycle;
+ busyDeliveryMode: BusyDeliveryMode;
+ supportsStdinNotification: boolean;
}
/** Convert a validated TaskApi (snake_case wire format) to the internal Task type. */
diff --git a/steering-alignment-fixes.md b/steering-alignment-fixes.md
new file mode 100644
index 000000000..d4de6f766
--- /dev/null
+++ b/steering-alignment-fixes.md
@@ -0,0 +1,319 @@
+# Steering Alignment Fixes — Follow-up Dev Plan
+
+## Features / Showcase
+
+Fix alignment gaps between alook's steering implementation and the agent-backends reference. All issues are in the steering-ON path only — steering-OFF (default) is unaffected.
+
+### Before → After
+
+| Issue | Before | After |
+|---|---|---|
+| turnState has no tool boundary gate | Messages can inject mid-thinking block | `canSteerBusy` gate blocks during thinking/tool boundaries |
+| No stalled recovery | Hung agent stays hung forever | Stalled agent detected and terminated after configurable threshold |
+| Notification spam | Every mailbox message sent immediately | Burst batching via debounce timer; session-scoped dedup |
+| Claude missing internal_progress events | `system.status` / `stream_event` silently dropped | Mapped to `internal_progress`, improves liveness detection |
+| Codex missing MCP/reasoning events | MCP tool calls invisible to steering | Mapped to `tool_call` / `thinking` |
+| Weak error classification | No HTTP status extraction, 8 auth patterns | HTTP status detection, 23+ auth patterns, `NotFoundError` class |
+
+---
+
+## Designs Overview
+
+This is a follow-up to the initial steering implementation. All changes are within existing files — no new files needed. The reference source is `agent-backends` at `/Users/gustavoye/Desktop/memodb_w/agent-backends/`.
+
+---
+
+## TODOs
+
+### Prerequisite: Type Updates
+
+- [x] **0.1 Update ParsedEvent type union in types.ts**
+ - Extend `internal_progress` variant: add `source?: string`, `itemType?: string`, `payloadBytes?: number` fields (currently only has `detail?: string`)
+ - Extend `turn_end` variant: add optional `sessionId?: string` field (needed for recovery features)
+ - Add `NotFoundError` to any error class types if referenced in errorDiagnostics
+ - **Files:** `src/cli/daemon/types.ts`
+ - **Acceptance criteria:** ParsedEvent type supports enriched internal_progress and turn_end fields.
+
+### Critical: Steering Gate
+
+- [x] **1.1 Add steering gate to RuntimeTurnState**
+ - Add `steeringGateActive: boolean` private field (default `false`)
+ - Add `canSteerBusy` getter: `return Boolean(this._turnId && !this.steeringGateActive)` — this is the actual injection-safety check
+ - Add `markToolBoundary()`: sets `steeringGateActive = true` — called on `tool_call`, `thinking`, `compaction_started` events (unsafe to inject)
+ - Add `markProgress()`: sets `steeringGateActive = false` — called on `text`, `tool_output`, `compaction_finished` events (safe boundary)
+ - Add `adoptTurnId(turnId)`: updates turn ID without changing gate state
+ - Add `reset()`: clears all state
+ - `markTurnStarted()`: also sets `steeringGateActive = false` (gate open at turn start)
+ - `markTurnCompleted()`: also sets `steeringGateActive = false`
+ - Reference: `agent-backends/src/runtime/turnState.ts` lines 16-62
+ - **Files:** `src/cli/daemon/steering/turnState.ts`
+ - **Acceptance criteria:** `canSteerBusy` returns false during tool boundaries, thinking blocks, and compaction. Returns true at safe points (after tool_output, text). Existing `isInTurn` behavior unchanged.
+
+### Critical: Replace ApmStateMachine with Reference-Aligned Version
+
+The current `apmStateMachine.ts` has a fundamentally different state shape (4 fields) and effect type (`{ type: "flush", messages }`) vs the reference (8 fields, `{ kind: "notify_stdin"|"deliver_stdin", reason, stdinMode, clauseId }`). TODOs below are a coordinated rewrite — not incremental patches.
+
+- [x] **1.2 Rewrite ApmStateMachine to match reference**
+ - **New state shape** — replace `ApmGatedState` (4 fields) with `ApmGatedSteeringState`:
+ ```
+ isIdle: boolean
+ expectedTerminationReason: string | null
+ phase: "idle" | "tool_wait" | "tool_boundary" | "assistant_continuation" | "compacting" | "error"
+ outstandingToolUses: number
+ compacting: boolean
+ toolBoundaryFlushDisabled: boolean (rename from flushDisabled — more precise)
+ lastFlushReason: string | null
+ recentEvents: string[] (capped at 12)
+ pendingMessages: string[] (keep from current)
+ ```
+ - **New effect type** — replace `StdinDeliveryEffect` with:
+ ```
+ { kind: "notify_stdin" | "deliver_stdin"; reason: string; stdinMode: "busy" | "idle"; clauseId: "SMR-002" }
+ ```
+ - **Flush check** — `canFlush()` uses `turnState.canSteerBusy` (not `turnState.isInTurn`). Keep `turnState.isInTurn` for idle-vs-busy mode selection only.
+ - **All reducers to implement:**
+ - `reduceApmIdleState(state, { isIdle })` — track idle/busy
+ - `reduceApmGatedToolUse(state, { kind })` → returns `{ state, hadOutstandingToolUse, shouldFlushToolBatch, effects }`
+ - `reduceApmGatedCompaction(state, { kind })` → handles `compaction_started`, `compaction_finished`, `compaction_interrupted` (interrupted = reset without flush)
+ - `reduceApmGatedAssistantContinuation(state)` → update phase
+ - `reduceApmGatedFlushReadiness(state, { isGated, hasSession, inboxLength, reason })` → central gating decision with structured blockedReason
+ - `reduceApmGatedTurnEnd(state, { inboxLength, supportsStdinNotification, hasSession })` → flush remaining + reset
+ - `reduceApmGatedError(state, { disableToolBoundaryFlush })` → set phase to error, disable flush
+ - `reduceApmGatedFlush(state, { reason })` → record flush reason
+ - `reduceApmGatedRecentEvent(state, { event })` → maintain capped event history
+ - `reduceApmStalledRecoveryTermination(state, input)` → stalled recovery check (input: `inboxLength, staleForMs, staleThresholdMs, runtimeProgressIsStale, hasSession, busyDeliveryMode, hasDirectStdinRecoveryEvidence`)
+ - `reduceApmStartupTimeoutTermination(state, { hasRuntimeProgressEvent })` → startup timeout check
+ - **Keep `reduceApmGatedEnqueue()`** — this is alook-specific (reference doesn't need it because messages are held in notificationState inbox, not in APM state). Adapt to new state shape.
+ - Reference: `agent-backends/src/runtime/apmStateMachine.ts` (full file, 327 lines)
+ - **Files:** `src/cli/daemon/steering/apmStateMachine.ts`
+ - **Acceptance criteria:** All reducer functions implemented with reference-matching logic. Phase tracking works. Stalled recovery returns `shouldTerminate` correctly. Event history capped at 12.
+
+- [x] **1.3 Rewire session-runner for new ApmStateMachine + turnState gate**
+ - This is a coordinated update — ALL existing reducer call sites change shape. Before/after:
+ - `turnState.isInTurn` checks for injection safety → `turnState.canSteerBusy`
+ - `reduceApmGatedToolUse(state, input, turnState)` → `reduceApmGatedToolUse(state, input)` (no turnState arg — gate check moves to `reduceApmGatedFlushReadiness`)
+ - `reduceApmGatedCompaction(state, input, turnState)` → `reduceApmGatedCompaction(state, input)` (same)
+ - `reduceApmGatedEnqueue(state, message, turnState)` → adapt to new state shape
+ - `reduceApmGatedTurnEnd(state)` → `reduceApmGatedTurnEnd(state, { inboxLength, ... })`
+ - Effect handling: `eff.type === "flush"` → `eff.kind === "notify_stdin" | "deliver_stdin"`
+ - **Add turnState gate transitions** in ParsedEvent consumer:
+ - `tool_call` → `turnState.markToolBoundary()` BEFORE reducer
+ - `tool_output` → `turnState.markProgress()` BEFORE reducer
+ - `text` → `turnState.markProgress()`
+ - `thinking` → `turnState.markToolBoundary()`
+ - `compaction_started` → `turnState.markToolBoundary()`
+ - `compaction_finished` → `turnState.markProgress()`
+ - **Add stalled recovery timer:** `setInterval` (30s) checks `reduceApmStalledRecoveryTermination()` with `progressState.ageMs()` and `progressState.isStale`. If `shouldTerminate`, kill agent process.
+ - **Add startup timeout check:** On first progress timer tick, check `reduceApmStartupTimeoutTermination()`. If no progress events received, kill agent.
+ - **Files:** `src/cli/daemon/session-runner.ts`
+ - **Acceptance criteria:** All reducer calls updated to new API. turnState gate transitions wired. Stalled recovery and startup timeout active. No old-API calls remain.
+
+### Critical: Notification State
+
+- [x] **2.1 Add session-scoped dedup + debounce to NotificationState**
+ - Add `sessionId` tracking: `contributedIdentities: Set<string>`, `contributionSessionId: string | null`
+ - `isDuplicateNotice(fingerprint, sessionId)` — 2-part key (fingerprint + sessionId)
+ - `recordNoticeWritten(fingerprint, sessionId, messages)` — track contributed identities per session
+ - `filterUncontributedMessages(messages, sessionId)` — reset tracking on session boundary
+ - Add pending count: `pendingCount` field, `add(count)`, `takePendingAndClearTimer()`
+ - Add debounce timer: `schedule(callback, delayMs)` — one-shot timer for batching bursts
+ - Add encode failure tracking: `recordNoticeEncodeFailed()`, `isDuplicateEncodeFailedNotice()`
+ - Normalize identity: prefix seq with `"s:"`, message_id/id with `"m:"` to prevent collisions between numeric and string IDs
+ - Validate `seq` as finite positive number (not just string)
+ - Reference: `agent-backends/src/runtime/notificationState.ts` lines 47-134
+ - **Files:** `src/cli/daemon/steering/notificationState.ts`
+ - **Acceptance criteria:** Bursts of notifications batched via debounce timer. Session boundary resets contribution tracking. Encode failures cached. Identity normalization prevents collisions.
+
+- [x] **2.2 Update session-runner to use new NotificationState API**
+ - Update mailbox watcher callback to pass `sessionId` to `isDuplicateNotice()` and `markSent()`
+ - Use `schedule()` for debounced delivery instead of immediate
+ - **Files:** `src/cli/daemon/session-runner.ts`
+ - **Acceptance criteria:** Mailbox watcher uses session-scoped dedup and debounced delivery.
+
+### High: Event Mapping Gaps
+
+- [x] **3.1 Claude: add `internal_progress` for system status/stream events**
+ - In `claude.ts` `parseLine()`, `system` case: add mapping for subtypes `"status"` and `"stream_event"` → `{ kind: "internal_progress", source: "system", itemType: subtype }`
+ - Uses the enriched `internal_progress` ParsedEvent variant (from TODO 0.1)
+ - These currently fall through to the `default` case (logged as debug)
+ - Reference: `agent-backends/src/drivers/claudeEventNormalizer.ts` lines 67-74
+ - **Files:** `src/cli/daemon/agent/claude.ts`
+ - **Depends on:** 0.1
+ - **Acceptance criteria:** Claude `system.status` and `system.stream_event` emit `internal_progress` ParsedEvents with source and itemType.
+
+- [x] **3.2 Claude: enrich telemetry + turn_end with sessionId**
+ - In `parseLine()` result case, extract additional fields from `usage`: `cache_creation_input_tokens`, `cache_read_input_tokens`, `service_tier`
+ - Add `cost` and `duration_ms` from `event.cost` and `event.duration_ms` if present
+ - `turn_end` event should carry `sessionId` when available (needed by recovery features in 1.2)
+ - Reference: `agent-backends/src/drivers/claudeEventNormalizer.ts` lines 110-132
+ - **Files:** `src/cli/daemon/agent/claude.ts`
+ - **Depends on:** 0.1
+ - **Acceptance criteria:** Telemetry ParsedEvent includes cache/cost/timing fields. turn_end carries sessionId.
+
+- [x] **3.3 Codex: add MCP, WebSearch, CollabAgent, Reasoning, Compaction events**
+ - In `codex.ts` `parseLine()`, `item/started` case: add mappings for:
+ - `mcpToolCall` → `{ kind: "tool_call", name: "mcp_<toolName>" }`
+ - `webSearch` → `{ kind: "tool_call", name: "web_search" }`
+ - `collabAgentToolCall` → `{ kind: "tool_call", name: "collab_agent" }`
+ - `contextCompaction` → `{ kind: "compaction_started" }`
+ - In `item/completed` case: add mappings for:
+ - `reasoning` → `{ kind: "thinking", text }`
+ - `mcpToolCall` → `{ kind: "tool_output", callId, output }` (MCP tool completion)
+ - `contextCompaction` → `{ kind: "compaction_finished" }`
+ - `agentMessage` text extraction — verify completeness (already partially implemented)
+ - Reference: `agent-backends/src/drivers/codexEventNormalizer.ts` lines 89-125
+ - **Files:** `src/cli/daemon/agent/codex.ts`
+ - **Acceptance criteria:** Codex MCP, web search, collaboration, reasoning, and compaction events all appear as correct ParsedEvents.
+
+- [x] **3.4 Codex: map `item/agentMessage/delta` as text, not internal_progress**
+ - Currently mapped as `{ kind: "internal_progress", detail: delta }` — should be `{ kind: "text", text: delta }` to match agent-backends behavior
+ - Reference: `agent-backends/src/drivers/codexEventNormalizer.ts` — delta events emit `text`
+ - **Files:** `src/cli/daemon/agent/codex.ts` (line ~170)
+ - **Acceptance criteria:** Agent message streaming deltas are `text` events, not `internal_progress`.
+
+### Moderate: Error Diagnostics
+
+- [x] **4.1 Upgrade error classification: HTTP extraction + explicit token detection**
+ - Add `extractHttpStatus(message: string): number | null` function — regex to extract HTTP status codes from labeled ("HTTP 429") and semantic ("status: 401") contexts
+ - Add explicit `Error`/`Exception` token extraction: regex `/\b([A-Z][A-Za-z0-9_]*(?:Error|Exception))\b/` checked FIRST in priority chain
+ - **Change `classifyRuntimeError()` signature** from `(message: string)` to `(message: string, httpStatus?: number | null)`. If httpStatus is not passed, auto-extract via `extractHttpStatus()`.
+ - **Update all callers** of `classifyRuntimeError()` in session-runner.ts
+ - Classification priority: explicit Error/Exception token → HTTP status → text pattern → fallback
+ - HTTP status mappings: 429 → `RateLimitError`, 401/403 → `AuthError`, 404 → `NotFoundError` (new), 5xx → `ProviderServerError`, other 4xx → `ProviderApiError`
+ - Add `NotFoundError` to `ErrorClass` type
+ - **Remove bare numeric patterns** from `RATE_LIMIT_PATTERNS` (`/429/i`), `AUTH_PATTERNS` (`/401/`, `/403/`), and `SERVER_PATTERNS` (`/5\d{2}/`) — these are now handled by HTTP status extraction and would cause double-matching
+ - Reference: `agent-backends/src/runtime/errorDiagnostics.ts` lines 68-100
+ - **Files:** `src/cli/daemon/steering/errorDiagnostics.ts`, `src/cli/daemon/session-runner.ts`
+ - **Acceptance criteria:** HTTP status correctly extracted and classified. Explicit Error tokens detected first. No double-matching from bare numeric patterns. `NotFoundError` class added. Callers updated.
+
+- [x] **4.2 Expand auth patterns to match agent-backends coverage**
+ - Add 15+ additional auth patterns from agent-backends: token revocation, refresh failures, logout states, credential not found, API key missing, etc.
+ - Reference: `agent-backends/src/runtime/errorDiagnostics.ts` lines 41-62 (23+ patterns)
+ - **Files:** `src/cli/daemon/steering/errorDiagnostics.ts`
+ - **Acceptance criteria:** All 23+ auth patterns from agent-backends are covered. Token revocation and refresh failures correctly classified as `AuthError`.
+
+### Moderate: Progress State
+
+- [x] **5.1 Add `ageMs()` to RuntimeProgressState + refactor `shouldMarkStale`**
+ - Add `ageMs(nowMs?: number): number` method — returns milliseconds since last event
+ - Refactor `shouldMarkStale(thresholdMs, now)` to use `ageMs()` internally for consistency
+ - Used by stalled recovery logic (TODO 1.2/1.3)
+ - Reference: `agent-backends/src/runtime/progressState.ts` lines 31-33
+ - **Files:** `src/cli/daemon/steering/progressState.ts`
+ - **Acceptance criteria:** `ageMs()` returns correct elapsed time. `shouldMarkStale` delegates to `ageMs()`.
+
+> **Note:** Phase tracking, event history, `compaction_interrupted`, stalled recovery, and startup timeout are all included in TODO 1.2 (ApmStateMachine rewrite). They are not separate TODOs.
+
+### Tests
+
+- [x] **6.1 Update turnState tests for new gate methods**
+ - Test `canSteerBusy`: false during tool boundary, true after markProgress, false during thinking
+ - Test `markToolBoundary()` → `markProgress()` cycle
+ - Test `adoptTurnId()`, `reset()`
+ - **Files:** `src/cli/daemon/steering/__tests__/turnState.test.ts`
+ - **Acceptance criteria:** All gate transitions tested. `canSteerBusy` correct at each state.
+
+- [x] **6.2 Rewrite apmStateMachine tests for new API**
+ - Test all new reducers: tool use, compaction (including `compaction_interrupted`), flush readiness, turn end, error, stalled recovery, startup timeout
+ - Test phase transitions across reducer calls
+ - Test `reduceApmStalledRecoveryTermination()`: stale + inbox → terminate; not stale → no terminate
+ - Test `reduceApmStartupTimeoutTermination()`: no progress → terminate; has progress → no terminate
+ - Test `canFlush()` uses `canSteerBusy` (not `isInTurn`)
+ - Test `recentEvents` capped at 12
+ - **Files:** `src/cli/daemon/steering/__tests__/apmStateMachine.test.ts`
+ - **Acceptance criteria:** All reducers tested including new ones. Phase transitions verified. Recovery/timeout logic covered.
+
+- [x] **6.3 New notificationState tests for session-scoped dedup + debounce**
+ - Test session boundary resets contribution tracking
+ - Test debounce timer behavior
+ - Test encode failure caching
+ - Test identity normalization (`s:` / `m:` prefixes)
+ - **Files:** `src/cli/daemon/steering/__tests__/notificationState.test.ts` (new file)
+ - **Acceptance criteria:** All new NotificationState features tested.
+
+- [x] **6.4 Update parseLine tests for new event mappings**
+ - Claude: test `system.status` → `internal_progress`, enriched telemetry
+ - Codex: test `mcpToolCall`, `webSearch`, `reasoning`, `agentMessage` delta as `text`
+ - **Files:** `src/cli/daemon/agent/__tests__/claude.parseLine.test.ts`, `src/cli/daemon/agent/__tests__/codex.parseLine.test.ts`
+ - **Acceptance criteria:** All new event mappings have test coverage.
+
+- [x] **6.5 Update error diagnostics tests**
+ - Test HTTP status extraction from various message formats
+ - Test `NotFoundError` classification for 404
+ - Test expanded auth patterns (token revocation, refresh failures)
+ - **Files:** `src/cli/daemon/steering/__tests__/errorDiagnostics.test.ts`
+ - **Acceptance criteria:** All new error classes and patterns tested.
+
+---
+
+## Test Cases
+
+### turnState gate
+- [ ] `canSteerBusy` false when no turn active
+- [ ] `canSteerBusy` true after `markTurnStarted()` (gate open at turn start)
+- [ ] `canSteerBusy` false after `markToolBoundary()` (tool call in flight)
+- [ ] `canSteerBusy` true after `markProgress()` (tool output received)
+- [ ] `canSteerBusy` false after `thinking` event (thinking = gate closed)
+- [ ] `canSteerBusy` false during compaction
+- [ ] Gate reopens after `compaction_finished`
+- [ ] `reset()` clears all state
+
+### Stalled recovery + startup timeout
+- [ ] Agent stale > threshold with inbox messages → `shouldTerminate: true`
+- [ ] Agent stale > threshold with empty inbox → `shouldTerminate: false` (nothing to deliver)
+- [ ] Agent not stale with inbox messages → `shouldTerminate: false`
+- [ ] Startup timeout: no progress events within window → `shouldTerminate: true`
+- [ ] Startup timeout: has progress events → `shouldTerminate: false`
+- [ ] `compaction_interrupted` resets compacting flag without flushing
+
+### Notification dedup
+- [ ] Session boundary resets contribution tracking
+- [ ] Same fingerprint + same sessionId → duplicate
+- [ ] Same fingerprint + different sessionId → not duplicate
+- [ ] Debounce timer batches burst of 3 notifications into 1 delivery
+- [ ] Encode failure cached, not retried
+- [ ] Identity normalization: numeric seq gets `"s:"` prefix
+- [ ] Identity normalization: string id gets `"m:"` prefix
+
+### Event mappings
+- [ ] Claude `system.status` → `internal_progress`
+- [ ] Claude `system.stream_event` → `internal_progress`
+- [ ] Claude telemetry includes `cache_creation_input_tokens`, `cache_read_input_tokens`
+- [ ] Codex `item/started` mcpToolCall → `tool_call` with name `"mcp_<name>"`
+- [ ] Codex `item/started` webSearch → `tool_call` with name `"web_search"`
+- [ ] Codex `item/started` contextCompaction → `compaction_started`
+- [ ] Codex `item/completed` reasoning → `thinking`
+- [ ] Codex `item/completed` mcpToolCall → `tool_output`
+- [ ] Codex `item/completed` contextCompaction → `compaction_finished`
+- [ ] Codex `item/agentMessage/delta` → `text` (not internal_progress)
+- [ ] Claude `turn_end` carries sessionId
+
+### Error diagnostics
+- [ ] "HTTP 429" → extracted status 429 → `RateLimitError`
+- [ ] "status: 401" → extracted status 401 → `AuthError`
+- [ ] "HTTP 404" → extracted status 404 → `NotFoundError`
+- [ ] "token revoked" → `AuthError` (expanded pattern)
+- [ ] "refresh token expired" → `AuthError` (expanded pattern)
+
+---
+
+## New Dependencies
+
+**None.**
+
+---
+
+## Modified Files Summary
+
+```
+src/cli/daemon/steering/turnState.ts ← add gate (canSteerBusy, markToolBoundary, markProgress)
+src/cli/daemon/steering/apmStateMachine.ts ← wire canSteerBusy, add stalled recovery, phase tracking
+src/cli/daemon/steering/notificationState.ts ← session dedup, debounce, encode failure tracking
+src/cli/daemon/steering/progressState.ts ← add ageMs()
+src/cli/daemon/steering/errorDiagnostics.ts ← HTTP extraction, expanded auth patterns, NotFoundError
+src/cli/daemon/agent/claude.ts ← internal_progress mapping, enriched telemetry
+src/cli/daemon/agent/codex.ts ← MCP/reasoning/webSearch mappings, delta as text
+src/cli/daemon/session-runner.ts ← wire gate transitions, stalled recovery timer, new notification API
+src/cli/daemon/steering/__tests__/*.test.ts ← updated tests
+src/cli/daemon/agent/__tests__/*.test.ts ← updated tests
+```