@lincoln504/pi-research 1.7.22 → 1.7.24

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.mjs CHANGED
@@ -2013,10 +2013,10 @@ function stripTrailingLlmPunctuation(input) {
2013
2013
  continue;
2014
2014
  }
2015
2015
  if (last === ")" || last === "]" || last === "}") {
2016
- const open5 = last === ")" ? "(" : last === "]" ? "[" : "{";
2016
+ const open6 = last === ")" ? "(" : last === "]" ? "[" : "{";
2017
2017
  let balance = 0;
2018
2018
  for (const ch of s.slice(0, -1)) {
2019
- if (ch === open5) balance++;
2019
+ if (ch === open6) balance++;
2020
2020
  else if (ch === last) balance = Math.max(0, balance - 1);
2021
2021
  }
2022
2022
  if (balance === 0) {
@@ -3039,11 +3039,11 @@ function createConfig(env, processEnv) {
3039
3039
  }
3040
3040
  function getConfig(cwd = process.cwd(), iface) {
3041
3041
  const cacheKey = `${normalizeWorkspacePath(cwd)}:${iface ?? ""}`;
3042
- const cached = configCache.get(cacheKey);
3043
- if (cached && configFingerprints.get(cacheKey) === configSourcesFingerprint(cwd, iface)) {
3044
- return cached;
3042
+ const cached2 = configCache.get(cacheKey);
3043
+ if (cached2 && configFingerprints.get(cacheKey) === configSourcesFingerprint(cwd, iface)) {
3044
+ return cached2;
3045
3045
  }
3046
- if (cached) {
3046
+ if (cached2) {
3047
3047
  logger.info(`[config] Configuration files changed on disk; reloading for ${cwd} (cached values were from process start)`);
3048
3048
  }
3049
3049
  const fingerprint = configSourcesFingerprint(cwd, iface);
@@ -3475,8 +3475,8 @@ function findMatchingBracket(text, start) {
3475
3475
  let depth = 0;
3476
3476
  let inString = false;
3477
3477
  let escaped = false;
3478
- const open5 = text[start];
3479
- const close = open5 === "{" ? "}" : "]";
3478
+ const open6 = text[start];
3479
+ const close = open6 === "{" ? "}" : "]";
3480
3480
  for (let i = start; i < text.length; i++) {
3481
3481
  const ch = text[i];
3482
3482
  if (escaped) {
@@ -3492,7 +3492,7 @@ function findMatchingBracket(text, start) {
3492
3492
  continue;
3493
3493
  }
3494
3494
  if (inString) continue;
3495
- if (ch === open5) depth++;
3495
+ if (ch === open6) depth++;
3496
3496
  else if (ch === close) {
3497
3497
  depth--;
3498
3498
  if (depth === 0) return { index: i, inString: false };
@@ -4209,6 +4209,7 @@ async function retryWithBackoff(fn, options = {}) {
4209
4209
  const startTime = Date.now();
4210
4210
  let lastError = null;
4211
4211
  let attempt = 0;
4212
+ let totalDelayMs = 0;
4212
4213
  metrics.increment("retry_attempts_total", 1, { label: opts.label });
4213
4214
  while (attempt <= opts.maxRetries) {
4214
4215
  try {
@@ -4234,6 +4235,15 @@ async function retryWithBackoff(fn, options = {}) {
4234
4235
  const jitter = Math.random() * 0.5 * baseDelay;
4235
4236
  const override = opts.delayFor?.(attempt + 2, lastError);
4236
4237
  const delay2 = override != null && Number.isFinite(override) && override > 0 ? Math.round(override) : Math.min(baseDelay + jitter, opts.maxDelay);
4238
+ if (opts.maxTotalDelayMs !== void 0 && totalDelayMs + delay2 > opts.maxTotalDelayMs) {
4239
+ const retryAt = new Date(Date.now() + delay2).toISOString().slice(11, 19);
4240
+ metrics.increment("retry_total_delay_exhausted_total", 1, { label: opts.label });
4241
+ throw new Error(
4242
+ `Provider capacity: ${opts.label} asked for a ${Math.round(delay2 / 1e3)}s wait, but only ${Math.max(0, Math.round((opts.maxTotalDelayMs - totalDelayMs) / 1e3))}s of its ${Math.round(opts.maxTotalDelayMs / 1e3)}s total-wait budget is left. Rerun after ${retryAt}Z. Cause: ${lastError.message}`,
4243
+ { cause: error }
4244
+ );
4245
+ }
4246
+ totalDelayMs += delay2;
4237
4247
  metrics.increment("retry_backoff_total", 1, { attempt: String(attempt), label: opts.label });
4238
4248
  metrics.observe("retry_backoff_delay_ms", delay2, { attempt: String(attempt), label: opts.label });
4239
4249
  logger.warn(`[Retry] ${opts.label} failed (attempt ${attempt + 1}/${opts.maxRetries + 1}), retrying in ${Math.round(delay2)}ms: ${lastError.message}`);
@@ -4924,10 +4934,10 @@ async function resolveEmbeddingDevice(requested, model, timeoutMs) {
4924
4934
  if (requested === "cpu") return "cpu";
4925
4935
  if (requested === "webgpu") return "webgpu";
4926
4936
  const signature = hostSignature(model);
4927
- const cached = await readVerdict(signature);
4928
- if (cached !== null) {
4929
- logger.info(`[embedder] WebGPU viability (cached verdict): ${cached ? "viable -> webgpu" : "not viable -> cpu"}`);
4930
- return cached ? "webgpu" : "cpu";
4937
+ const cached2 = await readVerdict(signature);
4938
+ if (cached2 !== null) {
4939
+ logger.info(`[embedder] WebGPU viability (cached verdict): ${cached2 ? "viable -> webgpu" : "not viable -> cpu"}`);
4940
+ return cached2 ? "webgpu" : "cpu";
4931
4941
  }
4932
4942
  if (!await isModelCached(model)) {
4933
4943
  logger.info("[embedder] Embedding model not cached yet \u2014 using CPU for now; WebGPU will be probed once the model is present.");
@@ -5144,17 +5154,17 @@ var init_embedder = __esm({
5144
5154
  this.device = "cpu";
5145
5155
  }
5146
5156
  }
5147
- const cached = await isModelCached(this.model);
5157
+ const cached2 = await isModelCached(this.model);
5148
5158
  logger.info(
5149
- `[embedder] Loading model: ${this.model} (${cached ? "from local cache" : "downloading from HuggingFace"})...`
5159
+ `[embedder] Loading model: ${this.model} (${cached2 ? "from local cache" : "downloading from HuggingFace"})...`
5150
5160
  );
5151
5161
  const env = await getHFEnv();
5152
5162
  const prevAllowRemote = env.allowRemoteModels;
5153
- if (cached) {
5163
+ if (cached2) {
5154
5164
  env.allowRemoteModels = false;
5155
5165
  }
5156
5166
  try {
5157
- const timeoutMs = cached ? 3e4 : this.initializationTimeoutMs;
5167
+ const timeoutMs = cached2 ? 3e4 : this.initializationTimeoutMs;
5158
5168
  const { pipeline: loadedPipeline } = await loadPipelineWithTimeout(this.model, this.device, timeoutMs, this.useCache);
5159
5169
  this.pipeline = loadedPipeline;
5160
5170
  logger.info(`[embedder] Pipeline loaded (device: ${this.device})`);
@@ -5175,7 +5185,7 @@ var init_embedder = __esm({
5175
5185
  this.pipeline = result.pipeline ?? null;
5176
5186
  this.device = "cpu";
5177
5187
  this.gpuLockHeld = false;
5178
- } else if (cached && isCorruptModelError(loadErr)) {
5188
+ } else if (cached2 && isCorruptModelError(loadErr)) {
5179
5189
  const errMsg = loadErr instanceof Error ? loadErr.message : String(loadErr);
5180
5190
  logger.warn(`[embedder] Corrupt model cache detected on load (${errMsg}); purging and re-downloading once`);
5181
5191
  await purgeModelCache(this.model);
@@ -6780,8 +6790,8 @@ var init_file_lock_service = __esm({
6780
6790
  async _resolveOwnerAlive(pid, startTime, memo) {
6781
6791
  if (!memo) return this._isOwnerAlive(pid, startTime);
6782
6792
  const key = `${pid ?? "null"}:${startTime ?? "null"}`;
6783
- const cached = memo.get(key);
6784
- if (cached !== void 0) return cached;
6793
+ const cached2 = memo.get(key);
6794
+ if (cached2 !== void 0) return cached2;
6785
6795
  const alive = await this._isOwnerAlive(pid, startTime);
6786
6796
  memo.set(key, alive);
6787
6797
  return alive;
@@ -7463,6 +7473,16 @@ var init_lancedb_loader = __esm({
7463
7473
  }
7464
7474
  });
7465
7475
 
7476
+ // src/knowledge/sql-utils.ts
7477
+ function sqlString(value) {
7478
+ return `'${value.replace(/'/g, "''")}'`;
7479
+ }
7480
+ var init_sql_utils = __esm({
7481
+ "src/knowledge/sql-utils.ts"() {
7482
+ "use strict";
7483
+ }
7484
+ });
7485
+
7466
7486
  // src/knowledge/store-schema.ts
7467
7487
  import {
7468
7488
  Schema,
@@ -7751,8 +7771,8 @@ async function findRelevantUrlsBm25(table, query, limit, scopeFilter) {
7751
7771
  }
7752
7772
  async function findDocumentsByUrl(table, url, scopeFilter) {
7753
7773
  const startTime = Date.now();
7754
- const escapedUrl = url.replace(/'/g, "''");
7755
- let filter = `url = '${escapedUrl}'`;
7774
+ const escapedUrl = sqlString(url);
7775
+ let filter = `url = ${escapedUrl}`;
7756
7776
  if (scopeFilter) {
7757
7777
  filter = `(${filter}) AND (${scopeFilter})`;
7758
7778
  }
@@ -7824,6 +7844,7 @@ var init_store_operations = __esm({
7824
7844
  "src/knowledge/store-operations.ts"() {
7825
7845
  "use strict";
7826
7846
  init_logger();
7847
+ init_sql_utils();
7827
7848
  init_metrics();
7828
7849
  }
7829
7850
  });
@@ -7841,6 +7862,7 @@ var init_store = __esm({
7841
7862
  "src/knowledge/store.ts"() {
7842
7863
  "use strict";
7843
7864
  init_lancedb_loader();
7865
+ init_sql_utils();
7844
7866
  init_circuit_breaker();
7845
7867
  init_logger();
7846
7868
  init_metrics();
@@ -7917,10 +7939,10 @@ var init_store = __esm({
7917
7939
  return this.options.embedder;
7918
7940
  }
7919
7941
  getScopeFilter() {
7920
- const ws = this.getWorkspace().replace(/'/g, "''");
7942
+ const ws = sqlString(this.getWorkspace());
7921
7943
  switch (this.options.knowledgeMode) {
7922
7944
  case "project":
7923
- return `workspace = '${ws}'`;
7945
+ return `workspace = ${ws}`;
7924
7946
  case "global":
7925
7947
  return "is_global = true";
7926
7948
  default:
@@ -8465,8 +8487,8 @@ var init_store = __esm({
8465
8487
  const table = await this.getFreshTable();
8466
8488
  const startTime = Date.now();
8467
8489
  try {
8468
- const escapedUrl = url.replace(/'/g, "''");
8469
- await table.delete(`url = '${escapedUrl}' AND (${scopeFilter})`);
8490
+ const escapedUrl = sqlString(url);
8491
+ await table.delete(`url = ${escapedUrl} AND (${scopeFilter})`);
8470
8492
  const duration = Date.now() - startTime;
8471
8493
  metrics.observe("knowledge_store_delete_duration_ms", duration);
8472
8494
  metrics.increment("knowledge_store_delete_total", 1, { operation: "by_url", status: "success" });
@@ -8512,10 +8534,10 @@ var init_store = __esm({
8512
8534
  const table = await this.getFreshTable();
8513
8535
  const startTime = Date.now();
8514
8536
  try {
8515
- const escapedUrl = url.replace(/'/g, "''");
8516
- const escapedType = ingestionType.replace(/'/g, "''");
8537
+ const escapedUrl = sqlString(url);
8538
+ const escapedType = sqlString(ingestionType);
8517
8539
  const ageClause = Number.isFinite(olderThan) ? ` AND timestamp < ${Math.floor(olderThan)}` : "";
8518
- await table.delete(`url = '${escapedUrl}' AND ingestion_type = '${escapedType}' AND (${scopeFilter})${ageClause}`);
8540
+ await table.delete(`url = ${escapedUrl} AND ingestion_type = ${escapedType} AND (${scopeFilter})${ageClause}`);
8519
8541
  const duration = Date.now() - startTime;
8520
8542
  metrics.observe("knowledge_store_delete_duration_ms", duration, { operation: "by_url_and_type" });
8521
8543
  metrics.increment("knowledge_store_delete_total", 1, { operation: "by_url_and_type", status: "success" });
@@ -8555,10 +8577,10 @@ var init_store = __esm({
8555
8577
  while (retryCount <= MAX_RETRIES) {
8556
8578
  const table = await this.getFreshTable();
8557
8579
  try {
8558
- const escapedUrl = url.replace(/'/g, "''");
8559
- const escapedType = ingestionType.replace(/'/g, "''");
8580
+ const escapedUrl = sqlString(url);
8581
+ const escapedType = sqlString(ingestionType);
8560
8582
  await table.update({
8561
- where: `url = '${escapedUrl}' AND ingestion_type = '${escapedType}' AND timestamp = ${Math.floor(generationTs)} AND (${scopeFilter})`,
8583
+ where: `url = ${escapedUrl} AND ingestion_type = ${escapedType} AND timestamp = ${Math.floor(generationTs)} AND (${scopeFilter})`,
8562
8584
  valuesSql: { timestamp: String(Math.floor(newTs)) }
8563
8585
  });
8564
8586
  logger.log(`[store] Refreshed timestamp for unchanged ${ingestionType} chunks of ${url}`);
@@ -8629,8 +8651,8 @@ var init_store = __esm({
8629
8651
  const table = await this.getFreshTable();
8630
8652
  const scopeFilter = this.getScopeFilter();
8631
8653
  const startTime = Date.now();
8632
- const escapedUrl = url.replace(/'/g, "''");
8633
- const whereClause = `url = '${escapedUrl}' AND ingestion_type = 'synthesis-description' AND (${scopeFilter})`;
8654
+ const escapedUrl = sqlString(url);
8655
+ const whereClause = `url = ${escapedUrl} AND ingestion_type = 'synthesis-description' AND (${scopeFilter})`;
8634
8656
  let results = await table.query().where(whereClause).limit(16).toArray();
8635
8657
  if (results.length === 16) {
8636
8658
  results = await table.query().where(whereClause).limit(1024).toArray();
@@ -8883,9 +8905,9 @@ var init_store = __esm({
8883
8905
  try {
8884
8906
  const table = await this.getFreshTable();
8885
8907
  const ws = normalizeWorkspacePath(workspace || this.getWorkspace());
8886
- const escaped = ws.replace(/'/g, "''");
8908
+ const escaped = sqlString(ws);
8887
8909
  const [local, global] = await Promise.all([
8888
- table.countRows(`workspace = '${escaped}'`),
8910
+ table.countRows(`workspace = ${escaped}`),
8889
8911
  table.countRows(`is_global = true`)
8890
8912
  ]);
8891
8913
  const allWorkspaces = await table.query().select(["workspace"]).toArray();
@@ -10288,12 +10310,12 @@ function isTransientSynthesisError(message) {
10288
10310
  m.includes("terminated") || m.includes("other side closed") || m.includes("socket hang up") || m.includes("und_err");
10289
10311
  }
10290
10312
  function splitPromptAtUserTurn(template) {
10291
- const open5 = template.indexOf("<!-- USER_TURN");
10292
- if (open5 < 0) return { system: template, user: null };
10293
- const close = template.indexOf("-->", open5);
10313
+ const open6 = template.indexOf("<!-- USER_TURN");
10314
+ if (open6 < 0) return { system: template, user: null };
10315
+ const close = template.indexOf("-->", open6);
10294
10316
  if (close < 0) return { system: template, user: null };
10295
10317
  return {
10296
- system: template.slice(0, open5).trimEnd(),
10318
+ system: template.slice(0, open6).trimEnd(),
10297
10319
  user: template.slice(close + "-->".length).trimStart()
10298
10320
  };
10299
10321
  }
@@ -11335,24 +11357,26 @@ function isSpentAccountError(error) {
11335
11357
  function isRateLimitError(error) {
11336
11358
  if (isSpentAccountError(error)) return false;
11337
11359
  const msg2 = (error instanceof Error ? error.message : String(error)).toLowerCase();
11338
- return /\b429\b/.test(msg2) || msg2.includes("rate limit") || msg2.includes("rate-limit") || msg2.includes("rate limited") || msg2.includes("too many requests") || msg2.includes("engine_overloaded") || msg2.includes("provider_overloaded");
11360
+ return /\b429\b/.test(msg2) || /\b(?:http|status|code|error|response|returned)\W{0,4}50[0234]\b/i.test(msg2) || /\b50[0234]\b\W{0,4}(?:provider|service|unavailable|bad|gateway|internal|error|timeout)/i.test(msg2) || msg2.includes("service unavailable") || msg2.includes("bad gateway") || msg2.includes("gateway timeout") || msg2.includes("rate limit") || msg2.includes("rate-limit") || msg2.includes("rate limited") || msg2.includes("too many requests") || msg2.includes("retry delay") || msg2.includes("retry-after") || msg2.includes("engine_overloaded") || msg2.includes("provider_overloaded");
11339
11361
  }
11340
11362
  function isCapacityFailureReason(reason) {
11341
11363
  return reason !== void 0 && reason !== "" && isRateLimitError(reason);
11342
11364
  }
11343
11365
  function parseRetryAfterMs(error) {
11344
11366
  const message = error instanceof Error ? error.message : String(error);
11345
- const m = /["']?retry-after["']?\s*[:=]\s*["']?(\d{1,4})/i.exec(message);
11367
+ const m = /["']?retry-after["']?\s*[:=]\s*["']?(\d{1,4})/i.exec(message) || /requested\s+(\d{1,4})\s*s(?:ec(?:onds?)?)?\s+retry\s+delay/i.exec(message) || /retry\s+after\s+(\d{1,4})\s*s/i.exec(message);
11346
11368
  if (!m) return null;
11347
11369
  const seconds = Number(m[1]);
11348
11370
  if (!Number.isFinite(seconds) || seconds <= 0) return null;
11349
- return Math.min(Math.max(seconds, 5), 60) * 1e3;
11371
+ return Math.min(Math.max(seconds, 5), STATED_RETRY_AFTER_MAX_MS / 1e3) * 1e3;
11350
11372
  }
11351
11373
  var RATE_LIMIT_BACKOFF_BASE_MS = 15e3;
11352
11374
  var RATE_LIMIT_BACKOFF_MAX_MS = 6e4;
11375
+ var STATED_RETRY_AFTER_MAX_MS = 18e4;
11376
+ var RATE_LIMIT_TOTAL_WAIT_MAX_MS = 24e4;
11353
11377
  function rateLimitBackoffMs(attempt, retryAfterMs, random = Math.random) {
11354
11378
  if (retryAfterMs !== null && Number.isFinite(retryAfterMs) && retryAfterMs > 0) {
11355
- return clampRateLimitWait(retryAfterMs);
11379
+ return Math.min(Math.max(Math.round(retryAfterMs), 1e3), STATED_RETRY_AFTER_MAX_MS);
11356
11380
  }
11357
11381
  const exponent = Math.max(0, attempt - 2);
11358
11382
  const base = Math.min(RATE_LIMIT_BACKOFF_BASE_MS * Math.pow(2, exponent), RATE_LIMIT_BACKOFF_MAX_MS);
@@ -11618,19 +11642,19 @@ function rewriteCitationMarkers(text, remap, isDangling) {
11618
11642
  }
11619
11643
  function fencedCodeMask(text) {
11620
11644
  const ranges = [];
11621
- let open5 = -1;
11645
+ let open6 = -1;
11622
11646
  let pos = 0;
11623
11647
  for (const line of text.split("\n")) {
11624
11648
  if (/^\s{0,3}(```|~~~)/.test(line)) {
11625
- if (open5 < 0) open5 = pos;
11649
+ if (open6 < 0) open6 = pos;
11626
11650
  else {
11627
- ranges.push([open5, pos + line.length]);
11628
- open5 = -1;
11651
+ ranges.push([open6, pos + line.length]);
11652
+ open6 = -1;
11629
11653
  }
11630
11654
  }
11631
11655
  pos += line.length + 1;
11632
11656
  }
11633
- if (open5 >= 0) ranges.push([open5, text.length]);
11657
+ if (open6 >= 0) ranges.push([open6, text.length]);
11634
11658
  return (offset) => ranges.some(([start, end]) => offset >= start && offset < end);
11635
11659
  }
11636
11660
  function inInlineCodeSpan(text, offset) {
@@ -12293,7 +12317,10 @@ Respond by calling the ${submitPlanTool.name} tool with the plan as its argument
12293
12317
  label: "coordinator-generatePlan",
12294
12318
  signal,
12295
12319
  isTransientError: (err) => isRetriableLlmError(err, signal),
12296
- delayFor: rateLimitDelayFor
12320
+ delayFor: rateLimitDelayFor,
12321
+ // Bound the TOTAL wait for THIS call: a provider that keeps asking for
12322
+ // a long window must not spend the run's whole budget sleeping here.
12323
+ maxTotalDelayMs: RATE_LIMIT_TOTAL_WAIT_MAX_MS
12297
12324
  }
12298
12325
  );
12299
12326
  recordLlmUsage(model, response.usage, { component: "coordinator", complexity, observer });
@@ -12708,7 +12735,10 @@ Respond by calling the ${submitRoutingTool.name} tool with the updated plan as i
12708
12735
  label,
12709
12736
  signal,
12710
12737
  isTransientError: (err) => isRetriableLlmError(err, signal),
12711
- delayFor: rateLimitDelayFor
12738
+ delayFor: rateLimitDelayFor,
12739
+ // Bound the TOTAL wait for THIS call: a provider that keeps asking for
12740
+ // a long window must not spend the run's whole budget sleeping here.
12741
+ maxTotalDelayMs: RATE_LIMIT_TOTAL_WAIT_MAX_MS
12712
12742
  }
12713
12743
  );
12714
12744
  recordLlmUsage(model, response.usage, { component: args.component, complexity, observer });
@@ -18304,8 +18334,8 @@ async function isRegisteredLeaderAliveUncached(container) {
18304
18334
  const info = await stateManager.getBrowserServer();
18305
18335
  if (!info) return false;
18306
18336
  const schedulerService = await getService(ServiceNames.SCHEDULER, void 0, container);
18307
- const cached = schedulerService.getSchedulerInstance();
18308
- if (cached instanceof BrowserClient && cached.targetPort !== info.port) return false;
18337
+ const cached2 = schedulerService.getSchedulerInstance();
18338
+ if (cached2 instanceof BrowserClient && cached2.targetPort !== info.port) return false;
18309
18339
  return await stateManager.isPidAlive(info.pid, info.schedulerId);
18310
18340
  } catch {
18311
18341
  return false;
@@ -18475,6 +18505,246 @@ async function runWorkerSearch(query, config, signal, retries = 1, sessionId, co
18475
18505
  }
18476
18506
  }
18477
18507
 
18508
+ // src/infrastructure/browser/proxy-health.ts
18509
+ import net3 from "node:net";
18510
+
18511
+ // src/infrastructure/browser/proxy-prefs.ts
18512
+ import { existsSync as existsSync12, readFileSync as readFileSync7 } from "node:fs";
18513
+ import { homedir as homedir6 } from "node:os";
18514
+ function proxyConfigPath() {
18515
+ return process.env["PI_RESEARCH_PROXY_JSON"] || `${homedir6()}/.pi/research/proxy.json`;
18516
+ }
18517
+ var cached;
18518
+ var cachedAt = 0;
18519
+ var CACHE_TTL_MS = 1e4;
18520
+ function getSocksProxyEndpoint() {
18521
+ const now = Date.now();
18522
+ if (cached !== void 0 && now - cachedAt < CACHE_TTL_MS) return cached;
18523
+ cachedAt = now;
18524
+ try {
18525
+ const file = proxyConfigPath();
18526
+ if (!existsSync12(file)) {
18527
+ cached = null;
18528
+ return cached;
18529
+ }
18530
+ const cfg = JSON.parse(readFileSync7(file, "utf8"));
18531
+ const host = cfg.host === void 0 ? "127.0.0.1" : typeof cfg.host === "string" ? cfg.host.trim() : "";
18532
+ const port = cfg.port === void 0 ? 1080 : Number.isInteger(cfg.port) ? cfg.port : -1;
18533
+ if (host === "" || port < 1 || port > 65535) {
18534
+ cached = null;
18535
+ return cached;
18536
+ }
18537
+ cached = { host, port };
18538
+ return cached;
18539
+ } catch {
18540
+ cached = null;
18541
+ return cached;
18542
+ }
18543
+ }
18544
+
18545
+ // src/infrastructure/browser/proxy-health.ts
18546
+ var DEFAULT_TIMEOUT_MS = 5e3;
18547
+ var DEFAULT_DATA_TIMEOUT_MS = 8e3;
18548
+ var DEFAULT_TARGET_HOST = "lite.duckduckgo.com";
18549
+ var DEFAULT_TARGET_PORT = 80;
18550
+ var NEUTRAL_TARGET_HOST = "example.com";
18551
+ var NEUTRAL_TARGET_PORT = 80;
18552
+ function fail(code, reason, endpoint, startedAt) {
18553
+ return { healthy: false, code, reason, endpoint, latencyMs: Date.now() - startedAt };
18554
+ }
18555
+ function probeSocksProxyForwarding(endpoint = getSocksProxyEndpoint(), options = {}) {
18556
+ const startedAt = Date.now();
18557
+ if (!endpoint) {
18558
+ return Promise.resolve({
18559
+ healthy: true,
18560
+ code: "not-configured",
18561
+ reason: "no SOCKS proxy configured (browser connects directly)",
18562
+ endpoint: null,
18563
+ latencyMs: 0
18564
+ });
18565
+ }
18566
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
18567
+ const dataTimeoutMs = options.dataTimeoutMs ?? DEFAULT_DATA_TIMEOUT_MS;
18568
+ const targetHost = options.targetHost ?? DEFAULT_TARGET_HOST;
18569
+ const targetPort = options.targetPort ?? DEFAULT_TARGET_PORT;
18570
+ const where = `${endpoint.host}:${endpoint.port}`;
18571
+ return new Promise((resolve9) => {
18572
+ const socket = net3.connect({ host: endpoint.host, port: endpoint.port });
18573
+ let stage = "greet";
18574
+ let settled = false;
18575
+ let buffer = Buffer.alloc(0);
18576
+ let connectTimer;
18577
+ let dataTimer;
18578
+ const onAbort = () => {
18579
+ finish(fail("aborted", "proxy probe cancelled by the caller", endpoint, startedAt));
18580
+ };
18581
+ const finish = (result) => {
18582
+ if (settled) return;
18583
+ settled = true;
18584
+ clearTimeout(connectTimer);
18585
+ clearTimeout(dataTimer);
18586
+ options.signal?.removeEventListener("abort", onAbort);
18587
+ socket.destroy();
18588
+ resolve9(result);
18589
+ };
18590
+ if (options.signal?.aborted) {
18591
+ onAbort();
18592
+ return;
18593
+ }
18594
+ options.signal?.addEventListener("abort", onAbort, { once: true });
18595
+ connectTimer = setTimeout(() => {
18596
+ finish(fail(
18597
+ stage === "greet" ? "unreachable" : "no-data",
18598
+ stage === "greet" ? `proxy at ${where} did not accept a TCP connection within ${timeoutMs}ms` : `proxy at ${where} accepted the connection but did not answer within ${timeoutMs}ms`,
18599
+ endpoint,
18600
+ startedAt
18601
+ ));
18602
+ }, timeoutMs);
18603
+ connectTimer.unref?.();
18604
+ const armDataTimer = () => {
18605
+ dataTimer = setTimeout(() => {
18606
+ finish(fail(
18607
+ "no-data",
18608
+ `proxy at ${where} completed the SOCKS handshake to ${targetHost}:${targetPort} but returned no data within ${dataTimeoutMs}ms (the tunnel is not forwarding answers \u2014 check that the proxy process is running the current script and restart it)`,
18609
+ endpoint,
18610
+ startedAt
18611
+ ));
18612
+ }, dataTimeoutMs);
18613
+ dataTimer.unref?.();
18614
+ };
18615
+ socket.on("connect", () => {
18616
+ socket.write(Buffer.from([5, 1, 0]));
18617
+ });
18618
+ socket.on("data", (chunk) => {
18619
+ if (settled) return;
18620
+ buffer = Buffer.concat([buffer, chunk]);
18621
+ if (stage === "greet") {
18622
+ if (buffer.length < 2) return;
18623
+ if (buffer[0] !== 5 || buffer[1] !== 0) {
18624
+ finish(fail(
18625
+ "protocol-error",
18626
+ `proxy at ${where} answered the SOCKS greeting with [${[...buffer.subarray(0, 2)]}] instead of [5,0]`,
18627
+ endpoint,
18628
+ startedAt
18629
+ ));
18630
+ return;
18631
+ }
18632
+ buffer = buffer.subarray(2);
18633
+ const hostBytes = Buffer.from(targetHost, "utf8");
18634
+ socket.write(Buffer.concat([
18635
+ Buffer.from([5, 1, 0, 3, hostBytes.length]),
18636
+ hostBytes,
18637
+ Buffer.from([targetPort >> 8 & 255, targetPort & 255])
18638
+ ]));
18639
+ stage = "connect";
18640
+ return;
18641
+ }
18642
+ if (stage === "connect") {
18643
+ if (buffer.length < 4) return;
18644
+ if (buffer[0] !== 5) {
18645
+ finish(fail("protocol-error", `proxy at ${where} answered the SOCKS request malformed`, endpoint, startedAt));
18646
+ return;
18647
+ }
18648
+ const reply = buffer[1];
18649
+ if (reply !== 0) {
18650
+ const meaning = reply === 2 ? "refused by ruleset" : reply === 3 ? "network unreachable" : reply === 4 ? "host unreachable" : reply === 5 ? "connection refused by the target" : `SOCKS error ${reply}`;
18651
+ finish(fail(
18652
+ "connect-rejected",
18653
+ `proxy at ${where} refused CONNECT to ${targetHost}:${targetPort} (${meaning})`,
18654
+ endpoint,
18655
+ startedAt
18656
+ ));
18657
+ return;
18658
+ }
18659
+ const atyp = buffer[3];
18660
+ let addrLen;
18661
+ if (atyp === 1) {
18662
+ addrLen = 4;
18663
+ } else if (atyp === 4) {
18664
+ addrLen = 16;
18665
+ } else if (atyp === 3) {
18666
+ if (buffer.length < 5) return;
18667
+ addrLen = 1 + (buffer[4] ?? 0);
18668
+ } else {
18669
+ finish(fail("protocol-error", `proxy at ${where} answered CONNECT with unknown address type ${atyp}`, endpoint, startedAt));
18670
+ return;
18671
+ }
18672
+ const replyLen = 4 + addrLen + 2;
18673
+ if (buffer.length < replyLen) return;
18674
+ buffer = buffer.subarray(replyLen);
18675
+ clearTimeout(connectTimer);
18676
+ socket.write(
18677
+ `GET / HTTP/1.0\r
18678
+ Host: ${targetHost}\r
18679
+ Connection: close\r
18680
+ \r
18681
+ `
18682
+ );
18683
+ stage = "data";
18684
+ armDataTimer();
18685
+ if (buffer.length > 0) {
18686
+ finish({
18687
+ healthy: true,
18688
+ code: "ok",
18689
+ reason: `proxy at ${where} forwards traffic (first byte in ${Date.now() - startedAt}ms)`,
18690
+ endpoint,
18691
+ latencyMs: Date.now() - startedAt
18692
+ });
18693
+ }
18694
+ return;
18695
+ }
18696
+ finish({
18697
+ healthy: true,
18698
+ code: "ok",
18699
+ reason: `proxy at ${where} forwards traffic (first byte in ${Date.now() - startedAt}ms)`,
18700
+ endpoint,
18701
+ latencyMs: Date.now() - startedAt
18702
+ });
18703
+ });
18704
+ socket.on("error", (err) => {
18705
+ const detail = err.code === "ECONNREFUSED" ? "nothing is listening there \u2014 is the proxy service running?" : err.message;
18706
+ finish(fail("unreachable", `proxy at ${where} is unusable: ${detail}`, endpoint, startedAt));
18707
+ });
18708
+ socket.on("close", () => {
18709
+ finish(fail(
18710
+ "no-data",
18711
+ `proxy at ${where} closed the tunnel before returning data`,
18712
+ endpoint,
18713
+ startedAt
18714
+ ));
18715
+ });
18716
+ });
18717
+ }
18718
+ async function describeProxyIfBroken(signal, options = {}) {
18719
+ const endpoint = getSocksProxyEndpoint();
18720
+ if (!endpoint) return null;
18721
+ const opts = {
18722
+ timeoutMs: options.timeoutMs ?? 3e3,
18723
+ dataTimeoutMs: options.dataTimeoutMs ?? 3e3,
18724
+ signal
18725
+ };
18726
+ let last = await probeSocksProxyForwarding(endpoint, opts);
18727
+ if (last.code === "aborted") return null;
18728
+ if (!last.healthy) {
18729
+ last = await probeSocksProxyForwarding(endpoint, {
18730
+ ...opts,
18731
+ dataTimeoutMs: options.dataTimeoutMs ?? 4e3
18732
+ });
18733
+ if (last.code === "aborted") return null;
18734
+ }
18735
+ if (last.healthy) return null;
18736
+ const neutral = await probeSocksProxyForwarding(endpoint, {
18737
+ ...opts,
18738
+ targetHost: NEUTRAL_TARGET_HOST,
18739
+ targetPort: NEUTRAL_TARGET_PORT
18740
+ });
18741
+ if (neutral.code === "aborted") return null;
18742
+ if (neutral.healthy) {
18743
+ return `SOCKS proxy check: the proxy forwards traffic to example.com, but DuckDuckGo is unreachable through it (${last.reason}). The tunnel works; the pinned DuckDuckGo front doors are not answering. Update DDG_PIN_IPS in the proxy service or remove ~/.pi/research/proxy.json.`;
18744
+ }
18745
+ return `SOCKS proxy check: ${last.reason}. The proxy did not forward traffic to example.com either, so the tunnel itself is broken.`;
18746
+ }
18747
+
18478
18748
  // src/web-research/browser-search.ts
18479
18749
  init_logger();
18480
18750
  init_safe_unref();
@@ -18618,8 +18888,9 @@ async function performSearch(queries, config, signal, onProgress, container = ge
18618
18888
  `Search completely failed: ${reason}, all with a missing native module. This is an incomplete install, not a network problem: the browser launcher's native dependency (impit) ships a prebuilt binding per platform as a separate package, and npm sometimes drops it (npm/cli#4828). Reinstall this package (npm install, or pi install again) to restore it.` + (sampleWorkerError ? ` Last worker error: ${sampleWorkerError}` : "")
18619
18889
  );
18620
18890
  }
18891
+ const proxyDiagnosis = await describeProxyIfBroken(signal);
18621
18892
  throw new Error(
18622
- `Search completely failed: ${reason}. Browser workers may be unavailable, DuckDuckGo is unreachable, or the system is under extreme load.` + (sampleWorkerError ? ` Last worker error: ${sampleWorkerError}` : "")
18893
+ `Search completely failed: ${reason}. ` + (proxyDiagnosis ? `${proxyDiagnosis} Every browser request is routed through the configured proxy, so no search can succeed until it forwards DuckDuckGo traffic or ~/.pi/research/proxy.json is removed.` : `Browser workers may be unavailable, DuckDuckGo is unreachable, or the system is under extreme load.`) + (sampleWorkerError ? ` Last worker error: ${sampleWorkerError}` : "")
18623
18894
  );
18624
18895
  }
18625
18896
  const totalDuration = Date.now() - startTime;
@@ -18824,6 +19095,35 @@ function registerHealthChecks(registry, container = getServiceContainer()) {
18824
19095
  return { healthy: false, error: `Browser healthcheck failed: ${e instanceof Error ? e.message : String(e)}` };
18825
19096
  }
18826
19097
  }, { timeoutMs: Math.max(healthTimeoutMs, 15e4, getHealthCheckBudgetMs(config)), critical: true });
19098
+ registry.register("SocksProxy", async () => {
19099
+ const endpoint = getSocksProxyEndpoint();
19100
+ if (!endpoint) {
19101
+ return { healthy: true, diagnostic: { status: "not configured (browser connects directly)" } };
19102
+ }
19103
+ const probe = await probeSocksProxyForwarding(endpoint, { timeoutMs: 4e3, dataTimeoutMs: 5e3 });
19104
+ if (probe.healthy) {
19105
+ return {
19106
+ healthy: true,
19107
+ diagnostic: {
19108
+ status: `forwarding via ${endpoint.host}:${endpoint.port}`,
19109
+ firstByteMs: probe.latencyMs
19110
+ }
19111
+ };
19112
+ }
19113
+ const neutral = await probeSocksProxyForwarding(endpoint, {
19114
+ timeoutMs: 4e3,
19115
+ dataTimeoutMs: 5e3,
19116
+ targetHost: NEUTRAL_TARGET_HOST,
19117
+ targetPort: NEUTRAL_TARGET_PORT
19118
+ });
19119
+ if (neutral.healthy) {
19120
+ return {
19121
+ healthy: false,
19122
+ error: `the proxy forwards traffic to ${NEUTRAL_TARGET_HOST}, but DuckDuckGo is unreachable through it (${probe.reason}). The tunnel works; the pinned front doors do not. Update DDG_PIN_IPS and restart the proxy, or remove ~/.pi/research/proxy.json.`
19123
+ };
19124
+ }
19125
+ return { healthy: false, error: probe.reason };
19126
+ }, { timeoutMs: 25e3, critical: true });
18827
19127
  registry.register("KnowledgeStore", async (options) => {
18828
19128
  const existing = container.tryGet(ServiceNames.KNOWLEDGE_STORE);
18829
19129
  const alreadyInitialized = existing?.lifecycle === "initialized" /* INITIALIZED */;
@@ -18952,7 +19252,8 @@ function isBusyPoolHealthFailure(health) {
18952
19252
  const capabilityOk = !capability || capability.healthy !== false;
18953
19253
  const unhealthy = components.filter((c) => c.healthy === false);
18954
19254
  const isTimeout = (c) => /tim(e|ed)\s*out|timeout/i.test(String(c.error || ""));
18955
- return capabilityOk && unhealthy.length > 0 && unhealthy.every(isTimeout);
19255
+ const proxyBroken = unhealthy.some((c) => c.component === "SocksProxy");
19256
+ return capabilityOk && !proxyBroken && unhealthy.length > 0 && unhealthy.every(isTimeout);
18956
19257
  }
18957
19258
  async function runHealthCheck(options) {
18958
19259
  const container = tryGetServiceContainerFromCtx(options?.ctx);
@@ -18981,11 +19282,11 @@ import { createAgentSession, SessionManager, SettingsManager as SettingsManagerC
18981
19282
 
18982
19283
  // src/tools/read-guard.ts
18983
19284
  import { constants as constants2 } from "node:fs";
18984
- import { access as access3, readFile as readFile7, realpath as realpath2 } from "node:fs/promises";
18985
- import { homedir as homedir6 } from "node:os";
19285
+ import { access as access3, open as open5, readFile as readFile7, realpath as realpath2 } from "node:fs/promises";
19286
+ import { homedir as homedir7 } from "node:os";
18986
19287
  import { basename as basename5, dirname as dirname13, relative, isAbsolute as isAbsolute3, parse, sep as sep2 } from "node:path";
18987
- var DENIED_SEGMENTS = /* @__PURE__ */ new Set([".ssh", ".aws", ".gnupg", ".git", ".kube", ".docker", ".azure", ".gcloud"]);
18988
- var DENIED_BASENAME = /^(\.env(\..*)?|\.envrc|\.netrc|_netrc|\.npmrc|\.pypirc|\.git-credentials|\.pgpass|\.my\.cnf|\.htpasswd|\.dockercfg|\.vault-token|\.bash_history|\.zsh_history|kubeconfig|terraform\.tfstate(\..*)?|(credentials|secrets?)(\.(json|ya?ml|toml|env|ini|txt|xml))?|id_(rsa|dsa|ecdsa|ed25519)(\..*)?|.*\.(pem|p12|pfx|jks|keystore|kdbx|asc|gpg|tfvars)|.*[-_.](secret|secrets|credentials)\.(json|ya?ml|toml|env)|service-account.*\.json)$/;
19288
+ var DENIED_SEGMENTS = /* @__PURE__ */ new Set([".ssh", ".aws", ".gnupg", ".git", ".kube", ".docker", ".azure", ".gcloud", ".terraform"]);
19289
+ var DENIED_BASENAME = /^(\.env(\..*)?|\.envrc|\.netrc|_netrc|\.npmrc|\.pypirc|\.git-credentials|\.pgpass|\.my\.cnf|\.htpasswd|\.dockercfg|\.dockerconfigjson|\.vault-token|\.bash_history|\.zsh_history|kubeconfig|terraform\.tfstate(\..*)?|(credentials|secrets?)(\.(json|ya?ml|toml|env|ini|txt|xml))?|id_(rsa|dsa|ecdsa|ed25519)([._-].*)?|.*\.(pem|p12|pfx|jks|keystore|kdbx|asc|gpg|tfvars|key)|.*[-_.](secret|secrets|credentials)\.(json|ya?ml|toml|env)|service-account.*\.json)$/;
18989
19290
  var ALLOWED_ENV_TEMPLATE = /^\.env\.(example|sample|template|dist)$/;
18990
19291
  function normalizeName(name) {
18991
19292
  return name.toLowerCase().replace(/:.*$/, "").replace(/[. ]+$/, "");
@@ -19011,7 +19312,7 @@ function isWithin(root, target) {
19011
19312
  }
19012
19313
  async function assertReadAllowed(cwd, absolutePath) {
19013
19314
  const root = await resolveReal(cwd);
19014
- const home = await resolveReal(homedir6());
19315
+ const home = await resolveReal(homedir7());
19015
19316
  if (root === parse(root).root || isWithin(root, home)) {
19016
19317
  throw new ReadDeniedError("the working directory is a home or filesystem root, not a project directory");
19017
19318
  }
@@ -19036,7 +19337,16 @@ function createGuardedReadOperations(cwd) {
19036
19337
  },
19037
19338
  readFile: async (p) => {
19038
19339
  await assertReadAllowed(cwd, p);
19039
- return readFile7(p);
19340
+ const handle = await open5(p, constants2.O_RDONLY | constants2.O_NOFOLLOW);
19341
+ try {
19342
+ const stat6 = await handle.stat();
19343
+ if (!stat6.isFile()) {
19344
+ throw new ReadDeniedError("path is not a regular file");
19345
+ }
19346
+ return await readFile7(handle);
19347
+ } finally {
19348
+ await handle.close();
19349
+ }
19040
19350
  }
19041
19351
  };
19042
19352
  }
@@ -19285,7 +19595,7 @@ init_metrics();
19285
19595
  init_logger();
19286
19596
  import * as dns from "node:dns/promises";
19287
19597
  import * as dnsCb from "node:dns";
19288
- import * as net3 from "node:net";
19598
+ import * as net4 from "node:net";
19289
19599
  import crypto9 from "node:crypto";
19290
19600
  import { NodeHtmlMarkdown } from "node-html-markdown";
19291
19601
  function getRandomUserAgent() {
@@ -19318,7 +19628,7 @@ function validateUrlForSSRFSync(url) {
19318
19628
  throw new Error("Only HTTP/HTTPS protocols are allowed");
19319
19629
  }
19320
19630
  if (process.env["PI_RESEARCH_ALLOW_LOOPBACK_SCRAPE"] === "true") {
19321
- const isLoopback = hostname === "localhost" || hostname.endsWith(".localhost") || /^127\./.test(hostname) || hostname === "::1" || net3.isIPv6(hostname) && isPrivateIpv6(hostname) && isMappedLoopback(hostname);
19631
+ const isLoopback = hostname === "localhost" || hostname.endsWith(".localhost") || /^127\./.test(hostname) || hostname === "::1" || net4.isIPv6(hostname) && isPrivateIpv6(hostname) && isMappedLoopback(hostname);
19322
19632
  if (isLoopback) return true;
19323
19633
  }
19324
19634
  if (hostname === "localhost" || hostname.endsWith(".localhost")) {
@@ -19331,7 +19641,7 @@ function validateUrlForSSRFSync(url) {
19331
19641
  throw new Error("Access to internal networks is not allowed");
19332
19642
  }
19333
19643
  }
19334
- const literalKind = net3.isIP(hostname);
19644
+ const literalKind = net4.isIP(hostname);
19335
19645
  if (literalKind === 4 && isPrivateIp(hostname)) {
19336
19646
  metrics.increment("scrape_ssrf_blocks_total", 1, { block_type: "ip_literal_v4" });
19337
19647
  throw new Error("Access to private/reserved IPv4 address is not allowed");
@@ -19417,8 +19727,8 @@ async function disposeSsrfSafeFetcher() {
19417
19727
  const pending = cachedSsrfFetcher;
19418
19728
  cachedSsrfFetcher = void 0;
19419
19729
  if (pending === void 0) return;
19420
- const cached = await pending.catch(() => null);
19421
- const closable = cached?.dispatcher;
19730
+ const cached2 = await pending.catch(() => null);
19731
+ const closable = cached2?.dispatcher;
19422
19732
  if (!closable?.close) return;
19423
19733
  try {
19424
19734
  await closable.close();
@@ -19633,7 +19943,7 @@ init_service_registry();
19633
19943
  init_logger();
19634
19944
  init_metrics();
19635
19945
  init_error_tracker();
19636
- import { existsSync as existsSync12 } from "node:fs";
19946
+ import { existsSync as existsSync13 } from "node:fs";
19637
19947
  import { dirname as dirname14, join as join21 } from "node:path";
19638
19948
  import { fileURLToPath as fileURLToPath4 } from "node:url";
19639
19949
  import { Worker } from "node:worker_threads";
@@ -19706,7 +20016,7 @@ var pendingRequests = /* @__PURE__ */ new Map();
19706
20016
  var warnedWorkerUnavailable = false;
19707
20017
  function resolveWorkerPath() {
19708
20018
  const candidate = join21(MODULE_DIR, WORKER_FILENAME);
19709
- return existsSync12(candidate) ? candidate : null;
20019
+ return existsSync13(candidate) ? candidate : null;
19710
20020
  }
19711
20021
  function pdfWorkerEnabled() {
19712
20022
  if (process.env["PI_RESEARCH_PDF_WORKER"] === "off") return false;
@@ -24754,6 +25064,7 @@ ${effectiveInitialLinks.map((l) => `- ${l}`).join("\n")}`;
24754
25064
  const deliveredSteeringIds = /* @__PURE__ */ new Set();
24755
25065
  const researcherSystemPrompt = injectCurrentDate(researcherPromptTemplate, "researcher").replace("{{extra_tool_guidelines}}", "").replaceAll("{{max_scrape_urls}}", String(config.MAX_SCRAPE_URLS)).replace("{{digest_section}}", () => RESEARCHER_DIGEST_SECTION).trim();
24756
25066
  let inFlightBackoffMs = null;
25067
+ let capacityWaitSpentMs = 0;
24757
25068
  for (let attempt = 1; attempt <= maxAttempts; attempt++) {
24758
25069
  if (signal?.aborted) throw new Error("Aborted");
24759
25070
  if (stopRequested()) {
@@ -25015,6 +25326,20 @@ ${responseText}`);
25015
25326
  metrics.increment("researcher_rate_limit_backoff_total", 1, { mode: "deep", complexity: String(complexity) });
25016
25327
  logger.warn(`[ResearcherExecutor] Researcher ${id} hit a provider rate limit; backing off ${inFlightBackoffMs}ms before attempt ${attempt + 1}`);
25017
25328
  }
25329
+ if (inFlightBackoffMs !== null) {
25330
+ const remainingBudgetMs = RATE_LIMIT_TOTAL_WAIT_MAX_MS - capacityWaitSpentMs;
25331
+ if (inFlightBackoffMs > remainingBudgetMs) {
25332
+ const windowSeconds = Math.ceil(inFlightBackoffMs / 1e3);
25333
+ const retryAt = new Date(Date.now() + inFlightBackoffMs).toISOString().slice(11, 19);
25334
+ lastError = new Error(
25335
+ `Provider capacity: it asked for a ${windowSeconds}s cool-off, but this researcher has only ${Math.max(0, Math.round(remainingBudgetMs / 1e3))}s of its ${Math.round(RATE_LIMIT_TOTAL_WAIT_MAX_MS / 1e3)}s capacity-wait budget left. Rerun after ${retryAt}Z. Cause: ${errMsg}`
25336
+ );
25337
+ logger.error(`[ResearcherExecutor] Researcher ${id} stopping instead of waiting ${inFlightBackoffMs}ms (capacity budget exhausted); rerun after ${retryAt}Z`);
25338
+ metrics.increment("researcher_capacity_budget_exhausted_total", 1, { mode: "deep", complexity: String(complexity) });
25339
+ break;
25340
+ }
25341
+ capacityWaitSpentMs += inFlightBackoffMs;
25342
+ }
25018
25343
  }
25019
25344
  if (attempt < maxAttempts) {
25020
25345
  logger.warn(`[ResearcherExecutor] Researcher ${id} attempt ${attempt} failed: ${errMsg}; will retry`);
@@ -25681,6 +26006,13 @@ var DeepResearchOrchestrator = class {
25681
26006
  const orchestrationService = await this.getOrchestrationService();
25682
26007
  const planningService = await this.getPlanningService();
25683
26008
  await orchestrationService.cleanupResearchServices(void 0, researchId, ctx, this.config);
26009
+ const proxyDiagnosis = await describeProxyIfBroken(signal);
26010
+ if (signal?.aborted) return "";
26011
+ if (proxyDiagnosis) {
26012
+ throw new Error(
26013
+ `Research cannot start: ${proxyDiagnosis} Repair or remove ~/.pi/research/proxy.json (docs/TROUBLESHOOTING.md), then rerun.`
26014
+ );
26015
+ }
25684
26016
  logger.log(`[DeepOrchestrator] Starting multi-round research (complexity ${complexity}) for: "${query}" (Run: ${researchId})`);
25685
26017
  metrics.increment("research_sessions_total", 1, { mode: "deep", complexity: String(complexity) });
25686
26018
  observer?.onStart?.(query, complexity);
@@ -27783,7 +28115,7 @@ init_url_utils();
27783
28115
  init_logger();
27784
28116
  init_constants();
27785
28117
  import { promises as fs16 } from "node:fs";
27786
- import { homedir as homedir7, tmpdir as tmpdir4, platform as platform4 } from "node:os";
28118
+ import { homedir as homedir8, tmpdir as tmpdir4, platform as platform4 } from "node:os";
27787
28119
  import { join as join22, resolve as resolve5, normalize, sep as sep3 } from "node:path";
27788
28120
  import { randomBytes as randomBytes6 } from "node:crypto";
27789
28121
  var PREFERRED_SUBDIRS = [
@@ -27826,7 +28158,7 @@ var WIN_SYSTEM_PREFIXES_LC = [
27826
28158
  ];
27827
28159
  function isSafeToWriteDirectly(dir) {
27828
28160
  const normalized = normalize(resolve5(dir));
27829
- const home = normalize(resolve5(homedir7()));
28161
+ const home = normalize(resolve5(homedir8()));
27830
28162
  if (normalized === home) return false;
27831
28163
  if (platform4() === "win32") {
27832
28164
  if (/^[a-zA-Z]:\\?$/.test(normalized)) return false;