@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,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,124 @@
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?: unknown; port?: unknown };
55
+ // Type-check the values: a hand-edited file with a numeric host or an
56
+ // out-of-range port must mean "no proxy", not a browser launched with a
57
+ // nonsense endpoint.
58
+ const host = cfg.host === undefined ? '127.0.0.1' : typeof cfg.host === 'string' ? cfg.host.trim() : '';
59
+ const port = cfg.port === undefined ? 1080 : Number.isInteger(cfg.port) ? (cfg.port as number) : -1;
60
+ if (host === '' || port < 1 || port > 65535) {
61
+ cached = null;
62
+ return cached;
63
+ }
64
+ cached = { host, port };
65
+ return cached;
66
+ } catch {
67
+ cached = null;
68
+ return cached;
69
+ }
70
+ }
71
+
72
+ /** Firefox prefs that route the browser through the configured SOCKS proxy. */
73
+ export function loadSocksProxyPrefs(): Record<string, string | number | boolean> {
74
+ const endpoint = getSocksProxyEndpoint();
75
+ if (!endpoint) return {};
76
+ return {
77
+ 'network.proxy.type': 1,
78
+ 'network.proxy.socks': endpoint.host,
79
+ 'network.proxy.socks_port': endpoint.port,
80
+ 'network.proxy.socks_remote_dns': true,
81
+ 'network.proxy.socks_version': 5,
82
+ 'network.proxy.no_proxies_on': '',
83
+ };
84
+ }
85
+
86
+ /** Drop the memoized endpoint (tests; also called when the file changes). */
87
+ export function resetSocksProxyCache(): void {
88
+ cached = undefined;
89
+ cachedAt = 0;
90
+ }
91
+
92
+ /**
93
+ * True when `ip` describes the proxy hop rather than the origin server.
94
+ *
95
+ * PROVEN behaviour (measured 2026-10-25 on this machine, camoufox 0.5.8): through
96
+ * the SOCKS proxy, `response.serverAddr().ipAddress` for https://example.com is
97
+ * `0.0.0.0`; with the proxy off it is the real origin IP (`104.20.23.154`).
98
+ *
99
+ * Firefox cannot report the origin's address when a SOCKS5 proxy with remote DNS
100
+ * resolves and connects on its behalf, so `0.0.0.0`/`::` mean "unknown", NOT
101
+ * "connect to the unspecified address". Treating unknown as private poisoned
102
+ * every proxied scrape: from the day the proxy landed (2026-09-03) until this
103
+ * fix, 100% of browser-fallback scrapes failed with
104
+ * 'Fetch blocked: a response was served from a private/reserved address', which
105
+ * removed the path that gets content from sites answering a plain fetch with 403
106
+ * (Stack Overflow, Android developer docs, DeepWiki were the ones failing in the
107
+ * observed runs; some fallbacks fail for unrelated reasons too, so this was the
108
+ * largest single cause rather than the only one).
109
+ *
110
+ * The check is deliberately gated on a configured proxy: with no proxy, Firefox
111
+ * reports the true remote address, and an unspecified address there is anomalous
112
+ * enough to keep blocking.
113
+ *
114
+ * Only the unspecified addresses are exempt, never the proxy host itself:
115
+ * with the proxy on 127.0.0.1 (the normal configuration), an origin address of
116
+ * 127.0.0.1 is indistinguishable from a genuine loopback origin, and the
117
+ * conservative call is to poison the scrape. Measured with camoufox 0.5.8 the
118
+ * hop reports 0.0.0.0, which is covered above.
119
+ */
120
+ export function isProxyHopAddress(ip: string, proxy: SocksProxyEndpoint | null = getSocksProxyEndpoint()): boolean {
121
+ if (!proxy) return false;
122
+ const addr = ip.trim().toLowerCase().replace(/^\[|\]$/g, '');
123
+ return addr === '' || addr === '0.0.0.0' || addr === '::' || addr === '::0';
124
+ }
@@ -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;
@@ -10,6 +10,7 @@ import { appendFileSync, promises as fsp } from 'node:fs';
10
10
  import { redactSecrets } from '../../utils/log-utils.ts';
11
11
  import { safeUnref } from '../../utils/safe-unref.ts';
