@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.
package/docs/CHANGELOG.md CHANGED
@@ -5,6 +5,116 @@ All notable changes to this project will be documented in this file.
5
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
6
6
  and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
7
 
8
+ ## [1.7.24] - 2026-10-30
9
+
10
+ ### Fixed
11
+
12
+ - **The SOCKS proxy forwarded requests one way and black-holed every response.** 1.7.23 replaced
13
+ `client.pipe(upstream); upstream.pipe(client);` with `pipeline([client, upstream], ...)` while
14
+ closing an fd leak. `pipeline([a, b])` means `a → b`, so the return path was removed: the proxy
15
+ accepted the SOCKS handshake, connected upstream, forwarded the client's request, and never sent
16
+ a byte back. Every browser request through a configured proxy therefore timed out, and every
17
+ research run with `~/.pi/research/proxy.json` present failed: `Search completely failed: all 36
18
+ queries encountered worker errors` after seven minutes, twice on 2026-10-30, plus a 32-query run
19
+ on 2026-10-29. The tunnel is now two directional `pipeline()` calls, which keeps the fd-leak fix
20
+ (both sockets are still destroyed when either ends) and restores the return path. Normal tunnel
21
+ teardown no longer logs `Premature close` once per request. The tunnel wiring moved into an
22
+ exported `attachTunnel()` so it can be tested without network egress:
23
+ `test/unit/scripts/ddg-socks-proxy-tunnel.test.ts` pins both directions and the teardown rule.
24
+ The published 1.7.23 npm tarball carries the broken script, so upgrading is the only fix for a
25
+ consumer who runs the shipped proxy.
26
+ - **`pipeline()` throws on a dead endpoint, and the throw lands where nothing catches it.** Browsers
27
+ open speculative SOCKS connections and drop them, and the proxy's own 8s data deadline cuts both
28
+ ends on a stall, so `attachTunnel` regularly runs against an already-destroyed socket.
29
+ `pipeline()` raises `ERR_STREAM_UNABLE_TO_PIPE` synchronously, and the call sits inside a
30
+ socket `'connect'` handler — outside every promise chain and `try` in the file — so it killed the
31
+ daemon. Measured while validating this release: 20 restarts in 25 minutes, every one this
32
+ error. Attaching to a dead pair is now a no-op, the attach path is wrapped, half-close and
33
+ already-dead teardown no longer log, and the crash guards have tests.
34
+ - **The proxy now exits non-zero when it cannot listen.** `server.on('error')` logged the failure
35
+ and left the process running without a listening socket, the one state a supervisor cannot see:
36
+ `Restart=always` never fires and every browser request fails at connect. It exits so the
37
+ supervisor retries. This covers `EADDRINUSE` (port already taken) and other listen failures such
38
+ as `EACCES`.
39
+ - **The main-module guard broke when the script was installed as a symlink.** It compared
40
+ `process.argv[1]` with `import.meta.url` as strings. The documented install links
41
+ `~/.pi/research/scripts/ddg-socks-proxy.mjs` to the copy in the repo, so `argv[1]` is the symlink
42
+ and `import.meta.url` is the real path: the comparison says "imported", the proxy exits 0 without
43
+ ever listening, and the supervisor reports a healthy service that refuses every connection. (A
44
+ symlinked directory with a relative entry is fine — Node resolves the cwd. A symlinked script
45
+ file is not.) It now compares real paths (`realpathSync`), and a test spawns the script through a
46
+ temp symlink and asserts it reaches "listening".
47
+ - **A broken proxy reported a clean bill of health.** `health` proved only that the browser was
48
+ installed (`BrowserCapability` never touches the network) and `BrowserRuntime` returns
49
+ `ready (idle)` without probing when the scheduler is idle, so a one-way tunnel produced "All
50
+ systems operational" while every search failed. There is now a **critical** `SocksProxy` health
51
+ component: when `proxy.json` exists it speaks SOCKS5 to the proxy, sends one request to
52
+ **DuckDuckGo's own front door** (`lite.duckduckgo.com:80`, which exercises the proxy's pinned
53
+ addresses rather than ordinary DNS), and requires **bytes back**, because the observed failure
54
+ accepts the handshake and then forwards nothing. If DuckDuckGo answers nothing it probes a
55
+ neutral host, so the report distinguishes "the tunnel is dead" (restart the proxy) from "the
56
+ tunnel works but DuckDuckGo's pinned front doors are dead" (repin or drop the proxy). Explicit
57
+ 4s/5s per-probe budgets keep the pair inside the 25s registration timeout.
58
+ `src/infrastructure/browser/proxy-health.ts`; tests `test/unit/infrastructure/proxy-health.test.ts`
59
+ cover the healthy path, a black-holed tunnel, a ruleset refusal, a refused connection, a
60
+ non-SOCKS greeting, the not-configured case, the dead-pin/neutral-host split, the two-sample
61
+ retry, and abort handling.
62
+ - **A broken proxy is no longer mistaken for a busy pool.** `isBusyPoolHealthFailure` treats any set
63
+ of timeout-shaped probe failures as "pool busy, proceed" so sustained load cannot abort a healthy
64
+ run. A dead proxy produces exactly that signature, so the gate always said "operational" and let
65
+ the whole search burst run into the dead tunnel. An unhealthy `SocksProxy` now makes the gate
66
+ return false. Test: `test/unit/healthcheck/index.test.ts`.
67
+ - **A deep run now checks the proxy before it searches.** Only the quick orchestrator and the UI
68
+ health gate ran a pre-flight check, so a deep run spent its entire burst first. The orchestrator
69
+ probes at the start (3s connect + 3s data, a second sample at 3s/4s, then the neutral-host check)
70
+ and fails immediately with the diagnosis. It requires two failed samples before stopping a run,
71
+ because one refused connect during a proxy restart must not abort work the next probe would
72
+ clear. The run's `AbortSignal` is passed through, so Esc during a dead proxy's probe sequence
73
+ cancels at once instead of waiting it out. The deep start path is covered by
74
+ `test/integration/research-workflow.test.ts`; the diagnostic path it calls is unit-tested.
75
+ - **`Search completely failed` now names a broken proxy instead of listing three guesses.** When the
76
+ proxy probe fails on the total-failure path, the error says what is wrong and what to do, rather
77
+ than "Browser workers may be unavailable, DuckDuckGo is unreachable, or the system is under
78
+ extreme load".
79
+ - **A 5xx with a stated cool-off burned the retry budget in seconds and killed the run** (issue
80
+ #22, "503 + provider Retry-After > 60s is retried 3x at 1s/2s and kills the whole run": eight
81
+ consecutive runs lost on 2026-10-28 while the search burst had already collected 48-104 results).
82
+ Gaps closed in `src/utils/provider-errors.ts` and the retry callers:
83
+ - `isRateLimitError` now classifies the 5xx overload class as capacity, so it takes the long-wait
84
+ path instead of the ordinary 1s/2s curve. The numeric match is anchored to status context
85
+ (`http`/`status`/`code`/`error`/`response`/`returned`, or a 5xx followed by a provider/gateway
86
+ word) so a message that merely contains "502ms" or "max_tokens=500" is not misread as an
87
+ outage — this classifier also drives the run-level stop threshold.
88
+ - `parseRetryAfterMs` now reads pi's own sentence — `Server requested 120s retry delay (max:
89
+ 60s)` — which is the only statement of when the pool reopens, plus the prose `retry after Ns`
90
+ form. Its doc comment no longer claims the 60s exponential ceiling applies to a stated window.
91
+ - A stated window is no longer clamped to 60s. 60s is the ceiling for the **exponential**
92
+ backoff, not for a window the provider stated: clamping 120s to 60s guaranteed the next attempt
93
+ failed too. Stated windows are honoured up to 180s (`STATED_RETRY_AFTER_MAX_MS`) and the
94
+ exponential fallback keeps its 60s ceiling.
95
+ - Total capacity waiting per researcher is bounded at 240s
96
+ (`RATE_LIMIT_TOTAL_WAIT_MAX_MS`). Past it the loop stops and reports the provider's window and
97
+ the time to rerun ("Rerun after 22:10:00Z") instead of sleeping into the run timeout and
98
+ reporting a failure with no cause.
99
+ - The planner/router/synthesizer retries now take the same total bound (`maxTotalDelayMs` in
100
+ `retryWithBackoff`, set to `RATE_LIMIT_TOTAL_WAIT_MAX_MS` in `planning-service.ts`). Their
101
+ per-attempt delay already honoured a stated window; without a sum bound, two 180s windows were
102
+ six minutes of sleeping inside one 900s run. Tests: `test/unit/utils/provider-errors.test.ts`
103
+ (classification and stated windows) and `test/unit/web-research/retry-utils.test.ts` (the
104
+ total-wait cap).
105
+
106
+ ### Documentation
107
+
108
+ - **`docs/TROUBLESHOOTING.md` gained the two failures that actually happened:** every search failing
109
+ with "all N queries encountered worker errors" (proxy diagnosis in five steps, including the one
110
+ `curl` that proves forwarding, and the reminder that a supervisor keeps the code it started with),
111
+ and "`health` says everything is OK but nothing can be searched" (what `health` did and did not
112
+ prove, and what the `SocksProxy` component now reports).
113
+ - **The proxy section now ships a systemd unit** instead of "run under cron", and states the
114
+ failure mode the pins have: they are a snapshot of DuckDuckGo's front doors, so both dying at once
115
+ cannot self-heal. `docs/CONFIGURATION.md` says the proxy is critical when configured and that
116
+ `DDG_PIN_IPS` needs a restart.
117
+
8
118
  ## [1.7.23] - 2026-10-26
9
119
 
10
120
  ### Security
@@ -179,9 +179,9 @@ Diagnostics & platform
179
179
  | `PLAYWRIGHT_INSTALL_DEPS` | _(unset)_ | Linux only. Set `true` during `npm install` to also install system libraries via `npx playwright install-deps` (same as `npm run install:system-deps`). |
180
180
  | `PI_RESEARCH_STRICT_SETUP` | _(unset)_ | Read by the bundled `scripts/setup.cjs` during `npm install`. Set `1`/`true` to make a failed browser download fail the install instead of deferring it to first use. |
181
181
  | `PI_RESEARCH_CONFIG_DIR_NAME` | `.pi` | Override the host config-directory name under your home dir (advanced; e.g. set to share another harness's config root). |
182
- | `PI_RESEARCH_PROXY_JSON` | `~/.pi/research/proxy.json` | Path of the SOCKS proxy config file the browser workers read (`{"host":"127.0.0.1","port":1080}`), routing every browser request through the local SOCKS proxy. Read fresh per scrape, so toggling needs no restart. See [Troubleshooting](TROUBLESHOOTING.md). |
183
- | `DDG_SOCKS_PORT` | `1080` | Port the local SOCKS proxy (`scripts/ddg-socks-proxy.mjs`, run under cron) listens on. Read by the proxy script, not the main runtime. |
184
- | `DDG_PIN_IPS` | `52.250.42.157,40.89.244.232` | Pinned DuckDuckGo front-door IPs for the local SOCKS proxy (comma-separated). The proxy rotates past any address that stalls, so the list self-heals; change it only for a different egress path. |
182
+ | `PI_RESEARCH_PROXY_JSON` | `~/.pi/research/proxy.json` | Path of the SOCKS proxy config file the browser workers read (`{"host":"127.0.0.1","port":1080}`), routing every browser request through the local SOCKS proxy. Read fresh per scrape, so toggling needs no restart. When the file exists, the proxy is a **critical** health component and a run refuses to start if it is not forwarding. See [Troubleshooting](TROUBLESHOOTING.md). |
183
+ | `DDG_SOCKS_PORT` | `1080` | Port the local SOCKS proxy (`scripts/ddg-socks-proxy.mjs`) listens on. Read by the proxy script, not the main runtime. Supervise it with systemd (see [Troubleshooting](TROUBLESHOOTING.md#the-socks-proxy-refuses-a-url-with-connection-not-allowed-by-ruleset)); a proxy started by hand keeps whatever code it loaded until it is restarted. |
184
+ | `DDG_PIN_IPS` | `52.250.42.157,40.89.244.232` | Pinned DuckDuckGo front-door IPs for the local SOCKS proxy (comma-separated). The proxy rotates past any address that stalls, so the list self-heals; change it only for a different egress path. Both pins dying at once is a real failure mode (DuckDuckGo moves its front doors) — repin, or remove `proxy.json` when direct egress works. |
185
185
  | `PI_CODING_AGENT_DIR` | `~/.pi/agent` | Override the pi agent directory the standalone engine/launcher looks in for host config (settings.json, models.json). |
186
186
 
187
187
  Testing only — never enable in production
@@ -70,10 +70,102 @@ Updating fixes it. To confirm the cause on an affected build, disable the proxy
70
70
 
71
71
  **What the fix does and does not cover.** The check it exempts compares the address Firefox actually connected to against the address the hostname resolves to — that comparison is what catches DNS rebinding. A SOCKS5 proxy makes it impossible: Firefox never sees the origin address. So with a proxy configured, a page that rebinds a public hostname to an internal address is not caught at bake time. Two things still apply. Request-time DNS validation still runs on every navigation and every subresource the page pulls in, and rejects a hostname that resolves into private space before the request is allowed out. And `scripts/ddg-socks-proxy.mjs` (the proxy this project ships instructions for) now refuses to CONNECT to a loopback, private, link-local, CGNAT, multicast or reserved destination, checking both the requested host and every address it resolves to. A third-party SOCKS proxy you point `proxy.json` at does not have that guard — do not route through one you do not trust.
72
72
 
73
+ ## Every search fails: "Search completely failed: all N queries encountered worker errors"
74
+
75
+ This is the whole burst failing, not one query. Most of the time it is network reachability for
76
+ the search provider, and the most common local cause is a configured SOCKS proxy that is not
77
+ forwarding. The error now names it when it can:
78
+
79
+ ```
80
+ Search completely failed: all 36 queries encountered worker errors.
81
+ SOCKS proxy check: proxy at 127.0.0.1:1080 completed the SOCKS handshake to lite.duckduckgo.com:80
82
+ but returned no data within 3000ms (...). Every browser request is routed through the configured
83
+ proxy, so no search can succeed until it forwards traffic or ~/.pi/research/proxy.json is removed.
84
+ ```
85
+
86
+ Diagnose in this order.
87
+
88
+ 1. **Is a proxy configured?** `cat ~/.pi/research/proxy.json`. Absent means the browser connects
89
+ directly. Present means 100% of browser traffic goes through it, so a dead proxy is a dead
90
+ system.
91
+ 2. **Is it forwarding?** One command, and it must print an HTTP status code:
92
+ ```bash
93
+ curl -sS -x socks5h://127.0.0.1:1080 -o /dev/null -w '%{http_code}\n' https://example.com/
94
+ ```
95
+ `000` after 15s means the proxy is not returning data. `curl: (97)` means the proxy refused the
96
+ destination (see the ruleset section below).
97
+ 3. **Is the proxy process running the current script?** A systemd unit or a cron job keeps the code
98
+ it started with. After `pi update`, restart it:
99
+ ```bash
100
+ systemctl --user restart ddg-socks-proxy.service # or whatever supervises it
101
+ ```
102
+ Verify what it actually loaded: `systemctl --user show ddg-socks-proxy.service -p ExecStart`.
103
+ 4. **Read the proxy's own log.** With the unit below it goes to journald
104
+ (`journalctl --user -u ddg-socks-proxy -n 50`); a unit that appends to a file puts it in that
105
+ file instead. `connected but sent no data within 8000ms` repeated, or `tunnel closed: Premature
106
+ close` in bulk, means the tunnel is established and nothing comes back.
107
+ 5. **No proxy needed?** Remove it: `mv ~/.pi/research/proxy.json ~/.pi/research/proxy.json.off`.
108
+ The file is read per scrape, so no restart is needed. Do this whenever direct egress works —
109
+ the proxy exists for an egress path that can reach only one DuckDuckGo front-door, and most
110
+ machines do not need it.
111
+
112
+ If the proxy is healthy, the same error means the provider itself: DuckDuckGo timing out, or a
113
+ blocked egress path. Check `PI_RESEARCH_SEARCH_TIMEOUT_MS` (45s by default) against a slow link,
114
+ and try `curl https://lite.duckduckgo.com/lite/` from the same machine.
115
+
116
+ ## `health` says everything is OK but nothing can be searched
117
+
118
+ Fixed in the release that adds the `SocksProxy` health component. Before it, `health` proved only
119
+ that the browser was installed: `BrowserCapability` never touches the network, and `BrowserRuntime`
120
+ returns `ready (idle)` without probing when the scheduler is idle. A one-way proxy therefore
121
+ reported a clean bill of health while every run failed.
122
+
123
+ Current builds check the configured proxy by speaking SOCKS5 to it and requiring **bytes back**, so a
124
+ tunnel that connects and then returns nothing is reported as:
125
+
126
+ ```
127
+ [FAIL] **SocksProxy** [CRITICAL]
128
+ - Error: proxy at 127.0.0.1:1080 completed the SOCKS handshake to lite.duckduckgo.com:80 but returned no data within 5000ms (...)
129
+ ```
130
+
131
+ That check also runs before a research run starts, so the run stops in seconds with a diagnosis
132
+ instead of spending its whole search burst first. Two other signals are worth knowing:
133
+
134
+ - A readiness-probe timeout alone is treated as "pool busy" and the run proceeds. That rule is
135
+ deliberate (a loaded machine queues probes behind real work), and a broken proxy is excluded
136
+ from it.
137
+ - `PI_RESEARCH_SKIP_HEALTHCHECK=1` skips the pre-flight check entirely. It does not skip the
138
+ proxy probe.
139
+
73
140
  ## The SOCKS proxy refuses a URL with "connection not allowed by ruleset"
