agentcap-cli 0.2.0__tar.gz → 0.2.1__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.1}/PKG-INFO +39 -9
  2. {agentcap_cli-0.2.0 → agentcap_cli-0.2.1}/README.md +38 -8
  3. {agentcap_cli-0.2.0 → agentcap_cli-0.2.1}/pyproject.toml +1 -1
  4. {agentcap_cli-0.2.0 → agentcap_cli-0.2.1}/src/agentcap/__init__.py +1 -1
  5. {agentcap_cli-0.2.0 → agentcap_cli-0.2.1}/src/agentcap/cli.py +8 -0
  6. {agentcap_cli-0.2.0 → agentcap_cli-0.2.1}/src/agentcap/history.py +4 -2
  7. {agentcap_cli-0.2.0 → agentcap_cli-0.2.1}/src/agentcap/quota.py +119 -12
  8. {agentcap_cli-0.2.0 → agentcap_cli-0.2.1}/src/agentcap/waste.py +45 -11
  9. {agentcap_cli-0.2.0 → agentcap_cli-0.2.1}/tests/test_agents.py +84 -0
  10. {agentcap_cli-0.2.0 → agentcap_cli-0.2.1}/tests/test_cc_plugin.py +54 -0
  11. {agentcap_cli-0.2.0 → agentcap_cli-0.2.1}/tests/test_quota.py +104 -1
  12. {agentcap_cli-0.2.0 → agentcap_cli-0.2.1}/.gitignore +0 -0
  13. {agentcap_cli-0.2.0 → agentcap_cli-0.2.1}/LICENSE +0 -0
  14. {agentcap_cli-0.2.0 → agentcap_cli-0.2.1}/src/agentcap/adapters.py +0 -0
  15. {agentcap_cli-0.2.0 → agentcap_cli-0.2.1}/src/agentcap/alerts.py +0 -0
  16. {agentcap_cli-0.2.0 → agentcap_cli-0.2.1}/src/agentcap/analytics.py +0 -0
  17. {agentcap_cli-0.2.0 → agentcap_cli-0.2.1}/src/agentcap/budget.py +0 -0
  18. {agentcap_cli-0.2.0 → agentcap_cli-0.2.1}/src/agentcap/clamp.py +0 -0
  19. {agentcap_cli-0.2.0 → agentcap_cli-0.2.1}/src/agentcap/cli_history.py +0 -0
  20. {agentcap_cli-0.2.0 → agentcap_cli-0.2.1}/src/agentcap/data/pricing.json +0 -0
  21. {agentcap_cli-0.2.0 → agentcap_cli-0.2.1}/src/agentcap/demo.py +0 -0
  22. {agentcap_cli-0.2.0 → agentcap_cli-0.2.1}/src/agentcap/devtools/__init__.py +0 -0
  23. {agentcap_cli-0.2.0 → agentcap_cli-0.2.1}/src/agentcap/devtools/fake_upstream.py +0 -0
  24. {agentcap_cli-0.2.0 → agentcap_cli-0.2.1}/src/agentcap/estimate.py +0 -0
  25. {agentcap_cli-0.2.0 → agentcap_cli-0.2.1}/src/agentcap/eta.py +0 -0
  26. {agentcap_cli-0.2.0 → agentcap_cli-0.2.1}/src/agentcap/ledger.py +0 -0
  27. {agentcap_cli-0.2.0 → agentcap_cli-0.2.1}/src/agentcap/license.py +0 -0
  28. {agentcap_cli-0.2.0 → agentcap_cli-0.2.1}/src/agentcap/loop.py +0 -0
  29. {agentcap_cli-0.2.0 → agentcap_cli-0.2.1}/src/agentcap/plans.py +0 -0
  30. {agentcap_cli-0.2.0 → agentcap_cli-0.2.1}/src/agentcap/pricing.py +0 -0
  31. {agentcap_cli-0.2.0 → agentcap_cli-0.2.1}/src/agentcap/proxy.py +0 -0
  32. {agentcap_cli-0.2.0 → agentcap_cli-0.2.1}/src/agentcap/report.py +0 -0
  33. {agentcap_cli-0.2.0 → agentcap_cli-0.2.1}/src/agentcap/runner.py +0 -0
  34. {agentcap_cli-0.2.0 → agentcap_cli-0.2.1}/src/agentcap/upstreams.py +0 -0
  35. {agentcap_cli-0.2.0 → agentcap_cli-0.2.1}/src/agentcap/usage.py +0 -0
  36. {agentcap_cli-0.2.0 → agentcap_cli-0.2.1}/tests/conftest.py +0 -0
  37. {agentcap_cli-0.2.0 → agentcap_cli-0.2.1}/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.1}/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.1}/tests/fixtures/agents/claude/projects/-home-dev-shop/sess-p.jsonl +0 -0
  40. {agentcap_cli-0.2.0 → agentcap_cli-0.2.1}/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.1}/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.1}/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.1}/tests/fixtures/history/claude/.credentials.json +0 -0
  44. {agentcap_cli-0.2.0 → agentcap_cli-0.2.1}/tests/fixtures/history/claude/projects/-home-dev-shop/1f0c-sess-a.jsonl +0 -0
  45. {agentcap_cli-0.2.0 → agentcap_cli-0.2.1}/tests/fixtures/history/codex/auth.json +0 -0
  46. {agentcap_cli-0.2.0 → agentcap_cli-0.2.1}/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.1}/tests/license_support.py +0 -0
  48. {agentcap_cli-0.2.0 → agentcap_cli-0.2.1}/tests/proxy_support.py +0 -0
  49. {agentcap_cli-0.2.0 → agentcap_cli-0.2.1}/tests/test_adapters.py +0 -0
  50. {agentcap_cli-0.2.0 → agentcap_cli-0.2.1}/tests/test_alerts.py +0 -0
  51. {agentcap_cli-0.2.0 → agentcap_cli-0.2.1}/tests/test_analytics.py +0 -0
  52. {agentcap_cli-0.2.0 → agentcap_cli-0.2.1}/tests/test_anthropic_proxy.py +0 -0
  53. {agentcap_cli-0.2.0 → agentcap_cli-0.2.1}/tests/test_anthropic_units.py +0 -0
  54. {agentcap_cli-0.2.0 → agentcap_cli-0.2.1}/tests/test_budget.py +0 -0
  55. {agentcap_cli-0.2.0 → agentcap_cli-0.2.1}/tests/test_clamp.py +0 -0
  56. {agentcap_cli-0.2.0 → agentcap_cli-0.2.1}/tests/test_claude_adapter_and_tiers.py +0 -0
  57. {agentcap_cli-0.2.0 → agentcap_cli-0.2.1}/tests/test_cli.py +0 -0
  58. {agentcap_cli-0.2.0 → agentcap_cli-0.2.1}/tests/test_e2e_claude.py +0 -0
  59. {agentcap_cli-0.2.0 → agentcap_cli-0.2.1}/tests/test_estimate.py +0 -0
  60. {agentcap_cli-0.2.0 → agentcap_cli-0.2.1}/tests/test_history.py +0 -0
  61. {agentcap_cli-0.2.0 → agentcap_cli-0.2.1}/tests/test_ledger.py +0 -0
  62. {agentcap_cli-0.2.0 → agentcap_cli-0.2.1}/tests/test_license.py +0 -0
  63. {agentcap_cli-0.2.0 → agentcap_cli-0.2.1}/tests/test_loop.py +0 -0
  64. {agentcap_cli-0.2.0 → agentcap_cli-0.2.1}/tests/test_pricing.py +0 -0
  65. {agentcap_cli-0.2.0 → agentcap_cli-0.2.1}/tests/test_proxy_cancel.py +0 -0
  66. {agentcap_cli-0.2.0 → agentcap_cli-0.2.1}/tests/test_proxy_core.py +0 -0
  67. {agentcap_cli-0.2.0 → agentcap_cli-0.2.1}/tests/test_proxy_extras.py +0 -0
  68. {agentcap_cli-0.2.0 → agentcap_cli-0.2.1}/tests/test_proxy_streaming.py +0 -0
  69. {agentcap_cli-0.2.0 → agentcap_cli-0.2.1}/tests/test_report_cli.py +0 -0
  70. {agentcap_cli-0.2.0 → agentcap_cli-0.2.1}/tests/test_runaway.py +0 -0
  71. {agentcap_cli-0.2.0 → agentcap_cli-0.2.1}/tests/test_runner.py +0 -0
  72. {agentcap_cli-0.2.0 → agentcap_cli-0.2.1}/tests/test_upstreams.py +0 -0
  73. {agentcap_cli-0.2.0 → agentcap_cli-0.2.1}/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.1
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,29 @@ 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.
66
82
  - **Free** runs the same detectors in observe-only mode and prints what Pro would have done.
