@lincoln504/pi-research 1.7.23 → 1.7.25

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (99) hide show
  1. package/agent-skill/pi-research/SKILL.md +1 -1
  2. package/dist/cli.mjs +621 -205
  3. package/dist/prompts/research-tool-usage.md +4 -5
  4. package/dist/prompts/researcher.md +6 -36
  5. package/dist/prompts/system-coordinator.md +1 -1
  6. package/dist/prompts/system-lead-synthesizer.md +5 -5
  7. package/dist/thread-worker.mjs +22 -9
  8. package/docs/CHANGELOG.md +159 -0
  9. package/docs/CONFIGURATION.md +4 -3
  10. package/docs/TROUBLESHOOTING.md +92 -0
  11. package/package.json +9 -9
  12. package/scripts/ddg-socks-proxy.mjs +105 -15
  13. package/src/cli.ts +32 -14
  14. package/src/config.ts +20 -7
  15. package/src/core/interfaces/health-check-interfaces.ts +23 -2
  16. package/src/core/interfaces/knowledge-interfaces.ts +7 -4
  17. package/src/core/interfaces/observer-interfaces.ts +1 -1
  18. package/src/core/interfaces/orchestration-interfaces.ts +17 -12
  19. package/src/core/interfaces/planning-interfaces.ts +5 -5
  20. package/src/core/interfaces/process-interfaces.ts +2 -2
  21. package/src/core/interfaces/state-manager-interfaces.ts +6 -5
  22. package/src/core/llm/agentic-repair.ts +6 -6
  23. package/src/core/llm/llm-utils.ts +7 -4
  24. package/src/core/llm/model-registry-factory.ts +11 -11
  25. package/src/core/llm/research-model-resolver.ts +11 -11
  26. package/src/core/pi-version.ts +10 -1
  27. package/src/core/planning-service.ts +40 -14
  28. package/src/core/planning-utils.ts +33 -7
  29. package/src/core/service-initialization.ts +1 -1
  30. package/src/core/service-registry.ts +18 -11
  31. package/src/healthcheck/index.ts +67 -5
  32. package/src/healthcheck/registry.ts +5 -18
  33. package/src/index.ts +12 -16
  34. package/src/infrastructure/browser/browser-client.ts +4 -4
  35. package/src/infrastructure/browser/browser-error-utils.ts +6 -1
  36. package/src/infrastructure/browser/browser-lifecycle.ts +8 -3
  37. package/src/infrastructure/browser/browser-server.ts +3 -3
  38. package/src/infrastructure/browser/browser-task-scheduler.ts +13 -9
  39. package/src/infrastructure/browser/priority-task-queue.ts +13 -10
  40. package/src/infrastructure/browser/proxy-health.ts +342 -0
  41. package/src/infrastructure/browser/thread-worker-browser.ts +14 -11
  42. package/src/infrastructure/browser/thread-worker-lifecycle.ts +21 -15
  43. package/src/infrastructure/browser/thread-worker-messaging.ts +39 -31
  44. package/src/infrastructure/browser/thread-worker-types.ts +3 -1
  45. package/src/infrastructure/browser/thread-worker.mjs +22 -9
  46. package/src/infrastructure/browser/thread-worker.ts +3 -2
  47. package/src/infrastructure/browser/worker-pool-manager.ts +5 -5
  48. package/src/infrastructure/gpu-resource-service.ts +16 -9
  49. package/src/infrastructure/knowledge-store-service.ts +13 -10
  50. package/src/infrastructure/scheduler-factory-service.ts +4 -3
  51. package/src/infrastructure/service-initialization.ts +1 -1
  52. package/src/infrastructure/state/state-manager-service.ts +2 -2
  53. package/src/infrastructure/state/state-manager.ts +3 -3
  54. package/src/infrastructure/state/state-validator.ts +9 -3
  55. package/src/infrastructure/types/state-types.ts +12 -91
  56. package/src/knowledge/embedder-init.ts +8 -8
  57. package/src/knowledge/embedder-utils.ts +7 -3
  58. package/src/knowledge/embedder.ts +14 -10
  59. package/src/knowledge/onnx-env.ts +2 -2
  60. package/src/knowledge/store.ts +12 -11
  61. package/src/logger.ts +1 -1
  62. package/src/orchestration/deep-research-orchestrator.ts +36 -7
  63. package/src/orchestration/headless-observer.ts +1 -1
  64. package/src/orchestration/orchestration-types.ts +2 -2
  65. package/src/orchestration/quick-research-orchestrator.ts +4 -4
  66. package/src/orchestration/research-orchestration-service.ts +13 -13
  67. package/src/orchestration/research-synthesis-service.ts +15 -8
  68. package/src/orchestration/researcher-executor.ts +51 -8
  69. package/src/orchestration/researcher.ts +19 -7
  70. package/src/orchestration/service-initialization.ts +1 -1
  71. package/src/prompts/research-tool-usage.md +4 -5
  72. package/src/prompts/researcher.md +6 -36
  73. package/src/prompts/system-coordinator.md +1 -1
  74. package/src/prompts/system-lead-synthesizer.md +5 -5
  75. package/src/research-config.ts +11 -9
  76. package/src/sdk.ts +10 -10
  77. package/src/skill-install/skill-installer.ts +19 -10
  78. package/src/tools/grep.ts +57 -5
  79. package/src/tools/index.ts +0 -3
  80. package/src/tools/read-guard.ts +12 -0
  81. package/src/tools/research-knowledge-search.ts +15 -13
  82. package/src/tools/research-tool-definition.ts +15 -10
  83. package/src/tools/scrape.ts +3 -2
  84. package/src/tui/research-panel.ts +1 -1
  85. package/src/types/extension-context.ts +2 -2
  86. package/src/types/llm.ts +8 -7
  87. package/src/types/research-panel-types.ts +3 -1
  88. package/src/types/state-types.ts +98 -0
  89. package/src/utils/coverage-digest.ts +27 -6
  90. package/src/utils/llm-usage.ts +3 -3
  91. package/src/utils/provider-errors.ts +61 -9
  92. package/src/utils/safe-unref.ts +2 -2
  93. package/src/utils/shutdown-manager.ts +6 -6
  94. package/src/utils/stdio-capture.ts +25 -10
  95. package/src/utils/text-utils.ts +35 -0
  96. package/src/web-research/browser-search.ts +13 -1
  97. package/src/web-research/retry-utils.ts +29 -1
  98. package/src/web-research/scraper-utils.ts +9 -3
  99. package/src/web-research/web-scraper.ts +25 -10
