agentcap-cli 0.4.0__tar.gz → 0.4.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 (113) hide show
  1. {agentcap_cli-0.4.0 → agentcap_cli-0.4.1}/PKG-INFO +13 -3
  2. {agentcap_cli-0.4.0 → agentcap_cli-0.4.1}/README.md +12 -2
  3. {agentcap_cli-0.4.0 → agentcap_cli-0.4.1}/pyproject.toml +1 -1
  4. {agentcap_cli-0.4.0 → agentcap_cli-0.4.1}/src/agentcap/__init__.py +1 -1
  5. {agentcap_cli-0.4.0 → agentcap_cli-0.4.1}/src/agentcap/quota.py +125 -5
  6. {agentcap_cli-0.4.0 → agentcap_cli-0.4.1}/src/agentcap/waste.py +36 -0
  7. {agentcap_cli-0.4.0 → agentcap_cli-0.4.1}/tests/test_cc_plugin.py +14 -0
  8. {agentcap_cli-0.4.0 → agentcap_cli-0.4.1}/tests/test_live_quota.py +154 -1
  9. {agentcap_cli-0.4.0 → agentcap_cli-0.4.1}/tests/test_proxy_auth.py +1 -1
  10. {agentcap_cli-0.4.0 → agentcap_cli-0.4.1}/.gitignore +0 -0
  11. {agentcap_cli-0.4.0 → agentcap_cli-0.4.1}/LICENSE +0 -0
  12. {agentcap_cli-0.4.0 → agentcap_cli-0.4.1}/landing/v2/README.md +0 -0
  13. {agentcap_cli-0.4.0 → agentcap_cli-0.4.1}/plugin/LICENSE +0 -0
  14. {agentcap_cli-0.4.0 → agentcap_cli-0.4.1}/src/agentcap/_lifeline_exec.py +0 -0
  15. {agentcap_cli-0.4.0 → agentcap_cli-0.4.1}/src/agentcap/_lifeline_watch.py +0 -0
  16. {agentcap_cli-0.4.0 → agentcap_cli-0.4.1}/src/agentcap/adapters.py +0 -0
  17. {agentcap_cli-0.4.0 → agentcap_cli-0.4.1}/src/agentcap/alerts.py +0 -0
  18. {agentcap_cli-0.4.0 → agentcap_cli-0.4.1}/src/agentcap/analytics.py +0 -0
  19. {agentcap_cli-0.4.0 → agentcap_cli-0.4.1}/src/agentcap/budget.py +0 -0
  20. {agentcap_cli-0.4.0 → agentcap_cli-0.4.1}/src/agentcap/clamp.py +0 -0
  21. {agentcap_cli-0.4.0 → agentcap_cli-0.4.1}/src/agentcap/cli.py +0 -0
  22. {agentcap_cli-0.4.0 → agentcap_cli-0.4.1}/src/agentcap/cli_history.py +0 -0
  23. {agentcap_cli-0.4.0 → agentcap_cli-0.4.1}/src/agentcap/data/pricing.json +0 -0
  24. {agentcap_cli-0.4.0 → agentcap_cli-0.4.1}/src/agentcap/demo.py +0 -0
  25. {agentcap_cli-0.4.0 → agentcap_cli-0.4.1}/src/agentcap/devtools/__init__.py +0 -0
  26. {agentcap_cli-0.4.0 → agentcap_cli-0.4.1}/src/agentcap/devtools/fake_upstream.py +0 -0
  27. {agentcap_cli-0.4.0 → agentcap_cli-0.4.1}/src/agentcap/estimate.py +0 -0
  28. {agentcap_cli-0.4.0 → agentcap_cli-0.4.1}/src/agentcap/eta.py +0 -0
  29. {agentcap_cli-0.4.0 → agentcap_cli-0.4.1}/src/agentcap/failsafe.py +0 -0
  30. {agentcap_cli-0.4.0 → agentcap_cli-0.4.1}/src/agentcap/harness.py +0 -0
  31. {agentcap_cli-0.4.0 → agentcap_cli-0.4.1}/src/agentcap/history.py +0 -0
  32. {agentcap_cli-0.4.0 → agentcap_cli-0.4.1}/src/agentcap/ledger.py +0 -0
  33. {agentcap_cli-0.4.0 → agentcap_cli-0.4.1}/src/agentcap/license.py +0 -0
  34. {agentcap_cli-0.4.0 → agentcap_cli-0.4.1}/src/agentcap/lifeline.py +0 -0
  35. {agentcap_cli-0.4.0 → agentcap_cli-0.4.1}/src/agentcap/live_quota.py +0 -0
  36. {agentcap_cli-0.4.0 → agentcap_cli-0.4.1}/src/agentcap/logschema.py +0 -0
  37. {agentcap_cli-0.4.0 → agentcap_cli-0.4.1}/src/agentcap/loop.py +0 -0
  38. {agentcap_cli-0.4.0 → agentcap_cli-0.4.1}/src/agentcap/plans.py +0 -0
  39. {agentcap_cli-0.4.0 → agentcap_cli-0.4.1}/src/agentcap/pricing.py +0 -0
  40. {agentcap_cli-0.4.0 → agentcap_cli-0.4.1}/src/agentcap/private.py +0 -0
  41. {agentcap_cli-0.4.0 → agentcap_cli-0.4.1}/src/agentcap/procstop.py +0 -0
  42. {agentcap_cli-0.4.0 → agentcap_cli-0.4.1}/src/agentcap/proxy.py +0 -0
  43. {agentcap_cli-0.4.0 → agentcap_cli-0.4.1}/src/agentcap/report.py +0 -0
  44. {agentcap_cli-0.4.0 → agentcap_cli-0.4.1}/src/agentcap/runner.py +0 -0
  45. {agentcap_cli-0.4.0 → agentcap_cli-0.4.1}/src/agentcap/upstreams.py +0 -0
  46. {agentcap_cli-0.4.0 → agentcap_cli-0.4.1}/src/agentcap/usage.py +0 -0
  47. {agentcap_cli-0.4.0 → agentcap_cli-0.4.1}/tests/conftest.py +0 -0
  48. {agentcap_cli-0.4.0 → agentcap_cli-0.4.1}/tests/fixtures/agents/claude/projects/-home-dev-shop/sess-p/subagents/agent-a1b2c3.jsonl +0 -0
  49. {agentcap_cli-0.4.0 → agentcap_cli-0.4.1}/tests/fixtures/agents/claude/projects/-home-dev-shop/sess-p/subagents/agent-d4e5f6.jsonl +0 -0
  50. {agentcap_cli-0.4.0 → agentcap_cli-0.4.1}/tests/fixtures/agents/claude/projects/-home-dev-shop/sess-p.jsonl +0 -0
  51. {agentcap_cli-0.4.0 → agentcap_cli-0.4.1}/tests/fixtures/agents/codex/sessions/2026/10/29/rollout-2026-10-29T09-00-00-thr-parent.jsonl +0 -0
  52. {agentcap_cli-0.4.0 → agentcap_cli-0.4.1}/tests/fixtures/agents/codex/sessions/2026/10/29/rollout-2026-10-29T09-00-50-thr-child.jsonl +0 -0
  53. {agentcap_cli-0.4.0 → agentcap_cli-0.4.1}/tests/fixtures/agents/codex/sessions/2026/10/29/rollout-2026-10-29T09-01-20-thr-fork.jsonl +0 -0
  54. {agentcap_cli-0.4.0 → agentcap_cli-0.4.1}/tests/fixtures/harness_logs/agy-1.4.11-2026-10-30.jsonl +0 -0
  55. {agentcap_cli-0.4.0 → agentcap_cli-0.4.1}/tests/fixtures/harness_logs/claude-2.1.316-pretooluse.json +0 -0
  56. {agentcap_cli-0.4.0 → agentcap_cli-0.4.1}/tests/fixtures/harness_logs/claude-2.1.316-statusline.json +0 -0
  57. {agentcap_cli-0.4.0 → agentcap_cli-0.4.1}/tests/fixtures/harness_logs/codex-rollout-2026-10-29.jsonl +0 -0
  58. {agentcap_cli-0.4.0 → agentcap_cli-0.4.1}/tests/fixtures/harness_logs/opencode-2026-10-30.jsonl +0 -0
  59. {agentcap_cli-0.4.0 → agentcap_cli-0.4.1}/tests/fixtures/history/claude/.credentials.json +0 -0
  60. {agentcap_cli-0.4.0 → agentcap_cli-0.4.1}/tests/fixtures/history/claude/projects/-home-dev-shop/1f0c-sess-a.jsonl +0 -0
  61. {agentcap_cli-0.4.0 → agentcap_cli-0.4.1}/tests/fixtures/history/codex/auth.json +0 -0
  62. {agentcap_cli-0.4.0 → agentcap_cli-0.4.1}/tests/fixtures/history/codex/sessions/2026/10/29/rollout-2026-10-29T10-00-00-0199aaaa-bbbb-cccc-dddd-eeeeeeeeeeee.jsonl +0 -0
  63. {agentcap_cli-0.4.0 → agentcap_cli-0.4.1}/tests/fixtures/upstream/README.md +0 -0
  64. {agentcap_cli-0.4.0 → agentcap_cli-0.4.1}/tests/fixtures/upstream/anthropic_403_permission_error.json +0 -0
  65. {agentcap_cli-0.4.0 → agentcap_cli-0.4.1}/tests/fixtures/upstream/openai_403_region_blocked.json +0 -0
  66. {agentcap_cli-0.4.0 → agentcap_cli-0.4.1}/tests/fixtures/upstream/openrouter_401_user_not_found.json +0 -0
  67. {agentcap_cli-0.4.0 → agentcap_cli-0.4.1}/tests/fixtures/upstream/openrouter_403_moderation.json +0 -0
  68. {agentcap_cli-0.4.0 → agentcap_cli-0.4.1}/tests/fixtures/upstream/openrouter_429_rate_limited.json +0 -0
  69. {agentcap_cli-0.4.0 → agentcap_cli-0.4.1}/tests/license_support.py +0 -0
  70. {agentcap_cli-0.4.0 → agentcap_cli-0.4.1}/tests/proxy_support.py +0 -0
  71. {agentcap_cli-0.4.0 → agentcap_cli-0.4.1}/tests/test_adapters.py +0 -0
  72. {agentcap_cli-0.4.0 → agentcap_cli-0.4.1}/tests/test_agents.py +0 -0
  73. {agentcap_cli-0.4.0 → agentcap_cli-0.4.1}/tests/test_alerts.py +0 -0
  74. {agentcap_cli-0.4.0 → agentcap_cli-0.4.1}/tests/test_analytics.py +0 -0
  75. {agentcap_cli-0.4.0 → agentcap_cli-0.4.1}/tests/test_anthropic_proxy.py +0 -0
  76. {agentcap_cli-0.4.0 → agentcap_cli-0.4.1}/tests/test_anthropic_units.py +0 -0
  77. {agentcap_cli-0.4.0 → agentcap_cli-0.4.1}/tests/test_budget.py +0 -0
  78. {agentcap_cli-0.4.0 → agentcap_cli-0.4.1}/tests/test_child_status.py +0 -0
  79. {agentcap_cli-0.4.0 → agentcap_cli-0.4.1}/tests/test_clamp.py +0 -0
  80. {agentcap_cli-0.4.0 → agentcap_cli-0.4.1}/tests/test_claude_adapter_and_tiers.py +0 -0
  81. {agentcap_cli-0.4.0 → agentcap_cli-0.4.1}/tests/test_cli.py +0 -0
  82. {agentcap_cli-0.4.0 → agentcap_cli-0.4.1}/tests/test_concurrent_forgive.py +0 -0
  83. {agentcap_cli-0.4.0 → agentcap_cli-0.4.1}/tests/test_e2e_claude.py +0 -0
  84. {agentcap_cli-0.4.0 → agentcap_cli-0.4.1}/tests/test_estimate.py +0 -0
  85. {agentcap_cli-0.4.0 → agentcap_cli-0.4.1}/tests/test_exit_codes.py +0 -0
  86. {agentcap_cli-0.4.0 → agentcap_cli-0.4.1}/tests/test_failsafe.py +0 -0
  87. {agentcap_cli-0.4.0 → agentcap_cli-0.4.1}/tests/test_harness.py +0 -0
  88. {agentcap_cli-0.4.0 → agentcap_cli-0.4.1}/tests/test_history.py +0 -0
  89. {agentcap_cli-0.4.0 → agentcap_cli-0.4.1}/tests/test_ledger.py +0 -0
  90. {agentcap_cli-0.4.0 → agentcap_cli-0.4.1}/tests/test_license.py +0 -0
  91. {agentcap_cli-0.4.0 → agentcap_cli-0.4.1}/tests/test_lifeline.py +0 -0
  92. {agentcap_cli-0.4.0 → agentcap_cli-0.4.1}/tests/test_log_contract.py +0 -0
  93. {agentcap_cli-0.4.0 → agentcap_cli-0.4.1}/tests/test_log_contract_live.py +0 -0
  94. {agentcap_cli-0.4.0 → agentcap_cli-0.4.1}/tests/test_loop.py +0 -0
  95. {agentcap_cli-0.4.0 → agentcap_cli-0.4.1}/tests/test_plugin_package.py +0 -0
  96. {agentcap_cli-0.4.0 → agentcap_cli-0.4.1}/tests/test_pricing.py +0 -0
  97. {agentcap_cli-0.4.0 → agentcap_cli-0.4.1}/tests/test_private_dirs.py +0 -0
  98. {agentcap_cli-0.4.0 → agentcap_cli-0.4.1}/tests/test_procstop.py +0 -0
  99. {agentcap_cli-0.4.0 → agentcap_cli-0.4.1}/tests/test_proxy_cancel.py +0 -0
  100. {agentcap_cli-0.4.0 → agentcap_cli-0.4.1}/tests/test_proxy_core.py +0 -0
  101. {agentcap_cli-0.4.0 → agentcap_cli-0.4.1}/tests/test_proxy_extras.py +0 -0
  102. {agentcap_cli-0.4.0 → agentcap_cli-0.4.1}/tests/test_proxy_streaming.py +0 -0
  103. {agentcap_cli-0.4.0 → agentcap_cli-0.4.1}/tests/test_quota.py +0 -0
  104. {agentcap_cli-0.4.0 → agentcap_cli-0.4.1}/tests/test_release.py +0 -0
  105. {agentcap_cli-0.4.0 → agentcap_cli-0.4.1}/tests/test_report_cli.py +0 -0
  106. {agentcap_cli-0.4.0 → agentcap_cli-0.4.1}/tests/test_runaway.py +0 -0
  107. {agentcap_cli-0.4.0 → agentcap_cli-0.4.1}/tests/test_runner.py +0 -0
  108. {agentcap_cli-0.4.0 → agentcap_cli-0.4.1}/tests/test_self_approve.py +0 -0
  109. {agentcap_cli-0.4.0 → agentcap_cli-0.4.1}/tests/test_stop_matrix.py +0 -0
  110. {agentcap_cli-0.4.0 → agentcap_cli-0.4.1}/tests/test_upstream_refusals.py +0 -0
  111. {agentcap_cli-0.4.0 → agentcap_cli-0.4.1}/tests/test_upstreams.py +0 -0
  112. {agentcap_cli-0.4.0 → agentcap_cli-0.4.1}/tests/test_usage.py +0 -0
  113. {agentcap_cli-0.4.0 → agentcap_cli-0.4.1}/tests/test_zombie_collector.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: agentcap-cli
