@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
@@ -52,7 +52,7 @@ export class GPUResourceService implements IGPUResourceService {
52
52
  }
53
53
  }
54
54
 
55
- async initialize(ctx?: any): Promise<void> {
55
+ async initialize(ctx?: unknown): Promise<void> {
56
56
  if (this.lifecycle === ServiceLifecycle.INITIALIZED) {
57
57
  return;
58
58
  }
@@ -152,12 +152,16 @@ export class GPUResourceService implements IGPUResourceService {
152
152
  /**
153
153
  * Acquire the global GPU lock
154
154
  */
155
- async acquireGpuLock(sessionId?: string | ((updater: any) => Promise<any>), timeoutMs?: number | string, ctx?: any): Promise<boolean> {
155
+ async acquireGpuLock(
156
+ sessionId?: string | ((updater: (state: SingletonState) => SingletonState | Promise<SingletonState>) => Promise<void>),
157
+ timeoutMs?: number | string,
158
+ ctx?: unknown,
159
+ ): Promise<boolean> {
156
160
  // Check if we are being called by StateManager (sessionId is actually updateState function)
157
161
  if (typeof sessionId === 'function') {
158
- const updateState = sessionId as any;
159
- const actualSessionId = timeoutMs as any as string;
160
- const actualTimeoutMs = ctx as any as number;
162
+ const updateState = sessionId;
163
+ const actualSessionId = timeoutMs as string;
164
+ const actualTimeoutMs = ctx as number;
161
165
  return this.performAcquireGpuLock(updateState, actualSessionId, actualTimeoutMs);
162
166
  }
163
167
 
@@ -170,15 +174,18 @@ export class GPUResourceService implements IGPUResourceService {
170
174
  /**
171
175
  * Release the global GPU lock
172
176
  */
173
- async releaseGpuLock(pid?: number | ((updater: any) => Promise<any>), ctx?: any): Promise<void> {
177
+ async releaseGpuLock(
178
+ pid?: number | ((updater: (state: SingletonState) => SingletonState | Promise<SingletonState>) => Promise<void>),
179
+ ctx?: unknown,
180
+ ): Promise<void> {
174
181
  // Check if we are being called by StateManager (pid is actually updateState function)
175
182
  if (typeof pid === 'function') {
176
- const updateState = pid as any;
177
- const actualPid = ctx as any as number;
183
+ const updateState = pid;
184
+ const actualPid = ctx as number;
178
185
  const currentPid = this.processLifecycle!.getCurrentPid();
179
186
  const targetPid = actualPid || currentPid;
180
187
 
181
- await updateState(async (state: any) => {
188
+ await updateState(async (state: SingletonState) => {
182
189
  if (state.gpuOwner && state.gpuOwner.pid === targetPid) {
183
190
  // Releasing our own lock decrements the re-entrant hold count and only
184
191
  // clears the owner record when the last in-process hold is released.
@@ -23,7 +23,7 @@ import {
23
23
  getModelChunkConfig as getKnowledgeModelChunkConfig,
24
24
  } from '../knowledge/index.ts';
25
25
  import { getEmbedder, clearEmbeddingInstance } from './embedding/embedding-factory.ts';
26
- import { getConfig } from '../config.ts';
26
+ import { getConfig, type Config } from '../config.ts';
27
27
  import { isNativeStackUnavailableError } from '../knowledge/embedder-utils.ts';
28
28
  import { probeKnowledgeStoreAvailability } from '../knowledge/availability.ts';
29
29
 
@@ -66,7 +66,7 @@ export class KnowledgeStoreService implements IKnowledgeStoreService {
66
66
  // two would race to close/null each other's components.
67
67
  private _disposalPromise: Promise<void> | null = null;
68
68
 
69
- async initialize(ctx?: any): Promise<void> {
69
+ async initialize(ctx?: unknown): Promise<void> {
70
70
  // A dispose() in flight must settle before anything below inspects
71
71
  // lifecycle or decides what to do — while() (not if()) because a newer
72
72
  // disposal can start again during the await (mirrors the
@@ -75,6 +75,9 @@ export class KnowledgeStoreService implements IKnowledgeStoreService {
75
75
  await this._disposalPromise;
76
76
  }
77
77
 
78
+ // Structural view of the init context: the service consumes only these two
79
+ // fields, and the caller's ctx (a pi host context) is wider.
80
+ const initCtx = ctx as { cwd?: string; config?: Config } | undefined;
78
81
  // Only an EXPLICIT ctx.cwd may re-scope the store. The lazy callers
79
82
  // (getStore/getEmbedder/getWriterQueue) call initialize() with no ctx — they
80
83
  // must NOT flip the scope. Resolving the missing cwd to process.cwd() here was
@@ -83,7 +86,7 @@ export class KnowledgeStoreService implements IKnowledgeStoreService {
83
86
  // disposed the correctly-scoped store and rebuilt it against process.cwd(),
84
87
  // so reads/writes silently scoped to the wrong workspace. Falling back to the
85
88
  // already-resolved this._cwd keeps the scope stable across lazy calls.
86
- const newCwd = ctx?.cwd || this._cwd;
89
+ const newCwd = initCtx?.cwd || this._cwd;
87
90
 
88
91
  // If already settled for this cwd, return early — UNLESS the live Knowledge Mode has changed
89
92
  // since we initialized (via /research-config), in which case re-initialize so the change
@@ -92,7 +95,7 @@ export class KnowledgeStoreService implements IKnowledgeStoreService {
92
95
  // - INITIALIZED and mode != the built mode : project↔global re-scope, or enabled→'none'.
93
96
  // A native-unavailable DISABLED ('native') stays memoized — retrying is futile on that platform.
94
97
  if ((this.lifecycle === ServiceLifecycle.INITIALIZED || this.lifecycle === ServiceLifecycle.DISABLED) && this._cwd === newCwd) {
95
- const liveConfig = ctx?.config || getConfig(this._cwd);
98
+ const liveConfig = initCtx?.config || getConfig(this._cwd);
96
99
  const liveMode: string = liveConfig.KNOWLEDGE_STORE_MODE;
97
100
  // Retrieval strategy ('vector' hybrid / 'bm25' lexical) participates in the same
98
101
  // live-change detection: a /research-config switch must re-scope the store onto
@@ -107,14 +110,14 @@ export class KnowledgeStoreService implements IKnowledgeStoreService {
107
110
  this.lifecycle === ServiceLifecycle.DISABLED && this._disabledReason === 'mode' && liveMode !== 'none';
108
111
  const modeChanged =
109
112
  this.lifecycle === ServiceLifecycle.INITIALIZED &&
110
- ctx?.config !== undefined &&
113
+ initCtx?.config !== undefined &&
111
114
  this._initializedMode !== undefined &&
112
- this._initializedMode !== ctx.config.KNOWLEDGE_STORE_MODE;
115
+ this._initializedMode !== initCtx.config.KNOWLEDGE_STORE_MODE;
113
116
  const retrievalChanged =
114
117
  this.lifecycle === ServiceLifecycle.INITIALIZED &&
115
- ctx?.config !== undefined &&
118
+ initCtx?.config !== undefined &&
116
119
  this._initializedRetrieval !== undefined &&
117
- this._initializedRetrieval !== ctx.config.KNOWLEDGE_STORE_RETRIEVAL;
120
+ this._initializedRetrieval !== initCtx.config.KNOWLEDGE_STORE_RETRIEVAL;
118
121
  if (!reviveFromMode && !modeChanged && !retrievalChanged) {
119
122
  return;
120
123
  }
@@ -178,10 +181,10 @@ export class KnowledgeStoreService implements IKnowledgeStoreService {
178
181
  // Prefer an explicit ctx.cwd; otherwise keep the cwd already resolved on this
179
182
  // service (defaults to process.cwd() on a never-initialized instance). This
180
183
  // mirrors the newCwd resolution above so a lazy getStore() never re-scopes.
181
- this._cwd = ctx?.cwd || this._cwd;
184
+ this._cwd = initCtx?.cwd || this._cwd;
182
185
  // Prefer a caller-resolved config (the SDK/CLI/tool seed ctx.config with the
183
186
  // interface-resolved overlay); else load this directory's config.
184
- const config = ctx?.config || getConfig(this._cwd);
187
+ const config = initCtx?.config || getConfig(this._cwd);
185
188
  // Record the mode this build reflects so a later runtime mode change is detected above.
186
189
  this._initializedMode = config.KNOWLEDGE_STORE_MODE;
187
190
  this._initializedRetrieval = config.KNOWLEDGE_STORE_RETRIEVAL;
@@ -22,9 +22,10 @@ export class SchedulerFactoryService implements ISchedulerFactory, IService {
22
22
  lifecycle = ServiceLifecycle.UNINITIALIZED;
23
23
  private container: ServiceContainer = getServiceContainer();
24
24
 
25
- async initialize(ctx?: any): Promise<void> {
26
- if (ctx?.container) {
27
- this.container = ctx.container;
25
+ async initialize(ctx?: unknown): Promise<void> {
26
+ const initCtx = ctx as { container?: ServiceContainer } | undefined;
27
+ if (initCtx?.container) {
28
+ this.container = initCtx.container;
28
29
  }
29
30
  this.lifecycle = ServiceLifecycle.INITIALIZED;
30
31
  }
@@ -276,7 +276,7 @@ export function registerInfrastructureServices(container: ServiceContainer = get
276
276
  * @param ctx - Optional extension context
277
277
  * @param container - Service container instance
278
278
  */
279
- export async function initializeInfrastructureServices(ctx?: any, container: ServiceContainer = getServiceContainer()): Promise<{ success: boolean; initialized: string[]; failed: string[] }> {
279
+ export async function initializeInfrastructureServices(ctx?: unknown, container: ServiceContainer = getServiceContainer()): Promise<{ success: boolean; initialized: string[]; failed: string[] }> {
280
280
  logger.log('[InfrastructureServiceInit] Initializing infrastructure services...');
281
281
 
282
282
  const initialized: string[] = [];
@@ -35,7 +35,7 @@ export class StateManagerService implements IStateManager {
35
35
  // The underlying state manager instance
36
36
  private _stateManager: StateManager | null = null;
37
37
 
38
- async initialize(ctx?: any): Promise<void> {
38
+ async initialize(ctx?: unknown): Promise<void> {
39
39
  if (this.lifecycle === ServiceLifecycle.INITIALIZED) {
40
40
  return;
41
41
  }
@@ -223,7 +223,7 @@ export class StateManagerService implements IStateManager {
223
223
  /**
224
224
  * Information about the current GPU owner
225
225
  */
226
- async getGpuOwner(): Promise<SingletonState['gpuOwner'] | null> {
226
+ async getGpuOwner(): Promise<NonNullable<SingletonState['gpuOwner']> | null> {
227
227
  return this.getStateManager().getGpuOwner();
228
228
  }
229
229
 
@@ -497,14 +497,14 @@ export class StateManager {
497
497
  // ==================== GPU Lock API ====================
498
498
 
499
499
  public async acquireGpuLock(sessionId?: string, timeoutMs?: number): Promise<boolean> {
500
- return this.gpuResourceService.acquireGpuLock(this.updateState.bind(this) as any, sessionId, timeoutMs);
500
+ return this.gpuResourceService.acquireGpuLock(this.updateState.bind(this), sessionId, timeoutMs);
501
501
  }
502
502
 
503
503
  public async releaseGpuLock(pid?: number): Promise<void> {
504
- await this.gpuResourceService.releaseGpuLock(this.updateState.bind(this) as any, pid);
504
+ await this.gpuResourceService.releaseGpuLock(this.updateState.bind(this), pid);
505
505
  }
506
506
 
507
- public async getGpuOwner(): Promise<SingletonState['gpuOwner'] | null> {
507
+ public async getGpuOwner(): Promise<NonNullable<SingletonState['gpuOwner']> | null> {
508
508
  const state = await this.readState();
509
509
  return state.gpuOwner || null;
510
510
  }
@@ -36,9 +36,15 @@ export class StateValidator implements IService {
36
36
  if (!Value.Check(SingletonStateSchema, coerced)) {
37
37
  // Use coerced state for error reporting to get better paths
38
38
  const errors = [...Value.Errors(SingletonStateSchema, coerced)];
39
- const errorMsg = errors.map((e: any) => {
40
- const path = String(e.path || 'root');
41
- return `${path}: ${e.message} (${JSON.stringify(e.value)})`;
39
+ // TLocalizedValidationError carries the failing property in `instancePath` (not
40
+ // `path`); the old `(e: any).path` read was always undefined, reporting 'root'
41
+ // for every field.
42
+ const errorMsg = errors.map(e => {
43
+ const path = String(e.instancePath || 'root');
44
+ // `value` is present on most TLocalizedValidationError variants but not
45
+ // all; read it through a structural view so the message stays uniform.
46
+ const value = (e as { value?: unknown }).value;
47
+ return `${path}: ${e.message} (${JSON.stringify(value)})`;
42
48
  }).join(', ');
43
49
  throw new Error(`Invalid state: ${errorMsg}`);
44
50
  }
@@ -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) {