@alexgreensh/token-optimizer 5.13.50 → 5.13.51
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/module_runner.py +303 -4
- package/hooks/run.py +16 -4
- package/package.json +1 -1
- package/skills/fleet-auditor/SKILL.md +13 -14
- package/skills/fleet-auditor/scripts/fleet.py +22 -1
- package/skills/token-coach/SKILL.md +12 -0
- package/skills/token-dashboard/SKILL.md +27 -6
- package/skills/token-optimizer/scripts/antigravity_install.py +3 -0
- package/skills/token-optimizer/scripts/cloud_kit.py +26 -6
- package/skills/token-optimizer/scripts/copilot_install.py +11 -0
- package/skills/token-optimizer/scripts/cursor_install.py +3 -0
- package/skills/token-optimizer/scripts/grok_install.py +3 -0
- package/skills/token-optimizer/scripts/hook_runtime.py +4 -1
- package/skills/token-optimizer/scripts/measure.py +910 -118
- package/skills/token-optimizer/scripts/runtime_env.py +30 -0
|
@@ -806,8 +806,13 @@ class BaseAdapter:
|
|
|
806
806
|
|
|
807
807
|
Returns (runs, errors) where errors is a list of non-fatal error messages.
|
|
808
808
|
If conn is provided, skips already-collected runs.
|
|
809
|
+
|
|
810
|
+
The default is for adapters that can detect a system but not read its
|
|
811
|
+
runs yet. It says so: a bare ([], []) printed "0 scanned" for a system
|
|
812
|
+
detect() had just reported as installed, the silent-zero of #149.
|
|
809
813
|
"""
|
|
810
|
-
return [], [
|
|
814
|
+
return [], [f"{self.display_name} fleet collection is not implemented yet, "
|
|
815
|
+
f"so its runs are not counted here (0 is not a measurement)."]
|
|
811
816
|
|
|
812
817
|
def parse_config(self) -> dict:
|
|
813
818
|
"""Parse system configuration for Tier 1 waste analysis.
|
|
@@ -1529,6 +1534,19 @@ ADAPTER_REGISTRY: list[type[BaseAdapter]] = [
|
|
|
1529
1534
|
]
|
|
1530
1535
|
|
|
1531
1536
|
|
|
1537
|
+
def _require_known_system(target_system):
|
|
1538
|
+
"""Exit 2 on a --system no adapter answers to. It used to filter every
|
|
1539
|
+
adapter out and print "0 new runs collected", a silent zero (#149 class)
|
|
1540
|
+
for a typo such as --system claude-code."""
|
|
1541
|
+
if target_system is None:
|
|
1542
|
+
return
|
|
1543
|
+
known = [cls.name for cls in ADAPTER_REGISTRY]
|
|
1544
|
+
if target_system not in known:
|
|
1545
|
+
print(f" Unknown --system {target_system!r}. Known systems: {', '.join(known)}.",
|
|
1546
|
+
file=sys.stderr)
|
|
1547
|
+
sys.exit(2)
|
|
1548
|
+
|
|
1549
|
+
|
|
1532
1550
|
# ===================================================================
|
|
1533
1551
|
# WASTE PATTERN DETECTORS
|
|
1534
1552
|
# ===================================================================
|
|
@@ -2139,6 +2157,7 @@ def cmd_scan(args: list[str]):
|
|
|
2139
2157
|
pass
|
|
2140
2158
|
elif a == "--system" and i + 1 < len(args):
|
|
2141
2159
|
target_system = args[i + 1]
|
|
2160
|
+
_require_known_system(target_system)
|
|
2142
2161
|
|
|
2143
2162
|
since = datetime.now(timezone.utc) - timedelta(days=days)
|
|
2144
2163
|
conn = _init_fleet_db()
|
|
@@ -2238,6 +2257,7 @@ def cmd_audit(args: list[str]):
|
|
|
2238
2257
|
pass
|
|
2239
2258
|
elif a == "--system" and i + 1 < len(args):
|
|
2240
2259
|
target_system = args[i + 1]
|
|
2260
|
+
_require_known_system(target_system)
|
|
2241
2261
|
|
|
2242
2262
|
# First, ensure we have data
|
|
2243
2263
|
if not FLEET_DB.exists():
|
|
@@ -2390,6 +2410,7 @@ def cmd_report(args: list[str]):
|
|
|
2390
2410
|
pass
|
|
2391
2411
|
elif a == "--system" and i + 1 < len(args):
|
|
2392
2412
|
target_system = args[i + 1]
|
|
2413
|
+
_require_known_system(target_system)
|
|
2393
2414
|
|
|
2394
2415
|
if not FLEET_DB.exists():
|
|
2395
2416
|
print(" No fleet.db found. Run 'fleet.py scan' first.")
|
|
@@ -22,6 +22,18 @@ if [ -z "$RUNTIME" ]; then
|
|
|
22
22
|
RUNTIME="opencode"
|
|
23
23
|
elif [ -n "$CODEX_HOME" ]; then
|
|
24
24
|
RUNTIME="codex"
|
|
25
|
+
# Explicit config-dir env of another harness: same tier as Python's
|
|
26
|
+
# detect_runtime() (above CLAUDECODE, which every Claude Code child inherits).
|
|
27
|
+
elif [ -n "$HERMES_HOME" ]; then
|
|
28
|
+
RUNTIME="hermes"
|
|
29
|
+
elif [ -n "$COPILOT_HOME" ] || [ -n "$TOKEN_OPTIMIZER_COPILOT_HOME" ]; then
|
|
30
|
+
RUNTIME="copilot"
|
|
31
|
+
elif [ -n "$TOKEN_OPTIMIZER_CURSOR_HOME" ]; then
|
|
32
|
+
RUNTIME="cursor"
|
|
33
|
+
elif [ -n "$TOKEN_OPTIMIZER_ANTIGRAVITY_HOME" ]; then
|
|
34
|
+
RUNTIME="antigravity"
|
|
35
|
+
elif [ -n "$GROK_HOME" ] || [ -n "$TOKEN_OPTIMIZER_GROK_HOME" ]; then
|
|
36
|
+
RUNTIME="grok"
|
|
25
37
|
elif [ -n "$CLAUDECODE" ] || [ -n "$CLAUDE_CODE_ENTRYPOINT" ] || [ -n "$CLAUDE_CODE_SESSION_ID" ]; then
|
|
26
38
|
RUNTIME="claude"
|
|
27
39
|
elif [ -d "$HOME/.config/opencode" ] && [ ! -d "$HOME/.codex" ]; then
|
|
@@ -1,12 +1,11 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: token-dashboard
|
|
3
|
-
description:
|
|
4
|
-
disable-model-invocation: true
|
|
3
|
+
description: Answers what a past session cost ("the Navina session yesterday", a session id) with a priced number, and opens the Token Optimizer dashboard when asked to see it.
|
|
5
4
|
---
|
|
6
5
|
|
|
7
6
|
# Token Optimizer Dashboard
|
|
8
7
|
|
|
9
|
-
|
|
8
|
+
Answers what a session cost from the user's own words, and opens an up-to-date dashboard of context usage, quality, session history and skills. Open the dashboard only when the user asks to see it; a cost question never opens a browser.
|
|
10
9
|
|
|
11
10
|
## Instructions
|
|
12
11
|
|
|
@@ -20,6 +19,18 @@ if [ -z "$RUNTIME" ]; then
|
|
|
20
19
|
RUNTIME="opencode"
|
|
21
20
|
elif [ -n "$CODEX_HOME" ]; then
|
|
22
21
|
RUNTIME="codex"
|
|
22
|
+
# Explicit config-dir env of another harness: same tier as Python's
|
|
23
|
+
# detect_runtime() (above CLAUDECODE, which every Claude Code child inherits).
|
|
24
|
+
elif [ -n "$HERMES_HOME" ]; then
|
|
25
|
+
RUNTIME="hermes"
|
|
26
|
+
elif [ -n "$COPILOT_HOME" ] || [ -n "$TOKEN_OPTIMIZER_COPILOT_HOME" ]; then
|
|
27
|
+
RUNTIME="copilot"
|
|
28
|
+
elif [ -n "$TOKEN_OPTIMIZER_CURSOR_HOME" ]; then
|
|
29
|
+
RUNTIME="cursor"
|
|
30
|
+
elif [ -n "$TOKEN_OPTIMIZER_ANTIGRAVITY_HOME" ]; then
|
|
31
|
+
RUNTIME="antigravity"
|
|
32
|
+
elif [ -n "$GROK_HOME" ] || [ -n "$TOKEN_OPTIMIZER_GROK_HOME" ]; then
|
|
33
|
+
RUNTIME="grok"
|
|
23
34
|
elif [ -n "$CLAUDECODE" ] || [ -n "$CLAUDE_CODE_ENTRYPOINT" ] || [ -n "$CLAUDE_CODE_SESSION_ID" ]; then
|
|
24
35
|
RUNTIME="claude"
|
|
25
36
|
elif [ -d "$HOME/.config/opencode" ] && [ ! -d "$HOME/.codex" ]; then
|
|
@@ -51,7 +62,17 @@ if [ -z "$MEASURE_PY" ]; then echo "[Error] measure.py not found. Is Token Optim
|
|
|
51
62
|
export TOKEN_OPTIMIZER_RUNTIME="$RUNTIME"
|
|
52
63
|
```
|
|
53
64
|
|
|
54
|
-
2. **
|
|
65
|
+
2. **A cost question** ("what did the Navina session yesterday cost?", "how much were my TR sync sessions?", "cost of session <id>"): run this instead of steps 3-4.
|
|
66
|
+
```bash
|
|
67
|
+
python3 "$MEASURE_PY" session-cost <the user's words> --json
|
|
68
|
+
```
|
|
69
|
+
- Pass the user's own words (`navina yesterday`, `tr sync`, an id or its first 8 characters). Names match topic, slug and project, case-insensitively, and all of them must match; `today`, `yesterday` and `YYYY-MM-DD` set the day. Add `--days N` for "this week" (default 30), `--limit N` to list more.
|
|
70
|
+
- Answer from `sessions[]`: date, topic, `cost_usd.total`, the main-thread and subagent split when subagents ran, `cost_usd.on_date` when a day was asked and the session ran over several days, and `partial_reason` when set. Several matches: give `total_cost_usd` and list them, asking which one only when it changes the answer.
|
|
71
|
+
- State `basis` in one line: API list prices, so on a subscription it is what the work would have cost, not a bill.
|
|
72
|
+
- No match: say so, show `closest[]`, and pass on `note` (a session is collected when it ends).
|
|
73
|
+
- Never query trends.db or price tokens yourself: this is the dashboard's own number, read without writing.
|
|
74
|
+
|
|
75
|
+
3. **Collect and open**:
|
|
55
76
|
```bash
|
|
56
77
|
# TOKEN_OPTIMIZER_INTERACTIVE=1 marks this as a user-initiated open, so the 20s
|
|
57
78
|
# hook budget does not cut off a heavy rebuild on a large history. The user is
|
|
@@ -62,11 +83,11 @@ TOKEN_OPTIMIZER_INTERACTIVE=1 python3 "$MEASURE_PY" collect --quiet && \
|
|
|
62
83
|
|
|
63
84
|
This collects the latest session data into the trends database, regenerates the dashboard HTML, and opens it in your default browser.
|
|
64
85
|
|
|
65
|
-
|
|
86
|
+
4. **Tell the user** the dashboard is open. Probe the daemon before mentioning any URL:
|
|
66
87
|
- Probe daemon: `python3 "$MEASURE_PY" daemon-status 2>/dev/null`
|
|
67
88
|
- If DAEMON_RUNNING: lead with `URL: http://localhost:24842/token-optimizer` (bookmarkable, auto-updates), then mention the file fallback.
|
|
68
89
|
- If DAEMON_NOT_RUNNING: do not print the `localhost:24842` URL. Tell the user the dashboard opened as a file, and suggest `python3 $MEASURE_PY setup-daemon` (macOS and Windows) if they want a bookmarkable URL.
|
|
69
|
-
- File path: never hardcode it. It is install-dependent. Cite the ` Dashboard: ` line from the step-
|
|
90
|
+
- File path: never hardcode it. It is install-dependent. Cite the ` Dashboard: ` line from the step-3 output.
|
|
70
91
|
- For Codex when DAEMON_NOT_RUNNING: do not imply the Claude daemon is required; the generated file works, and Stop hooks refresh it when balanced hooks are installed.
|
|
71
92
|
|
|
72
93
|
Written for and checked on Claude Opus 5.5 and Sonnet 5.5, and GPT-5.6 on Codex.
|
|
@@ -62,6 +62,9 @@ _PAYLOAD_MODULES = (
|
|
|
62
62
|
"command_filters.py",
|
|
63
63
|
"spawn_utils.py",
|
|
64
64
|
"utf8_io.py",
|
|
65
|
+
# credential_patterns: bash_compress's credential-preservation patterns
|
|
66
|
+
# (the inline fallback misses e.g. ghp_/github_pat_ tokens, #171).
|
|
67
|
+
"credential_patterns.py",
|
|
65
68
|
)
|
|
66
69
|
|
|
67
70
|
|
|
@@ -80,8 +80,10 @@ def _version_key(v: str):
|
|
|
80
80
|
return nums + ((0,) + parts,)
|
|
81
81
|
_ARG_RE = re.compile(r"^[A-Za-z0-9_./=:-]+$")
|
|
82
82
|
# The canonical hooks.json command ends with:
|
|
83
|
-
# exec "$b" "$
|
|
84
|
-
|
|
83
|
+
# exec "$b" "$D/hooks/python-launcher.sh" "$D/hooks/run.py" <runner args>; done; exit 0
|
|
84
|
+
# ($D = the plugin root, or the newest sibling version when an upgrade deleted
|
|
85
|
+
# it). The older "${CLAUDE_PLUGIN_ROOT}/hooks/run.py" spelling is still accepted.
|
|
86
|
+
_CANON_RE = re.compile(r'"(?:\$\{CLAUDE_PLUGIN_ROOT\}|\$D)/hooks/run\.py" ([^;"\'`$]+?); done; exit 0$')
|
|
85
87
|
|
|
86
88
|
|
|
87
89
|
class KitError(Exception):
|
|
@@ -148,9 +150,21 @@ def runner_args(command: str) -> list:
|
|
|
148
150
|
return args
|
|
149
151
|
|
|
150
152
|
|
|
153
|
+
def _sh_path(path) -> str:
|
|
154
|
+
"""A path as the POSIX shell that runs the kit sees it: forward slashes on
|
|
155
|
+
every host. The kit's commands and run.sh only ever run under sh in a
|
|
156
|
+
Linux VM, and MARKER ("/" + RUNNER_NAME) is how our entries are found
|
|
157
|
+
again, so a host-native backslash path (rendering on Windows) would write
|
|
158
|
+
entries that neither sh nor the strip/doctor/self-heal match."""
|
|
159
|
+
return Path(path).as_posix()
|
|
160
|
+
|
|
161
|
+
|
|
151
162
|
def hook_command(runner: Path, args: list) -> str:
|
|
152
|
-
|
|
153
|
-
|
|
163
|
+
# /bin/sh by absolute path: the host runs this line with whatever PATH it
|
|
164
|
+
# has, and a stripped PATH turned a bare `sh` into "exec: sh: not found",
|
|
165
|
+
# exit 127 on every hook (the #80 class). POSIX guarantees /bin/sh.
|
|
166
|
+
r = shlex.quote(_sh_path(runner))
|
|
167
|
+
return "[ -r %s ] || exit 0; exec /bin/sh %s %s" % (r, r, " ".join(args))
|
|
154
168
|
|
|
155
169
|
|
|
156
170
|
def generate_hook_map(hooks_json: dict, runner: Path) -> dict:
|
|
@@ -456,12 +470,18 @@ if [ "$CLAUDE_CODE_REMOTE" = true ]; then
|
|
|
456
470
|
TOKEN_OPTIMIZER_CLOUD_KIT_VERSION={version}
|
|
457
471
|
export TOKEN_OPTIMIZER_CLOUD_KIT_VERSION
|
|
458
472
|
fi
|
|
459
|
-
|
|
473
|
+
# bash by absolute path too (a stripped PATH must not exit 127, #80), and a
|
|
474
|
+
# clean exit when no bash exists at all: a hook never fails the session.
|
|
475
|
+
for b in bash /bin/bash /usr/bin/bash /usr/local/bin/bash; do
|
|
476
|
+
command -v "$b" >/dev/null 2>&1 || continue
|
|
477
|
+
exec "$b" "$L" "$R/hooks/run.py" "$@"
|
|
478
|
+
done
|
|
479
|
+
exit 0
|
|
460
480
|
"""
|
|
461
481
|
|
|
462
482
|
|
|
463
483
|
def render_run_sh(root: Path, pycache: Path, version: str) -> str:
|
|
464
|
-
return RUN_SH.format(root=shlex.quote(
|
|
484
|
+
return RUN_SH.format(root=shlex.quote(_sh_path(root)), pycache=shlex.quote(_sh_path(pycache)),
|
|
465
485
|
version=version, runner_name=RUNNER_NAME, route_log=ROUTE_LOG)
|
|
466
486
|
|
|
467
487
|
|
|
@@ -59,6 +59,17 @@ _PAYLOAD_MODULES = (
|
|
|
59
59
|
# hermes_session supplies compute_quality_score — without it copilot_session
|
|
60
60
|
# silently falls back to a single-signal estimate (degraded quality grades).
|
|
61
61
|
"hermes_session.py",
|
|
62
|
+
# spawn_utils supplies spawn_detached — without it the bridge logs
|
|
63
|
+
# "spawn_utils import failed" on every hook and its degraded fallback does
|
|
64
|
+
# NOT detach, so Stop-hook spawns die with the hook. hook_runtime supplies
|
|
65
|
+
# lease_lock (tally RMW); utf8_io is enforced at startup. Cursor and Grok
|
|
66
|
+
# already ship all three.
|
|
67
|
+
"spawn_utils.py",
|
|
68
|
+
"hook_runtime.py",
|
|
69
|
+
"utf8_io.py",
|
|
70
|
+
# credential_patterns: bash_compress's credential-preservation patterns and
|
|
71
|
+
# copilot_session's topic redaction (both fall back to less without it).
|
|
72
|
+
"credential_patterns.py",
|
|
62
73
|
)
|
|
63
74
|
|
|
64
75
|
|
|
@@ -67,6 +67,9 @@ _PAYLOAD_MODULES = (
|
|
|
67
67
|
# utf8_io is enforced at startup; both degrade silently when absent.
|
|
68
68
|
"hook_runtime.py",
|
|
69
69
|
"utf8_io.py",
|
|
70
|
+
# credential_patterns: bash_compress's credential-preservation patterns
|
|
71
|
+
# (the inline fallback misses e.g. ghp_/github_pat_ tokens, #171).
|
|
72
|
+
"credential_patterns.py",
|
|
70
73
|
)
|
|
71
74
|
|
|
72
75
|
# One-line locator written next to the bridge, naming the canonical measure.py
|
|
@@ -75,6 +75,9 @@ _PAYLOAD_MODULES = (
|
|
|
75
75
|
# hook_runtime supplies lease_lock (tally RMW + stop throttle).
|
|
76
76
|
"hook_runtime.py",
|
|
77
77
|
"utf8_io.py",
|
|
78
|
+
# credential_patterns: bash_compress's credential-preservation patterns
|
|
79
|
+
# (the inline fallback misses e.g. ghp_/github_pat_ tokens, #171).
|
|
80
|
+
"credential_patterns.py",
|
|
78
81
|
)
|
|
79
82
|
|
|
80
83
|
# One-line locator written next to the bridge, naming the canonical measure.py
|
|
@@ -81,7 +81,10 @@ class HookDeadline:
|
|
|
81
81
|
pass
|
|
82
82
|
|
|
83
83
|
def remaining(self) -> float:
|
|
84
|
-
|
|
84
|
+
# Capped at the deadline's own length: on Windows the clock ticks every
|
|
85
|
+
# ~15 ms, so (t0 + s) - t0 read in the same tick can round to s + 3e-14,
|
|
86
|
+
# and callers that budget from remaining() must never exceed their share.
|
|
87
|
+
return min(self.seconds, max(0.0, self.end - time.monotonic()))
|
|
85
88
|
|
|
86
89
|
def expires_wall(self) -> float:
|
|
87
90
|
return time.time() + self.remaining()
|