@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,709 @@
1
+ #!/usr/bin/env python3
2
+ """Token Optimizer — GitHub Copilot CLI hook bridge.
3
+
4
+ Thin, fast, fail-safe entry point invoked by Copilot's hooks system
5
+ (~/.copilot/hooks/token-optimizer.json). One bridge handles all events:
6
+
7
+ copilot_hook_bridge.py session-start
8
+ copilot_hook_bridge.py pre-tool-use
9
+ copilot_hook_bridge.py post-tool-use
10
+ copilot_hook_bridge.py stop
11
+
12
+ Contract notes (verified against github/copilot-cli as of v1.0.60, 2026-06-10):
13
+
14
+ - Hook payloads arrive on stdin as JSON. ``toolArgs`` may be a JSON-encoded
15
+ STRING (camelCase variant) or a parsed object under
16
+ ``tool_input`` (snake_case variant). Both are handled; anything that fails
17
+ to decode results in a silent no-op — never a malformed permission output.
18
+ - Every engine action is gated on ``capabilities.json``: a per-installed-
19
+ version capability map, refreshed whenever the Copilot CLI version changes
20
+ (upgrades AND downgrades — weekly releases break hook fields upstream).
21
+ - Output uses Copilot's hookSpecificOutput contract. ``updatedInput`` and
22
+ ``modifiedArgs`` are both emitted (release notes name both; emitting the
23
+ pair tolerates either reader). A schema mismatch is silently ignored by
24
+ Copilot, so the doctor's probe is the source of truth for whether rewrites
25
+ actually take effect on the installed version.
26
+
27
+ Security posture mirrors bash_hook.py: command rewriting reuses its
28
+ whitelist + dangerous-char exclusions; decisions fail CLOSED (emit nothing)
29
+ on any uncertainty. This bridge never imports Copilot internals and never
30
+ writes outside <copilot_home>/token-optimizer/.
31
+ """
32
+
33
+ from __future__ import annotations
34
+
35
+ import json
36
+ import logging
37
+ import os
38
+ import re
39
+ import shlex
40
+ import subprocess
41
+ import sys
42
+ import time
43
+ from contextlib import contextmanager
44
+ from pathlib import Path
45
+
46
+ logger = logging.getLogger(__name__)
47
+
48
+ # Windows console-flash guard. `copilot` is distributed via npm, so on
49
+ # Windows the PATH entry is copilot.cmd -- CreateProcess hands a .cmd to
50
+ # cmd.exe, a console-subsystem binary that allocates a console window unless
51
+ # the parent passes CREATE_NO_WINDOW. Same for python.exe children. getattr ->
52
+ # 0 on POSIX, where creationflags=0 is an accepted no-op (CPython only rejects
53
+ # creationflags != 0 off-Windows).
54
+ _NO_WINDOW = getattr(subprocess, "CREATE_NO_WINDOW", 0)
55
+
56
+ _SCRIPT_DIR = Path(__file__).resolve().parent
57
+ sys.path.insert(0, str(_SCRIPT_DIR))
58
+
59
+ # The bridge must run even if siblings are missing (partial install): every
60
+ # import below is optional, with the dependent feature disabled when absent.
61
+ try:
62
+ from runtime_env import copilot_home
63
+ except ImportError: # pragma: no cover - broken install
64
+ copilot_home = None # type: ignore[assignment]
65
+
66
+ try:
67
+ from spawn_utils import spawn_detached
68
+ except ImportError: # pragma: no cover - broken install
69
+ logger.warning("[copilot] spawn_utils import failed; using degraded fallback")
70
+ def spawn_detached(argv, **popen_kwargs): # type: ignore[no-redef]
71
+ # degraded broken-install path: does NOT detach. Does NOT replicate the
72
+ # OS-flag logic or the breakaway retry; canonical
73
+ # spawn_utils.spawn_detached has both. It DOES carry CREATE_NO_WINDOW
74
+ # so a broken install degrades to "child dies with the parent"
75
+ # rather than to "console window flashes on every stop hook". OR-in
76
+ # rather than assign so a caller-supplied creationflags survives.
77
+ import subprocess as _sp
78
+ kwargs = dict(popen_kwargs)
79
+ kwargs["creationflags"] = kwargs.get("creationflags", 0) | _NO_WINDOW
80
+ try:
81
+ return _sp.Popen(argv, **kwargs)
82
+ except OSError:
83
+ return None
84
+
85
+ try:
86
+ import bash_hook as _bash_hook
87
+ except ImportError: # pragma: no cover
88
+ _bash_hook = None # type: ignore[assignment]
89
+
90
+ try:
91
+ from codex_io import atomic_write_json as _atomic_write_json_impl
92
+ except ImportError: # pragma: no cover - broken install
93
+ _atomic_write_json_impl = None # type: ignore[assignment]
94
+
95
+ try:
96
+ from hook_runtime import lease_lock
97
+ except ImportError: # pragma: no cover - broken install
98
+ lease_lock = None # type: ignore[assignment]
99
+
100
+ _MAX_STDIN_BYTES = 4 * 1024 * 1024 # refuse absurd payloads (amplification)
101
+ # Snapshot at import: the installed payload is static for the process lifetime,
102
+ # so the per-hook-call exists() stat would be pure waste on the hot path.
103
+ _COMPRESS_PATH = _SCRIPT_DIR / "bash_compress.py"
104
+ _COMPRESS_AVAILABLE = _COMPRESS_PATH.exists()
105
+ _NUDGE_EVENTS_BYTES = (400_000, 900_000) # events.jsonl size thresholds (proxy for context growth)
106
+ _INFLIGHT_STALE_SECS = 7 * 24 * 3600
107
+
108
+ # Capability keys. Seeds encode the verified matrix for the installed version;
109
+ # see _seed_capabilities(). Manual override: TOKEN_OPTIMIZER_COPILOT_CAPS_JSON.
110
+ CAP_DENY = "deny"
111
+ CAP_ALLOW = "allow"
112
+ CAP_UPDATED_INPUT = "updated_input"
113
+ CAP_PRETOOL_CTX = "pretooluse_ctx"
114
+ CAP_POSTTOOL_CTX = "posttooluse_ctx"
115
+ CAP_USERPROMPT_CTX = "userprompt_ctx"
116
+ CAP_SESSIONSTART_CTX = "sessionstart_ctx"
117
+
118
+
119
+ # ---------------------------------------------------------------------------
120
+ # Payload decoding (fail-closed)
121
+ # ---------------------------------------------------------------------------
122
+
123
+ _SESSION_ID_RE = re.compile(r"[^A-Za-z0-9_-]")
124
+
125
+
126
+ def _sanitize_session_id(sid):
127
+ """Strip everything but [A-Za-z0-9_-] so a hook payload can never traverse.
128
+
129
+ Mirrors measure.sanitize_session_id (inlined to keep the hot-path bridge
130
+ free of the 24K-LOC measure import). A payload sessionId like
131
+ "/../../hooks/token-optimizer" would otherwise let _atomic_write_json /
132
+ unlink escape the data dir — lab-confirmed path traversal.
133
+ """
134
+ if not sid:
135
+ return "unknown"
136
+ cleaned = _SESSION_ID_RE.sub("", sid)[:64]
137
+ return cleaned if len(cleaned) >= 6 else "unknown"
138
+
139
+
140
+ def _read_stdin_payload():
141
+ """Read and decode the hook payload from stdin. None on any failure.
142
+
143
+ Intentionally NOT hook_io.read_stdin_hook_input: Copilot payloads carry
144
+ JSON-string-encoded toolArgs that can run large (4MB cap vs hook_io's 1MB)
145
+ and this reader rejects non-dict top-level values outright.
146
+ """
147
+ try:
148
+ raw = sys.stdin.read(_MAX_STDIN_BYTES + 1)
149
+ except (OSError, UnicodeDecodeError):
150
+ return None
151
+ if not raw or len(raw) > _MAX_STDIN_BYTES:
152
+ return None
153
+ try:
154
+ payload = json.loads(raw)
155
+ except (json.JSONDecodeError, ValueError):
156
+ return None
157
+ if not isinstance(payload, dict):
158
+ return None
159
+ return payload
160
+
161
+
162
+ def decode_payload(payload):
163
+ """Normalize a Copilot hook payload across its camelCase / snake_case shapes.
164
+
165
+ Returns a dict with: tool_name (str), tool_args (dict), session_id (str),
166
+ cwd (str), timestamp. Missing fields default to empty values; a
167
+ string-encoded toolArgs that fails to parse yields {} (fail-closed: the
168
+ caller then has no command to rewrite, so the hook no-ops).
169
+ """
170
+ out = {"tool_name": "", "tool_args": {}, "session_id": "", "cwd": "", "timestamp": None}
171
+ if not isinstance(payload, dict):
172
+ return out
173
+
174
+ tool_name = payload.get("toolName", payload.get("tool_name", ""))
175
+ if isinstance(tool_name, str):
176
+ out["tool_name"] = tool_name.strip()
177
+
178
+ raw_args = payload.get("toolArgs", payload.get("tool_args", payload.get("tool_input", {})))
179
+ if isinstance(raw_args, str):
180
+ if raw_args:
181
+ try:
182
+ parsed = json.loads(raw_args)
183
+ if isinstance(parsed, dict):
184
+ out["tool_args"] = parsed
185
+ except (json.JSONDecodeError, ValueError):
186
+ pass # fail-closed: leave {}
187
+ elif isinstance(raw_args, dict):
188
+ out["tool_args"] = raw_args
189
+
190
+ sid = payload.get("sessionId", payload.get("session_id", ""))
191
+ if isinstance(sid, str):
192
+ out["session_id"] = _sanitize_session_id(sid)
193
+ cwd = payload.get("cwd", "")
194
+ if isinstance(cwd, str):
195
+ # Cap: cwd is rewritten into the tally on every tool call and into
196
+ # restore-context; an unbounded value would bloat both.
197
+ out["cwd"] = cwd[:1024]
198
+ out["timestamp"] = payload.get("timestamp")
199
+ return out
200
+
201
+
202
+ # ---------------------------------------------------------------------------
203
+ # Capabilities (version-gated engine powers)
204
+ # ---------------------------------------------------------------------------
205
+
206
+
207
+ def _to_dir():
208
+ """Token Optimizer's data dir under the Copilot home. None if unavailable."""
209
+ if copilot_home is None:
210
+ return None
211
+ try:
212
+ d = copilot_home() / "token-optimizer"
213
+ d.mkdir(parents=True, exist_ok=True)
214
+ return d
215
+ except OSError:
216
+ return None
217
+
218
+
219
+ def _atomic_write_json(path, obj):
220
+ """Atomic JSON write; concurrent writers never corrupt or orphan tmp files.
221
+
222
+ Delegates to codex_io.atomic_write_json (mkstemp + unlink-on-failure).
223
+ """
224
+ if _atomic_write_json_impl is None:
225
+ logger.debug(
226
+ "[copilot_hook_bridge] codex_io unavailable — atomic write to %s "
227
+ "skipped (crash recovery / capability cache degraded this session)",
228
+ path,
229
+ )
230
+ return False
231
+ try:
232
+ _atomic_write_json_impl(path, obj)
233
+ return True
234
+ except OSError as exc:
235
+ logger.debug("[copilot_hook_bridge] atomic write to %s failed: %s", path, exc)
236
+ return False
237
+
238
+
239
+ def _parse_version(text):
240
+ """Extract (major, minor, patch) from a version string. None if absent."""
241
+ if not isinstance(text, str):
242
+ return None
243
+ m = re.search(r"(\d+)\.(\d+)\.(\d+)", text)
244
+ if not m:
245
+ return None
246
+ return (int(m.group(1)), int(m.group(2)), int(m.group(3)))
247
+
248
+
249
+ def _copilot_cli_version():
250
+ """Best-effort `copilot --version`. Returns (version_tuple, raw) or (None, "")."""
251
+ exe = os.environ.get("TOKEN_OPTIMIZER_COPILOT_BIN") or "copilot"
252
+ try:
253
+ proc = subprocess.run(
254
+ [exe, "--version"], capture_output=True, text=True,
255
+ encoding="utf-8", errors="replace", timeout=5,
256
+ creationflags=_NO_WINDOW,
257
+ )
258
+ raw = (proc.stdout or proc.stderr or "").strip()
259
+ return _parse_version(raw), raw
260
+ except (OSError, subprocess.SubprocessError, ValueError):
261
+ return None, ""
262
+
263
+
264
+ def _seed_capabilities(version):
265
+ """Verified capability matrix for a Copilot CLI version (2026-06-10 research).
266
+
267
+ Sources: github/copilot-cli release notes and issue tracker. Unknown/future versions stay conservative: fields with a
268
+ history of breakage stay OFF until the matrix is updated; long-stable
269
+ fields stay ON.
270
+ """
271
+ v = version or (0, 0, 0)
272
+ caps = {
273
+ CAP_DENY: True, # stable since launch
274
+ CAP_ALLOW: v >= (1, 0, 18), # v1.0.18 release notes
275
+ CAP_UPDATED_INPUT: v >= (1, 0, 24), # v1.0.24 Copilot CLI release notes
276
+ CAP_PRETOOL_CTX: False, # OPEN as of 2026-06-10
277
+ CAP_POSTTOOL_CTX: v >= (1, 0, 49), # v1.0.49/51 release notes
278
+ CAP_SESSIONSTART_CTX: True, # closed-fixed
279
+ # Worked through v1.0.59; regressed in v1.0.60 (Copilot CLI). Future
280
+ # versions stay OFF until the regression is confirmed fixed.
281
+ CAP_USERPROMPT_CTX: (1, 0, 30) <= v <= (1, 0, 59),
282
+ }
283
+ return caps
284
+
285
+
286
+ def load_capabilities(refresh=True):
287
+ """Load capabilities.json, re-seeding when the CLI version changed.
288
+
289
+ The override env TOKEN_OPTIMIZER_COPILOT_CAPS_JSON (a JSON object) wins
290
+ over everything — the escape hatch when upstream fixes land before our
291
+ matrix does.
292
+ """
293
+ override = os.environ.get("TOKEN_OPTIMIZER_COPILOT_CAPS_JSON", "").strip()
294
+ if override:
295
+ try:
296
+ data = json.loads(override)
297
+ if isinstance(data, dict):
298
+ base = _seed_capabilities(None)
299
+ # deny/allow are security decisions, not version-compat toggles:
300
+ # the override exists to flip injection caps when upstream fixes
301
+ # land, and must never weaken the block primitive.
302
+ base.update({
303
+ k: bool(v) for k, v in data.items()
304
+ if k in base and k not in (CAP_DENY, CAP_ALLOW)
305
+ })
306
+ return base
307
+ except (json.JSONDecodeError, ValueError):
308
+ pass
309
+
310
+ to_dir = _to_dir()
311
+ cap_path = to_dir / "capabilities.json" if to_dir else None
312
+ cached = None
313
+ if cap_path is not None and cap_path.exists():
314
+ try:
315
+ cached = json.loads(cap_path.read_text(encoding="utf-8"))
316
+ except (OSError, json.JSONDecodeError, ValueError):
317
+ cached = None
318
+
319
+ if not refresh and isinstance(cached, dict) and isinstance(cached.get("caps"), dict):
320
+ return cached["caps"]
321
+
322
+ # Hot-path guard: the pre/post-tool-use hooks pass refresh=False. If the
323
+ # cache file is absent (fresh install, first tool before sessionStart), do
324
+ # NOT spawn `copilot --version` on every tool call — that subprocess can
325
+ # block up to its 5s timeout per call. Return a conservative seeded default;
326
+ # sessionStart (refresh=True) writes the real cache shortly after.
327
+ if not refresh:
328
+ return _seed_capabilities(None)
329
+
330
+ version, raw = _copilot_cli_version()
331
+
332
+ # Detection failure must NOT downgrade a previously-resolved matrix back to
333
+ # the conservative "unknown" seed. The sessionStart hook and `bash install.sh`
334
+ # often run in a WSL-root context where the native-Windows `copilot` binary
335
+ # isn't on PATH, so `copilot --version` returns nothing there even though the
336
+ # CLI is real and capable. Erasing known-good caps in that context
337
+ # silently gates postToolUse/allow/updated-input off. Keep what we resolved.
338
+ if (
339
+ version is None
340
+ and isinstance(cached, dict)
341
+ and isinstance(cached.get("caps"), dict)
342
+ and cached.get("cli_version") not in (None, "", "unknown")
343
+ ):
344
+ return cached["caps"]
345
+
346
+ version_key = ".".join(str(n) for n in version) if version else "unknown"
347
+ if (
348
+ isinstance(cached, dict)
349
+ and cached.get("cli_version") == version_key
350
+ and isinstance(cached.get("caps"), dict)
351
+ ):
352
+ return cached["caps"]
353
+
354
+ return _write_capabilities(version, raw, cap_path)
355
+
356
+
357
+ def _write_capabilities(version, raw, cap_path=None):
358
+ """Seed caps for ``version`` and persist to ``cap_path``. Returns the caps."""
359
+ caps = _seed_capabilities(version)
360
+ version_key = ".".join(str(n) for n in version) if version else "unknown"
361
+ if cap_path is None:
362
+ to_dir = _to_dir()
363
+ cap_path = to_dir / "capabilities.json" if to_dir else None
364
+ if cap_path is not None:
365
+ _atomic_write_json(
366
+ cap_path,
367
+ {
368
+ "cli_version": version_key,
369
+ "cli_version_raw": raw,
370
+ "seeded_at": time.time(),
371
+ "matrix_research_date": "2026-06-10",
372
+ "caps": caps,
373
+ },
374
+ )
375
+ return caps
376
+
377
+
378
+ def reseed_capabilities(version, raw=""):
379
+ """Force-write the capability matrix for an externally-resolved version.
380
+
381
+ copilot-doctor calls this to self-heal a matrix stuck at "unknown" (or seeded
382
+ for an older CLI) the moment it HAS resolved the real version. The doctor runs
383
+ in the native shell where `copilot` is on PATH, unlike the WSL-root hook that
384
+ seeded "unknown". Returns the freshly-written caps.
385
+ """
386
+ return _write_capabilities(version, raw)
387
+
388
+
389
+ # ---------------------------------------------------------------------------
390
+ # Event handlers
391
+ # ---------------------------------------------------------------------------
392
+
393
+
394
+ def _emit(obj):
395
+ print(json.dumps(obj))
396
+
397
+
398
+ def handle_session_start(payload):
399
+ """Refresh capabilities, clean stale in-flight tallies, inject continuity."""
400
+ caps = load_capabilities(refresh=True) # version check happens here
401
+
402
+ to_dir = _to_dir()
403
+ if to_dir is not None:
404
+ now = time.time()
405
+ try:
406
+ for p in to_dir.glob("inflight-*.json"):
407
+ try:
408
+ if now - p.stat().st_mtime > _INFLIGHT_STALE_SECS:
409
+ p.unlink()
410
+ except OSError:
411
+ continue
412
+ # Orphaned lease artifacts from the portable lock (hook_runtime.
413
+ # LeaseLock): published lock files and crash-left candidate files
414
+ # persist across sessions, so sweep them on the same stale threshold
415
+ # as the in-flight tallies. Error-tolerant like the tally sweep — a
416
+ # sweep failure must never break sessionStart.
417
+ for pattern in ("inflight-*.lock", ".inflight-*.lock.candidate-*"):
418
+ for p in to_dir.glob(pattern):
419
+ try:
420
+ if now - p.stat().st_mtime > _INFLIGHT_STALE_SECS:
421
+ p.unlink()
422
+ except OSError:
423
+ continue
424
+ except OSError:
425
+ pass
426
+
427
+ if not caps.get(CAP_SESSIONSTART_CTX):
428
+ return
429
+
430
+ # Continuity restore: measure.py copilot-rollup maintains this file from
431
+ # the previous session's decisions/checkpoint intel (U7 seam).
432
+ restore = None
433
+ if to_dir is not None:
434
+ restore_path = to_dir / "restore-context.md"
435
+ try:
436
+ if restore_path.exists() and restore_path.stat().st_size <= 16_384:
437
+ restore = restore_path.read_text(encoding="utf-8").strip() or None
438
+ except OSError:
439
+ restore = None
440
+ if restore:
441
+ _emit(
442
+ {
443
+ "hookSpecificOutput": {
444
+ "hookEventName": "sessionStart",
445
+ "additionalContext": restore,
446
+ }
447
+ }
448
+ )
449
+
450
+
451
+ def handle_pre_tool_use(payload):
452
+ """Bash output compression via updatedInput, gated and fail-closed."""
453
+ caps = load_capabilities(refresh=False)
454
+ if not caps.get(CAP_UPDATED_INPUT):
455
+ return
456
+ if _bash_hook is None:
457
+ return
458
+ if os.environ.get("TOKEN_OPTIMIZER_BASH_COMPRESS", "").strip() == "0":
459
+ return
460
+
461
+ fields = decode_payload(payload)
462
+ # Copilot's Unix terminal tool is `bash` (Windows: `powershell` — no
463
+ # compression there; bash_compress wrappers are POSIX).
464
+ if fields["tool_name"] != "bash":
465
+ return
466
+ command = fields["tool_args"].get("command", "")
467
+ if not isinstance(command, str) or not command:
468
+ return
469
+ if _bash_hook._has_dangerous_chars(command):
470
+ return
471
+ if not _bash_hook._is_whitelisted(command):
472
+ return
473
+
474
+ if not _COMPRESS_AVAILABLE:
475
+ return
476
+ compress_path = _COMPRESS_PATH
477
+ try:
478
+ original_tokens = shlex.split(command)
479
+ except ValueError:
480
+ return
481
+ rewritten = (
482
+ shlex.quote(sys.executable)
483
+ + " " + shlex.quote(str(compress_path))
484
+ + " " + " ".join(shlex.quote(t) for t in original_tokens)
485
+ )
486
+
487
+ # Emit only the fields we validated/produced. Echoing the whole tool_args
488
+ # dict would forward un-checked model-generated fields (e.g. a future
489
+ # `restart` flag) straight back into Copilot's execution input.
490
+ updated = {"command": rewritten}
491
+ if isinstance(fields["tool_args"].get("description"), str):
492
+ updated["description"] = fields["tool_args"]["description"]
493
+
494
+ # Release notes name both `updatedInput` and `modifiedArgs`; emit both so
495
+ # either reader applies. permissionDecision allow suppresses the approval
496
+ # dialog for the rewrite (capability-gated separately).
497
+ hook_out = {
498
+ "hookEventName": "preToolUse",
499
+ "updatedInput": updated,
500
+ "modifiedArgs": updated,
501
+ }
502
+ # Approve only commands that cannot write, delete or run other programs;
503
+ # anything else keeps Copilot's own approval dialog.
504
+ if caps.get(CAP_ALLOW) and _bash_hook._is_auto_approvable(command):
505
+ hook_out["permissionDecision"] = "allow"
506
+ _emit({"hookSpecificOutput": hook_out})
507
+
508
+
509
+ @contextmanager
510
+ def _session_lock(to_dir, sid):
511
+ """Bounded portable lease over a session's tally read-modify-write.
512
+
513
+ Fail-open on contention: contenders skip the mutation after 75ms rather
514
+ than blocking the hot path. The tally is a soft counter, so a skipped
515
+ update is tolerable. Broken-install fallback (hook_runtime unavailable)
516
+ proceeds without a lock, matching the prior best-effort behavior.
517
+ """
518
+ lock_path = to_dir / f"inflight-{sid}.lock"
519
+ if lease_lock is None:
520
+ yield True
521
+ return
522
+ with lease_lock(lock_path, acquire_timeout=0.075) as acquired:
523
+ yield acquired
524
+
525
+
526
+ def handle_post_tool_use(payload):
527
+ """Update the in-flight tally (crash recovery + liveness) and nudge."""
528
+ fields = decode_payload(payload)
529
+ sid = fields["session_id"] or "unknown"
530
+ to_dir = _to_dir()
531
+ nudge_level = 0
532
+ tool_calls = 1
533
+
534
+ if to_dir is not None:
535
+ with _session_lock(to_dir, sid) as acquired:
536
+ if not acquired:
537
+ return
538
+ tally_path = to_dir / f"inflight-{sid}.json"
539
+ tally = {}
540
+ try:
541
+ if tally_path.exists():
542
+ tally = json.loads(tally_path.read_text(encoding="utf-8"))
543
+ if not isinstance(tally, dict):
544
+ tally = {}
545
+ except (OSError, json.JSONDecodeError, ValueError):
546
+ tally = {}
547
+ tool_calls = int(tally.get("tool_calls", 0) or 0) + 1
548
+ tally.update(
549
+ {
550
+ "session_id": sid,
551
+ "updated_at": time.time(),
552
+ "tool_calls": tool_calls,
553
+ "cwd": fields["cwd"],
554
+ "models": tally.get("models", {}),
555
+ }
556
+ )
557
+ nudge_level = int(tally.get("nudge_level", 0) or 0)
558
+ # Hot path: skip the events.jsonl stat once the level is maxed out,
559
+ # and only touch capabilities.json when a nudge is actually firing.
560
+ if nudge_level < len(_NUDGE_EVENTS_BYTES):
561
+ new_level = _events_growth_level(sid)
562
+ else:
563
+ new_level = nudge_level
564
+ if new_level > nudge_level:
565
+ tally["nudge_level"] = new_level
566
+ _atomic_write_json(tally_path, tally)
567
+
568
+ if new_level > nudge_level and load_capabilities(refresh=False).get(CAP_POSTTOOL_CTX):
569
+ _emit(
570
+ {
571
+ "hookSpecificOutput": {
572
+ "hookEventName": "postToolUse",
573
+ "additionalContext": (
574
+ "[Token Optimizer] Context is growing large for this "
575
+ "session. Prefer targeted reads over full files, avoid "
576
+ "re-reading unchanged files, and summarize before "
577
+ "continuing long explorations."
578
+ ),
579
+ }
580
+ }
581
+ )
582
+
583
+
584
+ def _events_growth_level(session_id):
585
+ """0/1/2 by events.jsonl size — a cheap proxy for context growth.
586
+
587
+ Hook payloads carry no token data (a Copilot CLI hook contract gap), so size thresholds on the
588
+ persisted event stream are the honest live signal available per tool call.
589
+ """
590
+ if copilot_home is None or not session_id or session_id == "unknown":
591
+ return 0
592
+ try:
593
+ events = copilot_home() / "session-state" / session_id / "events.jsonl"
594
+ size = events.stat().st_size
595
+ except OSError:
596
+ return 0
597
+ level = 0
598
+ for threshold in _NUDGE_EVENTS_BYTES:
599
+ if size >= threshold:
600
+ level += 1
601
+ return level
602
+
603
+
604
+ def handle_stop(payload):
605
+ """Fire-and-forget rollup so trends stay fresh without blocking the CLI."""
606
+ fields = decode_payload(payload)
607
+ measure = _SCRIPT_DIR / "measure.py"
608
+ if not measure.exists():
609
+ return
610
+ env = dict(os.environ)
611
+ env["TOKEN_OPTIMIZER_RUNTIME"] = "copilot"
612
+ # Force UTF-8 in the spawned measure.py so non-ASCII session content can't crash it
613
+ # on a non-UTF-8 host (parity with run.py / the hermes bridge). measure.py also
614
+ # self-re-execs, but inject here so coverage doesn't hinge on os.execv being available.
615
+ env["PYTHONUTF8"] = "1"
616
+ env["PYTHONIOENCODING"] = "utf-8"
617
+ try:
618
+ _proc = spawn_detached(
619
+ [sys.executable, str(measure), "copilot-rollup", "--quiet"],
620
+ env=env,
621
+ stdout=subprocess.DEVNULL,
622
+ stderr=subprocess.DEVNULL,
623
+ )
624
+ except (OSError, subprocess.SubprocessError):
625
+ pass
626
+ else:
627
+ if _proc is None:
628
+ logger.warning("[copilot_hook_bridge] handle_stop spawn_detached returned None")
629
+ # Parity Gap 2: also refresh the dashboard on session-end so a Copilot user
630
+ # sees current data without a manual open (Claude Code/Codex/Cowork already
631
+ # do this). Detached + TOKEN_OPTIMIZER_INTERACTIVE=1 so it runs UNBOUNDED off
632
+ # the hot path -- never blocks the CLI, never truncates on the 20s hook budget.
633
+ try:
634
+ spawn_detached(
635
+ [sys.executable, str(measure), "dashboard", "--quiet"],
636
+ env={**env, "TOKEN_OPTIMIZER_INTERACTIVE": "1"},
637
+ stdout=subprocess.DEVNULL,
638
+ stderr=subprocess.DEVNULL,
639
+ )
640
+ except (OSError, subprocess.SubprocessError):
641
+ pass
642
+ # Remove this session's in-flight tally: shutdown event is now authoritative.
643
+ # Also drop the published lease lock file so a fast sessionStart doesn't
644
+ # see a stale inflight-{sid}.lock from this session (candidate files age
645
+ # out via the sessionStart sweep).
646
+ to_dir = _to_dir()
647
+ sid = fields["session_id"]
648
+ if to_dir is not None and sid:
649
+ try:
650
+ (to_dir / f"inflight-{sid}.json").unlink()
651
+ except OSError:
652
+ pass
653
+ # The .lock pathname IS the published LeaseLock name for this session
654
+ # (see _session_lock). Unlinking it unconditionally removes the
655
+ # rendezvous point out from under a PostToolUse handler that is still
656
+ # inside its critical section: a third process can then publish a fresh
657
+ # candidate onto the now-free name and run concurrently, while the
658
+ # original holder -- which operates on its own candidate inode -- never
659
+ # notices it was displaced. Nothing in the Copilot hook contract
660
+ # guarantees Stop is serialised after PostToolUse returns.
661
+ #
662
+ # So only remove the lock when it is provably unheld: take it
663
+ # non-blocking, and if that fails, leave it for the sessionStart sweep.
664
+ lock_path = to_dir / f"inflight-{sid}.lock"
665
+ if lease_lock is None:
666
+ try:
667
+ lock_path.unlink()
668
+ except OSError:
669
+ pass
670
+ else:
671
+ with lease_lock(lock_path, acquire_timeout=0) as acquired:
672
+ if acquired:
673
+ try:
674
+ lock_path.unlink()
675
+ except OSError:
676
+ pass
677
+
678
+
679
+ _HANDLERS = {
680
+ "session-start": handle_session_start,
681
+ "pre-tool-use": handle_pre_tool_use,
682
+ "post-tool-use": handle_post_tool_use,
683
+ "stop": handle_stop,
684
+ }
685
+
686
+
687
+ def main(argv=None):
688
+ try:
689
+ from utf8_io import enforce_utf8_io
690
+ enforce_utf8_io()
691
+ except Exception:
692
+ pass
693
+ args = list(sys.argv[1:] if argv is None else argv)
694
+ if not args or args[0] not in _HANDLERS:
695
+ return 0
696
+ os.environ.setdefault("TOKEN_OPTIMIZER_RUNTIME", "copilot")
697
+ payload = _read_stdin_payload()
698
+ if payload is None:
699
+ payload = {}
700
+ try:
701
+ _HANDLERS[args[0]](payload)
702
+ except Exception:
703
+ # A hook must never break the user's Copilot session. No output, exit 0.
704
+ return 0
705
+ return 0
706
+
707
+
708
+ if __name__ == "__main__":
709
+ sys.exit(main())