@lincoln504/pi-research 1.7.23 → 1.7.25

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 (99) hide show
  1. package/agent-skill/pi-research/SKILL.md +1 -1
  2. package/dist/cli.mjs +621 -205
  3. package/dist/prompts/research-tool-usage.md +4 -5
  4. package/dist/prompts/researcher.md +6 -36
  5. package/dist/prompts/system-coordinator.md +1 -1
  6. package/dist/prompts/system-lead-synthesizer.md +5 -5
  7. package/dist/thread-worker.mjs +22 -9
  8. package/docs/CHANGELOG.md +159 -0
  9. package/docs/CONFIGURATION.md +4 -3
  10. package/docs/TROUBLESHOOTING.md +92 -0
  11. package/package.json +9 -9
  12. package/scripts/ddg-socks-proxy.mjs +105 -15
  13. package/src/cli.ts +32 -14
  14. package/src/config.ts +20 -7
  15. package/src/core/interfaces/health-check-interfaces.ts +23 -2
  16. package/src/core/interfaces/knowledge-interfaces.ts +7 -4
  17. package/src/core/interfaces/observer-interfaces.ts +1 -1
  18. package/src/core/interfaces/orchestration-interfaces.ts +17 -12
  19. package/src/core/interfaces/planning-interfaces.ts +5 -5
  20. package/src/core/interfaces/process-interfaces.ts +2 -2
  21. package/src/core/interfaces/state-manager-interfaces.ts +6 -5
  22. package/src/core/llm/agentic-repair.ts +6 -6
  23. package/src/core/llm/llm-utils.ts +7 -4
  24. package/src/core/llm/model-registry-factory.ts +11 -11
  25. package/src/core/llm/research-model-resolver.ts +11 -11
  26. package/src/core/pi-version.ts +10 -1
  27. package/src/core/planning-service.ts +40 -14
  28. package/src/core/planning-utils.ts +33 -7
  29. package/src/core/service-initialization.ts +1 -1
  30. package/src/core/service-registry.ts +18 -11
  31. package/src/healthcheck/index.ts +67 -5
  32. package/src/healthcheck/registry.ts +5 -18
  33. package/src/index.ts +12 -16
  34. package/src/infrastructure/browser/browser-client.ts +4 -4
  35. package/src/infrastructure/browser/browser-error-utils.ts +6 -1
  36. package/src/infrastructure/browser/browser-lifecycle.ts +8 -3
  37. package/src/infrastructure/browser/browser-server.ts +3 -3
  38. package/src/infrastructure/browser/browser-task-scheduler.ts +13 -9
  39. package/src/infrastructure/browser/priority-task-queue.ts +13 -10
  40. package/src/infrastructure/browser/proxy-health.ts +342 -0
  41. package/src/infrastructure/browser/thread-worker-browser.ts +14 -11
  42. package/src/infrastructure/browser/thread-worker-lifecycle.ts +21 -15
  43. package/src/infrastructure/browser/thread-worker-messaging.ts +39 -31
  44. package/src/infrastructure/browser/thread-worker-types.ts +3 -1
  45. package/src/infrastructure/browser/thread-worker.mjs +22 -9
  46. package/src/infrastructure/browser/thread-worker.ts +3 -2
  47. package/src/infrastructure/browser/worker-pool-manager.ts +5 -5
  48. package/src/infrastructure/gpu-resource-service.ts +16 -9
  49. package/src/infrastructure/knowledge-store-service.ts +13 -10
  50. package/src/infrastructure/scheduler-factory-service.ts +4 -3
  51. package/src/infrastructure/service-initialization.ts +1 -1
  52. package/src/infrastructure/state/state-manager-service.ts +2 -2
  53. package/src/infrastructure/state/state-manager.ts +3 -3
  54. package/src/infrastructure/state/state-validator.ts +9 -3
  55. package/src/infrastructure/types/state-types.ts +12 -91
  56. package/src/knowledge/embedder-init.ts +8 -8
  57. package/src/knowledge/embedder-utils.ts +7 -3
  58. package/src/knowledge/embedder.ts +14 -10
  59. package/src/knowledge/onnx-env.ts +2 -2
  60. package/src/knowledge/store.ts +12 -11
  61. package/src/logger.ts +1 -1
  62. package/src/orchestration/deep-research-orchestrator.ts +36 -7
  63. package/src/orchestration/headless-observer.ts +1 -1
  64. package/src/orchestration/orchestration-types.ts +2 -2
  65. package/src/orchestration/quick-research-orchestrator.ts +4 -4
  66. package/src/orchestration/research-orchestration-service.ts +13 -13
  67. package/src/orchestration/research-synthesis-service.ts +15 -8
  68. package/src/orchestration/researcher-executor.ts +51 -8
  69. package/src/orchestration/researcher.ts +19 -7
  70. package/src/orchestration/service-initialization.ts +1 -1
  71. package/src/prompts/research-tool-usage.md +4 -5
  72. package/src/prompts/researcher.md +6 -36
  73. package/src/prompts/system-coordinator.md +1 -1
  74. package/src/prompts/system-lead-synthesizer.md +5 -5
  75. package/src/research-config.ts +11 -9
  76. package/src/sdk.ts +10 -10
  77. package/src/skill-install/skill-installer.ts +19 -10
  78. package/src/tools/grep.ts +57 -5
  79. package/src/tools/index.ts +0 -3
  80. package/src/tools/read-guard.ts +12 -0
  81. package/src/tools/research-knowledge-search.ts +15 -13
  82. package/src/tools/research-tool-definition.ts +15 -10
  83. package/src/tools/scrape.ts +3 -2
  84. package/src/tui/research-panel.ts +1 -1
  85. package/src/types/extension-context.ts +2 -2
  86. package/src/types/llm.ts +8 -7
  87. package/src/types/research-panel-types.ts +3 -1
  88. package/src/types/state-types.ts +98 -0
  89. package/src/utils/coverage-digest.ts +27 -6
  90. package/src/utils/llm-usage.ts +3 -3
  91. package/src/utils/provider-errors.ts +61 -9
  92. package/src/utils/safe-unref.ts +2 -2
  93. package/src/utils/shutdown-manager.ts +6 -6
  94. package/src/utils/stdio-capture.ts +25 -10
  95. package/src/utils/text-utils.ts +35 -0
  96. package/src/web-research/browser-search.ts +13 -1
  97. package/src/web-research/retry-utils.ts +29 -1
  98. package/src/web-research/scraper-utils.ts +9 -3
  99. package/src/web-research/web-scraper.ts +25 -10
package/dist/cli.mjs CHANGED
@@ -1113,8 +1113,9 @@ function tryGetService(name, container = globalServiceContainer) {
1113
1113
  return container.tryGet(name);
1114
1114
  }
1115
1115
  function tryGetServiceContainerFromCtx(ctx) {
1116
- if (ctx?.container && typeof ctx.container.get === "function" && typeof ctx.container.register === "function") {
1117
- return ctx.container;
1116
+ const container = ctx?.container;
1117
+ if (container && typeof container.get === "function" && typeof container.register === "function") {
1118
+ return container;
1118
1119
  }
1119
1120
  return globalServiceContainer;
1120
1121
  }
@@ -1339,7 +1340,8 @@ var init_service_registry = __esm({
1339
1340
  });
1340
1341
  }
1341
1342
  if (registration.instance && registration.instance.dispose) {
1342
- await registration.instance.dispose().catch((err) => {
1343
+ const disposal = Promise.resolve(registration.instance.dispose());
1344
+ await disposal.catch((err) => {
1343
1345
  logger.warn(`[ServiceContainer] Error disposing service '${name}':`, err);
1344
1346
  });
1345
1347
  }
@@ -1372,7 +1374,8 @@ var init_service_registry = __esm({
1372
1374
  });
1373
1375
  }
1374
1376
  if (registration.instance && registration.instance.dispose) {
1375
- await registration.instance.dispose().catch((err) => {
1377
+ const disposal = Promise.resolve(registration.instance.dispose());
1378
+ await disposal.catch((err) => {
1376
1379
  logger.warn(`[ServiceContainer] Error disposing old service '${name}':`, err);
1377
1380
  });
1378
1381
  }
@@ -1935,10 +1938,11 @@ function extractUsage(model, rawUsage) {
1935
1938
  }
1936
1939
  const parsed = parseTokenUsage(rawUsage);
1937
1940
  const tokens = calculateTotalTokens(parsed);
1938
- let cost = parsed.cost?.total ?? rawUsage.cost?.total ?? 0;
1941
+ const usage = rawUsage;
1942
+ let cost = parsed.cost?.total ?? usage.cost?.total ?? 0;
1939
1943
  if (cost === 0 && tokens > 0) {
1940
1944
  try {
1941
- const calculatedCost = calculateCost(model, rawUsage);
1945
+ const calculatedCost = calculateCost(model, usage);
1942
1946
  cost = calculatedCost.total;
1943
1947
  } catch {
1944
1948
  }
@@ -2127,6 +2131,21 @@ var init_url_utils = __esm({
2127
2131
 
2128
2132
  // src/utils/text-utils.ts
2129
2133
  import * as path4 from "node:path";
2134
+ function extractToolResults(session) {
2135
+ const parts = [];
2136
+ for (const msg2 of session.messages) {
2137
+ if (msg2.role !== "toolResult") continue;
2138
+ const tr = msg2;
2139
+ if (tr.isError) continue;
2140
+ let text = (tr.content ?? []).map((c) => c && c.type === "text" ? String(c.text ?? "") : "").join("");
2141
+ text = text.replace(/\n-{3,}\n## Session URL Pool\n[\s\S]*$/, "").trimEnd();
2142
+ if (text.trim()) {
2143
+ parts.push(`### ${tr.toolName ?? "tool"}
2144
+ ${text}`);
2145
+ }
2146
+ }
2147
+ return parts.join("\n\n");
2148
+ }
2130
2149
  function extractText(message) {
2131
2150
  if (!message || typeof message !== "object") {
2132
2151
  return "";
@@ -2795,6 +2814,7 @@ function saveConfig(config, scope = "local", cwd = process.cwd(), changedKeys) {
2795
2814
  PI_RESEARCH_MAX_RETRIES: String(config.RESEARCHER_MAX_RETRIES),
2796
2815
  PI_RESEARCH_RETRY_DELAY_MS: String(config.RESEARCHER_MAX_RETRY_DELAY_MS),
2797
2816
  PI_RESEARCH_MAX_FAILED_RESEARCHERS: String(config.MAX_FAILED_RESEARCHERS ?? DEFAULTS.MAX_FAILED_RESEARCHERS),
2817
+ PI_RESEARCH_SINGLE_RESEARCHER: String(config.SINGLE_RESEARCHER ?? DEFAULTS.SINGLE_RESEARCHER),
2798
2818
  PI_RESEARCH_HEALTH_CHECK_TIMEOUT_MS: String(config.HEALTH_CHECK_TIMEOUT_MS ?? DEFAULTS.HEALTH_CHECK_TIMEOUT_MS),
2799
2819
  PI_RESEARCH_SEARCH_TIMEOUT_MS: String(config.SEARCH_TIMEOUT_MS),
2800
2820
  PI_RESEARCH_TUI_REFRESH_DEBOUNCE_MS: String(config.TUI_REFRESH_DEBOUNCE_MS),
@@ -2976,6 +2996,7 @@ function createConfig(env, processEnv) {
2976
2996
  RESEARCHER_MAX_RETRIES: parseEnvNumber(e, "PI_RESEARCH_MAX_RETRIES", DEFAULTS.RESEARCHER_MAX_RETRIES, 0, 5, true),
2977
2997
  RESEARCHER_MAX_RETRY_DELAY_MS: parseEnvNumber(e, "PI_RESEARCH_RETRY_DELAY_MS", DEFAULTS.RESEARCHER_MAX_RETRY_DELAY_MS, 100, 1e4),
2978
2998
  MAX_FAILED_RESEARCHERS: parseEnvNumber(e, "PI_RESEARCH_MAX_FAILED_RESEARCHERS", DEFAULTS.MAX_FAILED_RESEARCHERS, 1, 10, true),
2999
+ SINGLE_RESEARCHER: parseEnvBool(e, "PI_RESEARCH_SINGLE_RESEARCHER", DEFAULTS.SINGLE_RESEARCHER),
2979
3000
  DEFAULT_RESEARCH_DEPTH: parseEnvNumber(e, "PI_RESEARCH_DEFAULT_RESEARCH_DEPTH", DEFAULTS.DEFAULT_RESEARCH_DEPTH, 0, 3, true),
2980
3001
  QUICK_RESEARCH: parseEnvBool(e, "PI_RESEARCH_QUICK_RESEARCH", DEFAULTS.QUICK_RESEARCH),
2981
3002
  MAX_SCRAPE_BATCHES: parseEnvNumber(e, "PI_RESEARCH_MAX_SCRAPE_BATCHES", DEFAULTS.MAX_SCRAPE_BATCHES, 0, 99, true),
@@ -3039,11 +3060,11 @@ function createConfig(env, processEnv) {
3039
3060
  }
3040
3061
  function getConfig(cwd = process.cwd(), iface) {
3041
3062
  const cacheKey = `${normalizeWorkspacePath(cwd)}:${iface ?? ""}`;
3042
- const cached = configCache.get(cacheKey);
3043
- if (cached && configFingerprints.get(cacheKey) === configSourcesFingerprint(cwd, iface)) {
3044
- return cached;
3063
+ const cached2 = configCache.get(cacheKey);
3064
+ if (cached2 && configFingerprints.get(cacheKey) === configSourcesFingerprint(cwd, iface)) {
3065
+ return cached2;
3045
3066
  }
3046
- if (cached) {
3067
+ if (cached2) {
3047
3068
  logger.info(`[config] Configuration files changed on disk; reloading for ${cwd} (cached values were from process start)`);
3048
3069
  }
3049
3070
  const fingerprint = configSourcesFingerprint(cwd, iface);
@@ -3061,7 +3082,7 @@ function resetConfig() {
3061
3082
  function validateConfig(config) {
3062
3083
  const errors = [...Value.Errors(ConfigSchema, config)];
3063
3084
  if (errors.length > 0) {
3064
- throw new Error(`Invalid configuration: ${errors.map((e) => `${e.path || ""} ${e.message}`).join(", ")}`);
3085
+ throw new Error(`Invalid configuration: ${errors.map((e) => `${e.instancePath || ""} ${e.message}`).join(", ")}`);
3065
3086
  }
3066
3087
  }
3067
3088
  function parseEnvNumber(env, key, def, min, max, integer = false) {
@@ -3118,6 +3139,14 @@ var init_config = __esm({
3118
3139
  RESEARCHER_MAX_RETRY_DELAY_MS: Type.Number({ minimum: 100, maximum: 1e4, default: 2e3 }),
3119
3140
  /** Unique researcher failures that abort the entire run (default: 2, range: 1-10) */
3120
3141
  MAX_FAILED_RESEARCHERS: Type.Number({ minimum: 1, maximum: 10, default: 2 }),
3142
+ /**
3143
+ * Run research with a SINGLE sequential researcher that carries all the queries, instead
3144
+ * of a team of parallel researchers. One session doing all the work keeps one growing,
3145
+ * fully-cached context (each turn re-reads the prior context as a cache hit), at the cost
3146
+ * of serial latency and a larger single context. Default: true (single, cache-friendly
3147
+ * researcher at every depth; Level 1 is always single regardless of this flag).
3148
+ */
3149
+ SINGLE_RESEARCHER: Type.Boolean({ default: true }),
3121
3150
  /** Target depth for recursive research (default: 1, range: 0-3; 0 = quick mode, requires QUICK_RESEARCH) */
3122
3151
  DEFAULT_RESEARCH_DEPTH: Type.Number({ minimum: 0, maximum: 3, default: 1 }),
3123
3152
  /** Opt-in gate for depth-0 (quick mode) research. When false (default), depth 0 is invisible to the agent-facing tool and any depth-0 default resolves to 1 — upstream behavior. When true, agents can pass depth: 0 and DEFAULT_RESEARCH_DEPTH=0 is honored. */
@@ -4209,6 +4238,7 @@ async function retryWithBackoff(fn, options = {}) {
4209
4238
  const startTime = Date.now();
4210
4239
  let lastError = null;
4211
4240
  let attempt = 0;
4241
+ let totalDelayMs = 0;
4212
4242
  metrics.increment("retry_attempts_total", 1, { label: opts.label });
4213
4243
  while (attempt <= opts.maxRetries) {
4214
4244
  try {
@@ -4234,6 +4264,15 @@ async function retryWithBackoff(fn, options = {}) {
4234
4264
  const jitter = Math.random() * 0.5 * baseDelay;
4235
4265
  const override = opts.delayFor?.(attempt + 2, lastError);
4236
4266
  const delay2 = override != null && Number.isFinite(override) && override > 0 ? Math.round(override) : Math.min(baseDelay + jitter, opts.maxDelay);
4267
+ if (opts.maxTotalDelayMs !== void 0 && totalDelayMs + delay2 > opts.maxTotalDelayMs) {
4268
+ const retryAt = new Date(Date.now() + delay2).toISOString().slice(11, 19);
4269
+ metrics.increment("retry_total_delay_exhausted_total", 1, { label: opts.label });
4270
+ throw new Error(
4271
+ `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}`,
4272
+ { cause: error }
4273
+ );
4274
+ }
4275
+ totalDelayMs += delay2;
4237
4276
  metrics.increment("retry_backoff_total", 1, { attempt: String(attempt), label: opts.label });
4238
4277
  metrics.observe("retry_backoff_delay_ms", delay2, { attempt: String(attempt), label: opts.label });
4239
4278
  logger.warn(`[Retry] ${opts.label} failed (attempt ${attempt + 1}/${opts.maxRetries + 1}), retrying in ${Math.round(delay2)}ms: ${lastError.message}`);
@@ -4401,13 +4440,14 @@ async function initializeDawnWebGPU() {
4401
4440
  try {
4402
4441
  const adapter = await logger.runCapturingStderr(async () => {
4403
4442
  const { create, globals } = await import("webgpu");
4443
+ const gpu = create([]);
4404
4444
  Object.assign(globalThis, globals);
4405
4445
  Object.defineProperty(globalThis, "navigator", {
4406
- value: { gpu: create([]) },
4446
+ value: { gpu },
4407
4447
  writable: true,
4408
4448
  configurable: true
4409
4449
  });
4410
- return await globalThis.navigator.gpu.requestAdapter({ powerPreference: "high-performance" });
4450
+ return await gpu.requestAdapter({ powerPreference: "high-performance" });
4411
4451
  });
4412
4452
  if (!adapter) {
4413
4453
  logger.warn("[embedder] No WebGPU adapter available \u2014 using CPU.");
@@ -4415,7 +4455,7 @@ async function initializeDawnWebGPU() {
4415
4455
  }
4416
4456
  const info = adapter.info ?? {};
4417
4457
  const haystack = [info.vendor, info.architecture, info.device, info.description].filter(Boolean).join(" ").toLowerCase();
4418
- if (adapter.isFallbackAdapter === true || SOFTWARE_ADAPTER_PATTERNS.some((p) => haystack.includes(p))) {
4458
+ if (adapter.info?.isFallbackAdapter === true || SOFTWARE_ADAPTER_PATTERNS.some((p) => haystack.includes(p))) {
4419
4459
  logger.warn(
4420
4460
  `[embedder] WebGPU adapter is software/paravirtual (${haystack || "fallback"}) \u2014 Dawn would crash on compute; using CPU.`
4421
4461
  );
@@ -4750,7 +4790,8 @@ async function handleWebGPULoadError(loadErr, pipeline, stateManager, gpuLockHel
4750
4790
  }
4751
4791
  if (pipeline) {
4752
4792
  try {
4753
- if (typeof pipeline.dispose === "function") await pipeline.dispose();
4793
+ const disposable = pipeline;
4794
+ if (typeof disposable.dispose === "function") await disposable.dispose();
4754
4795
  } catch (err) {
4755
4796
  logger.warn("[embedder] Error disposing pipeline:", err);
4756
4797
  }
@@ -4774,7 +4815,8 @@ async function handleWebGPUWarmupError(warmupErr, pipeline, stateManager, gpuLoc
4774
4815
  logger.debug("[embedder] Warmup error details:", warmupErr.message);
4775
4816
  if (pipeline) {
4776
4817
  try {
4777
- if (typeof pipeline.dispose === "function") await pipeline.dispose();
4818
+ const disposable = pipeline;
4819
+ if (typeof disposable.dispose === "function") await disposable.dispose();
4778
4820
  } catch (err) {
4779
4821
  logger.warn("[embedder] Error disposing pipeline:", err);
4780
4822
  }
@@ -4788,7 +4830,8 @@ async function handleWebGPUWarmupError(warmupErr, pipeline, stateManager, gpuLoc
4788
4830
  logger.error("[embedder] CPU fallback pipeline warmup failed:", cpuWarmupErr);
4789
4831
  if (cpuPipeline) {
4790
4832
  try {
4791
- if (typeof cpuPipeline.dispose === "function") await cpuPipeline.dispose();
4833
+ const cpuDisposable = cpuPipeline;
4834
+ if (typeof cpuDisposable.dispose === "function") await cpuDisposable.dispose();
4792
4835
  } catch (err) {
4793
4836
  logger.warn("[embedder] Error disposing fallback CPU pipeline:", err);
4794
4837
  }
@@ -4924,10 +4967,10 @@ async function resolveEmbeddingDevice(requested, model, timeoutMs) {
4924
4967
  if (requested === "cpu") return "cpu";
4925
4968
  if (requested === "webgpu") return "webgpu";
4926
4969
  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";
4970
+ const cached2 = await readVerdict(signature);
4971
+ if (cached2 !== null) {
4972
+ logger.info(`[embedder] WebGPU viability (cached verdict): ${cached2 ? "viable -> webgpu" : "not viable -> cpu"}`);
4973
+ return cached2 ? "webgpu" : "cpu";
4931
4974
  }
4932
4975
  if (!await isModelCached(model)) {
4933
4976
  logger.info("[embedder] Embedding model not cached yet \u2014 using CPU for now; WebGPU will be probed once the model is present.");
@@ -5144,17 +5187,17 @@ var init_embedder = __esm({
5144
5187
  this.device = "cpu";
5145
5188
  }
5146
5189
  }
5147
- const cached = await isModelCached(this.model);
5190
+ const cached2 = await isModelCached(this.model);
5148
5191
  logger.info(
5149
- `[embedder] Loading model: ${this.model} (${cached ? "from local cache" : "downloading from HuggingFace"})...`
5192
+ `[embedder] Loading model: ${this.model} (${cached2 ? "from local cache" : "downloading from HuggingFace"})...`
5150
5193
  );
5151
5194
  const env = await getHFEnv();
5152
5195
  const prevAllowRemote = env.allowRemoteModels;
5153
- if (cached) {
5196
+ if (cached2) {
5154
5197
  env.allowRemoteModels = false;
5155
5198
  }
5156
5199
  try {
5157
- const timeoutMs = cached ? 3e4 : this.initializationTimeoutMs;
5200
+ const timeoutMs = cached2 ? 3e4 : this.initializationTimeoutMs;
5158
5201
  const { pipeline: loadedPipeline } = await loadPipelineWithTimeout(this.model, this.device, timeoutMs, this.useCache);
5159
5202
  this.pipeline = loadedPipeline;
5160
5203
  logger.info(`[embedder] Pipeline loaded (device: ${this.device})`);
@@ -5175,7 +5218,7 @@ var init_embedder = __esm({
5175
5218
  this.pipeline = result.pipeline ?? null;
5176
5219
  this.device = "cpu";
5177
5220
  this.gpuLockHeld = false;
5178
- } else if (cached && isCorruptModelError(loadErr)) {
5221
+ } else if (cached2 && isCorruptModelError(loadErr)) {
5179
5222
  const errMsg = loadErr instanceof Error ? loadErr.message : String(loadErr);
5180
5223
  logger.warn(`[embedder] Corrupt model cache detected on load (${errMsg}); purging and re-downloading once`);
5181
5224
  await purgeModelCache(this.model);
@@ -5219,11 +5262,14 @@ var init_embedder = __esm({
5219
5262
  this.pipeline = result.pipeline ?? null;
5220
5263
  this.device = "cpu";
5221
5264
  this.gpuLockHeld = false;
5222
- dummy = result.dummy;
5265
+ dummy = result.dummy ?? null;
5223
5266
  } else {
5224
5267
  throw warmupErr;
5225
5268
  }
5226
5269
  }
5270
+ if (dummy === null) {
5271
+ throw new Error("[embedder] warmup completed without a dummy tensor; dimension cannot be determined");
5272
+ }
5227
5273
  this.dimension = dummy.dims[dummy.dims.length - 1] ?? null;
5228
5274
  await releaseGpuLock(this.stateManager, this.gpuLockHeld);
5229
5275
  this.gpuLockHeld = false;
@@ -5233,7 +5279,8 @@ var init_embedder = __esm({
5233
5279
  this.gpuLockHeld = false;
5234
5280
  if (this.pipeline) {
5235
5281
  try {
5236
- if (typeof this.pipeline.dispose === "function") await this.pipeline.dispose();
5282
+ const disposable = this.pipeline;
5283
+ if (typeof disposable.dispose === "function") await disposable.dispose();
5237
5284
  } catch (err2) {
5238
5285
  logger.warn("[embedder] Error disposing pipeline:", err2);
5239
5286
  }
@@ -5417,7 +5464,8 @@ var init_embedder = __esm({
5417
5464
  }
5418
5465
  if (this.pipeline) {
5419
5466
  try {
5420
- if (typeof this.pipeline.dispose === "function") await this.pipeline.dispose();
5467
+ const disposable = this.pipeline;
5468
+ if (typeof disposable.dispose === "function") await disposable.dispose();
5421
5469
  } catch (err) {
5422
5470
  logger.warn("[embedder] Error disposing pipeline:", err);
5423
5471
  }
@@ -5496,8 +5544,9 @@ var init_embedder = __esm({
5496
5544
  this.pipeline = null;
5497
5545
  } else {
5498
5546
  try {
5499
- if (typeof this.pipeline.dispose === "function") {
5500
- await this.pipeline.dispose();
5547
+ const disposable = this.pipeline;
5548
+ if (typeof disposable.dispose === "function") {
5549
+ await disposable.dispose();
5501
5550
  }
5502
5551
  } catch (err) {
5503
5552
  logger.warn("[embedder] Error during pipeline dispose:", err);
@@ -6780,8 +6829,8 @@ var init_file_lock_service = __esm({
6780
6829
  async _resolveOwnerAlive(pid, startTime, memo) {
6781
6830
  if (!memo) return this._isOwnerAlive(pid, startTime);
6782
6831
  const key = `${pid ?? "null"}:${startTime ?? "null"}`;
6783
- const cached = memo.get(key);
6784
- if (cached !== void 0) return cached;
6832
+ const cached2 = memo.get(key);
6833
+ if (cached2 !== void 0) return cached2;
6785
6834
  const alive = await this._isOwnerAlive(pid, startTime);
6786
6835
  memo.set(key, alive);
6787
6836
  return alive;
@@ -8059,9 +8108,10 @@ var init_store = __esm({
8059
8108
  const isVersionMismatch = storedVersion !== CURRENT_SCHEMA_VERSION;
8060
8109
  if (!isModelMismatch) {
8061
8110
  const vectorField = schema.fields.find((f) => f.name === "vector");
8062
- if (vectorField && vectorField.type.constructor.name === "FixedSizeList") {
8063
- const dim = vectorField.type.listSize;
8064
- if (this.embedder.getDimension() === null) {
8111
+ const vectorType = vectorField?.type;
8112
+ if (vectorField && vectorType?.constructor?.name === "FixedSizeList") {
8113
+ const dim = vectorType.listSize;
8114
+ if (typeof dim === "number" && this.embedder.getDimension() === null) {
8065
8115
  this.embedder.setDimension(dim);
8066
8116
  logger.debug(`[store] Extracted dimension ${dim} from existing table schema`);
8067
8117
  }
@@ -9544,14 +9594,15 @@ var init_knowledge_store_service = __esm({
9544
9594
  while (this._disposalPromise) {
9545
9595
  await this._disposalPromise;
9546
9596
  }
9547
- const newCwd = ctx?.cwd || this._cwd;
9597
+ const initCtx = ctx;
9598
+ const newCwd = initCtx?.cwd || this._cwd;
9548
9599
  if ((this.lifecycle === "initialized" /* INITIALIZED */ || this.lifecycle === "disabled" /* DISABLED */) && this._cwd === newCwd) {
9549
- const liveConfig = ctx?.config || getConfig(this._cwd);
9600
+ const liveConfig = initCtx?.config || getConfig(this._cwd);
9550
9601
  const liveMode = liveConfig.KNOWLEDGE_STORE_MODE;
9551
9602
  const liveRetrieval = liveConfig.KNOWLEDGE_STORE_RETRIEVAL;
9552
9603
  const reviveFromMode = this.lifecycle === "disabled" /* DISABLED */ && this._disabledReason === "mode" && liveMode !== "none";
9553
- const modeChanged = this.lifecycle === "initialized" /* INITIALIZED */ && ctx?.config !== void 0 && this._initializedMode !== void 0 && this._initializedMode !== ctx.config.KNOWLEDGE_STORE_MODE;
9554
- const retrievalChanged = this.lifecycle === "initialized" /* INITIALIZED */ && ctx?.config !== void 0 && this._initializedRetrieval !== void 0 && this._initializedRetrieval !== ctx.config.KNOWLEDGE_STORE_RETRIEVAL;
9604
+ const modeChanged = this.lifecycle === "initialized" /* INITIALIZED */ && initCtx?.config !== void 0 && this._initializedMode !== void 0 && this._initializedMode !== initCtx.config.KNOWLEDGE_STORE_MODE;
9605
+ const retrievalChanged = this.lifecycle === "initialized" /* INITIALIZED */ && initCtx?.config !== void 0 && this._initializedRetrieval !== void 0 && this._initializedRetrieval !== initCtx.config.KNOWLEDGE_STORE_RETRIEVAL;
9555
9606
  if (!reviveFromMode && !modeChanged && !retrievalChanged) {
9556
9607
  return;
9557
9608
  }
@@ -9587,8 +9638,8 @@ var init_knowledge_store_service = __esm({
9587
9638
  let initPromise = null;
9588
9639
  initPromise = (async () => {
9589
9640
  try {
9590
- this._cwd = ctx?.cwd || this._cwd;
9591
- const config = ctx?.config || getConfig(this._cwd);
9641
+ this._cwd = initCtx?.cwd || this._cwd;
9642
+ const config = initCtx?.config || getConfig(this._cwd);
9592
9643
  this._initializedMode = config.KNOWLEDGE_STORE_MODE;
9593
9644
  this._initializedRetrieval = config.KNOWLEDGE_STORE_RETRIEVAL;
9594
9645
  const embedderFactory = () => getEmbedder(config);
@@ -10681,7 +10732,7 @@ function createResearchKnowledgeSearchTool(iface) {
10681
10732
  // Cache/session-affinity hint only (keeps repeated calls on the same warmed
10682
10733
  // replica) — same resolution research-config.ts uses, since this tool has no
10683
10734
  // researchId of its own to key on. ctx.sessionId is read defensively: it is
10684
- // not on every host's ExtensionContext shape, hence the `as any`.
10735
+ // not on every host's ExtensionContext shape, hence the cast.
10685
10736
  ctx.sessionId || ctx.sessionManager?.getSessionId()
10686
10737
  );
10687
10738
  const durationMs = Date.now() - startTime;
@@ -10774,6 +10825,10 @@ import * as fs17 from "node:fs";
10774
10825
  import * as os7 from "node:os";
10775
10826
  import * as path19 from "node:path";
10776
10827
  import { fileURLToPath as fileURLToPath5 } from "node:url";
10828
+ function errDetail(err) {
10829
+ const e = err;
10830
+ return e?.code ?? e?.message ?? String(err);
10831
+ }
10777
10832
  function readSkillVersion(sourceDir) {
10778
10833
  try {
10779
10834
  const md = fs17.readFileSync(path19.join(sourceDir, "SKILL.md"), "utf-8");
@@ -10948,9 +11003,9 @@ function installSkill(toolIds, opts = {}) {
10948
11003
  try {
10949
11004
  copyDir(source, absSkillPath);
10950
11005
  upsertEntry(manifest, { tool: id, path: absSkillPath, type: "copy", source, createdAt: now, ...skillVersion ? { version: skillVersion } : {} });
10951
- results.push({ tool: id, path: absSkillPath, type: "copy", status: "installed", message: `symlink re-point unavailable (${relinkErr?.code ?? relinkErr?.message}); copied instead` });
11006
+ results.push({ tool: id, path: absSkillPath, type: "copy", status: "installed", message: `symlink re-point unavailable (${errDetail(relinkErr)}); copied instead` });
10952
11007
  } catch (copyErr) {
10953
- results.push({ tool: id, path: absSkillPath, type: "symlink", status: "error", message: `symlink re-point failed (${relinkErr?.code ?? relinkErr?.message}) and the copy fallback also failed: ${copyErr?.message ?? String(copyErr)}` });
11008
+ results.push({ tool: id, path: absSkillPath, type: "symlink", status: "error", message: `symlink re-point failed (${errDetail(relinkErr)}) and the copy fallback also failed: ${errDetail(copyErr)}` });
10954
11009
  }
10955
11010
  }
10956
11011
  continue;
@@ -10983,7 +11038,7 @@ function installSkill(toolIds, opts = {}) {
10983
11038
  } catch (err) {
10984
11039
  copyDir(source, absSkillPath);
10985
11040
  upsertEntry(manifest, { tool: id, path: absSkillPath, type: "copy", source, createdAt: now, ...skillVersion ? { version: skillVersion } : {} });
10986
- results.push({ tool: id, path: absSkillPath, type: "copy", status: "installed", message: `symlink unavailable (${err?.code ?? err?.message}); copied instead` });
11041
+ results.push({ tool: id, path: absSkillPath, type: "copy", status: "installed", message: `symlink unavailable (${errDetail(err)}); copied instead` });
10987
11042
  continue;
10988
11043
  }
10989
11044
  } else {
@@ -10992,7 +11047,7 @@ function installSkill(toolIds, opts = {}) {
10992
11047
  upsertEntry(manifest, { tool: id, path: absSkillPath, type, source, createdAt: now, ...skillVersion ? { version: skillVersion } : {} });
10993
11048
  results.push({ tool: id, path: absSkillPath, type, status: "installed" });
10994
11049
  } catch (err) {
10995
- results.push({ tool: id, path: absSkillPath, type, status: "error", message: err?.message ?? String(err) });
11050
+ results.push({ tool: id, path: absSkillPath, type, status: "error", message: errDetail(err) });
10996
11051
  }
10997
11052
  }
10998
11053
  if (!opts.dryRun) writeManifest(manifest, opts);
@@ -11038,7 +11093,7 @@ function uninstallSkill(toolIds, opts = {}) {
11038
11093
  else fs17.rmSync(skillPath, { recursive: true, force: true, maxRetries: 5, retryDelay: 50 });
11039
11094
  results.push({ tool, path: skillPath, status: "removed" });
11040
11095
  } catch (err) {
11041
- results.push({ tool, path: skillPath, status: "error", message: err?.message ?? String(err) });
11096
+ results.push({ tool, path: skillPath, status: "error", message: errDetail(err) });
11042
11097
  const e = manifest.entries.find((x) => x.path === skillPath);
11043
11098
  if (e) keep.push(e);
11044
11099
  }
@@ -11347,24 +11402,26 @@ function isSpentAccountError(error) {
11347
11402
  function isRateLimitError(error) {
11348
11403
  if (isSpentAccountError(error)) return false;
11349
11404
  const msg2 = (error instanceof Error ? error.message : String(error)).toLowerCase();
11350
- 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");
11405
+ 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");
11351
11406
  }
11352
11407
  function isCapacityFailureReason(reason) {
11353
11408
  return reason !== void 0 && reason !== "" && isRateLimitError(reason);
11354
11409
  }
11355
11410
  function parseRetryAfterMs(error) {
11356
11411
  const message = error instanceof Error ? error.message : String(error);
11357
- const m = /["']?retry-after["']?\s*[:=]\s*["']?(\d{1,4})/i.exec(message);
11412
+ 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);
11358
11413
  if (!m) return null;
11359
11414
  const seconds = Number(m[1]);
11360
11415
  if (!Number.isFinite(seconds) || seconds <= 0) return null;
11361
- return Math.min(Math.max(seconds, 5), 60) * 1e3;
11416
+ return Math.min(Math.max(seconds, 5), STATED_RETRY_AFTER_MAX_MS / 1e3) * 1e3;
11362
11417
  }
11363
11418
  var RATE_LIMIT_BACKOFF_BASE_MS = 15e3;
11364
11419
  var RATE_LIMIT_BACKOFF_MAX_MS = 6e4;
11420
+ var STATED_RETRY_AFTER_MAX_MS = 18e4;
11421
+ var RATE_LIMIT_TOTAL_WAIT_MAX_MS = 24e4;
11365
11422
  function rateLimitBackoffMs(attempt, retryAfterMs, random = Math.random) {
11366
11423
  if (retryAfterMs !== null && Number.isFinite(retryAfterMs) && retryAfterMs > 0) {
11367
- return clampRateLimitWait(retryAfterMs);
11424
+ return Math.min(Math.max(Math.round(retryAfterMs), 1e3), STATED_RETRY_AFTER_MAX_MS);
11368
11425
  }
11369
11426
  const exponent = Math.max(0, attempt - 2);
11370
11427
  const base = Math.min(RATE_LIMIT_BACKOFF_BASE_MS * Math.pow(2, exponent), RATE_LIMIT_BACKOFF_MAX_MS);
@@ -11669,18 +11726,18 @@ var COVERAGE_DIGEST_TERMINATOR = "END COVERAGE DIGEST";
11669
11726
  var DIGEST_HEAD_WINDOW_CHARS = 600;
11670
11727
  var MAX_DIGEST_CHARS = 2400;
11671
11728
  var MAX_DIGEST_BLOCK_CHARS = 8e3;
11672
- var RESEARCHER_DIGEST_SECTION = `Your report has three parts in this exact order: a COVERAGE DIGEST block, the report body, and the CITED LINKS list.
11729
+ var RESEARCHER_DIGEST_SECTION = `Your final message is the COVERAGE DIGEST block. Emit it and stop \u2014 do NOT write a report. The raw content you scraped is what the synthesis step reads; your job is to scrape, then account for what you covered.
11673
11730
 
11674
- ### Part 1 \u2014 COVERAGE DIGEST (first, mandatory)
11731
+ ### COVERAGE DIGEST (mandatory)
11675
11732
 
11676
- Open the report with this block, exactly as shown. The research lead reads it to decide what still needs investigating. On the round your report arrives the lead reads the digest alongside the full report and checks one against the other; on every later round it sees ONLY this digest \u2014 so anything you leave out of it is invisible to every decision after the first.
11733
+ The research lead reads this to decide what still needs investigating. On the round your work arrives the lead reads the digest alongside the raw content and checks one against the other; on every later round it sees ONLY this digest \u2014 so anything you leave out of it is invisible to every decision after the first.
11677
11734
 
11678
11735
  ${COVERAGE_DIGEST_HEADER}
11679
11736
  Goal: [your assigned goal, restated in one line]
11680
11737
  Covered: [the specific topics you actually established from sources, separated by semicolons \u2014 be concrete, name the things you found out, not the areas you looked at]
11681
11738
  Unsubstantiated: [claims you searched for but could not ground in any source; write "none" if there are none]
11682
11739
  Gaps: [what a follow-up researcher would still need to investigate on this goal; write "none" if your goal is fully covered]
11683
- Sources: [the number of entries in your CITED LINKS list]
11740
+ Sources: [the number of URLs you scraped]
11684
11741
  ${COVERAGE_DIGEST_TERMINATOR}
11685
11742
 
11686
11743
  Rules for the digest:
@@ -11688,8 +11745,6 @@ Rules for the digest:
11688
11745
  - Be honest about \`Gaps\` and \`Unsubstantiated\`. Claiming full coverage you do not have is the single most damaging thing you can write here: it argues for ending the research on this topic, and after the round it arrives there is no report left for the lead to check the claim against.
11689
11746
  - Write both delimiter lines exactly, in capitals, each on its own line.
11690
11747
 
11691
- ### Part 2 \u2014 Report body
11692
-
11693
11748
  `;
11694
11749
  function delimiterRegex(word) {
11695
11750
  return new RegExp(`(^|\\n)([ \\t]*(?:#{1,6}[ \\t]*|>[ \\t]*|\\*\\*[ \\t]*)?)${word}\\b`, "i");
@@ -11719,6 +11774,14 @@ function splitCoverageDigest(report) {
11719
11774
  if (!body) return { digest: "", body: report };
11720
11775
  return { digest, body };
11721
11776
  }
11777
+ function buildFallbackDigest(goal, scrapeCount) {
11778
+ const topic = goal.trim() || "unknown \u2014 no goal recorded";
11779
+ return [
11780
+ `Covered: ${topic} (no coverage digest emitted; goal restated)`,
11781
+ `Gaps: unknown \u2014 this researcher emitted no coverage digest`,
11782
+ `Sources: ${scrapeCount}`
11783
+ ].join("\n");
11784
+ }
11722
11785
  function deriveCoverageDigest(body) {
11723
11786
  const citationCount = parseCitations(body).length;
11724
11787
  const citedIdx = lastCitedLinksHeaderIndex(body);
@@ -11779,6 +11842,9 @@ init_constants();
11779
11842
  function getTeamSize(complexity) {
11780
11843
  return complexity === 1 ? MAX_TEAM_SIZE_LEVEL_1 : complexity === 2 ? MAX_TEAM_SIZE_LEVEL_2 : MAX_TEAM_SIZE_LEVEL_3;
11781
11844
  }
11845
+ function effectiveSingleResearcher(complexity, singleResearcher) {
11846
+ return complexity === 1 ? true : singleResearcher;
11847
+ }
11782
11848
  function getQueryBudget(complexity) {
11783
11849
  return complexity === 1 ? MAX_QUERIES_PER_RESEARCHER_LEVEL_1 : complexity === 2 ? MAX_QUERIES_PER_RESEARCHER_LEVEL_2 : MAX_QUERIES_PER_RESEARCHER_LEVEL_3;
11784
11850
  }
@@ -11787,7 +11853,7 @@ function getMaxRounds(complexity) {
11787
11853
  }
11788
11854
  function getComplexityGuidance(complexity, maxTeamSize, queryBudget) {
11789
11855
  if (complexity === 1) {
11790
- return "**Complexity: Level 1 (Normal)**. Conduct a thorough, well-rounded investigation of the topic covering the primary angles with adequate citations. **Plan ONLY Round 1** \u2014 a single comprehensive round. **Default to a single researcher** for most Level 1 topics \u2014 one focused researcher can handle the majority of normal-complexity queries efficiently. Use 2 researchers only when the topic clearly spans two distinct, non-overlapping domains that benefit from parallel investigation. This is a ONE-SHOT effort: plan Round 1 as if it is the only round, because it should be. Only Level 2 or Level 3 research should involve multiple rounds.";
11856
+ return "**Complexity: Level 1 (Normal)**. Conduct a thorough, well-rounded investigation of the topic covering the primary angles with adequate citations. **Plan ONLY Round 1** \u2014 a single comprehensive round. **Use ONE researcher** \u2014 one focused researcher handles normal-complexity queries. This is a ONE-SHOT effort: plan Round 1 as if it is the only round, because it should be. Only Level 2 or Level 3 research should involve multiple rounds.";
11791
11857
  } else if (complexity === 2) {
11792
11858
  return `**Complexity: Level 2 (Deep)**. **ONLY for HIGH/EXTREME research needs.** Level 2 should be reserved for topics that clearly require deeper investigation than a single comprehensive round can provide. **Plan ONLY Round 1** \u2014 a thorough, well-structured first round. Subsequent rounds are reactive and only delegated when Round 1 findings reveal clear gaps that warrant deeper or broader coverage. Do not pre-plan multiple rounds; delegate follow-ups only when Round 1 demonstrates genuine need.
11793
11859
 
@@ -11809,7 +11875,7 @@ function getEvaluatorComplexityGuidance(complexity, researchRounds) {
11809
11875
  - **SYNTHESIZE when**: The primary topic is covered from multiple angles with evidence from diverse sources and no significant gaps remain that would prevent a complete answer.
11810
11876
  - **DELEGATE when**: Coverage is incomplete, important angles are missing, or additional sources would meaningfully strengthen the findings.
11811
11877
 
11812
- **DEFAULT PATH**: Synthesize after Round 1 if the researcher produced solid coverage of the core topic. **Level 1 should almost always be a single round** \u2014 only delegate a second round when Round 1 clearly missed important angles or lacks source diversity. A single researcher is the default for Level 1 follow-up rounds \u2014 only use 2 researchers if the remaining gaps clearly span two distinct domains. Level 2 research escalation should be reserved for truly high/extreme research needs only.`;
11878
+ **DEFAULT PATH**: Synthesize after Round 1 if the researcher produced solid coverage of the core topic. **Level 1 should almost always be a single round** \u2014 only delegate a second round when Round 1 clearly missed important angles or lacks source diversity. **Use ONE researcher** for follow-up rounds. Level 2 research escalation should be reserved for truly high/extreme research needs only.`;
11813
11879
  } else if (complexity === 2) {
11814
11880
  return `**Level 2 (Deep)** - Thorough, multi-phase investigation with comprehensive citations.
11815
11881
 
@@ -11953,7 +12019,7 @@ function parseJsonPlan(text) {
11953
12019
  const coerced = Value3.Convert(ResearchPlanSchema, candidate);
11954
12020
  if (!Value3.Check(ResearchPlanSchema, coerced)) {
11955
12021
  const errors = [...Value3.Errors(ResearchPlanSchema, coerced)];
11956
- const errorMsg = errors.map((e) => `${e.path}: ${e.message}`).join(", ");
12022
+ const errorMsg = errors.map((e) => `${e.instancePath || ""} ${e.message}`).join(", ");
11957
12023
  throw new Error(`Plan validation failed: ${errorMsg}`);
11958
12024
  }
11959
12025
  const plan = coerced;
@@ -11984,11 +12050,12 @@ function buildFallbackCoordinatorPlan(serviceName, _rawText, query) {
11984
12050
  allQueries: queries
11985
12051
  };
11986
12052
  }
11987
- function capResearcherQueries(plan, complexity, serviceName) {
11988
- const budget = getQueryBudget(complexity);
12053
+ function capResearcherQueries(plan, complexity, serviceName, singleResearcher = false) {
12054
+ const perResearcher = getQueryBudget(complexity);
12055
+ const budget = singleResearcher ? getTeamSize(complexity) * perResearcher : perResearcher;
11989
12056
  const ROUND_HARD_CAP = complexity === 1 ? 20 : complexity === 2 ? 45 : 100;
11990
12057
  if (!plan.researchers) return plan;
11991
- const maxTeam = getTeamSize(complexity);
12058
+ const maxTeam = singleResearcher ? 1 : getTeamSize(complexity);
11992
12059
  plan.researchers = plan.researchers.filter((r) => r && typeof r === "object" && Array.isArray(r.queries) && r.queries.length > 0).slice(0, maxTeam).map((r) => {
11993
12060
  const normalized = { ...r, id: String(r.id) };
11994
12061
  if (normalized.queries.length > budget) {
@@ -12215,8 +12282,8 @@ var PlanningService = class {
12215
12282
  buildFallbackCoordinatorPlan(rawText, query) {
12216
12283
  return buildFallbackCoordinatorPlan("PlanningService", rawText, query);
12217
12284
  }
12218
- capResearcherQueries(plan, complexity, serviceName) {
12219
- return capResearcherQueries(plan, complexity, serviceName);
12285
+ capResearcherQueries(plan, complexity, serviceName, singleResearcher = false) {
12286
+ return capResearcherQueries(plan, complexity, serviceName, singleResearcher);
12220
12287
  }
12221
12288
  generateResearchers(plan, query, complexity) {
12222
12289
  return generateResearchers(plan, query, complexity);
@@ -12242,7 +12309,9 @@ var PlanningService = class {
12242
12309
  const promptTemplate = loadPrompt("system-coordinator");
12243
12310
  const maxTeamSize = this.getTeamSize(complexity);
12244
12311
  const queryBudget = this.getQueryBudget(complexity);
12245
- const complexityGuidance = this.getComplexityGuidance(complexity, maxTeamSize, queryBudget);
12312
+ const singleResearcher = effectiveSingleResearcher(complexity, config.SINGLE_RESEARCHER);
12313
+ const teamSizeGuidance = singleResearcher ? "Plan **exactly ONE researcher** that covers the entire scope, carrying all the queries. Do NOT split the work across multiple researchers \u2014 one agent doing all the work keeps a single growing, fully-cached context." : `**Team size**: Plan between **1 and ${maxTeamSize} researchers**. A **single researcher is a complete, valid plan** \u2014 when the topic is focused or singular, assign just one. Add more only for genuinely distinct, non-overlapping angles; never split a narrow topic just to fill the team. (See the complexity guidance below for the default at this level.)`;
12314
+ const complexityGuidance = singleResearcher ? `**Complexity: ${complexity === 1 ? "Level 1 (Normal)" : complexity === 2 ? "Level 2 (Deep)" : "Level 3 (Ultra)"}** \u2014 Plan ONE researcher with the full query budget (${queryBudget} queries) covering the entire scope. Do not split across researchers; the single agent reads every source in sequence.` : this.getComplexityGuidance(complexity, maxTeamSize, queryBudget);
12246
12315
  let steeringSection = "";
12247
12316
  if (steeringMessages && steeringMessages.length > 0) {
12248
12317
  steeringSection = "\n\n### ADDITIONAL USER GUIDANCE (Apply these rules and instructions to your plan and decisions)\n" + steeringMessages.map((m) => `- ${m}`).join("\n");
@@ -12256,6 +12325,7 @@ The following tools are DISABLED for this session: ${options.excludeTools.join("
12256
12325
  root_query: query,
12257
12326
  additional_considerations: steeringSection,
12258
12327
  complexity_label: complexity === 1 ? "Level 1 (Normal)" : complexity === 2 ? "Level 2 (Deep)" : "Level 3 (Ultra)",
12328
+ team_size_guidance: teamSizeGuidance,
12259
12329
  max_team_size: maxTeamSize,
12260
12330
  query_budget: queryBudget,
12261
12331
  complexity_guidance: complexityGuidance,
@@ -12305,7 +12375,10 @@ Respond by calling the ${submitPlanTool.name} tool with the plan as its argument
12305
12375
  label: "coordinator-generatePlan",
12306
12376
  signal,
12307
12377
  isTransientError: (err) => isRetriableLlmError(err, signal),
12308
- delayFor: rateLimitDelayFor
12378
+ delayFor: rateLimitDelayFor,
12379
+ // Bound the TOTAL wait for THIS call: a provider that keeps asking for
12380
+ // a long window must not spend the run's whole budget sleeping here.
12381
+ maxTotalDelayMs: RATE_LIMIT_TOTAL_WAIT_MAX_MS
12309
12382
  }
12310
12383
  );
12311
12384
  recordLlmUsage(model, response.usage, { component: "coordinator", complexity, observer });
@@ -12351,10 +12424,10 @@ Respond by calling the ${submitPlanTool.name} tool with the plan as its argument
12351
12424
  logger.warn("[PlanningService] Failed to generate valid plan, building fallback");
12352
12425
  plan = this.buildFallbackCoordinatorPlan(responseText, query);
12353
12426
  }
12354
- plan = this.capResearcherQueries(plan, complexity, this.name);
12427
+ plan = this.capResearcherQueries(plan, complexity, this.name, singleResearcher);
12355
12428
  if (!plan.researchers || plan.researchers.length === 0) {
12356
12429
  logger.warn("[PlanningService] Coordinator produced no runnable researchers (empty queries); using single-researcher fallback");
12357
- plan = this.capResearcherQueries(this.buildFallbackCoordinatorPlan(responseText, query), complexity, this.name);
12430
+ plan = this.capResearcherQueries(this.buildFallbackCoordinatorPlan(responseText, query), complexity, this.name, singleResearcher);
12358
12431
  }
12359
12432
  plan.action = "delegate";
12360
12433
  this.currentPlans.set(sessionId, plan);
@@ -12371,7 +12444,7 @@ Respond by calling the ${submitPlanTool.name} tool with the plan as its argument
12371
12444
  }
12372
12445
  logger.warn("[PlanningService] Coordinator call failed transiently; building fallback plan so the run can proceed");
12373
12446
  let plan = this.buildFallbackCoordinatorPlan("", query);
12374
- plan = this.capResearcherQueries(plan, complexity, this.name);
12447
+ plan = this.capResearcherQueries(plan, complexity, this.name, singleResearcher);
12375
12448
  if (plan.action !== "synthesize") {
12376
12449
  plan.action = "delegate";
12377
12450
  }
@@ -12406,7 +12479,8 @@ Respond by calling the ${submitPlanTool.name} tool with the plan as its argument
12406
12479
  logger.log(`[PlanningService] ${isRouter ? "Routing after" : "Synthesizing at"} Round ${round} for: "${query}"`);
12407
12480
  const config = options.config ?? getConfig(options.cwd);
12408
12481
  const promptTemplate = loadPrompt(isRouter ? "system-lead-router" : "system-lead-synthesizer");
12409
- const maxTeamSize = this.getTeamSize(complexity);
12482
+ const singleResearcher = effectiveSingleResearcher(complexity, config.SINGLE_RESEARCHER);
12483
+ const maxTeamSize = singleResearcher ? 1 : this.getTeamSize(complexity);
12410
12484
  const queryBudget = this.getQueryBudget(complexity);
12411
12485
  const maxRounds = options.maxRounds ?? getMaxRounds(complexity);
12412
12486
  const researchRounds = Math.max(1, maxRounds - 1);
@@ -12561,13 +12635,14 @@ Respond by calling the ${submitRoutingTool.name} tool with the updated plan as i
12561
12635
  finalPlan.action = "delegate";
12562
12636
  }
12563
12637
  if (finalPlan.action === "delegate") {
12564
- const capped = this.capResearcherQueries(finalPlan, complexity, this.name);
12638
+ const capped = this.capResearcherQueries(finalPlan, complexity, this.name, singleResearcher);
12565
12639
  if (!capped.researchers || capped.researchers.length === 0) {
12566
12640
  if (previousPlan?.researchers && previousPlan.researchers.length > 0) {
12567
12641
  const fallback2 = this.capResearcherQueries(
12568
12642
  { action: "delegate", content: "", researchers: previousPlan.researchers },
12569
12643
  complexity,
12570
- this.name
12644
+ this.name,
12645
+ singleResearcher
12571
12646
  );
12572
12647
  if (fallback2.researchers && fallback2.researchers.length > 0) {
12573
12648
  logger.warn("[PlanningService] Evaluator delegated zero runnable researchers; continuing the prior agenda rather than synthesizing early");
@@ -12596,7 +12671,8 @@ Respond by calling the ${submitRoutingTool.name} tool with the updated plan as i
12596
12671
  const fallback2 = this.capResearcherQueries(
12597
12672
  { action: "delegate", content: "", researchers: previousPlan.researchers },
12598
12673
  complexity,
12599
- this.name
12674
+ this.name,
12675
+ singleResearcher
12600
12676
  );
12601
12677
  this.currentPlans.set(sessionId, fallback2);
12602
12678
  return fallback2;
@@ -12720,7 +12796,10 @@ Respond by calling the ${submitRoutingTool.name} tool with the updated plan as i
12720
12796
  label,
12721
12797
  signal,
12722
12798
  isTransientError: (err) => isRetriableLlmError(err, signal),
12723
- delayFor: rateLimitDelayFor
12799
+ delayFor: rateLimitDelayFor,
12800
+ // Bound the TOTAL wait for THIS call: a provider that keeps asking for
12801
+ // a long window must not spend the run's whole budget sleeping here.
12802
+ maxTotalDelayMs: RATE_LIMIT_TOTAL_WAIT_MAX_MS
12724
12803
  }
12725
12804
  );
12726
12805
  recordLlmUsage(model, response.usage, { component: args.component, complexity, observer });
@@ -14570,6 +14649,8 @@ var BrowserTaskScheduler = class {
14570
14649
  }
14571
14650
  try {
14572
14651
  return await executePoolTaskWithDeathBackstop(
14652
+ // poolifier pools are Response = unknown by default; the worker
14653
+ // settles search tasks with this in-band shape.
14573
14654
  () => pool.execute({ type: "search", query, queuedAt: startTime, taskTimeoutMs: timeoutMs }),
14574
14655
  timeoutMs,
14575
14656
  "Search"
@@ -14658,6 +14739,8 @@ var BrowserTaskScheduler = class {
14658
14739
  }
14659
14740
  try {
14660
14741
  return await executePoolTaskWithDeathBackstop(
14742
+ // poolifier pools are Response = unknown by default; the worker
14743
+ // settles scrape tasks with the in-band ScrapeResult shape.
14661
14744
  () => pool.execute({ type: "scrape", url, queuedAt: startTime, taskTimeoutMs: timeoutMs }),
14662
14745
  timeoutMs,
14663
14746
  "Scrape"
@@ -14849,7 +14932,7 @@ var BrowserTaskScheduler = class {
14849
14932
  if (this.workerPoolManager) {
14850
14933
  const pool = this.workerPoolManager.getPool();
14851
14934
  if (pool && pool.workerNodes) {
14852
- const workerPids = pool.workerNodes.map((n) => n.worker?.process?.pid).filter(Boolean);
14935
+ const workerPids = pool.workerNodes.map((n) => n.worker?.process?.pid).filter((pid) => pid !== void 0);
14853
14936
  if (workerPids.length > 0) {
14854
14937
  targetBrowserPids = await getBrowserPidsForWorkers(workerPids);
14855
14938
  }
@@ -15155,8 +15238,9 @@ var SchedulerFactoryService = class {
15155
15238
  lifecycle = "uninitialized" /* UNINITIALIZED */;
15156
15239
  container = getServiceContainer();
15157
15240
  async initialize(ctx) {
15158
- if (ctx?.container) {
15159
- this.container = ctx.container;
15241
+ const initCtx = ctx;
15242
+ if (initCtx?.container) {
15243
+ this.container = initCtx.container;
15160
15244
  }
15161
15245
  this.lifecycle = "initialized" /* INITIALIZED */;
15162
15246
  }
@@ -15200,7 +15284,7 @@ import * as path12 from "node:path";
15200
15284
  import * as crypto7 from "node:crypto";
15201
15285
  import process2 from "node:process";
15202
15286
 
15203
- // src/infrastructure/types/state-types.ts
15287
+ // src/types/state-types.ts
15204
15288
  import { Type as Type3 } from "typebox";
15205
15289
  var CURRENT_STATE_VERSION = 1;
15206
15290
  var SessionInfoSchema = Type3.Object({
@@ -16702,8 +16786,9 @@ var StateValidator = class {
16702
16786
  if (!Value4.Check(SingletonStateSchema, coerced)) {
16703
16787
  const errors = [...Value4.Errors(SingletonStateSchema, coerced)];
16704
16788
  const errorMsg = errors.map((e) => {
16705
- const path21 = String(e.path || "root");
16706
- return `${path21}: ${e.message} (${JSON.stringify(e.value)})`;
16789
+ const path21 = String(e.instancePath || "root");
16790
+ const value = e.value;
16791
+ return `${path21}: ${e.message} (${JSON.stringify(value)})`;
16707
16792
  }).join(", ");
16708
16793
  throw new Error(`Invalid state: ${errorMsg}`);
16709
16794
  }
@@ -17044,8 +17129,9 @@ var workerId = "";
17044
17129
  var BENIGN_IPC_CODES = /* @__PURE__ */ new Set(["EPIPE", "ERR_IPC_CHANNEL_CLOSED", "ECONNRESET"]);
17045
17130
  function isBenignClusterIpcError(err) {
17046
17131
  if (!err) return false;
17047
- if (typeof err.code === "string" && BENIGN_IPC_CODES.has(err.code)) return true;
17048
- const msg2 = String(err.message || err);
17132
+ const e = err;
17133
+ if (typeof e.code === "string" && BENIGN_IPC_CODES.has(e.code)) return true;
17134
+ const msg2 = String(e.message || err);
17049
17135
  return /\b(EPIPE|ECONNRESET)\b/.test(msg2) || /channel closed/i.test(msg2);
17050
17136
  }
17051
17137
  var masterIpcGuardInstalled = false;
@@ -17055,7 +17141,7 @@ function setupMasterIpcErrorHandler() {
17055
17141
  masterIpcGuardInstalled = true;
17056
17142
  cluster.on("fork", (worker) => guardClusterWorker(worker));
17057
17143
  for (const id of Object.keys(cluster.workers ?? {})) {
17058
- const w = cluster.workers?.[id];
17144
+ const w = (cluster.workers ?? {})[id];
17059
17145
  if (w) guardClusterWorker(w);
17060
17146
  }
17061
17147
  guardWorkerEmitReemit();
@@ -17073,11 +17159,12 @@ function guardWorkerEmitReemit() {
17073
17159
  Worker2.prototype.emit = function(event, ...args) {
17074
17160
  if (event === "error" && typeof this.listenerCount === "function" && this.listenerCount("error") === 0) {
17075
17161
  this.on("error", (err) => {
17162
+ const e = err;
17076
17163
  if (isBenignClusterIpcError(err)) {
17077
- logToDebugFile("DEBUG", `[Master] Last-resort guard swallowed listener-less IPC error: ${err?.code || err?.message}`);
17164
+ logToDebugFile("DEBUG", `[Master] Last-resort guard swallowed listener-less IPC error: ${e?.code || e?.message}`);
17078
17165
  return;
17079
17166
  }
17080
- logToDebugFile("WARN", `[Master] Last-resort guard handled listener-less worker error: ${err?.stack || err?.message || err}`);
17167
+ logToDebugFile("WARN", `[Master] Last-resort guard handled listener-less worker error: ${e?.stack || e?.message || err}`);
17081
17168
  });
17082
17169
  }
17083
17170
  return origEmit.apply(this, [event, ...args]);
@@ -17087,11 +17174,12 @@ function guardClusterWorker(worker) {
17087
17174
  if (!worker || worker.__piIpcGuarded) return;
17088
17175
  worker.__piIpcGuarded = true;
17089
17176
  const guard = (err) => {
17177
+ const e = err;
17090
17178
  if (isBenignClusterIpcError(err)) {
17091
- logToDebugFile("DEBUG", `[Master] Swallowed benign worker IPC error: ${err?.code || err?.message}`);
17179
+ logToDebugFile("DEBUG", `[Master] Swallowed benign worker IPC error: ${e?.code || e?.message}`);
17092
17180
  return;
17093
17181
  }
17094
- logToDebugFile("WARN", `[Master] Worker error (non-IPC): ${err?.stack || err?.message || err}`);
17182
+ logToDebugFile("WARN", `[Master] Worker error (non-IPC): ${e?.stack || e?.message || err}`);
17095
17183
  };
17096
17184
  worker.on("error", guard);
17097
17185
  if (worker.process && typeof worker.process.on === "function") {
@@ -18316,8 +18404,8 @@ async function isRegisteredLeaderAliveUncached(container) {
18316
18404
  const info = await stateManager.getBrowserServer();
18317
18405
  if (!info) return false;
18318
18406
  const schedulerService = await getService(ServiceNames.SCHEDULER, void 0, container);
18319
- const cached = schedulerService.getSchedulerInstance();
18320
- if (cached instanceof BrowserClient && cached.targetPort !== info.port) return false;
18407
+ const cached2 = schedulerService.getSchedulerInstance();
18408
+ if (cached2 instanceof BrowserClient && cached2.targetPort !== info.port) return false;
18321
18409
  return await stateManager.isPidAlive(info.pid, info.schedulerId);
18322
18410
  } catch {
18323
18411
  return false;
@@ -18487,6 +18575,246 @@ async function runWorkerSearch(query, config, signal, retries = 1, sessionId, co
18487
18575
  }
18488
18576
  }
18489
18577
 
18578
+ // src/infrastructure/browser/proxy-health.ts
18579
+ import net3 from "node:net";
18580
+
18581
+ // src/infrastructure/browser/proxy-prefs.ts
18582
+ import { existsSync as existsSync12, readFileSync as readFileSync7 } from "node:fs";
18583
+ import { homedir as homedir6 } from "node:os";
18584
+ function proxyConfigPath() {
18585
+ return process.env["PI_RESEARCH_PROXY_JSON"] || `${homedir6()}/.pi/research/proxy.json`;
18586
+ }
18587
+ var cached;
18588
+ var cachedAt = 0;
18589
+ var CACHE_TTL_MS = 1e4;
18590
+ function getSocksProxyEndpoint() {
18591
+ const now = Date.now();
18592
+ if (cached !== void 0 && now - cachedAt < CACHE_TTL_MS) return cached;
18593
+ cachedAt = now;
18594
+ try {
18595
+ const file = proxyConfigPath();
18596
+ if (!existsSync12(file)) {
18597
+ cached = null;
18598
+ return cached;
18599
+ }
18600
+ const cfg = JSON.parse(readFileSync7(file, "utf8"));
18601
+ const host = cfg.host === void 0 ? "127.0.0.1" : typeof cfg.host === "string" ? cfg.host.trim() : "";
18602
+ const port = cfg.port === void 0 ? 1080 : Number.isInteger(cfg.port) ? cfg.port : -1;
18603
+ if (host === "" || port < 1 || port > 65535) {
18604
+ cached = null;
18605
+ return cached;
18606
+ }
18607
+ cached = { host, port };
18608
+ return cached;
18609
+ } catch {
18610
+ cached = null;
18611
+ return cached;
18612
+ }
18613
+ }
18614
+
18615
+ // src/infrastructure/browser/proxy-health.ts
18616
+ var DEFAULT_TIMEOUT_MS = 5e3;
18617
+ var DEFAULT_DATA_TIMEOUT_MS = 8e3;
18618
+ var DEFAULT_TARGET_HOST = "lite.duckduckgo.com";
18619
+ var DEFAULT_TARGET_PORT = 80;
18620
+ var NEUTRAL_TARGET_HOST = "example.com";
18621
+ var NEUTRAL_TARGET_PORT = 80;
18622
+ function fail(code, reason, endpoint, startedAt) {
18623
+ return { healthy: false, code, reason, endpoint, latencyMs: Date.now() - startedAt };
18624
+ }
18625
+ function probeSocksProxyForwarding(endpoint = getSocksProxyEndpoint(), options = {}) {
18626
+ const startedAt = Date.now();
18627
+ if (!endpoint) {
18628
+ return Promise.resolve({
18629
+ healthy: true,
18630
+ code: "not-configured",
18631
+ reason: "no SOCKS proxy configured (browser connects directly)",
18632
+ endpoint: null,
18633
+ latencyMs: 0
18634
+ });
18635
+ }
18636
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
18637
+ const dataTimeoutMs = options.dataTimeoutMs ?? DEFAULT_DATA_TIMEOUT_MS;
18638
+ const targetHost = options.targetHost ?? DEFAULT_TARGET_HOST;
18639
+ const targetPort = options.targetPort ?? DEFAULT_TARGET_PORT;
18640
+ const where = `${endpoint.host}:${endpoint.port}`;
18641
+ return new Promise((resolve9) => {
18642
+ const socket = net3.connect({ host: endpoint.host, port: endpoint.port });
18643
+ let stage = "greet";
18644
+ let settled = false;
18645
+ let buffer = Buffer.alloc(0);
18646
+ let connectTimer;
18647
+ let dataTimer;
18648
+ const onAbort = () => {
18649
+ finish(fail("aborted", "proxy probe cancelled by the caller", endpoint, startedAt));
18650
+ };
18651
+ const finish = (result) => {
18652
+ if (settled) return;
18653
+ settled = true;
18654
+ clearTimeout(connectTimer);
18655
+ clearTimeout(dataTimer);
18656
+ options.signal?.removeEventListener("abort", onAbort);
18657
+ socket.destroy();
18658
+ resolve9(result);
18659
+ };
18660
+ if (options.signal?.aborted) {
18661
+ onAbort();
18662
+ return;
18663
+ }
18664
+ options.signal?.addEventListener("abort", onAbort, { once: true });
18665
+ connectTimer = setTimeout(() => {
18666
+ finish(fail(
18667
+ stage === "greet" ? "unreachable" : "no-data",
18668
+ 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`,
18669
+ endpoint,
18670
+ startedAt
18671
+ ));
18672
+ }, timeoutMs);
18673
+ connectTimer.unref?.();
18674
+ const armDataTimer = () => {
18675
+ dataTimer = setTimeout(() => {
18676
+ finish(fail(
18677
+ "no-data",
18678
+ `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)`,
18679
+ endpoint,
18680
+ startedAt
18681
+ ));
18682
+ }, dataTimeoutMs);
18683
+ dataTimer.unref?.();
18684
+ };
18685
+ socket.on("connect", () => {
18686
+ socket.write(Buffer.from([5, 1, 0]));
18687
+ });
18688
+ socket.on("data", (chunk) => {
18689
+ if (settled) return;
18690
+ buffer = Buffer.concat([buffer, chunk]);
18691
+ if (stage === "greet") {
18692
+ if (buffer.length < 2) return;
18693
+ if (buffer[0] !== 5 || buffer[1] !== 0) {
18694
+ finish(fail(
18695
+ "protocol-error",
18696
+ `proxy at ${where} answered the SOCKS greeting with [${[...buffer.subarray(0, 2)]}] instead of [5,0]`,
18697
+ endpoint,
18698
+ startedAt
18699
+ ));
18700
+ return;
18701
+ }
18702
+ buffer = buffer.subarray(2);
18703
+ const hostBytes = Buffer.from(targetHost, "utf8");
18704
+ socket.write(Buffer.concat([
18705
+ Buffer.from([5, 1, 0, 3, hostBytes.length]),
18706
+ hostBytes,
18707
+ Buffer.from([targetPort >> 8 & 255, targetPort & 255])
18708
+ ]));
18709
+ stage = "connect";
18710
+ return;
18711
+ }
18712
+ if (stage === "connect") {
18713
+ if (buffer.length < 4) return;
18714
+ if (buffer[0] !== 5) {
18715
+ finish(fail("protocol-error", `proxy at ${where} answered the SOCKS request malformed`, endpoint, startedAt));
18716
+ return;
18717
+ }
18718
+ const reply = buffer[1];
18719
+ if (reply !== 0) {
18720
+ 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}`;
18721
+ finish(fail(
18722
+ "connect-rejected",
18723
+ `proxy at ${where} refused CONNECT to ${targetHost}:${targetPort} (${meaning})`,
18724
+ endpoint,
18725
+ startedAt
18726
+ ));
18727
+ return;
18728
+ }
18729
+ const atyp = buffer[3];
18730
+ let addrLen;
18731
+ if (atyp === 1) {
18732
+ addrLen = 4;
18733
+ } else if (atyp === 4) {
18734
+ addrLen = 16;
18735
+ } else if (atyp === 3) {
18736
+ if (buffer.length < 5) return;
18737
+ addrLen = 1 + (buffer[4] ?? 0);
18738
+ } else {
18739
+ finish(fail("protocol-error", `proxy at ${where} answered CONNECT with unknown address type ${atyp}`, endpoint, startedAt));
18740
+ return;
18741
+ }
18742
+ const replyLen = 4 + addrLen + 2;
18743
+ if (buffer.length < replyLen) return;
18744
+ buffer = buffer.subarray(replyLen);
18745
+ clearTimeout(connectTimer);
18746
+ socket.write(
18747
+ `GET / HTTP/1.0\r
18748
+ Host: ${targetHost}\r
18749
+ Connection: close\r
18750
+ \r
18751
+ `
18752
+ );
18753
+ stage = "data";
18754
+ armDataTimer();
18755
+ if (buffer.length > 0) {
18756
+ finish({
18757
+ healthy: true,
18758
+ code: "ok",
18759
+ reason: `proxy at ${where} forwards traffic (first byte in ${Date.now() - startedAt}ms)`,
18760
+ endpoint,
18761
+ latencyMs: Date.now() - startedAt
18762
+ });
18763
+ }
18764
+ return;
18765
+ }
18766
+ finish({
18767
+ healthy: true,
18768
+ code: "ok",
18769
+ reason: `proxy at ${where} forwards traffic (first byte in ${Date.now() - startedAt}ms)`,
18770
+ endpoint,
18771
+ latencyMs: Date.now() - startedAt
18772
+ });
18773
+ });
18774
+ socket.on("error", (err) => {
18775
+ const detail = err.code === "ECONNREFUSED" ? "nothing is listening there \u2014 is the proxy service running?" : err.message;
18776
+ finish(fail("unreachable", `proxy at ${where} is unusable: ${detail}`, endpoint, startedAt));
18777
+ });
18778
+ socket.on("close", () => {
18779
+ finish(fail(
18780
+ "no-data",
18781
+ `proxy at ${where} closed the tunnel before returning data`,
18782
+ endpoint,
18783
+ startedAt
18784
+ ));
18785
+ });
18786
+ });
18787
+ }
18788
+ async function describeProxyIfBroken(signal, options = {}) {
18789
+ const endpoint = getSocksProxyEndpoint();
18790
+ if (!endpoint) return null;
18791
+ const opts = {
18792
+ timeoutMs: options.timeoutMs ?? 3e3,
18793
+ dataTimeoutMs: options.dataTimeoutMs ?? 3e3,
18794
+ signal
18795
+ };
18796
+ let last = await probeSocksProxyForwarding(endpoint, opts);
18797
+ if (last.code === "aborted") return null;
18798
+ if (!last.healthy) {
18799
+ last = await probeSocksProxyForwarding(endpoint, {
18800
+ ...opts,
18801
+ dataTimeoutMs: options.dataTimeoutMs ?? 4e3
18802
+ });
18803
+ if (last.code === "aborted") return null;
18804
+ }
18805
+ if (last.healthy) return null;
18806
+ const neutral = await probeSocksProxyForwarding(endpoint, {
18807
+ ...opts,
18808
+ targetHost: NEUTRAL_TARGET_HOST,
18809
+ targetPort: NEUTRAL_TARGET_PORT
18810
+ });
18811
+ if (neutral.code === "aborted") return null;
18812
+ if (neutral.healthy) {
18813
+ 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.`;
18814
+ }
18815
+ return `SOCKS proxy check: ${last.reason}. The proxy did not forward traffic to example.com either, so the tunnel itself is broken.`;
18816
+ }
18817
+
18490
18818
  // src/web-research/browser-search.ts
18491
18819
  init_logger();
18492
18820
  init_safe_unref();
@@ -18630,8 +18958,9 @@ async function performSearch(queries, config, signal, onProgress, container = ge
18630
18958
  `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}` : "")
18631
18959
  );
18632
18960
  }
18961
+ const proxyDiagnosis = await describeProxyIfBroken(signal);
18633
18962
  throw new Error(
18634
- `Search completely failed: ${reason}. Browser workers may be unavailable, DuckDuckGo is unreachable, or the system is under extreme load.` + (sampleWorkerError ? ` Last worker error: ${sampleWorkerError}` : "")
18963
+ `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}` : "")
18635
18964
  );
18636
18965
  }
18637
18966
  const totalDuration = Date.now() - startTime;
@@ -18836,6 +19165,35 @@ function registerHealthChecks(registry, container = getServiceContainer()) {
18836
19165
  return { healthy: false, error: `Browser healthcheck failed: ${e instanceof Error ? e.message : String(e)}` };
18837
19166
  }
18838
19167
  }, { timeoutMs: Math.max(healthTimeoutMs, 15e4, getHealthCheckBudgetMs(config)), critical: true });
19168
+ registry.register("SocksProxy", async () => {
19169
+ const endpoint = getSocksProxyEndpoint();
19170
+ if (!endpoint) {
19171
+ return { healthy: true, diagnostic: { status: "not configured (browser connects directly)" } };
19172
+ }
19173
+ const probe = await probeSocksProxyForwarding(endpoint, { timeoutMs: 4e3, dataTimeoutMs: 5e3 });
19174
+ if (probe.healthy) {
19175
+ return {
19176
+ healthy: true,
19177
+ diagnostic: {
19178
+ status: `forwarding via ${endpoint.host}:${endpoint.port}`,
19179
+ firstByteMs: probe.latencyMs
19180
+ }
19181
+ };
19182
+ }
19183
+ const neutral = await probeSocksProxyForwarding(endpoint, {
19184
+ timeoutMs: 4e3,
19185
+ dataTimeoutMs: 5e3,
19186
+ targetHost: NEUTRAL_TARGET_HOST,
19187
+ targetPort: NEUTRAL_TARGET_PORT
19188
+ });
19189
+ if (neutral.healthy) {
19190
+ return {
19191
+ healthy: false,
19192
+ 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.`
19193
+ };
19194
+ }
19195
+ return { healthy: false, error: probe.reason };
19196
+ }, { timeoutMs: 25e3, critical: true });
18839
19197
  registry.register("KnowledgeStore", async (options) => {
18840
19198
  const existing = container.tryGet(ServiceNames.KNOWLEDGE_STORE);
18841
19199
  const alreadyInitialized = existing?.lifecycle === "initialized" /* INITIALIZED */;
@@ -18964,7 +19322,8 @@ function isBusyPoolHealthFailure(health) {
18964
19322
  const capabilityOk = !capability || capability.healthy !== false;
18965
19323
  const unhealthy = components.filter((c) => c.healthy === false);
18966
19324
  const isTimeout = (c) => /tim(e|ed)\s*out|timeout/i.test(String(c.error || ""));
18967
- return capabilityOk && unhealthy.length > 0 && unhealthy.every(isTimeout);
19325
+ const proxyBroken = unhealthy.some((c) => c.component === "SocksProxy");
19326
+ return capabilityOk && !proxyBroken && unhealthy.length > 0 && unhealthy.every(isTimeout);
18968
19327
  }
18969
19328
  async function runHealthCheck(options) {
18970
19329
  const container = tryGetServiceContainerFromCtx(options?.ctx);
@@ -18979,7 +19338,7 @@ async function runHealthCheck(options) {
18979
19338
  success: result.status !== "unhealthy",
18980
19339
  status: result.status,
18981
19340
  components: result.components,
18982
- error: result.status === "unhealthy" ? result.components.find((c) => !c.healthy && registry.isCritical(c.component))?.error : void 0
19341
+ error: result.status === "unhealthy" ? result.components.find((c) => !c.healthy && registry.isCritical(c.component ?? ""))?.error : void 0
18983
19342
  };
18984
19343
  }
18985
19344
 
@@ -18991,80 +19350,6 @@ init_config();
18991
19350
  // src/orchestration/researcher.ts
18992
19351
  import { createAgentSession, SessionManager, SettingsManager as SettingsManagerClass } from "@earendil-works/pi-coding-agent";
18993
19352
 
18994
- // src/tools/read-guard.ts
18995
- import { constants as constants2 } from "node:fs";
18996
- import { access as access3, open as open5, readFile as readFile7, realpath as realpath2 } from "node:fs/promises";
18997
- import { homedir as homedir6 } from "node:os";
18998
- import { basename as basename5, dirname as dirname13, relative, isAbsolute as isAbsolute3, parse, sep as sep2 } from "node:path";
18999
- var DENIED_SEGMENTS = /* @__PURE__ */ new Set([".ssh", ".aws", ".gnupg", ".git", ".kube", ".docker", ".azure", ".gcloud", ".terraform"]);
19000
- 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)$/;
19001
- var ALLOWED_ENV_TEMPLATE = /^\.env\.(example|sample|template|dist)$/;
19002
- function normalizeName(name) {
19003
- return name.toLowerCase().replace(/:.*$/, "").replace(/[. ]+$/, "");
19004
- }
19005
- var ReadDeniedError = class extends Error {
19006
- constructor(reason) {
19007
- super(`read denied: ${reason}`);
19008
- this.name = "ReadDeniedError";
19009
- }
19010
- };
19011
- async function resolveReal(p) {
19012
- try {
19013
- return await realpath2(p);
19014
- } catch {
19015
- const parent = dirname13(p);
19016
- if (parent === p) return p;
19017
- return `${await resolveReal(parent)}${sep2}${basename5(p)}`;
19018
- }
19019
- }
19020
- function isWithin(root, target) {
19021
- const rel = relative(root, target);
19022
- return rel === "" || rel !== ".." && !rel.startsWith(`..${sep2}`) && !isAbsolute3(rel);
19023
- }
19024
- async function assertReadAllowed(cwd, absolutePath) {
19025
- const root = await resolveReal(cwd);
19026
- const home = await resolveReal(homedir6());
19027
- if (root === parse(root).root || isWithin(root, home)) {
19028
- throw new ReadDeniedError("the working directory is a home or filesystem root, not a project directory");
19029
- }
19030
- const target = await resolveReal(absolutePath);
19031
- if (!isWithin(root, target)) {
19032
- throw new ReadDeniedError("path is outside the project directory");
19033
- }
19034
- const segments = relative(root, target).split(sep2);
19035
- if (segments.some((s) => DENIED_SEGMENTS.has(s.toLowerCase()))) {
19036
- throw new ReadDeniedError("path is inside a credential or VCS-internals directory");
19037
- }
19038
- const name = normalizeName(basename5(target));
19039
- if (!ALLOWED_ENV_TEMPLATE.test(name) && DENIED_BASENAME.test(name)) {
19040
- throw new ReadDeniedError("file looks like a credential or secret");
19041
- }
19042
- }
19043
- function createGuardedReadOperations(cwd) {
19044
- return {
19045
- access: async (p) => {
19046
- await assertReadAllowed(cwd, p);
19047
- await access3(p, constants2.R_OK);
19048
- },
19049
- readFile: async (p) => {
19050
- await assertReadAllowed(cwd, p);
19051
- const handle = await open5(p, constants2.O_RDONLY | constants2.O_NOFOLLOW);
19052
- try {
19053
- const stat6 = await handle.stat();
19054
- if (!stat6.isFile()) {
19055
- throw new ReadDeniedError("path is not a regular file");
19056
- }
19057
- return await readFile7(handle);
19058
- } finally {
19059
- await handle.close();
19060
- }
19061
- }
19062
- };
19063
- }
19064
-
19065
- // src/tools/index.ts
19066
- import { createReadToolDefinition } from "@earendil-works/pi-coding-agent";
19067
-
19068
19353
  // src/tools/search.ts
19069
19354
  import { Type as Type4 } from "typebox";
19070
19355
  import { Value as Value5 } from "typebox/value";
@@ -19306,7 +19591,7 @@ init_metrics();
19306
19591
  init_logger();
19307
19592
  import * as dns from "node:dns/promises";
19308
19593
  import * as dnsCb from "node:dns";
19309
- import * as net3 from "node:net";
19594
+ import * as net4 from "node:net";
19310
19595
  import crypto9 from "node:crypto";
19311
19596
  import { NodeHtmlMarkdown } from "node-html-markdown";
19312
19597
  function getRandomUserAgent() {
@@ -19339,7 +19624,7 @@ function validateUrlForSSRFSync(url) {
19339
19624
  throw new Error("Only HTTP/HTTPS protocols are allowed");
19340
19625
  }
19341
19626
  if (process.env["PI_RESEARCH_ALLOW_LOOPBACK_SCRAPE"] === "true") {
19342
- const isLoopback = hostname === "localhost" || hostname.endsWith(".localhost") || /^127\./.test(hostname) || hostname === "::1" || net3.isIPv6(hostname) && isPrivateIpv6(hostname) && isMappedLoopback(hostname);
19627
+ const isLoopback = hostname === "localhost" || hostname.endsWith(".localhost") || /^127\./.test(hostname) || hostname === "::1" || net4.isIPv6(hostname) && isPrivateIpv6(hostname) && isMappedLoopback(hostname);
19343
19628
  if (isLoopback) return true;
19344
19629
  }
19345
19630
  if (hostname === "localhost" || hostname.endsWith(".localhost")) {
@@ -19352,7 +19637,7 @@ function validateUrlForSSRFSync(url) {
19352
19637
  throw new Error("Access to internal networks is not allowed");
19353
19638
  }
19354
19639
  }
19355
- const literalKind = net3.isIP(hostname);
19640
+ const literalKind = net4.isIP(hostname);
19356
19641
  if (literalKind === 4 && isPrivateIp(hostname)) {
19357
19642
  metrics.increment("scrape_ssrf_blocks_total", 1, { block_type: "ip_literal_v4" });
19358
19643
  throw new Error("Access to private/reserved IPv4 address is not allowed");
@@ -19425,6 +19710,9 @@ function getSsrfSafeFetcher() {
19425
19710
  const { Agent: Agent2, fetch: undiciFetch } = await import("undici");
19426
19711
  return {
19427
19712
  fetch: undiciFetch,
19713
+ // node:net's LookupFunction pins the callback to `string | LookupAddress[]`
19714
+ // (no undefined); the wrapper's callback allows undefined for the single
19715
+ // resolution, so the two signatures differ by exactly that — a double cast.
19428
19716
  dispatcher: new Agent2({ connect: { lookup: ssrfSafeLookup } })
19429
19717
  };
19430
19718
  } catch (e) {
@@ -19438,8 +19726,8 @@ async function disposeSsrfSafeFetcher() {
19438
19726
  const pending = cachedSsrfFetcher;
19439
19727
  cachedSsrfFetcher = void 0;
19440
19728
  if (pending === void 0) return;
19441
- const cached = await pending.catch(() => null);
19442
- const closable = cached?.dispatcher;
19729
+ const cached2 = await pending.catch(() => null);
19730
+ const closable = cached2?.dispatcher;
19443
19731
  if (!closable?.close) return;
19444
19732
  try {
19445
19733
  await closable.close();
@@ -19654,11 +19942,11 @@ init_service_registry();
19654
19942
  init_logger();
19655
19943
  init_metrics();
19656
19944
  init_error_tracker();
19657
- import { existsSync as existsSync12 } from "node:fs";
19658
- import { dirname as dirname14, join as join21 } from "node:path";
19945
+ import { existsSync as existsSync13 } from "node:fs";
19946
+ import { dirname as dirname13, join as join21 } from "node:path";
19659
19947
  import { fileURLToPath as fileURLToPath4 } from "node:url";
19660
19948
  import { Worker } from "node:worker_threads";
19661
- var MODULE_DIR = dirname14(fileURLToPath4(import.meta.url));
19949
+ var MODULE_DIR = dirname13(fileURLToPath4(import.meta.url));
19662
19950
  var PdfExtractError = class extends Error {
19663
19951
  kind;
19664
19952
  constructor(kind, message, options) {
@@ -19727,7 +20015,7 @@ var pendingRequests = /* @__PURE__ */ new Map();
19727
20015
  var warnedWorkerUnavailable = false;
19728
20016
  function resolveWorkerPath() {
19729
20017
  const candidate = join21(MODULE_DIR, WORKER_FILENAME);
19730
- return existsSync12(candidate) ? candidate : null;
20018
+ return existsSync13(candidate) ? candidate : null;
19731
20019
  }
19732
20020
  function pdfWorkerEnabled() {
19733
20021
  if (process.env["PI_RESEARCH_PDF_WORKER"] === "off") return false;
@@ -20096,7 +20384,16 @@ async function scrapeWithStealthBrowser(_url, config, signal, sessionId, contain
20096
20384
  const result = await runBrowserTask({ url: _url, sessionId }, "scrape", config, signal, 1, container);
20097
20385
  const browserDuration = Date.now() - browserStart;
20098
20386
  const legacyBuffer = result.buffer;
20099
- const pdfBytes = typeof result.bufferB64 === "string" ? Buffer.from(result.bufferB64, "base64") : Array.isArray(legacyBuffer?.data) ? Buffer.from(legacyBuffer.data) : legacyBuffer instanceof Uint8Array ? Buffer.from(legacyBuffer) : null;
20387
+ let pdfBytes;
20388
+ if (typeof result.bufferB64 === "string") {
20389
+ pdfBytes = Buffer.from(result.bufferB64, "base64");
20390
+ } else if (legacyBuffer && !(legacyBuffer instanceof Uint8Array) && Array.isArray(legacyBuffer.data)) {
20391
+ pdfBytes = Buffer.from(legacyBuffer.data);
20392
+ } else if (legacyBuffer instanceof Uint8Array) {
20393
+ pdfBytes = Buffer.from(legacyBuffer);
20394
+ } else {
20395
+ pdfBytes = null;
20396
+ }
20100
20397
  if (pdfBytes !== null) {
20101
20398
  const markdown2 = await extractPdfToMarkdown(pdfBytes);
20102
20399
  validateContent("", markdown2, _url);
@@ -23311,6 +23608,75 @@ Failed to query Stack Exchange. This may be due to API rate limiting (300/day an
23311
23608
  init_constants();
23312
23609
  import { createGrepToolDefinition } from "@earendil-works/pi-coding-agent";
23313
23610
  import { Value as Value9 } from "typebox/value";
23611
+ import { resolve as resolvePath, isAbsolute as isAbsolute4 } from "node:path";
23612
+
23613
+ // src/tools/read-guard.ts
23614
+ import { access as access3, open as open5, readFile as readFile7, realpath as realpath2 } from "node:fs/promises";
23615
+ import { homedir as homedir7 } from "node:os";
23616
+ import { basename as basename5, dirname as dirname14, relative, isAbsolute as isAbsolute3, parse, sep as sep2 } from "node:path";
23617
+ var DENIED_SEGMENTS = /* @__PURE__ */ new Set([".ssh", ".aws", ".gnupg", ".git", ".kube", ".docker", ".azure", ".gcloud", ".terraform"]);
23618
+ 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)$/;
23619
+ var ALLOWED_ENV_TEMPLATE = /^\.env\.(example|sample|template|dist)$/;
23620
+ function normalizeName(name) {
23621
+ return name.toLowerCase().replace(/:.*$/, "").replace(/[. ]+$/, "");
23622
+ }
23623
+ var ReadDeniedError = class extends Error {
23624
+ constructor(reason) {
23625
+ super(`read denied: ${reason}`);
23626
+ this.name = "ReadDeniedError";
23627
+ }
23628
+ };
23629
+ async function resolveReal(p) {
23630
+ try {
23631
+ return await realpath2(p);
23632
+ } catch {
23633
+ const parent = dirname14(p);
23634
+ if (parent === p) return p;
23635
+ return `${await resolveReal(parent)}${sep2}${basename5(p)}`;
23636
+ }
23637
+ }
23638
+ function isWithin(root, target) {
23639
+ const rel = relative(root, target);
23640
+ return rel === "" || rel !== ".." && !rel.startsWith(`..${sep2}`) && !isAbsolute3(rel);
23641
+ }
23642
+ async function assertReadAllowed(cwd, absolutePath) {
23643
+ const root = await resolveReal(cwd);
23644
+ const home = await resolveReal(homedir7());
23645
+ if (root === parse(root).root || isWithin(root, home)) {
23646
+ throw new ReadDeniedError("the working directory is a home or filesystem root, not a project directory");
23647
+ }
23648
+ const target = await resolveReal(absolutePath);
23649
+ if (!isWithin(root, target)) {
23650
+ throw new ReadDeniedError("path is outside the project directory");
23651
+ }
23652
+ const segments = relative(root, target).split(sep2);
23653
+ if (segments.some((s) => DENIED_SEGMENTS.has(s.toLowerCase()))) {
23654
+ throw new ReadDeniedError("path is inside a credential or VCS-internals directory");
23655
+ }
23656
+ const name = normalizeName(basename5(target));
23657
+ if (!ALLOWED_ENV_TEMPLATE.test(name) && DENIED_BASENAME.test(name)) {
23658
+ throw new ReadDeniedError("file looks like a credential or secret");
23659
+ }
23660
+ }
23661
+ function isDeniedPathName(name) {
23662
+ const segments = name.split(sep2);
23663
+ if (segments.some((s) => DENIED_SEGMENTS.has(s.toLowerCase()))) return true;
23664
+ const base = normalizeName(basename5(name));
23665
+ return !ALLOWED_ENV_TEMPLATE.test(base) && DENIED_BASENAME.test(base);
23666
+ }
23667
+
23668
+ // src/tools/grep.ts
23669
+ function filterDeniedLines(text) {
23670
+ const lines = text.split("\n");
23671
+ const kept = [];
23672
+ for (const line of lines) {
23673
+ const m = line.match(/^(.+?):\d+: /) ?? line.match(/^(.+?)-\d+- /);
23674
+ const prefix = m?.[1];
23675
+ if (prefix && isDeniedPathName(prefix)) continue;
23676
+ kept.push(line);
23677
+ }
23678
+ return kept.join("\n");
23679
+ }
23314
23680
  function createGrepTool(options) {
23315
23681
  const cwd = options.cwd ?? process.cwd();
23316
23682
  const sdkGrep = createGrepToolDefinition(cwd);
@@ -23319,7 +23685,7 @@ function createGrepTool(options) {
23319
23685
  ...sdkGrep,
23320
23686
  label: "Code Search",
23321
23687
  promptGuidelines: [
23322
- "Available for fast recursive text search in codebases.",
23688
+ "Available for fast recursive text search in the local project directory (nothing outside it; credential files and directories are refused).",
23323
23689
  'Pattern supports regex. Use glob to scope to file types (e.g., "**/*.ts").',
23324
23690
  "Options: ignoreCase, literal (disable regex), context (lines around match), limit (max matches).",
23325
23691
  `Local code search \u2014 it does NOT consume your web-gathering budget (limit: ${MAX_GREP_CALLS} calls).`
@@ -23337,8 +23703,24 @@ function createGrepTool(options) {
23337
23703
  details: { blocked: true, reason: "limit_reached" }
23338
23704
  };
23339
23705
  }
23706
+ const searchDir = params.path ?? ".";
23707
+ const searchPath = isAbsolute4(searchDir) ? searchDir : resolvePath(cwd, searchDir);
23340
23708
  try {
23341
- return await sdkExecute(toolCallId, params, signal, onUpdate, ctx);
23709
+ await assertReadAllowed(cwd, searchPath);
23710
+ } catch (err) {
23711
+ const msg2 = err instanceof ReadDeniedError ? err.message : `read denied: ${String(err)}`;
23712
+ return {
23713
+ content: [{ type: "text", text: `Grep refused: ${msg2}` }],
23714
+ details: { error: "denied_path" }
23715
+ };
23716
+ }
23717
+ try {
23718
+ const result = await sdkExecute(toolCallId, params, signal, onUpdate, ctx);
23719
+ const content = result.content;
23720
+ for (const block of content) {
23721
+ if (block.type === "text") block.text = filterDeniedLines(block.text);
23722
+ }
23723
+ return result;
23342
23724
  } catch (err) {
23343
23725
  const msg2 = err instanceof Error ? err.message : String(err);
23344
23726
  return {
@@ -24055,7 +24437,6 @@ function createResearchTools(options) {
24055
24437
  })
24056
24438
  };
24057
24439
  return [
24058
- createReadToolDefinition(options.cwd, { operations: createGuardedReadOperations(options.cwd) }),
24059
24440
  createSearchTool({
24060
24441
  ...resolvedOptions,
24061
24442
  onProgress: options.onSearchProgress,
@@ -24320,12 +24701,13 @@ async function createResearcherSession(options) {
24320
24701
  maxScrapeUrls,
24321
24702
  getTokensUsed: () => {
24322
24703
  if (!sessionRef.session) return 0;
24323
- if (typeof sessionRef.session.getContextUsage === "function") {
24324
- const usage = sessionRef.session.getContextUsage();
24704
+ const usageSession = sessionRef.session;
24705
+ if (typeof usageSession?.getContextUsage === "function") {
24706
+ const usage = usageSession.getContextUsage();
24325
24707
  if (usage && typeof usage.tokens === "number") return usage.tokens;
24326
24708
  }
24327
- if (typeof sessionRef.session.getUsage === "function") {
24328
- const usage = sessionRef.session.getUsage();
24709
+ if (typeof usageSession?.getUsage === "function") {
24710
+ const usage = usageSession.getUsage();
24329
24711
  return (usage.input || 0) + (usage.output || 0) + (usage.cacheRead || 0) + (usage.cacheWrite || 0);
24330
24712
  }
24331
24713
  return 0;
@@ -24775,6 +25157,7 @@ ${effectiveInitialLinks.map((l) => `- ${l}`).join("\n")}`;
24775
25157
  const deliveredSteeringIds = /* @__PURE__ */ new Set();
24776
25158
  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();
24777
25159
  let inFlightBackoffMs = null;
25160
+ let capacityWaitSpentMs = 0;
24778
25161
  for (let attempt = 1; attempt <= maxAttempts; attempt++) {
24779
25162
  if (signal?.aborted) throw new Error("Aborted");
24780
25163
  if (stopRequested()) {
@@ -24992,7 +25375,10 @@ ${responseText}`);
24992
25375
  continue;
24993
25376
  }
24994
25377
  const synthesisService = await getService(ServiceNames.RESEARCH_SYNTHESIS_SERVICE, ctx, container);
24995
- synthesisService.storeReport(researchId, `${round}.${id}`, responseText);
25378
+ const report = extractToolResults(session);
25379
+ const { digest: rawDigest } = splitCoverageDigest(responseText);
25380
+ const digest = rawDigest || buildFallbackDigest(researcherConfig.goal, successfulScrapeCount);
25381
+ synthesisService.storeReport(researchId, `${round}.${id}`, report, digest);
24996
25382
  observer?.onResearcherComplete?.(id, synthesisService.getReport(researchId, `${round}.${id}`) ?? responseText);
24997
25383
  return;
24998
25384
  } catch (err) {
@@ -25009,7 +25395,10 @@ ${responseText}`);
25009
25395
  const ungrounded = scrapeEnabled && successfulScrapeCount === 0 && nonScrapeGroundingHits === 0 && historicalUrls.length === 0;
25010
25396
  if (partialResponse && partialResponse.trim().length > 50 && !ungrounded) {
25011
25397
  const synthesisService = await getService(ServiceNames.RESEARCH_SYNTHESIS_SERVICE, ctx, container);
25012
- synthesisService.storeReport(researchId, `${round}.${id}`, partialResponse + "\n\n---\n*WARNING: This report was truncated due to a timeout/error. Content may be incomplete.*");
25398
+ const report = extractToolResults(session) + "\n\n---\n*WARNING: This report was truncated due to a timeout/error. Content may be incomplete.*";
25399
+ const { digest: rawDigest } = splitCoverageDigest(partialResponse);
25400
+ const digest = rawDigest || buildFallbackDigest(researcherConfig.goal, successfulScrapeCount);
25401
+ synthesisService.storeReport(researchId, `${round}.${id}`, report, digest);
25013
25402
  logger.log(`[ResearcherExecutor] Researcher ${id} salvaged partial content (${partialResponse.length} chars) after error: ${errMsg}`);
25014
25403
  observer?.onResearcherComplete?.(id, synthesisService.getReport(researchId, `${round}.${id}`) ?? partialResponse);
25015
25404
  return;
@@ -25036,6 +25425,20 @@ ${responseText}`);
25036
25425
  metrics.increment("researcher_rate_limit_backoff_total", 1, { mode: "deep", complexity: String(complexity) });
25037
25426
  logger.warn(`[ResearcherExecutor] Researcher ${id} hit a provider rate limit; backing off ${inFlightBackoffMs}ms before attempt ${attempt + 1}`);
25038
25427
  }
25428
+ if (inFlightBackoffMs !== null) {
25429
+ const remainingBudgetMs = RATE_LIMIT_TOTAL_WAIT_MAX_MS - capacityWaitSpentMs;
25430
+ if (inFlightBackoffMs > remainingBudgetMs) {
25431
+ const windowSeconds = Math.ceil(inFlightBackoffMs / 1e3);
25432
+ const retryAt = new Date(Date.now() + inFlightBackoffMs).toISOString().slice(11, 19);
25433
+ lastError = new Error(
25434
+ `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}`
25435
+ );
25436
+ logger.error(`[ResearcherExecutor] Researcher ${id} stopping instead of waiting ${inFlightBackoffMs}ms (capacity budget exhausted); rerun after ${retryAt}Z`);
25437
+ metrics.increment("researcher_capacity_budget_exhausted_total", 1, { mode: "deep", complexity: String(complexity) });
25438
+ break;
25439
+ }
25440
+ capacityWaitSpentMs += inFlightBackoffMs;
25441
+ }
25039
25442
  }
25040
25443
  if (attempt < maxAttempts) {
25041
25444
  logger.warn(`[ResearcherExecutor] Researcher ${id} attempt ${attempt} failed: ${errMsg}; will retry`);
@@ -25702,6 +26105,13 @@ var DeepResearchOrchestrator = class {
25702
26105
  const orchestrationService = await this.getOrchestrationService();
25703
26106
  const planningService = await this.getPlanningService();
25704
26107
  await orchestrationService.cleanupResearchServices(void 0, researchId, ctx, this.config);
26108
+ const proxyDiagnosis = await describeProxyIfBroken(signal);
26109
+ if (signal?.aborted) return "";
26110
+ if (proxyDiagnosis) {
26111
+ throw new Error(
26112
+ `Research cannot start: ${proxyDiagnosis} Repair or remove ~/.pi/research/proxy.json (docs/TROUBLESHOOTING.md), then rerun.`
26113
+ );
26114
+ }
25705
26115
  logger.log(`[DeepOrchestrator] Starting multi-round research (complexity ${complexity}) for: "${query}" (Run: ${researchId})`);
25706
26116
  metrics.increment("research_sessions_total", 1, { mode: "deep", complexity: String(complexity) });
25707
26117
  observer?.onStart?.(query, complexity);
@@ -25949,6 +26359,9 @@ var DeepResearchOrchestrator = class {
25949
26359
  const hasReports = synthesisCheckService.hasReports(researchId);
25950
26360
  const failedIds = getFailedResearchers(this.options.sessionId, researchId);
25951
26361
  if (!hasReports && failedIds.length > 0) {
26362
+ if (hasOnlyCapacityFailures(this.options.sessionId, researchId)) {
26363
+ throw createResearchStopError(this.options.sessionId, researchId);
26364
+ }
25952
26365
  const reasons = getResearcherFailureReasons(this.options.sessionId, researchId);
25953
26366
  const causes = failedIds.map((id) => `researcher ${id}: ${reasons[id] ?? "no usable report"}`).join("; ");
25954
26367
  throw new Error(
@@ -26798,16 +27211,18 @@ var ResearchSynthesisService = class _ResearchSynthesisService {
26798
27211
  * @param id - Report identifier (typically "round.researcherId")
26799
27212
  * @param report - The researcher's report content
26800
27213
  */
26801
- storeReport(sessionId, id, report) {
26802
- const { digest, body } = splitCoverageDigest(report);
27214
+ storeReport(sessionId, id, report, digest) {
27215
+ const explicit = digest?.trim();
27216
+ const { digest: splitDigest, body } = explicit ? { digest: "", body: report } : splitCoverageDigest(report);
27217
+ const finalDigest = explicit || splitDigest;
26803
27218
  this.getSessionReports(sessionId).set(id, body);
26804
27219
  let sessionDigests = this.digests.get(sessionId);
26805
- if (digest) {
27220
+ if (finalDigest) {
26806
27221
  if (!sessionDigests) {
26807
27222
  sessionDigests = /* @__PURE__ */ new Map();
26808
27223
  this.digests.set(sessionId, sessionDigests);
26809
27224
  }
26810
- sessionDigests.set(id, digest);
27225
+ sessionDigests.set(id, finalDigest);
26811
27226
  } else if (sessionDigests) {
26812
27227
  sessionDigests.delete(id);
26813
27228
  if (sessionDigests.size === 0) this.digests.delete(sessionId);
@@ -27804,7 +28219,7 @@ init_url_utils();
27804
28219
  init_logger();
27805
28220
  init_constants();
27806
28221
  import { promises as fs16 } from "node:fs";
27807
- import { homedir as homedir7, tmpdir as tmpdir4, platform as platform4 } from "node:os";
28222
+ import { homedir as homedir8, tmpdir as tmpdir4, platform as platform4 } from "node:os";
27808
28223
  import { join as join22, resolve as resolve5, normalize, sep as sep3 } from "node:path";
27809
28224
  import { randomBytes as randomBytes6 } from "node:crypto";
27810
28225
  var PREFERRED_SUBDIRS = [
@@ -27847,7 +28262,7 @@ var WIN_SYSTEM_PREFIXES_LC = [
27847
28262
  ];
27848
28263
  function isSafeToWriteDirectly(dir) {
27849
28264
  const normalized = normalize(resolve5(dir));
27850
- const home = normalize(resolve5(homedir7()));
28265
+ const home = normalize(resolve5(homedir8()));
27851
28266
  if (normalized === home) return false;
27852
28267
  if (platform4() === "win32") {
27853
28268
  if (/^[a-zA-Z]:\\?$/.test(normalized)) return false;
@@ -28016,40 +28431,41 @@ function makeProgressObserver() {
28016
28431
  return {
28017
28432
  enableLogging: false,
28018
28433
  onProgress: (event, data) => {
28434
+ const d = data;
28019
28435
  switch (event) {
28020
28436
  case "planning_success":
28021
- toStderr(` \u2022 plan: ${data?.plan?.researchers?.length ?? "?"} researcher(s)
28437
+ toStderr(` \u2022 plan: ${d?.plan?.researchers?.length ?? "?"} researcher(s)
28022
28438
  `);
28023
28439
  break;
28024
28440
  case "run_queued":
28025
28441
  toStderr(
28026
- ` \u2022 queued: ${data?.slots ?? "?"} concurrent run(s) already active \u2014 waiting up to ${Math.round((data?.maxWaitMs ?? 0) / 1e3)}s for a slot\u2026
28442
+ ` \u2022 queued: ${d?.slots ?? "?"} concurrent run(s) already active \u2014 waiting up to ${Math.round((d?.maxWaitMs ?? 0) / 1e3)}s for a slot\u2026
28027
28443
  `
28028
28444
  );
28029
28445
  break;
28030
28446
  case "round_start":
28031
- toStderr(` \u2022 round ${data?.round}
28447
+ toStderr(` \u2022 round ${d?.round}
28032
28448
  `);
28033
28449
  break;
28034
28450
  case "search_start":
28035
- toStderr(` \u2022 search burst: ${data?.queries?.length ?? 0} ${(data?.queries?.length ?? 0) === 1 ? "query" : "queries"}
28451
+ toStderr(` \u2022 search burst: ${d?.queries?.length ?? 0} ${(d?.queries?.length ?? 0) === 1 ? "query" : "queries"}
28036
28452
  `);
28037
28453
  break;
28038
28454
  case "researcher_start":
28039
- toStderr(` \u2022 researcher ${data?.id}: ${data?.name}
28455
+ toStderr(` \u2022 researcher ${d?.id}: ${d?.name}
28040
28456
  `);
28041
28457
  break;
28042
28458
  case "researcher_failure":
28043
- toStderr(` \u2022 researcher ${data?.id} failed: ${data?.error}
28459
+ toStderr(` \u2022 researcher ${d?.id} failed: ${d?.error}
28044
28460
  `);
28045
28461
  break;
28046
28462
  case "evaluation_decision":
28047
- toStderr(` \u2022 evaluator: ${data?.action}
28463
+ toStderr(` \u2022 evaluator: ${d?.action}
28048
28464
  `);
28049
28465
  break;
28050
28466
  case "tokens_consumed": {
28051
- const consumed = Number(data?.tokens ?? 0);
28052
- const costVal = typeof data?.cost === "number" ? data.cost : void 0;
28467
+ const consumed = Number(d?.tokens ?? 0);
28468
+ const costVal = typeof d?.cost === "number" ? d.cost : void 0;
28053
28469
  if (consumed > 0 || costVal !== void 0) {
28054
28470
  const costPart = costVal === void 0 ? "" : ` ($${costVal.toFixed(4)})`;
28055
28471
  toStderr(` \u2022 tokens: ${consumed}${costPart}
@@ -28058,9 +28474,9 @@ function makeProgressObserver() {
28058
28474
  break;
28059
28475
  }
28060
28476
  case "complete": {
28061
- toStderr(` \u2022 complete (${data?.result?.length ?? 0} chars)
28477
+ toStderr(` \u2022 complete (${d?.result?.length ?? 0} chars)
28062
28478
  `);
28063
- const reportText = typeof data?.result === "string" ? data.result : "";
28479
+ const reportText = typeof d?.result === "string" ? d.result : "";
28064
28480
  if (reportText.includes("No web sources were successfully retrieved") || reportText.includes("None of the links above could be verified")) {
28065
28481
  toStderr(" \u2022 WARNING: no web sources could be retrieved \u2014 the report is unverified\n");
28066
28482
  } else if (reportText.includes("Grounding notice: only")) {
@@ -28069,7 +28485,7 @@ function makeProgressObserver() {
28069
28485
  break;
28070
28486
  }
28071
28487
  case "error":
28072
- toStderr(` \u2022 error: ${data?.message}
28488
+ toStderr(` \u2022 error: ${d?.message}
28073
28489
  `);
28074
28490
  break;
28075
28491
  default: