@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.
package/README.md CHANGED
@@ -49,31 +49,25 @@ npm install -g @lincoln504/pi-research
49
49
  pi-research skill install
50
50
  ```
51
51
 
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
-
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:
55
-
56
- ```bash
57
- npm install -g @earendil-works/pi-coding-agent
58
- ```
59
-
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.
52
+ No extra setup is needed. The package ships ready-made bindings for every platform and declares no build step. The stealth browser (about 1 GB) is downloaded once, at install or on the first scrape depending on your npm version (see [Troubleshooting](docs/TROUBLESHOOTING.md#the-first-scrape-takes-minutes-or-install-downloads-over-a-gigabyte)).
61
53
 
62
54
  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
55
 
56
+ If something does not work, start with [Troubleshooting](docs/TROUBLESHOOTING.md).
57
+
64
58
  ### Update
65
59
 
66
- `pi update --extensions` moves every installed extension to its newest published version; `pi update npm:@lincoln504/pi-research` targets only this one. A versioned source (`npm:@lincoln504/pi-research@1.7.9`) is pinned and never updates — remove and reinstall it to move versions.
60
+ `pi update --extensions` moves every installed extension to its newest published version; `pi update npm:@lincoln504/pi-research` targets only this one. A versioned source (`npm:@lincoln504/pi-research@1.7.9`) is pinned and never updates; remove and reinstall it to move versions. Restart open pi sessions afterwards.
67
61
 
68
62
  ### Uninstall
69
63
 
70
- `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.
64
+ `pi remove npm:@lincoln504/pi-research` removes the extension; `npm uninstall -g @lincoln504/pi-research` removes the standalone engine. Neither removes skill links into other agents, the state directory (`~/.pi/research/state`) or the cache (`~/.cache/pi-research`). Run `pi-research skill uninstall` first, then `pi-research cleanup`. See [AGENT-SKILL.md](docs/AGENT-SKILL.md#installation-flow) for the full picture.
71
65
 
72
66
  ### How it works
73
67
 
74
68
  A research run works in rounds. A coordinator plans each round and starts the first search, researcher agents scrape and read pages in parallel, and a research lead then either starts another round or writes the final report from everything collected. The result is one cited Markdown report, optionally saved to the knowledge store.
75
69
 
76
- Three depth levels (normal, deep, ultra) set the team size and number of rounds. Just describe what you need in plain language, and the tool picks the right one:
70
+ Three depth levels (normal, deep, ultra) set the team size and number of rounds; an opt-in quick mode (depth 0) answers a simple question in one pass with no team. Just describe what you need in plain language, and the tool picks the right one:
77
71
 
78
72
  ![Two research runs in parallel in the pi TUI](https://raw.githubusercontent.com/Lincoln504/pi-research/main/docs/media/hero.png)
79
73
 
@@ -96,23 +90,14 @@ Three depth levels (normal, deep, ultra) set the team size and number of rounds.
96
90
  - Node.js >= 22.22.2
97
91
  - An LLM with a 100k+ context window (an API key or a local model)
98
92
  - Internet access on a residential IP, since search, scraping, and YouTube transcripts get bot-blocked from datacenter/VPS/cloud IPs
99
- - 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`.
93
+ - pi (`@earendil-works/pi-coding-agent`) 0.99.0 or newer, including the 1.x line. 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`. The standalone CLI and skill use the host packages as peer dependencies (see [Troubleshooting](docs/TROUBLESHOOTING.md#the-agent-skill-or-cli-says-cannot-start--missing-required-runtime-dependencies)).
100
94
  - 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).
102
95
  - Cloudflare Turnstile and similar systems block scraping on some sites. A run compensates with a wide pool of search results to scrape.
103
96
 
104
- ### Channels
105
-
106
- npm (`npm:@lincoln504/pi-research`) is the stable channel and is kept current with breaking pi changes. A git install is the development channel. It has the latest commits and receives breaking changes first.
107
-
108
97
  ### License
109
98
 
110
99
  MIT. Bundled third-party licenses are listed in [docs/THIRD-PARTY-NOTICES.md](docs/THIRD-PARTY-NOTICES.md).
111
100
 
112
- ### Package identity
113
-
114
- This project is always `@lincoln504/pi-research` on npm. The `pi-research` (unscoped) package is unrelated and deprecated.
115
-
116
- ### Versioning
101
+ ### Notes
117
102
 
118
- pi-research typically follows the latest pi version and is not actively backwards compatible.
103
+ The package is always `@lincoln504/pi-research` on npm; the unscoped `pi-research` package is unrelated and deprecated. npm is the stable channel; a git install has the latest commits and receives breaking changes first. pi-research typically follows the latest pi version and is not actively backwards compatible.
@@ -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.20", "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,107 @@
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 as readFileSync2, 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, readFileSync, realpathSync } from "node:fs";
12
+ import { homedir } from "node:os";
13
+ import { delimiter, dirname, isAbsolute, 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 || !isAbsolute(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 npmGlobalRoot() {
35
+ try {
36
+ let command = "npm";
37
+ let args = ["root", "-g"];
38
+ if (process.platform === "win32") {
39
+ const cli = join(dirname(process.execPath), "node_modules", "npm", "bin", "npm-cli.js");
40
+ if (!existsSync(cli)) return null;
41
+ command = process.execPath;
42
+ args = [cli, "root", "-g"];
43
+ }
44
+ const r = spawnSync(command, args, { encoding: "utf8", timeout: 8e3, cwd: homedir() });
45
+ return r.status === 0 && r.stdout.trim() ? r.stdout.trim() : null;
46
+ } catch {
47
+ return null;
48
+ }
49
+ }
50
+ function candidateNodeModulesDirs({ spawnNpm = false } = {}) {
51
+ const dirs = /* @__PURE__ */ new Set();
52
+ const explicit = process.env["PI_RESEARCH_HOST_DIR"];
53
+ if (explicit) {
54
+ dirs.add(explicit);
55
+ dirs.add(join(explicit, "node_modules"));
56
+ }
57
+ for (const bin of binsOnPath("pi")) {
58
+ try {
59
+ const m = /^(.*[\\/]node_modules)[\\/]/.exec(realpathSync(bin));
60
+ if (m) dirs.add(m[1]);
61
+ } catch {
62
+ }
63
+ }
64
+ try {
65
+ const agentDir = process.env["PI_CODING_AGENT_DIR"] || join(homedir(), ".pi", "agent");
66
+ const current = readFileSync(join(agentDir, "install", "current-version"), "utf8").trim();
67
+ if (/^[A-Za-z0-9._+-]+$/.test(current) && current !== "." && current !== "..") {
68
+ dirs.add(join(agentDir, "install", "releases", current, "node_modules"));
69
+ }
70
+ } catch {
71
+ }
72
+ dirs.add(join(dirname(process.execPath), "..", "lib", "node_modules"));
73
+ dirs.add(join(dirname(process.execPath), "node_modules"));
74
+ dirs.add(join(homedir(), ".bun", "install", "global", "node_modules"));
75
+ if (spawnNpm) {
76
+ const root = npmGlobalRoot();
77
+ if (root) dirs.add(root);
78
+ }
79
+ return [...dirs];
80
+ }
81
+ function locate(name, nodeModulesDirs) {
82
+ for (const nm of nodeModulesDirs) {
83
+ if (existsSync(join(nm, name, "package.json"))) return nm;
84
+ const nested = join(nm, ...PI_CODING_AGENT, "node_modules");
85
+ if (existsSync(join(nested, name, "package.json"))) return nested;
86
+ }
87
+ return null;
88
+ }
89
+ function findHostPackages(names = HOST_PACKAGES) {
90
+ const found = /* @__PURE__ */ new Map();
91
+ if (process.env["PI_RESEARCH_NO_HOST_FALLBACK"] === "1") return { found, missing: [...names] };
92
+ let pending = [...names];
93
+ for (const spawnNpm of [false, true]) {
94
+ if (pending.length === 0) break;
95
+ const dirs = candidateNodeModulesDirs({ spawnNpm });
96
+ pending = pending.filter((name) => {
97
+ const nm = locate(name, dirs);
98
+ if (nm) found.set(name, nm);
99
+ return !nm;
100
+ });
101
+ }
102
+ return { found, missing: pending };
103
+ }
104
+
105
+ // agent-skill/pi-research/scripts/run.ts
9
106
  import { fileURLToPath } from "node:url";
10
107
  var PKG = "@lincoln504/pi-research";
11
108
  var REQUIRED_DEP = "@earendil-works/pi-coding-agent";
@@ -30,13 +127,13 @@ function resolvePackageDir(specifier, roots) {
30
127
  for (const root of candidates) {
31
128
  try {
32
129
  const pkgJson = require2.resolve(`${specifier}/package.json`, { paths: [root] });
33
- return dirname(pkgJson);
130
+ return dirname2(pkgJson);
34
131
  } catch {
35
132
  }
36
133
  }
37
134
  try {
38
135
  const pkgJson = require2.resolve(`${specifier}/package.json`);
39
- return dirname(pkgJson);
136
+ return dirname2(pkgJson);
40
137
  } catch {
41
138
  return null;
42
139
  }
@@ -47,9 +144,9 @@ function findOnPath(bin) {
47
144
  for (const dir of pathVar.split(process.platform === "win32" ? ";" : ":")) {
48
145
  if (!dir) continue;
49
146
  for (const ext of exts) {
50
- const candidate = join(dir, bin + ext);
147
+ const candidate = join2(dir, bin + ext);
51
148
  try {
52
- if (existsSync(candidate)) return candidate;
149
+ if (existsSync2(candidate)) return candidate;
53
150
  } catch {
54
151
  }
55
152
  }
@@ -57,8 +154,8 @@ function findOnPath(bin) {
57
154
  return null;
58
155
  }
59
156
  function resolveEngine(skillDir) {
60
- const home = homedir();
61
- if (process.env["PI_RESEARCH_BIN"] && existsSync(process.env["PI_RESEARCH_BIN"])) {
157
+ const home = homedir2();
158
+ if (process.env["PI_RESEARCH_BIN"] && existsSync2(process.env["PI_RESEARCH_BIN"])) {
62
159
  return { argv: [process.env["PI_RESEARCH_BIN"]], label: process.env["PI_RESEARCH_BIN"] };
63
160
  }
64
161
  const explicitPath = process.env["PI_RESEARCH_PATH"];
@@ -75,7 +172,7 @@ function resolveEngine(skillDir) {
75
172
  if (anchor && !depResolvableFrom(anchor)) depMissing(anchor);
76
173
  return { argv: [onPath], label: onPath };
77
174
  }
78
- const pkgDir = resolvePackageDir(PKG, [skillDir, process.cwd(), home, join(home, ".pi")]);
175
+ const pkgDir = resolvePackageDir(PKG, [skillDir, process.cwd(), home, join2(home, ".pi")]);
79
176
  if (pkgDir) {
80
177
  const fromPkg = engineFromPackageDir(pkgDir);
81
178
  if (fromPkg) {
@@ -83,8 +180,8 @@ function resolveEngine(skillDir) {
83
180
  return fromPkg;
84
181
  }
85
182
  }
86
- const piBin = join(home, ".pi", "bin", "pi-research");
87
- if (existsSync(piBin)) {
183
+ const piBin = join2(home, ".pi", "bin", "pi-research");
184
+ if (existsSync2(piBin)) {
88
185
  const anchor = packageAnchorFor(piBin);
89
186
  if (anchor && !depResolvableFrom(anchor)) depMissing(anchor);
90
187
  return { argv: [piBin], label: piBin };
@@ -94,7 +191,7 @@ function resolveEngine(skillDir) {
94
191
  function packageAnchorFor(binPath) {
95
192
  let real;
96
193
  try {
97
- real = realpathSync(binPath);
194
+ real = realpathSync2(binPath);
98
195
  } catch {
99
196
  return null;
100
197
  }
@@ -103,19 +200,19 @@ function packageAnchorFor(binPath) {
103
200
  }
104
201
  function engineFromPackageDir(pkgDir) {
105
202
  try {
106
- const pkg = JSON.parse(readFileSync(join(pkgDir, "package.json"), "utf-8"));
203
+ const pkg = JSON.parse(readFileSync2(join2(pkgDir, "package.json"), "utf-8"));
107
204
  const binField = typeof pkg?.bin === "string" ? pkg.bin : pkg?.bin?.["pi-research"];
108
205
  if (binField) {
109
- const binPath = join(pkgDir, binField);
110
- if (existsSync(binPath)) {
206
+ const binPath = join2(pkgDir, binField);
207
+ if (existsSync2(binPath)) {
111
208
  const isJsModule = /\.(m|c)?js$/i.test(binField);
112
209
  return isJsModule ? { argv: [process.execPath, binPath], label: binPath } : { argv: [binPath], label: binPath };
113
210
  }
114
211
  }
115
212
  } catch {
116
213
  }
117
- const cliPath = join(pkgDir, "dist", "cli.mjs");
118
- if (existsSync(cliPath)) {
214
+ const cliPath = join2(pkgDir, "dist", "cli.mjs");
215
+ if (existsSync2(cliPath)) {
119
216
  return { argv: [process.execPath, cliPath], label: cliPath };
120
217
  }
121
218
  return null;
@@ -124,11 +221,16 @@ function depResolvableFrom(anchorDir) {
124
221
  const depSegs = REQUIRED_DEP.split("/");
125
222
  let dir = resolve(anchorDir);
126
223
  for (; ; ) {
127
- if (existsSync(join(dir, "node_modules", ...depSegs, "package.json"))) return true;
128
- const parent = dirname(dir);
129
- if (parent === dir) return false;
224
+ if (existsSync2(join2(dir, "node_modules", ...depSegs, "package.json"))) return true;
225
+ const parent = dirname2(dir);
226
+ if (parent === dir) break;
130
227
  dir = parent;
131
228
  }
229
+ return findHostPackages([REQUIRED_DEP]).missing.length === 0;
230
+ }
231
+ function enginePrefix(pkgDir) {
232
+ const m = /^(.*)[\\/]node_modules[\\/](?:@[^\\/]+[\\/])?[^\\/]+$/.exec(pkgDir);
233
+ return m?.[1] ?? pkgDir;
132
234
  }
133
235
  function depMissing(pkgDir) {
134
236
  const lines = [
@@ -137,15 +239,18 @@ function depMissing(pkgDir) {
137
239
  `'${REQUIRED_DEP}' is not installed alongside it.`,
138
240
  "",
139
241
  "The standalone engine imports this package at startup, so it cannot run",
140
- "without it. These three options all work:",
242
+ "without it, and none was found where pi or a global npm install puts one.",
243
+ "Any ONE of these fixes it:",
141
244
  "",
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)",
245
+ ` npm install --prefix "${enginePrefix(pkgDir)}" --legacy-peer-deps @earendil-works/pi-ai @earendil-works/pi-coding-agent @earendil-works/pi-tui typebox`,
246
+ " # into the tree the engine is installed in (kept across `pi update`)",
247
+ " npm install -g @earendil-works/pi-coding-agent # a global install is found automatically",
248
+ " npm install -g @lincoln504/pi-research # global \u2014 brings the peers in with the engine",
249
+ " export PI_RESEARCH_HOST_DIR=/path/to/node_modules # a directory that holds them",
145
250
  " # or point the launcher at a working engine: export PI_RESEARCH_PATH=/path/to/pi-research",
146
251
  "",
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.",
252
+ "This happens when the install skipped peer dependencies (--legacy-peer-deps, which",
253
+ "`pi install` always passes; yarn classic): pi itself provides them only in-process.",
149
254
  "",
150
255
  `(engine located at: ${pkgDir})`,
151
256
  ""
@@ -154,7 +259,7 @@ function depMissing(pkgDir) {
154
259
  process.exit(EXIT.CONFIG);
155
260
  }
156
261
  function notInstalled() {
157
- const home = homedir();
262
+ const home = homedir2();
158
263
  const lines = [
159
264
  "",
160
265
  "Error: pi-research engine not found.",
@@ -176,8 +281,8 @@ function notInstalled() {
176
281
  "After installing, configure the model (PI_RESEARCH_MODEL is required) + API key.",
177
282
  "Locations:",
178
283
  ` \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)`,
284
+ ` \u2022 global config file: ${join2(home, ".pi", "research", "config.env")}`,
285
+ ` \u2022 pi config (keys): ${join2(home, ".pi", "agent", "auth.json")} (supplies the API key only)`,
181
286
  "",
182
287
  "Run `status` once installed to verify detection.",
183
288
  ""
@@ -189,14 +294,14 @@ function hasCmdMetachar(s) {
189
294
  return /[&|<>^"%()!\r\n]/.test(s);
190
295
  }
191
296
  function resolveWinShimToNode(shimPath) {
192
- const fromLayout = engineFromPackageDir(join(dirname(shimPath), "node_modules", ...PKG.split("/")));
297
+ const fromLayout = engineFromPackageDir(join2(dirname2(shimPath), "node_modules", ...PKG.split("/")));
193
298
  if (fromLayout && fromLayout.argv[0] === process.execPath) return fromLayout;
194
299
  try {
195
- const content = readFileSync(shimPath, "utf-8");
300
+ const content = readFileSync2(shimPath, "utf-8");
196
301
  const m = content.match(/node_modules[\\/][^"\r\n]*?\.(?:mjs|cjs|js)\b/i);
197
302
  if (m) {
198
- const abs = resolve(dirname(shimPath), m[0]);
199
- if (existsSync(abs)) return { argv: [process.execPath, abs], label: abs };
303
+ const abs = resolve(dirname2(shimPath), m[0]);
304
+ if (existsSync2(abs)) return { argv: [process.execPath, abs], label: abs };
200
305
  }
201
306
  } catch {
202
307
  }
@@ -283,7 +388,7 @@ function printUsage() {
283
388
  ].join("\n")
284
389
  );
285
390
  }
286
- var here = dirname(fileURLToPath(import.meta.url));
391
+ var here = dirname2(fileURLToPath(import.meta.url));
287
392
  var engine = resolveEngine(here);
288
393
  if (!engine) notInstalled();
289
394
  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,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
+ }