@lincoln504/pi-research 1.7.15 → 1.7.16

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
@@ -98,6 +98,7 @@ Three depth levels (normal, deep, ultra) set the team size and number of rounds.
98
98
  - Internet access on a residential IP, since search, scraping, and YouTube transcripts get bot-blocked from datacenter/VPS/cloud IPs
99
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`.
100
100
  - 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).
101
102
  - Cloudflare Turnstile and similar systems block scraping on some sites. A run compensates with a wide pool of search results to scrape.
102
103
 
103
104
  ### 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.15", "package": "@lincoln504/pi-research", "engine": "pi-research-sdk", "openclaw": { "requires": { "bins": ["node"] } } }
5
+ metadata: { "author": "Lincoln Deen", "version": "1.7.16", "package": "@lincoln504/pi-research", "engine": "pi-research-sdk", "openclaw": { "requires": { "bins": ["node"] } } }
6
6
  allowed-tools: Bash(node:*)
7
7
  ---
8
8
 
package/dist/cli.mjs CHANGED
@@ -1684,13 +1684,13 @@ function loadPrompt(name) {
1684
1684
  logger.error(`[prompts] Failed to load prompt: ${name} (searched: ${PROMPT_CANDIDATES.join(", ")})`);
1685
1685
  throw new Error(`[prompts] Failed to load prompt "${name}" (searched: ${PROMPT_CANDIDATES.join(", ")})`);
1686
1686
  }
1687
- var __filename, CORE_LLM_DIR, PROMPT_CANDIDATES;
1687
+ var __filename2, CORE_LLM_DIR, PROMPT_CANDIDATES;
1688
1688
  var init_prompts = __esm({
1689
1689
  "src/core/llm/prompts.ts"() {
1690
1690
  "use strict";
1691
1691
  init_logger();
1692
- __filename = fileURLToPath(import.meta.url);
1693
- CORE_LLM_DIR = dirname2(__filename);
1692
+ __filename2 = fileURLToPath(import.meta.url);
1693
+ CORE_LLM_DIR = dirname2(__filename2);
1694
1694
  PROMPT_CANDIDATES = [
1695
1695
  join3(CORE_LLM_DIR, "../../prompts"),
1696
1696
  // source tree
@@ -7824,6 +7824,13 @@ var init_store = __esm({
7824
7824
  // 'bm25' owns activeBm25TableName).
7825
7825
  otherModeTableName = null;
7826
7826
  manifestPath;
7827
+ // The state of the manifest FILE at the last loadManifest(): 'absent' (no
7828
+ // file — no migration state is known), 'loaded' (parsed — the live table
7829
+ // name is positively identified), or 'corrupt' (the file EXISTS but did not
7830
+ // parse — the live table name is UNKNOWN, so consumers of it such as
7831
+ // pruneOrphanedMigrationDirs must treat the store's data layout as unknown
7832
+ // rather than as "no migration in flight").
7833
+ manifestLoadState = "absent";
7827
7834
  isClosing = false;
7828
7835
  activeWrites = /* @__PURE__ */ new Set();
7829
7836
  // Last recorded model/schema migration (persisted in the store manifest).
@@ -7891,6 +7898,7 @@ var init_store = __esm({
7891
7898
  async loadManifest() {
7892
7899
  try {
7893
7900
  if (fs14.existsSync(this.manifestPath)) {
7901
+ this.manifestLoadState = "corrupt";
7894
7902
  const content = await fsPromises.readFile(this.manifestPath, "utf-8");
7895
7903
  const manifest = JSON.parse(content);
7896
7904
  const savedVectorTable = typeof manifest.activeTableName === "string" ? manifest.activeTableName : null;
@@ -7907,6 +7915,9 @@ var init_store = __esm({
7907
7915
  if (manifest.prevMigration && typeof manifest.prevMigration.model === "string") {
7908
7916
  this.prevMigration = { model: manifest.prevMigration.model, ts: Number(manifest.prevMigration.ts) || 0 };
7909
7917
  }
7918
+ this.manifestLoadState = "loaded";
7919
+ } else {
7920
+ this.manifestLoadState = "absent";
7910
7921
  }
7911
7922
  } catch (err) {
7912
7923
  logger.warn("[store] Failed to load manifest, using default table name:", err);
@@ -8747,6 +8758,10 @@ var init_store = __esm({
8747
8758
  }
8748
8759
  async pruneOrphanedMigrationDirs() {
8749
8760
  if (!this.table) return;
8761
+ if (this.manifestLoadState === "corrupt") {
8762
+ logger.warn("[store] Skipping migration-dir pruning: the manifest exists but is unparseable, so the live table cannot be positively identified.");
8763
+ return;
8764
+ }
8750
8765
  try {
8751
8766
  const activeDir = `${this.tableName}.lance`;
8752
8767
  const entries = await fsPromises.readdir(this.options.dbDir, { withFileTypes: true });
@@ -8870,7 +8885,10 @@ var init_store = __esm({
8870
8885
  const duration = Date.now() - startTime;
8871
8886
  metrics.observe("knowledge_store_clear_duration_ms", duration);
8872
8887
  metrics.increment("knowledge_store_clear_total", 1, { status: "success" });
8873
- metrics.setGauge("knowledge_store_total_documents", 0);
8888
+ try {
8889
+ metrics.setGauge("knowledge_store_total_documents", await table.countRows(this.getScopeFilter()));
8890
+ } catch {
8891
+ }
8874
8892
  logger.info(`[store] Knowledge store cleared for scope: ${scopeFilter}`);
8875
8893
  return;
8876
8894
  } catch (err) {
@@ -13041,7 +13059,7 @@ function loadPin(packageRoot) {
13041
13059
  function findPackageRoot(fromUrl) {
13042
13060
  try {
13043
13061
  const require2 = createRequire4(fromUrl);
13044
- return path10.dirname(require2.resolve("@camoufox/camoufox/package.json"));
13062
+ return path10.dirname(require2.resolve("camoufox/package.json"));
13045
13063
  } catch {
13046
13064
  return null;
13047
13065
  }
@@ -13297,7 +13315,6 @@ function defaultNativeDepLoad() {
13297
13315
  function isBrowserAvailable() {
13298
13316
  if (isFullMockMode()) return false;
13299
13317
  try {
13300
- import.meta.resolve("@camoufox/camoufox");
13301
13318
  const root = findPackageRoot(import.meta.url);
13302
13319
  return isUsable(getCamoufoxBinaryPath(), root ? loadPin(root) : null);
13303
13320
  } catch {
@@ -16648,7 +16665,7 @@ function isBrowserBinaryPresent() {
16648
16665
  function resolveCamoufoxCli() {
16649
16666
  try {
16650
16667
  const require2 = createRequire6(import.meta.url);
16651
- const pkgJson = require2.resolve("@camoufox/camoufox/package.json");
16668
+ const pkgJson = require2.resolve("camoufox/package.json");
16652
16669
  const pkg = JSON.parse(readFileSync5(pkgJson, "utf8"));
16653
16670
  const rel = typeof pkg.bin === "string" ? pkg.bin : pkg.bin?.["camoufox"];
16654
16671
  if (rel) {
@@ -16664,7 +16681,7 @@ function runFetch() {
16664
16681
  return new Promise((resolve9, reject) => {
16665
16682
  const cli = resolveCamoufoxCli();
16666
16683
  if (!cli) {
16667
- reject(new Error("@camoufox/camoufox is not installed (cannot find its CLI); run npm install"));
16684
+ reject(new Error("camoufox is not installed (cannot find its CLI); run npm install"));
16668
16685
  return;
16669
16686
  }
16670
16687
  const install = resolveInstall(process.env, platform3(), homedir5());
@@ -17000,8 +17017,8 @@ function logToDebugFile(level, ...args) {
17000
17017
  init_service_registry();
17001
17018
  init_safe_unref();
17002
17019
  init_service_names();
17003
- var __filename2 = fileURLToPath3(import.meta.url);
17004
- var __dirname = dirname10(__filename2);
17020
+ var __filename3 = fileURLToPath3(import.meta.url);
17021
+ var __dirname = dirname10(__filename3);
17005
17022
  function buildWorkerPoolOptions(config) {
17006
17023
  return {
17007
17024
  workerChoiceStrategy: WorkerChoiceStrategies.LEAST_USED,
@@ -18987,13 +19004,20 @@ import { Type as Type5 } from "typebox";
18987
19004
  import { Value as Value6 } from "typebox/value";
18988
19005
 
18989
19006
  // src/web-research/utils.ts
19007
+ import { createRequire as createRequire7 } from "node:module";
19008
+ import { pathToFileURL } from "node:url";
18990
19009
  function checkModule(name) {
18991
- try {
18992
- import.meta.resolve(name);
18993
- return true;
18994
- } catch {
18995
- return false;
19010
+ const anchors = [];
19011
+ if (typeof import.meta.url === "string") anchors.push(import.meta.url);
19012
+ if (typeof __filename !== "undefined") anchors.push(pathToFileURL(__filename).href);
19013
+ for (const anchor of anchors) {
19014
+ try {
19015
+ createRequire7(anchor).resolve(`${name}/package.json`);
19016
+ return true;
19017
+ } catch {
19018
+ }
18996
19019
  }
19020
+ return false;
18997
19021
  }
18998
19022
 
18999
19023
  // src/web-research/web-scraper.ts
@@ -19678,7 +19702,7 @@ var FETCH_RETRY_DELAY_MS = 250;
19678
19702
  var playwrightAvailable = false;
19679
19703
  var markdownConverterPromise = null;
19680
19704
  function initScraperDependencies() {
19681
- playwrightAvailable = checkModule("playwright-core") && checkModule("@camoufox/camoufox");
19705
+ playwrightAvailable = checkModule("playwright-core") && checkModule("camoufox");
19682
19706
  }
19683
19707
  initScraperDependencies();
19684
19708
  async function getMarkdownConverter() {
@@ -12,7 +12,7 @@ The `research` tool (from pi-research extension) is your tool for web/internet r
12
12
 
13
13
  **KNOWLEDGE SEARCH (a knowledge store is enabled)**
14
14
 
15
- Check the knowledge store first. For a web-research question, call `research_knowledge_search` before the live `research` tool — it is a local lookup (instant, no network) and covers both the Project and User knowledge stores, so the live tool is only needed when the store doesn't already answer the question.
15
+ Check the knowledge store first. For a web-research question, call `research_knowledge_search` before the live `research` tool — it is a local lookup (instant, no network) and covers both the Project and User knowledge stores, so the live tool is only needed when the store doesn't already answer the question. Where a question turns on the current state of things, stored material can be stale enough to mislead — treat it as a lead, not a source.
16
16
 
17
17
  - Workflow:
18
18
  1. Call `research_knowledge_search` with the question.
@@ -3048,9 +3048,9 @@ async function initBrowser() {
3048
3048
  logToDebugFile3("INFO", `[Worker-${workerId3}] Initializing browser instance...`);
3049
3049
  let CamoufoxModule;
3050
3050
  try {
3051
- CamoufoxModule = await import("@camoufox/camoufox");
3051
+ CamoufoxModule = await import("camoufox");
3052
3052
  } catch (e) {
3053
- throw new Error(`[Worker] @camoufox/camoufox not found in node_modules. Please run 'npm install'. Original error: ${e instanceof Error ? e.message : String(e)}`, { cause: e });
3053
+ throw new Error(`[Worker] camoufox not found in node_modules. Please run 'npm install'. Original error: ${e instanceof Error ? e.message : String(e)}`, { cause: e });
3054
3054
  }
3055
3055
  const { Camoufox } = CamoufoxModule;
3056
3056
  const launchTimeoutMs = BROWSER_LAUNCH_TIMEOUT_MS;
@@ -310,9 +310,9 @@ in one cannot affect the orchestrator or other sessions.
310
310
 
311
311
  Pinned browser stack — the three browser packages are coupled and upgraded together,
312
312
  because each floating range broke fresh consumer installs that our lockfile masked.
313
- `@camoufox/camoufox` is pinned to its `0.5` line (`^0.5.7`), `playwright-core` is exact at
314
- `1.62.1` and `impit` exact at `0.14.5`. The playwright pin follows the launcher's declared
315
- peer: `@camoufox/camoufox` declares
313
+ `camoufox` is exact at `0.5.8`, `playwright-core` is exact at
314
+ `1.62.1` and `impit` exact at `0.14.6`. The playwright pin follows the launcher's declared
315
+ peer: `camoufox` declares
316
316
  `peerDependencies: { "playwright-core": "<1.63" }` (`1.60.0` was the old `camoufox-js`
317
317
  bound, which capped `<1.61.0`). `impit` stays exact because npm `overrides` do not
318
318
  propagate to consumers, so an exact pin is the only way to force a version downstream;
@@ -332,15 +332,20 @@ navigator.product in config`, while machines holding an older cached browser kep
332
332
  which is why CI (a fresh cache) went red while local runs stayed green. There was no pin to
