@lilmgenius/win-hooks 1.10.0 → 1.12.0

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.
@@ -1,250 +0,0 @@
1
- #!/bin/bash
2
- # win-hooks: apply-patches
3
- # Reads tab-separated lines from find-incompatible on stdin:
4
- # plugin\tinstall_path\thooks_file\tevent\tcommand
5
- # Creates wrapper scripts and patches hooks.json files.
6
- #
7
- # Usage: find-incompatible | apply-patches <template_cmd_path>
8
-
9
- set -euo pipefail
10
-
11
- if [[ $# -lt 1 ]]; then
12
- echo "Usage: apply-patches <template_cmd_path>" >&2
13
- exit 1
14
- fi
15
-
16
- TEMPLATE_CMD="$1"
17
- if [[ ! -f "$TEMPLATE_CMD" ]]; then
18
- echo "Template not found: $TEMPLATE_CMD" >&2
19
- exit 1
20
- fi
21
-
22
- SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
23
- LIB="${SCRIPT_DIR}/lib/plugins.sh"
24
- if [[ ! -f "$LIB" ]]; then
25
- echo "win-hooks: shared lib not found: $LIB" >&2
26
- exit 1
27
- fi
28
- source "$LIB"
29
-
30
- extract_rel_path() {
31
- wh_decode_json_command "$1" \
32
- | sed -nE 's#.*"?\$(\{CLAUDE_PLUGIN_ROOT\}|CLAUDE_PLUGIN_ROOT)"?/([A-Za-z0-9_./-]+).*#\2#p' \
33
- | head -1
34
- }
35
-
36
- # Extract the script path token from a hook command.
37
- # For interpreter-prefixed commands (e.g. `bash ${CLAUDE_PLUGIN_ROOT}/x.sh`)
38
- # the path is NOT $1 (which is the interpreter) — pick the token containing
39
- # ${CLAUDE_PLUGIN_ROOT}; otherwise fall back to the first token.
40
- extract_path_part() {
41
- local cmd="$1" rel
42
- rel=$(extract_rel_path "$cmd")
43
- if [[ -n "$rel" ]]; then
44
- printf '${CLAUDE_PLUGIN_ROOT}/%s' "$rel"
45
- else
46
- wh_decode_json_command "$cmd" | awk '{print $1}' | tr -d "\"'\\\\"
47
- fi
48
- }
49
-
50
- # Extract a meaningful wrapper name from a hook command.
51
- # Returns an extensionless name to avoid colliding with original plugin files.
52
- get_wrapper_name() {
53
- local cmd="$1"
54
-
55
- # "tool mcp -k inject-secure-defaults" -> "inject-secure-defaults"
56
- if [[ "$cmd" =~ -k[[:space:]]+([^[:space:]]+) ]]; then
57
- echo "${BASH_REMATCH[1]}"
58
- return
59
- fi
60
-
61
- # "${CLAUDE_PLUGIN_ROOT}/scripts/check_version.sh" -> "check-version"
62
- # "$CLAUDE_PLUGIN_ROOT"/scripts/check_version.sh -> "check-version"
63
- local rel_path
64
- rel_path=$(extract_rel_path "$cmd")
65
- if [[ -n "$rel_path" ]]; then
66
- local base
67
- base=$(basename "$rel_path")
68
- base="${base%.*}"
69
- echo "${base//_/-}"
70
- return
71
- fi
72
-
73
- # Bare command: "foo bar baz" -> "foo-bar-baz"
74
- local name
75
- name=$(wh_decode_json_command "$cmd" | awk '{for(i=1;i<=3&&i<=NF;i++){printf "%s",$i;if(i<3&&i<NF)printf "-"}}')
76
- name=$(printf '%s' "$name" | sed 's/[^a-zA-Z0-9-]//g')
77
- echo "${name:-hook-wrapper}"
78
- }
79
-
80
- # Generate bash wrapper script content for an incompatible command.
81
- generate_wrapper() {
82
- local cmd="$1"
83
- local shell_cmd rel_path
84
- shell_cmd=$(wh_decode_json_command "$cmd")
85
- rel_path=$(extract_rel_path "$cmd")
86
-
87
- # .sh script via CLAUDE_PLUGIN_ROOT
88
- if [[ -n "$rel_path" && "$shell_cmd" == *".sh"* ]]; then
89
- printf '#!/bin/bash\nSCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"\nPLUGIN_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"\nexec bash "$PLUGIN_ROOT/%s" "$@"\n' "$rel_path"
90
- return
91
- fi
92
-
93
- # Interpreter-prefixed Python script via CLAUDE_PLUGIN_ROOT
94
- # (e.g. `python3 ${CLAUDE_PLUGIN_ROOT}/hooks/x.py`). Always wrapped on Windows:
95
- # exec the real Python resolved at patch time (PY_RESOLVED, found by a
96
- # functional probe — see resolve_python) so the hook works even when `python3`
97
- # is only the Microsoft Store stub. Resolving once at patch time (not per
98
- # invocation) keeps hot hooks like PreToolUse from paying a second Python
99
- # startup. Graceful no-op if no working Python exists. Copying python.exe ->
100
- # python3.exe (CASE-09) can't be relied on — system installs like
101
- # C:\ProgramData aren't writable without admin — so the wrapper is the fix.
102
- if [[ -n "$rel_path" ]]; then
103
- local interp
104
- interp=$(printf '%s' "$shell_cmd" | awk '{print $1}' | tr -d "\"'\\\\")
105
- if [[ "$interp" == "python3" || "$interp" == "python" ]]; then
106
- if [[ -n "$PY_RESOLVED" ]]; then
107
- printf '#!/bin/bash\nSCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"\nPLUGIN_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"\nexec "%s" "$PLUGIN_ROOT/%s" "$@"\n' "$PY_RESOLVED" "$rel_path"
108
- else
109
- printf '#!/bin/bash\n# win-hooks: no working Python found at patch time — graceful no-op\nexit 0\n'
110
- fi
111
- return
112
- fi
113
- fi
114
-
115
- # Non-.sh path via CLAUDE_PLUGIN_ROOT
116
- if [[ -n "$rel_path" ]]; then
117
- printf '#!/bin/bash\nSCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"\nPLUGIN_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"\nexec "$PLUGIN_ROOT/%s" "$@"\n' "$rel_path"
118
- return
119
- fi
120
-
121
- # Bare command with dependency check
122
- local dep
123
- dep=$(printf '%s' "$shell_cmd" | awk '{print $1}')
124
- printf '#!/bin/bash\nif ! command -v "%s" &>/dev/null; then\n exit 0\nfi\n%s\n' "$dep" "$shell_cmd"
125
- }
126
-
127
- # Sanitize a file: strip UTF-8 BOM and normalize CRLF -> LF.
128
- # Pure bash — no external runtime needed (uses od + sed from coreutils).
129
- sanitize_file() {
130
- local file="$1"
131
- # Strip BOM (EF BB BF) if present at start of file
132
- local bom
133
- bom=$(od -A n -t x1 -N 3 "$file" 2>/dev/null | tr -d ' \n')
134
- if [[ "$bom" == "efbbbf" ]]; then
135
- tail -c +4 "$file" > "${file}.tmp" && mv "${file}.tmp" "$file"
136
- fi
137
- # Normalize CRLF -> LF (sed 's/\r$//' is GNU sed, shipped with Git Bash)
138
- sed -i 's/\r$//' "$file" 2>/dev/null || {
139
- sed 's/\r$//' "$file" > "${file}.tmp" && mv "${file}.tmp" "$file"
140
- }
141
- }
142
-
143
- # Replace a command string in hooks.json using exact (literal) matching.
144
- # Uses awk index() which is not regex-based, so no escaping issues.
145
- # After replacement: strips BOM, normalizes CRLF, validates JSON.
146
- # If validation fails, restores from .bak and reports error.
147
- patch_hooks_json() {
148
- local hooks_file="$1"
149
- export _PATCH_OLD="$2" _PATCH_NEW="$3"
150
- awk '
151
- BEGIN { old = ENVIRON["_PATCH_OLD"]; new = ENVIRON["_PATCH_NEW"] }
152
- {
153
- idx = index($0, old)
154
- if (idx > 0) {
155
- print substr($0, 1, idx-1) new substr($0, idx + length(old))
156
- } else {
157
- print
158
- }
159
- }
160
- ' "$hooks_file" > "${hooks_file}.tmp" && mv "${hooks_file}.tmp" "$hooks_file"
161
- unset _PATCH_OLD _PATCH_NEW
162
-
163
- # Sanitize output (BOM + CRLF)
164
- sanitize_file "$hooks_file"
165
-
166
- # Validate JSON — restore backup if broken
167
- local err
168
- if err=$(wh_validate_json "$hooks_file"); then
169
- : # valid
170
- else
171
- echo "win-hooks: patched JSON is invalid, restoring backup: $hooks_file" >&2
172
- [[ -n "$err" ]] && echo " $err" >&2
173
- if [[ -f "${hooks_file}.bak" ]]; then
174
- cp "${hooks_file}.bak" "$hooks_file"
175
- fi
176
- return 1
177
- fi
178
- }
179
-
180
- PY_RESOLVED=$(wh_resolve_python || true)
181
-
182
- # Track which hooks files have been set up
183
- declare -A SETUP_DONE
184
- declare -A PATCHED_PLUGINS
185
- patched_count=0
186
-
187
- while IFS=$'\t' read -r plugin install_path hooks_file event cmd; do
188
- [[ -z "$plugin" ]] && continue
189
-
190
- scripts_dir="${install_path}/_hooks"
191
-
192
- # One-time setup per plugin
193
- if [[ -z "${SETUP_DONE[$hooks_file]:-}" ]]; then
194
- mkdir -p "$scripts_dir"
195
- # Always refresh from the current template (CASE-27) — run-hook.cmd is
196
- # pure win-hooks-owned infrastructure, never user-edited, so a template
197
- # fix (e.g. the WH_BASH_EXE override) reaches already-patched plugins on
198
- # their next patch-all run instead of only new patches.
199
- cp "$TEMPLATE_CMD" "${scripts_dir}/run-hook.cmd"
200
- [[ ! -f "${hooks_file}.bak" ]] && cp "$hooks_file" "${hooks_file}.bak"
201
- # Pre-sanitize: strip BOM/CRLF before any patching so awk works cleanly
202
- sanitize_file "$hooks_file"
203
- SETUP_DONE[$hooks_file]=1
204
- fi
205
-
206
- wrapper_name=$(get_wrapper_name "$cmd")
207
- wrapper_content=$(generate_wrapper "$cmd")
208
- wrapper_path="${scripts_dir}/${wrapper_name}"
209
-
210
- # Write wrapper — skip if existing non-wrapper file
211
- if [[ -f "$wrapper_path" ]]; then
212
- existing=$(cat "$wrapper_path")
213
- if [[ "$existing" != "#!/bin/bash"* ]]; then
214
- continue
215
- fi
216
- # Skip rewrite if content matches
217
- if [[ "$existing" != "$wrapper_content" ]]; then
218
- printf '%s' "$wrapper_content" > "$wrapper_path"
219
- fi
220
- else
221
- printf '%s' "$wrapper_content" > "$wrapper_path"
222
- fi
223
-
224
- # Build new command (JSON-escaped form for text replacement)
225
- new_cmd='\"${CLAUDE_PLUGIN_ROOT}/_hooks/run-hook.cmd\" '"${wrapper_name}"
226
-
227
- # For CLAUDE_PLUGIN_ROOT paths, preserve genuine trailing arguments.
228
- # Strip everything up to AND INCLUDING the script path token (which the
229
- # wrapper body already encodes), so an interpreter prefix or the path
230
- # itself is never re-appended as a bogus arg.
231
- rel_path=$(extract_rel_path "$cmd")
232
- if [[ -n "$rel_path" ]]; then
233
- extra_args=$(wh_decode_json_command "$cmd" \
234
- | sed -E 's#.*"?\$(\{CLAUDE_PLUGIN_ROOT\}|CLAUDE_PLUGIN_ROOT)"?/[A-Za-z0-9_./-]+##' \
235
- | sed -E 's/^[\"[:space:]]+//; s/[[:space:]]+$//')
236
- [[ -n "$extra_args" ]] && new_cmd="${new_cmd} ${extra_args}"
237
- fi
238
-
239
- # Replace command in hooks.json
240
- patch_hooks_json "$hooks_file" "$cmd" "$new_cmd"
241
-
242
- # Track patched plugins
243
- if [[ -z "${PATCHED_PLUGINS[$plugin]:-}" ]]; then
244
- PATCHED_PLUGINS[$plugin]=1
245
- patched_count=$((patched_count + 1))
246
- echo "PATCHED: $plugin" >&2
247
- fi
248
- done
249
-
250
- echo "patched: $patched_count"
@@ -1,108 +0,0 @@
1
- #!/bin/bash
2
- # win-hooks: codex-apply-patches
3
- # Reads rows from codex-find-incompatible and adds commandWindows wrappers.
4
-
5
- set -euo pipefail
6
-
7
- if [[ $# -lt 1 ]]; then
8
- echo "Usage: codex-apply-patches <template_cmd_path>" >&2
9
- exit 1
10
- fi
11
-
12
- TEMPLATE_CMD="$1"
13
- [[ -f "$TEMPLATE_CMD" ]] || { echo "Template not found: $TEMPLATE_CMD" >&2; exit 1; }
14
-
15
- SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
16
- LIB="${SCRIPT_DIR}/lib/plugins.sh"
17
- if [[ ! -f "$LIB" ]]; then
18
- echo "win-hooks: shared lib not found: $LIB" >&2
19
- exit 1
20
- fi
21
- source "$LIB"
22
-
23
- extract_rel_path() {
24
- wh_decode_json_command "$1" \
25
- | sed -nE 's#.*"?\$(\{PLUGIN_ROOT\}|PLUGIN_ROOT)"?/([A-Za-z0-9_./-]+).*#\2#p' \
26
- | head -1
27
- }
28
-
29
- wrapper_name_for() {
30
- local cmd="$1" rel base name
31
- rel=$(extract_rel_path "$cmd")
32
- if [[ -n "$rel" ]]; then
33
- base=$(basename "$rel")
34
- base="${base%.*}"
35
- printf '%s' "${base//_/-}" | sed 's/[^a-zA-Z0-9-]//g'
36
- return
37
- fi
38
- name=$(wh_decode_json_command "$cmd" | awk '{for(i=1;i<=3&&i<=NF;i++){printf "%s",$i;if(i<3&&i<NF)printf "-"}}')
39
- printf '%s' "$name" | sed 's/[^a-zA-Z0-9-]//g'
40
- }
41
-
42
- generate_wrapper() {
43
- local cmd="$1" shell_cmd rel interp dep
44
- shell_cmd=$(wh_decode_json_command "$cmd")
45
- rel=$(extract_rel_path "$cmd")
46
- if [[ -n "$rel" ]]; then
47
- interp=$(printf '%s' "$shell_cmd" | awk '{print $1}' | tr -d "\"'\\\\")
48
- wh_wrapper_exec_body "$rel" "$interp"
49
- return
50
- fi
51
- # Bare command: run it only if the dependency resolves at hook time.
52
- dep=$(printf '%s' "$shell_cmd" | awk '{print $1}')
53
- printf '#!/bin/bash\nif ! command -v "%s" >/dev/null 2>&1; then\n exit 0\nfi\nexec %s "$@"\n' "$dep" "$shell_cmd"
54
- }
55
-
56
- patch_hooks_json() {
57
- local hooks_file="$1" event="$2" group_index="$3" hook_index="$4" command_windows="$5"
58
- export WH_EVENT="$event" WH_GROUP_INDEX="$group_index" WH_HOOK_INDEX="$hook_index" WH_COMMAND_WINDOWS="$command_windows"
59
- node - "$hooks_file" <<'JSEOF'
60
- const fs = require('fs');
61
- const file = process.argv[2];
62
- const event = process.env.WH_EVENT;
63
- const groupIndex = Number(process.env.WH_GROUP_INDEX);
64
- const hookIndex = Number(process.env.WH_HOOK_INDEX);
65
- const commandWindows = process.env.WH_COMMAND_WINDOWS;
66
- const raw = fs.readFileSync(file, 'utf8').replace(/^\uFEFF/, '');
67
- const data = JSON.parse(raw);
68
- const hook = data.hooks?.[event]?.[groupIndex]?.hooks?.[hookIndex];
69
- if (!hook || hook.type !== 'command') {
70
- process.stderr.write(`win-hooks: hook index not found in ${file}\n`);
71
- process.exit(1);
72
- }
73
- if (!hook.commandWindows) hook.commandWindows = commandWindows;
74
- fs.writeFileSync(file, JSON.stringify(data, null, 2) + '\n');
75
- JSEOF
76
- unset WH_EVENT WH_GROUP_INDEX WH_HOOK_INDEX WH_COMMAND_WINDOWS
77
- }
78
-
79
- declare -A SETUP_DONE
80
- declare -A PATCHED
81
- patched_count=0
82
-
83
- while IFS=$'\t' read -r plugin install_path hooks_file event group_index hook_index cmd; do
84
- [[ -z "${plugin:-}" ]] && continue
85
- hooks_dir="${install_path}/_codex_hooks"
86
- if [[ -z "${SETUP_DONE[$hooks_file]:-}" ]]; then
87
- mkdir -p "$hooks_dir"
88
- [[ ! -f "${hooks_dir}/run-hook.cmd" ]] && cp "$TEMPLATE_CMD" "${hooks_dir}/run-hook.cmd"
89
- [[ ! -f "${hooks_file}.codex-win-hooks.bak" ]] && cp "$hooks_file" "${hooks_file}.codex-win-hooks.bak"
90
- SETUP_DONE[$hooks_file]=1
91
- fi
92
-
93
- wrapper=$(wrapper_name_for "$cmd")
94
- wrapper="${wrapper:-codex-hook-wrapper}"
95
- wrapper_path="${hooks_dir}/${wrapper}"
96
- generate_wrapper "$cmd" > "$wrapper_path"
97
-
98
- command_windows="\"\${PLUGIN_ROOT}\\_codex_hooks\\run-hook.cmd\" ${wrapper}"
99
- patch_hooks_json "$hooks_file" "$event" "$group_index" "$hook_index" "$command_windows"
100
-
101
- if [[ -z "${PATCHED[$plugin]:-}" ]]; then
102
- PATCHED[$plugin]=1
103
- patched_count=$((patched_count + 1))
104
- echo "PATCHED: $plugin" >&2
105
- fi
106
- done
107
-
108
- echo "patched: $patched_count"
@@ -1,94 +0,0 @@
1
- #!/bin/bash
2
- # win-hooks: codex-find-incompatible
3
- # Outputs tab-separated rows:
4
- # plugin_id install_path hooks_file event group_index hook_index command
5
-
6
- set -uo pipefail
7
-
8
- NEWER_THAN=""
9
- if [[ "${1:-}" == "--newer" ]]; then
10
- NEWER_THAN="${2:-}"
11
- fi
12
-
13
- if ! command -v codex >/dev/null 2>&1; then
14
- exit 0
15
- fi
16
- if ! command -v node >/dev/null 2>&1; then
17
- echo "win-hooks: node not found, cannot inspect Codex plugins" >&2
18
- exit 1
19
- fi
20
-
21
- PLUGIN_LIST=$(codex plugin list --json 2>/dev/null) || exit 0
22
- export PLUGIN_LIST NEWER_THAN
23
-
24
- node <<'JSEOF'
25
- const fs = require('fs');
26
- const path = require('path');
27
-
28
- const list = JSON.parse(process.env.PLUGIN_LIST || '{}');
29
- const newerThan = process.env.NEWER_THAN || '';
30
- const newerTime = newerThan && fs.existsSync(newerThan) ? fs.statSync(newerThan).mtimeMs : 0;
31
-
32
- function normalize(p) {
33
- return String(p || '').replace(/^\\\\\?\\/, '').replace(/\\/g, '/');
34
- }
35
-
36
- function hasPluginRoot(cmd) {
37
- return /\$\{?PLUGIN_ROOT\}?/.test(cmd);
38
- }
39
-
40
- function isIncompatible(cmd, commandWindows) {
41
- if (!cmd || commandWindows) return false;
42
- const c = String(cmd).replace(/\\"/g, '"').trim();
43
- if (!c) return false;
44
- if (/\.cmd(\s|$|")/i.test(c) || /\.exe(\s|$|")/i.test(c)) return false;
45
- if (/\.sh(\s|$|")/i.test(c)) return true;
46
- if (hasPluginRoot(c)) {
47
- const first = c.split(/\s+/)[0].replace(/^["']|["']$/g, '');
48
- if (/^(node|npx|npm)$/i.test(first)) return false;
49
- return true;
50
- }
51
- const first = c.split(/\s+/)[0].replace(/^["']|["']$/g, '');
52
- if (/^(node|npx|npm|powershell|powershell\.exe|pwsh|cmd|cmd\.exe)$/i.test(first)) return false;
53
- return false;
54
- }
55
-
56
- for (const plugin of list.installed || []) {
57
- if (!plugin.installed || !plugin.enabled) continue;
58
- const pluginId = plugin.pluginId || `${plugin.name || 'unknown'}@${plugin.marketplaceName || 'unknown'}`;
59
- if (/^(win-hooks|codex-win-hooks)@/.test(pluginId) || plugin.name === 'win-hooks') continue;
60
- const installPath = normalize(plugin.source && plugin.source.path);
61
- if (!installPath) continue;
62
- const manifest = path.join(installPath, '.codex-plugin', 'plugin.json');
63
- if (!fs.existsSync(manifest)) continue;
64
- let meta;
65
- try {
66
- meta = JSON.parse(fs.readFileSync(manifest, 'utf8').replace(/^\uFEFF/, ''));
67
- } catch {
68
- continue;
69
- }
70
- if (!meta.hooks) continue;
71
- const hooksFile = normalize(path.resolve(installPath, meta.hooks));
72
- if (!fs.existsSync(hooksFile)) continue;
73
- if (newerTime && fs.statSync(hooksFile).mtimeMs <= newerTime) continue;
74
- let data;
75
- try {
76
- data = JSON.parse(fs.readFileSync(hooksFile, 'utf8').replace(/^\uFEFF/, ''));
77
- } catch {
78
- continue;
79
- }
80
- const hooks = data.hooks || {};
81
- for (const [event, groups] of Object.entries(hooks)) {
82
- if (!Array.isArray(groups)) continue;
83
- groups.forEach((group, groupIndex) => {
84
- const commands = Array.isArray(group && group.hooks) ? group.hooks : [];
85
- commands.forEach((hook, hookIndex) => {
86
- if (!hook || hook.type !== 'command') return;
87
- if (isIncompatible(hook.command || '', hook.commandWindows || '')) {
88
- console.log([pluginId, installPath, hooksFile, event, groupIndex, hookIndex, hook.command].join('\t'));
89
- }
90
- });
91
- });
92
- }
93
- }
94
- JSEOF