@lincoln504/pi-research 1.7.18 → 1.7.19

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 CHANGED
@@ -51,13 +51,16 @@ pi-research skill install
51
51
 
52
52
  No extra setup is needed. The package ships ready-made bindings for every platform and declares no build step, so there is nothing to approve or compile. The stealth browser (1GB+ installed) is fetched by the `postinstall` script whenever npm runs dependency install scripts — which is npm 10 through 11.19 (11.16–11.19 print a warning) — and that includes the npm bundled with the Node 22.22.2 floor this package requires (10.9.7) and the npm bundled with Node 24/25 (11.19.0), so expect the fetch during install. npm 12, the current npm, blocks dependency install scripts by default, and the browser is then fetched lazily on the first scrape instead. Either way the first scrape takes a few minutes until it is in place. Set `PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1` to defer the fetch deliberately.
53
53
 
54
- The `@earendil-works/pi-*` host packages are **peer dependencies**. pi supplies its own copies when it loads this as an extension, and npm ≥7 installs them automatically for a standalone (global or project) install. An install that skips peers does not get them: `npm install --legacy-peer-deps`, yarn classic, and `pi install` itself (it passes that flag on purpose) are all in that group. The standalone engine and the agent-skill launcher then stop with a message naming the missing package; add it with:
54
+ The `@earendil-works/pi-*` host packages are **peer dependencies**. pi supplies its own copies when it loads this as an extension, and npm ≥7 installs them automatically for a standalone (global or project) install. An install that skips peers does not get them: `npm install --legacy-peer-deps`, yarn classic, and `pi install` itself (it passes that flag on purpose) are all in that group. The standalone engine and the agent-skill launcher look for the host's copies where pi or a global npm install puts them (the global npm root of the running Node, the directory behind the `pi` command, bun's global root, or a directory named by `PI_RESEARCH_HOST_DIR`) and use them when they are not installed beside the engine, so a `pi install` plus a global pi works for agents with no extra step. When nothing is found they stop with a message naming the missing packages and the commands that fix it:
55
55
 
56
56
  ```bash
57
+ # into the tree pi-research is installed in (for pi: ~/.pi/agent/npm); kept across `pi update`
58
+ npm install --prefix ~/.pi/agent/npm --legacy-peer-deps @earendil-works/pi-ai @earendil-works/pi-coding-agent @earendil-works/pi-tui typebox
59
+ # or a global install, which is found automatically
57
60
  npm install -g @earendil-works/pi-coding-agent
58
61
  ```
59
62
 
60
- Standalone use needs that package on disk because the CLI and SDK import it directly. In pi, nothing is needed: the host's own copy is aliased in for both.
63
+ `PI_RESEARCH_NO_HOST_FALLBACK=1` turns the lookup off. Inside pi nothing is needed: the host's own copy is aliased in for the extension, and the browser worker bundle carries the one peer it needs (`typebox`) itself.
61
64
 
62
65
  In pi, the extension works out of the box on the session's model and pi's configuration. Standalone use ([agent skill](docs/AGENT-SKILL.md) or [SDK](docs/SDK.md)) needs a model configured. See [Configuration](docs/CONFIGURATION.md).
63
66
 
@@ -67,6 +70,8 @@ In pi, the extension works out of the box on the session's model and pi's config
67
70
 
68
71
  ### Uninstall
69
72
 
73
+ If `pi update` prints errors for this extension, check `~/.pi/agent/settings.json` (`pi list`) for a source spelled `npm:lincoln504/pi-research`, without the `@`. npm reads `lincoln504/pi-research` as a GitHub `user/repo`, so pi installs the repository's main branch (building it, and registering the extension a second time) instead of the published release. Run `pi remove npm:lincoln504/pi-research`, then `pi install npm:@lincoln504/pi-research`.
74
+
70
75
  `pi remove npm:@lincoln504/pi-research` removes the extension. `npm uninstall -g @lincoln504/pi-research` removes the standalone engine. npm 7+ no longer runs `preuninstall`, so nothing else is removed on its own: skill links into other agents (Claude Code, Codex, …), the state directory (`~/.pi/research/state`), and the cache (`~/.cache/pi-research`, including any downloaded embedding models) stay in place. Remove the skill links first with `pi-research skill uninstall` (or `/research-config` → Remove from External Agents), then remove the rest with `pi-research cleanup`: The shared stealth-browser cache (`~/.cache/camoufox`) is preserved unless `PI_RESEARCH_PURGE_BROWSERS=1`. See [AGENT-SKILL.md](docs/AGENT-SKILL.md#installation-flow) for the full picture.
71
76
 
72
77
  ### How it works
@@ -98,7 +103,7 @@ Three depth levels (normal, deep, ultra) set the team size and number of rounds.
98
103
  - Internet access on a residential IP, since search, scraping, and YouTube transcripts get bot-blocked from datacenter/VPS/cloud IPs
99
104
  - pi (`@earendil-works/pi-coding-agent`) 0.99.0 or newer, including the 1.x line. The pi extension uses the host's copy while the standalone CLI and agent skill install it as a dependency. A host newer than the last version this release was tested against still runs, with a one-line notice; the tested ceiling is in `src/core/pi-version.ts`.
100
105
  - Local knowledge-store embeddings need `@huggingface/transformers`, an optional dependency. If its native image chain (sharp) cannot install, npm skips it with a warning and the install still succeeds, so everything works except local embeddings. The store tells you how to restore them. Prefer no embedding model at all? Set `PI_RESEARCH_KNOWLEDGE_STORE_RETRIEVAL=bm25` for a pure lexical (BM25) knowledge store — see [KNOWLEDGE-STORE.md](docs/KNOWLEDGE-STORE.md).
101
- - `npm audit` on a consumer project may report a high-severity `sharp` 0.33.5 chain under `@lancedb/lancedb`. LanceDB pins an old `@huggingface/transformers` and npm ignores a dependency's `overrides`, so only the consuming project can fix it. pi-research never calls that copy. Add `"overrides": {"@lancedb/lancedb": {"@huggingface/transformers": "^4.3.1"}}` to the consuming project's `package.json` (for `pi install`, to `~/.pi/agent/npm/package.json`) to remove that chain entirely (measured 0 advisories on every install shape). The narrower `"overrides": {"sharp": "^0.35.4"}` also clears it. Details in [AUDIT-GATE.md](docs/AUDIT-GATE.md).
106
+ - `npm audit` on a consumer project reported a high-severity `sharp` 0.33.5 chain under `@lancedb/lancedb` for every release before 1.7.18: LanceDB pins an old `@huggingface/transformers` as an optional dependency and npm ignores a dependency's `overrides`. From 1.7.18 the package ships LanceDB bundled with those optional edges removed, so no override is needed (measured 0 advisories on every install shape). On an older release, add `"overrides": {"@lancedb/lancedb": {"@huggingface/transformers": "^4.3.1"}}` to the consuming project's `package.json` (for `pi install`, to `~/.pi/agent/npm/package.json`). Details in [AUDIT-GATE.md](docs/AUDIT-GATE.md).
102
107
  - Cloudflare Turnstile and similar systems block scraping on some sites. A run compensates with a wide pool of search results to scrape.
103
108
 
104
109
  ### Channels
@@ -2,7 +2,7 @@
2
2
  name: pi-research
3
3
  description: "Multi-agent web research for any coding agent. Use for anything requiring current information from the internet — news, trends, product/service/company facts, statistics, people, places, events, APIs, library behavior, or 'what is X / how does X work' questions. Also use to search a local knowledge store of previously researched findings before doing live research. Powered by the pi-research engine (search, stealth scraping, security databases, Stack Exchange). Not for reading local files, running project commands, or analyzing this repository's own source."
4
4
  license: MIT
5
- metadata: { "author": "Lincoln Deen", "version": "1.7.18", "package": "@lincoln504/pi-research", "engine": "pi-research-sdk", "openclaw": { "requires": { "bins": ["node"] } } }
5
+ metadata: { "author": "Lincoln Deen", "version": "1.7.19", "package": "@lincoln504/pi-research", "engine": "pi-research-sdk", "openclaw": { "requires": { "bins": ["node"] } } }
6
6
  allowed-tools: Bash(node:*)
7
7
  ---
8
8
 
@@ -2,10 +2,90 @@
2
2
 
3
3
  // agent-skill/pi-research/scripts/run.ts
4
4
  import { spawn } from "node:child_process";
5
- import { existsSync, readFileSync, realpathSync } from "node:fs";
6
- import { homedir, constants as osConstants } from "node:os";
7
- import { dirname, join, resolve } from "node:path";
5
+ import { existsSync as existsSync2, readFileSync, realpathSync as realpathSync2 } from "node:fs";
6
+ import { homedir as homedir2, constants as osConstants } from "node:os";
7
+ import { dirname as dirname2, join as join2, resolve } from "node:path";
8
8
  import { createRequire } from "node:module";
9
+
10
+ // src/host-roots.mjs
11
+ import { existsSync, realpathSync } from "node:fs";
12
+ import { homedir } from "node:os";
13
+ import { delimiter, dirname, join } from "node:path";
14
+ import { spawnSync } from "node:child_process";
15
+ var HOST_PACKAGES = [
16
+ "@earendil-works/pi-ai",
17
+ "@earendil-works/pi-coding-agent",
18
+ "@earendil-works/pi-tui",
19
+ "typebox"
20
+ ];
21
+ var PI_CODING_AGENT = ["@earendil-works", "pi-coding-agent"];
22
+ function binsOnPath(name) {
23
+ const exts = process.platform === "win32" ? (process.env["PATHEXT"] ?? ".EXE;.CMD").split(";") : [""];
24
+ const out = [];
25
+ for (const dir of (process.env["PATH"] ?? "").split(delimiter)) {
26
+ if (!dir) continue;
27
+ for (const ext of exts) {
28
+ const candidate = join(dir, name + ext);
29
+ if (existsSync(candidate)) out.push(candidate);
30
+ }
31
+ }
32
+ return out;
33
+ }
34
+ function candidateNodeModulesDirs({ spawnNpm = false } = {}) {
35
+ const dirs = /* @__PURE__ */ new Set();
36
+ const explicit = process.env["PI_RESEARCH_HOST_DIR"];
37
+ if (explicit) {
38
+ dirs.add(explicit);
39
+ dirs.add(join(explicit, "node_modules"));
40
+ }
41
+ for (const bin of binsOnPath("pi")) {
42
+ try {
43
+ const m = /^(.*[\\/]node_modules)[\\/]/.exec(realpathSync(bin));
44
+ if (m) dirs.add(m[1]);
45
+ } catch {
46
+ }
47
+ }
48
+ dirs.add(join(dirname(process.execPath), "..", "lib", "node_modules"));
49
+ dirs.add(join(dirname(process.execPath), "node_modules"));
50
+ dirs.add(join(homedir(), ".bun", "install", "global", "node_modules"));
51
+ if (spawnNpm) {
52
+ try {
53
+ const r = spawnSync(process.platform === "win32" ? "npm.cmd" : "npm", ["root", "-g"], {
54
+ encoding: "utf8",
55
+ timeout: 8e3,
56
+ shell: process.platform === "win32"
57
+ });
58
+ if (r.status === 0 && r.stdout.trim()) dirs.add(r.stdout.trim());
59
+ } catch {
60
+ }
61
+ }
62
+ return [...dirs];
63
+ }
64
+ function locate(name, nodeModulesDirs) {
65
+ for (const nm of nodeModulesDirs) {
66
+ if (existsSync(join(nm, name, "package.json"))) return nm;
67
+ const nested = join(nm, ...PI_CODING_AGENT, "node_modules");
68
+ if (existsSync(join(nested, name, "package.json"))) return nested;
69
+ }
70
+ return null;
71
+ }
72
+ function findHostPackages(names = HOST_PACKAGES) {
73
+ const found = /* @__PURE__ */ new Map();
74
+ if (process.env["PI_RESEARCH_NO_HOST_FALLBACK"] === "1") return { found, missing: [...names] };
75
+ let pending = [...names];
76
+ for (const spawnNpm of [false, true]) {
77
+ if (pending.length === 0) break;
78
+ const dirs = candidateNodeModulesDirs({ spawnNpm });
79
+ pending = pending.filter((name) => {
80
+ const nm = locate(name, dirs);
81
+ if (nm) found.set(name, nm);
82
+ return !nm;
83
+ });
84
+ }
85
+ return { found, missing: pending };
86
+ }
87
+
88
+ // agent-skill/pi-research/scripts/run.ts
9
89
  import { fileURLToPath } from "node:url";
10
90
  var PKG = "@lincoln504/pi-research";
11
91
  var REQUIRED_DEP = "@earendil-works/pi-coding-agent";
@@ -30,13 +110,13 @@ function resolvePackageDir(specifier, roots) {
30
110
  for (const root of candidates) {
31
111
  try {
32
112
  const pkgJson = require2.resolve(`${specifier}/package.json`, { paths: [root] });
33
- return dirname(pkgJson);
113
+ return dirname2(pkgJson);
34
114
  } catch {
35
115
  }
36
116
  }
37
117
  try {
38
118
  const pkgJson = require2.resolve(`${specifier}/package.json`);
39
- return dirname(pkgJson);
119
+ return dirname2(pkgJson);
40
120
  } catch {
41
121
  return null;
42
122
  }
@@ -47,9 +127,9 @@ function findOnPath(bin) {
47
127
  for (const dir of pathVar.split(process.platform === "win32" ? ";" : ":")) {
48
128
  if (!dir) continue;
49
129
  for (const ext of exts) {
50
- const candidate = join(dir, bin + ext);
130
+ const candidate = join2(dir, bin + ext);
51
131
  try {
52
- if (existsSync(candidate)) return candidate;
132
+ if (existsSync2(candidate)) return candidate;
53
133
  } catch {
54
134
  }
55
135
  }
@@ -57,8 +137,8 @@ function findOnPath(bin) {
57
137
  return null;
58
138
  }
59
139
  function resolveEngine(skillDir) {
60
- const home = homedir();
61
- if (process.env["PI_RESEARCH_BIN"] && existsSync(process.env["PI_RESEARCH_BIN"])) {
140
+ const home = homedir2();
141
+ if (process.env["PI_RESEARCH_BIN"] && existsSync2(process.env["PI_RESEARCH_BIN"])) {
62
142
  return { argv: [process.env["PI_RESEARCH_BIN"]], label: process.env["PI_RESEARCH_BIN"] };
63
143
  }
64
144
  const explicitPath = process.env["PI_RESEARCH_PATH"];
@@ -75,7 +155,7 @@ function resolveEngine(skillDir) {
75
155
  if (anchor && !depResolvableFrom(anchor)) depMissing(anchor);
76
156
  return { argv: [onPath], label: onPath };
77
157
  }
78
- const pkgDir = resolvePackageDir(PKG, [skillDir, process.cwd(), home, join(home, ".pi")]);
158
+ const pkgDir = resolvePackageDir(PKG, [skillDir, process.cwd(), home, join2(home, ".pi")]);
79
159
  if (pkgDir) {
80
160
  const fromPkg = engineFromPackageDir(pkgDir);
81
161
  if (fromPkg) {
@@ -83,8 +163,8 @@ function resolveEngine(skillDir) {
83
163
  return fromPkg;
84
164
  }
85
165
  }
86
- const piBin = join(home, ".pi", "bin", "pi-research");
87
- if (existsSync(piBin)) {
166
+ const piBin = join2(home, ".pi", "bin", "pi-research");
167
+ if (existsSync2(piBin)) {
88
168
  const anchor = packageAnchorFor(piBin);
89
169
  if (anchor && !depResolvableFrom(anchor)) depMissing(anchor);
90
170
  return { argv: [piBin], label: piBin };
@@ -94,7 +174,7 @@ function resolveEngine(skillDir) {
94
174
  function packageAnchorFor(binPath) {
95
175
  let real;
96
176
  try {
97
- real = realpathSync(binPath);
177
+ real = realpathSync2(binPath);
98
178
  } catch {
99
179
  return null;
100
180
  }
@@ -103,19 +183,19 @@ function packageAnchorFor(binPath) {
103
183
  }
104
184
  function engineFromPackageDir(pkgDir) {
105
185
  try {
106
- const pkg = JSON.parse(readFileSync(join(pkgDir, "package.json"), "utf-8"));
186
+ const pkg = JSON.parse(readFileSync(join2(pkgDir, "package.json"), "utf-8"));
107
187
  const binField = typeof pkg?.bin === "string" ? pkg.bin : pkg?.bin?.["pi-research"];
108
188
  if (binField) {
109
- const binPath = join(pkgDir, binField);
110
- if (existsSync(binPath)) {
189
+ const binPath = join2(pkgDir, binField);
190
+ if (existsSync2(binPath)) {
111
191
  const isJsModule = /\.(m|c)?js$/i.test(binField);
112
192
  return isJsModule ? { argv: [process.execPath, binPath], label: binPath } : { argv: [binPath], label: binPath };
113
193
  }
114
194
  }
115
195
  } catch {
116
196
  }
117
- const cliPath = join(pkgDir, "dist", "cli.mjs");
118
- if (existsSync(cliPath)) {
197
+ const cliPath = join2(pkgDir, "dist", "cli.mjs");
198
+ if (existsSync2(cliPath)) {
119
199
  return { argv: [process.execPath, cliPath], label: cliPath };
120
200
  }
121
201
  return null;
@@ -124,11 +204,16 @@ function depResolvableFrom(anchorDir) {
124
204
  const depSegs = REQUIRED_DEP.split("/");
125
205
  let dir = resolve(anchorDir);
126
206
  for (; ; ) {
127
- if (existsSync(join(dir, "node_modules", ...depSegs, "package.json"))) return true;
128
- const parent = dirname(dir);
129
- if (parent === dir) return false;
207
+ if (existsSync2(join2(dir, "node_modules", ...depSegs, "package.json"))) return true;
208
+ const parent = dirname2(dir);
209
+ if (parent === dir) break;
130
210
  dir = parent;
131
211
  }
212
+ return findHostPackages([REQUIRED_DEP]).missing.length === 0;
213
+ }
214
+ function enginePrefix(pkgDir) {
215
+ const m = /^(.*)[\\/]node_modules[\\/](?:@[^\\/]+[\\/])?[^\\/]+$/.exec(pkgDir);
216
+ return m?.[1] ?? pkgDir;
132
217
  }
133
218
  function depMissing(pkgDir) {
134
219
  const lines = [
@@ -137,15 +222,18 @@ function depMissing(pkgDir) {
137
222
  `'${REQUIRED_DEP}' is not installed alongside it.`,
138
223
  "",
139
224
  "The standalone engine imports this package at startup, so it cannot run",
140
- "without it. These three options all work:",
225
+ "without it, and none was found where pi or a global npm install puts one.",
226
+ "Any ONE of these fixes it:",
141
227
  "",
142
- " npm install -g @earendil-works/pi-coding-agent # install just the missing host package",
143
- " npm install -g @lincoln504/pi-research # global \u2014 brings it in with the engine",
144
- " # (npm >= 7 resolves peer dependencies)",
228
+ ` npm install --prefix "${enginePrefix(pkgDir)}" --legacy-peer-deps @earendil-works/pi-ai @earendil-works/pi-coding-agent @earendil-works/pi-tui typebox`,
229
+ " # into the tree the engine is installed in (kept across `pi update`)",
230
+ " npm install -g @earendil-works/pi-coding-agent # a global install is found automatically",
231
+ " npm install -g @lincoln504/pi-research # global \u2014 brings the peers in with the engine",
232
+ " export PI_RESEARCH_HOST_DIR=/path/to/node_modules # a directory that holds them",
145
233
  " # or point the launcher at a working engine: export PI_RESEARCH_PATH=/path/to/pi-research",
146
234
  "",
147
- "This happens when the install skipped peer dependencies (--legacy-peer-deps,",
148
- "yarn classic), or when pi itself provides the host package only in-process.",
235
+ "This happens when the install skipped peer dependencies (--legacy-peer-deps, which",
236
+ "`pi install` always passes; yarn classic): pi itself provides them only in-process.",
149
237
  "",
150
238
  `(engine located at: ${pkgDir})`,
151
239
  ""
@@ -154,7 +242,7 @@ function depMissing(pkgDir) {
154
242
  process.exit(EXIT.CONFIG);
155
243
  }
156
244
  function notInstalled() {
157
- const home = homedir();
245
+ const home = homedir2();
158
246
  const lines = [
159
247
  "",
160
248
  "Error: pi-research engine not found.",
@@ -176,8 +264,8 @@ function notInstalled() {
176
264
  "After installing, configure the model (PI_RESEARCH_MODEL is required) + API key.",
177
265
  "Locations:",
178
266
  ` \u2022 env vars: PI_RESEARCH_API_KEY / PI_RESEARCH_PROVIDER / PI_RESEARCH_MODEL`,
179
- ` \u2022 global config file: ${join(home, ".pi", "research", "config.env")}`,
180
- ` \u2022 pi config (keys): ${join(home, ".pi", "agent", "auth.json")} (supplies the API key only)`,
267
+ ` \u2022 global config file: ${join2(home, ".pi", "research", "config.env")}`,
268
+ ` \u2022 pi config (keys): ${join2(home, ".pi", "agent", "auth.json")} (supplies the API key only)`,
181
269
  "",
182
270
  "Run `status` once installed to verify detection.",
183
271
  ""
@@ -189,14 +277,14 @@ function hasCmdMetachar(s) {
189
277
  return /[&|<>^"%()!\r\n]/.test(s);
190
278
  }
191
279
  function resolveWinShimToNode(shimPath) {
192
- const fromLayout = engineFromPackageDir(join(dirname(shimPath), "node_modules", ...PKG.split("/")));
280
+ const fromLayout = engineFromPackageDir(join2(dirname2(shimPath), "node_modules", ...PKG.split("/")));
193
281
  if (fromLayout && fromLayout.argv[0] === process.execPath) return fromLayout;
194
282
  try {
195
283
  const content = readFileSync(shimPath, "utf-8");
196
284
  const m = content.match(/node_modules[\\/][^"\r\n]*?\.(?:mjs|cjs|js)\b/i);
197
285
  if (m) {
198
- const abs = resolve(dirname(shimPath), m[0]);
199
- if (existsSync(abs)) return { argv: [process.execPath, abs], label: abs };
286
+ const abs = resolve(dirname2(shimPath), m[0]);
287
+ if (existsSync2(abs)) return { argv: [process.execPath, abs], label: abs };
200
288
  }
201
289
  } catch {
202
290
  }
@@ -283,7 +371,7 @@ function printUsage() {
283
371
  ].join("\n")
284
372
  );
285
373
  }
286
- var here = dirname(fileURLToPath(import.meta.url));
374
+ var here = dirname2(fileURLToPath(import.meta.url));
287
375
  var engine = resolveEngine(here);
288
376
  if (!engine) notInstalled();
289
377
  launch(engine);
package/dist/cli-bin.mjs CHANGED
@@ -35,7 +35,10 @@
35
35
  */
36
36
 
37
37
  import { existsSync } from 'node:fs';
38
+ import { register } from 'node:module';
39
+ import { dirname } from 'node:path';
38
40
  import { fileURLToPath } from 'node:url';
41
+ import { findHostPackages, hostDirs } from './host-roots.mjs';
39
42
 
40
43
  const REQUIRED_PEERS = [
41
44
  '@earendil-works/pi-ai',
@@ -84,9 +87,27 @@ function probePeer(name) {
84
87
  }
85
88
 
86
89
  const status = new Map(REQUIRED_PEERS.map((name) => [name, probePeer(name)]));
87
- const missing = REQUIRED_PEERS.filter((name) => status.get(name) === 'missing');
90
+ let missing = REQUIRED_PEERS.filter((name) => status.get(name) === 'missing');
88
91
  const broken = REQUIRED_PEERS.filter((name) => status.get(name) === 'broken');
89
92
 
93
+ // Peers that do not resolve from here are very often still on the machine: pi keeps its own
94
+ // copies, and a global `npm install -g @earendil-works/pi-coding-agent` puts them in the
95
+ // global root. Node's ESM resolver never looks in either from this package's directory
96
+ // (a `pi install` managed tree, installed with --legacy-peer-deps, has no peers at all), so
97
+ // register a resolve hook that falls back to them. See host-roots.mjs. Only names that
98
+ // failed normal resolution are searched for, and only those the search found are rescued.
99
+ if (missing.length > 0 && broken.length === 0) {
100
+ try {
101
+ const { found } = findHostPackages(missing);
102
+ if (found.size > 0) {
103
+ register('./host-resolve-hook.mjs', import.meta.url, { data: { dirs: hostDirs(found) } });
104
+ missing = missing.filter((name) => !found.has(name));
105
+ }
106
+ } catch {
107
+ /* fall through to the message below */
108
+ }
109
+ }
110
+
90
111
  if (missing.length > 0 || broken.length > 0) {
91
112
  // The remedy names the packages that are ACTUALLY absent. It used to hardcode
92
113
  // `npm install -g @earendil-works/pi-coding-agent` with the comment "add just
@@ -94,6 +115,10 @@ if (missing.length > 0 || broken.length > 0) {
94
115
  // one: the instruction named a package the user already had, and following it
95
116
  // changed nothing. Reported by review 2026-10-01.
96
117
  const needsInstall = [...missing, ...broken];
118
+ // The tree this package sits in, when it is a node_modules install (the pi-managed one).
119
+ const installRoot = /^(.*)[\\/]node_modules[\\/](?:@[^\\/]+[\\/])?[^\\/]+[\\/]dist$/.exec(
120
+ dirname(fileURLToPath(import.meta.url)),
121
+ )?.[1];
97
122
  const lines = [
98
123
  '',
99
124
  'Error: pi-research cannot start — it is missing required runtime dependencies:',
@@ -102,15 +127,22 @@ if (missing.length > 0 || broken.length > 0) {
102
127
  '',
103
128
  'These are PEER dependencies. pi provides its own copies when it loads this',
104
129
  'package as an extension, and npm >= 7 installs them automatically for a',
105
- 'standalone (global or project) install. This install skipped them, which is',
106
- 'what --legacy-peer-deps, yarn classic, and a pnpm config with',
107
- 'auto-install-peers=false do.',
130
+ 'standalone (global or project) install. This install skipped them (what',
131
+ '--legacy-peer-deps, which `pi install` always passes, yarn classic and a pnpm',
132
+ 'config with auto-install-peers=false do), and no copy was found where pi or a',
133
+ 'global npm install would have put one.',
108
134
  '',
109
- 'Install the missing package(s), or reinstall this package, which resolves',
110
- 'them as peers:',
135
+ 'Any ONE of these fixes it:',
111
136
  '',
137
+ ...(installRoot
138
+ ? [
139
+ ` npm install --prefix "${installRoot}" --legacy-peer-deps ${needsInstall.join(' ')}`,
140
+ ' # into the tree this package is installed in (kept across `pi update`)',
141
+ ]
142
+ : []),
112
143
  ` npm install -g ${needsInstall.join(' ')}`,
113
- ' npm install -g @lincoln504/pi-research',
144
+ ' # a global install is found automatically',
145
+ ' export PI_RESEARCH_HOST_DIR=/path/to/node_modules # a directory that holds them',
114
146
  '',
115
147
  ];
116
148
  process.stderr.write(lines.join('\n'));
@@ -0,0 +1,37 @@
1
+ /**
2
+ * ESM resolve hook (registered by the bin shim via module.register) that falls back to the
3
+ * host's own copies of the peer dependencies — see host-roots.mjs for why the engine needs
4
+ * it. It only ever acts AFTER normal resolution failed, and only for the host packages, so
5
+ * an install that has them beside the engine is never affected.
6
+ */
7
+
8
+ import { join } from 'node:path';
9
+ import { pathToFileURL } from 'node:url';
10
+
11
+ const HOST = new Set(['@earendil-works/pi-ai', '@earendil-works/pi-coding-agent', '@earendil-works/pi-tui', 'typebox']);
12
+ let dirs = [];
13
+
14
+ function packageName(specifier) {
15
+ return specifier.startsWith('@') ? specifier.split('/').slice(0, 2).join('/') : specifier.split('/')[0];
16
+ }
17
+
18
+ export async function initialize(data) {
19
+ dirs = Array.isArray(data?.dirs) ? data.dirs : [];
20
+ }
21
+
22
+ export async function resolve(specifier, context, nextResolve) {
23
+ try {
24
+ return await nextResolve(specifier, context);
25
+ } catch (err) {
26
+ if (err?.code !== 'ERR_MODULE_NOT_FOUND' || !HOST.has(packageName(specifier))) throw err;
27
+ for (const nm of dirs) {
28
+ try {
29
+ // A parent that lives IN the node_modules directory makes Node's lookup start there.
30
+ return await nextResolve(specifier, { ...context, parentURL: pathToFileURL(join(nm, '__host__.mjs')).href });
31
+ } catch {
32
+ /* try the next location */
33
+ }
34
+ }
35
+ throw err;
36
+ }
37
+ }
@@ -0,0 +1,122 @@
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, realpathSync } from 'node:fs';
21
+ import { homedir } from 'node:os';
22
+ import { delimiter, dirname, 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
+ if (!dir) continue;
40
+ for (const ext of exts) {
41
+ const candidate = join(dir, name + ext);
42
+ if (existsSync(candidate)) out.push(candidate);
43
+ }
44
+ }
45
+ return out;
46
+ }
47
+
48
+ /**
49
+ * node_modules directories that may hold the host's packages, most specific first.
50
+ * `spawnNpm` additionally asks npm for its global root (a process spawn, so it is only
51
+ * done when the cheap candidates found nothing).
52
+ */
53
+ export function candidateNodeModulesDirs({ spawnNpm = false } = {}) {
54
+ const dirs = new Set();
55
+ const explicit = process.env['PI_RESEARCH_HOST_DIR'];
56
+ if (explicit) {
57
+ dirs.add(explicit);
58
+ dirs.add(join(explicit, 'node_modules'));
59
+ }
60
+ // The directory behind the `pi` command: <root>/node_modules/@earendil-works/pi-coding-agent/...
61
+ for (const bin of binsOnPath('pi')) {
62
+ try {
63
+ const m = /^(.*[\\/]node_modules)[\\/]/.exec(realpathSync(bin));
64
+ if (m) dirs.add(m[1]);
65
+ } catch {
66
+ /* dangling link: skip */
67
+ }
68
+ }
69
+ // The global root of the Node that is running us, without spawning npm.
70
+ dirs.add(join(dirname(process.execPath), '..', 'lib', 'node_modules'));
71
+ dirs.add(join(dirname(process.execPath), 'node_modules'));
72
+ dirs.add(join(homedir(), '.bun', 'install', 'global', 'node_modules'));
73
+ if (spawnNpm) {
74
+ try {
75
+ const r = spawnSync(process.platform === 'win32' ? 'npm.cmd' : 'npm', ['root', '-g'], {
76
+ encoding: 'utf8',
77
+ timeout: 8000,
78
+ shell: process.platform === 'win32',
79
+ });
80
+ if (r.status === 0 && r.stdout.trim()) dirs.add(r.stdout.trim());
81
+ } catch {
82
+ /* npm not on PATH */
83
+ }
84
+ }
85
+ return [...dirs];
86
+ }
87
+
88
+ /** The node_modules directory holding `name`, searching the candidates (and pi's own nested deps). */
89
+ function locate(name, nodeModulesDirs) {
90
+ for (const nm of nodeModulesDirs) {
91
+ if (existsSync(join(nm, name, 'package.json'))) return nm;
92
+ const nested = join(nm, ...PI_CODING_AGENT, 'node_modules');
93
+ if (existsSync(join(nested, name, 'package.json'))) return nested;
94
+ }
95
+ return null;
96
+ }
97
+
98
+ /**
99
+ * Locate every host package in `names` that the caller could not resolve itself.
100
+ * @returns {{ found: Map<string, string>, missing: string[] }} name -> node_modules dir
101
+ */
102
+ export function findHostPackages(names = HOST_PACKAGES) {
103
+ const found = new Map();
104
+ // Opt-out: insist on peers installed beside the engine (strict deployments, hermetic tests).
105
+ if (process.env['PI_RESEARCH_NO_HOST_FALLBACK'] === '1') return { found, missing: [...names] };
106
+ let pending = [...names];
107
+ for (const spawnNpm of [false, true]) {
108
+ if (pending.length === 0) break;
109
+ const dirs = candidateNodeModulesDirs({ spawnNpm });
110
+ pending = pending.filter((name) => {
111
+ const nm = locate(name, dirs);
112
+ if (nm) found.set(name, nm);
113
+ return !nm;
114
+ });
115
+ }
116
+ return { found, missing: pending };
117
+ }
118
+
119
+ /** Distinct node_modules directories from a findHostPackages() result. */
120
+ export function hostDirs(found) {
121
+ return [...new Set(found.values())];
122
+ }