Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(mcp-host): settle shell_exec when an escaped process holds stdio
Alfredo Lopez6f550a14951c
diff --git a/docs/operations/gfs-large-file-host-downloads.md b/docs/operations/gfs-large-file-host-downloads.mdindex fe54e99bd..8cad1fb0d 100644--- a/docs/operations/gfs-large-file-host-downloads.md+++ b/docs/operations/gfs-large-file-host-downloads.md@@ -167,7 +167,7 @@ Partial reads are not possible, because publication is an atomic `rename` ofUnix directory modes and random directory names do not provide cross-caller OS isolation when a Host shares one UID. Approved arbitrary shell access remains a documented Stage 1 residual; stronger executor isolation is separate Stage 2 work.-Shell cleanup signals and waits for the detached process group before the tool result is returned. Operating systems may reuse a process-group identifier after the original leader has been reaped; Stage 1 narrows that window by signaling immediately on leader close, but stronger executor identity is required to eliminate it.+Shell cleanup signals and waits for the detached process group before the tool result is returned, or reports `process_group_termination_failed` when its termination cannot be confirmed. A process that moved outside that group (for example through `setsid` or a detached spawn) can keep stdout/stderr open after the group is gone, so the Host bounds settlement without waiting for those pipes to close. After a timeout, cancellation or output overflow, termination has 5000 ms of SIGTERM grace and the call settles at the 6000 ms cleanup budget at the latest. When the command exits on its own, the Host checks every 1000 ms whether the process group is gone and settles once it is. In both cases the Host stops output capture, the result starts with `[stdio_held_by_detached_process: <reason>; ...]` and is an error, and a `shell_stdio_held_by_detached_process` warning is logged. The escaped process is not signalled and may keep running; this bounds the call, it does not contain the process. Redirect background output to a file or `/dev/null`. Operating systems may reuse a process-group identifier after the original leader has been reaped; Stage 1 narrows that window by signaling immediately on leader close, but stronger executor identity is required to eliminate it.Generic workspace tools reject direct and symlink-resolved access to`.gfs-downloads` and the complete `.gfs-download-store` accounting namespacediff --git a/mcp-host/package-lock.json b/mcp-host/package-lock.jsonindex 6762357d1..054066a5c 100644--- a/mcp-host/package-lock.json+++ b/mcp-host/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-mcp-host",- "version": "0.1.516",+ "version": "0.1.517","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-mcp-host",- "version": "0.1.516",+ "version": "0.1.517","license": "SEE LICENSE IN LICENSE","dependencies": {"@anthropic-ai/sdk": "^0.32.0",diff --git a/mcp-host/package.json b/mcp-host/package.jsonindex a55b5f02b..b04e555e1 100644--- a/mcp-host/package.json+++ b/mcp-host/package.json@@ -1,6 +1,6 @@{"name": "clerum-mcp-host",- "version": "0.1.516",+ "version": "0.1.517","description": "MCP Host - reads Host CRD and provides LLM access via OpenAI/Claude","main": "dist/main.js","engines": {diff --git a/mcp-host/src/core/tools/__tests__/shell.detachedStdio.test.ts b/mcp-host/src/core/tools/__tests__/shell.detachedStdio.test.tsnew file mode 100644index 000000000..b184df796--- /dev/null+++ b/mcp-host/src/core/tools/__tests__/shell.detachedStdio.test.ts@@ -0,0 +1,542 @@+import { type MockInstance, afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { spawn } from 'child_process'+import { EventEmitter } from 'events'+import { existsSync, readFileSync } from 'fs'+import { mkdir, mkdtemp, rm, writeFile } from 'fs/promises'+import { tmpdir } from 'os'+import { join } from 'path'+import { PassThrough } from 'stream'+import { logger } from '../../../logger'+import { executeWithTimeout } from '../../orchestration/toolExecutionTimeout'+import { ShellTool } from '../shell'+import { SHELL_STDIO_DRAIN_MS, SHELL_TIMEOUT_CLEANUP_MS } from '../shellTimeouts'++// Real processes run unless a test replaces one spawn with a hermetic child.+vi.mock('child_process', async importOriginal => {+ const actual = await importOriginal<typeof import('child_process')>()+ return { ...actual, spawn: vi.fn(actual.spawn) }+})++/** Mirrors ShellTool.MAX_RESULT_BYTES (1 MB minus 2048 bytes of headroom). */+const MAX_RESULT_BYTES = 1024 * 1024 - 2048+/** Delay before a timeout or cancellation is triggered on a real process. */+const TRIGGER_MS = 3_000+/** Scheduling margin for a loaded machine. */+const MARGIN_MS = 2_000+/** F4: cleanup budget + margin + trigger delay. */+const TERMINATION_TEST_TIMEOUT_MS = SHELL_TIMEOUT_CLEANUP_MS + MARGIN_MS + TRIGGER_MS+/** F4: the natural-exit case runs with a 30 s execution timeout and must settle long before it. */+const NATURAL_EXIT_EXECUTION_TIMEOUT_MS = 30_000+const NATURAL_EXIT_TEST_TIMEOUT_MS = 15_000++const notice = (reason: string) =>+ `[stdio_held_by_detached_process: ${reason}; output capture stopped; redirect background output to a file or /dev/null]\n\n`++let workspacePath: string+const holderPids: number[] = []+let warn: MockInstance<typeof logger.warn>++beforeEach(async () => {+ workspacePath = await mkdtemp(join(tmpdir(), 'clerum-shell-held-'))+ vi.mocked(spawn).mockClear()+ warn = vi.spyOn(logger, 'warn').mockImplementation(() => {})+})++afterEach(async () => {+ for (const pid of holderPids.splice(0)) {+ if (isAlive(pid)) process.kill(pid, 'SIGKILL')+ }+ vi.restoreAllMocks()+ vi.useRealTimers()+ await rm(workspacePath, { recursive: true, force: true })+})++/**+ * A command prefix that starts a Node process with `detached: true` (its own+ * session and process group, so the shell's group signals never reach it)+ * that inherits the shell's stdout/stderr, writes READY to stdout and then+ * idles. The launcher returns only after READY was written, so the escape has+ * happened before the rest of the command runs. `setsid` is not needed.+ */+async function escapedHolder(): Promise<{ prefix: string; pidFile: string }> {+ const launcher = join(workspacePath, 'launch-holder.js')+ const holder = join(workspacePath, 'holder.js')+ const pidFile = join(workspacePath, 'holder.pid')+ await writeFile(+ holder,+ [+ "const fs = require('fs')",+ "fs.writeSync(1, 'READY\\n')",+ "fs.writeSync(3, 'R')",+ 'fs.closeSync(3)',+ // Bounded lifetime in case a failing test never reaches afterEach.+ 'setTimeout(() => process.exit(0), 60000)',+ ].join('\n')+ )+ await writeFile(+ launcher,+ [+ "const { spawn } = require('child_process')",+ "const fs = require('fs')",+ 'const [pidFile, holderPath] = process.argv.slice(2)',+ 'const holder = spawn(process.execPath, [holderPath], {',+ ' detached: true,',+ " stdio: ['ignore', 'inherit', 'inherit', 'pipe'],",+ '})',+ "holder.stdio[3].once('data', () => {",+ ' fs.writeFileSync(pidFile, String(holder.pid))',+ ' holder.stdio[3].destroy()',+ ' holder.unref()',+ ' process.exit(0)',+ '})',+ ].join('\n')+ )+ const prefix = [process.execPath, launcher, pidFile, holder].map(arg => JSON.stringify(arg))+ return { prefix: `${prefix.join(' ')};`, pidFile }+}++async function holderPid(pidFile: string): Promise<number> {+ const pid = Number(await waitForFile(pidFile))+ expect(Number.isSafeInteger(pid) && pid > 0).toBe(true)+ holderPids.push(pid)+ return pid+}++async function waitFor(condition: () => boolean, what: string, timeoutMs = 5_000): Promise<void> {+ const deadline = Date.now() + timeoutMs+ while (!condition()) {+ if (Date.now() >= deadline) throw new Error(`Timed out waiting for ${what}`)+ await new Promise(resolve => setTimeout(resolve, 10))+ }+}++async function waitForFile(file: string, timeoutMs = 5_000): Promise<string> {+ let content = ''+ await waitFor(+ () => existsSync(file) && (content = readFileSync(file, 'utf8').trim()) !== '',+ file,+ timeoutMs+ )+ return content+}++function isAlive(pid: number): boolean {+ try {+ process.kill(pid, 0)+ return true+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code === 'ESRCH') return false+ throw error+ }+}++function heldWarnings(): unknown[] {+ return warn.mock.calls+ .map(call => call[0] as unknown)+ .filter(+ fields =>+ typeof fields === 'object' &&+ fields !== null &&+ (fields as { event?: unknown }).event === 'shell_stdio_held_by_detached_process'+ )+}++describe('ShellTool with stdio held by a process outside its group (#1028 P1)', () => {+ it(+ 'P1-a: a timeout with an escaped stdout/stderr holder settles through executeWithTimeout within the cleanup budget',+ async () => {+ const { prefix, pidFile } = await escapedHolder()+ const command = `${prefix} printf out-marker; printf err-marker >&2; sleep 30`+ const tool = new ShellTool(workspacePath, NATURAL_EXIT_EXECUTION_TIMEOUT_MS, ['PATH'])+ let streamed = ''+ const startedAt = performance.now()+ const execution = executeWithTimeout(+ tool,+ { command },+ { onOutput: chunk => (streamed += chunk) },+ TRIGGER_MS+ )++ // Witness before termination: the holder escaped, is alive, and its READY+ // reached the call through the shared pipe.+ const holder = await holderPid(pidFile)+ await waitFor(() => streamed.includes('READY'), 'READY on the progress stream')+ expect(isAlive(holder)).toBe(true)+ expect(performance.now() - startedAt).toBeLessThan(TRIGGER_MS)++ const result = await execution+ const elapsed = performance.now() - startedAt++ expect(elapsed).toBeLessThanOrEqual(TRIGGER_MS + SHELL_TIMEOUT_CLEANUP_MS + MARGIN_MS)+ expect(result.is_error).toBe(true)+ expect(result.content.startsWith(notice('timeout'))).toBe(true)+ expect(result.content).toContain('stdout:\nREADY\nout-marker')+ expect(result.content).toContain('stderr:\nerr-marker')+ expect(result.content).toContain(+ `[Command killed after ${TRIGGER_MS}ms timeout — partial output above]`+ )+ const held = heldWarnings()+ expect(held).toEqual([+ {+ component: 'ShellTool',+ event: 'shell_stdio_held_by_detached_process',+ reason: 'timeout',+ exitCode: null,+ leaderExited: true,+ processGroupTerminated: expect.any(Boolean),+ durationMs: expect.any(Number),+ },+ ])+ // F6: the single probe at the deadline may still see the group.+ const groupTerminated = (held[0] as { processGroupTerminated: boolean })+ .processGroupTerminated+ expect(result.content.includes('[process_group_termination_failed]')).toBe(!groupTerminated)+ const logged = JSON.stringify(warn.mock.calls)+ for (const fragment of ['out-marker', 'err-marker', 'sleep 30', 'launch-holder', pidFile]) {+ expect(logged).not.toContain(fragment)+ }+ // Direct witness that the holder was outside the signalled group.+ expect(isAlive(holder)).toBe(true)+ },+ TERMINATION_TEST_TIMEOUT_MS+ )++ it(+ 'P1-b: a cancellation with an escaped holder settles within the cleanup budget with cause cancelled',+ async () => {+ const { prefix, pidFile } = await escapedHolder()+ const tool = new ShellTool(workspacePath, NATURAL_EXIT_EXECUTION_TIMEOUT_MS, ['PATH'])+ const parent = new AbortController()+ let streamed = ''+ const execution = executeWithTimeout(+ tool,+ { command: `${prefix} printf before-cancel; sleep 30` },+ { onOutput: chunk => (streamed += chunk) },+ NATURAL_EXIT_EXECUTION_TIMEOUT_MS,+ parent.signal+ )+ const holder = await holderPid(pidFile)+ await waitFor(() => streamed.includes('before-cancel'), 'output before cancellation')+ expect(isAlive(holder)).toBe(true)++ const cancelledAt = performance.now()+ parent.abort(new Error('user cancelled'))+ const result = await execution++ expect(performance.now() - cancelledAt).toBeLessThanOrEqual(+ SHELL_TIMEOUT_CLEANUP_MS + MARGIN_MS+ )+ expect(result.is_error).toBe(true)+ expect(result.content.startsWith(notice('cancelled'))).toBe(true)+ expect(result.content).toContain('READY\nbefore-cancel')+ expect(result.content).toContain('[Command cancelled — partial output above]')+ expect(result.content).not.toContain('timeout — partial output above')+ expect(heldWarnings()).toEqual([expect.objectContaining({ reason: 'cancelled' })])+ expect(isAlive(holder)).toBe(true)+ },+ TERMINATION_TEST_TIMEOUT_MS+ )++ it(+ 'P1-b: an output overflow with an escaped holder settles within the cleanup budget with cause maxbuffer, notice and footer inside the result budget',+ async () => {+ const { prefix, pidFile } = await escapedHolder()+ const tool = new ShellTool(workspacePath, NATURAL_EXIT_EXECUTION_TIMEOUT_MS, ['PATH'])+ let streamedBytes = 0+ const execution = executeWithTimeout(+ tool,+ { command: `${prefix} yes` },+ { onOutput: chunk => (streamedBytes += Buffer.byteLength(chunk)) },+ NATURAL_EXIT_EXECUTION_TIMEOUT_MS+ )+ const holder = await holderPid(pidFile)+ const overflowStartedAt = performance.now()+ const result = await execution++ expect(performance.now() - overflowStartedAt).toBeLessThanOrEqual(+ SHELL_TIMEOUT_CLEANUP_MS + MARGIN_MS+ )+ expect(streamedBytes).toBeGreaterThan(0)+ expect(result.is_error).toBe(true)+ expect(result.content.startsWith(notice('maxbuffer'))).toBe(true)+ expect(result.content).toContain('stdout:\nREADY\ny\ny\n')+ expect(+ result.content.endsWith(+ '[output_limit_exceeded: command killed after more than 1048576 output bytes — bounded partial output above]'+ ) ||+ result.content.endsWith(+ '[output_limit_exceeded: command killed after more than 1048576 output bytes — bounded partial output above]\n\n[process_group_termination_failed]'+ )+ ).toBe(true)+ expect(Buffer.byteLength(result.content)).toBeLessThanOrEqual(MAX_RESULT_BYTES)+ expect(result.content).not.toContain('[Command killed after')+ expect(heldWarnings()).toEqual([expect.objectContaining({ reason: 'maxbuffer' })])+ expect(isAlive(holder)).toBe(true)+ },+ TERMINATION_TEST_TIMEOUT_MS+ )++ it(+ 'P1-c: a command that exits 0 after starting an escaped holder settles about one drain interval after exit, not at the execution timeout',+ async () => {+ const { prefix, pidFile } = await escapedHolder()+ const tool = new ShellTool(workspacePath, NATURAL_EXIT_EXECUTION_TIMEOUT_MS, ['PATH'])+ const startedAt = performance.now()+ const execution = executeWithTimeout(+ tool,+ { command: `printf own-before; ${prefix} printf own-after` },+ { onOutput: () => {} },+ NATURAL_EXIT_EXECUTION_TIMEOUT_MS+ )+ const holder = await holderPid(pidFile)+ const result = await execution+ const elapsed = performance.now() - startedAt++ expect(elapsed).toBeGreaterThanOrEqual(SHELL_STDIO_DRAIN_MS)+ expect(elapsed).toBeLessThan(NATURAL_EXIT_EXECUTION_TIMEOUT_MS / 3)+ expect(result.is_error).toBe(true)+ expect(result.content).toBe(`${notice('exited')}stdout:\nown-beforeREADY\nown-after`)+ expect(heldWarnings()).toEqual([+ {+ component: 'ShellTool',+ event: 'shell_stdio_held_by_detached_process',+ reason: 'exited',+ exitCode: 0,+ leaderExited: true,+ processGroupTerminated: true,+ durationMs: expect.any(Number),+ },+ ])+ expect(isAlive(holder)).toBe(true)+ },+ NATURAL_EXIT_TEST_TIMEOUT_MS+ )++ it('P1-d: an in-group background job that writes after the leader exits is still collected', async () => {+ const tool = new ShellTool(workspacePath, NATURAL_EXIT_EXECUTION_TIMEOUT_MS, ['PATH'])+ const result = await tool.execute({ command: '(sleep 2; printf late) & printf early' })++ // Witness: the trailing marker written two drain intervals after exit.+ expect(result).toMatchObject({ is_error: false, content: 'stdout:\nearlylate' })+ expect(result.content).not.toContain('stdio_held_by_detached_process')+ expect(heldWarnings()).toEqual([])+ }, 10_000)++ it(+ 'P1-h: a forced closure with a non-zero exit near the output limit keeps the notice and the failure prefix in the first 200 characters',+ async () => {+ const { prefix, pidFile } = await escapedHolder()+ const tool = new ShellTool(workspacePath, NATURAL_EXIT_EXECUTION_TIMEOUT_MS, ['PATH'])+ // Below the 1 MB admission bound, above the result budget.+ const bodyBytes = 1024 * 1024 - 1024+ let streamedBytes = 0+ const execution = tool.execute(+ { command: `${prefix} head -c ${bodyBytes} /dev/zero | tr '\\000' x; exit 3` },+ { onOutput: chunk => (streamedBytes += Buffer.byteLength(chunk)) }+ )+ const holder = await holderPid(pidFile)+ const result = await execution++ expect(streamedBytes).toBeGreaterThan(0)+ expect(result.is_error).toBe(true)+ const head = `${notice('exited')}Command failed (exit code 3):\nstdout:\nREADY\nxxxx`+ expect(result.content.startsWith(head)).toBe(true)+ expect(+ head.indexOf('Command failed (exit code 3):') + 'Command failed (exit code 3):'.length+ ).toBeLessThan(200)+ expect(Buffer.byteLength(result.content)).toBeLessThanOrEqual(MAX_RESULT_BYTES)+ expect(Buffer.byteLength(result.content)).toBeGreaterThan(MAX_RESULT_BYTES - 16)+ expect(heldWarnings()).toEqual([expect.objectContaining({ reason: 'exited', exitCode: 3 })])+ expect(isAlive(holder)).toBe(true)+ },+ NATURAL_EXIT_TEST_TIMEOUT_MS+ )++ it('P1-g: an asynchronous start failure reports only the error code and publishes one result', async () => {+ const loggerError = vi.spyOn(logger, 'error').mockImplementation(() => {})+ const missing = join(workspacePath, 'created-after-first-call')+ const tool = new ShellTool(missing, 5_000, ['PATH'])++ const result = await tool.execute({ command: 'printf never-runs' })+ // Any late close from the failed spawn has time to arrive.+ await new Promise(resolve => setTimeout(resolve, 50))++ expect(result).toEqual({+ content: 'Command failed to start: ENOENT',+ duration_ms: expect.any(Number),+ is_error: true,+ })+ expect(vi.mocked(spawn).mock.results[0]!.type).toBe('return')+ expect(loggerError.mock.calls.map(call => call[0])).toEqual([+ { component: 'ShellTool', errorCode: 'ENOENT' },+ ])+ expect(JSON.stringify(loggerError.mock.calls)).not.toContain(missing)++ // Witness: the same tool instance runs once the directory exists.+ await mkdir(missing)+ const ok = await tool.execute({ command: 'printf runs' })+ expect(ok).toMatchObject({ is_error: false, content: 'stdout:\nruns' })+ expect(spawn).toHaveBeenCalledTimes(2)+ })+})++describe('ShellTool single finalizer races (#1028 P1, hermetic child)', () => {+ // These races cannot be ordered with a real process, so one spawn returns a+ // hermetic ChildProcess and process.kill is intercepted: no signal is sent.+ const FAKE_PID = 424_242++ function hermeticChild() {+ return Object.assign(new EventEmitter(), {+ pid: FAKE_PID,+ exitCode: null as number | null,+ signalCode: null as NodeJS.Signals | null,+ killed: false,+ stdout: new PassThrough(),+ stderr: new PassThrough(),+ kill: vi.fn(() => true),+ })+ }++ const groupGone = () => Object.assign(new Error('group gone'), { code: 'ESRCH' })++ it('P1-e: a close delivered after the cleanup deadline finalized the call publishes nothing more and sends no further signal', async () => {+ vi.useFakeTimers()+ const child = hermeticChild()+ vi.mocked(spawn).mockImplementationOnce(() => child as never)+ const signals: Array<[number, unknown]> = []+ vi.spyOn(process, 'kill').mockImplementation((pid: number, signal?: string | number) => {+ signals.push([pid, signal])+ if (signal === 0) throw groupGone()+ return true+ })+ const controller = new AbortController()+ const removeListener = vi.spyOn(controller.signal, 'removeEventListener')+ const streamed: string[] = []+ const execution = new ShellTool(workspacePath, 1_000, []).execute(+ { command: 'hermetic command' },+ { signal: controller.signal, onOutput: chunk => streamed.push(chunk) }+ )+ child.stdout.emit('data', Buffer.from('first chunk'))+ await vi.advanceTimersByTimeAsync(1_000)+ expect(signals).toEqual([[-FAKE_PID, 'SIGTERM']])+ await vi.advanceTimersByTimeAsync(SHELL_TIMEOUT_CLEANUP_MS)+ const result = await execution++ expect(streamed).toEqual(['first chunk'])+ expect(result.content).toBe(+ `${notice('timeout')}stdout:\nfirst chunk\n\n[Command killed after 1000ms timeout — partial output above]`+ )+ // SIGTERM, SIGKILL after the grace, SIGKILL at the deadline, one probe.+ const atSettlement: Array<[number, unknown]> = [+ [-FAKE_PID, 'SIGTERM'],+ [-FAKE_PID, 'SIGKILL'],+ [-FAKE_PID, 'SIGKILL'],+ [-FAKE_PID, 0],+ ]+ expect(signals).toEqual(atSettlement)++ // Destroyed pipes let the runtime deliver close later.+ child.emit('close', null)+ await vi.advanceTimersByTimeAsync(SHELL_TIMEOUT_CLEANUP_MS)++ expect(signals).toEqual(atSettlement)+ expect(heldWarnings()).toHaveLength(1)+ expect(vi.getTimerCount()).toBe(0)+ expect(removeListener).toHaveBeenCalledWith('abort', expect.any(Function))+ })++ it('P1-e: an abort delivered during close verification keeps the natural-exit result and sends no termination signal', async () => {+ const child = hermeticChild()+ vi.mocked(spawn).mockImplementationOnce(() => child as never)+ const controller = new AbortController()+ const signals: Array<[number, unknown]> = []+ let probes = 0+ vi.spyOn(process, 'kill').mockImplementation((pid: number, signal?: string | number) => {+ signals.push([pid, signal])+ if (signal !== 0) return true+ probes += 1+ if (probes === 1) {+ controller.abort(new Error('late cancellation'))+ return true+ }+ throw groupGone()+ })+ const execution = new ShellTool(workspacePath, 30_000, []).execute(+ { command: 'hermetic command' },+ { signal: controller.signal, onOutput: () => {} }+ )+ child.stdout.emit('data', Buffer.from('natural output'))+ child.exitCode = 0+ child.emit('exit', 0, null)+ child.emit('close', 0)+ const result = await execution++ // Witness: the abort was delivered while the group was still being probed.+ expect(controller.signal.aborted).toBe(true)+ expect(probes).toBe(2)+ expect(result).toEqual({+ content: 'stdout:\nnatural output',+ duration_ms: expect.any(Number),+ is_error: false,+ })+ expect(signals).toEqual([+ [-FAKE_PID, 'SIGKILL'],+ [-FAKE_PID, 0],+ [-FAKE_PID, 0],+ ])+ expect(heldWarnings()).toEqual([])+ })++ it('P1-f: a chunk that arrives after close claimed finalization is neither retained nor streamed', async () => {+ const child = hermeticChild()+ vi.mocked(spawn).mockImplementationOnce(() => child as never)+ const streamed: string[] = []+ let probes = 0+ vi.spyOn(process, 'kill').mockImplementation((_pid: number, signal?: string | number) => {+ if (signal !== 0) return true+ probes += 1+ if (probes === 1) {+ child.stdout.emit('data', Buffer.from('late chunk'))+ return true+ }+ throw groupGone()+ })+ const execution = new ShellTool(workspacePath, 30_000, []).execute(+ { command: 'hermetic command' },+ { onOutput: chunk => streamed.push(chunk) }+ )+ child.stdout.emit('data', Buffer.from('early chunk'))+ child.emit('close', 0)+ const result = await execution++ // Witness: the late chunk was delivered during verification.+ expect(probes).toBe(2)+ expect(streamed).toEqual(['early chunk'])+ expect(result).toMatchObject({ is_error: false, content: 'stdout:\nearly chunk' })+ })++ it('logs and keeps waiting when a group probe fails with a code other than ESRCH or EPERM', async () => {+ const child = hermeticChild()+ vi.mocked(spawn).mockImplementationOnce(() => child as never)+ let probes = 0+ vi.spyOn(process, 'kill').mockImplementation((_pid: number, signal?: string | number) => {+ if (signal !== 0) return true+ probes += 1+ if (probes === 1) throw Object.assign(new Error('invalid'), { code: 'EINVAL' })+ throw groupGone()+ })+ const execution = new ShellTool(workspacePath, 30_000, []).execute({+ command: 'hermetic command',+ })+ child.stdout.emit('data', Buffer.from('output'))+ child.emit('close', 0)+ const result = await execution++ // EINVAL did not count as absence: a second probe was needed.+ expect(probes).toBe(2)+ expect(result).toMatchObject({ is_error: false, content: 'stdout:\noutput' })+ expect(warn.mock.calls.map(call => call[0])).toEqual([+ { component: 'ShellTool', errorCode: 'EINVAL' },+ ])+ })+})diff --git a/mcp-host/src/core/tools/__tests__/shell.test.ts b/mcp-host/src/core/tools/__tests__/shell.test.tsindex cf99bd0e7..57c9bc243 100644--- a/mcp-host/src/core/tools/__tests__/shell.test.ts+++ b/mcp-host/src/core/tools/__tests__/shell.test.ts@@ -773,7 +773,8 @@ describe('ShellTool start failures (#1020)', () => {const tool = new ShellTool(missing, 5_000, ['PATH'])const result = await tool.execute({ command: 'printf never-runs' })expect(result.is_error).toBe(true)- expect(result.content).toMatch(/^Command failed to start: .*ENOENT/)+ expect(result.content).toBe('Command failed to start: ENOENT')+ expect(result.content).not.toContain(missing)expect(result.content).not.toContain('never-runs')// Witness: spawn returned a child; the failure arrived on its error event.expect(spawn).toHaveBeenCalledOnce()diff --git a/mcp-host/src/core/tools/shell.ts b/mcp-host/src/core/tools/shell.tsindex 578d00446..ff3ef9120 100644--- a/mcp-host/src/core/tools/shell.ts+++ b/mcp-host/src/core/tools/shell.ts@@ -7,7 +7,11 @@ import { verifyManagedCallerRootPath } from '../../workspace/callerRootBinding'import { ToolError, ToolErrorCode } from '../errors'import { ExecutionContext, Tool } from '../interfaces'import { ToolOutput } from '../types'-import { SHELL_SIGKILL_GRACE_MS, SHELL_TIMEOUT_CLEANUP_MS } from './shellTimeouts'+import {+ SHELL_SIGKILL_GRACE_MS,+ SHELL_STDIO_DRAIN_MS,+ SHELL_TIMEOUT_CLEANUP_MS,+} from './shellTimeouts'// D3 (stateless-agents) §1.2 — lexical defense-in-depth: reject commands that// reference the session state database (state.db + WAL laterals) or the@@ -23,6 +27,12 @@ const STATE_DB_COMMAND_PATTERN =// identifiers; anything else is not echoed to the model.const SPAWN_ERROR_CODE_PATTERN = /^[A-Z0-9_]+$/+/** Returns a well-formed Node/libuv error code, never any part of the message. */+function wellFormedErrorCode(error: unknown): string | undefined {+ const rawCode = (error as NodeJS.ErrnoException | undefined)?.code+ return typeof rawCode === 'string' && SPAWN_ERROR_CODE_PATTERN.test(rawCode) ? rawCode : undefined+}+function truncateUtf8Bytes(value: string, maximumBytes: number): string {if (maximumBytes <= 0) return ''const bytes = Buffer.from(value, 'utf8')@@ -33,16 +43,37 @@ function truncateUtf8Bytes(value: string, maximumBytes: number): string {.replace(/\uFFFD$/u, '')}+/**+ * Only ESRCH confirms that the group is gone. EPERM means it exists under+ * another owner; any other failure leaves absence unconfirmed, so the group is+ * treated as present and the code is logged.+ */function processGroupExists(processGroupId: number): boolean {try {process.kill(-processGroupId, 0)return true} catch (error) {- return (error as NodeJS.ErrnoException).code === 'EPERM'+ const code = (error as NodeJS.ErrnoException).code+ if (code === 'ESRCH') return false+ if (code !== 'EPERM') {+ logger.warn(+ { component: 'ShellTool', errorCode: wellFormedErrorCode(error) ?? 'UNKNOWN' },+ 'Shell process-group probe failed; group absence is not confirmed'+ )+ }+ return true}}-async function ensureProcessGroupTerminated(processGroupId: number): Promise<boolean> {+/**+ * Sends SIGKILL to the group and polls for its absence. Polling stops after+ * about one second, or at `deadlineAt` (a `performance.now()` value) when the+ * call is already inside its declared termination budget.+ */+async function ensureProcessGroupTerminated(+ processGroupId: number,+ deadlineAt?: number+): Promise<boolean> {try {process.kill(-processGroupId, 'SIGKILL')} catch {@@ -50,11 +81,21 @@ async function ensureProcessGroupTerminated(processGroupId: number): Promise<boo}for (let attempt = 0; attempt < 100; attempt += 1) {if (!processGroupExists(processGroupId)) return true- await sleep(10)+ if (deadlineAt !== undefined) {+ const remaining = deadlineAt - performance.now()+ if (remaining <= 0) break+ await sleep(Math.min(10, remaining))+ } else {+ await sleep(10)+ }}return !processGroupExists(processGroupId)}+function isValidProcessId(pid: number | undefined): pid is number {+ return typeof pid === 'number' && Number.isSafeInteger(pid) && pid > 0+}+/*** ShellTool — runs an arbitrary shell command in the agent's workspace.*@@ -252,11 +293,7 @@ export class ShellTool implements Tool {// No process exists, so this is a start failure reported as an error// result. Node error messages can embed argument and env values, so// only a well-formed error code is reported, never the message.- const rawCode = (error as NodeJS.ErrnoException | undefined)?.code- const errorCode =- typeof rawCode === 'string' && SPAWN_ERROR_CODE_PATTERN.test(rawCode)- ? rawCode- : undefined+ const errorCode = wellFormedErrorCode(error)logger.error({ component: 'ShellTool', errorCode: errorCode ?? 'UNKNOWN' },'Shell command failed to start'@@ -276,9 +313,16 @@ export class ShellTool implements Tool {const stderrBuf: Buffer[] = []let totalBytes = 0let progressBytes = 0+ // The first cause wins; later events never overwrite it.let killed: 'timeout' | 'maxbuffer' | 'cancelled' | null = nulllet resolved = false+ // Claimed synchronously by the first finalizer (close, drain check,+ // cleanup deadline, start failure). Every later path returns.+ let finalizing = false+ let terminationStartedAt: number | undefinedlet killTimer: ReturnType<typeof setTimeout> | undefined+ let deadlineTimer: ReturnType<typeof setTimeout> | undefined+ let drainTimer: ReturnType<typeof setInterval> | undefinedconst resolveOnce = (out: ToolOutput) => {if (resolved) return@@ -286,6 +330,20 @@ export class ShellTool implements Tool {resolve(out)}+ const clearFinalizationTimers = () => {+ clearInterval(drainTimer)+ drainTimer = undefined+ clearTimeout(deadlineTimer)+ deadlineTimer = undefined+ }++ const claimFinalization = (): boolean => {+ if (finalizing) return false+ finalizing = true+ clearFinalizationTimers()+ return true+ }+const forceKill = () => {// Kill the entire process group so grandchildren (e.g., `sleep` inside a// semi-colon chain) are also terminated and the stdout/stderr pipes close.@@ -303,6 +361,10 @@ export class ShellTool implements Tool {} else {child.kill('SIGTERM')}+ terminationStartedAt = performance.now()+ // Termination owns settlement from here; the natural-exit drain poll stops.+ clearInterval(drainTimer)+ drainTimer = undefinedkillTimer = setTimeout(() => {if (canGroupKill) {try {@@ -315,9 +377,14 @@ export class ShellTool implements Tool {}}, ShellTool.SIGKILL_GRACE_MS)killTimer.unref?.()+ // A process outside the group can hold stdout/stderr open after the+ // group is gone, so `close` may never arrive. The deadline bounds the+ // call to the declared cleanup budget.+ deadlineTimer = setTimeout(() => finalizeAtCleanupDeadline(), SHELL_TIMEOUT_CLEANUP_MS)}const onChunk = (chunk: Buffer, which: 'stdout' | 'stderr') => {+ if (finalizing) return// Bound both destinations before accepting the chunk. Bytes beyond the// admission bound are counted only for the truthful limit decision and// never enter retained output.@@ -353,18 +420,29 @@ export class ShellTool implements Tool {return which === 'stdout' ? stdoutBuf : stderrBuf}- child.stdout?.on('data', c => onChunk(c, 'stdout'))- child.stderr?.on('data', c => onChunk(c, 'stderr'))+ const onStdout = (chunk: Buffer) => onChunk(chunk, 'stdout')+ const onStderr = (chunk: Buffer) => onChunk(chunk, 'stderr')+ child.stdout?.on('data', onStdout)+ child.stderr?.on('data', onStderr)++ // Destroying the pipes bounds settlement; it does not contain or signal+ // the process holding them, which may get EPIPE on later writes.+ const stopOutputCapture = () => {+ child.stdout?.off('data', onStdout)+ child.stderr?.off('data', onStderr)+ child.stdout?.destroy()+ child.stderr?.destroy()+ }const timer = setTimeout(() => {- if (!killed) {+ if (!killed && !finalizing) {killed = 'timeout'forceKill()}}, timeout)const onAbort = () => {- if (!killed && !resolved) {+ if (!killed && !resolved && !finalizing) {killed =context?.signal?.reason instanceof ToolError &&context.signal.reason.code === ToolErrorCode.Timeout@@ -373,21 +451,20 @@ export class ShellTool implements Tool {forceKill()}}- context?.signal?.addEventListener('abort', onAbort, { once: true })- if (context?.signal?.aborted) onAbort()const cleanup = () => {clearTimeout(timer)clearTimeout(killTimer)+ clearFinalizationTimers()context?.signal?.removeEventListener('abort', onAbort)}- const handleClose = async (exitCode: number | null): Promise<void> => {- // Leader/stdio close does not prove descendants exited. Always complete- // group termination before resolving.- const processGroupId = child.pid- const groupTerminated =- typeof processGroupId === 'number' && processGroupId > 0- ? await ensureProcessGroupTerminated(processGroupId)- : true++ /** Builds and publishes the one result of this call. */+ const publish = (+ exitCode: number | null,+ groupTerminated: boolean,+ outputCaptureStopped: boolean,+ cause: typeof killed+ ) => {cleanup()const stdout = Buffer.concat(stdoutBuf).toString('utf8')const stderr = Buffer.concat(stderrBuf).toString('utf8')@@ -395,67 +472,143 @@ export class ShellTool implements Tool {[stdout ? `stdout:\n${stdout}` : '', stderr ? `stderr:\n${stderr}` : ''].filter(Boolean).join('\n\n') || '(no output)'- const format = (status: string) => {- return `${truncateUtf8Bytes(- body,- ShellTool.MAX_RESULT_BYTES - Buffer.byteLength(status, 'utf8')- )}${status}`- }- let out: ToolOutput- if (killed === 'timeout') {- const status = `\n\n[Command killed after ${timeout}ms timeout — partial output above]`- out = { content: format(status), duration_ms: Date.now() - startTime, is_error: true }- } else if (killed === 'cancelled') {- const status = '\n\n[Command cancelled — partial output above]'- out = { content: format(status), duration_ms: Date.now() - startTime, is_error: true }- } else if (killed === 'maxbuffer') {- const status = `\n\n[output_limit_exceeded: command killed after more than ${ShellTool.MAX_TOTAL_BYTES} output bytes — bounded partial output above]`- out = { content: format(status), duration_ms: Date.now() - startTime, is_error: true }- } else if (exitCode !== 0 && exitCode !== null) {- const status = `Command failed (exit code ${exitCode}):\n`- out = {- content: `${status}${truncateUtf8Bytes(- body,- ShellTool.MAX_RESULT_BYTES - Buffer.byteLength(status, 'utf8')- )}`,- duration_ms: Date.now() - startTime,- is_error: true,- }- } else {- out = {- content: truncateUtf8Bytes(body, ShellTool.MAX_RESULT_BYTES),- duration_ms: Date.now() - startTime,- is_error: false,- }+ // The completion summary keeps only the first 200 characters, so the+ // forced-closure notice goes first.+ const notice = outputCaptureStopped+ ? `[stdio_held_by_detached_process: ${cause ?? 'exited'}; output capture stopped; redirect background output to a file or /dev/null]\n\n`+ : ''+ const failure =+ cause === null && exitCode !== 0 && exitCode !== null+ ? `Command failed (exit code ${exitCode}):\n`+ : ''+ let footers = ''+ if (cause === 'timeout') {+ footers += `\n\n[Command killed after ${timeout}ms timeout — partial output above]`+ } else if (cause === 'cancelled') {+ footers += '\n\n[Command cancelled — partial output above]'+ } else if (cause === 'maxbuffer') {+ footers += `\n\n[output_limit_exceeded: command killed after more than ${ShellTool.MAX_TOTAL_BYTES} output bytes — bounded partial output above]`+ }+ if (!groupTerminated) footers += '\n\n[process_group_termination_failed]'+ // Every diagnostic is reserved before the body is truncated, so none+ // erases another; a negative budget would keep almost the whole body.+ const bodyBudget = Math.max(+ 0,+ ShellTool.MAX_RESULT_BYTES - Buffer.byteLength(`${notice}${failure}${footers}`, 'utf8')+ )+ const durationMs = Date.now() - startTime++ if (outputCaptureStopped) {+ logger.warn(+ {+ component: 'ShellTool',+ event: 'shell_stdio_held_by_detached_process',+ reason: cause ?? 'exited',+ exitCode,+ leaderExited: child.exitCode !== null || child.signalCode !== null,+ processGroupTerminated: groupTerminated,+ durationMs,+ },+ "A process outside the command's process group kept stdout/stderr open; shell output capture stopped"+ )}+ resolveOnce({+ content: `${notice}${failure}${truncateUtf8Bytes(body, bodyBudget)}${footers}`,+ duration_ms: durationMs,+ is_error: outputCaptureStopped || cause !== null || failure !== '' || !groupTerminated,+ })+ }- if (!groupTerminated) {- const status = '\n\n[process_group_termination_failed]'- out = {- content: `${truncateUtf8Bytes(- out.content,- ShellTool.MAX_RESULT_BYTES - Buffer.byteLength(status, 'utf8')- )}${status}`,- duration_ms: Date.now() - startTime,- is_error: true,+ // Termination path: `close` did not arrive within the cleanup budget.+ const finalizeAtCleanupDeadline = () => {+ if (!claimFinalization()) return+ const pid = child.pid+ if (isValidProcessId(pid)) {+ try {+ process.kill(-pid, 'SIGKILL')+ } catch {+ /* The group can already be gone; the probe below decides. */}+ } else if (!child.killed) {+ child.kill('SIGKILL')}- resolveOnce(out)+ stopOutputCapture()+ // One probe only: the budget is spent.+ const groupTerminated = isValidProcessId(pid) ? !processGroupExists(pid) : true+ publish(child.exitCode, groupTerminated, true, killed)+ }++ // Natural-exit path: the leader exited without a cause. Exit alone does+ // not publish, because an in-group background job can still write; only+ // the absence of the whole group does.+ child.once('exit', () => {+ const processGroupId = child.pid+ if (killed || finalizing || !isValidProcessId(processGroupId)) return+ drainTimer = setInterval(() => {+ if (finalizing || processGroupExists(processGroupId)) return+ // A pipe EOF pending in this poll phase delivers `close` first.+ setImmediate(() => {+ if (!claimFinalization()) return+ stopOutputCapture()+ publish(child.exitCode, true, true, killed)+ })+ }, SHELL_STDIO_DRAIN_MS)+ })++ const handleClose = async (exitCode: number | null): Promise<void> => {+ if (!claimFinalization()) return+ const cause = killed+ // Leader/stdio close does not prove descendants exited. Always complete+ // group termination before resolving, inside the cleanup budget when a+ // cause already started it.+ const processGroupId = child.pid+ const deadlineAt =+ cause !== null && terminationStartedAt !== undefined+ ? terminationStartedAt + SHELL_TIMEOUT_CLEANUP_MS+ : undefined+ const groupTerminated = isValidProcessId(processGroupId)+ ? await ensureProcessGroupTerminated(processGroupId, deadlineAt)+ : true+ publish(exitCode, groupTerminated, false, cause)}child.on('close', exitCode => {void handleClose(exitCode)})- child.on('error', err => {+ child.on('error', error => {+ // Node error messages can embed argument and env values, so only a+ // well-formed error code is reported, never the message.+ const errorCode = wellFormedErrorCode(error)+ const loggedCode = errorCode ?? 'UNKNOWN'+ if (isValidProcessId(child.pid)) {+ // A started process reports `error` only when signalling it failed.+ // Termination stays with the existing timers and cause.+ logger.error(+ { component: 'ShellTool', errorCode: loggedCode },+ 'Shell process reported an error'+ )+ return+ }+ if (!claimFinalization()) returncleanup()+ logger.error(+ { component: 'ShellTool', errorCode: loggedCode },+ 'Shell command failed to start'+ )resolveOnce({- content: `Command failed to start: ${err.message}`,+ content:+ errorCode === undefined+ ? 'Command failed to start'+ : `Command failed to start: ${errorCode}`,duration_ms: Date.now() - startTime,is_error: true,})})++ context?.signal?.addEventListener('abort', onAbort, { once: true })+ if (context?.signal?.aborted) onAbort()})}diff --git a/mcp-host/src/core/tools/shellTimeouts.ts b/mcp-host/src/core/tools/shellTimeouts.tsindex c13c0b985..f53f0b64b 100644--- a/mcp-host/src/core/tools/shellTimeouts.ts+++ b/mcp-host/src/core/tools/shellTimeouts.ts@@ -1,12 +1,22 @@/** Grace period between SIGTERM and SIGKILL for a timed-out shell process group. */export const SHELL_SIGKILL_GRACE_MS = 5000+/**+ * Interval at which a shell whose leader exited without a cause checks whether+ * its process group is gone. When the group is gone but stdout/stderr are still+ * held open by a process outside it, output capture stops and the call settles.+ */+export const SHELL_STDIO_DRAIN_MS = 1000+/*** Cleanup budget the shell declares after its deadline: the SIGKILL grace plus- * 1s for close/output delivery. executeWithTimeout does not arm a cleanup timer- * for the shell, because the shell joins abort settlement and owns its own- * process-group termination; the budget is only reserved by executeWithTimeout's- * check that timeout + cleanup stays within the largest delay a Node.js timer- * accepts, so a configured timeout must leave room for it (#1021).+ * one drain interval for close/output delivery. When `close` has not arrived by+ * then, the shell stops output capture and settles even if a process outside+ * its group still holds the pipes. executeWithTimeout does not arm a cleanup+ * timer for the shell, because the shell joins abort settlement and owns its+ * own process-group termination; the budget is only reserved by+ * executeWithTimeout's check that timeout + cleanup stays within the largest+ * delay a Node.js timer accepts, so a configured timeout must leave room for+ * it (#1021).*/-export const SHELL_TIMEOUT_CLEANUP_MS = SHELL_SIGKILL_GRACE_MS + 1000+export const SHELL_TIMEOUT_CLEANUP_MS = SHELL_SIGKILL_GRACE_MS + SHELL_STDIO_DRAIN_MSdiff --git a/scripts/ci/pinned-vitest-cases/mcp-host.json b/scripts/ci/pinned-vitest-cases/mcp-host.jsonindex af3851d54..6915cd845 100644--- a/scripts/ci/pinned-vitest-cases/mcp-host.json+++ b/scripts/ci/pinned-vitest-cases/mcp-host.json@@ -95,6 +95,14 @@"suite": "gfsDownloadStoreRecovery.test.ts","fullName": "legacy processing leases after #1019 S1: discards an expired foreign-session lease left by a crashed Host and admits downloads"},+ {+ "suite": "gfsDownloadStoreRecovery.test.ts",+ "fullName": "legacy processing leases after #1019 S1b: discards a non-expired foreign-session lease left by a crashed Host and admits downloads"+ },+ {+ "suite": "taskExecutor.gfsExecutionSafety.test.ts",+ "fullName": "X2b: a store at corrupt_store_ledger still answers admitted inline reads, accessible and resolve"+ },{"suite": "gfsDownloadStoreRecovery.test.ts","fullName": "legacy processing leases after #1019 S8: a discard whose persist fails before the rename leaves the ledger byte-identical and is retried by the next initialize"@@ -106,5 +114,21 @@{"suite": "gfsDownloadStoreRecovery.test.ts","fullName": "legacy processing leases after #1019 S9: reports the current quarantined-record count after reconcile without double counting across boots"+ },+ {+ "suite": "shell.detachedStdio.test.ts",+ "fullName": "ShellTool with stdio held by a process outside its group (#1028 P1) P1-a: a timeout with an escaped stdout/stderr holder settles through executeWithTimeout within the cleanup budget"+ },+ {+ "suite": "shell.detachedStdio.test.ts",+ "fullName": "ShellTool with stdio held by a process outside its group (#1028 P1) P1-c: a command that exits 0 after starting an escaped holder settles about one drain interval after exit, not at the execution timeout"+ },+ {+ "suite": "shell.detachedStdio.test.ts",+ "fullName": "ShellTool with stdio held by a process outside its group (#1028 P1) P1-g: an asynchronous start failure reports only the error code and publishes one result"+ },+ {+ "suite": "config.toolProgressInterval.test.ts",+ "fullName": "CLERUM_TOOL_PROGRESS_INTERVAL_MS (#1028 P2) P2-b: malformed and sub-second values stop startup with the exact message and do not echo the value"}]