@mupt-ai/dari-gateway 1.0.291 → 1.0.294

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.
Files changed (35) hide show
  1. package/README.md +6 -5
  2. package/dist/platform/platform.d.ts +30 -2
  3. package/dist/providers/execution.js +66 -1
  4. package/dist/providers/provider_attempt_runner.d.ts +3 -0
  5. package/dist/providers/provider_attempt_runner.js +11 -2
  6. package/dist/providers/response_capture.d.ts +3 -1
  7. package/dist/providers/response_capture.js +6 -2
  8. package/dist/providers/subscription_limits.d.ts +16 -0
  9. package/dist/providers/subscription_limits.js +25 -0
  10. package/dist/runtime/prepare_routed_completion.js +2 -0
  11. package/dist/self_host/platform.d.ts +1 -1
  12. package/dist/self_host/platform.js +15 -0
  13. package/dist/self_host/resolve.js +6 -2
  14. package/dist/self_host/subscription_test_gateway.d.ts +16 -0
  15. package/dist/self_host/subscription_test_gateway.js +120 -0
  16. package/dist/self_host/subscriptions/http.js +8 -1
  17. package/dist/self_host/subscriptions/index.d.ts +3 -2
  18. package/dist/self_host/subscriptions/index.js +3 -2
  19. package/dist/self_host/subscriptions/store.d.ts +36 -5
  20. package/dist/self_host/subscriptions/store.js +129 -17
  21. package/dist/self_host/subscriptions/test_support.d.ts +15 -0
  22. package/dist/self_host/subscriptions/test_support.js +34 -0
  23. package/package.json +2 -2
  24. package/src/platform/platform.ts +39 -2
  25. package/src/providers/execution.ts +72 -0
  26. package/src/providers/provider_attempt_runner.ts +18 -2
  27. package/src/providers/response_capture.ts +10 -2
  28. package/src/providers/subscription_limits.ts +39 -0
  29. package/src/runtime/prepare_routed_completion.ts +2 -0
  30. package/src/self_host/platform.ts +14 -1
  31. package/src/self_host/resolve.ts +6 -2
  32. package/src/self_host/subscription_test_gateway.ts +129 -0
  33. package/src/self_host/subscriptions/http.ts +9 -1
  34. package/src/self_host/subscriptions/index.ts +3 -2
  35. package/src/self_host/subscriptions/store.ts +181 -19
@@ -1,17 +1,30 @@
1
1
  /**
2
- * SQLite storage for personal subscription credentials and pending OAuth flows.
2
+ * SQLite storage for personal subscription credentials, the conversations
3
+ * each one serves, and pending OAuth flows.
3
4
  *
4
5
  * Tokens are stored as PLAINTEXT in the gateway's own database file. Anyone
5
6
  * who can read that file can use the connected subscriptions until the
6
7
  * provider revokes them, so keep the file on storage only the gateway's
7
8
  * operator can read, and treat backups of it as secrets.
8
9
  *
9
- * Connection order (`position`) is the order routing switches through: the
10
- * active credential for a provider is the first one, in that order, that is
11
- * not held. A hold ends on its own once `unavailable_until` passes.
10
+ * Choosing a subscription (`selectCredential`), for each provider:
11
+ * - A conversation stays on the subscription it started on, so its prompt
12
+ * cache stays warm, until that subscription is held or reports at least
13
+ * SWITCH_AT_UTILIZATION of a window used.
14
+ * - Otherwise it moves to the subscription with headroom whose reported
15
+ * usage resets soonest, so quota about to reset is spent before fresh
16
+ * quota. Ties go to the subscription used last, whose cached system prompt
17
+ * new conversations share, then onward from it in connection order
18
+ * (`position`). A request with no conversation stays on the subscription
19
+ * used last.
20
+ * - When every subscription is past the threshold, the least used serves.
21
+ * A hold ends on its own once `unavailable_until` passes; reported usage
22
+ * stops counting once its window resets.
12
23
  */
13
24
  import type { Database } from "bun:sqlite";
25
+ import type { SubscriptionUsage } from "../../providers/subscription_limits.js";
14
26
  import type { OAuthTokens, SubscriptionProvider } from "./oauth.js";
27
+ export declare const SWITCH_AT_UTILIZATION = 0.95;
15
28
  export type SubscriptionCredential = {
16
29
  id: string;
17
30
  provider: SubscriptionProvider;
@@ -24,6 +37,9 @@ export type SubscriptionCredential = {
24
37
  expiresAt: Date;
25
38
  unavailableUntil: Date | null;
26
39
  unavailableReason: string | null;
40
+ usage: (SubscriptionUsage & {
41
+ observedAt: Date;
42
+ }) | null;
27
43
  position: number;
28
44
  createdAt: Date;
29
45
  updatedAt: Date;
@@ -43,8 +59,21 @@ export declare class SubscriptionStore {
43
59
  list(provider?: SubscriptionProvider): SubscriptionCredential[];
44
60
  get(id: string): SubscriptionCredential | null;
45
61
  getByName(name: string): SubscriptionCredential | null;
46
- /** The credential routing uses now, or null when none is connected or every one is held. */
62
+ /**
63
+ * The subscription a request without a conversation would use now, or null
64
+ * when none is connected or every one is held.
65
+ */
47
66
  activeCredential(provider: SubscriptionProvider, now?: Date): SubscriptionCredential | null;
67
+ /**
68
+ * The subscription that serves a conversation's next turn (see the module
69
+ * comment), or null when none is connected or every one is held. A
70
+ * conversation is remembered on the subscription chosen for it.
71
+ */
72
+ selectCredential(provider: SubscriptionProvider, conversationId: string | undefined, now?: Date): SubscriptionCredential | null;
73
+ /** Record the usage a response reported for a subscription. */
74
+ recordUsage(id: string, usage: SubscriptionUsage, now?: Date): void;
75
+ private pinnedCredential;
76
+ private pinConversation;
48
77
  /**
49
78
  * Store tokens from a completed OAuth flow. `reconnectName` replaces that
50
79
  * subscription (null when it is not connected). Otherwise a subscription
@@ -74,5 +103,7 @@ export declare class SubscriptionStore {
74
103
  private freeName;
75
104
  }
76
105
  export declare function isHeld(credential: SubscriptionCredential, now: Date): boolean;
106
+ /** The usage a subscription last reported, while its window has not reset. */
107
+ export declare function currentUsage(credential: SubscriptionCredential, now: Date): SubscriptionUsage | null;
77
108
  /** Subscription names are env-var-style identifiers; matching is case-insensitive. */
78
109
  export declare function normalizeName(name: string): string;
@@ -1,9 +1,21 @@
1
1
  import { randomBytes, randomUUID } from "node:crypto";
2
+ // The share of a usage window past which conversations leave a subscription
3
+ // at their next turn, before the provider starts refusing requests.
4
+ export const SWITCH_AT_UTILIZATION = 0.95;
5
+ // A conversation idle this long is forgotten; its next turn starts over.
6
+ const CONVERSATION_PIN_TTL_MS = 7 * 24 * 60 * 60_000;
2
7
  const BASE_NAMES = {
3
8
  anthropic_claude_code: "ANTHROPIC_CLAUDE_CODE_OAUTH_TOKEN",
4
9
  openai_codex: "OPENAI_CODEX_OAUTH_TOKEN",
5
10
  meta_muse: "META_MUSE_OAUTH_TOKEN",
6
11
  };
12
+ // Usage columns added after the table first shipped; existing databases gain
13
+ // them on open.
14
+ const USAGE_COLUMNS = {
15
+ usage_utilization: "REAL",
16
+ usage_resets_at: "INTEGER",
17
+ usage_observed_at: "INTEGER",
18
+ };
7
19
  export class SubscriptionStore {
8
20
  db;
9
21
  constructor(db) {
@@ -20,10 +32,25 @@ export class SubscriptionStore {
20
32
  expires_at INTEGER NOT NULL,
21
33
  unavailable_until INTEGER,
22
34
  unavailable_reason TEXT,
35
+ usage_utilization REAL,
36
+ usage_resets_at INTEGER,
37
+ usage_observed_at INTEGER,
23
38
  position INTEGER NOT NULL,
24
39
  created_at INTEGER NOT NULL,
25
40
  updated_at INTEGER NOT NULL,
26
41
  last_used_at INTEGER
42
+ )`);
43
+ const columns = new Set(db.query("PRAGMA table_info(subscription_credentials)").all().map((column) => column.name));
44
+ for (const [column, type] of Object.entries(USAGE_COLUMNS)) {
45
+ if (!columns.has(column))
46
+ db.run(`ALTER TABLE subscription_credentials ADD COLUMN ${column} ${type}`);
47
+ }
48
+ db.run(`CREATE TABLE IF NOT EXISTS subscription_conversation_pins (
49
+ conversation_id TEXT NOT NULL,
50
+ provider TEXT NOT NULL,
51
+ credential_id TEXT NOT NULL,
52
+ used_at INTEGER NOT NULL,
53
+ PRIMARY KEY (conversation_id, provider)
27
54
  )`);
28
55
  db.run(`CREATE TABLE IF NOT EXISTS subscription_oauth_sessions (
29
56
  token TEXT PRIMARY KEY,
@@ -52,23 +79,55 @@ export class SubscriptionStore {
52
79
  .get(normalizeName(name));
53
80
  return row === null ? null : credentialFromRow(row);
54
81
  }
55
- /** The credential routing uses now, or null when none is connected or every one is held. */
82
+ /**
83
+ * The subscription a request without a conversation would use now, or null
84
+ * when none is connected or every one is held.
85
+ */
56
86
  activeCredential(provider, now = new Date()) {
57
- // Stay on the most recently used subscription while it serves, so its
58
- // prompt cache stays warm; once it is held, move on in connection order.
59
- const credentials = this.list(provider);
60
- let start = 0;
61
- credentials.forEach((credential, index) => {
62
- const lastUsed = credential.lastUsedAt?.getTime() ?? -1;
63
- if (lastUsed > (credentials[start].lastUsedAt?.getTime() ?? -1))
64
- start = index;
65
- });
66
- for (let offset = 0; offset < credentials.length; offset += 1) {
67
- const credential = credentials[(start + offset) % credentials.length];
68
- if (!isHeld(credential, now))
69
- return credential;
87
+ return this.selectCredential(provider, undefined, now);
88
+ }
89
+ /**
90
+ * The subscription that serves a conversation's next turn (see the module
91
+ * comment), or null when none is connected or every one is held. A
92
+ * conversation is remembered on the subscription chosen for it.
93
+ */
94
+ selectCredential(provider, conversationId, now = new Date()) {
95
+ const all = this.list(provider);
96
+ const available = all.filter((credential) => !isHeld(credential, now));
97
+ if (available.length === 0)
98
+ return null;
99
+ const order = rotationFrom(all, lastUsed(all));
100
+ const withHeadroom = available.filter((credential) => hasHeadroom(credential, now));
101
+ const current = conversationId === undefined
102
+ ? lastUsed(available)
103
+ : this.pinnedCredential(conversationId, provider, available, now);
104
+ let chosen = current !== null && withHeadroom.includes(current) ? current : null;
105
+ if (chosen === null) {
106
+ chosen = withHeadroom.length > 0
107
+ ? [...withHeadroom].sort(soonestResetFirst(now, order))[0]
108
+ : [...available].sort(leastUsedFirst(now, order))[0];
70
109
  }
71
- return null;
110
+ if (conversationId !== undefined)
111
+ this.pinConversation(conversationId, provider, chosen.id, now);
112
+ return chosen;
113
+ }
114
+ /** Record the usage a response reported for a subscription. */
115
+ recordUsage(id, usage, now = new Date()) {
116
+ this.db.run("UPDATE subscription_credentials SET usage_utilization = ?, usage_resets_at = ?, usage_observed_at = ? WHERE id = ?", [usage.utilization, usage.resetsAt.getTime(), now.getTime(), id]);
117
+ }
118
+ // A pin idle past CONVERSATION_PIN_TTL_MS is forgotten: the conversation is
119
+ // assigned like a new one.
120
+ pinnedCredential(conversationId, provider, available, now) {
121
+ const row = this.db
122
+ .query(`SELECT credential_id FROM subscription_conversation_pins
123
+ WHERE conversation_id = ? AND provider = ? AND used_at >= ?`)
124
+ .get(conversationId, provider, now.getTime() - CONVERSATION_PIN_TTL_MS);
125
+ return available.find((credential) => credential.id === row?.credential_id) ?? null;
126
+ }
127
+ pinConversation(conversationId, provider, credentialId, now) {
128
+ this.db.run(`INSERT INTO subscription_conversation_pins (conversation_id, provider, credential_id, used_at) VALUES (?, ?, ?, ?)
129
+ ON CONFLICT (conversation_id, provider) DO UPDATE SET credential_id = excluded.credential_id, used_at = excluded.used_at`, [conversationId, provider, credentialId, now.getTime()]);
130
+ this.db.run("DELETE FROM subscription_conversation_pins WHERE used_at < ?", [now.getTime() - CONVERSATION_PIN_TTL_MS]);
72
131
  }
73
132
  /**
74
133
  * Store tokens from a completed OAuth flow. `reconnectName` replaces that
@@ -84,10 +143,14 @@ export class SubscriptionStore {
84
143
  if (reconnectName !== null && existing?.provider !== tokens.provider)
85
144
  return null;
86
145
  if (existing !== null) {
87
- // Another (or an unidentified) account must not inherit the previous account's hold.
146
+ // Another (or an unidentified) account must not inherit the previous
147
+ // account's hold, reported usage, or conversations (whose cache is
148
+ // the previous account's).
88
149
  const sameAccount = tokens.accountEmail !== null && tokens.accountEmail === existing.accountEmail;
150
+ const usage = sameAccount ? existing.usage : null;
89
151
  this.db.run(`UPDATE subscription_credentials SET access_token = ?, refresh_token = ?, expires_at = ?,
90
- account_id = ?, account_email = ?, unavailable_until = ?, unavailable_reason = ?, updated_at = ?
152
+ account_id = ?, account_email = ?, unavailable_until = ?, unavailable_reason = ?,
153
+ usage_utilization = ?, usage_resets_at = ?, usage_observed_at = ?, updated_at = ?
91
154
  WHERE id = ?`, [
92
155
  tokens.accessToken,
93
156
  tokens.refreshToken,
@@ -96,9 +159,15 @@ export class SubscriptionStore {
96
159
  tokens.accountEmail,
97
160
  sameAccount ? existing.unavailableUntil?.getTime() ?? null : null,
98
161
  sameAccount ? existing.unavailableReason : null,
162
+ usage?.utilization ?? null,
163
+ usage?.resetsAt.getTime() ?? null,
164
+ usage?.observedAt.getTime() ?? null,
99
165
  now.getTime(),
100
166
  existing.id,
101
167
  ]);
168
+ if (!sameAccount) {
169
+ this.db.run("DELETE FROM subscription_conversation_pins WHERE credential_id = ?", [existing.id]);
170
+ }
102
171
  return this.get(existing.id);
103
172
  }
104
173
  const id = `cred_${randomUUID().replaceAll("-", "")}`;
@@ -153,6 +222,7 @@ export class SubscriptionStore {
153
222
  if (credential === null)
154
223
  return null;
155
224
  this.db.run("DELETE FROM subscription_credentials WHERE id = ?", [credential.id]);
225
+ this.db.run("DELETE FROM subscription_conversation_pins WHERE credential_id = ?", [credential.id]);
156
226
  return credential;
157
227
  }
158
228
  /**
@@ -211,6 +281,41 @@ export class SubscriptionStore {
211
281
  export function isHeld(credential, now) {
212
282
  return credential.unavailableUntil !== null && credential.unavailableUntil > now;
213
283
  }
284
+ /** The usage a subscription last reported, while its window has not reset. */
285
+ export function currentUsage(credential, now) {
286
+ return credential.usage !== null && credential.usage.resetsAt > now ? credential.usage : null;
287
+ }
288
+ function hasHeadroom(credential, now) {
289
+ return (currentUsage(credential, now)?.utilization ?? 0) < SWITCH_AT_UTILIZATION;
290
+ }
291
+ function lastUsed(credentials) {
292
+ let latest = null;
293
+ for (const credential of credentials) {
294
+ if (credential.lastUsedAt !== null && (latest === null || credential.lastUsedAt > latest.lastUsedAt)) {
295
+ latest = credential;
296
+ }
297
+ }
298
+ return latest;
299
+ }
300
+ // Each credential's rank in connection order starting at `anchor` (the one
301
+ // used last), wrapping past the end; without an anchor, connection order.
302
+ function rotationFrom(all, anchor) {
303
+ const start = anchor === null ? 0 : all.indexOf(anchor);
304
+ return new Map(all.map((credential, index) => [credential.id, (index - start + all.length) % all.length]));
305
+ }
306
+ // Spend quota about to reset first; a subscription with no current usage
307
+ // report (fresh, or its window reset) comes after, then rotation order.
308
+ function soonestResetFirst(now, order) {
309
+ return (a, b) => {
310
+ const resetA = currentUsage(a, now)?.resetsAt.getTime() ?? Infinity;
311
+ const resetB = currentUsage(b, now)?.resetsAt.getTime() ?? Infinity;
312
+ return resetA - resetB || order.get(a.id) - order.get(b.id);
313
+ };
314
+ }
315
+ function leastUsedFirst(now, order) {
316
+ return (a, b) => (currentUsage(a, now)?.utilization ?? 0) - (currentUsage(b, now)?.utilization ?? 0)
317
+ || order.get(a.id) - order.get(b.id);
318
+ }
214
319
  /** Subscription names are env-var-style identifiers; matching is case-insensitive. */
215
320
  export function normalizeName(name) {
216
321
  return name.trim().toUpperCase();
@@ -228,6 +333,13 @@ function credentialFromRow(row) {
228
333
  expiresAt: new Date(row.expires_at),
229
334
  unavailableUntil: row.unavailable_until === null ? null : new Date(row.unavailable_until),
230
335
  unavailableReason: row.unavailable_reason,
336
+ usage: row.usage_utilization === null || row.usage_resets_at === null || row.usage_observed_at === null
337
+ ? null
338
+ : {
339
+ utilization: row.usage_utilization,
340
+ resetsAt: new Date(row.usage_resets_at),
341
+ observedAt: new Date(row.usage_observed_at),
342
+ },
231
343
  position: row.position,
232
344
  createdAt: new Date(row.created_at),
233
345
  updatedAt: new Date(row.updated_at),
@@ -0,0 +1,15 @@
1
+ import type { OAuthFetch, OAuthTokens } from "./oauth.js";
2
+ export type RecordedCall = {
3
+ url: string;
4
+ init: RequestInit;
5
+ body: string;
6
+ };
7
+ /** A fetch that answers from a queue and records every request. */
8
+ export declare function fakeFetch(responses: Array<() => Response>): OAuthFetch & {
9
+ calls: RecordedCall[];
10
+ };
11
+ export declare function jsonResponse(body: unknown, status?: number): () => Response;
12
+ /** An unsigned JWT; only the payload matters to the gateway. */
13
+ export declare function jwt(payload: Record<string, unknown>): string;
14
+ export declare function codexAccessToken(accountId: string, exp?: number): string;
15
+ export declare function tokens(overrides?: Partial<OAuthTokens>): OAuthTokens;
@@ -0,0 +1,34 @@
1
+ /** A fetch that answers from a queue and records every request. */
2
+ export function fakeFetch(responses) {
3
+ const calls = [];
4
+ const fetch = async (url, init) => {
5
+ calls.push({ url, init, body: String(init.body) });
6
+ const next = responses.shift();
7
+ if (next === undefined)
8
+ throw new Error(`unexpected request to ${url}`);
9
+ return next();
10
+ };
11
+ return Object.assign(fetch, { calls });
12
+ }
13
+ export function jsonResponse(body, status = 200) {
14
+ return () => Response.json(body, { status });
15
+ }
16
+ /** An unsigned JWT; only the payload matters to the gateway. */
17
+ export function jwt(payload) {
18
+ const part = (value) => Buffer.from(JSON.stringify(value)).toString("base64url");
19
+ return `${part({ alg: "none" })}.${part(payload)}.sig`;
20
+ }
21
+ export function codexAccessToken(accountId, exp) {
22
+ return jwt({ ...(exp === undefined ? {} : { exp }), "https://api.openai.com/auth": { chatgpt_account_id: accountId } });
23
+ }
24
+ export function tokens(overrides = {}) {
25
+ return {
26
+ provider: "anthropic_claude_code",
27
+ accessToken: "sk-ant-oat01-access",
28
+ refreshToken: "sk-ant-ort01-refresh",
29
+ expiresAt: new Date("2026-10-20T13:00:00Z"),
30
+ accountId: null,
31
+ accountEmail: "one@example.com",
32
+ ...overrides,
33
+ };
34
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mupt-ai/dari-gateway",
3
- "version": "1.0.291",
3
+ "version": "1.0.294",
4
4
  "description": "Self-hostable LLM gateway for coding agents and APIs: one endpoint for Anthropic Messages, OpenAI Chat Completions, and OpenAI Responses, with subscription pooling, failover, and prompt-cache-aware routing.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -51,7 +51,7 @@
51
51
  },
52
52
  "dependencies": {
53
53
  "@aws-sdk/client-sts": "3.1063.0",
54
- "@mupt-ai/dari-router": "1.0.291",
54
+ "@mupt-ai/dari-router": "1.0.294",
55
55
  "@mupt-ai/pi-ai": "1.4.0-mupt.3"
56
56
  },
57
57
  "devDependencies": {
@@ -5,7 +5,7 @@ import type {
5
5
  } from "@mupt-ai/dari-router/policy-engine";
6
6
  import type { HarnessConversationIdentity } from "../runtime/harness_identity/index.js";
7
7
  import type { InteractionRequest, SourceProtocol } from "../interaction/types.js";
8
- import type { SubscriptionUsageLimit } from "../providers/subscription_limits.js";
8
+ import type { SubscriptionUsage, SubscriptionUsageLimit } from "../providers/subscription_limits.js";
9
9
  import type {
10
10
  ClientHarness,
11
11
  ProviderCredential,
@@ -54,6 +54,19 @@ export type GatewayPlatform = {
54
54
  * another connected subscription for the same provider can serve a retry.
55
55
  */
56
56
  markSubscriptionUnavailable(hold: SubscriptionHold): Promise<boolean>;
57
+ /**
58
+ * Optional. Record how much of a personal subscription's quota a successful
59
+ * response reports used, so the platform can move new conversations to
60
+ * plans with headroom before one runs out.
61
+ */
62
+ recordSubscriptionUsage?(report: SubscriptionUsageReport): Promise<void>;
63
+ /**
64
+ * Optional. After `markSubscriptionUnavailable` reports another plan can
65
+ * serve, the plan that serves this conversation next, so the gateway
66
+ * retries the request on it at once instead of failing it. Undefined when
67
+ * none can.
68
+ */
69
+ nextSubscription?(request: NextSubscriptionRequest): Promise<NextSubscription | undefined>;
57
70
  /**
58
71
  * Account one call served on a platform-managed provider key. Only reached
59
72
  * when `resolveRouter` reports a "managed" key source.
@@ -72,6 +85,10 @@ export type ResolveRouterRequest = {
72
85
  conversationId?: string;
73
86
  includePublicEvalCatalog?: boolean;
74
87
  clientHarness?: ClientHarness;
88
+ // A later resolve with this request's `conversationId` replaces this one's
89
+ // credentials, so none from it serve the request: a platform should not
90
+ // mark a credential used or refresh it for this resolve.
91
+ provisional?: boolean;
75
92
  };
76
93
 
77
94
  export type ProviderCredentialRequest = {
@@ -125,6 +142,24 @@ export type SubscriptionHold = {
125
142
  limit: SubscriptionUsageLimit;
126
143
  };
127
144
 
145
+ export type NextSubscriptionRequest = {
146
+ userId: string;
147
+ provider: Provider;
148
+ conversationId: string;
149
+ };
150
+
151
+ export type NextSubscription = {
152
+ credentialId: string;
153
+ // The plan's access token, sent as the bearer credential.
154
+ apiKey: string;
155
+ };
156
+
157
+ export type SubscriptionUsageReport = {
158
+ userId: string;
159
+ credentialId: string;
160
+ usage: SubscriptionUsage;
161
+ };
162
+
128
163
  export type RequestRecord = {
129
164
  // The full request log row: routing decision, usage, costs, and (outside
130
165
  // ZDR) request and response content.
@@ -221,7 +256,9 @@ export type OperationalErrorCode =
221
256
  | "server_force_stop_failed"
222
257
  | "session_pin_write_failed"
223
258
  | "stream_report_finalization_failed"
224
- | "subscription_unavailable_ingest_failed";
259
+ | "subscription_unavailable_ingest_failed"
260
+ | "subscription_usage_record_failed"
261
+ | "next_subscription_lookup_failed";
225
262
 
226
263
  export type OperationalErrorContext = {
227
264
  code: OperationalErrorCode;
@@ -44,10 +44,12 @@ import {
44
44
  NO_DELIVERED_OUTPUT,
45
45
  observeDeliveredOutput,
46
46
  } from "./cancel_estimate.js";
47
+ import type { NextSubscription } from "../platform/platform.js";
47
48
  import { providerResponseCaptureFromError, type ProviderResponseCapture } from "./response_capture.js";
48
49
  import { createStreamFinalizer } from "./stream_finalization.js";
49
50
  import {
50
51
  detectSubscriptionUsageLimit,
52
+ subscriptionUsageFromHeaders,
51
53
  failureWithSubscriptionUsageLimit,
52
54
  retryAfterSeconds,
53
55
  subscriptionUsageLimitFromFailure,
@@ -245,6 +247,7 @@ async function completeWithRetries(args: {
245
247
  }),
246
248
  recordFailedAttempt: ({ choice, attempt, result }) =>
247
249
  recordSettledFailure(args.reporter, choice, attempt, result),
250
+ onSubscription: onNextSubscription,
248
251
  });
249
252
  }
250
253
 
@@ -278,6 +281,7 @@ async function runCompletionAttempt(args: {
278
281
  started.responseCapture,
279
282
  );
280
283
  }
284
+ noteSubscriptionUsage(args.choice.execution, started.responseCapture);
281
285
  if (args.choice.execution.usageContext && hasUsage(completion.message)) {
282
286
  await reportRoutingUsage(
283
287
  {
@@ -478,6 +482,7 @@ export async function prepareStreamingExecution(args: {
478
482
  }),
479
483
  recordFailedAttempt: ({ choice, attempt, result }) =>
480
484
  recordSettledFailure(args.reporter, choice, attempt, result),
485
+ onSubscription: onNextSubscription,
481
486
  });
482
487
  args.reporter.attachServingDecision(result.choice.decision);
483
488
  if (result.kind === "customer_canceled") {
@@ -542,6 +547,7 @@ async function runStreamSetupAttempt(args: {
542
547
  started.responseCapture,
543
548
  );
544
549
  }
550
+ noteSubscriptionUsage(args.choice.execution, started.responseCapture);
545
551
  return {
546
552
  kind: "succeeded",
547
553
  value: {
@@ -717,11 +723,17 @@ async function providerFailedAttempt(
717
723
  credentialId: execution.subscriptionCredentialId,
718
724
  limit,
719
725
  });
726
+ // Nothing reached the client yet, so the same request is retried on the
727
+ // next plan at once when the platform names it.
728
+ const nextSubscription = switched
729
+ ? await nextSubscriptionFor(execution)
730
+ : undefined;
720
731
  return {
721
732
  kind: "provider_failed",
722
733
  message: failureWithSubscriptionUsageLimit(message, { ...limit, switched }),
723
734
  latencyMs,
724
735
  retryable: false,
736
+ ...(nextSubscription === undefined ? {} : { nextSubscription }),
725
737
  };
726
738
  }
727
739
 
@@ -777,6 +789,66 @@ function isPromptPolicyRejection(message: Record<string, unknown>): boolean {
777
789
  return text.includes("invalid prompt") && text.includes("usage policy");
778
790
  }
779
791
 
792
+ // The plan that serves this conversation after its plan was held, or
793
+ // undefined when the platform names none. A failure leaves the request to
794
+ // fail as before.
795
+ async function nextSubscriptionFor(execution: ProviderExecution): Promise<NextSubscription | undefined> {
796
+ const platform = gatewayPlatform();
797
+ if (platform.nextSubscription === undefined || execution.subscriptionUserId === undefined) return undefined;
798
+ try {
799
+ return await platform.nextSubscription({
800
+ userId: execution.subscriptionUserId,
801
+ provider: execution.provider,
802
+ conversationId: execution.conversationId,
803
+ });
804
+ } catch (error) {
805
+ console.error("next subscription lookup failed", error);
806
+ captureOperationalError(error, { code: "next_subscription_lookup_failed" });
807
+ return undefined;
808
+ }
809
+ }
810
+
811
+ // The same choice served by another of the user's plans.
812
+ function onNextSubscription(choice: ProviderChoice, next: NextSubscription): ProviderChoice {
813
+ return {
814
+ ...choice,
815
+ execution: {
816
+ ...choice.execution,
817
+ apiKey: next.apiKey,
818
+ auth: { type: "bearer", apiKey: next.apiKey },
819
+ subscriptionCredentialId: next.credentialId,
820
+ },
821
+ };
822
+ }
823
+
824
+ // A served subscription request reports the plan's remaining quota; record
825
+ // it without waiting, and never fail the request over it.
826
+ function noteSubscriptionUsage(
827
+ execution: ProviderExecution,
828
+ responseCapture: ProviderResponseCapture | undefined,
829
+ ): void {
830
+ const platform = gatewayPlatform();
831
+ const headers = responseCapture?.succeeded;
832
+ if (
833
+ platform.recordSubscriptionUsage === undefined ||
834
+ headers === undefined ||
835
+ execution.subscriptionUserId === undefined ||
836
+ execution.subscriptionCredentialId === undefined
837
+ ) {
838
+ return;
839
+ }
840
+ const usage = subscriptionUsageFromHeaders(execution.provider, execution.providerKeySource, headers);
841
+ if (usage === null) return;
842
+ platform.recordSubscriptionUsage({
843
+ userId: execution.subscriptionUserId,
844
+ credentialId: execution.subscriptionCredentialId,
845
+ usage,
846
+ }).catch((error: unknown) => {
847
+ console.error("subscription usage record failed", error);
848
+ captureOperationalError(error, { code: "subscription_usage_record_failed" });
849
+ });
850
+ }
851
+
780
852
  // Never fails the request: the provider already refused. Resolves whether
781
853
  // another subscription now serves.
782
854
  async function holdSubscription(hold: SubscriptionHold): Promise<boolean> {
@@ -1,3 +1,4 @@
1
+ import type { NextSubscription } from "../platform/platform.js";
1
2
  import { subscriptionUsageLimitFromFailure } from "./subscription_limits.js";
2
3
 
3
4
  export type ProviderAttemptFailure =
@@ -6,6 +7,9 @@ export type ProviderAttemptFailure =
6
7
  message: Record<string, unknown>;
7
8
  latencyMs: number;
8
9
  retryable: boolean;
10
+ // The plan that replaced an exhausted one; the same request is retried
11
+ // on it at once.
12
+ nextSubscription?: NextSubscription;
9
13
  }
10
14
  | {
11
15
  kind: "customer_canceled";
@@ -44,6 +48,9 @@ type RunProviderAttemptPlanArgs<TChoice, TValue, TInitial> = {
44
48
  attempt: number;
45
49
  result: ProviderAttemptFailure;
46
50
  }) => void;
51
+ // The choice served by another of the user's plans; without it a failure
52
+ // naming one is not retried on it.
53
+ onSubscription?: (choice: TChoice, next: NextSubscription) => TChoice;
47
54
  };
48
55
 
49
56
  type ChoiceResult<TChoice, TValue> = ProviderAttemptPlanResult<TChoice, TValue>;
@@ -78,14 +85,18 @@ export async function runProviderAttemptPlan<TChoice, TValue, TInitial>(
78
85
 
79
86
  async function runChoice<TChoice, TValue, TInitial>(
80
87
  args: RunProviderAttemptPlanArgs<TChoice, TValue, TInitial>,
81
- choice: TChoice,
88
+ firstChoice: TChoice,
82
89
  initial: TInitial | undefined,
83
90
  ): Promise<ChoiceResult<TChoice, TValue>> {
91
+ let choice = firstChoice;
84
92
  let latencyMs = 0;
85
93
  let lastFailure: Record<string, unknown> | null = null;
86
94
  let lastAttempt = 0;
87
95
 
88
- for (let attempt = 1; attempt <= args.retries + 1; attempt += 1) {
96
+ // A switch to another plan retries without spending the retry budget; each
97
+ // switch holds a plan, so switches are bounded by the plans connected.
98
+ let maxAttempts = args.retries + 1;
99
+ for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {
89
100
  lastAttempt = attempt;
90
101
  if (attempt !== 1 || initial === undefined) {
91
102
  if (args.isCustomerCanceled(choice)) {
@@ -114,6 +125,11 @@ async function runChoice<TChoice, TValue, TInitial>(
114
125
  failure: result.message,
115
126
  };
116
127
  }
128
+ if (result.kind === "provider_failed" && result.nextSubscription !== undefined && args.onSubscription) {
129
+ choice = args.onSubscription(choice, result.nextSubscription);
130
+ maxAttempts += 1;
131
+ continue;
132
+ }
117
133
  if (!result.retryable) break;
118
134
  }
119
135
 
@@ -9,12 +9,16 @@ export type ProviderFetch = (input: string | URL | Request, init?: RequestInit)
9
9
  export type ProviderResponseCapture = {
10
10
  fetch: ProviderFetch;
11
11
  last: CapturedProviderResponse | undefined;
12
+ // Headers of the last successful provider response, which carry a
13
+ // subscription's remaining usage.
14
+ succeeded: Headers | undefined;
12
15
  };
13
16
 
14
17
  const CAPTURED_BODY_MAX_BYTES = 64 * 1024;
15
18
 
16
19
  /**
17
- * A fetch wrapper that remembers the last failed provider response. pi-ai
20
+ * A fetch wrapper that remembers the last failed provider response, and the
21
+ * headers of the last successful one. pi-ai
18
22
  * flattens provider errors into one message string before they reach the
19
23
  * runtime, so this is the only place the status, rate-limit headers, and
20
24
  * structured error body of a rejected call can still be read.
@@ -22,9 +26,13 @@ const CAPTURED_BODY_MAX_BYTES = 64 * 1024;
22
26
  export function createProviderResponseCapture(): ProviderResponseCapture {
23
27
  const capture: ProviderResponseCapture = {
24
28
  last: undefined,
29
+ succeeded: undefined,
25
30
  fetch: async (input, init) => {
26
31
  const response = await globalThis.fetch(input, init);
27
- if (response.ok) return response;
32
+ if (response.ok) {
33
+ capture.succeeded = response.headers;
34
+ return response;
35
+ }
28
36
  const bodyText = await readBodyPrefix(response.clone());
29
37
  capture.last = { status: response.status, headers: response.headers, bodyText };
30
38
  return response;