@@ -11,6 +11,7 @@ import { redactSecrets } from '../../utils/log-utils.ts';
11
11
  import { safeUnref } from '../../utils/safe-unref.ts';
12
12
  import { MAX_HTML_SIZE, MAX_PDF_SIZE } from '../../web-research/scraper-types.ts';
13
13
  import { isProxyHopAddress } from './proxy-prefs.ts';
14
+ import type { BrowserContext, Download, Page } from 'playwright-core';
14
15
 
15
16
  /**
16
17
  * Mutex lock to serialize page creation. Playwright/Firefox can deadlock if newPage()
@@ -28,10 +29,10 @@ const PAGE_CREATION_HARD_RELEASE_MS = 5 * 60 * 1000;
28
29
  * newPage() on that SAME context is exactly what pageCreationLock exists to
29
30
  * prevent, so any call for this context is rejected fast (without ever
30
31
  * calling newPage()) until the stuck call actually settles and clears this. */
31
- let wedgedContext: any = null;
32
+ let wedgedContext: BrowserContext | null = null;
32
33
 
33
34
  /** Exported for unit testing of the page-creation mutex's timeout behavior. */
34
- export async function createPageSafe(context: any): Promise<any> {
35
+ export async function createPageSafe(context: BrowserContext): Promise<Page> {
35
36
  let release!: () => void;
36
37
  const nextLock = new Promise<void>(resolve => { release = resolve; });
37
38
  const currentLock = pageCreationLock;
@@ -95,7 +96,7 @@ export async function createPageSafe(context: any): Promise<any> {
95
96
  if (timeoutId) clearTimeout(timeoutId);
96
97
  // The timeout (or another error) won the race. If newPage() later resolves,
97
98
  // close that orphaned page so it doesn't accumulate in the long-lived context.
98
- pagePromise.then((p: any) => { try { p?.close?.(); } catch { /* already gone */ } }).catch(() => {});
99
+ pagePromise.then((p) => { try { void p.close().catch(() => {}); } catch { /* already gone */ } }).catch(() => {});
99
100
  throw err;
100
101
  }
101
102
  }
@@ -126,7 +127,7 @@ function parseTimeoutMs(envVar: string | undefined, def: number): number {
126
127
  /**
127
128
  * Log to debug file
128
129
  */
129
- function logToDebugFile(level: string, ...args: any[]): void {
130
+ function logToDebugFile(level: string, ...args: unknown[]): void {
130
131
  const logFile = process.env['PI_RESEARCH_LOG_FILE'];
131
132
  if (!logFile) return;
132
133
  // Match the main-process logger: WARN/ERROR are always recorded (crash diagnostics);
@@ -159,7 +160,7 @@ function logToDebugFile(level: string, ...args: any[]): void {
159
160
  * Setup mocking for the browser context if configured via environment variables.
160
161
  * This is used in CI to make integration tests fast and reliable without hitting real networks.
161
162
  */
162
- export async function setupMocking(context: any): Promise<void> {
163
+ export async function setupMocking(context: BrowserContext): Promise<void> {
163
164
  const mockSearch = process.env['PI_RESEARCH_MOCK_SEARCH'] === 'true';
164
165
  const mockScrape = process.env['PI_RESEARCH_MOCK_SCRAPE'] === 'true';
165
166
 
@@ -167,7 +168,7 @@ export async function setupMocking(context: any): Promise<void> {
167
168
 
168
169
  logToDebugFile('INFO', `[Worker-${workerId}] Setting up browser mocking (Search: ${mockSearch}, Scrape: ${mockScrape})`);
169
170
 
170
- await context.route('**', (route: any, request: any) => {
171
+ await context.route('**', (route, request) => {
171
172
  const urlStr = request.url();
172
173
  let url: URL;
173
174
  try {
@@ -264,13 +265,20 @@ export async function setupMocking(context: any): Promise<void> {
264
265
  /**
265
266
  * Extract search results from DuckDuckGo Lite page
266
267
  */
267
- async function extractSearchResults(page: any): Promise<any[]> {
268
+ /** One DuckDuckGo search result row. */
269
+ interface SearchHit {
270
+ title: string;
271
+ url: string;
272
+ content: string;
273
+ }
274
+
275
+ async function extractSearchResults(page: Page): Promise<SearchHit[]> {
268
276
  return await page.evaluate(() => {
269
- const found: any[] = [];
277
+ const found: SearchHit[] = [];
270
278
  // document is available in browser context (callback runs in the page)
271
279
  // eslint-disable-next-line no-undef
272
- const links = Array.from(document.querySelectorAll('a.result-link, a.result__a'));
273
- links.forEach((link: any) => {
280
+ const links = Array.from(document.querySelectorAll<HTMLAnchorElement>('a.result-link, a.result__a'));
281
+ links.forEach((link) => {
274
282
  // lite layout: <a class="result-link"> inside a <tr>; the snippet lives in
275
283
  // the NEXT sibling <tr>'s td.result-snippet (each result is a two-row pair:
276
284
  // link row + snippet row). Fall back to inside-row for robustness.
@@ -320,7 +328,7 @@ async function extractSearchResults(page: any): Promise<any[]> {
320
328
  * rejects with 'Target closed', which runTask's catch already maps back to the
321
329
  * task timeout. Fire-and-forget, `{ once }` so the listener cannot outlive the task.
322
330
  */
323
- function bindTaskAbortToPage(page: any, signal?: AbortSignal): void {
331
+ function bindTaskAbortToPage(page: Page, signal?: AbortSignal): void {
324
332
  if (!signal) return;
325
333
  const onAbort = () => { page.close().catch(() => {}); };
326
334
  if (signal.aborted) onAbort();
@@ -328,10 +336,10 @@ function bindTaskAbortToPage(page: any, signal?: AbortSignal): void {
328
336
  }
329
337
 
330
338
  export async function executeSearchTask(
331
- _context: any,
339
+ _context: BrowserContext,
332
340
  query: string,
333
341
  signal?: AbortSignal
334
- ): Promise<{ results: any[]; jitter: number }> {
342
+ ): Promise<{ results: SearchHit[]; jitter: number }> {
335
343
  const page = await createPageSafe(_context);
336
344
  const SEARCH_TIMEOUT = parseTimeoutMs(process.env['PI_RESEARCH_SEARCH_TIMEOUT_MS'], 45000);
337
345
  page.setDefaultTimeout(SEARCH_TIMEOUT);
@@ -403,7 +411,7 @@ export async function executeSearchTask(
403
411
  page.waitForNavigation({ waitUntil: 'domcontentloaded' }),
404
412
  nextButton.click(),
405
413
  ]);
406
- const seen = new Set(results.map((r: any) => r.url));
414
+ const seen = new Set(results.map((r) => r.url));
407
415
  for (const r of await extractSearchResults(page)) {
408
416
  if (!seen.has(r.url)) {
409
417
  seen.add(r.url);
@@ -413,8 +421,8 @@ export async function executeSearchTask(
413
421
  } else {
414
422
  logToDebugFile('DEBUG', `[Worker-${workerId}] SCRAPE_SECOND_PAGE: no next-page control (single page of results) for: ${query}`);
415
423
  }
416
- } catch (err: any) {
417
- logToDebugFile('WARN', `[Worker-${workerId}] SCRAPE_SECOND_PAGE: page-2 fetch failed (keeping page-1 results) for: ${query} — ${err?.message || String(err)}`);
424
+ } catch (err: unknown) {
425
+ logToDebugFile('WARN', `[Worker-${workerId}] SCRAPE_SECOND_PAGE: page-2 fetch failed (keeping page-1 results) for: ${query} — ${err instanceof Error ? err.message : String(err)}`);
418
426
  }
419
427
  }
420
428
 
@@ -428,7 +436,7 @@ export async function executeSearchTask(
428
436
 
429
437
  return { results, jitter };
430
438
  } catch (error) {
431
- await page.close().catch((err: any) => logToDebugFile('DEBUG', `[ThreadWorker] Swallowed page close/wait error: ${err.message || String(err)}`));
439
+ await page.close().catch((err: unknown) => logToDebugFile('DEBUG', `[ThreadWorker] Swallowed page close/wait error: ${err instanceof Error ? err.message : String(err)}`));
432
440
  throw error;
433
441
  }
434
442
  }
@@ -536,7 +544,7 @@ const PDF_REFETCH_TIMEOUT_MS = 90_000;
536
544
  * subresource TOCTOU window the request-time check already accepts.
537
545
  */
538
546
  async function refetchPdfBody(
539
- page: any,
547
+ page: Page,
540
548
  url: string,
541
549
  validateForWorker: (u: string) => Promise<unknown>,
542
550
  signal?: AbortSignal,
@@ -569,7 +577,7 @@ async function refetchPdfBody(
569
577
  // follow — report it as the HTTP outcome it is rather than reading a redirect body.
570
578
  if (!response.ok?.()) throw new Error(`HTTP ${status}`);
571
579
 
572
- const declared = parseInt(String((await response.headersArray?.() ?? []).find?.((h: any) => String(h.name).toLowerCase() === 'content-length')?.value ?? ''), 10);
580
+ const declared = parseInt(String((await response.headersArray?.() ?? []).find?.((h) => String(h.name).toLowerCase() === 'content-length')?.value ?? ''), 10);
573
581
  if (Number.isFinite(declared) && declared > MAX_PDF_SIZE) {
574
582
  throw new Error(`PDF too large (${Math.round(declared / 1024 / 1024)}MB, max 100MB)`);
575
583
  }
@@ -598,9 +606,9 @@ async function refetchPdfBody(
598
606
  * equivalent here.
599
607
  */
600
608
  async function readPdfDownload(
601
- download: any,
609
+ download: Download,
602
610
  url: string,
603
- page: any,
611
+ page: Page,
604
612
  pendingAddrChecks: Array<Promise<void>>,
605
613
  getPoisonedError: () => Error | null,
606
614
  ): Promise<{ contentType: string; bufferB64: string; jitter: number }> {
@@ -657,7 +665,7 @@ async function readPdfDownload(
657
665
  * Execute a scrape task
658
666
  */
659
667
  export async function executeScrapeTask(
660
- _context: any,
668
+ _context: BrowserContext,
661
669
  url: string,
662
670
  signal?: AbortSignal
663
671
  ): Promise<{ contentType: string; html?: string; bufferB64?: string; jitter: number }> {
@@ -700,7 +708,7 @@ export async function executeScrapeTask(
700
708
  // the PDF branch below was never reached and the document was lost even though the
701
709
  // bytes had already arrived. Captured here so the goto catch can finish the scrape
702
710
  // from the downloaded file instead of failing the URL.
703
- let pendingDownload: any = null;
711
+ let pendingDownload: Download | null = null;
704
712
 
705
713
  try {
706
714
  logToDebugFile('DEBUG', `[Worker-${workerId}] Starting scrape for: ${url}`);
@@ -721,7 +729,7 @@ export async function executeScrapeTask(
721
729
  // preserves mocking while actually gating each request.
722
730
  const { validateUrlForSSRF: validateForWorker, validateUrlForSSRFSync: validateForWorkerSync } =
723
731
  await import('../../web-research/scraper-utils.ts');
724
- await page.route('**', async (route: any, req: any) => {
732
+ await page.route('**', async (route, req) => {
725
733
  const reqUrl: string = req.url();
726
734
  // Only http(s) requests can reach a private host over the network; in-page
727
735
  // data:/blob:/about: schemes are not an SSRF vector and must pass through
@@ -776,7 +784,7 @@ export async function executeScrapeTask(
776
784
  // the scrape: close the page (aborting the load) and fail with a 'Fetch blocked:' error,
777
785
  // which isBenignScrapeFailure classifies as an expected per-URL outcome (debug, not ERROR).
778
786
  let finalMainFrameAddr: Promise<{ ipAddress?: string } | null> = Promise.resolve(null);
779
- page.on('response', (resp: any) => {
787
+ page.on('response', (resp) => {
780
788
  try {
781
789
  if (resp.request().resourceType() === 'document' && resp.frame() === page.mainFrame()) {
782
790
  finalMainFrameAddr = resp.serverAddr().catch(() => null);
@@ -852,7 +860,7 @@ export async function executeScrapeTask(
852
860
  // A navigation the server marks as an attachment never becomes a document: Firefox
853
861
  // routes it to the download manager and goto() rejects. Record the Download object
854
862
  // so the goto catch below can read the bytes that already arrived.
855
- page.on('download', (d: any) => { pendingDownload ??= d; });
863
+ page.on('download', (d) => { pendingDownload ??= d; });
856
864
 
857
865
  // High-fidelity wait: try domcontentloaded first for speed
858
866
  let response;
@@ -1019,7 +1027,7 @@ export async function executeScrapeTask(
1019
1027
  html.includes('<noscript>');
1020
1028
 
1021
1029
  if (needsWait) {
1022
- await page.waitForLoadState('networkidle', { timeout: 10000 }).catch((err: any) => logToDebugFile('DEBUG', `[ThreadWorker] Swallowed page close/wait error: ${err.message || String(err)}`));
1030
+ await page.waitForLoadState('networkidle', { timeout: 10000 }).catch((err: unknown) => logToDebugFile('DEBUG', `[ThreadWorker] Swallowed page close/wait error: ${err instanceof Error ? err.message : String(err)}`));
1023
1031
  html = await page.content();
1024
1032
  }
1025
1033
 
@@ -1057,7 +1065,7 @@ export async function executeScrapeTask(
1057
1065
  await page.close();
1058
1066
  return { contentType, html, jitter };
1059
1067
  } catch (error) {
1060
- await page.close().catch((err: any) => logToDebugFile('DEBUG', `[ThreadWorker] Swallowed page close/wait error: ${err.message || String(err)}`));
1068
+ await page.close().catch((err: unknown) => logToDebugFile('DEBUG', `[ThreadWorker] Swallowed page close/wait error: ${err instanceof Error ? err.message : String(err)}`));
1061
1069
  // An early-abort-triggered page.close() (oversized PDF, or SSRF poisoning) makes
1062
1070
  // the in-flight goto/content()/body() reject with 'Target closed'; report the
1063
1071
  // actual reason (a benign-classified failure) instead of that secondary teardown
@@ -1086,7 +1094,7 @@ const HEALTH_FALLBACK_URL = 'https://example.com/';
1086
1094
  * Execute a health check attempt against a given URL (defaults to the search provider).
1087
1095
  */
1088
1096
  async function executeHealthCheckAttempt(
1089
- _context: any,
1097
+ _context: BrowserContext,
1090
1098
  navTimeoutMs: number,
1091
1099
  url: string = HEALTH_PRIMARY_URL,
1092
1100
  signal?: AbortSignal
@@ -1111,7 +1119,7 @@ async function executeHealthCheckAttempt(
1111
1119
  await page.close();
1112
1120
  return { success: !!title, navMs };
1113
1121
  } catch (error) {
1114
- await page.close().catch((err: any) => logToDebugFile('DEBUG', `[ThreadWorker] Swallowed page close/wait error: ${err.message || String(err)}`));
1122
+ await page.close().catch((err: unknown) => logToDebugFile('DEBUG', `[ThreadWorker] Swallowed page close/wait error: ${err instanceof Error ? err.message : String(err)}`));
1115
1123
  throw error;
1116
1124
  }
1117
1125
  }
@@ -1120,7 +1128,7 @@ async function executeHealthCheckAttempt(
1120
1128
  * Execute a health check task
1121
1129
  */
1122
1130
  export async function executeHealthCheck(
1123
- _context: any,
1131
+ _context: BrowserContext,
1124
1132
  initMs: number,
1125
1133
  signal?: AbortSignal
1126
1134
  ): Promise<{ success: boolean; navMs: number }> {
@@ -4,6 +4,8 @@
4
4
  * Shared types for thread worker modules.
5
5
  */
6
6
 
7
+ import type { SearchResult } from '../../web-research/types.ts';
8
+
7
9
  export interface TaskData {
8
10
  type: string;
9
11
  query?: string;
@@ -13,7 +15,7 @@ export interface TaskData {
13
15
  }
14
16
 
15
17
  export interface TaskResult {
16
- results?: any[];
18
+ results?: SearchResult[];
17
19
  duration: number;
18
20
  jitter?: number;
19
21
  error?: string;
@@ -1708,6 +1708,9 @@ function getSsrfSafeFetcher() {
1708
1708
  const { Agent, fetch: undiciFetch } = await import("undici");
1709
1709
  return {
1710
1710
  fetch: undiciFetch,
1711
+ // node:net's LookupFunction pins the callback to `string | LookupAddress[]`
1712
+ // (no undefined); the wrapper's callback allows undefined for the single
1713
+ // resolution, so the two signatures differ by exactly that — a double cast.
1711
1714
  dispatcher: new Agent({ connect: { lookup: ssrfSafeLookup } })
1712
1715
  };
1713
1716
  } catch (e) {
@@ -1967,8 +1970,9 @@ function setupIpcErrorHandler() {
1967
1970
  var BENIGN_IPC_CODES = /* @__PURE__ */ new Set(["EPIPE", "ERR_IPC_CHANNEL_CLOSED", "ECONNRESET"]);
1968
1971
  function isBenignClusterIpcError(err) {
1969
1972
  if (!err) return false;
1970
- if (typeof err.code === "string" && BENIGN_IPC_CODES.has(err.code)) return true;
1971
- const msg = String(err.message || err);
1973
+ const e = err;
1974
+ if (typeof e.code === "string" && BENIGN_IPC_CODES.has(e.code)) return true;
1975
+ const msg = String(e.message || err);
1972
1976
  return /\b(EPIPE|ECONNRESET)\b/.test(msg) || /channel closed/i.test(msg);
1973
1977
  }
1974
1978
  function markWorkerBootstrap(id) {
@@ -2222,7 +2226,8 @@ async function createPageSafe(context) {
2222
2226
  if (timeoutId) clearTimeout(timeoutId);
2223
2227
  pagePromise.then((p) => {
2224
2228
  try {
2225
- p?.close?.();
2229
+ void p.close().catch(() => {
2230
+ });
2226
2231
  } catch {
2227
2232
  }
2228
2233
  }).catch(() => {
@@ -2427,7 +2432,7 @@ async function executeSearchTask(_context, query, signal) {
2427
2432
  logToDebugFile2("DEBUG", `[Worker-${workerId2}] SCRAPE_SECOND_PAGE: no next-page control (single page of results) for: ${query}`);
2428
2433
  }
2429
2434
  } catch (err) {
2430
- logToDebugFile2("WARN", `[Worker-${workerId2}] SCRAPE_SECOND_PAGE: page-2 fetch failed (keeping page-1 results) for: ${query} \u2014 ${err?.message || String(err)}`);
2435
+ logToDebugFile2("WARN", `[Worker-${workerId2}] SCRAPE_SECOND_PAGE: page-2 fetch failed (keeping page-1 results) for: ${query} \u2014 ${err instanceof Error ? err.message : String(err)}`);
2431
2436
  }
2432
2437
  }
2433
2438
  await page.close();
@@ -2437,7 +2442,7 @@ async function executeSearchTask(_context, query, signal) {
2437
2442
  await new Promise((r) => setTimeout(r, jitter));
2438
2443
  return { results, jitter };
2439
2444
  } catch (error) {
2440
- await page.close().catch((err) => logToDebugFile2("DEBUG", `[ThreadWorker] Swallowed page close/wait error: ${err.message || String(err)}`));
2445
+ await page.close().catch((err) => logToDebugFile2("DEBUG", `[ThreadWorker] Swallowed page close/wait error: ${err instanceof Error ? err.message : String(err)}`));
2441
2446
  throw error;
2442
2447
  }
2443
2448
  }
@@ -2711,7 +2716,7 @@ async function executeScrapeTask(_context, url, signal) {
2711
2716
  }
2712
2717
  const needsWait = html.length < 5e3 || html.includes('id="root"') || html.includes('id="app"') || html.includes("<noscript>");
2713
2718
  if (needsWait) {
2714
- await page.waitForLoadState("networkidle", { timeout: 1e4 }).catch((err) => logToDebugFile2("DEBUG", `[ThreadWorker] Swallowed page close/wait error: ${err.message || String(err)}`));
2719
+ await page.waitForLoadState("networkidle", { timeout: 1e4 }).catch((err) => logToDebugFile2("DEBUG", `[ThreadWorker] Swallowed page close/wait error: ${err instanceof Error ? err.message : String(err)}`));
2715
2720
  html = await page.content();
2716
2721
  }
2717
2722
  if (html.length > MAX_HTML_SIZE) {
@@ -2730,7 +2735,7 @@ async function executeScrapeTask(_context, url, signal) {
2730
2735
  await page.close();
2731
2736
  return { contentType, html, jitter };
2732
2737
  } catch (error) {
2733
- await page.close().catch((err) => logToDebugFile2("DEBUG", `[ThreadWorker] Swallowed page close/wait error: ${err.message || String(err)}`));
2738
+ await page.close().catch((err) => logToDebugFile2("DEBUG", `[ThreadWorker] Swallowed page close/wait error: ${err instanceof Error ? err.message : String(err)}`));
2734
2739
  if (oversizedPdfError) throw oversizedPdfError;
2735
2740
  if (poisonedError) throw poisonedError;
2736
2741
  throw error;
@@ -2756,7 +2761,7 @@ async function executeHealthCheckAttempt(_context, navTimeoutMs, url = HEALTH_PR
2756
2761
  await page.close();
2757
2762
  return { success: !!title, navMs };
2758
2763
  } catch (error) {
2759
- await page.close().catch((err) => logToDebugFile2("DEBUG", `[ThreadWorker] Swallowed page close/wait error: ${err.message || String(err)}`));
2764
+ await page.close().catch((err) => logToDebugFile2("DEBUG", `[ThreadWorker] Swallowed page close/wait error: ${err instanceof Error ? err.message : String(err)}`));
2760
2765
  throw error;
2761
2766
  }
2762
2767
  }
@@ -11286,6 +11291,14 @@ var ConfigSchema = typebox_exports.Object({
11286
11291
  RESEARCHER_MAX_RETRY_DELAY_MS: typebox_exports.Number({ minimum: 100, maximum: 1e4, default: 2e3 }),
11287
11292
  /** Unique researcher failures that abort the entire run (default: 2, range: 1-10) */
11288
11293
  MAX_FAILED_RESEARCHERS: typebox_exports.Number({ minimum: 1, maximum: 10, default: 2 }),
11294
+ /**
11295
+ * Run research with a SINGLE sequential researcher that carries all the queries, instead
11296
+ * of a team of parallel researchers. One session doing all the work keeps one growing,
11297
+ * fully-cached context (each turn re-reads the prior context as a cache hit), at the cost
11298
+ * of serial latency and a larger single context. Default: true (single, cache-friendly
11299
+ * researcher at every depth; Level 1 is always single regardless of this flag).
11300
+ */
11301
+ SINGLE_RESEARCHER: typebox_exports.Boolean({ default: true }),
11289
11302
  /** Target depth for recursive research (default: 1, range: 0-3; 0 = quick mode, requires QUICK_RESEARCH) */
11290
11303
  DEFAULT_RESEARCH_DEPTH: typebox_exports.Number({ minimum: 0, maximum: 3, default: 1 }),
11291
11304
  /** Opt-in gate for depth-0 (quick mode) research. When false (default), depth 0 is invisible to the agent-facing tool and any depth-0 default resolves to 1 — upstream behavior. When true, agents can pass depth: 0 and DEFAULT_RESEARCH_DEPTH=0 is honored. */
@@ -11518,7 +11531,7 @@ function taskFinished() {
11518
11531
  }
11519
11532
  var isBrowserConnected = () => {
11520
11533
  try {
11521
- return browser && typeof browser.isConnected === "function" && browser.isConnected();
11534
+ return !!(browser && "isConnected" in browser && browser.isConnected());
11522
11535
  } catch {
11523
11536
  logToDebugFile3("DEBUG", "[ThreadWorker] browser.isConnected check threw, treating as disconnected");
11524
11537
  return false;
@@ -8,6 +8,7 @@
8
8
  */
9
9
 
10
10
  import { ClusterWorker } from 'poolifier';
11
+ import type { BrowserContext } from 'playwright-core';
11
12
  import crypto from 'node:crypto';
12
13
  import process from 'node:process';
13
14
 
@@ -118,13 +119,13 @@ async function runTask(data: TaskData | undefined): Promise<TaskResult> {
118
119
  // Task-owned, not module-owned: acquireTaskContext() below hands back a
119
120
  // FRESH BrowserContext for this task alone, closed in the finally below —
120
121
  // never shared with a concurrent or later sibling task.
121
- let taskContext: any;
122
+ let taskContext: BrowserContext | undefined;
122
123
  try {
123
124
  await initBrowser();
124
125
  const initMs = Date.now() - startTime;
125
126
  taskContext = await acquireTaskContext();
126
127
 
127
- let result: any;
128
+ let result: TaskResult;
128
129
  if (type === 'search') {
129
130
  if (!query) throw new Error('Search task requires a query');
130
131
  const searchResult = await executeSearchTask(taskContext, query, abortController.signal);
@@ -82,8 +82,8 @@ export class WorkerPoolManager implements IService {
82
82
  readonly name = ServiceNames.WORKER_POOL_MANAGER;
83
83
  lifecycle = ServiceLifecycle.UNINITIALIZED;
84
84
 
85
- private pool: any | null = null;
86
- private poolInitializationPromise: Promise<any> | null = null;
85
+ private pool: FixedClusterPool | null = null;
86
+ private poolInitializationPromise: Promise<FixedClusterPool> | null = null;
87
87
  private currentWorkerCount: number | null = null;
88
88
  /** Per-worker task concurrency the LIVE pool was built with. Baked into
89
89
  * poolifier's tasksQueueOptions at construction and not changeable after, so a
@@ -149,7 +149,7 @@ export class WorkerPoolManager implements IService {
149
149
  * Ensure the pool is initialized with the current config.
150
150
  * Recreates the pool if the worker count has changed.
151
151
  */
152
- async ensurePool(config?: Config): Promise<any> {
152
+ async ensurePool(config?: Config): Promise<FixedClusterPool> {
153
153
  const maxWorkers = getMaxWorkers(config);
154
154
 
155
155
  // Fast-fail if a shutdown is in progress — the caller should retry after
@@ -379,7 +379,7 @@ export class WorkerPoolManager implements IService {
379
379
  // a concurrent path may already have moved on.
380
380
  if (this.pool === built) this.pool = null;
381
381
  this.poolEpoch++; // intentional destroy: silence the dying pool's exit events
382
- await built.destroy().catch((err: any) => logger.debug('Swallowed pool destroy error:', err));
382
+ await built.destroy().catch((err: unknown) => logger.debug('Swallowed pool destroy error:', err));
383
383
  throw new Error('Worker pool is shutting down');
384
384
  }
385
385
 
@@ -414,7 +414,7 @@ export class WorkerPoolManager implements IService {
414
414
  /**
415
415
  * Get the current pool instance.
416
416
  */
417
- getPool(): any | null {
417
+ getPool(): FixedClusterPool | null {
418
418
  return this.pool;
419
419
  }
420
420
 
@@ -52,7 +52,7 @@ export class GPUResourceService implements IGPUResourceService {
52
52
  }
53
53
  }
54
54
 
55
- async initialize(ctx?: any): Promise<void> {
55
+ async initialize(ctx?: unknown): Promise<void> {
56
56
  if (this.lifecycle === ServiceLifecycle.INITIALIZED) {
57
57
  return;
58
58
  }
@@ -152,12 +152,16 @@ export class GPUResourceService implements IGPUResourceService {
152
152
  /**
153
153
  * Acquire the global GPU lock
154
154
  */
155
- async acquireGpuLock(sessionId?: string | ((updater: any) => Promise<any>), timeoutMs?: number | string, ctx?: any): Promise<boolean> {
155
+ async acquireGpuLock(
156
+ sessionId?: string | ((updater: (state: SingletonState) => SingletonState | Promise<SingletonState>) => Promise<void>),
157
+ timeoutMs?: number | string,
158
+ ctx?: unknown,
159
+ ): Promise<boolean> {
156
160
  // Check if we are being called by StateManager (sessionId is actually updateState function)
157
161
  if (typeof sessionId === 'function') {
158
- const updateState = sessionId as any;
159
- const actualSessionId = timeoutMs as any as string;
160
- const actualTimeoutMs = ctx as any as number;
162
+ const updateState = sessionId;
163
+ const actualSessionId = timeoutMs as string;
164
+ const actualTimeoutMs = ctx as number;
161
165
  return this.performAcquireGpuLock(updateState, actualSessionId, actualTimeoutMs);
162
166
  }
163
167
 
@@ -170,15 +174,18 @@ export class GPUResourceService implements IGPUResourceService {
170
174
  /**
171
175
  * Release the global GPU lock
172
176
  */
173
- async releaseGpuLock(pid?: number | ((updater: any) => Promise<any>), ctx?: any): Promise<void> {
177
+ async releaseGpuLock(
178
+ pid?: number | ((updater: (state: SingletonState) => SingletonState | Promise<SingletonState>) => Promise<void>),
179
+ ctx?: unknown,
180
+ ): Promise<void> {
174
181
  // Check if we are being called by StateManager (pid is actually updateState function)
175
182
  if (typeof pid === 'function') {
176
- const updateState = pid as any;
177
- const actualPid = ctx as any as number;
183
+ const updateState = pid;
184
+ const actualPid = ctx as number;
178
185
  const currentPid = this.processLifecycle!.getCurrentPid();
179
186
  const targetPid = actualPid || currentPid;
180
187
 
181
- await updateState(async (state: any) => {
188
+ await updateState(async (state: SingletonState) => {
182
189
  if (state.gpuOwner && state.gpuOwner.pid === targetPid) {
183
190
  // Releasing our own lock decrements the re-entrant hold count and only
184
191
  // clears the owner record when the last in-process hold is released.
@@ -23,7 +23,7 @@ import {
23
23
  getModelChunkConfig as getKnowledgeModelChunkConfig,
24
24
  } from '../knowledge/index.ts';
25
25
  import { getEmbedder, clearEmbeddingInstance } from './embedding/embedding-factory.ts';
26
- import { getConfig } from '../config.ts';
26
+ import { getConfig, type Config } from '../config.ts';
27
27
  import { isNativeStackUnavailableError } from '../knowledge/embedder-utils.ts';
28
28
  import { probeKnowledgeStoreAvailability } from '../knowledge/availability.ts';
29
29
 
@@ -66,7 +66,7 @@ export class KnowledgeStoreService implements IKnowledgeStoreService {
66
66
  // two would race to close/null each other's components.
67
67
  private _disposalPromise: Promise<void> | null = null;
68
68
 
69
- async initialize(ctx?: any): Promise<void> {
69
+ async initialize(ctx?: unknown): Promise<void> {
70
70
  // A dispose() in flight must settle before anything below inspects
71
71
  // lifecycle or decides what to do — while() (not if()) because a newer
72
72
  // disposal can start again during the await (mirrors the
@@ -75,6 +75,9 @@ export class KnowledgeStoreService implements IKnowledgeStoreService {
75
75
  await this._disposalPromise;
76
76
  }
77
77
 
78
+ // Structural view of the init context: the service consumes only these two
79
+ // fields, and the caller's ctx (a pi host context) is wider.
80
+ const initCtx = ctx as { cwd?: string; config?: Config } | undefined;
78
81
  // Only an EXPLICIT ctx.cwd may re-scope the store. The lazy callers
79
82
  // (getStore/getEmbedder/getWriterQueue) call initialize() with no ctx — they
80
83
  // must NOT flip the scope. Resolving the missing cwd to process.cwd() here was
@@ -83,7 +86,7 @@ export class KnowledgeStoreService implements IKnowledgeStoreService {
83
86
  // disposed the correctly-scoped store and rebuilt it against process.cwd(),
84
87
  // so reads/writes silently scoped to the wrong workspace. Falling back to the
85
88
  // already-resolved this._cwd keeps the scope stable across lazy calls.
86
- const newCwd = ctx?.cwd || this._cwd;
89
+ const newCwd = initCtx?.cwd || this._cwd;
87
90
 
88
91
  // If already settled for this cwd, return early — UNLESS the live Knowledge Mode has changed
89
92
  // since we initialized (via /research-config), in which case re-initialize so the change
@@ -92,7 +95,7 @@ export class KnowledgeStoreService implements IKnowledgeStoreService {
92
95
  // - INITIALIZED and mode != the built mode : project↔global re-scope, or enabled→'none'.
93
96
  // A native-unavailable DISABLED ('native') stays memoized — retrying is futile on that platform.
94
97
  if ((this.lifecycle === ServiceLifecycle.INITIALIZED || this.lifecycle === ServiceLifecycle.DISABLED) && this._cwd === newCwd) {
95
- const liveConfig = ctx?.config || getConfig(this._cwd);
98
+ const liveConfig = initCtx?.config || getConfig(this._cwd);
96
99
  const liveMode: string = liveConfig.KNOWLEDGE_STORE_MODE;
97
100
  // Retrieval strategy ('vector' hybrid / 'bm25' lexical) participates in the same
98
101
  // live-change detection: a /research-config switch must re-scope the store onto
@@ -107,14 +110,14 @@ export class KnowledgeStoreService implements IKnowledgeStoreService {
107
110
  this.lifecycle === ServiceLifecycle.DISABLED && this._disabledReason === 'mode' && liveMode !== 'none';
108
111
  const modeChanged =
109
112
  this.lifecycle === ServiceLifecycle.INITIALIZED &&
110
- ctx?.config !== undefined &&
113
+ initCtx?.config !== undefined &&
111
114
  this._initializedMode !== undefined &&
112
- this._initializedMode !== ctx.config.KNOWLEDGE_STORE_MODE;
115
+ this._initializedMode !== initCtx.config.KNOWLEDGE_STORE_MODE;
113
116
  const retrievalChanged =
114
117
  this.lifecycle === ServiceLifecycle.INITIALIZED &&
115
- ctx?.config !== undefined &&
118
+ initCtx?.config !== undefined &&
116
119
  this._initializedRetrieval !== undefined &&
117
- this._initializedRetrieval !== ctx.config.KNOWLEDGE_STORE_RETRIEVAL;
120
+ this._initializedRetrieval !== initCtx.config.KNOWLEDGE_STORE_RETRIEVAL;
118
121
  if (!reviveFromMode && !modeChanged && !retrievalChanged) {
119
122
  return;
120
123
  }
@@ -178,10 +181,10 @@ export class KnowledgeStoreService implements IKnowledgeStoreService {
178
181
  // Prefer an explicit ctx.cwd; otherwise keep the cwd already resolved on this
179
182
  // service (defaults to process.cwd() on a never-initialized instance). This
180
183
  // mirrors the newCwd resolution above so a lazy getStore() never re-scopes.
181
- this._cwd = ctx?.cwd || this._cwd;
184
+ this._cwd = initCtx?.cwd || this._cwd;
182
185
  // Prefer a caller-resolved config (the SDK/CLI/tool seed ctx.config with the
183
186
  // interface-resolved overlay); else load this directory's config.
184
- const config = ctx?.config || getConfig(this._cwd);
187
+ const config = initCtx?.config || getConfig(this._cwd);
185
188
  // Record the mode this build reflects so a later runtime mode change is detected above.
186
189
  this._initializedMode = config.KNOWLEDGE_STORE_MODE;
187
190
  this._initializedRetrieval = config.KNOWLEDGE_STORE_RETRIEVAL;
@@ -22,9 +22,10 @@ export class SchedulerFactoryService implements ISchedulerFactory, IService {
22
22
  lifecycle = ServiceLifecycle.UNINITIALIZED;
23
23
  private container: ServiceContainer = getServiceContainer();
24
24
 
25
- async initialize(ctx?: any): Promise<void> {
26
- if (ctx?.container) {
27
- this.container = ctx.container;
25
+ async initialize(ctx?: unknown): Promise<void> {
26
+ const initCtx = ctx as { container?: ServiceContainer } | undefined;
27
+ if (initCtx?.container) {
28
+ this.container = initCtx.container;
28
29
  }
29
30
  this.lifecycle = ServiceLifecycle.INITIALIZED;
30
31
  }
@@ -276,7 +276,7 @@ export function registerInfrastructureServices(container: ServiceContainer = get
276
276
  * @param ctx - Optional extension context
277
277
  * @param container - Service container instance
278
278
  */
279
- export async function initializeInfrastructureServices(ctx?: any, container: ServiceContainer = getServiceContainer()): Promise<{ success: boolean; initialized: string[]; failed: string[] }> {
279
+ export async function initializeInfrastructureServices(ctx?: unknown, container: ServiceContainer = getServiceContainer()): Promise<{ success: boolean; initialized: string[]; failed: string[] }> {
280
280
  logger.log('[InfrastructureServiceInit] Initializing infrastructure services...');
281
281
 
282
282
  const initialized: string[] = [];
@@ -35,7 +35,7 @@ export class StateManagerService implements IStateManager {
35
35
  // The underlying state manager instance
36
36
  private _stateManager: StateManager | null = null;
37
37
 
38
- async initialize(ctx?: any): Promise<void> {
38
+ async initialize(ctx?: unknown): Promise<void> {
39
39
  if (this.lifecycle === ServiceLifecycle.INITIALIZED) {
40
40
  return;
41
41
  }
@@ -223,7 +223,7 @@ export class StateManagerService implements IStateManager {
223
223
  /**
224
224
  * Information about the current GPU owner
225
225
  */
226
- async getGpuOwner(): Promise<SingletonState['gpuOwner'] | null> {
226
+ async getGpuOwner(): Promise<NonNullable<SingletonState['gpuOwner']> | null> {
227
227
  return this.getStateManager().getGpuOwner();
228
228
  }
229
229
 
@@ -497,14 +497,14 @@ export class StateManager {
497
497
  // ==================== GPU Lock API ====================
498
498
 
499
499
  public async acquireGpuLock(sessionId?: string, timeoutMs?: number): Promise<boolean> {
500
- return this.gpuResourceService.acquireGpuLock(this.updateState.bind(this) as any, sessionId, timeoutMs);
500
+ return this.gpuResourceService.acquireGpuLock(this.updateState.bind(this), sessionId, timeoutMs);
501
501
  }
502
502
 
503
503
  public async releaseGpuLock(pid?: number): Promise<void> {
504
- await this.gpuResourceService.releaseGpuLock(this.updateState.bind(this) as any, pid);
504
+ await this.gpuResourceService.releaseGpuLock(this.updateState.bind(this), pid);
505
505
  }
506
506
 
507
- public async getGpuOwner(): Promise<SingletonState['gpuOwner'] | null> {
507
+ public async getGpuOwner(): Promise<NonNullable<SingletonState['gpuOwner']> | null> {
508
508
  const state = await this.readState();
509
509
  return state.gpuOwner || null;
510
510
  }
@@ -36,9 +36,15 @@ export class StateValidator implements IService {
36
36
  if (!Value.Check(SingletonStateSchema, coerced)) {
37
37
  // Use coerced state for error reporting to get better paths
38
38
  const errors = [...Value.Errors(SingletonStateSchema, coerced)];
39
- const errorMsg = errors.map((e: any) => {
40
- const path = String(e.path || 'root');
41
- return `${path}: ${e.message} (${JSON.stringify(e.value)})`;
39
+ // TLocalizedValidationError carries the failing property in `instancePath` (not
40
+ // `path`); the old `(e: any).path` read was always undefined, reporting 'root'
41
+ // for every field.
42
+ const errorMsg = errors.map(e => {
43
+ const path = String(e.instancePath || 'root');
44
+ // `value` is present on most TLocalizedValidationError variants but not
45
+ // all; read it through a structural view so the message stays uniform.
46
+ const value = (e as { value?: unknown }).value;
47
+ return `${path}: ${e.message} (${JSON.stringify(value)})`;
42
48
  }).join(', ');
43
49
  throw new Error(`Invalid state: ${errorMsg}`);
44
50
  }