67
83
 
68
84
  Honest limits: Claude tool-error streaks are only caught on API-key runs (the subscription hook sees
@@ -135,10 +151,12 @@ integrated terminal behind `agentcap run --cap`, shows live run spend in the
135
151
  status bar, warns at 80% / 95%, and shows a modal when the cap (exit 3) or Pro's
136
152
  loop breaker (exit 4) stops the run. It needs the `agentcap` CLI above.
137
153
 
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):
154
+ 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)
155
+ (sha256 `175213b0979019cb472752ad71e613a48c6a22e7d899b761093ab7eac9867e70`) and install it:
140
156
 
141
157
  ```bash
158
+ curl -LO https://agentcap.launchbench.studio/agentcap-0.2.0.vsix
159
+ sha256sum agentcap-0.2.0.vsix # compare with the sha256 above
142
160
  code --install-extension agentcap-0.2.0.vsix # VS Code
143
161
  cursor --install-extension agentcap-0.2.0.vsix # Cursor
144
162
  ```
@@ -303,7 +321,9 @@ agentcap quota # read-only: last seen usage (Fre
303
321
  statusline command that records the official `rate_limits` (`five_hour` / `seven_day`
304
322
  `used_percentage`, `resets_at`) and then runs **your own statusline command unchanged**,
