@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
@@ -11,6 +11,8 @@ from pathlib import Path
11
11
  from typing import Any
12
12
 
13
13
  from runtime_env import codex_home, detect_runtime, runtime_home
14
+ import codex_compact_prompt
15
+ import codex_install
14
16
  import codex_state
15
17
  import codex_statusline
16
18
 
@@ -230,13 +232,39 @@ def _compact_prompt_check() -> dict[str, str]:
230
232
  except UnicodeDecodeError:
231
233
  return _check("FAIL", "Compact prompt", f"{config_path} is not valid UTF-8; run measure.py codex-compact-prompt --install")
232
234
  expected = codex_home() / "token-optimizer" / "codex-compact-prompt.md"
233
- if str(expected) in text and expected.exists():
235
+ state = codex_compact_prompt.configured_prompt_state(text, expected)
236
+ if state == "ours" and expected.exists():
234
237
  return _check("OK", "Compact prompt", str(expected))
235
- if "compact_prompt" in text or "experimental_compact_prompt_file" in text:
238
+ if state == "misplaced":
239
+ return _check("FAIL", "Compact prompt", "setting sits inside a table, so Codex ignores it; rerun measure.py codex-compact-prompt --install to move it")
240
+ if state in ("ours", "custom"):
236
241
  return _check("WARN", "Compact prompt", "custom compact prompt configured")
237
242
  return _check("FAIL", "Compact prompt", "not configured yet; run measure.py codex-compact-prompt --install")
238
243
 
239
244
 
245
+ def _stop_hook_activity_check() -> dict[str, str]:
246
+ """Report the last Stop-hook refresh, so "registered" and "actually ran"
247
+ are no longer the same line (issue #276)."""
248
+ status_path = runtime_home() / "token-optimizer" / "hook-status.json"
249
+ data, error = _load_json(status_path)
250
+ entry = data.get("stop_flush") if isinstance(data, dict) else None
251
+ if error or not isinstance(entry, dict):
252
+ return _check("WARN", "Stop hook last run", "no run recorded yet; finish one Codex turn, then run the doctor again")
253
+ when = entry.get("at", "unknown time")
254
+ result = str(entry.get("result", "unknown"))
255
+ level = "WARN" if result.startswith("error") else "OK"
256
+ detail = f"{when}: {result}"
257
+ # What the host actually sent (field presence only, never values) and
258
+ # whether the checkpoint could be tied to a session (issue #278).
259
+ for key, label in (("stop_payload", "host payload"), ("stop_capture", "checkpoint")):
260
+ extra = data.get(key) if isinstance(data, dict) else None
261
+ if isinstance(extra, dict) and extra.get("result"):
262
+ detail += f"; {label} ({extra.get('at', 'unknown time')}): {extra['result']}"
263
+ if key == "stop_capture" and str(extra["result"]).startswith("skipped"):
264
+ level = "WARN"
265
+ return _check(level, "Stop hook last run", detail)
266
+
267
+
240
268
  def _status_line_check() -> dict[str, str]:
241
269
  try:
242
270
  state = codex_statusline.status()
@@ -249,6 +277,16 @@ def _status_line_check() -> dict[str, str]:
249
277
  return _check("WARN", "Codex CLI status line", "not configured; rerun codex-install with --enable-status-line")
250
278
 
251
279
 
280
+ def _has_our_hooks(data: dict[str, Any]) -> bool:
281
+ """Same ownership test the installer uses. The consolidated runner hooks
282
+ carry no "token-optimizer/scripts" text on POSIX installs, so a substring
283
+ check called a working install "no Token Optimizer hooks"."""
284
+ for groups in data.get("hooks", {}).values():
285
+ if isinstance(groups, list) and any(codex_install._is_token_optimizer_group(g) for g in groups):
286
+ return True
287
+ return False
288
+
289
+
252
290
  def _global_hook_check() -> dict[str, str]:
253
291
  hooks_path = codex_home() / "hooks.json"
254
292
  data, error = _load_json(hooks_path)
@@ -256,11 +294,78 @@ def _global_hook_check() -> dict[str, str]:
256
294
  return _check("FAIL", "Global hooks", f"{hooks_path} not found; run measure.py codex-install")
257
295
  if not isinstance(data, dict) or not isinstance(data.get("hooks"), dict):
258
296
  return _check("FAIL", "Global hooks", f"{hooks_path} has no hooks object")
259
- if "token-optimizer/scripts" in json.dumps(data, sort_keys=True):
297
+ if _has_our_hooks(data):
260
298
  return _check("OK", "Global hooks", str(hooks_path))
