Gateway hooks
Gateway hooks let a gateway or agent harness send conversations to the Watcher API. You do not need to install the Watcher client on developer machines. The resulting sessions, tool-call judgments, and grades appear in the Analyzer. See the gateway deployment reference for Aperture and LiteLLM diagrams, network paths, and credential boundaries.
| Endpoint | When to use it | Who can enforce the result |
|---|---|---|
POST /api/v1/hooks/pre-tool-use | Send a structured conversation, or a raw provider request and response, for enforcement, observation, or ingestion only. | In enforce mode, your integration holds the call. It applies Watcher's returned decision. |
POST /api/v1/hooks/aperture | Every Aperture hook stage, told apart by metadata.stage: the request before inference (pre_request), pending client tool calls (pre_response), or a completed exchange (post_complete). | pre_request: nobody; Watcher adds a fixed instruction about its notices. pre_response: Aperture releases allowed calls, replaces each refused call with a notice or removes it, or blocks the pending callback. post_complete: nobody; Watcher records advisory judgments after the response. |
POST /api/v1/hooks/aperture/entire-request | Observation only: a completed supported coding-agent request and response. | Nobody through this hook. It records advisory judgments after the response. |
Authentication and reachability
On Apollo cloud, use https://app.apolloresearch.ai/api as the API base URL.
For self-hosting, use your deployment's Analyzer hostname with /api. The
gateway must reach that hostname over HTTPS on TCP port 443. For a private
self-hosted deployment, configure routing from the gateway to the Watcher host.
Configure DNS and firewall rules.
In SSO mode, send an organization API key in x-api-key. Attributing sessions
to another developer requires sessions:write:any on any hook. Aperture always
supplies another developer's identity through metadata.login_name. Therefore,
sessions:write:any is mandatory. Its absence returns HTTP 403. Generic
integrations can omit user and act as the authenticated caller. The optional
user field is honored only with sessions:write:any. A service key with only
sessions:ingest can record unattributed generic-hook sessions. This is
session-write permission for unattributed sessions. All conversation IDs match
within the caller's write scope. A personal capture cannot claim an unowned
session or join another developer's session. It records a separate session.
To join a developer's client recording, attribute the capture to that developer
using trusted identity and sessions:write:any. See
Two recorders.
Non-ephemeral enforce and observe requests record their judgments. Paused
requests record only the transcript. In enforce and observe modes, callers
without session-write permission still receive a completed judgment. However,
the endpoint skips transcript and decision recording. These rules describe full
requests. Append requests require authority to write
the named session before reading its stored context. They cannot be ephemeral.
On a full request, set ephemeral: true to evaluate without
storing the transcript, decision, or grades. Usage accounting still applies.
When you send a coding agent's own transcript file, store it through your own
uploads, and send only part of it here, set record_transcript: false instead:
the endpoint stores neither the messages nor a decision, but keeps the grades
under the conversation your external_ids name, so a decision you upload later
can cite them.
In self-hosted proxy mode, Watcher does not accept organization API keys. Your
reverse proxy must authenticate the gateway. It must pass an identity with
session-write permission. Attributing sessions to another developer requires
permission to write sessions for other users. Therefore, Aperture needs that
permission. Aperture can send a configured credential as x-api-key. However,
your proxy must validate it and supply that authorized identity. An interactive
browser sign-in alone does not authenticate a gateway request. See
API authentication and
self-hosted authentication.
Enforcement modes
The enforcement mode in the administrator's
managed client settings
document controls hook behavior through enforcement.mode. Administrator
changes can take up to 60 seconds to reach a server worker's policy cache. An
in-flight request keeps the policy snapshot it started with. This applies to all
its inputs.
| Administrator mode | Generic pre-tool-use hook | Aperture pre-response hook | Aperture entire-request hook |
|---|---|---|---|
enforce | Evaluates the call. Returns an enforceable decision. | Evaluates pending calls before release. Withholds denials and escalations. | Evaluates the call. Records an advisory judgment. |
observe | Evaluates the call. Returns its completed advisory judgment with decision: "deferred". Authorized, non-ephemeral requests record that judgment. | Releases calls immediately; evaluates them in the background. | Evaluates the call. Records an advisory judgment. |
paused | Ingests the transcript without evaluating thresholds, rules, or monitors. Records no tool-call decision. | Releases calls unchanged and records only the transcript. | Ingests the transcript without evaluating thresholds, rules, or monitors. Records no tool-call decision. |
For example, an administrator can select observation in the managed document:
enforcement:
mode:
value: observe
permission: locked
Generic integrations can set enforcement.mode in settings_overrides. You can
use either a YAML string or a JSON object. For example:
{"settings_overrides": {"enforcement": {"mode": "observe"}}}
The normal administrator permission rules apply. An override that changes a locked setting is rejected with HTTP 422. One that repeats the locked value is accepted, so a caller can send the settings it already resolved without dropping the locked ones. Watcher merges permitted overrides into the administrator's settings before evaluating the request. The override document is limited to 65,536 characters of YAML or serialized JSON. Oversized overrides return HTTP 422. Overrides that take too long to validate and merge also return HTTP 422.
The generic hook waits for evaluation before responding. This applies in both enforce and observe modes. The request's policy snapshot governs its judgments and subsequent recording. Full requests record transcripts and decisions after the response. Append requests wait for their messages and available decisions to be stored before returning HTTP 200. Recording requires session-write permission and non-ephemeral input.
Both Aperture routes use the administrator's settings. Their fixed webhook
body does not carry settings_overrides. The entire_request route caps
behavior at observe, even under a locked enforce policy. It acknowledges
admission before processing the capture. The opt-in pre_response stage waits
for a decision in enforce mode. In observe mode it allows delivery immediately
and grades in the background. Observation and allowed-call recording run
asynchronously. Refused calls are recorded before their action is returned. See
Configure Aperture enforcement.
Paused hooks return an unjudged acknowledgement. They only ingest the transcript, as the Watcher client's paused mode evaluates nothing either. Hook modes do not configure trailing review. Trailing review can separately review ingested sessions.
Tool names and policy
Tool thresholds
and command rules
name Claude Code's tools, such as Bash, Read, Write and Edit. This holds
for the built-in settings and usually for your own. Other agents give the same
kinds of tool their own names and argument keys. Before evaluating thresholds
and command rules, gateway hooks translate a call from a supported agent onto
the matching Claude Code tool. The built-in policy and your Bash, Read or
Write entries therefore apply to those agents' calls too. One entry for a
Claude Code tool now covers every agent's matching tool: an always-allow pair
on Read or Bash, for example, switches off that tool's rules for all of
them, except an agent whose own exact entry (described below) supplies its
thresholds.
Translation affects only thresholds and command rules. The stored tool call, the
transcript and the input the graders review keep the agent's own tool name and
arguments, so the Analyzer shows what the agent called. A translated call's
recorded decision carries a note in its decision_context field, returned with
a trajectory's tool-call decisions, for example
Policy evaluated this run_shell_command call as Bash. The note names the
Claude Code tool even when an entry keyed to the agent's own name supplied the
thresholds. A decision without the note was evaluated under the agent's own
tool name.
Which translations apply depends on the identified agent. The Aperture hook uses
the agent whose markers matched (see Configure Aperture).
An OpenCode user agent takes precedence over Claude Code or Codex system text in
the same request, so such a capture uses the OpenCode translations. pi's markers
take precedence over Claude Code's, so a pi capture uses the pi translations
even when it carries Claude Code's user agent and identity line. The generic
hook uses the claude_code, codex, opencode or github_copilot_cli key in
external_ids; with none of them, tool names are evaluated as sent. The Watcher
client does not translate: on the developer's machine, Claude Code and Codex
report their tool calls under the names the built-in settings use. GitHub
Copilot CLI calls sent under Copilot's own names are translated as below.
| Agent | Tools translated, as agent name → Claude Code name | Left under the agent's own name |
|---|---|---|
| Claude Code, including Claude Cowork | mcp__workspace__bash → Bash. Claude Code's own tools already use these names. | Everything else. |
| Codex | exec_command, shell, shell_command, container.exec, local_shell → Bash; view_image → Read; update_plan → TodoWrite; spawn_agent, collaborationspawn_agent → Agent; send_message, collaborationsend_message → SendMessage; request_user_input, request_user_input_async → AskUserQuestion; tool_search → ToolSearch | exec (Code Mode), js, write_stdin, and wait_agent, followup_task, list_agents, close_agent, interrupt_agent, wait, sleep, with or without a Codex tool-group prefix such as collaboration or clock. Names of the form mcp__<server>__<tool>, which Codex's hooks give MCP tools, even when <tool> is a translated tool's name. apply_patch already matches the built-in rules. |
| OpenCode | bash → Bash; read, write, edit → Read, Write, Edit; glob, grep → Glob, Grep; webfetch, websearch → WebFetch, WebSearch; todowrite → TodoWrite; task → Agent; skill → Skill; lsp → LSP; question → AskUserQuestion; plan_exit → ExitPlanMode | list, and the experimental code-mode tool execute. apply_patch already matches. |
| Gemini CLI | run_shell_command → Bash; read_file, write_file, replace → Read, Write, Edit; glob → Glob; grep_search, search_file_content → Grep; web_fetch → WebFetch; google_web_search → WebSearch; write_todos → TodoWrite; activate_skill → Skill; invoke_agent → Agent; ask_user → AskUserQuestion; enter_plan_mode, exit_plan_mode → EnterPlanMode, ExitPlanMode | list_directory, read_many_files, save_memory, get_internal_docs. |
| Qwen Code | run_shell_command → Bash; read_file, write_file → Read, Write; edit, replace → Edit; glob → Glob; grep_search, search_file_content → Grep; web_fetch, web_search → WebFetch, WebSearch; todo_write → TodoWrite; agent, task → Agent; skill → Skill; ask_user_question → AskUserQuestion; enter_plan_mode, exit_plan_mode → EnterPlanMode, ExitPlanMode | exec (code mode), list_directory, save_memory, and the scheduling, team and worktree tools. |
| Mistral Vibe | bash, git_bash → Bash; powershell → PowerShell; read_file, read, write_file → Read, Read, Write; edit, search_replace → Edit; grep → Grep; web_fetch, web_search → WebFetch, WebSearch; todo → TodoWrite; task → Agent; skill → Skill; ask_user_question → AskUserQuestion; exit_plan_mode → ExitPlanMode | The companion tools that read or feed a running shell session. |
| pi | bash → Bash; read, write, edit → Read, Write, Edit; grep → Grep; find → Glob; powershell → PowerShell. With a Claude subscription pi already sends Read, Write, Edit, Bash and Grep; for the file tools under either spelling, pi's path argument is evaluated as file_path. | ls. |
| GitHub Copilot CLI | bash, local_shell → Bash; powershell → PowerShell; view, create, edit → Read, Write, Edit, with path evaluated as file_path; glob → Glob; grep, rg → Grep; web_fetch, web_search → WebFetch, WebSearch; task → Agent; skill → Skill; ask_user → AskUserQuestion; write_bash, write_powershell → Bash, PowerShell, with the typed text as command; str_replace_editor by its command: view → Read, create → Write, str_replace and insert → Edit; lsp reading operations → LSP | lsp rename and any operation not listed, other str_replace_editor commands, list_bash, read_bash, stop_bash, sql, and MCP tools. apply_patch already matches the built-in rules. |
| Antigravity CLI | run_command → Bash; view_file, write_to_file, replace_file_content → Read, Write, Edit; grep_search → Grep; find_by_name → Glob; read_url_content → WebFetch; search_web → WebSearch | list_dir, manage_task, ask_question, generate_image. |
A tool is translated only where it does what the Claude Code tool does. A tool
left under its own name is evaluated under that name, without translation: add
threshold entries and rules under that name, as the Analyzer shows it. A tool
with no exact entry, matching glob or built-in default receives the unknown
fallback pair. With a "*" glob present, that fallback is unused. See
how tool thresholds are selected.
Code-mode tools (Codex exec, Qwen Code exec, OpenCode execute) take a
JavaScript program that calls the agent's other tools. The program is graded as
one call on its text. The shell commands and file operations inside it are not
evaluated as Bash, Read or Write calls, so the rules for those tools do
not see them.
Codex reads files mostly through its shell tools, which translate to Bash.
Read entries cover only Codex's view_image. Codex's spawn_agent and
send_message are translated bare or in their default collaboration group; if
Codex's configuration renames that group, they are evaluated under the renamed
names.
Policy does not support Codex's non_prefixed_mcp_tool_names feature, which is
off by default, for captured provider requests: the Aperture hook and the
generic hook's raw format. With it on,
Codex's requests no longer mark a tool as coming from an MCP server. Watcher
then names the tool by running the server name and the tool name together, as
the last row of the Codex namespace table under
Configure Aperture describes. That name can
spell a Codex tool the table above translates. A server named local_ with a
tool shell gives local_shell, and a server named collaboration with a tool
send_message gives collaborationsend_message. Such an MCP call is evaluated
as Bash or SendMessage, under those tools' thresholds and rules, allow rules
included, so it can be allowed without grading. Entries keyed to
mcp__<server>__<tool> do not apply to it. Keep the feature off for Codex
traffic that Watcher receives as captured provider requests. A generic hook
request in the ordinary format is evaluated under the tool names it sends, so
send MCP tools as mcp__<server>__<tool> there. The Watcher client is not
affected, because Codex's own hooks still report these tools as
mcp__<server>__<tool>.
Arguments are translated so that rules match what they expect:
- A shell tool's command is matched as the
Bashcommand text, whatever key the agent uses. A command sent as an argument list is joined into one shell command. A list of the formbash -c <script>contributes only the script, and only when the program isbash,shorzsh, by name or under/binor/usr/bin. - A working directory sent with a shell call (such as OpenCode's
workdir) is never added to the command: rules always match the command as the agent wrote it, split at shell control operators such as;,&&and|as usual. A rule anchored with^, such as a deny on^rm -rf, matches the same way whatever directory was sent. - The directory only limits allow rules. It is trusted when it is a plain
relative path inside the project, such as
srcor./pkg/sub, and allow rules then apply as usual. For any other directory (absolute, home-relative, or leaving the project with..), allow rules cannot approve the call, so it is graded (triage, then gateway review) unless a deny or escalate-to-human rule decides it first. This guards against a relative read, such ascat passwdrun in/etc, matching a read-only allow rule. Codexexec_commandand Antigravity CLI calls usually carry an absolute working directory, so allow rules rarely approve them. - Arguments that change what runs without appearing in the command text have
the same effect as an untrusted directory whenever they carry a value: an
environment (Mistral Vibe
env, Codexlocal_shellenv), a shell executable override (Codexexec_commandand Mistral Vibeshell), another execution environment (Codexexec_commandenvironment_id), or a user to run as (Codexlocal_shelluser). So does a request to run outside the agent's sandbox (Codexsandbox_permissionswith any value butuse_default, orwith_escalated_permissionsset to true). Allow rules cannot approve such a call; deny and escalate-to-human rules still apply. - A file tool's path is matched as the
Read,WriteorEditpath.
Entries keyed to an agent's own tool name still apply after translation, with one limit: rules keyed that way can no longer allow a call on their own.
- A
tool_thresholdsentry whose key is exactly the agent's tool name, such asbash, takes precedence over the Claude Code tool's entry. If that entry always allows, always denies or always flags, it decides before any rule, including rules matching the agent's name. A glob pattern that matches only the agent's name never supplies a translated call's thresholds, even when the Claude Code tool has no entry of its own. If such a glob always allows, though, it still switches off rules keyed to names it matches, as any always-allow pair does for its tool's rules. - A command rule whose
tool_namematches the agent's name, including a glob such as*, is also evaluated against the agent's own arguments. There, only its deny and escalate-to-human outcomes count: its allow and its send-to-grading outcomes are ignored. The most severe outcome wins, so such a deny beats aBashallow that matches the same call. - Those deny and escalate-to-human outcomes apply even when the call's
thresholds come from a Claude Code tool that always allows, such as the
built-in
Read. That pair switches off rules keyed toReaditself, for translated and Claude Code reads alike, but not rules matching the agent's name. So under the built-in thresholds a.envdeny keyed toReadnever fires, while one keyed toread_filefires for Gemini CLI reads. An always-allow entry keyed toread_filewould switch that rule off too. - A rule whose
tool_namealso matches the Claude Code name, as*does, applies to the translated call as well, allow included. To allow a translated call, write the rule for the Claude Code name.
Generic pre-tool-use hook
Send the conversation in top-level messages. Include messages through the
assistant message containing the pending tool calls. To send only new messages,
use append_after. input selects the calls
to evaluate. You can send one object or a list of objects, one per call. A list
can contain at most 32 inputs. Larger lists return HTTP 422 before grading or
ingestion. Batches with more than one input must send messages at the top
level. Each input must omit messages or set it to null or []. A nonempty
nested transcript is rejected even when it matches the top-level transcript.
Batch inputs must have distinct tool_use_id values.
A selected ID that appears in the transcript must identify the same tool name
and arguments as the input. Object key order does not matter. However, JSON
value types and string content must match. You may omit tool_input for a call
whose arguments are {}. Explicit null is not an empty object. Repeated
occurrences of that ID must all agree. Mismatches return HTTP 422 before grading
or ingestion. Every non-ephemeral named input requires a matching transcript
call. This applies even when the effective mode is paused. Ephemeral inputs may
omit it.
Watcher evaluates calls concurrently. It returns results in input order. It
ingests the shared transcript once. Do not include tool results that occur after
the pending calls. When a later request carries a call's result, set the tool
message's error if the call failed when it ran. Report a call your integration
refused or cancelled as blocked or cancelled instead; a result with neither
is recorded as completed (see Execution status).
For transcript-only ingestion, supply messages. Set input to null or [],
or omit input. The response is []. No mode override is needed. No tool-call
ID is needed. The transcript may contain historical tool calls without
requesting a judgment for them.
Save this body as hook-request.json, replacing the conversation ID, call ID,
messages, and tool input with your integration's values:
{
"format": "watcher",
"messages": [
{"role": "user", "content": "Print hello."},
{
"role": "assistant",
"content": "",
"tool_calls": [
{"id": "call-001", "function": "Bash", "arguments": {"command": "printf hello"}}
]
}
],
"input": {
"tool_name": "Bash",
"tool_input": {"command": "printf hello"},
"tool_use_id": "call-001"
},
"external_ids": {"other": "conversation-001"}
}
Set WATCHER_API_URL to your API base URL and WATCHER_API_KEY to your
organization API key, then send it:
curl --fail-with-body \
-H "x-api-key: $WATCHER_API_KEY" \
-H "Content-Type: application/json" \
--data-binary @hook-request.json \
"$WATCHER_API_URL/v1/hooks/pre-tool-use"
Multiple tool calls
Select each pending call once. The output list follows input order, even when
that differs from the order of tool calls in messages:
{
"format": "watcher",
"messages": [
{"role": "user", "content": "Read the two files."},
{
"role": "assistant",
"content": "",
"tool_calls": [
{"id": "call-001", "function": "Read", "arguments": {"file_path": "/work/one.txt"}},
{"id": "call-002", "function": "Read", "arguments": {"file_path": "/work/two.txt"}}
]
}
],
"input": [
{"tool_name": "Read", "tool_input": {"file_path": "/work/two.txt"}, "tool_use_id": "call-002"},
{"tool_name": "Read", "tool_input": {"file_path": "/work/one.txt"}, "tool_use_id": "call-001"}
],
"external_ids": {"other": "conversation-002"}
}
For this request, output 0 has tool_use_id: "call-002" and output 1 has
tool_use_id: "call-001". Handle each output separately as described below.
Transcript-only ingestion
Send the transcript with no selected calls:
{
"format": "watcher",
"messages": [
{"role": "user", "content": "Hello."},
{"role": "assistant", "content": "Hello. How can I help?"}
],
"input": null,
"external_ids": {"other": "conversation-003"}
}
The response is HTTP 200 with []. Use the same curl command above with this
body. Setting input to [] or omitting it has the same effect. messages is
required when there are no inputs. Full transcripts are recorded after the
response. An append saves its delta before responding and returns an envelope
with the next append_after cursor and results: []. Neither creates a
tool-call judgment or hook grade when there are no inputs.
Execution status
The hook decides a call before it runs, so Watcher records each evaluated call
with execution status pending. When a later request in the same conversation
carries that call's result in its messages, Watcher sets the status from it:
| What Watcher applied | The call's result | Execution status |
|---|---|---|
allow, deferred (observe and paused modes) or not_evaluated | Sent in this request in the watcher format, with no error | completed |
allow, deferred or not_evaluated | Has an error, or arrived any other way (below) | unknown |
deny or escalate | Any | unknown |
A result shows that the agent answered the call, not that it ran. After a
denial or escalation the result can be the agent's refusal, and an error can
be a failed run or, in formats other than this contract, a refusal, so those
calls become unknown.
If you send results in the watcher format, mark every call that did not
complete normally. Set the tool message's error when the call failed while
it ran. For a call that did not run because a person, a policy or your own
integration refused it, or because it was cancelled, keep the refusal text as
the result without error and upload the call's status as blocked or
cancelled with
POST /v1/tool-call-decisions/batch.
Watcher records a call it let through whose result has neither as completed,
so an unreported refusal is recorded as having run. If your agent framework's
own history has no error field (for example OpenAI Responses items), add
error to a failed call's result when you convert it to the watcher format.
The status upload needs a key that owns the session or holds
sessions:write:any; an ingest-only key cannot attach decisions
(permissions). It also needs the
session's Watcher ID: find it by your conversation ID with session search, as
for an append anchor. You can upload before or after
the call's result arrives; an upload after Watcher settled the call replaces its
status. An integration that cannot upload statuses has no other way to mark a
refusal, so its refused calls are recorded as completed.
Results that arrive any other way make the call unknown:
- In the raw format and in Aperture captures, the history is a copy of provider traffic. A gateway can put its own receipts there for calls it withheld or released, and OpenAI and Gemini tool results have no error field.
- An agent's own transcript file keeps refusals as ordinary results.
- A result Watcher reads back from storage, rather than one the request sends, may have come in any of these ways. That covers results before the cursor of an append. It also covers a full request whose decisions, which are recorded after the response, are recorded after a later request carrying the result was stored.
A status that is already completed, blocked or cancelled is never
changed this way, whichever order the requests arrive in. Calls the Watcher
client recorded are not changed either, because the client reports its own
outcomes. Neither are calls Aperture withheld: the notice Aperture sends in
place of a withheld call is not that call's result.
A call your raw-format gateway names in withheld_tool_use_ids moves on from
pending or unknown, because it never reached the agent: to blocked when
Watcher refused it, and to cancelled when Watcher allowed it and your gateway
withheld it only because another call in the same response was refused (see
withheld calls).
The conversation's last calls have no later request to carry their results.
To settle them, send a transcript-only request
with their results once they have run. To report a status yourself, for
example a call your integration blocked, upload it with
POST /v1/tool-call-decisions/batch.
Send the coding agent's own transcript
A client on the developer's machine can send the agent's transcript file
itself instead of structured messages. Set format to the file's format and
put the file in messages, in the shape POST /v1/ingest accepts:
{
"format": "claude-code-jsonl",
"messages": {
"format": "claude-code-jsonl",
"session_id": "<Claude Code session uuid>",
"timestamp": "2026-10-05T10:00:00Z",
"entries": [{"type": "user", "uuid": "...", "parentUuid": null, "sessionId": "...", "message": {"role": "user", "content": "..."}}]
},
"input": {"tool_name": "Bash", "tool_input": {"command": "pytest"}, "tool_use_id": "toolu_01..."},
"external_ids": {"claude_code": "<Claude Code session uuid>"}
}
Use "codex-jsonl" for a Codex rollout. For GitHub Copilot CLI, use
"copilot-events-jsonl" and send one conversation of the session's
events.jsonl at a time: set messages.agent_id to null for the main
conversation, or to a subagent's agentId for that subagent's events, which
Watcher records as its own session. Watcher reads the conversation's ID from
the log's first session.start and messages.agent_id
("<session id>:agent:<agent id>" for a subagent), so the github_copilot_cli
value in external_ids is optional: send {"github_copilot_cli": null}. A
value that differs from the log's is replaced by it.
For Claude Code, set messages.session_id to the current Claude Code conversation
ID on both full uploads and deltas. It takes precedence over sessionId values
in copied historical entries, keeping a resumed or forked transcript consistent
across uploads. If omitted, each parsed branch uses its first entry's sessionId.
This ID is distinct from the Watcher session UUID in append_after; ownership
and conversation checks still apply.
What is judged and what is stored
- The calls in
inputare judged with the file's latest conversation branch as context, including the turn the agent is still writing. - The file is stored up to its last complete tool call and result. The turn in progress is left out because the agent will finish it differently; a later upload of the finished file then continues the stored conversation instead of forking it.
- A decision is recorded only for a call the stored part holds. For any other call, record the outcome with your own decision upload, citing the returned grade IDs.
How each call is checked against the file
- Claude Code: name each call's
tool_use_id. If the file holds that call,tool_namemust be the file's, and every argument both carry must be unchanged.tool_inputmay add arguments, such as defaults the agent fills in. It may also leave out arguments the file records, as Claude Code's hook does for some calls (aMonitorcall'spersistent, say): command rules then cannot allow the call, and the monitors see the file's arguments beside yours. Where the entry also records arguments the model sent (wireToolInputs) that its message does not show unchanged, as when Claude Code moves a Bash command's leadingcdinto the entry's working directory,tool_inputis checked against those too and may match either. If the file does not hold the call yet, it is judged frominputalone. - Codex: name each call's
tool_use_id, the rollout'scall_id. Codex's permission hook does not report it; read it from the rollout (the SDK'swatcher_transcript_transport.codex.pending_call_idfinds the one pending call matching the hook's report). The rollout's record decides what the report leaves out: a shell call's working directory and any request to run outside the sandbox apply to command rules. A shell call is compared on its command, andapply_patchon its patch text. - A Codex call with no
tool_use_id, or one the rollout does not hold, is judged as a call asking to run outside the sandbox: command rules cannot allow it, and the monitors decide. If its report matches pending calls in the rollout (two calls running one command with different options, say), the monitors see each of those calls, and the gateway monitor decides: triage alone cannot allow it. If there are more such calls than the monitors can be shown, it is escalated without grading. - GitHub Copilot CLI: name each call's
tool_use_id. Copilot's hook does not report it; read it from the log'shook.startrecord for that call. Send Copilot's own tool name and arguments, as the log records them (a freeform call such asapply_patchputs its text underinput). If the log holds the call, the name and arguments must be exactly the log's; if it does not hold it yet, the call is judged frominputalone. Command rules and tool thresholds still apply to Copilot's tools under their Claude Code names (bashasBash,viewasRead), and the stored call keeps Copilot's name.
Grade only the current Claude trajectory
Clients that upload complete history independently can use
format: "claude-code-trajectory" in both the request and messages. Its
other fields match the Claude JSONL payload above. Select the active path with
watcher_transcript_transport.claude.current_trajectory_groups and flatten the
groups; retain its compaction boundaries and queued-command records. The server
converts that supplied order without rebuilding abandoned branches.
Reuse upload acknowledgments with append_after. Send every entry in the
selected continuation after that anchor. For sessions using current hashes
(scheme 3), this format permits an anchor that already has stored children.
This applies to every append using this format, including ordinary appends;
the server does not check whether a rewind occurred. Matching stored messages
are reused; a different continuation creates a branch. Older hash schemes
retain the ordinary non-leaf refusal. Ownership and anchor checks still apply.
The response confirms only that continuation, never unrelated branches in the source file. The background uploader must still deliver those branches. Recording, historical call validation, ephemeral grading and request size limits stay the same as for native V1 requests.
Limits
- With
append_after, send only the entries written after the anchor; an emptyentrieslist judges the stored conversation alone. - Inputs cannot carry their own
messages. - A Claude Code file may contain at most 500 entries that start a conversation
tree: entries with no
parentUuid, or a parent not in the request. A real session has a few (one per compaction or first-prompt rewind); more is refused with 422. - A Claude Code file may rewind the conversation (edit or restore an earlier prompt, the first one included, leaving the abandoned continuation in the file) at most 100 times. A real session rewinds a few times at most; more is refused with 422.
- Each abandoned continuation is read again together with the conversation before it, so a Claude Code file is also limited in total reading: one that would need more than 8 reads per entry it carries, plus 50,000, is refused with 422. Each content block in an entry's message counts as one more entry. A session needs one or two reads per entry, plus one more for each abandoned continuation, so even retrying the last prompt of a long session six times fits.
external_idsmust not name another agent (aclaude_codekey with a Codex rollout or a Copilot log, acodexkey with a Claude Code file, or agithub_copilot_clikey with either).- A Copilot append whose events depend on events before the anchor is refused
with 409 and the message
context_before_anchor; send the whole conversation instead. - In a Copilot log, each event's
id,timestampandparentIdmust be text or null, itsagentIdnon-empty text or null, and itsdataan object or null. Any other type is refused with 422. The SDK'swatcher_transcript_transport.copilot.read_eventsreplaces such a line, and one nested more than 128 levels deep, with a placeholder event, which Watcher records as a gap.
Send only new messages
For format: "watcher", set append_after to the last stored message you
know. Both the Watcher session_id and that message's trajectory_id are
required. These identify the session and branch, as they do for trajectory
append through the ingestion API. Append cannot be combined with
ephemeral: true; that combination returns HTTP 422 before stored content is
read.
Send only the messages after it in messages. Watcher loads the stored prefix
through that anchor, joins the new messages, and validates the selected calls
against the combined conversation before evaluation. A selected call can be in
the stored prefix, so messages: [] is valid. Batches use the same combined
conversation for every input.
Obtain the initial anchor from a successful
trajectory ingest, or obtain session_id and
latest_trajectory_id from
search_sessions, filtered by your conversation
ID. Session search needs session-read permission. For example, a generic
integration can search with external_ids={"other": ["conversation-001"]}.
After a full hook request, wait until its background recording appears in the
search results. A full hook response does not contain an anchor.
The latest trajectory can belong to another branch or another recorder. Use it
only if it ends at the prefix your delta follows. When unsure, read the
trajectory with view=TrajectoryView.EXTENDED
and check it against your local conversation. When the Watcher client also
recorded the conversation, the API returns the reconciled transcript of both
recordings, which is not the stored chain your delta continues. Continue from
the append_after anchor of your last successful append. Without one, send
full requests: a full response carries no anchor, so in such a session an
integration that has not kept an anchor keeps sending full requests. If you
cannot identify the right prefix, send a full request. Watcher never selects a leaf from external_ids
alone. Keep the chosen anchor with the local message position it represents.
Every successful append returns append_after naming the last committed
message in that continuation, alongside an ordered results list. Use that
cursor directly for the next delta; no further session search is needed.
The cursor does not select the newest leaf across other branches or recorders.
A caller with only sessions:ingest can continue from a known anchor without
session-read permission. It needs an ingestion response or a separate
authorized reader to obtain the initial anchor. A full-request fallback returns
no cursor, so acquire and verify an anchor again before resuming appends.
Replace the identifiers and messages in this request with your stored anchor and new call, then use the curl command above:
{
"format": "watcher",
"append_after": {
"session_id": "c0a7d671-8c3e-4877-925d-f7a1fe8e3508",
"trajectory_id": "<stored-trajectory-id>"
},
"messages": [
{
"role": "assistant",
"content": "",
"tool_calls": [
{"id": "call-002", "function": "Bash", "arguments": {"command": "pwd"}}
]
}
],
"input": {
"tool_name": "Bash",
"tool_input": {"command": "pwd"},
"tool_use_id": "call-002"
},
"external_ids": {"other": "conversation-001"}
}
Keep the harness keys in external_ids and any attributed user unchanged.
Append requires an exact stored-harness match. If another ingestion path stored
the session under a harness that the generic hook cannot select, use a full
request instead.
Every non-null external ID must already belong to the named session. Recorded
requests still require external_ids; use an explicit null value if no ID is
known. Append does not add IDs or change the session's owner.
For a Claude Code session, send external_ids: {"claude_code": null} if its
conversation ID is unknown; for Codex, use {"codex": null}. Omitting the
harness key identifies the request as another harness and returns HTTP 409.
Append requires session-write authority under the hook permission rules. An ingest-only key cannot use session search to discover an anchor; see session read requirements.
When admin access auditing
is enabled, cross-user prefix reads create a transcript.read event, including
requests that later fail combined-transcript validation or grading. An invalid
ephemeral append reads no prefix and creates no transcript-read event. The log
contains resource identifiers, not transcript content. Self-access and internal
service operations retain their audit exemptions.
On an append, HTTP 200 confirms that the delta and available decisions were
stored. Its messages continue the same chain as a full upload would. This is
not one atomic transaction: HTTP 503 with detail.code: "append_recording_failed"
means recording failed after the messages may already have committed. Its body
also contains top-level results, with the same ordered items as a successful
append, but no append_after cursor. Apply those decisions, including denies,
before using a generic HTTP-error failure policy. A per-call error is not an
allow. Retry the same append to finish recording, keeping the original cursor,
messages, and tool-call IDs.
Depending on the session's stored format, an exact repeat
can succeed without duplicating messages while its last message remains a leaf.
Clients must also handle HTTP 409 on an identical retry, using the full-request
fallback below. A conflicting continuation returns HTTP 409; it does not
silently choose another branch. A concurrent write can cause that conflict
after grading has run, so its grading usage may still be counted.
| Status | Meaning and recovery |
|---|---|
403 | The credential has no session-write authority. Grant sessions:ingest or sessions:write:any, or send full requests. |
404 | The session or anchor is missing or outside the caller's write scope. Retry once with a full request. |
409 | The anchor cannot accept this continuation, or the harness, user attribution, or external IDs differ. detail has code: "anchor_conflict" and a message giving the reason. Retry once with a full request. |
422 | The append request is invalid, or an older server does not accept append_after. Retry once with a full request. |
503 with detail.code: "append_recording_failed" | Apply the decisions in top-level results. No new cursor is returned. Retry the same append to finish recording when your retry policy permits it. If that retry returns 404, 409, or 422, use the full-request fallback. |
For that one fallback, omit append_after and send the entire conversation in
messages. Keep the selected calls and their IDs. If the full request fails,
surface the error; do not repeat this fallback indefinitely. It still has the
normal request-body limit, so a full request that exceeds that limit returns
HTTP 413.
Both Python clients expose pre_tool_use_hook(..., messages=delta, append_after={"session_id": session_id, "trajectory_id": trajectory_id}).
An append returns an object with append_after and results, even for one
input. For an async client with a verified anchor, send the next messages
and retain the returned cursor:
response = await client.pre_tool_use_hook(
messages=new_messages,
input=pending_call,
external_ids={"other": "conversation-001"},
append_after=anchor,
)
anchor = response.append_after.to_dict()
Apply the decisions in response.results as described below. The next call
uses append_after=anchor and only messages after that cursor. For the sync
client, omit await. Both clients raise WatcherAPIError with status_code
on HTTP failures. For error.code == "append_recording_failed", read the
completed outcomes from error.body["results"] and apply them before retrying
recording. Older servers may omit results; handle missing results with your
normal failure policy. Combining append_after with ephemeral=True raises
ValueError locally, before sending a request. The SDK does not automatically retry append requests or perform
the full-transcript fallback; the caller owns retry policy and the full prefix.
The field is optional: clients can keep sending full requests to new servers,
and use the fallback with older servers. Nothing is deprecated.
The body-size limit applies to the submitted delta. Reconstruction still loads the whole prefix into server memory. Graders apply the same context policy and model limits as for a full request. Append reduces upload size; it does not promise lower grading cost or an unlimited model context.
For full and append requests alike, Watcher fits each monitor's prompt to that monitor's model. Tool outputs and agent reasoning are not sent to the blocking monitors. If the remaining transcript is still too long, Watcher removes its middle, keeps the start and the turns leading up to the call, and marks the cut. The call is still graded; a long transcript is not rejected below the request-body limit.
Reusing a completed evaluation
By default, a hook request can reuse a completed evaluation. This applies for
the same organization, session and tool-call ID. The selected tool name and
arguments must match the stored call exactly. A call reported under another
tool name matches when both map to the same call under the tool names policy
uses and mapping lost nothing that decides how it runs: a Codex hook's Bash
call matches the exec_command call a gateway recorded, unless that call set a
working directory or passed its command as an argument list. Reuse requires
known conversation IDs. It requires permission to read the resolved session. It
requires authority to ingest it. The read check uses
findings access, including for
unattributed sessions. Ephemeral requests evaluate normally. Calls without a reusable
record evaluate normally. Write-only API keys evaluate normally. A grading
failure is not a reusable evaluation. An unjudged record is not a reusable
evaluation.
Watcher applies the request's current enforcement mode to the stored judgment. For example, a judgment first recorded in observe mode can later produce an allow for an enforcing caller. It can produce a deny or escalation. Reuse creates no new grades. It creates no new evaluation record. The submitted transcript can still be ingested.
Send force_regrade: true to bypass reuse and evaluate again. The new
evaluation can replace the stored decision. This applies even when the request
observes rather than enforces. Rules still run. Paused mode still only ingests.
Policy changes do not automatically invalidate a stored judgment. Use this
option when a new evaluation is wanted.
The Watcher client sends its calls through this endpoint too. When a gateway hook and the client watch the same Claude Code conversation, the one whose judgment is recorded first answers the other's later request for the same call, with the original grades. Requests that arrive together, or before the first judgment is recorded, each grade the call: Watcher does not coordinate evaluations still in flight. This is common when a gateway and the client see a call at almost the same moment.
The Python SDK's pre_tool_use_hook(..., force_regrade=True) sends this option.
pre_tool_use(..., force_regrade=True) also skips the SDK's local decision
path. For ordinary local decisions, selected tool names and arguments are
checked before returning a judgment; mismatches raise ValueError. Ambiguous
copies of top-level and nested transcripts are sent to the server for
validation.
Request fields
| Field | Contract |
|---|---|
format | Required. watcher for structured messages; claude-code-jsonl, codex-jsonl or copilot-events-jsonl for the agent's transcript file; claude-code-trajectory for its selected current Claude conversation. |
messages | The shared structured conversation, or only the new messages when append_after is set. Native formats supply the agent's transcript file, or the selected Claude conversation with claude-code-trajectory; see Send the coding agent's own transcript. Required when input is null, empty, omitted, or contains more than one item. A scalar or one-item list may instead supply input.messages; if both locations are non-null, their transcripts must agree. Multiple inputs must omit nested messages or set it to null or []. |
append_after | Optional { "session_id": "<UUID>", "trajectory_id": "<stored message ID>" }; both identifiers are required when supplied. Restores that exact prefix before evaluating messages as a delta. Requires session-write authority and rejects ephemeral: true. Success returns an envelope with the next cursor and an ordered results list. See Send only new messages for anchor selection and recovery. |
input | One monitoring input, a list of inputs for the shared conversation, or null. Null, an empty list, or omission requests transcript ingestion only. Full requests return []; appends return the next cursor with results: []. |
input.tool_name, input.tool_input | Each input object requires tool_name; tool_input supplies its arguments. Omission is allowed for a matching call with empty {} arguments. |
input.tool_use_id | A stable ID matching the selected tool's name and arguments in the shared messages, including the stored prefix for append requests. Required for every non-ephemeral named input, including paused requests. Batch IDs must be distinct; every transcript occurrence of a selected ID must agree. Ephemeral inputs may omit a corresponding transcript call; for an agent's own transcript file, see how each call is checked. |
external_ids | Conversation IDs keyed by claude_code, codex, opencode, github_copilot_cli, aperture, or other. Required unless ephemeral: true. Include the harness key when known: a claude_code, codex, opencode or github_copilot_cli key records the session as that agent, and a session with none of them is stored as other. If no ID exists, send an explicit null value such as {"claude_code": null}. Every append must preserve the exact stored harness. Session responses may report a recognized SDK agent from its retained adapter ID; that reporting does not change the stored harness an append must preserve. The session stores an aperture value under the tailscale-aperture key, the same key the Aperture webhook uses for the session IDs it keeps. |
user | Optional developer email for callers authorized to write sessions for other users. Otherwise ignored. |
force_regrade | false by default. Set to true to evaluate again instead of reusing a completed judgment. Does not enable grading in paused mode. |
mode | full by default. triage_only skips the gateway monitor after triage; a call triage does not clear returns an escalation judgment. |
ephemeral | false by default. When true, saves no transcript, tool-call decision, or tool-call grades. Usage data is retained. Enforce and observe still return a completed judgment. Cannot be combined with append_after; that combination returns HTTP 422 before reading stored messages. |
record_transcript | true by default. When false, saves no transcript and no tool-call decision, but keeps the tool-call grades and returns their IDs. The grades are filed under the conversation external_ids names when that conversation is already stored. Accepted only when messages is a coding agent's own transcript file, not with format: "watcher". Requires at least one non-null external_ids value. Cannot be combined with ephemeral: true or append_after; any of these combinations returns HTTP 422. |
settings_overrides | Optional settings overlay as a YAML string or JSON object. Watcher merges it into the administrator's settings before evaluation. Set enforcement.mode here to change mode. Overrides that change an admin-locked value, and overrides exceeding 65,536 serialized characters, are rejected with HTTP 422. |
skip_rules, policy_version | For integrations that already evaluate deterministic checks using Watcher's shared SDK evaluator. That evaluator uses tool names as sent, so skip_rules is ignored for a call the hook translates: the hook runs the checks again under the Claude Code name, and the thresholds it grades against are always the translated ones. Other integrations should leave these unset. |
Pre-rendered input.transcript and caller-supplied input.triage_assessment
are rejected. Scalar inputs with an explicit empty tool_name are accepted for
transcript-only ingestion and return one unjudged response object, inside
results for an append. Use null or an empty list for new integrations.
Supply stable conversation IDs whenever possible. Without them, Watcher reconciles by transcript prefix, so independent conversations with identical transcripts can initially share a session. Keep a call's ID stable when retrying so its recorded decision converges on the same call.
Handle the response
A successful request returns HTTP 200. Without append_after, a scalar input
returns one response; a list returns one output per input in the same order.
Null or omitted input returns an empty list.
An append always returns an envelope with append_after and results.
results has one output per input in input order, including a one-element list
for scalar input. With no selected calls, the response has this shape:
{
"append_after": {
"session_id": "c0a7d671-8c3e-4877-925d-f7a1fe8e3508",
"trajectory_id": "<last-committed-trajectory-id>"
},
"results": []
}
Keep the returned cursor for the next append. Every result includes
tool_use_id, echoing that input's ID or null when no ID was supplied. Apply
each available decision field:
decision | Caller behavior |
|---|---|
allow | The call may proceed. |
deny | Do not execute the call. |
escalate | Obtain human approval before proceeding, or apply your integration's policy for unavailable approval. A raw-format gateway that sets withholds_refused_calls withholds the call unless a person approves it; see withheld calls. |
deferred | Watcher withholds enforcement. Continue through your integration's own permission flow. |
In enforce or observe mode, a monitor refusal in a batch produces an error output in that input's position, while the other inputs continue. For example:
{"tool_use_id": "call-002", "status_code": 503, "detail": "Monitor temporarily unavailable"}
An error output has no decision. Handle its status as you would a scalar HTTP
error, using your integration's failure policy. Successful judgments are still
recorded; retry only failed inputs when your retry policy permits it. After an
append returns HTTP 200, use its returned cursor with messages: [] to retry
those calls against the stored conversation. Input validation and settings
errors reject the whole request before evaluation.
In enforce and observe modes, judged_decision reports the completed judgment.
Observe always returns decision: "deferred", so the judgment is advisory.
Outputs for paused calls and legacy unnamed inputs have a null judgment and
decision_source: "bypass". Transcript-only requests with no inputs return
[], or an append envelope with results: []. verdict explains the result;
triage and gateway contain stage results when those stages ran.
enforcement_mode reports the effective mode.
cost_usd is the estimated USD cost for that input's triage and gateway
grading, including retries with reported usage. Batch outputs have separate
totals. Skipped stages add no cost; a skipped or reused evaluation costs 0.
The value is null if usage or pricing is missing, or a stage is still running
when the response is returned. Provider retries whose usage is not reported
cannot be included. Estimates use the prices set on the server. Error outputs
do not carry a cost. For typical costs and how to measure yours, see
Monitoring cost.
Enforce and observe responses can take seconds to minutes. Watcher waits up to
about 10 seconds for triage before starting gateway review, and up to about 300
seconds for gateway review before applying policy_monitors.on_grading_failure.
Set your caller's timeout above about 310 seconds so it receives that decision,
and decide what it does if Watcher cannot be reached. For full
requests, HTTP 200 confirms the returned result; transcript and decision
storage run afterward. That background recording can fail without affecting
the response, leaving missing or incomplete records in Analyzer. An append
waits for its delta and available decisions to be stored before HTTP 200.
Slack alert delivery runs after the response and does not delay the returned anchor.
Its recording errors return HTTP 503 as described in
Send only new messages. A monitor task that already
timed out can still finish and retain its grade and usage after either kind
of response.
Validation errors
Request validation failures return HTTP 422 and reject the whole request before
ingestion or grading. The detail list contains error locations (loc), messages
(msg) and categories (type). An unsupported stored session format uses
loc: ["body", "append_after"] in that list. Body validation errors can include the selected format,
watcher or raw, immediately after body in loc.
For example, a request with format: "watcher" and mode: "invalid" returns
an error like this:
{
"detail": [
{
"loc": ["body", "watcher", "mode"],
"msg": "Input should be 'full' or 'triage_only'",
"type": "literal_error"
}
]
}
Do not require the format segment on every error. A missing or unknown format
can produce loc: ["body"]. Errors raised while converting a raw exchange also
use ["body"]. A locked settings override uses ["body", "settings_overrides"]:
{
"detail": [
{
"loc": ["body", "settings_overrides"],
"msg": "settings_overrides changes admin-locked settings: enforcement.mode",
"type": "value_error"
}
]
}
Handle validation failures by HTTP status and error type, rather than exact
message text or a fixed location length. If your client matches field locations,
accept or remove the optional watcher or raw segment immediately after
body before applying those matches. Keep the rest of the location unchanged,
including array indices. Accept locations without that segment too.
The Python SDK raises WatcherValidationError
for HTTP 422. Code that only handles that exception needs no change for these
location segments. Custom code that inspects the exception's body must handle
them as described above.
Raw provider request and response
A synchronous hook, such as a LiteLLM proxy callback, can send the provider
request and response as they are with format: "raw". Watcher converts them
and selects the new tool calls. The SDK's pre_tool_use_hook accepts
request_body and response_body for this, and the SDK's LiteLLM example
uses it.
Supported formats are OpenAI Chat Completions, OpenAI Responses, Anthropic
Messages, Gemini generateContent and Bedrock Converse. Both bodies must use
the same API format. Assemble streamed content into its non-streaming shape
before sending it; each proposed call must have complete arguments.
A gateway can evaluate a stream one completed call at a time. For each later
call, append the previously released response prefix to a copy of the request's
assistant history. Put only the new suffix in response_body. Earlier calls
then remain context without being selected again. Keep their original IDs and
arguments, preserve the conversation's identity fields, and leave the request
sent to the provider unchanged. The gateway must hold each pending call and
later content until it receives a matching permitted decision.
Use the same conversation identity for every increment. Legacy callers can
use stable external_ids or recognized native identity instead. Partial
proposals do not reliably match by shared text alone. Incremental evaluations and the final delivered history can create
separate trajectory branches in
one session; a recorded proposal is not proof that it reached the client.
The LiteLLM callback
validates the selected conversation ID before it calls the provider, as
described below.
{
"format": "raw",
"request_body": {"model": "gpt-5.4-mini", "messages": [{"role": "user", "content": "Tidy the notes file."}], "tools": ["..."]},
"response_body": {"id": "chatcmpl-1", "model": "gpt-5.4-mini", "choices": ["..."]},
"url": "/v1/chat/completions",
"user_agent": "my-agent/1.0",
"conversation": {"namespace": "other", "id": "my-integration:conversation-123"},
"source": {"type": "gateway", "name": "my-integration"}
}
| Field | Meaning |
|---|---|
request_body, response_body | Required. They replace messages and input. |
url | The client-facing endpoint path or URL. It resolves formats with similar bodies and is recorded without query or credentials. |
user_agent | The client's User-Agent. With the request body, it identifies supported coding agents. |
provider | Your route or model alias, recorded with the messages. |
conversation | Optional {namespace, id} naming the sole session-matching identity. Namespaces are other, claude_code, codex and opencode. When supplied, native IDs and external_ids are not added as aliases, and shared transcript text cannot select another session. |
parent_conversation | Optional {namespace, id} for the immediate parent. Requires a distinct conversation in the same namespace. Watcher links after recording the transcript and decisions, under normal ingestion permissions. A known parent ID can create a session without messages; later parent captures fill it. Failed links preserve the capture. Later captures retry linking only when they include the parent identity. |
spawning_tool_use_id | Optional nonempty native ID of the parent call that spawned this child. Requires parent_conversation. Watcher stores the ID and searches the parent's recorded messages for it. If the message has not arrived, later child captures with parent identity retry the message link. |
source | Optional delivery source: {type, name?}. Type is gateway, sdk or other; raw captures reject client with HTTP 422. Session and decision recording use the same delivery type. The optional integration name is reporting metadata: 1–64 lowercase letters, digits, hyphens or underscores, starting with a letter or digit. Never use a user, hostname or credential. Neither field selects a session or grants permissions. |
external_ids | Legacy conversation aliases. When conversation is absent, they combine with recognized native IDs; native IDs win for the same key. With conversation, they add no matching aliases. Native Copilot captures use {"github_copilot_cli": null} to select Copilot's tool rules without another matching ID. |
response_index | Zero-based array position of the Chat choice or Gemini candidate to evaluate, regardless of its provider index field. Required when there are multiple alternatives. |
user, mode, ephemeral, force_regrade, skip_rules, policy_version, settings_overrides | As in request fields. |
withheld_tool_use_ids | Optional list of the tool-use IDs your gateway withheld from the client in favor of this response. Only the raw format accepts it, and a non-empty list requires withholds_refused_calls: true. See withheld calls. |
withholds_refused_calls | Optional, default false. Set it to true only if your gateway withholds from the client every call Watcher denies or escalates in enforce mode. Only the raw format accepts it. See withheld calls. |
parent_conversation looks up the parent using the child's coding-agent platform.
Use it only when both sessions come from the same harness. For custom integrations
linking different harnesses, omit this field and record both sessions first. Then
call PUT /v1/sessions/{child_session_id}/agent-relationship with
{"parent_session_id": "<parent-session-uuid>"}. Use Watcher's session UUIDs for
both IDs; see linking child sessions.
A canonical conversation ID must be nonblank and contain no control
characters. Custom IDs in other allow up to 2,048 characters; OpenCode IDs
allow 1,024. Codex IDs and Claude root IDs must be UUIDs. Claude children use
subagent:["<root-uuid>","<agent-id>"], with an agent ID of at most 1,024
characters. Invalid canonical identity returns HTTP 422. Keep the same namespace
and ID across turns. A harness recognized from the client user agent and request
body takes precedence. Otherwise, a native namespace selects the harness,
including its tool translations and policy thresholds.
Without conversation, the released raw API keeps its native-ID and caller-alias
matching behavior, including shared-history reconciliation. Without source,
Watcher uses its existing delivery classification. Raw captures remain distinct
from Watcher client uploads for transcript reconciliation and execution tracking,
regardless of the reported integration name or HTTP User-Agent. See
capture and retained-message sources.
LiteLLM identity selection. The callback selects and validates the canonical identity before provider generation:
- An explicit
x-watcher-session-idwins. It becomes anotherID with alitellm:prefix unless already present. No native matching aliases are added. - Otherwise, Claude Code uses its root UUID from metadata or
x-claude-code-session-id, plusx-claude-code-agent-idfor children. Codex usesclient_metadata.thread_id. OpenCode usesx-opencode-session-idorx-session-id; both must agree if supplied. - Missing or invalid selected identity returns HTTP 400 before generation. An invalid explicit override never falls back to native identity.
Custom header IDs allow up to 1,024 characters, including any litellm:
prefix. They cannot be blank or contain control characters. A valid override
ignores native identity fields. Without an override, relevant native IDs must
be complete, valid and consistent; other agents' identity headers are ignored.
For native Codex requests, client_metadata["x-codex-parent-thread-id"] supplies
the immediate parent. Claude Code's x-claude-code-agent-id identifies a child
of the root session; x-claude-code-parent-agent-id identifies its parent agent
when nested. OpenCode supplies x-opencode-parent-session-id or
x-parent-session-id; both must agree when present.
Custom integrations can send x-watcher-parent-session-id
alongside x-watcher-session-id; both follow the same validation, prefix and
account-scoping rules. The custom parent header requires a custom child ID.
With a custom child ID, omitting the custom parent header creates no new link,
even when native parent metadata exists. Existing links are preserved. Invalid
selected parent IDs and self-parentage return HTTP 400 before generation.
The callback sends canonical identities and
source: {"type": "gateway", "name": "litellm"} to Watcher, not the original
identity or authentication headers.
Custom integrations must keep IDs stable and supply distinct IDs for children they want stored separately. Reusing an ID groups requests within the existing organization, ownership and agent-platform scope. IDs and source metadata grant no access. See subagent coverage.
The response is a list with one output per selected new client tool call,
in response order, shaped like the outputs in
handle the response. Each output's tool_use_id is the
call's ID in your response_body. Gemini calls get generated IDs and are
matched by order within the selected candidate.
Some client calls in the original response have no output. For example,
Anthropic calls before the final fallback block are omitted. Calls in
unselected choices or candidates are also omitted. An empty list means no
client calls were selected, not that the original response contains none.
Provider-run calls and calls from earlier turns are not evaluated and get no
output. A call from an earlier turn that has its result in the request, and
that has not been recorded in this conversation, is recorded as an ungraded
not_evaluated record with history_only as its decision context: for
example a turn your gateway did not send to Watcher. For a supported coding
agent, a call another conversation already recorded with the same ID, tool and
arguments is treated as a copy and not recorded again, as described for
Aperture captures. Gemini calls are excluded, and nothing
is recorded this way in paused mode. Requests in the watcher format record only the calls in
input.
Before releasing executable content:
- Identify every client tool call in the response you will deliver. Deliver only the selected choice or candidate when the provider returns alternatives.
- Match each call to exactly one output using its provider call ID. For Gemini, match by call order and require equal call and output counts.
- Withhold the response if a call has no output, IDs are duplicated, or an output cannot be matched to a call. Otherwise, apply each decision. An error output is not permission to run the call.
One response may contain any number of tool calls; the 32-input limit applies
only to the watcher format. Supported coding agents' own helper requests
without selected client calls return [] and are not recorded: Claude Code
background requests such as its permission classifier, Codex thread titles,
approval reviews and memory extraction, and Antigravity title requests. The
same delivery checks apply to these responses. Qwen Code's memory-recall
request is the exception: its response normally carries a respond_in_schema
call, which Qwen Code reads as its memory selection. Watcher evaluates that
call under your policy and returns a decision, so a gateway can deliver the
selection, without recording a session, decision or grade for it. Grading usage
is still counted; a tool_thresholds or command rule for respond_in_schema
avoids model grading. A recall answer returned as plain text has no call and
returns [].
A pair Watcher cannot convert returns HTTP 422 with one of these messages:
provider_error for a provider error body, unsupported_api when no supported
format matches, and malformed_exchange for invalid content or an unselected
alternative. Other invalid fields and locked settings overrides return the usual
validation errors.
Withheld calls
A raw-format gateway that withholds from the client every call Watcher denies
or escalates in enforce mode can say so with withholds_refused_calls: true.
Watcher then records each such call's execution status as blocked when it
decides the call, with no human answer. A host outcome or human answer already
recorded for the call is kept. Without the flag the status starts as pending,
as it does in observe mode and for requests in the watcher format or an
agent's own transcript file, until a later request settles it (see
Execution status).
Leave the flag unset if a refused call might still reach the client. For example, you might send an exchange after the client already received it, or pass escalations to the agent's own approval prompt. Servers that predate the flag reject it with HTTP 422.
If your gateway asks a person about an escalated call and then releases it,
upload that answer with
POST /v1/tool-call-decisions/batch.
It replaces the blocked status and records the person's decision.
A gateway can deliver a different response in place of a proposal it withheld,
such as a notice or an alternative the model proposed after the refusal. To
record what it withheld, send withheld_tool_use_ids on the raw-format request
that records the delivered response. Other formats reject the field with HTTP
422.
- List every call you withheld in favor of that response: each refused call, and the calls you withheld with it from the same proposal. Never list a call the client received.
- Set
withholds_refused_calls: trueon the same request, and on every request that evaluated the withheld calls. A non-emptywithheld_tool_use_idswithout it returns HTTP 422. - Omit the field when you withheld nothing. It is optional, and not stored
for
ephemeralrequests. - Send at most 4,096 IDs. Duplicates are removed, and sending the request again merges its IDs with those already stored.
Watcher stores the IDs with the response's last message, the end of
response_body. An empty assistant message at the end is skipped in favor of
the message before it. This happens when you record calls already released to
the client as history, with an empty response after them. Watcher resolves the
IDs each time a trajectory is read,
so you can send the field before Watcher records the refused proposals.
A trajectory read that includes that message lists matching decisions in
gateway_withheld_decisions. It includes each named call that Watcher
evaluated in the same session and that the trajectory does not already show.
Other IDs are ignored. Entries follow the order the calls were proposed: by the
proposing message's position in the conversation, then by the call's position
in that message. Each entry carries gateway_delivery, which no other decision
has:
| Field | Meaning |
|---|---|
action | blocked when Watcher denied or escalated the call. cancelled when Watcher did not refuse it but you withheld it with a refused call. |
delivered_message_ref | The message_ref of the message delivered instead, as the trajectory shows it. A reconciled transcript that shows another copy of the delivered message names that copy: the Watcher client's copy of a message making the same tool call, or, for a message of text alone, the copy of that answer in the same turn. When the turn is unclear, the ref stays the stored message, which that transcript may not show. |
proposal_message_ref | The message_ref of the message that proposed the call. |
Once Watcher has stored the IDs, each named call that Watcher evaluated in the
same session also gets an execution status if it is still pending or
unknown, matching its action:
blocked for a call Watcher refused, and cancelled for a call Watcher allowed,
which never reached the agent either. This happens whichever Watcher records
first, the named call or the response that names it. A completed, blocked
or cancelled status, such as one you uploaded with a person's answer, is
kept, and the decision itself does not change.
Servers that predate the field reject it with HTTP 422.
Configure Aperture
For support levels by agent and provider, see Supported agents.
Prerequisite: your coding agent's requests already appear in Aperture's logs. Use Aperture's client setup guides to establish that connection before configuring this webhook.
For Codex, define a custom model provider in Codex's config.toml, as
Aperture's Codex guide
does, and set supports_websockets = false in it:
model_provider = "aperture"
[model_providers.aperture]
name = "Aperture"
base_url = "http://<aperture-hostname>/v1"
wire_api = "responses"
supports_websockets = false
Watcher supports Codex through Aperture over HTTP; WebSocket requests are not a
supported route. A custom provider already uses HTTP when supports_websockets
is unset; setting it makes that explicit. codex doctor reports the active
provider's supports websockets value.
Codex's built-in OpenAI provider, which Codex uses when you point the
openai_base_url key in config.toml at Aperture instead, first tries a
WebSocket connection to /v1/responses. When Aperture refuses it, for example
with HTTP 404, each new Codex session makes several failed attempts, warns
Falling back from WebSockets to HTTPS transport, and then sends its requests
over HTTP. Watcher records those HTTP requests as usual; the cost is a delay of
several seconds before each session's first request.
The observation endpoint accepts Aperture's entire_request event in these formats:
| Format | Admitted coding-agent identity |
|---|---|
| Anthropic Messages, including the hosted variants detailed below | Claude Code, OpenCode or pi, using the markers below. |
| OpenAI Responses, including OpenRouter | Codex or OpenCode, using the markers below. |
| OpenAI Chat Completions, including OpenRouter | Codex, OpenCode, Qwen Code or Mistral Vibe, using the markers below. Ordinary OpenAI SDK application traffic is excluded. |
Gemini generateContent, including Vertex | Antigravity CLI or OpenCode, using the markers below. Gemini CLI captures are recorded without support, as described below. |
| Bedrock Converse and ConverseStream | OpenCode's user-agent marker below. Ordinary AWS SDK traffic is excluded. |
Watcher records each admitted session as the agent whose markers matched, so the
Analyzer shows and filters sessions by that agent. A capture that matches no
supported agent is skipped with excluded_conversation, never recorded as other.
An Anthropic-format capture qualifies when any one of these Claude harness cues matches, unless an OpenCode user agent or pi's markers (both described below) identify another agent:
| Cue | Accepted value |
|---|---|
| 5a. User agent | The webhook envelope's metadata.user_agent starts with claude-cli/. |
| 5b. CLI system text | Contains You are Claude Code, Anthropic's official CLI for Claude. |
| 5c. Agent SDK system text | Contains You are a Claude agent, built on Anthropic's Claude Agent SDK. or You are Claude Code, Anthropic's official CLI for Claude, running within the Claude Agent SDK. |
| 5z. Native body metadata | request_body.metadata.user_id is a JSON string with string-valued device_id and account_uuid fields, and a canonical lowercase, hyphenated UUID session_id. |
request_body.metadata belongs to the original Claude API request. It is
separate from the webhook envelope's metadata, which Aperture adds. Watcher
reads Claude's native conversation ID from the JSON string in
request_body.metadata.user_id, rather than from an HTTP header or Aperture's
grouping ID.
These checks identify the captured harness; they do not authenticate its origin.
Webhook authentication and developer attribution follow the requirements
above. A matching system message needs no
user-agent label, and a matching user agent needs no particular system prompt.
A session UUID alone or Aperture's own metadata.session_id is insufficient.
The native request's session header is not part of the observed or documented
webhook envelope, and this adapter does not use it.
Claude Code subagent requests, including its built-in Explore agent, are part of the conversation rather than background requests. They carry the parent conversation's native session ID, are recorded in its session and have their tool calls graded.
A Codex capture qualifies when any one of these Codex cues matches:
| Cue | Accepted value |
|---|---|
| User agent | metadata.user_agent begins with codex (case-insensitive), followed by _, -, /, whitespace or the end of the value. This includes codex_cli_rs, codex_vscode, codex-tui, codex_exec and Codex Desktop/0.155.0-alpha.9; no particular version syntax is required. |
| Identity text | A system or developer message, or Responses instructions, starts with You are Codex, . |
| Codex body metadata | request_body.client_metadata has a non-empty string under x-codex-installation-id, x-codex-turn-metadata or x-codex-window-id. Codex writes these keys itself, so they also identify Codex's request body when it arrives under a different user agent, such as a generic Bun/ runtime value. |
User-message text, model names, provider names and generic client_metadata
keys such as thread_id, session_id or turn_id do not satisfy this gate.
Modern Codex uses Responses; Chat Completions is accepted only when the
captured request carries one of these cues. An OpenCode user agent keeps
OpenCode's attribution in both formats even when the body also carries Codex
metadata; a Qwen Code or Mistral Vibe user agent does so for Chat Completions
only, because those markers do not admit Responses captures.
Codex's own helper requests, captured as Responses turns, are skipped as
excluded_conversation even when a Codex cue matches. Watcher reads the JSON
string at request_body.client_metadata["x-codex-turn-metadata"]. Most helpers
run under their own thread ID, so recording one would add a separate session
with no agent work. Watcher skips requests whose thread_source is one of
these values:
thread_title: naming the conversation.system: the terminal UI's temporary structured threads, such as session recaps.guardian_review: the auto-review approval reviewer. Codex reuses a reviewer thread across approvals, and Codex Desktop can start a new reviewer thread with a copy of the previous reviewer's history, so a review request can carry tool calls from an earlier review.guardian_classifier: the auto-review approval classifier.thread_description: Codex Desktop writing a conversation's description. It forks the conversation for this request, so the request carries a copy of the conversation's history, including its tool calls. Those calls are the conversation's, not the description's.
Watcher also skips requests whose request_kind is memory. When Codex's
memories feature is on, a starting conversation first sends one such request,
asking the model to extract memories from an earlier conversation's
transcript. It carries the new conversation's thread ID, so recording it would
add the earlier conversation's content to the new conversation's session.
A helper request that contains a tool call of its own is recorded: a client
tool call in the response, or one in the history after the request's last user
message, which is the helper's instruction or the review request. Calls earlier
in the history belong to another conversation or to an earlier request on the
same thread. When a helper thread compacts, the summarization instruction Codex
adds does not count as that last user message, so the helper's calls before it
still count. Other thread_source values are recorded, including
memory_consolidation turns, because Codex's memory consolidation agent runs
tools. A missing or unreadable value is also recorded.
When a Codex conversation runs long, Codex compacts it: it sends one summarization request, then continues with a shortened history and a summary. With a custom model provider the summary is readable text. With its built-in OpenAI provider (including when pointed at Aperture) or Azure OpenAI, the summary is an encrypted item.
Watcher keeps monitoring a Codex conversation through either kind of compaction. It skips Codex's summarization request itself, replaces an encrypted summary with a placeholder (its content is never stored or shown), and inserts a compaction notice so graders know the agent's earlier context was compacted at that point. Later tool calls are graded as usual. When Watcher already holds earlier turns of the same Codex thread, the turns after the compaction continue that trajectory, so the earlier turns stay visible. In the Analyzer, the compaction appears as a "Context compacted" marker.
OpenCode captures require a metadata.user_agent beginning with the application
name opencode, in lowercase, followed by /, whitespace or the end of the value. A version
is optional and is not validated; both opencode and opencode/1.18.30 qualify.
This engine marker also covers applications built on OpenCode. Custom system
instructions are accepted. Title-generation and context-summary requests are
retained even when they contain no client tool calls. OpenCode auxiliary
requests are not separately classified or excluded. OpenCode does not inherit
Claude Code or Codex session IDs. OpenCode 1.18.30 sends its session ID in the
X-Session-Id header, which Aperture reports as an xsid_ session ID; Watcher
uses that as the conversation ID, as described in
Aperture session IDs. The title-generation request
carries the same ID and is recorded as a separate trajectory in the
conversation's session. The Analyzer opens a session at its newest trajectory
by capture time, so a title request answered after the conversation's last
request is shown first until the conversation continues.
When an OpenCode conversation runs long, or on request, OpenCode compacts it: its compaction agent sends one summarization request, then every later request starts with OpenCode's question "What did we do so far?", the summary as the model's reply, and the recent turns OpenCode kept. The summarization request is recorded as its own trajectory in the conversation's session. Watcher inserts a compaction notice after the summary so graders know the agent's earlier context was compacted at that point, and later tool calls are graded as usual. When Watcher already holds earlier turns under the same OpenCode session ID and the same system prompt, the turns after the compaction continue that trajectory, so the earlier turns and their tool calls stay visible; the turns OpenCode kept appear again after the summary, as the agent saw them. If the system prompt changed at the compaction (for example, after switching to a model that uses a different OpenCode prompt), the compacted history starts a new trajectory in the same session instead. If the summary reaches Watcher merged into a kept turn that calls a tool, Watcher does not recognize the compaction: it inserts no notice and stores the compacted history as a new trajectory. When Watcher recognizes the compaction, the Analyzer shows a "Context compacted" marker. A conversation whose own first message is exactly "What did we do so far?" gets the same marker after its first reply.
A capture without that ID is placed by its transcript, and its auxiliary
requests can create additional sessions. OpenCode's Gemini generateContent
and streamGenerateContent captures then also use the Gemini history-matching
fallback described below. It covers histories in which OpenCode replays earlier
reasoning as explicit thought parts. OpenCode's other formats use ordinary
transcript matching only. Without the ID, do not assume one Watcher session
covers the complete native conversation.
Anthropic Messages captures from pi, the coding agent, are recorded as pi, whether pi signs in with a Claude subscription or uses an API key. When signed in with a Claude subscription, pi itself makes its requests look like Claude Code's: it sends Claude Code's user agent and identity line. Watcher therefore recognizes pi by these markers, which take precedence over the Claude harness cues above:
| Marker | Accepted value |
|---|---|
| pi system prompt | A text block of request_body.system starts with You are an expert coding assistant operating inside pi, a coding agent harness., the opening of pi's default system prompt, or with You are a context summarization assistant. Your task is to read a conversation between a user and an AI assistant, then produce a structured summary following the exact format specified., the opening of pi's compaction summary request. |
| pi placeholder tool | request_body.tools declares a tool named __pi_deferred_placeholder__ with defer_loading: true, and one of the Claude harness cues above also matches. pi declares this tool only on models that accept mid-conversation tool changes, such as Claude Opus 4.8 and later. |
An OpenCode user agent still keeps OpenCode's attribution. If you replace pi's default system prompt, only the placeholder tool identifies pi. Without it:
- a subscription request is recorded as Claude Code, under the Claude Code
session ID in
request_body.metadata.user_idif a pi extension filled it in; - an API-key request is not recorded.
pi's requests carry no other marker that survives a custom system prompt: pi's tools and their descriptions change with its version, settings and extensions.
pi's own user agent, which begins pi (, is not a marker: other applications
built on the same request library that pi uses send it too. pi extensions
(add-ons installed into pi) can rewrite its subscription requests. One that
moves pi's system prompt out of request_body.system and removes the
placeholder tool makes pi's requests indistinguishable from Claude Code's.
pi's OpenAI Responses, Chat Completions, Gemini and Bedrock Converse captures
are not admitted.
pi sends no conversation ID in Anthropic format. Watcher never reads one from
request_body.metadata.user_id in a pi capture: pi does not set that field,
but some pi extensions fill it with Claude Code-style values, some of them new
on every request. If Aperture reports a pi session ID (pisn_), Watcher uses
it, as described in Aperture session IDs. For
subscription captures Aperture reports a content fingerprint instead, so
Watcher places them by their transcript: a resumed pi session continues the
same Watcher session. After pi compacts a conversation, its next request
starts with the summary instead of the earlier turns, so the rest of the
conversation is recorded as a new session, and the compaction summary request
is recorded as a session of its own. Claude Code's background-request
exclusions do not apply to pi, and pi's own auxiliary requests are not
separately classified or excluded.
The Qwen Code and Mistral Vibe user-agent markers admit Chat Completions captures
when the value starts with QwenCode or Mistral-Vibe, with that exact
capitalization, followed by a slash, whitespace or the end of the value. Version
text is optional and is not validated.
These markers alone do not admit Responses, Gemini, Anthropic or Bedrock Converse
captures; independent recognized harness cues still apply to those formats.
Sessions are recorded as Qwen Code or Mistral Vibe. Their captures carry no
native conversation ID, so Watcher places them by their transcript. A
successful retry without a native ID can be graded again.
In Aperture captures, Qwen Code's memory-recall request is skipped as
excluded_conversation (raw hooks return a decision instead; see above). Once a
memory has been saved, Qwen Code sends it before each prompt to choose which
memories to load. Watcher recognizes it by its exact shape: the recall system
prompt verbatim, one user message, and only the respond_in_schema function
Qwen Code uses to return the selection, which it reads rather than runs. A
recall response that proposes any other tool call is recorded and graded.
Mistral Vibe's auxiliary requests, and Qwen Code's other ones, are not
separately classified or excluded.
Qwen Code's managed-memory helper is recorded as a separate session. That helper can contain copies of earlier messages and tool results. Its separate session does not mean the user's resumed conversation lost its grade links.
Both clients rebuild parts of their system message when a conversation is
resumed. When matching the system message, Watcher ignores the lines of the git
snapshot each client generates (branch, changed files and recent commits). For
Qwen Code, it also ignores the saved memories in the generated auto-memory
section (the memory index and the saving instructions around it), but not the
memory directories that section names. For Mistral Vibe, it also ignores the
random suffix of the generated scratchpad path and the current date. Edits,
commits or a branch switch between sessions, a memory Qwen Code saves, a new
temporary directory, or resuming on a later day therefore do not split the
conversation or detach earlier judgments. Project instructions such as
QWEN.md or AGENTS.md are still matched in full. The stored message keeps its
original text. Other changes to earlier content can still create a separate
session because these captures have no native ID.
OpenAI-compatible hosts, including OpenRouter, use the same Chat Completions and Responses formats and format-specific identity requirements above. API compatibility alone does not admit ordinary SDK applications or other coding agents. A configured route and a supported response shape are still required.
Codex places some tools in a Responses namespace: each MCP server's tools, and
Codex's own tool groups such as collaboration and clock. Watcher folds the
namespace into the tool name the way Codex's own hooks do, and uses that name in
the transcript and in the call's judgment alike:
| Namespace | Recorded name | Example |
|---|---|---|
None, or Codex's default functions | The bare tool name | exec_command |
An MCP server, mcp__<server> | mcp__<server>__<tool> | mcp__github__create_issue |
multi_agent_v1, tool spawn_agent | The bare tool name | spawn_agent |
| Any other | The namespace followed directly by the tool name | collaborationsend_message, clocksleep |
Key command rules and tool thresholds for these tools to the recorded names.
If Codex is configured to drop the mcp__ prefix from MCP namespaces, the
capture no longer shows that the tool is from an MCP server, and Watcher names it
by the last row, for example github and create_issue become
githubcreate_issue, while Codex's hooks still report mcp__github__create_issue.
Policy does not support that configuration, because such a name can match a
translated Codex tool (see Tool names and policy).
Only the namespace is folded in: bare tool names are recorded as the agent sent
them, even where Codex's hooks report a different name, such as Bash for
exec_command.
For Chat Completions and Responses, recorded assistant model names preserve the response's model value, or the requested model when the response omits it. Watcher does not infer a provider prefix from the wire format, model name or route. Capture metadata separately records the provider key, reported model and URL without credentials, query parameters or fragments. These facts describe the captured exchange, not the original route of every historical message, and do not establish provider-specific pricing.
Watcher does not support Gemini CLI. A capture whose metadata.user_agent
starts with a versioned GeminiCLI/ or GeminiCLI-tui/ marker with that exact
capitalization, such as
GeminiCLI-tui/0.45.2/gemini-2.5-pro (linux; x64; terminal), is still recorded
as Gemini CLI and its tool calls are reviewed, but nothing else is adapted to
it. Its helper requests, such as chat compression, web search and fetch, and
model routing, are recorded like agent turns, usually each as a session of its
own. Its captures reconcile only by exact transcript matching, so when the
client replays earlier turns differently, the conversation continues in a new
session. Gemini CLI conversation IDs are not available in these captures, and Watcher
ignores Aperture's gcli_ session ID.
OpenCode's Gemini captures without a conversation ID use a history-matching fallback. It tolerates assistant whitespace and text/thought block changes, and text disappearing beside an unchanged tool call when the continuation contains its result. User messages, tool arguments, results, models and media must still agree. The incoming history must be longer than the stored history it continues. It must also share a completed tool invocation with that history, and exactly one session may match. The fallback preserves the different representations as separate trajectories within that session, with tool judgments available by their stable call IDs. The same comparison, reversed, recognizes a capture recorded after a longer history that already contains it; that capture adds no messages. An exact continuation from an older retained representation must also agree with the longest stored histories. A conflicting follow-up is not added to that Watcher session. Ambiguous matches, text-only conversations, and previously recorded captures without this matching capability stay on ordinary transcript matching. The fallback cannot resolve persistent ambiguity: later rewritten captures can continue forming separate sessions. Switching models can also split rewritten histories. The search considers only the same user's sessions whose messages before the first assistant reply, such as the system instructions and opening request, are identical to the incoming capture's. More than 32 such sessions, or more than 10,000 stored messages in them, stops the search, even when only one session would match, and the capture then reconciles by its transcript instead. Without a native conversation ID, grouping captures into one Watcher session does not prove that they belong to the same native conversation.
An Antigravity CLI capture qualifies when this cue matches:
| Cue | Accepted value |
|---|---|
| 5e. Identity text | A system text part begins with <identity>, optional whitespace and You are Antigravity. The name must end at a comma, period, whitespace, </identity> or end of text. |
For example, this system text satisfies 5e:
<identity>
You are Antigravity, a coding assistant.
</identity>
Version syntax is not checked. In Gemini API-key mode the CLI sends the generic
Google Go SDK user agent, for example
google-genai-sdk/1.71.0 gl-go/go1.28-20260721-RC03 cl/951519500 +3ebc191975 X:fieldtrack,boringcrypto,simd,mapsplitgroup.
Unrelated Go applications send the same user agent, so it never admits a capture
on its own; these captures qualify through 5e.
Cue 5e applies under any user agent except the Gemini CLI and OpenCode markers, which keep their own attribution. These cues identify the harness; they do not authenticate the client. Watcher does not distinguish Antigravity CLI from another client that sends this cue: such captures are recorded as Antigravity CLI.
Antigravity's title-generation requests are excluded. Watcher recognizes one by
either of two signals: a system text part beginning with
You are a conversation title generator, or a request that declares no tools
and has no Antigravity identity text. Otherwise, a request without tools that
carries the identity text is still recorded. Neither signal excludes a request
that declares client functions or whose response proposes a client tool call:
the CLI may run that call, so the capture is recorded and the call is graded.
Antigravity's native conversation UUID is read from the
Conversation ID: line in its <user_information> system block and stored in
the session's external_ids under the other key; the session is still
recorded as Antigravity CLI. The block must occur once across the system text and belong to the
single text part that starts with the Antigravity identity. A missing, invalid
or ambiguous UUID leaves identity to
ordinary transcript reconciliation. User
messages cannot supply this UUID. The Gemini history-matching
fallback does not apply to Antigravity.
These rules apply to every Gemini capture Watcher records:
- Watcher assigns tool-call IDs from user/tool history and invocation order, and uses wire IDs only to match results, so calls and results remain linked when a client adds wire IDs in a later request. Changes to user/tool history, including compression, can change the generated IDs. Retries without a native conversation ID may be graded again.
- Only the first response candidate is recorded. Provider-executed tools are context and are not graded.
- Identical results repeated with the same explicit ID are recorded once; conflicting repeats are rejected. Orphaned tool results are rejected.
- Request-history blocks with role
modelcontaining only function responses are recorded as tool results, and must match preceding calls. Mixed assistant/results blocks and function responses in the new response candidate remain invalid. - A completed response whose candidate has no parts (
finishReasonSTOPwith null or absentparts, or an emptypartslist) records the request's history, including its latest tool results, without an empty assistant message. Other responses that omit candidate content, such as token-limited or safety-blocked ones, are skipped asmalformed_capture, or asunsupported_apiwhen the entire candidate list is absent. - Aperture records a streamed response's thoughts as ordinary text joined with
the answer, while OpenCode and Antigravity CLI replay that turn differently in
their next request. When the capture carries a conversation ID (OpenCode's
xsid_session ID, or Antigravity CLI's native conversation UUID), Watcher stores one copy of such a turn, normally the response as Aperture recorded it, so its thoughts appear as ordinary text and the turn's tool calls stay on the conversation's trajectory. Without a conversation ID, the turn is stored twice, and the conversation continues from the replayed copy.
Antigravity CLI's Gemini API-key mode sends the Gemini API format. Its gateway route must permit that format for the selected model. Selecting a Gemini model does not make the request a Vertex API request.
Responses function calls, custom tool calls and local shell calls are recorded
with their call IDs. So is a client-executed tool search (tool_search_call
with execution: "client"), which Codex sends to find deferred MCP, app or
dynamic tools: it is recorded and graded as a tool_search call, and the
matching tool_search_output is recorded as its result. Provider-run tool
searches (execution: "server") and their outputs are kept as JSON text in
new responses and supplied history, without becoming client calls. Other
supported provider-executed actions remain transcript context and
are not selected for client-tool grading. Provider-action IDs are generated from
the action order visible in the capture. They can differ from the provider's item IDs.
Requests using previous_response_id
or conversation to reference provider-managed history are skipped: Watcher
cannot recover the missing earlier context. Opaque compaction items are
recorded as the placeholder described for Codex above.
Malformed historical tool arguments remain raw transcript context, so a later
valid call can still be graded. Malformed arguments or duplicate IDs in newly
returned client calls cause the capture to be skipped. New client calls must
also have different IDs from the earlier client calls in the supplied history.
Chat Completions uses
tool_calls; the legacy function_call field causes a skip even when it appears
only in supplied history. Unrecognized content inside a Responses assistant
message remains JSON text in the transcript. Input parts mixed into an output
message are also retained as JSON text. This applies to new output and supplied
history; recognized text and refusal fields must still contain strings.
Chat audio output and its transcript are not recorded.
For Chat Completions, only the first response choice and its client tool calls
are recorded.
Provider aliases and hostnames do not grant admission. Watcher identifies the
API format using both bodies and the endpoint path in metadata.url. A unique
paired body signature wins even when the URL suggests another format. Otherwise,
a known URL selects its format when no signatures match or when its format is
among several matches. Unresolved ambiguity is skipped. Only the selected parser
runs, and its validation must still succeed. Hosted Anthropic APIs use the same
Claude Code or OpenCode identity checks above and require a reconstructed Messages response:
| Host and API | Capture support |
|---|---|
5h. Amazon Bedrock Anthropic Invoke (invoke, invoke-with-response-stream) | Claude Code tool calls, tool results, and resumed conversations are supported. |
5i. Google Vertex Anthropic (rawPredict, streamRawPredict) | Claude Code tool calls, tool results, and resumed conversations are supported. |
5j. Microsoft Foundry Anthropic (/anthropic/v1/messages) | Uses Anthropic Messages and the Claude identity requirements above. |
Hosted Anthropic captures keep the anthropic/ model prefix and the response's
model name. Watcher does not rename Vertex or Foundry models to vertex/ or
azure/, or normalize Bedrock model names for pricing.
Bedrock Converse and ConverseStream accept OpenCode captures with a reconstructed
output.message response. Tool-use IDs link results to their earlier calls;
only the new response's client calls are selected for grading. Inline images
are recorded as markers (see Images in hook requests).
Aperture's reconstruction of a ConverseStream response leaves
signed reasoning out, and OpenCode replays it in the next request. When the
capture carries OpenCode's xsid_ session ID, Watcher stores one copy of that
turn, normally Aperture's, so its reasoning is usually not recorded; without
the ID, both copies are stored and the replayed one keeps the reasoning.
Documents, remote media and unfamiliar blocks
remain serialized context and are not fetched. Prompt-cache markers are omitted
from recorded messages. Duplicate call IDs and unmatched
results, and blocks with competing content types, are skipped as malformed captures.
Model attribution uses bedrock/
plus the model identifier from the endpoint, or bedrock/unknown on a custom
path. OpenAI models hosted on Bedrock remain unverified.
Application names and provider ownership do not grant admission. Claude Desktop and Cowork traffic must carry the Claude Code markers above; Codex Desktop and ChatGPT Desktop local Work traffic must carry a Codex marker. These engine markers do not identify the selected desktop mode. A provider's public API support does not establish support for a consumer app's protocol or conversation history, and a model appearing in an application's menu does not establish Aperture routing. Confirm the application's requests appear in Aperture using a supported format.
See Supported agents for the assessed agent and provider pairings.
The observation endpoint uses the configured response body to extract new client tool calls for
review; it does not require Aperture's optional tools send type. Earlier
calls in the request history and provider-executed calls are not graded. When
the client closes a streamed Anthropic Messages response before it finishes,
Aperture's copy has no stop reason. Watcher treats a tool call in that copy that
has no input as a call the client never received, and neither records nor grades
it. A call whose input had streamed is graded as usual, because the client may
still run it. The generic
HTTP endpoint's 32-input limit does not apply to captured Aperture responses.
The shared executor bounds fan-out using the monitor-grade admission limit.
The opt-in pre-response stage has a narrower
format contract and checks only the calls Aperture is holding.
A capture that never reaches Watcher, or that Watcher skips, leaves its calls
ungraded. The client may still have run them. If a later capture's history
contains such a call together with its result, Watcher records the call when
the call or its result first appears there. This also covers a call whose
capture was stored but whose decision could not be recorded. The client usually
sends its next request while the previous capture is still being graded, so a
call can show this ungraded record until its graded decision replaces it. The record is
ungraded, with not_evaluated as both the decision source and the applied
decision, and history_only as the decision context. It appears in Analyzer's
tool-call list and session transcript as not evaluated. A history call with no
result is not recorded, because nothing shows that the client answered it. For a
supported coding agent, a call already recorded in another session of the
organization with the same ID, tool and arguments, such as one a fork or helper
thread copied from its original conversation, is not recorded again.
Gemini-format calls are not recorded this way: Gemini sends no call IDs, and the
ID Watcher derives for a call changes when a client rewrites earlier history,
so an already-recorded call could be recorded again. Nothing is
recorded this way while the enforcement mode is paused. If the capture that
proposed the call arrives later, its graded decision replaces the ungraded
record. The exception is a call a fork recorded first: the original
conversation's later graded decision is then recorded alongside the fork's
ungraded record.
Unrecognized application traffic and known Claude Code
background requests such as warmups, usage-limit checks, title generation,
session naming, session recaps, WebFetch page summaries, and Auto Mode
permission classifications are skipped. The classifier is
recognized by its system text or by a request with no tools whose
stop_sequences list contains </severity>. The usage-limit check is a single
user message quota with max_tokens set to 1. A session recap, which Claude
Code requests when you return to an idle session, or a session name is
recognized when the request's final user message is exactly Claude Code's
recap or naming instruction, or for naming, by a request with no tools whose
system prompt is Claude Code's identity followed by the naming instruction. A
message containing other text besides the instruction is recorded. A WebFetch page summary is recognized by a request with no tools, a
system prompt that is only Claude Code's identity, and a single user message
holding the fetched page and WebFetch's fixed closing instruction. The
conversation still records the WebFetch call and its result. Either classifier
cue is sufficient, and background requests are skipped even when they carry the
conversation's native session ID. A background request is recognized by its
leading system prompt, its request shape or its final user messages, not by
text in later mid-conversation system messages. A Claude Code capture whose
response proposes a client tool call is never skipped as a background request:
it is recorded and its calls are graded. Null
or upstream-error responses and captured content rejected by validation are
skipped too. Skipped deliveries are acknowledged with HTTP 202 and do not
create sessions or grades. Each skip has one of these reasons; the
aperture_hook_skipped log event records the reason for unsupported_api,
malformed_capture skips only:
| Reason | Meaning |
|---|---|
6a. missing_response | The captured response is null or absent, as when the client disconnects before the provider responds. Also: Aperture replaced the response with an aperture_error marker, for example after a response truncated upstream; the response has null content (a refusal with no content blocks); it reports an Anthropic error or OpenAI/Gemini/Converse error object; or it has a failed/cancelled Responses status. |
6b. unsupported_api | The API format is unsupported or ambiguous, or the required request/response fields for that format are missing. |
6c. malformed_capture | The response carries an invalid_body marker, message content fails validation, metadata.url cannot be parsed, a Responses computer_call or a tool_search_call with an execution type other than client or server is unsupported, or a history reference leaves earlier context unavailable. |
6d. excluded_conversation | The capture does not match a supported coding-agent identity, or matches an excluded background request (Claude Code, a Codex helper request identified by its thread_source or request_kind, or a Qwen Code memory-recall request). |
missing_response and excluded_conversation skips are routine (most
Aperture captures are other applications' traffic) and are not logged. Other
applications' traffic is still not ingested. While
agent inventory is on, Aperture captures
and raw-format requests record sightings of their clients: the client's name
and the person, nothing else, at most once every five minutes per person and
client. A person the gateway names under sessions:write:any becomes a Watcher
user, as for recorded sessions. Watcher
decides most routine skips from the capture's user agent and a few top-level fields,
before the delivery takes a worker, and acknowledges those without converting
the capture. A capture from an application with no supported coding-agent cue,
and a background request recognized by its system prompt or request shape whose
response contains no client tool call, such as the web search helper, produce
excluded_conversation even when the capture would fail validation.
A Converse response with only a top-level message and no reconstructed
output is classified as unsupported_api, including errors delivered in
that shape.
Once an Aperture envelope passes validation, every log line for a delivery that is not skipped as routine, from the capacity check through grading and recording, identifies the capture without its content:
| Field | Meaning |
|---|---|
aperture_request_id, aperture_session_id | Aperture's metadata.request_id and metadata.session_id, exactly as Aperture sent them, so you can search the log for an identifier Aperture shows and group the lines of one capture or one Aperture session. aperture_session_id is null when Aperture sent no session identifier. Neither is a Watcher session UUID. Aperture session IDs describes which values Watcher uses to match conversations. |
aperture_user_agent_family | The captured client: claude-cli, codex, opencode, gemini-cli, antigravity, qwen-code, mistral-vibe, other or absent. The family names the application marker the user agent matches, not whether the capture was admitted. Antigravity CLI's Gemini API-key mode sends the generic Google Go SDK user agent, which is logged as other. The user agent itself is never logged. |
A malformed_capture skip also records error_class and error_module (the
exception class), error_cause (the class of the exception it was raised
from) and, when one of Watcher's format parsers raised it, error_code, a
fixed phrase such as invalid_tool_arguments. A skip caused by Aperture's
invalid_body marker records error_code: invalid_body only. None of these
fields contains message text, tool arguments or other values from the capture.
Unexpected processing failures are logged separately as aperture_hook_failed
with the exception class.
- Configure an authenticated, reachable Watcher endpoint as described above.
- Choose the Aperture users or device tags and provider keys whose conversations you want to observe. Start with a test scope. Avoid capturing the same test conversation through both Aperture and an installed Watcher client.
- Merge the following hook and grant into your existing Aperture configuration. Replace the URL, API key, login, and provider pattern with your values. The example is for an SSO-mode deployment.
{
"hooks": {
"watcher": {
"url": "https://watcher.example.com/api/v1/hooks/aperture/entire-request",
"authorization": "x-api-key",
"apikey": "<organization-api-key-with-sessions:write:any>",
"timeout": "60s"
}
},
"grants": [
{
"src": ["developer@example.com"],
"app": {
"tailscale.com/cap/aperture": [
{
"models": "anthropic/**",
"send_hooks": [
{
"name": "watcher",
"events": ["entire_request"],
"send": ["request_body", "response_body"]
}
]
}
]
}
}
]
}
The timeout value is a duration string. We recommend 60s. See
Aperture delivery timeout.
The models pattern uses your Aperture provider key. For a provider named
bedrock, use bedrock/**; add a separate capability entry to capture both
providers. A src device tag must already identify the intended machine. A
login scope captures that user's matching requests from all their machines. See
Aperture's configuration reference
for grant syntax.
Aperture sends a fixed JSON envelope containing metadata, request_body, and
response_body. metadata.login_name supplies developer attribution. When the
Watcher client already recorded the conversation for that developer, the capture
joins that session. An unowned session or one belonging to another developer
stays separate. Recording never changes its owner.
Watcher reads Claude Code's native conversation ID from
request_body.metadata.user_id, Codex's from
request_body.client_metadata.thread_id, and Antigravity CLI's from the
<user_information> block in its identity system text. If no native ID is
available, Watcher reconciles transcript prefixes.
Codex's thread ID identifies one conversation; its body
session_id can be shared by a parent and its child agents. A missing or invalid
thread ID leaves the native ID unset, even if a valid session_id is present.
Watcher never uses Aperture's request_id as a conversation ID, and uses
Aperture's metadata.session_id only as described in
Aperture session IDs.
Watcher turns client tool calls in the response into one generic batch, using prior
turns only as context and ingesting the transcript once after evaluation finishes.
Completed judgments can be reused on redelivery when the request has a native
conversation ID or a kept Aperture session ID and the
key has permission to read the session. Captures without either ID and keys
with only sessions:write:any grade again. Failed
or unjudged records are evaluated again. Read permission grants broader session
access; it is optional and is not needed to accept or record a delivery.
Text-only turns are ingested too. An advisory denial records what Watcher judged;
this asynchronous hook cannot stop the tool from running.
POST /api/v1/hooks/aperture also accepts these observation deliveries, and
serves the enforcement stages below from the same URL. A delivery whose
metadata.stage is post_complete, or that names no stage, is observed
exactly as through /entire-request.
Configure Aperture enforcement
Enforcement uses the same URL, POST /api/v1/hooks/aperture, from a
synchronous tool_call_pre_response hook. Watcher switches on
metadata.stage. It accepts Anthropic Messages, OpenAI Responses and Chat
Completions, Bedrock (Converse and InvokeModel), and Gemini calls. The selected
calls must match the captured provider response exactly.
Start with one test user and provider. Use the same authentication and network
prerequisites as the observation hook. Set the administrator's
enforcement.mode to enforce. Merge this example into the existing Aperture
configuration, replacing the URL, credential, user and provider pattern:
{
"hooks": {
"watcher-enforce": {
"url": "https://watcher.example.com/api/v1/hooks/aperture",
"authorization": "x-api-key",
"apikey": "<organization-api-key-with-sessions:write:any>",
"timeout": "310s",
"fail_policy": "fail_closed",
"block_response": "message",
"fail_response": "message"
},
"watcher": {
"url": "https://watcher.example.com/api/v1/hooks/aperture",
"authorization": "x-api-key",
"apikey": "<organization-api-key-with-sessions:write:any>",
"timeout": "60s",
"fail_policy": "fail_open"
}
},
"grants": [
{
"src": ["developer@example.com"],
"app": {
"tailscale.com/cap/aperture": [
{
"models": "anthropic/**",
"send_hooks": [
{
"name": "watcher",
"events": ["pre_request", "entire_request"],
"send": ["request_body", "response_body"]
},
{
"name": "watcher-enforce",
"events": ["tool_call_pre_response"],
"send": ["request_body", "response_body", "tools"]
}
]
}
]
}
}
]
}
Both hooks use the one URL. They are separate entries because Aperture sets
the failure policy and timeout per hook, not per event: the notice and
observation must fail open, while enforcement must fail closed. While Watcher
is unreachable, a pre_request delivery waits up to the watcher hook's
timeout before Aperture lets the request through; if that delay matters, give
pre_request a third hook entry with the same URL and a short timeout.
For Codex, use the configured OpenAI provider key in models, for example
openai/**. Keep the HTTP-only Codex setup described above. Do not add this
hook to every provider grant until you have tested each client and format.
Keep fail_policy set to fail_closed: transport errors, invalid callbacks
and Watcher timeouts must not release unchecked pending calls. Watcher has a
300-second evaluation budget; the longer Aperture timeout leaves room for
transport overhead. Shorter proxy or client timeouts can still stop the run.
Set block_response and fail_response to "message". Without them, a block
on a non-streamed response reaches the client as an HTTP 403 error, and a
fail_closed failure as an HTTP 503 error, which agents often retry as failed
calls. With them, the client receives a normal assistant answer instead: the
block message, or guardrail hook unavailable after a failure. Either way the
pending calls do not run. Both settings default to "error".
Configure the entire_request observation hook alongside enforcement. It
records the full transcript, including tool results and text-only responses.
It reuses decisions for calls already judged by enforcement instead of grading
those calls again. An observation hook alone cannot enforce policy, even when
enforcement.mode is enforce.
Subscribe the fail-open hook to pre_request as well, on the same provider
grant. For that stage Watcher adds a fixed system notice explaining replacement calls and how to react
to denials and escalations, without grading or enforcing policy. You can omit
that event only when managed client instructions already include the exact
notice Watcher returns. The notice is added at most once to supported requests.
Aperture tells each delivery's stage in metadata.stage, and
/api/v1/hooks/aperture answers it accordingly: pre_request with the notice,
pre_response with a decision, and post_complete (or a delivery with no
stage, or one Watcher does not know) with a 202 for observation. A
pre_response delivery without response_body is rejected with HTTP 422. The
observation-only /entire-request URL skips a delivery whose stage is
pre_request or pre_response.
Watcher compares selected tool IDs, names and arguments with the supplied
response before grading. If tool_calls is absent, it derives completed calls
from the response. Nonfinal text without completed calls is ignored. Earlier
released calls are not selected again and cannot be retracted.
Allowed calls remain unchanged, and Aperture releases them even when another
call in the same response is refused. For a denied or escalated Bash,
bash, exec_command or exec call, Watcher replaces its arguments with a
harmless command that prints a literal notice. The tool name and call ID stay
unchanged. The original operation does not run. These replacements use
command for Bash and bash (OpenCode's shell tool), cmd for
exec_command, and JavaScript text(...) in input for exec. For Codex
Code Mode, whose model calls every tool from inside one exec program, the
whole program is replaced, including any allowed steps it contained.
A refused call to another tool, such as an MCP tool or a file edit, is renamed
to one of those notice tools when the request's tools declares it with the
same call type: Bash or bash for Anthropic Messages, exec_command,
Bash, bash or exec for an OpenAI function call (Responses or Chat
Completions), and exec for an OpenAI Responses custom tool call. The call
keeps its ID and prints a notice that names the original tool and summarizes
its arguments. Aperture renames a call only to a tool the client declared, of
the same call type.
No notice tool is available when the request declares none of those tools
with the refused call's type. In practice that is Codex's apply_patch, a
custom tool call, when Codex runs without Code Mode and declares only the
exec_command function; Codex Code Mode's helper tools such as
request_user_input, whose declarations Codex sends inside input rather than
tools; Bedrock Converse calls; Codex local_shell and client tool search
calls; and clients whose shell tool has another name.
A denied call no notice tool can replace is removed from the response, as long as another call still reaches the client. When another refused call produces a notice, the first such notice also names the removed calls and their reasons; beside only allowed calls, a removed call gets no notice of its own. When nothing would reach the client, Watcher blocks the whole pending callback instead, so the agent receives the block message explaining why rather than an empty answer. An escalated call no notice tool can replace always blocks the whole pending callback: removing it would hide that it needs a person. The block message then asks the agent to stop and ask the user, with the same labelled choices as an escalation notice.
Renaming and removal need an Aperture that supports per-call edits, which
shipped together with metadata.stage.
A denial notice includes a shortened call summary and policy reason. It asks the agent to continue by another approach without repeating the identical blocked call. An escalation notice instead asks the agent to stop and present a short human question with labelled choices, such as skipping the call, doing something else, or stopping to get approval outside the gateway. The gateway does not grant human approval: a reply does not bypass the policy applied to the next proposal.
Gemini calls cannot be edited one at a time, so a refused Gemini call blocks the
whole pending callback, including otherwise allowed siblings. Gemini function
calls usually carry no ID, and Aperture's tool_calls then name none; Watcher
matches them to the response by position, and only when they list every call
in the response in order. A block message includes
the reason and all withheld calls. A block ends the current turn in Claude
Code and Codex. For autonomous workloads that must resume after a block, use a
controller that re-prompts the same conversation with the denial message and
asks it to continue by an allowed approach. Retry at most twice per task, then
stop for a person if the task is still incomplete. Stop sooner if it repeats
a blocked operation or makes no progress. Each new proposal is checked normally.
This route does not resample the model. A grading failure follows the
administrator's policy_monitors.on_grading_failure setting. With allow, a
failed review can release a call without a complete grade. Use deny when
such calls must be withheld. Transport failures instead follow Aperture's
fail_policy.
In observe mode a pre_response delivery gets allow immediately, then Watcher grades
and records in the background. It never replaces or blocks calls based on those
grades. Paused mode records the transcript without grading. Transport failures
can still withhold calls when Aperture uses fail_closed.
Watcher records refused calls before returning a replacement, removal or block. The record keeps the original proposal, its original tool name, its policy judgment, and evidence that the original call was withheld. It does not say which of the three delivery actions withheld it. Allowed-call recording runs asynchronously. Later observation does not overwrite that original judgment with a grade for the notice command. Raw arguments in notices are not copied into findings-only decision context. A server restart can lose pending background recording. A redelivery can repeat grading and charges; replay is not guaranteed.
Verify with a harmless task and a scoped deny rule. Check that the original operation has no effect, the replacement prints the call and reason, and the agent can choose an allowed alternative. Test escalation separately: the agent should ask for a labelled human choice. In Analyzer, inspect the original proposal and decision, plus later tool results from observation. Test a refused non-shell tool beside an allowed call: the refused call should come back as a notice from the client's shell tool while the allowed call still runs. Finally, test an unreachable enforcement URL: pending calls must remain withheld. Restore the URL after the outage test.
Aperture session IDs
Aperture adds its own metadata.session_id to each delivery and prefixes it
with how it derived the value. It sends the same value at every stage, so a
pre-response decision and the later entire-request capture of that exchange
land in the same session. Watcher keeps two prefixes and ignores the rest.
A kept value is used only for a capture without a native conversation ID; a
native ID stays the capture's only ID.
| Prefix | Aperture derives it from | Watcher |
|---|---|---|
7a. xsid_ | The client's X-Session-Id request header, from whichever client sends it. OpenCode sends its session ID there, and keeps it when a session is resumed. | Uses it as the conversation ID |
7b. pisn_ | A pi agent session. Whether it stays the same when a session is resumed has not been verified. pi requests sent with a Claude subscription get an anfp_ fingerprint (7f) instead. | Uses it as the conversation ID |
7c. ancc_, bdrk_ | A Claude Code session on Anthropic or Bedrock. | Ignores it: Watcher reads Claude Code's own session ID from the request |
7d. ocdx_ | Codex's Session-Id header, which a parent agent shares with its subagents. | Ignores it: it names several conversations, and Watcher reads each Codex thread ID instead |
7e. gcli_ | Gemini CLI. | Ignores it |
7f. orfp_, anfp_, xrnd_ | Fingerprints of request content, or a random value, that change on nearly every request. | Ignores it |
| 7g. Any other prefix | Not documented. | Ignores it |
A kept value is stored in the session's external IDs under the
tailscale-aperture key and places captures the way a native ID does:
- Captures with the same ID join one session even when the transcript no longer matches: a resumed session with a changed system prompt, a reverted turn, a compacted history, or an auxiliary request, which becomes a separate trajectory in that session.
- A capture whose transcript continues a session that has a different ID starts its own session with a copy of the shared history. A forked OpenCode session therefore gets its own session, and the parent's next turn stays in the parent's.
- Sessions with different IDs never merge, even when their first captures are identical.
A client that sends X-Session-Id through Aperture should keep the value
constant for exactly one conversation. Reusing it for several conversations
merges them into one session. Sending a new value with each request makes
every capture look like a fork, so each gets its own session. Captures without
a kept value are placed by their transcript, as described above for each
harness.
The stored value is returned in the session's external_ids by the sessions
API and the Python SDK, whose search_sessions
filter finds the sessions you can read that carry one value, for example
external_ids={"tailscale-aperture": ["xsid_…"]}. The Analyzer does not show
it.
Watcher records a capture only after all its tool calls are graded, so a capture
whose calls take longer to grade can be recorded after a later capture of the
same conversation. A late capture with a kept value joins the session holding
it, adding a branch where its transcript differs from the stored one. Without
one, when exactly one session already stores a longer transcript
containing the late capture's conversation, Watcher records the late capture's
decisions in that session, linked to the stored tool calls and results, and
stores none of its messages again. OpenCode Gemini captures recognize
containment with the history-matching comparison described above; other
captures, Gemini CLI's included, require the stored transcript to contain the
capture exactly. When several sessions contain it, an exact copy's judgments are
not recorded, and the delivery logs aperture_hook_recording_incomplete; an
OpenCode Gemini capture starts a new session instead.
Images in hook requests
Watcher does not store the bytes of inline images in structured hook requests:
format: "watcher" transcripts, format: "raw" provider requests, and
Aperture captures. Before evaluation, each image block that carries its image
inline as base64 has its image field replaced with a marker:
watcher-elided-image:<media type>;bytes=<decoded size>;sha256=<hex digest>
For example, watcher-elided-image:image/png;bytes=1203456;sha256=9f86d0...
(the digest is 64 hexadecimal characters). bytes counts the decoded image
bytes, and sha256 is the SHA-256 digest of those bytes, so the same image
always produces the same marker. Session and message API responses return the
marker, and the Analyzer shows it as "Image not stored" with the media type and
size. A data URI may carry media-type parameters and line breaks in its
base64. Percent-escaped base64 is not decoded and is stored as sent. An image given as a URL is stored as sent, and so is a data URI whose
base64 contains any other character outside the base64 alphabet or does not
decode, or whose header (the part before the first comma) is longer than 256
characters. Base64 inside text and non-image attachments, such as
PDF documents, are stored as sent.
Monitors and graders never receive image content, so evaluation is the same
with or without the marker. Watcher identifies an image by its digest when
matching a conversation, so a transcript that carries an image inline and a
later request carrying its marker continue the same trajectory. Agent
transcript files sent to the generic hook (format: "claude-code-jsonl" or
"codex-jsonl") and transcripts uploaded through the ingestion API, including
those the Watcher client uploads, keep their images as the agent recorded them.
Conversations recorded with images by a Watcher version that stored image
bytes are matched differently. The first full transcript of such a conversation
sent after an upgrade, which every Aperture capture is, starts a new branch at
its first image-bearing message: in the same session when the request carries a
conversation ID, otherwise in a new session. Later full transcripts continue the
new branch. An append_after request still extends the stored messages, but the
next full transcript of that conversation starts the new branch. If such a
session's content was removed by retention and the conversation is recorded
again, retained grades on messages at or after its first image-bearing message
stay detached from the restored messages.
Delivery limits and verification
| Result | Endpoint | Meaning |
|---|---|---|
| HTTP 200 with a decision or ordered list | Generic, full request | Evaluation finished. Observe returns a completed advisory judgment. Recording can still be in progress. |
HTTP 200 with [] | Generic, full request | Transcript-only input was accepted; no tool calls were evaluated. |
HTTP 200 with append_after and results | Generic, append | The delta and available decisions were stored. Use the returned cursor for the next append. results: [] means no calls were selected. |
HTTP 200 with decision_source: "grading_error" | Generic | A grading timeout, grade-capacity limit, exhausted allowance, or grading failure invoked policy_monitors.on_grading_failure. Inspect grading_error.code (timeout, at_capacity, allowance_exhausted, grader_failed, or no_result) and grading_error.stage (triage or gateway, for the stage that failed), and apply the returned decision. One case escalates regardless of the failure policy: a Codex call that too many pending calls in the transcript could match returns grader_failed with a null stage. |
HTTP 200 with action: "allow", "modify" or "block" | Aperture pre-response | Evaluation completed. Aperture releases the pending calls, edits individual calls (new arguments, a new tool name, or removal), or withholds them all. Recording may still be in progress. |
| HTTP 422 or 504 | Aperture pre-response | The pending calls could not be safely evaluated, the delivery had no response_body, or the 300-second budget expired. With fail_closed, Aperture withholds them. |
HTTP 202, {"status":"accepted"} | Aperture post_complete or entire-request | Admitted for background processing. It does not confirm completed grading or durable storage. |
| HTTP 202 followed by a logged skip | Aperture entire-request | The capture has a missing/error response, an unsupported API shape, malformed content, or an excluded conversation. No session or grade is created. |
| HTTP 403 | Aperture | The caller lacks sessions:write:any, needed for developer attribution. |
| HTTP 422 | Aperture entire-request | The outer webhook envelope is invalid. Watcher logs aperture_hook_rejected with each error's field location and type, never the rejected values. Unsupported captured API formats are skipped after HTTP 202 instead. |
| HTTP 503 | Aperture entire-request | Delivery workers are full. This delivery was not accepted. |
HTTP 503 with detail.code: "image_capacity_exhausted" and Retry-After | Generic | The server is already converting its maximum number of image-bearing requests (8 per API process). Nothing was evaluated or recorded; retry the whole request after Retry-After seconds. |
HTTP 503 with detail.code: "append_recording_failed" | Generic, append | Apply the decisions in top-level results; no new cursor is returned. Retry the same append to finish recording; handle 404, 409, or 422 with one full-request fallback. |
| HTTP 403 | Generic, append | The credential has no session-write authority (sessions:ingest or sessions:write:any). |
| HTTP 401 | All hooks | Authentication is missing or invalid. |
| HTTP 413 | All hooks | The request exceeds the configured upload limit, described below. Watcher logs hook_request_body_too_large with the limit and the declared or received size. |
| HTTP 422 | Generic | Request validation failed, settings_overrides is invalid or forbidden, or an append names an unsupported stored format. Combining append_after with ephemeral: true is invalid, as is combining record_transcript: false with either. The whole request is rejected before ingestion or grading. detail is a list of validation errors; unsupported stored formats use loc: ["body", "append_after"]. |
HTTP error for a scalar; status_code and detail in one batch output | Generic | A monitor stage refused the call, for example HTTP 500 when its configured monitor is unavailable on the deployment. A batch keeps that error in input order and continues with the other inputs. |
All hook endpoints use the shared upload limit. When that setting is unset, their default is 64 MiB. An Aperture capture is the entire model request, including attached screenshots, so ordinary captures can reach tens of MiB. The packaged gateway has an independent 72 MiB limit. A proxy refusal reaches neither Watcher nor its logs, and Aperture does not retry a refused delivery. All hook endpoints share a limit of 128 in-flight monitor grades per server process. This limit does not reserve capacity for enforcement or provide per-organization or per-session quotas. Paused requests and requests with only unnamed or no inputs need no grading admission. Their ingestion still needs database capacity and permission to record the transcript.
The asynchronous Aperture endpoint admits up to 64 deliveries per server process through
evaluation and recording, independently of calls per delivery. Generic observe requests wait
for completed judgments and do not consume this delivery limit. Self-hosted
operators can set WATCHER_HOOKS_MAX_INFLIGHT_DELIVERIES in the Compose .env.
Helm deployments use api.hooksMaxInflightDeliveries. Both limits apply per
API server process (Compose runs WATCHER_UVICORN_WORKERS processes, 2 by
default). Converting a capture briefly needs about three times its body size.
After conversion, an admitted delivery releases the request body and keeps
its transcript with each image reduced to a marker (see
Images in hook requests). Large captures are
mostly screenshots, so a waiting delivery usually holds a small fraction of its
body. A capture made mostly of text keeps that text until it is recorded. A
generic request holds its whole body until its response is sent, because the
caller waits for the decision; a grade that finishes after the response does
not keep that body. Size the API's memory for the request bodies it may be
receiving or answering at once, plus that text, or lower either limit.
Hook execution does not retain database transactions while waiting for monitor responses. Timed-out grades continue under the same admission bound so their results and usage can be retained.
Aperture background work and full-request post-response recording are held in
memory, not a durable queue. A server restart can lose an accepted Aperture
delivery or interrupt that recording. Appends wait for message and available
decision recording, but a disconnect can leave the caller unsure whether they
committed. Retrying can incur additional grading charges when a
reusable evaluation is unavailable, recording has not finished, or
force_regrade is true. Decision recording keeps one canonical decision.
Missing-grade recovery can link evidence from another attempt, and some grades
can remain unlinked. A native enforced decision takes precedence over a hook
observation unless force_regrade explicitly requests replacement. The caller
owns transport-failure handling.
To verify the integration, send the example request above with a unique
external_ids.other value. Inspect the returned decision and find the session
in Analyzer under the authenticated or authorized attributed user. In observe
mode, verify that the response is deferred, retains the completed
judged_decision, and that the later stored judgment is advisory. With an
administrator-paused hook policy, verify that the transcript appears without
hook decisions or hook grades. Check the server logs if the expected session
does not appear after a successful response.
Aperture's asynchronous hooks fail open; this integration does not promise retries or delivery of every turn. Unsupported formats, excluded background calls, and processing failures are recorded in server logs after admission.
For Aperture observation, run a scoped conversation in the coding agent you are integrating and have it use a tool. Find its session in Analyzer under the developer's login and inspect the tool-call judgment and attached grades. Verify that the record is advisory and that the tool still ran. With an administrator-paused policy, verify that the transcript appears without hook decisions or grades.
Aperture delivery timeout
Aperture's hook timeout bounds the whole delivery. It can expire while the
delivery waits to be sent behind other deliveries, not only while Watcher
responds. A large capture that uploads slowly can hold later deliveries for
tens of seconds. With Aperture's 5-second default, those later deliveries can
time out.
Aperture abandons a delivery that times out. Its documentation describes no retry for asynchronous hooks. Usually Aperture has already started the request, so it cancels the request before the body finishes arriving. Watcher then never receives the complete capture, so it writes no session update or grade for that turn. If the timeout expires after Watcher admits the delivery but before Aperture sees the HTTP 202, processing still continues.
The entire_request event does not delay the coding agent, so a long timeout
costs no agent latency. Use at least 60s, as in the example above.