@alexgreensh/token-optimizer 0.0.0-stage → 5.13.50

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.
Files changed (161) hide show
  1. package/.claude-plugin/marketplace.json +76 -0
  2. package/.claude-plugin/plugin.json +21 -0
  3. package/LICENSE +130 -0
  4. package/LICENSE-SMALL-BUSINESS.md +62 -0
  5. package/PRIVACY.md +200 -0
  6. package/README.md +13 -2
  7. package/hooks/codex-hooks.json +4 -0
  8. package/hooks/hooks.json +182 -0
  9. package/hooks/module_runner.py +149 -0
  10. package/hooks/posttooluse_runner.py +1110 -0
  11. package/hooks/python-launcher.sh +816 -0
  12. package/hooks/run.py +776 -0
  13. package/hooks/sessionstart_runner.py +629 -0
  14. package/hooks/stop_runner.py +408 -0
  15. package/hooks/userpromptsubmit_runner.py +722 -0
  16. package/hooks/windows-launcher.py +163 -0
  17. package/install-cloud.sh +23 -0
  18. package/package.json +29 -4
  19. package/skills/fleet-auditor/SKILL.md +150 -0
  20. package/skills/fleet-auditor/references/fleet-systems.md +167 -0
  21. package/skills/fleet-auditor/references/report-template.md +50 -0
  22. package/skills/fleet-auditor/references/waste-patterns.md +126 -0
  23. package/skills/fleet-auditor/scripts/fleet.py +3612 -0
  24. package/skills/fleet-auditor/scripts/shared.py +277 -0
  25. package/skills/resume-checkpoint/SKILL.md +52 -0
  26. package/skills/resume-checkpoint/scripts/pull_checkpoint.py +188 -0
  27. package/skills/token-coach/SKILL.md +129 -0
  28. package/skills/token-coach/assets/coach-dashboard-tab.html +45 -0
  29. package/skills/token-coach/examples/coaching-session-agentic.md +62 -0
  30. package/skills/token-coach/examples/coaching-session-heavy-setup.md +46 -0
  31. package/skills/token-coach/examples/coaching-session-new-project.md +38 -0
  32. package/skills/token-coach/references/agentic-systems.md +147 -0
  33. package/skills/token-coach/references/coach-patterns.md +120 -0
  34. package/skills/token-coach/references/coaching-scripts.md +146 -0
  35. package/skills/token-coach/references/deterministic-stages.md +102 -0
  36. package/skills/token-coach/references/keepwarm-consent.md +48 -0
  37. package/skills/token-coach/references/quick-reference.md +155 -0
  38. package/skills/token-dashboard/SKILL.md +72 -0
  39. package/skills/token-optimizer/SKILL.md +150 -0
  40. package/skills/token-optimizer/assets/dashboard.html +7251 -0
  41. package/skills/token-optimizer/examples/claude-md-optimized.md +40 -0
  42. package/skills/token-optimizer/examples/hooks-starter.json +179 -0
  43. package/skills/token-optimizer/examples/permissions-deny-template.json +24 -0
  44. package/skills/token-optimizer/pricing/prices.json +695 -0
  45. package/skills/token-optimizer/references/agent-prompts.md +687 -0
  46. package/skills/token-optimizer/references/cli-reference.md +92 -0
  47. package/skills/token-optimizer/references/codex-workflow.md +188 -0
  48. package/skills/token-optimizer/references/cursor-workflow.md +74 -0
  49. package/skills/token-optimizer/references/error-recovery.md +37 -0
  50. package/skills/token-optimizer/references/implementation-playbook.md +416 -0
  51. package/skills/token-optimizer/references/keepwarm-consent.md +48 -0
  52. package/skills/token-optimizer/references/opencode-workflow.md +72 -0
  53. package/skills/token-optimizer/references/optimization-checklist.md +714 -0
  54. package/skills/token-optimizer/references/phase0-setup.md +142 -0
  55. package/skills/token-optimizer/references/presentation-workflow.md +72 -0
  56. package/skills/token-optimizer/references/session-continuity.md +19 -0
  57. package/skills/token-optimizer/references/token-flow-architecture.md +629 -0
  58. package/skills/token-optimizer/scripts/activity_tracker.py +143 -0
  59. package/skills/token-optimizer/scripts/antigravity_doctor.py +548 -0
  60. package/skills/token-optimizer/scripts/antigravity_hook_bridge.py +511 -0
  61. package/skills/token-optimizer/scripts/antigravity_install.py +376 -0
  62. package/skills/token-optimizer/scripts/antigravity_proto.py +413 -0
  63. package/skills/token-optimizer/scripts/antigravity_session.py +346 -0
  64. package/skills/token-optimizer/scripts/antigravity_state.py +486 -0
  65. package/skills/token-optimizer/scripts/archive_result.py +1725 -0
  66. package/skills/token-optimizer/scripts/bash_compress.py +2490 -0
  67. package/skills/token-optimizer/scripts/bash_compress_hook.py +766 -0
  68. package/skills/token-optimizer/scripts/bash_hook.py +61 -0
  69. package/skills/token-optimizer/scripts/bash_whitelist.py +243 -0
  70. package/skills/token-optimizer/scripts/benchmark.py +1765 -0
  71. package/skills/token-optimizer/scripts/build_output_compress.py +776 -0
  72. package/skills/token-optimizer/scripts/cloud_kit.py +991 -0
  73. package/skills/token-optimizer/scripts/codex_command_compress.py +434 -0
  74. package/skills/token-optimizer/scripts/codex_compact_prompt.py +273 -0
  75. package/skills/token-optimizer/scripts/codex_doctor.py +454 -0
  76. package/skills/token-optimizer/scripts/codex_hook_bridge.py +311 -0
  77. package/skills/token-optimizer/scripts/codex_install.py +810 -0
  78. package/skills/token-optimizer/scripts/codex_io.py +119 -0
  79. package/skills/token-optimizer/scripts/codex_log_index.py +219 -0
  80. package/skills/token-optimizer/scripts/codex_models.py +34 -0
  81. package/skills/token-optimizer/scripts/codex_session.py +1186 -0
  82. package/skills/token-optimizer/scripts/codex_state.py +707 -0
  83. package/skills/token-optimizer/scripts/codex_statusline.py +303 -0
  84. package/skills/token-optimizer/scripts/command_filters.py +386 -0
  85. package/skills/token-optimizer/scripts/compression_backfill.py +600 -0
  86. package/skills/token-optimizer/scripts/compression_log.py +230 -0
  87. package/skills/token-optimizer/scripts/context_intel.py +331 -0
  88. package/skills/token-optimizer/scripts/context_pressure.py +115 -0
  89. package/skills/token-optimizer/scripts/copilot_doctor.py +406 -0
  90. package/skills/token-optimizer/scripts/copilot_hook_bridge.py +709 -0
  91. package/skills/token-optimizer/scripts/copilot_install.py +277 -0
  92. package/skills/token-optimizer/scripts/copilot_session.py +496 -0
  93. package/skills/token-optimizer/scripts/copilot_state.py +569 -0
  94. package/skills/token-optimizer/scripts/copilot_vscode.py +832 -0
  95. package/skills/token-optimizer/scripts/cowork_doctor.py +270 -0
  96. package/skills/token-optimizer/scripts/cowork_install.py +380 -0
  97. package/skills/token-optimizer/scripts/credential_patterns.py +1514 -0
  98. package/skills/token-optimizer/scripts/cursor_doctor.py +602 -0
  99. package/skills/token-optimizer/scripts/cursor_hook_bridge.py +843 -0
  100. package/skills/token-optimizer/scripts/cursor_install.py +423 -0
  101. package/skills/token-optimizer/scripts/cursor_session.py +303 -0
  102. package/skills/token-optimizer/scripts/cursor_state.py +348 -0
  103. package/skills/token-optimizer/scripts/delta_diff.py +110 -0
  104. package/skills/token-optimizer/scripts/detectors/__init__.py +2 -0
  105. package/skills/token-optimizer/scripts/detectors/bad_decomposition.py +78 -0
  106. package/skills/token-optimizer/scripts/detectors/cache_instability.py +504 -0
  107. package/skills/token-optimizer/scripts/detectors/looping.py +88 -0
  108. package/skills/token-optimizer/scripts/detectors/output_waste.py +143 -0
  109. package/skills/token-optimizer/scripts/detectors/overpowered.py +116 -0
  110. package/skills/token-optimizer/scripts/detectors/pdf_ingestion.py +52 -0
  111. package/skills/token-optimizer/scripts/detectors/registry.py +65 -0
  112. package/skills/token-optimizer/scripts/detectors/respond_to_bash.py +76 -0
  113. package/skills/token-optimizer/scripts/detectors/retry_churn.py +83 -0
  114. package/skills/token-optimizer/scripts/detectors/tool_cascade.py +62 -0
  115. package/skills/token-optimizer/scripts/detectors/wasteful_thinking.py +75 -0
  116. package/skills/token-optimizer/scripts/detectors/weak_model.py +55 -0
  117. package/skills/token-optimizer/scripts/detectors/websearch_routing.py +72 -0
  118. package/skills/token-optimizer/scripts/deterministic_candidates.py +1458 -0
  119. package/skills/token-optimizer/scripts/devin_compress.py +790 -0
  120. package/skills/token-optimizer/scripts/devin_doctor.py +403 -0
  121. package/skills/token-optimizer/scripts/devin_hooks.py +453 -0
  122. package/skills/token-optimizer/scripts/devin_install.py +1086 -0
  123. package/skills/token-optimizer/scripts/devin_source.py +119 -0
  124. package/skills/token-optimizer/scripts/devin_state.py +330 -0
  125. package/skills/token-optimizer/scripts/devin_verify.py +67 -0
  126. package/skills/token-optimizer/scripts/grok_doctor.py +560 -0
  127. package/skills/token-optimizer/scripts/grok_hook_bridge.py +699 -0
  128. package/skills/token-optimizer/scripts/grok_install.py +397 -0
  129. package/skills/token-optimizer/scripts/grok_session.py +317 -0
  130. package/skills/token-optimizer/scripts/grok_state.py +299 -0
  131. package/skills/token-optimizer/scripts/hermes_doctor.py +479 -0
  132. package/skills/token-optimizer/scripts/hermes_hook_bridge.py +285 -0
  133. package/skills/token-optimizer/scripts/hermes_install.py +668 -0
  134. package/skills/token-optimizer/scripts/hermes_session.py +691 -0
  135. package/skills/token-optimizer/scripts/hermes_state.py +448 -0
  136. package/skills/token-optimizer/scripts/hook_io.py +120 -0
  137. package/skills/token-optimizer/scripts/hook_runtime.py +713 -0
  138. package/skills/token-optimizer/scripts/injection.py +156 -0
  139. package/skills/token-optimizer/scripts/install_reconcile.py +952 -0
  140. package/skills/token-optimizer/scripts/measure.py +58739 -0
  141. package/skills/token-optimizer/scripts/outline.py +53 -0
  142. package/skills/token-optimizer/scripts/pipeline_analyzer.py +723 -0
  143. package/skills/token-optimizer/scripts/plugin_env.py +562 -0
  144. package/skills/token-optimizer/scripts/py_trust.py +80 -0
  145. package/skills/token-optimizer/scripts/quality_cache_gate.py +320 -0
  146. package/skills/token-optimizer/scripts/read_cache.py +2489 -0
  147. package/skills/token-optimizer/scripts/recovery_output.py +110 -0
  148. package/skills/token-optimizer/scripts/refetch_fingerprint.py +236 -0
  149. package/skills/token-optimizer/scripts/refetch_guard.py +244 -0
  150. package/skills/token-optimizer/scripts/routing_advisor.py +389 -0
  151. package/skills/token-optimizer/scripts/runtime_env.py +1893 -0
  152. package/skills/token-optimizer/scripts/session_store.py +979 -0
  153. package/skills/token-optimizer/scripts/spawn_utils.py +122 -0
  154. package/skills/token-optimizer/scripts/statusline.js +660 -0
  155. package/skills/token-optimizer/scripts/structure_map.py +2880 -0
  156. package/skills/token-optimizer/scripts/structure_map_ts.py +676 -0
  157. package/skills/token-optimizer/scripts/structure_replay.py +1556 -0
  158. package/skills/token-optimizer/scripts/thrash_guard.py +604 -0
  159. package/skills/token-optimizer/scripts/token_estimate.py +80 -0
  160. package/skills/token-optimizer/scripts/tool_search_diagnostic.py +61 -0
  161. package/skills/token-optimizer/scripts/utf8_io.py +219 -0
