@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,110 @@
1
+ """Recognize outputs whose contract is to return a previously stored original.
2
+
3
+ Identity is narrow: ordinary search/retrieval tools still use compression.
4
+ This is an output-fidelity rule, not an authorization or security boundary.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import re
9
+ import shlex
10
+ from pathlib import Path
11
+
12
+ _RECOVERY_TOOLS = frozenset({'headroom_retrieve', 'caveman_retrieve'})
13
+ # Shell tools whose `command` can be our own `measure.py expand` (the archive matcher
14
+ # covers both; PowerShell is the Windows-native one).
15
+ _SHELL_TOOLS = frozenset({'Bash', 'PowerShell'})
16
+ _QUOTE_OR_EXPANSION = re.compile(r"""['"$`\\]""")
17
+ # Every interpreter name a printed hint may use (python3 on macOS/Linux, python on
18
+ # Windows, py for the Windows launcher) is accepted on every OS: a transcript can
19
+ # be read on a different machine from the one that printed it.
20
+ _INTERPRETERS = ('python3', 'python', 'py')
21
+ _PYTHON = re.compile(r'(?:python(?:3(?:\.\d+)?)?|py)(?:\.exe)?\Z', re.IGNORECASE)
22
+
23
+
24
+ def is_recovery_tool(tool_name: str) -> bool:
25
+ """Match a known bare identity or the tool segment of an MCP identity."""
26
+ if not isinstance(tool_name, str):
27
+ return False
28
+ if tool_name.startswith('mcp__'):
29
+ parts = tool_name.split('__')
30
+ if len(parts) != 3 or not parts[1]:
31
+ return False
32
+ tool_name = parts[2]
33
+ return tool_name in _RECOVERY_TOOLS
34
+
35
+
36
+ # An id never starts with a dash, so --list and --search keep the normal pipeline.
37
+ # One optional trailing ']' is tolerated: pointers shipped before the bracket
38
+ # moved to its own line ended "expand <id>]", and those stale hints are still in
39
+ # live transcripts — a Bash call copied from one is a recovery attempt (whose
40
+ # failed output must never be archived), not new tool output.
41
+ _HINT_TAIL = re.compile(
42
+ r'[a-zA-Z0-9_][a-zA-Z0-9_-]*(?: --session [a-zA-Z0-9_][a-zA-Z0-9_-]*)?\]?\Z')
43
+
44
+
45
+ def _is_printed_hint(command: str) -> bool:
46
+ """The command exactly as Token Optimizer prints it, on any OS.
47
+
48
+ shlex reads POSIX shell: a Windows path loses its backslashes and a path
49
+ with a space splits, so the printed hint is matched as text first. The
50
+ older unquoted form is kept because archived pointers in a live transcript
51
+ still carry it. The tail pattern admits no shell operator.
52
+ """
53
+ try:
54
+ from refetch_fingerprint import measure_py_path, shell_path
55
+ raw = measure_py_path()
56
+ except Exception:
57
+ return False
58
+ text = command.strip()
59
+ fwd = raw.replace('\\', '/')
60
+ shown_forms = {shell_path(raw), raw, fwd}
61
+ # Plainly quoted forms: single quotes (what a Windows install printed before
62
+ # cmd.exe-safe double quotes) and double quotes. A path that itself holds a
63
+ # quote or a shell-expanding character has no plain quoted form, so only the
64
+ # printer's own escaped form above can match it.
65
+ if not _QUOTE_OR_EXPANSION.search(fwd):
66
+ shown_forms.update((f"'{raw}'", f"'{fwd}'", f'"{fwd}"'))
67
+ for interp in _INTERPRETERS:
68
+ for shown in shown_forms:
69
+ prefix = f'{interp} {shown} expand '
70
+ if text.startswith(prefix) and _HINT_TAIL.match(text[len(prefix):]):
71
+ return True
72
+ return False
73
+
74
+
75
+ def is_expand_command(command: str) -> bool:
76
+ """Only a simple invocation of this installation's measure.py expand.
77
+
78
+ Shell operators are not interpreted. A compound command may also contain
79
+ ordinary output, so it must keep the normal pipeline rather than granting
80
+ the whole command a recovery exemption.
81
+ """
82
+ if not isinstance(command, str) or len(command) > 16_384:
83
+ return False
84
+ if _is_printed_hint(command):
85
+ return True
86
+ try:
87
+ tokens = shlex.split(command)
88
+ if len(tokens) not in (4, 6) or tokens[2] != 'expand':
89
+ return False
90
+ if not _PYTHON.fullmatch(Path(tokens[0]).name):
91
+ return False
92
+ # Tolerate one trailing ']' — the stale pointer format ended that way.
93
+ key = tokens[3][:-1] if tokens[3].endswith(']') else tokens[3]
94
+ if key.startswith('-') or not re.fullmatch(r'[a-zA-Z0-9_-]+', key):
95
+ return False
96
+ if len(tokens) == 6:
97
+ sid = tokens[5][:-1] if tokens[5].endswith(']') else tokens[5]
98
+ if tokens[4] != '--session' or not re.fullmatch(r'[a-zA-Z0-9_-]+', sid):
99
+ return False
100
+ expected = Path(__file__).resolve().parent / 'measure.py'
101
+ return Path(tokens[1]).is_absolute() and Path(tokens[1]).resolve() == expected
102
+ except (ValueError, OSError, RuntimeError):
103
+ return False
104
+
105
+
106
+ def is_recovery_output(tool_name: str, tool_input) -> bool:
107
+ if is_recovery_tool(tool_name):
108
+ return True
109
+ return (tool_name in _SHELL_TOOLS and isinstance(tool_input, dict)
110
+ and is_expand_command(tool_input.get('command', '')))
@@ -0,0 +1,236 @@
1
+ #!/usr/bin/env python3
2
+ """Shared re-fetch fingerprint for Token Optimizer (self-healing).
3
+
4
+ SINGLE SOURCE OF TRUTH for the archive de-duplication fingerprint. Imported by
5
+ archive_result.py (writes the fingerprint into the archive manifest at
6
+ PostToolUse) and refetch_guard.py (recomputes it at PreToolUse to detect an
7
+ identical re-fetch). Keeping the writer and reader on one function prevents the
8
+ two from drifting apart — the class of gap that caused a regression.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import hashlib
14
+ import json
15
+ import os
16
+ import re
17
+ from pathlib import Path
18
+
19
+ # SINGLE SOURCE OF TRUTH for the manifest field name the writer stores and the
20
+ # guard matches on. Referencing this constant from both sides means a rename is a
21
+ # one-line change that can't silently break the match (the exact drift mode:
22
+ # a renamed field makes `entry.get("args_hash")` return None and the guard stops
23
+ # denying with zero error).
24
+ ARGS_HASH_KEY = "args_hash"
25
+
26
+
27
+ # Tools that OBSERVE live state (a browser page, a screen). Identical arguments
28
+ # do not mean an identical result: a screenshot or page read after a click is
29
+ # new data, so the re-fetch guard must never redirect these to an old archive.
30
+ # Matched with fnmatch against the full tool name; fnmatch is case-sensitive on
31
+ # POSIX, so names are lowercased first.
32
+ # Hosts spell the same server differently (mcp__claude-in-chrome__,
33
+ # mcp__Claude_in_Chrome__, mcp__plugin_claude-in-chrome_claude-in-chrome__), and
34
+ # some servers carry the keyword in the tool name instead (mcp__my-tools__
35
+ # browser_click), so match on either segment. Over-matching only means the
36
+ # guard never blocks that tool, which is the safe direction: the worst a broad
37
+ # substring match does is leave a tool un-denied, never deny a legit tool.
38
+ LIVE_STATE_TOOL_PATTERNS: tuple[str, ...] = (
39
+ # Keyword in the SERVER segment: mcp__browser__click.
40
+ "mcp__*chrome*__*",
41
+ "mcp__*playwright*__*",
42
+ "mcp__*puppeteer*__*",
43
+ "mcp__*browser*__*",
44
+ "mcp__*browse*__*",
45
+ "mcp__*chromium*__*",
46
+ "mcp__*devtools*__*",
47
+ "mcp__*computer?use*__*",
48
+ "mcp__*computeruse*__*",
49
+ # Keyword in the TOOL segment (after the last __): a server that groups
50
+ # many tools names its browser tools by prefix — mcp__my-tools__browser_click.
51
+ "mcp__*__*chrome*",
52
+ "mcp__*__*playwright*",
53
+ "mcp__*__*puppeteer*",
54
+ "mcp__*__*browser*",
55
+ "mcp__*__*browse*",
56
+ "mcp__*__*chromium*",
57
+ "mcp__*__*devtools*",
58
+ "mcp__*__*computer?use*",
59
+ "mcp__*__*computeruse*",
60
+ # Observer verbs that live in the tool segment on a generic server:
61
+ # mcp__x__take_screenshot, mcp__x__page_snapshot, mcp__x__get_page_state.
62
+ "mcp__*__*screenshot*",
63
+ "mcp__*__*snapshot*",
64
+ "mcp__*__*page_state*",
65
+ )
66
+
67
+ # Opt-in allowlist for servers whose live-state tools match no keyword:
68
+ # TOKEN_OPTIMIZER_LIVE_STATE_TOOLS="mcp__acme__screen*,mcp__acme__scrape_*".
69
+ # Comma-separated fnmatch patterns, matched against the full (lowercased)
70
+ # tool name. A match has THREE effects, all in the safe direction: the
71
+ # re-fetch guard never denies the tool, the archive writer stores
72
+ # args_hash=None (the result is never fingerprinted), and the archive footer
73
+ # tells the model to call the tool again for current state. A broad glob like
74
+ # mcp__* therefore disables the whole re-fetch loop — strictly stronger than
75
+ # TOKEN_OPTIMIZER_REFETCH_GUARD_WINDOW_SECONDS=0, which only lifts the deny.
76
+ _LIVE_STATE_TOOLS_ENV = "TOKEN_OPTIMIZER_LIVE_STATE_TOOLS"
77
+
78
+ # A pathological allowlist value must not multiply per-call match latency:
79
+ # at most this many comma-separated patterns are honoured.
80
+ _LIVE_STATE_TOOLS_MAX_PATTERNS = 64
81
+
82
+ # Parsed once per process: hooks spawn a fresh interpreter per call, but
83
+ # within one process (the archive writer, in-process tests) a repeated
84
+ # classification must not re-split the value or re-read settings.json.
85
+ # The sentinel marks "not yet read"; a failed read is NOT cached so a
86
+ # transient settings error does not stick.
87
+ _LIVE_STATE_PATTERNS_UNSET = object()
88
+ _LIVE_STATE_PATTERNS_CACHE: tuple[str, ...] | object = _LIVE_STATE_PATTERNS_UNSET
89
+
90
+ # The guard exists to break an immediate loop (the model re-issuing the call it
91
+ # just got a pointer for). Past this window an identical call is far more likely
92
+ # a deliberate re-check of live data (an inbox, a chat, a calendar), and serving
93
+ # the old archive would hand the model stale data as if it were current.
94
+ REFETCH_GUARD_WINDOW_SECONDS = 300
95
+
96
+
97
+ def _env_live_state_patterns() -> tuple[str, ...]:
98
+ """Comma-separated fnmatch patterns from TOKEN_OPTIMIZER_LIVE_STATE_TOOLS.
99
+
100
+ Read the same way the sibling TOKEN_OPTIMIZER_ARCHIVE_EXEMPT_TOOLS knob is
101
+ read (archive_result.py): process environment first, then the env block of
102
+ the user's global settings.json, so hosts that do not inject settings env
103
+ into hook subprocesses still honour it.
104
+
105
+ Parsed once per process and capped: hooks spawn a fresh interpreter per
106
+ call, but within one process (the archive writer, an in-process test, the
107
+ delegate seam) a repeated call must not re-split the value, and a
108
+ pathological 20k-pattern value must not multiply match latency.
109
+
110
+ Fail-open on bad input: a malformed value or a broken settings file yields
111
+ no extra patterns rather than breaking classification. A failed read is
112
+ NOT cached, so a transient settings read error does not stick.
113
+ """
114
+ global _LIVE_STATE_PATTERNS_CACHE
115
+ if _LIVE_STATE_PATTERNS_CACHE is not _LIVE_STATE_PATTERNS_UNSET:
116
+ return _LIVE_STATE_PATTERNS_CACHE
117
+ try:
118
+ raw = os.environ.get(_LIVE_STATE_TOOLS_ENV, "").strip()
119
+ if not raw:
120
+ # Lazy import: keeps this module dependency-free for readers that
121
+ # only need tool_fingerprint, and any failure stays inside the
122
+ # fail-open except.
123
+ from runtime_env import settings_env_value
124
+
125
+ raw = settings_env_value(_LIVE_STATE_TOOLS_ENV)
126
+ parsed = tuple(
127
+ p.strip().lower() for p in raw.split(",") if p.strip()
128
+ )[:_LIVE_STATE_TOOLS_MAX_PATTERNS]
129
+ except Exception:
130
+ return ()
131
+ _LIVE_STATE_PATTERNS_CACHE = parsed
132
+ return parsed
133
+
134
+
135
+ def is_live_state_tool(tool_name: str) -> bool:
136
+ """True for tools whose result depends on live external state. Never raises."""
137
+ try:
138
+ import fnmatch
139
+ name = (tool_name or "").lower()
140
+ return any(
141
+ fnmatch.fnmatch(name, pat)
142
+ for pat in LIVE_STATE_TOOL_PATTERNS + _env_live_state_patterns()
143
+ )
144
+ except Exception:
145
+ return False
146
+
147
+
148
+ def tool_fingerprint(tool_name: str, tool_input) -> str:
149
+ """Stable 16-hex fingerprint of an MCP tool call (name + normalized args).
150
+
151
+ Two calls to the same tool with identical arguments produce the same
152
+ fingerprint, so an exact re-fetch is detectable. Dict-key-order insensitive;
153
+ never raises (falls back to repr for exotic, non-JSON-serializable inputs).
154
+ """
155
+ try:
156
+ args = json.dumps(tool_input, sort_keys=True, ensure_ascii=False, default=str)
157
+ except Exception:
158
+ args = repr(tool_input)
159
+ raw = f"{tool_name}\x00{args}".encode("utf-8", errors="replace")
160
+ return hashlib.sha256(raw).hexdigest()[:16]
161
+
162
+
163
+ def measure_py_path() -> str:
164
+ """Absolute path to measure.py (this module ships in the same scripts dir).
165
+
166
+ Shared by the archive footer and the guard's deny reason so the `expand`
167
+ command they print can never diverge. Correct at any install layout because
168
+ it resolves from this file's own location.
169
+ """
170
+ return str(Path(__file__).resolve().parent / "measure.py")
171
+
172
+
173
+ def expand_command(key: str) -> str:
174
+ """The exact Bash command that retrieves an archived result — one source of
175
+ truth for both the archive footer and the guard's deny reason."""
176
+ return f"{hint_python()} {shell_path(measure_py_path())} expand {key}"
177
+
178
+
179
+ def _windows_hints() -> bool:
180
+ """True when printed commands must run in cmd.exe, PowerShell and Git Bash.
181
+
182
+ The one predicate every hint helper reads, so the Windows forms can be
183
+ exercised on any OS by patching it.
184
+ """
185
+ return os.name == "nt"
186
+
187
+
188
+ def hint_python() -> str:
189
+ """The interpreter name a printed command should use on this OS.
190
+
191
+ ``python.exe`` ships with python.org AND Microsoft Store installs; ``python3``
192
+ exists on Windows only as a Store alias. macOS and Linux keep ``python3``
193
+ (``python`` is Python 2 or absent on many of them).
194
+ """
195
+ return "python" if _windows_hints() else "python3"
196
+
197
+
198
+ _SHELL_SAFE_PATH = re.compile(r"[A-Za-z0-9_./:@%+=,-]+\Z")
199
+ # Inside double quotes these still expand: `$`/backtick in Bash and PowerShell,
200
+ # `%` in cmd.exe. A Windows path holding one cannot be double-quoted safely.
201
+ _WINDOWS_DOUBLE_QUOTE_UNSAFE = re.compile(r"[$`%]")
202
+
203
+
204
+ def shell_path(path: str) -> str:
205
+ """A path the model or a user can paste unchanged into Bash, Git Bash,
206
+ PowerShell or cmd.exe.
207
+
208
+ On Windows backslashes become forward slashes (Python opens C:/x, and an
209
+ unquoted backslash is an escape in Bash) and a path that needs quoting is
210
+ DOUBLE-quoted: cmd.exe does not treat a single quote as a quote at all, so
211
+ `'C:/Users/First Last/x.py'` splits at the space and reaches Python with the
212
+ quote characters in it, while double quotes are read as one argument by
213
+ cmd.exe, PowerShell and Bash alike. A Windows path with `$`, a backtick or
214
+ `%` (expanded even inside double quotes) falls back to single quotes, which
215
+ Bash and PowerShell read literally.
216
+
217
+ On macOS and Linux anything beyond plain path characters, a space above all,
218
+ is single-quoted. A path that needs no quoting is returned as is.
219
+ """
220
+ text = str(path)
221
+ if _windows_hints():
222
+ text = text.replace("\\", "/")
223
+ if _SHELL_SAFE_PATH.match(text) and "%" not in text:
224
+ return text
225
+ if not _WINDOWS_DOUBLE_QUOTE_UNSAFE.search(text):
226
+ return f'"{text}"'
227
+ if "'" not in text:
228
+ return f"'{text}'"
229
+ if _SHELL_SAFE_PATH.match(text):
230
+ return text
231
+ if "'" not in text:
232
+ return f"'{text}'"
233
+ # A single quote in the path: double quotes, with Bash's four specials escaped.
234
+ for ch in ("\\", '"', "$", "`"):
235
+ text = text.replace(ch, "\\" + ch)
236
+ return f'"{text}"'
@@ -0,0 +1,244 @@
1
+ #!/usr/bin/env python3
2
+ """Token Optimizer - PreToolUse re-fetch guard (standalone entry point).
3
+
4
+ Self-healing loop-breaker. When a large MCP result is archived,
5
+ its compressed replacement tells the model to `expand` the saved copy instead of
6
+ re-fetching. If the model re-issues the SAME MCP call anyway (identical tool +
7
+ arguments), this guard detects the duplicate against the session archive manifest
8
+ and DENIES the call, handing the model the exact `expand` command. That converts
9
+ an unbounded re-fetch loop (each iteration re-inflating context with a huge
10
+ result) into a single cheap, actionable redirect.
11
+
12
+ Standalone for minimal startup overhead (mirrors archive_result.py / read_cache.py).
13
+ Fail-open by construction: any error, missing input, or unreadable manifest ->
14
+ emit a neutral PreToolUse response and let the tool call proceed untouched. The
15
+ guard can only ever ADD a deny for a proven exact duplicate; it never blocks a
16
+ first-time or novel call.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import json
22
+ import os
23
+ import re
24
+ import sys
25
+ import time
26
+ from collections import deque
27
+ from pathlib import Path
28
+
29
+ _NEUTRAL = json.dumps({"hookSpecificOutput": {"hookEventName": "PreToolUse"}})
30
+
31
+ try:
32
+ from hook_io import read_stdin_hook_input
33
+ from plugin_env import resolve_snapshot_dir
34
+ from refetch_fingerprint import (
35
+ ARGS_HASH_KEY,
36
+ REFETCH_GUARD_WINDOW_SECONDS,
37
+ expand_command,
38
+ is_live_state_tool,
39
+ tool_fingerprint,
40
+ )
41
+ from recovery_output import is_recovery_tool
42
+ from session_store import _sanitize_session_id as sanitize_sid
43
+ except Exception:
44
+ # If our own modules can't load, never block a tool call.
45
+ print(_NEUTRAL)
46
+ sys.exit(0)
47
+
48
+ _STDIN_MAX_BYTES = 1_048_576 # 1MB: tool_input is small; cap defensively.
49
+ _MANIFEST_MAX_LINES = 5000 # keep the NEWEST N manifest entries (append-only file).
50
+ # archive_result.py's _ARCHIVE_MAX_SIZE caps a legitimate entry's response at
51
+ # 5MB; add generous headroom for the surrounding JSON/metadata so no real
52
+ # entry is ever truncated mid-parse, while still bounding this hot PreToolUse
53
+ # read against a pathological/corrupt file pulling unbounded bytes into memory.
54
+ _ENTRY_RENDER_MAX_BYTES = 8 * 1024 * 1024
55
+ _DEBUG = os.environ.get("TOKEN_OPTIMIZER_DEBUG", "").strip().lower() not in ("", "0", "false", "no")
56
+
57
+
58
+ def _debug(msg: str) -> None:
59
+ """Opt-in stderr diagnostic (TOKEN_OPTIMIZER_DEBUG=1) so a silent fail-open path
60
+ is observable during incident diagnosis without editing hooks.json. No-op otherwise."""
61
+ if _DEBUG:
62
+ print(f"[refetch_guard] {msg}", file=sys.stderr)
63
+
64
+
65
+ def _emit(permission_decision: str | None = None, reason: str | None = None) -> None:
66
+ payload: dict = {"hookSpecificOutput": {"hookEventName": "PreToolUse"}}
67
+ if permission_decision:
68
+ payload["hookSpecificOutput"]["permissionDecision"] = permission_decision
69
+ if reason:
70
+ payload["hookSpecificOutput"]["permissionDecisionReason"] = reason
71
+ print(json.dumps(payload))
72
+
73
+
74
+ def _read_manifest_tail(manifest: Path) -> list:
75
+ """Return up to the last _MANIFEST_MAX_LINES parsed manifest entries (newest last).
76
+
77
+ Opens with O_NOFOLLOW to match the writer's symlink hardening (the writer uses it
78
+ in _append_manifest_line; the reader must not be the weaker link). Streams via a
79
+ bounded deque so a huge manifest never loads fully into memory, and — because the
80
+ file is append-only — the tail is exactly the newest entries the guard needs.
81
+ Never raises.
82
+ """
83
+ flags = os.O_RDONLY
84
+ if hasattr(os, "O_NOFOLLOW"):
85
+ flags |= os.O_NOFOLLOW
86
+ fd = os.open(str(manifest), flags)
87
+ tail: deque = deque(maxlen=_MANIFEST_MAX_LINES)
88
+ with os.fdopen(fd, "r", encoding="utf-8") as handle:
89
+ for line in handle:
90
+ line = line.strip()
91
+ if line:
92
+ tail.append(line)
93
+ parsed = []
94
+ for line in tail:
95
+ try:
96
+ parsed.append(json.loads(line))
97
+ except Exception:
98
+ continue
99
+ return parsed
100
+
101
+
102
+ def _entry_is_renderable(archive_dir: Path, tool_use_id: str) -> bool:
103
+ """True when the archive entry file exists, is readable JSON, and has a non-empty
104
+ ``response`` field — i.e. ``expand`` can actually serve it. Never raises."""
105
+ try:
106
+ entry_path = archive_dir / f"{tool_use_id}.json"
107
+ if not entry_path.is_file() or entry_path.is_symlink():
108
+ return False
109
+ with entry_path.open("rb") as fh:
110
+ raw = fh.read(_ENTRY_RENDER_MAX_BYTES)
111
+ if not raw:
112
+ return False
113
+ payload = json.loads(raw)
114
+ return isinstance(payload.get("response"), str) and bool(payload["response"])
115
+ except Exception:
116
+ return False
117
+
118
+
119
+ def _within_window(timestamp, now: float) -> bool:
120
+ """True when an archive entry's ISO timestamp is inside the guard window.
121
+
122
+ An unparseable or missing timestamp counts as OUTSIDE the window: the guard
123
+ only ever denies on proof, so doubt means allow. Never raises.
124
+ """
125
+ try:
126
+ from datetime import datetime
127
+ ts = datetime.fromisoformat(str(timestamp)).timestamp()
128
+ except Exception:
129
+ return False
130
+ return 0 <= now - ts <= _guard_window_seconds()
131
+
132
+
133
+ def _guard_window_seconds() -> int:
134
+ raw = os.environ.get("TOKEN_OPTIMIZER_REFETCH_GUARD_WINDOW_SECONDS", "").strip()
135
+ try:
136
+ return max(0, int(raw)) if raw else REFETCH_GUARD_WINDOW_SECONDS
137
+ except ValueError:
138
+ return REFETCH_GUARD_WINDOW_SECONDS
139
+
140
+
141
+ def _lookup_archived(session_id: str, tool_name: str, fingerprint: str):
142
+ """Return (tool_use_id, tokens_est) for a prior identical (tool_name, fingerprint),
143
+ else (None, 0).
144
+
145
+ Scans only the current session's manifest (a match is inherently recent — manifests
146
+ are TTL-pruned at 48h), newest-first, so the most recent archive of an identical call
147
+ wins and the scan stops early. A manifest hit is only returned when the actual archive
148
+ entry file is renderable (exists, readable JSON, non-empty response); on a bad match
149
+ the scan continues to older entries. Never raises.
150
+ """
151
+ try:
152
+ # Gate on the RAW session id: sanitize() turns an empty/invalid id into a random
153
+ # `fallback-<uuid>` that can't match any archive dir, so there is nothing to look up.
154
+ if not session_id or not session_id.strip():
155
+ return None, 0
156
+ sid = sanitize_sid(session_id)
157
+ archive_dir = resolve_snapshot_dir() / "tool-archive" / sid
158
+ manifest = archive_dir / "manifest.jsonl"
159
+ if not manifest.is_file() or manifest.is_symlink():
160
+ return None, 0
161
+ now = time.time()
162
+ for entry in reversed(_read_manifest_tail(manifest)): # newest first
163
+ if entry.get("tool_name") == tool_name and entry.get(ARGS_HASH_KEY) == fingerprint:
164
+ # Newest match is too old: every older one is too, and an old
165
+ # identical call is a deliberate re-check of live data, not a loop.
166
+ if not _within_window(entry.get("timestamp"), now):
167
+ return None, 0
168
+ tool_use_id = entry.get("tool_use_id")
169
+ if tool_use_id and _entry_is_renderable(archive_dir, tool_use_id):
170
+ return tool_use_id, int(entry.get("tokens_est") or 0)
171
+ # Manifest entry exists but the archive file is not renderable —
172
+ # keep scanning older entries instead of giving up.
173
+ return None, 0
174
+ except Exception as exc:
175
+ _debug(f"manifest lookup failed ({type(exc).__name__}: {exc}); allowing call")
176
+ return None, 0
177
+
178
+
179
+ def _log_refetch_block(session_id: str, tool_name: str, archived_id: str, saved_tokens: int) -> None:
180
+ """Record a blocked re-fetch as a savings event — a denied duplicate is real tokens
181
+ saved (the model would have re-pulled the full result).
182
+
183
+ Lazy import + fail-open: the common allow path never pays for the SQLite dependency,
184
+ and a logging failure can never turn into a wedged tool call. (Headline-savings
185
+ categorization is deliberately left as a separate change to the compression-category
186
+ registry; this row is the persistent metric/audit trail of guard denies.)
187
+ """
188
+ if saved_tokens <= 0:
189
+ return
190
+ try:
191
+ from archive_result import _log_savings_event
192
+ _log_savings_event(
193
+ "tool_archive_refetch_block",
194
+ saved_tokens,
195
+ session_id=session_id or None,
196
+ detail=f"blocked re-fetch of {tool_name} (archived {archived_id})",
197
+ )
198
+ except Exception as exc:
199
+ _debug(f"deny logging failed ({type(exc).__name__}: {exc})")
200
+
201
+
202
+ def refetch_guard() -> None:
203
+ hook_input = read_stdin_hook_input(_STDIN_MAX_BYTES)
204
+ if not hook_input:
205
+ _emit()
206
+ return
207
+
208
+ tool_name = hook_input.get("tool_name", "") or ""
209
+ # Only MCP tools loop this way; native tools (Read/Bash/…) are out of scope.
210
+ # Live-state tools (browser, screen) return new data for the same arguments,
211
+ # so a repeat is never a re-fetch. Checked here too, not only at archive
212
+ # time, so manifests written by older versions cannot block them either.
213
+ if "__" not in tool_name or is_live_state_tool(tool_name) or is_recovery_tool(tool_name):
214
+ _emit()
215
+ return
216
+
217
+ fingerprint = tool_fingerprint(tool_name, hook_input.get("tool_input", {}))
218
+ session_id = hook_input.get("session_id", "") or ""
219
+ archived_id, saved_tokens = _lookup_archived(session_id, tool_name, fingerprint)
220
+
221
+ if not archived_id or not re.match(r"^[a-zA-Z0-9_-]+$", str(archived_id)):
222
+ _emit() # no prior identical call — allow.
223
+ return
224
+
225
+ _log_refetch_block(session_id, tool_name, archived_id, saved_tokens)
226
+ _debug(f"denied re-fetch of {tool_name}; redirecting to expand {archived_id}")
227
+ reason = (
228
+ f"Token Optimizer: this exact {tool_name} call already ran and its full result is "
229
+ f"archived on disk (id {archived_id}) — re-fetching would re-inflate context with data "
230
+ f"you already have. Do NOT call {tool_name} again. Read the saved result by running this "
231
+ f"in Bash:\n {expand_command(archived_id)}"
232
+ )
233
+ _emit(permission_decision="deny", reason=reason)
234
+
235
+
236
+ if __name__ == "__main__":
237
+ try:
238
+ refetch_guard()
239
+ except Exception:
240
+ # Absolute fail-open backstop: a broken guard must never wedge tool use.
241
+ try:
242
+ print(_NEUTRAL)
243
+ except Exception:
244
+ pass