@lincoln504/pi-research 1.7.21 → 1.7.22

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,129 @@
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, h2, h3, h4, 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.
89
+ if ((h0 & 0xfe00) === 0xfc00) return true;
90
+ if ((h0 & 0xffc0) === 0xfe80) return true;
91
+ if ((h0 & 0xff00) === 0xff00) return true;
92
+ return false;
93
+ }
94
+
95
+ /**
96
+ * True when `address` is a loopback, private, link-local, CGNAT, multicast, reserved or
97
+ * otherwise unparseable IP ADDRESS that the proxy must refuse to connect to.
98
+ *
99
+ * Takes an address, never a hostname. A hostname is not parseable as an address, so
100
+ * passing one lands in the fail-closed branch and blocks it — see
101
+ * `isBlockedProxyTarget`, which is what callers wanting to judge a host:port want.
102
+ */
103
+ export function isBlockedDestination(address) {
104
+ if (typeof address !== 'string' || address === '') return true;
105
+ if (address.includes(':')) return isBlockedIpv6(address);
106
+ return isBlockedIpv4(address);
107
+ }
108
+
109
+ /**
110
+ * Decide a SOCKS request's destination before DNS: refuses names that resolve only to the
111
+ * local host, refuses IP literals that point at internal space, and passes hostnames
112
+ * through to be judged AFTER resolution (that second check is the load-bearing one, since
113
+ * a name can resolve anywhere).
114
+ *
115
+ * Do not collapse this into `isBlockedDestination(host)`: every hostname is unparseable
116
+ * as an address, so that call refuses everything. It did, on a live run: Firefox sends
117
+ * `socks_remote_dns: true` domain-type requests for every hop, so a hostname-stage call
118
+ * to the address guard refused all traffic, including the DuckDuckGo pins.
119
+ */
120
+ export function isBlockedProxyTarget(host) {
121
+ if (typeof host !== 'string' || host === '') return true;
122
+ const name = host.toLowerCase().replace(/\.$/, '');
123
+ // `localhost` and `*.localhost` are loopback by name and never reach DNS.
124
+ if (name === 'localhost' || name.endsWith('.localhost')) return true;
125
+ // An IP literal needs no resolution, so judge it now.
126
+ if (net.isIP(name) !== 0) return isBlockedDestination(name);
127
+ // A domain: judged by the addresses it resolves to (see the proxy's resolve() filter).
128
+ return false;
129
+ }
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
  }
