agentcap-cli 0.2.0__tar.gz → 0.2.2__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. {agentcap_cli-0.2.0 → agentcap_cli-0.2.2}/PKG-INFO +42 -10
  2. {agentcap_cli-0.2.0 → agentcap_cli-0.2.2}/README.md +41 -9
  3. {agentcap_cli-0.2.0 → agentcap_cli-0.2.2}/pyproject.toml +1 -1
  4. {agentcap_cli-0.2.0 → agentcap_cli-0.2.2}/src/agentcap/__init__.py +1 -1
  5. {agentcap_cli-0.2.0 → agentcap_cli-0.2.2}/src/agentcap/cli.py +8 -0
  6. {agentcap_cli-0.2.0 → agentcap_cli-0.2.2}/src/agentcap/history.py +4 -2
  7. {agentcap_cli-0.2.0 → agentcap_cli-0.2.2}/src/agentcap/quota.py +131 -12
  8. {agentcap_cli-0.2.0 → agentcap_cli-0.2.2}/src/agentcap/waste.py +45 -11
  9. {agentcap_cli-0.2.0 → agentcap_cli-0.2.2}/tests/test_agents.py +84 -0
  10. {agentcap_cli-0.2.0 → agentcap_cli-0.2.2}/tests/test_cc_plugin.py +54 -0
  11. {agentcap_cli-0.2.0 → agentcap_cli-0.2.2}/tests/test_quota.py +132 -1
  12. {agentcap_cli-0.2.0 → agentcap_cli-0.2.2}/.gitignore +0 -0
  13. {agentcap_cli-0.2.0 → agentcap_cli-0.2.2}/LICENSE +0 -0
  14. {agentcap_cli-0.2.0 → agentcap_cli-0.2.2}/src/agentcap/adapters.py +0 -0
  15. {agentcap_cli-0.2.0 → agentcap_cli-0.2.2}/src/agentcap/alerts.py +0 -0
  16. {agentcap_cli-0.2.0 → agentcap_cli-0.2.2}/src/agentcap/analytics.py +0 -0
  17. {agentcap_cli-0.2.0 → agentcap_cli-0.2.2}/src/agentcap/budget.py +0 -0
  18. {agentcap_cli-0.2.0 → agentcap_cli-0.2.2}/src/agentcap/clamp.py +0 -0
  19. {agentcap_cli-0.2.0 → agentcap_cli-0.2.2}/src/agentcap/cli_history.py +0 -0
  20. {agentcap_cli-0.2.0 → agentcap_cli-0.2.2}/src/agentcap/data/pricing.json +0 -0
  21. {agentcap_cli-0.2.0 → agentcap_cli-0.2.2}/src/agentcap/demo.py +0 -0
  22. {agentcap_cli-0.2.0 → agentcap_cli-0.2.2}/src/agentcap/devtools/__init__.py +0 -0
  23. {agentcap_cli-0.2.0 → agentcap_cli-0.2.2}/src/agentcap/devtools/fake_upstream.py +0 -0
  24. {agentcap_cli-0.2.0 → agentcap_cli-0.2.2}/src/agentcap/estimate.py +0 -0
  25. {agentcap_cli-0.2.0 → agentcap_cli-0.2.2}/src/agentcap/eta.py +0 -0
  26. {agentcap_cli-0.2.0 → agentcap_cli-0.2.2}/src/agentcap/ledger.py +0 -0
  27. {agentcap_cli-0.2.0 → agentcap_cli-0.2.2}/src/agentcap/license.py +0 -0
  28. {agentcap_cli-0.2.0 → agentcap_cli-0.2.2}/src/agentcap/loop.py +0 -0
  29. {agentcap_cli-0.2.0 → agentcap_cli-0.2.2}/src/agentcap/plans.py +0 -0
  30. {agentcap_cli-0.2.0 → agentcap_cli-0.2.2}/src/agentcap/pricing.py +0 -0
  31. {agentcap_cli-0.2.0 → agentcap_cli-0.2.2}/src/agentcap/proxy.py +0 -0
  32. {agentcap_cli-0.2.0 → agentcap_cli-0.2.2}/src/agentcap/report.py +0 -0
  33. {agentcap_cli-0.2.0 → agentcap_cli-0.2.2}/src/agentcap/runner.py +0 -0
  34. {agentcap_cli-0.2.0 → agentcap_cli-0.2.2}/src/agentcap/upstreams.py +0 -0
  35. {agentcap_cli-0.2.0 → agentcap_cli-0.2.2}/src/agentcap/usage.py +0 -0
  36. {agentcap_cli-0.2.0 → agentcap_cli-0.2.2}/tests/conftest.py +0 -0
  37. {agentcap_cli-0.2.0 → agentcap_cli-0.2.2}/tests/fixtures/agents/claude/projects/-home-dev-shop/sess-p/subagents/agent-a1b2c3.jsonl +0 -0
  38. {agentcap_cli-0.2.0 → agentcap_cli-0.2.2}/tests/fixtures/agents/claude/projects/-home-dev-shop/sess-p/subagents/agent-d4e5f6.jsonl +0 -0
  39. {agentcap_cli-0.2.0 → agentcap_cli-0.2.2}/tests/fixtures/agents/claude/projects/-home-dev-shop/sess-p.jsonl +0 -0
  40. {agentcap_cli-0.2.0 → agentcap_cli-0.2.2}/tests/fixtures/agents/codex/sessions/2026/10/29/rollout-2026-10-29T09-00-00-thr-parent.jsonl +0 -0
  41. {agentcap_cli-0.2.0 → agentcap_cli-0.2.2}/tests/fixtures/agents/codex/sessions/2026/10/29/rollout-2026-10-29T09-00-50-thr-child.jsonl +0 -0
  42. {agentcap_cli-0.2.0 → agentcap_cli-0.2.2}/tests/fixtures/agents/codex/sessions/2026/10/29/rollout-2026-10-29T09-01-20-thr-fork.jsonl +0 -0
  43. {agentcap_cli-0.2.0 → agentcap_cli-0.2.2}/tests/fixtures/history/claude/.credentials.json +0 -0
  44. {agentcap_cli-0.2.0 → agentcap_cli-0.2.2}/tests/fixtures/history/claude/projects/-home-dev-shop/1f0c-sess-a.jsonl +0 -0
  45. {agentcap_cli-0.2.0 → agentcap_cli-0.2.2}/tests/fixtures/history/codex/auth.json +0 -0
  46. {agentcap_cli-0.2.0 → agentcap_cli-0.2.2}/tests/fixtures/history/codex/sessions/2026/10/29/rollout-2026-10-29T10-00-00-0199aaaa-bbbb-cccc-dddd-eeeeeeeeeeee.jsonl +0 -0
  47. {agentcap_cli-0.2.0 → agentcap_cli-0.2.2}/tests/license_support.py +0 -0
  48. {agentcap_cli-0.2.0 → agentcap_cli-0.2.2}/tests/proxy_support.py +0 -0
  49. {agentcap_cli-0.2.0 → agentcap_cli-0.2.2}/tests/test_adapters.py +0 -0
  50. {agentcap_cli-0.2.0 → agentcap_cli-0.2.2}/tests/test_alerts.py +0 -0
  51. {agentcap_cli-0.2.0 → agentcap_cli-0.2.2}/tests/test_analytics.py +0 -0
  52. {agentcap_cli-0.2.0 → agentcap_cli-0.2.2}/tests/test_anthropic_proxy.py +0 -0
  53. {agentcap_cli-0.2.0 → agentcap_cli-0.2.2}/tests/test_anthropic_units.py +0 -0
  54. {agentcap_cli-0.2.0 → agentcap_cli-0.2.2}/tests/test_budget.py +0 -0
  55. {agentcap_cli-0.2.0 → agentcap_cli-0.2.2}/tests/test_clamp.py +0 -0
  56. {agentcap_cli-0.2.0 → agentcap_cli-0.2.2}/tests/test_claude_adapter_and_tiers.py +0 -0
  57. {agentcap_cli-0.2.0 → agentcap_cli-0.2.2}/tests/test_cli.py +0 -0
  58. {agentcap_cli-0.2.0 → agentcap_cli-0.2.2}/tests/test_e2e_claude.py +0 -0
  59. {agentcap_cli-0.2.0 → agentcap_cli-0.2.2}/tests/test_estimate.py +0 -0
  60. {agentcap_cli-0.2.0 → agentcap_cli-0.2.2}/tests/test_history.py +0 -0
  61. {agentcap_cli-0.2.0 → agentcap_cli-0.2.2}/tests/test_ledger.py +0 -0
  62. {agentcap_cli-0.2.0 → agentcap_cli-0.2.2}/tests/test_license.py +0 -0
  63. {agentcap_cli-0.2.0 → agentcap_cli-0.2.2}/tests/test_loop.py +0 -0
  64. {agentcap_cli-0.2.0 → agentcap_cli-0.2.2}/tests/test_pricing.py +0 -0
  65. {agentcap_cli-0.2.0 → agentcap_cli-0.2.2}/tests/test_proxy_cancel.py +0 -0
  66. {agentcap_cli-0.2.0 → agentcap_cli-0.2.2}/tests/test_proxy_core.py +0 -0
  67. {agentcap_cli-0.2.0 → agentcap_cli-0.2.2}/tests/test_proxy_extras.py +0 -0
  68. {agentcap_cli-0.2.0 → agentcap_cli-0.2.2}/tests/test_proxy_streaming.py +0 -0
  69. {agentcap_cli-0.2.0 → agentcap_cli-0.2.2}/tests/test_report_cli.py +0 -0
  70. {agentcap_cli-0.2.0 → agentcap_cli-0.2.2}/tests/test_runaway.py +0 -0
  71. {agentcap_cli-0.2.0 → agentcap_cli-0.2.2}/tests/test_runner.py +0 -0
  72. {agentcap_cli-0.2.0 → agentcap_cli-0.2.2}/tests/test_upstreams.py +0 -0
  73. {agentcap_cli-0.2.0 → agentcap_cli-0.2.2}/tests/test_usage.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: agentcap-cli
