@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,270 @@
1
+ #!/usr/bin/env python3
2
+ """Cowork adapter readiness checks for Token Optimizer.
3
+
4
+ Reports what can be verified FROM THIS MACHINE: desktop build, domain
5
+ allowlist state (the live dxt:allowlist* keys in the Claude desktop
6
+ config), local VM session tree, probe fire-matrix, payload built, OTel /
7
+ collector wiring. What it cannot see — the org admin plugin console state
8
+ and whether hooks fired in a CLOUD session — it reports as NEEDS-LIVE so
9
+ the live-verification checklist is explicit rather than silently green.
10
+
11
+ Stdlib-only on purpose: must run on a machine with nothing but python3.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import argparse
17
+ import json
18
+ import os
19
+ import plistlib
20
+ import sys
21
+ import urllib.parse
22
+ import urllib.request
23
+ from pathlib import Path
24
+ from typing import Any
25
+
26
+ # ONE source of truth: import the event tuple the packager actually
27
+ # emits instead of duplicating it. The doctor previously hardcoded
28
+ # ("SessionStart", "UserPromptSubmit", "PreToolUse", "Stop"), so it FAILed a
29
+ # correctly built payload -- SessionStart does NOT fire in Cowork and PostToolUse
30
+ # does -- and told the operator not to ship. cowork_doctor.py ships beside
31
+ # cowork_install.py in the same scripts dir, so this import always resolves.
32
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
33
+ from cowork_install import COWORK_EVENTS # noqa: E402
34
+
35
+
36
+ def _check(status: str, name: str, detail: str) -> dict[str, str]:
37
+ return {"status": status, "name": name, "detail": detail}
38
+
39
+
40
+ def _repo_root() -> Path:
41
+ """Walk up to the plugin root (holds .claude-plugin/plugin.json).
42
+
43
+ Mirrors cowork_install._repo_root: parents[3] is wrong from the
44
+ Codex-marketplace mirror tree, so walk up for the marker and fall back to the
45
+ legacy index if none is found. Keeps the doctor from reading payload/version
46
+ off the wrong root in the mirror.
47
+ """
48
+ here = Path(__file__).resolve()
49
+ for parent in here.parents:
50
+ if (parent / ".claude-plugin" / "plugin.json").exists():
51
+ return parent
52
+ parents = here.parents
53
+ return parents[3] if len(parents) > 3 else here.parent
54
+
55
+
56
+ def _desktop_support_dir() -> Path:
57
+ if sys.platform == "darwin":
58
+ return Path.home() / "Library" / "Application Support" / "Claude"
59
+ if sys.platform == "win32":
60
+ return Path(os.environ.get("APPDATA", Path.home() / "AppData" / "Roaming")) / "Claude"
61
+ return Path.home() / ".config" / "Claude"
62
+
63
+
64
+ def _desktop_build_checks() -> list[dict[str, str]]:
65
+ if sys.platform != "darwin":
66
+ return [_check("WARN", "Cowork desktop build", f"unsupported platform {sys.platform}; check the app version manually")]
67
+ plist = Path("/Applications/Claude.app/Contents/Info.plist")
68
+ if not plist.exists():
69
+ return [_check("WARN", "Cowork desktop build", "/Applications/Claude.app not found")]
70
+ try:
71
+ info = plistlib.loads(plist.read_bytes())
72
+ except Exception as exc: # noqa: BLE001 - report, never crash the doctor
73
+ return [_check("WARN", "Cowork desktop build", f"could not read Info.plist: {exc}")]
74
+ version = info.get("CFBundleShortVersionString", "unknown")
75
+ # OTel needs Desktop >= 1.1.4173 (local) / >= 1.22209.3 (cloud), Team or
76
+ # Enterprise (claude.com/docs/cowork/monitoring, fetched 2026-08-13).
77
+ return [_check("OK", "Cowork desktop build", f"Claude.app {version} (OTel needs >= 1.1.4173 local / 1.22209.3 cloud)")]
78
+
79
+
80
+ def _allowlist_checks() -> list[dict[str, str]]:
81
+ config = _desktop_support_dir() / "config.json"
82
+ if not config.exists():
83
+ return [_check("WARN", "Domain allowlist", f"{config} not found; is the Claude desktop app installed?")]
84
+ try:
85
+ data = json.loads(config.read_text(encoding="utf-8"))
86
+ except (OSError, json.JSONDecodeError) as exc:
87
+ return [_check("WARN", "Domain allowlist", f"could not read {config}: {exc}")]
88
+
89
+ checks: list[dict[str, str]] = []
90
+ keys = {k: v for k, v in data.items() if k.startswith("dxt:allowlist")}
91
+ if not keys:
92
+ return [_check("WARN", "Domain allowlist", "no dxt:allowlist* keys in desktop config; allowlist machinery not active on this machine")]
93
+ enabled_keys = {k: v for k, v in keys.items() if k.startswith("dxt:allowlistEnabled")}
94
+ for key, value in sorted(enabled_keys.items()):
95
+ scope = "global" if key == "dxt:allowlistEnabled" else f"env {key.split(':', 2)[2][:8]}…"
96
+ updated = data.get(key.replace("allowlistEnabled", "allowlistLastUpdated"), "?")
97
+ if value:
98
+ checks.append(_check("OK", f"Domain allowlist ({scope})", f"ENFORCED (updated {updated}) — the TO collector domain MUST be on the org allowlist or phone-home/OTel POSTs are blocked"))
99
+ else:
100
+ checks.append(_check("OK", f"Domain allowlist ({scope})", f"not enforced (enabled=false, updated {updated}) — outbound hook POSTs are not domain-filtered here"))
101
+ # The allowlist contents live server-side; the local cache is opaque.
102
+ checks.append(_check("NEEDS-LIVE", "Allowlist contents", "dxt:allowlistCache is an opaque blob; confirm the TO collector domain in the org admin console, not locally"))
103
+ return checks
104
+
105
+
106
+ def _session_tree_checks() -> list[dict[str, str]]:
107
+ tree = _desktop_support_dir() / "local-agent-mode-sessions"
108
+ if not tree.exists():
109
+ return [_check("WARN", "Local VM session tree", f"{tree} not found — no local Cowork sessions on this machine yet")]
110
+ sessions = [d for d in tree.iterdir() if d.is_dir() and d.name != "skills-plugin"]
111
+ checks = [_check("OK", "Local VM session tree", f"{tree} ({len(sessions)} session dir(s))")]
112
+ audits = sorted(tree.glob("*/**/audit.jsonl"), key=lambda p: p.stat().st_mtime, reverse=True)
113
+ if audits:
114
+ checks.append(_check("OK", "audit.jsonl", f"{len(audits)} found; newest: {audits[0]}"))
115
+ else:
116
+ checks.append(_check("WARN", "audit.jsonl", "none found under the session tree (cloud-only usage, or format changed)"))
117
+ bridge = list(tree.glob("*/**/bridge-state.json"))
118
+ if bridge:
119
+ checks.append(_check("OK", "Cloud-vs-local marker", f"bridge-state.json present ({len(bridge)}) — local VM sessions confirmed"))
120
+ else:
121
+ checks.append(_check("WARN", "Cloud-vs-local marker", "no bridge-state.json found; cannot distinguish cloud vs local from disk"))
122
+ return checks
123
+
124
+
125
+ def _probe_checks() -> list[dict[str, str]]:
126
+ checks: list[dict[str, str]] = []
127
+ fired: dict[str, int] = {}
128
+ ledgers = [
129
+ Path(os.environ.get("TO_PROBE_DIR", "") or (Path.home() / ".to-hook-probe")) / "fired.log",
130
+ Path("/tmp/to-hook-probe/fired.log"),
131
+ ]
132
+ seen_ledger = None
133
+ for ledger in ledgers:
134
+ try:
135
+ for line in ledger.read_text(encoding="utf-8", errors="replace").splitlines():
136
+ parts = line.split()
137
+ if len(parts) >= 2:
138
+ fired[parts[1]] = fired.get(parts[1], 0) + 1
139
+ seen_ledger = seen_ledger or ledger
140
+ except OSError:
141
+ continue
142
+ if not fired:
143
+ checks.append(_check("NEEDS-LIVE", "Hook fire matrix", "no to-hook-probe ledger found — push to-hook-probe via the org console and run one Cowork session (see cowork/to-hook-probe/README.md)"))
144
+ return checks
145
+ checks.append(_check("OK", "Probe ledger", f"{seen_ledger}"))
146
+ for event in COWORK_EVENTS:
147
+ if event in fired:
148
+ checks.append(_check("OK", f"Hook fires: {event}", f"{fired[event]} time(s)"))
149
+ else:
150
+ checks.append(_check("FAIL", f"Hook fires: {event}", "expected for the Cowork payload but never seen in the probe ledger"))
151
+ extras = sorted(set(fired) - set(COWORK_EVENTS))
152
+ if extras:
153
+ checks.append(_check("OK", "Bonus events firing", f"{', '.join(extras)} — consider widening COWORK_EVENTS in cowork_install.py"))
154
+ return checks
155
+
156
+
157
+ def _payload_checks(root: Path) -> list[dict[str, str]]:
158
+ try:
159
+ version = json.loads((root / ".claude-plugin" / "plugin.json").read_text(encoding="utf-8")).get("version", "?")
160
+ except (OSError, json.JSONDecodeError):
161
+ version = "?"
162
+ dist = root / "dist" / "cowork"
163
+ zips = sorted(dist.glob("*.zip")) if dist.exists() else []
164
+ if not zips:
165
+ return [_check("WARN", "Cowork payload", "not built yet; run: bash install.sh --cowork")]
166
+ checks = [_check("OK", "Cowork payload", ", ".join(z.name for z in zips))]
167
+ if not any(version in z.name for z in zips if "token-optimizer" in z.name):
168
+ checks.append(_check("WARN", "Payload version", f"no zip matches plugin.json version {version}; rebuild with: bash install.sh --cowork"))
169
+ hooks_file = dist / f"token-optimizer-cowork-{version}" / "hooks" / "hooks.json"
170
+ try:
171
+ events = sorted(json.loads(hooks_file.read_text(encoding="utf-8")).get("hooks", {}))
172
+ missing = [e for e in COWORK_EVENTS if e not in events]
173
+ if missing:
174
+ checks.append(_check("FAIL", "Payload hook events", f"missing {', '.join(missing)} (has: {', '.join(events)})"))
175
+ else:
176
+ checks.append(_check("OK", "Payload hook events", ", ".join(events)))
177
+ except (OSError, json.JSONDecodeError):
178
+ checks.append(_check("WARN", "Payload hook events", f"could not read {hooks_file}"))
179
+ return checks
180
+
181
+
182
+ def _telemetry_checks() -> list[dict[str, str]]:
183
+ checks: list[dict[str, str]] = []
184
+ otel = os.environ.get("OTEL_EXPORTER_OTLP_ENDPOINT", "").strip()
185
+ if otel:
186
+ checks.append(_check("OK", "OTel endpoint (env)", otel))
187
+ else:
188
+ checks.append(_check("NEEDS-LIVE", "OTel endpoint", "org-admin setting (Organization settings -> Cowork); not readable from this machine. Team/Enterprise only; http/protobuf (no gRPC for Cowork)"))
189
+ collector = os.environ.get("TO_COWORK_COLLECTOR_URL", "").strip() or os.environ.get("TO_PROBE_URL", "").strip()
190
+ if not collector:
191
+ checks.append(_check("WARN", "TO collector", "TO_COWORK_COLLECTOR_URL/TO_PROBE_URL not set; start cowork/collector/to_collector.py and set probe.env before packaging"))
192
+ else:
193
+ try:
194
+ if any(ord(char) < 32 or ord(char) == 127 for char in collector):
195
+ raise ValueError("control character")
196
+ parsed = urllib.parse.urlsplit(collector)
197
+ if (
198
+ parsed.scheme not in {"http", "https"}
199
+ or not parsed.hostname
200
+ or parsed.username is not None
201
+ or parsed.password is not None
202
+ or parsed.query
203
+ or parsed.fragment
204
+ ):
205
+ raise ValueError("expected an HTTP(S) base URL without credentials, query, or fragment")
206
+ _ = parsed.port # Validate malformed ports before the request.
207
+ except ValueError:
208
+ checks.append(_check("WARN", "TO collector", "invalid collector URL; use an HTTP(S) base URL without credentials, query, or fragment"))
209
+ return checks
210
+
211
+ class _NoRedirect(urllib.request.HTTPRedirectHandler):
212
+ def redirect_request(self, request, fp, code, msg, headers, newurl):
213
+ return None
214
+
215
+ try:
216
+ opener = urllib.request.build_opener(_NoRedirect())
217
+ with opener.open(f"{collector.rstrip('/')}/healthz", timeout=2) as resp:
218
+ ok = resp.status == 200
219
+ checks.append(_check("OK" if ok else "WARN", "TO collector", f"{collector} healthz {'OK' if ok else 'unexpected status'}"))
220
+ except Exception as exc: # noqa: BLE001
221
+ checks.append(_check("WARN", "TO collector", f"{collector} unreachable: {exc}"))
222
+ return checks
223
+
224
+
225
+ def _org_console_checks() -> list[dict[str, str]]:
226
+ return [
227
+ _check("NEEDS-LIVE", "Org console: plugin pushed", "confirm token-optimizer (and to-hook-probe first) is registered as available/default/required in the Anthropic admin console"),
228
+ _check("NEEDS-LIVE", "Org console: allowlist entry", "confirm the TO collector domain is on Cowork's domain allowlist"),
229
+ _check("NEEDS-LIVE", "Cloud session evidence", "cloud sessions leave no local disk; verify via collector probe.jsonl POSTs from a cloud run"),
230
+ ]
231
+
232
+
233
+ def run_checks() -> list[dict[str, str]]:
234
+ root = _repo_root()
235
+ checks = [_check("OK", "Repo root", str(root))]
236
+ checks.extend(_desktop_build_checks())
237
+ checks.extend(_allowlist_checks())
238
+ checks.extend(_session_tree_checks())
239
+ checks.extend(_payload_checks(root))
240
+ checks.extend(_probe_checks())
241
+ checks.extend(_telemetry_checks())
242
+ checks.extend(_org_console_checks())
243
+ return checks
244
+
245
+
246
+ def _print_text(checks: list[dict[str, str]]) -> None:
247
+ print("\nToken Optimizer Cowork Doctor")
248
+ print("=" * 29)
249
+ for check in checks:
250
+ print(f"[{check['status']}] {check['name']}: {check['detail']}")
251
+ counts = {s: sum(1 for c in checks if c["status"] == s) for s in ("OK", "WARN", "FAIL", "NEEDS-LIVE")}
252
+ print(f"\nSummary: {counts['OK']} OK, {counts['WARN']} WARN, {counts['FAIL']} FAIL, {counts['NEEDS-LIVE']} need a live org-console/Cowork session")
253
+ print("\nNEEDS-LIVE items are the hand-off checklist: they can only be")
254
+ print("verified with org-admin console access plus a live Cowork run.")
255
+
256
+
257
+ def main(argv: list[str] | None = None) -> int:
258
+ parser = argparse.ArgumentParser(description="Check Token Optimizer Cowork adapter readiness.")
259
+ parser.add_argument("--json", action="store_true", help="Emit machine-readable output")
260
+ args = parser.parse_args(argv)
261
+ checks = run_checks()
262
+ if args.json:
263
+ print(json.dumps({"checks": checks}, indent=2))
264
+ else:
265
+ _print_text(checks)
266
+ return 1 if any(c["status"] == "FAIL" for c in checks) else 0
267
+
268
+
269
+ if __name__ == "__main__":
270
+ raise SystemExit(main())
@@ -0,0 +1,380 @@
1
+ #!/usr/bin/env python3
2
+ """Package Token Optimizer for Claude Cowork (org admin plugin console).
3
+
4
+ Cowork does NOT read ~/.claude — plugins reach Cowork sessions (cloud AND
5
+ local VM) only via the Anthropic org admin plugin console, which
6
+ account-syncs a pushed plugin into every org user's sessions. So unlike
7
+ codex_install.py this "installer" never edits local config: it builds a
8
+ clean plugin payload (dir + zip) under dist/cowork/ for the admin to push,
9
+ plus the to-hook-probe diagnostic plugin, and prints the console steps.
10
+
11
+ TO is already a plugin in the shared Claude Code/Cowork format, so the
12
+ payload is the existing repo runtime set verbatim with ONE change:
13
+ hooks/hooks.json is trimmed to the event set that PROVABLY fires in Cowork
14
+ (UserPromptSubmit, PreToolUse, PostToolUse, Stop) and keepwarm is dropped
15
+ (its premise — keep a local CLI warm — does not transfer to Cowork).
16
+
17
+ No SessionStart remap lives here anymore. The master hooks/hooks.json is
18
+ Cowork-native in place: the run-once SessionStart features (ensure-health,
19
+ quality-cache --force, compact-restore --new-session-only) are ALSO wired
20
+ onto UserPromptSubmit behind a per-session run-once guard
21
+ (measure.py --once-per-session). On native Claude Code, SessionStart fires
22
+ them first and sets the guard marker, so the UserPromptSubmit copies no-op
23
+ (one stat) — zero behaviour change. In Cowork (SessionStart is dead) the
24
+ UserPromptSubmit copies do the work on the first prompt. So this packager is
25
+ now a PURE TRIM to the firing events: the trimmed UserPromptSubmit already
26
+ carries full parity, no injection required. SubagentStop fires in Cowork but
27
+ the master hooks.json wires nothing to it, so nothing rides it.
28
+
29
+ Degraded in Cowork (documented, unavoidable): compaction-restore on the
30
+ NATIVE compaction trigger. The master SessionStart "compact" matcher
31
+ (compact-restore --compact + read_cache --clear-compacted) and PreCompact /
32
+ PostCompact all rely on events that do not fire in Cowork, so they are
33
+ trimmed away. The Stop-hook compact-CAPTURE still saves state, and the
34
+ fresh-session compact-restore --new-session-only reads it back on the next
35
+ session's first prompt; only the in-place restore at the moment Cowork
36
+ auto-compacts is lost.
37
+ """
38
+
39
+ from __future__ import annotations
40
+
41
+ import argparse
42
+ import json
43
+ import os
44
+ import shutil
45
+ import sys
46
+ from pathlib import Path
47
+ from typing import Any
48
+
49
+ # The hook events that PROVABLY fire in cloud Cowork (Claude Code 2.1.231
50
+ # engine in a VM), verified live. Everything else in hooks/hooks.json
51
+ # (SessionStart, PreCompact, PostCompact, SessionEnd, StopFailure,
52
+ # CwdChanged) does NOT fire in Cowork and is dropped from the payload; hooks
53
+ # are additive and fail-open, so a dropped event degrades nothing. SessionStart
54
+ # is dead here — its run-once features are carried on UserPromptSubmit by the
55
+ # master hooks.json (see module docstring), so no remap is needed at pack time.
56
+ # SubagentStop fires in Cowork but the master hooks.json wires nothing to it.
57
+ COWORK_EVENTS = ("UserPromptSubmit", "PreToolUse", "PostToolUse", "Stop")
58
+
59
+ # Commands containing these markers are excluded even within kept events.
60
+ DROP_COMMAND_MARKERS = ("keepwarm-arm",)
61
+
62
+ # Runtime set that must ride into the payload. Everything else in the repo
63
+ # (docs, tests, other host adapters, qa dirs) stays out of the zip.
64
+ PAYLOAD_INCLUDE = (
65
+ ".claude-plugin",
66
+ "hooks",
67
+ "skills",
68
+ "commands",
69
+ "LICENSE",
70
+ "LICENSE-SMALL-BUSINESS.md",
71
+ "PRIVACY.md",
72
+ "README.md",
73
+ )
74
+
75
+ # The committed self-contained Cowork plugin (cowork/token-optimizer/) carries a
76
+ # Cowork-specific manifest: a distinct plugin name so Cowork's marketplace lists
77
+ # it separately from the desktop token-optimizer entry (whose source is the whole
78
+ # repo and does NOT render in Cowork), plus a description that names Cowork.
79
+ COMMITTED_PLUGIN_NAME = "token-optimizer-cowork"
80
+ COMMITTED_PLUGIN_DESCRIPTION = (
81
+ "Token Optimizer for Claude Cowork: self-contained plugin with full skills "
82
+ "and Cowork-native hooks (UserPromptSubmit, PreToolUse, PostToolUse, Stop). "
83
+ "Install THIS in Cowork; the standard token-optimizer entry is for desktop "
84
+ "Claude Code."
85
+ )
86
+
87
+ _IGNORE = shutil.ignore_patterns("__pycache__", "*.pyc", ".DS_Store", "benchmark.py")
88
+
89
+
90
+ def _repo_root() -> Path:
91
+ """Walk up to the plugin root -- the dir that holds .claude-plugin/plugin.json.
92
+
93
+ From the canonical tree (skills/token-optimizer/scripts/) that is parents[3];
94
+ but from the Codex-marketplace MIRROR
95
+ (plugins/token-optimizer/skills/token-optimizer/scripts/) parents[3] is
96
+ plugins/token-optimizer, which has no .claude-plugin/ -- so the old hardcoded
97
+ index made _plugin_version() traceback with FileNotFoundError even on
98
+ --dry-run for any Codex-marketplace user. Walking up for the
99
+ marker resolves to the real repo root in both trees, and falls back to the
100
+ legacy parents[3] (bounded) if no marker is found so a stripped/relocated
101
+ checkout degrades instead of crashing.
102
+ """
103
+ here = Path(__file__).resolve()
104
+ for parent in here.parents:
105
+ if (parent / ".claude-plugin" / "plugin.json").exists():
106
+ return parent
107
+ parents = here.parents
108
+ return parents[3] if len(parents) > 3 else here.parent
109
+
110
+
111
+ def _plugin_version(root: Path) -> str:
112
+ # Guarded read: a missing/unreadable manifest must degrade to a
113
+ # placeholder version, never a raw traceback -- _repo_root() may fall back to
114
+ # a tree without .claude-plugin/plugin.json.
115
+ try:
116
+ manifest = json.loads((root / ".claude-plugin" / "plugin.json").read_text(encoding="utf-8"))
117
+ except (OSError, json.JSONDecodeError):
118
+ return "0.0.0"
119
+ return str(manifest.get("version", "0.0.0"))
120
+
121
+
122
+ def _claude_home() -> Path:
123
+ return Path(os.environ.get("CLAUDE_CONFIG_DIR", "") or (Path.home() / ".claude")).expanduser()
124
+
125
+
126
+ def _guard_out_dir(out: Path) -> None:
127
+ """Refuse to build inside ~/.claude: Cowork account-syncs plugins from
128
+ the org console, not from local files, and writing there both misleads
129
+ (looks installed, is not) and risks polluting the account-synced tree."""
130
+ resolved = out.resolve(strict=False)
131
+ claude_home = _claude_home().resolve(strict=False)
132
+ if resolved == claude_home or resolved.is_relative_to(claude_home):
133
+ raise ValueError(
134
+ f"refusing to write the Cowork payload under {claude_home} — "
135
+ "Cowork does not read local plugin files; build to a neutral dir "
136
+ "and push via the org admin console"
137
+ )
138
+
139
+
140
+ def build_cowork_hooks(template: dict[str, Any]) -> dict[str, Any]:
141
+ """Trim the Claude Code hooks.json to the Cowork-firing event set.
142
+
143
+ Pure trim, no injection: the master UserPromptSubmit group already carries
144
+ the run-once SessionStart features (ensure-health / quality-cache --force /
145
+ compact-restore --new-session-only, each guarded with --once-per-session),
146
+ so trimming to COWORK_EVENTS yields full Cowork parity automatically.
147
+ keepwarm is still dropped via DROP_COMMAND_MARKERS.
148
+ """
149
+ hooks = template.get("hooks", {})
150
+ trimmed: dict[str, Any] = {}
151
+ for event in COWORK_EVENTS:
152
+ groups = []
153
+ for group in hooks.get(event, []):
154
+ kept = [
155
+ h for h in group.get("hooks", [])
156
+ if not any(marker in h.get("command", "") for marker in DROP_COMMAND_MARKERS)
157
+ ]
158
+ if kept:
159
+ groups.append({**group, "hooks": kept})
160
+ if groups:
161
+ trimmed[event] = groups
162
+ return {"hooks": trimmed}
163
+
164
+
165
+ def _copy_runtime_payload(root: Path, payload: Path) -> None:
166
+ """Copy the PAYLOAD_INCLUDE runtime set into ``payload`` and overwrite
167
+ hooks/hooks.json with the Cowork-trimmed variant. Shared by the versioned
168
+ dist payload (build_plugin_payload) and the committed stable-path payload
169
+ (build_committed_plugin) so both stay byte-for-byte in step."""
170
+ for rel in PAYLOAD_INCLUDE:
171
+ src = root / rel
172
+ if not src.exists():
173
+ continue
174
+ if src.is_dir():
175
+ shutil.copytree(src, payload / rel, ignore=_IGNORE)
176
+ else:
177
+ shutil.copy2(src, payload / rel)
178
+ # A plugin payload is a PLUGIN, not a marketplace: strip the repo-root
179
+ # marketplace.json that rides along inside .claude-plugin/. The loader reads
180
+ # only plugin.json, and the proven-working probe carries plugin.json alone --
181
+ # matching that shape avoids confusing Cowork's marketplace scanner.
182
+ (payload / ".claude-plugin" / "marketplace.json").unlink(missing_ok=True)
183
+ template = json.loads((root / "hooks" / "hooks.json").read_text(encoding="utf-8"))
184
+ cowork_hooks = build_cowork_hooks(template)
185
+ (payload / "hooks" / "hooks.json").write_text(
186
+ json.dumps(cowork_hooks, indent=2) + "\n", encoding="utf-8"
187
+ )
188
+
189
+
190
+ def build_plugin_payload(root: Path, dist: Path) -> Path:
191
+ version = _plugin_version(root)
192
+ payload = dist / f"token-optimizer-cowork-{version}"
193
+ if payload.exists():
194
+ shutil.rmtree(payload)
195
+ payload.mkdir(parents=True)
196
+ _copy_runtime_payload(root, payload)
197
+ _add_hooks_pointer(payload / ".claude-plugin" / "plugin.json")
198
+ return payload
199
+
200
+
201
+ def committed_plugin_dir(root: Path) -> Path:
202
+ """The STABLE committed path for the self-contained Cowork plugin.
203
+
204
+ No version in the dirname so the marketplace source (./cowork/token-optimizer)
205
+ is stable across releases and an anti-drift test can rebuild + diff in place."""
206
+ return root / "cowork" / "token-optimizer"
207
+
208
+
209
+ def build_committed_plugin(root: Path) -> Path:
210
+ """Build the self-contained Cowork plugin into the committed stable path
211
+ ``cowork/token-optimizer/`` (no version in the dirname).
212
+
213
+ Same shape as the dist payload (Cowork-trimmed hooks + PAYLOAD_INCLUDE +
214
+ hooks pointer), but with a Cowork-specific manifest: name
215
+ ``token-optimizer-cowork``, version pinned to the root plugin.json, a
216
+ description that names Cowork, and the ``./hooks/hooks.json`` pointer.
217
+
218
+ Idempotent: wipes and rewrites the target so re-runs overwrite cleanly and
219
+ leave ``git status`` clean when nothing upstream changed."""
220
+ payload = committed_plugin_dir(root)
221
+ if payload.exists():
222
+ shutil.rmtree(payload)
223
+ payload.mkdir(parents=True)
224
+ _copy_runtime_payload(root, payload)
225
+ _finalize_committed_manifest(payload / ".claude-plugin" / "plugin.json", _plugin_version(root))
226
+ return payload
227
+
228
+
229
+ def _finalize_committed_manifest(manifest_path: Path, version: str) -> None:
230
+ """Rewrite the copied root manifest into the Cowork plugin manifest: distinct
231
+ name, pinned version, Cowork-naming description, and the hooks pointer (added
232
+ via the shared _add_hooks_pointer helper)."""
233
+ manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
234
+ manifest["name"] = COMMITTED_PLUGIN_NAME
235
+ manifest["version"] = version
236
+ manifest["description"] = COMMITTED_PLUGIN_DESCRIPTION
237
+ manifest_path.write_text(json.dumps(manifest, indent=2) + "\n", encoding="utf-8")
238
+ _add_hooks_pointer(manifest_path)
239
+
240
+
241
+ def _add_hooks_pointer(manifest_path: Path) -> None:
242
+ """Point the manifest at hooks/hooks.json explicitly. In some Cowork builds,
243
+ plugin hooks only load when the manifest declares
244
+ them; Claude Code defaults to the same path, so the field is harmless
245
+ everywhere else.
246
+
247
+ Also drops ``types``: it describes the desktop status bar's state, and the
248
+ Cowork plugin carries neither the bar nor the file it points at."""
249
+ manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
250
+ manifest.pop("types", None)
251
+ manifest["hooks"] = "./hooks/hooks.json"
252
+ manifest_path.write_text(json.dumps(manifest, indent=2) + "\n", encoding="utf-8")
253
+
254
+
255
+ def build_probe_payload(root: Path, dist: Path) -> Path | None:
256
+ src = root / "cowork" / "to-hook-probe"
257
+ if not src.exists():
258
+ return None
259
+ version = json.loads(
260
+ (src / ".claude-plugin" / "plugin.json").read_text(encoding="utf-8")
261
+ ).get("version", "0.0.0")
262
+ payload = dist / f"to-hook-probe-{version}"
263
+ if payload.exists():
264
+ shutil.rmtree(payload)
265
+ shutil.copytree(src, payload, ignore=_IGNORE)
266
+ return payload
267
+
268
+
269
+ def _zip(payload: Path) -> Path:
270
+ archive = shutil.make_archive(str(payload), "zip", root_dir=payload)
271
+ return Path(archive)
272
+
273
+
274
+ ORG_CONSOLE_STEPS = """\
275
+ Next steps (org admin, needs a live console — see cowork/README.md):
276
+ 1. Anthropic admin console -> Settings -> Plugins.
277
+ 2. Register/upload the payload above (zip, or point the console at this
278
+ git repo if it takes a marketplace source) and set availability:
279
+ 'available to install' / 'installed by default' / 'required'.
280
+ Push to-hook-probe FIRST to prove hooks fire on your build.
281
+ 3. Add the TO telemetry/collector domain to Cowork's domain allowlist
282
+ (org security settings) or hook phone-home + OTel POSTs are blocked.
283
+ 4. Run one Cowork session, then: python3 skills/token-optimizer/scripts/cowork_doctor.py
284
+ """
285
+
286
+
287
+ def main(argv: list[str] | None = None) -> int:
288
+ parser = argparse.ArgumentParser(
289
+ description="Build the Token Optimizer Cowork plugin payload (org-console push; never touches ~/.claude)."
290
+ )
291
+ parser.add_argument("--out", default=None, help="Output dir (default: <repo>/dist/cowork)")
292
+ parser.add_argument("--no-zip", action="store_true", help="Build payload dirs only, skip zips")
293
+ parser.add_argument("--plugin-only", action="store_true", help="Skip the to-hook-probe payload")
294
+ parser.add_argument("--probe-only", action="store_true", help="Build only the to-hook-probe payload")
295
+ parser.add_argument(
296
+ "--emit-committed",
297
+ action="store_true",
298
+ help=(
299
+ "Build the self-contained Cowork plugin into the committed stable path "
300
+ "cowork/token-optimizer/ (no version in dirname, name token-optimizer-cowork). "
301
+ "Idempotent; used by the marketplace source and the anti-drift test."
302
+ ),
303
+ )
304
+ parser.add_argument("--dry-run", action="store_true", help="Print intended outputs without writing")
305
+ parser.add_argument("--json", action="store_true", help="Emit machine-readable output")
306
+ args = parser.parse_args(argv)
307
+
308
+ root = _repo_root()
309
+
310
+ if args.emit_committed:
311
+ target = committed_plugin_dir(root)
312
+ committed_result: dict[str, Any] = {
313
+ "mode": "emit-committed",
314
+ "version": _plugin_version(root),
315
+ "events": list(COWORK_EVENTS),
316
+ "dry_run": args.dry_run,
317
+ "artifacts": [str(target)],
318
+ }
319
+ if not args.dry_run:
320
+ build_committed_plugin(root)
321
+ if args.json:
322
+ print(json.dumps(committed_result, indent=2))
323
+ else:
324
+ verb = "Would emit" if args.dry_run else "Emitted"
325
+ print(
326
+ f"[Token Optimizer] {verb} committed Cowork plugin "
327
+ f"'{COMMITTED_PLUGIN_NAME}' v{committed_result['version']} "
328
+ f"(hooks: {', '.join(COWORK_EVENTS)}):"
329
+ )
330
+ print(f" {target}")
331
+ return 0
332
+
333
+ dist = Path(args.out).expanduser() if args.out else root / "dist" / "cowork"
334
+ try:
335
+ _guard_out_dir(dist)
336
+ except ValueError as exc:
337
+ print(f"[Token Optimizer] {exc}", file=sys.stderr)
338
+ return 1
339
+
340
+ result: dict[str, Any] = {
341
+ "dist": str(dist),
342
+ "version": _plugin_version(root),
343
+ "events": list(COWORK_EVENTS),
344
+ "dry_run": args.dry_run,
345
+ "artifacts": [],
346
+ }
347
+
348
+ if args.dry_run:
349
+ if not args.probe_only:
350
+ result["artifacts"].append(str(dist / f"token-optimizer-cowork-{result['version']}"))
351
+ if not args.plugin_only:
352
+ result["artifacts"].append(str(dist / "to-hook-probe-<version>"))
353
+ else:
354
+ dist.mkdir(parents=True, exist_ok=True)
355
+ payloads: list[Path] = []
356
+ if not args.probe_only:
357
+ payloads.append(build_plugin_payload(root, dist))
358
+ if not args.plugin_only:
359
+ probe = build_probe_payload(root, dist)
360
+ if probe is not None:
361
+ payloads.append(probe)
362
+ for payload in payloads:
363
+ result["artifacts"].append(str(payload))
364
+ if not args.no_zip:
365
+ result["artifacts"].append(str(_zip(payload)))
366
+
367
+ if args.json:
368
+ print(json.dumps(result, indent=2))
369
+ else:
370
+ verb = "Would build" if args.dry_run else "Built"
371
+ print(f"[Token Optimizer] {verb} Cowork payload (hooks: {', '.join(COWORK_EVENTS)}):")
372
+ for artifact in result["artifacts"]:
373
+ print(f" {artifact}")
374
+ print()
375
+ print(ORG_CONSOLE_STEPS)
376
+ return 0
377
+
378
+
379
+ if __name__ == "__main__":
380
+ raise SystemExit(main())