@yasaswy.nagavolu/agents 0.26.14 → 0.26.17

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 (38) hide show
  1. package/README.md +4 -0
  2. package/bin/cli.js +43 -6
  3. package/content/global/hooks/project_hook.sh +13 -11
  4. package/content/global/hooks/pyrun.js +461 -0
  5. package/content/global/hooks/store_guard.js +220 -0
  6. package/content/global/hooks/store_guard_rules.json +126 -0
  7. package/content/hooks/conclusion-scribe/README.md +1 -1
  8. package/content/hooks/tracker_proof_gate.py +1 -1
  9. package/content/manifest.json +146 -42
  10. package/content/proxy/README.md +28 -28
  11. package/content/proxy/agent_dispatch_guard.py +1 -1
  12. package/content/proxy/agent_model_guard.py +1 -1
  13. package/content/proxy/credential_mutation_guard.py +1 -1
  14. package/content/proxy/gitlab_mutation_guard.py +1 -1
  15. package/content/proxy/handover_ledger_hook.py +1 -1
  16. package/content/proxy/headless_spawn_guard.py +1 -1
  17. package/content/proxy/managed_files_guard.py +1 -1
  18. package/content/proxy/prd_closing_gate.py +1 -1
  19. package/content/proxy/publish_guard.py +1 -1
  20. package/content/proxy/web_search_guard.py +1 -1
  21. package/content/skills/README.md +4 -0
  22. package/content/skills/html-mocker/audit.js +11 -1
  23. package/content/skills/html-mocker/tests/test_audit.py +18 -0
  24. package/content/skills/low-ram-advisor/SKILL.md +68 -0
  25. package/content/skills/low-ram-advisor/advisor.py +529 -0
  26. package/content/skills/low-ram-advisor/tests/test_advisor.py +533 -0
  27. package/content/skills/publish-article/SKILL.md +13 -1
  28. package/content/skills/publish-article/caption_review.py +124 -0
  29. package/content/skills/publish-article/publish_article.py +35 -1
  30. package/content/skills/publish-article/review_store.py +8 -6
  31. package/content/skills/publish-article/tests/test_caption_review.py +71 -0
  32. package/content/skills/publish-article/tests/test_publish_article.py +92 -0
  33. package/lib/install.js +15 -6
  34. package/lib/pyrun.js +15 -0
  35. package/lib/pythonHooks.js +215 -0
  36. package/lib/update.js +5 -5
  37. package/lib/wiring.js +66 -90
  38. package/package.json +1 -1
package/README.md CHANGED
@@ -92,6 +92,10 @@ agents-cli install
92
92
  `--scan-root <dir>` checks every git repo directly under `<dir>` instead of the cwd repo. `install` and `update`
93
93
  accept the same `--scan-root` plus `--fix-project-hooks` and report (or fix) bare project hooks after the run.
94
94
  Paste-ready fix from inside any repo: `npx -y @yasaswy.nagavolu/agents@latest doctor --fix`.
95
+ It also fails on Python hook launch problems: a hook or statusline command starting with a bare `python`/`python3`/`py`
96
+ token (the Microsoft Store stub makes it fail), a missing `hooks/pyrun.js` launcher, an unresolvable interpreter, and a
97
+ WindowsApps python stub ahead of a real interpreter on PATH; `--fix` rewrites the bare tokens to
98
+ `node <target>/hooks/pyrun.js <script>` and never edits PATH or App Execution Aliases.
95
99
  It also flags a project `permissions.defaultMode` weaker than the global default in `~/.claude/settings.json`
96
100
  (for example `dontAsk` under a global `bypassPermissions`); `--fix` removes it from `settings.local.json`
97
101
  only, a committed `settings.json` is reported and never edited. The `permission_mode_enforce.js` hook
package/bin/cli.js CHANGED
@@ -17,7 +17,7 @@ const { updateBundles, UpdateError } = require('../lib/update');
17
17
  const { formatVersionBanner } = require('../lib/version-banner');
18
18
  const { bundleInstallState, installChip, installDetailLine, chipIsChange } = require('../lib/install-state');
19
19
  const { ledgerPath } = require('../lib/ledger');
20
- const { WiringError } = require('../lib/wiring');
20
+ const { WiringError, expectedWiringRecordsForManifest } = require('../lib/wiring');
21
21
  const { applyModels, formatPlan, ModelsError } = require('../lib/modelsApply');
22
22
  const { dispatchUsage, formatUsage } = require('../lib/modelsUsage');
