@alexgreensh/token-optimizer 0.0.0-stage → 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 +76 -0
- package/.claude-plugin/plugin.json +21 -0
- package/LICENSE +130 -0
- package/LICENSE-SMALL-BUSINESS.md +62 -0
- package/PRIVACY.md +200 -0
- package/README.md +13 -2
- package/hooks/codex-hooks.json +4 -0
- package/hooks/hooks.json +182 -0
- package/hooks/module_runner.py +448 -0
- package/hooks/posttooluse_runner.py +1110 -0
- package/hooks/python-launcher.sh +816 -0
- package/hooks/run.py +788 -0
- package/hooks/sessionstart_runner.py +629 -0
- package/hooks/stop_runner.py +408 -0
- package/hooks/userpromptsubmit_runner.py +722 -0
- package/hooks/windows-launcher.py +163 -0
- package/install-cloud.sh +23 -0
- package/package.json +29 -4
- package/skills/fleet-auditor/SKILL.md +149 -0
- package/skills/fleet-auditor/references/fleet-systems.md +167 -0
- package/skills/fleet-auditor/references/report-template.md +50 -0
- package/skills/fleet-auditor/references/waste-patterns.md +126 -0
- package/skills/fleet-auditor/scripts/fleet.py +3633 -0
- package/skills/fleet-auditor/scripts/shared.py +277 -0
- package/skills/resume-checkpoint/SKILL.md +52 -0
- package/skills/resume-checkpoint/scripts/pull_checkpoint.py +188 -0
- package/skills/token-coach/SKILL.md +141 -0
- package/skills/token-coach/assets/coach-dashboard-tab.html +45 -0
- package/skills/token-coach/examples/coaching-session-agentic.md +62 -0
- package/skills/token-coach/examples/coaching-session-heavy-setup.md +46 -0
- package/skills/token-coach/examples/coaching-session-new-project.md +38 -0
- package/skills/token-coach/references/agentic-systems.md +147 -0
- package/skills/token-coach/references/coach-patterns.md +120 -0
- package/skills/token-coach/references/coaching-scripts.md +146 -0
- package/skills/token-coach/references/deterministic-stages.md +102 -0
- package/skills/token-coach/references/keepwarm-consent.md +48 -0
- package/skills/token-coach/references/quick-reference.md +155 -0
- package/skills/token-dashboard/SKILL.md +93 -0
- package/skills/token-optimizer/SKILL.md +150 -0
- package/skills/token-optimizer/assets/dashboard.html +7251 -0
- package/skills/token-optimizer/examples/claude-md-optimized.md +40 -0
- package/skills/token-optimizer/examples/hooks-starter.json +179 -0
- package/skills/token-optimizer/examples/permissions-deny-template.json +24 -0
- package/skills/token-optimizer/pricing/prices.json +695 -0
- package/skills/token-optimizer/references/agent-prompts.md +687 -0
- package/skills/token-optimizer/references/cli-reference.md +92 -0
- package/skills/token-optimizer/references/codex-workflow.md +188 -0
- package/skills/token-optimizer/references/cursor-workflow.md +74 -0
- package/skills/token-optimizer/references/error-recovery.md +37 -0
- package/skills/token-optimizer/references/implementation-playbook.md +416 -0
- package/skills/token-optimizer/references/keepwarm-consent.md +48 -0
- package/skills/token-optimizer/references/opencode-workflow.md +72 -0
- package/skills/token-optimizer/references/optimization-checklist.md +714 -0
- package/skills/token-optimizer/references/phase0-setup.md +142 -0
- package/skills/token-optimizer/references/presentation-workflow.md +72 -0
- package/skills/token-optimizer/references/session-continuity.md +19 -0
- package/skills/token-optimizer/references/token-flow-architecture.md +629 -0
- package/skills/token-optimizer/scripts/activity_tracker.py +143 -0
- package/skills/token-optimizer/scripts/antigravity_doctor.py +548 -0
- package/skills/token-optimizer/scripts/antigravity_hook_bridge.py +511 -0
- package/skills/token-optimizer/scripts/antigravity_install.py +379 -0
- package/skills/token-optimizer/scripts/antigravity_proto.py +413 -0
- package/skills/token-optimizer/scripts/antigravity_session.py +346 -0
- package/skills/token-optimizer/scripts/antigravity_state.py +486 -0
- package/skills/token-optimizer/scripts/archive_result.py +1725 -0
- package/skills/token-optimizer/scripts/bash_compress.py +2490 -0
- package/skills/token-optimizer/scripts/bash_compress_hook.py +766 -0
- package/skills/token-optimizer/scripts/bash_hook.py +61 -0
- package/skills/token-optimizer/scripts/bash_whitelist.py +243 -0
- package/skills/token-optimizer/scripts/benchmark.py +1765 -0
- package/skills/token-optimizer/scripts/build_output_compress.py +776 -0
- package/skills/token-optimizer/scripts/cloud_kit.py +1011 -0
- package/skills/token-optimizer/scripts/codex_command_compress.py +434 -0
- package/skills/token-optimizer/scripts/codex_compact_prompt.py +273 -0
- package/skills/token-optimizer/scripts/codex_doctor.py +454 -0
- package/skills/token-optimizer/scripts/codex_hook_bridge.py +311 -0
- package/skills/token-optimizer/scripts/codex_install.py +810 -0
- package/skills/token-optimizer/scripts/codex_io.py +119 -0
- package/skills/token-optimizer/scripts/codex_log_index.py +219 -0
- package/skills/token-optimizer/scripts/codex_models.py +34 -0
- package/skills/token-optimizer/scripts/codex_session.py +1186 -0
- package/skills/token-optimizer/scripts/codex_state.py +707 -0
- package/skills/token-optimizer/scripts/codex_statusline.py +303 -0
- package/skills/token-optimizer/scripts/command_filters.py +386 -0
- package/skills/token-optimizer/scripts/compression_backfill.py +600 -0
- package/skills/token-optimizer/scripts/compression_log.py +230 -0
- package/skills/token-optimizer/scripts/context_intel.py +331 -0
- package/skills/token-optimizer/scripts/context_pressure.py +115 -0
- package/skills/token-optimizer/scripts/copilot_doctor.py +406 -0
- package/skills/token-optimizer/scripts/copilot_hook_bridge.py +709 -0
- package/skills/token-optimizer/scripts/copilot_install.py +288 -0
- package/skills/token-optimizer/scripts/copilot_session.py +496 -0
- package/skills/token-optimizer/scripts/copilot_state.py +569 -0
- package/skills/token-optimizer/scripts/copilot_vscode.py +832 -0
- package/skills/token-optimizer/scripts/cowork_doctor.py +270 -0
- package/skills/token-optimizer/scripts/cowork_install.py +380 -0
- package/skills/token-optimizer/scripts/credential_patterns.py +1514 -0
- package/skills/token-optimizer/scripts/cursor_doctor.py +602 -0
- package/skills/token-optimizer/scripts/cursor_hook_bridge.py +843 -0
- package/skills/token-optimizer/scripts/cursor_install.py +426 -0
- package/skills/token-optimizer/scripts/cursor_session.py +303 -0
- package/skills/token-optimizer/scripts/cursor_state.py +348 -0
- package/skills/token-optimizer/scripts/delta_diff.py +110 -0
- package/skills/token-optimizer/scripts/detectors/__init__.py +2 -0
- package/skills/token-optimizer/scripts/detectors/bad_decomposition.py +78 -0
- package/skills/token-optimizer/scripts/detectors/cache_instability.py +504 -0
- package/skills/token-optimizer/scripts/detectors/looping.py +88 -0
- package/skills/token-optimizer/scripts/detectors/output_waste.py +143 -0
- package/skills/token-optimizer/scripts/detectors/overpowered.py +116 -0
- package/skills/token-optimizer/scripts/detectors/pdf_ingestion.py +52 -0
- package/skills/token-optimizer/scripts/detectors/registry.py +65 -0
- package/skills/token-optimizer/scripts/detectors/respond_to_bash.py +76 -0
- package/skills/token-optimizer/scripts/detectors/retry_churn.py +83 -0
- package/skills/token-optimizer/scripts/detectors/tool_cascade.py +62 -0
- package/skills/token-optimizer/scripts/detectors/wasteful_thinking.py +75 -0
- package/skills/token-optimizer/scripts/detectors/weak_model.py +55 -0
- package/skills/token-optimizer/scripts/detectors/websearch_routing.py +72 -0
- package/skills/token-optimizer/scripts/deterministic_candidates.py +1458 -0
- package/skills/token-optimizer/scripts/devin_compress.py +790 -0
- package/skills/token-optimizer/scripts/devin_doctor.py +403 -0
- package/skills/token-optimizer/scripts/devin_hooks.py +453 -0
- package/skills/token-optimizer/scripts/devin_install.py +1086 -0
- package/skills/token-optimizer/scripts/devin_source.py +119 -0
- package/skills/token-optimizer/scripts/devin_state.py +330 -0
- package/skills/token-optimizer/scripts/devin_verify.py +67 -0
- package/skills/token-optimizer/scripts/grok_doctor.py +560 -0
- package/skills/token-optimizer/scripts/grok_hook_bridge.py +699 -0
- package/skills/token-optimizer/scripts/grok_install.py +400 -0
- package/skills/token-optimizer/scripts/grok_session.py +317 -0
- package/skills/token-optimizer/scripts/grok_state.py +299 -0
- package/skills/token-optimizer/scripts/hermes_doctor.py +479 -0
- package/skills/token-optimizer/scripts/hermes_hook_bridge.py +285 -0
- package/skills/token-optimizer/scripts/hermes_install.py +668 -0
- package/skills/token-optimizer/scripts/hermes_session.py +691 -0
- package/skills/token-optimizer/scripts/hermes_state.py +448 -0
- package/skills/token-optimizer/scripts/hook_io.py +120 -0
- package/skills/token-optimizer/scripts/hook_runtime.py +716 -0
- package/skills/token-optimizer/scripts/injection.py +156 -0
- package/skills/token-optimizer/scripts/install_reconcile.py +952 -0
- package/skills/token-optimizer/scripts/measure.py +59531 -0
- package/skills/token-optimizer/scripts/outline.py +53 -0
- package/skills/token-optimizer/scripts/pipeline_analyzer.py +723 -0
- package/skills/token-optimizer/scripts/plugin_env.py +562 -0
- package/skills/token-optimizer/scripts/py_trust.py +80 -0
- package/skills/token-optimizer/scripts/quality_cache_gate.py +320 -0
- package/skills/token-optimizer/scripts/read_cache.py +2489 -0
- package/skills/token-optimizer/scripts/recovery_output.py +110 -0
- package/skills/token-optimizer/scripts/refetch_fingerprint.py +236 -0
- package/skills/token-optimizer/scripts/refetch_guard.py +244 -0
- package/skills/token-optimizer/scripts/routing_advisor.py +389 -0
- package/skills/token-optimizer/scripts/runtime_env.py +1923 -0
- package/skills/token-optimizer/scripts/session_store.py +979 -0
- package/skills/token-optimizer/scripts/spawn_utils.py +122 -0
- package/skills/token-optimizer/scripts/statusline.js +660 -0
- package/skills/token-optimizer/scripts/structure_map.py +2880 -0
- package/skills/token-optimizer/scripts/structure_map_ts.py +676 -0
- package/skills/token-optimizer/scripts/structure_replay.py +1556 -0
- package/skills/token-optimizer/scripts/thrash_guard.py +604 -0
- package/skills/token-optimizer/scripts/token_estimate.py +80 -0
- package/skills/token-optimizer/scripts/tool_search_diagnostic.py +61 -0
- package/skills/token-optimizer/scripts/utf8_io.py +219 -0
package/hooks/run.py
ADDED
|
@@ -0,0 +1,788 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Cross-platform hook dispatcher.
|
|
3
|
+
|
|
4
|
+
Invoked from hooks.json via a small bash launcher that locates a usable
|
|
5
|
+
Python 3 interpreter on macOS, Linux, and Windows:
|
|
6
|
+
|
|
7
|
+
"command": "bash \"${CLAUDE_PLUGIN_ROOT}/hooks/python-launcher.sh\" \"${CLAUDE_PLUGIN_ROOT}/hooks/run.py\" <script-relative-path> [args...]"
|
|
8
|
+
|
|
9
|
+
The launcher handles Windows-specific gotchas (Program Files spaced paths,
|
|
10
|
+
Microsoft Store zero-byte stubs in WindowsApps, py launcher fallback) so
|
|
11
|
+
this file can assume it's running under a real Python 3.9+.
|
|
12
|
+
|
|
13
|
+
This dispatcher resolves the target script under CLAUDE_PLUGIN_ROOT,
|
|
14
|
+
checks it exists, and runs it with the same interpreter (sys.executable).
|
|
15
|
+
On timeout we kill the child (Popen.kill) to avoid leaking a process
|
|
16
|
+
holding the trends.db SQLite lock. Always exits 0 so hook failures never
|
|
17
|
+
block the user's tool call.
|
|
18
|
+
|
|
19
|
+
Windows reap note: module_runner.py runs measure.py IN-PROCESS via
|
|
20
|
+
runpy.run_module, so the child proc IS measure.py (the trends.db lock
|
|
21
|
+
holder), not a grandchild. On Windows we reap with plain proc.kill()
|
|
22
|
+
(TerminateProcess of proc.pid only), NOT taskkill /F /T which would walk
|
|
23
|
+
the PPID tree and wrongly kill the detached session-end-flush worker
|
|
24
|
+
(the one CREATE_BREAKAWAY_FROM_JOB exists to keep alive). The SIGINT/
|
|
25
|
+
SIGTERM handler is best effort on Windows: the detached child has no console
|
|
26
|
+
and never sees Ctrl+C, Popen.wait() there is a plain WaitForSingleObject that a
|
|
27
|
+
Python handler cannot interrupt (the handler runs once the wait returns), and
|
|
28
|
+
an external TerminateProcess from the host bypasses Python handlers entirely.
|
|
29
|
+
"""
|
|
30
|
+
from __future__ import annotations
|
|
31
|
+
|
|
32
|
+
import json
|
|
33
|
+
import os
|
|
34
|
+
import signal
|
|
35
|
+
import subprocess
|
|
36
|
+
import sys
|
|
37
|
+
import traceback
|
|
38
|
+
from pathlib import Path
|
|
39
|
+
|
|
40
|
+
# Defense in depth: the launcher script already filters interpreters, but
|
|
41
|
+
# if a user's PATH has a stale Python 3.7 that slipped through, bail early
|
|
42
|
+
# so later imports don't explode with confusing SyntaxError noise.
|
|
43
|
+
if sys.version_info < (3, 9):
|
|
44
|
+
sys.exit(0)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
# Module-level handle so the signal handler can reach the active child when
|
|
48
|
+
# Claude Code (or any parent) sends SIGTERM/SIGINT to run.py itself. Without
|
|
49
|
+
# this, an external kill reaps run.py but orphans the measure.py grandchild,
|
|
50
|
+
# which keeps the inherited stdout pipe open and makes the parent hang waiting
|
|
51
|
+
# for EOF (the multi-minute stop-hook hang).
|
|
52
|
+
_child_proc: subprocess.Popen | None = None
|
|
53
|
+
|
|
54
|
+
# Hard ceiling on one hook child, seconds. One name for both the POSIX reap
|
|
55
|
+
# timer and the Windows wait so tests can shorten it in a single place.
|
|
56
|
+
_CHILD_WAIT_TIMEOUT_S = 120
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
_PYCACHE_PREFIX_ENV = "PYTHONPYCACHEPREFIX"
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _remote_vm_env() -> bool:
|
|
63
|
+
"""True in a hosted Claude Code VM (cloud or Cowork). Env-only, no imports:
|
|
64
|
+
this runs before anything from the plugin's scripts dir is imported."""
|
|
65
|
+
if os.environ.get("CLAUDE_CODE_REMOTE", "").strip().lower() in ("1", "true", "yes", "on"):
|
|
66
|
+
return True
|
|
67
|
+
if os.environ.get("CLAUDE_CODE_REMOTE_SESSION_ID", "").strip():
|
|
68
|
+
return True
|
|
69
|
+
if os.environ.get("TOKEN_OPTIMIZER_CLOUD_KIT_VERSION", "").strip():
|
|
70
|
+
return True
|
|
71
|
+
return os.environ.get("TOKEN_OPTIMIZER_REMOTE_HOST", "").strip().lower() in ("cloud", "cowork")
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _inside_git_work_tree(path: Path) -> bool:
|
|
75
|
+
"""True when ``path`` or any ancestor holds a ``.git`` entry (dir or file).
|
|
76
|
+
A bounded walk of cheap stats; any error reads as False."""
|
|
77
|
+
try:
|
|
78
|
+
current = Path(path)
|
|
79
|
+
for _ in range(64):
|
|
80
|
+
if (current / ".git").exists():
|
|
81
|
+
return True
|
|
82
|
+
parent = current.parent
|
|
83
|
+
if parent == current:
|
|
84
|
+
return False
|
|
85
|
+
current = parent
|
|
86
|
+
except (OSError, ValueError):
|
|
87
|
+
pass
|
|
88
|
+
return False
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def _bytecode_cache_dir() -> Path:
|
|
92
|
+
"""Per-user bytecode cache: %LOCALAPPDATA% on Windows, $XDG_CACHE_HOME or
|
|
93
|
+
~/.cache elsewhere, then token-optimizer/pycache."""
|
|
94
|
+
base = None
|
|
95
|
+
if os.name == "nt":
|
|
96
|
+
raw = os.environ.get("LOCALAPPDATA", "").strip()
|
|
97
|
+
if raw and os.path.isabs(raw):
|
|
98
|
+
base = Path(raw)
|
|
99
|
+
else:
|
|
100
|
+
raw = os.environ.get("XDG_CACHE_HOME", "").strip()
|
|
101
|
+
if raw and os.path.isabs(raw):
|
|
102
|
+
base = Path(raw)
|
|
103
|
+
if base is None:
|
|
104
|
+
base = Path.home() / ".cache"
|
|
105
|
+
return base / "token-optimizer" / "pycache"
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def _bytecode_prefix_for(plugin_root: Path) -> str | None:
|
|
109
|
+
"""Where Python bytecode for the plugin should go, or None for "beside the
|
|
110
|
+
scripts" (the default, unchanged on a normal desktop install).
|
|
111
|
+
|
|
112
|
+
Bytecode is moved out of the plugin tree when the tree sits inside a git
|
|
113
|
+
work tree (a plugin vendored into a repo, a dev checkout) or when running
|
|
114
|
+
in a hosted VM. Otherwise every hook drops ``__pycache__`` dirs into the
|
|
115
|
+
user's repo: untracked files that Claude Code cloud's own Stop hook then
|
|
116
|
+
nags the model to commit. A cache PREFIX keeps the warm-start speedup
|
|
117
|
+
(module_runner's whole point); disabling bytecode would lose it. An
|
|
118
|
+
existing PYTHONPYCACHEPREFIX is the user's choice and is left alone.
|
|
119
|
+
"""
|
|
120
|
+
try:
|
|
121
|
+
if os.environ.get(_PYCACHE_PREFIX_ENV, "").strip():
|
|
122
|
+
return None
|
|
123
|
+
if not (_remote_vm_env() or _inside_git_work_tree(plugin_root)):
|
|
124
|
+
return None
|
|
125
|
+
return str(_bytecode_cache_dir())
|
|
126
|
+
except Exception:
|
|
127
|
+
return None
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def _apply_bytecode_prefix(prefix: str | None, child_env: dict | None = None) -> None:
|
|
131
|
+
"""Point this process (sys.pycache_prefix) and the hook child (env) at
|
|
132
|
+
``prefix``. A no-op for None. Never raises."""
|
|
133
|
+
if not prefix:
|
|
134
|
+
return
|
|
135
|
+
try:
|
|
136
|
+
sys.pycache_prefix = prefix
|
|
137
|
+
if child_env is not None:
|
|
138
|
+
child_env[_PYCACHE_PREFIX_ENV] = prefix
|
|
139
|
+
except Exception:
|
|
140
|
+
pass
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def _reap(proc, posix_sig):
|
|
144
|
+
"""Reap the child process. Never raises.
|
|
145
|
+
|
|
146
|
+
On Windows, the child proc IS measure.py (module_runner.py runs it
|
|
147
|
+
in-process via runpy.run_module), so a plain ``proc.kill()``
|
|
148
|
+
(TerminateProcess of proc.pid only) releases the trends.db lock without
|
|
149
|
+
walking the PPID tree and killing the detached session-end-flush worker
|
|
150
|
+
(the one CREATE_BREAKAWAY_FROM_JOB exists to keep alive).
|
|
151
|
+
|
|
152
|
+
On POSIX, the child is started with ``start_new_session=True`` so it leads
|
|
153
|
+
its own process group; killing the group reaps any grandchildren (the
|
|
154
|
+
launcher chain uses ``exec``, so run.py's PID is the one the host tracks).
|
|
155
|
+
Falls back to ``proc.kill()`` when the group is already gone.
|
|
156
|
+
"""
|
|
157
|
+
if proc.poll() is not None:
|
|
158
|
+
return
|
|
159
|
+
if os.name == "nt":
|
|
160
|
+
try:
|
|
161
|
+
proc.kill()
|
|
162
|
+
except OSError:
|
|
163
|
+
try:
|
|
164
|
+
sys.stderr.write("run.py: nt reap kill failed\n")
|
|
165
|
+
sys.stderr.flush()
|
|
166
|
+
except (OSError, ValueError):
|
|
167
|
+
pass
|
|
168
|
+
elif hasattr(os, "killpg"):
|
|
169
|
+
try:
|
|
170
|
+
os.killpg(os.getpgid(proc.pid), posix_sig)
|
|
171
|
+
except (ProcessLookupError, OSError):
|
|
172
|
+
try:
|
|
173
|
+
proc.kill()
|
|
174
|
+
except OSError:
|
|
175
|
+
try:
|
|
176
|
+
sys.stderr.write("run.py: posix reap kill failed\n")
|
|
177
|
+
sys.stderr.flush()
|
|
178
|
+
except (OSError, ValueError):
|
|
179
|
+
pass
|
|
180
|
+
else:
|
|
181
|
+
try:
|
|
182
|
+
proc.kill()
|
|
183
|
+
except OSError:
|
|
184
|
+
try:
|
|
185
|
+
sys.stderr.write("run.py: fallback reap kill failed\n")
|
|
186
|
+
sys.stderr.flush()
|
|
187
|
+
except (OSError, ValueError):
|
|
188
|
+
pass
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def _forward_and_exit(signum, frame):
|
|
192
|
+
"""Forward SIGTERM/SIGINT to the child, then exit.
|
|
193
|
+
|
|
194
|
+
On Windows this is best effort: Popen.wait() is not interruptible by a
|
|
195
|
+
Python handler, so it runs once the wait returns, and an external
|
|
196
|
+
TerminateProcess from the host bypasses Python handlers entirely.
|
|
197
|
+
"""
|
|
198
|
+
global _child_proc
|
|
199
|
+
if _child_proc is not None:
|
|
200
|
+
_reap(_child_proc, signal.SIGTERM)
|
|
201
|
+
os._exit(0)
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
# Diagnostics log for unexpected errors in the consent gate. Mirrors the
|
|
205
|
+
# pattern in the hook runners: write to SNAPSHOT_DIR (never stderr, which
|
|
206
|
+
# the host captures into the model's session context). Capped at 256 KB.
|
|
207
|
+
_DIAGNOSTICS_LOG_NAME = "consent_diagnostics.log"
|
|
208
|
+
_DIAGNOSTICS_LOG_CAP = 256 * 1024
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def _consent_diagnostics_log_path():
|
|
212
|
+
"""Resolve the diagnostics log path under measure.SNAPSHOT_DIR, or None."""
|
|
213
|
+
try:
|
|
214
|
+
import measure
|
|
215
|
+
base = getattr(measure, "SNAPSHOT_DIR", None)
|
|
216
|
+
if base is None:
|
|
217
|
+
return None
|
|
218
|
+
from pathlib import Path as _P
|
|
219
|
+
return _P(base) / _DIAGNOSTICS_LOG_NAME
|
|
220
|
+
except Exception:
|
|
221
|
+
return None
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
def _consent_log_diagnostics(message):
|
|
225
|
+
"""Append a diagnostics chunk to the consent diagnostics log, capped."""
|
|
226
|
+
path = _consent_diagnostics_log_path()
|
|
227
|
+
if path is None:
|
|
228
|
+
return
|
|
229
|
+
try:
|
|
230
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
231
|
+
with open(path, "a", encoding="utf-8") as f:
|
|
232
|
+
f.write(message)
|
|
233
|
+
if path.stat().st_size > _DIAGNOSTICS_LOG_CAP:
|
|
234
|
+
data = path.read_bytes()[-_DIAGNOSTICS_LOG_CAP:]
|
|
235
|
+
path.write_bytes(data)
|
|
236
|
+
except OSError:
|
|
237
|
+
pass
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
def _check_consent(plugin_root: Path | None = None) -> bool:
|
|
241
|
+
"""Return True if consent is given or assumed. Fail-open on any error."""
|
|
242
|
+
try:
|
|
243
|
+
home = Path.home()
|
|
244
|
+
|
|
245
|
+
# Resolve config path from env (set by Claude Code before hook invocation)
|
|
246
|
+
plugin_data = os.environ.get("CLAUDE_PLUGIN_DATA", "")
|
|
247
|
+
config_path = None
|
|
248
|
+
if plugin_data:
|
|
249
|
+
pd = Path(plugin_data).resolve()
|
|
250
|
+
if not str(pd).startswith(str(home)):
|
|
251
|
+
return True # Path outside home = skip (fail-open)
|
|
252
|
+
# In-home CLAUDE_PLUGIN_DATA must still be a declared identity of
|
|
253
|
+
# THIS plugin, not a foreign plugin's leaked value sharing the same
|
|
254
|
+
# shared plugins/data root. Reuse the
|
|
255
|
+
# SAME identity-checked resolver plugin_env.py uses for every other
|
|
256
|
+
# hook script instead of trusting pd raw. If the resolver truly
|
|
257
|
+
# can't be imported (unusual/non-standard plugin layout), fall back
|
|
258
|
+
# to trusting pd -- matching prior behavior -- so a missing
|
|
259
|
+
# import never blocks the consent check. If it CAN be imported but
|
|
260
|
+
# rejects pd as foreign, fall through to the identical legacy chain
|
|
261
|
+
# a session with no CLAUDE_PLUGIN_DATA at all would use below --
|
|
262
|
+
# never re-trust the raw (possibly leaked) value.
|
|
263
|
+
resolver_ran = False
|
|
264
|
+
identity_checked = None
|
|
265
|
+
if plugin_root is not None:
|
|
266
|
+
try:
|
|
267
|
+
scripts_dir = plugin_root / "skills" / "token-optimizer" / "scripts"
|
|
268
|
+
scripts_str = str(scripts_dir)
|
|
269
|
+
if scripts_str not in sys.path:
|
|
270
|
+
sys.path.insert(0, scripts_str)
|
|
271
|
+
from plugin_env import resolve_claude_plugin_data_env
|
|
272
|
+
resolver_ran = True
|
|
273
|
+
identity_checked = resolve_claude_plugin_data_env()
|
|
274
|
+
except Exception:
|
|
275
|
+
resolver_ran = False
|
|
276
|
+
if identity_checked is not None:
|
|
277
|
+
config_path = identity_checked / "config" / "config.json"
|
|
278
|
+
elif not resolver_ran:
|
|
279
|
+
config_path = pd / "config" / "config.json"
|
|
280
|
+
# else: resolver ran and rejected pd as a foreign identity --
|
|
281
|
+
# config_path stays None and falls through to the legacy chain.
|
|
282
|
+
|
|
283
|
+
if config_path is None:
|
|
284
|
+
# Legacy / Codex fallback
|
|
285
|
+
codex_home = os.environ.get("CODEX_HOME", "")
|
|
286
|
+
if codex_home:
|
|
287
|
+
ch = Path(codex_home).resolve()
|
|
288
|
+
if not str(ch).startswith(str(home)):
|
|
289
|
+
return True
|
|
290
|
+
config_path = ch / "token-optimizer" / "config.json"
|
|
291
|
+
else:
|
|
292
|
+
# Honor CLAUDE_CONFIG_DIR (Claude Code's official config-dir
|
|
293
|
+
# override) before falling back to ~/.claude. Mirrors
|
|
294
|
+
# runtime_env.claude_home(): accept any absolute, existing,
|
|
295
|
+
# non-symlink directory (CLAUDE_CONFIG_DIR may legitimately live
|
|
296
|
+
# OUTSIDE $HOME — containers, CI), reject relative/symlink, else
|
|
297
|
+
# fall back. The previous str.startswith($HOME) check both
|
|
298
|
+
# excluded valid out-of-home dirs and sibling-prefix-matched
|
|
299
|
+
# (/Users/alex-evil passing for /Users/alex).
|
|
300
|
+
claude_config = os.environ.get("CLAUDE_CONFIG_DIR", "").strip()
|
|
301
|
+
cc = None
|
|
302
|
+
if claude_config:
|
|
303
|
+
candidate = Path(claude_config).expanduser()
|
|
304
|
+
try:
|
|
305
|
+
if candidate.is_absolute() and candidate.is_dir() and not candidate.is_symlink():
|
|
306
|
+
cc = candidate.resolve()
|
|
307
|
+
except OSError:
|
|
308
|
+
cc = None
|
|
309
|
+
if cc is not None:
|
|
310
|
+
config_path = cc / "token-optimizer" / "config.json"
|
|
311
|
+
else:
|
|
312
|
+
config_path = home / ".claude" / "token-optimizer" / "config.json"
|
|
313
|
+
|
|
314
|
+
if not config_path.exists() or config_path.is_symlink():
|
|
315
|
+
return True # No config or symlink = fail-open
|
|
316
|
+
|
|
317
|
+
with open(config_path, encoding="utf-8") as f:
|
|
318
|
+
config = json.load(f)
|
|
319
|
+
|
|
320
|
+
if config.get("enterprise_consent_shown"):
|
|
321
|
+
return True
|
|
322
|
+
|
|
323
|
+
# Backward compat backfill: existing users who saw v5 welcome have
|
|
324
|
+
# implicitly consented -- but ONLY when enterprise_consent_shown was
|
|
325
|
+
# never written. A present-and-False enterprise_consent_shown is an
|
|
326
|
+
# explicit opt-out (`consent --reset`); backfilling over it would
|
|
327
|
+
# silently re-enable a user who opted out.
|
|
328
|
+
if config.get("v5_welcome_shown") and "enterprise_consent_shown" not in config:
|
|
329
|
+
config["enterprise_consent_shown"] = True
|
|
330
|
+
# Atomic write (tempfile + os.replace)
|
|
331
|
+
import tempfile
|
|
332
|
+
fd, tmp = tempfile.mkstemp(dir=str(config_path.parent), suffix=".tmp")
|
|
333
|
+
try:
|
|
334
|
+
with os.fdopen(fd, "w", encoding="utf-8") as tf:
|
|
335
|
+
json.dump(config, tf, indent=2)
|
|
336
|
+
os.replace(tmp, str(config_path))
|
|
337
|
+
except Exception:
|
|
338
|
+
try:
|
|
339
|
+
os.unlink(tmp)
|
|
340
|
+
except OSError:
|
|
341
|
+
pass
|
|
342
|
+
return True
|
|
343
|
+
|
|
344
|
+
# Flags ABSENT is the SessionStart race window (v5.11.93 silent
|
|
345
|
+
# no-op), NOT an opt-out: config.json can be created by a non-consent
|
|
346
|
+
# writer (ensure-health's last_hook_heal_check, a v5 feature toggle)
|
|
347
|
+
# before the consent bootstrap writes the flags. Fail OPEN so
|
|
348
|
+
# non-exempt hooks -- the PreToolUse Bash compression rewrite
|
|
349
|
+
# included -- keep working in that window; the exempt bootstrap
|
|
350
|
+
# (ensure-health/consent/v5) writes the flags shortly after. A
|
|
351
|
+
# consent key PRESENT and False is a genuine explicit opt-out
|
|
352
|
+
# (`measure.py consent --reset`) and stays gated.
|
|
353
|
+
if "enterprise_consent_shown" not in config and "v5_welcome_shown" not in config:
|
|
354
|
+
return True
|
|
355
|
+
|
|
356
|
+
return False # Explicit opt-out (a consent key was written False)
|
|
357
|
+
except (OSError, json.JSONDecodeError):
|
|
358
|
+
return True # Fail-open: expected (missing/corrupt config)
|
|
359
|
+
except Exception:
|
|
360
|
+
# Unexpected error — make corruption visible without blocking.
|
|
361
|
+
# Log the traceback to the diagnostics file (never stderr, which
|
|
362
|
+
# the host captures into the model's session context), then
|
|
363
|
+
# fail-open so behavior is unchanged.
|
|
364
|
+
import io
|
|
365
|
+
try:
|
|
366
|
+
buf = io.StringIO()
|
|
367
|
+
buf.write("[Token Optimizer] _check_consent unexpected error, failing open\n")
|
|
368
|
+
traceback.print_exc(file=buf)
|
|
369
|
+
_consent_log_diagnostics(buf.getvalue())
|
|
370
|
+
except Exception:
|
|
371
|
+
pass
|
|
372
|
+
return True # Fail-open: never block on errors
|
|
373
|
+
|
|
374
|
+
|
|
375
|
+
def _windows_stdio_kwargs():
|
|
376
|
+
"""Return the standard handles for a detached (no console) child.
|
|
377
|
+
|
|
378
|
+
A stream with a real OS handle is passed through. When at least one is
|
|
379
|
+
usable, every unusable one gets ``subprocess.DEVNULL``: CPython otherwise
|
|
380
|
+
falls back to ``GetStdHandle`` for a stream left out, and a stale non-NULL
|
|
381
|
+
value there makes ``DuplicateHandle`` fail (WinError 6), so ``Popen`` raises
|
|
382
|
+
and the hook never runs. With none usable nothing is passed (CPython then
|
|
383
|
+
sets no STARTF_USESTDHANDLES and the child has no std handles at all).
|
|
384
|
+
"""
|
|
385
|
+
kwargs = {}
|
|
386
|
+
missing = []
|
|
387
|
+
for name in ("stdin", "stdout", "stderr"):
|
|
388
|
+
stream = getattr(sys, name, None)
|
|
389
|
+
if stream is None:
|
|
390
|
+
missing.append(name)
|
|
391
|
+
continue
|
|
392
|
+
try:
|
|
393
|
+
stream.fileno()
|
|
394
|
+
except (AttributeError, OSError, ValueError):
|
|
395
|
+
missing.append(name)
|
|
396
|
+
continue
|
|
397
|
+
kwargs[name] = stream
|
|
398
|
+
if kwargs:
|
|
399
|
+
for name in missing:
|
|
400
|
+
kwargs[name] = subprocess.DEVNULL
|
|
401
|
+
return kwargs
|
|
402
|
+
|
|
403
|
+
|
|
404
|
+
def _claude_settings_path() -> Path | None:
|
|
405
|
+
"""Resolve the host's settings.json path, honoring CLAUDE_CONFIG_DIR.
|
|
406
|
+
|
|
407
|
+
Mirrors the CLAUDE_CONFIG_DIR handling in the enterprise-consent resolver
|
|
408
|
+
above and in runtime_env.claude_home(): accept any absolute, existing,
|
|
409
|
+
non-symlink directory (CLAUDE_CONFIG_DIR may legitimately live OUTSIDE
|
|
410
|
+
$HOME -- containers, CI runners, relocated config volumes), reject
|
|
411
|
+
relative/symlink, else fall back to ~/.claude. Without this the disable
|
|
412
|
+
self-check read the wrong file for every CLAUDE_CONFIG_DIR user and the
|
|
413
|
+
feature silently no-opped for exactly the population the repo otherwise
|
|
414
|
+
supports (test_claude_config_dir, test_host_safety_guard, etc.).
|
|
415
|
+
Returns None when no usable settings.json exists.
|
|
416
|
+
"""
|
|
417
|
+
claude_config = os.environ.get("CLAUDE_CONFIG_DIR", "").strip()
|
|
418
|
+
base = None
|
|
419
|
+
if claude_config:
|
|
420
|
+
candidate = Path(claude_config).expanduser()
|
|
421
|
+
try:
|
|
422
|
+
if candidate.is_absolute() and candidate.is_dir() and not candidate.is_symlink():
|
|
423
|
+
base = candidate.resolve()
|
|
424
|
+
except OSError:
|
|
425
|
+
base = None
|
|
426
|
+
if base is None:
|
|
427
|
+
base = Path.home() / ".claude"
|
|
428
|
+
settings_path = base / "settings.json"
|
|
429
|
+
if not settings_path.is_file() or settings_path.is_symlink():
|
|
430
|
+
return None
|
|
431
|
+
return settings_path
|
|
432
|
+
|
|
433
|
+
|
|
434
|
+
def _plugin_disabled_by_host() -> bool:
|
|
435
|
+
"""Return True if the host explicitly turned this plugin off via the host
|
|
436
|
+
settings.json's enabledPlugins map, so main() can no-op before spawning the
|
|
437
|
+
dispatch subprocess at all.
|
|
438
|
+
|
|
439
|
+
Claude Code's plugin loader does not appear to reliably stop invoking an
|
|
440
|
+
already-registered plugin's hooks.json commands for existing sessions
|
|
441
|
+
after enabledPlugins[<name>@<marketplace>] is flipped to false (observed:
|
|
442
|
+
8/8 sessions started after such an edit still ran hooks and printed
|
|
443
|
+
"[Token Optimizer]" output). This is a defensive self-check so the plugin
|
|
444
|
+
honors its own disable flag even when the host does not enforce it,
|
|
445
|
+
instead of silently continuing to spend tokens on every hook event.
|
|
446
|
+
|
|
447
|
+
The settings path is resolved via _claude_settings_path(), which honors
|
|
448
|
+
CLAUDE_CONFIG_DIR (the consent resolver and runtime_env.claude_home() both
|
|
449
|
+
do); hardcoding ~/.claude/settings.json left every CLAUDE_CONFIG_DIR user
|
|
450
|
+
reading the wrong file and never getting the disable honored.
|
|
451
|
+
|
|
452
|
+
Fail-open (return False) on any error -- a missing/unreadable settings
|
|
453
|
+
file, or a plugin/marketplace name we can't resolve, must never silently
|
|
454
|
+
disable the plugin for users who never touched this setting.
|
|
455
|
+
"""
|
|
456
|
+
try:
|
|
457
|
+
plugin_root = os.environ.get("CLAUDE_PLUGIN_ROOT", "").strip()
|
|
458
|
+
if not plugin_root:
|
|
459
|
+
return False
|
|
460
|
+
meta_dir = Path(plugin_root) / ".claude-plugin"
|
|
461
|
+
plugin_json = meta_dir / "plugin.json"
|
|
462
|
+
marketplace_json = meta_dir / "marketplace.json"
|
|
463
|
+
if not plugin_json.is_file() or not marketplace_json.is_file():
|
|
464
|
+
return False
|
|
465
|
+
# Cap reads: this runs on every hook event (a fresh process each time, so
|
|
466
|
+
# nothing can be cached across events). settings.json is user-controlled and
|
|
467
|
+
# could be pathologically large; an oversized config reads as "can't tell" ->
|
|
468
|
+
# fail-open (plugin treated as enabled), the safe default.
|
|
469
|
+
_CFG_MAX = 4_000_000
|
|
470
|
+
for _cfg in (plugin_json, marketplace_json):
|
|
471
|
+
if _cfg.stat().st_size > _CFG_MAX:
|
|
472
|
+
return False
|
|
473
|
+
plugin_name = json.loads(plugin_json.read_text(encoding="utf-8")).get("name", "").strip()
|
|
474
|
+
marketplace_name = json.loads(marketplace_json.read_text(encoding="utf-8")).get("name", "").strip()
|
|
475
|
+
if not plugin_name or not marketplace_name:
|
|
476
|
+
return False
|
|
477
|
+
settings_path = _claude_settings_path()
|
|
478
|
+
if settings_path is None:
|
|
479
|
+
return False
|
|
480
|
+
if settings_path.stat().st_size > _CFG_MAX:
|
|
481
|
+
return False
|
|
482
|
+
settings = json.loads(settings_path.read_text(encoding="utf-8"))
|
|
483
|
+
enabled_plugins = settings.get("enabledPlugins")
|
|
484
|
+
if not isinstance(enabled_plugins, dict):
|
|
485
|
+
return False
|
|
486
|
+
key = f"{plugin_name}@{marketplace_name}"
|
|
487
|
+
return enabled_plugins.get(key) is False
|
|
488
|
+
except Exception:
|
|
489
|
+
return False
|
|
490
|
+
|
|
491
|
+
|
|
492
|
+
_COWORK_PLUGIN_NAME = "token-optimizer-cowork"
|
|
493
|
+
_STANDARD_PLUGIN_NAME = "token-optimizer"
|
|
494
|
+
# Marker present in every hook command a script install writes into settings.json.
|
|
495
|
+
_SCRIPT_INSTALL_HOOK_MARKER = "skills/token-optimizer/scripts/"
|
|
496
|
+
|
|
497
|
+
|
|
498
|
+
def _cowork_copy_should_stand_down() -> bool:
|
|
499
|
+
"""True when this is the Cowork build running on a desktop host that already
|
|
500
|
+
has the standard Token Optimizer installed.
|
|
501
|
+
|
|
502
|
+
Account-synced plugins land in desktop Claude Code as well as Cowork, so a
|
|
503
|
+
user with both the standard plugin and the Cowork build would otherwise get
|
|
504
|
+
every hook twice: duplicate context injected on each prompt, duplicate
|
|
505
|
+
archives, duplicate nudges. The Cowork build exists for Cowork, so on a
|
|
506
|
+
desktop host it defers to the standard install.
|
|
507
|
+
|
|
508
|
+
Desktop vs Cowork is decided only by the Cowork host environment
|
|
509
|
+
(CLAUDE_CODE_REMOTE / CLAUDE_CODE_CONTAINER_ID), never by the plugin's
|
|
510
|
+
install path: a synced plugin sits under /plugins/synced/ on desktop too.
|
|
511
|
+
|
|
512
|
+
Fail-open (return False) on any error, so the Cowork build keeps running
|
|
513
|
+
whenever we cannot tell.
|
|
514
|
+
"""
|
|
515
|
+
try:
|
|
516
|
+
if os.environ.get("CLAUDE_CODE_REMOTE", "").strip().lower() in ("1", "true", "yes", "on"):
|
|
517
|
+
return False
|
|
518
|
+
if os.environ.get("CLAUDE_CODE_CONTAINER_ID", "").strip():
|
|
519
|
+
return False
|
|
520
|
+
plugin_root = os.environ.get("CLAUDE_PLUGIN_ROOT", "").strip()
|
|
521
|
+
if not plugin_root:
|
|
522
|
+
return False
|
|
523
|
+
plugin_json = Path(plugin_root) / ".claude-plugin" / "plugin.json"
|
|
524
|
+
if not plugin_json.is_file() or plugin_json.stat().st_size > 4_000_000:
|
|
525
|
+
return False
|
|
526
|
+
name = json.loads(plugin_json.read_text(encoding="utf-8")).get("name", "")
|
|
527
|
+
if not isinstance(name, str) or name.strip() != _COWORK_PLUGIN_NAME:
|
|
528
|
+
return False
|
|
529
|
+
settings_path = _claude_settings_path()
|
|
530
|
+
if settings_path is None or settings_path.stat().st_size > 4_000_000:
|
|
531
|
+
return False
|
|
532
|
+
settings = json.loads(settings_path.read_text(encoding="utf-8"))
|
|
533
|
+
if not isinstance(settings, dict):
|
|
534
|
+
return False
|
|
535
|
+
enabled = settings.get("enabledPlugins")
|
|
536
|
+
if isinstance(enabled, dict):
|
|
537
|
+
for key, value in enabled.items():
|
|
538
|
+
if value is True and isinstance(key, str) and key.split("@", 1)[0] == _STANDARD_PLUGIN_NAME:
|
|
539
|
+
return True
|
|
540
|
+
hooks = settings.get("hooks")
|
|
541
|
+
if hooks and _SCRIPT_INSTALL_HOOK_MARKER in json.dumps(hooks).replace("\\\\", "/"):
|
|
542
|
+
return True
|
|
543
|
+
return False
|
|
544
|
+
except Exception:
|
|
545
|
+
return False
|
|
546
|
+
|
|
547
|
+
|
|
548
|
+
def main() -> int:
|
|
549
|
+
if len(sys.argv) < 2:
|
|
550
|
+
return 0
|
|
551
|
+
# Bytecode location first, before this process imports anything from the
|
|
552
|
+
# plugin's scripts dir (the consent check and runtime detection below do).
|
|
553
|
+
_pycache_prefix = None
|
|
554
|
+
try:
|
|
555
|
+
_pr = os.environ.get("CLAUDE_PLUGIN_ROOT", "").strip()
|
|
556
|
+
_pycache_prefix = _bytecode_prefix_for(Path(_pr) if _pr else Path(__file__).resolve().parent.parent)
|
|
557
|
+
_apply_bytecode_prefix(_pycache_prefix)
|
|
558
|
+
except Exception:
|
|
559
|
+
_pycache_prefix = None
|
|
560
|
+
if _plugin_disabled_by_host():
|
|
561
|
+
return 0
|
|
562
|
+
if _cowork_copy_should_stand_down():
|
|
563
|
+
return 0
|
|
564
|
+
|
|
565
|
+
script_rel = sys.argv[1]
|
|
566
|
+
script_args = sys.argv[2:]
|
|
567
|
+
|
|
568
|
+
# Whole-UserPromptSubmit-path opt-out. Checked BEFORE the
|
|
569
|
+
# module_runner command is built (no stdin read, no imports, no fs access)
|
|
570
|
+
# so a user who sets TOKEN_OPTIMIZER_HOOKS_USERPROMPTSUBMIT=0 pays zero
|
|
571
|
+
# per-prompt cost. The consolidated dispatcher lives at this relative path;
|
|
572
|
+
# the gate is exact-target so it never silences any other hook script.
|
|
573
|
+
if script_rel == "hooks/userpromptsubmit_runner.py":
|
|
574
|
+
if os.environ.get("TOKEN_OPTIMIZER_HOOKS_USERPROMPTSUBMIT", "").strip() == "0":
|
|
575
|
+
return 0
|
|
576
|
+
|
|
577
|
+
rel_path = Path(script_rel)
|
|
578
|
+
if rel_path.is_absolute() or ".." in rel_path.parts:
|
|
579
|
+
return 0
|
|
580
|
+
|
|
581
|
+
plugin_root = os.environ.get("CLAUDE_PLUGIN_ROOT", "").strip()
|
|
582
|
+
# A CLAUDE_PLUGIN_ROOT that no longer exists is the host's stale view of a
|
|
583
|
+
# version dir an upgrade deleted under the running session (Codex keeps the
|
|
584
|
+
# root it loaded at session start). The manifest already found the live
|
|
585
|
+
# sibling version and exec'd ITS run.py, so this file's own location is the
|
|
586
|
+
# live root. Trusting the stale value made every hook exit 0 having done
|
|
587
|
+
# nothing until the session restarted.
|
|
588
|
+
stale_plugin_root = bool(plugin_root) and not os.path.isdir(plugin_root)
|
|
589
|
+
if plugin_root and not stale_plugin_root:
|
|
590
|
+
root_path = Path(plugin_root)
|
|
591
|
+
else:
|
|
592
|
+
# Fallback: relative to this wrapper's parent directory.
|
|
593
|
+
root_path = Path(__file__).resolve().parent.parent
|
|
594
|
+
|
|
595
|
+
try:
|
|
596
|
+
root_resolved = root_path.resolve(strict=True)
|
|
597
|
+
candidate = root_resolved / rel_path
|
|
598
|
+
if not candidate.is_file():
|
|
599
|
+
return 0
|
|
600
|
+
script_path = candidate.resolve(strict=True)
|
|
601
|
+
if not script_path.is_relative_to(root_resolved):
|
|
602
|
+
return 0
|
|
603
|
+
except (OSError, ValueError):
|
|
604
|
+
return 0
|
|
605
|
+
|
|
606
|
+
# Use the interpreter that ran this wrapper so we inherit the correct
|
|
607
|
+
# Python across macOS/Linux/Windows without relying on PATH.
|
|
608
|
+
#
|
|
609
|
+
# Dispatch through module_runner.py rather than running script_path
|
|
610
|
+
# directly: CPython never caches __pycache__ bytecode for a script run as
|
|
611
|
+
# __main__, only for imported modules, so a direct `python script_path`
|
|
612
|
+
# recompiles the target from source on every single hook invocation. For
|
|
613
|
+
# measure.py (~2.7 MB) that is 1.7 s on a fast Mac and 20+ s on some
|
|
614
|
+
# Windows machines (#264), paid on every call. module_runner.py runs it as
|
|
615
|
+
# a module instead, so the import system's normal bytecode cache applies,
|
|
616
|
+
# and moves the one cold compile off the hook's deadline. See
|
|
617
|
+
# module_runner.py.
|
|
618
|
+
module_runner = Path(__file__).resolve().parent / "module_runner.py"
|
|
619
|
+
cmd = [sys.executable, str(module_runner), str(script_path.parent), script_path.stem, *script_args]
|
|
620
|
+
|
|
621
|
+
# Consent gate: skip data collection until acknowledged.
|
|
622
|
+
# EXEMPT: ensure-health and consent commands bootstrap the consent flag itself.
|
|
623
|
+
# Blocking them creates a deadlock (config.json exists without flags -> ensure-health
|
|
624
|
+
# can't run -> flags never written -> plugin permanently inert).
|
|
625
|
+
exempt_commands = {"ensure-health", "consent", "v5"}
|
|
626
|
+
is_exempt = any(arg in exempt_commands for arg in script_args[:2])
|
|
627
|
+
# The consolidated UserPromptSubmit runner is dispatched as
|
|
628
|
+
# `run.py hooks/userpromptsubmit_runner.py` with NO trailing args, so
|
|
629
|
+
# script_args=[] and the exempt_commands check above never matches it. The
|
|
630
|
+
# runner contains the ensure-health bootstrap itself, so it MUST be let
|
|
631
|
+
# through this consent gate even when consent is False; the runner then
|
|
632
|
+
# makes the per-subcommand consent decision internally (ensure-health
|
|
633
|
+
# bootstraps the flags, the other five skip until consent is True). Without
|
|
634
|
+
# this exemption the runner is never dispatched when consent is False ->
|
|
635
|
+
# ensure-health never fires -> v5_welcome_shown / enterprise_consent_shown
|
|
636
|
+
# never written -> consent False FOREVER -> all six subcommands permanently
|
|
637
|
+
# dead. Latent on native Claude Code (SessionStart bootstraps consent
|
|
638
|
+
# out-of-band), FATAL on Cowork (no SessionStart hook).
|
|
639
|
+
# Same reasoning for the consolidated SessionStart dispatcher. Before
|
|
640
|
+
# consolidation the `ensure-health --once-mark` SessionStart entry matched
|
|
641
|
+
# exempt_commands on its literal arg and bootstrapped the consent flags;
|
|
642
|
+
# the runner is dispatched as `run.py hooks/sessionstart_runner.py` with no
|
|
643
|
+
# args, so it must be let through here and makes the per-subcommand consent
|
|
644
|
+
# decision internally (ensure-health bootstraps, the other four skip until
|
|
645
|
+
# consent is True).
|
|
646
|
+
if script_rel in ("hooks/userpromptsubmit_runner.py",
|
|
647
|
+
"hooks/sessionstart_runner.py"):
|
|
648
|
+
is_exempt = True
|
|
649
|
+
if not is_exempt and not _check_consent(root_resolved):
|
|
650
|
+
return 0
|
|
651
|
+
|
|
652
|
+
# Force UTF-8 in every dispatched script regardless of the host locale, so
|
|
653
|
+
# non-ASCII session paths / transcript content (Hebrew, CJK, accented names)
|
|
654
|
+
# never crash a hook with UnicodeDecode/EncodeError. PYTHONUTF8 also makes the
|
|
655
|
+
# child's default open() encoding UTF-8; PYTHONIOENCODING covers its std streams.
|
|
656
|
+
child_env = {**os.environ, "PYTHONUTF8": "1", "PYTHONIOENCODING": "utf-8"}
|
|
657
|
+
if stale_plugin_root:
|
|
658
|
+
# The handler and everything it imports resolve paths from this too.
|
|
659
|
+
child_env["CLAUDE_PLUGIN_ROOT"] = str(root_resolved)
|
|
660
|
+
# The child (and every detached worker it spawns) inherits the bytecode
|
|
661
|
+
# prefix chosen at the top of main(), so no __pycache__ lands in a repo.
|
|
662
|
+
_apply_bytecode_prefix(_pycache_prefix, child_env)
|
|
663
|
+
|
|
664
|
+
# Hot-path latency: resolve the runtime HERE and hand the
|
|
665
|
+
# answer to the child via TOKEN_OPTIMIZER_RUNTIME, the override tier
|
|
666
|
+
# detect_runtime() already honors (the Copilot hook bridge uses the same
|
|
667
|
+
# mechanism). Without this, runtime detection runs twice per hook event —
|
|
668
|
+
# once in this process (during _check_consent's plugin_env import) and once
|
|
669
|
+
# in the child (during its own plugin_env import) — and each run pays the
|
|
670
|
+
# OpenCode ancestor `ps` scan (~100 ms measured). This process's parent is
|
|
671
|
+
# the long-lived host CLI, so runtime_env's negative-result ancestor cache
|
|
672
|
+
# (keyed by parent pid) makes the scan here near-free after the first hook
|
|
673
|
+
# of a session; the child's parent is this ephemeral process, so its cache
|
|
674
|
+
# can never hit and the export is the only way to spare it. The exported
|
|
675
|
+
# value IS detect_runtime()'s own resolution for this env — the child's
|
|
676
|
+
# process tree adds only this dispatcher and its child, never an
|
|
677
|
+
# opencode/copilot ancestor, so the child would always resolve identically.
|
|
678
|
+
# Fail-open: any error here leaves the child to detect normally.
|
|
679
|
+
try:
|
|
680
|
+
_scripts_dir = root_resolved / "skills" / "token-optimizer" / "scripts"
|
|
681
|
+
if _scripts_dir.is_dir():
|
|
682
|
+
if str(_scripts_dir) not in sys.path:
|
|
683
|
+
sys.path.insert(0, str(_scripts_dir))
|
|
684
|
+
import runtime_env as _runtime_env
|
|
685
|
+
|
|
686
|
+
child_env["TOKEN_OPTIMIZER_RUNTIME"] = _runtime_env.detect_runtime()
|
|
687
|
+
except Exception:
|
|
688
|
+
pass
|
|
689
|
+
|
|
690
|
+
proc = None
|
|
691
|
+
global _child_proc
|
|
692
|
+
# Install SIGTERM/SIGINT handlers BEFORE spawning the child so an external
|
|
693
|
+
# kill from Claude Code reaps the whole child process group instead of
|
|
694
|
+
# orphaning the grandchild. On Windows this is best effort: Popen.wait()
|
|
695
|
+
# cannot be interrupted by a Python handler (it runs once the wait
|
|
696
|
+
# returns) and an external TerminateProcess from the host bypasses Python
|
|
697
|
+
# handlers entirely.
|
|
698
|
+
signal.signal(signal.SIGTERM, _forward_and_exit)
|
|
699
|
+
signal.signal(signal.SIGINT, _forward_and_exit)
|
|
700
|
+
try:
|
|
701
|
+
# start_new_session=True puts the child in its own process group so a
|
|
702
|
+
# timeout/external kill can reap the whole group (grandchildren included)
|
|
703
|
+
# via os.killpg. On POSIX do NOT add stdout=/stderr=/stdin= here:
|
|
704
|
+
# several hooks inject via stdout and MUST inherit run.py's stdio.
|
|
705
|
+
# On Windows, start_new_session is a no-op; use DETACHED_PROCESS so the
|
|
706
|
+
# child allocates NO console at all. CREATE_NO_WINDOW only hides the
|
|
707
|
+
# console -- it still spawns conhost.exe, which on Windows 11 25H2
|
|
708
|
+
# leaks a kernel token reference per hook run (issue #215). Do NOT add
|
|
709
|
+
# CREATE_NEW_PROCESS_GROUP (inert for reaping here since run.py never
|
|
710
|
+
# sends GenerateConsoleCtrlEvent). A detached child has no console, so
|
|
711
|
+
# it never sees Ctrl+C either, and its stdio MUST arrive via the three
|
|
712
|
+
# explicit handles _windows_stdio_kwargs() adds (CPython passes them
|
|
713
|
+
# via STARTF_USESTDHANDLES) -- without them the child's std handles
|
|
714
|
+
# bind to NULL and every byte a hook writes to stdout would be
|
|
715
|
+
# silently discarded.
|
|
716
|
+
_popen_kwargs = dict(env=child_env)
|
|
717
|
+
if os.name == "nt":
|
|
718
|
+
_flags = getattr(subprocess, "DETACHED_PROCESS", 0)
|
|
719
|
+
if _flags:
|
|
720
|
+
_popen_kwargs["creationflags"] = _flags
|
|
721
|
+
_popen_kwargs.update(_windows_stdio_kwargs())
|
|
722
|
+
else:
|
|
723
|
+
_popen_kwargs["start_new_session"] = True
|
|
724
|
+
proc = subprocess.Popen(cmd, **_popen_kwargs)
|
|
725
|
+
_child_proc = proc
|
|
726
|
+
if os.name != "nt":
|
|
727
|
+
# POSIX: a blocking waitpid returns the instant the child exits.
|
|
728
|
+
# Popen.wait(timeout=...) instead busy-polls with sleeps that double
|
|
729
|
+
# up to 50 ms, so a hook that finished at 83 ms was only noticed
|
|
730
|
+
# at ~137 ms; every hook on every tool call paid that overshoot.
|
|
731
|
+
# The ceiling moves to a daemon timer that reaps the child's
|
|
732
|
+
# process group, which makes the blocking wait return. _reap's
|
|
733
|
+
# poll() takes the waitpid lock non-blocking, so it cannot deadlock
|
|
734
|
+
# against this wait. SIGTERM/SIGINT still interrupt the wait and
|
|
735
|
+
# run _forward_and_exit (PEP 475 runs handlers before retrying).
|
|
736
|
+
import threading
|
|
737
|
+
|
|
738
|
+
def _timeout_reap():
|
|
739
|
+
try:
|
|
740
|
+
_reap(proc, signal.SIGKILL)
|
|
741
|
+
except Exception:
|
|
742
|
+
pass
|
|
743
|
+
|
|
744
|
+
reaper = threading.Timer(_CHILD_WAIT_TIMEOUT_S, _timeout_reap)
|
|
745
|
+
reaper.daemon = True
|
|
746
|
+
reaper.start()
|
|
747
|
+
try:
|
|
748
|
+
proc.wait()
|
|
749
|
+
finally:
|
|
750
|
+
reaper.cancel()
|
|
751
|
+
return 0
|
|
752
|
+
try:
|
|
753
|
+
proc.wait(timeout=_CHILD_WAIT_TIMEOUT_S)
|
|
754
|
+
except subprocess.TimeoutExpired:
|
|
755
|
+
# Important: Popen.wait doesn't auto-kill on timeout. Leaving
|
|
756
|
+
# the child alive would leak a process holding the trends.db
|
|
757
|
+
# SQLite lock, starving the next hook invocation. _reap handles
|
|
758
|
+
# the nt/posix split (see _reap docstring).
|
|
759
|
+
try:
|
|
760
|
+
# signal.SIGKILL does not exist on Windows (AttributeError
|
|
761
|
+
# at the call site, before _reap even runs). Use getattr so
|
|
762
|
+
# the nt branch of _reap (which ignores posix_sig) is never
|
|
763
|
+
# blocked by a missing attribute. POSIX has SIGKILL.
|
|
764
|
+
_reap(proc, getattr(signal, "SIGKILL", signal.SIGTERM))
|
|
765
|
+
proc.wait(timeout=5)
|
|
766
|
+
except (subprocess.SubprocessError, OSError):
|
|
767
|
+
pass
|
|
768
|
+
except (subprocess.SubprocessError, OSError) as exc:
|
|
769
|
+
if proc is not None:
|
|
770
|
+
try:
|
|
771
|
+
proc.kill()
|
|
772
|
+
except (subprocess.SubprocessError, OSError):
|
|
773
|
+
pass
|
|
774
|
+
else:
|
|
775
|
+
# Popen itself failed: the hook did not run. Leave one line in the
|
|
776
|
+
# diagnostics log (never stderr, which the host feeds to the model).
|
|
777
|
+
try:
|
|
778
|
+
_consent_log_diagnostics(
|
|
779
|
+
f"[Token Optimizer] run.py: Popen failed for {script_rel!r}: "
|
|
780
|
+
f"{type(exc).__name__}: {' '.join(str(exc).split())[:200]}\n"
|
|
781
|
+
)
|
|
782
|
+
except Exception:
|
|
783
|
+
pass
|
|
784
|
+
return 0
|
|
785
|
+
|
|
786
|
+
|
|
787
|
+
if __name__ == "__main__":
|
|
788
|
+
sys.exit(main())
|