3
- Version: 0.2.0
3
+ Version: 0.2.2
4
4
  Summary: API-key spend guard for unattended Codex CLI, Gemini CLI and Claude Code runs: hard per-run cap, kills the process at the limit.
5
5
  Project-URL: Homepage, https://agentcap.launchbench.studio
6
6
  Project-URL: Repository, https://github.com/Blitz00X/agentcap
@@ -40,7 +40,10 @@ tool loops and error streaks.
40
40
  $ agentcap waste --since 7d
41
41
  SUBAGENTS $41.20 25% of spend in 31 subagent/forked threads
42
42
  OPUS $38.90 24% of spend
43
- CACHE MISSES $6.10 57 cache re-writes after the TTL ran out (5 min, or 1 h)
43
+ CACHE MISSES $6.10 57 cache re-writes after the TTL ran out (5 min since the last request, or 1 h)
44
+ main session $2.30 21x subagents $3.80 36x
45
+ Tip: idle subagents re-wrote their own context 36x (~$3.80). Set subagentPromptCacheTtl: "1h" ...
46
+ STARTING CONTEXT 31 subagents, first request median 38.2k tok, largest 131.0k (7f3a91c2/a1b2c3d4)
44
47
  REPEATED TOOL CALLS $9.80 12 streaks of >= 3 identical calls in a row
45
48
  TOOL ERROR STREAKS $4.30 5 streaks of >= 3 failing calls in a row
46
49
  Pro would have stopped this run at $3.12 / at 4 repeats (Bash x11 in 7f3a91c2, $2.40 after that).
@@ -53,16 +56,31 @@ Pro would have stopped this run at $3.12 / at 4 repeats (Bash x11 in 7f3a91c2, $
53
56
  agentcap run --quota 5% -- claude # subscription: stop at 5% of the weekly quota, or on a loop
54
57
  agentcap run --quota 10% --window 5h -- codex # same for Codex on a ChatGPT plan
55
58
  agentcap run --cap 2 -- codex exec "fix tests" # API key: $2 cap + loop/burn breaker
59
+ agentcap approve # raise a stopped job's limit by 50% (at most twice)
56
60
  ```
57
61
 
62
+ On a $20/month Codex plan, two code-review prompts used the whole 5-hour limit
63
+ ([Povilas Korop](https://x.com/PovilasKorop/status/2116114249655501050): $7.70 + $1.43 at API prices).
64
+ `--quota 10% --window 5h -- codex` stops the job before that.
65
+
66
+ Free tools like [claude-code-spend-stop](https://github.com/VedantBhayani/claude-code-spend-stop) and
67
+ [RelayPlane](https://relayplane.com) give you a free $ cap. AgentCap adds the loop breaker, a cap on
68
+ your subscription quota % and Codex support.
69
+
58
70
  - **Loop breaker.** Same tool call (name + input) 4 times in a row, or 8 failing tool calls in a
59
71
  row: the run is stopped (exit 4). On subscriptions it works without touching your login or
60
- traffic: Claude Code via an official `PreToolUse` hook (denies the 4th identical call, then
61
- SIGINT if the agent keeps going); Codex by reading its own rollout file (SIGINT). On API keys the
72
+ traffic: Claude Code via an official `PreToolUse` hook (denies the 4th identical call and ends
73
+ the turn; an interactive session stays open so you can `agentcap approve` or quit; headless
74
+ `claude -p` runs get SIGINT if they keep going); Codex by reading its own rollout file (SIGINT). On API keys the
62
75
  proxy also catches identical requests and `--max-burn` $/min spikes.
63
76
  - **Per-job quota %.** Stop one job at its share of the account's weekly or 5-hour limit.
64
77
  - **Evidence receipt.** Each stop prints and saves why (`same tool call 4 times in a row (Bash)`,
65
- `this job used 5.1% of the weekly quota`) as numbers only, never prompts.
78
+ `this job used 5.1% of the weekly quota`) and the last tool call's name, as numbers and tool
79
+ names only, never prompts or tool inputs.
80
+ - **Approve.** After a stop, `agentcap approve` (or `/agentcap:approve` in the plugin) raises the
81
+ limit by 50%, at most twice, and the run continues. This works for interactive Claude Code,
82
+ which stays open after a stop. Codex and headless `claude -p` jobs are stopped with SIGINT, so
83
+ there approve only helps before the limit is hit; after a stop it says so and changes nothing.
66
84
  - **Free** runs the same detectors in observe-only mode and prints what Pro would have done.
67
85
 
68
86
  Honest limits: Claude tool-error streaks are only caught on API-key runs (the subscription hook sees
@@ -135,10 +153,12 @@ integrated terminal behind `agentcap run --cap`, shows live run spend in the
135
153
  status bar, warns at 80% / 95%, and shows a modal when the cap (exit 3) or Pro's
136
154
  loop breaker (exit 4) stops the run. It needs the `agentcap` CLI above.
137
155
 
138
- It is **not on the VS Code Marketplace or Open VSX yet**. Install the `.vsix`
139
- attached to the [GitHub release](https://github.com/Blitz00X/agentcap/releases):
156
+ It is **not on the VS Code Marketplace or Open VSX yet**. [Download agentcap-0.2.0.vsix](https://agentcap.launchbench.studio/agentcap-0.2.0.vsix)
157
+ (sha256 `175213b0979019cb472752ad71e613a48c6a22e7d899b761093ab7eac9867e70`) and install it:
140
158
 
141
159
  ```bash
160
+ curl -LO https://agentcap.launchbench.studio/agentcap-0.2.0.vsix
161
+ sha256sum agentcap-0.2.0.vsix # compare with the sha256 above
142
162
  code --install-extension agentcap-0.2.0.vsix # VS Code
143
163
  cursor --install-extension agentcap-0.2.0.vsix # Cursor
144
164
  ```
@@ -303,7 +323,9 @@ agentcap quota # read-only: last seen usage (Fre
303
323
  statusline command that records the official `rate_limits` (`five_hour` / `seven_day`
304
324
  `used_percentage`, `resets_at`) and then runs **your own statusline command unchanged**,
305
325
  plus a `PreToolUse` hook that denies further tool calls with a clear reason once the job's
306
- share reaches the limit. If the agent does not stop, AgentCap sends it SIGINT. Exit code 3.
326
+ share reaches the limit and ends the turn (`continue: false`). An interactive session stays open
327
+ (run `agentcap approve` to continue, or quit). Headless `claude -p` runs, and sessions where
328
+ the hook never fired, get SIGINT. Exit code 3.
307
329
  - **Codex CLI:** AgentCap tails the `token_count` events Codex writes to
308
330
  `~/.codex/sessions/**/rollout-*.jsonl` (`rate_limits.primary/secondary.used_percent`,
309
331
  `window_minutes`, `resets_at`) and sends SIGINT at the limit. Exit code 3.
@@ -318,7 +340,7 @@ agentcap quota # read-only: last seen usage (Fre
318
340
  use in the same window counts against the job (AgentCap warns when it sees another session).
319
341
  Values arrive once per model response, so a job **can overshoot by up to one request**.
320
342
  Claude Code only reports `rate_limits` for Pro/Max logins and only in interactive sessions
321
- (the statusline does not run in `claude -p`). Codex's rollout format is undocumented and may change.
343
+ (the statusline does not run in `claude -p`). Codex's rollout format is undocumented and may change. Codex reports `used_percent` in whole percent, so a Codex cap under 1% cannot trigger until the job has used a full 1% (AgentCap warns at start). Use `--quota 1%` or more for Codex.
322
344
  **Verified so far on fixtures and fake CLIs only** (plus real Claude Code 2.1.197: the `--settings`
323
345
  layer, the chained statusline and the `PreToolUse` deny were checked against a local fake API);
324
346
  a check on a real Max / ChatGPT account is still pending.
@@ -491,6 +513,15 @@ agentcap run -- codex exec "..." # uses the $2 task cap from the budget
491
513
  agentcap run --quota -- claude # uses the 5% / 5h quota from the budget
492
514
  ```
493
515
 
516
+ Tools like agent-tree show you what your subagents are doing; AgentCap also stops them when they loop
517
+ (same tool call 4x in a row or 8 tool errors in a row, Pro). `agentcap waste` lists cache misses first:
518
+ resuming a session after the cache expired re-writes the whole prompt cache, so start a new session (or `/clear`) after a break.
519
+ Misses are split into main session and subagents. An idle subagent re-writes only its own context
520
+ (not the whole conversation, unless it is a forked subagent), at 1.25x normal input. If your
521
+ subagents sit idle for more than 5 minutes, set `subagentPromptCacheTtl: "1h"`. A 1 h write costs
522
+ 2x input, so it only pays off when the subagent is reused. `STARTING CONTEXT` shows how many tokens
523
+ each subagent's first request carries.
524
+
494
525
  - **Store:** `~/.local/share/agentcap/usage.db` (`$XDG_DATA_HOME` respected, mode 600). `import` is
495
526
  idempotent; it reads only `*.jsonl` session logs and AgentCap's own files. It never opens auth or
496
527
  credential files, never stores prompt or response text, and never touches network or OAuth traffic.
@@ -506,7 +537,8 @@ agentcap run --quota -- claude # uses the 5% / 5h quota from the budget
506
537
  are undocumented and change between CLI versions.
507
538
  - **`waste` heuristics:** a cache miss is a cache write larger than the cache read after the prompt
508
539
  cache TTL ran out (5 min; 1 h when written with `ephemeral_1h`; Codex: a big uncached prompt after
509
- > 5 min idle). Tool inputs are hashed, never printed. Not in local logs: `agent_summary` / title
540
+ > 5 min idle). Its $ is what the re-write cost above a cache read: 5 min writes at 1.25x input,
541
+ 1 h writes at 2x input (Anthropic list prices). Tool inputs are hashed, never printed. Not in local logs: `agent_summary` / title
510
542
  background calls and HTTP retries (planned: local OTel receiver).