@@ -0,0 +1,104 @@
1
+ /**
2
+ * Initial-coordinator model selection.
3
+ *
4
+ * Round 1 planning is the one research call that does NOT use the research model.
5
+ * It uses the parent chat's model so the coordinator prompt shares a cache lineage
6
+ * with the conversation that triggered the tool — same provider, same model, same
7
+ * cached prefix. That is a real saving and stays the default.
8
+ *
9
+ * It is a bad default when the chat model is not a planner. Observed 2026-10-25 on
10
+ * this host: the chat model was a local llama-swap server with one seat, and round-1
11
+ * planning alone took 2m07s (4,886 tokens) while the hosted research model planned
12
+ * the same query in seconds. A single-seat local server also refuses a concurrent
13
+ * request from the owner, so a long coordinator call is felt by the user directly.
14
+ * `PI_RESEARCH_COORDINATOR_MODEL=research` (or an explicit `provider/id`) opts out.
15
+ *
16
+ * Kept as a pure function (no registry, no config import) so the precedence is
17
+ * testable without a live model registry; the caller supplies the lookup.
18
+ */
19
+
20
+ export type CoordinatorModelChoice =
21
+ /** `host` / unset — the chat's model (default). */
22
+ | { kind: 'host' }
23
+ /** `research` — the research model, same as rounds 2+. */
24
+ | { kind: 'research' }
25
+ /** An explicit model reference the caller must resolve. */
26
+ | { kind: 'explicit'; reference: string };
27
+
28
+ /** Parse the configured value into a choice. Unset/blank → host. */
29
+ export function parseCoordinatorModelChoice(value: string | undefined | null): CoordinatorModelChoice {
30
+ const raw = (value ?? '').trim();
31
+ if (raw === '' || raw.toLowerCase() === 'host') return { kind: 'host' };
32
+ if (raw.toLowerCase() === 'research') return { kind: 'research' };
33
+ return { kind: 'explicit', reference: raw };
34
+ }
35
+
36
+ export interface ResolveCoordinatorModelOptions<M> {
37
+ /** Raw `COORDINATOR_MODEL` setting. */
38
+ readonly setting: string | undefined;
39
+ /** The parent chat's model (`ctx.model`). */
40
+ readonly hostModel: M | undefined;
41
+ /** The resolved research model. */
42
+ readonly researchModel: M;
43
+ /** Look up an explicit model reference; return undefined when unknown. */
44
+ readonly findByReference?: (reference: string) => M | undefined;
45
+ /** Called when an explicit reference cannot be resolved (for a warning). */
46
+ readonly onUnresolved?: (reference: string) => void;
47
+ }
48
+
49
+ /**
50
+ * Pick the model for round-1 planning.
51
+ *
52
+ * An explicit reference that cannot be resolved falls back to the research model,
53
+ * NOT to the host model: the user asked to stop planning on the host model, so a
54
+ * typo must not silently restore it. (The opposite would be a trap — the config
55
+ * looks applied while the behaviour is the one it was meant to change.)
56
+ */
57
+ export function resolveCoordinatorModel<M>(
58
+ options: ResolveCoordinatorModelOptions<M>,
59
+ ): M {
60
+ const { setting, hostModel, researchModel, findByReference, onUnresolved } = options;
61
+ const choice = parseCoordinatorModelChoice(setting);
62
+ switch (choice.kind) {
63
+ case 'research':
64
+ return researchModel;
65
+ case 'explicit': {
66
+ const found = findByReference?.(choice.reference);
67
+ if (found) return found;
68
+ onUnresolved?.(choice.reference);
69
+ return researchModel;
70
+ }
71
+ case 'host':
72
+ default:
73
+ return hostModel ?? researchModel;
74
+ }
75
+ }
76
+
77
+ /**
78
+ * Strict `provider/id` (or authed bare-id) lookup for an explicit reference.
79
+ *
80
+ * Deliberately NOT resolveResearchModel: that function falls back through
81
+ * RESEARCH_MODEL and then to "the first available model", so it can never return
82
+ * undefined. Using it as the existence check for COORDINATOR_MODEL meant a typo
83
+ * silently ran on an arbitrary available model and the warning never fired.
84
+ *
85
+ * Returns undefined when the reference matches nothing.
86
+ */
87
+ export function findModelByReference<M extends { provider: string; id: string }>(
88
+ reference: string,
89
+ models: readonly M[],
90
+ available: readonly M[] = [],
91
+ ): M | undefined {
92
+ // An exact `provider/id` is unambiguous, but the registry can list the same pair twice
93
+ // (a keyless OAuth-style entry next to an authed one), so prefer the entry that is
94
+ // actually usable before falling back to the full list.
95
+ const exact = available.find((m) => `${m.provider}/${m.id}` === reference)
96
+ ?? models.find((m) => `${m.provider}/${m.id}` === reference);
97
+ if (exact) return exact;
98
+ // Bare id: prefer an entry whose provider actually has auth, mirroring
99
+ // resolveResearchModel's matchById, so a keyless duplicate cannot win.
100
+ const sameId = models.filter((m) => m.id === reference);
101
+ if (sameId.length === 0) return undefined;
102
+ const authed = new Set(available.map((m) => `${m.provider}/${m.id}`));
103
+ return sameId.find((m) => authed.has(`${m.provider}/${m.id}`)) ?? sameId[0];
104
+ }
@@ -16,6 +16,8 @@ import type {
16
16
  GeneratePlanOptions
17
17
  } from './service-interfaces.ts';
18
18
  import { logger } from '../logger.ts';
19
+ import { metrics } from '../utils/metrics.ts';
20
+ import { isRateLimitError, parseRetryAfterMs, rateLimitBackoffMs } from '../utils/provider-errors.ts';
19
21
  import { completeSimple } from './llm/pi-ai-completion.ts';
20
22
  import { injectCurrentDate } from './llm/inject-date.ts';
21
23
  import { loadPrompt } from './llm/prompts.ts';
