@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
@@ -64,10 +64,30 @@ export function isRateLimitError(error: unknown): boolean {
64
64
  if (isSpentAccountError(error)) return false;
65
65
  const msg = (error instanceof Error ? error.message : String(error)).toLowerCase();
66
66
  return /\b429\b/.test(msg)
67
+ // A provider that is OVERLOADED says 5xx, and pi passes the status through:
68
+ // "503 Provider returned error"
69
+ // That is as transient as a 429 and must take the same long-wait path. Before
70
+ // this, a 503 fell through to the ordinary 1s/2s curve and killed the run
71
+ // (2026-10-28, eight consecutive runs lost while the search burst had already
72
+ // collected 48-104 results).
73
+ // Anchored to STATUS CONTEXT on purpose. A bare `/\b50[0234]\b/` also matches
74
+ // "took 502ms", "max_tokens=500" and "504 results", and this classifier drives
75
+ // both the retry policy and the run-level stop threshold, so a false positive
76
+ // buys a long wait and stops counting a genuine failure.
77
+ || /\b(?:http|status|code|error|response|returned)\W{0,4}50[0234]\b/i.test(msg)
78
+ || /\b50[0234]\b\W{0,4}(?:provider|service|unavailable|bad|gateway|internal|error|timeout)/i.test(msg)
79
+ || msg.includes('service unavailable')
80
+ || msg.includes('bad gateway')
81
+ || msg.includes('gateway timeout')
67
82
  || msg.includes('rate limit')
68
83
  || msg.includes('rate-limit')
69
84
  || msg.includes('rate limited')
70
85
  || msg.includes('too many requests')
86
+ // pi's own client throws this sentence when the provider's Retry-After is
87
+ // longer than pi's cap. It is a capacity signal, not a bug report:
88
+ // "Server requested 120s retry delay (max: 60s). 503 Provider returned error"
89
+ || msg.includes('retry delay')
90
+ || msg.includes('retry-after')
71
91
  || msg.includes('engine_overloaded')
72
92
  || msg.includes('provider_overloaded');
73
93
  }
@@ -84,8 +104,10 @@ export function isCapacityFailureReason(reason: string | undefined): boolean {
84
104
  }
85
105
 
86
106
  /**
87
- * The `Retry-After` a provider error asked for, in ms, clamped to [5s, 60s], or null when
88
- * the error carries none. Read out of the message because every caller sees a serialized
107
+ * The `Retry-After` a provider error asked for, in ms, clamped to [5s, 180s], or null when
108
+ * the error carries none. 60s is only the EXPONENTIAL ceiling: a stated window is the
109
+ * provider telling us when its pool reopens, so it keeps its full length up to
110
+ * STATED_RETRY_AFTER_MAX_MS. Read out of the message because every caller sees a serialized
89
111
  * provider error, not the raw Response headers: pi's `after_provider_response` hook
90
112
  * (src/index.ts) is the only place with headers, and it does not feed these retry loops.
91
113
  *
@@ -94,11 +116,20 @@ export function isCapacityFailureReason(reason: string | undefined): boolean {
94
116
  */
95
117
  export function parseRetryAfterMs(error: unknown): number | null {
96
118
  const message = error instanceof Error ? error.message : String(error);
97
- const m = /["']?retry-after["']?\s*[:=]\s*["']?(\d{1,4})/i.exec(message);
119
+ // Three shapes are in the wild:
120
+ // 1. `retry-after: 30` — a header echoed into the message
121
+ // 2. `retry after 30s` — prose form
122
+ // 3. `Server requested 120s retry delay (max: 60s). 503 ...`
123
+ // — pi's client refusing a window longer than its own cap. The provider's
124
+ // number is the load-bearing one: it is the ONLY statement of when the
125
+ // pool reopens, and the run has just been told to come back in 120s.
126
+ const m = /["']?retry-after["']?\s*[:=]\s*["']?(\d{1,4})/i.exec(message)
127
+ || /requested\s+(\d{1,4})\s*s(?:ec(?:onds?)?)?\s+retry\s+delay/i.exec(message)
128
+ || /retry\s+after\s+(\d{1,4})\s*s/i.exec(message);
98
129
  if (!m) return null;
99
130
  const seconds = Number(m[1]);
100
131
  if (!Number.isFinite(seconds) || seconds <= 0) return null;
101
- return Math.min(Math.max(seconds, 5), 60) * 1000;
132
+ return Math.min(Math.max(seconds, 5), STATED_RETRY_AFTER_MAX_MS / 1000) * 1000;
102
133
  }
