@lincoln504/pi-research 1.7.21 → 1.7.23

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (32) hide show
  1. package/agent-skill/pi-research/SKILL.md +1 -1
  2. package/dist/cli.mjs +399 -163
  3. package/dist/thread-worker.mjs +77 -31
  4. package/docs/CHANGELOG.md +46 -0
  5. package/docs/CONFIGURATION.md +8 -3
  6. package/docs/THIRD-PARTY-NOTICES.md +29 -13
  7. package/docs/TROUBLESHOOTING.md +16 -0
  8. package/package.json +12 -9
  9. package/scripts/ddg-socks-proxy.mjs +279 -0
  10. package/scripts/lib/npm-cmd.cjs +66 -0
  11. package/scripts/lib/private-addresses.mjs +143 -0
  12. package/src/config.ts +75 -2
  13. package/src/core/interfaces/steering-interfaces.ts +11 -0
  14. package/src/core/llm/coordinator-model.ts +104 -0
  15. package/src/core/planning-service.ts +24 -0
  16. package/src/index.ts +7 -1
  17. package/src/infrastructure/browser/proxy-prefs.ts +124 -0
  18. package/src/infrastructure/browser/thread-worker-browser.ts +5 -21
  19. package/src/infrastructure/browser/thread-worker-messaging.ts +9 -4
  20. package/src/infrastructure/browser/thread-worker.mjs +77 -31
  21. package/src/knowledge/embedder-utils.ts +1 -1
  22. package/src/knowledge/sql-utils.ts +15 -0
  23. package/src/knowledge/store-operations.ts +3 -2
  24. package/src/knowledge/store.ts +15 -14
  25. package/src/orchestration/deep-research-orchestrator.ts +71 -2
  26. package/src/orchestration/research-synthesis-service.ts +14 -1
  27. package/src/orchestration/researcher-executor.ts +33 -33
  28. package/src/orchestration/session-state.ts +155 -7
  29. package/src/tools/read-guard.ts +23 -4
  30. package/src/tui/tui-controller.ts +25 -1
  31. package/src/utils/provider-errors.ts +149 -0
  32. package/src/web-research/retry-utils.ts +22 -3
package/dist/cli.mjs CHANGED
@@ -1658,104 +1658,6 @@ var init_safe_unref = __esm({
1658
1658
  }
1659
1659
  });
1660
1660
 
1661
- // src/core/llm/pi-ai-completion.ts
1662
- import { completeSimple } from "@earendil-works/pi-ai/compat";
1663
- var init_pi_ai_completion = __esm({
1664
- "src/core/llm/pi-ai-completion.ts"() {
1665
- "use strict";
1666
- }
1667
- });
1668
-
1669
- // src/core/llm/prompts.ts
1670
- import { readFileSync } from "node:fs";
1671
- import { join as join3, dirname as dirname2 } from "node:path";
1672
- import { fileURLToPath } from "node:url";
1673
- function loadPrompt(name) {
1674
- if (typeof name !== "string" || !/^[A-Za-z0-9._-]+$/.test(name) || name.includes("..")) {
1675
- logger.error(`[prompts] Rejected unsafe prompt name: ${JSON.stringify(name)}`);
1676
- throw new Error(`[prompts] Rejected unsafe prompt name: ${JSON.stringify(name)}`);
1677
- }
1678
- for (const dir of PROMPT_CANDIDATES) {
1679
- try {
1680
- return readFileSync(join3(dir, `${name}.md`), "utf-8");
1681
- } catch {
1682
- }
1683
- }
1684
- logger.error(`[prompts] Failed to load prompt: ${name} (searched: ${PROMPT_CANDIDATES.join(", ")})`);
1685
- throw new Error(`[prompts] Failed to load prompt "${name}" (searched: ${PROMPT_CANDIDATES.join(", ")})`);
1686
- }
1687
- var __filename2, CORE_LLM_DIR, PROMPT_CANDIDATES;
1688
- var init_prompts = __esm({
1689
- "src/core/llm/prompts.ts"() {
1690
- "use strict";
1691
- init_logger();
1692
- __filename2 = fileURLToPath(import.meta.url);
1693
- CORE_LLM_DIR = dirname2(__filename2);
1694
- PROMPT_CANDIDATES = [
1695
- join3(CORE_LLM_DIR, "../../prompts"),
1696
- // source tree
1697
- join3(CORE_LLM_DIR, "prompts")
1698
- // bundled CLI (dist/prompts/)
1699
- ];
1700
- }
1701
- });
1702
-
1703
- // src/types/llm.ts
1704
- import { calculateCost } from "@earendil-works/pi-ai";
1705
- function parseTokenUsage(usage) {
1706
- if (!usage || typeof usage !== "object") {
1707
- return {};
1708
- }
1709
- const obj = usage;
1710
- const result = {};
1711
- if (typeof obj["input"] === "number") {
1712
- result.input = obj["input"];
1713
- }
1714
- if (typeof obj["output"] === "number") {
1715
- result.output = obj["output"];
1716
- }
1717
- if (typeof obj["cacheRead"] === "number") {
1718
- result.cacheRead = obj["cacheRead"];
1719
- }
1720
- if (typeof obj["cacheWrite"] === "number") {
1721
- result.cacheWrite = obj["cacheWrite"];
1722
- }
1723
- if (typeof obj["totalTokens"] === "number") {
1724
- result.totalTokens = obj["totalTokens"];
1725
- }
1726
- if (obj["cost"] && typeof obj["cost"] === "object") {
1727
- result.cost = obj["cost"];
1728
- }
1729
- return result;
1730
- }
1731
- function calculateTotalTokens(usage) {
1732
- if (usage.totalTokens !== void 0) {
1733
- return usage.totalTokens;
1734
- }
1735
- return (usage.input ?? 0) + (usage.output ?? 0) + (usage.cacheRead ?? 0) + (usage.cacheWrite ?? 0);
1736
- }
1737
- function extractUsage(model, rawUsage) {
1738
- if (!rawUsage) {
1739
- return { tokens: 0, cost: 0, parsed: {} };
1740
- }
1741
- const parsed = parseTokenUsage(rawUsage);
1742
- const tokens = calculateTotalTokens(parsed);
1743
- let cost = parsed.cost?.total ?? rawUsage.cost?.total ?? 0;
1744
- if (cost === 0 && tokens > 0) {
1745
- try {
1746
- const calculatedCost = calculateCost(model, rawUsage);
1747
- cost = calculatedCost.total;
1748
- } catch {
1749
- }
1750
- }
1751
- return { tokens, cost, parsed };
1752
- }
1753
- var init_llm = __esm({
1754
- "src/types/llm.ts"() {
1755
- "use strict";
1756
- }
1757
- });
1758
-
1759
1661
  // src/utils/metrics.ts
1760
1662
  import { AsyncLocalStorage as AsyncLocalStorage5 } from "node:async_hooks";
1761
1663
  function runWithRunRegistry(registry, fn) {
@@ -1951,6 +1853,104 @@ var init_metrics = __esm({
1951
1853
  }
1952
1854
  });
1953
1855
 
1856
+ // src/core/llm/pi-ai-completion.ts
1857
+ import { completeSimple } from "@earendil-works/pi-ai/compat";
1858
+ var init_pi_ai_completion = __esm({
1859
+ "src/core/llm/pi-ai-completion.ts"() {
1860
+ "use strict";
1861
+ }
1862
+ });
1863
+
1864
+ // src/core/llm/prompts.ts
1865
+ import { readFileSync } from "node:fs";
1866
+ import { join as join3, dirname as dirname2 } from "node:path";
1867
+ import { fileURLToPath } from "node:url";
1868
+ function loadPrompt(name) {
1869
+ if (typeof name !== "string" || !/^[A-Za-z0-9._-]+$/.test(name) || name.includes("..")) {
1870
+ logger.error(`[prompts] Rejected unsafe prompt name: ${JSON.stringify(name)}`);
1871
+ throw new Error(`[prompts] Rejected unsafe prompt name: ${JSON.stringify(name)}`);
1872
+ }
1873
+ for (const dir of PROMPT_CANDIDATES) {
1874
+ try {
1875
+ return readFileSync(join3(dir, `${name}.md`), "utf-8");
1876
+ } catch {
1877
+ }
1878
+ }
1879
+ logger.error(`[prompts] Failed to load prompt: ${name} (searched: ${PROMPT_CANDIDATES.join(", ")})`);
1880
+ throw new Error(`[prompts] Failed to load prompt "${name}" (searched: ${PROMPT_CANDIDATES.join(", ")})`);
1881
+ }
1882
+ var __filename2, CORE_LLM_DIR, PROMPT_CANDIDATES;
1883
+ var init_prompts = __esm({
1884
+ "src/core/llm/prompts.ts"() {
1885
+ "use strict";
1886
+ init_logger();
1887
+ __filename2 = fileURLToPath(import.meta.url);
1888
+ CORE_LLM_DIR = dirname2(__filename2);
1889
+ PROMPT_CANDIDATES = [
1890
+ join3(CORE_LLM_DIR, "../../prompts"),
1891
+ // source tree
1892
+ join3(CORE_LLM_DIR, "prompts")
1893
+ // bundled CLI (dist/prompts/)
1894
+ ];
1895
+ }
1896
+ });
1897
+
1898
+ // src/types/llm.ts
1899
+ import { calculateCost } from "@earendil-works/pi-ai";
1900
+ function parseTokenUsage(usage) {
1901
+ if (!usage || typeof usage !== "object") {
1902
+ return {};
1903
+ }
1904
+ const obj = usage;
1905
+ const result = {};
1906
+ if (typeof obj["input"] === "number") {
1907
+ result.input = obj["input"];
1908
+ }
1909
+ if (typeof obj["output"] === "number") {
1910
+ result.output = obj["output"];
1911
+ }
1912
+ if (typeof obj["cacheRead"] === "number") {
1913
+ result.cacheRead = obj["cacheRead"];
1914
+ }
1915
+ if (typeof obj["cacheWrite"] === "number") {
1916
+ result.cacheWrite = obj["cacheWrite"];
1917
+ }
1918
+ if (typeof obj["totalTokens"] === "number") {
1919
+ result.totalTokens = obj["totalTokens"];
1920
+ }
1921
+ if (obj["cost"] && typeof obj["cost"] === "object") {
1922
+ result.cost = obj["cost"];
1923
+ }
1924
+ return result;
1925
+ }
1926
+ function calculateTotalTokens(usage) {
1927
+ if (usage.totalTokens !== void 0) {
1928
+ return usage.totalTokens;
1929
+ }
1930
+ return (usage.input ?? 0) + (usage.output ?? 0) + (usage.cacheRead ?? 0) + (usage.cacheWrite ?? 0);
1931
+ }
1932
+ function extractUsage(model, rawUsage) {
1933
+ if (!rawUsage) {
1934
+ return { tokens: 0, cost: 0, parsed: {} };
1935
+ }
1936
+ const parsed = parseTokenUsage(rawUsage);
1937
+ const tokens = calculateTotalTokens(parsed);
1938
+ let cost = parsed.cost?.total ?? rawUsage.cost?.total ?? 0;
1939
+ if (cost === 0 && tokens > 0) {
1940
+ try {
1941
+ const calculatedCost = calculateCost(model, rawUsage);
1942
+ cost = calculatedCost.total;
1943
+ } catch {
1944
+ }
1945
+ }
1946
+ return { tokens, cost, parsed };
1947
+ }
1948
+ var init_llm = __esm({
1949
+ "src/types/llm.ts"() {
1950
+ "use strict";
1951
+ }
1952
+ });
1953
+
1954
1954
  // src/utils/llm-usage.ts
