trs

AI Agent Integrations: Reference

How trs integrates with each supported AI coding agent. Use this doc when adding a new agent, debugging a broken integration, or reviewing why a specific quirk exists.

Last validated: 2026-04-19 against trs v0.5.7.

Output-saver matrix

trs output-saver installs output-reduction rules into each agent’s global config. Orthogonal to the input-side hook/plugin/rules install matrix below. Six distinct target paths across three mechanisms:

Agent Mechanism Path
Claude Code standalone file + @import ~/.claude/trs-output-saver.md + line in ~/.claude/CLAUDE.md
Gemini CLI standalone file + @import ~/.gemini/trs-output-saver.md + line in ~/.gemini/GEMINI.md
Cursor local plugin, always-apply rule ~/.cursor/plugins/local/trs/
Codex inline with sentinels ~/.codex/AGENTS.md
Windsurf inline with sentinels ~/.codeium/windsurf/memories/global_rules.md
OpenCode inline with sentinels ~/.config/opencode/AGENTS.md
Kilo Code inline with sentinels ~/.config/kilo/AGENTS.md
Factory Droid inline with sentinels ~/.factory/AGENTS.md
Antigravity IDE @import (shared with Gemini), ~/.gemini/trs.md + line in ~/.gemini/GEMINI.md (output-saver); hooks live separately, see below  
Antigravity CLI (agy) @import (shared with Gemini), ~/.gemini/trs.md + line in ~/.gemini/GEMINI.md (output-saver); hooks live separately, see below  
Grok Build inline with sentinels $GROK_HOME/AGENTS.md (default ~/.grok/AGENTS.md)
Kiro steering file with inclusion: always ~/.kiro/steering/trs.md
OpenClaw inline with sentinels ~/.openclaw/workspace/SOUL.md

Grok Build was confirmed on grok 1.0.70: a needle in ~/.grok/AGENTS.md reached a headless session. Kiro and OpenClaw follow each agent’s docs. No real binary has confirmed they load, so treat them as unverified until one does.

Inline installs use the sentinels <!-- trs:output-saver:start v1 --> / <!-- trs:output-saver:end --> so a second run replaces the block between them without touching the surrounding user content.

