operon-agents-core 0.1.0-alpha.25 → 0.1.0-alpha.27

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.
@@ -1,3 +1,4 @@
1
+ import { completeWithRetry } from "../../llm/retry.js";
1
2
  import { logDataPolicy, noopLogger } from "../../logging/index.js";
2
3
  import { summaryMessage } from "../../loop/context.js";
3
4
  import { systemReminder } from "../injection.js";
@@ -113,7 +114,7 @@ async function summarize(deps, initialCount) {
113
114
  let summaryText = "";
114
115
  let truncatedOrError = false;
115
116
  try {
116
- const message = await deps.model.complete(request, { signal: deps.signal });
117
+ const message = await completeWithRetry(deps.model, request, { signal: deps.signal }, undefined, logger);
117
118
  if (message.stopReason === "error")
118
119
  throw new Error(message.errorMessage ?? "compaction stream error");
119
120
  summaryText = textOf(message);
@@ -1,7 +1,7 @@
1
1
  import { z } from "zod";
2
2
  export declare const ProviderTypeSchema: z.ZodEnum<{
3
- anthropic: "anthropic";
4
3
  openai: "openai";
4
+ anthropic: "anthropic";
5
5
  kimi: "kimi";
6
6
  "google-genai": "google-genai";
7
7
  openai_responses: "openai_responses";
@@ -17,8 +17,8 @@ export declare const ProviderOAuthSchema: z.ZodObject<{
17
17
  }, z.core.$strip>;
18
18
  export declare const ProviderConfigSchema: z.ZodObject<{
19
19
  type: z.ZodEnum<{
20
- anthropic: "anthropic";
21
20
  openai: "openai";
21
+ anthropic: "anthropic";
22
22
  kimi: "kimi";
23
23
  "google-genai": "google-genai";
24
24
  openai_responses: "openai_responses";
@@ -239,8 +239,8 @@ export declare const PluginRefSchema: z.ZodObject<{
239
239
  export declare const AgentFrameworkConfigSchema: z.ZodObject<{
240
240
  providers: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodObject<{
241
241
  type: z.ZodEnum<{
242
- anthropic: "anthropic";
243
242
  openai: "openai";
243
+ anthropic: "anthropic";
244
244
  kimi: "kimi";
245
245
  "google-genai": "google-genai";
246
246
  openai_responses: "openai_responses";
@@ -110,6 +110,12 @@ function normalizeMcpServerKeys(value) {
110
110
  if (typeof value !== "object" || value === null || Array.isArray(value))
111
111
  return value;
112
112
  const out = renameKeys(value, MCP_SNAKE_CASE_KEYS);
113
+ // Hosts and other agents' config formats offer a separate "sse" type; here every URL-based
114
+ // server goes through the one http transport.
115
+ for (const key of ["type", "transport"]) {
116
+ if (out[key] === "sse")
117
+ out[key] = "http";
118
+ }
113
119
  const oauth = out["oauth"];
114
120
  if (typeof oauth === "object" && oauth !== null && !Array.isArray(oauth)) {
115
121
  out["oauth"] = renameKeys(oauth, MCP_OAUTH_SNAKE_CASE_KEYS);
@@ -148,7 +154,8 @@ const McpServerConfigObjectSchema = z.object({
148
154
  }
149
155
  }).transform(({ type, transport, ...rest }) => ({
150
156
  ...rest,
151
- transport: transport ?? type ?? "stdio",
157
+ // A bare `{ url }` can only be a network server; everything else keeps the stdio default.
158
+ transport: transport ?? type ?? (rest.command === undefined && rest.url !== undefined ? "http" : "stdio"),
152
159
  }));
153
160
  export const McpServerConfigSchema = z.preprocess(normalizeMcpServerKeys, McpServerConfigObjectSchema);
154
161
  export const HookDefConfigSchema = z.object({
package/dist/index.d.ts CHANGED
@@ -18,6 +18,6 @@ export { loadMarketplace, parseMarketplace, loadMarketplaceEntryDetails, parseGi
18
18
  export type { Marketplace, MarketplaceEntry, LoadMarketplaceOptions, MarketplaceEntryDetails, } from "./plugins/marketplace.ts";
19
19
  export { PluginManager, pluginsCapability, parseHooksDocument, hookDefsFromConfig, } from "./plugins/index.ts";
20
20
  export type { PluginManagerOptions, SessionStartSkillResolver, PluginSummary, PluginInfo, PluginSource, ParsedPluginHooks, } from "./plugins/index.ts";
21
- export { mcpServersCapability, createMcpServers, McpOAuthService, JsonFileStore, MemoryMcpCredentialStore, McpTransportNotPermittedError } from "./mcp/index.ts";
21
+ export { mcpServersCapability, createMcpServers, assertMcpTransportsPermitted, McpOAuthService, JsonFileStore, MemoryMcpCredentialStore, McpTransportNotPermittedError } from "./mcp/index.ts";
22
22
  export type { McpServersCapabilityOptions, McpOAuthServiceOptions, McpCredentialStore, McpTransportKind, McpServersHandle, McpServerView, McpCredential, McpCredentialProvider, McpCredentialRequest } from "./mcp/index.ts";
23
23
  //# sourceMappingURL=index.d.ts.map
package/dist/index.js CHANGED
@@ -19,5 +19,5 @@ export { loadMarketplace, parseMarketplace, loadMarketplaceEntryDetails, parseGi
19
19
  export { PluginManager, pluginsCapability, parseHooksDocument, hookDefsFromConfig, } from "./plugins/index.js";
20
20
  // The per-workspace MCP capability, exposed so `defaultCapabilities` can build it from
21
21
  // workspace + plugin servers (it lives under the ./mcp subtree, not the main capabilities barrel).
22
- export { mcpServersCapability, createMcpServers, McpOAuthService, JsonFileStore, MemoryMcpCredentialStore, McpTransportNotPermittedError } from "./mcp/index.js";
22
+ export { mcpServersCapability, createMcpServers, assertMcpTransportsPermitted, McpOAuthService, JsonFileStore, MemoryMcpCredentialStore, McpTransportNotPermittedError } from "./mcp/index.js";
23
23
  //# sourceMappingURL=index.js.map
@@ -1,6 +1,7 @@
1
1
  import type { Api, AssistantMessage, AssistantMessageEventStream, Model, Provider, ProviderHeaders, Transport } from "../protocol/index.ts";
2
2
  import { type ModelRuntime } from "./runtime.ts";
3
3
  import type { CallOptions, LlmRequest } from "./model.ts";
4
+ import { type RequestRetryPolicy } from "./request-retry.ts";
4
5
  /**
5
6
  * How to reach the endpoint, as opposed to how the model should think. Fixed when the model is
6
7
  * built, applied to every request it makes.
@@ -25,12 +26,15 @@ export interface ModelConnection {
25
26
  readonly timeoutMs?: number;
26
27
  /**
27
28
  * 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.
29
+ * connection failures. Exponential backoff, honoring `Retry-After` and rate-limit reset
30
+ * headers. Defaults to 10; 0 turns them off. pi's own retries are always off, so
31
+ * `streamWithRetry` can report each wait.
31
32
  */
32
33
  readonly maxRetries?: number;
33
- /** Cap on honoring a server-requested retry delay. pi defaults to 60s; 0 disables the cap. */
34
+ /**
35
+ * The longest single retry wait. Defaults to 5 minutes; 0 removes the cap. A server asking for
36
+ * longer fails the request at once.
37
+ */
34
38
  readonly maxRetryDelayMs?: number;
35
39
  /**
36
40
  * Wire transport. Today only `openai-codex-responses` (the ChatGPT-subscription backend)
@@ -94,6 +98,8 @@ export declare class ChatModel {
94
98
  /** Build-time settings (`apiKey` + `connection`) flattened once into pi's option shape.
95
99
  * Every request starts from these; `params` and `providerOptions` layer on top. */
96
100
  private readonly requestDefaults;
101
+ /** Read by `streamWithRetry` and `completeWithRetry`, which own every retry. */
102
+ readonly requestRetry: RequestRetryPolicy;
97
103
  constructor(spec: ModelSpec);
98
104
  stream(req: LlmRequest, call?: CallOptions): AssistantMessageEventStream;
99
105
  complete(req: LlmRequest, call?: CallOptions): Promise<AssistantMessage>;
@@ -1,9 +1,19 @@
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 { 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;
4
+ import { DEFAULT_REQUEST_RETRY_POLICY } from "./request-retry.js";
5
+ /** Node's longest timer, which is what "no cap" on a retry wait amounts to. */
6
+ const MAX_TIMER_MS = 2 ** 31 - 1;
7
+ /** pi's adapters that send through `options.fetch`; the Google ones reject it outright. */
8
+ const APIS_WITH_CUSTOM_FETCH = new Set([
9
+ "anthropic-messages",
10
+ "azure-openai-responses",
11
+ "mistral-conversations",
12
+ "openai-codex-responses",
13
+ "openai-completions",
14
+ "openai-responses",
15
+ "pi-messages",
16
+ ]);
7
17
  export class ChatModel {
8
18
  id;
9
19
  provider;
@@ -20,18 +30,21 @@ export class ChatModel {
20
30
  /** Build-time settings (`apiKey` + `connection`) flattened once into pi's option shape.
21
31
  * Every request starts from these; `params` and `providerOptions` layer on top. */
22
32
  requestDefaults;
33
+ /** Read by `streamWithRetry` and `completeWithRetry`, which own every retry. */
34
+ requestRetry;
23
35
  constructor(spec) {
24
36
  this.runtime = spec.runtime ?? createModelRuntime();
25
37
  this.piModel = withAnthropicToolChanges(resolvePiModel(spec, this.runtime));
26
- const maxRetries = spec.connection?.maxRetries ?? DEFAULT_PROVIDER_MAX_RETRIES;
27
- const maxRetryDelayMs = spec.connection?.maxRetryDelayMs;
38
+ const { maxRetries, maxRetryDelayMs, ...transport } = spec.connection ?? {};
39
+ this.requestRetry = {
40
+ ...DEFAULT_REQUEST_RETRY_POLICY,
41
+ ...(maxRetries !== undefined ? { maxRetries } : {}),
42
+ ...(maxRetryDelayMs !== undefined ? { maxDelayMs: maxRetryDelayMs === 0 ? MAX_TIMER_MS : maxRetryDelayMs } : {}),
43
+ };
28
44
  this.requestDefaults = {
29
45
  ...(spec.apiKey !== undefined ? { apiKey: spec.apiKey } : {}),
30
- ...spec.connection,
31
- maxRetries,
32
- ...(this.piModel.api === "mistral-conversations"
33
- ? { fetch: createRetryingFetch({ maxRetries, ...(maxRetryDelayMs !== undefined ? { maxRetryDelayMs } : {}) }) }
34
- : {}),
46
+ ...transport,
47
+ maxRetries: 0,
35
48
  };
36
49
  this.id = this.piModel.id;
37
50
  this.provider = this.piModel.provider;
@@ -70,7 +83,10 @@ export class ChatModel {
70
83
  }
71
84
  }
72
85
  options(req, call) {
73
- return toOptions(req, call, this.requestDefaults);
86
+ const options = toOptions(req, call, this.requestDefaults);
87
+ if (call?.onHttpExchange === undefined || !APIS_WITH_CUSTOM_FETCH.has(this.api))
88
+ return options;
89
+ return { ...options, fetch: observingFetch(options.fetch, call.onHttpExchange) };
74
90
  }
75
91
  async streamWithAuthRetry(req, call, ctx, out) {
76
92
  const first = await this.runAttempt(req, call, ctx, out);
@@ -141,6 +157,21 @@ export class ChatModel {
141
157
  };
142
158
  }
143
159
  }
160
+ /** Reports each exchange and changes nothing about it. */
161
+ function observingFetch(inner, observe) {
162
+ return async (input, init) => {
163
+ let response;
164
+ try {
165
+ response = await (inner ?? globalThis.fetch)(input, init);
166
+ }
167
+ catch (error) {
168
+ observe({ headers: {} });
169
+ throw error;
170
+ }
171
+ observe({ status: response.status, headers: Object.fromEntries(response.headers) });
172
+ return response;
173
+ };
174
+ }
144
175
  function messageOf(error) {
145
176
  return error instanceof Error ? error.message : String(error);
146
177
  }
@@ -1,11 +1,13 @@
1
1
  export { streamResult } from "./model.ts";
2
- export type { LlmRequest, CallOptions, ModelSettings, ThinkingBudgets, ThinkingLevel, StreamResultOptions, } from "./model.ts";
2
+ export type { LlmRequest, CallOptions, HttpExchange, 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";
6
6
  export { createModelRuntime, forceRefreshOAuth } from "./runtime.ts";
7
7
  export type { ModelRuntime, CreateModelRuntimeOptions } from "./runtime.ts";
8
- export { streamWithRetry, DEFAULT_MAX_RETRIES_PER_STEP } from "./retry.ts";
8
+ export { completeWithRetry, streamWithRetry, DEFAULT_MAX_RETRIES_PER_STEP } from "./retry.ts";
9
+ export { DEFAULT_REQUEST_RETRY_POLICY } from "./request-retry.ts";
10
+ export type { RequestRetryPolicy } from "./request-retry.ts";
9
11
  export type { StreamWithRetryInput, StreamWithRetryResult, StepRetryingEvent, StepResetEvent } from "./retry.ts";
10
12
  export { InMemoryCredentialStore, MemoryCredentialStore, FileCredentialStore, } from "./auth.ts";
11
13
  export type { CredentialStore, Credential, CredentialInfo, AuthInteraction, AuthPrompt, AuthResult, AuthType, OAuthCredential, OAuthCredentials, } from "./auth.ts";
package/dist/llm/index.js CHANGED
@@ -2,7 +2,8 @@ export { streamResult } from "./model.js";
2
2
  export { ChatModel, defineModel, tryGetPiModel } from "./define-model.js";
3
3
  export * from "./provider.js";
4
4
  export { createModelRuntime, forceRefreshOAuth } from "./runtime.js";
5
- export { streamWithRetry, DEFAULT_MAX_RETRIES_PER_STEP } from "./retry.js";
5
+ export { completeWithRetry, streamWithRetry, DEFAULT_MAX_RETRIES_PER_STEP } from "./retry.js";
6
+ export { DEFAULT_REQUEST_RETRY_POLICY } from "./request-retry.js";
6
7
  export { InMemoryCredentialStore, MemoryCredentialStore, FileCredentialStore, } from "./auth.js";
7
8
  export { UNKNOWN_CAPABILITY, capabilityFromPiModel, applyDeclaredCapability, } from "./capability.js";
8
9
  export { ChatProviderError, APIConnectionError, APITimeoutError, APIStatusError, APIContextOverflowError, APIEmptyResponseError, isContextOverflowStatusError, isContextOverflowErrorCode, isContextOverflowMessage, normalizeAPIStatusError, } from "./errors.js";
@@ -30,9 +30,20 @@ export interface LlmRequest {
30
30
  readonly params?: ModelSettings;
31
31
  readonly providerOptions?: Readonly<Record<string, unknown>>;
32
32
  }
33
+ /** What came back from one HTTP request. A connection failure has no `status`. */
34
+ export interface HttpExchange {
35
+ readonly status?: number;
36
+ /** Lower-cased names. */
37
+ readonly headers: Readonly<Record<string, string>>;
38
+ }
33
39
  export interface CallOptions {
34
40
  readonly signal?: AbortSignal;
35
41
  readonly timeoutMs?: number;
42
+ /**
43
+ * Called after every HTTP request, failed ones included, unlike pi's `onResponse`. Not called
44
+ * for APIs that accept no custom `fetch`: Google, Vertex and Bedrock.
45
+ */
46
+ readonly onHttpExchange?: (exchange: HttpExchange) => void;
36
47
  }
37
48
  export interface StreamResultOptions {
38
49
  readonly onEvent?: (event: AssistantMessageEvent) => void;
@@ -0,0 +1,18 @@
1
+ import type { AssistantMessage } from "../protocol/index.ts";
2
+ import type { HttpExchange } from "./model.ts";
3
+ /** How a request that never got a response is retried. */
4
+ export interface RequestRetryPolicy {
5
+ readonly maxRetries: number;
6
+ readonly baseDelayMs: number;
7
+ /** The longest single wait. A server asking for more fails the request instead. */
8
+ readonly maxDelayMs: number;
9
+ }
10
+ /**
11
+ * 1s, 2s, 4s … doubling up to 5 minutes, ten retries in all. A transient failure clears within
12
+ * the first few seconds, and six retries already span the one-minute window most token rate
13
+ * limits use.
14
+ */
15
+ export declare const DEFAULT_REQUEST_RETRY_POLICY: RequestRetryPolicy;
16
+ /** The wait before retrying a failed request, or undefined when it should not be retried. */
17
+ export declare function requestRetryDelayMs(message: AssistantMessage, exchange: HttpExchange | undefined, retries: number, policy: RequestRetryPolicy): number | undefined;
18
+ //# sourceMappingURL=request-retry.d.ts.map
@@ -0,0 +1,93 @@
1
+ import { isRetryableAssistantError } from "@earendil-works/pi-ai/utils/retry";
2
+ /**
3
+ * 1s, 2s, 4s … doubling up to 5 minutes, ten retries in all. A transient failure clears within
4
+ * the first few seconds, and six retries already span the one-minute window most token rate
5
+ * limits use.
6
+ */
7
+ export const DEFAULT_REQUEST_RETRY_POLICY = {
8
+ maxRetries: 10,
9
+ baseDelayMs: 1_000,
10
+ maxDelayMs: 300_000,
11
+ };
12
+ const SERVER_DELAY_MAX_JITTER_MS = 1_000;
13
+ /** The wait before retrying a failed request, or undefined when it should not be retried. */
14
+ export function requestRetryDelayMs(message, exchange, retries, policy) {
15
+ if (retries >= policy.maxRetries || !isRetryableRequestFailure(message, exchange))
16
+ return undefined;
17
+ const serverDelayMs = exchange === undefined ? undefined : serverRequestedDelayMs(exchange);
18
+ if (serverDelayMs !== undefined) {
19
+ if (serverDelayMs > policy.maxDelayMs)
20
+ return undefined;
21
+ return Math.min(serverDelayMs + Math.random() * SERVER_DELAY_MAX_JITTER_MS, policy.maxDelayMs);
22
+ }
23
+ const backoffMs = Math.min(policy.baseDelayMs * 2 ** retries, policy.maxDelayMs);
24
+ return Math.round(backoffMs * (1 - Math.random() * 0.25));
25
+ }
26
+ function isRetryableRequestFailure(message, exchange) {
27
+ if (exchange !== undefined && exchange.status === undefined)
28
+ return true; // connection failure
29
+ const shouldRetry = exchange?.headers["x-should-retry"];
30
+ if (shouldRetry === "true")
31
+ return true;
32
+ if (shouldRetry === "false")
33
+ return false;
34
+ const status = exchange?.status ?? bedrockFailureStatus(message);
35
+ // Google exposes neither responses nor a status, so pi's message classifier decides there.
36
+ if (status === undefined)
37
+ return isRetryableAssistantError(message);
38
+ // A 429 also reports exhausted quota, which waiting cannot fix. Only the body tells them apart.
39
+ if (status === 429)
40
+ return isRetryableAssistantError(message);
41
+ return status === 408 || status === 409 || status >= 500;
42
+ }
43
+ function bedrockFailureStatus(message) {
44
+ const status = message.diagnostics?.find((d) => d.type === "bedrock_response_failure")?.details?.["status"];
45
+ return typeof status === "number" ? status : undefined;
46
+ }
47
+ function serverRequestedDelayMs(exchange) {
48
+ return retryAfterMs(exchange.headers) ?? (exchange.status === 429 ? rateLimitResetMs(exchange.headers) : undefined);
49
+ }
50
+ function retryAfterMs(headers) {
51
+ const millis = positive(Number.parseFloat(headers["retry-after-ms"] ?? ""));
52
+ if (millis !== undefined)
53
+ return millis;
54
+ const value = headers["retry-after"];
55
+ if (value === undefined)
56
+ return undefined;
57
+ const seconds = Number(value);
58
+ return positive(Number.isNaN(seconds) ? Date.parse(value) - Date.now() : seconds * 1_000);
59
+ }
60
+ const RATE_LIMIT_RESET_HEADER = /^(?:x-ratelimit-reset-(?<openai>.+)|anthropic-ratelimit-(?<anthropic>.+)-reset)$/;
61
+ /** When the exhausted limits reset. A limit with budget left is not what rejected the request. */
62
+ function rateLimitResetMs(headers) {
63
+ let latest;
64
+ for (const [name, value] of Object.entries(headers)) {
65
+ const groups = RATE_LIMIT_RESET_HEADER.exec(name)?.groups;
66
+ if (groups === undefined)
67
+ continue;
68
+ const remaining = groups["openai"] !== undefined
69
+ ? headers[`x-ratelimit-remaining-${groups["openai"]}`]
70
+ : headers[`anthropic-ratelimit-${groups["anthropic"]}-remaining`];
71
+ if (remaining !== "0")
72
+ continue;
73
+ const resetMs = groups["openai"] !== undefined ? durationMs(value) : positive(Date.parse(value) - Date.now());
74
+ if (resetMs !== undefined && (latest === undefined || resetMs > latest))
75
+ latest = resetMs;
76
+ }
77
+ return latest;
78
+ }
79
+ const DURATION_UNIT_MS = { h: 3_600_000, m: 60_000, s: 1_000, ms: 1 };
80
+ /** OpenAI's reset format: `37s`, `6m0s`, `1h2m3.5s`, `250ms`. */
81
+ function durationMs(value) {
82
+ if (!/^(?:\d+(?:\.\d+)?(?:ms|h|m|s))+$/.test(value))
83
+ return undefined;
84
+ let total = 0;
85
+ for (const [, amount, unit] of value.matchAll(/(\d+(?:\.\d+)?)(ms|h|m|s)/g)) {
86
+ total += Number(amount) * DURATION_UNIT_MS[unit];
87
+ }
88
+ return positive(total);
89
+ }
90
+ function positive(ms) {
91
+ return Number.isFinite(ms) && ms > 0 ? ms : undefined;
92
+ }
93
+ //# sourceMappingURL=request-retry.js.map
@@ -1,5 +1,6 @@
1
1
  import type { ChatModel } from "./define-model.ts";
2
2
  import type { CallOptions, LlmRequest } from "./model.ts";
3
+ import { type RequestRetryPolicy } from "./request-retry.ts";
3
4
  import type { AssistantMessage, AssistantMessageEvent } from "../protocol/index.ts";
4
5
  import { type Logger } from "../logging/index.ts";
5
6
  export declare const DEFAULT_MAX_RETRIES_PER_STEP = 3;
@@ -32,9 +33,17 @@ export interface StreamWithRetryResult {
32
33
  readonly stopReason: AssistantMessage["stopReason"];
33
34
  }
34
35
  /**
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.
36
+ * Retries a failed step, the only place besides `completeWithRetry` that does: pi's retries are
37
+ * off so that every wait reaches `onRetrying`.
38
+ *
39
+ * The two kinds of failure have separate budgets. A request that never got a response costs
40
+ * nothing to resend and may need minutes to clear (`ModelConnection.maxRetries`). A response that
41
+ * failed after it started has been paid for, so it gets the few retries in `maxRetries`.
38
42
  */
39
43
  export declare function streamWithRetry(input: StreamWithRetryInput): Promise<StreamWithRetryResult>;
44
+ /**
45
+ * `model.complete` with the request retries a step gets, for callers outside the turn loop.
46
+ * `policy` overrides the model's, for a caller that cannot wait minutes.
47
+ */
48
+ export declare function completeWithRetry(model: ChatModel, request: LlmRequest, call?: CallOptions, policy?: Partial<RequestRetryPolicy>, logger?: Logger): Promise<AssistantMessage>;
40
49
  //# sourceMappingURL=retry.d.ts.map
package/dist/llm/retry.js CHANGED
@@ -1,33 +1,42 @@
1
1
  import { isContextOverflowMessage } from "./errors.js";
2
2
  import { streamResult } from "./model.js";
3
+ import { DEFAULT_REQUEST_RETRY_POLICY, requestRetryDelayMs } from "./request-retry.js";
3
4
  import { logDataPolicy, noopLogger } from "../logging/index.js";
4
5
  export const DEFAULT_MAX_RETRIES_PER_STEP = 3;
5
6
  const BASE_DELAY_MS = 300;
6
7
  const MAX_BACKOFF_MS = 32_000;
7
8
  /**
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.
9
+ * Retries a failed step, the only place besides `completeWithRetry` that does: pi's retries are
10
+ * off so that every wait reaches `onRetrying`.
11
+ *
12
+ * The two kinds of failure have separate budgets. A request that never got a response costs
13
+ * nothing to resend and may need minutes to clear (`ModelConnection.maxRetries`). A response that
14
+ * failed after it started has been paid for, so it gets the few retries in `maxRetries`.
11
15
  */
12
16
  export async function streamWithRetry(input) {
13
17
  const { model, request, call } = input;
14
18
  const logger = input.logger ?? noopLogger;
15
19
  const maxRetries = input.maxRetries ?? DEFAULT_MAX_RETRIES_PER_STEP;
16
20
  const signal = call?.signal;
21
+ const requestPolicy = requestPolicyOf(model);
17
22
  let useCompleteFallback = false;
23
+ let responseRetries = 0;
24
+ let requestRetries = 0;
18
25
  for (let attempt = 0;; attempt++) {
19
26
  signal?.throwIfAborted();
20
27
  const mode = useCompleteFallback ? "complete" : "stream";
21
28
  logger.log("debug", "llm request", logDataPolicy.dontLogModelData
22
29
  ? { model: model.id, attempt, mode, messages: request.messages.length, tools: request.tools?.length ?? 0 }
23
30
  : { 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
- });
31
+ let exchange;
32
+ const observe = (seen) => {
33
+ exchange = seen;
34
+ };
35
+ const attemptRequest = observeResponses(request, observe);
36
+ const attemptCall = { ...call, onHttpExchange: observe };
28
37
  const attemptResult = useCompleteFallback
29
- ? await runCompleteAttempt(model, attemptRequest, call)
30
- : await runStreamAttempt(model, attemptRequest, call, input.onEvent);
38
+ ? await runCompleteAttempt(model, attemptRequest, attemptCall)
39
+ : await runStreamAttempt(model, attemptRequest, attemptCall, input.onEvent);
31
40
  const result = { message: attemptResult.message, stopReason: attemptResult.message.stopReason };
32
41
  if (result.stopReason !== "error") {
33
42
  if (attemptResult.mode === "complete")
@@ -37,10 +46,24 @@ export async function streamWithRetry(input) {
37
46
  : { model: model.id, attempt, mode: attemptResult.mode, stopReason: result.stopReason, content: result.message.content, usage: result.message.usage });
38
47
  return result; // success (stop / toolUse / length / aborted)
39
48
  }
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 });
49
+ let retry;
50
+ if (!isContextOverflowMessage(result.message.errorMessage ?? "")) {
51
+ if (failedAfterResponseStarted(attemptResult.surfaced, exchange?.status)) {
52
+ if (responseRetries < maxRetries) {
53
+ retry = { attempt: responseRetries + 1, maxAttempts: maxRetries, delayMs: retryDelayMs(responseRetries) };
54
+ responseRetries++;
55
+ }
56
+ }
57
+ else {
58
+ const delayMs = requestRetryDelayMs(result.message, exchange, requestRetries, requestPolicy);
59
+ if (delayMs !== undefined) {
60
+ retry = { attempt: requestRetries + 1, maxAttempts: requestPolicy.maxRetries, delayMs };
61
+ requestRetries++;
62
+ }
63
+ }
64
+ }
65
+ if (retry === undefined) {
66
+ logger.log("error", "llm error", { model: model.id, attempt, mode: attemptResult.mode, reason: result.message.errorMessage });
44
67
  return result; // give up → environment error as the result
45
68
  }
46
69
  input.onDropPartial?.(result.message);
@@ -53,18 +76,33 @@ export async function streamWithRetry(input) {
53
76
  reason: result.message.errorMessage,
54
77
  });
55
78
  }
56
- const delayMs = retryDelayMs(attempt);
57
- logger.log("warn", "llm retry", { model: model.id, attempt: attempt + 1, maxAttempts: maxRetries, delayMs, reason: result.message.errorMessage });
58
- input.onRetrying?.({
59
- type: "step_retrying",
60
- attempt: attempt + 1,
61
- maxAttempts: maxRetries,
62
- delayMs,
63
- reason: result.message.errorMessage,
64
- });
65
- await abortableSleep(delayMs, signal);
79
+ logger.log("warn", "llm retry", { model: model.id, ...retry, reason: result.message.errorMessage });
80
+ input.onRetrying?.({ type: "step_retrying", ...retry, reason: result.message.errorMessage });
81
+ await abortableSleep(retry.delayMs, signal);
82
+ }
83
+ }
84
+ /**
85
+ * `model.complete` with the request retries a step gets, for callers outside the turn loop.
86
+ * `policy` overrides the model's, for a caller that cannot wait minutes.
87
+ */
88
+ export async function completeWithRetry(model, request, call, policy, logger = noopLogger) {
89
+ const resolved = { ...requestPolicyOf(model), ...policy };
90
+ for (let retries = 0;; retries++) {
91
+ let exchange;
92
+ const message = await model.complete(request, { ...call, onHttpExchange: (seen) => { exchange = seen; } });
93
+ if (message.stopReason !== "error" || isContextOverflowMessage(message.errorMessage ?? ""))
94
+ return message;
95
+ const delayMs = requestRetryDelayMs(message, exchange, retries, resolved);
96
+ if (delayMs === undefined)
97
+ return message;
98
+ logger.log("warn", "llm retry", { model: model.id, attempt: retries + 1, maxAttempts: resolved.maxRetries, delayMs, reason: message.errorMessage });
99
+ await abortableSleep(delayMs, call?.signal);
66
100
  }
67
101
  }
102
+ /** Test doubles cast to `ChatModel` carry no policy. */
103
+ function requestPolicyOf(model) {
104
+ return model.requestRetry ?? DEFAULT_REQUEST_RETRY_POLICY;
105
+ }
68
106
  async function runStreamAttempt(model, request, call, onEvent) {
69
107
  let surfaced = false;
70
108
  const message = await streamResult(model.stream(request, call), {
@@ -143,15 +181,15 @@ function isSurfacedEvent(event) {
143
181
  return false;
144
182
  }
145
183
  }
146
- /** Report each HTTP response's status to `observe`, ahead of any `onResponse` already set. */
147
- function observeHttpStatus(request, observe) {
184
+ /** Report each response pi surfaces to `observe`, ahead of any `onResponse` already set. */
185
+ function observeResponses(request, observe) {
148
186
  const prior = request.providerOptions?.["onResponse"];
149
187
  return {
150
188
  ...request,
151
189
  providerOptions: {
152
190
  ...request.providerOptions,
153
191
  onResponse: async (response, ...rest) => {
154
- observe(response.status);
192
+ observe(response);
155
193
  await prior?.(response, ...rest);
156
194
  },
157
195
  },
@@ -8,7 +8,7 @@ export { convertMcpContentBlock, mcpResultToContent, MCP_MAX_OUTPUT_CHARS, MCP_M
8
8
  export { mcpToolProvider, wrapMcpTool } from "./provider.ts";
9
9
  export { mcpCapability } from "./capability.ts";
10
10
  export type { MCPCapabilityOptions } from "./capability.ts";
11
- export { serverFromConfig, mcpOAuthSettings, mcpServersCapability, createMcpServers, DEFAULT_RECONNECT_POLICY, McpTransportNotPermittedError } from "./manager.ts";
11
+ export { serverFromConfig, mcpOAuthSettings, mcpServersCapability, createMcpServers, assertMcpTransportsPermitted, DEFAULT_RECONNECT_POLICY, McpTransportNotPermittedError } from "./manager.ts";
12
12
  export type { McpCredential, McpCredentialProvider, McpCredentialRequest } from "./credentials.ts";
13
13
  export type { McpServerStatus, McpTransportKind, McpServerView, McpServersHandle, McpServersCapabilityOptions, ServerFromConfigOptions, McpTransportFactory, McpStatusListener, ReconnectPolicy, KeepAlivePolicy, McpTimer, } from "./manager.ts";
14
14
  export { createMcpAuthTool, MCP_OAUTH_AUTHORIZATION_URL_UPDATE } from "./auth-tool.ts";
package/dist/mcp/index.js CHANGED
@@ -4,7 +4,7 @@ export { qualifyMcpToolName, sanitizeMcpNamePart, isMcpToolName } from "./tool-n
4
4
  export { convertMcpContentBlock, mcpResultToContent, MCP_MAX_OUTPUT_CHARS, MCP_MAX_IMAGE_PART_BYTES } from "./output.js";
5
5
  export { mcpToolProvider, wrapMcpTool } from "./provider.js";
6
6
  export { mcpCapability } from "./capability.js";
7
- export { serverFromConfig, mcpOAuthSettings, mcpServersCapability, createMcpServers, DEFAULT_RECONNECT_POLICY, McpTransportNotPermittedError } from "./manager.js";
7
+ export { serverFromConfig, mcpOAuthSettings, mcpServersCapability, createMcpServers, assertMcpTransportsPermitted, DEFAULT_RECONNECT_POLICY, McpTransportNotPermittedError } from "./manager.js";
8
8
  export { createMcpAuthTool, MCP_OAUTH_AUTHORIZATION_URL_UPDATE } from "./auth-tool.js";
9
9
  export { MockMCPTransport } from "./mock-transport.js";
10
10
  export { mcpStdioTransport, mcpStreamableHttpTransport, mergeStdioEnv, isTerminalTransportError, buildMcpHttpHeaders, } from "./sdk-transport.js";
@@ -3,7 +3,7 @@ import type { MCPTool, MCPTransport } from "./types.ts";
3
3
  import type { McpOAuthClientSettings, McpOAuthService } from "./oauth/index.ts";
4
4
  import type { Capability, ToolProvider } from "../index.ts";
5
5
  import type { EventSink } from "../events/index.ts";
6
- import type { McpServerConfig } from "../config/schema.ts";
6
+ import { type McpServerConfig } from "../config/schema.ts";
7
7
  import type { McpCredential, McpCredentialProvider } from "./credentials.ts";
8
8
  export type McpServerStatus = "pending" | "connected" | "failed" | "disabled" | "needs-auth";
9
9
  /** How a server is reached. `stdio` is a CHILD PROCESS of the host; `http` is a network call. */
@@ -70,7 +70,7 @@ export interface ServerFromConfigOptions {
70
70
  /** A provider's answer for this connect. Takes the place of the OAuth service. */
71
71
  readonly credential?: McpCredential;
72
72
  }
73
- export declare function serverFromConfig(name: string, config: McpServerConfig, opts?: ServerFromConfigOptions): TransportMCPServer;
73
+ export declare function serverFromConfig(name: string, rawConfig: McpServerConfig, opts?: ServerFromConfigOptions): TransportMCPServer;
74
74
  /** The OAuth client/scopes a server config pins (Codex `.mcp.json` `oauth` / `scopes`). */
75
75
  export declare function mcpOAuthSettings(config: McpServerConfig): McpOAuthClientSettings;
76
76
  export interface McpServersCapabilityOptions {
@@ -117,6 +117,14 @@ export interface McpServersHandle {
117
117
  connect(ctx: McpConnectContext): Promise<void>;
118
118
  shutdown(): Promise<void>;
119
119
  }
120
+ /**
121
+ * Refuse, up front, any server this host does not offer a transport for.
122
+ *
123
+ * A server switched off in configuration is none of this rule's business: `enabled: false` is
124
+ * how one configuration file serves both a laptop and a server, and rejecting it would take
125
+ * that away for no gain — a disabled server spawns nothing.
126
+ */
127
+ export declare function assertMcpTransportsPermitted(configs: Record<string, McpServerConfig>, allowed: readonly McpTransportKind[] | undefined): void;
120
128
  /**
121
129
  * The controller set behind a group of configured servers — buildable on its own so a HARNESS
122
130
  * can hold one set of connections for every session it serves (`HarnessParts.mcpServers`), or a session can
@@ -3,6 +3,7 @@ import { mcpStdioTransport, mcpStreamableHttpTransport } from "./sdk-transport.j
3
3
  import { mcpToolProvider } from "./provider.js";
4
4
  import { qualifyMcpToolName } from "./tool-naming.js";
5
5
  import { createMcpAuthTool } from "./auth-tool.js";
6
+ import { McpServerConfigSchema } from "../config/schema.js";
6
7
  /**
7
8
  * Raised when a configured server asks for a transport its host does not offer.
8
9
  *
@@ -61,7 +62,32 @@ const REAL_TIMER = {
61
62
  clearTimeout: (handle) => clearTimeout(handle),
62
63
  };
63
64
  const DEFAULT_CACHE_TOOLS = true;
64
- export function serverFromConfig(name, config, opts = {}) {
65
+ /**
66
+ * Apply the config schema to one server entry.
67
+ *
68
+ * The type says `McpServerConfig`, but hosts pass JSON from their own settings straight through
69
+ * (`{ command, args }`, `{ type: "http", url }`), so `transport` cannot be assumed to be set here.
70
+ * Parsing an already-parsed config changes nothing. An invalid entry comes back with `error` and
71
+ * a placeholder config, so it can fail alone instead of taking its siblings down.
72
+ */
73
+ function normalizeServerConfig(name, raw) {
74
+ const parsed = McpServerConfigSchema.safeParse(raw);
75
+ if (parsed.success)
76
+ return { config: parsed.data };
77
+ const issues = parsed.error.issues.map((issue) => (issue.path.length > 0 ? `${issue.path.join(".")}: ${issue.message}` : issue.message));
78
+ const entry = (typeof raw === "object" && raw !== null ? raw : {});
79
+ return {
80
+ config: {
81
+ transport: entry["command"] === undefined && entry["url"] !== undefined ? "http" : "stdio",
82
+ ...(entry["enabled"] === false ? { enabled: false } : {}),
83
+ },
84
+ error: `MCP server "${name}" has an invalid configuration: ${issues.join("; ")}`,
85
+ };
86
+ }
87
+ export function serverFromConfig(name, rawConfig, opts = {}) {
88
+ const { config, error } = normalizeServerConfig(name, rawConfig);
89
+ if (error !== undefined)
90
+ throw new Error(error);
65
91
  const transport = opts.transport ?? transportFromConfig(name, config, opts.oauthService, opts.credential);
66
92
  const filter = staticFilterFromConfig(config);
67
93
  return new TransportMCPServer({
@@ -145,6 +171,7 @@ function isUnauthorizedLikeError(error) {
145
171
  class McpServerController {
146
172
  name;
147
173
  config;
174
+ configError;
148
175
  oauthService;
149
176
  credentials;
150
177
  cacheToolsList;
@@ -165,6 +192,7 @@ class McpServerController {
165
192
  constructor(opts) {
166
193
  this.name = opts.name;
167
194
  this.config = opts.config;
195
+ this.configError = opts.configError;
168
196
  this.oauthService = opts.oauthService;
169
197
  this.credentials = opts.credentials;
170
198
  this.cacheToolsList = opts.cacheToolsList;
@@ -211,6 +239,11 @@ class McpServerController {
211
239
  return { serverName: this.name, url: this.config.url, sessionId: this.session?.sessionId ?? "" };
212
240
  }
213
241
  async attempt(retriedAuth = false) {
242
+ if (this.configError !== undefined) {
243
+ this.setStatus("failed", this.configError);
244
+ this.emitWarning(this.configError);
245
+ return this._status;
246
+ }
214
247
  // Attempts can overlap: a manual reconnect() can fire while an in-flight attempt is still
215
248
  // awaiting connect(). Every mutation of the shared `this.server` slot is therefore guarded
216
249
  // by identity — an attempt only ever publishes/retracts the server IT created, never a
@@ -459,11 +492,13 @@ function keepAliveOptions(config, defaults) {
459
492
  * how one configuration file serves both a laptop and a server, and rejecting it would take
460
493
  * that away for no gain — a disabled server spawns nothing.
461
494
  */
462
- function assertTransportsPermitted(configs, allowed) {
495
+ export function assertMcpTransportsPermitted(configs, allowed) {
463
496
  if (allowed === undefined)
464
497
  return;
465
- for (const [name, config] of Object.entries(configs)) {
466
- if (config.enabled === false)
498
+ for (const [name, raw] of Object.entries(configs)) {
499
+ const { config, error } = normalizeServerConfig(name, raw);
500
+ // An invalid entry never starts, and its transport is only a guess: it fails on its own.
501
+ if (error !== undefined || config.enabled === false)
467
502
  continue;
468
503
  if (!allowed.includes(config.transport)) {
469
504
  throw new McpTransportNotPermittedError(name, config.transport, allowed);
@@ -483,24 +518,28 @@ function assertTransportsPermitted(configs, allowed) {
483
518
  * more warning in a stream, so it is raised before a single controller exists.
484
519
  */
485
520
  export function createMcpServers(configs, options = {}) {
486
- assertTransportsPermitted(configs, options.allowedTransports);
521
+ assertMcpTransportsPermitted(configs, options.allowedTransports);
487
522
  const listeners = new Set();
488
523
  const notify = (view) => {
489
524
  for (const listener of listeners)
490
525
  listener(view);
491
526
  };
492
- const controllers = Object.entries(configs).map(([name, config]) => new McpServerController({
493
- name,
494
- config,
495
- ...(options.oauthService !== undefined ? { oauthService: options.oauthService } : {}),
496
- ...(options.credentials !== undefined ? { credentials: options.credentials } : {}),
497
- cacheToolsList: options.cacheToolsList ?? DEFAULT_CACHE_TOOLS,
498
- ...(options.transportFactory !== undefined ? { transportFactory: options.transportFactory } : {}),
499
- ...(options.reconnectPolicy !== undefined ? { reconnectPolicy: options.reconnectPolicy } : {}),
500
- ...keepAliveOptions(config, options.keepAlive),
501
- onStatusChange: notify,
502
- timer: options.timer ?? REAL_TIMER,
503
- }));
527
+ const controllers = Object.entries(configs).map(([name, raw]) => {
528
+ const { config, error } = normalizeServerConfig(name, raw);
529
+ return new McpServerController({
530
+ name,
531
+ config,
532
+ ...(error !== undefined ? { configError: error } : {}),
533
+ ...(options.oauthService !== undefined ? { oauthService: options.oauthService } : {}),
534
+ ...(options.credentials !== undefined ? { credentials: options.credentials } : {}),
535
+ cacheToolsList: options.cacheToolsList ?? DEFAULT_CACHE_TOOLS,
536
+ ...(options.transportFactory !== undefined ? { transportFactory: options.transportFactory } : {}),
537
+ ...(options.reconnectPolicy !== undefined ? { reconnectPolicy: options.reconnectPolicy } : {}),
538
+ ...keepAliveOptions(config, options.keepAlive),
539
+ onStatusChange: notify,
540
+ timer: options.timer ?? REAL_TIMER,
541
+ });
542
+ });
504
543
  const byName = new Map(controllers.map((c) => [c.name, c]));
505
544
  let shuttingDown;
506
545
  const shutdown = async () => {
@@ -1,3 +1,4 @@
1
+ import { completeWithRetry } from "../../llm/retry.js";
1
2
  import { buildClassifierSystemPrompt } from "./prompts.js";
2
3
  import { buildToolLookup, buildTranscriptText, projectToolCall } from "./transcript.js";
3
4
  import { parseXmlBlock, parseXmlReason } from "./xml.js";
@@ -7,6 +8,8 @@ const XML_S1_SUFFIX = "\nErr on the side of blocking. <block> immediately.";
7
8
  const XML_S2_SUFFIX = "\nReview the classification process and follow it carefully, making sure you deny actions that should be blocked. As a reminder, explicit (not suggestive or implicit) user confirmation is required to override blocks. Use <thinking> before responding with <block>.";
8
9
  const DEFAULT_STAGE1_MAX_TOKENS = 512;
9
10
  const DEFAULT_STAGE2_MAX_TOKENS = 4096;
11
+ /** A tool call is waiting on this verdict, so it gets seconds of retries, not minutes. */
12
+ const CLASSIFIER_RETRY_POLICY = { maxRetries: 5, maxDelayMs: 8_000 };
10
13
  const DEFAULT_MAX_CONSECUTIVE_ERRORS = 3;
11
14
  const DEFAULT_BREAKER_PROBE_DELAY_MS = 30_000;
12
15
  const DEFAULT_BREAKER_MAX_PROBE_DELAY_MS = 5 * 60_000;
@@ -134,13 +137,14 @@ export class LlmAutoApprover {
134
137
  const request = {
135
138
  system: this.system(),
136
139
  messages: [{ role: "user", content: [{ type: "text", text: userText }], timestamp: Date.now() }],
137
- // No thinking (so temperature applies and tokens aren't spent reasoning), temp 0 for
138
- // determinism (pi drops it for models that reject it). cacheRetention enables prompt
139
- // caching of the shared system + transcript prefix across stages/calls.
140
- params: { temperature: 0, maxTokens },
140
+ // No thinking, so tokens aren't spent reasoning. No temperature either: providers disagree
141
+ // on what they accept (Mistral rejects 0 without top_p 1), and a request refused here
142
+ // silently demotes `auto` to asking. cacheRetention enables prompt caching of the shared
143
+ // system + transcript prefix across stages/calls.
144
+ params: { maxTokens },
141
145
  providerOptions: { cacheRetention: "long" },
142
146
  };
143
- const message = await model.complete(request, { signal });
147
+ const message = await completeWithRetry(model, request, { signal }, CLASSIFIER_RETRY_POLICY);
144
148
  if (message.stopReason === "error")
145
149
  throw new Error(message.errorMessage ?? "classifier stream error");
146
150
  this.consecutiveErrors = 0; // the model responded — clear the breaker
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "operon-agents-core",
3
- "version": "0.1.0-alpha.25",
3
+ "version": "0.1.0-alpha.27",
4
4
  "description": "Internal engine for operon-agents. Prefer operon-agents for application code.",
5
5
  "type": "module",
6
6
  "engines": {
@@ -1,17 +0,0 @@
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
@@ -1,66 +0,0 @@
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