operon-agents-core 0.1.0-alpha.24 → 0.1.0-alpha.25
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/llm/define-model.d.ts +5 -6
- package/dist/llm/define-model.js +9 -4
- package/dist/llm/errors.d.ts +0 -3
- package/dist/llm/errors.js +0 -80
- package/dist/llm/index.d.ts +2 -2
- package/dist/llm/index.js +1 -1
- package/dist/llm/model.d.ts +0 -4
- package/dist/llm/retry.d.ts +5 -0
- package/dist/llm/retry.js +36 -10
- package/dist/llm/retrying-fetch.d.ts +17 -0
- package/dist/llm/retrying-fetch.js +66 -0
- package/package.json +1 -1
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import type { Api, AssistantMessage, AssistantMessageEventStream, Model, Provider, ProviderHeaders, Transport } from "../protocol/index.ts";
|
|
2
2
|
import { type ModelRuntime } from "./runtime.ts";
|
|
3
|
-
import type { CallOptions, LlmRequest
|
|
3
|
+
import type { CallOptions, LlmRequest } from "./model.ts";
|
|
4
4
|
/**
|
|
5
5
|
* How to reach the endpoint, as opposed to how the model should think. Fixed when the model is
|
|
6
6
|
* built, applied to every request it makes.
|
|
@@ -24,10 +24,10 @@ export interface ModelConnection {
|
|
|
24
24
|
/** HTTP request timeout, for providers/SDKs that support it. */
|
|
25
25
|
readonly timeoutMs?: number;
|
|
26
26
|
/**
|
|
27
|
-
* Retries
|
|
28
|
-
*
|
|
29
|
-
*
|
|
30
|
-
*
|
|
27
|
+
* Retries of a request that failed before its response started: 429, 408, 409, 5xx and
|
|
28
|
+
* connection failures, honoring `Retry-After`. Defaults to 8; 0 turns them off. These run
|
|
29
|
+
* inside the provider call and emit no events. A failure after the response has started is
|
|
30
|
+
* `streamWithRetry`'s. Bedrock and `pi-messages` do not read this setting.
|
|
31
31
|
*/
|
|
32
32
|
readonly maxRetries?: number;
|
|
33
33
|
/** Cap on honoring a server-requested retry delay. pi defaults to 60s; 0 disables the cap. */
|
|
@@ -102,7 +102,6 @@ export declare class ChatModel {
|
|
|
102
102
|
/** Stream one attempt. Non-terminal events are relayed live; the terminal event is held so
|
|
103
103
|
* a clean pre-content failure can be retried instead of surfaced. */
|
|
104
104
|
private runAttempt;
|
|
105
|
-
classifyError(err: unknown): RetryHint;
|
|
106
105
|
private errorEvent;
|
|
107
106
|
private errorMessage;
|
|
108
107
|
}
|
package/dist/llm/define-model.js
CHANGED
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
import { createAssistantMessageEventStream } from "@earendil-works/pi-ai";
|
|
2
2
|
import { emptyUsage } from "../loop/usage.js";
|
|
3
3
|
import { createModelRuntime, forceRefreshOAuth, } from "./runtime.js";
|
|
4
|
-
import {
|
|
4
|
+
import { createRetryingFetch } from "./retrying-fetch.js";
|
|
5
|
+
/** Roughly 30–40s of backoff with pi's policy, enough to outlast a typical short rate-limit window. */
|
|
6
|
+
const DEFAULT_PROVIDER_MAX_RETRIES = 8;
|
|
5
7
|
export class ChatModel {
|
|
6
8
|
id;
|
|
7
9
|
provider;
|
|
@@ -21,9 +23,15 @@ export class ChatModel {
|
|
|
21
23
|
constructor(spec) {
|
|
22
24
|
this.runtime = spec.runtime ?? createModelRuntime();
|
|
23
25
|
this.piModel = withAnthropicToolChanges(resolvePiModel(spec, this.runtime));
|
|
26
|
+
const maxRetries = spec.connection?.maxRetries ?? DEFAULT_PROVIDER_MAX_RETRIES;
|
|
27
|
+
const maxRetryDelayMs = spec.connection?.maxRetryDelayMs;
|
|
24
28
|
this.requestDefaults = {
|
|
25
29
|
...(spec.apiKey !== undefined ? { apiKey: spec.apiKey } : {}),
|
|
26
30
|
...spec.connection,
|
|
31
|
+
maxRetries,
|
|
32
|
+
...(this.piModel.api === "mistral-conversations"
|
|
33
|
+
? { fetch: createRetryingFetch({ maxRetries, ...(maxRetryDelayMs !== undefined ? { maxRetryDelayMs } : {}) }) }
|
|
34
|
+
: {}),
|
|
27
35
|
};
|
|
28
36
|
this.id = this.piModel.id;
|
|
29
37
|
this.provider = this.piModel.provider;
|
|
@@ -116,9 +124,6 @@ export class ChatModel {
|
|
|
116
124
|
}
|
|
117
125
|
return { resolved: false, errorMessage, terminal };
|
|
118
126
|
}
|
|
119
|
-
classifyError(err) {
|
|
120
|
-
return classifyError(err);
|
|
121
|
-
}
|
|
122
127
|
errorEvent(text) {
|
|
123
128
|
return { type: "error", reason: "error", error: this.errorMessage(text) };
|
|
124
129
|
}
|
package/dist/llm/errors.d.ts
CHANGED
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
import type { RetryHint } from "./model.ts";
|
|
2
1
|
export declare class ChatProviderError extends Error {
|
|
3
2
|
constructor(message: string);
|
|
4
3
|
}
|
|
@@ -19,7 +18,6 @@ export declare class APIContextOverflowError extends APIStatusError {
|
|
|
19
18
|
export declare class APIEmptyResponseError extends ChatProviderError {
|
|
20
19
|
constructor(message: string);
|
|
21
20
|
}
|
|
22
|
-
export declare function isRetryableGenerateError(error: unknown): boolean;
|
|
23
21
|
export declare function isContextOverflowErrorCode(code: string | null | undefined): boolean;
|
|
24
22
|
/**
|
|
25
23
|
* Message-text-only overflow detection, for the paths where the transport has already reduced
|
|
@@ -29,5 +27,4 @@ export declare function isContextOverflowErrorCode(code: string | null | undefin
|
|
|
29
27
|
export declare function isContextOverflowMessage(message: string): boolean;
|
|
30
28
|
export declare function isContextOverflowStatusError(statusCode: number, message: string): boolean;
|
|
31
29
|
export declare function normalizeAPIStatusError(statusCode: number, message: string, requestId?: string | null): APIStatusError;
|
|
32
|
-
export declare function classifyError(error: unknown): RetryHint;
|
|
33
30
|
//# sourceMappingURL=errors.d.ts.map
|
package/dist/llm/errors.js
CHANGED
|
@@ -38,20 +38,6 @@ export class APIEmptyResponseError extends ChatProviderError {
|
|
|
38
38
|
this.name = "APIEmptyResponseError";
|
|
39
39
|
}
|
|
40
40
|
}
|
|
41
|
-
const RETRYABLE_STATUS_CODES = [429, 500, 502, 503, 504];
|
|
42
|
-
export function isRetryableGenerateError(error) {
|
|
43
|
-
if (error instanceof APIConnectionError || error instanceof APITimeoutError) {
|
|
44
|
-
return true;
|
|
45
|
-
}
|
|
46
|
-
if (error instanceof APIEmptyResponseError) {
|
|
47
|
-
return true;
|
|
48
|
-
}
|
|
49
|
-
if (error instanceof APIStatusError) {
|
|
50
|
-
return RETRYABLE_STATUS_CODES.includes(error.statusCode);
|
|
51
|
-
}
|
|
52
|
-
const status = extractStatusCode(error);
|
|
53
|
-
return status !== undefined && RETRYABLE_STATUS_CODES.includes(status);
|
|
54
|
-
}
|
|
55
41
|
const CONTEXT_OVERFLOW_MESSAGE_PATTERNS = [
|
|
56
42
|
/context[ _-]?length/,
|
|
57
43
|
/(?:context[ _-]?window.*exceed|exceed.*context[ _-]?window)/,
|
|
@@ -85,70 +71,4 @@ export function normalizeAPIStatusError(statusCode, message, requestId) {
|
|
|
85
71
|
}
|
|
86
72
|
return new APIStatusError(statusCode, message, requestId);
|
|
87
73
|
}
|
|
88
|
-
export function classifyError(error) {
|
|
89
|
-
if (error instanceof APIContextOverflowError) {
|
|
90
|
-
return { retryable: false };
|
|
91
|
-
}
|
|
92
|
-
const status = extractStatusCode(error);
|
|
93
|
-
const message = extractMessage(error);
|
|
94
|
-
if (status !== undefined && isContextOverflowStatusError(status, message)) {
|
|
95
|
-
return { retryable: false };
|
|
96
|
-
}
|
|
97
|
-
// No status to gate on (the string path): classify overflow from the message alone, so the
|
|
98
|
-
// retry layer gives up immediately instead of falling through the generic-retryable check.
|
|
99
|
-
if (status === undefined && isContextOverflowMessage(message)) {
|
|
100
|
-
return { retryable: false };
|
|
101
|
-
}
|
|
102
|
-
if (isRetryableGenerateError(error)) {
|
|
103
|
-
const afterMs = parseRetryAfterMs(error);
|
|
104
|
-
return afterMs === undefined ? { retryable: true } : { retryable: true, afterMs };
|
|
105
|
-
}
|
|
106
|
-
return { retryable: false };
|
|
107
|
-
}
|
|
108
|
-
// Generic error-shape extraction (interface adapter for non-class errors).
|
|
109
|
-
function extractStatusCode(error) {
|
|
110
|
-
if (typeof error !== "object" || error === null)
|
|
111
|
-
return undefined;
|
|
112
|
-
const record = error;
|
|
113
|
-
const candidate = record["statusCode"] ?? record["status"];
|
|
114
|
-
return typeof candidate === "number" ? candidate : undefined;
|
|
115
|
-
}
|
|
116
|
-
function extractMessage(error) {
|
|
117
|
-
if (error instanceof Error)
|
|
118
|
-
return error.message;
|
|
119
|
-
if (typeof error === "string")
|
|
120
|
-
return error;
|
|
121
|
-
return String(error);
|
|
122
|
-
}
|
|
123
|
-
function parseRetryAfterMs(error) {
|
|
124
|
-
const raw = extractRetryAfter(error);
|
|
125
|
-
if (raw === undefined)
|
|
126
|
-
return undefined;
|
|
127
|
-
const seconds = Number(raw);
|
|
128
|
-
if (Number.isFinite(seconds))
|
|
129
|
-
return Math.max(0, seconds * 1000);
|
|
130
|
-
const at = Date.parse(raw);
|
|
131
|
-
if (Number.isFinite(at))
|
|
132
|
-
return Math.max(0, at - Date.now());
|
|
133
|
-
return undefined;
|
|
134
|
-
}
|
|
135
|
-
function extractRetryAfter(error) {
|
|
136
|
-
if (typeof error !== "object" || error === null)
|
|
137
|
-
return undefined;
|
|
138
|
-
const record = error;
|
|
139
|
-
const headers = record["headers"];
|
|
140
|
-
if (headers instanceof Headers) {
|
|
141
|
-
return headers.get("retry-after") ?? undefined;
|
|
142
|
-
}
|
|
143
|
-
if (typeof headers === "object" && headers !== null) {
|
|
144
|
-
const bag = headers;
|
|
145
|
-
const value = bag["retry-after"] ?? bag["Retry-After"];
|
|
146
|
-
if (typeof value === "string" || typeof value === "number")
|
|
147
|
-
return String(value);
|
|
148
|
-
}
|
|
149
|
-
const top = record["retryAfter"];
|
|
150
|
-
if (typeof top === "string" || typeof top === "number")
|
|
151
|
-
return String(top);
|
|
152
|
-
return undefined;
|
|
153
|
-
}
|
|
154
74
|
//# sourceMappingURL=errors.js.map
|
package/dist/llm/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
export { streamResult } from "./model.ts";
|
|
2
|
-
export type { LlmRequest, CallOptions, ModelSettings,
|
|
2
|
+
export type { LlmRequest, CallOptions, ModelSettings, ThinkingBudgets, ThinkingLevel, StreamResultOptions, } from "./model.ts";
|
|
3
3
|
export { ChatModel, defineModel, tryGetPiModel } from "./define-model.ts";
|
|
4
4
|
export * from "./provider.ts";
|
|
5
5
|
export type { ModelConnection, ModelSpec } from "./define-model.ts";
|
|
@@ -11,5 +11,5 @@ export { InMemoryCredentialStore, MemoryCredentialStore, FileCredentialStore, }
|
|
|
11
11
|
export type { CredentialStore, Credential, CredentialInfo, AuthInteraction, AuthPrompt, AuthResult, AuthType, OAuthCredential, OAuthCredentials, } from "./auth.ts";
|
|
12
12
|
export { UNKNOWN_CAPABILITY, capabilityFromPiModel, applyDeclaredCapability, } from "./capability.ts";
|
|
13
13
|
export type { ModelCapability } from "./capability.ts";
|
|
14
|
-
export { ChatProviderError, APIConnectionError, APITimeoutError, APIStatusError, APIContextOverflowError, APIEmptyResponseError,
|
|
14
|
+
export { ChatProviderError, APIConnectionError, APITimeoutError, APIStatusError, APIContextOverflowError, APIEmptyResponseError, isContextOverflowStatusError, isContextOverflowErrorCode, isContextOverflowMessage, normalizeAPIStatusError, } from "./errors.ts";
|
|
15
15
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/llm/index.js
CHANGED
|
@@ -5,5 +5,5 @@ export { createModelRuntime, forceRefreshOAuth } from "./runtime.js";
|
|
|
5
5
|
export { streamWithRetry, DEFAULT_MAX_RETRIES_PER_STEP } from "./retry.js";
|
|
6
6
|
export { InMemoryCredentialStore, MemoryCredentialStore, FileCredentialStore, } from "./auth.js";
|
|
7
7
|
export { UNKNOWN_CAPABILITY, capabilityFromPiModel, applyDeclaredCapability, } from "./capability.js";
|
|
8
|
-
export { ChatProviderError, APIConnectionError, APITimeoutError, APIStatusError, APIContextOverflowError, APIEmptyResponseError,
|
|
8
|
+
export { ChatProviderError, APIConnectionError, APITimeoutError, APIStatusError, APIContextOverflowError, APIEmptyResponseError, isContextOverflowStatusError, isContextOverflowErrorCode, isContextOverflowMessage, normalizeAPIStatusError, } from "./errors.js";
|
|
9
9
|
//# sourceMappingURL=index.js.map
|
package/dist/llm/model.d.ts
CHANGED
|
@@ -1,9 +1,5 @@
|
|
|
1
1
|
import type { AssistantMessage, AssistantMessageEvent, AssistantMessageEventStream, Message, ThinkingBudgets, ThinkingLevel, ToolSchema } from "../protocol/index.ts";
|
|
2
2
|
export type { ThinkingBudgets, ThinkingLevel };
|
|
3
|
-
export type RetryHint = {
|
|
4
|
-
readonly retryable: boolean;
|
|
5
|
-
readonly afterMs?: number;
|
|
6
|
-
};
|
|
7
3
|
/**
|
|
8
4
|
* How the model should behave for one request — the knobs that legitimately vary per agent
|
|
9
5
|
* and per turn. Deliberately NOT pi's `SimpleStreamOptions`: connection-tier settings
|
package/dist/llm/retry.d.ts
CHANGED
|
@@ -31,5 +31,10 @@ export interface StreamWithRetryResult {
|
|
|
31
31
|
readonly message: AssistantMessage;
|
|
32
32
|
readonly stopReason: AssistantMessage["stopReason"];
|
|
33
33
|
}
|
|
34
|
+
/**
|
|
35
|
+
* Recovers a response that failed after it had started. A request that never got a response is
|
|
36
|
+
* retried below this, inside the provider call (`ModelConnection.maxRetries`), so a failure
|
|
37
|
+
* without a successful status or any output is final here.
|
|
38
|
+
*/
|
|
34
39
|
export declare function streamWithRetry(input: StreamWithRetryInput): Promise<StreamWithRetryResult>;
|
|
35
40
|
//# sourceMappingURL=retry.d.ts.map
|
package/dist/llm/retry.js
CHANGED
|
@@ -1,8 +1,14 @@
|
|
|
1
|
+
import { isContextOverflowMessage } from "./errors.js";
|
|
1
2
|
import { streamResult } from "./model.js";
|
|
2
3
|
import { logDataPolicy, noopLogger } from "../logging/index.js";
|
|
3
4
|
export const DEFAULT_MAX_RETRIES_PER_STEP = 3;
|
|
4
5
|
const BASE_DELAY_MS = 300;
|
|
5
6
|
const MAX_BACKOFF_MS = 32_000;
|
|
7
|
+
/**
|
|
8
|
+
* Recovers a response that failed after it had started. A request that never got a response is
|
|
9
|
+
* retried below this, inside the provider call (`ModelConnection.maxRetries`), so a failure
|
|
10
|
+
* without a successful status or any output is final here.
|
|
11
|
+
*/
|
|
6
12
|
export async function streamWithRetry(input) {
|
|
7
13
|
const { model, request, call } = input;
|
|
8
14
|
const logger = input.logger ?? noopLogger;
|
|
@@ -15,9 +21,13 @@ export async function streamWithRetry(input) {
|
|
|
15
21
|
logger.log("debug", "llm request", logDataPolicy.dontLogModelData
|
|
16
22
|
? { model: model.id, attempt, mode, messages: request.messages.length, tools: request.tools?.length ?? 0 }
|
|
17
23
|
: { model: model.id, attempt, mode, system: request.system, messages: request.messages, tools: request.tools?.map((t) => t.name), params: request.params });
|
|
24
|
+
let httpStatus;
|
|
25
|
+
const attemptRequest = observeHttpStatus(request, (status) => {
|
|
26
|
+
httpStatus = status;
|
|
27
|
+
});
|
|
18
28
|
const attemptResult = useCompleteFallback
|
|
19
|
-
? await runCompleteAttempt(model,
|
|
20
|
-
: await runStreamAttempt(model,
|
|
29
|
+
? await runCompleteAttempt(model, attemptRequest, call)
|
|
30
|
+
: await runStreamAttempt(model, attemptRequest, call, input.onEvent);
|
|
21
31
|
const result = { message: attemptResult.message, stopReason: attemptResult.message.stopReason };
|
|
22
32
|
if (result.stopReason !== "error") {
|
|
23
33
|
if (attemptResult.mode === "complete")
|
|
@@ -27,10 +37,10 @@ export async function streamWithRetry(input) {
|
|
|
27
37
|
: { model: model.id, attempt, mode: attemptResult.mode, stopReason: result.stopReason, content: result.message.content, usage: result.message.usage });
|
|
28
38
|
return result; // success (stop / toolUse / length / aborted)
|
|
29
39
|
}
|
|
30
|
-
const
|
|
31
|
-
|
|
32
|
-
if (!
|
|
33
|
-
logger.log("error", "llm error", { model: model.id, attempt, mode: attemptResult.mode, retryable
|
|
40
|
+
const retryable = failedAfterResponseStarted(attemptResult.surfaced, httpStatus)
|
|
41
|
+
&& !isContextOverflowMessage(result.message.errorMessage ?? "");
|
|
42
|
+
if (!retryable || attempt >= maxRetries) {
|
|
43
|
+
logger.log("error", "llm error", { model: model.id, attempt, mode: attemptResult.mode, retryable, reason: result.message.errorMessage });
|
|
34
44
|
return result; // give up → environment error as the result
|
|
35
45
|
}
|
|
36
46
|
input.onDropPartial?.(result.message);
|
|
@@ -43,7 +53,7 @@ export async function streamWithRetry(input) {
|
|
|
43
53
|
reason: result.message.errorMessage,
|
|
44
54
|
});
|
|
45
55
|
}
|
|
46
|
-
const delayMs = retryDelayMs(attempt
|
|
56
|
+
const delayMs = retryDelayMs(attempt);
|
|
47
57
|
logger.log("warn", "llm retry", { model: model.id, attempt: attempt + 1, maxAttempts: maxRetries, delayMs, reason: result.message.errorMessage });
|
|
48
58
|
input.onRetrying?.({
|
|
49
59
|
type: "step_retrying",
|
|
@@ -133,9 +143,25 @@ function isSurfacedEvent(event) {
|
|
|
133
143
|
return false;
|
|
134
144
|
}
|
|
135
145
|
}
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
146
|
+
/** Report each HTTP response's status to `observe`, ahead of any `onResponse` already set. */
|
|
147
|
+
function observeHttpStatus(request, observe) {
|
|
148
|
+
const prior = request.providerOptions?.["onResponse"];
|
|
149
|
+
return {
|
|
150
|
+
...request,
|
|
151
|
+
providerOptions: {
|
|
152
|
+
...request.providerOptions,
|
|
153
|
+
onResponse: async (response, ...rest) => {
|
|
154
|
+
observe(response.status);
|
|
155
|
+
await prior?.(response, ...rest);
|
|
156
|
+
},
|
|
157
|
+
},
|
|
158
|
+
};
|
|
159
|
+
}
|
|
160
|
+
/** Output was shown, or the last HTTP response succeeded: either way the failure came later. */
|
|
161
|
+
function failedAfterResponseStarted(surfaced, httpStatus) {
|
|
162
|
+
return surfaced || (httpStatus !== undefined && httpStatus >= 200 && httpStatus < 300);
|
|
163
|
+
}
|
|
164
|
+
function retryDelayMs(attempt) {
|
|
139
165
|
const baseDelay = Math.min(BASE_DELAY_MS * 2 ** attempt, MAX_BACKOFF_MS);
|
|
140
166
|
return Math.round(baseDelay + Math.random() * 0.25 * baseDelay);
|
|
141
167
|
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
export interface RetryingFetchOptions {
|
|
2
|
+
readonly maxRetries: number;
|
|
3
|
+
readonly maxRetryDelayMs?: number;
|
|
4
|
+
}
|
|
5
|
+
/**
|
|
6
|
+
* A `fetch` with pi's provider retry policy, for adapters that call `fetch` directly and so never
|
|
7
|
+
* reach `retryProviderRequest` themselves (`mistral-conversations`, as of pi-ai 1.5.0). Remove it
|
|
8
|
+
* when the adapter retries on its own.
|
|
9
|
+
*
|
|
10
|
+
* pi decides what is retryable and how long to wait. A response it gives up on is returned
|
|
11
|
+
* unread, so the adapter reports the failure exactly as it would have without retries.
|
|
12
|
+
*
|
|
13
|
+
* `init.signal` bounds the whole sequence, backoff included, and the options are fixed when the
|
|
14
|
+
* wrapper is built. The request body must be replayable, which a string is.
|
|
15
|
+
*/
|
|
16
|
+
export declare function createRetryingFetch(options: RetryingFetchOptions): typeof globalThis.fetch;
|
|
17
|
+
//# sourceMappingURL=retrying-fetch.d.ts.map
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import { retryProviderRequest } from "@earendil-works/pi-ai/utils/provider-retry";
|
|
2
|
+
/** The shape `retryProviderRequest` retries on. An undefined status is a connection failure. */
|
|
3
|
+
class AttemptFailure extends Error {
|
|
4
|
+
status;
|
|
5
|
+
headers;
|
|
6
|
+
response;
|
|
7
|
+
constructor(message, response, cause) {
|
|
8
|
+
super(message, { cause });
|
|
9
|
+
this.status = response?.status;
|
|
10
|
+
this.headers = response?.headers;
|
|
11
|
+
this.response = response;
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* A `fetch` with pi's provider retry policy, for adapters that call `fetch` directly and so never
|
|
16
|
+
* reach `retryProviderRequest` themselves (`mistral-conversations`, as of pi-ai 1.5.0). Remove it
|
|
17
|
+
* when the adapter retries on its own.
|
|
18
|
+
*
|
|
19
|
+
* pi decides what is retryable and how long to wait. A response it gives up on is returned
|
|
20
|
+
* unread, so the adapter reports the failure exactly as it would have without retries.
|
|
21
|
+
*
|
|
22
|
+
* `init.signal` bounds the whole sequence, backoff included, and the options are fixed when the
|
|
23
|
+
* wrapper is built. The request body must be replayable, which a string is.
|
|
24
|
+
*/
|
|
25
|
+
export function createRetryingFetch(options) {
|
|
26
|
+
return async (input, init) => {
|
|
27
|
+
let unread;
|
|
28
|
+
const release = async () => {
|
|
29
|
+
const response = unread;
|
|
30
|
+
unread = undefined;
|
|
31
|
+
await response?.body?.cancel().catch(() => undefined);
|
|
32
|
+
};
|
|
33
|
+
try {
|
|
34
|
+
return await retryProviderRequest(async () => {
|
|
35
|
+
await release();
|
|
36
|
+
const response = await send(input, init);
|
|
37
|
+
if (response.ok)
|
|
38
|
+
return response;
|
|
39
|
+
unread = response;
|
|
40
|
+
throw new AttemptFailure(`HTTP ${response.status}`, response);
|
|
41
|
+
}, {
|
|
42
|
+
maxRetries: options.maxRetries,
|
|
43
|
+
...(options.maxRetryDelayMs !== undefined ? { maxRetryDelayMs: options.maxRetryDelayMs } : {}),
|
|
44
|
+
...(init?.signal ? { signal: init.signal } : {}),
|
|
45
|
+
});
|
|
46
|
+
}
|
|
47
|
+
catch (error) {
|
|
48
|
+
if (error instanceof AttemptFailure) {
|
|
49
|
+
if (error.response !== undefined)
|
|
50
|
+
return error.response;
|
|
51
|
+
throw error.cause;
|
|
52
|
+
}
|
|
53
|
+
await release();
|
|
54
|
+
throw error;
|
|
55
|
+
}
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
async function send(input, init) {
|
|
59
|
+
try {
|
|
60
|
+
return await globalThis.fetch(input, init);
|
|
61
|
+
}
|
|
62
|
+
catch (cause) {
|
|
63
|
+
throw new AttemptFailure("connection failed", undefined, cause);
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
//# sourceMappingURL=retrying-fetch.js.map
|