@aragon-agent/core 0.2.76 → 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.
@@ -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) {
@@ -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;
@@ -123,6 +123,8 @@ export class Agent {
123
123
  sandbox;
124
124
  contextManager;
125
125
  projectMessages;
126
+ /** Tiered reconnect: read once per run, so the host's config stays live (§4.4). */
127
+ resolveEscalation;
126
128
  // --- LLM generation parameters ---
127
129
  maxTokens;
128
130
  // --- Timeouts ---
@@ -157,6 +159,7 @@ export class Agent {
157
159
  this.sandbox = config.sandbox;
158
160
  this.contextManager = config.contextManager;
159
161
  this.projectMessages = config.projectMessages;
162
+ this.resolveEscalation = config.resolveEscalation;
160
163
  this.maxTokens = config.maxTokens;
161
164
  // Timeouts
162
165
  this.llmCallTimeout = config.timeouts?.llmCallTimeout ?? DEFAULT_LLM_CALL_TIMEOUT;
@@ -441,6 +444,10 @@ export class Agent {
441
444
  this.abortController = new AbortController();
442
445
  this.watchdog.start();
443
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;
444
451
  try {
445
452
  await runAgentLoop({
446
453
  providerRegistry: this.providerRegistry,
@@ -461,6 +468,10 @@ export class Agent {
461
468
  // which is what makes the byte-identity claim in AC-1 provable.
462
469
  ...(this.contextManager ? { contextManager: this.contextManager } : {}),
463
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 } : {}),
464
475
  signal: this.abortController.signal,
465
476
  timeouts: {
466
477
  llmCallTimeout: this.llmCallTimeout,
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';
@@ -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
  /**
@@ -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, RETRY_LIMITS.absoluteMaxDelayMs);
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), RETRY_LIMITS.absoluteMaxDelayMs));
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 retryIndex = 0;
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 the budget clock on the FIRST failure, before anything reads it.
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. Derive the candidate wait for the NEXT attempt. `retryIndex + 1`
415
- // because `computeBackoffDelay` is 1-based and `retryIndex` counts
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 candidateDelay = computeBackoffDelay(retryIndex + 1, policy, {
419
- ...(retryAfterMs !== undefined ? { retryAfterMs } : {}),
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
- const decision = decide({
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
- if (!decision.retry) {
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
- retryIndex += 1;
441
- // What we ANNOUNCE is what we WAIT. Recomputing here would let the card and
442
- // the timer disagree by a jitter draw.
443
- const delay = candidateDelay;
444
- if (committed) {
445
- yield { type: 'stream_restart', attempt: retryIndex, discardedToolCallIds: toolCallIds };
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
- yield {
448
- type: 'retry_scheduled',
449
- attempt: retryIndex,
450
- maxRetries: policy.maxRetries,
451
- delayMs: delay,
452
- resumeAt: now() + delay,
453
- errorType: errorTypeOf(terminalError),
454
- message: messageOf(terminalError),
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
- await sleep(delay, signal); // G2
458
- if (signal?.aborted === true)
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
  }
@@ -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
- /** 1-based retry index. */
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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aragon-agent/core",
3
- "version": "0.2.76",
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",