# Agents 1 labs: the agent loop and the prompt cache

Two scripts that read Claude Code's loop from the outside. Both run offline with Python 3.9+ and the
standard library. `loop_trace.py --real` is the only part that calls a model, and it is opt-in and capped.

| Lab | What it does | Docs |
|---|---|---|
| `loop_trace.py` | Rebuilds the loop from stream-json transcripts: one row per model response (events grouped by `message.id`), tool calls with their results and denials, `system/api_retry` events, then a verdict on how the run ended. The verdict checks `stop_reason` first (a refusal), then `terminal_reason`, then `subtype`, the order the docs give. | [headless](https://code.claude.com/docs/en/headless), [agent loop](https://code.claude.com/docs/en/agent-sdk/agent-loop), [ResultMessage](https://code.claude.com/docs/en/agent-sdk/python#resultmessage), [ResultError](https://code.claude.com/docs/en/agent-sdk/python#resulterror) |
| `cache_sim.py` | A toy model of the prompt cache. It replays scripted sessions, prices each request (reads, 5m/1h writes, uncached input), and labels each one HIT, PARTIAL or MISS with the reason the prefix changed. | [prompt caching](https://code.claude.com/docs/en/prompt-caching), [API prompt caching](https://platform.claude.com/docs/en/build-with-claude/prompt-caching) |

## Run

```bash
cd labs
python3 agents-1/loop_trace.py                          # common fixtures, the real api_error run, synthetic endings
python3 agents-1/loop_trace.py --only max_turns_stop     # one transcript
python3 agents-1/loop_trace.py --transcript run.jsonl    # your own claude -p ... --output-format stream-json --verbose
python3 agents-1/loop_trace.py --json --save             # summary rows as JSON, plus agents-1/out/loop_trace.json
python3 agents-1/loop_trace.py --real --max-turns 2 --max-budget-usd 0.05 --model haiku   # costs money

python3 agents-1/cache_sim.py                            # every scenario + per-request usage from a fixture
python3 agents-1/cache_sim.py --scenario coffee-break --billing api
python3 agents-1/cache_sim.py --scenario switches --billing cloud   # Bedrock, Agent Platform or a Claude apps gateway
python3 agents-1/cache_sim.py --scenario-file my.json    # {"name": ..., "steps": [{"at": 0, "do": "request", "add": 1200}, ...]}
```

`--real` runs `claude -p` through `common/cc.py`: a temp copy of `common/samples/tiny-app`, `--tools Read,Grep,Glob`,
`--permission-mode dontAsk`, hooks and MCP off, and always `--max-turns` and `--max-budget-usd`.

## loop_trace.py output (offline)

```
── explore_readonly  (common/fixtures/stream/explore_readonly.jsonl)
  init: model=claude-haiku-5-5 permissionMode=dontAsk tools=Glob,Grep,Read
  step 1  msg_lab_explore_01     text "I'll list the package modules first."; Glob(tinyapp/*.py) ✓
  step 2  msg_lab_explore_02     Read(tinyapp/pricing.py) ✓; Read(tinyapp/cart.py) ✓  [2 tool calls in one response]
  step 3  msg_lab_explore_03     Grep(^def ) ✓
  step 4  msg_lab_explore_04     text 'tinyapp has four modules: - `pricing.py`: `mone…'
  result: stop_reason=end_turn terminal_reason=completed subtype=success num_turns=4 cost=$0.001987
  verdict: COMPLETED - stop_reason=end_turn, terminal_reason=completed

── api_error  (agents-1/fixtures/api_error.jsonl: a real run that never reached the model)
  init: model=claude-haiku-5-5 permissionMode=dontAsk tools=mcp__tinyapp__quote_cart
  step 1  msg_lab_apierror_01    text 'API Error: Could not load AWS credentials · Cou…'
           ↳ assistant error category: cloud_credential_error
  api_retry: attempt 1/2 error=cloud_credential_error status=None, attempt 2/2 error=cloud_credential_error status=None
  result: stop_reason=stop_sequence terminal_reason=api_error subtype=success num_turns=1 cost=$0.000000
  verdict: API_ERROR - terminal_reason=api_error (no HTTP status: the request never got a response); subtype is 'success', so a subtype-only check would call this a success

── synthetic/refusal  (success with stop_reason refusal and terminal_reason completed)
  result: stop_reason=refusal terminal_reason=completed subtype=success num_turns=3 cost=$0.001407
  verdict: REFUSAL - stop_reason=refusal: the model declined (terminal_reason=completed, subtype=success); a subtype-only check would call it a success

── synthetic/refusal_api_error  (the same refusal with terminal_reason api_error, which the docs say a refusal can read)
  result: stop_reason=refusal terminal_reason=api_error subtype=success num_turns=3 cost=$0.001407
  verdict: REFUSAL - stop_reason=refusal: the model declined (terminal_reason=api_error, subtype=success); checking terminal_reason first would call it an API error
```

The summary table:

```
transcript                   responses  tools  errors  denied  num_turns  stop_reason    terminal_reason   subtype                 verdict
───────────────────────────  ─────────  ─────  ──────  ──────  ─────────  ─────────────  ────────────────  ──────────────────────  ────────────
explore_readonly             4          4      0       0       4          end_turn       completed         success                 COMPLETED
tool_error_recovery          4          3      1       0       4          end_turn       completed         success                 COMPLETED
max_turns_stop               2          3      1       0       3          tool_use       max_turns         error_max_turns         TURN_LIMIT
permission_denied            2          1      1       1       2          end_turn       completed         success                 COMPLETED
api_error                    1          0      0       0       1          stop_sequence  api_error         success                 API_ERROR
synthetic/budget_stop        2          3      1       0       3          tool_use       budget_exhausted  error_max_budget_usd    BUDGET_LIMIT
synthetic/context_full       2          3      1       0       3          None           prompt_too_long   success                 CONTEXT_FULL
synthetic/interrupted        2          3      1       0       3          None           aborted_tools     error_during_execution  INTERRUPTED
synthetic/refusal            2          3      1       0       3          refusal        completed         success                 REFUSAL
synthetic/refusal_api_error  2          3      1       0       3          refusal        api_error         success                 REFUSAL
synthetic/killed             2          3      1       0       None       None           None              None                    INCOMPLETE
```

Read it this way:

- **Responses vs tool calls.** `max_turns_stop` made 3 tool calls in 2 responses, because step 2 ran `Glob` and `Read` in parallel. It reports `num_turns: 3` under `--max-turns 2`. Read the number from the result; don't recompute it.
- **Permission denials.** `permission_denied` ends `success` with one denial. A gate that wants "did everything it tried" must check `permission_denials` as well.
- **The `api_error` trap.** Four rows say `subtype: success` and aren't successes: `api_error`, `synthetic/context_full` and the two refusals. So is any `--json-schema` run without `structured_output`. After the refusal check, the verdict reads `terminal_reason`: only `completed` is a finished loop, so `api_error`, `prompt_too_long`, `model_error` or `budget_exhausted` next to `subtype: success` still fails.
- **Refusals come first.** The docs' order is `stop_reason`, then `terminal_reason`, then `subtype`. A declined response has `stop_reason: "refusal"`, usually with `subtype: "success"`, and its `terminal_reason` "can read `completed` or `api_error`". So `synthetic/refusal_api_error` is REFUSAL, not API_ERROR: a gate that read `terminal_reason` first would retry it as an outage.

## cache_sim.py output (offline, toy model)

```
switches: mid-session actions, cache-safe and not  (main TTL 1h, others 5m)
at   who      event                                         read    write   input  out   cost     cache
0m   main     first request                                 0       11,697  3      300   $0.0996  MISS (cold: nothing cached for this model and lane)
1m   main     after permission mode change                  11,700  1,097   3      300   $0.0171  HIT+tail
2m   main     after editing CLAUDE.md                       12,800  1,097   3      300   $0.0173  HIT+tail
3m   main     after adding an MCP server (tool search on)   13,900  1,097   3      300   $0.0176  HIT+tail
4m   main     after /effort high                            15,000  1,097   3      300   $0.0178  HIT+tail
5m   main     after /model sonnet                           0       17,197  3      300   $0.0718  MISS (cold: nothing cached for this model and lane)
6m   main     back to opus within its TTL                   16,100  2,197   3      300   $0.0268  HIT+tail
7m   main     after adding an MCP server (tool search off)  9,000   12,797  3      300   $0.1102  PARTIAL (prefix changed at mcp:1)
8m   compact  /compact (summarization request)              21,800  497     3      2000  $0.0469  HIT+tail
9m   main     first request after /compact                  11,400  3,997   3      300   $0.0403  PARTIAL (prefix changed at project:v2)
10m  main     after /rewind                                 14,600  797     3      300   $0.0153  HIT+tail
11m  main     after upgrading Claude Code                   0       16,497  3      300   $0.1380  MISS (prefix changed at sys:v2:e0)
  total: $0.6186 with caching vs $0.8542 without (28% saved); 64% of input tokens read from cache
```

- **`HIT+tail`** means everything up to the new conversation tail came from the cache. Claude Code caches up to the end of each request, so a healthy session writes only what's new. The `observed` table at the top shows that pattern in a recorded transcript: 9,812 tokens written, then reads of 9,812, 9,988 and 11,456.
- **Cache-safe actions:** a permission-mode change, a CLAUDE.md edit, an MCP server with tool search on, and `/effort` on Opus 5.5 with an API key or a subscription. On Bedrock, Google Cloud's Agent Platform or a Claude apps gateway, `/effort` invalidates; `--billing cloud` shows that row as a MISS.
- **TTL defaults:** a subscription's 1-hour main bucket applies within the plan's included usage (usage credits drop it to 5 minutes), a few server-controlled helper requests get 1 hour, and `promptCacheTtl` / `subagentPromptCacheTtl` (`--main-ttl` / `--sub-ttl`) override either bucket.
- **Invalidating actions:** a model switch (each model has its own cache), an MCP server whose tools load upfront, compaction and an upgrade.
- **The 8m row** is the `/compact` summarization request. It reads the conversation's cache, but compaction is in the "everything else" TTL bucket, so its write is priced at the 5-minute rate even on a subscription.
- **The 9m row** changes the project layer because the CLAUDE.md edit from 2m finally applies after `/compact`. That's the documented "the edit also doesn't apply" behavior.
- **`coffee-break`** costs one full rebuild on a 5-minute TTL and none on 1 hour. The TTL comparison table prints both. On a subscription the dollar figures are API list-price equivalents, not charges.

## Fixtures

- `common/fixtures/stream/*.jsonl`: the shared transcripts (see `common/fixtures/FIXTURES.md`).
- `agents-1/fixtures/api_error.jsonl`: a real Claude Code v2.1.303 Agent SDK run from 2026-10-20 whose Bedrock credentials didn't load, so it cost $0. claude-agent-sdk 0.2.168 bundles CLI 2.1.301, so the run used the installed CLI through `cli_path` (`agents-2/sdk_agent.py --cli-path`); the init line's `claude_code_version` is 2.1.303.
  - **Sanitized:** the temp path became `/tmp/cc-lab-demo/tiny-app`, and the session ids and uuids are deterministic.
  - **Removed:** the undocumented init fields (`original_cwd`, `messaging_socket_path`, `analytics_disabled`, `product_feedback_disabled`, `view_mode`, `per_turn_effort_active`, `additional_directories`, `fast_mode_*`, `terminal_slash_commands`, the MCP server `source`). The `slash_commands`, `agents` and `capabilities` lists are trimmed.
  - **Kept:** the `system/api_retry` fields match the headless page's table (`attempt`, `max_retries`, `retry_delay_ms`, `error_status`, `error`). Both the real SDK 0.2.168 parser and `common/sdk_fake.to_message` produce identical dataclasses from every line.
- **Synthetic endings** are built in code from `max_turns_stop`, changing only documented result fields. Every `terminal_reason` they use is in the agent-sdk/typescript enum: `budget_exhausted` on the budget stop (a real v2.1.303 budget stop gave the same), `prompt_too_long`, `aborted_tools`, and `completed` and `api_error` on the refusals. Where the docs don't say which subtype pairs with a value (`aborted_tools`, `prompt_too_long`), the output marks it as assumed.
- **The two refusals** follow agent-sdk/python: `stop_reason: "refusal"`, `subtype: "success"` and `is_error: true` ([ResultMessage](https://code.claude.com/docs/en/agent-sdk/python#resultmessage)), with `terminal_reason` `completed` and `api_error`, the two values [ResultError](https://code.claude.com/docs/en/agent-sdk/python#resulterror) says a refusal can read. The refusal text is illustrative.