@@ -55,6 +57,26 @@ import {
55
57
  // (repeated full LLM_TIMEOUT_MS) still degrades to the deterministic fallback plan within a
56
58
  // sane wall-clock budget rather than multiplying a 5-minute timeout many times over.
57
59
  const LLM_MAX_RETRIES = 2;
60
+
61
+ /**
62
+ * Let the coordinator / research-lead / synthesis retries spend a REAL wait on a rate
63
+ * limit instead of the 1s/2s ordinary step.
64
+ *
65
+ * Observed 2026-10-25: the round-2 router 429'd three times in ~4s (`retrying in
66
+ * 1098ms` / `2738ms` in the log) and the orchestrator degraded to "continue the prior
67
+ * agenda" while the provider's shared pool was still refusing requests six minutes
68
+ * later. The researcher loop got a 15s/30s/60s path for exactly this reason; without
69
+ * the same treatment here the highest-value calls in the run still give up in seconds.
70
+ *
71
+ * Returns null for every non-rate-limit error, so the ordinary curve (and its
72
+ * maxDelay bound) is untouched.
73
+ */
74
+ function rateLimitDelayFor(nextAttempt: number, error: Error): number | null {
75
+ if (!isRateLimitError(error)) return null;
76
+ const delay = rateLimitBackoffMs(nextAttempt, parseRetryAfterMs(error));
77
+ metrics.increment('planning_rate_limit_backoff_total', 1, { nextAttempt: String(nextAttempt) });
78
+ return delay;
79
+ }
58
80
  const LLM_RETRY_INITIAL_DELAY_MS = 1000;
59
81
  const LLM_RETRY_MAX_DELAY_MS = 8000;
60
82
 
@@ -479,6 +501,7 @@ export class PlanningService implements IPlanningService {
479
501
  label: 'coordinator-generatePlan',
480
502
  signal,
481
503
  isTransientError: (err) => isRetriableLlmError(err, signal),
504
+ delayFor: rateLimitDelayFor,
482
505
  },
483
506
  );
484
507
 
@@ -1148,6 +1171,7 @@ export class PlanningService implements IPlanningService {
1148
1171
  label,
1149
1172
  signal,
1150
1173
  isTransientError: (err) => isRetriableLlmError(err, signal),
1174
+ delayFor: rateLimitDelayFor,
1151
1175
  },
1152
1176
  );
1153
1177
 
package/src/index.ts CHANGED
@@ -22,7 +22,7 @@ import { metrics } from './utils/metrics.ts';
22
22
  import { handleResearchConfigCommand } from './research-config.ts';
23
23
  import { loadPrompt } from './core/llm/prompts.ts';
24
24
  import { buildResearchDepthGuidance, buildEscalationNudge } from './prompts/research-depth-guidance.ts';
25
- import { clearAllSessionState, addSteeringMessage, getSteeringMessages, normalizeSessionId, getActiveSessionCount, popQueuedMessages, requeuePoppedMessage, getAllTrackedSessions, getPiActiveSessionOrder, getPiActivePanels } from './orchestration/session-state.ts';
25
+ import { clearAllSessionState, addSteeringMessage, getSteeringMessages, normalizeSessionId, getActiveSessionCount, popQueuedMessages, requeuePoppedMessage, markSteeringForwardedToPi, getAllTrackedSessions, getPiActiveSessionOrder, getPiActivePanels } from './orchestration/session-state.ts';
26
26
  import { initGlobalTuiController, disposeGlobalTuiController } from './tui/tui-controller.ts';
27
27
  import { registerCoreServices, initializeCoreServices, disposeCoreServices } from './core/service-initialization.ts';
28
28
  import { getServiceContainer, resetServiceContainer } from './core/service-registry.ts';
