Introducing a new way to review your PRs.

Read the announcement

kenryu42 / cc-safety-net

A pre-execution guard for AI coding agents. It blocks destructive Git and file system commands, plus common attempts to access sensitive files, before a tool call runs. Supports Amp Code, Antigravity CLI, Claude Code, Codex, Cursor, DeepSeek Harness, Devin CLI, GitHub Copilot CLI, Grok Build, Hermes Agent, Kimi Code, OpenClaw, OpenCode, and Pi.

View on GitHub

20 documents · Updated Nov 23, 2026

docs / hook-routing-and-tool-adapters

Hook routing and tool adapters

Hook routing is the boundary between coding agents and the common safety check. It selects one agent hook from the CLI request, reads the agent payload, turns the payload into a shared tool invocation, and returns a denial in the format that the agent expects. This page sits under Agent integrations; integration installation and detection explains how hooks are installed, and agent connector implementations covers agent-specific packages and registration files.

Hook entry routing

The hook command is a small protocol entry point. It reads JSON from standard input and runs exactly one runtime hook adapter named by a flag. The runtime set is defined by the catalog, then joined to its runner in src/…/hook-integrations.ts.

AgentHook flagInput event or shape
Antigravity CLI-ac, --agy-cliPreToolUse payload
Claude Code-cc, --coding-cliPreToolUse payload
GitHub Copilot CLI-cp, --copilot-clipreToolUse payload
Cursor-cu, --cursorpreToolUse payload
Gemini CLI-gc, --gemini-cliBeforeTool payload
Hermes Agent-ha, --hermes-agentpre_tool_call payload
Kimi Code-kc, --kimi-codePreToolUse payload

The resolver rejects a missing flag, more than one integration flag, an unknown option, or an extra argument. A few old top-level aliases remain for compatibility, but the normal form is cc-safety-net hook INTEGRATION_FLAG. A hook without a valid integration flag prints help to standard error and does not consume the payload as a hook request. src/…/hook.ts describes this user-facing contract.

References: src/…/hook-integrations.ts• L14-71 src/…/hook.ts• L13-25 src/…/catalog.ts• L25-227

Common hook lifecycle

Hook adapters and plugin tool-call adapters use the same safety lifecycle. Each adapter supplies the agent-specific rules for reading fields, naming tools, finding a working directory, and making the output object. The shared safety path owns validation, route creation, evaluation, audit handoff, and the allow or deny result. Hook adapters can also expose an ask result when the host can send the decision to a person; hosts that cannot prompt keep the result as a denial.

The following flow shows how an agent payload reaches the shared safety guard.

flowchart LR
    A[Agent JSON on stdin] --> B[Bounded read and JSON parse]
    B --> C[Adapter event and envelope check]
    C --> D[Tool name and tool input extraction]
    D --> E[Tool route and contained context]
    E --> F[Shared tool invocation]
    F --> G[Runtime safety guard]
    G --> H{Decision}
    H -->|allow| I[Empty output or host allow]
    H -->|ask| J[Host prompt output]
    H -->|deny| K[Redacted denial in agent format]

The handler stops early for an unsupported event and prints nothing. It fails closed for a bad JSON envelope, a missing tool name, an unusable context, or a limit error. For a valid request it records the guard result with agent and session data, then projects a guard denial into the common denial model before the adapter formats it. src/…/common.ts is the shared boundary, while src/…/invocation.ts defines the data passed to the guard.

References: src/…/common.ts• L62-76 src/…/common.ts• L133-242 src/…/runtime.ts• L21-41 src/…/invocation.ts• L9-39

Adapter contracts

An adapter maps an agent protocol to six shared questions: whether the event is supported, which agent identity to audit, which tool was called, what input belongs to that tool, which directories define the request, and which session identifies it. This keeps agent protocol changes at the edge and gives the safety guard one input shape.

