@lincoln504/pi-research 1.7.23 → 1.7.24

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.
@@ -0,0 +1,342 @@
1
+ /**
2
+ * Liveness probe for the configured SOCKS proxy.
3
+ *
4
+ * WHY THIS EXISTS
5
+ *
6
+ * `~/.pi/research/proxy.json` routes EVERY browser request through a local
7
+ * SOCKS5 proxy. Until this module, nothing verified that the proxy actually
8
+ * forwards traffic: the health registry only checked that the browser is
9
+ * installed, and the browser runtime check returns "ready (idle)" without
10
+ * probing when the scheduler is idle. On 2026-10-29 the shipped proxy
11
+ * (1.7.23) accepted the SOCKS handshake, connected upstream, and forwarded
12
+ * nothing — a one-directional `pipeline()` — and the only symptom was
13
+ * "Search completely failed: all 36 queries encountered worker errors" seven
14
+ * minutes later, with `health` reporting "All systems operational".
15
+ *
16
+ * The probe speaks the protocol the browser speaks: SOCKS5 no-auth greeting,
17
+ * CONNECT to an ordinary public host, one minimal HTTP request, and then it
18
+ * requires at least one byte BACK. A tunnel that connects but never returns a
19
+ * byte is the exact regression, so a connect-only check would not catch it.
20
+ *
21
+ * It is deliberately narrow: one host, one request, a few seconds. It is not a
22
+ * substitute for the DuckDuckGo readiness probe; it answers "is the proxy
23
+ * moving bytes", which is a different question from "is search working".
24
+ */
25
+
26
+ import net from 'node:net';
27
+ import { getSocksProxyEndpoint, type SocksProxyEndpoint } from './proxy-prefs.ts';
28
+
29
+ export type ProxyProbeCode =
30
+ | 'ok'
31
+ | 'not-configured'
32
+ | 'unreachable'
33
+ | 'handshake-rejected'
34
+ | 'connect-rejected'
35
+ | 'no-data'
36
+ | 'protocol-error'
37
+ /** The caller's AbortSignal fired. Not a verdict on the proxy. */
38
+ | 'aborted';
39
+
40
+ export interface ProxyProbeResult {
41
+ readonly healthy: boolean;
42
+ readonly code: ProxyProbeCode;
43
+ readonly reason: string;
44
+ readonly endpoint: SocksProxyEndpoint | null;
45
+ readonly latencyMs: number;
46
+ }
47
+
48
+ export interface ProxyProbeOptions {
49
+ /** TCP connect + SOCKS handshake deadline. */
50
+ readonly timeoutMs?: number;
51
+ /** How long to wait for the first upstream byte after CONNECT succeeds. */
52
+ readonly dataTimeoutMs?: number;
53
+ /** Host:port the probe asks the proxy to reach. */
54
+ readonly targetHost?: string;
55
+ readonly targetPort?: number;
56
+ /** Cancel the probe. An aborted probe returns code 'aborted', not 'unhealthy'. */
57
+ readonly signal?: AbortSignal;
58
+ }
59
+
60
+ const DEFAULT_TIMEOUT_MS = 5_000;
61
+ const DEFAULT_DATA_TIMEOUT_MS = 8_000;
62
+ // DuckDuckGo's own front door on plain HTTP, deliberately NOT example.com: the
63
+ // proxy pins *.duckduckgo.com addresses and rotates past a dead pin. A probe to
64
+ // example.com resolves with ordinary DNS and never touches a pin, so it cannot
65
+ // catch the failure this proxy has actually had (both pins dying at once). DDG
66
+ // answers port 80 with a 301, and the probe only needs one byte back.
67
+ const DEFAULT_TARGET_HOST = 'lite.duckduckgo.com';
68
+ const DEFAULT_TARGET_PORT = 80;
69
+ /** The neutral fallback target used to separate "proxy broken" from "DDG unreachable". */
70
+ export const NEUTRAL_TARGET_HOST = 'example.com';
71
+ export const NEUTRAL_TARGET_PORT = 80;
72
+
73
+ function fail(
74
+ code: ProxyProbeCode,
75
+ reason: string,
76
+ endpoint: SocksProxyEndpoint | null,
77
+ startedAt: number,
78
+ ): ProxyProbeResult {
79
+ return { healthy: false, code, reason, endpoint, latencyMs: Date.now() - startedAt };
80
+ }
81
+
82
+ /**
83
+ * Ask the proxy for one page and require bytes back.
84
+ * Never throws: every failure is a classified result.
85
+ */
86
+ export function probeSocksProxyForwarding(
87
+ endpoint: SocksProxyEndpoint | null = getSocksProxyEndpoint(),
88
+ options: ProxyProbeOptions = {},
89
+ ): Promise<ProxyProbeResult> {
90
+ const startedAt = Date.now();
91
+ if (!endpoint) {
92
+ return Promise.resolve({
93
+ healthy: true,
94
+ code: 'not-configured',
95
+ reason: 'no SOCKS proxy configured (browser connects directly)',
96
+ endpoint: null,
97
+ latencyMs: 0,
98
+ });
99
+ }
100
+
101
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
102
+ const dataTimeoutMs = options.dataTimeoutMs ?? DEFAULT_DATA_TIMEOUT_MS;
103
+ const targetHost = options.targetHost ?? DEFAULT_TARGET_HOST;
104
+ const targetPort = options.targetPort ?? DEFAULT_TARGET_PORT;
105
+ const where = `${endpoint.host}:${endpoint.port}`;
106
+
107
+ return new Promise<ProxyProbeResult>((resolve) => {
108
+ const socket = net.connect({ host: endpoint.host, port: endpoint.port });
109
+ let stage: 'greet' | 'connect' | 'data' = 'greet';
110
+ let settled = false;
111
+ let buffer = Buffer.alloc(0);
112
+ // Declared before `finish` so the already-aborted path can clear them without
113
+ // a temporal-dead-zone ReferenceError.
114
+ let connectTimer: ReturnType<typeof setTimeout> | undefined;
115
+ let dataTimer: ReturnType<typeof setTimeout> | undefined;
116
+
117
+ const onAbort = () => {
118
+ finish(fail('aborted', 'proxy probe cancelled by the caller', endpoint, startedAt));
119
+ };
120
+
121
+ const finish = (result: ProxyProbeResult) => {
122
+ if (settled) return;
123
+ settled = true;
124
+ clearTimeout(connectTimer);
125
+ clearTimeout(dataTimer);
126
+ options.signal?.removeEventListener('abort', onAbort);
127
+ socket.destroy();
128
+ resolve(result);
129
+ };
130
+
131
+ // A probe runs at the START of a run and on the health path, both of which a
132
+ // user can cancel. Without this, Esc during a dead proxy's 3s+4s+3s+4s probe
133
+ // sequence did nothing until the sequence finished.
134
+ if (options.signal?.aborted) {
135
+ onAbort();
136
+ return;
137
+ }
138
+ options.signal?.addEventListener('abort', onAbort, { once: true });
139
+
140
+ connectTimer = setTimeout(() => {
141
+ finish(fail(
142
+ stage === 'greet' ? 'unreachable' : 'no-data',
143
+ stage === 'greet'
144
+ ? `proxy at ${where} did not accept a TCP connection within ${timeoutMs}ms`
145
+ : `proxy at ${where} accepted the connection but did not answer within ${timeoutMs}ms`,
146
+ endpoint,
147
+ startedAt,
148
+ ));
149
+ }, timeoutMs);
150
+ connectTimer.unref?.();
151
+
152
+ // Armed only after the success reply, so it measures the thing that broke:
153
+ // the proxy said "connected" and then delivered nothing.
154
+ const armDataTimer = () => {
155
+ dataTimer = setTimeout(() => {
156
+ finish(fail(
157
+ 'no-data',
158
+ `proxy at ${where} completed the SOCKS handshake to ${targetHost}:${targetPort} `
159
+ + `but returned no data within ${dataTimeoutMs}ms `
160
+ + '(the tunnel is not forwarding answers — check that the proxy process is running the current script and restart it)',
161
+ endpoint,
162
+ startedAt,
163
+ ));
164
+ }, dataTimeoutMs);
165
+ dataTimer.unref?.();
166
+ };
167
+
168
+ socket.on('connect', () => {
169
+ socket.write(Buffer.from([0x05, 0x01, 0x00])); // SOCKS5, one method: no auth
170
+ });
171
+
172
+ socket.on('data', (chunk: Buffer) => {
173
+ if (settled) return;
174
+ buffer = Buffer.concat([buffer, chunk]);
175
+
176
+ if (stage === 'greet') {
177
+ if (buffer.length < 2) return;
178
+ if (buffer[0] !== 0x05 || buffer[1] !== 0x00) {
179
+ finish(fail(
180
+ 'protocol-error',
181
+ `proxy at ${where} answered the SOCKS greeting with [${[...buffer.subarray(0, 2)]}] instead of [5,0]`,
182
+ endpoint,
183
+ startedAt,
184
+ ));
185
+ return;
186
+ }
187
+ buffer = buffer.subarray(2);
188
+ const hostBytes = Buffer.from(targetHost, 'utf8');
189
+ socket.write(Buffer.concat([
190
+ Buffer.from([0x05, 0x01, 0x00, 0x03, hostBytes.length]),
191
+ hostBytes,
192
+ Buffer.from([(targetPort >> 8) & 0xff, targetPort & 0xff]),
193
+ ]));
194
+ stage = 'connect';
195
+ return;
196
+ }
197
+
198
+ if (stage === 'connect') {
199
+ if (buffer.length < 4) return;
200
+ if (buffer[0] !== 0x05) {
201
+ finish(fail('protocol-error', `proxy at ${where} answered the SOCKS request malformed`, endpoint, startedAt));
202
+ return;
203
+ }
204
+ const reply = buffer[1];
205
+ if (reply !== 0x00) {
206
+ const meaning = reply === 0x02
207
+ ? 'refused by ruleset'
208
+ : reply === 0x03 ? 'network unreachable'
209
+ : reply === 0x04 ? 'host unreachable'
210
+ : reply === 0x05 ? 'connection refused by the target' : `SOCKS error ${reply}`;
211
+ finish(fail(
212
+ 'connect-rejected',
213
+ `proxy at ${where} refused CONNECT to ${targetHost}:${targetPort} (${meaning})`,
214
+ endpoint,
215
+ startedAt,
216
+ ));
217
+ return;
218
+ }
219
+ // Consume the bound-address field so leftover bytes cannot be mistaken
220
+ // for the response body of the request below.
221
+ const atyp = buffer[3];
222
+ let addrLen: number;
223
+ if (atyp === 0x01) {
224
+ addrLen = 4;
225
+ } else if (atyp === 0x04) {
226
+ addrLen = 16;
227
+ } else if (atyp === 0x03) {
228
+ if (buffer.length < 5) return; // the domain-length byte is not in yet
229
+ addrLen = 1 + (buffer[4] ?? 0);
230
+ } else {
231
+ finish(fail('protocol-error', `proxy at ${where} answered CONNECT with unknown address type ${atyp}`, endpoint, startedAt));
232
+ return;
233
+ }
234
+ const replyLen = 4 + addrLen + 2;
235
+ if (buffer.length < replyLen) return;
236
+ buffer = buffer.subarray(replyLen);
237
+ // The handshake is over: the connect deadline must not keep ticking while
238
+ // we wait for the response, or a short connect budget would masquerade as
239
+ // "no data". The data deadline takes over.
240
+ clearTimeout(connectTimer);
241
+ socket.write(
242
+ `GET / HTTP/1.0\r\nHost: ${targetHost}\r\nConnection: close\r\n\r\n`,
243
+ );
244
+ stage = 'data';
245
+ armDataTimer();
246
+ // A pipelined byte that arrived with the reply counts as data.
247
+ if (buffer.length > 0) {
248
+ finish({
249
+ healthy: true,
250
+ code: 'ok',
251
+ reason: `proxy at ${where} forwards traffic (first byte in ${Date.now() - startedAt}ms)`,
252
+ endpoint,
253
+ latencyMs: Date.now() - startedAt,
254
+ });
255
+ }
256
+ return;
257
+ }
258
+
259
+ finish({
260
+ healthy: true,
261
+ code: 'ok',
262
+ reason: `proxy at ${where} forwards traffic (first byte in ${Date.now() - startedAt}ms)`,
263
+ endpoint,
264
+ latencyMs: Date.now() - startedAt,
265
+ });
266
+ });
267
+
268
+ socket.on('error', (err: NodeJS.ErrnoException) => {
269
+ const detail = err.code === 'ECONNREFUSED'
270
+ ? 'nothing is listening there — is the proxy service running?'
271
+ : err.message;
272
+ finish(fail('unreachable', `proxy at ${where} is unusable: ${detail}`, endpoint, startedAt));
273
+ });
274
+
275
+ socket.on('close', () => {
276
+ finish(fail(
277
+ 'no-data',
278
+ `proxy at ${where} closed the tunnel before returning data`,
279
+ endpoint,
280
+ startedAt,
281
+ ));
282
+ });
283
+ });
284
+ }
285
+
286
+ /**
287
+ * A one-line diagnosis to append to a run-level search failure, or null when the
288
+ * proxy is healthy/not configured. Kept separate from the probe used by the
289
+ * health registry: this one is bounded tighter, because it runs while the user
290
+ * is already waiting for an error.
291
+ */
292
+ export interface ProxyDiagnosisOptions {
293
+ /** Per-probe connect deadline. Default 3s. */
294
+ readonly timeoutMs?: number;
295
+ /** Per-probe first-byte deadline. Default 3s (4s on the second sample). */
296
+ readonly dataTimeoutMs?: number;
297
+ }
298
+
299
+ export async function describeProxyIfBroken(
300
+ signal?: AbortSignal,
301
+ options: ProxyDiagnosisOptions = {},
302
+ ): Promise<string | null> {
303
+ const endpoint = getSocksProxyEndpoint();
304
+ if (!endpoint) return null;
305
+ const opts = {
306
+ timeoutMs: options.timeoutMs ?? 3_000,
307
+ dataTimeoutMs: options.dataTimeoutMs ?? 3_000,
308
+ signal,
309
+ } as const;
310
+
311
+ // TWO attempts against DuckDuckGo. This verdict STOPS a run, so it must not rest
312
+ // on one sample: a single refused connect during a proxy restart, or one
313
+ // oversized response, would abort work the next probe would have cleared. A
314
+ // genuinely dead or one-way tunnel fails both attempts.
315
+ let last = await probeSocksProxyForwarding(endpoint, opts);
316
+ if (last.code === 'aborted') return null;
317
+ if (!last.healthy) {
318
+ last = await probeSocksProxyForwarding(endpoint, {
319
+ ...opts,
320
+ dataTimeoutMs: (options.dataTimeoutMs ?? 4_000),
321
+ });
322
+ if (last.code === 'aborted') return null;
323
+ }
324
+ if (last.healthy) return null;
325
+
326
+ // DDG failed twice. Before blaming the proxy, ask it for a neutral host: that
327
+ // separates "the tunnel is dead" from "the tunnel works but DDG is blocked or
328
+ // its pins are dead". Both stop a run, but only one is fixed by restarting the
329
+ // proxy, and the message should say which.
330
+ const neutral = await probeSocksProxyForwarding(endpoint, {
331
+ ...opts,
332
+ targetHost: NEUTRAL_TARGET_HOST,
333
+ targetPort: NEUTRAL_TARGET_PORT,
334
+ });
335
+ if (neutral.code === 'aborted') return null;
336
+ if (neutral.healthy) {
337
+ return 'SOCKS proxy check: the proxy forwards traffic to example.com, but DuckDuckGo is '
338
+ + `unreachable through it (${last.reason}). The tunnel works; the pinned DuckDuckGo front `
339
+ + 'doors are not answering. Update DDG_PIN_IPS in the proxy service or remove ~/.pi/research/proxy.json.';
340
+ }
341
+ return `SOCKS proxy check: ${last.reason}. The proxy did not forward traffic to example.com either, so the tunnel itself is broken.`;
342
+ }
@@ -7,6 +7,7 @@
7
7
  import type { ExtensionContext, AgentToolResult } from '@earendil-works/pi-coding-agent';
