Skip to content

sdk: add an opt-in pre-execution hook stage to the Bash tool (primitive only) - #1765

Open
YKI-KMI wants to merge 1 commit into
CodebuffAI:mainfrom
YKI-KMI:yki/bash-tool-pre-execution-hook
Open

YKI-KMI wants to merge 1 commit into
CodebuffAI:mainfrom
YKI-KMI:yki/bash-tool-pre-execution-hook

Conversation

@YKI-KMI

@YKI-KMI YKI-KMI commented Nov 29, 2026 •

Copy link
Copy Markdown

Scope changed in response to the review below. This PR is now the SDK primitive alone: one commit, 4 files, 436 insertions, 1 deletion — and no existing code is refactored. The hook is a new module; the only edit to a running code path is one line at the single Bash call site. The CLI settings/wiring/transcript work and the docs are parked on a stacked branch, not deleted (see What moved out).

Refs #1760 (deliberately not Closes: the user-facing opt-in still needs the CLI half).

What this adds

A host can hand CodebuffClient a terminalCommandHook: the user's own command, run before a Bash tool call, which may return a replacement command. It runs at the one place the SDK dispatches run_terminal_command, before anything is spawned, so a rewrite reaches every Bash call instead of depending on the model remembering to prefix one.

The wire contract is Claude Code's PreToolUse rewrite contract, adopted rather than invented:

// stdin
{"hook_event_name":"PreToolUse","tool_name":"Bash","tool_input":{"command":"..."},"cwd":"/abs/path"}
// stdout, exit 0 -> this runs instead
{"hookSpecificOutput":{"updatedInput":{"command":"..."}}}

Only hookSpecificOutput.updatedInput.command is honored. A permission decision, another field, a non-zero exit, malformed JSON or no answer leaves the command exactly as the model wrote it. Reusing that contract means a hook already written for that ecosystem works here unchanged, and nothing in the stage is specific to one wrapper.

The design question

do we want an arbitrary user-shell-command-in-front-of-every-Bash-call extension point at all? ... whether terminalCommandHook belongs on CodebuffClient

Four placements were available. This PR takes A; I would like a verdict before anything else is built on top.

A. CodebuffClientOptions.terminalCommandHook — this PR. The hook is host policy for the whole client, sitting next to terminalCommandBroker, which is already a client-level "how this host runs commands" option. Cost: client-wide lifetime, so a host that wanted a different hook per agent turn could not express that.

B. RunOptions.hooks — arguably better scoping, since a hook is a property of a session or turn rather than of a client. Cheap to move: the value threads through runOnce → handleToolCall, so relocating it is roughly a ten-line change. If you would rather scope it per run, say so and I will switch it before merge.

C. No SDK change — do it in overrideTools.run_terminal_command. This is the option actually worth arguing about, because the override dispatch in handleToolCall can intercept run_terminal_command today, so a host could already do something like this. It is not sufficient in practice:

  1. An override replaces the tool rather than wrapping it, so every host would reimplement spawning, POSIX process-group kills with SIGKILL escalation, timeout-with-output-retention, background log files, Windows Git Bash lookup and nul redirect rewriting, output bounding and the broker path — the several hundred lines that are hardest to get right — in order to add six lines of policy.
  2. The intended consumer already passes a broker: cli/src/utils/codebuff-client.ts sets terminalCommandBroker. That broker is used inside runTerminalCommand (ownsShell, PTY, tree cleanup). An override returns its own ToolResultOutput[] and never reaches that path, so a hook written as an override would also drop the host's process boundary for every command — the opposite of what the CLI wants.

So the hook has to sit inside the existing terminal pipeline. A is the recommendation; B is a reasonable narrower alternative I will take if preferred.

D. A hooks map ({ 'bash.before-execute': ... }) instead of a single field — reasonable eventual shape, but with exactly one hook site it is speculative generality. Add the second entry point first, generalize then.

On the broader question: I think the extension point is worth having on these terms, all enforced here — off unless the host supplies it, never discovered from a repository file, hard-bounded so it cannot stall a tool call, and unable to block or fail a tool.

Safety properties

  • Never blocks or fails the tool. Non-zero exit, malformed JSON, unusable or over-long rewrite, refused spawn, aborted run and the hard timeout all run the original command.
  • Hard timeout. 2000 ms default, clamped 100–10000 ms, because the hook sits in front of every call. On timeout its process group is killed and the original runs without waiting for it.
  • Not repository-controlled. The SDK never reads a hooks file; only a host that constructs the client can enable one, so cloning a repository cannot make the agent run a hook.
  • Diagnostics only. Hook stderr is bounded at 4 KiB, passed to an onStderr callback for the host's log, and never enters the tool result or model context.
  • Bypass. FREEBUFF_DISABLE_BASH_HOOK=1 skips it for every command.