103
134
 
104
135
  /**
@@ -110,12 +141,31 @@ export function parseRetryAfterMs(error: unknown): number | null {
110
141
  export const RATE_LIMIT_BACKOFF_BASE_MS = 15_000;
111
142
 
112
143
  /**
113
- * Ceiling for one rate-limit wait. The provider's own `Retry-After` wins when
114
- * present (clamped by parseRetryAfterMs to 60s); this only bounds the exponential
115
- * fallback, so three retries cost at most 15s + 30s + 60s of waiting.
144
+ * Ceiling for one EXPONENTIAL rate-limit wait. A provider's stated `Retry-After`
145
+ * bypasses this bound (parseRetryAfterMs clamps it to STATED_RETRY_AFTER_MAX_MS
146
+ * instead); this only bounds the exponential fallback, so three retries cost at
147
+ * most 15s + 30s + 60s of waiting.
116
148
  */
117
149
  export const RATE_LIMIT_BACKOFF_MAX_MS = 60_000;
118
150
 
151
+ /**
152
+ * Ceiling for a wait the PROVIDER stated, which is a different thing from the
153
+ * exponential ceiling above. A provider that asks for 120s has told us when its
154
+ * pool reopens. Clamping that to 60s does not make the request succeed — it
155
+ * guarantees the next attempt fails too, and burns one of three attempts to learn
156
+ * nothing. 180s still bounds a run: PI_RESEARCH_TIMEOUT_MS defaults to 900s.
157
+ */
158
+ export const STATED_RETRY_AFTER_MAX_MS = 180_000;
159
+
160
+ /**
161
+ * Total time ONE researcher may spend waiting on provider capacity across its
162
+ * attempts. Three stated 120s windows would be six minutes inside a single
163
+ * researcher, which is most of a run's budget spent on one call. Past this bound
164
+ * the loop stops and says WHEN to rerun, instead of sleeping into the run timeout
165
+ * and reporting a failure with no cause.
166
+ */
167
+ export const RATE_LIMIT_TOTAL_WAIT_MAX_MS = 240_000;
168
+
119
169
  /**
120
170
  * How long to wait before retry `attempt` (2 = first retry).
121
171
  *
@@ -135,7 +185,9 @@ export function rateLimitBackoffMs(
135
185
  random: () => number = Math.random,
136
186
  ): number {
137
187
  if (retryAfterMs !== null && Number.isFinite(retryAfterMs) && retryAfterMs > 0) {
138
- return clampRateLimitWait(retryAfterMs);
188
+ // A stated window keeps its full length up to STATED_RETRY_AFTER_MAX_MS; only
189
+ // the exponential fallback below is bounded by RATE_LIMIT_BACKOFF_MAX_MS.
190
+ return Math.min(Math.max(Math.round(retryAfterMs), 1_000), STATED_RETRY_AFTER_MAX_MS);
139
191
  }
140
192
  const exponent = Math.max(0, attempt - 2);
141
193
  const base = Math.min(RATE_LIMIT_BACKOFF_BASE_MS * Math.pow(2, exponent), RATE_LIMIT_BACKOFF_MAX_MS);
@@ -143,7 +195,7 @@ export function rateLimitBackoffMs(
143
195
  return clampRateLimitWait(base + jitter);
144
196
  }
145
197
 
146
- /** Keep a wait inside [1s, 60s] — the same bounds parseRetryAfterMs applies to a stated window. */
198
+ /** Keep an EXPONENTIAL wait inside [1s, 60s]. A provider-stated window is NOT clamped here. */
147
199
  export function clampRateLimitWait(ms: number): number {
148
200
  return Math.min(Math.max(Math.round(ms), 1_000), RATE_LIMIT_BACKOFF_MAX_MS);
149
201
  }
@@ -6,8 +6,8 @@
6
6
  * repeated `(timer as any).unref()` pattern.
7
7
  */
8
8
  export function safeUnref(timer: NodeJS.Timeout | null | undefined): void {
9
- if (timer && typeof (timer as any).unref === 'function') {
10
- (timer as any).unref();
9
+ if (timer && typeof timer.unref === 'function') {
10
+ timer.unref();
11
11
  }
12
12
  }
13
13
 
@@ -5,15 +5,15 @@ export type CleanupTask = () => Promise<void> | void;
5
5
 
6
6
  // Minimal interface matching Node.js EventEmitter and process
7
7
  interface EventEmitterLike {
8
- on(event: string | symbol, listener: (...args: any[]) => void): any;
9
- off?(event: string | symbol, listener: (...args: any[]) => void): any;
10
- removeListener?(event: string | symbol, listener: (...args: any[]) => void): any;
8
+ on(event: string | symbol, listener: (...args: unknown[]) => void): unknown;
9
+ off?(event: string | symbol, listener: (...args: unknown[]) => void): unknown;
10
+ removeListener?(event: string | symbol, listener: (...args: unknown[]) => void): unknown;
11
11
  }
12
12
 
13
13
  interface EventListenerCleanup {
14
14
  target: EventEmitterLike;
15
15
  event: string;
16
- listener: (...args: any[]) => void;
16
+ listener: (...args: unknown[]) => void;
17
17
  }
18
18
 
19
19
  export class ShutdownManager {
@@ -32,7 +32,7 @@ export class ShutdownManager {
32
32
  registerEventListener<T extends EventEmitterLike>(
33
33
  target: T,
34
34
  event: string,
35
- listener: (...args: any[]) => void
35
+ listener: (...args: unknown[]) => void
36
36
  ) {
37
37
  target.on(event, listener);
38
38
  this.eventListeners.push({ target, event, listener });
@@ -41,7 +41,7 @@ export class ShutdownManager {
41
41
  unregisterEventListener<T extends EventEmitterLike>(
42
42
  target: T,
43
43
  event: string,
44
- listener: (...args: any[]) => void
44
+ listener: (...args: unknown[]) => void
45
45
  ) {
46
46
  if (target.off) {
47
47
  target.off(event, listener);
@@ -233,10 +233,25 @@ export async function captureStdio<T>(
233
233
  const fd1SyncDecoder = new TextDecoder();
234
234
  const fd2SyncDecoder = new TextDecoder();
235
235
 
236
- // Save originals
237
- const originalStderrWrite = process.stderr.write;
238
- const originalStdoutWrite = process.stdout.write;
236
+ // Save originals. Node types the stock write() as an overload whose callback
237
+ // position is a plain callback (no BufferEncoding union), so a direct
238
+ // assignment to StdioWriteFn fails; the structural cast is the honest shape.
239
+ const originalStderrWrite = process.stderr.write as unknown as StdioWriteFn;
240
+ const originalStdoutWrite = process.stdout.write as unknown as StdioWriteFn;
239
241
  const originalFsWriteSync = fs.writeSync;
242
+
243
+ // The shapes of the write functions installed below. Node types the stock
244
+ // write() with `any` chunk/encoding/callback, so these are directly
245
+ // assignable to process.stdout/stderr.write and fs.writeSync.
246
+ type StdioWriteFn = (
247
+ chunk: string | Uint8Array,
248
+ // `string` rather than BufferEncoding: the global encoding union is not
249
+ // importable from 'node:buffer' in this @types/node, and a wider parameter
250
+ // keeps the replacement assignable to the original write signature.
251
+ encodingOrCb?: string | ((err?: Error | null) => void),
252
+ callback?: (err?: Error | null) => void,
253
+ ) => boolean;
254
+ type FsWriteSyncFn = (fd: number, chunk: string | Uint8Array, ...args: unknown[]) => number;
240
255
  const originalConsole = {
241
256
  log: console.log,
242
257
  info: console.info,
@@ -281,7 +296,7 @@ export async function captureStdio<T>(
281
296
  console.debug = createConsolePatch('debug', logFile, hasSufficientDiskSpace);
282
297
 
283
298
  // Patch stderr.write
284
- (process.stderr.write as any) = (chunk: string | Uint8Array, encodingOrCb?: any, callback?: any) => {
299
+ (process.stderr.write as StdioWriteFn) = (chunk: string | Uint8Array, encodingOrCb?: string | ((err?: Error | null) => void), callback?: (err?: Error | null) => void) => {
285
300
  const cb = typeof encodingOrCb === 'function' ? encodingOrCb : callback;
286
301
  const message = typeof chunk === 'string' ? chunk : stderrDecoder.decode(chunk, { stream: true });
287
302
 
@@ -318,7 +333,7 @@ export async function captureStdio<T>(
318
333
  };
319
334
 
320
335
  // Patch stdout.write
321
- (process.stdout.write as any) = (chunk: string | Uint8Array, encodingOrCb?: any, callback?: any) => {
336
+ (process.stdout.write as StdioWriteFn) = (chunk: string | Uint8Array, encodingOrCb?: string | ((err?: Error | null) => void), callback?: (err?: Error | null) => void) => {
322
337
  const message = typeof chunk === 'string' ? chunk : stdoutDecoder.decode(chunk, { stream: true });
323
338
 
324
339
  // Native log patterns or plain text that we want to divert from TUI
@@ -382,7 +397,7 @@ export async function captureStdio<T>(
382
397
  try {
383
398
  const descriptor = Object.getOwnPropertyDescriptor(fs, 'writeSync');
384
399
  if (!descriptor || (descriptor.writable || descriptor.set)) {
385
- fs.writeSync = (fd: number, chunk: any, ...args: any[]) => {
400
+ (fs.writeSync as FsWriteSyncFn) = (fd: number, chunk: string | Uint8Array, ...args: unknown[]) => {
386
401
  if (fd === 1 || fd === 2) {
387
402
  const fdDecoder = fd === 1 ? fd1SyncDecoder : fd2SyncDecoder;
388
403
  const message = typeof chunk === 'string' ? chunk : fdDecoder.decode(chunk, { stream: true });
@@ -395,7 +410,7 @@ export async function captureStdio<T>(
395
410
  // fdDecoder for the completing chunk) must be skipped explicitly to
396
411
  // avoid writing an empty log entry on every mid-character split.
397
412
  if (fd === 2 && message.length === 0) {
398
- return (typeof chunk === 'string' ? Buffer.from(chunk).length : (chunk as any).length);
413
+ return (typeof chunk === 'string' ? Buffer.from(chunk).length : chunk.length);
399
414
  }
400
415
 
401
416
  const isNative = isNativeLog(message);
@@ -409,7 +424,7 @@ export async function captureStdio<T>(
409
424
 
410
425
  if (shouldDivert) {
411
426
  if (!hasSufficientDiskSpace()) {
412
- return (typeof chunk === 'string' ? Buffer.from(chunk).length : (chunk as any).length);
427
+ return (typeof chunk === 'string' ? Buffer.from(chunk).length : chunk.length);
413
428
  }
414
429
 
415
430
  const timestamp = new Date().toISOString();
@@ -422,10 +437,10 @@ export async function captureStdio<T>(
422
437
  try {
423
438
  fs.appendFileSync(logFile, `${safeJsonStringify(entry)}\n`);
424
439
  } catch { /* ignore */ }
425
- return (typeof chunk === 'string' ? Buffer.from(chunk).length : (chunk as any).length);
440
+ return (typeof chunk === 'string' ? Buffer.from(chunk).length : chunk.length);
426
441
  }
427
442
  }
428
- return (originalFsWriteSync as any).apply(fs, [fd, chunk, ...args]);
443
+ return (originalFsWriteSync as FsWriteSyncFn).apply(fs, [fd, chunk, ...args]);
429
444
  };
430
445
  }
431
446
  } catch (_e) { /* ignore */ }
@@ -3,6 +3,41 @@ import type { AssistantMessage } from '@earendil-works/pi-ai';
3
3
  import { logger } from '../logger.ts';
4
4
  import { stripTrailingLlmPunctuation } from './url-utils.ts';
5
5
 
6
+ /**
7
+ * Extract the raw tool results (the content a researcher gathered) from a session.
8
+ *
9
+ * In the raw-scrape synthesis flow the researcher's report-writing turn is skipped: the
10
+ * synthesis corpus is the raw content the researcher gathered (its tool results), not a
11
+ * written report. This collects every non-error tool result's text content, labelled by
12
+ * tool name, in conversation order, so the synthesizer reads the source material directly.
13
+ *
14
+ * @param session - The agent session to read
15
+ * @returns The concatenated tool-result text, empty when there are none
16
+ */
17
+ export function extractToolResults(session: AgentSession): string {
18
+ const parts: string[] = [];
19
+ for (const msg of session.messages) {
20
+ if (msg.role !== 'toolResult') continue;
21
+ const tr = msg as unknown as {
22
+ toolName?: string;
23
+ content?: Array<{ type?: string; text?: string }>;
24
+ isError?: boolean;
25
+ };
26
+ if (tr.isError) continue;
27
+ let text = (tr.content ?? [])
28
+ .map((c) => (c && c.type === 'text' ? String(c.text ?? '') : ''))
29
+ .join('');
30
+ // Strip the "Session URL Pool" footer: it is per-scrape sibling-routing metadata
31
+ // (URLs other researchers scraped), not content, and would be noise in the
32
+ // synthesis corpus. It is appended as `\n---\n## Session URL Pool\n...`.
33
+ text = text.replace(/\n-{3,}\n## Session URL Pool\n[\s\S]*$/, '').trimEnd();
34
+ if (text.trim()) {
35
+ parts.push(`### ${tr.toolName ?? 'tool'}\n${text}`);
36
+ }
37
+ }
38
+ return parts.join('\n\n');
39
+ }
40
+
6
41
  /**
7
42
  * Text Utilities
8
43
  *
@@ -7,6 +7,7 @@
7
7
  import { runWorkerSearch } from '../infrastructure/browser/task-execution-service.ts';
8
8
  import { getMaxWorkers, COLD_START_ALLOWANCE_MS } from '../infrastructure/browser/config.ts';
9
9
  import { isTaskTimeoutError, isNativeBindingError } from '../infrastructure/browser/browser-error-utils.ts';
10
+ import { describeProxyIfBroken } from '../infrastructure/browser/proxy-health.ts';
10
11
  import { logger } from '../logger.ts';
11
12
  import { safeUnref } from '../utils/safe-unref.ts';
12
13
  import { normalizeUrl } from '../utils/url-utils.ts';
@@ -339,9 +340,20 @@ export async function performSearch(
339
340
  );
340
341
  }
341
342
 
343
+ // Name the actual cause when the configured proxy is the cause. Without
344
+ // this the message lists three hypotheses (workers, DuckDuckGo, load) and
345
+ // none of them is "the local SOCKS proxy is a black hole", which is what
346
+ // every one of these failures was between 2026-10-28 and 2026-10-30.
347
+ // Cheap: this branch only runs after a burst has already failed.
348
+ // Pass the run signal: if the caller cancels mid-diagnosis, the two DDG
349
+ // samples plus the neutral check must stop at once, not run to completion.
350
+ const proxyDiagnosis = await describeProxyIfBroken(signal);
342
351
  throw new Error(
343
352
  `Search completely failed: ${reason}. ` +
344
- `Browser workers may be unavailable, DuckDuckGo is unreachable, or the system is under extreme load.` +
353
+ (proxyDiagnosis
354
+ ? `${proxyDiagnosis} Every browser request is routed through the configured proxy, ` +
355
+ `so no search can succeed until it forwards DuckDuckGo traffic or ~/.pi/research/proxy.json is removed.`
356
+ : `Browser workers may be unavailable, DuckDuckGo is unreachable, or the system is under extreme load.`) +
345
357
  (sampleWorkerError ? ` Last worker error: ${sampleWorkerError}` : '')
346
358
  );
347
359
  }
@@ -47,6 +47,17 @@ export interface RetryOptions {
47
47
  * `rateLimitDelayFor` in src/core/planning-service.ts.
48
48
  */
49
49
  readonly delayFor?: (nextAttempt: number, error: Error) => number | null;
50
+ /**
51
+ * Hard ceiling on the SUM of the waits this one call may spend.
52
+ *
53
+ * `delayFor` lets a provider-mandated window (up to 180s) bypass `maxDelay`, which
54
+ * is correct per attempt and unbounded across attempts. The planning/router calls
55
+ * retry up to twice, so two stated 180s windows are six minutes inside a 900s run
56
+ * — most of the budget spent sleeping, and no actionable error at the end of it.
57
+ * Past this bound the call throws the provider's own window and the time to
58
+ * rerun instead of sleeping into the caller's timeout.
59
+ */
60
+ readonly maxTotalDelayMs?: number;
50
61
  }
51
62
 
52
63
  /**
@@ -299,7 +310,7 @@ export async function retryWithBackoff<T>(
299
310
  ): Promise<T> {
300
311
  // `delayFor` stays optional (absent for every caller that does not override the wait),
301
312
  // so it is excluded from the Required<> normalization rather than given a default.
302
- const opts: Required<Omit<RetryOptions, 'signal' | 'delayFor'>> & RetryOptions = {
313
+ const opts: Required<Omit<RetryOptions, 'signal' | 'delayFor' | 'maxTotalDelayMs'>> & RetryOptions = {
303
314
  maxRetries: 3,
304
315
  initialDelay: 1000,
305
316
  maxDelay: 10000,
@@ -311,6 +322,8 @@ export async function retryWithBackoff<T>(
311
322
  const startTime = Date.now();
312
323
  let lastError: Error | null = null;
313
324
  let attempt = 0;
325
+ // Sum of the waits actually slept, for the optional maxTotalDelayMs ceiling.
326
+ let totalDelayMs = 0;
314
327
  metrics.increment('retry_attempts_total', 1, { label: opts.label });
315
328
 
316
329
  while (attempt <= opts.maxRetries) {
@@ -345,6 +358,21 @@ export async function retryWithBackoff<T>(
345
358
  ? Math.round(override)
346
359
  : Math.min(baseDelay + jitter, opts.maxDelay);
347
360
 
361
+ // Bound the TOTAL waiting before sleeping, so a provider that keeps asking
362
+ // for a long window cannot spend the caller's whole timeout here.
363
+ if (opts.maxTotalDelayMs !== undefined && totalDelayMs + delay > opts.maxTotalDelayMs) {
364
+ const retryAt = new Date(Date.now() + delay).toISOString().slice(11, 19);
365
+ metrics.increment('retry_total_delay_exhausted_total', 1, { label: opts.label });
366
+ throw new Error(
367
+ `Provider capacity: ${opts.label} asked for a ${Math.round(delay / 1000)}s wait, but only `
368
+ + `${Math.max(0, Math.round((opts.maxTotalDelayMs - totalDelayMs) / 1000))}s of its `
369
+ + `${Math.round(opts.maxTotalDelayMs / 1000)}s total-wait budget is left. Rerun after ${retryAt}Z. `
370
+ + `Cause: ${lastError.message}`,
371
+ { cause: error },
372
+ );
373
+ }
374
+ totalDelayMs += delay;
375
+
348
376
  metrics.increment('retry_backoff_total', 1, { attempt: String(attempt), label: opts.label });
349
377
  metrics.observe('retry_backoff_delay_ms', delay, { attempt: String(attempt), label: opts.label });
350
378
  logger.warn(`[Retry] ${opts.label} failed (attempt ${attempt + 1}/${opts.maxRetries + 1}), retrying in ${Math.round(delay)}ms: ${lastError.message}`);
@@ -4,6 +4,7 @@
4
4
 
5
5
  import * as dns from 'node:dns/promises';
6
6
  import * as dnsCb from 'node:dns';
7
+ import type { LookupFunction } from 'node:net';
7
8
  import * as net from 'node:net';
8
9
  import crypto from 'node:crypto';
9
10
  import { NodeHtmlMarkdown } from 'node-html-markdown';
@@ -190,9 +191,11 @@ export async function validateUrlForSSRF(url: string): Promise<void> {
190
191
  export function ssrfSafeLookup(
191
192
  hostname: string,
192
193
  options: dnsCb.LookupAllOptions | dnsCb.LookupOneOptions | number | undefined,
193
- callback: (err: NodeJS.ErrnoException | null, address?: any, family?: number) => void,
194
+ callback: (err: NodeJS.ErrnoException | null, address?: string | dnsCb.LookupAddress[], family?: number) => void,
194
195
  // Resolver is injectable for tests; undici calls with the standard 3 args.
195
- resolveImpl: (hostname: string, opts: dnsCb.LookupAllOptions, cb: (err: NodeJS.ErrnoException | null, addresses: dnsCb.LookupAddress[]) => void) => void = dnsCb.lookup as any,
196
+ // `dnsCb.lookup` is an overload set; pin the all-lookup signature this
197
+ // wrapper always invokes.
198
+ resolveImpl: (hostname: string, opts: dnsCb.LookupAllOptions, cb: (err: NodeJS.ErrnoException | null, addresses: dnsCb.LookupAddress[]) => void) => void = dnsCb.lookup as (hostname: string, opts: dnsCb.LookupAllOptions, cb: (err: NodeJS.ErrnoException | null, addresses: dnsCb.LookupAddress[]) => void) => void,
196
199
  ): void {
197
200
  const family = typeof options === 'number' ? options : (options?.family ?? 0);
198
201
  const wantsAll = typeof options === 'object' && options?.all === true;
@@ -293,7 +296,10 @@ export function getSsrfSafeFetcher(): Promise<SsrfSafeFetcher | null> {
293
296
  const { Agent, fetch: undiciFetch } = await import('undici');
294
297
  return {
295
298
  fetch: undiciFetch as unknown as SsrfSafeFetcher['fetch'],
296
- dispatcher: new Agent({ connect: { lookup: ssrfSafeLookup } }),
299
+ // node:net's LookupFunction pins the callback to `string | LookupAddress[]`
300
+ // (no undefined); the wrapper's callback allows undefined for the single
301
+ // resolution, so the two signatures differ by exactly that — a double cast.
302
+ dispatcher: new Agent({ connect: { lookup: ssrfSafeLookup as unknown as LookupFunction } }),
297
303
  };
298
304
  } catch (e) {
299
305
  logger.warn(`[Scrapers] undici unavailable; connect-time SSRF pinning disabled (request-time validation still active): ${e instanceof Error ? e.message : String(e)}`);
@@ -34,6 +34,17 @@ import { cacheScrapedContent } from '../utils/shared-links.ts';
34
34
  // identical in-process fallback); same export name and contract as before.
35
35
  import { extractPdfToMarkdown } from './pdf-extraction.ts';
36
36
 
37
+ /**
38
+ * The browser worker's scrape result shape. `buffer` is the pre-bufferB64
39
+ * legacy shape (a raw Uint8Array, or the JSON-roundtripped {type:'Buffer',
40
+ * data:[...]}), kept so a mixed-version leader/follower pair keeps working.
41
+ */
42
+ type BrowserScrapeResult = {
43
+ buffer?: unknown;
44
+ bufferB64?: string;
45
+ html?: string;
46
+ };
47
+
37
48
  /** Backoff before the fetch layer's single transient retry. */
38
49
  const FETCH_RETRY_DELAY_MS = 250;
39
50
 
@@ -321,7 +332,7 @@ async function scrapeWithFetch(url: string, signal?: AbortSignal): Promise<Scrap
321
332
  async function scrapeWithStealthBrowser(_url: string, config?: Config, signal?: AbortSignal, sessionId?: string, container: ServiceContainer = getServiceContainer()): Promise<ScrapeLayerResult> {
322
333
  const browserStart = Date.now();
323
334
  try {
324
- const result = await runBrowserTask<any>({ url: _url, sessionId }, 'scrape', config, signal, 1, container);
335
+ const result = await runBrowserTask<BrowserScrapeResult>({ url: _url, sessionId }, 'scrape', config, signal, 1, container);
325
336
  const browserDuration = Date.now() - browserStart;
326
337
 
327
338
  // PDF bytes travel base64-encoded (bufferB64): the worker result crosses the
@@ -331,15 +342,19 @@ async function scrapeWithStealthBrowser(_url: string, config?: Config, signal?:
331
342
  // extraction ran on nothing and its error string was cached as a "success".
332
343
  // The JSON-roundtripped legacy shape is still decoded so a mixed-version
333
344
  // leader/follower pair keeps working.
334
- const legacyBuffer = result.buffer;
335
- const pdfBytes: Buffer | null =
336
- typeof result.bufferB64 === 'string'
337
- ? Buffer.from(result.bufferB64, 'base64')
338
- : Array.isArray(legacyBuffer?.data)
339
- ? Buffer.from(legacyBuffer.data)
340
- : legacyBuffer instanceof Uint8Array
341
- ? Buffer.from(legacyBuffer)
342
- : null;
345
+ // `buffer` is the pre-bufferB64 legacy shape (a raw Uint8Array, or the
346
+ // JSON-roundtripped {type:'Buffer',data:[...]}); narrow it for the decodes below.
347
+ const legacyBuffer = result.buffer as { data?: number[] } | Uint8Array | null | undefined;
348
+ let pdfBytes: Buffer | null;
349
+ if (typeof result.bufferB64 === 'string') {
350
+ pdfBytes = Buffer.from(result.bufferB64, 'base64');
351
+ } else if (legacyBuffer && !(legacyBuffer instanceof Uint8Array) && Array.isArray(legacyBuffer.data)) {
352
+ pdfBytes = Buffer.from(legacyBuffer.data);
353
+ } else if (legacyBuffer instanceof Uint8Array) {
354
+ pdfBytes = Buffer.from(legacyBuffer);
355
+ } else {
356
+ pdfBytes = null;
357
+ }
343
358
 
344
359
  if (pdfBytes !== null) {
345
360
  const markdown = await extractPdfToMarkdown(pdfBytes);