@lincoln504/pi-research 1.7.21 → 1.7.22

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -2,7 +2,7 @@
2
2
  name: pi-research
3
3
  description: "Multi-agent web research for any coding agent. Use for anything requiring current information from the internet — news, trends, product/service/company facts, statistics, people, places, events, APIs, library behavior, or 'what is X / how does X work' questions. Also use to search a local knowledge store of previously researched findings before doing live research. Powered by the pi-research engine (search, stealth scraping, security databases, Stack Exchange). Not for reading local files, running project commands, or analyzing this repository's own source."
4
4
  license: MIT
5
- metadata: { "author": "Lincoln Deen", "version": "1.7.21", "package": "@lincoln504/pi-research", "engine": "pi-research-sdk", "openclaw": { "requires": { "bins": ["node"] } } }
5
+ metadata: { "author": "Lincoln Deen", "version": "1.7.22", "package": "@lincoln504/pi-research", "engine": "pi-research-sdk", "openclaw": { "requires": { "bins": ["node"] } } }
6
6
  allowed-tools: Bash(node:*)
7
7
  ---
8
8
 
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;
@@ -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
 
@@ -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}`);
@@ -11284,6 +11325,45 @@ var SchedulerService = class {
11284
11325
  init_service_registry();
11285
11326
  init_service_interfaces();
11286
11327
  init_logger();
11328
+ init_metrics();
11329
+
11330
+ // src/utils/provider-errors.ts
11331
+ function isSpentAccountError(error) {
11332
+ const msg2 = (error instanceof Error ? error.message : String(error)).toLowerCase();
11333
+ 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");
11334
+ }
11335
+ function isRateLimitError(error) {
11336
+ if (isSpentAccountError(error)) return false;
11337
+ const msg2 = (error instanceof Error ? error.message : String(error)).toLowerCase();
11338
+ return /\b429\b/.test(msg2) || msg2.includes("rate limit") || msg2.includes("rate-limit") || msg2.includes("rate limited") || msg2.includes("too many requests") || msg2.includes("engine_overloaded") || msg2.includes("provider_overloaded");
11339
+ }
11340
+ function isCapacityFailureReason(reason) {
11341
+ return reason !== void 0 && reason !== "" && isRateLimitError(reason);
11342
+ }
11343
+ function parseRetryAfterMs(error) {
11344
+ const message = error instanceof Error ? error.message : String(error);
11345
+ const m = /["']?retry-after["']?\s*[:=]\s*["']?(\d{1,4})/i.exec(message);
11346
+ if (!m) return null;
11347
+ const seconds = Number(m[1]);
11348
+ if (!Number.isFinite(seconds) || seconds <= 0) return null;
11349
+ return Math.min(Math.max(seconds, 5), 60) * 1e3;
11350
+ }
11351
+ var RATE_LIMIT_BACKOFF_BASE_MS = 15e3;
11352
+ var RATE_LIMIT_BACKOFF_MAX_MS = 6e4;
11353
+ function rateLimitBackoffMs(attempt, retryAfterMs, random = Math.random) {
11354
+ if (retryAfterMs !== null && Number.isFinite(retryAfterMs) && retryAfterMs > 0) {
11355
+ return clampRateLimitWait(retryAfterMs);
11356
+ }
11357
+ const exponent = Math.max(0, attempt - 2);
11358
+ const base = Math.min(RATE_LIMIT_BACKOFF_BASE_MS * Math.pow(2, exponent), RATE_LIMIT_BACKOFF_MAX_MS);
11359
+ const jitter = base * 0.2 * (random() * 2 - 1);
11360
+ return clampRateLimitWait(base + jitter);
11361
+ }
11362
+ function clampRateLimitWait(ms) {
11363
+ return Math.min(Math.max(Math.round(ms), 1e3), RATE_LIMIT_BACKOFF_MAX_MS);
11364
+ }
11365
+
11366
+ // src/core/planning-service.ts
11287
11367
  init_pi_ai_completion();
11288
11368
 
11289
11369
  // src/core/llm/inject-date.ts
@@ -11960,6 +12040,12 @@ function generateResearchers(plan, _query, _complexity) {
11960
12040
 
11961
12041
  // src/core/planning-service.ts
11962
12042
  var LLM_MAX_RETRIES = 2;
12043
+ function rateLimitDelayFor(nextAttempt, error) {
12044
+ if (!isRateLimitError(error)) return null;
12045
+ const delay2 = rateLimitBackoffMs(nextAttempt, parseRetryAfterMs(error));
12046
+ metrics.increment("planning_rate_limit_backoff_total", 1, { nextAttempt: String(nextAttempt) });
12047
+ return delay2;
12048
+ }
11963
12049
  var LLM_RETRY_INITIAL_DELAY_MS = 1e3;
11964
12050
  var LLM_RETRY_MAX_DELAY_MS = 8e3;
11965
12051
  var ROUTER_MAX_TOKENS = 8192;
@@ -12206,7 +12292,8 @@ Respond by calling the ${submitPlanTool.name} tool with the plan as its argument
12206
12292
  maxDelay: LLM_RETRY_MAX_DELAY_MS,
12207
12293
  label: "coordinator-generatePlan",
12208
12294
  signal,
12209
- isTransientError: (err) => isRetriableLlmError(err, signal)
12295
+ isTransientError: (err) => isRetriableLlmError(err, signal),
12296
+ delayFor: rateLimitDelayFor
12210
12297
  }
12211
12298
  );
12212
12299
  recordLlmUsage(model, response.usage, { component: "coordinator", complexity, observer });
@@ -12620,7 +12707,8 @@ Respond by calling the ${submitRoutingTool.name} tool with the updated plan as i
12620
12707
  maxDelay: LLM_RETRY_MAX_DELAY_MS,
12621
12708
  label,
12622
12709
  signal,
12623
- isTransientError: (err) => isRetriableLlmError(err, signal)
12710
+ isTransientError: (err) => isRetriableLlmError(err, signal),
12711
+ delayFor: rateLimitDelayFor
12624
12712
  }
12625
12713
  );
12626
12714
  recordLlmUsage(model, response.usage, { component: args.component, complexity, observer });
@@ -24486,25 +24574,69 @@ function getFailedResearchers(piSessionId, researchId) {
24486
24574
  return [...new Set(failures)];
24487
24575
  }
24488
24576
  var DEFAULT_MAX_FAILED_RESEARCHERS = 2;
24577
+ function countTowardStopThreshold(reasons, researcherId) {
24578
+ return !isCapacityFailureReason(reasons?.get(researcherId));
24579
+ }
24580
+ function hasOnlyCapacityFailures(piSessionId, researchId) {
24581
+ const sid = normalizeSessionId(piSessionId);
24582
+ const failed = getFailedResearchers(sid, researchId);
24583
+ if (failed.length === 0) return false;
24584
+ const reasons = peekPiState(sid)?.failureReasons.get(researchId);
24585
+ return failed.every((id) => isCapacityFailureReason(reasons?.get(id)));
24586
+ }
24489
24587
  function shouldStopResearch(piSessionId, researchId, maxFailedResearchers = DEFAULT_MAX_FAILED_RESEARCHERS) {
24490
24588
  const sid = normalizeSessionId(piSessionId);
24491
- return getFailedResearchers(sid, researchId).length >= maxFailedResearchers;
24589
+ const failed = getFailedResearchers(sid, researchId);
24590
+ if (failed.length === 0) return false;
24591
+ const reasons = peekPiState(sid)?.failureReasons.get(researchId);
24592
+ const counted = failed.filter((id) => countTowardStopThreshold(reasons, id));
24593
+ if (counted.length !== failed.length) {
24594
+ logger.debug(
24595
+ `[ResearchSessionState] ${failed.length - counted.length} capacity failure(s) excluded from the stop threshold (${counted.length}/${maxFailedResearchers} counted: ${counted.join(", ") || "none"})`
24596
+ );
24597
+ }
24598
+ return counted.length >= maxFailedResearchers;
24492
24599
  }
24493
24600
  function getResearchStopMessage(piSessionId, researchId) {
24494
24601
  const sid = normalizeSessionId(piSessionId);
24495
24602
  const failed = getFailedResearchers(sid, researchId);
24496
- const count = failed.length;
24603
+ const stateForReasons = peekPiState(sid);
24604
+ const reasonsForCount = stateForReasons?.failureReasons.get(researchId);
24605
+ const countedFailures = failed.filter((id) => countTowardStopThreshold(reasonsForCount, id));
24606
+ const capacityFailures = failed.filter((id) => !countTowardStopThreshold(reasonsForCount, id));
24607
+ const count = countedFailures.length;
24608
+ const failedList = countedFailures.length > 0 ? countedFailures.join(", ") : failed.join(", ");
24497
24609
  const state = peekPiState(sid);
24498
24610
  const reasons = state?.failureReasons.get(researchId);
24499
24611
  const recorded = reasons && reasons.size > 0 ? ["Recorded errors:", ...[...reasons].map(([id, r]) => `\u2022 researcher ${id}: ${r}`), ""] : [];
24612
+ 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
24613
  return [
24501
- `Research stopped: ${count} researcher(s) did not return a usable report: ${failed.join(", ")}.`,
24614
+ headline,
24502
24615
  "",
24616
+ ...capacityFailures.length > 0 ? [
24617
+ `Provider capacity failures (excluded from the stop threshold): ${capacityFailures.join(", ")}.`,
24618
+ "Those researchers lost every retry to a rate limit or an exhausted in-flight budget,",
24619
+ "not to anything about the topic. Retrying the run later is the repair.",
24620
+ ""
24621
+ ] : [],
24503
24622
  ...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.",
24623
+ // Only give the "get a better model" advice when the model's output was actually the
24624
+ // problem. When every failure was the provider refusing to serve (a rate limit or an
24625
+ // exhausted budget), the model never ran — telling the user to change models sends
24626
+ // them to buy a different one for a supply problem.
24627
+ ...capacityFailures.length > 0 && capacityFailures.length === failed.length ? [
24628
+ "Most likely cause \u2014 the provider would not serve the requests:",
24629
+ "\u2022 Every researcher lost its retries to a rate limit or an exhausted in-flight budget.",
24630
+ "\u2022 Wait and retry. A shared/free upstream pool (OpenRouter free tier, for one) is",
24631
+ " routinely overloaded, and nothing about your setup needs to change.",
24632
+ "\u2022 If it keeps happening, set PI_RESEARCH_MODEL to a model with a dedicated key or",
24633
+ " a provider that is not sharing a pool."
24634
+ ] : [
24635
+ "Most likely cause \u2014 the research model could not produce grounded results:",
24636
+ '\u2022 Try a more capable research model. Very small or "thinking-only" models often',
24637
+ " emit no final text after their tool calls, which fails every researcher.",
24638
+ "\u2022 Verify the model is available and the API key / context settings are valid."
24639
+ ],
24508
24640
  "",
24509
24641
  "Less likely \u2014 a network or browser problem (only if the health check did NOT pass):",
24510
24642
  "\u2022 Verify the network connection is active.",
@@ -24523,21 +24655,12 @@ function createResearchStopError(piSessionId, researchId) {
24523
24655
 
24524
24656
  // src/orchestration/researcher-executor.ts
24525
24657
  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");
24658
+ return isSpentAccountError(error);
24528
24659
  }
24529
24660
  function isInFlightBudgetError(error) {
24530
24661
  const lower = (error instanceof Error ? error.message : String(error)).toLowerCase();
24531
24662
  return lower.includes("in_flight_budget_exhausted") || lower.includes("would exceed your available credits given your current in-flight requests");
24532
24663
  }
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
24664
  async function runResearcher(options) {
24542
24665
  const {
24543
24666
  config: researcherConfig,
@@ -24882,10 +25005,16 @@ ${responseText}`);
24882
25005
  metrics.increment("researcher_unretriable_total", 1, { mode: "deep", complexity: String(complexity) });