12
12
  import { MAX_HTML_SIZE, MAX_PDF_SIZE } from '../../web-research/scraper-types.ts';
13
+ import { isProxyHopAddress } from './proxy-prefs.ts';
13
14
 
14
15
  /**
15
16
  * Mutex lock to serialize page creation. Playwright/Firefox can deadlock if newPage()
@@ -266,7 +267,7 @@ export async function setupMocking(context: any): Promise<void> {
266
267
  async function extractSearchResults(page: any): Promise<any[]> {
267
268
  return await page.evaluate(() => {
268
269
  const found: any[] = [];
269
- // @ts-ignore - document is available in browser context
270
+ // document is available in browser context (callback runs in the page)
270
271
  // eslint-disable-next-line no-undef
271
272
  const links = Array.from(document.querySelectorAll('a.result-link, a.result__a'));
272
273
  links.forEach((link: any) => {
@@ -824,6 +825,10 @@ export async function executeScrapeTask(
824
825
  .then((addr: { ipAddress?: string } | null) => {
825
826
  const ip = addr?.ipAddress;
826
827
  if (!ip || poisonedError) return;
828
+ // Through the configured SOCKS proxy Firefox reports the proxy hop
829
+ // (`0.0.0.0`), not the origin — validating that as if it were the
830
+ // origin condemned every proxied scrape. See isProxyHopAddress.
831
+ if (isProxyHopAddress(ip)) return;
827
832
  try {
828
833
  validateForWorkerSync(ip.includes(':') ? `http://[${ip}]/` : `http://${ip}/`);
829
834
  } catch (cause: unknown) {
@@ -879,7 +884,7 @@ export async function executeScrapeTask(
879
884
  // prevent the TCP connection itself, but it stops the rendered response (e.g. cloud IAM
880
885
  // credentials) from being exfiltrated to the researcher/report, which is the real harm here.
881
886
  const serverAddr = await response?.serverAddr().catch(() => null);
882
- if (serverAddr?.ipAddress) {
887
+ if (serverAddr?.ipAddress && !isProxyHopAddress(serverAddr.ipAddress)) {
883
888
  const ip: string = serverAddr.ipAddress;
884
889
  validateForWorkerSync(ip.includes(':') ? `http://[${ip}]/` : `http://${ip}/`);
885
890
  }
@@ -980,7 +985,7 @@ export async function executeScrapeTask(
980
985
  try {
981
986
  await page.waitForFunction(
982
987
  () => {
983
- // @ts-ignore - document is available in browser context
988
+ // document is available in browser context (callback runs in the page)
984
989
  // eslint-disable-next-line no-undef
985
990
  const body = document.body.innerHTML;
986
991
  return !body.includes('_cf_chl_') &&
@@ -1037,7 +1042,7 @@ export async function executeScrapeTask(
1037
1042
  // Re-validate the final rendered main-frame document's connected IP (catches a client-side
1038
1043
  // navigation to a DNS-rebinding host that occurred after the initial goto passed).
1039
1044
  const finalAddr = await finalMainFrameAddr;
1040
- if (finalAddr?.ipAddress) {
1045
+ if (finalAddr?.ipAddress && !isProxyHopAddress(finalAddr.ipAddress)) {
1041
1046
  const fip: string = finalAddr.ipAddress;
1042
1047
  validateForWorkerSync(fip.includes(':') ? `http://[${fip}]/` : `http://${fip}/`);
1043
1048
  }
@@ -891,7 +891,7 @@ var init_stdio_capture = __esm({
891
891
  });
892
892
 
893
893
  // src/logger.ts
894
- import { appendFileSync, existsSync as existsSync2, mkdirSync, openSync as openSync2, closeSync as closeSync2 } from "node:fs";
894
+ import { appendFileSync, existsSync as existsSync3, mkdirSync, openSync as openSync2, closeSync as closeSync2 } from "node:fs";
895
895
  import { appendFile as appendFile2 } from "node:fs/promises";
896
896
  import { AsyncLocalStorage as AsyncLocalStorage3 } from "node:async_hooks";
897
897
  import * as path3 from "node:path";
@@ -1047,7 +1047,7 @@ var init_logger = __esm({
1047
1047
  this.rotation = new LogRotation(this);
1048
1048
  this.diskSpaceChecker = new DiskSpaceChecker();
1049
1049
  try {
1050
- if (!existsSync2(this.logDir)) {
1050
+ if (!existsSync3(this.logDir)) {
1051
1051
  mkdirSync(this.logDir, { recursive: true, mode: 448 });
1052
1052
  }
1053
1053
  try {
@@ -1721,8 +1721,8 @@ async function disposeSsrfSafeFetcher() {
1721
1721
  const pending = cachedSsrfFetcher;
1722
1722
  cachedSsrfFetcher = void 0;
1723
1723
  if (pending === void 0) return;
1724
- const cached = await pending.catch(() => null);
1725
- const closable = cached?.dispatcher;
1724
+ const cached2 = await pending.catch(() => null);
1725
+ const closable = cached2?.dispatcher;
1726
1726
  if (!closable?.close) return;
1727
1727
  try {
1728
1728
  await closable.close();
@@ -2102,8 +2102,57 @@ function createKillHandler() {
2102
2102
 
2103
2103
  // src/infrastructure/browser/thread-worker-browser.ts
2104
2104
  import { platform as platform2 } from "node:os";
2105
- import { readFileSync, existsSync as existsSync3 } from "node:fs";
2106
- import { homedir as homedir2 } from "node:os";
2105
+
2106
+ // src/infrastructure/browser/proxy-prefs.ts
2107
+ import { existsSync, readFileSync } from "node:fs";
2108
+ import { homedir } from "node:os";
2109
+ function proxyConfigPath() {
2110
+ return process.env["PI_RESEARCH_PROXY_JSON"] || `${homedir()}/.pi/research/proxy.json`;
2111
+ }
2112
+ var cached;
2113
+ var cachedAt = 0;
2114
+ var CACHE_TTL_MS = 1e4;
2115
+ function getSocksProxyEndpoint() {
2116
+ const now = Date.now();
2117
+ if (cached !== void 0 && now - cachedAt < CACHE_TTL_MS) return cached;
2118
+ cachedAt = now;
2119
+ try {
2120
+ const file = proxyConfigPath();
2121
+ if (!existsSync(file)) {
2122
+ cached = null;
2123
+ return cached;
2124
+ }
2125
+ const cfg = JSON.parse(readFileSync(file, "utf8"));
2126
+ const host = cfg.host === void 0 ? "127.0.0.1" : typeof cfg.host === "string" ? cfg.host.trim() : "";
2127
+ const port = cfg.port === void 0 ? 1080 : Number.isInteger(cfg.port) ? cfg.port : -1;
2128
+ if (host === "" || port < 1 || port > 65535) {
2129
+ cached = null;
2130
+ return cached;
2131
+ }
2132
+ cached = { host, port };
2133
+ return cached;
2134
+ } catch {
2135
+ cached = null;
2136
+ return cached;
2137
+ }
2138
+ }
2139
+ function loadSocksProxyPrefs() {
2140
+ const endpoint = getSocksProxyEndpoint();
2141
+ if (!endpoint) return {};
2142
+ return {
2143
+ "network.proxy.type": 1,
2144
+ "network.proxy.socks": endpoint.host,
2145
+ "network.proxy.socks_port": endpoint.port,
2146
+ "network.proxy.socks_remote_dns": true,
2147
+ "network.proxy.socks_version": 5,
2148
+ "network.proxy.no_proxies_on": ""
2149
+ };
2150
+ }
2151
+ function isProxyHopAddress(ip, proxy = getSocksProxyEndpoint()) {
2152
+ if (!proxy) return false;
2153
+ const addr = ip.trim().toLowerCase().replace(/^\[|\]$/g, "");
2154
+ return addr === "" || addr === "0.0.0.0" || addr === "::" || addr === "::0";
2155
+ }
2107
2156
 
2108
2157
  // src/infrastructure/browser/thread-worker-messaging.ts
2109
2158
  init_log_utils();
@@ -2403,8 +2452,8 @@ function getCachedSubresourceVerdict(reqUrl, validate) {
2403
2452
  return Promise.resolve(e instanceof Error ? e : new Error(String(e)));
2404
2453
  }
2405
2454
  const now = Date.now();
2406
- const cached = subresourceDnsVerdicts.get(hostname);
2407
- if (cached && cached.expires > now) return cached.verdict;
2455
+ const cached2 = subresourceDnsVerdicts.get(hostname);
2456
+ if (cached2 && cached2.expires > now) return cached2.verdict;
2408
2457
  const verdict = validate(reqUrl).then(
2409
2458
  () => null,
2410
2459
  (e) => e instanceof Error ? e : new Error(String(e))
@@ -2565,6 +2614,7 @@ async function executeScrapeTask(_context, url, signal) {
2565
2614
  const check = Promise.resolve(resp.serverAddr()).then((addr) => {
2566
2615
  const ip = addr?.ipAddress;
2567
2616
  if (!ip || poisonedError) return;
2617
+ if (isProxyHopAddress(ip)) return;
2568
2618
  try {
2569
2619
  validateForWorkerSync(ip.includes(":") ? `http://[${ip}]/` : `http://${ip}/`);
2570
2620
  } catch (cause) {
@@ -2602,7 +2652,7 @@ async function executeScrapeTask(_context, url, signal) {
2602
2652
  return await readPdfDownload(pendingDownload, url, page, pendingAddrChecks, () => poisonedError);
2603
2653
  }
2604
2654
  const serverAddr = await response?.serverAddr().catch(() => null);
2605
- if (serverAddr?.ipAddress) {
2655
+ if (serverAddr?.ipAddress && !isProxyHopAddress(serverAddr.ipAddress)) {
2606
2656
  const ip = serverAddr.ipAddress;
2607
2657
  validateForWorkerSync(ip.includes(":") ? `http://[${ip}]/` : `http://${ip}/`);
2608
2658
  }
@@ -2671,7 +2721,7 @@ async function executeScrapeTask(_context, url, signal) {
2671
2721
  const jitter = process.env["PI_RESEARCH_MOCK_SCRAPE"] === "true" ? 0 : Math.floor(Math.random() * 1e3) + 500;
2672
2722
  if (jitter > 0) await new Promise((r) => setTimeout(r, jitter));
2673
2723
  const finalAddr = await finalMainFrameAddr;
2674
- if (finalAddr?.ipAddress) {
2724
+ if (finalAddr?.ipAddress && !isProxyHopAddress(finalAddr.ipAddress)) {
2675
2725
  const fip = finalAddr.ipAddress;
2676
2726
  validateForWorkerSync(fip.includes(":") ? `http://[${fip}]/` : `http://${fip}/`);
2677
2727
  }
@@ -2749,7 +2799,7 @@ function shouldResetBrowser(errorMsg) {
2749
2799
  init_log_utils();
2750
2800
 
2751
2801
  // src/infrastructure/browser/config.ts
2752
- import { platform, homedir } from "node:os";
2802
+ import { platform, homedir as homedir2 } from "node:os";
2753
2803
 
2754
2804
  // src/config.ts
2755
2805
  init_logger();
@@ -11368,9 +11418,24 @@ var ConfigSchema = typebox_exports.Object({
11368
11418
  * When set, this governs the evaluator/synthesis rounds and the researcher
11369
11419
  * sub-agents (both deep and quick) and the knowledge synthesis background LLM.
11370
11420
  * The initial coordinator (round 1 planning) uses the parent chat's model (ctx.model)
11371
- * for prompt-cache continuity with the conversation that triggered research.
11421
+ * by DEFAULT, for prompt-cache continuity with the conversation that triggered
11422
+ * research; COORDINATOR_MODEL overrides that decision (see below).
11372
11423
  */