The hook is the user's own program with the user's privileges, so it runs with the run's environment as-is; the credential scrubbing that applies to model-written commands is not extended to it.

Size

 sdk/src/__tests__/terminal-command-hook.test.ts | 193 ++++++++++++++++
 sdk/src/index.ts                                |  10 +
 sdk/src/run.ts                                  |  29 +++-
 sdk/src/tools/terminal-command-hook.ts          | 205 +++++++++++++++
 4 files changed, 436 insertions(+), 1 deletion(-)
  • tools/terminal-command-hook.ts — new file, self-contained: the type, three constants, the timeout clamp, the output parser, and applyTerminalCommandHook.
  • run.ts — 29 lines and the single changed one: option on CodebuffClientOptions, threaded through the two existing hops, and applied at the run_terminal_command dispatch site.
  • index.ts — 10 lines of exports.
  • The tests are the other half of the diff; the implementation is ~150 lines of readable code.

runTerminalCommand and its output schema are untouched, so nothing about command execution, the broker, backgrounding or existing consumers changes. Earlier drafts wrapped the spawn path and added an originalCommand field to the shared output schema; both are gone, and rewrite observability now travels with the CLI half, where it is actually rendered.

What moved out

The CLI half — bashCommandHook in settings.json, loadBashCommandHook, client wiring, transcript rendering and the docs section — is preserved on yki/bash-command-hook-cli, stacked on this branch and pushed to my fork. It is not part of this PR; I will open it separately once this primitive is accepted, and I am happy to change its settings shape or the rendered transcript note to whatever you prefer in the meantime.

Verification

bun test sdk/src/__tests__/terminal-command-hook.test.ts
  9 pass, 0 fail, 20 expect() calls

Covers: a rewrite is returned and the payload arrives on stdin with the absolute cwd; non-zero exit leaves the command alone; non-answer output leaves it alone; a timeout leaves it alone and does not wait for the hook; an aborted run never starts the hook; FREEBUFF_DISABLE_BASH_HOOK=1 skips it entirely; hook stderr reaches the host's log but never the result; parseTerminalCommandHookOutput honors only updatedInput.command; the timeout clamp.

  • tsc --noEmit -p sdk/tsconfig.json — clean.
  • eslint on the changed files — 0 errors (pre-existing warnings only).

Not verified here: a live authenticated CLI agent turn, since that needs the CLI half.

Open questions

  1. A, B or C for placement.
  2. Single terminalCommandHook field, or a hooks map later.

@codebuff-team

Copy link
Copy Markdown
Contributor

Credit where due: the engineering here is careful. applyTerminalCommandHook bounds stdout/stderr, kills the hook's process group on timeout, never blocks or fails the tool on a bad answer, and the settings loader correctly preserves a disabled hook entry (cli/src/utils/settings.ts) instead of silently dropping the user's command. The test coverage in sdk/src/__tests__/terminal-command-hook.test.ts is genuinely thorough (timeout, non-zero exit, malformed JSON, abort, env bypass, stderr isolation).

That said, this is a ~900-line addition that introduces a new trust boundary into the core run_terminal_command path (SDK client option, CLI settings schema, wire-format change in common/src/tools/params/tool/run-terminal-command.ts, transcript rendering) in service of one named external tool (RTK). Nothing here is maintainer-requested design — it's a generic PreToolUse-style rewrite hook grafted onto the Bash tool because it makes RTK's output compression work automatically. That's a reasonable idea, but it's a product decision (do we want an arbitrary user-shell-command-in-front-of-every-Bash-call extension point at all?) that should be discussed and scoped before 14 files get touched across sdk/cli/common/docs in one shot.

Concretely I'd want to see this split: (1) the SDK-level hook primitive and its tests on its own, with a design discussion about whether terminalCommandHook belongs on CodebuffClient at all, and (2) the CLI settings/wiring/transcript-rendering changes as a follow-up once the primitive is accepted. As it stands this is too large and too unilateral an addition to be a clean single-PR port, even though none of it touches forbidden paths and the code itself is solid.

