@lincoln504/pi-research 1.7.21 → 1.7.23

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 (32) hide show
  1. package/agent-skill/pi-research/SKILL.md +1 -1
  2. package/dist/cli.mjs +399 -163
  3. package/dist/thread-worker.mjs +77 -31
  4. package/docs/CHANGELOG.md +46 -0
  5. package/docs/CONFIGURATION.md +8 -3
  6. package/docs/THIRD-PARTY-NOTICES.md +29 -13
  7. package/docs/TROUBLESHOOTING.md +16 -0
  8. package/package.json +12 -9
  9. package/scripts/ddg-socks-proxy.mjs +279 -0
  10. package/scripts/lib/npm-cmd.cjs +66 -0
  11. package/scripts/lib/private-addresses.mjs +143 -0
  12. package/src/config.ts +75 -2
  13. package/src/core/interfaces/steering-interfaces.ts +11 -0
  14. package/src/core/llm/coordinator-model.ts +104 -0
  15. package/src/core/planning-service.ts +24 -0
  16. package/src/index.ts +7 -1
  17. package/src/infrastructure/browser/proxy-prefs.ts +124 -0
  18. package/src/infrastructure/browser/thread-worker-browser.ts +5 -21
  19. package/src/infrastructure/browser/thread-worker-messaging.ts +9 -4
  20. package/src/infrastructure/browser/thread-worker.mjs +77 -31
  21. package/src/knowledge/embedder-utils.ts +1 -1
  22. package/src/knowledge/sql-utils.ts +15 -0
  23. package/src/knowledge/store-operations.ts +3 -2
  24. package/src/knowledge/store.ts +15 -14
  25. package/src/orchestration/deep-research-orchestrator.ts +71 -2
  26. package/src/orchestration/research-synthesis-service.ts +14 -1
  27. package/src/orchestration/researcher-executor.ts +33 -33
  28. package/src/orchestration/session-state.ts +155 -7
  29. package/src/tools/read-guard.ts +23 -4
  30. package/src/tui/tui-controller.ts +25 -1
  31. package/src/utils/provider-errors.ts +149 -0
  32. package/src/web-research/retry-utils.ts +22 -3