511
543
 
512
544
  ### Pro extras: analytics (`agentcap report <view>`)
@@ -10,7 +10,10 @@ tool loops and error streaks.
10
10
  $ agentcap waste --since 7d
11
11
  SUBAGENTS $41.20 25% of spend in 31 subagent/forked threads
12
12
  OPUS $38.90 24% of spend
13
- CACHE MISSES $6.10 57 cache re-writes after the TTL ran out (5 min, or 1 h)
13
+ CACHE MISSES $6.10 57 cache re-writes after the TTL ran out (5 min since the last request, or 1 h)
14
+ main session $2.30 21x subagents $3.80 36x
15
+ Tip: idle subagents re-wrote their own context 36x (~$3.80). Set subagentPromptCacheTtl: "1h" ...
16
+ STARTING CONTEXT 31 subagents, first request median 38.2k tok, largest 131.0k (7f3a91c2/a1b2c3d4)
14
17
  REPEATED TOOL CALLS $9.80 12 streaks of >= 3 identical calls in a row
15
18
  TOOL ERROR STREAKS $4.30 5 streaks of >= 3 failing calls in a row
16
19
  Pro would have stopped this run at $3.12 / at 4 repeats (Bash x11 in 7f3a91c2, $2.40 after that).
@@ -23,16 +26,31 @@ Pro would have stopped this run at $3.12 / at 4 repeats (Bash x11 in 7f3a91c2, $
23
26
  agentcap run --quota 5% -- claude # subscription: stop at 5% of the weekly quota, or on a loop
24
27
  agentcap run --quota 10% --window 5h -- codex # same for Codex on a ChatGPT plan
25
28
  agentcap run --cap 2 -- codex exec "fix tests" # API key: $2 cap + loop/burn breaker
29
+ agentcap approve # raise a stopped job's limit by 50% (at most twice)
26
30
  ```
27
31
 
32
+ On a $20/month Codex plan, two code-review prompts used the whole 5-hour limit
33
+ ([Povilas Korop](https://x.com/PovilasKorop/status/2116114249655501050): $7.70 + $1.43 at API prices).
34
+ `--quota 10% --window 5h -- codex` stops the job before that.
35
+
36
+ Free tools like [claude-code-spend-stop](https://github.com/VedantBhayani/claude-code-spend-stop) and
37
+ [RelayPlane](https://relayplane.com) give you a free $ cap. AgentCap adds the loop breaker, a cap on
38
+ your subscription quota % and Codex support.
39
+
28
40
  - **Loop breaker.** Same tool call (name + input) 4 times in a row, or 8 failing tool calls in a
29
41
  row: the run is stopped (exit 4). On subscriptions it works without touching your login or
30
- traffic: Claude Code via an official `PreToolUse` hook (denies the 4th identical call, then
31
- SIGINT if the agent keeps going); Codex by reading its own rollout file (SIGINT). On API keys the
42
+ traffic: Claude Code via an official `PreToolUse` hook (denies the 4th identical call and ends
43
+ the turn; an interactive session stays open so you can `agentcap approve` or quit; headless
44
+ `claude -p` runs get SIGINT if they keep going); Codex by reading its own rollout file (SIGINT). On API keys the
32
45
  proxy also catches identical requests and `--max-burn` $/min spikes.
33
46
  - **Per-job quota %.** Stop one job at its share of the account's weekly or 5-hour limit.
34
47
  - **Evidence receipt.** Each stop prints and saves why (`same tool call 4 times in a row (Bash)`,
35
- `this job used 5.1% of the weekly quota`) as numbers only, never prompts.
48
+ `this job used 5.1% of the weekly quota`) and the last tool call's name, as numbers and tool
49
+ names only, never prompts or tool inputs.
50
+ - **Approve.** After a stop, `agentcap approve` (or `/agentcap:approve` in the plugin) raises the
51
+ limit by 50%, at most twice, and the run continues. This works for interactive Claude Code,
52
+ which stays open after a stop. Codex and headless `claude -p` jobs are stopped with SIGINT, so
53
+ there approve only helps before the limit is hit; after a stop it says so and changes nothing.
36
54
  - **Free** runs the same detectors in observe-only mode and prints what Pro would have done.
37
55
 
38
56
  Honest limits: Claude tool-error streaks are only caught on API-key runs (the subscription hook sees
@@ -105,10 +123,12 @@ integrated terminal behind `agentcap run --cap`, shows live run spend in the
105
123
  status bar, warns at 80% / 95%, and shows a modal when the cap (exit 3) or Pro's
106
124
  loop breaker (exit 4) stops the run. It needs the `agentcap` CLI above.
107
125
 
108
- It is **not on the VS Code Marketplace or Open VSX yet**. Install the `.vsix`
109
- attached to the [GitHub release](https://github.com/Blitz00X/agentcap/releases):
126
+ It is **not on the VS Code Marketplace or Open VSX yet**. [Download agentcap-0.2.0.vsix](https://agentcap.launchbench.studio/agentcap-0.2.0.vsix)
127
+ (sha256 `175213b0979019cb472752ad71e613a48c6a22e7d899b761093ab7eac9867e70`) and install it:
110
128
 
111
129
  ```bash
130
+ curl -LO https://agentcap.launchbench.studio/agentcap-0.2.0.vsix
131
+ sha256sum agentcap-0.2.0.vsix # compare with the sha256 above
112
132
  code --install-extension agentcap-0.2.0.vsix # VS Code
113
133
  cursor --install-extension agentcap-0.2.0.vsix # Cursor
114
134
  ```
@@ -273,7 +293,9 @@ agentcap quota # read-only: last seen usage (Fre
273
293
  statusline command that records the official `rate_limits` (`five_hour` / `seven_day`
274
294
  `used_percentage`, `resets_at`) and then runs **your own statusline command unchanged**,
275
295
  plus a `PreToolUse` hook that denies further tool calls with a clear reason once the job's
276
- share reaches the limit. If the agent does not stop, AgentCap sends it SIGINT. Exit code 3.
296
+ share reaches the limit and ends the turn (`continue: false`). An interactive session stays open
297
+ (run `agentcap approve` to continue, or quit). Headless `claude -p` runs, and sessions where
298
+ the hook never fired, get SIGINT. Exit code 3.
277
299
  - **Codex CLI:** AgentCap tails the `token_count` events Codex writes to
278
300
  `~/.codex/sessions/**/rollout-*.jsonl` (`rate_limits.primary/secondary.used_percent`,
279
301
  `window_minutes`, `resets_at`) and sends SIGINT at the limit. Exit code 3.
@@ -288,7 +310,7 @@ agentcap quota # read-only: last seen usage (Fre
288
310
  use in the same window counts against the job (AgentCap warns when it sees another session).
289
311
  Values arrive once per model response, so a job **can overshoot by up to one request**.
290
312
  Claude Code only reports `rate_limits` for Pro/Max logins and only in interactive sessions
291
- (the statusline does not run in `claude -p`). Codex's rollout format is undocumented and may change.
313
+ (the statusline does not run in `claude -p`). Codex's rollout format is undocumented and may change. Codex reports `used_percent` in whole percent, so a Codex cap under 1% cannot trigger until the job has used a full 1% (AgentCap warns at start). Use `--quota 1%` or more for Codex.
292
314
  **Verified so far on fixtures and fake CLIs only** (plus real Claude Code 2.1.197: the `--settings`
293
315
  layer, the chained statusline and the `PreToolUse` deny were checked against a local fake API);
294
316
  a check on a real Max / ChatGPT account is still pending.
@@ -461,6 +483,15 @@ agentcap run -- codex exec "..." # uses the $2 task cap from the budget
461
483
  agentcap run --quota -- claude # uses the 5% / 5h quota from the budget
462
484
  ```
463
485
 
486
+ Tools like agent-tree show you what your subagents are doing; AgentCap also stops them when they loop
487
+ (same tool call 4x in a row or 8 tool errors in a row, Pro). `agentcap waste` lists cache misses first:
488
+ resuming a session after the cache expired re-writes the whole prompt cache, so start a new session (or `/clear`) after a break.
489
+ Misses are split into main session and subagents. An idle subagent re-writes only its own context
490
+ (not the whole conversation, unless it is a forked subagent), at 1.25x normal input. If your
491
+ subagents sit idle for more than 5 minutes, set `subagentPromptCacheTtl: "1h"`. A 1 h write costs
492
+ 2x input, so it only pays off when the subagent is reused. `STARTING CONTEXT` shows how many tokens
493
+ each subagent's first request carries.
494
+
464
495
  - **Store:** `~/.local/share/agentcap/usage.db` (`$XDG_DATA_HOME` respected, mode 600). `import` is
465
496
  idempotent; it reads only `*.jsonl` session logs and AgentCap's own files. It never opens auth or
466
497
  credential files, never stores prompt or response text, and never touches network or OAuth traffic.
@@ -476,7 +507,8 @@ agentcap run --quota -- claude # uses the 5% / 5h quota from the budget
476
507
  are undocumented and change between CLI versions.
477
508
  - **`waste` heuristics:** a cache miss is a cache write larger than the cache read after the prompt
478
509
  cache TTL ran out (5 min; 1 h when written with `ephemeral_1h`; Codex: a big uncached prompt after
479
- > 5 min idle). Tool inputs are hashed, never printed. Not in local logs: `agent_summary` / title
510
+ > 5 min idle). Its $ is what the re-write cost above a cache read: 5 min writes at 1.25x input,
511
+ 1 h writes at 2x input (Anthropic list prices). Tool inputs are hashed, never printed. Not in local logs: `agent_summary` / title
480
512
  background calls and HTTP retries (planned: local OTel receiver).
