operon-agents-core 0.1.0-alpha.24 → 0.1.0-alpha.26

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";
@@ -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
- import type { CallOptions, LlmRequest, RetryHint } from "./model.ts";
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.
@@ -24,13 +25,16 @@ export interface ModelConnection {
24
25
  /** HTTP request timeout, for providers/SDKs that support it. */
25
26
  readonly timeoutMs?: number;
26
27
  /**
27
- * Retries INSIDE the provider call, below `streamWithRetry`. Leave unset: pi defaults it to
28
- * 0 and the loop's own retry is the one with the context to decide (it can tell a
29
- * mid-stream failure from a clean one and fall back to non-streaming). Setting it here
30
- * multiplies with that — 3 loop attempts × N here.
28
+ * Retries of a request that failed before its response started: 429, 408, 409, 5xx and
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>;
@@ -102,7 +108,6 @@ export declare class ChatModel {
102
108
  /** Stream one attempt. Non-terminal events are relayed live; the terminal event is held so
103
109
  * a clean pre-content failure can be retried instead of surfaced. */
104
110
  private runAttempt;
105
- classifyError(err: unknown): RetryHint;
106
111
  private errorEvent;
107
112
  private errorMessage;
108
113
  }
@@ -1,7 +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 { classifyError } from "./errors.js";
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
+ ]);
5
17
  export class ChatModel {
6
18
  id;
7
19
  provider;
@@ -18,12 +30,21 @@ export class ChatModel {
18
30
  /** Build-time settings (`apiKey` + `connection`) flattened once into pi's option shape.
19
31
  * Every request starts from these; `params` and `providerOptions` layer on top. */
20
32
  requestDefaults;
33
+ /** Read by `streamWithRetry` and `completeWithRetry`, which own every retry. */
34
+ requestRetry;
21
35
  constructor(spec) {
22
36
  this.runtime = spec.runtime ?? createModelRuntime();
23
37
  this.piModel = withAnthropicToolChanges(resolvePiModel(spec, this.runtime));
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
+ };
24
44
  this.requestDefaults = {
25
45
  ...(spec.apiKey !== undefined ? { apiKey: spec.apiKey } : {}),
26
- ...spec.connection,
46
+ ...transport,
47
+ maxRetries: 0,
27
48
  };
28
49
  this.id = this.piModel.id;
29
50
  this.provider = this.piModel.provider;
@@ -62,7 +83,10 @@ export class ChatModel {
62
83
  }
63
84
  }
64
85
  options(req, call) {
65
- 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) };
66
90
  }
67
91
  async streamWithAuthRetry(req, call, ctx, out) {
68
92
  const first = await this.runAttempt(req, call, ctx, out);
@@ -116,9 +140,6 @@ export class ChatModel {
116
140
  }
117
141
  return { resolved: false, errorMessage, terminal };
118
142
  }
119
- classifyError(err) {
120
- return classifyError(err);
121
- }
122
143
  errorEvent(text) {
123
144
  return { type: "error", reason: "error", error: this.errorMessage(text) };
124
145
  }
@@ -136,6 +157,21 @@ export class ChatModel {
136
157
  };
137
158
  }
138
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
+ }
139
175
  function messageOf(error) {
140
176
  return error instanceof Error ? error.message : String(error);
141
177
  }
@@ -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
@@ -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
@@ -1,15 +1,17 @@
1
1
  export { streamResult } from "./model.ts";
