@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,668 @@
1
+ #!/usr/bin/env python3
2
+ """Install Token Optimizer into Hermes as a plugin.
3
+
4
+ Copies the ``hermes/`` payload directory from the Token Optimizer repo into
5
+ ``~/.hermes/plugins/token-optimizer/`` (or ``$HERMES_HOME/plugins/token-optimizer/``)
6
+ AND the runtime modules the plugin imports at load time (the hermes_*.py shims
7
+ that live next to this installer in scripts/).
8
+
9
+ v5.X.Y: the payload alone (plugin.yaml + __init__.py + README) is not a
10
+ working plugin — __init__.py imports hermes_hook_bridge / hermes_state /
11
+ hermes_session from its own directory. Earlier installs copied only the payload,
12
+ leaving those imports broken (dead /token-optimizer command, dashboard launcher,
13
+ and rollups). We now also copy the three runtime modules and write a one-line
14
+ ``measure-path`` locator pointing at the canonical measure.py in the checkout
15
+ (rather than copying measure.py + its dependency tree, which would silently go
16
+ stale because nothing refreshes plugin-dir copies on update).
17
+
18
+ Hermes (v0.15.x) does NOT auto-discover plugins by directory presence: the
19
+ plugin must be allow-listed in the Hermes config under ``plugins.enabled``.
20
+ ``--enable`` patches that config idempotently; without it we print the exact
21
+ snippet for the user to add.
22
+
23
+ The operation is idempotent: re-running replaces files in place without
24
+ corrupting any existing Hermes state or other plugins.
25
+
26
+ Usage (from measure.py dispatch or directly):
27
+ python3 hermes_install.py [--dry-run] [--uninstall] [--enable] [--json]
28
+ """
29
+
30
+ from __future__ import annotations
31
+
32
+ import argparse
33
+ import datetime as _dt
34
+ import json
35
+ import os
36
+ import shutil
37
+ import sys
38
+ from pathlib import Path
39
+
40
+ from runtime_env import hermes_home
41
+
42
+ # ---------------------------------------------------------------------------
43
+ # Paths
44
+ # ---------------------------------------------------------------------------
45
+
46
+ _PLUGIN_NAME = "token-optimizer"
47
+ _HERMES_PLUGIN_DIR_NAME = "plugins"
48
+
49
+ # Runtime modules the Hermes plugin imports from its own directory at load time
50
+ # (see hermes/__init__.py "sys.path assumption"). Sourced from the scripts/ dir
51
+ # that contains THIS installer, so install never depends on cwd or the checkout
52
+ # layout beyond "the installer lives next to the modules it ships".
53
+ _RUNTIME_MODULES = (
54
+ "hermes_hook_bridge.py",
55
+ "hermes_state.py",
56
+ "hermes_session.py",
57
+ "runtime_env.py",
58
+ # hermes_hook_bridge imports `from spawn_utils import spawn_detached` at load
59
+ # time. Omitting it made the plugin dir import-fail at runtime even
60
+ # though hermes-doctor's bridge smoke test caught it as ModuleNotFoundError.
61
+ "spawn_utils.py",
62
+ )
63
+
64
+ # Plain-text locator file written into the plugin dir: one line, the absolute
65
+ # path to the canonical measure.py. hermes_hook_bridge._locate_measure_py reads
66
+ # it. We do NOT copy measure.py itself (version-drift risk — nothing refreshes a
67
+ # plugin-dir copy on update; the checkout's measure.py stays the single source).
68
+ _MEASURE_LOCATOR_NAME = "measure-path"
69
+
70
+ # Hermes config: the plugin must be allow-listed under plugins.enabled. No other
71
+ # part of the codebase references a canonical config path, so we default to
72
+ # config.yaml and fall back to config.yml when only that exists.
73
+ _CONFIG_PRIMARY = "config.yaml"
74
+ _CONFIG_FALLBACK = "config.yml"
75
+
76
+ _ENABLE_SNIPPET = "plugins:\n enabled:\n - token-optimizer\n"
77
+
78
+
79
+ def _scripts_dir() -> Path:
80
+ """Return the scripts/ dir that contains this installer and the runtime modules."""
81
+ return Path(__file__).resolve().parent
82
+
83
+
84
+ def _repo_root() -> Path:
85
+ """Return the token-optimizer repo root (3 parents up from this script)."""
86
+ return Path(__file__).resolve().parents[3]
87
+
88
+
89
+ def _payload_dir() -> Path:
90
+ """Return the ``hermes/`` payload directory bundled in the repo."""
91
+ return _repo_root() / "hermes"
92
+
93
+
94
+ def _plugin_install_dir(hermes_root: Path) -> Path:
95
+ """Return the path where Hermes should find our plugin."""
96
+ return hermes_root / _HERMES_PLUGIN_DIR_NAME / _PLUGIN_NAME
97
+
98
+
99
+ # ---------------------------------------------------------------------------
100
+ # Safety helpers
101
+ # ---------------------------------------------------------------------------
102
+
103
+ def _assert_no_symlink_escape(path: Path, expected_parent: Path) -> None:
104
+ """Raise ValueError if *path* would escape *expected_parent* after resolution."""
105
+ try:
106
+ resolved = path.resolve(strict=False)
107
+ expected_resolved = expected_parent.resolve(strict=False)
108
+ except (OSError, ValueError) as exc:
109
+ raise ValueError(f"Path resolution failed for {path}: {exc}") from exc
110
+ if not resolved.is_relative_to(expected_resolved):
111
+ raise ValueError(f"{path} escapes {expected_parent}")
112
+
113
+
114
+ # ---------------------------------------------------------------------------
115
+ # Hermes config activation (--enable)
116
+ # ---------------------------------------------------------------------------
117
+
118
+ def _config_path(hermes_root: Path) -> Path:
119
+ """Return the Hermes config path to patch.
120
+
121
+ Prefer config.yaml. If it is absent but config.yml exists, target that
122
+ instead (so we don't create a second competing file).
123
+ """
124
+ primary = hermes_root / _CONFIG_PRIMARY
125
+ fallback = hermes_root / _CONFIG_FALLBACK
126
+ if not primary.exists() and fallback.exists():
127
+ return fallback
128
+ return primary
129
+
130
+
131
+ def _timestamp() -> str:
132
+ # v5.11.1: include microseconds so two backups within the same second
133
+ # (e.g. a retried install) don't collide on the same filename.
134
+ return _dt.datetime.now().strftime("%Y%m%d-%H%M%S-%f")
135
+
136
+
137
+ def _enabled_in_text(text: str) -> bool:
138
+ """Conservative text scan: is token-optimizer already under plugins.enabled?
139
+
140
+ Handles both the block-list form::
141
+
142
+ plugins:
143
+ enabled:
144
+ - token-optimizer
145
+
146
+ and the inline form ``enabled: [token-optimizer, ...]``. Does not attempt a
147
+ full YAML parse (PyYAML may be absent and would lose comments on dump).
148
+ """
149
+ # v5.11.1: bail on pathologically large config text rather than scan
150
+ # line-by-line (a malformed/huge file is the user's to fix, not ours to chew).
151
+ if len(text) > 1_000_000:
152
+ return False
153
+ lines = text.splitlines()
154
+ in_plugins = False
155
+ in_enabled = False
156
+ plugins_indent = -1
157
+ enabled_indent = -1
158
+ for raw in lines:
159
+ stripped = raw.strip()
160
+ if not stripped or stripped.startswith("#"):
161
+ continue
162
+ indent = len(raw) - len(raw.lstrip())
163
+ # Leaving the plugins block once we dedent back to/under its key indent.
164
+ if in_plugins and indent <= plugins_indent and not raw.lstrip().startswith("plugins:"):
165
+ in_plugins = False
166
+ in_enabled = False
167
+ # v5.11.1: only a TOP-LEVEL plugins: key (indent == 0) is the
168
+ # Hermes plugin allow-list. A nested "plugins:" (e.g. outer.plugins) is
169
+ # an unrelated mapping and must not be matched.
170
+ if stripped.startswith("plugins:") and indent == 0:
171
+ in_plugins = True
172
+ plugins_indent = indent
173
+ # Inline form on the plugins line is not expected; keep scanning.
174
+ continue
175
+ if in_plugins and not in_enabled and stripped.startswith("enabled:"):
176
+ in_enabled = True
177
+ enabled_indent = indent
178
+ # Inline list form: enabled: [a, token-optimizer]
179
+ rest = stripped[len("enabled:"):].strip()
180
+ if rest.startswith("[") and _PLUGIN_NAME in [
181
+ item.strip().strip("'\"") for item in rest.strip("[]").split(",")
182
+ ]:
183
+ return True
184
+ continue
185
+ if in_enabled:
186
+ # Block-list items are more-indented "- name" entries.
187
+ if indent <= enabled_indent and not stripped.startswith("-"):
188
+ in_enabled = False
189
+ elif stripped.startswith("-") and stripped[1:].strip().strip("'\"") == _PLUGIN_NAME:
190
+ return True
191
+ return False
192
+
193
+
194
+ def _patch_config_text(text: str) -> tuple[str | None, str]:
195
+ """Insert token-optimizer into an existing plugins.enabled list via text surgery.
196
+
197
+ Returns (new_text, status). status is one of:
198
+ - "already-enabled": no change needed.
199
+ - "enabled": new_text contains the patched config.
200
+ - "manual-required": structure is ambiguous; caller must not write.
201
+
202
+ Preserves comments and surrounding formatting (no yaml load/dump rewrite).
203
+ """
204
+ # v5.11.1: refuse pathologically large configs (caller treats this as
205
+ # manual-required and won't write).
206
+ if len(text) > 1_000_000:
207
+ return None, "manual-required"
208
+ if _enabled_in_text(text):
209
+ return None, "already-enabled"
210
+
211
+ # v5.11.1: detect the file's line ending once and reuse it for every
212
+ # line we synthesize, so a CRLF config stays uniformly CRLF after patching.
213
+ eol = "\r\n" if "\r\n" in text else "\n"
214
+
215
+ lines = text.splitlines(keepends=True)
216
+ in_plugins = False
217
+ saw_plugins = False
218
+ plugins_indent = -1
219
+ enabled_lead = "" # literal leading whitespace of the enabled: line
220
+ for i, raw in enumerate(lines):
221
+ body = raw.rstrip("\r\n")
222
+ stripped = body.strip()
223
+ if not stripped or stripped.startswith("#"):
224
+ continue
225
+ lead = body[: len(body) - len(body.lstrip())]
226
+ indent = len(lead)
227
+ if in_plugins and indent <= plugins_indent and not body.lstrip().startswith("plugins:"):
228
+ in_plugins = False
229
+ # v5.11.1: only a TOP-LEVEL plugins: key (indent == 0) is the
230
+ # Hermes plugin allow-list; nested plugins: mappings are unrelated.
231
+ if stripped.startswith("plugins:") and indent == 0:
232
+ in_plugins = True
233
+ saw_plugins = True
234
+ plugins_indent = indent
235
+ continue
236
+ if in_plugins and stripped.startswith("enabled:"):
237
+ enabled_lead = lead
238
+ rest = stripped[len("enabled:"):].strip()
239
+ # v5.11.1: strip a trailing comment so `enabled: # note` is
240
+ # treated as an empty block-list, not a scalar.
241
+ rest = rest.split("#", 1)[0].strip()
242
+ if rest.startswith("[") and rest.endswith("]"):
243
+ # Inline list form — rewrite this one line, preserving prefix.
244
+ inner = rest[1:-1].strip()
245
+ items = [x.strip() for x in inner.split(",") if x.strip()] if inner else []
246
+ items.append(_PLUGIN_NAME)
247
+ prefix = lead
248
+ newline = eol if (raw.endswith("\n") or raw.endswith("\r")) else ""
249
+ lines[i] = f"{prefix}enabled: [{', '.join(items)}]{newline}"
250
+ return "".join(lines), "enabled"
251
+ if rest and not rest.startswith("["):
252
+ # enabled: <scalar> — not a list we can safely extend.
253
+ return None, "manual-required"
254
+ # Block-list form: insert a "- token-optimizer" item.
255
+ # v5.11.1: derive the inserted line's leading whitespace from
256
+ # an EXISTING item line's literal prefix (the actual chars before
257
+ # "-"), preserving tabs. If there is no existing item line and the
258
+ # surrounding indentation uses tabs, bail manual-required rather than
259
+ # guess a space count that yaml would reject.
260
+ item_lead = None
261
+ insert_at = i + 1
262
+ for j in range(i + 1, len(lines)):
263
+ jbody = lines[j].rstrip("\r\n")
264
+ jstripped = jbody.strip()
265
+ if not jstripped or jstripped.startswith("#"):
266
+ insert_at = j + 1
267
+ continue
268
+ jlead = jbody[: len(jbody) - len(jbody.lstrip())]
269
+ jindent = len(jlead)
270
+ if jstripped.startswith("-") and jindent > indent:
271
+ item_lead = jlead
272
+ insert_at = j + 1
273
+ continue
274
+ break
275
+ if item_lead is None:
276
+ # No existing item to copy indentation from. If the enabled:/
277
+ # plugins: indentation contains tabs, we cannot safely pick an
278
+ # indent — bail conservatively.
279
+ if "\t" in enabled_lead or "\t" in lead:
280
+ return None, "manual-required"
281
+ item_lead = " " * (indent + 2)
282
+ new_line = f"{item_lead}- {_PLUGIN_NAME}{eol}"
283
+ lines.insert(insert_at, new_line)
284
+ return "".join(lines), "enabled"
285
+
286
+ if not saw_plugins:
287
+ # No plugins: block anywhere — appending a fresh top-level block at the
288
+ # end of the file is unambiguous (cannot interact with other keys).
289
+ suffix = "" if (not text or text.endswith("\n") or text.endswith("\r")) else eol
290
+ snippet = _ENABLE_SNIPPET.replace("\n", eol) if eol != "\n" else _ENABLE_SNIPPET
291
+ return text + suffix + snippet, "enabled"
292
+
293
+ # plugins: exists but no enabled: list we can safely extend — ambiguous.
294
+ return None, "manual-required"
295
+
296
+
297
+ def enable_in_config(hermes_root: Path, *, dry_run: bool = False) -> dict:
298
+ """Idempotently allow-list token-optimizer in the Hermes config.
299
+
300
+ Returns a dict with keys: status, config_path, and optionally backup/note.
301
+ status ∈ {"enabled", "already-enabled", "manual-required"}.
302
+
303
+ A timestamped backup is written ONLY when we actually mutate the file.
304
+ """
305
+ cfg = _config_path(hermes_root)
306
+ _assert_no_symlink_escape(cfg, hermes_root)
307
+ result: dict = {"config_path": str(cfg)}
308
+
309
+ if not cfg.exists():
310
+ if dry_run:
311
+ # v5.11.1: dry-run must not claim "enabled" when nothing was
312
+ # written. Report the action we WOULD take ("would-enable").
313
+ result["status"] = "would-enable"
314
+ result["note"] = "config does not exist; would create minimal plugins.enabled"
315
+ # v5.11.1: pre-flight writability of the nearest existing
316
+ # ancestor so the dry-run preview is honest about a likely failure.
317
+ check_dir = cfg.parent if cfg.parent.exists() else None
318
+ if check_dir is not None and not os.access(check_dir, os.W_OK):
319
+ result["status"] = "manual-required"
320
+ result["note"] = (
321
+ f"config does not exist and {check_dir} is not writable; "
322
+ "create plugins.enabled manually"
323
+ )
324
+ return result
325
+ # v5.11.1: wrap the new-config write — set status only AFTER the
326
+ # write succeeds so a failure doesn't claim success.
327
+ try:
328
+ cfg.parent.mkdir(parents=True, exist_ok=True)
329
+ cfg.write_text(_ENABLE_SNIPPET, encoding="utf-8")
330
+ except OSError as exc:
331
+ raise ValueError(
332
+ f"Could not create Hermes config at {cfg}: {exc}. "
333
+ "No config was written; add plugins.enabled manually."
334
+ ) from exc
335
+ result["status"] = "enabled"
336
+ result["note"] = "config did not exist; created minimal plugins.enabled"
337
+ return result
338
+
339
+ try:
340
+ # v5.11.1: newline="" disables universal-newline translation so a
341
+ # CRLF config arrives with its \r\n intact, letting _patch_config_text
342
+ # detect and preserve the line ending.
343
+ with open(cfg, "r", encoding="utf-8", newline="") as _f:
344
+ text = _f.read()
345
+ except OSError as exc:
346
+ result["status"] = "manual-required"
347
+ result["note"] = f"could not read config ({exc}); add the snippet manually"
348
+ return result
349
+
350
+ new_text, status = _patch_config_text(text)
351
+ if status == "manual-required":
352
+ result["status"] = status
353
+ result["note"] = "plugins.enabled structure is ambiguous; file left untouched"
354
+ return result
355
+ if status == "already-enabled":
356
+ result["status"] = status
357
+ result["note"] = "token-optimizer already allow-listed; no change"
358
+ return result
359
+
360
+ # status == "enabled": back up then write.
361
+ backup = cfg.with_name(f"{cfg.name}.bak-{_timestamp()}")
362
+ result["backup"] = str(backup)
363
+ if dry_run:
364
+ # v5.11.1: nothing written under dry-run -> "would-enable".
365
+ result["status"] = "would-enable"
366
+ return result
367
+ # v5.11.1: new_text is guaranteed non-None when status == "enabled".
368
+ assert new_text is not None
369
+ # v5.11.1: wrap backup + write so a disk/permission failure surfaces
370
+ # as a clean actionable error naming the backup, not a raw traceback.
371
+ try:
372
+ shutil.copy2(cfg, backup)
373
+ # v5.11.1: newline="" so the \r\n we preserved in new_text is
374
+ # written verbatim (no platform os.linesep re-translation).
375
+ with open(cfg, "w", encoding="utf-8", newline="") as _f:
376
+ _f.write(new_text)
377
+ except OSError as exc:
378
+ raise ValueError(
379
+ f"Could not update Hermes config {cfg}: {exc}. A backup may exist at "
380
+ f"{backup}; the original config may be partially modified -- restore "
381
+ "from the backup if needed and add plugins.enabled manually."
382
+ ) from exc
383
+ result["status"] = "enabled"
384
+ return result
385
+
386
+
387
+ # ---------------------------------------------------------------------------
388
+ # Core install / uninstall
389
+ # ---------------------------------------------------------------------------
390
+
391
+ def install(
392
+ *,
393
+ dry_run: bool = False,
394
+ enable: bool = False,
395
+ ) -> tuple[Path, str, dict]:
396
+ """Copy the ``hermes/`` payload + runtime modules into Hermes's plugins dir.
397
+
398
+ Returns (install_dir, action, details).
399
+
400
+ Idempotent: existing files are overwritten; extra files in the target dir
401
+ that came from a previous install are retained (they may have been written
402
+ by Hermes or the user). We only copy *our* payload files, never delete.
403
+ """
404
+ payload = _payload_dir()
405
+ if not payload.is_dir():
406
+ raise ValueError(
407
+ f"Hermes plugin payload not found at {payload}. "
408
+ "The repo's hermes/ directory must exist before installing."
409
+ )
410
+
411
+ scripts_dir = _scripts_dir()
412
+ # Resolve the runtime modules up front so a missing one fails fast with the
413
+ # same shape of error as the missing-payload case (don't half-install).
414
+ runtime_srcs: list[Path] = []
415
+ for mod in _RUNTIME_MODULES:
416
+ src = scripts_dir / mod
417
+ if not src.is_file():
418
+ raise ValueError(
419
+ f"Hermes runtime module not found at {src}. "
420
+ "It must sit next to hermes_install.py for the plugin to import it."
421
+ )
422
+ runtime_srcs.append(src)
423
+
424
+ hermes_root = hermes_home()
425
+ install_dir = _plugin_install_dir(hermes_root)
426
+
427
+ # Verify the install_dir is inside the hermes root (not a symlink escape).
428
+ _assert_no_symlink_escape(install_dir, hermes_root)
429
+
430
+ # v5.11.1: never ship compiled bytecode — exclude __pycache__ dirs and
431
+ # any .pyc so the plugin dir contains only source.
432
+ payload_files = [
433
+ f for f in sorted(payload.rglob("*"))
434
+ if f.is_file()
435
+ and "__pycache__" not in f.parts
436
+ and f.suffix != ".pyc"
437
+ ]
438
+
439
+ # The locator points at the canonical measure.py in the checkout, written
440
+ # only if measure.py actually exists next to the installer.
441
+ measure_py = scripts_dir / "measure.py"
442
+ write_locator = measure_py.is_file()
443
+
444
+ listed_files = [str(f.relative_to(payload)) for f in payload_files]
445
+ listed_files += [mod for mod in _RUNTIME_MODULES]
446
+ if write_locator:
447
+ listed_files.append(_MEASURE_LOCATOR_NAME)
448
+
449
+ details: dict = {
450
+ "plugin_dir": str(install_dir),
451
+ "hermes_home": str(hermes_root),
452
+ "files": listed_files,
453
+ "dry_run": dry_run,
454
+ }
455
+
456
+ if dry_run:
457
+ details["activation"] = _activation_dry_run_note(hermes_root, enable)
458
+ if enable:
459
+ details["activation_result"] = enable_in_config(hermes_root, dry_run=True)
460
+ else:
461
+ # v5.11.1: keep the JSON schema stable -- activation_result is
462
+ # always present, even on a plain --dry-run with no --enable.
463
+ details["activation_result"] = {
464
+ "status": "manual-required",
465
+ "config_path": str(_config_path(hermes_root)),
466
+ }
467
+ return install_dir, "would-install", details
468
+
469
+ # v5.11.1: wrap every user-state write so a disk/permission failure
470
+ # surfaces as a clean actionable error naming the failing path, not a raw
471
+ # traceback. main() turns ValueError into a clean message + exit 1.
472
+ try:
473
+ # Create the target directory tree.
474
+ install_dir.mkdir(parents=True, exist_ok=True)
475
+ except OSError as exc:
476
+ raise ValueError(
477
+ f"Could not create Hermes plugin directory {install_dir}: {exc}."
478
+ ) from exc
479
+
480
+ # Copy each payload file, preserving relative structure.
481
+ for src in payload_files:
482
+ rel = src.relative_to(payload)
483
+ dst = install_dir / rel
484
+ try:
485
+ dst.parent.mkdir(parents=True, exist_ok=True)
486
+ shutil.copy2(src, dst)
487
+ except OSError as exc:
488
+ raise ValueError(
489
+ f"Could not copy plugin file to {dst}: {exc}."
490
+ ) from exc
491
+
492
+ # Copy the runtime modules flat into the plugin dir.
493
+ for src in runtime_srcs:
494
+ dst = install_dir / src.name
495
+ try:
496
+ shutil.copy2(src, dst)
497
+ except OSError as exc:
498
+ raise ValueError(
499
+ f"Could not copy runtime module to {dst}: {exc}."
500
+ ) from exc
501
+
502
+ # Write the measure.py locator (one line, absolute path).
503
+ if write_locator:
504
+ locator = install_dir / _MEASURE_LOCATOR_NAME
505
+ try:
506
+ locator.write_text(f"{measure_py}\n", encoding="utf-8")
507
+ except OSError as exc:
508
+ raise ValueError(
509
+ f"Could not write measure.py locator to {locator}: {exc}."
510
+ ) from exc
511
+
512
+ # Activation: Hermes requires the plugin to be allow-listed. Either patch
513
+ # the config (--enable) or print the snippet the user must add.
514
+ if enable:
515
+ activation = enable_in_config(hermes_root, dry_run=False)
516
+ details["activation_result"] = activation
517
+ details["activation"] = _activation_message(activation)
518
+ else:
519
+ cfg_hint = _config_path(hermes_root)
520
+ details["activation_result"] = {
521
+ "status": "manual-required",
522
+ "config_path": str(cfg_hint),
523
+ }
524
+ details["activation"] = (
525
+ "Hermes requires this plugin to be allow-listed in its config. Add:\n"
526
+ f"{_ENABLE_SNIPPET}"
527
+ f"to {cfg_hint} "
528
+ "(or re-run with --enable to patch it automatically)."
529
+ )
530
+
531
+ return install_dir, "installed", details
532
+
533
+
534
+ def _activation_dry_run_note(hermes_root: Path, enable: bool) -> str:
535
+ cfg = _config_path(hermes_root)
536
+ if enable:
537
+ return f"Would allow-list token-optimizer in {cfg}."
538
+ return (
539
+ "Hermes requires this plugin to be allow-listed. Would print snippet for:\n"
540
+ f"{cfg}"
541
+ )
542
+
543
+
544
+ def _activation_message(activation: dict) -> str:
545
+ status = activation.get("status")
546
+ cfg = activation.get("config_path", "")
547
+ if status == "enabled":
548
+ return f"Allow-listed token-optimizer under plugins.enabled in {cfg}."
549
+ if status == "already-enabled":
550
+ return f"token-optimizer already allow-listed in {cfg}; no change."
551
+ # manual-required
552
+ return (
553
+ f"Could not safely patch {cfg} ({activation.get('note', 'ambiguous')}). "
554
+ "Add this manually:\n" + _ENABLE_SNIPPET
555
+ )
556
+
557
+
558
+ def uninstall(*, dry_run: bool = False) -> tuple[Path, str, dict]:
559
+ """Remove Token Optimizer from Hermes's plugins directory.
560
+
561
+ Does NOT auto-remove the plugins.enabled config entry (the user may have
562
+ edited the config); we only print a note that they may remove it.
563
+ """
564
+ hermes_root = hermes_home()
565
+ install_dir = _plugin_install_dir(hermes_root)
566
+
567
+ _assert_no_symlink_escape(install_dir, hermes_root)
568
+
569
+ details: dict = {
570
+ "plugin_dir": str(install_dir),
571
+ "hermes_home": str(hermes_root),
572
+ "dry_run": dry_run,
573
+ "existed": install_dir.exists(),
574
+ "activation_note": (
575
+ "Left the plugins.enabled entry in your Hermes config untouched; "
576
+ f"remove '- {_PLUGIN_NAME}' from {_config_path(hermes_root)} if desired."
577
+ ),
578
+ }
579
+
580
+ if not install_dir.exists():
581
+ return install_dir, "not-found", details
582
+
583
+ if not dry_run:
584
+ # v5.11.1: a running Hermes can hold file locks (notably on
585
+ # Windows). Surface a clean, actionable error naming the dir instead of
586
+ # a raw PermissionError traceback.
587
+ try:
588
+ shutil.rmtree(install_dir)
589
+ except (PermissionError, OSError) as exc:
590
+ raise ValueError(
591
+ f"Could not remove {install_dir}: {exc}. Stop Hermes first "
592
+ "(it may be holding file locks), then re-run --uninstall."
593
+ ) from exc
594
+
595
+ return install_dir, "removed" if not dry_run else "would-remove", details
596
+
597
+
598
+ # ---------------------------------------------------------------------------
599
+ # CLI
600
+ # ---------------------------------------------------------------------------
601
+
602
+ def build_parser() -> argparse.ArgumentParser:
603
+ parser = argparse.ArgumentParser(
604
+ description="Install Token Optimizer as a Hermes plugin."
605
+ )
606
+ parser.add_argument(
607
+ "--dry-run",
608
+ action="store_true",
609
+ help="Validate and print intended action without writing",
610
+ )
611
+ parser.add_argument(
612
+ "--uninstall",
613
+ action="store_true",
614
+ help="Remove Token Optimizer from Hermes plugins",
615
+ )
616
+ parser.add_argument(
617
+ "--enable",
618
+ action="store_true",
619
+ help="Also allow-list the plugin in the Hermes config (plugins.enabled)",
620
+ )
621
+ parser.add_argument(
622
+ "--json",
623
+ action="store_true",
624
+ help="Emit machine-readable JSON output",
625
+ )
626
+ return parser
627
+
628
+
629
+ def main(argv: list[str] | None = None) -> int:
630
+ args = build_parser().parse_args(argv)
631
+
632
+ try:
633
+ if args.uninstall:
634
+ install_dir, action, details = uninstall(dry_run=args.dry_run)
635
+ else:
636
+ install_dir, action, details = install(dry_run=args.dry_run, enable=args.enable)
637
+ except ValueError as exc:
638
+ print(f"[Token Optimizer] {exc}", file=sys.stderr)
639
+ return 1
640
+
641
+ # Activation status lives at details.activation_result only (no duplicate
642
+ # top-level copy — one canonical location for JSON consumers).
643
+ payload = {
644
+ "action": action,
645
+ "plugin_dir": str(install_dir),
646
+ "dry_run": args.dry_run,
647
+ "details": details,
648
+ }
649
+
650
+ if args.json:
651
+ print(json.dumps(payload, indent=2))
652
+ else:
653
+ prefix = "Would update" if args.dry_run else "Updated"
654
+ n_files = len(details.get("files", []))
655
+ print(f"[Token Optimizer] {prefix} {install_dir} ({action}; {n_files} files)")
656
+ if "activation" in details:
657
+ print(f"[Token Optimizer] {details['activation']}")
658
+ # v5.11.1: print the activation note on ALL uninstall outcomes,
659
+ # including "not-found" -- the user may still have a stale plugins.enabled
660
+ # entry to clean up.
661
+ if action in ("removed", "would-remove", "not-found") and "activation_note" in details:
662
+ print(f"[Token Optimizer] {details['activation_note']}")
663
+
664
+ return 0
665
+
666
+
667
+ if __name__ == "__main__":
668
+ raise SystemExit(main())