@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
@@ -1,94 +1,15 @@
1
1
  /**
2
2
  * State Types
3
3
  *
4
- * Shared types for state management.
5
- * Extracted to separate file to avoid circular dependencies.
6
- */
7
-
8
- import { Type, type Static } from 'typebox';
9
-
10
- /**
11
- * Current on-disk state schema version. Bump this (and add a migration step in
12
- * state-migration.ts) whenever the persisted shape changes incompatibly. The
13
- * schema's `version` literal is pinned to this value so a reader only accepts a
14
- * state it actually understands; older/newer files are routed through migration
15
- * or future-version quarantine rather than being silently overwritten.
16
- */
17
- export const CURRENT_STATE_VERSION = 1 as const;
18
-
19
- /**
20
- * State metrics interface
21
- */
22
- export interface StateMetrics {
23
- totalSessions: number;
24
- activeSessions: number;
25
- oldestSession: number | null;
26
- newestSession: number | null;
27
- containerUptime: number | null;
28
- lastHeartbeatAge: number | null;
29
- }
30
-
31
- /**
32
- * Session information interface
33
- */
34
- export const SessionInfoSchema = Type.Object({
35
- pid: Type.Number(),
36
- startTime: Type.Optional(Type.Number()),
37
- lastSeen: Type.Number(),
38
- connectedAt: Type.Number(),
39
- });
40
-
41
- /**
42
- * Main state structure interface
43
- */
44
- export const SingletonStateSchema = Type.Object({
45
- version: Type.Literal(CURRENT_STATE_VERSION),
46
- containerId: Type.String(),
47
- containerName: Type.String(),
48
- port: Type.Number(),
49
- sessions: Type.Record(Type.String(), SessionInfoSchema),
50
- lastUpdated: Type.Number(),
51
- browserServer: Type.Optional(Type.Object({
52
- port: Type.Number(),
53
- pid: Type.Number(),
54
- startTime: Type.Optional(Type.Number()),
55
- schedulerId: Type.Optional(Type.String()),
56
- authSecret: Type.Optional(Type.String()),
57
- })),
58
- schedulerVersion: Type.Optional(Type.String()),
59
- gpuOwner: Type.Optional(Type.Object({
60
- pid: Type.Number(),
61
- startTime: Type.Optional(Type.Number()),
62
- startedAt: Type.Number(),
63
- sessionId: Type.Optional(Type.String()),
64
- // Re-entrant hold count for the owning process. The lock is shared by N
65
- // concurrent in-process embedding calls (activeEmbeddings is designed > 1);
66
- // each re-entrant acquire increments and each release decrements, so the
67
- // cross-process owner record is only cleared when the last in-process hold
68
- // is released. Absent on state written before refcounting — treated as 1.
69
- holds: Type.Optional(Type.Number()),
70
- })),
71
- embeddingServer: Type.Optional(Type.Object({
72
- port: Type.Number(),
73
- pid: Type.Number(),
74
- startTime: Type.Optional(Type.Number()),
75
- serverId: Type.String(),
76
- // EMBEDDING_MODEL the leader serves. A follower configured with a DIFFERENT
77
- // model must not adopt this leader (same-dimension models would silently
78
- // cross-embed and corrupt the vector space) — it falls back to a local
79
- // in-process embedder instead. Optional for entries written by older
80
- // processes, which are tolerated as matching.
81
- model: Type.Optional(Type.String()),
82
- // Shared secret a follower must present on every embed request. Mirrors
83
- // browserServer.authSecret: the server listens on loopback, but loopback is
84
- // not an authorization boundary — any local process could otherwise enqueue
85
- // embedding work, and because the serial queue steps the leader down when
86
- // poisoned, sustained abuse denies the knowledge store rather than merely
87
- // burning GPU. Optional so an entry written by an older leader still parses;
88
- // a client that finds none simply sends no header, and such a leader does not
89
- // check one either.
90
- authSecret: Type.Optional(Type.String()),
91
- })),
92
- });
93
-
94
- export type SingletonState = Static<typeof SingletonStateSchema>;
4
+ * Re-export shim. The types moved to the foundation `src/types/state-types.ts`
5
+ * (see that file) so that `core/interfaces/` can name the state shape without
6
+ * depending on `infrastructure/`. This file is kept so the many `infrastructure/`
7
+ * import sites (`../types/state-types.ts`) continue to resolve unchanged.
8
+ */
9
+
10
+ export {
11
+ CURRENT_STATE_VERSION,
12
+ SessionInfoSchema,
13
+ SingletonStateSchema,
14
+ } from '../../types/state-types.ts';
15
+ export type { StateMetrics, SingletonState } from '../../types/state-types.ts';
@@ -4,7 +4,7 @@
4
4
  * Handles initialization and warmup logic for the embedder
5
5
  */
6
6
 
7
- import type { FeatureExtractionPipeline } from '@huggingface/transformers';
7
+ import type { FeatureExtractionPipeline, Tensor } from '@huggingface/transformers';
8
8
  import { logger } from '../logger.ts';
9
9
  import type { IStateManager } from '../core/service-interfaces.ts';
10
10
  import { DisposablePipeline } from '../core/interfaces/knowledge-interfaces.ts';
@@ -71,7 +71,7 @@ export async function warmupPipeline(
71
71
  pipeline: FeatureExtractionPipeline,
72
72
  poolingMode: 'mean' | 'cls' | 'last_token',
73
73
  useCache: boolean
74
- ): Promise<{ dummy: any; success: boolean; error?: Error }> {
74
+ ): Promise<{ dummy: Tensor | null; success: boolean; error?: Error }> {
75
75
  try {
76
76
  // Inside runCapturingStderr for the same reason the load above is, and for one
77
77
  // more: warmup is the FIRST inference, so it is where a GPU that cannot serve the
@@ -91,7 +91,7 @@ export async function warmupPipeline(
91
91
  const dummy = await logger.runCapturingStderr(async () =>
92
92
  withTimeout(
93
93
  pipeline('warmup', {
94
- pooling: poolingMode as any,
94
+ pooling: poolingMode,
95
95
  normalize: false,
96
96
  ...(useCache === false ? { use_cache: false } : {}),
97
97
  }),
@@ -416,7 +416,7 @@ export async function handleWebGPULoadError(
416
416
  model: string,
417
417
  initializationTimeoutMs: number,
418
418
  useCache: boolean
419
- ): Promise<{ success: boolean; pipeline?: FeatureExtractionPipeline; error?: Error; dummy?: any }> {
419
+ ): Promise<{ success: boolean; pipeline?: FeatureExtractionPipeline; error?: Error; dummy?: Tensor | null }> {
420
420
  const errorMsg = loadErr instanceof Error ? loadErr.message : String(loadErr);
421
421
  const isValidationError = errorMsg.toLowerCase().includes('validation');
422
422
 
@@ -431,7 +431,7 @@ export async function handleWebGPULoadError(
431
431
 
432
432
  // Clean up
433
433
  if (pipeline) {
434
- try { if (typeof (pipeline as any).dispose === 'function') await (pipeline as DisposablePipeline).dispose(); } catch (err) { logger.warn('[embedder] Error disposing pipeline:', err); }
434
+ try { const disposable = pipeline as FeatureExtractionPipeline & DisposablePipeline; if (typeof disposable.dispose === 'function') await disposable.dispose(); } catch (err) { logger.warn('[embedder] Error disposing pipeline:', err); }
435
435
  }
436
436
  await releaseGpuLock(stateManager, gpuLockHeld);
437
437
 
@@ -459,7 +459,7 @@ export async function handleWebGPUWarmupError(
459
459
  initializationTimeoutMs: number,
460
460
  useCache: boolean,
461
461
  poolingMode: 'mean' | 'cls' | 'last_token' = 'mean'
462
- ): Promise<{ success: boolean; pipeline?: FeatureExtractionPipeline; error?: Error; dummy?: any }> {
462
+ ): Promise<{ success: boolean; pipeline?: FeatureExtractionPipeline; error?: Error; dummy?: Tensor | null }> {
463
463
  markWebGpuFallback();
464
464
 
465
465
  // Deliberately does NOT try to name the cause from this error's text. The split it
@@ -482,7 +482,7 @@ export async function handleWebGPUWarmupError(
482
482
 
483
483
  // Clean up
484
484
  if (pipeline) {
485
- try { if (typeof (pipeline as any).dispose === 'function') await (pipeline as DisposablePipeline).dispose(); } catch (err) { logger.warn('[embedder] Error disposing pipeline:', err); }
485
+ try { const disposable = pipeline as FeatureExtractionPipeline & DisposablePipeline; if (typeof disposable.dispose === 'function') await disposable.dispose(); } catch (err) { logger.warn('[embedder] Error disposing pipeline:', err); }
486
486
  }
487
487
  await releaseGpuLock(stateManager, gpuLockHeld);
488
488
 
@@ -496,7 +496,7 @@ export async function handleWebGPUWarmupError(
496
496
  if (!success || cpuWarmupErr) {
497
497
  logger.error('[embedder] CPU fallback pipeline warmup failed:', cpuWarmupErr);
498
498
  if (cpuPipeline) {
499
- try { if (typeof (cpuPipeline as any).dispose === 'function') await (cpuPipeline as DisposablePipeline).dispose(); } catch (err) { logger.warn('[embedder] Error disposing fallback CPU pipeline:', err); }
499
+ try { const cpuDisposable = cpuPipeline as FeatureExtractionPipeline & DisposablePipeline; if (typeof cpuDisposable.dispose === 'function') await cpuDisposable.dispose(); } catch (err) { logger.warn('[embedder] Error disposing fallback CPU pipeline:', err); }
500
500
  }
501
501
  const error = new Error(`WebGPU initialization failed and CPU fallback warmup also failed: ${cpuWarmupErr?.message || 'Unknown error'}`, { cause: cpuWarmupErr });
502
502
  return { success: false, error };
@@ -271,14 +271,15 @@ export async function initializeDawnWebGPU(): Promise<boolean> {
271
271
  const adapter = await logger.runCapturingStderr(async () => {
272
272
  // webgpu is an optional dependency (types resolve because it is installed for dev)
273
273
  const { create, globals } = await import('webgpu');
274
+ const gpu = create([]);
274
275
  Object.assign(globalThis, globals);
275
276
  // Use Object.defineProperty — Node.js defines navigator as a configurable getter
276
277
  Object.defineProperty(globalThis, 'navigator', {
277
- value: { gpu: create([]) },
278
+ value: { gpu },
278
279
  writable: true,
279
280
  configurable: true,
280
281
  });
281
- return await (globalThis as any).navigator.gpu.requestAdapter({ powerPreference: 'high-performance' });
282
+ return await gpu.requestAdapter({ powerPreference: 'high-performance' });
282
283
  });
283
284
 
284
285
  if (!adapter) {
@@ -292,7 +293,10 @@ export async function initializeDawnWebGPU(): Promise<boolean> {
292
293
  .join(' ')
293
294
  .toLowerCase();
294
295
 
295
- if (adapter.isFallbackAdapter === true || SOFTWARE_ADAPTER_PATTERNS.some((p) => haystack.includes(p))) {
296
+ // `isFallbackAdapter` lives on `info` (GPUAdapterInfo), not on the adapter
297
+ // itself — the old direct read was always undefined, so a software adapter
298
+ // was only caught by the string patterns below.
299
+ if (adapter.info?.isFallbackAdapter === true || SOFTWARE_ADAPTER_PATTERNS.some((p) => haystack.includes(p))) {
296
300
  logger.warn(
297
301
  `[embedder] WebGPU adapter is software/paravirtual (${haystack || 'fallback'}) — Dawn would crash on compute; using CPU.`,
298
302
  );
@@ -6,7 +6,7 @@
6
6
  * to release GPU memory when not in use.
7
7
  */
8
8
 
9
- import type { FeatureExtractionPipeline } from '@huggingface/transformers';
9
+ import type { FeatureExtractionPipeline, Tensor } from '@huggingface/transformers';
10
10
 
11
11
  import { logger } from '../logger.ts';
12
12
  import { safeUnref } from '../utils/safe-unref.ts';
@@ -323,7 +323,7 @@ export class Embedder {
323
323
  }
324
324
 
325
325
  // Warmup
326
- let dummy: any;
326
+ let dummy: Tensor | null;
327
327
  try {
328
328
  const warmupResult = await warmupPipeline(this.pipeline!, this.poolingMode, this.useCache);
329
329
  if (!warmupResult.success) {
@@ -348,12 +348,15 @@ export class Embedder {
348
348
  this.pipeline = result.pipeline ?? null;
349
349
  this.device = 'cpu';
350
350
  this.gpuLockHeld = false;
351
- dummy = result.dummy;
351
+ dummy = result.dummy ?? null;
352
352
  } else {
353
353
  throw warmupErr;
354
354
  }
355
355
  }
356
-
356
+
357
+ if (dummy === null) {
358
+ throw new Error('[embedder] warmup completed without a dummy tensor; dimension cannot be determined');
359
+ }
357
360
  this.dimension = dummy.dims[dummy.dims.length - 1] ?? null;
358
361
 
359
362
  await releaseGpuLock(this.stateManager, this.gpuLockHeld);
@@ -364,7 +367,7 @@ export class Embedder {
364
367
  await releaseGpuLock(this.stateManager, this.gpuLockHeld);
365
368
  this.gpuLockHeld = false;
366
369
  if (this.pipeline) {
367
- try { if (typeof (this.pipeline as any).dispose === 'function') await (this.pipeline as DisposablePipeline).dispose(); } catch (err) { logger.warn('[embedder] Error disposing pipeline:', err); }
370
+ try { const disposable = this.pipeline as FeatureExtractionPipeline & DisposablePipeline; if (typeof disposable.dispose === 'function') await disposable.dispose(); } catch (err) { logger.warn('[embedder] Error disposing pipeline:', err); }
368
371
  this.pipeline = null;
369
372
  }
370
373
  logger.error(`[embedder] Failed to initialize:`, err);
@@ -431,7 +434,7 @@ export class Embedder {
431
434
  * Run the pipeline over an input, tracked in activeInferences so recoverToCpu's
432
435
  * drain loop waits only on calls genuinely inside the model.
433
436
  */
434
- private async runInference(input: string | string[]): Promise<any> {
437
+ private async runInference(input: string | string[]): Promise<Tensor> {
435
438
  // A disposal/recovery that raced this call may have nulled the pipeline out
436
439
  // from under us. Calling through null raises a bare TypeError that nothing
437
440
  // classifies (the writer queue drops the document as a generic ingest_error);
@@ -527,7 +530,7 @@ export class Embedder {
527
530
  this.truncateText(this.documentPrefix ? this.documentPrefix + t : t)
528
531
  );
529
532
 
530
- let output: any;
533
+ let output: Tensor;
531
534
  try {
532
535
  output = await this.runInference(batch);
533
536
  } catch (err) {
@@ -624,7 +627,7 @@ export class Embedder {
624
627
  }
625
628
 
626
629
  if (this.pipeline) {
627
- try { if (typeof (this.pipeline as any).dispose === 'function') await (this.pipeline as DisposablePipeline).dispose(); } catch (err) { logger.warn('[embedder] Error disposing pipeline:', err); }
630
+ try { const disposable = this.pipeline as FeatureExtractionPipeline & DisposablePipeline; if (typeof disposable.dispose === 'function') await disposable.dispose(); } catch (err) { logger.warn('[embedder] Error disposing pipeline:', err); }
628
631
  this.pipeline = null;
629
632
  }
630
633
 
@@ -738,8 +741,9 @@ export class Embedder {
738
741
  this.pipeline = null;
739
742
  } else {
740
743
  try {
741
- if (typeof (this.pipeline as any).dispose === 'function') {
742
- await (this.pipeline as DisposablePipeline).dispose();
744
+ const disposable = this.pipeline as FeatureExtractionPipeline & DisposablePipeline;
745
+ if (typeof disposable.dispose === 'function') {
746
+ await disposable.dispose();
743
747
  }
744
748
  } catch (err) {
745
749
  logger.warn('[embedder] Error during pipeline dispose:', err);
@@ -37,8 +37,8 @@ export async function initializeONNXEnv(): Promise<void> {
37
37
  envObj.backends.onnx.logLevel = 'error';
38
38
  }
39
39
  // Fallback for older transformers.js versions if any
40
- if ((envObj as any).onnx) {
41
- (envObj as any).onnx.logLevel = 'error';
40
+ if (envObj.onnx) {
41
+ envObj.onnx.logLevel = 'error';
42
42
  }
43
43
  } catch (e) {
44
44
  logger.debug('[embedder] Failed to set ONNX logLevel:', e);
@@ -111,7 +111,7 @@ export class KnowledgeStore implements IKnowledgeStore {
111
111
  // rather than as "no migration in flight").
112
112
  private manifestLoadState: 'absent' | 'loaded' | 'corrupt' = 'absent';
113
113
  private isClosing = false;
114
- private activeWrites = new Set<Promise<any>>();
114
+ private activeWrites = new Set<Promise<unknown>>();
115
115
  // Last recorded model/schema migration (persisted in the store manifest).
116
116
  // Compared against the incoming migration target to detect alternating-model
117
117
  // thrash against a shared dbDir (see the alternation warn in openInternal).
@@ -328,10 +328,10 @@ export class KnowledgeStore implements IKnowledgeStore {
328
328
  let storedModel = schema.metadata.get('embedding_model');
329
329
  let storedVersion = schema.metadata.get('schema_version');
330
330
 
331
- if (typeof storedModel === 'object' && storedModel !== null && 'byteLength' in (storedModel as any)) {
331
+ if (typeof storedModel === 'object' && storedModel !== null && 'byteLength' in (storedModel as object)) {
332
332
  storedModel = new TextDecoder().decode(storedModel as unknown as Uint8Array);
333
333
  }
334
- if (typeof storedVersion === 'object' && storedVersion !== null && 'byteLength' in (storedVersion as any)) {
334
+ if (typeof storedVersion === 'object' && storedVersion !== null && 'byteLength' in (storedVersion as object)) {
335
335
  storedVersion = new TextDecoder().decode(storedVersion as unknown as Uint8Array);
336
336
  }
337
337
 
@@ -347,9 +347,10 @@ export class KnowledgeStore implements IKnowledgeStore {
347
347
  // below before creating any table.
348
348
  if (!isModelMismatch) {
349
349
  const vectorField = schema.fields.find(f => f.name === 'vector');
350
- if (vectorField && (vectorField.type as any).constructor.name === 'FixedSizeList') {
351
- const dim = (vectorField.type as any).listSize;
352
- if (this.embedder.getDimension() === null) {
350
+ const vectorType = vectorField?.type as { constructor?: { name?: string }; listSize?: number } | undefined;
351
+ if (vectorField && vectorType?.constructor?.name === 'FixedSizeList') {
352
+ const dim = vectorType.listSize;
353
+ if (typeof dim === 'number' && this.embedder.getDimension() === null) {
353
354
  this.embedder.setDimension(dim);
354
355
  logger.debug(`[store] Extracted dimension ${dim} from existing table schema`);
355
356
  }
@@ -577,7 +578,7 @@ export class KnowledgeStore implements IKnowledgeStore {
577
578
  const batchRows = await this.table.query().limit(batchSize).offset(i).toArray();
578
579
 
579
580
  const batchDocs = batchRows.flatMap(row => {
580
- let metadata: Record<string, any> = {};
581
+ let metadata: Record<string, unknown> = {};
581
582
  try { metadata = JSON.parse(row.metadata as string); } catch {
582
583
  logger.warn('[store] Skipping row with corrupted metadata during re-embed migration');
583
584
  }
@@ -1153,7 +1154,7 @@ export class KnowledgeStore implements IKnowledgeStore {
1153
1154
  // 2. Format for web
1154
1155
  // We use a compact format to keep the JSON size manageable
1155
1156
  const exportData = results.map(r => {
1156
- let metadata: Record<string, any> = {};
1157
+ let metadata: Record<string, unknown> = {};
1157
1158
  try {
1158
1159
  metadata = JSON.parse(r.metadata as string);
1159
1160
  } catch {
@@ -1195,7 +1196,7 @@ export class KnowledgeStore implements IKnowledgeStore {
1195
1196
  return this.findDocumentsByUrl(url);
1196
1197
  }
1197
1198
 
1198
- async rebuildDocument(url: string): Promise<{ text: string; description: string | null; metadata: Record<string, any>; ageDays?: number } | null> {
1199
+ async rebuildDocument(url: string): Promise<{ text: string; description: string | null; metadata: Record<string, unknown>; ageDays?: number } | null> {
1199
1200
  // Runs mid-research (scrape cache lookup); coordinate with close() so a teardown
1200
1201
  // can't free the native handle while this query is in flight.
1201
1202
  return this.trackOperation('rebuildDocument', null, async () => {
@@ -1245,7 +1246,7 @@ export class KnowledgeStore implements IKnowledgeStore {
1245
1246
  // LanceDB's fragment-scan order is not insertion order, so without this a
1246
1247
  // non-zero chunk sorting first would silently return just that one
1247
1248
  // chunk's own fragment in place of the full document.
1248
- const chunkIndexOf = (row: any): number => {
1249
+ const chunkIndexOf = (row: { metadata?: unknown; timestamp?: unknown }): number => {
1249
1250
  try {
1250
1251
  const parsed = JSON.parse(row.metadata as string);
1251
1252
  return typeof parsed.chunkIndex === 'number' ? parsed.chunkIndex : 0;
@@ -1253,7 +1254,7 @@ export class KnowledgeStore implements IKnowledgeStore {
1253
1254
  return 0;
1254
1255
  }
1255
1256
  };
1256
- results.sort((a: any, b: any) => {
1257
+ results.sort((a: { metadata?: unknown; timestamp?: unknown }, b: { metadata?: unknown; timestamp?: unknown }) => {
1257
1258
  const tsDiff = Number(b.timestamp) - Number(a.timestamp);
1258
1259
  return tsDiff !== 0 ? tsDiff : chunkIndexOf(a) - chunkIndexOf(b);
1259
1260
  });
package/src/logger.ts CHANGED
@@ -411,7 +411,7 @@ export function getLogger(sessionId?: string): Logger {
411
411
  }
412
412
 
413
413
  export function setLogger(loggerInstance: Logger, sessionId?: string): void {
414
- if (loggerInstance && !(loggerInstance as any)[LOGGER_BRAND]) {
414
+ if (loggerInstance && !loggerInstance[LOGGER_BRAND]) {
415
415
  throw new Error('setLogger must be called with a Logger instance, not the wrapper.');
416
416
  }
417
417
  if (sessionId) {
@@ -5,8 +5,9 @@
5
5
  */
6
6
 
7
7
  import type { ExtensionContext, AgentToolResult } from '@earendil-works/pi-coding-agent';
8
- import { type Model } from '@earendil-works/pi-ai';
8
+ import { type Api, type Model } from '@earendil-works/pi-ai';
9
9
  import { logger } from '../logger.ts';
10
+ import { describeProxyIfBroken } from '../infrastructure/browser/proxy-health.ts';
10
11
  import { metrics } from '../utils/metrics.ts';
11
12
  import { getSteeringMessages, consumeQueuedMessages, getActiveSteeringMessages, getFailedResearchers, getResearcherFailureReasons, shouldStopResearch, createResearchStopError, hasOnlyCapacityFailures } from './session-state.ts';
12
13
  import { MAX_EXTRA_ROUNDS_WITH_STEERING, MIN_SYNTHESIS_PROSE_CHARS, SYNTHESIS_FALLBACK_NOTICE, resolveExcludedTools } from '../constants.ts';
@@ -33,13 +34,13 @@ import type { PlanningService } from '../core/planning-service.ts';
33
34
 
34
35
  export interface DeepResearchOrchestratorOptions {
35
36
  ctx: ExtensionContext;
36
- model: Model<any>;
37
+ model: Model<Api>;
37
38
  query: string;
38
39
  complexity: 1 | 2 | 3;
39
40
  sessionId: string;
40
41
  researchId: string;
41
42
  observer?: ResearchObserver | HeadlessObserverOptions;
42
- onUpdate?: (update: AgentToolResult<any>) => void;
43
+ onUpdate?: (update: AgentToolResult<unknown>) => void;
43
44
  config?: Config;
44
45
  orchestrationService?: IResearchOrchestration;
45
46
  excludeTools?: string[];
@@ -116,9 +117,9 @@ export class DeepResearchOrchestrator {
116
117
  // PI_RESEARCH_COORDINATOR_MODEL overrides that first call: `research` (or an
117
118
  // explicit provider/id) when the chat model is a poor or single-seat planner.
118
119
  // See src/core/llm/coordinator-model.ts for the measured case.
119
- const initialCoordinatorModel = resolveCoordinatorModel<Model<any>>({
120
+ const initialCoordinatorModel = resolveCoordinatorModel<Model<Api>>({
120
121
  setting: this.config.COORDINATOR_MODEL,
121
- hostModel: ctx.model as Model<any> | undefined,
122
+ hostModel: ctx.model,
122
123
  researchModel: model,
123
124
  // STRICT lookup (never resolveResearchModel): that resolver always returns a
124
125
  // model — it falls back through RESEARCH_MODEL to "first available" — so a typo
@@ -126,8 +127,8 @@ export class DeepResearchOrchestrator {
126
127
  findByReference: (reference) => {
127
128
  try {
128
129
  const registry = ctx.modelRegistry;
129
- const all = (registry?.getAll?.() ?? []) as Model<any>[];
130
- const available = (registry?.getAvailable?.() ?? []) as Model<any>[];
130
+ const all = (registry?.getAll?.() ?? []) as Model<Api>[];
131
+ const available = (registry?.getAvailable?.() ?? []) as Model<Api>[];
131
132
  return findModelByReference(reference, all, available);
132
133
  } catch {
133
134
  return undefined;
@@ -150,6 +151,26 @@ export class DeepResearchOrchestrator {
150
151
  // which already passes ctx).
151
152
  await orchestrationService.cleanupResearchServices(undefined, researchId, ctx, this.config);
152
153
 
154
+ // A configured-but-broken SOCKS proxy fails EVERY browser request. Only the
155
+ // UI health gate and the quick orchestrator run a pre-flight check; a deep
156
+ // run has no such gate, so without this the whole search burst is spent
157
+ // first (36 queries, ~7 minutes on 2026-10-30) and then dies with the
158
+ // generic "Search completely failed". One probe costs seconds.
159
+ //
160
+ // Bounded generously (3s connect + 3-4s data, then a neutral-host check): the
161
+ // point is to catch a dead or one-way tunnel, not to convict a proxy that is
162
+ // merely slow on a loaded box.
163
+ // The run signal is passed through so Esc during a dead proxy's probe sequence
164
+ // cancels immediately instead of waiting out both attempts.
165
+ const proxyDiagnosis = await describeProxyIfBroken(signal);
166
+ if (signal?.aborted) return '';
167
+ if (proxyDiagnosis) {
168
+ throw new Error(
169
+ `Research cannot start: ${proxyDiagnosis} ` +
170
+ 'Repair or remove ~/.pi/research/proxy.json (docs/TROUBLESHOOTING.md), then rerun.',
171
+ );
172
+ }
173
+
153
174
  logger.log(`[DeepOrchestrator] Starting multi-round research (complexity ${complexity}) for: "${query}" (Run: ${researchId})`);
154
175
  metrics.increment('research_sessions_total', 1, { mode: 'deep', complexity: String(complexity) });
155
176
 
@@ -576,6 +597,14 @@ export class DeepResearchOrchestrator {
576
597
  const hasReports = synthesisCheckService.hasReports(researchId);
577
598
  const failedIds = getFailedResearchers(this.options.sessionId, researchId);
578
599
  if (!hasReports && failedIds.length > 0) {
600
+ // Every recorded failure was a provider-capacity failure (a rate limit or an
601
+ // exhausted in-flight budget): the topic is researchable, the upstream was not
602
+ // serving. Use the capacity-specific stop message, which tells the user to wait
603
+ // and retry rather than to change models — the generic "no source material" text
604
+ // would mis-attribute a supply outage to the topic or the model.
605
+ if (hasOnlyCapacityFailures(this.options.sessionId, researchId)) {
606
+ throw createResearchStopError(this.options.sessionId, researchId);
607
+ }
579
608
  const reasons = getResearcherFailureReasons(this.options.sessionId, researchId);
580
609
  const causes = failedIds
581
610
  .map((id) => `researcher ${id}: ${reasons[id] ?? 'no usable report'}`)
@@ -111,7 +111,7 @@ export function isHeadlessObserverBag(observer: unknown): boolean {
111
111
  export class HeadlessObserver implements ResearchObserver {
112
112
  constructor(private options: HeadlessObserverOptions = {}) {}
113
113
 
114
- private emit(event: string, data?: any) {
114
+ private emit(event: string, data?: unknown) {
115
115
  if (this.options.enableLogging) {
116
116
  logger.debug(`[HeadlessObserver] ${event}`, data);
117
117
  }
@@ -3,7 +3,7 @@
3
3
  */
4
4
 
5
5
  import type { ExtensionContext } from '@earendil-works/pi-coding-agent';
6
- import type { Model } from '@earendil-works/pi-ai';
6
+ import type { Api, Model } from '@earendil-works/pi-ai';
7
7
  import type { ResearcherConfig } from '../core/service-interfaces.ts';
8
8
  import type { IPlanningService } from '../core/interfaces/planning-interfaces.ts';
9
9
  import type { StoreUrlEntry } from '../core/interfaces/knowledge-interfaces.ts';
@@ -24,7 +24,7 @@ export interface RunResearcherOptions {
24
24
  query: string;
25
25
  complexity: 1 | 2 | 3;
26
26
  ctx: ExtensionContext;
27
- model: Model<any>;
27
+ model: Model<Api>;
28
28
  researchConfig: Config;
29
29
  planningService: IPlanningService;
30
30
  observer?: ResearchObserver;
@@ -10,7 +10,7 @@ import {
10
10
  type AgentSessionEvent,
11
11
  type AgentToolResult,
12
12
  } from '@earendil-works/pi-coding-agent';
13
- import { type Model } from '@earendil-works/pi-ai';
13
+ import { type Api, type Model } from '@earendil-works/pi-ai';
14
14
  import { injectCurrentDate } from '../core/llm/inject-date.ts';
15
15
  import { loadPrompt } from '../core/llm/prompts.ts';
16
16
  import { recordLlmUsage } from '../utils/llm-usage.ts';
@@ -35,12 +35,12 @@ import type { SystemResearchState } from './deep-research-types.ts';
35
35
 
36
36
  export interface QuickResearchOrchestratorOptions {
37
37
  ctx: ExtensionContext;
38
- model: Model<any>;
38
+ model: Model<Api>;
39
39
  query: string;
40
40
  sessionId: string;
41
41
  researchId: string;
42
42
  observer?: ResearchObserver | HeadlessObserverOptions;
43
- onUpdate?: (update: AgentToolResult<any>) => void;
43
+ onUpdate?: (update: AgentToolResult<unknown>) => void;
44
44
  config?: Config;
45
45
  excludeTools?: string[];
46
46
  initialLinks?: string[];
@@ -282,7 +282,7 @@ export class QuickResearchOrchestrator {
282
282
  const msg = event.message as unknown as ResearchMessage;
283
283
  if (msg?.['role'] !== 'assistant') return;
284
284
 
285
- const rawUsage = msg['usage'] as any;
285
+ const rawUsage = msg['usage'];
286
286
  if (rawUsage) {
287
287
  const { tokens, cost } = recordLlmUsage(resolvedModel, rawUsage, {
288
288
  component: 'quick_researcher',
@@ -10,7 +10,7 @@
10
10
  * - Knowledge store integration for link descriptions
11
11
  */
12
12
 
13
- import type { Model } from '@earendil-works/pi-ai';
13
+ import type { Api, Model } from '@earendil-works/pi-ai';
14
14
  import { resolveResearchModel } from '../core/llm/research-model-resolver.ts';
15
15
  import type { QueryResultWithError } from '../web-research/types.ts';
16
16
  import type { RunResearchersOptions } from './orchestration-types.ts';
@@ -64,21 +64,21 @@ export class ResearchOrchestrationService implements IResearchOrchestration {
64
64
  /**
65
65
  * Resolve the model for research based on options and config.
66
66
  */
67
- async resolveResearchModel(options: ResearchOptions): Promise<Model<any>> {
67
+ async resolveResearchModel(options: ResearchOptions): Promise<Model<Api>> {
68
68
  const { ctx, model, config } = options;
69
69
  // If a fully-resolved model was already provided (carries both provider and
70
70
  // id), use it verbatim. Re-resolving from its id alone can land on a
71
71
  // different provider's entry that happens to share the same id — e.g. the
72
72
  // host's authed `glm-coding/glm-4.7` vs pi's built-in unauthed `zai/glm-4.7`
73
73
  // — silently dropping the provider that actually has an API key.
74
- if (model && (model as any).provider && (model as any).id) {
75
- return model as Model<any>;
74
+ if (model && model.provider && model.id) {
75
+ return model;
76
76
  }
77
77
  return resolveResearchModel({
78
78
  modelRegistry: ctx.modelRegistry,
79
79
  config: config || getConfig(ctx.cwd),
80
- modelId: (model as any)?.id,
81
- hostModel: ctx.model as Model<any>,
80
+ modelId: model?.id,
81
+ hostModel: ctx.model,
82
82
  cwd: ctx.cwd,
83
83
  });
84
84
  }
@@ -249,7 +249,7 @@ export class ResearchOrchestrationService implements IResearchOrchestration {
249
249
  * durability lives in the LanceDB commits already made, and the next run's
250
250
  * cleanup performs the same rebuild).
251
251
  */
252
- async cleanupResearchServices(sessionId?: string, researchId?: string, ctx?: any, config?: Config, opts?: { skipStoreMaintenance?: boolean }): Promise<void> {
252
+ async cleanupResearchServices(sessionId?: string, researchId?: string, ctx?: unknown, config?: Config, opts?: { skipStoreMaintenance?: boolean }): Promise<void> {
253
253
  const targetId = researchId || sessionId;
254
254
  const container = tryGetServiceContainerFromCtx(ctx);
255
255
  // Use the run's RESOLVED config when the caller has it — an SDK caller's
@@ -257,7 +257,7 @@ export class ResearchOrchestrationService implements IResearchOrchestration {
257
257
  // vector stack) must govern this post-run FTS/optimize gate too. Falling back to a
258
258
  // fresh getConfig(cwd) would ignore that override and either load the native stack on
259
259
  // a platform that lacks it, or skip the rebuild a store-enabled run legitimately needs.
260
- const resolvedConfig = config ?? getConfig(ctx?.cwd);
260
+ const resolvedConfig = config ?? getConfig((ctx as { cwd?: string } | undefined)?.cwd);
261
261
 
262
262
  // Cleanup session service
263
263
  try {
@@ -324,7 +324,7 @@ export class ResearchOrchestrationService implements IResearchOrchestration {
324
324
  * @param _ctx - Optional context for container isolation
325
325
  * @returns Map of researcher ID -> array of URLs
326
326
  */
327
- async distributeSearchResults(plan: ResearchPlan, results: QueryResultWithError[], _ctx?: any): Promise<Map<string, string[]>> {
327
+ async distributeSearchResults(plan: ResearchPlan, results: QueryResultWithError[], _ctx?: unknown): Promise<Map<string, string[]>> {
328
328
  const startTime = Date.now();
329
329
  const queryToResults = new Map(results.map(r => [r.query, r.results || []]));
330
330
  const linkMap = new Map<string, string[]>();
@@ -355,7 +355,7 @@ export class ResearchOrchestrationService implements IResearchOrchestration {
355
355
  options: RunResearchersOptions,
356
356
  researcherLinks?: Map<string, string[]>,
357
357
  storeLinks?: Map<string, StoreUrlEntry[]>,
358
- _ctx?: any
358
+ _ctx?: unknown
359
359
  ): Promise<void> {
360
360
  const { plan, options: orchestratorOptions, currentRound, signal } = options;
361
361
  const { sessionId, researchId, observer, ctx } = orchestratorOptions;
@@ -575,7 +575,7 @@ export class ResearchOrchestrationService implements IResearchOrchestration {
575
575
  config: Config,
576
576
  signal?: AbortSignal,
577
577
  onProgress?: (links: number) => void,
578
- ctx?: any
578
+ ctx?: unknown
579
579
  ): Promise<QueryResultWithError[]> {
580
580
  const container = tryGetServiceContainerFromCtx(ctx);
581
581
  const results = await search(queries, config, signal, onProgress, container);
@@ -592,7 +592,7 @@ export class ResearchOrchestrationService implements IResearchOrchestration {
592
592
  * @param config - Research configuration
593
593
  * @param ctx - Optional extension context for container isolation
594
594
  */
595
- async storeLinkDescriptions(_sessionId: string, round: number, researchId: string, config: Config, ctx?: any): Promise<void> {
595
+ async storeLinkDescriptions(_sessionId: string, round: number, researchId: string, config: Config, ctx?: unknown): Promise<void> {
596
596
  // Knowledge store disabled — never load the native vector stack. Mirrors the
597
597
  // gates in the quick orchestrator and scrape.ts; without this, resolving the
598
598
  // service throws on platforms lacking the native @lancedb binding (e.g. Intel
@@ -691,7 +691,7 @@ export class ResearchOrchestrationService implements IResearchOrchestration {
691
691
  * @param round - Current round number
692
692
  * @param ctx - Optional extension context for container isolation
693
693
  */
694
- async checkHealth(round: number, _researchId?: string, ctx?: any, signal?: AbortSignal): Promise<void> {
694
+ async checkHealth(round: number, _researchId?: string, ctx?: unknown, signal?: AbortSignal): Promise<void> {
695
695
  // Round 1 is skipped because there is nothing to diagnose yet — the pool was
696
696
  // built moments earlier and no work has run through it. A consequence worth
697
697
  // stating: a complexity-1 run has exactly ONE research round, so it now never