Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Introduction

Retake records real LLM API exchanges into “take” files and replays them deterministically in tests, for any language or SDK.

Tests of LLM agents that call a live API are flaky (the model answers differently from run to run), slow, cost money on every run, and need an API key wherever they run, including CI. Retake runs your test command once against the real API and records every request and response. After that, the same command replays from the recording: no network, no API key, and the same responses every time.

Secrets matching a configured pattern are redacted before any byte is written to disk. Content Retake cannot scan is never written unless you opt in with --allow-unscanned. See Redaction.

Retake is at 0.1. It supports the Anthropic Messages API on macOS and Linux. The take format may still change before 1.0; when it does, retake upgrade rewrites existing takes in the new format. See Status for what is supported, and Installation.

Status

Supported today:

  • retake record and retake replay wrapping any command, with one take per run (_main.take) in --takes-dir (default tests/takes).
  • With the pytest plugin, one take per test case, _session.take for requests outside tests, failed tests keeping their previous take, and replay failing tests that leave exchanges unused.
  • The Anthropic Messages API, including streamed (server-sent event) responses, with replay pacing selected by --pacing.
  • Content matching with mismatch descriptions, and the header allow-list.
  • Normalization rules: selectors, built-ins, user rules in retake.toml, the guard, and match counts in the summary.
  • Redaction: built-in and user patterns, consistent placeholders, the stream window, the final scan, and withholding unscannable content.
  • Binary content: hash-only parts, blob files for opted-in content, relaxed media rules, decoded text inside base64, decompressed responses and multipart uploads.
  • Refusing or dropping account and transient errors while recording.
  • Detecting test takes that depend on IDs from _session.take, finalizing such runs at the end, retake finalize after a crash, retake clean and retake init.
  • resource records for uploaded files and message batches, the leftover list in the recording summary, _resource.take and retake reap.
  • retake check and retake ls (with --json), staleness by Retake version and API version with --fail-on-stale, format versioning with retake upgrade, and JSON Schemas for takes, retake.toml and the --json output.

Not done yet for test-runner plugins: freezing the clock at the recording time during replay, other server-side resource kinds, retake prune / retake mv for renamed tests, plugins for other test runners, and outcomes other than passed, failed and skipped.

Design

The design decisions are recorded as Architecture Decision Records in docs/adr/, covering the take storage model, take granularity and naming, the write lifecycle, stream representation, redaction, the plugin–proxy protocol, replay matching, normalization rules, binary content, metadata and staleness, format versioning and JSON Schemas.

Prior art

The closest existing tool is rig-cassette, part of the Rig project. It is a Rust library for recording and replaying LLM exchanges in Rig’s own test suite. Retake differs in that it wraps any test command and works with any language’s SDK through a local proxy, and it matches requests by content and reports mismatches as readable diffs.

Installation

Retake is one binary, retake. It runs on macOS (Apple Silicon and Intel) and Linux (x86_64 and arm64). Windows is not supported yet: forwarding signals to the wrapped command uses Unix calls.

From crates.io

cargo install --locked retake

This needs Rust 1.88 or later and a C compiler (see From source).

With the pytest plugin (Python)

pip install pytest-retake

pytest-retake depends on retake-cli, a wheel that contains the retake binary, so this installs both and needs no Rust toolchain. pip install retake-cli installs the binary alone. The two packages and Retake share one version number.

Prebuilt binaries

Each GitHub Release has archives for every platform, with checksums, and a shell installer:

curl --proto '=https' --tlsv1.2 -LsSf https://github.com/simdugas/retake/releases/latest/download/retake-installer.sh | sh

The installer puts retake in $CARGO_HOME/bin (~/.cargo/bin). The Linux binaries are statically linked (musl) and run on any distribution.

Homebrew

Each GitHub Release has a Homebrew formula, retake.rb, among its files. There is no Homebrew tap yet, so brew install retake does not find it; you can add the formula to a tap of your own (brew tap-new), or use the shell installer above.

From source

Retake needs Rust 1.88 or later (the minimum supported version, rust-version in Cargo.toml) and a C compiler: the HTTP client uses reqwest’s rustls backend, which depends on aws-lc-rs.

git clone https://github.com/simdugas/retake
cd retake
cargo install --locked --path .
retake --version

To work on Retake itself, see CONTRIBUTING.md, which covers building, the tests and the other checks.

Getting started

The repository includes a small Anthropic agent, examples/refund/main.rs, that uses tools to look up and refund an order, and a take recorded from it, examples/refund/_main.take.

With retake installed, run the commands below from a clone of the repository. cargo run --example refund builds and runs the example, which needs Rust 1.88 or later and a C compiler; the first run downloads and compiles its dependencies.

git clone https://github.com/simdugas/retake
cd retake

Replay (no API key)

env -u ANTHROPIC_API_KEY ANTHROPIC_MODEL=claude-haiku-5-5 \
  retake replay --takes-dir examples/refund -- cargo run -q --example refund

The agent runs as usual, but every API response comes from the take:

> refund half of order 100
> (thinking)
> [get_order {"id":100}]
>  {"id":100,"status":"Arrived","total":8000,"refund":0}
> (thinking)
> [refund_order {"amount":4000,"id":100}]
>  order 100 refunded 4000 cents
> Order 100 has been refunded half its total: $40.00 (4000 cents) of the $80.00 order. It had no prior refunds.
retake: replayed 3 exchange(s) from examples/refund/_main.take
retake: matches: 3 exact, 0 with rules

ANTHROPIC_MODEL must match the recording because the model is part of each request. If a request differs from what was recorded, Retake answers it with an error, explains the difference, and the run exits non-zero. For example, with ANTHROPIC_MODEL=claude-sonnet-5-5:

retake: no recorded response for POST /v1/messages (retake_no_match):
closest recorded exchange is #0 (first 1 of 1 message(s) identical); it differs in:
  body model: recorded "claude-haiku-5-5", request "claude-sonnet-5-5"
...
retake: replay failed: 1 request(s) had no recorded response (1 unmatched, 0 exhausted, 0 withheld)

Record (needs an API key)

ANTHROPIC_API_KEY=... ANTHROPIC_MODEL=claude-haiku-5-5 \
  retake record --takes-dir my-takes -- cargo run -q --example refund

This makes real, billed API calls and writes my-takes/_main.take. Recording over an existing take asks for confirmation on a terminal; elsewhere it needs --yes (or RETAKE_ASSUME_YES=1).

More examples

Next

  • How it works: what record and replay do around your command.
  • pytest: one take per test with the pytest-retake plugin.
  • The take file: what a recording contains.
  • Redaction: what is kept out of takes, and how to add your own patterns.

How it works

