@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
@@ -16,12 +16,18 @@ import type { IStateManager, IHealthRegistryService, IKnowledgeStoreService, ISc
16
16
  import { healthRegistry as globalHealthRegistry } from './registry.ts';
17
17
  import { isNativeStackUnavailableError } from '../knowledge/embedder-utils.ts';
18
18
  import { probeKnowledgeStoreAvailability } from '../knowledge/availability.ts';
19
+ import { getSocksProxyEndpoint } from '../infrastructure/browser/proxy-prefs.ts';
20
+ import {
21
+ probeSocksProxyForwarding,
22
+ NEUTRAL_TARGET_HOST,
23
+ NEUTRAL_TARGET_PORT,
24
+ } from '../infrastructure/browser/proxy-health.ts';
19
25
 
20
26
  /**
21
27
  * Standalone BrowserCapability check, exported so tests can call it directly
22
28
  * without going through the full registry.
23
29
  */
24
- export async function checkBrowserCapability(): Promise<{ healthy: boolean; error?: string; diagnostic?: Record<string, any> }> {
30
+ export async function checkBrowserCapability(): Promise<{ healthy: boolean; error?: string; diagnostic?: Record<string, unknown> }> {
25
31
  const mockMode = process.env['PI_RESEARCH_MOCK_SEARCH'] === 'true' &&
26
32
  process.env['PI_RESEARCH_MOCK_SCRAPE'] === 'true';
27
33
  if (isBrowserAvailable() || mockMode) {
@@ -109,6 +115,55 @@ export function registerHealthChecks(registry: IHealthRegistryService, container
109
115
  // class the derived budget exists to prevent, one call-frame further out.
110
116
  }, { timeoutMs: Math.max(healthTimeoutMs, 150000, getHealthCheckBudgetMs(config)), critical: true });
111
117
 
118
+ // Register SOCKS Proxy Check — only meaningful when `proxy.json` exists, and
119
+ // CRITICAL when it does: every browser request goes through it, so a proxy that
120
+ // is not forwarding means 100% of searches fail. Before this check existed, a
121
+ // one-way tunnel (1.7.23) reported "All systems operational" while every run
122
+ // died, because BrowserCapability only proves the browser is installed and the
123
+ // browser runtime check short-circuits to "ready (idle)" when idle.
124
+ //
125
+ // The probe speaks SOCKS5 and requires BYTES BACK, not just a successful
126
+ // CONNECT: the observed failure accepted the handshake and black-holed the
127
+ // response, so a connect-only check passes it.
128
+ registry.register('SocksProxy', async () => {
129
+ const endpoint = getSocksProxyEndpoint();
130
+ if (!endpoint) {
131
+ return { healthy: true, diagnostic: { status: 'not configured (browser connects directly)' } };
132
+ }
133
+ // Explicit budgets so the DDG probe plus the neutral fallback stay inside the
134
+ // 25s registration timeout below (4+5+4+5 = 18s worst case).
135
+ const probe = await probeSocksProxyForwarding(endpoint, { timeoutMs: 4_000, dataTimeoutMs: 5_000 });
136
+ if (probe.healthy) {
137
+ return {
138
+ healthy: true,
139
+ diagnostic: {
140
+ status: `forwarding via ${endpoint.host}:${endpoint.port}`,
141
+ firstByteMs: probe.latencyMs,
142
+ },
143
+ };
144
+ }
145
+ // DuckDuckGo answered nothing. Ask the proxy for a neutral host before
146
+ // declaring the tunnel broken: that separates "the tunnel is dead" (restart
147
+ // the proxy) from "the tunnel works but DuckDuckGo's pinned front doors are
148
+ // dead" (repin or drop the proxy). Both make research impossible, but they
149
+ // are different repairs.
150
+ const neutral = await probeSocksProxyForwarding(endpoint, {
151
+ timeoutMs: 4_000,
152
+ dataTimeoutMs: 5_000,
153
+ targetHost: NEUTRAL_TARGET_HOST,
154
+ targetPort: NEUTRAL_TARGET_PORT,
155
+ });
156
+ if (neutral.healthy) {
157
+ return {
158
+ healthy: false,
159
+ error: `the proxy forwards traffic to ${NEUTRAL_TARGET_HOST}, but DuckDuckGo is unreachable through it (${probe.reason}). The tunnel works; the pinned front doors do not. Update DDG_PIN_IPS and restart the proxy, or remove ~/.pi/research/proxy.json.`,
160
+ };
161
+ }
162
+ return { healthy: false, error: probe.reason };
163
+ // Two probes with explicit 4s/5s deadlines (18s worst case) plus room for a
164
+ // loaded machine, inside the 25s registration timeout.
165
+ }, { timeoutMs: 25_000, critical: true });
166
+
112
167
  // Register Knowledge Store Check — NON-critical: the store is the optional cache
113
168
  // research must run without (see the darwin-x64 comment below). A failure here
114
169
  // (e.g. a dead embedding server, ECONNREFUSED) must degrade health, not flip the
@@ -334,13 +389,19 @@ export function isBusyPoolHealthFailure(
334
389
  // probe abort an otherwise-operational session. A non-timeout error (browser not
335
390
  // installed, "connection refused", embedder missing) is a real fault → returns false.
336
391
  const isTimeout = (c: { error?: string }) => /tim(e|ed)\s*out|timeout/i.test(String(c.error || ''));
337
- return capabilityOk && unhealthy.length > 0 && unhealthy.every(isTimeout);
392
+ // A BROKEN PROXY IS NEVER "BUSY". Under total search failure every probe
393
+ // times out, so the timeout-only rule above would call the pool busy and let
394
+ // the run fan out its whole search burst into a dead tunnel (observed
395
+ // 2026-10-30: 36 searches, 7 minutes, one generic error). The proxy check
396
+ // distinguishes "no bytes came back" from "the pool is congested".
397
+ const proxyBroken = unhealthy.some(c => c.component === 'SocksProxy');
398
+ return capabilityOk && !proxyBroken && unhealthy.length > 0 && unhealthy.every(isTimeout);
338
399
  }
339
400
 
340
401
  /**
341
402
  * Perform a full system health check
342
403
  */
343
- export async function runHealthCheck(options?: { force?: boolean; ctx?: any }) {
404
+ export async function runHealthCheck(options?: { force?: boolean; ctx?: unknown }) {
344
405
  const container = tryGetServiceContainerFromCtx(options?.ctx);
345
406
 
346
407
  let registry: IHealthRegistryService;
@@ -356,8 +417,9 @@ export async function runHealthCheck(options?: { force?: boolean; ctx?: any }) {
356
417
  success: result.status !== 'unhealthy',
357
418
  status: result.status,
358
419
  components: result.components,
359
- error: result.status === 'unhealthy'
360
- ? result.components.find(c => !c.healthy && registry.isCritical(c.component))?.error
420
+ error: result.status === 'unhealthy'
421
+ ? (result.components as { healthy?: boolean; component?: string; error?: string }[])
422
+ .find(c => !c.healthy && registry.isCritical(c.component ?? ''))?.error
361
423
  : undefined
362
424
  };
363
425
  }
@@ -1,24 +1,11 @@
1
- import type { IHealthRegistryService } from '../core/interfaces/health-check-interfaces.ts';
1
+ import type { IHealthRegistryService, SystemHealth, HealthCheckStatus } from '../core/interfaces/health-check-interfaces.ts';
2
2
  import { ServiceLifecycle } from '../core/service-registry.ts';
3
3
  import { ServiceNames } from '../core/interfaces/service-names.ts';
4
4
  import { logger } from '../logger.ts';
5
5
 
6
- export interface HealthCheckStatus {
7
- component: string;
8
- healthy: boolean;
9
- durationMs: number;
10
- error?: string;
11
- diagnostic?: Record<string, any>;
12
- timestamp: string;
13
- }
14
-
15
- export interface SystemHealth {
16
- status: 'healthy' | 'degraded' | 'unhealthy';
17
- components: HealthCheckStatus[];
18
- timestamp: string;
19
- }
6
+ export { SystemHealth, HealthCheckStatus } from '../core/interfaces/health-check-interfaces.ts';
20
7
 
21
- export type HealthCheckFn = (options?: { force?: boolean }) => Promise<{ healthy: boolean; error?: string; diagnostic?: Record<string, any> }>;
8
+ export type HealthCheckFn = (options?: { force?: boolean }) => Promise<{ healthy: boolean; error?: string; diagnostic?: Record<string, unknown> }>;
22
9
 
23
10
  interface RegisteredCheck {
24
11
  name: string;
@@ -67,7 +54,7 @@ export class HealthCheckRegistry implements IHealthRegistryService {
67
54
 
68
55
  let timeoutId: NodeJS.Timeout | undefined;
69
56
  try {
70
- const timeoutPromise = new Promise<{ healthy: boolean; error?: string; diagnostic?: Record<string, any> }>((_, reject) => {
57
+ const timeoutPromise = new Promise<{ healthy: boolean; error?: string; diagnostic?: Record<string, unknown> }>((_, reject) => {
71
58
  timeoutId = setTimeout(() => reject(new Error(`Health check timed out after ${registeredCheck.timeoutMs}ms`)), registeredCheck.timeoutMs);
72
59
  // Don't let a pending health-check timer keep the event loop alive and
73
60
  // delay process exit if the check itself rejects (race jumps to catch,
@@ -76,7 +63,7 @@ export class HealthCheckRegistry implements IHealthRegistryService {
76
63
  });
77
64
 
78
65
  const checkPromise = registeredCheck.check(options);
79
- checkPromise.catch((err: any) => logger.debug(`[HealthCheck] Background check rejection: ${err instanceof Error ? err.message : String(err)}`));
66
+ checkPromise.catch((err: unknown) => logger.debug(`[HealthCheck] Background check rejection: ${err instanceof Error ? err.message : String(err)}`));
80
67
  const result = await Promise.race([checkPromise, timeoutPromise]);
81
68
 
82
69
  status.healthy = result.healthy;
package/src/index.ts CHANGED
@@ -3,7 +3,7 @@
3
3
  // Level 3 = Error, 4 = Fatal.
4
4
  process.env['ORT_LOGGING_LEVEL'] = '3';
5
5
 
6
- import type { ExtensionAPI, ToolDefinition, AgentToolResult, ExtensionContext, SessionShutdownEvent, SessionBeforeCompactEvent, SessionCompactEvent } from '@earendil-works/pi-coding-agent';
6
+ import type { ExtensionAPI, ToolDefinition, AgentToolResult, ExtensionContext, SessionShutdownEvent, SessionBeforeCompactEvent, SessionCompactEvent, InputEvent, SessionStartEvent, BeforeAgentStartEvent, AfterProviderResponseEvent } from '@earendil-works/pi-coding-agent';
7
7
  import type { ExtendedExtensionContext } from './types/extension-context.ts';
8
8
  import { VERSION as PI_VERSION } from '@earendil-works/pi-coding-agent';
9
9
  import { Key } from '@earendil-works/pi-tui';
@@ -128,7 +128,7 @@ export default async function (pi: ExtensionAPI) {
128
128
 
129
129
  // 1. REGISTER CRITICAL EVENT LISTENERS IMMEDIATELY
130
130
  // This ensures we capture steering even if initialization takes time.
131
- pi.on('input', async (event: any, ctx: ExtensionContext) => {
131
+ pi.on('input', async (event: InputEvent, ctx: ExtensionContext) => {
132
132
  // A new prompt (not steering typed while the agent runs): re-align the
133
133
  // knowledge-search tool's exposure with live config before pi builds this
134
134
  // turn's prompt, so a /research-config Knowledge Mode change applies without
@@ -283,7 +283,7 @@ export default async function (pi: ExtensionAPI) {
283
283
 
284
284
  // Validate config at startup (using pi.cwd)
285
285
  try {
286
- const config = getConfig((pi as any).cwd, 'pi');
286
+ const config = getConfig('pi');
287
287
  validateConfig(config);
288
288
  logger.debug('[pi-research] Config validated');
289
289
  } catch (err) {
@@ -366,7 +366,7 @@ export default async function (pi: ExtensionAPI) {
366
366
  let knowledgeSearchExposure: 'direct' | 'hidden' | undefined;
367
367
  const syncKnowledgeSearchExposure = (ctx?: ExtensionContext): void => {
368
368
  try {
369
- const mode = getConfig(ctx?.cwd ?? (pi as any).cwd, 'pi').KNOWLEDGE_STORE_MODE;
369
+ const mode = getConfig(ctx?.cwd, 'pi').KNOWLEDGE_STORE_MODE;
370
370
  const want: 'direct' | 'hidden' = mode === 'none' ? 'hidden' : 'direct';
371
371
  if (want === knowledgeSearchExposure) return;
372
372
  pi.registerTool({ ...researchKnowledgeSearchTool, exposure: want });
@@ -377,7 +377,7 @@ export default async function (pi: ExtensionAPI) {
377
377
  }
378
378
  };
379
379
  syncKnowledgeSearchExposure();
380
- pi.on('session_start', async (_event: any, ctx: ExtensionContext) => {
380
+ pi.on('session_start', async (_event: SessionStartEvent, ctx: ExtensionContext) => {
381
381
  syncKnowledgeSearchExposure(ctx);
382
382
  });
383
383
 
@@ -482,7 +482,7 @@ export default async function (pi: ExtensionAPI) {
482
482
  display: true,
483
483
  details: {
484
484
  totalTokens: (result.details as ResearchResultDetails)?.totalTokens ?? 0,
485
- researchId: (result.details as any)?.researchId
485
+ researchId: (result.details as ResearchResultDetails | undefined)?.['researchId']
486
486
  },
487
487
  });
488
488
 
@@ -547,7 +547,7 @@ export default async function (pi: ExtensionAPI) {
547
547
  // Key the gate off the SAME cwd the tool below resolves its config from (ctx.cwd, not
548
548
  // the activation pi.cwd) so the "disabled?" check and the tool never disagree on the
549
549
  // mode when the session cwd differs from the activation directory.
550
- if (getConfig(ctx.cwd ?? (pi as any).cwd, 'pi').KNOWLEDGE_STORE_MODE === 'none') {
550
+ if (getConfig(ctx.cwd, 'pi').KNOWLEDGE_STORE_MODE === 'none') {
551
551
  const msg = 'The knowledge store is disabled (Knowledge Mode = none). Enable it via /research-config.';
552
552
  if (ctx.hasUI) ctx.ui.notify(msg, 'warning');
553
553
  else pi.sendMessage({ customType: 'knowledge-store', content: msg, display: true });
@@ -569,7 +569,7 @@ export default async function (pi: ExtensionAPI) {
569
569
  customType: 'knowledge-store',
570
570
  content: output,
571
571
  display: true,
572
- details: { researchId: (result.details as any)?.researchId },
572
+ details: { researchId: (result.details as ResearchResultDetails | undefined)?.['researchId'] },
573
573
  });
574
574
  if (ctx.hasUI) ctx.ui.notify('Knowledge search finished.', 'info');
575
575
  } catch (deliverErr) {
@@ -600,11 +600,7 @@ export default async function (pi: ExtensionAPI) {
600
600
  });
601
601
 
602
602
  // JIT Prompt Injection (Simplified & Non-Intrusive)
603
- pi.on('before_agent_start', async (event: any, ctx: ExtensionContext) => {
604
- if (event.streamingBehavior === 'steer') {
605
- return { systemPrompt: event.systemPrompt };
606
- }
607
-
603
+ pi.on('before_agent_start', async (event: BeforeAgentStartEvent, ctx: ExtensionContext) => {
608
604
  if (ctx.mode === 'tui' && ctx.hasUI) {
609
605
  initGlobalTuiController(ctx.ui, (ctx as ExtendedExtensionContext).sessionId);
610
606
  }
@@ -647,7 +643,7 @@ export default async function (pi: ExtensionAPI) {
647
643
  // from (ctx.cwd, not the activation pi.cwd) — KNOWLEDGE_STORE_MODE is per-directory, so
648
644
  // when the session cwd differs from the activation dir the prompt block and the tool
649
645
  // must not disagree on whether the store is enabled.
650
- const knowledgeModeEnabled = getConfig(ctx.cwd ?? (pi as any).cwd, 'pi').KNOWLEDGE_STORE_MODE !== 'none';
646
+ const knowledgeModeEnabled = getConfig(ctx.cwd, 'pi').KNOWLEDGE_STORE_MODE !== 'none';
651
647
  const isKnowledgeSearchAvailable = knowledgeModeEnabled &&
652
648
  (!event.systemPromptOptions || event.systemPromptOptions.selectedTools?.includes(researchKnowledgeSearchTool.name));
653
649
 
@@ -682,7 +678,7 @@ export default async function (pi: ExtensionAPI) {
682
678
  });
683
679
 
684
680
  // Monitor provider responses for diagnostics
685
- pi.on('after_provider_response', async (event: any, ctx: any) => {
681
+ pi.on('after_provider_response', async (event: AfterProviderResponseEvent, ctx: ExtensionContext) => {
686
682
  const { status, headers } = event;
687
683
 
688
684
  if (status >= 500) {
@@ -706,7 +702,7 @@ export default async function (pi: ExtensionAPI) {
706
702
  const health = await healthRegistry.runAll();
707
703
  const statusIcon = health.status === 'healthy' ? '[OK]' :
708
704
  health.status === 'degraded' ? '[WARN]' : '[ERROR]';
709
- const failedComponents = health.components.filter((c: any) => !c.healthy).map((c: any) => c.component).join(', ');
705
+ const failedComponents = health.components.filter((c) => !c.healthy).map((c) => c.component).join(', ');
710
706
 
711
707
  if (health.status === 'healthy') {
712
708
  logger.log(`[pi-research] ${statusIcon} System health check passed. All components operational.`);
@@ -9,7 +9,7 @@ import * as http from 'node:http';
9
9
  import type { Config } from '../../config.ts';
10
10
  import { getConfig } from '../../config.ts';
11
11
 
12
- import type { SearchResult } from '../../web-research/types.ts';
12
+ import type { SearchResult, ScrapeResult } from '../../web-research/types.ts';
13
13
  import type { IScheduler, TaskDispatchListener } from '../../core/interfaces/scheduler-interfaces.ts';
14
14
  import { logger } from '../../logger.ts';
15
15
  import { errorTracker } from '../../utils/error-tracker.ts';
@@ -116,7 +116,7 @@ export class BrowserClient implements IScheduler {
116
116
  logger.log(`[BrowserClient] Connecting to global scheduler at http://127.0.0.1:${port}`);
117
117
  }
118
118
 
119
- private async request<T>(path: string, data: any, signal?: AbortSignal, config?: Config): Promise<T> {
119
+ private async request<T>(path: string, data: unknown, signal?: AbortSignal, config?: Config): Promise<T> {
120
120
  const start = Date.now();
121
121
  // Extract operation from path for error tracking
122
122
  const operation = path.includes('/search') ? 'search' :
@@ -325,8 +325,8 @@ export class BrowserClient implements IScheduler {
325
325
  }
326
326
 
327
327
  /** See runSearch on why `onTaskEvent` is not invoked. */
328
- async runScrape(url: string, config?: Config, signal?: AbortSignal, _onTaskEvent?: TaskDispatchListener): Promise<any> {
329
- return this.request('/scrape', { url }, signal, config);
328
+ async runScrape(url: string, config?: Config, signal?: AbortSignal, _onTaskEvent?: TaskDispatchListener): Promise<ScrapeResult> {
329
+ return this.request<ScrapeResult>('/scrape', { url }, signal, config);
330
330
  }
331
331
 
332
332
  async runHealthCheck(config?: Config, signal?: AbortSignal): Promise<{ success: boolean }> {
@@ -210,7 +210,12 @@ const MAX_SESSION_BREAKERS = 256;
210
210
  /**
211
211
  * Default circuit breaker configuration
212
212
  */
213
- const DEFAULT_BREAKER_CONFIG: any = {
213
+ const DEFAULT_BREAKER_CONFIG: {
214
+ failureThreshold: number;
215
+ resetTimeoutMs: number;
216
+ name: string;
217
+ isTransientError: (error: unknown) => boolean;
218
+ } = {
214
219
  // Raised from 3→8: parallel search bursts of 20 queries frequently produce
215
220
  // simultaneous timeouts on slow/CF-protected sites. A threshold of 3 caused
216
221
  // the breaker to open mid-burst, blocking all subsequent requests for the round.
@@ -35,8 +35,13 @@ export async function stopBrowserManager(): Promise<void> {
35
35
 
36
36
  if (instance instanceof BrowserTaskScheduler) {
37
37
  await instance.shutdown();
38
- } else if (instance && typeof (instance as any).shutdown === 'function') {
39
- await (instance as any).shutdown();
38
+ } else {
39
+ // A scheduler implementation other than BrowserTaskScheduler may still
40
+ // expose shutdown(); feature-detect it structurally.
41
+ const shutdown = (instance as { shutdown?: () => Promise<void> } | undefined)?.shutdown;
42
+ if (typeof shutdown === 'function') {
43
+ await shutdown();
44
+ }
40
45
  }
41
46
 
42
47
  // Clear all cached scheduler references
@@ -92,7 +97,7 @@ export async function waitForBrowserPoolIdle(maxWaitMs = 15000): Promise<void> {
92
97
  timeoutId = setTimeout(() => resolve('timeout'), remainingMs);
93
98
  });
94
99
  const pendingPromise = pendingShutdown.then(() => 'done' as const);
95
- pendingPromise.catch((err: any) => logger.debug(`[BrowserLifecycle] Background pending shutdown rejection: ${err instanceof Error ? err.message : String(err)}`));
100
+ pendingPromise.catch((err: unknown) => logger.debug(`[BrowserLifecycle] Background pending shutdown rejection: ${err instanceof Error ? err.message : String(err)}`));
96
101
  const winner = await Promise.race([
97
102
  pendingPromise,
98
103
  timeoutPromise,
@@ -2,12 +2,12 @@ import * as http from 'node:http';
2
2
  import * as crypto from 'node:crypto';
3
3
  import { logger } from '../../logger.ts';
4
4
  import { Utf8Body } from '../../utils/http-body.ts';
5
- import type { SearchResult } from '../../web-research/types.ts';
5
+ import type { SearchResult, ScrapeResult } from '../../web-research/types.ts';
6
6
  import { isCloudflareBlockError, isPoolShutdownError, isBenignScrapeFailure } from './browser-error-utils.ts';
7
7
 
8
8
  export interface BrowserServerOptions {
9
9
  onSearch: (query: string, signal?: AbortSignal) => Promise<SearchResult[]>;
10
- onScrape: (url: string, signal?: AbortSignal) => Promise<any>;
10
+ onScrape: (url: string, signal?: AbortSignal) => Promise<ScrapeResult>;
11
11
  onHealthCheck: (signal?: AbortSignal) => Promise<{ success: boolean }>;
12
12
  }
13
13
 
@@ -169,7 +169,7 @@ export class BrowserServer {
169
169
  req.on('end', async () => {
170
170
  try {
171
171
  const data = JSON.parse(collected.toString());
172
- let result: any;
172
+ let result: unknown;
173
173
 
174
174
  switch (req.url) {
175
175
  case '/search':
@@ -120,9 +120,9 @@ export class BrowserTaskScheduler implements IScheduler {
120
120
  private workerPoolManager: WorkerPoolManager | null = null;
121
121
  private server: BrowserServer | null = null;
122
122
  private priorityQueue: PriorityTaskQueue | null = null;
123
- private leadershipTimer: any = null;
123
+ private leadershipTimer: NodeJS.Timeout | null = null;
124
124
  private leadershipMonitorStarted: boolean = false;
125
- private idleTimer: any = null;
125
+ private idleTimer: NodeJS.Timeout | null = null;
126
126
  private consecutiveLeadershipMisses: number = 0;
127
127
  private readonly LEADERSHIP_CHECK_INTERVAL_MS: number = 5000;
128
128
  private readonly LEADERSHIP_MISS_THRESHOLD: number = 3;
@@ -318,7 +318,7 @@ export class BrowserTaskScheduler implements IScheduler {
318
318
  });
319
319
 
320
320
  logger.debug(`[BrowserTaskScheduler] Executing search: "${query}" (Timeout: ${timeoutMs}ms)`);
321
- let result: any;
321
+ let result: { error?: string; results: SearchResult[] };
322
322
  // Settling the outer race must also release the task's queue claim: a task
323
323
  // still QUEUED when the caller is answered is cancelled before it consumes
324
324
  // a slot, and a RUNNING one frees its slot instead of keeping it (plus a
@@ -338,8 +338,10 @@ export class BrowserTaskScheduler implements IScheduler {
338
338
  // when we settle. A listener that throws must not take the task down.
339
339
  try { onTaskEvent?.('dispatched'); } catch { /* caller's guard, caller's problem */ }
340
340
  try {
341
- return await executePoolTaskWithDeathBackstop(
342
- () => pool.execute({ type: 'search', query, queuedAt: startTime, taskTimeoutMs: timeoutMs }),
341
+ return await executePoolTaskWithDeathBackstop<{ error?: string; results: SearchResult[] }>(
342
+ // poolifier pools are Response = unknown by default; the worker
343
+ // settles search tasks with this in-band shape.
344
+ () => pool.execute({ type: 'search', query, queuedAt: startTime, taskTimeoutMs: timeoutMs }) as Promise<{ error?: string; results: SearchResult[] }>,
343
345
  timeoutMs,
344
346
  'Search',
345
347
  );
@@ -441,7 +443,7 @@ export class BrowserTaskScheduler implements IScheduler {
441
443
  };
442
444
  });
443
445
 
444
- let result: any;
446
+ let result: ScrapeResult;
445
447
  // See runSearch: outer settle releases the queue claim; the backstop bounds
446
448
  // a dead worker's never-settling execute().
447
449
  const settled = new AbortController();
@@ -454,8 +456,10 @@ export class BrowserTaskScheduler implements IScheduler {
454
456
  // See runSearch: the caller's guard is armed on dispatch and disarmed on settle.
455
457
  try { onTaskEvent?.('dispatched'); } catch { /* caller's guard, caller's problem */ }
456
458
  try {
457
- return await executePoolTaskWithDeathBackstop(
458
- () => pool.execute({ type: 'scrape', url, queuedAt: startTime, taskTimeoutMs: timeoutMs }),
459
+ return await executePoolTaskWithDeathBackstop<ScrapeResult>(
460
+ // poolifier pools are Response = unknown by default; the worker
461
+ // settles scrape tasks with the in-band ScrapeResult shape.
462
+ () => pool.execute({ type: 'scrape', url, queuedAt: startTime, taskTimeoutMs: timeoutMs }) as Promise<ScrapeResult>,
459
463
  timeoutMs,
460
464
  'Scrape',
461
465
  );
@@ -762,7 +766,7 @@ export class BrowserTaskScheduler implements IScheduler {
762
766
  if (this.workerPoolManager) {
763
767
  const pool = this.workerPoolManager.getPool();
764
768
  if (pool && pool.workerNodes) {
765
- const workerPids = pool.workerNodes.map((n: any) => n.worker?.process?.pid).filter(Boolean);
769
+ const workerPids = pool.workerNodes.map((n: { worker?: { process?: { pid?: number } } }) => n.worker?.process?.pid).filter((pid): pid is number => pid !== undefined);
766
770
  if (workerPids.length > 0) {
767
771
  targetBrowserPids = await getBrowserPidsForWorkers(workerPids);
768
772
  }
@@ -19,8 +19,11 @@ function isTaskFailureResult(result: unknown): boolean {
19
19
  export interface QueuedTask<T> {
20
20
  type: TaskType;
21
21
  fn: () => Promise<T>;
22
- resolve: (val: T) => void;
23
- reject: (err: any) => void;
22
+ // Method syntax (not a function property): method parameters are bivariant, so a
23
+ // QueuedTask<T> is assignable to QueuedTask<unknown> and the shared queues can
24
+ // hold tasks of any T.
25
+ resolve(val: T): void;
26
+ reject(err: unknown): void;
24
27
  signal?: AbortSignal;
25
28
  }
26
29
 
@@ -34,9 +37,9 @@ export interface QueuedTask<T> {
34
37
  * long-running scrapes.
35
38
  */
36
39
  export class PriorityTaskQueue {
37
- private searchQueue: QueuedTask<any>[] = [];
38
- private healthcheckQueue: QueuedTask<any>[] = [];
39
- private scrapeQueue: QueuedTask<any>[] = [];
40
+ private searchQueue: QueuedTask<unknown>[] = [];
41
+ private healthcheckQueue: QueuedTask<unknown>[] = [];
42
+ private scrapeQueue: QueuedTask<unknown>[] = [];
40
43
  private activeCount = 0;
41
44
  private maxTotalConcurrency: number;
42
45
  private readonly maxQueueDepth: number;
@@ -93,7 +96,7 @@ export class PriorityTaskQueue {
93
96
  if (signal && onAbort) signal.removeEventListener('abort', onAbort);
94
97
  resolve(val);
95
98
  };
96
- const wrappedReject = (err: any) => {
99
+ const wrappedReject = (err: unknown) => {
97
100
  if (signal && onAbort) signal.removeEventListener('abort', onAbort);
98
101
  reject(err);
99
102
  };
@@ -129,7 +132,7 @@ export class PriorityTaskQueue {
129
132
  return this.maxTotalConcurrency;
130
133
  }
131
134
 
132
- private removeFromQueue(task: QueuedTask<any>): boolean {
135
+ private removeFromQueue(task: QueuedTask<unknown>): boolean {
133
136
  const queues = [this.healthcheckQueue, this.searchQueue, this.scrapeQueue];
134
137
  for (const q of queues) {
135
138
  const idx = q.indexOf(task);
@@ -144,7 +147,7 @@ export class PriorityTaskQueue {
144
147
  private process() {
145
148
  // Fill available slots
146
149
  while (this.activeCount < this.maxTotalConcurrency) {
147
- let task: QueuedTask<any> | undefined;
150
+ let task: QueuedTask<unknown> | undefined;
148
151
 
149
152
  if (this.healthcheckQueue.length > 0) {
150
153
  task = this.healthcheckQueue.shift();
@@ -169,7 +172,7 @@ export class PriorityTaskQueue {
169
172
  }
170
173
  }
171
174
 
172
- private async runTask(task: QueuedTask<any>) {
175
+ private async runTask(task: QueuedTask<unknown>) {
173
176
  // Double check abortion right before incrementing activeCount (redundant but safe)
174
177
  if (task.signal?.aborted) {
175
178
  task.reject(new Error(`Task ${task.type} aborted before starting`));
@@ -200,7 +203,7 @@ export class PriorityTaskQueue {
200
203
  // Prevent an unhandled rejection if abort wins the race and fn() rejects later.
201
204
  fnPromise.catch(() => { /* handled via the race below or abandoned on abort */ });
202
205
 
203
- let result: any;
206
+ let result: unknown;
204
207
  if (task.signal) {
205
208
  const abortPromise = new Promise<never>((_, rej) => {
206
209
  onAbort = () => rej(new Error(`Task ${task.type} aborted while running`));