23
23
  const {
@@ -39,6 +39,8 @@ const memoryIndexCheck = require('../lib/memoryIndexCheck');
39
39
  const projectHooks = require('../lib/projectHooks');
40
40
  const modeDrift = require('../lib/modeDrift');
41
41
  const permissionRules = require('../lib/permissionRules');
42
+ const pythonHooks = require('../lib/pythonHooks');
43
+ const pyrun = require('../lib/pyrun');
42
44
  const { checkModVersions } = require('../lib/claudeVersion');
43
45
 
44
46
  const PACKAGE_ROOT = path.join(__dirname, '..');
@@ -178,6 +180,12 @@ whose script file is missing, and a bare (non-launcher) project hook command, wh
178
180
  and so blocks every tool call when it is a PreToolUse hook. A launcher-form hook with a missing file fails open but is still
179
181
  reported. Without --fix nothing is modified.
180
182
 
183
+ doctor also fails on Python hook launch problems: a hook or statusline command in <target>/settings.json or the
184
+ project settings that starts with a bare python/python3/py token (the Microsoft Store stub makes it fail), a
185
+ hooks/pyrun.js launcher that is not installed, an interpreter that does not resolve, and a WindowsApps python stub
186
+ ahead of a real interpreter on PATH. --fix rewrites the bare tokens to "node <target>/hooks/pyrun.js <script>" in place;
187
+ it never edits PATH or App Execution Aliases.
188
+
181
189
  doctor also flags a project .claude/settings.json or settings.local.json whose permissions.defaultMode is weaker
182
190
  than the global default in <target>/settings.json (for example "dontAsk" under a global "bypassPermissions"), which
183
191
  silently downgrades every session in that repo. --fix removes the key from settings.local.json only; a committed
@@ -349,11 +357,10 @@ function installOneBundle({ bundleKey, bundleTitle, targetDir, targetConfig, ite
349
357
  if (result.settingsBackupFile) {
350
358
  console.log(` ${mark()} backed up existing settings.json to ${result.settingsBackupFile} before this CLI's first write`);
351
359
  }
352
- if (result.hooksSkippedNoPython.length > 0) {
353
- const names = result.hooksSkippedNoPython.map((h) => h.path).join(', ');
360
+ if (result.pythonUnresolved) {
354
361
  console.log(
355
- ` ${mark('skip')} skipped wiring ${result.hooksSkippedNoPython.length} Python hook(s) (${names}): no python3/python found on PATH. ` +
356
- `Install Python, then re-run: agents-cli install --bundle ${result.bundle} --yes`
362
+ ` ${mark('skip')} wired Python hook(s) cannot run yet: no Python 3.8+ interpreter found (Microsoft Store stubs are ignored). ` +
363
+ `Install Python 3 from python.org or set AGENTS_PYTHON; hooks pick it up on their next run.`
357
364
  );
358
365
  }
359
366
  if (result.mcpWired.length > 0) {
@@ -1211,6 +1218,20 @@ Project hooks (${step.findings.length} finding(s), ${step.repos.length} repo(s)
1211
1218
  }
1212
1219
  }
1213
1220
 
1221
+ function printPythonLaunchReport(py) {
1222
+ if (py.fixed.length > 0) {
1223
+ console.log(`\nRewrote ${py.fixed.length} bare python hook command(s) to the pyrun launcher:`);
1224
+ for (const c of py.fixed) console.log(` ${c.file}\n - ${c.from}\n + ${c.to}`);
1225
+ }
1226
+ if (py.healthy) return;
1227
+ console.log('\nPython hook launch:');
1228
+ for (const f of py.findings) console.log(` ${pythonHooks.describeFinding(f)}`);
1229
+ for (const m of py.missingLaunchers) console.log(` ${m.file}: launcher not found: ${m.launcher}`);
1230
+ if (!py.interpreter.ok) console.log(` ${pyrun.unresolvedMessage(py.interpreter, null)}`);
1231
+ for (const stub of py.stubs) console.log(` ${pythonHooks.describeStub(stub)}`);
1232
+ if (py.findings.length > 0 && !py.fixRequested) console.log(` Fix: ${projectHooks.FIX_COMMAND}`);
1233
+ }
1234
+
1214
1235
  function printModeDriftReport(modes) {
1215
1236
  if (modes.fixed.length > 0) {
1216
1237
  console.log(`\nRemoved ${modes.fixed.length} defaultMode override(s) weaker than the global "${modes.globalMode}":`);
@@ -1313,11 +1334,25 @@ function runDoctor(argv) {
1313
1334
  console.error(hooks.error);
1314
1335
  return 1;
1315
1336
  }
1337
+ const { manifest } = loadManifest(PACKAGE_ROOT);
1338
+ const py = pythonHooks.checkPythonLaunch({
1339
+ ...scope,
1340
+ fix: args.fix,
1341
+ expectedRecords: expectedWiringRecordsForManifest(manifest, scope.targetBase),
1342
+ resolve: () => pyrun.resolvePython({ stateDir: path.join(scope.targetBase, 'state') }),
1343
+ ...(process.env.NODE_ENV === 'test' && !process.env.AGENTS_CLI_PATH_STUBS ? { stubs: () => [] } : {}),
1344
+ });
1345
+ py.fixRequested = args.fix;
1346
+ if (py.error) {
1347
+ console.error(py.error);
1348
+ return 1;
1349
+ }
1316
1350
  const { fixed } = hooks;
1317
1351
  result.projectHooks = { repos: hooks.repos, findings: hooks.findings, fixed };
1318
1352
  result.modeDrift = { globalMode: modes.globalMode, findings: modes.findings, fixed: modes.fixed };
1319
1353
  result.permissionRules = { findings: rules.findings, fixed: rules.fixed };
1320
- result.healthy = result.healthy && hooks.findings.length === 0 && modes.findings.length === 0 && rules.findings.length === 0;
1354
+ result.pythonLaunch = { files: py.files, findings: py.findings, fixed: py.fixed, missingLaunchers: py.missingLaunchers, interpreter: py.interpreter, stubs: py.stubs };
1355
+ result.healthy = result.healthy && hooks.findings.length === 0 && modes.findings.length === 0 && rules.findings.length === 0 && py.healthy;
1321
1356
 
1322
1357
  if (args.json) {
1323
1358
  console.log(JSON.stringify(result, null, 2));
@@ -1361,6 +1396,7 @@ function runDoctor(argv) {
1361
1396
  };
1362
1397
 
1363
1398
  if (result.healthy) {
1399
+ printPythonLaunchReport(py);
1364
1400
  console.log(`${result.targetBase}: healthy — no orphans, no missing files, no drift.`);
1365
1401
  printModVersions();
1366
1402
  printModValidation();
@@ -1388,6 +1424,7 @@ function runDoctor(argv) {
1388
1424
  printMemoryIndex();
1389
1425
  printRoutingMod();
1390
1426
  printProjectHooks();
1427
+ printPythonLaunchReport(py);
1391
1428
  printModeDrift();
1392
1429
  return 1;
1393
1430
  } catch (err) {
@@ -23,18 +23,20 @@ slashes() {
23
23
  done
24
24
  }
25
25
 
26
- # A real interpreter first; the WindowsApps python3 stub only as a last resort.
26
+ # The interpreter pyrun.js resolved (hooks/../state), else a real one on PATH; a WindowsApps stub is never used.
27
27
  find_python() {
28
- for pass in real stub; do
29
- for cand in python3 python py; do
30
- cmd="$(command -v "$cand" 2>/dev/null)" || continue
31
- case "$cmd" in
32
- *WindowsApps*) [ "$pass" = stub ] || continue ;;
33
- *) [ "$pass" = real ] || continue ;;
34
- esac
35
- echo "$cmd"
36
- return 0
37
- done
28
+ cached=""
29
+ cache="${0%/*}/../state/python-interpreter"
30
+ if [ -f "$cache" ]; then IFS= read -r cached < "$cache" || :; fi
31
+ if [ -n "$cached" ] && [ -f "$cached" ]; then
32
+ echo "$cached"
33
+ return 0
34
+ fi
35
+ for cand in python3 python py; do
36
+ cmd="$(command -v "$cand" 2>/dev/null)" || continue
37
+ case "$cmd" in *WindowsApps*) continue ;; esac
38
+ echo "$cmd"
39
+ return 0
38
40
  done
39
41
  return 1
40
42
  }
@@ -0,0 +1,461 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+ // Runs a Python hook through an interpreter resolved at run time; hook commands never carry a bare python/python3/py token.
4
+ const fs = require('node:fs');
5
+ const os = require('node:os');
6
+ const path = require('node:path');
7
+ const { spawnSync } = require('node:child_process');
8
+
9
+ const FIX_COMMAND = 'npx -y @yasaswy.nagavolu/agents@latest doctor --fix';
10
+ const MIN_MINOR = 8;
11
+ const PROBE_TIMEOUT_MS = 8000;
12
+ const WARN_WINDOW_MS = 60000;
13
+ const PROBE_CODE = 'import sys;sys.stdout.write("%d.%d|%s"%(sys.version_info[0],sys.version_info[1],sys.executable))';
14
+ const STUB_SEGMENT = /[\\/]WindowsApps[\\/]/i;
15
+ const BARE_NAME = /^(?:python(?:3(?:\.\d+)?)?|pythonw|py|pyw|py3)(?:\.exe)?$/i;
16
+ const LAUNCHER_FLAG = /^-(?:3|2)(?:\.\d+)?(?:-\d+)?$/;
17
+ const SHELL_TOOLS = ['Bash', 'PowerShell', 'Monitor'];
18
+ const CACHE_NAME = 'python-interpreter';
19
+
20
+ const slashes = (p) => p.replace(/\\/g, '/');
21
+
22
+ const flavor = (deps) => (deps.platform === 'win32' ? path.win32 : path.posix);
23
+
24
+ function isStubPath(p) {
25
+ return STUB_SEGMENT.test(String(p));
26
+ }
27
+
28
+ function defaultDeps() {
29
+ return {
30
+ platform: process.platform,
31
+ env: process.env,
32
+ fs,
33
+ homedir: os.homedir(),
34
+ now: () => Date.now(),
35
+ run(exe, args, options) {
36
+ return spawnSync(exe, args, { encoding: 'utf8', timeout: PROBE_TIMEOUT_MS, windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'], ...options });
37
+ },
38
+ };
39
+ }
40
+
41
+ function pathDirs(deps) {
42
+ const raw = deps.env.PATH !== undefined ? deps.env.PATH : deps.env.Path || '';
43
+ const sep = deps.platform === 'win32' ? ';' : ':';
44
+ const seen = new Set();
45
+ const dirs = [];
46
+ for (const entry of raw.split(sep)) {
47
+ const dir = entry.trim().replace(/^"|"$/g, '');
48
+ const key = deps.platform === 'win32' ? dir.toLowerCase() : dir;
49
+ if (dir && !seen.has(key)) {
50
+ seen.add(key);
51
+ dirs.push(dir);
52
+ }
53
+ }
54
+ return dirs;
55
+ }
56
+
57
+ // lstat, not stat: stat fails on a Store app-execution alias, and a stub must still be seen to be skipped.
58
+ function isFile(deps, p) {
59
+ try {
60
+ return !deps.fs.lstatSync(p).isDirectory();
61
+ } catch {
62
+ return false;
63
+ }
64
+ }
65
+
66
+ function listDir(deps, dir) {
67
+ try {
68
+ return deps.fs.readdirSync(dir);
69
+ } catch {
70
+ return [];
71
+ }
72
+ }
73
+
74
+ function versionSorted(names) {
75
+ const num = (n) => Number((/(\d+(?:\.\d+)?)/.exec(n) || [0, 0])[1]);
76
+ return [...names].sort((a, b) => num(b) - num(a));
77
+ }
78
+
79
+ function windowsKnownDirs(deps) {
80
+ const env = deps.env;
81
+ const local = env.LOCALAPPDATA || flavor(deps).join(deps.homedir, 'AppData', 'Local');
82
+ const roots = [];
83
+ const addMatching = (base, re) => {
84
+ for (const name of versionSorted(listDir(deps, base).filter((n) => re.test(n)))) roots.push(flavor(deps).join(base, name));
85
+ };
86
+ addMatching(flavor(deps).join(local, 'Programs', 'Python'), /^Python3\d+/i);
87
+ addMatching(flavor(deps).join(local, 'Python'), /^pythoncore-3/i);
88
+ roots.push(flavor(deps).join(local, 'Python', 'bin'));
89
+ for (const pf of [env.ProgramFiles, env['ProgramFiles(x86)']].filter(Boolean)) addMatching(pf, /^Python3\d+/i);
90
+ addMatching(`${env.SystemDrive || 'C:'}\\`, /^Python3\d+/i);
91
+ return roots;
92
+ }
93
+
94
+ const REGISTRY_ROOTS = ['HKCU\\Software\\Python\\PythonCore', 'HKLM\\Software\\Python\\PythonCore', 'HKLM\\Software\\WOW6432Node\\Python\\PythonCore'];
95
+
96
+ function versionKey(text) {
97
+ const m = /(\d+)\.(\d+)/.exec(text);
98
+ return m ? Number(m[1]) * 1000 + Number(m[2]) : 0;
99
+ }
100
+
101
+ /** PEP 514: interpreters registered under PythonCore, highest version first. */
102
+ function registryPythons(deps) {
103
+ const found = [];
104
+ for (const root of REGISTRY_ROOTS) {
105
+ const res = deps.run('reg', ['query', root, '/s']);
106
+ if (!res || res.error || res.status !== 0) continue;
107
+ let tag = null;
108
+ for (const raw of String(res.stdout || '').split(/\r?\n/)) {
109
+ const line = raw.trim();
110
+ if (/^HK/i.test(line)) {
111
+ const key = /PythonCore\\([^\\]+)\\InstallPath$/i.exec(line);
112
+ tag = key ? key[1] : null;
113
+ continue;
114
+ }
115
+ if (!tag) continue;
116
+ const exe = /^ExecutablePath\s+REG_SZ\s+(.+\.exe)$/i.exec(line);
117
+ const dir = /^\(Default\)\s+REG_SZ\s+([A-Za-z]:[\\/].+)$/i.exec(line);
118
+ if (exe) found.push({ exe: exe[1].trim(), version: versionKey(tag) });
119
+ else if (dir) found.push({ exe: `${dir[1].trim().replace(/[\\/]+$/, '')}\\python.exe`, version: versionKey(tag) });
120
+ }
121
+ }
122
+ const seen = new Set();
123
+ return found
124
+ .sort((a, b) => b.version - a.version)
125
+ .map((p) => p.exe)
126
+ .filter((exe) => (seen.has(exe.toLowerCase()) ? false : seen.add(exe.toLowerCase())));
127
+ }
128
+
129
+ /** `py -0p`: one installed interpreter path per line, highest version first. */
130
+ function launcherListed(deps, launcher) {
131
+ const res = deps.run(launcher, ['-0p']);
132
+ if (!res || res.error || res.status !== 0) return [];
133
+ const paths = [];
134
+ for (const line of String(res.stdout || '').split(/\r?\n/)) {
135
+ const m = /^\s*-V:(\S+)\s+\*?\s*(\S.*?python[w3]*\.exe)\s*$/i.exec(line);
136
+ if (m && /^3/.test(m[1].replace(/^[^\d]*/, ''))) paths.push({ exe: m[2], version: versionKey(m[1]) });
137
+ }
138
+ return paths.sort((a, b) => b.version - a.version).map((p) => p.exe);
139
+ }
140
+
141
+ /** Ordered interpreter candidates: [{exe, args, source}]. Never yields a WindowsApps path. */
142
+ function candidates(deps) {
143
+ const out = [];
144
+ const seen = new Set();
145
+ const add = (exe, args, source) => {
146
+ if (!exe || isStubPath(exe)) return;
147
+ const key = `${deps.platform === 'win32' ? exe.toLowerCase() : exe}|${args.join(' ')}`;
148
+ if (seen.has(key)) return;
149
+ seen.add(key);
150
+ out.push({ exe, args, source });
151
+ };
152
+ const override = deps.env.AGENTS_PYTHON;
153
+ if (override) add(override, [], 'AGENTS_PYTHON');
154
+ const dirs = pathDirs(deps);
155
+ if (deps.platform === 'win32') {
156
+ for (const exe of registryPythons(deps)) add(exe, [], 'registry');
157
+ const launcherDirs = [flavor(deps).join(deps.env.LOCALAPPDATA || '', 'Programs', 'Python', 'Launcher'), deps.env.WINDIR || 'C:\\Windows', ...dirs];
158
+ const launchers = launcherDirs.map((dir) => flavor(deps).join(dir, 'py.exe')).filter((exe) => !isStubPath(exe) && isFile(deps, exe));
159
+ if (launchers.length > 0) for (const exe of launcherListed(deps, launchers[0])) add(exe, [], 'py -0p');
160
+ for (const dir of windowsKnownDirs(deps)) {
161
+ const exe = flavor(deps).join(dir, 'python.exe');
162
+ if (isFile(deps, exe)) add(exe, [], 'known install');
163
+ }
164
+ for (const dir of dirs) {
165
+ for (const name of ['python.exe', 'python3.exe']) {
166
+ const exe = flavor(deps).join(dir, name);
167
+ if (isFile(deps, exe)) add(exe, [], 'PATH');
168
+ }
169
+ }
170
+ for (const exe of launchers) add(exe, ['-3'], 'py launcher');
171
+ return out;
172
+ }
173
+ for (const name of ['python3', 'python']) {
174
+ for (const dir of dirs) {
175
+ const exe = flavor(deps).join(dir, name);
176
+ if (isFile(deps, exe)) add(exe, [], 'PATH');
177
+ }
178
+ }
179
+ return out;
180
+ }
181
+
182
+ /** Runs the interpreter once; returns {ok, path, version, reason}. Stub output (exit 49, "Python was not found") is a failure. */
183
+ function probe(candidate, deps) {
184
+ const res = deps.run(candidate.exe, [...candidate.args, '-c', PROBE_CODE]);
185
+ if (!res || res.error) return { ok: false, reason: res && res.error ? res.error.code || res.error.message : 'no result' };
186
+ if (res.status !== 0) return { ok: false, reason: `exit ${res.status}` };
187
+ const m = /^(\d+)\.(\d+)\|(.+)$/.exec(String(res.stdout || '').trim());
188
+ if (!m) return { ok: false, reason: 'unexpected output' };
189
+ const real = m[3].trim();
190
+ if (Number(m[1]) !== 3 || Number(m[2]) < MIN_MINOR) return { ok: false, reason: `Python ${m[1]}.${m[2]} is too old` };
191
+ if (isStubPath(real)) return { ok: false, reason: 'reports a WindowsApps path' };
192
+ return { ok: true, path: slashes(real), version: `${m[1]}.${m[2]}` };
193
+ }
194
+
195
+ function stateDir(deps, base) {
196
+ return base || flavor(deps).join(deps.homedir, '.claude', 'state');
197
+ }
198
+
199
+ function readCache(deps, dir) {
200
+ try {
201
+ const first = String(deps.fs.readFileSync(flavor(deps).join(dir, CACHE_NAME), 'utf8')).split(/\r?\n/)[0].trim();
202
+ if (first && !isStubPath(first) && isFile(deps, first)) return first;
203
+ } catch {
204
+ // no cache yet
205
+ }
206
+ return null;
207
+ }
208
+
209
+ function writeFileSafe(deps, file, text) {
210
+ try {
211
+ deps.fs.mkdirSync(flavor(deps).dirname(file), { recursive: true });
212
+ const tmp = `${file}.tmp-${process.pid}`;
213
+ deps.fs.writeFileSync(tmp, text);
214
+ deps.fs.renameSync(tmp, file);
215
+ } catch {
216
+ // a cache that cannot be written only costs a re-resolve
217
+ }
218
+ }
219
+
220
+ function forgetCache(deps, dir) {
221
+ try {
222
+ deps.fs.rmSync(flavor(deps).join(dir, CACHE_NAME), { force: true });
223
+ } catch {
224
+ // already gone
225
+ }
226
+ }
227
+
228
+ /** Resolve the interpreter: cache, then candidates probed in order. Returns {ok, path, version?, source, tried[]}. */
229
+ function resolvePython(options = {}) {
230
+ const deps = { ...defaultDeps(), ...options };
231
+ const dir = stateDir(deps, options.stateDir);
232
+ const tried = [];
233
+ if (!options.noCache) {
234
+ const cached = readCache(deps, dir);
235
+ if (cached) return { ok: true, path: cached, source: 'cache', tried };
236
+ }
237
+ for (const candidate of candidates(deps)) {
238
+ const res = probe(candidate, deps);
239
+ tried.push({ exe: candidate.exe, source: candidate.source, ok: res.ok, reason: res.reason || null });
240
+ if (res.ok) {
241
+ writeFileSafe(deps, flavor(deps).join(dir, CACHE_NAME), `${res.path}\n`);
242
+ return { ok: true, path: res.path, version: res.version, source: candidate.source, tried };
243
+ }
244
+ }
245
+ return { ok: false, path: null, source: null, tried };
246
+ }
247
+
248
+ /** Policy: a guard may fail closed only when its matcher leaves shell tools alone, so the repair command can still run. */
249
+ function mayFailClosed(event, matcher) {
250
+ if (event !== 'PreToolUse' || !matcher) return false;
251
+ let re;
252
+ try {
253
+ re = new RegExp(`^(?:${matcher})$`);
254
+ } catch {
255
+ return false;
256
+ }
257
+ return !SHELL_TOOLS.some((tool) => re.test(tool));
258
+ }
259
+
260
+ function commandWords(command) {
261
+ const words = [];
262
+ const re = /"([^"]*)"|'([^']*)'|(\S+)/g;
263
+ let m;
264
+ while ((m = re.exec(String(command).trim())) !== null) words.push(m[1] !== undefined ? m[1] : m[2] !== undefined ? m[2] : m[3]);
265
+ return words;
266
+ }
267
+
268
+ /** The bare interpreter token a hook command starts with (after env assignments), or null. A WindowsApps-qualified path counts as bare. */
269
+ function bareInterpreter(command) {
270
+ const words = commandWords(command);
271
+ let i = 0;
272
+ while (i < words.length && (/^[A-Za-z_]\w*=/.test(words[i]) || words[i] === 'env')) i += 1;
273
+ const first = words[i];
274
+ if (!first) return null;
275
+ const base = slashes(first).split('/').pop();
276
+ if (!BARE_NAME.test(base)) return null;
277
+ const isQualified = /[\\/]/.test(first);
278
+ return !isQualified || isStubPath(first) ? first : null;
279
+ }
280
+
281
+ /** Split `python [flags] script args` into its parts; null when the command is not a bare interpreter call. */
282
+ function splitBareCommand(command) {
283
+ const token = bareInterpreter(command);
284
+ if (token === null) return null;
285
+ const text = String(command).trim();
286
+ const at = text.indexOf(token);
287
+ const restText = text.slice(at + token.length);
288
+ const isLauncher = /^py(w)?(\.exe)?$/i.test(slashes(token).split('/').pop());
289
+ const flags = [];
290
+ let rest = restText;
291
+ for (;;) {
292
+ const m = /^\s+(-[A-Za-z0-9.]+)(?=\s|$)/.exec(rest);
293
+ if (!m) break;
294
+ if (isLauncher && LAUNCHER_FLAG.test(m[1])) {
295
+ rest = rest.slice(m[0].length);
296
+ continue;
297
+ }
298
+ if (/^-[uBsESIO]+$/.test(m[1])) {
299
+ flags.push(m[1]);
300
+ rest = rest.slice(m[0].length);
301
+ continue;
302
+ }
303
+ break;
304
+ }
305
+ return { token, prefix: text.slice(0, at), flags, rest: rest.replace(/^\s+/, '') };
306
+ }
307
+
308
+ /** Per-name PATH report for Windows: where a WindowsApps stub shadows a real interpreter or stands alone. */
309
+ function stubReport(options = {}) {
310
+ const deps = { ...defaultDeps(), ...options };
311
+ if (deps.platform !== 'win32') return [];
312
+ const dirs = pathDirs(deps);
313
+ const report = [];
314
+ for (const name of ['python.exe', 'python3.exe', 'py.exe', 'pythonw.exe']) {
315
+ const hits = dirs.map((dir) => flavor(deps).join(dir, name)).filter((p) => isFile(deps, p));
316
+ if (hits.length === 0 || !isStubPath(hits[0])) continue;
317
+ const real = hits.find((p) => !isStubPath(p)) || null;
318
+ report.push({ name, stub: hits[0], shadows: real, status: real ? 'shadows-real' : 'stub-only' });
319
+ }
320
+ return report;
321
+ }
322
+
323
+ function oneLine(text) {
324
+ return String(text).replace(/\s+/g, ' ').trim();
325
+ }
326
+
327
+ function unresolvedMessage(result, script) {
328
+ const why = result.tried.length === 0 ? 'no candidate on PATH or in the usual install folders' : `${result.tried.length} candidate(s) failed`;
329
+ return oneLine(
330
+ `pyrun: no Python 3.${MIN_MINOR}+ interpreter found (${why}; Microsoft Store stubs under WindowsApps are ignored)` +
331
+ `${script ? `, '${script}' did not run` : ''}. Install Python 3 from python.org or set AGENTS_PYTHON, then run: ${FIX_COMMAND}`
332
+ );
333
+ }
334
+
335
+ function shouldWarn(deps, dir) {
336
+ const marker = flavor(deps).join(dir, `${CACHE_NAME}.warned`);
337
+ try {
338
+ const age = deps.now() - deps.fs.statSync(marker).mtimeMs;
339
+ if (age >= 0 && age < WARN_WINDOW_MS) return false;
340
+ } catch {
341
+ // never warned
342
+ }
343
+ writeFileSafe(deps, marker, `${deps.now()}\n`);
344
+ return true;
345
+ }
346
+
347
+ function readSettings(file) {
348
+ try {
349
+ return JSON.parse(fs.readFileSync(file, 'utf8').replace(/^/, ''));
350
+ } catch {
351
+ return null;
352
+ }
353
+ }
354
+
355
+ function bareHookCommands(settings) {
356
+ const found = [];
357
+ if (!settings || typeof settings !== 'object') return found;
358
+ for (const [event, groups] of Object.entries(settings.hooks && typeof settings.hooks === 'object' ? settings.hooks : {})) {
359
+ for (const group of Array.isArray(groups) ? groups : []) {
360
+ for (const hook of group && Array.isArray(group.hooks) ? group.hooks : []) {
361
+ if (hook && typeof hook.command === 'string' && bareInterpreter(hook.command)) found.push({ event, command: hook.command });
362
+ }
363
+ }
364
+ }
365
+ for (const key of ['statusLine', 'subagentStatusLine']) {
366
+ const entry = settings[key];
367
+ if (entry && typeof entry.command === 'string' && bareInterpreter(entry.command)) found.push({ event: key, command: entry.command });
368
+ }
369
+ return found;
370
+ }
371
+
372
+ function runCheck(deps, dir, settingsFile) {
373
+ const problems = [];
374
+ const res = resolvePython({ ...deps, stateDir: dir });
375
+ if (!res.ok) problems.push(unresolvedMessage(res, null));
376
+ const bare = bareHookCommands(readSettings(settingsFile));
377
+ if (bare.length > 0) {
378
+ problems.push(`${bare.length} hook command(s) in ${settingsFile} still start with a bare python token; run: ${FIX_COMMAND}`);
379
+ }
380
+ return problems;
381
+ }
382
+
383
+ function main(argv, deps = defaultDeps()) {
384
+ const args = argv.slice(2);
385
+ const closed = args[0] === '--closed';
386
+ if (closed) args.shift();
387
+ const base = path.dirname(__dirname);
388
+ const dir = stateDir(deps, process.env.AGENTS_PYRUN_STATE_DIR || path.join(base, 'state'));
389
+ const settingsFile = path.join(base, 'settings.json');
390
+
391
+ if (args[0] === '--print') {
392
+ const res = resolvePython({ ...deps, stateDir: dir, noCache: args.includes('--fresh') });
393
+ if (!res.ok) {
394
+ process.stderr.write(`${unresolvedMessage(res, null)}\n`);
395
+ return 1;
396
+ }
397
+ process.stdout.write(`${res.path}\n`);
398
+ return 0;
399
+ }
400
+ if (args[0] === '--check') {
401
+ const problems = runCheck(deps, dir, settingsFile);
402
+ if (problems.length > 0) process.stdout.write(`${JSON.stringify({ systemMessage: `python hooks: ${problems.join(' ')}` })}\n`);
403
+ return 0;
404
+ }
405
+ if (args.length === 0) {
406
+ process.stderr.write('pyrun: usage: node pyrun.js [--closed] <python args...> | --print | --check\n');
407
+ return 1;
408
+ }
409
+
410
+ const script = args.find((a) => !a.startsWith('-'));
411
+ const label = script ? path.basename(script) : null;
412
+ let res = resolvePython({ ...deps, stateDir: dir });
413
+ let ran = null;
414
+ if (res.ok) {
415
+ ran = spawnSync(res.path, args, { stdio: 'inherit', windowsHide: true });
416
+ if (ran.error && res.source === 'cache') {
417
+ forgetCache(deps, dir);
418
+ res = resolvePython({ ...deps, stateDir: dir });
419
+ ran = res.ok ? spawnSync(res.path, args, { stdio: 'inherit', windowsHide: true }) : null;
420
+ }
421
+ }
422
+ if (ran && !ran.error) return ran.status === null ? 1 : ran.status;
423
+
424
+ const message = ran && ran.error ? oneLine(`pyrun: cannot start ${res.path}: ${ran.error.message}${label ? `, '${label}' did not run` : ''}`) : unresolvedMessage(res, label);
425
+ if (closed) {
426
+ process.stderr.write(`${message} (fail-closed guard: this tool call is blocked until Python resolves)\n`);
427
+ return 2;
428
+ }
429
+ if (shouldWarn(deps, dir)) {
430
+ process.stderr.write(`${message}\n`);
431
+ return 1;
432
+ }
433
+ return 0;
434
+ }
435
+
436
+ module.exports = {
437
+ FIX_COMMAND,
438
+ bareHookCommands,
439
+ bareInterpreter,
440
+ candidates,
441
+ mayFailClosed,
442
+ isStubPath,
443
+ launcherListed,
444
+ pathDirs,
445
+ registryPythons,
446
+ probe,
447
+ resolvePython,
448
+ splitBareCommand,
449
+ stubReport,
450
+ unresolvedMessage,
451
+ };
452
+
453
+ if (require.main === module) {
454
+ let code = 1;
455
+ try {
456
+ code = main(process.argv);
457
+ } catch (err) {
458
+ process.stderr.write(`pyrun: ${err.message}\n`);
459
+ }
460
+ process.exit(code);
461
+ }