@mupt-ai/dari-gateway 1.0.290 → 1.0.292

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 (55) hide show
  1. package/README.md +1 -1
  2. package/dist/ingress/codex_models.d.ts +1 -1
  3. package/dist/ingress/codex_models.js +1 -1
  4. package/dist/ingress/models.js +11 -1
  5. package/dist/ingress/muse_models.d.ts +1 -1
  6. package/dist/ingress/muse_models.js +1 -1
  7. package/dist/models/canonical.d.ts +7 -2
  8. package/dist/models/canonical.js +3 -3
  9. package/dist/models/canonical_models.json +337 -0
  10. package/dist/platform/platform.d.ts +30 -2
  11. package/dist/providers/execution.js +66 -1
  12. package/dist/providers/provider_attempt_runner.d.ts +3 -0
  13. package/dist/providers/provider_attempt_runner.js +11 -2
  14. package/dist/providers/response_capture.d.ts +3 -1
  15. package/dist/providers/response_capture.js +6 -2
  16. package/dist/providers/subscription_limits.d.ts +16 -0
  17. package/dist/providers/subscription_limits.js +25 -0
  18. package/dist/runtime/prepare_routed_completion.js +2 -0
  19. package/dist/self_host/main.js +4 -3
  20. package/dist/self_host/platform.d.ts +1 -1
  21. package/dist/self_host/platform.js +15 -0
  22. package/dist/self_host/resolve.d.ts +1 -0
  23. package/dist/self_host/resolve.js +7 -2
  24. package/dist/self_host/subscription_test_gateway.d.ts +16 -0
  25. package/dist/self_host/subscription_test_gateway.js +120 -0
  26. package/dist/self_host/subscriptions/http.js +8 -1
  27. package/dist/self_host/subscriptions/index.d.ts +3 -2
  28. package/dist/self_host/subscriptions/index.js +3 -2
  29. package/dist/self_host/subscriptions/store.d.ts +36 -5
  30. package/dist/self_host/subscriptions/store.js +129 -17
  31. package/dist/self_host/subscriptions/test_support.d.ts +15 -0
  32. package/dist/self_host/subscriptions/test_support.js +34 -0
  33. package/dist/types.d.ts +1 -0
  34. package/package.json +2 -2
  35. package/src/ingress/codex_models.ts +2 -2
  36. package/src/ingress/models.ts +14 -1
  37. package/src/ingress/muse_models.ts +2 -2
  38. package/src/models/canonical.ts +10 -3
  39. package/src/models/canonical_models.json +337 -0
  40. package/src/platform/platform.ts +39 -2
  41. package/src/providers/execution.ts +72 -0
  42. package/src/providers/provider_attempt_runner.ts +18 -2
  43. package/src/providers/response_capture.ts +10 -2
  44. package/src/providers/subscription_limits.ts +39 -0
  45. package/src/runtime/prepare_routed_completion.ts +2 -0
  46. package/src/self_host/main.ts +4 -3
  47. package/src/self_host/platform.ts +14 -1
  48. package/src/self_host/resolve.ts +10 -2
  49. package/src/self_host/subscription_test_gateway.ts +129 -0
  50. package/src/self_host/subscriptions/http.ts +9 -1
  51. package/src/self_host/subscriptions/index.ts +3 -2
  52. package/src/self_host/subscriptions/store.ts +181 -19
  53. package/src/types.ts +4 -0
  54. package/dist/models/canonical_model_ids.json +0 -33
  55. package/src/models/canonical_model_ids.json +0 -33
@@ -1,6 +1,7 @@
1
1
  const CAPTURED_BODY_MAX_BYTES = 64 * 1024;