24883
25006
  break;
24884
25007
  }
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}`);
25008
+ if (attempt < maxAttempts) {
25009
+ if (isInFlightBudgetError(err)) {
25010
+ inFlightBackoffMs = parseRetryAfterMs(err) ?? 15e3;
25011
+ metrics.increment("researcher_inflight_budget_backoff_total", 1, { mode: "deep", complexity: String(complexity) });
25012
+ 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}`);
25013
+ } else if (isRateLimitError(err)) {
25014
+ inFlightBackoffMs = rateLimitBackoffMs(attempt + 1, parseRetryAfterMs(err));
25015
+ metrics.increment("researcher_rate_limit_backoff_total", 1, { mode: "deep", complexity: String(complexity) });
25016
+ logger.warn(`[ResearcherExecutor] Researcher ${id} hit a provider rate limit; backing off ${inFlightBackoffMs}ms before attempt ${attempt + 1}`);
25017
+ }
24889
25018
  }
24890
25019
  if (attempt < maxAttempts) {
24891
25020
  logger.warn(`[ResearcherExecutor] Researcher ${id} attempt ${attempt} failed: ${errMsg}; will retry`);
@@ -25448,6 +25577,41 @@ init_text_utils();
25448
25577
  init_service_interfaces();
25449
25578
  init_service_registry();
25450
25579
  init_config();
25580
+
25581
+ // src/core/llm/coordinator-model.ts
25582
+ function parseCoordinatorModelChoice(value) {
25583
+ const raw = (value ?? "").trim();
25584
+ if (raw === "" || raw.toLowerCase() === "host") return { kind: "host" };
25585
+ if (raw.toLowerCase() === "research") return { kind: "research" };
25586
+ return { kind: "explicit", reference: raw };
25587
+ }
25588
+ function resolveCoordinatorModel(options) {
25589
+ const { setting, hostModel, researchModel, findByReference, onUnresolved } = options;
25590
+ const choice = parseCoordinatorModelChoice(setting);
25591
+ switch (choice.kind) {
25592
+ case "research":
25593
+ return researchModel;
25594
+ case "explicit": {
25595
+ const found = findByReference?.(choice.reference);
25596
+ if (found) return found;
25597
+ onUnresolved?.(choice.reference);
25598
+ return researchModel;
25599
+ }
25600
+ case "host":
25601
+ default:
25602
+ return hostModel ?? researchModel;
25603
+ }
25604
+ }
25605
+ function findModelByReference(reference, models, available = []) {
25606
+ const exact = available.find((m) => `${m.provider}/${m.id}` === reference) ?? models.find((m) => `${m.provider}/${m.id}` === reference);
25607
+ if (exact) return exact;
25608
+ const sameId = models.filter((m) => m.id === reference);
25609
+ if (sameId.length === 0) return void 0;
25610
+ const authed = new Set(available.map((m) => `${m.provider}/${m.id}`));
25611
+ return sameId.find((m) => authed.has(`${m.provider}/${m.id}`)) ?? sameId[0];
25612
+ }
25613
+
25614
+ // src/orchestration/deep-research-orchestrator.ts
25451
25615
  var DeepResearchOrchestrator = class {
25452
25616
  constructor(options) {
25453
25617
  this.options = options;
@@ -25492,7 +25656,27 @@ var DeepResearchOrchestrator = class {
25492
25656
  const { model, query, complexity, researchId, ctx } = this.options;
25493
25657
  const observer = this.observer;
25494
25658
  const container = tryGetServiceContainerFromCtx(ctx);
25495
- const initialCoordinatorModel = ctx.model ?? model;
25659
+ const initialCoordinatorModel = resolveCoordinatorModel({
25660
+ setting: this.config.COORDINATOR_MODEL,
25661
+ hostModel: ctx.model,
25662
+ researchModel: model,
25663
+ // STRICT lookup (never resolveResearchModel): that resolver always returns a
25664
+ // model — it falls back through RESEARCH_MODEL to "first available" — so a typo
25665
+ // would silently run on an arbitrary model AND never trigger onUnresolved.
25666
+ findByReference: (reference) => {
25667
+ try {
25668
+ const registry = ctx.modelRegistry;
25669
+ const all = registry?.getAll?.() ?? [];
25670
+ const available = registry?.getAvailable?.() ?? [];
25671
+ return findModelByReference(reference, all, available);
25672
+ } catch {
25673
+ return void 0;
25674
+ }
25675
+ },
25676
+ onUnresolved: (reference) => logger.warn(
25677
+ `[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).`
25678
+ )
25679
+ });
25496
25680
  const evaluatorModel = model;
25497
25681
  const orchestrationService = await this.getOrchestrationService();
25498
25682
  const planningService = await this.getPlanningService();
@@ -25513,6 +25697,7 @@ var DeepResearchOrchestrator = class {
25513
25697
  }
25514
25698
  const MAX_WAIT_RETRIES = 5;
25515
25699
  let waitRetryCount = 0;
25700
+ let capacityOnlyRounds = 0;
25516
25701
  let routerChoseSynthesis = false;
25517
25702
  let lastAnnouncedRound = 0;
25518
25703
  try {
@@ -25641,12 +25826,20 @@ var DeepResearchOrchestrator = class {
25641
25826
  continue;
25642
25827
  }
25643
25828
  waitRetryCount = 0;
25829
+ if (shouldStopResearch(this.options.sessionId, researchId, this.config.MAX_FAILED_RESEARCHERS)) {
25830
+ throw createResearchStopError(this.options.sessionId, researchId);
25831
+ }
25644
25832
  if (plan.action === "delegate" && plan.researchers && plan.researchers.length > 0) {
25645
25833
  planningService.incrementTotalResearchersPlanned(researchId, plan.researchers.length);
25646
25834
  }
25647
25835
  if (plan.allQueries && plan.allQueries.length > 0) {
25648
25836
  planningService.addToQueryHistory(researchId, plan.allQueries);
25649
25837
  }
25838
+ const reportsBeforeRound = (await getService(
25839
+ ServiceNames.RESEARCH_SYNTHESIS_SERVICE,
25840
+ ctx,
25841
+ container
25842
+ )).getReportCount(researchId);
25650
25843
  let researcherLinks;
25651
25844
  let storeLinks;
25652
25845
  const searchTask = plan.allQueries && plan.allQueries.length > 0 ? (async () => {
@@ -25708,6 +25901,22 @@ var DeepResearchOrchestrator = class {
25708
25901
  currentRound: this.currentRound,
25709
25902
  signal
25710
25903
  }, researcherLinks, storeLinks);
25904
+ const reportsAfterRound = (await getService(
25905
+ ServiceNames.RESEARCH_SYNTHESIS_SERVICE,
25906
+ ctx,
25907
+ container
25908
+ )).getReportCount(researchId);
25909
+ if (reportsAfterRound <= reportsBeforeRound && hasOnlyCapacityFailures(this.options.sessionId, researchId)) {
25910
+ capacityOnlyRounds++;
25911
+ logger.warn(
25912
+ `[DeepOrchestrator] Round ${this.currentRound} produced no report and every failure was a provider capacity failure (${capacityOnlyRounds} consecutive, 1 tolerated)`
25913
+ );
25914
+ if (capacityOnlyRounds > 1) {
25915
+ throw createResearchStopError(this.options.sessionId, researchId);
25916
+ }
25917
+ } else {
25918
+ capacityOnlyRounds = 0;
25919
+ }
25711
25920
  }
25712
25921
  if (signal?.aborted) throw new Error("Research aborted");
25713
25922
  observer?.onEvaluationProgress?.("embedding");
@@ -26668,9 +26877,15 @@ var ResearchSynthesisService = class _ResearchSynthesisService {
26668
26877
  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
26878
 
26670
26879
  `;
26671
- synthesis += Array.from(reports.entries()).map(([id, report]) => `Researcher ${id}
26672
-
26673
- ${report}`).join("\n\n");
26880
+ synthesis += Array.from(reports.entries()).map(([key, report]) => {
26881
+ const dot = key.indexOf(".");
26882
+ const round = dot > 0 ? key.slice(0, dot) : "";
26883
+ const researcherId = dot > 0 ? key.slice(dot + 1) : key;
26884
+ const label = round && /^\d+$/.test(round) ? `Researcher ${researcherId} (round ${round})` : `Researcher ${key}`;
26885
+ return `${label}
26886
+
26887
+ ${report}`;
26888
+ }).join("\n\n");
26674
26889
  }
26675
26890
  return synthesis;
26676
26891
  }