@@ -0,0 +1,279 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * ddg-socks-proxy.mjs — minimal SOCKS5 (no-auth, CONNECT) local proxy.
4
+ *
5
+ * Why: egress for this machine (Tailscale exit node 67.173.236.18) can reach
6
+ * only ONE of DuckDuckGo's two Azure front-doors. The system resolver hands
7
+ * out the unreachable IP (52.250.42.157) for every duckduckgo.com hostname,
8
+ * so every HTTP client (curl, Node fetch, Camoufox workers) times out at TCP
9
+ * connect while the other front-door (40.89.244.232) answers in ~1s.
10
+ *
11
+ * This proxy CONNECTs on the caller's behalf and resolves *.duckduckgo.com to
12
+ * the pinned, verified-live IP, using normal DNS for everything else. It is
13
+ * deliberately dependency-free (net + dns only), holds no state beyond each
14
+ * socket, and is safe to run under cron keepalive.
15
+ *
16
+ * Configuration:
17
+ * DDG_SOCKS_PORT port to listen on (default 1080)
18
+ * DDG_PIN_IPS comma-separated pinned IPs for duckduckgo.com (default
19
+ * "52.250.42.157,40.89.244.232"). Which front-door is live
20
+ * flips with the egress path, so the starting pin ROTATES
21
+ * past any address observed stalling or failing; a healthy
22
+ * address keeps its position, so the list self-heals toward
23
+ * whichever IP last worked.
24
+ *
25
+ * The worker-side hook is thread-worker-browser.ts: when
26
+ * ~/.pi/research/proxy.json exists with {"port":N,"host":"127.0.0.1"}, the
27
+ * browser is launched through this proxy (SOCKS remote DNS on).
28
+ */
29
+
30
+ import net from 'node:net';
31
+ import dns from 'node:dns';
32
+ import { pipeline } from 'node:stream';
33
+ import { isBlockedDestination, isBlockedProxyTarget } from './lib/private-addresses.mjs';
34
+
35
+ const PORT = Number(process.env.DDG_SOCKS_PORT || 1080);
36
+ const PINS = (process.env.DDG_PIN_IPS || '52.250.42.157,40.89.244.232').split(',').map((s) => s.trim()).filter(Boolean);
37
+
38
+ function isDdgHost(host) {
39
+ return /(^|\.)duckduckgo\.com$/i.test(host);
40
+ }
41
+
42
+ function resolve(host) {
43
+ if (isDdgHost(host)) {
44
+ return Promise.resolve(PINS);
45
+ }
46
+ return new Promise((resolveP, rejectP) => {
47
+ dns.lookup(host, { all: true }, (err, addrs) => {
48
+ if (err) return rejectP(err);
49
+ resolveP(addrs.map((a) => a.address).filter(Boolean));
50
+ });
51
+ });
52
+ }
53
+
54
+ /**
55
+ * Starting index into the pinned list for the next connection. Rotates past a
56
+ * front-door the moment it shows the accept-then-stall pattern, and sticks to
57
+ * the one that last delivered data — the live front-door flips with the
58
+ * egress path, so no static order stays right for long.
59
+ */
60
+ let pinIndex = 0;
61
+
62
+ // 8000ms data deadline ≈ half the 15s curl default: an all-dead edge costs
63
+ // ~16s of client time before failing, and the healthy front-door answers the
64
+ // TLS ClientHello in <1s.
65
+ const DATA_DEADLINE_MS = 8000;
66
+
67
+ /**
68
+ * Try each pinned address (starting at the rotated pinIndex) until one
69
+ * connects, then hand the socket over. The data deadline SPANS the TCP
70
+ * connect and the post-connect TLS ClientHello wait — DDG's dead front-door
71
+ * ACCEPTS the TCP handshake then never answers the ClientHello, so a deadline
72
+ * cleared at connect (the old behavior) never caught it and clients hung
73
+ * until their own 45s timeout.
74
+ *
75
+ * SOCKS has no transparent retry once the success reply is out (the client
76
+ * speaks first over the tunnel and can't replay), so post-reply we can't
77
+ * fail over: we cut both ends so the client fails fast, and rotate pinIndex
78
+ * so the NEXT connection starts at the next front-door. The caller passes the
79
+ * client socket precisely so it can be cut on that path.
80
+ */
81
+ function connectWithFallback(client, host, addrs, port, cb) {
82
+ let settled = false;
83
+ let attempts = 0;
84
+ // Only DuckDuckGo front-doors rotate: for any other destination the address
85
+ // list comes from DNS and a "starting index" has no meaning, so a refused
86
+ // connection to an arbitrary host must not shift the pin order.
87
+ const rotate = (usedIdx) => {
88
+ if (isDdgHost(host)) pinIndex = (usedIdx + 1) % addrs.length;
89
+ };
90
+ const tryNext = () => {
91
+ if (settled) return;
92
+ if (attempts >= addrs.length) {
93
+ settled = true;
94
+ return cb(new Error('all pinned addresses failed'));
95
+ }
96
+ const offset = attempts++;
97
+ const usedIdx = (pinIndex + offset) % addrs.length;
98
+ const addr = addrs[usedIdx];
99
+ const sock = net.connect({ host: addr, port });
100
+ const deadline = setTimeout(() => {
101
+ if (settled) {
102
+ // Success reply already sent — no transparent retry is possible.
103
+ // Fast-fail both ends and rotate the starting pin for next time.
104
+ sock.destroy();
105
+ client.destroy();
106
+ rotate(usedIdx);
107
+ console.error(`[ddg-socks] ${addr} connected but sent no data within ${DATA_DEADLINE_MS}ms — client cut, rotating pin`);
108
+ return;
109
+ }
110
+ sock.destroy();
111
+ tryNext();
112
+ }, DATA_DEADLINE_MS);
113
+ sock.once('data', () => {
114
+ // First upstream byte — the address is healthy. Nothing else to do: the
115
+ // success reply was already sent on 'connect' (data cannot precede
116
+ // connect, so 'settled' is always true here); this handler exists to
117
+ // disarm the stall deadline so a healthy connection is never cut.
118
+ clearTimeout(deadline);
119
+ });
120
+ sock.once('connect', () => {
121
+ // Do NOT clear the deadline here — the stall we must catch happens
122
+ // after connect. Reply success immediately: the SOCKS client waits
123
+ // for this reply before sending its first payload (TLS ClientHello),
124
+ // and the upstream won't send anything until it receives one.
125
+ if (!settled) {
126
+ settled = true;
127
+ cb(null, sock);
128
+ }
129
+ });
130
+ sock.once('error', (err) => {
131
+ clearTimeout(deadline);
132
+ sock.destroy();
133
+ if (!settled) {
134
+ // Connection refusal / reset — this address is dead from this egress
135
+ // too; rotate past it for the next connection, same as a stall.
136
+ rotate(usedIdx);
137
+ tryNext();
138
+ }
139
+ });
140
+ };
141
+ tryNext();
142
+ }
143
+
144
+ const server = net.createServer((client) => {
145
+ client.on('error', () => client.destroy());
146
+ let buf = Buffer.alloc(0);
147
+ let stage = 'greet';
148
+ let targetHost = '';
149
+ let targetPort = 0;
150
+
151
+ const onData = (chunk) => {
152
+ // Cap the handshake buffer: a well-formed SOCKS request is under 300
153
+ // bytes. Anything larger is not a handshake and must not accumulate.
154
+ if (buf.length + chunk.length > 4096) {
155
+ client.destroy();
156
+ return;
157
+ }
158
+ buf = Buffer.concat([buf, chunk]);
159
+ try {
160
+ if (stage === 'greet') {
161
+ if (buf.length < 2) return;
162
+ const nmethods = buf[1];
163
+ if (buf.length < 2 + nmethods) return;
164
+ // Reply: no-auth required
165
+ client.write(Buffer.from([0x05, 0x00]));
166
+ buf = buf.subarray(2 + nmethods);
167
+ stage = 'request';
168
+ }
169
+ if (stage === 'request') {
170
+ if (buf.length < 4) return;
171
+ const ver = buf[0];
172
+ const cmd = buf[1];
173
+ const atyp = buf[3];
174
+ if (ver !== 5 || cmd !== 1) {
175
+ client.write(Buffer.from([0x05, 0x07, 0x00, 0x01, 0, 0, 0, 0, 0, 0])); // cmd not supported
176
+ client.destroy();
177
+ return;
178
+ }
179
+ if (atyp === 1) { // IPv4
180
+ if (buf.length < 10) return;
181
+ targetHost = [buf[4], buf[5], buf[6], buf[7]].join('.');
182
+ targetPort = buf.readUInt16BE(8);
183
+ buf = buf.subarray(10);
184
+ stage = 'connect';
185
+ } else if (atyp === 3) { // domain
186
+ const len = buf[4];
187
+ if (buf.length < 5 + len + 2) return;
188
+ targetHost = buf.subarray(5, 5 + len).toString('utf8');
189
+ targetPort = buf.readUInt16BE(5 + len);
190
+ buf = buf.subarray(7 + len);
191
+ stage = 'connect';
192
+ } else if (atyp === 4) { // IPv6
193
+ if (buf.length < 22) return;
194
+ const raw = buf.subarray(4, 20);
195
+ const parts = [];
196
+ for (let i2 = 0; i2 < 16; i2 += 2) parts.push(raw.readUInt16BE(i2).toString(16));
197
+ targetHost = parts.join(':');
198
+ targetPort = buf.readUInt16BE(20);
199
+ buf = buf.subarray(22);
200
+ stage = 'connect';
201
+ } else {
202
+ client.write(Buffer.from([0x05, 0x08, 0x00, 0x01, 0, 0, 0, 0, 0, 0])); // atyp not supported
203
+ client.destroy();
204
+ return;
205
+ }
206
+ }
207
+ if (stage === 'connect') {
208
+ stage = 'done';
209
+ // Handshake complete: the tunnel below owns the stream from here on.
210
+ // Detach this listener, or `buf` would grow without bound for the
211
+ // lifetime of every long-lived proxied connection.
212
+ client.removeListener('data', onData);
213
+ // SSRF backstop for proxied traffic. The browser cannot check this itself through
214
+ // a SOCKS5 proxy (Firefox reports 0.0.0.0 as the origin address — see
215
+ // src/infrastructure/browser/proxy-prefs.ts), so the proxy is the last place that
216
+ // can refuse to reach internal infrastructure. A hostile page that gets the
217
+ // browser to request http://169.254.169.254/ or http://127.0.0.1:8443/ lands here.
218
+ if (isBlockedProxyTarget(targetHost)) {
219
+ // JSON.stringify: targetHost is raw domain bytes from a SOCKS
220
+ // client and may carry newlines (log injection).
221
+ console.error(`[ddg-socks] refused private/reserved destination ${JSON.stringify(targetHost)}:${targetPort}`);
222
+ client.write(Buffer.from([0x05, 0x02, 0x00, 0x01, 0, 0, 0, 0, 0, 0])); // not allowed by ruleset
223
+ client.destroy();
224
+ return;
225
+ }
226
+ resolve(targetHost).then((addrs) => {
227
+ const allowed = addrs.filter((addr) => {
228
+ // A DNS answer can point anywhere: check the ADDRESS, not just the hostname.
229
+ // The DDG pins are public by construction, so they pass this check too — no
230
+ // hostname-based bypass, because a bypass is what an attacker would aim for.
231
+ if (isBlockedDestination(addr)) {
232
+ console.error(`[ddg-socks] refused ${JSON.stringify(targetHost)} — resolves to private/reserved ${addr}`);
233
+ return false;
234
+ }
235
+ return true;
236
+ });
237
+ if (allowed.length === 0) {
238
+ client.write(Buffer.from([0x05, 0x02, 0x00, 0x01, 0, 0, 0, 0, 0, 0])); // not allowed by ruleset
239
+ client.destroy();
240
+ return;
241
+ }
242
+ return connectWithFallback(client, targetHost, allowed, targetPort, (err, upstream) => {
243
+ if (err) {
244
+ client.write(Buffer.from([0x05, 0x04, 0x00, 0x01, 0, 0, 0, 0, 0, 0])); // host unreachable
245
+ client.destroy();
246
+ return;
247
+ }
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
+ });
260
+ });
261
+ }).catch(() => {
262
+ client.write(Buffer.from([0x05, 0x04, 0x00, 0x01, 0, 0, 0, 0, 0, 0]));
263
+ client.destroy();
264
+ });
265
+ }
266
+ } catch {
267
+ client.destroy();
268
+ }
269
+ };
270
+ client.on('data', onData);
271
+ });
272
+
273
+ server.on('error', (err) => {
274
+ console.error(`[ddg-socks] server error: ${err.message}`);
275
+ });
276
+
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
+ });
@@ -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 };
@@ -0,0 +1,143 @@
1
+ import net from 'node:net';
2
+
3
+ /**
4
+ * Destination guard for `scripts/ddg-socks-proxy.mjs`.
5
+ *
6
+ * Why this exists at all: the browser's SSRF backstop (`serverAddr()` in
7
+ * src/infrastructure/browser/thread-worker-messaging.ts) compares the address Firefox
8
+ * actually connected to against the resolved address, to catch DNS rebinding. Through a
9
+ * SOCKS5 proxy that comparison is impossible — Firefox never sees the origin address and
10
+ * reports `0.0.0.0` — so the backstop is skipped for proxied use (see
11
+ * src/infrastructure/browser/proxy-prefs.ts). The proxy sits on the socket, resolves every
12
+ * destination itself, and is therefore the only place left that can refuse to connect to
13
+ * internal infrastructure.
14
+ *
15
+ * Deliberately dependency-free and separate from the TS source: the proxy runs standalone
16
+ * under cron (`node scripts/ddg-socks-proxy.mjs`) and cannot import the TypeScript tree.
17
+ * The ranges mirror the TS classifier (`isPrivateIp` / `isPrivateIpv6` in
18
+ * src/web-research/scraper-utils.ts) plus this guard's baseline; keep the two in step.
19
+ */
20
+
21
+ /** IPv4 ranges that must never be a scrape destination. */
22
+ function isBlockedIpv4(address) {
23
+ const parts = address.split('.').map(Number);
24
+ if (parts.length !== 4 || parts.some((p) => !Number.isInteger(p) || p < 0 || p > 255)) {
25
+ // Not a dotted quad: not something this guard can vouch for. Fail closed —
26
+ // resolve() only ever yields dotted quads, so this means a malformed input.
27
+ return true;
28
+ }
29
+ const [a, b, c] = parts;
30
+ return (
31
+ a === 0 || // 0.0.0.0/8 "this network"
32
+ a === 10 || // RFC 1918
33
+ (a === 100 && b >= 64 && b <= 127) || // RFC 6598 CGNAT / cloud-internal
34
+ a === 127 || // loopback
35
+ (a === 169 && b === 254) || // link-local, incl. 169.254.169.254 metadata
36
+ (a === 172 && b >= 16 && b <= 31) || // RFC 1918
37
+ (a === 192 && b === 168) || // RFC 1918
38
+ (a === 192 && b === 0 && (c === 0 || c === 2)) || // IETF protocol / TEST-NET-1
39
+ (a === 198 && (b === 18 || b === 19)) || // RFC 2544 benchmarking
40
+ (a === 198 && b === 51 && c === 100) || // TEST-NET-2
41
+ (a === 203 && b === 0 && c === 113) || // TEST-NET-3
42
+ a >= 224 // multicast + reserved + broadcast
43
+ );
44
+ }
45
+
46
+ /** Expand an IPv6 literal to 8 hextets, or null when it is not parseable. */
47
+ function ipv6Hextets(address) {
48
+ let text = address.toLowerCase().replace(/^\[|\]$/g, '');
49
+ // Drop a zone id (fe80::1%eth0).
50
+ const pct = text.indexOf('%');
51
+ if (pct !== -1) text = text.slice(0, pct);
52
+
53
+ // An embedded dotted quad in the tail (::ffff:127.0.0.1) becomes two hextets.
54
+ const dotted = /^(.*:)((?:\d{1,3}\.){3}\d{1,3})$/.exec(text);
55
+ if (dotted) {
56
+ const quad = dotted[2].split('.').map(Number);
57
+ if (quad.length !== 4 || quad.some((p) => !Number.isInteger(p) || p < 0 || p > 255)) return null;
58
+ text = `${dotted[1]}${((quad[0] << 8) | quad[1]).toString(16)}:${((quad[2] << 8) | quad[3]).toString(16)}`;
59
+ }
60
+
61
+ const halves = text.split('::');
62
+ if (halves.length > 2) return null;
63
+ const head = halves[0] ? halves[0].split(':') : [];
64
+ const tail = halves.length === 2 && halves[1] ? halves[1].split(':') : [];
65
+ const missing = 8 - head.length - tail.length;
66
+ if (halves.length === 1 ? head.length !== 8 : missing < 0) return null;
67
+ const all = halves.length === 2
68
+ ? [...head, ...Array(missing).fill('0'), ...tail]
69
+ : head;
70
+ const hextets = all.map((h) => parseInt(h, 16));
71
+ if (hextets.some((h) => !Number.isInteger(h) || h < 0 || h > 0xffff)) return null;
72
+ return hextets;
73
+ }
74
+
75
+ function isBlockedIpv6(address) {
76
+ const hextets = ipv6Hextets(address);
77
+ if (!hextets) return true; // unparseable → refuse
78
+ const [h0, h1, , , , h5, h6, h7] = hextets;
79
+
80
+ // :: and ::1
81
+ if (hextets.every((h) => h === 0)) return true;
82
+ if (hextets.slice(0, 7).every((h) => h === 0) && h7 === 1) return true;
83
+ // IPv4-mapped (::ffff:a.b.c.d) and IPv4-compatible: judge the embedded v4 address.
84
+ if (hextets.slice(0, 5).every((h) => h === 0) && (h5 === 0xffff || h5 === 0)) {
85
+ const v4 = `${h6 >> 8}.${h6 & 0xff}.${h7 >> 8}.${h7 & 0xff}`;
86
+ return isBlockedIpv4(v4);
87
+ }
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;
106
+ return false;
107
+ }
108
+
109
+ /**
110
+ * True when `address` is a loopback, private, link-local, CGNAT, multicast, reserved or
111
+ * otherwise unparseable IP ADDRESS that the proxy must refuse to connect to.
112
+ *
113
+ * Takes an address, never a hostname. A hostname is not parseable as an address, so
114
+ * passing one lands in the fail-closed branch and blocks it — see
115
+ * `isBlockedProxyTarget`, which is what callers wanting to judge a host:port want.
116
+ */
117
+ export function isBlockedDestination(address) {
118
+ if (typeof address !== 'string' || address === '') return true;
119
+ if (address.includes(':')) return isBlockedIpv6(address);
120
+ return isBlockedIpv4(address);
121
+ }
122
+
123
+ /**
124
+ * Decide a SOCKS request's destination before DNS: refuses names that resolve only to the
125
+ * local host, refuses IP literals that point at internal space, and passes hostnames
126
+ * through to be judged AFTER resolution (that second check is the load-bearing one, since
127
+ * a name can resolve anywhere).
128
+ *
129
+ * Do not collapse this into `isBlockedDestination(host)`: every hostname is unparseable
130
+ * as an address, so that call refuses everything. It did, on a live run: Firefox sends
131
+ * `socks_remote_dns: true` domain-type requests for every hop, so a hostname-stage call
132
+ * to the address guard refused all traffic, including the DuckDuckGo pins.
133
+ */
134
+ export function isBlockedProxyTarget(host) {
135
+ if (typeof host !== 'string' || host === '') return true;
136
+ const name = host.toLowerCase().replace(/\.$/, '');
137
+ // `localhost` and `*.localhost` are loopback by name and never reach DNS.
138
+ if (name === 'localhost' || name.endsWith('.localhost')) return true;
139
+ // An IP literal needs no resolution, so judge it now.
140
+ if (net.isIP(name) !== 0) return isBlockedDestination(name);
141
+ // A domain: judged by the addresses it resolves to (see the proxy's resolve() filter).
142
+ return false;
143
+ }
package/src/config.ts CHANGED
@@ -170,9 +170,24 @@ export const ConfigSchema = Type.Object({
170
170
  * When set, this governs the evaluator/synthesis rounds and the researcher
171
171
  * sub-agents (both deep and quick) and the knowledge synthesis background LLM.
172
172
  * The initial coordinator (round 1 planning) uses the parent chat's model (ctx.model)
173
- * for prompt-cache continuity with the conversation that triggered research.
173
+ * by DEFAULT, for prompt-cache continuity with the conversation that triggered
174
+ * research; COORDINATOR_MODEL overrides that decision (see below).
174
175
  */
175
176
  RESEARCH_MODEL: Type.Optional(Type.String()),
177
+ /**
178
+ * Which model runs the INITIAL coordinator (round-1 planning), the one call that
179
+ * otherwise uses the parent chat's model (`ctx.model`) for prompt-cache continuity:
180
+ * • `host` (default) — the chat's model, current behaviour.
181
+ * • `research` — the RESEARCH_MODEL / researcher model, same as every later round.
182
+ * • `provider/id` (or a bare id) — that model.
183
+ *
184
+ * Exists because the chat model is not always a good planner: a local single-seat
185
+ * server (llama-swap `concurrencyLimit: 1`, 4k output) turns the coordinator call into
186
+ * minutes of wall clock and can 429 the owner's own next prompt, while a hosted
187
+ * research model plans the same query in seconds. The cache-lineage benefit is real
188
+ * but must be opt-out-able. Unset = `host`.
189
+ */
190
+ COORDINATOR_MODEL: Type.Optional(Type.String()),
176
191
  /** Explicit directory for the knowledge store database (overrides default) */
177
192
  KNOWLEDGE_STORE_DIR: Type.Optional(Type.String()),
178
193
  /** Directory for transient browser profile data. Defaults to a disk-backed
@@ -292,6 +307,7 @@ const USER_MIGRATION_KEYS = [
292
307
  'PI_RESEARCH_QUICK_MAX_SCRAPE_URLS',
293
308
  'PI_RESEARCH_CONSOLE_LOG',
294
309
  'PI_RESEARCH_MODEL',
310
+ 'PI_RESEARCH_COORDINATOR_MODEL',
295
311
  'PI_RESEARCH_KNOWLEDGE_DIR',
296
312
  'PI_RESEARCH_TMP_DIR',
297
313
  'PI_RESEARCH_REPORT_EXPORT_ENABLED',
@@ -987,6 +1003,7 @@ export function saveConfig(config: Config, scope: 'local' | 'user' = 'local', cw
987
1003
  PI_RESEARCH_MIGRATION_STRATEGY: config.MIGRATION_STRATEGY,
988
1004
  PI_RESEARCH_CONSOLE_LOG: String(config.CONSOLE_LOG),
989
1005
  ...(config.RESEARCH_MODEL ? { PI_RESEARCH_MODEL: config.RESEARCH_MODEL } : {}),
1006
+ ...(config.COORDINATOR_MODEL ? { PI_RESEARCH_COORDINATOR_MODEL: config.COORDINATOR_MODEL } : {}),
990
1007
  ...(config.KNOWLEDGE_STORE_DIR ? { PI_RESEARCH_KNOWLEDGE_DIR: config.KNOWLEDGE_STORE_DIR } : {}),
991
1008
  ...(config.TMP_DIR ? { PI_RESEARCH_TMP_DIR: config.TMP_DIR } : {}),
992
1009
  PI_RESEARCH_REPORT_EXPORT_ENABLED: String(config.RESEARCH_REPORT_EXPORT_ENABLED),
@@ -1166,9 +1183,47 @@ export function saveConfig(config: Config, scope: 'local' | 'user' = 'local', cw
1166
1183
  /**
1167
1184
  * Config cache keyed by normalized CWD.
1168
1185
  * Avoids stale cached config when the process CWD changes between sessions.
1186
+ *
1187
+ * The cache is keyed by CWD *and* a fingerprint of the files it was built from, so
1188
+ * an edit to config.env made outside this process (an editor, sed, a second pi
1189
+ * session, the standalone CLI) is picked up on the next getConfig() instead of being
1190
+ * silently ignored until the process exits.
1191
+ *
1192
+ * Why this matters: pi sessions live for days. A process started 2026-10-22 18:30
1193
+ * kept the RESEARCH_MODEL it read at startup (ling-3.0-flash) for the next 60 hours,
1194
+ * even though config.env switched to deepseek-flash-latest at 20:13 that evening —
1195
+ * two research runs on 2026-10-24/25 then used a model the user had already replaced,
1196
+ * and one of them died on that model's upstream rate limit.
1169
1197
  */
1170
1198
  const configCache = new Map<string, Config>();
1171
1199
 
1200
+ /** configCache key → fingerprint of the config files that produced its entry. */
1201
+ const configFingerprints = new Map<string, string>();
1202
+
1203
+ /**
1204
+ * Identity of every file loadEnvFiles() reads for this (cwd, iface) pair.
1205
+ *
1206
+ * existsSync is checked before statSync so a missing file contributes a CONSTANT
1207
+ * marker: a test that mocks node:fs (statSync returning a fresh Date.now() each
1208
+ * call, existsSync false) must not make the cache look permanently stale, which
1209
+ * would break setConfig()'s override-on-top-of-cache contract.
1210
+ */
1211
+ function configSourcesFingerprint(cwd: string, iface?: ConfigInterface): string {
1212
+ const sources = [getGlobalEnvFilePath(), getProjectSettingsRegistryPath(), getLocalEnvFilePath(cwd)];
1213
+ if (iface) sources.push(getInterfaceEnvFilePath(iface));
1214
+ return sources
1215
+ .map((file) => {
1216
+ try {
1217
+ if (!fs.existsSync(file)) return `${file}=absent`;
1218
+ const st = fs.statSync(file);
1219
+ return `${file}=${st.mtimeMs}:${st.size}`;
1220
+ } catch {
1221
+ return `${file}=unreadable`;
1222
+ }
1223
+ })
1224
+ .join('|');
1225
+ }
1226
+
1172
1227
  /**
1173
1228
  * Internal factory for creating a configuration object from env.
1174
1229
  */
@@ -1223,6 +1278,7 @@ export function createConfig(env: Record<string, string | undefined>, processEnv
1223
1278
  MIGRATION_STRATEGY: parseEnvEnum(e, 'PI_RESEARCH_MIGRATION_STRATEGY', ['drop', 're-embed', 'backup'] as const, DEFAULTS.MIGRATION_STRATEGY),
1224
1279
  CONSOLE_LOG: parseEnvBool(e, 'PI_RESEARCH_CONSOLE_LOG', DEFAULTS.CONSOLE_LOG),
1225
1280
  RESEARCH_MODEL: parseEnvString(e, 'PI_RESEARCH_MODEL', DEFAULTS.RESEARCH_MODEL),
1281
+ COORDINATOR_MODEL: parseEnvString(e, 'PI_RESEARCH_COORDINATOR_MODEL', DEFAULTS.COORDINATOR_MODEL),
1226
1282
  KNOWLEDGE_STORE_DIR: parseEnvString(e, 'PI_RESEARCH_KNOWLEDGE_DIR', DEFAULTS.KNOWLEDGE_STORE_DIR),
1227
1283
  TMP_DIR: parseEnvString(e, 'PI_RESEARCH_TMP_DIR', DEFAULTS.TMP_DIR),
1228
1284
  RESEARCH_REPORT_EXPORT_ENABLED: parseEnvBool(e, 'PI_RESEARCH_REPORT_EXPORT_ENABLED', DEFAULTS.RESEARCH_REPORT_EXPORT_ENABLED),
@@ -1276,12 +1332,24 @@ export function createConfig(env: Record<string, string | undefined>, processEnv
1276
1332
  export function getConfig(cwd: string = process.cwd(), iface?: ConfigInterface): Config {
1277
1333
  const cacheKey = `${normalizeWorkspacePath(cwd)}:${iface ?? ''}`;
1278
1334
  const cached = configCache.get(cacheKey);
1279
- if (cached) return cached;
1335
+ if (cached && configFingerprints.get(cacheKey) === configSourcesFingerprint(cwd, iface)) {
1336
+ return cached;
1337
+ }
1338
+ if (cached) {
1339
+ logger.info(`[config] Configuration files changed on disk; reloading for ${cwd} (cached values were from process start)`);
1340
+ }
1280
1341
 
1342
+ // Fingerprint BEFORE the read, and store exactly that value: a write landing during
1343
+ // loadEnvFiles then leaves the entry stale (fingerprint says "as it was before the
1344
+ // read"), so the next call reloads. Fingerprinting after the read would stamp the
1345
+ // entry fresh with the OLD values and reintroduce the very bug this cache check fixes,
1346
+ // for one edit window.
1347
+ const fingerprint = configSourcesFingerprint(cwd, iface);
1281
1348
  const e = loadEnvFiles(cwd, iface);
1282
1349
  const config = createConfig(e, process.env);
1283
1350
 
1284
1351
  configCache.set(cacheKey, config);
1352
+ configFingerprints.set(cacheKey, fingerprint);
1285
1353
  return config;
1286
1354
  }
1287
1355
 
@@ -1293,10 +1361,15 @@ export function setConfig(config: Partial<Config>, iface?: ConfigInterface): voi
1293
1361
  const current = getConfig(process.cwd(), iface);
1294
1362
  const cacheKey = `${normalizeWorkspacePath(process.cwd())}:${iface ?? ''}`;
1295
1363
  configCache.set(cacheKey, { ...current, ...config });
1364
+ // Pin the fingerprint to the CURRENT files so the override survives the next
1365
+ // getConfig() — but still yields to a real on-disk change (the on-disk value wins
1366
+ // over a process-local override, which is what a user editing config.env expects).
1367
+ configFingerprints.set(cacheKey, configSourcesFingerprint(process.cwd(), iface));
1296
1368
  }
1297
1369
 
1298
1370
  export function resetConfig(): void {
1299
1371
  configCache.clear();
1372
+ configFingerprints.clear();
1300
1373
  warnedLegacyEnvVars = false;
1301
1374
  }
1302
1375
 
@@ -9,6 +9,12 @@
9
9
  /**
10
10
  * Steering message status lifecycle:
11
11
  * queued → active (consumed by orchestrator) or queued → popped (removed by user via Alt+P)
12
+ *
13
+ * A popped message can additionally be FORWARDED to pi (Alt+P hands it to pi's own
14
+ * steering queue). That is tracked separately (forwardedToPiAt) rather than as a
15
+ * fourth status: once forwarded, the message has left this extension's control —
16
+ * pi owns delivery — and the only remaining question is whether pi still holds it
17
+ * un-delivered, which decides whether Esc may cancel pi's agent turn.
12
18
  */
13
19
  export type SteeringMessageStatus = 'queued' | 'active' | 'popped';
14
20
 
@@ -28,4 +34,9 @@ export interface SteeringMessage {
28
34
  consumedAt: number | null;
29
35
  /** Timestamp when the message was popped by the user */
30
36
  poppedAt: number | null;
37
+ /**
38
+ * Timestamp when a popped message was successfully handed to pi's own steering
39
+ * queue (Alt+P). null while it is not, and on every non-popped message.
40
+ */
41
+ forwardedToPiAt: number | null;
31
42
  }