The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
fix(provider): contain child stdin errors (#2490)
0xken15f0c71d6fa183
diff --git a/provider/example-provider/src/claude.ts b/provider/example-provider/src/claude.tsindex d3bf5bb08..7164a2de0 100644--- a/provider/example-provider/src/claude.ts+++ b/provider/example-provider/src/claude.ts@@ -28,8 +28,8 @@ export interface TurnOptions {}export interface TurnHandle {- /** Resolves when the process exits. Never rejects — a failure is reported through `onLine`. */- done: Promise<{ code: number | null; killed: boolean }>+ /** Resolves on exit. CLI failures arrive through `onLine`; input delivery failures set `inputError`. */+ done: Promise<{ code: number | null; killed: boolean; inputError?: string }>kill: () => void}@@ -63,6 +63,7 @@ export function runTurn(opts: TurnOptions, onLine: (line: StreamLine) => void, o})let killed = false+ let inputError: string | undefinedconst kill = (): void => {if (killed || child.exitCode !== null) returnkilled = true@@ -70,6 +71,13 @@ export function runTurn(opts: TurnOptions, onLine: (line: StreamLine) => void, o}opts.signal?.addEventListener('abort', kill, { once: true })+ const failInput = (err: Error): void => {+ inputError = `could not write input to claude: ${err.message}`+ // A broken pipe is an execution failure, not a user cancellation.+ killGroup(child)+ }+ child.stdin?.on('error', failInput)+if (child.stdout) {const rl = createInterface({ input: child.stdout, crlfDelay: Infinity })rl.on('line', (raw) => {@@ -92,17 +100,17 @@ export function runTurn(opts: TurnOptions, onLine: (line: StreamLine) => void, otry {child.stdin?.write(`${JSON.stringify({ type: 'user', message: { role: 'user', content: [{ type: 'text', text: opts.text }] } })}\n`)child.stdin?.end()- } catch {- kill()+ } catch (err) {+ failInput(err instanceof Error ? err : new Error(String(err)))}- const done = new Promise<{ code: number | null; killed: boolean }>((resolve) => {+ const done = new Promise<{ code: number | null; killed: boolean; inputError?: string }>((resolve) => {let settled = falseconst finish = (code: number | null): void => {if (settled) returnsettled = trueopts.signal?.removeEventListener('abort', kill)- resolve({ code, killed })+ resolve({ code, killed, ...(inputError ? { inputError } : {}) })}child.on('close', finish)child.on('error', () => finish(null))diff --git a/provider/example-provider/src/recap.ts b/provider/example-provider/src/recap.tsindex 2b48c39e2..3816610ef 100644--- a/provider/example-provider/src/recap.ts+++ b/provider/example-provider/src/recap.ts@@ -127,11 +127,16 @@ function oneShot(opts: SummariseOptions): Promise<string> {if (code === 0) resolve(out)else reject(new Error(`claude exited ${code}`))})+ const failInput = (err: Error): void => {+ clearTimeout(timer)+ child.kill('SIGKILL')+ reject(err)+ }+ child.stdin?.on('error', failInput)try {child.stdin?.end(`${PROMPT}${opts.turnText.slice(0, 50_000)}\n`)} catch (err) {- clearTimeout(timer)- reject(err)+ failInput(err instanceof Error ? err : new Error(String(err)))}})}diff --git a/provider/example-provider/src/server.ts b/provider/example-provider/src/server.tsindex 1beb3aa8d..268d5a8a6 100644--- a/provider/example-provider/src/server.ts+++ b/provider/example-provider/src/server.ts@@ -211,7 +211,7 @@ async function agentSend(res: ServerResponse, deps: Deps, params: Record<string,(chunk) => { stderr += chunk },)- const { killed } = await handle.done+ const { killed, inputError } = await handle.donedeps.running.delete(turnId)// Exactly one terminal frame on EVERY stream. A process that dies without emitting@@ -220,6 +220,8 @@ async function agentSend(res: ServerResponse, deps: Deps, params: Record<string,let terminal: ProviderEvent = { kind: 'turn_completed' }if (killed) {terminal = { kind: 'turn_cancelled' }+ } else if (inputError) {+ terminal = { kind: 'turn_failed', error: { code: 'internal', message: inputError } }} else if (failed) {terminal = { kind: 'turn_failed', error: { code: 'internal', message: failDetail ?? 'claude reported an error' } }} else if (!sawResult) {diff --git a/provider/example-provider/src/stdin.spec.ts b/provider/example-provider/src/stdin.spec.tsnew file mode 100644index 000000000..a2e6db390--- /dev/null+++ b/provider/example-provider/src/stdin.spec.ts@@ -0,0 +1,86 @@+/** A child that refuses stdin must fail its operation, not crash the provider process. */+import { execFileSync } from 'node:child_process'+import { chmodSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join, resolve } from 'node:path'+import { afterAll, beforeAll, describe, expect, it } from 'vitest'++const root = mkdtempSync(join(tmpdir(), 'provider-stdin-'))+const claudeBin = join(root, 'early-exit.sh')++beforeAll(() => {+ writeFileSync(claudeBin, '#!/bin/sh\nexit 1\n')+ chmodSync(claudeBin, 0o755)+})+afterAll(() => rmSync(root, { recursive: true, force: true }))++// Isolate the provider code in a process: an unhandled stream error must really+// exit that process, rather than being swallowed by the test runner's handlers.+function run(code: string): unknown {+ return JSON.parse(execFileSync(process.execPath, ['--import', 'tsx', '--input-type=module', '-e', code], {+ cwd: resolve(import.meta.dirname, '..'),+ encoding: 'utf8',+ timeout: 5_000,+ }))+}++describe('closed child stdin', () => {+ it('finishes a failed turn without treating it as a user cancellation', () => {+ const result = run(`+ import { runTurn } from ${JSON.stringify(new URL('./claude.js', import.meta.url).href)};+ const handle = runTurn({+ claudeBin: ${JSON.stringify(claudeBin)}, cwd: ${JSON.stringify(root)},+ text: 'x'.repeat(512 * 1024),+ }, () => {});+ console.log(JSON.stringify(await handle.done));+ `) as { code: number | null; killed: boolean; inputError?: string }+ expect(result.killed).toBe(false)+ expect(result.code).not.toBe(0)+ expect(result.inputError).toContain('EPIPE')+ })++ it('falls back to an excerpt when the recap process refuses its input', () => {+ const result = run(`+ import { summariseTurn } from ${JSON.stringify(new URL('./recap.js', import.meta.url).href)};+ const recap = await summariseTurn({+ claudeBin: ${JSON.stringify(claudeBin)}, cwd: ${JSON.stringify(root)},+ turnText: 'Result. ' + '結'.repeat(50_000),+ });+ console.log(JSON.stringify(recap));+ `) as { recap: string; body: string }+ expect(result.recap).toBe('Result.')+ expect(result.body).toContain('Result. 結')+ })++ it('reports turn_failed over HTTP and keeps serving other requests', () => {+ const result = run(`+ import { createProviderServer } from ${JSON.stringify(new URL('./server.js', import.meta.url).href)};+ const { server } = createProviderServer({+ agents: [{ id: 'fixture', name: 'Fixture', cwd: ${JSON.stringify(root)} }],+ workspaceRoot: ${JSON.stringify(root)}, agentsFile: ${JSON.stringify(join(root, 'agents.json'))},+ claudeBin: ${JSON.stringify(claudeBin)}, port: 0,+ stateFile: ${JSON.stringify(join(root, 'state.json'))},+ claudeProjectsDir: ${JSON.stringify(join(root, 'projects'))}, recapDisabled: true,+ });+ await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));+ const url = 'http://127.0.0.1:' + server.address().port;+ const rpc = (method, params) => fetch(url, {+ method: 'POST', headers: { authorization: 'Bearer fixture', 'content-type': 'application/json' },+ body: JSON.stringify({ jsonrpc: '2.0', id: 1, method, params }),+ });+ try {+ const response = await rpc('agent.send', {+ agentId: 'fixture', turnId: 'fixture-turn', message: { text: 'x'.repeat(512 * 1024) },+ });+ const stream = await response.text();+ const list = await (await rpc('agent.list', {})).json();+ console.log(JSON.stringify({ stream, agents: list.result.agents }));+ } finally {+ await new Promise(resolve => server.close(resolve));+ }+ `) as { stream: string; agents: Array<{ id: string }> }+ expect(result.stream).toContain('"kind":"turn_failed"')+ expect(result.stream).not.toContain('"kind":"turn_cancelled"')+ expect(result.agents.map(agent => agent.id)).toEqual(['fixture'])+ })+})