@aragon-agent/core 0.2.75 → 0.2.77
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/dist/engine/agent-loop.d.ts +9 -0
- package/dist/engine/agent-loop.js +5 -0
- package/dist/engine/agent.d.ts +19 -0
- package/dist/engine/agent.js +126 -1
- package/dist/index.d.ts +2 -2
- package/dist/llm/provider.d.ts +23 -0
- package/dist/llm/providers/index.js +7 -0
- package/dist/llm/retry.d.ts +82 -0
- package/dist/llm/retry.js +346 -35
- package/dist/llm/types.d.ts +25 -1
- package/dist/types.d.ts +38 -0
- package/package.json +1 -1
|
@@ -7,6 +7,7 @@
|
|
|
7
7
|
*/
|
|
8
8
|
import type { Message, ThinkingLevel } from '../llm/types.js';
|
|
9
9
|
import type { ProviderRegistry } from '../llm/providers/index.js';
|
|
10
|
+
import type { EscalationResolution } from '../llm/retry.js';
|
|
10
11
|
import type { ToolExecutor } from '../tools/executor.js';
|
|
11
12
|
import type { ToolRegistry } from '../tools/registry.js';
|
|
12
13
|
import type { AgentEvent } from '../types.js';
|
|
@@ -62,6 +63,14 @@ export interface AgentLoopContext {
|
|
|
62
63
|
*/
|
|
63
64
|
compactionHardTimeout?: number;
|
|
64
65
|
};
|
|
66
|
+
/**
|
|
67
|
+
* Tiered reconnect (tiered-reconnect §4.4), read ONCE per run by `Agent`.
|
|
68
|
+
*
|
|
69
|
+
* `undefined` means "one tier", which is what every host that does not opt in
|
|
70
|
+
* gets. It lives here rather than on the registry so subagents — which share
|
|
71
|
+
* the registry instance — cannot inherit an endless wait (D-4 / D-5).
|
|
72
|
+
*/
|
|
73
|
+
escalation?: EscalationResolution;
|
|
65
74
|
}
|
|
66
75
|
/**
|
|
67
76
|
* A CEILING, NOT A POLICY (P1-3). It must sit STRICTLY ABOVE the largest wall
|
|
@@ -324,6 +324,11 @@ export async function runAgentLoop(ctx) {
|
|
|
324
324
|
signal: ctx.signal,
|
|
325
325
|
thinkingLevel: ctx.thinkingLevel,
|
|
326
326
|
maxTokens: ctx.maxTokens,
|
|
327
|
+
// THE ONLY PLACE IN THE WHOLE REPOSITORY THAT SETS `retryEscalation`
|
|
328
|
+
// (tiered-reconnect §4.4, pinned by a source scan in AC-12). Both keys stay
|
|
329
|
+
// absent when the host did not opt in, so the request body is unchanged.
|
|
330
|
+
...(ctx.escalation?.policy ? { retryEscalation: ctx.escalation.policy } : {}),
|
|
331
|
+
...(ctx.escalation?.startRung ? { startRung: ctx.escalation.startRung } : {}),
|
|
327
332
|
});
|
|
328
333
|
try {
|
|
329
334
|
for await (const event of stream) {
|
package/dist/engine/agent.d.ts
CHANGED
|
@@ -7,6 +7,7 @@
|
|
|
7
7
|
*/
|
|
8
8
|
import type { ContentPart, Message, ThinkingLevel, UserMessage } from '../llm/types.js';
|
|
9
9
|
import type { ProviderRegistry } from '../llm/providers/index.js';
|
|
10
|
+
import type { EscalationResolution } from '../llm/retry.js';
|
|
10
11
|
import type { AgentTool } from '../tools/types.js';
|
|
11
12
|
import type { AgentEventListener } from '../types.js';
|
|
12
13
|
import type { CodeActSandbox, ModelRef } from './agent-loop.js';
|
|
@@ -45,6 +46,17 @@ export interface AgentConfig {
|
|
|
45
46
|
* nothing to change must return the same array reference.
|
|
46
47
|
*/
|
|
47
48
|
projectMessages?: (messages: readonly Message[]) => readonly Message[];
|
|
49
|
+
/**
|
|
50
|
+
* Tiered reconnect (tiered-reconnect §4.4). CALLED ONCE PER RUN, so the host can
|
|
51
|
+
* read live configuration: `/retry reconnect off` takes effect on the next
|
|
52
|
+
* request without a restart and without a second push (contrast
|
|
53
|
+
* `setRetryPolicy`, which must be pushed because a `RetryPolicy` is a VALUE —
|
|
54
|
+
* this is a FUNCTION).
|
|
55
|
+
*
|
|
56
|
+
* Absent, or returning `{ policy: null }`, means exactly today's behaviour: one
|
|
57
|
+
* tier, and events with no tier keys at all (D-9).
|
|
58
|
+
*/
|
|
59
|
+
resolveEscalation?: () => EscalationResolution | null;
|
|
48
60
|
/** Timeout configuration. */
|
|
49
61
|
timeouts?: {
|
|
50
62
|
/** Single LLM call timeout (ms). Default: 300_000 (5 min). */
|
|
@@ -102,6 +114,8 @@ export declare class Agent {
|
|
|
102
114
|
private readonly sandbox?;
|
|
103
115
|
private readonly contextManager?;
|
|
104
116
|
private readonly projectMessages?;
|
|
117
|
+
/** Tiered reconnect: read once per run, so the host's config stays live (§4.4). */
|
|
118
|
+
private readonly resolveEscalation?;
|
|
105
119
|
private maxTokens;
|
|
106
120
|
private readonly llmCallTimeout;
|
|
107
121
|
private readonly idleTimeout;
|
|
@@ -116,11 +130,16 @@ export declare class Agent {
|
|
|
116
130
|
* (`llm-network-error-dead-run` F).
|
|
117
131
|
*/
|
|
118
132
|
private watchdogFired;
|
|
133
|
+
/** Where the run was when the watchdog fired; captured THEN, before the abort unwinds. */
|
|
134
|
+
private stall;
|
|
135
|
+
private activity;
|
|
119
136
|
/** Failure facts for the NEXT `agent_end`; cleared as they are emitted. */
|
|
120
137
|
private endFailure;
|
|
121
138
|
private running;
|
|
122
139
|
private idlePromiseResolvers;
|
|
123
140
|
constructor(config: AgentConfig);
|
|
141
|
+
/** The watchdog's own evidence: what was last seen, and for how long nothing was. */
|
|
142
|
+
private describeStall;
|
|
124
143
|
get state(): AgentState;
|
|
125
144
|
/**
|
|
126
145
|
* Send a user message and run the Agent loop until completion.
|
package/dist/engine/agent.js
CHANGED
|
@@ -18,6 +18,90 @@ const DEFAULT_LLM_CALL_TIMEOUT = 300_000;
|
|
|
18
18
|
const DEFAULT_IDLE_TIMEOUT = 60_000;
|
|
19
19
|
const DEFAULT_TOOL_TIMEOUT = 120_000;
|
|
20
20
|
const DEFAULT_CODE_TIMEOUT = 30_000;
|
|
21
|
+
function freshActivity() {
|
|
22
|
+
return {
|
|
23
|
+
lastEvent: 'none',
|
|
24
|
+
phase: 'awaiting_response',
|
|
25
|
+
toolName: undefined,
|
|
26
|
+
monotonicAt: performance.now(),
|
|
27
|
+
wallAt: Date.now(),
|
|
28
|
+
eventsSeen: 0,
|
|
29
|
+
toolsInFlight: 0,
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
/** `message_update` and friends read better in a log as `message_update:text_delta`. */
|
|
33
|
+
function describeEvent(event) {
|
|
34
|
+
return event.type === 'message_update'
|
|
35
|
+
? `message_update:${event.streamEvent.type}`
|
|
36
|
+
: event.type;
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Fold one event into the activity record. Mutates `a`; allocation-free because it
|
|
40
|
+
* runs for every streamed delta of every run, which is the only reason this is
|
|
41
|
+
* not written as a pure `(a, event) => a`.
|
|
42
|
+
*/
|
|
43
|
+
function recordActivity(a, event) {
|
|
44
|
+
a.lastEvent = describeEvent(event);
|
|
45
|
+
a.monotonicAt = performance.now();
|
|
46
|
+
a.wallAt = Date.now();
|
|
47
|
+
a.eventsSeen += 1;
|
|
48
|
+
switch (event.type) {
|
|
49
|
+
case 'agent_start':
|
|
50
|
+
a.toolsInFlight = 0;
|
|
51
|
+
a.phase = 'awaiting_response';
|
|
52
|
+
a.toolName = undefined;
|
|
53
|
+
return;
|
|
54
|
+
case 'turn_start':
|
|
55
|
+
a.phase = 'awaiting_response';
|
|
56
|
+
a.toolName = undefined;
|
|
57
|
+
return;
|
|
58
|
+
case 'turn_end':
|
|
59
|
+
a.phase = 'between_turns';
|
|
60
|
+
return;
|
|
61
|
+
case 'tool_execution_start':
|
|
62
|
+
case 'code_execution_start':
|
|
63
|
+
a.toolsInFlight += 1;
|
|
64
|
+
a.phase = 'tool_running';
|
|
65
|
+
a.toolName = event.type === 'tool_execution_start' ? event.toolName : 'code';
|
|
66
|
+
return;
|
|
67
|
+
case 'tool_execution_end':
|
|
68
|
+
case 'code_execution_end':
|
|
69
|
+
a.toolsInFlight = Math.max(0, a.toolsInFlight - 1);
|
|
70
|
+
if (a.toolsInFlight === 0) {
|
|
71
|
+
a.phase = 'awaiting_response';
|
|
72
|
+
a.toolName = undefined;
|
|
73
|
+
}
|
|
74
|
+
return;
|
|
75
|
+
case 'message_update':
|
|
76
|
+
break;
|
|
77
|
+
default:
|
|
78
|
+
return;
|
|
79
|
+
}
|
|
80
|
+
switch (event.streamEvent.type) {
|
|
81
|
+
case 'thinking_start':
|
|
82
|
+
case 'thinking_delta':
|
|
83
|
+
a.phase = 'thinking';
|
|
84
|
+
return;
|
|
85
|
+
case 'text_delta':
|
|
86
|
+
a.phase = 'text';
|
|
87
|
+
return;
|
|
88
|
+
case 'tool_call_start':
|
|
89
|
+
a.phase = 'tool_input';
|
|
90
|
+
a.toolName = event.streamEvent.toolName;
|
|
91
|
+
return;
|
|
92
|
+
case 'tool_call_delta':
|
|
93
|
+
a.phase = 'tool_input';
|
|
94
|
+
return;
|
|
95
|
+
case 'retry_attempt':
|
|
96
|
+
case 'stream_restart':
|
|
97
|
+
// A new request is going out: the silence that follows is before ITS first byte.
|
|
98
|
+
a.phase = 'awaiting_response';
|
|
99
|
+
a.toolName = undefined;
|
|
100
|
+
return;
|
|
101
|
+
default:
|
|
102
|
+
return;
|
|
103
|
+
}
|
|
104
|
+
}
|
|
21
105
|
// ---------------------------------------------------------------------------
|
|
22
106
|
// Agent
|
|
23
107
|
// ---------------------------------------------------------------------------
|
|
@@ -39,6 +123,8 @@ export class Agent {
|
|
|
39
123
|
sandbox;
|
|
40
124
|
contextManager;
|
|
41
125
|
projectMessages;
|
|
126
|
+
/** Tiered reconnect: read once per run, so the host's config stays live (§4.4). */
|
|
127
|
+
resolveEscalation;
|
|
42
128
|
// --- LLM generation parameters ---
|
|
43
129
|
maxTokens;
|
|
44
130
|
// --- Timeouts ---
|
|
@@ -56,6 +142,9 @@ export class Agent {
|
|
|
56
142
|
* (`llm-network-error-dead-run` F).
|
|
57
143
|
*/
|
|
58
144
|
watchdogFired = false;
|
|
145
|
+
/** Where the run was when the watchdog fired; captured THEN, before the abort unwinds. */
|
|
146
|
+
stall = null;
|
|
147
|
+
activity = freshActivity();
|
|
59
148
|
/** Failure facts for the NEXT `agent_end`; cleared as they are emitted. */
|
|
60
149
|
endFailure = null;
|
|
61
150
|
running = false;
|
|
@@ -70,6 +159,7 @@ export class Agent {
|
|
|
70
159
|
this.sandbox = config.sandbox;
|
|
71
160
|
this.contextManager = config.contextManager;
|
|
72
161
|
this.projectMessages = config.projectMessages;
|
|
162
|
+
this.resolveEscalation = config.resolveEscalation;
|
|
73
163
|
this.maxTokens = config.maxTokens;
|
|
74
164
|
// Timeouts
|
|
75
165
|
this.llmCallTimeout = config.timeouts?.llmCallTimeout ?? DEFAULT_LLM_CALL_TIMEOUT;
|
|
@@ -91,9 +181,26 @@ export class Agent {
|
|
|
91
181
|
console.error('[Agent] idle watchdog fired — aborting');
|
|
92
182
|
// BEFORE the abort, so the fact survives the unwind this call starts.
|
|
93
183
|
this.watchdogFired = true;
|
|
184
|
+
// CAPTURED NOW, NOT IN `finally`: the abort makes the loop emit events of its
|
|
185
|
+
// own while it unwinds, and each of them would move `lastEvent` to something
|
|
186
|
+
// that is not where the silence began.
|
|
187
|
+
this.stall = this.describeStall();
|
|
94
188
|
this.abort();
|
|
95
189
|
});
|
|
96
190
|
}
|
|
191
|
+
/** The watchdog's own evidence: what was last seen, and for how long nothing was. */
|
|
192
|
+
describeStall() {
|
|
193
|
+
const a = this.activity;
|
|
194
|
+
return {
|
|
195
|
+
phase: a.phase,
|
|
196
|
+
lastEvent: a.lastEvent,
|
|
197
|
+
msSinceLastEvent: Math.round(performance.now() - a.monotonicAt),
|
|
198
|
+
wallMsSinceLastEvent: Date.now() - a.wallAt,
|
|
199
|
+
eventsSeen: a.eventsSeen,
|
|
200
|
+
idleTimeoutMs: this.idleTimeout,
|
|
201
|
+
...(a.toolName !== undefined ? { toolName: a.toolName } : {}),
|
|
202
|
+
};
|
|
203
|
+
}
|
|
97
204
|
// =========================================================================
|
|
98
205
|
// Public readonly state
|
|
99
206
|
// =========================================================================
|
|
@@ -244,6 +351,7 @@ export class Agent {
|
|
|
244
351
|
// the watchdog armed across a 30-second backoff and the run is aborted for
|
|
245
352
|
// being "idle" while it is provably waiting on purpose.
|
|
246
353
|
this.applyWatchdogPolicy(event);
|
|
354
|
+
recordActivity(this.activity, event);
|
|
247
355
|
for (const listener of this.listeners) {
|
|
248
356
|
try {
|
|
249
357
|
listener(event);
|
|
@@ -331,9 +439,15 @@ export class Agent {
|
|
|
331
439
|
async runLoopWithLifecycle() {
|
|
332
440
|
this.running = true;
|
|
333
441
|
this.watchdogFired = false;
|
|
442
|
+
this.stall = null;
|
|
443
|
+
this.activity = freshActivity();
|
|
334
444
|
this.abortController = new AbortController();
|
|
335
445
|
this.watchdog.start();
|
|
336
446
|
this.emit({ type: 'agent_start' });
|
|
447
|
+
// Tiered reconnect (§4.4): ONE read per run. `null` (no resolver, or a null
|
|
448
|
+
// policy) leaves the loop context untouched, so a host that never opted in is
|
|
449
|
+
// indistinguishable from a pre-feature build.
|
|
450
|
+
const resolvedEscalation = this.resolveEscalation?.() ?? null;
|
|
337
451
|
try {
|
|
338
452
|
await runAgentLoop({
|
|
339
453
|
providerRegistry: this.providerRegistry,
|
|
@@ -354,6 +468,10 @@ export class Agent {
|
|
|
354
468
|
// which is what makes the byte-identity claim in AC-1 provable.
|
|
355
469
|
...(this.contextManager ? { contextManager: this.contextManager } : {}),
|
|
356
470
|
...(this.projectMessages ? { projectMessages: this.projectMessages } : {}),
|
|
471
|
+
// Read ONCE per run, and spread only when a policy is actually resolved:
|
|
472
|
+
// with the feature off, the loop context has no `escalation` key at all
|
|
473
|
+
// (D-9 / AC-1, the same discipline as `contextManager` above).
|
|
474
|
+
...(resolvedEscalation !== null ? { escalation: resolvedEscalation } : {}),
|
|
357
475
|
signal: this.abortController.signal,
|
|
358
476
|
timeouts: {
|
|
359
477
|
llmCallTimeout: this.llmCallTimeout,
|
|
@@ -392,9 +510,16 @@ export class Agent {
|
|
|
392
510
|
// turn is safe. `endFailure` wins when both could apply: the loop reached
|
|
393
511
|
// an error of its own, which is the more specific fact.
|
|
394
512
|
const failure = this.watchdogFired && !this.endFailure
|
|
395
|
-
? {
|
|
513
|
+
? {
|
|
514
|
+
errored: true,
|
|
515
|
+
reason: 'idle_watchdog',
|
|
516
|
+
errorType: 'timeout',
|
|
517
|
+
retryable: true,
|
|
518
|
+
...(this.stall ? { stall: this.stall } : {}),
|
|
519
|
+
}
|
|
396
520
|
: (this.endFailure ?? {});
|
|
397
521
|
this.endFailure = null;
|
|
522
|
+
this.stall = null;
|
|
398
523
|
this.emit({
|
|
399
524
|
type: 'agent_end',
|
|
400
525
|
messages: this.messageManager.getAll(),
|
package/dist/index.d.ts
CHANGED
|
@@ -14,7 +14,7 @@ export { IMAGE_TOKEN_ESTIMATE } from './llm/image-tokens.js';
|
|
|
14
14
|
export type { OutputLimitInput, OutputLimitResolution, CeilingSource, } from './llm/output-limits.js';
|
|
15
15
|
export { classifyOutputLimitFailure, sendWithOutputLimitRecovery, learnTokenField, getLearnedTokenField, clearLearnedTokenFields, } from './llm/output-limit-recovery.js';
|
|
16
16
|
export { RETRY_LIMITS, DEFAULT_RETRY_POLICY, isRetryableError, computeBackoffDelay, parseRetryAfterMs, withRetry, } from './llm/retry.js';
|
|
17
|
-
export type { RetryPolicy, RetryDecision, WithRetryOptions, } from './llm/retry.js';
|
|
17
|
+
export type { RetryPolicy, RetryDecision, WithRetryOptions, RetryTierId, RetryTier, EscalationPolicy, EscalationResolution, } from './llm/retry.js';
|
|
18
18
|
export type { OutputLimitFailure, RecoveryAttempt, RecoveryOptions, TokenField, } from './llm/output-limit-recovery.js';
|
|
19
19
|
export type { SSEEvent } from './llm/stream-utils.js';
|
|
20
20
|
export { parseSSEStream, consumeStream, } from './llm/stream-utils.js';
|
|
@@ -42,7 +42,7 @@ export { createSkillFindTool } from './skills/skill-find-tool.js';
|
|
|
42
42
|
export { computeToolPolicy, evaluateToolCall } from './skills/tool-policy.js';
|
|
43
43
|
export { SKILL_CATALOG_MAX_BYTES, SKILL_BODY_MAX_BYTES, SKILL_RESULT_MAX_BYTES, ALWAYS_SKILLS_MAX_BYTES, SKILL_MD_MAX_BYTES, SKILL_DESC_LINE_MAX, SKILL_FILES_MAX, SKILL_FIND_MAX_BYTES, SKILL_NAME_PATTERN, } from './skills/constants.js';
|
|
44
44
|
export type { SkillScope, SkillActivation, SkillFrontmatter, SkillRecord, SkillFileRef, SkillHost, SkillManifest, SkillValidationIssue, SkillCatalogOptions, SkillBodyOptions, SkillFindOptions, SkillIntegrity, SkillUsageStat, SkillUsageMap, SkillInvocationOptions, SkillPlatform, SkillPolicyView, SkillToolPolicyMode, ToolPolicyDecision, ToolPolicyInput, ToolPolicySource, ToolPolicyVerdict, } from './skills/types.js';
|
|
45
|
-
export type { AgentEvent, AgentEventListener, AgentStartEvent, AgentEndEvent, TurnStartEvent, SteeringAcceptedEvent, TurnEndEvent, MessageUpdateEvent, ToolExecutionStartEvent, ToolExecutionEndEvent, CodeExecutionStartEvent, CodeExecutionEndEvent, CompactionStartEvent, CompactionEndEvent, } from './types.js';
|
|
45
|
+
export type { AgentEvent, AgentEventListener, AgentStartEvent, AgentEndEvent, AgentStallInfo, AgentStallPhase, TurnStartEvent, SteeringAcceptedEvent, TurnEndEvent, MessageUpdateEvent, ToolExecutionStartEvent, ToolExecutionEndEvent, CodeExecutionStartEvent, CodeExecutionEndEvent, CompactionStartEvent, CompactionEndEvent, } from './types.js';
|
|
46
46
|
export { Agent } from './engine/agent.js';
|
|
47
47
|
export type { AgentConfig, AgentState } from './engine/agent.js';
|
|
48
48
|
export type { ModelRef } from './engine/agent-loop.js';
|
package/dist/llm/provider.d.ts
CHANGED
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
* LLM Provider interface, request types, and error classification.
|
|
3
3
|
*/
|
|
4
4
|
import type { AssistantMessage, Message, ModelInfo, StreamEvent, ThinkingLevel, ToolDefinition } from './types.js';
|
|
5
|
+
import type { EscalationPolicy, RetryTierId } from './retry.js';
|
|
5
6
|
export interface LLMRequest {
|
|
6
7
|
/** Model identifier, e.g. 'claude-sonnet-4-5-20250929'. */
|
|
7
8
|
model: string;
|
|
@@ -44,6 +45,28 @@ export interface LLMRequest {
|
|
|
44
45
|
/** Explicit thinking budget (tokens). Overrides thinkingLevel if both are set. */
|
|
45
46
|
thinkingBudget?: number;
|
|
46
47
|
stopSequences?: string[];
|
|
48
|
+
/**
|
|
49
|
+
* Tiered reconnect (tiered-reconnect §4.4). ABSENT MEANS ONE TIER: every caller
|
|
50
|
+
* that does not opt in — the compactor, the fast tier, gene/curator, model
|
|
51
|
+
* probes, `completeLLM`, every subagent — behaves exactly as it did before this
|
|
52
|
+
* field existed.
|
|
53
|
+
*
|
|
54
|
+
* WHY IT RIDES ON THE REQUEST AND NOT ON THE REGISTRY: `ProviderRegistry` is a
|
|
55
|
+
* single shared instance, and every subagent borrows it (`team/subagent.ts`).
|
|
56
|
+
* A policy stored there would make every child wait forever, and — because
|
|
57
|
+
* `subagentTimeoutMs` / `dispatchTimeoutMs` default to 0 — nothing would ever
|
|
58
|
+
* stop them. Request-level means the default is "off", so a forgotten call site
|
|
59
|
+
* fails safe.
|
|
60
|
+
*
|
|
61
|
+
* `retry.ts` reads it as `import type` only; no new runtime edge is created
|
|
62
|
+
* (§4.4, R-4 #1).
|
|
63
|
+
*/
|
|
64
|
+
retryEscalation?: EscalationPolicy | null;
|
|
65
|
+
/**
|
|
66
|
+
* Tier to start from, default 1. `> 1` (sticky rung, §4.9) changes only the
|
|
67
|
+
* pace AFTER the first failure: the initial attempt still goes out immediately.
|
|
68
|
+
*/
|
|
69
|
+
startRung?: RetryTierId;
|
|
47
70
|
}
|
|
48
71
|
export interface LLMProvider {
|
|
49
72
|
/** Unique provider identifier, e.g. 'anthropic', 'openai', 'google'. */
|
|
@@ -75,6 +75,13 @@ export class ProviderRegistry {
|
|
|
75
75
|
providerId,
|
|
76
76
|
modelId: request.model,
|
|
77
77
|
...(request.signal ? { signal: request.signal } : {}),
|
|
78
|
+
// Pure pass-through (tiered-reconnect §4.4): the escalation decided per
|
|
79
|
+
// REQUEST, never stored on this registry, because the registry is shared
|
|
80
|
+
// with every subagent. Absent ⇒ `withRetry` runs exactly one tier.
|
|
81
|
+
...(request.retryEscalation !== undefined
|
|
82
|
+
? { escalation: request.retryEscalation }
|
|
83
|
+
: {}),
|
|
84
|
+
...(request.startRung !== undefined ? { startRung: request.startRung } : {}),
|
|
78
85
|
});
|
|
79
86
|
}
|
|
80
87
|
/**
|
package/dist/llm/retry.d.ts
CHANGED
|
@@ -49,6 +49,18 @@ export declare const RETRY_LIMITS: {
|
|
|
49
49
|
readonly retryAfterCeilingMs: 60000;
|
|
50
50
|
/** Floor under any computed wait, so jitter can never produce a 0 ms "retry". */
|
|
51
51
|
readonly minDelayMs: 100;
|
|
52
|
+
/** Ceiling on ONE wait inside an escalation tier (15 min; tier 3 defaults to 5). */
|
|
53
|
+
readonly escalationMaxDelayMs: 900000;
|
|
54
|
+
/** Ceiling on tier 2's attempt count, whatever a hand-written policy claims. */
|
|
55
|
+
readonly hardMaxSlowAttempts: 30;
|
|
56
|
+
/**
|
|
57
|
+
* Tier 3's NOMINAL attempt count. It exists only to give a `number` field a
|
|
58
|
+
* finite value — 10 000 x 5 min is 34 days, far past any process lifetime, and
|
|
59
|
+
* the decision itself runs on `Rung.unbounded`, never on this count (T-2).
|
|
60
|
+
*/
|
|
61
|
+
readonly holdNominalAttempts: 10000;
|
|
62
|
+
/** Floor under tier 3's interval: below this it is a "hold" no longer. */
|
|
63
|
+
readonly holdMinDelayMs: 60000;
|
|
52
64
|
};
|
|
53
65
|
export interface RetryPolicy {
|
|
54
66
|
/** Retries AFTER the initial attempt. `10` => up to 11 total requests. */
|
|
@@ -90,6 +102,54 @@ export declare const CONTENT_EVENTS: ReadonlySet<StreamEvent['type']>;
|
|
|
90
102
|
* this being present but unwired.
|
|
91
103
|
*/
|
|
92
104
|
export declare function normalizePolicy(policy: RetryPolicy): RetryPolicy;
|
|
105
|
+
/** Tier number. Tier 1 IS a `RetryPolicy`, so only 2 and 3 are described here. */
|
|
106
|
+
export type RetryTierId = 1 | 2 | 3;
|
|
107
|
+
/** One slower tier. Tier 1 is not described by this — it is `RetryPolicy` itself. */
|
|
108
|
+
export interface RetryTier {
|
|
109
|
+
/** Attempts in this tier, the first one included. `0` tier 2 = no escalation. */
|
|
110
|
+
attempts: number;
|
|
111
|
+
/** Wait before the tier's first attempt (a tier's first beat waits too, §4.1). */
|
|
112
|
+
initialDelayMs: number;
|
|
113
|
+
/** Ceiling on one wait inside the tier. */
|
|
114
|
+
maxDelayMs: number;
|
|
115
|
+
/** Growth factor inside the tier. Flat 1 for tiers 2/3. */
|
|
116
|
+
multiplier: number;
|
|
117
|
+
/** Jitter inside the tier. Forced off: a countdown must be the truth. */
|
|
118
|
+
jitter: boolean;
|
|
119
|
+
}
|
|
120
|
+
/**
|
|
121
|
+
* What happens AFTER tier 1. Tier 1 is absent on purpose: it is the user's own
|
|
122
|
+
* `retry.*` policy, and this feature changes none of its numbers.
|
|
123
|
+
*/
|
|
124
|
+
export interface EscalationPolicy {
|
|
125
|
+
/** Tier 2: every `initialDelayMs`, `attempts` times. */
|
|
126
|
+
slow: RetryTier;
|
|
127
|
+
/** Tier 3: every 5 minutes, forever. `null` = bounded mode (headless). */
|
|
128
|
+
hold: RetryTier | null;
|
|
129
|
+
/**
|
|
130
|
+
* Wall-clock budget for the WHOLE LADDER, anchored on this request's first
|
|
131
|
+
* failure. Absent = unbounded, which is the interactive default (§4.3.4).
|
|
132
|
+
*/
|
|
133
|
+
totalBudgetMs?: number;
|
|
134
|
+
}
|
|
135
|
+
/**
|
|
136
|
+
* The product of `AgentConfig.resolveEscalation`. An object from day one so the
|
|
137
|
+
* optional `startRung` step is a pure addition, never a type change.
|
|
138
|
+
*/
|
|
139
|
+
export interface EscalationResolution {
|
|
140
|
+
/** `null` = do not escalate (switched off, or tier 1 does not exist). */
|
|
141
|
+
policy: EscalationPolicy | null;
|
|
142
|
+
/** Default 1. `> 1` only changes the pace AFTER the first failure (§4.9). */
|
|
143
|
+
startRung?: RetryTierId;
|
|
144
|
+
}
|
|
145
|
+
/**
|
|
146
|
+
* Clamp an arbitrary escalation; `null` means "do not escalate".
|
|
147
|
+
*
|
|
148
|
+
* G5: THIS IS THE TIERS' OWN GATE and its output never passes through
|
|
149
|
+
* `normalizePolicy`, whose `finiteOr` would rewrite "no budget" as 240 000 and
|
|
150
|
+
* whose `hardMaxRetries` would cut tier 3 to 20 attempts (§2.2#2/#3).
|
|
151
|
+
*/
|
|
152
|
+
export declare function normalizeEscalation(raw: EscalationPolicy | null | undefined): EscalationPolicy | null;
|
|
93
153
|
export interface RetryDecision {
|
|
94
154
|
retry: boolean;
|
|
95
155
|
/** Machine reason, for logs and for the acceptance tests. */
|
|
@@ -151,6 +211,7 @@ export declare function decide(input: DecideInput): RetryDecision;
|
|
|
151
211
|
export declare function computeBackoffDelay(retryIndex: number, policy: RetryPolicy, opts?: {
|
|
152
212
|
retryAfterMs?: number;
|
|
153
213
|
random?: () => number;
|
|
214
|
+
ceilingMs?: number;
|
|
154
215
|
}): number;
|
|
155
216
|
/**
|
|
156
217
|
* The server-stated wait, in ms, or `undefined` when absent or unparseable.
|
|
@@ -179,6 +240,17 @@ export interface WithRetryOptions {
|
|
|
179
240
|
now?: () => number;
|
|
180
241
|
sleep?: (ms: number, signal?: AbortSignal) => Promise<void>;
|
|
181
242
|
random?: () => number;
|
|
243
|
+
/**
|
|
244
|
+
* Tiered reconnect (tiered-reconnect §4.4). ABSENT = ONE TIER = today's
|
|
245
|
+
* behaviour, event payload and all (D-9).
|
|
246
|
+
*
|
|
247
|
+
* It travels on the REQUEST rather than on the `ProviderRegistry`, because the
|
|
248
|
+
* registry is one shared instance: every subagent, the compactor and the fast
|
|
249
|
+
* tier would inherit an endless wait, and nothing would ever stop them (§2.3).
|
|
250
|
+
*/
|
|
251
|
+
escalation?: EscalationPolicy | null;
|
|
252
|
+
/** Tier to start from. Default 1; `> 1` only changes the pace AFTER a failure. */
|
|
253
|
+
startRung?: RetryTierId;
|
|
182
254
|
}
|
|
183
255
|
/**
|
|
184
256
|
* Wrap a stream factory with retry.
|
|
@@ -197,6 +269,16 @@ export interface WithRetryOptions {
|
|
|
197
269
|
* in-loop guard, the `decide` short-circuit, and the post-sleep check.
|
|
198
270
|
* - G4 — `normalizePolicy` RUNS ONCE, at generator entry, so `RETRY_LIMITS`
|
|
199
271
|
* bounds an embedder's policy and not merely a CLI-resolved one.
|
|
272
|
+
* - G5 — the escalation tiers have their OWN gate (`normalizeEscalation`) and never
|
|
273
|
+
* pass through `normalizePolicy`, whose `finiteOr` would rewrite "no budget" as
|
|
274
|
+
* 240 s and whose `hardMaxRetries` would cut tier 3 to 20 attempts.
|
|
275
|
+
* - G6 — `Retry-After`'s "> 60 s stops the ladder" rule is TIER 1's only; tiers 2/3
|
|
276
|
+
* cap the ADOPTED wait at their own interval and still report the raw number.
|
|
277
|
+
* - G7 — what is announced is what is waited, and the ladder budget is tested
|
|
278
|
+
* BEFORE anything is announced.
|
|
279
|
+
* - G8 — only `attempts_exhausted` / `budget_exhausted` / `retry_after_too_long`
|
|
280
|
+
* end a TIER. `committed` and `not_retryable` end the WHOLE ladder, because
|
|
281
|
+
* escalating `committed` would replay text the user has already read.
|
|
200
282
|
* - THE SUCCESS PATH IS UNTOUCHED. A request that works yields exactly the
|
|
201
283
|
* events the adapter produced, in the same order, with no extra allocation
|
|
202
284
|
* beyond one boolean and one empty array. The wrapper is not installed at all
|
package/dist/llm/retry.js
CHANGED
|
@@ -52,6 +52,22 @@ export const RETRY_LIMITS = {
|
|
|
52
52
|
retryAfterCeilingMs: 60_000,
|
|
53
53
|
/** Floor under any computed wait, so jitter can never produce a 0 ms "retry". */
|
|
54
54
|
minDelayMs: 100,
|
|
55
|
+
// ---- tiered-reconnect: these bound ESCALATION TIERS ONLY -------------------
|
|
56
|
+
// Tier 1 keeps every bound above, unchanged: the requirement is literally
|
|
57
|
+
// "the first tier is today's fast retry". Only the two slower tiers may wait
|
|
58
|
+
// longer than `absoluteMaxDelayMs`, and only they may be unbounded.
|
|
59
|
+
/** Ceiling on ONE wait inside an escalation tier (15 min; tier 3 defaults to 5). */
|
|
60
|
+
escalationMaxDelayMs: 900_000,
|
|
61
|
+
/** Ceiling on tier 2's attempt count, whatever a hand-written policy claims. */
|
|
62
|
+
hardMaxSlowAttempts: 30,
|
|
63
|
+
/**
|
|
64
|
+
* Tier 3's NOMINAL attempt count. It exists only to give a `number` field a
|
|
65
|
+
* finite value — 10 000 x 5 min is 34 days, far past any process lifetime, and
|
|
66
|
+
* the decision itself runs on `Rung.unbounded`, never on this count (T-2).
|
|
67
|
+
*/
|
|
68
|
+
holdNominalAttempts: 10_000,
|
|
69
|
+
/** Floor under tier 3's interval: below this it is a "hold" no longer. */
|
|
70
|
+
holdMinDelayMs: 60_000,
|
|
55
71
|
};
|
|
56
72
|
export const DEFAULT_RETRY_POLICY = {
|
|
57
73
|
maxRetries: 10,
|
|
@@ -147,6 +163,68 @@ export function normalizePolicy(policy) {
|
|
|
147
163
|
onPartialStream: policy.onPartialStream !== false,
|
|
148
164
|
};
|
|
149
165
|
}
|
|
166
|
+
const DEFAULT_TIER = {
|
|
167
|
+
attempts: 10,
|
|
168
|
+
initialDelayMs: 60_000,
|
|
169
|
+
maxDelayMs: 60_000,
|
|
170
|
+
multiplier: 1,
|
|
171
|
+
jitter: false,
|
|
172
|
+
};
|
|
173
|
+
const DEFAULT_HOLD_INTERVAL_MS = 300_000;
|
|
174
|
+
const MAX_LADDER_BUDGET_MS = 24 * 3600_000;
|
|
175
|
+
const MIN_LADDER_BUDGET_MS = 60_000;
|
|
176
|
+
function clampIntOr(value, fallback, min, max) {
|
|
177
|
+
const v = Math.floor(finiteOr(value, fallback));
|
|
178
|
+
return Math.min(max, Math.max(min, v));
|
|
179
|
+
}
|
|
180
|
+
/**
|
|
181
|
+
* Clamp an arbitrary escalation; `null` means "do not escalate".
|
|
182
|
+
*
|
|
183
|
+
* G5: THIS IS THE TIERS' OWN GATE and its output never passes through
|
|
184
|
+
* `normalizePolicy`, whose `finiteOr` would rewrite "no budget" as 240 000 and
|
|
185
|
+
* whose `hardMaxRetries` would cut tier 3 to 20 attempts (§2.2#2/#3).
|
|
186
|
+
*/
|
|
187
|
+
export function normalizeEscalation(raw) {
|
|
188
|
+
if (!raw || typeof raw !== 'object')
|
|
189
|
+
return null;
|
|
190
|
+
const slowRaw = raw.slow;
|
|
191
|
+
if (!slowRaw || typeof slowRaw !== 'object')
|
|
192
|
+
return null;
|
|
193
|
+
const slowAttempts = clampIntOr(slowRaw.attempts, DEFAULT_TIER.attempts, 0, RETRY_LIMITS.hardMaxSlowAttempts);
|
|
194
|
+
// ZERO TIER-2 ATTEMPTS IS "NO ESCALATION", never "skip to the hold tier": a
|
|
195
|
+
// shape nobody asked for must not be reachable through a config typo.
|
|
196
|
+
if (slowAttempts === 0)
|
|
197
|
+
return null;
|
|
198
|
+
const slowInitial = clampIntOr(slowRaw.initialDelayMs, DEFAULT_TIER.initialDelayMs, RETRY_LIMITS.minDelayMs, RETRY_LIMITS.escalationMaxDelayMs);
|
|
199
|
+
const slow = {
|
|
200
|
+
attempts: slowAttempts,
|
|
201
|
+
initialDelayMs: slowInitial,
|
|
202
|
+
// Same invariant `clampRetryConfig` keeps: a ceiling below the floor makes the
|
|
203
|
+
// ladder a lie about what the user sees.
|
|
204
|
+
maxDelayMs: Math.max(clampIntOr(slowRaw.maxDelayMs, slowInitial, RETRY_LIMITS.minDelayMs, RETRY_LIMITS.escalationMaxDelayMs), slowInitial),
|
|
205
|
+
multiplier: Math.min(5, Math.max(1, finiteOr(slowRaw.multiplier, 1))),
|
|
206
|
+
jitter: false,
|
|
207
|
+
};
|
|
208
|
+
const holdRaw = raw.hold;
|
|
209
|
+
let hold = null;
|
|
210
|
+
if (holdRaw && typeof holdRaw === 'object') {
|
|
211
|
+
const interval = clampIntOr(holdRaw.initialDelayMs, DEFAULT_HOLD_INTERVAL_MS, RETRY_LIMITS.holdMinDelayMs, RETRY_LIMITS.escalationMaxDelayMs);
|
|
212
|
+
// ONE interval in both fields: tiers 2/3 are flat, and a `maxDelayMs` that
|
|
213
|
+
// disagreed with `initialDelayMs` would make the countdown lie (G7).
|
|
214
|
+
hold = {
|
|
215
|
+
attempts: clampIntOr(holdRaw.attempts, RETRY_LIMITS.holdNominalAttempts, 1, RETRY_LIMITS.holdNominalAttempts),
|
|
216
|
+
initialDelayMs: interval,
|
|
217
|
+
maxDelayMs: interval,
|
|
218
|
+
multiplier: 1,
|
|
219
|
+
jitter: false,
|
|
220
|
+
};
|
|
221
|
+
}
|
|
222
|
+
const budget = raw.totalBudgetMs;
|
|
223
|
+
const totalBudgetMs = typeof budget === 'number' && Number.isFinite(budget)
|
|
224
|
+
? Math.min(MAX_LADDER_BUDGET_MS, Math.max(MIN_LADDER_BUDGET_MS, Math.floor(budget)))
|
|
225
|
+
: undefined;
|
|
226
|
+
return { slow, hold, ...(totalBudgetMs !== undefined ? { totalBudgetMs } : {}) };
|
|
227
|
+
}
|
|
150
228
|
/**
|
|
151
229
|
* Whether this failure may be retried at all, ignoring budgets and counters.
|
|
152
230
|
*
|
|
@@ -221,8 +299,12 @@ export function decide(input) {
|
|
|
221
299
|
*/
|
|
222
300
|
export function computeBackoffDelay(retryIndex, policy, opts) {
|
|
223
301
|
const rand = opts?.random ?? Math.random;
|
|
302
|
+
// `ceilingMs` exists for ONE reason: tier 3 must be able to wait 300 s, and the
|
|
303
|
+
// structural ceiling of tier 1 (120 s) lives inside this function. Callers that
|
|
304
|
+
// do not pass it get `absoluteMaxDelayMs` and therefore today's numbers exactly.
|
|
305
|
+
const ceiling = opts?.ceilingMs ?? RETRY_LIMITS.absoluteMaxDelayMs;
|
|
224
306
|
const raw = policy.initialDelayMs * Math.pow(policy.multiplier, Math.max(0, retryIndex - 1));
|
|
225
|
-
const base = Math.min(raw, policy.maxDelayMs,
|
|
307
|
+
const base = Math.min(raw, policy.maxDelayMs, ceiling);
|
|
226
308
|
const jittered = policy.jitter ? base / 2 + rand() * (base / 2) : base;
|
|
227
309
|
// MAX, not replace. A `Retry-After: 1` arriving on the ninth retry must not
|
|
228
310
|
// undo eight retries' worth of backoff — the server is stating a FLOOR ("not
|
|
@@ -230,7 +312,7 @@ export function computeBackoffDelay(retryIndex, policy, opts) {
|
|
|
230
312
|
const withHeader = policy.respectRetryAfter && opts?.retryAfterMs !== undefined
|
|
231
313
|
? Math.max(jittered, opts.retryAfterMs)
|
|
232
314
|
: jittered;
|
|
233
|
-
return Math.round(Math.min(Math.max(withHeader, RETRY_LIMITS.minDelayMs),
|
|
315
|
+
return Math.round(Math.min(Math.max(withHeader, RETRY_LIMITS.minDelayMs), ceiling));
|
|
234
316
|
}
|
|
235
317
|
// ---------------------------------------------------------------------------
|
|
236
318
|
// Retry-After parsing
|
|
@@ -329,6 +411,188 @@ function retryAfterOf(err) {
|
|
|
329
411
|
const v = err?.retryAfterMs;
|
|
330
412
|
return typeof v === 'number' && Number.isFinite(v) && v >= 0 ? v : undefined;
|
|
331
413
|
}
|
|
414
|
+
function rung1(policy) {
|
|
415
|
+
return {
|
|
416
|
+
id: 1,
|
|
417
|
+
policy,
|
|
418
|
+
ceilingMs: RETRY_LIMITS.absoluteMaxDelayMs,
|
|
419
|
+
retryAfterCeilingMs: RETRY_LIMITS.retryAfterCeilingMs,
|
|
420
|
+
unbounded: false,
|
|
421
|
+
};
|
|
422
|
+
}
|
|
423
|
+
function rung2(base, tier) {
|
|
424
|
+
return {
|
|
425
|
+
id: 2,
|
|
426
|
+
ceilingMs: RETRY_LIMITS.escalationMaxDelayMs,
|
|
427
|
+
retryAfterCeilingMs: tier.maxDelayMs,
|
|
428
|
+
unbounded: false,
|
|
429
|
+
policy: {
|
|
430
|
+
// Inherited: `respectRetryAfter` / `onPartialStream` are one user switch
|
|
431
|
+
// each, not per-tier policy.
|
|
432
|
+
...base,
|
|
433
|
+
maxRetries: tier.attempts,
|
|
434
|
+
initialDelayMs: tier.initialDelayMs,
|
|
435
|
+
maxDelayMs: tier.maxDelayMs,
|
|
436
|
+
multiplier: tier.multiplier,
|
|
437
|
+
jitter: tier.jitter,
|
|
438
|
+
// Finite: "N+1 waits" is this tier's natural ceiling, and an infinite budget
|
|
439
|
+
// would have been rewritten by `finiteOr` anyway (§2.2#3).
|
|
440
|
+
maxElapsedMs: (tier.attempts + 1) * tier.maxDelayMs,
|
|
441
|
+
},
|
|
442
|
+
};
|
|
443
|
+
}
|
|
444
|
+
function rung3(base, tier) {
|
|
445
|
+
return {
|
|
446
|
+
id: 3,
|
|
447
|
+
ceilingMs: RETRY_LIMITS.escalationMaxDelayMs,
|
|
448
|
+
retryAfterCeilingMs: tier.maxDelayMs,
|
|
449
|
+
unbounded: true,
|
|
450
|
+
policy: {
|
|
451
|
+
...base,
|
|
452
|
+
// NOMINAL only: a finite value for a `number` field. A test lowers it to prove
|
|
453
|
+
// the ladder crosses it (AC-4).
|
|
454
|
+
maxRetries: tier.attempts,
|
|
455
|
+
initialDelayMs: tier.initialDelayMs,
|
|
456
|
+
maxDelayMs: tier.maxDelayMs,
|
|
457
|
+
multiplier: 1,
|
|
458
|
+
jitter: false,
|
|
459
|
+
// No budget: `unbounded` guarantees the stop never comes; this keeps the
|
|
460
|
+
// arithmetic total.
|
|
461
|
+
maxElapsedMs: Number.MAX_SAFE_INTEGER,
|
|
462
|
+
},
|
|
463
|
+
};
|
|
464
|
+
}
|
|
465
|
+
/** The ladder. `escalation === null` yields ONE rung: a switched-off embedder is
|
|
466
|
+
* then byte-identical to a pre-feature one. */
|
|
467
|
+
function buildRungs(policy, escalation) {
|
|
468
|
+
if (!escalation)
|
|
469
|
+
return [rung1(policy)];
|
|
470
|
+
const rungs = [rung1(policy), rung2(policy, escalation.slow)];
|
|
471
|
+
if (escalation.hold)
|
|
472
|
+
rungs.push(rung3(policy, escalation.hold));
|
|
473
|
+
return rungs;
|
|
474
|
+
}
|
|
475
|
+
/** The tier after `current`, or `undefined` when the ladder is over. */
|
|
476
|
+
function nextRung(current, rungs) {
|
|
477
|
+
return rungs.find((r) => r.id === current.id + 1);
|
|
478
|
+
}
|
|
479
|
+
/**
|
|
480
|
+
* The three reasons that mean "this TIER is done" (G8). Everything else - and
|
|
481
|
+
* `committed` most of all - ends the whole LADDER: escalating that one would
|
|
482
|
+
* `stream_restart` text the user has already read (P0-1 / R-15).
|
|
483
|
+
*/
|
|
484
|
+
const LADDER_END_REASONS = new Set([
|
|
485
|
+
'attempts_exhausted',
|
|
486
|
+
'budget_exhausted',
|
|
487
|
+
'retry_after_too_long',
|
|
488
|
+
]);
|
|
489
|
+
/**
|
|
490
|
+
* Adopt the server's stated wait for THIS tier. Tier 1 is returned untouched, so a
|
|
491
|
+
* `Retry-After: 3600` still stops the fast tier with the provider's own number;
|
|
492
|
+
* tiers 2/3 cap the ADOPTED wait at one tier interval, which is what keeps "every
|
|
493
|
+
* 1 minute", "every 5 minutes" and "about 14 minutes to tier 3" all true at once.
|
|
494
|
+
*/
|
|
495
|
+
function adoptRetryAfter(retryAfterMs, rung) {
|
|
496
|
+
if (retryAfterMs === undefined)
|
|
497
|
+
return undefined;
|
|
498
|
+
if (rung.id === 1)
|
|
499
|
+
return retryAfterMs;
|
|
500
|
+
return Math.min(retryAfterMs, rung.retryAfterCeilingMs);
|
|
501
|
+
}
|
|
502
|
+
function planNextStep(input) {
|
|
503
|
+
const escalating = !input.decision.retry;
|
|
504
|
+
if (escalating && !LADDER_END_REASONS.has(input.decision.reason))
|
|
505
|
+
return undefined;
|
|
506
|
+
const rung = escalating ? nextRung(input.rung, input.rungs) : input.rung;
|
|
507
|
+
if (!rung)
|
|
508
|
+
return undefined;
|
|
509
|
+
if (!escalating)
|
|
510
|
+
return { rung, escalating: false, delay: input.candidateDelay };
|
|
511
|
+
// A new tier's FIRST beat waits its own interval too (§4.1): it is still "one
|
|
512
|
+
// retry", and hammering immediately would repeat the last attempt for free.
|
|
513
|
+
const adopted = adoptRetryAfter(input.retryAfterMs, rung);
|
|
514
|
+
return {
|
|
515
|
+
rung,
|
|
516
|
+
escalating: true,
|
|
517
|
+
delay: computeBackoffDelay(1, rung.policy, {
|
|
518
|
+
...(adopted !== undefined ? { retryAfterMs: adopted } : {}),
|
|
519
|
+
random: input.random,
|
|
520
|
+
ceilingMs: rung.ceilingMs,
|
|
521
|
+
}),
|
|
522
|
+
};
|
|
523
|
+
}
|
|
524
|
+
/**
|
|
525
|
+
* The WHOLE ladder's wall clock, anchored on this request's first failure
|
|
526
|
+
* (§4.3.4). No budget = always `true`, the interactive default; and
|
|
527
|
+
* `ladderStart === undefined` returns `true` on purpose, because "the clock has not
|
|
528
|
+
* started" must never read as "out of budget" (the `NaN` trap `decide` documents).
|
|
529
|
+
*/
|
|
530
|
+
function withinLadderBudget(ladderStart, nextDelay, escalation, now) {
|
|
531
|
+
if (!escalation)
|
|
532
|
+
return true;
|
|
533
|
+
const budget = escalation.totalBudgetMs;
|
|
534
|
+
if (budget === undefined)
|
|
535
|
+
return true;
|
|
536
|
+
if (ladderStart === undefined)
|
|
537
|
+
return true;
|
|
538
|
+
return now() - ladderStart + nextDelay <= budget;
|
|
539
|
+
}
|
|
540
|
+
/**
|
|
541
|
+
* When the CURRENT tier runs out, for the UI only. `undefined` for an unbounded
|
|
542
|
+
* tier; approximate, which is acceptable because no decision reads it.
|
|
543
|
+
*/
|
|
544
|
+
function tierEndsAt(rung, at, attemptInRung) {
|
|
545
|
+
if (rung.unbounded)
|
|
546
|
+
return undefined;
|
|
547
|
+
const remaining = Math.max(0, rung.policy.maxRetries - attemptInRung);
|
|
548
|
+
return at + remaining * rung.policy.maxDelayMs;
|
|
549
|
+
}
|
|
550
|
+
/**
|
|
551
|
+
* Announce, then wait, then announce again: the ONE place `retry_scheduled` and
|
|
552
|
+
* `retry_attempt` are produced. Extracted so `withRetry` stays inside the
|
|
553
|
+
* complexity budget while both paths keep one declaration discipline (G7).
|
|
554
|
+
*/
|
|
555
|
+
async function* announceAndWait(input, sleep, signal) {
|
|
556
|
+
const tier = input.withTier
|
|
557
|
+
? {
|
|
558
|
+
tier: input.rung.id,
|
|
559
|
+
tierCount: input.tierCount,
|
|
560
|
+
totalAttempts: input.totalAttempts,
|
|
561
|
+
...(input.tierEndsAt !== undefined ? { tierEndsAt: input.tierEndsAt } : {}),
|
|
562
|
+
}
|
|
563
|
+
: {};
|
|
564
|
+
if (input.committed) {
|
|
565
|
+
yield { type: 'stream_restart', attempt: input.attempt, discardedToolCallIds: input.toolCallIds };
|
|
566
|
+
}
|
|
567
|
+
yield {
|
|
568
|
+
type: 'retry_scheduled',
|
|
569
|
+
attempt: input.attempt,
|
|
570
|
+
maxRetries: input.rung.policy.maxRetries,
|
|
571
|
+
delayMs: input.delay,
|
|
572
|
+
resumeAt: input.resumeAt,
|
|
573
|
+
errorType: errorTypeOf(input.error),
|
|
574
|
+
message: messageOf(input.error),
|
|
575
|
+
// The provider's own number, UNCAPPED: what we did with it is our policy, but
|
|
576
|
+
// the operator reading the log deserves the truth.
|
|
577
|
+
...(input.retryAfterMs !== undefined ? { retryAfterMs: input.retryAfterMs } : {}),
|
|
578
|
+
...tier,
|
|
579
|
+
};
|
|
580
|
+
await sleep(input.delay, signal); // G2
|
|
581
|
+
if (signal?.aborted === true)
|
|
582
|
+
return; // G3 again: silent
|
|
583
|
+
yield {
|
|
584
|
+
type: 'retry_attempt',
|
|
585
|
+
attempt: input.attempt,
|
|
586
|
+
maxRetries: input.rung.policy.maxRetries,
|
|
587
|
+
...(input.withTier
|
|
588
|
+
? {
|
|
589
|
+
tier: input.rung.id,
|
|
590
|
+
tierCount: input.tierCount,
|
|
591
|
+
totalAttempts: input.totalAttempts,
|
|
592
|
+
}
|
|
593
|
+
: {}),
|
|
594
|
+
};
|
|
595
|
+
}
|
|
332
596
|
/**
|
|
333
597
|
* Wrap a stream factory with retry.
|
|
334
598
|
*
|
|
@@ -346,6 +610,16 @@ function retryAfterOf(err) {
|
|
|
346
610
|
* in-loop guard, the `decide` short-circuit, and the post-sleep check.
|
|
347
611
|
* - G4 — `normalizePolicy` RUNS ONCE, at generator entry, so `RETRY_LIMITS`
|
|
348
612
|
* bounds an embedder's policy and not merely a CLI-resolved one.
|
|
613
|
+
* - G5 — the escalation tiers have their OWN gate (`normalizeEscalation`) and never
|
|
614
|
+
* pass through `normalizePolicy`, whose `finiteOr` would rewrite "no budget" as
|
|
615
|
+
* 240 s and whose `hardMaxRetries` would cut tier 3 to 20 attempts.
|
|
616
|
+
* - G6 — `Retry-After`'s "> 60 s stops the ladder" rule is TIER 1's only; tiers 2/3
|
|
617
|
+
* cap the ADOPTED wait at their own interval and still report the raw number.
|
|
618
|
+
* - G7 — what is announced is what is waited, and the ladder budget is tested
|
|
619
|
+
* BEFORE anything is announced.
|
|
620
|
+
* - G8 — only `attempts_exhausted` / `budget_exhausted` / `retry_after_too_long`
|
|
621
|
+
* end a TIER. `committed` and `not_retryable` end the WHOLE ladder, because
|
|
622
|
+
* escalating `committed` would replay text the user has already read.
|
|
349
623
|
* - THE SUCCESS PATH IS UNTOUCHED. A request that works yields exactly the
|
|
350
624
|
* events the adapter produced, in the same order, with no extra allocation
|
|
351
625
|
* beyond one boolean and one empty array. The wrapper is not installed at all
|
|
@@ -358,13 +632,22 @@ function retryAfterOf(err) {
|
|
|
358
632
|
*/
|
|
359
633
|
export async function* withRetry(makeStream, opts) {
|
|
360
634
|
const policy = normalizePolicy(opts.policy);
|
|
635
|
+
const escalation = normalizeEscalation(opts.escalation ?? null);
|
|
636
|
+
const rungs = buildRungs(policy, escalation);
|
|
361
637
|
const now = opts.now ?? Date.now;
|
|
362
638
|
const sleep = opts.sleep ?? defaultSleep;
|
|
363
639
|
const random = opts.random ?? Math.random;
|
|
364
640
|
const signal = opts.signal;
|
|
641
|
+
const withTier = escalation !== null;
|
|
642
|
+
/** Clock for the WHOLE ladder (only `totalBudgetMs` reads it). */
|
|
643
|
+
let firstFailureAtLadder;
|
|
644
|
+
/** Clock for the CURRENT tier (only `decide`'s budget reads it). */
|
|
365
645
|
let firstFailureAt;
|
|
366
|
-
/** Retries COMPLETED so far. */
|
|
367
|
-
let
|
|
646
|
+
/** Retries COMPLETED so far inside the current tier. */
|
|
647
|
+
let attemptInRung = 0;
|
|
648
|
+
/** Retries COMPLETED so far in this request, across tiers (D-7). */
|
|
649
|
+
let totalAttempts = 0;
|
|
650
|
+
let rung = rungs[Math.max(0, (opts.startRung ?? 1) - 1)] ?? rungs[0];
|
|
368
651
|
for (;;) {
|
|
369
652
|
if (Boolean(signal?.aborted))
|
|
370
653
|
return;
|
|
@@ -409,54 +692,82 @@ export async function* withRetry(makeStream, opts) {
|
|
|
409
692
|
terminalError = new LLMError(`${opts.providerId}/${opts.modelId} stream ended without producing a done or error event`, opts.providerId, 'network_error', true);
|
|
410
693
|
}
|
|
411
694
|
// ---- ORDER IS NORMATIVE FROM HERE -----------------------------------
|
|
412
|
-
// 1. Anchor
|
|
695
|
+
// 1. Anchor BOTH clocks on the FIRST failure. Reading `firstFailureAt` before
|
|
696
|
+
// anchoring computes `NaN`, and `NaN > budget` is false: a budget that never
|
|
697
|
+
// triggers, silently.
|
|
698
|
+
firstFailureAtLadder ??= now();
|
|
413
699
|
firstFailureAt ??= now();
|
|
414
|
-
// 2.
|
|
415
|
-
// because `computeBackoffDelay` is 1-based and `
|
|
700
|
+
// 2. The server's floor, adopted per THIS tier (D-8). `attemptInRung + 1`
|
|
701
|
+
// because `computeBackoffDelay` is 1-based and `attemptInRung` counts
|
|
416
702
|
// COMPLETED retries.
|
|
417
|
-
const retryAfterMs = policy.respectRetryAfter ? retryAfterOf(terminalError) : undefined;
|
|
418
|
-
const
|
|
419
|
-
|
|
703
|
+
const retryAfterMs = rung.policy.respectRetryAfter ? retryAfterOf(terminalError) : undefined;
|
|
704
|
+
const adoptedRetryAfterMs = adoptRetryAfter(retryAfterMs, rung);
|
|
705
|
+
const candidateDelay = computeBackoffDelay(attemptInRung + 1, rung.policy, {
|
|
706
|
+
...(adoptedRetryAfterMs !== undefined ? { retryAfterMs: adoptedRetryAfterMs } : {}),
|
|
420
707
|
random,
|
|
708
|
+
ceilingMs: rung.ceilingMs,
|
|
421
709
|
});
|
|
422
|
-
// 3. Only now can `decide` answer the budget question.
|
|
423
|
-
|
|
710
|
+
// 3. Only now can `decide` answer the budget question. G6: `retryAfterMs` goes
|
|
711
|
+
// to `decide` for TIER 1 ONLY, so "come back in an hour" still stops the fast
|
|
712
|
+
// tier honestly and never stops tiers 2/3.
|
|
713
|
+
let decision = decide({
|
|
424
714
|
error: terminalError,
|
|
425
715
|
...(signal ? { signal } : {}),
|
|
426
716
|
committed,
|
|
427
|
-
retryIndex,
|
|
717
|
+
retryIndex: attemptInRung,
|
|
428
718
|
firstFailureAt,
|
|
429
719
|
candidateDelay,
|
|
430
|
-
...(retryAfterMs !== undefined ? { retryAfterMs } : {}),
|
|
431
|
-
policy,
|
|
720
|
+
...(rung.id === 1 && retryAfterMs !== undefined ? { retryAfterMs } : {}),
|
|
721
|
+
policy: rung.policy,
|
|
432
722
|
now,
|
|
433
723
|
});
|
|
724
|
+
// Tier 3's ONLY definition of "unbounded": rewrite the nominal count into
|
|
725
|
+
// "keep going", and change nothing else `decide` said (T-2).
|
|
726
|
+
if (rung.unbounded && decision.reason === 'attempts_exhausted') {
|
|
727
|
+
decision = { retry: true, reason: 'retryable' };
|
|
728
|
+
}
|
|
434
729
|
if (decision.reason === 'aborted')
|
|
435
730
|
return; // G3 — no trailing error event
|
|
436
|
-
|
|
731
|
+
const plan = planNextStep({
|
|
732
|
+
decision,
|
|
733
|
+
rung,
|
|
734
|
+
rungs,
|
|
735
|
+
candidateDelay,
|
|
736
|
+
...(retryAfterMs !== undefined ? { retryAfterMs } : {}),
|
|
737
|
+
random,
|
|
738
|
+
});
|
|
739
|
+
if (!plan) {
|
|
437
740
|
yield { type: 'error', error: terminalError };
|
|
438
741
|
return;
|
|
439
742
|
}
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
743
|
+
if (plan.escalating) {
|
|
744
|
+
// The TIER clock restarts; the LADDER clock does not (§4.1).
|
|
745
|
+
firstFailureAt = undefined;
|
|
746
|
+
attemptInRung = 0;
|
|
747
|
+
}
|
|
748
|
+
rung = plan.rung;
|
|
749
|
+
attemptInRung += 1;
|
|
750
|
+
totalAttempts += 1;
|
|
751
|
+
// BEFORE announcing, never after: a wait we would not perform must not be
|
|
752
|
+
// declared (G7). `totalBudgetMs` exists only because a user asked for a cap.
|
|
753
|
+
if (!withinLadderBudget(firstFailureAtLadder, plan.delay, escalation, now)) {
|
|
754
|
+
yield { type: 'error', error: terminalError };
|
|
755
|
+
return;
|
|
446
756
|
}
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
757
|
+
const endsAt = withTier ? tierEndsAt(rung, now(), attemptInRung) : undefined;
|
|
758
|
+
yield* announceAndWait({
|
|
759
|
+
rung,
|
|
760
|
+
tierCount: rungs.length,
|
|
761
|
+
attempt: attemptInRung,
|
|
762
|
+
totalAttempts,
|
|
763
|
+
delay: plan.delay,
|
|
764
|
+
resumeAt: now() + plan.delay,
|
|
765
|
+
error: terminalError,
|
|
766
|
+
committed,
|
|
767
|
+
toolCallIds,
|
|
455
768
|
...(retryAfterMs !== undefined ? { retryAfterMs } : {}),
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
return; // G3 again: silent
|
|
460
|
-
yield { type: 'retry_attempt', attempt: retryIndex, maxRetries: policy.maxRetries };
|
|
769
|
+
...(endsAt !== undefined ? { tierEndsAt: endsAt } : {}),
|
|
770
|
+
withTier,
|
|
771
|
+
}, sleep, signal);
|
|
461
772
|
}
|
|
462
773
|
}
|
package/dist/llm/types.d.ts
CHANGED
|
@@ -7,6 +7,7 @@
|
|
|
7
7
|
* structures.
|
|
8
8
|
*/
|
|
9
9
|
import type { LLMErrorType } from './provider.js';
|
|
10
|
+
import type { RetryTierId } from './retry.js';
|
|
10
11
|
export interface TextContentPart {
|
|
11
12
|
type: 'text';
|
|
12
13
|
text: string;
|
|
@@ -102,7 +103,15 @@ export interface ErrorEvent {
|
|
|
102
103
|
/** A retryable failure occurred; the next attempt fires at `resumeAt`. */
|
|
103
104
|
export interface RetryScheduledEvent {
|
|
104
105
|
type: 'retry_scheduled';
|
|
105
|
-
/**
|
|
106
|
+
/**
|
|
107
|
+
* 1-based retry index **WITHIN THE CURRENT TIER**.
|
|
108
|
+
*
|
|
109
|
+
* The semantics of `attempt` / `maxRetries` did NOT change when tiers arrived
|
|
110
|
+
* (tiered-reconnect D-7 / T-3): every existing reader divides, percentiles and
|
|
111
|
+
* renders them as "this tier's nth of m", and turning them into a cross-tier
|
|
112
|
+
* counter would make `attempt > maxRetries` and every one of those values
|
|
113
|
+
* meaningless. The cross-tier total is `totalAttempts` below.
|
|
114
|
+
*/
|
|
106
115
|
attempt: number;
|
|
107
116
|
maxRetries: number;
|
|
108
117
|
delayMs: number;
|
|
@@ -121,12 +130,27 @@ export interface RetryScheduledEvent {
|
|
|
121
130
|
message: string;
|
|
122
131
|
/** Present only when the provider stated one. */
|
|
123
132
|
retryAfterMs?: number;
|
|
133
|
+
/** Which tier is retrying: 1 = today's fast ladder, 2 = 1-minute, 3 = 5-minute. */
|
|
134
|
+
tier?: RetryTierId;
|
|
135
|
+
/** How many tiers this ladder has: 2 = bounded (headless), 3 = full (TUI). */
|
|
136
|
+
tierCount?: number;
|
|
137
|
+
/** Retries completed in THIS REQUEST, across all tiers (D-7). */
|
|
138
|
+
totalAttempts?: number;
|
|
139
|
+
/** When the current tier runs out. Absent on tier 3: it never does. */
|
|
140
|
+
tierEndsAt?: number;
|
|
124
141
|
}
|
|
125
142
|
/** The wait is over; attempt `attempt` is going out now. */
|
|
126
143
|
export interface RetryAttemptEvent {
|
|
127
144
|
type: 'retry_attempt';
|
|
145
|
+
/** Within the current tier — see `RetryScheduledEvent.attempt`. */
|
|
128
146
|
attempt: number;
|
|
129
147
|
maxRetries: number;
|
|
148
|
+
/** Which tier is retrying. Absent when escalation is off. */
|
|
149
|
+
tier?: RetryTierId;
|
|
150
|
+
/** How many tiers this ladder has. Absent when escalation is off. */
|
|
151
|
+
tierCount?: number;
|
|
152
|
+
/** Retries completed in this request, across all tiers. */
|
|
153
|
+
totalAttempts?: number;
|
|
130
154
|
}
|
|
131
155
|
/**
|
|
132
156
|
* Content already forwarded this turn is being discarded and replayed.
|
package/dist/types.d.ts
CHANGED
|
@@ -18,6 +18,38 @@ export interface AgentStartEvent {
|
|
|
18
18
|
* feature: `Object.keys(end)` is `['messages', 'type']` on the happy path.
|
|
19
19
|
*/
|
|
20
20
|
export type AgentEndReason = 'llm_error' | 'idle_watchdog';
|
|
21
|
+
/**
|
|
22
|
+
* What the run was doing when the idle watchdog gave up on it
|
|
23
|
+
* (`team-idle-watchdog-dead-run` F0).
|
|
24
|
+
*
|
|
25
|
+
* The `run_end` log row used to say only "the watchdog fired", so a silence that
|
|
26
|
+
* began while the model was still waiting for its first byte, one that began in
|
|
27
|
+
* the middle of a long tool-call argument and one that began while a local tool
|
|
28
|
+
* was running all looked identical, and the next investigation had to infer the
|
|
29
|
+
* stage from the gap to the previous log line. Every field is a FACT the engine
|
|
30
|
+
* already holds at that instant; nothing here is a guess about why.
|
|
31
|
+
*
|
|
32
|
+
* `msSinceLastEvent` (monotonic) and `wallMsSinceLastEvent` (wall clock) are both
|
|
33
|
+
* recorded on purpose: when the machine was suspended the two diverge by the
|
|
34
|
+
* length of the sleep, which is the only way to tell "the network went quiet"
|
|
35
|
+
* from "this laptop was asleep" in a log read afterwards.
|
|
36
|
+
*/
|
|
37
|
+
export type AgentStallPhase = 'awaiting_response' | 'thinking' | 'text' | 'tool_input' | 'tool_running' | 'between_turns';
|
|
38
|
+
export interface AgentStallInfo {
|
|
39
|
+
phase: AgentStallPhase;
|
|
40
|
+
/** The last engine event before the silence (`message_update:text_delta`, ...). */
|
|
41
|
+
lastEvent: string;
|
|
42
|
+
/** Silence measured on the monotonic clock (`performance.now`). */
|
|
43
|
+
msSinceLastEvent: number;
|
|
44
|
+
/** The same silence on the wall clock (`Date.now`). */
|
|
45
|
+
wallMsSinceLastEvent: number;
|
|
46
|
+
/** Engine events emitted since `agent_start`. NOT raw SSE frames: the engine never sees those. */
|
|
47
|
+
eventsSeen: number;
|
|
48
|
+
/** The window the watchdog was armed with. */
|
|
49
|
+
idleTimeoutMs: number;
|
|
50
|
+
/** The tool being written (`tool_input`) or run (`tool_running`), when there was one. */
|
|
51
|
+
toolName?: string;
|
|
52
|
+
}
|
|
21
53
|
export interface AgentEndEvent {
|
|
22
54
|
type: 'agent_end';
|
|
23
55
|
messages: Message[];
|
|
@@ -39,6 +71,12 @@ export interface AgentEndEvent {
|
|
|
39
71
|
*/
|
|
40
72
|
retryable?: boolean;
|
|
41
73
|
reason?: AgentEndReason;
|
|
74
|
+
/**
|
|
75
|
+
* Present ONLY when `reason` is `idle_watchdog`: where the run went quiet.
|
|
76
|
+
* Absent on every other `agent_end`, so the happy path keeps its
|
|
77
|
+
* `['messages', 'type']` shape.
|
|
78
|
+
*/
|
|
79
|
+
stall?: AgentStallInfo;
|
|
42
80
|
}
|
|
43
81
|
export interface TurnStartEvent {
|
|
44
82
|
type: 'turn_start';
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@aragon-agent/core",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.77",
|
|
4
4
|
"description": "AragonAgent core engine — LLM provider adapters, streaming, tool registry/execution, steering, idle watchdog, and an optional isolated-vm sandbox.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "AragonAgent contributors",
|