305
323
  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.
324
+ share reaches the limit and ends the turn (`continue: false`). An interactive session stays open
325
+ (run `agentcap approve` to continue, or quit). Headless `claude -p` runs, and sessions where
326
+ the hook never fired, get SIGINT. Exit code 3.
307
327
  - **Codex CLI:** AgentCap tails the `token_count` events Codex writes to
308
328
  `~/.codex/sessions/**/rollout-*.jsonl` (`rate_limits.primary/secondary.used_percent`,
309
329
  `window_minutes`, `resets_at`) and sends SIGINT at the limit. Exit code 3.
@@ -491,6 +511,15 @@ agentcap run -- codex exec "..." # uses the $2 task cap from the budget
491
511
  agentcap run --quota -- claude # uses the 5% / 5h quota from the budget
492
512
  ```
493
513
 
514
+ Tools like agent-tree show you what your subagents are doing; AgentCap also stops them when they loop
515
+ (same tool call 4x in a row or 8 tool errors in a row, Pro). `agentcap waste` lists cache misses first:
516
+ resuming a session after the cache expired re-writes the whole prompt cache, so start a new session (or `/clear`) after a break.
517
+ Misses are split into main session and subagents. An idle subagent re-writes only its own context
518
+ (not the whole conversation, unless it is a forked subagent), at 1.25x normal input. If your
519
+ subagents sit idle for more than 5 minutes, set `subagentPromptCacheTtl: "1h"`. A 1 h write costs
520
+ 2x input, so it only pays off when the subagent is reused. `STARTING CONTEXT` shows how many tokens
521
+ each subagent's first request carries.
522
+
494
523
  - **Store:** `~/.local/share/agentcap/usage.db` (`$XDG_DATA_HOME` respected, mode 600). `import` is
495
524
  idempotent; it reads only `*.jsonl` session logs and AgentCap's own files. It never opens auth or
496
525
  credential files, never stores prompt or response text, and never touches network or OAuth traffic.
@@ -506,7 +535,8 @@ agentcap run --quota -- claude # uses the 5% / 5h quota from the budget
506
535
  are undocumented and change between CLI versions.
507
536
  - **`waste` heuristics:** a cache miss is a cache write larger than the cache read after the prompt
508
537
  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
538
+ > 5 min idle). Its $ is what the re-write cost above a cache read: 5 min writes at 1.25x input,
539
+ 1 h writes at 2x input (Anthropic list prices). Tool inputs are hashed, never printed. Not in local logs: `agent_summary` / title
510
540
  background calls and HTTP retries (planned: local OTel receiver).
511
541
 
512
542
  ### 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,29 @@ 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.
36
52
  - **Free** runs the same detectors in observe-only mode and prints what Pro would have done.
37
53
 
38
54
  Honest limits: Claude tool-error streaks are only caught on API-key runs (the subscription hook sees
@@ -105,10 +121,12 @@ integrated terminal behind `agentcap run --cap`, shows live run spend in the
105
121
  status bar, warns at 80% / 95%, and shows a modal when the cap (exit 3) or Pro's
106
122
  loop breaker (exit 4) stops the run. It needs the `agentcap` CLI above.
107
123
 
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):
124
+ 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)
125
+ (sha256 `175213b0979019cb472752ad71e613a48c6a22e7d899b761093ab7eac9867e70`) and install it:
110
126
 
111
127
  ```bash
