Where agent teams gather. Cross-platform team chat where AI agents are first-class teammates — with cloud or bring-your-own (Claude Code / Codex) brains.
TypeScript
fix(byoa): a dead engine's stdin must not crash the daemon
Xialie Zhuang9784aff1a261
diff --git a/server/src/__tests__/engine-stdin-safety.test.ts b/server/src/__tests__/engine-stdin-safety.test.tsnew file mode 100644index 0000000..dbf2547--- /dev/null+++ b/server/src/__tests__/engine-stdin-safety.test.ts@@ -0,0 +1,80 @@+/**+ * Guard: no raw `child.stdin.write()` in the engine adapters.+ *+ * A failed pipe write — EPIPE, when the engine died or was killed mid-write —+ * is delivered ASYNCHRONOUSLY as an 'error' event on the stdin stream+ * (`afterWriteDispatched`, a tick later). The try/catch that used to wrap every+ * one of these writes had already returned by then and could not catch it, and+ * with no listener on the stream Node turns it into an uncaught exception.+ *+ * It surfaced as a flaky `write EPIPE` in PiAdapter.probeWake on CI — but every+ * adapter had the same hole, so this pins the whole file rather than that one+ * call site.+ *+ * Run: node --import tsx --test server/src/__tests__/engine-stdin-safety.test.ts+ */+import { test } from 'node:test'+import assert from 'node:assert/strict'+import { readFileSync } from 'node:fs'+import { fileURLToPath } from 'node:url'+import { dirname, join } from 'node:path'+import { PassThrough } from 'node:stream'++const ENGINE = join(dirname(fileURLToPath(import.meta.url)), '..', 'agents', 'computer', 'engine.ts')++/** Lines that write to a child's stdin directly, ignoring comments.+ *+ * `writeStdin` itself is the one legitimate writer — it is the helper that+ * attaches the listener first — so its body is excluded by slicing it out+ * rather than by a broad pattern that could also hide a real offender. */+function rawStdinWrites(source: string): string[] {+ const start = source.indexOf('function writeStdin(')+ let body = source+ if (start >= 0) {+ const end = source.indexOf('\n}', start)+ body = source.slice(0, start) + (end >= 0 ? source.slice(end) : '')+ }+ return body.split('\n')+ .map((l) => l.trim())+ .filter((l) => !l.startsWith('//') && !l.startsWith('*'))+ .filter((l) => /stdin[?!]?\.write\s*\(/.test(l))+}++test('every engine stdin write goes through the safe helper', () => {+ const offenders = rawStdinWrites(readFileSync(ENGINE, 'utf8'))+ assert.deepEqual(+ offenders, [],+ '\nA raw stdin write cannot be protected by try/catch — EPIPE arrives a tick\n' ++ 'later as a stream error and, unlistened, becomes an uncaught exception.\n' ++ 'Use writeStdin() instead:\n' + offenders.map((l) => ` ${l}`).join('\n'),+ )+})++test('the matcher would catch a raw write', () => {+ // Keeps the guard above from silently becoming a no-op.+ assert.equal(rawStdinWrites(' child.stdin?.write("x")').length, 1)+ assert.equal(rawStdinWrites(' this.child.stdin!.write(msg)').length, 1)+ assert.equal(rawStdinWrites(' // child.stdin?.write("x") — explained in prose').length, 0)+})++test('an async stream write error escapes try/catch but not a listener', () => {+ // The mechanism itself, so the reason for the guard is executable and not+ // just an assertion in a comment.+ return new Promise<void>((resolve, reject) => {+ const stream = new PassThrough()+ let caughtByTryCatch = false+ let caughtByListener = false+ stream.on('error', () => { caughtByListener = true })+ try {+ stream.write('x')+ setImmediate(() => stream.emit('error', Object.assign(new Error('write EPIPE'), { code: 'EPIPE' })))+ } catch { caughtByTryCatch = true }+ setTimeout(() => {+ try {+ assert.equal(caughtByTryCatch, false, 'the try/catch cannot see an error delivered on a later tick')+ assert.equal(caughtByListener, true, 'only a stream listener sees it')+ resolve()+ } catch (e) { reject(e) }+ }, 50)+ })+})diff --git a/server/src/agents/computer/engine.ts b/server/src/agents/computer/engine.tsindex 3e8bf6d..a0317ee 100644--- a/server/src/agents/computer/engine.ts+++ b/server/src/agents/computer/engine.ts@@ -426,6 +426,39 @@ function failurePreview(args: {return detail ? `${prefix}\n${detail}`.slice(0, MAX_FAILURE_CHARS) : prefix}+/** Write to an engine's stdin without letting a dead pipe crash the process.+ *+ * Every stdin write in this file was wrapped in a try/catch whose comment said+ * the child's own error/close path would report the failure. That is not what+ * happens. A failed pipe write — EPIPE, when the engine died or was killed+ * mid-write — is delivered ASYNCHRONOUSLY as an 'error' event on the stdin+ * stream (`afterWriteDispatched`, a tick later), so the try/catch has already+ * returned and cannot catch it. With no listener on the stream, Node turns it+ * into an uncaught exception. It surfaced as a flaky `write EPIPE` failure in+ * PiAdapter.probeWake on CI, but every adapter had the same hole.+ *+ * A dead engine is ordinary: the operator quit the CLI, a turn was aborted,+ * doctor tore its probe down. The child's own 'error'/'close' handlers already+ * report it, so the stream error is noise — it just must not be UNHANDLED.+ *+ * Returns false when the write could not even be attempted, so callers that+ * care can bail; the ones that don't already fall through to their close path. */+function writeStdin(child: ChildProcess, text: string, opts: { end?: boolean } = {}): boolean {+ const stdin = child.stdin+ if (!stdin) return false+ // Attach once per stream — repeated writes must not stack listeners.+ if (stdin.listenerCount('error') === 0) {+ stdin.on('error', () => { /* reported by the child's own close/error path */ })+ }+ try {+ stdin.write(text)+ if (opts.end) stdin.end()+ return true+ } catch {+ return false+ }+}+function spawnEngine(bin: string,args: string[],@@ -439,7 +472,7 @@ function spawnEngine(shell: spawnOpts.shell ?? false,})if (spawnOpts.stdinText != null) {- try { child.stdin?.write(spawnOpts.stdinText); child.stdin?.end() } catch { /* the 'error' handler resolves */ }+ writeStdin(child, spawnOpts.stdinText, { end: true })}const onAbort = (): void => { child.kill('SIGTERM') }signal.addEventListener('abort', onAbort, { once: true })@@ -563,7 +596,7 @@ function spawnCapture(shell: shell ?? false,})if (stdinText != null) {- try { child.stdin?.write(stdinText); child.stdin?.end() } catch { /* the 'error' handler resolves */ }+ writeStdin(child, stdinText, { end: true })}const onAbort = (): void => { child.kill('SIGTERM') }signal.addEventListener('abort', onAbort, { once: true })@@ -718,10 +751,8 @@ class ClaudeSession implements EngineSession {this.pendingTimer.unref?.()}const msg = JSON.stringify({ type: 'user', message: { role: 'user', content: [{ type: 'text', text: stripLoneSurrogates(prompt) }] } }) + '\n'- try {- this.child.stdin!.write(msg)- } catch (err) {- this.settle({ exitCode: 1, error: `failed to write turn to engine: ${err instanceof Error ? err.message : String(err)}`, sessionId: this.sid })+ if (!writeStdin(this.child, msg)) {+ this.settle({ exitCode: 1, error: 'failed to write turn to engine (stdin closed)', sessionId: this.sid })}})}@@ -744,9 +775,7 @@ class ClaudeSession implements EngineSession {if (!this.pending || !this.alive) returnwhile (this.steerQueue.length > 0) {const text = this.steerQueue.shift()!- try {- this.child.stdin!.write(JSON.stringify({ type: 'user', message: { role: 'user', content: [{ type: 'text', text: stripLoneSurrogates(text) }] } }) + '\n')- } catch { break }+ if (!writeStdin(this.child, JSON.stringify({ type: 'user', message: { role: 'user', content: [{ type: 'text', text: stripLoneSurrogates(text) }] } }) + '\n')) break}}@@ -1137,10 +1166,8 @@ class CodexSession implements EngineSession {steer(text: string): void {if (!this.alive || !text.trim() || !this.threadId || !this.activeTurnId || this.steerGate) return- try {- this.child.stdin!.write(JSON.stringify({ jsonrpc: '2.0', id: this.nextId(), method: 'turn/steer',- params: { threadId: this.threadId, expectedTurnId: this.activeTurnId, input: [{ type: 'text', text: stripLoneSurrogates(text) }] } }) + '\n')- } catch { /* best-effort */ }+ writeStdin(this.child, JSON.stringify({ jsonrpc: '2.0', id: this.nextId(), method: 'turn/steer',+ params: { threadId: this.threadId, expectedTurnId: this.activeTurnId, input: [{ type: 'text', text: stripLoneSurrogates(text) }] } }) + '\n')}stop(): void {@@ -1152,11 +1179,11 @@ class CodexSession implements EngineSession {private nextId(): number { this.reqId += 1; return this.reqId }private req(method: string, params: Record<string, unknown>): number {const id = this.nextId()- try { this.child.stdin?.write(JSON.stringify({ jsonrpc: '2.0', id, method, params }) + '\n') } catch { /* die() handles */ }+ writeStdin(this.child, JSON.stringify({ jsonrpc: '2.0', id, method, params }) + '\n')return id}private notify(method: string, params: Record<string, unknown>): void {- try { this.child.stdin?.write(JSON.stringify({ jsonrpc: '2.0', method, params }) + '\n') } catch { /* die() handles */ }+ writeStdin(this.child, JSON.stringify({ jsonrpc: '2.0', method, params }) + '\n')}private startTurn(prompt: string): void {if (this.threadId) {@@ -1413,7 +1440,7 @@ class CodexAdapter implements EngineAdapter {let initialized = falselet threadAcked = falseconst writeRpc = (msg: object) => {- try { child.stdin?.write(JSON.stringify(msg) + '\n') } catch { /* die path handles */ }+ writeStdin(child, JSON.stringify(msg) + '\n')}// Kick off the handshake once the process is up. spawn() emits stdout// 'data' lazily — that's the point at which we know the child is alive@@ -1615,7 +1642,7 @@ class GrokSession implements EngineSession {private nextId(): number { this.reqId += 1; return this.reqId }private req(method: string, params: Record<string, unknown>): number {const id = this.nextId()- try { this.child.stdin?.write(JSON.stringify({ jsonrpc: '2.0', id, method, params }) + '\n') } catch { /* die() */ }+ writeStdin(this.child, JSON.stringify({ jsonrpc: '2.0', id, method, params }) + '\n')return id}@@ -1850,7 +1877,7 @@ class GrokAdapter implements EngineAdapter {const sessionId = 2let initialized = falseconst writeRpc = (msg: object) => {- try { child.stdin?.write(JSON.stringify(msg) + '\n') } catch { /* die */ }+ writeStdin(child, JSON.stringify(msg) + '\n')}writeRpc({jsonrpc: '2.0', id: initId, method: 'initialize',@@ -2099,7 +2126,7 @@ function spawnCursorStream(shell: opts.shell,})if (opts.stdinText != null) {- try { child.stdin?.write(opts.stdinText); child.stdin?.end() } catch { /* the 'error' handler resolves */ }+ writeStdin(child, opts.stdinText, { end: true })}const onAbort = (): void => { child.kill('SIGTERM') }opts.signal.addEventListener('abort', onAbort, { once: true })@@ -2872,7 +2899,7 @@ function spawnPiJson(shell: opts.shell,})if (opts.stdinText != null) {- try { child.stdin?.write(opts.stdinText); child.stdin?.end() } catch { /* the 'error' handler resolves */ }+ writeStdin(child, opts.stdinText, { end: true })}const onAbort = (): void => { child.kill('SIGTERM') }opts.signal.addEventListener('abort', onAbort, { once: true })@@ -3018,7 +3045,7 @@ class PiSession implements EngineSession {}private write(msg: object): boolean {- try { this.child.stdin!.write(`${JSON.stringify(msg)}\n`); return true } catch { return false }+ return writeStdin(this.child, `${JSON.stringify(msg)}\n`)}private onStdout(buf: Buffer): void {@@ -3186,7 +3213,7 @@ class PiAdapter implements EngineAdapter {args.signal.addEventListener('abort', onAbort, { once: true })let buf = ''let stderrTail = ''- try { child.stdin?.write(`${JSON.stringify({ id: 'doctor', type: 'get_state' })}\n`) } catch { /* close handler reports */ }+ writeStdin(child, `${JSON.stringify({ id: 'doctor', type: 'get_state' })}\n`)child.stdout?.on('data', (b: Buffer) => {buf += b.toString('utf8')for (;;) {