481
513
 
482
514
  ### Pro extras: analytics (`agentcap report <view>`)
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "agentcap-cli"
7
- version = "0.2.0"
7
+ version = "0.2.2"
8
8
  description = "API-key spend guard for unattended Codex CLI, Gemini CLI and Claude Code runs: hard per-run cap, kills the process at the limit."
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.11"
@@ -2,6 +2,6 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
- __version__ = "0.2.0"
5
+ __version__ = "0.2.2"
6
6
 
7
7
  __all__ = ["__version__"]
@@ -229,6 +229,9 @@ def _build_parser() -> argparse.ArgumentParser:
229
229
  subparsers.add_parser(
230
230
  "quota", help="show subscription quota usage seen locally (read-only)"
231
231
  )
232
+ subparsers.add_parser(
233
+ "approve", help="raise the running quota job's limit by 50%% (Pro, at most twice)"
234
+ )
232
235
  subparsers.add_parser(
233
236
  "demo", help="run a simulated spend-cap demo against a fake local API"
234
237
  )
@@ -734,6 +737,11 @@ def main(argv: list[str] | None = None) -> int:
734
737
  return _status(args)
735
738
  if args.subcommand == "quota":
736
739
  return _quota(args)
740
+ if args.subcommand == "approve":
741
+ from .quota import approve_job
742
+
743
+ print(approve_job())
744
+ return 0
737
745
  if args.subcommand == "demo":
738
746
  return _demo(args)
739
747
  from . import cli_history
@@ -210,7 +210,8 @@ class _Pricer:
210
210
  except PricingError:
211
211
  self.store = None
212
212
 
213
- def usd(self, model: str, inp: int, cread: int, cwrite: int, out: int) -> str | None:
213
+ def usd(self, model: str, inp: int, cread: int, cwrite: int, out: int,
214
+ cwrite_1h: int = 0) -> str | None:
214
215
  if self.store is None or not model:
215
216
  return None
216
217
  price = None
@@ -225,7 +226,8 @@ class _Pricer:
225
226
  try:
226
227
  if price.provider == "anthropic":
227
228
  value = cost(
228
- price, inp + cread + cwrite, cread, out, cache_write_tokens=cwrite
229
+ price, inp + cread + cwrite, cread, out, cache_write_tokens=cwrite,
230
+ cache_write_1h_tokens=min(cwrite_1h, cwrite),
229
231
  )
230
232
  else: # OpenAI: cache writes bill as ordinary input
231
233
  value = cost(price, inp + cread + cwrite, cread, out)
@@ -15,6 +15,11 @@ only *reads* official local signals and stops the local agent:
15
15
  ``rate_limits`` into ``~/.codex/sessions/**/rollout-*.jsonl``; we tail them
16
16
  and SIGINT the child at the limit.
17
17
 
18
+ Interactive Claude Code is never signalled while the hook works: the deny
19
+ ends the turn (``continue: false``) and the session stays open, so the user
20
+ can ``agentcap approve`` (+50%, at most twice) or quit. Headless runs
21
+ (``claude -p``) and Codex are still SIGINT'd at the limit.
22
+
18
23
  Percentages are account-level, so parallel sessions are counted too (we warn
19
24
  when we detect them). Values update once per model response, so a job can
20
25
  overshoot by up to one request.
@@ -38,6 +43,58 @@ WARN_FRACTION = 0.8
38
43
  EXIT_QUOTA_EXCEEDED = 3
39
44
  EXIT_LOOP_DETECTED = 4
40
45
  BASELINE_MAX_AGE_S = 15 * 60
46
+ APPROVE_FACTOR = 1.5
47
+ APPROVE_MAX = 2
48
+
49
+
50
+ def is_headless_claude(argv: Sequence[str]) -> bool:
51
+ """``claude -p`` / ``--print`` runs non-interactively; nobody is there to approve."""
52
+
53
+ return any(a in ("-p", "--print") or a.startswith("--print=") for a in argv[1:])
54
+
55
+
56
+ def _running_jobs(root: Path) -> list[Path]:
57
+ jobs = root / "jobs"
58
+ if not jobs.is_dir():
59
+ return []
60
+ out = [d for d in jobs.iterdir()
61
+ if (d / "job.json").exists() and not (d / "done.json").exists()]
62
+ return sorted(out, key=lambda d: (d / "job.json").stat().st_mtime, reverse=True)
63
+
64
+
65
+ def approve_job(root: Path | None = None) -> str:
66
+ """Raise the newest running quota job's limit by 50% (max twice) and clear a loop stop."""
67
+
68
+ root = root or state_root()
69
+ running = _running_jobs(root)
70
+ if not running:
71
+ return "agentcap: no running quota job to approve."
72
+ d = running[0]
73
+ job = _read_json(d / "job.json") or {}
74
+ if not job.get("enforce"):
75
+ return "agentcap: this job is observe-only (Free); approve is a Pro feature."
76
+ if job.get("stopped"):
77
+ return ("agentcap: this job was already stopped (SIGINT), so approve cannot resume it. "
78
+ "Start it again with a higher --quota.")
79
+ n = int(job.get("approvals") or 0)
80
+ if n >= APPROVE_MAX:
81
+ return (f"agentcap: already approved twice (limit {float(job.get('quota', 0)):g}%); "
82
+ "start a new job if you really need more.")
83
+ new = round(float(job.get("quota", 0)) * APPROVE_FACTOR, 4)
84
+ job.update({"quota": new, "approvals": n + 1, "approved_at": time.time()})
85
+ _atomic_write(d / "job.json", job)
86
+ status = _read_json(d / "status.json")
87
+ if status:
88
+ status["limit_hit"] = False
89
+ status["quota"] = new
90
+ _atomic_write(d / "status.json", status)
91
+ for name in ("loop.json", "tools.json", "denies.log"):
92
+ try:
93
+ (d / name).unlink()
94
+ except OSError:
95
+ pass
96
+ return (f"agentcap: approved ({n + 1}/{APPROVE_MAX}): limit raised to {new:g}% of the "
97
+ f"{'weekly' if job.get('window') == 'week' else '5-hour'} quota; the run continues.")
41
98
  CLAUDE_KEYS = {"5h": "five_hour", "week": "seven_day"}
