Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

fix: imporve backend support for cli

Gus71ea5d15b616
diff --git a/src/cli/daemon/agent/__tests__/claude.test.ts b/src/cli/daemon/agent/__tests__/claude.test.ts
new file mode 100644
index 000000000..12731df25
--- /dev/null
+++ b/src/cli/daemon/agent/__tests__/claude.test.ts
@@ -0,0 +1,255 @@
+import { describe, it, expect, vi, beforeEach } from "vitest";
+import { EventEmitter } from "events";
+import { Readable } from "stream";
+import type { AgentMessage } from "../../types.js";
+
+let currentMockProc: ReturnType<typeof createMockProc> | null = null;
+
+function createMockProc() {
+ const stdinWrites: string[] = [];
+ const stdout = new Readable({ read() {} });
+ const stderr = new Readable({ read() {} });
+ const proc = Object.assign(new EventEmitter(), {
+ stdout,
+ stderr,
+ stdin: {
+ write: (data: string) => {
+ stdinWrites.push(data);
+ return true;
+ },
+ },
+ kill: vi.fn(),
+ pid: 12345,
+ });
+ return { proc, stdout, stderr, stdinWrites };
+}
+
+vi.mock("child_process", () => ({
+ spawn: vi.fn(() => {
+ currentMockProc = createMockProc();
+ return currentMockProc.proc;
+ }),
+}));
+
+const tick = (ms = 15) => new Promise((r) => setTimeout(r, ms));
+
+async function collectMessages(
+ messages: AsyncIterable<AgentMessage>,
+ maxMessages = 50,
+ timeoutMs = 500,
+): Promise<AgentMessage[]> {
+ const collected: AgentMessage[] = [];
+ const timeout = new Promise<void>((resolve) => setTimeout(resolve, timeoutMs));
+ const iter = messages[Symbol.asyncIterator]();
+ for (let i = 0; i < maxMessages; i++) {
+ const next = iter.next();
+ const result = await Promise.race([next, timeout.then(() => null)]);
+ if (!result || result.done) break;
+ collected.push(result.value);
+ }
+ return collected;
+}
+
+const { ClaudeBackend } = await import("../claude.js");
+
+describe("ClaudeBackend", () => {
+ let backend: InstanceType<typeof ClaudeBackend>;
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ currentMockProc = null;
+ backend = new ClaudeBackend("/usr/bin/claude");
+ });
+
+ function getMock() {
+ return currentMockProc!;
+ }
+
+ it("emits MessageText for assistant text blocks", async () => {
+ const session = backend.execute("hello", { cwd: "/tmp" });
+ const mock = getMock();
+
+ mock.stdout.push(
+ JSON.stringify({
+ type: "assistant",
+ message: { content: [{ type: "text", text: "Hello world" }] },
+ }) + "\n",
+ );
+ await tick();
+ mock.proc.emit("close", 0);
+
+ const messages = await collectMessages(session.messages);
+ expect(messages).toContainEqual({ type: "text", content: "Hello world" });
+ });
+
+ it("emits MessageThinking for thinking blocks", async () => {
+ const session = backend.execute("hello", { cwd: "/tmp" });
+ const mock = getMock();
+
+ mock.stdout.push(
+ JSON.stringify({
+ type: "assistant",
+ message: { content: [{ type: "thinking", text: "Let me think..." }] },
+ }) + "\n",
+ );
+ await tick();
+ mock.proc.emit("close", 0);
+
+ const messages = await collectMessages(session.messages);
+ expect(messages).toContainEqual({ type: "thinking", content: "Let me think..." });
+ });
+
+ it("emits MessageToolUse for tool_use blocks", async () => {
+ const session = backend.execute("hello", { cwd: "/tmp" });
+ const mock = getMock();
+
+ mock.stdout.push(
+ JSON.stringify({
+ type: "assistant",
+ message: {
+ content: [
+ { type: "tool_use", name: "read_file", id: "call_123", input: { path: "/tmp/test.txt" } },
+ ],
+ },
+ }) + "\n",
+ );
+ await tick();
+ mock.proc.emit("close", 0);
+
+ const messages = await collectMessages(session.messages);
+ expect(messages).toContainEqual({
+ type: "tool-use",
+ tool: "read_file",
+ callId: "call_123",
+ input: { path: "/tmp/test.txt" },
+ });
+ });
+
+ it("emits MessageToolResult for tool_result events", async () => {
+ const session = backend.execute("hello", { cwd: "/tmp" });
+ const mock = getMock();
+
+ mock.stdout.push(
+ JSON.stringify({ type: "tool_result", content: "file contents here", tool_use_id: "call_123" }) + "\n",
+ );
+ await tick();
+ mock.proc.emit("close", 0);
+
+ const messages = await collectMessages(session.messages);
+ expect(messages).toContainEqual({
+ type: "tool-result",
+ callId: "call_123",
+ output: "file contents here",
+ });
+ });
+
+ it("writes correct control_request approval format", async () => {
+ const session = backend.execute("hello", { cwd: "/tmp" });
+ const mock = getMock();
+
+ mock.stdout.push(
+ JSON.stringify({
+ type: "control_request",
+ request_id: "req_abc",
+ payload: { input: '{"command":"ls"}' },
+ }) + "\n",
+ );
+ await tick();
+ mock.proc.emit("close", 0);
+
+ await session.result;
+
+ const approvalWrite = mock.stdinWrites.find((w) => w.includes("control_response"));
+ expect(approvalWrite).toBeDefined();
+ const parsed = JSON.parse(approvalWrite!.trim());
+ expect(parsed.type).toBe("control_response");
+ expect(parsed.response.subtype).toBe("success");
+ expect(parsed.response.request_id).toBe("req_abc");
+ expect(parsed.response.response.behavior).toBe("allow");
+ expect(parsed.response.response.updatedInput).toEqual({ command: "ls" });
+ });
+
+ it("does not write approval when request_id is missing", async () => {
+ const session = backend.execute("hello", { cwd: "/tmp" });
+ const mock = getMock();
+
+ mock.stdout.push(JSON.stringify({ type: "control_request" }) + "\n");
+ await tick();
+ mock.proc.emit("close", 0);
+
+ await session.result;
+
+ const approvalWrite = mock.stdinWrites.find((w) => w.includes("control_response"));
+ expect(approvalWrite).toBeUndefined();
+ });
+
+ it("captures session ID from system event (subtype init)", async () => {
+ const session = backend.execute("hello", { cwd: "/tmp" });
+ const mock = getMock();
+
+ mock.stdout.push(
+ JSON.stringify({ type: "system", subtype: "init", session_id: "sess_123" }) + "\n",
+ );
+ await tick();
+ mock.proc.emit("close", 0);
+
+ const result = await session.result;
+ expect(result.sessionId).toBe("sess_123");
+ });
+
+ it("captures session ID from result event", async () => {
+ const session = backend.execute("hello", { cwd: "/tmp" });
+ const mock = getMock();
+
+ mock.stdout.push(
+ JSON.stringify({ type: "result", result: "done", session_id: "sess_456" }) + "\n",
+ );
+ await tick();
+ mock.proc.emit("close", 0);
+
+ const result = await session.result;
+ expect(result.sessionId).toBe("sess_456");
+ });
+
+ it("sets status to failed when result event has is_error", async () => {
+ const session = backend.execute("hello", { cwd: "/tmp" });
+ const mock = getMock();
+
+ mock.stdout.push(
+ JSON.stringify({ type: "result", result: "something went wrong", is_error: true }) + "\n",
+ );
+ await tick();
+ mock.proc.emit("close", 0);
+
+ const result = await session.result;
+ expect(result.status).toBe("failed");
+ expect(result.error).toBe("something went wrong");
+ });
+
+ it("handles invalid JSON gracefully", async () => {
+ const session = backend.execute("hello", { cwd: "/tmp" });
+ const mock = getMock();
+
+ mock.stdout.push("not json at all\n");
+ await tick();
+ mock.proc.emit("close", 0);
+
+ const messages = await collectMessages(session.messages);
+ expect(messages).toContainEqual({ type: "log", content: "not json at all", level: "debug" });
+ });
+
+ it("sets status to timeout when process is killed by timeout", async () => {
+ vi.useFakeTimers();
+ const session = backend.execute("hello", { cwd: "/tmp", timeout: 1000 });
+ const mock = getMock();
+
+ vi.advanceTimersByTime(1000);
+ expect(mock.proc.kill).toHaveBeenCalledWith("SIGTERM");
+
+ mock.proc.emit("close", null);
+
+ const result = await session.result;
+ expect(result.status).toBe("timeout");
+ vi.useRealTimers();
+ });
+});
diff --git a/src/cli/daemon/agent/__tests__/codex.test.ts b/src/cli/daemon/agent/__tests__/codex.test.ts
new file mode 100644
index 000000000..68aec9e43
--- /dev/null
+++ b/src/cli/daemon/agent/__tests__/codex.test.ts
@@ -0,0 +1,619 @@
+import { describe, it, expect, vi, beforeEach } from "vitest";
+import { EventEmitter } from "events";
+import { Readable } from "stream";
+import type { AgentMessage } from "../../types.js";
+
+let currentMockProc: ReturnType<typeof createMockProc> | null = null;
+
+function createMockProc() {
+ const stdinWrites: string[] = [];
+ const stdout = new Readable({ read() {} });
+ const stderr = new Readable({ read() {} });
+ const proc = Object.assign(new EventEmitter(), {
+ stdout,
+ stderr,
+ stdin: {
+ write: (data: string) => {
+ stdinWrites.push(data);
+ return true;
+ },
+ },
+ kill: vi.fn(),
+ pid: 12345,
+ });
+ return { proc, stdout, stderr, stdinWrites };
+}
+
+vi.mock("child_process", () => ({
+ spawn: vi.fn(() => {
+ currentMockProc = createMockProc();
+ return currentMockProc.proc;
+ }),
+}));
+
+async function collectMessages(
+ messages: AsyncIterable<AgentMessage>,
+ maxMessages = 100,
+ timeoutMs = 500,
+): Promise<AgentMessage[]> {
+ const collected: AgentMessage[] = [];
+ const timeout = new Promise<void>((resolve) => setTimeout(resolve, timeoutMs));
+ const iter = messages[Symbol.asyncIterator]();
+ for (let i = 0; i < maxMessages; i++) {
+ const next = iter.next();
+ const result = await Promise.race([next, timeout.then(() => null)]);
+ if (!result || result.done) break;
+ collected.push(result.value);
+ }
+ return collected;
+}
+
+const { CodexBackend, extractThreadID, nilIfEmpty } = await import("../codex.js");
+
+function getMock() {
+ return currentMockProc!;
+}
+
+function sendResponse(id: number, result: unknown) {
+ getMock().stdout.push(JSON.stringify({ jsonrpc: "2.0", id, result }) + "\n");
+}
+
+function sendError(id: number, error: { code: number; message: string }) {
+ getMock().stdout.push(JSON.stringify({ jsonrpc: "2.0", id, error }) + "\n");
+}
+
+function sendNotification(method: string, params?: Record<string, unknown>) {
+ const msg: Record<string, unknown> = { jsonrpc: "2.0", method };
+ if (params) msg.params = params;
+ getMock().stdout.push(JSON.stringify(msg) + "\n");
+}
+
+function sendServerRequest(id: number, method: string, params?: Record<string, unknown>) {
+ const msg: Record<string, unknown> = { jsonrpc: "2.0", id, method };
+ if (params) msg.params = params;
+ getMock().stdout.push(JSON.stringify(msg) + "\n");
+}
+
+async function completeHandshake(threadId = "thread_abc") {
+ await tick();
+ sendResponse(1, { capabilities: {} }); // initialize response
+ await tick();
+ sendResponse(2, { thread: { id: threadId } }); // thread/start response
+ await tick();
+ sendResponse(3, {}); // turn/start response
+ await tick();
+}
+
+function tick(ms = 15) {
+ return new Promise((r) => setTimeout(r, ms));
+}
+
+describe("extractThreadID", () => {
+ it("extracts from nested response", () => {
+ expect(extractThreadID({ result: { thread: { id: "t_1" } } })).toBe("t_1");
+ });
+
+ it("extracts from flat thread object", () => {
+ expect(extractThreadID({ thread: { id: "t_2" } })).toBe("t_2");
+ });
+
+ it("returns empty string when missing", () => {
+ expect(extractThreadID(null)).toBe("");
+ expect(extractThreadID({})).toBe("");
+ expect(extractThreadID({ thread: {} })).toBe("");
+ });
+});
+
+describe("nilIfEmpty", () => {
+ it("returns undefined for empty/null", () => {
+ expect(nilIfEmpty("")).toBeUndefined();
+ expect(nilIfEmpty(null)).toBeUndefined();
+ expect(nilIfEmpty(undefined)).toBeUndefined();
+ });
+
+ it("returns string when non-empty", () => {
+ expect(nilIfEmpty("hello")).toBe("hello");
+ });
+});
+
+describe("CodexBackend", () => {
+ let backend: InstanceType<typeof CodexBackend>;
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ currentMockProc = null;
+ backend = new CodexBackend("/usr/bin/codex");
+ });
+
+ it("sends structured initialize params", async () => {
+ const session = backend.execute("hello", { cwd: "/tmp" });
+ const mock = getMock();
+
+ await tick();
+
+ const initWrite = mock.stdinWrites.find((w) => w.includes('"initialize"'));
+ expect(initWrite).toBeDefined();
+ const parsed = JSON.parse(initWrite!);
+ expect(parsed.params.clientInfo.name).toBe("alook-daemon");
+ expect(parsed.params.clientInfo.title).toBe("Alook Agent SDK");
+ expect(parsed.params.capabilities.experimentalApi).toBe(true);
+ expect(parsed.id).toBe(1);
+
+ mock.proc.emit("close", 1);
+ await session.result;
+ });
+
+ it("sends initialized notification after initialize response", async () => {
+ const session = backend.execute("hello", { cwd: "/tmp" });
+ const mock = getMock();
+
+ await tick();
+ sendResponse(1, { capabilities: {} });
+ await tick();
+
+ const initializedWrite = mock.stdinWrites.find((w) => w.includes('"initialized"'));
+ expect(initializedWrite).toBeDefined();
+ const parsed = JSON.parse(initializedWrite!);
+ expect(parsed.method).toBe("initialized");
+ expect(parsed.id).toBeUndefined();
+
+ mock.proc.emit("close", 1);
+ await session.result;
+ });
+
+ it("thread/start includes correct params (no prompt)", async () => {
+ const session = backend.execute("hello", {
+ cwd: "/tmp",
+ systemPrompt: "You are helpful",
+ model: "gpt-4",
+ });
+ const mock = getMock();
+
+ await tick();
+ sendResponse(1, {});
+ await tick(30);
+
+ const threadWrite = mock.stdinWrites.find((w) => w.includes('"thread/start"'));
+ expect(threadWrite).toBeDefined();
+ const parsed = JSON.parse(threadWrite!);
+ expect(parsed.params.cwd).toBe("/tmp");
+ expect(parsed.params.sandbox).toBe("workspace-write");
+ expect(parsed.params.persistExtendedHistory).toBe(true);
+ expect(parsed.params.experimentalRawEvents).toBe(false);
+ expect(parsed.params.developerInstructions).toBe("You are helpful");
+ expect(parsed.params.model).toBe("gpt-4");
+ expect(parsed.params.instructions).toBeUndefined();
+
+ mock.proc.emit("close", 1);
+ await session.result;
+ });
+
+ it("turn/start RPC sent with threadId and prompt", async () => {
+ const session = backend.execute("do stuff", { cwd: "/tmp" });
+ const mock = getMock();
+
+ await completeHandshake("thread_xyz");
+
+ const turnWrite = mock.stdinWrites.find((w) => w.includes('"turn/start"'));
+ expect(turnWrite).toBeDefined();
+ const parsed = JSON.parse(turnWrite!);
+ expect(parsed.params.threadId).toBe("thread_xyz");
+ expect(parsed.params.input).toEqual([{ type: "text", text: "do stuff" }]);
+
+ mock.proc.emit("close", 0);
+ await session.result;
+ });
+
+ it("extracts session ID from thread/start response", async () => {
+ const session = backend.execute("hello", { cwd: "/tmp" });
+ const mock = getMock();
+
+ await completeHandshake("my_thread_id");
+ mock.proc.emit("close", 0);
+
+ const result = await session.result;
+ expect(result.sessionId).toBe("my_thread_id");
+ });
+
+ it("JSON-RPC error response rejects pending request", async () => {
+ const session = backend.execute("hello", { cwd: "/tmp" });
+ const mock = getMock();
+
+ await tick();
+ sendError(1, { code: -1, message: "init failed" });
+ await tick(30);
+
+ mock.proc.emit("close", 1);
+
+ const result = await session.result;
+ expect(result.status).toBe("failed");
+ expect(result.error).toContain("init failed");
+ });
+
+ it("JSON-RPC error response (id + error, no method) routed to response resolution", async () => {
+ const session = backend.execute("hello", { cwd: "/tmp" });
+ const mock = getMock();
+
+ await tick();
+ // Send error response — should NOT go to notification handler
+ sendError(1, { code: -32600, message: "bad request" });
+ await tick(30);
+
+ mock.proc.emit("close", 1);
+ const result = await session.result;
+ expect(result.error).toContain("bad request");
+ });
+
+ it("routes server requests (id + method) to handleServerRequest", async () => {
+ const session = backend.execute("hello", { cwd: "/tmp" });
+ const mock = getMock();
+
+ await completeHandshake();
+ sendServerRequest(99, "item/commandExecution/requestApproval", {});
+ await tick();
+
+ const resp = mock.stdinWrites.find((w) => w.includes('"id":99') && w.includes('"decision"'));
+ expect(resp).toBeDefined();
+ expect(JSON.parse(resp!).result.decision).toBe("accept");
+
+ mock.proc.emit("close", 0);
+ await session.result;
+ });
+
+ it("sends {decision: accept} for item/fileChange/requestApproval", async () => {
+ const session = backend.execute("hello", { cwd: "/tmp" });
+ const mock = getMock();
+
+ await completeHandshake();
+ sendServerRequest(100, "item/fileChange/requestApproval", {});
+ await tick();
+
+ const resp = mock.stdinWrites.find((w) => w.includes('"id":100'));
+ expect(JSON.parse(resp!).result.decision).toBe("accept");
+
+ mock.proc.emit("close", 0);
+ await session.result;
+ });
+
+ it("sends {decision: accept} for execCommandApproval", async () => {
+ const session = backend.execute("hello", { cwd: "/tmp" });
+ const mock = getMock();
+
+ await completeHandshake();
+ sendServerRequest(101, "execCommandApproval", {});
+ await tick();
+
+ const resp = mock.stdinWrites.find((w) => w.includes('"id":101'));
+ expect(JSON.parse(resp!).result.decision).toBe("accept");
+
+ mock.proc.emit("close", 0);
+ await session.result;
+ });
+
+ it("sends {decision: accept} for applyPatchApproval", async () => {
+ const session = backend.execute("hello", { cwd: "/tmp" });
+ const mock = getMock();
+
+ await completeHandshake();
+ sendServerRequest(102, "applyPatchApproval", {});
+ await tick();
+
+ const resp = mock.stdinWrites.find((w) => w.includes('"id":102'));
+ expect(JSON.parse(resp!).result.decision).toBe("accept");
+
+ mock.proc.emit("close", 0);
+ await session.result;
+ });
+
+ it("sends empty {} for unknown server requests", async () => {
+ const session = backend.execute("hello", { cwd: "/tmp" });
+ const mock = getMock();
+
+ await completeHandshake();
+ sendServerRequest(200, "unknown/method", {});
+ await tick();
+
+ const resp = mock.stdinWrites.find((w) => w.includes('"id":200'));
+ expect(resp).toBeDefined();
+ expect(JSON.parse(resp!).result).toEqual({});
+
+ mock.proc.emit("close", 0);
+ await session.result;
+ });
+
+ // Legacy protocol tests
+ it("legacy codex/event — task_started emits status running", async () => {
+ const session = backend.execute("hello", { cwd: "/tmp" });
+ const mock = getMock();
+
+ await completeHandshake();
+ sendNotification("codex/event", { type: "task_started" });
+ mock.proc.emit("close", 0);
+
+ const messages = await collectMessages(session.messages);
+ expect(messages).toContainEqual({ type: "status", status: "running" });
+ });
+
+ it("legacy codex/event — agent_message emits MessageText", async () => {
+ const session = backend.execute("hello", { cwd: "/tmp" });
+ const mock = getMock();
+
+ await completeHandshake();
+ sendNotification("codex/event", { type: "agent_message", text: "I found the issue" });
+ mock.proc.emit("close", 0);
+
+ const messages = await collectMessages(session.messages);
+ expect(messages).toContainEqual({ type: "text", content: "I found the issue" });
+ });
+
+ it("legacy codex/event — exec_command_begin/end emits tool-use + tool-result", async () => {
+ const session = backend.execute("hello", { cwd: "/tmp" });
+ const mock = getMock();
+
+ await completeHandshake();
+ sendNotification("codex/event", { type: "exec_command_begin", id: "cmd_1", command: "ls" });
+ sendNotification("codex/event", { type: "exec_command_end", id: "cmd_1", output: "total 0" });
+ mock.proc.emit("close", 0);
+
+ const messages = await collectMessages(session.messages);
+ expect(messages).toContainEqual(
+ expect.objectContaining({ type: "tool-use", tool: "exec_command", callId: "cmd_1" }),
+ );
+ expect(messages).toContainEqual(
+ expect.objectContaining({ type: "tool-result", callId: "cmd_1", output: "total 0" }),
+ );
+ });
+
+ it("legacy codex/event — patch_apply_begin/end emits tool-use + tool-result", async () => {
+ const session = backend.execute("hello", { cwd: "/tmp" });
+ const mock = getMock();
+
+ await completeHandshake();
+ sendNotification("codex/event", { type: "patch_apply_begin", id: "patch_1" });
+ sendNotification("codex/event", { type: "patch_apply_end", id: "patch_1", output: "applied" });
+ mock.proc.emit("close", 0);
+
+ const messages = await collectMessages(session.messages);
+ expect(messages).toContainEqual(
+ expect.objectContaining({ type: "tool-use", tool: "patch_apply", callId: "patch_1" }),
+ );
+ expect(messages).toContainEqual(
+ expect.objectContaining({ type: "tool-result", callId: "patch_1", output: "applied" }),
+ );
+ });
+
+ it("legacy codex/event — task_complete triggers turn done (not aborted)", async () => {
+ const session = backend.execute("hello", { cwd: "/tmp" });
+ const mock = getMock();
+
+ await completeHandshake();
+ sendNotification("codex/event", { type: "task_complete", output: "all done" });
+ mock.proc.emit("close", 0);
+
+ const result = await session.result;
+ expect(result.status).toBe("completed");
+ expect(result.output).toBe("all done");
+ });
+
+ it("legacy codex/event — turn_aborted triggers aborted", async () => {
+ const session = backend.execute("hello", { cwd: "/tmp" });
+ const mock = getMock();
+
+ await completeHandshake();
+ sendNotification("codex/event", { type: "turn_aborted" });
+ mock.proc.emit("close", 0);
+
+ const result = await session.result;
+ expect(result.status).toBe("aborted");
+ });
+
+ // Raw protocol tests
+ it("raw protocol — turn/started sets status and captures turnId", async () => {
+ const session = backend.execute("hello", { cwd: "/tmp" });
+ const mock = getMock();
+
+ await completeHandshake();
+ sendNotification("turn/started", { turnId: "turn_1" });
+ mock.proc.emit("close", 0);
+
+ const messages = await collectMessages(session.messages);
+ expect(messages).toContainEqual({ type: "status", status: "turn_start" });
+ });
+
+ it("raw protocol — turn/completed with completed triggers turn done", async () => {
+ const session = backend.execute("hello", { cwd: "/tmp" });
+ const mock = getMock();
+
+ await completeHandshake();
+ sendNotification("turn/completed", { turnId: "turn_1", status: "completed" });
+ mock.proc.emit("close", 0);
+
+ const result = await session.result;
+ expect(result.status).toBe("completed");
+ });
+
+ it("raw protocol — turn/completed with cancelled triggers aborted", async () => {
+ const session = backend.execute("hello", { cwd: "/tmp" });
+ const mock = getMock();
+
+ await completeHandshake();
+ sendNotification("turn/completed", { turnId: "turn_1", status: "cancelled" });
+ mock.proc.emit("close", 0);
+
+ const result = await session.result;
+ expect(result.status).toBe("aborted");
+ });
+
+ it("raw protocol — duplicate turn/completed for same turnId is deduplicated", async () => {
+ const session = backend.execute("hello", { cwd: "/tmp" });
+ const mock = getMock();
+
+ await completeHandshake();
+ sendNotification("turn/completed", { turnId: "turn_1", status: "completed" });
+ sendNotification("turn/completed", { turnId: "turn_1", status: "failed", output: "should not override" });
+ mock.proc.emit("close", 0);
+
+ const result = await session.result;
+ expect(result.status).toBe("completed");
+ });
+
+ it("raw protocol — item/started (commandExecution) emits tool-use", async () => {
+ const session = backend.execute("hello", { cwd: "/tmp" });
+ const mock = getMock();
+
+ await completeHandshake();
+ sendNotification("item/started", {
+ item: { type: "commandExecution", id: "cmd_1", command: "ls" },
+ });
+ mock.proc.emit("close", 0);
+
+ const messages = await collectMessages(session.messages);
+ expect(messages).toContainEqual(
+ expect.objectContaining({ type: "tool-use", tool: "exec_command", callId: "cmd_1" }),
+ );
+ });
+
+ it("raw protocol — item/completed (commandExecution) emits tool-result with aggregatedOutput", async () => {
+ const session = backend.execute("hello", { cwd: "/tmp" });
+ const mock = getMock();
+
+ await completeHandshake();
+ sendNotification("item/completed", {
+ item: { type: "commandExecution", id: "cmd_1", aggregatedOutput: "total 0\n" },
+ });
+ mock.proc.emit("close", 0);
+
+ const messages = await collectMessages(session.messages);
+ expect(messages).toContainEqual(
+ expect.objectContaining({ type: "tool-result", callId: "cmd_1", output: "total 0\n" }),
+ );
+ });
+
+ it("raw protocol — item/started (fileChange) emits tool-use patch_apply", async () => {
+ const session = backend.execute("hello", { cwd: "/tmp" });
+ const mock = getMock();
+
+ await completeHandshake();
+ sendNotification("item/started", { item: { type: "fileChange", id: "fc_1" } });
+ mock.proc.emit("close", 0);
+
+ const messages = await collectMessages(session.messages);
+ expect(messages).toContainEqual(
+ expect.objectContaining({ type: "tool-use", tool: "patch_apply", callId: "fc_1" }),
+ );
+ });
+
+ it("raw protocol — item/completed (fileChange) emits tool-result", async () => {
+ const session = backend.execute("hello", { cwd: "/tmp" });
+ const mock = getMock();
+
+ await completeHandshake();
+ sendNotification("item/completed", { item: { type: "fileChange", id: "fc_1" } });
+ mock.proc.emit("close", 0);
+
+ const messages = await collectMessages(session.messages);
+ expect(messages).toContainEqual(
+ expect.objectContaining({ type: "tool-result", callId: "fc_1", output: "" }),
+ );
+ });
+
+ it("raw protocol — item/completed (agentMessage, phase=final_answer) emits text + turn done", async () => {
+ const session = backend.execute("hello", { cwd: "/tmp" });
+ const mock = getMock();
+
+ await completeHandshake();
+ sendNotification("item/completed", {
+ item: {
+ type: "agentMessage",
+ phase: "final_answer",
+ content: [{ type: "text", text: "Here is the answer" }],
+ },
+ });
+ mock.proc.emit("close", 0);
+
+ const messages = await collectMessages(session.messages);
+ expect(messages).toContainEqual({ type: "text", content: "Here is the answer" });
+ });
+
+ it("raw protocol — thread/status/changed (idle) triggers turn done", async () => {
+ const session = backend.execute("hello", { cwd: "/tmp" });
+ const mock = getMock();
+
+ await completeHandshake();
+ sendNotification("turn/started", { turnId: "turn_1" });
+ sendNotification("thread/status/changed", { status: "idle" });
+ mock.proc.emit("close", 0);
+
+ const result = await session.result;
+ expect(result.status).toBe("completed");
+ });
+
+ // Protocol detection / locking
+ it("first legacy event locks protocol to legacy", async () => {
+ const session = backend.execute("hello", { cwd: "/tmp" });
+ const mock = getMock();
+
+ await completeHandshake();
+ sendNotification("codex/event", { type: "task_started" });
+ sendNotification("turn/started", { turnId: "turn_1" });
+ mock.proc.emit("close", 0);
+
+ const messages = await collectMessages(session.messages);
+ expect(messages).toContainEqual({ type: "status", status: "running" });
+ expect(messages).not.toContainEqual({ type: "status", status: "turn_start" });
+ });
+
+ it("first raw event locks protocol to raw", async () => {
+ const session = backend.execute("hello", { cwd: "/tmp" });
+ const mock = getMock();
+
+ await completeHandshake();
+ sendNotification("turn/started", { turnId: "turn_1" });
+ sendNotification("codex/event", { type: "agent_message", text: "ignored" });
+ mock.proc.emit("close", 0);
+
+ const messages = await collectMessages(session.messages);
+ expect(messages).toContainEqual({ type: "status", status: "turn_start" });
+ expect(messages).not.toContainEqual({ type: "text", content: "ignored" });
+ });
+
+ it("handles invalid JSON gracefully", async () => {
+ const session = backend.execute("hello", { cwd: "/tmp" });
+ const mock = getMock();
+
+ mock.stdout.push("not valid json\n");
+ await tick();
+ mock.proc.emit("close", 1);
+
+ const messages = await collectMessages(session.messages);
+ expect(messages).toContainEqual({ type: "log", content: "not valid json", level: "debug" });
+ });
+
+ it("closeAllPending sends error to all pending RPC callbacks on process close", async () => {
+ const session = backend.execute("hello", { cwd: "/tmp" });
+ const mock = getMock();
+
+ // Don't respond to initialize — let process close while it's pending
+ await tick(30);
+ mock.proc.emit("close", 1);
+
+ const result = await session.result;
+ // Process exiting with code 1 without responding sets failed status
+ expect(result.status).toBe("failed");
+ });
+
+ it("timeout kills process and sets status to timeout", async () => {
+ vi.useFakeTimers();
+ const session = backend.execute("hello", { cwd: "/tmp", timeout: 5000 });
+ const mock = getMock();
+
+ vi.advanceTimersByTime(5000);
+ expect(mock.proc.kill).toHaveBeenCalledWith("SIGTERM");
+
+ mock.proc.emit("close", null);
+
+ const result = await session.result;
+ expect(result.status).toBe("timeout");
+ vi.useRealTimers();
+ });
+});
diff --git a/src/cli/daemon/agent/__tests__/index.test.ts b/src/cli/daemon/agent/__tests__/index.test.ts
new file mode 100644
index 000000000..45116bc30
--- /dev/null
+++ b/src/cli/daemon/agent/__tests__/index.test.ts
@@ -0,0 +1,31 @@
+import { describe, it, expect } from "vitest";
+import { createBackend } from "../index.js";
+import { ClaudeBackend } from "../claude.js";
+import { CodexBackend } from "../codex.js";
+import { OpenCodeBackend } from "../opencode.js";
+
+describe("createBackend", () => {
+ it('returns ClaudeBackend for "claude"', () => {
+ const backend = createBackend("claude", "/usr/bin/claude");
+ expect(backend).toBeInstanceOf(ClaudeBackend);
+ expect(backend.name).toBe("claude");
+ });
+
+ it('returns CodexBackend for "codex"', () => {
+ const backend = createBackend("codex", "/usr/bin/codex");
+ expect(backend).toBeInstanceOf(CodexBackend);
+ expect(backend.name).toBe("codex");
+ });
+
+ it('returns OpenCodeBackend for "opencode"', () => {
+ const backend = createBackend("opencode", "/usr/bin/opencode");
+ expect(backend).toBeInstanceOf(OpenCodeBackend);
+ expect(backend.name).toBe("opencode");
+ });
+
+ it("throws for unknown provider", () => {
+ expect(() => createBackend("unknown", "/usr/bin/unknown")).toThrow(
+ "Unknown provider: unknown",
+ );
+ });
+});
diff --git a/src/cli/daemon/agent/__tests__/opencode.test.ts b/src/cli/daemon/agent/__tests__/opencode.test.ts
new file mode 100644
index 000000000..324482137
--- /dev/null
+++ b/src/cli/daemon/agent/__tests__/opencode.test.ts
@@ -0,0 +1,277 @@
+import { describe, it, expect, vi, beforeEach } from "vitest";
+import { EventEmitter } from "events";
+import { Readable } from "stream";
+import type { AgentMessage } from "../../types.js";
+
+let currentMockProc: ReturnType<typeof createMockProc> | null = null;
+let lastSpawnArgs: { cmd: string; args: string[]; opts: Record<string, unknown> } | null = null;
+
+function createMockProc() {
+ const stdinWrites: string[] = [];
+ const stdout = new Readable({ read() {} });
+ const stderr = new Readable({ read() {} });
+ const proc = Object.assign(new EventEmitter(), {
+ stdout,
+ stderr,
+ stdin: {
+ write: (data: string) => {
+ stdinWrites.push(data);
+ return true;
+ },
+ },
+ kill: vi.fn(),
+ pid: 12345,
+ });
+ return { proc, stdout, stderr, stdinWrites };
+}
+
+vi.mock("child_process", () => ({
+ spawn: vi.fn((cmd: string, args: string[], opts: Record<string, unknown>) => {
+ lastSpawnArgs = { cmd, args, opts };
+ currentMockProc = createMockProc();
+ return currentMockProc.proc;
+ }),
+}));
+
+const tick = (ms = 15) => new Promise((r) => setTimeout(r, ms));
+
+async function collectMessages(
+ messages: AsyncIterable<AgentMessage>,
+ maxMessages = 50,
+ timeoutMs = 500,
+): Promise<AgentMessage[]> {
+ const collected: AgentMessage[] = [];
+ const timeout = new Promise<void>((resolve) => setTimeout(resolve, timeoutMs));
+ const iter = messages[Symbol.asyncIterator]();
+ for (let i = 0; i < maxMessages; i++) {
+ const next = iter.next();
+ const result = await Promise.race([next, timeout.then(() => null)]);
+ if (!result || result.done) break;
+ collected.push(result.value);
+ }
+ return collected;
+}
+
+const { OpenCodeBackend } = await import("../opencode.js");
+
+function getMock() {
+ return currentMockProc!;
+}
+
+describe("OpenCodeBackend", () => {
+ let backend: InstanceType<typeof OpenCodeBackend>;
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ currentMockProc = null;
+ lastSpawnArgs = null;
+ backend = new OpenCodeBackend("/usr/bin/opencode");
+ });
+
+ it("emits MessageText for assistant message events", async () => {
+ const session = backend.execute("hello", { cwd: "/tmp" });
+ const mock = getMock();
+
+ mock.stdout.push(JSON.stringify({ type: "message", role: "assistant", content: "Hi there" }) + "\n");
+ await tick();
+ mock.proc.emit("close", 0);
+
+ const messages = await collectMessages(session.messages);
+ expect(messages).toContainEqual({ type: "text", content: "Hi there" });
+ });
+
+ it("does not emit for empty message content", async () => {
+ const session = backend.execute("hello", { cwd: "/tmp" });
+ const mock = getMock();
+
+ mock.stdout.push(JSON.stringify({ type: "message", role: "assistant", content: "" }) + "\n");
+ await tick();
+ mock.proc.emit("close", 0);
+
+ const messages = await collectMessages(session.messages);
+ const textMessages = messages.filter((m) => m.type === "text");
+ expect(textMessages).toHaveLength(0);
+ });
+
+ it("emits tool-use for tool_call events", async () => {
+ const session = backend.execute("hello", { cwd: "/tmp" });
+ const mock = getMock();
+
+ mock.stdout.push(
+ JSON.stringify({ type: "tool_call", name: "read_file", call_id: "call_1", input: { path: "/test" } }) + "\n",
+ );
+ await tick();
+ mock.proc.emit("close", 0);
+
+ const messages = await collectMessages(session.messages);
+ expect(messages).toContainEqual({
+ type: "tool-use",
+ tool: "read_file",
+ callId: "call_1",
+ input: { path: "/test" },
+ });
+ });
+
+ it("emits tool-result for tool_result events", async () => {
+ const session = backend.execute("hello", { cwd: "/tmp" });
+ const mock = getMock();
+
+ mock.stdout.push(
+ JSON.stringify({ type: "tool_result", call_id: "call_1", output: "file contents" }) + "\n",
+ );
+ await tick();
+ mock.proc.emit("close", 0);
+
+ const messages = await collectMessages(session.messages);
+ expect(messages).toContainEqual({
+ type: "tool-result",
+ callId: "call_1",
+ output: "file contents",
+ });
+ });
+
+ it("emits error event and sets error", async () => {
+ const session = backend.execute("hello", { cwd: "/tmp" });
+ const mock = getMock();
+
+ mock.stdout.push(JSON.stringify({ type: "error", message: "something broke" }) + "\n");
+ await tick();
+ mock.proc.emit("close", 1);
+
+ const messages = await collectMessages(session.messages);
+ expect(messages).toContainEqual({ type: "error", content: "something broke" });
+ });
+
+ it("error event with content fallback works", async () => {
+ const session = backend.execute("hello", { cwd: "/tmp" });
+ const mock = getMock();
+
+ mock.stdout.push(JSON.stringify({ type: "error", content: "fallback error" }) + "\n");
+ await tick();
+ mock.proc.emit("close", 1);
+
+ const messages = await collectMessages(session.messages);
+ expect(messages).toContainEqual({ type: "error", content: "fallback error" });
+ });
+
+ it("captures session ID from session event", async () => {
+ const session = backend.execute("hello", { cwd: "/tmp" });
+ const mock = getMock();
+
+ mock.stdout.push(JSON.stringify({ type: "session", session_id: "sess_abc" }) + "\n");
+ await tick();
+ mock.proc.emit("close", 0);
+
+ const result = await session.result;
+ expect(result.sessionId).toBe("sess_abc");
+ });
+
+ it("session ID uses last non-empty value", async () => {
+ const session = backend.execute("hello", { cwd: "/tmp" });
+ const mock = getMock();
+
+ mock.stdout.push(JSON.stringify({ type: "session", session_id: "first" }) + "\n");
+ mock.stdout.push(JSON.stringify({ type: "session", session_id: "" }) + "\n");
+ mock.stdout.push(JSON.stringify({ type: "session", session_id: "last" }) + "\n");
+ await tick();
+ mock.proc.emit("close", 0);
+
+ const result = await session.result;
+ expect(result.sessionId).toBe("last");
+ });
+
+ it("handles empty lines and invalid JSON gracefully", async () => {
+ const session = backend.execute("hello", { cwd: "/tmp" });
+ const mock = getMock();
+
+ mock.stdout.push("\n");
+ mock.stdout.push(" \n");
+ mock.stdout.push("not json\n");
+ await tick();
+ mock.proc.emit("close", 0);
+
+ const messages = await collectMessages(session.messages);
+ expect(messages).toContainEqual({ type: "log", content: "not json", level: "debug" });
+ });
+
+ it("OPENCODE_PERMISSION env var is set on subprocess", () => {
+ backend.execute("hello", { cwd: "/tmp" });
+ expect(lastSpawnArgs).toBeTruthy();
+ const env = lastSpawnArgs!.opts.env as Record<string, string>;
+ expect(env.OPENCODE_PERMISSION).toBe('{"*":"allow"}');
+ });
+
+ it("uses --prompt for systemPrompt and user prompt as positional arg", () => {
+ backend.execute("do things", { cwd: "/tmp", systemPrompt: "You are helpful" });
+ expect(lastSpawnArgs).toBeTruthy();
+ const args = lastSpawnArgs!.args;
+ const promptIdx = args.indexOf("--prompt");
+ expect(promptIdx).toBeGreaterThan(-1);
+ expect(args[promptIdx + 1]).toBe("You are helpful");
+ expect(args[args.length - 1]).toBe("do things");
+ });
+
+ it("without systemPrompt, no --prompt flag, user prompt is positional", () => {
+ backend.execute("do things", { cwd: "/tmp" });
+ expect(lastSpawnArgs).toBeTruthy();
+ const args = lastSpawnArgs!.args;
+ expect(args).not.toContain("--prompt");
+ expect(args[args.length - 1]).toBe("do things");
+ });
+
+ it("sets status to timeout when process is killed by timeout", async () => {
+ vi.useFakeTimers();
+ const session = backend.execute("hello", { cwd: "/tmp", timeout: 3000 });
+ const mock = getMock();
+
+ vi.advanceTimersByTime(3000);
+ expect(mock.proc.kill).toHaveBeenCalledWith("SIGTERM");
+
+ mock.proc.emit("close", null);
+
+ const result = await session.result;
+ expect(result.status).toBe("timeout");
+ vi.useRealTimers();
+ });
+
+ it("error event with nil error emits empty content", async () => {
+ const session = backend.execute("hello", { cwd: "/tmp" });
+ const mock = getMock();
+
+ mock.stdout.push(JSON.stringify({ type: "error" }) + "\n");
+ await tick();
+ mock.proc.emit("close", 1);
+
+ const messages = await collectMessages(session.messages);
+ expect(messages).toContainEqual({ type: "error", content: "" });
+ });
+
+ it("tool_call with missing fields does not crash", async () => {
+ const session = backend.execute("hello", { cwd: "/tmp" });
+ const mock = getMock();
+
+ mock.stdout.push(JSON.stringify({ type: "tool_call" }) + "\n");
+ await tick();
+ mock.proc.emit("close", 0);
+
+ const messages = await collectMessages(session.messages);
+ expect(messages).toContainEqual(
+ expect.objectContaining({ type: "tool-use", tool: "" }),
+ );
+ });
+
+ it("done/complete event updates output and session ID", async () => {
+ const session = backend.execute("hello", { cwd: "/tmp" });
+ const mock = getMock();
+
+ mock.stdout.push(
+ JSON.stringify({ type: "done", output: "final output", session_id: "sess_done", status: "completed" }) + "\n",
+ );
+ await tick();
+ mock.proc.emit("close", 0);
+
+ const result = await session.result;
+ expect(result.output).toBe("final output");
+ expect(result.sessionId).toBe("sess_done");
+ });
+});
diff --git a/src/cli/daemon/agent/claude.ts b/src/cli/daemon/agent/claude.ts
index 77d783588..629979038 100644
--- a/src/cli/daemon/agent/claude.ts
+++ b/src/cli/daemon/agent/claude.ts
@@ -38,9 +38,11 @@ export class ClaudeBackend implements AgentBackend {
env: { ...process.env },
});
+ let timedOut = false;
let timeoutTimer: ReturnType<typeof setTimeout> | undefined;
if (options.timeout) {
timeoutTimer = setTimeout(() => {
+ timedOut = true;
proc.kill("SIGTERM");
}, options.timeout);
}
@@ -152,7 +154,7 @@ export class ClaudeBackend implements AgentBackend {
break;
}
- case "control": {
+ case "control_request": {
handleControlRequest(proc, event);
break;
}
@@ -170,7 +172,9 @@ export class ClaudeBackend implements AgentBackend {
proc.on("close", (code: number | null) => {
if (timeoutTimer) clearTimeout(timeoutTimer);
- if (code !== 0 && resultStatus === "completed") {
+ if (timedOut) {
+ resultStatus = "timeout";
+ } else if (code !== 0 && resultStatus === "completed") {
resultStatus = "failed";
}
@@ -222,13 +226,35 @@ function handleControlRequest(
proc: ChildProcess,
event: Record<string, unknown>,
): void {
- const controlId = event.control_id as string | undefined;
- if (!controlId) return;
+ 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) {
+ const input = payload.input;
+ if (typeof input === "string") {
+ try {
+ updatedInput = JSON.parse(input);
+ } catch {
+ updatedInput = input;
+ }
+ } else if (input !== undefined) {
+ updatedInput = input;
+ }
+ }
const approval = JSON.stringify({
type: "control_response",
- control_id: controlId,
- approved: true,
+ response: {
+ subtype: "success",
+ request_id: requestId,
+ response: {
+ behavior: "allow",
+ updatedInput,
+ },
+ },
});
try {
diff --git a/src/cli/daemon/agent/codex.ts b/src/cli/daemon/agent/codex.ts
index c071596e4..192663da4 100644
--- a/src/cli/daemon/agent/codex.ts
+++ b/src/cli/daemon/agent/codex.ts
@@ -12,6 +12,38 @@ interface JsonRpcMessage {
error?: { code: number; message: string };
}
+type NotificationProtocol = "unknown" | "legacy" | "raw";
+
+const RAW_DETECTION_METHODS = new Set([
+ "turn/started",
+ "turn/completed",
+ "thread/started",
+ "item/started",
+ "item/completed",
+]);
+
+/** Extract thread ID from a thread/start response. */
+export function extractThreadID(response: unknown): string {
+ if (response && typeof response === "object") {
+ const r = response as Record<string, unknown>;
+ // Try nested result.thread.id first, then thread.id, then top-level id
+ const thread =
+ (r.result as Record<string, unknown> | undefined)?.thread ??
+ (r.thread as Record<string, unknown> | undefined);
+ if (thread && typeof thread === "object") {
+ const id = (thread as Record<string, unknown>).id;
+ if (typeof id === "string" && id) return id;
+ }
+ if (typeof r.id === "string" && r.id) return r.id;
+ }
+ return "";
+}
+
+/** Return undefined if the string is empty/null, otherwise the string. */
+export function nilIfEmpty(s: string | undefined | null): string | undefined {
+ return s ? s : undefined;
+}
+
export class CodexBackend implements AgentBackend {
name = "codex";
@@ -24,9 +56,11 @@ export class CodexBackend implements AgentBackend {
env: { ...process.env },
});
+ let timedOut = false;
let timeoutTimer: ReturnType<typeof setTimeout> | undefined;
if (options.timeout) {
timeoutTimer = setTimeout(() => {
+ timedOut = true;
proc.kill("SIGTERM");
}, options.timeout);
}
@@ -36,6 +70,19 @@ export class CodexBackend implements AgentBackend {
let lastOutput = "";
let lastError = "";
let resultStatus: AgentResult["status"] = "completed";
+ let sessionId = "";
+
+ // Protocol detection state
+ let notificationProtocol: NotificationProtocol = "unknown";
+
+ // Turn deduplication
+ let lastCompletedTurnId = "";
+
+ // Pending RPC callbacks
+ const pendingRequests = new Map<
+ number,
+ { resolve: (value: unknown) => void; reject: (err: Error) => void }
+ >();
const messageQueue: AgentMessage[] = [];
let messageResolve: (() => void) | null = null;
@@ -50,32 +97,263 @@ export class CodexBackend implements AgentBackend {
}
};
- const sendRpc = (
- method: string,
- params: Record<string, unknown>,
- id?: number,
- ) => {
- const msg: JsonRpcMessage = { jsonrpc: "2.0", method, params };
- if (id !== undefined) msg.id = id;
+ const writeStdin = (data: string) => {
try {
- proc.stdin?.write(JSON.stringify(msg) + "\n");
+ proc.stdin?.write(data + "\n");
} catch {
// stdin closed
}
};
+ const sendRpc = (
+ method: string,
+ params: Record<string, unknown>,
+ ): Promise<unknown> => {
+ const id = ++requestId;
+ const msg: JsonRpcMessage = { jsonrpc: "2.0", id, method, params };
+ writeStdin(JSON.stringify(msg));
+ return new Promise((resolve, reject) => {
+ pendingRequests.set(id, { resolve, reject });
+ });
+ };
+
+ const sendNotification = (method: string) => {
+ const msg = { jsonrpc: "2.0" as const, method };
+ writeStdin(JSON.stringify(msg));
+ };
+
const sendResponse = (id: number, result: unknown) => {
const msg = { jsonrpc: "2.0" as const, id, result };
- try {
- proc.stdin?.write(JSON.stringify(msg) + "\n");
- } catch {
- // stdin closed
+ writeStdin(JSON.stringify(msg));
+ };
+
+ /** Cancel all pending RPC requests. */
+ const closeAllPending = (reason: string) => {
+ for (const [, cb] of pendingRequests) {
+ cb.reject(new Error(reason));
+ }
+ pendingRequests.clear();
+ };
+
+ const triggerTurnDone = (aborted: boolean) => {
+ if (aborted) {
+ resultStatus = "aborted";
+ } else {
+ resultStatus = "completed";
+ }
+ };
+
+ const handleServerRequest = (msg: JsonRpcMessage) => {
+ const method = msg.method!;
+ const id = msg.id!;
+
+ switch (method) {
+ case "item/commandExecution/requestApproval":
+ case "execCommandApproval":
+ case "item/fileChange/requestApproval":
+ case "applyPatchApproval":
+ sendResponse(id, { decision: "accept" });
+ break;
+ default:
+ sendResponse(id, {});
+ break;
+ }
+ };
+
+ const handleNotification = (msg: JsonRpcMessage) => {
+ const method = msg.method!;
+ const params = msg.params || {};
+
+ // Legacy protocol detection
+ if (method === "codex/event") {
+ if (notificationProtocol === "raw") return; // locked to raw, ignore legacy
+ notificationProtocol = "legacy";
+ handleLegacyEvent(params);
+ return;
+ }
+
+ // Raw protocol detection — these methods trigger detection
+ if (RAW_DETECTION_METHODS.has(method)) {
+ if (notificationProtocol === "legacy") return; // locked to legacy, ignore raw
+ notificationProtocol = "raw";
+ }
+
+ // thread/status/changed is raw-only but NOT a detection trigger
+ if (method === "thread/status/changed" && notificationProtocol === "legacy") {
+ return;
+ }
+
+ switch (method) {
+ case "turn/started": {
+ pushMessage({ type: "status", status: "turn_start" });
+ break;
+ }
+
+ case "turn/completed": {
+ const turnId = params.turnId as string | undefined;
+ if (turnId && turnId === lastCompletedTurnId) return; // deduplicate
+ if (turnId) lastCompletedTurnId = turnId;
+
+ const status = params.status as string | undefined;
+ if (status === "completed" || status === "finished") {
+ triggerTurnDone(false);
+ } else if (status === "cancelled" || status === "aborted") {
+ triggerTurnDone(true);
+ } else if (status === "error" || status === "failed") {
+ resultStatus = "failed";
+ lastError = (params.output as string) || "turn failed";
+ }
+ break;
+ }
+
+ case "thread/status/changed": {
+ const status = params.status as string | undefined;
+ if (status === "idle") {
+ triggerTurnDone(false);
+ }
+ 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") {
+ pushMessage({
+ type: "tool-use",
+ tool: "exec_command",
+ callId: item.id as string,
+ input: item as Record<string, unknown>,
+ });
+ } else if (itemType === "fileChange") {
+ pushMessage({
+ type: "tool-use",
+ tool: "patch_apply",
+ callId: item.id as string,
+ input: item as Record<string, unknown>,
+ });
+ }
+ 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") {
+ const output = (item.aggregatedOutput as string) || "";
+ pushMessage({
+ type: "tool-result",
+ callId: item.id as string,
+ output,
+ });
+ } else if (itemType === "fileChange") {
+ pushMessage({
+ type: "tool-result",
+ callId: item.id as string,
+ output: "",
+ });
+ } else if (itemType === "agentMessage") {
+ 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") {
+ if (block.text) {
+ pushMessage({ type: "text", content: block.text });
+ lastOutput = block.text;
+ }
+ }
+ }
+ }
+ const phase = item.phase as string | undefined;
+ if (phase === "final_answer") {
+ triggerTurnDone(false);
+ }
+ }
+ break;
+ }
+
+ default: {
+ pushMessage({
+ type: "log",
+ content: JSON.stringify(msg),
+ level: "debug",
+ });
+ }
+ }
+ };
+
+ const handleLegacyEvent = (params: Record<string, unknown>) => {
+ const eventType = params.type as string | undefined;
+ if (!eventType) return;
+
+ switch (eventType) {
+ case "task_started":
+ pushMessage({ type: "status", status: "running" });
+ break;
+
+ case "agent_message": {
+ const text = (params.text as string) || (params.message as string) || "";
+ if (text) {
+ pushMessage({ type: "text", content: text });
+ lastOutput = text;
+ }
+ break;
+ }
+
+ case "exec_command_begin":
+ pushMessage({
+ type: "tool-use",
+ tool: "exec_command",
+ callId: params.id as string,
+ input: params as Record<string, unknown>,
+ });
+ break;
+
+ case "exec_command_end":
+ pushMessage({
+ type: "tool-result",
+ callId: params.id as string,
+ output: (params.output as string) || "",
+ });
+ break;
+
+ case "patch_apply_begin":
+ pushMessage({
+ type: "tool-use",
+ tool: "patch_apply",
+ callId: params.id as string,
+ input: params as Record<string, unknown>,
+ });
+ break;
+
+ case "patch_apply_end":
+ pushMessage({
+ type: "tool-result",
+ callId: params.id as string,
+ output: (params.output as string) || "",
+ });
+ break;
+
+ case "task_complete": {
+ const output = params.output as string | undefined;
+ if (output) lastOutput = output;
+ triggerTurnDone(false);
+ break;
+ }
+
+ case "turn_aborted":
+ triggerTurnDone(true);
+ break;
}
};
const resultPromise = new Promise<AgentResult>((resolve) => {
const stderrChunks: string[] = [];
- let initialized = false;
proc.stderr?.on("data", (chunk: Buffer) => {
stderrChunks.push(chunk.toString());
@@ -94,137 +372,110 @@ export class CodexBackend implements AgentBackend {
return;
}
- if (msg.id !== undefined && msg.result !== undefined && !msg.method) {
- if (!initialized) {
- initialized = true;
- startThread(prompt, options);
- }
+ // Route: server request (has both id AND method)
+ if (msg.id !== undefined && msg.method) {
+ handleServerRequest(msg);
return;
}
- if (msg.method) {
+ // Route: notification (has method, no id)
+ if (msg.method && msg.id === undefined) {
handleNotification(msg);
return;
}
- if (msg.error) {
- lastError = msg.error.message;
- pushMessage({
- type: "error",
- content: msg.error.message,
- });
- }
- });
-
- const startThread = (prompt: string, opts: ExecOptions) => {
- const threadParams: Record<string, unknown> = {
- instructions: prompt,
- };
- if (opts.model) {
- threadParams.model = opts.model;
- }
-
- const id = ++requestId;
- sendRpc("thread/start", threadParams, id);
- };
-
- const handleNotification = (msg: JsonRpcMessage) => {
- switch (msg.method) {
- case "turn/start": {
- pushMessage({
- type: "status",
- status: "turn_start",
- });
- break;
- }
-
- case "turn/complete": {
- const output = msg.params?.output as string | undefined;
- if (output) lastOutput = output;
- const status = msg.params?.status as string | undefined;
-
- if (status === "completed" || status === "finished") {
- resultStatus = "completed";
- } else if (status === "error" || status === "failed") {
- resultStatus = "failed";
- lastError = output || "turn failed";
+ // Route: response (has id, no method) — both success and error
+ if (msg.id !== undefined && !msg.method) {
+ const pending = pendingRequests.get(msg.id);
+ if (pending) {
+ pendingRequests.delete(msg.id);
+ if (msg.error) {
+ pending.reject(new Error(msg.error.message));
+ } else {
+ pending.resolve(msg.result);
}
- break;
}
+ return;
+ }
- case "thread/complete": {
- const output = msg.params?.output as string | undefined;
- if (output) lastOutput = output;
- break;
- }
+ // Fallback
+ pushMessage({
+ type: "log",
+ content: JSON.stringify(msg),
+ level: "debug",
+ });
+ });
- case "item/created": {
- const item = msg.params?.item as Record<string, unknown> | undefined;
- if (!item) break;
-
- const itemType = item.type as string | undefined;
- if (itemType === "message") {
- 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") {
- pushMessage({ type: "text", content: block.text });
- if (block.text) lastOutput = block.text;
- }
- }
- }
- } else if (
- itemType === "function_call" ||
- itemType === "tool_call"
- ) {
- pushMessage({
- type: "tool-use",
- tool: (item.name as string) || (item.function as string) || "",
- callId: item.call_id as string,
- input: item.arguments as Record<string, unknown>,
- });
- } else if (itemType === "function_call_output") {
- pushMessage({
- type: "tool-result",
- callId: item.call_id as string,
- output: item.output as string,
- });
- }
- break;
- }
+ // Handshake: initialize → initialized → thread/start → turn/start
+ const startHandshake = async () => {
+ try {
+ // 1. Initialize
+ await sendRpc("initialize", {
+ clientInfo: {
+ name: "alook-daemon",
+ title: "Alook Agent SDK",
+ version: "0.1.0",
+ },
+ capabilities: { experimentalApi: true },
+ });
- case "approval/requested": {
- const approvalId = msg.params?.id as number | undefined;
- if (approvalId !== undefined) {
- sendResponse(approvalId, { approved: true });
+ // 2. Send initialized notification
+ sendNotification("initialized");
+
+ // 3. Start or resume thread
+ let threadResponse: unknown;
+ if (options.resumeSessionId) {
+ // thread/resume reopens an existing thread by ID
+ threadResponse = await sendRpc("thread/resume", {
+ threadId: options.resumeSessionId,
+ ...(options.model ? { model: options.model } : {}),
+ ...(nilIfEmpty(options.systemPrompt)
+ ? { developerInstructions: options.systemPrompt }
+ : {}),
+ });
+ sessionId = options.resumeSessionId;
+ } else {
+ // thread/start creates a new thread
+ const threadParams: Record<string, unknown> = {
+ cwd: options.cwd,
+ sandbox: "workspace-write",
+ persistExtendedHistory: true,
+ experimentalRawEvents: false,
+ };
+ if (nilIfEmpty(options.systemPrompt)) {
+ threadParams.developerInstructions = options.systemPrompt;
}
- const reqId = msg.id;
- if (reqId !== undefined) {
- sendResponse(reqId, { approved: true });
+ if (options.model) {
+ threadParams.model = options.model;
}
- break;
+ threadResponse = await sendRpc("thread/start", threadParams);
+ sessionId = extractThreadID(threadResponse);
}
- default: {
- pushMessage({
- type: "log",
- content: JSON.stringify(msg),
- level: "debug",
- });
- }
+ // 5. Send turn/start with the prompt
+ await sendRpc("turn/start", {
+ threadId: sessionId,
+ input: [{ type: "text", text: prompt }],
+ });
+ } catch (err) {
+ const errMsg =
+ err instanceof Error ? err.message : "handshake failed";
+ lastError = errMsg;
+ resultStatus = "failed";
+ pushMessage({ type: "error", content: errMsg });
}
};
- // Send initialize request
- const initId = ++requestId;
- sendRpc("initialize", { client: "alook-daemon", version: "0.1.0" }, initId);
+ startHandshake();
proc.on("close", (code: number | null) => {
if (timeoutTimer) clearTimeout(timeoutTimer);
- if (code !== 0 && resultStatus === "completed") {
+ closeAllPending("process closed");
+
+ if (timedOut) {
+ resultStatus = "timeout";
+ } else if (code !== 0 && resultStatus === "completed") {
resultStatus = "failed";
}
@@ -245,7 +496,7 @@ export class CodexBackend implements AgentBackend {
output: lastOutput,
error: lastError,
durationMs: Date.now() - startTime,
- sessionId: "",
+ sessionId,
});
});
});
diff --git a/src/cli/daemon/agent/opencode.ts b/src/cli/daemon/agent/opencode.ts
index ef06572a7..eea61777e 100644
--- a/src/cli/daemon/agent/opencode.ts
+++ b/src/cli/daemon/agent/opencode.ts
@@ -14,21 +14,27 @@ export class OpenCodeBackend implements AgentBackend {
if (options.model) {
args.push("--model", options.model);
}
+ if (options.systemPrompt) {
+ args.push("--prompt", options.systemPrompt);
+ }
if (options.resumeSessionId) {
args.push("--session", options.resumeSessionId);
}
- args.push("--prompt", prompt);
+ // User prompt as positional argument (no flag)
+ args.push(prompt);
const proc = spawn(this.cliPath, args, {
cwd: options.cwd,
stdio: ["pipe", "pipe", "pipe"],
- env: { ...process.env },
+ env: { ...process.env, OPENCODE_PERMISSION: '{"*":"allow"}' },
});
+ let timedOut = false;
let timeoutTimer: ReturnType<typeof setTimeout> | undefined;
if (options.timeout) {
timeoutTimer = setTimeout(() => {
+ timedOut = true;
proc.kill("SIGTERM");
}, options.timeout);
}
@@ -122,7 +128,7 @@ export class OpenCodeBackend implements AgentBackend {
}
case "error": {
- const content = event.message as string || event.content as string || "";
+ const content = (event.message as string) || (event.content as string) || "";
lastError = content;
pushMessage({ type: "error", content });
break;
@@ -157,7 +163,9 @@ export class OpenCodeBackend implements AgentBackend {
proc.on("close", (code: number | null) => {
if (timeoutTimer) clearTimeout(timeoutTimer);
- if (code !== 0 && resultStatus === "completed") {
+ if (timedOut) {
+ resultStatus = "timeout";
+ } else if (code !== 0 && resultStatus === "completed") {
resultStatus = "failed";
}