diff --git a/packages/server/src/server/agent/providers/acp-agent.ts b/packages/server/src/server/agent/providers/acp-agent.ts index e26b6e4ade..d2973d42c7 100644 --- a/packages/server/src/server/agent/providers/acp-agent.ts +++ b/packages/server/src/server/agent/providers/acp-agent.ts @@ -142,14 +142,26 @@ function assertChildWithPipes( } } -// Node reports a failed spawn (missing binary or missing cwd) as a child -// `error` event; without a listener it becomes an uncaught exception. -function rejectOnSpawnError(child: ChildProcess, stderrChunks: string[]): Promise { +// Watch process failures as well as spawn errors: the SDK leaves initialize +// pending when the child exits without replying. `close` waits for stderr to +// drain, so the failure includes the launcher's diagnostic. +function rejectOnProcessFailure(child: ChildProcess, stderrChunks: string[]): Promise { return new Promise((_, reject) => { child.once("error", (error) => { const stderr = stderrChunks.join("").trim(); reject(new Error(stderr ? `${String(error)}\n${stderr}` : String(error))); }); + child.once("close", (code, signal) => { + const stderr = stderrChunks.join("").trim(); + const status = signal ? `signal ${signal}` : `exit code ${code ?? "unknown"}`; + reject( + new Error( + `ACP agent process exited before initialization completed (${status})${ + stderr ? `\n${stderr}` : "" + }`, + ), + ); + }); }); } @@ -542,7 +554,7 @@ interface ACPProcessTransport { connection: ClientSideConnection; stderrChunks: string[]; spawnReady: Promise; - spawnError: Promise; + processError: Promise; } interface ACPImportPromptPreviews { @@ -1380,6 +1392,7 @@ export class ACPAgentClient implements AgentClient { client?: ACPClient; }, ): Promise { + const configuredOptions = ACPProviderOptionsSchema.parse(options?.providerOptions ?? {}); const transport = await this.spawnTransport(launchEnv, options?.client); const probe: UninitializedACPProcess = { child: transport.child, @@ -1391,7 +1404,7 @@ export class ACPAgentClient implements AgentClient { const initialize = await this.initializeTransport( transport, options?.initializeTimeoutMs, - options?.providerOptions, + configuredOptions.clientCapabilities, ); const initializedProbe: SpawnedACPProcess = { ...probe, @@ -1425,7 +1438,7 @@ export class ACPAgentClient implements AgentClient { stderrChunks.push(chunk.toString()); }); - const spawnErrorPromise = rejectOnSpawnError(child, stderrChunks); + const processErrorPromise = rejectOnProcessFailure(child, stderrChunks); const spawnReadyPromise = new Promise((resolve) => { child.once("spawn", () => { resolve(); @@ -1444,16 +1457,15 @@ export class ACPAgentClient implements AgentClient { connection, stderrChunks, spawnReady: spawnReadyPromise, - spawnError: spawnErrorPromise, + processError: processErrorPromise, }; } protected async initializeTransport( transport: ACPProcessTransport, initializeTimeoutMs?: number, - providerOptions?: Record, + clientCapabilities?: ACPClientCapabilities, ): Promise { - const configuredOptions = ACPProviderOptionsSchema.parse(providerOptions ?? {}); let timeout: ReturnType | null = null; const initializeTimeoutPromise = initializeTimeoutMs ? new Promise((_, reject) => { @@ -1470,11 +1482,11 @@ export class ACPAgentClient implements AgentClient { protocolVersion: PROTOCOL_VERSION, clientCapabilities: buildACPClientCapabilities( this.clientCapabilityMeta, - configuredOptions.clientCapabilities ?? this.clientCapabilities, + clientCapabilities ?? this.clientCapabilities, ), clientInfo: { name: "Paseo", version: "dev" }, }), - transport.spawnError, + transport.processError, ...(initializeTimeoutPromise ? [initializeTimeoutPromise] : []), ]), ); @@ -1555,7 +1567,7 @@ export class ACPAgentClient implements AgentClient { try { transport = await this.spawnTransport(PROBE_ENV); await withTimeout( - Promise.race([transport.spawnReady, transport.spawnError]), + Promise.race([transport.spawnReady, transport.processError]), phaseTimeoutMs, `ACP spawn timed out after ${phaseTimeoutMs}ms`, ); @@ -2910,7 +2922,7 @@ export class ACPAgentSession implements AgentSession, ACPClient { child.stderr.on("data", (chunk: Buffer | string) => { stderrChunks.push(chunk.toString()); }); - const spawnError = rejectOnSpawnError(child, stderrChunks); + const processError = rejectOnProcessFailure(child, stderrChunks); child.once("exit", (code, signal) => { if (this.closed || this.historyRuntimeReleased) { return; @@ -2947,7 +2959,7 @@ export class ACPAgentSession implements AgentSession, ACPClient { ), clientInfo: { name: "Paseo", version: "dev" }, }), - spawnError, + processError, ]), ); diff --git a/packages/server/src/server/agent/providers/acp-startup-exit.test.ts b/packages/server/src/server/agent/providers/acp-startup-exit.test.ts new file mode 100644 index 0000000000..39ae6f743e --- /dev/null +++ b/packages/server/src/server/agent/providers/acp-startup-exit.test.ts @@ -0,0 +1,112 @@ +import { execFile } from "node:child_process"; +import { promisify } from "node:util"; +import { describe, expect, test } from "vitest"; + +import { GenericACPAgentClient } from "./generic-acp-agent.js"; +import { createTestLogger } from "../../../test-utils/test-logger.js"; + +// Exercise the public catalog API with a real child, including stdout EOF and +// stderr draining. No provider installation or external service is involved. +const failingCommand: [string, ...string[]] = [ + process.execPath, + "-e", + "process.stdin.once('data', () => { process.stderr.write('launcher failed: fixture startup error\\n'); process.exitCode = 1; process.stdin.destroy(); });", +]; + +describe("ACP catalog startup failures", () => { + test("reports a process that exits during initialize with its stderr", async () => { + const client = new GenericACPAgentClient({ + logger: createTestLogger(), + command: failingCommand, + }); + await expect( + client.fetchCatalog({ scope: "workspace", cwd: process.cwd(), force: true }), + ).rejects.toThrow(/launcher failed: fixture startup error/); + }, 5_000); + + test("session startup reports the same process exit with its stderr", async () => { + const client = new GenericACPAgentClient({ + logger: createTestLogger(), + command: failingCommand, + }); + await expect(client.createSession({ provider: "acp", cwd: process.cwd() })).rejects.toThrow( + /launcher failed: fixture startup error/, + ); + }, 5_000); + + test("provider diagnostics report the startup exit instead of an initialize timeout", async () => { + const client = new GenericACPAgentClient({ + logger: createTestLogger(), + command: failingCommand, + diagnosticPhaseTimeoutMs: 2_000, + }); + const { diagnostic } = await client.getDiagnostic(); + expect(diagnostic).toContain( + "ACP agent process exited before initialization completed (exit code 1)", + ); + expect(diagnostic).toContain("launcher failed: fixture startup error"); + expect(diagnostic).not.toContain("initialize timed out"); + }); + + test("invalid provider options reject without crashing the host process", async () => { + const clientModule = new URL("./generic-acp-agent.ts", import.meta.url).href; + const loggerModule = new URL("../../../test-utils/test-logger.ts", import.meta.url).href; + const script = ` + import { GenericACPAgentClient } from ${JSON.stringify(clientModule)}; + import { createTestLogger } from ${JSON.stringify(loggerModule)}; + const client = new GenericACPAgentClient({ + logger: createTestLogger(), + command: [process.execPath, '-e', 'setInterval(() => {}, 1000)'], + }); + try { + await client.fetchCatalog({ + scope: 'workspace', cwd: process.cwd(), force: true, + providerOptions: { clientCapabilities: { fs: 'invalid' } }, + }); + throw new Error('Expected invalid options to reject'); + } catch (error) { + if (error.name !== 'ZodError') throw error; + } + // Let child cleanup and Node's unhandled-rejection check complete. + await new Promise(resolve => setTimeout(resolve, 100)); + console.log('host stayed alive'); + `; + const result = await promisify(execFile)( + process.execPath, + ["--import", "tsx", "--input-type=module", "-e", script], + { timeout: 10_000 }, + ); + expect(result.stdout).toContain("host stayed alive"); + expect(result.stderr).toBe(""); + }); + + test("a successful catalog probe still returns its models and closes cleanly", async () => { + const client = new GenericACPAgentClient({ + logger: createTestLogger(), + command: [ + process.execPath, + "-e", + ` + require('node:readline').createInterface({ input: process.stdin }).on('line', (line) => { + const request = JSON.parse(line); + const result = request.method === 'initialize' + ? { protocolVersion: 1, agentCapabilities: {} } + : { sessionId: 'fixture', models: { + currentModelId: 'fixture-model', + availableModels: [{ modelId: 'fixture-model', name: 'Fixture model' }] + } }; + process.stdout.write(JSON.stringify({ jsonrpc: '2.0', id: request.id, result }) + '\\n'); + }); + `, + ], + }); + const catalog = await client.fetchCatalog({ + scope: "workspace", + cwd: process.cwd(), + force: true, + }); + expect(catalog.models).toEqual([ + expect.objectContaining({ id: "fixture-model", label: "Fixture model" }), + ]); + }); +});