@codebuff-team codebuff-team added bot:triaged Classified by the community triage bot pr:needs-work Right idea, not mergeable as written labels Nov 29, 2026
@YKI-KMI
YKI-KMI force-pushed the yki/bash-tool-pre-execution-hook branch from fe3fc8c to 20ded3f Compare November 30, 2026 10:16
@YKI-KMI YKI-KMI changed the title Add an opt-in pre-execution hook for the Bash tool (RTK-style command rewrite) sdk: add an opt-in pre-execution hook stage to the Bash tool (primitive only) Nov 30, 2026
@YKI-KMI

YKI-KMI commented Nov 30, 2026 •

Copy link
Copy Markdown
Author

Restructured per this review

thanks, the split is the right call.

This branch is now the SDK primitive alone: one commit, 5 files (hook stage, its CodebuffClient option, plumbing, optional originalCommand, and 246 lines of tests). The CLI settings/wiring/transcript changes and the docs are preserved on yki/bash-command-hook-cli, stacked on this branch and pushed, no PR yet — it opens after this is accepted. RTK is also out of the code comments and the test fixture, so the stage reads as generic.

The PR body is now the design discussion you asked for. The option worth your attention is C: overrideTools.run_terminal_command can intercept the tool today with no SDK change, but it replaces the tool rather than wrapping it , every host would reimplement the spawn/process-group/timeout/Windows-Git-Bash pipeline to add six lines of policy, and it bypasses terminalCommandBroker, which the CLI always sets, so the hook would drop the host's PTY boundary. That is why the stage sits inside runTerminalCommand rather than at the override boundary. If you would rather scope it to RunOptions than to CodebuffClient, it is a ~10-line move and I will make it before merge.

On whether the extension point should exist at all: I think yes, on the terms stated in the body — host-supplied only, never repo-discovered, bounded, and structurally unable to block or fail a tool. Happy to drop it if the product call goes the other way.

@YKI-KMI
YKI-KMI force-pushed the yki/bash-tool-pre-execution-hook branch from 20ded3f to 867781b Compare November 30, 2026 10:37
A host can now give CodebuffClient a terminalCommandHook: the user's own
command, run before each Bash tool call, which may rewrite the command the
model wrote. The stage sits in run_terminal_command before anything is
spawned, so a rewrite reaches every Bash call instead of depending on the
model prefixing commands.

It speaks Claude Code's PreToolUse rewrite contract on purpose -- the hook
gets {"tool_name":"Bash","tool_input":{"command":...},"cwd":...} on stdin
and answers with hookSpecificOutput.updatedInput.command -- so a hook
already written for that ecosystem works unchanged. Only that field counts:
a permission decision or any other answer leaves the command alone.

A hook can never break the tool. A non-zero exit, malformed JSON, an
unusable rewrite, a refused spawn, an aborted run, or the hard timeout
(2000 ms by default, capped at 10000 ms) runs the command as the model
wrote it. FREEBUFF_DISABLE_BASH_HOOK=1 skips the hook for every command.
Hook stderr is bounded, goes only to the host's diagnostics through
onHookStderr, and never enters the tool result. A rewrite makes the result
carry originalCommand beside command, so what actually ran stays visible.

The SDK never reads a hooks file itself: the host supplies the hook, so
nothing in a cloned repository can turn one on.

Co-Authored-By: Codebuff <noreply@codebuff.com>
@YKI-KMI
YKI-KMI force-pushed the yki/bash-tool-pre-execution-hook branch from 867781b to afb3838 Compare November 30, 2026 10:44
@YKI-KMI

YKI-KMI commented Nov 30, 2026

Copy link
Copy Markdown
Author

Reduced to the smallest shape that still does the job:

  • 1 commit, 4 files, 436 insertions, 1 deletion (from 588/33/5).
  • No existing code is refactored. runTerminalCommand, its spawn path and its output schema are untouched, and the common package is no longer part of the diff. The hook is one self-contained new module, sdk/src/tools/terminal-command-hook.ts, applied at the single run_terminal_command dispatch site; the only changed line in a running path is that call site.
  • What the earlier draft had grown — wrapping the spawn path, extracting the env resolver, threading originalCommand through four return paths — is gone. Rewrite observability travels with the CLI half instead, where it is rendered.
  • The tests assert the stage's contract directly rather than spawning a shell: rewrite honored, payload shape, non-zero exit, non-answer, timeout, abort, bypass env var, stderr never in the result.

The design question is unchanged and still open: A (CodebuffClientOptions), B (RunOptions), or C (no SDK change). B remains a ~10-line move if you prefer it scoped per run.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bot:triaged Classified by the community triage bot pr:needs-work Right idea, not mergeable as written

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants