Skip to content

docs(guide): add a guide for embedding rtk in a custom agent harness - #3918

Merged
KuSh merged 5 commits into
rtk-ai:developfrom
zerone0x:docs/embedding-guide
Nov 16, 2026
Merged

KuSh merged 5 commits into
rtk-ai:developfrom
zerone0x:docs/embedding-guide

Conversation

@zerone0x

@zerone0x zerone0x commented Sep 7, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Adds docs/guide/getting-started/embedding.md, a one-page guide for hosts that call rtk rewrite from their own bash tool instead of installing one of the shipped hooks. Nothing in docs/ covered that case; the shipped hooks are the only worked examples and each is tied to one agent's JSON format.
  • Documents the rtk rewrite exit-code contract as a non-Claude-Code host sees it. Outside Claude Code no settings files exist, PermissionVerdict::Default maps to exit 3, so exit 3 is the ordinary answer for every rewritable command. A host that treats 3 as anything but 0 has RTK silently switched off. That trap is the reason the page exists.
  • Covers call ordering (after the host's own approval gate, before the shell is spawned), the fail-open rules with hooks/pi/rtk.ts as the reference implementation, a minimal Python sketch, per-invocation RTK_DB_PATH accounting with the verified rtk gain --format json field names, RTK_TELEMETRY_DISABLED=1 for sandboxes, rtk proxy and [hooks] exclude_commands, and links to the savings caveat instead of restating it.
  • Cross-links the page from the "Integration tiers explained" section of supported-agents.md. Sidebar order 5 in the frontmatter, matching the other getting-started pages.
  • The RTK_DISABLED note is written to stay true once feat(rewrite): honour RTK_DISABLED=1 from the environment #3917 (honour the exported variable in rtk rewrite) lands: it tells the host to check the variable itself, states that releases up to 0.48.0 honour it only as an in-command prefix, and links feat(rewrite): honour RTK_DISABLED=1 from the environment #3917.
  • Version floor, for the maintainers to decide. The page says rtk rewrite needs 0.25.0. The release history agrees on three independent lines: the rewrite command file (src/rewrite_cmd.rs at the time, src/hooks/rewrite_cmd.rs since 46fa31c) is absent at v0.23.0 and v0.24.0 and present at v0.25.0 (GitHub contents API); commit f447a3d, feat: rtk rewrite — single source of truth for LLM hook rewrites (#241) of 2026-03-05, is not an ancestor of v0.24.0 and is first contained in v0.25.0; and CHANGELOG.md lists rtk rewrite under 0.25.0 (2026-03-05). The v0.23.0 and v0.24.0 release binaries answer rtk rewrite "git status" with exit 2 and empty stdout. The 0.23.0 floor in hooks/pi/rtk.ts (header comment and MIN_SUPPORTED_RTK_MINOR), hooks/claude/rtk-rewrite.sh, hooks/cursor/rtk-rewrite.sh, hooks/README.md, hooks/claude/README.md and hooks/cursor/README.md is therefore inconsistent with the release history. This PR leaves those files alone. Either floor is safe for a fail-open host, and the page says so.

Test plan

  • Ran every command on the page against rtk 0.48.0 with RTK_DB_PATH pointed at a scratch directory and RTK_TELEMETRY_DISABLED=1: rtk rewrite "git status" prints rtk git status and exits 3; htop, a redirect, and an RTK_DISABLED=1 prefix exit 1 with empty stdout; a compound command rewrites both sides; an already-prefixed command comes back unchanged.
  • Simulated allow, deny, ask and no-rule verdicts with a temporary HOME holding a .claude/settings.json: exit 0, 2, 3, 3 as documented. A [hooks] exclude_commands entry in a temporary config.toml makes the excluded command exit 1.
  • rtk gain --format json against a path that does not exist creates it and returns zeros; after one rtk git status the summary object holds exactly the seven fields listed on the page; rtk proxy is tracked at zero savings; no sidecar files are left behind, so deleting the one file is enough. A missing parent directory and an empty pre-created file both work.
  • Executed the Python sketch from the page against the real binary, an empty PATH, a 1.5 MB argument (E2BIG), and the v0.23.0 and v0.24.0 release binaries: every failure path returns the original command.
  • Cross-checked the version floor three ways: the GitHub contents API for the rewrite command file at v0.23.0, v0.24.0 and v0.25.0; git log --diff-filter=A --follow plus git merge-base --is-ancestor and git tag --contains on a full clone; and the CHANGELOG.md entry. All three give 0.25.0.
  • Checked that every relative link and anchor in the new page resolves and that the two linked source files exist on master.

Hosts that call `rtk rewrite` from their own bash tool had no page to
read, and the exit-3 default outside Claude Code is easy to get wrong.
Covers the exit-code contract, call ordering, fail-open rules,
per-invocation RTK_DB_PATH accounting, telemetry, proxy and exclusions,
and links the savings caveat. Cross-linked from supported-agents.md.
…tk-ai#3917

Tell the host to check RTK_DISABLED itself before spawning `rtk rewrite`,
state that releases up to 0.48.0 honor it only as an in-command prefix,
and link rtk-ai#3917, which makes `rtk rewrite` honor the exported
variable too. The note stays true before and after that PR lands.
Say which integrations delegate to `rtk rewrite` and which Rust-binary
hooks run the registry in-process; narrow the passthrough sentence to
file redirects and command substitution (a pipe rewrites its consumer,
`2>&1` does not block the rewrite); point the JSON field names at
`ExportSummary` in src/analytics/gain.rs.
@ismoss

ismoss commented Nov 2, 2026

Copy link
Copy Markdown

Adding the one rule my closed #4841 had that this guide does not, since @KuSh asked for it to land here. Suggestion only — edit or drop it freely.

The gap. The guide covers where the call goes and how to fail open, but not what a host should do with a rewrite it cannot show the user. If your transcript, audit log or permission prompt displays the command the model asked for — which is the normal case when the rewrite happens below that layer — then the text that actually runs differs from the audited text. Minding that difference is the host's job, and it is cheap to do.

Proposed section, fitting after "Where the call goes" and before "Fail open":

Reject rewrites that are not pure insertions

rtk rewrite is a black box from the host's side: the output is whatever RTK's registry decided, and nothing in the exit-code contract promises that the only difference is an inserted rtk token. A host that cannot display the substituted command should verify it before spawning:

  • tokenize both strings on shell operators only (&&, ||, |, ;, &), keeping quoted spans — quotes included — as single tokens;
  • walk the rewritten tokens against the original left to right, preferring a literal match at each position, so an argument that is itself rtk (git log --grep rtk) is matched as data, not mistaken for an inserted prefix;
  • every unmatched rewritten token must be exactly rtk or rtk.exe;
  • the walk must consume the original exactly — no dropped, added or requoted token.

When the check fails, run the original command. On rtk 1.1.0 nothing we rewrote needed it: git diff, gh pr list, cargo test, kubectl get pods, docker ps, dotnet build, rg foo ., git log -n 3 all came back with a pure rtk prefix. That is the point — the guard costs nothing while the registry behaves, and it is the only thing standing between a registry change and a host silently running a command it never audited.

Reference implementation with the negative cases as tests: ismoss/dsh-rtk — isPrefixInsertion in lib/index.js, and test/invariant.test.mjs, which asserts that a dropped argument, an added argument, split quotes, an injected pipeline, a truncated command and an appended second command are all refused.

Happy to send this as a patch against the branch if that is easier than applying it by hand.

Some registry rules rename or reorder (cat -> rtk read, python -m pytest
-> rtk pytest, yadm -> rtk git). Describe a pure-insertion check for hosts
that audit only the original command, as suggested in review.
@zerone0x

zerone0x commented Nov 2, 2026 •

Copy link
Copy Markdown
Contributor Author

Added a section "Rewrites that are more than a prefix" between "Where the call goes" and "Fail open", based on the pure-insertion check suggested by @ismoss (thanks). It links ismoss/dsh-rtk as an external example.

Changes from the proposed text, after checking against rtk 1.1.0 and develop:

  • Some rewrites are not a pure rtk prefix: cat foo.txt becomes rtk read foo.txt, head -n 5 foo.txt becomes rtk read foo.txt --head-lines 5, python -m pytest -x becomes rtk pytest -x, npm run lint becomes rtk lint, and yadm status becomes rtk git status. The section lists these and says the check runs them unfiltered.
  • The check is described as optional, for hosts whose audit or prompt shows only the original command.
  • Dropped rtk.exe, because every registry rule emits a literal rtk.

New head: 2fa9cbc

@zerone0x
zerone0x force-pushed the docs/embedding-guide branch from 64e6546 to 2fa9cbc Compare November 2, 2026 14:50
- Call `rtk rewrite -- "<command>"`: without `--`, a command string such
  as `--help` or `-h` makes rtk print its own help on stdout with exit 0,
  and the sketch handed that text back as the command to run.
- The sketch now caches its version probe, checks `RTK_DISABLED` and
  `rtk_ready()` before spawning, and fails open on `ValueError` (an
  embedded NUL), as the page's own rules ask.
- `rtk gain --format json` has carried `oversized_excluded` since 1.0.0;
  a command above the 30,000-byte cap only increments it, so a
  per-command database reads all zeros for a large output.
- The exit-code table names partial allow rules, shell wrappers and an
  unparseable settings file (exit 3), a deny inside a wrapper's script
  (exit 1) and an inherited `RTK_REWRITE_HOST`; the settings paths
  follow the nearest `.claude/` and `$CLAUDE_CONFIG_DIR`.
- OpenCode now runs `rtk hook opencode`, not `rtk rewrite`; the Hermes
  plugin's timeout is 5 s; `rtk bypass` is the escape hatch's name since
  1.0.0; Linux caps a single argument at 32 pages; the
  `exclude_commands` example uses commands rtk rewrites.
- Version references move to 1.2.0, against which every row was rerun.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

@KuSh KuSh left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Round 1 of 3 — APPROVED, follow-ups filed

Claim: a new guide page for hosts that call rtk rewrite from their own bash tool: the exit-code contract, where the call goes, fail-open rules, a Python sketch and per-invocation accounting.
Scope: accept (round 1, frozen); maintainer PRs: checked against #4153, #4458, #4909 (with #4894), #5021, #5022, #5041, #5100 and the #4315 stack up to #5112. Every row on the page gives the same answer on each of them (#5112 only adds warning: to the RTK_DISABLED=1 detected line), and #3875 and #4653, the two that also touch supported-agents.md, merge clean with this PR.
Ran: every command on the page against rtk 1.2.0 and develop, in a scratch HOME with LC_ALL=C: the four exit codes with settings files in each location, compound, redirect, $(…) and 2>&1 forms, the prefix and rename tables, RTK_DISABLED as prefix and exported, exclude_commands, the stderr notices, timing (13–15 ms per call). Accounting: RTK_DB_PATH on a missing path, a missing parent dir, an empty pre-created file, precedence over tracking.database_path, sidecar files, rtk bypass/rtk proxy, and one output above the 30,000-byte cap. The Python sketch ran on 13 inputs: the real binary, a missing binary, a 200 KB argument, a hanging and a crashing stand-in, --help, -h, an embedded NUL, RTK_DISABLED=1 exported. Invariants: under the hook (the page is rtk rewrite itself) | over-cap + accounting | split streams (stderr notices kept apart) | every decision (exit 0, 1, 2, 3 each reached); savings: n/a (docs).
Pins: 0 code decisions (docs only). The fixup's 4 sketch decisions were each executed before and after.
Matrix: executed this round; pin check: executed this round (nothing to mutate)
CI @61de0133: all green (16/16)

Blocks merge (0)

Nothing blocks. The page was written against 0.48.0, and a few statements drifted with 1.0.0–1.2.0. I pushed one docs commit that brings it in line rather than sending it back to you:

  • Accounting. Since 1.0.0, rtk gain --format json has carried an eighth field, oversized_excluded. Any command whose raw output is above 7,500 estimated tokens (30,000 bytes) is left out of every total and only counted there. In the one-database-per-command recipe, rtk grep 1 big.txt (108,894 bytes → 177) reads "total_commands": 0, "total_saved": 0, "oversized_excluded": 1. A host following the page would record zero for its largest outputs. The page now lists the field and says to check it before recording a zero.
  • rtk rewrite -- "<command>". Without --, an agent command of --help or -h makes rtk rewrite print its own help on stdout with exit 0, and the sketch returned that 1789-character text as the command to spawn. With --, the same input gives exit 1 and real commands are unchanged (1.1.0, 1.2.0, develop).
  • Sketch. It now caches rtk_ready(), calls it, and checks RTK_DISABLED before spawning, as the page's text asks. It also catches ValueError: an embedded NUL used to raise out of rewrite(). On every one of the 13 inputs the new sketch returns either the rewrite or the original.
  • Exit-code table. It now covers allow rules that cover only part of a command (exit 3), a shell wrapper (3), an unparseable settings file (3), a deny inside a bash -c script (1), an inherited RTK_REWRITE_HOST=openclaw (3 becomes 0), and which settings files are read (the nearest .claude/, plus ~/.claude or $CLAUDE_CONFIG_DIR).
  • Smaller corrections.
    • OpenCode now runs rtk hook opencode (in-process) rather than rtk rewrite.
    • The Hermes plugin's timeout is 5 s.
    • rtk proxy has been rtk bypass since 1.0.0.
    • oversized_excluded and the Linux single-argument limit (32 pages) are stated.
    • The exclude_commands example now uses commands rtk does rewrite: git rebase and git cherry-pick already exit 1 with no config.
    • Version references move to 1.2.0, against which every row was rerun.

Optional — will not hold merge

  • The pure-insertion check accepts exactly what it describes, pure insertions. That includes an rtk inserted as an argument (git log --grep → git log --grep rtk) and a newline turned into a space, if newlines are split as whitespace. If you want it stricter, the check would keep operators and newlines as tokens and require each inserted rtk to start a command segment (after VAR=value). On 1.2.0 that would also leave unfiltered the rewrites rtk makes behind a wrapper: timeout 5 git status → timeout 5 rtk git status, and likewise env, nice, nohup, time, command, exec. Your call, with @ismoss.

Filed as follow-ups

  • #5126 hooks: version floor says rtk rewrite came in 0.23.0; it came in 0.25.0. Outside this PR's hunks, filed.
  • #5127 delegates call rtk rewrite <cmd> without --, so --help/-h comes back as help text with exit 0 (Pi, Hermes, OpenClaw, the shell hooks). Outside this PR's hunks, filed.

Checked and correct — no need to re-verify

The four exit codes and the stdout they carry; no trailing newline; an already-prefixed command comes back unchanged with exit 3; redirect and $(…) give exit 1, 2>&1 does not; compound commands; every row of the rename table on 1.2.0; rtk rewrite creates no tracking database; RTK_DB_PATH creates a missing parent, works on an empty pre-created file, beats tracking.database_path, and leaves no -wal/-shm sidecar; rtk bypass is tracked at zero savings; RTK_TELEMETRY_DISABLED is the variable the code reads; rtk rewrite first shipped in 0.25.0 (f447a3d is in v0.25.0 and not in v0.24.0); all relative links and anchors resolve; sidebar order 5 is free.

Your questions

  • "Version floor, for the maintainers to decide." → The page's 0.25.0 is right. The 0.23.0 in the Pi extension and the legacy shell hooks is the inaccurate one, and it is harmless because they fail open. Fixing those files is #5126, not this PR.

Next

fixup 61de013 pushed, code-reviewed: docs only, brings the page in line with rtk 1.2.0 (accounting, --, sketch, exit table, delegate details) — approving.
Rounds: 1/3. Threads: 0 open, 0 resolved this round.

@KuSh
KuSh merged commit 8bb6096 into rtk-ai:develop Nov 16, 2026
16 checks passed
@rtk-release-bot rtk-release-bot Bot mentioned this pull request Nov 16, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants