@lincoln504/pi-research 1.7.18 → 1.7.20

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.
@@ -0,0 +1,151 @@
1
+ /**
2
+ * Where the pi HOST's copies of the peer dependencies live, when they are not installed
3
+ * beside this package.
4
+ *
5
+ * `pi install` runs npm with --legacy-peer-deps, so the managed install
6
+ * (~/.pi/agent/npm) never contains @earendil-works/* or typebox: pi hands its own copies
7
+ * to extension code in-process. The standalone engine (CLI, agent skill) is launched
8
+ * through the bin shim in a plain Node process, where Node's ESM resolver walks up
9
+ * node_modules directories only — it ignores NODE_PATH and the global root — so every
10
+ * agent call died with "required runtime dependency ... is not installed alongside it",
11
+ * and the advertised remedy (`npm install -g @earendil-works/pi-coding-agent`) could not
12
+ * help: a global install is not on that resolution path either.
13
+ *
14
+ * This module finds the host's copies in the places pi is realistically installed, so the
15
+ * shim can point the resolver at them (host-resolve-hook.mjs). Plain ESM with no imports
16
+ * from this package: it is loaded by the unbundled shim before anything else, and bundled
17
+ * into the agent-skill launcher.
18
+ */
19
+
20
+ import { existsSync, readFileSync, realpathSync } from 'node:fs';
21
+ import { homedir } from 'node:os';
22
+ import { delimiter, dirname, isAbsolute, join } from 'node:path';
23
+ import { spawnSync } from 'node:child_process';
24
+
25
+ /** The peer dependencies the engine imports at startup. */
26
+ export const HOST_PACKAGES = [
27
+ '@earendil-works/pi-ai',
28
+ '@earendil-works/pi-coding-agent',
29
+ '@earendil-works/pi-tui',
30
+ 'typebox',
31
+ ];
32
+
33
+ const PI_CODING_AGENT = ['@earendil-works', 'pi-coding-agent'];
34
+
35
+ function binsOnPath(name) {
36
+ const exts = process.platform === 'win32' ? (process.env['PATHEXT'] ?? '.EXE;.CMD').split(';') : [''];
37
+ const out = [];
38
+ for (const dir of (process.env['PATH'] ?? '').split(delimiter)) {
39
+ // Absolute entries only: a relative one (`node_modules/.bin`, `.`) resolves against the
40
+ // cwd, and a hostile checkout could plant a `pi` there that leads to ITS node_modules.
41
+ if (!dir || !isAbsolute(dir)) continue;
42
+ for (const ext of exts) {
43
+ const candidate = join(dir, name + ext);
44
+ if (existsSync(candidate)) out.push(candidate);
45
+ }
46
+ }
47
+ return out;
48
+ }
49
+
50
+ /**
51
+ * `npm root -g`, run from the home directory — never the cwd, which may be an untrusted
52
+ * checkout. On Windows npm is a .cmd shim, and running it through cmd.exe would search the
53
+ * cwd first (a planted npm.cmd would run); instead run npm's own script with the Node that is
54
+ * already running us, no shell involved.
55
+ */
56
+ function npmGlobalRoot() {
57
+ try {
58
+ let command = 'npm';
59
+ let args = ['root', '-g'];
60
+ if (process.platform === 'win32') {
61
+ const cli = join(dirname(process.execPath), 'node_modules', 'npm', 'bin', 'npm-cli.js');
62
+ if (!existsSync(cli)) return null;
63
+ command = process.execPath;
64
+ args = [cli, 'root', '-g'];
65
+ }
66
+ const r = spawnSync(command, args, { encoding: 'utf8', timeout: 8000, cwd: homedir() });
67
+ return r.status === 0 && r.stdout.trim() ? r.stdout.trim() : null;
68
+ } catch {
69
+ return null;
70
+ }
71
+ }
72
+
73
+ /**
74
+ * node_modules directories that may hold the host's packages, most specific first.
75
+ * `spawnNpm` additionally asks npm for its global root (a process spawn, so it is only
76
+ * done when the cheap candidates found nothing).
77
+ */
78
+ export function candidateNodeModulesDirs({ spawnNpm = false } = {}) {
79
+ const dirs = new Set();
80
+ const explicit = process.env['PI_RESEARCH_HOST_DIR'];
81
+ if (explicit) {
82
+ dirs.add(explicit);
83
+ dirs.add(join(explicit, 'node_modules'));
84
+ }
85
+ // The directory behind the `pi` command: <root>/node_modules/@earendil-works/pi-coding-agent/...
86
+ for (const bin of binsOnPath('pi')) {
87
+ try {
88
+ const m = /^(.*[\\/]node_modules)[\\/]/.exec(realpathSync(bin));
89
+ if (m) dirs.add(m[1]);
90
+ } catch {
91
+ /* dangling link: skip */
92
+ }
93
+ }
94
+ // pi's own managed install (pi 1.x): ~/.pi/agent/install/releases/<current-version>/node_modules.
95
+ // The `pi` on PATH is then a shell script, not a link into node_modules, so the lookup above
96
+ // cannot see it.
97
+ try {
98
+ const agentDir = process.env['PI_CODING_AGENT_DIR'] || join(homedir(), '.pi', 'agent');
99
+ const current = readFileSync(join(agentDir, 'install', 'current-version'), 'utf8').trim();
100
+ if (/^[A-Za-z0-9._+-]+$/.test(current) && current !== '.' && current !== '..') {
101
+ dirs.add(join(agentDir, 'install', 'releases', current, 'node_modules'));
102
+ }
103
+ } catch {
104
+ /* no managed install */
105
+ }
106
+ // The global root of the Node that is running us, without spawning npm.
107
+ dirs.add(join(dirname(process.execPath), '..', 'lib', 'node_modules'));
108
+ dirs.add(join(dirname(process.execPath), 'node_modules'));
109
+ dirs.add(join(homedir(), '.bun', 'install', 'global', 'node_modules'));
110
+ if (spawnNpm) {
111
+ const root = npmGlobalRoot();
112
+ if (root) dirs.add(root);
113
+ }
114
+ return [...dirs];
115
+ }
116
+
117
+ /** The node_modules directory holding `name`, searching the candidates (and pi's own nested deps). */
118
+ function locate(name, nodeModulesDirs) {
119
+ for (const nm of nodeModulesDirs) {
120
+ if (existsSync(join(nm, name, 'package.json'))) return nm;
121
+ const nested = join(nm, ...PI_CODING_AGENT, 'node_modules');
122
+ if (existsSync(join(nested, name, 'package.json'))) return nested;
123
+ }
124
+ return null;
125
+ }
126
+
127
+ /**
128
+ * Locate every host package in `names` that the caller could not resolve itself.
129
+ * @returns {{ found: Map<string, string>, missing: string[] }} name -> node_modules dir
130
+ */
131
+ export function findHostPackages(names = HOST_PACKAGES) {
132
+ const found = new Map();
133
+ // Opt-out: insist on peers installed beside the engine (strict deployments, hermetic tests).
134
+ if (process.env['PI_RESEARCH_NO_HOST_FALLBACK'] === '1') return { found, missing: [...names] };
135
+ let pending = [...names];
136
+ for (const spawnNpm of [false, true]) {
137
+ if (pending.length === 0) break;
138
+ const dirs = candidateNodeModulesDirs({ spawnNpm });
139
+ pending = pending.filter((name) => {
140
+ const nm = locate(name, dirs);
141
+ if (nm) found.set(name, nm);
142
+ return !nm;
143
+ });
144
+ }
145
+ return { found, missing: pending };
146
+ }
147
+
148
+ /** Distinct node_modules directories from a findHostPackages() result. */
149
+ export function hostDirs(found) {
150
+ return [...new Set(found.values())];
151
+ }