3
- Version: 0.4.0
3
+ Version: 0.4.1
4
4
  Summary: Local-first quota and cost guard for coding agents: per-job share of Claude Code/Codex/Gemini subscription quota, loop breaker, evidence receipt.
5
5
  Project-URL: Homepage, https://agentcap.launchbench.studio
6
6
  Project-URL: Repository, https://github.com/Blitz00X/agentcap
@@ -296,6 +296,10 @@ How it works:
296
296
  `Stop` prints a receipt (`session 4.2% / 5% (weekly)`). **Free:** live meter + one notice
297
297
  at the limit (`Pro would stop the agent here`). Pro is read from the licence the `agentcap`
298
298
  CLI stores after `agentcap license activate` (paste the key at the hidden prompt).
299
+ - Waiting is not looping: a shell call that starts with `sleep N` (`sleep 4; ls done.flag`,
300
+ `sleep 30 && curl .../health`) counts toward neither the repeat streak nor the error streak,
301
+ in the CLI (Claude and Codex) and the plugin (live gate test: a 4th wait-for-a-file check was
302
+ stopped as a loop). An endless `sleep 1; retry` loop is then only stopped by the quota.
299
303
  - Loop breaker (works with or without `/agentcap:quota`): `PreToolUse` hashes each tool call
300
304
  (name + input, per session and per subagent; polling tools like `TaskOutput`/`BashOutput`
301
305
  are ignored). The 4th identical call in a row is denied with `continue: false` on **Pro**;
@@ -344,7 +348,13 @@ agentcap quota # read-only: current usage, asked
344
348
  every minute and once after exit. The statusline % and `/usage` differ by one point at both
345
349
  ends of a job (live: 26/27 at start, 31/32 at the end), so the statusline is only compared
346
350
  with itself, the hook also denies when `/usage` shows the limit first, and the receipt is the
347
- `/usage` difference (`measured_by: usage`).
351
+ `/usage` difference (`measured_by: usage`). `/usage` itself shows a job's usage 30-90 s after
352
+ its requests (live gate test: short jobs read 0.0% at exit and the % appeared a minute later),
353
+ so a quota stop can come that much later, and after a Claude job a detached process keeps
354
+ reading `/usage` for up to 90 s and rewrites the receipt with the settled share
355
+ (`settled: true`, `share_pct_at_exit` keeps the first value). It stops early when the value
356
+ holds or when another AgentCap quota job starts (`settle_cut`); other Claude use on the account
357
+ in those 90 s (another chat, another device) still counts toward the receipt.
348
358
  The hook can stop Claude only before a tool call, so one large response overshoots: live, a
349
359
  3% limit ended at 5% after one response with 7 parallel file reads used 3%. Usage on the same
350
360
  account from anywhere else (claude.ai, the desktop or phone app, another terminal) counts
@@ -495,7 +505,7 @@ period AgentCap sends SIGINT and the session ends; Codex's sandbox can't run com
495
505
  `kernel.apparmor_restrict_unprivileged_userns=1` blocks bubblewrap's user namespace
