@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,991 @@
1
+ #!/usr/bin/env python3
2
+ """Token Optimizer for Claude Code cloud sessions (claude.ai/code).
3
+
4
+ Cloud VMs load no plugins, so the plugin install never reaches them. What a
5
+ cloud VM does run is the environment's *setup script* (as root, before Claude
6
+ Code starts, for every repository and multi-repo session that uses the
7
+ environment) and the hooks in the VM's user-level ``~/.claude/settings.json``.
8
+
9
+ This module puts the REAL Token Optimizer there, not a reimplementation:
10
+
11
+ ``measure.py cloud-setup-script``
12
+ Prints a short, paste-ready setup script. It downloads the published npm
13
+ tarball ``@alexgreensh/token-optimizer@<version>`` from registry.npmjs.org,
14
+ checks its sha512 against the integrity the registry published, and only
15
+ then runs the ``install-cloud.sh`` inside it. Nothing unverified executes.
16
+
17
+ ``install-cloud.sh`` -> ``cloud_kit.py install``
18
+ Copies the package to ``~/.cache/token-optimizer-cloud/<version>``, writes
19
+ ``~/.cache/token-optimizer-cloud/token-optimizer-cloud-run.sh`` (sets CLAUDE_PLUGIN_ROOT and execs
20
+ the real hooks/python-launcher.sh -> hooks/run.py), and merges into
21
+ ``~/.claude/settings.json`` a hook map GENERATED from the package's own
22
+ hooks/hooks.json: same events, matchers, timeouts, async flags and runner
23
+ arguments, only the launcher prefix differs. Commands carry absolute paths
24
+ and never the literal ``${CLAUDE_PLUGIN_ROOT}`` (repo/user hooks containing
25
+ it never run in cloud sessions).
26
+
27
+ ``measure.py cloud-doctor``
28
+ Checks the install from inside a VM (or any machine).
29
+
30
+ Rules this module keeps:
31
+ * stdlib only, no imports from sibling modules: install runs under
32
+ ``python3 -I`` straight out of the extracted tarball.
33
+ * nothing is written into any repository working tree.
34
+ * settings are merged, never overwritten; only entries whose command runs
35
+ our run.sh are ever replaced or removed; JSONC / duplicate keys refused.
36
+ * ``main`` never raises (any error is one line on stderr, which
37
+ install-cloud.sh appends to install.log, and exit status 1), and the
38
+ shell wrapper always exits 0, so a cloud session's setup never fails.
39
+ """
40
+
41
+ from __future__ import annotations
42
+
43
+ import base64
44
+ import compileall
45
+ import hashlib
46
+ import json
47
+ import os
48
+ import re
49
+ import shlex
50
+ import shutil
51
+ import sys
52
+ import tempfile
53
+ import urllib.parse
54
+ import urllib.request
55
+ from pathlib import Path
56
+
57
+ PACKAGE = "@alexgreensh/token-optimizer"
58
+ REGISTRY = "https://registry.npmjs.org"
59
+ CACHE_DIRNAME = "token-optimizer-cloud"
60
+ RUNNER_NAME = "token-optimizer-cloud-run.sh"
61
+ # Every hook command we write contains this (whatever the cache dir is); it is
62
+ # how we, and measure.py's self-heal, recognize our entries and only ours.
63
+ MARKER = "/" + RUNNER_NAME
64
+
65
+ SCRIPTS_DIR = Path(__file__).resolve().parent
66
+ PLUGIN_ROOT = SCRIPTS_DIR.parents[2]
67
+
68
+ # Semver with an optional prerelease tag (5.13.50-rc.1). The charset stays
69
+ # shell-safe because the version is rendered into the setup script.
70
+ _VERSION_RE = re.compile(r"^\d+\.\d+\.\d+(?:-[0-9A-Za-z]+(?:\.[0-9A-Za-z]+)*)?$")
71
+
72
+
73
+ def _version_key(v: str):
74
+ """Sort key: releases after their prereleases, numeric parts numerically."""
75
+ core, _, pre = v.partition("-")
76
+ nums = tuple(int(x) for x in core.split("."))
77
+ if not pre:
78
+ return nums + ((1,),)
79
+ parts = tuple((0, int(x), "") if x.isdigit() else (1, 0, x) for x in pre.split("."))
80
+ return nums + ((0,) + parts,)
81
+ _ARG_RE = re.compile(r"^[A-Za-z0-9_./=:-]+$")
82
+ # The canonical hooks.json command ends with:
83
+ # exec "$b" "$L" "${CLAUDE_PLUGIN_ROOT}/hooks/run.py" <runner args>; done; exit 0
84
+ _CANON_RE = re.compile(r'"\$\{CLAUDE_PLUGIN_ROOT\}/hooks/run\.py" ([^;"\'`$]+?); done; exit 0$')
85
+
86
+
87
+ class KitError(Exception):
88
+ """A refusal with a message meant for the user."""
89
+
90
+
91
+ # --------------------------------------------------------------------- paths
92
+
93
+
94
+ def cache_dir() -> Path:
95
+ override = os.environ.get("TOKEN_OPTIMIZER_CLOUD_HOME")
96
+ if override:
97
+ return Path(override)
98
+ return Path(os.path.expanduser("~")) / ".cache" / CACHE_DIRNAME
99
+
100
+
101
+ def claude_dir() -> Path:
102
+ override = os.environ.get("CLAUDE_CONFIG_DIR")
103
+ if override:
104
+ return Path(override)
105
+ return Path(os.path.expanduser("~")) / ".claude"
106
+
107
+
108
+ # Managed-settings drop-in (opt-in fallback, see write_managed_fallback). Our
109
+ # own file in Claude Code's documented drop-in dir; managed-settings.json and
110
+ # every other file there are never read for writing, changed or removed.
111
+ MANAGED_DIR = "/etc/claude-code/managed-settings.d"
112
+ MANAGED_FILE = "50-token-optimizer-cloud.json"
113
+ MANAGED_ENV = "TOKEN_OPTIMIZER_CLOUD_MANAGED"
114
+ ROUTE_LOG = "route.log"
115
+
116
+
117
+ def managed_dir() -> Path:
118
+ return Path(os.environ.get("TOKEN_OPTIMIZER_CLOUD_MANAGED_DIR") or MANAGED_DIR)
119
+
120
+
121
+ def managed_fallback_requested() -> bool:
122
+ return os.environ.get(MANAGED_ENV, "").strip().lower() in ("1", "true", "yes", "on")
123
+
124
+
125
+ def package_version(root: Path) -> str:
126
+ for rel in ("package.json", ".claude-plugin/plugin.json"):
127
+ try:
128
+ v = json.loads((root / rel).read_text(encoding="utf-8")).get("version")
129
+ except (OSError, ValueError, AttributeError):
130
+ continue
131
+ if isinstance(v, str) and _VERSION_RE.match(v):
132
+ return v
133
+ raise KitError("cannot read a version from %s" % root)
134
+
135
+
136
+ # ------------------------------------------------------------------ hook map
137
+
138
+
139
+ def runner_args(command: str) -> list:
140
+ """Runner arguments of one canonical hooks.json command (after run.py)."""
141
+ m = _CANON_RE.search(command or "")
142
+ if not m:
143
+ raise KitError("hooks.json command has an unexpected shape: %r" % (command or "")[:120])
144
+ args = m.group(1).split()
145
+ for a in args:
146
+ if not _ARG_RE.match(a):
147
+ raise KitError("unexpected runner argument %r in hooks.json" % a)
148
+ return args
149
+
150
+
151
+ def hook_command(runner: Path, args: list) -> str:
152
+ r = shlex.quote(str(runner))
153
+ return "[ -r %s ] || exit 0; exec sh %s %s" % (r, r, " ".join(args))
154
+
155
+
156
+ def generate_hook_map(hooks_json: dict, runner: Path) -> dict:
157
+ """event -> groups, mirroring hooks.json exactly except each command."""
158
+ src = hooks_json.get("hooks") if isinstance(hooks_json, dict) else None
159
+ if not isinstance(src, dict) or not src:
160
+ raise KitError("hooks.json has no hooks")
161
+ out = {}
162
+ for event, groups in src.items():
163
+ new_groups = []
164
+ for group in groups:
165
+ g = {}
166
+ for key, value in group.items():
167
+ if key != "hooks":
168
+ g[key] = value
169
+ continue
170
+ hooks = []
171
+ for hook in value:
172
+ h = dict(hook)
173
+ if h.get("type") != "command":
174
+ raise KitError("non-command hook in hooks.json (%s)" % event)
175
+ h["command"] = hook_command(runner, runner_args(h.get("command", "")))
176
+ hooks.append(h)
177
+ g["hooks"] = hooks
178
+ new_groups.append(g)
179
+ out[event] = new_groups
180
+ return out
181
+
182
+
183
+ def load_hooks_json(root: Path) -> dict:
184
+ return json.loads((root / "hooks" / "hooks.json").read_text(encoding="utf-8"))
185
+
186
+
187
+ # ------------------------------------------------------------------ settings
188
+
189
+
190
+ def _no_dup_pairs(pairs):
191
+ seen = {}
192
+ for k, v in pairs:
193
+ if k in seen:
194
+ raise KitError("duplicate key %r" % k)
195
+ seen[k] = v
196
+ return seen
197
+
198
+
199
+ def load_settings(path: Path):
200
+ """Return (data, raw_text). {} for a missing or blank file."""
201
+ try:
202
+ raw = path.read_bytes()
203
+ except FileNotFoundError:
204
+ return {}, None
205
+ text = raw.decode("utf-8-sig")
206
+ if not text.strip():
207
+ return {}, text
208
+ try:
209
+ data = json.loads(text, object_pairs_hook=_no_dup_pairs)
210
+ except KitError as exc:
211
+ raise KitError("%s has a %s; nothing was changed" % (path, exc)) from None
212
+ except ValueError as exc:
213
+ raise KitError("%s is not plain JSON (comments or trailing commas?); nothing was "
214
+ "changed: %s" % (path, exc)) from None
215
+ if not isinstance(data, dict):
216
+ raise KitError("%s is not a JSON object; nothing was changed" % path)
217
+ return data, text
218
+
219
+
220
+ def _is_our_hook(hook) -> bool:
221
+ return isinstance(hook, dict) and MARKER in str(hook.get("command", ""))
222
+
223
+
224
+ def _is_ours(group) -> bool:
225
+ """True when a group carries at least one of our hook commands."""
226
+ return isinstance(group, dict) and isinstance(group.get("hooks"), list) and any(
227
+ _is_our_hook(h) for h in group["hooks"])
228
+
229
+
230
+ def _without_ours(groups: list) -> list:
231
+ """The groups with our hook commands taken out, hook by hook. A group that
232
+ also holds the user's own hooks (someone added one next to ours) keeps
233
+ them, with its matcher and other keys; only a group left with no hooks at
234
+ all is dropped. Groups without any of ours are returned untouched."""
235
+ kept = []
236
+ for group in groups:
237
+ if not _is_ours(group):
238
+ kept.append(group)
239
+ continue
240
+ rest = [h for h in group["hooks"] if not _is_our_hook(h)]
241
+ if rest:
242
+ g = dict(group)
243
+ g["hooks"] = rest
244
+ kept.append(g)
245
+ return kept
246
+
247
+
248
+ def _only_ours(groups: list) -> list:
249
+ """The inverse view, for the doctor: each group cut down to our hooks."""
250
+ out = []
251
+ for group in groups:
252
+ if _is_ours(group):
253
+ g = dict(group)
254
+ g["hooks"] = [h for h in group["hooks"] if _is_our_hook(h)]
255
+ out.append(g)
256
+ return out
257
+
258
+
259
+ def merge_settings(settings: dict, hook_map: dict) -> dict:
260
+ out = dict(settings)
261
+ hooks = out.get("hooks", {})
262
+ if not isinstance(hooks, dict):
263
+ raise KitError("'hooks' in settings.json is not an object; nothing was changed")
264
+ hooks = dict(hooks)
265
+ for event in list(hooks):
266
+ groups = hooks[event]
267
+ if not isinstance(groups, list):
268
+ raise KitError("hooks.%s in settings.json is not a list; nothing was changed" % event)
269
+ kept = _without_ours(groups)
270
+ if kept or event in hook_map or not groups:
271
+ hooks[event] = kept
272
+ else:
273
+ del hooks[event]
274
+ for event, groups in hook_map.items():
275
+ hooks[event] = hooks.get(event, []) + groups
276
+ out["hooks"] = hooks
277
+ return out
278
+
279
+
280
+ def strip_settings(settings: dict) -> dict:
281
+ hooks = settings.get("hooks")
282
+ if not isinstance(hooks, dict):
283
+ return dict(settings)
284
+ out = dict(settings)
285
+ new_hooks = {}
286
+ for event, groups in hooks.items():
287
+ if not isinstance(groups, list):
288
+ new_hooks[event] = groups
289
+ continue
290
+ kept = _without_ours(groups)
291
+ if kept or not groups:
292
+ new_hooks[event] = kept
293
+ if new_hooks or not hooks:
294
+ out["hooks"] = new_hooks
295
+ else:
296
+ del out["hooks"]
297
+ return out
298
+
299
+
300
+ def _indent_of(text) -> object:
301
+ if not text:
302
+ return 2
303
+ for line in text.splitlines()[1:]:
304
+ stripped = line.lstrip(" \t")
305
+ if stripped and stripped != line:
306
+ ws = line[: len(line) - len(stripped)]
307
+ return "\t" if ws.startswith("\t") else len(ws)
308
+ return 2
309
+
310
+
311
+ def dump_settings(data: dict, like_text) -> bytes:
312
+ return (json.dumps(data, indent=_indent_of(like_text), ensure_ascii=False) + "\n").encode("utf-8")
313
+
314
+
315
+ def _atomic_write(path: Path, data: bytes, mode=None) -> None:
316
+ path.parent.mkdir(parents=True, exist_ok=True)
317
+ if mode is None:
318
+ try:
319
+ mode = path.stat().st_mode & 0o777
320
+ except OSError:
321
+ mode = 0o644
322
+ fd, tmp = tempfile.mkstemp(dir=str(path.parent), prefix="." + path.name + ".", suffix=".tmp")
323
+ try:
324
+ with os.fdopen(fd, "wb") as fh:
325
+ fh.write(data)
326
+ os.chmod(tmp, mode)
327
+ os.replace(tmp, str(path))
328
+ except BaseException:
329
+ try:
330
+ os.unlink(tmp)
331
+ except OSError:
332
+ pass
333
+ raise
334
+
335
+
336
+ def write_settings_hooks(settings_path: Path, hook_map) -> bool:
337
+ """Merge (hook_map given) or strip (None). Returns True when the file changed."""
338
+ data, text = load_settings(settings_path)
339
+ new = merge_settings(data, hook_map) if hook_map is not None else strip_settings(data)
340
+ if new == data:
341
+ return False
342
+ # A file that held only our hooks is left as {} rather than deleted: we
343
+ # cannot know whether something else created it.
344
+ _atomic_write(settings_path, dump_settings(new, text))
345
+ return True
346
+
347
+
348
+ def write_managed_fallback(hook_map: dict, directory=None) -> str:
349
+ """Write the same hook map into our own managed-settings drop-in.
350
+
351
+ WHY, AND WHY OPT-IN. The primary route is the VM's ~/.claude/settings.json:
352
+ proven live (probe P7: hooks written there fire), absent at session start,
353
+ and separate from the launcher's own hooks (~/.claude/launcher-settings.json).
354
+ If a future launcher rewrote that file after the setup script, our hooks
355
+ would vanish silently. The only other documented layer a root setup script
356
+ can write without touching the repository is the managed tier:
357
+ /etc/claude-code/managed-settings.d/*.json on Linux (code.claude.com
358
+ managed-settings: drop-ins merge with managed-settings.json, one file per
359
+ owner). Hooks there merge with user hooks, and a handler defined in more
360
+ than one settings file runs once (hooks docs, "Deduplication of identical
361
+ handlers"), so the drop-in carries byte-identical commands.
362
+
363
+ But the docs only promise that file to SELF-HOSTED environments ("also
364
+ reads the managed settings file in its runner image ... only when neither
365
+ server-managed settings nor an MDM policy supplies the managed tier"); for
366
+ Anthropic-hosted VMs they say policy comes from server-managed settings.
367
+ And a managed file that fails to parse stops Claude Code from starting. So
368
+ this is off unless asked for (TOKEN_OPTIMIZER_CLOUD_MANAGED=1, printed by
369
+ `cloud-setup-script --managed-fallback`), never touches another file in the
370
+ dir, and is written atomically. Returns the path written, '' when skipped.
371
+ """
372
+ d = Path(directory) if directory else managed_dir()
373
+ if not managed_fallback_requested() and directory is None:
374
+ return ""
375
+ target = d / MANAGED_FILE
376
+ data = (json.dumps({"hooks": hook_map}, indent=2, ensure_ascii=False) + "\n").encode("utf-8")
377
+ try:
378
+ if target.read_bytes() == data:
379
+ return str(target)
380
+ except OSError:
381
+ pass
382
+ _atomic_write(target, data, 0o644)
383
+ return str(target)
384
+
385
+
386
+ def remove_managed_fallback(directory=None) -> bool:
387
+ """Delete our drop-in, only if it is ours (carries our runner marker)."""
388
+ target = (Path(directory) if directory else managed_dir()) / MANAGED_FILE
389
+ try:
390
+ if MARKER not in target.read_text(encoding="utf-8", errors="replace"):
391
+ return False
392
+ target.unlink()
393
+ return True
394
+ except OSError:
395
+ return False
396
+
397
+
398
+ def managed_fallback_hooks(directory=None) -> dict:
399
+ """Our hooks as the managed drop-in carries them ({} when absent)."""
400
+ target = (Path(directory) if directory else managed_dir()) / MANAGED_FILE
401
+ try:
402
+ data = json.loads(target.read_text(encoding="utf-8"))
403
+ except (OSError, ValueError):
404
+ return {}
405
+ hooks = data.get("hooks") if isinstance(data, dict) else None
406
+ if not isinstance(hooks, dict):
407
+ return {}
408
+ return {e: _only_ours(gs) for e, gs in hooks.items() if isinstance(gs, list) and _only_ours(gs)}
409
+
410
+
411
+ # --------------------------------------------------------------------- run.sh
412
+
413
+
414
+ RUN_SH = """#!/bin/sh
415
+ # Token Optimizer for Claude Code cloud sessions. Written by install-cloud.sh
416
+ # (version {version}); hooks in ~/.claude/settings.json call it. It runs one
417
+ # real Token Optimizer hook and stays silent itself.
418
+ # Off outside Claude Code cloud VMs; TOKEN_OPTIMIZER_CLOUD_KIT=off disables it,
419
+ # =force runs it anyway (skips both checks below).
420
+ R={root}
421
+ L="$R/hooks/python-launcher.sh"
422
+ [ -r "$L" ] || exit 0
423
+ case "${{TOKEN_OPTIMIZER_CLOUD_KIT:-}}" in
424
+ off|0|false) exit 0 ;;
425
+ force) ;;
426
+ *)
427
+ [ "$CLAUDE_CODE_REMOTE" = true ] || exit 0
428
+ # Stand down when the real plugin is loaded too (an enabled plugin install
429
+ # that applies here, or an account-synced copy), so no hook runs twice.
430
+ # The grep is a cheap pre-filter; cloud_kit.py decides on the parsed file
431
+ # (scope, project path, enabledPlugins).
432
+ P="${{CLAUDE_CONFIG_DIR:-$HOME/.claude}}/plugins"
433
+ if [ -f "$P/installed_plugins.json" ] && grep -Eq '"token-optimizer[^"@]*@' "$P/installed_plugins.json" 2>/dev/null; then
434
+ python3 -I "$R/skills/token-optimizer/scripts/cloud_kit.py" plugin-active >/dev/null 2>&1 && exit 0
435
+ fi
436
+ for f in "$P"/synced/*/token-optimizer*/hooks/hooks.json; do [ -f "$f" ] && exit 0; done
437
+ ;;
438
+ esac
439
+ # Route check, once per session: if our hooks are not in the user settings
440
+ # file, something rewrote it after the setup script and this hook was wired by
441
+ # another layer (the managed fallback). cloud-doctor reports the last line.
442
+ if [ "$1" = hooks/sessionstart_runner.py ]; then
443
+ S="${{CLAUDE_CONFIG_DIR:-$HOME/.claude}}/settings.json"
444
+ if ! grep -qF "/{runner_name}" "$S" 2>/dev/null; then
445
+ date -u "+%Y-%m-%dT%H:%M:%SZ session-start: hooks missing from $S; wired by another layer" \\
446
+ >> "$(dirname "$0")/{route_log}" 2>/dev/null
447
+ fi
448
+ fi
449
+ CLAUDE_PLUGIN_ROOT="$R"
450
+ PYTHONPYCACHEPREFIX={pycache}
451
+ export CLAUDE_PLUGIN_ROOT PYTHONPYCACHEPREFIX
452
+ # The kit version doubles as Token Optimizer's "this is a cloud VM" evidence
453
+ # (lean profile), so it is exported only inside one: =force on a desktop must
454
+ # not switch the desktop to the cloud profile.
455
+ if [ "$CLAUDE_CODE_REMOTE" = true ]; then
456
+ TOKEN_OPTIMIZER_CLOUD_KIT_VERSION={version}
457
+ export TOKEN_OPTIMIZER_CLOUD_KIT_VERSION
458
+ fi
459
+ exec bash "$L" "$R/hooks/run.py" "$@"
460
+ """
461
+
462
+
463
+ def render_run_sh(root: Path, pycache: Path, version: str) -> str:
464
+ return RUN_SH.format(root=shlex.quote(str(root)), pycache=shlex.quote(str(pycache)),
465
+ version=version, runner_name=RUNNER_NAME, route_log=ROUTE_LOG)
466
+
467
+
468
+ # -------------------------------------------------------------------- install
469
+
470
+ # What the package carries and the install copies. Everything else in the
471
+ # extracted tarball (package.json, README, LICENSE files) is copied too; this
472
+ # list is what must exist for a usable install.
473
+ _REQUIRED = ("hooks/hooks.json", "hooks/python-launcher.sh", "hooks/run.py",
474
+ "skills/token-optimizer/scripts/measure.py")
475
+
476
+
477
+ # Written into the cache dir on install. Uninstall only removes the shared
478
+ # names (pycache, .stage-*, the runner, install.log) where it finds this, and
479
+ # prune/uninstall only remove version dirs that hold our package: the cache
480
+ # dir can be user-set (TOKEN_OPTIMIZER_CLOUD_HOME) and shared with other tools.
481
+ CACHE_MARKER = ".token-optimizer-cloud-kit"
482
+
483
+
484
+ def _is_our_version_dir(child: Path) -> bool:
485
+ if not child.is_dir() or child.is_symlink() or not _VERSION_RE.match(child.name):
486
+ return False
487
+ if not (child / "hooks" / "run.py").is_file():
488
+ return False
489
+ for rel, want in (("package.json", PACKAGE), (".claude-plugin/plugin.json", "token-optimizer")):
490
+ try:
491
+ if json.loads((child / rel).read_text(encoding="utf-8")).get("name") == want:
492
+ return True
493
+ except (OSError, ValueError, AttributeError):
494
+ continue
495
+ return False
496
+
497
+
498
+ def _validate_tree(root: Path) -> None:
499
+ missing = [r for r in _REQUIRED if not (root / r).is_file()]
500
+ if missing:
501
+ raise KitError("package at %s is incomplete, missing: %s" % (root, ", ".join(missing)))
502
+
503
+
504
+ def _precompile(root: Path, pycache: Path) -> None:
505
+ """Byte-compile into the pycache prefix so the first hooks start warm.
506
+
507
+ Keyed by absolute source path, so it must run on the final location.
508
+ """
509
+ old = sys.pycache_prefix
510
+ sys.pycache_prefix = str(pycache)
511
+ try:
512
+ for sub in ("hooks", "skills/token-optimizer/scripts"):
513
+ compileall.compile_dir(str(root / sub), quiet=1, workers=1)
514
+ finally:
515
+ sys.pycache_prefix = old
516
+
517
+
518
+ def install(source: Path, cache=None, claude=None, precompile=True) -> dict:
519
+ source = Path(source).resolve()
520
+ cache = Path(cache) if cache else cache_dir()
521
+ claude = Path(claude) if claude else claude_dir()
522
+ _validate_tree(source)
523
+ version = package_version(source)
524
+ target = cache / version
525
+ cache.mkdir(parents=True, exist_ok=True)
526
+
527
+ if source != target.resolve() and not (target / "hooks" / "run.py").is_file():
528
+ stage = Path(tempfile.mkdtemp(prefix=".stage-", dir=str(cache)))
529
+ try:
530
+ shutil.copytree(str(source), str(stage / "pkg"), symlinks=False,
531
+ ignore=shutil.ignore_patterns("__pycache__", "*.pyc"))
532
+ _validate_tree(stage / "pkg")
533
+ try:
534
+ os.rename(str(stage / "pkg"), str(target))
535
+ except OSError:
536
+ if not (target / "hooks" / "run.py").is_file():
537
+ raise
538
+ finally:
539
+ shutil.rmtree(str(stage), ignore_errors=True)
540
+ _validate_tree(target)
541
+
542
+ pycache = cache / "pycache"
543
+ runner = cache / RUNNER_NAME
544
+ _atomic_write(cache / CACHE_MARKER, b"Token Optimizer cloud kit cache. Safe to delete with the dir.\n", 0o644)
545
+ _atomic_write(runner, render_run_sh(target, pycache, version).encode("utf-8"), 0o755)
546
+
547
+ hook_map = generate_hook_map(load_hooks_json(target), runner)
548
+ settings_path = claude / "settings.json"
549
+ changed = write_settings_hooks(settings_path, hook_map)
550
+ managed = ""
551
+ if managed_fallback_requested():
552
+ try:
553
+ managed = write_managed_fallback(hook_map)
554
+ except OSError as exc: # not root, read-only /etc: the primary route stands
555
+ managed = "skipped: %s" % exc
556
+
557
+ if precompile:
558
+ try:
559
+ _precompile(target, pycache)
560
+ except Exception: # noqa: BLE001 - warm start is an optimization only
561
+ pass
562
+
563
+ pruned = []
564
+ for child in sorted(cache.iterdir()):
565
+ if child.name != version and _is_our_version_dir(child):
566
+ shutil.rmtree(str(child), ignore_errors=True)
567
+ pruned.append(child.name)
568
+
569
+ return {"version": version, "root": str(target), "runner": str(runner),
570
+ "settings": str(settings_path), "settings_changed": changed,
571
+ "managed_fallback": managed, "events": sorted(hook_map), "pruned": pruned}
572
+
573
+
574
+ def uninstall(cache=None, claude=None) -> dict:
575
+ cache = Path(cache) if cache else cache_dir()
576
+ claude = Path(claude) if claude else claude_dir()
577
+ changed = write_settings_hooks(claude / "settings.json", None)
578
+ removed = []
579
+ if remove_managed_fallback():
580
+ removed.append(MANAGED_FILE)
581
+ if cache.is_dir():
582
+ ours = (cache / CACHE_MARKER).is_file()
583
+ for child in cache.iterdir():
584
+ if _is_our_version_dir(child) or (ours and child.is_dir() and not child.is_symlink() and (
585
+ child.name == "pycache" or child.name.startswith(".stage-"))):
586
+ shutil.rmtree(str(child), ignore_errors=True)
587
+ removed.append(child.name)
588
+ for name in ((RUNNER_NAME, "install.log", ROUTE_LOG, CACHE_MARKER) if ours else (RUNNER_NAME,)):
589
+ p = cache / name
590
+ if p.is_file():
591
+ p.unlink()
592
+ removed.append(name)
593
+ try:
594
+ cache.rmdir()
595
+ except OSError:
596
+ pass
597
+ return {"settings_changed": changed, "removed": sorted(removed)}
598
+
599
+
600
+ # --------------------------------------------------------------- setup script
601
+
602
+
603
+ def tarball_url(version: str, registry: str = REGISTRY) -> str:
604
+ return "%s/%s/-/token-optimizer-%s.tgz" % (registry.rstrip("/"), PACKAGE, version)
605
+
606
+
607
+ def integrity_of_file(path: Path) -> str:
608
+ h = hashlib.sha512()
609
+ with open(path, "rb") as fh:
610
+ for chunk in iter(lambda: fh.read(1 << 16), b""):
611
+ h.update(chunk)
612
+ return "sha512-" + base64.b64encode(h.digest()).decode("ascii")
613
+
614
+
615
+ def registry_dist(version: str, registry: str = REGISTRY, timeout: float = 15.0) -> dict:
616
+ url = "%s/%s/%s" % (registry.rstrip("/"), urllib.parse.quote(PACKAGE, safe="@"), version)
617
+ try:
618
+ with urllib.request.urlopen(url, timeout=timeout) as resp: # noqa: S310 - fixed https host
619
+ meta = json.loads(resp.read().decode("utf-8"))
620
+ except Exception as exc: # noqa: BLE001
621
+ raise KitError("could not read %s@%s from %s (%s). Is this version published on npm?"
622
+ % (PACKAGE, version, registry, exc)) from None
623
+ dist = meta.get("dist") or {}
624
+ integrity = " ".join(i for i in str(dist.get("integrity", "")).split() if i.startswith("sha512-"))
625
+ if not integrity:
626
+ raise KitError("registry has no sha512 integrity for %s@%s" % (PACKAGE, version))
627
+ return {"tarball": dist.get("tarball") or tarball_url(version, registry),
628
+ "integrity": integrity.split()[0]}
629
+
630
+
631
+ # The verify-then-run core shared by both channels. $U = tarball URL, $I = the
632
+ # sha512 integrity string. install-cloud.sh only runs after the hash matched.
633
+ _VERIFY_RUN = (
634
+ 'curl -fsSL --retry 2 --max-time 120 -o t.tgz "$U" && '
635
+ '[ "sha512-$(openssl dgst -sha512 -binary t.tgz | base64 | tr -d \'\\n\')" = "$I" ] && '
636
+ 'tar -xzf t.tgz && sh package/install-cloud.sh'
637
+ )
638
+
639
+
640
+ def _install_cmd(managed: bool) -> str:
641
+ return ("%s=1 sh package/install-cloud.sh" % MANAGED_ENV) if managed else "sh package/install-cloud.sh"
642
+
643
+
644
+ def render_setup_script(version: str, integrity: str, url: str, managed: bool = False) -> str:
645
+ """Pinned: the paste carries the hash, so the code that runs is fixed."""
646
+ for v, label in ((version, "version"), (integrity, "integrity")):
647
+ if "'" in v or "\n" in v:
648
+ raise KitError("bad %s" % label)
649
+ if not _VERSION_RE.match(version) or not integrity.startswith("sha512-"):
650
+ raise KitError("bad version or integrity")
651
+ return (
652
+ "# Token Optimizer %s for Claude Code cloud sessions: fetches the npm tarball, checks its\n"
653
+ "# sha512, runs its install-cloud.sh. Quiet and never fails the setup (log: ~/.cache/%s/install.log).\n"
654
+ "( U=%s I=%s T=\"$(mktemp -d)\" && cd \"$T\" && %s; cd /; rm -rf \"$T\" ) >/dev/null 2>&1 || true\n"
655
+ % (version, CACHE_DIRNAME, shlex.quote(url), shlex.quote(integrity),
656
+ _VERIFY_RUN.replace("sh package/install-cloud.sh", _install_cmd(managed)))
657
+ )
658
+
659
+
660
+ def render_setup_script_latest(registry: str = REGISTRY, managed: bool = False) -> str:
661
+ """Follows the `latest` dist-tag; the hash is the registry's own integrity.
662
+
663
+ That hash proves the bytes arrived intact, not who published them: this
664
+ script trusts whatever is published under the package name."""
665
+ meta = "%s/%s/latest" % (registry.rstrip("/"), urllib.parse.quote(PACKAGE, safe="@"))
666
+ prefix = "%s/%s/-/" % (registry.rstrip("/"), PACKAGE)
667
+ py = ('import json,sys;d=json.load(open(sys.argv[1]))["dist"];'
668
+ 'print(d["tarball"],[i for i in d["integrity"].split() if i.startswith("sha512-")][0])')
669
+ return (
670
+ "# Token Optimizer (latest on npm) for Claude Code cloud sessions: checks the tarball against\n"
671
+ "# the sha512 the registry publishes. Quiet and never fails the setup (log: ~/.cache/%s/install.log).\n"
672
+ "( T=\"$(mktemp -d)\" && cd \"$T\" && curl -fsSL --max-time 30 -o m.json %s && "
673
+ "set -- $(python3 -I -c %s m.json) && U=\"$1\" I=\"$2\" && [ \"${U#%s}\" != \"$U\" ] && %s; "
674
+ "cd /; rm -rf \"$T\" ) >/dev/null 2>&1 || true\n"
675
+ % (CACHE_DIRNAME, shlex.quote(meta), shlex.quote(py), prefix,
676
+ _VERIFY_RUN.replace("sh package/install-cloud.sh", _install_cmd(managed)))
677
+ )
678
+
679
+
680
+ # --------------------------------------------------------------------- doctor
681
+
682
+
683
+ _TO_KEY_RE = re.compile(r"^token-optimizer[^@]*@")
684
+
685
+
686
+ def _same_dir(a, b) -> bool:
687
+ try:
688
+ return Path(a).resolve() == Path(b).resolve()
689
+ except (OSError, RuntimeError, ValueError, TypeError):
690
+ return False
691
+
692
+
693
+ def _enabled_flag(path: Path, key: str):
694
+ """enabledPlugins[key] from one settings file: True / False / None (unset)."""
695
+ try:
696
+ data = json.loads(path.read_text(encoding="utf-8-sig"))
697
+ except (OSError, ValueError):
698
+ return None
699
+ flags = data.get("enabledPlugins") if isinstance(data, dict) else None
700
+ value = flags.get(key) if isinstance(flags, dict) else None
701
+ return value if isinstance(value, bool) else None
702
+
703
+
704
+ def _registry_entry_active(key: str, records, claude: Path, project) -> bool:
705
+ """True when one installed_plugins.json entry is a Token Optimizer install
706
+ that Claude Code loads for THIS session: a user-scope install, or a
707
+ project/local-scope one whose projectPath is this project, and not turned
708
+ off in enabledPlugins (project settings beat user settings)."""
709
+ applies = False
710
+ for rec in records if isinstance(records, list) else []:
711
+ if not isinstance(rec, dict):
712
+ continue
713
+ scope = rec.get("scope") or "user"
714
+ if scope in ("user", "managed"):
715
+ applies = True
716
+ elif scope in ("project", "local") and project and _same_dir(rec.get("projectPath") or "", project):
717
+ applies = True
718
+ if not applies:
719
+ return False
720
+ layers = []
721
+ if project:
722
+ layers += [Path(project) / ".claude" / "settings.local.json", Path(project) / ".claude" / "settings.json"]
723
+ layers.append(claude / "settings.json")
724
+ for layer in layers:
725
+ flag = _enabled_flag(layer, key)
726
+ if flag is not None:
727
+ return flag
728
+ return True
729
+
730
+
731
+ def plugin_loaded(claude=None, project=None) -> str:
732
+ """Mirror of run.sh's stand-down check. Returns the reason, '' when clear.
733
+
734
+ Stands down only for a Token Optimizer plugin Claude Code actually loads
735
+ here: an enabled install whose scope covers this project, or an
736
+ account-synced copy (when account plugin sync reaches cloud VMs, the synced
737
+ plugin runs and the kit must step aside). A disabled entry, or one scoped
738
+ to another project, no longer silences the kit. An unreadable registry that
739
+ names Token Optimizer still stands down: two copies of every hook is the
740
+ worse failure."""
741
+ claude = Path(claude) if claude else claude_dir()
742
+ if project is None:
743
+ project = os.environ.get("CLAUDE_PROJECT_DIR") or os.getcwd()
744
+ plugins = claude / "plugins"
745
+ reg = plugins / "installed_plugins.json"
746
+ try:
747
+ text = reg.read_text(encoding="utf-8", errors="replace")
748
+ except OSError:
749
+ text = ""
750
+ if text and re.search(r'"token-optimizer[^"@]*@', text):
751
+ try:
752
+ data = json.loads(text)
753
+ entries = data.get("plugins") if isinstance(data, dict) else None
754
+ if not isinstance(entries, dict):
755
+ raise ValueError("no plugins map")
756
+ except ValueError:
757
+ return "plugin named in an unreadable %s" % reg
758
+ for key, records in sorted(entries.items()):
759
+ if isinstance(key, str) and _TO_KEY_RE.match(key) and \
760
+ _registry_entry_active(key, records, claude, project):
761
+ return "plugin %s listed in %s" % (key, reg)
762
+ for f in sorted(plugins.glob("synced/*/token-optimizer*/hooks/hooks.json")):
763
+ if f.is_file():
764
+ return "account-synced plugin at %s" % f.parents[1]
765
+ return ""
766
+
767
+
768
+ def _host_detail() -> str:
769
+ keys = ("CLAUDE_CODE_REMOTE", "CLAUDE_CODE_REMOTE_ENVIRONMENT_TYPE", "CLAUDE_CODE_REMOTE_SESSION_ID")
770
+ return ", ".join("%s=%s" % (k, os.environ.get(k) or "(unset)") for k in keys)
771
+
772
+
773
+ def doctor(cache=None, claude=None, managed=None) -> dict:
774
+ """Check the install and say which route runs the hooks in THIS session.
775
+
776
+ Routes, in the order Claude Code would honour them for Token Optimizer:
777
+ a loaded plugin (installed or account-synced: the kit stands down), the
778
+ VM's ~/.claude/settings.json (the setup script's primary target), the
779
+ opt-in managed-settings drop-in, or none. "Hooks missing from
780
+ ~/.claude/settings.json" while the runner is installed means something
781
+ rewrote that file after the setup script ran: called out on its own."""
782
+ cache = Path(cache) if cache else cache_dir()
783
+ claude = Path(claude) if claude else claude_dir()
784
+ checks = []
785
+
786
+ def add(ok, name, detail):
787
+ checks.append({"ok": bool(ok), "check": name, "detail": detail})
788
+
789
+ in_cloud = os.environ.get("CLAUDE_CODE_REMOTE", "").strip().lower() == "true"
790
+ add(True, "Cloud session", _host_detail())
791
+ runner = cache / RUNNER_NAME
792
+ add(runner.is_file(), "Runner", str(runner) if runner.is_file() else "missing: run the setup script")
793
+ versions = sorted((c.name for c in cache.iterdir() if _is_our_version_dir(c)),
794
+ key=_version_key) if cache.is_dir() else []
795
+ root = cache / versions[-1] if versions else None
796
+ add(bool(versions), "Installed version", ", ".join(versions) or "none")
797
+ expected = None
798
+ if root is not None:
799
+ try:
800
+ expected = generate_hook_map(load_hooks_json(root), runner)
801
+ except (OSError, ValueError, KitError) as exc:
802
+ add(False, "Hook map", "cannot build from %s: %s" % (root, exc))
803
+
804
+ settings_path = claude / "settings.json"
805
+ ours = {}
806
+ settings_error = ""
807
+ try:
808
+ data, _ = load_settings(settings_path)
809
+ hooks = data.get("hooks") if isinstance(data.get("hooks"), dict) else {}
810
+ ours = {e: _only_ours(gs) for e, gs in hooks.items() if isinstance(gs, list)}
811
+ ours = {e: gs for e, gs in ours.items() if gs}
812
+ except KitError as exc:
813
+ settings_error = str(exc)
814
+ managed_hooks = managed_fallback_hooks(managed)
815
+ managed_path = (Path(managed) if managed else managed_dir()) / MANAGED_FILE
816
+ reason = plugin_loaded(claude)
817
+
818
+ if reason:
819
+ route = "plugin"
820
+ elif ours:
821
+ route = "settings"
822
+ elif managed_hooks:
823
+ route = "managed"
824
+ else:
825
+ route = "none"
826
+
827
+ if settings_error:
828
+ add(False, "Settings hooks", settings_error)
829
+ elif not ours:
830
+ if runner.is_file() and in_cloud:
831
+ add(route in ("managed", "plugin"), "Settings hooks",
832
+ "MISSING from %s at session time: the setup script wrote them, so something "
833
+ "rewrote the file after it ran. %s" % (
834
+ settings_path,
835
+ "Hooks still run through the managed fallback (%s)." % managed_path
836
+ if route == "managed" else
837
+ "No other route wires them: Token Optimizer is NOT running in this session. "
838
+ "Re-run the setup script, or add --managed-fallback to it."
839
+ if route == "none" else "The plugin runs the hooks instead."))
840
+ else:
841
+ add(route in ("managed", "plugin"), "Settings hooks", "none in %s" % settings_path)
842
+ elif expected is None:
843
+ add(True, "Settings hooks", "%d events wired" % len(ours))
844
+ else:
845
+ add(ours == expected, "Settings hooks",
846
+ "match hooks.json (%d events)" % len(expected) if ours == expected
847
+ else "drift from hooks.json: re-run the setup script")
848
+
849
+ if managed_hooks:
850
+ same = expected is None or managed_hooks == expected
851
+ add(same, "Managed fallback", "%s (%s)" % (
852
+ managed_path, "identical to the settings hooks, deduplicated by Claude Code" if same
853
+ else "drift from hooks.json: re-run the setup script"))
854
+ else:
855
+ add(True, "Managed fallback", "not installed (opt-in: cloud-setup-script --managed-fallback)")
856
+ add(True, "Plugin also loaded", ("yes, the cloud hooks stand down (%s)" % reason) if reason else "no")
857
+
858
+ labels = {"plugin": "the Token Optimizer plugin (%s)" % reason,
859
+ "settings": "%s (setup script)" % settings_path,
860
+ "managed": "%s (managed fallback)" % managed_path,
861
+ "none": "none: no hooks are wired"}
862
+ add(route != "none", "Live route", labels[route])
863
+ try:
864
+ lines = (cache / ROUTE_LOG).read_text(encoding="utf-8", errors="replace").splitlines()
865
+ if lines:
866
+ add(True, "Route log", "%d session start(s) without settings hooks; last: %s"
867
+ % (len(lines), lines[-1]))
868
+ except OSError:
869
+ pass
870
+ return {"ok": all(c["ok"] for c in checks), "route": route, "checks": checks}
871
+
872
+
873
+ # ------------------------------------------------------------------------ CLI
874
+
875
+ _SETUP_USAGE = """usage: measure.py cloud-setup-script [--latest] [--managed-fallback] [--version V]
876
+ [--integrity sha512-...] [--from-tarball FILE] [--registry URL]
877
+
878
+ Prints a setup script for Claude Code cloud environments (claude.ai/code ->
879
+ environment settings -> Setup script). Paste it once per environment: every
880
+ session in that environment, any repo, then runs the real Token Optimizer
881
+ hooks. Default pins this version and its registry sha512.
882
+
883
+ --latest follow npm's latest tag instead. Each download is checked
884
+ against the sha512 the registry publishes, which proves the
885
+ bytes are intact, NOT who published them: it trusts whatever
886
+ is published under @alexgreensh/token-optimizer.
887
+ --managed-fallback also write the hooks to /etc/claude-code/managed-settings.d/
888
+ (our own drop-in file), in case something rewrites
889
+ ~/.claude/settings.json after the setup script. Documented
890
+ for self-hosted environments; see the docs."""
891
+
892
+
893
+ def main_setup_script(argv) -> int:
894
+ if "-h" in argv or "--help" in argv:
895
+ print(_SETUP_USAGE)
896
+ return 0
897
+ opts = {"--version": None, "--integrity": None, "--from-tarball": None, "--registry": None,
898
+ "--tarball-url": None}
899
+ latest = False
900
+ managed = False
901
+ i = 0
902
+ while i < len(argv):
903
+ a = argv[i]
904
+ if a == "--latest":
905
+ latest = True
906
+ elif a == "--managed-fallback":
907
+ managed = True
908
+ elif a in opts and i + 1 < len(argv):
909
+ opts[a] = argv[i + 1]
910
+ i += 1
911
+ else:
912
+ print("cloud-setup-script: unknown argument %r\n\n%s" % (a, _SETUP_USAGE), file=sys.stderr)
913
+ return 2
914
+ i += 1
915
+ registry = opts["--registry"] or REGISTRY
916
+ try:
917
+ if latest:
918
+ sys.stdout.write(render_setup_script_latest(registry, managed=managed))
919
+ return 0
920
+ version = opts["--version"] or package_version(PLUGIN_ROOT)
921
+ url = opts["--tarball-url"] or tarball_url(version, registry)
922
+ if opts["--integrity"]:
923
+ integrity = opts["--integrity"]
924
+ elif opts["--from-tarball"]:
925
+ integrity = integrity_of_file(Path(opts["--from-tarball"]))
926
+ else:
927
+ dist = registry_dist(version, registry)
928
+ integrity, url = dist["integrity"], opts["--tarball-url"] or dist["tarball"]
929
+ sys.stdout.write(render_setup_script(version, integrity, url, managed=managed))
930
+ return 0
931
+ except (KitError, OSError) as exc:
932
+ print("cloud-setup-script: %s" % exc, file=sys.stderr)
933
+ return 1
934
+
935
+
936
+ def main_doctor(argv) -> int:
937
+ report = doctor()
938
+ if "--json" in argv:
939
+ print(json.dumps(report, indent=2, ensure_ascii=False))
940
+ else:
941
+ print("Token Optimizer cloud doctor")
942
+ for c in report["checks"]:
943
+ print(" [%s] %s: %s" % ("OK" if c["ok"] else "!!", c["check"], c["detail"]))
944
+ return 0 if report["ok"] else 1
945
+
946
+
947
+ def main(argv) -> int:
948
+ """Entry for install-cloud.sh: ``cloud_kit.py install --source DIR [--cache DIR]``."""
949
+ cmd = argv[0] if argv else ""
950
+ args = argv[1:]
951
+ opts = {}
952
+ i = 0
953
+ while i < len(args):
954
+ if args[i] in ("--source", "--cache", "--claude-dir") and i + 1 < len(args):
955
+ opts[args[i]] = args[i + 1]
956
+ i += 2
957
+ elif args[i] == "--no-precompile":
958
+ opts["--no-precompile"] = True
959
+ i += 1
960
+ else:
961
+ print("cloud_kit: unknown argument %r" % args[i], file=sys.stderr)
962
+ return 2
963
+ try:
964
+ if cmd == "install":
965
+ report = install(Path(opts.get("--source") or PLUGIN_ROOT), opts.get("--cache"),
966
+ opts.get("--claude-dir"), precompile="--no-precompile" not in opts)
967
+ elif cmd == "uninstall":
968
+ report = uninstall(opts.get("--cache"), opts.get("--claude-dir"))
969
+ elif cmd == "doctor":
970
+ return main_doctor(args)
971
+ elif cmd == "plugin-active":
972
+ # run.sh's stand-down: exit 0 = a loaded plugin owns the hooks.
973
+ return 0 if plugin_loaded() else 1
974
+ else:
975
+ print("usage: cloud_kit.py install|uninstall|doctor|plugin-active [--source DIR] [--cache DIR] "
976
+ "[--claude-dir DIR]", file=sys.stderr)
977
+ return 2
978
+ except (KitError, OSError) as exc:
979
+ print("cloud_kit %s: %s" % (cmd, exc), file=sys.stderr)
980
+ return 1
981
+ except Exception as exc: # noqa: BLE001 - never a traceback out of the setup script
982
+ # A settings.json that is not UTF-8, an odd value type, a bug: report
983
+ # it in install.log and fail this command, never raise.
984
+ print("cloud_kit %s: unexpected %s: %s" % (cmd, type(exc).__name__, exc), file=sys.stderr)
985
+ return 1
986
+ print(json.dumps(report, ensure_ascii=False))
987
+ return 0
988
+
989
+
990
+ if __name__ == "__main__":
991
+ sys.exit(main(sys.argv[1:]))