74
141
 
75
142
  That is `scripts/ddg-socks-proxy.mjs` blocking an SSRF attempt, not a bug: the destination was loopback, private, link-local (`169.254.169.254` metadata included), CGNAT, multicast or reserved, spelled either as the host or as the address it resolves to. The log line names it: `[ddg-socks] refused private/reserved destination <host>:<port>` or `refused <host> — resolves to private/reserved <addr>`. A research run never needs such a destination. If you added the proxy for a private mirror, run that request without the proxy.
76
143
 
144
+ Running the proxy under systemd (recommended over cron: it restarts, and its output lands in the
145
+ journal) — the unit is a local file, not something this package installs:
146
+
147
+ ```ini
148
+ [Unit]
149
+ Description=DDG SOCKS5 pin proxy for pi-research
150
+ After=network-online.target
151
+
152
+ [Service]
153
+ WorkingDirectory=%h/.pi/agent/extensions/pi-research # or the npm install path
154
+ Environment=DDG_SOCKS_PORT=1080
155
+ Environment=DDG_PIN_IPS=52.250.42.157,40.89.244.232
156
+ ExecStart=/usr/bin/node scripts/ddg-socks-proxy.mjs
157
+ Restart=always
158
+ RestartSec=5
159
+
160
+ [Install]
161
+ WantedBy=default.target
162
+ ```
163
+
164
+ Point `ExecStart` at the Node binary that runs pi (`command -v node`). `DDG_PIN_IPS` is read only by
165
+ the proxy, so changing it needs a restart. The pins are a snapshot of DuckDuckGo's front doors: if
166
+ both go dead the proxy cannot recover by itself, and `curl` through it will stall — repin, or drop
167
+ the proxy if direct egress works on your machine.
168
+
77
169
  ## A research run used a different model than `~/.pi/research/config.env` says
78
170
 
79
171
  Before the release that fingerprints the config sources, `getConfig()` cached configuration for the life of the process and never re-read it. Editing `config.env` from another shell, editor or pi session therefore did not affect a session that was already running, however long it lived. Restart pi (the loaded code and the loaded config are both fixed at start-up) or set the value through `/research-config`, which calls `resetConfig()`. Confirm what a run actually used: the report footer names the model, and the log carries `Using model for researcher <id>: <provider>/<model>`.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lincoln504/pi-research",
3
- "version": "1.7.23",
3
+ "version": "1.7.24",
4
4
  "description": "Web research for your agents with smart and safe tooling + knowledge store",
5
5
  "type": "module",
6
6
  "private": false,
@@ -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();
@@ -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
  /**