11373
11424
  RESEARCH_MODEL: typebox_exports.Optional(typebox_exports.String()),
11425
+ /**
11426
+ * Which model runs the INITIAL coordinator (round-1 planning), the one call that
11427
+ * otherwise uses the parent chat's model (`ctx.model`) for prompt-cache continuity:
11428
+ * • `host` (default) — the chat's model, current behaviour.
11429
+ * • `research` — the RESEARCH_MODEL / researcher model, same as every later round.
11430
+ * • `provider/id` (or a bare id) — that model.
11431
+ *
11432
+ * Exists because the chat model is not always a good planner: a local single-seat
11433
+ * server (llama-swap `concurrencyLimit: 1`, 4k output) turns the coordinator call into
11434
+ * minutes of wall clock and can 429 the owner's own next prompt, while a hosted
11435
+ * research model plans the same query in seconds. The cache-lineage benefit is real
11436
+ * but must be opt-out-able. Unset = `host`.
11437
+ */
11438
+ COORDINATOR_MODEL: typebox_exports.Optional(typebox_exports.String()),
11374
11439
  /** Explicit directory for the knowledge store database (overrides default) */
11375
11440
  KNOWLEDGE_STORE_DIR: typebox_exports.Optional(typebox_exports.String()),
11376
11441
  /** Directory for transient browser profile data. Defaults to a disk-backed
@@ -11428,25 +11493,6 @@ var CONTEXT_CREATION_TIMEOUT_MS = 3e4;
11428
11493
  var COLD_START_ALLOWANCE_MS = BROWSER_LAUNCH_TIMEOUT_MS + CONTEXT_CREATION_TIMEOUT_MS;
11429
11494
 
11430
11495
  // src/infrastructure/browser/thread-worker-browser.ts
11431
- function loadSocksProxyPrefs() {
11432
- try {
11433
- const p = `${homedir2()}/.pi/research/proxy.json`;
11434
- if (!existsSync3(p)) return {};
11435
- const cfg = JSON.parse(readFileSync(p, "utf8"));
11436
- const host = cfg.host ?? "127.0.0.1";
11437
- const port = cfg.port ?? 1080;
11438
- return {
11439
- "network.proxy.type": 1,
11440
- "network.proxy.socks": host,
11441
- "network.proxy.socks_port": port,
11442
- "network.proxy.socks_remote_dns": true,
11443
- "network.proxy.socks_version": 5,
11444
- "network.proxy.no_proxies_on": ""
11445
- };
11446
- } catch {
11447
- return {};
11448
- }
11449
- }
11450
11496
  var browser = null;
11451
11497
  var initPromise = null;
11452
11498
  var workerId3 = "";
@@ -269,7 +269,7 @@ export async function initializeDawnWebGPU(): Promise<boolean> {
269
269
  // reason; the adapter probe below is the other native entry point and was
270
270
  // missing it, which is why a plain `knowledge` run still printed them.
271
271
  const adapter = await logger.runCapturingStderr(async () => {
272
- // @ts-ignore — optional dependency
272
+ // webgpu is an optional dependency (types resolve because it is installed for dev)
273
273
  const { create, globals } = await import('webgpu');
274
274
  Object.assign(globalThis, globals);
275
275
  // Use Object.defineProperty — Node.js defines navigator as a configurable getter
@@ -0,0 +1,15 @@
1
+ /**
2
+ * SQL string literal for the knowledge store's DataFusion queries.
3
+ *
4
+ * The store builds LanceDB/DataFusion SQL by string interpolation, and the
5
+ * interpolated values are attacker-influenced (stored URLs, workspace paths,
6
+ * ingestion types). Every interpolated string MUST go through here so the
7
+ * escaping rule is written once and cannot drift across the call sites.
8
+ *
9
+ * DataFusion's string-literal grammar escapes a single quote by doubling it
10
+ * (standard SQL `''`); that is the only escape the engine applies on read-back,
11
+ * which is why doubling is the complete rule for this dialect.
12
+ */
13
+ export function sqlString(value: string): string {
14
+ return `'${value.replace(/'/g, "''")}'`;
15
+ }
@@ -10,6 +10,7 @@
10
10
  // ./lancedb-loader.ts for why that matters.
11
11
  import type * as lancedb from '@lancedb/lancedb';
12
12
  import { logger } from '../logger.ts';
13
+ import { sqlString } from './sql-utils.ts';
13
14
  import { metrics } from '../utils/metrics.ts';
14
15
  import { StoreDocument } from '../core/interfaces/knowledge-interfaces.ts';
15
16
 
@@ -376,9 +377,9 @@ export async function findDocumentsByUrl(
376
377
  const startTime = Date.now();
377
378
 
378
379
  // Escape single quotes in URL to prevent SQL injection
379
- const escapedUrl = url.replace(/'/g, "''");
380
+ const escapedUrl = sqlString(url);
380
381
 
381
- let filter = `url = '${escapedUrl}'`;
382
+ let filter = `url = ${escapedUrl}`;
382
383
  if (scopeFilter) {
383
384
  filter = `(${filter}) AND (${scopeFilter})`;
384
385
  }