@alexgreensh/token-optimizer 0.0.0-stage → 5.13.51

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 +448 -0
  10. package/hooks/posttooluse_runner.py +1110 -0
  11. package/hooks/python-launcher.sh +816 -0
  12. package/hooks/run.py +788 -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 +149 -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 +3633 -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 +141 -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 +93 -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 +379 -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 +1011 -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 +288 -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 +426 -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 +400 -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 +716 -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 +59531 -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 +1923 -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,143 @@
1
+ """Output token waste detector: flags sessions with excessive output relative to task complexity."""
2
+
3
+ from runtime_env import detect_runtime
4
+
5
+ _OUTPUT_RATIO_THRESHOLD = 3.0 # output/input ratio above this on simple turns
6
+ _VERBOSE_RESPONSE_TOKENS = 2000 # assistant message above this after simple ops
7
+ _SIMILARITY_THRESHOLD = 0.6 # Jaccard word overlap for repeated explanations
8
+ _MIN_TURNS_FOR_DETECTION = 5
9
+ _MIN_SAVINGS_TOKENS = 5000 # minimum token savings to report a finding
10
+
11
+
12
+ def _jaccard_words(a: str, b: str) -> float:
13
+ wa = set(a.lower().split())
14
+ wb = set(b.lower().split())
15
+ if not wa or not wb:
16
+ return 0.0
17
+ return len(wa & wb) / len(wa | wb)
18
+
19
+
20
+ def _is_simple_tool_turn(turn: dict) -> bool:
21
+ tools = turn.get("tools_used", [])
22
+ if not tools:
23
+ return False
24
+ simple = {"Read", "Glob", "Grep", "Edit", "Write"}
25
+ return all(t in simple for t in tools) and len(tools) <= 2
26
+
27
+
28
+ def detect_output_waste(session_data):
29
+ """Detect sessions where output tokens are disproportionate to task complexity.
30
+
31
+ Three signals:
32
+ 1. High output/input ratio on turns with only simple tools
33
+ 2. Long assistant messages (>2K tokens) after single-file operations
34
+ 3. Repeated similar explanations across turns (Jaccard >0.6)
35
+ """
36
+ turns = session_data.get("turns", [])
37
+ if len(turns) < _MIN_TURNS_FOR_DETECTION:
38
+ return []
39
+
40
+ total_output = session_data.get("total_output_tokens", 0)
41
+ if total_output == 0:
42
+ return []
43
+
44
+ findings = []
45
+
46
+ # Instruction file is runtime-specific; Codex reads AGENTS.md, foreign
47
+ # runtimes (cursor, antigravity, grok, opencode, copilot, hermes) have no
48
+ # CLAUDE.md surface at all — name it generically rather than print a
49
+ # Claude-only filename.
50
+ _rt = detect_runtime()
51
+ _instr = ("AGENTS.md" if _rt == "codex"
52
+ else "CLAUDE.md" if _rt == "claude"
53
+ else "your agent instructions")
54
+
55
+ # Signal 1: Session-level output/input ratio on simple turns
56
+ simple_turn_output = 0
57
+ simple_turn_input = 0
58
+ simple_turn_count = 0
59
+ for turn in turns:
60
+ if _is_simple_tool_turn(turn):
61
+ simple_turn_output += turn.get("output_tokens", 0)
62
+ simple_turn_input += turn.get("input_tokens", 1)
63
+ simple_turn_count += 1
64
+
65
+ if simple_turn_count >= 3 and simple_turn_input > 0:
66
+ ratio = simple_turn_output / simple_turn_input
67
+ if ratio > _OUTPUT_RATIO_THRESHOLD:
68
+ excess = simple_turn_output - int(simple_turn_input * 1.5)
69
+ if excess > _MIN_SAVINGS_TOKENS:
70
+ findings.append({
71
+ "name": "output_waste",
72
+ "confidence": min(0.5 + (ratio - _OUTPUT_RATIO_THRESHOLD) * 0.1, 0.85),
73
+ "evidence": (
74
+ f"{ratio:.1f}x output/input ratio across {simple_turn_count} simple turns "
75
+ f"({simple_turn_output:,} output vs {simple_turn_input:,} input tokens)"
76
+ ),
77
+ "savings_tokens": excess,
78
+ "suggestion": (
79
+ f"Output tokens are {ratio:.1f}x higher than input on simple file operations. "
80
+ f"This session could save ~{excess:,} output tokens by requesting concise responses. "
81
+ f"Add 'Be concise' or 'No explanations' to {_instr} for routine tasks."
82
+ ),
83
+ "occurrence_count": simple_turn_count,
84
+ })
85
+
86
+ # Signal 2: Verbose responses after simple operations
87
+ verbose_after_simple = 0
88
+ verbose_waste = 0
89
+ for turn in turns:
90
+ if _is_simple_tool_turn(turn):
91
+ output_tok = turn.get("output_tokens", 0)
92
+ if output_tok > _VERBOSE_RESPONSE_TOKENS:
93
+ verbose_after_simple += 1
94
+ verbose_waste += output_tok - _VERBOSE_RESPONSE_TOKENS
95
+
96
+ if verbose_after_simple >= 3 and verbose_waste > _MIN_SAVINGS_TOKENS:
97
+ findings.append({
98
+ "name": "output_waste",
99
+ "confidence": 0.65,
100
+ "evidence": (
101
+ f"{verbose_after_simple} turns had >2K output tokens after simple file operations "
102
+ f"(~{verbose_waste:,} excess output tokens)"
103
+ ),
104
+ "savings_tokens": verbose_waste,
105
+ "suggestion": (
106
+ f"Found {verbose_after_simple} cases of verbose responses to simple edits/reads. "
107
+ f"~{verbose_waste:,} output tokens could be saved with more targeted instructions."
108
+ ),
109
+ "occurrence_count": verbose_after_simple,
110
+ })
111
+
112
+ # Signal 3: Repeated similar explanations
113
+ assistant_msgs = [
114
+ t.get("assistant_text", "")
115
+ for t in turns
116
+ if len(t.get("assistant_text", "")) > 200
117
+ ][:100]
118
+ repeated_pairs = 0
119
+ repeated_waste = 0
120
+ for i in range(len(assistant_msgs)):
121
+ for j in range(i + 1, min(i + 5, len(assistant_msgs))):
122
+ if _jaccard_words(assistant_msgs[i], assistant_msgs[j]) > _SIMILARITY_THRESHOLD:
123
+ repeated_pairs += 1
124
+ repeated_waste += len(assistant_msgs[j]) // 4
125
+
126
+ if repeated_pairs >= 2 and repeated_waste > _MIN_SAVINGS_TOKENS:
127
+ findings.append({
128
+ "name": "output_waste",
129
+ "confidence": 0.55,
130
+ "evidence": (
131
+ f"{repeated_pairs} pairs of similar assistant responses detected "
132
+ f"(>{_SIMILARITY_THRESHOLD:.0%} word overlap, ~{repeated_waste:,} repeated tokens)"
133
+ ),
134
+ "savings_tokens": repeated_waste,
135
+ "suggestion": (
136
+ f"The model repeated similar explanations {repeated_pairs} times. "
137
+ f"~{repeated_waste:,} tokens could be saved. "
138
+ f"Consider adding 'Don't repeat previous explanations' to {_instr}."
139
+ ),
140
+ "occurrence_count": repeated_pairs,
141
+ })
142
+
143
+ return findings
@@ -0,0 +1,116 @@
1
+ """Overpowered model detector: expensive model used for simple tasks."""
2
+
3
+ import re
4
+
5
+ from runtime_env import detect_runtime
6
+
7
+ _TOP_TIER_MODELS = ("fable", "opus", "claude-opus")
8
+ _SIMPLE_TOOLS = frozenset({"Read", "Glob", "Grep", "Edit", "Write", "Bash"})
9
+
10
+ # Session-log model strings are attacker-influenceable (a crafted or
11
+ # custom-provider transcript controls the model_usage keys). The dominant
12
+ # model name is interpolated into evidence/suggestion text that the coach
13
+ # prints verbatim, so strip terminal control sequences first.
14
+ _ANSI_ESCAPE_RE = re.compile(
15
+ r"\x1b\[[0-9;:<=>?]*[ -/]*[@-~]" # CSI (full ECMA-48 parameter bytes 0x30-0x3f)
16
+ r"|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)" # OSC ... BEL or ST
17
+ r"|\x1b[()][0-2A-Z]" # charset selection
18
+ r"|\x1b[@-Z\\-_]" # remaining two-byte escapes
19
+ )
20
+
21
+
22
+ def _strip_ansi(text):
23
+ return _ANSI_ESCAPE_RE.sub("", str(text))
24
+
25
+ # v5.11.1: per-model input token rate ($/Mtok), kept self-contained per this
26
+ # file's hot-path convention (no import of the pricing table). Sonnet's input
27
+ # rate is 3.0; the savings ratio vs a top-tier model is 1 - (3.0 / input_rate).
28
+ _INPUT_RATE = {"fable": 10.0, "opus": 5.0}
29
+
30
+
31
+ def _dominant_top_tier(model_usage):
32
+ """Return (model_name, tokens) for the top-tier model with the most tokens.
33
+
34
+ model_name is a normalized key into _INPUT_RATE ("fable" or "opus"); the
35
+ display name returned is the raw model string for the evidence message.
36
+ """
37
+ best_raw = None
38
+ best_norm = "opus"
39
+ best_tokens = 0
40
+ for k, v in model_usage.items():
41
+ kl = k.lower()
42
+ if not any(t in kl for t in _TOP_TIER_MODELS):
43
+ continue
44
+ if v > best_tokens:
45
+ best_tokens = v
46
+ best_raw = k
47
+ best_norm = "fable" if "fable" in kl else "opus"
48
+ return best_raw, best_norm
49
+
50
+
51
+ def detect_overpowered(session_data):
52
+ """Detect sessions where a top-tier model was used for tasks a cheaper model
53
+ could handle.
54
+
55
+ Flags when: short output (<5K tokens per turn avg) + mostly simple tools
56
+ + a top-tier model (Fable/Opus) is dominant.
57
+ """
58
+ if detect_runtime() not in ("claude", "hermes"):
59
+ # The ladder and the "Sonnet would save" suggestion are Claude-model
60
+ # routing advice. Under foreign runtimes a Claude-tier key in
61
+ # model_usage (custom provider entry, crafted log) must not produce
62
+ # foreign-runtime guidance. Hermes is a Claude runtime and keeps it.
63
+ return []
64
+ model_usage = session_data.get("model_usage", {})
65
+ if not model_usage:
66
+ return []
67
+
68
+ total_tokens = sum(model_usage.values())
69
+ if total_tokens == 0:
70
+ return []
71
+
72
+ # Check top-tier dominance.
73
+ top_tier_tokens = sum(v for k, v in model_usage.items()
74
+ if any(t in k.lower() for t in _TOP_TIER_MODELS))
75
+ top_tier_pct = top_tier_tokens / total_tokens
76
+
77
+ if top_tier_pct < 0.5:
78
+ return []
79
+
80
+ # Check if work was simple: low output, mostly basic tools
81
+ total_output = session_data.get("total_output_tokens", 0)
82
+ api_calls = session_data.get("api_calls", 1)
83
+ avg_output_per_turn = total_output / max(api_calls, 1)
84
+
85
+ tool_calls = session_data.get("tool_calls", {})
86
+ total_tool_count = sum(tool_calls.values())
87
+ simple_tool_count = sum(tool_calls.get(t, 0) for t in _SIMPLE_TOOLS)
88
+ simple_pct = simple_tool_count / max(total_tool_count, 1)
89
+
90
+ # Only flag if output is light AND tools are simple
91
+ if avg_output_per_turn > 5000 or simple_pct < 0.7:
92
+ return []
93
+
94
+ # v5.11.1: model-aware savings. Fable's input rate (10.0) is twice Opus's
95
+ # (5.0), so dropping to Sonnet (3.0) saves a different fraction depending on
96
+ # which top-tier model was dominant.
97
+ dom_raw, dom_norm = _dominant_top_tier(model_usage)
98
+ dom_display = _strip_ansi(dom_raw or dom_norm)
99
+ input_rate = _INPUT_RATE.get(dom_norm, 5.0)
100
+ savings_ratio = 1 - (3.0 / input_rate)
101
+ sonnet_savings = int(top_tier_tokens * savings_ratio)
102
+ return [{
103
+ "name": "overpowered",
104
+ "confidence": 0.6,
105
+ "evidence": (
106
+ f"{top_tier_pct:.0%} {dom_display} usage, {avg_output_per_turn:.0f} avg output tokens/turn, "
107
+ f"{simple_pct:.0%} simple tool calls"
108
+ ),
109
+ "savings_tokens": sonnet_savings,
110
+ "suggestion": (
111
+ f"This session used {dom_display} for mostly simple edits and file reads. "
112
+ f"Sonnet would save ~{sonnet_savings:,} tokens (~{savings_ratio:.0%} cost reduction) "
113
+ "for equivalent quality on these tasks."
114
+ ),
115
+ "occurrence_count": 1,
116
+ }]
@@ -0,0 +1,52 @@
1
+ """PDF/Image ingestion detector for Token Optimizer.
2
+
3
+ Detects expensive binary file reads (PDFs, images, Office docs) and warns
4
+ about token cost. Used inline by read_cache.py hook.
5
+ """
6
+
7
+ # Subset of read_cache.py:BINARY_EXTENSIONS that triggers token-cost warnings.
8
+ EXPENSIVE_BINARY = frozenset({
9
+ ".pdf", ".png", ".jpg", ".jpeg", ".gif", ".bmp", ".webp",
10
+ ".docx", ".xlsx", ".pptx",
11
+ })
12
+
13
+ # Tokens per MB: documents are denser, media is lighter
14
+ _DOCUMENT_TOKENS_PER_MB = 2500
15
+ _MEDIA_TOKENS_PER_MB = 1500
16
+ _DOCUMENT_EXTS = frozenset({".pdf", ".docx", ".xlsx", ".pptx"})
17
+
18
+ _PDF_SUGGESTION = "Extract text first (`pdftotext`), read specific pages (pages: param), or summarize externally."
19
+ _DEFAULT_SUGGESTION = "Consider extracting text content first, or describe what you need from this file."
20
+
21
+
22
+ def detect_pdf_ingestion_inline(file_path, file_size_bytes, ext):
23
+ """Inline check for read_cache.py hook.
24
+
25
+ Args:
26
+ file_path: Path to the file being read
27
+ file_size_bytes: File size in bytes
28
+ ext: File extension (lowercase, with dot)
29
+
30
+ Returns:
31
+ dict with name/confidence/evidence/savings_tokens/suggestion, or None
32
+ """
33
+ if ext not in EXPENSIVE_BINARY:
34
+ return None
35
+
36
+ # Skip tiny files (< 1KB) - not worth warning
37
+ if file_size_bytes < 1024:
38
+ return None
39
+
40
+ size_mb = file_size_bytes / (1024 * 1024)
41
+ tpm = _DOCUMENT_TOKENS_PER_MB if ext in _DOCUMENT_EXTS else _MEDIA_TOKENS_PER_MB
42
+ est_tokens = int(size_mb * tpm)
43
+ suggestion = _PDF_SUGGESTION if ext == ".pdf" else _DEFAULT_SUGGESTION
44
+
45
+ return {
46
+ "name": "pdf_ingestion",
47
+ "confidence": 0.9,
48
+ "evidence": f"{ext} file, {size_mb:.1f}MB, ~{est_tokens:,} estimated tokens",
49
+ "savings_tokens": est_tokens,
50
+ "suggestion": suggestion,
51
+ "occurrence_count": 1,
52
+ }
@@ -0,0 +1,65 @@
1
+ """Detector registry: session and config detectors with run helper."""
2
+
3
+ from detectors.retry_churn import detect_retry_churn
4
+ from detectors.tool_cascade import detect_tool_cascade
5
+ from detectors.looping import detect_looping
6
+ from detectors.overpowered import detect_overpowered
7
+ from detectors.weak_model import detect_weak_model
8
+ from detectors.bad_decomposition import detect_bad_decomposition
9
+ from detectors.wasteful_thinking import detect_wasteful_thinking
10
+ from detectors.output_waste import detect_output_waste
11
+ from detectors.cache_instability import detect_cache_instability
12
+ from detectors.respond_to_bash import detect_respond_to_bash
13
+
14
+ ALL_DETECTORS = [
15
+ {"name": "respond_to_bash_commands", "fn": detect_respond_to_bash},
16
+ {"name": "retry_churn", "fn": detect_retry_churn},
17
+ {"name": "tool_cascade", "fn": detect_tool_cascade},
18
+ {"name": "looping", "fn": detect_looping},
19
+ {"name": "overpowered", "fn": detect_overpowered},
20
+ {"name": "weak_model", "fn": detect_weak_model},
21
+ {"name": "bad_decomposition", "fn": detect_bad_decomposition},
22
+ {"name": "wasteful_thinking", "fn": detect_wasteful_thinking},
23
+ {"name": "output_waste", "fn": detect_output_waste},
24
+ {"name": "cache_instability", "fn": detect_cache_instability},
25
+ ]
26
+
27
+ _TRIAGE_MIN_TOKENS = 5000
28
+
29
+
30
+ def run_all_detectors(session_data):
31
+ """Run all session and config detectors. Returns sorted findings list."""
32
+ findings = []
33
+ for d in ALL_DETECTORS:
34
+ try:
35
+ results = d["fn"](session_data)
36
+ for r in (results or []):
37
+ if r.get("always_show") or r.get("confidence", 0) > 0.3:
38
+ findings.append(r)
39
+ except Exception as e:
40
+ import sys
41
+ print(f"[token-optimizer] detector {d['name']} failed: {type(e).__name__}: {e}", file=sys.stderr)
42
+ continue
43
+ findings.sort(key=lambda f: f.get("confidence", 0), reverse=True)
44
+ # Deduplicate config-check findings (always_show=True) only. Session-data
45
+ # detectors may legitimately emit multiple distinct findings with one name.
46
+ seen_config = set()
47
+ deduped = []
48
+ for f in findings:
49
+ if f.get("always_show"):
50
+ name = f.get("name")
51
+ if name not in seen_config:
52
+ seen_config.add(name)
53
+ deduped.append(f)
54
+ else:
55
+ deduped.append(f)
56
+ return deduped
57
+
58
+
59
+ def triage(findings):
60
+ """Filter findings to actionable ones. Config checks (always_show) bypass
61
+ the token floor since they have no measured per-session saving."""
62
+ return [
63
+ f for f in findings
64
+ if f.get("always_show") or f.get("savings_tokens", 0) > _TRIAGE_MIN_TOKENS
65
+ ]
@@ -0,0 +1,76 @@
1
+ """Detector: respondToBashCommands settings check.
2
+
3
+ When respondToBashCommands is not set to false in ~/.claude/settings.json,
4
+ Claude Code generates a model reply after every /slash-command and !bash output
5
+ (added as the default in v2.1.186), spending output tokens on unrequested replies.
6
+
7
+ This detector reads settings.json directly -- no session turn parsing required.
8
+ Settings are cached per resolved path so batch runs do not re-read the file per
9
+ session. Credit: detection idea + tests contributed by @danikdanik (PR #74).
10
+ """
11
+
12
+ from runtime_env import detect_runtime
13
+
14
+ import functools
15
+ import json
16
+ import sys
17
+ from pathlib import Path
18
+
19
+ try:
20
+ from runtime_env import claude_home as _get_claude_home
21
+ except ImportError:
22
+ _get_claude_home = None
23
+
24
+
25
+ @functools.lru_cache(maxsize=8)
26
+ def _load_settings(settings_path):
27
+ """Read and parse settings.json. Cached so batch runs hit the file once."""
28
+ if not settings_path.exists():
29
+ return {}
30
+ try:
31
+ parsed = json.loads(settings_path.read_text(encoding="utf-8"))
32
+ return parsed if isinstance(parsed, dict) else {}
33
+ except PermissionError as e:
34
+ print(
35
+ f"[token-optimizer] respond_to_bash: cannot read {settings_path}: {e}",
36
+ file=sys.stderr,
37
+ )
38
+ return None # None signals "unknown" -- caller must not fire
39
+ except (json.JSONDecodeError, UnicodeDecodeError):
40
+ return {} # treat as empty settings -- finding fires
41
+
42
+
43
+ def detect_respond_to_bash(_session_data):
44
+ """Return a finding if respondToBashCommands is not explicitly false."""
45
+ if detect_runtime() != "claude":
46
+ return []
47
+ if _get_claude_home is not None:
48
+ settings_path = _get_claude_home() / "settings.json"
49
+ else:
50
+ settings_path = Path.home() / ".claude" / "settings.json"
51
+
52
+ settings = _load_settings(settings_path)
53
+ if settings is None: # PermissionError -- cannot determine setting
54
+ return []
55
+
56
+ if settings.get("respondToBashCommands") is False:
57
+ return []
58
+
59
+ return [{
60
+ "name": "respond_to_bash_commands",
61
+ "confidence": 0.9,
62
+ "always_show": True,
63
+ # Config nudge, not a measured per-session saving. Keep the key present
64
+ # so the display layer (which reads f["savings_tokens"]) never KeyErrors.
65
+ "savings_tokens": 0,
66
+ "evidence": (
67
+ "respondToBashCommands is not disabled in settings.json. "
68
+ "Since v2.1.186, Claude Code generates a model reply after every "
69
+ "/command and !bash output by default, spending output tokens on "
70
+ "unrequested replies."
71
+ ),
72
+ "suggestion": (
73
+ f'Set "respondToBashCommands": false in {settings_path} '
74
+ "to stop Claude from generating unsolicited replies to command outputs."
75
+ ),
76
+ }]
@@ -0,0 +1,83 @@
1
+ """Retry churn detector: same tool+input repeated 3+ times with errors."""
2
+
3
+ import json
4
+
5
+
6
+ def detect_retry_churn(session_data):
7
+ """Detect repeated tool calls that keep failing.
8
+
9
+ Scans JSONL for tool_use blocks where the same (tool, input_hash) appears
10
+ 3+ times, indicating the model is retrying a failing approach.
11
+ """
12
+ jsonl_path = session_data.get("jsonl_path")
13
+ if not jsonl_path:
14
+ return []
15
+
16
+ # Track (tool_name, input_prefix) -> count of error-preceded repeats
17
+ tool_attempts = {}
18
+ last_tool_key = None
19
+ last_had_error = False
20
+
21
+ try:
22
+ with open(jsonl_path, "r", encoding="utf-8", errors="replace") as f:
23
+ for line in f:
24
+ try:
25
+ record = json.loads(line)
26
+ except json.JSONDecodeError:
27
+ continue
28
+
29
+ rec_type = record.get("type")
30
+
31
+ # Check tool results for errors
32
+ if rec_type == "tool_result":
33
+ content = record.get("content", "")
34
+ text = content if isinstance(content, str) else str(content)[:500]
35
+ if "error" in text.lower() or "failed" in text.lower():
36
+ last_had_error = True
37
+ continue
38
+
39
+ if rec_type != "assistant":
40
+ continue
41
+
42
+ msg = record.get("message", {})
43
+ content = msg.get("content", [])
44
+ if not isinstance(content, list):
45
+ continue
46
+
47
+ for block in content:
48
+ if not isinstance(block, dict) or block.get("type") != "tool_use":
49
+ continue
50
+ tool_name = block.get("name", "")
51
+ inp = block.get("input", {})
52
+ # Hash first 200 chars of input for grouping
53
+ inp_key = str(inp)[:200]
54
+ key = (tool_name, inp_key)
55
+
56
+ if key == last_tool_key and last_had_error:
57
+ tool_attempts[key] = tool_attempts.get(key, 1) + 1
58
+ elif key not in tool_attempts:
59
+ tool_attempts[key] = 1
60
+
61
+ last_tool_key = key
62
+ last_had_error = False
63
+
64
+ except (OSError, PermissionError):
65
+ return []
66
+
67
+ findings = []
68
+ for (tool_name, _), count in tool_attempts.items():
69
+ if count >= 3:
70
+ est_tokens = count * 3000 # ~3K tokens per retry attempt
71
+ findings.append({
72
+ "name": "retry_churn",
73
+ "confidence": 0.8,
74
+ "evidence": f"{tool_name} retried {count} times with errors",
75
+ "savings_tokens": est_tokens,
76
+ "suggestion": (
77
+ f"Stop and diagnose after 2 failures instead of retrying. "
78
+ f"{count} retries of {tool_name} wasted ~{est_tokens:,} tokens."
79
+ ),
80
+ "occurrence_count": count,
81
+ })
82
+
83
+ return findings
@@ -0,0 +1,62 @@
1
+ """Tool cascade detector: 3+ consecutive tool errors forming an error chain."""
2
+
3
+ import json
4
+
5
+
6
+ def detect_tool_cascade(session_data):
7
+ """Detect chains of consecutive tool errors.
8
+
9
+ Scans JSONL for sequences where 4+ tool results are errors in a row,
10
+ indicating an error propagation cascade.
11
+ """
12
+ jsonl_path = session_data.get("jsonl_path")
13
+ if not jsonl_path:
14
+ return []
15
+
16
+ consecutive_errors = 0
17
+ streaks = []
18
+
19
+ try:
20
+ with open(jsonl_path, "r", encoding="utf-8", errors="replace") as f:
21
+ for line in f:
22
+ try:
23
+ record = json.loads(line)
24
+ except json.JSONDecodeError:
25
+ continue
26
+
27
+ if record.get("type") != "tool_result":
28
+ continue
29
+
30
+ content = record.get("content", "")
31
+ text = content if isinstance(content, str) else str(content)[:500]
32
+ is_error = record.get("is_error", False) or "error" in text.lower()
33
+
34
+ if is_error:
35
+ consecutive_errors += 1
36
+ else:
37
+ if consecutive_errors >= 4:
38
+ streaks.append(consecutive_errors)
39
+ consecutive_errors = 0
40
+
41
+ except (OSError, PermissionError):
42
+ return []
43
+
44
+ if consecutive_errors >= 4:
45
+ streaks.append(consecutive_errors)
46
+
47
+ findings = []
48
+ for streak_len in streaks:
49
+ est_tokens = streak_len * 2500
50
+ findings.append({
51
+ "name": "tool_cascade",
52
+ "confidence": 0.7,
53
+ "evidence": f"{streak_len} consecutive tool errors in a row",
54
+ "savings_tokens": est_tokens,
55
+ "suggestion": (
56
+ f"A cascade of {streak_len} tool errors burned ~{est_tokens:,} tokens. "
57
+ "Break error chains early: diagnose the root cause after 2 failures."
58
+ ),
59
+ "occurrence_count": len(streaks),
60
+ })
61
+
62
+ return findings
@@ -0,0 +1,75 @@
1
+ """Wasteful thinking detector: extended thinking tokens disproportionate to output.
2
+
3
+ Claude Code only (extended thinking is CC-specific).
4
+ """
5
+
6
+ import json
7
+
8
+
9
+ def detect_wasteful_thinking(session_data):
10
+ """Detect turns where thinking tokens are disproportionately high vs output.
11
+
12
+ Flags when: thinking tokens > 4x output tokens across 4+ turns.
13
+ Indicates overthinking on simple tasks.
14
+ """
15
+ jsonl_path = session_data.get("jsonl_path")
16
+ if not jsonl_path:
17
+ return []
18
+
19
+ wasteful_turns = 0
20
+ total_wasted = 0
21
+
22
+ try:
23
+ with open(jsonl_path, "r", encoding="utf-8", errors="replace") as f:
24
+ for line in f:
25
+ try:
26
+ record = json.loads(line)
27
+ except json.JSONDecodeError:
28
+ continue
29
+
30
+ if record.get("type") != "assistant":
31
+ continue
32
+
33
+ msg = record.get("message", {})
34
+ usage = msg.get("usage", {})
35
+ if not usage:
36
+ continue
37
+
38
+ # Extract thinking tokens (extended thinking / reasoning)
39
+ thinking = (
40
+ usage.get("thinking_tokens", 0)
41
+ or usage.get("internal_reasoning_tokens", 0)
42
+ or 0
43
+ )
44
+ output_tokens = usage.get("output_tokens", 0)
45
+
46
+ if thinking == 0 or output_tokens == 0:
47
+ continue
48
+
49
+ # Check if thinking is disproportionate
50
+ if thinking <= 4 * output_tokens:
51
+ continue
52
+
53
+ wasteful_turns += 1
54
+ total_wasted += thinking - output_tokens # excess thinking
55
+
56
+ except (OSError, PermissionError):
57
+ return []
58
+
59
+ if wasteful_turns >= 4:
60
+ return [{
61
+ "name": "wasteful_thinking",
62
+ "confidence": 0.7,
63
+ "evidence": (
64
+ f"{wasteful_turns} turns with thinking >4x output, "
65
+ f"~{total_wasted:,} excess thinking tokens"
66
+ ),
67
+ "savings_tokens": total_wasted,
68
+ "suggestion": (
69
+ f"{wasteful_turns} turns used extended thinking heavily for small output. "
70
+ "For simple changes, disable extended thinking or use a lighter model."
71
+ ),
72
+ "occurrence_count": wasteful_turns,
73
+ }]
74
+
75
+ return []