retake record -- <cmd> and retake replay -- <cmd> start a local HTTP proxy, then run <cmd> with ANTHROPIC_BASE_URL pointing at it. Anthropic SDKs, and the example agent, read that variable, so the command needs no changes and can be in any language: a test runner, a script, or a binary.

  • Record: the proxy forwards each request to the real API (your ANTHROPIC_BASE_URL if you had one set, else https://api.anthropic.com) and appends the request and response to the take. Streamed ("stream": true) responses reach the command as they arrive, and each event is appended to the take as it completes.
  • Errors while recording: account errors refuse the recording, and transient errors are dropped when a retry succeeds; see Errors while recording.
  • Replay: the proxy never contacts the network. It matches each incoming request against the recorded ones by content (method, path, query, the relevant headers and the JSON body, ignoring key order and whitespace, after normalization rules) and returns the recorded response. A request with no match, or more requests than were recorded, fails the run with a description of the closest recorded exchange. If ANTHROPIC_API_KEY is unset, the command gets a placeholder so SDKs that require a key still start.
  • Streams on replay: recorded events are sent in order. --pacing (or RETAKE_PACING) sets the timing: instant (the default), realtime (at the recorded offsets), or a speed-up factor such as 4. A stream that the client closed during recording ends the same way on replay.
  • Headers: only allow-listed headers are stored. API keys, other authentication headers and cookies are never written to a take. retake.toml can add headers (see Redaction).
  • Test-runner plugins: retake also passes RETAKE_URL and a per-run RETAKE_TOKEN to the command. A plugin (pytest’s is the only one so far) uses them to call control endpoints on the proxy’s port, under /_retake/: hello to agree on a protocol version, then test/begin and test/end (with passed, failed or skipped) around each test. Its requests carry the test ID in an x-retake-test header, so concurrent workers are told apart. Each test’s take is written as <name>.take.partial and renamed when the test passes (at the end of the run when _session.take has dependents). test/end waits for the test’s requests still in flight, up to --inflight-timeout seconds (default 120); requests for a test that has ended are rejected with a 400 of type retake_test_finished and listed in the summary (--fail-on-late-requests fails the run). Until a plugin calls hello, everything goes to _main.take as before.

The exit code is the wrapped command’s, or non-zero when the command succeeded but Retake’s part of the run failed (including a test whose take Retake refused or could not replay). A command that cannot be started at all (not found, or not executable) exits 127 or 126, as in a shell; it made no requests, so retake record writes no take, leaves no .partial, and leaves an existing take unchanged.

pytest: one take per test

python/pytest-retake is a pytest plugin. Under Retake it tells the proxy when each test begins and ends and whether it passed, and attributes each request to its test, so every test case gets its own take. examples/pytest_refund is a pytest suite for a Python version of the refund agent, using the official anthropic SDK: a plain test, a parametrized test, a refused refund and a streamed run.

In your own project, pip install pytest-retake installs the plugin and the retake command (see Installation); then wrap your usual pytest command, e.g. retake replay -- pytest tests/.

To try the example, record it (real, billed API calls) from the root of a clone of the repository. uv run --with installs anthropic, pytest and the plugin from PyPI into a temporary environment; any environment with those three works the same way:

ANTHROPIC_API_KEY=... ANTHROPIC_MODEL=claude-haiku-5-5 \
  retake record --takes-dir examples/pytest_refund/takes \
  -- uv run --with anthropic --with pytest --with pytest-retake \
  pytest examples/pytest_refund
retake: recorded 15 exchange(s) to per-test takes in examples/pytest_refund/takes (...)
retake: 5 test take(s) recorded:
retake:   test_refund.py/test_order_not_arrived.take: recorded 3 exchange(s)
retake:   test_refund.py/test_refund_amount/case-all.take: recorded 3 exchange(s)
retake:   test_refund.py/test_refund_amount/case-quarter.take: recorded 3 exchange(s)
retake:   test_refund.py/test_refund_half.take: recorded 3 exchange(s)
retake:   test_refund.py/test_refund_half_streamed.take: recorded 3 exchange(s)

(The exchange counts depend on what the model does.) Replay it with no key and no network, with the same model:

env -u ANTHROPIC_API_KEY ANTHROPIC_MODEL=claude-haiku-5-5 \
  retake replay --takes-dir examples/pytest_refund/takes \
  -- uv run --with anthropic --with pytest --with pytest-retake \
  pytest examples/pytest_refund

With the plugin:

  • Take names follow the pytest node ID, relative to the takes directory: test_refund.py::test_refund_amount[quarter] is test_refund.py/test_refund_amount/case-quarter.take. IDs with unsafe characters, or too long, get a short hash. @pytest.mark.retake("some/name") sets a name explicitly. The full test ID is in the take’s header.
  • A test that fails while recording leaves its previous take in place; the new recording is discarded. --keep-failed keeps it, marked "outcome":"failed" in the footer, and replay refuses such a take unless --allow-failed is given.
  • A test that passes without making any request while recording has its previous take removed (it would fail replay as unused); the summary lists it as removed.
  • A skipped test (skip, skipif, importorskip, or a skip in the middle of the test) never loses its take: while recording, whatever it recorded is discarded and its previous take kept; on replay, its take is not checked for unused exchanges.
  • On replay, a test that leaves recorded exchanges unused fails (it made fewer calls than were recorded), as does a test with no take.
  • Requests made outside a test (session- or module-scoped fixtures, imports) go to _session.take, which every recording run replaces. Tests that use IDs from it are re-recorded together; see below.
  • Without Retake (RETAKE_URL unset) the plugin does nothing and warns once; RETAKE_REQUIRED=1 makes that an error, e.g. in CI.

The plugin attaches the test ID by wrapping httpx2 and httpx (which the anthropic SDK uses); see its README for how this works and its limits.

Session IDs and dependent takes

A session fixture that creates something on the provider (a file, a stored response, a message whose ID later requests refer to) gets a new ID on every recording run. A test take whose requests contain an ID from the current _session.take is a dependent: if _session.take is re-recorded without it, the old take refers to an ID the new _session.take no longer serves.

What counts as an ID: a whole JSON string value in a _session.take response (full bodies and stream events; not object keys) shaped like a provider ID, i.e. 2 to 20 lowercase letters, _ or -, then at least 16 letters and digits with at least one of each (msg_01XFDUDYJgAACzvnptvVoYEL, file_011CNha8iCJcU1wXNR6q4V8w, chatcmpl-AbC123...), or a UUID. Model names, stop reasons and other words never match. A test take is a dependent when any of its requests contains such an ID anywhere in the path, query or body.

When _session.take has dependents, a recording run:

  • lists them at the start and asks for confirmation; headless runs (no TTY) refuse unless --yes or RETAKE_ASSUME_YES=1 is given;
  • writes every take to <name>.take.partial as usual, but renames them all at the end of the run instead of when each test passes;
  • renames them only if _session.take and every dependent were re-recorded (ran and passed). Otherwise it renames none, keeps every previous take unchanged, fails, and lists the tests that must be included:
retake: end-of-run finalization refused: 2 take(s) use IDs from the previous _session.take; no take was finalized and the previous takes are unchanged
retake: re-record them in one run; these tests must be included (1 missing):
retake:   tests/test_suite.py::test_b (tests/test_suite.py/test_b.take): not run
retake: the new recordings stay as .partial files; `retake clean` removes them

When all of them were re-recorded, the summary ends with finalized 4 take(s) at the end of the run (2 dependent(s) of _session.take re-recorded).

If Retake itself dies during such a run (killed, machine lost), nothing is renamed. retake finalize --takes-dir <dir> performs the end-of-run step on what the run left: it completes _session.take.partial (dropping a cut-off last line and adding a footer with "run_exit": null, since the run never exited; replay warns that the recording run did not finish, as it does for a non-zero exit), then renames every finished .partial that run wrote, if every dependent is among them. Unfinished .partial files (tests that never ended, refused recordings) and ones from earlier runs are left in place and listed. A passing test that made no requests in the crashed run keeps its previous take, since its removal was only pending in memory.

Leftover .partial files

A crash, a refused recording, or a refused end-of-run finalization leaves .partial files next to the takes. They are never replayed. retake clean --takes-dir <dir> lists and removes every *.take.partial under the takes directory; --dry-run only lists them. retake init adds *.take.partial and _resource.take to .gitignore in the current directory, and marks the takes directory’s blob files as binary in .gitattributes (tests/takes/_blobs/** binary, following --takes-dir), creating either file if needed; running it again changes nothing.

retake clean also removes blob files in _blobs/ that no take refers to (see Blobs); --dry-run lists them. If a take cannot be read, no blob is removed, since it could refer to any of them.

retake clean only deletes local files. Resources a removed .partial created on the provider are first copied to _resource.take, so retake reap can still delete them.

The take file

A take is a JSON Lines file, one record per line:

  • a header with the format version, the test ID, when it was recorded and the version of Retake that recorded it (takes recorded before Retake wrote its version lack it);
  • for each exchange, a request record (method, path, allow-listed headers, JSON body) and a response record (status, allow-listed headers, body). A streamed response has no body: it is followed by one event record per server-sent event (event name, id, data, and a millisecond offset) and a stream_end record saying how the stream ended;
  • a resource record after an exchange that created or deleted an uploaded file or a message batch (see Server-side resources);
  • a footer with the wrapped command’s exit code. A take without a footer is incomplete, and replay refuses it.

Content stored with --allow-unscanned lives in blob files next to the takes, in _blobs/ (see Blobs), so a take that uses them is no longer a single file. Secrets in any record are replaced by placeholders such as <redacted:anthropic-api-key:1> (see Redaction). Nothing else is recorded about the machine, the user, the repository or the SDK; the models are in the request and response bodies.

Every record is described by the JSON Schema schema/take-v1.schema.json; the rules across lines (header first, footer last, consistent exchange numbers) are in schema/README.md.

Abridged, from examples/refund/_main.take:

{"type":"header","format":1,"test_id":"_main","recorded_at":"2026-12-04T16:08:38.386Z"}
{"type":"request","exchange":0,"provider":"anthropic","method":"POST","path":"/v1/messages","headers":[["anthropic-version","2026-10-21"],["content-type","application/json"],["accept","*/*"]],"body":{"max_tokens":1024,"messages":[...],"model":"claude-haiku-5-5","tools":[...]}}
{"type":"response","exchange":0,"status":200,"headers":[["content-type","application/json"],["request-id","req_..."]],"body":{...}}
...
{"type":"footer","run_exit":0}

Streaming

examples/refund_stream/main.rs does the same task with "stream": true: it reads the server-sent events itself, prints text as it arrives, and rebuilds each assistant message from the events. Its take, examples/refund_stream/_main.take, holds one event record per event. Replay serves the events instantly by default; --pacing realtime serves them at the recorded offsets, so the text appears at the speed it was generated:

env -u ANTHROPIC_API_KEY ANTHROPIC_MODEL=claude-haiku-5-5 \
  retake replay --pacing realtime --takes-dir examples/refund_stream \
  -- cargo run -q --example refund_stream

Replay pacing

Recorded events are sent in order. --pacing (or RETAKE_PACING) sets the timing: instant (the default), realtime (at the recorded offsets), or a speed-up factor such as 4. A stream that the client closed during recording ends the same way on replay.

While recording, streamed ("stream": true) responses reach the command as they arrive, and each event is appended to the take as it completes. How a secret split across events is redacted is described in Redaction: Streams.

Errors while recording

An account error (401, 402, 403) refuses the recording. A transient error (429, any 5xx, a stream the provider cut off, or a request that failed to reach the provider, which the client sees as a 502) is dropped from the take if the same request is then retried successfully, and refuses the recording otherwise. A refused recording leaves the previous take in place and exits non-zero; its new recording stays as <name>.take.partial, without a footer, for debugging (the summary names it), unless the final scan finds a secret in it, in which case it is deleted. Refusal is decided when the test or run ends; the run is never stopped early. --allow-errors keeps every response as recorded. Other errors, such as 400, are always kept.

Response while recordingDefaultWith --allow-errors
401, 402, 403 (account)Refuses the recordingKept
429, any 5xx, a cut-off stream, a failed connection (502), then a successful retryDropped; the retry is keptKept
The same, never retried successfullyRefuses the recordingKept
Other errors, such as 400KeptKept

--allow-errors (RETAKE_ALLOW_ERRORS) applies to the whole run. With the pytest plugin, @pytest.mark.retake(expect_errors=[429]) keeps the listed statuses for one test; see the plugin’s README.

Dropped and refused exchanges are listed in the recording summary. A refused recording’s .partial file can be removed with retake clean; see Leftover .partial files.

Redaction

Secrets matching a configured pattern are redacted before any byte is written to disk. Content Retake cannot scan is never written unless you opt in with --allow-unscanned.

What is redacted, in every record before it is appended to the take (.partial files included): the request path and query, the values of allow-listed request and response headers, request and response bodies (every JSON string, object keys included, and non-JSON text), and stream events.

Placeholders

A secret becomes <redacted:NAME:N>, where NAME is the pattern’s name and N counts distinct values of that pattern in the take: the same value always gets the same placeholder within a take. Placeholders contain no quotes or backslashes, so they are safe inside JSON strings and JSON fragments, and nothing in them is derived from the secret. A placeholder written into a take is never matched again.

On replay the client sends the real secret again. Retake redacts the incoming request the same way and renumbers placeholders on both sides by first appearance within the request (object keys in sorted order), then compares. What a secret was does not matter for matching; which values are equal does: a request that uses one key where the recording used two different ones does not match. Mismatch descriptions only ever show placeholders.

Abridged, a request that sent a key and a streamed reply that echoed it across three events (the key’s remainder trimmed from the second and third):

{"type":"request","exchange":0,...,"body":{"messages":[{"content":"my key is <redacted:anthropic-api-key:1>","role":"user"}],...}}
{"type":"event","exchange":0,"offset_ms":3,"event":"content_block_delta","data":{"delta":{"text":"Key: <redacted:anthropic-api-key:1>","type":"text_delta"},"index":0,"type":"content_block_delta"}}
{"type":"event","exchange":0,"offset_ms":3,"event":"content_block_delta","data":{"delta":{"text":"","type":"text_delta"},"index":0,"type":"content_block_delta"}}
{"type":"event","exchange":0,"offset_ms":4,"event":"content_block_delta","data":{"delta":{"text":" done","type":"text_delta"},"index":0,"type":"content_block_delta"}}

Built-in patterns

On by default. Each starts with a fixed, distinctive prefix, so ordinary prompt text does not trigger them.

NameMatches
anthropic-api-keyAnthropic API and admin keys (sk-ant-api03-…, sk-ant-admin01-…)
openai-api-keyOpenAI sk-proj-, sk-svcacct-, sk-admin- keys, and legacy 48-character sk- keys
aws-access-key-idAWS access key IDs (AKIA…, ASIA…, ABIA…, ACCA…, 20 characters)
github-tokenGitHub tokens (ghp_, gho_, ghu_, ghs_, ghr_, github_pat_)
slack-tokenSlack tokens (xoxb-, xoxp-, xoxa-, xoxo-, xoxs-, xoxr-)
google-api-keyGoogle API keys (AIza…, 39 characters)
pem-private-keyPEM private key blocks from BEGIN to END (RSA, EC, OpenSSH, PKCS#8, encrypted), up to 6 KiB, with real newlines or \n escapes
retake-tokenThe run’s own RETAKE_TOKEN; always on

AWS secret access keys, passwords, and personal data have no reliable format; add your own patterns for them.

retake.toml

Read from the current directory, or from --config FILE / RETAKE_CONFIG. Every key is optional; unknown keys are an error. Its JSON Schema is schema/retake-toml.schema.json (see Editor support).

[redact]
builtins = true                      # false turns every built-in pattern off
disable  = ["google-api-key"]        # or turn some off by name

[[redact.patterns]]
name    = "employee-id"              # a-z, 0-9 and `-`; used in the placeholder
regex   = 'EMP-[0-9]{6}'             # Rust `regex` syntax
# max_len = 64                       # bytes; required when the regex is unbounded

[headers]
request  = [{ name = "x-tenant", match = true }]   # `match` is required
response = [{ name = "x-ratelimit-remaining" }]
  • Patterns use Rust regex syntax (linear time; no look-around or backreferences). Retake computes each pattern’s longest possible match. A regex without an upper bound (+, *, {n,}) is refused when the file loads unless it declares max_len; a pattern that can match the empty string is refused. A match longer than a declared max_len is still redacted when it is in view, but may slip past the stream window; the final scan then fails the recording. When two patterns overlap, the earliest match wins, then the longest, then user patterns over built-ins.
  • Headers extend the allow-lists. Each added request header declares whether it counts for replay matching (match = true compares its value exactly, after redaction). Credential headers and cookies (authorization, x-api-key, cookie, set-cookie, …) cannot be added. Added header values are redacted like everything else, but a header that carries a secret in no known format is recorded as-is.
  • [match] holds normalization rules; see Normalization rules.

Streams

A secret can be split across server-sent events. For each content block, Retake holds deltas back from the take until the text after the oldest one is at least the longest possible match of any active pattern (6 KiB with the built-ins, because of PEM blocks), or the block ends. The placeholder is then written whole into the event where the secret starts, and the rest of the secret is trimmed from the events after it, which can leave an event with empty text. On replay, the client reassembles the block with the placeholder in place of the secret. Text and thinking deltas are scanned as text; input_json_delta fragments are scanned as raw JSON, and the reassembled JSON stays valid. Other events are written in arrival order behind held deltas.

Holding back only delays writes to the take. The client receives every byte as the provider sends it; nothing is buffered beyond the window.

Final scan

Before a take is finalized, Retake reads the .partial back and scans every string, and each content block’s text joined across events. If it finds a match outside a placeholder, the recording fails, the .partial is deleted and the previous take is kept. The message names the pattern and the line, never the value. A refused recording’s .partial is scanned the same way before it is kept for debugging, and deleted if the scan finds anything.

Normalization rules

Requests often contain values that change on every run: timestamps in system prompts, UUIDs an agent generates, temporary paths, tool lists built from sets. Normalization rules make such requests match their recording. Takes stay raw; rules run at replay time on both the recorded and the incoming request, so changing a rule affects every existing take immediately.

A rule is a regex replacement applied to string values. Each match becomes a numbered placeholder: the first distinct value becomes <KIND_1>, the next <KIND_2>, and a repeated value reuses its number. Numbering is computed separately for each request, so two runs that generate different IDs still match, but a request that reuses one ID where the recording used two different ones does not.

Selectors

A rule applies to the parts of the request its select names. Selectors are provider-neutral; for the Anthropic Messages API they map as follows:

SelectorAnthropic Messages API
systemthe system field
user_messagesuser message content, except tool_result blocks
assistant_messagesassistant message content, except tool_use blocks
tool_resultsthe content of tool_result blocks
tool_call_argsthe input of tool_use blocks
tool_definitionsthe tools array
allthe whole body

A selector that starts with / is a raw-body path, for fields the selectors do not cover: a JSON Pointer where a * segment matches any key or index, e.g. /metadata/user_id or /messages/*/content. Raw paths are provider-specific. A rule applies to everything inside what it selects. except takes selectors in the same form and removes them from the selection.

Built-ins

Built-inDefaultMatchesPlaceholder
uuidon, everywhere123e4567-e89b-12d3-a456-426614174000<UUID_1>
iso-timestampon, except in user_messages2026-12-05T10:11:12Z, 2026-12-05 10:11, with optional seconds, fraction and offset<TIMESTAMP_1>
temp-pathon, everywhere/tmp/…, /var/folders/…, /private/var/folders/…, C:\Users\…\AppData\Local\Temp\…, C:\Windows\Temp\…<TEMP_PATH_1>
iso-dateoff2026-12-05<DATE_1>
unix-timestampoffany 10-digit number<UNIX_TIME_1>

Structural normalization, also on by default:

  • crlf: CRLF becomes LF in every string. Other whitespace is compared exactly.
  • embedded-json: a string in tool_results that parses as a JSON object or array is compared as parsed JSON (key order and whitespace ignored). Rules then apply to the strings and numbers inside it.
  • unordered-tool-definitions: the tools array is compared in any order.

Redaction (see Placeholders) runs as one more built-in rule. It is configured in [redact], not here, and is not counted or named in what replay reports.

[match] in retake.toml

[match]
unordered = ["/metadata/tags"]       # raw paths of arrays compared in any order

[match.builtins]
iso-date  = true                     # turn an off-by-default built-in on
temp-path = false                    # or one off (crlf, embedded-json and
                                     # unordered-tool-definitions too)
uuid = { select = ["tool_results", "tool_call_args"] }   # or re-scope it
# a table also takes `except`, `tests`, and `enabled = false`

[[match.rules]]
name    = "prompt-date"
select  = "system"                   # a selector, `all`, a raw path, or a list of them
pattern = '\d{4}-\d{2}-\d{2}'
replace = "DATE"                     # becomes <DATE_1>, <DATE_2>, ...
tests   = ["tests/agent/test_booking.py::*"]   # optional

[[match.rules]]
name      = "price-noise"
select    = "tool_results"
tolerance = 0.01                     # JSON numbers within 0.01 compare equal

[[match.rules]]
name   = "screenshots"
select = "user_messages"
media  = "image/*"                   # binary parts of this media range...
match  = "any"                       # ...match any content of the range
tests  = ["tests/test_screenshot_*"] # optional, as for any rule
  • name: a-z, 0-9 and -; it may not be a built-in’s name. replace: letters, digits, _ and -.
  • pattern uses the syntax of the Rust regex crate: matching is guaranteed linear-time; look-around and backreferences are not supported. Patterns are checked when the file loads. A rule that should ignore a value entirely replaces the whole value, e.g. pattern = '(?s).+'.
  • tolerance is an absolute difference, applies to JSON numbers only (including numbers in tool results parsed as JSON), and is never on by default.
  • media and match = "any" relax binary matching: in the selected locations, binary parts (withheld or in a blob) whose media type is in the media range (image/png, image/*) match any content of that range, e.g. screenshots or re-encoded uploads whose bytes change on every run. There is no perceptual (“visually similar”) matching. Such a rule can hide a real change in an image, so limit it with select and tests. Media rules are covered by the guard and counted in the summary like any rule.
  • A rule has exactly one of: pattern and replace, tolerance, or media and match.
  • tests limits a rule to takes whose test ID matches one of the globs (* matches any characters, ? one). Without it, a rule applies to every take; with it, it never applies to _main.take or _session.take.
  • Unknown keys are an error.

How rules combine

Every request goes through the same steps, on both sides:

  1. Structural: CRLF to LF; JSON in tool results parsed.
  2. Replace: each string is scanned once. At each position the match that starts earliest is used; among matches that start at the same position the longest wins; equal lengths go to user rules over built-ins, then to the rule earlier in the file. Rules never see each other’s output, so iso-timestamp takes a whole timestamp even when a date rule is also active.
  3. Sort: unordered arrays are sorted, comparing placeholders by kind only.
  4. Number: placeholders are numbered walking the body with object keys sorted.
  5. Compare: equality, with numeric tolerance where a rule sets one.

The guard

When a take is loaded, Retake normalizes every recorded request. If a rule makes two recorded requests with different bodies and different responses compare equal, replay could serve the wrong one, so it refuses: the run fails before the command starts (exit 2), or with a plugin, the test fails. The message names the rules and both exchanges:

retake: cannot load tests/takes/_main.take: normalization rule(s) any-order make recorded exchanges #0 and #1 indistinguishable: their requests differ but normalize to the same value, and their responses differ, so replay could serve the wrong one. Narrow the rule in retake.toml (e.g. with `select` or `tests`). The requests differ in:
  body system: #0 "Handle order 7", #1 "Handle order 8"

Redaction never triggers the guard: two recorded requests that differ only in which secret they carry are treated as identical requests, served in recorded order.

What replay reports

The run summary counts matches that were exact and matches that needed rules, per rule. A rule is counted for a match when the match fails without it. Rules that never made a difference are not listed. Redaction is not counted: recorded placeholders are numbered per take and incoming ones per request, so they often differ, and a match whose only difference is in redacted values counts as exact.

retake: replayed 7 exchange(s) from tests/takes/_main.take
retake: matches: 3 exact, 4 with rules (crlf 1, embedded-json 1, iso-timestamp 1, unordered-tool-definitions 1, uuid 1)

retake replay --verbose (RETAKE_VERBOSE=1) prints each difference rules hid, as the request is matched, in stored form with placeholders renumbered per request (secrets appear as placeholders, and placeholder numbers that differ only by numbering are not listed):

retake: POST /v1/messages: matched recorded exchange #0 with rule(s) iso-timestamp; differences hidden:
  body system: recorded "Now: 2026-12-01T09:00:00Z", request "Now: 2026-12-05T17:45:12Z"

Mismatch descriptions show normalized values only:

retake: no recorded response for POST /v1/messages (retake_no_match):
closest recorded exchange is #0 (first 2 of 3 message(s) identical); it differs in:
  body messages[2].content[0].content.⟨json⟩.parent: recorded "<UUID_2>", request "<UUID_1>"

⟨json⟩ in a path marks JSON parsed out of a tool result string.

Binary content

Content Retake cannot scan

Binary media types (image/*, audio/*, video/*, font/*, application/octet-stream, application/pdf, application/zip, …), bodies that are not valid UTF-8, and bodies compressed with an encoding Retake cannot decode are withheld:

  • Requests: the body is stored as {"withheld":"sha256:…","bytes":48213,"media_type":"image/png"} (key body_withheld). Inside a JSON body, base64 blocks ({"type":"base64","media_type":…,"data":…}, e.g. images and PDFs in messages) are parts of their own: an unscannable block’s data is replaced by "withheld":"sha256:…" and "bytes", the hash and size of the decoded content. Replay withholds the incoming request the same way and matches on the hash, so a test that sends the same image still replays. Nothing but the hash, size and media type reaches the disk.
  • Responses: the body is withheld. Replaying that exchange answers 502 with error type retake_withheld, and the run fails (exit 1) as for an unmatched request; the replay summary counts it as withheld (with a test-runner plugin, the test that made the request fails). Replay never serves stand-in content for a withheld body. A JSON response with an unscannable base64 block is withheld whole. In a streamed response, such a block is withheld in its event record (hash and size only) and the whole stream is withheld on replay; the client still gets every event as it arrives while recording.
  • --allow-unscanned <media types> (RETAKE_ALLOW_UNSCANNED), e.g. --allow-unscanned 'image/*,application/pdf', stores matching content without scanning it, in blob files (see Blobs), in streamed events too. The take’s header lists the media ranges, and its footer lists every part stored unscanned (unscanned: exchange, request, response or event, JSON Pointer, media type, size, blob hash), so reviewers can see it.

Text inside base64

Base64 blocks whose media type is text-like (text/*, application/json, application/xml, and +json / +xml types) are decoded, redacted like any other text and stored readable, with text in place of data:

{"type": "base64", "media_type": "text/plain", "text": "deploy token: <redacted:github-token:1>\n"}

Replay re-encodes them as base64, so the client sees the wire format it was sent; on the request side they are compared decoded, so normalization rules and redaction apply to the text. A payload that does not decode as UTF-8 stays unscannable. Images and PDFs are never decoded to scan them: they stay hash-only unless opted in.

Blobs

Content stored with --allow-unscanned goes to one content-addressed directory at the root of the takes directory, shared by every take:

tests/takes/
  _blobs/
    sha256-3f1c…9a2e.png
    sha256-77b0…c41d.pdf
  _main.take
  tests/test_agent.py/test_screenshot.take

Each file holds the decoded content, named by its SHA-256 and an extension from its media type (bin when unknown), so a reviewer can open it. The take refers to it by hash, as a whole body (body_blob) or in place of a base64 block’s data:

{"type": "base64", "media_type": "image/png", "blob": "sha256:3f1c…9a2e", "bytes": 48213}

An image re-sent on every turn of a conversation, or by several tests, is stored once. Blobs are written before the record that refers to them. When a take is loaded, every blob it refers to must exist and match its hash; otherwise replay refuses the take (exit 2), naming the missing or changed blob, and retake check reports it. retake clean removes blobs no take refers to.

Commit _blobs/ with the takes. Git diffs of binary files are not useful, so mark them binary (retake init adds the first line below), and consider Git LFS for large ones, e.g. in .gitattributes:

tests/takes/_blobs/** binary
# or, with Git LFS installed:
tests/takes/_blobs/** filter=lfs diff=lfs merge=lfs -text

Compressed responses

Retake asks the provider for uncompressed bodies (accept-encoding: identity). A response compressed anyway with gzip, br or zstd, streamed or not, is decoded while recording (a stream before its events are parsed), then classified, redacted and stored like any other: a compressed 401 refuses the recording as an uncompressed one does. The client receives it decoded, and replay serves it uncompressed without content-encoding. Other encodings are passed through and withheld.

Uploads

multipart/form-data requests (e.g. the Files API) are parsed and stored part by part under body_multipart, without the boundary, which is random on every run; the stored content-type is multipart/form-data:

"body_multipart": [
  {"name": "purpose", "text": "user_data"},
  {"name": "file", "filename": "shot.png", "media_type": "image/png", "withheld": "sha256:…", "bytes": 48213}
]

Text fields (no filename, or a text-like media type) are stored as redacted text; field names and filenames are redacted too. Other parts are binary parts: hash-only, or blobs with --allow-unscanned. For matching, the parts compare as the JSON document {"multipart": [...]}, so a new boundary still matches, and rules can select parts with all or raw paths such as /multipart/0/text. The file ID an upload returns is ordinary JSON in the response: when a session fixture uploads a file that tests refer to, those tests depend on _session.take like any other ID (see Session IDs and dependent takes).

Server-side resources and retake reap

Some requests create state on the provider that outlives the test: uploaded files and message batches. While recording, Retake recognises the requests that create and delete these, and adds a resource record to the take after each successful one:

{"type":"resource","exchange":0,"provider":"anthropic","kind":"file","id":"file_011CNha8iCJcU1wXNR6q4V8w","action":"created"}
{"type":"resource","exchange":1,"provider":"anthropic","kind":"file","id":"file_011CNha8iCJcU1wXNR6q4V8w","action":"deleted"}
KindCreated byDeleted by
filePOST /v1/filesDELETE /v1/files/{id}
message_batchPOST /v1/messages/batchesDELETE /v1/messages/batches/{id}

Not tracked yet: Skills (and their versions), Managed Agents objects (agents, sessions, environments, vaults and credentials, memory stores, deployments), and files created inside code execution or a Managed Agents session rather than uploaded. Recordings that create these leave them for you to delete.

The recording summary lists the resources the run created and did not delete. A recording is never refused for them: a test may keep state on purpose, or remove it in a teardown that runs outside Retake’s view.

retake: 1 resource(s) created by this recording and not deleted; `retake reap` deletes them:
retake:   file file_011CNha8iCJcU1wXNR6q4V8w (tests/test_files.py/test_upload.take, exchange 0)

When a recording does not become a take (a failed test, a refused recording, a refused end-of-run finalization, a final scan that found a secret), when a new recording replaces or removes a take, and when retake clean removes a .partial, the resources it created and did not delete are appended to _resource.take in the takes directory. That file accumulates across runs as the worklist for retake reap. It describes the recording account, not test behaviour, so retake init adds it to .gitignore.

retake reap lists every resource that the committed takes and _resource.take say was created and never deleted, then deletes them with your own credentials (ANTHROPIC_API_KEY, or else ANTHROPIC_AUTH_TOKEN as a bearer token, as the SDK takes them), sent to the same place retake record sends requests (--record-anthropic-url, else ANTHROPIC_BASE_URL, else https://api.anthropic.com):

$ retake reap --dry-run
retake: 2 outstanding resource(s) in tests/takes:
retake:   file file_011CNha8iCJcU1wXNR6q4V8w (from tests/test_files.py/test_upload.take, exchange 0)
retake:   message_batch msgbatch_013Zva2CMHLNnXjNJJKqJ2EF (_resource.take, from tests/test_batch.py/test_submit.take, exchange 0)
retake: dry run; nothing deleted
  • It asks before deleting; a run without a terminal is refused unless --yes (or RETAKE_ASSUME_YES=1) is given. --dry-run only lists.
  • It deletes only IDs found in resource records, never anything else in the account.
  • A resource the provider no longer has (404) counts as reaped.
  • A message batch that is still processing cannot be deleted: reap cancels it and tries again; if it is still cancelling, it stays on the list and reap exits 1, saying to run retake reap again later. A failed deletion also exits 1.
  • reap never modifies committed takes. What it reaped is recorded only in _resource.take: entries it settles leave the file, and a reaped resource that a committed take still names gets a "action":"reaped" record there, so it is not listed again (until that take is re-recorded). Since _resource.take is local, another checkout lists those resources again; deleting them then answers 404, which counts as reaped.

Replay never creates anything on the provider: resource records are informational, the recorded IDs are served as recorded, and a replay run gives reap nothing to do. A test take whose requests use an ID from a _session.take resource record counts as a dependent of _session.take (see Session IDs).

Checking, listing and versions

Checking takes: retake check

retake check --takes-dir <dir> checks every take under the takes directory without running tests or calling any API, so it needs no API key. For each take it checks that:

  • every line is JSON and matches the take schema of its format, and the format and record types are ones this Retake reads;
  • the rules across lines hold and the take has a footer;
  • every blob it refers to exists in the _blobs/ of its own takes directory and matches its hash (see Blobs). That is the nearest _blobs/ between the take and the directory checked, else the checked directory’s, so a directory that holds several takes directories can be checked at once;
  • the guard passes with the current retake.toml (see The guard);
  • the redaction scan with the current patterns finds no secret, which catches hand edits and patterns added after the take was recorded. A secret found is reported by line and pattern name, never printed.

_resource.take (see retake reap) is checked too, but not counted as a take, as retake ls does not list it. It also warns about leftover .partial files, takes recorded from a run that exited non-zero or did not finish, takes from failed tests (--keep-failed), streams that never ended, and stale takes. Errors exit 1; warnings exit 0, except stale takes with --fail-on-stale. A missing takes directory or a bad retake.toml exits 2.

$ retake check --takes-dir tests/takes
tests/takes/agent/test_booking.take:3: error: schema: /status: "200" is not of type "integer"
tests/takes/agent/test_refund.take:12: error: secret: the current redaction patterns match (anthropic-api-key); remove the secret and re-record the take
tests/takes/_main.take: warning: stale: recorded by Retake 0.1.0; this is Retake 0.2.0
retake check: 14 take(s) in tests/takes checked in 41 ms: 2 error(s), 1 warning(s)

--json prints the same findings as JSON ("version": 1, described by schema/check-v1.schema.json), each with path, line (when it concerns one line), severity, kind and message. The check takes tens of milliseconds on the example takes, so it can run as a pre-commit hook, e.g. in .pre-commit-config.yaml:

repos:
  - repo: local
    hooks:
      - id: retake-check
        name: retake check
        entry: retake check --takes-dir tests/takes
        language: system
        pass_filenames: false
        files: '\.take$|^retake\.toml$'

Listing takes: retake ls

retake ls --takes-dir <dir> lists every take: its test ID (the path, for _main.take and _session.take), its age, the Retake version that recorded it (unknown for takes recorded before Retake wrote it), the models in its exchanges (requested and serving), how the recording ended (passed, failed, exit N, run unfinished or incomplete) and why it is stale. Takes that cannot be read are listed with the reason, and make retake ls exit 1 after listing everything else.

$ retake ls --takes-dir examples
TEST                                         AGE  RETAKE   MODELS            RESULT  STALE
test_refund.py::test_order_not_arrived       14h  unknown  claude-haiku-5-5  passed  -
test_refund.py::test_refund_half             14h  unknown  claude-haiku-5-5  passed  -
refund/_main.take                            23h  unknown  claude-haiku-5-5  exit 0  -

--json prints the list as JSON ("version": 1, described by schema/ls-v1.schema.json), with recorded_at, age_seconds, and outcome or run_exit as recorded in the footer.

Stale takes

A take is stale when:

  • the API version header a client sends during replay (anthropic-version) differs from the recorded one; only replay can tell, and the request still matches;
  • an older Retake recorded it: an older minor version before 1.0 (0.3 vs 0.4), an older major version from 1.0 on. Patch releases never make a take stale, and neither does age. A take without a recorded Retake version is never stale by version.

Staleness is a warning. retake replay lists every stale take at the end of the run:

retake: warning: tests/takes/_main.take is stale (anthropic-version: recorded 2023-06-01, sent 2026-10-21); re-record it

--fail-on-stale (or RETAKE_FAIL_ON_STALE=1) on retake replay and retake check makes stale takes fail the run (exit 1), for teams that want it in CI. Secrets an older Retake failed to redact are not a staleness question: retake check re-scans every take with the current patterns.

Format versions and retake upgrade

The header’s format is a single integer, raised only for changes an older Retake would misread; the Retake version and the format version are independent. Retake:

  • ignores fields it does not know, and refuses a take with a record type it does not know (exit 2), naming the type: a new record type always comes with a new format;
  • refuses a take in a newer format (exit 2), naming both versions, e.g. recorded with format 3 by Retake 0.6.0; this is Retake 0.5.2, which reads formats 1–2; upgrade Retake;
  • reads the current and the previous format, the previous one with a warning;
  • always writes the current format, so re-recording a take upgrades it.

retake upgrade --takes-dir <dir> rewrites takes in the previous format to the current one, changing their bytes but not their meaning. Format 1 is the only format so far, so today it reports that every take is already current. Before 1.0 any minor release may raise the format (with read support for the previous one and retake upgrade); from 1.0 only major releases may. retake.toml has no version key, and the --json output of retake check and retake ls carries its own "version".

retake.toml reference

Retake reads retake.toml from the current directory, or the file given by --config FILE / RETAKE_CONFIG. Every key is optional; unknown keys are an error, and a file that does not load stops the run before the command starts (exit 2). The file has no version key. Its JSON Schema is retake-toml.schema.json; see Editor support.

TableWhat it setsDetails
[redact]Built-in redaction patterns on or off (builtins, disable)Redaction
[[redact.patterns]]Your own patterns: name, regex, max_lenRedaction
[headers]Extra request and response headers to record (request, response)Redaction
[match]Arrays compared in any order (unordered)Normalization rules
[match.builtins]Built-in normalization rules on, off or re-scopedNormalization rules
[[match.rules]]Your own normalization rulesNormalization rules

A file using every table:

[redact]
builtins = true                      # false turns every built-in pattern off
disable  = ["google-api-key"]        # or turn some off by name

[[redact.patterns]]
name    = "employee-id"              # a-z, 0-9 and `-`; used in the placeholder
regex   = 'EMP-[0-9]{6}'             # Rust `regex` syntax
# max_len = 64                       # bytes; required when the regex is unbounded

[headers]
request  = [{ name = "x-tenant", match = true }]   # `match` is required
response = [{ name = "x-ratelimit-remaining" }]

[match]
unordered = ["/metadata/tags"]       # raw paths of arrays compared in any order

[match.builtins]
iso-date  = true                     # turn an off-by-default built-in on
temp-path = false                    # or one off
uuid = { select = ["tool_results", "tool_call_args"] }   # or re-scope it

[[match.rules]]
name    = "prompt-date"
select  = "system"
pattern = '\d{4}-\d{2}-\d{2}'
replace = "DATE"                     # becomes <DATE_1>, <DATE_2>, ...
tests   = ["tests/agent/test_booking.py::*"]   # optional

Changing [match] affects every existing take at its next replay, since rules run at replay time. Changing [redact] affects new recordings, and retake check re-scans committed takes with the current patterns.

Command-line options and their environment variables are listed in the CLI reference.

CLI reference

Generated from retake --help by docs/guide/cli-reference.sh; do not edit by hand. Every option can also be set by the environment variable shown with it.

Record real LLM API exchanges and replay them deterministically

Usage: retake <COMMAND>

Commands:
  record    Run a command through the proxy, forwarding to the provider and recording every exchange to `_main.take`, or to one take per test when a test-runner plugin is active
  replay    Run a command through the proxy, answering every request from `_main.take` (or each test's take when a test-runner plugin is active) without contacting the network
  clean     Remove leftover `.partial` files (takes left behind by a crash, a refused recording or an unfinished end-of-run finalization) under the takes directory, listing each one. Only deletes local files; their server-side resources are first saved to `_resource.take` for `retake reap`
  finalize  Finish a recording run that crashed while `_session.take` had dependents: rename the `.partial` files it left (completing `_session.take.partial`) if every dependent test was re-recorded, as the run would have at its end; otherwise rename nothing and list the tests that must be included
  check     Check the takes statically, without running tests or calling any API: every line parses and matches the take schema, the take is complete, the current `retake.toml`'s rules and redaction patterns accept it; also lists leftover `.partial` files, takes from failed or unfinished runs and stale takes. Exits 1 on errors (and on stale takes with `--fail-on-stale`)
  ls        List every take: its test ID, age, the Retake version that recorded it, the models in its exchanges, its outcome or exit code, and why it is stale, if it is. Takes that cannot be read are listed with the reason and make it exit 1
  upgrade   Rewrite takes recorded in the previous take format to the current one, keeping their meaning. Every take this Retake reads is in format 1, the only format so far, so there is nothing to rewrite yet
  reap      Delete the server-side resources (uploaded files, message batches) that recordings created and did not delete, as listed by `resource` records in the committed takes and in `_resource.take`, using your own ANTHROPIC_API_KEY. Lists them and asks first; never deletes anything not named by such a record. Unlike `retake clean`, it acts on the provider account, not on local files. Uses ANTHROPIC_AUTH_TOKEN (as a bearer token) when ANTHROPIC_API_KEY is unset
  init      Set up a project for Retake: add `*.take.partial` and `_resource.take` to `.gitignore` and mark the takes directory's `_blobs/` files as binary in `.gitattributes`, both in the current directory (creating them if needed). Running it again changes nothing
  help      Print this message or the help of the given subcommand(s)

Options:
  -h, --help     Print help
  -V, --version  Print version

retake record

Run a command through the proxy, forwarding to the provider and recording every exchange to `_main.take`, or to one take per test when a test-runner plugin is active

Usage: retake record [OPTIONS] -- <COMMAND>...

Arguments:
  <COMMAND>...  The command to run, after `--`

Options:
      --takes-dir <DIR>                Directory holding take files [env: RETAKE_TAKES_DIR=] [default: tests/takes]
      --config <FILE>                  Configuration file. Default: `retake.toml` in the current directory, if there is one [env: RETAKE_CONFIG=]
      --inflight-timeout <SECONDS>     How long the end of a test waits for that test's requests still in flight before dropping them (test-runner plugins only) [env: RETAKE_INFLIGHT_TIMEOUT=] [default: 120]
      --fail-on-late-requests          Fail the run when a request arrives for a test that has already ended (late requests are always rejected and listed) [env: RETAKE_FAIL_ON_LATE_REQUESTS=]
  -y, --yes                            Replace an existing `_main.take` without asking (required when not on a TTY). `RETAKE_ASSUME_YES` accepts `1`/`true`/`yes`/`on`; `0`/`false`/`no`/`off` or empty mean no [env: RETAKE_ASSUME_YES=]
      --record-anthropic-url <URL>     Where `retake record` sends Anthropic requests. Defaults to your ANTHROPIC_BASE_URL, else https://api.anthropic.com. Not used by `retake replay`. [env: RETAKE_RECORD_ANTHROPIC_URL=]
      --allow-errors                   Keep every error response as recorded. By default account errors (401, 402, 403) refuse the recording, and transient errors (429, any 5xx, streams the provider cut off) are dropped when retried successfully and otherwise refuse it [env: RETAKE_ALLOW_ERRORS=]
      --keep-failed                    Keep the takes of failed tests, marked `outcome: failed`, instead of discarding them and keeping the previous take (test-runner plugins only) [env: RETAKE_KEEP_FAILED=]
      --allow-unscanned <MEDIA_TYPES>  Store content Retake cannot scan as-is when its media type is in this comma-separated list (e.g. `image/*,application/pdf`), instead of withholding it. The take's footer lists every part stored this way [env: RETAKE_ALLOW_UNSCANNED=]
  -h, --help                           Print help

retake replay

Run a command through the proxy, answering every request from `_main.take` (or each test's take when a test-runner plugin is active) without contacting the network

Usage: retake replay [OPTIONS] -- <COMMAND>...

Arguments:
  <COMMAND>...  The command to run, after `--`

Options:
      --takes-dir <DIR>             Directory holding take files [env: RETAKE_TAKES_DIR=] [default: tests/takes]
      --config <FILE>               Configuration file. Default: `retake.toml` in the current directory, if there is one [env: RETAKE_CONFIG=]
      --inflight-timeout <SECONDS>  How long the end of a test waits for that test's requests still in flight before dropping them (test-runner plugins only) [env: RETAKE_INFLIGHT_TIMEOUT=] [default: 120]
      --fail-on-late-requests       Fail the run when a request arrives for a test that has already ended (late requests are always rejected and listed) [env: RETAKE_FAIL_ON_LATE_REQUESTS=]
      --pacing <PACING>             How fast recorded streams are served: `instant` (every event at once), `realtime` (at the recorded offsets), or a speed-up factor such as `4` (four times faster than recorded) [env: RETAKE_PACING=] [default: instant]
      --allow-failed                Replay takes recorded from failed tests (kept with `--keep-failed`) instead of refusing them [env: RETAKE_ALLOW_FAILED=]
      --fail-on-stale               Fail the run (exit 1) when a replayed take is stale: recorded by an older Retake minor version (major from 1.0), or with a different API version header than the client sends now. Stale takes are only a warning by default [env: RETAKE_FAIL_ON_STALE=]
  -v, --verbose                     Print every difference between a recorded and a sent request that normalization rules hid, as each request is matched [env: RETAKE_VERBOSE=]
  -h, --help                        Print help

retake clean

Remove leftover `.partial` files (takes left behind by a crash, a refused recording or an unfinished end-of-run finalization) under the takes directory, listing each one. Only deletes local files; their server-side resources are first saved to `_resource.take` for `retake reap`

Usage: retake clean [OPTIONS]

Options:
      --takes-dir <DIR>  Directory holding take files [env: RETAKE_TAKES_DIR=] [default: tests/takes]
  -n, --dry-run          List the files that would be removed without removing them
  -h, --help             Print help

retake finalize

Finish a recording run that crashed while `_session.take` had dependents: rename the `.partial` files it left (completing `_session.take.partial`) if every dependent test was re-recorded, as the run would have at its end; otherwise rename nothing and list the tests that must be included

Usage: retake finalize [OPTIONS]

Options:
      --takes-dir <DIR>  Directory holding take files [env: RETAKE_TAKES_DIR=] [default: tests/takes]
      --config <FILE>    Configuration file, for the redaction patterns of the final secret scan. Default: `retake.toml` in the current directory, if there is one [env: RETAKE_CONFIG=]
  -h, --help             Print help

retake check

Check the takes statically, without running tests or calling any API: every line parses and matches the take schema, the take is complete, the current `retake.toml`'s rules and redaction patterns accept it; also lists leftover `.partial` files, takes from failed or unfinished runs and stale takes. Exits 1 on errors (and on stale takes with `--fail-on-stale`)

Usage: retake check [OPTIONS]

Options:
      --takes-dir <DIR>  Directory holding take files [env: RETAKE_TAKES_DIR=] [default: tests/takes]
      --config <FILE>    Configuration file whose redaction patterns and matching rules the takes are checked against. Default: `retake.toml` in the current directory, if there is one [env: RETAKE_CONFIG=]
      --json             Print the findings as JSON (`"version": 1`, see schema/check-v1.schema.json)
      --fail-on-stale    Exit 1 when a take is stale (recorded by an older Retake minor version before 1.0, major from 1.0). Stale takes are only a warning by default [env: RETAKE_FAIL_ON_STALE=]
  -h, --help             Print help

retake ls

List every take: its test ID, age, the Retake version that recorded it, the models in its exchanges, its outcome or exit code, and why it is stale, if it is. Takes that cannot be read are listed with the reason and make it exit 1

Usage: retake ls [OPTIONS]

Options:
      --takes-dir <DIR>  Directory holding take files [env: RETAKE_TAKES_DIR=] [default: tests/takes]
      --json             Print the list as JSON (`"version": 1`, see schema/ls-v1.schema.json)
  -h, --help             Print help

retake upgrade

Rewrite takes recorded in the previous take format to the current one, keeping their meaning. Every take this Retake reads is in format 1, the only format so far, so there is nothing to rewrite yet

Usage: retake upgrade [OPTIONS]

Options:
      --takes-dir <DIR>  Directory holding take files [env: RETAKE_TAKES_DIR=] [default: tests/takes]
  -h, --help             Print help

retake reap

Delete the server-side resources (uploaded files, message batches) that recordings created and did not delete, as listed by `resource` records in the committed takes and in `_resource.take`, using your own ANTHROPIC_API_KEY. Lists them and asks first; never deletes anything not named by such a record. Unlike `retake clean`, it acts on the provider account, not on local files. Uses ANTHROPIC_AUTH_TOKEN (as a bearer token) when ANTHROPIC_API_KEY is unset

Usage: retake reap [OPTIONS]

Options:
      --takes-dir <DIR>             Directory holding take files [env: RETAKE_TAKES_DIR=] [default: tests/takes]
  -n, --dry-run                     List the outstanding resources without deleting anything
  -y, --yes                         Delete without asking (required when not on a TTY). `RETAKE_ASSUME_YES` accepts `1`/`true`/`yes`/`on` [env: RETAKE_ASSUME_YES=]
      --record-anthropic-url <URL>  Where to send Anthropic deletions, as for `retake record`: this flag, else your ANTHROPIC_BASE_URL, else https://api.anthropic.com [env: RETAKE_RECORD_ANTHROPIC_URL=]
  -h, --help                        Print help

retake init

Set up a project for Retake: add `*.take.partial` and `_resource.take` to `.gitignore` and mark the takes directory's `_blobs/` files as binary in `.gitattributes`, both in the current directory (creating them if needed). Running it again changes nothing

Usage: retake init [OPTIONS]

Options:
      --takes-dir <DIR>  Directory holding take files [env: RETAKE_TAKES_DIR=] [default: tests/takes]
  -h, --help             Print help

JSON Schemas

Retake’s formats are described by hand-written JSON Schemas (draft 2020-12) in schema/:

FileDescribes
take-v1.schema.jsonOne line (record) of a format-1 take
retake-toml.schema.jsonretake.toml
check-v1.schema.jsonretake check --json output
ls-v1.schema.jsonretake ls --json output

They are a contract: retake check validates every take against the schema of its format, and Retake’s test suite checks every take, retake.toml and --json output it produces against them. Takes do not name their schema; the header’s format selects it. Each schema’s $id is its URL on this site, https://simdugas.github.io/retake/schema/<file name>; building the guide copies the schemas there. The site is deployed from each release, so it serves the schemas of the latest release; the repository’s schema/ directory has those of any other version.

Editor support for retake.toml

Editors using Taplo (e.g. the Even Better TOML extension for VS Code) can validate and complete retake.toml with the schema. Either put a directive on the first line of the file:

#:schema https://simdugas.github.io/retake/schema/retake-toml.schema.json

or associate it in a .taplo.toml at the project root:

[[rule]]
include = ["retake.toml"]

[rule.schema]
path = "https://simdugas.github.io/retake/schema/retake-toml.schema.json"

A local copy of the file works too (path = "./retake-toml.schema.json"), and is the way to pin the schema to the Retake version you run: the site serves the schema of the version the guide was last built from.