@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
@@ -15,6 +15,45 @@ export type SubscriptionUsageLimit = {
15
15
  switched?: boolean;
16
16
  };
17
17
 
18
+ /**
19
+ * How much of a subscription's quota is used, from a successful response.
20
+ * `utilization` is the binding window's share used (0 to 1): the window
21
+ * closest to its limit, whose reset is `resetsAt`.
22
+ */
23
+ export type SubscriptionUsage = {
24
+ utilization: number;
25
+ resetsAt: Date;
26
+ };
27
+
28
+ // Claude Code's unified limiter reports each window on every response, the
29
+ // same headers Claude Code itself reads: `-utilization` as a fraction of the
30
+ // window and `-reset` in unix seconds.
31
+ const CLAUDE_CODE_USAGE_WINDOWS = ["5h", "7d"] as const;
32
+
33
+ /**
34
+ * The quota a successful subscription response reports used, or null when it
35
+ * reports none. Only Claude Code plans report usage on every response; a
36
+ * ChatGPT plan reports it inside the response stream, which the provider
37
+ * client does not surface, so its plans are switched only on a usage limit.
38
+ */
39
+ export function subscriptionUsageFromHeaders(
40
+ provider: string,
41
+ keySource: ProviderKeySource,
42
+ headers: Headers,
43
+ now = new Date(),
44
+ ): SubscriptionUsage | null {
45
+ if (subscriptionOAuthProviderFor(provider, keySource) !== "anthropic_claude_code") return null;
46
+ let binding: SubscriptionUsage | null = null;
47
+ for (const window of CLAUDE_CODE_USAGE_WINDOWS) {
48
+ const raw = Number(headers.get(`anthropic-ratelimit-unified-${window}-utilization`) ?? NaN);
49
+ const resetsAt = unixSecondsDeadline(headers.get(`anthropic-ratelimit-unified-${window}-reset`), now);
50
+ if (!Number.isFinite(raw) || resetsAt === null) continue;
51
+ const utilization = Math.max(0, Math.min(1, raw));
52
+ if (binding === null || utilization > binding.utilization) binding = { utilization, resetsAt };
53
+ }
54
+ return binding;
55
+ }
56
+
18
57
  // Neither provider guarantees a reset time on every usage-limit response.
19
58
  // Without one, hold the subscription out for an hour rather than hammering an
20
59
  // exhausted plan on every request.
@@ -81,6 +81,8 @@ export async function prepareRoutedCompletion(args: {
81
81
  ...resolveRequest,
82
82
  prefixHashes,
83
83
  clientHarness: args.clientHarness,
84
+ // Re-resolved below with the harness conversation, whose credentials serve.
85
+ ...(!background && args.harnessConversationIdentity !== undefined ? { provisional: true } : {}),
84
86
  });
85
87
  const canonicalRouterId = credentials.router_id;
86
88
  const organizationId = credentials.organization_id;
@@ -1,9 +1,10 @@
1
1
  import { errorCode } from "../http/errors.js";
2
+ import { subscriptionOAuthProviderFor } from "../providers/subscription_limits.js";
2
3
  import type { GatewayPlatform } from "../platform/platform.js";
3
4
  import type { PrefixStore } from "./prefix_store.js";
4
5
  import type { SessionPinStore } from "./session_pin_store.js";
5
6
  import { resolveSelfHostedRouter, type SelfHostedResolverDeps } from "./resolve.js";
6
- import type { SubscriptionStore } from "./subscriptions/index.js";
7
+ import { freshAccessToken, type SubscriptionStore } from "./subscriptions/index.js";
7
8
 