AGENTS.md convention: Codex, OpenCode, Kilo, and Droid all auto-load the AGENTS.md convention (Droid is a signatory of the AGENTS.md consortium, see https://factory.ai/news/agents-md). That’s why those four converge on the same install mechanism.

Plugin-level hook note: OpenCode’s plugin API has no prompt-layer hook (tool.execute.* only). Kilo exposes experimental.chat.system.transform and Droid exposes SessionStart / UserPromptSubmit, both could inject rules dynamically. For a static rules block the AGENTS.md file is simpler and less likely to break across agent updates.

Integration types

Agents fall into three architectural buckets. Pick the right bucket BEFORE writing a template, the install mechanism, test strategy, and failure modes differ.

Type How it works Agents File written
Hook (JSON event) Agent fires a PreToolUse-style event, hands us the command on stdin, applies our rewrite response Claude Code, Gemini CLI, Cursor, Factory Droid, Codex (codex-cli ≥ 0.134), Antigravity IDE, Antigravity CLI settings.json / hooks.json
Plugin (TypeScript) Agent auto-discovers .ts plugin files at startup and mutates tool args in-process OpenCode, Kilo Code plugins/trs.ts
Rules file No programmatic interception. Agent reads a rules/instructions file and VOLUNTARILY prefixes trs Windsurf, Codex (fallback on older builds) AGENTS.md / .windsurfrules

Hook and plugin are deterministic (binary: fires or not). Rules-based is probabilistic, depends on the agent choosing to follow the guidance.

Wire-format dispatch (hook agents)

All three hook agents send tool_input.command on stdin but expect different output shapes. src/rewrite.rs::HookEvent dispatches on the hook_event_name field of the stdin JSON:

hook_event_name Client Output envelope
PreToolUse (capital P) Claude Code hookSpecificOutput.updatedInput.command
BeforeTool Gemini CLI hookSpecificOutput.tool_input.command + top-level decision
preToolUse (lowercase p) Cursor top-level updated_input.command (no permission)
missing / unknown fallback Claude format

Claude’s PreToolUse and Cursor’s preToolUse differ ONLY by case. If you change the match order or add a case-insensitive comparison, you will break one of them silently.

Factory Droid uses Claude’s Shape verbatim, hook_event_name: "PreToolUse".

Agent attribution (TRS_AGENT)

Added in v0.5.8. When the rewriter or a plugin template emits a rewritten command, it prefixes it with TRS_AGENT=<label> so the downstream trs <cmd> execution can attribute the run.

Agent Detection Label
Claude Code hook_event_name: PreToolUse claude
Gemini CLI hook_event_name: BeforeTool gemini
Cursor hook_event_name: preToolUse cursor
OpenCode plugin template bakes the label opencode
Kilo Code separate plugin template bakes the label kilo
Factory Droid same wire format as Claude claude (indistinguishable from Claude)
Antigravity IDE / CLI rules-only as of v0.6.6 (why) (untagged)
Codex PreToolUse hook command carries TRS_AGENT=codex (codex-cli ≥ 0.134) codex (rules-only fallback: (untagged))
Windsurf rules-only, no programmatic signal (untagged)

The shell treats leading VAR=value as a per-command env override and strips it before executing the downstream program, so the tag is transparent to git/cargo/etc. Read via std::env::var("TRS_AGENT") at log time in tracker::log_execution. View results with trs stats --by-agent.

Droid limitation: Droid’s envelope is identical to Claude’s at the wire-format layer. We can’t distinguish them without a separate signal (install-time flag, marker in the hook content, etc.). Both show up as claude in attribution today.

Per-agent reference

Claude Code

   
Type Hook
Config ~/.claude/settings.json (global) or hooks/hooks.json (project)
Event PreToolUse with matcher: "Bash"
Template CLAUDE_HOOKS
Test prompt hook-based

Canonical client: we treat its format as the default. One quirk, permissions: Claude Code matches permissions.allow/ask/deny against the command after the hook rewrote it (checked on a real Claude Code with a rewriting hook), and a hook permissionDecision: "allow" overrides them. A blanket allow therefore ran git push even with deny: Bash(git push:*), and a plain rewrite made a user’s allow: Bash(git status:*) stop matching trs git status. So for the claude label, src/rewrite_permissions.rs reads the user’s rules and applies them to the original command (every &&/||/;/| part):

Original command Hook does
matches a deny or ask rule no rewrite, Claude handles the original
every part matches an allow rule or is read-only (ls, cat, git status, …) rewrite and allow
anything else rewrite, no decision: Claude’s own prompt applies
a settings file exists but cannot be parsed no rewrite (fail closed)

Sources: ~/.claude (or CLAUDE_CONFIG_DIR), managed settings, and .claude/settings{,.local}.json from the cwd upwards. A project’s allow counts only when ~/.claude.json marks the folder trusted (Claude ignores it otherwise); its deny/ask always count. Rules passed with --settings are invisible to the hook. The other agents each have their own gate, see Permissions per agent.

Gemini CLI

   
Type Hook
Config ~/.gemini/settings.json
Event BeforeTool with matcher: ".*"
Tool name run_shell_command
Template GEMINI_HOOKS
Docs https://geminicli.com/docs/hooks/reference/

Quirk: emits a different output envelope than Claude. Early installs copied Claude’s shape and silently failed, hook fired, exit 0, command not rewritten. Fixed in a662c9d by dispatching on hook_event_name.

Hallucination caveat: Gemini’s chat mode sometimes fabricates plausible command output when shell is unavailable. If the reported trs --version shows a version that doesn’t exist (e.g. v0.14.13), Gemini is inventing, validate via trs stats --history from a real terminal.

Cursor

   
Type Hook
Config ~/.cursor/hooks.json
Event preToolUse with matcher: "Shell"
Tool name Shell
Template CURSOR_HOOKS
Docs https://cursor.com/docs/hooks

Quirks:

Factory Droid

   
Type Hook
Config ~/.factory/settings.json
Event PreToolUse with matcher: ".*"
Tool name Execute (NOT Bash)
Template DROID_HOOKS

Quirk: Droid’s shell tool is called Execute, not Bash. Initial installs copied Claude’s template with matcher: "Bash" → hook registered but never matched. Fixed in af5b783 by widening the matcher to ".*". Our trs rewrite internally filters non-shell input, so the wider matcher is safe.

Output envelope is identical to Claude Code.

OpenCode

   
Type Plugin (TypeScript)
Config ~/.config/opencode/plugins/trs.ts (global) or .opencode/plugins/trs.ts (project)
Hook key 1.x "tool.execute.before" (string literal, not before_tool_call)
Hook key 2.x ctx.tool.hook("execute.before") and ctx.shell.hook("create.before")
Tool name check 1.x input.tool === "bash", 2.x input.tool === "shell"
Mutation 1.x output.args.command = viaTrs(cmd), 2.x input.input = { ...input.input, command: viaTrs(cmd) }
Template OPENCODE_PLUGIN (one default export serves both)
Docs https://opencode.ai/docs/plugins/

Quirks:

Kilo Code

   
Type Plugin (TypeScript)
Config ~/.config/kilo/plugins/trs.ts (global) or .kilo/plugins/trs.ts (project)
Template KILO_PLUGIN (1.x plugin API, named export)

Kilo mirrors OpenCode 1.x’s plugin architecture. Same tool.execute.before hook, same auto-discovery. Our install spec treats it as an OpenCode 1.x clone and ships its own named-export template (KILO_PLUGIN); revisit it if Kilo moves to the 2.x plugin API.

Codex

   
Type Hook (codex-cli ≥ 0.134) with rules-file fallback
Config ~/.codex/hooks.json (PreToolUse, matcher "Bash") + ~/.codex/AGENTS.md
Event PreToolUse; reply via hookSpecificOutput.updatedInput.command with permissionDecision: "allow"
Hook command trs rewrite --caller codex
Template CODEX_AGENTS_SECTION (rules block)
Version gate REWRITE_HOOK_MIN_VERSION = Some((0,134,0)) in src/codex.rs

Version-gated. Codex CLI implements programmatic command rewriting via the PreToolUse hook’s hookSpecificOutput.updatedInput.command field starting in codex-cli ≥ 0.134 (PR openai/codex#20527, merged 2026-05-12; verified end-to-end on 0.136.0). On a qualifying build, trs init codex --global merges a real PreToolUse hook into ~/.codex/hooks.json (preserving the user’s other hooks; idempotent). Approve it once via Codex’s /hooks prompt and commands are rewritten automatically, no trs prefix needed.

Rules-only fallback. On older codex builds (or when the hook isn’t trusted), trs falls back to the ~/.codex/AGENTS.md block instructing Codex to prefix trs. Prefixing is always safe: trs never double-wraps a command already starting with trs.

Caveat. codex exec dispatches PreToolUse too (verified on 0.166), but only once the hook is trusted ([hooks.state] in config.toml, or --dangerously-bypass-hook-trust); an untrusted hook silently does not run.

Validate with the hook-based test prompt on ≥ 0.134, or the rules-based test prompt on the fallback (see docs/agent-test-prompts.md section below).

Antigravity IDE + Antigravity CLI

   
Type Rules file (was programmatic hook, reverted in v0.6.6)
Config (shared) ~/.gemini/GEMINI.md (sentinel-wrapped rules block)
Template ANTIGRAVITY_RULES_SECTION
Tool name n/a, no programmatic interception

v0.6.6 revert. Antigravity (IDE + CLI/agy) is rules-only. Empirical testing against agy v1.0.1 showed user-defined entries in ~/.gemini/antigravity-{cli,ide}/hooks.json load as subagents (via invoke_subagent), not as tool-call wrappers. Bash invocations go through Step_RunCommand and bypass the user-visible PreToolHook pipeline entirely. The full investigation lives at docs/development/antigravity-hooks-research.md.

Update (agy 1.4.12). “Rules-only” is stale for the CLI: it now has its own hooks.json with decision/overwrite replies. trs does not use it yet (TASK_TODO P3); until then the rules file stays the integration.

Detection:

Attribution: (untagged) in trs stats --by-agent. The hook never fires programmatically, so there is no TRS_AGENT signal to attach. Manual prefixes (trs git status typed by the agent or user) also land in (untagged). Same posture as Codex/Windsurf.

Migration cleanup. trs init and trs uninstall both sweep:

Re-enable plan. When Google ships user-configurable PreToolHook for Bash, restoring the programmatic integration is a mechanical revert of branch fix/antigravity-rules-only-revert. See the research doc for the exact checklist.

Quirks:

Windsurf

   
Type Rules file
Config .windsurfrules (project root)
Template WINDSURF_RULES

Windsurf Cascade has no pre-execution hook: rules-based voluntary adoption only (like Codex’s fallback on older builds).

Grok Build

   
Type Output-saver only; the hook never rewrites for Grok, on purpose
Config $GROK_HOME/AGENTS.md (default ~/.grok/AGENTS.md)

Grok has a Claude-shaped PreToolUse hook in ~/.grok/hooks/*.json, and a rewrite does apply, but on grok 1.0.70 trs must not install one:

[compat.claude] hooks defaults to true, so Grok also runs the trs hook installed for Claude Code. Before #215 that hook omitted description, Grok’s schema refused the rewrite, and every rewritable command failed. After #215 the rewrite applied and deny rules stopped firing. So rewrite_gate.rs has a grok row that tells it apart by tool_name (run_terminal_command) and never rewrites; with it the deny rule fires again. Unchecked: a Cursor hook reaching Grok through [compat.cursor], since an explicit --caller skips the tool-name lookup.

Permissions per agent

Most agents match their permission rules against the command after the rewrite, so git push becomes TRS_AGENT=x trs git push and a user’s deny: git push or allow: git status stops matching. A hook allow can also skip the rules entirely. Each agent therefore has a gate (src/rewrite_gate.rs, one src/rewrite_perm_<agent>.rs per host) that reads the user’s rules and applies them to the original command. Outcomes: Skip (no rewrite, the agent handles the original), Allow (rewrite and approve), Defer (rewrite, no decision, the agent’s own prompt applies). Every gate fails closed: an unreadable or unknown rule file means Skip, and a project’s allow counts only when the folder is trusted (deny/ask always count).

Agent Rules read Gate result Unverified
Claude Code settings{,.local}.json, managed Skip / Allow / Defer --settings rules invisible
Codex $CODEX_HOME/rules/*.rules, trusted .codex/rules Skip on any matching rule, else Allow (Codex needs the allow for updatedInput) managed requirements.toml, --ignore-rules
Factory Droid commandAllowlist/Denylist/Blocklist in ~/.factory, project settings, the managed settings.json and the cached org settings Skip on deny/block, Allow if all parts listed, Defer only in auto-high, else Skip; permissionRules (version 1): ask/block skip, allow approves (a project’s allow is ignored); FACTORY_RUNTIME_SETTINGS_PATH overlay read --settings flag overlays
Gemini CLI settings.json, policies/*.toml, trusted project settings never Allow (Gemini ignores a hook allow); Skip on deny/ask, narrow tools.allowed, or read-only commands system settings, admin policies, -y
Devin CLI ~/.config/devin/config.json, .devin/config{,.local}.json Skip on deny/ask, Allow if all parts match Exec(...), else Defer org rules, dangerous mode, trust
Cursor Shell(...) deny rules in $CURSOR_CONFIG_DIR or ~/.cursor/cli-config.json, and a project’s .cursor/cli.json (read, not verified live) Skip on deny, else rewrite with no decision (a hook allow never approves nor beats a deny) ask rules (no effect seen)
Copilot CLI / VS Code none readable no allow is sent; --deny-tool flags and VS Code auto-approve settings are invisible flags
OpenCode 2.x permission.bash via ctx.permission.assert plugin asks about the original segments (trs rewrite --json, rewrite and segments in one spawn) before rewriting 1.x config shape
Kilo / OpenCode 1.x client.config.get() rewrite only if no ask/deny rule for bash  
Pi none (no permission engine) rewrite lives only in the bash spawnHook; never mutate event.input so user gates see the original  
Antigravity n/a rules file only; agy 1.4.12 has its own hooks.json with decision/overwrite, unused by trs  

Notes:

Test prompts

Hook-based / plugin-based agents

Estoy validando el hook de trs en este entorno. Ejecuta los comandos
abajo usando tu tool de shell. Pega outputs literales.

CRITICO: Si no tienes acceso a shell, di "no tengo shell" en lugar de
inventar. Si ejecutas algo, no parafrasees, copy-paste literal.

1. `trs --version`
2. `git status`
3. `trs stats --history 2>&1 | tail -5`

Despues responde en 1 frase:
- Que tool usaste para ejecutar los comandos
- Que sabes de trs por tu contexto actual

Pass criteria:

Rules-based agents (Codex, Antigravity, Windsurf)

Tu archivo de instrucciones (AGENTS.md / .windsurfrules /
.agent/rules/) debe mencionar `trs`. Haz estos 3 tests sin inventar:

1. AWARENESS: Antes de ejecutar nada: ¿que sabes de trs por tu
   contexto actual? Una frase.

2. TOOL CHECK: Ejecuta `trs --version` y pega el output literal.

3. VOLUNTARY USE: Necesito ver el estado del repositorio git,
   minimizando consumo de tokens. NO ejecutes todavia. ESCRIBE el
   comando que usarias y explica por que.

Pass criteria:

Debugging a broken integration

If a hook/plugin is installed but commands pass through unchanged, use a debug wrapper instead of trusting the agent’s self-report:

# 1. Create a logging wrapper
cat > /tmp/trs-hook-debug.sh <<'EOF'
#!/bin/bash
LOG=/tmp/trs-hook-debug.log
TS=$(date '+%H:%M:%S')
INPUT=$(cat)
echo "[$TS] >>> STDIN: $INPUT" >> $LOG
OUTPUT=$(echo "$INPUT" | /path/to/trs rewrite)
echo "[$TS] <<< STDOUT: $OUTPUT" >> $LOG
echo "$OUTPUT"
EOF
chmod +x /tmp/trs-hook-debug.sh

# 2. Point the agent's hook at the wrapper (back up first)
# cp ~/.xyz/settings.json ~/.xyz/settings.json.bak
# edit the config to replace `trs rewrite` with `/tmp/trs-hook-debug.sh`

# 3. Reproduce the failure in the agent (full quit + restart first)

# 4. Inspect
cat /tmp/trs-hook-debug.log

The log tells you:

Adding a new agent

  1. Classify: hook, plugin, or rules? Read the agent’s hook/plugin docs BEFORE writing anything. Cursor’s and Gemini’s formats both looked Claude-compatible at first glance and weren’t.
  2. Find the rewrite path: does the agent support updated_input or equivalent? If only allow/deny, it can’t be a hook integration.
  3. Find the wire identifier: hook_event_name, tool_name, or a header field the agent includes in its stdin payload.
  4. Write the template in src/init_templates.rs. Don’t copy another agent’s template verbatim, the matcher field and tool name must match THIS agent’s conventions.
  5. Add a dispatch arm in src/rewrite.rs::HookEvent::parse if the output envelope differs from existing clients.
  6. Add the install spec in src/init.rs::spec() with correct global_dir (often .config/<agent>/<subdir>).
  7. Test with the debug wrapper before declaring success. Self-reports from the agent can hallucinate.
  8. Document here: add an entry to the per-agent table.

What the hook refuses to rewrite

The hook wraps a command by manipulating its text. That is only sound when the string really is one flat command, so rewrite_decide::is_simple_command bails out on everything else. Each rule below exists because the alternative was observed in the field, and every one of them failed silently or fatally, never loudly:

Shape What wrapping did
newline (multi-line script) Two statements collapsed into one: V=abc + printf "$V" became V=abc trs printf "$V", where the shell expands $V before the command-scoped assignment applies. Non-exported values vanished; exported ones survived, which made it look intermittent.
heredoc (<<) The body is data, not commands, yet ` && ` inside it was substituted, so the injected text landed in the written file. In one report it reached main and corrupted a security test whose grep then read compressed output.
quoted operators git commit -m "fix a && b" had its message rewritten; grep -r "foo && bar" had its pattern rewritten, so the search silently looked for something else and returned “not found”.
array literal (arr=(…)) The env-prefix split walks by whitespace and landed inside the parens, inserting a phantom element: [uno][trs][dos]. No error, no exit code, corrupt data that downstream loops iterate over.
compound keywords, ( ), { }, f() {} trs for f in … makes the shell read for as a program and do as a syntax error: the command dies outright.
; sequences Independent commands, same problem as newlines.
assignment heading a && chain S=x && rm -rf $S/* became S=x trs && ...: S went to trs’s environment, $S expanded empty and the shell ran rm -rf /* (2026-11-29, fixed in 0.10.5).

Behind the shape gate, src/rewrite_guard.rs holds three rules (why: the 2026-11-29 incident):

rewrite_guard_tests.rs runs each rewrite, and the agent-tagged command the agent really gets, next to its original under sh -u (and zsh -f when present) and compares output, status and the files left behind.

Besides those rules and the shape gate, a short prefix list (cat, head) skips commands not worth wrapping. A shape that looks exempt may simply be unparseable: check the gate, the rules and the prefixes before concluding.

Escape hatch for anything the gate lets through: TRS_SKIP=1 <cmd>. It does not work in front of shell keywords or (/{, an env prefix there is itself a syntax error; wrap those as TRS_SKIP=1 sh -c "…".