@alexgreensh/token-optimizer 5.13.57 → 5.13.59
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/hooks.json +16 -16
- package/hooks/python-launcher.sh +10 -0
- package/hooks/stop_runner.py +27 -4
- package/hooks/windows-launcher.py +57 -3
- package/package.json +1 -1
- package/skills/fleet-auditor/scripts/shared.py +29 -1
- package/skills/token-optimizer/pricing/prices.json +13 -1
- package/skills/token-optimizer/scripts/codex_doctor.py +78 -1
- package/skills/token-optimizer/scripts/codex_install.py +379 -41
- package/skills/token-optimizer/scripts/codex_session.py +38 -8
- package/skills/token-optimizer/scripts/copilot_doctor.py +129 -6
- package/skills/token-optimizer/scripts/copilot_hook_bridge.py +62 -14
- package/skills/token-optimizer/scripts/copilot_install.py +56 -4
- package/skills/token-optimizer/scripts/detectors/cache_instability.py +18 -4
- package/skills/token-optimizer/scripts/deterministic_candidates.py +55 -15
- package/skills/token-optimizer/scripts/devin_source.py +1 -1
- package/skills/token-optimizer/scripts/hermes_doctor.py +177 -1
- package/skills/token-optimizer/scripts/hermes_hook_bridge.py +190 -0
- package/skills/token-optimizer/scripts/hermes_install.py +43 -0
- package/skills/token-optimizer/scripts/hermes_session.py +133 -0
- package/skills/token-optimizer/scripts/hermes_state.py +58 -0
- package/skills/token-optimizer/scripts/hermes_tool_hooks.py +291 -0
- package/skills/token-optimizer/scripts/measure.py +1302 -319
- package/skills/token-optimizer/scripts/plugin_env.py +18 -0
- package/skills/token-optimizer/scripts/recovery_output.py +15 -2
- package/skills/token-optimizer/scripts/refetch_fingerprint.py +36 -1
- package/skills/token-optimizer/scripts/runtime_env.py +5 -1
|
@@ -25,6 +25,7 @@ import argparse
|
|
|
25
25
|
import calendar
|
|
26
26
|
import json
|
|
27
27
|
import os
|
|
28
|
+
import re
|
|
28
29
|
import shutil
|
|
29
30
|
import sys
|
|
30
31
|
import time
|
|
@@ -126,6 +127,94 @@ def _home_checks() -> list:
|
|
|
126
127
|
return checks
|
|
127
128
|
|
|
128
129
|
|
|
130
|
+
# Copilot's hook loader is Rust (`[rust:hooks]` in its logs), whose regex engine has no
|
|
131
|
+
# lookaround or backreferences. Python's `re` accepts both, so they are flagged separately.
|
|
132
|
+
_RUST_REGEX_UNSUPPORTED = re.compile(r"\(\?<?[=!]|\\[1-9]")
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def _matcher_is_skipped(matcher) -> bool:
|
|
136
|
+
"""True when Copilot would skip a hook entry with this matcher."""
|
|
137
|
+
if not isinstance(matcher, str):
|
|
138
|
+
return True
|
|
139
|
+
if not matcher.strip():
|
|
140
|
+
return True # ^(?:)$ matches no tool name, so the hook never fires
|
|
141
|
+
if _RUST_REGEX_UNSUPPORTED.search(matcher):
|
|
142
|
+
return True
|
|
143
|
+
try:
|
|
144
|
+
re.compile(matcher)
|
|
145
|
+
except re.error:
|
|
146
|
+
return True
|
|
147
|
+
return False
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def _invalid_matcher_events(hooks) -> list:
|
|
151
|
+
"""Events with an entry whose `matcher` Copilot would reject or never match.
|
|
152
|
+
|
|
153
|
+
Copilot compiles `matcher` as the regex ^(?:PATTERN)$ and skips an entry
|
|
154
|
+
whose matcher is not a valid regex string, so an event listed in the file
|
|
155
|
+
can still never fire.
|
|
156
|
+
"""
|
|
157
|
+
bad = []
|
|
158
|
+
if not isinstance(hooks, dict):
|
|
159
|
+
return bad
|
|
160
|
+
for event in sorted(hooks):
|
|
161
|
+
entries = hooks[event]
|
|
162
|
+
if not isinstance(entries, list):
|
|
163
|
+
continue
|
|
164
|
+
for entry in entries:
|
|
165
|
+
if isinstance(entry, dict) and "matcher" in entry and _matcher_is_skipped(entry["matcher"]):
|
|
166
|
+
bad.append(event)
|
|
167
|
+
break
|
|
168
|
+
return bad
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def _required_payload_modules() -> tuple:
|
|
172
|
+
"""Every module the installer ships next to the bridge. A missing one can
|
|
173
|
+
silently disable the bridge (for example, no runtime_env means no data dir,
|
|
174
|
+
so the tally cleanup is skipped), so the payload check covers the full set."""
|
|
175
|
+
try:
|
|
176
|
+
from copilot_install import _PAYLOAD_MODULES # noqa: PLC0415
|
|
177
|
+
return tuple(_PAYLOAD_MODULES)
|
|
178
|
+
except Exception:
|
|
179
|
+
return ("copilot_hook_bridge.py", "codex_io.py", "bash_compress.py")
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def _measure_reachable(plugin_dir: Path) -> bool:
|
|
183
|
+
"""True when the installed bridge can resolve measure.py: a sibling copy, or
|
|
184
|
+
a `measure-path` locator naming a regular measure.py file."""
|
|
185
|
+
sibling = plugin_dir / "measure.py"
|
|
186
|
+
if sibling.is_file() and not sibling.is_symlink():
|
|
187
|
+
return True
|
|
188
|
+
try:
|
|
189
|
+
locator = plugin_dir / "measure-path"
|
|
190
|
+
if locator.is_file() and not locator.is_symlink():
|
|
191
|
+
target = Path(locator.read_text(encoding="utf-8").strip())
|
|
192
|
+
return target.is_file() and not target.is_symlink() and target.name == "measure.py"
|
|
193
|
+
except (OSError, ValueError):
|
|
194
|
+
pass
|
|
195
|
+
return False
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def _has_legacy_stop(hooks) -> bool:
|
|
199
|
+
"""True when the file wires Token Optimizer's bridge under the lowercase
|
|
200
|
+
`stop` key that earlier installs wrote. Copilot has no such event.
|
|
201
|
+
|
|
202
|
+
Only a `stop` entry that runs the Token Optimizer bridge counts, so a user's
|
|
203
|
+
own `stop` entries, and any other event name, are left alone.
|
|
204
|
+
"""
|
|
205
|
+
if not isinstance(hooks, dict):
|
|
206
|
+
return False
|
|
207
|
+
entries = hooks.get("stop")
|
|
208
|
+
if not isinstance(entries, list):
|
|
209
|
+
return False
|
|
210
|
+
for entry in entries:
|
|
211
|
+
if isinstance(entry, dict):
|
|
212
|
+
cmd = entry.get("bash") or entry.get("command") or ""
|
|
213
|
+
if isinstance(cmd, str) and "copilot_hook_bridge" in cmd:
|
|
214
|
+
return True
|
|
215
|
+
return False
|
|
216
|
+
|
|
217
|
+
|
|
129
218
|
def _hook_config_checks() -> list:
|
|
130
219
|
checks = []
|
|
131
220
|
hook_path = copilot_home() / "hooks" / "token-optimizer.json"
|
|
@@ -141,8 +230,35 @@ def _hook_config_checks() -> list:
|
|
|
141
230
|
return checks
|
|
142
231
|
try:
|
|
143
232
|
config = json.loads(hook_path.read_text(encoding="utf-8"))
|
|
144
|
-
|
|
145
|
-
|
|
233
|
+
hooks = config.get("hooks") if isinstance(config, dict) else None
|
|
234
|
+
if hooks is None and isinstance(config, dict):
|
|
235
|
+
hooks = {}
|
|
236
|
+
if not isinstance(hooks, dict):
|
|
237
|
+
raise ValueError("expected a JSON object with a `hooks` object")
|
|
238
|
+
events = sorted(hooks.keys())
|
|
239
|
+
bad = _invalid_matcher_events(hooks)
|
|
240
|
+
if bad:
|
|
241
|
+
checks.append(
|
|
242
|
+
_check(
|
|
243
|
+
"fail",
|
|
244
|
+
"TO hook config",
|
|
245
|
+
f"{hook_path}: `matcher` must be a regex string in {', '.join(bad)}; "
|
|
246
|
+
"Copilot skips those hooks.",
|
|
247
|
+
_hint("Re-run `python3 measure.py copilot-install` to rewrite it."),
|
|
248
|
+
)
|
|
249
|
+
)
|
|
250
|
+
else:
|
|
251
|
+
checks.append(_check("ok", "TO hook config", f"{hook_path} (events: {', '.join(events)})"))
|
|
252
|
+
if _has_legacy_stop(hooks):
|
|
253
|
+
checks.append(
|
|
254
|
+
_check(
|
|
255
|
+
"warn",
|
|
256
|
+
"TO session-end hook",
|
|
257
|
+
"The hook file wires Token Optimizer under a lowercase `stop` event. "
|
|
258
|
+
"Copilot has no such event, so the session-end rollup and cleanup never run.",
|
|
259
|
+
_hint("Re-run `python3 measure.py copilot-install` to switch it to sessionEnd."),
|
|
260
|
+
)
|
|
261
|
+
)
|
|
146
262
|
except (OSError, json.JSONDecodeError, ValueError) as exc:
|
|
147
263
|
checks.append(
|
|
148
264
|
_check(
|
|
@@ -157,10 +273,7 @@ def _hook_config_checks() -> list:
|
|
|
157
273
|
# tally + capability writes silently no-op (crash recovery dies).
|
|
158
274
|
plugin_dir = copilot_home() / "token-optimizer" / "plugin"
|
|
159
275
|
if plugin_dir.is_dir():
|
|
160
|
-
missing = [
|
|
161
|
-
m for m in ("copilot_hook_bridge.py", "codex_io.py", "bash_compress.py")
|
|
162
|
-
if not (plugin_dir / m).exists()
|
|
163
|
-
]
|
|
276
|
+
missing = [m for m in _required_payload_modules() if not (plugin_dir / m).exists()]
|
|
164
277
|
if missing:
|
|
165
278
|
checks.append(
|
|
166
279
|
_check(
|
|
@@ -172,6 +285,16 @@ def _hook_config_checks() -> list:
|
|
|
172
285
|
)
|
|
173
286
|
else:
|
|
174
287
|
checks.append(_check("ok", "hook payload", f"{plugin_dir} (complete)"))
|
|
288
|
+
if not _measure_reachable(plugin_dir):
|
|
289
|
+
checks.append(
|
|
290
|
+
_check(
|
|
291
|
+
"warn",
|
|
292
|
+
"session-end refresh",
|
|
293
|
+
"The installed bridge cannot find measure.py, so the session-end "
|
|
294
|
+
"rollup and dashboard refresh are paused.",
|
|
295
|
+
_hint("Re-run `python3 measure.py copilot-install` to rewrite the locator."),
|
|
296
|
+
)
|
|
297
|
+
)
|
|
175
298
|
return checks
|
|
176
299
|
|
|
177
300
|
|
|
@@ -7,7 +7,7 @@ Thin, fast, fail-safe entry point invoked by Copilot's hooks system
|
|
|
7
7
|
copilot_hook_bridge.py session-start
|
|
8
8
|
copilot_hook_bridge.py pre-tool-use
|
|
9
9
|
copilot_hook_bridge.py post-tool-use
|
|
10
|
-
copilot_hook_bridge.py
|
|
10
|
+
copilot_hook_bridge.py session-end
|
|
11
11
|
|
|
12
12
|
Contract notes (verified against github/copilot-cli as of v1.0.60, 2026-06-10):
|
|
13
13
|
|
|
@@ -601,11 +601,39 @@ def _events_growth_level(session_id):
|
|
|
601
601
|
return level
|
|
602
602
|
|
|
603
603
|
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
604
|
+
# The installer does NOT copy measure.py into the plugin dir (version-drift
|
|
605
|
+
# risk: nothing refreshes a plugin-dir copy on update). It writes a one-line
|
|
606
|
+
# "measure-path" locator next to this bridge naming the canonical measure.py.
|
|
607
|
+
# Resolution order: a sibling measure.py (dev/test checkout), then the locator.
|
|
608
|
+
# Same scheme as cursor_hook_bridge._locate_measure_py.
|
|
609
|
+
_MEASURE_LOCATOR = _SCRIPT_DIR / "measure-path"
|
|
610
|
+
|
|
611
|
+
|
|
612
|
+
def _locate_measure_py():
|
|
613
|
+
"""Return the path to measure.py, or None if not found (refresh paused).
|
|
614
|
+
|
|
615
|
+
The plugin dir is user-writable, so only a regular, non-symlinked file
|
|
616
|
+
named measure.py is accepted from the locator.
|
|
617
|
+
"""
|
|
618
|
+
sibling = _SCRIPT_DIR / "measure.py"
|
|
619
|
+
if sibling.is_file() and not sibling.is_symlink():
|
|
620
|
+
return sibling
|
|
621
|
+
try:
|
|
622
|
+
if _MEASURE_LOCATOR.is_file() and not _MEASURE_LOCATOR.is_symlink():
|
|
623
|
+
located = Path(_MEASURE_LOCATOR.read_text(encoding="utf-8").strip())
|
|
624
|
+
if (located.is_file() and not located.is_symlink()
|
|
625
|
+
and located.name == "measure.py"):
|
|
626
|
+
return located
|
|
627
|
+
except (OSError, ValueError):
|
|
628
|
+
pass
|
|
629
|
+
return None
|
|
630
|
+
|
|
631
|
+
|
|
632
|
+
def _spawn_session_end_refresh():
|
|
633
|
+
"""Detached rollup + dashboard refresh. A no-op when measure.py cannot be
|
|
634
|
+
located; cleanup of the session's tally and lock never depends on this."""
|
|
635
|
+
measure = _locate_measure_py()
|
|
636
|
+
if measure is None:
|
|
609
637
|
return
|
|
610
638
|
env = dict(os.environ)
|
|
611
639
|
env["TOKEN_OPTIMIZER_RUNTIME"] = "copilot"
|
|
@@ -625,11 +653,11 @@ def handle_stop(payload):
|
|
|
625
653
|
pass
|
|
626
654
|
else:
|
|
627
655
|
if _proc is None:
|
|
628
|
-
logger.warning("[copilot_hook_bridge]
|
|
629
|
-
#
|
|
630
|
-
#
|
|
631
|
-
#
|
|
632
|
-
#
|
|
656
|
+
logger.warning("[copilot_hook_bridge] handle_session_end spawn_detached returned None")
|
|
657
|
+
# Also refresh the dashboard on session end so a Copilot user sees current
|
|
658
|
+
# data without a manual open. Detached + TOKEN_OPTIMIZER_INTERACTIVE=1 so it
|
|
659
|
+
# runs UNBOUNDED off the hot path -- never blocks the CLI, never truncates
|
|
660
|
+
# on the 20s hook budget.
|
|
633
661
|
try:
|
|
634
662
|
spawn_detached(
|
|
635
663
|
[sys.executable, str(measure), "dashboard", "--quiet"],
|
|
@@ -639,6 +667,14 @@ def handle_stop(payload):
|
|
|
639
667
|
)
|
|
640
668
|
except (OSError, subprocess.SubprocessError):
|
|
641
669
|
pass
|
|
670
|
+
|
|
671
|
+
|
|
672
|
+
def handle_session_end(payload):
|
|
673
|
+
"""Session-exit work, wired to Copilot's sessionEnd event: fire-and-forget
|
|
674
|
+
rollup and dashboard refresh, then drop this session's in-flight tally and
|
|
675
|
+
lock. The cleanup runs even when measure.py cannot be located."""
|
|
676
|
+
fields = decode_payload(payload)
|
|
677
|
+
_spawn_session_end_refresh()
|
|
642
678
|
# Remove this session's in-flight tally: shutdown event is now authoritative.
|
|
643
679
|
# Also drop the published lease lock file so a fast sessionStart doesn't
|
|
644
680
|
# see a stale inflight-{sid}.lock from this session (candidate files age
|
|
@@ -657,7 +693,7 @@ def handle_stop(payload):
|
|
|
657
693
|
# candidate onto the now-free name and run concurrently, while the
|
|
658
694
|
# original holder -- which operates on its own candidate inode -- never
|
|
659
695
|
# notices it was displaced. Nothing in the Copilot hook contract
|
|
660
|
-
# guarantees
|
|
696
|
+
# guarantees sessionEnd is serialised after PostToolUse returns.
|
|
661
697
|
#
|
|
662
698
|
# So only remove the lock when it is provably unheld: take it
|
|
663
699
|
# non-blocking, and if that fails, leave it for the sessionStart sweep.
|
|
@@ -668,7 +704,12 @@ def handle_stop(payload):
|
|
|
668
704
|
except OSError:
|
|
669
705
|
pass
|
|
670
706
|
else:
|
|
671
|
-
|
|
707
|
+
# reclaim_released: a lease its owner already released is free to
|
|
708
|
+
# take at once (session end is a mutation of its own, not one of the
|
|
709
|
+
# herd the post-release reuse reservation absorbs). A lease still
|
|
710
|
+
# held is never taken, so a live PostToolUse critical section is
|
|
711
|
+
# left alone.
|
|
712
|
+
with lease_lock(lock_path, acquire_timeout=0, reclaim_released=True) as acquired:
|
|
672
713
|
if acquired:
|
|
673
714
|
try:
|
|
674
715
|
lock_path.unlink()
|
|
@@ -676,11 +717,18 @@ def handle_stop(payload):
|
|
|
676
717
|
pass
|
|
677
718
|
|
|
678
719
|
|
|
720
|
+
# Back-compat name for callers and tests that predate the sessionEnd wiring.
|
|
721
|
+
handle_stop = handle_session_end
|
|
722
|
+
|
|
723
|
+
|
|
679
724
|
_HANDLERS = {
|
|
680
725
|
"session-start": handle_session_start,
|
|
681
726
|
"pre-tool-use": handle_pre_tool_use,
|
|
682
727
|
"post-tool-use": handle_post_tool_use,
|
|
683
|
-
"
|
|
728
|
+
"session-end": handle_session_end,
|
|
729
|
+
# Legacy name written by earlier installs (under an event Copilot never
|
|
730
|
+
# fires). Kept so a manual `... stop` invocation still works.
|
|
731
|
+
"stop": handle_session_end,
|
|
684
732
|
}
|
|
685
733
|
|
|
686
734
|
|
|
@@ -61,7 +61,7 @@ _PAYLOAD_MODULES = (
|
|
|
61
61
|
"hermes_session.py",
|
|
62
62
|
# spawn_utils supplies spawn_detached — without it the bridge logs
|
|
63
63
|
# "spawn_utils import failed" on every hook and its degraded fallback does
|
|
64
|
-
# NOT detach, so
|
|
64
|
+
# NOT detach, so session-end spawns die with the hook. hook_runtime supplies
|
|
65
65
|
# lease_lock (tally RMW); utf8_io is enforced at startup. Cursor and Grok
|
|
66
66
|
# already ship all three.
|
|
67
67
|
"spawn_utils.py",
|
|
@@ -73,6 +73,13 @@ _PAYLOAD_MODULES = (
|
|
|
73
73
|
)
|
|
74
74
|
|
|
75
75
|
|
|
76
|
+
# One-line locator written next to the bridge, naming the canonical measure.py
|
|
77
|
+
# in the checkout. measure.py is NOT copied into the plugin dir (version drift:
|
|
78
|
+
# nothing refreshes a plugin-dir copy on update). The bridge's session-end
|
|
79
|
+
# rollup/dashboard spawns resolve it through this locator.
|
|
80
|
+
_MEASURE_LOCATOR_NAME = "measure-path"
|
|
81
|
+
|
|
82
|
+
|
|
76
83
|
def _plugin_dir(root: Path) -> Path:
|
|
77
84
|
return root / "token-optimizer" / "plugin"
|
|
78
85
|
|
|
@@ -141,6 +148,24 @@ def _resolve_safe_python() -> str:
|
|
|
141
148
|
)
|
|
142
149
|
|
|
143
150
|
|
|
151
|
+
# PowerShell ends a single-quoted string at any of these, so each is doubled.
|
|
152
|
+
_PS_SINGLE_QUOTES = "'\u2018\u2019\u201a\u201b"
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def _ps_single_quote(value: str) -> str:
|
|
156
|
+
"""``value`` as a PowerShell single-quoted literal: nothing inside expands
|
|
157
|
+
($, backtick, %, ! are all literal there); quote characters are doubled."""
|
|
158
|
+
return "'" + "".join(ch * 2 if ch in _PS_SINGLE_QUOTES else ch for ch in value) + "'"
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def _powershell_hook_command(py: str, bridge: str, event: str) -> str:
|
|
162
|
+
"""The Windows form of the hook: set the runtime for the child, then call
|
|
163
|
+
the interpreter by literal path with the call operator. The hook payload
|
|
164
|
+
on stdin is inherited by the native child."""
|
|
165
|
+
return (f"$env:TOKEN_OPTIMIZER_RUNTIME='copilot'; "
|
|
166
|
+
f"& {_ps_single_quote(py)} {_ps_single_quote(bridge)} {event}")
|
|
167
|
+
|
|
168
|
+
|
|
144
169
|
def _hook_config(bridge_path: Path) -> dict:
|
|
145
170
|
"""The hooks file Copilot loads. Format per the official hooks reference:
|
|
146
171
|
{"version": 1, "hooks": {event: [{"type": "command", "bash": ...}]}}.
|
|
@@ -154,16 +179,25 @@ def _hook_config(bridge_path: Path) -> dict:
|
|
|
154
179
|
bridge_q = shlex.quote(str(bridge_path))
|
|
155
180
|
|
|
156
181
|
def cmd(event: str) -> dict:
|
|
157
|
-
|
|
182
|
+
entry = {
|
|
158
183
|
"type": "command",
|
|
159
184
|
"bash": f"TOKEN_OPTIMIZER_RUNTIME=copilot {py_q} {bridge_q} {event}",
|
|
160
185
|
"timeoutSec": HOOK_TIMEOUT_SEC,
|
|
161
186
|
}
|
|
187
|
+
if sys.platform == "win32":
|
|
188
|
+
# Copilot CLI runs the `powershell` field on Windows and skips a
|
|
189
|
+
# hook that only has `bash`, so without this no Token Optimizer
|
|
190
|
+
# hook ever fired on native Windows.
|
|
191
|
+
entry["powershell"] = _powershell_hook_command(py, str(bridge_path), event)
|
|
192
|
+
return entry
|
|
162
193
|
|
|
163
194
|
pre = cmd("pre-tool-use")
|
|
164
195
|
# Only the bash tool is rewritten; the matcher keeps every other tool
|
|
165
196
|
# call out of the bridge's hot path entirely.
|
|
166
|
-
|
|
197
|
+
# Copilot reads `matcher` as a regex string tested against the tool name
|
|
198
|
+
# (anchored as ^(?:PATTERN)$). An object is rejected and the whole hook
|
|
199
|
+
# entry is skipped.
|
|
200
|
+
pre["matcher"] = "bash"
|
|
167
201
|
|
|
168
202
|
return {
|
|
169
203
|
"version": 1,
|
|
@@ -171,7 +205,9 @@ def _hook_config(bridge_path: Path) -> dict:
|
|
|
171
205
|
"sessionStart": [cmd("session-start")],
|
|
172
206
|
"preToolUse": [pre],
|
|
173
207
|
"postToolUse": [cmd("post-tool-use")],
|
|
174
|
-
|
|
208
|
+
# Copilot's end-of-session event. The lowercase `stop` event is not
|
|
209
|
+
# a Copilot event name, so a hook under it never fires.
|
|
210
|
+
"sessionEnd": [cmd("session-end")],
|
|
175
211
|
},
|
|
176
212
|
}
|
|
177
213
|
|
|
@@ -213,6 +249,22 @@ def install(*, dry_run: bool = False, home: Path = None) -> dict:
|
|
|
213
249
|
f"{actions['skipped']} — refusing to wire hooks against an incomplete bridge."
|
|
214
250
|
)
|
|
215
251
|
|
|
252
|
+
measure_py = _SCRIPT_DIR / "measure.py"
|
|
253
|
+
if measure_py.is_file():
|
|
254
|
+
actions["measure_locator"] = str(measure_py)
|
|
255
|
+
if not dry_run:
|
|
256
|
+
try:
|
|
257
|
+
locator = plugin_dir / _MEASURE_LOCATOR_NAME
|
|
258
|
+
tmp = locator.with_name(f".{locator.name}.tmp")
|
|
259
|
+
tmp.write_text(f"{measure_py}\n", encoding="utf-8")
|
|
260
|
+
os.replace(tmp, locator) # swaps a symlink, never follows it
|
|
261
|
+
except OSError as exc:
|
|
262
|
+
try:
|
|
263
|
+
tmp.unlink()
|
|
264
|
+
except OSError:
|
|
265
|
+
pass
|
|
266
|
+
raise RuntimeError(f"failed writing measure-path locator: {exc}") from exc
|
|
267
|
+
|
|
216
268
|
hook_path = hooks_dir / HOOK_FILE_NAME
|
|
217
269
|
config = _hook_config(plugin_dir / "copilot_hook_bridge.py")
|
|
218
270
|
if not dry_run:
|
|
@@ -88,7 +88,8 @@ def _state_dir():
|
|
|
88
88
|
-- this detector WRITES state, so a foreign
|
|
89
89
|
plugin's CLAUDE_PLUGIN_DATA sharing the same shared plugins/data root must
|
|
90
90
|
never redirect that write into another plugin's directory, unlike the
|
|
91
|
-
pre-fix raw env read this duplicated); else
|
|
91
|
+
pre-fix raw env read this duplicated); else <claude_home()>/token-optimizer/data
|
|
92
|
+
(CLAUDE_CONFIG_DIR when set and valid, else ~/.claude).
|
|
92
93
|
Returns None only if HOME itself is unresolvable, in which case the
|
|
93
94
|
snapshot diff is skipped (no finding, no crash).
|
|
94
95
|
"""
|
|
@@ -103,8 +104,11 @@ def _state_dir():
|
|
|
103
104
|
if plugin_data is not None:
|
|
104
105
|
return plugin_data / "data"
|
|
105
106
|
try:
|
|
106
|
-
|
|
107
|
-
|
|
107
|
+
# claude_home() honors CLAUDE_CONFIG_DIR, so a relocated Claude config
|
|
108
|
+
# keeps this detector's state beside the rest of Token Optimizer's.
|
|
109
|
+
from runtime_env import claude_home
|
|
110
|
+
return claude_home() / "token-optimizer" / "data"
|
|
111
|
+
except (ImportError, RuntimeError, OSError):
|
|
108
112
|
return None
|
|
109
113
|
|
|
110
114
|
|
|
@@ -358,12 +362,22 @@ def _process_prefix_dirs(cwd):
|
|
|
358
362
|
"""Return the ordered list of process-library prefix directories to scan."""
|
|
359
363
|
cwd_path = Path(cwd)
|
|
360
364
|
home = Path.home()
|
|
361
|
-
|
|
365
|
+
dirs = [
|
|
362
366
|
cwd_path / ".a5c" / "processes",
|
|
363
367
|
cwd_path / ".claude" / "processes",
|
|
364
368
|
home / ".a5c" / "processes",
|
|
365
369
|
home / ".claude" / "processes",
|
|
366
370
|
]
|
|
371
|
+
# A relocated Claude config (CLAUDE_CONFIG_DIR) keeps its user-level
|
|
372
|
+
# processes/ there; scan it too, without dropping the ~/.claude default.
|
|
373
|
+
try:
|
|
374
|
+
from runtime_env import claude_home
|
|
375
|
+
config_processes = claude_home() / "processes"
|
|
376
|
+
if config_processes not in dirs:
|
|
377
|
+
dirs.append(config_processes)
|
|
378
|
+
except (ImportError, RuntimeError, OSError):
|
|
379
|
+
pass
|
|
380
|
+
return dirs
|
|
367
381
|
|
|
368
382
|
|
|
369
383
|
def _scan_process_prefixes(cwd):
|
|
@@ -32,7 +32,10 @@ An inline script (``python3 - <<'EOF'``, ``python3 -c``, ``bash -c``, ``node -e`
|
|
|
32
32
|
differs: the call key carries a fingerprint of the redacted, literal-blanked body.
|
|
33
33
|
|
|
34
34
|
Pricing is injected (``price_fn``) so this module stays free of measure.py and the
|
|
35
|
-
numbers come from the same rate cards as every other dollar figure in the tool.
|
|
35
|
+
numbers come from the same rate cards as every other dollar figure in the tool. A
|
|
36
|
+
turn whose usage carries advisor iterations is split into billed parts by the
|
|
37
|
+
injected ``split_usage`` (measure.py's ``_billed_usage_parts``), and each part is
|
|
38
|
+
priced at its own model, exactly as every other per-turn dollar figure is.
|
|
36
39
|
"""
|
|
37
40
|
|
|
38
41
|
from __future__ import annotations
|
|
@@ -51,7 +54,8 @@ from credential_patterns import CommandMarks, scrub_command_syntax
|
|
|
51
54
|
# Part of the cache key. Bump when the SHAPE of stored examples changes, so a cache
|
|
52
55
|
# written by an older algorithm (possibly holding an example the newer scrubbers would
|
|
53
56
|
# have blanked) is never served again. 3: command-shape secret scrubbers (review F4).
|
|
54
|
-
|
|
57
|
+
# 4: advisor turns priced per part (a cached total priced every turn at one model).
|
|
58
|
+
ALGO_VERSION = 4
|
|
55
59
|
BASIS = "measured on your transcripts"
|
|
56
60
|
USED_NOT_SAVED_NOTE = "Moving a step to code removes those turns; the saving is at most this much."
|
|
57
61
|
PROGRESS_MIN_INTERVAL_S = 2.0
|
|
@@ -416,11 +420,13 @@ class Call:
|
|
|
416
420
|
|
|
417
421
|
|
|
418
422
|
class Turn:
|
|
419
|
-
__slots__ = ("fresh", "cr", "cc", "cc1h", "cc5m", "out", "model", "reply_chars", "ut")
|
|
423
|
+
__slots__ = ("fresh", "cr", "cc", "cc1h", "cc5m", "out", "model", "reply_chars", "ut", "usage")
|
|
420
424
|
|
|
421
425
|
def __init__(self, ut):
|
|
422
426
|
self.fresh = self.cr = self.cc = self.cc1h = self.cc5m = self.out = 0
|
|
423
427
|
self.model = "unknown"
|
|
428
|
+
# Raw usage, kept only when it carries advisor iterations (priced per part).
|
|
429
|
+
self.usage = None
|
|
424
430
|
self.reply_chars = 0
|
|
425
431
|
self.ut = ut
|
|
426
432
|
|
|
@@ -726,6 +732,8 @@ def extract_claude(path: Path | str, keys: _KeyMaker, seen_ids: set,
|
|
|
726
732
|
turn.cc = max(turn.cc, cc)
|
|
727
733
|
turn.cc1h = max(turn.cc1h, cc1)
|
|
728
734
|
turn.cc5m = max(turn.cc5m, cc5)
|
|
735
|
+
if _has_advisor_iterations(usage):
|
|
736
|
+
turn.usage = usage
|
|
729
737
|
model = msg.get("model")
|
|
730
738
|
if isinstance(model, str) and model and model != "<synthetic>":
|
|
731
739
|
turn.model = model
|
|
@@ -1201,23 +1209,53 @@ def detect_check_turns(traces: list[Trace]) -> list[_Cand]:
|
|
|
1201
1209
|
# ---------------------------------------------------------------------------
|
|
1202
1210
|
|
|
1203
1211
|
PriceFn = Callable[[str, int, int, int, int, int, int], "float | None"]
|
|
1212
|
+
# (executor model, raw usage) -> [(price_model, {"inp","out","cr","cc","cc_1h","cc_5m"}), ...]
|
|
1213
|
+
SplitFn = Callable[[str, dict], list]
|
|
1204
1214
|
|
|
1205
1215
|
|
|
1206
|
-
def
|
|
1216
|
+
def _has_advisor_iterations(usage: Any) -> bool:
|
|
1217
|
+
its = usage.get("iterations") if isinstance(usage, dict) else None
|
|
1218
|
+
return isinstance(its, list) and any(
|
|
1219
|
+
isinstance(i, dict) and i.get("type") == "advisor_message" for i in its)
|
|
1220
|
+
|
|
1221
|
+
|
|
1222
|
+
def _turn_parts(t: Turn, split: SplitFn | None) -> list[tuple[str, tuple[int, int, int, int, int, int]]]:
|
|
1223
|
+
"""Billed parts of one turn as (model, (fresh, out, cr, cc, cc1h, cc5m))."""
|
|
1224
|
+
if t.usage is not None and split is not None:
|
|
1225
|
+
try:
|
|
1226
|
+
parts = split(t.model, t.usage)
|
|
1227
|
+
except Exception:
|
|
1228
|
+
parts = None
|
|
1229
|
+
if parts:
|
|
1230
|
+
return [(pm, (int(b.get("inp", 0)), int(b.get("out", 0)), int(b.get("cr", 0)),
|
|
1231
|
+
int(b.get("cc", 0)), int(b.get("cc_1h", 0)), int(b.get("cc_5m", 0))))
|
|
1232
|
+
for pm, b in parts]
|
|
1233
|
+
return [(t.model, (t.fresh, t.out, t.cr, t.cc, t.cc1h, t.cc5m))]
|
|
1234
|
+
|
|
1235
|
+
|
|
1236
|
+
def _price_turns(traces: list[Trace], turns: Iterable[tuple[int, int]], price: PriceFn,
|
|
1237
|
+
split: SplitFn | None = None) -> dict[str, Any]:
|
|
1207
1238
|
fresh = cr = cc = out = 0
|
|
1208
1239
|
cost = 0.0
|
|
1209
1240
|
priced = unpriced = 0
|
|
1210
1241
|
for si, ti in turns:
|
|
1211
1242
|
t = traces[si].turns[ti]
|
|
1212
|
-
|
|
1213
|
-
|
|
1214
|
-
|
|
1215
|
-
|
|
1216
|
-
|
|
1217
|
-
|
|
1243
|
+
turn_cost = 0.0
|
|
1244
|
+
turn_unpriced = False
|
|
1245
|
+
for pm, (p_fresh, p_out, p_cr, p_cc, p_1h, p_5m) in _turn_parts(t, split):
|
|
1246
|
+
fresh += p_fresh
|
|
1247
|
+
cr += p_cr
|
|
1248
|
+
cc += p_cc
|
|
1249
|
+
out += p_out
|
|
1250
|
+
c = price(pm, p_fresh, p_out, p_cr, p_cc, p_1h, p_5m)
|
|
1251
|
+
if c is None or (c == 0 and (p_fresh or p_cr or p_cc or p_out)):
|
|
1252
|
+
turn_unpriced = True
|
|
1253
|
+
else:
|
|
1254
|
+
turn_cost += c
|
|
1255
|
+
if turn_unpriced:
|
|
1218
1256
|
unpriced += 1
|
|
1219
1257
|
else:
|
|
1220
|
-
cost +=
|
|
1258
|
+
cost += turn_cost
|
|
1221
1259
|
priced += 1
|
|
1222
1260
|
input_tokens = fresh + cr + cc
|
|
1223
1261
|
return {
|
|
@@ -1242,7 +1280,8 @@ def _finish_example(text: str, redact: Redactor) -> str:
|
|
|
1242
1280
|
|
|
1243
1281
|
|
|
1244
1282
|
def analyse(traces: list[Trace], price: PriceFn, redact: Redactor,
|
|
1245
|
-
deadline: float | None = None
|
|
1283
|
+
deadline: float | None = None,
|
|
1284
|
+
split: SplitFn | None = None) -> tuple[list[dict], dict[str, Any], bool]:
|
|
1246
1285
|
"""Run all detectors. Returns (candidates, union totals, partial)."""
|
|
1247
1286
|
cands = detect_check_turns(traces) + detect_polling(traces) + detect_subagents(traces)
|
|
1248
1287
|
partial = False
|
|
@@ -1254,7 +1293,7 @@ def analyse(traces: list[Trace], price: PriceFn, redact: Redactor,
|
|
|
1254
1293
|
partial = True
|
|
1255
1294
|
scored = []
|
|
1256
1295
|
for c in cands:
|
|
1257
|
-
stats = _price_turns(traces, c.turns, price)
|
|
1296
|
+
stats = _price_turns(traces, c.turns, price, split)
|
|
1258
1297
|
scored.append((stats["total_tokens"], stats["cost_usd"], c, stats))
|
|
1259
1298
|
scored.sort(key=lambda r: (-r[0], -r[1], -r[2].times))
|
|
1260
1299
|
top = scored[:MAX_CANDIDATES]
|
|
@@ -1278,7 +1317,7 @@ def analyse(traces: list[Trace], price: PriceFn, redact: Redactor,
|
|
|
1278
1317
|
if c.kind == "templated_subagent":
|
|
1279
1318
|
entry["tokens_scope"] = "launching turns only; subagent transcripts are not attributed"
|
|
1280
1319
|
out.append(entry)
|
|
1281
|
-
totals = _price_turns(traces, union, price)
|
|
1320
|
+
totals = _price_turns(traces, union, price, split)
|
|
1282
1321
|
return out, totals, partial
|
|
1283
1322
|
|
|
1284
1323
|
|
|
@@ -1379,6 +1418,7 @@ def run(
|
|
|
1379
1418
|
use_cache: bool = True,
|
|
1380
1419
|
redact: Redactor | None = None,
|
|
1381
1420
|
progress: Callable[[str], None] | None = None,
|
|
1421
|
+
split_usage: SplitFn | None = None,
|
|
1382
1422
|
) -> dict[str, Any]:
|
|
1383
1423
|
"""Scan ``files`` (newest first) and return the deterministic_candidates block.
|
|
1384
1424
|
|
|
@@ -1436,7 +1476,7 @@ def run(
|
|
|
1436
1476
|
traces.append(tr)
|
|
1437
1477
|
if len(files) > len(considered):
|
|
1438
1478
|
base["sessions_not_scanned_cap"] = len(files) - len(considered)
|
|
1439
|
-
cands, totals, a_partial = analyse(traces, price, redact, total_deadline)
|
|
1479
|
+
cands, totals, a_partial = analyse(traces, price, redact, total_deadline, split_usage)
|
|
1440
1480
|
partial = partial or a_partial
|
|
1441
1481
|
base.update(
|
|
1442
1482
|
status="ok" if cands else "no_data",
|
|
@@ -30,7 +30,7 @@ REPO_MODULES = frozenset((
|
|
|
30
30
|
'devin_compress', 'devin_doctor', 'devin_hooks', 'devin_install', 'devin_source', 'devin_state',
|
|
31
31
|
'devin_verify', 'grok_doctor', 'grok_hook_bridge', 'grok_install', 'grok_session',
|
|
32
32
|
'grok_state', 'hermes_doctor', 'hermes_hook_bridge', 'hermes_install', 'hermes_session',
|
|
33
|
-
'hermes_state', 'hook_io', 'hook_runtime', 'injection', 'install_reconcile', 'measure',
|
|
33
|
+
'hermes_state', 'hermes_tool_hooks', 'hook_io', 'hook_runtime', 'injection', 'install_reconcile', 'measure',
|
|
34
34
|
'outline', 'pipeline_analyzer', 'plugin_env', 'py_trust', 'quality_cache_gate',
|
|
35
35
|
'read_cache', 'recovery_output', 'refetch_fingerprint', 'refetch_guard', 'routing_advisor',
|
|
36
36
|
'runtime_env', 'session_store', 'spawn_utils', 'structure_map', 'structure_map_ts',
|