@lincoln504/pi-research 1.7.22 → 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.
@@ -29,6 +29,9 @@
29
29
 
30
30
  import net from 'node:net';
31
31
  import dns from 'node:dns';
32
+ import { pipeline } from 'node:stream';
33
+ import { realpathSync } from 'node:fs';
34
+ import { fileURLToPath } from 'node:url';
32
35
  import { isBlockedDestination, isBlockedProxyTarget } from './lib/private-addresses.mjs';
33
36
 
34
37
  const PORT = Number(process.env.DDG_SOCKS_PORT || 1080);
@@ -77,9 +80,15 @@ const DATA_DEADLINE_MS = 8000;
77
80
  * so the NEXT connection starts at the next front-door. The caller passes the
78
81
  * client socket precisely so it can be cut on that path.
79
82
  */
80
- function connectWithFallback(client, addrs, port, cb) {
83
+ function connectWithFallback(client, host, addrs, port, cb) {
81
84
  let settled = false;
82
85
  let attempts = 0;
86
+ // Only DuckDuckGo front-doors rotate: for any other destination the address
87
+ // list comes from DNS and a "starting index" has no meaning, so a refused
88
+ // connection to an arbitrary host must not shift the pin order.
89
+ const rotate = (usedIdx) => {
90
+ if (isDdgHost(host)) pinIndex = (usedIdx + 1) % addrs.length;
91
+ };
83
92
  const tryNext = () => {
84
93
  if (settled) return;
85
94
  if (attempts >= addrs.length) {
@@ -96,7 +105,7 @@ function connectWithFallback(client, addrs, port, cb) {
96
105
  // Fast-fail both ends and rotate the starting pin for next time.
97
106
  sock.destroy();
98
107
  client.destroy();
99
- pinIndex = (usedIdx + 1) % addrs.length;
108
+ rotate(usedIdx);
100
109
  console.error(`[ddg-socks] ${addr} connected but sent no data within ${DATA_DEADLINE_MS}ms — client cut, rotating pin`);
101
110
  return;
102
111
  }
@@ -126,7 +135,7 @@ function connectWithFallback(client, addrs, port, cb) {
126
135
  if (!settled) {
127
136
  // Connection refusal / reset — this address is dead from this egress
128
137
  // too; rotate past it for the next connection, same as a stall.
129
- pinIndex = (usedIdx + 1) % addrs.length;
138
+ rotate(usedIdx);
130
139
  tryNext();
131
140
  }
132
141
  });
@@ -141,7 +150,13 @@ const server = net.createServer((client) => {
141
150
  let targetHost = '';
142
151
  let targetPort = 0;
143
152
 
144
- client.on('data', (chunk) => {
153
+ const onData = (chunk) => {
154
+ // Cap the handshake buffer: a well-formed SOCKS request is under 300
155
+ // bytes. Anything larger is not a handshake and must not accumulate.
156
+ if (buf.length + chunk.length > 4096) {
157
+ client.destroy();
158
+ return;
159
+ }
145
160
  buf = Buffer.concat([buf, chunk]);
146
161
  try {
147
162
  if (stage === 'greet') {
@@ -193,13 +208,19 @@ const server = net.createServer((client) => {
193
208
  }
194
209
  if (stage === 'connect') {
195
210
  stage = 'done';
211
+ // Handshake complete: the tunnel below owns the stream from here on.
212
+ // Detach this listener, or `buf` would grow without bound for the
213
+ // lifetime of every long-lived proxied connection.
214
+ client.removeListener('data', onData);
196
215
  // SSRF backstop for proxied traffic. The browser cannot check this itself through
197
216
  // a SOCKS5 proxy (Firefox reports 0.0.0.0 as the origin address — see
198
217
  // src/infrastructure/browser/proxy-prefs.ts), so the proxy is the last place that
199
218
  // can refuse to reach internal infrastructure. A hostile page that gets the
200
219
  // browser to request http://169.254.169.254/ or http://127.0.0.1:8443/ lands here.
201
220
  if (isBlockedProxyTarget(targetHost)) {
202
- console.error(`[ddg-socks] refused private/reserved destination ${targetHost}:${targetPort}`);
221
+ // JSON.stringify: targetHost is raw domain bytes from a SOCKS
222
+ // client and may carry newlines (log injection).
223
+ console.error(`[ddg-socks] refused private/reserved destination ${JSON.stringify(targetHost)}:${targetPort}`);
203
224
  client.write(Buffer.from([0x05, 0x02, 0x00, 0x01, 0, 0, 0, 0, 0, 0])); // not allowed by ruleset
204
225
  client.destroy();
205
226
  return;
@@ -210,7 +231,7 @@ const server = net.createServer((client) => {
210
231
  // The DDG pins are public by construction, so they pass this check too — no
211
232
  // hostname-based bypass, because a bypass is what an attacker would aim for.
212
233
  if (isBlockedDestination(addr)) {
213
- console.error(`[ddg-socks] refused ${targetHost} — resolves to private/reserved ${addr}`);
234
+ console.error(`[ddg-socks] refused ${JSON.stringify(targetHost)} — resolves to private/reserved ${addr}`);
214
235
  return false;
215
236
  }
216
237
  return true;
@@ -220,21 +241,33 @@ const server = net.createServer((client) => {
220
241
  client.destroy();
221
242
  return;
222
243
  }
223
- return connectWithFallback(client, allowed, targetPort, (err, upstream) => {
244
+ return connectWithFallback(client, targetHost, allowed, targetPort, (err, upstream) => {
224
245
  if (err) {
225
246
  client.write(Buffer.from([0x05, 0x04, 0x00, 0x01, 0, 0, 0, 0, 0, 0])); // host unreachable
226
247
  client.destroy();
227
248
  return;
228
249
  }
229
- // Success reply (IPv4 0.0.0.0:0 is acceptable)
230
- client.write(Buffer.from([0x05, 0x00, 0x00, 0x01, 0, 0, 0, 0, 0, 0]));
231
- upstream.on('error', () => upstream.destroy());
232
- // A client that pipelined its payload with the request (instead of
233
- // waiting for this reply, as most do) had those bytes buffered in
234
- // `buf` — forward them before attaching pipe, or they are lost.
235
- if (buf.length) upstream.write(buf);
236
- client.pipe(upstream);
237
- upstream.pipe(client);
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
+ }
238
271
  });
239
272
  }).catch(() => {
240
273
  client.write(Buffer.from([0x05, 0x04, 0x00, 0x01, 0, 0, 0, 0, 0, 0]));
@@ -244,13 +277,93 @@ const server = net.createServer((client) => {
244
277
  } catch {
245
278
  client.destroy();
246
279
  }
247
- });
280
+ };
281
+ client.on('data', onData);
248
282
  });
249
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
+
250
331
  server.on('error', (err) => {
251
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);
252
338
  });
253
339
 
254
- server.listen(PORT, '127.0.0.1', () => {
255
- console.log(`[ddg-socks] SOCKS5 listening on 127.0.0.1:${PORT} (pins: ${PINS.join(',')})`);
256
- });
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();
@@ -0,0 +1,66 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ /**
5
+ * Resolve npm for a shell-less (argv array) spawn, on every platform.
6
+ *
7
+ * Why this exists: a bare `npm` in an argv-array spawn is unresolvable on
8
+ * Windows. The npm on PATH there is a `.cmd` shim, and Node's shell-less spawn
9
+ * resolves only exact file names — `npm` is `ENOENT`. `npm.cmd` is not a fix
10
+ * either: since the CVE-2024-27980 hardening (Node 18.20.2 / 20.12.2 / 21.7.3,
11
+ * i.e. every Node 20/22/24), spawning a `.cmd` file directly is rejected
12
+ * outright with `EINVAL`. `shell: true` would work, but it reintroduces
13
+ * exactly the argument parsing the argv-array hardening removed — the
14
+ * arguments include paths read from disk (a `RUNNER_TEMP` prefix, a spec read
15
+ * from an installed `package.json`) that must never be parsed by a shell.
16
+ *
17
+ * So: run the npm CLI that ships INSIDE the Node distribution, directly with
18
+ * the Node binary. The absolute path needs no PATH lookup, no shim resolution
19
+ * and no shell, and the arguments stay a clean argv array.
20
+ *
21
+ * Known layouts of the bundled npm CLI (checked in order):
22
+ * <node-dir>/node_modules/npm/bin/npm-cli.js
23
+ * nodejs.org zip/MSI installs and the actions/node-versions builds CI
24
+ * downloads (the CI "Use npm 12" step runs under exactly this layout)
25
+ * <node-dir>/../lib/node_modules/npm/bin/npm-cli.js
26
+ * nvm and Homebrew installs
27
+ *
28
+ * Usage:
29
+ * const { command, args } = npmInvocation();
30
+ * execFileSync(command, [...args, 'install', '-g', 'npm@12', '--prefix', prefix],
31
+ * { stdio: 'inherit' });
32
+ *
33
+ * `execPath` is injectable so tests can pin a layout without a Windows host.
34
+ */
35
+
36
+ const fs = require('node:fs');
37
+ const path = require('node:path');
38
+
39
+ /**
40
+ * Candidate locations of the bundled npm CLI for a node binary at `execPath`,
41
+ * platform-correct one first. Pure path math (no fs), so tests can pin the
42
+ * layout per platform.
43
+ */
44
+ function npmCliCandidates(execPath, platform = process.platform) {
45
+ const p = platform === 'win32' ? path.win32 : path;
46
+ const nodeDir = p.dirname(execPath);
47
+ return [
48
+ p.join(nodeDir, 'node_modules', 'npm', 'bin', 'npm-cli.js'),
49
+ p.join(nodeDir, '..', 'lib', 'node_modules', 'npm', 'bin', 'npm-cli.js'),
50
+ ];
51
+ }
52
+
53
+ /**
54
+ * @param {string} [execPath] the Node binary (default: process.execPath).
55
+ * @returns {{ command: string, args: string[] }} the argv prefix that runs
56
+ * npm without a shell. Primary: the bundled npm CLI run by the Node binary.
57
+ * Fallback (no bundled CLI found — a non-standard Node build): the bare `npm`
58
+ * name, which is correct on POSIX.
59
+ */
60
+ function npmInvocation(execPath = process.execPath) {
61
+ const cli = npmCliCandidates(execPath).find((f) => fs.existsSync(f));
62
+ if (cli) return { command: execPath, args: [cli] };
63
+ return { command: 'npm', args: [] };
64
+ }
65
+
66
+ module.exports = { npmCliCandidates, npmInvocation };
@@ -75,7 +75,7 @@ function ipv6Hextets(address) {
75
75
  function isBlockedIpv6(address) {
76
76
  const hextets = ipv6Hextets(address);
77
77
  if (!hextets) return true; // unparseable → refuse
78
- const [h0, h1, h2, h3, h4, h5, h6, h7] = hextets;
78
+ const [h0, h1, , , , h5, h6, h7] = hextets;
79
79
 
80
80
  // :: and ::1
81
81
  if (hextets.every((h) => h === 0)) return true;
@@ -85,10 +85,24 @@ function isBlockedIpv6(address) {
85
85
  const v4 = `${h6 >> 8}.${h6 & 0xff}.${h7 >> 8}.${h7 & 0xff}`;
86
86
  return isBlockedIpv4(v4);
87
87
  }
88
- // fc00::/7 unique-local, fe80::/10 link-local, ff00::/8 multicast.
89
- if ((h0 & 0xfe00) === 0xfc00) return true;
90
- if ((h0 & 0xffc0) === 0xfe80) return true;
91
- if ((h0 & 0xff00) === 0xff00) return true;
88
+ // fc00::/7 unique-local, fe80::/10 link-local, ff00::/8 multicast, and the
89
+ // deprecated site-local fec0::/10 (RFC 3879) — private/reserved space with
90
+ // no legitimate scrape target. Range checks mirror the TS classifier's
91
+ // string-prefix checks exactly (fc/fd, fe8–feb plus fec–fef, ff).
92
+ // fec0::/10 is a subset of fe80::/10, so the /10 range covers it.
93
+ if (h0 >= 0xfc00 && h0 <= 0xfdff) return true;
94
+ if (h0 >= 0xfe80 && h0 <= 0xfeff) return true;
95
+ if (h0 >= 0xff00) return true;
96
+ // 6to4 (2002::/16), Teredo (2001::/32) and NAT64 (64:ff9b::/96) tunnel an
97
+ // IPv4 address inside the IPv6 literal, so a public-looking literal can
98
+ // carry a private/loopback IPv4 (2002:7f00:1:: → 127.0.0.x,
99
+ // 64:ff9b::a9fe:a9fe → 169.254.169.254). Block the whole ranges, mirroring
100
+ // the TS classifier (isPrivateIpv6 in src/web-research/scraper-utils.ts).
101
+ if (h0 === 0x2002) return true;
102
+ // Teredo is 2001:0::/32, NOT the whole 2001::/32: 2001:4860:4860::8888
103
+ // (public DNS) must stay allowed, so the second hextet must be zero.
104
+ if (h0 === 0x2001 && h1 === 0) return true;
105
+ if (h0 === 0x0064 && h1 === 0xff9b) return true;
92
106
  return false;
93
107
  }
94
108
 
@@ -17,7 +17,7 @@ import type {
17
17
  } from './service-interfaces.ts';
18
18
  import { logger } from '../logger.ts';
19
19
  import { metrics } from '../utils/metrics.ts';
20
- import { isRateLimitError, parseRetryAfterMs, rateLimitBackoffMs } from '../utils/provider-errors.ts';
20
+ import { isRateLimitError, parseRetryAfterMs, rateLimitBackoffMs, RATE_LIMIT_TOTAL_WAIT_MAX_MS } from '../utils/provider-errors.ts';
21
21
  import { completeSimple } from './llm/pi-ai-completion.ts';
22
22
  import { injectCurrentDate } from './llm/inject-date.ts';
23
23
  import { loadPrompt } from './llm/prompts.ts';
@@ -502,6 +502,9 @@ export class PlanningService implements IPlanningService {
502
502
  signal,
503
503
  isTransientError: (err) => isRetriableLlmError(err, signal),
504
504
  delayFor: rateLimitDelayFor,
505
+ // Bound the TOTAL wait for THIS call: a provider that keeps asking for
506
+ // a long window must not spend the run's whole budget sleeping here.
507
+ maxTotalDelayMs: RATE_LIMIT_TOTAL_WAIT_MAX_MS,
505
508
  },
506
509
  );
507
510
 
@@ -1172,6 +1175,9 @@ export class PlanningService implements IPlanningService {
1172
1175
  signal,
1173
1176
  isTransientError: (err) => isRetriableLlmError(err, signal),
1174
1177
  delayFor: rateLimitDelayFor,
1178
+ // Bound the TOTAL wait for THIS call: a provider that keeps asking for
1179
+ // a long window must not spend the run's whole budget sleeping here.
1180
+ maxTotalDelayMs: RATE_LIMIT_TOTAL_WAIT_MAX_MS,
1175
1181
  },
1176
1182
  );
1177
1183
 
@@ -16,6 +16,12 @@ import type { IStateManager, IHealthRegistryService, IKnowledgeStoreService, ISc
16
16
  import { healthRegistry as globalHealthRegistry } from './registry.ts';
17
17
  import { isNativeStackUnavailableError } from '../knowledge/embedder-utils.ts';
18
18
  import { probeKnowledgeStoreAvailability } from '../knowledge/availability.ts';
19
+ import { getSocksProxyEndpoint } from '../infrastructure/browser/proxy-prefs.ts';
20
+ import {
21
+ probeSocksProxyForwarding,
22
+ NEUTRAL_TARGET_HOST,
23
+ NEUTRAL_TARGET_PORT,
24
+ } from '../infrastructure/browser/proxy-health.ts';
19
25
 
20
26
  /**
21
27
  * Standalone BrowserCapability check, exported so tests can call it directly
@@ -109,6 +115,55 @@ export function registerHealthChecks(registry: IHealthRegistryService, container
109
115
  // class the derived budget exists to prevent, one call-frame further out.
110
116
  }, { timeoutMs: Math.max(healthTimeoutMs, 150000, getHealthCheckBudgetMs(config)), critical: true });
111
117
 
118
+ // Register SOCKS Proxy Check — only meaningful when `proxy.json` exists, and
119
+ // CRITICAL when it does: every browser request goes through it, so a proxy that
120
+ // is not forwarding means 100% of searches fail. Before this check existed, a
121
+ // one-way tunnel (1.7.23) reported "All systems operational" while every run
122
+ // died, because BrowserCapability only proves the browser is installed and the
123
+ // browser runtime check short-circuits to "ready (idle)" when idle.
124
+ //
125
+ // The probe speaks SOCKS5 and requires BYTES BACK, not just a successful
126
+ // CONNECT: the observed failure accepted the handshake and black-holed the
127
+ // response, so a connect-only check passes it.
128
+ registry.register('SocksProxy', async () => {
129
+ const endpoint = getSocksProxyEndpoint();
130
+ if (!endpoint) {
131
+ return { healthy: true, diagnostic: { status: 'not configured (browser connects directly)' } };
132
+ }
133
+ // Explicit budgets so the DDG probe plus the neutral fallback stay inside the
134
+ // 25s registration timeout below (4+5+4+5 = 18s worst case).
135
+ const probe = await probeSocksProxyForwarding(endpoint, { timeoutMs: 4_000, dataTimeoutMs: 5_000 });
136
+ if (probe.healthy) {
137
+ return {
138
+ healthy: true,
139
+ diagnostic: {
140
+ status: `forwarding via ${endpoint.host}:${endpoint.port}`,
141
+ firstByteMs: probe.latencyMs,
142
+ },
143
+ };
144
+ }
145
+ // DuckDuckGo answered nothing. Ask the proxy for a neutral host before
146
+ // declaring the tunnel broken: that separates "the tunnel is dead" (restart
147
+ // the proxy) from "the tunnel works but DuckDuckGo's pinned front doors are
148
+ // dead" (repin or drop the proxy). Both make research impossible, but they
149
+ // are different repairs.
150
+ const neutral = await probeSocksProxyForwarding(endpoint, {
151
+ timeoutMs: 4_000,
152
+ dataTimeoutMs: 5_000,
153
+ targetHost: NEUTRAL_TARGET_HOST,
154
+ targetPort: NEUTRAL_TARGET_PORT,
155
+ });
156
+ if (neutral.healthy) {
157
+ return {
158
+ healthy: false,
159
+ error: `the proxy forwards traffic to ${NEUTRAL_TARGET_HOST}, but DuckDuckGo is unreachable through it (${probe.reason}). The tunnel works; the pinned front doors do not. Update DDG_PIN_IPS and restart the proxy, or remove ~/.pi/research/proxy.json.`,
160
+ };
161
+ }
162
+ return { healthy: false, error: probe.reason };
163
+ // Two probes with explicit 4s/5s deadlines (18s worst case) plus room for a
164
+ // loaded machine, inside the 25s registration timeout.
165
+ }, { timeoutMs: 25_000, critical: true });
166
+
112
167
  // Register Knowledge Store Check — NON-critical: the store is the optional cache
113
168
  // research must run without (see the darwin-x64 comment below). A failure here
114
169
  // (e.g. a dead embedding server, ECONNREFUSED) must degrade health, not flip the
@@ -334,7 +389,13 @@ export function isBusyPoolHealthFailure(
334
389
  // probe abort an otherwise-operational session. A non-timeout error (browser not
335
390
  // installed, "connection refused", embedder missing) is a real fault → returns false.
336
391
  const isTimeout = (c: { error?: string }) => /tim(e|ed)\s*out|timeout/i.test(String(c.error || ''));
337
- return capabilityOk && unhealthy.length > 0 && unhealthy.every(isTimeout);
392
+ // A BROKEN PROXY IS NEVER "BUSY". Under total search failure every probe
393
+ // times out, so the timeout-only rule above would call the pool busy and let
394
+ // the run fan out its whole search burst into a dead tunnel (observed
395
+ // 2026-10-30: 36 searches, 7 minutes, one generic error). The proxy check
396
+ // distinguishes "no bytes came back" from "the pool is congested".
397
+ const proxyBroken = unhealthy.some(c => c.component === 'SocksProxy');
398
+ return capabilityOk && !proxyBroken && unhealthy.length > 0 && unhealthy.every(isTimeout);
338
399
  }
339
400
 
340
401
  /**