8
8
  import { type Model } from '@earendil-works/pi-ai';
9
9
  import { logger } from '../logger.ts';
10
+ import { describeProxyIfBroken } from '../infrastructure/browser/proxy-health.ts';
10
11
  import { metrics } from '../utils/metrics.ts';
11
12
  import { getSteeringMessages, consumeQueuedMessages, getActiveSteeringMessages, getFailedResearchers, getResearcherFailureReasons, shouldStopResearch, createResearchStopError, hasOnlyCapacityFailures } from './session-state.ts';
12
13
  import { MAX_EXTRA_ROUNDS_WITH_STEERING, MIN_SYNTHESIS_PROSE_CHARS, SYNTHESIS_FALLBACK_NOTICE, resolveExcludedTools } from '../constants.ts';
@@ -150,6 +151,26 @@ export class DeepResearchOrchestrator {
150
151
  // which already passes ctx).
151
152
  await orchestrationService.cleanupResearchServices(undefined, researchId, ctx, this.config);
152
153
 
154
+ // A configured-but-broken SOCKS proxy fails EVERY browser request. Only the
155
+ // UI health gate and the quick orchestrator run a pre-flight check; a deep
156
+ // run has no such gate, so without this the whole search burst is spent
157
+ // first (36 queries, ~7 minutes on 2026-10-30) and then dies with the
158
+ // generic "Search completely failed". One probe costs seconds.
159
+ //
160
+ // Bounded generously (3s connect + 3-4s data, then a neutral-host check): the
161
+ // point is to catch a dead or one-way tunnel, not to convict a proxy that is
162
+ // merely slow on a loaded box.
163
+ // The run signal is passed through so Esc during a dead proxy's probe sequence
164
+ // cancels immediately instead of waiting out both attempts.
165
+ const proxyDiagnosis = await describeProxyIfBroken(signal);
166
+ if (signal?.aborted) return '';
167
+ if (proxyDiagnosis) {
168
+ throw new Error(
169
+ `Research cannot start: ${proxyDiagnosis} ` +
170
+ 'Repair or remove ~/.pi/research/proxy.json (docs/TROUBLESHOOTING.md), then rerun.',
171
+ );
172
+ }
173
+
153
174
  logger.log(`[DeepOrchestrator] Starting multi-round research (complexity ${complexity}) for: "${query}" (Run: ${researchId})`);
154
175
  metrics.increment('research_sessions_total', 1, { mode: 'deep', complexity: String(complexity) });
155
176
 
@@ -24,7 +24,7 @@ import { isAbortSentinel, boundSessionAbort } from './abort-utils.ts';
24
24
  import type { RunResearcherOptions } from './orchestration-types.ts';
25
25
  import { search } from '../web-research/search.ts';
26
26
  import { RESEARCHER_DIGEST_SECTION } from '../utils/coverage-digest.ts';
27
- import { isRateLimitError, isSpentAccountError, parseRetryAfterMs, rateLimitBackoffMs } from '../utils/provider-errors.ts';
27
+ import { isRateLimitError, isSpentAccountError, parseRetryAfterMs, rateLimitBackoffMs, RATE_LIMIT_TOTAL_WAIT_MAX_MS } from '../utils/provider-errors.ts';
28
28
 
29
29
  /**
30
30
  * Failures a retry cannot fix, because the next attempt sends the same request to
@@ -233,6 +233,11 @@ export async function runResearcher(options: RunResearcherOptions): Promise<void
233
233
  // rate limit: the next backoff uses the provider's Retry-After (or the long
234
234
  // rate-limit step) instead of the small exponential 1-2s step.
235
235
  let inFlightBackoffMs: number | null = null;
236
+ // Provider-capacity waits already spent by THIS researcher. Bounds the case the
237
+ // rate-limit path made possible: a provider stating a long window on every
238
+ // attempt ("requested 120s retry delay"), which would otherwise spend most of a
239
+ // run's budget sleeping inside one researcher.
240
+ let capacityWaitSpentMs = 0;
236
241
 
237
242
  for (let attempt = 1; attempt <= maxAttempts; attempt++) {
238
243
  // Launch boundary: never build a session for a run that is already cancelled
@@ -638,6 +643,28 @@ export async function runResearcher(options: RunResearcherOptions): Promise<void
638
643
  metrics.increment('researcher_rate_limit_backoff_total', 1, { mode: 'deep', complexity: String(complexity) });
639
644
  logger.warn(`[ResearcherExecutor] Researcher ${id} hit a provider rate limit; backing off ${inFlightBackoffMs}ms before attempt ${attempt + 1}`);
640
645
  }
646
+
647
+ // Bound total capacity waiting, and FAIL WITH A TIME when the bound is the
648
+ // reason. `break` (not throw) so the loop's own lastError wins and every
649
+ // caller keeps its existing failure classification. Issue #22: eight runs
650
+ // died on 3 x 1s/2s retries against a provider that had asked for 120s.
651
+ if (inFlightBackoffMs !== null) {
652
+ const remainingBudgetMs = RATE_LIMIT_TOTAL_WAIT_MAX_MS - capacityWaitSpentMs;
653
+ if (inFlightBackoffMs > remainingBudgetMs) {
654
+ const windowSeconds = Math.ceil(inFlightBackoffMs / 1000);
655
+ const retryAt = new Date(Date.now() + inFlightBackoffMs).toISOString().slice(11, 19);
656
+ lastError = new Error(
657
+ `Provider capacity: it asked for a ${windowSeconds}s cool-off, but this researcher ` +
658
+ `has only ${Math.max(0, Math.round(remainingBudgetMs / 1000))}s of its ` +
659
+ `${Math.round(RATE_LIMIT_TOTAL_WAIT_MAX_MS / 1000)}s capacity-wait budget left. ` +
660
+ `Rerun after ${retryAt}Z. Cause: ${errMsg}`,
661
+ );
662
+ logger.error(`[ResearcherExecutor] Researcher ${id} stopping instead of waiting ${inFlightBackoffMs}ms (capacity budget exhausted); rerun after ${retryAt}Z`);
663
+ metrics.increment('researcher_capacity_budget_exhausted_total', 1, { mode: 'deep', complexity: String(complexity) });
664
+ break;
665
+ }
666
+ capacityWaitSpentMs += inFlightBackoffMs;
667
+ }
641
668
  }
642
669
 
643
670
  if (attempt < maxAttempts) {
@@ -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
  }
@@ -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}`);