@@ -0,0 +1,182 @@
1
+ {
2
+ "modules": [
3
+ "../desktop/token-optimizer-desktop/hooks/register.tsx"
4
+ ],
5
+ "hooks": {
6
+ "PreToolUse": [
7
+ {
8
+ "matcher": "Read",
9
+ "hooks": [
10
+ {
11
+ "type": "command",
12
+ "command": "for b in bash /bin/bash /usr/bin/bash /usr/local/bin/bash /opt/homebrew/bin/bash; do command -v \"$b\" >/dev/null 2>&1 || continue; L=\"${CLAUDE_PLUGIN_ROOT}/hooks/python-launcher.sh\"; [ -r \"$L\" ] || exit 0; exec \"$b\" \"$L\" \"${CLAUDE_PLUGIN_ROOT}/hooks/run.py\" skills/token-optimizer/scripts/read_cache.py --quiet; done; exit 0",
13
+ "timeout": 10
14
+ }
15
+ ]
16
+ },
17
+ {
18
+ "matcher": "Bash",
19
+ "hooks": [
20
+ {
21
+ "type": "command",
22
+ "command": "for b in bash /bin/bash /usr/bin/bash /usr/local/bin/bash /opt/homebrew/bin/bash; do command -v \"$b\" >/dev/null 2>&1 || continue; L=\"${CLAUDE_PLUGIN_ROOT}/hooks/python-launcher.sh\"; [ -r \"$L\" ] || exit 0; exec \"$b\" \"$L\" \"${CLAUDE_PLUGIN_ROOT}/hooks/run.py\" skills/token-optimizer/scripts/bash_hook.py --quiet; done; exit 0",
23
+ "timeout": 10
24
+ }
25
+ ]
26
+ },
27
+ {
28
+ "matcher": "Agent|Task",
29
+ "hooks": [
30
+ {
31
+ "type": "command",
32
+ "command": "for b in bash /bin/bash /usr/bin/bash /usr/local/bin/bash /opt/homebrew/bin/bash; do command -v \"$b\" >/dev/null 2>&1 || continue; L=\"${CLAUDE_PLUGIN_ROOT}/hooks/python-launcher.sh\"; [ -r \"$L\" ] || exit 0; exec \"$b\" \"$L\" \"${CLAUDE_PLUGIN_ROOT}/hooks/run.py\" skills/token-optimizer/scripts/measure.py checkpoint-trigger --milestone pre-fanout --quiet; done; exit 0",
33
+ "async": true,
34
+ "timeout": 20
35
+ }
36
+ ]
37
+ },
38
+ {
39
+ "matcher": "mcp__.*",
40
+ "hooks": [
41
+ {
42
+ "type": "command",
43
+ "command": "for b in bash /bin/bash /usr/bin/bash /usr/local/bin/bash /opt/homebrew/bin/bash; do command -v \"$b\" >/dev/null 2>&1 || continue; L=\"${CLAUDE_PLUGIN_ROOT}/hooks/python-launcher.sh\"; [ -r \"$L\" ] || exit 0; exec \"$b\" \"$L\" \"${CLAUDE_PLUGIN_ROOT}/hooks/run.py\" skills/token-optimizer/scripts/refetch_guard.py --quiet; done; exit 0",
44
+ "timeout": 10
45
+ }
46
+ ]
47
+ }
48
+ ],
49
+ "PreCompact": [
50
+ {
51
+ "hooks": [
52
+ {
53
+ "type": "command",
54
+ "command": "for b in bash /bin/bash /usr/bin/bash /usr/local/bin/bash /opt/homebrew/bin/bash; do command -v \"$b\" >/dev/null 2>&1 || continue; L=\"${CLAUDE_PLUGIN_ROOT}/hooks/python-launcher.sh\"; [ -r \"$L\" ] || exit 0; exec \"$b\" \"$L\" \"${CLAUDE_PLUGIN_ROOT}/hooks/run.py\" skills/token-optimizer/scripts/measure.py dynamic-compact-instructions --quiet; done; exit 0",
55
+ "timeout": 20
56
+ }
57
+ ]
58
+ },
59
+ {
60
+ "hooks": [
61
+ {
62
+ "type": "command",
63
+ "command": "for b in bash /bin/bash /usr/bin/bash /usr/local/bin/bash /opt/homebrew/bin/bash; do command -v \"$b\" >/dev/null 2>&1 || continue; L=\"${CLAUDE_PLUGIN_ROOT}/hooks/python-launcher.sh\"; [ -r \"$L\" ] || exit 0; exec \"$b\" \"$L\" \"${CLAUDE_PLUGIN_ROOT}/hooks/run.py\" skills/token-optimizer/scripts/measure.py compact-capture --trigger auto --quiet; done; exit 0",
64
+ "async": true,
65
+ "timeout": 30
66
+ }
67
+ ]
68
+ },
69
+ {
70
+ "hooks": [
71
+ {
72
+ "type": "command",
73
+ "command": "for b in bash /bin/bash /usr/bin/bash /usr/local/bin/bash /opt/homebrew/bin/bash; do command -v \"$b\" >/dev/null 2>&1 || continue; L=\"${CLAUDE_PLUGIN_ROOT}/hooks/python-launcher.sh\"; [ -r \"$L\" ] || exit 0; exec \"$b\" \"$L\" \"${CLAUDE_PLUGIN_ROOT}/hooks/run.py\" skills/token-optimizer/scripts/read_cache.py --clear --quiet; done; exit 0",
74
+ "timeout": 10
75
+ }
76
+ ]
77
+ }
78
+ ],
79
+ "SessionStart": [
80
+ {
81
+ "hooks": [
82
+ {
83
+ "type": "command",
84
+ "command": "for b in bash /bin/bash /usr/bin/bash /usr/local/bin/bash /opt/homebrew/bin/bash; do command -v \"$b\" >/dev/null 2>&1 || continue; L=\"${CLAUDE_PLUGIN_ROOT}/hooks/python-launcher.sh\"; [ -r \"$L\" ] || exit 0; exec \"$b\" \"$L\" \"${CLAUDE_PLUGIN_ROOT}/hooks/run.py\" hooks/sessionstart_runner.py; done; exit 0",
85
+ "timeout": 20
86
+ }
87
+ ]
88
+ }
89
+ ],
90
+ "Stop": [
91
+ {
92
+ "hooks": [
93
+ {
94
+ "type": "command",
95
+ "command": "for b in bash /bin/bash /usr/bin/bash /usr/local/bin/bash /opt/homebrew/bin/bash; do command -v \"$b\" >/dev/null 2>&1 || continue; L=\"${CLAUDE_PLUGIN_ROOT}/hooks/python-launcher.sh\"; [ -r \"$L\" ] || exit 0; exec \"$b\" \"$L\" \"${CLAUDE_PLUGIN_ROOT}/hooks/run.py\" hooks/stop_runner.py; done; exit 0",
96
+ "timeout": 15
97
+ }
98
+ ]
99
+ }
100
+ ],
101
+ "SessionEnd": [
102
+ {
103
+ "hooks": [
104
+ {
105
+ "type": "command",
106
+ "command": "for b in bash /bin/bash /usr/bin/bash /usr/local/bin/bash /opt/homebrew/bin/bash; do command -v \"$b\" >/dev/null 2>&1 || continue; L=\"${CLAUDE_PLUGIN_ROOT}/hooks/python-launcher.sh\"; [ -r \"$L\" ] || exit 0; exec \"$b\" \"$L\" \"${CLAUDE_PLUGIN_ROOT}/hooks/run.py\" hooks/stop_runner.py; done; exit 0",
107
+ "async": true,
108
+ "timeout": 60
109
+ }
110
+ ]
111
+ }
112
+ ],
113
+ "StopFailure": [
114
+ {
115
+ "hooks": [
116
+ {
117
+ "type": "command",
118
+ "command": "for b in bash /bin/bash /usr/bin/bash /usr/local/bin/bash /opt/homebrew/bin/bash; do command -v \"$b\" >/dev/null 2>&1 || continue; L=\"${CLAUDE_PLUGIN_ROOT}/hooks/python-launcher.sh\"; [ -r \"$L\" ] || exit 0; exec \"$b\" \"$L\" \"${CLAUDE_PLUGIN_ROOT}/hooks/run.py\" skills/token-optimizer/scripts/measure.py compact-capture --trigger stop-failure --quiet; done; exit 0",
119
+ "timeout": 12
120
+ }
121
+ ]
122
+ }
123
+ ],
124
+ "UserPromptSubmit": [
125
+ {
126
+ "hooks": [
127
+ {
128
+ "type": "command",
129
+ "command": "for b in bash /bin/bash /usr/bin/bash /usr/local/bin/bash /opt/homebrew/bin/bash; do command -v \"$b\" >/dev/null 2>&1 || continue; L=\"${CLAUDE_PLUGIN_ROOT}/hooks/python-launcher.sh\"; [ -r \"$L\" ] || exit 0; exec \"$b\" \"$L\" \"${CLAUDE_PLUGIN_ROOT}/hooks/run.py\" hooks/userpromptsubmit_runner.py; done; exit 0",
130
+ "timeout": 20
131
+ }
132
+ ]
133
+ }
134
+ ],
135
+ "PostToolUse": [
136
+ {
137
+ "matcher": "Bash|PowerShell|Read|Glob|Grep|Agent|Edit|Write|MultiEdit|NotebookEdit|mcp__.*",
138
+ "hooks": [
139
+ {
140
+ "type": "command",
141
+ "command": "for b in bash /bin/bash /usr/bin/bash /usr/local/bin/bash /opt/homebrew/bin/bash; do command -v \"$b\" >/dev/null 2>&1 || continue; L=\"${CLAUDE_PLUGIN_ROOT}/hooks/python-launcher.sh\"; [ -r \"$L\" ] || exit 0; exec \"$b\" \"$L\" \"${CLAUDE_PLUGIN_ROOT}/hooks/run.py\" hooks/posttooluse_runner.py; done; exit 0",
142
+ "timeout": 10
143
+ }
144
+ ]
145
+ }
146
+ ],
147
+ "PostToolUseFailure": [
148
+ {
149
+ "matcher": "Bash|PowerShell",
150
+ "hooks": [
151
+ {
152
+ "type": "command",
153
+ "command": "for b in bash /bin/bash /usr/bin/bash /usr/local/bin/bash /opt/homebrew/bin/bash; do command -v \"$b\" >/dev/null 2>&1 || continue; L=\"${CLAUDE_PLUGIN_ROOT}/hooks/python-launcher.sh\"; [ -r \"$L\" ] || exit 0; exec \"$b\" \"$L\" \"${CLAUDE_PLUGIN_ROOT}/hooks/run.py\" hooks/posttooluse_runner.py; done; exit 0",
154
+ "timeout": 10
155
+ }
156
+ ]
157
+ }
158
+ ],
159
+ "PostCompact": [
160
+ {
161
+ "hooks": [
162
+ {
163
+ "type": "command",
164
+ "command": "for b in bash /bin/bash /usr/bin/bash /usr/local/bin/bash /opt/homebrew/bin/bash; do command -v \"$b\" >/dev/null 2>&1 || continue; L=\"${CLAUDE_PLUGIN_ROOT}/hooks/python-launcher.sh\"; [ -r \"$L\" ] || exit 0; exec \"$b\" \"$L\" \"${CLAUDE_PLUGIN_ROOT}/hooks/run.py\" skills/token-optimizer/scripts/measure.py quality-cache --force --quiet; done; exit 0",
165
+ "timeout": 20
166
+ }
167
+ ]
168
+ }
169
+ ],
170
+ "CwdChanged": [
171
+ {
172
+ "hooks": [
173
+ {
174
+ "type": "command",
175
+ "command": "for b in bash /bin/bash /usr/bin/bash /usr/local/bin/bash /opt/homebrew/bin/bash; do command -v \"$b\" >/dev/null 2>&1 || continue; L=\"${CLAUDE_PLUGIN_ROOT}/hooks/python-launcher.sh\"; [ -r \"$L\" ] || exit 0; exec \"$b\" \"$L\" \"${CLAUDE_PLUGIN_ROOT}/hooks/run.py\" skills/token-optimizer/scripts/read_cache.py --clear --quiet; done; exit 0",
176
+ "timeout": 10
177
+ }
178
+ ]
179
+ }
180
+ ]
181
+ }
182
+ }
@@ -0,0 +1,149 @@
1
+ #!/usr/bin/env python3
2
+ """Runs a hook script as a module instead of as `__main__`, so CPython reuses
3
+ its __pycache__ bytecode across invocations.
4
+
5
+ Script-mode execution (`python foo.py`) never checks or writes __pycache__ for
6
+ the file being run as __main__ -- only for things it imports. Since every hook
7
+ call is a fresh process, running measure.py (35k+ lines) as a script recompiles
8
+ it from source every single time: ~0.3s of pure CPython parse/compile on top of
9
+ whatever the hook actually does. Module-mode goes through the import system,
10
+ which does check/write __pycache__, cutting that to ~0.1s after the first call.
11
+
12
+ sys.path is stripped of '' and '.' (the cwd-equivalent entries the interpreter
13
+ would otherwise add) before inserting scripts_dir explicitly, so a same-named
14
+ file in the invoking project's own working directory (e.g. a project that
15
+ happens to have its own measure.py at its root) can never shadow the plugin's
16
+ module.
17
+ """
18
+ from __future__ import annotations
19
+
20
+ import os
21
+ import runpy
22
+ import sys
23
+
24
+
25
+ def _warn_readonly_scripts_dir_once(scripts_dir: str) -> None:
26
+ """If scripts_dir isn't writable, __pycache__ can't be written and CPython
27
+ recompiles the target from source on every call — the perf win silently
28
+ evaporates. Surface it, but at most once per day per user so we don't spam
29
+ stderr on the per-tool-call hot path. The marker lives in the OS temp dir
30
+ (writable even when the plugin install dir is read-only, which is the whole
31
+ failure mode). Best-effort: any error here must never break the hook."""
32
+ try:
33
+ if getattr(sys, "pycache_prefix", None):
34
+ return # bytecode goes to a cache prefix, scripts_dir needn't be writable
35
+ if os.access(scripts_dir, os.W_OK):
36
+ return # normal case — bytecode cache works, stay silent
37
+ import hashlib
38
+ import tempfile
39
+ import time
40
+
41
+ tag = hashlib.sha1(scripts_dir.encode("utf-8", "replace")).hexdigest()[:12]
42
+ marker = os.path.join(tempfile.gettempdir(), f".token-optimizer-ro-pyc-{tag}")
43
+ try:
44
+ fresh = (time.time() - os.path.getmtime(marker)) < 86400
45
+ except OSError:
46
+ fresh = False
47
+ if fresh:
48
+ return
49
+ # This marker lives at a predictable, world-shared temp path, so another
50
+ # local user can pre-plant something hostile there (CWE-377). Defend
51
+ # against all of it: unlink any existing entry first (drops a planted
52
+ # symlink, FIFO, or hardlink by name -- a hardlink's target is left
53
+ # untouched), then create our own EXCLUSIVELY. O_EXCL means we only ever
54
+ # open a file we just created; O_NOFOLLOW + O_NONBLOCK close the tiny
55
+ # unlink->open race (a re-planted symlink fails ELOOP, a re-planted FIFO
56
+ # fails ENXIO instead of blocking the hook forever). Every failure here
57
+ # is swallowed by the outer `except Exception` -> the hook stays
58
+ # fail-open and just skips the once-a-day warning. O_NOFOLLOW/O_NONBLOCK
59
+ # are absent on Windows; the getattr fallback of 0 makes them no-ops.
60
+ try:
61
+ os.unlink(marker)
62
+ except OSError:
63
+ pass
64
+ flags = (os.O_WRONLY | os.O_CREAT | os.O_EXCL
65
+ | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_NONBLOCK", 0))
66
+ fd = os.open(marker, flags, 0o600)
67
+ with os.fdopen(fd, "w", encoding="utf-8") as fh:
68
+ fh.write(str(time.time()))
69
+ sys.stderr.write(
70
+ f"[Token Optimizer] note: {scripts_dir} is not writable, so Python "
71
+ "bytecode (__pycache__) can't be cached — hooks will be slower than "
72
+ "expected. Make the plugin scripts dir writable to restore the speedup.\n"
73
+ )
74
+ except Exception:
75
+ pass
76
+
77
+
78
+ def main() -> int:
79
+ if len(sys.argv) < 3:
80
+ return 0
81
+
82
+ scripts_dir = sys.argv[1]
83
+ module_name = sys.argv[2]
84
+ script_args = sys.argv[3:]
85
+
86
+ # Defense-in-depth: don't rely solely on run.py sanitizing these. Refuse a
87
+ # module_name that isn't a bare Python identifier (blocks path separators,
88
+ # dots, and traversal), and require the resolved target to actually exist in
89
+ # scripts_dir. Fail OPEN (return 0) rather than raise — a hook must never
90
+ # crash the tool call. Without this, any future caller that skipped run.py's
91
+ # own validation would hand runpy an arbitrary-module-execution primitive.
92
+ if not module_name.isidentifier():
93
+ return 0
94
+ if not os.path.isfile(os.path.join(scripts_dir, module_name + ".py")):
95
+ return 0
96
+
97
+ _warn_readonly_scripts_dir_once(scripts_dir)
98
+
99
+ sys.path = [p for p in sys.path if p not in ("", ".")]
100
+ sys.path.insert(0, scripts_dir)
101
+ sys.argv = [module_name, *script_args]
102
+
103
+ # Per-event entry budget first (PreToolUse / PostToolUse / Stop). These are
104
+ # self-imposed deadlines that land far under the host's hooks.json timeout,
105
+ # so an over-budget hook exits 0 with NO output instead of being killed
106
+ # mid-write by the host. hook_runtime.resolve_entry_budget owns the table
107
+ # and the evidence behind each number. When the entry point isn't budgeted
108
+ # (consolidated Claude runners, or entries with no precise argv rule) we
109
+ # fall back to the 110s orphan backstop described below.
110
+ #
111
+ # Generic Windows orphan-grandchild backstop, NOT a collect/dashboard fossil bound.
112
+ #
113
+ # When the host TerminateProcess-es run.py on Windows it bypasses run.py's
114
+ # SIGTERM handler, orphaning this in-process grandchild while it still
115
+ # holds the hook stdout pipe. HookDeadline's daemon thread calls
116
+ # os._exit(0) so the pipe EOFs even when no parent is left to reap us.
117
+ # The 110s sits a few seconds under run.py's 120s wait so a normally
118
+ # reaped hook never trips it.
119
+ #
120
+ # This does NOT bound the collect/dashboard fossil: that fossil is a
121
+ # raw `measure.py collect && dashboard` in settings.json that invokes
122
+ # measure.py directly via the launcher, never through run.py/module_runner,
123
+ # so this layer never sees it. The fossil is bounded by the 20s dispatch
124
+ # budget in measure.py._dispatch_collect/_dispatch_dashboard,
125
+ # armed only on the hook path. The session-end-flush path this DOES wrap
126
+ # already self-bounds at 60s, so 110s is a last-resort backstop for any
127
+ # OTHER hook that runs past run.py's wait while orphaned on Windows.
128
+ # Fail-open if hook_runtime is missing (unit-test dummy plugin trees).
129
+ deadline = None
130
+ try:
131
+ from hook_runtime import HookDeadline, arm_entry_budget
132
+ deadline = arm_entry_budget(module_name, script_args)
133
+ if deadline is None:
134
+ deadline = HookDeadline(110).start()
135
+ except Exception:
136
+ deadline = None
137
+ try:
138
+ runpy.run_module(module_name, run_name="__main__", alter_sys=True)
139
+ finally:
140
+ if deadline is not None:
141
+ try:
142
+ deadline.cancel()
143
+ except Exception:
144
+ pass
145
+ return 0
146
+
147
+
148
+ if __name__ == "__main__":
149
+ sys.exit(main())