@lincoln504/pi-research 1.7.24 → 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 (93) hide show
  1. package/agent-skill/pi-research/SKILL.md +1 -1
  2. package/dist/cli.mjs +276 -171
  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 +49 -0
  9. package/docs/CONFIGURATION.md +1 -0
  10. package/package.json +9 -9
  11. package/src/cli.ts +32 -14
  12. package/src/config.ts +20 -7
  13. package/src/core/interfaces/health-check-interfaces.ts +23 -2
  14. package/src/core/interfaces/knowledge-interfaces.ts +7 -4
  15. package/src/core/interfaces/observer-interfaces.ts +1 -1
  16. package/src/core/interfaces/orchestration-interfaces.ts +17 -12
  17. package/src/core/interfaces/planning-interfaces.ts +5 -5
  18. package/src/core/interfaces/process-interfaces.ts +2 -2
  19. package/src/core/interfaces/state-manager-interfaces.ts +6 -5
  20. package/src/core/llm/agentic-repair.ts +6 -6
  21. package/src/core/llm/llm-utils.ts +7 -4
  22. package/src/core/llm/model-registry-factory.ts +11 -11
  23. package/src/core/llm/research-model-resolver.ts +11 -11
  24. package/src/core/pi-version.ts +10 -1
  25. package/src/core/planning-service.ts +33 -13
  26. package/src/core/planning-utils.ts +33 -7
  27. package/src/core/service-initialization.ts +1 -1
  28. package/src/core/service-registry.ts +18 -11
  29. package/src/healthcheck/index.ts +5 -4
  30. package/src/healthcheck/registry.ts +5 -18
  31. package/src/index.ts +12 -16
  32. package/src/infrastructure/browser/browser-client.ts +4 -4
  33. package/src/infrastructure/browser/browser-error-utils.ts +6 -1
  34. package/src/infrastructure/browser/browser-lifecycle.ts +8 -3
  35. package/src/infrastructure/browser/browser-server.ts +3 -3
  36. package/src/infrastructure/browser/browser-task-scheduler.ts +13 -9
  37. package/src/infrastructure/browser/priority-task-queue.ts +13 -10
  38. package/src/infrastructure/browser/thread-worker-browser.ts +14 -11
  39. package/src/infrastructure/browser/thread-worker-lifecycle.ts +21 -15
  40. package/src/infrastructure/browser/thread-worker-messaging.ts +39 -31
  41. package/src/infrastructure/browser/thread-worker-types.ts +3 -1
  42. package/src/infrastructure/browser/thread-worker.mjs +22 -9
  43. package/src/infrastructure/browser/thread-worker.ts +3 -2
  44. package/src/infrastructure/browser/worker-pool-manager.ts +5 -5
  45. package/src/infrastructure/gpu-resource-service.ts +16 -9
  46. package/src/infrastructure/knowledge-store-service.ts +13 -10
  47. package/src/infrastructure/scheduler-factory-service.ts +4 -3
  48. package/src/infrastructure/service-initialization.ts +1 -1
  49. package/src/infrastructure/state/state-manager-service.ts +2 -2
  50. package/src/infrastructure/state/state-manager.ts +3 -3
  51. package/src/infrastructure/state/state-validator.ts +9 -3
  52. package/src/infrastructure/types/state-types.ts +12 -91
  53. package/src/knowledge/embedder-init.ts +8 -8
  54. package/src/knowledge/embedder-utils.ts +7 -3
  55. package/src/knowledge/embedder.ts +14 -10
  56. package/src/knowledge/onnx-env.ts +2 -2
  57. package/src/knowledge/store.ts +12 -11
  58. package/src/logger.ts +1 -1
  59. package/src/orchestration/deep-research-orchestrator.ts +15 -7
  60. package/src/orchestration/headless-observer.ts +1 -1
  61. package/src/orchestration/orchestration-types.ts +2 -2
  62. package/src/orchestration/quick-research-orchestrator.ts +4 -4
  63. package/src/orchestration/research-orchestration-service.ts +13 -13
  64. package/src/orchestration/research-synthesis-service.ts +15 -8
  65. package/src/orchestration/researcher-executor.ts +23 -7
  66. package/src/orchestration/researcher.ts +19 -7
  67. package/src/orchestration/service-initialization.ts +1 -1
  68. package/src/prompts/research-tool-usage.md +4 -5
  69. package/src/prompts/researcher.md +6 -36
  70. package/src/prompts/system-coordinator.md +1 -1
  71. package/src/prompts/system-lead-synthesizer.md +5 -5
  72. package/src/research-config.ts +11 -9
  73. package/src/sdk.ts +10 -10
  74. package/src/skill-install/skill-installer.ts +19 -10
  75. package/src/tools/grep.ts +57 -5
  76. package/src/tools/index.ts +0 -3
  77. package/src/tools/read-guard.ts +12 -0
  78. package/src/tools/research-knowledge-search.ts +15 -13
  79. package/src/tools/research-tool-definition.ts +15 -10
  80. package/src/tools/scrape.ts +3 -2
  81. package/src/tui/research-panel.ts +1 -1
  82. package/src/types/extension-context.ts +2 -2
  83. package/src/types/llm.ts +8 -7
  84. package/src/types/research-panel-types.ts +3 -1
  85. package/src/types/state-types.ts +98 -0
  86. package/src/utils/coverage-digest.ts +27 -6
  87. package/src/utils/llm-usage.ts +3 -3
  88. package/src/utils/safe-unref.ts +2 -2
  89. package/src/utils/shutdown-manager.ts +6 -6
  90. package/src/utils/stdio-capture.ts +25 -10
  91. package/src/utils/text-utils.ts +35 -0
  92. package/src/web-research/scraper-utils.ts +9 -3
  93. package/src/web-research/web-scraper.ts +25 -10
@@ -9,6 +9,7 @@
9
9
  */
10
10
 
11
11
  import { platform } from 'node:os';
12
+ import type { Browser, BrowserContext } from 'playwright-core';
12
13
  import { loadSocksProxyPrefs } from './proxy-prefs.ts';
13
14
  import { setupMocking } from './thread-worker-messaging.ts';
14
15
  import { redactSecrets } from '../../utils/log-utils.ts';
@@ -25,7 +26,7 @@ import { resolveHeadlessMode, BROWSER_LAUNCH_TIMEOUT_MS, CONTEXT_CREATION_TIMEOU
25
26
  // SAME setting to know that a response's serverAddr() is the proxy hop rather
26
27
  // than the origin (see isProxyHopAddress there).
27
28
 
28
- let browser: any = null;
29
+ let browser: Browser | BrowserContext | null = null;
29
30
  let initPromise: Promise<void> | null = null;
30
31
  let workerId: string = '';
31
32
 
@@ -49,7 +50,7 @@ let resetPending = false;
49
50
  // immediate path (doResetBrowser() + a fresh initBrowser() relaunch) while
50
51
  // this flag is still pending — see taskFinished() below for why the flag
51
52
  // alone isn't enough to know whether it's still safe to apply.
52
- let resetPendingForBrowser: any = null;
53
+ let resetPendingForBrowser: Browser | BrowserContext | null = null;
53
54
 
54
55
  /**
55
56
  * Set the worker ID for logging purposes
@@ -89,7 +90,9 @@ export function taskFinished(): void {
89
90
  */
90
91
  const isBrowserConnected = () => {
91
92
  try {
92
- return browser && typeof browser.isConnected === 'function' && browser.isConnected();
93
+ // `isConnected` is a Browser-only member; the `in` check narrows the
94
+ // Browser | BrowserContext union to Browser.
95
+ return !!(browser && 'isConnected' in browser && browser.isConnected());
93
96
  } catch {
94
97
  logToDebugFile('DEBUG', '[ThreadWorker] browser.isConnected check threw, treating as disconnected');
95
98
  return false;
@@ -101,7 +104,7 @@ const isBrowserConnected = () => {
101
104
  * This is the only logging mechanism available to worker processes —
102
105
  * the main-process logger is not accessible from isolated worker threads.
103
106
  */
104
- function logToDebugFile(level: string, ...args: any[]): void {
107
+ function logToDebugFile(level: string, ...args: unknown[]): void {
105
108
  const logFile = process.env['PI_RESEARCH_LOG_FILE'];
106
109
  if (!logFile) return;
107
110
  // Match the main-process logger: WARN/ERROR are always recorded (crash diagnostics);
@@ -183,7 +186,7 @@ export async function initBrowser(): Promise<void> {
183
186
  // Always re-verify a REAL headless run after touching any of this: the
184
187
  // unit and integration suites mock the browser, so a Juggler mismatch
185
188
  // reaches production with a fully green suite.
186
- let CamoufoxModule: any;
189
+ let CamoufoxModule: typeof import('camoufox');
187
190
  try {
188
191
  CamoufoxModule = await import('camoufox');
189
192
  } catch (e: unknown) {
@@ -278,7 +281,7 @@ export async function initBrowser(): Promise<void> {
278
281
  // Firefox with no owner, surviving the orphan sweep (its parent worker is
279
282
  // alive) until the pool shuts down. Adopt and close it, exactly as
280
283
  // createPageSafe already does for an orphaned page.
281
- launchPromise.then((b: any) => {
284
+ launchPromise.then((b: Browser | BrowserContext) => {
282
285
  if (!raceLost) return;
283
286
  logToDebugFile('WARN', `[Worker-${workerId}] Browser launch completed after its deadline; closing the orphaned instance.`);
284
287
  try { b?.close?.(); } catch { /* already gone */ }
@@ -338,7 +341,7 @@ export async function initBrowser(): Promise<void> {
338
341
 
339
342
  // camoufox headless: "virtual" spawns Xvfb on Linux when no DISPLAY is set.
340
343
  // CannotFindXvfb is thrown when `which Xvfb` fails (xvfb not installed).
341
- const errName = e instanceof Error ? (e as any).constructor?.name ?? '' : '';
344
+ const errName = e instanceof Error ? (e as { constructor?: { name?: string } }).constructor?.name ?? '' : '';
342
345
  if (errName === 'CannotFindXvfb' || errName === 'CannotExecuteXvfb' || msg.includes('Xvfb') || msg.includes('virtual display')) {
343
346
  throw new Error(
344
347
  '[Worker] No display server found on Linux. Install Xvfb for headless use (TTY/Wayland): sudo apt install xvfb',
@@ -376,20 +379,20 @@ export async function initBrowser(): Promise<void> {
376
379
  * context that finishes creating AFTER that timeout is adopted and closed
377
380
  * rather than left to leak.
378
381
  */
379
- export async function acquireTaskContext(): Promise<any> {
382
+ export async function acquireTaskContext(): Promise<BrowserContext> {
380
383
  // acceptDownloads is explicit, not defaulted: executeScrapeTask recovers PDFs that a
381
384
  // server sends as an attachment by reading the resulting Download, and that object
382
385
  // only exists when downloads are accepted.
383
- const contextPromise = browser.newContext({ acceptDownloads: true });
386
+ const contextPromise = (browser as Browser).newContext({ acceptDownloads: true });
384
387
  contextPromise.catch((err: Error) => logToDebugFile('DEBUG', `[ThreadWorker] Background browser context rejection: ${err.message}`));
385
388
  let contextTimeoutId: NodeJS.Timeout | undefined;
386
389
  let contextRaceLost = false;
387
- contextPromise.then((c: any) => {
390
+ contextPromise.then((c: BrowserContext) => {
388
391
  if (!contextRaceLost) return;
389
392
  logToDebugFile('WARN', `[Worker-${workerId}] Browser context creation completed after its deadline; closing the orphaned context.`);
390
393
  try { c?.close?.(); } catch { /* already gone */ }
391
394
  }).catch(() => { /* rejection already logged above */ });
392
- let newContext: any;
395
+ let newContext: BrowserContext;
393
396
  try {
394
397
  newContext = await Promise.race([
395
398
  contextPromise,
@@ -10,6 +10,9 @@ import cluster from 'node:cluster';
10
10
  import * as fs from 'node:fs/promises';
11
11
  import { redactSecrets } from '../../utils/log-utils.ts';
12
12
 
13
+ /** cluster.Worker plus the module's own guard marker, set on guarded workers. */
14
+ type GuardedWorker = cluster.Worker & { __piIpcGuarded?: boolean };
15
+
13
16
  let workerId: string = '';
14
17
 
15
18
  /**
@@ -35,7 +38,7 @@ export function setupIpcErrorHandler(): void {
35
38
  if (!cluster.isWorker || !cluster.worker) {
36
39
  return;
37
40
  }
38
- cluster.worker.on('error', (err: any) => {
41
+ cluster.worker.on('error', (err: unknown) => {
39
42
  if (isBenignClusterIpcError(err)) {
40
43
  return;
41
44
  }
@@ -54,10 +57,11 @@ export function setupIpcErrorHandler(): void {
54
57
  */
55
58
  const BENIGN_IPC_CODES = new Set(['EPIPE', 'ERR_IPC_CHANNEL_CLOSED', 'ECONNRESET']);
56
59
 
57
- export function isBenignClusterIpcError(err: any): boolean {
60
+ export function isBenignClusterIpcError(err: unknown): boolean {
58
61
  if (!err) return false;
59
- if (typeof err.code === 'string' && BENIGN_IPC_CODES.has(err.code)) return true;
60
- const msg = String(err.message || err);
62
+ const e = err as { code?: string; message?: string };
63
+ if (typeof e.code === 'string' && BENIGN_IPC_CODES.has(e.code)) return true;
64
+ const msg = String(e.message || err);
61
65
  return /\b(EPIPE|ECONNRESET)\b/.test(msg) || /channel closed/i.test(msg);
62
66
  }
63
67
 
@@ -94,11 +98,11 @@ export function setupMasterIpcErrorHandler(): void {
94
98
  // cluster emits 'fork' for every worker poolifier creates, including the
95
99
  // respawns it triggers via startMinimumNumberOfWorkers() after an unexpected
96
100
  // exit — so this catches the churn-driven workers, not just the initial set.
97
- cluster.on('fork', (worker) => guardClusterWorker(worker));
101
+ cluster.on('fork', (worker) => guardClusterWorker(worker as GuardedWorker));
98
102
 
99
103
  // Cover any workers already forked before this handler was installed.
100
104
  for (const id of Object.keys(cluster.workers ?? {})) {
101
- const w = (cluster.workers as any)?.[id];
105
+ const w = (cluster.workers ?? {})[id] as GuardedWorker | undefined;
102
106
  if (w) guardClusterWorker(w);
103
107
  }
104
108
 
@@ -137,14 +141,15 @@ export function guardWorkerEmitReemit(): void {
137
141
  const origEmit = Worker.prototype.emit;
138
142
  if (typeof origEmit !== 'function') return;
139
143
  workerEmitOriginal = origEmit;
140
- Worker.prototype.emit = function (this: any, event: string | symbol, ...args: unknown[]) {
144
+ Worker.prototype.emit = function (this: cluster.Worker, event: string | symbol, ...args: unknown[]) {
141
145
  if (event === 'error' && typeof this.listenerCount === 'function' && this.listenerCount('error') === 0) {
142
- this.on('error', (err: any) => {
146
+ this.on('error', (err: unknown) => {
147
+ const e = err as { code?: string; message?: string; stack?: string } | undefined;
143
148
  if (isBenignClusterIpcError(err)) {
144
- logToDebugFile('DEBUG', `[Master] Last-resort guard swallowed listener-less IPC error: ${err?.code || err?.message}`);
149
+ logToDebugFile('DEBUG', `[Master] Last-resort guard swallowed listener-less IPC error: ${e?.code || e?.message}`);
145
150
  return;
146
151
  }
147
- logToDebugFile('WARN', `[Master] Last-resort guard handled listener-less worker error: ${err?.stack || err?.message || err}`);
152
+ logToDebugFile('WARN', `[Master] Last-resort guard handled listener-less worker error: ${e?.stack || e?.message || err}`);
148
153
  });
149
154
  }
150
155
  return origEmit.apply(this, [event, ...args]);
@@ -161,19 +166,20 @@ export function __resetWorkerEmitGuardForTests(): void {
161
166
  workerEmitGuardPatched = false;
162
167
  }
163
168
 
164
- function guardClusterWorker(worker: any): void {
169
+ function guardClusterWorker(worker: GuardedWorker): void {
165
170
  if (!worker || worker.__piIpcGuarded) return;
166
171
  worker.__piIpcGuarded = true;
167
172
 
168
- const guard = (err: any) => {
173
+ const guard = (err: unknown) => {
174
+ const e = err as { code?: string; message?: string; stack?: string } | undefined;
169
175
  if (isBenignClusterIpcError(err)) {
170
- logToDebugFile('DEBUG', `[Master] Swallowed benign worker IPC error: ${err?.code || err?.message}`);
176
+ logToDebugFile('DEBUG', `[Master] Swallowed benign worker IPC error: ${e?.code || e?.message}`);
171
177
  return;
172
178
  }
173
179
  // Non-benign worker errors are independently handled by poolifier's own
174
180
  // errorHandler (which counts them and triggers pool recovery). Re-throwing
175
181
  // here would itself become an uncaughtException, so just record it.
176
- logToDebugFile('WARN', `[Master] Worker error (non-IPC): ${err?.stack || err?.message || err}`);
182
+ logToDebugFile('WARN', `[Master] Worker error (non-IPC): ${e?.stack || e?.message || err}`);
177
183
  };
178
184
 
179
185
  worker.on('error', guard);
@@ -375,7 +381,7 @@ export function cleanupOrphanProtection(): void {
375
381
  /**
376
382
  * Log to debug file
377
383
  */
378
- function logToDebugFile(level: string, ...args: any[]): void {
384
+ function logToDebugFile(level: string, ...args: unknown[]): void {
379
385
  const logFile = process.env['PI_RESEARCH_LOG_FILE'];
380
386
  if (!logFile) return;
381
387
  // Match the main-process logger: WARN/ERROR are always recorded (crash diagnostics);
@@ -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