Skip to content
Browse the documentation

Permission Routing (Hooks)

Route the tool permissions of Claude Code, Codex CLI, Gemini CLI and OpenCode through AgentLock with hooks, Bash rules and approvals.

What is permission routing?

Permission routing controls whether AgentLock or the agent's harness decides if a tool call is allowed. Each agent has a routing mode you pick on its detail page under Tool permission routing:

Bypass — AgentLock is not in the loop. The harness handles its own permissions, usually by prompting in the terminal. Nothing for this agent shows up in the AgentLock inbox or audit log. Pick this when you don't want AgentLock involved for that agent.

Gateway — Every controlled tool call (Bash, Edit, Write and the equivalents for other harnesses) flows through AgentLock. The decision happens server-side based on your policy: anything you've explicitly allowed runs immediately, anything you've explicitly blocked is denied immediately, everything else lands in your approvals inbox (web + mobile, biometric-gated). Gateway mode is strict by default — without policy rules every command needs approval. Nothing ever silently slips through to the terminal.

Terminal — Same loop as Gateway: every controlled call goes through AgentLock, and your Bash rules, kill switch, safe mode and audit log all apply. The difference is where you decide — instead of the approvals inbox, anything that needs a decision surfaces as the harness's own native permission prompt (in Claude Code: the y / yes-always-this-session / no dialog) with the AgentLock reason attached. Explicit Allow/Block rules still act immediately, and two-person approvals still go to the inbox — one keypress can't stand in for two approvers.

Gateway or Terminal? Pick Terminal when you sit at the terminal anyway and want approvals inline, without switching to the inbox — you keep the policy engine and the audit trail. Pick Gateway when you approve from your phone, when approvers are other people, or when you want the decision itself recorded centrally (in Terminal mode the audit records that a call was surfaced locally, not which button you pressed).

Why use Gateway: if you're not at the keyboard you can't approve. With Gateway on, requests show up in your inbox and the harness waits for your decision.

Supported harnesses: Claude Code, OpenAI Codex CLI, Google Gemini CLI, OpenCode.

Set up Claude Code

0. Get the adapter — no repo checkout needed, both files are hosted:

sh
curl -fsSL --create-dirs -o ~/.agentlock/claude-code-agentlock-hook.mjs https://app.agentlock.net/hooks/claude-code-agentlock-hook.mjs
curl -fsSL --create-dirs -o ~/.agentlock/hooks/core.mjs https://app.agentlock.net/hooks/hooks/core.mjs

Then use node ~/.agentlock/claude-code-agentlock-hook.mjs as the hook command below. Your agent's detail page (Tool permission routing → Set up the hook) shows the same snippets pre-filled.

1. Create an API token for the agent (Agents → your agent → Tokens tab → Create Token).

2. Set environment variables in the shell where you run claude:

sh
export AGENTLOCK_URL="https://app.agentlock.net"
export AGENTLOCK_TOKEN="alt_..."

