pi-harness-runtime 1.1.481 → 1.1.483

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 (53) hide show
  1. package/CHANGELOG.md +119 -0
  2. package/harness/pending-actions.ts +408 -0
  3. package/harness/pending-question-state.ts +15 -7
  4. package/harness/provider-failure.ts +344 -0
  5. package/harness/provider-recovery.ts +351 -0
  6. package/index.ts +368 -2
  7. package/package.json +1 -1
  8. package/packages/agent-policy/package.json +1 -1
  9. package/packages/auth/package.json +1 -1
  10. package/packages/autonomous-runtime/package.json +1 -1
  11. package/packages/checkpoint/package.json +1 -1
  12. package/packages/clipboard/package.json +1 -1
  13. package/packages/codex-watcher/package.json +1 -1
  14. package/packages/config-capture/package.json +1 -1
  15. package/packages/contracts/package.json +1 -1
  16. package/packages/cookie-sanitizer/package.json +1 -1
  17. package/packages/evaluation-engine/package.json +1 -1
  18. package/packages/event-bus/package.json +1 -1
  19. package/packages/event-store/package.json +1 -1
  20. package/packages/experience-replay/package.json +1 -1
  21. package/packages/file-copy-helper/package.json +1 -1
  22. package/packages/intent-analyzer/package.json +1 -1
  23. package/packages/jev-judge/package.json +1 -1
  24. package/packages/knowledge-retrieval/package.json +1 -1
  25. package/packages/learning-engine/package.json +1 -1
  26. package/packages/logging/package.json +1 -1
  27. package/packages/memory-engine/package.json +1 -1
  28. package/packages/notification/package.json +1 -1
  29. package/packages/paperclip-integration/package.json +1 -1
  30. package/packages/performance-optimizer/package.json +1 -1
  31. package/packages/privilege-broker/package.json +1 -1
  32. package/packages/prompt-compiler/package.json +1 -1
  33. package/packages/providers/package.json +1 -1
  34. package/packages/qdrant-skills/package.json +1 -1
  35. package/packages/quota-manager/package.json +1 -1
  36. package/packages/relay/package.json +1 -1
  37. package/packages/skill-mcp-client/package.json +1 -1
  38. package/packages/skills/package.json +1 -1
  39. package/packages/todo-bd-sync/package.json +1 -1
  40. package/packages/token-estimation/package.json +1 -1
  41. package/packages/tooling-preference/package.json +1 -1
  42. package/packages/trajectory/package.json +1 -1
  43. package/packages/tui/dist/harness-footer.d.ts +10 -0
  44. package/packages/tui/dist/harness-footer.d.ts.map +1 -1
  45. package/packages/tui/dist/harness-footer.js +16 -1
  46. package/packages/tui/dist/harness-footer.js.map +1 -1
  47. package/packages/tui/package.json +1 -1
  48. package/packages/tui/src/harness-footer.ts +18 -1
  49. package/packages/two-phase-review/package.json +1 -1
  50. package/packages/types/package.json +1 -1
  51. package/packages/webmcp-tester/package.json +1 -1
  52. package/packages/wiki/package.json +1 -1
  53. package/packages/write-review/package.json +1 -1
@@ -0,0 +1,344 @@
1
+ /**
2
+ * The kind of a provider failure.
3
+ *
4
+ * A failure of a provider is not one thing: a temporary limit recovers, an
5
+ * exhausted plan does not, and a rejected credential never recovers by
6
+ * waiting. The kind decides whether an automatic retry may be scheduled at
7
+ * all, so the classification belongs before the retry policy.
8
+ *
9
+ * The kinds are deliberately few. An unknown failure stays unknown: it must
10
+ * never be turned into an approval, a completion, or an unlimited retry.
11
+ */
12
+ export type ProviderFailureKind =
13
+ /** A temporary limit. A `Retry-After` may name the deadline. */
14
+ | "rate-limit"
15
+ /** A temporary overload of the provider, without a supplied deadline. */
16
+ | "overload"
17
+ /** The plan, the credit, or the quota of the account is exhausted. */
18
+ | "usage-exhausted"
19
+ /** The credential was rejected. Waiting does not help. */
20
+ | "credentials"
21
+ /** The failure could not be classified. */
22
+ | "unknown";
23
+
24
+ /**
25
+ * The policy that decides the deadline of a retry.
26
+ *
27
+ * The classification names the failure; the policy names what may happen
28
+ * next. They are apart, because the same failure may be recovered by a
29
+ * stated deadline, by a bounded backoff, or not at all.
30
+ */
31
+ export type ProviderRecoveryPolicy =
32
+ /** No automatic retry. The failure waits for a human. */
33
+ | "none"
34
+ /** The evidence states the deadline. The retry runs at that deadline. */
35
+ | "retry-after"
36
+ /** A bounded backoff of the provider decides the deadline. */
37
+ | "backoff"
38
+ /**
39
+ * A bounded recovery cycle of the harness decides the deadline.
40
+ *
41
+ * The cycle is finite (four attempts at most) and every deadline it
42
+ * picks is a *next attempt*, never a promised recovery of the provider.
43
+ */
44
+ | "bounded-recovery";
45
+
46
+ /**
47
+ * A classified provider failure.
48
+ */
49
+ export interface ProviderFailure {
50
+ /** The kind of the failure. */
51
+ kind: ProviderFailureKind;
52
+ /** May an automatic retry help? */
53
+ retryable: boolean;
54
+ /** The policy that decides the deadline of the retry. */
55
+ recovery: ProviderRecoveryPolicy;
56
+ /**
57
+ * The window the limit belongs to, when the evidence names one.
58
+ *
59
+ * A reset of the provider may only be used as the floor of a retry
60
+ * when it belongs to the same window ("h5", "weekly", ...). A failure
61
+ * that names no window has no window, so no reset applies to it.
62
+ */
63
+ window?: string;
64
+ /**
65
+ * The validated deadline of a retry in milliseconds.
66
+ *
67
+ * It is only set when the evidence carries one. A failure without a
68
+ * deadline has no `retryAfterMs`: a made-up deadline is a lie in the
69
+ * status row.
70
+ */
71
+ retryAfterMs?: number;
72
+ /** The code the provider reported (429, 2067, ...). */
73
+ code?: string;
74
+ /** The provider the failure names, when the evidence names one. */
75
+ provider?: string;
76
+ /** A short, truthful reason for a status row. */
77
+ reason: string;
78
+ }
79
+
80
+ /**
81
+ * The wrapper a client puts around the failure it retried.
82
+ *
83
+ * "Retry failed after 3 attempts: <the real error>" says how often the
84
+ * client tried; the real error is what classifies the failure.
85
+ */
86
+ const RETRY_WRAPPER = /Retry failed after\s+(\d+)\s+attempts\s*:\s*([\s\S]*)$/i;
87
+
88
+ /**
89
+ * The usage exhaustion of a plan, a credit, or a quota.
90
+ *
91
+ * The check comes first: the message of a plan limit also says "rate
92
+ * limit", so the rate limit pattern would otherwise win.
93
+ */
94
+ const USAGE_EXHAUSTED = [
95
+ /usage limit (?:has been|was|is) reached/i,
96
+ /token plan usage limit/i,
97
+ /insufficient[ _-]?(?:quota|balance|credits?|funds)/i,
98
+ /quota (?:exhausted|used up)/i,
99
+ /out of credits/i,
100
+ /billing (?:hard )?limit/i,
101
+ /\b2067\b/,
102
+ ];
103
+
104
+ /** A temporary limit of the provider. */
105
+ const RATE_LIMIT = [/\brate[ _-]?limit/i, /too many requests/i, /\b429\b/];
106
+
107
+ /** A temporary overload of the provider. */
108
+ const OVERLOAD = [
109
+ /overloaded_error/i,
110
+ /peak-hour surge/i,
111
+ /temporarily busy/i,
112
+ /try again shortly/i,
113
+ /\b529\b/,
114
+ /\b2064\b/,
115
+ /timed[ _-]?out/i,
116
+ ];
117
+
118
+ /** A rejected credential. */
119
+ const CREDENTIALS = [
120
+ /unauthorized/i,
121
+ /invalid[ _-]?api[ _-]?key/i,
122
+ /authentication (?:failed|error)/i,
123
+ /permission denied/i,
124
+ /\b401\b/,
125
+ /\b403\b/,
126
+ ];
127
+
128
+ /**
129
+ * The output limit of the session.
130
+ *
131
+ * It is not a failure of the provider: the session ran out of output, and
132
+ * the continuation of the output limit owns it. The classifier leaves it
133
+ * alone, so no blocked row appears next to that continuation.
134
+ */
135
+ const OUTPUT_LIMIT = [
136
+ /maximum output token limit/i,
137
+ /output[ _-]?token[ _-]?limit/i,
138
+ /output[ _-]?limit/i,
139
+ /max_output_tokens/i,
140
+ /max_tokens/i,
141
+ ];
142
+
143
+ /** The codes the providers of this harness are known by. */
144
+ const PROVIDER_BY_CODE: Record<string, string> = {
145
+ "2064": "GLM",
146
+ "2067": "MiniMax",
147
+ "529": "Anthropic",
148
+ };
149
+
150
+ /**
151
+ * The window a limit belongs to, when the evidence names one.
152
+ *
153
+ * The window decides whether a reset may be used as the floor of a retry:
154
+ * a reset of the five-hour window says nothing about a plan limit that the
155
+ * provider does not tie to a window.
156
+ */
157
+ export function detectLimitWindow(text: string): string | undefined {
158
+ if (/\b5[\s-]?h(?:our)?s?\b|\bh5\b|\bhourly\b|\bper hour\b/i.test(text)) return "h5";
159
+ if (/\bweekly\b|\bper week\b/i.test(text)) return "weekly";
160
+ if (/\bmonthly\b|\bper month\b/i.test(text)) return "monthly";
161
+ if (/\bdaily\b|\bper day\b/i.test(text)) return "daily";
162
+ return undefined;
163
+ }
164
+
165
+ /**
166
+ * The inner failure of a retry wrapper.
167
+ *
168
+ * The wrapper is unwrapped so that the classification sees the real error;
169
+ * the number of attempts is returned with it.
170
+ */
171
+ export function unwrapRetryWrapper(text: string): {
172
+ inner: string;
173
+ attempts?: number;
174
+ wrapped: boolean;
175
+ } {
176
+ const match = RETRY_WRAPPER.exec(text.trim());
177
+ if (!match) return { inner: text, wrapped: false };
178
+ const attempts = Number.parseInt(match[1], 10);
179
+ return {
180
+ inner: match[2],
181
+ attempts: Number.isFinite(attempts) ? attempts : undefined,
182
+ wrapped: true,
183
+ };
184
+ }
185
+
186
+ /**
187
+ * The retry deadline that the evidence states.
188
+ *
189
+ * Only a stated deadline counts: "retry after 30 seconds" and "Retry-After:
190
+ * 120" name one, and nothing else does. A deadline that the provider did
191
+ * not state is never invented here.
192
+ */
193
+ export function parseRetryAfterMs(text: string): number | undefined {
194
+ // The minutes come first: a duration of minutes also matches the
195
+ // pattern of the seconds, and "2 minutes" is not two seconds.
196
+ const minutes = /retry[- ]?after\s*[:=]?\s*(\d+(?:\.\d+)?)\s*(?:m|min|mins|minute|minutes)\b/i.exec(
197
+ text,
198
+ );
199
+ if (minutes) {
200
+ const value = Number.parseFloat(minutes[1]);
201
+ if (Number.isFinite(value) && value >= 0) return Math.round(value * 60_000);
202
+ }
203
+ const seconds = /retry[- ]?after\s*[:=]?\s*(\d+(?:\.\d+)?)\s*(?:s|sec|secs|second|seconds)\b/i.exec(
204
+ text,
205
+ );
206
+ if (seconds) {
207
+ const value = Number.parseFloat(seconds[1]);
208
+ if (Number.isFinite(value) && value >= 0) return Math.round(value * 1000);
209
+ }
210
+ const bare = /retry[- ]?after\s*[:=]?\s*(\d+(?:\.\d+)?)\b/i.exec(text);
211
+ if (bare) {
212
+ const value = Number.parseFloat(bare[1]);
213
+ if (Number.isFinite(value) && value >= 0) return Math.round(value * 1000);
214
+ }
215
+ return undefined;
216
+ }
217
+
218
+ /**
219
+ * The code the provider reported, when the evidence carries one.
220
+ */
221
+ export function parseFailureCode(text: string): string | undefined {
222
+ // A code is three digits (an HTTP status) or four (a provider code such
223
+ // as 2067), so the pattern accepts both.
224
+ const match = /(?:\(|code["'\s:=]+|status(?:\s+code)?["'\s:=]+)(\d{3,4})\b/i.exec(
225
+ text,
226
+ );
227
+ if (!match) return undefined;
228
+ const code = match[1];
229
+ // A code that is not an HTTP status and not a provider code proves
230
+ // nothing: the numbers in an error message are not always a code.
231
+ if (code === "429" || code === "401" || code === "403" || code === "529") return code;
232
+ if (code === "2064" || code === "2067") return code;
233
+ return undefined;
234
+ }
235
+
236
+ /**
237
+ * Classify a failure of a provider.
238
+ *
239
+ * `null` means that the text does not look like a failure at all, so the
240
+ * caller can tell "no failure" from "a failure of an unknown kind".
241
+ */
242
+ export function classifyProviderFailure(text: string | undefined): ProviderFailure | null {
243
+ if (!text) return null;
244
+ const raw = text.trim();
245
+ if (raw.length === 0) return null;
246
+
247
+ const { inner } = unwrapRetryWrapper(raw);
248
+ const code = parseFailureCode(inner) ?? parseFailureCode(raw);
249
+ const provider = code ? PROVIDER_BY_CODE[code] : undefined;
250
+ const retryAfterMs = parseRetryAfterMs(inner) ?? parseRetryAfterMs(raw);
251
+ const window = detectLimitWindow(inner) ?? detectLimitWindow(raw);
252
+
253
+ const matches = (patterns: RegExp[]): boolean =>
254
+ patterns.some((pattern) => pattern.test(inner) || pattern.test(raw));
255
+
256
+ // The output limit of the session is not a failure of the provider: the
257
+ // continuation of the output limit owns it.
258
+ if (matches(OUTPUT_LIMIT)) return null;
259
+
260
+ if (matches(USAGE_EXHAUSTED)) {
261
+ return {
262
+ kind: "usage-exhausted",
263
+ // The plan of the account is exhausted. That is not the end of the
264
+ // work: a bounded recovery cycle may still try, because the
265
+ // provider can reject around a reset that the harness does not
266
+ // see. The cycle is finite, and its deadline is the next attempt,
267
+ // never a promised recovery.
268
+ retryable: true,
269
+ recovery: "bounded-recovery",
270
+ ...(window ? { window } : {}),
271
+ ...(code ? { code } : {}),
272
+ ...(provider ? { provider } : {}),
273
+ reason: provider
274
+ ? `${provider} usage limit reached${code ? ` (${code})` : ""}`
275
+ : `usage limit reached${code ? ` (${code})` : ""}`,
276
+ };
277
+ }
278
+
279
+ if (matches(RATE_LIMIT)) {
280
+ return {
281
+ kind: "rate-limit",
282
+ retryable: true,
283
+ recovery: retryAfterMs !== undefined ? "retry-after" : "backoff",
284
+ ...(window ? { window } : {}),
285
+ ...(retryAfterMs !== undefined ? { retryAfterMs } : {}),
286
+ ...(code ? { code } : {}),
287
+ ...(provider ? { provider } : {}),
288
+ reason: `rate limited${code ? ` (${code})` : ""}`,
289
+ };
290
+ }
291
+
292
+ if (matches(OVERLOAD)) {
293
+ return {
294
+ kind: "overload",
295
+ retryable: true,
296
+ recovery: "backoff",
297
+ ...(window ? { window } : {}),
298
+ ...(retryAfterMs !== undefined ? { retryAfterMs } : {}),
299
+ ...(code ? { code } : {}),
300
+ ...(provider ? { provider } : {}),
301
+ reason: provider
302
+ ? `${provider} is overloaded${code ? ` (${code})` : ""}`
303
+ : `provider overloaded${code ? ` (${code})` : ""}`,
304
+ };
305
+ }
306
+
307
+ if (matches(CREDENTIALS)) {
308
+ return {
309
+ kind: "credentials",
310
+ retryable: false,
311
+ recovery: "none",
312
+ ...(window ? { window } : {}),
313
+ ...(code ? { code } : {}),
314
+ ...(provider ? { provider } : {}),
315
+ reason: `credentials rejected${code ? ` (${code})` : ""}`,
316
+ };
317
+ }
318
+
319
+ // The text is not a known failure. It is only a failure when it looks
320
+ // like one: an arbitrary text of an assistant message is not an error.
321
+ if (!looksLikeFailure(raw)) return null;
322
+ return {
323
+ kind: "unknown",
324
+ retryable: false,
325
+ recovery: "none",
326
+ ...(code ? { code } : {}),
327
+ reason: "provider error",
328
+ };
329
+ }
330
+
331
+ /**
332
+ * Does the text look like a failure at all?
333
+ */
334
+ function looksLikeFailure(text: string): boolean {
335
+ return (
336
+ /\berror\b/i.test(text) ||
337
+ /\bfailed\b/i.test(text) ||
338
+ /\bfailure\b/i.test(text) ||
339
+ /went wrong/i.test(text) ||
340
+ /\bstatus\s*code\b/i.test(text) ||
341
+ /\bhttp\s*\d{3}\b/i.test(text) ||
342
+ /\bexceeded\b/i.test(text)
343
+ );
344
+ }
@@ -0,0 +1,351 @@
1
+ /**
2
+ * The bounded recovery of a provider that rejects a request.
3
+ *
4
+ * A provider can reject a request around a reset that the harness does not
5
+ * see: the quota row shows a positive allowance, and the request still
6
+ * fails. The work must not be stranded because the client gave up after
7
+ * three short attempts, and it must not be retried forever either.
8
+ *
9
+ * The cycle is therefore finite and explicit:
10
+ *
11
+ * - the waits between the attempts are quadratic: 1, 4, 9 and 16 minutes,
12
+ * - at most four attempts run,
13
+ * - a repeated copy of the same error neither reschedules the pending
14
+ * attempt nor resets the counter,
15
+ * - a deadline the evidence states (an applicable reset, a `Retry-After`)
16
+ * is a lower bound of the deadline, never a shorter one,
17
+ * - every deadline is the *next attempt*, never a promised recovery of the
18
+ * provider.
19
+ *
20
+ * The controller decides the deadlines. It never dispatches anything: the
21
+ * executor that owns the resume stays the only owner of the execution.
22
+ */
23
+ import type { ProviderFailureKind } from "./provider-failure.ts";
24
+
25
+ /**
26
+ * The number of attempts of a recovery cycle.
27
+ *
28
+ * After the fourth attempt fails, the cycle is exhausted: the row shows
29
+ * that no fifth attempt is scheduled.
30
+ */
31
+ export const MAX_RECOVERY_ATTEMPTS = 4;
32
+
33
+ /**
34
+ * The buffer after an applicable reset.
35
+ *
36
+ * A reset that is reached exactly at its second is not usable yet, so the
37
+ * retry waits half a minute more.
38
+ */
39
+ export const RESET_BUFFER_MS = 30_000;
40
+
41
+ /**
42
+ * The age after which a reset observation is stale.
43
+ *
44
+ * A stale observation never sets a deadline: the displayed reset moves, and
45
+ * a moving deadline would postpone the retry forever.
46
+ */
47
+ export const MAX_RESET_EVIDENCE_AGE_MS = 30 * 60_000;
48
+
49
+ /**
50
+ * The wait after the attempt that failed.
51
+ *
52
+ * The sequence is quadratic: 1, 4, 9 and 16 minutes. The nominal cumulative
53
+ * waiting time is therefore 1, 5, 14 and 30 minutes - measured from the
54
+ * first failure, without the time the requests themselves took.
55
+ */
56
+ export function quadraticRecoveryDelayMs(attempt: number): number {
57
+ const index = Math.max(1, Math.floor(attempt));
58
+ return index * index * 60_000;
59
+ }
60
+
61
+ /**
62
+ * A reset of the provider that the harness observed.
63
+ *
64
+ * The evidence carries its own identity and its observation time, so a
65
+ * stale or foreign reset cannot become the deadline of a retry.
66
+ */
67
+ export interface RecoveryResetEvidence {
68
+ /** The provider the reset belongs to. */
69
+ provider: string;
70
+ /** The window the reset belongs to ("h5", "weekly", ...). */
71
+ window: string;
72
+ /** The epoch ms of the reset. */
73
+ resetAt: number;
74
+ /** The epoch ms of the observation. */
75
+ observedAt: number;
76
+ /** The source of the observation, for the log. */
77
+ source?: string;
78
+ }
79
+
80
+ /**
81
+ * The failure that the recovery cycle reacts to.
82
+ */
83
+ export interface RecoveryFailureInput {
84
+ /**
85
+ * The identity of the failed turn.
86
+ *
87
+ * A repeated copy of the same error carries the same identity, so it
88
+ * cannot start a second cycle.
89
+ */
90
+ failureKey: string;
91
+ /** The session the failure happened in. */
92
+ sessionId: string;
93
+ /** The provider that rejected the request. */
94
+ provider: string;
95
+ /** The kind of the failure. */
96
+ kind: ProviderFailureKind;
97
+ /** The window the limit belongs to, when the evidence names one. */
98
+ window?: string;
99
+ /** The absolute deadline the evidence states, in epoch ms. */
100
+ retryAfterAt?: number;
101
+ }
102
+
103
+ /**
104
+ * What the cycle decided about a failure.
105
+ */
106
+ export type RecoveryOutcome =
107
+ | {
108
+ /** An attempt was scheduled. */
109
+ outcome: "scheduled";
110
+ /** The number of the attempt that will run. */
111
+ attempt: number;
112
+ /** The absolute deadline of the attempt. */
113
+ dueAt: number;
114
+ /** The wait after the failure. */
115
+ delayMs: number;
116
+ /** What decided the deadline. */
117
+ boundBy: "policy" | "reset" | "retry-after";
118
+ }
119
+ | {
120
+ /** The budget of the cycle is used up. No attempt is scheduled. */
121
+ outcome: "blocked";
122
+ /** The number of attempts that ran. */
123
+ attempt: number;
124
+ }
125
+ | {
126
+ /** The same error arrived again. The cycle does not move. */
127
+ outcome: "duplicate";
128
+ /** The number of the attempt that is pending or was the last one. */
129
+ attempt: number;
130
+ }
131
+ | {
132
+ /** An attempt is already pending. No second timer is created. */
133
+ outcome: "already-scheduled";
134
+ /** The number of the pending attempt. */
135
+ attempt: number;
136
+ /** The deadline of the pending attempt. */
137
+ dueAt: number;
138
+ };
139
+
140
+ /**
141
+ * The state of a recovery cycle.
142
+ */
143
+ export interface RecoveryCycleState {
144
+ /** The session the cycle belongs to. */
145
+ sessionId: string;
146
+ /** The provider the cycle belongs to. */
147
+ provider: string;
148
+ /** The number of the attempt that runs next. */
149
+ attempt: number;
150
+ /** The deadline of the pending attempt. */
151
+ dueAt: number | null;
152
+ /** The identity of the failure the cycle reacted to last. */
153
+ lastFailureKey: string | null;
154
+ /** The moment the first failure of the cycle was seen. */
155
+ startedAt: number;
156
+ /** The cycle has used its budget. */
157
+ exhausted: boolean;
158
+ }
159
+
160
+ /**
161
+ * The options of the controller.
162
+ */
163
+ export interface ProviderRecoveryControllerOptions {
164
+ /** The clock of the controller. It is injected, so the tests are exact. */
165
+ now?: () => number;
166
+ /** The age after which a reset observation is stale. */
167
+ maxResetEvidenceAgeMs?: number;
168
+ }
169
+
170
+ /**
171
+ * The controller of the recovery cycles.
172
+ */
173
+ export interface ProviderRecoveryController {
174
+ /**
175
+ * React to a failure of a provider.
176
+ *
177
+ * The failure decides the deadline of the next attempt. The controller
178
+ * never dispatches anything itself.
179
+ */
180
+ noteFailure(
181
+ input: RecoveryFailureInput,
182
+ resetEvidence?: RecoveryResetEvidence,
183
+ ): RecoveryOutcome;
184
+ /** A successful turn ends the cycle and resets its counter. */
185
+ noteSuccess(key: { sessionId: string; provider: string }): void;
186
+ /** A cancellation ends the cycle. */
187
+ cancel(key: { sessionId: string; provider: string }): void;
188
+ /** The state of a cycle, for the status row and the tests. */
189
+ cycle(key: {
190
+ sessionId: string;
191
+ provider: string;
192
+ kind: ProviderFailureKind;
193
+ }): RecoveryCycleState | null;
194
+ /** Remove every cycle. */
195
+ clear(): void;
196
+ }
197
+
198
+ /**
199
+ * The identity of a cycle.
200
+ *
201
+ * The cycle belongs to the session, to the provider and to the kind of the
202
+ * failure. A session change therefore starts a new cycle, and a different
203
+ * provider never shares the counter of another one.
204
+ */
205
+ function cycleKey(key: {
206
+ sessionId: string;
207
+ provider: string;
208
+ kind: ProviderFailureKind;
209
+ }): string {
210
+ return `${key.sessionId}|${key.provider}|${key.kind}`;
211
+ }
212
+
213
+ /**
214
+ * Create the controller of the recovery cycles.
215
+ */
216
+ export function createProviderRecoveryController(
217
+ options: ProviderRecoveryControllerOptions = {},
218
+ ): ProviderRecoveryController {
219
+ const now = options.now ?? (() => Date.now());
220
+ const maxResetEvidenceAgeMs =
221
+ options.maxResetEvidenceAgeMs ?? MAX_RESET_EVIDENCE_AGE_MS;
222
+ const cycles = new Map<string, RecoveryCycleState>();
223
+
224
+ /**
225
+ * The deadline that the applicable evidence states.
226
+ *
227
+ * A reset only counts when it is fresh, when it belongs to the same
228
+ * provider and to the same window as the failure, and when it lies in
229
+ * the future. A failure that names no window has no window, so no reset
230
+ * applies to it.
231
+ */
232
+ const resetFloor = (
233
+ input: RecoveryFailureInput,
234
+ evidence: RecoveryResetEvidence | undefined,
235
+ failureObservedAt: number,
236
+ ): number | undefined => {
237
+ if (!evidence) return undefined;
238
+ if (evidence.provider !== input.provider) return undefined;
239
+ if (!input.window || evidence.window !== input.window) return undefined;
240
+ if (evidence.resetAt <= failureObservedAt) return undefined;
241
+ if (failureObservedAt - evidence.observedAt > maxResetEvidenceAgeMs) return undefined;
242
+ return evidence.resetAt + RESET_BUFFER_MS;
243
+ };
244
+
245
+ return {
246
+ noteFailure(
247
+ input: RecoveryFailureInput,
248
+ resetEvidence?: RecoveryResetEvidence,
249
+ ): RecoveryOutcome {
250
+ const failureObservedAt = now();
251
+ const key = cycleKey({
252
+ sessionId: input.sessionId,
253
+ provider: input.provider,
254
+ kind: input.kind,
255
+ });
256
+ const cycle = cycles.get(key);
257
+
258
+ // An attempt that is still pending owns the next deadline. A
259
+ // second copy of the same error must not create a second timer
260
+ // and must not postpone the deadline.
261
+ if (cycle && cycle.dueAt !== null && cycle.dueAt > failureObservedAt) {
262
+ return {
263
+ outcome: "already-scheduled",
264
+ attempt: cycle.attempt,
265
+ dueAt: cycle.dueAt,
266
+ };
267
+ }
268
+ // The very same failure again: the cycle does not move. The
269
+ // counter of the attempts stays where it is.
270
+ if (cycle && cycle.lastFailureKey === input.failureKey) {
271
+ return { outcome: "duplicate", attempt: cycle.attempt };
272
+ }
273
+ // The budget of the cycle is used up: no fifth attempt.
274
+ if (cycle && cycle.exhausted) {
275
+ return { outcome: "blocked", attempt: cycle.attempt };
276
+ }
277
+
278
+ const attempt = (cycle?.attempt ?? 0) + 1;
279
+ if (attempt > MAX_RECOVERY_ATTEMPTS) {
280
+ const exhausted: RecoveryCycleState = {
281
+ sessionId: input.sessionId,
282
+ provider: input.provider,
283
+ attempt: MAX_RECOVERY_ATTEMPTS,
284
+ dueAt: null,
285
+ lastFailureKey: input.failureKey,
286
+ startedAt: cycle?.startedAt ?? failureObservedAt,
287
+ exhausted: true,
288
+ };
289
+ cycles.set(key, exhausted);
290
+ return { outcome: "blocked", attempt: MAX_RECOVERY_ATTEMPTS };
291
+ }
292
+
293
+ const delayMs = quadraticRecoveryDelayMs(attempt);
294
+ const policyDueAt = failureObservedAt + delayMs;
295
+ const floor = resetFloor(input, resetEvidence, failureObservedAt);
296
+ const retryAfterDueAt =
297
+ input.retryAfterAt && input.retryAfterAt > failureObservedAt
298
+ ? input.retryAfterAt
299
+ : undefined;
300
+
301
+ let dueAt = policyDueAt;
302
+ let boundBy: "policy" | "reset" | "retry-after" = "policy";
303
+ if (floor !== undefined && floor > dueAt) {
304
+ dueAt = floor;
305
+ boundBy = "reset";
306
+ }
307
+ if (retryAfterDueAt !== undefined && retryAfterDueAt > dueAt) {
308
+ dueAt = retryAfterDueAt;
309
+ boundBy = "retry-after";
310
+ }
311
+
312
+ cycles.set(key, {
313
+ sessionId: input.sessionId,
314
+ provider: input.provider,
315
+ attempt,
316
+ dueAt,
317
+ lastFailureKey: input.failureKey,
318
+ startedAt: cycle?.startedAt ?? failureObservedAt,
319
+ exhausted: false,
320
+ });
321
+
322
+ return { outcome: "scheduled", attempt, dueAt, delayMs, boundBy };
323
+ },
324
+
325
+ noteSuccess(key): void {
326
+ // A successful turn of the provider ends every cycle of that
327
+ // provider in that session: the counter starts at zero again.
328
+ for (const [id, cycle] of [...cycles.entries()]) {
329
+ if (cycle.sessionId === key.sessionId && cycle.provider === key.provider) {
330
+ cycles.delete(id);
331
+ }
332
+ }
333
+ },
334
+
335
+ cancel(key): void {
336
+ for (const [id, cycle] of [...cycles.entries()]) {
337
+ if (cycle.sessionId === key.sessionId && cycle.provider === key.provider) {
338
+ cycles.delete(id);
339
+ }
340
+ }
341
+ },
342
+
343
+ cycle(key): RecoveryCycleState | null {
344
+ return cycles.get(cycleKey(key)) ?? null;
345
+ },
346
+
347
+ clear(): void {
348
+ cycles.clear();
349
+ },
350
+ };
351
+ }