AdapterCommand tools and shell modeImportant input mapping
Claude CodeBash → POSIX; PowerShell → PowerShellUses tool_input and the hook cwd
Gemini CLIrun_shell_command → automatic shell choiceUses tool_input and the hook cwd
Kimi CodeBash → POSIXUses tool_input; its command input can supply a contained cwd
GitHub Copilot CLIbash or Bash → automatic; PowerShell names → PowerShellParses the JSON string in toolArgs
Antigravity CLIrun_command → automatic shell choiceConverts CommandLine in toolCall.args to the shared command field
CursorShell → automatic shell choiceUses tool_input and its workspace directory fields
Hermes Agentterminal → POSIXUses tool_input; its command can supply workdir
AmpTool calls resolved by the Amp plugin APIUses the plugin helpers for shell calls and the workspace root for context

Each adapter accepts only the event or payload shape that belongs to it. For example, Gemini ignores an AfterTool event, while Copilot and Antigravity use their own nested or encoded argument fields. Amp receives a plugin tool-call event and asks the Amp API to identify a shell command. Its output uses allow or reject-and-continue, so the shared safety path does not need to know the host's permission vocabulary.

References: src/…/hook.ts• L7-34 src/…/hook.ts• L25-52 src/…/hook.ts• L6-17 src/…/hook.ts• L18-61 src/…/hook.ts• L47-82 src/…/hook.ts• L32-58 src/…/hook.ts• L17-33 src/…/tool-call.ts• L32-49

Plugin tool-call adapters

Plugin adapters accept an in-process tool-call event instead of JSON from standard input. The shared plugin handler lets each host provide extraction, session, allow, and block behavior while it keeps cancellation checks, malformed-call audits, guard evaluation, and unexpected-error handling consistent.

Malformed calls and unusable working directories become host blocks before guard evaluation. A valid extraction produces the same tool invocation used by command hooks, so plugin calls receive the same policy and audit treatment without sharing an agent's wire format.

References: src/…/plugin-adapter.ts• L17-69 src/…/plugin-adapter.ts• L71-120 src/…/tool-call.ts• L51-107

Amp tool-call adapter

The Amp adapter turns a plugin tool-call event into the shared tool invocation used by the safety guard. It validates the tool name and input, checks the configured workspace, then uses the Amp API to classify the call as a shell command or a non-command tool.

Amp keeps the workspace root as the policy scope. A shell call may provide a different execution directory, but that directory must resolve to a real usable directory. This supports commands that run outside the workspace while still giving path checks the true execution location. The adapter records the Amp thread as the session and returns either allow or a redacted reject-and-continue message.

References: src/…/tool-call.ts• L51-107 src/…/tool-call.ts• L110-140

Tool route model

The route tells the safety system what kind of tool input it received. Exact tool-name matches create a command route with a shell mode. Other recognized names create a path, patch, grep, or glob route. An unrecognized name becomes unknown rather than gaining command power by accident.

This distinction limits the effect of agent-specific fields. A patch payload that contains text such as a shell command remains a patch request, and an unknown tool does not receive destructive command analysis. Non-command routes still allow path protections to inspect file targets. The route maps live beside each adapter and use getToolRoute from src/…/intake.ts.

RouteSafety meaning
commandAnalyze the extracted command using POSIX, PowerShell, or automatic shell rules
patchTreat the input as a file change rather than as shell text
pathApply path checks to the tool's file target
grep or globApply the matching non-command path behavior
unknownDo not infer a command; retain applicable path protection

References: src/…/intake.ts• L131-137 src/…/invocation.ts• L1-30

Agent identity detection

Some Claude-shaped payloads can come from Claude Code, Codex, or GitHub Copilot CLI. The Claude Code adapter uses the transcript path to identify the caller for audit records without changing the safety decision.

Detection first checks whether the canonical transcript path is inside one configured agent root. The default roots are .codex, .copilot, and .claude under the home directory. CODEX_HOME, COPILOT_HOME, and CLAUDE_CONFIG_DIR can replace those roots. A valid absolute path must match one root only; a relative path, sibling-prefix path, ambiguous match, or path that exceeds the canonicalization budget produces unknown. If no root matches, Claude-specific environment markers can identify Claude Code.