1955
1955
  function warnIfUnpriced(model, tokens, cost) {
1956
1956
  if (tokens <= 0 || cost > 0) return;
@@ -2013,10 +2013,10 @@ function stripTrailingLlmPunctuation(input) {
2013
2013
  continue;
2014
2014
  }
2015
2015
  if (last === ")" || last === "]" || last === "}") {
2016
- const open5 = last === ")" ? "(" : last === "]" ? "[" : "{";
2016
+ const open6 = last === ")" ? "(" : last === "]" ? "[" : "{";
2017
2017
  let balance = 0;
2018
2018
  for (const ch of s.slice(0, -1)) {
2019
- if (ch === open5) balance++;
2019
+ if (ch === open6) balance++;
2020
2020
  else if (ch === last) balance = Math.max(0, balance - 1);
2021
2021
  }
2022
2022
  if (balance === 0) {
@@ -2831,6 +2831,7 @@ function saveConfig(config, scope = "local", cwd = process.cwd(), changedKeys) {
2831
2831
  PI_RESEARCH_MIGRATION_STRATEGY: config.MIGRATION_STRATEGY,
2832
2832
  PI_RESEARCH_CONSOLE_LOG: String(config.CONSOLE_LOG),
2833
2833
  ...config.RESEARCH_MODEL ? { PI_RESEARCH_MODEL: config.RESEARCH_MODEL } : {},
2834
+ ...config.COORDINATOR_MODEL ? { PI_RESEARCH_COORDINATOR_MODEL: config.COORDINATOR_MODEL } : {},
2834
2835
  ...config.KNOWLEDGE_STORE_DIR ? { PI_RESEARCH_KNOWLEDGE_DIR: config.KNOWLEDGE_STORE_DIR } : {},
2835
2836
  ...config.TMP_DIR ? { PI_RESEARCH_TMP_DIR: config.TMP_DIR } : {},
2836
2837
  PI_RESEARCH_REPORT_EXPORT_ENABLED: String(config.RESEARCH_REPORT_EXPORT_ENABLED),
@@ -2954,6 +2955,19 @@ function saveConfig(config, scope = "local", cwd = process.cwd(), changedKeys) {
2954
2955
  }
2955
2956
  }
2956
2957
  }
2958
+ function configSourcesFingerprint(cwd, iface) {
2959
+ const sources = [getGlobalEnvFilePath(), getProjectSettingsRegistryPath(), getLocalEnvFilePath(cwd)];
2960
+ if (iface) sources.push(getInterfaceEnvFilePath(iface));
2961
+ return sources.map((file) => {
2962
+ try {
2963
+ if (!fs5.existsSync(file)) return `${file}=absent`;
2964
+ const st = fs5.statSync(file);
2965
+ return `${file}=${st.mtimeMs}:${st.size}`;
2966
+ } catch {
2967
+ return `${file}=unreadable`;
2968
+ }
2969
+ }).join("|");
2970
+ }
2957
2971
  function createConfig(env, processEnv) {
2958
2972
  const e = { ...env, ...processEnv };
2959
2973
  const raw = {
@@ -3001,6 +3015,7 @@ function createConfig(env, processEnv) {
3001
3015
  MIGRATION_STRATEGY: parseEnvEnum(e, "PI_RESEARCH_MIGRATION_STRATEGY", ["drop", "re-embed", "backup"], DEFAULTS.MIGRATION_STRATEGY),
3002
3016
  CONSOLE_LOG: parseEnvBool(e, "PI_RESEARCH_CONSOLE_LOG", DEFAULTS.CONSOLE_LOG),
3003
3017
  RESEARCH_MODEL: parseEnvString(e, "PI_RESEARCH_MODEL", DEFAULTS.RESEARCH_MODEL),
3018
+ COORDINATOR_MODEL: parseEnvString(e, "PI_RESEARCH_COORDINATOR_MODEL", DEFAULTS.COORDINATOR_MODEL),
3004
3019
  KNOWLEDGE_STORE_DIR: parseEnvString(e, "PI_RESEARCH_KNOWLEDGE_DIR", DEFAULTS.KNOWLEDGE_STORE_DIR),
3005
3020
  TMP_DIR: parseEnvString(e, "PI_RESEARCH_TMP_DIR", DEFAULTS.TMP_DIR),
3006
3021
  RESEARCH_REPORT_EXPORT_ENABLED: parseEnvBool(e, "PI_RESEARCH_REPORT_EXPORT_ENABLED", DEFAULTS.RESEARCH_REPORT_EXPORT_ENABLED),
@@ -3025,14 +3040,22 @@ function createConfig(env, processEnv) {
3025
3040
  function getConfig(cwd = process.cwd(), iface) {
3026
3041
  const cacheKey = `${normalizeWorkspacePath(cwd)}:${iface ?? ""}`;
3027
3042
  const cached = configCache.get(cacheKey);
3028
- if (cached) return cached;
3043
+ if (cached && configFingerprints.get(cacheKey) === configSourcesFingerprint(cwd, iface)) {
3044
+ return cached;
3045
+ }
3046
+ if (cached) {
3047
+ logger.info(`[config] Configuration files changed on disk; reloading for ${cwd} (cached values were from process start)`);
3048
+ }
3049
+ const fingerprint = configSourcesFingerprint(cwd, iface);
3029
3050
  const e = loadEnvFiles(cwd, iface);
3030
3051
  const config = createConfig(e, process.env);
3031
3052
  configCache.set(cacheKey, config);
3053
+ configFingerprints.set(cacheKey, fingerprint);
3032
3054
  return config;
3033
3055
  }
3034
3056
  function resetConfig() {
3035
3057
  configCache.clear();
3058
+ configFingerprints.clear();
3036
3059
  warnedLegacyEnvVars = false;
3037
3060
  }
3038
3061
  function validateConfig(config) {
@@ -3075,7 +3098,7 @@ function parseEnvEnum(env, key, allowed, def) {
3075
3098
  logger.warn(`[config] Invalid ${key}="${raw}" (expected one of: ${allowed.join(", ")}). Using default "${def}".`);
3076
3099
  return def;
3077
3100
  }
3078
- var ConfigSchema, DEFAULTS, LOCAL_SCOPE_KEYS, USER_MIGRATION_KEYS, RECLAIM_FILE_SWEEP_AGE_MS, LEGACY_ENV_VARS, warnedLegacyEnvVars, warnedMissingConfigWorkspaces, configCache;
3101
+ var ConfigSchema, DEFAULTS, LOCAL_SCOPE_KEYS, USER_MIGRATION_KEYS, RECLAIM_FILE_SWEEP_AGE_MS, LEGACY_ENV_VARS, warnedLegacyEnvVars, warnedMissingConfigWorkspaces, configCache, configFingerprints;
3079
3102
  var init_config = __esm({
3080
3103
  "src/config.ts"() {
3081
3104
  "use strict";
@@ -3227,9 +3250,24 @@ var init_config = __esm({
3227
3250
  * When set, this governs the evaluator/synthesis rounds and the researcher
3228
3251
  * sub-agents (both deep and quick) and the knowledge synthesis background LLM.
3229
3252
  * The initial coordinator (round 1 planning) uses the parent chat's model (ctx.model)
3230
- * for prompt-cache continuity with the conversation that triggered research.
3253
+ * by DEFAULT, for prompt-cache continuity with the conversation that triggered
3254
+ * research; COORDINATOR_MODEL overrides that decision (see below).
3231
3255
  */
3232
3256
  RESEARCH_MODEL: Type.Optional(Type.String()),
3257
+ /**
3258
+ * Which model runs the INITIAL coordinator (round-1 planning), the one call that
3259
+ * otherwise uses the parent chat's model (`ctx.model`) for prompt-cache continuity:
3260
+ * • `host` (default) — the chat's model, current behaviour.
3261
+ * • `research` — the RESEARCH_MODEL / researcher model, same as every later round.
3262
+ * • `provider/id` (or a bare id) — that model.
3263
+ *
3264
+ * Exists because the chat model is not always a good planner: a local single-seat
3265
+ * server (llama-swap `concurrencyLimit: 1`, 4k output) turns the coordinator call into
3266
+ * minutes of wall clock and can 429 the owner's own next prompt, while a hosted
3267
+ * research model plans the same query in seconds. The cache-lineage benefit is real
3268
+ * but must be opt-out-able. Unset = `host`.
3269
+ */
3270
+ COORDINATOR_MODEL: Type.Optional(Type.String()),
3233
3271
  /** Explicit directory for the knowledge store database (overrides default) */
3234
3272
  KNOWLEDGE_STORE_DIR: Type.Optional(Type.String()),
3235
3273
  /** Directory for transient browser profile data. Defaults to a disk-backed
@@ -3315,6 +3353,7 @@ var init_config = __esm({
3315
3353
  "PI_RESEARCH_QUICK_MAX_SCRAPE_URLS",
3316
3354
  "PI_RESEARCH_CONSOLE_LOG",
3317
3355
  "PI_RESEARCH_MODEL",
3356
+ "PI_RESEARCH_COORDINATOR_MODEL",
3318
3357
  "PI_RESEARCH_KNOWLEDGE_DIR",
3319
3358
  "PI_RESEARCH_TMP_DIR",
3320
3359
  "PI_RESEARCH_REPORT_EXPORT_ENABLED",
@@ -3335,6 +3374,7 @@ var init_config = __esm({
3335
3374
  warnedLegacyEnvVars = false;
3336
3375
  warnedMissingConfigWorkspaces = /* @__PURE__ */ new Set();
3337
3376
  configCache = /* @__PURE__ */ new Map();
3377
+ configFingerprints = /* @__PURE__ */ new Map();
3338
3378
  }
3339
3379
  });
3340
3380
 
@@ -3435,8 +3475,8 @@ function findMatchingBracket(text, start) {
3435
3475
  let depth = 0;
3436
3476
  let inString = false;
3437
3477
  let escaped = false;
3438
- const open5 = text[start];
3439
- const close = open5 === "{" ? "}" : "]";
3478
+ const open6 = text[start];
3479
+ const close = open6 === "{" ? "}" : "]";
3440
3480
  for (let i = start; i < text.length; i++) {
3441
3481
  const ch = text[i];
3442
3482
  if (escaped) {
@@ -3452,7 +3492,7 @@ function findMatchingBracket(text, start) {
3452
3492
  continue;
3453
3493
  }
3454
3494
  if (inString) continue;
3455
- if (ch === open5) depth++;
3495
+ if (ch === open6) depth++;
3456
3496
  else if (ch === close) {
3457
3497
  depth--;
3458
3498
  if (depth === 0) return { index: i, inString: false };
@@ -4192,7 +4232,8 @@ async function retryWithBackoff(fn, options = {}) {
4192
4232
  }
4193
4233
  const baseDelay = opts.initialDelay * Math.pow(2, attempt);
4194
4234
  const jitter = Math.random() * 0.5 * baseDelay;
4195
- const delay2 = Math.min(baseDelay + jitter, opts.maxDelay);
4235
+ const override = opts.delayFor?.(attempt + 2, lastError);
4236
+ const delay2 = override != null && Number.isFinite(override) && override > 0 ? Math.round(override) : Math.min(baseDelay + jitter, opts.maxDelay);
4196
4237
  metrics.increment("retry_backoff_total", 1, { attempt: String(attempt), label: opts.label });
4197
4238
  metrics.observe("retry_backoff_delay_ms", delay2, { attempt: String(attempt), label: opts.label });
4198
4239
  logger.warn(`[Retry] ${opts.label} failed (attempt ${attempt + 1}/${opts.maxRetries + 1}), retrying in ${Math.round(delay2)}ms: ${lastError.message}`);
@@ -7422,6 +7463,16 @@ var init_lancedb_loader = __esm({
7422
7463
  }
7423
7464
  });
7424
7465
 
7466
+ // src/knowledge/sql-utils.ts
7467
+ function sqlString(value) {
7468
+ return `'${value.replace(/'/g, "''")}'`;
7469
+ }
7470
+ var init_sql_utils = __esm({
7471
+ "src/knowledge/sql-utils.ts"() {
7472
+ "use strict";
7473
+ }
7474
+ });
7475
+
7425
7476
  // src/knowledge/store-schema.ts
7426
7477
  import {
7427
7478
  Schema,
@@ -7710,8 +7761,8 @@ async function findRelevantUrlsBm25(table, query, limit, scopeFilter) {
7710
7761
  }
7711
7762
  async function findDocumentsByUrl(table, url, scopeFilter) {
7712
7763
  const startTime = Date.now();
7713
- const escapedUrl = url.replace(/'/g, "''");
7714
- let filter = `url = '${escapedUrl}'`;
7764
+ const escapedUrl = sqlString(url);
7765
+ let filter = `url = ${escapedUrl}`;
7715
7766
  if (scopeFilter) {
7716
7767
  filter = `(${filter}) AND (${scopeFilter})`;
7717
7768
  }
@@ -7783,6 +7834,7 @@ var init_store_operations = __esm({
7783
7834
  "src/knowledge/store-operations.ts"() {
7784
7835
  "use strict";
7785
7836
  init_logger();
7837
+ init_sql_utils();
7786
7838
  init_metrics();
7787
7839
  }
7788
7840
  });
@@ -7800,6 +7852,7 @@ var init_store = __esm({
7800
7852
  "src/knowledge/store.ts"() {
7801
7853
  "use strict";
7802
7854
  init_lancedb_loader();
7855
+ init_sql_utils();
7803
7856
  init_circuit_breaker();
7804
7857
  init_logger();
7805
7858
  init_metrics();
@@ -7876,10 +7929,10 @@ var init_store = __esm({
7876
7929
  return this.options.embedder;
7877
7930
  }
7878
7931
  getScopeFilter() {
7879
- const ws = this.getWorkspace().replace(/'/g, "''");
7932
+ const ws = sqlString(this.getWorkspace());
7880
7933
  switch (this.options.knowledgeMode) {
7881
7934
  case "project":
7882
- return `workspace = '${ws}'`;
7935
+ return `workspace = ${ws}`;
7883
7936
  case "global":
7884
7937
  return "is_global = true";
7885
7938
  default:
@@ -8424,8 +8477,8 @@ var init_store = __esm({
8424
8477
  const table = await this.getFreshTable();
8425
8478
  const startTime = Date.now();
8426
8479
  try {
8427
- const escapedUrl = url.replace(/'/g, "''");
8428
- await table.delete(`url = '${escapedUrl}' AND (${scopeFilter})`);
8480
+ const escapedUrl = sqlString(url);
8481
+ await table.delete(`url = ${escapedUrl} AND (${scopeFilter})`);
8429
8482
  const duration = Date.now() - startTime;
8430
8483
  metrics.observe("knowledge_store_delete_duration_ms", duration);
8431
8484
  metrics.increment("knowledge_store_delete_total", 1, { operation: "by_url", status: "success" });
@@ -8471,10 +8524,10 @@ var init_store = __esm({
8471
8524
  const table = await this.getFreshTable();
8472
8525
  const startTime = Date.now();
8473
8526
  try {
8474
- const escapedUrl = url.replace(/'/g, "''");
8475
- const escapedType = ingestionType.replace(/'/g, "''");
8527
+ const escapedUrl = sqlString(url);
8528
+ const escapedType = sqlString(ingestionType);
8476
8529
  const ageClause = Number.isFinite(olderThan) ? ` AND timestamp < ${Math.floor(olderThan)}` : "";
8477
- await table.delete(`url = '${escapedUrl}' AND ingestion_type = '${escapedType}' AND (${scopeFilter})${ageClause}`);
8530
+ await table.delete(`url = ${escapedUrl} AND ingestion_type = ${escapedType} AND (${scopeFilter})${ageClause}`);
8478
8531
  const duration = Date.now() - startTime;
8479
8532
  metrics.observe("knowledge_store_delete_duration_ms", duration, { operation: "by_url_and_type" });
8480
8533
  metrics.increment("knowledge_store_delete_total", 1, { operation: "by_url_and_type", status: "success" });
@@ -8514,10 +8567,10 @@ var init_store = __esm({
8514
8567
  while (retryCount <= MAX_RETRIES) {
8515
8568
  const table = await this.getFreshTable();
8516
8569
  try {
8517
- const escapedUrl = url.replace(/'/g, "''");
8518
- const escapedType = ingestionType.replace(/'/g, "''");
8570
+ const escapedUrl = sqlString(url);
8571
+ const escapedType = sqlString(ingestionType);
8519
8572
  await table.update({
8520
- where: `url = '${escapedUrl}' AND ingestion_type = '${escapedType}' AND timestamp = ${Math.floor(generationTs)} AND (${scopeFilter})`,
8573
+ where: `url = ${escapedUrl} AND ingestion_type = ${escapedType} AND timestamp = ${Math.floor(generationTs)} AND (${scopeFilter})`,
8521
8574
  valuesSql: { timestamp: String(Math.floor(newTs)) }
8522
8575
  });
8523
8576
  logger.log(`[store] Refreshed timestamp for unchanged ${ingestionType} chunks of ${url}`);
@@ -8588,8 +8641,8 @@ var init_store = __esm({
8588
8641
  const table = await this.getFreshTable();
8589
8642
  const scopeFilter = this.getScopeFilter();
8590
8643
  const startTime = Date.now();
8591
- const escapedUrl = url.replace(/'/g, "''");
8592
- const whereClause = `url = '${escapedUrl}' AND ingestion_type = 'synthesis-description' AND (${scopeFilter})`;
8644
+ const escapedUrl = sqlString(url);
8645
+ const whereClause = `url = ${escapedUrl} AND ingestion_type = 'synthesis-description' AND (${scopeFilter})`;
8593
8646
  let results = await table.query().where(whereClause).limit(16).toArray();
8594
8647
  if (results.length === 16) {
8595
8648
  results = await table.query().where(whereClause).limit(1024).toArray();
@@ -8842,9 +8895,9 @@ var init_store = __esm({
8842
8895
  try {
8843
8896
  const table = await this.getFreshTable();
8844
8897
  const ws = normalizeWorkspacePath(workspace || this.getWorkspace());
8845
- const escaped = ws.replace(/'/g, "''");
8898
+ const escaped = sqlString(ws);
8846
8899
  const [local, global] = await Promise.all([
8847
- table.countRows(`workspace = '${escaped}'`),
8900
+ table.countRows(`workspace = ${escaped}`),
8848
8901
  table.countRows(`is_global = true`)
8849
8902
  ]);
8850
8903
  const allWorkspaces = await table.query().select(["workspace"]).toArray();
@@ -10247,12 +10300,12 @@ function isTransientSynthesisError(message) {
10247
10300
  m.includes("terminated") || m.includes("other side closed") || m.includes("socket hang up") || m.includes("und_err");
10248
10301
  }
10249
10302
  function splitPromptAtUserTurn(template) {
10250
- const open5 = template.indexOf("<!-- USER_TURN");
10251
- if (open5 < 0) return { system: template, user: null };
10252
- const close = template.indexOf("-->", open5);
10303
+ const open6 = template.indexOf("<!-- USER_TURN");
10304
+ if (open6 < 0) return { system: template, user: null };
10305
+ const close = template.indexOf("-->", open6);
10253
10306
  if (close < 0) return { system: template, user: null };
10254
10307
  return {
10255
- system: template.slice(0, open5).trimEnd(),
10308
+ system: template.slice(0, open6).trimEnd(),
10256
10309
  user: template.slice(close + "-->".length).trimStart()
10257
10310
  };
10258
10311
  }
@@ -11284,6 +11337,45 @@ var SchedulerService = class {
11284
11337
  init_service_registry();
11285
11338
  init_service_interfaces();
11286
11339
  init_logger();
11340
+ init_metrics();
11341
+
11342
+ // src/utils/provider-errors.ts
11343
+ function isSpentAccountError(error) {
11344
+ const msg2 = (error instanceof Error ? error.message : String(error)).toLowerCase();
11345
+ return msg2.includes("insufficient_quota") || msg2.includes("insufficient credits") || msg2.includes("requires more credits") || msg2.includes("exceeded your current quota") || msg2.includes("out of credits");
11346
+ }
11347
+ function isRateLimitError(error) {
11348
+ if (isSpentAccountError(error)) return false;
11349
+ 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");
11351
+ }
11352
+ function isCapacityFailureReason(reason) {
11353
+ return reason !== void 0 && reason !== "" && isRateLimitError(reason);
11354
+ }
11355
+ function parseRetryAfterMs(error) {
11356
+ const message = error instanceof Error ? error.message : String(error);
11357
+ const m = /["']?retry-after["']?\s*[:=]\s*["']?(\d{1,4})/i.exec(message);
11358
+ if (!m) return null;
11359
+ const seconds = Number(m[1]);
11360
+ if (!Number.isFinite(seconds) || seconds <= 0) return null;
11361
+ return Math.min(Math.max(seconds, 5), 60) * 1e3;
11362
+ }
11363
+ var RATE_LIMIT_BACKOFF_BASE_MS = 15e3;
11364
+ var RATE_LIMIT_BACKOFF_MAX_MS = 6e4;
11365
+ function rateLimitBackoffMs(attempt, retryAfterMs, random = Math.random) {
11366
+ if (retryAfterMs !== null && Number.isFinite(retryAfterMs) && retryAfterMs > 0) {
11367
+ return clampRateLimitWait(retryAfterMs);
11368
+ }
11369
+ const exponent = Math.max(0, attempt - 2);
11370
+ const base = Math.min(RATE_LIMIT_BACKOFF_BASE_MS * Math.pow(2, exponent), RATE_LIMIT_BACKOFF_MAX_MS);
11371
+ const jitter = base * 0.2 * (random() * 2 - 1);
11372
+ return clampRateLimitWait(base + jitter);
11373
+ }
11374
+ function clampRateLimitWait(ms) {
11375
+ return Math.min(Math.max(Math.round(ms), 1e3), RATE_LIMIT_BACKOFF_MAX_MS);
11376
+ }
11377
+
11378
+ // src/core/planning-service.ts
11287
11379
  init_pi_ai_completion();
11288
11380
 
11289
11381
  // src/core/llm/inject-date.ts
@@ -11538,19 +11630,19 @@ function rewriteCitationMarkers(text, remap, isDangling) {
11538
11630
  }
11539
11631
  function fencedCodeMask(text) {
11540
11632
  const ranges = [];
11541
- let open5 = -1;
11633
+ let open6 = -1;
11542
11634
  let pos = 0;
11543
11635
  for (const line of text.split("\n")) {
11544
11636
  if (/^\s{0,3}(```|~~~)/.test(line)) {
11545
- if (open5 < 0) open5 = pos;
11637
+ if (open6 < 0) open6 = pos;
11546
11638
  else {
11547
- ranges.push([open5, pos + line.length]);
11548
- open5 = -1;
11639
+ ranges.push([open6, pos + line.length]);
11640
+ open6 = -1;
11549
11641
  }
11550
11642
  }
11551
11643
  pos += line.length + 1;
11552
11644
  }
11553
- if (open5 >= 0) ranges.push([open5, text.length]);
11645
+ if (open6 >= 0) ranges.push([open6, text.length]);
11554
11646
  return (offset) => ranges.some(([start, end]) => offset >= start && offset < end);
11555
11647
  }
11556
11648
  function inInlineCodeSpan(text, offset) {
@@ -11960,6 +12052,12 @@ function generateResearchers(plan, _query, _complexity) {
11960
12052
 
11961
12053
  // src/core/planning-service.ts
11962
12054
  var LLM_MAX_RETRIES = 2;
12055
+ function rateLimitDelayFor(nextAttempt, error) {
12056
+ if (!isRateLimitError(error)) return null;
12057
+ const delay2 = rateLimitBackoffMs(nextAttempt, parseRetryAfterMs(error));
12058
+ metrics.increment("planning_rate_limit_backoff_total", 1, { nextAttempt: String(nextAttempt) });
12059
+ return delay2;
12060
+ }
11963
12061
  var LLM_RETRY_INITIAL_DELAY_MS = 1e3;
11964
12062
  var LLM_RETRY_MAX_DELAY_MS = 8e3;
11965
12063
  var ROUTER_MAX_TOKENS = 8192;
@@ -12206,7 +12304,8 @@ Respond by calling the ${submitPlanTool.name} tool with the plan as its argument
12206
12304
  maxDelay: LLM_RETRY_MAX_DELAY_MS,
12207
12305
  label: "coordinator-generatePlan",
12208
12306
  signal,
12209
- isTransientError: (err) => isRetriableLlmError(err, signal)
12307
+ isTransientError: (err) => isRetriableLlmError(err, signal),
12308
+ delayFor: rateLimitDelayFor
12210
12309
  }
12211
12310
  );
12212
12311
  recordLlmUsage(model, response.usage, { component: "coordinator", complexity, observer });
@@ -12620,7 +12719,8 @@ Respond by calling the ${submitRoutingTool.name} tool with the updated plan as i
12620
12719
  maxDelay: LLM_RETRY_MAX_DELAY_MS,
12621
12720
  label,
12622
12721
  signal,
12623
- isTransientError: (err) => isRetriableLlmError(err, signal)
12722
+ isTransientError: (err) => isRetriableLlmError(err, signal),
12723
+ delayFor: rateLimitDelayFor
12624
12724
  }
12625
12725
  );
12626
12726
  recordLlmUsage(model, response.usage, { component: args.component, complexity, observer });
@@ -18893,11 +18993,11 @@ import { createAgentSession, SessionManager, SettingsManager as SettingsManagerC
18893
18993
 
18894
18994
  // src/tools/read-guard.ts
18895
18995
  import { constants as constants2 } from "node:fs";
18896
- import { access as access3, readFile as readFile7, realpath as realpath2 } from "node:fs/promises";
18996
+ import { access as access3, open as open5, readFile as readFile7, realpath as realpath2 } from "node:fs/promises";
18897
18997
  import { homedir as homedir6 } from "node:os";
18898
18998
  import { basename as basename5, dirname as dirname13, relative, isAbsolute as isAbsolute3, parse, sep as sep2 } from "node:path";
18899
- var DENIED_SEGMENTS = /* @__PURE__ */ new Set([".ssh", ".aws", ".gnupg", ".git", ".kube", ".docker", ".azure", ".gcloud"]);
18900
- var DENIED_BASENAME = /^(\.env(\..*)?|\.envrc|\.netrc|_netrc|\.npmrc|\.pypirc|\.git-credentials|\.pgpass|\.my\.cnf|\.htpasswd|\.dockercfg|\.vault-token|\.bash_history|\.zsh_history|kubeconfig|terraform\.tfstate(\..*)?|(credentials|secrets?)(\.(json|ya?ml|toml|env|ini|txt|xml))?|id_(rsa|dsa|ecdsa|ed25519)(\..*)?|.*\.(pem|p12|pfx|jks|keystore|kdbx|asc|gpg|tfvars)|.*[-_.](secret|secrets|credentials)\.(json|ya?ml|toml|env)|service-account.*\.json)$/;
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)$/;
18901
19001
  var ALLOWED_ENV_TEMPLATE = /^\.env\.(example|sample|template|dist)$/;
18902
19002
  function normalizeName(name) {
18903
19003
  return name.toLowerCase().replace(/:.*$/, "").replace(/[. ]+$/, "");
@@ -18948,7 +19048,16 @@ function createGuardedReadOperations(cwd) {
18948
19048
  },
18949
19049
  readFile: async (p) => {
18950
19050
  await assertReadAllowed(cwd, p);
18951
- return readFile7(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
+ }
18952
19061
  }
18953
19062
  };
18954
19063
  }
@@ -24486,25 +24595,69 @@ function getFailedResearchers(piSessionId, researchId) {
24486
24595
  return [...new Set(failures)];
24487
24596
  }
24488
24597
  var DEFAULT_MAX_FAILED_RESEARCHERS = 2;
24598
+ function countTowardStopThreshold(reasons, researcherId) {
24599
+ return !isCapacityFailureReason(reasons?.get(researcherId));
24600
+ }
24601
+ function hasOnlyCapacityFailures(piSessionId, researchId) {
24602
+ const sid = normalizeSessionId(piSessionId);
24603
+ const failed = getFailedResearchers(sid, researchId);
24604
+ if (failed.length === 0) return false;
24605
+ const reasons = peekPiState(sid)?.failureReasons.get(researchId);
24606
+ return failed.every((id) => isCapacityFailureReason(reasons?.get(id)));
24607
+ }
24489
24608
  function shouldStopResearch(piSessionId, researchId, maxFailedResearchers = DEFAULT_MAX_FAILED_RESEARCHERS) {
24490
24609
  const sid = normalizeSessionId(piSessionId);
24491
- return getFailedResearchers(sid, researchId).length >= maxFailedResearchers;
24610
+ const failed = getFailedResearchers(sid, researchId);
24611
+ if (failed.length === 0) return false;
24612
+ const reasons = peekPiState(sid)?.failureReasons.get(researchId);
24613
+ const counted = failed.filter((id) => countTowardStopThreshold(reasons, id));
24614
+ if (counted.length !== failed.length) {
24615
+ logger.debug(
24616
+ `[ResearchSessionState] ${failed.length - counted.length} capacity failure(s) excluded from the stop threshold (${counted.length}/${maxFailedResearchers} counted: ${counted.join(", ") || "none"})`
24617
+ );
24618
+ }
24619
+ return counted.length >= maxFailedResearchers;
24492
24620
  }
24493
24621
  function getResearchStopMessage(piSessionId, researchId) {
24494
24622
  const sid = normalizeSessionId(piSessionId);
24495
24623
  const failed = getFailedResearchers(sid, researchId);
24496
- const count = failed.length;
24624
+ const stateForReasons = peekPiState(sid);
24625
+ const reasonsForCount = stateForReasons?.failureReasons.get(researchId);
24626
+ const countedFailures = failed.filter((id) => countTowardStopThreshold(reasonsForCount, id));
24627
+ const capacityFailures = failed.filter((id) => !countTowardStopThreshold(reasonsForCount, id));
24628
+ const count = countedFailures.length;
24629
+ const failedList = countedFailures.length > 0 ? countedFailures.join(", ") : failed.join(", ");
24497
24630
  const state = peekPiState(sid);
24498
24631
  const reasons = state?.failureReasons.get(researchId);
24499
24632
  const recorded = reasons && reasons.size > 0 ? ["Recorded errors:", ...[...reasons].map(([id, r]) => `\u2022 researcher ${id}: ${r}`), ""] : [];
24633
+ const headline = countedFailures.length > 0 ? `Research stopped: ${count} researcher(s) did not return a usable report: ${failedList}.` : `Research stopped: no report was collected, and every recorded failure was a provider-capacity failure${failedList ? `: ${failedList}` : ""}.`;
24500
24634
  return [
24501
- `Research stopped: ${count} researcher(s) did not return a usable report: ${failed.join(", ")}.`,
24635
+ headline,
24502
24636
  "",
24637
+ ...capacityFailures.length > 0 ? [
24638
+ `Provider capacity failures (excluded from the stop threshold): ${capacityFailures.join(", ")}.`,
24639
+ "Those researchers lost every retry to a rate limit or an exhausted in-flight budget,",
24640
+ "not to anything about the topic. Retrying the run later is the repair.",
24641
+ ""
24642
+ ] : [],
24503
24643
  ...recorded,
24504
- "Most likely cause \u2014 the research model could not produce grounded results:",
24505
- '\u2022 Try a more capable research model. Very small or "thinking-only" models often',
24506
- " emit no final text after their tool calls, which fails every researcher.",
24507
- "\u2022 Verify the model is available and the API key / context settings are valid.",
24644
+ // Only give the "get a better model" advice when the model's output was actually the
24645
+ // problem. When every failure was the provider refusing to serve (a rate limit or an
24646
+ // exhausted budget), the model never ran — telling the user to change models sends
24647
+ // them to buy a different one for a supply problem.
24648
+ ...capacityFailures.length > 0 && capacityFailures.length === failed.length ? [
24649
+ "Most likely cause \u2014 the provider would not serve the requests:",
24650
+ "\u2022 Every researcher lost its retries to a rate limit or an exhausted in-flight budget.",
24651
+ "\u2022 Wait and retry. A shared/free upstream pool (OpenRouter free tier, for one) is",
24652
+ " routinely overloaded, and nothing about your setup needs to change.",
24653
+ "\u2022 If it keeps happening, set PI_RESEARCH_MODEL to a model with a dedicated key or",
24654
+ " a provider that is not sharing a pool."
24655
+ ] : [
24656
+ "Most likely cause \u2014 the research model could not produce grounded results:",
24657
+ '\u2022 Try a more capable research model. Very small or "thinking-only" models often',
24658
+ " emit no final text after their tool calls, which fails every researcher.",
24659
+ "\u2022 Verify the model is available and the API key / context settings are valid."
24660
+ ],
24508
24661
  "",
24509
24662
  "Less likely \u2014 a network or browser problem (only if the health check did NOT pass):",
24510
24663
  "\u2022 Verify the network connection is active.",
@@ -24523,21 +24676,12 @@ function createResearchStopError(piSessionId, researchId) {
24523
24676
 
24524
24677
  // src/orchestration/researcher-executor.ts
24525
24678
  function isUnretriableResearcherError(error) {
24526
- const message = (error instanceof Error ? error.message : String(error)).toLowerCase();
24527
- return message.includes("requires more credits") || message.includes("insufficient credits") || message.includes("insufficient_quota");
24679
+ return isSpentAccountError(error);
24528
24680
  }
24529
24681
  function isInFlightBudgetError(error) {
24530
24682
  const lower = (error instanceof Error ? error.message : String(error)).toLowerCase();
24531
24683
  return lower.includes("in_flight_budget_exhausted") || lower.includes("would exceed your available credits given your current in-flight requests");
24532
24684
  }
24533
- function parseRetryAfterMs(error) {
24534
- const message = error instanceof Error ? error.message : String(error);
24535
- const m = /["']?retry-after["']?\s*[:=]\s*["']?(\d{1,4})/i.exec(message);
24536
- if (!m) return null;
24537
- const seconds = Number(m[1]);
24538
- if (!Number.isFinite(seconds) || seconds <= 0) return null;
24539
- return Math.min(Math.max(seconds, 5), 60) * 1e3;
24540
- }
24541
24685
  async function runResearcher(options) {
24542
24686
  const {
24543
24687
  config: researcherConfig,
@@ -24882,10 +25026,16 @@ ${responseText}`);
24882
25026
  metrics.increment("researcher_unretriable_total", 1, { mode: "deep", complexity: String(complexity) });
24883
25027
  break;
24884
25028
  }
24885
- if (isInFlightBudgetError(err) && attempt < maxAttempts) {
24886
- inFlightBackoffMs = parseRetryAfterMs(err) ?? 15e3;
24887
- metrics.increment("researcher_inflight_budget_backoff_total", 1, { mode: "deep", complexity: String(complexity) });
24888
- logger.warn(`[ResearcherExecutor] Researcher ${id} hit the provider's in-flight budget; backing off ${inFlightBackoffMs}ms (provider Retry-After, else 15s) before attempt ${attempt + 1}`);
25029
+ if (attempt < maxAttempts) {
25030
+ if (isInFlightBudgetError(err)) {
25031
+ inFlightBackoffMs = parseRetryAfterMs(err) ?? 15e3;
25032
+ metrics.increment("researcher_inflight_budget_backoff_total", 1, { mode: "deep", complexity: String(complexity) });
25033
+ logger.warn(`[ResearcherExecutor] Researcher ${id} hit the provider's in-flight budget; backing off ${inFlightBackoffMs}ms (provider Retry-After, else 15s) before attempt ${attempt + 1}`);
25034
+ } else if (isRateLimitError(err)) {
25035
+ inFlightBackoffMs = rateLimitBackoffMs(attempt + 1, parseRetryAfterMs(err));
25036
+ metrics.increment("researcher_rate_limit_backoff_total", 1, { mode: "deep", complexity: String(complexity) });
25037
+ logger.warn(`[ResearcherExecutor] Researcher ${id} hit a provider rate limit; backing off ${inFlightBackoffMs}ms before attempt ${attempt + 1}`);
25038
+ }
24889
25039
  }
24890
25040
  if (attempt < maxAttempts) {
24891
25041
  logger.warn(`[ResearcherExecutor] Researcher ${id} attempt ${attempt} failed: ${errMsg}; will retry`);
@@ -25448,6 +25598,41 @@ init_text_utils();
25448
25598
  init_service_interfaces();
25449
25599
  init_service_registry();
25450
25600
  init_config();
25601
+
25602
+ // src/core/llm/coordinator-model.ts
25603
+ function parseCoordinatorModelChoice(value) {
25604
+ const raw = (value ?? "").trim();
25605
+ if (raw === "" || raw.toLowerCase() === "host") return { kind: "host" };
25606
+ if (raw.toLowerCase() === "research") return { kind: "research" };
25607
+ return { kind: "explicit", reference: raw };
25608
+ }
25609
+ function resolveCoordinatorModel(options) {
25610
+ const { setting, hostModel, researchModel, findByReference, onUnresolved } = options;
25611
+ const choice = parseCoordinatorModelChoice(setting);
25612
+ switch (choice.kind) {
25613
+ case "research":
25614
+ return researchModel;
25615
+ case "explicit": {
25616
+ const found = findByReference?.(choice.reference);
25617
+ if (found) return found;
25618
+ onUnresolved?.(choice.reference);
25619
+ return researchModel;
25620
+ }
25621
+ case "host":
25622
+ default:
25623
+ return hostModel ?? researchModel;
25624
+ }
25625
+ }
25626
+ function findModelByReference(reference, models, available = []) {
25627
+ const exact = available.find((m) => `${m.provider}/${m.id}` === reference) ?? models.find((m) => `${m.provider}/${m.id}` === reference);
25628
+ if (exact) return exact;
25629
+ const sameId = models.filter((m) => m.id === reference);
25630
+ if (sameId.length === 0) return void 0;
25631
+ const authed = new Set(available.map((m) => `${m.provider}/${m.id}`));
25632
+ return sameId.find((m) => authed.has(`${m.provider}/${m.id}`)) ?? sameId[0];
25633
+ }
25634
+
25635
+ // src/orchestration/deep-research-orchestrator.ts
25451
25636
  var DeepResearchOrchestrator = class {
25452
25637
  constructor(options) {
25453
25638
  this.options = options;
@@ -25492,7 +25677,27 @@ var DeepResearchOrchestrator = class {
25492
25677
  const { model, query, complexity, researchId, ctx } = this.options;
25493
25678
  const observer = this.observer;
25494
25679
  const container = tryGetServiceContainerFromCtx(ctx);
25495
- const initialCoordinatorModel = ctx.model ?? model;
25680
+ const initialCoordinatorModel = resolveCoordinatorModel({
25681
+ setting: this.config.COORDINATOR_MODEL,
25682
+ hostModel: ctx.model,
25683
+ researchModel: model,
25684
+ // STRICT lookup (never resolveResearchModel): that resolver always returns a
25685
+ // model — it falls back through RESEARCH_MODEL to "first available" — so a typo
25686
+ // would silently run on an arbitrary model AND never trigger onUnresolved.
25687
+ findByReference: (reference) => {
25688
+ try {
25689
+ const registry = ctx.modelRegistry;
25690
+ const all = registry?.getAll?.() ?? [];
25691
+ const available = registry?.getAvailable?.() ?? [];
25692
+ return findModelByReference(reference, all, available);
25693
+ } catch {
25694
+ return void 0;
25695
+ }
25696
+ },
25697
+ onUnresolved: (reference) => logger.warn(
25698
+ `[DeepOrchestrator] COORDINATOR_MODEL '${reference}' is not an available model; falling back to the research model (not the chat model, which this setting exists to replace).`
25699
+ )
25700
+ });
25496
25701
  const evaluatorModel = model;
25497
25702
  const orchestrationService = await this.getOrchestrationService();
25498
25703
  const planningService = await this.getPlanningService();
@@ -25513,6 +25718,7 @@ var DeepResearchOrchestrator = class {
25513
25718
  }
25514
25719
  const MAX_WAIT_RETRIES = 5;
25515
25720
  let waitRetryCount = 0;
25721
+ let capacityOnlyRounds = 0;
25516
25722
  let routerChoseSynthesis = false;
25517
25723
  let lastAnnouncedRound = 0;
25518
25724
  try {
@@ -25641,12 +25847,20 @@ var DeepResearchOrchestrator = class {
25641
25847
  continue;
25642
25848
  }
25643
25849
  waitRetryCount = 0;
25850
+ if (shouldStopResearch(this.options.sessionId, researchId, this.config.MAX_FAILED_RESEARCHERS)) {
25851
+ throw createResearchStopError(this.options.sessionId, researchId);
25852
+ }
25644
25853
  if (plan.action === "delegate" && plan.researchers && plan.researchers.length > 0) {
25645
25854
  planningService.incrementTotalResearchersPlanned(researchId, plan.researchers.length);
25646
25855
  }
25647
25856
  if (plan.allQueries && plan.allQueries.length > 0) {
25648
25857
  planningService.addToQueryHistory(researchId, plan.allQueries);
25649
25858
  }
25859
+ const reportsBeforeRound = (await getService(
25860
+ ServiceNames.RESEARCH_SYNTHESIS_SERVICE,
25861
+ ctx,
25862
+ container
25863
+ )).getReportCount(researchId);
25650
25864
  let researcherLinks;
25651
25865
  let storeLinks;
25652
25866
  const searchTask = plan.allQueries && plan.allQueries.length > 0 ? (async () => {
@@ -25708,6 +25922,22 @@ var DeepResearchOrchestrator = class {
25708
25922
  currentRound: this.currentRound,
25709
25923
  signal
25710
25924
  }, researcherLinks, storeLinks);
25925
+ const reportsAfterRound = (await getService(
25926
+ ServiceNames.RESEARCH_SYNTHESIS_SERVICE,
25927
+ ctx,
25928
+ container
25929
+ )).getReportCount(researchId);
25930
+ if (reportsAfterRound <= reportsBeforeRound && hasOnlyCapacityFailures(this.options.sessionId, researchId)) {
25931
+ capacityOnlyRounds++;
25932
+ logger.warn(
25933
+ `[DeepOrchestrator] Round ${this.currentRound} produced no report and every failure was a provider capacity failure (${capacityOnlyRounds} consecutive, 1 tolerated)`
25934
+ );
25935
+ if (capacityOnlyRounds > 1) {
25936
+ throw createResearchStopError(this.options.sessionId, researchId);
25937
+ }
25938
+ } else {
25939
+ capacityOnlyRounds = 0;
25940
+ }
25711
25941
  }
25712
25942
  if (signal?.aborted) throw new Error("Research aborted");
25713
25943
  observer?.onEvaluationProgress?.("embedding");
@@ -26668,9 +26898,15 @@ var ResearchSynthesisService = class _ResearchSynthesisService {
26668
26898
  synthesis += `This is an automated compilation of ${reportCount} individual researcher report(s). The synthesis step did not produce a usable summary for this run, so the findings are presented as collected.
26669
26899
 
26670
26900
  `;
26671
- synthesis += Array.from(reports.entries()).map(([id, report]) => `Researcher ${id}
26672
-
26673
- ${report}`).join("\n\n");
26901
+ synthesis += Array.from(reports.entries()).map(([key, report]) => {
26902
+ const dot = key.indexOf(".");
26903
+ const round = dot > 0 ? key.slice(0, dot) : "";
26904
+ const researcherId = dot > 0 ? key.slice(dot + 1) : key;
26905
+ const label = round && /^\d+$/.test(round) ? `Researcher ${researcherId} (round ${round})` : `Researcher ${key}`;
26906
+ return `${label}
26907
+
26908
+ ${report}`;
26909
+ }).join("\n\n");
26674
26910
  }
26675
26911
  return synthesis;
26676
26912
  }