2
- export type { LlmRequest, CallOptions, ModelSettings, RetryHint, 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";
12
14
  export { UNKNOWN_CAPABILITY, capabilityFromPiModel, applyDeclaredCapability, } from "./capability.ts";
13
15
  export type { ModelCapability } from "./capability.ts";
14
- export { ChatProviderError, APIConnectionError, APITimeoutError, APIStatusError, APIContextOverflowError, APIEmptyResponseError, classifyError, isRetryableGenerateError, isContextOverflowStatusError, isContextOverflowErrorCode, isContextOverflowMessage, normalizeAPIStatusError, } from "./errors.ts";
16
+ export { ChatProviderError, APIConnectionError, APITimeoutError, APIStatusError, APIContextOverflowError, APIEmptyResponseError, isContextOverflowStatusError, isContextOverflowErrorCode, isContextOverflowMessage, normalizeAPIStatusError, } from "./errors.ts";
15
17
  //# sourceMappingURL=index.d.ts.map
package/dist/llm/index.js CHANGED
@@ -2,8 +2,9 @@ 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
- export { ChatProviderError, APIConnectionError, APITimeoutError, APIStatusError, APIContextOverflowError, APIEmptyResponseError, classifyError, isRetryableGenerateError, isContextOverflowStatusError, isContextOverflowErrorCode, isContextOverflowMessage, normalizeAPIStatusError, } from "./errors.js";
9
+ export { ChatProviderError, APIConnectionError, APITimeoutError, APIStatusError, APIContextOverflowError, APIEmptyResponseError, isContextOverflowStatusError, isContextOverflowErrorCode, isContextOverflowMessage, normalizeAPIStatusError, } from "./errors.js";
9
10
  //# sourceMappingURL=index.js.map
@@ -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
@@ -34,9 +30,20 @@ export interface LlmRequest {
34
30
  readonly params?: ModelSettings;
35
31
  readonly providerOptions?: Readonly<Record<string, unknown>>;
36
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
+ }
37
39
  export interface CallOptions {
38
40
  readonly signal?: AbortSignal;
39
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;
40
47
  }
41
48
  export interface StreamResultOptions {
42
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;
@@ -31,5 +32,18 @@ export interface StreamWithRetryResult {
31
32
  readonly message: AssistantMessage;
32
33
  readonly stopReason: AssistantMessage["stopReason"];
33
34
  }
35
+ /**
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`.
42
+ */
34
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>;
35
49
  //# sourceMappingURL=retry.d.ts.map
package/dist/llm/retry.js CHANGED
@@ -1,23 +1,42 @@
1
+ import { isContextOverflowMessage } from "./errors.js";
1
2
  import { streamResult } from "./model.js";
3
+ import { DEFAULT_REQUEST_RETRY_POLICY, requestRetryDelayMs } from "./request-retry.js";
2
4
  import { logDataPolicy, noopLogger } from "../logging/index.js";
3
5
  export const DEFAULT_MAX_RETRIES_PER_STEP = 3;
4
6
  const BASE_DELAY_MS = 300;
5
7
  const MAX_BACKOFF_MS = 32_000;
8
+ /**
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`.
15
+ */
6
16
  export async function streamWithRetry(input) {
7
17
  const { model, request, call } = input;
8
18
  const logger = input.logger ?? noopLogger;
9
19
  const maxRetries = input.maxRetries ?? DEFAULT_MAX_RETRIES_PER_STEP;
10
20
  const signal = call?.signal;
21
+ const requestPolicy = requestPolicyOf(model);
11
22
  let useCompleteFallback = false;
23
+ let responseRetries = 0;
24
+ let requestRetries = 0;
12
25
  for (let attempt = 0;; attempt++) {
13
26
  signal?.throwIfAborted();
14
27
  const mode = useCompleteFallback ? "complete" : "stream";
15
28
  logger.log("debug", "llm request", logDataPolicy.dontLogModelData
16
29
  ? { model: model.id, attempt, mode, messages: request.messages.length, tools: request.tools?.length ?? 0 }
17
30
  : { model: model.id, attempt, mode, system: request.system, messages: request.messages, tools: request.tools?.map((t) => t.name), params: request.params });
31
+ let exchange;
32
+ const observe = (seen) => {
33
+ exchange = seen;
34
+ };
35
+ const attemptRequest = observeResponses(request, observe);
36
+ const attemptCall = { ...call, onHttpExchange: observe };
18
37
  const attemptResult = useCompleteFallback
19
- ? await runCompleteAttempt(model, request, call)
20
- : await runStreamAttempt(model, request, call, input.onEvent);
38
+ ? await runCompleteAttempt(model, attemptRequest, attemptCall)
39
+ : await runStreamAttempt(model, attemptRequest, attemptCall, input.onEvent);
21
40
  const result = { message: attemptResult.message, stopReason: attemptResult.message.stopReason };
22
41
  if (result.stopReason !== "error") {
23
42
  if (attemptResult.mode === "complete")
@@ -27,10 +46,24 @@ export async function streamWithRetry(input) {
27
46
  : { model: model.id, attempt, mode: attemptResult.mode, stopReason: result.stopReason, content: result.message.content, usage: result.message.usage });
28
47
  return result; // success (stop / toolUse / length / aborted)
29
48
  }
30
- const reason = result.message.errorMessage ?? "";
31
- const hint = model.classifyError(reason);
32
- if (!hint.retryable || attempt >= maxRetries) {
33
- logger.log("error", "llm error", { model: model.id, attempt, mode: attemptResult.mode, retryable: hint.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 });
34
67
  return result; // give up → environment error as the result
35
68
  }
36
69
  input.onDropPartial?.(result.message);
@@ -43,18 +76,33 @@ export async function streamWithRetry(input) {
43
76
  reason: result.message.errorMessage,
44
77
  });
45
78
  }
46
- const delayMs = retryDelayMs(attempt, hint.afterMs);
47
- logger.log("warn", "llm retry", { model: model.id, attempt: attempt + 1, maxAttempts: maxRetries, delayMs, reason: result.message.errorMessage });
48
- input.onRetrying?.({
49
- type: "step_retrying",
50
- attempt: attempt + 1,
51
- maxAttempts: maxRetries,
52
- delayMs,
53
- reason: result.message.errorMessage,
54
- });
55
- 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);
56
82
  }