2
2
  /**
3
- * A fetch wrapper that remembers the last failed provider response. pi-ai
3
+ * A fetch wrapper that remembers the last failed provider response, and the
4
+ * headers of the last successful one. pi-ai
4
5
  * flattens provider errors into one message string before they reach the
5
6
  * runtime, so this is the only place the status, rate-limit headers, and
6
7
  * structured error body of a rejected call can still be read.
@@ -8,10 +9,13 @@ const CAPTURED_BODY_MAX_BYTES = 64 * 1024;
8
9
  export function createProviderResponseCapture() {
9
10
  const capture = {
10
11
  last: undefined,
12
+ succeeded: undefined,
11
13
  fetch: async (input, init) => {
12
14
  const response = await globalThis.fetch(input, init);
13
- if (response.ok)
15
+ if (response.ok) {
16
+ capture.succeeded = response.headers;
14
17
  return response;
18
+ }
15
19
  const bodyText = await readBodyPrefix(response.clone());
16
20
  capture.last = { status: response.status, headers: response.headers, bodyText };
17
21
  return response;
@@ -7,6 +7,22 @@ export type SubscriptionUsageLimit = {
7
7
  reason: string;
8
8
  switched?: boolean;
9
9
  };
10
+ /**
11
+ * How much of a subscription's quota is used, from a successful response.
12
+ * `utilization` is the binding window's share used (0 to 1): the window
13
+ * closest to its limit, whose reset is `resetsAt`.
14
+ */
15
+ export type SubscriptionUsage = {
16
+ utilization: number;
17
+ resetsAt: Date;
18
+ };
19
+ /**
20
+ * The quota a successful subscription response reports used, or null when it
21
+ * reports none. Only Claude Code plans report usage on every response; a
22
+ * ChatGPT plan reports it inside the response stream, which the provider
23
+ * client does not surface, so its plans are switched only on a usage limit.
24
+ */
25
+ export declare function subscriptionUsageFromHeaders(provider: string, keySource: ProviderKeySource, headers: Headers, now?: Date): SubscriptionUsage | null;
10
26
  export declare const DEFAULT_USAGE_LIMIT_WINDOW_MS: number;
11
27
  export declare function subscriptionOAuthProviderFor(provider: string, keySource: ProviderKeySource): SubscriptionOAuthProvider | null;
12
28
  /**
@@ -1,5 +1,30 @@
1
1
  import { isRecord } from "@mupt-ai/dari-router/policy-engine";
2
2
  import { providerFailureMessage } from "../runtime/provider_stream_outcome.js";
3
+ // Claude Code's unified limiter reports each window on every response, the
4
+ // same headers Claude Code itself reads: `-utilization` as a fraction of the
5
+ // window and `-reset` in unix seconds.
6
+ const CLAUDE_CODE_USAGE_WINDOWS = ["5h", "7d"];
7
+ /**
8
+ * The quota a successful subscription response reports used, or null when it
9
+ * reports none. Only Claude Code plans report usage on every response; a
10
+ * ChatGPT plan reports it inside the response stream, which the provider
11
+ * client does not surface, so its plans are switched only on a usage limit.
12
+ */
13
+ export function subscriptionUsageFromHeaders(provider, keySource, headers, now = new Date()) {
14
+ if (subscriptionOAuthProviderFor(provider, keySource) !== "anthropic_claude_code")
15
+ return null;
16
+ let binding = null;
17
+ for (const window of CLAUDE_CODE_USAGE_WINDOWS) {
18
+ const raw = Number(headers.get(`anthropic-ratelimit-unified-${window}-utilization`) ?? NaN);
19
+ const resetsAt = unixSecondsDeadline(headers.get(`anthropic-ratelimit-unified-${window}-reset`), now);
20
+ if (!Number.isFinite(raw) || resetsAt === null)
21
+ continue;
22
+ const utilization = Math.max(0, Math.min(1, raw));
23
+ if (binding === null || utilization > binding.utilization)
24
+ binding = { utilization, resetsAt };
25
+ }
26
+ return binding;
27
+ }
3
28
  // Neither provider guarantees a reset time on every usage-limit response.
4
29
  // Without one, hold the subscription out for an hour rather than hammering an