128
+ curl -LO https://agentcap.launchbench.studio/agentcap-0.2.0.vsix
129
+ sha256sum agentcap-0.2.0.vsix # compare with the sha256 above
112
130
  code --install-extension agentcap-0.2.0.vsix # VS Code
113
131
  cursor --install-extension agentcap-0.2.0.vsix # Cursor
114
132
  ```
@@ -273,7 +291,9 @@ agentcap quota # read-only: last seen usage (Fre
273
291
  statusline command that records the official `rate_limits` (`five_hour` / `seven_day`
274
292
  `used_percentage`, `resets_at`) and then runs **your own statusline command unchanged**,
275
293
  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.
294
+ share reaches the limit and ends the turn (`continue: false`). An interactive session stays open
295
+ (run `agentcap approve` to continue, or quit). Headless `claude -p` runs, and sessions where
296
+ the hook never fired, get SIGINT. Exit code 3.
277
297
  - **Codex CLI:** AgentCap tails the `token_count` events Codex writes to
278
298
  `~/.codex/sessions/**/rollout-*.jsonl` (`rate_limits.primary/secondary.used_percent`,
279
299
  `window_minutes`, `resets_at`) and sends SIGINT at the limit. Exit code 3.
@@ -461,6 +481,15 @@ agentcap run -- codex exec "..." # uses the $2 task cap from the budget
461
481
  agentcap run --quota -- claude # uses the 5% / 5h quota from the budget
462
482
  ```
463
483
 
484
+ Tools like agent-tree show you what your subagents are doing; AgentCap also stops them when they loop
485
+ (same tool call 4x in a row or 8 tool errors in a row, Pro). `agentcap waste` lists cache misses first:
486
+ resuming a session after the cache expired re-writes the whole prompt cache, so start a new session (or `/clear`) after a break.
487
+ Misses are split into main session and subagents. An idle subagent re-writes only its own context
488
+ (not the whole conversation, unless it is a forked subagent), at 1.25x normal input. If your
489
+ subagents sit idle for more than 5 minutes, set `subagentPromptCacheTtl: "1h"`. A 1 h write costs
490
+ 2x input, so it only pays off when the subagent is reused. `STARTING CONTEXT` shows how many tokens
491
+ each subagent's first request carries.
492
+
464
493
  - **Store:** `~/.local/share/agentcap/usage.db` (`$XDG_DATA_HOME` respected, mode 600). `import` is
465
494
  idempotent; it reads only `*.jsonl` session logs and AgentCap's own files. It never opens auth or
466
495
  credential files, never stores prompt or response text, and never touches network or OAuth traffic.
@@ -476,7 +505,8 @@ agentcap run --quota -- claude # uses the 5% / 5h quota from the budget
476
505
  are undocumented and change between CLI versions.
477
506
  - **`waste` heuristics:** a cache miss is a cache write larger than the cache read after the prompt
478
507
  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
508
+ > 5 min idle). Its $ is what the re-write cost above a cache read: 5 min writes at 1.25x input,
509
+ 1 h writes at 2x input (Anthropic list prices). Tool inputs are hashed, never printed. Not in local logs: `agent_summary` / title
480
510
  background calls and HTTP retries (planned: local OTel receiver).
481
511
 
482
512
  ### 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.1"
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.1"
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,55 @@ 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
+ n = int(job.get("approvals") or 0)
77
+ if n >= APPROVE_MAX:
78
+ return (f"agentcap: already approved twice (limit {float(job.get('quota', 0)):g}%); "
79
+ "start a new job if you really need more.")
80
+ new = round(float(job.get("quota", 0)) * APPROVE_FACTOR, 4)
81
+ job.update({"quota": new, "approvals": n + 1, "approved_at": time.time()})
82
+ _atomic_write(d / "job.json", job)
83
+ status = _read_json(d / "status.json")
84
+ if status:
85
+ status["limit_hit"] = False
86
+ status["quota"] = new
87
+ _atomic_write(d / "status.json", status)
88
+ for name in ("loop.json", "tools.json", "denies.log"):
89
+ try:
90
+ (d / name).unlink()
91
+ except OSError:
92
+ pass
93
+ return (f"agentcap: approved ({n + 1}/{APPROVE_MAX}): limit raised to {new:g}% of the "
94
+ f"{'weekly' if job.get('window') == 'week' else '5-hour'} quota; the run continues.")
41
95
  CLAUDE_KEYS = {"5h": "five_hour", "week": "seven_day"}