261
299
  return _check("WARN", "Global hooks", f"no Token Optimizer hooks in {hooks_path}; run measure.py codex-install")
262
300
 
263
301
 
302
+ def _hook_shell_check() -> list[dict[str, str]]:
303
+ """Flag Windows launcher hook commands only cmd.exe can run (issue #278).
304
+
305
+ Codex runs a command hook in the session shell, normally PowerShell, which
306
+ cannot parse the ``set ... &&`` prefix or a quoted first token that older
307
+ installs wrote. The hook then exits 1 before Token Optimizer starts.
308
+ """
309
+ hooks_path = codex_home() / "hooks.json"
310
+ data, error = _load_json(hooks_path)
311
+ if error or not isinstance(data, dict) or not isinstance(data.get("hooks"), dict):
312
+ return []
313
+ ours = 0
314
+ cmd_only = 0
315
+ dev_only = 0
316
+ advices: list[str] = []
317
+ for groups in data["hooks"].values():
318
+ if not isinstance(groups, list):
319
+ continue
320
+ for group in groups:
321
+ if not isinstance(group, dict):
322
+ continue
323
+ group_ours = codex_install._is_token_optimizer_group(group)
324
+ for hook in group.get("hooks", []):
325
+ command = hook.get("command") if isinstance(hook, dict) else None
326
+ if not isinstance(command, str):
327
+ continue
328
+ # Dev-checkout installs (non-semver root) carry no launcher
329
+ # marker: they are `set "TOKEN_OPTIMIZER_RUNTIME=codex" && ...
330
+ # hooks/run.py`, cmd-only by construction.
331
+ dev_checkout = (command.startswith('set "TOKEN_OPTIMIZER_RUNTIME=codex" && ')
332
+ and re.search(r"hooks[/\\]+run\.py", command) is not None
333
+ and codex_install._LAUNCHER_MARKER not in command)
334
+ if not dev_checkout and not (group_ours and codex_install._LAUNCHER_MARKER in command):
335
+ continue
336
+ ours += 1
337
+ if dev_checkout:
338
+ dev_only += 1
339
+ continue
340
+ if not codex_install.is_shell_neutral_command(command):
341
+ cmd_only += 1
342
+ advice = codex_install.explain_cmd_only_command(command)
343
+ if advice and advice not in advices:
344
+ advices.append(advice)
345
+ if not ours:
346
+ return []
347
+ if dev_only and not cmd_only:
348
+ return [_check(
349
+ "WARN", "Hook shell compatibility",
350
+ f"{dev_only} of {ours} hook command(s) come from a development checkout and only run under cmd.exe; "
351
+ "Codex normally runs hooks in PowerShell, where they exit 1. To fix: run measure.py codex-install "
352
+ "again from the checkout (it now writes a form PowerShell runs), then restart Codex")]
353
+ if dev_only or cmd_only:
354
+ cmd_only += dev_only
355
+ if cmd_only:
356
+ # Say exactly what to change when the cause is known (an interpreter or
357
+ # plugin folder no PowerShell-safe spelling exists for), else the
358
+ # generic repair (issue #278).
359
+ fix = "; ".join(advices) if advices else (
360
+ "run any measure.py command to repair them or rerun measure.py codex-install, "
361
+ "then restart Codex")
362
+ return [_check(
363
+ "WARN", "Hook shell compatibility",
364
+ f"{cmd_only} of {ours} hook command(s) only run under cmd.exe, but Codex normally runs hooks in "
365
+ f"PowerShell, where they exit 1 before Token Optimizer starts. To fix: {fix}")]
366
+ return [_check("OK", "Hook shell compatibility", f"{ours} hook command(s) run under PowerShell and cmd.exe")]
367
+
368
+
264
369
  def _global_hook_config_checks() -> list[dict[str, str]]:
265
370
  hooks_path = codex_home() / "hooks.json"
266
371
  data, error = _load_json(hooks_path)
@@ -302,32 +407,42 @@ def _project_hook_check(project: Path) -> dict[str, str]:
302
407
  return _check("WARN", "Project hooks", f"{hooks_path} not found; per-project hooks are optional when global hooks are installed")
303
408
  if not isinstance(data, dict) or not isinstance(data.get("hooks"), dict):
304
409
  return _check("FAIL", "Project hooks", f"{hooks_path} has no hooks object")
305
- if "token-optimizer/scripts" in json.dumps(data, sort_keys=True):
410
+ if _has_our_hooks(data):
306
411
  return _check("OK", "Project hooks", str(hooks_path))
307
412
  return _check("WARN", "Project hooks", f"no Token Optimizer hooks installed in {hooks_path}; manual refresh mode avoids visible Codex hook rows")