5
30
  // exhausted plan on every request.
@@ -33,6 +33,8 @@ export async function prepareRoutedCompletion(args) {
33
33
  ...resolveRequest,
34
34
  prefixHashes,
35
35
  clientHarness: args.clientHarness,
36
+ // Re-resolved below with the harness conversation, whose credentials serve.
37
+ ...(!background && args.harnessConversationIdentity !== undefined ? { provisional: true } : {}),
36
38
  });
37
39
  const canonicalRouterId = credentials.router_id;
38
40
  const organizationId = credentials.organization_id;
@@ -11,7 +11,7 @@ import { createPrioritySelectorBackend } from "../strategies/priority_selector.j
11
11
  import { createSelfHostedPlatform } from "./platform.js";
12
12
  import { providerForModel } from "@mupt-ai/dari-router/policy-engine";
13
13
  import { checkProviderKey } from "../providers/key_check.js";
14
- import { CANONICAL_MODEL_IDS } from "../models/canonical.js";
14
+ import { CANONICAL_MODELS } from "../models/canonical.js";
15
15
  import { DEFAULT_GATEWAY_CONFIG, loadGatewayConfig } from "./config.js";
16
16
  import { configuredProviderApiKey, gatewayKeyIndex, providersWithoutCredentials } from "./resolve.js";
17
17
  import { PrefixStore } from "./prefix_store.js";
@@ -55,6 +55,7 @@ export async function startSelfHostedGateway(env = process.env) {
55
55
  authContext: { env: async (name) => env[name], fileExists: async () => false },
56
56
  });
57
57
  const providerApiKey = async (provider) => (await piModels.getAuth(provider))?.auth.apiKey;
58
+ const autoRoutingKey = env.DARI_AUTO_ROUTING_API_KEY?.trim();
58
59
  const platform = createSelfHostedPlatform({
59
60
  config,
60
61
  gatewayKeys,
@@ -62,6 +63,7 @@ export async function startSelfHostedGateway(env = process.env) {
62
63
  prefixes,
63
64
  sessionPins,
64
65
  providerApiKey,
66
+ autoRouting: Boolean(autoRoutingKey),
65
67
  env,
66
68
  fetch,
67
69
  });
@@ -74,7 +76,6 @@ export async function startSelfHostedGateway(env = process.env) {
74
76
  }
75
77
  }
76
78
  await checkConfiguredProviderKeys(config, (provider) => configuredProviderApiKey({ config, providerApiKey, env }, provider));
77
- const autoRoutingKey = env.DARI_AUTO_ROUTING_API_KEY?.trim();
78
79
  const selectorBackend = autoRoutingKey
