@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.
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 +448 -0
  10. package/hooks/posttooluse_runner.py +1110 -0
  11. package/hooks/python-launcher.sh +816 -0
  12. package/hooks/run.py +788 -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 +149 -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 +3633 -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 +141 -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 +93 -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 +379 -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 +1011 -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 +288 -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 +426 -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 +400 -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 +716 -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 +59531 -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 +1923 -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; D=\"${CLAUDE_PLUGIN_ROOT}\"; [ -r \"$D/hooks/python-launcher.sh\" ] || D=\"$(ls -d \"${D%/*}\"/*/ 2>/dev/null | grep -E \"/[0-9]+[.][0-9]+[.][0-9]+/$\" | sort -V | tail -n1)\"; D=\"${D%/}\"; [ -r \"$D/hooks/python-launcher.sh\" ] || exit 0; exec \"$b\" \"$D/hooks/python-launcher.sh\" \"$D/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; D=\"${CLAUDE_PLUGIN_ROOT}\"; [ -r \"$D/hooks/python-launcher.sh\" ] || D=\"$(ls -d \"${D%/*}\"/*/ 2>/dev/null | grep -E \"/[0-9]+[.][0-9]+[.][0-9]+/$\" | sort -V | tail -n1)\"; D=\"${D%/}\"; [ -r \"$D/hooks/python-launcher.sh\" ] || exit 0; exec \"$b\" \"$D/hooks/python-launcher.sh\" \"$D/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; D=\"${CLAUDE_PLUGIN_ROOT}\"; [ -r \"$D/hooks/python-launcher.sh\" ] || D=\"$(ls -d \"${D%/*}\"/*/ 2>/dev/null | grep -E \"/[0-9]+[.][0-9]+[.][0-9]+/$\" | sort -V | tail -n1)\"; D=\"${D%/}\"; [ -r \"$D/hooks/python-launcher.sh\" ] || exit 0; exec \"$b\" \"$D/hooks/python-launcher.sh\" \"$D/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; D=\"${CLAUDE_PLUGIN_ROOT}\"; [ -r \"$D/hooks/python-launcher.sh\" ] || D=\"$(ls -d \"${D%/*}\"/*/ 2>/dev/null | grep -E \"/[0-9]+[.][0-9]+[.][0-9]+/$\" | sort -V | tail -n1)\"; D=\"${D%/}\"; [ -r \"$D/hooks/python-launcher.sh\" ] || exit 0; exec \"$b\" \"$D/hooks/python-launcher.sh\" \"$D/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; D=\"${CLAUDE_PLUGIN_ROOT}\"; [ -r \"$D/hooks/python-launcher.sh\" ] || D=\"$(ls -d \"${D%/*}\"/*/ 2>/dev/null | grep -E \"/[0-9]+[.][0-9]+[.][0-9]+/$\" | sort -V | tail -n1)\"; D=\"${D%/}\"; [ -r \"$D/hooks/python-launcher.sh\" ] || exit 0; exec \"$b\" \"$D/hooks/python-launcher.sh\" \"$D/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; D=\"${CLAUDE_PLUGIN_ROOT}\"; [ -r \"$D/hooks/python-launcher.sh\" ] || D=\"$(ls -d \"${D%/*}\"/*/ 2>/dev/null | grep -E \"/[0-9]+[.][0-9]+[.][0-9]+/$\" | sort -V | tail -n1)\"; D=\"${D%/}\"; [ -r \"$D/hooks/python-launcher.sh\" ] || exit 0; exec \"$b\" \"$D/hooks/python-launcher.sh\" \"$D/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; D=\"${CLAUDE_PLUGIN_ROOT}\"; [ -r \"$D/hooks/python-launcher.sh\" ] || D=\"$(ls -d \"${D%/*}\"/*/ 2>/dev/null | grep -E \"/[0-9]+[.][0-9]+[.][0-9]+/$\" | sort -V | tail -n1)\"; D=\"${D%/}\"; [ -r \"$D/hooks/python-launcher.sh\" ] || exit 0; exec \"$b\" \"$D/hooks/python-launcher.sh\" \"$D/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; D=\"${CLAUDE_PLUGIN_ROOT}\"; [ -r \"$D/hooks/python-launcher.sh\" ] || D=\"$(ls -d \"${D%/*}\"/*/ 2>/dev/null | grep -E \"/[0-9]+[.][0-9]+[.][0-9]+/$\" | sort -V | tail -n1)\"; D=\"${D%/}\"; [ -r \"$D/hooks/python-launcher.sh\" ] || exit 0; exec \"$b\" \"$D/hooks/python-launcher.sh\" \"$D/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; D=\"${CLAUDE_PLUGIN_ROOT}\"; [ -r \"$D/hooks/python-launcher.sh\" ] || D=\"$(ls -d \"${D%/*}\"/*/ 2>/dev/null | grep -E \"/[0-9]+[.][0-9]+[.][0-9]+/$\" | sort -V | tail -n1)\"; D=\"${D%/}\"; [ -r \"$D/hooks/python-launcher.sh\" ] || exit 0; exec \"$b\" \"$D/hooks/python-launcher.sh\" \"$D/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; D=\"${CLAUDE_PLUGIN_ROOT}\"; [ -r \"$D/hooks/python-launcher.sh\" ] || D=\"$(ls -d \"${D%/*}\"/*/ 2>/dev/null | grep -E \"/[0-9]+[.][0-9]+[.][0-9]+/$\" | sort -V | tail -n1)\"; D=\"${D%/}\"; [ -r \"$D/hooks/python-launcher.sh\" ] || exit 0; exec \"$b\" \"$D/hooks/python-launcher.sh\" \"$D/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; D=\"${CLAUDE_PLUGIN_ROOT}\"; [ -r \"$D/hooks/python-launcher.sh\" ] || D=\"$(ls -d \"${D%/*}\"/*/ 2>/dev/null | grep -E \"/[0-9]+[.][0-9]+[.][0-9]+/$\" | sort -V | tail -n1)\"; D=\"${D%/}\"; [ -r \"$D/hooks/python-launcher.sh\" ] || exit 0; exec \"$b\" \"$D/hooks/python-launcher.sh\" \"$D/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; D=\"${CLAUDE_PLUGIN_ROOT}\"; [ -r \"$D/hooks/python-launcher.sh\" ] || D=\"$(ls -d \"${D%/*}\"/*/ 2>/dev/null | grep -E \"/[0-9]+[.][0-9]+[.][0-9]+/$\" | sort -V | tail -n1)\"; D=\"${D%/}\"; [ -r \"$D/hooks/python-launcher.sh\" ] || exit 0; exec \"$b\" \"$D/hooks/python-launcher.sh\" \"$D/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; D=\"${CLAUDE_PLUGIN_ROOT}\"; [ -r \"$D/hooks/python-launcher.sh\" ] || D=\"$(ls -d \"${D%/*}\"/*/ 2>/dev/null | grep -E \"/[0-9]+[.][0-9]+[.][0-9]+/$\" | sort -V | tail -n1)\"; D=\"${D%/}\"; [ -r \"$D/hooks/python-launcher.sh\" ] || exit 0; exec \"$b\" \"$D/hooks/python-launcher.sh\" \"$D/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; D=\"${CLAUDE_PLUGIN_ROOT}\"; [ -r \"$D/hooks/python-launcher.sh\" ] || D=\"$(ls -d \"${D%/*}\"/*/ 2>/dev/null | grep -E \"/[0-9]+[.][0-9]+[.][0-9]+/$\" | sort -V | tail -n1)\"; D=\"${D%/}\"; [ -r \"$D/hooks/python-launcher.sh\" ] || exit 0; exec \"$b\" \"$D/hooks/python-launcher.sh\" \"$D/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; D=\"${CLAUDE_PLUGIN_ROOT}\"; [ -r \"$D/hooks/python-launcher.sh\" ] || D=\"$(ls -d \"${D%/*}\"/*/ 2>/dev/null | grep -E \"/[0-9]+[.][0-9]+[.][0-9]+/$\" | sort -V | tail -n1)\"; D=\"${D%/}\"; [ -r \"$D/hooks/python-launcher.sh\" ] || exit 0; exec \"$b\" \"$D/hooks/python-launcher.sh\" \"$D/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; D=\"${CLAUDE_PLUGIN_ROOT}\"; [ -r \"$D/hooks/python-launcher.sh\" ] || D=\"$(ls -d \"${D%/*}\"/*/ 2>/dev/null | grep -E \"/[0-9]+[.][0-9]+[.][0-9]+/$\" | sort -V | tail -n1)\"; D=\"${D%/}\"; [ -r \"$D/hooks/python-launcher.sh\" ] || exit 0; exec \"$b\" \"$D/hooks/python-launcher.sh\" \"$D/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,448 @@
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 as a script would recompile it from
8
+ source every single time. Module-mode goes through the import system, which
9
+ checks and writes __pycache__, so only the first call pays the compile.
10
+
11
+ That first compile is not small. measure.py is ~2.7 MB / 58k lines (5.13.51).
12
+ Compiling it takes ~1.7 s on an Apple-silicon Mac and ~4 s under WSL2 Linux on
13
+ a 2015 i7, but 20-28 s with Windows CPython 3.12/3.13 on that same i7 (#264;
14
+ compile time grows faster than linearly with file size there). That is longer
15
+ than the host's hook timeouts (Stop 15 s, UserPromptSubmit/SessionStart 20 s),
16
+ and Python writes the .pyc only once the compile finishes, so a hook killed
17
+ mid-compile never warms the cache and every later call starts cold again.
18
+ _measure_bytecode_ready() therefore moves the cold compile into ONE detached
19
+ background process and lets the hook wait for it only as long as the host
20
+ deadline allows; a warm cache costs one stat and a 16-byte read. The
21
+ structural fix is splitting measure.py so each hook compiles only what it uses.
22
+
23
+ sys.path is stripped of '' and '.' (the cwd-equivalent entries the interpreter
24
+ would otherwise add) before inserting scripts_dir explicitly, so a same-named
25
+ file in the invoking project's own working directory (e.g. a project that
26
+ happens to have its own measure.py at its root) can never shadow the plugin's
27
+ module.
28
+ """
29
+ from __future__ import annotations
30
+
31
+ import os
32
+ import runpy
33
+ import sys
34
+
35
+
36
+ def _warn_readonly_scripts_dir_once(scripts_dir: str) -> None:
37
+ """If scripts_dir isn't writable, __pycache__ can't be written and CPython
38
+ recompiles the target from source on every call — the perf win silently
39
+ evaporates. Surface it, but at most once per day per user so we don't spam
40
+ stderr on the per-tool-call hot path. The marker lives in the OS temp dir
41
+ (writable even when the plugin install dir is read-only, which is the whole
42
+ failure mode). Best-effort: any error here must never break the hook."""
43
+ try:
44
+ if getattr(sys, "pycache_prefix", None):
45
+ return # bytecode goes to a cache prefix, scripts_dir needn't be writable
46
+ if os.access(scripts_dir, os.W_OK):
47
+ return # normal case — bytecode cache works, stay silent
48
+ import hashlib
49
+ import tempfile
50
+ import time
51
+
52
+ tag = hashlib.sha1(scripts_dir.encode("utf-8", "replace")).hexdigest()[:12]
53
+ marker = os.path.join(tempfile.gettempdir(), f".token-optimizer-ro-pyc-{tag}")
54
+ try:
55
+ fresh = (time.time() - os.path.getmtime(marker)) < 86400
56
+ except OSError:
57
+ fresh = False
58
+ if fresh:
59
+ return
60
+ # This marker lives at a predictable, world-shared temp path, so another
61
+ # local user can pre-plant something hostile there (CWE-377). Defend
62
+ # against all of it: unlink any existing entry first (drops a planted
63
+ # symlink, FIFO, or hardlink by name -- a hardlink's target is left
64
+ # untouched), then create our own EXCLUSIVELY. O_EXCL means we only ever
65
+ # open a file we just created; O_NOFOLLOW + O_NONBLOCK close the tiny
66
+ # unlink->open race (a re-planted symlink fails ELOOP, a re-planted FIFO
67
+ # fails ENXIO instead of blocking the hook forever). Every failure here
68
+ # is swallowed by the outer `except Exception` -> the hook stays
69
+ # fail-open and just skips the once-a-day warning. O_NOFOLLOW/O_NONBLOCK
70
+ # are absent on Windows; the getattr fallback of 0 makes them no-ops.
71
+ try:
72
+ os.unlink(marker)
73
+ except OSError:
74
+ pass
75
+ flags = (os.O_WRONLY | os.O_CREAT | os.O_EXCL
76
+ | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_NONBLOCK", 0))
77
+ fd = os.open(marker, flags, 0o600)
78
+ with os.fdopen(fd, "w", encoding="utf-8") as fh:
79
+ fh.write(str(time.time()))
80
+ sys.stderr.write(
81
+ f"[Token Optimizer] note: {scripts_dir} is not writable, so Python "
82
+ "bytecode (__pycache__) can't be cached — hooks will be slower than "
83
+ "expected. Make the plugin scripts dir writable to restore the speedup.\n"
84
+ )
85
+ except Exception:
86
+ pass
87
+
88
+
89
+ # --- Cold-compile gate (#264) ------------------------------------------------
90
+ # Entry points that import measure.py before doing anything, and how long each
91
+ # may wait for a background compile of it. Each wait leaves 8 s of the host's
92
+ # hook timeout (4.5 s for the Codex subagent bridge, whose own budget is 2.5 s)
93
+ # for interpreter start-up, loading the fresh .pyc and the hook's own work
94
+ # (1.0-1.5 s warm on the #264 machine):
95
+ # UserPromptSubmit / SessionStart runners: host 20 s (Claude Code and Codex)
96
+ # Stop runner: host 15 s (SessionEnd runs it async with 60 s)
97
+ # measure.py subcommands: StopFailure is the tightest at 12 s
98
+ # codex_hook_bridge: Codex SubagentStart/Stop, host 6 s
99
+ # A compile that finishes inside the wait gives exactly the old behaviour (the
100
+ # hook runs, warm). One that does not makes the hook exit 0 with no output, the
101
+ # host's "nothing to add", instead of being killed with the cache still cold.
102
+ _COLD_COMPILE_WAIT_S = {
103
+ "userpromptsubmit_runner": 12.0,
104
+ "sessionstart_runner": 12.0,
105
+ "stop_runner": 7.0,
106
+ "measure": 4.0,
107
+ "codex_hook_bridge": 1.5,
108
+ }
109
+ # Seconds; overrides every wait above. A negative value turns the gate off
110
+ # (compile inline, the pre-5.13.51 behaviour).
111
+ _COLD_COMPILE_WAIT_ENV = "TOKEN_OPTIMIZER_COLD_COMPILE_WAIT_S"
112
+ # A lock older than this belongs to a compile that died (killed, machine
113
+ # slept): the next hook takes over. ~4x the slowest compile measured (28 s).
114
+ _COLD_COMPILE_LOCK_STALE_S = 120.0
115
+ _COLD_COMPILE_LOCK = ".token-optimizer-compile.lock"
116
+ _COLD_COMPILE_FAILED = ".token-optimizer-compile.failed"
117
+ _COLD_COMPILE_TAG = "token-optimizer-bytecode-warmup"
118
+
119
+ # The detached compiler, run as `python -c`. It compiles measure.py first and
120
+ # drops the lock as soon as that one is written (the hooks only wait for it),
121
+ # then warms the consolidated runners and the plugin's other scripts. A
122
+ # failure on measure.py leaves a marker keyed to the source's mtime and size,
123
+ # so hooks stop deferring to a compile that cannot succeed and compile inline
124
+ # as before.
125
+ _COMPILER_SOURCE = r'''
126
+ import sys
127
+ sys.path[:] = [p for p in sys.path if p not in ("", ".")]
128
+ sys.dont_write_bytecode = False
129
+ import os, importlib.util, py_compile
130
+ _tag, lock, failed, prefix, opt, measure_src, hooks_dir, scripts_dir = sys.argv[1:9]
131
+ sys.pycache_prefix = prefix or None
132
+ opt = int(opt)
133
+ mode = py_compile.PycInvalidationMode.TIMESTAMP
134
+
135
+ def _fresh(src, cfile):
136
+ try:
137
+ st = os.stat(src)
138
+ with open(cfile, "rb") as fh:
139
+ head = fh.read(16)
140
+ except OSError:
141
+ return False
142
+ if len(head) < 16 or head[:4] != importlib.util.MAGIC_NUMBER:
143
+ return False
144
+ if int.from_bytes(head[4:8], "little") & 1:
145
+ return True
146
+ return (int.from_bytes(head[8:12], "little") == int(st.st_mtime) & 0xFFFFFFFF
147
+ and int.from_bytes(head[12:16], "little") == st.st_size & 0xFFFFFFFF)
148
+
149
+ def _compile(src):
150
+ cfile = importlib.util.cache_from_source(src, optimization="" if opt == 0 else opt)
151
+ if not _fresh(src, cfile):
152
+ py_compile.compile(src, cfile=cfile, doraise=True, optimize=opt, invalidation_mode=mode)
153
+
154
+ try:
155
+ _compile(measure_src)
156
+ except BaseException:
157
+ try:
158
+ st = os.stat(measure_src)
159
+ with open(failed, "w", encoding="utf-8") as fh:
160
+ fh.write("%d:%d" % (st.st_mtime_ns, st.st_size))
161
+ except OSError:
162
+ pass
163
+ finally:
164
+ try:
165
+ os.unlink(lock)
166
+ except OSError:
167
+ pass
168
+ # Then the rest a hook imports: the consolidated runners and the scripts.
169
+ for folder, suffix in ((hooks_dir, "_runner.py"), (scripts_dir, ".py")):
170
+ try:
171
+ names = sorted(os.listdir(folder))
172
+ except OSError:
173
+ continue
174
+ for name in names:
175
+ src = os.path.join(folder, name)
176
+ if name.endswith(suffix) and name[:-3].isidentifier() and src != measure_src:
177
+ try:
178
+ _compile(src)
179
+ except BaseException:
180
+ pass
181
+ '''
182
+
183
+
184
+ def _bytecode_path(source: str) -> str:
185
+ """Where the import system reads and writes ``source``'s bytecode for this
186
+ interpreter, honouring sys.pycache_prefix (PYTHONPYCACHEPREFIX, or the
187
+ per-user prefix run.py chooses inside a git work tree or a hosted VM)."""
188
+ import importlib.util
189
+
190
+ return importlib.util.cache_from_source(source)
191
+
192
+
193
+ def _bytecode_fresh(source: str, cache: str) -> bool:
194
+ """True when ``cache`` is bytecode the import system will accept for
195
+ ``source`` without recompiling: one stat and a 16-byte read. The checks
196
+ mirror importlib's: magic number, then the source mtime and size a
197
+ timestamp .pyc records. A hash-based .pyc counts as fresh (import itself
198
+ validates its hash)."""
199
+ import importlib.util
200
+
201
+ try:
202
+ st = os.stat(source)
203
+ with open(cache, "rb") as fh:
204
+ head = fh.read(16)
205
+ except OSError:
206
+ return False
207
+ if len(head) < 16 or head[:4] != importlib.util.MAGIC_NUMBER:
208
+ return False
209
+ if int.from_bytes(head[4:8], "little") & 1:
210
+ return True
211
+ return (int.from_bytes(head[8:12], "little") == int(st.st_mtime) & 0xFFFFFFFF
212
+ and int.from_bytes(head[12:16], "little") == st.st_size & 0xFFFFFFFF)
213
+
214
+
215
+ def _compile_failed_for(marker: str, source: str) -> bool:
216
+ """The background compile already failed on this exact source."""
217
+ try:
218
+ st = os.stat(source)
219
+ with open(marker, encoding="utf-8") as fh:
220
+ return fh.read(64).strip() == f"{st.st_mtime_ns}:{st.st_size}"
221
+ except (OSError, ValueError):
222
+ return False
223
+
224
+
225
+ def _take_compile_lock(lock: str):
226
+ """True: this hook owns the compile. False: another hook's compile is
227
+ running. None: no lock can be made here (read-only cache dir), so the
228
+ caller compiles inline as before. A lock past its stale age is taken over
229
+ once."""
230
+ import time
231
+
232
+ for _attempt in range(2):
233
+ try:
234
+ fd = os.open(lock, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
235
+ except FileExistsError:
236
+ try:
237
+ age = time.time() - os.path.getmtime(lock)
238
+ except OSError:
239
+ continue # released between the two calls: try again
240
+ if age < _COLD_COMPILE_LOCK_STALE_S:
241
+ return False
242
+ try:
243
+ os.unlink(lock)
244
+ except OSError:
245
+ return False
246
+ continue
247
+ except OSError:
248
+ return None
249
+ try:
250
+ os.write(fd, f"{os.getpid()} {time.time():.3f}\n".encode("ascii"))
251
+ except OSError:
252
+ pass
253
+ finally:
254
+ os.close(fd)
255
+ return True
256
+ return False
257
+
258
+
259
+ def _start_background_compile(lock, failed, measure_src, plugin_scripts):
260
+ """Start the one detached compiler. Returns its Popen, or None (the lock is
261
+ then released again and the caller compiles inline)."""
262
+ import subprocess
263
+
264
+ hooks_dir = os.path.dirname(os.path.abspath(__file__))
265
+ argv = [sys.executable, "-c", _COMPILER_SOURCE, _COLD_COMPILE_TAG, lock, failed,
266
+ getattr(sys, "pycache_prefix", None) or "", str(sys.flags.optimize),
267
+ measure_src, hooks_dir, plugin_scripts]
268
+ proc = None
269
+ try:
270
+ from spawn_utils import spawn_detached
271
+
272
+ # stdio to DEVNULL: an inherited stdout would hold the hook's pipe
273
+ # open, and the host waits for EOF on it.
274
+ proc = spawn_detached(argv, cwd=plugin_scripts, stdin=subprocess.DEVNULL,
275
+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
276
+ except Exception:
277
+ proc = None
278
+ if proc is None:
279
+ try:
280
+ os.unlink(lock)
281
+ except OSError:
282
+ pass
283
+ return proc
284
+
285
+
286
+ def _measure_bytecode_ready(plugin_scripts: str, wait_s: float) -> bool:
287
+ """False only when measure.py's bytecode is still being compiled in the
288
+ background after ``wait_s``: the hook should then exit 0 without output.
289
+
290
+ True means import as usual: the cache is warm, a compile finished inside
291
+ the wait, or the background route is unavailable (no cache_tag, read-only
292
+ cache dir, spawn refused, the compile failed or died), in which case the
293
+ import compiles inline exactly as it did before this gate existed."""
294
+ import time
295
+
296
+ measure_src = os.path.join(plugin_scripts, "measure.py")
297
+ try:
298
+ cache = _bytecode_path(measure_src)
299
+ except Exception:
300
+ return True
301
+ if _bytecode_fresh(measure_src, cache):
302
+ return True
303
+ if not os.path.isfile(measure_src):
304
+ return True
305
+ cache_dir = os.path.dirname(cache)
306
+ lock = os.path.join(cache_dir, _COLD_COMPILE_LOCK)
307
+ failed = os.path.join(cache_dir, _COLD_COMPILE_FAILED)
308
+ try:
309
+ os.makedirs(cache_dir, exist_ok=True)
310
+ except OSError:
311
+ return True
312
+ end = time.monotonic() + max(0.0, wait_s)
313
+ child = None
314
+ while True:
315
+ if _bytecode_fresh(measure_src, cache):
316
+ return True
317
+ if _compile_failed_for(failed, measure_src):
318
+ return True
319
+ if child is not None and child.poll() is not None:
320
+ # Ours exited and the cache is still cold: compile inline.
321
+ return True
322
+ if child is None:
323
+ owned = _take_compile_lock(lock)
324
+ if owned is None:
325
+ return True
326
+ if owned:
327
+ child = _start_background_compile(lock, failed, measure_src, plugin_scripts)
328
+ if child is None:
329
+ return True
330
+ if time.monotonic() >= end:
331
+ return False
332
+ time.sleep(0.05)
333
+
334
+
335
+ def _cold_compile_wait(module_name: str):
336
+ """Seconds this entry may wait for a background compile, or None when the
337
+ entry is not gated (it does not import measure.py up front)."""
338
+ wait = _COLD_COMPILE_WAIT_S.get(module_name)
339
+ if wait is None:
340
+ return None
341
+ raw = os.environ.get(_COLD_COMPILE_WAIT_ENV, "").strip()
342
+ if raw:
343
+ try:
344
+ wait = float(raw)
345
+ except ValueError:
346
+ pass
347
+ return None if wait < 0 else wait
348
+
349
+
350
+ def main() -> int:
351
+ if len(sys.argv) < 3:
352
+ return 0
353
+
354
+ scripts_dir = sys.argv[1]
355
+ module_name = sys.argv[2]
356
+ script_args = sys.argv[3:]
357
+
358
+ # Defense-in-depth: don't rely solely on run.py sanitizing these. Refuse a
359
+ # module_name that isn't a bare Python identifier (blocks path separators,
360
+ # dots, and traversal), and require the resolved target to actually exist in
361
+ # scripts_dir. Fail OPEN (return 0) rather than raise — a hook must never
362
+ # crash the tool call. Without this, any future caller that skipped run.py's
363
+ # own validation would hand runpy an arbitrary-module-execution primitive.
364
+ if not module_name.isidentifier():
365
+ return 0
366
+ if not os.path.isfile(os.path.join(scripts_dir, module_name + ".py")):
367
+ return 0
368
+
369
+ _warn_readonly_scripts_dir_once(scripts_dir)
370
+
371
+ # A host-set PYTHONDONTWRITEBYTECODE=1 would stop __pycache__ being written.
372
+ sys.dont_write_bytecode = False
373
+
374
+ sys.path = [p for p in sys.path if p not in ("", ".")]
375
+ sys.path.insert(0, scripts_dir)
376
+ sys.argv = [module_name, *script_args]
377
+
378
+ # The plugin's own scripts dir (hook_runtime, spawn_utils, measure.py).
379
+ # The consolidated runners live in hooks/, so scripts_dir is hooks/ for
380
+ # them; APPENDED so it can never shadow a module of the hook being run.
381
+ _plugin_scripts = os.path.join(
382
+ os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
383
+ "skills", "token-optimizer", "scripts")
384
+ if os.path.isdir(_plugin_scripts) and _plugin_scripts not in sys.path:
385
+ sys.path.append(_plugin_scripts)
386
+
387
+ # Before anything imports measure.py: never compile it on the hook's
388
+ # deadline (#264). See _measure_bytecode_ready.
389
+ _wait = _cold_compile_wait(module_name)
390
+ if _wait is not None:
391
+ try:
392
+ if not _measure_bytecode_ready(_plugin_scripts, _wait):
393
+ return 0
394
+ except Exception:
395
+ pass
396
+
397
+ # Per-event entry budget first (PreToolUse / PostToolUse / Stop). These are
398
+ # self-imposed deadlines that land far under the host's hooks.json timeout,
399
+ # so an over-budget hook exits 0 with NO output instead of being killed
400
+ # mid-write by the host. hook_runtime.resolve_entry_budget owns the table
401
+ # and the evidence behind each number. When the entry point isn't budgeted
402
+ # (consolidated Claude runners, or entries with no precise argv rule) we
403
+ # fall back to the 110s orphan backstop described below.
404
+ #
405
+ # Generic Windows orphan-grandchild backstop, NOT a collect/dashboard fossil bound.
406
+ #
407
+ # When the host TerminateProcess-es run.py on Windows it bypasses run.py's
408
+ # SIGTERM handler, orphaning this in-process grandchild while it still
409
+ # holds the hook stdout pipe. HookDeadline's daemon thread calls
410
+ # os._exit(0) so the pipe EOFs even when no parent is left to reap us.
411
+ # The 110s sits a few seconds under run.py's 120s wait so a normally
412
+ # reaped hook never trips it.
413
+ #
414
+ # This does NOT bound the collect/dashboard fossil: that fossil is a
415
+ # raw `measure.py collect && dashboard` in settings.json that invokes
416
+ # measure.py directly via the launcher, never through run.py/module_runner,
417
+ # so this layer never sees it. The fossil is bounded by the 20s dispatch
418
+ # budget in measure.py._dispatch_collect/_dispatch_dashboard,
419
+ # armed only on the hook path. The session-end-flush path this DOES wrap
420
+ # already self-bounds at 60s, so 110s is a last-resort backstop for any
421
+ # OTHER hook that runs past run.py's wait while orphaned on Windows.
422
+ # Fail-open if hook_runtime is missing (unit-test dummy plugin trees).
423
+ # The consolidated runners live in hooks/, so scripts_dir is hooks/ and
424
+ # hook_runtime (in skills/token-optimizer/scripts) was never importable for
425
+ # them: the import failed, the except swallowed it, and every runner ran
426
+ # with no backstop at all. It is found through the plugin's own scripts
427
+ # dir, appended to sys.path above.
428
+ deadline = None
429
+ try:
430
+ from hook_runtime import HookDeadline, arm_entry_budget
431
+ deadline = arm_entry_budget(module_name, script_args)
432
+ if deadline is None:
433
+ deadline = HookDeadline(110).start()
434
+ except Exception:
435
+ deadline = None
436
+ try:
437
+ runpy.run_module(module_name, run_name="__main__", alter_sys=True)
438
+ finally:
439
+ if deadline is not None:
440
+ try:
441
+ deadline.cancel()
442
+ except Exception:
443
+ pass
444
+ return 0
445
+
446
+
447
+ if __name__ == "__main__":
448
+ sys.exit(main())