8
9
  /**
9
10
  * The self-hosted platform: routers from the config file, subscriptions,
@@ -31,6 +32,18 @@ export function createSelfHostedPlatform(deps: Omit<SelfHostedResolverDeps, "pre
31
32
  writeSessionPin: async (write) => {
32
33
  deps.sessionPins.write(write);
33
34
  },
35
+ recordSubscriptionUsage: async (report) => {
36
+ deps.subscriptions.recordUsage(report.credentialId, report.usage);
37
+ },
38
+ async nextSubscription(request) {
39
+ const plan = subscriptionOAuthProviderFor(request.provider, "subscription");
40
+ const next = plan === null ? null : deps.subscriptions.selectCredential(plan, request.conversationId);
41
+ if (next === null) return undefined;
42
+ return {
43
+ credentialId: next.id,
44
+ apiKey: await freshAccessToken(deps.subscriptions, next, { fetch: deps.fetch }),
45
+ };
46
+ },
34
47
  markSubscriptionUnavailable: async (hold) =>
35
48
  hold.credentialId !== undefined &&
36
49
  deps.subscriptions.markUnavailable(hold.credentialId, hold.limit.resetsAt, hold.limit.reason),
@@ -77,10 +77,14 @@ export async function resolveSelfHostedRouter(
77
77
  : null;
78
78
  const active = subscription === null
79
79
  ? null
80
- : deps.subscriptions.activeCredential(subscription, now);
80
+ : deps.subscriptions.selectCredential(subscription, request.conversationId, now);
81
81
  if (active !== null) {
82
82
  credentials.set(provider, {
83
- key: await freshAccessToken(deps.subscriptions, active, { fetch: deps.fetch }),
83
+ // A provisional resolve's credentials never serve, so it neither marks
84
+ // the plan used nor refreshes its token.
85
+ key: request.provisional === true
86
+ ? active.accessToken
87
+ : await freshAccessToken(deps.subscriptions, active, { fetch: deps.fetch }),
84
88
  source: "subscription",
85
89
  subscription: active,
86
90
  });
@@ -0,0 +1,129 @@
1
+ import { Database } from "bun:sqlite";
2
+ import { expect } from "bun:test";
3
+ import { mkdtempSync, writeFileSync } from "node:fs";
4
+ import { tmpdir } from "node:os";
5
+ import { join } from "node:path";
6
+
7
+ import { SubscriptionStore } from "./subscriptions/index.js";
8
+ import { tokens } from "./subscriptions/test_support.js";
9
+
10
+ /**
11
+ * A self-hosted gateway, run through its entrypoint as its own process so no
12
+ * other test file's module mocks reach it, serving two Claude Code plans
13
+ * (access tokens `sk-ant-oat01-a` and `-b`) against a local stand-in for
14
+ * Anthropic. `upstream` answers each provider call given the plan's token.
15
+ */
16
+ export async function startSubscriptionGateway(upstream: (token: string) => Response) {
17
+ const served: string[] = [];
18
+ const provider = Bun.serve({
19
+ port: 0,
20
+ fetch(request) {
21
+ const token = (request.headers.get("authorization") ?? "").replace(/^Bearer /, "");
22
+ served.push(token);
23
+ return upstream(token);
24
+ },
25
+ });
26
+ const dir = mkdtempSync(join(tmpdir(), "dari-gateway-plans-"));
27
+ const dbPath = join(dir, "gateway.db");
28
+ const setup = new SubscriptionStore(new Database(dbPath));
29
+ const future = new Date(Date.now() + 86_400_000);
30
+ const plans = ["a", "b"].map((plan) =>
31
+ setup.connect(tokens({ accountEmail: `${plan}@example.com`, accessToken: `sk-ant-oat01-${plan}`, expiresAt: future }), null)!
32
+ );
33
+ const configPath = join(dir, "dari-gateway.yaml");
34
+ writeFileSync(configPath, `
35
+ routers:
36
+ default:
37
+ models: [anthropic/claude-sonnet-5-5]
38
+ providers:
39
+ anthropic:
40
+ baseUrl: http://127.0.0.1:${provider.port}
41
+ api: anthropic-messages
42
+ `);
43
+ const port = await freePort();
44
+ const gateway = Bun.spawn(["bun", join(import.meta.dir, "main.ts")], {
45
+ env: {
46
+ PATH: process.env.PATH ?? "",
47
+ DARI_GATEWAY_KEYS: "k",
48
+ DARI_GATEWAY_CONFIG: configPath,
49
+ DARI_GATEWAY_DB: dbPath,
50
+ PORT: String(port),
51
+ },
52
+ stdout: "pipe",
53
+ stderr: "inherit",
54
+ });
55
+ await waitForLine(gateway.stdout as ReadableStream<Uint8Array>, "dari-gateway listening");
56
+ const baseUrl = `http://127.0.0.1:${port}`;
57
+
58
+ return {
59
+ served,
60
+ planIds: plans.map((plan) => plan.id),
61
+ // The plans as the gateway stored them.
62
+ plan: (id: string) => new SubscriptionStore(new Database(dbPath)).get(id),
63
+ // One Claude Code request in the conversation `sessionId` starts.
64
+ claudeCode: async (sessionId: string, text: string) =>
65
+ await fetch(`${baseUrl}/v1/messages`, {
66
+ method: "POST",
67
+ headers: {
68
+ "x-api-key": "k",
69
+ "anthropic-version": "2023-06-01",
70
+ "content-type": "application/json",
71
+ "user-agent": "claude-cli/2.1.300 (external, cli)",
72
+ "x-app": "cli",
73
+ "x-claude-code-session-id": sessionId,
74
+ },
75
+ body: JSON.stringify({
76
+ model: "dari/model/anthropic/claude-sonnet-5-5",
77
+ max_tokens: 64,
78
+ stream: true,
79
+ messages: [{ role: "user", content: text }],
80
+ }),
81
+ }),
82
+ stop: async () => {
83
+ gateway.kill();
84
+ await gateway.exited;
85
+ await provider.stop(true);
86
+ },
87
+ };
88
+ }
89
+
90
+ /** A streamed Anthropic reply with the given response headers. */
91
+ export function anthropicReply(headers: Record<string, string> = {}): Response {
92
+ const events = [
93
+ { type: "message_start", message: { id: "msg_1", type: "message", role: "assistant", model: "claude-sonnet-5-5", content: [], stop_reason: null, stop_sequence: null, usage: { input_tokens: 10, output_tokens: 0 } } },
94
+ { type: "content_block_start", index: 0, content_block: { type: "text", text: "" } },
95
+ { type: "content_block_delta", index: 0, delta: { type: "text_delta", text: "hi" } },
96
+ { type: "content_block_stop", index: 0 },
97
+ { type: "message_delta", delta: { stop_reason: "end_turn", stop_sequence: null }, usage: { output_tokens: 2 } },
98
+ { type: "message_stop" },
99
+ ];
100
+ const text = events.map((event) => `event: ${event.type}\ndata: ${JSON.stringify(event)}\n\n`).join("");
101
+ return new Response(text, { headers: { "content-type": "text/event-stream", ...headers } });
102
+ }
103
+
104
+ export async function waitFor(condition: () => boolean): Promise<void> {
105
+ for (let attempt = 0; attempt < 200 && !condition(); attempt += 1) {
106
+ await new Promise((resolve) => setTimeout(resolve, 10));
107
+ }
108
+ expect(condition()).toBe(true);
109
+ }
110
+
111
+ async function freePort(): Promise<number> {
112
+ const probe = Bun.serve({ port: 0, fetch: () => new Response() });
113
+ const port = probe.port;
114
+ await probe.stop(true);
115
+ return port!;
116
+ }
117
+
118
+ async function waitForLine(stream: ReadableStream<Uint8Array>, marker: string): Promise<void> {
119
+ const reader = stream.getReader();
120
+ const decoder = new TextDecoder();
121
+ let output = "";
122
+ while (!output.includes(marker)) {
123
+ const { value, done } = await reader.read();
124
+ if (done) throw new Error(`Gateway exited before "${marker}":\n${output}`);
125
+ output += decoder.decode(value);
126
+ }
127
+ reader.releaseLock();
128
+ void stream.pipeTo(new WritableStream());
129
+ }
@@ -13,7 +13,7 @@ import {
13
13
  type OAuthFetch,
14
14
  type SubscriptionProvider,
15
15
  } from "./oauth.js";
