@alexgreensh/token-optimizer 0.0.0-stage → 5.13.51

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