1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
|
#!/usr/bin/env bash
# Find a working Python 3 interpreter and exec the hook with it.
#
# On Windows + Git Bash, `python3` typically resolves to the Microsoft Store
# stub at C:\Users\<user>\AppData\Local\Microsoft\WindowsApps\python3, which
# is not a Python; it is told by its link and not started (sg_is_redirector).
# This shim probes each other candidate with `-c ""` and skips any that fails,
# so the search reaches the real python.org install (`python` in Git Bash) or
# the `py -3` launcher.
#
# Order:
# 1. python3 — canonical on macOS/Linux; the Store stub is skipped.
# 2. python — python.org installs on Windows; some Linux distros (RHEL 7
# EOL'd 2024-06) point this at Python 2, but `-c ""` succeeds
# on Python 2 too — guard with a version check.
# 3. py -3 — Windows Python launcher.
#
# Args after the shim path are passed straight through to the chosen
# interpreter, so the hooks.json invocation is:
# bash "${CLAUDE_PLUGIN_ROOT}/hooks/sg-python.sh" \
# "${CLAUDE_PLUGIN_ROOT}/hooks/security_reminder_hook.py"
set -e
# Force UTF-8 for ALL Python filesystem + IO operations (PEP 540).
# Without this, Windows Python defaults `locale.getpreferredencoding()` to
# cp1252 — which makes `text=True` in subprocess.run / open() / json.load
# crash the internal reader thread on any byte that's undefined in cp1252
# (e.g. the 0x81 byte from ف, present in any path/filename with
# Arabic/Hebrew/CJK characters). See #2056, #2099.
#
# No-op on macOS/Linux (already UTF-8). Must be set BEFORE Python starts —
# changing it from inside the interpreter has no effect.
export PYTHONUTF8=1
# Set to 1 below only when the interpreter had to be found by its real path
# (pass 4); the hook reports it as the `launcher_fallback` metric.
unset SG_LAUNCHER_FALLBACK
# Git Bash / MSYS on Windows hands script paths to this shim in POSIX form
# (`/c/Users/...`). When we exec a Windows `python.exe` (which we do on
# Windows since `python3` is the Microsoft Store stub), python interprets the
# leading `/` as the root of the current drive — e.g. `/c/Users/...` becomes
# `C:\c\Users\...` or `D:\c\Users\...` (whichever drive the shell is on),
# fails with ENOENT, and every Edit/Write/MultiEdit tool use blocks until the
# session restarts. See anthropics/claude-plugins-official#2043.
#
# Fix: convert absolute path args to native Windows form before exec.
# `cygpath` ships with Git Bash; it's absent on macOS/Linux, where the
# `command -v` guard makes this a no-op. `cygpath -w` is idempotent for
# already-Windows paths so the rare mixed-form case is safe.
#
# Under Git Bash every $(...) is a new Windows process, and this shim runs on
# every hook, so drive paths (`/c/Users/...`, where the plugin lives) are
# converted in-shell. Git Bash and MSYS2 (OSTYPE=msys) mount drives at
# /<letter>; anything else (`/tmp`, `/usr`, Cygwin's /cygdrive) needs cygpath
# to resolve. See #6470.
if command -v cygpath >/dev/null 2>&1; then
sg_drive_mounts=""
case "${OSTYPE:-}" in msys*) sg_drive_mounts=1 ;; esac
converted=()
for a in "$@"; do
case "$a" in
/[A-Za-z]/*)
if [ -n "$sg_drive_mounts" ]; then
drive="${a:1:1}"
rest="${a:3}"
converted+=("${drive^^}:\\${rest//\//\\}")
else
converted+=("$(cygpath -w "$a")")
fi ;;
/*) converted+=("$(cygpath -w "$a")") ;;
*) converted+=("$a") ;;
esac
done
set -- "${converted[@]}"
fi
# The hook script the chosen interpreter has to run (already in native form).
SG_TARGET=""
case "${1:-}" in
""|-*) ;;
*) SG_TARGET="$1" ;;
esac
# Names whose interpreter runs but cannot see the hook script ("|"-separated).
sg_unreadable=""
# The other names that are there but cannot be used, each with why, e.g.
# "python3 (exit 127)". sg_failed_short is for one short line: python3, python
# and py -3, a full path by its last part, each once. sg_failed_versioned is
# the first of the python3.NN names.
sg_failed=""
sg_failed_short=""
sg_failed_versioned=""
sg_failed_others=""
probe() {
# $1..N: the interpreter command (may be multi-word like `py -3`)
# Writes "<major>.<minor>" to stdout and exits 0 iff it is at least
# Python 3 AND it can read the hook script; exits 3 if it cannot.
#
# The second half matters on Windows: an interpreter started through a
# packaged launcher alias (Microsoft Store Python, Python Install Manager;
# the python/python3/py entries under ...\Microsoft\WindowsApps) runs with
# a different view of %APPDATA% than the process that started it. It
# answers `-c` fine, then fails on the script with "can't open file ...
# [Errno 2]" and exit code 2 -- and exit 2 from an asyncRewake hook wakes
# the model, whose reply runs the Stop hook again: an endless loop that
# never reviewed anything. See #6251, #5781.
#
# On Windows a second line carries sys.executable (see sg_own_path), but not
# for a virtual environment's interpreter.
#
# Only for `$(probe ...)`: the `exec` replaces that subshell instead of
# forking a second process from it.
[ "${BASH_SUBSHELL:-0}" -gt 0 ] || return 1
# PYTHONSAFEPATH (3.11+, ignored before): the probe needs the standard
# library only, so Python is told not to add its usual first entry to the
# import path. For this call alone; the hook's environment is unchanged.
#
# The code can reach cmd.exe through a .bat shim (pyenv-win), so it is one
# line of characters that arrive unchanged: a ">=" was read as a redirect
# and left a stray file. See #7172. On Windows a name that loses the
# argument also exits 3, so that pass 4 can start its real interpreter.
PYTHONSAFEPATH=1 exec "$@" -c 'import os, sys; t = (sys.argv[1:] or [""])[0]; sys.exit(3) if sys.platform == "win32" and not sys.argv[1:] or t and not (os.path.isfile(t) and os.access(t, os.R_OK)) else print(f"{sys.version_info[0]}.{sys.version_info[1]}"); sys.platform == "win32" and sys.version_info.__ge__((3, 10)) and sys.prefix == sys.base_prefix and print(sys.executable)' "$SG_TARGET" 2>/dev/null
}
# Use as `ask ... || { note_unreadable "<name>"; continue; }` (see ask below).
note_unreadable() {
local rc=$?
if [ "$rc" -eq 3 ]; then
sg_unreadable="$sg_unreadable|$1|"
else
note_failed "$1" "exit $rc"
fi
return 0
}
# For the message at the end only; changes nothing about the search.
note_failed() {
local entry="${1##*/} ($2)"
sg_failed="${sg_failed:+$sg_failed, }$1 ($2)"
case "$1" in
*/*) ;;
python3.*)
[ -z "$sg_failed_versioned" ] || sg_failed_others=1
sg_failed_versioned="${sg_failed_versioned:-$entry}"
return 0 ;;
esac
case ", $sg_failed_short, " in
*", $entry, "*) ;;
*) sg_failed_short="${sg_failed_short:+$sg_failed_short, }$entry" ;;
esac
}
# $1 answered with $v and is not started: notes it when that is not a version,
# as from a version manager's shim that prints its complaint and exits 0.
note_answer() {
case "$v" in
[0-9]*.[0-9]*) ;;
*) note_failed "$1" "unexpected answer" ;;
esac
}
# Where packaged aliases exist (and bash has what telling them apart needs).
sg_windows=""
case "${OSTYPE:-}" in
msys*|cygwin*) [ "${BASH_VERSINFO[0]:-0}" -lt 4 ] || sg_windows=1 ;;
esac
# True iff the command's executable is on PATH ($1 of a possibly multi-word
# command like `py -3`). A builtin lookup: `$(probe ...)` costs a process even
# when the interpreter does not exist, so missing names are skipped first. On
# Windows a python or python3 that is only App Installer's alias counts as
# missing; that check takes one process, in place of starting the alias.
sg_skipped=""
on_path() {
case "$sg_windows:$1" in
1:python|1:python3)
hash "$1" 2>/dev/null || return 1
if sg_is_redirector "${BASH_CMDS[$1]:-}"; then
sg_skipped="${sg_skipped:+$sg_skipped, }$1"
return 1
fi ;;
*) command -v "$1" >/dev/null 2>&1 ;;
esac
}
# True iff $1 is the path of App Installer's python or python3, which Windows
# puts under ...\Microsoft\WindowsApps when no packaged Python is installed.
# It is not a Python, it points the user to the Store, so nothing is lost by
# telling it by where its link leads instead of starting it. Starting it is a
# packaged app activation on every hook, and waits for Windows' package
# services: normally a fraction of a second, but until they answer again when
# they are stuck, in every session on the machine at once. See #3870, #6348.
# Git Bash shows these aliases as symbolic links; where the link cannot be
# read, the name is probed like any other. Aliases of a packaged Python are
# interpreters and are probed too.
sg_is_redirector() {
local to
[ -n "$sg_windows" ] && sg_is_alias_path "$1" || return 1
# Full path: another readlink on PATH may not know these links.
to=$(/usr/bin/readlink -- "$1" 2>/dev/null </dev/null) || return 1
# Not lowercased: the result would depend on the locale.
case "$to" in
*[/\\]Microsoft.DesktopAppInstaller_*) return 0 ;;
esac
return 1
}
# How long the probes took, for the launcher_probe_max_ms / launcher_probe_ms
# metrics the hook reports. Measurement only: `ask` is `v=$(probe ...)` with a
# clock around it, and changes neither which interpreter runs nor how long a
# probe may take. EPOCHREALTIME needs bash 5; older bash (macOS /bin/bash) only
# has whole seconds, where a difference of 1 can be a few milliseconds: there
# a single probe counts from 2 s, and the total is first probe to last.
unset SG_LAUNCHER_PROBE_MS SG_LAUNCHER_PROBE_MAX_MS
sg_probe_ms=0
sg_probe_max_ms=0
sg_probe_first=""
sg_coarse=""
sg_rejected="" # a name that is not a packaged alias was started and not used
sg_clock() {
# Sets $sg_now (ms) without starting a process.
case "${EPOCHREALTIME:-}" in
[0-9]*[.,][0-9][0-9][0-9][0-9][0-9][0-9]) # the decimal point follows the locale
sg_now=${EPOCHREALTIME//[!0-9]/}
sg_now=$((10#$sg_now / 1000)) ;;
*)
sg_coarse=1
sg_now=$((SECONDS * 1000)) ;;
esac
}
ask() {
# Sets $v and $sg_exe; same exit status as probe.
local rc=0 t0 ms
sg_clock; t0=$sg_now
[ -n "$sg_probe_first" ] || sg_probe_first=$t0
v=$(probe "$@") || rc=$?
sg_exe=""
case "$v" in
*$'\n'*)
sg_exe=${v#*$'\n'}; sg_exe=${sg_exe%$'\r'}
v=${v%%$'\n'*} ;;
esac
sg_clock; ms=$((sg_now - t0))
if [ -n "$sg_coarse" ]; then
[ "$ms" -ge 2000 ] || ms=0
sg_probe_ms=$((sg_now - sg_probe_first))
[ "$sg_probe_ms" -ge 2000 ] || sg_probe_ms=0
elif [ "$ms" -gt 0 ]; then
sg_probe_ms=$((sg_probe_ms + ms))
fi
[ "$ms" -le "$sg_probe_max_ms" ] || sg_probe_max_ms=$ms
if [ "$sg_probe_ms" -gt 0 ]; then
export SG_LAUNCHER_PROBE_MS=$sg_probe_ms SG_LAUNCHER_PROBE_MAX_MS=$sg_probe_max_ms
fi
# Only where sg_own_path asks: bash 5 on Windows.
if [ -n "$sg_memo" ] && { [ $rc -ne 0 ] || ! is_sdk_compatible "${v%$'\r'}"; }; then
case "$1" in
/*) sg_is_alias_path "$1" || sg_rejected=1 ;;
*) { hash "$1" 2>/dev/null && sg_is_alias_path "${BASH_CMDS[$1]:-}"; } || sg_rejected=1 ;;
esac
fi
return $rc
}
# True iff arg is a "M.m" version string >= 3.10. claude_agent_sdk requires
# Python >= 3.10; below that, pip install fails ("No matching distribution")
# and the LLM-powered review (Stop / commit / push) silently no-ops while
# pattern checks (PostToolUse regex) keep working. macOS ships 3.9.6 as the
# default `python3` on current versions, so this guard matters in practice.
# See anthropics/claude-plugins-official#2071.
is_sdk_compatible() {
case "$1" in
3.1[0-9]|3.[2-9][0-9]|[4-9].*|[1-9][0-9].*) return 0 ;;
*) return 1 ;;
esac
}
# One interpreter start per hook on Windows. The search below starts the chosen
# name twice, to check it and to run the hook, on every Edit, prompt and Stop,
# and a start there can cost more than its own time:
# - a packaged alias (python, python3 and py under ...\Microsoft\WindowsApps)
# starts more than Python. The Python Install Manager's aliases make Windows
# check the package for an update. See anthropics/claude-code#98929.
# - in the packaged Claude Desktop app, Windows keeps some kernel memory until
# the next restart for every file opened through a junction or symlink under
# AppData, and uv's `python3.12` runs its interpreter through one, so every
# file Python loads counts. See anthropics/claude-code#96870.
#
# So when the interpreter behind the name is certain (sg_own_path), the hook runs
# with that file, by its path with the links resolved, and the path is kept in
# the plugin's state folder (`launcher-python`) for a day. Later hooks start it
# directly: one start, no alias, no link. The remembered path is used only while
# PATH and the hook folder are what they were when it was checked and the file
# is still there; anything else is the full search, which writes the entry again.
# A hook that fails on the remembered path drops its entry, so the next one
# searches again; deleting the file does the same by hand. Up to four entries
# are kept, so sessions with different PATHs do not push each other out.
#
# Not while a virtual environment is active, and never an environment's own
# interpreter: an environment can be rebuilt with another Python at the same
# path, and other sessions should not inherit it. Not while PY_PYTHON or
# PY_PYTHON3 chooses for the py launcher either.
#
# Builtins only: nothing here starts a process on the remembered route.
unset SG_LAUNCHER_DIRECT
sg_args=("$@")
sg_exe="" # sys.executable from the last `ask` (Windows, Python 3.10+)
sg_own="" # set by sg_recall and sg_own_path
sg_how="" # with sg_own: "alias", "regular" or "fallback" (regular, by pass 4)
sg_in_pass4=""
sg_memo="" # the file; empty where none of this applies
sg_target_dir=""
case "${OSTYPE:-}" in
msys*|cygwin*)
if [ "${BASH_VERSINFO[0]:-0}" -ge 5 ] && [ -n "$SG_TARGET" ] && [ -z "${VIRTUAL_ENV:-}${PY_PYTHON:-}${PY_PYTHON3:-}" ]; then
# The folder _base.state_dir() resolves to.
sg_home="${USERPROFILE:-${HOME:-}}"
sg_memo="${SECURITY_WARNINGS_STATE_DIR:-}"
if [ -z "$sg_memo" ] && [ -n "${CLAUDE_CONFIG_DIR:-}" ]; then
sg_memo="$CLAUDE_CONFIG_DIR/security"
fi
[ -n "$sg_memo" ] || sg_memo="~/.claude/security"
case "$sg_memo" in
"~"|"~"[\\/]*)
if [ -n "$sg_home" ]; then sg_memo="$sg_home${sg_memo:1}"; else sg_memo=""; fi ;;
esac
[ -z "$sg_memo" ] || sg_memo="$sg_memo/launcher-python"
sg_target_dir="${SG_TARGET%[\\/]*}"
fi ;;
esac
sg_is_alias_path() {
case "${1,,}" in
*/microsoft/windowsapps/*|*\\microsoft\\windowsapps\\*) return 0 ;;
esac
return 1
}
# An interpreter the remembered route may start: python*.exe by absolute
# path, a regular file, and not an alias itself.
sg_startable() {
local name="${1##*/}"
case "$1" in
//*) return 1 ;; # a network share, which may be gone for the next hook
/*) ;;
*) return 1 ;;
esac
case "${name,,}" in
python*.exe) ;;
*) return 1 ;;
esac
! sg_is_alias_path "$1" || return 1
[ -f "$1" ] && [ -x "$1" ]
}
# Sets $sg_posix to $1, a path as Windows Python prints it, in the form the
# shell uses.
sg_to_posix() {
local drive
sg_posix="$1"
case "$1" in
[A-Za-z]:[\\/]*)
if [ -n "${sg_drive_mounts:-}" ]; then
drive="${1:0:1}"
sg_posix="/${drive,,}/${1:3}"
sg_posix="${sg_posix//\\//}"
else
sg_posix=$(cygpath -u "$1" 2>/dev/null) || return 1
fi ;;
esac
}
# True iff $1, found on PATH, is uv's starter for $2, one of uv's own Pythons:
# a program in the folder uv puts them in. It always runs the same interpreter.
sg_is_uv_starter() {
local root="${UV_PYTHON_INSTALL_DIR:-}" bin sg_posix
if [ -z "$root" ]; then
[ -n "${APPDATA:-}" ] || return 1
root="$APPDATA/uv/python"
fi
sg_to_posix "$root" || return 1
root="${sg_posix%/}"
case "$root" in /?*) ;; *) return 1 ;; esac
case "${2,,}" in "${root,,}"/*) ;; *) return 1 ;; esac
[ -f "${1%.exe}.exe" ] || return 1
for bin in "${UV_PYTHON_BIN_DIR:-}" "${XDG_BIN_HOME:-}" "${sg_home:+$sg_home/.local/bin}"; do
if [ -n "$bin" ] && [ "${1%/*}" -ef "$bin" ]; then return 0; fi
done
return 1
}
# Reads the file. Sets $sg_keep to the entries for other sessions and, if there
# is one for this session that is not a day old, $sg_exe_kept and $sg_how.
sg_read_memo() {
local tag saved path exe dir how end age kept=0
sg_keep=""
sg_exe_kept=""
sg_how=""
[ -f "$sg_memo" ] && [ -r "$sg_memo" ] || return 0
while IFS= read -r tag && IFS= read -r saved && IFS= read -r path &&
IFS= read -r exe && IFS= read -r dir && IFS= read -r how && IFS= read -r end; do
[ "$tag" = "sg-launcher-python 2" ] && [ "$end" = "end" ] || return 0
case "$how" in alias|regular|fallback|search) ;; *) return 0 ;; esac
case "$saved" in
""|*[!0-9]*|????????????*) return 0 ;;
esac
age=$((EPOCHSECONDS - 10#$saved))
[ "$age" -ge 0 ] && [ "$age" -lt 86400 ] || continue
if [ "$path" = "$PATH" ] && [ "$dir" = "$sg_target_dir" ]; then
sg_exe_kept="$exe"
sg_how="$how"
elif [ "$kept" -lt 3 ]; then
kept=$((kept + 1))
sg_keep+="$tag"$'\n'"$saved"$'\n'"$path"$'\n'"$exe"$'\n'"$dir"$'\n'"$how"$'\n'"$end"$'\n'
fi
done 2>/dev/null < "$sg_memo" || true # it may be locked, or gone by now
return 0
}
# Replaces this session's entry with $1 (empty: none) and keeps the others, read
# again here because a hook can take minutes. Two hooks writing at once can lose
# an entry or leave a broken one, which costs a search.
sg_write_memo() {
local how="$sg_how"
[ -d "${sg_memo%/*}" ] || return 0
[ ! -e "$sg_memo" ] || [ -f "$sg_memo" ] || return 0
sg_read_memo
sg_how="$how"
printf '%s' "$1$sg_keep" 2>/dev/null > "$sg_memo" || true
}
# Use as `sg_uncertain; return`: for a day this session's hooks search as they
# always did, instead of working out again that there is nothing to remember.
sg_uncertain() {
sg_entry "" search
sg_write_memo "$sg_line"
return 1
}
sg_entry() {
# Sets $sg_line to the entry that says: run this session's hooks with $1.
sg_line="sg-launcher-python 2"$'\n'"$EPOCHSECONDS"$'\n'"$PATH"$'\n'"$1"$'\n'"$sg_target_dir"$'\n'"$2"$'\n'"end"$'\n'
}
sg_recall() {
# Sets $sg_own and $sg_how to the remembered interpreter iff it may run
# this hook.
[ -n "$sg_memo" ] || return 1
sg_read_memo
[ -n "$sg_how" ] || return 1
if [ "$sg_how" = search ]; then
sg_memo="" # nothing to look for again today
return 1
fi
sg_startable "$sg_exe_kept" && [ -r "$SG_TARGET" ] || return 1
sg_own="$sg_exe_kept"
}
sg_own_path() {
# $1: the name that just answered `ask` with version $v. Succeeds, with
# $sg_own set, iff it is certain which file runs under that name today and
# would run tomorrow: the name is a packaged alias, or the interpreter
# itself, or the py launcher, or uv's starter for one of its own Pythons.
# (Not certain: a version manager's shim, which chooses by folder, whether
# it is this name or an earlier one that had nothing to offer here.)
# Remembers the file for the next hooks.
local found="" own want="$v" real sg_posix sg_line
[ -n "$sg_memo" ] && [ -n "$sg_exe" ] || return 1
case "$1" in
/*) found="$1" ;; # pass 4
*) hash "$1" 2>/dev/null && found="${BASH_CMDS[$1]:-}" ;;
esac
case "$found" in
/*) ;;
*) return 1 ;; # found through a relative PATH entry
esac
if sg_is_alias_path "$found"; then
sg_how=alias
sg_to_posix "$sg_exe" || return 1
own="$sg_posix"
sg_startable "$own" || return 1
else
[ -z "$sg_rejected" ] || return 1
# Where nothing can be kept, the search is all it costs.
[ -d "${sg_memo%/*}" ] && [ -w "${sg_memo%/*}" ] || return 1
if [ -e "$sg_memo" ]; then [ -f "$sg_memo" ] && [ -w "$sg_memo" ] || return 1; fi
sg_how=regular
[ -z "$sg_in_pass4" ] || sg_how=fallback
sg_to_posix "$sg_exe" || { sg_uncertain; return; }
own="$sg_posix"
sg_startable "$own" || { sg_uncertain; return; }
[ "$found" -ef "$own" ] || [ "$1" = "py" ] || sg_is_uv_starter "$found" "$own" || { sg_uncertain; return; }
[ ! -d "${own%/*}/conda-meta" ] || { sg_uncertain; return; } # a conda environment
fi
# Links resolved. One process, on hooks that do the search only. Full path:
# another readlink on PATH may not know Windows' links.
real=$(/usr/bin/readlink -f -- "$own" 2>/dev/null </dev/null) || real=""
if sg_startable "$real" && [ "$real" -ef "$own" ]; then own="$real"; fi
# The probe has run $found; any other path is checked before it is used.
if [ "$own" != "$found" ] && [ "$own" != "$found.exe" ]; then
if ! ask "$own" || [ "${v%$'\r'}" != "$want" ]; then
v=$want
[ "$sg_how" != alias ] || return 1
sg_uncertain
return
fi
v=${v%$'\r'}
fi
sg_own="$own"
sg_entry "$own" "$sg_how"
sg_write_memo "$sg_line"
return 0
}
# Use right before `exec <name> "$@"`: runs the hook with the interpreter
# behind <name> instead when sg_own_path finds one, else returns.
sg_direct() {
if sg_own_path "$@"; then
if [ "$sg_how" = alias ]; then SG_LAUNCHER_DIRECT=2; else SG_LAUNCHER_DIRECT=4; fi
export SG_LAUNCHER_DIRECT
exec "$sg_own" "${sg_args[@]}"
fi
return 0
}
if sg_recall; then
if [ "$sg_how" = alias ]; then SG_LAUNCHER_DIRECT=1; else SG_LAUNCHER_DIRECT=3; fi
export SG_LAUNCHER_DIRECT
[ "$sg_how" != fallback ] || export SG_LAUNCHER_FALLBACK=1
# Not exec'd, so a failure can drop the entry: no probe checked this
# interpreter today, and a broken one must not fail every hook for a day.
# Exit 2 included, although a review with findings ends that way: so does a
# Python that cannot open the script (see probe).
sg_rc=0
"$sg_own" "$@" || sg_rc=$?
# `|| true`: under `set -e` nothing here may end the launcher, because the
# exit code of the hook is what wakes the model.
[ "$sg_rc" -eq 0 ] || sg_write_memo "" || true
exit "$sg_rc"
fi
# Pass 1 — try minor-versioned binaries in descending order. These are only
# present if the user explicitly installed them (Homebrew / python.org / pyenv),
# so picking one here always upgrades over the system `python3`. Highest
# of these wins; the user doesn't have to PATH-prefer it. Releases newer
# than this list are pass 2b.
for cmd in "python3.13" "python3.12" "python3.11" "python3.10"; do
on_path "$cmd" || continue
ask "$cmd" || { note_unreadable "$cmd"; continue; }
v=${v%$'\r'}
if is_sdk_compatible "$v"; then
sg_direct "$cmd"
exec "$cmd" "$@"
fi
note_failed "$cmd" "unexpected answer"
done
# Pass 2 — bare interpreters, but only if SDK-compatible. Covers Linux distros
# that ship 3.10+ as the default `python3`, and Windows where `python` /
# `py -3` resolves to the user's python.org install.
sg_older="" # first of these that is a readable Python 3 below 3.10
for cmd in "python3" "python" "py -3"; do
# shellcheck disable=SC2086
on_path $cmd || continue
# shellcheck disable=SC2086
ask $cmd || { note_unreadable "$cmd"; continue; }
v=${v%$'\r'}
if is_sdk_compatible "$v"; then
# shellcheck disable=SC2086
sg_direct $cmd
# shellcheck disable=SC2086
exec $cmd "$@"
fi
# Anything that successfully reported a "M.m" string.
case "$v" in
[0-9]*.[0-9]*) [ -n "$sg_older" ] || sg_older="$cmd" ;;
esac
note_answer "$cmd"
done
# Pass 2b — minor versions newer than the pass 1 list, so a machine whose
# only SDK-compatible Python is a recent release (system `python3` 3.9 next to
# Homebrew's python3.14) is not left on pass 3. Tried only when nothing
# above is compatible: an interpreter that already works is never traded for
# a newer one, which may not have the SDK or wheels for its dependencies yet.
# Oldest first for the same reason. Missing names cost no process (on_path).
# See #4907, #5024.
for cmd in "python3.14" "python3.15" "python3.16" "python3.17" "python3.18" "python3.19"; do
on_path "$cmd" || continue
ask "$cmd" || { note_unreadable "$cmd"; continue; }
v=${v%$'\r'}
if is_sdk_compatible "$v"; then
sg_direct "$cmd"
exec "$cmd" "$@"
fi
note_failed "$cmd" "unexpected answer"
done
# Pass 3 — fallback to any Python 3, even <3.10. Pattern-based checks
# (PostToolUse regex on Edit/Write) only need 3.6+ and are useful on their
# own; the SDK-dependent paths will detect the version mismatch and degrade
# inside the Python code. Without this fallback, the entire plugin would
# stop working on default macOS, which is a regression vs today.
if [ -n "$sg_older" ]; then
# shellcheck disable=SC2086
exec $sg_older "$@"
fi
# Pass 4 — nothing above could run the hook script. If that is because the
# names on PATH resolve to packaged launcher aliases that cannot see the
# plugin directory (see probe), the same interpreter usually works when it is
# started by its real path instead of through the alias. Candidates:
# - every further python3/python on PATH, by full path (a regular install
# often sits behind the alias in PATH order; the first match is the one
# the bare name resolved to above),
# - the real executable each alias reports as sys.executable.
# The list is built before the loop that execs, and from a here-document: a
# redirect around that loop would become the hook's stdin.
sg_candidates=()
for name in "python3" "python"; do
first=1
while IFS= read -r c; do
if [ -n "$first" ]; then first=""; continue; fi
[ -n "$c" ] && ! sg_is_redirector "$c" && sg_candidates+=("$c")
done <<EOF
$(type -ap "$name" 2>/dev/null)
EOF
done
for cmd in "python3" "python" "py -3"; do
case "$sg_unreadable" in *"|$cmd|"*) ;; *) continue ;; esac
# The same limits on the code as in probe.
# shellcheck disable=SC2086
c=$(PYTHONSAFEPATH=1 $cmd -c 'import sys; print(sys.executable)' 2>/dev/null) || continue
c=${c%$'\r'} # native Windows Python prints CRLF
[ -n "$c" ] || continue
if command -v cygpath >/dev/null 2>&1; then
c=$(cygpath -u "$c" 2>/dev/null) || continue
fi
sg_candidates+=("$c")
done
export SG_LAUNCHER_FALLBACK=1
sg_in_pass4=1
sg_fallback=""
sg_tried="|"
for cmd in "${sg_candidates[@]}"; do
case "$sg_tried" in *"|$cmd|"*) continue ;; esac
sg_tried="$sg_tried$cmd|"
ask "$cmd" || { note_unreadable "$cmd"; continue; }
v=${v%$'\r'}
if is_sdk_compatible "$v"; then
sg_direct "$cmd"
exec "$cmd" "$@"
fi
case "$v" in
[0-9]*.[0-9]*) [ -n "$sg_fallback" ] || sg_fallback="$cmd" ;;
esac
note_answer "$cmd"
done
if [ -n "$sg_fallback" ]; then
exec "$sg_fallback" "$@"
fi
# Exit 1, never 2: on an asyncRewake hook exit 2 means "the review has
# findings, wake the model", and a launcher failure is not a finding.
if [ -n "$sg_unreadable" ]; then
echo "security-guidance: found Python, but it cannot read the hook script (missing, or not visible to Python), so no security checks ran." >&2
echo " hook script: $SG_TARGET" >&2
echo " on Windows this happens when python, python3 and py are Microsoft Store or Python Install Manager aliases;" >&2
echo " install Python from https://python.org and put it ahead of ...\\Microsoft\\WindowsApps in PATH" >&2
[ -z "$sg_failed" ] || echo " also tried: $sg_failed" >&2
# No Python to report it, so the launcher emits the metric itself.
echo '{"metrics": {"launcher_unreadable": 1}}'
exit 1
fi
# Claude Code's terminal shows only the first line of a failed hook, so what
# tells a broken interpreter from a missing one is on it. Not all of it: a
# version manager's folder has a name per version.
sg_why=""
if [ -n "$sg_failed" ]; then
sg_why="${sg_failed_short:-$sg_failed_versioned}"
if [ -n "$sg_failed_short" ] && [ -n "$sg_failed_versioned" ]; then sg_failed_others=1; fi
sg_why=" On PATH but not usable: $sg_why${sg_failed_others:+, and more}."
fi
echo "security-guidance: no working Python 3 interpreter found.$sg_why" >&2
echo " tried: python3.13 to python3.10, python3, python, py -3, python3.14 to python3.19" >&2
[ -z "$sg_failed" ] || echo " failed: $sg_failed" >&2
if [ -n "$sg_skipped" ]; then
echo " not started: $sg_skipped (App Installer's alias, which is not a Python)" >&2
fi
# --version, because it is safe in any folder: -m and -c import from it.
[ -z "$sg_failed" ] || echo " running one of the failed ones with --version in the project folder may show why" >&2
[ -z "$sg_failed" ] || echo " if that does not help:" >&2
echo " on Windows, install Python from https://python.org (NOT the Microsoft Store)" >&2
echo " on macOS, install Python 3.10+ via Homebrew (\`brew install python\`)" >&2
exit 1
|