diff --git a/sdk/src/__tests__/terminal-command-hook.test.ts b/sdk/src/__tests__/terminal-command-hook.test.ts new file mode 100644 index 0000000000..c4d2822bf3 --- /dev/null +++ b/sdk/src/__tests__/terminal-command-hook.test.ts @@ -0,0 +1,193 @@ +import { afterEach, describe, expect, test } from 'bun:test' +import { + existsSync, + mkdtempSync, + readFileSync, + rmSync, + writeFileSync, +} from 'fs' +import { tmpdir } from 'os' +import { join } from 'path' + +import { + applyTerminalCommandHook, + parseTerminalCommandHookOutput, + terminalCommandHookTimeoutMs, +} from '../tools/terminal-command-hook' + +const tempDirs: string[] = [] + +afterEach(() => { + for (const dir of tempDirs.splice(0)) { + rmSync(dir, { recursive: true, force: true }) + } +}) + +const tempDir = (): string => { + const dir = mkdtempSync(join(tmpdir(), 'codebuff-bash-hook-')) + tempDirs.push(dir) + return dir +} + +/** + * A hook script with env switches, so each test states only its own answer: it + * records that it ran, reads the payload, then rewrites, exits, or answers + * something that is not a hook answer. + */ +const HOOK_SCRIPT = ` +const fs = require('node:fs') +if (process.env.HOOK_MARKER) fs.writeFileSync(process.env.HOOK_MARKER, 'ran') +let input = '' +process.stdin.setEncoding('utf8') +process.stdin.on('data', (chunk) => (input += chunk)) +process.stdin.on('end', () => { + if (process.env.HOOK_LOG) fs.writeFileSync(process.env.HOOK_LOG, input) + if (process.env.HOOK_STDERR) process.stderr.write('hook-diagnostic-noise') + if (process.env.HOOK_EXIT) process.exit(Number(process.env.HOOK_EXIT)) + if (process.env.HOOK_REWRITE === undefined) return + process.stdout.write(JSON.stringify({ + hookSpecificOutput: { + hookEventName: 'PreToolUse', + updatedInput: { command: process.env.HOOK_REWRITE }, + }, + })) +}) +` + +const hookCommand = (script = HOOK_SCRIPT): string => { + const file = join(tempDir(), 'hook.js') + writeFileSync(file, script) + return `${JSON.stringify(process.execPath)} ${JSON.stringify(file)}` +} + +const run = ({ + hook, + env, + timeoutMs, + signal, + onStderr, + command = 'printf original', +}: { + hook: string + env?: Record + timeoutMs?: number + signal?: AbortSignal + onStderr?: (stderr: string) => void + command?: string +}) => + applyTerminalCommandHook({ + hook: { command: hook, ...(timeoutMs !== undefined ? { timeoutMs } : {}) }, + command, + cwd: process.cwd(), + env, + signal, + onStderr, + }) + +describe('Bash tool pre-execution hook', () => { + test('rewrites the command and receives Claude Code’s payload', async () => { + const log = join(tempDir(), 'payload.json') + const result = await run({ + hook: hookCommand(), + env: { HOOK_LOG: log, HOOK_REWRITE: 'printf rewritten' }, + }) + + expect(result).toEqual({ command: 'printf rewritten' }) + expect(JSON.parse(readFileSync(log, 'utf8'))).toEqual({ + hook_event_name: 'PreToolUse', + tool_name: 'Bash', + tool_input: { command: 'printf original' }, + cwd: process.cwd(), + }) + }) + + test('a non-zero exit leaves the command alone', async () => { + const result = await run({ + hook: hookCommand(), + env: { HOOK_EXIT: '1', HOOK_REWRITE: 'printf rewritten' }, + }) + + expect(result).toEqual({ command: 'printf original' }) + }) + + test('output that is not a hook answer leaves the command alone', async () => { + expect(await run({ hook: hookCommand() })).toEqual({ + command: 'printf original', + }) + }) + + test('a timeout leaves the command alone and does not wait for the hook', async () => { + const started = Date.now() + const result = await run({ + hook: hookCommand('setTimeout(() => {}, 5000)'), + timeoutMs: 200, + }) + + expect(Date.now() - started).toBeLessThan(3000) + expect(result).toEqual({ command: 'printf original' }) + }) + + test('an aborted run never starts the hook', async () => { + const marker = join(tempDir(), 'ran') + const controller = new AbortController() + controller.abort() + const result = await run({ + hook: hookCommand(), + env: { HOOK_MARKER: marker, HOOK_REWRITE: 'printf rewritten' }, + signal: controller.signal, + }) + + expect(existsSync(marker)).toBe(false) + expect(result).toEqual({ command: 'printf original' }) + }) + + test('FREEBUFF_DISABLE_BASH_HOOK=1 skips the hook entirely', async () => { + const marker = join(tempDir(), 'ran') + const result = await run({ + hook: hookCommand(), + env: { + HOOK_MARKER: marker, + HOOK_REWRITE: 'printf rewritten', + FREEBUFF_DISABLE_BASH_HOOK: '1', + }, + }) + + expect(existsSync(marker)).toBe(false) + expect(result).toEqual({ command: 'printf original' }) + }) + + test('hook stderr goes to the host’s log, never into the result', async () => { + const seen: string[] = [] + const result = await run({ + hook: hookCommand(), + env: { HOOK_STDERR: '1', HOOK_REWRITE: 'printf rewritten' }, + onStderr: (stderr) => seen.push(stderr), + }) + + expect(seen.join('')).toContain('hook-diagnostic-noise') + expect(JSON.stringify(result)).not.toContain('hook-diagnostic-noise') + }) +}) + +describe('parseTerminalCommandHookOutput', () => { + test('reads only updatedInput.command, and only a usable one', () => { + const answer = (hookSpecificOutput: unknown) => + parseTerminalCommandHookOutput(JSON.stringify({ hookSpecificOutput })) + + expect(answer({ updatedInput: { command: 'git status --porcelain' } })).toBe( + 'git status --porcelain', + ) + expect(answer({ permissionDecision: 'deny' })).toBeNull() + expect(answer({ updatedInput: { command: '' } })).toBeNull() + expect(parseTerminalCommandHookOutput('not json')).toBeNull() + expect(parseTerminalCommandHookOutput('')).toBeNull() + }) +}) + +describe('terminalCommandHookTimeoutMs', () => { + test('defaults, floors and caps the timeout', () => { + expect(terminalCommandHookTimeoutMs(undefined)).toBe(2000) + expect(terminalCommandHookTimeoutMs(1)).toBe(100) + expect(terminalCommandHookTimeoutMs(60_000)).toBe(10_000) + }) +}) diff --git a/sdk/src/index.ts b/sdk/src/index.ts index a3829a9197..098da9e536 100644 --- a/sdk/src/index.ts +++ b/sdk/src/index.ts @@ -154,6 +154,16 @@ export type { TerminalCommandProcess, TerminalCommandSpawnRequest, } from './tools/run-terminal-command' +export { + applyTerminalCommandHook, + TERMINAL_COMMAND_HOOK_DISABLE_ENV, + TERMINAL_COMMAND_HOOK_TIMEOUT_MAX_MS, + TERMINAL_COMMAND_HOOK_TIMEOUT_MS, +} from './tools/terminal-command-hook' +export type { + TerminalCommandHook, + TerminalCommandHookResult, +} from './tools/terminal-command-hook' // Containment for a sponsored run on the user's own machine (COD-336). Exported // from the SDK rather than kept in Desktop because the CLI needs the same // boundary, and a second copy of a seatbelt profile is a second thing to be diff --git a/sdk/src/run.ts b/sdk/src/run.ts index 854695f2ef..e2c6888822 100644 --- a/sdk/src/run.ts +++ b/sdk/src/run.ts @@ -66,6 +66,8 @@ import { runTerminalCommand, } from './tools/run-terminal-command' import type { TerminalCommandBroker } from './tools/run-terminal-command' +import { applyTerminalCommandHook } from './tools/terminal-command-hook' +import type { TerminalCommandHook } from './tools/terminal-command-hook' import type { CustomToolDefinition } from './custom-tool' import type { CodebuffRequestHeadersProvider } from './impl/model-provider' @@ -232,6 +234,11 @@ export type CodebuffClientOptions = { /** Optional host process boundary that keeps terminal tools away from an * interactive console. Headless consumers can omit it. */ terminalCommandBroker?: TerminalCommandBroker + /** Opt-in Bash-tool pre-execution hook: the user's own command, which may + * rewrite a command before it runs (Claude Code's `PreToolUse` contract). + * Unset runs every command exactly as the model wrote it; a hook that fails, + * times out or answers nothing usable leaves the command alone. */ + terminalCommandHook?: TerminalCommandHook /** Every event but `tool_input`, which goes to `handleToolInput` alone. */ handleEvent?: (event: PrintModeEvent) => void | Promise @@ -729,6 +736,7 @@ async function runOnce({ maxAgentSteps = MAX_AGENT_STEPS_DEFAULT, env, terminalCommandBroker, + terminalCommandHook, handleEvent, handleToolInput, @@ -1039,6 +1047,7 @@ async function runOnce({ fs, env: toolEnv, terminalCommandBroker, + terminalCommandHook, byok, signal, logger, @@ -1517,6 +1526,7 @@ async function handleToolCall({ fs, env, terminalCommandBroker, + terminalCommandHook, byok, signal, logger, @@ -1530,6 +1540,7 @@ async function handleToolCall({ fs: CodebuffFileSystem env?: Record terminalCommandBroker?: TerminalCommandBroker + terminalCommandHook?: TerminalCommandHook byok?: ResolvedByokConnection signal?: AbortSignal logger?: Logger @@ -1637,9 +1648,25 @@ async function handleToolCall({ }) } else if (toolName === 'run_terminal_command') { const resolvedCwd = requireCwd(cwd, 'run_terminal_command') + const resolvedPath = path.resolve(resolvedCwd, input.cwd ?? '.') + const command = terminalCommandHook + ? ( + await applyTerminalCommandHook({ + hook: terminalCommandHook, + command: input.command, + cwd: resolvedPath, + env, + signal, + // For the host's log only: hook stderr never reaches the model. + onStderr: (stderr) => + logger?.debug?.({ stderr }, 'Bash pre-execution hook stderr'), + }) + ).command + : input.command result = await runTerminalCommand({ ...input, - cwd: path.resolve(resolvedCwd, input.cwd ?? '.'), + command, + cwd: resolvedPath, env, scrubEnvironmentKeys: byok ? [ diff --git a/sdk/src/tools/terminal-command-hook.ts b/sdk/src/tools/terminal-command-hook.ts new file mode 100644 index 0000000000..8d1174fbbe --- /dev/null +++ b/sdk/src/tools/terminal-command-hook.ts @@ -0,0 +1,205 @@ +import { spawn } from 'child_process' +import * as os from 'os' + +import { getSystemProcessEnv } from '../env' + +/** + * An opt-in Bash-tool pre-execution hook: the user's own program, run on their + * computer before a command the model asked for, that may answer with the + * command to run instead. + * + * It speaks Claude Code's `PreToolUse` rewrite contract + * (`hookSpecificOutput.updatedInput.command`) rather than inventing one, so a + * hook already written for that ecosystem works unchanged. The host decides + * whether a hook exists at all: the SDK never reads a hooks file, so a + * repository cannot turn one on by adding a file to it. + */ +export type TerminalCommandHook = { + /** Shell command run before each Bash tool call; the payload arrives on stdin. */ + command: string + /** Hard limit in milliseconds: 2000 by default, never more than 10000. */ + timeoutMs?: number +} + +/** How long a hook may run when its config names no timeout. */ +export const TERMINAL_COMMAND_HOOK_TIMEOUT_MS = 2_000 +/** A longer configured timeout is cut to this: the hook fronts every command. */ +export const TERMINAL_COMMAND_HOOK_TIMEOUT_MAX_MS = 10_000 +/** Set to `1` in the environment to skip the hook for every command. */ +export const TERMINAL_COMMAND_HOOK_DISABLE_ENV = 'FREEBUFF_DISABLE_BASH_HOOK' + +/** A hook's stdout is one JSON object; more than this is not an answer. */ +const STDOUT_LIMIT = 64 * 1024 +/** The most hook stderr is kept for diagnostics. It never reaches the model. */ +const STDERR_LIMIT = 4 * 1024 +/** A rewritten command longer than this is refused: no wrapper needs one. */ +const COMMAND_LIMIT = 100_000 + +/** `timeoutMs` as it is applied: defaulted, at least 100 ms, cut to the cap. */ +export function terminalCommandHookTimeoutMs(timeoutMs?: number): number { + if (timeoutMs === undefined || !Number.isFinite(timeoutMs)) { + return TERMINAL_COMMAND_HOOK_TIMEOUT_MS + } + return Math.min( + Math.max(Math.round(timeoutMs), 100), + TERMINAL_COMMAND_HOOK_TIMEOUT_MAX_MS, + ) +} + +/** + * The command a hook's stdout asks to run instead, or null for any other answer. + * Only Claude Code's rewrite field counts: a permission decision or anything + * else leaves the command as the model wrote it. + */ +export function parseTerminalCommandHookOutput(stdout: string): string | null { + const text = stdout.trim() + if (!text) return null + let parsed: unknown + try { + parsed = JSON.parse(text) + } catch { + return null + } + const command = ( + parsed as { + hookSpecificOutput?: { updatedInput?: { command?: unknown } } + } | null + )?.hookSpecificOutput?.updatedInput?.command + if (typeof command !== 'string') return null + if (command.trim() === '' || command.length > COMMAND_LIMIT) return null + return command +} + +export type TerminalCommandHookResult = { + /** The command to run: the hook's rewrite, or the original. */ + command: string + /** Bounded hook stderr, for the host's own diagnostics. Never model context. */ + stderr?: string +} + +/** + * Run a Bash tool's pre-execution hook and return the command to execute. + * + * Every failure -- a refused spawn, a timeout, a non-zero exit, malformed + * output, an unusable rewrite or an abort -- returns the original command, so a + * broken hook can never block or fail the tool. The payload is Claude Code's + * shape: `{"tool_name":"Bash","tool_input":{"command":"..."},"cwd":"..."}`. + */ +export async function applyTerminalCommandHook({ + hook, + command, + cwd, + env, + signal, + onStderr, +}: { + hook: TerminalCommandHook + command: string + cwd: string + env?: Record + signal?: AbortSignal + /** Hook stderr, for the host's log only. Must not throw. */ + onStderr?: (stderr: string) => void +}): Promise { + const unchanged: TerminalCommandHookResult = { command } + if (!hook.command.trim()) return unchanged + + const hookEnv = { ...getSystemProcessEnv(), ...env } + if (hookEnv[TERMINAL_COMMAND_HOOK_DISABLE_ENV] === '1') return unchanged + if (signal?.aborted) return unchanged + + return new Promise((resolve) => { + let child: ReturnType | undefined + let settled = false + let stdout = '' + let stdoutOverflow = false + let stderr = '' + let timer: NodeJS.Timeout | undefined + + const settle = (result: TerminalCommandHookResult) => { + if (settled) return + settled = true + if (timer) clearTimeout(timer) + signal?.removeEventListener('abort', onAbort) + if (stderr) { + try { + onStderr?.(stderr) + } catch { + // Diagnostics never change a command's result. + } + } + resolve(result) + } + const stopHook = () => { + if (!child?.pid) return + try { + // Own process group on POSIX, so the hook's children die with it too. + if (os.platform() === 'win32') child.kill('SIGKILL') + else process.kill(-child.pid, 'SIGKILL') + } catch { + // Already gone; the answer is unchanged either way. + } + } + const onAbort = () => { + stopHook() + settle(unchanged) + } + + try { + child = spawn(hook.command, { + cwd, + env: hookEnv, + // The hook is a shell command like the tool's own: `python3 ~/hook.py` + // or `my-compressor pretooluse`, with whatever quoting the user wrote. + shell: true, + stdio: ['pipe', 'pipe', 'pipe'], + detached: os.platform() !== 'win32', + windowsHide: true, + }) + } catch { + resolve(unchanged) + return + } + + timer = setTimeout(() => { + stopHook() + settle(unchanged) + }, terminalCommandHookTimeoutMs(hook.timeoutMs)) + timer.unref?.() + signal?.addEventListener('abort', onAbort, { once: true }) + + child.stdout?.on('data', (data: Buffer) => { + if (stdoutOverflow) return + stdout += data.toString() + if (stdout.length > STDOUT_LIMIT) { + stdoutOverflow = true + stdout = '' + } + }) + child.stderr?.on('data', (data: Buffer) => { + if (stderr.length < STDERR_LIMIT) { + stderr = (stderr + data.toString()).slice(0, STDERR_LIMIT) + } + }) + // A hook may exit without reading stdin; that EPIPE is its own business. + child.stdin?.on('error', () => {}) + child.once('error', () => settle(unchanged)) + child.once('close', (code) => { + // Only a rewritable answer counts: exit 0 plus updatedInput.command. + const rewritten = + code === 0 && !stdoutOverflow + ? parseTerminalCommandHookOutput(stdout) + : null + settle(rewritten === null ? unchanged : { command: rewritten }) + }) + + child.stdin?.end( + JSON.stringify({ + hook_event_name: 'PreToolUse', + tool_name: 'Bash', + tool_input: { command }, + cwd, + }), + ) + }) +}