@alexgreensh/token-optimizer 5.13.80 → 5.13.82
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/.claude-plugin/marketplace.json +2 -2
- package/.claude-plugin/plugin.json +1 -1
- package/hooks/module_runner.py +1 -1
- package/package.json +1 -1
- package/skills/token-optimizer/assets/savings_story.js +6 -4
- package/skills/token-optimizer/scripts/_measure/__init__.py +2 -2
- package/skills/token-optimizer/scripts/_measure/audit.py +5 -6
- package/skills/token-optimizer/scripts/_measure/cache_policy.py +16 -39
- package/skills/token-optimizer/scripts/_measure/continuity.py +30 -3
- package/skills/token-optimizer/scripts/_measure/cost_per_message_trend.py +32 -15
- package/skills/token-optimizer/scripts/_measure/daemon.py +25 -2
- package/skills/token-optimizer/scripts/_measure/dashboard.py +2 -1
- package/skills/token-optimizer/scripts/_measure/feature_health.py +14 -5
- package/skills/token-optimizer/scripts/_measure/install_baseline.py +2 -1
- package/skills/token-optimizer/scripts/_measure/like_for_like.py +329 -0
- package/skills/token-optimizer/scripts/_measure/limit_units.py +39 -0
- package/skills/token-optimizer/scripts/_measure/model_families.py +133 -0
- package/skills/token-optimizer/scripts/_measure/own_price_card.py +38 -14
- package/skills/token-optimizer/scripts/_measure/pilot_report.py +197 -48
- package/skills/token-optimizer/scripts/_measure/pricing.py +7 -2
- package/skills/token-optimizer/scripts/_measure/project_md_walk.py +29 -0
- package/skills/token-optimizer/scripts/_measure/quality_archive.py +41 -19
- package/skills/token-optimizer/scripts/_measure/quality_continuity.py +2 -0
- package/skills/token-optimizer/scripts/_measure/savings.py +155 -80
- package/skills/token-optimizer/scripts/_measure/sessions.py +7 -2
- package/skills/token-optimizer/scripts/_measure/transcript_product.py +113 -58
- package/skills/token-optimizer/scripts/_measure/trends.py +20 -2
- package/skills/token-optimizer/scripts/_measure/ttl_file_memo.py +109 -0
- package/skills/token-optimizer/scripts/_measure/weekly_activity.py +64 -7
- package/skills/token-optimizer/scripts/antigravity_doctor.py +62 -17
- package/skills/token-optimizer/scripts/antigravity_hook_bridge.py +20 -3
- package/skills/token-optimizer/scripts/antigravity_install.py +18 -9
- package/skills/token-optimizer/scripts/cloud_kit.py +1 -1
- package/skills/token-optimizer/scripts/codex_doctor.py +1 -1
- package/skills/token-optimizer/scripts/cursor_coach.py +5 -4
- package/skills/token-optimizer/scripts/cursor_install.py +1 -0
- package/skills/token-optimizer/scripts/delta_serve.py +174 -0
- package/skills/token-optimizer/scripts/devin_source.py +1 -1
- package/skills/token-optimizer/scripts/hermes_doctor.py +2 -1
- package/skills/token-optimizer/scripts/hermes_install.py +2 -1
- package/skills/token-optimizer/scripts/measure.py +14 -21
- package/skills/token-optimizer/scripts/read_cache.py +19 -76
- package/skills/token-optimizer/scripts/reset_epoch.py +5 -3
- package/skills/token-optimizer/scripts/session_activity.py +1 -1
- package/skills/token-optimizer/scripts/session_store.py +5 -6
|
@@ -32,74 +32,129 @@ def _time(value):
|
|
|
32
32
|
return None
|
|
33
33
|
|
|
34
34
|
|
|
35
|
+
# Per-file events keyed by (path, mtime_ns, size). A dashboard build asks for
|
|
36
|
+
# this check more than once; an unchanged transcript is read only the first
|
|
37
|
+
# time, and a file that grew is read again on its own. Entries hold only the
|
|
38
|
+
# small records the check needs (sizes, stamps, call ids), never transcript text.
|
|
39
|
+
_EVENTS = {}
|
|
40
|
+
_EVENTS_MAX = 20000
|
|
41
|
+
_TAGS = ('"tool_use"', '"skill_listing"', '"deferred_tools_delta"', '"mcp_instructions_delta"')
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _delta(kind, a):
|
|
45
|
+
"""What one tools/instructions delta adds, as (error type, mismatch, adds)."""
|
|
46
|
+
names = a.get('addedNames') or []
|
|
47
|
+
values = a.get('addedLines' if kind == 'deferred_tools_delta' else 'addedBlocks') or []
|
|
48
|
+
try:
|
|
49
|
+
if kind == 'deferred_tools_delta':
|
|
50
|
+
adds = []
|
|
51
|
+
for value in values:
|
|
52
|
+
if isinstance(value, str):
|
|
53
|
+
name = value.split(None, 1)[0] if value.strip() else ''
|
|
54
|
+
if _server(name):
|
|
55
|
+
adds.append((name, len(value)))
|
|
56
|
+
return None, False, adds
|
|
57
|
+
if len(names) == len(values):
|
|
58
|
+
return None, False, [(n, len(v)) for n, v in zip(names, values)
|
|
59
|
+
if isinstance(n, str) and isinstance(v, str)]
|
|
60
|
+
return None, True, []
|
|
61
|
+
except Exception as exc: # replayed only when the delta is in the window
|
|
62
|
+
return type(exc), False, []
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def _read_events(source):
|
|
66
|
+
"""One pass over a transcript: the records scan() weighs against `now`."""
|
|
67
|
+
ev = {'bad': False, 'error': False, 'listings': [], 'ops': [], 'calls': []}
|
|
68
|
+
try:
|
|
69
|
+
with source.open(encoding='utf-8', errors='replace') as stream:
|
|
70
|
+
for line in stream:
|
|
71
|
+
if not any(tag in line for tag in _TAGS):
|
|
72
|
+
continue
|
|
73
|
+
try:
|
|
74
|
+
record = json.loads(line)
|
|
75
|
+
except (ValueError, TypeError):
|
|
76
|
+
ev['bad'] = True
|
|
77
|
+
continue
|
|
78
|
+
if not isinstance(record, dict):
|
|
79
|
+
continue
|
|
80
|
+
a = record.get('attachment') or {}
|
|
81
|
+
if not isinstance(a, dict):
|
|
82
|
+
continue
|
|
83
|
+
kind = a.get('type')
|
|
84
|
+
stamp = _time(record.get('timestamp'))
|
|
85
|
+
if kind == 'skill_listing' and a.get('isInitial') and isinstance(a.get('content'), str):
|
|
86
|
+
ev['listings'].append((stamp, len(a['content']), a.get('skillCount')))
|
|
87
|
+
if kind in ('deferred_tools_delta', 'mcp_instructions_delta'):
|
|
88
|
+
ev['ops'].append((stamp, kind, a.get('removedNames') or []) + _delta(kind, a))
|
|
89
|
+
if record.get('type') != 'assistant':
|
|
90
|
+
continue
|
|
91
|
+
message = record.get('message') or {}
|
|
92
|
+
content = message.get('content') if isinstance(message, dict) else []
|
|
93
|
+
if not isinstance(content, list):
|
|
94
|
+
continue
|
|
95
|
+
for item in content:
|
|
96
|
+
if not isinstance(item, dict) or item.get('type') != 'tool_use':
|
|
97
|
+
continue
|
|
98
|
+
server = _server(item.get('name'))
|
|
99
|
+
if server:
|
|
100
|
+
ev['calls'].append((stamp, item.get('id'), _normalize(server)))
|
|
101
|
+
except OSError:
|
|
102
|
+
ev['error'] = True
|
|
103
|
+
return ev
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def _events(source):
|
|
107
|
+
try:
|
|
108
|
+
st = os.stat(source)
|
|
109
|
+
key = (str(source), st.st_mtime_ns, st.st_size)
|
|
110
|
+
except OSError:
|
|
111
|
+
key = None
|
|
112
|
+
if key is not None and key in _EVENTS:
|
|
113
|
+
return _EVENTS[key]
|
|
114
|
+
ev = _read_events(source)
|
|
115
|
+
if key is not None and not ev['error']:
|
|
116
|
+
if len(_EVENTS) >= _EVENTS_MAX:
|
|
117
|
+
_EVENTS.clear()
|
|
118
|
+
_EVENTS[key] = ev
|
|
119
|
+
return ev
|
|
120
|
+
|
|
121
|
+
|
|
35
122
|
def scan(paths, budget=None, now=None, days=30):
|
|
36
123
|
now = now or datetime.now(timezone.utc)
|
|
37
124
|
cutoff = now - timedelta(days=days)
|
|
125
|
+
week = now - timedelta(days=7)
|
|
38
126
|
listing, samples, used, seen_calls = [], {}, set(), set()
|
|
39
127
|
incomplete = False
|
|
40
128
|
for path in paths:
|
|
41
129
|
path = Path(path)
|
|
42
130
|
tools, instructions = {}, {}
|
|
43
|
-
have_listing = False
|
|
44
131
|
files = [path] + sorted((path.parent / path.stem / 'subagents').glob('*.jsonl'))
|
|
45
132
|
for source in files:
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
for name in a.get('removedNames') or []:
|
|
72
|
-
target.pop(name, None)
|
|
73
|
-
if kind == 'deferred_tools_delta':
|
|
74
|
-
for value in values:
|
|
75
|
-
if isinstance(value, str):
|
|
76
|
-
name = value.split(None, 1)[0] if value.strip() else ''
|
|
77
|
-
if _server(name):
|
|
78
|
-
target[name] = len(value)
|
|
79
|
-
elif len(names) == len(values):
|
|
80
|
-
for name, value in zip(names, values):
|
|
81
|
-
if isinstance(name, str) and isinstance(value, str):
|
|
82
|
-
target[name] = len(value)
|
|
83
|
-
else:
|
|
84
|
-
incomplete = True
|
|
85
|
-
if record.get('type') != 'assistant':
|
|
86
|
-
continue
|
|
87
|
-
message = record.get('message') or {}
|
|
88
|
-
content = message.get('content') if isinstance(message, dict) else []
|
|
89
|
-
if not isinstance(content, list):
|
|
90
|
-
continue
|
|
91
|
-
for item in content:
|
|
92
|
-
if not isinstance(item, dict) or item.get('type') != 'tool_use':
|
|
93
|
-
continue
|
|
94
|
-
server = _server(item.get('name'))
|
|
95
|
-
call_id = item.get('id')
|
|
96
|
-
if server and (stamp is None or cutoff <= stamp <= now):
|
|
97
|
-
if not call_id or call_id not in seen_calls:
|
|
98
|
-
used.add(_normalize(server))
|
|
99
|
-
if call_id:
|
|
100
|
-
seen_calls.add(call_id)
|
|
101
|
-
except OSError:
|
|
102
|
-
incomplete = True
|
|
133
|
+
ev = _events(source)
|
|
134
|
+
incomplete = incomplete or ev['bad'] or ev['error']
|
|
135
|
+
if source == path:
|
|
136
|
+
for stamp, size, count in ev['listings']:
|
|
137
|
+
if stamp is not None and week <= stamp <= now:
|
|
138
|
+
listing.append((size, count))
|
|
139
|
+
break
|
|
140
|
+
for stamp, kind, removed, error, mismatch, adds in ev['ops']:
|
|
141
|
+
if stamp is None or not week <= stamp <= now:
|
|
142
|
+
continue
|
|
143
|
+
target = tools if kind == 'deferred_tools_delta' else instructions
|
|
144
|
+
for name in removed:
|
|
145
|
+
target.pop(name, None)
|
|
146
|
+
if error is not None:
|
|
147
|
+
raise error()
|
|
148
|
+
if mismatch:
|
|
149
|
+
incomplete = True
|
|
150
|
+
for name, size in adds:
|
|
151
|
+
target[name] = size
|
|
152
|
+
for stamp, call_id, server in ev['calls']:
|
|
153
|
+
if stamp is None or cutoff <= stamp <= now:
|
|
154
|
+
if not call_id or call_id not in seen_calls:
|
|
155
|
+
used.add(server)
|
|
156
|
+
if call_id:
|
|
157
|
+
seen_calls.add(call_id)
|
|
103
158
|
session = {}
|
|
104
159
|
for name, size in tools.items():
|
|
105
160
|
server = _server(name)
|
|
@@ -890,6 +890,21 @@ def _init_trends_db():
|
|
|
890
890
|
except _measure_facade.sqlite3.Error as _e:
|
|
891
891
|
_measure_facade._log_migration_error(f"{_origin_table} origin column", _e)
|
|
892
892
|
_measure_facade.ensure_activity_schema(conn)
|
|
893
|
+
# One-time data repair (#360): unmeasured sessions (grade '?') used to
|
|
894
|
+
# store the scorer's fallback score (last_measured_score, default 100),
|
|
895
|
+
# which then read as a perfect score in raw queries and any consumer that
|
|
896
|
+
# does not filter grade. Null those stored scores; when any row changed,
|
|
897
|
+
# rebuild daily_stats now so its stored quality average cannot stay stale.
|
|
898
|
+
try:
|
|
899
|
+
if not conn.execute("SELECT 1 FROM schema_migrations WHERE name='unmeasured_quality_null_v1'").fetchone():
|
|
900
|
+
cur = conn.execute(
|
|
901
|
+
"UPDATE session_log SET quality_score = NULL WHERE quality_grade = '?' AND quality_score IS NOT NULL")
|
|
902
|
+
if cur.rowcount > 0:
|
|
903
|
+
_measure_facade._rebuild_aggregate_tables(conn)
|
|
904
|
+
conn.execute("INSERT OR IGNORE INTO schema_migrations (name) VALUES ('unmeasured_quality_null_v1')")
|
|
905
|
+
conn.commit()
|
|
906
|
+
except _measure_facade.sqlite3.Error as _e:
|
|
907
|
+
_measure_facade._log_migration_error("unmeasured quality scores", _e)
|
|
893
908
|
# Backfill session_uuid from jsonl_path basename stem for existing rows,
|
|
894
909
|
# then create an index so joins are O(log n) instead of full-table LIKE scans.
|
|
895
910
|
try:
|
|
@@ -1270,7 +1285,10 @@ def _backfill_session_metrics(conn, days=None, limit=None):
|
|
|
1270
1285
|
OR avg_call_gap_seconds IS NULL
|
|
1271
1286
|
OR max_call_gap_seconds IS NULL
|
|
1272
1287
|
OR p95_call_gap_seconds IS NULL
|
|
1273
|
-
|
|
1288
|
+
-- quality_score IS NULL on an unmeasured ('?') row is the
|
|
1289
|
+
-- stored truth, not a gap: re-parsing it every flush is a
|
|
1290
|
+
-- perpetual latency tax that can never fill (#360).
|
|
1291
|
+
OR (quality_score IS NULL AND IFNULL(quality_grade, '') != '?')
|
|
1274
1292
|
)
|
|
1275
1293
|
ORDER BY date DESC, collected_at DESC
|
|
1276
1294
|
LIMIT ?""",
|
|
@@ -1301,7 +1319,7 @@ def _backfill_session_metrics(conn, days=None, limit=None):
|
|
|
1301
1319
|
max_gap = parsed.get("max_call_gap_seconds")
|
|
1302
1320
|
p95_gap = parsed.get("p95_call_gap_seconds")
|
|
1303
1321
|
sq = _measure_facade.score_session_quality(parsed)
|
|
1304
|
-
q_score = sq["score"]
|
|
1322
|
+
q_score = sq["score"] if sq.get("measured") else None
|
|
1305
1323
|
q_grade = sq["grade"]
|
|
1306
1324
|
updates.append((ttl_1h, ttl_5m, avg_gap, max_gap, p95_gap, q_score, q_grade, str(jsonl_path)))
|
|
1307
1325
|
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
"""Per-transcript facts for the cache TTL waste report, read once per file.
|
|
2
|
+
|
|
3
|
+
One dashboard build asks for the report over more than one window (30 days and
|
|
4
|
+
the dashboard's own history length). Every fact taken from a transcript here
|
|
5
|
+
is the same for any window, except the turn timestamps the window filters on,
|
|
6
|
+
so each file is parsed once and summarized by (path, mtime_ns, size). A file
|
|
7
|
+
that changed is parsed again on its own. Entries keep only token counts,
|
|
8
|
+
timestamps and rebuild events, never the parsed turns.
|
|
9
|
+
"""
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import os
|
|
13
|
+
from datetime import datetime
|
|
14
|
+
|
|
15
|
+
_MAX = 20000
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def _memo(f):
|
|
19
|
+
memo = f.__dict__.get('_ttl_file_memo')
|
|
20
|
+
if memo is None:
|
|
21
|
+
memo = {}
|
|
22
|
+
setattr(f, '_ttl_file_memo', memo)
|
|
23
|
+
return memo
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _stamp(raw):
|
|
27
|
+
"""Epoch seconds the explicit-TTL detector derives from a turn timestamp."""
|
|
28
|
+
if not raw:
|
|
29
|
+
return None
|
|
30
|
+
try:
|
|
31
|
+
return datetime.fromisoformat(str(raw).replace('Z', '+00:00')).timestamp()
|
|
32
|
+
except (ValueError, TypeError):
|
|
33
|
+
return None
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _summarize(f, filepath, parse_fn, runtime, tier_data, candidate_floor):
|
|
37
|
+
try:
|
|
38
|
+
turns = parse_fn(filepath)
|
|
39
|
+
except Exception:
|
|
40
|
+
return None, False
|
|
41
|
+
if not turns:
|
|
42
|
+
return None, True
|
|
43
|
+
model = f._dominant_turn_model(turns)
|
|
44
|
+
prof_key, profile = f._resolve_cache_profile(model, runtime=runtime)
|
|
45
|
+
kind = profile['cache_kind']
|
|
46
|
+
cache_read = full_input = 0
|
|
47
|
+
for turn in turns:
|
|
48
|
+
cr = int(turn.get('cache_read', 0) or 0)
|
|
49
|
+
cc = int(turn.get('cache_creation', 0) or 0)
|
|
50
|
+
cache_read += cr
|
|
51
|
+
full_input += cr + cc + int(turn.get('input_tokens', 0) or 0)
|
|
52
|
+
s = {'prof_key': prof_key, 'profile': profile, 'kind': kind,
|
|
53
|
+
'cache_read': cache_read, 'full_input': full_input}
|
|
54
|
+
if kind == 'explicit_ttl':
|
|
55
|
+
split = []
|
|
56
|
+
for turn in turns:
|
|
57
|
+
h1 = int(turn.get('cache_creation_1h', 0) or 0)
|
|
58
|
+
m5 = int(turn.get('cache_creation_5m', 0) or 0)
|
|
59
|
+
if h1 or m5:
|
|
60
|
+
split.append((f._keepwarm_iso_to_epoch(turn.get('timestamp')), h1, m5))
|
|
61
|
+
events = []
|
|
62
|
+
f._detect_explicit_ttl(
|
|
63
|
+
turns, tier_data, profile, dominant_model=model,
|
|
64
|
+
boundary=min(candidate_floor, profile.get('effective_ttl_seconds') or candidate_floor),
|
|
65
|
+
cutoff_ts=None, events_out=events)
|
|
66
|
+
s['split'] = split
|
|
67
|
+
s['events'] = [(_stamp(e.get('timestamp')), e) for e in events]
|
|
68
|
+
elif kind != 'none':
|
|
69
|
+
detail = {}
|
|
70
|
+
s['collapse'] = f._detect_automatic_collapse(turns, profile, dominant_model=model, detail_out=detail)
|
|
71
|
+
s['max_gap'] = detail.get('max_gap', 0)
|
|
72
|
+
return s, True
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def summary(f, filepath, parse_fn, runtime, tier_data, candidate_floor):
|
|
76
|
+
"""The file's window-independent facts, or None when it has no turns."""
|
|
77
|
+
try:
|
|
78
|
+
st = os.stat(filepath)
|
|
79
|
+
key = (str(filepath), st.st_mtime_ns, st.st_size, runtime, id(tier_data), candidate_floor,
|
|
80
|
+
id(parse_fn), id(f._resolve_cache_profile), id(f._detect_explicit_ttl),
|
|
81
|
+
id(f._detect_automatic_collapse), id(f._dominant_turn_model))
|
|
82
|
+
except OSError:
|
|
83
|
+
key = None
|
|
84
|
+
memo = _memo(f)
|
|
85
|
+
if key is not None and key in memo:
|
|
86
|
+
return memo[key]
|
|
87
|
+
s, cacheable = _summarize(f, filepath, parse_fn, runtime, tier_data, candidate_floor)
|
|
88
|
+
if key is not None and cacheable:
|
|
89
|
+
if len(memo) >= _MAX:
|
|
90
|
+
memo.clear()
|
|
91
|
+
memo[key] = s
|
|
92
|
+
return s
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def split_in_window(s, cutoff_ts):
|
|
96
|
+
"""1h and 5m cache-write tokens on turns inside the window."""
|
|
97
|
+
h1 = m5 = 0
|
|
98
|
+
for ts, a, b in s['split']:
|
|
99
|
+
if cutoff_ts is not None and (ts is None or ts < cutoff_ts):
|
|
100
|
+
continue
|
|
101
|
+
h1 += a
|
|
102
|
+
m5 += b
|
|
103
|
+
return h1, m5
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def events_in_window(s, cutoff_ts):
|
|
107
|
+
"""Fresh copies of the rebuilds whose resume turn is inside the window."""
|
|
108
|
+
return [dict(e) for ts, e in s['events']
|
|
109
|
+
if cutoff_ts is None or (ts is not None and ts >= cutoff_ts)]
|
|
@@ -1,15 +1,63 @@
|
|
|
1
1
|
"""Price a weekly activity window while reporting missing transcript coverage."""
|
|
2
2
|
|
|
3
|
+
import os
|
|
4
|
+
|
|
5
|
+
# Transcripts are append-only, so a file last modified before the window opened
|
|
6
|
+
# holds no record stamped inside it. One day of slack covers clock adjustments.
|
|
7
|
+
_SETTLED_SLACK_SECONDS = 86400
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def _merge_model_usage(into, extra):
|
|
11
|
+
for model, tokens in (extra or {}).items():
|
|
12
|
+
try:
|
|
13
|
+
value = float(tokens or 0)
|
|
14
|
+
except (TypeError, ValueError):
|
|
15
|
+
continue
|
|
16
|
+
if value > 0:
|
|
17
|
+
into[model] = into.get(model, 0) + value
|
|
18
|
+
return into
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _merge_breakdown(into, extra):
|
|
22
|
+
for model, parts in (extra or {}).items():
|
|
23
|
+
if not isinstance(parts, dict):
|
|
24
|
+
continue
|
|
25
|
+
target = into.setdefault(model, {})
|
|
26
|
+
for key, value in parts.items():
|
|
27
|
+
if isinstance(value, (int, float)) and not isinstance(value, bool):
|
|
28
|
+
target[key] = target.get(key, 0) + value
|
|
29
|
+
elif key == "requests" and isinstance(value, list):
|
|
30
|
+
target[key] = list(target.get(key) or []) + list(value)
|
|
31
|
+
elif key not in target:
|
|
32
|
+
target[key] = value
|
|
33
|
+
return into
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _settled_before(paths, start):
|
|
37
|
+
"""True when every file was last written well before ``start``.
|
|
38
|
+
|
|
39
|
+
Such a transcript contributes nothing to the window, so it is not parsed.
|
|
40
|
+
Any stat failure answers False and the file is parsed as before.
|
|
41
|
+
"""
|
|
42
|
+
cutoff = start.timestamp() - _SETTLED_SLACK_SECONDS
|
|
43
|
+
try:
|
|
44
|
+
return all(os.stat(p).st_mtime < cutoff for p in paths)
|
|
45
|
+
except (OSError, ValueError, OverflowError):
|
|
46
|
+
return False
|
|
47
|
+
|
|
3
48
|
|
|
4
49
|
def price(facade, conn, start, end, tier):
|
|
5
50
|
paths = conn.execute(
|
|
6
51
|
"SELECT jsonl_path, date, last_activity_day, cost_usd FROM session_log "
|
|
7
52
|
"WHERE input_tokens IS NOT NULL AND COALESCE(is_sidechain,0)=0").fetchall()
|
|
8
|
-
|
|
53
|
+
# Compare resolved paths: a file discovered under another spelling of a
|
|
54
|
+
# logged path (a symlinked config dir) is the same transcript.
|
|
55
|
+
known = {os.path.realpath(str(row[0])) for row in paths}
|
|
9
56
|
for path, _mtime, _ in facade._find_all_jsonl_files(None):
|
|
10
|
-
|
|
57
|
+
real = os.path.realpath(str(path))
|
|
58
|
+
if real not in known:
|
|
11
59
|
paths.append((str(path), '', None, None))
|
|
12
|
-
known.add(
|
|
60
|
+
known.add(real)
|
|
13
61
|
rows, missing = [], 0
|
|
14
62
|
costs, missing_cost, cost_complete = 0.0, 0.0, True
|
|
15
63
|
request_ledger = {}
|
|
@@ -25,6 +73,8 @@ def price(facade, conn, start, end, tier):
|
|
|
25
73
|
missing_cost += max(0.0, float(recorded_cost))
|
|
26
74
|
continue
|
|
27
75
|
children = facade._find_subagent_jsonl_files(path)
|
|
76
|
+
if _settled_before([path, *children], start):
|
|
77
|
+
continue
|
|
28
78
|
parsed = facade._parse_session_jsonl(path, window_start=start, window_end=end)
|
|
29
79
|
if parsed and parsed.get('is_sidechain'):
|
|
30
80
|
continue
|
|
@@ -38,6 +88,8 @@ def price(facade, conn, start, end, tier):
|
|
|
38
88
|
inp, out = parsed['total_input_tokens'], parsed['total_output_tokens']
|
|
39
89
|
cw1, cw5 = parsed['total_cache_create_1h'], parsed['total_cache_create_5m']
|
|
40
90
|
child_cache_read = 0
|
|
91
|
+
combined_usage = _merge_model_usage({}, parsed.get('model_usage'))
|
|
92
|
+
combined_breakdown = _merge_breakdown({}, parsed.get('model_usage_breakdown'))
|
|
41
93
|
for child in children:
|
|
42
94
|
cp = facade._parse_session_jsonl(child, window_start=start, window_end=end)
|
|
43
95
|
if cp:
|
|
@@ -47,16 +99,21 @@ def price(facade, conn, start, end, tier):
|
|
|
47
99
|
cw1 += cp['total_cache_create_1h']
|
|
48
100
|
cw5 += cp['total_cache_create_5m']
|
|
49
101
|
child_cache_read += cp['total_cache_read']
|
|
102
|
+
_merge_model_usage(combined_usage, cp.get('model_usage'))
|
|
103
|
+
_merge_breakdown(combined_breakdown, cp.get('model_usage_breakdown'))
|
|
50
104
|
if not parsed['api_calls'] and inp + out == 0:
|
|
51
105
|
continue
|
|
52
106
|
if recorded_cost is None:
|
|
53
107
|
cost_complete = False
|
|
54
108
|
else:
|
|
55
109
|
costs += max(0.0, float(recorded_cost))
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
110
|
+
parent_usage = facade.json.dumps(parsed['model_usage'])
|
|
111
|
+
usage = facade.json.dumps(combined_usage)
|
|
112
|
+
cache_read = float(parsed.get('total_cache_read') or 0) + child_cache_read
|
|
113
|
+
hit = cache_read / inp if inp else 0
|
|
114
|
+
rows.append((inp, out, cw5, cw1, hit, parent_usage, usage,
|
|
115
|
+
parsed['api_calls'], parsed['message_count'],
|
|
116
|
+
facade.json.dumps(combined_breakdown)))
|
|
60
117
|
total = len(rows) + missing
|
|
61
118
|
cost_share = missing_cost / (costs + missing_cost) if cost_complete and costs + missing_cost > 0 else None
|
|
62
119
|
# Beyond 5% missing, a partial workload is too incomplete to headline.
|
|
@@ -40,6 +40,10 @@ DAEMON_PORT = 24847
|
|
|
40
40
|
_VERSION_TIMEOUT_SECONDS = 5
|
|
41
41
|
|
|
42
42
|
|
|
43
|
+
def _is_windows() -> bool:
|
|
44
|
+
return os.name == "nt"
|
|
45
|
+
|
|
46
|
+
|
|
43
47
|
def _check(status: str, name: str, detail: str, hint: str = "") -> dict:
|
|
44
48
|
out = {"status": status, "name": name, "detail": detail}
|
|
45
49
|
if hint:
|
|
@@ -47,6 +51,15 @@ def _check(status: str, name: str, detail: str, hint: str = "") -> dict:
|
|
|
47
51
|
return out
|
|
48
52
|
|
|
49
53
|
|
|
54
|
+
def _measure_cli_current_python(*args: str) -> str:
|
|
55
|
+
command = _measure_cli(*args)
|
|
56
|
+
generic, sep, rest = command.partition(" ")
|
|
57
|
+
interpreter = os.path.basename(sys.executable)
|
|
58
|
+
if sep and interpreter and generic in {"python", "python3"}:
|
|
59
|
+
return f"{interpreter} {rest}"
|
|
60
|
+
return command
|
|
61
|
+
|
|
62
|
+
|
|
50
63
|
def _binary_checks() -> list:
|
|
51
64
|
checks = []
|
|
52
65
|
override = os.environ.get("TOKEN_OPTIMIZER_ANTIGRAVITY_BIN", "").strip()
|
|
@@ -194,7 +207,13 @@ def _plugin_checks() -> list:
|
|
|
194
207
|
config = json.loads(hooks_path.read_text(encoding="utf-8"))
|
|
195
208
|
group = config.get("token-optimizer") if isinstance(config, dict) else None
|
|
196
209
|
events = sorted(group.keys()) if isinstance(group, dict) else []
|
|
197
|
-
|
|
210
|
+
# PreToolUse is POSIX-only (the bash rewrite never runs on
|
|
211
|
+
# Windows). A Windows install that still carries it keeps working
|
|
212
|
+
# but is reported below so a reinstall removes it.
|
|
213
|
+
stale_windows_pre_tool = _is_windows() and "PreToolUse" in events
|
|
214
|
+
expected = {"PreInvocation", "Stop"} | (set() if _is_windows() else {"PreToolUse"})
|
|
215
|
+
if stale_windows_pre_tool:
|
|
216
|
+
expected.add("PreToolUse")
|
|
198
217
|
if not expected <= set(events):
|
|
199
218
|
raise ValueError(f"missing events: {sorted(expected - set(events))}")
|
|
200
219
|
# Every hook must call the bridge inside this plugin dir. Installs
|
|
@@ -208,11 +227,23 @@ def _plugin_checks() -> list:
|
|
|
208
227
|
cmds = [h.get("command", "") for h in handlers if isinstance(h, dict)]
|
|
209
228
|
if not any(isinstance(c, str) and any(s in c for s in spellings) for c in cmds):
|
|
210
229
|
raise ValueError(f"{name} hook does not call {bridge}")
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
230
|
+
if stale_windows_pre_tool:
|
|
231
|
+
reinstall = _measure_cli_current_python("antigravity-install")
|
|
232
|
+
checks.append(
|
|
233
|
+
_check(
|
|
234
|
+
"warn",
|
|
235
|
+
"plugin hooks",
|
|
236
|
+
f"{hooks_path} still registers PreToolUse, which is no "
|
|
237
|
+
"longer installed on Windows.",
|
|
238
|
+
_hint(f"Re-run `{reinstall}` to remove it."),
|
|
239
|
+
)
|
|
240
|
+
)
|
|
241
|
+
else:
|
|
242
|
+
checks.append(
|
|
243
|
+
_check(
|
|
244
|
+
"ok", "plugin hooks", f"{hooks_path} (events: {', '.join(events)})"
|
|
245
|
+
)
|
|
214
246
|
)
|
|
215
|
-
)
|
|
216
247
|
except (OSError, json.JSONDecodeError, ValueError) as exc:
|
|
217
248
|
checks.append(
|
|
218
249
|
_check(
|
|
@@ -492,18 +523,32 @@ def _bridge_selftest_check() -> dict:
|
|
|
492
523
|
_hint("Re-run `python3 measure.py antigravity-install` to refresh the payload."),
|
|
493
524
|
)
|
|
494
525
|
out = (proc.stdout or "").strip()
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
526
|
+
try:
|
|
527
|
+
reply = json.loads(out) if out else None
|
|
528
|
+
except (json.JSONDecodeError, ValueError):
|
|
529
|
+
return _check(
|
|
530
|
+
"fail",
|
|
531
|
+
"bridge self-test",
|
|
532
|
+
f"stdout is not valid JSON; the host would read the hook as "
|
|
533
|
+
f"malformed (stdout: {out[:200]!r}).",
|
|
534
|
+
_hint("Re-run `python3 measure.py antigravity-install` to refresh the payload."),
|
|
535
|
+
)
|
|
536
|
+
# agy denies a PreToolUse reply that has no "decision", so a bare {} or
|
|
537
|
+
# empty stdout blocks every shell command even though it is valid JSON.
|
|
538
|
+
if not (isinstance(reply, dict) and reply.get("decision")):
|
|
539
|
+
return _check(
|
|
540
|
+
"fail",
|
|
541
|
+
"bridge self-test",
|
|
542
|
+
f"PreToolUse reply has no decision; agy treats that as deny and "
|
|
543
|
+
f"blocks every run_command (stdout: {out[:200]!r}).",
|
|
544
|
+
_hint("Re-run `python3 measure.py antigravity-install` to refresh the payload."),
|
|
545
|
+
)
|
|
546
|
+
detail = (
|
|
547
|
+
"exit 0, bridge probe carries a decision"
|
|
548
|
+
if _is_windows()
|
|
549
|
+
else "exit 0, PreToolUse reply carries a decision"
|
|
550
|
+
)
|
|
551
|
+
return _check("ok", "bridge self-test", detail)
|
|
507
552
|
|
|
508
553
|
|
|
509
554
|
def run_checks() -> list:
|
|
@@ -98,6 +98,18 @@ def _read_payload() -> dict | None:
|
|
|
98
98
|
return obj if isinstance(obj, dict) else None
|
|
99
99
|
|
|
100
100
|
|
|
101
|
+
# agy requires a PreToolUse reply to carry "decision" and treats a reply
|
|
102
|
+
# without one as deny, which blocked every run_command. "ask" defers to the
|
|
103
|
+
# user's own permission mode, so a no-op stays a no-op.
|
|
104
|
+
_PRE_TOOL_PASS = {"decision": "ask"}
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def _pre_tool_reply(out) -> dict:
|
|
108
|
+
if isinstance(out, dict) and out.get("decision"):
|
|
109
|
+
return out
|
|
110
|
+
return dict(_PRE_TOOL_PASS)
|
|
111
|
+
|
|
112
|
+
|
|
101
113
|
def _emit(obj: dict) -> None:
|
|
102
114
|
"""Write exactly one JSON object to stdout."""
|
|
103
115
|
try:
|
|
@@ -485,21 +497,24 @@ def main(argv=None) -> int:
|
|
|
485
497
|
event = sys.argv[1]
|
|
486
498
|
|
|
487
499
|
payload = _read_payload() or {}
|
|
500
|
+
pre_tool = event == "pre-tool-use"
|
|
488
501
|
|
|
489
502
|
try:
|
|
490
503
|
from runtime_env import antigravity_home
|
|
491
504
|
except Exception:
|
|
505
|
+
if pre_tool:
|
|
506
|
+
_emit(_pre_tool_reply({}))
|
|
492
507
|
return 0
|
|
493
508
|
|
|
494
509
|
try:
|
|
495
510
|
if not _consent_ok(antigravity_home()):
|
|
496
|
-
_emit({})
|
|
511
|
+
_emit(_pre_tool_reply({}) if pre_tool else {})
|
|
497
512
|
return 0
|
|
498
513
|
|
|
499
514
|
if event == "pre-invocation":
|
|
500
515
|
out = handle_pre_invocation(payload)
|
|
501
|
-
elif
|
|
502
|
-
out = handle_pre_tool_use(payload)
|
|
516
|
+
elif pre_tool:
|
|
517
|
+
out = _pre_tool_reply(handle_pre_tool_use(payload))
|
|
503
518
|
elif event == "stop":
|
|
504
519
|
out = handle_stop(payload)
|
|
505
520
|
else:
|
|
@@ -515,6 +530,8 @@ def main(argv=None) -> int:
|
|
|
515
530
|
traceback.print_exc(file=sys.stderr)
|
|
516
531
|
except Exception:
|
|
517
532
|
pass
|
|
533
|
+
if pre_tool:
|
|
534
|
+
_emit(_pre_tool_reply({}))
|
|
518
535
|
return 0
|
|
519
536
|
return 0
|
|
520
537
|
|
|
@@ -139,6 +139,10 @@ def data_dir(home: Path) -> Path:
|
|
|
139
139
|
return home / "token-optimizer"
|
|
140
140
|
|
|
141
141
|
|
|
142
|
+
def _is_windows() -> bool:
|
|
143
|
+
return os.name == "nt"
|
|
144
|
+
|
|
145
|
+
|
|
142
146
|
def _hooks_config(bridge_path: Path) -> dict:
|
|
143
147
|
"""hooks.json per the Antigravity hooks contract (builtin agy-customizations
|
|
144
148
|
docs): a JSON object keyed by hook NAME; PreToolUse uses a matcher group,
|
|
@@ -157,18 +161,23 @@ def _hooks_config(bridge_path: Path) -> dict:
|
|
|
157
161
|
"timeout": timeout,
|
|
158
162
|
}
|
|
159
163
|
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
164
|
+
hooks = {
|
|
165
|
+
"PreInvocation": [cmd("pre-invocation", PRE_TIMEOUT_SEC)],
|
|
166
|
+
"Stop": [cmd("stop", STOP_TIMEOUT_SEC)],
|
|
167
|
+
}
|
|
168
|
+
if not _is_windows():
|
|
169
|
+
# Only the run_command tool is rewritten; the matcher keeps every
|
|
170
|
+
# other tool call out of the bridge's hot path entirely. Windows is
|
|
171
|
+
# not registered at all: the bridge never rewrites there, so the hook
|
|
172
|
+
# would only add a Python launch (and a chance to fail) to every
|
|
173
|
+
# shell command for nothing.
|
|
174
|
+
hooks = {
|
|
163
175
|
"PreToolUse": [
|
|
164
|
-
|
|
165
|
-
# other tool call out of the bridge's hot path entirely.
|
|
166
|
-
{"matcher": "run_command", "hooks": [pre_tool]},
|
|
176
|
+
{"matcher": "run_command", "hooks": [cmd("pre-tool-use", PRE_TIMEOUT_SEC)]},
|
|
167
177
|
],
|
|
168
|
-
|
|
169
|
-
"Stop": [cmd("stop", STOP_TIMEOUT_SEC)],
|
|
178
|
+
**hooks,
|
|
170
179
|
}
|
|
171
|
-
}
|
|
180
|
+
return {HOOK_NAME: hooks}
|
|
172
181
|
|
|
173
182
|
|
|
174
183
|
def _ensure_config_dir_permissions(path: Path) -> None:
|