@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.
- package/README.md +36 -130
- package/bin/win-hooks.mjs +94 -60
- package/hooks/codex-hooks.json +7 -7
- package/hooks/hooks.json +4 -4
- package/hooks/run-hook.cmd +43 -30
- package/hooks/win-hooks +10 -0
- package/package.json +8 -13
- package/src/env.mjs +122 -0
- package/src/heal.mjs +125 -0
- package/src/hosts.mjs +122 -0
- package/src/patch.mjs +93 -0
- package/src/rules.mjs +129 -0
- package/src/settings.mjs +61 -0
- package/src/verify.mjs +196 -0
- package/hooks/codex-patch-all +0 -75
- package/hooks/patch-all +0 -169
- package/hooks/reheal +0 -71
- package/scripts/apply-patches +0 -250
- package/scripts/codex-apply-patches +0 -108
- package/scripts/codex-find-incompatible +0 -94
- package/scripts/codex-verify +0 -393
- package/scripts/find-incompatible +0 -82
- package/scripts/fix-backslash-paths +0 -94
- package/scripts/fix-bare-commands +0 -147
- package/scripts/lib/plugins.sh +0 -132
- package/scripts/sync-version +0 -42
- package/scripts/verify +0 -334
package/src/env.mjs
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
// Runtime discovery and encoding-safe file IO.
|
|
2
|
+
//
|
|
3
|
+
// Every interpreter probe here is FUNCTIONAL, never a path heuristic: an
|
|
4
|
+
// interpreter counts as usable only if it actually runs. That is the only way
|
|
5
|
+
// to tell a real Python from a dead Microsoft Store App Execution Alias stub,
|
|
6
|
+
// which sits on PATH, answers `where`, and then fails on exec (CASE-09).
|
|
7
|
+
|
|
8
|
+
import { spawnSync } from 'node:child_process';
|
|
9
|
+
import { existsSync, readFileSync, writeFileSync, copyFileSync, statSync } from 'node:fs';
|
|
10
|
+
import { homedir } from 'node:os';
|
|
11
|
+
|
|
12
|
+
export const HOME = process.env.HOME || process.env.USERPROFILE || homedir();
|
|
13
|
+
|
|
14
|
+
export const isWindows = () => process.platform === 'win32';
|
|
15
|
+
|
|
16
|
+
export const toPosix = (p) => String(p || '').replace(/^\\\\\?\\/, '').replace(/\\/g, '/');
|
|
17
|
+
|
|
18
|
+
const memo = new Map();
|
|
19
|
+
const once = (key, fn) => {
|
|
20
|
+
if (!memo.has(key)) memo.set(key, fn());
|
|
21
|
+
return memo.get(key);
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
// Absolute paths a bare name resolves to, best candidate first.
|
|
25
|
+
const whichAll = (name) => once('which:' + name, () => {
|
|
26
|
+
const r = spawnSync('where.exe', [name], { encoding: 'utf8', windowsHide: true });
|
|
27
|
+
if (r.status !== 0) return [];
|
|
28
|
+
return (r.stdout || '').split(/\r?\n/).map((s) => s.trim()).filter(Boolean);
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
// Does this exact binary actually run? A missing binary and a dead Store alias
|
|
32
|
+
// stub both surface here as non-zero.
|
|
33
|
+
const runs = (exe, args) => {
|
|
34
|
+
const r = spawnSync(exe, args, { stdio: 'ignore', windowsHide: true, timeout: 10000 });
|
|
35
|
+
return !r.error && r.status === 0;
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
// Absolute path for a bare interpreter, or null when it cannot be trusted.
|
|
39
|
+
// Probing each candidate absolutely (rather than the PATH-resolved name alone)
|
|
40
|
+
// keeps a real Store-installed Python while rejecting the dead alias stub.
|
|
41
|
+
export const resolveInterpreter = (name) => once('interp:' + name, () => {
|
|
42
|
+
for (const abs of whichAll(name)) {
|
|
43
|
+
if (/^python3?$/.test(name) && !runs(abs, ['-c', ''])) continue;
|
|
44
|
+
return toPosix(abs);
|
|
45
|
+
}
|
|
46
|
+
return null;
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
// The first Python that truly executes. Hooks say `python3`; Windows often only
|
|
50
|
+
// has `python`, and sometimes only the stub answers to either.
|
|
51
|
+
export const resolvePython = () => once('python', () =>
|
|
52
|
+
['python3', 'python', 'py'].reduce((found, name) => found || resolveInterpreter(name), null));
|
|
53
|
+
|
|
54
|
+
export const hasCommand = (name) => whichAll(name).length > 0;
|
|
55
|
+
|
|
56
|
+
// ── Encoding-safe file IO ─────────────────────────────────────────────
|
|
57
|
+
// A UTF-8 BOM breaks JSON.parse, bash shebangs, and cmd.exe label parsing
|
|
58
|
+
// (CASE-01); CRLF breaks bash script execution (CASE-02/03). Strip both on the
|
|
59
|
+
// way in, and never write either back out.
|
|
60
|
+
|
|
61
|
+
export function hasBom(file) {
|
|
62
|
+
try {
|
|
63
|
+
const head = readFileSync(file);
|
|
64
|
+
return head[0] === 0xef && head[1] === 0xbb && head[2] === 0xbf;
|
|
65
|
+
} catch {
|
|
66
|
+
return false;
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export const readText = (file) => readFileSync(file, 'utf8').replace(/^\uFEFF/, '');
|
|
71
|
+
|
|
72
|
+
export function hasCrlf(file) {
|
|
73
|
+
try {
|
|
74
|
+
return readText(file).includes('\r\n');
|
|
75
|
+
} catch {
|
|
76
|
+
return false;
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
export function readJson(file) {
|
|
81
|
+
try {
|
|
82
|
+
return { ok: true, data: JSON.parse(readText(file)) };
|
|
83
|
+
} catch (e) {
|
|
84
|
+
return { ok: false, error: e.message };
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
// Always LF, always BOM-free, always newline-terminated.
|
|
89
|
+
export const writeJson = (file, data) =>
|
|
90
|
+
writeText(file, JSON.stringify(data, null, 2) + '\n');
|
|
91
|
+
|
|
92
|
+
export const writeText = (file, body) =>
|
|
93
|
+
writeFileSync(file, body.replace(/^\uFEFF/, '').replace(/\r\n/g, '\n'), 'utf8');
|
|
94
|
+
|
|
95
|
+
// Normalize a file in place; returns the corruptions repaired.
|
|
96
|
+
export function sanitize(file) {
|
|
97
|
+
if (!existsSync(file)) return [];
|
|
98
|
+
const raw = readFileSync(file, 'utf8');
|
|
99
|
+
const fixed = [];
|
|
100
|
+
if (raw.startsWith('\uFEFF')) fixed.push('bom');
|
|
101
|
+
if (raw.includes('\r\n')) fixed.push('crlf');
|
|
102
|
+
if (fixed.length) writeText(file, raw);
|
|
103
|
+
return fixed;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
// Back up exactly once. The first backup is the pristine pre-win-hooks state
|
|
107
|
+
// and must never be overwritten by an already-patched file.
|
|
108
|
+
export function backupOnce(file, suffix) {
|
|
109
|
+
const bak = file + suffix;
|
|
110
|
+
if (!existsSync(bak)) copyFileSync(file, bak);
|
|
111
|
+
return bak;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
// Newest mtime across a set of files; 0 when none exist.
|
|
115
|
+
export const newestMtime = (files) => files.reduce((max, f) => {
|
|
116
|
+
try {
|
|
117
|
+
const { mtimeMs } = statSync(f);
|
|
118
|
+
return Math.max(max, mtimeMs);
|
|
119
|
+
} catch {
|
|
120
|
+
return max;
|
|
121
|
+
}
|
|
122
|
+
}, 0);
|
package/src/heal.mjs
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
// Orchestration: the one code path every surface goes through - the plugin's
|
|
2
|
+
// own hooks, the CLI, and the slash commands.
|
|
3
|
+
//
|
|
4
|
+
// Two rules govern this file. Nothing is ever written to stdout from a hook: a
|
|
5
|
+
// UserPromptSubmit hook's stdout is injected into the model's context, so
|
|
6
|
+
// progress chatter would silently poison every prompt. And an environmental
|
|
7
|
+
// failure degrades to a no-op rather than breaking the session it exists to
|
|
8
|
+
// protect.
|
|
9
|
+
|
|
10
|
+
import { appendFileSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
|
11
|
+
import { join, dirname } from 'node:path';
|
|
12
|
+
import { fileURLToPath } from 'node:url';
|
|
13
|
+
import { newestMtime, readJson, writeJson, writeText } from './env.mjs';
|
|
14
|
+
import { HOSTS } from './hosts.mjs';
|
|
15
|
+
import { findIncompatible, patchAll } from './patch.mjs';
|
|
16
|
+
import { fixSettings } from './settings.mjs';
|
|
17
|
+
import { verify } from './verify.mjs';
|
|
18
|
+
|
|
19
|
+
const ROOT = join(dirname(fileURLToPath(import.meta.url)), '..');
|
|
20
|
+
const TEMPLATE_CMD = join(ROOT, 'hooks/run-hook.cmd');
|
|
21
|
+
|
|
22
|
+
const stateFile = (host, name) => join(host.stateDir, name);
|
|
23
|
+
|
|
24
|
+
// Proof-of-run on disk. The happy path is silent, so without this a healthy
|
|
25
|
+
// run, a run killed by the session-start timeout, and a hook that never
|
|
26
|
+
// dispatched at all are indistinguishable. Kept to the last 50 lines.
|
|
27
|
+
//
|
|
28
|
+
// The same directory also holds a `root` marker naming this install, which is how
|
|
29
|
+
// the slash commands and skill locate win-hooks without re-deriving it from
|
|
30
|
+
// installed_plugins.json.
|
|
31
|
+
function record(host, fields) {
|
|
32
|
+
try {
|
|
33
|
+
mkdirSync(host.stateDir, { recursive: true });
|
|
34
|
+
writeText(stateFile(host, 'root'), ROOT.replace(/\\/g, '/') + '\n');
|
|
35
|
+
|
|
36
|
+
const log = stateFile(host, 'last-run.log');
|
|
37
|
+
const stamp = new Date().toISOString().replace(/\.\d+Z$/, '');
|
|
38
|
+
const line = [stamp, ...Object.entries(fields).map(([k, v]) => k + '=' + v)].join('\t');
|
|
39
|
+
appendFileSync(log, line + '\n');
|
|
40
|
+
|
|
41
|
+
const lines = readFileSync(log, 'utf8').split('\n').filter(Boolean);
|
|
42
|
+
if (lines.length > 50) writeFileSync(log, lines.slice(-50).join('\n') + '\n');
|
|
43
|
+
} catch { /* never fail a session over telemetry */ }
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
// Can this run be skipped? A plugin update reinstalls hooks.json in its
|
|
47
|
+
// unpatched form (CASE-13) after SessionStart has already fired, so the
|
|
48
|
+
// per-prompt guard is what re-heals mid-session (CASE-26).
|
|
49
|
+
//
|
|
50
|
+
// The guard must not enumerate: listing Codex plugins costs a subprocess plus a
|
|
51
|
+
// manifest read per plugin, far too much to pay on every prompt. So each full
|
|
52
|
+
// run records what it watched, and the guard only stats that list:
|
|
53
|
+
//
|
|
54
|
+
// every hooks.json seen - an update rewriting one moves its mtime
|
|
55
|
+
// their parent dirs - a hook file added or removed moves the dir's
|
|
56
|
+
// the host registry - a plugin installed, removed, or enabled moves it
|
|
57
|
+
//
|
|
58
|
+
// Anything newer than the stamp means there may be work, and only then is the
|
|
59
|
+
// real scan run. A false positive costs one full heal; there is no false
|
|
60
|
+
// negative, since nothing can change a hooks.json without moving one of these.
|
|
61
|
+
const watchList = (host, plugins) =>
|
|
62
|
+
[...new Set([...host.registry, ...plugins.flatMap((p) => [p.hooksFile, dirname(p.hooksFile)])])];
|
|
63
|
+
|
|
64
|
+
function unchanged(host) {
|
|
65
|
+
const stamp = newestMtime([stateFile(host, 'stamp')]);
|
|
66
|
+
const watched = readJson(stateFile(host, 'seen.json'));
|
|
67
|
+
if (!stamp || !watched.ok || !Array.isArray(watched.data)) return false;
|
|
68
|
+
return newestMtime(watched.data) <= stamp;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
// The stamp is written last, after every hooks.json this run rewrote, so a
|
|
72
|
+
// repair never re-triggers itself on the next prompt.
|
|
73
|
+
const commit = (host, plugins) => {
|
|
74
|
+
try {
|
|
75
|
+
mkdirSync(host.stateDir, { recursive: true });
|
|
76
|
+
writeJson(stateFile(host, 'seen.json'), watchList(host, plugins));
|
|
77
|
+
writeFileSync(stateFile(host, 'stamp'), '');
|
|
78
|
+
} catch { /* best effort */ }
|
|
79
|
+
};
|
|
80
|
+
|
|
81
|
+
// Scan, patch, and verify one host. Returns a summary; prints nothing.
|
|
82
|
+
export function heal(hostId, { changedOnly = false } = {}) {
|
|
83
|
+
const host = HOSTS[hostId];
|
|
84
|
+
const started = Date.now();
|
|
85
|
+
if (changedOnly && unchanged(host)) return null;
|
|
86
|
+
|
|
87
|
+
const plugins = host.listPlugins();
|
|
88
|
+
const { patched, failed } = patchAll(host, TEMPLATE_CMD, plugins);
|
|
89
|
+
const settings = fixSettings(host.settingsFile, { fix: true });
|
|
90
|
+
const { issues, fixes } = verify(host, { fix: true, templateCmd: TEMPLATE_CMD, plugins });
|
|
91
|
+
|
|
92
|
+
commit(host, plugins);
|
|
93
|
+
record(host, {
|
|
94
|
+
dur: (Date.now() - started) + 'ms',
|
|
95
|
+
plugins: plugins.length,
|
|
96
|
+
patched: patched.length,
|
|
97
|
+
settings: settings.length,
|
|
98
|
+
fixed: fixes.length,
|
|
99
|
+
issues: issues.length,
|
|
100
|
+
});
|
|
101
|
+
|
|
102
|
+
return { host, patched, failed, settings, issues, fixes };
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
// Report without touching anything.
|
|
106
|
+
export function inspect(hostId) {
|
|
107
|
+
const host = HOSTS[hostId];
|
|
108
|
+
const plugins = host.listPlugins();
|
|
109
|
+
return {
|
|
110
|
+
host,
|
|
111
|
+
plugins,
|
|
112
|
+
incompatible: findIncompatible(host, plugins),
|
|
113
|
+
issues: verify(host, { plugins }).issues,
|
|
114
|
+
settings: fixSettings(host.settingsFile),
|
|
115
|
+
log: readLog(host),
|
|
116
|
+
};
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
function readLog(host, lines = 5) {
|
|
120
|
+
try {
|
|
121
|
+
return readFileSync(stateFile(host, 'last-run.log'), 'utf8').trim().split('\n').slice(-lines);
|
|
122
|
+
} catch {
|
|
123
|
+
return [];
|
|
124
|
+
}
|
|
125
|
+
}
|
package/src/hosts.mjs
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
// Host descriptors.
|
|
2
|
+
//
|
|
3
|
+
// Claude Code and Codex differ in four ways: how plugins are enumerated, which
|
|
4
|
+
// variable names the plugin root, where wrappers live, and how a patch is
|
|
5
|
+
// recorded. Claude rewrites "command" in place; Codex adds a "commandWindows"
|
|
6
|
+
// sibling so the portable command keeps working on macOS and Linux. Scanning,
|
|
7
|
+
// wrapper generation, and verification are identical, so they are shared.
|
|
8
|
+
|
|
9
|
+
import { spawnSync } from 'node:child_process';
|
|
10
|
+
import { existsSync } from 'node:fs';
|
|
11
|
+
import { join, resolve } from 'node:path';
|
|
12
|
+
import { HOME, readJson, toPosix } from './env.mjs';
|
|
13
|
+
|
|
14
|
+
// Both hosts use the same hooks.json shape:
|
|
15
|
+
// { hooks: { <Event>: [ { hooks: [ { type: "command", command } ] } ] } }
|
|
16
|
+
export function* eachHook(data) {
|
|
17
|
+
for (const [event, groups] of Object.entries(data?.hooks || {})) {
|
|
18
|
+
if (!Array.isArray(groups)) continue;
|
|
19
|
+
for (const group of groups) {
|
|
20
|
+
for (const hook of group?.hooks || []) {
|
|
21
|
+
if (hook?.type === 'command') yield { event, hook };
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
// win-hooks never patches itself.
|
|
28
|
+
const isSelf = (id) => /win-hooks/i.test(id);
|
|
29
|
+
|
|
30
|
+
const target = (id, installPath, hooksFile) =>
|
|
31
|
+
(existsSync(hooksFile) ? [{ id, installPath, hooksFile }] : []);
|
|
32
|
+
|
|
33
|
+
// ── Claude Code ───────────────────────────────────────────────────────
|
|
34
|
+
|
|
35
|
+
// installed_plugins.json is v1 ({ "name@src": [{installPath}] }) or v2
|
|
36
|
+
// ({ version: 2, plugins: {...} }). Parsing the JSON rather than pattern
|
|
37
|
+
// matching its text handles both, plus minified files (CASE-06).
|
|
38
|
+
function listClaudePlugins() {
|
|
39
|
+
const { ok, data } = readJson(join(HOME, '.claude/plugins/installed_plugins.json'));
|
|
40
|
+
if (!ok) return [];
|
|
41
|
+
const table = data?.version === 2 ? data.plugins : data;
|
|
42
|
+
|
|
43
|
+
return Object.entries(table || {}).flatMap(([id, entries]) => {
|
|
44
|
+
if (isSelf(id) || !Array.isArray(entries)) return [];
|
|
45
|
+
return entries.flatMap((entry) => {
|
|
46
|
+
const installPath = toPosix(entry?.installPath);
|
|
47
|
+
return installPath ? target(id, installPath, installPath + '/hooks/hooks.json') : [];
|
|
48
|
+
});
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
const claude = {
|
|
53
|
+
id: 'claude',
|
|
54
|
+
label: 'Claude Code',
|
|
55
|
+
rootVar: 'CLAUDE_PLUGIN_ROOT',
|
|
56
|
+
wrapperDir: '_hooks',
|
|
57
|
+
bakSuffix: '.bak',
|
|
58
|
+
stateDir: join(HOME, '.claude/win-hooks'),
|
|
59
|
+
settingsFile: join(HOME, '.claude/settings.json'),
|
|
60
|
+
// Files that change when the plugin set does. The per-prompt guard stats
|
|
61
|
+
// these to rule out work without enumerating anything (CASE-26).
|
|
62
|
+
registry: [join(HOME, '.claude/plugins/installed_plugins.json'), join(HOME, '.claude/settings.json')],
|
|
63
|
+
listPlugins: listClaudePlugins,
|
|
64
|
+
// Claude replaces the command outright, so an already-patched hook is one
|
|
65
|
+
// that already points at our wrapper - which isIncompatible sees as a .cmd.
|
|
66
|
+
sourceCommand: (hook) => hook.command,
|
|
67
|
+
patchedCommand: (hook) => hook.command,
|
|
68
|
+
applyPatch: (hook, ref) => { hook.command = ref; },
|
|
69
|
+
wrapperRef: (wrapper, args) =>
|
|
70
|
+
'"${CLAUDE_PLUGIN_ROOT}/_hooks/run-hook.cmd" ' + wrapper + (args ? ' ' + args : ''),
|
|
71
|
+
};
|
|
72
|
+
|
|
73
|
+
// ── Codex ─────────────────────────────────────────────────────────────
|
|
74
|
+
|
|
75
|
+
function listCodexPlugins() {
|
|
76
|
+
// Through cmd.exe because `codex` on Windows is a .cmd shim, which
|
|
77
|
+
// spawnSync cannot execute directly. The command is a fixed string, so
|
|
78
|
+
// there is nothing here for a shell to interpolate.
|
|
79
|
+
const r = spawnSync('cmd.exe', ['/d', '/s', '/c', 'codex plugin list --json'], {
|
|
80
|
+
encoding: 'utf8', windowsHide: true, timeout: 30000,
|
|
81
|
+
});
|
|
82
|
+
let data;
|
|
83
|
+
try { data = JSON.parse(r.stdout); } catch { return []; }
|
|
84
|
+
|
|
85
|
+
return (data?.installed || []).flatMap((plugin) => {
|
|
86
|
+
if (!plugin?.installed || !plugin?.enabled) return [];
|
|
87
|
+
const id = plugin.pluginId || plugin.name || 'unknown';
|
|
88
|
+
const installPath = toPosix(plugin.source?.path);
|
|
89
|
+
if (isSelf(id) || !installPath) return [];
|
|
90
|
+
|
|
91
|
+
// Codex plugins declare their hooks file(s) in the manifest - one path, or
|
|
92
|
+
// an array of them (one file per event is the idiomatic layout).
|
|
93
|
+
const manifest = readJson(join(installPath, '.codex-plugin/plugin.json'));
|
|
94
|
+
const declared = manifest.ok ? manifest.data?.hooks : null;
|
|
95
|
+
return [declared].flat().flatMap((rel) =>
|
|
96
|
+
(typeof rel === 'string' ? target(id, installPath, toPosix(resolve(installPath, rel))) : []));
|
|
97
|
+
});
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
const codex = {
|
|
101
|
+
id: 'codex',
|
|
102
|
+
label: 'Codex',
|
|
103
|
+
rootVar: 'PLUGIN_ROOT',
|
|
104
|
+
wrapperDir: '_codex_hooks',
|
|
105
|
+
bakSuffix: '.codex-win-hooks.bak',
|
|
106
|
+
stateDir: join(HOME, '.codex/win-hooks'),
|
|
107
|
+
settingsFile: null,
|
|
108
|
+
// Codex records every install, removal, enable, and marketplace update in
|
|
109
|
+
// config.toml, so one stat covers the whole plugin set.
|
|
110
|
+
registry: [join(HOME, '.codex/config.toml')],
|
|
111
|
+
listPlugins: listCodexPlugins,
|
|
112
|
+
// A hook that already carries commandWindows is patched; leave the portable
|
|
113
|
+
// command alone so it still runs natively on macOS and Linux.
|
|
114
|
+
sourceCommand: (hook) => (hook.commandWindows ? null : hook.command),
|
|
115
|
+
patchedCommand: (hook) => hook.commandWindows,
|
|
116
|
+
applyPatch: (hook, ref) => { hook.commandWindows = ref; },
|
|
117
|
+
// Codex dispatches commandWindows through cmd.exe, which wants backslashes.
|
|
118
|
+
wrapperRef: (wrapper, args) =>
|
|
119
|
+
'"${PLUGIN_ROOT}\\_codex_hooks\\run-hook.cmd" ' + wrapper + (args ? ' ' + args : ''),
|
|
120
|
+
};
|
|
121
|
+
|
|
122
|
+
export const HOSTS = { claude, codex };
|
package/src/patch.mjs
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
// Scan installed plugins and repair Windows-incompatible hooks.
|
|
2
|
+
//
|
|
3
|
+
// One pass per plugin: read hooks.json once, decide, write once. Because the
|
|
4
|
+
// JSON is parsed rather than pattern-matched, a malformed result is impossible
|
|
5
|
+
// by construction - no write-then-validate-then-restore dance is needed.
|
|
6
|
+
|
|
7
|
+
import { existsSync, mkdirSync, copyFileSync, readFileSync } from 'node:fs';
|
|
8
|
+
import { join } from 'node:path';
|
|
9
|
+
import { backupOnce, hasCommand, readJson, sanitize, writeJson, writeText } from './env.mjs';
|
|
10
|
+
import { eachHook } from './hosts.mjs';
|
|
11
|
+
import { isIncompatible, trailingArgs, wrapperBody, wrapperName } from './rules.mjs';
|
|
12
|
+
|
|
13
|
+
const scanOpts = (host) => ({ rootVar: host.rootVar, isInstalled: hasCommand });
|
|
14
|
+
|
|
15
|
+
// Hooks in this plugin that still need a Windows wrapper.
|
|
16
|
+
function incompatibleHooks(host, plugin) {
|
|
17
|
+
const { ok, data, error } = readJson(plugin.hooksFile);
|
|
18
|
+
if (!ok) return { error };
|
|
19
|
+
|
|
20
|
+
const opts = scanOpts(host);
|
|
21
|
+
const targets = [];
|
|
22
|
+
for (const entry of eachHook(data)) {
|
|
23
|
+
const command = host.sourceCommand(entry.hook);
|
|
24
|
+
if (command && isIncompatible(command, opts)) targets.push({ ...entry, command });
|
|
25
|
+
}
|
|
26
|
+
return { data, targets };
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
// Repair one plugin. Returns null when nothing needed doing - the
|
|
30
|
+
// overwhelmingly common case, which must stay cheap.
|
|
31
|
+
function patchPlugin(host, plugin, templateCmd) {
|
|
32
|
+
// BOM/CRLF are corruption in their own right (CASE-01/02/03); clear them
|
|
33
|
+
// whether or not this plugin turns out to need a wrapper.
|
|
34
|
+
sanitize(plugin.hooksFile);
|
|
35
|
+
const { error, data, targets } = incompatibleHooks(host, plugin);
|
|
36
|
+
if (error) return { plugin, error: 'hooks.json is not valid JSON: ' + error };
|
|
37
|
+
if (!targets.length) return null;
|
|
38
|
+
|
|
39
|
+
const wrapperDir = join(plugin.installPath, host.wrapperDir);
|
|
40
|
+
mkdirSync(wrapperDir, { recursive: true });
|
|
41
|
+
|
|
42
|
+
// Always refresh run-hook.cmd (CASE-27). It is win-hooks-owned infrastructure
|
|
43
|
+
// users never edit, so template fixes must reach already-patched plugins.
|
|
44
|
+
copyFileSync(templateCmd, join(wrapperDir, 'run-hook.cmd'));
|
|
45
|
+
backupOnce(plugin.hooksFile, host.bakSuffix);
|
|
46
|
+
|
|
47
|
+
const wrappers = [];
|
|
48
|
+
for (const { hook, command } of targets) {
|
|
49
|
+
const name = wrapperName(command, host.rootVar);
|
|
50
|
+
const body = wrapperBody(command, host.rootVar);
|
|
51
|
+
const file = join(wrapperDir, name);
|
|
52
|
+
|
|
53
|
+
// Never clobber a file that is not one of ours.
|
|
54
|
+
const existing = existsSync(file) ? readFileSync(file, 'utf8') : null;
|
|
55
|
+
if (existing !== null && !existing.startsWith('#!/bin/bash')) continue;
|
|
56
|
+
if (existing !== body) writeText(file, body);
|
|
57
|
+
|
|
58
|
+
host.applyPatch(hook, host.wrapperRef(name, trailingArgs(command, host.rootVar)));
|
|
59
|
+
wrappers.push(name);
|
|
60
|
+
}
|
|
61
|
+
if (!wrappers.length) return null;
|
|
62
|
+
|
|
63
|
+
writeJson(plugin.hooksFile, data);
|
|
64
|
+
return { plugin, wrappers };
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export function patchAll(host, templateCmd, plugins = host.listPlugins()) {
|
|
68
|
+
const patched = [];
|
|
69
|
+
const failed = [];
|
|
70
|
+
for (const plugin of plugins) {
|
|
71
|
+
let result;
|
|
72
|
+
try {
|
|
73
|
+
result = patchPlugin(host, plugin, templateCmd);
|
|
74
|
+
} catch (e) {
|
|
75
|
+
// One unreadable plugin must never abort the rest of the run.
|
|
76
|
+
failed.push({ plugin, error: e.message });
|
|
77
|
+
continue;
|
|
78
|
+
}
|
|
79
|
+
if (!result) continue;
|
|
80
|
+
(result.error ? failed : patched).push(result);
|
|
81
|
+
}
|
|
82
|
+
return { patched, failed };
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
// Report-only: which hooks would be patched.
|
|
86
|
+
export function findIncompatible(host, plugins = host.listPlugins()) {
|
|
87
|
+
const out = [];
|
|
88
|
+
for (const plugin of plugins) {
|
|
89
|
+
const { targets } = incompatibleHooks(host, plugin);
|
|
90
|
+
for (const { event, command } of targets || []) out.push({ ...plugin, event, command });
|
|
91
|
+
}
|
|
92
|
+
return out;
|
|
93
|
+
}
|
package/src/rules.mjs
ADDED
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
// The domain knowledge: which hook commands break on Windows, what to name the
|
|
2
|
+
// wrapper that replaces them, and what that wrapper contains.
|
|
3
|
+
//
|
|
4
|
+
// This is the one module worth reading to understand win-hooks; everything else
|
|
5
|
+
// is plumbing. Each rule maps to a CASE in AGENTS.md.
|
|
6
|
+
|
|
7
|
+
import { resolvePython } from './env.mjs';
|
|
8
|
+
|
|
9
|
+
// Hook commands are stored JSON-escaped; recover the shell command as written.
|
|
10
|
+
const decode = (cmd) => String(cmd || '').replace(/\\"/g, '"');
|
|
11
|
+
|
|
12
|
+
const head = (cmd) =>
|
|
13
|
+
decode(cmd).trim().split(/\s+/)[0].replace(/^["']|["']$/g, '').replace(/\\/g, '');
|
|
14
|
+
|
|
15
|
+
// The plugin-root-relative target a command points at, e.g.
|
|
16
|
+
// bash ${CLAUDE_PLUGIN_ROOT}/hooks/check.sh -> hooks/check.sh
|
|
17
|
+
export function relPath(cmd, rootVar) {
|
|
18
|
+
const re = new RegExp('"?\\$(?:\\{' + rootVar + '\\}|' + rootVar + ')"?/([A-Za-z0-9_./-]+)');
|
|
19
|
+
const m = decode(cmd).match(re);
|
|
20
|
+
return m ? m[1] : '';
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
// Arguments that follow the script path and must survive the rewrite. The path
|
|
24
|
+
// itself is baked into the wrapper body, so re-appending it would be a bug.
|
|
25
|
+
export function trailingArgs(cmd, rootVar) {
|
|
26
|
+
const re = new RegExp('.*"?\\$(?:\\{' + rootVar + '\\}|' + rootVar + ')"?/[A-Za-z0-9_./-]+');
|
|
27
|
+
return decode(cmd).replace(re, '').replace(/^["\s]+|\s+$/g, '');
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
// Does this hook command need a Windows wrapper?
|
|
31
|
+
//
|
|
32
|
+
// isInstalled is injected so the bare-binary rule stays testable, and so the
|
|
33
|
+
// Codex lane can opt out of it.
|
|
34
|
+
export function isIncompatible(cmd, { rootVar, isInstalled = () => true } = {}) {
|
|
35
|
+
const c = decode(cmd).trim();
|
|
36
|
+
if (!c) return false;
|
|
37
|
+
if (/\.cmd(\s|"|$)/i.test(c)) return false; // already wrapped
|
|
38
|
+
if (/\.exe(\s|"|$)/i.test(c)) return false; // native Windows binary
|
|
39
|
+
if (/\.sh(\s|"|$)/i.test(c)) return true; // CASE-07: cmd.exe cannot run .sh
|
|
40
|
+
|
|
41
|
+
const h = head(c);
|
|
42
|
+
if (relPath(c, rootVar)) {
|
|
43
|
+
// CASE-09: bare python may be a dead Store stub, and the cmd.exe that
|
|
44
|
+
// dispatches the hook can resolve a different interpreter than Git Bash
|
|
45
|
+
// does. Always wrap, so a probed absolute path is what actually runs.
|
|
46
|
+
if (/^python3?$/.test(h)) return true;
|
|
47
|
+
// Node tooling resolves reliably under both dispatchers.
|
|
48
|
+
if (/^(node|npx|npm)$/.test(h)) return false;
|
|
49
|
+
// A plain plugin-root .py path is handed to the OS, not to a shell.
|
|
50
|
+
if (/\.py(\s|"|$)/i.test(c)) return false;
|
|
51
|
+
return true;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
// CASE-08: a bare Unix-only binary that simply is not installed here.
|
|
55
|
+
if (!/[/\\$]/.test(h)) return !isInstalled(h);
|
|
56
|
+
return false;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
// Wrapper filenames are extensionless, so Claude Code's Windows auto-detection
|
|
60
|
+
// does not prepend "bash" to anything containing ".sh" (CASE-07).
|
|
61
|
+
export function wrapperName(cmd, rootVar) {
|
|
62
|
+
const c = decode(cmd);
|
|
63
|
+
|
|
64
|
+
// A keyed invocation names itself after its subject:
|
|
65
|
+
// tool mcp -k inject-secure-defaults -> inject-secure-defaults
|
|
66
|
+
const keyed = c.match(/-k\s+(\S+)/);
|
|
67
|
+
if (keyed) return keyed[1];
|
|
68
|
+
|
|
69
|
+
const rel = relPath(c, rootVar);
|
|
70
|
+
if (rel) {
|
|
71
|
+
const base = rel.split('/').pop().replace(/\.[^.]*$/, '');
|
|
72
|
+
return base.replace(/_/g, '-').replace(/[^A-Za-z0-9-]/g, '');
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
const name = c.trim().split(/\s+/).slice(0, 3).join('-').replace(/[^A-Za-z0-9-]/g, '');
|
|
76
|
+
return name || 'hook-wrapper';
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
const PREAMBLE =
|
|
80
|
+
'#!/bin/bash\n' +
|
|
81
|
+
'SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"\n' +
|
|
82
|
+
'PLUGIN_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"\n';
|
|
83
|
+
|
|
84
|
+
export const passthroughBody = () =>
|
|
85
|
+
'#!/bin/bash\n# win-hooks: exec the real target passed through by run-hook.cmd\nexec bash "$@"\n';
|
|
86
|
+
|
|
87
|
+
export const disabledBody = (why) =>
|
|
88
|
+
'#!/bin/bash\n# win-hooks: disabled - ' + why + '\nexit 0\n';
|
|
89
|
+
|
|
90
|
+
// The wrapper body. Bash, because it has to exec .sh targets and inherits the
|
|
91
|
+
// plugin-root convention every hook already relies on.
|
|
92
|
+
export function wrapperBody(cmd, rootVar) {
|
|
93
|
+
const c = decode(cmd);
|
|
94
|
+
const rel = relPath(c, rootVar);
|
|
95
|
+
const h = head(c);
|
|
96
|
+
|
|
97
|
+
if (rel) {
|
|
98
|
+
if (/^python3?$/.test(h)) {
|
|
99
|
+
// Resolved once at patch time, not per invocation: hot hooks such as
|
|
100
|
+
// PreToolUse should not pay a second interpreter startup.
|
|
101
|
+
const py = resolvePython();
|
|
102
|
+
if (!py) return disabledBody('no working Python found at patch time');
|
|
103
|
+
return PREAMBLE + 'exec "' + py + '" "$PLUGIN_ROOT/' + rel + '" "$@"\n';
|
|
104
|
+
}
|
|
105
|
+
if (/\.sh$/.test(rel) || /^(bash|sh)$/.test(h)) {
|
|
106
|
+
return PREAMBLE + 'exec bash "$PLUGIN_ROOT/' + rel + '" "$@"\n';
|
|
107
|
+
}
|
|
108
|
+
return PREAMBLE + 'exec "$PLUGIN_ROOT/' + rel + '" "$@"\n';
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
// CASE-08: stay silent when the dependency is genuinely absent, rather than
|
|
112
|
+
// failing the hook loudly on every single invocation.
|
|
113
|
+
return '#!/bin/bash\nif ! command -v "' + h + '" >/dev/null 2>&1; then\n exit 0\nfi\n' + c.trim() + '\n';
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
// A wrapper body is "broken" when it execs a target that cannot exist: the
|
|
117
|
+
// interpreter name captured instead of the script (exec "$PLUGIN_ROOT/bash"),
|
|
118
|
+
// or a path that is simply absent. Symptom: bash: .../bash: No such file.
|
|
119
|
+
export function brokenWrapperTarget(body, installPath, existsAt) {
|
|
120
|
+
const escaped = body.match(/\\"\$(?:\{)?(?:CLAUDE_)?PLUGIN_ROOT(?:\})?\\"\/([A-Za-z0-9_./-]+)/);
|
|
121
|
+
if (escaped) return { kind: 'escaped-quotes', rel: escaped[1] };
|
|
122
|
+
|
|
123
|
+
const m = body.match(/exec (?:[^\s"]+ )?"\$PLUGIN_ROOT\/([^"]+)"/);
|
|
124
|
+
if (!m) return null;
|
|
125
|
+
const rel = m[1];
|
|
126
|
+
if (/^(bash|sh|python3?|node|npx|npm)$/.test(rel)) return { kind: 'interpreter', rel };
|
|
127
|
+
if (!existsAt(installPath + '/' + rel)) return { kind: 'missing-target', rel };
|
|
128
|
+
return null;
|
|
129
|
+
}
|
package/src/settings.mjs
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
// Repairs for ~/.claude/settings.json hook commands.
|
|
2
|
+
//
|
|
3
|
+
// These hooks are dispatched through cmd.exe, whose environment is not Git
|
|
4
|
+
// Bash's. Two things break as a result, and both are rewrites of the command
|
|
5
|
+
// string rather than wrapper generation - so they live apart from the plugin
|
|
6
|
+
// pipeline.
|
|
7
|
+
|
|
8
|
+
import { existsSync } from 'node:fs';
|
|
9
|
+
import { backupOnce, readJson, resolveInterpreter, writeJson } from './env.mjs';
|
|
10
|
+
|
|
11
|
+
// CASE-20: a Windows path inside a hook command loses its backslashes to shell
|
|
12
|
+
// unescaping, producing MODULE_NOT_FOUND. Forward slashes survive.
|
|
13
|
+
const forwardSlashes = (cmd) => cmd.replace(/([A-Za-z]):\\([^\s"]*)/g, (m) => m.replace(/\\/g, '/'));
|
|
14
|
+
|
|
15
|
+
// CASE-11: a bare interpreter resolves in Git Bash but not always under
|
|
16
|
+
// cmd.exe. Bake in the absolute path we probed instead.
|
|
17
|
+
const BARE = /^(node|python3|python|npx|npm)(\s|$)/;
|
|
18
|
+
function absoluteInterpreter(cmd) {
|
|
19
|
+
const m = cmd.match(BARE);
|
|
20
|
+
if (!m) return cmd;
|
|
21
|
+
const abs = resolveInterpreter(m[1]);
|
|
22
|
+
return abs ? '"' + abs + '"' + cmd.slice(m[1].length) : cmd;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
// Walk every { command } in the settings tree, applying both repairs.
|
|
26
|
+
function rewrite(node, path, changes) {
|
|
27
|
+
if (Array.isArray(node)) {
|
|
28
|
+
node.forEach((item, i) => rewrite(item, path + '[' + i + ']', changes));
|
|
29
|
+
return;
|
|
30
|
+
}
|
|
31
|
+
if (!node || typeof node !== 'object') return;
|
|
32
|
+
|
|
33
|
+
if (typeof node.command === 'string') {
|
|
34
|
+
const slashed = forwardSlashes(node.command);
|
|
35
|
+
if (slashed !== node.command) changes.push({ path, type: 'backslash_path', from: node.command, to: slashed });
|
|
36
|
+
|
|
37
|
+
const resolved = absoluteInterpreter(slashed);
|
|
38
|
+
if (resolved !== slashed) changes.push({ path, type: 'bare_command', from: slashed, to: resolved });
|
|
39
|
+
|
|
40
|
+
node.command = resolved;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
for (const [key, value] of Object.entries(node)) {
|
|
44
|
+
if (key !== 'command') rewrite(value, path + '.' + key, changes);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
// Returns the changes found. With { fix: true } they are also written to disk.
|
|
49
|
+
export function fixSettings(file, { fix = false } = {}) {
|
|
50
|
+
if (!file || !existsSync(file)) return [];
|
|
51
|
+
const { ok, data } = readJson(file);
|
|
52
|
+
if (!ok || !data?.hooks) return [];
|
|
53
|
+
|
|
54
|
+
const changes = [];
|
|
55
|
+
rewrite(data.hooks, 'hooks', changes);
|
|
56
|
+
if (changes.length && fix) {
|
|
57
|
+
backupOnce(file, '.winhooks.bak');
|
|
58
|
+
writeJson(file, data);
|
|
59
|
+
}
|
|
60
|
+
return changes;
|
|
61
|
+
}
|