@caddis/cli 0.4.91 → 0.4.93
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.
- package/README.md +4 -0
- package/bundles/antigravity-plugin/agents/debug.md +2 -0
- package/bundles/antigravity-plugin/plugin.json +1 -1
- package/bundles/antigravity-plugin/scripts/__pycache__/caddis_exit.cpython-311.pyc +0 -0
- package/bundles/antigravity-plugin/scripts/__pycache__/caddis_file_lock.cpython-311.pyc +0 -0
- package/bundles/antigravity-plugin/scripts/__pycache__/caddis_frontmatter.cpython-311.pyc +0 -0
- package/bundles/antigravity-plugin/scripts/__pycache__/caddis_redact.cpython-311.pyc +0 -0
- package/bundles/antigravity-plugin/scripts/__pycache__/caddis_roadmap.cpython-311.pyc +0 -0
- package/bundles/antigravity-plugin/scripts/__pycache__/caddis_rows.cpython-311.pyc +0 -0
- package/bundles/antigravity-plugin/scripts/__pycache__/caddis_status.cpython-311.pyc +0 -0
- package/bundles/antigravity-plugin/scripts/__pycache__/caddis_tidy.cpython-311.pyc +0 -0
- package/bundles/antigravity-plugin/scripts/__pycache__/caddis_todo.cpython-311.pyc +0 -0
- package/bundles/antigravity-plugin/scripts/__pycache__/caddis_workstreams.cpython-311.pyc +0 -0
- package/bundles/antigravity-plugin/scripts/__pycache__/caddis_worktree_safety.cpython-311.pyc +0 -0
- package/bundles/antigravity-plugin/scripts/caddis_checkout_guard.py +1 -1
- package/bundles/antigravity-plugin/scripts/caddis_fleet.py +26 -9
- package/bundles/antigravity-plugin/scripts/caddis_gate.py +8 -8
- package/bundles/antigravity-plugin/scripts/caddis_guide.json +58 -6
- package/bundles/antigravity-plugin/scripts/caddis_lanes.py +17 -17
- package/bundles/antigravity-plugin/scripts/caddis_preload_review.py +554 -0
- package/bundles/antigravity-plugin/scripts/caddis_review.py +1 -1
- package/bundles/antigravity-plugin/scripts/caddis_roadmap_run.py +25 -39
- package/bundles/antigravity-plugin/scripts/caddis_routing.py +1 -1
- package/bundles/antigravity-plugin/scripts/caddis_run.py +160 -0
- package/bundles/antigravity-plugin/scripts/caddis_spawn.py +17 -1
- package/bundles/antigravity-plugin/scripts/caddis_spend.py +121 -138
- package/bundles/antigravity-plugin/scripts/caddis_upstream_check.py +108 -10
- package/bundles/antigravity-plugin/scripts/oss_review.py +15 -13
- package/bundles/antigravity-plugin/scripts/roadmap-recheck.ps1 +4 -2
- package/bundles/antigravity-plugin/scripts/schemas/hub-collect.schema.json +6 -0
- package/bundles/antigravity-plugin/scripts/schemas/hub-spend.schema.json +6 -0
- package/bundles/antigravity-plugin/scripts/setup_project_ai.py +65 -1
- package/bundles/antigravity-plugin/skills/_registry.md +3 -1
- package/bundles/antigravity-plugin/skills/brainstorming/SKILL.md +232 -40
- package/bundles/antigravity-plugin/skills/brainstorming/builder-check-prompt.md +25 -0
- package/bundles/antigravity-plugin/skills/cross-review/SKILL.md +1 -1
- package/bundles/antigravity-plugin/skills/feature-plan/SKILL.md +8 -2
- package/bundles/antigravity-plugin/skills/fleet-close/SKILL.md +4 -1
- package/bundles/antigravity-plugin/skills/graph-email/SKILL.md +15 -0
- package/bundles/antigravity-plugin/skills/handoff/SKILL.md +9 -2
- package/bundles/antigravity-plugin/skills/implement/SKILL.md +10 -6
- package/bundles/antigravity-plugin/skills/particle-art/SKILL.md +1 -3
- package/bundles/antigravity-plugin/skills/preload-review/SKILL.md +69 -0
- package/bundles/antigravity-plugin/skills/roadmap/SKILL.md +10 -6
- package/bundles/antigravity-plugin/skills/roadmap/assets/plan-resume-prompt.md +7 -6
- package/bundles/antigravity-plugin/skills/spawn-session/SKILL.md +5 -0
- package/bundles/antigravity-plugin/skills/tdd/SKILL.md +2 -1
- package/bundles/antigravity-plugin/skills/usage-review/SKILL.md +2 -0
- package/bundles/antigravity-plugin-extras/plugin.json +1 -1
- package/bundles/antigravity-plugin-extras/skills/_registry.md +1 -0
- package/bundles/antigravity-plugin-extras/skills/graph-email/SKILL.md +53 -0
- package/bundles/antigravity-plugin-extras/skills/graph-email/email.toml.example +44 -0
- package/bundles/antigravity-plugin-extras/skills/graph-email/scripts/send_email.py +432 -0
- package/bundles/codex/.codex/skills/media/particle-art/SKILL.md +1 -3
- package/bundles/codex/.codex/skills/workflow/brainstorming/SKILL.md +232 -40
- package/bundles/codex/.codex/skills/workflow/brainstorming/builder-check-prompt.md +25 -0
- package/bundles/codex/.codex/skills/workflow/roadmap/SKILL.md +10 -6
- package/bundles/codex/.codex/skills/workflow/roadmap/assets/plan-resume-prompt.md +7 -6
- package/bundles/manifest.json +3 -3
- package/dist/export/assets/export-CMtV-slT.css +1 -0
- package/dist/export/index.html +2 -2
- package/dist/ui/assets/{Activity-DZKPMOeV.js → Activity-BDjet2xd.js} +1 -1
- package/dist/ui/assets/Guide-Czn5sK0f.js +9 -0
- package/dist/ui/assets/Guide-D-Zy4cUT.css +1 -0
- package/dist/ui/assets/{RoadmapTab-DPsiSmIF.js → RoadmapTab-Bd8geyQx.js} +1 -1
- package/dist/ui/assets/index-Bd0Z4jR8.css +1 -0
- package/dist/ui/assets/{index-xl156OCN.js → index-CmngQ8Mk.js} +12 -12
- package/dist/ui/index.html +2 -2
- package/package.json +1 -1
- package/dist/export/assets/export-HxTgj3z2.css +0 -1
- package/dist/ui/assets/Guide-5ZFfL6sl.js +0 -9
- package/dist/ui/assets/Guide-Dnsb-TRd.css +0 -1
- package/dist/ui/assets/index-DGlNAmeA.css +0 -1
- /package/dist/export/assets/{export-B7BBDg5I.js → export-DtlDFN4L.js} +0 -0
|
@@ -1,47 +1,39 @@
|
|
|
1
1
|
#!/usr/bin/env python3
|
|
2
|
-
"""caddis_spend -
|
|
2
|
+
"""caddis_spend - the agy usage log and the `run` wrapper for every agy launch caddis makes.
|
|
3
3
|
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
4
|
+
History: on 7 Oct 2026 two unattended overnight agy runs cost EUR 793 in one billing day. caddis then
|
|
5
|
+
had a spend cap here (EUR per rolling 24 h). The owner removed the cap on 1 Nov 2026. The usage log stays,
|
|
6
|
+
so agy spend stays visible, and the owner's rule "cost-heavy runs need approval first" stays as text.
|
|
7
|
+
Nothing in this file refuses an agy launch because of money. Instead, at or above an advise level (EUR 300
|
|
8
|
+
committed in 24 h, or CADDIS_SPEND_ADVISE_EUR), `run` prints one `caddis_spend: ADVISORY:` line to stderr before
|
|
9
|
+
the launch and after the settle, and `status` / `check` add ` - ADVISORY (>= EUR <level>)`. Exit codes do not
|
|
10
|
+
change. The committed EUR comes from the prices below, so with no prices it stays 0 and no advisory shows.
|
|
9
11
|
|
|
10
|
-
|
|
12
|
+
Every agy launch that caddis makes through a lane (`caddis_lanes.run_lane`, which ci-watch also uses), a
|
|
13
|
+
plan Lane line (`caddis_spend.py run -- agy ...`) or the roadmap/plan runner (`caddis_roadmap_run.py
|
|
14
|
+
--engine agy`) calls `reserve()` before it starts and `settle()` after it ends.
|
|
11
15
|
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
eur_per_million_input_tokens = 0 # from Google Cloud billing; 0 = unset
|
|
16
|
-
eur_per_million_output_tokens = 0
|
|
16
|
+
Log `~/.caddis/spend/agy.jsonl`, append-only. A `pending` line is written under a file lock before the
|
|
17
|
+
launch and a `settled` line with the same id after it. A settled line holds the token counts and an EUR
|
|
18
|
+
estimate. A pending line with no settled line (a crash) counts its `reserve_eur` (now 0) for 24 h.
|
|
17
19
|
|
|
18
|
-
|
|
19
|
-
|
|
20
|
+
Prices (optional): when `~/.caddis/spend-cap.toml` has an `[agy]` table with
|
|
21
|
+
`eur_per_million_input_tokens` and `eur_per_million_output_tokens` (finite numbers above 0), a settled
|
|
22
|
+
line records EUR from the token counts. Every other key in that file (an old `eur_per_24h`, a reserve) is
|
|
23
|
+
ignored, and with no valid prices EUR is recorded as 0 with `estimated: true`. caddis never writes the file.
|
|
20
24
|
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
counting its reserve for 24 h, so a killed or crashed call is never free, and two callers cannot both
|
|
24
|
-
pass the check with the last EUR of the cap.
|
|
25
|
-
|
|
26
|
-
Limits (by design, see .caddis/plans/caddis-next.md Phase 4):
|
|
27
|
-
- The cap is per machine. The only cap across machines is a Google Cloud budget alert.
|
|
28
|
-
- agy started by hand, or by a script outside caddis, is not covered.
|
|
29
|
-
- The cap file and the log are plain files of this user: any process of this user, including an agy
|
|
30
|
-
session started with --dangerously-skip-permissions, can edit them. The cap stops accidents and
|
|
31
|
-
runaway loops; it is not a security boundary against a hostile local process.
|
|
32
|
-
- The check runs at launch. A long call can cost more than its reserve before it is settled; an
|
|
33
|
-
estimated settle records its duration so the overshoot is visible.
|
|
25
|
+
Limits:
|
|
26
|
+
- The log is per machine. agy started by hand, or by a script outside caddis, is not logged.
|
|
34
27
|
- EUR is an estimate from token counts and the owner's prices, not the real bill.
|
|
35
28
|
|
|
36
29
|
CLI:
|
|
37
|
-
python caddis_spend.py check exit 0
|
|
38
|
-
python caddis_spend.py status
|
|
30
|
+
python caddis_spend.py check always exit 0; prints the status line
|
|
31
|
+
python caddis_spend.py status [--json] prints the logged spend of the last 24 h
|
|
39
32
|
python caddis_spend.py run --caller X -- agy ...
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
CADDIS_SPEND_RUN_TIMEOUT_S, else 3600 s) and its process tree was killed.
|
|
43
|
-
|
|
44
|
-
refusal also prints a `caddis_spend:` line.
|
|
33
|
+
log, run, settle. Returns agy's own exit code, or 75 when the headless depth is at its limit or the
|
|
34
|
+
log could not be locked or written, or 124 when the command ran past its time limit (--timeout-s,
|
|
35
|
+
else CADDIS_SPEND_RUN_TIMEOUT_S, else 3600 s) and its process tree was killed. Each refusal also
|
|
36
|
+
prints a `caddis_spend:` line.
|
|
45
37
|
On Windows the command runs on a hidden desktop (caddis_hidden_desktop.py), so the console windows agy opens
|
|
46
38
|
for its tools never show; CADDIS_AGY_VISIBLE=1 runs it on the normal desktop.
|
|
47
39
|
"""
|
|
@@ -58,30 +50,43 @@ import sys
|
|
|
58
50
|
import time
|
|
59
51
|
import uuid
|
|
60
52
|
from contextlib import contextmanager
|
|
61
|
-
from dataclasses import dataclass
|
|
62
53
|
from datetime import datetime, timedelta, timezone
|
|
63
54
|
from pathlib import Path
|
|
64
55
|
|
|
65
56
|
EXIT_OK = 0
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
RUN_REFUSED = 75 # `run`: over the cap, or could not lock (EX_TEMPFAIL)
|
|
69
|
-
RUN_NOT_CONFIGURED = 78 # `run`: not configured (EX_CONFIG)
|
|
57
|
+
EXIT_LOG_ERROR = 1 # `status` only: the log could not be read
|
|
58
|
+
RUN_REFUSED = 75 # `run`: headless depth at its limit, or the log could not be locked or written (EX_TEMPFAIL)
|
|
70
59
|
RUN_TIMEOUT = 124 # `run`: the child ran past its time limit and its process tree was killed (as timeout(1))
|
|
71
60
|
DEFAULT_RUN_TIMEOUT_S = 3600.0 # one hour: a run over about 1 hour needs the owner's approval anyway
|
|
72
61
|
# No console window for the child on Windows (robustness #19; see no_window.py: never DETACHED_PROCESS).
|
|
73
62
|
_NO_WINDOW_KW = {"creationflags": 0x08000000} if os.name == "nt" else {}
|
|
74
63
|
LOCK_TIMEOUT_S = 10.0
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
64
|
+
# Advisory, never a refusal: at or above this committed EUR in 24 h, `run` and `status` say so. The owner may change it
|
|
65
|
+
# with CADDIS_SPEND_ADVISE_EUR (a finite number above 0; anything else means this default).
|
|
66
|
+
ADVISE_EUR_PER_24H = 300.0
|
|
67
|
+
ADVISE_VAR = "CADDIS_SPEND_ADVISE_EUR"
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def advise_eur(env=None) -> float:
|
|
71
|
+
"""The advisory level in EUR per 24 h: CADDIS_SPEND_ADVISE_EUR when it is a finite number above 0, else 300."""
|
|
72
|
+
env = os.environ if env is None else env
|
|
73
|
+
try:
|
|
74
|
+
value = float(str(env.get(ADVISE_VAR, "")).strip())
|
|
75
|
+
except ValueError:
|
|
76
|
+
return ADVISE_EUR_PER_24H
|
|
77
|
+
return value if math.isfinite(value) and value > 0 else ADVISE_EUR_PER_24H
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def advisory_line(committed: float, level: float) -> str:
|
|
81
|
+
return (f"caddis_spend: ADVISORY: EUR {committed:.2f} committed in the last 24 h on this machine "
|
|
82
|
+
f"(advise level EUR {level:g}). No cap applies. Tell the owner.")
|
|
78
83
|
|
|
79
84
|
|
|
80
85
|
# Recursion guard on headless starts (robustness #19). Every launcher of a headless caddis session passes
|
|
81
86
|
# CADDIS_HEADLESS_DEPTH one higher than it got, and refuses to launch once the depth is at the limit, so a
|
|
82
87
|
# headless session that starts a headless session that starts one... ends after MAX_HEADLESS_DEPTH levels.
|
|
83
88
|
# The owner may change the limit with CADDIS_HEADLESS_MAX_DEPTH. This stops accidents and loops; a hostile
|
|
84
|
-
# process can reset the variable
|
|
89
|
+
# process can reset the variable.
|
|
85
90
|
HEADLESS_DEPTH_VAR = "CADDIS_HEADLESS_DEPTH"
|
|
86
91
|
MAX_HEADLESS_DEPTH = 3
|
|
87
92
|
|
|
@@ -112,19 +117,8 @@ def bump_headless_depth(env) -> dict:
|
|
|
112
117
|
return out
|
|
113
118
|
|
|
114
119
|
|
|
115
|
-
|
|
116
|
-
"""The
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
@dataclass
|
|
120
|
-
class Cap:
|
|
121
|
-
eur_per_24h: float
|
|
122
|
-
reserve: float
|
|
123
|
-
price_in: float
|
|
124
|
-
price_out: float
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
def _cap_path(home: Path) -> Path:
|
|
120
|
+
def _prices_path(home: Path) -> Path:
|
|
121
|
+
"""The optional price file. Only its two token prices are read; any cap value in it is ignored."""
|
|
128
122
|
return home / ".caddis" / "spend-cap.toml"
|
|
129
123
|
|
|
130
124
|
|
|
@@ -132,26 +126,24 @@ def _log_path(home: Path) -> Path:
|
|
|
132
126
|
return home / ".caddis" / "spend" / "agy.jsonl"
|
|
133
127
|
|
|
134
128
|
|
|
135
|
-
def
|
|
136
|
-
"""
|
|
137
|
-
|
|
138
|
-
raise ValueError(f"not a number: {value!r}")
|
|
139
|
-
number = float(value)
|
|
140
|
-
if not math.isfinite(number) or number <= 0:
|
|
141
|
-
raise ValueError(f"must be a finite number above 0: {value!r}")
|
|
142
|
-
return number
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
def load_cap(home: Path) -> Cap:
|
|
129
|
+
def load_prices(home: Path) -> tuple[float, float] | None:
|
|
130
|
+
"""(EUR per million input tokens, EUR per million output tokens) from the `[agy]` table of the optional price
|
|
131
|
+
file, or None when the file is missing or unreadable, or a price is not a finite number above 0."""
|
|
146
132
|
import tomllib
|
|
147
133
|
|
|
148
|
-
path = _cap_path(home)
|
|
149
134
|
try:
|
|
150
|
-
data = tomllib.loads(
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
135
|
+
data = tomllib.loads(_prices_path(home).read_text(encoding="utf-8")).get("agy", {})
|
|
136
|
+
prices = (data["eur_per_million_input_tokens"], data["eur_per_million_output_tokens"])
|
|
137
|
+
except (OSError, ValueError, KeyError, TypeError, AttributeError, tomllib.TOMLDecodeError):
|
|
138
|
+
return None
|
|
139
|
+
numbers = []
|
|
140
|
+
for value in prices:
|
|
141
|
+
if isinstance(value, bool) or not isinstance(value, (int, float)):
|
|
142
|
+
return None
|
|
143
|
+
if not math.isfinite(value) or value <= 0:
|
|
144
|
+
return None
|
|
145
|
+
numbers.append(float(value))
|
|
146
|
+
return numbers[0], numbers[1]
|
|
155
147
|
|
|
156
148
|
|
|
157
149
|
@contextmanager
|
|
@@ -251,10 +243,10 @@ def _amount(value) -> float | None:
|
|
|
251
243
|
|
|
252
244
|
def committed_last_24h(home: Path, now: datetime) -> float:
|
|
253
245
|
"""Valid settled EUR, plus the reserve of every pending call with no valid settled line, newer than 24 h.
|
|
246
|
+
This is a report only; nothing refuses a launch on it.
|
|
254
247
|
|
|
255
|
-
A settled line with a bad `eur` does not count as settled, so its pending reserve keeps counting
|
|
256
|
-
A pending line with a bad reserve (
|
|
257
|
-
value) counts as 0."""
|
|
248
|
+
A settled line with a bad `eur` does not count as settled, so its pending reserve keeps counting (reserve()
|
|
249
|
+
now writes 0; older lines may hold a reserve). A pending line with a bad reserve (a hand edit) counts as 0."""
|
|
258
250
|
since = now - timedelta(hours=24)
|
|
259
251
|
records = _read(home)
|
|
260
252
|
settled: dict[str, float] = {}
|
|
@@ -275,36 +267,33 @@ def committed_last_24h(home: Path, now: datetime) -> float:
|
|
|
275
267
|
return total
|
|
276
268
|
|
|
277
269
|
|
|
278
|
-
def reserve(home: Path, caller: str, now: datetime) -> str
|
|
279
|
-
"""
|
|
280
|
-
|
|
270
|
+
def reserve(home: Path, caller: str, now: datetime) -> str:
|
|
271
|
+
"""Write a `pending` line for a call about to start and return its id. Never refuses for money.
|
|
272
|
+
Raises TimeoutError when the log cannot be locked, OSError when it cannot be written."""
|
|
281
273
|
with _locked(home):
|
|
282
|
-
if committed_last_24h(home, now) + cap.reserve > cap.eur_per_24h:
|
|
283
|
-
return None
|
|
284
274
|
rid = uuid.uuid4().hex
|
|
285
275
|
_append(home, {"kind": "pending", "id": rid, "ts": now.isoformat(), "caller": caller,
|
|
286
|
-
"pid": os.getpid(), "reserve_eur":
|
|
276
|
+
"pid": os.getpid(), "reserve_eur": 0})
|
|
287
277
|
return rid
|
|
288
278
|
|
|
289
279
|
|
|
290
280
|
def settle(home: Path, rid: str, tokens: tuple[int, int] | None, now: datetime,
|
|
291
281
|
duration_s: float | None = None) -> float:
|
|
292
|
-
"""
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
cap = None
|
|
282
|
+
"""Write the `settled` line of a call. With token counts and valid prices: the EUR from the counts. With counts
|
|
283
|
+
but no prices: the counts and EUR 0, estimated. With no counts: the pending line's reserve (0 for new lines),
|
|
284
|
+
estimated. The duration is recorded when given."""
|
|
285
|
+
prices = load_prices(home)
|
|
297
286
|
record: dict = {"kind": "settled", "id": rid, "ts": now.isoformat()}
|
|
298
|
-
if tokens is None
|
|
287
|
+
if tokens is None:
|
|
299
288
|
pending = next((r for r in _read(home) if r.get("kind") == "pending" and r.get("id") == rid), {})
|
|
300
|
-
eur = _amount(pending.get("reserve_eur"))
|
|
301
|
-
if eur is None:
|
|
302
|
-
eur = cap.reserve if cap else 0.0
|
|
289
|
+
eur = _amount(pending.get("reserve_eur")) or 0.0
|
|
303
290
|
record.update({"tokens_in": 0, "tokens_out": 0, "eur": round(eur, 4), "estimated": True})
|
|
304
291
|
else:
|
|
305
292
|
t_in, t_out = tokens
|
|
306
|
-
eur = t_in / 1e6 *
|
|
307
|
-
|
|
293
|
+
eur = 0.0 if prices is None else t_in / 1e6 * prices[0] + t_out / 1e6 * prices[1]
|
|
294
|
+
# Zero tokens cost exactly 0 (nothing ran); other counts with no prices are an estimate.
|
|
295
|
+
estimated = prices is None and (t_in, t_out) != (0, 0)
|
|
296
|
+
record.update({"tokens_in": t_in, "tokens_out": t_out, "eur": round(eur, 4), "estimated": estimated})
|
|
308
297
|
if duration_s is not None:
|
|
309
298
|
record["duration_s"] = round(duration_s, 1)
|
|
310
299
|
with _locked(home):
|
|
@@ -344,7 +333,7 @@ def _count(value) -> int | None:
|
|
|
344
333
|
def tokens_from_output(stdout: str) -> tuple[int, int] | None:
|
|
345
334
|
"""(usage.input_tokens, usage.output_tokens) from agy's JSON document; output_tokens includes thinking
|
|
346
335
|
tokens (sample: 27249 in, 85 out of which 84 thinking, total 27334). None when not readable, or when a
|
|
347
|
-
count is not a non-negative integer (then the call settles
|
|
336
|
+
count is not a non-negative integer (then the call settles as estimated)."""
|
|
348
337
|
doc = _agy_document(stdout)
|
|
349
338
|
usage = doc.get("usage") if doc else None
|
|
350
339
|
if not isinstance(usage, dict):
|
|
@@ -426,35 +415,30 @@ def _run_child(argv: list[str], env: dict, timeout_s: float) -> tuple[int | None
|
|
|
426
415
|
except BaseException:
|
|
427
416
|
# Ctrl-C or any other error while waiting: the child (agy, spending) must not outlive us. It runs in its
|
|
428
417
|
# own session/group, so it does not get our SIGINT. Kill the tree, then let the exception go on; run()
|
|
429
|
-
# settles the
|
|
418
|
+
# settles the call in its `finally`.
|
|
430
419
|
_kill_tree(proc)
|
|
431
420
|
raise
|
|
432
421
|
|
|
433
422
|
|
|
434
423
|
def run(argv: list[str], caller: str, home: Path, timeout_s: float | None = None) -> int:
|
|
435
|
-
"""
|
|
436
|
-
RUN_TIMEOUT (124: the child ran past `timeout_s`, default run_timeout_s(); its
|
|
437
|
-
call is
|
|
424
|
+
"""Log, run agy, settle. Returns agy's exit code, or RUN_REFUSED (75: headless depth at its limit, or the log
|
|
425
|
+
could not be locked or written) / RUN_TIMEOUT (124: the child ran past `timeout_s`, default run_timeout_s(); its
|
|
426
|
+
process tree was killed and the call is settled as estimated). Money never refuses a start."""
|
|
438
427
|
now = lambda: datetime.now(timezone.utc) # noqa: E731
|
|
439
428
|
try:
|
|
440
|
-
env = bump_headless_depth(os.environ) # before the
|
|
429
|
+
env = bump_headless_depth(os.environ) # before the pending line: a refused start writes nothing
|
|
441
430
|
except HeadlessDepthExceeded as exc:
|
|
442
431
|
print(str(exc), file=sys.stderr)
|
|
443
432
|
return RUN_REFUSED
|
|
444
433
|
try:
|
|
445
434
|
rid = reserve(home, caller, now())
|
|
446
|
-
except NotConfigured:
|
|
447
|
-
print(NOT_CONFIGURED_MESSAGE, file=sys.stderr)
|
|
448
|
-
return RUN_NOT_CONFIGURED
|
|
449
435
|
except TimeoutError as exc:
|
|
450
436
|
print(str(exc), file=sys.stderr)
|
|
451
437
|
return RUN_REFUSED
|
|
452
|
-
except Exception as exc: #
|
|
453
|
-
print(f"caddis_spend: could not
|
|
454
|
-
return RUN_REFUSED
|
|
455
|
-
if rid is None:
|
|
456
|
-
print(f"caddis_spend: over cap: agy refused ({status_line(home, now())})", file=sys.stderr)
|
|
438
|
+
except Exception as exc: # a file error on the log: refuse with the refusal code, never exit 1
|
|
439
|
+
print(f"caddis_spend: could not write the spend log: {exc!r}", file=sys.stderr)
|
|
457
440
|
return RUN_REFUSED
|
|
441
|
+
advise(home, now()) # already at the level before the launch: say so, then start anyway
|
|
458
442
|
out = ""
|
|
459
443
|
counts: tuple[int, int] | None = None
|
|
460
444
|
started = time.monotonic()
|
|
@@ -465,7 +449,7 @@ def run(argv: list[str], caller: str, home: Path, timeout_s: float | None = None
|
|
|
465
449
|
sys.stdout.write(out)
|
|
466
450
|
sys.stderr.write(err)
|
|
467
451
|
print(f"caddis_spend: {argv[0]} timed out after {limit:g}s; its process tree was killed "
|
|
468
|
-
f"(
|
|
452
|
+
f"(settled as estimated). Set CADDIS_SPEND_RUN_TIMEOUT_S or --timeout-s to change the limit.",
|
|
469
453
|
file=sys.stderr)
|
|
470
454
|
return RUN_TIMEOUT
|
|
471
455
|
# Tokens only from JSON mode: in text mode the model's own lines could pose as a usage document.
|
|
@@ -481,29 +465,38 @@ def run(argv: list[str], caller: str, home: Path, timeout_s: float | None = None
|
|
|
481
465
|
finally:
|
|
482
466
|
try:
|
|
483
467
|
settle(home, rid, counts, now(), duration_s=time.monotonic() - started)
|
|
484
|
-
except Exception as exc: # the pending
|
|
468
|
+
except Exception as exc: # the pending line stays unsettled; never lose agy's own result
|
|
485
469
|
print(f"caddis_spend: could not settle {rid}: {exc}", file=sys.stderr)
|
|
470
|
+
advise(home, now())
|
|
486
471
|
|
|
487
472
|
|
|
488
|
-
def
|
|
473
|
+
def advise(home: Path, now: datetime) -> None:
|
|
474
|
+
"""Print the ADVISORY line to stderr when the committed EUR of the last 24 h is at or above the advise level.
|
|
475
|
+
Advice only: it never changes an exit code, and a log it cannot read prints nothing."""
|
|
489
476
|
try:
|
|
490
|
-
|
|
491
|
-
except
|
|
492
|
-
|
|
493
|
-
|
|
477
|
+
committed, level = committed_last_24h(home, now), advise_eur()
|
|
478
|
+
except Exception:
|
|
479
|
+
return
|
|
480
|
+
if committed >= level:
|
|
481
|
+
print(advisory_line(committed, level), file=sys.stderr)
|
|
482
|
+
|
|
483
|
+
|
|
484
|
+
def status_line(home: Path, now: datetime) -> str:
|
|
485
|
+
committed, level = committed_last_24h(home, now), advise_eur()
|
|
486
|
+
line = f"agy: EUR {committed:.2f} in the last 24 h on this machine (no cap)"
|
|
487
|
+
return line + (f" - ADVISORY (>= EUR {level:g})" if committed >= level else "")
|
|
494
488
|
|
|
495
489
|
|
|
496
490
|
def spend_json(home: Path, now: datetime | None = None) -> dict:
|
|
497
|
-
"""The spend status as one JSON-ready dict. It holds no key, no prompt and no caller name.
|
|
491
|
+
"""The spend status as one JSON-ready dict. It holds no key, no prompt and no caller name.
|
|
492
|
+
There is no cap: `configured` is always False and `cap_eur` and `reserve_eur` are always None (the keys stay for
|
|
493
|
+
the hub schema, scripts/schemas/hub-spend.schema.json). `advise_eur` is the advise level and `advisory` is True at
|
|
494
|
+
or above it."""
|
|
498
495
|
now = now or datetime.now(timezone.utc)
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
cap_eur = reserve_eur = None
|
|
504
|
-
return {"schema": 1, "configured": cap_eur is not None, "cap_eur": cap_eur,
|
|
505
|
-
"committed_eur": round(committed_last_24h(home, now), 6), "reserve_eur": reserve_eur,
|
|
506
|
-
"window_h": 24}
|
|
496
|
+
committed, level = committed_last_24h(home, now), advise_eur()
|
|
497
|
+
return {"schema": 1, "configured": False, "cap_eur": None,
|
|
498
|
+
"committed_eur": round(committed, 6), "reserve_eur": None,
|
|
499
|
+
"window_h": 24, "advise_eur": level, "advisory": committed >= level}
|
|
507
500
|
|
|
508
501
|
|
|
509
502
|
def main(argv: list[str] | None = None) -> int:
|
|
@@ -514,7 +507,7 @@ def main(argv: list[str] | None = None) -> int:
|
|
|
514
507
|
if "--" in raw:
|
|
515
508
|
i = raw.index("--")
|
|
516
509
|
raw, tail = raw[:i], raw[i + 1:]
|
|
517
|
-
parser = argparse.ArgumentParser(description="
|
|
510
|
+
parser = argparse.ArgumentParser(description="agy usage log and run wrapper (EUR per rolling 24 h, this machine)")
|
|
518
511
|
sub = parser.add_subparsers(dest="cmd", required=True)
|
|
519
512
|
sub.add_parser("check")
|
|
520
513
|
p_status = sub.add_parser("status")
|
|
@@ -532,23 +525,13 @@ def main(argv: list[str] | None = None) -> int:
|
|
|
532
525
|
print(json.dumps(spend_json(home, now)) if args.json else status_line(home, now))
|
|
533
526
|
except Exception as exc:
|
|
534
527
|
print(f"caddis_spend: could not read the spend log: {exc!r}", file=sys.stderr)
|
|
535
|
-
return
|
|
528
|
+
return EXIT_LOG_ERROR
|
|
536
529
|
return EXIT_OK
|
|
537
|
-
if args.cmd == "check":
|
|
538
|
-
try:
|
|
539
|
-
cap = load_cap(home)
|
|
540
|
-
except NotConfigured:
|
|
541
|
-
print(NOT_CONFIGURED_MESSAGE, file=sys.stderr)
|
|
542
|
-
return EXIT_NOT_CONFIGURED
|
|
530
|
+
if args.cmd == "check": # there is no cap: always 0, so no caller is blocked by it
|
|
543
531
|
try:
|
|
544
|
-
|
|
532
|
+
print(f"ok: {status_line(home, now)}")
|
|
545
533
|
except Exception as exc:
|
|
546
|
-
print(f"caddis_spend: could not read the spend log: {exc!r}"
|
|
547
|
-
return EXIT_NOT_CONFIGURED
|
|
548
|
-
if committed + cap.reserve > cap.eur_per_24h:
|
|
549
|
-
print(f"over cap: {status_line(home, now)}")
|
|
550
|
-
return EXIT_OVER_CAP
|
|
551
|
-
print(f"ok: {status_line(home, now)}")
|
|
534
|
+
print(f"ok: caddis_spend: could not read the spend log: {exc!r}")
|
|
552
535
|
return EXIT_OK
|
|
553
536
|
if not tail:
|
|
554
537
|
parser.error("run needs the agy command after --")
|
|
@@ -1,33 +1,55 @@
|
|
|
1
1
|
#!/usr/bin/env python3
|
|
2
2
|
"""caddis_upstream_check - say when an upstream skill that caddis borrowed ideas from has changed.
|
|
3
3
|
|
|
4
|
-
Why:
|
|
5
|
-
subagent-driven-development
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
4
|
+
Why: caddis owns the routing-critical skills and commands that it adapted from obra/superpowers
|
|
5
|
+
(writing-plans, subagent-driven-development, brainstorming, using-git-worktrees; MIT). The other superpowers
|
|
6
|
+
skills are used straight from the plugin. `.github/upstream-sources.json` records, per borrowed file, the upstream version and the
|
|
7
|
+
sha256 of the file we read. This script compares that record with upstream, so caddis does not fall
|
|
8
|
+
behind without anyone seeing it. /caddis:usage-review runs the local mode. The weekly workflow
|
|
9
|
+
`.github/workflows/upstream-drift.yml` runs `--remote` and opens one issue when anything drifts.
|
|
10
|
+
|
|
11
|
+
Two modes:
|
|
12
|
+
local (default) compare with the copies installed in the Claude Code plugin cache
|
|
13
|
+
(`~/.claude/plugins/cache/<marketplace>/<plugin>/<version>/<path>`). It is blind
|
|
14
|
+
when the upstream plugin is turned off or not installed.
|
|
15
|
+
--remote ask GitHub instead: take the latest release tag of each `upstream` repo (the
|
|
16
|
+
newest tag when there is no release), fetch the file at that tag from
|
|
17
|
+
raw.githubusercontent.com and hash it. Needs the network. Set GITHUB_TOKEN to
|
|
18
|
+
avoid the anonymous API rate limit. Stdlib `urllib` only.
|
|
9
19
|
|
|
10
20
|
One line per source:
|
|
11
21
|
UP-TO-DATE <id> <version>
|
|
12
|
-
DRIFT <id> recorded <v> installed <
|
|
13
|
-
|
|
22
|
+
DRIFT <id> recorded <v> installed <new> (sha differs): review the upstream diff and port what fits, ...
|
|
23
|
+
DRIFT <id> recorded <v> upstream <tag> (sha differs): ... (--remote)
|
|
24
|
+
DRIFT <id> recorded <v> upstream <tag> (file not found at that tag): ... (--remote)
|
|
25
|
+
NOT-INSTALLED <id> (local only)
|
|
26
|
+
UNREACHABLE <id> <reason> (--remote: network or API error)
|
|
14
27
|
`NO-SOURCES <path>` means there is no record (any repo other than the caddis source repo).
|
|
15
28
|
|
|
16
|
-
Advisory
|
|
29
|
+
Advisory: the exit code is 0 unless `--fail-on-drift` is set and some line is DRIFT (then 1).
|
|
30
|
+
This script never copies upstream text. The caddis files are adapted, so a copy would undo the
|
|
31
|
+
adaptation: a human reads the diff and ports what fits.
|
|
17
32
|
|
|
18
33
|
Usage:
|
|
19
34
|
python caddis_upstream_check.py [--sources <json>] [--cache-root <dir>] [--json]
|
|
35
|
+
[--remote] [--fail-on-drift]
|
|
20
36
|
"""
|
|
21
37
|
from __future__ import annotations
|
|
22
38
|
|
|
23
39
|
import argparse
|
|
24
40
|
import hashlib
|
|
25
41
|
import json
|
|
42
|
+
import os
|
|
26
43
|
import sys
|
|
44
|
+
import urllib.error
|
|
45
|
+
import urllib.request
|
|
27
46
|
from pathlib import Path
|
|
28
47
|
|
|
29
48
|
SOURCES_REL = Path(".github") / "upstream-sources.json"
|
|
30
49
|
DRIFT_ADVICE = "review the upstream diff and port what fits, then update .github/upstream-sources.json"
|
|
50
|
+
API_ROOT = "https://api.github.com"
|
|
51
|
+
RAW_ROOT = "https://raw.githubusercontent.com"
|
|
52
|
+
TIMEOUT_SECONDS = 20
|
|
31
53
|
|
|
32
54
|
|
|
33
55
|
def default_sources() -> Path:
|
|
@@ -78,11 +100,83 @@ def check_source(src: dict, cache_root: Path) -> dict:
|
|
|
78
100
|
return row
|
|
79
101
|
|
|
80
102
|
|
|
103
|
+
# ---- remote mode ------------------------------------------------------------------------------------
|
|
104
|
+
|
|
105
|
+
class FetchError(Exception):
|
|
106
|
+
"""A network or HTTP failure. `status` is the HTTP status code, or None for a network error."""
|
|
107
|
+
|
|
108
|
+
def __init__(self, message: str, status: int | None = None):
|
|
109
|
+
super().__init__(message)
|
|
110
|
+
self.status = status
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def fetch(url: str, token: str | None = None) -> bytes:
|
|
114
|
+
"""GET a URL and return the body. Raise FetchError on any failure. Tests replace this function."""
|
|
115
|
+
headers = {"User-Agent": "caddis-upstream-check", "Accept": "application/vnd.github+json"}
|
|
116
|
+
if token:
|
|
117
|
+
headers["Authorization"] = f"Bearer {token}"
|
|
118
|
+
try:
|
|
119
|
+
with urllib.request.urlopen(urllib.request.Request(url, headers=headers), timeout=TIMEOUT_SECONDS) as resp:
|
|
120
|
+
return resp.read()
|
|
121
|
+
except urllib.error.HTTPError as exc:
|
|
122
|
+
raise FetchError(f"HTTP {exc.code} for {url}", exc.code) from exc
|
|
123
|
+
except (urllib.error.URLError, OSError, ValueError) as exc:
|
|
124
|
+
raise FetchError(f"{exc} for {url}") from exc
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def latest_tag(upstream: str, token: str | None = None) -> str | None:
|
|
128
|
+
"""The latest release tag of `owner/repo`; when it has no release, the newest tag; else None."""
|
|
129
|
+
try:
|
|
130
|
+
release = json.loads(fetch(f"{API_ROOT}/repos/{upstream}/releases/latest", token))
|
|
131
|
+
if release.get("tag_name"):
|
|
132
|
+
return str(release["tag_name"])
|
|
133
|
+
except FetchError as exc:
|
|
134
|
+
if exc.status != 404:
|
|
135
|
+
raise
|
|
136
|
+
tags = json.loads(fetch(f"{API_ROOT}/repos/{upstream}/tags?per_page=100", token))
|
|
137
|
+
names = [str(tag["name"]) for tag in tags if isinstance(tag, dict) and tag.get("name")]
|
|
138
|
+
return max(names, key=lambda name: _version_key(name.lstrip("v"))) if names else None
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def check_source_remote(src: dict, tags: dict[str, str | None], token: str | None = None) -> dict:
|
|
142
|
+
"""Compare one record with the file at the latest upstream tag. `tags` caches one lookup per repo."""
|
|
143
|
+
sid, recorded, upstream = src["id"], src["version"], src["upstream"]
|
|
144
|
+
row = {"id": sid, "status": "UNREACHABLE", "recorded_version": recorded, "installed_version": None,
|
|
145
|
+
"upstream_tag": None, "line": ""}
|
|
146
|
+
|
|
147
|
+
def done(status: str, line: str) -> dict:
|
|
148
|
+
row.update(status=status, line=line)
|
|
149
|
+
return row
|
|
150
|
+
|
|
151
|
+
try:
|
|
152
|
+
if upstream not in tags:
|
|
153
|
+
tags[upstream] = latest_tag(upstream, token)
|
|
154
|
+
tag = tags[upstream]
|
|
155
|
+
if tag is None:
|
|
156
|
+
return done("UNREACHABLE", f"UNREACHABLE {sid} {upstream} has no releases and no tags")
|
|
157
|
+
row["upstream_tag"] = tag
|
|
158
|
+
try:
|
|
159
|
+
body = fetch(f"{RAW_ROOT}/{upstream}/{tag}/{src['path']}", token)
|
|
160
|
+
except FetchError as exc:
|
|
161
|
+
if exc.status == 404:
|
|
162
|
+
return done("DRIFT", f"DRIFT {sid} recorded {recorded} upstream {tag} "
|
|
163
|
+
f"(file not found at that tag): {DRIFT_ADVICE}")
|
|
164
|
+
raise
|
|
165
|
+
except (FetchError, ValueError, KeyError, TypeError) as exc:
|
|
166
|
+
return done("UNREACHABLE", f"UNREACHABLE {sid} {exc}")
|
|
167
|
+
if hashlib.sha256(body).hexdigest() == src["sha256"]:
|
|
168
|
+
return done("UP-TO-DATE", f"UP-TO-DATE {sid} {recorded}")
|
|
169
|
+
return done("DRIFT", f"DRIFT {sid} recorded {recorded} upstream {tag} (sha differs): {DRIFT_ADVICE}")
|
|
170
|
+
|
|
171
|
+
|
|
81
172
|
def main(argv: list[str] | None = None) -> int:
|
|
82
173
|
ap = argparse.ArgumentParser(description="Compare borrowed upstream skills with the installed copies.")
|
|
83
174
|
ap.add_argument("--sources", type=Path, default=None, help="path to upstream-sources.json")
|
|
84
175
|
ap.add_argument("--cache-root", type=Path, default=None, help="the Claude Code plugin cache folder")
|
|
85
176
|
ap.add_argument("--json", action="store_true", help="print the rows as a JSON list")
|
|
177
|
+
ap.add_argument("--remote", action="store_true",
|
|
178
|
+
help="ask GitHub for the latest release of each upstream repo instead of reading the plugin cache")
|
|
179
|
+
ap.add_argument("--fail-on-drift", action="store_true", help="exit 1 when any source shows DRIFT")
|
|
86
180
|
args = ap.parse_args(argv)
|
|
87
181
|
sources = args.sources or default_sources()
|
|
88
182
|
cache_root = args.cache_root or default_cache_root()
|
|
@@ -91,7 +185,11 @@ def main(argv: list[str] | None = None) -> int:
|
|
|
91
185
|
return 0
|
|
92
186
|
try:
|
|
93
187
|
data = json.loads(sources.read_text(encoding="utf-8"))
|
|
94
|
-
|
|
188
|
+
if args.remote:
|
|
189
|
+
token, tags = os.environ.get("GITHUB_TOKEN") or None, {}
|
|
190
|
+
rows = [check_source_remote(src, tags, token) for src in data.get("sources", [])]
|
|
191
|
+
else:
|
|
192
|
+
rows = [check_source(src, cache_root) for src in data.get("sources", [])]
|
|
95
193
|
except (OSError, ValueError, KeyError, TypeError) as exc:
|
|
96
194
|
print(f"NO-SOURCES {sources} (unreadable: {exc})")
|
|
97
195
|
return 0
|
|
@@ -100,7 +198,7 @@ def main(argv: list[str] | None = None) -> int:
|
|
|
100
198
|
else:
|
|
101
199
|
for row in rows:
|
|
102
200
|
print(row["line"])
|
|
103
|
-
return 0
|
|
201
|
+
return 1 if args.fail_on_drift and any(row["status"] == "DRIFT" for row in rows) else 0
|
|
104
202
|
|
|
105
203
|
|
|
106
204
|
if __name__ == "__main__":
|