@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
|
@@ -6,6 +6,7 @@
|
|
|
6
6
|
*/
|
|
7
7
|
|
|
8
8
|
import { generateSessionId as generateUniqueSessionId, clearAllSharedLinks } from '../utils/shared-links.ts';
|
|
9
|
+
import { isCapacityFailureReason } from '../utils/provider-errors.ts';
|
|
9
10
|
import { logger } from '../logger.ts';
|
|
10
11
|
import { getConfig } from '../config.ts';
|
|
11
12
|
import type { ResearchPanelState } from '../types/research-panel-types.ts';
|
|
@@ -176,6 +177,7 @@ export function addSteeringMessage(piSessionId: string | undefined, message: str
|
|
|
176
177
|
addedAt: Date.now(),
|
|
177
178
|
consumedAt: null,
|
|
178
179
|
poppedAt: null,
|
|
180
|
+
forwardedToPiAt: null,
|
|
179
181
|
};
|
|
180
182
|
|
|
181
183
|
logger.debug(`[session-state] Adding steering message to session ${sid}: ${message} (id: ${steeringMsg.id})`);
|
|
@@ -297,10 +299,53 @@ export function requeuePoppedMessage(piSessionId: string | undefined, messageId:
|
|
|
297
299
|
if (!msg) return;
|
|
298
300
|
msg.status = 'queued';
|
|
299
301
|
msg.poppedAt = null;
|
|
302
|
+
msg.forwardedToPiAt = null;
|
|
300
303
|
logger.debug(`[session-state] Restored popped steering message to queued in session ${sid} (id: ${messageId})`);
|
|
301
304
|
refreshAllSessions(sid);
|
|
302
305
|
}
|
|
303
306
|
|
|
307
|
+
/**
|
|
308
|
+
* Record that a popped message was successfully handed to pi's own steering queue
|
|
309
|
+
* (Alt+P). Called only AFTER pi accepted it: a failed forward is requeued instead.
|
|
310
|
+
*/
|
|
311
|
+
export function markSteeringForwardedToPi(piSessionId: string | undefined, messageIds: readonly string[]): void {
|
|
312
|
+
const sid = normalizeSessionId(piSessionId);
|
|
313
|
+
const state = piSessions.get(sid);
|
|
314
|
+
if (!state || messageIds.length === 0) return;
|
|
315
|
+
const now = Date.now();
|
|
316
|
+
const want = new Set(messageIds);
|
|
317
|
+
let marked = 0;
|
|
318
|
+
for (const msg of state.steeringMessages) {
|
|
319
|
+
if (msg.status === 'popped' && want.has(msg.id) && msg.forwardedToPiAt === null) {
|
|
320
|
+
msg.forwardedToPiAt = now;
|
|
321
|
+
marked++;
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
if (marked > 0) {
|
|
325
|
+
logger.debug(`[session-state] Marked ${marked} popped steering message(s) as forwarded to pi in session ${sid}`);
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
/**
|
|
330
|
+
* True while this pi session still has a steering message this extension handed to
|
|
331
|
+
* pi and pi has not necessarily delivered yet.
|
|
332
|
+
*
|
|
333
|
+
* Used by the global TUI controller: while streaming, pi's Esc handler is
|
|
334
|
+
* `restoreQueuedMessagesToEditor({abort:true})`, which CLEARS pi's steering queue,
|
|
335
|
+
* dumps the queued texts into the editor and aborts the turn. A popped message that
|
|
336
|
+
* fell through that path therefore stops being an instruction and a later editor
|
|
337
|
+
* clear loses it. See the Esc branch in tui-controller.ts.
|
|
338
|
+
*
|
|
339
|
+
* Deliberately a per-session read, not per-run: the marker is cleared when the run
|
|
340
|
+
* ends (the message is pruned with the run) or when a new run starts.
|
|
341
|
+
*/
|
|
342
|
+
export function hasForwardedSteering(piSessionId: string | undefined): boolean {
|
|
343
|
+
const sid = normalizeSessionId(piSessionId);
|
|
344
|
+
const state = piSessions.get(sid);
|
|
345
|
+
if (!state) return false;
|
|
346
|
+
return state.steeringMessages.some(m => m.status === 'popped' && m.forwardedToPiAt !== null);
|
|
347
|
+
}
|
|
348
|
+
|
|
304
349
|
/**
|
|
305
350
|
* Clear all steering messages for a Pi session regardless of status.
|
|
306
351
|
*/
|
|
@@ -502,6 +547,12 @@ export function startResearchSession(piSessionId: string | undefined, customRese
|
|
|
502
547
|
const state = getPiState(sid);
|
|
503
548
|
state.failures.set(researchId, []);
|
|
504
549
|
state.failureReasons.set(researchId, new Map());
|
|
550
|
+
// A message forwarded to pi belongs to the run it was popped during: by the time a
|
|
551
|
+
// NEW run starts, pi has had its next agent step and delivered it. Keeping the
|
|
552
|
+
// marker would make the next run's FIRST Esc consume itself for no reason.
|
|
553
|
+
for (const msg of state.steeringMessages) {
|
|
554
|
+
if (msg.forwardedToPiAt !== null) msg.forwardedToPiAt = null;
|
|
555
|
+
}
|
|
505
556
|
return researchId;
|
|
506
557
|
}
|
|
507
558
|
|
|
@@ -683,12 +734,64 @@ export function getFailedResearchers(piSessionId: string | undefined, researchId
|
|
|
683
734
|
*/
|
|
684
735
|
const DEFAULT_MAX_FAILED_RESEARCHERS = 2;
|
|
685
736
|
|
|
737
|
+
/**
|
|
738
|
+
* Failures that must NOT count toward the stop threshold.
|
|
739
|
+
*
|
|
740
|
+
* A provider-capacity failure (429 / upstream pool exhausted / in-flight budget) says
|
|
741
|
+
* nothing about whether the topic is researchable — the same model produces a report
|
|
742
|
+
* once the pool frees up. Counting it lets one upstream outage end an otherwise healthy
|
|
743
|
+
* run: on 2026-10-25 two of three researchers lost every attempt to a DeepInfra
|
|
744
|
+
* `engine_overloaded` 429, the threshold (2) tripped, and the run stopped with one
|
|
745
|
+
* third of its angle set explored and a raw-compilation fallback as the answer.
|
|
746
|
+
* Dropping these from the count keeps the run alive; it is still bounded by the round
|
|
747
|
+
* budget and RESEARCHER_TIMEOUT_MS, and each researcher still owns its own retries.
|
|
748
|
+
*/
|
|
749
|
+
function countTowardStopThreshold(reasons: Map<string, string> | undefined, researcherId: string): boolean {
|
|
750
|
+
return !isCapacityFailureReason(reasons?.get(researcherId));
|
|
751
|
+
}
|
|
752
|
+
|
|
753
|
+
/**
|
|
754
|
+
* True when this run has at least one recorded failure and EVERY one of them is a
|
|
755
|
+
* provider-capacity failure.
|
|
756
|
+
*
|
|
757
|
+
* Run-scoped and de-duplicated by design (`state.failures` keeps unique ids, first reason
|
|
758
|
+
* wins). It answers "has anything in this run failed for a non-capacity reason?", which is
|
|
759
|
+
* the right question when paired with "this round produced no report": a round cannot have
|
|
760
|
+
* produced nothing for a quality reason without recording a quality failure. It cannot
|
|
761
|
+
* attribute a single round, and no caller should read it that way.
|
|
762
|
+
*
|
|
763
|
+
* Used to bound the cost of an outage: capacity failures are excluded from
|
|
764
|
+
* shouldStopResearch, so a total outage would otherwise keep the run alive for every
|
|
765
|
+
* remaining round, paying a full search burst each time against a provider that cannot
|
|
766
|
+
* answer. The orchestrator allows exactly one such empty round (the outage may clear —
|
|
767
|
+
* the observed one lasted six minutes, and each round already spends ~100s in the
|
|
768
|
+
* researcher retries) and stops after a second.
|
|
769
|
+
*/
|
|
770
|
+
export function hasOnlyCapacityFailures(piSessionId: string | undefined, researchId: string): boolean {
|
|
771
|
+
const sid = normalizeSessionId(piSessionId);
|
|
772
|
+
const failed = getFailedResearchers(sid, researchId);
|
|
773
|
+
if (failed.length === 0) return false;
|
|
774
|
+
const reasons = peekPiState(sid)?.failureReasons.get(researchId);
|
|
775
|
+
return failed.every((id) => isCapacityFailureReason(reasons?.get(id)));
|
|
776
|
+
}
|
|
777
|
+
|
|
686
778
|
/**
|
|
687
779
|
* Check if research should stop due to too many unique failures
|
|
688
780
|
*/
|
|
689
781
|
export function shouldStopResearch(piSessionId: string | undefined, researchId: string, maxFailedResearchers: number = DEFAULT_MAX_FAILED_RESEARCHERS): boolean {
|
|
690
782
|
const sid = normalizeSessionId(piSessionId);
|
|
691
|
-
|
|
783
|
+
const failed = getFailedResearchers(sid, researchId);
|
|
784
|
+
if (failed.length === 0) return false;
|
|
785
|
+
// Peek, never create — same read-path rule as getResearcherFailureReasons.
|
|
786
|
+
const reasons = peekPiState(sid)?.failureReasons.get(researchId);
|
|
787
|
+
const counted = failed.filter((id) => countTowardStopThreshold(reasons, id));
|
|
788
|
+
if (counted.length !== failed.length) {
|
|
789
|
+
logger.debug(
|
|
790
|
+
`[ResearchSessionState] ${failed.length - counted.length} capacity failure(s) excluded from the stop threshold ` +
|
|
791
|
+
`(${counted.length}/${maxFailedResearchers} counted: ${counted.join(', ') || 'none'})`,
|
|
792
|
+
);
|
|
793
|
+
}
|
|
794
|
+
return counted.length >= maxFailedResearchers;
|
|
692
795
|
}
|
|
693
796
|
|
|
694
797
|
/**
|
|
@@ -697,7 +800,16 @@ export function shouldStopResearch(piSessionId: string | undefined, researchId:
|
|
|
697
800
|
export function getResearchStopMessage(piSessionId: string | undefined, researchId: string): string {
|
|
698
801
|
const sid = normalizeSessionId(piSessionId);
|
|
699
802
|
const failed = getFailedResearchers(sid, researchId);
|
|
700
|
-
|
|
803
|
+
// Capacity failures do NOT count toward the threshold (see countTowardStopThreshold),
|
|
804
|
+
// so they must not inflate the headline either: it must agree with the rule that
|
|
805
|
+
// actually stopped the run. They are reported separately below, because the user still
|
|
806
|
+
// wants to know the provider refused them.
|
|
807
|
+
const stateForReasons = peekPiState(sid);
|
|
808
|
+
const reasonsForCount = stateForReasons?.failureReasons.get(researchId);
|
|
809
|
+
const countedFailures = failed.filter((id) => countTowardStopThreshold(reasonsForCount, id));
|
|
810
|
+
const capacityFailures = failed.filter((id) => !countTowardStopThreshold(reasonsForCount, id));
|
|
811
|
+
const count = countedFailures.length;
|
|
812
|
+
const failedList = countedFailures.length > 0 ? countedFailures.join(', ') : failed.join(', ');
|
|
701
813
|
|
|
702
814
|
// Order the causes by likelihood. The pre-run health check verifies search and
|
|
703
815
|
// scrape BEFORE researchers run, so when it passed (the normal case) the browser
|
|
@@ -715,14 +827,50 @@ export function getResearchStopMessage(piSessionId: string | undefined, research
|
|
|
715
827
|
? ['Recorded errors:', ...[...reasons].map(([id, r]) => `• researcher ${id}: ${r}`), '']
|
|
716
828
|
: [];
|
|
717
829
|
|
|
830
|
+
// Two headlines, because the two stoppage paths mean different things: a threshold stop
|
|
831
|
+
// has a real count to report; a capacity-only stop (the orchestrator's grace-round bound)
|
|
832
|
+
// has no counted failure at all, and "0 researcher(s) did not return a usable report"
|
|
833
|
+
// would read as nonsense.
|
|
834
|
+
//
|
|
835
|
+
// The capacity wording is deliberately about what is RECORDED, not about this round:
|
|
836
|
+
// the failure list is run-scoped and de-duplicated, so a round that failed the same
|
|
837
|
+
// researchers again adds nothing to it. "every recorded failure was a provider-capacity
|
|
838
|
+
// failure" is exactly true either way; "this round failed on capacity" would not be.
|
|
839
|
+
const headline = countedFailures.length > 0
|
|
840
|
+
? `Research stopped: ${count} researcher(s) did not return a usable report: ${failedList}.`
|
|
841
|
+
: `Research stopped: no report was collected, and every recorded failure was a provider-capacity failure${failedList ? `: ${failedList}` : ''}.`;
|
|
842
|
+
|
|
718
843
|
return [
|
|
719
|
-
|
|
844
|
+
headline,
|
|
720
845
|
'',
|
|
846
|
+
...(capacityFailures.length > 0
|
|
847
|
+
? [
|
|
848
|
+
`Provider capacity failures (excluded from the stop threshold): ${capacityFailures.join(', ')}.`,
|
|
849
|
+
'Those researchers lost every retry to a rate limit or an exhausted in-flight budget,',
|
|
850
|
+
'not to anything about the topic. Retrying the run later is the repair.',
|
|
851
|
+
'',
|
|
852
|
+
]
|
|
853
|
+
: []),
|
|
721
854
|
...recorded,
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
855
|
+
// Only give the "get a better model" advice when the model's output was actually the
|
|
856
|
+
// problem. When every failure was the provider refusing to serve (a rate limit or an
|
|
857
|
+
// exhausted budget), the model never ran — telling the user to change models sends
|
|
858
|
+
// them to buy a different one for a supply problem.
|
|
859
|
+
...(capacityFailures.length > 0 && capacityFailures.length === failed.length
|
|
860
|
+
? [
|
|
861
|
+
'Most likely cause — the provider would not serve the requests:',
|
|
862
|
+
'• Every researcher lost its retries to a rate limit or an exhausted in-flight budget.',
|
|
863
|
+
'• Wait and retry. A shared/free upstream pool (OpenRouter free tier, for one) is',
|
|
864
|
+
' routinely overloaded, and nothing about your setup needs to change.',
|
|
865
|
+
'• If it keeps happening, set PI_RESEARCH_MODEL to a model with a dedicated key or',
|
|
866
|
+
' a provider that is not sharing a pool.',
|
|
867
|
+
]
|
|
868
|
+
: [
|
|
869
|
+
'Most likely cause — the research model could not produce grounded results:',
|
|
870
|
+
'• Try a more capable research model. Very small or "thinking-only" models often',
|
|
871
|
+
' emit no final text after their tool calls, which fails every researcher.',
|
|
872
|
+
'• Verify the model is available and the API key / context settings are valid.',
|
|
873
|
+
]),
|
|
726
874
|
'',
|
|
727
875
|
'Less likely — a network or browser problem (only if the health check did NOT pass):',
|
|
728
876
|
'• Verify the network connection is active.',
|
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
|
|
10
10
|
import type { ExtensionUIContext } from '@earendil-works/pi-coding-agent';
|
|
11
11
|
import { isKeyRelease, matchesKey } from '@earendil-works/pi-tui';
|
|
12
|
-
import { getActiveSessionCount, abortAllSessions, refreshAllSessions, hideMasterWidget } from '../orchestration/session-state.ts';
|
|
12
|
+
import { getActiveSessionCount, abortAllSessions, refreshAllSessions, hideMasterWidget, hasForwardedSteering } from '../orchestration/session-state.ts';
|
|
13
13
|
import { logger } from '../logger.ts';
|
|
14
14
|
|
|
15
15
|
/**
|
|
@@ -140,6 +140,30 @@ export function initGlobalTuiController(ui: ExtensionUIContext, piSessionId?: st
|
|
|
140
140
|
} catch (err) {
|
|
141
141
|
logger.error('[TUI] Failed to abort sessions on cancel:', err);
|
|
142
142
|
}
|
|
143
|
+
|
|
144
|
+
// EXCEPTION to the fall-through above: the user handed a steering message
|
|
145
|
+
// to pi (Alt+P) during this run, so pi is holding it in its own queue.
|
|
146
|
+
//
|
|
147
|
+
// pi's Esc-while-streaming path is `restoreQueuedMessagesToEditor({abort:
|
|
148
|
+
// true})` (verified in pi's bundled TUI): it calls `clearAllQueues()`, joins
|
|
149
|
+
// the queued texts into the EDITOR, and then aborts the turn. So falling
|
|
150
|
+
// through un-queues the popped message, turns it into editor text, and ends
|
|
151
|
+
// the turn — it is never delivered as an instruction, and any later editor
|
|
152
|
+
// clear loses it. That is the "my popped message vanished" report.
|
|
153
|
+
//
|
|
154
|
+
// Consuming the key skips that path: research still cancels (abortAllSessions
|
|
155
|
+
// above), the research tool returns into pi's turn, and pi drains its steering
|
|
156
|
+
// queue at the next step — exactly what "pop" promised. Steering the user did
|
|
157
|
+
// NOT pop never reached pi's queue, stays in this extension's state, and is
|
|
158
|
+
// still dropped with the run, as before.
|
|
159
|
+
//
|
|
160
|
+
// Cost, deliberately accepted: pi does not abort its own turn for this Esc. A
|
|
161
|
+
// second Esc (no active research) falls through normally, so the panic-cancel
|
|
162
|
+
// gesture is one extra keystroke away, not gone.
|
|
163
|
+
if (hasForwardedSteering(state.piSessionId)) {
|
|
164
|
+
logger.info('[TUI] Esc while a popped steering message is queued in pi — aborting research and consuming the key so pi delivers the message.');
|
|
165
|
+
return { consume: true };
|
|
166
|
+
}
|
|
143
167
|
}
|
|
144
168
|
return undefined;
|
|
145
169
|
}
|
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Provider capacity-error classification.
|
|
3
|
+
*
|
|
4
|
+
* Two places need the same answer to "is this failure the provider running out of
|
|
5
|
+
* room, rather than this run being wrong?":
|
|
6
|
+
*
|
|
7
|
+
* - the researcher retry loop, which must wait long enough for a shared-pool
|
|
8
|
+
* rate limit to clear instead of burning its whole retry budget in 7 seconds
|
|
9
|
+
* (researcher-executor.ts), and
|
|
10
|
+
* - the run-level failure threshold, which must not treat "every researcher hit
|
|
11
|
+
* the provider's rate limit" as "the research model cannot do this topic"
|
|
12
|
+
* (session-state.ts shouldStopResearch).
|
|
13
|
+
*
|
|
14
|
+
* Kept in a leaf module so neither importer has to depend on the other; the
|
|
15
|
+
* executor already imports session-state, so putting the predicate there would
|
|
16
|
+
* create a cycle.
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* A SPENT ACCOUNT, which is often reported as a 429 too.
|
|
21
|
+
*
|
|
22
|
+
* This is the single wording list for the class. OpenAI-style quotas answer `429` with
|
|
23
|
+
* `insufficient_quota`; OpenRouter answers `402` with "requires more credits". The status
|
|
24
|
+
* code cannot separate these from a transient rate limit, but the consequence is opposite:
|
|
25
|
+
* the balance does not refill between attempts, so this class is unretriable AND must
|
|
26
|
+
* never be treated as capacity — a run kept alive through three rounds against an account
|
|
27
|
+
* that cannot pay does nothing but burn DuckDuckGo load. `isUnretriableResearcherError`
|
|
28
|
+
* (researcher-executor.ts) delegates here rather than keeping a second copy.
|
|
29
|
+
*/
|
|
30
|
+
export function isSpentAccountError(error: unknown): boolean {
|
|
31
|
+
const msg = (error instanceof Error ? error.message : String(error)).toLowerCase();
|
|
32
|
+
return msg.includes('insufficient_quota')
|
|
33
|
+
|| msg.includes('insufficient credits')
|
|
34
|
+
|| msg.includes('requires more credits')
|
|
35
|
+
|| msg.includes('exceeded your current quota')
|
|
36
|
+
|| msg.includes('out of credits');
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Provider wording for "too many requests right now".
|
|
41
|
+
*
|
|
42
|
+
* Matched on the provider's wording rather than a bare status code, for the same
|
|
43
|
+
* reason as isSpentAccountError: a `429` substring can appear inside an
|
|
44
|
+
* unrelated payload (a token count, a URL, a quoted response body), and this
|
|
45
|
+
* predicate decides how long a researcher sleeps and whether a run keeps going.
|
|
46
|
+
*
|
|
47
|
+
* The real OpenRouter shape (observed 2026-10-25):
|
|
48
|
+
* `429: {"message":"Provider returned error","code":429,"metadata":{"raw":
|
|
49
|
+
* "inclusionai/ling-3.0-flash is temporarily rate-limited upstream. Please
|
|
50
|
+
* retry shortly, ...","provider_name":"DeepInfra",
|
|
51
|
+
* "provider_error_code":"engine_overloaded",
|
|
52
|
+
* "limit_source":"upstream_provider_shared_pool"}}`
|
|
53
|
+
* pi-research's own wrapper adds the prefix `Model API rate limit (429) — wait a
|
|
54
|
+
* moment and retry.`
|
|
55
|
+
*
|
|
56
|
+
* `engine_overloaded` / `provider_overloaded` are the upstream-pool variants that
|
|
57
|
+
* arrive as a 429 body; matched explicitly so a bare "overloaded" cannot collide
|
|
58
|
+
* with unrelated wording (e.g. a CSS/DOM "overloaded selector" in scraped text).
|
|
59
|
+
*/
|
|
60
|
+
export function isRateLimitError(error: unknown): boolean {
|
|
61
|
+
// A spent account answers 429 as well; it is NOT a transient limit. Checked first so
|
|
62
|
+
// no caller that forgot the distinction (backoff, stop threshold, retry policy) can
|
|
63
|
+
// treat an empty balance as a temporary condition.
|
|
64
|
+
if (isSpentAccountError(error)) return false;
|
|
65
|
+
const msg = (error instanceof Error ? error.message : String(error)).toLowerCase();
|
|
66
|
+
return /\b429\b/.test(msg)
|
|
67
|
+
|| msg.includes('rate limit')
|
|
68
|
+
|| msg.includes('rate-limit')
|
|
69
|
+
|| msg.includes('rate limited')
|
|
70
|
+
|| msg.includes('too many requests')
|
|
71
|
+
|| msg.includes('engine_overloaded')
|
|
72
|
+
|| msg.includes('provider_overloaded');
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* The same question, asked of a recorded failure REASON (a string, not an Error).
|
|
77
|
+
* A missing reason is not a capacity failure: the conservative default is to count
|
|
78
|
+
* it toward the stop threshold, exactly as before this classification existed.
|
|
79
|
+
*/
|
|
80
|
+
export function isCapacityFailureReason(reason: string | undefined): boolean {
|
|
81
|
+
// isRateLimitError already excludes the spent-account class, so an out-of-credits
|
|
82
|
+
// failure is NOT capacity and still counts toward the stop threshold.
|
|
83
|
+
return reason !== undefined && reason !== '' && isRateLimitError(reason);
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* The `Retry-After` a provider error asked for, in ms, clamped to [5s, 60s], or null when
|
|
88
|
+
* the error carries none. Read out of the message because every caller sees a serialized
|
|
89
|
+
* provider error, not the raw Response headers: pi's `after_provider_response` hook
|
|
90
|
+
* (src/index.ts) is the only place with headers, and it does not feed these retry loops.
|
|
91
|
+
*
|
|
92
|
+
* Shared (researcher loop + planning/router retries) so the two cannot drift; it lives
|
|
93
|
+
* here rather than in either caller because core/ must not import orchestration/.
|
|
94
|
+
*/
|
|
95
|
+
export function parseRetryAfterMs(error: unknown): number | null {
|
|
96
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
97
|
+
const m = /["']?retry-after["']?\s*[:=]\s*["']?(\d{1,4})/i.exec(message);
|
|
98
|
+
if (!m) return null;
|
|
99
|
+
const seconds = Number(m[1]);
|
|
100
|
+
if (!Number.isFinite(seconds) || seconds <= 0) return null;
|
|
101
|
+
return Math.min(Math.max(seconds, 5), 60) * 1000;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* Base delay for a researcher's first retry after a rate limit. 15s, not the 1s
|
|
106
|
+
* the ordinary exponential step uses: a shared-pool limit is enforced over
|
|
107
|
+
* seconds-to-minutes, and the observed outage (2026-10-25) outlasted four
|
|
108
|
+
* attempts spaced 1s/2s/4s by more than six minutes.
|
|
109
|
+
*/
|
|
110
|
+
export const RATE_LIMIT_BACKOFF_BASE_MS = 15_000;
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* Ceiling for one rate-limit wait. The provider's own `Retry-After` wins when
|
|
114
|
+
* present (clamped by parseRetryAfterMs to 60s); this only bounds the exponential
|
|
115
|
+
* fallback, so three retries cost at most 15s + 30s + 60s of waiting.
|
|
116
|
+
*/
|
|
117
|
+
export const RATE_LIMIT_BACKOFF_MAX_MS = 60_000;
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* How long to wait before retry `attempt` (2 = first retry).
|
|
121
|
+
*
|
|
122
|
+
* `retryAfterMs` is the provider's stated window when the error carried one — it
|
|
123
|
+
* overrides the exponential step, because the provider knows when its pool frees
|
|
124
|
+
* up and we do not. Otherwise: 15s, 30s, 60s (capped), each with ±20% jitter.
|
|
125
|
+
*
|
|
126
|
+
* The jitter is load-bearing, not cosmetic: every researcher in a round normally
|
|
127
|
+
* retries on the same second, so without it N researchers slam the same exhausted
|
|
128
|
+
* upstream pool in lockstep and all fail again, which is exactly what happened on
|
|
129
|
+
* 2026-10-25 (researchers 1.1 and 1.2 retried at 15:58:03, 15:58:27 and 15:58:54
|
|
130
|
+
* and failed three times each in cadence).
|
|
131
|
+
*/
|
|
132
|
+
export function rateLimitBackoffMs(
|
|
133
|
+
attempt: number,
|
|
134
|
+
retryAfterMs: number | null,
|
|
135
|
+
random: () => number = Math.random,
|
|
136
|
+
): number {
|
|
137
|
+
if (retryAfterMs !== null && Number.isFinite(retryAfterMs) && retryAfterMs > 0) {
|
|
138
|
+
return clampRateLimitWait(retryAfterMs);
|
|
139
|
+
}
|
|
140
|
+
const exponent = Math.max(0, attempt - 2);
|
|
141
|
+
const base = Math.min(RATE_LIMIT_BACKOFF_BASE_MS * Math.pow(2, exponent), RATE_LIMIT_BACKOFF_MAX_MS);
|
|
142
|
+
const jitter = base * 0.2 * (random() * 2 - 1);
|
|
143
|
+
return clampRateLimitWait(base + jitter);
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/** Keep a wait inside [1s, 60s] — the same bounds parseRetryAfterMs applies to a stated window. */
|
|
147
|
+
export function clampRateLimitWait(ms: number): number {
|
|
148
|
+
return Math.min(Math.max(Math.round(ms), 1_000), RATE_LIMIT_BACKOFF_MAX_MS);
|
|
149
|
+
}
|
|
@@ -35,6 +35,18 @@ export interface RetryOptions {
|
|
|
35
35
|
// When provided, aborting it short-circuits the inter-attempt backoff wait and
|
|
36
36
|
// stops further retries, so a caller cancel isn't stuck behind a long sleep.
|
|
37
37
|
readonly signal?: AbortSignal;
|
|
38
|
+
/**
|
|
39
|
+
* Optional per-attempt delay override. Return a value (ms) to use it instead of the
|
|
40
|
+
* exponential step, or null to keep the default. `nextAttempt` is 1-based in the
|
|
41
|
+
* caller's terms (2 = the first retry), i.e. the same numbering
|
|
42
|
+
* `rateLimitBackoffMs` uses.
|
|
43
|
+
*
|
|
44
|
+
* Exists for provider-mandated waits: a 429 against a shared pool needs tens of
|
|
45
|
+
* seconds, and `maxDelay` (10s here) exists to bound the ORDINARY step, not to cap a
|
|
46
|
+
* wait the provider asked for. The planning/router calls use it; see
|
|
47
|
+
* `rateLimitDelayFor` in src/core/planning-service.ts.
|
|
48
|
+
*/
|
|
49
|
+
readonly delayFor?: (nextAttempt: number, error: Error) => number | null;
|
|
38
50
|
}
|
|
39
51
|
|
|
40
52
|
/**
|
|
@@ -285,7 +297,9 @@ export async function retryWithBackoff<T>(
|
|
|
285
297
|
fn: () => Promise<T>,
|
|
286
298
|
options: Partial<RetryOptions> = {},
|
|
287
299
|
): Promise<T> {
|
|
288
|
-
|
|
300
|
+
// `delayFor` stays optional (absent for every caller that does not override the wait),
|
|
301
|
+
// so it is excluded from the Required<> normalization rather than given a default.
|
|
302
|
+
const opts: Required<Omit<RetryOptions, 'signal' | 'delayFor'>> & RetryOptions = {
|
|
289
303
|
maxRetries: 3,
|
|
290
304
|
initialDelay: 1000,
|
|
291
305
|
maxDelay: 10000,
|
|
@@ -324,7 +338,12 @@ export async function retryWithBackoff<T>(
|
|
|
324
338
|
// Calculate delay with exponential backoff and jitter
|
|
325
339
|
const baseDelay = opts.initialDelay * Math.pow(2, attempt);
|
|
326
340
|
const jitter = Math.random() * 0.5 * baseDelay; // ±50% jitter
|
|
327
|
-
|
|
341
|
+
// A caller that knows better (a provider-stated or rate-limit wait) wins over the
|
|
342
|
+
// step — including over maxDelay, which bounds only the ordinary step.
|
|
343
|
+
const override = opts.delayFor?.(attempt + 2, lastError);
|
|
344
|
+
const delay = override != null && Number.isFinite(override) && override > 0
|
|
345
|
+
? Math.round(override)
|
|
346
|
+
: Math.min(baseDelay + jitter, opts.maxDelay);
|
|
328
347
|
|
|
329
348
|
metrics.increment('retry_backoff_total', 1, { attempt: String(attempt), label: opts.label });
|
|
330
349
|
metrics.observe('retry_backoff_delay_ms', delay, { attempt: String(attempt), label: opts.label });
|