@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
@@ -30,6 +30,8 @@
30
30
  import net from 'node:net';
31
31
  import dns from 'node:dns';
32
32
  import { pipeline } from 'node:stream';
33
+ import { realpathSync } from 'node:fs';
34
+ import { fileURLToPath } from 'node:url';
33
35
  import { isBlockedDestination, isBlockedProxyTarget } from './lib/private-addresses.mjs';
34
36
 
35
37
  const PORT = Number(process.env.DDG_SOCKS_PORT || 1080);
@@ -245,18 +247,27 @@ const server = net.createServer((client) => {
245
247
  client.destroy();
246
248
  return;
247
249
  }
248
- // Success reply (IPv4 0.0.0.0:0 is acceptable)
249
- client.write(Buffer.from([0x05, 0x00, 0x00, 0x01, 0, 0, 0, 0, 0, 0]));
250
- upstream.on('error', () => upstream.destroy());
251
- // A client that pipelined its payload with the request (instead of
252
- // waiting for this reply, as most do) had those bytes buffered in
253
- // `buf` — forward them before attaching pipe, or they are lost.
254
- if (buf.length) upstream.write(buf);
255
- // pipeline() (not pipe) destroys BOTH ends when either one ends:
256
- // a client RST used to leave the upstream socket open (fd leak).
257
- pipeline([client, upstream], (err) => {
258
- if (err) console.error(`[ddg-socks] tunnel closed: ${err.message}`);
259
- });
250
+ // This callback runs from a socket 'connect' event, NOT from a promise
251
+ // chain: an exception thrown here is uncaught and ends the process.
252
+ // Every step that touches a socket therefore stays inside one guard.
253
+ try {
254
+ if (client.destroyed) {
255
+ upstream.destroy();
256
+ return;
257
+ }
258
+ // Success reply (IPv4 0.0.0.0:0 is acceptable)
259
+ client.write(Buffer.from([0x05, 0x00, 0x00, 0x01, 0, 0, 0, 0, 0, 0]));
260
+ upstream.on('error', () => upstream.destroy());
261
+ // A client that pipelined its payload with the request (instead of
262
+ // waiting for this reply, as most do) had those bytes buffered in
263
+ // `buf` — forward them before attaching the tunnel, or they are lost.
264
+ if (buf.length) upstream.write(buf);
265
+ attachTunnel(client, upstream);
266
+ } catch (attachErr) {
267
+ console.error(`[ddg-socks] failed to establish tunnel: ${attachErr && attachErr.message}`);
268
+ client.destroy();
269
+ upstream.destroy();
270
+ }
260
271
  });