333
333
  turn — the library had no version argument and no environment variable for the browser.
334
334
 
335
- `@camoufox/camoufox` fixes that structurally: every published copy is stamped with the one
336
- browser build compiled from the same sources (`browser-pin.json`; 0.5.7 pins
337
- `v156.0.1-beta.34`), and it fetches and launches exactly that build by default. The two
335
+ The rename (2026-10-22). The scoped `@camoufox/camoufox` is deprecated on npm ("Moved to camoufox: npm i
336
+ camoufox"), so every consumer install printed `npm warn deprecated`. The dependency is now `camoufox` `0.5.8`
337
+ (exact), which has the same dependency shape and the same `playwright-core <1.63` peer, and pins browser
338
+ `v156.0.1-beta.36` in place of `v156.0.1-beta.34`.
339
+
340
+ `camoufox` fixes that structurally: every published copy is stamped with the one
341
+ browser build compiled from the same sources (`browser-pin.json`; 0.5.8 pins
342
+ `v156.0.1-beta.36`, 0.5.7 pinned `v156.0.1-beta.34`), and it fetches and launches exactly that build by default. The two
338
343
  halves of the stack are released together, so a schema change cannot reach a launcher that
339
344
  does not understand it. The browser BINARY is PINNED now, where the old stack left it
340
- floating, and the practical consequence runs the other way: a stale `@camoufox/camoufox`
345
+ floating, and the practical consequence runs the other way: a stale `camoufox`
341
346
  means a stale Firefox, and the browser only moves when this dependency does.
342
347
 
343
- The extra install layer this adds: `@camoufox/camoufox` installs under
348
+ The extra install layer this adds: `camoufox` installs under
344
349
  `<INSTALL_DIR>/browsers/<repo>/<version>/` (multi-version, with `config.json`,
345
350
  `repo_cache.json` and a `.0.5_FLAG` above it) where `camoufox-js` laid the browser flat
346
351
  with a root `version.json`, and it derives `INSTALL_DIR` only from the platform cache
@@ -351,7 +356,7 @@ directory — it reads neither `CAMOUFOX_INSTALL_DIR` nor `PLAYWRIGHT_BROWSERS_P
351
356
  location and for the override the launcher does read (`XDG_CACHE_HOME` on Linux,
352
357
  `LOCALAPPDATA` on Windows); it also recognises a legacy flat install, which matters
353
358
  because `camoufox fetch` runs `rm -rf INSTALL_DIR` over a directory it does not recognise.
354
- `@camoufox/camoufox` has no `better-sqlite3` dependency (the native surface on the launch
359
+ `camoufox` has no `better-sqlite3` dependency (the native surface on the launch
355
360
  path is now only `impit`), so the old npm-install-script blocker on this stack is gone.
356
361
  Re-verify a real launch when bumping it — the unit and integration suites mock the browser
357
362
  and cannot catch a Juggler mismatch.
package/docs/CHANGELOG.md CHANGED
@@ -5,6 +5,37 @@ All notable changes to this project will be documented in this file.
5
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
6
6
  and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
7
 
8
+ ## [1.7.16] - 2026-10-23
9
+
10
+ ### Changed
11
+
12
+ - **The repository's own dependency tree no longer carries LanceDB's bundled `@huggingface/transformers` 3.0.2.** `package.json` `overrides` gains `"@lancedb/lancedb": { "@huggingface/transformers": "$@huggingface/transformers" }`, which collapses the copy `@lancedb/lancedb` 0.40.0 declares as an exact-pinned optional dependency onto the root's 4.3.1. This removes the second `onnxruntime-node` (1.19.2, with its install script), `openai`, `node-fetch`, `jinja` and the rest of LanceDB's nested tree (11 lock entries, 120 lines, deletions only) and makes the dev/CI/test tree the same shape the consumer recipe below produces. Nothing at runtime changes: LanceDB is used for storage only, and embeddings already ran through the root copy. `test/unit/package.test.ts` pins both the override and the absence of any nested `@lancedb/lancedb/node_modules/@huggingface/*` lock entry (it fails on the 1.7.15 tree, passes now). Verified: `npm ci --dry-run` clean, `npm audit` 0, `npm ls` shows one `transformers@4.3.1` and one `sharp@0.35.5`.
13
+
14
+ - **The browser launcher dependency is renamed from the deprecated `@camoufox/camoufox` 0.5.7 to `camoufox` 0.5.8, pinned exactly.** npm marks the scoped name deprecated ("Moved to camoufox: npm i camoufox"), so every consumer install printed `npm warn deprecated @camoufox/camoufox`. The successor has the same dependency shape (`adm-zip ^0.6.1`, `impit ^0.14.1`, `ua-parser-js ^2.0.2`, MIT) and the same `playwright-core <1.63` peer, so `playwright-core` stays at 1.62.1. Its `browser-pin.json` moves the pinned browser from `v156.0.1-beta.34` to `v156.0.1-beta.36`, and the package version is now exact (`0.5.8`, was `^0.5.7`) because the launcher and the browser build it fetches are one release: a floating range would move the browser with it. Every import, the postinstall/cleanup scripts (`scripts/setup.cjs`, `scripts/cleanup.cjs`, `scripts/camoufox-layout.cjs`), `src/infrastructure/browser/*`, `src/cli.ts`, `src/web-research/web-scraper.ts`, the CI workflow (`npx camoufox fetch`, `import { Camoufox } from 'camoufox'`) and the unit/integration test fixtures use the new name. Measured on 2026-10-22: the fresh browser download through `scripts/setup.cjs` with an empty `XDG_CACHE_HOME` and no `GITHUB_TOKEN` (the unauthenticated path consumers use) installed `v156.0.1-beta.36` (2.7 GB cache including GeoIP and the uBlock addon, 22 min on this link) and reported `camoufox ready`. A headless launch from the repo and from a packed-tarball consumer tree navigated to https://example.com, read the DOM title and body text and wrote a 1920x1087 PNG screenshot, and closed cleanly. A plain `npm install` of the packed tarball prints no `@camoufox/camoufox` deprecation (the one remaining `node-domexception` deprecation comes from the host `@earendil-works/pi-ai` peer tree via `@google/genai`), and `pi-research --version` prints 1.7.16. No Turnstile or Cloudflare behavior was changed or tested (the wall from the closed "Open specific / high value blocked sites to a browser tab" issue is unchanged).
15
+ - **`KnowledgeStore.clear(filter)` no longer reports an empty store after a partial clear.** `clearInner` set the `knowledge_store_total_documents` gauge to a hard-coded `0` after every successful delete, so a caller-supplied `filter` that removed only some rows left the gauge claiming zero while rows remained (only the next `count()` corrected it). It now recounts the store's own scope after the delete and reports that, best-effort (a failed recount keeps the previous gauge value and does not fail the clear). New test in `test/unit/knowledge/store.test.ts` fails against the old code (`expected 0 to be 1`) and passes now.
16
+
17
+ - **`pruneOrphanedMigrationDirs` no longer reaps directories when the manifest exists but fails to parse.** `loadManifest` tracked no state: a parse failure fell back to the default table name, and the prune pass then classified the real live `knowledge_migration_<ts>` directory (the persisted re-embed rename-failure state, with the manifest pointing at it) as an orphan and deleted it. `loadManifest` now records `absent` / `loaded` / `corrupt`, and the prune pass skips entirely in the `corrupt` case (the live table name is unknown, so no directory can be positively identified as garbage). A missing manifest still prunes as before. The write is atomic (tmp then rename), so corruption is unlikely in practice. The next successful open rewrites a valid manifest and pruning resumes.
18
+
19
+ - **`checkModule` and `isBrowserAvailable` no longer call `import.meta.resolve`.** pi loads the extension through a transform pipeline (jiti / esbuild to CJS) where `import.meta` compiles to an empty object: `import.meta.url` may be shimmed but `import.meta.resolve` is undefined, so the call threw and the surrounding `catch` reported an installed module as missing. Measured with the repo's esbuild: the CJS output is `var import_meta = {}`, and `import_meta.resolve("camoufox")` is `undefined(...)`, a TypeError. The failure had two effects in a real session: every research run aborted with "Browser engine not installed" before any run, and `playwrightAvailable` in `web-scraper.ts` was silently false, disabling the browser scrape path. `checkModule` now resolves via `createRequire` from the first available file anchor (`import.meta.url` in ESM/jiti, `__filename` in CJS output); `isBrowserAvailable` drops the resolve call and relies on `findPackageRoot` (already a `createRequire` anchor) plus the layout check. New `test/unit/infrastructure/loader-context.test.ts` reproduces the pi loader context by bundling the real source modules to CJS with the jiti shim (url present, resolve absent) and asserting both checks work: 2 failed before the fix, 2 pass now.
20
+
21
+ ### CI
22
+
23
+ - **Code scanning now covers the workflow files on every push.** A `Analyze (CodeQL actions)` job scans `.github` with `languages: actions` and the `security-and-quality` query suite, pinned to the same `codeql-action` SHA as the existing JavaScript job. The old dynamic `language:actions` configuration (last scanned June 2) is superseded: the CI job updates the same configuration on every push, so there is no second configuration and no double scan (the JavaScript job's Summary step counts open alerts across all configurations once). The open `js/unused-local-variable` alert (`test/unit/knowledge/store-fault-injection.test.ts`, unused `fsPromises` import) is fixed in this release.
24
+
25
+ ### Documentation
26
+
27
+ - **The research tool prompt's knowledge-search paragraph now carries a timeliness caveat.** Integrated into the existing point, not a new one: "Where a question turns on the current state of things, stored material can be stale enough to mislead — treat it as a lead, not a source." Stored material stays a fast first lookup; live research remains the source of record for current-state questions.
28
+
29
+ - **Docs follow the launcher rename.** `docs/ARCHITECTURE.md` (pin, rename note, `browser-pin.json` 0.5.8 -> beta.36), `docs/CONFIGURATION.md`, `docs/AUDIT-GATE.md`, `docs/THIRD-PARTY-NOTICES.md`, `.env.example`, and the ES/JA/ZH documentation translations now name `camoufox` 0.5.8 and `v156.0.1-beta.36` where they describe the current stack. Mentions of the 2026-10-05 move to `@camoufox/camoufox` and of `0.5.7`/`beta.34` stay as history. The stale `impit` pin in the architecture text (`0.14.5`) is corrected to the actual `0.14.6`.
30
+ - **Consumer-side fix for the `sharp` 0.33.5 `npm audit` finding is now one override that removes the chain, not just patches `sharp`** (GitHub issue "Vulnerable transitive sharp dependency through LanceDB's optional Transformers dependency"). `overrides: {"@lancedb/lancedb": {"@huggingface/transformers": "^4.3.1"}}` in the consumer's `package.json` (for `pi install`: `~/.pi/agent/npm/package.json`, which pi's `ensureNpmProject` creates only when absent and so never overwrites). Measured 2026-10-22 on the packed 1.7.15 tarball in three install shapes (`--legacy-peer-deps`, plain `npm install`, and pi's `--prefix` layout): nested `transformers@3.0.2` and `sharp@0.33.5` gone, one `transformers@4.3.1` and one `sharp@0.35.5`, `npm audit --omit=dev` 0 (4 HIGH without), and a LanceDB create/add/vector-query round trip passes with no `sharp` or `@huggingface` module in `require.cache`. The npm `$name` form does NOT work from a consumer root (it resolves against the consumer's own direct dependencies, which lack `transformers`; measured: nested 3.0.2 and 4 HIGH remained), so the version is spelled out. The narrower `sharp` override stays documented as the fallback.
31
+ - **`docs/AUDIT-GATE.md`** records the permanent answer to "should we use LanceDB's bundled transformers": no, because the root copy gives control of the model, ONNX runtime, quantization and device policy, and the override is safe only because pi-research never loads LanceDB's embedding registry. The stale "0.39.0 is the newest stable" LanceDB claim was corrected (0.40.0 stable, `preview` 0.41.0-beta.12, both pinning transformers 3.0.2). README limitations list carries the new recipe.
32
+
33
+ ### Tests
34
+
35
+ - **Fault-injection coverage for the knowledge store, against a real LanceDB table.** New `test/unit/knowledge/store-fault-injection.test.ts` (8 tests) pins what a store looks like after an embedder dies mid-write (no partial rows, the next write succeeds, a reconnect-classified failure is retried once through `reconnectFactory`), after the manifest cannot be written (open and writes keep working), after a truncated manifest (falls back to the canonical table and still serves the data), after a corrupt manifest with live data in a migration-named table (the live table survives the open's prune pass, fails against the pre-fix code), after an orphaned migration directory with the manifest absent (pruning still proceeds, regression guard for the corrupt-manifest skip), after an unusable read-only `dbDir` (open fails loudly, a later `open()` really retries because the half-open handle is rolled back), and after the table directory vanishes under an open handle (search surfaces an error instead of serving a stale handle). Also exercised by hand, not committed: SIGKILL of a writer process while the embedder hung and again while a 60,000-row `addDocuments` was in flight left the table at exactly its prior committed row count (1, no partial batch) and a fresh process reopened it and wrote normally. Read line by line with no defect found: `src/knowledge/store.ts` (all 1,722 lines), `src/knowledge/embedder.ts` (all 770) and `src/knowledge/embedder-init.ts` (all 511). The `isEmbedderUnreachable` match on "aborted" is deliberate, not a smell: `Embedder.runInference` throws `embed aborted: pipeline disposed ...` precisely so the store reconnects (`embedder.ts` around the `if (!this.pipeline)` guard), undici surfaces a closed-connection request as "aborted", and no `AbortSignal` is plumbed into the knowledge layer, so a user abort cannot reach that matcher. Worst case is one bounded extra retry.
36
+
37
+ - **Loader-context coverage for the CJS transform pipeline.** New `test/unit/infrastructure/loader-context.test.ts` bundles the real `src/web-research/utils.ts` and `src/infrastructure/browser/config.ts` to CJS with the repo's esbuild, patches the compiled `import_meta` objects to carry only `url` (the exact jiti shim: url present, resolve absent), requires the bundles, and asserts `checkModule` finds installed packages (camoufox, playwright-core; a fake package still returns false) and `isBrowserAvailable` reports an installed browser (a fake layout in the sandboxed HOME, with a negative control: no compat flag, no browser). Both assertions fail against the pre-fix code.
38
+
8
39
  ## [1.7.15] - 2026-10-21
9
40
 
10
41
  ### Fixed
@@ -169,7 +169,7 @@ Diagnostics & platform
169
169
  | `PI_RESEARCH_SKILL_DIR` | _(auto)_ | Override the bundled research-skill source directory used by the skill installer. |
170
170
  | `PI_RESEARCH_PURGE_BROWSERS` | _(unset)_ | Read by the bundled `scripts/cleanup.cjs`: set `1` to also delete the shared camoufox browser cache (kept by default because other installs may use it). Note npm ≥7 does not run `preuninstall`, so that script does not fire on `npm uninstall` — see [AGENT-SKILL.md](AGENT-SKILL.md). |
171
171
  | `PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD` | _(unset)_ | Set `1` during `npm install` to skip the camoufox browser download (fetched lazily on first use instead; standard Playwright convention). |
172
- | `CAMOUFOX_INSTALL_DIR` | _(user cache)_ | Relocates the browser download. Honoured by pi-research, not by the launcher: `@camoufox/camoufox` reads only the platform cache variable, so pi-research maps this value onto it — `XDG_CACHE_HOME` on Linux, `LOCALAPPDATA` on Windows — and exports that to the postinstall fetch and to browser workers, so install and lookup cannot drift. Ignored on macOS, where the launcher derives its cache from `$HOME`; pi-research prints a note there. See ARCHITECTURE.md. |
172
+ | `CAMOUFOX_INSTALL_DIR` | _(user cache)_ | Relocates the browser download. Honoured by pi-research, not by the launcher: `camoufox` reads only the platform cache variable, so pi-research maps this value onto it — `XDG_CACHE_HOME` on Linux, `LOCALAPPDATA` on Windows — and exports that to the postinstall fetch and to browser workers, so install and lookup cannot drift. Ignored on macOS, where the launcher derives its cache from `$HOME`; pi-research prints a note there. See ARCHITECTURE.md. |
173
173
  | `PLAYWRIGHT_BROWSERS_PATH` | _(user cache)_ | Alias for `CAMOUFOX_INSTALL_DIR`, accepted for compatibility. |
174
174
  | `XDG_CACHE_HOME` | `~/.cache` | Standard XDG variable. When set, every `~/.cache/pi-research/...` path below is rooted at `$XDG_CACHE_HOME/pi-research/...` instead. |
175
175
  | `PI_RESEARCH_BIN` (alias `PI_RESEARCH_PATH`) | _(auto)_ | Agent-skill launcher only: explicit path to the pi-research engine binary when auto-resolution (PATH → local install → npx) should be bypassed. See [agent-skill/pi-research/references/configuration.md](../agent-skill/pi-research/references/configuration.md). |
@@ -12,10 +12,11 @@ first-party sources, so no third-party code is inlined).
12
12
 
13
13
  ### Notable dependency licensing
14
14
 
15
- @camoufox/camoufox / Camoufox browser
15
+ camoufox / Camoufox browser
16
16
 
17
- The `@camoufox/camoufox` npm package itself is licensed under **MIT**. It is the
18
- launcher that replaced `camoufox-js` 0.12.0 (MPL-2.0) in the current development line.
17
+ The `camoufox` npm package itself is licensed under **MIT**. It is the
18
+ launcher that replaced `camoufox-js` 0.12.0 (MPL-2.0) (via its former scoped name
19
+ `@camoufox/camoufox`, deprecated on npm in favour of `camoufox`).
19
20
  It is resolved at install time and **not bundled** into this package's artifacts (the
20
21
  bundled entry points are built `--packages=external`). It is used in-process only to
21
22
  configure and launch the Camoufox (Firefox-fork) browser **binary as a separate
@@ -29,11 +30,11 @@ ua-parser-js
29
30
  package free of AGPL-licensed code in its dependency tree, `package.json`
30
31
  `overrides` pins `ua-parser-js` to the `1.x` line, which is MIT-licensed. The
31
32
  1.x and 2.x APIs are compatible for the only surface our direct dependency
32
- (`@camoufox/camoufox`, which declares `^2.0.2`) uses — it calls just
33
+ (`camoufox`, which declares `^2.0.2`) uses — it calls just
33
34
  `new UAParser(ua).getBrowser().name` and `.getOS().name`, both present in 1.x and
34
35
  verified against the pinned `1.0.41` — and the pin is behavior-neutral for this
35
36
  package's usage (no custom `navigator.userAgent`/`fingerprint` is passed to Camoufox).
36
- Re-check that surface on every `@camoufox/camoufox` bump: a 2.x-only call would make
37
+ Re-check that surface on every `camoufox` bump: a 2.x-only call would make
37
38
  this override a runtime break, not just a licensing choice.
38
39
 
39
40
  youtubei.js / bgutils-js / jsdom (YouTube transcripts)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lincoln504/pi-research",
3
- "version": "1.7.15",
3
+ "version": "1.7.16",
4
4
  "description": "Web research for your agents with smart and safe tooling + knowledge store",
5
5
  "type": "module",
6
6
  "private": false,
@@ -120,11 +120,11 @@
120
120
  "image": "https://raw.githubusercontent.com/Lincoln504/pi-research/main/docs/media/hero.png"
121
121
  },
122
122
  "dependencies": {
123
- "@camoufox/camoufox": "^0.5.7",
124
123
  "@kreuzberg/html-to-markdown-node": "^3.7.2",
125
124
  "@lancedb/lancedb": "0.40.0",
126
125
  "apache-arrow": "21.1.0",
127
126
  "bgutils-js": "^4.0.3",
127
+ "camoufox": "0.5.8",
128
128
  "esbuild": "^0.28.2",
129
129
  "impit": "0.14.6",
130
130
  "jsdom": "^30.1.0",
@@ -158,7 +158,10 @@
158
158
  "jsdom": {
159
159
  "undici": "^8.10.2"
160
160
  },
161
- "sharp": "^0.35.0"
161
+ "sharp": "^0.35.0",
162
+ "@lancedb/lancedb": {
163
+ "@huggingface/transformers": "$@huggingface/transformers"
164
+ }
162
165
  },
163
166
  "devDependencies": {
164
167
  "@earendil-works/pi-ai": ">=0.99.0 <2",
@@ -9,7 +9,7 @@
9
9
  * between "where setup installed it" and "where the runtime looks" is exactly the
10
10
  * install/runtime mismatch this package has shipped before.
11
11
  *
12
- * Why this exists. `@camoufox/camoufox` (0.5.x) differs from the old `camoufox-js`:
12
+ * Why this exists. `camoufox` (0.5.x) differs from the old `camoufox-js`:
13
13
  * - It installs under <INSTALL_DIR>/browsers/<repo>/<version>/ (multi-version),
14
14
  * with `config.json`, `repo_cache.json` and a `.0.5_FLAG` beside it. camoufox-js
15
15
  * put the browser files FLAT in INSTALL_DIR with a root `version.json`.
@@ -54,7 +54,7 @@ function customDir(env = process.env) {
54
54
  return env.CAMOUFOX_INSTALL_DIR || env.PLAYWRIGHT_BROWSERS_PATH || null;
55
55
  }
56
56
 
57
- /** Mirrors @camoufox/camoufox paths.js userCacheDir('camoufox') for a given environment. */
57
+ /** Mirrors camoufox paths.js userCacheDir('camoufox') for a given environment. */
58
58
  function defaultInstallDir(env = process.env, platform = process.platform, home = os.homedir()) {
59
59
  if (platform === 'win32') {
60
60
  const base = env.LOCALAPPDATA && path.win32.isAbsolute(env.LOCALAPPDATA)
@@ -183,9 +183,9 @@ function hasExplicitChoice(dir) {
183
183
  }
184
184
 
185
185
  /**
186
- * The browser build @camoufox/camoufox was released with, from its browser-pin.json
186
+ * The browser build camoufox was released with, from its browser-pin.json
187
187
  * (`{ repoName, version, build }`, repoName lowercased), or null when unpinned/unreadable.
188
- * `packageRoot` is the directory of the @camoufox/camoufox package.
188
+ * `packageRoot` is the directory of the camoufox package.
189
189
  */
190
190
  function loadPin(packageRoot) {
191
191
  try {
@@ -197,10 +197,10 @@ function loadPin(packageRoot) {
197
197
  }
198
198
  }
199
199
 
200
- /** The @camoufox/camoufox package directory as seen from `fromDir`, or null. */
200
+ /** The camoufox package directory as seen from `fromDir`, or null. */
201
201
  function findPackageRoot(fromDir) {
202
202
  try {
203
- return path.dirname(require.resolve('@camoufox/camoufox/package.json', { paths: [fromDir] }));
203
+ return path.dirname(require.resolve('camoufox/package.json', { paths: [fromDir] }));
204
204
  } catch (_) {
205
205
  return null;
206
206
  }
@@ -94,12 +94,12 @@ removeInstalledSkills();
94
94
  const layout = require('./camoufox-layout.cjs');
95
95
 
96
96
  /**
97
- * Resolve the `camoufox` CLI entry of @camoufox/camoufox (see setup.cjs: run through
97
+ * Resolve the `camoufox` CLI entry of camoufox (see setup.cjs: run through
98
98
  * process.execPath with an argv array, never a shell string).
99
99
  */
100
100
  function resolveCamoufoxCli() {
101
101
  try {
102
- const pkgJson = require.resolve('@camoufox/camoufox/package.json', { paths: [projectRoot] });
102
+ const pkgJson = require.resolve('camoufox/package.json', { paths: [projectRoot] });
103
103
  const pkg = require(pkgJson);
104
104
  const rel = typeof pkg.bin === 'string' ? pkg.bin : pkg.bin && pkg.bin.camoufox;
105
105
  if (rel) {
package/scripts/setup.cjs CHANGED
@@ -40,7 +40,7 @@ if (belowMinimum) {
40
40
  const layout = require('./camoufox-layout.cjs');
41
41
 
42
42
  /**
43
- * Resolve the `camoufox` CLI entry of @camoufox/camoufox.
43
+ * Resolve the `camoufox` CLI entry of camoufox.
44
44
  *
45
45
  * Dependencies are hoisted, so the package's own node_modules may be empty:
46
46
  * require.resolve finds the real location. We run the CLI's JS entry with
@@ -49,7 +49,7 @@ const layout = require('./camoufox-layout.cjs');
49
49
  */
50
50
  function resolveCamoufoxCli() {
51
51
  try {
52
- const pkgJson = require.resolve('@camoufox/camoufox/package.json', { paths: [projectRoot] });
52
+ const pkgJson = require.resolve('camoufox/package.json', { paths: [projectRoot] });
53
53
  const pkg = require(pkgJson);
54
54
  const rel = typeof pkg.bin === 'string' ? pkg.bin : pkg.bin && pkg.bin.camoufox;
55
55
  if (rel) {
@@ -66,7 +66,7 @@ let browsersInstalled = false;
66
66
  // separate from browsersInstalled so the summary below still tells the truth.
67
67
  let fetchSkipped = false;
68
68
 
69
- // @camoufox/camoufox derives its install dir ONLY from the platform cache location
69
+ // camoufox derives its install dir ONLY from the platform cache location
70
70
  // and ignores CAMOUFOX_INSTALL_DIR / PLAYWRIGHT_BROWSERS_PATH. The layout module turns
71
71
  // a user's custom dir into the variable it does read (XDG_CACHE_HOME / LOCALAPPDATA).
72
72
  // The same function runs at runtime (src/infrastructure/browser/config.ts), so the
@@ -134,7 +134,7 @@ if (process.env.PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD === '1') {
134
134
  // hanging `npm install` forever (the failure path below exits 0 and the browser is
135
135
  // re-fetchable). 45 min covers a working link down to ~500 KB/s.
136
136
  const runFetch = () => {
137
- if (!cli) throw new Error('@camoufox/camoufox is not installed (cannot find its CLI)');
137
+ if (!cli) throw new Error('camoufox is not installed (cannot find its CLI)');
138
138
  const res = spawnSync(process.execPath, [cli, 'fetch'], { stdio: 'inherit', env, timeout: 45 * 60 * 1000 });
139
139
  if (res.error) throw res.error;
140
140
  if (res.status !== 0) throw new Error(`camoufox fetch exited with code ${res.status}`);
package/src/cli.ts CHANGED
@@ -821,7 +821,7 @@ async function cmdStatus(json?: boolean): Promise<number> {
821
821
  // previously assumed away here with "nothing else fails". The launcher's native
822
822
  // module (`impit`) resolves a prebuilt platform package; if npm drops it (npm/cli#4828)
823
823
  // the module fails at first use. (Historically this was better-sqlite3, a dependency
824
- // of the camoufox-js launcher this package replaced with @camoufox/camoufox.)
824
+ // of the camoufox-js launcher this package replaced with camoufox.)
825
825
  // When it is missing every browser worker dies and SEARCH IS DEAD — not degraded — while the knowledge store keeps
826
826
  // working because onnxruntime and lancedb both ship their binaries. That is not a
827
827
  // capability note, so it gates `ready`: a build that cannot search cannot research.
@@ -42,7 +42,7 @@ export async function cleanupOrphanedCamoufoxProcesses(): Promise<void> {
42
42
  * Marker that identifies a browser process as one WE launched (Camoufox via
43
43
  * Playwright), never the user's own system Firefox. We match on the launched
44
44
  * EXECUTABLE — `camoufox-bin` (Linux), `camoufox.exe` (Windows) or
45
- * `…/MacOS/camoufox` (macOS), per @camoufox/camoufox's LAUNCH_FILE — plus our
45
+ * `…/MacOS/camoufox` (macOS), per camoufox's LAUNCH_FILE — plus our
46
46
  * `…/pi-research/profiles/…` profile path (the fallback when PI_RESEARCH_TMP_DIR
47
47
  * relocates profiles). Anchoring on the executable name (rather than a bare
48
48
  * `camoufox` substring) keeps an incidental `tail camoufox.log`, `grep camoufox`,
@@ -132,7 +132,7 @@ export function isPoolShutdownError(error: unknown): boolean {
132
132
  * plain `npm install` no longer runs dependency lifecycle scripts, and npm can drop a
133
133
  * native dependency's platform package (npm/cli#4828). Historically this was
134
134
  * `better-sqlite3` (a dependency of the old `camoufox-js` launcher; the launcher is now
135
- * `@camoufox/camoufox`, whose native module is `impit`). Every browser worker then dies
135
+ * `camoufox`, whose native module is `impit`). Every browser worker then dies
136
136
  * with "Could not locate the bindings file", every query fails, and the run reported that DuckDuckGo might be
137
137
  * unreachable or the machine under extreme load. Neither was true, and the advice
138
138
  * that follows from each is useless. An install fault has to say so.
@@ -7,7 +7,7 @@
7
7
  * between "where setup installed it" and "where the runtime looks" is exactly the
8
8
  * install/runtime mismatch this package has shipped before.
9
9
  *
10
- * Why this exists. `@camoufox/camoufox` (0.5.x) differs from the old `camoufox-js`:
10
+ * Why this exists. `camoufox` (0.5.x) differs from the old `camoufox-js`:
11
11
  * - It installs under <INSTALL_DIR>/browsers/<repo>/<version>/ (multi-version),
12
12
  * with `config.json`, `repo_cache.json` and a `.0.5_FLAG` beside it. camoufox-js
13
13
  * put the browser files FLAT in INSTALL_DIR with a root `version.json`.
@@ -53,7 +53,7 @@ export function customDir(env: NodeJS.ProcessEnv = process.env): string | null {
53
53
  return env['CAMOUFOX_INSTALL_DIR'] || env['PLAYWRIGHT_BROWSERS_PATH'] || null;
54
54
  }
55
55
 
56
- /** Mirrors @camoufox/camoufox paths.js userCacheDir('camoufox') for a given environment. */
56
+ /** Mirrors camoufox paths.js userCacheDir('camoufox') for a given environment. */
57
57
  export function defaultInstallDir(env: NodeJS.ProcessEnv = process.env, platform: NodeJS.Platform = process.platform, home: string = os.homedir()): string {
58
58
  if (platform === 'win32') {
59
59
  const base = env['LOCALAPPDATA'] && path.win32.isAbsolute(env['LOCALAPPDATA'])
@@ -106,7 +106,7 @@ export function resolveInstall(env: NodeJS.ProcessEnv = process.env, platform: N
106
106
  /** Every `browsers/<repo>/<version>/` directory that holds a parseable version.json. */
107
107
  export interface InstalledBuild { repo: string; name: string; path: string; rel: string; version: string; build: string }
108
108
 
109
- /** The browser build @camoufox/camoufox was released with (repoName lowercased). */
109
+ /** The browser build camoufox was released with (repoName lowercased). */
110
110
  export interface BrowserPin { repoName: string; version: string; build: string }
111
111
 
112
112
  export function listInstalls(dir: string): InstalledBuild[] {
@@ -194,8 +194,8 @@ export function hasExplicitChoice(dir: string): boolean {
194
194
  }
195
195
 
196
196
  /**
197
- * The browser build @camoufox/camoufox was released with, from its browser-pin.json,
198
- * or null when unpinned/unreadable. `packageRoot` is the @camoufox/camoufox directory.
197
+ * The browser build camoufox was released with, from its browser-pin.json,
198
+ * or null when unpinned/unreadable. `packageRoot` is the camoufox directory.
199
199
  */
200
200
  export function loadPin(packageRoot: string): BrowserPin | null {
201
201
  try {
@@ -207,11 +207,11 @@ export function loadPin(packageRoot: string): BrowserPin | null {
207
207
  }
208
208
  }
209
209
 
210
- /** The @camoufox/camoufox package directory as seen from `fromUrl`, or null. */
210
+ /** The camoufox package directory as seen from `fromUrl`, or null. */
211
211
  export function findPackageRoot(fromUrl: string): string | null {
212
212
  try {
213
213
  const require = createRequire(fromUrl);
214
- return path.dirname(require.resolve('@camoufox/camoufox/package.json'));
214
+ return path.dirname(require.resolve('camoufox/package.json'));
215
215
  } catch {
216
216
  return null;
217
217
  }
@@ -23,7 +23,7 @@ import { createRequire } from 'node:module';
23
23
  * Where the Camoufox browser lives, and which environment overrides make the
24
24
  * browser launcher agree with that.
25
25
  *
26
- * `@camoufox/camoufox` derives its install directory ONLY from the platform cache
26
+ * `camoufox` derives its install directory ONLY from the platform cache
27
27
  * location (XDG_CACHE_HOME on Linux, LOCALAPPDATA on Windows, $HOME/Library/Caches on
28
28
  * macOS). Unlike the camoufox-js it replaced, it does NOT read CAMOUFOX_INSTALL_DIR
29
29
  * or PLAYWRIGHT_BROWSERS_PATH. Both variables are still honoured here as the
@@ -250,7 +250,7 @@ export function resolveHeadlessMode(): boolean | 'virtual' {
250
250
  * Check if the browser is available for meaningful browser pool testing.
251
251
  *
252
252
  * Returns false if:
253
- * - @camoufox/camoufox package is not installed
253
+ * - camoufox package is not installed
254
254
  * - no browser build is installed under the cache dir (new `browsers/<repo>/<version>` layout)
255
255
  * - FULL_MOCK_MODE is active (both search and scrape mocked)
256
256
  *
@@ -269,7 +269,7 @@ export function resolveHeadlessMode(): boolean | 'virtual' {
269
269
  *
270
270
  * History: camoufox-js required `better-sqlite3`, whose binding came from a dependency
271
271
  * INSTALL SCRIPT that npm 12 turns off, so the module imported fine and every browser
272
- * worker died at first use. `@camoufox/camoufox` has no better-sqlite3; the one native
272
+ * worker died at first use. `camoufox` has no better-sqlite3; the one native
273
273
  * module left in the launcher's path is `impit` (its IP/geo lookups), which resolves a
274
274
  * prebuilt platform package. That package can still be dropped by npm's optional-
275
275
  * dependency bug (npm/cli#4828), and the failure is again at first use, so the probe
@@ -300,7 +300,12 @@ function defaultNativeDepLoad(): void {
300
300
  export function isBrowserAvailable(): boolean {
301
301
  if (isFullMockMode()) return false;
302
302
  try {
303
- import.meta.resolve('@camoufox/camoufox');
303
+ // findPackageRoot() anchors on a file path (createRequire), so it works in
304
+ // every loader context. The previous import.meta.resolve() call was the
305
+ // failure mode: pi loads the extension through a transform pipeline where
306
+ // import.meta compiles to an empty object, import.meta.resolve is
307
+ // undefined, the call throws, and the catch reported an installed browser
308
+ // as missing ("Browser engine not installed" before every research run).
304
309
  const root = findPackageRoot(import.meta.url);
305
310
  return isUsable(getCamoufoxBinaryPath(), root ? loadPin(root) : null);
306
311
  } catch {
@@ -45,7 +45,7 @@ const POLL_INTERVAL_MS = 2000;
45
45
  /** In-process dedupe: concurrent pool inits / scrapers share one fetch. */
46
46
  let inFlight: Promise<void> | null = null;
47
47
 
48
- /** The paired browser build this installed @camoufox/camoufox was released with. */
48
+ /** The paired browser build this installed camoufox was released with. */
49
49
  function currentPin(): BrowserPin | null {
50
50
  const root = findPackageRoot(import.meta.url);
51
51
  return root ? loadPin(root) : null;
@@ -65,11 +65,11 @@ export function isBrowserBinaryPresent(): boolean {
65
65
  }
66
66
  }
67
67
 
68
- /** Resolve the `camoufox` CLI entry (JS file) of @camoufox/camoufox, mirroring scripts/setup.cjs. */
68
+ /** Resolve the `camoufox` CLI entry (JS file) of camoufox, mirroring scripts/setup.cjs. */
69
69
  function resolveCamoufoxCli(): string | null {
70
70
  try {
71
71
  const require = createRequire(import.meta.url);
72
- const pkgJson = require.resolve('@camoufox/camoufox/package.json');
72
+ const pkgJson = require.resolve('camoufox/package.json');
73
73
  const pkg = JSON.parse(readFileSync(pkgJson, 'utf8')) as { bin?: string | Record<string, string> };
74
74
  const rel = typeof pkg.bin === 'string' ? pkg.bin : pkg.bin?.['camoufox'];
75
75
  if (rel) {
@@ -102,7 +102,7 @@ function runFetch(): Promise<boolean> {
102
102
  return new Promise<boolean>((resolve, reject) => {
103
103
  const cli = resolveCamoufoxCli();
104
104
  if (!cli) {
105
- reject(new Error('@camoufox/camoufox is not installed (cannot find its CLI); run npm install'));
105
+ reject(new Error('camoufox is not installed (cannot find its CLI); run npm install'));
106
106
  return;
107
107
  }
108
108
  // The launcher reads only XDG_CACHE_HOME / LOCALAPPDATA: hand it the override derived
@@ -164,10 +164,11 @@ export async function initBrowser(): Promise<void> {
164
164
  // without our lockfile, so a floating range resolves to a newer, broken
165
165
  // version):
166
166
  //
167
- // • @camoufox/camoufox ^0.5.7 (replaced camoufox-js 0.12.0, 2026-10-05).
167
+ // • camoufox 0.5.8 exact (renamed from the deprecated @camoufox/camoufox
168
+ // 0.5.7 on 2026-10-22; replaced camoufox-js 0.12.0 on 2026-10-05).
168
169
  // The launcher ships `dist/data-files/browser-pin.json` naming the ONE
169
- // browser build it was released and tested with (v156.0.1-beta.34 at
170
- // 0.5.7), and by default fetches and launches exactly that build. The
170
+ // browser build it was released and tested with (v156.0.1-beta.36 at
171
+ // 0.5.8, v156.0.1-beta.34 at 0.5.7), and by default fetches and launches exactly that build. The
171
172
  // old camoufox-js had no such pairing: it took "the newest non-prerelease
172
173
  // GitHub release", so when upstream flagged v156.0.1-beta.34
173
174
  // non-prerelease on 2026-10-03 every fresh install got a browser whose
@@ -178,7 +179,7 @@ export async function initBrowser(): Promise<void> {
178
179
  // the launcher it was verified against, and no longer on upstream's
179
180
  // release timing.
180
181
  // • playwright-core 1.62.1 (exact) → playwright-core and the Camoufox
181
- // build are one matched Juggler-protocol pair. @camoufox/camoufox
182
+ // build are one matched Juggler-protocol pair. camoufox
182
183
  // declares `peerDependencies: playwright-core "<1.63"` and mirrors it
183
184
  // from its Python twin ("every Playwright minor is free to change
184
185
  // Juggler, so the ceiling is bumped deliberately"). 1.61 added a
@@ -192,7 +193,7 @@ export async function initBrowser(): Promise<void> {
192
193
  // installs our lockfile masks.
193
194
  //
194
195
  // better-sqlite3 is gone: it was camoufox-js's dependency, not ours, and
195
- // @camoufox/camoufox has none. The one native module left on the launch
196
+ // camoufox has none. The one native module left on the launch
196
197
  // path is impit, probed by probeBrowserNativeDeps().
197
198
  //
198
199
  // Always re-verify a REAL headless run after touching any of this: the
@@ -200,9 +201,9 @@ export async function initBrowser(): Promise<void> {
200
201
  // reaches production with a fully green suite.
201
202
  let CamoufoxModule: any;
202
203
  try {
203
- CamoufoxModule = await import('@camoufox/camoufox');
204
+ CamoufoxModule = await import('camoufox');
204
205
  } catch (e: unknown) {
205
- throw new Error(`[Worker] @camoufox/camoufox not found in node_modules. Please run 'npm install'. Original error: ${e instanceof Error ? e.message : String(e)}`, { cause: e });
206
+ throw new Error(`[Worker] camoufox not found in node_modules. Please run 'npm install'. Original error: ${e instanceof Error ? e.message : String(e)}`, { cause: e });
206
207
  }
207
208
 
208
209
  const { Camoufox } = CamoufoxModule;
@@ -3048,9 +3048,9 @@ async function initBrowser() {
3048
3048
  logToDebugFile3("INFO", `[Worker-${workerId3}] Initializing browser instance...`);
3049
3049
  let CamoufoxModule;
3050
3050
  try {
3051
- CamoufoxModule = await import("@camoufox/camoufox");
3051
+ CamoufoxModule = await import("camoufox");
3052
3052
  } catch (e) {
3053
- throw new Error(`[Worker] @camoufox/camoufox not found in node_modules. Please run 'npm install'. Original error: ${e instanceof Error ? e.message : String(e)}`, { cause: e });
3053
+ throw new Error(`[Worker] camoufox not found in node_modules. Please run 'npm install'. Original error: ${e instanceof Error ? e.message : String(e)}`, { cause: e });
3054
3054
  }
3055
3055
  const { Camoufox } = CamoufoxModule;
3056
3056
  const launchTimeoutMs = BROWSER_LAUNCH_TIMEOUT_MS;
@@ -102,6 +102,13 @@ export class KnowledgeStore implements IKnowledgeStore {
102
102
  // 'bm25' owns activeBm25TableName).
103
103
  private otherModeTableName: string | null = null;
104
104
  private manifestPath: string;
105
+ // The state of the manifest FILE at the last loadManifest(): 'absent' (no
106
+ // file — no migration state is known), 'loaded' (parsed — the live table
107
+ // name is positively identified), or 'corrupt' (the file EXISTS but did not
108
+ // parse — the live table name is UNKNOWN, so consumers of it such as
109
+ // pruneOrphanedMigrationDirs must treat the store's data layout as unknown
110
+ // rather than as "no migration in flight").
111
+ private manifestLoadState: 'absent' | 'loaded' | 'corrupt' = 'absent';
105
112
  private isClosing = false;
106
113
  private activeWrites = new Set<Promise<any>>();
107
114
  // Last recorded model/schema migration (persisted in the store manifest).
@@ -177,6 +184,11 @@ export class KnowledgeStore implements IKnowledgeStore {
177
184
  private async loadManifest(): Promise<void> {
178
185
  try {
179
186
  if (fs.existsSync(this.manifestPath)) {
187
+ // Optimistically 'corrupt': a successful parse below flips it to
188
+ // 'loaded'. A readFile/parse failure lands in the catch, which keeps
189
+ // 'corrupt' — the file existed, so its contents are authoritative
190
+ // evidence that a migration state may be persisted in there.
191
+ this.manifestLoadState = 'corrupt';
180
192
  const content = await fsPromises.readFile(this.manifestPath, 'utf-8');
181
193
  const manifest = JSON.parse(content);
182
194
  const savedVectorTable = typeof manifest.activeTableName === 'string' ? manifest.activeTableName : null;
@@ -196,6 +208,9 @@ export class KnowledgeStore implements IKnowledgeStore {
196
208
  if (manifest.prevMigration && typeof manifest.prevMigration.model === 'string') {
197
209
  this.prevMigration = { model: manifest.prevMigration.model, ts: Number(manifest.prevMigration.ts) || 0 };
198
210
  }
211
+ this.manifestLoadState = 'loaded';
212
+ } else {
213
+ this.manifestLoadState = 'absent';
199
214
  }
200
215
  } catch (err) {
201
216
  logger.warn('[store] Failed to load manifest, using default table name:', err);
@@ -1477,6 +1492,16 @@ export class KnowledgeStore implements IKnowledgeStore {
1477
1492
  // the manifest points at — never reap dirs when we can't positively
1478
1493
  // establish which one is live.
1479
1494
  if (!this.table) return;
1495
+ // A manifest that EXISTS but failed to parse means the live table name is
1496
+ // unknown: loadManifest fell back to the default, so an orphan scan would
1497
+ // classify the real live `knowledge_migration_<ts>` dir (the persisted
1498
+ // re-embed rename-failure state) as garbage and delete it. Skip pruning
1499
+ // entirely in that state; the dirs can be reaped once a valid manifest is
1500
+ // back (the next successful open rewrites it).
1501
+ if (this.manifestLoadState === 'corrupt') {
1502
+ logger.warn('[store] Skipping migration-dir pruning: the manifest exists but is unparseable, so the live table cannot be positively identified.');
1503
+ return;
1504
+ }
1480
1505
  try {
1481
1506
  // The dir the manifest currently points at is the live table — NEVER
1482
1507
  // delete it, even if its name contains `_migration_`/`_backup_` (a
@@ -1653,7 +1678,15 @@ export class KnowledgeStore implements IKnowledgeStore {
1653
1678
  const duration = Date.now() - startTime;
1654
1679
  metrics.observe('knowledge_store_clear_duration_ms', duration);
1655
1680
  metrics.increment('knowledge_store_clear_total', 1, { status: 'success' });
1656
- metrics.setGauge('knowledge_store_total_documents', 0);
1681
+ // Report what is actually left in THIS store's scope. A caller-supplied `filter`
1682
+ // clears only part of it, so a hard-coded 0 here made the gauge claim an empty
1683
+ // store while rows remained (count() refreshes it, but only when next called).
1684
+ // Best-effort: a failed recount must not turn a successful clear into an error.
1685
+ try {
1686
+ metrics.setGauge('knowledge_store_total_documents', await table.countRows(this.getScopeFilter()));
1687
+ } catch {
1688
+ // gauge stays at its previous value until the next count()
1689
+ }
1657
1690
  logger.info(`[store] Knowledge store cleared for scope: ${scopeFilter}`);
1658
1691
  return;
1659
1692
  } catch (err) {
@@ -12,7 +12,7 @@ The `research` tool (from pi-research extension) is your tool for web/internet r
12
12
 
13
13
  **KNOWLEDGE SEARCH (a knowledge store is enabled)**
14
14
 
15
- Check the knowledge store first. For a web-research question, call `research_knowledge_search` before the live `research` tool — it is a local lookup (instant, no network) and covers both the Project and User knowledge stores, so the live tool is only needed when the store doesn't already answer the question.
15
+ Check the knowledge store first. For a web-research question, call `research_knowledge_search` before the live `research` tool — it is a local lookup (instant, no network) and covers both the Project and User knowledge stores, so the live tool is only needed when the store doesn't already answer the question. Where a question turns on the current state of things, stored material can be stale enough to mislead — treat it as a lead, not a source.
16
16
 
17
17
  - Workflow:
18
18
  1. Call `research_knowledge_search` with the question.
@@ -4,14 +4,33 @@
4
4
  * Helper functions, type guards, and utilities
5
5
  */
6
6
 
7
+ import { createRequire } from 'node:module';
8
+ import { pathToFileURL } from 'node:url';
9
+
7
10
  /**
8
- * Common module checking utility
11
+ * Common module checking utility.
12
+ *
13
+ * Resolves via CJS `require.resolve` from a file anchor. `import.meta.resolve`
14
+ * cannot be used: pi loads this extension through a transform pipeline (jiti /
15
+ * esbuild CJS) where `import.meta` compiles to an empty object, so
16
+ * `import.meta.resolve` is undefined and calling it throws — the old
17
+ * implementation silently reported an installed module as missing, which
18
+ * disabled the browser scrape path (`playwrightAvailable` in web-scraper.ts).
19
+ * Try each available anchor in turn: the ESM `import.meta.url` (valid under
20
+ * jiti and plain Node ESM) and the CJS `__filename` (valid in CJS-compiled
21
+ * output, where `import.meta.url` is undefined).
9
22
  */
10
23
  export function checkModule(name: string): boolean {
11
- try {
12
- import.meta.resolve(name);
13
- return true;
14
- } catch {
15
- return false;
24
+ const anchors: string[] = [];
25
+ if (typeof import.meta.url === 'string') anchors.push(import.meta.url);
26
+ if (typeof __filename !== 'undefined') anchors.push(pathToFileURL(__filename).href);
27
+ for (const anchor of anchors) {
28
+ try {
29
+ createRequire(anchor).resolve(`${name}/package.json`);
30
+ return true;
31
+ } catch {
32
+ // try the next anchor
33
+ }
16
34
  }
35
+ return false;
17
36
  }
@@ -41,7 +41,7 @@ let playwrightAvailable: boolean = false;
41
41
  let markdownConverterPromise: Promise<(html: string) => Promise<string>> | null = null;
42
42
 
43
43
  export function initScraperDependencies(): void {
44
- playwrightAvailable = checkModule('playwright-core') && checkModule('@camoufox/camoufox');
44
+ playwrightAvailable = checkModule('playwright-core') && checkModule('camoufox');
45
45
  }
46
46
  initScraperDependencies();
47
47