Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: stop a dead agent CLI's stdin pipe from killing the server (#5655)
Adam Eivy0633e21e0a3e
diff --git a/server/cos-runner/index.js b/server/cos-runner/index.jsindex c861045588..cf58a7a74c 100644--- a/server/cos-runner/index.js+++ b/server/cos-runner/index.js@@ -17,7 +17,7 @@ import { existsSync } from 'fs';import http from 'http';import { Server as SocketServer } from 'socket.io';import { ensureDir, PATHS, sleep, watchForFile } from '../lib/fileUtils.js';-import { prepareCliSpawn, killProcessTree } from '../lib/bufferedSpawn.js';+import { prepareCliSpawn, killProcessTree, guardChildStdin } from '../lib/bufferedSpawn.js';import { buildCliChildEnv } from '../lib/cliChildEnv.js';import { prepareCliPrompt } from '../lib/cliProviderArgs.js';import { commandExists } from '../lib/commandExists.js';@@ -506,10 +506,20 @@ app.post('/spawn', async (req, res) => {workspacePath: cwd});+ // Guard the stdin pipe BEFORE writing: a child that exits before reading it+ // (bad flag, missing CLI) emits EPIPE, and an unlistened stream 'error' out+ // here crashes the runner process. The 'error'/'close' handlers settle the run.+ guardChildStdin(claudeProcess);+// Send prompt via stdin (skipped when the prompt was delivered via argv —// antigravity's --print value, or grok's Windows temp file).- if (useStdin) claudeProcess.stdin.write(prompt);- claudeProcess.stdin.end();+ try {+ if (useStdin) claudeProcess.stdin.write(prompt);+ claudeProcess.stdin.end();+ } catch {+ // Synchronous write failure (already-destroyed stdin) — the 'error'/'close'+ // handler settles the run with the real cause.+ }// Handle stdoutclaudeProcess.stdout.on('data', (data) => {diff --git a/server/cos-runner/index.test.js b/server/cos-runner/index.test.jsindex 51eadc7cd8..d696d01cc4 100644--- a/server/cos-runner/index.test.js+++ b/server/cos-runner/index.test.js@@ -79,7 +79,10 @@ describe('cos-runner termination', () => {// those for real; all this file pins is that index.js delegates to both// rather than hand-rolling either.it('kills only through the shared killProcessTree helper', () => {- expect(RUNNER_SRC).toContain("import { prepareCliSpawn, killProcessTree } from '../lib/bufferedSpawn.js';");+ // Matched as "killProcessTree is on the bufferedSpawn import line" rather than+ // as the exact line text — pinning the whole specifier list made an unrelated+ // helper import (guardChildStdin, #5655) fail a kill-path assertion.+ expect(RUNNER_SRC).toMatch(/^import \{[^}]*\bkillProcessTree\b[^}]*\} from '\.\.\/lib\/bufferedSpawn\.js';$/m);// A BARE `.kill()` is still fine — the sentinel watcher closes a finished// TUI session that way, and a bare kill is the one form node-pty accepts// on every platform. What must not reappear is a hand-rolled signal kill.diff --git a/server/lib/README.md b/server/lib/README.mdindex ca562e8659..c5f9e2bf7f 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -265,7 +265,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `interactiveShellResolver.js` | `resolveInteractiveShell()` — picks the shell binary a PTY session runs (Shell page, agent TUI shells). On Windows the old `COMSPEC` default meant `cmd.exe`, where no command a user would type reaches another drive: `cd I:` silently PRINTS that drive's cwd and stays put, a bare `I:\` is "not recognized as a command", and `cd 'I:\path'` is a syntax error (no single-quote quoting) — so a Windows install with its repos on a second drive was stuck on `C:`. Resolves PORTOS_SHELL → newest `pwsh.exe` under `%ProgramFiles%\PowerShell\<major>` (majors enumerated and sorted numerically, so a future 8 needs no code change) → any `pwsh.exe` on PATH via `findCommandOnPath` (scoop/choco/Store shim) → `powershell.exe` 5.1 (ships with Windows) → `cmd.exe` last. PowerShell crosses drives with every form. Unchanged on POSIX (`SHELL` → zsh). `resolveInteractiveShellWith({platform, env, exists, readdir, findOnPath})` is the un-memoized injectable form for tests. || `openFolder.js` | `openFolderInSystemExplorer(localPath)` — cross-platform "open in Finder/Explorer/Nautilus" via detached spawn; child `error` handler prevents spawn failures from crashing the process. || `childProcess.js` | Drop-in `child_process` replacement that defaults every spawn to `windowsHide: true` — `spawn` / `spawnSync` / `fork` / `exec` / `execSync` / `execFile` / `execFileSync`, plus a `ChildProcess` re-export. **Server runtime code must import from here, never from `child_process` directly** (enforced by `childProcess.guards.test.js`): a console-less PM2 fork spawning a console child without `CREATE_NO_WINDOW` makes Windows hand the new console to Windows Terminal, which flashes a focus-stealing window. `exec`/`execFile` carry `util.promisify.custom` so `promisify(execFile)` still resolves to `{ stdout, stderr }`. An explicit `windowsHide: false` is respected. Background: `docs/WINDOWS_CONSOLE.md`. |-| `bufferedSpawn.js` | `bufferedSpawn(cmd, args, opts)` (structured non-throwing result) + `bufferedSpawnOrThrow` (throwing adapter), plus `killProcessTree`, `resolveWindowsExecutable`, `prepareWindowsSafeSpawn`, `prepareCliSpawn(command, args, env)` (composed resolve+wrap for a `spawn()`-safe pair), `needsShell`, `IS_WIN32`, `WIN_CMD_SHIMS`, `MAX_OUTPUT_BYTES`, `spawnFailureDetail(result, fallback)` (the most useful sentence from a failed result — prefers the spawn error, then a stderr line, then a stdout line that isn't bare JSON punctuation, because a `--json` CLI prints its payload to stdout even when it exits non-zero) — shared buffered-spawn machinery with capped stdout/stderr, timeout SIGTERM plus fire-and-forget SIGKILL escalation (`killGraceMs`, default 8s), Windows `.cmd`/`.bat` shim resolution, and `taskkill /T /F` tree-kill. `killProcessTree(child, signal, { processGroup })` takes the POSIX group down too when the child was spawned `detached` (Windows always tree-kills). A killable that is NOT a `ChildProcess` — a node-pty `IPty` TUI session — is killed through its own `.kill()`, with **no signal on Windows**: node-pty throws `Signals not supported on windows.` for any signal argument, so a signalled kill there killed nothing and threw past the caller. Used by `appBuilder.js`, `appUpdater.js`, the CoS agent spawners, and `setupScriptRunner.js`. |+| `bufferedSpawn.js` | `bufferedSpawn(cmd, args, opts)` (structured non-throwing result) + `bufferedSpawnOrThrow` (throwing adapter), plus `killProcessTree`, `resolveWindowsExecutable`, `prepareWindowsSafeSpawn`, `prepareCliSpawn(command, args, env)` (composed resolve+wrap for a `spawn()`-safe pair), `needsShell`, `IS_WIN32`, `WIN_CMD_SHIMS`, `MAX_OUTPUT_BYTES`, `guardChildStdin(child)` (attach the no-op `stdin` `'error'` listener BEFORE any `stdin.write`/`stdin.end` — a child that dies before reading stdin makes the pipe emit `EPIPE`, and an unlistened stream `'error'` outside the Express request lifecycle takes the whole server process down; used by every CLI-agent spawn site), `spawnFailureDetail(result, fallback)` (the most useful sentence from a failed result — prefers the spawn error, then a stderr line, then a stdout line that isn't bare JSON punctuation, because a `--json` CLI prints its payload to stdout even when it exits non-zero) — shared buffered-spawn machinery with capped stdout/stderr, timeout SIGTERM plus fire-and-forget SIGKILL escalation (`killGraceMs`, default 8s), Windows `.cmd`/`.bat` shim resolution, and `taskkill /T /F` tree-kill. `killProcessTree(child, signal, { processGroup })` takes the POSIX group down too when the child was spawned `detached` (Windows always tree-kills). A killable that is NOT a `ChildProcess` — a node-pty `IPty` TUI session — is killed through its own `.kill()`, with **no signal on Windows**: node-pty throws `Signals not supported on windows.` for any signal argument, so a signalled kill there killed nothing and threw past the caller. Used by `appBuilder.js`, `appUpdater.js`, the CoS agent spawners, and `setupScriptRunner.js`. || `setupScriptRunner.js` | `spawnSetupScript(envVars)` / `stopSetupScript(child)` / `SETUP_IMAGE_VIDEO_SCRIPT` — the one way to run `scripts/setup-image-video.sh` (shared by the Video Gen BYOV runtimes, the music engines and the MuScriptor venv). Runs it under `resolveBashBinary()` with a `toBashPath` script path, and on Windows presets the `PYTHON_BIN` the script would otherwise default to `python3` for. Cancel via `stopSetupScript`, which tree-kills so uv / pip / git die with bash. || `commandExists.js` | `commandExists(cmd, args = ['--version'], { timeoutMs = 5_000, env, cwd })` — does running `cmd args` succeed? A capability probe (`execFile`-based), not a PATH lookup like `processEnv.js`'s `whichFirst`; `env`/`cwd` let a caller check the exact child process configuration. Consolidates the two previously-private copies in `localLlm.js`/`ollamaManager.js`; callers probing a heavier CLI (e.g. `codeReview.js`'s reviewer-binary probe) pass a longer `timeoutMs`. || `spawnCwd.js` | `resolveSpawnCwd(workspacePath, fallbackRoot, label)` — resolves and **logs** the working directory a run/agent spawns into (expanding `~`), and throws when a workspace was requested but is missing / not a directory. Behind `services/runner.js#resolveRunCwd`, which turns that throw into a normal failed-run record for the two spawning runners. Stops a bad app `repoPath` from silently spawning in the PortOS checkout (#3180). `usesCreativeDirectorScratchCwd(task)` / `creativeDirectorScratchCwd(agentId)` / `removeCreativeDirectorScratchCwd(agentId)` / `resolveAgentCliCwd({ workspacePath, fallbackRoot, task, agentId })` — Creative Director no-worktree tasks get a per-agent scratch cwd under `os.tmpdir()/portos-cd-cwd/<id>` (outside the PortOS git tree) instead of the PortOS root, so native CLI AGENTS.md / CLAUDE.md discovery cannot walk up into the repo (#4650). `removeCreativeDirectorScratchCwd` is the matching finalize cleanup. `withSpawnCwdEnv(env, cwd)` — returns a copy of `env` with `PWD` pinned to `cwd` (dropping stale case-variant keys), because `spawn({ cwd })` doesn't rewrite the inherited `PWD` and OpenCode resolves its project root as `process.env.PWD ?? process.cwd()` (#3193). Apply it at every spawn that names its own cwd — the shared wrappers (`bufferedSpawn`, `spawnDetached`) already do, so their callers inherit it. `spawnCwd.test.js` discovers cwd-passing spawns across `server/` and fails on any that neither pins nor is listed exempt.diff --git a/server/lib/bufferedSpawn.js b/server/lib/bufferedSpawn.jsindex a933bcd6e7..04021f3d4b 100644--- a/server/lib/bufferedSpawn.js+++ b/server/lib/bufferedSpawn.js@@ -424,3 +424,29 @@ export function spawnFailureDetail(result, fallback) {if (stdoutTail && !/^[}\]]+,?$/.test(stdoutTail)) return stdoutTail;return fallback;}++/**+ * Attach the no-op `'error'` listener every spawned child's `stdin` needs before+ * anything writes to it.+ *+ * A child that dies before reading its stdin (a CLI that isn't on PATH, or one+ * that exits on a bad flag) makes the pipe emit `EPIPE`. A stream `'error'` with+ * no listener is re-thrown by Node, and every spawn site here runs OUTSIDE the+ * Express request lifecycle — there is no `next(err)` to bubble to, so the throw+ * takes down the single server process that owns every live agent run, PTY+ * shell, media job and socket. Swallowing it is correct: the child's own+ * `'error'`/`'exit'`/`'close'` handler is the authoritative settle point and+ * reports the real cause.+ *+ * A crash guard must never be the crash: a `spawn()` that failed command lookup+ * hands back a handle with no stdio at all, and a child configured with a+ * non-pipe stdin has no emitter to listen on either. Both are a no-op here+ * rather than a `TypeError` thrown from the very line meant to prevent one.+ *+ * @param {import('child_process').ChildProcess} child+ * @returns {import('child_process').ChildProcess} the same child, for chaining+ */+export function guardChildStdin(child) {+ if (typeof child?.stdin?.on === 'function') child.stdin.on('error', () => {});+ return child;+}diff --git a/server/lib/bufferedSpawn.test.js b/server/lib/bufferedSpawn.test.jsindex 25fcd759cc..6f5034f0c7 100644--- a/server/lib/bufferedSpawn.test.js+++ b/server/lib/bufferedSpawn.test.js@@ -29,6 +29,7 @@ const {WIN_CMD_SHIMS,MAX_OUTPUT_BYTES,spawnFailureDetail,+ guardChildStdin,} = await import('./bufferedSpawn.js');/**@@ -602,3 +603,30 @@ describe('spawnFailureDetail', () => {expect(spawnFailureDetail(null, fallback)).toBe(fallback);});});++describe('guardChildStdin', () => {+ // An 'error' on a stream with no listener is re-thrown by Node. Every CLI-agent+ // spawn site runs outside the Express request lifecycle, so that throw takes the+ // whole server process down — with every live agent run, PTY shell and socket on+ // it. This is the contract those three call sites rely on.+ it('swallows an EPIPE emitted on the child stdin pipe', () => {+ const child = { stdin: new EventEmitter() };+ guardChildStdin(child);+ expect(() => child.stdin.emit('error', Object.assign(new Error('write EPIPE'), { code: 'EPIPE' }))).not.toThrow();+ });++ it('proves the fake really is unguarded without it (bypass probe)', () => {+ const child = { stdin: new EventEmitter() };+ expect(() => child.stdin.emit('error', new Error('write EPIPE'))).toThrow('write EPIPE');+ });++ it('is a no-op for a spawn that failed command lookup and has no stdio at all', () => {+ expect(() => guardChildStdin({})).not.toThrow();+ expect(() => guardChildStdin(null)).not.toThrow();+ });++ it('returns the child so it can be chained at a spawn site', () => {+ const child = { stdin: new EventEmitter() };+ expect(guardChildStdin(child)).toBe(child);+ });+});diff --git a/server/lib/cliProviderRun.js b/server/lib/cliProviderRun.jsindex c2e85e7fe1..2a5010d53e 100644--- a/server/lib/cliProviderRun.js+++ b/server/lib/cliProviderRun.js@@ -18,7 +18,7 @@import { spawn } from './childProcess.js';import { buildCliArgs, prepareCliPrompt } from './cliProviderArgs.js';-import { killProcessTree, resolveWindowsExecutable, prepareWindowsSafeSpawn } from './bufferedSpawn.js';+import { killProcessTree, resolveWindowsExecutable, prepareWindowsSafeSpawn, guardChildStdin } from './bufferedSpawn.js';import { buildCliChildEnv } from './cliChildEnv.js';// How much stderr to hand back to callers. Enough to carry a rate-limit banner@@ -174,9 +174,8 @@ export function runCliProviderPrompt(args = {}) {child.stderr?.on('data', (d) => { const t = d.toString(); stderr += t; onData?.(t, 'stderr'); });// Swallow EPIPE on stdin (child gone before/while we write) — the close/- // error handler is the authoritative settle point; an unhandled stdin- // 'error' would crash the process.- child.stdin?.on('error', () => {});+ // error handler is the authoritative settle point. See guardChildStdin.+ guardChildStdin(child);try {// When grok is delivered via a Windows temp file, the prompt is already on// disk — just close stdin instead of writing it.diff --git a/server/services/agentCliSpawning.js b/server/services/agentCliSpawning.jsindex 30ff4dc864..ca0cca69ec 100644--- a/server/services/agentCliSpawning.js+++ b/server/services/agentCliSpawning.js@@ -36,7 +36,7 @@ import { buildVendorSpawnConfig } from '../lib/providerVendors.js';import { resolveCliModel, providerSuppliesGithubToken, isOllamaClaudeProvider } from '../lib/providerModels.js';import { resolveForgeTokenEnv } from './git.js';import { resolveAgentCliCwd } from '../lib/spawnCwd.js';-import { prepareCliSpawn, killProcessTree } from '../lib/bufferedSpawn.js';+import { prepareCliSpawn, killProcessTree, guardChildStdin } from '../lib/bufferedSpawn.js';import { buildCliChildEnv } from '../lib/cliChildEnv.js';import { prClaimWasVerified, resolvePrCompletion, resolvePrCreation } from '../lib/prDisposition.js';import { canTypeSlashCommands, agentOwnsPrWorkflow } from '../lib/slashdoInvocation.js';@@ -434,6 +434,10 @@ export async function spawnDirectly({if (handleSpawnError) void handleSpawnError(err);else pendingSpawnError = err;});+ // Same reasoning for the stdin pipe: a child that exits before reading it+ // emits EPIPE, and an unlistened stream 'error' out here would crash the+ // server. The 'error'/'exit' handlers below settle the run with the real cause.+ guardChildStdin(claudeProcess);const spawnedPid = claudeProcess.pid;if (spawnedPid != null) {@@ -446,8 +450,13 @@ export async function spawnDirectly({prompt: (task.description || '').substring(0, 500)});- if (writePromptToStdin && claudeProcess.stdin) claudeProcess.stdin.write(prompt);- claudeProcess.stdin?.end();+ try {+ if (writePromptToStdin && claudeProcess.stdin) claudeProcess.stdin.write(prompt);+ claudeProcess.stdin?.end();+ } catch {+ // Synchronous write failure (already-destroyed stdin) — the 'error'/'exit'+ // handler settles the agent run with the real cause.+ }activeAgents.set(agentId, {process: claudeProcess,diff --git a/server/services/agentCliSpawning.test.js b/server/services/agentCliSpawning.test.jsindex b8d023fa8b..73017b09fd 100644--- a/server/services/agentCliSpawning.test.js+++ b/server/services/agentCliSpawning.test.js@@ -82,7 +82,11 @@ vi.mock('fs', () => ({ existsSync: vi.fn().mockReturnValue(false) }));// Default passthrough for the Windows resolve+wrap helper (#2243) — POSIX// behavior. A specific test overrides it with mockReturnValueOnce to assert the// spawn wiring uses whatever prepareCliSpawn returns.-vi.mock('../lib/bufferedSpawn.js', () => ({+// Only the two spawn-shaping helpers are stubbed. `guardChildStdin` stays REAL+// so the stdin-EPIPE containment test below pins the production listener rather+// than a test double of it.+vi.mock('../lib/bufferedSpawn.js', async (importActual) => ({+ ...(await importActual()),prepareCliSpawn: vi.fn((command, args) => ({ command, args })),killProcessTree: vi.fn(),}));@@ -525,7 +529,10 @@ describe('stream error containment', () => {const proc = new EventEmitter();if (!noStdin) {proc.pid = 12345;- proc.stdin = { write: vi.fn(), end: vi.fn() };+ // A real ChildProcess stdin is a stream, so the fake is one too — otherwise+ // the production `guardChildStdin` listener has nothing to attach to and the+ // stdin-EPIPE path below would be tested against a shape that can't occur.+ proc.stdin = Object.assign(new EventEmitter(), { write: vi.fn(), end: vi.fn() });}proc.stdout = new EventEmitter();proc.stderr = new EventEmitter();@@ -633,6 +640,30 @@ describe('stream error containment', () => {const lines = agentStateMocks.appendAgentOutputLines.mock.calls.flatMap(([, batch]) => batch);expect(lines.some((line) => line.includes('ENOENT'))).toBe(true);});++ it('contains an EPIPE on stdin from a child that died before reading the prompt', async () => {+ // Two hazards in one shape, both fatal to the WHOLE server process because+ // this runs outside the Express request lifecycle (no next(err) to bubble to):+ // 1. a synchronous throw from stdin.write on an already-destroyed pipe, and+ // 2. an 'error' emitted on the stdin stream with no listener, which Node re-throws.+ // Regression guard for the listener drifting back below the write.+ const epipe = () => Object.assign(new Error('write EPIPE'), { code: 'EPIPE' });+ fakeProcess = makeFakeProcess();+ fakeProcess.stdin = Object.assign(new EventEmitter(), {+ write: vi.fn(() => { throw epipe(); }),+ end: vi.fn(),+ });++ const spawnPromise = spawnDirectly(minimalArgs);+ await new Promise((r) => setTimeout(r, 10));++ // A listener IS attached, so the late pipe error is swallowed instead of thrown.+ expect(() => fakeProcess.stdin.emit('error', epipe())).not.toThrow();++ fakeProcess.emit('close', 0);+ // The synchronous write throw did not escape as a rejected spawn either.+ await expect(spawnPromise).resolves.toBe('agent-test');+ });});// ─── Lifecycle ledger — the first-output boundary (#4540) ─────────────────diff --git a/server/services/runner.js b/server/services/runner.jsindex 5fc638f9cb..15e637949c 100644--- a/server/services/runner.js+++ b/server/services/runner.js@@ -11,7 +11,7 @@ import { hasModelFlag, extractBakedModel } from '../lib/providerModels.js';import { buildCliArgs, prepareCliPrompt } from '../lib/cliProviderArgs.js';import { buildCliChildEnv } from '../lib/cliChildEnv.js';import { createImmediateFallbackSignalDetector, ERROR_CATEGORIES } from '../lib/aiToolkit/errorDetection.js';-import { killProcessTree, resolveWindowsExecutable, prepareWindowsSafeSpawn } from '../lib/bufferedSpawn.js';+import { killProcessTree, resolveWindowsExecutable, prepareWindowsSafeSpawn, guardChildStdin } from '../lib/bufferedSpawn.js';import { isHostShuttingDown } from '../lib/hostShutdown.js';import { ensureOllamaAgentContext } from './ollamaAgentContext.js';import { isOllamaBackedProvider } from './providers.js';@@ -408,11 +408,21 @@ export async function executeCliRun({ runId, provider, prompt, workspacePath, scenv: childEnv});+ // Guard the stdin pipe BEFORE writing: a child that exits before reading it+ // (bad flag, missing CLI) emits EPIPE, and an unlistened stream 'error' out+ // here crashes the server. The 'error'/'close' handlers below settle the run.+ guardChildStdin(childProcess);+// Pass prompt via stdin to avoid OS argv limits. When grok is delivered via a// Windows temp file (useStdin === false) the prompt is already on disk, so// just close stdin.- if (useStdin) childProcess.stdin.write(promptInput);- childProcess.stdin.end();+ try {+ if (useStdin) childProcess.stdin.write(promptInput);+ childProcess.stdin.end();+ } catch {+ // Synchronous write failure (already-destroyed stdin) — the 'error'/'close'+ // handler settles the run with the real cause.+ }// Track active run via the toolkit's declared external-run registry so its// stopRun/isRunActive/deleteRun account for this host-spawned child process.