261
272
  }).catch(() => {
262
273
  client.write(Buffer.from([0x05, 0x04, 0x00, 0x01, 0, 0, 0, 0, 0, 0]));
@@ -270,10 +281,89 @@ const server = net.createServer((client) => {
270
281
  client.on('data', onData);
271
282
  });
272
283
 
284
+ /**
285
+ * Wire a client socket to an upstream socket in BOTH directions.
286
+ *
287
+ * Exported so the regression this replaced can be tested without network
288
+ * egress: 1.7.23 shipped `pipeline([client, upstream])`, which forwards only
289
+ * client→upstream. The tunnel accepted the SOCKS handshake, connected, and then
290
+ * black-holed every response, so every browser request through the proxy timed
291
+ * out. The unit suite stayed green because nothing tested the return path.
292
+ *
293
+ * TWO directional pipelines, not one array: `pipeline([a, b])` means `a → b`.
294
+ * pipeline (not pipe) is still the right primitive — it destroys both ends when
295
+ * either ends, which is what closed the file-descriptor leak on a client RST.
296
+ */
297
+ export function attachTunnel(client, upstream) {
298
+ const onError = (err) => {
299
+ // A HALF-CLOSE is normal tunnel teardown (HTTP/1.0 `Connection: close`, a
300
+ // TLS close_notify, either peer hanging up first), and an already-dead pair
301
+ // is the same race seen twice. Logging either would fill the journal with
302
+ // one line per request. Genuine faults still log.
303
+ if (err && err.code !== 'ERR_STREAM_PREMATURE_CLOSE' && err.code !== 'ERR_STREAM_UNABLE_TO_PIPE') {
304
+ console.error(`[ddg-socks] tunnel closed: ${err.message}`);
305
+ }
306
+ client.destroy();
307
+ upstream.destroy();
308
+ };
309
+
310
+ // A peer can be gone by the time the upstream connect resolves: browsers open
311
+ // speculative SOCKS connections and drop them, and this proxy's own
312
+ // DATA_DEADLINE cuts both ends on a stall. `pipeline()` THROWS
313
+ // ERR_STREAM_UNABLE_TO_PIPE synchronously on a closed/destroyed endpoint —
314
+ // `pipe()` did not — and that throw lands in a socket 'connect' handler, i.e.
315
+ // OUTSIDE every promise chain and try/catch in this file, so it killed the
316
+ // daemon. Measured 2026-10-30: 20 restarts in a few minutes, every one this
317
+ // error. Attaching a tunnel to a dead pair must be a no-op.
318
+ if (client.destroyed || upstream.destroyed) {
319
+ client.destroy();
320
+ upstream.destroy();
321
+ return;
322
+ }
323
+ try {
324
+ pipeline(client, upstream, onError);
325
+ pipeline(upstream, client, onError);
326
+ } catch (err) {
327
+ onError(err);
328
+ }
329
+ }
330
+
273
331
  server.on('error', (err) => {
274
332
  console.error(`[ddg-socks] server error: ${err.message}`);
333
+ // A proxy that is ALIVE but not listening is the worst state: the supervisor
334
+ // thinks it is up, Restart=always never fires, and every browser request fails
335
+ // at connect with no explanation. EADDRINUSE/EACCES are not recoverable in
336
+ // process, so exit non-zero and let the supervisor retry.
337
+ process.exit(1);
275
338
  });
276
339
 
277
- server.listen(PORT, '127.0.0.1', () => {
278
- console.log(`[ddg-socks] SOCKS5 listening on 127.0.0.1:${PORT} (pins: ${PINS.join(',')})`);
279
- });
340
+ /**
341
+ * Start listening. Separated from module load so a test can import attachTunnel
342
+ * (and the guard helpers) without binding port 1080.
343
+ */
344
+ export function startProxy(port = PORT) {
345
+ server.listen(port, '127.0.0.1', () => {
346
+ console.log(`[ddg-socks] SOCKS5 listening on 127.0.0.1:${port} (pins: ${PINS.join(',')})`);
347
+ });
348
+ return server;
349
+ }
350
+
351
+ // Main-module guard: `process.argv[1]` is absent when imported by a test runner.
352
+ //
353
+ // Compare REAL paths, not URL strings. The documented install links
354
+ // ~/.pi/research/scripts/ddg-socks-proxy.mjs to the copy in the repo (the same
355
+ // layout a ~/bin wrapper uses). `import.meta.url` is already the real path, but
356
+ // `process.argv[1]` is the symlink, so a string comparison says "imported" and
357
+ // the proxy exits 0 without ever listening: the supervisor then reports a
358
+ // healthy service that refuses every connection. A symlinked DIRECTORY with a
359
+ // relative entry is fine (Node resolves the cwd); a symlinked script FILE is not.
360
+ const isMainModule = (() => {
361
+ try {
362
+ if (!process.argv[1]) return false;
363
+ return realpathSync(process.argv[1]) === realpathSync(fileURLToPath(import.meta.url));
364
+ } catch {
365
+ return false;
366
+ }
367
+ })();
368
+
369
+ if (isMainModule) startProxy();
package/src/cli.ts CHANGED
@@ -156,43 +156,61 @@ function pretty(obj: unknown): string {
156
156
  export function makeProgressObserver(): HeadlessObserverOptions {
157
157
  return {
158
158
  enableLogging: false,
159
- onProgress: (event: string, data?: any) => {
159
+ onProgress: (event: string, data?: unknown) => {
160
+ // Structural view of the progress payload; each event carries a
161
+ // different shape, so the fields are optional and string/number-typed
162
+ // at the point of use.
163
+ const d = data as {
164
+ plan?: { researchers?: unknown[] };
165
+ slots?: number;
166
+ maxWaitMs?: number;
167
+ round?: number;
168
+ queries?: unknown[];
169
+ id?: string;
170
+ name?: string;
171
+ error?: string;
172
+ action?: string;
173
+ tokens?: number;
174
+ cost?: number;
175
+ result?: string;
176
+ message?: string;
177
+ } | undefined;
160
178
  switch (event) {
161
179
  case 'planning_success':
162
- toStderr(` • plan: ${data?.plan?.researchers?.length ?? '?'} researcher(s)\n`);
180
+ toStderr(` • plan: ${d?.plan?.researchers?.length ?? '?'} researcher(s)\n`);
163
181
  break;
164
182
  case 'run_queued':
165
183
  toStderr(
166
- ` • queued: ${data?.slots ?? '?'} concurrent run(s) already active — waiting up to ` +
167
- `${Math.round((data?.maxWaitMs ?? 0) / 1000)}s for a slot…\n`,
184
+ ` • queued: ${d?.slots ?? '?'} concurrent run(s) already active — waiting up to ` +
185
+ `${Math.round((d?.maxWaitMs ?? 0) / 1000)}s for a slot…\n`,
168
186
  );
169
187
  break;
170
188
  case 'round_start':
171
- toStderr(` • round ${data?.round}\n`);
189
+ toStderr(` • round ${d?.round}\n`);
172
190
  break;
173
191
  case 'search_start':
174
192
  // "N queries", not "N query/s" — the old `query/${n===1?'':'s'}` form rendered a
175
193
  // COUNT as what reads unmistakably as a RATE ("45 query/s"), so a burst that was
176
194
  // in fact 45 queries looked like 45 per second and then appeared frozen. It also
177
195
  // emitted a bare trailing slash ("1 query/") in the singular.
178
- toStderr(` • search burst: ${data?.queries?.length ?? 0} ${(data?.queries?.length ?? 0) === 1 ? 'query' : 'queries'}\n`);
196
+ toStderr(` • search burst: ${d?.queries?.length ?? 0} ${(d?.queries?.length ?? 0) === 1 ? 'query' : 'queries'}\n`);
179
197
  break;
180
198
  case 'researcher_start':
181
- toStderr(` • researcher ${data?.id}: ${data?.name}\n`);
199
+ toStderr(` • researcher ${d?.id}: ${d?.name}\n`);
182
200
  break;
183
201
  case 'researcher_failure':
184
- toStderr(` • researcher ${data?.id} failed: ${data?.error}\n`);
202
+ toStderr(` • researcher ${d?.id} failed: ${d?.error}\n`);
185
203
  break;
186
204
  case 'evaluation_decision':
187
- toStderr(` • evaluator: ${data?.action}\n`);
205
+ toStderr(` • evaluator: ${d?.action}\n`);
188
206
  break;
189
207
  case 'tokens_consumed': {
190
208
  // A truthiness check on cost used to gate this whole line, so a model with
191
209
  // an all-zero price table suppressed the TOKEN count as well — the run
192
210
  // looked like it consumed nothing. Tokens stand on their own; cost is
193
211
  // appended whenever it is a number, including 0.
194
- const consumed = Number(data?.tokens ?? 0);
195
- const costVal = typeof data?.cost === 'number' ? data.cost : undefined;
212
+ const consumed = Number(d?.tokens ?? 0);
213
+ const costVal = typeof d?.cost === 'number' ? d.cost : undefined;
196
214
  if (consumed > 0 || costVal !== undefined) {
197
215
  const costPart = costVal === undefined ? '' : ` ($${costVal.toFixed(4)})`;
198
216
  toStderr(` • tokens: ${consumed}${costPart}\n`);
@@ -200,7 +218,7 @@ export function makeProgressObserver(): HeadlessObserverOptions {
200
218
  break;
201
219
  }
202
220
  case 'complete': {
203
- toStderr(` • complete (${data?.result?.length ?? 0} chars)\n`);
221
+ toStderr(` • complete (${d?.result?.length ?? 0} chars)\n`);
204
222
  // Degradation signal for callers that read stderr (the agent skill
205
223
  // does): a run that completes but is weakly grounded or retrieved no
206
224
  // sources at all looks identical to a healthy run on exit code and
@@ -208,7 +226,7 @@ export function makeProgressObserver(): HeadlessObserverOptions {
208
226
  // degraded reports (1 citation / 0 sources) with nothing on stderr to
209
227
  // distinguish them. The markers are the synthesis service's own
210
228
  // notices, appended by ensureCitedLinks.
211
- const reportText = typeof data?.result === 'string' ? data.result : '';
229
+ const reportText = typeof d?.result === 'string' ? d.result : '';
212
230
  if (reportText.includes('No web sources were successfully retrieved') ||
213
231
  reportText.includes('None of the links above could be verified')) {
214
232
  toStderr(' • WARNING: no web sources could be retrieved — the report is unverified\n');
@@ -218,7 +236,7 @@ export function makeProgressObserver(): HeadlessObserverOptions {
218
236
  break;
219
237
  }
220
238
  case 'error':
221
- toStderr(` • error: ${data?.message}\n`);
239
+ toStderr(` • error: ${d?.message}\n`);
222
240
  break;
223
241
  default:
224
242
  // Other granular events are intentionally silent to keep output clean.
package/src/config.ts CHANGED
@@ -38,6 +38,14 @@ export const ConfigSchema = Type.Object({
38
38
  RESEARCHER_MAX_RETRY_DELAY_MS: Type.Number({ minimum: 100, maximum: 10000, default: 2000 }),
39
39
  /** Unique researcher failures that abort the entire run (default: 2, range: 1-10) */
40
40
  MAX_FAILED_RESEARCHERS: Type.Number({ minimum: 1, maximum: 10, default: 2 }),
41
+ /**
42
+ * Run research with a SINGLE sequential researcher that carries all the queries, instead
43
+ * of a team of parallel researchers. One session doing all the work keeps one growing,
44
+ * fully-cached context (each turn re-reads the prior context as a cache hit), at the cost
45
+ * of serial latency and a larger single context. Default: true (single, cache-friendly
46
+ * researcher at every depth; Level 1 is always single regardless of this flag).
47
+ */
48
+ SINGLE_RESEARCHER: Type.Boolean({ default: true }),
41
49
  /** Target depth for recursive research (default: 1, range: 0-3; 0 = quick mode, requires QUICK_RESEARCH) */
42
50
  DEFAULT_RESEARCH_DEPTH: Type.Number({ minimum: 0, maximum: 3, default: 1 }),
43
51
  /** Opt-in gate for depth-0 (quick mode) research. When false (default), depth 0 is invisible to the agent-facing tool and any depth-0 default resolves to 1 — upstream behavior. When true, agents can pass depth: 0 and DEFAULT_RESEARCH_DEPTH=0 is honored. */
@@ -494,8 +502,8 @@ function updateProjectSettingsRegistry(mutate: (registry: Record<string, Record<
494
502
  // in the same state dir as config.env / backups).
495
503
  lockFd = fs.openSync(lockPath, 'wx', 0o600);
496
504
  break;
497
- } catch (err: any) {
498
- if (err.code === 'EEXIST') {
505
+ } catch (err: unknown) {
506
+ if ((err as { code?: string }).code === 'EEXIST') {
499
507
  // Stale lock check
500
508
  try {
501
509
  const stats = fs.statSync(lockPath);
@@ -967,6 +975,7 @@ export function saveConfig(config: Config, scope: 'local' | 'user' = 'local', cw
967
975
  PI_RESEARCH_MAX_RETRIES: String(config.RESEARCHER_MAX_RETRIES),
968
976
  PI_RESEARCH_RETRY_DELAY_MS: String(config.RESEARCHER_MAX_RETRY_DELAY_MS),
969
977
  PI_RESEARCH_MAX_FAILED_RESEARCHERS: String(config.MAX_FAILED_RESEARCHERS ?? DEFAULTS.MAX_FAILED_RESEARCHERS),
978
+ PI_RESEARCH_SINGLE_RESEARCHER: String(config.SINGLE_RESEARCHER ?? DEFAULTS.SINGLE_RESEARCHER),
970
979
  PI_RESEARCH_HEALTH_CHECK_TIMEOUT_MS: String(config.HEALTH_CHECK_TIMEOUT_MS ?? DEFAULTS.HEALTH_CHECK_TIMEOUT_MS),
971
980
  PI_RESEARCH_SEARCH_TIMEOUT_MS: String(config.SEARCH_TIMEOUT_MS),
972
981
  PI_RESEARCH_TUI_REFRESH_DEBOUNCE_MS: String(config.TUI_REFRESH_DEBOUNCE_MS),
@@ -1072,8 +1081,8 @@ export function saveConfig(config: Config, scope: 'local' | 'user' = 'local', cw
1072
1081
  // 0o600: owner-only, matching the 0o700 directory posture.
1073
1082
  lockFd = fs.openSync(lockPath, 'wx', 0o600);
1074
1083
  break;
1075
- } catch (err: any) {
1076
- if (err.code === 'EEXIST') {
1084
+ } catch (err: unknown) {
1085
+ if ((err as { code?: string }).code === 'EEXIST') {
1077
1086
  // Check if lock is stale (older than 30s)
1078
1087
  try {
1079
1088
  const stats = fs.statSync(lockPath);
@@ -1236,6 +1245,7 @@ export function createConfig(env: Record<string, string | undefined>, processEnv
1236
1245
  RESEARCHER_MAX_RETRIES: parseEnvNumber(e, 'PI_RESEARCH_MAX_RETRIES', DEFAULTS.RESEARCHER_MAX_RETRIES, 0, 5, true),
1237
1246
  RESEARCHER_MAX_RETRY_DELAY_MS: parseEnvNumber(e, 'PI_RESEARCH_RETRY_DELAY_MS', DEFAULTS.RESEARCHER_MAX_RETRY_DELAY_MS, 100, 10000),
1238
1247
  MAX_FAILED_RESEARCHERS: parseEnvNumber(e, 'PI_RESEARCH_MAX_FAILED_RESEARCHERS', DEFAULTS.MAX_FAILED_RESEARCHERS, 1, 10, true),
1248
+ SINGLE_RESEARCHER: parseEnvBool(e, 'PI_RESEARCH_SINGLE_RESEARCHER', DEFAULTS.SINGLE_RESEARCHER),
1239
1249
  DEFAULT_RESEARCH_DEPTH: parseEnvNumber(e, 'PI_RESEARCH_DEFAULT_RESEARCH_DEPTH', DEFAULTS.DEFAULT_RESEARCH_DEPTH, 0, 3, true),
1240
1250
  QUICK_RESEARCH: parseEnvBool(e, 'PI_RESEARCH_QUICK_RESEARCH', DEFAULTS.QUICK_RESEARCH),
1241
1251
  MAX_SCRAPE_BATCHES: parseEnvNumber(e, 'PI_RESEARCH_MAX_SCRAPE_BATCHES', DEFAULTS.MAX_SCRAPE_BATCHES, 0, 99, true),
@@ -1287,10 +1297,10 @@ export function createConfig(env: Record<string, string | undefined>, processEnv
1287
1297
  DISABLED_TOOLS: parseEnvString(e, 'PI_RESEARCH_DISABLED_TOOLS', DEFAULTS.DISABLED_TOOLS),
1288
1298
  };
1289
1299
 
1290
- const config = { ...DEFAULTS };
1300
+ const config: Config = { ...DEFAULTS };
1291
1301
  for (const [key, value] of Object.entries(raw)) {
1292
1302
  if (value !== undefined) {
1293
- (config as any)[key] = value;
1303
+ (config as Record<string, unknown>)[key] = value;
1294
1304
  }
1295
1305
  }
1296
1306
 
@@ -1379,7 +1389,10 @@ export function resetConfig(): void {
1379
1389
  export function validateConfig(config: Config): void {
1380
1390
  const errors = [...Value.Errors(ConfigSchema, config)];
1381
1391
  if (errors.length > 0) {
1382
- throw new Error(`Invalid configuration: ${errors.map(e => `${(e as any).path || ''} ${e.message}`).join(', ')}`);
1392
+ // TLocalizedValidationError carries the failing property in `instancePath` (not
1393
+ // `path`); the old `(e as any).path` read was always undefined, dropping the path
1394
+ // from the message.
1395
+ throw new Error(`Invalid configuration: ${errors.map(e => `${e.instancePath || ''} ${e.message}`).join(', ')}`);
1383
1396
  }
1384
1397
  }
1385
1398
 
@@ -4,11 +4,32 @@
4
4
 
5
5
  import type { IService } from '../service-registry.ts';
6
6
 
7
+ /**
8
+ * Per-component health status, as reported by a single check.
9
+ */
10
+ export interface HealthCheckStatus {
11
+ component: string;
12
+ healthy: boolean;
13
+ durationMs: number;
14
+ error?: string;
15
+ diagnostic?: Record<string, unknown>;
16
+ timestamp: string;
17
+ }
18
+
19
+ /**
20
+ * Aggregate system health across every registered component.
21
+ */
22
+ export interface SystemHealth {
23
+ status: 'healthy' | 'degraded' | 'unhealthy';
24
+ components: HealthCheckStatus[];
25
+ timestamp: string;
26
+ }
27
+
7
28
  /**
8
29
  * Health check registry interface
9
30
  */
10
31
  export interface IHealthRegistryService extends IService {
11
- register(name: string, check: (options?: { force?: boolean }) => Promise<{ healthy: boolean; error?: string; diagnostic?: Record<string, any> }>, options?: { timeoutMs?: number; critical?: boolean }): void;
32
+ register(name: string, check: (options?: { force?: boolean }) => Promise<{ healthy: boolean; error?: string; diagnostic?: Record<string, unknown> }>, options?: { timeoutMs?: number; critical?: boolean }): void;
12
33
  isCritical(componentName: string): boolean;
13
- runAll(options?: { force?: boolean }): Promise<{ status: 'healthy' | 'degraded' | 'unhealthy'; components: any[]; timestamp: string }>;
34
+ runAll(options?: { force?: boolean }): Promise<SystemHealth>;
14
35
  }
@@ -3,6 +3,7 @@
3
3
  */
4
4
 
5
5
  import type { IService } from '../service-registry.ts';
6
+ import type { IStateManager } from './state-manager-interfaces.ts';
6
7
 
7
8
  /**
8
9
  * Single document record in the knowledge store
@@ -11,7 +12,7 @@ export interface StoreDocument {
11
12
  url: string;
12
13
  text: string;
13
14
  content?: string;
14
- metadata: Record<string, any>;
15
+ metadata: Record<string, unknown>;
15
16
  timestamp: number;
16
17
  workspace?: string;
17
18
  is_global?: boolean;
@@ -34,6 +35,8 @@ export interface HFEnv {
34
35
  backends: {
35
36
  onnx: ONNXRuntimeEnv;
36
37
  };
38
+ /** Older transformers.js versions exposed the ONNX env at the top level. */
39
+ onnx?: ONNXRuntimeEnv;
37
40
  }
38
41
 
39
42
  /**
@@ -56,7 +59,7 @@ export interface EmbedderOptions {
56
59
  batchSize?: number;
57
60
  charsPerToken?: number;
58
61
  documentPrefix?: string;
59
- stateManager?: any; // To avoid circular dependency with IStateManager
62
+ stateManager?: IStateManager; // type-only import — no runtime cycle
60
63
  useCache?: boolean;
61
64
  }
62
65
 
@@ -72,7 +75,7 @@ export interface IngestionItem {
72
75
  url: string;
73
76
  markdown: string;
74
77
  content?: string;
75
- metadata?: Record<string, any>;
78
+ metadata?: Record<string, unknown>;
76
79
  }
77
80
 
78
81
  /**
@@ -112,7 +115,7 @@ export interface IKnowledgeStore extends IService {
112
115
  count(): Promise<number>;
113
116
  search(query: string, options?: { limit?: number }): Promise<StoreDocument[]>;
114
117
  findRelevantUrls(query: string, options?: { limit?: number }): Promise<StoreUrlEntry[]>;
115
- rebuildDocument(url: string): Promise<{ text: string; description: string | null; metadata: Record<string, any>; ageDays?: number } | null>;
118
+ rebuildDocument(url: string): Promise<{ text: string; description: string | null; metadata: Record<string, unknown>; ageDays?: number } | null>;
116
119
  findDocumentsByUrl(url: string): Promise<StoreDocument[]>;
117
120
  findByUrl(url: string): Promise<StoreDocument[]>;
118
121
  countScoped(workspace?: string): Promise<{ local: number; global: number; projects: number }>;
@@ -10,7 +10,7 @@
10
10
  import type { ResearchPlan } from './research-plan-types.ts';
11
11
  export interface HeadlessObserverOptions {
12
12
  /** Callback for progress updates */
13
- onProgress?: (event: string, data?: any) => void;
13
+ onProgress?: (event: string, data?: unknown) => void;
14
14
  /** Whether to log events to the console/logger */
15
15
  enableLogging?: boolean;
16
16
  }
@@ -8,7 +8,7 @@ import type { ResearchPlan, ResearcherConfig } from './planning-interfaces.ts';
8
8
  import type { QueryResultWithError } from '../../web-research/types.ts';
9
9
  import type { StoreUrlEntry } from './knowledge-interfaces.ts';
10
10
 
11
- import type { Model } from '@earendil-works/pi-ai';
11
+ import type { Api, Model } from '@earendil-works/pi-ai';
12
12
  import type { ExtensionContext, AgentToolResult } from '@earendil-works/pi-coding-agent';
13
13
  import type { ResearchObserver, HeadlessObserverOptions } from './observer-interfaces.ts';
14
14
  import type { SteeringMessage } from './steering-interfaces.ts';
@@ -21,9 +21,9 @@ export interface ResearchOptions {
21
21
  query: string;
22
22
  depth?: 0 | 1 | 2 | 3;
23
23
  complexity?: 1 | 2 | 3;
24
- model?: Model<any>;
24
+ model?: Model<Api>;
25
25
  observer?: ResearchObserver | HeadlessObserverOptions;
26
- onUpdate?: (update: AgentToolResult<any>) => void;
26
+ onUpdate?: (update: AgentToolResult<unknown>) => void;
27
27
  sessionId: string;
28
28
  researchId: string;
29
29
  config?: Config;
@@ -44,7 +44,7 @@ export interface RunResearchersOptions {
44
44
  complexity: 1 | 2 | 3;
45
45
  excludeTools?: string[];
46
46
  ctx: ExtensionContext;
47
- model: Model<any>;
47
+ model: Model<Api>;
48
48
  config?: Config;
49
49
  observer?: ResearchObserver;
50
50
  initialLinks?: string[];
@@ -57,7 +57,12 @@ export interface RunResearchersOptions {
57
57
  * Research Synthesis Service Interface
58
58
  */
59
59
  export interface IResearchSynthesisService extends IService {
60
- storeReport(researchId: string, researcherId: string, report: string): void;
60
+ /**
61
+ * Store a researcher report. `digest` is the researcher's coverage digest, passed
62
+ * explicitly in the raw-scrape flow where the "report" is the raw tool results (which
63
+ * carry no embedded digest). When omitted, the digest is split off the report head.
64
+ */
65
+ storeReport(researchId: string, researcherId: string, report: string, digest?: string): void;
61
66
  getAllReports(researchId: string): Map<string, string>;
62
67
  /** Coverage digest per stored report, derived when a researcher emitted none. */
63
68
  getAllDigests(researchId: string): Map<string, string>;
@@ -76,13 +81,13 @@ export interface IResearchSynthesisService extends IService {
76
81
  * Research Orchestration Service Interface
77
82
  */
78
83
  export interface IResearchOrchestration extends IService {
79
- resolveResearchModel(options: ResearchOptions): Promise<Model<any>>;
84
+ resolveResearchModel(options: ResearchOptions): Promise<Model<Api>>;
80
85
  runResearch(options: ResearchOptions, signal?: AbortSignal): Promise<string>;
81
- cleanupResearchServices(sessionId?: string, researchId?: string, ctx?: any, config?: Config, opts?: { skipStoreMaintenance?: boolean }): Promise<void>;
82
- distributeSearchResults(plan: ResearchPlan, results: QueryResultWithError[], ctx?: any): Promise<Map<string, string[]>>;
83
- runResearchers(options: RunResearchersOptions, researcherLinks?: Map<string, string[]>, storeLinks?: Map<string, StoreUrlEntry[]>, ctx?: any): Promise<void>;
84
- runSearchBurst(queries: string[], config: Config, signal?: AbortSignal, onProgress?: (links: number) => void, ctx?: any): Promise<QueryResultWithError[]>;
85
- storeLinkDescriptions(sessionId: string, round: number, researchId: string, config: Config, ctx?: any): Promise<void>;
86
+ cleanupResearchServices(sessionId?: string, researchId?: string, ctx?: unknown, config?: Config, opts?: { skipStoreMaintenance?: boolean }): Promise<void>;
87
+ distributeSearchResults(plan: ResearchPlan, results: QueryResultWithError[], ctx?: unknown): Promise<Map<string, string[]>>;
88
+ runResearchers(options: RunResearchersOptions, researcherLinks?: Map<string, string[]>, storeLinks?: Map<string, StoreUrlEntry[]>, ctx?: unknown): Promise<void>;
89
+ runSearchBurst(queries: string[], config: Config, signal?: AbortSignal, onProgress?: (links: number) => void, ctx?: unknown): Promise<QueryResultWithError[]>;
90
+ storeLinkDescriptions(sessionId: string, round: number, researchId: string, config: Config, ctx?: unknown): Promise<void>;
86
91
  // Advisory only — logs infrastructure health; research never aborts on the result.
87
- checkHealth(round: number, researchId?: string, ctx?: any, signal?: AbortSignal): Promise<void>;
92
+ checkHealth(round: number, researchId?: string, ctx?: unknown, signal?: AbortSignal): Promise<void>;
88
93
  }
@@ -3,7 +3,7 @@
3
3
  */
4
4
 
5
5
  import type { IService } from '../service-registry.ts';
6
- import type { Model } from '@earendil-works/pi-ai';
6
+ import type { Api, Model } from '@earendil-works/pi-ai';
7
7
  import type { ModelRegistry } from '@earendil-works/pi-coding-agent';
8
8
  import type { ResearchObserver } from './observer-interfaces.ts';
9
9
  import type { ResearchPlan, ResearcherConfig } from './research-plan-types.ts';
@@ -27,7 +27,7 @@ export interface GeneratePlanOptions {
27
27
  sessionId: string;
28
28
  query: string;
29
29
  complexity: 1 | 2 | 3;
30
- model: Model<any>;
30
+ model: Model<Api>;
31
31
  modelRegistry: ModelRegistry;
32
32
  cwd: string;
33
33
  signal?: AbortSignal;
@@ -46,7 +46,7 @@ export interface GenerateQueriesOptions {
46
46
  researcher: ResearcherConfig;
47
47
  query: string;
48
48
  complexity: 1 | 2 | 3;
49
- model: Model<any>;
49
+ model: Model<Api>;
50
50
  signal?: AbortSignal;
51
51
  }
52
52
 
@@ -65,7 +65,7 @@ export interface UpdatePlanOptions {
65
65
  round: number;
66
66
  query: string;
67
67
  complexity: 1 | 2 | 3;
68
- model: Model<any>;
68
+ model: Model<Api>;
69
69
  modelRegistry: ModelRegistry;
70
70
  cwd: string;
71
71
  signal?: AbortSignal;
@@ -106,7 +106,7 @@ export interface IPlanningService extends IService {
106
106
  getComplexityGuidance(complexity: 1 | 2 | 3, maxTeamSize: number, queryBudget: number): string;
107
107
  getEvaluatorComplexityGuidance(complexity: 1 | 2 | 3, researchRounds: number): string;
108
108
  getRoundPhaseGuidance(currentRound: number, maxRounds: number, complexity: 1 | 2 | 3, maxTeamSize: number): string;
109
- capResearcherQueries(plan: ResearchPlan, complexity: 1 | 2 | 3, serviceName: string): ResearchPlan;
109
+ capResearcherQueries(plan: ResearchPlan, complexity: 1 | 2 | 3, serviceName: string, singleResearcher?: boolean): ResearchPlan;
110
110
  parseJsonPlan(text: string): ResearchPlan;
111
111
  buildFallbackCoordinatorPlan(rawText: string, query: string): ResearchPlan;
112
112
  clearPlanningState(sessionId?: string): void;
@@ -32,6 +32,6 @@ export interface IProcessLifecycle extends IService {
32
32
  * GPU Resource Service Interface
33
33
  */
34
34
  export interface IGPUResourceService extends IService {
35
- acquireGpuLock(sessionId?: string, timeoutMs?: number, ctx?: any): Promise<boolean>;
36
- releaseGpuLock(pid?: number, ctx?: any): Promise<void>;
35
+ acquireGpuLock(sessionId?: string, timeoutMs?: number, ctx?: unknown): Promise<boolean>;
36
+ releaseGpuLock(pid?: number, ctx?: unknown): Promise<void>;
37
37
  }
@@ -3,6 +3,7 @@
3
3
  */
4
4
 
5
5
  import type { IService } from '../service-registry.ts';
6
+ import type { SingletonState, StateMetrics } from '../../types/state-types.ts';
6
7
 
7
8
  /**
8
9
  * State manager service interface
@@ -16,9 +17,9 @@ export interface IStateManager extends IService {
16
17
  * implement it; callers use `isReadOnly?.()` (absent ⇒ not read-only).
17
18
  */
18
19
  isReadOnly?(): boolean;
19
- readState(): Promise<any>;
20
- writeState(state: any): Promise<void>;
21
- updateState(updater: (state: any) => any | Promise<any>): Promise<void>;
20
+ readState(): Promise<SingletonState>;
21
+ writeState(state: SingletonState): Promise<void>;
22
+ updateState(updater: (state: SingletonState) => SingletonState | Promise<SingletonState>): Promise<void>;
22
23
  addSession(sessionId: string, param: number | string): Promise<void>;
23
24
  removeSession(sessionId: string): Promise<void>;
24
25
  updateHeartbeat(sessionId: string): Promise<void>;
@@ -38,7 +39,7 @@ export interface IStateManager extends IService {
38
39
  isPidAlive(pid: number, expectedSchedulerId?: string, skipLock?: boolean): Promise<boolean>;
39
40
  acquireGpuLock(sessionId?: string, timeoutMs?: number): Promise<boolean>;
40
41
  releaseGpuLock(pid?: number): Promise<void>;
41
- getGpuOwner(): Promise<any | null>;
42
- getMetrics(): Promise<any>;
42
+ getGpuOwner(): Promise<NonNullable<SingletonState['gpuOwner']> | null>;
43
+ getMetrics(): Promise<StateMetrics>;
43
44
  cleanup(): Promise<void>;
44
45
  }
@@ -14,7 +14,7 @@
14
14
  * catch below for why a timeout is not retried where a validation failure is).
15
15
  */
16
16
 
17
- import type { Model, AssistantMessage, SimpleStreamOptions, ModelThinkingLevel } from '@earendil-works/pi-ai';
17
+ import type { Api, Model, AssistantMessage, Message, SimpleStreamOptions, ModelThinkingLevel } from '@earendil-works/pi-ai';
18
18
  import { logger } from '../../logger.ts';
19
19
  import { extractJson } from '../../utils/json-utils.ts';
20
20
  import { withTimeout, getLlmTimeoutMs } from './llm-timeout.ts';
@@ -28,7 +28,7 @@ import { Value } from 'typebox/value';
28
28
  */
29
29
  export interface JsonRepairOptions {
30
30
  /** The model to use for the repair pass */
31
- model: Model<any>;
31
+ model: Model<Api>;
32
32
  /** Original user prompt or context for the repair */
33
33
  context?: string;
34
34
  /** Optional schema for validation after repair */
@@ -65,8 +65,8 @@ export interface JsonRepairOptions {
65
65
  * LLM completion function compatible with `completeSimple` (see ./pi-ai-completion.ts).
66
66
  */
67
67
  export type LlmCompleter = (
68
- model: Model<any>,
69
- context: { systemPrompt?: string; messages: any[] },
68
+ model: Model<Api>,
69
+ context: { systemPrompt?: string; messages: Message[] },
70
70
  options?: SimpleStreamOptions
71
71
  ) => Promise<AssistantMessage>;
72
72
 
@@ -79,7 +79,7 @@ export type LlmCompleter = (
79
79
  * @param options - Repair options
80
80
  * @returns Salvaged object or null if repair fails
81
81
  */
82
- export async function repairJsonWithLlm<T = any>(
82
+ export async function repairJsonWithLlm<T = unknown>(
83
83
  text: string,
84
84
  completer: LlmCompleter,
85
85
  // headers values are string | null to match pi-ai's ProviderHeaders — a null
@@ -185,7 +185,7 @@ Return ONLY the valid JSON object. No prose before or after.`;
185
185
  const coerced = Value.Convert(schema, salvaged);
186
186
  if (!Value.Check(schema, coerced)) {
187
187
  const errors = [...Value.Errors(schema, coerced)];
188
- const errorDetail = errors.map((e: any) => `${e.path}: ${e.message}`).join(', ');
188
+ const errorDetail = errors.map((e: { path?: unknown; message?: string }) => `${e.path}: ${e.message}`).join(', ');
189
189
  logger.warn(`[${serviceName}] Salvage attempt ${attempt} succeeded but validation failed: ${errorDetail}. Salvaged: ${JSON.stringify(salvaged)}, Coerced: ${JSON.stringify(coerced)}`);
190
190
 
191
191
  if (attempt < maxAttempts) {