@alexgreensh/token-optimizer 0.0.0-stage → 5.13.50

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 +149 -0
  10. package/hooks/posttooluse_runner.py +1110 -0
  11. package/hooks/python-launcher.sh +816 -0
  12. package/hooks/run.py +776 -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 +150 -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 +3612 -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 +129 -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 +72 -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 +376 -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 +991 -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 +277 -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 +423 -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 +397 -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 +713 -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 +58739 -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 +1893 -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,816 @@
1
+ #!/usr/bin/env bash
2
+ # Locate a usable Python 3 interpreter and exec it with the given arguments.
3
+ # Survives:
4
+ # - macOS / Linux (python3 on PATH)
5
+ # - Windows python.org installs at spaced paths like "C:\Program Files\Python313\"
6
+ # - Windows py-launcher-only installs (py -3)
7
+ # - Windows Store Python (real installs proven alive via a flash-free
8
+ # GUI-twin proof-of-life probe, console --version probe as the fallback
9
+ # authority; non-functional AppExecutionAlias stubs skipped automatically)
10
+ # On Windows (Git Bash/MSYS), exec prefers the GUI-subsystem twin over the
11
+ # console binary to avoid the per-hook console-window flash and orphaned
12
+ # conhost.exe: python.exe/python3.exe swap to pythonw.exe, and py.exe (the
13
+ # py-launcher) swaps to pyw.exe beside it, so py-launcher-only installs no
14
+ # longer flash. See _maybe_swap_to_pythonw for the constraints.
15
+ # Exits 127 with a diagnostic message if none found.
16
+
17
+ set -eu
18
+ # A failed `exec` (bad shebang, file gone between discovery and exec, ENOEXEC)
19
+ # must return to the caller instead of terminating the shell non-zero, so
20
+ # discovery can advance to the next candidate and the launcher keeps its
21
+ # exit-0 guarantee (see HOOK-SAFETY at the bottom). `execfail` is half of that;
22
+ # _try_exec below is the other half.
23
+ shopt -s execfail
24
+
25
+ # _try_exec <interpreter> [args...] -- exec, returning 1 if the exec fails.
26
+ # bash 3.2 (macOS /bin/bash) exits the shell on a failed `exec` whenever errexit
27
+ # is on, even with execfail and even when the call sits in an `||` list. So
28
+ # errexit is dropped for the exec itself and restored on the only path that
29
+ # returns (a failed exec). A successful exec never returns.
30
+ _try_exec() {
31
+ set +e
32
+ exec "$@"
33
+ set -e
34
+ return 1
35
+ }
36
+ # Extglob enables +([0-9]) in the version-number case patterns below so
37
+ # the glob is anchored to the path-component boundary. Without it, * in a
38
+ # case pattern crosses / and Python[23]* matches Python3-evil/python.exe.
39
+ shopt -s extglob
40
+
41
+ # Known-safe prefixes for Python interpreter binaries.
42
+ # Binaries outside these directories are rejected even if on PATH.
43
+ # This prevents a compromised PATH entry from hijacking the interpreter.
44
+ # All prefixes are hardcoded (not derived from PATH-controlled binaries
45
+ # like `brew --prefix`, which would be circular trust).
46
+ _SAFE_PREFIXES="/usr/bin /usr/local/bin /opt/homebrew/bin /opt/homebrew/opt /home/linuxbrew/.linuxbrew/bin"
47
+
48
+ # _canonicalize_dir <dir> -> canonical absolute path via $_CANON_DIR
49
+ #
50
+ # `cd -P` resolves every symlink level portably (no realpath/readlink -f, which
51
+ # are absent or inconsistent on older macOS and MSYS). The old $(cd ...; pwd -P)
52
+ # form forked a bash subshell per call -- a whole process each on MSYS -- so
53
+ # this runs the builtin `cd` in a plain if-block (no subshell). That makes the
54
+ # jump visible to the whole launcher, and the launcher then `exec`s the hook
55
+ # interpreter, so the caller's state is put back before returning: the working
56
+ # directory (the hook must run in the project the host launched it from, not in
57
+ # the plugin's hooks/ dir), $PWD (logical, as the host had it) and OLDPWD
58
+ # (restored, or left unset if it was unset -- never exported as an empty string).
59
+ #
60
+ # `builtin cd` everywhere: a user who exports a `cd` shell function (the classic
61
+ # "cd then ls" wrapper; bash imports it from the environment) would otherwise
62
+ # have it run here, and whatever it prints would land in the hook's stdout ahead
63
+ # of the hook's own output (it used to be captured by the old $(...) form).
64
+ #
65
+ # Never leave a directory we cannot return to: if the start dir was removed
66
+ # (worktree cleanup), lost its +x bit, or its path no longer leads back to the
67
+ # same directory, the jump would be one-way and the interpreter would wake up
68
+ # inside the plugin's hooks/ dir with a PWD that points there. In that case skip
69
+ # the canonicalisation (callers treat failure as "cache off for this run").
70
+ # `-ef` is a builtin test (no fork) that follows symlinks, so a logical $PWD
71
+ # through a symlink still passes.
72
+ _canonicalize_dir() {
73
+ local _start=$PWD _had_old=${OLDPWD+x} _oldpwd=${OLDPWD:-} _rc=1
74
+ if [ -n "$_start" ] && [ -d "$_start" ] && [ -x "$_start" ] && [ "$_start" -ef . ]; then
75
+ :
76
+ else
77
+ return 1
78
+ fi
79
+ if CDPATH='' builtin cd -P -- "$1" 2>/dev/null; then
80
+ _CANON_DIR=$PWD
81
+ _rc=0
82
+ # Best effort: if the start dir vanished or lost +x there is nothing
83
+ # better to restore, and the launcher must still never abort (set -e).
84
+ CDPATH='' builtin cd -- "$_start" 2>/dev/null || :
85
+ fi
86
+ if [ -n "$_had_old" ]; then OLDPWD=$_oldpwd; else unset OLDPWD; fi
87
+ return "$_rc"
88
+ }
89
+
90
+ # Canonicalize a file path (resolve symlinks). exec follows symlinks, so a
91
+ # user-owned symlink pointing at a hostile target must be judged by the TARGET.
92
+ # realpath/`readlink -f` are absent on older macOS; fall back to a `pwd -P` walk
93
+ # of the parent (the leaf's own ownership is still checked via `-O`, which
94
+ # dereferences symlinks). Prints the resolved path, or fails.
95
+ _to_realpath() {
96
+ local p="$1" d b
97
+ if command -v realpath >/dev/null 2>&1; then
98
+ realpath "$p" 2>/dev/null && return 0
99
+ fi
100
+ if readlink -f "$p" >/dev/null 2>&1; then
101
+ readlink -f "$p" 2>/dev/null && return 0
102
+ fi
103
+ d=${p%/*}
104
+ if [ "$d" = "$p" ]; then d=.; elif [ -z "$d" ]; then d=/; fi
105
+ b=${p##*/}
106
+ _canonicalize_dir "$d" || return 1
107
+ printf '%s/%s\n' "$_CANON_DIR" "$b"
108
+ }
109
+
110
+ # Print a path's permission bits as octal, ZERO-PADDED to at least 3 digits.
111
+ # GNU stat first, then BSD/macOS stat. Fails if neither works (caller refuses
112
+ # trust). The pad matters: GNU `stat -c %a` prints "2" for mode 0002, and the
113
+ # caller's last-3-digit slice would then read EMPTY group/other digits -- a set
114
+ # write bit reading as clean, a false-accept. Flooring to 3 digits makes the
115
+ # group/other-writable check robust to stat's short formatting.
116
+ _to_mode() {
117
+ local mode
118
+ mode=$(stat -c '%a' "$1" 2>/dev/null || stat -f '%Lp' "$1" 2>/dev/null) || return 1
119
+ [ -n "$mode" ] || return 1
120
+ while [ "${#mode}" -lt 3 ]; do mode="0$mode"; done
121
+ printf '%s\n' "$mode"
122
+ }
123
+
124
+ # True IFF the interpreter (after symlink resolution) AND its containing dir are
125
+ # both owned by the effective uid and writable by NOBODY else (not group, not
126
+ # other) -- the trust boundary ssh/sudo/git(safe.directory) use. This is a pure
127
+ # stat check; it never runs the target (deciding trust by executing the binary
128
+ # would mean running attacker code to find out whether it is safe). It lets any
129
+ # version-manager shim (mise/pyenv/asdf/rbenv/custom dir, under any home root)
130
+ # be trusted generically, while a hijack `python3` in a world-writable or
131
+ # foreign-owned dir stays refused. POSIX only -- the caller gates out Windows,
132
+ # where stat ownership/mode is faked under Git-Bash/MSYS.
133
+ _to_owned_unwritable() {
134
+ local p="$1" real dir mode g o
135
+ real=$(_to_realpath "$p") || return 1
136
+ [ -n "$real" ] || return 1
137
+ dir=$(dirname "$real") || return 1
138
+ # Ownership: `-O` == owned by the effective uid (portable, no stat parse;
139
+ # dereferences symlinks so the resolved target's owner is what's checked).
140
+ [ -O "$real" ] || return 1
141
+ [ -O "$dir" ] || return 1
142
+ # Not group- or other-writable, on BOTH the file and its dir. The low 3
143
+ # octal digits are user/group/other; a set write bit makes the digit 2,3,6,7.
144
+ mode=$(_to_mode "$real") || return 1
145
+ mode=${mode: -3}; g=${mode:1:1}; o=${mode:2:1}
146
+ case "$g" in 2|3|6|7) return 1 ;; esac
147
+ case "$o" in 2|3|6|7) return 1 ;; esac
148
+ mode=$(_to_mode "$dir") || return 1
149
+ mode=${mode: -3}; g=${mode:1:1}; o=${mode:2:1}
150
+ case "$g" in 2|3|6|7) return 1 ;; esac
151
+ case "$o" in 2|3|6|7) return 1 ;; esac
152
+ return 0
153
+ }
154
+
155
+ _is_safe_prefix() {
156
+ local IFS=$' \t\n'
157
+ local binpath="$1" prefix
158
+ # Reject path traversal FIRST: a '..' component lets a textual prefix match
159
+ # (e.g. /usr/bin/../../tmp/evil/python3) pass the allow-list globs below yet
160
+ # resolve OUTSIDE a trusted dir at exec time. Interpreter paths are absolute
161
+ # and never legitimately contain a '..' path component.
162
+ case "$binpath" in
163
+ *"/../"*|*"/..") return 1 ;;
164
+ esac
165
+ for prefix in $_SAFE_PREFIXES; do
166
+ case "$binpath" in
167
+ "$prefix"/*) return 0 ;;
168
+ esac
169
+ done
170
+ # Windows install locations (git-bash/MSYS path form, e.g. /c/...).
171
+ # Drive-letter-anchored to preserve the anti-PATH-hijack intent.
172
+ # Version-number suffixes block directory-name spoofing (e.g. Python3-evil).
173
+ case "$binpath" in
174
+ # +([0-9]) anchors the version suffix to digits-only so a spoofed
175
+ # dir name like Python3-evil cannot pass (previously * crossed / and
176
+ # matched Python3-evil/python.exe). The trailing /* requires a path
177
+ # separator after the version component.
178
+ /[a-zA-Z]/Program\ Files/Python[23]+([0-9])/*) return 0 ;;
179
+ /[a-zA-Z]/Program\ Files\ \(x86\)/Python[23]+([0-9])/*) return 0 ;;
180
+ /[a-zA-Z]/Python3+([0-9])/*) return 0 ;;
181
+ /[a-zA-Z]/Users/*/AppData/Local/Programs/Python/*) return 0 ;;
182
+ /[a-zA-Z]/Users/*/AppData/Local/Microsoft/WindowsApps/*) return 0 ;;
183
+ # Version-manager shims, Windows default data dirs. Hardcoded default
184
+ # locations only -- never derived from MISE_DATA_DIR/PYENV_ROOT, which
185
+ # would reopen the PATH-hijack vector. POSIX shims are covered generically
186
+ # by the ownership fallback below; Windows has no reliable stat, so its
187
+ # managers are enumerated here. (mise pattern, trekie86.)
188
+ /[a-zA-Z]/Users/*/AppData/Local/mise/shims/*) return 0 ;;
189
+ /[a-zA-Z]/Users/*/.pyenv/pyenv-win/shims/*) return 0 ;;
190
+ # All-users `py` launcher lives in the (admin-only-writable) Windows dir.
191
+ # Exact filename keeps the anti-hijack intent (no wildcard in that dir).
192
+ /[a-zA-Z]/Windows/py.exe) return 0 ;;
193
+ /[a-zA-Z]/Windows/pyw.exe) return 0 ;;
194
+ esac
195
+ # Case-insensitive WindowsApps allow for Windows-style drive-letter
196
+ # paths. On a case-insensitive FS the dir can be any casing; the drive-
197
+ # letter anchor ([a-zA-Z]/) constrains this to Windows-style paths so
198
+ # Linux is unaffected.
199
+ case "$binpath" in
200
+ /[a-zA-Z]/*)
201
+ _path_contains_windowsapps "$binpath" && return 0
202
+ ;;
203
+ esac
204
+ # HYBRID FALLBACK (POSIX only): the hardcoded allowlist above cannot
205
+ # enumerate every version manager (mise/pyenv/asdf/rbenv/...), every custom
206
+ # data dir (MISE_DATA_DIR, PYENV_ROOT), or every home root (/home/*, /root,
207
+ # NFS). Rather than a manager-by-manager treadmill, bless an interpreter the
208
+ # allowlist missed by an ownership/permission gate: it and its dir must be
209
+ # owned by us and writable by nobody else (see _to_owned_unwritable). This is
210
+ # strictly narrower than "any shim dir" -- a hijack python3 in /tmp/evil or
211
+ # another user's tree is still refused -- and it never runs the target.
212
+ # Skipped on Windows: Git-Bash/MSYS stat ownership+mode is unreliable, and
213
+ # its managers are covered by the drive-letter patterns above.
214
+ if ! _is_msys_platform; then
215
+ _to_owned_unwritable "$binpath" && return 0
216
+ fi
217
+ return 1
218
+ }
219
+
220
+ # The cache is an optional optimization only. Any setup, read, or write failure
221
+ # leaves _PY_CACHE_FILE empty (or is ignored) so interpreter discovery proceeds
222
+ # exactly as it did before caching was added.
223
+ _PY_CACHE_FILE=""
224
+
225
+ # Hard ceiling on records in the interpreter-cache dir. The key already
226
+ # dedupes PATH noise (see _setup_interpreter_cache), but candidate churn can
227
+ # still accumulate records slowly (venvs created/deleted over months); cap
228
+ # with oldest-first eviction so the dir can never regrow toward the 174
229
+ # files the whole-PATH checksum produced.
230
+ _PY_CACHE_MAX_FILES=32
231
+
232
+ _is_msys_platform() {
233
+ # Bash supplies OSTYPE on Git Bash/MSYS and Cygwin. Avoid spawning uname
234
+ # on the Windows hot path; retain the probe for other shell environments.
235
+ case "${OSTYPE:-}" in
236
+ msys*|cygwin*) return 0 ;;
237
+ esac
238
+ local platform
239
+ platform=$(uname -s 2>/dev/null) || return 1
240
+ case "$platform" in
241
+ MINGW*|MSYS*|CYGWIN*) return 0 ;;
242
+ esac
243
+ return 1
244
+ }
245
+
246
+ # Windows is case-insensitive, so the WindowsApps directory can appear in
247
+ # any casing (WindowsApps, windowsapps, WINDOWSAPPS, Windowsapps). The old
248
+ # explicit-variant patterns (*/WindowsApps/*|*/windowsapps/*) only covered
249
+ # two casings and would miss others, letting a Store AppExecutionAlias stub
250
+ # through unprobed or skipping a legit Store install in the safe-prefix list.
251
+ # A shell pattern avoids spawning tr on every twin selection.
252
+ _path_contains_windowsapps() {
253
+ case "$1" in
254
+ */[wW][iI][nN][dD][oO][wW][sS][aA][pP][pP][sS]/*) return 0 ;;
255
+ esac
256
+ return 1
257
+ }
258
+
259
+ # Non-cryptographic cache partition only. Every record is still validated
260
+ # against the interpreter safety policy before exec. Bash arithmetic is masked
261
+ # to 32 bits to keep filenames bounded on both 32- and 64-bit shells.
262
+ # LC_ALL=C makes indexing byte-based, independent of the user's locale.
263
+ _cache_checksum() {
264
+ local LC_ALL=C hash=0 char byte
265
+ # read advances linearly; indexing a long Bash string for each byte is
266
+ # quadratic. The here-string adds the same final newline to every key.
267
+ while IFS= read -r -n 1 -d '' char; do
268
+ printf -v byte '%d' "'$char"
269
+ hash=$(( (hash * 65599 + byte) & 4294967295 ))
270
+ done <<< "$1"
271
+ _CACHE_CHECKSUM=$hash
272
+ }
273
+
274
+ _cache_dir_is_per_user() {
275
+ local cache_dir="$1" cache_real root
276
+ # In-place builtin canonicalize (no subshell) -- this runs on every cache
277
+ # HIT on MSYS, where each $(cd ...) fork is a process.
278
+ _canonicalize_dir "$cache_dir" || return 1
279
+ cache_real=$_CANON_DIR
280
+ for root in "${XDG_CACHE_HOME:-}" "${HOME:-}"; do
281
+ [ -n "$root" ] && [ -d "$root" ] || continue
282
+ _canonicalize_dir "$root" || continue
283
+ case "$cache_real" in
284
+ "$_CANON_DIR"/*) return 0 ;;
285
+ esac
286
+ done
287
+ return 1
288
+ }
289
+
290
+ _cache_dir_ready() {
291
+ local cache_dir="$1"
292
+ if [ ! -d "$cache_dir" ]; then
293
+ (umask 077; mkdir -p "$cache_dir") >/dev/null 2>&1 || return 1
294
+ fi
295
+ [ -d "$cache_dir" ] && [ -w "$cache_dir" ] || return 1
296
+ if _is_msys_platform; then
297
+ # Git Bash/MSYS2/Cygwin emulate POSIX ownership, so `test -O` can reject
298
+ # the current user's own directory. Canonical confinement under HOME or
299
+ # XDG_CACHE_HOME supplies the equivalent Windows ACL trust boundary.
300
+ _cache_dir_is_per_user "$cache_dir"
301
+ else
302
+ # On native POSIX, require ownership rather than mere writability so a
303
+ # planted cache record in another user's directory is never trusted.
304
+ [ -O "$cache_dir" ]
305
+ fi
306
+ }
307
+
308
+ # _python_candidate_paths -> sets _CAND_PATHS to the ordered list of PATH
309
+ # entries that contain a python3 / python / py interpreter file.
310
+ #
311
+ # The cache key must change iff find_interpreter() can return a different
312
+ # answer. find_interpreter walks PATH in order and probes
313
+ # $dir/{python3,python,py}{,.exe} (+ .bat/.cmd on Windows), so its answer
314
+ # depends only on PATH entries that HOLD one of those names. Keying on the
315
+ # whole PATH string minted a new record for any PATH churn (one machine
316
+ # accumulated 174 files); keying on the candidate set dedupes every PATH that
317
+ # yields the same discovery answer while still separating PATHs whose answers
318
+ # can differ. No candidates still gets a stable key -- the direct-probe
319
+ # fallback result is equally cacheable. Bash builtins only ([ -e ] on the
320
+ # py* glob + [ -x -s ]): this runs on every cache HIT, so no utilities and
321
+ # no subshells may be used here.
322
+ _python_candidate_paths() {
323
+ local dir f base IFS=: win_exts=""
324
+ _CAND_PATHS=""
325
+ if _is_msys_platform; then win_exts=1; fi
326
+ for dir in ${PATH:-}; do
327
+ [ -n "$dir" ] || dir="."
328
+ for f in "$dir"/py*; do
329
+ # Non-matching globs return the literal pattern; [ -e ] rejects it.
330
+ [ -e "$f" ] || continue
331
+ base=${f##*/}
332
+ case "$base" in
333
+ python3|python|py|python3.exe|python.exe|py.exe) ;;
334
+ python3.bat|python3.cmd|python.bat|python.cmd|py.bat|py.cmd)
335
+ [ -n "$win_exts" ] || continue ;;
336
+ *) continue ;;
337
+ esac
338
+ [ -x "$f" ] && [ -s "$f" ] || continue
339
+ # Key on the dir once even when it holds several names: discovery's
340
+ # answer is the dir ORDER, and which name wins inside a dir is
341
+ # decided by the same executable checks repeated here.
342
+ _CAND_PATHS="${_CAND_PATHS}${dir}"$'\n'
343
+ break
344
+ done
345
+ done
346
+ }
347
+
348
+ # _prune_interpreter_cache -- oldest-first eviction keeping the record dir
349
+ # <= _PY_CACHE_MAX_FILES. Called only on the WRITE (miss) path: misses already
350
+ # pay for discovery, while the `ls`/`rm` below would be unaffordable process
351
+ # launches on the hit path this whole change set exists to cheapen.
352
+ _prune_interpreter_cache() {
353
+ [ -n "$_PY_CACHE_FILE" ] || return 0
354
+ local cache_dir=${_PY_CACHE_FILE%/*}
355
+ local f i count=0
356
+ local -a files=()
357
+ while IFS= read -r f; do
358
+ [ -n "$f" ] || continue
359
+ [ "$f" = "$_PY_CACHE_FILE" ] && continue
360
+ files+=("$f")
361
+ count=$((count + 1))
362
+ done <<EOF
363
+ $(ls -1tr "$cache_dir"/interpreter-e*-*.cache 2>/dev/null)
364
+ EOF
365
+ i=0
366
+ while [ "$count" -ge "$_PY_CACHE_MAX_FILES" ] && [ "$i" -lt "${#files[@]}" ]; do
367
+ # `|| :` -- an unremovable record (held by antivirus, immutable) must
368
+ # never abort the launcher under `set -e`: that abort would land before
369
+ # the cache write, so no new record is ever stored and every later hook
370
+ # aborts the same way.
371
+ rm -f -- "${files[$i]}" 2>/dev/null || :
372
+ i=$((i + 1))
373
+ count=$((count - 1))
374
+ done
375
+ }
376
+
377
+ _setup_interpreter_cache() {
378
+ local launcher_dir plugin_dir plugin_hash path_hash cache_dir hash_output
379
+
380
+ launcher_dir=${0%/*}
381
+ [ "$launcher_dir" != "$0" ] || launcher_dir=.
382
+ # In-place builtin canonicalize -- the $(cd ...) form forked a bash
383
+ # subshell on every cache HIT on MSYS.
384
+ if ! _canonicalize_dir "$launcher_dir"; then
385
+ return 0
386
+ fi
387
+ plugin_dir=$_CANON_DIR
388
+
389
+ # The PATH half of the key covers only what can change discovery's answer
390
+ # (the PATH entries that actually hold a python/py candidate), not the
391
+ # whole PATH string.
392
+ _python_candidate_paths
393
+
394
+ if _is_msys_platform; then
395
+ # Windows process startup is expensive. Keep both checksums in Bash.
396
+ _cache_checksum "$plugin_dir"
397
+ plugin_hash=$_CACHE_CHECKSUM
398
+ _cache_checksum "$_CAND_PATHS"
399
+ path_hash=$_CACHE_CHECKSUM
400
+ else
401
+ # Native POSIX utility startup is cheap; cksum avoids a shell byte
402
+ # loop on unusually long PATHs. Failure simply disables the cache.
403
+ hash_output=$(printf '%s' "$plugin_dir" | cksum 2>/dev/null) || return 0
404
+ plugin_hash=${hash_output%% *}
405
+ hash_output=$(printf '%s' "$_CAND_PATHS" | cksum 2>/dev/null) || return 0
406
+ path_hash=${hash_output%% *}
407
+ case "$plugin_hash" in ''|*[!0-9]*) return 0 ;; esac
408
+ case "$path_hash" in ''|*[!0-9]*) return 0 ;; esac
409
+ fi
410
+
411
+ if [ "${TOKEN_OPTIMIZER_PY_CACHE+x}" = x ]; then
412
+ cache_dir=$TOKEN_OPTIMIZER_PY_CACHE
413
+ [ -n "$cache_dir" ] || return 0
414
+ _cache_dir_ready "$cache_dir" || return 0
415
+ else
416
+ cache_dir=""
417
+ if [ -n "${XDG_CACHE_HOME:-}" ]; then
418
+ cache_dir="${XDG_CACHE_HOME}/token-optimizer/pylauncher"
419
+ elif [ -n "${HOME:-}" ]; then
420
+ cache_dir="${HOME}/.cache/token-optimizer/pylauncher"
421
+ fi
422
+
423
+ # No shared/world-predictable fallback (e.g. /tmp/token-optimizer-$UID):
424
+ # such a path lets another local user pre-create the dir and plant a
425
+ # poisoned interpreter record. If no per-user home cache dir is available
426
+ # and writable, caching stays OFF and discovery runs exactly as before
427
+ # (fail-open). HOME is set in every supported hook env, incl. Git Bash.
428
+ { [ -n "$cache_dir" ] && _cache_dir_ready "$cache_dir"; } || return 0
429
+ fi
430
+
431
+ # Cache key includes a PROBE-LOGIC EPOCH. The key is otherwise
432
+ # plugin-dir + PATH checksums, neither of which changes when the launcher's
433
+ # interpreter-liveness logic changes -- so a user already bitten by a stale
434
+ # probe has a
435
+ # cache record naming the DEAD WindowsApps stub, and the fixed probe never runs
436
+ # on a cache HIT (only on a miss). Bumping this epoch renames the cache file, so
437
+ # every stale record is ignored once on upgrade: discovery re-runs, the new
438
+ # probe rejects the dead stub, and a healthy interpreter is cached under the new
439
+ # key. Bump `e4` on any future change to interpreter-liveness probing.
440
+ # (e4: the PATH half of the key changed from the whole PATH string to the
441
+ # candidate-dir set -- see _python_candidate_paths.)
442
+ _PY_CACHE_FILE="${cache_dir%/}/interpreter-e4-${plugin_hash}-${path_hash}.cache"
443
+ }
444
+
445
+ # On Windows (Git Bash/MSYS), python.exe is a console-subsystem binary: each
446
+ # hook invocation allocates a transient console window (the "flash") and can
447
+ # orphan a conhost.exe. pythonw.exe is the GUI-subsystem twin shipped beside
448
+ # it by python.org; launching it allocates no console. We prefer pythonw.exe
449
+ # at EXEC time (not discovery time) so a stale cache record that still names
450
+ # python.exe does not keep flashing forever -- the cache key is unchanged, so
451
+ # the swap must happen on every exec, in both _exec_cached_interpreter and
452
+ # _exec_discovered_interpreter.
453
+ #
454
+ # Constraints (each is a real failure mode, not paranoia):
455
+ # * Same directory only: pythonw.exe must sit next to the resolved
456
+ # python.exe (same install, same version). We never synthesise a path
457
+ # from PATH.
458
+ # * Skip WindowsApps: a Microsoft Store pythonw AppExecutionAlias exits
459
+ # silently outside an interactive token (see measure.py).
460
+ # * stdout must be a pipe, not a tty: pythonw is GUI-subsystem. When its
461
+ # std handles are not valid pipes, CPython sets sys.stdout/sys.stderr to
462
+ # None and the hook protocol goes dark while the process exits 0 -- the
463
+ # top regression for this change. A tty on fd 1 means a console is
464
+ # already attached (no flash to avoid) AND pythonw could null it, so we
465
+ # keep python.exe there. The hook context always provides a pipe, which
466
+ # pythonw inherits intact.
467
+ # * Non-Windows is a strict no-op: the MSYS guard short-circuits before any
468
+ # filesystem probe, so POSIX behaviour is byte-for-byte unchanged.
469
+ # * py.exe (the `py -3` launcher) swaps to pyw.exe in the same directory.
470
+ # pyw.exe is the GUI-subsystem launcher twin and `pyw -3` execs
471
+ # pythonw.exe. Every other guard (same-dir, safe prefix, WindowsApps
472
+ # skip, tty check, liveness probe) applies to pyw.exe unchanged.
473
+ #
474
+ # Sets _PYW_INTERP to the chosen interpreter (pythonw.exe when swapped, else
475
+ # the input unchanged). Selection never fails -- on any doubt we keep the
476
+ # caller's interpreter, so this can only ever opt INTO pythonw, never block
477
+ # an exec. Uses a variable (not stdout) so the [ -t 1 ] guard sees the
478
+ # launcher's real fd 1, not a command-substitution pipe.
479
+ _maybe_swap_to_pythonw() {
480
+ local interp="$1" dir twin pythonw
481
+ _PYW_INTERP="$interp"
482
+ case "$interp" in
483
+ */python|*/python3|*/python.exe|*/python3.exe) twin="pythonw.exe" ;;
484
+ */py|*/py.exe) twin="pyw.exe" ;;
485
+ *) return 0 ;;
486
+ esac
487
+ _is_msys_platform || return 0
488
+ if [ -t 1 ]; then
489
+ return 0
490
+ fi
491
+ dir=${interp%/*}
492
+ pythonw="${dir}/${twin}"
493
+ [ -f "$pythonw" ] && [ -x "$pythonw" ] && [ -s "$pythonw" ] || return 0
494
+ _is_safe_prefix "$pythonw" || return 0
495
+ # Case-insensitive WindowsApps skip (any casing on case-insensitive FS).
496
+ _path_contains_windowsapps "$pythonw" && return 0
497
+ # Liveness-probe the twin before committing to it. A corrupt/garbage
498
+ # pythonw.exe (e.g. a half-overwritten install twin, or a 0xC000-style
499
+ # Windows stub) passes the -f/-x/-s metadata checks but exits nonzero
500
+ # (often 127) when actually run. exec consumes the process, so a dead
501
+ # twin would brick every hook exec and the launcher's fallback ladder
502
+ # becomes unreachable. Probe exactly like find_interpreter probes
503
+ # WindowsApps python.exe: 2s timeout, -c "" (no program), stdin from
504
+ # /dev/null so the hook's real stdin is never consumed by the probe.
505
+ # On any doubt, keep python.exe (return 0) -- this can only ever opt
506
+ # INTO pythonw, never block an exec.
507
+ # --kill-after=1s escalates to SIGKILL 1s after SIGTERM. pythonw is
508
+ # GUI-subsystem and can ignore SIGTERM (no console handler), leaving a
509
+ # hung twin holding the 2s budget past expiry and stalling the hook.
510
+ if command -v timeout >/dev/null 2>&1; then
511
+ timeout --kill-after=1s 2s "$pythonw" -c "" </dev/null >/dev/null 2>&1 || return 0
512
+ else
513
+ "$pythonw" -c "" </dev/null >/dev/null 2>&1 || return 0
514
+ fi
515
+ _PYW_INTERP="$pythonw"
516
+ }
517
+
518
+ _exec_cached_interpreter() {
519
+ local record payload interp marker
520
+
521
+ [ -n "$_PY_CACHE_FILE" ] && [ -f "$_PY_CACHE_FILE" ] || return 1
522
+ record=""
523
+ if ! IFS= read -r record 2>/dev/null < "$_PY_CACHE_FILE"; then
524
+ return 1
525
+ fi
526
+ case "$record" in
527
+ $'INTERP\t'*) payload=${record#*$'\t'} ;;
528
+ *) return 1 ;;
529
+ esac
530
+ case "$payload" in
531
+ *$'\t'*)
532
+ interp=${payload%%$'\t'*}
533
+ marker=${payload#*$'\t'}
534
+ [ "$marker" = "-3" ] || return 1
535
+ ;;
536
+ *)
537
+ interp=$payload
538
+ marker=""
539
+ ;;
540
+ esac
541
+ [ -n "$interp" ] || return 1
542
+ case "$interp" in
543
+ /*) ;;
544
+ *) return 1 ;;
545
+ esac
546
+ # A cache record must name the discovered interpreter (python.exe/py.exe),
547
+ # never its GUI twin (the swap is exec-only, see _maybe_swap_to_pythonw).
548
+ # A record ending in /pythonw.exe or /pyw.exe is either poisoned or a stale
549
+ # artefact of a broken twin that should have been probed out -- reject and
550
+ # let discovery re-run, rather than exec'ing a possibly-dead twin directly.
551
+ case "$interp" in
552
+ */pythonw.exe|*/pyw.exe) return 1 ;;
553
+ esac
554
+ [ -x "$interp" ] && [ -s "$interp" ] || return 1
555
+ # A cache entry never bypasses the anti-PATH-hijack policy.
556
+ _is_safe_prefix "$interp" || return 1
557
+ # Windows: prefer the GUI-subsystem pythonw.exe twin at exec time so a
558
+ # cached python.exe record does not keep flashing. No-op off-Windows.
559
+ _maybe_swap_to_pythonw "$interp"
560
+ interp=$_PYW_INTERP
561
+ [ -n "$interp" ] || return 1
562
+ [ -x "$interp" ] && [ -s "$interp" ] || return 1
563
+ _is_safe_prefix "$interp" || return 1
564
+
565
+ if [ "$marker" = "-3" ]; then
566
+ _try_exec "$interp" -3 "$@"
567
+ return 1
568
+ fi
569
+ _try_exec "$interp" "$@"
570
+ }
571
+
572
+ _write_interpreter_cache() {
573
+ local interp="$1" marker="$2" cache_tmp
574
+
575
+ [ -n "$_PY_CACHE_FILE" ] || return 0
576
+ _prune_interpreter_cache
577
+ cache_tmp="${_PY_CACHE_FILE}.tmp.$$"
578
+ if [ "$marker" = "-3" ]; then
579
+ (umask 077; set -C; printf 'INTERP\t%s\t-3\n' "$interp" > "$cache_tmp" &&
580
+ mv -f "$cache_tmp" "$_PY_CACHE_FILE") 2>/dev/null || :
581
+ else
582
+ (umask 077; set -C; printf 'INTERP\t%s\n' "$interp" > "$cache_tmp" &&
583
+ mv -f "$cache_tmp" "$_PY_CACHE_FILE") 2>/dev/null || :
584
+ fi
585
+ return 0
586
+ }
587
+
588
+ _exec_discovered_interpreter() {
589
+ local interp="$1" marker="$2"
590
+ shift 2
591
+
592
+ # Discovery already applied the safe-prefix check. Re-applying it here
593
+ # makes that invariant explicit at the shared cache-write/exec boundary.
594
+ _is_safe_prefix "$interp" || return 1
595
+ _write_interpreter_cache "$interp" "$marker"
596
+ # Windows: prefer the GUI-subsystem pythonw.exe twin at exec time. The
597
+ # cache record keeps naming python.exe (the discovered interpreter), and
598
+ # the swap is reapplied on every exec -- including cache hits -- so a
599
+ # stale record never freezes us on the flashing python.exe. No-op
600
+ # off-Windows.
601
+ _maybe_swap_to_pythonw "$interp"
602
+ interp=$_PYW_INTERP
603
+ [ -n "$interp" ] || return 1
604
+ [ -x "$interp" ] && [ -s "$interp" ] || return 1
605
+ _is_safe_prefix "$interp" || return 1
606
+ if [ "$marker" = "-3" ]; then
607
+ _try_exec "$interp" -3 "$@"
608
+ return 1
609
+ fi
610
+ _try_exec "$interp" "$@"
611
+ }
612
+
613
+ # Explicit user override. pyenv / asdf / conda / venv interpreters, and Codex
614
+ # Desktop's bundled runtime, live outside the PATH-hijack safe-prefix allow-list
615
+ # and are otherwise rejected. Naming one in TOKEN_OPTIMIZER_PYTHON is an explicit
616
+ # trust decision by the user, so it bypasses the allow-list, but we still verify
617
+ # it is genuinely a Python 3 before exec so a stale/broken/wrong override degrades
618
+ # instead of wedging. The compound `if` keeps set -e from aborting when the probe
619
+ # fails.
620
+ #
621
+ # The probe MUST be Python-specific. A bare `-c ''` is not: POSIX shells
622
+ # (/bin/sh, bash, dash, ksh) also accept `-c ''` and exit 0, so a probe of `''`
623
+ # would pass for a shell, then `exec /bin/sh run.py` parses run.py as shell and
624
+ # exits non-zero (2) -- a BLOCKING hook, the exact wedge this file exists to
625
+ # prevent. `import sys; ...` fails on any shell (`import: not found`) and only a
626
+ # real Python 3 (version_info[0] >= 3) exits 0, so only Python is ever exec'd.
627
+ if [ -n "${TOKEN_OPTIMIZER_PYTHON:-}" ]; then
628
+ _ov="$TOKEN_OPTIMIZER_PYTHON"
629
+ if [ -x "$_ov" ] && [ -s "$_ov" ] && \
630
+ "$_ov" -c 'import sys; sys.exit(0 if sys.version_info[0] >= 3 else 1)' >/dev/null 2>&1; then
631
+ # `|| :`: a failed exec falls through to normal discovery.
632
+ _try_exec "$_ov" "$@" || :
633
+ fi
634
+ # `|| :` so a failed write (stderr closed) cannot abort under `set -e` before
635
+ # we fall through to normal discovery.
636
+ echo "token-optimizer: TOKEN_OPTIMIZER_PYTHON=$_ov is not a working Python 3; ignoring it" >&2 || :
637
+ fi
638
+
639
+ _setup_interpreter_cache
640
+ _exec_cached_interpreter "$@" || :
641
+
642
+ # Decide whether a WindowsApps candidate is a real Store install
643
+ # or a dead AppExecutionAlias stub -- WITHOUT flashing a console window on
644
+ # the common path. The old probe ran the console-subsystem `python.exe
645
+ # --version` on every cache miss, which is exactly the flash this launcher
646
+ # exists to prevent.
647
+ #
648
+ # Design (revised for the WindowsApps probe fix): the CANDIDATE ITSELF must supply POSITIVE PROOF
649
+ # OF LIFE by writing a marker to a temp file whose content we then require. A
650
+ # dead AppExecutionAlias stub exits without writing it. We do NOT trust a bare
651
+ # exit code (a dead alias can exit 0 silently, see measure.py), and we do NOT
652
+ # trust a sibling "twin" (pythonw.exe): the WindowsApps probe proved that in WindowsApps each
653
+ # alias name is claimed independently, so a LIVE pythonw twin can sit beside a
654
+ # DEAD python3.exe from a different package -- the old twin probe then cached
655
+ # and exec'd the dead stub on every hook. Only the candidate's own liveness
656
+ # decides now.
657
+ #
658
+ # Flash tradeoff (the no-flash concern): the twin was GUI-subsystem, so probing
659
+ # it never flashed a console; probing the console candidate directly can flash
660
+ # a window ONCE on a cache miss. That regression is accepted deliberately -- a
661
+ # silently-dead cached interpreter breaks EVERY hook for affected users, which
662
+ # is far worse than a one-time flash that only occurs on the rare cache-miss
663
+ # path (the result is cached immediately after). The old code already ran the
664
+ # console candidate directly in its `--version` fallback, so invoking the
665
+ # candidate here is not a new class of behavior.
666
+ #
667
+ # Two-tier ladder (both key on the CANDIDATE, never a twin):
668
+ # Tier 1 -- write-marker: candidate writes "ok" via -c -> alive (fast positive).
669
+ # Tier 2 -- --version OUTPUT (not exit code): a live interpreter prints
670
+ # "Python X.Y.Z"; a dead redirector exits 0 but prints a localized "not found /
671
+ # install from Store" message with no version number. Matching the version
672
+ # STRING is what makes this safe -- trusting the bare exit code was the original
673
+ # false-pass. Tier 2 both (a) rescues a live interpreter that could not write the
674
+ # marker (AV-blocked or unwritable temp, cold start, cygpath path mismatch) and
675
+ # (b) rejects a dead stub that reached here because Tier 1 could not run. There
676
+ # is no remaining exit-code-only fallback, so no surviving Store-stub false-pass.
677
+ #
678
+ # The temp path is handed to the candidate as a native Windows path via cygpath
679
+ # when available, so the probe is immune to MSYS argv path-conversion settings
680
+ # (MSYS_NO_PATHCONV). Probe stdin comes from /dev/null so the hook's real stdin
681
+ # is never consumed. C6 timeout semantics (2s budget, SIGKILL escalation 1s
682
+ # after SIGTERM) apply to the probe and the fallback. Strict POSIX no-op is
683
+ # preserved: this function is only reached for paths matching
684
+ # _path_contains_windowsapps, exactly like the old inline probe.
685
+ _probe_windowsapps_candidate() {
686
+ local binpath="$1" probe_tmp probe_arg out ver
687
+ # Probe the CANDIDATE ITSELF, never a sibling "twin". In WindowsApps each
688
+ # App Execution Alias name is claimed independently, so pythonw.exe can resolve
689
+ # to a DIFFERENT, live package (e.g. the Python Install Manager) while this
690
+ # candidate (python3.exe) is a dead Microsoft Store redirector. The old code
691
+ # proof-of-life-probed the twin, so a live twin masked a dead candidate and the
692
+ # dead stub got cached and exec'd on every hook. Only the candidate's own
693
+ # liveness may decide.
694
+ #
695
+ # Safe-prefix and a working `timeout` gate the WHOLE function, so both tiers sit
696
+ # under the same guards: never exec an untrusted path, and never run the
697
+ # candidate UNBOUNDED (a blocking/half-broken stub would otherwise hang every
698
+ # hook forever). Without `timeout` we fail closed -- return 1 so discovery
699
+ # advances to the next candidate -- rather than risk an unbounded spawn.
700
+ _is_safe_prefix "$binpath" || return 1
701
+ command -v timeout >/dev/null 2>&1 || return 1
702
+ # Tier 1 (fast positive): the candidate writes a proof-of-life marker via -c. A
703
+ # live interpreter writes "ok"; a dead redirector ignores -c and writes nothing.
704
+ # mktemp already creates a fresh empty 0600 file, so no pre-truncation is needed.
705
+ probe_tmp=$(mktemp "${TMPDIR:-/tmp}/token-optimizer-pyprobe.XXXXXX" 2>/dev/null) || probe_tmp=""
706
+ if [ -n "$probe_tmp" ]; then
707
+ probe_arg=$(cygpath -w "$probe_tmp" 2>/dev/null) || probe_arg=""
708
+ [ -n "$probe_arg" ] || probe_arg="$probe_tmp"
709
+ timeout --kill-after=1s 2s "$binpath" -c \
710
+ 'import sys; open(sys.argv[1], "w").write("ok")' \
711
+ "$probe_arg" </dev/null >/dev/null 2>&1 || :
712
+ out=$(cat "$probe_tmp" 2>/dev/null) || out=""
713
+ rm -f "$probe_tmp" 2>/dev/null || :
714
+ if [ "$out" = "ok" ]; then
715
+ return 0 # definitive: the candidate itself is a live interpreter
716
+ fi
717
+ fi
718
+ # Tier 2 (discriminating fallback): trust the candidate's --version OUTPUT, never
719
+ # its exit code. A dead Store redirector exits 0 (the old false pass) but prints a
720
+ # "not found / install from Store" banner; a live interpreter LEADS with
721
+ # "Python X.Y.Z". Matching the version string -- not the exit code -- closes BOTH
722
+ # failure modes the marker probe alone left open:
723
+ # * a LIVE interpreter that merely could not write the marker (AV/DLP-blocked
724
+ # temp, cold start over budget, cygpath path mismatch, no writable temp) is
725
+ # still accepted here instead of being wrongly rejected; and
726
+ # * a DEAD stub reached because Tier 1 could not run (no writable temp) is
727
+ # rejected here instead of false-passing on a bare exit-0.
728
+ # Discriminator is hardened against a LOCALIZED banner that names a version to
729
+ # install (e.g. "Python 3 was not found; install from the Microsoft Store"):
730
+ # reject the banner tokens FIRST, then require the version to LEAD the output
731
+ # (head-anchored, no leading '*'), so a version buried in a sentence cannot pass.
732
+ # 2>&1 because CPython has historically printed --version to stderr.
733
+ ver=$(timeout --kill-after=1s 2s "$binpath" --version </dev/null 2>&1) || :
734
+ case "$ver" in
735
+ *[Nn]ot' '[Ff]ound*|*[Ii]nstall*|*[Ss]tore*|*Microsoft*) return 1 ;;
736
+ [Pp]ython' '[0-9]*) return 0 ;; # version string LEADS the output
737
+ *) return 1 ;;
738
+ esac
739
+ }
740
+
741
+ find_interpreter() {
742
+ local name="$1"
743
+ local IFS=:
744
+ local dir binpath ext win_exts=""
745
+ # pyenv-win (and some scoop shims) ship `.bat`/`.cmd` wrappers with no bare
746
+ # or `.exe` twin on PATH, so they were never even discovered. MSYS can exec a
747
+ # .bat directly; a mis-exec is fail-safe here (falls through to the next
748
+ # candidate, then to the exit-0 no-block guarantee), never a wedge. Gated to
749
+ # Windows so a POSIX box never probes for a python3.bat. NOTE: the .bat exec
750
+ # path is only verifiable on a real Windows host -- discovery is
751
+ # what this adds; exec is MSYS-native and may flash a console window.
752
+ _is_msys_platform 2>/dev/null && win_exts=".bat .cmd"
753
+ for dir in $PATH; do
754
+ [ -n "$dir" ] || dir="."
755
+ for ext in "" ".exe" $win_exts; do
756
+ binpath="${dir}/${name}${ext}"
757
+ [ -x "$binpath" ] || continue
758
+ [ -s "$binpath" ] || continue
759
+ # Reject interpreters outside known-safe prefix directories.
760
+ # Prevents PATH-order attacks where a malicious dir appears first.
761
+ _is_safe_prefix "$binpath" || continue
762
+ # Case-insensitive WindowsApps detection (any casing on
763
+ # case-insensitive FS). WindowsApps may contain real Store-installed
764
+ # Python OR non-functional AppExecutionAlias stubs (non-zero-byte,
765
+ # pass -s). Distinguish them flash-free via the GUI
766
+ # twin's proof-of-life probe, with the console --version probe as
767
+ # the fallback authority -- see _probe_windowsapps_candidate.
768
+ if _path_contains_windowsapps "$binpath"; then
769
+ _probe_windowsapps_candidate "$binpath" || continue
770
+ fi
771
+ printf "%s\n" "$binpath"
772
+ return 0
773
+ done
774
+ done
775
+ return 1
776
+ }
777
+
778
+ if py3=$(find_interpreter "python3"); then
779
+ _exec_discovered_interpreter "$py3" "" "$@" || :
780
+ fi
781
+
782
+ if py=$(find_interpreter "python"); then
783
+ _exec_discovered_interpreter "$py" "" "$@" || :
784
+ fi
785
+
786
+ if pyl=$(find_interpreter "py"); then
787
+ _exec_discovered_interpreter "$pyl" "-3" "$@" || :
788
+ fi
789
+
790
+ # Direct probe: hook environments often have a stripped PATH that excludes
791
+ # the user's Python. Check known locations directly as a fallback.
792
+ for _direct in /opt/homebrew/bin/python3 /usr/local/bin/python3 /usr/bin/python3 \
793
+ /home/linuxbrew/.linuxbrew/bin/python3; do
794
+ if [ -x "$_direct" ] && [ -s "$_direct" ] && _is_safe_prefix "$_direct"; then
795
+ _exec_discovered_interpreter "$_direct" "" "$@" || :
796
+ fi
797
+ done
798
+
799
+ # HOOK-SAFETY: we are now on the terminal degradation path and WILL `exit 0`.
800
+ # Disable `set -e` first so NOTHING below can abort non-zero before that exit --
801
+ # in particular a diagnostic `echo >&2` when the harness invoked the hook with
802
+ # stderr closed: under `set -e` the failed write aborts with a non-zero status,
803
+ # which is a blocking hook. `set +e` makes the whole exit path unconditional.
804
+ set +e
805
+ echo "token-optimizer: no usable Python 3 interpreter found" >&2
806
+ echo " tried: python3, python, py -3, direct paths, TOKEN_OPTIMIZER_PYTHON" >&2
807
+ echo " fix: set TOKEN_OPTIMIZER_PYTHON=/path/to/python3 (pyenv/asdf/conda/venv are fine)," >&2
808
+ echo " or install Python 3 from https://python.org/ , then restart your agent" >&2
809
+ # HOOK-SAFETY (never remove): this launcher is invoked ONLY from hook wrappers in
810
+ # hooks/hooks.json. A hook MUST NOT exit non-zero. Codex and Claude Code treat a
811
+ # non-zero PreToolUse hook as a tool-blocking failure, so a missing interpreter
812
+ # here would fail on EVERY Read and Bash and freeze the session ("shell runner
813
+ # unavailable"). The `; exit 0` in the wrapper is dead code once `exec` replaces
814
+ # the shell, so the guarantee has to live here. Degrade cleanly instead: skip the
815
+ # optimization and let the tool proceed. Diagnostics above went to stderr.
816
+ exit 0