3. Edit ~/.claude/settings.json (or your project's .claude/settings.json):

json
{
  "hooks": {
    "PreToolUse": [{
      "matcher": "Bash|Edit|Write|MultiEdit|NotebookEdit",
      "hooks": [{
        "type": "command",
        "timeout": 360,
        "statusMessage": "Waiting for AgentLock",
        "command": "node ~/.agentlock/claude-code-agentlock-hook.mjs"
      }]
    }],
    "PermissionRequest": [{
      "matcher": "Bash|Edit|Write|MultiEdit|NotebookEdit",
      "hooks": [{
        "type": "command",
        "timeout": 360,
        "command": "node ~/.agentlock/claude-code-agentlock-hook.mjs"
      }]
    }]
  }
}

Restart Claude Code. The next time it tries a Bash/Edit/Write call, you'll see "Waiting for AgentLock" in the terminal and the request shows up in your approvals inbox.

PreToolUse vs PermissionRequest: PreToolUse fires for every controlled tool, even ones Claude Code wouldn't normally ask about (it enforces routing). PermissionRequest covers the native prompt path so AgentLock can answer on behalf of the user.

Set up Codex CLI

Codex's hook envelope is byte-identical to Claude Code's, so the setup is nearly the same — just a different config file and a feature flag.

0. Get the adapter (hosted, no repo needed):

sh
curl -fsSL --create-dirs -o ~/.agentlock/codex-agentlock-hook.mjs https://app.agentlock.net/hooks/codex-agentlock-hook.mjs
curl -fsSL --create-dirs -o ~/.agentlock/hooks/core.mjs https://app.agentlock.net/hooks/hooks/core.mjs

1. Create an API token (Agents → your agent → Tokens) and set env vars:

sh
export AGENTLOCK_URL="https://app.agentlock.net"
export AGENTLOCK_TOKEN="alt_..."

2. Enable hooks in ~/.codex/config.toml:

toml
[features]
codex_hooks = true

3. Add the hook to ~/.codex/hooks.json:

json
{
  "hooks": {
    "PreToolUse": [{
      "matcher": "Bash|apply_patch",
      "hooks": [{
        "type": "command",
        "command": "node ~/.agentlock/codex-agentlock-hook.mjs",
        "statusMessage": "Waiting for AgentLock",
        "timeout": 360
      }]
    }]
  }
}

The adapter normalises Codex's apply_patch to Claude Code's Edit internally so the gateway's classifier and your Bash rules behave the same way regardless of which harness sent the command.

Set up Gemini CLI

Gemini's hook output format differs from Claude Code's ({ decision, reason } instead of the hookSpecificOutput wrapper), but the adapter handles that — your config still looks similar.

0. Get the adapter (hosted, no repo needed):

sh
curl -fsSL --create-dirs -o ~/.agentlock/gemini-agentlock-hook.mjs https://app.agentlock.net/hooks/gemini-agentlock-hook.mjs
curl -fsSL --create-dirs -o ~/.agentlock/hooks/core.mjs https://app.agentlock.net/hooks/hooks/core.mjs

1. Create an API token and set env vars (AGENTLOCK_URL, AGENTLOCK_TOKEN).

2. Edit ~/.config/gemini-cli/settings.json:

json
{
  "hooks": {
    "BeforeTool": [{
      "matcher": "run_shell_command|write_file|edit_file|replace|create_file",
      "hooks": [{
        "type": "command",
        "command": "node ~/.agentlock/gemini-agentlock-hook.mjs",
        "name": "AgentLock",
        "timeout": 360000
      }]
    }]
  }
}

The matcher uses Gemini's tool names — run_shell_command is the equivalent of Claude Code's Bash, write_file of Write, and replace/edit_file of Edit. Read-only tools like read_file and list_directory are intentionally NOT in the matcher (you don't want to approve every file read).

A note on Gemini's terminal prompt: Gemini doesn't have a built-in "ask the user first" output for hooks. So when this agent is set to Bypass, the adapter steps aside and Gemini's own permission prompt takes over in the terminal. In Gateway mode the decision always comes back from AgentLock (allow, deny, or send to your approvals inbox), so the local prompt never appears. In Terminal mode the local prompt is used deliberately — AgentLock classifies the call, applies your rules and writes the audit event, then hands the ask to Gemini's prompt.

Set up OpenCode

OpenCode is the odd one out: plugins are in-process JS modules, not external commands. Setup is one file copy + env vars.

1. Create an API token and set env vars (AGENTLOCK_URL, AGENTLOCK_TOKEN).

2. Download the plugin (hosted, no repo needed) into one of OpenCode's plugin directories:

sh
# global (every project):
curl -fsSL --create-dirs -o ~/.config/opencode/plugins/agentlock.mjs https://app.agentlock.net/hooks/opencode-agentlock-plugin.mjs
  • ~/.config/opencode/plugins/agentlock.mjs (global, applies to every project)
  • <project>/.opencode/plugins/agentlock.mjs (per-project)

3. Restart OpenCode. No further configuration — OpenCode discovers plugins in those directories automatically and registers the tool.execute.before hook for every tool call.

How blocking works in OpenCode: denials surface to the agent as a tool error so it sees the call was rejected; allows go through silently. OpenCode's plugin surface has no "ask the user first" hook, so when this agent is set to Bypass the plugin steps aside and OpenCode's own permission system (if any) handles the prompt. In Gateway mode the decision always comes back from AgentLock, so this fallback never fires. In Terminal mode AgentLock answers ask-locally for unmatched calls — the plugin lets the call through to OpenCode's own permission flow after classifying and auditing it.

The plugin is self-contained (it doesn't import from sibling files) so you only need to copy this one file. The downside is a small amount of duplicated logic with the external-command adapters; the upside is drop-in install.

allowed_tools and the meta-tool

Every adapter talks to AgentLock through a virtual tool called permission.claude_code. It's a no-op connector — the harness still runs every command locally; AgentLock only records the approval and audit event.

If your agent has an empty allowed_tools list (the default), nothing extra is needed.

If you've restricted the agent to a specific allowlist, AgentLock automatically lets the routing meta-tool through while the agent is set to Gateway or Terminal (Terminal mode still forwards two-person approvals through the gateway). You do not need to add it to the allowlist by hand. Switching the agent back to Bypass removes that exemption so a locked-down agent stays locked down.

This is intentional: the meta-tool is invisible plumbing between the hook and AgentLock, not an action the agent itself ever calls.

Fallback behaviour when AgentLock is unavailable

Two failure modes the adapters handle explicitly:

1. AGENTLOCK_TOKEN is unset. The hook falls back to the harness's normal local prompt — it does NOT block tool use. An unfinished setup doesn't brick your dev session: you just get the native prompt as if AgentLock weren't installed.

2. AgentLock can't be reached or refuses the call (network down, server error, or an invalid, expired or revoked token). Default behaviour is fail-closed: the adapter denies the tool call rather than letting it through unsupervised. To switch to fail-open ("fall back to local prompt during outages"), set:

sh
export AGENTLOCK_HOOK_FALLBACK="ask"

Default is AGENTLOCK_HOOK_FALLBACK="deny". Pick ask if your team is small and you'd rather not block dev work during the rare API outage; pick deny (the default) if you're using AgentLock to enforce production-style guardrails and "no decision = no action" is the right posture.

Additional optional env vars:

  • AGENTLOCK_HOOK_TIMEOUT_MS — max wait for an approval (default 300000 = 5 minutes)
  • AGENTLOCK_HOOK_POLL_MS — interval between polls while waiting (default 2000 = 2s)

Custom Bash classification rules

By default AgentLock classifies forwarded Bash commands with a small built-in pattern list (read-only / write / admin-class). You can override or extend that classifier per policy under Policies → [policy] → Bash command rules (or the same section in the Create Policy wizard).

Each rule is one line, format DECISION: pattern:

text
ALLOW: git status
ALLOW: grep *
ALLOW: grep /home/*
REQUIRE_APPROVAL: pnpm install *
BLOCK: /^(rm|dd|mkfs)\b/

Pattern syntax — globs, same style as the SSH command rules:

  • grep — only the bare command, no arguments
  • grep * — grep followed by anything (grep foo, grep /tmp/x)
  • grep /home/* — grep with arguments that start with /home/
  • ^git (push|pull) — regex (any regex hint character switches the line to regex mode)
  • /^foo\b/ — fully raw regex when you wrap the whole pattern in slashes

Leaving out the * makes your rule narrower, not wider — exact match is the default. Rules are evaluated top to bottom and the first match wins.

Decisions:

  • Allow — the harness runs the command immediately, no inbox stop
  • Block — denied right away, the agent gets an error
  • Require approval — sent to your approvals inbox regardless of how the command would otherwise be classified

Default decision (no match) controls what happens when nothing in your list matches. Out of the box it's Require approval for everything, so anything you haven't whitelisted still asks you. Switch it to Allow if you'd rather only catch the commands you explicitly block, or to Block for the opposite stance.

These rules apply to agents set to Gateway or Terminal. In Terminal mode an unmatched command (or an explicit Require-approval rule) surfaces the harness's own prompt instead of the inbox; Allow and Block behave identically in both modes. Agents set to Bypass don't go through AgentLock at all, so the policy isn't consulted.

Bash rule editor — Presets, Linter, Sandbox, Recent commands

Both the policy wizard and the advanced editor expose four helpers stacked under the rules textarea:

Starter presets — curated rule sets you can drop in as a starting skeleton:

  • "Common safe Git commands" — read-only Git inspection (status, diff, log, branch)
  • "Read-only inspection toolkit" — ls, cat, grep, find style commands
  • "Package manager workflow" — typical npm/pnpm/yarn flows that send installs to the approval inbox
  • "Common admin banlist" — straight blocks for rm -rf, dd, mkfs, shutdown and friends

Each preset has an Append button (add on top of what you already have) and a Replace button (start over with just the preset). Treat them as a starting point, not a finished policy.

Linter — flags three classes of issue as you type:

  • syntactically invalid lines (missing decision, malformed pattern)
  • rules that are shadowed by an earlier rule and would never get a chance to match
  • Allow rules on dangerous commands like rm -rf, git push, kubectl apply — they still work as written, the linter just wants you to notice before saving

Test sandbox — type any command and see which rule would match, what the resulting decision is, and why. Feedback is instant and the result is exactly what an agent would get if it tried that command live.

Recent Bash commands — click "Show" to load the last 50 unique Bash commands that came through this workspace, with the timestamp of the most recent occurrence and a count of how often the command came up. One click adds any of them as Allow, Require approval, or Block. This list is only visible to owners and admins.

Approve & remember — write a rule from inside the approval card

Workspace owners and admins see an extra Approve & remember button on the approval card whenever the request is a Bash permission from any of the supported harnesses. Clicking it opens an inline form pre-filled with:

  • a suggested glob (e.g. git push * for a git push origin main request — last literal arg replaced with *)
  • a decision dropdown (default Allow, change to Require approval / Block as needed)
  • an optional description (max 200 chars)

Submitting the form approves the request and writes the rule to the policy that's actually applied to this agent — so the next time a command of the same shape comes in, it hits the rule directly.

Editing in place when the pattern already exists. If the policy already has a rule with exactly the same pattern, the new decision replaces the old one in the same spot rather than getting appended at the bottom. This matters because rules are evaluated top to bottom: a rule appended below a still-matching duplicate would just be dead text. Both the replacement and the original decision are recorded in the audit log so you can see what changed.

Two-person approvals. When a request needs two approvers, the first Approve & remember click only records the first approval — it does not yet write the rule, because the second approver might still deny. If the rule were written too early, the first approver could effectively bypass the two-person check on every future call of that shape. Once the second approver confirms, the rule is written.

Failure modes: if the rule write fails (for example because the policy is already at the maximum number of Bash rules and the new rule isn't replacing an existing one), the approval still goes through and the form surfaces a warning. Resolve it by hand in the policy editor.

Permissions: approvers can decide approvals but can't change policies, so only owners and admins see the Approve & remember button.

Safety gates on Bash rules — shell metacharacters and admin commands

Two safeguards apply on top of your custom Bash rules:

1. Shell-metacharacter escalation. When a glob-pattern ALLOW rule (or a default decision of Allow) matches a command, but the command itself contains ;, &, &&, ||, |, backtick, $ (including $(), ${…} and $VAR), >, <, or a line break, the rule is escalated to REQUIRE_APPROVAL — the command is forwarded for human review instead of auto-approved.

This stops ALLOW: git status * from silently approving git status; rm -rf / or git status > /etc/passwd. The reason shows up in the routing decision and the audit event so you can see why a command you expected to allow ended up in the approvals queue.

If you genuinely want to approve a specific compound command, wrap your pattern in /.../ (or use any regex hint character like ^, (, |). Raw-regex mode is interpreted as "I know what I'm doing — don't escalate":

text
# Glob — escalates on shell-meta:
ALLOW: git pull origin main

# Regex — opts in to compound matching, no escalation:
ALLOW: /^git pull origin main && pnpm install$/

Note that BLOCK and REQUIRE_APPROVAL rules are never escalated — they're always honoured as written. The gate only fires on ALLOW, where the surprise risk is highest.

2. Admin-class commands are NOT auto-escalated (the policy engine used to do this; it was removed because it surprised admins more than it protected them). Instead, the policy editor's linter warns at save time when an ALLOW rule covers an admin-class command (git push, rm -rf, kubectl apply, terraform apply, etc.). The runtime then honours the rule exactly as written — your explicit ALLOW is treated as your explicit intent.

The Danger Zone at the bottom of the policy editor is a separate, policy-wide setting for all other tools: while auto-approval of Admin actions is off (the default), an Allow that applies to an Admin-classified action, for example an SSH command rule, is escalated to approval. It does not change Bash rules, which are honoured as written.

Permission Routing (Hooks) | AgentLock Docs