Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
193 changes: 193 additions & 0 deletions sdk/src/__tests__/terminal-command-hook.test.ts
Original file line number Diff line number Diff line change
@@ -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<string, string>
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)
})
})
10 changes: 10 additions & 0 deletions sdk/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
29 changes: 28 additions & 1 deletion sdk/src/run.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down Expand Up @@ -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<void>
Expand Down Expand Up @@ -729,6 +736,7 @@ async function runOnce({
maxAgentSteps = MAX_AGENT_STEPS_DEFAULT,
env,
terminalCommandBroker,
terminalCommandHook,

handleEvent,
handleToolInput,
Expand Down Expand Up @@ -1039,6 +1047,7 @@ async function runOnce({
fs,
env: toolEnv,
terminalCommandBroker,
terminalCommandHook,
byok,
signal,
logger,
Expand Down Expand Up @@ -1517,6 +1526,7 @@ async function handleToolCall({
fs,
env,
terminalCommandBroker,
terminalCommandHook,
byok,
signal,
logger,
Expand All @@ -1530,6 +1540,7 @@ async function handleToolCall({
fs: CodebuffFileSystem
env?: Record<string, string>
terminalCommandBroker?: TerminalCommandBroker
terminalCommandHook?: TerminalCommandHook
byok?: ResolvedByokConnection
signal?: AbortSignal
logger?: Logger
Expand Down Expand Up @@ -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
? [
Expand Down
Loading
Loading