@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,408 @@
1
+ #!/usr/bin/env python3
2
+ """Single-import Stop + SessionEnd dispatcher.
3
+
4
+ Replaces the THREE separate ``Stop`` hook commands in hooks.json that each
5
+ spawned ``python-launcher.sh -> run.py -> module_runner.py -> runpy(measure.py)``
6
+ and caused each subcommand to start a separate interpreter and import
7
+ ``measure.py`` independently:
8
+
9
+ 1. ``measure.py compact-capture --trigger stop --quiet`` (timeout 12)
10
+ 2. ``measure.py session-end-flush --trigger stop --quiet --defer`` (timeout 8)
11
+ 3. ``measure.py keepwarm-arm --quiet`` (timeout 5)
12
+
13
+ The separate processes also repeat cold imports when a read-only plugin
14
+ installation cannot retain ``__pycache__``. Consolidation pays that startup
15
+ cost once, then runs the real work under one shared deadline.
16
+
17
+ The ``SessionEnd`` hook (a fourth entry: ``session-end-flush --trigger end
18
+ --defer``, async, timeout 60) joins this runner too. It is a separate hooks.json
19
+ entry (different event, ``async: true``, timeout 60) but dispatches the SAME
20
+ runner file, branching on ``hook_event_name`` so the trigger value ``end`` is
21
+ preserved exactly. This saves one more measure.py import per session end.
22
+
23
+ This is the same consolidation the ``SessionStart`` and ``UserPromptSubmit``
24
+ groups received (``hooks/sessionstart_runner.py``,
25
+ ``hooks/userpromptsubmit_runner.py``); the structure deliberately mirrors those
26
+ files.
27
+
28
+ Key properties:
29
+ - ONE shared ``HookDeadline`` (13s for Stop, 2s margin under the hooks.json
30
+ timeout of 15; 58s for SessionEnd, 2s margin under timeout 60) replaces the
31
+ three independent per-entry timeouts (12 + 8 + 5 = 25s). Remaining time is
32
+ budgeted fairly across the subcommands still pending (``_runner_budget``);
33
+ the shared deadline's ``os._exit(0)`` is the ONLY kill switch in the
34
+ process, so an early subcommand hang can never preemptively kill later ones.
35
+ - The ``--defer`` behaviour is preserved EXACTLY: ``session-end-flush`` calls
36
+ ``measure._dispatch_session_end_flush`` with the same args list the
37
+ ``__main__`` dispatch received, so the detached worker gets the same
38
+ ``--trigger`` / ``--defer`` / ``--quiet`` flags.
39
+ - The trigger values ``stop`` and ``end`` are preserved EXACTLY so entry
40
+ budget rules can distinguish the Stop and SessionEnd work.
41
+ - The ``async: true`` flag on the SessionEnd hooks.json entry is a host-level
42
+ semantic (fire-and-forget); the runner itself is the same for both events.
43
+ - No once-per-session latching exists in the Stop/SessionEnd chain (none of
44
+ the three subcommands use ``_mark_ran_this_session`` or
45
+ ``_ran_once_this_session``), so there is nothing to preserve there.
46
+ - stdout from all subcommands is captured through one buffered emitter and
47
+ emitted in dispatch order at the end of ``main()``. Under ``--quiet`` (the
48
+ Stop path) all three subcommands produce no stdout; the SessionEnd path
49
+ likewise produces none (``_dispatch_session_end_flush`` only spawns a
50
+ detached worker). The buffer is a safety net for any unexpected output.
51
+ - One subcommand throwing/aborting never aborts the others (each is wrapped in
52
+ ``_run_safely``); the hook always exits 0.
53
+ - No consent gate: the Stop and SessionEnd subcommands are all data
54
+ collection, none bootstrap the consent flags (unlike SessionStart /
55
+ UserPromptSubmit which contain ensure-health). run.py's consent gate
56
+ handles them: when consent is False, run.py returns 0 and the runner never
57
+ fires. The runner is NOT in run.py's exempt list, preserving the
58
+ consent-gated semantics of the three legacy entries.
59
+
60
+ The runner calls the same module-level entrypoints used by the ``__main__``
61
+ dispatch, preserving their arguments and behavior while only changing how
62
+ they are scheduled.
63
+
64
+ Run: ``hooks/stop_runner.py`` (via run.py -> module_runner.py).
65
+ """
66
+ from __future__ import annotations
67
+
68
+ import io
69
+ import os
70
+ import sys
71
+ import traceback
72
+ from contextlib import redirect_stdout
73
+ from pathlib import Path
74
+
75
+
76
+ def _resolve_measure_dir() -> str:
77
+ """Locate the directory holding measure.py so ``import measure`` works.
78
+
79
+ module_runner.py puts THIS file's parent (``hooks/``) on ``sys.path[0]``;
80
+ measure.py lives in ``skills/token-optimizer/scripts/``. Resolve it from
81
+ ``CLAUDE_PLUGIN_ROOT`` (set by the host before hook invocation) with a
82
+ ``__file__``-relative fallback (the plugin root is this file's
83
+ grandparent), and insert it ahead of ``hooks/`` so measure.py and its
84
+ sibling modules (runtime_env, plugin_env, hook_io, hook_runtime) resolve.
85
+ """
86
+ candidates: list[Path] = []
87
+ pr = os.environ.get("CLAUDE_PLUGIN_ROOT", "").strip()
88
+ if pr:
89
+ candidates.append(Path(pr) / "skills" / "token-optimizer" / "scripts")
90
+ try:
91
+ candidates.append(
92
+ Path(__file__).resolve().parent.parent
93
+ / "skills" / "token-optimizer" / "scripts"
94
+ )
95
+ except Exception:
96
+ pass
97
+ for c in candidates:
98
+ try:
99
+ if (c / "measure.py").is_file():
100
+ return str(c.resolve())
101
+ except OSError:
102
+ continue
103
+ # Last resort: assume CWD-relative scripts layout (manual/dev invocation).
104
+ return str((Path.cwd() / "skills" / "token-optimizer" / "scripts").resolve())
105
+
106
+
107
+ _MEASURE_DIR = _resolve_measure_dir()
108
+ if _MEASURE_DIR and _MEASURE_DIR not in sys.path:
109
+ sys.path.insert(0, _MEASURE_DIR)
110
+
111
+ import measure # noqa: E402 (path bootstrapped above)
112
+
113
+
114
+ def _read_hook_input() -> dict:
115
+ """Read the hook stdin JSON once, non-blocking, shared across subcommands.
116
+
117
+ Uses measure's own shared reader (Windows pipe-peek + Unix select) so the
118
+ behavior matches what each ``__main__`` handler saw individually. 1 MB cap
119
+ is generous: the largest handler (compact-capture) reads the default 65536,
120
+ and none of the three Stop handlers reads more.
121
+ """
122
+ try:
123
+ return measure._read_stdin_hook_input(max_bytes=1_000_000) or {}
124
+ except Exception:
125
+ return {}
126
+
127
+
128
+ def _is_session_end(hook_input: dict) -> bool:
129
+ """True when the firing hook is SessionEnd, not Stop.
130
+
131
+ The host sends ``hook_event_name`` in the stdin payload. The runner is
132
+ registered under both ``Stop`` and ``SessionEnd`` in hooks.json; this check
133
+ routes to the right subcommand set. Case-insensitive to tolerate host
134
+ variations. When the field is missing, default to the Stop path (the
135
+ primary use case -- running all three subcommands when only
136
+ session-end-flush was needed is harmless and fail-open; the reverse would
137
+ miss the checkpoint and keepwarm arm).
138
+ """
139
+ event = str(hook_input.get("hook_event_name") or "").strip().lower()
140
+ return event == "sessionend"
141
+
142
+
143
+ def _run_safely(name: str, fn, *args, **kwargs) -> None:
144
+ """Run fn, swallow any failure to stderr, never propagate.
145
+
146
+ Catches ``Exception``, ``SystemExit``, and ``measure._HookTimeout`` (a
147
+ ``BaseException``) so one subcommand's bug, internal ``sys.exit()``, or
148
+ legacy timeout signal cannot abort the others. The ``session-end-flush``
149
+ and ``keepwarm-arm`` dispatch blocks both end in ``sys.exit(0)``; in-process
150
+ that is a ``SystemExit`` that this guard isolates. The original
151
+ ``__main__`` blocks explicitly catch ``_HookTimeout``; in production the
152
+ new ``HookDeadline`` watchdog calls ``os._exit(0)`` directly (uncatchable),
153
+ but ``_HookTimeout`` is caught here for defense-in-depth and for tests
154
+ that inject it.
155
+ """
156
+ try:
157
+ fn(*args, **kwargs)
158
+ except (Exception, SystemExit):
159
+ try:
160
+ sys.stderr.write(f"[Token Optimizer] {name} failed, continuing\n")
161
+ traceback.print_exc(file=sys.stderr)
162
+ sys.stderr.flush()
163
+ except (OSError, ValueError):
164
+ pass
165
+ except BaseException:
166
+ # _HookTimeout (a BaseException subclass in measure.py) and any other
167
+ # BaseException that is not Exception/SystemExit. Swallow it so the
168
+ # remaining subcommands still run; the shared HookDeadline's
169
+ # os._exit(0) is the only uncatchable kill switch.
170
+ try:
171
+ sys.stderr.write(f"[Token Optimizer] {name} hit a base exception, continuing\n")
172
+ sys.stderr.flush()
173
+ except (OSError, ValueError):
174
+ pass
175
+
176
+
177
+ # --------------------------------------------------------------------------- #
178
+ # Shared deadline: ONE HookDeadline for the whole runner replaces the three
179
+ # independent per-entry timeouts (12 + 8 + 5 = 25s declared for Stop).
180
+ #
181
+ # WHY 13s for Stop:
182
+ # * The three legacy entries declared 25s combined. The consolidated
183
+ # hooks.json entry declares timeout=15 (well under the 25s original, and
184
+ # under any plausible host ceiling).
185
+ # * The internal deadline is 13s: 2s of margin under the declared 15 so the
186
+ # runner self-exits 0 with its buffered stdout emitted, rather than being
187
+ # SIGKILLed by the host mid-write. Same 2s margin the SessionStart and
188
+ # UserPromptSubmit runners use.
189
+ #
190
+ # WHY 58s for SessionEnd:
191
+ # * The legacy SessionEnd entry declared timeout=60 with async=true. The
192
+ # consolidated entry preserves both. The internal deadline is 58s (2s
193
+ # margin under 60). The work is trivial (spawn a detached worker and
194
+ # return), so the deadline is a safety net that never fires in practice.
195
+ # * The 58s applies to Claude Code only. The Codex
196
+ # marketplace plugin clamps SessionEnd to timeout=3 (via
197
+ # sync-codex-marketplace-plugin.sh CODEX_SESSION_END_TIMEOUT_CAP=3), so on
198
+ # Codex the host kills the process at 3s and the 58s deadline never fires.
199
+ # The work (spawn detached, return) completes well within 3s, so this is
200
+ # not a functional issue, only a headroom claim that is wrong for one host.
201
+ # --------------------------------------------------------------------------- #
202
+
203
+ _RUNNER_DEADLINE = None # type: measure.HookDeadline | None
204
+ _RUNNER_TOTAL_BUDGET = 13.0 # seconds, 2s margin under hooks.json timeout=15 (Stop)
205
+ _SUBCOMMANDS_PENDING = 0 # decremented by _runner_budget on each call
206
+
207
+
208
+ def _install_runner_deadline(total_seconds=None):
209
+ """Arm ONE shared HookDeadline watchdog for the entire runner."""
210
+ global _RUNNER_DEADLINE
211
+ if _RUNNER_DEADLINE is not None:
212
+ return _RUNNER_DEADLINE
213
+ if total_seconds is None:
214
+ total_seconds = _RUNNER_TOTAL_BUDGET
215
+ _RUNNER_DEADLINE = measure.HookDeadline(total_seconds)
216
+ _RUNNER_DEADLINE.start()
217
+ return _RUNNER_DEADLINE
218
+
219
+
220
+ def _runner_budget(default_seconds, subcommand_count_hint=None):
221
+ """Return the fair-share budget (seconds) for one subcommand.
222
+
223
+ Divides the shared deadline's remaining time among the subcommands that
224
+ have not yet run. Callers check the returned value: if it is below a
225
+ minimum threshold they skip the subcommand entirely so a later subcommand
226
+ with real work still gets a chance.
227
+ """
228
+ global _SUBCOMMANDS_PENDING
229
+ if subcommand_count_hint is not None:
230
+ _SUBCOMMANDS_PENDING = subcommand_count_hint
231
+ _SUBCOMMANDS_PENDING = max(0, _SUBCOMMANDS_PENDING - 1)
232
+ if _RUNNER_DEADLINE is None:
233
+ return default_seconds
234
+ remaining = _RUNNER_DEADLINE.remaining()
235
+ if remaining <= 0:
236
+ return 0.0
237
+ divisor = max(1, _SUBCOMMANDS_PENDING + 1)
238
+ fair = remaining / divisor
239
+ return min(default_seconds, max(0.1, fair))
240
+
241
+
242
+ def _clear_runner_deadline():
243
+ """Cancel the shared deadline (normal completion)."""
244
+ global _RUNNER_DEADLINE
245
+ if _RUNNER_DEADLINE is not None:
246
+ _RUNNER_DEADLINE.cancel()
247
+ _RUNNER_DEADLINE = None
248
+
249
+
250
+ # --------------------------------------------------------------------------- #
251
+ # Subcommand handlers -- each mirrors its measure.py __main__ dispatch block.
252
+ # --------------------------------------------------------------------------- #
253
+
254
+
255
+ def _sub_compact_capture_stop(hook_input: dict) -> None:
256
+ """``measure.py compact-capture --trigger stop --quiet`` (Stop entry 1).
257
+
258
+ Mirrors the ``compact-capture`` dispatch (measure.py ~L42447):
259
+ --trigger stop -> trigger="stop";
260
+ reads stdin for transcript_path and session_id;
261
+ calls compact_capture(transcript_path=..., session_id=..., trigger="stop");
262
+ --quiet suppresses the print.
263
+ The dispatch's own ``_install_hook_budget(8)`` is replaced by the runner's
264
+ shared HookDeadline; the ``_HookTimeout`` / ``Exception`` catches are
265
+ replaced by ``_run_safely``.
266
+ """
267
+ budget = _runner_budget(8)
268
+ if budget < 0.1:
269
+ return
270
+ transcript = hook_input.get("transcript_path")
271
+ sid = hook_input.get("session_id")
272
+ result = measure.compact_capture(
273
+ transcript_path=transcript, session_id=sid, trigger="stop"
274
+ )
275
+ # --quiet: no print. The dispatch only prints when result is truthy AND
276
+ # --quiet is NOT in args; the Stop path always has --quiet, so no print.
277
+ # Non-quiet output (if ever needed) would go through the stdout buffer.
278
+
279
+
280
+ def _sub_session_end_flush_stop(hook_input: dict) -> None:
281
+ """``measure.py session-end-flush --trigger stop --quiet --defer`` (entry 2).
282
+
283
+ Mirrors the ``session-end-flush`` dispatch (measure.py ~L42154):
284
+ calls _dispatch_session_end_flush(args) with the exact args list;
285
+ _dispatch_session_end_flush defers by default (--no-defer not present),
286
+ spawning a detached worker with args[1:] = [--trigger, stop, --quiet,
287
+ --defer]; the worker reads --trigger for its compact_capture call.
288
+ The dispatch's trailing ``sys.exit(0)`` is NOT part of
289
+ _dispatch_session_end_flush; calling the function directly avoids it. Even
290
+ if it did sys.exit, ``_run_safely`` catches SystemExit.
291
+ """
292
+ budget = _runner_budget(8)
293
+ if budget < 0.1:
294
+ return
295
+ measure._dispatch_session_end_flush(
296
+ ["session-end-flush", "--trigger", "stop", "--quiet", "--defer"],
297
+ budget_seconds=budget,
298
+ )
299
+
300
+
301
+ def _sub_keepwarm_arm(hook_input: dict) -> None:
302
+ """``measure.py keepwarm-arm --quiet`` (Stop entry 3).
303
+
304
+ Mirrors the ``keepwarm-arm`` dispatch (measure.py ~L42479):
305
+ reads stdin for session_id and transcript_path;
306
+ calls write_keepwarm_arm_record(sid, transcript);
307
+ --quiet suppresses the print.
308
+ The dispatch's own ``_install_hook_budget(2)`` is replaced by the runner's
309
+ shared HookDeadline. The dispatch's ``sys.exit(0)`` on _HookTimeout /
310
+ Exception is replaced by ``_run_safely``'s SystemExit catch.
311
+ """
312
+ budget = _runner_budget(2)
313
+ if budget < 0.1:
314
+ return
315
+ sid = hook_input.get("session_id")
316
+ transcript = hook_input.get("transcript_path")
317
+ measure.write_keepwarm_arm_record(sid, transcript)
318
+
319
+
320
+ def _sub_session_end_flush_end(hook_input: dict) -> None:
321
+ """``measure.py session-end-flush --trigger end --defer`` (SessionEnd entry).
322
+
323
+ Same function as the Stop path's session-end-flush but with trigger=end and
324
+ no --quiet (the legacy SessionEnd entry did not pass --quiet). The trigger
325
+ value ``end`` is preserved exactly for the latency budget table that
326
+ matches on it. ``--defer`` is preserved (default defer, but the flag is
327
+ passed through to the detached worker's args).
328
+ """
329
+ budget = _runner_budget(60)
330
+ if budget < 0.1:
331
+ return
332
+ measure._dispatch_session_end_flush(
333
+ ["session-end-flush", "--trigger", "end", "--defer"],
334
+ budget_seconds=budget,
335
+ )
336
+
337
+
338
+ def main() -> int:
339
+ # Wrap the entire body in a top-level guard so "exit 0 always" is truly
340
+ # always: an unhandled exception in main() (e.g. from _install_runner_deadline
341
+ # or _is_session_end) would otherwise propagate and yield a non-zero exit.
342
+ # The only non-zero path is the uncatchable os._exit(0) from the HookDeadline
343
+ # watchdog (which exits 0 anyway). Per-subcommand failures are already
344
+ # isolated by _run_safely; this guard covers the orchestration layer.
345
+ try:
346
+ hook_input = _read_hook_input()
347
+ is_session_end = _is_session_end(hook_input)
348
+
349
+ # ONE shared HookDeadline for the entire runner. The budget differs by
350
+ # event: 13s for Stop (under the 15s declared timeout), 58s for SessionEnd
351
+ # (under the 60s declared timeout). The SessionEnd path runs one trivial
352
+ # subcommand (spawn detached, return), so the 58s deadline is a safety net.
353
+ if is_session_end:
354
+ _install_runner_deadline(58.0)
355
+ else:
356
+ _install_runner_deadline()
357
+
358
+ # Buffer every subcommand's stdout and emit in dispatch order at the end.
359
+ # Under --quiet (the Stop path) all three subcommands produce no stdout;
360
+ # the SessionEnd path likewise produces none. The buffer is a safety net
361
+ # for any unexpected output, preserving the host's no-output contract.
362
+ _stdout_bufs: list[str] = []
363
+
364
+ def _capture(name: str, fn, *args, **kwargs) -> None:
365
+ buf = io.StringIO()
366
+ with redirect_stdout(buf):
367
+ _run_safely(name, fn, *args, **kwargs)
368
+ captured = buf.getvalue()
369
+ if captured:
370
+ _stdout_bufs.append(captured)
371
+
372
+ if is_session_end:
373
+ # SessionEnd: only session-end-flush --trigger end --defer.
374
+ _runner_budget(60, subcommand_count_hint=1)
375
+ _capture("session-end-flush --trigger end", _sub_session_end_flush_end,
376
+ hook_input)
377
+ else:
378
+ # Stop: all three subcommands in dispatch order (matching the legacy
379
+ # hooks.json entry order: compact-capture, session-end-flush, keepwarm-arm).
380
+ _runner_budget(8, subcommand_count_hint=3)
381
+ _capture("compact-capture", _sub_compact_capture_stop, hook_input)
382
+ _capture("session-end-flush --trigger stop", _sub_session_end_flush_stop,
383
+ hook_input)
384
+ _capture("keepwarm-arm", _sub_keepwarm_arm, hook_input)
385
+
386
+ # Emit all buffered stdout in order (preserves per-shape contract: each
387
+ # subcommand's output is a self-contained unit, emitted in the order the
388
+ # host expects from the consolidated dispatcher).
389
+ for buf in _stdout_bufs:
390
+ sys.stdout.write(buf)
391
+ except BaseException:
392
+ # Catch BaseException (not just Exception) so _HookTimeout and any
393
+ # other BaseException subclass from measure.py is swallowed. The
394
+ # HookDeadline's os._exit(0) is uncatchable and bypasses this guard,
395
+ # which is the correct behavior (it exits 0).
396
+ try:
397
+ sys.stderr.write("[Token Optimizer] stop_runner top-level error, exiting 0\n")
398
+ traceback.print_exc(file=sys.stderr)
399
+ sys.stderr.flush()
400
+ except (OSError, ValueError):
401
+ pass
402
+ finally:
403
+ _clear_runner_deadline()
404
+ return 0
405
+
406
+
407
+ if __name__ == "__main__":
408
+ sys.exit(main())