agentcap-cli 0.2.0__py3-none-any.whl → 0.2.2__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 +1 -1
- agentcap/cli.py +8 -0
- agentcap/history.py +4 -2
- agentcap/quota.py +131 -12
- agentcap/waste.py +45 -11
- {agentcap_cli-0.2.0.dist-info → agentcap_cli-0.2.2.dist-info}/METADATA +42 -10
- {agentcap_cli-0.2.0.dist-info → agentcap_cli-0.2.2.dist-info}/RECORD +10 -10
- {agentcap_cli-0.2.0.dist-info → agentcap_cli-0.2.2.dist-info}/WHEEL +0 -0
- {agentcap_cli-0.2.0.dist-info → agentcap_cli-0.2.2.dist-info}/entry_points.txt +0 -0
- {agentcap_cli-0.2.0.dist-info → agentcap_cli-0.2.2.dist-info}/licenses/LICENSE +0 -0
agentcap/__init__.py
CHANGED
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
|
|
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,58 @@ WARN_FRACTION = 0.8
|
|
|
38
43
|
EXIT_QUOTA_EXCEEDED = 3
|
|
39
44
|
EXIT_LOOP_DETECTED = 4
|
|
40
45
|
BASELINE_MAX_AGE_S = 15 * 60
|
|
46
|
+
APPROVE_FACTOR = 1.5
|
|
47
|
+
APPROVE_MAX = 2
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def is_headless_claude(argv: Sequence[str]) -> bool:
|
|
51
|
+
"""``claude -p`` / ``--print`` runs non-interactively; nobody is there to approve."""
|
|
52
|
+
|
|
53
|
+
return any(a in ("-p", "--print") or a.startswith("--print=") for a in argv[1:])
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _running_jobs(root: Path) -> list[Path]:
|
|
57
|
+
jobs = root / "jobs"
|
|
58
|
+
if not jobs.is_dir():
|
|
59
|
+
return []
|
|
60
|
+
out = [d for d in jobs.iterdir()
|
|
61
|
+
if (d / "job.json").exists() and not (d / "done.json").exists()]
|
|
62
|
+
return sorted(out, key=lambda d: (d / "job.json").stat().st_mtime, reverse=True)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def approve_job(root: Path | None = None) -> str:
|
|
66
|
+
"""Raise the newest running quota job's limit by 50% (max twice) and clear a loop stop."""
|
|
67
|
+
|
|
68
|
+
root = root or state_root()
|
|
69
|
+
running = _running_jobs(root)
|
|
70
|
+
if not running:
|
|
71
|
+
return "agentcap: no running quota job to approve."
|
|
72
|
+
d = running[0]
|
|
73
|
+
job = _read_json(d / "job.json") or {}
|
|
74
|
+
if not job.get("enforce"):
|
|
75
|
+
return "agentcap: this job is observe-only (Free); approve is a Pro feature."
|
|
76
|
+
if job.get("stopped"):
|
|
77
|
+
return ("agentcap: this job was already stopped (SIGINT), so approve cannot resume it. "
|
|
78
|
+
"Start it again with a higher --quota.")
|
|
79
|
+
n = int(job.get("approvals") or 0)
|
|
80
|
+
if n >= APPROVE_MAX:
|
|
81
|
+
return (f"agentcap: already approved twice (limit {float(job.get('quota', 0)):g}%); "
|
|
82
|
+
"start a new job if you really need more.")
|
|
83
|
+
new = round(float(job.get("quota", 0)) * APPROVE_FACTOR, 4)
|
|
84
|
+
job.update({"quota": new, "approvals": n + 1, "approved_at": time.time()})
|
|
85
|
+
_atomic_write(d / "job.json", job)
|
|
86
|
+
status = _read_json(d / "status.json")
|
|
87
|
+
if status:
|
|
88
|
+
status["limit_hit"] = False
|
|
89
|
+
status["quota"] = new
|
|
90
|
+
_atomic_write(d / "status.json", status)
|
|
91
|
+
for name in ("loop.json", "tools.json", "denies.log"):
|
|
92
|
+
try:
|
|
93
|
+
(d / name).unlink()
|
|
94
|
+
except OSError:
|
|
95
|
+
pass
|
|
96
|
+
return (f"agentcap: approved ({n + 1}/{APPROVE_MAX}): limit raised to {new:g}% of the "
|
|
97
|
+
f"{'weekly' if job.get('window') == 'week' else '5-hour'} quota; the run continues.")
|
|
41
98
|
CLAUDE_KEYS = {"5h": "five_hour", "week": "seven_day"}
|
|
42
99
|
CODEX_MINUTES = {"5h": 300, "week": 10080}
|
|
43
100
|
STATE_ENV = "AGENTCAP_QUOTA_DIR"
|
|
@@ -425,7 +482,7 @@ def _loop_hook(job_dir: Path, payload: Mapping[str, Any]) -> str | None:
|
|
|
425
482
|
d = _digest(name, payload.get("tool_input"))
|
|
426
483
|
state = _read_json(job_dir / "tools.json") or {}
|
|
427
484
|
count = int(state.get("count") or 0) + 1 if state.get("digest") == d else 1
|
|
428
|
-
_atomic_write(job_dir / "tools.json", {"digest": d, "count": count})
|
|
485
|
+
_atomic_write(job_dir / "tools.json", {"digest": d, "count": count, "tool": name[:40]})
|
|
429
486
|
if count < LOOP_REPEATS:
|
|
430
487
|
return None
|
|
431
488
|
enforce = bool((_read_json(job_dir / "job.json") or {}).get("enforce"))
|
|
@@ -434,10 +491,19 @@ def _loop_hook(job_dir: Path, payload: Mapping[str, Any]) -> str | None:
|
|
|
434
491
|
"stopped": enforce, "ts": time.time()})
|
|
435
492
|
if not enforce:
|
|
436
493
|
return None
|
|
494
|
+
_note_deny(job_dir)
|
|
437
495
|
return (f"agentcap loop breaker: {detail}. Stop now: do not call more tools; "
|
|
438
496
|
"summarise what is done and what is left.")
|
|
439
497
|
|
|
440
498
|
|
|
499
|
+
def _note_deny(job_dir: Path) -> None:
|
|
500
|
+
try:
|
|
501
|
+
with open(job_dir / "denies.log", "a", encoding="utf-8") as fh:
|
|
502
|
+
fh.write(f"{time.time()}\n")
|
|
503
|
+
except OSError:
|
|
504
|
+
pass
|
|
505
|
+
|
|
506
|
+
|
|
441
507
|
def _deny(stdout: TextIO, reason: str) -> int:
|
|
442
508
|
json.dump(
|
|
443
509
|
{
|
|
@@ -471,16 +537,12 @@ def hook_main(job_dir: Path, stdin: TextIO, stdout: TextIO) -> int:
|
|
|
471
537
|
status = _read_json(job_dir / "status.json")
|
|
472
538
|
if not status or not status.get("limit_hit"):
|
|
473
539
|
return 0
|
|
474
|
-
|
|
475
|
-
with open(job_dir / "denies.log", "a", encoding="utf-8") as fh:
|
|
476
|
-
fh.write(f"{time.time()}\n")
|
|
477
|
-
except OSError:
|
|
478
|
-
pass
|
|
540
|
+
_note_deny(job_dir)
|
|
479
541
|
reason = (
|
|
480
542
|
f"agentcap quota mode: this job used {float(status.get('share', 0)):.1f}% of the "
|
|
481
543
|
f"{'weekly' if status.get('window') == 'week' else '5-hour'} subscription quota "
|
|
482
544
|
f"(limit {float(status.get('quota', 0)):g}%). Stop now: do not call more tools; "
|
|
483
|
-
"summarise what is done and what is left."
|
|
545
|
+
"summarise what is done and what is left. (The user can run `agentcap approve` to raise it.)"
|
|
484
546
|
)
|
|
485
547
|
json.dump(
|
|
486
548
|
{
|
|
@@ -633,6 +695,7 @@ class QuotaRunner:
|
|
|
633
695
|
self.agent = detect_quota_agent(self.argv)
|
|
634
696
|
if self.agent is None:
|
|
635
697
|
raise ValueError("quota mode supports `claude` and `codex` only")
|
|
698
|
+
self.headless = self.agent == "codex" or is_headless_claude(self.argv)
|
|
636
699
|
self.quota = quota
|
|
637
700
|
self.window = window
|
|
638
701
|
self.enforce = enforce
|
|
@@ -685,6 +748,12 @@ class QuotaRunner:
|
|
|
685
748
|
pass
|
|
686
749
|
|
|
687
750
|
def _stop(self) -> None:
|
|
751
|
+
job = _read_json(self.job_dir / "job.json") or {}
|
|
752
|
+
job["stopped"] = True # a signalled job cannot be resumed by `agentcap approve`
|
|
753
|
+
try:
|
|
754
|
+
_atomic_write(self.job_dir / "job.json", job)
|
|
755
|
+
except OSError:
|
|
756
|
+
pass
|
|
688
757
|
self._signal(signal.SIGINT)
|
|
689
758
|
deadline = time.time() + 5
|
|
690
759
|
while self.child and self.child.poll() is None and time.time() < deadline:
|
|
@@ -711,7 +780,12 @@ class QuotaRunner:
|
|
|
711
780
|
_atomic_write(settings, claude_settings(self.job_dir))
|
|
712
781
|
argv = inject_claude_settings(argv, settings)
|
|
713
782
|
else:
|
|
783
|
+
_atomic_write(self.job_dir / "job.json", {
|
|
784
|
+
"quota": self.quota, "window": self.window, "started_at": started,
|
|
785
|
+
"enforce": self.enforce, "agent": "codex",
|
|
786
|
+
})
|
|
714
787
|
tailer = CodexTailer(self.sessions_dir, started)
|
|
788
|
+
self._tailer = tailer
|
|
715
789
|
prior = tailer.last_reading_before(self.window)
|
|
716
790
|
if prior and started - prior[0] <= BASELINE_MAX_AGE_S and (
|
|
717
791
|
prior[1].resets_at is None or prior[1].resets_at > started
|
|
@@ -726,6 +800,9 @@ class QuotaRunner:
|
|
|
726
800
|
else f"observe only (Free); Pro would stop it at {self.quota:g}%")
|
|
727
801
|
+ ". Read-only; your login and traffic are untouched."
|
|
728
802
|
)
|
|
803
|
+
if self.agent == "codex" and self.quota < 1:
|
|
804
|
+
self._say(f"agentcap: WARNING: Codex reports quota in whole percent, so a {self.quota:g}% cap "
|
|
805
|
+
"cannot trigger until the job has used a full 1%. Use --quota 1% or more for Codex.")
|
|
729
806
|
self.child = subprocess.Popen(argv, env=env, start_new_session=True, cwd=self.cwd)
|
|
730
807
|
|
|
731
808
|
warned = hit = parallel = observed = no_data_warned = False
|
|
@@ -735,10 +812,22 @@ class QuotaRunner:
|
|
|
735
812
|
reason = "exited"
|
|
736
813
|
share = 0.0
|
|
737
814
|
stopped = False
|
|
815
|
+
open_said = False
|
|
816
|
+
approvals = 0
|
|
738
817
|
try:
|
|
739
818
|
while True:
|
|
740
819
|
code = self.child.poll()
|
|
741
820
|
now = time.time()
|
|
821
|
+
jobnow = _read_json(self.job_dir / "job.json") or {}
|
|
822
|
+
if int(jobnow.get("approvals") or 0) > approvals and code is None:
|
|
823
|
+
approvals = int(jobnow["approvals"])
|
|
824
|
+
self.quota = float(jobnow.get("quota", self.quota))
|
|
825
|
+
hit = warned = stopped = open_said = False
|
|
826
|
+
hit_at = loop_at = None
|
|
827
|
+
loop_detail = None
|
|
828
|
+
self._say(f"agentcap: approved ({approvals}/{APPROVE_MAX}): limit is now "
|
|
829
|
+
f"{self.quota:g}%; continuing.")
|
|
830
|
+
self._event("quota_approved", share, approvals=approvals)
|
|
742
831
|
if self.agent == "claude":
|
|
743
832
|
status = _read_json(self.job_dir / "status.json") or {}
|
|
744
833
|
if status.get("has_rate_limits"):
|
|
@@ -784,8 +873,10 @@ class QuotaRunner:
|
|
|
784
873
|
and hit_at is not None and code is None
|
|
785
874
|
):
|
|
786
875
|
denies = (self.job_dir / "denies.log").exists()
|
|
787
|
-
if
|
|
788
|
-
self.
|
|
876
|
+
if not self.headless and denies:
|
|
877
|
+
open_said = self._say_open(open_said, "the quota limit")
|
|
878
|
+
elif now - hit_at >= (self.claude_grace_s if denies else self.claude_grace_s * 3):
|
|
879
|
+
self._stop() # headless, or the hook never ran (fallback)
|
|
789
880
|
stopped = True
|
|
790
881
|
if loop_detail is None:
|
|
791
882
|
if self.agent == "claude":
|
|
@@ -802,9 +893,14 @@ class QuotaRunner:
|
|
|
802
893
|
self._stop()
|
|
803
894
|
stopped = True
|
|
804
895
|
if (loop_detail and self.enforce and not stopped and code is None
|
|
805
|
-
and loop_at is not None
|
|
806
|
-
self.
|
|
807
|
-
|
|
896
|
+
and loop_at is not None):
|
|
897
|
+
denies = (self.job_dir / "denies.log").exists()
|
|
898
|
+
if not self.headless and denies:
|
|
899
|
+
open_said = self._say_open(open_said, "the loop breaker")
|
|
900
|
+
elif now - loop_at >= (self.claude_grace_s if denies or self.headless
|
|
901
|
+
else self.claude_grace_s * 3):
|
|
902
|
+
self._stop()
|
|
903
|
+
stopped = True
|
|
808
904
|
self._live(share, observed, hit)
|
|
809
905
|
if code is not None:
|
|
810
906
|
break
|
|
@@ -827,8 +923,27 @@ class QuotaRunner:
|
|
|
827
923
|
tracker.baseline_exact, tracker.resets_seen, parallel, observed,
|
|
828
924
|
)
|
|
829
925
|
self._receipt(self.summary)
|
|
926
|
+
try:
|
|
927
|
+
_atomic_write(self.job_dir / "done.json", {"ts": time.time(), "exit_code": code})
|
|
928
|
+
except OSError:
|
|
929
|
+
pass
|
|
830
930
|
return code
|
|
831
931
|
|
|
932
|
+
def _say_open(self, said: bool, what: str) -> bool:
|
|
933
|
+
if not said:
|
|
934
|
+
self._say(f"agentcap: {what} stopped this turn (tool calls are denied). The session stays "
|
|
935
|
+
"open: run `agentcap approve` in another terminal to raise the limit by 50% "
|
|
936
|
+
f"(at most {APPROVE_MAX}x), or quit Claude Code.")
|
|
937
|
+
return True
|
|
938
|
+
|
|
939
|
+
def _last_tool(self) -> str | None:
|
|
940
|
+
t = _read_json(self.job_dir / "tools.json") or {}
|
|
941
|
+
name = t.get("tool")
|
|
942
|
+
if not name and self.agent == "codex":
|
|
943
|
+
tailer = getattr(self, "_tailer", None)
|
|
944
|
+
name = tailer.loop.tool if tailer is not None else None
|
|
945
|
+
return str(name)[:40] if name else None
|
|
946
|
+
|
|
832
947
|
def _live(self, share: float, observed: bool, hit: bool) -> None:
|
|
833
948
|
"""Optional live status for editor integrations (AGENTCAP_QUOTA_LIVE)."""
|
|
834
949
|
|
|
@@ -861,6 +976,9 @@ class QuotaRunner:
|
|
|
861
976
|
+ (f" (limit {s.quota:g}%)" if self.enforce else "")
|
|
862
977
|
+ (f"; {'; '.join(notes)}" if notes else "") + "."
|
|
863
978
|
)
|
|
979
|
+
last = self._last_tool()
|
|
980
|
+
if last:
|
|
981
|
+
self._say(f"agentcap: last tool call: {last}")
|
|
864
982
|
if not self.enforce and s.share >= s.quota:
|
|
865
983
|
self._say(
|
|
866
984
|
f"agentcap: Pro's quota mode would have stopped this job at {s.quota:g}%. "
|
|
@@ -875,6 +993,7 @@ class QuotaRunner:
|
|
|
875
993
|
"quota_pct": s.quota, "share_pct": s.share, "exit_code": s.exit_code,
|
|
876
994
|
"reason": s.reason, "baseline_exact": s.baseline_exact,
|
|
877
995
|
"parallel_sessions": s.parallel, "window_resets": s.resets_seen,
|
|
996
|
+
"last_tool": last,
|
|
878
997
|
})
|
|
879
998
|
except OSError:
|
|
880
999
|
pass
|
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
|
-
|
|
200
|
-
|
|
201
|
-
|
|
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
|
-
|
|
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.
|
|
3
|
+
Version: 0.2.2
|
|
4
4
|
Summary: API-key spend guard for unattended Codex CLI, Gemini CLI and Claude Code runs: hard per-run cap, kills the process at the limit.
|
|
5
5
|
Project-URL: Homepage, https://agentcap.launchbench.studio
|
|
6
6
|
Project-URL: Repository, https://github.com/Blitz00X/agentcap
|
|
@@ -40,7 +40,10 @@ tool loops and error streaks.
|
|
|
40
40
|
$ agentcap waste --since 7d
|
|
41
41
|
SUBAGENTS $41.20 25% of spend in 31 subagent/forked threads
|
|
42
42
|
OPUS $38.90 24% of spend
|
|
43
|
-
CACHE MISSES $6.10 57 cache re-writes after the TTL ran out (5 min, or 1 h)
|
|
43
|
+
CACHE MISSES $6.10 57 cache re-writes after the TTL ran out (5 min since the last request, or 1 h)
|
|
44
|
+
main session $2.30 21x subagents $3.80 36x
|
|
45
|
+
Tip: idle subagents re-wrote their own context 36x (~$3.80). Set subagentPromptCacheTtl: "1h" ...
|
|
46
|
+
STARTING CONTEXT 31 subagents, first request median 38.2k tok, largest 131.0k (7f3a91c2/a1b2c3d4)
|
|
44
47
|
REPEATED TOOL CALLS $9.80 12 streaks of >= 3 identical calls in a row
|
|
45
48
|
TOOL ERROR STREAKS $4.30 5 streaks of >= 3 failing calls in a row
|
|
46
49
|
Pro would have stopped this run at $3.12 / at 4 repeats (Bash x11 in 7f3a91c2, $2.40 after that).
|
|
@@ -53,16 +56,31 @@ Pro would have stopped this run at $3.12 / at 4 repeats (Bash x11 in 7f3a91c2, $
|
|
|
53
56
|
agentcap run --quota 5% -- claude # subscription: stop at 5% of the weekly quota, or on a loop
|
|
54
57
|
agentcap run --quota 10% --window 5h -- codex # same for Codex on a ChatGPT plan
|
|
55
58
|
agentcap run --cap 2 -- codex exec "fix tests" # API key: $2 cap + loop/burn breaker
|
|
59
|
+
agentcap approve # raise a stopped job's limit by 50% (at most twice)
|
|
56
60
|
```
|
|
57
61
|
|
|
62
|
+
On a $20/month Codex plan, two code-review prompts used the whole 5-hour limit
|
|
63
|
+
([Povilas Korop](https://x.com/PovilasKorop/status/2116114249655501050): $7.70 + $1.43 at API prices).
|
|
64
|
+
`--quota 10% --window 5h -- codex` stops the job before that.
|
|
65
|
+
|
|
66
|
+
Free tools like [claude-code-spend-stop](https://github.com/VedantBhayani/claude-code-spend-stop) and
|
|
67
|
+
[RelayPlane](https://relayplane.com) give you a free $ cap. AgentCap adds the loop breaker, a cap on
|
|
68
|
+
your subscription quota % and Codex support.
|
|
69
|
+
|
|
58
70
|
- **Loop breaker.** Same tool call (name + input) 4 times in a row, or 8 failing tool calls in a
|
|
59
71
|
row: the run is stopped (exit 4). On subscriptions it works without touching your login or
|
|
60
|
-
traffic: Claude Code via an official `PreToolUse` hook (denies the 4th identical call
|
|
61
|
-
|
|
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
|
|
78
|
+
`this job used 5.1% of the weekly quota`) and the last tool call's name, as numbers and tool
|
|
79
|
+
names only, never prompts or tool inputs.
|
|
80
|
+
- **Approve.** After a stop, `agentcap approve` (or `/agentcap:approve` in the plugin) raises the
|
|
81
|
+
limit by 50%, at most twice, and the run continues. This works for interactive Claude Code,
|
|
82
|
+
which stays open after a stop. Codex and headless `claude -p` jobs are stopped with SIGINT, so
|
|
83
|
+
there approve only helps before the limit is hit; after a stop it says so and changes nothing.
|
|
66
84
|
- **Free** runs the same detectors in observe-only mode and prints what Pro would have done.
|
|
67
85
|
|
|
68
86
|
Honest limits: Claude tool-error streaks are only caught on API-key runs (the subscription hook sees
|
|
@@ -135,10 +153,12 @@ integrated terminal behind `agentcap run --cap`, shows live run spend in the
|
|
|
135
153
|
status bar, warns at 80% / 95%, and shows a modal when the cap (exit 3) or Pro's
|
|
136
154
|
loop breaker (exit 4) stops the run. It needs the `agentcap` CLI above.
|
|
137
155
|
|
|
138
|
-
It is **not on the VS Code Marketplace or Open VSX yet**.
|
|
139
|
-
|
|
156
|
+
It is **not on the VS Code Marketplace or Open VSX yet**. [Download agentcap-0.2.0.vsix](https://agentcap.launchbench.studio/agentcap-0.2.0.vsix)
|
|
157
|
+
(sha256 `175213b0979019cb472752ad71e613a48c6a22e7d899b761093ab7eac9867e70`) and install it:
|
|
140
158
|
|
|
141
159
|
```bash
|
|
160
|
+
curl -LO https://agentcap.launchbench.studio/agentcap-0.2.0.vsix
|
|
161
|
+
sha256sum agentcap-0.2.0.vsix # compare with the sha256 above
|
|
142
162
|
code --install-extension agentcap-0.2.0.vsix # VS Code
|
|
143
163
|
cursor --install-extension agentcap-0.2.0.vsix # Cursor
|
|
144
164
|
```
|
|
@@ -303,7 +323,9 @@ agentcap quota # read-only: last seen usage (Fre
|
|
|
303
323
|
statusline command that records the official `rate_limits` (`five_hour` / `seven_day`
|
|
304
324
|
`used_percentage`, `resets_at`) and then runs **your own statusline command unchanged**,
|
|
305
325
|
plus a `PreToolUse` hook that denies further tool calls with a clear reason once the job's
|
|
306
|
-
share reaches the limit
|
|
326
|
+
share reaches the limit and ends the turn (`continue: false`). An interactive session stays open
|
|
327
|
+
(run `agentcap approve` to continue, or quit). Headless `claude -p` runs, and sessions where
|
|
328
|
+
the hook never fired, get SIGINT. Exit code 3.
|
|
307
329
|
- **Codex CLI:** AgentCap tails the `token_count` events Codex writes to
|
|
308
330
|
`~/.codex/sessions/**/rollout-*.jsonl` (`rate_limits.primary/secondary.used_percent`,
|
|
309
331
|
`window_minutes`, `resets_at`) and sends SIGINT at the limit. Exit code 3.
|
|
@@ -318,7 +340,7 @@ agentcap quota # read-only: last seen usage (Fre
|
|
|
318
340
|
use in the same window counts against the job (AgentCap warns when it sees another session).
|
|
319
341
|
Values arrive once per model response, so a job **can overshoot by up to one request**.
|
|
320
342
|
Claude Code only reports `rate_limits` for Pro/Max logins and only in interactive sessions
|
|
321
|
-
(the statusline does not run in `claude -p`). Codex's rollout format is undocumented and may change.
|
|
343
|
+
(the statusline does not run in `claude -p`). Codex's rollout format is undocumented and may change. Codex reports `used_percent` in whole percent, so a Codex cap under 1% cannot trigger until the job has used a full 1% (AgentCap warns at start). Use `--quota 1%` or more for Codex.
|
|
322
344
|
**Verified so far on fixtures and fake CLIs only** (plus real Claude Code 2.1.197: the `--settings`
|
|
323
345
|
layer, the chained statusline and the `PreToolUse` deny were checked against a local fake API);
|
|
324
346
|
a check on a real Max / ChatGPT account is still pending.
|
|
@@ -491,6 +513,15 @@ agentcap run -- codex exec "..." # uses the $2 task cap from the budget
|
|
|
491
513
|
agentcap run --quota -- claude # uses the 5% / 5h quota from the budget
|
|
492
514
|
```
|
|
493
515
|
|
|
516
|
+
Tools like agent-tree show you what your subagents are doing; AgentCap also stops them when they loop
|
|
517
|
+
(same tool call 4x in a row or 8 tool errors in a row, Pro). `agentcap waste` lists cache misses first:
|
|
518
|
+
resuming a session after the cache expired re-writes the whole prompt cache, so start a new session (or `/clear`) after a break.
|
|
519
|
+
Misses are split into main session and subagents. An idle subagent re-writes only its own context
|
|
520
|
+
(not the whole conversation, unless it is a forked subagent), at 1.25x normal input. If your
|
|
521
|
+
subagents sit idle for more than 5 minutes, set `subagentPromptCacheTtl: "1h"`. A 1 h write costs
|
|
522
|
+
2x input, so it only pays off when the subagent is reused. `STARTING CONTEXT` shows how many tokens
|
|
523
|
+
each subagent's first request carries.
|
|
524
|
+
|
|
494
525
|
- **Store:** `~/.local/share/agentcap/usage.db` (`$XDG_DATA_HOME` respected, mode 600). `import` is
|
|
495
526
|
idempotent; it reads only `*.jsonl` session logs and AgentCap's own files. It never opens auth or
|
|
496
527
|
credential files, never stores prompt or response text, and never touches network or OAuth traffic.
|
|
@@ -506,7 +537,8 @@ agentcap run --quota -- claude # uses the 5% / 5h quota from the budget
|
|
|
506
537
|
are undocumented and change between CLI versions.
|
|
507
538
|
- **`waste` heuristics:** a cache miss is a cache write larger than the cache read after the prompt
|
|
508
539
|
cache TTL ran out (5 min; 1 h when written with `ephemeral_1h`; Codex: a big uncached prompt after
|
|
509
|
-
> 5 min idle).
|
|
540
|
+
> 5 min idle). Its $ is what the re-write cost above a cache read: 5 min writes at 1.25x input,
|
|
541
|
+
1 h writes at 2x input (Anthropic list prices). Tool inputs are hashed, never printed. Not in local logs: `agent_summary` / title
|
|
510
542
|
background calls and HTTP retries (planned: local OTel receiver).
|
|
511
543
|
|
|
512
544
|
### Pro extras: analytics (`agentcap report <view>`)
|
|
@@ -1,32 +1,32 @@
|
|
|
1
|
-
agentcap/__init__.py,sha256=
|
|
1
|
+
agentcap/__init__.py,sha256=d2cAPCN-dbocgIA2sQhRVfCZpsQd7Hw8y8JS9aP2RlQ,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=
|
|
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=
|
|
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=
|
|
19
|
+
agentcap/quota.py,sha256=K66vd73dS2_24cj82Gjm3ZCudaxii-jCgMNgWpC8Z1o,41637
|
|
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=
|
|
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.
|
|
29
|
-
agentcap_cli-0.2.
|
|
30
|
-
agentcap_cli-0.2.
|
|
31
|
-
agentcap_cli-0.2.
|
|
32
|
-
agentcap_cli-0.2.
|
|
28
|
+
agentcap_cli-0.2.2.dist-info/METADATA,sha256=dJevzKWpJCbABUiTzw62umOLbCLndDdvQz6m9WVI3ZE,39951
|
|
29
|
+
agentcap_cli-0.2.2.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
30
|
+
agentcap_cli-0.2.2.dist-info/entry_points.txt,sha256=eUEtK13KEPXT2pO_lD6zzZWu5yHHo7EKrVQe3Fw6q4U,47
|
|
31
|
+
agentcap_cli-0.2.2.dist-info/licenses/LICENSE,sha256=b9WVuKHVLMITmseyT63ENNC9TbX_zg_I0oSQNJVGYJo,1070
|
|
32
|
+
agentcap_cli-0.2.2.dist-info/RECORD,,
|
|
File without changes
|
|
File without changes
|
|
File without changes
|