42
99
  CODEX_MINUTES = {"5h": 300, "week": 10080}
43
100
  STATE_ENV = "AGENTCAP_QUOTA_DIR"
@@ -425,7 +482,7 @@ def _loop_hook(job_dir: Path, payload: Mapping[str, Any]) -> str | None:
425
482
  d = _digest(name, payload.get("tool_input"))
426
483
  state = _read_json(job_dir / "tools.json") or {}
427
484
  count = int(state.get("count") or 0) + 1 if state.get("digest") == d else 1
428
- _atomic_write(job_dir / "tools.json", {"digest": d, "count": count})
485
+ _atomic_write(job_dir / "tools.json", {"digest": d, "count": count, "tool": name[:40]})
429
486
  if count < LOOP_REPEATS:
430
487
  return None
431
488
  enforce = bool((_read_json(job_dir / "job.json") or {}).get("enforce"))
@@ -434,10 +491,19 @@ def _loop_hook(job_dir: Path, payload: Mapping[str, Any]) -> str | None:
434
491
  "stopped": enforce, "ts": time.time()})
435
492
  if not enforce:
436
493
  return None
494
+ _note_deny(job_dir)
437
495
  return (f"agentcap loop breaker: {detail}. Stop now: do not call more tools; "
438
496
  "summarise what is done and what is left.")
439
497
 
440
498
 
499
+ def _note_deny(job_dir: Path) -> None:
500
+ try:
501
+ with open(job_dir / "denies.log", "a", encoding="utf-8") as fh:
502
+ fh.write(f"{time.time()}\n")
503
+ except OSError:
504
+ pass
505
+
506
+
441
507
  def _deny(stdout: TextIO, reason: str) -> int:
442
508
  json.dump(
443
509
  {
@@ -471,16 +537,12 @@ def hook_main(job_dir: Path, stdin: TextIO, stdout: TextIO) -> int:
471
537
  status = _read_json(job_dir / "status.json")
472
538
  if not status or not status.get("limit_hit"):
473
539
  return 0
474
- try:
475
- with open(job_dir / "denies.log", "a", encoding="utf-8") as fh:
476
- fh.write(f"{time.time()}\n")
477
- except OSError:
478
- pass
540
+ _note_deny(job_dir)
479
541
  reason = (
480
542
  f"agentcap quota mode: this job used {float(status.get('share', 0)):.1f}% of the "
481
543
  f"{'weekly' if status.get('window') == 'week' else '5-hour'} subscription quota "
482
544
  f"(limit {float(status.get('quota', 0)):g}%). Stop now: do not call more tools; "
483
- "summarise what is done and what is left."
545
+ "summarise what is done and what is left. (The user can run `agentcap approve` to raise it.)"
484
546
  )
485
547
  json.dump(
486
548
  {
@@ -633,6 +695,7 @@ class QuotaRunner:
633
695
  self.agent = detect_quota_agent(self.argv)
634
696
  if self.agent is None:
635
697
  raise ValueError("quota mode supports `claude` and `codex` only")
698
+ self.headless = self.agent == "codex" or is_headless_claude(self.argv)
636
699
  self.quota = quota
637
700
  self.window = window
638
701
  self.enforce = enforce
@@ -685,6 +748,12 @@ class QuotaRunner:
685
748
  pass
686
749
 
687
750
  def _stop(self) -> None:
751
+ job = _read_json(self.job_dir / "job.json") or {}
752
+ job["stopped"] = True # a signalled job cannot be resumed by `agentcap approve`
753
+ try:
754
+ _atomic_write(self.job_dir / "job.json", job)
755
+ except OSError:
756
+ pass
688
757
  self._signal(signal.SIGINT)
689
758
  deadline = time.time() + 5
690
759
  while self.child and self.child.poll() is None and time.time() < deadline:
@@ -711,7 +780,12 @@ class QuotaRunner:
711
780
  _atomic_write(settings, claude_settings(self.job_dir))
712
781
  argv = inject_claude_settings(argv, settings)
713
782
  else:
783
+ _atomic_write(self.job_dir / "job.json", {
784
+ "quota": self.quota, "window": self.window, "started_at": started,
785
+ "enforce": self.enforce, "agent": "codex",
786
+ })
714
787
  tailer = CodexTailer(self.sessions_dir, started)
788
+ self._tailer = tailer
715
789
  prior = tailer.last_reading_before(self.window)
716
790
  if prior and started - prior[0] <= BASELINE_MAX_AGE_S and (
717
791
  prior[1].resets_at is None or prior[1].resets_at > started
@@ -726,6 +800,9 @@ class QuotaRunner:
726
800
  else f"observe only (Free); Pro would stop it at {self.quota:g}%")
727
801
  + ". Read-only; your login and traffic are untouched."
728
802
  )
803
+ if self.agent == "codex" and self.quota < 1:
804
+ self._say(f"agentcap: WARNING: Codex reports quota in whole percent, so a {self.quota:g}% cap "
805
+ "cannot trigger until the job has used a full 1%. Use --quota 1% or more for Codex.")
729
806
  self.child = subprocess.Popen(argv, env=env, start_new_session=True, cwd=self.cwd)
730
807
 
731
808
  warned = hit = parallel = observed = no_data_warned = False
@@ -735,10 +812,22 @@ class QuotaRunner:
735
812
  reason = "exited"
736
813
  share = 0.0
737
814
  stopped = False
815
+ open_said = False
816
+ approvals = 0
738
817
  try:
739
818
  while True:
740
819
  code = self.child.poll()
741
820
  now = time.time()
821
+ jobnow = _read_json(self.job_dir / "job.json") or {}
822
+ if int(jobnow.get("approvals") or 0) > approvals and code is None:
823
+ approvals = int(jobnow["approvals"])
824
+ self.quota = float(jobnow.get("quota", self.quota))
825
+ hit = warned = stopped = open_said = False
826
+ hit_at = loop_at = None
827
+ loop_detail = None
828
+ self._say(f"agentcap: approved ({approvals}/{APPROVE_MAX}): limit is now "
829
+ f"{self.quota:g}%; continuing.")
830
+ self._event("quota_approved", share, approvals=approvals)
742
831
  if self.agent == "claude":
743
832
  status = _read_json(self.job_dir / "status.json") or {}
744
833
  if status.get("has_rate_limits"):
@@ -784,8 +873,10 @@ class QuotaRunner:
784
873
  and hit_at is not None and code is None
785
874
  ):
786
875
  denies = (self.job_dir / "denies.log").exists()
787
- if now - hit_at >= (self.claude_grace_s if denies else self.claude_grace_s * 3):
788
- self._stop()
876
+ if not self.headless and denies:
877
+ open_said = self._say_open(open_said, "the quota limit")
878
+ elif now - hit_at >= (self.claude_grace_s if denies else self.claude_grace_s * 3):
879
+ self._stop() # headless, or the hook never ran (fallback)
789
880
  stopped = True
790
881
  if loop_detail is None:
791
882
  if self.agent == "claude":
@@ -802,9 +893,14 @@ class QuotaRunner:
802
893
  self._stop()
803
894
  stopped = True
804
895
  if (loop_detail and self.enforce and not stopped and code is None
805
- and loop_at is not None and now - loop_at >= self.claude_grace_s):
806
- self._stop()
807
- stopped = True
896
+ and loop_at is not None):
897
+ denies = (self.job_dir / "denies.log").exists()
898
+ if not self.headless and denies:
899
+ open_said = self._say_open(open_said, "the loop breaker")
900
+ elif now - loop_at >= (self.claude_grace_s if denies or self.headless
901
+ else self.claude_grace_s * 3):
902
+ self._stop()
903
+ stopped = True
808
904
  self._live(share, observed, hit)
809
905
  if code is not None:
810
906
  break
@@ -827,8 +923,27 @@ class QuotaRunner:
827
923
  tracker.baseline_exact, tracker.resets_seen, parallel, observed,
828
924
  )
829
925
  self._receipt(self.summary)
926
+ try:
927
+ _atomic_write(self.job_dir / "done.json", {"ts": time.time(), "exit_code": code})
928
+ except OSError:
929
+ pass
830
930
  return code
831
931
 
932
+ def _say_open(self, said: bool, what: str) -> bool:
933
+ if not said:
934
+ self._say(f"agentcap: {what} stopped this turn (tool calls are denied). The session stays "
935
+ "open: run `agentcap approve` in another terminal to raise the limit by 50% "
936
+ f"(at most {APPROVE_MAX}x), or quit Claude Code.")
937
+ return True
938
+
939
+ def _last_tool(self) -> str | None:
940
+ t = _read_json(self.job_dir / "tools.json") or {}
941
+ name = t.get("tool")
942
+ if not name and self.agent == "codex":
943
+ tailer = getattr(self, "_tailer", None)
944
+ name = tailer.loop.tool if tailer is not None else None
945
+ return str(name)[:40] if name else None
946
+
832
947
  def _live(self, share: float, observed: bool, hit: bool) -> None:
