diff --git a/apps/desktop/src/main/agent-host-client.spec.ts b/apps/desktop/src/main/agent-host-client.spec.ts new file mode 100644 index 0000000..12fe55d --- /dev/null +++ b/apps/desktop/src/main/agent-host-client.spec.ts @@ -0,0 +1,171 @@ +import type { + AgentHostEnvelope, + AgentHostRequest, + AgentHostResponse, +} from "@pi-desktop/shared"; +import { afterEach, describe, expect, it, vi } from "vitest"; + +import { + type AgentHostTransport, + createAgentHostClient, +} from "./agent-host-client"; + +class FakeTransport implements AgentHostTransport { + readonly sent: AgentHostRequest[] = []; + failPostMessage: Error | null = null; + + private messageListener: ((message: unknown) => void) | null = null; + private disconnectListener: ((error: Error) => void) | null = null; + + on(_event: "message", listener: (message: unknown) => void): this { + this.messageListener = listener; + return this; + } + + onDisconnect(listener: (error: Error) => void): this { + this.disconnectListener = listener; + return this; + } + + postMessage(message: AgentHostRequest): void { + if (this.failPostMessage) { + throw this.failPostMessage; + } + this.sent.push(message); + } + + respond(response: AgentHostResponse): void { + const envelope: AgentHostEnvelope = { type: "response", response }; + this.messageListener?.(envelope); + } + + disconnect(error: Error): void { + this.disconnectListener?.(error); + } +} + +describe("createAgentHostClient", () => { + afterEach(() => { + vi.useRealTimers(); + }); + + it("resolves requests when matching responses arrive", async () => { + const transport = new FakeTransport(); + const client = createAgentHostClient(transport); + + const bootstrap = client.bootstrap(); + const request = transport.sent[0]; + expect(request?.type).toBe("bootstrap"); + transport.respond({ requestId: request?.requestId ?? "", kind: "ack" }); + + await expect(bootstrap).resolves.toBeUndefined(); + }); + + it("times out non-prompt requests after the request timeout", async () => { + vi.useFakeTimers(); + const transport = new FakeTransport(); + const client = createAgentHostClient(transport, { + requestTimeoutMs: 5_000, + }); + + const snapshot = client.getSnapshot(); + const assertion = expect(snapshot).rejects.toThrow( + "Agent host request getSnapshot timed out after 5000ms", + ); + + await vi.advanceTimersByTimeAsync(5_000); + await assertion; + }); + + it("does not time out a prompt: long turns stay running past the request timeout", async () => { + vi.useFakeTimers(); + const transport = new FakeTransport(); + const client = createAgentHostClient(transport, { + requestTimeoutMs: 5_000, + }); + + let settled = false; + const prompt = client.prompt("write a long report").then( + () => { + settled = true; + }, + () => { + settled = true; + }, + ); + + // Far beyond the generic request timeout the prompt must still be + // pending: only the host's acceptance ack (or a disconnect) settles it. + await vi.advanceTimersByTimeAsync(60_000); + expect(settled).toBe(false); + + const request = transport.sent[0]; + transport.respond({ requestId: request?.requestId ?? "", kind: "ack" }); + await prompt; + expect(settled).toBe(true); + }); + + it("rejects every pending request immediately on disconnect, including prompts", async () => { + const transport = new FakeTransport(); + const client = createAgentHostClient(transport); + + const prompt = client.prompt("hello"); + const snapshot = client.getSnapshot(); + const promptAssertion = expect(prompt).rejects.toThrow( + "Agent host socket disconnected", + ); + const snapshotAssertion = expect(snapshot).rejects.toThrow( + "Agent host socket disconnected", + ); + + transport.disconnect(new Error("Agent host socket disconnected")); + + await promptAssertion; + await snapshotAssertion; + + // Responses arriving after the disconnect are ignored, not delivered. + transport.respond({ requestId: "1", kind: "ack" }); + }); + + it("rejects and forgets a request when postMessage throws", async () => { + const transport = new FakeTransport(); + transport.failPostMessage = new Error("transport is not connected"); + const client = createAgentHostClient(transport); + + await expect(client.bootstrap()).rejects.toThrow( + "transport is not connected", + ); + + // The failed request must not linger as pending: a late response for + // its id is ignored instead of settling a forgotten promise. + transport.failPostMessage = null; + const second = client.bootstrap(); + transport.respond({ + requestId: transport.sent[0]?.requestId ?? "", + kind: "ack", + }); + await expect(second).resolves.toBeUndefined(); + }); + + it("works with transports that do not expose a disconnect signal", async () => { + const listeners: Array<(message: unknown) => void> = []; + const transport: AgentHostTransport = { + on(_event, listener) { + listeners.push(listener); + return this; + }, + postMessage: vi.fn(), + }; + const client = createAgentHostClient(transport); + + const bootstrap = client.bootstrap(); + for (const listener of listeners) { + listener({ + type: "response", + response: { requestId: "1", kind: "ack" }, + }); + } + + await expect(bootstrap).resolves.toBeUndefined(); + }); +}); diff --git a/apps/desktop/src/main/agent-host-client.ts b/apps/desktop/src/main/agent-host-client.ts index f0a4bd9..a83673e 100644 --- a/apps/desktop/src/main/agent-host-client.ts +++ b/apps/desktop/src/main/agent-host-client.ts @@ -20,6 +20,10 @@ type AgentHostRequestInput = DistributiveOmit; export interface AgentHostTransport { on(event: "message", listener: (message: unknown) => void): this; postMessage(message: AgentHostRequest): void; + // Optional disconnect signal: transports that can detect a dead host + // (sockets) report it here so pending requests fail immediately instead + // of waiting for a timeout that may never be appropriate (prompts). + onDisconnect?(listener: (error: Error) => void): this; } interface PendingRequest< @@ -53,6 +57,14 @@ export function createAgentHostClient( const listeners = new Set(); const pending = new Map(); + function rejectAllPending(error: Error): void { + const requests = Array.from(pending.values()); + pending.clear(); + for (const request of requests) { + request.reject(error); + } + } + child.on("message", (message) => { const envelope = message as AgentHostEnvelope; @@ -84,6 +96,10 @@ export function createAgentHostClient( request.resolve(envelope.response); }); + child.onDisconnect?.((error) => { + rejectAllPending(error); + }); + function send( request: AgentHostRequestInput, ): Promise { @@ -95,26 +111,50 @@ export function createAgentHostClient( } as AgentHostRequest; return new Promise((resolve, reject) => { - const timeout = setTimeout(() => { - pending.delete(nextRequest.requestId); - reject( - new Error( - `Agent host request ${nextRequest.type} timed out after ${requestTimeoutMs}ms`, - ), - ); - }, requestTimeoutMs); + // Prompt acceptance is separated from turn completion: the host acks + // a prompt once the turn is accepted, and completion arrives through + // events. The generic request timeout must therefore not apply to + // prompts — a long turn is not a stuck request, and timing one out + // here would report failure for a prompt the host is still running + // (and must never be retried blindly, since it may have been + // accepted). A dead host still fails the prompt immediately via the + // transport disconnect signal above. + const timeout = + nextRequest.type === "prompt" + ? null + : setTimeout(() => { + pending.delete(nextRequest.requestId); + reject( + new Error( + `Agent host request ${nextRequest.type} timed out after ${requestTimeoutMs}ms`, + ), + ); + }, requestTimeoutMs); pending.set(nextRequest.requestId, { reject: (error) => { - clearTimeout(timeout); + if (timeout) { + clearTimeout(timeout); + } reject(error); }, resolve: (response) => { - clearTimeout(timeout); + if (timeout) { + clearTimeout(timeout); + } resolve(response as TResponse); }, }); - child.postMessage(nextRequest); + + try { + child.postMessage(nextRequest); + } catch (error) { + pending.delete(nextRequest.requestId); + if (timeout) { + clearTimeout(timeout); + } + reject(error instanceof Error ? error : new Error(String(error))); + } }); } diff --git a/apps/desktop/src/main/agent-host-socket-transport.spec.ts b/apps/desktop/src/main/agent-host-socket-transport.spec.ts new file mode 100644 index 0000000..4e53571 --- /dev/null +++ b/apps/desktop/src/main/agent-host-socket-transport.spec.ts @@ -0,0 +1,152 @@ +import fs from "node:fs"; +import net from "node:net"; +import os from "node:os"; +import path from "node:path"; +import { afterEach, describe, expect, it, vi } from "vitest"; + +import { + createAgentHostSocketTransport, + isSocketFrame, + MAX_SOCKET_FRAME_CHARS, +} from "./agent-host-socket-transport"; + +describe("isSocketFrame", () => { + it("accepts JSON objects, including envelopes and legacy shapes", () => { + expect(isSocketFrame({ type: "event", event: { type: "agent_end" } })).toBe( + true, + ); + expect( + isSocketFrame({ + type: "response", + response: { requestId: "1", kind: "ack" }, + }), + ).toBe(true); + expect(isSocketFrame({ kind: "event", event: { type: "agent_end" } })).toBe( + true, + ); + }); + + it("rejects non-objects and arrays", () => { + expect(isSocketFrame(null)).toBe(false); + expect(isSocketFrame("response")).toBe(false); + expect(isSocketFrame(42)).toBe(false); + expect(isSocketFrame([{ type: "event" }])).toBe(false); + }); +}); + +describe("createAgentHostSocketTransport", () => { + let server: net.Server | null = null; + let serverSocket: net.Socket | null = null; + let socketDirectory: string | null = null; + + afterEach(async () => { + serverSocket?.destroy(); + serverSocket = null; + if (server) { + await new Promise((resolve) => server?.close(() => resolve())); + server = null; + } + if (socketDirectory) { + fs.rmSync(socketDirectory, { recursive: true, force: true }); + socketDirectory = null; + } + vi.restoreAllMocks(); + }); + + async function startServer(onSocket: (socket: net.Socket) => void) { + socketDirectory = fs.mkdtempSync(path.join(os.tmpdir(), "pd-client-")); + const socketPath = path.join(socketDirectory, "agent.sock"); + server = net.createServer((socket) => { + serverSocket = socket; + onSocket(socket); + }); + await new Promise((resolve) => + server?.listen(socketPath, () => resolve()), + ); + return socketPath; + } + + it("delivers object frames and drops malformed or non-object frames", async () => { + const socketPath = await startServer(() => {}); + const transport = createAgentHostSocketTransport(socketPath); + const messages: unknown[] = []; + transport.on("message", (message) => { + messages.push(message); + }); + const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {}); + + await transport.connect(); + serverSocket?.write( + `${JSON.stringify({ + type: "response", + response: { requestId: "1", kind: "ack" }, + })}\n`, + ); + serverSocket?.write("not json\n"); + serverSocket?.write("42\n"); + serverSocket?.write( + `${JSON.stringify({ type: "event", event: { type: "agent_end" } })}\n`, + ); + + await vi.waitFor(() => { + expect(messages).toHaveLength(2); + }); + expect(messages[0]).toEqual({ + type: "response", + response: { requestId: "1", kind: "ack" }, + }); + expect(messages[1]).toEqual({ + type: "event", + event: { type: "agent_end" }, + }); + expect(errorSpy).toHaveBeenCalledTimes(2); + + transport.close(); + }); + + it("notifies disconnect listeners exactly once when the host socket closes", async () => { + const socketPath = await startServer(() => {}); + const transport = createAgentHostSocketTransport(socketPath); + const onDisconnect = vi.fn(); + transport.onDisconnect(onDisconnect); + + await transport.connect(); + serverSocket?.destroy(); + + await vi.waitFor(() => { + expect(onDisconnect).toHaveBeenCalledOnce(); + }); + expect(onDisconnect.mock.calls[0]?.[0]).toBeInstanceOf(Error); + + transport.close(); + expect(onDisconnect).toHaveBeenCalledOnce(); + }); + + // Moving a >16MiB frame through the socket is CPU-bound under test + // parallelism, so this case gets a longer timeout than the default. + it("notifies disconnect and drops the connection when a frame exceeds the size bound", async () => { + const socketPath = await startServer(() => {}); + const transport = createAgentHostSocketTransport(socketPath); + const messages: unknown[] = []; + transport.on("message", (message) => { + messages.push(message); + }); + const onDisconnect = vi.fn(); + transport.onDisconnect(onDisconnect); + vi.spyOn(console, "error").mockImplementation(() => {}); + + await transport.connect(); + serverSocket?.write("x".repeat(MAX_SOCKET_FRAME_CHARS + 1)); + + await vi.waitFor( + () => { + expect(onDisconnect).toHaveBeenCalledOnce(); + }, + { timeout: 20_000, interval: 50 }, + ); + expect(onDisconnect.mock.calls[0]?.[0]).toBeInstanceOf(Error); + expect(messages).toHaveLength(0); + + transport.close(); + }, 30_000); +}); diff --git a/apps/desktop/src/main/agent-host-socket-transport.ts b/apps/desktop/src/main/agent-host-socket-transport.ts index 8084a3e..ed3bf73 100644 --- a/apps/desktop/src/main/agent-host-socket-transport.ts +++ b/apps/desktop/src/main/agent-host-socket-transport.ts @@ -3,34 +3,115 @@ import type { AgentHostEnvelope, AgentHostRequest } from "@pi-desktop/shared"; import type { AgentHostTransport } from "./agent-host-client"; type MessageListener = (message: unknown) => void; +type DisconnectListener = (error: Error) => void; export interface AgentHostSocketTransport extends AgentHostTransport { connect(): Promise; close(): void; + // The socket transport always reports disconnects (unlike generic + // transports, where the signal is optional). + onDisconnect(listener: (error: Error) => void): this; +} + +// Inbound frames are bounded: a host that never sends a newline must not +// grow main-process memory without limit. Oversized partial frames are +// dropped and the connection is torn down, which also fails any pending +// client requests through the disconnect signal. +export const MAX_SOCKET_FRAME_CHARS = 16 * 1024 * 1024; + +function isRecord(value: unknown): value is Record { + return typeof value === "object" && value !== null; +} + +// The transport validates frame shape only as far as it safely can: a +// frame must be a JSON object. Strict protocol validation lives at the +// ends of the pipe — the host's socket bridge validates requests before +// dispatch, and the client discriminates envelopes by `type` before +// acting on them — so unknown or legacy fields are forwarded untouched +// rather than silently desynchronizing the stream. +export function isSocketFrame(value: unknown): value is AgentHostEnvelope { + return isRecord(value) && !Array.isArray(value); } export function createAgentHostSocketTransport( socketPath: string, ): AgentHostSocketTransport { const listeners = new Set(); + const disconnectListeners = new Set(); let socket: net.Socket | null = null; - let buffer = ""; + // Partial frames accumulate as chunks (joined only once a newline + // arrives) so a large frame costs linear, not quadratic, copying. + let bufferedChunks: string[] = []; + let bufferedLength = 0; + let disconnectNotified = false; + + function resetBuffer(): void { + bufferedChunks = []; + bufferedLength = 0; + } + + function notifyDisconnect(error: Error): void { + if (disconnectNotified) { + return; + } + disconnectNotified = true; + + for (const listener of disconnectListeners) { + try { + listener(error); + } catch (listenerError) { + console.error( + "[agent-host-socket] disconnect listener threw", + listenerError instanceof Error + ? (listenerError.stack ?? listenerError.message) + : listenerError, + ); + } + } + } function attachSocket(nextSocket: net.Socket): void { nextSocket.setEncoding("utf8"); nextSocket.on("data", (chunk) => { - buffer += chunk; + const text = typeof chunk === "string" ? chunk : chunk.toString(); + bufferedChunks.push(text); + bufferedLength += text.length; + + if (bufferedLength > MAX_SOCKET_FRAME_CHARS) { + console.error( + "[agent-host-socket] dropping connection: frame exceeded maximum size", + ); + resetBuffer(); + notifyDisconnect( + new Error( + "Agent host socket frame exceeded the maximum allowed size", + ), + ); + nextSocket.destroy(); + return; + } + + if (!text.includes("\n")) { + return; + } + + const buffer = bufferedChunks.join(""); + resetBuffer(); const messages = buffer.split("\n"); - buffer = messages.pop() ?? ""; + const remainder = messages.pop() ?? ""; + if (remainder) { + bufferedChunks = [remainder]; + bufferedLength = remainder.length; + } for (const message of messages) { if (!message.trim()) { continue; } - let envelope: AgentHostEnvelope; + let parsed: unknown; try { - envelope = JSON.parse(message) as AgentHostEnvelope; + parsed = JSON.parse(message) as unknown; } catch (error) { // A malformed frame must not crash the main process. Surface it for // diagnostics and keep draining the socket. @@ -41,9 +122,16 @@ export function createAgentHostSocketTransport( continue; } + if (!isSocketFrame(parsed)) { + console.error( + "[agent-host-socket] dropping frame that is not a JSON object", + ); + continue; + } + for (const listener of listeners) { try { - listener(envelope); + listener(parsed); } catch (error) { console.error( "[agent-host-socket] listener threw", @@ -53,6 +141,15 @@ export function createAgentHostSocketTransport( } } }); + + nextSocket.on("error", (error) => { + notifyDisconnect( + new Error(`Agent host socket disconnected: ${error.message}`), + ); + }); + nextSocket.on("close", () => { + notifyDisconnect(new Error("Agent host socket disconnected")); + }); } return { @@ -62,6 +159,10 @@ export function createAgentHostSocketTransport( } return this; }, + onDisconnect(listener: DisconnectListener) { + disconnectListeners.add(listener); + return this; + }, postMessage(message: AgentHostRequest) { if (!socket || socket.readyState !== "open") { throw new Error("Agent host socket transport is not connected"); @@ -73,6 +174,7 @@ export function createAgentHostSocketTransport( return; } + disconnectNotified = false; socket = net.createConnection(socketPath); attachSocket(socket); @@ -82,10 +184,13 @@ export function createAgentHostSocketTransport( }); }, close() { + // An intentional close still ends every pending request: nothing + // will ever answer them on this transport. + notifyDisconnect(new Error("Agent host socket transport closed")); socket?.end(); socket?.destroy(); socket = null; - buffer = ""; + resetBuffer(); listeners.clear(); }, }; diff --git a/apps/desktop/src/main/local-thread-runtime-manager.spec.ts b/apps/desktop/src/main/local-thread-runtime-manager.spec.ts index 7de800a..354b0e8 100644 --- a/apps/desktop/src/main/local-thread-runtime-manager.spec.ts +++ b/apps/desktop/src/main/local-thread-runtime-manager.spec.ts @@ -87,6 +87,70 @@ describe("LocalThreadRuntimeManager", () => { ); }); + it("keeps the runtime starting until the child process spawns", async () => { + const child = createFakeChild(); + spawnMock.mockReturnValue(child); + + const manager = new LocalThreadRuntimeManager(); + const descriptor = await manager.ensureThreadRuntime({ + threadId: "thread-starting", + worktreePath: "/tmp/repo", + command: ["/bin/electron", "entry.js"], + }); + + expect(descriptor.status).toBe("starting"); + expect(descriptor.lastError).toBeNull(); + + // Still starting while the child exists but has not spawned yet. + const beforeSpawn = await manager.getRuntimeState({ + threadId: "thread-starting", + worktreePath: "/tmp/repo", + }); + expect(beforeSpawn.status).toBe("starting"); + + child.emit("spawn"); + + const afterSpawn = await manager.getRuntimeState({ + threadId: "thread-starting", + worktreePath: "/tmp/repo", + }); + expect(afterSpawn.status).toBe("ready"); + expect(afterSpawn.lastError).toBeNull(); + + // Re-ensuring the same runtime reports the spawned state. + const again = await manager.ensureThreadRuntime({ + threadId: "thread-starting", + worktreePath: "/tmp/repo", + command: ["/bin/electron", "entry.js"], + }); + expect(again.status).toBe("ready"); + expect(spawnMock).toHaveBeenCalledOnce(); + }); + + it("reports an error instead of ready when spawning fails", async () => { + const child = createFakeChild(); + spawnMock.mockReturnValue(child); + + const manager = new LocalThreadRuntimeManager(); + const descriptor = await manager.ensureThreadRuntime({ + threadId: "thread-enoent", + worktreePath: "/tmp/repo", + command: ["missing-program", "entry.js"], + }); + expect(descriptor.status).toBe("starting"); + + const enoent = new Error("spawn missing-program ENOENT"); + Object.assign(enoent, { code: "ENOENT" }); + child.emit("error", enoent); + + const state = await manager.getRuntimeState({ + threadId: "thread-enoent", + worktreePath: "/tmp/repo", + }); + expect(state.status).toBe("error"); + expect(state.lastError).toContain("missing-program"); + }); + it("omits PI_CLI_PATH when Pi is not installed", async () => { resolvePiPathMock.mockReturnValue(null); const child = createFakeChild(); diff --git a/apps/desktop/src/main/local-thread-runtime-manager.ts b/apps/desktop/src/main/local-thread-runtime-manager.ts index f77be80..54503fb 100644 --- a/apps/desktop/src/main/local-thread-runtime-manager.ts +++ b/apps/desktop/src/main/local-thread-runtime-manager.ts @@ -66,8 +66,10 @@ export class LocalThreadRuntimeManager implements ThreadRuntimeManager { existing.commandSignature === nextCommandSignature && isChildRunning(existing.child) ) { - existing.descriptor.status = "ready"; - existing.descriptor.lastError = null; + // Report the recorded status as-is: a runtime stays "starting" + // until its process actually spawns (and, downstream, until the + // agent host bootstrap succeeds) instead of being marked ready + // just because a child process object exists. return { ...existing.descriptor }; } @@ -122,7 +124,9 @@ export class LocalThreadRuntimeManager implements ThreadRuntimeManager { this.runtimes.set(spec.threadId, record); - descriptor.status = "ready"; + // The descriptor stays "starting" until the child emits "spawn"; + // returning "ready" here would claim a runtime that may never start + // (spawn error) or whose agent host has not bootstrapped yet. return { ...descriptor }; } @@ -142,14 +146,12 @@ export class LocalThreadRuntimeManager implements ThreadRuntimeManager { }; } + // The recorded status is authoritative: "starting" until spawn, + // "ready" only after it, "error"/"exited" once those events land. + // A merely-running child is not necessarily a ready runtime. return { ...runtime.descriptor, worktreePath, - status: isChildRunning(runtime.child) - ? runtime.descriptor.status === "error" - ? "error" - : "ready" - : runtime.descriptor.status, }; } diff --git a/packages/agent-host/src/pi/pi-cli-rpc-framing.spec.ts b/packages/agent-host/src/pi/pi-cli-rpc-framing.spec.ts index 6db2059..35e44a6 100644 --- a/packages/agent-host/src/pi/pi-cli-rpc-framing.spec.ts +++ b/packages/agent-host/src/pi/pi-cli-rpc-framing.spec.ts @@ -2,6 +2,7 @@ import { describe, expect, it } from "vitest"; import { consumeJsonLines, + MAX_RPC_LINE_CHARS, safeJsonParse, serializeRpcCommand, } from "./pi-cli-rpc-framing.js"; @@ -20,6 +21,26 @@ describe("consumeJsonLines", () => { remainder: "left", }); }); + + it("drops an unterminated remainder that exceeds the line bound instead of buffering it forever", () => { + const oversized = "x".repeat(MAX_RPC_LINE_CHARS + 1); + const framed = consumeJsonLines("", oversized); + + expect(framed.lines).toEqual([]); + expect(framed.remainder).toBe(""); + + // Framing resynchronizes at the next newline after the dropped payload. + const next = consumeJsonLines(framed.remainder, '{"ok":true}\n'); + expect(next.lines).toEqual(['{"ok":true}']); + }); + + it("drops a single completed line that exceeds the line bound", () => { + const oversized = "x".repeat(MAX_RPC_LINE_CHARS + 1); + const framed = consumeJsonLines("", `${oversized}\n{"ok":true}\n`); + + expect(framed.lines).toEqual(['{"ok":true}']); + expect(framed.remainder).toBe(""); + }); }); describe("safeJsonParse", () => { diff --git a/packages/agent-host/src/pi/pi-cli-rpc-framing.ts b/packages/agent-host/src/pi/pi-cli-rpc-framing.ts index 5c39562..6792d30 100644 --- a/packages/agent-host/src/pi/pi-cli-rpc-framing.ts +++ b/packages/agent-host/src/pi/pi-cli-rpc-framing.ts @@ -1,5 +1,12 @@ import { Effect, Either } from "effect"; +// A single RPC frame (or the not-yet-terminated remainder of one) may not +// grow without bound: a peer that never sends a newline must not be able to +// exhaust host memory. Oversized lines and remainders are dropped, which +// resynchronizes framing at the next newline; the dropped payload fails +// JSON parsing downstream like any other malformed frame. +export const MAX_RPC_LINE_CHARS = 16 * 1024 * 1024; + export function safeJsonParse(text: string): unknown | null { const result = Effect.runSync( Effect.either( @@ -19,8 +26,12 @@ export function consumeJsonLines( ): { lines: string[]; remainder: string } { const nextBuffer = buffer + chunk; const segments = nextBuffer.split("\n"); - const remainder = segments.pop() ?? ""; - const lines = segments.filter((line) => line.trim().length > 0); + const rawRemainder = segments.pop() ?? ""; + const lines = segments.filter( + (line) => line.trim().length > 0 && line.length <= MAX_RPC_LINE_CHARS, + ); + const remainder = + rawRemainder.length <= MAX_RPC_LINE_CHARS ? rawRemainder : ""; return { lines, remainder }; } diff --git a/packages/agent-host/src/pi/pi-cli-rpc-process-lifecycle.spec.ts b/packages/agent-host/src/pi/pi-cli-rpc-process-lifecycle.spec.ts index ab0e7c5..e240cf5 100644 --- a/packages/agent-host/src/pi/pi-cli-rpc-process-lifecycle.spec.ts +++ b/packages/agent-host/src/pi/pi-cli-rpc-process-lifecycle.spec.ts @@ -1,7 +1,10 @@ import { EventEmitter } from "node:events"; import { PassThrough, Writable } from "node:stream"; import { describe, expect, it, vi } from "vitest"; -import { attachCliRpcProcessLifecycle } from "./pi-cli-rpc-process-lifecycle.js"; +import { + attachCliRpcProcessLifecycle, + MAX_STDERR_TAIL_CHARS, +} from "./pi-cli-rpc-process-lifecycle.js"; import { createExitError } from "./pi-cli-rpc-protocol.js"; class TestChildProcess extends EventEmitter { @@ -57,4 +60,31 @@ describe("attachCliRpcProcessLifecycle", () => { createExitError(9, null), ); }); + + it("appends a bounded stderr tail to the exit error as diagnostics", async () => { + const child = new TestChildProcess(); + const handleLine = vi.fn(); + const handleProcessFailure = vi.fn(); + + attachCliRpcProcessLifecycle({ + childProcess: child, + piCommand: "pi", + handleLine, + handleProcessFailure, + }); + + const noise = "n".repeat(MAX_STDERR_TAIL_CHARS * 2); + child.stderr.write(`${noise}fatal: model registry corrupted\n`); + child.emit("close", 1, null); + + expect(handleProcessFailure).toHaveBeenCalledOnce(); + const error = handleProcessFailure.mock.calls[0]?.[0] as Error; + expect(error.message).toContain("Pi CLI RPC process exited (1)"); + expect(error.message).toContain("fatal: model registry corrupted"); + // The retained diagnostics never exceed the tail bound (plus the + // exit message prefix). + expect(error.message.length).toBeLessThanOrEqual( + MAX_STDERR_TAIL_CHARS + 64, + ); + }); }); diff --git a/packages/agent-host/src/pi/pi-cli-rpc-process-lifecycle.ts b/packages/agent-host/src/pi/pi-cli-rpc-process-lifecycle.ts index 32fa5f8..3c2b557 100644 --- a/packages/agent-host/src/pi/pi-cli-rpc-process-lifecycle.ts +++ b/packages/agent-host/src/pi/pi-cli-rpc-process-lifecycle.ts @@ -38,6 +38,12 @@ function createProcessStartError(piCommand: string, error: Error): Error { ); } +// Only a bounded tail of the child's stderr is retained as diagnostics: +// enough to explain a crash, never enough to grow with a noisy process. +// Consuming stderr also keeps the pipe drained so the child cannot block +// on a full stderr buffer. +export const MAX_STDERR_TAIL_CHARS = 8_192; + export function attachCliRpcProcessLifecycle({ childProcess, piCommand, @@ -57,12 +63,23 @@ export function attachCliRpcProcessLifecycle({ } }); + let stderrTail = ""; + childProcess.stderr?.on("data", (chunk: string | Buffer) => { + stderrTail = (stderrTail + chunk.toString()).slice(-MAX_STDERR_TAIL_CHARS); + }); + childProcess.on("error", (error) => { handleProcessFailure(createProcessStartError(piCommand, error)); }); childProcess.on("close", (code, signal) => { - handleProcessFailure(createExitError(code, signal)); + const exitError = createExitError(code, signal); + const diagnostics = stderrTail.trim(); + handleProcessFailure( + diagnostics + ? new Error(`${exitError.message}: ${diagnostics}`) + : exitError, + ); }); } diff --git a/packages/agent-host/src/pi/pi-sdk-agent-runtime.spec.ts b/packages/agent-host/src/pi/pi-sdk-agent-runtime.spec.ts index 1a6ce61..c23688b 100644 --- a/packages/agent-host/src/pi/pi-sdk-agent-runtime.spec.ts +++ b/packages/agent-host/src/pi/pi-sdk-agent-runtime.spec.ts @@ -84,4 +84,85 @@ describe("PiSdkAgentRuntime", () => { expect(refresh).toHaveBeenCalledOnce(); expect(getAvailable).toHaveBeenCalledOnce(); }); + + it("shares one in-flight bootstrap across concurrent calls and stays starting until it succeeds", async () => { + let resolveSession!: (value: { session: unknown }) => void; + const sessionCreated = new Promise<{ session: unknown }>((resolve) => { + resolveSession = resolve; + }); + const session = { + sessionId: "session-shared", + messages: [], + subscribe: vi.fn(() => () => undefined), + }; + const createAgentSession = vi.fn(() => sessionCreated); + + const runtime = new PiSdkAgentRuntime({ + cwd: "/repo", + // @ts-expect-error - test double for the SDK session factory + createAgentSession, + createModelRegistry: () => ({ + refresh: vi.fn(), + getAvailable: vi.fn(() => []), + }), + createSettingsManager: () => ({ + getGlobalSettings: () => ({}), + getProjectSettings: () => ({}), + setDefaultProvider: () => undefined, + setDefaultModel: () => undefined, + }), + }); + + const first = runtime.bootstrap(); + const second = runtime.bootstrap(); + + expect(createAgentSession).toHaveBeenCalledOnce(); + expect(runtime.getSnapshot().status).toBe("starting"); + + resolveSession({ session }); + await expect(first).resolves.toBeUndefined(); + await expect(second).resolves.toBeUndefined(); + + expect(createAgentSession).toHaveBeenCalledOnce(); + expect(runtime.getSnapshot().status).toBe("ready"); + expect(runtime.getSnapshot().sessionId).toBe("session-shared"); + + // A later bootstrap is a no-op once the session exists. + await runtime.bootstrap(); + expect(createAgentSession).toHaveBeenCalledOnce(); + }); + + it("propagates bootstrap failure to all waiters and allows a retry", async () => { + const session = { + sessionId: "session-retry", + messages: [], + subscribe: vi.fn(() => () => undefined), + }; + const createAgentSession = vi + .fn() + .mockRejectedValueOnce(new Error("session create failed")) + .mockResolvedValue({ session }); + + const runtime = new PiSdkAgentRuntime({ + cwd: "/repo", + createAgentSession, + createModelRegistry: () => ({ + refresh: vi.fn(), + getAvailable: vi.fn(() => []), + }), + createSettingsManager: () => ({ + getGlobalSettings: () => ({}), + getProjectSettings: () => ({}), + setDefaultProvider: () => undefined, + setDefaultModel: () => undefined, + }), + }); + + await expect(runtime.bootstrap()).rejects.toThrow("session create failed"); + expect(runtime.getSnapshot().status).toBe("error"); + + await expect(runtime.bootstrap()).resolves.toBeUndefined(); + expect(runtime.getSnapshot().status).toBe("ready"); + expect(createAgentSession).toHaveBeenCalledTimes(2); + }); }); diff --git a/packages/agent-host/src/pi/pi-sdk-agent-runtime.ts b/packages/agent-host/src/pi/pi-sdk-agent-runtime.ts index 3aebef1..fc710db 100644 --- a/packages/agent-host/src/pi/pi-sdk-agent-runtime.ts +++ b/packages/agent-host/src/pi/pi-sdk-agent-runtime.ts @@ -65,6 +65,8 @@ export class PiSdkAgentRuntime { private session: AgentSession | null = null; + private bootstrapPromise: Promise | null = null; + private unsubscribeSession: (() => void) | null = null; private modelRegistry: ModelRegistryLike | null = null; @@ -143,16 +145,31 @@ export class PiSdkAgentRuntime { return; } - try { - const bootstrapped = await this.createSessionWiring(); + // Share one in-flight bootstrap: concurrent calls (for example a + // connect retry while session creation is still running) must not + // create duplicate sessions. The snapshot stays "starting" until the + // shared bootstrap actually succeeds; on failure every waiter gets + // the error and a later call may retry. + if (!this.bootstrapPromise) { + this.bootstrapPromise = (async () => { + try { + const bootstrapped = await this.createSessionWiring(); + + this.session = bootstrapped.session; + this.unsubscribeSession?.(); + this.unsubscribeSession = bootstrapped.unsubscribe; + this.snapshot = bootstrapped.snapshot; + } catch (error) { + this.setErrorState(error, ""); + throw error; + } + })(); + } - this.session = bootstrapped.session; - this.unsubscribeSession?.(); - this.unsubscribeSession = bootstrapped.unsubscribe; - this.snapshot = bootstrapped.snapshot; - } catch (error) { - this.setErrorState(error, ""); - throw error; + try { + await this.bootstrapPromise; + } finally { + this.bootstrapPromise = null; } } diff --git a/packages/agent-host/src/pi/pi-sdk-prompt-lifecycle.spec.ts b/packages/agent-host/src/pi/pi-sdk-prompt-lifecycle.spec.ts index 9fbcb32..f066c25 100644 --- a/packages/agent-host/src/pi/pi-sdk-prompt-lifecycle.spec.ts +++ b/packages/agent-host/src/pi/pi-sdk-prompt-lifecycle.spec.ts @@ -52,6 +52,7 @@ describe("createPiSdkPromptLifecycle", () => { expect(session.prompt).toHaveBeenCalledOnce(); expect(session.prompt).toHaveBeenCalledWith("hello", { signal: expect.any(AbortSignal), + preflightResult: expect.any(Function), }); expect(capturedSignal).toBeInstanceOf(AbortSignal); expect(refreshReadyState).toHaveBeenCalledOnce(); @@ -102,6 +103,118 @@ describe("createPiSdkPromptLifecycle", () => { expect(setErrorState).not.toHaveBeenCalled(); }); + it("resolves on preflight acceptance while the turn is still running", async () => { + const setStreamingState = vi.fn(); + const refreshReadyState = vi.fn(); + const setErrorState = vi.fn(); + const turnGate = createDeferred(); + let reportPreflight: ((success: boolean) => void) | undefined; + + const session = { + sessionId: "session-1", + prompt: vi.fn((_text: string, options?: object) => { + const preflight = options + ? Reflect.get(options, "preflightResult") + : undefined; + reportPreflight = + typeof preflight === "function" + ? (success: boolean) => preflight(success) + : undefined; + return turnGate.promise; + }), + }; + + const lifecycle = createPiSdkPromptLifecycle({ + getSession: () => session, + setStreamingState, + refreshReadyState, + setErrorState, + }); + + const promptPromise = lifecycle.prompt("hello"); + reportPreflight?.(true); + + // Acceptance resolves the call even though the turn has not finished. + await expect(promptPromise).resolves.toBeUndefined(); + expect(refreshReadyState).not.toHaveBeenCalled(); + expect(setErrorState).not.toHaveBeenCalled(); + + turnGate.resolve(undefined); + await vi.waitFor(() => { + expect(refreshReadyState).toHaveBeenCalledOnce(); + }); + expect(setErrorState).not.toHaveBeenCalled(); + }); + + it("records failures after acceptance as error state instead of rejecting the accepted call", async () => { + const setStreamingState = vi.fn(); + const refreshReadyState = vi.fn(); + const setErrorState = vi.fn(); + const turnGate = createDeferred(); + const failure = new Error("turn exploded"); + + const session = { + sessionId: "session-7", + prompt: vi.fn((_text: string, options?: object) => { + const preflight = options + ? Reflect.get(options, "preflightResult") + : undefined; + if (typeof preflight === "function") { + preflight(true); + } + return turnGate.promise; + }), + }; + + const lifecycle = createPiSdkPromptLifecycle({ + getSession: () => session, + setStreamingState, + refreshReadyState, + setErrorState, + }); + + await expect(lifecycle.prompt("hello")).resolves.toBeUndefined(); + + turnGate.reject(failure); + await vi.waitFor(() => { + expect(setErrorState).toHaveBeenCalledWith(failure, "session-7"); + }); + expect(refreshReadyState).not.toHaveBeenCalled(); + }); + + it("rejects when the prompt fails before preflight acceptance", async () => { + const setStreamingState = vi.fn(); + const refreshReadyState = vi.fn(); + const setErrorState = vi.fn(); + const failure = new Error("no model selected"); + + const session = { + sessionId: "session-9", + prompt: vi.fn(async (_text: string, options?: object) => { + const preflight = options + ? Reflect.get(options, "preflightResult") + : undefined; + if (typeof preflight === "function") { + preflight(false); + } + throw failure; + }), + }; + + const lifecycle = createPiSdkPromptLifecycle({ + getSession: () => session, + setStreamingState, + refreshReadyState, + setErrorState, + }); + + await expect(lifecycle.prompt("hello")).rejects.toThrow( + "no model selected", + ); + expect(setErrorState).toHaveBeenCalledWith(failure, "session-9"); + expect(refreshReadyState).not.toHaveBeenCalled(); + }); + it("records prompt failures with the current session id and rethrows the error", async () => { const error = new Error("prompt failed"); const setStreamingState = vi.fn(); diff --git a/packages/agent-host/src/pi/pi-sdk-prompt-lifecycle.ts b/packages/agent-host/src/pi/pi-sdk-prompt-lifecycle.ts index 5c03bd3..2513039 100644 --- a/packages/agent-host/src/pi/pi-sdk-prompt-lifecycle.ts +++ b/packages/agent-host/src/pi/pi-sdk-prompt-lifecycle.ts @@ -25,6 +25,15 @@ export const createPiSdkPromptLifecycle = ({ let promptAbortController: AbortController | null = null; return { + // Prompt acceptance is separated from turn completion: the returned + // promise resolves as soon as the SDK reports preflight acceptance + // (the same signal Pi's RPC mode uses to ack a prompt command) and + // rejects only when the prompt is refused before acceptance. The turn + // itself keeps running in the background; its progress and completion + // arrive through session events, and a failure after acceptance is + // recorded via setErrorState instead of rejecting a call that was + // already acknowledged. Callers must therefore never retry a prompt + // whose acceptance is uncertain — it may already be running. async prompt(text: string): Promise { const session = getSession(); @@ -39,22 +48,58 @@ export const createPiSdkPromptLifecycle = ({ const abortController = new AbortController(); promptAbortController = abortController; - try { - await session.prompt(text, { signal: abortController.signal }); - refreshReadyState(); - } catch (error) { - if (abortController.signal.aborted) { + let accepted = false; + let resolveAccepted!: () => void; + let rejectAccepted!: (error: unknown) => void; + const acceptance = new Promise((resolve, reject) => { + resolveAccepted = resolve; + rejectAccepted = reject; + }); + + const turn = (async (): Promise => { + try { + await session.prompt(text, { + signal: abortController.signal, + preflightResult: (success: boolean) => { + if (success && !accepted) { + accepted = true; + resolveAccepted(); + } + }, + }); refreshReadyState(); - return; + if (!accepted) { + // Sessions that never report preflight (test doubles, commands + // handled synchronously) accept by completing successfully. + accepted = true; + resolveAccepted(); + } + } catch (error) { + if (abortController.signal.aborted) { + refreshReadyState(); + if (!accepted) { + accepted = true; + resolveAccepted(); + } + return; + } + + setErrorState(error, session.sessionId); + if (!accepted) { + accepted = true; + rejectAccepted(error); + } + } finally { + if (promptAbortController === abortController) { + promptAbortController = null; + } } + })(); + // The turn's outcome is fully handled above (ready/error state); + // guard only against a state callback itself throwing. + turn.catch(() => undefined); - setErrorState(error, session.sessionId); - throw error; - } finally { - if (promptAbortController === abortController) { - promptAbortController = null; - } - } + return acceptance; }, async cancel(): Promise { diff --git a/packages/agent-host/src/session-server/socket-bridge.spec.ts b/packages/agent-host/src/session-server/socket-bridge.spec.ts new file mode 100644 index 0000000..f8fa7fc --- /dev/null +++ b/packages/agent-host/src/session-server/socket-bridge.spec.ts @@ -0,0 +1,227 @@ +import fs from "node:fs"; +import net from "node:net"; +import os from "node:os"; +import path from "node:path"; +import { afterEach, describe, expect, it, vi } from "vitest"; + +import type { CommandHandlerRuntime } from "../host/command-handler.js"; +import { + MAX_SOCKET_FRAME_CHARS, + parseAgentHostSocketRequest, + type SocketAgentHostRuntime, + startAgentHostSocketServer, +} from "./socket-bridge.js"; + +function makeRuntime( + overrides: Partial = {}, +): SocketAgentHostRuntime { + return { + bootstrap: vi.fn(async () => {}), + getProviders: vi.fn(async () => []), + getSettings: vi.fn(async () => ({})), + getSnapshot: vi.fn(() => ({ + sessionId: "s1", + status: "ready" as const, + messages: [], + lastError: null, + })), + switchModel: vi.fn(async () => {}), + prompt: vi.fn(async () => {}), + cancelPrompt: vi.fn(async () => {}), + reset: vi.fn(async () => {}), + subscribe: vi.fn(() => () => {}), + ...overrides, + }; +} + +describe("parseAgentHostSocketRequest", () => { + it("accepts a well-formed prompt request", () => { + const parsed = parseAgentHostSocketRequest( + JSON.stringify({ requestId: "r1", type: "prompt", text: "hello" }), + ); + + expect(parsed).toEqual({ + ok: true, + request: { requestId: "r1", type: "prompt", text: "hello" }, + }); + }); + + it("rejects invalid JSON with an unknown request id", () => { + expect(parseAgentHostSocketRequest("{nope")).toEqual({ + ok: false, + requestId: "unknown", + message: "Malformed agent host request: invalid JSON", + }); + }); + + it("rejects requests without a string requestId", () => { + const parsed = parseAgentHostSocketRequest( + JSON.stringify({ type: "bootstrap" }), + ); + + expect(parsed.ok).toBe(false); + if (!parsed.ok) { + expect(parsed.message).toContain("missing requestId"); + } + }); + + it("rejects unknown request types", () => { + const parsed = parseAgentHostSocketRequest( + JSON.stringify({ requestId: "r2", type: "rm -rf" }), + ); + + expect(parsed.ok).toBe(false); + if (!parsed.ok) { + expect(parsed.requestId).toBe("r2"); + expect(parsed.message).toContain("unknown type"); + } + }); + + it("rejects prompt requests whose text is not a string", () => { + const parsed = parseAgentHostSocketRequest( + JSON.stringify({ requestId: "r3", type: "prompt", text: 42 }), + ); + + expect(parsed.ok).toBe(false); + if (!parsed.ok) { + expect(parsed.message).toContain("prompt text must be a string"); + } + }); + + it("rejects switchModel requests without provider and model ids", () => { + const parsed = parseAgentHostSocketRequest( + JSON.stringify({ + requestId: "r4", + type: "switchModel", + request: { providerId: "google" }, + }), + ); + + expect(parsed.ok).toBe(false); + }); +}); + +describe("startAgentHostSocketServer", () => { + let server: Awaited> | null = + null; + let client: net.Socket | null = null; + let socketDirectory: string | null = null; + + afterEach(async () => { + client?.destroy(); + client = null; + await server?.close().catch(() => undefined); + server = null; + if (socketDirectory) { + fs.rmSync(socketDirectory, { recursive: true, force: true }); + socketDirectory = null; + } + }); + + async function connectAndCollect(runtime: SocketAgentHostRuntime) { + socketDirectory = fs.mkdtempSync(path.join(os.tmpdir(), "pd-sock-")); + const socketPath = path.join(socketDirectory, "agent.sock"); + server = await startAgentHostSocketServer({ socketPath, runtime }); + + const received: string[] = []; + let notify: (() => void) | null = null; + const waitForLines = (count: number) => + new Promise((resolve) => { + if (received.length >= count) { + resolve(); + return; + } + notify = () => { + if (received.length >= count) { + resolve(); + } + }; + }); + + client = net.createConnection(socketPath); + client.setEncoding("utf8"); + let buffer = ""; + client.on("data", (chunk) => { + buffer += chunk; + const lines = buffer.split("\n"); + buffer = lines.pop() ?? ""; + for (const line of lines) { + if (line.trim()) { + received.push(line); + } + } + notify?.(); + }); + await new Promise((resolve) => + client?.once("connect", () => resolve()), + ); + + return { received, waitForLines }; + } + + it("answers valid requests and rejects malformed frames with an error envelope", async () => { + const runtime = makeRuntime(); + const { received, waitForLines } = await connectAndCollect(runtime); + + client?.write(`${JSON.stringify({ requestId: "a", type: "bootstrap" })}\n`); + client?.write( + `${JSON.stringify({ requestId: "b", type: "prompt", text: 7 })}\n`, + ); + client?.write("not json\n"); + + await waitForLines(3); + + const envelopes = received.map( + (line) => JSON.parse(line) as Record, + ); + expect(envelopes).toContainEqual({ + type: "response", + response: { requestId: "a", kind: "ack" }, + }); + expect(envelopes).toContainEqual({ + type: "response", + response: { + requestId: "b", + kind: "error", + message: "Malformed agent host request: prompt text must be a string", + }, + }); + expect(envelopes).toContainEqual({ + type: "response", + response: { + requestId: "unknown", + kind: "error", + message: "Malformed agent host request: invalid JSON", + }, + }); + expect(runtime.prompt).not.toHaveBeenCalled(); + expect(runtime.bootstrap).toHaveBeenCalledOnce(); + }); + + // Moving a >16MiB frame through the socket is CPU-bound under test + // parallelism, so this case gets a longer timeout than the default. + it("destroys a connection whose unterminated frame exceeds the size bound", async () => { + const runtime = makeRuntime(); + const { received, waitForLines } = await connectAndCollect(runtime); + + const closed = new Promise((resolve) => + client?.once("close", () => resolve()), + ); + + client?.write("x".repeat(MAX_SOCKET_FRAME_CHARS + 1)); + + await waitForLines(1); + await closed; + + const envelope = JSON.parse(received[0] ?? "{}") as Record; + expect(envelope).toEqual({ + type: "response", + response: { + requestId: "unknown", + kind: "error", + message: "Agent host socket frame exceeded the maximum allowed size", + }, + }); + expect(runtime.bootstrap).not.toHaveBeenCalled(); + }, 30_000); +}); diff --git a/packages/agent-host/src/session-server/socket-bridge.ts b/packages/agent-host/src/session-server/socket-bridge.ts index 7066601..dfb111a 100644 --- a/packages/agent-host/src/session-server/socket-bridge.ts +++ b/packages/agent-host/src/session-server/socket-bridge.ts @@ -25,10 +25,122 @@ export interface AgentHostSocketServer { close(): Promise; } +// Inbound frames are bounded and validated before they reach the command +// handler: a peer that never sends a newline must not grow host memory +// without limit, and malformed payloads get an explicit error response +// instead of being cast to AgentHostRequest and crashing a runtime method. +export const MAX_SOCKET_FRAME_CHARS = 16 * 1024 * 1024; + +const AGENT_HOST_REQUEST_TYPES = new Set([ + "bootstrap", + "reset", + "getSnapshot", + "getProviders", + "getSettings", + "prompt", + "cancelPrompt", + "switchModel", +]); + +type ParsedSocketRequest = + | { ok: true; request: AgentHostRequest } + | { ok: false; requestId: string; message: string }; + +function isRecord(value: unknown): value is Record { + return typeof value === "object" && value !== null; +} + +export function parseAgentHostSocketRequest( + message: string, +): ParsedSocketRequest { + let parsed: unknown; + try { + parsed = JSON.parse(message) as unknown; + } catch { + return { + ok: false, + requestId: "unknown", + message: "Malformed agent host request: invalid JSON", + }; + } + + if (!isRecord(parsed)) { + return { + ok: false, + requestId: "unknown", + message: "Malformed agent host request: expected an object", + }; + } + + const requestId = + typeof parsed.requestId === "string" && parsed.requestId.length > 0 + ? parsed.requestId + : "unknown"; + + if (requestId === "unknown") { + return { + ok: false, + requestId, + message: "Malformed agent host request: missing requestId", + }; + } + + if ( + typeof parsed.type !== "string" || + !AGENT_HOST_REQUEST_TYPES.has(parsed.type) + ) { + return { + ok: false, + requestId, + message: `Malformed agent host request: unknown type ${String(parsed.type)}`, + }; + } + + if (parsed.type === "prompt" && typeof parsed.text !== "string") { + return { + ok: false, + requestId, + message: "Malformed agent host request: prompt text must be a string", + }; + } + + if (parsed.type === "switchModel") { + const request = parsed.request; + if ( + !isRecord(request) || + typeof request.providerId !== "string" || + typeof request.modelId !== "string" + ) { + return { + ok: false, + requestId, + message: + "Malformed agent host request: switchModel requires providerId and modelId strings", + }; + } + } + + return { ok: true, request: parsed as AgentHostRequest }; +} + function writeEnvelope(socket: net.Socket, envelope: AgentHostEnvelope): void { + if (socket.destroyed) { + return; + } socket.write(`${JSON.stringify(envelope)}\n`); } +function writeError( + socket: net.Socket, + requestId: string, + message: string, +): void { + writeEnvelope(socket, { + type: "response", + response: { requestId, kind: "error", message }, + }); +} + export async function startAgentHostSocketServer({ socketPath, runtime, @@ -43,41 +155,76 @@ export async function startAgentHostSocketServer({ const server = net.createServer((socket) => { sockets.add(socket); socket.setEncoding("utf8"); - let buffer = ""; + // Partial frames accumulate as chunks (joined only once a newline + // arrives) so a large frame costs linear, not quadratic, copying. + let bufferedChunks: string[] = []; + let bufferedLength = 0; socket.on("data", (chunk) => { - buffer += chunk; + const text = typeof chunk === "string" ? chunk : chunk.toString(); + bufferedChunks.push(text); + bufferedLength += text.length; + + if (bufferedLength > MAX_SOCKET_FRAME_CHARS) { + // No complete frame can be recovered from an over-limit buffer; + // report it and drop the connection so memory stays bounded. + bufferedChunks = []; + bufferedLength = 0; + const envelope: AgentHostEnvelope = { + type: "response", + response: { + requestId: "unknown", + kind: "error", + message: + "Agent host socket frame exceeded the maximum allowed size", + }, + }; + socket.write(`${JSON.stringify(envelope)}\n`, () => { + socket.destroy(); + }); + return; + } + + if (!text.includes("\n")) { + return; + } + + const buffer = bufferedChunks.join(""); + bufferedChunks = []; + bufferedLength = 0; const messages = buffer.split("\n"); - buffer = messages.pop() ?? ""; + const remainder = messages.pop() ?? ""; + if (remainder) { + bufferedChunks = [remainder]; + bufferedLength = remainder.length; + } for (const message of messages) { if (!message.trim()) { continue; } - let request: AgentHostRequest | null = null; - try { - request = JSON.parse(message) as AgentHostRequest; - } catch { + const parsed = parseAgentHostSocketRequest(message); + + if (!parsed.ok) { + writeError(socket, parsed.requestId, parsed.message); continue; } + const request = parsed.request; + void handleCommand(request) .then((envelope) => { writeEnvelope(socket, envelope); }) .catch((error) => { - writeEnvelope(socket, { - type: "response", - response: { - requestId: request?.requestId ?? "unknown", - kind: "error", - message: - error instanceof Error - ? error.message - : "Unknown agent host error", - }, - }); + writeError( + socket, + request.requestId, + error instanceof Error + ? error.message + : "Unknown agent host error", + ); }); } }); diff --git a/tests/integration/apps-desktop/agent-host-client.spec.ts b/tests/integration/apps-desktop/agent-host-client.spec.ts index 419192c..2f9c951 100644 --- a/tests/integration/apps-desktop/agent-host-client.spec.ts +++ b/tests/integration/apps-desktop/agent-host-client.spec.ts @@ -156,9 +156,9 @@ describe("createAgentHostClient", () => { try { const child = new FakeUtilityProcess(); const client = createAgentHostClient(child, { requestTimeoutMs: 25 }); - const promptPromise = client.prompt("Explain the active repository"); - const timeoutAssertion = expect(promptPromise).rejects.toThrow( - "Agent host request prompt timed out after 25ms", + const snapshotPromise = client.getSnapshot(); + const timeoutAssertion = expect(snapshotPromise).rejects.toThrow( + "Agent host request getSnapshot timed out after 25ms", ); await vi.advanceTimersByTimeAsync(25); @@ -169,6 +169,43 @@ describe("createAgentHostClient", () => { } }); + it("does not time out prompts: acceptance is separated from turn completion", async () => { + vi.useFakeTimers(); + + try { + const child = new FakeUtilityProcess(); + const client = createAgentHostClient(child, { requestTimeoutMs: 25 }); + + let settled = false; + const promptPromise = client.prompt("Explain the active repository").then( + () => { + settled = true; + }, + () => { + settled = true; + }, + ); + + // A long turn runs far past the generic request timeout; the prompt + // call must stay pending until the host acks acceptance (issue #9). + await vi.advanceTimersByTimeAsync(60_000); + expect(settled).toBe(false); + + child.emitMessage({ + type: "response", + response: { + requestId: "1", + kind: "ack", + }, + }); + + await promptPromise; + expect(settled).toBe(true); + } finally { + vi.useRealTimers(); + } + }); + it("forwards agent events to subscribers", () => { const child = new FakeUtilityProcess(); const client = createAgentHostClient(child);