496
506
  (host setting, not AgentCap; Codex falls back or needs an AppArmor profile for bwrap).
497
507
 
498
- **Platforms:** Linux and macOS. Windows: not yet (use WSL2).
508
+ **Platforms:** Linux (tested live). macOS: the code path exists but has not been tested on a real Mac yet; the Linux-only parts (parent-death signal, subreaper) do not apply there. Windows: not yet (use WSL2).
499
509
 
500
510
  ## How it works
501
511
 
@@ -266,6 +266,10 @@ How it works:
266
266
  `Stop` prints a receipt (`session 4.2% / 5% (weekly)`). **Free:** live meter + one notice
267
267
  at the limit (`Pro would stop the agent here`). Pro is read from the licence the `agentcap`
268
268
  CLI stores after `agentcap license activate` (paste the key at the hidden prompt).
269
+ - Waiting is not looping: a shell call that starts with `sleep N` (`sleep 4; ls done.flag`,
270
+ `sleep 30 && curl .../health`) counts toward neither the repeat streak nor the error streak,
271
+ in the CLI (Claude and Codex) and the plugin (live gate test: a 4th wait-for-a-file check was
272
+ stopped as a loop). An endless `sleep 1; retry` loop is then only stopped by the quota.
269
273
  - Loop breaker (works with or without `/agentcap:quota`): `PreToolUse` hashes each tool call
270
274
  (name + input, per session and per subagent; polling tools like `TaskOutput`/`BashOutput`
271
275
  are ignored). The 4th identical call in a row is denied with `continue: false` on **Pro**;
@@ -314,7 +318,13 @@ agentcap quota # read-only: current usage, asked
314
318
  every minute and once after exit. The statusline % and `/usage` differ by one point at both
315
319
  ends of a job (live: 26/27 at start, 31/32 at the end), so the statusline is only compared
316
320
  with itself, the hook also denies when `/usage` shows the limit first, and the receipt is the
317
- `/usage` difference (`measured_by: usage`).
321
+ `/usage` difference (`measured_by: usage`). `/usage` itself shows a job's usage 30-90 s after
322
+ its requests (live gate test: short jobs read 0.0% at exit and the % appeared a minute later),
323
+ so a quota stop can come that much later, and after a Claude job a detached process keeps
324
+ reading `/usage` for up to 90 s and rewrites the receipt with the settled share
325
+ (`settled: true`, `share_pct_at_exit` keeps the first value). It stops early when the value
326
+ holds or when another AgentCap quota job starts (`settle_cut`); other Claude use on the account
327
+ in those 90 s (another chat, another device) still counts toward the receipt.
318
328
  The hook can stop Claude only before a tool call, so one large response overshoots: live, a
319
329
  3% limit ended at 5% after one response with 7 parallel file reads used 3%. Usage on the same
320
330
  account from anywhere else (claude.ai, the desktop or phone app, another terminal) counts
@@ -465,7 +475,7 @@ period AgentCap sends SIGINT and the session ends; Codex's sandbox can't run com
465
475
  `kernel.apparmor_restrict_unprivileged_userns=1` blocks bubblewrap's user namespace
466
476
  (host setting, not AgentCap; Codex falls back or needs an AppArmor profile for bwrap).
467
477
 
468
- **Platforms:** Linux and macOS. Windows: not yet (use WSL2).
478
+ **Platforms:** Linux (tested live). macOS: the code path exists but has not been tested on a real Mac yet; the Linux-only parts (parent-death signal, subreaper) do not apply there. Windows: not yet (use WSL2).
469
479
 
470
480
  ## How it works
471
481
 
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "agentcap-cli"
7
- version = "0.4.0"
7
+ version = "0.4.1"
8
8
  description = "Local-first quota and cost guard for coding agents: per-job share of Claude Code/Codex/Gemini subscription quota, loop breaker, evidence receipt."
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.4.0"
5
+ __version__ = "0.4.1"
6
6
 
7
7
  __all__ = ["__version__"]
@@ -99,6 +99,12 @@ LIVE_POLL_S = 30.0
99
99
  # one-response lag. The statusline is compared only with itself; /usage, asked
100
100
  # at start, every minute and after exit, gives the receipt and catches a lag.
101
101
  CLAUDE_LIVE_POLL_S = 60.0
102
+ # Claude's /usage shows a job's usage only 30-90 s after its requests (live gate test,
103
+ # 13 Nov 2026: eight short jobs all read 0.0% while the account rose 21% -> 28%; each
104
+ # job's share appeared at the next job's start). After a Claude job exits, a detached
105
+ # process keeps reading /usage for a while and rewrites the receipt with the settled share.
106
+ CLAUDE_SETTLE_S = 90.0 # the lag measured live was 30-90 s; a longer window catches other usage
107
+ SETTLE_STEP_S = 20.0
102
108
  # Headless `claude -p` has no statusline at all, so /usage is the only source there.
103
109
  HEADLESS_LIVE_POLL_S = 30.0
