@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
@@ -30,6 +30,23 @@ export function getTeamSize(complexity: 1 | 2 | 3): number {
30
30
  : MAX_TEAM_SIZE_LEVEL_3;
31
31
  }
32
32
 
33
+ /**
34
+ * Resolve the effective single-researcher mode for a complexity level.
35
+ *
36
+ * Level 1 (Normal) always runs a single researcher — it is the simple, fast lane, and
37
+ * one focused researcher handles normal-complexity queries. This is structural, not a
38
+ * prompt nudge: the flag cannot turn it off. Level 2 and 3 follow the
39
+ * `SINGLE_RESEARCHER` config flag (default false → flexible delegation; true → one
40
+ * researcher carrying the full team budget).
41
+ *
42
+ * This is the single source of truth for "how many researchers": the coordinator
43
+ * guidance, the router clamp, and the query-cap all read this, so there is no second
44
+ * mechanism (no per-level prompt default) that can drift from it.
45
+ */
46
+ export function effectiveSingleResearcher(complexity: 1 | 2 | 3, singleResearcher: boolean): boolean {
47
+ return complexity === 1 ? true : singleResearcher;
48
+ }
49
+
33
50
  /**
34
51
  * Get the query budget per researcher for a complexity level
35
52
  */
@@ -53,7 +70,7 @@ export function getMaxRounds(complexity: 1 | 2 | 3): number {
53
70
  */
54
71
  export function getComplexityGuidance(complexity: 1 | 2 | 3, maxTeamSize: number, queryBudget: number): string {
55
72
  if (complexity === 1) {
56
- return '**Complexity: Level 1 (Normal)**. Conduct a thorough, well-rounded investigation of the topic covering the primary angles with adequate citations. **Plan ONLY Round 1** — a single comprehensive round. **Default to a single researcher** for most Level 1 topics — one focused researcher can handle the majority of normal-complexity queries efficiently. Use 2 researchers only when the topic clearly spans two distinct, non-overlapping domains that benefit from parallel investigation. This is a ONE-SHOT effort: plan Round 1 as if it is the only round, because it should be. Only Level 2 or Level 3 research should involve multiple rounds.';
73
+ return '**Complexity: Level 1 (Normal)**. Conduct a thorough, well-rounded investigation of the topic covering the primary angles with adequate citations. **Plan ONLY Round 1** — a single comprehensive round. **Use ONE researcher** — one focused researcher handles normal-complexity queries. This is a ONE-SHOT effort: plan Round 1 as if it is the only round, because it should be. Only Level 2 or Level 3 research should involve multiple rounds.';
57
74
  } else if (complexity === 2) {
58
75
  return `**Complexity: Level 2 (Deep)**. **ONLY for HIGH/EXTREME research needs.** Level 2 should be reserved for topics that clearly require deeper investigation than a single comprehensive round can provide. **Plan ONLY Round 1** — a thorough, well-structured first round. Subsequent rounds are reactive and only delegated when Round 1 findings reveal clear gaps that warrant deeper or broader coverage. Do not pre-plan multiple rounds; delegate follow-ups only when Round 1 demonstrates genuine need.
59
76
 
@@ -93,7 +110,7 @@ export function getEvaluatorComplexityGuidance(complexity: 1 | 2 | 3, researchRo
93
110
  - **SYNTHESIZE when**: The primary topic is covered from multiple angles with evidence from diverse sources and no significant gaps remain that would prevent a complete answer.
94
111
  - **DELEGATE when**: Coverage is incomplete, important angles are missing, or additional sources would meaningfully strengthen the findings.
95
112
 
96
- **DEFAULT PATH**: Synthesize after Round 1 if the researcher produced solid coverage of the core topic. **Level 1 should almost always be a single round** — only delegate a second round when Round 1 clearly missed important angles or lacks source diversity. A single researcher is the default for Level 1 follow-up rounds — only use 2 researchers if the remaining gaps clearly span two distinct domains. Level 2 research escalation should be reserved for truly high/extreme research needs only.`;
113
+ **DEFAULT PATH**: Synthesize after Round 1 if the researcher produced solid coverage of the core topic. **Level 1 should almost always be a single round** — only delegate a second round when Round 1 clearly missed important angles or lacks source diversity. **Use ONE researcher** for follow-up rounds. Level 2 research escalation should be reserved for truly high/extreme research needs only.`;
97
114
  } else if (complexity === 2) {
98
115
  return `**Level 2 (Deep)** - Thorough, multi-phase investigation with comprehensive citations.
99
116
 
@@ -206,7 +223,9 @@ export function parseJsonPlan(text: string): ResearchPlan {
206
223
  // 2. Validate against schema
207
224
  if (!Value.Check(ResearchPlanSchema, coerced)) {
208
225
  const errors = [...Value.Errors(ResearchPlanSchema, coerced)];
209
- const errorMsg = errors.map((e: any) => `${e.path}: ${e.message}`).join(', ');
226
+ // TLocalizedValidationError carries the failing property in `instancePath` (not
227
+ // `path`); the old `(e: any).path` read was always undefined, dropping the path.
228
+ const errorMsg = errors.map(e => `${e.instancePath || ''} ${e.message}`).join(', ');
210
229
  // If validation fails, we throw to satisfy tests and ensure system integrity
211
230
  throw new Error(`Plan validation failed: ${errorMsg}`);
212
231
  }
@@ -257,8 +276,13 @@ export function buildFallbackCoordinatorPlan(serviceName: string, _rawText: stri
257
276
  /**
258
277
  * Cap researcher queries to stay within budget
259
278
  */
260
- export function capResearcherQueries(plan: ResearchPlan, complexity: 1 | 2 | 3, serviceName: string): ResearchPlan {
261
- const budget = getQueryBudget(complexity);
279
+ export function capResearcherQueries(plan: ResearchPlan, complexity: 1 | 2 | 3, serviceName: string, singleResearcher = false): ResearchPlan {
280
+ // In single-researcher mode the lone researcher carries the whole team's query load, so
281
+ // its per-researcher cap is the full team budget (maxTeamSize × per-researcher), not the
282
+ // per-researcher figure a parallel team would each get. Default (false) keeps the
283
+ // per-researcher cap.
284
+ const perResearcher = getQueryBudget(complexity);
285
+ const budget = singleResearcher ? getTeamSize(complexity) * perResearcher : perResearcher;
262
286
 
263
287
  // Hard caps per round - based on actual maximum possible queries
264
288
  // Level 1: 2 researchers x 10 queries = 20 maximum
@@ -271,8 +295,10 @@ export function capResearcherQueries(plan: ResearchPlan, complexity: 1 | 2 | 3,
271
295
  if (!plan.researchers) return plan;
272
296
 
273
297
  // 1. Normalize IDs to strings and cap individual researchers
274
- // CRITICAL: Only keep researchers with non-empty queries to guarantee search results
275
- const maxTeam = getTeamSize(complexity);
298
+ // CRITICAL: Only keep researchers with non-empty queries to guarantee search results.
299
+ // In single-researcher mode the team is ONE researcher (one growing, fully-cached
300
+ // context), so the count cap is 1, not the complexity table's team size.
301
+ const maxTeam = singleResearcher ? 1 : getTeamSize(complexity);
276
302
  plan.researchers = plan.researchers
277
303
  .filter(r => r && typeof r === 'object' && Array.isArray(r.queries) && r.queries.length > 0)
278
304
  .slice(0, maxTeam)
@@ -53,7 +53,7 @@ export function registerCoreServices(container: ServiceContainer = getServiceCon
53
53
  * @param ctx - Optional extension context to pass to services
54
54
  * @param container - Service container instance
55
55
  */
56
- export async function initializeCoreServices(ctx?: any, container: ServiceContainer = getServiceContainer()): Promise<{ success: boolean; initialized: string[]; failed: string[] }> {
56
+ export async function initializeCoreServices(ctx?: unknown, container: ServiceContainer = getServiceContainer()): Promise<{ success: boolean; initialized: string[]; failed: string[] }> {
57
57
  logger.log('[ServiceInitialization] Initializing core services...');
58
58
 
59
59
  const initialized: string[] = [];
@@ -54,7 +54,7 @@ export interface IService {
54
54
  /**
55
55
  * Initialize the service (called before first use)
56
56
  */
57
- initialize?(ctx?: any): Promise<void> | void;
57
+ initialize?(ctx?: unknown): Promise<void> | void;
58
58
 
59
59
  /**
60
60
  * Dispose the service (called during shutdown)
@@ -111,7 +111,7 @@ const initializationContext = new AsyncLocalStorage<string>();
111
111
  * Centralized service container for dependency injection
112
112
  */
113
113
  export class ServiceContainer {
114
- private services: Map<string, ServiceRegistration<any>> = new Map();
114
+ private services: Map<string, ServiceRegistration<IService>> = new Map();
115
115
  private dependencies: Map<string, Set<string>> = new Map();
116
116
  public isDisposing: boolean = false;
117
117
  // The single in-flight disposeAll() run. Only reset() JOINS it (awaiting teardown
@@ -120,7 +120,7 @@ export class ServiceContainer {
120
120
  private _disposalPromise: Promise<void> | null = null;
121
121
  public isReady: boolean = false;
122
122
  public cwd: string = process.cwd();
123
- public config: any = null;
123
+ public config: unknown = null;
124
124
  private readonly defaultOptions: Required<ServiceContainerOptions>;
125
125
 
126
126
  constructor(options: ServiceContainerOptions = {}) {
@@ -225,7 +225,7 @@ export class ServiceContainer {
225
225
  /**
226
226
  * Get a service instance, initializing it if necessary
227
227
  */
228
- async get<T extends IService>(name: string, ctx?: any): Promise<T> {
228
+ async get<T extends IService>(name: string, ctx?: unknown): Promise<T> {
229
229
  if (this.isDisposing) {
230
230
  throw new Error(`Cannot get service '${name}' during container disposal`);
231
231
  }
@@ -419,7 +419,10 @@ export class ServiceContainer {
419
419
  }
420
420
 
421
421
  if (registration.instance && registration.instance.dispose) {
422
- await registration.instance.dispose().catch((err: unknown) => {
422
+ // dispose() may return a bare void (non-async implementation) — normalize to a
423
+ // promise so the catch handler always applies.
424
+ const disposal = Promise.resolve(registration.instance.dispose());
425
+ await disposal.catch((err: unknown) => {
423
426
  logger.warn(`[ServiceContainer] Error disposing service '${name}':`, err);
424
427
  });
425
428
  }
@@ -462,7 +465,10 @@ export class ServiceContainer {
462
465
 
463
466
  // Dispose old instance if present
464
467
  if (registration.instance && registration.instance.dispose) {
465
- await registration.instance.dispose().catch((err: unknown) => {
468
+ // dispose() may return a bare void (non-async implementation) — normalize to a
469
+ // promise so the catch handler always applies.
470
+ const disposal = Promise.resolve(registration.instance.dispose());
471
+ await disposal.catch((err: unknown) => {
466
472
  logger.warn(`[ServiceContainer] Error disposing old service '${name}':`, err);
467
473
  });
468
474
  }
@@ -731,7 +737,7 @@ export class ServiceContainer {
731
737
  */
732
738
  private async _initializeService<T extends IService>(
733
739
  registration: ServiceRegistration<T>,
734
- ctx?: any
740
+ ctx?: unknown
735
741
  ): Promise<T> {
736
742
  let instance: T | null = null;
737
743
  try {
@@ -831,7 +837,7 @@ export function replaceService<T extends IService>(
831
837
  /**
832
838
  * Convenience function to get a service
833
839
  */
834
- export function getService<T extends IService>(name: string, ctx?: any, container: ServiceContainer = globalServiceContainer): Promise<T> {
840
+ export function getService<T extends IService>(name: string, ctx?: unknown, container: ServiceContainer = globalServiceContainer): Promise<T> {
835
841
  return container.get<T>(name, ctx);
836
842
  }
837
843
 
@@ -866,9 +872,10 @@ export function isServiceInitialized(name: string, container: ServiceContainer =
866
872
  /**
867
873
  * Helper to extract a service container from a context object, if present.
868
874
  */
869
- export function tryGetServiceContainerFromCtx(ctx: any): ServiceContainer {
870
- if (ctx?.container && typeof ctx.container.get === 'function' && typeof ctx.container.register === 'function') {
871
- return ctx.container;
875
+ export function tryGetServiceContainerFromCtx(ctx: unknown): ServiceContainer {
876
+ const container = (ctx as { container?: { get?: unknown; register?: unknown } } | undefined)?.container;
877
+ if (container && typeof container.get === 'function' && typeof container.register === 'function') {
878
+ return container as unknown as ServiceContainer;
872
879
  }
873
880
  return globalServiceContainer;
874
881
  }
@@ -27,7 +27,7 @@ import {
27
27
  * Standalone BrowserCapability check, exported so tests can call it directly
28
28
  * without going through the full registry.
29
29
  */
30
- 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> }> {
31
31
  const mockMode = process.env['PI_RESEARCH_MOCK_SEARCH'] === 'true' &&
32
32
  process.env['PI_RESEARCH_MOCK_SCRAPE'] === 'true';
33
33
  if (isBrowserAvailable() || mockMode) {
@@ -401,7 +401,7 @@ export function isBusyPoolHealthFailure(
401
401
  /**
402
402
  * Perform a full system health check
403
403
  */
404
- export async function runHealthCheck(options?: { force?: boolean; ctx?: any }) {
404
+ export async function runHealthCheck(options?: { force?: boolean; ctx?: unknown }) {
405
405
  const container = tryGetServiceContainerFromCtx(options?.ctx);
406
406
 
407
407
  let registry: IHealthRegistryService;
@@ -417,8 +417,9 @@ export async function runHealthCheck(options?: { force?: boolean; ctx?: any }) {
417
417
  success: result.status !== 'unhealthy',
418
418
  status: result.status,
419
419
  components: result.components,
420
- error: result.status === 'unhealthy'
421
- ? 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
422
423
  : undefined
423
424
  };
424
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`));