308
413
 
309
414
 
310
415
  def _project_feature_checks(project: Path) -> list[dict[str, str]]:
311
- hooks_path = project / ".codex" / "hooks.json"
312
- data, error = _load_json(hooks_path)
313
- if error or not isinstance(data, dict) or not isinstance(data.get("hooks"), dict):
416
+ # Features count from the global hooks file AND the project one: the
417
+ # default install is global, so a project-only view reported every
418
+ # feature as missing on a correctly installed machine.
419
+ hooks: dict[str, list] = {}
420
+ for hooks_path in (codex_home() / "hooks.json", project / ".codex" / "hooks.json"):
421
+ data, error = _load_json(hooks_path)
422
+ if error or not isinstance(data, dict) or not isinstance(data.get("hooks"), dict):
423
+ continue
424
+ for event, groups in data["hooks"].items():
425
+ if isinstance(groups, list):
426
+ hooks.setdefault(event, []).extend(groups)
427
+ if not hooks:
314
428
  return []
315
429
 
316
- hooks = data.get("hooks", {})
317
430
  checks = []
318
- if _has_project_hook(hooks, "PreToolUse", "Bash", "bash_hook.py"):
431
+ if _has_project_hook(hooks, "PreToolUse", "Bash", ("codex_command_compress.py", "bash_hook.py")):
319
432
  checks.append(_check("OK", "Feature: Bash compression", "enabled for PreToolUse(Bash)"))
320
433
  else:
321
434
  checks.append(_check("OK", "Feature: Bash compression", "off by default to avoid visible Codex PreToolUse hook spam"))
322
435
 
323
436
  required_features = (
324
- ("Session continuity and dashboard refresh", "Stop", None, "session-end-flush"),
437
+ # Current installs route through the consolidated runners; the older
438
+ # per-script names still count so a pre-runner install reads right.
439
+ ("Session continuity and dashboard refresh", "Stop", None, ("stop_runner.py", "session-end-flush")),
325
440
  )
326
441
  optional_noisy_features = (
327
- ("Prompt quality nudges", "UserPromptSubmit", None, "codex_hook_bridge.py"),
328
- ("Subagent sprawl tracking", "SubagentStart", None, "subagent-start"),
329
- ("Tool output archive", "PostToolUse", "Bash", "archive_result.py"),
330
- ("Context intelligence", "PostToolUse", "Bash", "context_intel.py"),
442
+ ("Prompt quality nudges", "UserPromptSubmit", None, ("userpromptsubmit_runner.py", "codex_hook_bridge.py")),
443
+ ("Subagent sprawl tracking", "SubagentStart", None, ("subagent-start",)),
444
+ ("Tool output archive", "PostToolUse", "Bash", ("posttooluse_runner.py", "archive_result.py")),
445
+ ("Context intelligence", "PostToolUse", "Bash", ("posttooluse_runner.py", "context_intel.py")),
331
446
  )
332
447
  for feature, event, matcher, needle in required_features:
333
448
  if _has_project_hook(hooks, event, matcher, needle):
@@ -354,7 +469,8 @@ def _project_feature_checks(project: Path) -> list[dict[str, str]]:
354
469
  return checks
355
470
 
356
471
 
357
- def _has_project_hook(hooks: dict[str, Any], event: str, matcher: str | None, command_needle: str) -> bool:
472
+ def _has_project_hook(hooks: dict[str, Any], event: str, matcher: str | None, command_needle) -> bool:
473
+ needles = (command_needle,) if isinstance(command_needle, str) else tuple(command_needle)
358
474
  groups = hooks.get(event)
359
475
  if not isinstance(groups, list):
360
476
  return False
@@ -367,7 +483,7 @@ def _has_project_hook(hooks: dict[str, Any], event: str, matcher: str | None, co
367
483
  if not isinstance(hook, dict) or hook.get("type") != "command":
368
484
  continue
369
485
  command = hook.get("command", "")
370
- if isinstance(command, str) and command_needle in command:
486
+ if isinstance(command, str) and any(n in command for n in needles):
371
487
  return True
372
488
  return False
373
489
 
@@ -415,6 +531,8 @@ def run_checks(project: Path | None = None) -> list[dict[str, str]]:
415
531
  checks.append(_compact_prompt_check())
416
532
  checks.append(_status_line_check())
417
533
  checks.append(_global_hook_check())
534
+ checks.append(_stop_hook_activity_check())
535
+ checks.extend(_hook_shell_check())
418
536
  checks.extend(_global_hook_config_checks())
419
537
  checks.append(_project_hook_check(project))
420
538
  checks.extend(_project_feature_checks(project))