104
110
  HEADLESS_CLAUDE_LIVE_NOTE = (
@@ -735,11 +741,13 @@ class LoopWatch:
735
741
  self.count = 0
736
742
  self.errors = 0
737
743
  self.tripped: str | None = None
744
+ self.waiting = False # the last call was a wait (sleep ...): its result is neutral
738
745
 
739
746
  def call(self, name: str, payload: Any) -> None:
740
- from .waste import POLL_TOOLS, _digest
747
+ from .waste import _digest, is_wait_call
741
748
 
742
- if name in POLL_TOOLS:
749
+ self.waiting = is_wait_call(name, payload)
750
+ if self.waiting:
743
751
  return
744
752
  d = _digest(name, payload)
745
753
  self.count = self.count + 1 if d == self.digest else 1
@@ -748,6 +756,8 @@ class LoopWatch:
748
756
  self.tripped = f"same tool call {self.count} times in a row ({name[:40]})"
749
757
 
750
758
  def result(self, error: bool) -> None:
759
+ if self.waiting:
760
+ return
751
761
  self.errors = self.errors + 1 if error else 0
752
762
  if self.errors >= LOOP_ERRORS and not self.tripped:
753
763
  self.tripped = f"{self.errors} failing tool calls in a row ({self.tool[:40]})"
@@ -770,10 +780,10 @@ class LoopWatch:
770
780
  def _loop_hook(job_dir: Path, payload: Mapping[str, Any]) -> str | None:
771
781
  """Track identical PreToolUse calls; return a deny reason when Pro should stop."""
772
782
 
773
- from .waste import POLL_TOOLS, _digest
783
+ from .waste import _digest, is_wait_call
774
784
 
775
785
  name = payload.get("tool_name")
776
- if not isinstance(name, str) or name in POLL_TOOLS:
786
+ if not isinstance(name, str) or is_wait_call(name, payload.get("tool_input")):
777
787
  return None
778
788
 
779
789
  d = _digest(name, payload.get("tool_input"))
@@ -840,7 +850,10 @@ def transcript_error_streak(path: Any, since: float | None = None) -> int:
840
850
  data = fh.read().decode("utf-8", "replace")
841
851
  except OSError:
842
852
  return 0
853
+ from .waste import is_wait_call
854
+
843
855
  streak = 0
856
+ waits: set[str] = set()
844
857
  for line in data.splitlines():
845
858
  try:
846
859
  obj = json.loads(line)
@@ -855,7 +868,12 @@ def transcript_error_streak(path: Any, since: float | None = None) -> int:
855
868
  if not isinstance(content, list):
856
869
  continue
857
870
  for block in content:
871
+ if (isinstance(block, dict) and block.get("type") == "tool_use"
872
+ and is_wait_call(str(block.get("name") or ""), block.get("input"))):
873
+ waits.add(str(block.get("id")))
858
874
  if isinstance(block, dict) and block.get("type") == "tool_result":
875
+ if str(block.get("tool_use_id")) in waits:
876
+ continue # a wait (sleep ...) that has not seen its file yet
859
877
  if block.get("is_error") is True and any(m in _result_text(block) for m in OWN_DENIALS):
860
878
  continue # a pause by AgentCap itself, not a failing call
861
879
  streak = streak + 1 if block.get("is_error") is True else 0
@@ -895,6 +913,9 @@ def post_main(job_dir: Path, stdin: TextIO) -> int:
895
913
  return 0
896
914
  event = payload.get("hook_event_name")
897
915
  path = job_dir / "post_errors.json"
916
+ from .waste import is_wait_call
917
+ if is_wait_call(str(payload.get("tool_name") or ""), payload.get("tool_input")):
918
+ return 0
898
919
  if event == "PostToolUseFailure":
899
920
  errors = int((_read_json(path) or {}).get("errors") or 0) + 1
900
921
  elif event == "PostToolUse":
@@ -1223,6 +1244,7 @@ class QuotaRunner:
1223
1244
  live_reader: Callable[[str], Mapping[str, Reading] | None] | None = None,
1224
1245
  live_poll_s: float | None = LIVE_POLL_S,
1225
1246
  claude_live_poll_s: float = CLAUDE_LIVE_POLL_S,
1247
+ settle_s: float = CLAUDE_SETTLE_S,
1226
1248
  headless_live_poll_s: float = HEADLESS_LIVE_POLL_S,
1227
1249
  live_settle_s: float = LIVE_SETTLE_S,
1228
1250
  ) -> None:
@@ -1261,6 +1283,8 @@ class QuotaRunner:
1261
1283
  self.live_reader = live_reader
1262
1284
  self.live_poll_s = live_poll_s
1263
1285
  self.claude_live_poll_s = claude_live_poll_s
1286
+ self.settle_s = settle_s
1287
+ self._receipt_path: Path | None = None
1264
1288
  self.headless_live_poll_s = headless_live_poll_s
1265
1289
  self._live_tracker: ShareTracker | None = None # claude: /usage at start vs now
1266
1290
  self._live_written: tuple[float, float] | None = None
@@ -1341,6 +1365,40 @@ class QuotaRunner:
1341
1365
  stop_tree(self.child, self._pgid, int_timeout=5.0, term_timeout=3.0, kill_timeout=2.0)
1342
1366
 
1343
1367
  def run(self) -> int:
1368
+ code = self._run()
1369
+ try:
1370
+ self._start_settle()
1371
+ except Exception:
1372
+ pass
1373
+ return code
1374
+
1375
+ @staticmethod
1376
+ def _spawn_detached(argv: list[str], **kw: Any) -> Any:
1377
+ return subprocess.Popen(argv, **kw)
1378
+
1379
+ def _start_settle(self) -> None:
1380
+ """Claude: hand the receipt to a detached /usage settle process (see CLAUDE_SETTLE_S)."""
1381
+
1382
+ from .live_quota import _probe_env, live_enabled
1383
+
1384
+ if not (self.agent == "claude" and self._live_tracker is not None and self.final_live
1385
+ and self._receipt_path is not None and self.settle_s > 0 and live_enabled()):
1386
+ return
1387
+ _atomic_write(self.job_dir / "settle.json", {
1388
+ "receipt": str(self._receipt_path), "window": self.window,
1389
+ "tracker": self._live_tracker.to_dict(), "until": time.time() + self.settle_s,
1390
+ "ended_at": time.time(),
1391
+ })
1392
+ self._spawn_detached(
1393
+ [sys.executable, "-P", "-m", "agentcap.quota", "settle", "--job", str(self.job_dir)],
1394
+ stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
1395
+ start_new_session=True, close_fds=True, env=_probe_env(),
1396
+ )
1397
+ self._print(f"agentcap: Claude's /usage shows usage up to ~90 s late; the receipt is re-checked "
1398
+ f"in the background for {self.settle_s:g} s and updated with the settled share "
1399
+ f"({self._receipt_path}). Claude use elsewhere on the account in that time counts too.")
1400
+
1401
+ def _run(self) -> int:
1344
1402
  lock = JobLock(state_root() / "quota.lock")
1345
1403
  try:
1346
1404
  lock.acquire()
@@ -1902,7 +1960,8 @@ class QuotaRunner:
1902
1960
  self._event("quota_receipt", s.share, reason=s.reason, exit_code=s.exit_code)
1903
1961
  if self.receipt_dir is not None:
1904
1962
  try:
1905
- _atomic_write(self.receipt_dir / f"{self.job_id}.json", {
1963
+ self._receipt_path = self.receipt_dir / f"{self.job_id}.json"
1964
+ _atomic_write(self._receipt_path, {
1906
1965
  "type": "agentcap_quota_receipt", "agent": s.agent, "window": s.window,
1907
1966
  "quota_pct": s.quota, "share_pct": s.share, "exit_code": s.exit_code,
1908
1967
  "reason": s.reason, "baseline_exact": s.baseline_exact,
@@ -2007,6 +2066,62 @@ def _reset_text(resets_at: Any, now: float) -> str:
2007
2066
  return f", resets in {left // 3600}h{(left % 3600) // 60:02d}m"
2008
2067
 
2009
2068
 
2069
+ def _job_started_after(job_dir: Path, ts: float) -> bool:
2070
+ try:
2071
+ for d in job_dir.parent.iterdir():
2072
+ if d != job_dir and (_num((_read_json(d / "job.json") or {}).get("started_at")) or 0.0) > ts:
2073
+ return True
2074
+ except OSError:
2075
+ return False
2076
+ return False
2077
+
2078
+
2079
+ def settle_main(job_dir: Path, *, reader: Callable[[str], Mapping[str, Reading] | None] | None = None,
2080
+ sleep: Callable[[float], None] = time.sleep, clock: Callable[[], float] = time.time,
2081
+ step_s: float = SETTLE_STEP_S) -> int:
2082
+ """Keep reading /usage after a Claude job and rewrite its receipt with the settled share."""
2083
+
2084
+ if reader is None:
2085
+ from .live_quota import live_readings as reader
2086
+ cfg = _read_json(job_dir / "settle.json") or {}
2087
+ receipt_path = Path(str(cfg.get("receipt") or ""))
2088
+ receipt = _read_json(receipt_path)
2089
+ if not receipt or not cfg.get("window"):
2090
+ return 0
2091
+ tracker = ShareTracker.from_dict(cfg.get("tracker"))
2092
+ at_exit = float(receipt.get("share_pct") or 0.0)
2093
+ start, until = clock(), float(cfg.get("until") or 0.0)
2094
+ ended = float(cfg.get("ended_at") or start)
2095
+ unchanged = 0
2096
+ cut: str | None = None
2097
+ while clock() < until:
2098
+ sleep(max(0.0, min(step_s, until - clock())))
2099
+ if _job_started_after(job_dir, ended):
2100
+ # the % is account-wide: a newer job's usage would be charged to this receipt
2101
+ # (live 0.4.1 check, 13 Nov 2026: a polling job's receipt took the next job's 1%)
2102
+ cut = "another quota job started"
2103
+ break
2104
+ try:
2105
+ got = (reader("claude") or {}).get(cfg["window"])
2106
+ except Exception:
2107
+ got = None
2108
+ if got is None:
2109
+ continue
2110
+ before = tracker.share
2111
+ tracker.update(got)
2112
+ unchanged = unchanged + 1 if tracker.share <= before else 0
2113
+ if clock() - start >= 60 and unchanged >= 2:
2114
+ break
2115
+ settled = max(at_exit, tracker.share)
2116
+ receipt.update({"share_pct": settled, "share_pct_at_exit": at_exit, "settled": True,
2117
+ "settled_at": clock()})
2118
+ if cut:
2119
+ receipt["settle_cut"] = cut
2120
+ _atomic_write(receipt_path, receipt)
2121
+ _atomic_write(job_dir / "settled.json", {"ts": clock(), "share_pct": settled, "at_exit": at_exit})
2122
+ return 0
2123
+
2124
+
2010
2125
  def main(argv: Sequence[str] | None = None) -> int:
2011
2126
  args = list(sys.argv[1:] if argv is None else argv)
2012
2127
  if len(args) >= 3 and args[1] == "--job":
@@ -2026,6 +2141,11 @@ def main(argv: Sequence[str] | None = None) -> int:
2026
2141
  return post_main(job, sys.stdin)
2027
2142
  except Exception:
2028
2143
  return 0
2144
+ if args[0] == "settle":
2145
+ try:
2146
+ return settle_main(job)
2147
+ except Exception:
2148
+ return 0
2029
2149
  print("usage: python -m agentcap.quota statusline|hook --job DIR", file=sys.stderr)
2030
2150
  return 0
2031
2151
 
@@ -35,6 +35,42 @@ PRO_ERROR_STOP = 8 # Pro loop breaker: 8 tool errors in a row
35
35
  TTL_5M, TTL_1H = 300, 3600
36
36
  # polling / waiting tools repeat by design; never call them a loop
37
37
  POLL_TOOLS = frozenset({"wait", "sleep", "write_stdin", "list_agents", "TaskOutput", "BashOutput"})
38
+
39
+ # A shell call that starts by sleeping is waiting for something (CI, a deploy, a file),
40
+ # not a loop: live gate test 13 Nov 2026, `sleep 4; ls done.flag` until the file appeared
41
+ # was stopped by the loop breaker at the 4th check. Such calls count toward neither the
42
+ # repeat streak nor the error streak (the `ls` fails until the file is there).
43
+ _WAIT_RE = re.compile(r"^\s*sleep\s+\d+(?:\.\d+)?[smh]?\s*(?:;|&&|\n|$)")
44
+ _CMD_IN_TEXT = re.compile(r"""\bcmd\s*:\s*(["'])(.*?)(?<!\\)\1""", re.S)
45
+
46
+
47
+ def command_text(payload: Any) -> str | None:
48
+ """The shell command of a tool call: Claude Bash ``{"command": ...}``, Codex
49
+ ``{"cmd": ...}`` / ``["bash", "-lc", ...]`` or Codex's code-mode ``exec`` text."""
50
+
51
+ if isinstance(payload, str):
52
+ try:
53
+ payload = json.loads(payload)
54
+ except ValueError:
55
+ m = _CMD_IN_TEXT.search(payload)
56
+ return m.group(2) if m else None
57
+ if isinstance(payload, dict):
58
+ for key in ("command", "cmd"):
59
+ value = payload.get(key)
60
+ if isinstance(value, str):
61
+ return value
62
+ if isinstance(value, list) and value and all(isinstance(x, str) for x in value):
63
+ if len(value) >= 3 and value[1] in ("-lc", "-c"):
64
+ return value[2]
65
+ return " ".join(value)
66
+ return None
67
+
68
+
69
+ def is_wait_call(name: str, payload: Any) -> bool:
70
+ if name in POLL_TOOLS:
71
+ return True
72
+ cmd = command_text(payload)
73
+ return bool(cmd and _WAIT_RE.match(cmd))
38
74
  CODEX_MISS_MIN_TOKENS = 4096 # Codex has no cache writes; only flag big uncached prompts
39
75
 
40
76
 
@@ -562,3 +562,17 @@ def test_self_guard_denies_the_cli_approve(env):
562
562
  out = hook("pre", dict(PRE, tool_input={"command": command}))
563
563
  assert out and out["hookSpecificOutput"]["permissionDecision"] == "deny", command
564
564
  assert hook("pre", dict(PRE, tool_input={"command": "agentcap quota"})) is None
565
+
566
+
567
+ def test_plugin_waits_trip_neither_breaker(env):
568
+ # live gate test 13 Nov: `sleep 4; ls done.flag` until a file appears is waiting, not a loop
569
+ pro(env)
570
+ wait = dict(PRE, tool_input={"command": "sleep 4; ls done.flag"})
571
+ fail = {"session_id": SID, "hook_event_name": "PostToolUseFailure", "tool_name": "Bash",
572
+ "tool_input": {"command": "sleep 4; ls done.flag"}, "error": "ls: cannot access 'done.flag'"}
573
+ for _ in range(10):
574
+ assert hook("pre", wait) is None
575
+ assert hook("postfail", fail) is None
576
+ for _ in range(3):
577
+ assert hook("pre", dict(PRE, tool_input={"command": "pwd"})) is None
578
+ assert hook("pre", dict(PRE, tool_input={"command": "pwd"}))["hookSpecificOutput"]["permissionDecision"] == "deny"
@@ -275,7 +275,7 @@ def _runner(argv, tmp_path, live, **kw): # noqa: D401
275
275
 
276
276
  r = q.QuotaRunner(argv, quota=kw.pop("quota", 50.0), stderr=err, poll_s=0.05, claude_grace_s=1.0,
277
277
  receipt_dir=tmp_path / "receipts", cwd=tmp_path, home=tmp_path / "home",
278
- live_reader=reader, live_settle_s=0.05, **kw)
278
+ live_reader=reader, live_settle_s=0.05, **{"settle_s": 0, **kw})
279
279
  return r, err, asked
280
280
 
281
281
 
@@ -529,3 +529,156 @@ def test_a_background_agentcap_does_not_freeze_on_the_terminal(tmp_path):
529
529
  script.write_text(BACKGROUND_TTY)
530
530
  r = subprocess.run([sys.executable, str(script), src], capture_output=True, text=True, timeout=30)
531
531
  assert r.returncode == 0, (r.returncode, r.stderr)
532
+
533
+
534
+
535
+ # ------------------------------------------------- gate test 13 Nov: waits and settle
536
+ from agentcap.waste import command_text, is_wait_call # noqa: E402
537
+
538
+ CODEX_EXEC_WAIT = 'text(await tools.exec_command({cmd:"sleep 4; ls done.flag",max_output_tokens:100}));\n'
539
+
540
+
541
+ def test_wait_calls_are_recognised():
542
+ assert is_wait_call("Bash", {"command": "sleep 4; ls done.flag"})
543
+ assert is_wait_call("Bash", {"command": "sleep 30 && curl -s localhost:8080/health"})
544
+ assert is_wait_call("exec", CODEX_EXEC_WAIT)
545
+ assert is_wait_call("shell", {"command": ["bash", "-lc", "sleep 2.5\nls"]})
546
+ assert is_wait_call("TaskOutput", {})
547
+ for cmd in ("pwd", "sleepy 3", "echo hi; sleep 3", "npm test"):
548
+ assert not is_wait_call("Bash", {"command": cmd}), cmd
549
+ assert command_text(CODEX_EXEC_WAIT) == "sleep 4; ls done.flag"
550
+
551
+
552
+ def test_codex_waits_trip_neither_breaker():
553
+ w = q.LoopWatch()
554
+ for _ in range(10): # the live polling job: same call, failing `ls`, until the file appears
555
+ w.feed_codex({"type": "response_item", "payload": {"type": "custom_tool_call", "name": "exec",
556
+ "input": CODEX_EXEC_WAIT}})
557
+ w.feed_codex({"type": "response_item", "payload": {"type": "custom_tool_call_output",
558
+ "output": "Exit code: 2\nls: cannot access"}})
559
+ assert w.tripped is None
560
+ for _ in range(4):
561
+ w.call("exec", 'text(await tools.exec_command({cmd:"pwd"}));')
562
+ assert w.tripped and "same tool call 4 times" in w.tripped
563
+
564
+
565
+ def test_claude_hook_does_not_count_waits(tmp_path):
566
+ (tmp_path / "job.json").write_text(json.dumps({"enforce": True, "quota": 5, "window": "5h"}))
567
+ wait = {"tool_name": "Bash", "tool_input": {"command": "sleep 4; ls done.flag"}}
568
+ for _ in range(8):
569
+ assert q._loop_hook(tmp_path, wait) is None
570
+ pwd = {"tool_name": "Bash", "tool_input": {"command": "pwd"}}
571
+ assert [q._loop_hook(tmp_path, pwd) for _ in range(4)][-1] is not None
572
+
573
+
574
+ def test_transcript_error_streak_skips_wait_results(tmp_path):
575
+ path = tmp_path / "t.jsonl"
576
+ with open(path, "w") as fh:
577
+ for i in range(10):
578
+ fh.write(json.dumps({"message": {"content": [{"type": "tool_use", "id": f"w{i}", "name": "Bash",
579
+ "input": {"command": "sleep 4; ls done.flag"}}]}}) + "\n")
580
+ fh.write(json.dumps({"message": {"content": [{"type": "tool_result", "tool_use_id": f"w{i}",
581
+ "is_error": True, "content": "ls: cannot access"}]}}) + "\n")
582
+ assert q.transcript_error_streak(str(path)) == 0
583
+
584
+
585
+ def test_post_hook_ignores_a_failing_wait(tmp_path):
586
+ import io
587
+ payload = {"hook_event_name": "PostToolUseFailure", "tool_name": "Bash",
588
+ "tool_input": {"command": "sleep 4; ls done.flag"}}
589
+ for _ in range(9):
590
+ q.post_main(tmp_path, io.StringIO(json.dumps(payload)))
591
+ assert not (tmp_path / "post_errors.json").exists()
592
+
593
+
594
+ def _settle_setup(tmp_path, at_exit=0.0):
595
+ receipt = tmp_path / "r.json"
596
+ receipt.write_text(json.dumps({"type": "agentcap_quota_receipt", "share_pct": at_exit, "reason": "exited"}))
597
+ job = tmp_path / "jobs" / "job"
598
+ job.mkdir(parents=True)
599
+ t = q.ShareTracker()
600
+ t.seed(q.Reading(40.0, 5000.0))
601
+ (job / "settle.json").write_text(json.dumps({"receipt": str(receipt), "window": "5h",
602
+ "tracker": t.to_dict(), "until": 1000.0 + 90,
603
+ "ended_at": 1000.0}))
604
+ return receipt, job
605
+
606
+
607
+ def test_settle_rewrites_the_receipt_with_the_late_usage(tmp_path):
608
+ # live gate test: short Claude jobs read 0.0% at exit; /usage caught up 30-90 s later
609
+ receipt, job = _settle_setup(tmp_path)
610
+ values = iter([40.0, 41.0, 42.0, 42.0, 42.0, 42.0, 42.0, 42.0])
611
+ clock = [1000.0]
612
+
613
+ def sleep(s):
614
+ clock[0] += s
615
+
616
+ q.settle_main(job, reader=lambda a: {"5h": q.Reading(next(values), 5000.0)}, sleep=sleep,
617
+ clock=lambda: clock[0], step_s=20)
618
+ r = json.loads(receipt.read_text())
619
+ assert r["share_pct"] == 2.0 and r["share_pct_at_exit"] == 0.0 and r["settled"] is True
620
+ assert clock[0] - 1000.0 <= 90
621
+
622
+
623
+ def test_settle_never_lowers_the_receipt(tmp_path):
624
+ receipt, job = _settle_setup(tmp_path, at_exit=3.0)
625
+ clock = [1000.0]
626
+ q.settle_main(job, reader=lambda a: {"5h": q.Reading(41.0, 5000.0)},
627
+ sleep=lambda s: clock.__setitem__(0, clock[0] + s), clock=lambda: clock[0], step_s=20)
628
+ assert json.loads(receipt.read_text())["share_pct"] == 3.0
629
+
630
+
631
+ def test_claude_job_starts_the_settle_process(fakebin, tmp_path, monkeypatch):
632
+ monkeypatch.setenv("FAKE_START", "39")
633
+ monkeypatch.setenv("FAKE_N", "1")
634
+ started = []
635
+ r, err, asked = _runner(["claude"], tmp_path, {}, settle_s=150)
636
+ r._spawn_detached = lambda argv, **kw: started.append(argv)
637
+ r.live_reader = _seq(38.0, 40.0)
638
+ assert r.run() == 0
639
+ assert started and started[0][-3:] == ["settle", "--job", str(r.job_dir)] and "-P" in started[0]
640
+ cfg = json.loads((r.job_dir / "settle.json").read_text())
641
+ assert cfg["window"] == "week" and Path(cfg["receipt"]).exists()
642
+ assert "updated with the settled share" in err.getvalue()
643
+
644
+
645
+ def test_codex_job_has_no_settle_process(fakebin, tmp_path, monkeypatch):
646
+ monkeypatch.setenv("FAKE_N", "1")
647
+ started = []
648
+ r, err, asked = _runner(["codex"], tmp_path, {"codex": {"week": q.Reading(39.0, time.time() + 86400)}}, settle_s=150)
649
+ r._spawn_detached = lambda argv, **kw: started.append(argv)
650
+ r.run()
651
+ assert started == [] and not (r.job_dir / "settle.json").exists()
652
+
653
+
654
+ def test_settle_entry_point_runs_as_a_detached_process(tmp_path):
655
+ import subprocess
656
+ receipt, job = _settle_setup(tmp_path)
657
+ cfg = json.loads((job / "settle.json").read_text())
658
+ cfg["until"] = time.time() + 0.5
659
+ (job / "settle.json").write_text(json.dumps(cfg))
660
+ src = str(Path(__file__).resolve().parents[1] / "src")
661
+ env = {**os.environ, "PYTHONPATH": src, "AGENTCAP_LIVE_QUOTA": "0"}
662
+ code = subprocess.run([sys.executable, "-P", "-m", "agentcap.quota", "settle", "--job", str(job)],
663
+ env=env, timeout=60).returncode
664
+ assert code == 0 and json.loads(receipt.read_text())["settled"] is True
665
+
666
+
667
+
668
+ def test_settle_stops_when_the_next_quota_job_starts(tmp_path):
669
+ # live 0.4.1 check: the next job's 1% was charged to the previous job's settled receipt
670
+ receipt, job = _settle_setup(tmp_path)
671
+ clock = [1000.0]
672
+ reads = iter([41.0, 42.0, 45.0, 46.0])
673
+
674
+ def reader(agent):
675
+ if clock[0] >= 1040.0 and not (job.parent / "next").exists():
676
+ nxt = job.parent / "next"
677
+ nxt.mkdir()
678
+ (nxt / "job.json").write_text(json.dumps({"started_at": 1045.0}))
679
+ return {"5h": q.Reading(next(reads), 5000.0)}
680
+
681
+ q.settle_main(job, reader=reader, sleep=lambda s: clock.__setitem__(0, clock[0] + s),
682
+ clock=lambda: clock[0], step_s=20)
683
+ r = json.loads(receipt.read_text())
684
+ assert r["share_pct"] == 2.0 and r["settle_cut"] == "another quota job started"
@@ -352,7 +352,7 @@ def test_auth_rejected_statuses():
352
352
  "sk-proj-AbCdEf0123456789AbCdEf0123456789",
353
353
  "sk-ant-api03-AbCdEf0123456789AbCdEf0123456789",
354
354
  "AIza" + "Sy" + "T" * 33, # built at runtime: test fixture, never a real key
355
- "ghp_0123456789abcdefABCDEF0123456789abcd",
355
+ "gh" + "p_" + "0123456789abcdefABCDEF0123456789abcd", # built at runtime: test fixture, never a real token
356
356
  "Bearer abc.def.ghi",
357
357
  ],
358
358
  )
File without changes
File without changes