The detected value is audit metadata. The adapter still runs the same common route and guard, even when the value is unknown.

References: src/…/agent-detection.ts• L7-61 src/…/hook.ts• L26-34

Working-directory containment

Working-directory handling keeps the directory used to load policy aligned with the directory where the agent will run the tool. A usable directory must exist and be readable and searchable. When containment is required, trusted roots and the requested directory are resolved to real paths before the system checks whether the request is inside a trusted root. A separate canonical resolver supports agents whose commands may run outside the workspace root while still giving path guards the real execution location.

The standard adapters use the hook cwd, or the process directory when cwd is absent. A supplied empty, non-string, missing, or unusable directory fails closed. Some agents add a second directory field, which is checked against the agent's trusted roots:

AgentExtra directoryContainment rule
Antigravity CLICwd for commands; file targets for other toolsCommand Cwd stays in a workspace root. Non-command targets select one containing workspace root.
Kimi Codetool_input.cwdThe command directory stays inside the session configuration directory.
Hermes Agenttool_input.workdirThe work directory is resolved from the session directory and must resolve to a real trusted directory.
Cursorworkspace_roots and working_directoryThe base directory and command working directory stay inside the declared workspace roots.

The result has two values: configCwd is the policy scope, and executionCwd is the directory used by the tool. They are equal for the standard case. They differ when an agent runs a command in a contained subdirectory, which lets policy scope remain stable while path analysis uses the real execution directory.

References: src/…/intake.ts• L21-82 src/…/common.ts• L64-107 src/…/hook.ts• L85-185 src/…/hook.ts• L12-17 src/…/hook.ts• L36-64 src/…/hook.ts• L61-120

Input limits and fail-closed handling

Hook input is bounded before JSON parsing. readBoundedHookInput accepts at most 8 MiB of raw UTF-8 bytes, counts bytes across chunks, and stops the input source as soon as a chunk exceeds the limit. An oversized or unreadable stream is returned to the agent as a single parse-style denial rather than being buffered without limit.

Later stages also stop when tool input or path canonicalization exceeds a safety limit. Missing command fields, malformed encoded tool arguments, invalid tool names, bad directory values, and unexpected guard failures do not become an allow result. They produce a failed-closed denial in the adapter's protocol format. Debug mode may add a redacted diagnostic to standard error; the normal denial remains the agent-facing output.

References: src/…/intake.ts• L84-128 src/…/common.ts• L162-197 src/…/common.ts• L230-299

Denial formatting

The shared denial model carries the reason and optional rule, tool, command, segment, and configuration warning. formatDenial redacts sensitive values before it builds the message. A command or path segment is limited to 200 characters by default. The message includes a block marker, the reason, useful evidence, and a footer that tells the agent whether to stop, narrow, use an alternative, or ask the user.

Each adapter then wraps that message in the response object its host understands:

AgentDenial responseAllow response
Claude Code and Kimi CodehookSpecificOutput.permissionDecision = deny with the event name and reasonEmpty output
Gemini CLIdecision = deny, with reason and systemMessageEmpty output
GitHub Copilot CLIpermissionDecision = deny with a reasonEmpty output
Antigravity CLIdecision = deny with a reasonEmpty output
Hermes Agentaction = block with a messageEmpty output
Ampaction = reject-and-continue with a formatted messageaction = allow
Cursorpermission = deny with the same user and agent messagepermission = allow

The failed-closed reason states that the safety check failed unexpectedly and is not caused by the user's command. This is kept separate from a policy denial so an agent can report a system problem without treating it as a rule match.

References: src/…/denial.ts• L33-56 src/…/denial.ts• L58-161 src/…/hook.ts• L26-34 src/…/hook.ts• L31-52 src/…/hook.ts• L29-61 src/…/hook.ts• L66-82 src/…/hook.ts• L40-58 src/…/hook.ts• L19-33 src/…/tool-call.ts• L138-140

