@aragon-agent/core 0.2.93 → 0.2.94

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.
Files changed (48) hide show
  1. package/dist/engine/accept-steering.js +1 -15
  2. package/dist/engine/agent-loop.js +1 -533
  3. package/dist/engine/agent.js +1 -538
  4. package/dist/engine/compaction.js +1 -268
  5. package/dist/engine/context-manager.js +1 -13
  6. package/dist/engine/message-manager.js +1 -39
  7. package/dist/engine/steering.js +1 -72
  8. package/dist/engine/tool-result-content.js +1 -39
  9. package/dist/engine/watchdog.js +1 -73
  10. package/dist/index.js +1 -99
  11. package/dist/llm/context-window.js +1 -46
  12. package/dist/llm/image-tokens.js +1 -11
  13. package/dist/llm/model-discovery.js +1 -18
  14. package/dist/llm/model-registry.js +1 -370
  15. package/dist/llm/output-limit-recovery.js +1 -263
  16. package/dist/llm/output-limits.js +1 -283
  17. package/dist/llm/provider.js +1 -171
  18. package/dist/llm/providers/anthropic.js +1 -514
  19. package/dist/llm/providers/google.js +1 -464
  20. package/dist/llm/providers/index.js +1 -205
  21. package/dist/llm/providers/openai.js +1 -520
  22. package/dist/llm/providers/tool-result-images.js +1 -52
  23. package/dist/llm/retry.js +1 -948
  24. package/dist/llm/sse-parser.js +1 -103
  25. package/dist/llm/stream-utils.js +1 -118
  26. package/dist/llm/types.js +1 -17
  27. package/dist/sandbox/console-capture.js +1 -56
  28. package/dist/sandbox/http-bridge.js +1 -143
  29. package/dist/sandbox/isolated-vm-sandbox.js +1 -226
  30. package/dist/sandbox/tool-bridge.js +1 -98
  31. package/dist/sandbox/types.js +1 -8
  32. package/dist/skills/constants.js +1 -179
  33. package/dist/skills/disclosure.js +1 -788
  34. package/dist/skills/frontmatter.js +1 -177
  35. package/dist/skills/index.js +1 -18
  36. package/dist/skills/skill-find-tool.js +1 -117
  37. package/dist/skills/skill-registry.js +1 -208
  38. package/dist/skills/skill-tool.js +1 -96
  39. package/dist/skills/tool-policy.js +1 -272
  40. package/dist/skills/types.js +1 -8
  41. package/dist/skills/validate.js +1 -264
  42. package/dist/tools/executor.js +1 -281
  43. package/dist/tools/helpers.js +1 -87
  44. package/dist/tools/registry.js +1 -119
  45. package/dist/tools/types.js +1 -7
  46. package/dist/tools/validator.js +1 -210
  47. package/dist/types.js +1 -7
  48. package/package.json +3 -2