833
948
  """Optional live status for editor integrations (AGENTCAP_QUOTA_LIVE)."""
834
949
 
@@ -861,6 +976,9 @@ class QuotaRunner:
861
976
  + (f" (limit {s.quota:g}%)" if self.enforce else "")
862
977
  + (f"; {'; '.join(notes)}" if notes else "") + "."
863
978
  )
979
+ last = self._last_tool()
980
+ if last:
981
+ self._say(f"agentcap: last tool call: {last}")
864
982
  if not self.enforce and s.share >= s.quota:
865
983
  self._say(
866
984
  f"agentcap: Pro's quota mode would have stopped this job at {s.quota:g}%. "
@@ -875,6 +993,7 @@ class QuotaRunner:
875
993
  "quota_pct": s.quota, "share_pct": s.share, "exit_code": s.exit_code,
876
994
  "reason": s.reason, "baseline_exact": s.baseline_exact,
877
995
  "parallel_sessions": s.parallel, "window_resets": s.resets_seen,
996
+ "last_tool": last,
878
997
  })
879
998
  except OSError:
880
999
  pass
@@ -26,6 +26,7 @@ from decimal import Decimal
26
26
  from pathlib import Path
27
27
  from typing import Any, Iterator
28
28
 
29
+ from .pricing import ANTHROPIC_WRITE_1H, ANTHROPIC_WRITE_5M
29
30
  from .history import _Pricer, _int, _lines, _safe_file, _ts, codex_lineage
30
31
 
31
32
  REPEAT_MIN = 3 # report streaks from this length
@@ -45,6 +46,7 @@ class CacheMiss:
45
46
  gap_s: float
46
47
  tokens: int
47
48
  usd: float
49
+ agent: str | None = None # None = main session, else the subagent / forked thread id
48
50
 
49
51
 
50
52
  @dataclass
@@ -68,6 +70,7 @@ class WasteReport:
68
70
  opus_usd: float = 0.0
69
71
  subagent_threads: int = 0
70
72
  cache_misses: list[CacheMiss] = field(default_factory=list)
73
+ subagent_first: list[tuple] = field(default_factory=list) # (source, session, agent, tokens)
71
74
  repeat_streaks: list[Streak] = field(default_factory=list)
72
75
  error_streaks: list[Streak] = field(default_factory=list)
73
76
 
@@ -103,6 +106,7 @@ class _Stream: # one session or one subagent/forked thread
103
106
  agent: str | None = None
104
107
  parent: str | None = None
105
108
  usd: float = 0.0
109
+ first_seen: bool = False
106
110
  calls: list[_Call] = field(default_factory=list)
107
111
  by_id: dict[str, _Call] = field(default_factory=dict)
108
112
 