Change checklist

When these files or sections are changed, remember to consider these:

  • A new runtime hook must stay aligned across the catalog metadata, hookRunners, CLI flag parsing, event filter, input adapter, and output shape.
  • A tool-name change must update the exact route map and preserve the intended shell mode. A loose match can turn a non-command tool into command analysis.
  • A new working-directory field must set both the policy scope and the execution directory, then apply containment before guard evaluation.
  • A change to Claude-shaped payloads must preserve the transcript-root checks and the audit agent or shape values.
  • A denial reason or evidence field must remain safe after redaction and remain valid in every host response wrapper.
  • Changes to the raw hook limit must preserve byte counting across stream chunks and the fail-closed behavior at the first overflow.
  • A change to the shared hook adapter must preserve the order of bounded input, event filtering, route and context checks, audit, guard evaluation, and host output.
  • A change to the plugin adapter must preserve malformed-call audits, cancellation handling, host result mapping, and the failed-closed behavior for unexpected errors.
  • A change to the Amp tool-call adapter must preserve workspace-root validation, shell-command extraction through the Amp API, thread audit data, and the allow or reject-and-continue result contract.

Important failure modes

TriggerConsequenceGuard
No JSON, a scalar or array envelope, or input above 8 MiBOne protocol denial reports a parse or failed-closed resultBounded stdin reading and object validation stop the request before evaluation
Recognized command tool with a missing or malformed commandThe agent receives a failed-closed denialTool input extraction and command-limit handling do not infer a command
Supplied cwd, workdir, or working directory is missing, not a usable directory, or outside trusted rootsThe request is denied before guard evaluationCanonical directory checks and root containment protect both policy and execution context
Claude-shaped transcript matches no root or matches more than one rootAudit identity is unknown; safety evaluation still runsCanonical root matching requires one unambiguous match
Tool name differs from the exact command nameDestructive command analysis is not inferred; applicable path checks can still runPer-agent route maps grant command capability only to verified names
Hook event does not belong to the adapterNo hook output is producedEach adapter filters its supported event before tool processing
Plugin extraction returns a malformed call or the plugin context is cancelledThe host receives a failed-closed block and the malformed call is auditedThe shared plugin handler checks cancellation and records malformed denials before evaluation
Amp has no usable workspace root or its tool-call helper cannot decode the eventThe tool call is rejected as failed closedWorkspace resolution and helper errors become an integration denial before guard evaluation
Amp supplies a missing, inaccessible, or unsupported shell working directoryThe command is rejected before evaluationCanonical directory resolution validates the execution directory against the workspace context

Key files

FileWhy to read it
src/…/common.tsDefines the shared hook lifecycle, input bound, route selection, context checks, guard call, and allow or deny handoff.
src/…/pre-tool-use.tsShows the common PreToolUse contract, including event filtering, tool fields, and optional person prompts.
src/…/hook-integrations.tsConnects catalog metadata and CLI flags to the one selected hook runner.
src/…/hook.tsShows the public hook command contract and generated help entries.
src/…/catalog.tsDefines which integrations have runtime hooks and which flags name them.
src/…/invocation.tsDefines the shared route and the policy and execution directory context.
src/…/denial.tsDefines the common denial data and the redacted agent-facing message.
src/…/intake.tsDefines bounded input, route selection, standard context checks, and directory containment helpers.
src/…/plugin-adapter.tsDefines the shared plugin tool-call flow for extraction, audit, evaluation, and host result mapping.
src/…/agent-detection.tsDefines identity detection for Claude-shaped payloads.
src/…/hook.tsShows a standard event adapter with Claude-shaped identity detection.
src/…/hook.ts and src/…/hook.tsShow adapters that decode or normalize nested agent tool arguments.
src/…/hook.ts and src/…/hook.tsShow agent-specific working-directory and allow-output behavior.
src/…/tool-call.tsShows a plugin tool-call adapter that resolves Amp shell calls, separates policy and execution directories, records thread sessions, and formats host-specific results.