57
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);
100
+ }
101
+ }
102
+ /** Test doubles cast to `ChatModel` carry no policy. */
103
+ function requestPolicyOf(model) {
104
+ return model.requestRetry ?? DEFAULT_REQUEST_RETRY_POLICY;
105
+ }
58
106
  async function runStreamAttempt(model, request, call, onEvent) {
59
107
  let surfaced = false;
60
108
  const message = await streamResult(model.stream(request, call), {
@@ -133,9 +181,25 @@ function isSurfacedEvent(event) {
133
181
  return false;
134
182
  }
135
183
  }
136
- function retryDelayMs(attempt, retryAfterMs) {
137
- if (retryAfterMs !== undefined)
138
- return retryAfterMs;
184
+ /** Report each response pi surfaces to `observe`, ahead of any `onResponse` already set. */
185
+ function observeResponses(request, observe) {
186
+ const prior = request.providerOptions?.["onResponse"];
187
+ return {
188
+ ...request,
189
+ providerOptions: {
190
+ ...request.providerOptions,
191
+ onResponse: async (response, ...rest) => {
192
+ observe(response);
193
+ await prior?.(response, ...rest);
194
+ },
195
+ },
196
+ };
197
+ }
198
+ /** Output was shown, or the last HTTP response succeeded: either way the failure came later. */
199
+ function failedAfterResponseStarted(surfaced, httpStatus) {
200
+ return surfaced || (httpStatus !== undefined && httpStatus >= 200 && httpStatus < 300);
201
+ }
202
+ function retryDelayMs(attempt) {
139
203
  const baseDelay = Math.min(BASE_DELAY_MS * 2 ** attempt, MAX_BACKOFF_MS);
140
204
  return Math.round(baseDelay + Math.random() * 0.25 * baseDelay);
141
205
  }
@@ -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;
@@ -140,7 +143,7 @@ export class LlmAutoApprover {
140
143
  params: { temperature: 0, maxTokens },
141
144
  providerOptions: { cacheRetention: "long" },
142
145
  };
143
- const message = await model.complete(request, { signal });
146
+ const message = await completeWithRetry(model, request, { signal }, CLASSIFIER_RETRY_POLICY);
144
147
  if (message.stopReason === "error")
145
148
  throw new Error(message.errorMessage ?? "classifier stream error");
146
149
  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.24",
3
+ "version": "0.1.0-alpha.26",
4
4
  "description": "Internal engine for operon-agents. Prefer operon-agents for application code.",
5
5
  "type": "module",
6
6
  "engines": {