@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
package/README.md CHANGED
@@ -27,15 +27,18 @@ The gateway is the runtime behind Dari's hosted routing service, packaged to run
27
27
  ## Features
28
28
 
29
29
  - **One endpoint, three protocols.** `/v1/messages`, `/v1/chat/completions`, and `/v1/responses` (plus `/v1/models`) reach API-key providers in the [Pi AI](https://www.npmjs.com/package/@mupt-ai/pi-ai) catalog, such as Anthropic, OpenAI, and OpenRouter, or any OpenAI-compatible server.
30
- - **Subscription pooling.** Connect several Claude Code (Max/Pro) or ChatGPT plans. The gateway stays on one until it reports a usage limit, holds it until its reset, and moves to the next. When every plan is held, the provider's API key serves if you set one.
30
+ - **Subscription pooling.** Connect several Claude Code (Max/Pro) or ChatGPT plans. Each conversation stays on one plan so its prompt cache stays warm. Claude Code plans report their usage on every response: once a plan has used 95% of a window, its conversations move to another plan at their next turn, and new conversations start on the plan whose quota resets soonest. A plan that reports a usage limit is held until its reset, and the request it refused is served by the next plan at once. When every plan is held, the provider's API key serves if you set one.
31
31
  - **Failover.** A provider failure retries the router's next model.
32
32
  - **Prompt-cache aware.** Conversations keep their identity and serving model across turns, so provider caches stay warm. Responses carry `X-Dari-Selected-Model`, `X-Dari-Thinking-Level`, and `X-Dari-Conversation-Id` headers for status lines.
33
33
  - **Coding agents.** `dari claude`, `dari codex`, `dari opencode`, and `dari pi` from the [Dari CLI](https://github.com/mupt-ai/dari) launch straight against your gateway.
34
34
 
35
- The gateway is the same runtime that serves Dari's hosted routing service. Choosing among a router's models with Dari's trained routing policy (Dari Auto Routing) is optional and uses a Dari API key; without it, `dari/routing` serves the router's first available model.
35
+ Dari Auto Routing (choosing among a router's models with Dari's trained policy) is optional and needs a Dari API key; without it, `dari/routing` serves the router's first available model.
36
36
 
37
37
  ## Run
38
38
 
39
+ > [!IMPORTANT]
40
+ > **Observability needs hosted Dari.** Requests through your own gateway never reach Dari, so there is no Activity dashboard, per-request cost, or usage analytics. Use hosted mode (`dari gateway setup --mode hosted`) if you want them.
41
+
39
42
  The easiest way to run it on your own machine is the [Dari CLI](https://github.com/mupt-ai/dari): choose **Fully local** in `dari gateway setup` (or on your first `dari claude`), and it installs this gateway's standalone binary, runs it in the background, and connects your agents.
40
43
 
41
44
  To run it yourself, use [Bun](https://bun.sh) 1.3 or later, or the standalone binary for your platform from the [releases](https://github.com/mupt-ai/dari/releases). A config file is optional: without `DARI_GATEWAY_CONFIG` or a `dari-gateway.yaml` in the working directory, the gateway serves a default router of current Anthropic and OpenAI models, each once its provider has a subscription or API key. To choose models, write a `dari-gateway.yaml` (start from [`dari-gateway.example.yaml`](dari-gateway.example.yaml)). Then:
@@ -56,8 +59,6 @@ docker run -p 8080:8080 \
56
59
  ghcr.io/mupt-ai/dari-gateway
57
60
  ```
58
61
 
59
- From a clone of [mupt-ai/dari](https://github.com/mupt-ai/dari), `bun install && (cd packages/router && bun run build) && (cd packages/gateway && bun run start)` or `docker build -f packages/gateway/Dockerfile -t dari-gateway .` run the same thing.
60
-
61
62
  | Variable | Meaning |
62
63
  | --- | --- |
63
64
  | `DARI_GATEWAY_KEYS` | Required. Comma-separated bearer keys clients authenticate with. |
@@ -104,7 +105,7 @@ dari credentials subscription connect claude-code # or codex or muse-code; rep
104
105
  dari claude
105
106
  ```
106
107
 
107
- In gateway mode the CLI makes no calls to Dari's hosted API. `dari credentials subscription list`, `rename`, `mark-available`, and `disconnect` manage the gateway's subscriptions.
108
+ In gateway mode the CLI makes no calls to Dari's hosted API, and `dari activity` is unavailable.
108
109
 
109
110
  ## Embed
110
111
 
@@ -1,7 +1,7 @@
1
1
  import type { Provider, ReasoningEffort, RoutingStrategy } from "@mupt-ai/dari-router/policy-engine";
2
2
  import type { HarnessConversationIdentity } from "../runtime/harness_identity/index.js";
3
3
  import type { InteractionRequest, SourceProtocol } from "../interaction/types.js";
4
- import type { SubscriptionUsageLimit } from "../providers/subscription_limits.js";
4
+ import type { SubscriptionUsage, SubscriptionUsageLimit } from "../providers/subscription_limits.js";
5
5
  import type { ClientHarness, ProviderCredential, ProviderKeySource, ResolvedRouter } from "../types.js";
6
6
  /**
7
7
  * Everything the gateway runtime needs from the deployment around it: router
@@ -42,6 +42,19 @@ export type GatewayPlatform = {
42
42
  * another connected subscription for the same provider can serve a retry.
43
43
  */
44
44
  markSubscriptionUnavailable(hold: SubscriptionHold): Promise<boolean>;
45
+ /**
46
+ * Optional. Record how much of a personal subscription's quota a successful
47
+ * response reports used, so the platform can move new conversations to
48
+ * plans with headroom before one runs out.
49
+ */
50
+ recordSubscriptionUsage?(report: SubscriptionUsageReport): Promise<void>;
51
+ /**
52
+ * Optional. After `markSubscriptionUnavailable` reports another plan can
53
+ * serve, the plan that serves this conversation next, so the gateway
54
+ * retries the request on it at once instead of failing it. Undefined when
55
+ * none can.
56
+ */
57
+ nextSubscription?(request: NextSubscriptionRequest): Promise<NextSubscription | undefined>;
45
58
  /**
46
59
  * Account one call served on a platform-managed provider key. Only reached
47
60
  * when `resolveRouter` reports a "managed" key source.
@@ -59,6 +72,7 @@ export type ResolveRouterRequest = {
59
72
  conversationId?: string;
60
73
  includePublicEvalCatalog?: boolean;
61
74
  clientHarness?: ClientHarness;
75
+ provisional?: boolean;
62
76
  };
63
77
  export type ProviderCredentialRequest = {
64
78
  provider: Provider;
@@ -101,6 +115,20 @@ export type SubscriptionHold = {
101
115
  credentialId: string | undefined;
102
116
  limit: SubscriptionUsageLimit;
103
117
  };
118
+ export type NextSubscriptionRequest = {
119
+ userId: string;
120
+ provider: Provider;
121
+ conversationId: string;
122
+ };
123
+ export type NextSubscription = {
124
+ credentialId: string;
125
+ apiKey: string;
126
+ };
127
+ export type SubscriptionUsageReport = {
128
+ userId: string;
129
+ credentialId: string;
130
+ usage: SubscriptionUsage;
131
+ };
104
132
  export type RequestRecord = {
105
133
  row: Record<string, unknown>;
106
134
  summary: RequestSummary;
@@ -169,7 +197,7 @@ export type RequestErrorContext = {
169
197
  sourceProtocol: SourceProtocol | "openai_models" | "anthropic_models";
170
198
  status: number;
171
199
  };
172
- export type OperationalErrorCode = "background_drain_timeout" | "billing_usage_report_failed" | "routing_report_assembly_failed" | "routing_report_barrier_failed" | "server_force_stop_failed" | "session_pin_write_failed" | "stream_report_finalization_failed" | "subscription_unavailable_ingest_failed";
200
+ export type OperationalErrorCode = "background_drain_timeout" | "billing_usage_report_failed" | "routing_report_assembly_failed" | "routing_report_barrier_failed" | "server_force_stop_failed" | "session_pin_write_failed" | "stream_report_finalization_failed" | "subscription_unavailable_ingest_failed" | "subscription_usage_record_failed" | "next_subscription_lookup_failed";
173
201
  export type OperationalErrorContext = {
174
202
  code: OperationalErrorCode;
175
203
  requestId?: string;
@@ -12,7 +12,7 @@ import { runProviderAttemptPlan, } from "./provider_attempt_runner.js";
12
12
  import { estimatedCancelUsage, NO_DELIVERED_OUTPUT, observeDeliveredOutput, } from "./cancel_estimate.js";
13
13
  import { providerResponseCaptureFromError } from "./response_capture.js";
14
14
  import { createStreamFinalizer } from "./stream_finalization.js";
15
- import { detectSubscriptionUsageLimit, failureWithSubscriptionUsageLimit, retryAfterSeconds, subscriptionUsageLimitFromFailure, subscriptionSwitchedMessage, subscriptionUsageLimitMessage, } from "./subscription_limits.js";
15
+ import { detectSubscriptionUsageLimit, subscriptionUsageFromHeaders, failureWithSubscriptionUsageLimit, retryAfterSeconds, subscriptionUsageLimitFromFailure, subscriptionSwitchedMessage, subscriptionUsageLimitMessage, } from "./subscription_limits.js";
16
16
  export async function executeNonStreaming(args) {
17
17
  const result = await completeNonStreaming(args);
18
18
  if (result.reportBarrierError !== undefined) {
@@ -132,6 +132,7 @@ async function completeWithRetries(args) {
132
132
  clientSignal: args.clientSignal,
133
133
  }),
134
134
  recordFailedAttempt: ({ choice, attempt, result }) => recordSettledFailure(args.reporter, choice, attempt, result),
135
+ onSubscription: onNextSubscription,
135
136
  });
136
137
  }
137
138
  async function runCompletionAttempt(args) {
@@ -149,6 +150,7 @@ async function runCompletionAttempt(args) {
149
150
  if (isProviderFailureMessage(completion.message)) {
150
151
  return providerFailedAttempt(completion.message, completion.providerLatencyMs, args.choice.execution, started.responseCapture);
151
152
  }
153
+ noteSubscriptionUsage(args.choice.execution, started.responseCapture);
152
154
  if (args.choice.execution.usageContext && hasUsage(completion.message)) {
153
155
  await reportRoutingUsage({
154
156
  ...args.choice.execution.usageContext,
@@ -264,6 +266,7 @@ export async function prepareStreamingExecution(args) {
264
266
  clientSignal: args.clientSignal,
265
267
  }),
266
268
  recordFailedAttempt: ({ choice, attempt, result }) => recordSettledFailure(args.reporter, choice, attempt, result),
269
+ onSubscription: onNextSubscription,
267
270
  });
268
271
  args.reporter.attachServingDecision(result.choice.decision);
269
272
  if (result.kind === "customer_canceled") {
@@ -311,6 +314,7 @@ async function runStreamSetupAttempt(args) {
311
314
  started.customerAbort.dispose();
312
315
  return providerFailedAttempt(scrubProviderMessage(primed.failure, args.choice.execution.auth), Date.now() - startedAt, args.choice.execution, started.responseCapture);
313
316
  }
317
+ noteSubscriptionUsage(args.choice.execution, started.responseCapture);
314
318
  return {
315
319
  kind: "succeeded",
316
320
  value: {
@@ -428,11 +432,17 @@ async function providerFailedAttempt(message, latencyMs, execution, responseCapt
428
432
  credentialId: execution.subscriptionCredentialId,
429
433
  limit,
430
434
  });
435
+ // Nothing reached the client yet, so the same request is retried on the
436
+ // next plan at once when the platform names it.
437
+ const nextSubscription = switched
438
+ ? await nextSubscriptionFor(execution)
439
+ : undefined;
431
440
  return {
432
441
  kind: "provider_failed",
433
442
  message: failureWithSubscriptionUsageLimit(message, { ...limit, switched }),
434
443
  latencyMs,
435
444
  retryable: false,
445
+ ...(nextSubscription === undefined ? {} : { nextSubscription }),
436
446
  };
437
447
  }
438
448
  // The provider call was in flight, so the prompt was paid for. A completion
@@ -474,6 +484,61 @@ function isPromptPolicyRejection(message) {
474
484
  const text = providerFailureMessage(message).toLowerCase();
475
485
  return text.includes("invalid prompt") && text.includes("usage policy");
476
486
  }
487
+ // The plan that serves this conversation after its plan was held, or
488
+ // undefined when the platform names none. A failure leaves the request to
489
+ // fail as before.
490
+ async function nextSubscriptionFor(execution) {
491
+ const platform = gatewayPlatform();
492
+ if (platform.nextSubscription === undefined || execution.subscriptionUserId === undefined)
493
+ return undefined;
494
+ try {
495
+ return await platform.nextSubscription({
496
+ userId: execution.subscriptionUserId,
497
+ provider: execution.provider,
498
+ conversationId: execution.conversationId,
499
+ });
500
+ }
501
+ catch (error) {
502
+ console.error("next subscription lookup failed", error);
503
+ captureOperationalError(error, { code: "next_subscription_lookup_failed" });
504
+ return undefined;
505
+ }
506
+ }
507
+ // The same choice served by another of the user's plans.
508
+ function onNextSubscription(choice, next) {
509
+ return {
510
+ ...choice,
511
+ execution: {
512
+ ...choice.execution,
513
+ apiKey: next.apiKey,
514
+ auth: { type: "bearer", apiKey: next.apiKey },
515
+ subscriptionCredentialId: next.credentialId,
516
+ },
517
+ };
518
+ }
519
+ // A served subscription request reports the plan's remaining quota; record
520
+ // it without waiting, and never fail the request over it.
521
+ function noteSubscriptionUsage(execution, responseCapture) {
522
+ const platform = gatewayPlatform();
523
+ const headers = responseCapture?.succeeded;
524
+ if (platform.recordSubscriptionUsage === undefined ||
525
+ headers === undefined ||
526
+ execution.subscriptionUserId === undefined ||
527
+ execution.subscriptionCredentialId === undefined) {
528
+ return;
529
+ }
530
+ const usage = subscriptionUsageFromHeaders(execution.provider, execution.providerKeySource, headers);
531
+ if (usage === null)
532
+ return;
533
+ platform.recordSubscriptionUsage({
534
+ userId: execution.subscriptionUserId,
535
+ credentialId: execution.subscriptionCredentialId,
536
+ usage,
537
+ }).catch((error) => {
538
+ console.error("subscription usage record failed", error);
539
+ captureOperationalError(error, { code: "subscription_usage_record_failed" });
540
+ });
541
+ }
477
542
  // Never fails the request: the provider already refused. Resolves whether
478
543
  // another subscription now serves.
479
544
  async function holdSubscription(hold) {
@@ -1,8 +1,10 @@
1
+ import type { NextSubscription } from "../platform/platform.js";
1
2
  export type ProviderAttemptFailure = {
2
3
  kind: "provider_failed";
3
4
  message: Record<string, unknown>;
4
5
  latencyMs: number;
5
6
  retryable: boolean;
7
+ nextSubscription?: NextSubscription;
6
8
  } | {
7
9
  kind: "customer_canceled";
8
10
  message: Record<string, unknown>;
@@ -44,6 +46,7 @@ type RunProviderAttemptPlanArgs<TChoice, TValue, TInitial> = {
44
46
  attempt: number;
45
47
  result: ProviderAttemptFailure;
46
48
  }) => void;
49
+ onSubscription?: (choice: TChoice, next: NextSubscription) => TChoice;
47
50
  };
48
51
  /**
49
52
  * Owns the order-sensitive provider plan shared by completion and stream setup:
@@ -26,11 +26,15 @@ export async function runProviderAttemptPlan(args) {
26
26
  }
27
27
  return primary;
28
28
  }
29
- async function runChoice(args, choice, initial) {
29
+ async function runChoice(args, firstChoice, initial) {
30
+ let choice = firstChoice;
30
31
  let latencyMs = 0;
31
32
  let lastFailure = null;
32
33
  let lastAttempt = 0;
33
- for (let attempt = 1; attempt <= args.retries + 1; attempt += 1) {
34
+ // A switch to another plan retries without spending the retry budget; each
35
+ // switch holds a plan, so switches are bounded by the plans connected.
36
+ let maxAttempts = args.retries + 1;
37
+ for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {
34
38
  lastAttempt = attempt;
35
39
  if (attempt !== 1 || initial === undefined) {
36
40
  if (args.isCustomerCanceled(choice)) {
@@ -57,6 +61,11 @@ async function runChoice(args, choice, initial) {
57
61
  failure: result.message,
58
62
  };
59
63
  }
64
+ if (result.kind === "provider_failed" && result.nextSubscription !== undefined && args.onSubscription) {
65
+ choice = args.onSubscription(choice, result.nextSubscription);
66
+ maxAttempts += 1;
67
+ continue;
68
+ }
60
69
  if (!result.retryable)
61
70
  break;
62
71
  }
@@ -7,9 +7,11 @@ export type ProviderFetch = (input: string | URL | Request, init?: RequestInit)
7
7
  export type ProviderResponseCapture = {
8
8
  fetch: ProviderFetch;
9
9
  last: CapturedProviderResponse | undefined;
10
+ succeeded: Headers | undefined;
10
11
  };
11
12
  /**
12
- * A fetch wrapper that remembers the last failed provider response. pi-ai
13
+ * A fetch wrapper that remembers the last failed provider response, and the
14
+ * headers of the last successful one. pi-ai
13
15
  * flattens provider errors into one message string before they reach the
14
16
  * runtime, so this is the only place the status, rate-limit headers, and
15
17
  * structured error body of a rejected call can still be read.
@@ -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;
@@ -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() {
@@ -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
  });
@@ -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
  */