@@ -428,16 +428,22 @@ export default async function (pi: ExtensionAPI) {
428
428
  // into chat, the agent acts on it. (The input handler ignores source 'extension',
429
429
  // so this is not re-captured into the research queue.)
430
430
  let sent = 0;
431
+ const sentIds: string[] = [];
431
432
  for (const msg of popped) {
432
433
  try {
433
434
  await pi.sendUserMessage(msg.text, { deliverAs: 'steer' });
434
435
  sent++;
436
+ sentIds.push(msg.id);
435
437
  } catch (err) {
436
438
  // Never lose the user's words: restore the message to queued (still poppable).
437
439
  logger.warn('[pi-research] Failed to forward popped steering to pi:', err);
438
440
  requeuePoppedMessage(piSessionId, msg.id);
439
441
  }
440
442
  }
443
+ // Remember what pi now owns. pi holds it in its OWN steering queue until the
444
+ // next agent step, and the global TUI controller must not let an Esc destroy it
445
+ // on the way there (see hasForwardedSteering / the Esc branch).
446
+ markSteeringForwardedToPi(piSessionId, sentIds);
441
447
 
442
448
  if (ctx.hasUI) {
443
449
  if (sent > 0) {
@@ -0,0 +1,113 @@
1
+ /**
2
+ * Local SOCKS proxy preference for the browser workers.
3
+ *
4
+ * `~/.pi/research/proxy.json` ({"host":"127.0.0.1","port":1080}) routes every
5
+ * browser request through a local SOCKS proxy. It exists because the system
6
+ * resolver returns an unreachable DuckDuckGo front-door IP from this machine's
7
+ * egress path; the local proxy (scripts/ddg-socks-proxy.mjs) pins DDG hostnames
8
+ * to the verified-live IP. A file rather than an env var, so a long-lived leader
9
+ * picks it up without a restart.
10
+ *
11
+ * It lives in its own module because TWO code paths in the same worker process
12
+ * need it, for different reasons:
13
+ * • thread-worker-browser.ts — to launch the browser through it, and
14
+ * • thread-worker-messaging.ts — to know that a response's `serverAddr()` is
15
+ * the PROXY hop, not the origin, so the DNS-rebinding backstop does not
16
+ * condemn every proxied scrape (see isProxyHopAddress).
17
+ *
18
+ * Read fresh (short cache) so enabling/disabling the proxy does not need a
19
+ * process restart, matching how the launcher already treats the file.
20
+ */
21
+
22
+ import { existsSync, readFileSync } from 'node:fs';
23
+ import { homedir } from 'node:os';
24
+
25
+ export interface SocksProxyEndpoint {
26
+ readonly host: string;
27
+ readonly port: number;
28
+ }
29
+
30
+ /** Override the preference file (tests, and non-default layouts). */
31
+ function proxyConfigPath(): string {
32
+ return process.env['PI_RESEARCH_PROXY_JSON'] || `${homedir()}/.pi/research/proxy.json`;
33
+ }
34
+
35
+ let cached: SocksProxyEndpoint | null | undefined;
36
+ let cachedAt = 0;
37
+ const CACHE_TTL_MS = 10_000;
38
+
39
+ /**
40
+ * The configured SOCKS endpoint, or null when the proxy is off.
41
+ * Never throws: an unreadable/malformed file means "no proxy", exactly as the
42
+ * launcher treats it.
43
+ */
44
+ export function getSocksProxyEndpoint(): SocksProxyEndpoint | null {
45
+ const now = Date.now();
46
+ if (cached !== undefined && now - cachedAt < CACHE_TTL_MS) return cached;
47
+ cachedAt = now;
48
+ try {
49
+ const file = proxyConfigPath();
50
+ if (!existsSync(file)) {
51
+ cached = null;
52
+ return cached;
53
+ }
54
+ const cfg = JSON.parse(readFileSync(file, 'utf8')) as { host?: string; port?: number };
55
+ const host = cfg.host ?? '127.0.0.1';
56
+ const port = cfg.port ?? 1080;
57
+ cached = host ? { host, port } : null;
58
+ return cached;
59
+ } catch {
60
+ cached = null;
61
+ return cached;
62
+ }
63
+ }
64
+
65
+ /** Firefox prefs that route the browser through the configured SOCKS proxy. */
66
+ export function loadSocksProxyPrefs(): Record<string, string | number | boolean> {
67
+ const endpoint = getSocksProxyEndpoint();
68
+ if (!endpoint) return {};
69
+ return {
70
+ 'network.proxy.type': 1,
71
+ 'network.proxy.socks': endpoint.host,
72
+ 'network.proxy.socks_port': endpoint.port,
73
+ 'network.proxy.socks_remote_dns': true,
74
+ 'network.proxy.socks_version': 5,
75
+ 'network.proxy.no_proxies_on': '',
76
+ };
77
+ }
78
+
79
+ /** Drop the memoized endpoint (tests; also called when the file changes). */
80
+ export function resetSocksProxyCache(): void {
81
+ cached = undefined;
82
+ cachedAt = 0;
83
+ }
84
+
85
+ /**
86
+ * True when `ip` describes the proxy hop rather than the origin server.
87
+ *
88
+ * PROVEN behaviour (measured 2026-10-25 on this machine, camoufox 0.5.8): through
89
+ * the SOCKS proxy, `response.serverAddr().ipAddress` for https://example.com is
90
+ * `0.0.0.0`; with the proxy off it is the real origin IP (`104.20.23.154`).
91
+ *
92
+ * Firefox cannot report the origin's address when a SOCKS5 proxy with remote DNS
93
+ * resolves and connects on its behalf, so `0.0.0.0`/`::` mean "unknown", NOT
94
+ * "connect to the unspecified address". Treating unknown as private poisoned
95
+ * every proxied scrape: from the day the proxy landed (2026-09-03) until this
96
+ * fix, 100% of browser-fallback scrapes failed with
97
+ * 'Fetch blocked: a response was served from a private/reserved address', which
98
+ * removed the path that gets content from sites answering a plain fetch with 403
99
+ * (Stack Overflow, Android developer docs, DeepWiki were the ones failing in the
100
+ * observed runs; some fallbacks fail for unrelated reasons too, so this was the
101
+ * largest single cause rather than the only one).
102
+ *
103
+ * The check is deliberately gated on a configured proxy: with no proxy, Firefox
104
+ * reports the true remote address, and an unspecified address there is anomalous
105
+ * enough to keep blocking.
106
+ */
107
+ export function isProxyHopAddress(ip: string, proxy: SocksProxyEndpoint | null = getSocksProxyEndpoint()): boolean {
108
+ if (!proxy) return false;
109
+ const addr = ip.trim().toLowerCase().replace(/^\[|\]$/g, '');
110
+ if (addr === '' || addr === '0.0.0.0' || addr === '::' || addr === '::0') return true;
111
+ const proxyHost = proxy.host.trim().toLowerCase().replace(/^\[|\]$/g, '');
112
+ return addr === proxyHost;
113
+ }
@@ -9,8 +9,7 @@
9
9
  */
10
10
 
11
11
  import { platform } from 'node:os';
12
- import { readFileSync, existsSync } from 'node:fs';
13
- import { homedir } from 'node:os';
12
+ import { loadSocksProxyPrefs } from './proxy-prefs.ts';
14
13
  import { setupMocking } from './thread-worker-messaging.ts';
15
14
  import { redactSecrets } from '../../utils/log-utils.ts';
16
15
  import { resolveHeadlessMode, BROWSER_LAUNCH_TIMEOUT_MS, CONTEXT_CREATION_TIMEOUT_MS } from './config.ts';
@@ -21,25 +20,10 @@ import { resolveHeadlessMode, BROWSER_LAUNCH_TIMEOUT_MS, CONTEXT_CREATION_TIMEOU
21
20
  // returns an unreachable DuckDuckGo front-door IP from this machine's egress
22
21
  // path; the local proxy pins DDG hostnames to the verified-live IP. Uses a
23
22
  // file rather than env so a long-lived leader picks it up without a restart.
24
- function loadSocksProxyPrefs(): Record<string, string | number | boolean> {
25
- try {
26
- const p = `${homedir()}/.pi/research/proxy.json`;
27
- if (!existsSync(p)) return {};
28
- const cfg = JSON.parse(readFileSync(p, 'utf8')) as { host?: string; port?: number };
29
- const host = cfg.host ?? '127.0.0.1';
30
- const port = cfg.port ?? 1080;
31
- return {
32
- 'network.proxy.type': 1,
33
- 'network.proxy.socks': host,
34
- 'network.proxy.socks_port': port,
35
- 'network.proxy.socks_remote_dns': true,
36
- 'network.proxy.socks_version': 5,
37
- 'network.proxy.no_proxies_on': '',
38
- };
39
- } catch {
40
- return {};
41
- }
42
- }
23
+ //
24
+ // The reader now lives in ./proxy-prefs.ts: the scrape path has to consult the
25
+ // SAME setting to know that a response's serverAddr() is the proxy hop rather
26
+ // than the origin (see isProxyHopAddress there).
43
27
 
44
28
  let browser: any = null;
45
29
  let initPromise: Promise<void> | null = null;