@alexgreensh/token-optimizer 5.13.72 → 5.13.74
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 -8
- package/hooks/sessionstart_runner.py +25 -0
- package/package.json +1 -1
- package/skills/token-optimizer/assets/dashboard.html +20 -7
- package/skills/token-optimizer/assets/savings_story.js +10 -6
- package/skills/token-optimizer/references/cli-reference.md +9 -0
- package/skills/token-optimizer/scripts/_measure/__init__.py +3 -2
- package/skills/token-optimizer/scripts/_measure/baseline_provenance.py +3 -1
- package/skills/token-optimizer/scripts/_measure/cache_policy.py +2 -79
- package/skills/token-optimizer/scripts/_measure/cli.py +24 -0
- package/skills/token-optimizer/scripts/_measure/continuity.py +12 -0
- package/skills/token-optimizer/scripts/_measure/daemon.py +77 -15
- package/skills/token-optimizer/scripts/_measure/install_baseline.py +157 -0
- package/skills/token-optimizer/scripts/_measure/mod_action_booking.py +16 -3
- package/skills/token-optimizer/scripts/_measure/mod_action_diagnostics.py +24 -0
- package/skills/token-optimizer/scripts/_measure/mod_action_selftest.py +33 -0
- package/skills/token-optimizer/scripts/_measure/mod_compaction_booking.py +4 -4
- package/skills/token-optimizer/scripts/_measure/mod_fresh_booking.py +2 -2
- package/skills/token-optimizer/scripts/_measure/nudge_followthrough.py +334 -0
- package/skills/token-optimizer/scripts/_measure/own_price_card.py +3 -0
- package/skills/token-optimizer/scripts/_measure/pilot_report.py +349 -0
- package/skills/token-optimizer/scripts/_measure/pricing.py +15 -414
- package/skills/token-optimizer/scripts/_measure/quality_archive.py +5 -10
- package/skills/token-optimizer/scripts/_measure/routing_credit.py +60 -0
- package/skills/token-optimizer/scripts/_measure/routing_default.py +374 -0
- package/skills/token-optimizer/scripts/_measure/routing_savings.py +368 -0
- package/skills/token-optimizer/scripts/_measure/runway_all_in.py +42 -0
- package/skills/token-optimizer/scripts/_measure/savings.py +29 -247
- package/skills/token-optimizer/scripts/_measure/savings_story.py +8 -1
- package/skills/token-optimizer/scripts/_measure/session_activity.py +128 -0
- package/skills/token-optimizer/scripts/_measure/ttl_period.py +59 -0
- package/skills/token-optimizer/scripts/cloud_kit.py +1 -4
- package/skills/token-optimizer/scripts/codex_doctor.py +1 -10
- package/skills/token-optimizer/scripts/hermes_doctor.py +1 -10
- package/skills/token-optimizer/scripts/hermes_install.py +1 -10
- package/skills/token-optimizer/scripts/injection.py +5 -2
- package/skills/token-optimizer/scripts/measure.py +4 -4
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
"""Frozen baseline from the user's own activity around installation."""
|
|
2
|
+
from datetime import datetime, timedelta
|
|
3
|
+
import json
|
|
4
|
+
import math
|
|
5
|
+
import shutil
|
|
6
|
+
|
|
7
|
+
from . import _compat, baseline_provenance
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def compute():
|
|
11
|
+
f = _compat.facade()
|
|
12
|
+
try:
|
|
13
|
+
conn = f._init_trends_db()
|
|
14
|
+
f.ensure_activity_view(conn)
|
|
15
|
+
try:
|
|
16
|
+
rows = conn.execute(
|
|
17
|
+
"SELECT date,id,input_tokens,output_tokens,cache_create_5m_tokens,"
|
|
18
|
+
"cache_create_1h_tokens,cache_hit_rate FROM session_activity "
|
|
19
|
+
"WHERE input_tokens IS NOT NULL AND COALESCE(is_sidechain,0)=0 ORDER BY date,id"
|
|
20
|
+
).fetchall()
|
|
21
|
+
if not rows:
|
|
22
|
+
return None
|
|
23
|
+
evidence = baseline_provenance.install_evidence(f)
|
|
24
|
+
install = datetime.fromisoformat(evidence['date']) if evidence.get('date') else None
|
|
25
|
+
end = install if install and evidence.get('source') in ('snapshot', 'first_event') else None
|
|
26
|
+
start = end - timedelta(days=30) if end else None
|
|
27
|
+
selected = [r for r in rows if start and start <= datetime.fromisoformat(str(r[0])[:10]) < end]
|
|
28
|
+
coverage = 'pre_install'
|
|
29
|
+
if len({r[1] for r in selected}) < 30:
|
|
30
|
+
start = datetime.fromisoformat(str(rows[0][0])[:10]) + timedelta(days=f._BASELINE_ONBOARDING_DAYS)
|
|
31
|
+
end = start + timedelta(days=f._BASELINE_EARLY_WINDOW_DAYS)
|
|
32
|
+
selected = [r for r in rows if start <= datetime.fromisoformat(str(r[0])[:10]) < end]
|
|
33
|
+
coverage = 'post_install'
|
|
34
|
+
vectors = {}
|
|
35
|
+
for row in selected:
|
|
36
|
+
acc = vectors.setdefault(row[1], [0.0] * 5)
|
|
37
|
+
for i in range(4):
|
|
38
|
+
acc[i] += row[i + 2] or 0
|
|
39
|
+
acc[4] += (row[2] or 0) * (row[6] or 0)
|
|
40
|
+
window_rows = [(*v[:4], v[4] / v[0] if v[0] else 0.0) for v in vectors.values()]
|
|
41
|
+
if len(window_rows) < max(30, f._BASELINE_MIN_STABLE_SESSIONS):
|
|
42
|
+
return None
|
|
43
|
+
vec, used, total = f._winsorized_mean_session(window_rows)
|
|
44
|
+
if not all(math.isfinite(x) for x in vec):
|
|
45
|
+
return None
|
|
46
|
+
try:
|
|
47
|
+
model_rows = conn.execute(
|
|
48
|
+
'SELECT model, SUM(total_tokens) FROM model_daily WHERE date >= ? AND date < ? GROUP BY model',
|
|
49
|
+
(start.strftime('%Y-%m-%d'), end.strftime('%Y-%m-%d'))).fetchall()
|
|
50
|
+
except f.sqlite3.Error:
|
|
51
|
+
model_rows = []
|
|
52
|
+
if not model_rows:
|
|
53
|
+
try:
|
|
54
|
+
raw_rows = conn.execute(
|
|
55
|
+
'SELECT model_usage_json, all_model_usage_json FROM session_activity '
|
|
56
|
+
'WHERE date >= ? AND date < ? AND COALESCE(is_sidechain,0)=0',
|
|
57
|
+
(start.strftime('%Y-%m-%d'), end.strftime('%Y-%m-%d'))).fetchall()
|
|
58
|
+
for parent, combined in raw_rows:
|
|
59
|
+
usage = f._safe_json_dict(parent) or f._safe_json_dict(combined)
|
|
60
|
+
model_rows.extend(usage.items())
|
|
61
|
+
except f.sqlite3.Error:
|
|
62
|
+
pass
|
|
63
|
+
finally:
|
|
64
|
+
conn.close()
|
|
65
|
+
totals = {}
|
|
66
|
+
for model, tokens in model_rows:
|
|
67
|
+
family = f._normalize_model_name(str(model or ''))
|
|
68
|
+
if family and tokens and tokens > 0 and f._routing_class_rates(model):
|
|
69
|
+
totals[family] = totals.get(family, 0) + tokens
|
|
70
|
+
grand = sum(totals.values())
|
|
71
|
+
shares = {k: v / grand for k, v in totals.items()} if grand else (f._pretool_baseline_mix() or {})
|
|
72
|
+
source = 'robust_earliest' if grand else ('pretool_baseline' if shares else 'unavailable')
|
|
73
|
+
snap = baseline_provenance._read_json(f.SNAPSHOT_DIR / 'snapshot_before.json') or {}
|
|
74
|
+
return {'version': f._BASELINE_VERSION, 'activity_basis': 1,
|
|
75
|
+
'typical_session': dict(zip(('fresh_input', 'cache_write', 'cache_read', 'output'), (round(x, 1) for x in vec))),
|
|
76
|
+
'opus_share': round(float(shares.get('opus', 0)), 4), 'opus_share_source': source,
|
|
77
|
+
'model_shares': {k: round(float(v), 4) for k, v in shares.items() if v},
|
|
78
|
+
'window': {'start': start.strftime('%Y-%m-%d'), 'end': (end - timedelta(days=1)).strftime('%Y-%m-%d'),
|
|
79
|
+
'sessions_used': used, 'sessions_total': total, 'elapsed': datetime.now() >= end, 'coverage': coverage},
|
|
80
|
+
'method': 'winsorized_mean', 'winsor_pct': f._BASELINE_WINSOR_PCT,
|
|
81
|
+
'structural_overhead_tokens': int((snap.get('totals') or {}).get('estimated_total', 0) or 0)}
|
|
82
|
+
except (f.sqlite3.Error, OSError, ValueError, TypeError, OverflowError):
|
|
83
|
+
return None
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def get(freeze=True):
|
|
87
|
+
f = _compat.facade()
|
|
88
|
+
path = f.SNAPSHOT_DIR / 'baseline_state.json'
|
|
89
|
+
try:
|
|
90
|
+
old = json.loads(path.read_text(encoding='utf-8'))
|
|
91
|
+
if isinstance(old, dict) and old.get('version') == f._BASELINE_VERSION and old.get('activity_basis') == 1:
|
|
92
|
+
return old
|
|
93
|
+
except (OSError, ValueError, TypeError):
|
|
94
|
+
old = None
|
|
95
|
+
if isinstance(old, dict) and old.get('version') not in f._BASELINE_KNOWN_VERSIONS:
|
|
96
|
+
return None
|
|
97
|
+
if isinstance(old, dict) and old.get('activity_basis') == 1 and old.get('typical_session') and baseline_provenance.install_evidence(f).get('source') not in ('snapshot', 'first_event'):
|
|
98
|
+
return old
|
|
99
|
+
state = f._compute_baseline_state()
|
|
100
|
+
if not state or not (state.get('window') or {}).get('elapsed'):
|
|
101
|
+
if isinstance(old, dict) and old.get('activity_basis') == 1 and old.get('typical_session'):
|
|
102
|
+
return old
|
|
103
|
+
adopted = f._adopt_orphaned_baseline() if old is None else None
|
|
104
|
+
if adopted and adopted.get('activity_basis') == 1:
|
|
105
|
+
return adopted
|
|
106
|
+
return state
|
|
107
|
+
# A shrinking baseline means the HISTORY thinned, not that the user got cheaper.
|
|
108
|
+
# Keep the incumbent active, park the candidate beside it, and record the
|
|
109
|
+
# rejection rather than letting the reported saving quietly collapse.
|
|
110
|
+
incumbent = old if isinstance(old, dict) and old.get('activity_basis') == 1 and old.get('typical_session') else None
|
|
111
|
+
if incumbent is not None and f._baseline_shrink_is_material(incumbent, state):
|
|
112
|
+
try:
|
|
113
|
+
f._write_baseline_state(path.with_name('baseline_state.candidate.json'), dict(
|
|
114
|
+
state,
|
|
115
|
+
rejected_reason='materially smaller than the existing baseline',
|
|
116
|
+
rejected_at=datetime.now().isoformat(),
|
|
117
|
+
incumbent_cost_usd=round(f._baseline_priced_cost(incumbent), 4),
|
|
118
|
+
candidate_cost_usd=round(f._baseline_priced_cost(state), 4)))
|
|
119
|
+
except (OSError, AttributeError):
|
|
120
|
+
pass
|
|
121
|
+
return incumbent
|
|
122
|
+
if freeze and state['window']['elapsed']:
|
|
123
|
+
try:
|
|
124
|
+
if isinstance(old, dict):
|
|
125
|
+
backup = path.with_name('baseline_state.v%s.json' % old.get('version', 'unknown'))
|
|
126
|
+
if not backup.exists():
|
|
127
|
+
shutil.copy2(path, backup)
|
|
128
|
+
state['captured_at'] = datetime.now().isoformat()
|
|
129
|
+
state['source'] = 'frozen_from_history'
|
|
130
|
+
f._write_baseline_state(path, state)
|
|
131
|
+
except OSError:
|
|
132
|
+
pass
|
|
133
|
+
return state
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def workload_anchor(f, conn, tier):
|
|
137
|
+
"""Price the frozen window when its transcript-based anchor is unavailable."""
|
|
138
|
+
try:
|
|
139
|
+
state = json.loads((f.SNAPSHOT_DIR / 'baseline_state.json').read_text(encoding='utf-8'))
|
|
140
|
+
if state.get('version') != f._BASELINE_VERSION:
|
|
141
|
+
return None
|
|
142
|
+
window = state.get('window') or {}
|
|
143
|
+
start, end = window.get('start'), window.get('end')
|
|
144
|
+
if not start or not end:
|
|
145
|
+
return None
|
|
146
|
+
metrics = f._price_parent_window(conn, 'AND date >= ? AND date <= ?', (start, end), tier)
|
|
147
|
+
return {'metrics': metrics, 'label': 'baseline (%s to %s)' % (start, end)} if metrics else None
|
|
148
|
+
except (OSError, ValueError, TypeError):
|
|
149
|
+
return None
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def has_install_anchor(f):
|
|
153
|
+
try:
|
|
154
|
+
state = json.loads((f.SNAPSHOT_DIR / 'baseline_state.json').read_text(encoding='utf-8'))
|
|
155
|
+
return state.get('version') == f._BASELINE_VERSION
|
|
156
|
+
except (OSError, ValueError, TypeError, AttributeError):
|
|
157
|
+
return False
|
|
@@ -161,18 +161,31 @@ def record(facade, event):
|
|
|
161
161
|
'ts': when, 'state': 'armed', 'owner': None, 'pings_fired': [when],
|
|
162
162
|
'pause_key': pause_key, 'manual_action_id': ident})
|
|
163
163
|
return {'ok': True, 'pause_key': pause_key, 'cost_usd': cost, 'duplicate': bool(finished), 'resume_trackable': usable}
|
|
164
|
-
except Exception:
|
|
165
|
-
return {'ok': False, 'reason': 'receipt-unavailable'}
|
|
164
|
+
except Exception as exc:
|
|
165
|
+
return {'ok': False, 'reason': 'receipt-unavailable', 'exception_class': type(exc).__name__}
|
|
166
166
|
|
|
167
167
|
|
|
168
168
|
def main(facade):
|
|
169
169
|
"""Read a single bounded action receipt from standard input."""
|
|
170
|
+
if '--selftest' in facade.args[1:]:
|
|
171
|
+
from . import mod_action_selftest
|
|
172
|
+
return mod_action_selftest.main(facade)
|
|
173
|
+
event = None
|
|
170
174
|
try:
|
|
171
175
|
raw = facade.sys.stdin.read(65537)
|
|
172
176
|
if len(raw) > 65536:
|
|
173
177
|
raise ValueError('receipt too large')
|
|
174
|
-
|
|
178
|
+
event = json.loads(raw)
|
|
179
|
+
if isinstance(event, dict) and event.get('action') == 'diagnostic':
|
|
180
|
+
from . import mod_action_diagnostics
|
|
181
|
+
mod_action_diagnostics.log(facade.SNAPSHOT_DIR, {'action': 'fork', 'reason': str(event.get('reason', 'failed'))[:200]})
|
|
182
|
+
result = {'ok': True}
|
|
183
|
+
else:
|
|
184
|
+
result = record(facade, event)
|
|
175
185
|
except (ValueError, TypeError):
|
|
176
186
|
result = {'ok': False, 'reason': 'invalid-receipt'}
|
|
187
|
+
if not result['ok'] or result.get('reason') == 'receipt-unavailable':
|
|
188
|
+
from . import mod_action_diagnostics
|
|
189
|
+
mod_action_diagnostics.log(facade.SNAPSHOT_DIR, {'action': event.get('action') if isinstance(event, dict) else None, **result})
|
|
177
190
|
print(json.dumps(result, separators=(',', ':')))
|
|
178
191
|
return 0 if result['ok'] else 1
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
"""Small local diagnostic log for mod action failures."""
|
|
2
|
+
import json
|
|
3
|
+
import os
|
|
4
|
+
import time
|
|
5
|
+
|
|
6
|
+
MAX_BYTES = 65536
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def log(directory, details):
|
|
10
|
+
try:
|
|
11
|
+
directory.mkdir(parents=True, exist_ok=True)
|
|
12
|
+
path = directory / 'mod-actions.log'
|
|
13
|
+
line = json.dumps({'timestamp': time.time(), **details}, separators=(',', ':')) + '\n'
|
|
14
|
+
fd = os.open(str(path), os.O_WRONLY | os.O_CREAT | os.O_APPEND | getattr(os, 'O_NOFOLLOW', 0), 0o600)
|
|
15
|
+
with os.fdopen(fd, 'a', encoding='utf-8') as stream:
|
|
16
|
+
if stream.tell() + len(line.encode('utf-8')) > MAX_BYTES:
|
|
17
|
+
stream.close()
|
|
18
|
+
fd = os.open(str(path), os.O_WRONLY | os.O_TRUNC | getattr(os, 'O_NOFOLLOW', 0))
|
|
19
|
+
with os.fdopen(fd, 'w', encoding='utf-8') as replacement:
|
|
20
|
+
replacement.write(line)
|
|
21
|
+
return
|
|
22
|
+
stream.write(line)
|
|
23
|
+
except OSError:
|
|
24
|
+
pass
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
"""Exercise the real mod booking CLI in an isolated temporary environment."""
|
|
2
|
+
import json
|
|
3
|
+
import os
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
import subprocess
|
|
6
|
+
import sys
|
|
7
|
+
import tempfile
|
|
8
|
+
import time
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def main(facade):
|
|
12
|
+
try:
|
|
13
|
+
with tempfile.TemporaryDirectory(prefix='to-mod-selftest-') as temporary:
|
|
14
|
+
root = Path(temporary)
|
|
15
|
+
transcript = root / 'selftest-session.jsonl'
|
|
16
|
+
transcript.write_text(json.dumps({'type': 'assistant', 'timestamp': '2026-01-01T00:00:00Z', 'message': {'model': 'claude-sonnet-4-5', 'usage': {'cache_read_input_tokens': 20000, 'cache_creation': {'ephemeral_1h_input_tokens': 100}}}}) + '\n', encoding='utf-8')
|
|
17
|
+
stat = transcript.stat()
|
|
18
|
+
event = {'action': 'warm-prepare', 'action_id': 'selftest', 'session_id': 'selftest-session', 'timestamp': time.time(), 'transcript_path': str(transcript), 'byte_size': stat.st_size, 'transcript_mtime': stat.st_mtime}
|
|
19
|
+
env = dict(os.environ, HOME=str(root), CLAUDE_CONFIG_DIR=str(root), TOKEN_OPTIMIZER_SNAPSHOT_DIR=str(root / 'data'), TOKEN_OPTIMIZER_RUNTIME='claude')
|
|
20
|
+
cmd = [sys.executable, str(Path(facade.__file__).resolve()), 'mod-action']
|
|
21
|
+
for action in ('warm-prepare', 'warm-cancel'):
|
|
22
|
+
event['action'] = action
|
|
23
|
+
result = subprocess.run(cmd, input=json.dumps(event), text=True, capture_output=True, env=env, timeout=30)
|
|
24
|
+
if result.returncode or not json.loads(result.stdout).get('ok'):
|
|
25
|
+
raise RuntimeError(action + ' failed')
|
|
26
|
+
rows = [json.loads(line) for line in (root / 'data' / 'keepwarm_ledger.jsonl').read_text().splitlines()]
|
|
27
|
+
if [row['status'] for row in rows] != ['firing', 'cancelled']:
|
|
28
|
+
raise RuntimeError('ledger verification failed')
|
|
29
|
+
print('PASS')
|
|
30
|
+
return 0
|
|
31
|
+
except Exception as exc:
|
|
32
|
+
print('FAIL: ' + type(exc).__name__ + ': ' + str(exc))
|
|
33
|
+
return 1
|
|
@@ -143,8 +143,8 @@ def _record_verified(facade, event):
|
|
|
143
143
|
raise
|
|
144
144
|
finally:
|
|
145
145
|
conn.close()
|
|
146
|
-
except Exception:
|
|
147
|
-
return {'ok': False, 'reason': 'receipt-unavailable'}
|
|
146
|
+
except Exception as exc:
|
|
147
|
+
return {'ok': False, 'reason': 'receipt-unavailable', 'exception_class': type(exc).__name__}
|
|
148
148
|
|
|
149
149
|
|
|
150
150
|
|
|
@@ -208,8 +208,8 @@ def record(facade, event):
|
|
|
208
208
|
if (isinstance(event, dict) and (event.get('observed_manual') is True or event.get('observed_action') is True) and result.get('reason') in
|
|
209
209
|
('invalid-token-delta', 'existing-compaction-credit', 'usage-unavailable', 'cost-unavailable', 'cost-mismatch', 'cache-write-class-unavailable', 'model-unpriced',
|
|
210
210
|
'manual-boundary-unverified', 'receipt-unavailable')):
|
|
211
|
-
if _observe(facade, event, result.get('reason')):
|
|
212
|
-
return {'ok': True, 'priced': False, 'reason': result.get('reason')}
|
|
211
|
+
if _observe(facade, event, result.get('reason') + (':' + result['exception_class'] if result.get('exception_class') else '')):
|
|
212
|
+
return {'ok': True, 'priced': False, 'reason': result.get('reason'), **({'exception_class': result['exception_class']} if result.get('exception_class') else {})}
|
|
213
213
|
return result
|
|
214
214
|
|
|
215
215
|
|
|
@@ -76,8 +76,8 @@ def record(facade, event):
|
|
|
76
76
|
raise
|
|
77
77
|
finally:
|
|
78
78
|
conn.close()
|
|
79
|
-
except Exception:
|
|
80
|
-
return {'ok': False, 'reason': 'receipt-unavailable'}
|
|
79
|
+
except Exception as exc:
|
|
80
|
+
return {'ok': False, 'reason': 'receipt-unavailable', 'exception_class': type(exc).__name__}
|
|
81
81
|
|
|
82
82
|
|
|
83
83
|
def summary(facade, cutoff):
|
|
@@ -0,0 +1,334 @@
|
|
|
1
|
+
"""Record context nudges and price observed follow-through from transcripts."""
|
|
2
|
+
import json
|
|
3
|
+
import os
|
|
4
|
+
from datetime import datetime, timezone
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def _diagnostic(facade, exc):
|
|
9
|
+
"""Keep a bounded, path-free diagnostic without breaking collection."""
|
|
10
|
+
try:
|
|
11
|
+
directory = Path(facade.SNAPSHOT_DIR)
|
|
12
|
+
directory.mkdir(parents=True, exist_ok=True)
|
|
13
|
+
path = directory / 'nudge-resolve.log'
|
|
14
|
+
line = json.dumps({'operation': 'resolve', 'error': type(exc).__name__}) + '\n'
|
|
15
|
+
flags = os.O_WRONLY | os.O_CREAT | os.O_APPEND | getattr(os, 'O_NOFOLLOW', 0)
|
|
16
|
+
fd = os.open(str(path), flags, 0o600)
|
|
17
|
+
with os.fdopen(fd, 'a', encoding='utf-8') as stream:
|
|
18
|
+
if stream.tell() + len(line.encode('utf-8')) > 65536:
|
|
19
|
+
stream.close()
|
|
20
|
+
fd = os.open(str(path), os.O_WRONLY | os.O_TRUNC | getattr(os, 'O_NOFOLLOW', 0))
|
|
21
|
+
with os.fdopen(fd, 'w', encoding='utf-8') as replacement:
|
|
22
|
+
replacement.write(line)
|
|
23
|
+
else:
|
|
24
|
+
stream.write(line)
|
|
25
|
+
except (OSError, AttributeError):
|
|
26
|
+
pass
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _epoch(value):
|
|
30
|
+
try:
|
|
31
|
+
return datetime.fromisoformat(str(value).replace('Z', '+00:00')).timestamp()
|
|
32
|
+
except (ValueError, TypeError, OverflowError):
|
|
33
|
+
return None
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _rows(path):
|
|
37
|
+
with Path(path).open(encoding='utf-8', errors='replace') as stream:
|
|
38
|
+
for line in stream:
|
|
39
|
+
try:
|
|
40
|
+
row = json.loads(line)
|
|
41
|
+
if isinstance(row, dict) and not row.get('isSidechain'):
|
|
42
|
+
yield row
|
|
43
|
+
except ValueError:
|
|
44
|
+
continue
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _schema(conn):
|
|
48
|
+
conn.execute('CREATE TABLE IF NOT EXISTS nudge_events (id INTEGER PRIMARY KEY, session_uuid TEXT NOT NULL, kind TEXT NOT NULL, ts TEXT NOT NULL, context_tokens INTEGER, model TEXT, transcript_path TEXT, status TEXT NOT NULL DEFAULT "pending", action_ts TEXT, savings_event_id INTEGER)')
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def record(facade, sid, kind, tokens, model, path):
|
|
52
|
+
if not sid:
|
|
53
|
+
return
|
|
54
|
+
try:
|
|
55
|
+
conn = facade._init_trends_db()
|
|
56
|
+
try:
|
|
57
|
+
_schema(conn)
|
|
58
|
+
stamp = datetime.now(timezone.utc).isoformat()
|
|
59
|
+
conn.execute('INSERT INTO nudge_events(session_uuid,kind,ts,context_tokens,model,transcript_path) SELECT ?,?,?,?,?,? WHERE NOT EXISTS(SELECT 1 FROM nudge_events WHERE session_uuid=? AND kind=? AND ts=?)',
|
|
60
|
+
(sid, kind, stamp, tokens, model, str(path or ''), sid, kind, stamp))
|
|
61
|
+
conn.commit()
|
|
62
|
+
finally:
|
|
63
|
+
conn.close()
|
|
64
|
+
except Exception as exc:
|
|
65
|
+
_diagnostic(facade, exc)
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def _context(message):
|
|
69
|
+
usage = message.get('usage') or {}
|
|
70
|
+
try:
|
|
71
|
+
return sum(int(usage.get(k) or 0) for k in ('input_tokens', 'cache_read_input_tokens', 'cache_creation_input_tokens'))
|
|
72
|
+
except (AttributeError, TypeError, ValueError, OverflowError):
|
|
73
|
+
return 0
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
_MISSING = object()
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _message(row):
|
|
81
|
+
message = row.get('message')
|
|
82
|
+
return message if isinstance(message, dict) else None
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _ident(row, message):
|
|
86
|
+
ident = message.get('id') or row.get('uuid')
|
|
87
|
+
try:
|
|
88
|
+
hash(ident)
|
|
89
|
+
except TypeError:
|
|
90
|
+
return _MISSING
|
|
91
|
+
return ident
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def _requests(rows):
|
|
95
|
+
seen, requests = set(), []
|
|
96
|
+
for row in rows:
|
|
97
|
+
if row.get('type') != 'assistant':
|
|
98
|
+
continue
|
|
99
|
+
message = _message(row)
|
|
100
|
+
if message is None:
|
|
101
|
+
continue
|
|
102
|
+
ident = _ident(row, message)
|
|
103
|
+
if ident is _MISSING:
|
|
104
|
+
continue
|
|
105
|
+
if ident not in seen and _context(message) > 0:
|
|
106
|
+
seen.add(ident)
|
|
107
|
+
requests.append(message)
|
|
108
|
+
if len(requests) == 50:
|
|
109
|
+
break
|
|
110
|
+
return requests
|
|
111
|
+
|
|
112
|
+
def classify(rows, emitted, new_rows=None):
|
|
113
|
+
"""Return status, action timestamp and observed post-action requests."""
|
|
114
|
+
stamp = _epoch(emitted)
|
|
115
|
+
if stamp is None:
|
|
116
|
+
return 'pending', None, []
|
|
117
|
+
replies, action, following, seen = 0, None, [], set()
|
|
118
|
+
for row in rows:
|
|
119
|
+
ts = _epoch(row.get('timestamp'))
|
|
120
|
+
if ts is None or ts < stamp:
|
|
121
|
+
continue
|
|
122
|
+
if action is None:
|
|
123
|
+
if row.get('type') == 'system' and row.get('subtype') == 'compact_boundary':
|
|
124
|
+
action = row.get('timestamp')
|
|
125
|
+
continue
|
|
126
|
+
message = _message(row)
|
|
127
|
+
if row.get('type') == 'user' and message is not None and isinstance(message.get('content'), str) and message['content'].strip() == '/clear':
|
|
128
|
+
action = row.get('timestamp')
|
|
129
|
+
continue
|
|
130
|
+
if row.get('type') == 'assistant' and message is not None:
|
|
131
|
+
ident = _ident(row, message)
|
|
132
|
+
if ident is _MISSING:
|
|
133
|
+
continue
|
|
134
|
+
if ident not in seen:
|
|
135
|
+
seen.add(ident); replies += 1
|
|
136
|
+
if replies > 20:
|
|
137
|
+
return 'ignored', None, []
|
|
138
|
+
elif row.get('type') == 'system' and row.get('subtype') == 'compact_boundary':
|
|
139
|
+
break
|
|
140
|
+
elif row.get('type') == 'assistant':
|
|
141
|
+
message = _message(row)
|
|
142
|
+
if message is None:
|
|
143
|
+
continue
|
|
144
|
+
ident = _ident(row, message)
|
|
145
|
+
if ident is _MISSING:
|
|
146
|
+
continue
|
|
147
|
+
if ident not in seen and _context(message) > 0:
|
|
148
|
+
seen.add(ident); following.append(message)
|
|
149
|
+
if len(following) == 50:
|
|
150
|
+
break
|
|
151
|
+
if action is not None:
|
|
152
|
+
return 'followed', action, following
|
|
153
|
+
if new_rows:
|
|
154
|
+
end = max((_epoch(r.get('timestamp')) or 0 for r in rows), default=0)
|
|
155
|
+
start = min((_epoch(r.get('timestamp')) or float('inf') for r in new_rows), default=float('inf'))
|
|
156
|
+
if end and start - end > 1800:
|
|
157
|
+
return 'ignored', None, []
|
|
158
|
+
return 'followed', new_rows[0].get('timestamp'), _requests(new_rows)
|
|
159
|
+
return 'pending', None, []
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def _project_index(directory):
|
|
163
|
+
"""Read each transcript once before the database write transaction."""
|
|
164
|
+
transcripts, failures = {}, []
|
|
165
|
+
for path in Path(directory).glob('*.jsonl'):
|
|
166
|
+
if path.is_symlink():
|
|
167
|
+
continue
|
|
168
|
+
try:
|
|
169
|
+
rows = list(_rows(path))
|
|
170
|
+
stamps = [_epoch(row.get('timestamp')) for row in rows]
|
|
171
|
+
stamps = [stamp for stamp in stamps if stamp is not None]
|
|
172
|
+
if stamps:
|
|
173
|
+
transcripts[path] = (min(stamps), max(stamps), rows)
|
|
174
|
+
except Exception as exc:
|
|
175
|
+
failures.append(exc)
|
|
176
|
+
return transcripts, failures
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def _next_session(path, stamp, index):
|
|
180
|
+
current = Path(path)
|
|
181
|
+
entry = index.get(current)
|
|
182
|
+
if not entry:
|
|
183
|
+
return None
|
|
184
|
+
end = entry[1]
|
|
185
|
+
choices = [(start, str(candidate), rows) for candidate, (start, _, rows) in index.items()
|
|
186
|
+
if candidate != current and start > end and start > stamp]
|
|
187
|
+
if not choices:
|
|
188
|
+
return None, None
|
|
189
|
+
_, candidate, rows = min(choices)
|
|
190
|
+
return candidate, rows
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def _session_ended(facade, sid, last_ts):
|
|
194
|
+
"""A successor counts only once the nudged session has ended."""
|
|
195
|
+
if last_ts is None:
|
|
196
|
+
return False
|
|
197
|
+
if datetime.now(timezone.utc).timestamp() - last_ts >= 1800:
|
|
198
|
+
return True
|
|
199
|
+
probe = getattr(facade, '_session_process_alive', None)
|
|
200
|
+
if callable(probe):
|
|
201
|
+
try:
|
|
202
|
+
return probe(sid) is False
|
|
203
|
+
except Exception:
|
|
204
|
+
pass
|
|
205
|
+
return False
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def resolve(facade, conn=None):
|
|
209
|
+
"""Update estimates on collection; requests may arrive after the action."""
|
|
210
|
+
owned = conn is None
|
|
211
|
+
try:
|
|
212
|
+
conn = conn or facade._init_trends_db()
|
|
213
|
+
try:
|
|
214
|
+
if getattr(conn, 'in_transaction', False):
|
|
215
|
+
_diagnostic(facade, RuntimeError('caller transaction open'))
|
|
216
|
+
return
|
|
217
|
+
_schema(conn)
|
|
218
|
+
conn.commit()
|
|
219
|
+
events = conn.execute('SELECT id,session_uuid,ts,context_tokens,transcript_path,savings_event_id FROM nudge_events').fetchall()
|
|
220
|
+
projects = {Path(path).parent for _, _, _, _, path, _ in events if path}
|
|
221
|
+
indexes = {}
|
|
222
|
+
for project in projects:
|
|
223
|
+
try:
|
|
224
|
+
transcripts, failures = _project_index(project)
|
|
225
|
+
except Exception as exc:
|
|
226
|
+
transcripts, failures = {}, [exc]
|
|
227
|
+
for failure in failures:
|
|
228
|
+
_diagnostic(facade, failure)
|
|
229
|
+
indexes[project] = transcripts
|
|
230
|
+
prepared = {}
|
|
231
|
+
claimed_sessions = set()
|
|
232
|
+
events.sort(key=lambda event: (_epoch(event[2]) or 0, event[0]), reverse=True)
|
|
233
|
+
for ident, sid, ts, before, path, event_id in events:
|
|
234
|
+
if not path:
|
|
235
|
+
continue
|
|
236
|
+
entry = indexes[Path(path).parent].get(Path(path))
|
|
237
|
+
if not entry:
|
|
238
|
+
continue
|
|
239
|
+
rows = entry[2]
|
|
240
|
+
status, action, requests = classify(rows, ts)
|
|
241
|
+
if status == 'pending':
|
|
242
|
+
next_path, next_rows = _next_session(path, _epoch(ts), indexes[Path(path).parent])
|
|
243
|
+
if next_rows and _session_ended(facade, sid, entry[1]):
|
|
244
|
+
status, action, requests = classify(rows, ts, next_rows)
|
|
245
|
+
if status == 'followed':
|
|
246
|
+
if next_path in claimed_sessions:
|
|
247
|
+
status, action, requests = 'ignored', None, []
|
|
248
|
+
else:
|
|
249
|
+
claimed_sessions.add(next_path)
|
|
250
|
+
prepared[ident] = status, action, requests
|
|
251
|
+
conn.execute('BEGIN IMMEDIATE')
|
|
252
|
+
claimed = set()
|
|
253
|
+
for ident, sid, ts, before, path, event_id in events:
|
|
254
|
+
try:
|
|
255
|
+
if ident not in prepared:
|
|
256
|
+
continue
|
|
257
|
+
status, action, requests = prepared[ident]
|
|
258
|
+
current = conn.execute('SELECT status,savings_event_id FROM nudge_events WHERE id=?', (ident,)).fetchone()
|
|
259
|
+
if current is None or current[0] != 'pending' or current[1] is not None:
|
|
260
|
+
continue
|
|
261
|
+
event_id = current[1]
|
|
262
|
+
cost = 0.0
|
|
263
|
+
tokens = 0
|
|
264
|
+
duplicate = (sid, action) in claimed
|
|
265
|
+
if action:
|
|
266
|
+
claimed.add((sid, action))
|
|
267
|
+
if status == 'followed' and requests and before and not duplicate:
|
|
268
|
+
after = _context(requests[0])
|
|
269
|
+
delta = max(0, int(before) - after)
|
|
270
|
+
for message in requests:
|
|
271
|
+
model = message.get('model')
|
|
272
|
+
if facade._is_priced_model(model):
|
|
273
|
+
cost += facade._get_model_cost(model, 0, 0, delta, 0)
|
|
274
|
+
tokens += delta
|
|
275
|
+
# Existing compaction credits take precedence for the same action.
|
|
276
|
+
try:
|
|
277
|
+
for table, kind in (('compression_events', 'feature'), ('savings_events', 'event_type')):
|
|
278
|
+
old = conn.execute(f"SELECT timestamp FROM {table} WHERE (session_uuid=? OR session_id=?) AND ({kind} LIKE '%compact%' OR {kind} IN ('quality_nudge','mod_clean','mod_clean_first'))" + (" AND verified=1" if table == 'compression_events' else " AND event_type != 'mod_compaction_cost'"), (sid, sid)).fetchall()
|
|
279
|
+
if any(abs((_epoch(t) or 0) - (_epoch(action) or 0)) <= 120 for (t,) in old):
|
|
280
|
+
cost = tokens = 0
|
|
281
|
+
except Exception as exc:
|
|
282
|
+
_diagnostic(facade, exc)
|
|
283
|
+
continue
|
|
284
|
+
if cost > 0:
|
|
285
|
+
cur = conn.execute('INSERT INTO savings_events(timestamp,event_type,tokens_saved,cost_saved_usd,session_id,session_uuid,detail,model,unjoinable) VALUES(?,?,?,?,?,?,?,?,?)',
|
|
286
|
+
(datetime.fromtimestamp(_epoch(action)).isoformat(), 'nudge_followed', tokens, cost, sid, sid, 'nudge_id=' + str(ident), None, 0))
|
|
287
|
+
event_id = cur.lastrowid
|
|
288
|
+
conn.execute('UPDATE nudge_events SET status=?,action_ts=?,savings_event_id=? WHERE id=?', (status, action, event_id, ident))
|
|
289
|
+
except (OSError, ValueError, TypeError, KeyError) as exc:
|
|
290
|
+
raise exc
|
|
291
|
+
conn.commit()
|
|
292
|
+
finally:
|
|
293
|
+
if owned:
|
|
294
|
+
conn.close()
|
|
295
|
+
except Exception as exc:
|
|
296
|
+
if conn is not None:
|
|
297
|
+
try:
|
|
298
|
+
conn.rollback()
|
|
299
|
+
except Exception:
|
|
300
|
+
pass
|
|
301
|
+
_diagnostic(facade, exc)
|
|
302
|
+
|
|
303
|
+
|
|
304
|
+
|
|
305
|
+
def weekly_counts(facade):
|
|
306
|
+
"""Read the shipped event schema for the last seven days."""
|
|
307
|
+
from datetime import timedelta
|
|
308
|
+
try:
|
|
309
|
+
conn = facade._open_trends_db_readonly(timeout=1.0)
|
|
310
|
+
except Exception:
|
|
311
|
+
import sqlite3
|
|
312
|
+
path = Path(facade.TRENDS_DB)
|
|
313
|
+
if not path.exists():
|
|
314
|
+
return {'followed': 0, 'total': 0}
|
|
315
|
+
conn = sqlite3.connect('file:' + str(path) + '?mode=ro', uri=True)
|
|
316
|
+
try:
|
|
317
|
+
if not conn.execute("SELECT 1 FROM sqlite_master WHERE type='table' AND name='nudge_events'").fetchone():
|
|
318
|
+
return {'followed': 0, 'total': 0}
|
|
319
|
+
cutoff = (datetime.now(timezone.utc) - timedelta(days=7)).timestamp()
|
|
320
|
+
rows = conn.execute('SELECT ts, status FROM nudge_events').fetchall()
|
|
321
|
+
recent = [status for ts, status in rows if (_epoch(ts) or 0) >= cutoff]
|
|
322
|
+
return {'followed': sum(status == 'followed' for status in recent), 'total': len(recent)}
|
|
323
|
+
finally:
|
|
324
|
+
conn.close()
|
|
325
|
+
|
|
326
|
+
def record_emitted(facade, sid, path, quality_data, fresh, compact, advisory):
|
|
327
|
+
try:
|
|
328
|
+
telemetry = facade._absolute_context_tokens(quality_data, sid) or {}
|
|
329
|
+
model = facade._resolve_session_model(sid)
|
|
330
|
+
for kind, message in (('fresh_session', fresh), ('compact_tip', compact), ('context_size', advisory)):
|
|
331
|
+
if message:
|
|
332
|
+
record(facade, sid, kind, telemetry.get('tokens'), model, path)
|
|
333
|
+
except Exception:
|
|
334
|
+
pass
|
|
@@ -239,6 +239,9 @@ def anchor_step(facade, budget_seconds=None, tier=None):
|
|
|
239
239
|
# State written before activity dating (or surviving an archive
|
|
240
240
|
# collision) was computed on session-date windows; rebuild it.
|
|
241
241
|
state = {}
|
|
242
|
+
window = facade._pretool_window()
|
|
243
|
+
if window and state.get("window") != list(window):
|
|
244
|
+
state = {}
|
|
242
245
|
if state.get("status") == "unavailable":
|
|
243
246
|
return "unavailable"
|
|
244
247
|
if tier is None:
|