agentcap-cli 0.2.0__py3-none-any.whl → 0.2.1__py3-none-any.whl

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.
agentcap/__init__.py CHANGED
@@ -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__"]
agentcap/cli.py CHANGED
@@ -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
agentcap/history.py CHANGED
@@ -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)
agentcap/quota.py CHANGED
@@ -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
agentcap/waste.py CHANGED
@@ -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")
@@ -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>`)
@@ -1,32 +1,32 @@
1
- agentcap/__init__.py,sha256=fJoGav2uqSSta869IQmoirDJ8WEXDs2KdSYfzjQ5_sY,152
1
+ agentcap/__init__.py,sha256=zW95XkcrJTCaeUEIHz0HlwdWtEsBqPo03P4xflQley8,152
2
2
  agentcap/adapters.py,sha256=bgLjxW06At-uIyjLTmw4AscUVRkl0d2l6G8Qn8li3T8,17465
3
3
  agentcap/alerts.py,sha256=4Jn033yzjn7jkVwB_2LJ4w91GNBgDYFozF8UdnIf47U,13424
4
4
  agentcap/analytics.py,sha256=eiBmmdyzapqcoC6rnaGPbON8tN9cTabae8oyXjFr3Rc,14567
5
5
  agentcap/budget.py,sha256=fgweW2Lr2x52YkgWY10sbtiHraMAqXZmiG-zEGGdIbc,4270
6
6
  agentcap/clamp.py,sha256=cizXJaLMAQ-VlFKT8UhK7UTzlZ8Icp8ytrkE9CK41gg,10269
7
- agentcap/cli.py,sha256=JqFlgcqS1O_Uta7ffogYlhCwMbSsQzaEHuquNASqf4Q,25962
7
+ agentcap/cli.py,sha256=q5ArwlucPhyRwdySQj44FQ585Mb-itSrW_RJkmXs3e0,26209
8
8
  agentcap/cli_history.py,sha256=LZQZH7cP9ORSOSspGzJjTSFGVtR6Wt7Smuz1Cho0fuA,10092
9
9
  agentcap/demo.py,sha256=21ZbAyaSrK8AZOkcH4GNZnvNe3z7xjz0ufdOKRXam00,4643
10
10
  agentcap/estimate.py,sha256=-a2Ai-qDeyNMr-j5GHs1BtcAjYAkXGCNeYofByAyyhI,17656
11
11
  agentcap/eta.py,sha256=eflzCdSXFzu968tLCfMEMa4DM3-Nnnti1B5ZMi9aWWk,2153
12
- agentcap/history.py,sha256=xe_bFSVhry5kYhf_pQHFp2jqNSU3mJSHhnLuIJdck8E,19937
12
+ agentcap/history.py,sha256=55q5YxdUGwwF1crhiW-zqPZaYs7cKBC7DPXq2C-v7Ck,20036
13
13
  agentcap/ledger.py,sha256=YG9hrFdW5mGHw_kpt8xoWL-lIKshMUJMdPS2aaamIbw,13104
14
14
  agentcap/license.py,sha256=HtER69lgcYlrGWgob_iHIZVzRKW0qnWTAdUHHK9AUto,25945
15
15
  agentcap/loop.py,sha256=F7dUnbkt9GvuUm6csaqjncULtSwaGaxUpBb5IGEQ6L8,14153
16
16
  agentcap/plans.py,sha256=NwoRtjcFNW0yCMK2F63wozhAAN9DKOMl-ee5ZXCljO8,2895
17
17
  agentcap/pricing.py,sha256=MR3zYlVnN1dlJwnSk5IiWGYoF7k3LuShNnIgrYWpxj8,24001
18
18
  agentcap/proxy.py,sha256=JPtPnN9B7AN_vy5GyRHXn4NT0Aas-TBWFvpORH-wf9o,57987
19
- agentcap/quota.py,sha256=n9_O9NkYa64jE781QdJTvKqkhezA1Sa8Nmr2cdr99JQ,35955
19
+ agentcap/quota.py,sha256=yPIWdLFN-Pjcc_XrAMsT_ZTiFGKzGR04nXcEHvvaWB0,40928
20
20
  agentcap/report.py,sha256=RFVZab6-b9x9bnmbX5T30wV4RiZcuzlBTU4eZOJ-OKo,8563
21
21
  agentcap/runner.py,sha256=zthG-k4fzbwEppAlFueH44hNxp3BdM7GXnXwdwbnwSg,27419
22
22
  agentcap/upstreams.py,sha256=SSLZQh-HyEG9g867TnHOoOH2m4TneDxqBaNdXeyGuKk,4072
23
23
  agentcap/usage.py,sha256=ia3ATfKpmpYBor7ilRCBOFj3DMP9yty7BiLIxj4EEe8,17872
24
- agentcap/waste.py,sha256=x7v_kP-M5dHQtyd4qvt5p0Xn0WnWnS7JkekOp6LGdqA,19103
24
+ agentcap/waste.py,sha256=2AIfc7a67u98AZe8-bjn_xP99-XBApNc6ladxfzB_8U,21342
25
25
  agentcap/data/pricing.json,sha256=e1ZtPA7nD5lpgc3LwE3GTqfXykMXPHHLNsrv1tv4oMU,17741
26
26
  agentcap/devtools/__init__.py,sha256=EmCJZQ3xK6hAE3jPsu6w8f2IdwlW_akY0Stp2HH66Kg,60
27
27
  agentcap/devtools/fake_upstream.py,sha256=uDKvARc0ltxn9pnxOFqJ2XNENII4-UZovTbvX9SPVYE,21760
28
- agentcap_cli-0.2.0.dist-info/METADATA,sha256=WOex9aEaDl_K302Cm7a5ApaRq-5-p6neBHKu4avhXp0,37074
29
- agentcap_cli-0.2.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
30
- agentcap_cli-0.2.0.dist-info/entry_points.txt,sha256=eUEtK13KEPXT2pO_lD6zzZWu5yHHo7EKrVQe3Fw6q4U,47
31
- agentcap_cli-0.2.0.dist-info/licenses/LICENSE,sha256=b9WVuKHVLMITmseyT63ENNC9TbX_zg_I0oSQNJVGYJo,1070
32
- agentcap_cli-0.2.0.dist-info/RECORD,,
28
+ agentcap_cli-0.2.1.dist-info/METADATA,sha256=YE0gvQDMnr0rYeB-7n6tdzhQ4ao56cFFfmH4lJSPmw0,39535
29
+ agentcap_cli-0.2.1.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
30
+ agentcap_cli-0.2.1.dist-info/entry_points.txt,sha256=eUEtK13KEPXT2pO_lD6zzZWu5yHHo7EKrVQe3Fw6q4U,47
31
+ agentcap_cli-0.2.1.dist-info/licenses/LICENSE,sha256=b9WVuKHVLMITmseyT63ENNC9TbX_zg_I0oSQNJVGYJo,1070
32
+ agentcap_cli-0.2.1.dist-info/RECORD,,