16
- import { isHeld, type SubscriptionCredential, type SubscriptionStore } from "./store.js";
16
+ import { isHeld, type SubscriptionCredential, type SubscriptionStore, currentUsage } from "./store.js";
17
17
 
18
18
  export type SubscriptionHttpDeps = {
19
19
  store: SubscriptionStore;
@@ -160,6 +160,11 @@ function summary(store: SubscriptionStore, credential: SubscriptionCredential, n
160
160
  }
161
161
 
162
162
  /** The fields the CLI reads from a credential, never its tokens. */
163
+ function usageBody(credential: SubscriptionCredential, now: Date) {
164
+ const usage = currentUsage(credential, now);
165
+ return usage === null ? null : { utilization: usage.utilization, resets_at: usage.resetsAt.toISOString() };
166
+ }
167
+
163
168
  function credentialBody(credential: SubscriptionCredential, active: boolean, now: Date) {
164
169
  const held = isHeld(credential, now);
165
170
  return {
@@ -176,6 +181,9 @@ function credentialBody(credential: SubscriptionCredential, active: boolean, now
176
181
  unavailable_until: held ? credential.unavailableUntil!.toISOString() : null,
177
182
  unavailable_reason: held ? credential.unavailableReason : null,
178
183
  subscription_active: active,
184
+ // The share of its tightest window the plan last reported used, while
185
+ // that window has not reset; null when it reports none.
186
+ usage: usageBody(credential, now),
179
187
  // Spending banked Codex resets is hosted-only.
180
188
  auto_redeem_resets: false,
181
189
  };
@@ -13,8 +13,9 @@
13
13
  * Dari CLI uses to connect, list, rename, release, and disconnect
14
14
  * subscriptions. The caller authenticates the request first.
15
15
  *
16
- * Routing picks `store.activeCredential(provider)`: the subscription in use
17
- * while it serves, then the next one in connection order that is not held. When a provider reports a usage limit,
16
+ * Routing picks `store.selectCredential(provider, conversationId)`: see
17
+ * `store.ts` for how usage, resets, and conversations decide it. Successful
18
+ * responses report usage through `store.recordUsage`. When a provider reports a usage limit,
18
19
  * `store.markUnavailable` holds that subscription until its reset and says
19
20
  * whether another one can serve the retry.
20
21
  */
@@ -1,20 +1,39 @@
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";
14
25
  import { randomBytes, randomUUID } from "node:crypto";
15
26
 
27
+ import type { SubscriptionUsage } from "../../providers/subscription_limits.js";
16
28
  import type { OAuthTokens, SubscriptionProvider } from "./oauth.js";
17
29
 
30
+ // The share of a usage window past which conversations leave a subscription
31
+ // at their next turn, before the provider starts refusing requests.
32
+ export const SWITCH_AT_UTILIZATION = 0.95;
33
+
34
+ // A conversation idle this long is forgotten; its next turn starts over.
35
+ const CONVERSATION_PIN_TTL_MS = 7 * 24 * 60 * 60_000;
36
+
18
37
  export type SubscriptionCredential = {
19
38
  id: string;
20
39
  provider: SubscriptionProvider;
@@ -29,6 +48,8 @@ export type SubscriptionCredential = {
29
48
  expiresAt: Date;
30
49
  unavailableUntil: Date | null;
31
50
  unavailableReason: string | null;
51
+ // The last usage a response reported, and when.
52
+ usage: (SubscriptionUsage & { observedAt: Date }) | null;
32
53
  position: number;
33
54
  createdAt: Date;
34
55
  updatedAt: Date;
@@ -62,12 +83,23 @@ type CredentialRow = {
62
83
  expires_at: number;
63
84
  unavailable_until: number | null;
64
85
  unavailable_reason: string | null;
86
+ usage_utilization: number | null;
87
+ usage_resets_at: number | null;
88
+ usage_observed_at: number | null;
65
89
  position: number;
66
90
  created_at: number;
67
91
  updated_at: number;
68
92
  last_used_at: number | null;
69
93
  };
70
94
 
95
+ // Usage columns added after the table first shipped; existing databases gain
96
+ // them on open.
97
+ const USAGE_COLUMNS = {
98
+ usage_utilization: "REAL",
99
+ usage_resets_at: "INTEGER",
100
+ usage_observed_at: "INTEGER",
101
+ } as const;
102
+
71
103
  type SessionRow = {
72
104
  token: string;
73
105
  provider: SubscriptionProvider;
@@ -90,11 +122,27 @@ export class SubscriptionStore {
90
122
  expires_at INTEGER NOT NULL,
91
123
  unavailable_until INTEGER,
92
124
  unavailable_reason TEXT,
125
+ usage_utilization REAL,
126
+ usage_resets_at INTEGER,
127
+ usage_observed_at INTEGER,
93
128
  position INTEGER NOT NULL,
94
129
  created_at INTEGER NOT NULL,
95
130
  updated_at INTEGER NOT NULL,
96
131
  last_used_at INTEGER
97
132
  )`);
133
+ const columns = new Set(
134
+ db.query<{ name: string }, []>("PRAGMA table_info(subscription_credentials)").all().map((column) => column.name),
135
+ );
136
+ for (const [column, type] of Object.entries(USAGE_COLUMNS)) {
137
+ if (!columns.has(column)) db.run(`ALTER TABLE subscription_credentials ADD COLUMN ${column} ${type}`);
138
+ }
139
+ db.run(`CREATE TABLE IF NOT EXISTS subscription_conversation_pins (
140
+ conversation_id TEXT NOT NULL,
141
+ provider TEXT NOT NULL,
142
+ credential_id TEXT NOT NULL,
143
+ used_at INTEGER NOT NULL,
144
+ PRIMARY KEY (conversation_id, provider)
145
+ )`);
98
146
  db.run(`CREATE TABLE IF NOT EXISTS subscription_oauth_sessions (
99
147
  token TEXT PRIMARY KEY,
100
148
  provider TEXT NOT NULL,
@@ -126,21 +174,75 @@ export class SubscriptionStore {
126
174
  return row === null ? null : credentialFromRow(row);
127
175
  }
128
176
 
129
- /** The credential routing uses now, or null when none is connected or every one is held. */
177
+ /**
178
+ * The subscription a request without a conversation would use now, or null
179
+ * when none is connected or every one is held.
180
+ */
130
181
  activeCredential(provider: SubscriptionProvider, now = new Date()): SubscriptionCredential | null {
131
- // Stay on the most recently used subscription while it serves, so its
132
- // prompt cache stays warm; once it is held, move on in connection order.
133
- const credentials = this.list(provider);
134
- let start = 0;
135
- credentials.forEach((credential, index) => {
136
- const lastUsed = credential.lastUsedAt?.getTime() ?? -1;
137
- if (lastUsed > (credentials[start]!.lastUsedAt?.getTime() ?? -1)) start = index;
138
- });
139
- for (let offset = 0; offset < credentials.length; offset += 1) {
140
- const credential = credentials[(start + offset) % credentials.length]!;
141
- if (!isHeld(credential, now)) return credential;
182
+ return this.selectCredential(provider, undefined, now);
183
+ }
184
+
185
+ /**
186
+ * The subscription that serves a conversation's next turn (see the module
187
+ * comment), or null when none is connected or every one is held. A
188
+ * conversation is remembered on the subscription chosen for it.
189
+ */
190
+ selectCredential(
191
+ provider: SubscriptionProvider,
192
+ conversationId: string | undefined,
193
+ now = new Date(),
194
+ ): SubscriptionCredential | null {
195
+ const all = this.list(provider);
196
+ const available = all.filter((credential) => !isHeld(credential, now));
197
+ if (available.length === 0) return null;
198
+ const order = rotationFrom(all, lastUsed(all));
199
+ const withHeadroom = available.filter((credential) => hasHeadroom(credential, now));
200
+
201
+ const current = conversationId === undefined
202
+ ? lastUsed(available)
203
+ : this.pinnedCredential(conversationId, provider, available, now);
204
+ let chosen = current !== null && withHeadroom.includes(current) ? current : null;
205
+ if (chosen === null) {
206
+ chosen = withHeadroom.length > 0
207
+ ? [...withHeadroom].sort(soonestResetFirst(now, order))[0]!
208
+ : [...available].sort(leastUsedFirst(now, order))[0]!;
142
209
  }
143
- return null;
210
+ if (conversationId !== undefined) this.pinConversation(conversationId, provider, chosen.id, now);
211
+ return chosen;
212
+ }
213
+
214
+ /** Record the usage a response reported for a subscription. */
215
+ recordUsage(id: string, usage: SubscriptionUsage, now = new Date()): void {
216
+ this.db.run(
217
+ "UPDATE subscription_credentials SET usage_utilization = ?, usage_resets_at = ?, usage_observed_at = ? WHERE id = ?",
218
+ [usage.utilization, usage.resetsAt.getTime(), now.getTime(), id],
219
+ );
220
+ }
221
+
222
+ // A pin idle past CONVERSATION_PIN_TTL_MS is forgotten: the conversation is
223
+ // assigned like a new one.
224
+ private pinnedCredential(
225
+ conversationId: string,
226
+ provider: SubscriptionProvider,
227
+ available: SubscriptionCredential[],
228
+ now: Date,
229
+ ): SubscriptionCredential | null {
230
+ const row = this.db
231
+ .query<{ credential_id: string }, [string, string, number]>(
232
+ `SELECT credential_id FROM subscription_conversation_pins
233
+ WHERE conversation_id = ? AND provider = ? AND used_at >= ?`,
234
+ )
235
+ .get(conversationId, provider, now.getTime() - CONVERSATION_PIN_TTL_MS);
236
+ return available.find((credential) => credential.id === row?.credential_id) ?? null;
237
+ }
238
+
239
+ private pinConversation(conversationId: string, provider: SubscriptionProvider, credentialId: string, now: Date): void {
240
+ this.db.run(
241
+ `INSERT INTO subscription_conversation_pins (conversation_id, provider, credential_id, used_at) VALUES (?, ?, ?, ?)
242
+ ON CONFLICT (conversation_id, provider) DO UPDATE SET credential_id = excluded.credential_id, used_at = excluded.used_at`,
243
+ [conversationId, provider, credentialId, now.getTime()],
244
+ );
245
+ this.db.run("DELETE FROM subscription_conversation_pins WHERE used_at < ?", [now.getTime() - CONVERSATION_PIN_TTL_MS]);
144
246
  }
145
247
 
146
248
  /**
@@ -159,11 +261,15 @@ export class SubscriptionStore {
159
261
  if (reconnectName !== null && existing?.provider !== tokens.provider) return null;
160
262
 
161
263
  if (existing !== null) {
162
- // Another (or an unidentified) account must not inherit the previous account's hold.
264
+ // Another (or an unidentified) account must not inherit the previous
265
+ // account's hold, reported usage, or conversations (whose cache is
266
+ // the previous account's).
163
267
  const sameAccount = tokens.accountEmail !== null && tokens.accountEmail === existing.accountEmail;
268
+ const usage = sameAccount ? existing.usage : null;
164
269
  this.db.run(
165
270
  `UPDATE subscription_credentials SET access_token = ?, refresh_token = ?, expires_at = ?,
166
- account_id = ?, account_email = ?, unavailable_until = ?, unavailable_reason = ?, updated_at = ?
271
+ account_id = ?, account_email = ?, unavailable_until = ?, unavailable_reason = ?,
272
+ usage_utilization = ?, usage_resets_at = ?, usage_observed_at = ?, updated_at = ?
167
273
  WHERE id = ?`,
168
274
  [
169
275
  tokens.accessToken,
@@ -173,10 +279,16 @@ export class SubscriptionStore {
173
279
  tokens.accountEmail,
174
280
  sameAccount ? existing.unavailableUntil?.getTime() ?? null : null,
175
281
  sameAccount ? existing.unavailableReason : null,
282
+ usage?.utilization ?? null,
283
+ usage?.resetsAt.getTime() ?? null,
284
+ usage?.observedAt.getTime() ?? null,
176
285
  now.getTime(),
177
286
  existing.id,
178
287
  ],
179
288
  );
289
+ if (!sameAccount) {
290
+ this.db.run("DELETE FROM subscription_conversation_pins WHERE credential_id = ?", [existing.id]);
291
+ }
180
292
  return this.get(existing.id);
181
293
  }
182
294
 
@@ -240,6 +352,7 @@ export class SubscriptionStore {
240
352
  const credential = this.getByName(name);
241
353
  if (credential === null) return null;
242
354
  this.db.run("DELETE FROM subscription_credentials WHERE id = ?", [credential.id]);
355
+ this.db.run("DELETE FROM subscription_conversation_pins WHERE credential_id = ?", [credential.id]);
243
356
  return credential;
244
357
  }
245
358
 
@@ -314,6 +427,48 @@ export function isHeld(credential: SubscriptionCredential, now: Date): boolean {
314
427
  return credential.unavailableUntil !== null && credential.unavailableUntil > now;
315
428
  }
316
429
 
430
+ /** The usage a subscription last reported, while its window has not reset. */
431
+ export function currentUsage(credential: SubscriptionCredential, now: Date): SubscriptionUsage | null {
432
+ return credential.usage !== null && credential.usage.resetsAt > now ? credential.usage : null;
433
+ }
434
+
435
+ function hasHeadroom(credential: SubscriptionCredential, now: Date): boolean {
436
+ return (currentUsage(credential, now)?.utilization ?? 0) < SWITCH_AT_UTILIZATION;
437
+ }
438
+
439
+ function lastUsed(credentials: SubscriptionCredential[]): SubscriptionCredential | null {
440
+ let latest: SubscriptionCredential | null = null;
441
+ for (const credential of credentials) {
442
+ if (credential.lastUsedAt !== null && (latest === null || credential.lastUsedAt > latest.lastUsedAt!)) {
443
+ latest = credential;
444
+ }
445
+ }
446
+ return latest;
447
+ }
448
+
449
+ // Each credential's rank in connection order starting at `anchor` (the one
450
+ // used last), wrapping past the end; without an anchor, connection order.
451
+ function rotationFrom(all: SubscriptionCredential[], anchor: SubscriptionCredential | null): Map<string, number> {
452
+ const start = anchor === null ? 0 : all.indexOf(anchor);
453
+ return new Map(all.map((credential, index) => [credential.id, (index - start + all.length) % all.length]));
454
+ }
455
+
456
+ // Spend quota about to reset first; a subscription with no current usage
457
+ // report (fresh, or its window reset) comes after, then rotation order.
458
+ function soonestResetFirst(now: Date, order: Map<string, number>) {
459
+ return (a: SubscriptionCredential, b: SubscriptionCredential): number => {
460
+ const resetA = currentUsage(a, now)?.resetsAt.getTime() ?? Infinity;
461
+ const resetB = currentUsage(b, now)?.resetsAt.getTime() ?? Infinity;
462
+ return resetA - resetB || order.get(a.id)! - order.get(b.id)!;
463
+ };
464
+ }
465
+
466
+ function leastUsedFirst(now: Date, order: Map<string, number>) {
467
+ return (a: SubscriptionCredential, b: SubscriptionCredential): number =>
468
+ (currentUsage(a, now)?.utilization ?? 0) - (currentUsage(b, now)?.utilization ?? 0)
469
+ || order.get(a.id)! - order.get(b.id)!;
470
+ }
471
+
317
472
  /** Subscription names are env-var-style identifiers; matching is case-insensitive. */
318
473
  export function normalizeName(name: string): string {
319
474
  return name.trim().toUpperCase();
@@ -332,6 +487,13 @@ function credentialFromRow(row: CredentialRow): SubscriptionCredential {
332
487
  expiresAt: new Date(row.expires_at),
333
488
  unavailableUntil: row.unavailable_until === null ? null : new Date(row.unavailable_until),
334
489
  unavailableReason: row.unavailable_reason,
490
+ usage: row.usage_utilization === null || row.usage_resets_at === null || row.usage_observed_at === null
491
+ ? null
492
+ : {
493
+ utilization: row.usage_utilization,
494
+ resetsAt: new Date(row.usage_resets_at),
495
+ observedAt: new Date(row.usage_observed_at),
496
+ },
335
497
  position: row.position,
336
498
  createdAt: new Date(row.created_at),
337
499
  updatedAt: new Date(row.updated_at),