operon-agents-core 0.1.0-alpha.25 → 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.
- package/dist/capabilities/compaction/full.js +2 -1
- package/dist/config/schema.d.ts +3 -3
- package/dist/llm/define-model.d.ts +10 -4
- package/dist/llm/define-model.js +42 -11
- package/dist/llm/index.d.ts +4 -2
- package/dist/llm/index.js +2 -1
- package/dist/llm/model.d.ts +11 -0
- package/dist/llm/request-retry.d.ts +18 -0
- package/dist/llm/request-retry.js +93 -0
- package/dist/llm/retry.d.ts +12 -3
- package/dist/llm/retry.js +64 -26
- package/dist/permission/auto-approver/llm-auto-approver.js +4 -1
- package/package.json +1 -1
- package/dist/llm/retrying-fetch.d.ts +0 -17
- package/dist/llm/retrying-fetch.js +0 -66
|
@@ -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
|
|
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);
|
package/dist/config/schema.d.ts
CHANGED
|
@@ -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
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
|
|
29
|
-
*
|
|
30
|
-
* `streamWithRetry`
|
|
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
|
-
/**
|
|
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>;
|
package/dist/llm/define-model.js
CHANGED
|
@@ -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 {
|
|
5
|
-
/**
|
|
6
|
-
const
|
|
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
|
|
27
|
-
|
|
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
|
-
...
|
|
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
|
-
|
|
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
|
}
|
package/dist/llm/index.d.ts
CHANGED
|
@@ -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";
|
package/dist/llm/model.d.ts
CHANGED
|
@@ -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
|
package/dist/llm/retry.d.ts
CHANGED
|
@@ -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
|
-
*
|
|
36
|
-
*
|
|
37
|
-
*
|
|
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
|
-
*
|
|
9
|
-
*
|
|
10
|
-
*
|
|
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
|
|
25
|
-
const
|
|
26
|
-
|
|
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,
|
|
30
|
-
: await runStreamAttempt(model, attemptRequest,
|
|
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
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
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
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
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
|
|
147
|
-
function
|
|
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
|
|
192
|
+
observe(response);
|
|
155
193
|
await prior?.(response, ...rest);
|
|
156
194
|
},
|
|
157
195
|
},
|
|
@@ -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
|
|
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,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
|