@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.
- package/agent-skill/pi-research/SKILL.md +1 -1
- package/dist/cli.mjs +344 -129
- package/dist/thread-worker.mjs +75 -31
- package/docs/CHANGELOG.md +17 -0
- package/docs/CONFIGURATION.md +4 -3
- package/docs/TROUBLESHOOTING.md +16 -0
- package/package.json +3 -1
- package/scripts/ddg-socks-proxy.mjs +256 -0
- package/scripts/lib/private-addresses.mjs +129 -0
- package/src/config.ts +75 -2
- package/src/core/interfaces/steering-interfaces.ts +11 -0
- package/src/core/llm/coordinator-model.ts +104 -0
- package/src/core/planning-service.ts +24 -0
- package/src/index.ts +7 -1
- package/src/infrastructure/browser/proxy-prefs.ts +113 -0
- package/src/infrastructure/browser/thread-worker-browser.ts +5 -21
- package/src/infrastructure/browser/thread-worker-messaging.ts +7 -2
- package/src/infrastructure/browser/thread-worker.mjs +75 -31
- package/src/orchestration/deep-research-orchestrator.ts +71 -2
- package/src/orchestration/research-synthesis-service.ts +14 -1
- package/src/orchestration/researcher-executor.ts +33 -33
- package/src/orchestration/session-state.ts +155 -7
- package/src/tui/tui-controller.ts +25 -1
- package/src/utils/provider-errors.ts +149 -0
- package/src/web-research/retry-utils.ts +21 -2
|
@@ -10,6 +10,7 @@ import { appendFileSync, promises as fsp } from 'node:fs';
|
|
|
10
10
|
import { redactSecrets } from '../../utils/log-utils.ts';
|
|
11
11
|
import { safeUnref } from '../../utils/safe-unref.ts';
|
|
12
12
|
import { MAX_HTML_SIZE, MAX_PDF_SIZE } from '../../web-research/scraper-types.ts';
|
|
13
|
+
import { isProxyHopAddress } from './proxy-prefs.ts';
|
|
13
14
|
|
|
14
15
|
/**
|
|
15
16
|
* Mutex lock to serialize page creation. Playwright/Firefox can deadlock if newPage()
|
|
@@ -824,6 +825,10 @@ export async function executeScrapeTask(
|
|
|
824
825
|
.then((addr: { ipAddress?: string } | null) => {
|
|
825
826
|
const ip = addr?.ipAddress;
|
|
826
827
|
if (!ip || poisonedError) return;
|
|
828
|
+
// Through the configured SOCKS proxy Firefox reports the proxy hop
|
|
829
|
+
// (`0.0.0.0`), not the origin — validating that as if it were the
|
|
830
|
+
// origin condemned every proxied scrape. See isProxyHopAddress.
|
|
831
|
+
if (isProxyHopAddress(ip)) return;
|
|
827
832
|
try {
|
|
828
833
|
validateForWorkerSync(ip.includes(':') ? `http://[${ip}]/` : `http://${ip}/`);
|
|
829
834
|
} catch (cause: unknown) {
|
|
@@ -879,7 +884,7 @@ export async function executeScrapeTask(
|
|
|
879
884
|
// prevent the TCP connection itself, but it stops the rendered response (e.g. cloud IAM
|
|
880
885
|
// credentials) from being exfiltrated to the researcher/report, which is the real harm here.
|
|
881
886
|
const serverAddr = await response?.serverAddr().catch(() => null);
|
|
882
|
-
if (serverAddr?.ipAddress) {
|
|
887
|
+
if (serverAddr?.ipAddress && !isProxyHopAddress(serverAddr.ipAddress)) {
|
|
883
888
|
const ip: string = serverAddr.ipAddress;
|
|
884
889
|
validateForWorkerSync(ip.includes(':') ? `http://[${ip}]/` : `http://${ip}/`);
|
|
885
890
|
}
|
|
@@ -1037,7 +1042,7 @@ export async function executeScrapeTask(
|
|
|
1037
1042
|
// Re-validate the final rendered main-frame document's connected IP (catches a client-side
|
|
1038
1043
|
// navigation to a DNS-rebinding host that occurred after the initial goto passed).
|
|
1039
1044
|
const finalAddr = await finalMainFrameAddr;
|
|
1040
|
-
if (finalAddr?.ipAddress) {
|
|
1045
|
+
if (finalAddr?.ipAddress && !isProxyHopAddress(finalAddr.ipAddress)) {
|
|
1041
1046
|
const fip: string = finalAddr.ipAddress;
|
|
1042
1047
|
validateForWorkerSync(fip.includes(':') ? `http://[${fip}]/` : `http://${fip}/`);
|
|
1043
1048
|
}
|
|
@@ -891,7 +891,7 @@ var init_stdio_capture = __esm({
|
|
|
891
891
|
});
|
|
892
892
|
|
|
893
893
|
// src/logger.ts
|
|
894
|
-
import { appendFileSync, existsSync as
|
|
894
|
+
import { appendFileSync, existsSync as existsSync3, mkdirSync, openSync as openSync2, closeSync as closeSync2 } from "node:fs";
|
|
895
895
|
import { appendFile as appendFile2 } from "node:fs/promises";
|
|
896
896
|
import { AsyncLocalStorage as AsyncLocalStorage3 } from "node:async_hooks";
|
|
897
897
|
import * as path3 from "node:path";
|
|
@@ -1047,7 +1047,7 @@ var init_logger = __esm({
|
|
|
1047
1047
|
this.rotation = new LogRotation(this);
|
|
1048
1048
|
this.diskSpaceChecker = new DiskSpaceChecker();
|
|
1049
1049
|
try {
|
|
1050
|
-
if (!
|
|
1050
|
+
if (!existsSync3(this.logDir)) {
|
|
1051
1051
|
mkdirSync(this.logDir, { recursive: true, mode: 448 });
|
|
1052
1052
|
}
|
|
1053
1053
|
try {
|
|
@@ -1721,8 +1721,8 @@ async function disposeSsrfSafeFetcher() {
|
|
|
1721
1721
|
const pending = cachedSsrfFetcher;
|
|
1722
1722
|
cachedSsrfFetcher = void 0;
|
|
1723
1723
|
if (pending === void 0) return;
|
|
1724
|
-
const
|
|
1725
|
-
const closable =
|
|
1724
|
+
const cached2 = await pending.catch(() => null);
|
|
1725
|
+
const closable = cached2?.dispatcher;
|
|
1726
1726
|
if (!closable?.close) return;
|
|
1727
1727
|
try {
|
|
1728
1728
|
await closable.close();
|
|
@@ -2102,8 +2102,55 @@ function createKillHandler() {
|
|
|
2102
2102
|
|
|
2103
2103
|
// src/infrastructure/browser/thread-worker-browser.ts
|
|
2104
2104
|
import { platform as platform2 } from "node:os";
|
|
2105
|
-
|
|
2106
|
-
|
|
2105
|
+
|
|
2106
|
+
// src/infrastructure/browser/proxy-prefs.ts
|
|
2107
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
2108
|
+
import { homedir } from "node:os";
|
|
2109
|
+
function proxyConfigPath() {
|
|
2110
|
+
return process.env["PI_RESEARCH_PROXY_JSON"] || `${homedir()}/.pi/research/proxy.json`;
|
|
2111
|
+
}
|
|
2112
|
+
var cached;
|
|
2113
|
+
var cachedAt = 0;
|
|
2114
|
+
var CACHE_TTL_MS = 1e4;
|
|
2115
|
+
function getSocksProxyEndpoint() {
|
|
2116
|
+
const now = Date.now();
|
|
2117
|
+
if (cached !== void 0 && now - cachedAt < CACHE_TTL_MS) return cached;
|
|
2118
|
+
cachedAt = now;
|
|
2119
|
+
try {
|
|
2120
|
+
const file = proxyConfigPath();
|
|
2121
|
+
if (!existsSync(file)) {
|
|
2122
|
+
cached = null;
|
|
2123
|
+
return cached;
|
|
2124
|
+
}
|
|
2125
|
+
const cfg = JSON.parse(readFileSync(file, "utf8"));
|
|
2126
|
+
const host = cfg.host ?? "127.0.0.1";
|
|
2127
|
+
const port = cfg.port ?? 1080;
|
|
2128
|
+
cached = host ? { host, port } : null;
|
|
2129
|
+
return cached;
|
|
2130
|
+
} catch {
|
|
2131
|
+
cached = null;
|
|
2132
|
+
return cached;
|
|
2133
|
+
}
|
|
2134
|
+
}
|
|
2135
|
+
function loadSocksProxyPrefs() {
|
|
2136
|
+
const endpoint = getSocksProxyEndpoint();
|
|
2137
|
+
if (!endpoint) return {};
|
|
2138
|
+
return {
|
|
2139
|
+
"network.proxy.type": 1,
|
|
2140
|
+
"network.proxy.socks": endpoint.host,
|
|
2141
|
+
"network.proxy.socks_port": endpoint.port,
|
|
2142
|
+
"network.proxy.socks_remote_dns": true,
|
|
2143
|
+
"network.proxy.socks_version": 5,
|
|
2144
|
+
"network.proxy.no_proxies_on": ""
|
|
2145
|
+
};
|
|
2146
|
+
}
|
|
2147
|
+
function isProxyHopAddress(ip, proxy = getSocksProxyEndpoint()) {
|
|
2148
|
+
if (!proxy) return false;
|
|
2149
|
+
const addr = ip.trim().toLowerCase().replace(/^\[|\]$/g, "");
|
|
2150
|
+
if (addr === "" || addr === "0.0.0.0" || addr === "::" || addr === "::0") return true;
|
|
2151
|
+
const proxyHost = proxy.host.trim().toLowerCase().replace(/^\[|\]$/g, "");
|
|
2152
|
+
return addr === proxyHost;
|
|
2153
|
+
}
|
|
2107
2154
|
|
|
2108
2155
|
// src/infrastructure/browser/thread-worker-messaging.ts
|
|
2109
2156
|
init_log_utils();
|
|
@@ -2403,8 +2450,8 @@ function getCachedSubresourceVerdict(reqUrl, validate) {
|
|
|
2403
2450
|
return Promise.resolve(e instanceof Error ? e : new Error(String(e)));
|
|
2404
2451
|
}
|
|
2405
2452
|
const now = Date.now();
|
|
2406
|
-
const
|
|
2407
|
-
if (
|
|
2453
|
+
const cached2 = subresourceDnsVerdicts.get(hostname);
|
|
2454
|
+
if (cached2 && cached2.expires > now) return cached2.verdict;
|
|
2408
2455
|
const verdict = validate(reqUrl).then(
|
|
2409
2456
|
() => null,
|
|
2410
2457
|
(e) => e instanceof Error ? e : new Error(String(e))
|
|
@@ -2565,6 +2612,7 @@ async function executeScrapeTask(_context, url, signal) {
|
|
|
2565
2612
|
const check = Promise.resolve(resp.serverAddr()).then((addr) => {
|
|
2566
2613
|
const ip = addr?.ipAddress;
|
|
2567
2614
|
if (!ip || poisonedError) return;
|
|
2615
|
+
if (isProxyHopAddress(ip)) return;
|
|
2568
2616
|
try {
|
|
2569
2617
|
validateForWorkerSync(ip.includes(":") ? `http://[${ip}]/` : `http://${ip}/`);
|
|
2570
2618
|
} catch (cause) {
|
|
@@ -2602,7 +2650,7 @@ async function executeScrapeTask(_context, url, signal) {
|
|
|
2602
2650
|
return await readPdfDownload(pendingDownload, url, page, pendingAddrChecks, () => poisonedError);
|
|
2603
2651
|
}
|
|
2604
2652
|
const serverAddr = await response?.serverAddr().catch(() => null);
|
|
2605
|
-
if (serverAddr?.ipAddress) {
|
|
2653
|
+
if (serverAddr?.ipAddress && !isProxyHopAddress(serverAddr.ipAddress)) {
|
|
2606
2654
|
const ip = serverAddr.ipAddress;
|
|
2607
2655
|
validateForWorkerSync(ip.includes(":") ? `http://[${ip}]/` : `http://${ip}/`);
|
|
2608
2656
|
}
|
|
@@ -2671,7 +2719,7 @@ async function executeScrapeTask(_context, url, signal) {
|
|
|
2671
2719
|
const jitter = process.env["PI_RESEARCH_MOCK_SCRAPE"] === "true" ? 0 : Math.floor(Math.random() * 1e3) + 500;
|
|
2672
2720
|
if (jitter > 0) await new Promise((r) => setTimeout(r, jitter));
|
|
2673
2721
|
const finalAddr = await finalMainFrameAddr;
|
|
2674
|
-
if (finalAddr?.ipAddress) {
|
|
2722
|
+
if (finalAddr?.ipAddress && !isProxyHopAddress(finalAddr.ipAddress)) {
|
|
2675
2723
|
const fip = finalAddr.ipAddress;
|
|
2676
2724
|
validateForWorkerSync(fip.includes(":") ? `http://[${fip}]/` : `http://${fip}/`);
|
|
2677
2725
|
}
|
|
@@ -2749,7 +2797,7 @@ function shouldResetBrowser(errorMsg) {
|
|
|
2749
2797
|
init_log_utils();
|
|
2750
2798
|
|
|
2751
2799
|
// src/infrastructure/browser/config.ts
|
|
2752
|
-
import { platform, homedir } from "node:os";
|
|
2800
|
+
import { platform, homedir as homedir2 } from "node:os";
|
|
2753
2801
|
|
|
2754
2802
|
// src/config.ts
|
|
2755
2803
|
init_logger();
|
|
@@ -11368,9 +11416,24 @@ var ConfigSchema = typebox_exports.Object({
|
|
|
11368
11416
|
* When set, this governs the evaluator/synthesis rounds and the researcher
|
|
11369
11417
|
* sub-agents (both deep and quick) and the knowledge synthesis background LLM.
|
|
11370
11418
|
* The initial coordinator (round 1 planning) uses the parent chat's model (ctx.model)
|
|
11371
|
-
* for prompt-cache continuity with the conversation that triggered
|
|
11419
|
+
* by DEFAULT, for prompt-cache continuity with the conversation that triggered
|
|
11420
|
+
* research; COORDINATOR_MODEL overrides that decision (see below).
|
|
11372
11421
|
*/
|
|
11373
11422
|
RESEARCH_MODEL: typebox_exports.Optional(typebox_exports.String()),
|
|
11423
|
+
/**
|
|
11424
|
+
* Which model runs the INITIAL coordinator (round-1 planning), the one call that
|
|
11425
|
+
* otherwise uses the parent chat's model (`ctx.model`) for prompt-cache continuity:
|
|
11426
|
+
* • `host` (default) — the chat's model, current behaviour.
|
|
11427
|
+
* • `research` — the RESEARCH_MODEL / researcher model, same as every later round.
|
|
11428
|
+
* • `provider/id` (or a bare id) — that model.
|
|
11429
|
+
*
|
|
11430
|
+
* Exists because the chat model is not always a good planner: a local single-seat
|
|
11431
|
+
* server (llama-swap `concurrencyLimit: 1`, 4k output) turns the coordinator call into
|
|
11432
|
+
* minutes of wall clock and can 429 the owner's own next prompt, while a hosted
|
|
11433
|
+
* research model plans the same query in seconds. The cache-lineage benefit is real
|
|
11434
|
+
* but must be opt-out-able. Unset = `host`.
|
|
11435
|
+
*/
|
|
11436
|
+
COORDINATOR_MODEL: typebox_exports.Optional(typebox_exports.String()),
|
|
11374
11437
|
/** Explicit directory for the knowledge store database (overrides default) */
|
|
11375
11438
|
KNOWLEDGE_STORE_DIR: typebox_exports.Optional(typebox_exports.String()),
|
|
11376
11439
|
/** Directory for transient browser profile data. Defaults to a disk-backed
|
|
@@ -11428,25 +11491,6 @@ var CONTEXT_CREATION_TIMEOUT_MS = 3e4;
|
|
|
11428
11491
|
var COLD_START_ALLOWANCE_MS = BROWSER_LAUNCH_TIMEOUT_MS + CONTEXT_CREATION_TIMEOUT_MS;
|
|
11429
11492
|
|
|
11430
11493
|
// src/infrastructure/browser/thread-worker-browser.ts
|
|
11431
|
-
function loadSocksProxyPrefs() {
|
|
11432
|
-
try {
|
|
11433
|
-
const p = `${homedir2()}/.pi/research/proxy.json`;
|
|
11434
|
-
if (!existsSync3(p)) return {};
|
|
11435
|
-
const cfg = JSON.parse(readFileSync(p, "utf8"));
|
|
11436
|
-
const host = cfg.host ?? "127.0.0.1";
|
|
11437
|
-
const port = cfg.port ?? 1080;
|
|
11438
|
-
return {
|
|
11439
|
-
"network.proxy.type": 1,
|
|
11440
|
-
"network.proxy.socks": host,
|
|
11441
|
-
"network.proxy.socks_port": port,
|
|
11442
|
-
"network.proxy.socks_remote_dns": true,
|
|
11443
|
-
"network.proxy.socks_version": 5,
|
|
11444
|
-
"network.proxy.no_proxies_on": ""
|
|
11445
|
-
};
|
|
11446
|
-
} catch {
|
|
11447
|
-
return {};
|
|
11448
|
-
}
|
|
11449
|
-
}
|
|
11450
11494
|
var browser = null;
|
|
11451
11495
|
var initPromise = null;
|
|
11452
11496
|
var workerId3 = "";
|
|
@@ -8,7 +8,7 @@ import type { ExtensionContext, AgentToolResult } from '@earendil-works/pi-codin
|
|
|
8
8
|
import { type Model } from '@earendil-works/pi-ai';
|
|
9
9
|
import { logger } from '../logger.ts';
|
|
10
10
|
import { metrics } from '../utils/metrics.ts';
|
|
11
|
-
import { getSteeringMessages, consumeQueuedMessages, getActiveSteeringMessages, getFailedResearchers, getResearcherFailureReasons } from './session-state.ts';
|
|
11
|
+
import { getSteeringMessages, consumeQueuedMessages, getActiveSteeringMessages, getFailedResearchers, getResearcherFailureReasons, shouldStopResearch, createResearchStopError, hasOnlyCapacityFailures } from './session-state.ts';
|
|
12
12
|
import { MAX_EXTRA_ROUNDS_WITH_STEERING, MIN_SYNTHESIS_PROSE_CHARS, SYNTHESIS_FALLBACK_NOTICE, resolveExcludedTools } from '../constants.ts';
|
|
13
13
|
import { synthesisProseBody, isAnalysisFreeSynthesis } from '../utils/text-utils.ts';
|
|
14
14
|
import {
|
|
@@ -28,6 +28,7 @@ import {
|
|
|
28
28
|
import { getService, tryGetServiceContainerFromCtx } from '../core/service-registry.ts';
|
|
29
29
|
import { getConfig } from '../config.ts';
|
|
30
30
|
import type { Config } from '../config.ts';
|
|
31
|
+
import { findModelByReference, resolveCoordinatorModel } from '../core/llm/coordinator-model.ts';
|
|
31
32
|
import type { PlanningService } from '../core/planning-service.ts';
|
|
32
33
|
|
|
33
34
|
export interface DeepResearchOrchestratorOptions {
|
|
@@ -111,7 +112,32 @@ export class DeepResearchOrchestrator {
|
|
|
111
112
|
// Later evaluator rounds (round 2+ routing) and final synthesis
|
|
112
113
|
// use the research model (RESEARCH_MODEL override or host model),
|
|
113
114
|
// which is also what the researcher sub-agents use.
|
|
114
|
-
|
|
115
|
+
//
|
|
116
|
+
// PI_RESEARCH_COORDINATOR_MODEL overrides that first call: `research` (or an
|
|
117
|
+
// explicit provider/id) when the chat model is a poor or single-seat planner.
|
|
118
|
+
// See src/core/llm/coordinator-model.ts for the measured case.
|
|
119
|
+
const initialCoordinatorModel = resolveCoordinatorModel<Model<any>>({
|
|
120
|
+
setting: this.config.COORDINATOR_MODEL,
|
|
121
|
+
hostModel: ctx.model as Model<any> | undefined,
|
|
122
|
+
researchModel: model,
|
|
123
|
+
// STRICT lookup (never resolveResearchModel): that resolver always returns a
|
|
124
|
+
// model — it falls back through RESEARCH_MODEL to "first available" — so a typo
|
|
125
|
+
// would silently run on an arbitrary model AND never trigger onUnresolved.
|
|
126
|
+
findByReference: (reference) => {
|
|
127
|
+
try {
|
|
128
|
+
const registry = ctx.modelRegistry;
|
|
129
|
+
const all = (registry?.getAll?.() ?? []) as Model<any>[];
|
|
130
|
+
const available = (registry?.getAvailable?.() ?? []) as Model<any>[];
|
|
131
|
+
return findModelByReference(reference, all, available);
|
|
132
|
+
} catch {
|
|
133
|
+
return undefined;
|
|
134
|
+
}
|
|
135
|
+
},
|
|
136
|
+
onUnresolved: (reference) => logger.warn(
|
|
137
|
+
`[DeepOrchestrator] COORDINATOR_MODEL '${reference}' is not an available model; ` +
|
|
138
|
+
'falling back to the research model (not the chat model, which this setting exists to replace).',
|
|
139
|
+
),
|
|
140
|
+
});
|
|
115
141
|
const evaluatorModel = model;
|
|
116
142
|
|
|
117
143
|
const orchestrationService = await this.getOrchestrationService();
|
|
@@ -162,6 +188,14 @@ export class DeepResearchOrchestrator {
|
|
|
162
188
|
|
|
163
189
|
const MAX_WAIT_RETRIES = 5;
|
|
164
190
|
let waitRetryCount = 0;
|
|
191
|
+
// Rounds that produced ZERO new reports while every failure was a provider-capacity
|
|
192
|
+
// failure. Capacity failures are excluded from shouldStopResearch (one upstream
|
|
193
|
+
// outage must not end a healthy run), which would otherwise keep the run alive for
|
|
194
|
+
// every remaining round — a full search burst each time — against a provider that
|
|
195
|
+
// cannot answer. One such round is tolerated (the outage may clear; the observed one
|
|
196
|
+
// lasted six minutes and each round already spends ~100s in the researcher retries);
|
|
197
|
+
// a second consecutive one stops the run at the fallback synthesis.
|
|
198
|
+
let capacityOnlyRounds = 0;
|
|
165
199
|
// Whether the ROUTER chose to finish inside the loop, as opposed to the loop ending
|
|
166
200
|
// because the round budget ran out. The router never carries the report: it is asked
|
|
167
201
|
// for a decision, is given no corpus to write from (it sees each report once, on the
|
|
@@ -366,6 +400,17 @@ export class DeepResearchOrchestrator {
|
|
|
366
400
|
// Reset wait retry counter on successful actions
|
|
367
401
|
waitRetryCount = 0;
|
|
368
402
|
|
|
403
|
+
// Stop BEFORE the round's search burst when the failure threshold is already
|
|
404
|
+
// crossed. runResearchers performs the same check, but only after the planner
|
|
405
|
+
// and the whole search phase have run: on 2026-10-25 round 2 fanned out 36
|
|
406
|
+
// searches (296 results) that runResearchers then discarded, because round 1
|
|
407
|
+
// had already crossed the threshold. The stop error is identical to the one
|
|
408
|
+
// runResearchers raises, so the run's outcome (fallback synthesis from the
|
|
409
|
+
// reports already collected) does not change — only the wasted work does.
|
|
410
|
+
if (shouldStopResearch(this.options.sessionId, researchId, this.config.MAX_FAILED_RESEARCHERS)) {
|
|
411
|
+
throw createResearchStopError(this.options.sessionId, researchId);
|
|
412
|
+
}
|
|
413
|
+
|
|
369
414
|
// Track how many researchers were planned this round
|
|
370
415
|
// updatePlanForRound has a comment "We'll update totalResearchersPlanned in the orchestrator"
|
|
371
416
|
if (plan.action === 'delegate' && plan.researchers && plan.researchers.length > 0) {
|
|
@@ -377,6 +422,11 @@ export class DeepResearchOrchestrator {
|
|
|
377
422
|
planningService.addToQueryHistory(researchId, plan.allQueries);
|
|
378
423
|
}
|
|
379
424
|
|
|
425
|
+
// Report count BEFORE this round, for the capacity-only grace-round check below.
|
|
426
|
+
const reportsBeforeRound = (await getService<IResearchSynthesisService>(
|
|
427
|
+
ServiceNames.RESEARCH_SYNTHESIS_SERVICE, ctx, container,
|
|
428
|
+
)).getReportCount(researchId);
|
|
429
|
+
|
|
380
430
|
// 2. Search Phase + per-researcher store queries (run in parallel)
|
|
381
431
|
let researcherLinks: Map<string, string[]> | undefined;
|
|
382
432
|
let storeLinks: Map<string, { url: string; description: string }[]> | undefined;
|
|
@@ -456,6 +506,25 @@ export class DeepResearchOrchestrator {
|
|
|
456
506
|
currentRound: this.currentRound,
|
|
457
507
|
signal
|
|
458
508
|
}, researcherLinks, storeLinks);
|
|
509
|
+
|
|
510
|
+
// Did this round produce anything? Report count is cumulative, so a delta is
|
|
511
|
+
// the only honest answer; the failure list is cumulative too, hence the
|
|
512
|
+
// "all recorded failures are capacity" check rather than a per-round one.
|
|
513
|
+
const reportsAfterRound = (await getService<IResearchSynthesisService>(
|
|
514
|
+
ServiceNames.RESEARCH_SYNTHESIS_SERVICE, ctx, container,
|
|
515
|
+
)).getReportCount(researchId);
|
|
516
|
+
if (reportsAfterRound <= reportsBeforeRound && hasOnlyCapacityFailures(this.options.sessionId, researchId)) {
|
|
517
|
+
capacityOnlyRounds++;
|
|
518
|
+
logger.warn(
|
|
519
|
+
`[DeepOrchestrator] Round ${this.currentRound} produced no report and every failure was a provider ` +
|
|
520
|
+
`capacity failure (${capacityOnlyRounds} consecutive, 1 tolerated)`,
|
|
521
|
+
);
|
|
522
|
+
if (capacityOnlyRounds > 1) {
|
|
523
|
+
throw createResearchStopError(this.options.sessionId, researchId);
|
|
524
|
+
}
|
|
525
|
+
} else {
|
|
526
|
+
capacityOnlyRounds = 0;
|
|
527
|
+
}
|
|
459
528
|
}
|
|
460
529
|
|
|
461
530
|
// Esc/abort responsiveness: runResearchers returns NORMALLY when the signal
|
|
@@ -283,8 +283,21 @@ export class ResearchSynthesisService implements IService {
|
|
|
283
283
|
// the second, and telling a user the run was interrupted when it was not is exactly
|
|
284
284
|
// the kind of misleading output this fallback exists to avoid.
|
|
285
285
|
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.\n\n`;
|
|
286
|
+
// Report keys are `${round}.${researcherId}` (see researcher-executor's storeReport),
|
|
287
|
+
// and planner-assigned researcher ids are frequently themselves dotted (`1.1`, `1.2`),
|
|
288
|
+
// so printing the raw key labelled round 1's third researcher as "Researcher 1.1.3" —
|
|
289
|
+
// ambiguous, and read as a researcher that never existed. Print the two fields
|
|
290
|
+
// separately: the round belongs in prose, the id verbatim.
|
|
286
291
|
synthesis += Array.from(reports.entries())
|
|
287
|
-
.map(([
|
|
292
|
+
.map(([key, report]) => {
|
|
293
|
+
const dot = key.indexOf('.');
|
|
294
|
+
const round = dot > 0 ? key.slice(0, dot) : '';
|
|
295
|
+
const researcherId = dot > 0 ? key.slice(dot + 1) : key;
|
|
296
|
+
const label = round && /^\d+$/.test(round)
|
|
297
|
+
? `Researcher ${researcherId} (round ${round})`
|
|
298
|
+
: `Researcher ${key}`;
|
|
299
|
+
return `${label}\n\n${report}`;
|
|
300
|
+
})
|
|
288
301
|
.join('\n\n');
|
|
289
302
|
}
|
|
290
303
|
|
|
@@ -24,6 +24,7 @@ import { isAbortSentinel, boundSessionAbort } from './abort-utils.ts';
|
|
|
24
24
|
import type { RunResearcherOptions } from './orchestration-types.ts';
|
|
25
25
|
import { search } from '../web-research/search.ts';
|
|
26
26
|
import { RESEARCHER_DIGEST_SECTION } from '../utils/coverage-digest.ts';
|
|
27
|
+
import { isRateLimitError, isSpentAccountError, parseRetryAfterMs, rateLimitBackoffMs } from '../utils/provider-errors.ts';
|
|
27
28
|
|
|
28
29
|
/**
|
|
29
30
|
* Failures a retry cannot fix, because the next attempt sends the same request to
|
|
@@ -50,14 +51,13 @@ import { RESEARCHER_DIGEST_SECTION } from '../utils/coverage-digest.ts';
|
|
|
50
51
|
* bounding total retry time rather than by refusing the retry that usually works.
|
|
51
52
|
*/
|
|
52
53
|
export function isUnretriableResearcherError(error: unknown): boolean {
|
|
53
|
-
|
|
54
|
-
//
|
|
55
|
-
//
|
|
56
|
-
//
|
|
57
|
-
//
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|| message.includes('insufficient_quota');
|
|
54
|
+
// Delegated to isSpentAccountError (src/utils/provider-errors.ts) so there is ONE
|
|
55
|
+
// wording list. Both answer the same question — "is this a balance that will not
|
|
56
|
+
// refill?" — and when they drifted, a 429 worded "exceeded your current quota" was
|
|
57
|
+
// retried on the ordinary curve here while the capacity classifier already refused to
|
|
58
|
+
// call it capacity. Both match the provider's wording, never a bare status code: a code
|
|
59
|
+
// can appear inside an unrelated payload, and this gate ends a researcher's run.
|
|
60
|
+
return isSpentAccountError(error);
|
|
61
61
|
}
|
|
62
62
|
|
|
63
63
|
/**
|
|
@@ -75,21 +75,6 @@ export function isInFlightBudgetError(error: unknown): boolean {
|
|
|
75
75
|
|| lower.includes('would exceed your available credits given your current in-flight requests');
|
|
76
76
|
}
|
|
77
77
|
|
|
78
|
-
/**
|
|
79
|
-
* The `Retry-After` a provider error asked for, in ms, clamped to [5s, 60s], or null when
|
|
80
|
-
* the error carries none. Read out of the message because the researcher retry loop sees a
|
|
81
|
-
* serialized provider error, not the raw Response headers: pi's `after_provider_response`
|
|
82
|
-
* hook (src/index.ts) is the only place with headers, and it does not feed this loop.
|
|
83
|
-
*/
|
|
84
|
-
export function parseRetryAfterMs(error: unknown): number | null {
|
|
85
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
86
|
-
const m = /["']?retry-after["']?\s*[:=]\s*["']?(\d{1,4})/i.exec(message);
|
|
87
|
-
if (!m) return null;
|
|
88
|
-
const seconds = Number(m[1]);
|
|
89
|
-
if (!Number.isFinite(seconds) || seconds <= 0) return null;
|
|
90
|
-
return Math.min(Math.max(seconds, 5), 60) * 1000;
|
|
91
|
-
}
|
|
92
|
-
|
|
93
78
|
/**
|
|
94
79
|
* Run a single researcher with retries
|
|
95
80
|
*/
|
|
@@ -244,8 +229,9 @@ export async function runResearcher(options: RunResearcherOptions): Promise<void
|
|
|
244
229
|
.replace('{{digest_section}}', () => RESEARCHER_DIGEST_SECTION)
|
|
245
230
|
.trim();
|
|
246
231
|
|
|
247
|
-
// Set when the previous attempt failed on the provider's in-flight budget
|
|
248
|
-
// backoff uses the provider's Retry-After
|
|
232
|
+
// Set when the previous attempt failed on the provider's in-flight budget or on a
|
|
233
|
+
// rate limit: the next backoff uses the provider's Retry-After (or the long
|
|
234
|
+
// rate-limit step) instead of the small exponential 1-2s step.
|
|
249
235
|
let inFlightBackoffMs: number | null = null;
|
|
250
236
|
|
|
251
237
|
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
|
|
@@ -259,9 +245,13 @@ export async function runResearcher(options: RunResearcherOptions): Promise<void
|
|
|
259
245
|
return;
|
|
260
246
|
}
|
|
261
247
|
if (attempt > 1) {
|
|
262
|
-
// A provider-declared in-flight window overrides the exponential step
|
|
263
|
-
// one attempt: the condition cannot clear in 1-2s, and the provider
|
|
264
|
-
// how long it needs (isInFlightBudgetError / parseRetryAfterMs)
|
|
248
|
+
// A provider-declared rate-limit / in-flight window overrides the exponential step
|
|
249
|
+
// for exactly one attempt: the condition cannot clear in 1-2s, and the provider
|
|
250
|
+
// already said how long it needs (isInFlightBudgetError / parseRetryAfterMs), or —
|
|
251
|
+
// for an unadorned 429 — the rate-limit step (rateLimitBackoffMs) applies instead
|
|
252
|
+
// of the ordinary 1s/2s/4s curve, which cannot outlast a shared-pool limit.
|
|
253
|
+
// RESEARCHER_MAX_RETRY_DELAY_MS caps the ORDINARY step only; it is user-tunable to
|
|
254
|
+
// as little as a second, so it must never shorten a provider-mandated wait.
|
|
265
255
|
const delay = inFlightBackoffMs ?? Math.min(1000 * Math.pow(2, attempt - 2), config.RESEARCHER_MAX_RETRY_DELAY_MS);
|
|
266
256
|
inFlightBackoffMs = null;
|
|
267
257
|
logger.warn(`[ResearcherExecutor] Researcher ${id} retry ${attempt - 1}/${config.RESEARCHER_MAX_RETRIES} after ${delay}ms`);
|
|
@@ -632,12 +622,22 @@ export async function runResearcher(options: RunResearcherOptions): Promise<void
|
|
|
632
622
|
break;
|
|
633
623
|
}
|
|
634
624
|
|
|
635
|
-
// Transient provider
|
|
625
|
+
// Transient provider conditions that need a real wait, not a retry loop: honor the
|
|
636
626
|
// Retry-After it returned (clamped) for the next attempt instead of 1-2s.
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
627
|
+
// • in-flight budget (402): the account's own open requests must settle.
|
|
628
|
+
// • rate limit / 429: the upstream provider's shared pool is full. Observed on
|
|
629
|
+
// 2026-10-25 lasting over six minutes, while four attempts spaced 1s/2s/4s
|
|
630
|
+
// burned out in ~40s and failed two of three researchers.
|
|
631
|
+
if (attempt < maxAttempts) {
|
|
632
|
+
if (isInFlightBudgetError(err)) {
|
|
633
|
+
inFlightBackoffMs = parseRetryAfterMs(err) ?? 15000;
|
|
634
|
+
metrics.increment('researcher_inflight_budget_backoff_total', 1, { mode: 'deep', complexity: String(complexity) });
|
|
635
|
+
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}`);
|
|
636
|
+
} else if (isRateLimitError(err)) {
|
|
637
|
+
inFlightBackoffMs = rateLimitBackoffMs(attempt + 1, parseRetryAfterMs(err));
|
|
638
|
+
metrics.increment('researcher_rate_limit_backoff_total', 1, { mode: 'deep', complexity: String(complexity) });
|
|
639
|
+
logger.warn(`[ResearcherExecutor] Researcher ${id} hit a provider rate limit; backing off ${inFlightBackoffMs}ms before attempt ${attempt + 1}`);
|
|
640
|
+
}
|
|
641
641
|
}
|
|
642
642
|
|
|
643
643
|
if (attempt < maxAttempts) {
|