79
80
  ? createAutoRoutingSelectorBackend({
80
81
  apiKey: autoRoutingKey,
@@ -142,7 +143,7 @@ export async function runSelfHostedGateway() {
142
143
  // JSON, and exits; `--print-default-config` prints the built-in default.
143
144
  // The Dari CLI edits a local gateway's models from them.
144
145
  if (process.argv.includes("--print-canonical-models")) {
145
- console.log(JSON.stringify(CANONICAL_MODEL_IDS));
146
+ console.log(JSON.stringify(CANONICAL_MODELS));
146
147
  return;
147
148
  }
148
149
  if (process.argv.includes("--print-default-config")) {
@@ -2,7 +2,7 @@ import type { GatewayPlatform } from "../platform/platform.js";
2
2
  import type { PrefixStore } from "./prefix_store.js";
3
3
  import type { SessionPinStore } from "./session_pin_store.js";
4
4
  import { type SelfHostedResolverDeps } from "./resolve.js";
5
- import type { SubscriptionStore } from "./subscriptions/index.js";
5
+ import { type SubscriptionStore } from "./subscriptions/index.js";
6
6
  /**
7
7
  * The self-hosted platform: routers from the config file, subscriptions,
8
8
  * prefix-cache state, and session pins in the gateway's SQLite database, and one content-free
@@ -1,5 +1,7 @@
1
1
  import { errorCode } from "../http/errors.js";
2
+ import { subscriptionOAuthProviderFor } from "../providers/subscription_limits.js";
2
3
  import { resolveSelfHostedRouter } from "./resolve.js";
4
+ import { freshAccessToken } from "./subscriptions/index.js";
3
5
  /**
4
6
  * The self-hosted platform: routers from the config file, subscriptions,
5
7
  * prefix-cache state, and session pins in the gateway's SQLite database, and one content-free
@@ -22,6 +24,19 @@ export function createSelfHostedPlatform(deps) {
22
24
  writeSessionPin: async (write) => {
23
25
  deps.sessionPins.write(write);
24
26
  },
27
+ recordSubscriptionUsage: async (report) => {
28
+ deps.subscriptions.recordUsage(report.credentialId, report.usage);
29
+ },
30
+ async nextSubscription(request) {
31
+ const plan = subscriptionOAuthProviderFor(request.provider, "subscription");
32
+ const next = plan === null ? null : deps.subscriptions.selectCredential(plan, request.conversationId);
33
+ if (next === null)
34
+ return undefined;
35
+ return {
36
+ credentialId: next.id,
37
+ apiKey: await freshAccessToken(deps.subscriptions, next, { fetch: deps.fetch }),
38
+ };
39
+ },
25
40
  markSubscriptionUnavailable: async (hold) => hold.credentialId !== undefined &&
26
41
  deps.subscriptions.markUnavailable(hold.credentialId, hold.limit.resetsAt, hold.limit.reason),
27
42
  async recordUsage() {
@@ -15,6 +15,7 @@ export type SelfHostedResolverDeps = {
15
15
  conversationId?: string;
16
16
  }) => RouterPrefixHit[];
17
17
  providerApiKey: (provider: string) => Promise<string | undefined>;
18
+ autoRouting: boolean;
18
19
  env: Record<string, string | undefined>;
19
20
  fetch: OAuthFetch;
20
21
  };
@@ -32,10 +32,14 @@ export async function resolveSelfHostedRouter(deps, request) {
32
32
  : null;
33
33
  const active = subscription === null
34
34
  ? null
35
- : deps.subscriptions.activeCredential(subscription, now);
35
+ : deps.subscriptions.selectCredential(subscription, request.conversationId, now);
36
36
  if (active !== null) {
37
37
  credentials.set(provider, {
38
- key: await freshAccessToken(deps.subscriptions, active, { fetch: deps.fetch }),
38
+ // A provisional resolve's credentials never serve, so it neither marks
39
+ // the plan used nor refreshes its token.
40
+ key: request.provisional === true
41
+ ? active.accessToken
42
+ : await freshAccessToken(deps.subscriptions, active, { fetch: deps.fetch }),
39
43
  source: "subscription",
40
44
  subscription: active,
41
45
  });
@@ -58,6 +62,7 @@ export async function resolveSelfHostedRouter(deps, request) {
58
62
  api_key_id: `gateway_key_${keyIndex + 1}`,
59
63
  attributed_user_id: SELF_HOSTED_USER_ID,
60
64
  enabled_models: models.map((model) => model.id),
65
+ routing_listed: deps.autoRouting,
61
66
  provider_keys: {},
62
67
  provider_key_sources: {},
63
68
  subscription_credential_ids: {},
@@ -0,0 +1,16 @@
1
+ /**
2
+ * A self-hosted gateway, run through its entrypoint as its own process so no
3
+ * other test file's module mocks reach it, serving two Claude Code plans
4
+ * (access tokens `sk-ant-oat01-a` and `-b`) against a local stand-in for
5
+ * Anthropic. `upstream` answers each provider call given the plan's token.
6
+ */
7
+ export declare function startSubscriptionGateway(upstream: (token: string) => Response): Promise<{
8
+ served: string[];
9
+ planIds: string[];
10
+ plan: (id: string) => import("./subscriptions/store.js").SubscriptionCredential | null;
11
+ claudeCode: (sessionId: string, text: string) => Promise<Response>;
12
+ stop: () => Promise<void>;
13
+ }>;
14
+ /** A streamed Anthropic reply with the given response headers. */
15
+ export declare function anthropicReply(headers?: Record<string, string>): Response;
16
+ export declare function waitFor(condition: () => boolean): Promise<void>;
@@ -0,0 +1,120 @@
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
+ import { SubscriptionStore } from "./subscriptions/index.js";
7
+ import { tokens } from "./subscriptions/test_support.js";
8
+ /**
9
+ * A self-hosted gateway, run through its entrypoint as its own process so no
10
+ * other test file's module mocks reach it, serving two Claude Code plans
11
+ * (access tokens `sk-ant-oat01-a` and `-b`) against a local stand-in for
12
+ * Anthropic. `upstream` answers each provider call given the plan's token.
13
+ */
14
+ export async function startSubscriptionGateway(upstream) {
15
+ const served = [];
16
+ const provider = Bun.serve({
17
+ port: 0,
18
+ fetch(request) {
19
+ const token = (request.headers.get("authorization") ?? "").replace(/^Bearer /, "");
20
+ served.push(token);
21
+ return upstream(token);
22
+ },
23
+ });
24
+ const dir = mkdtempSync(join(tmpdir(), "dari-gateway-plans-"));
25
+ const dbPath = join(dir, "gateway.db");
26
+ const setup = new SubscriptionStore(new Database(dbPath));
27
+ const future = new Date(Date.now() + 86_400_000);
28
+ const plans = ["a", "b"].map((plan) => setup.connect(tokens({ accountEmail: `${plan}@example.com`, accessToken: `sk-ant-oat01-${plan}`, expiresAt: future }), null));
29
+ const configPath = join(dir, "dari-gateway.yaml");
30
+ writeFileSync(configPath, `
31
+ routers:
32
+ default:
33
+ models: [anthropic/claude-sonnet-5-5]
34
+ providers:
35
+ anthropic:
36
+ baseUrl: http://127.0.0.1:${provider.port}
37
+ api: anthropic-messages
38
+ `);
39
+ const port = await freePort();
40
+ const gateway = Bun.spawn(["bun", join(import.meta.dir, "main.ts")], {
41
+ env: {
42
+ PATH: process.env.PATH ?? "",
43
+ DARI_GATEWAY_KEYS: "k",
44
+ DARI_GATEWAY_CONFIG: configPath,
45
+ DARI_GATEWAY_DB: dbPath,
46
+ PORT: String(port),
47
+ },
48
+ stdout: "pipe",
49
+ stderr: "inherit",
50
+ });
51
+ await waitForLine(gateway.stdout, "dari-gateway listening");
52
+ const baseUrl = `http://127.0.0.1:${port}`;
53
+ return {
54
+ served,
55
+ planIds: plans.map((plan) => plan.id),
56
+ // The plans as the gateway stored them.
57
+ plan: (id) => new SubscriptionStore(new Database(dbPath)).get(id),
58
+ // One Claude Code request in the conversation `sessionId` starts.
59
+ claudeCode: async (sessionId, text) => await fetch(`${baseUrl}/v1/messages`, {
60
+ method: "POST",
61
+ headers: {
62
+ "x-api-key": "k",
63
+ "anthropic-version": "2023-06-01",
64
+ "content-type": "application/json",
65
+ "user-agent": "claude-cli/2.1.300 (external, cli)",
66
+ "x-app": "cli",
67
+ "x-claude-code-session-id": sessionId,
68
+ },
69
+ body: JSON.stringify({
70
+ model: "dari/model/anthropic/claude-sonnet-5-5",
71
+ max_tokens: 64,
72
+ stream: true,
73
+ messages: [{ role: "user", content: text }],
74
+ }),
75
+ }),
76
+ stop: async () => {
77
+ gateway.kill();
78
+ await gateway.exited;
79
+ await provider.stop(true);
80
+ },
81
+ };
82
+ }
83
+ /** A streamed Anthropic reply with the given response headers. */
84
+ export function anthropicReply(headers = {}) {
85
+ const events = [
86
+ { 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 } } },
87
+ { type: "content_block_start", index: 0, content_block: { type: "text", text: "" } },
88
+ { type: "content_block_delta", index: 0, delta: { type: "text_delta", text: "hi" } },
89
+ { type: "content_block_stop", index: 0 },
90
+ { type: "message_delta", delta: { stop_reason: "end_turn", stop_sequence: null }, usage: { output_tokens: 2 } },
91
+ { type: "message_stop" },
92
+ ];
93
+ const text = events.map((event) => `event: ${event.type}\ndata: ${JSON.stringify(event)}\n\n`).join("");
94
+ return new Response(text, { headers: { "content-type": "text/event-stream", ...headers } });
95
+ }
96
+ export async function waitFor(condition) {
97
+ for (let attempt = 0; attempt < 200 && !condition(); attempt += 1) {
98
+ await new Promise((resolve) => setTimeout(resolve, 10));
99
+ }
100
+ expect(condition()).toBe(true);
101
+ }
102
+ async function freePort() {
103
+ const probe = Bun.serve({ port: 0, fetch: () => new Response() });
104
+ const port = probe.port;
105
+ await probe.stop(true);
106
+ return port;
107
+ }
108
+ async function waitForLine(stream, marker) {
109
+ const reader = stream.getReader();
110
+ const decoder = new TextDecoder();
111
+ let output = "";
112
+ while (!output.includes(marker)) {
113
+ const { value, done } = await reader.read();
114
+ if (done)
115
+ throw new Error(`Gateway exited before "${marker}":\n${output}`);
116
+ output += decoder.decode(value);
117
+ }
118
+ reader.releaseLock();
119
+ void stream.pipeTo(new WritableStream());
120
+ }
@@ -5,7 +5,7 @@
5
5
  * every subscription. Errors are `{"detail": "..."}`, which the CLI prints.
6
6
  */
7
7
  import { SUBSCRIPTION_PROVIDERS, SubscriptionOAuthInputError, SubscriptionOAuthProviderError, completeOAuth, startOAuth, } from "./oauth.js";
8
- import { isHeld } from "./store.js";
8
+ import { isHeld, currentUsage } from "./store.js";
9
9
  const BASE = "/v1/organizations/current/credentials";
10
10
  // Subscription names are env-var-style, which keeps other credential routes
11
11
  // such as `provider-credentials/...` out of these matches.
@@ -144,6 +144,10 @@ function summary(store, credential, now) {
144
144
  return credentialBody(credential, store.activeCredential(credential.provider, now)?.id === credential.id, now);
145
145
  }
146
146
  /** The fields the CLI reads from a credential, never its tokens. */
147
+ function usageBody(credential, now) {
148
+ const usage = currentUsage(credential, now);
149
+ return usage === null ? null : { utilization: usage.utilization, resets_at: usage.resetsAt.toISOString() };
150
+ }
147
151
  function credentialBody(credential, active, now) {
148
152
  const held = isHeld(credential, now);
149
153
  return {
@@ -160,6 +164,9 @@ function credentialBody(credential, active, now) {
160
164
  unavailable_until: held ? credential.unavailableUntil.toISOString() : null,
161
165
  unavailable_reason: held ? credential.unavailableReason : null,
162
166
  subscription_active: active,
167
+ // The share of its tightest window the plan last reported used, while
168
+ // that window has not reset; null when it reports none.
169
+ usage: usageBody(credential, now),
163
170
  // Spending banked Codex resets is hosted-only.
164
171
  auto_redeem_resets: false,
165
172
  };
@@ -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
  */
@@ -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,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;