@alexgreensh/token-optimizer 5.13.75 → 5.13.76

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 (84) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/hooks/module_runner.py +1 -1
  4. package/hooks/posttooluse_runner.py +7 -9
  5. package/hooks/run.py +5 -1
  6. package/hooks/stop_runner.py +15 -56
  7. package/hooks/userpromptsubmit_runner.py +29 -4
  8. package/package.json +1 -1
  9. package/skills/token-optimizer/assets/dashboard.html +30 -14
  10. package/skills/token-optimizer/assets/savings_story.js +103 -27
  11. package/skills/token-optimizer/references/agent-prompts.md +2 -0
  12. package/skills/token-optimizer/references/implementation-playbook.md +1 -0
  13. package/skills/token-optimizer/scripts/_measure/__init__.py +1 -1
  14. package/skills/token-optimizer/scripts/_measure/apply_safe.py +512 -0
  15. package/skills/token-optimizer/scripts/_measure/audit.py +9 -20
  16. package/skills/token-optimizer/scripts/_measure/autocompact_advice.py +455 -0
  17. package/skills/token-optimizer/scripts/_measure/cache_policy.py +82 -127
  18. package/skills/token-optimizer/scripts/_measure/cli.py +10 -24
  19. package/skills/token-optimizer/scripts/_measure/cold_guard.py +777 -0
  20. package/skills/token-optimizer/scripts/_measure/continuity.py +45 -4
  21. package/skills/token-optimizer/scripts/_measure/counted_closes.py +398 -0
  22. package/skills/token-optimizer/scripts/_measure/counted_headline.py +112 -0
  23. package/skills/token-optimizer/scripts/_measure/dashboard.py +14 -6
  24. package/skills/token-optimizer/scripts/_measure/feature_health.py +6 -0
  25. package/skills/token-optimizer/scripts/_measure/keepwarm_auto.py +452 -0
  26. package/skills/token-optimizer/scripts/_measure/keepwarm_economics.py +8 -4
  27. package/skills/token-optimizer/scripts/_measure/keepwarm_safety.py +548 -24
  28. package/skills/token-optimizer/scripts/_measure/limit_units.py +463 -0
  29. package/skills/token-optimizer/scripts/_measure/local_adapt.py +192 -0
  30. package/skills/token-optimizer/scripts/_measure/mod_action_booking.py +71 -14
  31. package/skills/token-optimizer/scripts/_measure/next_actions.py +420 -0
  32. package/skills/token-optimizer/scripts/_measure/poc_commands.py +44 -0
  33. package/skills/token-optimizer/scripts/_measure/prefix_cost.py +215 -0
  34. package/skills/token-optimizer/scripts/_measure/pt_resume_cues.py +46 -0
  35. package/skills/token-optimizer/scripts/_measure/quality_archive.py +7 -10
  36. package/skills/token-optimizer/scripts/_measure/savings.py +75 -81
  37. package/skills/token-optimizer/scripts/_measure/savings_headline.py +17 -21
  38. package/skills/token-optimizer/scripts/_measure/savings_story.py +8 -1
  39. package/skills/token-optimizer/scripts/_measure/session_store_spool.py +119 -78
  40. package/skills/token-optimizer/scripts/_measure/status_bar_refresh.py +38 -3
  41. package/skills/token-optimizer/scripts/_measure/structural_ledger.py +1 -1
  42. package/skills/token-optimizer/scripts/_measure/subscription_audits.py +725 -0
  43. package/skills/token-optimizer/scripts/_measure/transcript_backfill.py +1 -1
  44. package/skills/token-optimizer/scripts/_measure/transcript_stream.py +8 -2
  45. package/skills/token-optimizer/scripts/antigravity_install.py +3 -0
  46. package/skills/token-optimizer/scripts/archive_result.py +16 -28
  47. package/skills/token-optimizer/scripts/archive_verify.py +1 -1
  48. package/skills/token-optimizer/scripts/bash_compress.py +156 -176
  49. package/skills/token-optimizer/scripts/bash_compress_hook.py +218 -174
  50. package/skills/token-optimizer/scripts/bash_search_results.py +189 -9
  51. package/skills/token-optimizer/scripts/bash_whitelist.py +6 -1
  52. package/skills/token-optimizer/scripts/benchmark.py +11 -13
  53. package/skills/token-optimizer/scripts/big_noncode_read.py +998 -0
  54. package/skills/token-optimizer/scripts/build_output_compress.py +103 -8
  55. package/skills/token-optimizer/scripts/builtin_tool_compress.py +716 -0
  56. package/skills/token-optimizer/scripts/cloud_kit.py +1 -1
  57. package/skills/token-optimizer/scripts/codex_doctor.py +1 -1
  58. package/skills/token-optimizer/scripts/command_compress_extra.py +955 -0
  59. package/skills/token-optimizer/scripts/compact_markers.py +129 -0
  60. package/skills/token-optimizer/scripts/copilot_install.py +3 -0
  61. package/skills/token-optimizer/scripts/cursor_install.py +7 -0
  62. package/skills/token-optimizer/scripts/devin_source.py +5 -5
  63. package/skills/token-optimizer/scripts/emit_safety_gate.py +518 -0
  64. package/skills/token-optimizer/scripts/fixtures/b2_more_commands.json +142 -0
  65. package/skills/token-optimizer/scripts/fixtures/b5_more_savings.json +26 -0
  66. package/skills/token-optimizer/scripts/fixtures/builtin_tools.json +103 -0
  67. package/skills/token-optimizer/scripts/fixtures/c7_review_ratchet.json +52 -0
  68. package/skills/token-optimizer/scripts/fixtures/large_output_policy.json +55 -0
  69. package/skills/token-optimizer/scripts/go_cargo_test_compress.py +493 -0
  70. package/skills/token-optimizer/scripts/grok_install.py +3 -0
  71. package/skills/token-optimizer/scripts/hermes_doctor.py +4 -1
  72. package/skills/token-optimizer/scripts/hermes_install.py +10 -1
  73. package/skills/token-optimizer/scripts/hook_fastpath.py +94 -0
  74. package/skills/token-optimizer/scripts/hook_runtime.py +6 -2
  75. package/skills/token-optimizer/scripts/large_output_policy.py +431 -0
  76. package/skills/token-optimizer/scripts/measure.py +10 -12
  77. package/skills/token-optimizer/scripts/pipe_file_compress.py +900 -0
  78. package/skills/token-optimizer/scripts/pipeline_analyzer.py +15 -1
  79. package/skills/token-optimizer/scripts/post_run_classify.py +2 -2
  80. package/skills/token-optimizer/scripts/preserved_reinject.py +20 -3
  81. package/skills/token-optimizer/scripts/process_identity.py +66 -0
  82. package/skills/token-optimizer/scripts/read_cache.py +51 -60
  83. package/skills/token-optimizer/scripts/statusline.js +21 -3
  84. package/skills/token-optimizer/scripts/visibility_rule.py +536 -0
@@ -189,7 +189,7 @@ def unmatched_markers(conn, session_uuid, scan, estimate_tokens, tokens_from_cha
189
189
  """Skip markers with a plausible native row, keeping ambiguous cases conservative."""
190
190
  ce = conn.execute("SELECT timestamp, original_tokens, command_pattern FROM compression_events WHERE "
191
191
  "(session_uuid=? OR session_id=?) AND (origin IS NULL OR origin!=?) "
192
- "AND (feature LIKE 'bash_%' OR feature IN ('build_output_compress','crossturn_dedup'))", (session_uuid, session_uuid, ORIGIN)).fetchall()
192
+ "AND (feature LIKE 'bash_%' OR feature LIKE 'cmd_%' OR feature IN ('build_output_compress','crossturn_dedup','pipe_compress','large_output_policy'))", (session_uuid, session_uuid, ORIGIN)).fetchall()
193
193
  se = conn.execute("SELECT timestamp, tokens_saved, detail FROM savings_events WHERE "
194
194
  "(session_uuid=? OR session_id=?) AND (origin IS NULL OR origin!=?) "
195
195
  "AND event_type='tool_archive'", (session_uuid, session_uuid, ORIGIN)).fetchall()
@@ -81,7 +81,7 @@ def records(filepath, seconds=None, raw=False):
81
81
  growing session. Replacement, truncation and same-size rewrites restart it.
82
82
  Incomplete final lines remain at their starting offset until completed.
83
83
  """
84
- deadline = time.monotonic() + (PASS_SECONDS if seconds is None else max(0, seconds))
84
+ budget = PASS_SECONDS if seconds is None else max(0, seconds)
85
85
  path = Path(filepath).resolve()
86
86
  key = str(path)
87
87
  conn = _connect()
@@ -102,7 +102,13 @@ def records(filepath, seconds=None, raw=False):
102
102
  offset, skipped = row[1], row[5]
103
103
  handle.seek(offset)
104
104
  stop = min(stat.st_size, offset + PASS_BYTES)
105
- while handle.tell() < stop and time.monotonic() < deadline:
105
+ # Start the scan budget after SQLite setup so a slow DB open/WAL init
106
+ # (e.g. AV scan on Windows) cannot consume the entire pass before any
107
+ # line is read.
108
+ deadline = time.monotonic() + budget
109
+ progressed = False
110
+ while handle.tell() < stop and (time.monotonic() < deadline or (budget > 0 and not progressed)):
111
+ progressed = True
106
112
  start = handle.tell()
107
113
  line = handle.readline(LINE_BYTES + 1)
108
114
  if not line:
@@ -60,6 +60,9 @@ _PAYLOAD_MODULES = (
60
60
  "post_run_classify.py",
61
61
  "preserved_reinject.py",
62
62
  "bash_search_results.py",
63
+ "command_compress_extra.py",
64
+ "visibility_rule.py",
65
+ "emit_safety_gate.py",
63
66
  # Dependency-free whitelist gate shared by bash_hook + bash_compress.
64
67
  "bash_whitelist.py",
65
68
  "command_filters.py",
@@ -222,8 +222,6 @@ def _safe_archive_key(tool_use_id: str) -> str:
222
222
  return f"h{digest}"
223
223
 
224
224
 
225
-
226
-
227
225
  def _archive_dir_for_session(session_id: str) -> Path:
228
226
  """Return the archive directory for a given session."""
229
227
  sid = _sanitize_session_id(session_id)
@@ -1611,10 +1609,7 @@ def archive_result(quiet: bool = False) -> None:
1611
1609
  if not quiet:
1612
1610
  print(f"[Tool Archive] Archived {tool_name} result ({char_count:,} chars, ~{token_est:,} tokens): {tool_use_id}", file=sys.stderr)
1613
1611
 
1614
- # WS4: measure-only opportunity event for large Agent/Task results. We do NOT
1615
- # replace the output (the 39.1% harm proxy fails the gate), but we record the
1616
- # would-be saving so coverage/dashboard surface the pool. The full result is
1617
- # already archived above, so an `expand` path exists regardless. Fail-open.
1612
+ # Record WS4 opportunity metric for 8KB-12KB Agent/Task results (larger ones are capped below).
1618
1613
  if tool_name in _AGENT_RESULT_TOOL_NAMES and original_char_count >= _AGENT_RESULT_MIN_CHARS:
1619
1614
  try:
1620
1615
  _log_agent_result_opportunity(tool_response, session_id)
@@ -1676,12 +1671,7 @@ def archive_result(quiet: bool = False) -> None:
1676
1671
  print(f"[Tool Archive] {tool_name} is allowlisted; serving full result (archived for expand).", file=sys.stderr)
1677
1672
  return
1678
1673
 
1679
- # For MCP tools (tool_name contains "__"): output replacement via stdout
1680
- # No pressure gate here: the compressed replacement SAVES tokens.
1681
- # Suppressing it would cause the full uncompressed response to flow through.
1682
- #
1683
- # Skip the replacement when the entry was pruned by the retention pass that
1684
- # ran after write. Emitting a pointer to a missing entry strands the model.
1674
+ # MCP tools emit updatedMCPToolOutput.
1685
1675
  if not entry_exists:
1686
1676
  return
1687
1677
 
@@ -1690,16 +1680,8 @@ def archive_result(quiet: bool = False) -> None:
1690
1680
  from _measure.mcp_archive_tripwire import structured_preview
1691
1681
  preview = structured_preview(safe_response, breaks_cluster=_breaks_cluster)
1692
1682
  suffix = f" ({output_type})" if output_type != "text" else ""
1693
- if original_char_count > _ARCHIVE_MAX_SIZE:
1694
- replacement = preview + (
1695
- f"\n\n[Full result archived ({original_char_count:,} chars{suffix}, truncated to 5MB) — "
1696
- f"saved to disk, not lost.\n{_expand_instruction(tool_use_id, tool_name)}\n]"
1697
- )
1698
- else:
1699
- replacement = preview + (
1700
- f"\n\n[Full result archived ({char_count:,} chars{suffix}) — saved to disk, not lost.\n"
1701
- f"{_expand_instruction(tool_use_id, tool_name)}\n]"
1702
- )
1683
+ size_note = f"{original_char_count:,} chars{suffix}, truncated to 5MB" if original_char_count > _ARCHIVE_MAX_SIZE else f"{char_count:,} chars{suffix}"
1684
+ replacement = f"{preview}\n\n[Full result archived ({size_note}) — saved to disk, not lost.\n{_expand_instruction(tool_use_id, tool_name)}\n]"
1703
1685
  original_tokens = int(original_char_count / CODE_CHARS_PER_TOKEN)
1704
1686
  replacement_tokens = int(len(replacement) / CODE_CHARS_PER_TOKEN)
1705
1687
  tokens_saved = max(0, original_tokens - replacement_tokens)
@@ -1709,15 +1691,21 @@ def archive_result(quiet: bool = False) -> None:
1709
1691
  archive_verify.verify(TRENDS_DB, session_id)
1710
1692
  if tokens_saved > 0: archive_verify.record(TRENDS_DB, session_id, raw_tool_use_id, tool_name,
1711
1693
  original_char_count, len(replacement), hook_input.get("transcript_path"), detail)
1712
- output = json.dumps({
1713
- "hookSpecificOutput": {
1714
- "hookEventName": "PostToolUse",
1715
- "updatedMCPToolOutput": replacement,
1716
- }
1717
- })
1694
+ output = json.dumps({"hookSpecificOutput": {"hookEventName": "PostToolUse", "updatedMCPToolOutput": replacement}})
1718
1695
  print(output)
1719
1696
  from _measure.mcp_archive_tripwire import record
1720
1697
  record(TRENDS_DB, tool_name, sanitize_sid(session_id), tool_use_id, tokens_saved)
1698
+ elif tool_name in ("Grep", "Glob"):
1699
+ try:
1700
+ from builtin_tool_compress import maybe_emit_builtin_replacement
1701
+ maybe_emit_builtin_replacement(
1702
+ tool_name=tool_name, raw_response=raw_response, safe_response=safe_response, hook_input=hook_input,
1703
+ tool_use_id=tool_use_id, raw_tool_use_id=raw_tool_use_id, session_id=session_id,
1704
+ original_char_count=original_char_count, char_count=char_count, truncated=truncated,
1705
+ code_chars_per_token=CODE_CHARS_PER_TOKEN, trends_db=TRENDS_DB,
1706
+ log_savings_event_fn=_log_savings_event, is_exempt_fn=_is_archive_exempt, redact_fn=_redact_credentials)
1707
+ except Exception:
1708
+ pass
1721
1709
 
1722
1710
 
1723
1711
  if __name__ == "__main__":
@@ -43,7 +43,7 @@ def record(trends_db, session_id, tool_use_id, tool_name, original_chars, pointe
43
43
  conn = None
44
44
  try:
45
45
  conn = _connect(trends_db)
46
- row = conn.execute("SELECT max(id) FROM savings_events WHERE event_type='tool_archive' AND session_id=? AND detail=?",
46
+ row = conn.execute("SELECT max(id) FROM savings_events WHERE event_type IN ('tool_archive','builtin_grep','builtin_glob') AND session_id=? AND detail=?",
47
47
  (session_id, detail)).fetchone()
48
48
  conn.execute("INSERT OR IGNORE INTO " + TABLE + " (tool_use_id, session_id, event_id, tool_name, original_chars, "
49
49
  "pointer_chars, transcript_path, logged_at) VALUES (?,?,?,?,?,?,?,?)",