42
96
  CODEX_MINUTES = {"5h": 300, "week": 10080}
43
97
  STATE_ENV = "AGENTCAP_QUOTA_DIR"
@@ -425,7 +479,7 @@ def _loop_hook(job_dir: Path, payload: Mapping[str, Any]) -> str | None:
425
479
  d = _digest(name, payload.get("tool_input"))
426
480
  state = _read_json(job_dir / "tools.json") or {}
427
481
  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})
482
+ _atomic_write(job_dir / "tools.json", {"digest": d, "count": count, "tool": name[:40]})
429
483
  if count < LOOP_REPEATS:
430
484
  return None
431
485
  enforce = bool((_read_json(job_dir / "job.json") or {}).get("enforce"))
@@ -434,10 +488,19 @@ def _loop_hook(job_dir: Path, payload: Mapping[str, Any]) -> str | None:
434
488
  "stopped": enforce, "ts": time.time()})
435
489
  if not enforce:
436
490
  return None
491
+ _note_deny(job_dir)
437
492
  return (f"agentcap loop breaker: {detail}. Stop now: do not call more tools; "
438
493
  "summarise what is done and what is left.")
439
494
 
440
495
 
496
+ def _note_deny(job_dir: Path) -> None:
497
+ try:
498
+ with open(job_dir / "denies.log", "a", encoding="utf-8") as fh:
499
+ fh.write(f"{time.time()}\n")
500
+ except OSError:
501
+ pass
502
+
503
+
441
504
  def _deny(stdout: TextIO, reason: str) -> int:
442
505
  json.dump(
443
506
  {
@@ -471,16 +534,12 @@ def hook_main(job_dir: Path, stdin: TextIO, stdout: TextIO) -> int:
471
534
  status = _read_json(job_dir / "status.json")
472
535
  if not status or not status.get("limit_hit"):
473
536
  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
537
+ _note_deny(job_dir)
479
538
  reason = (
480
539
  f"agentcap quota mode: this job used {float(status.get('share', 0)):.1f}% of the "
481
540
  f"{'weekly' if status.get('window') == 'week' else '5-hour'} subscription quota "
482
541
  f"(limit {float(status.get('quota', 0)):g}%). Stop now: do not call more tools; "
483
- "summarise what is done and what is left."
542
+ "summarise what is done and what is left. (The user can run `agentcap approve` to raise it.)"
484
543
  )
485
544
  json.dump(
486
545
  {
@@ -633,6 +692,7 @@ class QuotaRunner:
633
692
  self.agent = detect_quota_agent(self.argv)
634
693
  if self.agent is None:
635
694
  raise ValueError("quota mode supports `claude` and `codex` only")
695
+ self.headless = self.agent == "codex" or is_headless_claude(self.argv)
636
696
  self.quota = quota
637
697
  self.window = window
638
698
  self.enforce = enforce
@@ -711,7 +771,12 @@ class QuotaRunner:
711
771
  _atomic_write(settings, claude_settings(self.job_dir))
712
772
  argv = inject_claude_settings(argv, settings)
713
773
  else:
774
+ _atomic_write(self.job_dir / "job.json", {
775
+ "quota": self.quota, "window": self.window, "started_at": started,
776
+ "enforce": self.enforce, "agent": "codex",
777
+ })
714
778
  tailer = CodexTailer(self.sessions_dir, started)
779
+ self._tailer = tailer
715
780
  prior = tailer.last_reading_before(self.window)
716
781
  if prior and started - prior[0] <= BASELINE_MAX_AGE_S and (
717
782
  prior[1].resets_at is None or prior[1].resets_at > started
@@ -735,10 +800,22 @@ class QuotaRunner:
735
800
  reason = "exited"
736
801
  share = 0.0
737
802
  stopped = False
803
+ open_said = False
804
+ approvals = 0
738
805
  try:
739
806
  while True:
740
807
  code = self.child.poll()
741
808
  now = time.time()
809
+ jobnow = _read_json(self.job_dir / "job.json") or {}
810
+ if int(jobnow.get("approvals") or 0) > approvals and code is None:
811
+ approvals = int(jobnow["approvals"])
812
+ self.quota = float(jobnow.get("quota", self.quota))
813
+ hit = warned = stopped = open_said = False
814
+ hit_at = loop_at = None
815
+ loop_detail = None
816
+ self._say(f"agentcap: approved ({approvals}/{APPROVE_MAX}): limit is now "
817
+ f"{self.quota:g}%; continuing.")
818
+ self._event("quota_approved", share, approvals=approvals)
742
819
  if self.agent == "claude":
743
820
  status = _read_json(self.job_dir / "status.json") or {}
744
821
  if status.get("has_rate_limits"):
@@ -784,8 +861,10 @@ class QuotaRunner:
784
861
  and hit_at is not None and code is None
785
862
  ):
786
863
  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()
864
+ if not self.headless and denies:
865
+ open_said = self._say_open(open_said, "the quota limit")
866
+ elif now - hit_at >= (self.claude_grace_s if denies else self.claude_grace_s * 3):
867
+ self._stop() # headless, or the hook never ran (fallback)
789
868
  stopped = True
790
869
  if loop_detail is None:
791
870
  if self.agent == "claude":
@@ -802,9 +881,14 @@ class QuotaRunner:
802
881
  self._stop()
803
882
  stopped = True
804
883
  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
884
+ and loop_at is not None):
885
+ denies = (self.job_dir / "denies.log").exists()
886
+ if not self.headless and denies:
887
+ open_said = self._say_open(open_said, "the loop breaker")
888
+ elif now - loop_at >= (self.claude_grace_s if denies or self.headless
889
+ else self.claude_grace_s * 3):
890
+ self._stop()
891
+ stopped = True
808
892
  self._live(share, observed, hit)
809
893
  if code is not None:
810
894
  break
@@ -827,8 +911,27 @@ class QuotaRunner:
827
911
  tracker.baseline_exact, tracker.resets_seen, parallel, observed,
828
912
  )
829
913
  self._receipt(self.summary)
914
+ try:
915
+ _atomic_write(self.job_dir / "done.json", {"ts": time.time(), "exit_code": code})
916
+ except OSError:
917
+ pass
830
918
  return code
831
919
 
920
+ def _say_open(self, said: bool, what: str) -> bool:
921
+ if not said:
922
+ self._say(f"agentcap: {what} stopped this turn (tool calls are denied). The session stays "
923
+ "open: run `agentcap approve` in another terminal to raise the limit by 50% "
924
+ f"(at most {APPROVE_MAX}x), or quit Claude Code.")
925
+ return True
926
+
927
+ def _last_tool(self) -> str | None:
928
+ t = _read_json(self.job_dir / "tools.json") or {}
929
+ name = t.get("tool")
930
+ if not name and self.agent == "codex":
931
+ tailer = getattr(self, "_tailer", None)
932
+ name = tailer.loop.tool if tailer is not None else None
933
+ return str(name)[:40] if name else None
934
+
832
935
  def _live(self, share: float, observed: bool, hit: bool) -> None:
833
936
  """Optional live status for editor integrations (AGENTCAP_QUOTA_LIVE)."""
834
937
 
@@ -861,6 +964,9 @@ class QuotaRunner:
861
964
  + (f" (limit {s.quota:g}%)" if self.enforce else "")
862
965
  + (f"; {'; '.join(notes)}" if notes else "") + "."
863
966
  )
967
+ last = self._last_tool()
968
+ if last:
969
+ self._say(f"agentcap: last tool call: {last}")
864
970
  if not self.enforce and s.share >= s.quota:
865
971
  self._say(
866
972
  f"agentcap: Pro's quota mode would have stopped this job at {s.quota:g}%. "
@@ -875,6 +981,7 @@ class QuotaRunner:
875
981
  "quota_pct": s.quota, "share_pct": s.share, "exit_code": s.exit_code,
876
982
  "reason": s.reason, "baseline_exact": s.baseline_exact,
877
983
  "parallel_sessions": s.parallel, "window_resets": s.resets_seen,
984
+ "last_tool": last,
878
985
  })
879
986
  except OSError:
880
987
  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,106 @@ 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
File without changes
File without changes