@alexgreensh/token-optimizer 5.13.56 → 5.13.59

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 (30) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/hooks/hooks.json +16 -16
  4. package/hooks/python-launcher.sh +10 -0
  5. package/hooks/stop_runner.py +27 -4
  6. package/hooks/windows-launcher.py +57 -3
  7. package/package.json +1 -1
  8. package/skills/fleet-auditor/scripts/shared.py +29 -1
  9. package/skills/token-optimizer/pricing/prices.json +13 -1
  10. package/skills/token-optimizer/scripts/codex_compact_prompt.py +93 -9
  11. package/skills/token-optimizer/scripts/codex_doctor.py +134 -16
  12. package/skills/token-optimizer/scripts/codex_install.py +436 -26
  13. package/skills/token-optimizer/scripts/codex_session.py +38 -8
  14. package/skills/token-optimizer/scripts/copilot_doctor.py +129 -6
  15. package/skills/token-optimizer/scripts/copilot_hook_bridge.py +62 -14
  16. package/skills/token-optimizer/scripts/copilot_install.py +56 -4
  17. package/skills/token-optimizer/scripts/detectors/cache_instability.py +18 -4
  18. package/skills/token-optimizer/scripts/deterministic_candidates.py +55 -15
  19. package/skills/token-optimizer/scripts/devin_source.py +1 -1
  20. package/skills/token-optimizer/scripts/hermes_doctor.py +177 -1
  21. package/skills/token-optimizer/scripts/hermes_hook_bridge.py +190 -0
  22. package/skills/token-optimizer/scripts/hermes_install.py +43 -0
  23. package/skills/token-optimizer/scripts/hermes_session.py +133 -0
  24. package/skills/token-optimizer/scripts/hermes_state.py +58 -0
  25. package/skills/token-optimizer/scripts/hermes_tool_hooks.py +291 -0
  26. package/skills/token-optimizer/scripts/measure.py +1442 -325
  27. package/skills/token-optimizer/scripts/plugin_env.py +18 -0
  28. package/skills/token-optimizer/scripts/recovery_output.py +15 -2
  29. package/skills/token-optimizer/scripts/refetch_fingerprint.py +36 -1
  30. package/skills/token-optimizer/scripts/runtime_env.py +5 -1
@@ -241,6 +241,24 @@ def find_sibling_plugin_data_dirs(active: Path | None = None) -> list[Path]:
241
241
  return siblings
242
242
 
243
243
 
244
+ def snapshot_roots_for_home(home: Path) -> list[Path]:
245
+ """Snapshot roots Token Optimizer may have used under another runtime's
246
+ *home*: each safe ``plugins/data/token-optimizer-*`` identity's ``data``
247
+ dir, then the legacy ``_backups/token-optimizer``. Read-side recovery only
248
+ (expand's cross-runtime fallback); never a write target. Never raises."""
249
+ roots: list[Path] = []
250
+ try:
251
+ base = home / "plugins" / "data"
252
+ if base.is_dir() and not base.is_symlink():
253
+ for path in sorted(base.glob(f"{_PLUGIN_NAME}-*"), key=lambda p: p.name):
254
+ if _is_safe_subdir(path, base):
255
+ roots.append(path / "data")
256
+ except OSError:
257
+ pass
258
+ roots.append(home / "_backups" / "token-optimizer")
259
+ return roots
260
+
261
+
244
262
  def snapshot_dir_candidates() -> list[Path]:
245
263
  """Return active then sibling snapshot roots for read-side recovery."""
246
264
  override = os.environ.get("TOKEN_OPTIMIZER_SNAPSHOT_DIR", "").strip()
@@ -40,6 +40,10 @@ def is_recovery_tool(tool_name: str) -> bool:
40
40
  # failed output must never be archived), not new tool output.
41
41
  _HINT_TAIL = re.compile(
42
42
  r'[a-zA-Z0-9_][a-zA-Z0-9_-]*(?: --session [a-zA-Z0-9_][a-zA-Z0-9_-]*)?\]?\Z')
43
+ # A printed hint may pin its runtime with a leading `--runtime NAME` (Hermes and
44
+ # Codex archives live under their own homes; see refetch_fingerprint.expand_command).
45
+ _RUNTIME_PIN = re.compile(r'--runtime [a-z][a-z0-9-]{0,31} ')
46
+ _RUNTIME_NAME = re.compile(r'[a-z][a-z0-9-]{0,31}')
43
47
 
44
48
 
45
49
  def _is_printed_hint(command: str) -> bool:
@@ -66,8 +70,14 @@ def _is_printed_hint(command: str) -> bool:
66
70
  shown_forms.update((f"'{raw}'", f"'{fwd}'", f'"{fwd}"'))
67
71
  for interp in _INTERPRETERS:
68
72
  for shown in shown_forms:
69
- prefix = f'{interp} {shown} expand '
70
- if text.startswith(prefix) and _HINT_TAIL.match(text[len(prefix):]):
73
+ head = f'{interp} {shown} '
74
+ if not text.startswith(head):
75
+ continue
76
+ rest = text[len(head):]
77
+ pinned = _RUNTIME_PIN.match(rest)
78
+ if pinned:
79
+ rest = rest[pinned.end():]
80
+ if rest.startswith('expand ') and _HINT_TAIL.match(rest[len('expand '):]):
71
81
  return True
72
82
  return False
73
83
 
@@ -85,6 +95,9 @@ def is_expand_command(command: str) -> bool:
85
95
  return True
86
96
  try:
87
97
  tokens = shlex.split(command)
98
+ if (len(tokens) >= 4 and tokens[2] == '--runtime'
99
+ and _RUNTIME_NAME.fullmatch(tokens[3])):
100
+ tokens = tokens[:2] + tokens[4:]
88
101
  if len(tokens) not in (4, 6) or tokens[2] != 'expand':
89
102
  return False
90
103
  if not _PYTHON.fullmatch(Path(tokens[0]).name):
@@ -170,10 +170,45 @@ def measure_py_path() -> str:
170
170
  return str(Path(__file__).resolve().parent / "measure.py")
171
171
 
172
172
 
173
+ def _pinned_runtime_flag() -> str:
174
+ """`--runtime NAME ` when a printed command must name its runtime, else "".
175
+
176
+ Every runtime but Claude Code keeps its archives under its own home, and
177
+ the process that prints a pointer is the one that wrote the archive, so it
178
+ always knows the right runtime. The model's shell often does not:
179
+ - Hermes sets HERMES_HOME only when the user overrode it.
180
+ - Codex sets TOKEN_OPTIMIZER_RUNTIME=codex on our hook commands only,
181
+ never on the model's shell.
182
+ - Copilot, Cursor, Grok and Antigravity pin TOKEN_OPTIMIZER_RUNTIME on
183
+ their hook bridges only; their pointers come from bash_compress.py in
184
+ the model's shell, where the runtime is re-detected each run from env
185
+ or a time-boxed process-tree scan (Copilot, Antigravity, OpenCode)
186
+ that fails open to Claude Code.
187
+ A bare `measure.py expand <key>` that resolves a different runtime than the
188
+ run that archived looks in the wrong archive and finds nothing. The
189
+ leading `--runtime` flag (consume_runtime_flag) works in every shell.
190
+ Claude Code stays unpinned: it is the default a bare command resolves.
191
+ """
192
+ try:
193
+ from runtime_env import detect_runtime
194
+
195
+ runtime = detect_runtime()
196
+ if runtime and runtime != _UNPINNED_RUNTIME and _RUNTIME_NAME.fullmatch(runtime):
197
+ return f"--runtime {runtime} "
198
+ except Exception:
199
+ pass
200
+ return ""
201
+
202
+
203
+ _UNPINNED_RUNTIME = "claude"
204
+ # Same shape recovery_output accepts in the pinned slot.
205
+ _RUNTIME_NAME = re.compile(r"[a-z][a-z0-9-]{0,31}")
206
+
207
+
173
208
  def expand_command(key: str) -> str:
174
209
  """The exact Bash command that retrieves an archived result — one source of
175
210
  truth for both the archive footer and the guard's deny reason."""
176
- return f"{hint_python()} {shell_path(measure_py_path())} expand {key}"
211
+ return f"{hint_python()} {shell_path(measure_py_path())} {_pinned_runtime_flag()}expand {key}"
177
212
 
178
213
 
179
214
  def _windows_hints() -> bool:
@@ -1847,8 +1847,12 @@ def opencode_data_home() -> Path:
1847
1847
 
1848
1848
  def runtime_home() -> Path:
1849
1849
  """Return the home directory used by the active runtime."""
1850
- runtime = detect_runtime()
1850
+ return runtime_home_for(detect_runtime())
1851
+
1851
1852
 
1853
+ def runtime_home_for(runtime: str) -> Path:
1854
+ """Return the home directory a named runtime uses (Claude Code for an
1855
+ unknown name), resolved with the same overrides as runtime_home()."""
1852
1856
  if runtime == _RUNTIME_CODEX:
1853
1857
  return codex_home()
1854
1858