@andorra-labs/code 0.1.15 → 0.1.16
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/src/agent-definitions.js +29 -6
- package/dist/src/agent-execution.js +4 -2
- package/dist/src/agent-mcp.d.ts +1 -1
- package/dist/src/agent-mcp.js +13 -9
- package/dist/src/app-server/protocol.d.ts +4 -1
- package/dist/src/app-server/protocol.js +1 -1
- package/dist/src/app-server.d.ts +107 -0
- package/dist/src/app-server.js +893 -22
- package/dist/src/auth/deployment.js +2 -2
- package/dist/src/browser-runner.js +1 -0
- package/dist/src/browser-ui/style.css +3 -3
- package/dist/src/browser-ui/tokens.css +27 -16
- package/dist/src/claude-provider.js +3 -1
- package/dist/src/cli.js +22 -8
- package/dist/src/codex-errors.js +4 -1
- package/dist/src/command-screens.js +5 -3
- package/dist/src/commands.d.ts +2 -1
- package/dist/src/compaction-phrases.d.ts +4 -0
- package/dist/src/compaction-phrases.js +20 -0
- package/dist/src/context-compaction.js +2 -1
- package/dist/src/decision/DecisionManager.js +3 -2
- package/dist/src/decision/requestPhrases.d.ts +4 -0
- package/dist/src/decision/requestPhrases.js +23 -0
- package/dist/src/github-inbox.d.ts +55 -0
- package/dist/src/github-inbox.js +153 -0
- package/dist/src/graph-health.js +7 -3
- package/dist/src/graph-provider-portability.js +32 -10
- package/dist/src/graph-quota.d.ts +29 -2
- package/dist/src/graph-quota.js +68 -10
- package/dist/src/graph-runner.js +24 -7
- package/dist/src/graph-server.d.ts +1 -1
- package/dist/src/graph-server.js +9 -7
- package/dist/src/graph-ui/app.js +110 -33
- package/dist/src/graph-ui/controls.css +1 -0
- package/dist/src/graph-ui/embed.js +2 -2
- package/dist/src/graph-ui/icons.js +1 -0
- package/dist/src/graph-ui/index.html +1 -1
- package/dist/src/graph-ui/manager.css +1 -1
- package/dist/src/graph-ui/manager.js +2 -2
- package/dist/src/graph-ui/sidebar.js +30 -0
- package/dist/src/graph-ui/studio-canvas.js +26 -13
- package/dist/src/graph-ui/studio.css +15 -7
- package/dist/src/graph-ui/studio.js +11 -4
- package/dist/src/graph-ui/style.css +77 -45
- package/dist/src/graph-ui/theme.js +3 -36
- package/dist/src/graph-ui/tokens.css +27 -19
- package/dist/src/graphs.js +4 -3
- package/dist/src/membership.d.ts +20 -1
- package/dist/src/membership.js +29 -4
- package/dist/src/model-metadata.d.ts +1 -1
- package/dist/src/model-metadata.js +4 -2
- package/dist/src/plan-pass.d.ts +59 -0
- package/dist/src/plan-pass.js +165 -0
- package/dist/src/provider-engine.js +3 -0
- package/dist/src/providers.d.ts +17 -0
- package/dist/src/providers.js +68 -19
- package/dist/src/pull-request-checks.d.ts +26 -0
- package/dist/src/pull-request-checks.js +56 -0
- package/dist/src/pull-request-conversation.d.ts +134 -0
- package/dist/src/pull-request-conversation.js +221 -0
- package/dist/src/pull-request-create.d.ts +175 -0
- package/dist/src/pull-request-create.js +392 -0
- package/dist/src/pull-request-details.d.ts +242 -0
- package/dist/src/pull-request-details.js +614 -0
- package/dist/src/pull-request-edit.d.ts +23 -0
- package/dist/src/pull-request-edit.js +91 -0
- package/dist/src/pull-request-logs.d.ts +76 -0
- package/dist/src/pull-request-logs.js +172 -0
- package/dist/src/pull-request-merge.d.ts +112 -0
- package/dist/src/pull-request-merge.js +258 -0
- package/dist/src/pull-request-review.d.ts +137 -0
- package/dist/src/pull-request-review.js +401 -0
- package/dist/src/pull-requests.d.ts +43 -2
- package/dist/src/pull-requests.js +112 -21
- package/dist/src/react-runtime.js +37 -4
- package/dist/src/remote/engine-pool.js +16 -4
- package/dist/src/run-control.d.ts +10 -0
- package/dist/src/run-control.js +24 -0
- package/dist/src/run-progress.d.ts +10 -0
- package/dist/src/run-progress.js +122 -0
- package/dist/src/run-records.d.ts +2 -2
- package/dist/src/runtime.d.ts +5 -1
- package/dist/src/runtime.js +14 -2
- package/dist/src/subagent-run.js +1 -0
- package/dist/src/telemetry/capture-core.d.ts +17 -0
- package/dist/src/telemetry/capture-core.js +59 -1
- package/dist/src/telemetry/classify.d.ts +3 -1
- package/dist/src/telemetry/classify.js +37 -0
- package/dist/src/telemetry/emitter.d.ts +2 -0
- package/dist/src/telemetry/emitter.js +42 -5
- package/dist/src/telemetry/schema.d.ts +22 -0
- package/dist/src/telemetry/schema.js +68 -1
- package/dist/src/telemetry/surface.d.ts +1 -0
- package/dist/src/telemetry/uploader.d.ts +6 -1
- package/dist/src/telemetry/uploader.js +22 -3
- package/dist/src/terminal-ui.js +1 -1
- package/dist/src/transcript.js +8 -2
- package/dist/src/types.d.ts +7 -0
- package/dist/src/usage-analytics.js +18 -10
- package/package.json +1 -1
package/dist/src/membership.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { type Graph } from './graphs.js';
|
|
2
|
+
import { readOfflinePlan } from './plan-pass.js';
|
|
2
3
|
import type { TelemetryPlan } from './telemetry/schema.js';
|
|
3
4
|
export declare const SOFTWARE_ENGINEER_HARNESS: Graph;
|
|
4
5
|
export declare const RETIRED_ANDORRA_SELECTION = ":andorra";
|
|
@@ -31,6 +32,8 @@ export interface Membership {
|
|
|
31
32
|
windowDecisionResetsAt?: string;
|
|
32
33
|
/** Uncapped Paid account: no daily, window or global cap applies. The service answers `unlimited: true` and omits every allowance field. */
|
|
33
34
|
unlimited?: boolean;
|
|
35
|
+
/** The plan comes from a stored, signed pass because the account service could not be reached. */
|
|
36
|
+
offline?: true;
|
|
34
37
|
billingUrl?: string;
|
|
35
38
|
}
|
|
36
39
|
export declare function membershipPlanLabel(tier: MembershipTier | undefined, paid: boolean): string;
|
|
@@ -48,13 +51,29 @@ export interface MembershipDependencies {
|
|
|
48
51
|
apiBaseUrl(): string;
|
|
49
52
|
fetch: typeof globalThis.fetch;
|
|
50
53
|
recordPlan?: (answer: PlanConfirmation, home?: string) => Promise<void>;
|
|
54
|
+
/** Keeps the signed pass an answer carried, for use while the service is unreachable. */
|
|
55
|
+
storePass?: (pass: unknown, subject: string, home: string, serverTime: number | undefined, plan: {
|
|
56
|
+
paid: boolean;
|
|
57
|
+
tier?: string;
|
|
58
|
+
}) => Promise<unknown>;
|
|
51
59
|
}
|
|
52
60
|
export declare function createMembershipClient(deps: MembershipDependencies): (signal?: AbortSignal, home?: string) => Promise<Membership>;
|
|
53
61
|
export declare const getMembership: (signal?: AbortSignal, home?: string) => Promise<Membership>;
|
|
62
|
+
/**
|
|
63
|
+
* The plan check for custom graphs. It is `getMembership`, except that when the account service
|
|
64
|
+
* cannot be reached a stored pass for the signed-in account stands in for the answer until the pass
|
|
65
|
+
* lapses. Hosted services still need the network; this only decides which graphs may be used.
|
|
66
|
+
*/
|
|
67
|
+
export declare function createGraphMembership(deps: {
|
|
68
|
+
membership: (signal?: AbortSignal, home?: string) => Promise<Membership>;
|
|
69
|
+
subject: () => Promise<string | undefined>;
|
|
70
|
+
readPlan?: typeof readOfflinePlan;
|
|
71
|
+
}): (signal?: AbortSignal, home?: string) => Promise<Membership>;
|
|
72
|
+
export declare const getGraphMembership: (signal?: AbortSignal, home?: string) => Promise<Membership>;
|
|
54
73
|
export declare function requirePaidMembership(signal?: AbortSignal): Promise<void>;
|
|
55
74
|
export declare function requireGraphMembership(signal?: AbortSignal): Promise<void>;
|
|
56
75
|
export declare function readGraphMembership(signal?: AbortSignal): Promise<Membership>;
|
|
57
|
-
export declare function loadAccessibleGraph(id?: string, signal?: AbortSignal, membership?: (signal?: AbortSignal
|
|
76
|
+
export declare function loadAccessibleGraph(id?: string, signal?: AbortSignal, membership?: (signal?: AbortSignal) => Promise<Membership>, options?: {
|
|
58
77
|
bindProviders?: boolean;
|
|
59
78
|
allowDeleted?: boolean;
|
|
60
79
|
allowRetired?: boolean;
|
package/dist/src/membership.js
CHANGED
|
@@ -1,13 +1,14 @@
|
|
|
1
1
|
import { DEFAULT_AGENT_GRAPH } from './default-graph.js';
|
|
2
2
|
import { DEFAULT_HARNESS, GRAPH_MANAGER_GRAPH_ID, GRAPH_MANAGER_HARNESS, GraphDeletedError, isDeletedGraph, loadGraph } from './graphs.js';
|
|
3
|
-
import { AUTH_REFRESH_BUDGET_MS, AuthError, getAccessToken, getAuthConfiguration } from './auth/index.js';
|
|
3
|
+
import { AUTH_REFRESH_BUDGET_MS, AuthError, getAccessToken, getAuthConfiguration, getAuthStatus } from './auth/index.js';
|
|
4
|
+
import { readOfflinePlan, storePlanPass } from './plan-pass.js';
|
|
4
5
|
import { graphStorageDirectory } from './graph-account.js';
|
|
5
6
|
import { configDirectory, loadConfig } from './config.js';
|
|
6
7
|
import { analyticsPlanFromMembership, resolveAnalyticsConfig } from './analytics.js';
|
|
7
8
|
import { recordConfirmedPlan } from './telemetry/state.js';
|
|
8
9
|
import { telemetryDirectory } from './telemetry/identity.js';
|
|
9
10
|
import { bindPortableGraphProviders } from './graph-provider-portability.js';
|
|
10
|
-
import { loadFreeTierGraph } from './graph-quota.js';
|
|
11
|
+
import { loadFreeTierGraph, notePremiumGraphAccount } from './graph-quota.js';
|
|
11
12
|
export const SOFTWARE_ENGINEER_HARNESS = {
|
|
12
13
|
schemaVersion: 2, id: 'software-engineer', name: DEFAULT_AGENT_GRAPH.name, revision: 1, entry: DEFAULT_AGENT_GRAPH.entry,
|
|
13
14
|
nodes: structuredClone(DEFAULT_AGENT_GRAPH.nodes), edges: structuredClone(DEFAULT_AGENT_GRAPH.edges),
|
|
@@ -158,6 +159,8 @@ export function createMembershipClient(deps) {
|
|
|
158
159
|
? result.tier : undefined;
|
|
159
160
|
const observedAt = new Date().toISOString();
|
|
160
161
|
await (deps.recordPlan ?? recordPlanConfirmation)({ subject: result.subject, tier: analyticsPlanFromMembership(tier, result.paid), observedAt }, home).catch(() => { });
|
|
162
|
+
const served = Date.parse(response.headers?.get?.('date') ?? '');
|
|
163
|
+
await (deps.storePass ?? ((pass, subject, directory, serverTime, plan) => storePlanPass(pass, subject, directory, { serverTime, plan })))(result.pass, result.subject, home ?? configDirectory(), Number.isFinite(served) ? served : undefined, { paid: result.paid, ...(tier ? { tier } : {}) }).catch(() => { });
|
|
161
164
|
const windowed = windowFields(result);
|
|
162
165
|
const unlimited = typeof result.unlimited === 'boolean' ? result.unlimited : undefined;
|
|
163
166
|
const lifetime = Number.isSafeInteger(result.decisionsSinceRollout) && result.decisionsSinceRollout >= 0
|
|
@@ -187,6 +190,26 @@ export const getMembership = createMembershipClient({
|
|
|
187
190
|
accessToken: getAccessToken, apiBaseUrl: () => getAuthConfiguration().apiBaseUrl,
|
|
188
191
|
fetch: (...args) => globalThis.fetch(...args),
|
|
189
192
|
});
|
|
193
|
+
/**
|
|
194
|
+
* The plan check for custom graphs. It is `getMembership`, except that when the account service
|
|
195
|
+
* cannot be reached a stored pass for the signed-in account stands in for the answer until the pass
|
|
196
|
+
* lapses. Hosted services still need the network; this only decides which graphs may be used.
|
|
197
|
+
*/
|
|
198
|
+
export function createGraphMembership(deps) {
|
|
199
|
+
return async (signal, home) => {
|
|
200
|
+
const access = await deps.membership(signal, home);
|
|
201
|
+
if (!access.unavailable)
|
|
202
|
+
return access;
|
|
203
|
+
signal?.throwIfAborted();
|
|
204
|
+
const subject = await deps.subject().catch(() => undefined);
|
|
205
|
+
const plan = await (deps.readPlan ?? readOfflinePlan)(subject, home ?? configDirectory()).catch(() => undefined);
|
|
206
|
+
return plan ? { paid: plan.paid, tier: plan.tier, subject: plan.subject, offline: true } : access;
|
|
207
|
+
};
|
|
208
|
+
}
|
|
209
|
+
export const getGraphMembership = createGraphMembership({
|
|
210
|
+
membership: (signal, home) => getMembership(signal, home),
|
|
211
|
+
subject: async () => (await getAuthStatus()).subject,
|
|
212
|
+
});
|
|
190
213
|
export async function requirePaidMembership(signal) {
|
|
191
214
|
const access = await getMembership(signal);
|
|
192
215
|
if (!access.paid)
|
|
@@ -196,12 +219,12 @@ export async function requireGraphMembership(signal) {
|
|
|
196
219
|
await readGraphMembership(signal);
|
|
197
220
|
}
|
|
198
221
|
export async function readGraphMembership(signal) {
|
|
199
|
-
const access = await
|
|
222
|
+
const access = await getGraphMembership(signal);
|
|
200
223
|
if (!access.paid && !access.subject)
|
|
201
224
|
throw PaidMembershipRequiredError.for(access);
|
|
202
225
|
return access;
|
|
203
226
|
}
|
|
204
|
-
export async function loadAccessibleGraph(id = 'default', signal, membership =
|
|
227
|
+
export async function loadAccessibleGraph(id = 'default', signal, membership = getGraphMembership, options = {}) {
|
|
205
228
|
signal?.throwIfAborted();
|
|
206
229
|
if (id === RETIRED_ANDORRA_SELECTION && options.allowRetired) {
|
|
207
230
|
const access = await membership(signal);
|
|
@@ -223,6 +246,8 @@ export async function loadAccessibleGraph(id = 'default', signal, membership = g
|
|
|
223
246
|
if (!/^[A-Za-z0-9-]{1,128}$/.test(access.subject))
|
|
224
247
|
throw new PaidMembershipRequiredError();
|
|
225
248
|
const directory = await graphStorageDirectory(undefined, access.subject);
|
|
249
|
+
if (access.paid)
|
|
250
|
+
await notePremiumGraphAccount(directory);
|
|
226
251
|
const graph = access.paid ? await loadGraph(id, undefined, directory) : await loadFreeTierGraph(id, directory);
|
|
227
252
|
if (!options.allowDeleted && isDeletedGraph(graph))
|
|
228
253
|
throw new GraphDeletedError(graph.name);
|
|
@@ -4,7 +4,7 @@ export interface ModelMetadata {
|
|
|
4
4
|
contextWindow?: number;
|
|
5
5
|
}
|
|
6
6
|
export declare function resolveModelContext(provider: ProviderConfig, model: string | undefined, signal: AbortSignal): Promise<ProviderConfig>;
|
|
7
|
-
export declare function configuredModelSnapshot(provider: ProviderConfig,
|
|
7
|
+
export declare function configuredModelSnapshot(provider: ProviderConfig, requested: string | undefined): ProviderConfig;
|
|
8
8
|
export declare function withEvaluationReasoningEffort(snapshot: ProviderConfig, effort: string | undefined): ProviderConfig;
|
|
9
9
|
export declare function refreshModelContext(provider: ProviderConfig, signal: AbortSignal): Promise<ProviderConfig>;
|
|
10
10
|
/** What the provider lists, with Andorra-known Claude windows filled in where the listing gives none. */
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { configuredContextWindow, deadlinePhrase, MODEL_LISTING_TIMEOUT_MS } from './providers.js';
|
|
1
|
+
import { configuredContextWindow, deadlinePhrase, MODEL_LISTING_TIMEOUT_MS, providerModelId } from './providers.js';
|
|
2
2
|
import { providerAuthHeaders } from './anthropic-credentials.js';
|
|
3
3
|
import { validateConfig } from './config.js';
|
|
4
4
|
import { readOpenCodeModels } from './opencode-catalog.js';
|
|
@@ -14,7 +14,9 @@ import { createHostedClient } from './andorra/hosted.js';
|
|
|
14
14
|
export async function resolveModelContext(provider, model, signal) {
|
|
15
15
|
return refreshModelContext(configuredModelSnapshot(provider, model), signal);
|
|
16
16
|
}
|
|
17
|
-
export function configuredModelSnapshot(provider,
|
|
17
|
+
export function configuredModelSnapshot(provider, requested) {
|
|
18
|
+
// A model the provider lists in another case is requested in the provider's own spelling.
|
|
19
|
+
const model = requested === undefined ? undefined : providerModelId(provider, requested) ?? requested;
|
|
18
20
|
const snapshot = { ...provider };
|
|
19
21
|
if (model !== undefined && model !== snapshot.model) {
|
|
20
22
|
snapshot.model = model;
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The offline plan pass.
|
|
3
|
+
*
|
|
4
|
+
* When the account service answers a plan check it also returns a pass: the account, its plan, when
|
|
5
|
+
* the pass was issued and when it lapses, signed with a key whose private half stays in the
|
|
6
|
+
* service's key store. This module checks that signature with the public half, so a pass whose
|
|
7
|
+
* dates were edited on disk is rejected, and lets a valid pass stand in for the plan check while the
|
|
8
|
+
* service cannot be reached.
|
|
9
|
+
*
|
|
10
|
+
* The clock is not trusted. Beside the pass the file keeps the latest time this machine has seen,
|
|
11
|
+
* which only moves forward, and a system clock earlier than that is treated as tampering. A machine
|
|
12
|
+
* its owner controls can still restore both the pass and that record from a copy; this stops an
|
|
13
|
+
* edited date and a moved clock, not a restored backup.
|
|
14
|
+
*/
|
|
15
|
+
/** Public keys that sign passes, as base64 DER (SubjectPublicKeyInfo), newest first. Empty until the key exists. */
|
|
16
|
+
export declare const PLAN_PASS_KEYS: readonly string[];
|
|
17
|
+
export type PlanPassTier = 'free' | 'legacy' | 'paid';
|
|
18
|
+
export interface PlanPass {
|
|
19
|
+
subject: string;
|
|
20
|
+
tier: PlanPassTier;
|
|
21
|
+
paid: boolean;
|
|
22
|
+
issuedAt: number;
|
|
23
|
+
expiresAt: number;
|
|
24
|
+
}
|
|
25
|
+
export interface OfflinePlan extends PlanPass {
|
|
26
|
+
offline: true;
|
|
27
|
+
}
|
|
28
|
+
/** The claims of a pass one of `keys` signed, in milliseconds, or undefined for anything else. */
|
|
29
|
+
export declare function verifyPlanPass(token: unknown, keys?: readonly string[]): PlanPass | undefined;
|
|
30
|
+
/**
|
|
31
|
+
* Keeps the pass an online plan check returned. `serverTime` is the service's own clock from that
|
|
32
|
+
* answer; it replaces the latest time seen, so a machine whose clock once ran ahead recovers the
|
|
33
|
+
* next time it is online. A pass that does not verify, names another account, or disagrees with
|
|
34
|
+
* the `plan` the service just answered is not kept.
|
|
35
|
+
*
|
|
36
|
+
* When the answer brings no pass worth keeping, a pass already stored survives only if it still
|
|
37
|
+
* says what the service just said. A downgrade the service confirmed therefore ends the old pass at
|
|
38
|
+
* once, even when the service could not sign a new one.
|
|
39
|
+
*/
|
|
40
|
+
export declare function storePlanPass(token: unknown, subject: string, home: string, options?: {
|
|
41
|
+
serverTime?: number;
|
|
42
|
+
now?: number;
|
|
43
|
+
keys?: readonly string[];
|
|
44
|
+
plan?: {
|
|
45
|
+
paid: boolean;
|
|
46
|
+
tier?: string;
|
|
47
|
+
};
|
|
48
|
+
}): Promise<boolean>;
|
|
49
|
+
/**
|
|
50
|
+
* The plan a stored pass grants `subject` right now, while the service cannot be reached.
|
|
51
|
+
*
|
|
52
|
+
* Nothing is granted when the pass does not verify, names another account, has lapsed, when the
|
|
53
|
+
* record of the latest time seen is missing, or when the system clock is behind that record. Each
|
|
54
|
+
* use moves the record forward, so time spent offline is not handed back by turning the clock back.
|
|
55
|
+
*/
|
|
56
|
+
export declare function readOfflinePlan(subject: string | undefined, home: string, options?: {
|
|
57
|
+
now?: number;
|
|
58
|
+
keys?: readonly string[];
|
|
59
|
+
}): Promise<OfflinePlan | undefined>;
|
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
import { createPublicKey, randomBytes, verify } from 'node:crypto';
|
|
2
|
+
import { mkdir, readFile, rename, unlink, writeFile } from 'node:fs/promises';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
/**
|
|
5
|
+
* The offline plan pass.
|
|
6
|
+
*
|
|
7
|
+
* When the account service answers a plan check it also returns a pass: the account, its plan, when
|
|
8
|
+
* the pass was issued and when it lapses, signed with a key whose private half stays in the
|
|
9
|
+
* service's key store. This module checks that signature with the public half, so a pass whose
|
|
10
|
+
* dates were edited on disk is rejected, and lets a valid pass stand in for the plan check while the
|
|
11
|
+
* service cannot be reached.
|
|
12
|
+
*
|
|
13
|
+
* The clock is not trusted. Beside the pass the file keeps the latest time this machine has seen,
|
|
14
|
+
* which only moves forward, and a system clock earlier than that is treated as tampering. A machine
|
|
15
|
+
* its owner controls can still restore both the pass and that record from a copy; this stops an
|
|
16
|
+
* edited date and a moved clock, not a restored backup.
|
|
17
|
+
*/
|
|
18
|
+
/** Public keys that sign passes, as base64 DER (SubjectPublicKeyInfo), newest first. Empty until the key exists. */
|
|
19
|
+
export const PLAN_PASS_KEYS = [];
|
|
20
|
+
/** A pass never grants more than this, whatever it says: the service caps a pass at 31 days. */
|
|
21
|
+
const MAX_LIFETIME_MS = 32 * 86_400_000;
|
|
22
|
+
/** How far behind the latest time seen the system clock may be: ordinary drift and time-zone fixes. */
|
|
23
|
+
const CLOCK_SLACK_MS = 5 * 60_000;
|
|
24
|
+
const FILE = 'plan-pass.json';
|
|
25
|
+
function importKeys(keys) {
|
|
26
|
+
const imported = [];
|
|
27
|
+
for (const key of keys) {
|
|
28
|
+
try {
|
|
29
|
+
imported.push(createPublicKey({ key: Buffer.from(key, 'base64'), format: 'der', type: 'spki' }));
|
|
30
|
+
}
|
|
31
|
+
catch { /* an unusable key signs nothing */ }
|
|
32
|
+
}
|
|
33
|
+
return imported;
|
|
34
|
+
}
|
|
35
|
+
/** The claims of a pass one of `keys` signed, in milliseconds, or undefined for anything else. */
|
|
36
|
+
export function verifyPlanPass(token, keys = PLAN_PASS_KEYS) {
|
|
37
|
+
if (typeof token !== 'string' || token.length > 4096)
|
|
38
|
+
return undefined;
|
|
39
|
+
const parts = token.split('.');
|
|
40
|
+
if (parts.length !== 2 || !parts.every(part => /^[A-Za-z0-9_-]+$/.test(part)))
|
|
41
|
+
return undefined;
|
|
42
|
+
const signature = Buffer.from(parts[1], 'base64url');
|
|
43
|
+
if (!importKeys(keys).some(key => { try {
|
|
44
|
+
return verify('sha256', Buffer.from(parts[0], 'ascii'), key, signature);
|
|
45
|
+
}
|
|
46
|
+
catch {
|
|
47
|
+
return false;
|
|
48
|
+
} }))
|
|
49
|
+
return undefined;
|
|
50
|
+
let claims;
|
|
51
|
+
try {
|
|
52
|
+
claims = JSON.parse(Buffer.from(parts[0], 'base64url').toString('utf8'));
|
|
53
|
+
}
|
|
54
|
+
catch {
|
|
55
|
+
return undefined;
|
|
56
|
+
}
|
|
57
|
+
if (!claims || typeof claims !== 'object' || Array.isArray(claims))
|
|
58
|
+
return undefined;
|
|
59
|
+
const { v, sub, tier, paid, iat, exp } = claims;
|
|
60
|
+
if (v !== 1 || typeof sub !== 'string' || !/^[A-Za-z0-9-]{1,128}$/.test(sub))
|
|
61
|
+
return undefined;
|
|
62
|
+
if (tier !== 'free' && tier !== 'legacy' && tier !== 'paid')
|
|
63
|
+
return undefined;
|
|
64
|
+
if (paid !== (tier !== 'free'))
|
|
65
|
+
return undefined;
|
|
66
|
+
if (!Number.isSafeInteger(iat) || !Number.isSafeInteger(exp) || iat <= 0 || exp <= iat)
|
|
67
|
+
return undefined;
|
|
68
|
+
const issuedAt = iat * 1000, expiresAt = exp * 1000;
|
|
69
|
+
if (expiresAt - issuedAt > MAX_LIFETIME_MS)
|
|
70
|
+
return undefined;
|
|
71
|
+
return { subject: sub, tier, paid, issuedAt, expiresAt };
|
|
72
|
+
}
|
|
73
|
+
async function readStored(home) {
|
|
74
|
+
try {
|
|
75
|
+
const value = JSON.parse(await readFile(join(home, FILE), 'utf8'));
|
|
76
|
+
if (!value || typeof value !== 'object')
|
|
77
|
+
return undefined;
|
|
78
|
+
const { pass, lastSeen } = value;
|
|
79
|
+
return typeof pass === 'string' && Number.isSafeInteger(lastSeen) && lastSeen > 0 ? { pass, lastSeen: lastSeen } : undefined;
|
|
80
|
+
}
|
|
81
|
+
catch {
|
|
82
|
+
return undefined;
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
async function writeStored(home, stored) {
|
|
86
|
+
await mkdir(home, { recursive: true });
|
|
87
|
+
// Each write stages its own file: two plan checks finishing together must not share one.
|
|
88
|
+
const path = join(home, FILE), staged = `${path}.${process.pid}.${randomBytes(6).toString('hex')}.tmp`;
|
|
89
|
+
try {
|
|
90
|
+
await writeFile(staged, JSON.stringify(stored), { mode: 0o600 });
|
|
91
|
+
await rename(staged, path);
|
|
92
|
+
}
|
|
93
|
+
catch (error) {
|
|
94
|
+
await unlink(staged).catch(() => { });
|
|
95
|
+
throw error;
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
/** One read-and-update of a home's record at a time in this process, so none works from a stale copy. */
|
|
99
|
+
const queues = new Map();
|
|
100
|
+
function serial(home, task) {
|
|
101
|
+
const run = (queues.get(home) ?? Promise.resolve()).then(task, task);
|
|
102
|
+
const settled = run.catch(() => { });
|
|
103
|
+
queues.set(home, settled);
|
|
104
|
+
void settled.then(() => { if (queues.get(home) === settled)
|
|
105
|
+
queues.delete(home); });
|
|
106
|
+
return run;
|
|
107
|
+
}
|
|
108
|
+
/**
|
|
109
|
+
* Keeps the pass an online plan check returned. `serverTime` is the service's own clock from that
|
|
110
|
+
* answer; it replaces the latest time seen, so a machine whose clock once ran ahead recovers the
|
|
111
|
+
* next time it is online. A pass that does not verify, names another account, or disagrees with
|
|
112
|
+
* the `plan` the service just answered is not kept.
|
|
113
|
+
*
|
|
114
|
+
* When the answer brings no pass worth keeping, a pass already stored survives only if it still
|
|
115
|
+
* says what the service just said. A downgrade the service confirmed therefore ends the old pass at
|
|
116
|
+
* once, even when the service could not sign a new one.
|
|
117
|
+
*/
|
|
118
|
+
export function storePlanPass(token, subject, home, options = {}) {
|
|
119
|
+
const agrees = (pass) => pass !== undefined && pass.subject === subject
|
|
120
|
+
&& (options.plan === undefined || (pass.paid === options.plan.paid && (options.plan.tier === undefined || pass.tier === options.plan.tier)));
|
|
121
|
+
return serial(home, async () => {
|
|
122
|
+
const pass = verifyPlanPass(token, options.keys);
|
|
123
|
+
if (!agrees(pass)) {
|
|
124
|
+
const stored = await readStored(home);
|
|
125
|
+
if (stored && !agrees(verifyPlanPass(stored.pass, options.keys)))
|
|
126
|
+
await unlink(join(home, FILE)).catch(() => { });
|
|
127
|
+
return false;
|
|
128
|
+
}
|
|
129
|
+
const now = options.now ?? Date.now();
|
|
130
|
+
const serverTime = options.serverTime !== undefined && Number.isFinite(options.serverTime) ? options.serverTime : undefined;
|
|
131
|
+
await writeStored(home, { pass: token, lastSeen: Math.max(serverTime ?? now, pass.issuedAt) });
|
|
132
|
+
return true;
|
|
133
|
+
});
|
|
134
|
+
}
|
|
135
|
+
/**
|
|
136
|
+
* The plan a stored pass grants `subject` right now, while the service cannot be reached.
|
|
137
|
+
*
|
|
138
|
+
* Nothing is granted when the pass does not verify, names another account, has lapsed, when the
|
|
139
|
+
* record of the latest time seen is missing, or when the system clock is behind that record. Each
|
|
140
|
+
* use moves the record forward, so time spent offline is not handed back by turning the clock back.
|
|
141
|
+
*/
|
|
142
|
+
export function readOfflinePlan(subject, home, options = {}) {
|
|
143
|
+
return serial(home, () => readOfflinePlanNow(subject, home, options));
|
|
144
|
+
}
|
|
145
|
+
async function readOfflinePlanNow(subject, home, options) {
|
|
146
|
+
if (!subject)
|
|
147
|
+
return undefined;
|
|
148
|
+
const stored = await readStored(home);
|
|
149
|
+
if (!stored)
|
|
150
|
+
return undefined;
|
|
151
|
+
const pass = verifyPlanPass(stored.pass, options.keys);
|
|
152
|
+
if (!pass || pass.subject !== subject)
|
|
153
|
+
return undefined;
|
|
154
|
+
const now = options.now ?? Date.now();
|
|
155
|
+
const floor = Math.max(stored.lastSeen, pass.issuedAt);
|
|
156
|
+
if (now < floor - CLOCK_SLACK_MS)
|
|
157
|
+
return undefined;
|
|
158
|
+
const current = Math.max(now, floor);
|
|
159
|
+
// Recorded before the expiry is judged: a pass seen lapsed stays lapsed when the clock is moved back.
|
|
160
|
+
if (current > stored.lastSeen)
|
|
161
|
+
await writeStored(home, { pass: stored.pass, lastSeen: current }).catch(() => { });
|
|
162
|
+
if (current >= pass.expiresAt)
|
|
163
|
+
return undefined;
|
|
164
|
+
return { ...pass, offline: true };
|
|
165
|
+
}
|
|
@@ -228,13 +228,16 @@ export async function generateEngineResponse(request, host) {
|
|
|
228
228
|
const status = error.status;
|
|
229
229
|
if (status !== 400 && status !== 422)
|
|
230
230
|
throw error;
|
|
231
|
+
const recovered = () => request.onRecoveredError?.(`http_${status}`);
|
|
231
232
|
if (body.tool_choice !== undefined) {
|
|
232
233
|
const { tool_choice: _choice, ...unforced } = body;
|
|
234
|
+
recovered();
|
|
233
235
|
return sendWithFallbacks(unforced);
|
|
234
236
|
}
|
|
235
237
|
if (host.streamingDisabled?.())
|
|
236
238
|
throw error;
|
|
237
239
|
const { stream_options: _options, ...plain } = body;
|
|
240
|
+
recovered();
|
|
238
241
|
return host.send({ ...plain, stream: false });
|
|
239
242
|
}
|
|
240
243
|
};
|
package/dist/src/providers.d.ts
CHANGED
|
@@ -57,6 +57,14 @@ export declare function freeCodexAccountSlot(base: string, providers: readonly P
|
|
|
57
57
|
export declare function freeDraftCodexAccountSlot(base: string, draft: readonly Pick<ProviderConfig, 'id' | 'codexAccount'>[], saved: readonly Pick<ProviderConfig, 'id' | 'codexAccount'>[]): string;
|
|
58
58
|
export declare function allocateCodexAccountSlots(stored: readonly ProviderConfig[], next: readonly ProviderConfig[]): ProviderConfig[];
|
|
59
59
|
export declare function providerModels(provider: Pick<ProviderConfig, 'model' | 'models'>): string[];
|
|
60
|
+
/**
|
|
61
|
+
* Provider and model ids are matched without regard to case, so a graph saved on a machine whose provider is "GX10"
|
|
62
|
+
* runs on a machine that calls the same provider "gx10". An exact match always wins; otherwise the one entry whose id
|
|
63
|
+
* differs only in case is taken, and none when several do. Callers use the returned entry's own spelling from then on.
|
|
64
|
+
*/
|
|
65
|
+
export declare function findProviderById<P extends Pick<ProviderConfig, 'id'>>(providers: readonly P[], id: string | undefined): P | undefined;
|
|
66
|
+
/** The provider's own spelling of `model`, matched as findProviderById matches ids; undefined when it does not offer it. */
|
|
67
|
+
export declare function providerModelId(provider: Pick<ProviderConfig, 'model' | 'models'>, model: string): string | undefined;
|
|
60
68
|
export declare function configuredContextWindow(provider: Pick<ProviderConfig, 'model' | 'modelContextWindows'>, model: string | undefined): number | undefined;
|
|
61
69
|
export declare function applyModelContextWindow(provider: ProviderConfig, model: string): void;
|
|
62
70
|
export declare function providerSecrets(providers: ProviderConfig[], env?: NodeJS.ProcessEnv): string[];
|
|
@@ -69,8 +77,17 @@ export declare class ProviderRequestError extends Error {
|
|
|
69
77
|
readonly contextOverflow: boolean;
|
|
70
78
|
/** The system error code behind a connection that could not be made; recorded with the failure, never part of the message. */
|
|
71
79
|
connectionCause?: string;
|
|
80
|
+
/** What kind of failure this was, for telemetry (`provider_timeout`, `http_429`); never shown and never part of the message. */
|
|
81
|
+
telemetryCode?: string;
|
|
72
82
|
constructor(message: string, contextOverflow?: boolean);
|
|
73
83
|
}
|
|
84
|
+
/**
|
|
85
|
+
* The telemetry error code for an error that ended a run: a provider failure's code, a record-only
|
|
86
|
+
* `telemetryCode` another adapter attached (Claude's exhausted malformed steps), or `runtime_error`.
|
|
87
|
+
*/
|
|
88
|
+
export declare function runFailureCode(error: unknown): string;
|
|
89
|
+
/** The telemetry error code for a failed provider request: an OS code, a named kind, or `http_<status>`. */
|
|
90
|
+
export declare function providerFailureCode(error: unknown): string;
|
|
74
91
|
export declare const BLANK_TOOL_CALL_LIMIT = 4096;
|
|
75
92
|
export declare function createBlankToolCallGuard(limit?: number): {
|
|
76
93
|
fragment(text: string): void;
|
package/dist/src/providers.js
CHANGED
|
@@ -128,6 +128,30 @@ export function providerModels(provider) {
|
|
|
128
128
|
return provider.models.filter(model => model.trim());
|
|
129
129
|
return provider.model.trim() ? [provider.model] : [];
|
|
130
130
|
}
|
|
131
|
+
/**
|
|
132
|
+
* Provider and model ids are matched without regard to case, so a graph saved on a machine whose provider is "GX10"
|
|
133
|
+
* runs on a machine that calls the same provider "gx10". An exact match always wins; otherwise the one entry whose id
|
|
134
|
+
* differs only in case is taken, and none when several do. Callers use the returned entry's own spelling from then on.
|
|
135
|
+
*/
|
|
136
|
+
export function findProviderById(providers, id) {
|
|
137
|
+
if (id === undefined)
|
|
138
|
+
return undefined;
|
|
139
|
+
const exact = providers.find(provider => provider.id === id);
|
|
140
|
+
if (exact !== undefined)
|
|
141
|
+
return exact;
|
|
142
|
+
const folded = id.toLowerCase();
|
|
143
|
+
const matches = providers.filter(provider => typeof provider.id === 'string' && provider.id.toLowerCase() === folded);
|
|
144
|
+
return matches.length === 1 ? matches[0] : undefined;
|
|
145
|
+
}
|
|
146
|
+
/** The provider's own spelling of `model`, matched as findProviderById matches ids; undefined when it does not offer it. */
|
|
147
|
+
export function providerModelId(provider, model) {
|
|
148
|
+
const offered = [provider.model, ...(provider.models ?? [])].filter(item => typeof item === 'string' && item.trim());
|
|
149
|
+
if (offered.includes(model))
|
|
150
|
+
return model;
|
|
151
|
+
const folded = model.toLowerCase();
|
|
152
|
+
const matches = [...new Set(offered.filter(item => item.toLowerCase() === folded))];
|
|
153
|
+
return matches.length === 1 ? matches[0] : undefined;
|
|
154
|
+
}
|
|
131
155
|
export function configuredContextWindow(provider, model) {
|
|
132
156
|
const id = model ?? provider.model;
|
|
133
157
|
if (!provider.modelContextWindows || !Object.hasOwn(provider.modelContextWindows, id))
|
|
@@ -214,12 +238,38 @@ export class ProviderRequestError extends Error {
|
|
|
214
238
|
contextOverflow;
|
|
215
239
|
/** The system error code behind a connection that could not be made; recorded with the failure, never part of the message. */
|
|
216
240
|
connectionCause;
|
|
241
|
+
/** What kind of failure this was, for telemetry (`provider_timeout`, `http_429`); never shown and never part of the message. */
|
|
242
|
+
telemetryCode;
|
|
217
243
|
constructor(message, contextOverflow = false) {
|
|
218
244
|
super(message);
|
|
219
245
|
this.contextOverflow = contextOverflow;
|
|
220
246
|
this.name = 'Error';
|
|
221
247
|
}
|
|
222
248
|
}
|
|
249
|
+
function coded(error, code) { error.telemetryCode = code; return error; }
|
|
250
|
+
/**
|
|
251
|
+
* The telemetry error code for an error that ended a run: a provider failure's code, a record-only
|
|
252
|
+
* `telemetryCode` another adapter attached (Claude's exhausted malformed steps), or `runtime_error`.
|
|
253
|
+
*/
|
|
254
|
+
export function runFailureCode(error) {
|
|
255
|
+
if (error instanceof ProviderRequestError)
|
|
256
|
+
return providerFailureCode(error);
|
|
257
|
+
const code = error?.telemetryCode;
|
|
258
|
+
return typeof code === 'string' && code ? code : 'runtime_error';
|
|
259
|
+
}
|
|
260
|
+
/** The telemetry error code for a failed provider request: an OS code, a named kind, or `http_<status>`. */
|
|
261
|
+
export function providerFailureCode(error) {
|
|
262
|
+
if (!(error instanceof ProviderRequestError))
|
|
263
|
+
return 'provider_error';
|
|
264
|
+
if (error.connectionCause)
|
|
265
|
+
return error.connectionCause;
|
|
266
|
+
if (error.telemetryCode)
|
|
267
|
+
return error.telemetryCode;
|
|
268
|
+
if (error.contextOverflow)
|
|
269
|
+
return 'context_overflow';
|
|
270
|
+
const status = error.status;
|
|
271
|
+
return typeof status === 'number' && Number.isInteger(status) && status >= 100 && status <= 599 ? `http_${status}` : 'provider_error';
|
|
272
|
+
}
|
|
223
273
|
class RetryableProviderError extends ProviderRequestError {
|
|
224
274
|
retryAfterMs;
|
|
225
275
|
retryDelaysMs;
|
|
@@ -235,13 +285,13 @@ class RetryableProviderError extends ProviderRequestError {
|
|
|
235
285
|
}
|
|
236
286
|
}
|
|
237
287
|
class MalformedResponseProviderError extends RetryableProviderError {
|
|
238
|
-
constructor() { super(MALFORMED_RESPONSE_MESSAGE, 0, MALFORMED_RESPONSE_RETRY_DELAYS_MS, MALFORMED_RESPONSE_RETRIES, true); }
|
|
288
|
+
constructor() { super(MALFORMED_RESPONSE_MESSAGE, 0, MALFORMED_RESPONSE_RETRY_DELAYS_MS, MALFORMED_RESPONSE_RETRIES, true); this.telemetryCode = 'malformed_response'; }
|
|
239
289
|
}
|
|
240
290
|
class MalformedStreamProviderError extends MalformedResponseProviderError {
|
|
241
291
|
}
|
|
242
292
|
export const BLANK_TOOL_CALL_LIMIT = 4096;
|
|
243
293
|
class BlankToolCallProviderError extends RetryableProviderError {
|
|
244
|
-
constructor() { super('Provider streamed a tool call that kept generating blank output.', 0, MALFORMED_STREAM_RETRY_DELAYS_MS, MALFORMED_STREAM_RETRIES); }
|
|
294
|
+
constructor() { super('Provider streamed a tool call that kept generating blank output.', 0, MALFORMED_STREAM_RETRY_DELAYS_MS, MALFORMED_STREAM_RETRIES); this.telemetryCode = 'blank_tool_call'; }
|
|
245
295
|
}
|
|
246
296
|
export function createBlankToolCallGuard(limit = BLANK_TOOL_CALL_LIMIT) {
|
|
247
297
|
let blank = 0;
|
|
@@ -302,7 +352,7 @@ async function boundedJson(response) {
|
|
|
302
352
|
let bytes = 0;
|
|
303
353
|
try {
|
|
304
354
|
while (true) {
|
|
305
|
-
const chunk = await reader.read().catch(() => { throw new RetryableProviderError('Provider connection failed while reading its response.'); });
|
|
355
|
+
const chunk = await reader.read().catch(() => { throw coded(new RetryableProviderError('Provider connection failed while reading its response.'), 'stream_interrupted'); });
|
|
306
356
|
if (chunk.done)
|
|
307
357
|
break;
|
|
308
358
|
if (chunk.value.byteLength > buffer.length - bytes) {
|
|
@@ -704,7 +754,7 @@ function createAnthropicStreamAccumulator(now = Date.now) {
|
|
|
704
754
|
},
|
|
705
755
|
finish(requests, completionAdvertised) {
|
|
706
756
|
if (!started || !stopped || !finishReason)
|
|
707
|
-
throw new RetryableProviderError('Provider closed the stream before the response completed.');
|
|
757
|
+
throw coded(new RetryableProviderError('Provider closed the stream before the response completed.'), 'stream_interrupted');
|
|
708
758
|
const ordered = [...blocks.entries()].sort(([a], [b]) => a - b).map(([, block]) => block);
|
|
709
759
|
const text = ordered.filter(block => block.type === 'text').map(block => block.text).join('\n');
|
|
710
760
|
const measured = decodeWindow();
|
|
@@ -773,7 +823,7 @@ export function createAdapter(config, options = {}) {
|
|
|
773
823
|
if (signal.aborted)
|
|
774
824
|
cancelled();
|
|
775
825
|
if (authDeadline?.aborted)
|
|
776
|
-
throw new RetryableProviderError('Provider request timed out.');
|
|
826
|
+
throw coded(new RetryableProviderError('Provider request timed out.'), 'provider_timeout');
|
|
777
827
|
throw error;
|
|
778
828
|
}
|
|
779
829
|
const headers = { 'content-type': 'application/json', ...sessionHeader, ...credential };
|
|
@@ -803,19 +853,18 @@ export function createAdapter(config, options = {}) {
|
|
|
803
853
|
if (signal.aborted)
|
|
804
854
|
throw new Error('Provider request cancelled.');
|
|
805
855
|
if (deadline?.aborted)
|
|
806
|
-
throw new RetryableProviderError('Provider request timed out.');
|
|
856
|
+
throw coded(new RetryableProviderError('Provider request timed out.'), 'provider_timeout');
|
|
807
857
|
// A connection that could not be made is not one of the router's refusals: it gets the usual bounded
|
|
808
858
|
// retries, and the plain sentence (no address, no error code) while retrying and when they run out.
|
|
809
859
|
if (andorra) {
|
|
810
860
|
const failure = permanentConnectionFailure(error) ? new ProviderRequestError(ANDORRA_UNAVAILABLE_MESSAGE) : new RetryableProviderError(ANDORRA_UNAVAILABLE_MESSAGE);
|
|
811
861
|
failure.connectionCause = connectionFailureDetail(error);
|
|
812
|
-
throw failure;
|
|
862
|
+
throw coded(failure, 'connection_failed');
|
|
813
863
|
}
|
|
814
864
|
const cause = connectionFailureDetail(error);
|
|
815
865
|
const message = `Provider connection failed${cause ? ` (${cause})` : ''}. Check its URL and network connection.`;
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
throw new RetryableProviderError(message);
|
|
866
|
+
const failure = permanentConnectionFailure(error) ? new ProviderRequestError(message) : new RetryableProviderError(message);
|
|
867
|
+
throw coded(failure, cause ?? 'connection_failed');
|
|
819
868
|
}
|
|
820
869
|
if (response.status === 401 && config.anthropicAuth === 'console' && !forceRefresh) {
|
|
821
870
|
dispose();
|
|
@@ -836,12 +885,12 @@ export function createAdapter(config, options = {}) {
|
|
|
836
885
|
// The router's own refusals are sent once and shown as written here, never retried.
|
|
837
886
|
const refusal = andorra ? andorraRefusal(response.status, errorData, response.headers.get('retry-after')) : undefined;
|
|
838
887
|
if (refusal)
|
|
839
|
-
throw new ProviderRequestError(refusal);
|
|
888
|
+
throw coded(new ProviderRequestError(refusal), `http_${response.status}`);
|
|
840
889
|
const detail = providerErrorDetail(errorData);
|
|
841
890
|
const shown = detail === undefined ? undefined : redactCredential(detail, key);
|
|
842
891
|
const message = `Provider request failed (HTTP ${response.status})${shown ? `: ${shown}` : ''}. Check credentials, model, and provider availability.`;
|
|
843
892
|
if ([408, 409, 429, 500, 502, 503, 504, 529].includes(response.status)) {
|
|
844
|
-
throw new RetryableProviderError(message, retryAfter(response.headers.get('retry-after')));
|
|
893
|
+
throw coded(new RetryableProviderError(message, retryAfter(response.headers.get('retry-after'))), `http_${response.status}`);
|
|
845
894
|
}
|
|
846
895
|
throw new HttpProviderError(message, response.status);
|
|
847
896
|
}
|
|
@@ -929,7 +978,7 @@ export function createAdapter(config, options = {}) {
|
|
|
929
978
|
if (signal.aborted)
|
|
930
979
|
throw new Error('Provider request cancelled.');
|
|
931
980
|
if (deadline?.aborted)
|
|
932
|
-
throw new RetryableProviderError('Provider request timed out.');
|
|
981
|
+
throw coded(new RetryableProviderError('Provider request timed out.'), 'provider_timeout');
|
|
933
982
|
if (error instanceof ResponseTooLargeError || error instanceof RetryableProviderError)
|
|
934
983
|
throw error;
|
|
935
984
|
return malformed();
|
|
@@ -951,12 +1000,12 @@ export function createAdapter(config, options = {}) {
|
|
|
951
1000
|
if (retry >= error.maxRetries)
|
|
952
1001
|
throw error;
|
|
953
1002
|
if (error.retryAfterMs > MAX_AUTOMATIC_RETRY_AFTER_MS)
|
|
954
|
-
throw new ProviderRequestError(`${error.message} Retry-After exceeds the 120-second automatic retry limit.`);
|
|
1003
|
+
throw coded(new ProviderRequestError(`${error.message} Retry-After exceeds the 120-second automatic retry limit.`), providerFailureCode(error));
|
|
955
1004
|
const delayMs = Math.max(error.retryDelaysMs[retry] ?? error.retryDelaysMs.at(-1) ?? 0, error.retryAfterMs);
|
|
956
1005
|
const reason = error instanceof MalformedStreamProviderError
|
|
957
1006
|
? 'Provider returned a malformed streamed response; retrying without streaming.'
|
|
958
1007
|
: error.message;
|
|
959
|
-
await onRetry?.({ retry: retry + 1, maxRetries: error.maxRetries, delayMs, reason, ...(error.quiet ? { quiet: true } : {}),
|
|
1008
|
+
await onRetry?.({ retry: retry + 1, maxRetries: error.maxRetries, delayMs, reason, code: providerFailureCode(error), ...(error.quiet ? { quiet: true } : {}),
|
|
960
1009
|
...(error.connectionCause ? { cause: error.connectionCause } : {}) });
|
|
961
1010
|
try {
|
|
962
1011
|
await delay(delayMs, undefined, { signal });
|
|
@@ -1009,7 +1058,7 @@ export function createAdapter(config, options = {}) {
|
|
|
1009
1058
|
if (signal.aborted)
|
|
1010
1059
|
cancelled();
|
|
1011
1060
|
if (deadline?.aborted)
|
|
1012
|
-
throw new RetryableProviderError('Provider request timed out.');
|
|
1061
|
+
throw coded(new RetryableProviderError('Provider request timed out.'), 'provider_timeout');
|
|
1013
1062
|
if (error instanceof ResponseTooLargeError || error instanceof RetryableProviderError)
|
|
1014
1063
|
throw error;
|
|
1015
1064
|
return malformed();
|
|
@@ -1051,7 +1100,7 @@ export function createAdapter(config, options = {}) {
|
|
|
1051
1100
|
...(thinking.length ? { providerContinuation: { api: 'anthropic-messages', provider: config.id, model, thinking } } : {}) };
|
|
1052
1101
|
},
|
|
1053
1102
|
checkCalls: calls => checkCalls(calls, advertised),
|
|
1054
|
-
streamReadError: () => new RetryableProviderError('Provider connection failed while reading its response.'),
|
|
1103
|
+
streamReadError: () => coded(new RetryableProviderError('Provider connection failed while reading its response.'), 'stream_interrupted'),
|
|
1055
1104
|
streamMalformedError: () => new MalformedStreamProviderError(),
|
|
1056
1105
|
streamingDisabled: () => currentRequestNonStreaming,
|
|
1057
1106
|
...(anthropic ? { streamValidator() {
|
|
@@ -1061,7 +1110,7 @@ export function createAdapter(config, options = {}) {
|
|
|
1061
1110
|
const validator = createStreamAccumulator(() => { });
|
|
1062
1111
|
return { event: validator.event, finish() {
|
|
1063
1112
|
if (!validator.completed)
|
|
1064
|
-
throw new RetryableProviderError('Provider closed the stream before the response completed.');
|
|
1113
|
+
throw coded(new RetryableProviderError('Provider closed the stream before the response completed.'), 'stream_interrupted');
|
|
1065
1114
|
return validator.finish(requests, advertised);
|
|
1066
1115
|
} };
|
|
1067
1116
|
} }),
|
|
@@ -1069,7 +1118,7 @@ export function createAdapter(config, options = {}) {
|
|
|
1069
1118
|
if (signal.aborted)
|
|
1070
1119
|
cancelled();
|
|
1071
1120
|
if (deadline?.aborted)
|
|
1072
|
-
throw new RetryableProviderError('Provider request timed out.');
|
|
1121
|
+
throw coded(new RetryableProviderError('Provider request timed out.'), 'provider_timeout');
|
|
1073
1122
|
if (error instanceof Error && !(error instanceof RetryableProviderError) && error.message === MALFORMED_RESPONSE_MESSAGE)
|
|
1074
1123
|
throw new MalformedResponseProviderError();
|
|
1075
1124
|
throw error;
|