operon-agents-core 0.1.0-alpha.23 → 0.1.0-alpha.25
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +13 -0
- package/dist/agent/index.d.ts +1 -0
- package/dist/agent/index.js +1 -0
- package/dist/agent/lifecycle-recovery.d.ts +15 -0
- package/dist/agent/lifecycle-recovery.js +44 -0
- package/dist/agent/runner.js +1 -0
- package/dist/agent/session.d.ts +7 -0
- package/dist/agent/session.js +21 -0
- package/dist/config/schema.d.ts +2 -2
- package/dist/llm/define-model.d.ts +5 -6
- package/dist/llm/define-model.js +9 -4
- package/dist/llm/errors.d.ts +0 -3
- package/dist/llm/errors.js +0 -80
- package/dist/llm/index.d.ts +2 -2
- package/dist/llm/index.js +1 -1
- package/dist/llm/model.d.ts +0 -4
- package/dist/llm/retry.d.ts +5 -0
- package/dist/llm/retry.js +36 -10
- package/dist/llm/retrying-fetch.d.ts +17 -0
- package/dist/llm/retrying-fetch.js +66 -0
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -5,3 +5,16 @@ Internal engine for `operon-agents`.
|
|
|
5
5
|
Application code should import from `operon-agents`. This package intentionally
|
|
6
6
|
contains lower-level runtime, loop, permission, storage, and capability modules
|
|
7
7
|
that may change as the engine evolves.
|
|
8
|
+
|
|
9
|
+
## Execution recovery
|
|
10
|
+
|
|
11
|
+
`Runner.run` and `runStream` reconcile abandoned lifecycle frames before a Session's
|
|
12
|
+
first fresh run, under its run lock and any configured `SessionLock`. Durable
|
|
13
|
+
approval/input pauses remain resumable through `Runner.resume`. `Session.open`
|
|
14
|
+
alone never closes unfinished turns: opening is not proof that another executor died.
|
|
15
|
+
|
|
16
|
+
Hosts can call `recoverOrphanedTurns` without opening a Session, or
|
|
17
|
+
`closeOrphanedTurns` to receive the committed repair events for broadcasting.
|
|
18
|
+
Both require exclusive execution ownership. For stores shared across processes,
|
|
19
|
+
provide a distributed lock to Runner or acquire a host-managed lease before takeover.
|
|
20
|
+
Recovery closes orphan frames; it does not retry tools with unknown side effects.
|
package/dist/agent/index.d.ts
CHANGED
|
@@ -22,4 +22,5 @@ export type { ContextBreakdown, ContextSlice, ContextInjectionSlice, ComputeCont
|
|
|
22
22
|
export { Runner } from "./runner.ts";
|
|
23
23
|
export type { AgentInput, ResumeInput, RunInterruption, RunnerConfig, RunOptions, RunResult, RunStatus, } from "./runner.ts";
|
|
24
24
|
export * from "./workflow/index.ts";
|
|
25
|
+
export { closeOrphanedTurns, recoverOrphanedTurns } from "./lifecycle-recovery.ts";
|
|
25
26
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/agent/index.js
CHANGED
|
@@ -16,4 +16,5 @@ export { Runner } from "./runner.js";
|
|
|
16
16
|
// Workflow engine (the deterministic subagent-orchestration runtime) + its manager
|
|
17
17
|
// and snapshot/journal layers, exposed so upper layers can integrate programmatically.
|
|
18
18
|
export * from "./workflow/index.js";
|
|
19
|
+
export { closeOrphanedTurns, recoverOrphanedTurns } from "./lifecycle-recovery.js";
|
|
19
20
|
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { type AgentEvent } from "../events/index.ts";
|
|
2
|
+
import type { AgentRecord, SessionStore } from "../store/index.ts";
|
|
3
|
+
/**
|
|
4
|
+
* Close lifecycle frames abandoned by a previous executor, preserving durable pauses.
|
|
5
|
+
* The host MUST establish exclusive execution ownership before calling this function.
|
|
6
|
+
* It does not acquire a lease: an open turn alone is never evidence of a dead executor.
|
|
7
|
+
* Repeated calls under that ownership are idempotent, including after a partial write.
|
|
8
|
+
* A supplied log must be read under the same ownership and include every shard's tail.
|
|
9
|
+
* Returns committed records; a raw store does not broadcast them to live observers.
|
|
10
|
+
*/
|
|
11
|
+
export declare function recoverOrphanedTurns(sessionId: string, store: SessionStore, records?: readonly AgentRecord[]): Promise<AgentRecord[]>;
|
|
12
|
+
/** Host-facing recovery with projected events to broadcast after durable writes. Same
|
|
13
|
+
* exclusive-ownership requirement as recoverOrphanedTurns; no Session needs to be opened. */
|
|
14
|
+
export declare function closeOrphanedTurns(sessionId: string, store: SessionStore): Promise<readonly AgentEvent[]>;
|
|
15
|
+
//# sourceMappingURL=lifecycle-recovery.d.ts.map
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { SessionProjection, readSessionTails } from "../events/projection.js";
|
|
2
|
+
import { agentEventFromRecord, newAgentEventId } from "../events/index.js";
|
|
3
|
+
import { INTERRUPTION_STATE_KEY } from "../loop/interruption.js";
|
|
4
|
+
/**
|
|
5
|
+
* Close lifecycle frames abandoned by a previous executor, preserving durable pauses.
|
|
6
|
+
* The host MUST establish exclusive execution ownership before calling this function.
|
|
7
|
+
* It does not acquire a lease: an open turn alone is never evidence of a dead executor.
|
|
8
|
+
* Repeated calls under that ownership are idempotent, including after a partial write.
|
|
9
|
+
* A supplied log must be read under the same ownership and include every shard's tail.
|
|
10
|
+
* Returns committed records; a raw store does not broadcast them to live observers.
|
|
11
|
+
*/
|
|
12
|
+
export async function recoverOrphanedTurns(sessionId, store, records) {
|
|
13
|
+
if (await store.getState(INTERRUPTION_STATE_KEY) !== null)
|
|
14
|
+
return [];
|
|
15
|
+
// Reuse the core checkpoint/lifecycle reducer, without history or live subscriptions.
|
|
16
|
+
const frames = new SessionProjection(sessionId, { history: false });
|
|
17
|
+
for (const record of records ?? await readSessionTails(store))
|
|
18
|
+
frames.applyRecord(record);
|
|
19
|
+
const recovered = [];
|
|
20
|
+
for (const agent of frames.snapshot({ maxMessages: 0 }).agents) {
|
|
21
|
+
if (agent.turn !== undefined) {
|
|
22
|
+
await append(agent.address, { type: "turn.ended", turnId: agent.turn.turnId, reason: "failed" });
|
|
23
|
+
}
|
|
24
|
+
if (agent.live && agent.agent !== undefined) {
|
|
25
|
+
await append(agent.address, { type: "agent.ended", agent: agent.agent });
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
return recovered;
|
|
29
|
+
async function append(address, event) {
|
|
30
|
+
const record = { type: "event.lifecycle", eventId: newAgentEventId(), time: Date.now(), address, event };
|
|
31
|
+
await store.appendRecord(record);
|
|
32
|
+
recovered.push(record);
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
/** Host-facing recovery with projected events to broadcast after durable writes. Same
|
|
36
|
+
* exclusive-ownership requirement as recoverOrphanedTurns; no Session needs to be opened. */
|
|
37
|
+
export async function closeOrphanedTurns(sessionId, store) {
|
|
38
|
+
const records = await recoverOrphanedTurns(sessionId, store);
|
|
39
|
+
return records.flatMap((record) => {
|
|
40
|
+
const event = agentEventFromRecord(record, sessionId);
|
|
41
|
+
return event === undefined ? [] : [event];
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
//# sourceMappingURL=lifecycle-recovery.js.map
|
package/dist/agent/runner.js
CHANGED
|
@@ -293,6 +293,7 @@ export class Runner {
|
|
|
293
293
|
if (session.store && (await session.store.getState(INTERRUPTION_STATE_KEY)) !== null) {
|
|
294
294
|
throw new Error("This session has an interrupted run. Resume or resolve it before starting a new prompt.");
|
|
295
295
|
}
|
|
296
|
+
await session.recoverLifecycle();
|
|
296
297
|
const head = await this.resolveConversationHead(session, rootAgent);
|
|
297
298
|
const agent = head.agent;
|
|
298
299
|
const state = await this.beginRun(session, opts, undefined, head.address);
|
package/dist/agent/session.d.ts
CHANGED
|
@@ -254,6 +254,13 @@ export declare class Session implements SessionPort {
|
|
|
254
254
|
/** Each stateful capability's `durableState`, by name — registered when it is restored. */
|
|
255
255
|
private readonly durableOwners;
|
|
256
256
|
private constructor();
|
|
257
|
+
private lifecycleRecovered;
|
|
258
|
+
/**
|
|
259
|
+
* Reconcile a cold session before its first run. The caller MUST hold this session's
|
|
260
|
+
* run lock and exclusive execution ownership (a distributed lease for shared stores).
|
|
261
|
+
* Opening/observing a session alone never proves that the previous executor is dead.
|
|
262
|
+
*/
|
|
263
|
+
recoverLifecycle(): Promise<void>;
|
|
257
264
|
/**
|
|
258
265
|
* Open a session. Everything it depends on arrives in `opts`; `open` fills in the defaults for
|
|
259
266
|
* whatever is missing, builds the session's own objects (signal, event publisher, log reader,
|
package/dist/agent/session.js
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { recoverOrphanedTurns } from "./lifecycle-recovery.js";
|
|
2
|
+
import { readSessionTails } from "../events/projection.js";
|
|
1
3
|
import { FileFreshnessLedger } from "../tool/file-freshness.js";
|
|
2
4
|
import { PermissionManager } from "../permission/manager.js";
|
|
3
5
|
import { STAGED_POLICY_SLOTS } from "../permission/policies.js";
|
|
@@ -175,6 +177,25 @@ export class Session {
|
|
|
175
177
|
this.allCapabilities = opts.capabilities ?? [];
|
|
176
178
|
this.preloadedLog = opts.preloadedLog;
|
|
177
179
|
}
|
|
180
|
+
lifecycleRecovered = false;
|
|
181
|
+
/**
|
|
182
|
+
* Reconcile a cold session before its first run. The caller MUST hold this session's
|
|
183
|
+
* run lock and exclusive execution ownership (a distributed lease for shared stores).
|
|
184
|
+
* Opening/observing a session alone never proves that the previous executor is dead.
|
|
185
|
+
*/
|
|
186
|
+
async recoverLifecycle() {
|
|
187
|
+
if (this.lifecycleRecovered)
|
|
188
|
+
return;
|
|
189
|
+
if (this.store !== undefined) {
|
|
190
|
+
const records = await readSessionTails(this.store);
|
|
191
|
+
for (const address of new Set(records.map((record) => record.address ?? DEFAULT_ADDRESS))) {
|
|
192
|
+
this.checkpointing?.restoreFrame(address, records);
|
|
193
|
+
}
|
|
194
|
+
await recoverOrphanedTurns(this.id, this.store, records);
|
|
195
|
+
await this.flushEvents();
|
|
196
|
+
}
|
|
197
|
+
this.lifecycleRecovered = true;
|
|
198
|
+
}
|
|
178
199
|
/**
|
|
179
200
|
* Open a session. Everything it depends on arrives in `opts`; `open` fills in the defaults for
|
|
180
201
|
* whatever is missing, builds the session's own objects (signal, event publisher, log reader,
|
package/dist/config/schema.d.ts
CHANGED
|
@@ -132,9 +132,9 @@ export declare const ThinkingConfigSchema: z.ZodObject<{
|
|
|
132
132
|
on: "on";
|
|
133
133
|
}>;
|
|
134
134
|
effort: z.ZodOptional<z.ZodEnum<{
|
|
135
|
+
high: "high";
|
|
135
136
|
low: "low";
|
|
136
137
|
medium: "medium";
|
|
137
|
-
high: "high";
|
|
138
138
|
}>>;
|
|
139
139
|
}, z.core.$strip>;
|
|
140
140
|
export declare const McpOAuthClientConfigSchema: z.ZodObject<{
|
|
@@ -319,9 +319,9 @@ export declare const AgentFrameworkConfigSchema: z.ZodObject<{
|
|
|
319
319
|
on: "on";
|
|
320
320
|
}>;
|
|
321
321
|
effort: z.ZodOptional<z.ZodEnum<{
|
|
322
|
+
high: "high";
|
|
322
323
|
low: "low";
|
|
323
324
|
medium: "medium";
|
|
324
|
-
high: "high";
|
|
325
325
|
}>>;
|
|
326
326
|
}, z.core.$strip>>;
|
|
327
327
|
mcpServers: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodPreprocess<z.ZodPipe<z.ZodObject<{
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import type { Api, AssistantMessage, AssistantMessageEventStream, Model, Provider, ProviderHeaders, Transport } from "../protocol/index.ts";
|
|
2
2
|
import { type ModelRuntime } from "./runtime.ts";
|
|
3
|
-
import type { CallOptions, LlmRequest
|
|
3
|
+
import type { CallOptions, LlmRequest } from "./model.ts";
|
|
4
4
|
/**
|
|
5
5
|
* How to reach the endpoint, as opposed to how the model should think. Fixed when the model is
|
|
6
6
|
* built, applied to every request it makes.
|
|
@@ -24,10 +24,10 @@ export interface ModelConnection {
|
|
|
24
24
|
/** HTTP request timeout, for providers/SDKs that support it. */
|
|
25
25
|
readonly timeoutMs?: number;
|
|
26
26
|
/**
|
|
27
|
-
* Retries
|
|
28
|
-
*
|
|
29
|
-
*
|
|
30
|
-
*
|
|
27
|
+
* Retries of a request that failed before its response started: 429, 408, 409, 5xx and
|
|
28
|
+
* connection failures, honoring `Retry-After`. Defaults to 8; 0 turns them off. These run
|
|
29
|
+
* inside the provider call and emit no events. A failure after the response has started is
|
|
30
|
+
* `streamWithRetry`'s. Bedrock and `pi-messages` do not read this setting.
|
|
31
31
|
*/
|
|
32
32
|
readonly maxRetries?: number;
|
|
33
33
|
/** Cap on honoring a server-requested retry delay. pi defaults to 60s; 0 disables the cap. */
|
|
@@ -102,7 +102,6 @@ export declare class ChatModel {
|
|
|
102
102
|
/** Stream one attempt. Non-terminal events are relayed live; the terminal event is held so
|
|
103
103
|
* a clean pre-content failure can be retried instead of surfaced. */
|
|
104
104
|
private runAttempt;
|
|
105
|
-
classifyError(err: unknown): RetryHint;
|
|
106
105
|
private errorEvent;
|
|
107
106
|
private errorMessage;
|
|
108
107
|
}
|
package/dist/llm/define-model.js
CHANGED
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
import { createAssistantMessageEventStream } from "@earendil-works/pi-ai";
|
|
2
2
|
import { emptyUsage } from "../loop/usage.js";
|
|
3
3
|
import { createModelRuntime, forceRefreshOAuth, } from "./runtime.js";
|
|
4
|
-
import {
|
|
4
|
+
import { createRetryingFetch } from "./retrying-fetch.js";
|
|
5
|
+
/** Roughly 30–40s of backoff with pi's policy, enough to outlast a typical short rate-limit window. */
|
|
6
|
+
const DEFAULT_PROVIDER_MAX_RETRIES = 8;
|
|
5
7
|
export class ChatModel {
|
|
6
8
|
id;
|
|
7
9
|
provider;
|
|
@@ -21,9 +23,15 @@ export class ChatModel {
|
|
|
21
23
|
constructor(spec) {
|
|
22
24
|
this.runtime = spec.runtime ?? createModelRuntime();
|
|
23
25
|
this.piModel = withAnthropicToolChanges(resolvePiModel(spec, this.runtime));
|
|
26
|
+
const maxRetries = spec.connection?.maxRetries ?? DEFAULT_PROVIDER_MAX_RETRIES;
|
|
27
|
+
const maxRetryDelayMs = spec.connection?.maxRetryDelayMs;
|
|
24
28
|
this.requestDefaults = {
|
|
25
29
|
...(spec.apiKey !== undefined ? { apiKey: spec.apiKey } : {}),
|
|
26
30
|
...spec.connection,
|
|
31
|
+
maxRetries,
|
|
32
|
+
...(this.piModel.api === "mistral-conversations"
|
|
33
|
+
? { fetch: createRetryingFetch({ maxRetries, ...(maxRetryDelayMs !== undefined ? { maxRetryDelayMs } : {}) }) }
|
|
34
|
+
: {}),
|
|
27
35
|
};
|
|
28
36
|
this.id = this.piModel.id;
|
|
29
37
|
this.provider = this.piModel.provider;
|
|
@@ -116,9 +124,6 @@ export class ChatModel {
|
|
|
116
124
|
}
|
|
117
125
|
return { resolved: false, errorMessage, terminal };
|
|
118
126
|
}
|
|
119
|
-
classifyError(err) {
|
|
120
|
-
return classifyError(err);
|
|
121
|
-
}
|
|
122
127
|
errorEvent(text) {
|
|
123
128
|
return { type: "error", reason: "error", error: this.errorMessage(text) };
|
|
124
129
|
}
|
package/dist/llm/errors.d.ts
CHANGED
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
import type { RetryHint } from "./model.ts";
|
|
2
1
|
export declare class ChatProviderError extends Error {
|
|
3
2
|
constructor(message: string);
|
|
4
3
|
}
|
|
@@ -19,7 +18,6 @@ export declare class APIContextOverflowError extends APIStatusError {
|
|
|
19
18
|
export declare class APIEmptyResponseError extends ChatProviderError {
|
|
20
19
|
constructor(message: string);
|
|
21
20
|
}
|
|
22
|
-
export declare function isRetryableGenerateError(error: unknown): boolean;
|
|
23
21
|
export declare function isContextOverflowErrorCode(code: string | null | undefined): boolean;
|
|
24
22
|
/**
|
|
25
23
|
* Message-text-only overflow detection, for the paths where the transport has already reduced
|
|
@@ -29,5 +27,4 @@ export declare function isContextOverflowErrorCode(code: string | null | undefin
|
|
|
29
27
|
export declare function isContextOverflowMessage(message: string): boolean;
|
|
30
28
|
export declare function isContextOverflowStatusError(statusCode: number, message: string): boolean;
|
|
31
29
|
export declare function normalizeAPIStatusError(statusCode: number, message: string, requestId?: string | null): APIStatusError;
|
|
32
|
-
export declare function classifyError(error: unknown): RetryHint;
|
|
33
30
|
//# sourceMappingURL=errors.d.ts.map
|
package/dist/llm/errors.js
CHANGED
|
@@ -38,20 +38,6 @@ export class APIEmptyResponseError extends ChatProviderError {
|
|
|
38
38
|
this.name = "APIEmptyResponseError";
|
|
39
39
|
}
|
|
40
40
|
}
|
|
41
|
-
const RETRYABLE_STATUS_CODES = [429, 500, 502, 503, 504];
|
|
42
|
-
export function isRetryableGenerateError(error) {
|
|
43
|
-
if (error instanceof APIConnectionError || error instanceof APITimeoutError) {
|
|
44
|
-
return true;
|
|
45
|
-
}
|
|
46
|
-
if (error instanceof APIEmptyResponseError) {
|
|
47
|
-
return true;
|
|
48
|
-
}
|
|
49
|
-
if (error instanceof APIStatusError) {
|
|
50
|
-
return RETRYABLE_STATUS_CODES.includes(error.statusCode);
|
|
51
|
-
}
|
|
52
|
-
const status = extractStatusCode(error);
|
|
53
|
-
return status !== undefined && RETRYABLE_STATUS_CODES.includes(status);
|
|
54
|
-
}
|
|
55
41
|
const CONTEXT_OVERFLOW_MESSAGE_PATTERNS = [
|
|
56
42
|
/context[ _-]?length/,
|
|
57
43
|
/(?:context[ _-]?window.*exceed|exceed.*context[ _-]?window)/,
|
|
@@ -85,70 +71,4 @@ export function normalizeAPIStatusError(statusCode, message, requestId) {
|
|
|
85
71
|
}
|
|
86
72
|
return new APIStatusError(statusCode, message, requestId);
|
|
87
73
|
}
|
|
88
|
-
export function classifyError(error) {
|
|
89
|
-
if (error instanceof APIContextOverflowError) {
|
|
90
|
-
return { retryable: false };
|
|
91
|
-
}
|
|
92
|
-
const status = extractStatusCode(error);
|
|
93
|
-
const message = extractMessage(error);
|
|
94
|
-
if (status !== undefined && isContextOverflowStatusError(status, message)) {
|
|
95
|
-
return { retryable: false };
|
|
96
|
-
}
|
|
97
|
-
// No status to gate on (the string path): classify overflow from the message alone, so the
|
|
98
|
-
// retry layer gives up immediately instead of falling through the generic-retryable check.
|
|
99
|
-
if (status === undefined && isContextOverflowMessage(message)) {
|
|
100
|
-
return { retryable: false };
|
|
101
|
-
}
|
|
102
|
-
if (isRetryableGenerateError(error)) {
|
|
103
|
-
const afterMs = parseRetryAfterMs(error);
|
|
104
|
-
return afterMs === undefined ? { retryable: true } : { retryable: true, afterMs };
|
|
105
|
-
}
|
|
106
|
-
return { retryable: false };
|
|
107
|
-
}
|
|
108
|
-
// Generic error-shape extraction (interface adapter for non-class errors).
|
|
109
|
-
function extractStatusCode(error) {
|
|
110
|
-
if (typeof error !== "object" || error === null)
|
|
111
|
-
return undefined;
|
|
112
|
-
const record = error;
|
|
113
|
-
const candidate = record["statusCode"] ?? record["status"];
|
|
114
|
-
return typeof candidate === "number" ? candidate : undefined;
|
|
115
|
-
}
|
|
116
|
-
function extractMessage(error) {
|
|
117
|
-
if (error instanceof Error)
|
|
118
|
-
return error.message;
|
|
119
|
-
if (typeof error === "string")
|
|
120
|
-
return error;
|
|
121
|
-
return String(error);
|
|
122
|
-
}
|
|
123
|
-
function parseRetryAfterMs(error) {
|
|
124
|
-
const raw = extractRetryAfter(error);
|
|
125
|
-
if (raw === undefined)
|
|
126
|
-
return undefined;
|
|
127
|
-
const seconds = Number(raw);
|
|
128
|
-
if (Number.isFinite(seconds))
|
|
129
|
-
return Math.max(0, seconds * 1000);
|
|
130
|
-
const at = Date.parse(raw);
|
|
131
|
-
if (Number.isFinite(at))
|
|
132
|
-
return Math.max(0, at - Date.now());
|
|
133
|
-
return undefined;
|
|
134
|
-
}
|
|
135
|
-
function extractRetryAfter(error) {
|
|
136
|
-
if (typeof error !== "object" || error === null)
|
|
137
|
-
return undefined;
|
|
138
|
-
const record = error;
|
|
139
|
-
const headers = record["headers"];
|
|
140
|
-
if (headers instanceof Headers) {
|
|
141
|
-
return headers.get("retry-after") ?? undefined;
|
|
142
|
-
}
|
|
143
|
-
if (typeof headers === "object" && headers !== null) {
|
|
144
|
-
const bag = headers;
|
|
145
|
-
const value = bag["retry-after"] ?? bag["Retry-After"];
|
|
146
|
-
if (typeof value === "string" || typeof value === "number")
|
|
147
|
-
return String(value);
|
|
148
|
-
}
|
|
149
|
-
const top = record["retryAfter"];
|
|
150
|
-
if (typeof top === "string" || typeof top === "number")
|
|
151
|
-
return String(top);
|
|
152
|
-
return undefined;
|
|
153
|
-
}
|
|
154
74
|
//# sourceMappingURL=errors.js.map
|
package/dist/llm/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
export { streamResult } from "./model.ts";
|
|
2
|
-
export type { LlmRequest, CallOptions, ModelSettings,
|
|
2
|
+
export type { LlmRequest, CallOptions, ModelSettings, ThinkingBudgets, ThinkingLevel, StreamResultOptions, } from "./model.ts";
|
|
3
3
|
export { ChatModel, defineModel, tryGetPiModel } from "./define-model.ts";
|
|
4
4
|
export * from "./provider.ts";
|
|
5
5
|
export type { ModelConnection, ModelSpec } from "./define-model.ts";
|
|
@@ -11,5 +11,5 @@ export { InMemoryCredentialStore, MemoryCredentialStore, FileCredentialStore, }
|
|
|
11
11
|
export type { CredentialStore, Credential, CredentialInfo, AuthInteraction, AuthPrompt, AuthResult, AuthType, OAuthCredential, OAuthCredentials, } from "./auth.ts";
|
|
12
12
|
export { UNKNOWN_CAPABILITY, capabilityFromPiModel, applyDeclaredCapability, } from "./capability.ts";
|
|
13
13
|
export type { ModelCapability } from "./capability.ts";
|
|
14
|
-
export { ChatProviderError, APIConnectionError, APITimeoutError, APIStatusError, APIContextOverflowError, APIEmptyResponseError,
|
|
14
|
+
export { ChatProviderError, APIConnectionError, APITimeoutError, APIStatusError, APIContextOverflowError, APIEmptyResponseError, isContextOverflowStatusError, isContextOverflowErrorCode, isContextOverflowMessage, normalizeAPIStatusError, } from "./errors.ts";
|
|
15
15
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/llm/index.js
CHANGED
|
@@ -5,5 +5,5 @@ export { createModelRuntime, forceRefreshOAuth } from "./runtime.js";
|
|
|
5
5
|
export { streamWithRetry, DEFAULT_MAX_RETRIES_PER_STEP } from "./retry.js";
|
|
6
6
|
export { InMemoryCredentialStore, MemoryCredentialStore, FileCredentialStore, } from "./auth.js";
|
|
7
7
|
export { UNKNOWN_CAPABILITY, capabilityFromPiModel, applyDeclaredCapability, } from "./capability.js";
|
|
8
|
-
export { ChatProviderError, APIConnectionError, APITimeoutError, APIStatusError, APIContextOverflowError, APIEmptyResponseError,
|
|
8
|
+
export { ChatProviderError, APIConnectionError, APITimeoutError, APIStatusError, APIContextOverflowError, APIEmptyResponseError, isContextOverflowStatusError, isContextOverflowErrorCode, isContextOverflowMessage, normalizeAPIStatusError, } from "./errors.js";
|
|
9
9
|
//# sourceMappingURL=index.js.map
|
package/dist/llm/model.d.ts
CHANGED
|
@@ -1,9 +1,5 @@
|
|
|
1
1
|
import type { AssistantMessage, AssistantMessageEvent, AssistantMessageEventStream, Message, ThinkingBudgets, ThinkingLevel, ToolSchema } from "../protocol/index.ts";
|
|
2
2
|
export type { ThinkingBudgets, ThinkingLevel };
|
|
3
|
-
export type RetryHint = {
|
|
4
|
-
readonly retryable: boolean;
|
|
5
|
-
readonly afterMs?: number;
|
|
6
|
-
};
|
|
7
3
|
/**
|
|
8
4
|
* How the model should behave for one request — the knobs that legitimately vary per agent
|
|
9
5
|
* and per turn. Deliberately NOT pi's `SimpleStreamOptions`: connection-tier settings
|
package/dist/llm/retry.d.ts
CHANGED
|
@@ -31,5 +31,10 @@ export interface StreamWithRetryResult {
|
|
|
31
31
|
readonly message: AssistantMessage;
|
|
32
32
|
readonly stopReason: AssistantMessage["stopReason"];
|
|
33
33
|
}
|
|
34
|
+
/**
|
|
35
|
+
* Recovers a response that failed after it had started. A request that never got a response is
|
|
36
|
+
* retried below this, inside the provider call (`ModelConnection.maxRetries`), so a failure
|
|
37
|
+
* without a successful status or any output is final here.
|
|
38
|
+
*/
|
|
34
39
|
export declare function streamWithRetry(input: StreamWithRetryInput): Promise<StreamWithRetryResult>;
|
|
35
40
|
//# sourceMappingURL=retry.d.ts.map
|
package/dist/llm/retry.js
CHANGED
|
@@ -1,8 +1,14 @@
|
|
|
1
|
+
import { isContextOverflowMessage } from "./errors.js";
|
|
1
2
|
import { streamResult } from "./model.js";
|
|
2
3
|
import { logDataPolicy, noopLogger } from "../logging/index.js";
|
|
3
4
|
export const DEFAULT_MAX_RETRIES_PER_STEP = 3;
|
|
4
5
|
const BASE_DELAY_MS = 300;
|
|
5
6
|
const MAX_BACKOFF_MS = 32_000;
|
|
7
|
+
/**
|
|
8
|
+
* Recovers a response that failed after it had started. A request that never got a response is
|
|
9
|
+
* retried below this, inside the provider call (`ModelConnection.maxRetries`), so a failure
|
|
10
|
+
* without a successful status or any output is final here.
|
|
11
|
+
*/
|
|
6
12
|
export async function streamWithRetry(input) {
|
|
7
13
|
const { model, request, call } = input;
|
|
8
14
|
const logger = input.logger ?? noopLogger;
|
|
@@ -15,9 +21,13 @@ export async function streamWithRetry(input) {
|
|
|
15
21
|
logger.log("debug", "llm request", logDataPolicy.dontLogModelData
|
|
16
22
|
? { model: model.id, attempt, mode, messages: request.messages.length, tools: request.tools?.length ?? 0 }
|
|
17
23
|
: { model: model.id, attempt, mode, system: request.system, messages: request.messages, tools: request.tools?.map((t) => t.name), params: request.params });
|
|
24
|
+
let httpStatus;
|
|
25
|
+
const attemptRequest = observeHttpStatus(request, (status) => {
|
|
26
|
+
httpStatus = status;
|
|
27
|
+
});
|
|
18
28
|
const attemptResult = useCompleteFallback
|
|
19
|
-
? await runCompleteAttempt(model,
|
|
20
|
-
: await runStreamAttempt(model,
|
|
29
|
+
? await runCompleteAttempt(model, attemptRequest, call)
|
|
30
|
+
: await runStreamAttempt(model, attemptRequest, call, input.onEvent);
|
|
21
31
|
const result = { message: attemptResult.message, stopReason: attemptResult.message.stopReason };
|
|
22
32
|
if (result.stopReason !== "error") {
|
|
23
33
|
if (attemptResult.mode === "complete")
|
|
@@ -27,10 +37,10 @@ export async function streamWithRetry(input) {
|
|
|
27
37
|
: { model: model.id, attempt, mode: attemptResult.mode, stopReason: result.stopReason, content: result.message.content, usage: result.message.usage });
|
|
28
38
|
return result; // success (stop / toolUse / length / aborted)
|
|
29
39
|
}
|
|
30
|
-
const
|
|
31
|
-
|
|
32
|
-
if (!
|
|
33
|
-
logger.log("error", "llm error", { model: model.id, attempt, mode: attemptResult.mode, retryable
|
|
40
|
+
const retryable = failedAfterResponseStarted(attemptResult.surfaced, httpStatus)
|
|
41
|
+
&& !isContextOverflowMessage(result.message.errorMessage ?? "");
|
|
42
|
+
if (!retryable || attempt >= maxRetries) {
|
|
43
|
+
logger.log("error", "llm error", { model: model.id, attempt, mode: attemptResult.mode, retryable, reason: result.message.errorMessage });
|
|
34
44
|
return result; // give up → environment error as the result
|
|
35
45
|
}
|
|
36
46
|
input.onDropPartial?.(result.message);
|
|
@@ -43,7 +53,7 @@ export async function streamWithRetry(input) {
|
|
|
43
53
|
reason: result.message.errorMessage,
|
|
44
54
|
});
|
|
45
55
|
}
|
|
46
|
-
const delayMs = retryDelayMs(attempt
|
|
56
|
+
const delayMs = retryDelayMs(attempt);
|
|
47
57
|
logger.log("warn", "llm retry", { model: model.id, attempt: attempt + 1, maxAttempts: maxRetries, delayMs, reason: result.message.errorMessage });
|
|
48
58
|
input.onRetrying?.({
|
|
49
59
|
type: "step_retrying",
|
|
@@ -133,9 +143,25 @@ function isSurfacedEvent(event) {
|
|
|
133
143
|
return false;
|
|
134
144
|
}
|
|
135
145
|
}
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
146
|
+
/** Report each HTTP response's status to `observe`, ahead of any `onResponse` already set. */
|
|
147
|
+
function observeHttpStatus(request, observe) {
|
|
148
|
+
const prior = request.providerOptions?.["onResponse"];
|
|
149
|
+
return {
|
|
150
|
+
...request,
|
|
151
|
+
providerOptions: {
|
|
152
|
+
...request.providerOptions,
|
|
153
|
+
onResponse: async (response, ...rest) => {
|
|
154
|
+
observe(response.status);
|
|
155
|
+
await prior?.(response, ...rest);
|
|
156
|
+
},
|
|
157
|
+
},
|
|
158
|
+
};
|
|
159
|
+
}
|
|
160
|
+
/** Output was shown, or the last HTTP response succeeded: either way the failure came later. */
|
|
161
|
+
function failedAfterResponseStarted(surfaced, httpStatus) {
|
|
162
|
+
return surfaced || (httpStatus !== undefined && httpStatus >= 200 && httpStatus < 300);
|
|
163
|
+
}
|
|
164
|
+
function retryDelayMs(attempt) {
|
|
139
165
|
const baseDelay = Math.min(BASE_DELAY_MS * 2 ** attempt, MAX_BACKOFF_MS);
|
|
140
166
|
return Math.round(baseDelay + Math.random() * 0.25 * baseDelay);
|
|
141
167
|
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
export interface RetryingFetchOptions {
|
|
2
|
+
readonly maxRetries: number;
|
|
3
|
+
readonly maxRetryDelayMs?: number;
|
|
4
|
+
}
|
|
5
|
+
/**
|
|
6
|
+
* A `fetch` with pi's provider retry policy, for adapters that call `fetch` directly and so never
|
|
7
|
+
* reach `retryProviderRequest` themselves (`mistral-conversations`, as of pi-ai 1.5.0). Remove it
|
|
8
|
+
* when the adapter retries on its own.
|
|
9
|
+
*
|
|
10
|
+
* pi decides what is retryable and how long to wait. A response it gives up on is returned
|
|
11
|
+
* unread, so the adapter reports the failure exactly as it would have without retries.
|
|
12
|
+
*
|
|
13
|
+
* `init.signal` bounds the whole sequence, backoff included, and the options are fixed when the
|
|
14
|
+
* wrapper is built. The request body must be replayable, which a string is.
|
|
15
|
+
*/
|
|
16
|
+
export declare function createRetryingFetch(options: RetryingFetchOptions): typeof globalThis.fetch;
|
|
17
|
+
//# sourceMappingURL=retrying-fetch.d.ts.map
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import { retryProviderRequest } from "@earendil-works/pi-ai/utils/provider-retry";
|
|
2
|
+
/** The shape `retryProviderRequest` retries on. An undefined status is a connection failure. */
|
|
3
|
+
class AttemptFailure extends Error {
|
|
4
|
+
status;
|
|
5
|
+
headers;
|
|
6
|
+
response;
|
|
7
|
+
constructor(message, response, cause) {
|
|
8
|
+
super(message, { cause });
|
|
9
|
+
this.status = response?.status;
|
|
10
|
+
this.headers = response?.headers;
|
|
11
|
+
this.response = response;
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* A `fetch` with pi's provider retry policy, for adapters that call `fetch` directly and so never
|
|
16
|
+
* reach `retryProviderRequest` themselves (`mistral-conversations`, as of pi-ai 1.5.0). Remove it
|
|
17
|
+
* when the adapter retries on its own.
|
|
18
|
+
*
|
|
19
|
+
* pi decides what is retryable and how long to wait. A response it gives up on is returned
|
|
20
|
+
* unread, so the adapter reports the failure exactly as it would have without retries.
|
|
21
|
+
*
|
|
22
|
+
* `init.signal` bounds the whole sequence, backoff included, and the options are fixed when the
|
|
23
|
+
* wrapper is built. The request body must be replayable, which a string is.
|
|
24
|
+
*/
|
|
25
|
+
export function createRetryingFetch(options) {
|
|
26
|
+
return async (input, init) => {
|
|
27
|
+
let unread;
|
|
28
|
+
const release = async () => {
|
|
29
|
+
const response = unread;
|
|
30
|
+
unread = undefined;
|
|
31
|
+
await response?.body?.cancel().catch(() => undefined);
|
|
32
|
+
};
|
|
33
|
+
try {
|
|
34
|
+
return await retryProviderRequest(async () => {
|
|
35
|
+
await release();
|
|
36
|
+
const response = await send(input, init);
|
|
37
|
+
if (response.ok)
|
|
38
|
+
return response;
|
|
39
|
+
unread = response;
|
|
40
|
+
throw new AttemptFailure(`HTTP ${response.status}`, response);
|
|
41
|
+
}, {
|
|
42
|
+
maxRetries: options.maxRetries,
|
|
43
|
+
...(options.maxRetryDelayMs !== undefined ? { maxRetryDelayMs: options.maxRetryDelayMs } : {}),
|
|
44
|
+
...(init?.signal ? { signal: init.signal } : {}),
|
|
45
|
+
});
|
|
46
|
+
}
|
|
47
|
+
catch (error) {
|
|
48
|
+
if (error instanceof AttemptFailure) {
|
|
49
|
+
if (error.response !== undefined)
|
|
50
|
+
return error.response;
|
|
51
|
+
throw error.cause;
|
|
52
|
+
}
|
|
53
|
+
await release();
|
|
54
|
+
throw error;
|
|
55
|
+
}
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
async function send(input, init) {
|
|
59
|
+
try {
|
|
60
|
+
return await globalThis.fetch(input, init);
|
|
61
|
+
}
|
|
62
|
+
catch (cause) {
|
|
63
|
+
throw new AttemptFailure("connection failed", undefined, cause);
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
//# sourceMappingURL=retrying-fetch.js.map
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "operon-agents-core",
|
|
3
|
-
"version": "0.1.0-alpha.
|
|
3
|
+
"version": "0.1.0-alpha.25",
|
|
4
4
|
"description": "Internal engine for operon-agents. Prefer operon-agents for application code.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"engines": {
|
|
@@ -71,7 +71,7 @@
|
|
|
71
71
|
"README.md"
|
|
72
72
|
],
|
|
73
73
|
"dependencies": {
|
|
74
|
-
"@earendil-works/pi-ai": "1.
|
|
74
|
+
"@earendil-works/pi-ai": "1.5.0",
|
|
75
75
|
"@modelcontextprotocol/sdk": "^1.29.0",
|
|
76
76
|
"@opentelemetry/api": "^1.9.0",
|
|
77
77
|
"acorn": "^8.17.0",
|