@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,1923 @@
1
+ """Runtime home detection shared by Claude Code, Codex, Hermes, OpenCode, Copilot,
2
+ Google Antigravity, and Grok Build adapters.
3
+
4
+ This module keeps runtime integration deliberately simple:
5
+
6
+ - Claude Code stays the default runtime unless another runtime is clearly indicated.
7
+ - Codex activates when CODEX_HOME is set or TOKEN_OPTIMIZER_RUNTIME=codex.
8
+ - Hermes activates when HERMES_HOME is set or TOKEN_OPTIMIZER_RUNTIME=hermes.
9
+ - OpenCode activates when an OPENCODE_* env signal or an opencode ancestor process
10
+ is detected, or TOKEN_OPTIMIZER_RUNTIME=opencode. The ancestor scan reads full
11
+ command lines, so OpenCode launched through node/bun (its real launch shape) is
12
+ recognized, not only a bare ``opencode`` binary. OpenCode loads ~/.claude/skills
13
+ by default, so this skill can be invoked from inside OpenCode; detecting it keeps
14
+ the skill from scanning/mutating ~/.claude when the user is actually in OpenCode.
15
+ The ancestor signal is evaluated ahead of the Claude plugin-env
16
+ heuristic so a coexisting Claude install on the same host can't shadow it.
17
+ - Copilot activates when COPILOT_HOME or TOKEN_OPTIMIZER_COPILOT_HOME is set, a
18
+ `copilot` ancestor process is detected, or TOKEN_OPTIMIZER_RUNTIME=copilot.
19
+ The Copilot hook bridge always sets the explicit override; the other signals
20
+ are a safety net so the skill never scans/mutates ~/.claude while actually
21
+ running under GitHub Copilot. COPILOT_HOME is Copilot's OWN variable — TO
22
+ reads it but never asks users to set it; TOKEN_OPTIMIZER_COPILOT_HOME
23
+ is TO's own collision-free override.
24
+ - Cursor activates when TOKEN_OPTIMIZER_CURSOR_HOME is set, or when the
25
+ hook-spawned pair CURSOR_PROJECT_DIR + CURSOR_VERSION is present, or
26
+ TOKEN_OPTIMIZER_RUNTIME=cursor. Cursor has no documented CURSOR_HOME of its
27
+ own, so TO exposes only its namespaced TOKEN_OPTIMIZER_CURSOR_HOME override.
28
+ There is deliberately NO ancestor-process scan for Cursor: the CLI binary is
29
+ named `agent` (too generic to scan safely), so detection stays on env signals
30
+ the host exports into every hook subprocess. The cursor_hook_bridge always
31
+ sets the explicit override; the env pair is a weak safety net below the
32
+ CLAUDECODE tier so a Cursor launched from a CC Bash tool still resolves to
33
+ `cursor` only at the weak tier.
34
+ - Antigravity activates when TOKEN_OPTIMIZER_ANTIGRAVITY_HOME is set, an `agy`
35
+ ancestor process is detected, or TOKEN_OPTIMIZER_RUNTIME=antigravity. The
36
+ hook bridge always pins the explicit override (same safety-net pattern as
37
+ Copilot); TOKEN_OPTIMIZER_ANTIGRAVITY_HOME sits above the CLAUDECODE tier so a
38
+ genuine Antigravity session launched from a Claude Code Bash tool (which
39
+ inherits CLAUDECODE=1) still resolves to antigravity, and the `agy` ancestor
40
+ signal stays at the weak tier so it never shadows a coexisting Claude install.
41
+ Antigravity IS distinct from Gemini CLI (different binary, different hooks
42
+ format), so one home resolver covers only Antigravity, never Gemini CLI.
43
+ - Grok Build activates when GROK_HOME or TOKEN_OPTIMIZER_GROK_HOME is set, or
44
+ TOKEN_OPTIMIZER_RUNTIME=grok. GROK_HOME is Grok Build's OWN variable — TO reads
45
+ it but never asks users to set it; TOKEN_OPTIMIZER_GROK_HOME is TO's own
46
+ collision-free override.
47
+ - Cowork and Claude Code cloud (claude.ai/code, ``claude --cloud``) are NOT
48
+ separate runtimes: both run the same Claude Code engine in a VM, so
49
+ ``detect_runtime()`` still returns ``"claude"`` in either. ``remote_host()``
50
+ is a REFINEMENT signal exposed alongside it (mirroring how the runtime
51
+ lattice layers signals rather than adding runtimes) and resolves to
52
+ ``"cloud"``, ``"cowork"``, ``"remote"`` (hosted VM of unknown kind) or
53
+ ``""`` (local). ``is_claude_code_cloud()`` and ``is_cowork()`` are its two
54
+ booleans. Cloud needs positive evidence (``CLAUDE_CODE_REMOTE_ENVIRONMENT_TYPE
55
+ =cloud_*``, ``CLAUDE_CODE_REMOTE_SESSION_ID``, the cloud kit's runner, or the
56
+ ``TOKEN_OPTIMIZER_REMOTE_HOST`` pin); a bare ``CLAUDE_CODE_REMOTE=true`` is
57
+ "remote". ``CLAUDE_CODE_CONTAINER_ID`` and a ``/plugins/synced/`` plugin root
58
+ appear in the cloud VM too, so they mean Cowork only when no cloud evidence
59
+ is present. ``AI_AGENT`` is deliberately NOT a
60
+ signal: native Claude Code also sets ``AI_AGENT=claude-code_*_harness``, so
61
+ the harness marker is ambiguous and would false-positive on the local CLI.
62
+ Nothing about the existing ``detect_runtime()`` returns changes.
63
+ - Callers can keep legacy variable names while resolving to the correct home.
64
+
65
+ The goal is to let Token Optimizer share one Python core while platform
66
+ adapters grow feature-by-feature on top of it.
67
+ """
68
+
69
+ from __future__ import annotations
70
+
71
+ import functools
72
+ import hashlib
73
+ import json
74
+ import os
75
+ import re
76
+ import shlex
77
+ import sys
78
+ import time
79
+ from pathlib import Path
80
+
81
+ def shell_path(path) -> str:
82
+ """``path`` quoted so it pastes into Bash, Git Bash, PowerShell and cmd.exe.
83
+
84
+ One implementation (``refetch_fingerprint.shell_path``) serves every printed
85
+ command, so the hints cannot drift from what ``recovery_output`` recognises.
86
+ """
87
+ try:
88
+ from refetch_fingerprint import shell_path as _shell_path
89
+ except ImportError: # sibling module missing: the POSIX rules are still right
90
+ return shlex.quote(str(path))
91
+ return _shell_path(str(path))
92
+
93
+
94
+ def hint_python() -> str:
95
+ """Interpreter name for printed commands: ``python`` on Windows, ``python3`` elsewhere."""
96
+ try:
97
+ from refetch_fingerprint import hint_python as _hint_python
98
+ except ImportError:
99
+ return "python3"
100
+ return _hint_python()
101
+
102
+
103
+ def _windows_hints() -> bool:
104
+ try:
105
+ from refetch_fingerprint import _windows_hints as _wh
106
+ except ImportError:
107
+ return False
108
+ return _wh()
109
+
110
+
111
+ def measure_cli(*args: str) -> str:
112
+ """Pasteable command that runs the sibling ``measure.py`` from any directory.
113
+
114
+ The resolved, shell-quoted script path. A bare ``python3 measure.py`` only
115
+ works from inside the scripts directory, which is where nobody is. On Windows
116
+ the interpreter is ``python`` and the path uses forward slashes and double
117
+ quotes (see ``shell_path``): a backslash path in single quotes works in Git
118
+ Bash only, and ``python3`` exists there only as a Store alias.
119
+ """
120
+ parts = [hint_python(), shell_path(Path(__file__).resolve().parent / "measure.py")]
121
+ parts.extend(args)
122
+ return " ".join(parts)
123
+
124
+
125
+ def runtime_cli(runtime: str, *args: str) -> str:
126
+ """``measure_cli`` pinned to a runtime.
127
+
128
+ macOS/Linux: the ``TOKEN_OPTIMIZER_RUNTIME=NAME python3 ...`` prefix. That is
129
+ Bash syntax; cmd.exe and PowerShell reject it, so on Windows the same choice
130
+ is a leading ``--runtime NAME`` flag of measure.py (``consume_runtime_flag``).
131
+ """
132
+ script = shell_path(Path(__file__).resolve().parent / "measure.py")
133
+ if _windows_hints():
134
+ parts = [hint_python(), script, "--runtime", runtime]
135
+ else:
136
+ parts = [f"TOKEN_OPTIMIZER_RUNTIME={runtime}", hint_python(), script]
137
+ parts.extend(args)
138
+ return " ".join(parts)
139
+
140
+
141
+ _ENV_PREFIXED_BARE_HINT = re.compile(r"TOKEN_OPTIMIZER_RUNTIME=(\w+) python3 measure\.py")
142
+
143
+
144
+ def with_measure_cli(text: str) -> str:
145
+ """Swap the bare ``python3 measure.py`` prefix in a hint for ``measure_cli()``.
146
+
147
+ ``TOKEN_OPTIMIZER_RUNTIME=X python3 measure.py`` goes through ``runtime_cli``.
148
+ """
149
+ text = _ENV_PREFIXED_BARE_HINT.sub(lambda m: runtime_cli(m.group(1)), text)
150
+ return text.replace("python3 measure.py", measure_cli())
151
+
152
+
153
+ def consume_runtime_flag(argv: list, environ) -> list:
154
+ """Apply a LEADING ``--runtime NAME`` to ``environ`` and return argv without it.
155
+
156
+ The cross-shell spelling of ``TOKEN_OPTIMIZER_RUNTIME=NAME``. Only the first
157
+ argument after the script counts, so it can never swallow a subcommand's own
158
+ ``--runtime``. Runtime names are validated by ``detect_runtime`` as usual.
159
+ """
160
+ if len(argv) >= 3 and argv[1] == "--runtime" and argv[2] and not argv[2].startswith("-"):
161
+ environ["TOKEN_OPTIMIZER_RUNTIME"] = argv[2]
162
+ return [argv[0], *argv[3:]]
163
+ return list(argv)
164
+
165
+
166
+ _RUNTIME_OVERRIDE = "TOKEN_OPTIMIZER_RUNTIME"
167
+ _RUNTIME_CLAUDE = "claude"
168
+ _RUNTIME_CODEX = "codex"
169
+ _RUNTIME_HERMES = "hermes"
170
+ _RUNTIME_OPENCODE = "opencode"
171
+ _RUNTIME_COPILOT = "copilot"
172
+ _RUNTIME_CURSOR = "cursor"
173
+ _RUNTIME_ANTIGRAVITY = "antigravity"
174
+ _RUNTIME_GROK = "grok"
175
+ _RUNTIME_DEVIN = "devin"
176
+ _VALID_RUNTIMES = frozenset(
177
+ {
178
+ _RUNTIME_CLAUDE,
179
+ _RUNTIME_CODEX,
180
+ _RUNTIME_HERMES,
181
+ _RUNTIME_OPENCODE,
182
+ _RUNTIME_COPILOT,
183
+ _RUNTIME_CURSOR,
184
+ _RUNTIME_ANTIGRAVITY,
185
+ _RUNTIME_GROK,
186
+ _RUNTIME_DEVIN,
187
+ }
188
+ )
189
+ # Unrecognised TOKEN_OPTIMIZER_RUNTIME values already reported by this process.
190
+ _WARNED_BAD_OVERRIDES: set = set()
191
+
192
+
193
+ def _warn_bad_override(value: str) -> None:
194
+ """Say once per process that an override value was not honoured."""
195
+ if value in _WARNED_BAD_OVERRIDES:
196
+ return
197
+ _WARNED_BAD_OVERRIDES.add(value)
198
+ hint = ""
199
+ if value == "pi":
200
+ hint = (
201
+ " Pi is not a Python runtime: its extension is configured with "
202
+ "TOKEN_OPTIMIZER_PI_HOME."
203
+ )
204
+ # The value comes from the environment: cap what is echoed, and repr keeps
205
+ # control characters from turning the line into several.
206
+ shown = value if len(value) <= 40 else value[:40]
207
+ try:
208
+ sys.stderr.write(
209
+ f"[Token Optimizer] ignoring {_RUNTIME_OVERRIDE}={shown!r}: accepted values are "
210
+ f"{', '.join(sorted(_VALID_RUNTIMES))}; falling back to auto-detection.{hint}\n"
211
+ )
212
+ except Exception:
213
+ pass
214
+
215
+
216
+ _CLAUDE_PLUGIN_ENVS = ("CLAUDE_PLUGIN_ROOT", "CLAUDE_PLUGIN_DATA")
217
+ # Hosted-VM markers (Claude Code cloud and Claude Cowork). Both are Claude Code
218
+ # running in a VM, so these REFINE the claude runtime (via remote_host()) rather
219
+ # than name a new one.
220
+ # - CLAUDE_CODE_REMOTE=true: the ONLY DOCUMENTED cloud-vs-desktop signal
221
+ # (code.claude.com/docs/en/hooks.md: "$CLAUDE_CODE_REMOTE is set to 'true'
222
+ # in cloud, unset locally"; docs-grounding.md §3). On its own it says only
223
+ # "a hosted VM", so it resolves to "remote": neither Cowork nor cloud.
224
+ # - CLAUDE_CODE_CONTAINER_ID: set inside Cowork VMs AND the Claude Code cloud
225
+ # VM (live probe 2026-10-19), so it means Cowork only when no cloud
226
+ # evidence (session id, cloud environment type, kit) is present.
227
+ # - CLAUDE_PLUGIN_ROOT under /plugins/synced/: Cowork plugins arrive via the
228
+ # org admin console account-sync, landing under a synced-plugin path. The
229
+ # cloud VM has the same synced dir, so this is a Cowork hint only when no
230
+ # cloud evidence is present.
231
+ # - AI_AGENT is deliberately NOT consulted: native Claude Code (local CLI) also
232
+ # sets AI_AGENT=claude-code_<version>_harness, so the "_harness" marker is
233
+ # ambiguous between Cowork and desktop. Treating it as a Cowork signal caused
234
+ # is_cowork() false-positives on every native hook subprocess (which inherits
235
+ # AI_AGENT). See test_is_cowork_native_ai_agent_harness_is_not_cowork.
236
+ _COWORK_REMOTE_ENV = "CLAUDE_CODE_REMOTE"
237
+ _COWORK_CONTAINER_ENV = "CLAUDE_CODE_CONTAINER_ID"
238
+ _COWORK_SYNCED_PLUGIN_MARKER = "/plugins/synced/"
239
+ # Claude Code cloud (claude.ai/code web sessions, `claude --cloud`, routines).
240
+ # Live probes on 2026-10-19 (cse_01BTPiM55..., cse_01T2U8ZN..., cse_01Au8fmq...,
241
+ # cse_01DWjCoV...) showed the Anthropic-hosted VM exports CLAUDE_CODE_REMOTE=true,
242
+ # CLAUDE_CODE_REMOTE_SESSION_ID=cse_<id>, CLAUDE_CODE_REMOTE_ENVIRONMENT_TYPE=
243
+ # cloud_default AND CLAUDE_CODE_CONTAINER_ID, and carries an (empty, for now)
244
+ # ~/.claude/plugins/synced/<org>_<account>/ dir where account plugin sync will
245
+ # deliver plugins. So neither CLAUDE_CODE_CONTAINER_ID nor a /plugins/synced/
246
+ # plugin root is Cowork-only: checked before the cloud signals they labelled
247
+ # every cloud session Cowork. They now count as Cowork only after every cloud
248
+ # signal has been checked. The resolution order is:
249
+ # 1. TOKEN_OPTIMIZER_REMOTE_HOST=cloud|cowork|local (explicit pin, wins)
250
+ # 2. CLAUDE_CODE_REMOTE_ENVIRONMENT_TYPE: "cloud*" -> cloud, "*cowork*" ->
251
+ # cowork, any other value -> no signal (fall through)
252
+ # 3. TOKEN_OPTIMIZER_CLOUD_KIT_VERSION non-blank -> cloud (exported by
253
+ # the cloud kit's runner, only when CLAUDE_CODE_REMOTE=true)
254
+ # 4. CLAUDE_CODE_REMOTE_SESSION_ID non-blank -> cloud
255
+ # 5. synced plugin root (/plugins/synced/) -> cowork
256
+ # 6. CLAUDE_CODE_CONTAINER_ID non-blank -> cowork
257
+ # (5 and 6 are only reached with no cloud evidence above: the cloud VM
258
+ # carries both, but always with the session id and environment type)
259
+ # 7. CLAUDE_CODE_REMOTE truthy, nothing else -> "remote" (a hosted
260
+ # VM of unknown kind: no Cowork caveats, no cloud lean profile)
261
+ # 8. otherwise -> "" (local)
262
+ _CLOUD_SESSION_ID_ENV = "CLAUDE_CODE_REMOTE_SESSION_ID"
263
+ _CLOUD_KIT_ENV = "TOKEN_OPTIMIZER_CLOUD_KIT_VERSION"
264
+ _REMOTE_HOST_OVERRIDE_ENV = "TOKEN_OPTIMIZER_REMOTE_HOST"
265
+ _REMOTE_ENV_TYPE_ENV = "CLAUDE_CODE_REMOTE_ENVIRONMENT_TYPE"
266
+ REMOTE_HOST_CLOUD = "cloud"
267
+ REMOTE_HOST_COWORK = "cowork"
268
+ # A hosted VM that says only CLAUDE_CODE_REMOTE=true: remote, kind unknown.
269
+ REMOTE_HOST_UNKNOWN = "remote"
270
+ # Claude Code's own process-env signals. CLAUDECODE is inherited by every
271
+ # subprocess Claude Code spawns, so a genuine Codex/OpenCode/Copilot launched
272
+ # from a CC Bash tool inherits CLAUDECODE=1. This tier therefore sits BELOW the
273
+ # explicit CODEX_HOME/HERMES_HOME/COPILOT_HOME env checks (so a nested-Codex
274
+ # session with CODEX_HOME set, or a nested-Copilot session with COPILOT_HOME
275
+ # set, still resolves to its own runtime) but ABOVE the weak directory
276
+ # heuristics, so a host with CLAUDECODE=1 and a coexisting ~/.codex DIRECTORY
277
+ # resolves to claude, not codex. Copilot's explicit-env tier is
278
+ # _COPILOT_HOME_ENVS below, NOT the ancestor-process signal (which stays at the
279
+ # weak tier) -- a process scan cannot run ahead of CLAUDECODE without
280
+ # reintroducing the shadowing it was added to prevent.
281
+ _CLAUDE_CODE_ENVS = ("CLAUDECODE", "CLAUDE_CODE_ENTRYPOINT", "CLAUDE_CODE_SESSION_ID")
282
+ # Claude Code's official config-dir override. When set, Claude stores
283
+ # projects/, settings.json, etc. under this directory instead of ~/.claude.
284
+ _CLAUDE_CONFIG_DIR_ENV = "CLAUDE_CONFIG_DIR"
285
+ _CODEX_HOME_ENV = "CODEX_HOME"
286
+ _HERMES_HOME_ENV = "HERMES_HOME"
287
+ # COPILOT_HOME is GitHub Copilot CLI's OWN config variable (GitHub docs: it
288
+ # "replaces the entire ~/.copilot path", and Copilot's session-state/,
289
+ # session.db, events.jsonl all live inside it). Token Optimizer must NOT ask
290
+ # users to set it: a WSL /mnt value set for TO's benefit is also read by the
291
+ # native-Windows Copilot CLI and breaks its own session logging.
292
+ # So TO exposes its OWN namespaced override and only READS COPILOT_HOME as a
293
+ # back-compat location hint (with a guardrail warning for /mnt values).
294
+ _COPILOT_HOME_ENV = "COPILOT_HOME"
295
+ _TO_COPILOT_HOME_ENV = "TOKEN_OPTIMIZER_COPILOT_HOME"
296
+ # Cursor has no documented CURSOR_HOME of its own, so TO exposes only a
297
+ # namespaced override (never asks users to set a host var Cursor also reads).
298
+ _TO_CURSOR_HOME_ENV = "TOKEN_OPTIMIZER_CURSOR_HOME"
299
+ # The two env vars Cursor exports into every hook subprocess. Both must be
300
+ # present together to count (either alone is too weak). This is the hook-
301
+ # spawned-only weak signal; `agent` is too generic a binary name to scan.
302
+ _CURSOR_HOOK_ENVS = ("CURSOR_PROJECT_DIR", "CURSOR_VERSION")
303
+ # Copilot's explicit config-dir env vars. Like CODEX_HOME/HERMES_HOME these are
304
+ # the host's OWN variables, set by/for a genuine Copilot session. They sit ABOVE
305
+ # the CLAUDECODE tier so a Copilot session launched from a CC Bash tool (which
306
+ # inherits CLAUDECODE=1) still resolves to copilot, mirroring the Codex/Hermes
307
+ # guard. The ancestor-process signal (_copilot_signal's ps scan) stays at the
308
+ # weak tier below CLAUDECODE, since a process scan ahead of CLAUDECODE would
309
+ # re-introduce the OpenCode-shadowing problem for the copilot path too.
310
+ _COPILOT_HOME_ENVS = (_COPILOT_HOME_ENV, _TO_COPILOT_HOME_ENV)
311
+ # Google Antigravity CLI/app/IDE home override. Antigravity is a distinct
312
+ # product from Gemini CLI and ships its own `agy` binary; its data lives under
313
+ # ~/.gemini (antigravity-cli/, antigravity/, antigravity-ide/). This is TO's own
314
+ # namespaced override so the adapter never depends on a host-owned variable.
315
+ _TO_ANTIGRAVITY_HOME_ENV = "TOKEN_OPTIMIZER_ANTIGRAVITY_HOME"
316
+ _AGY_BASENAMES = frozenset({"agy", "agy.exe"})
317
+ # GROK_HOME is Grok Build's OWN config variable (docs.x.ai/build/settings/reference:
318
+ # it relocates the whole ~/.grok tree). Token Optimizer reads it but never asks
319
+ # users to set it; TO exposes its own namespaced override for the same reason as
320
+ # Copilot (a WSL /mnt value set for TO's benefit would also break Grok's own
321
+ # session logging on native Windows).
322
+ _GROK_HOME_ENV = "GROK_HOME"
323
+ _TO_GROK_HOME_ENV = "TOKEN_OPTIMIZER_GROK_HOME"
324
+ _GROK_HOME_ENVS = (_GROK_HOME_ENV, _TO_GROK_HOME_ENV)
325
+ # Windows profile names under /mnt/c/Users that are never a real user home.
326
+ _WINDOWS_NONUSER_PROFILES = frozenset(
327
+ {"public", "all users", "default", "default user", "windows", "wpsystem"}
328
+ )
329
+ # OpenCode launch/config env vars. Their presence in this process's environment
330
+ # is a strong signal we were spawned from within OpenCode. These are OpenCode's
331
+ # own documented variables (config/data/bin/client), not anything we set.
332
+ _OPENCODE_ENV_SIGNALS = (
333
+ "OPENCODE_BIN",
334
+ "OPENCODE_CONFIG_DIR",
335
+ "OPENCODE_DATA_DIR",
336
+ "OPENCODE_CONFIG",
337
+ "OPENCODE_CLIENT",
338
+ )
339
+ # Set to a truthy value to skip the (cheap, best-effort) process-tree scan used
340
+ # as a fallback OpenCode signal. Useful in tests/CI and locked-down sandboxes.
341
+ _PROC_SCAN_DISABLE_ENV = "TOKEN_OPTIMIZER_NO_PROC_SCAN"
342
+
343
+ # Warnings printed at most once per process. copilot_home()/_safe_home_from_env
344
+ # can be called several times in a single command (doctor, install, hook fire),
345
+ # and repeating the same warning reads as separate faults.
346
+ # Dedup by exact message text.
347
+ #
348
+ # The registry lives on ``sys`` — a guaranteed process-singleton — rather than a
349
+ # module global, because on Windows this module can be imported under two
350
+ # distinct identities (measure.py inserts scripts/ onto sys.path, and case- or
351
+ # separator-normalized path variants resolve to separate module objects). Two
352
+ # module objects mean two module-level sets, so a module global deduped the
353
+ # warning per-copy and it still printed twice. Anchoring the set on ``sys``
354
+ # makes every copy share one registry. (assafbem, native-Windows.)
355
+ _WARN_REGISTRY_ATTR = "_token_optimizer_warned_messages"
356
+
357
+
358
+ def _warned_registry() -> set:
359
+ """Return the process-singleton set of already-emitted warning messages.
360
+
361
+ Anchored on ``sys`` so every imported copy of this module (see the Windows
362
+ dual-identity note above) resolves to the same set. Also the reset/snapshot
363
+ seam tests use to isolate per-call dedup assertions.
364
+ """
365
+ registry = getattr(sys, _WARN_REGISTRY_ATTR, None)
366
+ if registry is None:
367
+ registry = set()
368
+ setattr(sys, _WARN_REGISTRY_ATTR, registry)
369
+ return registry
370
+
371
+
372
+ def __getattr__(name):
373
+ """Lazily expose ``_warned_messages`` as the process-singleton registry.
374
+
375
+ Callers/tests reference ``runtime_env._warned_messages`` to snapshot/reset
376
+ warning dedup. Resolving it through the module ``__getattr__`` (PEP 562)
377
+ returns the same set ``_warn_once`` mutates, while keeping import
378
+ side-effect-free: the ``sys`` registry is created on first warning or first
379
+ access, never merely by importing this module (strict POSIX invariance).
380
+ """
381
+ if name == "_warned_messages":
382
+ return _warned_registry()
383
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
384
+
385
+
386
+ def _warn_once(msg: str) -> None:
387
+ """Print ``msg`` to stderr the first time it is seen this process."""
388
+ registry = _warned_registry()
389
+ if msg in registry:
390
+ return
391
+ registry.add(msg)
392
+ print(msg, file=sys.stderr)
393
+
394
+
395
+ def _safe_home() -> Path:
396
+ """``Path.home()`` that never raises.
397
+
398
+ ``Path.home()`` raises RuntimeError when it cannot resolve a home directory
399
+ -- a Windows subprocess launched with no USERPROFILE, a stripped
400
+ container/CI env. A hook must DEGRADE, not crash, so fall back to the
401
+ platform home env vars and finally a temp dir. Real Claude Code sessions
402
+ always have a home; this only bites stripped envs, where any writable dir
403
+ keeps the hook alive instead of raising through claude_home()/runtime_home().
404
+ """
405
+ try:
406
+ return Path.home()
407
+ except (RuntimeError, OSError):
408
+ for key in ("USERPROFILE", "HOME"):
409
+ val = os.environ.get(key, "").strip()
410
+ if val:
411
+ return Path(val)
412
+ drive = os.environ.get("HOMEDRIVE", "").strip()
413
+ tail = os.environ.get("HOMEPATH", "").strip()
414
+ if drive and tail:
415
+ return Path(drive + tail)
416
+ return Path(os.environ.get("TEMP") or os.environ.get("TMP") or "/tmp")
417
+
418
+
419
+ def _home_root() -> Path:
420
+ """Return the resolved user home used for env-path confinement."""
421
+ return _safe_home().resolve(strict=False)
422
+
423
+
424
+ def _is_safe_home_dir(path: Path) -> bool:
425
+ """True when path is a non-symlink directory under the user's home."""
426
+ try:
427
+ if not path.is_absolute():
428
+ return False
429
+ resolved = path.resolve(strict=False)
430
+ home = _home_root()
431
+ if resolved == home or not resolved.is_relative_to(home):
432
+ return False
433
+ if path.exists():
434
+ return path.is_dir() and not path.is_symlink()
435
+ return False
436
+ except (OSError, ValueError):
437
+ return False
438
+
439
+
440
+ # Default-off explicit override: on containerized deploys (Docker/Umbrel)
441
+ # the runtime home may be a PARENT of $HOME (e.g. HERMES_HOME=/opt/data with
442
+ # HOME=/opt/data/home). This drops ONLY the under-$HOME containment policy;
443
+ # every other safety check (absolute, resolve, exists, is_dir, not symlink)
444
+ # is still enforced by _is_safe_home_dir_relaxed below.
445
+ _UNSAFE_RUNTIME_HOME_OVERRIDE_ENV = "TOKEN_OPTIMIZER_ALLOW_UNSAFE_RUNTIME_HOME"
446
+
447
+
448
+ def _truthy_env(env_var: str) -> bool:
449
+ """Parse a truthy env var (1/true/yes/on, case-insensitive). Mirrors the
450
+ _keepwarm_llm_ping_disabled() parser style in measure.py without importing
451
+ it (keeps runtime_env dependency-light)."""
452
+ val = os.environ.get(env_var)
453
+ return isinstance(val, str) and val.strip().lower() in ("1", "true", "yes", "on")
454
+
455
+
456
+ def _is_safe_home_dir_relaxed(path: Path) -> bool:
457
+ """Like _is_safe_home_dir but DROPS the under-$HOME containment check.
458
+
459
+ Keeps every other guard: absolute path, resolve(strict=False), must exist,
460
+ must be a real dir, must NOT be a symlink. Used only when the explicit
461
+ TOKEN_OPTIMIZER_ALLOW_UNSAFE_RUNTIME_HOME override is truthy, for
462
+ containerized deploys where the runtime home is a parent of $HOME.
463
+ """
464
+ try:
465
+ if not path.is_absolute():
466
+ return False
467
+ path.resolve(strict=False)
468
+ if path.exists():
469
+ return path.is_dir() and not path.is_symlink()
470
+ return False
471
+ except (OSError, ValueError):
472
+ return False
473
+
474
+
475
+ def _is_wsl_context() -> bool:
476
+ """True when this process is running inside Windows Subsystem for Linux.
477
+
478
+ Reads ``/proc/version`` and ``/proc/sys/kernel/osrelease`` and looks for
479
+ the ``microsoft`` / ``WSL`` markers the WSL kernel emits. Never raises.
480
+
481
+ This gates the WSL-root ``/mnt/`` opt-in so native-Linux
482
+ ``/mnt`` mounts stay on the strict safe-home path and behavior there is
483
+ byte-identical to before. Tests monkeypatch this function for
484
+ determinism on non-Linux hosts.
485
+ """
486
+ if not sys.platform.startswith("linux"):
487
+ return False
488
+ for probe in ("/proc/version", "/proc/sys/kernel/osrelease"):
489
+ try:
490
+ with open(probe, "r", encoding="utf-8", errors="replace") as fh:
491
+ text = fh.read()
492
+ except OSError:
493
+ continue
494
+ low = text.lower()
495
+ if "microsoft" in low or "wsl" in low:
496
+ return True
497
+ return False
498
+
499
+
500
+ def _wsl_mnt_safe_home(candidate: Path, *, mnt_root: Path | None = None) -> Path | None:
501
+ """Return ``candidate`` resolved if it passes the WSL ``/mnt/`` opt-in.
502
+
503
+ The opt-in: a runtime-home env var value that FAILS the
504
+ strict under-``$HOME`` guard is still accepted when ALL of:
505
+
506
+ (a) we are running inside WSL (gated on ``/proc`` markers —
507
+ native-Linux ``/mnt`` mounts stay on the strict path),
508
+ (b) the path is absolute (no relative traversal),
509
+ (c) the resolved path is under ``/mnt/`` (the WSL Windows-mount root;
510
+ ``/mnt/wsl/``, ``/mnt/c/``, ``/mnt/d/`` … — not arbitrary
511
+ filesystem locations),
512
+ (d) the path is not a symlink (no traversal tricks),
513
+ (e) the path exists and is a directory.
514
+
515
+ ``mnt_root`` is a FUNCTION PARAMETER (not an env var) so it can ONLY be
516
+ set by code calling this directly (tests pass a temp dir since macOS
517
+ can't create ``/mnt/c/...``). Production always uses the real ``/mnt`` —
518
+ there is no env var a user could set to widen the confinement.
519
+
520
+ Returns the resolved Path on success, ``None`` on any failure (caller
521
+ falls back to the strict path / default). Never raises.
522
+ """
523
+ if not _is_wsl_context():
524
+ return None
525
+ try:
526
+ if not candidate.is_absolute():
527
+ return None
528
+ resolved = candidate.resolve(strict=False)
529
+ root = Path(mnt_root) if mnt_root is not None else Path("/mnt")
530
+ mnt_root_resolved = root.resolve(strict=False)
531
+ if not resolved.is_relative_to(mnt_root_resolved):
532
+ return None
533
+ # Check the RESOLVED path for existence/dir (not the raw candidate):
534
+ # a path like /mnt/c/sub/../x/.copilot resolves to /mnt/c/x/.copilot,
535
+ # which exists and is under /mnt, but candidate.exists() fails when
536
+ # the intermediate "sub" dir doesn't exist (the OS can't traverse
537
+ # through a missing component). The symlink check stays on the raw
538
+ # candidate so a final-component symlink is still detected.
539
+ if not resolved.exists():
540
+ return None
541
+ if not resolved.is_dir() or candidate.is_symlink():
542
+ return None
543
+ return resolved
544
+ except (OSError, ValueError):
545
+ return None
546
+
547
+
548
+ def _wsl_root_context() -> bool:
549
+ """True when running as root inside WSL — the wrong-home case.
550
+
551
+ Under `bash install.sh` launched from a Windows shell, WSL runs as root, so
552
+ ``$HOME=/root`` while the user's real Copilot lives on the Windows profile
553
+ at ``/mnt/c/Users/<you>/.copilot``. Gated on actual WSL detection so a
554
+ native-Linux root session is unaffected. Never raises.
555
+ """
556
+ if not _is_wsl_context():
557
+ return False
558
+ try:
559
+ if hasattr(os, "geteuid") and os.geteuid() == 0:
560
+ return True
561
+ except OSError:
562
+ pass
563
+ try:
564
+ return _home_root() == Path("/root")
565
+ except (OSError, ValueError):
566
+ return False
567
+
568
+
569
+ def _autodetect_wsl_copilot_home(mnt_root: Path | None = None) -> Path | None:
570
+ """Find the Windows-profile Copilot home from WSL-root.
571
+
572
+ When running as root under WSL, ``$HOME/.copilot`` is ``/root/.copilot`` —
573
+ an empty dir the native-Windows Copilot CLI never reads. The real home is
574
+ the Windows profile at ``/mnt/c/Users/<you>/.copilot``. Probe for it so the
575
+ user never has to set an env var (and never has to set the collision-prone
576
+ COPILOT_HOME that would break Copilot's own logging).
577
+
578
+ Returns the resolved Path when EXACTLY ONE Windows profile carrying a
579
+ ``.copilot`` dir is found. Returns ``None`` when zero (caller falls back to
580
+ the default) or when several are found (ambiguous — the caller warns and
581
+ the user disambiguates with TOKEN_OPTIMIZER_COPILOT_HOME). Never raises.
582
+
583
+ ``mnt_root`` is a test-injection parameter (never set in production).
584
+ """
585
+ if not _wsl_root_context():
586
+ return None
587
+ root = Path(mnt_root) if mnt_root is not None else Path("/mnt")
588
+ try:
589
+ uniq: list[Path] = []
590
+ for drive in sorted(root.glob("*")):
591
+ users = drive / "Users"
592
+ if not users.is_dir():
593
+ continue
594
+ for prof in sorted(users.iterdir()):
595
+ if prof.name.lower() in _WINDOWS_NONUSER_PROFILES:
596
+ continue
597
+ cand = prof / ".copilot"
598
+ try:
599
+ if cand.is_dir() and not cand.is_symlink():
600
+ resolved = cand.resolve(strict=False)
601
+ if resolved not in uniq:
602
+ uniq.append(resolved)
603
+ except OSError:
604
+ continue
605
+ if len(uniq) == 1:
606
+ return uniq[0]
607
+ return None
608
+ except (OSError, ValueError):
609
+ return None
610
+
611
+
612
+ def _looks_like_mnt_path(raw: str) -> bool:
613
+ """True when ``raw`` is an absolute WSL /mnt/ path (the footgun value)."""
614
+ try:
615
+ return Path(raw).is_absolute() and raw.replace("\\", "/").startswith("/mnt/")
616
+ except (OSError, ValueError):
617
+ return raw.startswith("/mnt/")
618
+
619
+
620
+ def _warn_mnt_copilot_home(raw: str) -> None:
621
+ """Warn that a /mnt COPILOT_HOME breaks native-Windows Copilot.
622
+
623
+ GitHub Copilot CLI reads COPILOT_HOME itself; a WSL ``/mnt/...`` value —
624
+ meaningless on native Windows — makes Copilot relocate its own
625
+ session-state/session.db/events.jsonl into a path that doesn't exist, so it
626
+ silently stops logging. Steer the user to unset it and rely on
627
+ auto-detection, or to use Token Optimizer's own TOKEN_OPTIMIZER_COPILOT_HOME.
628
+ """
629
+ if not _looks_like_mnt_path(raw):
630
+ return
631
+ _warn_once(
632
+ f"[Token Optimizer] Warning: COPILOT_HOME={raw!r} is a WSL /mnt path. "
633
+ "GitHub Copilot CLI reads COPILOT_HOME too, and a /mnt value breaks its "
634
+ "own session logging on native Windows. Unset COPILOT_HOME (Token "
635
+ "Optimizer auto-detects your Windows Copilot home), or use "
636
+ "TOKEN_OPTIMIZER_COPILOT_HOME for Token Optimizer only."
637
+ )
638
+
639
+
640
+ def _non_symlinked_fallback(env_var: str, fallback: Path) -> Path:
641
+ """Return *fallback* unless it exists as a symlink.
642
+
643
+ ``_is_safe_home_dir`` rejects symlinked env-var values, but the no-env-var
644
+ fallback was returned unchecked: on a mixed host where ``~/.codex`` is a
645
+ symlink to ``~/.claude`` (shared config, careless admin, or a symlink
646
+ attack), every downstream read/write lands in a foreign runtime's tree —
647
+ a cross-runtime data leak with no env var set and no warning. Degrade to
648
+ a Token-Optimizer-owned dir under home instead of following the link.
649
+ """
650
+ try:
651
+ if fallback.is_symlink():
652
+ slug = (
653
+ env_var.lower()
654
+ .removeprefix("token_optimizer_")
655
+ .removesuffix("_home").removesuffix("_dir")
656
+ .replace("_", "-")
657
+ ) or "runtime-home"
658
+ alt = _safe_home() / ".token-optimizer" / slug
659
+ # Resolve outside the f-string so a diagnostic OSError does not
660
+ # discard `alt` and fall through to returning the symlink itself.
661
+ try:
662
+ resolved = fallback.resolve(strict=False)
663
+ except OSError:
664
+ resolved = "<unresolvable>"
665
+ _warn_once(
666
+ f"[Token Optimizer] Warning: default runtime home {fallback} is a symlink "
667
+ f"(resolves to {resolved}); refusing to follow it "
668
+ f"into a foreign tree. Using {alt} instead."
669
+ )
670
+ return alt
671
+ except OSError:
672
+ # If the symlink check itself raised, we cannot confirm the path is
673
+ # safe. Fail closed: return the alt dir rather than the unverified
674
+ # fallback (which may be a symlink we could not inspect).
675
+ slug = (
676
+ env_var.lower()
677
+ .removeprefix("token_optimizer_")
678
+ .removesuffix("_home").removesuffix("_dir")
679
+ .replace("_", "-")
680
+ ) or "runtime-home"
681
+ return _safe_home() / ".token-optimizer" / slug
682
+ return fallback
683
+
684
+
685
+ def _safe_home_from_env(env_var: str, fallback: Path, *, mnt_root: Path | None = None) -> Path:
686
+ """Resolve a runtime-home env var without letting it escape user home.
687
+
688
+ The WSL-root ``/mnt/`` opt-in: under WSL only, a value that
689
+ fails the strict under-``$HOME`` guard is still accepted when it points
690
+ at an absolute, existing, non-symlink directory under ``/mnt/`` (the WSL
691
+ Windows-mount root). This is the deliberate cross-filesystem opt-in that
692
+ lets a WSL-root install (where ``$HOME=/root``) point
693
+ ``COPILOT_HOME``/``CODEX_HOME``/``HERMES_HOME``/``OPENCODE_*`` at the
694
+ Windows profile path ``/mnt/c/Users/<you>/.copilot`` (etc.). Native-Linux
695
+ ``/mnt`` mounts stay on the strict path because the ``/mnt`` opt-in is
696
+ gated on actual WSL detection (see ``_is_wsl_context``).
697
+
698
+ ``mnt_root`` is a test-injection parameter (never set in production) so
699
+ tests can substitute a temp dir for ``/mnt`` on non-Linux hosts. When the
700
+ ``/mnt`` path is ACCEPTED, no "rejected" warning is printed — the warning
701
+ fires only for genuinely-rejected values.
702
+ """
703
+ raw_val = os.environ.get(env_var, "").strip()
704
+ if not raw_val:
705
+ return _non_symlinked_fallback(env_var, fallback)
706
+ candidate = Path(raw_val).expanduser()
707
+ if _is_safe_home_dir(candidate):
708
+ return candidate.resolve(strict=False)
709
+ # Strict guard rejected it. Try the WSL /mnt opt-in before warning so a
710
+ # legit WSL-root /mnt/c/Users/<you>/.copilot value is accepted silently.
711
+ mnt_result = _wsl_mnt_safe_home(candidate, mnt_root=mnt_root)
712
+ if mnt_result is not None:
713
+ return mnt_result
714
+ # Override (scoped to HERMES_HOME only): on containerized
715
+ # deploys (Docker/Umbrel) HERMES_HOME may be a PARENT of $HOME. When the
716
+ # explicit override env var is truthy, re-validate with the under-$HOME
717
+ # requirement DROPPED but all other checks kept (absolute, resolve, exists,
718
+ # is_dir, not symlink). Deliberately gated to HERMES_HOME only so the opt-in
719
+ # never relaxes CODEX_HOME/COPILOT_HOME/OPENCODE_* containment — those feed
720
+ # write paths (e.g. codex hooks.json), and least-privilege says don't widen
721
+ # them for a Hermes-only deployment need. Other runtimes get their own scoped
722
+ # opt-in if/when a container issue is actually reported for them.
723
+ if (
724
+ env_var == _HERMES_HOME_ENV
725
+ and _truthy_env(_UNSAFE_RUNTIME_HOME_OVERRIDE_ENV)
726
+ and _is_safe_home_dir_relaxed(candidate)
727
+ ):
728
+ return candidate.resolve(strict=False)
729
+ # Name the most common reason so the fix is obvious (assafbem): a
730
+ # ``/mnt/...`` value is a WSL mount path and is only honored inside WSL; on
731
+ # native Windows it points nowhere, so it is rejected. The /mnt opt-in above
732
+ # already accepted any legitimately-WSL value, so reaching here with a /mnt
733
+ # path means we are not in that context.
734
+ hint = ""
735
+ if _looks_like_mnt_path(raw_val):
736
+ hint = (
737
+ " (a /mnt path is WSL-only; on native Windows use a real path like"
738
+ " C:\\Users\\<you>\\.copilot, or unset it and let auto-detect find it)"
739
+ )
740
+ _warn_once(
741
+ f"[Token Optimizer] Warning: {env_var}={raw_val!r} rejected (not a safe directory). Using default.{hint}"
742
+ )
743
+ return _non_symlinked_fallback(env_var, fallback)
744
+
745
+
746
+ def _opencode_env_signal() -> bool:
747
+ """True when an OpenCode launch/config env var is present in this process."""
748
+ return any(os.environ.get(var) for var in _OPENCODE_ENV_SIGNALS)
749
+
750
+
751
+ # ---------------------------------------------------------------------------
752
+ # Shared process snapshot + negative-result ancestor-scan cache (hot path).
753
+ #
754
+ # Every hook invocation is a fresh Python process, and detect_runtime() used to
755
+ # spawn one `ps` per ancestor scanner on the hot path (~100 ms each measured).
756
+ # Two fixes, both behavior-preserving:
757
+ #
758
+ # 1. ONE `ps -Ao pid=,ppid=,comm=,args=` snapshot per process, shared by every
759
+ # scanner. A process's ancestor chain is fixed for its lifetime, so a single
760
+ # snapshot is exact; the OpenCode and Copilot scans read different columns
761
+ # of the same table.
762
+ # 2. A short-TTL disk cache of the OpenCode scan's NEGATIVE result ("no
763
+ # opencode ancestor"), keyed by parent pid + parent process start time
764
+ # (Linux /proc only) + runtime-signal env signature. Only the negative
765
+ # result is cached: a stale entry can then only ever reproduce the
766
+ # pre-fix claude-tier fallback for at most one TTL window, never flip a
767
+ # genuine Claude/Codex session into another runtime's home. The start-time
768
+ # component prevents PID reuse from suppressing a live OpenCode ancestor:
769
+ # a reused PID has a different incarnation and produces a different key.
770
+ # ---------------------------------------------------------------------------
771
+
772
+ _ANCESTOR_CACHE_TTL_SECONDS = 120
773
+ # v2: one entry per parent session ({"entries": {key: ts}}). v1 held a single
774
+ # entry, so every parallel host session evicted the others' negatives.
775
+ _ANCESTOR_CACHE_VERSION = 2
776
+ # Entries kept (newest first). Each is ~100 bytes; 24 stays well under the cap.
777
+ _ANCESTOR_CACHE_MAX_ENTRIES = 24
778
+ # Bound reads of the ancestor-scan cache file. A full payload is ~2.5 KB;
779
+ # anything larger is corrupt or hostile and is ignored.
780
+ _MAX_CACHE_BYTES = 8192
781
+
782
+ # Every env var whose value can change which runtime a hook resolves to. The
783
+ # cache key hashes their values so two sessions with different signals never
784
+ # share an entry.
785
+ _ANCESTOR_CACHE_ENV_VARS = (
786
+ _RUNTIME_OVERRIDE,
787
+ "CLAUDE_PLUGIN_ROOT",
788
+ "CLAUDE_PLUGIN_DATA",
789
+ "CLAUDECODE",
790
+ "CLAUDE_CODE_ENTRYPOINT",
791
+ "CLAUDE_CODE_SESSION_ID",
792
+ _CODEX_HOME_ENV,
793
+ _HERMES_HOME_ENV,
794
+ _COPILOT_HOME_ENV,
795
+ _TO_COPILOT_HOME_ENV,
796
+ *_OPENCODE_ENV_SIGNALS,
797
+ _PROC_SCAN_DISABLE_ENV,
798
+ )
799
+
800
+ _PROC_SCAN_SNAPSHOT: dict | None = None
801
+
802
+
803
+ def _load_proc_snapshot() -> dict:
804
+ """One process-table snapshot per process, shared by all ancestor scanners.
805
+
806
+ Returns a dict with keys: disabled (bool), parents {pid: ppid},
807
+ comms {pid: comm}, cmdlines {pid: args}. On any ps failure the tables are
808
+ empty, which makes every scanner walk find nothing — the same result the
809
+ previous per-scanner error handling produced.
810
+ """
811
+ global _PROC_SCAN_SNAPSHOT
812
+ if _PROC_SCAN_SNAPSHOT is not None:
813
+ return _PROC_SCAN_SNAPSHOT
814
+ disabled = bool(
815
+ os.environ.get(_PROC_SCAN_DISABLE_ENV, "").strip()
816
+ ) or sys.platform.startswith("win")
817
+ snapshot: dict = {
818
+ "disabled": disabled,
819
+ "parents": {},
820
+ "comms": {},
821
+ "cmdlines": {},
822
+ }
823
+ if not disabled:
824
+ try:
825
+ import subprocess
826
+
827
+ proc = subprocess.run(
828
+ ["ps", "-Ao", "pid=,ppid=,comm=,args="],
829
+ capture_output=True,
830
+ text=True,
831
+ encoding="utf-8",
832
+ errors="replace",
833
+ timeout=2,
834
+ # Unreachable on Windows (the disabled guard above returns
835
+ # first), but carried anyway so every spawn in this file states
836
+ # the no-flash intent. 0 on POSIX, so a no-op here.
837
+ creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0),
838
+ )
839
+ if proc.returncode == 0:
840
+ for line in proc.stdout.splitlines():
841
+ parts = line.split(None, 3)
842
+ if len(parts) < 3:
843
+ continue
844
+ try:
845
+ pid, ppid = int(parts[0]), int(parts[1])
846
+ except ValueError:
847
+ continue
848
+ snapshot["parents"][pid] = ppid
849
+ # Defunct/kernel rows can carry a comm but no args.
850
+ snapshot["comms"][pid] = parts[2]
851
+ if len(parts) > 3:
852
+ snapshot["cmdlines"][pid] = parts[3]
853
+ except Exception:
854
+ pass
855
+ _PROC_SCAN_SNAPSHOT = snapshot
856
+ return snapshot
857
+
858
+
859
+ def _ancestor_cache_path() -> Path:
860
+ """Runtime-neutral cache location (XDG cache), safe to compute pre-detection."""
861
+ # Own filename per format: a v1 install (older plugin copy, other runtime
862
+ # adapter) keeps writing ancestor-scan.json, and if both shared one file
863
+ # each would read the other's format as a miss and overwrite it.
864
+ return _xdg_base("XDG_CACHE_HOME", ".cache") / "token-optimizer" / "ancestor-scan-v2.json"
865
+
866
+
867
+ def _parent_starttime() -> str:
868
+ """Best-effort parent process start time (incarnation marker for PID-reuse safety).
869
+
870
+ On Linux, reads ``/proc/<ppid>/stat`` field 22 (starttime in clock ticks
871
+ since boot) — a cheap file read with no ``ps`` spawn. On non-Linux the
872
+ start time is unavailable cheaply; returns "" so the cache key falls back
873
+ to ``pid:env_hash`` (the pre-fix behavior, no regression). Never raises.
874
+ """
875
+ if not sys.platform.startswith("linux"):
876
+ return ""
877
+ try:
878
+ ppid = os.getppid()
879
+ data = Path(f"/proc/{ppid}/stat").read_text()
880
+ # comm is in parentheses and can contain spaces; split after the last ')'.
881
+ rparen = data.rfind(")")
882
+ if rparen < 0:
883
+ return ""
884
+ fields = data[rparen + 2:].split()
885
+ # After comm: state ppid pgrp session tty_nr tpgid flags minflt cminflt
886
+ # majflt cmajflt utime stime cutime cstime priority nice num_threads
887
+ # itrealvalue starttime ... — starttime is field 22, index 19 here.
888
+ if len(fields) > 19:
889
+ return fields[19]
890
+ except (OSError, ValueError, IndexError):
891
+ pass
892
+ return ""
893
+
894
+
895
+ def _ancestor_cache_key() -> str:
896
+ """Key binding the cached negative result to this parent + signal env.
897
+
898
+ Includes the parent's process start time (Linux ``/proc`` only) so a
899
+ reused PID with a different incarnation produces a different key and
900
+ cannot suppress a live ancestor scan. On non-Linux the start time is
901
+ unavailable cheaply; the key falls back to ``pid:env_hash``.
902
+ """
903
+ raw = "\n".join(
904
+ f"{name}={os.environ.get(name, '')}" for name in _ANCESTOR_CACHE_ENV_VARS
905
+ )
906
+ start = _parent_starttime()
907
+ return f"{os.getppid()}:{start}:{hashlib.sha256(raw.encode('utf-8', 'replace')).hexdigest()}"
908
+
909
+
910
+ def _load_ancestor_entries() -> dict:
911
+ """Fresh {key: ts} entries from the cache file; {} on any problem."""
912
+ try:
913
+ path = _ancestor_cache_path()
914
+ if not path.is_file() or path.stat().st_size > _MAX_CACHE_BYTES:
915
+ return {}
916
+ with path.open("r", encoding="utf-8") as fh:
917
+ data = json.load(fh)
918
+ if not isinstance(data, dict):
919
+ return {}
920
+ if data.get("version") != _ANCESTOR_CACHE_VERSION:
921
+ return {}
922
+ entries = data.get("entries")
923
+ if not isinstance(entries, dict):
924
+ return {}
925
+ now = time.time()
926
+ return {
927
+ k: ts for k, ts in entries.items()
928
+ if isinstance(k, str) and isinstance(ts, (int, float))
929
+ and 0 <= now - ts < _ANCESTOR_CACHE_TTL_SECONDS
930
+ }
931
+ except (OSError, ValueError, RecursionError):
932
+ return {}
933
+
934
+
935
+ def _ancestor_negative_cached() -> bool:
936
+ """True when a fresh cache entry says this session had no opencode ancestor."""
937
+ return _ancestor_cache_key() in _load_ancestor_entries()
938
+
939
+
940
+ def _store_ancestor_negative() -> None:
941
+ """Persist a negative opencode-ancestor scan result. Best-effort, atomic.
942
+
943
+ Keeps every other session's fresh entry, so parallel host sessions (one
944
+ parent pid each) no longer evict each other and re-pay the ps scan. A
945
+ concurrent writer can drop an entry (last replace wins); that only costs
946
+ one extra scan, never a wrong answer.
947
+ """
948
+ tmp = None
949
+ try:
950
+ path = _ancestor_cache_path()
951
+ path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
952
+ entries = _load_ancestor_entries()
953
+ entries[_ancestor_cache_key()] = time.time()
954
+ newest = sorted(entries.items(), key=lambda kv: kv[1])[-_ANCESTOR_CACHE_MAX_ENTRIES:]
955
+ payload = json.dumps({
956
+ "version": _ANCESTOR_CACHE_VERSION,
957
+ "entries": dict(newest),
958
+ })
959
+ tmp = path.with_name(f".{path.name}.{os.getpid()}.tmp")
960
+ with tmp.open("w", encoding="utf-8") as fh:
961
+ fh.write(payload)
962
+ os.chmod(tmp, 0o600)
963
+ os.replace(tmp, path)
964
+ except (OSError, ValueError):
965
+ if tmp is not None:
966
+ try:
967
+ tmp.unlink(missing_ok=True)
968
+ except OSError:
969
+ pass
970
+
971
+
972
+ def _ancestor_in_process_tree(basenames: frozenset) -> bool:
973
+ """Best-effort: is one of ``basenames`` an ancestor of this process?
974
+
975
+ Used only as a fallback signal when a host CLI runs this skill without
976
+ exporting an identifying env var. Reads the shared one-shot process
977
+ snapshot (``_load_proc_snapshot``) instead of spawning its own ``ps``:
978
+ a process's ancestor chain is fixed for its lifetime, so one snapshot
979
+ per process is exact for every scanner, and the OpenCode and Copilot
980
+ scans no longer pay two separate spawns (hot-path latency).
981
+
982
+ Never raises and never blocks for long: disabled on Windows, behind a
983
+ short timeout, and skippable via TOKEN_OPTIMIZER_NO_PROC_SCAN.
984
+ """
985
+ snapshot = _load_proc_snapshot()
986
+ if snapshot["disabled"]:
987
+ return False
988
+ parents = snapshot["parents"]
989
+ comms = snapshot["comms"]
990
+ pid = os.getpid()
991
+ seen: set[int] = set()
992
+ depth = 0
993
+ while pid and pid > 1 and pid not in seen and depth < 40:
994
+ seen.add(pid)
995
+ depth += 1
996
+ # Exact basename match, not a substring: an unrelated binary like
997
+ # "my-opencode-helper" or a repo dir named "opencode" in argv must
998
+ # not flip a genuine Claude Code session into another runtime's
999
+ # mode. The real CLIs run under their bare binary name (or
1000
+ # name.exe on Windows).
1001
+ comm = os.path.basename(comms.get(pid, "")).lower()
1002
+ if comm in basenames:
1003
+ return True
1004
+ pid = parents.get(pid, 0)
1005
+ return False
1006
+
1007
+
1008
+ _OPENCODE_BASENAMES = frozenset({"opencode", "opencode.exe"})
1009
+ _COPILOT_BASENAMES = frozenset({"copilot", "copilot.exe"})
1010
+
1011
+ # Bare ``opencode`` binary names — trusted ONLY in executable position (argv[0]).
1012
+ # A bare "opencode" as a later argument is ambiguous (it could be a directory a
1013
+ # Claude user passed as `--dir /home/me/opencode`), so it never matches there.
1014
+ _OPENCODE_EXE_BASENAMES = frozenset({"opencode", "opencode.exe"})
1015
+ # JS/TS runtimes OpenCode can be launched through. When an ancestor's executable
1016
+ # is one of these, OpenCode's own basename ("opencode") is NOT the ancestor
1017
+ # basename — the launcher is ("node"/"bun"/…). So a basename-only scan misses it.
1018
+ # We then inspect the launcher's arguments for an OpenCode entry.
1019
+ # The "run" subcommand (bun run opencode) is skipped so the npm script name
1020
+ # after it is recognized. An absolute path to the opencode binary as a launcher
1021
+ # argument (node /usr/local/bin/opencode) is also matched.
1022
+ _JS_LAUNCHERS = frozenset(
1023
+ {"node", "nodejs", "bun", "deno", "node.exe", "bun.exe", "deno.exe"}
1024
+ )
1025
+ _JS_RUN_SUBCOMMANDS = frozenset({"run"})
1026
+ # Named OpenCode entry SCRIPTS (carry a file extension). Unlike a bare
1027
+ # ``opencode`` token, these are unambiguous as a launcher argument, so they are
1028
+ # safe to match anywhere in the arg list.
1029
+ _OPENCODE_SCRIPT_BASENAMES = frozenset(
1030
+ {"opencode.js", "opencode.mjs", "opencode.cjs", "opencode.ts"}
1031
+ )
1032
+ # OpenCode's npm package name (the dominant install shape:
1033
+ # .../node_modules/opencode-ai/dist/index.js, incl. pnpm's `opencode-ai@x.y.z`).
1034
+ _OPENCODE_PKG = "opencode-ai"
1035
+ # Parent directories an installed package legitimately lives under. Requiring one
1036
+ # of these stops a user's own project dir named `opencode-ai` from matching.
1037
+ _OPENCODE_PKG_PARENTS = frozenset({"node_modules", ".pnpm"})
1038
+ _PATH_SPLIT = re.compile(r"[\\/]+")
1039
+
1040
+
1041
+ def _looks_like_opencode_entrypoint(path_token: str) -> bool:
1042
+ """True when an argument token is recognizably OpenCode's entry script.
1043
+
1044
+ Deliberately tight: we match the *entry script* or the
1045
+ *installed package*, never a bare occurrence of the word "opencode" anywhere
1046
+ in the command line. A Claude Code user whose project is named ``opencode``
1047
+ — even one with a stock ``index.js`` — must NOT be flipped into OpenCode
1048
+ mode, so a generic entry filename under an ``opencode`` directory is NOT a
1049
+ match. The trade-off: running OpenCode from an *uninstalled* source checkout
1050
+ (e.g. ``bun /opt/opencode/src/index.ts``) is not auto-detected; such dev runs
1051
+ set TOKEN_OPTIMIZER_RUNTIME=opencode explicitly. Installed users (npm package
1052
+ or the ``opencode`` binary) are always detected.
1053
+ """
1054
+ p = path_token.strip().strip('"').strip("'")
1055
+ if not p:
1056
+ return False
1057
+ base = os.path.basename(p).lower()
1058
+ # The script itself is a named OpenCode entry (opencode.mjs, opencode.js, …).
1059
+ if base in _OPENCODE_SCRIPT_BASENAMES:
1060
+ return True
1061
+ # The npm package directory — but only when it sits under node_modules / a
1062
+ # pnpm store, which is how every real install looks. Requiring that parent
1063
+ # rejects a user's own project directory that merely happens to be named
1064
+ # `opencode-ai` (false-positive guard).
1065
+ segs = [seg.lower() for seg in _PATH_SPLIT.split(p) if seg]
1066
+ for i, s in enumerate(segs):
1067
+ is_pkg = s == _OPENCODE_PKG or s.startswith(_OPENCODE_PKG + "@")
1068
+ if is_pkg and i > 0 and segs[i - 1] in _OPENCODE_PKG_PARENTS:
1069
+ return True
1070
+ return False
1071
+
1072
+
1073
+ def _is_opencode_command(args: str) -> bool:
1074
+ """True when a process command line is an OpenCode invocation.
1075
+
1076
+ ``args`` is a full command line (``ps -o args``). Matches either the bare
1077
+ ``opencode`` binary in executable position, or a JS-runtime launcher with an
1078
+ OpenCode entry script / package among ITS arguments. The launcher arg scan
1079
+ checks every token (not just the first non-flag one) so value-taking flags
1080
+ (``node --require x …``) and launcher subcommands (``bun run …``) don't hide
1081
+ the real entry script. The entry check is strict enough that flags, flag
1082
+ values, and bare directory arguments never match.
1083
+ """
1084
+ tokens = args.split()
1085
+ if not tokens:
1086
+ return False
1087
+ exe_base = os.path.basename(tokens[0].strip('"').strip("'")).lower()
1088
+ if exe_base in _OPENCODE_EXE_BASENAMES:
1089
+ return True
1090
+ if exe_base in _JS_LAUNCHERS:
1091
+ rest = [t.strip('"').strip("'") for t in tokens[1:]]
1092
+ # `bun run opencode` — the script name sits at rest[1] after the `run` subcommand.
1093
+ if rest and rest[0].lower() in _JS_RUN_SUBCOMMANDS:
1094
+ if len(rest) >= 2 and os.path.basename(rest[1]).lower() in _OPENCODE_EXE_BASENAMES:
1095
+ return True
1096
+ # `node /abs/path/opencode` — the opencode binary as the IMMEDIATE first argument
1097
+ # (rest[0]). Restricting to rest[0] (not a general scan) is what prevents a later
1098
+ # flag value like `--dir /home/me/opencode` from false-matching.
1099
+ elif rest and os.path.isabs(rest[0]) and os.path.basename(rest[0]).lower() in _OPENCODE_EXE_BASENAMES:
1100
+ return True
1101
+ # Named entry scripts (opencode.mjs/.js) and the installed npm package
1102
+ # (node_modules/opencode-ai) — tight check, safe to scan all tokens.
1103
+ for tok in tokens[1:]:
1104
+ if _looks_like_opencode_entrypoint(tok):
1105
+ return True
1106
+ return False
1107
+
1108
+
1109
+ def _opencode_in_process_tree() -> bool:
1110
+ """Best-effort: is OpenCode an ancestor of this process?
1111
+
1112
+ Scans the parent chain using full command lines so that OpenCode launched
1113
+ through ``node``/``bun`` is recognized, not only a bare ``opencode`` binary.
1114
+ Reads the shared one-shot process snapshot (one ``ps`` per
1115
+ process, shared with the Copilot scanner). A fresh NEGATIVE result is
1116
+ persisted to a short-TTL disk cache keyed by parent pid + parent start
1117
+ time (Linux /proc only) + signal-env signature, so subsequent hook
1118
+ processes in the same session skip the scan entirely; only the negative
1119
+ result is cached, so a stale entry can never flip a Claude/Codex session
1120
+ into another runtime. On Linux the start-time binding also prevents PID
1121
+ reuse from flipping an OpenCode session into claude: a reused PID has a
1122
+ different incarnation and produces a different key. On non-Linux the
1123
+ start time is unavailable cheaply; a stale entry can flip an OpenCode
1124
+ session into claude for at most one TTL window (worst case: the pre-fix
1125
+ claude-tier fallback). Same safety envelope as
1126
+ ``_ancestor_in_process_tree``: disabled on Windows, behind a short timeout,
1127
+ skippable via TOKEN_OPTIMIZER_NO_PROC_SCAN, and never raises.
1128
+ """
1129
+ if _ancestor_negative_cached():
1130
+ return False
1131
+ snapshot = _load_proc_snapshot()
1132
+ if snapshot["disabled"]:
1133
+ return False
1134
+ parents = snapshot["parents"]
1135
+ cmdlines = snapshot["cmdlines"]
1136
+ pid = os.getpid()
1137
+ seen: set[int] = set()
1138
+ depth = 0
1139
+ found = False
1140
+ while pid and pid > 1 and pid not in seen and depth < 40:
1141
+ seen.add(pid)
1142
+ depth += 1
1143
+ if _is_opencode_command(cmdlines.get(pid, "")):
1144
+ found = True
1145
+ break
1146
+ pid = parents.get(pid, 0)
1147
+ if not found and not snapshot["disabled"]:
1148
+ # Cache only the negative outcome (see docstring): a positive finding
1149
+ # is re-derived live on every scan so a runtime can never be sticky.
1150
+ _store_ancestor_negative()
1151
+ return found
1152
+
1153
+
1154
+ def _opencode_process_signal() -> bool:
1155
+ """Definitive OpenCode signal from the live process tree.
1156
+
1157
+ Ground truth for "running under OpenCode *right now*" — unlike an env var or
1158
+ a marker file, an OpenCode ancestor process can't be left behind by a prior
1159
+ session or a merely-installed copy. Evaluated ahead of the soft Claude
1160
+ plugin-env heuristic in ``detect_runtime``.
1161
+ """
1162
+ return _opencode_in_process_tree()
1163
+
1164
+
1165
+ def _opencode_config_signal() -> bool:
1166
+ """Weak OpenCode signal: a populated ~/.config/opencode directory.
1167
+
1168
+ Tertiary tier: catches a real OpenCode install that exports
1169
+ neither an OPENCODE_* env var nor an opencode ancestor (e.g. a host CLI
1170
+ spawned outside OpenCode's process group). A populated config dir is a
1171
+ weak signal — a stale uninstalled copy leaves an empty dir, which does
1172
+ NOT trigger. Suppressed by Claude env vars (Claude takes priority) and by
1173
+ CODEX_HOME/HERMES_HOME/COPILOT_HOME (those genuine runtimes win over this
1174
+ weak tier), and by a real Claude Code home (settings.json or projects/).
1175
+ Never raises; OSError/PermissionError -> False.
1176
+ """
1177
+ if any(os.environ.get(v) for v in _CLAUDE_PLUGIN_ENVS):
1178
+ return False
1179
+ if (
1180
+ os.environ.get(_CODEX_HOME_ENV)
1181
+ or os.environ.get(_HERMES_HOME_ENV)
1182
+ or os.environ.get(_COPILOT_HOME_ENV)
1183
+ or os.environ.get(_TO_COPILOT_HOME_ENV)
1184
+ or os.environ.get(_TO_CURSOR_HOME_ENV)
1185
+ or (
1186
+ os.environ.get(_CURSOR_HOOK_ENVS[0])
1187
+ and os.environ.get(_CURSOR_HOOK_ENVS[1])
1188
+ )
1189
+ or os.environ.get(_TO_ANTIGRAVITY_HOME_ENV)
1190
+ ):
1191
+ return False
1192
+ # A real Claude Code home (settings.json or projects/) means this is a Claude
1193
+ # user; the weak config-dir tier must not flip them to opencode. A live OpenCode
1194
+ # session is already caught by the ancestor (step 2) / OPENCODE_* env (step 4)
1195
+ # tiers, so this only prevents a false stop, never masks a real OpenCode run.
1196
+ # Bare ~/.claude existence is NOT used (OpenCode loads ~/.claude/skills).
1197
+ ch = claude_home()
1198
+ if ch.is_dir() and ((ch / "settings.json").is_file() or (ch / "projects").is_dir()):
1199
+ return False
1200
+ try:
1201
+ d = opencode_config_home()
1202
+ if not d.is_dir():
1203
+ if os.environ.get("TOKEN_OPTIMIZER_DEBUG"):
1204
+ print(f"[_opencode_config_signal] config dir not present: {d}", file=sys.stderr)
1205
+ return False
1206
+ if not any(d.iterdir()):
1207
+ if os.environ.get("TOKEN_OPTIMIZER_DEBUG"):
1208
+ print(f"[_opencode_config_signal] config dir empty: {d}", file=sys.stderr)
1209
+ return False
1210
+ return True
1211
+ except OSError as exc:
1212
+ if os.environ.get("TOKEN_OPTIMIZER_DEBUG"):
1213
+ print(f"[_opencode_config_signal] OSError inspecting config dir: {exc}", file=sys.stderr)
1214
+ return False
1215
+
1216
+
1217
+ def _opencode_signal() -> bool:
1218
+ """True when an OpenCode env signal or an OpenCode ancestor process is found."""
1219
+ return _opencode_env_signal() or _opencode_process_signal()
1220
+
1221
+
1222
+ def _copilot_signal() -> bool:
1223
+ """True when COPILOT_HOME is set or a ``copilot`` ancestor process is found.
1224
+
1225
+ The Copilot hook bridge always sets TOKEN_OPTIMIZER_RUNTIME=copilot
1226
+ explicitly; this signal is the safety net for direct invocations from
1227
+ inside a Copilot CLI session (never let an
1228
+ unrecognized host fall through to the Claude default and write ~/.claude).
1229
+ """
1230
+ if os.environ.get(_COPILOT_HOME_ENV) or os.environ.get(_TO_COPILOT_HOME_ENV):
1231
+ return True
1232
+ return _ancestor_in_process_tree(_COPILOT_BASENAMES)
1233
+
1234
+
1235
+ def _cursor_signal() -> bool:
1236
+ """True when both Cursor hook-spawned env vars are present.
1237
+
1238
+ Cursor exports CURSOR_PROJECT_DIR and CURSOR_VERSION into every hook
1239
+ subprocess; both must be present together (either alone is too weak).
1240
+ There is deliberately no ancestor-process scan: the Cursor CLI binary is
1241
+ named ``agent`` — too generic to scan without false positives. This signal
1242
+ sits at the weak tier BELOW the CLAUDECODE env check, so a Cursor launched
1243
+ from a CC Bash tool (which inherits CLAUDECODE=1) is not stolen here; the
1244
+ bridge always pins TOKEN_OPTIMIZER_RUNTIME=cursor anyway.
1245
+ """
1246
+ return bool(
1247
+ os.environ.get(_CURSOR_HOOK_ENVS[0])
1248
+ and os.environ.get(_CURSOR_HOOK_ENVS[1])
1249
+ )
1250
+
1251
+
1252
+ def _antigravity_signal() -> bool:
1253
+ """True when TOKEN_OPTIMIZER_ANTIGRAVITY_HOME is set or an `agy` ancestor runs.
1254
+
1255
+ The Antigravity hook bridge always sets TOKEN_OPTIMIZER_RUNTIME=antigravity
1256
+ explicitly; this signal is the safety net for direct invocations from inside
1257
+ an Antigravity session (the same class of bugs: never let an
1258
+ unrecognized host fall through to the Claude default and write ~/.claude).
1259
+ """
1260
+ if os.environ.get(_TO_ANTIGRAVITY_HOME_ENV):
1261
+ return True
1262
+ return _ancestor_in_process_tree(_AGY_BASENAMES)
1263
+
1264
+
1265
+ def _codex_plugin_env_signal() -> bool:
1266
+ """True when CLAUDE_PLUGIN_ROOT / CLAUDE_PLUGIN_DATA point inside Codex's
1267
+ plugins dir (``<codex home>/plugins/``): a hook Codex loaded from the
1268
+ plugin's hooks.json. Never raises."""
1269
+ try:
1270
+ base = (codex_home() / "plugins").resolve(strict=False)
1271
+ for var in _CLAUDE_PLUGIN_ENVS:
1272
+ raw = os.environ.get(var, "").strip()
1273
+ if not raw:
1274
+ continue
1275
+ try:
1276
+ Path(raw).expanduser().resolve(strict=False).relative_to(base)
1277
+ return True
1278
+ except (ValueError, OSError, RuntimeError):
1279
+ continue
1280
+ except Exception:
1281
+ return False
1282
+ return False
1283
+
1284
+
1285
+ @functools.lru_cache(maxsize=None)
1286
+ def detect_runtime() -> str:
1287
+ """Return the active runtime name.
1288
+
1289
+ Priority:
1290
+ 1. Explicit override via TOKEN_OPTIMIZER_RUNTIME
1291
+ 2. A definitive OpenCode signal — an opencode ancestor process — implies
1292
+ OpenCode, evaluated BEFORE the soft Claude plugin-env heuristic so a
1293
+ coexisting Claude Code install on the same host can't shadow it
1294
+ 3. Claude plugin env vars imply Claude Code
1295
+ 4. An OPENCODE_* env signal implies OpenCode (medium tier: beats
1296
+ Codex/Hermes so a leftover CODEX_HOME can't shadow a genuine
1297
+ OpenCode session — "Guy's bug"; still AFTER Claude env)
1298
+ 5. CODEX_HOME implies Codex
1299
+ 6. HERMES_HOME implies Hermes
1300
+ 7. COPILOT_HOME / TOKEN_OPTIMIZER_COPILOT_HOME implies Copilot (explicit
1301
+ config-dir env; sits ABOVE the CLAUDECODE tier so a Copilot session
1302
+ launched from a CC Bash tool, which inherits CLAUDECODE=1, still
1303
+ resolves to copilot -- the same guard Codex/Hermes get. The
1304
+ ancestor-process signal stays at the weak tier below CLAUDECODE.)
1305
+ 7b. TOKEN_OPTIMIZER_CURSOR_HOME implies Cursor (explicit config-dir env,
1306
+ same ABOVE-CLAUDECODE guard as Copilot; Cursor has no documented
1307
+ CURSOR_HOME of its own so this is TO's namespaced override only).
1308
+ 8. Claude Code process env (CLAUDECODE / CLAUDE_CODE_ENTRYPOINT /
1309
+ CLAUDE_CODE_SESSION_ID) implies Claude. Sits BELOW CODEX_HOME/
1310
+ HERMES_HOME/COPILOT_HOME/TOKEN_OPTIMIZER_CURSOR_HOME so a nested-
1311
+ Codex/Hermes/Copilot/Cursor session launched from a CC Bash tool
1312
+ (which inherits CLAUDECODE=1) still resolves to its own runtime, but
1313
+ ABOVE the directory heuristics so a host with CLAUDECODE=1 and a
1314
+ coexisting ~/.codex DIRECTORY resolves to claude, not codex
1315
+ 9. A populated opencode config dir implies OpenCode (weak tertiary
1316
+ tier; loses to Claude/Codex/Hermes/Copilot/Cursor env, beats default)
1317
+ 10. COPILOT_HOME or a copilot ancestor process implies Copilot
1318
+ 11. CURSOR_PROJECT_DIR + CURSOR_VERSION both set implies Cursor (weak
1319
+ hook-spawned tier, BELOW CLAUDECODE -- no ancestor scan since the
1320
+ Cursor CLI binary `agent` is too generic)
1321
+ 11b. TOKEN_OPTIMIZER_ANTIGRAVITY_HOME or an `agy` ancestor process
1322
+ implies Antigravity (weak tier, below CLAUDECODE)
1323
+ 12. Default to Claude Code for backward compatibility
1324
+
1325
+ Why step 2 is ahead of the Claude env check (KTD-3): on a host
1326
+ with BOTH Claude Code and OpenCode installed, a stray CLAUDE_PLUGIN_* env var
1327
+ would otherwise resolve a genuine OpenCode session to Claude and let the
1328
+ skill scan/mutate ~/.claude. An opencode ancestor process is ground truth
1329
+ for what's actually running, so it wins. It cannot steal a genuine Claude,
1330
+ Codex, or Hermes session: those have no opencode ancestor, so the scan
1331
+ returns False and resolution falls through unchanged. The OPENCODE_* env
1332
+ signal (step 4) sits AFTER the Claude env check so an exported OPENCODE_*
1333
+ var alone never overrides a real Claude session, but BEFORE Codex/Hermes
1334
+ so a leftover CODEX_HOME/HERMES_HOME can't shadow a genuine OpenCode
1335
+ session. The config-dir signal (step 7) is the weakest tier — it only
1336
+ fires when no Claude/Codex/Hermes/Copilot env is set and no real Claude
1337
+ Code home (settings.json or projects/) exists.
1338
+ """
1339
+ override = os.environ.get(_RUNTIME_OVERRIDE, "").strip().lower()
1340
+ if override in _VALID_RUNTIMES:
1341
+ return override
1342
+ if override:
1343
+ _warn_bad_override(override)
1344
+
1345
+ if _opencode_process_signal():
1346
+ return _RUNTIME_OPENCODE
1347
+
1348
+ # Codex loads the plugin's own hooks/hooks.json and hands each hook ONLY
1349
+ # CLAUDE_PLUGIN_ROOT / CLAUDE_PLUGIN_DATA (no CODEX_HOME, no override;
1350
+ # verified live, see tests/test_codex_sessionstart_json_contract.py). Both
1351
+ # point inside Codex's plugins dir, which no Claude Code plugin uses, so
1352
+ # they name Codex before the Claude plugin-env tier below claims them.
1353
+ # Without this, a Codex session wrote its state into ~/.claude and pointed
1354
+ # Claude Code's statusLine at the Codex plugin cache.
1355
+ if _codex_plugin_env_signal():
1356
+ return _RUNTIME_CODEX
1357
+
1358
+ if any(os.environ.get(env_var) for env_var in _CLAUDE_PLUGIN_ENVS):
1359
+ return _RUNTIME_CLAUDE
1360
+
1361
+ if _opencode_env_signal():
1362
+ return _RUNTIME_OPENCODE
1363
+
1364
+ if os.environ.get(_CODEX_HOME_ENV):
1365
+ return _RUNTIME_CODEX
1366
+
1367
+ if os.environ.get(_HERMES_HOME_ENV):
1368
+ return _RUNTIME_HERMES
1369
+
1370
+ # Copilot explicit config-dir env: ABOVE the CLAUDECODE tier so a Copilot
1371
+ # session launched from a CC Bash tool (inherits CLAUDECODE=1) still
1372
+ # resolves to copilot. Mirrors the CODEX_HOME/HERMES_HOME guard.
1373
+ if any(os.environ.get(v) for v in _COPILOT_HOME_ENVS):
1374
+ return _RUNTIME_COPILOT
1375
+
1376
+ # Cursor explicit config-dir env: ABOVE the CLAUDECODE tier (same guard as
1377
+ # Codex/Hermes/Copilot). Cursor has no documented CURSOR_HOME, so this is
1378
+ # TO's namespaced override only.
1379
+ if os.environ.get(_TO_CURSOR_HOME_ENV):
1380
+ return _RUNTIME_CURSOR
1381
+
1382
+ # Antigravity explicit config-dir env: ABOVE the CLAUDECODE tier (same
1383
+ # guard Codex/Hermes/Copilot get) so a genuine Antigravity session launched
1384
+ # from a Claude Code Bash tool (which inherits CLAUDECODE=1) still resolves
1385
+ # to antigravity, never writes ~/.claude.
1386
+ if os.environ.get(_TO_ANTIGRAVITY_HOME_ENV):
1387
+ return _RUNTIME_ANTIGRAVITY
1388
+
1389
+ # Grok Build explicit config-dir env: same guard as Copilot — a Grok session
1390
+ # launched from a CC Bash tool (inherits CLAUDECODE=1) still resolves to grok.
1391
+ if any(os.environ.get(v) for v in _GROK_HOME_ENVS):
1392
+ return _RUNTIME_GROK
1393
+
1394
+ if any(os.environ.get(v) for v in _CLAUDE_CODE_ENVS):
1395
+ return _RUNTIME_CLAUDE
1396
+
1397
+ if _opencode_config_signal():
1398
+ return _RUNTIME_OPENCODE
1399
+
1400
+ if _copilot_signal():
1401
+ return _RUNTIME_COPILOT
1402
+
1403
+ if _cursor_signal():
1404
+ return _RUNTIME_CURSOR
1405
+
1406
+ # `agy` ancestor process: the weak-tier safety net (same as the copilot
1407
+ # ancestor signal), below CLAUDECODE so a coexisting Claude install wins.
1408
+ if _antigravity_signal():
1409
+ return _RUNTIME_ANTIGRAVITY
1410
+
1411
+ return _RUNTIME_CLAUDE
1412
+
1413
+
1414
+ def _resolve_remote_host() -> str:
1415
+ """Body of :func:`remote_host` (see the order documented at
1416
+ ``_CLOUD_SESSION_ID_ENV``). Deliberately NOT cached: it is a handful of
1417
+ environment reads, and a cached answer outlives the environment it was
1418
+ computed from (a process, or a test, that changes the host env would keep
1419
+ the stale host). Never raises."""
1420
+ try:
1421
+ pinned = os.environ.get(_REMOTE_HOST_OVERRIDE_ENV, "").strip().lower()
1422
+ if pinned in (REMOTE_HOST_CLOUD, REMOTE_HOST_COWORK):
1423
+ return pinned
1424
+ if pinned in ("local", "none", "off"):
1425
+ return ""
1426
+ env_type = os.environ.get(_REMOTE_ENV_TYPE_ENV, "").strip().lower()
1427
+ if env_type.startswith("cloud"):
1428
+ return REMOTE_HOST_CLOUD
1429
+ if "cowork" in env_type:
1430
+ return REMOTE_HOST_COWORK
1431
+ if os.environ.get(_CLOUD_KIT_ENV, "").strip():
1432
+ return REMOTE_HOST_CLOUD
1433
+ if os.environ.get(_CLOUD_SESSION_ID_ENV, "").strip():
1434
+ return REMOTE_HOST_CLOUD
1435
+ for env_var in _CLAUDE_PLUGIN_ENVS:
1436
+ val = os.environ.get(env_var, "")
1437
+ if val and _COWORK_SYNCED_PLUGIN_MARKER in val.replace("\\", "/"):
1438
+ return REMOTE_HOST_COWORK
1439
+ # Observed in every Cowork VM. The cloud VM sets it too, but a cloud
1440
+ # VM always carries the session id and the cloud environment type,
1441
+ # which returned above, so reaching here with it means Cowork.
1442
+ if os.environ.get(_COWORK_CONTAINER_ENV, "").strip():
1443
+ return REMOTE_HOST_COWORK
1444
+ if _truthy_env(_COWORK_REMOTE_ENV):
1445
+ return REMOTE_HOST_UNKNOWN
1446
+ except Exception:
1447
+ pass
1448
+ return ""
1449
+
1450
+
1451
+ def remote_host() -> str:
1452
+ """Which hosted VM this Claude Code process runs in: ``"cloud"``,
1453
+ ``"cowork"``, ``"remote"`` (a hosted VM of unknown kind) or ``""`` for a
1454
+ local machine.
1455
+
1456
+ A REFINEMENT of the claude runtime, not a new runtime. Signals, in order:
1457
+
1458
+ 1. ``TOKEN_OPTIMIZER_REMOTE_HOST`` = ``cloud`` / ``cowork`` / ``local``:
1459
+ an explicit pin for anyone whose host exports an unexpected mix.
1460
+ 2. ``CLAUDE_CODE_REMOTE_ENVIRONMENT_TYPE``: ``cloud_default`` (observed
1461
+ in the Anthropic-hosted VM) or any ``cloud*`` value means cloud; a
1462
+ value containing ``cowork`` means Cowork; anything else is no signal.
1463
+ 3. ``TOKEN_OPTIMIZER_CLOUD_KIT_VERSION`` set (the cloud kit's runner
1464
+ exports it, only inside a VM with ``CLAUDE_CODE_REMOTE=true``): cloud.
1465
+ 4. ``CLAUDE_CODE_REMOTE_SESSION_ID`` set (``cse_...``): cloud. Observed
1466
+ in every live cloud probe.
1467
+ 5. ``CLAUDE_PLUGIN_ROOT`` / ``CLAUDE_PLUGIN_DATA`` under
1468
+ ``/plugins/synced/``, or ``CLAUDE_CODE_CONTAINER_ID`` set: Cowork.
1469
+ Only reached with no cloud evidence: the cloud VM carries both (a
1470
+ ``plugins/synced/`` dir for account plugin sync, and a container id),
1471
+ but always alongside the session id and environment type.
1472
+ 6. ``CLAUDE_CODE_REMOTE`` truthy with none of the above: ``"remote"``.
1473
+ It is the documented "running in a remote web environment" signal
1474
+ (code.claude.com hooks docs) but says nothing about which host, so it
1475
+ earns neither the Cowork caveats nor the cloud lean profile.
1476
+
1477
+ ``AI_AGENT`` is NOT a signal: native Claude Code (the local CLI)
1478
+ exports ``AI_AGENT=claude-code_<version>_harness`` into every hook
1479
+ subprocess, so the ``_harness`` marker is ambiguous (see PR #142).
1480
+
1481
+ Never raises; a missing/blank env just contributes no signal.
1482
+ """
1483
+ return _resolve_remote_host()
1484
+
1485
+
1486
+ def is_claude_code_cloud() -> bool:
1487
+ """True inside a Claude Code cloud session (claude.ai/code, ``--cloud``,
1488
+ routines) on positive evidence: the pin, the environment type, the kit's
1489
+ runner or the cloud session id. An ephemeral Ubuntu VM, running as root, no
1490
+ status line, no browser, thrown away when the session is reclaimed. A bare
1491
+ ``CLAUDE_CODE_REMOTE=true`` is not enough (see :func:`remote_host`).
1492
+ """
1493
+ return _resolve_remote_host() == REMOTE_HOST_CLOUD
1494
+
1495
+
1496
+ def is_cowork() -> bool:
1497
+ """True when running inside Claude Cowork (a Claude Code VM host).
1498
+
1499
+ A REFINEMENT of the claude runtime, not a new runtime: ``detect_runtime()``
1500
+ still returns ``"claude"`` inside Cowork. Resolved by :func:`remote_host`:
1501
+ the pin, a ``*cowork*`` environment type, or (with no cloud evidence) a
1502
+ ``/plugins/synced/`` plugin root/data path or ``CLAUDE_CODE_CONTAINER_ID``.
1503
+ ``CLAUDE_CODE_REMOTE`` alone does not mean Cowork. Never raises.
1504
+ """
1505
+ return _resolve_remote_host() == REMOTE_HOST_COWORK
1506
+
1507
+
1508
+ def is_remote_vm() -> bool:
1509
+ """True in either hosted VM (Claude Code cloud or Cowork)."""
1510
+ return bool(remote_host())
1511
+
1512
+
1513
+ def run_origin() -> str:
1514
+ """Where this process runs, for trends rows: ``cloud``, ``cowork``,
1515
+ ``remote`` (hosted VM of unknown kind) or ``local``. Lets a later import of a cloud VM's trends.db (or a teleported
1516
+ transcript) be told apart from the local machine's own rows."""
1517
+ return remote_host() or "local"
1518
+
1519
+
1520
+ # --- Project config layer ---------------------------------------------------
1521
+ # config.json lives in the user's home, which a Claude Code cloud VM throws away
1522
+ # with the session, so opt-outs, consent and feature toggles reset every cloud
1523
+ # session. A repo can carry them instead, in a committed, non-secret file:
1524
+ #
1525
+ # $CLAUDE_PROJECT_DIR/.claude/token-optimizer.json
1526
+ #
1527
+ # CLOUD ONLY. The file is read only inside a Claude Code cloud VM
1528
+ # (is_claude_code_cloud(): positive evidence, see remote_host()). On a desktop
1529
+ # it is ignored entirely: there the user's own config.json persists, and a
1530
+ # cloned repo must never steer machine-wide state (daemon_disabled stopping the
1531
+ # global dashboard revive, pricing_tier rewriting the cost_saved_usd stored in
1532
+ # the shared trends.db, v5 feature flags) just because a session opened in it.
1533
+ #
1534
+ # Precedence, highest first (every reader follows it):
1535
+ # 1. environment variable (TOKEN_OPTIMIZER_*)
1536
+ # 2. user config.json (<runtime-home>/token-optimizer/config.json, or the
1537
+ # plugin-data config the dashboard toggles write)
1538
+ # 3. this project file
1539
+ # 4. built-in default
1540
+ # So a user's own choice always beats the repo's, and the repo only fills keys
1541
+ # the user never set. Only the allowlisted, non-secret keys below are honoured
1542
+ # (everything else is ignored), values must be booleans or short strings, the
1543
+ # file must be a regular, non-symlink file under 64 KB, and Token Optimizer
1544
+ # never writes it: a team commits it by hand.
1545
+ PROJECT_CONFIG_RELPATH = (".claude", "token-optimizer.json")
1546
+ _PROJECT_CONFIG_MAX_BYTES = 64 * 1024
1547
+ _PROJECT_CONFIG_KEYS = frozenset({
1548
+ "read_cache_enabled",
1549
+ "daemon_disabled",
1550
+ "quality_bar_disabled",
1551
+ "vscode_ext_disabled",
1552
+ "pricing_tier",
1553
+ })
1554
+ # Feature gates (v5_quality_nudges, v5_bash_compress, ...). The onboarding
1555
+ # marker v5_welcome_shown is excluded: consent and onboarding are a person's
1556
+ # own record, never a repo's (and run.py's consent gate fails open on a fresh
1557
+ # VM, so a cloud session is not blocked without it).
1558
+ _PROJECT_CONFIG_KEY_RE = re.compile(r"^v5_(?!welcome_shown$)[a-z0-9_]{1,48}$")
1559
+ _PROJECT_CONFIG_MAX_STR = 32
1560
+
1561
+
1562
+ def _project_config_path():
1563
+ raw = os.environ.get("CLAUDE_PROJECT_DIR", "").strip()
1564
+ if not raw:
1565
+ return None
1566
+ try:
1567
+ root = Path(raw)
1568
+ if not root.is_absolute():
1569
+ return None
1570
+ return root.joinpath(*PROJECT_CONFIG_RELPATH)
1571
+ except (OSError, ValueError):
1572
+ return None
1573
+
1574
+
1575
+ def project_config() -> dict:
1576
+ """The repo-scoped settings layer (see the block comment above), filtered
1577
+ to the allowlist. Empty outside a Claude Code cloud VM, and when
1578
+ CLAUDE_PROJECT_DIR is unset, the file is missing/unsafe/malformed, or
1579
+ nothing in it is allowed. Never raises."""
1580
+ if not is_claude_code_cloud():
1581
+ return {}
1582
+ return _project_config_file()
1583
+
1584
+
1585
+ @functools.lru_cache(maxsize=None)
1586
+ def _project_config_file() -> dict:
1587
+ path = _project_config_path()
1588
+ if path is None:
1589
+ return {}
1590
+ try:
1591
+ if path.is_symlink() or not path.is_file():
1592
+ return {}
1593
+ if path.stat().st_size > _PROJECT_CONFIG_MAX_BYTES:
1594
+ return {}
1595
+ data = json.loads(path.read_text(encoding="utf-8-sig"))
1596
+ except (OSError, ValueError, UnicodeDecodeError):
1597
+ return {}
1598
+ if not isinstance(data, dict):
1599
+ return {}
1600
+ out = {}
1601
+ for key, value in data.items():
1602
+ if not isinstance(key, str):
1603
+ continue
1604
+ if key not in _PROJECT_CONFIG_KEYS and not _PROJECT_CONFIG_KEY_RE.match(key):
1605
+ continue
1606
+ if isinstance(value, bool):
1607
+ out[key] = value
1608
+ elif isinstance(value, str) and 0 < len(value) <= _PROJECT_CONFIG_MAX_STR:
1609
+ out[key] = value
1610
+ return out
1611
+
1612
+
1613
+ def project_config_value(key: str, default=None):
1614
+ """One key from :func:`project_config`, or ``default``."""
1615
+ return project_config().get(key, default)
1616
+
1617
+
1618
+ def claude_home() -> Path:
1619
+ """Return Claude Code's home directory.
1620
+
1621
+ Honors CLAUDE_CONFIG_DIR — Claude Code's official override for where it
1622
+ stores projects/, settings.json, etc. Unlike CODEX_HOME/HERMES_HOME (which
1623
+ route through ``_safe_home_from_env`` and are confined under ``$HOME``),
1624
+ Claude Code permits CLAUDE_CONFIG_DIR to point ANYWHERE: containers, CI
1625
+ runners, a relocated config volume, a non-home ``$HOME``. Confining it to
1626
+ ``$HOME`` would silently re-pin those users to a stale ~/.claude — the exact
1627
+ failure this is meant to fix. So this resolver accepts any ABSOLUTE,
1628
+ EXISTING, NON-SYMLINK directory (keeping the symlink + relative-path
1629
+ rejection for traversal safety) and only falls back to ~/.claude when the
1630
+ override is unset or unusable.
1631
+
1632
+ statusline.js (_claudeHome) and vscode-extension/src/paths.ts
1633
+ (resolveClaudeDir) reimplement these rules; change all three together or
1634
+ the status line and the hooks read different dirs (#198).
1635
+ """
1636
+ fallback = _safe_home() / ".claude"
1637
+ raw = os.environ.get(_CLAUDE_CONFIG_DIR_ENV, "").strip()
1638
+ if not raw:
1639
+ return fallback
1640
+ try:
1641
+ # expanduser() raises RuntimeError for an unknown ~user (a typo, or ~\x
1642
+ # on POSIX). Uncaught, that crashed every hook at import; reject instead.
1643
+ candidate = Path(raw).expanduser()
1644
+ if candidate.is_absolute() and candidate.is_dir() and not candidate.is_symlink():
1645
+ return candidate.resolve(strict=False)
1646
+ except (OSError, RuntimeError):
1647
+ pass
1648
+ print(
1649
+ f"[Token Optimizer] Warning: {_CLAUDE_CONFIG_DIR_ENV}={raw!r} rejected "
1650
+ "(not an absolute, existing, non-symlink directory). Using default.",
1651
+ file=sys.stderr,
1652
+ )
1653
+ return fallback
1654
+
1655
+
1656
+ def codex_home() -> Path:
1657
+ """Return Codex's home directory, safely honoring CODEX_HOME when valid."""
1658
+ return _safe_home_from_env(_CODEX_HOME_ENV, _safe_home() / ".codex")
1659
+
1660
+
1661
+ def settings_env_value(name: str) -> str:
1662
+ """Read ``name`` from the ``env`` block of the user's settings.json.
1663
+
1664
+ The single resolver for ``TOKEN_OPTIMIZER_*`` env knobs that out-of-process
1665
+ callers (hooks, tests, the daemon) need even when the host did not inject
1666
+ them. Scope is deliberately narrow: only the GLOBAL settings file
1667
+ (``claude_home() / "settings.json"``) is read — hooks run with the repo as
1668
+ cwd, so consulting project-level settings would let a checked-in
1669
+ ``.claude/settings.json`` silently repoint a security feature's config.
1670
+
1671
+ Only a regular file is read: ``is_file()`` is False for a FIFO, socket,
1672
+ directory or broken symlink, so a special file at that path can never
1673
+ block ``open()`` on a hot hook path. Never raises; returns "" when unset.
1674
+ """
1675
+ try:
1676
+ path = claude_home() / "settings.json"
1677
+ if not path.is_file() or path.stat().st_size > 1_048_576:
1678
+ return ""
1679
+ with open(path, "r", encoding="utf-8") as f:
1680
+ settings = json.load(f)
1681
+ env_block = settings.get("env", {}) if isinstance(settings, dict) else {}
1682
+ if not isinstance(env_block, dict):
1683
+ return ""
1684
+ return str(env_block.get(name, "") or "").strip()
1685
+ except Exception:
1686
+ return ""
1687
+
1688
+
1689
+ def hermes_home() -> Path:
1690
+ """Return Hermes's home directory, safely honoring HERMES_HOME when valid."""
1691
+ return _safe_home_from_env(_HERMES_HOME_ENV, _safe_home() / ".hermes")
1692
+
1693
+
1694
+ def copilot_home(*, mnt_root: Path | None = None) -> Path:
1695
+ """Return GitHub Copilot CLI's home directory (~/.copilot by default).
1696
+
1697
+ Resolution precedence (COPILOT_HOME is Copilot's OWN variable,
1698
+ so TO must not depend on the user setting it):
1699
+
1700
+ 1. TOKEN_OPTIMIZER_COPILOT_HOME — Token Optimizer's own override. Honored
1701
+ under the strict under-``$HOME`` guard, or the WSL-root ``/mnt/``
1702
+ opt-in. This is the ONLY override users should set to disambiguate a
1703
+ multi-profile Windows host; it never collides with Copilot's config.
1704
+ 2. COPILOT_HOME — read for back-compat as a location hint, but a WSL
1705
+ ``/mnt/`` value earns a loud guardrail warning because the native
1706
+ Windows Copilot CLI reads the same var and a /mnt value breaks its own
1707
+ logging.
1708
+ 3. WSL-root auto-detect — when running as root under WSL (``$HOME=/root``)
1709
+ and neither override is set, probe ``/mnt/c/Users/*/.copilot`` and use
1710
+ the sole match, so no env var is needed at all.
1711
+ 4. ``$HOME/.copilot`` — the default.
1712
+
1713
+ This is where Token Optimizer's own Copilot data lives
1714
+ (``<home>/token-optimizer/``) — never ~/.claude. ``mnt_root`` is a
1715
+ test-injection parameter (never set in production) so tests can substitute a
1716
+ temp dir for ``/mnt`` on non-Linux hosts.
1717
+ """
1718
+ fallback = _safe_home() / ".copilot"
1719
+
1720
+ # 1. TO's own namespaced override wins (no collision with Copilot's config).
1721
+ if os.environ.get(_TO_COPILOT_HOME_ENV, "").strip():
1722
+ return _safe_home_from_env(_TO_COPILOT_HOME_ENV, fallback, mnt_root=mnt_root)
1723
+
1724
+ # 2. Copilot's own COPILOT_HOME — back-compat location hint, guarded.
1725
+ cp_raw = os.environ.get(_COPILOT_HOME_ENV, "").strip()
1726
+ if cp_raw:
1727
+ _warn_mnt_copilot_home(cp_raw)
1728
+ return _safe_home_from_env(_COPILOT_HOME_ENV, fallback, mnt_root=mnt_root)
1729
+
1730
+ # 3. WSL-root: auto-detect the Windows-profile Copilot home (no env var).
1731
+ auto = _autodetect_wsl_copilot_home(mnt_root=mnt_root)
1732
+ if auto is not None:
1733
+ return auto
1734
+
1735
+ # 4. Default.
1736
+ return fallback
1737
+
1738
+
1739
+ def antigravity_home() -> Path:
1740
+ """Return Google Antigravity's home directory (~/.gemini by default).
1741
+
1742
+ Honors TOKEN_OPTIMIZER_ANTIGRAVITY_HOME under the strict under-``$HOME``
1743
+ guard. This is where Antigravity's own data lives (antigravity-cli/,
1744
+ antigravity/, antigravity-ide/) AND where Token Optimizer's Antigravity data
1745
+ lives (<home>/token-optimizer/) — never ~/.claude.
1746
+ """
1747
+ return _safe_home_from_env(_TO_ANTIGRAVITY_HOME_ENV, _safe_home() / ".gemini")
1748
+
1749
+
1750
+ def _warn_mnt_grok_home(raw: str) -> None:
1751
+ """Warn that a /mnt GROK_HOME breaks native-Windows Grok Build.
1752
+
1753
+ Grok Build reads GROK_HOME itself; a WSL ``/mnt/...`` value — meaningless on
1754
+ native Windows — relocates Grok's own sessions/hooks/config into a path that
1755
+ doesn't exist, so it silently stops persisting. Steer the user to unset it
1756
+ or to use Token Optimizer's own TOKEN_OPTIMIZER_GROK_HOME.
1757
+ """
1758
+ if not _looks_like_mnt_path(raw):
1759
+ return
1760
+ _warn_once(
1761
+ f"[Token Optimizer] Warning: GROK_HOME={raw!r} is a WSL /mnt path. "
1762
+ "Grok Build reads GROK_HOME too, and a /mnt value breaks its own "
1763
+ "session persistence on native Windows. Unset GROK_HOME, or use "
1764
+ "TOKEN_OPTIMIZER_GROK_HOME for Token Optimizer only."
1765
+ )
1766
+
1767
+
1768
+ def grok_home(*, mnt_root: Path | None = None) -> Path:
1769
+ """Return Grok Build's home directory (~/.grok by default).
1770
+
1771
+ Resolution precedence:
1772
+ 1. TOKEN_OPTIMIZER_GROK_HOME — Token Optimizer's own override (strict
1773
+ under-``$HOME`` guard, or the WSL-root ``/mnt/`` opt-in). The only var
1774
+ users should set for Token Optimizer's benefit.
1775
+ 2. GROK_HOME — Grok Build's OWN config variable (back-compat location
1776
+ hint); a WSL ``/mnt/`` value earns a guardrail warning because the
1777
+ native Grok CLI reads the same var and a /mnt value breaks its own
1778
+ session persistence.
1779
+ 3. ``$HOME/.grok`` — the default.
1780
+
1781
+ This is where Token Optimizer's own Grok data lives
1782
+ (``<home>/token-optimizer/``) — never ~/.claude. ``mnt_root`` is a
1783
+ test-injection parameter (never set in production).
1784
+ """
1785
+ fallback = _safe_home() / ".grok"
1786
+
1787
+ # 1. TO's own namespaced override wins (no collision with Grok's config).
1788
+ if os.environ.get(_TO_GROK_HOME_ENV, "").strip():
1789
+ return _safe_home_from_env(_TO_GROK_HOME_ENV, fallback, mnt_root=mnt_root)
1790
+
1791
+ # 2. Grok's own GROK_HOME — back-compat location hint, guarded.
1792
+ grok_raw = os.environ.get(_GROK_HOME_ENV, "").strip()
1793
+ if grok_raw:
1794
+ _warn_mnt_grok_home(grok_raw)
1795
+ return _safe_home_from_env(_GROK_HOME_ENV, fallback, mnt_root=mnt_root)
1796
+
1797
+ # 3. Default.
1798
+ return fallback
1799
+
1800
+
1801
+ def _xdg_base(env_var: str, default_rel: str) -> Path:
1802
+ """Resolve an XDG base dir, falling back to ~/<default_rel>.
1803
+
1804
+ Honors an absolute XDG_* override; otherwise uses the home-relative default.
1805
+ """
1806
+ raw = os.environ.get(env_var, "").strip()
1807
+ if raw:
1808
+ candidate = Path(raw).expanduser()
1809
+ if candidate.is_absolute():
1810
+ return candidate
1811
+ return _safe_home() / default_rel
1812
+
1813
+
1814
+ def cursor_home() -> Path:
1815
+ """Return Cursor's home directory (~/.cursor by default).
1816
+
1817
+ Cursor stores its hooks.json, transcripts and chats under ~/.cursor. Cursor
1818
+ has no documented CURSOR_HOME env var of its own, so the only override TO
1819
+ exposes is its namespaced TOKEN_OPTIMIZER_CURSOR_HOME, honoured under the
1820
+ strict under-``$HOME`` guard (a value outside $HOME falls back to ~/.cursor
1821
+ with the once-per-process warning). This is where Token Optimizer's own
1822
+ Cursor data lives (``<home>/token-optimizer/``) — never ~/.claude.
1823
+ """
1824
+ return _safe_home_from_env(_TO_CURSOR_HOME_ENV, _safe_home() / ".cursor")
1825
+
1826
+
1827
+ def opencode_config_home() -> Path:
1828
+ """Return OpenCode's config directory (~/.config/opencode by default).
1829
+
1830
+ Honors OPENCODE_CONFIG_DIR when it points at a safe directory under home,
1831
+ else XDG_CONFIG_HOME/opencode, else ~/.config/opencode.
1832
+ """
1833
+ default = _xdg_base("XDG_CONFIG_HOME", ".config") / "opencode"
1834
+ return _safe_home_from_env("OPENCODE_CONFIG_DIR", default)
1835
+
1836
+
1837
+ def opencode_data_home() -> Path:
1838
+ """Return OpenCode's data directory (~/.local/share/opencode by default).
1839
+
1840
+ Honors OPENCODE_DATA_DIR when it points at a safe directory under home,
1841
+ else XDG_DATA_HOME/opencode, else ~/.local/share/opencode. This is where
1842
+ Token Optimizer's own data would live under OpenCode — never ~/.claude.
1843
+ """
1844
+ default = _xdg_base("XDG_DATA_HOME", ".local/share") / "opencode"
1845
+ return _safe_home_from_env("OPENCODE_DATA_DIR", default)
1846
+
1847
+
1848
+ def runtime_home() -> Path:
1849
+ """Return the home directory used by the active runtime."""
1850
+ runtime = detect_runtime()
1851
+
1852
+ if runtime == _RUNTIME_CODEX:
1853
+ return codex_home()
1854
+
1855
+ if runtime == _RUNTIME_HERMES:
1856
+ return hermes_home()
1857
+
1858
+ if runtime == _RUNTIME_OPENCODE:
1859
+ return opencode_data_home()
1860
+
1861
+ if runtime == _RUNTIME_COPILOT:
1862
+ return copilot_home()
1863
+
1864
+ if runtime == _RUNTIME_CURSOR:
1865
+ return cursor_home()
1866
+
1867
+ if runtime == _RUNTIME_ANTIGRAVITY:
1868
+ return antigravity_home()
1869
+
1870
+ if runtime == _RUNTIME_GROK:
1871
+ return grok_home()
1872
+
1873
+ if runtime == _RUNTIME_DEVIN:
1874
+ from devin_state import home as devin_home
1875
+ return devin_home()
1876
+
1877
+ return claude_home()
1878
+
1879
+
1880
+ def plugin_data_env_vars() -> tuple[str, ...]:
1881
+ """Return plugin-data env vars in runtime-specific priority order."""
1882
+ if detect_runtime() in (
1883
+ _RUNTIME_CODEX,
1884
+ _RUNTIME_HERMES,
1885
+ _RUNTIME_OPENCODE,
1886
+ _RUNTIME_COPILOT,
1887
+ _RUNTIME_CURSOR,
1888
+ _RUNTIME_ANTIGRAVITY,
1889
+ _RUNTIME_GROK,
1890
+ _RUNTIME_DEVIN,
1891
+ ):
1892
+ return ("TOKEN_OPTIMIZER_PLUGIN_DATA",)
1893
+ return ("CLAUDE_PLUGIN_DATA", "TOKEN_OPTIMIZER_PLUGIN_DATA")
1894
+
1895
+
1896
+ def runtime_name_for_humans() -> str:
1897
+ """Return a display label for logs and user-facing output."""
1898
+ runtime = detect_runtime()
1899
+ if runtime == _RUNTIME_CODEX:
1900
+ return "Codex"
1901
+ if runtime == _RUNTIME_HERMES:
1902
+ return "Hermes"
1903
+ if runtime == _RUNTIME_OPENCODE:
1904
+ return "OpenCode"
1905
+ if runtime == _RUNTIME_COPILOT:
1906
+ return "GitHub Copilot"
1907
+ if runtime == _RUNTIME_CURSOR:
1908
+ return "Cursor"
1909
+ if runtime == _RUNTIME_ANTIGRAVITY:
1910
+ return "Google Antigravity"
1911
+ if runtime == _RUNTIME_GROK:
1912
+ return "Grok Build"
1913
+ if runtime == _RUNTIME_DEVIN:
1914
+ return "Devin CLI"
1915
+ # Cowork and Claude Code cloud are the claude runtime in a VM; label the
1916
+ # refinement without changing the runtime it resolves to.
1917
+ if runtime == _RUNTIME_CLAUDE:
1918
+ host = remote_host()
1919
+ if host == REMOTE_HOST_COWORK:
1920
+ return "Claude Code (Cowork)"
1921
+ if host == REMOTE_HOST_CLOUD:
1922
+ return "Claude Code (cloud)"
1923
+ return "Claude Code"