@@ -185,9 +189,11 @@ def _claude_file(path: Path, pricer: _Pricer, since: float | None, rep: WasteRep
185
189
  u = m["usage"]
186
190
  inp, cr = _int(u.get("input_tokens")), _int(u.get("cache_read_input_tokens"))
187
191
  cw, out = _int(u.get("cache_creation_input_tokens")), _int(u.get("output_tokens"))
188
- usd = _f(pricer.usd(m["model"], inp, cr, cw, out))
189
- _account(rep, st, m["model"], usd)
190
192
  cc = u.get("cache_creation") if isinstance(u.get("cache_creation"), dict) else {}
193
+ cw1h = min(_int(cc.get("ephemeral_1h_input_tokens")), cw)
194
+ usd = _f(pricer.usd(m["model"], inp, cr, cw, out, cwrite_1h=cw1h))
195
+ _account(rep, st, m["model"], usd)
196
+ _first(rep, st, inp + cr + cw)
191
197
  prev = last.get(m["skey"])
192
198
  if prev is not None and cw > 0 and cw > cr:
193
199
  gap = m["ts"] - prev["ts"]
@@ -196,9 +202,11 @@ def _claude_file(path: Path, pricer: _Pricer, since: float | None, rep: WasteRep
196
202
  price = _price(pricer, m["model"])
197
203
  extra = 0.0
198
204
  if price is not None:
199
- wp = price.cache_write_per_mtok or price.input_per_mtok
200
- extra = float((Decimal(cw) * (wp - price.cached_input_per_mtok)) / Decimal(1_000_000))
201
- rep.cache_misses.append(CacheMiss("claude", st.session, m["ts"], gap, cw, extra))
205
+ # paid a cache write (5m: 1.25x input, 1h: 2x input) instead of a cache read
206
+ inr, rd = price.input_per_mtok, price.cached_input_per_mtok
207
+ extra = float((Decimal(cw - cw1h) * (inr * ANTHROPIC_WRITE_5M - rd)
208
+ + Decimal(cw1h) * (inr * ANTHROPIC_WRITE_1H - rd)) / Decimal(1_000_000))
209
+ rep.cache_misses.append(CacheMiss("claude", st.session, m["ts"], gap, cw, extra, st.agent))
202
210
  last[m["skey"]] = {"ts": m["ts"],
203
211
  "h1": _int(cc.get("ephemeral_1h_input_tokens")) > 0
204
212
  or (prev is not None and prev["h1"] and m["ts"] - prev["ts"] <= TTL_1H)}
@@ -304,6 +312,7 @@ def _codex_file(path: Path, pricer: _Pricer, since: float | None, rep: WasteRepo
304
312
  cw = min(_int(u.get("cache_write_input_tokens")), inp - cr)
305
313
  usd = _f(pricer.usd(model, inp - cr - cw, cr, cw, _int(u.get("output_tokens"))))
306
314
  _account(rep, st, model, usd)
315
+ _first(rep, st, inp)
307
316
  if st.calls and st.calls[-1].cost == 0.0 and st.calls[-1].ts <= ts:
308
317
  pending = [c for c in st.calls if c.cost == 0.0 and c.run_usd == st.calls[-1].run_usd]
309
318
  for c in pending: # the request that produced these calls
@@ -316,10 +325,18 @@ def _codex_file(path: Path, pricer: _Pricer, since: float | None, rep: WasteRepo
316
325
  if price is not None:
317
326
  extra = float(Decimal(uncached) * (price.input_per_mtok - price.cached_input_per_mtok)
318
327
  / Decimal(1_000_000))
319
- rep.cache_misses.append(CacheMiss("codex", st.session, ts, ts - last_ts, uncached, extra))
328
+ rep.cache_misses.append(CacheMiss("codex", st.session, ts, ts - last_ts, uncached, extra, st.agent))
320
329
  last_ts = ts
321
330
 
322
331
 
332
+ def _first(rep: WasteReport, st: _Stream, tokens: int) -> None:
333
+ """Remember a subagent's first-request context size (what it starts with)."""
334
+
335
+ if st.agent is not None and not st.first_seen:
336
+ st.first_seen = True
337
+ rep.subagent_first.append((st.source, st.session, st.agent, tokens))
338
+
339
+
323
340
  def _account(rep: WasteReport, st: _Stream, model: str, usd: float) -> None:
324
341
  st.usd += usd
325
342
  rep.total_usd += usd
@@ -407,15 +424,32 @@ def _who(s: Streak) -> str:
407
424
  def render(rep: WasteReport, period: str, top: int = 3) -> str:
408
425
  out = [f"agentcap waste - {period} - {rep.sessions} sessions - ${rep.total_usd:,.2f} API-equivalent",
409
426
  "(local Claude Code / Codex logs, read-only; $ are estimates at API list prices)", ""]
410
- out.append(f"SUBAGENTS {_m(rep.subagent_usd):>10} {rep.subagent_share * 100:4.0f}% of spend"
411
- f" in {rep.subagent_threads} subagent/forked threads")
412
- out.append(f"OPUS {_m(rep.opus_usd):>10} {rep.opus_share * 100:4.0f}% of spend")
413
427
  cm = sum(m.usd for m in rep.cache_misses)
428
+ main = [m for m in rep.cache_misses if m.agent is None]
429
+ sub = [m for m in rep.cache_misses if m.agent is not None]
430
+ mu, su = sum(m.usd for m in main), sum(m.usd for m in sub)
414
431
  out.append(f"CACHE MISSES {_m(cm):>10} {len(rep.cache_misses)} cache re-writes after the TTL ran out"
415
- " (5 min, or 1 h)")
432
+ " (5 min since the last request, or 1 h)")
433
+ out.append(f" main session {_m(mu):>9} {len(main)}x subagents {_m(su):>9} {len(sub)}x")
416
434
  for m in rep.cache_misses[:top]:
417
- out.append(f" {m.source:<6} {_sid(m.session):<8} idle {m.gap_s / 60:5.0f} min "
435
+ who = _sid(m.session) + (f"/{m.agent[:8]}" if m.agent else "")
436
+ out.append(f" {m.source:<6} {who:<17} idle {m.gap_s / 60:5.0f} min "
418
437
  f"{m.tokens / 1000:7.1f}k tok rewritten ${m.usd:.2f}")
438
+ if main:
439
+ out.append(f" Tip: you resumed {len(main)}x after the cache expired and paid ~{_m(mu)} to"
440
+ " re-write it. Start a new session (or /clear) instead of resuming after a break.")
441
+ if any(m.source == "claude" for m in sub):
442
+ out.append(f" Tip: idle subagents re-wrote their own context {len(sub)}x (~{_m(su)}). Set"
443
+ ' subagentPromptCacheTtl: "1h" in Claude Code settings (1h writes cost 2x input'
444
+ " instead of 1.25x, so it pays off when subagents sit idle > 5 min).")
445
+ out.append(f"SUBAGENTS {_m(rep.subagent_usd):>10} {rep.subagent_share * 100:4.0f}% of spend"
446
+ f" in {rep.subagent_threads} subagent/forked threads")
447
+ if rep.subagent_first:
448
+ toks = sorted(t for *_, t in rep.subagent_first)
449
+ biggest = max(rep.subagent_first, key=lambda x: x[3])
450
+ out.append(f"STARTING CONTEXT {len(toks)} subagents, first request median {toks[len(toks) // 2] / 1000:.1f}k tok,"
451
+ f" largest {biggest[3] / 1000:.1f}k ({_sid(biggest[1])}/{str(biggest[2])[:8]})")
452
+ out.append(f"OPUS {_m(rep.opus_usd):>10} {rep.opus_share * 100:4.0f}% of spend")
419
453
  rp = sum(s.usd for s in rep.repeat_streaks)
420
454
  out.append(f"REPEATED TOOL CALLS {_m(rp):>10} {len(rep.repeat_streaks)} streaks of >= {REPEAT_MIN}"
421
455
  " identical calls in a row")
@@ -160,3 +160,87 @@ def test_top_level_and_subcommand_help_render(capsys):
160
160
  with _p.raises(SystemExit) as e:
161
161
  main(argv)
162
162
  assert e.value.code == 0
163
+
164
+
165
+ def test_waste_cache_misses_come_first_with_suggestion(home, capsys):
166
+ assert cli.main(["waste", "--since", "all"]) == 0
167
+ lines = capsys.readouterr().out.splitlines()
168
+ heads = [i for i, l in enumerate(lines) if l.split(" ")[0].strip() in
169
+ ("CACHE MISSES", "SUBAGENTS", "OPUS", "REPEATED TOOL CALLS", "TOOL ERROR STREAKS")]
170
+ assert lines[heads[0]].startswith("CACHE MISSES")
171
+ tip = [l for l in lines if l.strip().startswith("Tip:")]
172
+ assert tip and "new session" in tip[0] and "/clear" in tip[0]
173
+ assert tip[0] == lines[heads[1] - 1] # tip closes the cache section
174
+
175
+
176
+ # ---------------------------------------------- 0.2.1: miss split, 1h tip, pricing
177
+ def _msg(ts, sess, mid, cw, cr=0, h1=0, agent=None, model="claude-sonnet-4-5"):
178
+ o = {"type": "assistant", "timestamp": ts, "sessionId": sess, "uuid": "u" + mid, "requestId": "r" + mid,
179
+ "isSidechain": agent is not None,
180
+ "message": {"id": mid, "model": model, "role": "assistant", "content": [{"type": "text", "text": "x"}],
181
+ "usage": {"input_tokens": 10, "cache_read_input_tokens": cr,
182
+ "cache_creation_input_tokens": cw, "output_tokens": 10,
183
+ "cache_creation": {"ephemeral_5m_input_tokens": cw - h1,
184
+ "ephemeral_1h_input_tokens": h1}}}}
185
+ if agent:
186
+ o["agentId"] = agent
187
+ return json.dumps(o)
188
+
189
+
190
+ @pytest.fixture
191
+ def split_home(tmp_path):
192
+ proj = tmp_path / ".claude" / "projects" / "-w"
193
+ sub = proj / "s1" / "subagents"
194
+ sub.mkdir(parents=True)
195
+ (proj / "s1.jsonl").write_text("\n".join([
196
+ _msg("2026-10-29T09:00:00Z", "s1", "m1", 40000),
197
+ _msg("2026-10-29T09:10:00Z", "s1", "m2", 40000), # 10 min idle: main miss (5m)
198
+ ]) + "\n")
199
+ (sub / "agent-z9.jsonl").write_text("\n".join([
200
+ _msg("2026-10-29T09:00:30Z", "s1", "a1", 12000, agent="z9"), # first request: 12k context
201
+ _msg("2026-10-29T09:20:30Z", "s1", "a2", 100000, agent="z9"), # 20 min idle: subagent miss
202
+ ]) + "\n")
203
+ return tmp_path
204
+
205
+
206
+ def test_waste_misses_split_main_vs_subagent(split_home):
207
+ w = waste.scan(home=split_home)
208
+ main = [m for m in w.cache_misses if m.agent is None]
209
+ sub = [m for m in w.cache_misses if m.agent == "z9"]
210
+ assert len(main) == 1 and len(sub) == 1
211
+ text = waste.render(w, "all")
212
+ assert "main session" in text and "subagents" in text
213
+ assert 'subagentPromptCacheTtl: "1h"' in text
214
+
215
+
216
+ def test_waste_miss_cost_uses_5m_write_rate(split_home):
217
+ # sonnet-4-5: input $3/M, cache read $0.30/M; a 5-minute write is 1.25x input = $3.75/M
218
+ w = waste.scan(home=split_home)
219
+ main = next(m for m in w.cache_misses if m.agent is None)
220
+ assert main.usd == pytest.approx(40000 * (3.75 - 0.30) / 1e6, rel=1e-6)
221
+
222
+
223
+ def test_waste_miss_cost_uses_1h_write_rate(tmp_path):
224
+ proj = tmp_path / ".claude" / "projects" / "-w"
225
+ proj.mkdir(parents=True)
226
+ (proj / "s2.jsonl").write_text("\n".join([
227
+ _msg("2026-10-29T09:00:00Z", "s2", "m1", 40000, h1=40000),
228
+ _msg("2026-10-29T11:00:00Z", "s2", "m2", 40000, h1=40000), # 2 h idle on 1h TTL
229
+ ]) + "\n")
230
+ w = waste.scan(home=tmp_path)
231
+ assert len(w.cache_misses) == 1
232
+ assert w.cache_misses[0].usd == pytest.approx(40000 * (6.0 - 0.30) / 1e6, rel=1e-6) # 2x input
233
+
234
+
235
+ def test_waste_subagent_starting_context(split_home):
236
+ w = waste.scan(home=split_home)
237
+ assert w.subagent_first == [("claude", "s1", "z9", 12010)]
238
+ text = waste.render(w, "all")
239
+ assert "STARTING CONTEXT" in text and "12.0k" in text
240
+
241
+
242
+ def test_pricer_bills_1h_writes_at_2x():
243
+ p = history._Pricer()
244
+ five = Decimal(p.usd("claude-sonnet-4-5", 0, 0, 1_000_000, 0))
245
+ hour = Decimal(p.usd("claude-sonnet-4-5", 0, 0, 1_000_000, 0, cwrite_1h=1_000_000))
246
+ assert five == Decimal("3.75") and hour == Decimal("6")
@@ -242,3 +242,57 @@ def test_session_start_prunes_old_loop_state(env):
242
242
  _os.utime(other, (_t.time() - week, _t.time() - week))
243
243
  hook("start", {"session_id": SID, "cwd": "/w", "hook_event_name": "SessionStart"})
244
244
  assert not old.exists() and fresh.exists() and other.exists()
245
+
246
+
247
+ # ------------------------------------------- 0.2.1: end turn, approve, last tool
248
+ def _at_limit(env):
249
+ pro(env)
250
+ statusline(sl_payload(40.0)); cmd("quota", "4%"); statusline(sl_payload(44.5))
251
+
252
+
253
+ def test_quota_deny_ends_the_turn(env):
254
+ _at_limit(env)
255
+ d = hook("pre", PRE)
256
+ assert d["continue"] is False and d["hookSpecificOutput"]["permissionDecision"] == "deny"
257
+ assert "/agentcap:approve" in d["stopReason"]
258
+
259
+
260
+ def test_approve_raises_by_half_twice(env):
261
+ _at_limit(env)
262
+ assert hook("pre", PRE)["continue"] is False
263
+ out = cmd("approve")
264
+ assert "6%" in out and "1/2" in out
265
+ assert hook("pre", dict(PRE, tool_input={"command": "next"})) is None
266
+ assert "9%" in cmd("approve")
267
+ assert "already approved twice" in cmd("approve")
268
+ assert cc.load(SID)["quota"] == 9.0
269
+
270
+
271
+ def test_approve_is_pro_only(env):
272
+ statusline(sl_payload(40.0)); cmd("quota", "4%")
273
+ assert "Pro" in cmd("approve")
274
+ assert cc.load(SID)["quota"] == 4.0
275
+
276
+
277
+ def test_approve_resets_loop_streak(env):
278
+ pro(env)
279
+ for _ in range(4):
280
+ d = _pre()
281
+ assert d["continue"] is False
282
+ statusline(sl_payload(1.0)); cmd("quota", "50%")
283
+ cmd("approve")
284
+ assert _pre() is None
285
+
286
+
287
+ def test_stop_receipt_has_last_tool(env):
288
+ pro(env)
289
+ statusline(sl_payload(1.0)); cmd("quota", "5%"); statusline(sl_payload(2.0))
290
+ hook("pre", dict(PRE, tool_name="Edit", tool_input={"file_path": "/secret"}))
291
+ hook("stop", {"session_id": SID, "hook_event_name": "Stop", "cwd": "/w"})
292
+ rec = json.loads((cc.cc_dir() / "receipts.jsonl").read_text().splitlines()[-1])
293
+ assert rec["last_tool"] == "Edit" and "/secret" not in json.dumps(rec)
294
+
295
+
296
+ def test_approve_command_file_exists():
297
+ text = (ROOT / "commands" / "approve.md").read_text()
298
+ assert "approve" in text and "disable-model-invocation: true" in text
@@ -321,7 +321,7 @@ def test_live_status_file_for_editor(fakebin, tmp_path, monkeypatch):
321
321
  def test_e2e_claude_sigint_when_model_ignores_stop(fakebin, tmp_path, monkeypatch):
322
322
  monkeypatch.setenv("FAKE_IGNORE_STOP", "1")
323
323
  monkeypatch.setenv("FAKE_N", "200")
324
- r, events, err = make_runner(["claude"], tmp_path, grace=0.5)
324
+ r, events, err = make_runner(["claude", "-p", "fix"], tmp_path, grace=0.5)
325
325
  t0 = time.time()
326
326
  assert r.run() == 3
327
327
  assert time.time() - t0 < 20
@@ -494,3 +494,134 @@ def test_e2e_claude_loop_breaker_denies_and_stops(fakebin, tmp_path, monkeypatch
494
494
  assert r.run() == 4
495
495
  assert r.summary.reason == "loop_detected"
496
496
  assert "same tool call 4 times" in err.getvalue()
497
+
498
+
499
+ # ------------------------------------------- 0.2.1: interactive stop, approve
500
+ def test_e2e_interactive_claude_is_not_sigint_when_hook_denies(fakebin, tmp_path, monkeypatch):
501
+ # interactive session: the hook denies and ends the turn; agentcap must not kill the session
502
+ monkeypatch.setenv("FAKE_IGNORE_STOP", "1")
503
+ monkeypatch.setenv("FAKE_N", "14")
504
+ r, events, err = make_runner(["claude"], tmp_path, grace=0.2)
505
+ sent = []
506
+ monkeypatch.setattr(r, "_signal", lambda sig: sent.append(sig))
507
+ assert r.run() == 3
508
+ assert sent == []
509
+ assert "session stays open" in err.getvalue()
510
+
511
+
512
+ def test_e2e_headless_claude_still_sigint(fakebin, tmp_path, monkeypatch):
513
+ monkeypatch.setenv("FAKE_IGNORE_STOP", "1")
514
+ monkeypatch.setenv("FAKE_N", "200")
515
+ r, events, err = make_runner(["claude", "--print", "fix"], tmp_path, grace=0.3)
516
+ assert r.run() == 3
517
+
518
+
519
+ def test_is_headless_claude():
520
+ assert q.is_headless_claude(["claude", "-p", "x"])
521
+ assert q.is_headless_claude(["claude", "--print"])
522
+ assert not q.is_headless_claude(["claude"])
523
+ assert not q.is_headless_claude(["claude", "--resume"])
524
+
525
+
526
+ def _job(tmp_path, **kw):
527
+ root = tmp_path / "state"
528
+ d = root / "jobs" / "q1-1"
529
+ d.mkdir(parents=True)
530
+ job = {"enforce": True, "quota": 4.0, "window": "week", "started_at": 1}
531
+ job.update(kw)
532
+ (d / "job.json").write_text(json.dumps(job))
533
+ (d / "status.json").write_text(json.dumps({"limit_hit": True, "share": 4.2, "quota": 4.0}))
534
+ return root, d
535
+
536
+
537
+ def test_approve_raises_quota_50pct_at_most_twice(tmp_path):
538
+ root, d = _job(tmp_path)
539
+ (d / "loop.json").write_text("{}"); (d / "tools.json").write_text("{}")
540
+ msg = q.approve_job(root)
541
+ assert "6%" in msg and "1/2" in msg
542
+ job = json.loads((d / "job.json").read_text())
543
+ assert job["quota"] == 6.0 and job["approvals"] == 1
544
+ assert json.loads((d / "status.json").read_text())["limit_hit"] is False
545
+ assert not (d / "loop.json").exists() and not (d / "tools.json").exists()
546
+ assert "9%" in q.approve_job(root)
547
+ assert "already approved twice" in q.approve_job(root)
548
+ assert json.loads((d / "job.json").read_text())["quota"] == 9.0
549
+
550
+
551
+ def test_approve_free_job_and_no_job(tmp_path):
552
+ assert "no running" in q.approve_job(tmp_path / "none")
553
+ root, d = _job(tmp_path, enforce=False)
554
+ assert "Pro" in q.approve_job(root)
555
+
556
+
557
+ def test_approve_skips_finished_jobs(tmp_path):
558
+ root, d = _job(tmp_path)
559
+ (d / "done.json").write_text("{}")
560
+ assert "no running" in q.approve_job(root)
561
+
562
+
563
+ def test_hook_records_last_tool_name_only(tmp_path):
564
+ (tmp_path / "job.json").write_text(json.dumps({"enforce": True, "quota": 5, "window": "week"}))
565
+ _hook(tmp_path, tool="Edit", cmd="secret-arg")
566
+ t = json.loads((tmp_path / "tools.json").read_text())
567
+ assert t["tool"] == "Edit" and "secret-arg" not in json.dumps(t)
568
+
569
+
570
+ def test_receipt_has_last_tool(fakebin, tmp_path):
571
+ r, events, err = make_runner(["claude", "-p", "fix"], tmp_path)
572
+ assert r.run() == 3
573
+ receipt = json.loads(next((tmp_path / "receipts").glob("*.json")).read_text())
574
+ assert receipt["last_tool"] == "Bash"
575
+ assert "last tool call: Bash" in err.getvalue()
576
+
577
+
578
+ def test_runner_picks_up_approval(fakebin, tmp_path, monkeypatch):
579
+ # approve while running: quota goes 5 -> 7.5, the job continues past 5%
580
+ monkeypatch.setenv("FAKE_N", "7")
581
+ r, events, err = make_runner(["claude", "-p", "fix"], tmp_path, quota=3.0)
582
+ orig = r._live
583
+ def live(share, observed, hit):
584
+ if hit and not getattr(r, "_did", False):
585
+ r._did = True
586
+ q.approve_job(r.job_root)
587
+ return orig(share, observed, hit)
588
+ monkeypatch.setattr(r, "_live", live)
589
+ code = r.run()
590
+ assert "approved" in err.getvalue()
591
+ assert r.summary.quota == 4.5
592
+
593
+
594
+ def test_cli_approve(tmp_path, monkeypatch, capsys):
595
+ from agentcap import cli
596
+ root, d = _job(tmp_path)
597
+ monkeypatch.setenv("AGENTCAP_QUOTA_DIR", str(root))
598
+ assert cli.main(["approve"]) == 0
599
+ assert "6%" in capsys.readouterr().out
600
+
601
+
602
+ def test_approve_refuses_a_job_already_stopped_by_sigint(tmp_path):
603
+ # real Codex run 30 Oct: approve after the SIGINT said "the run continues" but the job was ending
604
+ root, d = _job(tmp_path, agent="codex", stopped=True)
605
+ msg = q.approve_job(root)
606
+ assert "already stopped" in msg and "continues" not in msg
607
+ assert json.loads((d / "job.json").read_text())["quota"] == 4.0
608
+
609
+
610
+ def test_codex_stop_marks_job_stopped(fakebin, tmp_path):
611
+ r, events, err = make_runner(["codex"], tmp_path)
612
+ assert r.run() == 3
613
+ assert json.loads((r.job_dir / "job.json").read_text())["stopped"] is True
614
+
615
+
616
+ def test_codex_sub_1pct_quota_warns_whole_percent(fakebin, tmp_path, monkeypatch):
617
+ monkeypatch.setenv("FAKE_N", "2")
618
+ r, events, err = make_runner(["codex"], tmp_path, quota=0.5)
619
+ r.run()
620
+ assert "whole percent" in err.getvalue()
621
+
622
+
623
+ def test_codex_1pct_quota_no_whole_percent_warning(fakebin, tmp_path, monkeypatch):
624
+ monkeypatch.setenv("FAKE_N", "2")
625
+ r, events, err = make_runner(["codex"], tmp_path, quota=1.0)
626
+ r.run()
627
+ assert "whole percent" not in err.getvalue()
File without changes
File without changes