package/dist/llm/retry.js CHANGED
@@ -1,948 +1 @@
1
- /**
2
- * Retry & exponential backoff — THE authority for "a provider call failed, now
3
- * what" (llm-api-retry-backoff §4).
4
- *
5
- * One module owns the policy type, the classification predicate, the backoff
6
- * arithmetic and a single generator `withRetry()` that wraps ANY
7
- * `AsyncIterableIterator<StreamEvent>`. `ProviderRegistry.stream()` applies it,
8
- * so all three adapters, the lead agent and every subagent inherit retry with
9
- * zero call-site changes.
10
- *
11
- * THE WRAPPER IS THE ONLY LAYER THAT CAN DO THIS JOB, and that is why it lives
12
- * here rather than in the adapters or in `runAgentLoop` (§3.1 / §3.2):
13
- *
14
- * - it knows whether any CONTENT has already been forwarded downstream (the
15
- * commit point), which decides whether a replay would duplicate text on the
16
- * user's screen;
17
- * - it holds the `AbortSignal`, which is what keeps a user pressing Esc from
18
- * being mistaken for a retryable timeout;
19
- * - it can emit its own events, which is what turns a silent 40-second stall
20
- * into a countdown a user can read.
21
- *
22
- * NO `node:*` IMPORTS. `no-host-coupling.test.ts` rule 2 bans every one of them
23
- * under core `src/` with a single grandfathered exception, so the abortable
24
- * `sleep` below uses the GLOBAL `setTimeout` plus one `abort` listener rather
25
- * than `node:timers/promises` (whose `setTimeout` takes `{ signal }` natively
26
- * and would be the idiomatic choice anywhere else).
27
- */
28
- import { LLMError } from './provider.js';
29
- // ---------------------------------------------------------------------------
30
- // Structural bounds
31
- // ---------------------------------------------------------------------------
32
- /**
33
- * Structural bounds. NOT user policy: these describe what the mechanism can
34
- * physically do, and a hand-edited config must not be able to exceed them.
35
- * (The same split `TEAM_LIMITS` states for team mode, one package over.)
36
- *
37
- * ENFORCED AT THIS BOUNDARY by `normalizePolicy`, not only by the CLI's
38
- * `clampRetryConfig` (§4.5 G4). Hardening one path and leaving the other open
39
- * would let an embedder passing `{ maxRetries: 5000 }` get 5000.
40
- */
41
- export const RETRY_LIMITS = {
42
- /** Ceiling on `maxRetries` from any layer. */
43
- hardMaxRetries: 20,
44
- /** Ceiling on one wait, whatever the config or a `Retry-After` header says. */
45
- absoluteMaxDelayMs: 120_000,
46
- /**
47
- * A `Retry-After` LARGER than this is not honoured and not retried — it is
48
- * surfaced immediately with the provider's own number in the message. A
49
- * provider asking us to come back in an hour is telling the user something,
50
- * and silently wedging the terminal for an hour is not relaying it.
51
- */
52
- retryAfterCeilingMs: 60_000,
53
- /** Floor under any computed wait, so jitter can never produce a 0 ms "retry". */
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,
71
- };
72
- export const DEFAULT_RETRY_POLICY = {
73
- maxRetries: 10,
74
- initialDelayMs: 1_000,
75
- /**
76
- * Core's default `idleTimeout` is 60 000 ms. Even with the watchdog pause of
77
- * §4.6 in place, a single wait longer than half the idle window is a design
78
- * smell: it means the mechanism depends on the pause being correct rather
79
- * than merely benefiting from it. Two independent guards, and the numeric one
80
- * costs nothing.
81
- */
82
- maxDelayMs: 30_000,
83
- multiplier: 2,
84
- jitter: true,
85
- respectRetryAfter: true,
86
- /**
87
- * 240 s, NOT 300 s. The CLI's `DEFAULT_TEAM_CONFIG.subagentTimeoutMs` is
88
- * 300 000, and a retry budget EQUAL to the per-child timeout means the child
89
- * is killed at the same instant its ladder ends — the user is then told
90
- * "subagent timed out" for what was a provider outage. 240 s fits the full
91
- * ten-step ladder (181 s worst case) with 59 s of headroom and still leaves
92
- * the child 60 s of its own window to actually produce an answer.
93
- *
94
- * THE INVARIANT IS `maxElapsedMs + one model round-trip <
95
- * team.subagentTimeoutMs` (§5.6). It is invisible at both edit sites, so the
96
- * CLI's `retry-config.test.ts` pins the inequality statically.
97
- */
98
- maxElapsedMs: 240_000,
99
- onPartialStream: true,
100
- };
101
- /**
102
- * The read-side silence window a policy that says nothing gets: **45 s**, and
103
- * DELIBERATELY BELOW core's own `DEFAULT_IDLE_TIMEOUT` (60 s), because the
104
- * deadline must fire before the watchdog or the ladder never gets a turn. A host
105
- * with a WIDER window keeps 45 s; a host with a NARROWER one has it narrowed
106
- * further by `resolveReadSilenceMs`, never left behind.
107
- *
108
- * NOT a field of `DEFAULT_RETRY_POLICY`, and that is load-bearing (F1′).
109
- * `DEFAULT_RETRY_POLICY` is PUBLIC and is compared WHOLE: the CLI's
110
- * `retry-config.test.ts` pins `toRetryPolicy(DEFAULT_RETRY_CONFIG)` deep-equal to
111
- * it, and that transform copies the eight keys a user can actually configure. A
112
- * ninth key here would make every host-built policy unequal to this object for a
113
- * value the host cannot express — so the default lives here, and `normalizePolicy`
114
- * folds it in at the one place a policy is made ready to run.
115
- */
116
- export const DEFAULT_READ_SILENCE_MS = 45_000;
117
- /**
118
- * The events that mean "the consumer has already rendered answer content", i.e.
119
- * the commit point (§4.5a).
120
- *
121
- * `thinking_start` is in the set even though it carries no text: it flips
122
- * `thinkingOpen` in the CLI reducer, which is visible state a restart must
123
- * rewind. The tool events are in the set because `tool_call_start` appends a
124
- * transcript card — that is why `stream_restart` carries `discardedToolCallIds`
125
- * at all. `done` and `error` are terminal, not content; the three `retry_*`
126
- * variants are ours and never round-trip through `makeStream()`.
127
- */
128
- export const CONTENT_EVENTS = new Set([
129
- 'text_delta',
130
- 'thinking_start',
131
- 'thinking_delta',
132
- 'tool_call_start',
133
- 'tool_call_delta',
134
- 'tool_call_end',
135
- ]);
136
- /**
137
- * The window ONE attempt may stay silent, given the host's idle-watchdog window.
138
- *
139
- * TWO BOUNDS, ONE NUMBER. The policy states the intent (45 s by default); the
140
- * watchdog states the hard ceiling, because a deadline that fires AFTER the
141
- * watchdog has already aborted the run is not a recovery mechanism — it is the
142
- * same death with extra steps. 60 % of the window leaves the remaining 40 % for
143
- * the backoff and the next attempt to land before the watchdog's own timer would
144
- * have expired; each retry re-kicks that timer as well.
145
- *
146
- * Returns `0` — "no deadline" — for a policy that opts out or has the ladder
147
- * switched off (`maxRetries <= 0`), so an opted-out embedder stays byte-identical
148
- * to a build that never had this feature.
149
- */
150
- export function resolveReadSilenceMs(policy, watchdogWindowMs) {
151
- if (!policy || policy.maxRetries <= 0)
152
- return 0;
153
- // `0` IS A VALUE, not an absence: it is how a caller says "no read deadline",
154
- // and reading it as "unset" would hand back the default and silently re-enable
155
- // exactly what the caller switched off.
156
- const configured = policy.readSilenceMs;
157
- const wanted = typeof configured === 'number' && Number.isFinite(configured)
158
- ? Math.max(0, configured)
159
- : DEFAULT_READ_SILENCE_MS;
160
- if (wanted <= 0)
161
- return 0;
162
- if (typeof watchdogWindowMs === 'number' &&
163
- Number.isFinite(watchdogWindowMs) &&
164
- watchdogWindowMs > 0) {
165
- return Math.max(RETRY_LIMITS.minDelayMs, Math.min(wanted, Math.floor(watchdogWindowMs * 0.6)));
166
- }
167
- return wanted;
168
- }
169
- // ---------------------------------------------------------------------------
170
- // normalizePolicy
171
- // ---------------------------------------------------------------------------
172
- function finiteOr(value, fallback) {
173
- return typeof value === 'number' && Number.isFinite(value) ? value : fallback;
174
- }
175
- /**
176
- * Clamp a policy to `RETRY_LIMITS`. Pure, total, and it NEVER THROWS — a bad
177
- * policy is corrected rather than rejected, because the alternative is a
178
- * library that crashes on a config typo.
179
- *
180
- * Module-internal by intent: exported so `llm-retry.test.ts` may import it
181
- * directly, but deliberately NOT re-exported from the barrel. The public
182
- * assertion is made THROUGH `withRetry`, which is also the only way to catch
183
- * this being present but unwired.
184
- */
185
- export function normalizePolicy(policy) {
186
- const maxRetries = Math.min(RETRY_LIMITS.hardMaxRetries, Math.max(0, Math.floor(finiteOr(policy.maxRetries, DEFAULT_RETRY_POLICY.maxRetries))));
187
- const maxDelayMs = Math.min(RETRY_LIMITS.absoluteMaxDelayMs, Math.max(RETRY_LIMITS.minDelayMs, Math.floor(finiteOr(policy.maxDelayMs, DEFAULT_RETRY_POLICY.maxDelayMs))));
188
- const initialDelayMs = Math.min(maxDelayMs, Math.max(RETRY_LIMITS.minDelayMs, Math.floor(finiteOr(policy.initialDelayMs, DEFAULT_RETRY_POLICY.initialDelayMs))));
189
- const multiplier = Math.max(1, finiteOr(policy.multiplier, DEFAULT_RETRY_POLICY.multiplier));
190
- /**
191
- * FLOORED AT `minDelayMs`, NOT AT `initialDelayMs`.
192
- *
193
- * `>= initialDelayMs` reads like the tighter bound and is the wrong one: it
194
- * would make "give up after 500 ms in total" unexpressible by silently raising
195
- * the budget to the first delay, at which point the first retry always fires —
196
- * so a budget SMALLER than one wait would stop being a budget at all, silently.
197
- * The CLI's own range for this key already starts at 10 000, so nothing a user
198
- * can type reaches the difference; what does reach it is a unit test asserting
199
- * that the budget is evaluated on the FIRST failure, which is the one property
200
- * a mis-ordered implementation gets wrong. See the spec's implementation-findings
201
- * section (IF-2).
202
- */
203
- const maxElapsedMs = Math.max(RETRY_LIMITS.minDelayMs, Math.floor(finiteOr(policy.maxElapsedMs, DEFAULT_RETRY_POLICY.maxElapsedMs)));
204
- return {
205
- maxRetries,
206
- initialDelayMs,
207
- maxDelayMs,
208
- multiplier,
209
- jitter: policy.jitter !== false,
210
- respectRetryAfter: policy.respectRetryAfter !== false,
211
- maxElapsedMs,
212
- onPartialStream: policy.onPartialStream !== false,
213
- // `0` is a MEANING ("no read deadline"), never a typo: only a negative or
214
- // non-finite value falls back to the default.
215
- readSilenceMs: typeof policy.readSilenceMs === 'number' && Number.isFinite(policy.readSilenceMs)
216
- ? Math.max(0, Math.floor(policy.readSilenceMs))
217
- : DEFAULT_READ_SILENCE_MS,
218
- };
219
- }
220
- const DEFAULT_TIER = {
221
- attempts: 10,
222
- initialDelayMs: 60_000,
223
- maxDelayMs: 60_000,
224
- multiplier: 1,
225
- jitter: false,
226
- };
227
- const DEFAULT_HOLD_INTERVAL_MS = 300_000;
228
- const MAX_LADDER_BUDGET_MS = 24 * 3600_000;
229
- const MIN_LADDER_BUDGET_MS = 60_000;
230
- function clampIntOr(value, fallback, min, max) {
231
- const v = Math.floor(finiteOr(value, fallback));
232
- return Math.min(max, Math.max(min, v));
233
- }
234
- /**
235
- * Clamp an arbitrary escalation; `null` means "do not escalate".
236
- *
237
- * G5: THIS IS THE TIERS' OWN GATE and its output never passes through
238
- * `normalizePolicy`, whose `finiteOr` would rewrite "no budget" as 240 000 and
239
- * whose `hardMaxRetries` would cut tier 3 to 20 attempts (§2.2#2/#3).
240
- */
241
- export function normalizeEscalation(raw) {
242
- if (!raw || typeof raw !== 'object')
243
- return null;
244
- const slowRaw = raw.slow;
245
- if (!slowRaw || typeof slowRaw !== 'object')
246
- return null;
247
- const slowAttempts = clampIntOr(slowRaw.attempts, DEFAULT_TIER.attempts, 0, RETRY_LIMITS.hardMaxSlowAttempts);
248
- // ZERO TIER-2 ATTEMPTS IS "NO ESCALATION", never "skip to the hold tier": a
249
- // shape nobody asked for must not be reachable through a config typo.
250
- if (slowAttempts === 0)
251
- return null;
252
- const slowInitial = clampIntOr(slowRaw.initialDelayMs, DEFAULT_TIER.initialDelayMs, RETRY_LIMITS.minDelayMs, RETRY_LIMITS.escalationMaxDelayMs);
253
- const slow = {
254
- attempts: slowAttempts,
255
- initialDelayMs: slowInitial,
256
- // Same invariant `clampRetryConfig` keeps: a ceiling below the floor makes the
257
- // ladder a lie about what the user sees.
258
- maxDelayMs: Math.max(clampIntOr(slowRaw.maxDelayMs, slowInitial, RETRY_LIMITS.minDelayMs, RETRY_LIMITS.escalationMaxDelayMs), slowInitial),
259
- multiplier: Math.min(5, Math.max(1, finiteOr(slowRaw.multiplier, 1))),
260
- jitter: false,
261
- };
262
- const holdRaw = raw.hold;
263
- let hold = null;
264
- if (holdRaw && typeof holdRaw === 'object') {
265
- const interval = clampIntOr(holdRaw.initialDelayMs, DEFAULT_HOLD_INTERVAL_MS, RETRY_LIMITS.holdMinDelayMs, RETRY_LIMITS.escalationMaxDelayMs);
266
- // ONE interval in both fields: tiers 2/3 are flat, and a `maxDelayMs` that
267
- // disagreed with `initialDelayMs` would make the countdown lie (G7).
268
- hold = {
269
- attempts: clampIntOr(holdRaw.attempts, RETRY_LIMITS.holdNominalAttempts, 1, RETRY_LIMITS.holdNominalAttempts),
270
- initialDelayMs: interval,
271
- maxDelayMs: interval,
272
- multiplier: 1,
273
- jitter: false,
274
- };
275
- }
276
- const budget = raw.totalBudgetMs;
277
- const totalBudgetMs = typeof budget === 'number' && Number.isFinite(budget)
278
- ? Math.min(MAX_LADDER_BUDGET_MS, Math.max(MIN_LADDER_BUDGET_MS, Math.floor(budget)))
279
- : undefined;
280
- return { slow, hold, ...(totalBudgetMs !== undefined ? { totalBudgetMs } : {}) };
281
- }
282
- /**
283
- * Whether this failure may be retried at all, ignoring budgets and counters.
284
- *
285
- * THE ORDER OF THE TWO CHECKS IS LOAD-BEARING.
286
- *
287
- * 1. `signal?.aborted === true` COMES FIRST. `wrapFetchError` classifies an
288
- * `AbortError` as `errorType: 'timeout', retryable: true`, so every user Esc,
289
- * every `AgentController.abort()`, every dispatch timeout and every
290
- * tool-timeout cancellation arrives here wearing a retryable badge. The CLI's
291
- * `team/retry.ts` records this trap in thirty lines of comment because it
292
- * cost someone an afternoon; reading the signal BEFORE `err.retryable` is
293
- * what makes Esc mean Esc.
294
- * 2. `retryable` is read STRUCTURALLY, never with `instanceof LLMError`. The
295
- * error crosses a package boundary, and a duplicated core instance (a linked
296
- * checkout, a hoisting accident) would make `instanceof` false while the
297
- * field is plainly there — and the failure mode would be "retries silently
298
- * stopped happening". This is the rule `isRetryableStreamError` and
299
- * `formatStreamError` already follow.
300
- */
301
- export function isRetryableError(err, signal) {
302
- if (signal?.aborted === true)
303
- return { retry: false, reason: 'aborted' };
304
- if (err?.retryable !== true) {
305
- return { retry: false, reason: 'not_retryable' };
306
- }
307
- return { retry: true, reason: 'retryable' };
308
- }
309
- /**
310
- * The retry decision, taking every input EXPLICITLY — no closure reads — and
311
- * returning the first matching reason (§4.5).
312
- *
313
- * Module-internal by intent, like `normalizePolicy` above.
314
- */
315
- export function decide(input) {
316
- const base = isRetryableError(input.error, input.signal);
317
- if (!base.retry)
318
- return base;
319
- if (input.committed && !input.policy.onPartialStream) {
320
- return { retry: false, reason: 'committed' };
321
- }
322
- // PRE-INCREMENT, so `maxRetries: 10` permits retries at `retryIndex` 0...9 and
323
- // stops the 11th failure.
324
- if (input.retryIndex >= input.policy.maxRetries) {
325
- return { retry: false, reason: 'attempts_exhausted' };
326
- }
327
- // `firstFailureAt` is a number by construction — the caller anchors it BEFORE
328
- // deriving `candidateDelay` and before calling here. An ordering that read it
329
- // first would compute `NaN`, and `NaN > maxElapsedMs` is `false`: a budget
330
- // that never triggers, silently.
331
- if (input.now() - input.firstFailureAt + input.candidateDelay > input.policy.maxElapsedMs) {
332
- return { retry: false, reason: 'budget_exhausted' };
333
- }
334
- if (input.retryAfterMs !== undefined &&
335
- input.retryAfterMs > RETRY_LIMITS.retryAfterCeilingMs) {
336
- return { retry: false, reason: 'retry_after_too_long' };
337
- }
338
- return { retry: true, reason: 'retryable' };
339
- }
340
- // ---------------------------------------------------------------------------
341
- // Backoff arithmetic
342
- // ---------------------------------------------------------------------------
343
- /**
344
- * The wait before retry number `retryIndex` (1-BASED: the first retry is 1).
345
- *
346
- * EQUAL JITTER, NOT FULL JITTER. Full jitter (`rand() * base`) is the textbook
347
- * contention minimiser, but it can return 40 ms on the sixth retry, and a UI
348
- * that just announced "retrying in 30s" and then fires in 40 ms reads as a bug.
349
- * Equal jitter keeps the announced number within a factor of two of the truth
350
- * while still de-correlating N concurrent subagents hitting the same 429. The
351
- * user-visible countdown is computed from the ACTUAL chosen delay, never from
352
- * `base`, so what the card says is always what happens.
353
- */
354
- export function computeBackoffDelay(retryIndex, policy, opts) {
355
- const rand = opts?.random ?? Math.random;
356
- // `ceilingMs` exists for ONE reason: tier 3 must be able to wait 300 s, and the
357
- // structural ceiling of tier 1 (120 s) lives inside this function. Callers that
358
- // do not pass it get `absoluteMaxDelayMs` and therefore today's numbers exactly.
359
- const ceiling = opts?.ceilingMs ?? RETRY_LIMITS.absoluteMaxDelayMs;
360
- const raw = policy.initialDelayMs * Math.pow(policy.multiplier, Math.max(0, retryIndex - 1));
361
- const base = Math.min(raw, policy.maxDelayMs, ceiling);
362
- const jittered = policy.jitter ? base / 2 + rand() * (base / 2) : base;
363
- // MAX, not replace. A `Retry-After: 1` arriving on the ninth retry must not
364
- // undo eight retries' worth of backoff — the server is stating a FLOOR ("not
365
- // before this"), not a ceiling.
366
- const withHeader = policy.respectRetryAfter && opts?.retryAfterMs !== undefined
367
- ? Math.max(jittered, opts.retryAfterMs)
368
- : jittered;
369
- return Math.round(Math.min(Math.max(withHeader, RETRY_LIMITS.minDelayMs), ceiling));
370
- }
371
- // ---------------------------------------------------------------------------
372
- // Retry-After parsing
373
- // ---------------------------------------------------------------------------
374
- /** Seconds-or-HTTP-date -> ms, or `undefined` when unusable. Never negative. */
375
- function parseDelaySeconds(raw, now) {
376
- if (raw === null)
377
- return undefined;
378
- const trimmed = raw.trim();
379
- if (trimmed.length === 0)
380
- return undefined;
381
- if (/^\d+(?:\.\d+)?$/.test(trimmed)) {
382
- const seconds = Number.parseFloat(trimmed);
383
- if (!Number.isFinite(seconds))
384
- return undefined;
385
- return Math.max(0, Math.round(seconds * 1000));
386
- }
387
- return parseInstant(trimmed, now);
388
- }
389
- /** An RFC-3339 / HTTP-date instant -> ms from now, or `undefined`. Never negative. */
390
- function parseInstant(raw, now) {
391
- const at = Date.parse(raw);
392
- if (!Number.isFinite(at))
393
- return undefined;
394
- return Math.max(0, Math.round(at - now()));
395
- }
396
- /**
397
- * The server-stated wait, in ms, or `undefined` when absent or unparseable.
398
- *
399
- * Read order: `retry-after` (integer seconds, or an HTTP-date), then
400
- * `x-ratelimit-reset-after` (seconds, OpenAI-flavoured), then
401
- * `anthropic-ratelimit-requests-reset`, then
402
- * `anthropic-ratelimit-input-tokens-reset` (both RFC-3339 instants).
403
- *
404
- * THE TOKEN HEADER IS READ, not skipped: on a long context it is the limit that
405
- * actually bites, and a request throttled on tokens that waits out only the
406
- * REQUEST window comes back to the same 429.
407
- *
408
- * A value above `RETRY_LIMITS.retryAfterCeilingMs` is returned AS-IS — the
409
- * CALLER (`withRetry`) decides to stop, so the honest number reaches the user's
410
- * error message rather than being silently rounded down to a wait we would then
411
- * actually perform.
412
- */
413
- export function parseRetryAfterMs(headers, now = Date.now) {
414
- if (!headers || typeof headers.get !== 'function')
415
- return undefined;
416
- const direct = parseDelaySeconds(headers.get('retry-after'), now);
417
- if (direct !== undefined)
418
- return direct;
419
- const openai = parseDelaySeconds(headers.get('x-ratelimit-reset-after'), now);
420
- if (openai !== undefined)
421
- return openai;
422
- const requests = headers.get('anthropic-ratelimit-requests-reset');
423
- if (requests !== null && requests.trim().length > 0) {
424
- const parsed = parseInstant(requests.trim(), now);
425
- if (parsed !== undefined)
426
- return parsed;
427
- }
428
- const inputTokens = headers.get('anthropic-ratelimit-input-tokens-reset');
429
- if (inputTokens !== null && inputTokens.trim().length > 0) {
430
- const parsed = parseInstant(inputTokens.trim(), now);
431
- if (parsed !== undefined)
432
- return parsed;
433
- }
434
- return undefined;
435
- }
436
- /**
437
- * Sleep, resolving on EITHER the timer or the signal's `abort` event.
438
- *
439
- * A bare `setTimeout` would make Esc take up to 30 s to be felt, which is the
440
- * single most visible way this feature can be made to feel cheap. The listener
441
- * is removed on both paths so a long-lived signal does not accumulate them.
442
- */
443
- function defaultSleep(ms, signal) {
444
- if (signal?.aborted === true)
445
- return Promise.resolve();
446
- return new Promise((resolve) => {
447
- const done = () => {
448
- clearTimeout(timer);
449
- signal?.removeEventListener('abort', done);
450
- resolve();
451
- };
452
- const timer = setTimeout(done, ms);
453
- signal?.addEventListener('abort', done, { once: true });
454
- });
455
- }
456
- function errorTypeOf(err) {
457
- const t = err?.errorType;
458
- return typeof t === 'string' ? t : 'unknown';
459
- }
460
- function messageOf(err) {
461
- const m = err?.message;
462
- return typeof m === 'string' && m.length > 0 ? m : 'Unknown provider error';
463
- }
464
- function retryAfterOf(err) {
465
- const v = err?.retryAfterMs;
466
- return typeof v === 'number' && Number.isFinite(v) && v >= 0 ? v : undefined;
467
- }
468
- function rung1(policy) {
469
- return {
470
- id: 1,
471
- policy,
472
- ceilingMs: RETRY_LIMITS.absoluteMaxDelayMs,
473
- retryAfterCeilingMs: RETRY_LIMITS.retryAfterCeilingMs,
474
- unbounded: false,
475
- };
476
- }
477
- function rung2(base, tier) {
478
- return {
479
- id: 2,
480
- ceilingMs: RETRY_LIMITS.escalationMaxDelayMs,
481
- retryAfterCeilingMs: tier.maxDelayMs,
482
- unbounded: false,
483
- policy: {
484
- // Inherited: `respectRetryAfter` / `onPartialStream` are one user switch
485
- // each, not per-tier policy.
486
- ...base,
487
- maxRetries: tier.attempts,
488
- initialDelayMs: tier.initialDelayMs,
489
- maxDelayMs: tier.maxDelayMs,
490
- multiplier: tier.multiplier,
491
- jitter: tier.jitter,
492
- // Finite: "N+1 waits" is this tier's natural ceiling, and an infinite budget
493
- // would have been rewritten by `finiteOr` anyway (§2.2#3).
494
- maxElapsedMs: (tier.attempts + 1) * tier.maxDelayMs,
495
- },
496
- };
497
- }
498
- function rung3(base, tier) {
499
- return {
500
- id: 3,
501
- ceilingMs: RETRY_LIMITS.escalationMaxDelayMs,
502
- retryAfterCeilingMs: tier.maxDelayMs,
503
- unbounded: true,
504
- policy: {
505
- ...base,
506
- // NOMINAL only: a finite value for a `number` field. A test lowers it to prove
507
- // the ladder crosses it (AC-4).
508
- maxRetries: tier.attempts,
509
- initialDelayMs: tier.initialDelayMs,
510
- maxDelayMs: tier.maxDelayMs,
511
- multiplier: 1,
512
- jitter: false,
513
- // No budget: `unbounded` guarantees the stop never comes; this keeps the
514
- // arithmetic total.
515
- maxElapsedMs: Number.MAX_SAFE_INTEGER,
516
- },
517
- };
518
- }
519
- /** The ladder. `escalation === null` yields ONE rung: a switched-off embedder is
520
- * then byte-identical to a pre-feature one. */
521
- function buildRungs(policy, escalation) {
522
- if (!escalation)
523
- return [rung1(policy)];
524
- const rungs = [rung1(policy), rung2(policy, escalation.slow)];
525
- if (escalation.hold)
526
- rungs.push(rung3(policy, escalation.hold));
527
- return rungs;
528
- }
529
- /** The tier after `current`, or `undefined` when the ladder is over. */
530
- function nextRung(current, rungs) {
531
- return rungs.find((r) => r.id === current.id + 1);
532
- }
533
- /**
534
- * The three reasons that mean "this TIER is done" (G8). Everything else - and
535
- * `committed` most of all - ends the whole LADDER: escalating that one would
536
- * `stream_restart` text the user has already read (P0-1 / R-15).
537
- */
538
- const LADDER_END_REASONS = new Set([
539
- 'attempts_exhausted',
540
- 'budget_exhausted',
541
- 'retry_after_too_long',
542
- ]);
543
- /**
544
- * Adopt the server's stated wait for THIS tier. Tier 1 is returned untouched, so a
545
- * `Retry-After: 3600` still stops the fast tier with the provider's own number;
546
- * tiers 2/3 cap the ADOPTED wait at one tier interval, which is what keeps "every
547
- * 1 minute", "every 5 minutes" and "about 14 minutes to tier 3" all true at once.
548
- */
549
- function adoptRetryAfter(retryAfterMs, rung) {
550
- if (retryAfterMs === undefined)
551
- return undefined;
552
- if (rung.id === 1)
553
- return retryAfterMs;
554
- return Math.min(retryAfterMs, rung.retryAfterCeilingMs);
555
- }
556
- function planNextStep(input) {
557
- const escalating = !input.decision.retry;
558
- if (escalating && !LADDER_END_REASONS.has(input.decision.reason))
559
- return undefined;
560
- const rung = escalating ? nextRung(input.rung, input.rungs) : input.rung;
561
- if (!rung)
562
- return undefined;
563
- if (!escalating)
564
- return { rung, escalating: false, delay: input.candidateDelay };
565
- // A new tier's FIRST beat waits its own interval too (§4.1): it is still "one
566
- // retry", and hammering immediately would repeat the last attempt for free.
567
- const adopted = adoptRetryAfter(input.retryAfterMs, rung);
568
- return {
569
- rung,
570
- escalating: true,
571
- delay: computeBackoffDelay(1, rung.policy, {
572
- ...(adopted !== undefined ? { retryAfterMs: adopted } : {}),
573
- random: input.random,
574
- ceilingMs: rung.ceilingMs,
575
- }),
576
- };
577
- }
578
- /**
579
- * The WHOLE ladder's wall clock, anchored on this request's first failure
580
- * (§4.3.4). No budget = always `true`, the interactive default; and
581
- * `ladderStart === undefined` returns `true` on purpose, because "the clock has not
582
- * started" must never read as "out of budget" (the `NaN` trap `decide` documents).
583
- */
584
- function withinLadderBudget(ladderStart, nextDelay, escalation, now) {
585
- if (!escalation)
586
- return true;
587
- const budget = escalation.totalBudgetMs;
588
- if (budget === undefined)
589
- return true;
590
- if (ladderStart === undefined)
591
- return true;
592
- return now() - ladderStart + nextDelay <= budget;
593
- }
594
- /**
595
- * When the CURRENT tier runs out, for the UI only. `undefined` for an unbounded
596
- * tier; approximate, which is acceptable because no decision reads it.
597
- */
598
- function tierEndsAt(rung, at, attemptInRung) {
599
- if (rung.unbounded)
600
- return undefined;
601
- const remaining = Math.max(0, rung.policy.maxRetries - attemptInRung);
602
- return at + remaining * rung.policy.maxDelayMs;
603
- }
604
- /**
605
- * Announce, then wait, then announce again: the ONE place `retry_scheduled` and
606
- * `retry_attempt` are produced. Extracted so `withRetry` stays inside the
607
- * complexity budget while both paths keep one declaration discipline (G7).
608
- */
609
- async function* announceAndWait(input, sleep, signal) {
610
- const tier = input.withTier
611
- ? {
612
- tier: input.rung.id,
613
- tierCount: input.tierCount,
614
- totalAttempts: input.totalAttempts,
615
- ...(input.tierEndsAt !== undefined ? { tierEndsAt: input.tierEndsAt } : {}),
616
- }
617
- : {};
618
- if (input.committed) {
619
- yield { type: 'stream_restart', attempt: input.attempt, discardedToolCallIds: input.toolCallIds };
620
- }
621
- yield {
622
- type: 'retry_scheduled',
623
- attempt: input.attempt,
624
- maxRetries: input.rung.policy.maxRetries,
625
- delayMs: input.delay,
626
- resumeAt: input.resumeAt,
627
- errorType: errorTypeOf(input.error),
628
- message: messageOf(input.error),
629
- // The provider's own number, UNCAPPED: what we did with it is our policy, but
630
- // the operator reading the log deserves the truth.
631
- ...(input.retryAfterMs !== undefined ? { retryAfterMs: input.retryAfterMs } : {}),
632
- ...tier,
633
- };
634
- await sleep(input.delay, signal); // G2
635
- if (signal?.aborted === true)
636
- return; // G3 again: silent
637
- yield {
638
- type: 'retry_attempt',
639
- attempt: input.attempt,
640
- maxRetries: input.rung.policy.maxRetries,
641
- ...(input.withTier
642
- ? {
643
- tier: input.rung.id,
644
- tierCount: input.tierCount,
645
- totalAttempts: input.totalAttempts,
646
- }
647
- : {}),
648
- };
649
- }
650
- function createAttemptDeadline(caller, readSilenceMs) {
651
- if (readSilenceMs <= 0) {
652
- return {
653
- controls: undefined,
654
- onFrame: () => { },
655
- fired: false,
656
- whenSilent: undefined,
657
- dispose: () => { },
658
- };
659
- }
660
- const controller = new AbortController();
661
- const onCallerAbort = () => controller.abort();
662
- caller?.addEventListener('abort', onCallerAbort, { once: true });
663
- if (caller?.aborted === true)
664
- controller.abort();
665
- let timer;
666
- /** The deadline fired, as opposed to the caller aborting. */
667
- let fired = false;
668
- let announceSilence = () => { };
669
- // ONE promise for the whole attempt, not one per event: a long stream would
670
- // otherwise leave a pending promise behind for every frame it produced.
671
- const whenSilent = new Promise((resolve) => {
672
- announceSilence = resolve;
673
- });
674
- const arm = () => {
675
- if (controller.signal.aborted)
676
- return;
677
- if (timer !== undefined)
678
- clearTimeout(timer);
679
- timer = setTimeout(() => {
680
- fired = true;
681
- // Abort FIRST, then announce: an adapter that honours the signal gets to
682
- // emit its own truncation error before the race resolves.
683
- controller.abort();
684
- announceSilence();
685
- }, readSilenceMs);
686
- };
687
- arm();
688
- const controls = { readDeadline: controller.signal, onFrame: arm };
689
- return {
690
- controls,
691
- onFrame: arm,
692
- get fired() {
693
- return fired && caller?.aborted !== true;
694
- },
695
- whenSilent,
696
- dispose: () => {
697
- if (timer !== undefined) {
698
- clearTimeout(timer);
699
- timer = undefined;
700
- }
701
- caller?.removeEventListener('abort', onCallerAbort);
702
- },
703
- };
704
- }
705
- /**
706
- * Iterate `source` while enforcing the attempt's silence window — and enforce it
707
- * HERE, not only in the adapters.
708
- *
709
- * A read deadline the adapter ignores would leave `withRetry` awaiting `next()`
710
- * forever, so silence would still kill the RUN and never reach `decide()`. Racing
711
- * `next()` against `whenSilent` makes the recovery a property of the ladder, which
712
- * is what the user asked for, and not a property of three hand-written adapters.
713
- *
714
- * `source.return()` runs on every exit path, so a pending read is released and the
715
- * SSE reader is not leaked when the deadline wins.
716
- */
717
- async function* guardSilence(source, deadline) {
718
- const whenSilent = deadline.whenSilent;
719
- if (!whenSilent) {
720
- yield* source;
721
- return;
722
- }
723
- try {
724
- for (;;) {
725
- const pending = source.next();
726
- // Abandoned when the deadline wins: without this an adapter rejecting later
727
- // would surface as an unhandled rejection with no user-visible cause.
728
- pending.catch(() => { });
729
- const step = await Promise.race([
730
- pending.then((result) => ({ kind: 'event', result })),
731
- whenSilent.then(() => ({ kind: 'silence' })),
732
- ]);
733
- if (step.kind === 'silence')
734
- return;
735
- if (step.result.done === true)
736
- return;
737
- deadline.onFrame();
738
- yield step.result.value;
739
- }
740
- }
741
- finally {
742
- // NOT AWAITED, and that is load-bearing. A generator suspended inside an
743
- // `await` does not settle `return()` until that await does, so awaiting it here
744
- // would hang on exactly the provider this guard exists for — one that ignores
745
- // the deadline. Firing it is still worth doing: a real adapter's read is already
746
- // rejecting because the deadline aborted it, so its `finally` releases the reader
747
- // on the next tick. The rejection is swallowed because nobody is left to read it.
748
- void source.return?.(undefined)?.catch(() => { });
749
- }
750
- }
751
- /**
752
- * Wrap a stream factory with retry.
753
- *
754
- * Six properties are load-bearing and easy to break:
755
- *
756
- * - G1 — THE ABORT GUARD IS CHECKED ON EVERY ITERATION, matching
757
- * `agent-loop.ts`'s own guard. Combined with G3 below, an aborted request
758
- * never forwards a trailing error to a subscriber.
759
- * - G2 — `sleep` MUST OBSERVE `signal`. See `defaultSleep`.
760
- * - G3 — `aborted` RETURNS SILENTLY. It is the one non-retry reason that must
761
- * not `yield` an `error`. `consumeStream` (the body of `complete()`) does not
762
- * consult the signal, so a yielded error would become a thrown, FABRICATED
763
- * `network_error` on user Esc — blaming the network for something the user
764
- * just did is worse than saying nothing. Three silent return sites: the
765
- * in-loop guard, the `decide` short-circuit, and the post-sleep check.
766
- * - G4 — `normalizePolicy` RUNS ONCE, at generator entry, so `RETRY_LIMITS`
767
- * bounds an embedder's policy and not merely a CLI-resolved one.
768
- * - G5 — the escalation tiers have their OWN gate (`normalizeEscalation`) and never
769
- * pass through `normalizePolicy`, whose `finiteOr` would rewrite "no budget" as
770
- * 240 s and whose `hardMaxRetries` would cut tier 3 to 20 attempts.
771
- * - G6 — `Retry-After`'s "> 60 s stops the ladder" rule is TIER 1's only; tiers 2/3
772
- * cap the ADOPTED wait at their own interval and still report the raw number.
773
- * - G7 — what is announced is what is waited, and the ladder budget is tested
774
- * BEFORE anything is announced.
775
- * - G8 — only `attempts_exhausted` / `budget_exhausted` / `retry_after_too_long`
776
- * end a TIER. `committed` and `not_retryable` end the WHOLE ladder, because
777
- * escalating `committed` would replay text the user has already read.
778
- * - THE SUCCESS PATH IS UNTOUCHED. A request that works yields exactly the
779
- * events the adapter produced, in the same order, with no extra allocation
780
- * beyond one boolean and one empty array. The wrapper is not installed at all
781
- * when `maxRetries <= 0`, so an opted-out embedder is byte-identical to a
782
- * pre-feature build.
783
- * - THE TERMINAL ERROR IS FORWARDED, NOT REPLACED. After exhaustion the
784
- * consumer sees the PROVIDER's own `LLMError`, so `formatStreamError`, the
785
- * `retryable` field and any downstream `instanceof` continue to behave. Only
786
- * the retry COUNT is new information, and it travels on the events.
787
- */
788
- export async function* withRetry(makeStream, opts) {
789
- const policy = normalizePolicy(opts.policy);
790
- const escalation = normalizeEscalation(opts.escalation ?? null);
791
- const rungs = buildRungs(policy, escalation);
792
- const now = opts.now ?? Date.now;
793
- const sleep = opts.sleep ?? defaultSleep;
794
- const random = opts.random ?? Math.random;
795
- const signal = opts.signal;
796
- const withTier = escalation !== null;
797
- // THE READ DEADLINE, resolved once: “a request that has said nothing for N ms is a
798
- // transport failure, hand it to the ladder” (F1′). `0` = the caller opted out.
799
- const readSilenceMs = resolveReadSilenceMs(policy, opts.watchdogWindowMs);
800
- /** Clock for the WHOLE ladder (only `totalBudgetMs` reads it). */
801
- let firstFailureAtLadder;
802
- /** Clock for the CURRENT tier (only `decide`'s budget reads it). */
803
- let firstFailureAt;
804
- /** Retries COMPLETED so far inside the current tier. */
805
- let attemptInRung = 0;
806
- /** Retries COMPLETED so far in this request, across tiers (D-7). */
807
- let totalAttempts = 0;
808
- let rung = rungs[Math.max(0, (opts.startRung ?? 1) - 1)] ?? rungs[0];
809
- for (;;) {
810
- if (Boolean(signal?.aborted))
811
- return;
812
- let committed = false;
813
- const toolCallIds = [];
814
- let sawDone = false;
815
- let terminalError;
816
- // A FRESH deadline per attempt: a silence that ended attempt N must not be
817
- // visible to attempt N+1, or the next one would look pre-cancelled.
818
- const deadline = createAttemptDeadline(signal, readSilenceMs);
819
- try {
820
- // `guardSilence` owns the per-event re-arm, so a frame that arrives as a
821
- // `StreamEvent` and a frame that only re-armed the wire both count.
822
- for await (const event of guardSilence(makeStream(deadline.controls), deadline)) {
823
- if (signal?.aborted === true)
824
- return; // G1
825
- if (CONTENT_EVENTS.has(event.type))
826
- committed = true;
827
- if (event.type === 'tool_call_start')
828
- toolCallIds.push(event.toolCallId);
829
- if (event.type === 'error') {
830
- // NOT FORWARDED YET: whether the consumer ever sees it depends on the
831
- // decision below. Breaking here also calls the source iterator's
832
- // `return()`, which runs its `finally` and releases the SSE reader.
833
- terminalError = event.error;
834
- break;
835
- }
836
- if (event.type === 'done')
837
- sawDone = true;
838
- yield event;
839
- }
840
- }
841
- finally {
842
- deadline.dispose();
843
- }
844
- if (Boolean(signal?.aborted))
845
- return;
846
- if (sawDone)
847
- return; // success; the hot path ends here
848
- // THE DEADLINE SPEAKS AS A PROVIDER WOULD (F1′). An adapter that honours
849
- // `readDeadline` has already produced its own truncation error above; this
850
- // covers a provider that ignored the field, so a silence still reaches
851
- // `decide()` as an ordinary retryable failure instead of escaping the generator.
852
- if (terminalError === undefined && deadline.fired) {
853
- terminalError = new LLMError(`${opts.providerId}/${opts.modelId} stream was silent for ${readSilenceMs} ms`, opts.providerId, 'timeout', true);
854
- }
855
- if (terminalError === undefined) {
856
- // Defensive only: with the adapters' terminal-sentinel contract in place
857
- // (§4.5a) every adapter terminates in `done` or `error`. Reaching here
858
- // means an adapter broke its own contract, and a silent success would be
859
- // the worst possible reading of that.
860
- // NAMES THE PROVIDER *AND* THE MODEL. `agent-loop.ts` throws an almost
861
- // identical sentence one layer up ("LLM stream ended without producing a
862
- // done event"), and both can reach a user; without the ids the two are
863
- // indistinguishable in a bug report, and the id is the first thing worth
864
- // knowing when one adapter of three is misbehaving. This is also the only
865
- // read of `opts.modelId` — a required option nothing consumes is one the
866
- // next caller will start passing wrong.
867
- terminalError = new LLMError(`${opts.providerId}/${opts.modelId} stream ended without producing a done or error event`, opts.providerId, 'network_error', true);
868
- }
869
- // ---- ORDER IS NORMATIVE FROM HERE -----------------------------------
870
- // 1. Anchor BOTH clocks on the FIRST failure. Reading `firstFailureAt` before
871
- // anchoring computes `NaN`, and `NaN > budget` is false: a budget that never
872
- // triggers, silently.
873
- firstFailureAtLadder ??= now();
874
- firstFailureAt ??= now();
875
- // 2. The server's floor, adopted per THIS tier (D-8). `attemptInRung + 1`
876
- // because `computeBackoffDelay` is 1-based and `attemptInRung` counts
877
- // COMPLETED retries.
878
- const retryAfterMs = rung.policy.respectRetryAfter ? retryAfterOf(terminalError) : undefined;
879
- const adoptedRetryAfterMs = adoptRetryAfter(retryAfterMs, rung);
880
- const candidateDelay = computeBackoffDelay(attemptInRung + 1, rung.policy, {
881
- ...(adoptedRetryAfterMs !== undefined ? { retryAfterMs: adoptedRetryAfterMs } : {}),
882
- random,
883
- ceilingMs: rung.ceilingMs,
884
- });
885
- // 3. Only now can `decide` answer the budget question. G6: `retryAfterMs` goes
886
- // to `decide` for TIER 1 ONLY, so "come back in an hour" still stops the fast
887
- // tier honestly and never stops tiers 2/3.
888
- let decision = decide({
889
- error: terminalError,
890
- ...(signal ? { signal } : {}),
891
- committed,
892
- retryIndex: attemptInRung,
893
- firstFailureAt,
894
- candidateDelay,
895
- ...(rung.id === 1 && retryAfterMs !== undefined ? { retryAfterMs } : {}),
896
- policy: rung.policy,
897
- now,
898
- });
899
- // Tier 3's ONLY definition of "unbounded": rewrite the nominal count into
900
- // "keep going", and change nothing else `decide` said (T-2).
901
- if (rung.unbounded && decision.reason === 'attempts_exhausted') {
902
- decision = { retry: true, reason: 'retryable' };
903
- }
904
- if (decision.reason === 'aborted')
905
- return; // G3 — no trailing error event
906
- const plan = planNextStep({
907
- decision,
908
- rung,
909
- rungs,
910
- candidateDelay,
911
- ...(retryAfterMs !== undefined ? { retryAfterMs } : {}),
912
- random,
913
- });
914
- if (!plan) {
915
- yield { type: 'error', error: terminalError };
916
- return;
917
- }
918
- if (plan.escalating) {
919
- // The TIER clock restarts; the LADDER clock does not (§4.1).
920
- firstFailureAt = undefined;
921
- attemptInRung = 0;
922
- }
923
- rung = plan.rung;
924
- attemptInRung += 1;
925
- totalAttempts += 1;
926
- // BEFORE announcing, never after: a wait we would not perform must not be
927
- // declared (G7). `totalBudgetMs` exists only because a user asked for a cap.
928
- if (!withinLadderBudget(firstFailureAtLadder, plan.delay, escalation, now)) {
929
- yield { type: 'error', error: terminalError };
930
- return;
931
- }
932
- const endsAt = withTier ? tierEndsAt(rung, now(), attemptInRung) : undefined;
933
- yield* announceAndWait({
934
- rung,
935
- tierCount: rungs.length,
936
- attempt: attemptInRung,
937
- totalAttempts,
938
- delay: plan.delay,
939
- resumeAt: now() + plan.delay,
940
- error: terminalError,
941
- committed,
942
- toolCallIds,
943
- ...(retryAfterMs !== undefined ? { retryAfterMs } : {}),
944
- ...(endsAt !== undefined ? { tierEndsAt: endsAt } : {}),
945
- withTier,
946
- }, sleep, signal);
947
- }
948
- }
1
+ const _0x3ba5d1=_0x1000;(function(_0x2b911d,_0x4ad00a){const _0x5154d1=_0x1000,_0x37905b=_0x2b911d();while(!![]){try{const _0x47080f=parseInt(_0x5154d1(0x221))/0x1*(-parseInt(_0x5154d1(0x206))/0x2)+parseInt(_0x5154d1(0x218))/0x3*(parseInt(_0x5154d1(0x22e))/0x4)+-parseInt(_0x5154d1(0x225))/0x5+-parseInt(_0x5154d1(0x1c9))/0x6*(parseInt(_0x5154d1(0x1dd))/0x7)+parseInt(_0x5154d1(0x1c7))/0x8+parseInt(_0x5154d1(0x230))/0x9*(parseInt(_0x5154d1(0x1bf))/0xa)+parseInt(_0x5154d1(0x22f))/0xb;if(_0x47080f===_0x4ad00a)break;else _0x37905b['push'](_0x37905b['shift']());}catch(_0x31cd85){_0x37905b['push'](_0x37905b['shift']());}}}(_0x5dfb,0xd9753));import{LLMError}from'./provider.js';export const RETRY_LIMITS={'hardMaxRetries':0x14,'absoluteMaxDelayMs':0x1d4c0,'retryAfterCeilingMs':0xea60,'minDelayMs':0x64,'escalationMaxDelayMs':0xdbba0,'hardMaxSlowAttempts':0x1e,'holdNominalAttempts':0x2710,'holdMinDelayMs':0xea60};export const DEFAULT_RETRY_POLICY={'maxRetries':0xa,'initialDelayMs':0x3e8,'maxDelayMs':0x7530,'multiplier':0x2,'jitter':!![],'respectRetryAfter':!![],'maxElapsedMs':0x3a980,'onPartialStream':!![]};export const DEFAULT_READ_SILENCE_MS=0xafc8;export const CONTENT_EVENTS=new Set([_0x3ba5d1(0x216),_0x3ba5d1(0x1db),_0x3ba5d1(0x1fb),_0x3ba5d1(0x1e4),'tool_call_delta','tool_call_end']);export function resolveReadSilenceMs(_0x352ce9,_0x1f9d9d){const _0x3e9923=_0x3ba5d1;if(!_0x352ce9||_0x352ce9[_0x3e9923(0x219)]<=0x0)return 0x0;const _0x43bb52=_0x352ce9['readSilenceMs'],_0x3c908f=typeof _0x43bb52===_0x3e9923(0x1f8)&&Number[_0x3e9923(0x1ff)](_0x43bb52)?Math[_0x3e9923(0x1ec)](0x0,_0x43bb52):DEFAULT_READ_SILENCE_MS;if(_0x3c908f<=0x0)return 0x0;if(typeof _0x1f9d9d==='number'&&Number[_0x3e9923(0x1ff)](_0x1f9d9d)&&_0x1f9d9d>0x0)return Math['max'](RETRY_LIMITS[_0x3e9923(0x209)],Math[_0x3e9923(0x232)](_0x3c908f,Math[_0x3e9923(0x1c6)](_0x1f9d9d*0.6)));return _0x3c908f;}function finiteOr(_0x538450,_0x5b93c7){const _0x228efd=_0x3ba5d1;return typeof _0x538450===_0x228efd(0x1f8)&&Number[_0x228efd(0x1ff)](_0x538450)?_0x538450:_0x5b93c7;}export function normalizePolicy(_0x1e3a95){const _0x73c0ca=_0x3ba5d1,_0x3b1bad=Math[_0x73c0ca(0x232)](RETRY_LIMITS[_0x73c0ca(0x1d5)],Math['max'](0x0,Math['floor'](finiteOr(_0x1e3a95[_0x73c0ca(0x219)],DEFAULT_RETRY_POLICY[_0x73c0ca(0x219)])))),_0x471ea1=Math['min'](RETRY_LIMITS['absoluteMaxDelayMs'],Math[_0x73c0ca(0x1ec)](RETRY_LIMITS['minDelayMs'],Math[_0x73c0ca(0x1c6)](finiteOr(_0x1e3a95[_0x73c0ca(0x224)],DEFAULT_RETRY_POLICY['maxDelayMs'])))),_0x150583=Math[_0x73c0ca(0x232)](_0x471ea1,Math[_0x73c0ca(0x1ec)](RETRY_LIMITS['minDelayMs'],Math[_0x73c0ca(0x1c6)](finiteOr(_0x1e3a95[_0x73c0ca(0x1f0)],DEFAULT_RETRY_POLICY[_0x73c0ca(0x1f0)])))),_0x535279=Math[_0x73c0ca(0x1ec)](0x1,finiteOr(_0x1e3a95[_0x73c0ca(0x1cb)],DEFAULT_RETRY_POLICY[_0x73c0ca(0x1cb)])),_0x5b6baa=Math['max'](RETRY_LIMITS[_0x73c0ca(0x209)],Math['floor'](finiteOr(_0x1e3a95[_0x73c0ca(0x20b)],DEFAULT_RETRY_POLICY['maxElapsedMs'])));return{'maxRetries':_0x3b1bad,'initialDelayMs':_0x150583,'maxDelayMs':_0x471ea1,'multiplier':_0x535279,'jitter':_0x1e3a95[_0x73c0ca(0x22a)]!==![],'respectRetryAfter':_0x1e3a95[_0x73c0ca(0x210)]!==![],'maxElapsedMs':_0x5b6baa,'onPartialStream':_0x1e3a95[_0x73c0ca(0x1fe)]!==![],'readSilenceMs':typeof _0x1e3a95[_0x73c0ca(0x1ee)]===_0x73c0ca(0x1f8)&&Number['isFinite'](_0x1e3a95[_0x73c0ca(0x1ee)])?Math[_0x73c0ca(0x1ec)](0x0,Math['floor'](_0x1e3a95[_0x73c0ca(0x1ee)])):DEFAULT_READ_SILENCE_MS};}const DEFAULT_TIER={'attempts':0xa,'initialDelayMs':0xea60,'maxDelayMs':0xea60,'multiplier':0x1,'jitter':![]},DEFAULT_HOLD_INTERVAL_MS=0x493e0,MAX_LADDER_BUDGET_MS=0x18*0x36ee80,MIN_LADDER_BUDGET_MS=0xea60;function clampIntOr(_0x1c5adc,_0x46ea67,_0x221494,_0x1a74be){const _0x3e0ee5=_0x3ba5d1,_0x2087fa=Math[_0x3e0ee5(0x1c6)](finiteOr(_0x1c5adc,_0x46ea67));return Math[_0x3e0ee5(0x232)](_0x1a74be,Math[_0x3e0ee5(0x1ec)](_0x221494,_0x2087fa));}export function normalizeEscalation(_0xb0830b){const _0xee20f2=_0x3ba5d1;if(!_0xb0830b||typeof _0xb0830b!==_0xee20f2(0x1e9))return null;const _0x18f9ae=_0xb0830b['slow'];if(!_0x18f9ae||typeof _0x18f9ae!=='object')return null;const _0xb3b88d=clampIntOr(_0x18f9ae['attempts'],DEFAULT_TIER[_0xee20f2(0x223)],0x0,RETRY_LIMITS[_0xee20f2(0x1d0)]);if(_0xb3b88d===0x0)return null;const _0x7850ee=clampIntOr(_0x18f9ae['initialDelayMs'],DEFAULT_TIER[_0xee20f2(0x1f0)],RETRY_LIMITS['minDelayMs'],RETRY_LIMITS['escalationMaxDelayMs']),_0x21cc55={'attempts':_0xb3b88d,'initialDelayMs':_0x7850ee,'maxDelayMs':Math[_0xee20f2(0x1ec)](clampIntOr(_0x18f9ae[_0xee20f2(0x224)],_0x7850ee,RETRY_LIMITS[_0xee20f2(0x209)],RETRY_LIMITS[_0xee20f2(0x1e6)]),_0x7850ee),'multiplier':Math[_0xee20f2(0x232)](0x5,Math[_0xee20f2(0x1ec)](0x1,finiteOr(_0x18f9ae[_0xee20f2(0x1cb)],0x1))),'jitter':![]},_0x301de8=_0xb0830b[_0xee20f2(0x214)];let _0x19701b=null;if(_0x301de8&&typeof _0x301de8===_0xee20f2(0x1e9)){const _0x406eed=clampIntOr(_0x301de8[_0xee20f2(0x1f0)],DEFAULT_HOLD_INTERVAL_MS,RETRY_LIMITS[_0xee20f2(0x201)],RETRY_LIMITS[_0xee20f2(0x1e6)]);_0x19701b={'attempts':clampIntOr(_0x301de8[_0xee20f2(0x223)],RETRY_LIMITS[_0xee20f2(0x1c8)],0x1,RETRY_LIMITS['holdNominalAttempts']),'initialDelayMs':_0x406eed,'maxDelayMs':_0x406eed,'multiplier':0x1,'jitter':![]};}const _0x2fafc7=_0xb0830b[_0xee20f2(0x215)],_0x18a3f8=typeof _0x2fafc7===_0xee20f2(0x1f8)&&Number[_0xee20f2(0x1ff)](_0x2fafc7)?Math[_0xee20f2(0x232)](MAX_LADDER_BUDGET_MS,Math[_0xee20f2(0x1ec)](MIN_LADDER_BUDGET_MS,Math[_0xee20f2(0x1c6)](_0x2fafc7))):undefined;return{'slow':_0x21cc55,'hold':_0x19701b,..._0x18a3f8!==undefined?{'totalBudgetMs':_0x18a3f8}:{}};}function _0x5dfb(){const _0x6025ba=['zMLYC3rgywLSDxjLqxq','ohrsy1PqqG','mte3mJe3nJvUwNbREK0','ovL0B1PPDG','DMfSDwu','BwLU','CMvZDwX0','C2LNBMfS','odi1mJe1mhDYsLfKta','y29TBwL0DgvK','CMvHC29U','BwvZC2fNzq','yNvKz2v0x2v4Agf1C3rLza','zxnJywXHDgLUzW','Cg9SAwn5','zMXVB3i','nJCZmJeXmNrZAvzOAW','Ag9Sze5VBwLUywXbDhrLBxb0CW','odK3nJi1mNbZDxrbDG','CgfYC2u','BxvSDgLWBgLLCG','y29Uy2f0','ihn0CMvHBsb3yxmGC2LSzw50igzVCIa','DgHLBG','CMv0CNLFyxr0zw1WDa','AgfYze1HEfnSB3DbDhrLBxb0CW','CMv0CNLHyMXL','C3rHCNrsDw5N','vw5RBM93BIbWCM92AwrLCIbLCNjVCG','ywjZB2X1DgvnyxHezwXHEu1Z','AgfYze1HEfjLDhjPzxm','Dg9VBenHBgXjza','tufyx1nbrKvFsu5uruDfuG','ywjVCNq','CNvUz3m','CMv0CNLFywz0zxjFDg9Vx2XVBMC','DgHPBMTPBMDFC3rHCNq','C2LSzw5Jzq','n2ToEe52qG','ywrKrxzLBNrmAxn0zw5LCG','ig1Z','ihn0CMvHBsbLBMrLzcb3AxrOB3v0ihbYB2r1y2LUzYbHigrVBMuGB3iGzxjYB3iGzxzLBNq','BMv4Da','ChvZAa','Dg9VBenHBgXjzhm','Dg9VBf9JywXSx3n0yxj0','zgvSyxK','zxnJywXHDgLVBK1HEerLBgf5txm','zxzLBNq','Cg93','B2jQzwn0','DhLWzq','C2XLzxa','Bwf4','zgLZCg9Zzq','CMvHzfnPBgvUy2vnCW','CNvUzW','Aw5PDgLHBerLBgf5txm','DhjPBq','DgLLCKnVDw50','yxr0zw1WDa','CMv0CNK','CM91BMq','Dw5IB3vUzgvK','ywjVCNrLza','BNvTyMvY','y2f0y2G','CMfJzq','DgHPBMTPBMDFzgvSDge','DgLLCKvUzhnbDa','ChjVDMLKzxjjza','B25qyxj0AwfSu3rYzwfT','AxngAw5PDgu','CMv0CNLjBMrLEa','Ag9Sze1PBKrLBgf5txm','A2LUza','y29UDhjVBhm','BgvUz3rO','CMvTB3zLrxzLBNrmAxn0zw5LCG','mtiWmZe0ohv1r3b0rG','zMLUza','C2XVDW','BwLUrgvSyxLnCW','CMv0CNKTywz0zxi','Bwf4rwXHChnLze1Z','DgvZDa','yxr0zw1WDhnFzxHOyxvZDgvK','Dg90ywXbDhrLBxb0CW','zg9Uzq','CMvZCgvJDfjLDhj5qwz0zxi','CMv0CNLbzNrLCK1Z','BM90x3jLDhj5ywjSzq','BM93','Ag9Sza','Dg90ywXcDwrNzxrnCW','Dgv4Df9KzwX0yq','Dw5RBM93BG','mte2mtGZnhbZsurtrG','Bwf4uMv0CMLLCW','CMfUzg9T','D2f0y2HKB2DxAw5KB3DnCW','y2fUzgLKyxrLrgvSyxK','y2vPBgLUz01Z','AgfZ','C3rYAw5N','C3rYzwfTx3jLC3rHCNq','mwTmA0fYsa','z2v0','yxr0zw1WDhm','Bwf4rgvSyxLnCW','mJu5mJG4nxzUz1LJAW','CMv0CNLbzNrLCKnLAwXPBMDnCW','zxjYB3i','CgfYC2vgBg9HDa','zgvJAxnPB24','AML0DgvY','D2L0AfrPzxi','Bw9KzwXjza'];_0x5dfb=function(){return _0x6025ba;};return _0x5dfb();}export function isRetryableError(_0x58e72e,_0x512f04){const _0x4de8d9=_0x3ba5d1;if(_0x512f04?.['aborted']===!![])return{'retry':![],'reason':'aborted'};if(_0x58e72e?.[_0x4de8d9(0x1d1)]!==!![])return{'retry':![],'reason':_0x4de8d9(0x212)};return{'retry':!![],'reason':_0x4de8d9(0x1d1)};}export function decide(_0xa3d7f6){const _0x4ae072=_0x3ba5d1,_0x315ad6=isRetryableError(_0xa3d7f6[_0x4ae072(0x227)],_0xa3d7f6[_0x4ae072(0x234)]);if(!_0x315ad6[_0x4ae072(0x1f4)])return _0x315ad6;if(_0xa3d7f6['committed']&&!_0xa3d7f6[_0x4ae072(0x1c5)][_0x4ae072(0x1fe)])return{'retry':![],'reason':_0x4ae072(0x1c0)};if(_0xa3d7f6[_0x4ae072(0x200)]>=_0xa3d7f6[_0x4ae072(0x1c5)][_0x4ae072(0x219)])return{'retry':![],'reason':_0x4ae072(0x20d)};if(_0xa3d7f6['now']()-_0xa3d7f6[_0x4ae072(0x22d)]+_0xa3d7f6['candidateDelay']>_0xa3d7f6[_0x4ae072(0x1c5)][_0x4ae072(0x20b)])return{'retry':![],'reason':_0x4ae072(0x1c3)};if(_0xa3d7f6[_0x4ae072(0x211)]!==undefined&&_0xa3d7f6[_0x4ae072(0x211)]>RETRY_LIMITS[_0x4ae072(0x226)])return{'retry':![],'reason':_0x4ae072(0x1da)};return{'retry':!![],'reason':'retryable'};}export function computeBackoffDelay(_0x105833,_0x2d7849,_0xa51e2){const _0x47f61a=_0x3ba5d1,_0x31f8e1=_0xa51e2?.[_0x47f61a(0x21a)]??Math[_0x47f61a(0x21a)],_0x51fbe8=_0xa51e2?.[_0x47f61a(0x21d)]??RETRY_LIMITS[_0x47f61a(0x1d4)],_0x54e5c2=_0x2d7849[_0x47f61a(0x1f0)]*Math[_0x47f61a(0x1e8)](_0x2d7849[_0x47f61a(0x1cb)],Math[_0x47f61a(0x1ec)](0x0,_0x105833-0x1)),_0x403131=Math[_0x47f61a(0x232)](_0x54e5c2,_0x2d7849[_0x47f61a(0x224)],_0x51fbe8),_0x16e183=_0x2d7849[_0x47f61a(0x22a)]?_0x403131/0x2+_0x31f8e1()*(_0x403131/0x2):_0x403131,_0x13fe65=_0x2d7849[_0x47f61a(0x210)]&&_0xa51e2?.['retryAfterMs']!==undefined?Math[_0x47f61a(0x1ec)](_0x16e183,_0xa51e2['retryAfterMs']):_0x16e183;return Math[_0x47f61a(0x1f5)](Math[_0x47f61a(0x232)](Math[_0x47f61a(0x1ec)](_0x13fe65,RETRY_LIMITS['minDelayMs']),_0x51fbe8));}function parseDelaySeconds(_0x9abfaf,_0x5688ad){const _0x47bfbb=_0x3ba5d1;if(_0x9abfaf===null)return undefined;const _0x650050=_0x9abfaf[_0x47bfbb(0x1f1)]();if(_0x650050['length']===0x0)return undefined;if(/^\d+(?:\.\d+)?$/[_0x47bfbb(0x20c)](_0x650050)){const _0x236c67=Number[_0x47bfbb(0x228)](_0x650050);if(!Number['isFinite'](_0x236c67))return undefined;return Math['max'](0x0,Math[_0x47bfbb(0x1f5)](_0x236c67*0x3e8));}return parseInstant(_0x650050,_0x5688ad);}function parseInstant(_0x537072,_0x51be42){const _0xc73be5=_0x3ba5d1,_0x56854c=Date[_0xc73be5(0x1ca)](_0x537072);if(!Number['isFinite'](_0x56854c))return undefined;return Math[_0xc73be5(0x1ec)](0x0,Math[_0xc73be5(0x1f5)](_0x56854c-_0x51be42()));}export function parseRetryAfterMs(_0x34354f,_0x3510df=Date[_0x3ba5d1(0x213)]){const _0x28df49=_0x3ba5d1;if(!_0x34354f||typeof _0x34354f[_0x28df49(0x222)]!=='function')return undefined;const _0x15447f=parseDelaySeconds(_0x34354f[_0x28df49(0x222)](_0x28df49(0x20a)),_0x3510df);if(_0x15447f!==undefined)return _0x15447f;const _0xdedef7=parseDelaySeconds(_0x34354f[_0x28df49(0x222)]('x-ratelimit-reset-after'),_0x3510df);if(_0xdedef7!==undefined)return _0xdedef7;const _0x4ce698=_0x34354f[_0x28df49(0x222)]('anthropic-ratelimit-requests-reset');if(_0x4ce698!==null&&_0x4ce698[_0x28df49(0x1f1)]()[_0x28df49(0x204)]>0x0){const _0x4ce658=parseInstant(_0x4ce698[_0x28df49(0x1f1)](),_0x3510df);if(_0x4ce658!==undefined)return _0x4ce658;}const _0xff25a8=_0x34354f['get']('anthropic-ratelimit-input-tokens-reset');if(_0xff25a8!==null&&_0xff25a8[_0x28df49(0x1f1)]()[_0x28df49(0x204)]>0x0){const _0x20bdd2=parseInstant(_0xff25a8[_0x28df49(0x1f1)](),_0x3510df);if(_0x20bdd2!==undefined)return _0x20bdd2;}return undefined;}function defaultSleep(_0x2e51a2,_0x4bf521){const _0xfdd3bf=_0x3ba5d1;if(_0x4bf521?.[_0xfdd3bf(0x1f7)]===!![])return Promise['resolve']();return new Promise(_0x3f2f36=>{const _0x34ce14=_0xfdd3bf,_0x31a11a=()=>{const _0x19858f=_0x1000;clearTimeout(_0x461681),_0x4bf521?.[_0x19858f(0x205)]('abort',_0x31a11a),_0x3f2f36();},_0x461681=setTimeout(_0x31a11a,_0x2e51a2);_0x4bf521?.['addEventListener'](_0x34ce14(0x1d8),_0x31a11a,{'once':!![]});});}function errorTypeOf(_0x36287e){const _0x5ed7b6=_0x3ba5d1,_0x4673a4=_0x36287e?.['errorType'];return typeof _0x4673a4===_0x5ed7b6(0x21f)?_0x4673a4:_0x5ed7b6(0x217);}function messageOf(_0x564ee5){const _0x2876fe=_0x3ba5d1,_0x11e45b=_0x564ee5?.[_0x2876fe(0x1c2)];return typeof _0x11e45b==='string'&&_0x11e45b[_0x2876fe(0x204)]>0x0?_0x11e45b:_0x2876fe(0x1d3);}function retryAfterOf(_0x45ddb1){const _0x395809=_0x3ba5d1,_0x30a6cb=_0x45ddb1?.[_0x395809(0x211)];return typeof _0x30a6cb===_0x395809(0x1f8)&&Number[_0x395809(0x1ff)](_0x30a6cb)&&_0x30a6cb>=0x0?_0x30a6cb:undefined;}function rung1(_0x318932){const _0x420c84=_0x3ba5d1;return{'id':0x1,'policy':_0x318932,'ceilingMs':RETRY_LIMITS[_0x420c84(0x1d4)],'retryAfterCeilingMs':RETRY_LIMITS[_0x420c84(0x226)],'unbounded':![]};}function rung2(_0x58a3d7,_0x2a6ff3){const _0x31e03f=_0x3ba5d1;return{'id':0x2,'ceilingMs':RETRY_LIMITS[_0x31e03f(0x1e6)],'retryAfterCeilingMs':_0x2a6ff3[_0x31e03f(0x224)],'unbounded':![],'policy':{..._0x58a3d7,'maxRetries':_0x2a6ff3['attempts'],'initialDelayMs':_0x2a6ff3[_0x31e03f(0x1f0)],'maxDelayMs':_0x2a6ff3[_0x31e03f(0x224)],'multiplier':_0x2a6ff3[_0x31e03f(0x1cb)],'jitter':_0x2a6ff3[_0x31e03f(0x22a)],'maxElapsedMs':(_0x2a6ff3[_0x31e03f(0x223)]+0x1)*_0x2a6ff3[_0x31e03f(0x224)]}};}function rung3(_0x9affbc,_0x402282){const _0x915759=_0x3ba5d1;return{'id':0x3,'ceilingMs':RETRY_LIMITS[_0x915759(0x1e6)],'retryAfterCeilingMs':_0x402282[_0x915759(0x224)],'unbounded':!![],'policy':{..._0x9affbc,'maxRetries':_0x402282[_0x915759(0x223)],'initialDelayMs':_0x402282[_0x915759(0x1f0)],'maxDelayMs':_0x402282['maxDelayMs'],'multiplier':0x1,'jitter':![],'maxElapsedMs':Number[_0x915759(0x1d7)]}};}function _0x1000(_0x4b7851,_0x47b791){_0x4b7851=_0x4b7851-0x1bf;const _0x5dfb0e=_0x5dfb();let _0x10000a=_0x5dfb0e[_0x4b7851];if(_0x1000['dcqmaz']===undefined){var _0x451bbd=function(_0x13b5fd){const _0x346204='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=';let _0x2185ac='',_0x352ce9='';for(let _0x1f9d9d=0x0,_0x43bb52,_0x3c908f,_0x538450=0x0;_0x3c908f=_0x13b5fd['charAt'](_0x538450++);~_0x3c908f&&(_0x43bb52=_0x1f9d9d%0x4?_0x43bb52*0x40+_0x3c908f:_0x3c908f,_0x1f9d9d++%0x4)?_0x2185ac+=String['fromCharCode'](0xff&_0x43bb52>>(-0x2*_0x1f9d9d&0x6)):0x0){_0x3c908f=_0x346204['indexOf'](_0x3c908f);}for(let _0x5b93c7=0x0,_0x1e3a95=_0x2185ac['length'];_0x5b93c7<_0x1e3a95;_0x5b93c7++){_0x352ce9+='%'+('00'+_0x2185ac['charCodeAt'](_0x5b93c7)['toString'](0x10))['slice'](-0x2);}return decodeURIComponent(_0x352ce9);};_0x1000['aeRKEx']=_0x451bbd,_0x1000['prXLsi']={},_0x1000['dcqmaz']=!![];}const _0x42ed1f=_0x5dfb0e[0x0];_0x1000['WeWpyb']!==_0x42ed1f&&(_0x1000['prXLsi']={},_0x1000['WeWpyb']=_0x42ed1f);const _0x91fb5c=_0x1000['prXLsi'][_0x4b7851];return _0x91fb5c===undefined?(_0x10000a=_0x1000['aeRKEx'](_0x10000a),_0x1000['prXLsi'][_0x4b7851]=_0x10000a):_0x10000a=_0x91fb5c,_0x10000a;}function buildRungs(_0x3c6625,_0x2b6dd1){const _0x196e12=_0x3ba5d1;if(!_0x2b6dd1)return[rung1(_0x3c6625)];const _0x3eefb8=[rung1(_0x3c6625),rung2(_0x3c6625,_0x2b6dd1[_0x196e12(0x208)])];if(_0x2b6dd1[_0x196e12(0x214)])_0x3eefb8[_0x196e12(0x1e2)](rung3(_0x3c6625,_0x2b6dd1[_0x196e12(0x214)]));return _0x3eefb8;}function nextRung(_0x1c0730,_0x1ad587){const _0x3f3c3c=_0x3ba5d1;return _0x1ad587[_0x3f3c3c(0x207)](_0x195fc3=>_0x195fc3['id']===_0x1c0730['id']+0x1);}const LADDER_END_REASONS=new Set([_0x3ba5d1(0x20d),'budget_exhausted','retry_after_too_long']);function adoptRetryAfter(_0x5db29f,_0xf21516){const _0x413816=_0x3ba5d1;if(_0x5db29f===undefined)return undefined;if(_0xf21516['id']===0x1)return _0x5db29f;return Math[_0x413816(0x232)](_0x5db29f,_0xf21516[_0x413816(0x226)]);}function planNextStep(_0x4359be){const _0x8b7578=_0x3ba5d1,_0x3c29c1=!_0x4359be[_0x8b7578(0x229)][_0x8b7578(0x1f4)];if(_0x3c29c1&&!LADDER_END_REASONS[_0x8b7578(0x21e)](_0x4359be['decision'][_0x8b7578(0x1c1)]))return undefined;const _0x12fe52=_0x3c29c1?nextRung(_0x4359be[_0x8b7578(0x1ef)],_0x4359be[_0x8b7578(0x1d9)]):_0x4359be[_0x8b7578(0x1ef)];if(!_0x12fe52)return undefined;if(!_0x3c29c1)return{'rung':_0x12fe52,'escalating':![],'delay':_0x4359be[_0x8b7578(0x21c)]};const _0x579fc7=adoptRetryAfter(_0x4359be[_0x8b7578(0x211)],_0x12fe52);return{'rung':_0x12fe52,'escalating':!![],'delay':computeBackoffDelay(0x1,_0x12fe52['policy'],{..._0x579fc7!==undefined?{'retryAfterMs':_0x579fc7}:{},'random':_0x4359be[_0x8b7578(0x21a)],'ceilingMs':_0x12fe52[_0x8b7578(0x21d)]})};}function withinLadderBudget(_0x31718a,_0x1b1055,_0x233b6b,_0x96bca5){if(!_0x233b6b)return!![];const _0x318a64=_0x233b6b['totalBudgetMs'];if(_0x318a64===undefined)return!![];if(_0x31718a===undefined)return!![];return _0x96bca5()-_0x31718a+_0x1b1055<=_0x318a64;}function tierEndsAt(_0x5a366e,_0x4ffd40,_0x3c2f15){const _0x17e448=_0x3ba5d1;if(_0x5a366e[_0x17e448(0x1f6)])return undefined;const _0x54f16f=Math[_0x17e448(0x1ec)](0x0,_0x5a366e['policy'][_0x17e448(0x219)]-_0x3c2f15);return _0x4ffd40+_0x54f16f*_0x5a366e[_0x17e448(0x1c5)][_0x17e448(0x224)];}async function*announceAndWait(_0x216cfd,_0x5a0430,_0x500ca4){const _0x6cde56=_0x3ba5d1,_0x47befe=_0x216cfd[_0x6cde56(0x22b)]?{'tier':_0x216cfd[_0x6cde56(0x1ef)]['id'],'tierCount':_0x216cfd[_0x6cde56(0x1f2)],'totalAttempts':_0x216cfd[_0x6cde56(0x20e)],..._0x216cfd[_0x6cde56(0x1fc)]!==undefined?{'tierEndsAt':_0x216cfd[_0x6cde56(0x1fc)]}:{}}:{};_0x216cfd[_0x6cde56(0x1c0)]&&(yield{'type':_0x6cde56(0x220),'attempt':_0x216cfd[_0x6cde56(0x1f3)],'discardedToolCallIds':_0x216cfd[_0x6cde56(0x1e3)]});yield{'type':'retry_scheduled','attempt':_0x216cfd[_0x6cde56(0x1f3)],'maxRetries':_0x216cfd[_0x6cde56(0x1ef)][_0x6cde56(0x1c5)][_0x6cde56(0x219)],'delayMs':_0x216cfd[_0x6cde56(0x1e5)],'resumeAt':_0x216cfd['resumeAt'],'errorType':errorTypeOf(_0x216cfd[_0x6cde56(0x227)]),'message':messageOf(_0x216cfd[_0x6cde56(0x227)]),..._0x216cfd[_0x6cde56(0x211)]!==undefined?{'retryAfterMs':_0x216cfd[_0x6cde56(0x211)]}:{},..._0x47befe},await _0x5a0430(_0x216cfd[_0x6cde56(0x1e5)],_0x500ca4);if(_0x500ca4?.[_0x6cde56(0x1f7)]===!![])return;yield{'type':_0x6cde56(0x1cf),'attempt':_0x216cfd[_0x6cde56(0x1f3)],'maxRetries':_0x216cfd['rung'][_0x6cde56(0x1c5)][_0x6cde56(0x219)],..._0x216cfd['withTier']?{'tier':_0x216cfd[_0x6cde56(0x1ef)]['id'],'tierCount':_0x216cfd[_0x6cde56(0x1f2)],'totalAttempts':_0x216cfd[_0x6cde56(0x20e)]}:{}};}function createAttemptDeadline(_0x3b0028,_0x292dd2){const _0x36b641=_0x3ba5d1;if(_0x292dd2<=0x0)return{'controls':undefined,'onFrame':()=>{},'fired':![],'whenSilent':undefined,'dispose':()=>{}};const _0x37e634=new AbortController(),_0x4bdbce=()=>_0x37e634[_0x36b641(0x1d8)]();_0x3b0028?.[_0x36b641(0x1de)](_0x36b641(0x1d8),_0x4bdbce,{'once':!![]});if(_0x3b0028?.[_0x36b641(0x1f7)]===!![])_0x37e634[_0x36b641(0x1d8)]();let _0x69b576,_0x2c0da9=![],_0x39992d=()=>{};const _0x1af4da=new Promise(_0x37cc5c=>{_0x39992d=_0x37cc5c;}),_0x5932f0=()=>{const _0x2f0c25=_0x36b641;if(_0x37e634[_0x2f0c25(0x234)]['aborted'])return;if(_0x69b576!==undefined)clearTimeout(_0x69b576);_0x69b576=setTimeout(()=>{const _0x137583=_0x2f0c25;_0x2c0da9=!![],_0x37e634[_0x137583(0x1d8)](),_0x39992d();},_0x292dd2);};_0x5932f0();const _0x53182f={'readDeadline':_0x37e634[_0x36b641(0x234)],'onFrame':_0x5932f0};return{'controls':_0x53182f,'onFrame':_0x5932f0,get 'fired'(){const _0x3ad793=_0x36b641;return _0x2c0da9&&_0x3b0028?.[_0x3ad793(0x1f7)]!==!![];},'whenSilent':_0x1af4da,'dispose':()=>{const _0x58ae68=_0x36b641;_0x69b576!==undefined&&(clearTimeout(_0x69b576),_0x69b576=undefined),_0x3b0028?.[_0x58ae68(0x205)]('abort',_0x4bdbce);}};}async function*guardSilence(_0x198adf,_0x238e10){const _0x429474=_0x3ba5d1,_0x19be2d=_0x238e10['whenSilent'];if(!_0x19be2d){yield*_0x198adf;return;}try{for(;;){const _0x574e1c=_0x198adf[_0x429474(0x1e1)]();_0x574e1c[_0x429474(0x1f9)](()=>{});const _0x4d06e6=await Promise[_0x429474(0x1fa)]([_0x574e1c[_0x429474(0x1ce)](_0x12d603=>({'kind':_0x429474(0x1e7),'result':_0x12d603})),_0x19be2d['then'](()=>({'kind':'silence'}))]);if(_0x4d06e6[_0x429474(0x202)]===_0x429474(0x1dc))return;if(_0x4d06e6[_0x429474(0x233)][_0x429474(0x20f)]===!![])return;_0x238e10['onFrame'](),yield _0x4d06e6[_0x429474(0x233)][_0x429474(0x231)];}}finally{void _0x198adf['return']?.(undefined)?.['catch'](()=>{});}}export async function*withRetry(_0x56709a,_0x1fffee){const _0x1f4892=_0x3ba5d1,_0x5ee320=normalizePolicy(_0x1fffee['policy']),_0x1a8843=normalizeEscalation(_0x1fffee['escalation']??null),_0x4a092f=buildRungs(_0x5ee320,_0x1a8843),_0x3333e9=_0x1fffee['now']??Date[_0x1f4892(0x213)],_0x1f2323=_0x1fffee[_0x1f4892(0x1eb)]??defaultSleep,_0x5161f2=_0x1fffee[_0x1f4892(0x21a)]??Math[_0x1f4892(0x21a)],_0x4a5ec7=_0x1fffee[_0x1f4892(0x234)],_0x238eeb=_0x1a8843!==null,_0x58a817=resolveReadSilenceMs(_0x5ee320,_0x1fffee[_0x1f4892(0x21b)]);let _0x635b1a,_0x1827fb,_0x141beb=0x0,_0x309a51=0x0,_0x2305fc=_0x4a092f[Math[_0x1f4892(0x1ec)](0x0,(_0x1fffee[_0x1f4892(0x1d2)]??0x1)-0x1)]??_0x4a092f[0x0];for(;;){if(Boolean(_0x4a5ec7?.[_0x1f4892(0x1f7)]))return;let _0x23009a=![];const _0x21af4e=[];let _0x592aa7=![],_0x11edde;const _0x5c5de0=createAttemptDeadline(_0x4a5ec7,_0x58a817);try{for await(const _0x4021fb of guardSilence(_0x56709a(_0x5c5de0[_0x1f4892(0x203)]),_0x5c5de0)){if(_0x4a5ec7?.['aborted']===!![])return;if(CONTENT_EVENTS[_0x1f4892(0x21e)](_0x4021fb[_0x1f4892(0x1ea)]))_0x23009a=!![];if(_0x4021fb['type']===_0x1f4892(0x1e4))_0x21af4e[_0x1f4892(0x1e2)](_0x4021fb[_0x1f4892(0x1d6)]);if(_0x4021fb[_0x1f4892(0x1ea)]===_0x1f4892(0x227)){_0x11edde=_0x4021fb[_0x1f4892(0x227)];break;}if(_0x4021fb['type']===_0x1f4892(0x20f))_0x592aa7=!![];yield _0x4021fb;}}finally{_0x5c5de0[_0x1f4892(0x1ed)]();}if(Boolean(_0x4a5ec7?.['aborted']))return;if(_0x592aa7)return;_0x11edde===undefined&&_0x5c5de0['fired']&&(_0x11edde=new LLMError(''[_0x1f4892(0x1cc)](_0x1fffee[_0x1f4892(0x1fd)],'/')[_0x1f4892(0x1cc)](_0x1fffee['modelId'],_0x1f4892(0x1cd))[_0x1f4892(0x1cc)](_0x58a817,_0x1f4892(0x1df)),_0x1fffee['providerId'],'timeout',!![]));_0x11edde===undefined&&(_0x11edde=new LLMError(''['concat'](_0x1fffee[_0x1f4892(0x1fd)],'/')['concat'](_0x1fffee[_0x1f4892(0x22c)],_0x1f4892(0x1e0)),_0x1fffee['providerId'],'network_error',!![]));_0x635b1a??=_0x3333e9(),_0x1827fb??=_0x3333e9();const _0x5ba596=_0x2305fc[_0x1f4892(0x1c5)]['respectRetryAfter']?retryAfterOf(_0x11edde):undefined,_0x2dbaab=adoptRetryAfter(_0x5ba596,_0x2305fc),_0x34eca5=computeBackoffDelay(_0x141beb+0x1,_0x2305fc[_0x1f4892(0x1c5)],{..._0x2dbaab!==undefined?{'retryAfterMs':_0x2dbaab}:{},'random':_0x5161f2,'ceilingMs':_0x2305fc[_0x1f4892(0x21d)]});let _0x25065e=decide({'error':_0x11edde,..._0x4a5ec7?{'signal':_0x4a5ec7}:{},'committed':_0x23009a,'retryIndex':_0x141beb,'firstFailureAt':_0x1827fb,'candidateDelay':_0x34eca5,..._0x2305fc['id']===0x1&&_0x5ba596!==undefined?{'retryAfterMs':_0x5ba596}:{},'policy':_0x2305fc[_0x1f4892(0x1c5)],'now':_0x3333e9});_0x2305fc[_0x1f4892(0x1f6)]&&_0x25065e['reason']===_0x1f4892(0x20d)&&(_0x25065e={'retry':!![],'reason':'retryable'});if(_0x25065e[_0x1f4892(0x1c1)]==='aborted')return;const _0x54bd99=planNextStep({'decision':_0x25065e,'rung':_0x2305fc,'rungs':_0x4a092f,'candidateDelay':_0x34eca5,..._0x5ba596!==undefined?{'retryAfterMs':_0x5ba596}:{},'random':_0x5161f2});if(!_0x54bd99){yield{'type':_0x1f4892(0x227),'error':_0x11edde};return;}_0x54bd99[_0x1f4892(0x1c4)]&&(_0x1827fb=undefined,_0x141beb=0x0);_0x2305fc=_0x54bd99[_0x1f4892(0x1ef)],_0x141beb+=0x1,_0x309a51+=0x1;if(!withinLadderBudget(_0x635b1a,_0x54bd99[_0x1f4892(0x1e5)],_0x1a8843,_0x3333e9)){yield{'type':_0x1f4892(0x227),'error':_0x11edde};return;}const _0x39d489=_0x238eeb?tierEndsAt(_0x2305fc,_0x3333e9(),_0x141beb):undefined;yield*announceAndWait({'rung':_0x2305fc,'tierCount':_0x4a092f[_0x1f4892(0x204)],'attempt':_0x141beb,'totalAttempts':_0x309a51,'delay':_0x54bd99[_0x1f4892(0x1e5)],'resumeAt':_0x3333e9()+_0x54bd99['delay'],'error':_0x11edde,'committed':_0x23009a,'toolCallIds':_0x21af4e,..._0x5ba596!==undefined?{'retryAfterMs':_0x5ba596}:{},..._0x39d489!==undefined?{'tierEndsAt':_0x39d489}:{},'withTier':_0x238eeb},_0x1f2323,_0x4a5ec7);}}