@mupt-ai/dari-gateway 1.0.311 → 1.0.312

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.
@@ -169,6 +169,13 @@ function sanitizeProviderContent(value) {
169
169
  if (part.type === "providerItem" && isRecord(part.item)) {
170
170
  return part.item;
171
171
  }
172
+ // A thinking signature is an opaque continuation token (encrypted
173
+ // reasoning, an Anthropic signature), not prompt text: its base64 would
174
+ // count far more tokens than the provider bills for it.
175
+ if (part.type === "thinking" && "thinkingSignature" in part) {
176
+ const { thinkingSignature: _signature, ...visible } = part;
177
+ return visible;
178
+ }
172
179
  if (part.type === "image"
173
180
  && typeof part.mimeType === "string"
174
181
  && typeof part.data === "string") {
@@ -13,7 +13,7 @@ import { estimatedCancelUsage, NO_DELIVERED_OUTPUT, observeDeliveredOutput, } fr
13
13
  import { providerResponseCaptureFromError } from "./response_capture.js";
14
14
  import { createStreamFinalizer } from "./stream_finalization.js";
15
15
  import { readCodexModelLimitReset, readCodexUsage } from "./codex_usage.js";
16
- import { detectSubscriptionUsageLimit, codexUsageLimitError, subscriptionOAuthProviderFor, subscriptionUsageFromHeaders, failureWithSubscriptionUsageLimit, retryAfterSeconds, subscriptionUsageLimitFromFailure, subscriptionSwitchedMessage, subscriptionUsageLimitMessage, } from "./subscription_limits.js";
16
+ import { detectSubscriptionUsageLimit, codexUsageLimitError, subscriptionOAuthProviderFor, subscriptionUsageFromHeaders, museSubscriptionUsage, failureWithSubscriptionUsageLimit, retryAfterSeconds, subscriptionUsageLimitFromFailure, subscriptionSwitchedMessage, subscriptionUsageLimitMessage, } from "./subscription_limits.js";
17
17
  export async function executeNonStreaming(args) {
18
18
  const result = await completeNonStreaming(args);
19
19
  if (result.reportBarrierError !== undefined) {
@@ -594,16 +594,20 @@ function noteSubscriptionUsage(execution, responseCapture) {
594
594
  const fromHeaders = headers === undefined
595
595
  ? null
596
596
  : subscriptionUsageFromHeaders(execution.provider, execution.providerKeySource, headers);
597
+ const oauthProvider = subscriptionOAuthProviderFor(execution.provider, execution.providerKeySource);
597
598
  // Codex's WebSocket transport carries no headers; its usage report does.
599
+ // Muse Code's usage is the last event of its stream.
598
600
  const usage = fromHeaders !== null
599
601
  ? Promise.resolve(fromHeaders)
600
- : subscriptionOAuthProviderFor(execution.provider, execution.providerKeySource) === "openai_codex"
602
+ : oauthProvider === "openai_codex"
601
603
  ? readCodexUsage({
602
604
  credentialId,
603
605
  accessToken: execution.apiKey,
604
606
  baseUrl: execution.endpoint?.baseUrl ?? execution.config?.base_url ?? undefined,
605
607
  })
606
- : Promise.resolve(null);
608
+ : oauthProvider === "meta_muse" && responseCapture !== undefined
609
+ ? responseCapture.streamedSubscriptionUsage.then((snapshot) => museSubscriptionUsage(snapshot, new Date()))
610
+ : Promise.resolve(null);
607
611
  usage
608
612
  .then((reported) => reported === null ? undefined : record({ userId, credentialId, usage: reported }))
609
613
  .catch((error) => {
@@ -8,6 +8,7 @@ import { scrubSecretValues } from "../telemetry/scrub.js";
8
8
  import { usageContextFor, } from "../telemetry/usage.js";
9
9
  import { awsRoleCredentials } from "./aws_assume_role.js";
10
10
  import { attachProviderResponseCapture, createProviderResponseCapture, } from "./response_capture.js";
11
+ import { subscriptionOAuthProviderFor } from "./subscription_limits.js";
11
12
  import { completeInteractionModel, streamInteractionModel, } from "./pi.js";
12
13
  import { promptTokenEstimateFor } from "./cancel_estimate.js";
13
14
  import { withSystemPromptSuffix } from "../interaction/system_prompt.js";
@@ -99,9 +100,12 @@ export function startProviderCompletion(args) {
99
100
  function responseCaptureFor(execution) {
100
101
  // A subscription's failures carry its usage limit; a customer key's say
101
102
  // whether the provider refused the key itself.
103
+ // Muse Code reports its plan's usage as the stream's last event.
102
104
  return execution.providerKeySource === "managed"
103
105
  ? undefined
104
- : createProviderResponseCapture();
106
+ : createProviderResponseCapture({
107
+ watchSubscriptionUsage: subscriptionOAuthProviderFor(execution.provider, execution.providerKeySource) === "meta_muse",
108
+ });
105
109
  }
106
110
  export async function startProviderStream(args) {
107
111
  const providerStartedMs = Date.now();
@@ -8,6 +8,7 @@ export type ProviderResponseCapture = {
8
8
  fetch: ProviderFetch;
9
9
  last: CapturedProviderResponse | undefined;
10
10
  succeeded: Headers | undefined;
11
+ streamedSubscriptionUsage: Promise<unknown>;
11
12
  };
12
13
  /**
13
14
  * A fetch wrapper that remembers the last failed provider response, and the
@@ -16,7 +17,9 @@ export type ProviderResponseCapture = {
16
17
  * runtime, so this is the only place the status, rate-limit headers, and
17
18
  * structured error body of a rejected call can still be read.
18
19
  */
19
- export declare function createProviderResponseCapture(): ProviderResponseCapture;
20
+ export declare function createProviderResponseCapture(options?: {
21
+ watchSubscriptionUsage?: boolean;
22
+ }): ProviderResponseCapture;
20
23
  /**
21
24
  * A provider call that throws before returning a stream loses its capture with
22
25
  * the started state, so the error carries it to the attempt runner instead.
@@ -1,3 +1,5 @@
1
+ const SUBSCRIPTION_USAGE_EVENT = "response.subscription_usage";
2
+ const MAX_SCANNED_LINE = 64 * 1024;
1
3
  const CAPTURED_BODY_MAX_BYTES = 64 * 1024;
2
4
  /**
3
5
  * A fetch wrapper that remembers the last failed provider response, and the
@@ -6,15 +8,23 @@ const CAPTURED_BODY_MAX_BYTES = 64 * 1024;
6
8
  * runtime, so this is the only place the status, rate-limit headers, and
7
9
  * structured error body of a rejected call can still be read.
8
10
  */
9
- export function createProviderResponseCapture() {
11
+ export function createProviderResponseCapture(options = {}) {
10
12
  const capture = {
11
13
  last: undefined,
12
14
  succeeded: undefined,
15
+ streamedSubscriptionUsage: Promise.resolve(null),
13
16
  fetch: async (input, init) => {
14
17
  const response = await globalThis.fetch(input, init);
15
18
  if (response.ok) {
16
19
  capture.succeeded = response.headers;
17
- return response;
20
+ if (options.watchSubscriptionUsage !== true
21
+ || response.body === null
22
+ || !response.headers.get("content-type")?.includes("text/event-stream")) {
23
+ return response;
24
+ }
25
+ const watched = watchSubscriptionUsage(response.body);
26
+ capture.streamedSubscriptionUsage = watched.usage;
27
+ return new Response(watched.body, response);
18
28
  }
19
29
  const bodyText = await readBodyPrefix(response.clone());
20
30
  capture.last = { status: response.status, headers: response.headers, bodyText };
@@ -23,6 +33,75 @@ export function createProviderResponseCapture() {
23
33
  };
24
34
  return capture;
25
35
  }
36
+ /**
37
+ * Passes a server-sent event stream through unchanged while watching for its
38
+ * subscription usage event. The usage resolves when the stream ends or is
39
+ * cancelled.
40
+ */
41
+ function watchSubscriptionUsage(source) {
42
+ let found = null;
43
+ let settle = () => undefined;
44
+ const usage = new Promise((resolve) => { settle = resolve; });
45
+ const decoder = new TextDecoder();
46
+ const reader = source.getReader();
47
+ // The usage event is small; a longer line (an image, a large output item)
48
+ // is skipped rather than buffered.
49
+ let line = "";
50
+ let skipping = false;
51
+ const take = (complete) => {
52
+ if (!complete.startsWith("data:") || !complete.includes(SUBSCRIPTION_USAGE_EVENT))
53
+ return;
54
+ try {
55
+ const event = JSON.parse(complete.slice(5));
56
+ if (event.type === SUBSCRIPTION_USAGE_EVENT)
57
+ found = event.subscription ?? null;
58
+ }
59
+ catch {
60
+ // Not this event; the stream itself is the client's to parse.
61
+ }
62
+ };
63
+ const scan = (text) => {
64
+ const pieces = text.split("\n");
65
+ for (let index = 0; index < pieces.length; index += 1) {
66
+ if (!skipping)
67
+ line += pieces[index];
68
+ if (line.length > MAX_SCANNED_LINE) {
69
+ line = "";
70
+ skipping = true;
71
+ }
72
+ if (index < pieces.length - 1) {
73
+ if (!skipping)
74
+ take(line.trimEnd());
75
+ line = "";
76
+ skipping = false;
77
+ }
78
+ }
79
+ };
80
+ const body = new ReadableStream({
81
+ async pull(controller) {
82
+ try {
83
+ const { done, value } = await reader.read();
84
+ if (done) {
85
+ scan(decoder.decode() + "\n");
86
+ settle(found);
87
+ controller.close();
88
+ return;
89
+ }
90
+ scan(decoder.decode(value, { stream: true }));
91
+ controller.enqueue(value);
92
+ }
93
+ catch (error) {
94
+ settle(found);
95
+ controller.error(error);
96
+ }
97
+ },
98
+ async cancel(reason) {
99
+ settle(found);
100
+ await reader.cancel(reason);
101
+ },
102
+ });
103
+ return { body, usage };
104
+ }
26
105
  async function readBodyPrefix(response) {
27
106
  try {
28
107
  const text = await response.text();
@@ -37,6 +37,21 @@ export declare function subscriptionUsageFromWindows(raw: Array<{
37
37
  * reports none: the most used of the plan's windows.
38
38
  */
39
39
  export declare function subscriptionUsageFromHeaders(provider: string, keySource: ProviderKeySource, headers: Headers, now?: Date): SubscriptionUsage | null;
40
+ /**
41
+ * The plan usage a Muse Code stream reports as its last event,
42
+ * `response.subscription_usage`: `{window: {used_percent, resets_at,
43
+ * window_duration_mins}, weekly: {used_percent, resets_at}, tier}`, the
44
+ * current five hour block and the rolling week, resets in unix seconds and
45
+ * percent that may exceed 100.
46
+ */
47
+ export declare function museSubscriptionUsage(snapshot: unknown, now: Date): SubscriptionUsage | null;
48
+ /**
49
+ * The usage OpenCode Go reports at `GET /zen/go/v1/usage`, which OpenCode's
50
+ * own `/usage` reads: `{usage: {rolling|weekly|monthly: {status: "ok" |
51
+ * "rate-limited", percent, resetsAt}}}`, percent out of 100. A window Go
52
+ * refuses on is at its limit whatever it rounds to.
53
+ */
54
+ export declare function openCodeGoUsageFromReport(report: unknown, now: Date): SubscriptionUsage | null;
40
55
  export declare const DEFAULT_USAGE_LIMIT_WINDOW_MS: number;
41
56
  export declare function subscriptionOAuthProviderFor(provider: string, keySource: ProviderKeySource): SubscriptionOAuthProvider | null;
42
57
  /**
@@ -46,6 +46,51 @@ export function subscriptionUsageFromHeaders(provider, keySource, headers, now =
46
46
  : [];
47
47
  return subscriptionUsageFromWindows(windows, now);
48
48
  }
49
+ /**
50
+ * The plan usage a Muse Code stream reports as its last event,
51
+ * `response.subscription_usage`: `{window: {used_percent, resets_at,
52
+ * window_duration_mins}, weekly: {used_percent, resets_at}, tier}`, the
53
+ * current five hour block and the rolling week, resets in unix seconds and
54
+ * percent that may exceed 100.
55
+ */
56
+ export function museSubscriptionUsage(snapshot, now) {
57
+ if (!isRecord(snapshot))
58
+ return null;
59
+ const number = (value) => typeof value === "number" && Number.isFinite(value) ? value : NaN;
60
+ return subscriptionUsageFromWindows([["window", FIVE_HOURS], ["weekly", ONE_WEEK]].map(([name, minutes]) => {
61
+ const raw = snapshot[name];
62
+ const window = isRecord(raw) ? raw : {};
63
+ const resetsAt = number(window.resets_at);
64
+ return {
65
+ minutes: number(window.window_duration_mins) > 0 ? Math.round(number(window.window_duration_mins)) : minutes,
66
+ used: number(window.used_percent) / 100,
67
+ resetsAt: Number.isNaN(resetsAt) ? null : new Date(resetsAt * 1000),
68
+ };
69
+ }), now);
70
+ }
71
+ // OpenCode Go's windows by their usage report names; the monthly one follows
72
+ // the billing cycle.
73
+ const OPENCODE_GO_USAGE_WINDOWS = [["rolling", FIVE_HOURS], ["weekly", ONE_WEEK], ["monthly", 30 * 24 * 60]];
74
+ /**
75
+ * The usage OpenCode Go reports at `GET /zen/go/v1/usage`, which OpenCode's
76
+ * own `/usage` reads: `{usage: {rolling|weekly|monthly: {status: "ok" |
77
+ * "rate-limited", percent, resetsAt}}}`, percent out of 100. A window Go
78
+ * refuses on is at its limit whatever it rounds to.
79
+ */
80
+ export function openCodeGoUsageFromReport(report, now) {
81
+ const usage = isRecord(report) && isRecord(report.usage) ? report.usage : {};
82
+ return subscriptionUsageFromWindows(OPENCODE_GO_USAGE_WINDOWS.map(([name, minutes]) => {
83
+ const raw = usage[name];
84
+ const meter = isRecord(raw) ? raw : {};
85
+ const percent = typeof meter.percent === "number" ? meter.percent / 100 : NaN;
86
+ const resetsAt = typeof meter.resetsAt === "string" ? new Date(meter.resetsAt) : null;
87
+ return {
88
+ minutes,
89
+ used: meter.status === "rate-limited" && Number.isFinite(percent) ? 1 : percent,
90
+ resetsAt: resetsAt === null || Number.isNaN(resetsAt.getTime()) ? null : resetsAt,
91
+ };
92
+ }), now);
93
+ }
49
94
  // Neither provider guarantees a reset time on every usage-limit response.
50
95
  // Without one, hold the subscription out for an hour rather than hammering an
51
96
  // exhausted plan on every request.
@@ -8,3 +8,8 @@ export declare function freshAccessToken(store: SubscriptionStore, credential: S
8
8
  fetch: OAuthFetch;
9
9
  now?: Date;
10
10
  }): Promise<string>;
11
+ /** A usable access token without recording a use. */
12
+ export declare function refreshedAccessToken(store: SubscriptionStore, credential: SubscriptionCredential, options: {
13
+ fetch: OAuthFetch;
14
+ now?: Date;
15
+ }): Promise<string>;
@@ -8,8 +8,12 @@ const inFlight = new Map();
8
8
  * when it expires within five minutes. Records the credential as used.
9
9
  */
10
10
  export async function freshAccessToken(store, credential, options) {
11
+ store.touch(credential.id, options.now ?? new Date());
12
+ return await refreshedAccessToken(store, credential, options);
13
+ }
14
+ /** A usable access token without recording a use. */
15
+ export async function refreshedAccessToken(store, credential, options) {
11
16
  const now = options.now ?? new Date();
12
- store.touch(credential.id, now);
13
17
  if (!expiresSoon(credential, now))
14
18
  return credential.accessToken;
15
19
  const pending = inFlight.get(credential.id);
@@ -7,6 +7,7 @@
7
7
  import { SUBSCRIPTION_PROVIDERS, SubscriptionOAuthInputError, SubscriptionOAuthProviderError, completeOAuth, startOAuth, } from "./oauth.js";
8
8
  import { canonicalModelName } from "../../models/canonical.js";
9
9
  import { activeModelHolds, currentUsage, isHeld, } from "./store.js";
10
+ import { refreshStaleUsage } from "./usage.js";
10
11
  const BASE = "/v1/organizations/current/credentials";
11
12
  // Subscription names are env-var-style, which keeps other credential routes
12
13
  // such as `provider-credentials/...` out of these matches.
@@ -26,8 +27,13 @@ export async function handleSubscriptionRequest(request, deps) {
26
27
  const path = url.pathname.slice(BASE.length);
27
28
  const now = deps.now?.() ?? new Date();
28
29
  try {
29
- if (path === "" && request.method === "GET")
30
+ if (path === "" && request.method === "GET") {
31
+ // OpenCode Go reports usage only when asked.
32
+ if (url.searchParams.get("refresh_usage") === "true") {
33
+ await refreshStaleUsage(deps.store, { fetch: deps.fetch, now });
34
+ }
30
35
  return json(200, listBody(deps.store, now));
36
+ }
31
37
  if (path === "/oauth/sessions" && request.method === "POST") {
32
38
  return json(201, await startSession(deps, await readBody(request), now));
33
39
  }
@@ -9,6 +9,9 @@
9
9
  * database file; protect that file like a secret.
10
10
  * - `access.ts`: `freshAccessToken` refreshes a token expiring within five
11
11
  * minutes before handing it out, one refresh per credential at a time.
12
+ * - `usage.ts`: `refreshStaleUsage` reads OpenCode Go plan usage from its
13
+ * usage endpoint, which its responses never report, when the accounts view
14
+ * asks.
12
15
  * - `http.ts`: `handleSubscriptionRequest` serves the credential endpoints the
13
16
  * Dari CLI uses to connect, list, rename, release, and disconnect
14
17
  * subscriptions. The caller authenticates the request first.
@@ -9,6 +9,9 @@
9
9
  * database file; protect that file like a secret.
10
10
  * - `access.ts`: `freshAccessToken` refreshes a token expiring within five
11
11
  * minutes before handing it out, one refresh per credential at a time.
12
+ * - `usage.ts`: `refreshStaleUsage` reads OpenCode Go plan usage from its
13
+ * usage endpoint, which its responses never report, when the accounts view
14
+ * asks.
12
15
  * - `http.ts`: `handleSubscriptionRequest` serves the credential endpoints the
13
16
  * Dari CLI uses to connect, list, rename, release, and disconnect
14
17
  * subscriptions. The caller authenticates the request first.
@@ -0,0 +1,7 @@
1
+ import type { OAuthFetch } from "./oauth.js";
2
+ import type { SubscriptionStore } from "./store.js";
3
+ /** Read every stale OpenCode Go plan again; a failed read keeps the last one. */
4
+ export declare function refreshStaleUsage(store: SubscriptionStore, options: {
5
+ fetch: OAuthFetch;
6
+ now?: Date;
7
+ }): Promise<void>;
@@ -0,0 +1,52 @@
1
+ import { openCodeGoUsageFromReport } from "../../providers/subscription_limits.js";
2
+ import { refreshedAccessToken } from "./access.js";
3
+ /**
4
+ * Claude Code, ChatGPT, and Muse Code report usage on the responses the
5
+ * gateway serves. OpenCode Go does not: it reports it from a usage endpoint
6
+ * that takes the plan's workspace, which the accounts view reads again when
7
+ * the last reading is stale.
8
+ */
9
+ // A read, failed or not, is not repeated within this interval.
10
+ const READ_INTERVAL_MS = 60_000;
11
+ const READ_TIMEOUT_MS = 8_000;
12
+ const OPENCODE_GO_USAGE_URL = "https://opencode.ai/zen/go/v1/usage";
13
+ // Reads that recorded nothing (failed, or no running window), so such a plan is
14
+ // not re-read on every listing. A recorded reading stamps the credential
15
+ // itself, which a reconnect clears.
16
+ const unrecordedAt = new Map();
17
+ /** Read every stale OpenCode Go plan again; a failed read keeps the last one. */
18
+ export async function refreshStaleUsage(store, options) {
19
+ const now = options.now ?? new Date();
20
+ const due = (at) => now.getTime() - (at ?? 0) >= READ_INTERVAL_MS;
21
+ const stale = store.list("opencode_go").filter((credential) => due(credential.usage?.observedAt.getTime()) && due(unrecordedAt.get(credential.id)));
22
+ await Promise.all(stale.map(async (credential) => {
23
+ unrecordedAt.set(credential.id, now.getTime());
24
+ try {
25
+ await readUsage(store, credential, { ...options, now });
26
+ }
27
+ catch (error) {
28
+ console.error(`subscription usage read failed for ${credential.name}:`, error instanceof Error ? error.message : error);
29
+ }
30
+ }));
31
+ }
32
+ async function readUsage(store, credential, options) {
33
+ const token = await refreshedAccessToken(store, credential, options);
34
+ const response = await options.fetch(OPENCODE_GO_USAGE_URL, {
35
+ method: "GET",
36
+ headers: {
37
+ Accept: "application/json",
38
+ Authorization: `Bearer ${token}`,
39
+ "User-Agent": "dari-gateway",
40
+ ...(credential.accountId === null ? {} : { "x-opencode-org-id": credential.accountId }),
41
+ },
42
+ signal: AbortSignal.timeout(READ_TIMEOUT_MS),
43
+ });
44
+ // Go answers 403 for a workspace without a Go plan.
45
+ if (!response.ok)
46
+ throw new Error(`OpenCode Go usage read failed with status ${response.status}.`);
47
+ const usage = openCodeGoUsageFromReport(await response.json(), options.now);
48
+ if (usage === null)
49
+ return;
50
+ unrecordedAt.delete(credential.id);
51
+ store.recordUsage(credential.id, usage, options.now);
52
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mupt-ai/dari-gateway",
3
- "version": "1.0.311",
3
+ "version": "1.0.312",
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.311",
54
+ "@mupt-ai/dari-router": "1.0.312",
55
55
  "@mupt-ai/pi-ai": "1.5.2-mupt.1"
56
56
  },
57
57
  "devDependencies": {
@@ -208,6 +208,13 @@ function sanitizeProviderContent(value: unknown): unknown {
208
208
  if (part.type === "providerItem" && isRecord(part.item)) {
209
209
  return part.item;
210
210
  }
211
+ // A thinking signature is an opaque continuation token (encrypted
212
+ // reasoning, an Anthropic signature), not prompt text: its base64 would
213
+ // count far more tokens than the provider bills for it.
214
+ if (part.type === "thinking" && "thinkingSignature" in part) {
215
+ const { thinkingSignature: _signature, ...visible } = part;
216
+ return visible;
217
+ }
211
218
  if (
212
219
  part.type === "image"
213
220
  && typeof part.mimeType === "string"
@@ -55,6 +55,7 @@ import {
55
55
  codexUsageLimitError,
56
56
  subscriptionOAuthProviderFor,
57
57
  subscriptionUsageFromHeaders,
58
+ museSubscriptionUsage,
58
59
  failureWithSubscriptionUsageLimit,
59
60
  retryAfterSeconds,
60
61
  subscriptionUsageLimitFromFailure,
@@ -914,16 +915,20 @@ function noteSubscriptionUsage(
914
915
  const fromHeaders = headers === undefined
915
916
  ? null
916
917
  : subscriptionUsageFromHeaders(execution.provider, execution.providerKeySource, headers);
918
+ const oauthProvider = subscriptionOAuthProviderFor(execution.provider, execution.providerKeySource);
917
919
  // Codex's WebSocket transport carries no headers; its usage report does.
920
+ // Muse Code's usage is the last event of its stream.
918
921
  const usage = fromHeaders !== null
919
922
  ? Promise.resolve(fromHeaders)
920
- : subscriptionOAuthProviderFor(execution.provider, execution.providerKeySource) === "openai_codex"
923
+ : oauthProvider === "openai_codex"
921
924
  ? readCodexUsage({
922
925
  credentialId,
923
926
  accessToken: execution.apiKey,
924
927
  baseUrl: execution.endpoint?.baseUrl ?? execution.config?.base_url ?? undefined,
925
928
  })
926
- : Promise.resolve(null);
929
+ : oauthProvider === "meta_muse" && responseCapture !== undefined
930
+ ? responseCapture.streamedSubscriptionUsage.then((snapshot) => museSubscriptionUsage(snapshot, new Date()))
931
+ : Promise.resolve(null);
927
932
  usage
928
933
  .then((reported) => reported === null ? undefined : record({ userId, credentialId, usage: reported }))
929
934
  .catch((error: unknown) => {
@@ -42,6 +42,7 @@ import {
42
42
  type ProviderFetch,
43
43
  type ProviderResponseCapture,
44
44
  } from "./response_capture.js";
45
+ import { subscriptionOAuthProviderFor } from "./subscription_limits.js";
45
46
  import {
46
47
  completeInteractionModel,
47
48
  streamInteractionModel,
@@ -213,9 +214,12 @@ export function startProviderCompletion(args: {
213
214
  function responseCaptureFor(execution: ProviderExecution): ProviderResponseCapture | undefined {
214
215
  // A subscription's failures carry its usage limit; a customer key's say
215
216
  // whether the provider refused the key itself.
217
+ // Muse Code reports its plan's usage as the stream's last event.
216
218
  return execution.providerKeySource === "managed"
217
219
  ? undefined
218
- : createProviderResponseCapture();
220
+ : createProviderResponseCapture({
221
+ watchSubscriptionUsage: subscriptionOAuthProviderFor(execution.provider, execution.providerKeySource) === "meta_muse",
222
+ });
219
223
  }
220
224
 
221
225
  export async function startProviderStream(args: {
@@ -12,8 +12,15 @@ export type ProviderResponseCapture = {
12
12
  // Headers of the last successful provider response, which carry a
13
13
  // subscription's remaining usage.
14
14
  succeeded: Headers | undefined;
15
+ // The `subscription` of the last successful stream's
16
+ // `response.subscription_usage` event, which Meta's Muse Code plans send
17
+ // last instead of usage headers; null once a stream ends without one.
18
+ streamedSubscriptionUsage: Promise<unknown>;
15
19
  };
16
20
 
21
+ const SUBSCRIPTION_USAGE_EVENT = "response.subscription_usage";
22
+ const MAX_SCANNED_LINE = 64 * 1024;
23
+
17
24
  const CAPTURED_BODY_MAX_BYTES = 64 * 1024;
18
25
 
19
26
  /**
@@ -23,15 +30,27 @@ const CAPTURED_BODY_MAX_BYTES = 64 * 1024;
23
30
  * runtime, so this is the only place the status, rate-limit headers, and
24
31
  * structured error body of a rejected call can still be read.
25
32
  */
26
- export function createProviderResponseCapture(): ProviderResponseCapture {
33
+ export function createProviderResponseCapture(
34
+ options: { watchSubscriptionUsage?: boolean } = {},
35
+ ): ProviderResponseCapture {
27
36
  const capture: ProviderResponseCapture = {
28
37
  last: undefined,
29
38
  succeeded: undefined,
39
+ streamedSubscriptionUsage: Promise.resolve(null),
30
40
  fetch: async (input, init) => {
31
41
  const response = await globalThis.fetch(input, init);
32
42
  if (response.ok) {
33
43
  capture.succeeded = response.headers;
34
- return response;
44
+ if (
45
+ options.watchSubscriptionUsage !== true
46
+ || response.body === null
47
+ || !response.headers.get("content-type")?.includes("text/event-stream")
48
+ ) {
49
+ return response;
50
+ }
51
+ const watched = watchSubscriptionUsage(response.body);
52
+ capture.streamedSubscriptionUsage = watched.usage;
53
+ return new Response(watched.body, response);
35
54
  }
36
55
  const bodyText = await readBodyPrefix(response.clone());
37
56
  capture.last = { status: response.status, headers: response.headers, bodyText };
@@ -41,6 +60,73 @@ export function createProviderResponseCapture(): ProviderResponseCapture {
41
60
  return capture;
42
61
  }
43
62
 
63
+ /**
64
+ * Passes a server-sent event stream through unchanged while watching for its
65
+ * subscription usage event. The usage resolves when the stream ends or is
66
+ * cancelled.
67
+ */
68
+ function watchSubscriptionUsage(source: ReadableStream<Uint8Array>): {
69
+ body: ReadableStream<Uint8Array>;
70
+ usage: Promise<unknown>;
71
+ } {
72
+ let found: unknown = null;
73
+ let settle: (usage: unknown) => void = () => undefined;
74
+ const usage = new Promise<unknown>((resolve) => { settle = resolve; });
75
+ const decoder = new TextDecoder();
76
+ const reader = source.getReader();
77
+ // The usage event is small; a longer line (an image, a large output item)
78
+ // is skipped rather than buffered.
79
+ let line = "";
80
+ let skipping = false;
81
+ const take = (complete: string) => {
82
+ if (!complete.startsWith("data:") || !complete.includes(SUBSCRIPTION_USAGE_EVENT)) return;
83
+ try {
84
+ const event = JSON.parse(complete.slice(5)) as { type?: unknown; subscription?: unknown };
85
+ if (event.type === SUBSCRIPTION_USAGE_EVENT) found = event.subscription ?? null;
86
+ } catch {
87
+ // Not this event; the stream itself is the client's to parse.
88
+ }
89
+ };
90
+ const scan = (text: string) => {
91
+ const pieces = text.split("\n");
92
+ for (let index = 0; index < pieces.length; index += 1) {
93
+ if (!skipping) line += pieces[index];
94
+ if (line.length > MAX_SCANNED_LINE) {
95
+ line = "";
96
+ skipping = true;
97
+ }
98
+ if (index < pieces.length - 1) {
99
+ if (!skipping) take(line.trimEnd());
100
+ line = "";
101
+ skipping = false;
102
+ }
103
+ }
104
+ };
105
+ const body = new ReadableStream<Uint8Array>({
106
+ async pull(controller) {
107
+ try {
108
+ const { done, value } = await reader.read();
109
+ if (done) {
110
+ scan(decoder.decode() + "\n");
111
+ settle(found);
112
+ controller.close();
113
+ return;
114
+ }
115
+ scan(decoder.decode(value, { stream: true }));
116
+ controller.enqueue(value);
117
+ } catch (error) {
118
+ settle(found);
119
+ controller.error(error);
120
+ }
121
+ },
122
+ async cancel(reason) {
123
+ settle(found);
124
+ await reader.cancel(reason);
125
+ },
126
+ });
127
+ return { body, usage };
128
+ }
129
+
44
130
  async function readBodyPrefix(response: Response): Promise<string> {
45
131
  try {
46
132
  const text = await response.text();
@@ -96,6 +96,59 @@ export function subscriptionUsageFromHeaders(
96
96
  return subscriptionUsageFromWindows(windows, now);
97
97
  }
98
98
 
99
+ /**
100
+ * The plan usage a Muse Code stream reports as its last event,
101
+ * `response.subscription_usage`: `{window: {used_percent, resets_at,
102
+ * window_duration_mins}, weekly: {used_percent, resets_at}, tier}`, the
103
+ * current five hour block and the rolling week, resets in unix seconds and
104
+ * percent that may exceed 100.
105
+ */
106
+ export function museSubscriptionUsage(snapshot: unknown, now: Date): SubscriptionUsage | null {
107
+ if (!isRecord(snapshot)) return null;
108
+ const number = (value: unknown) => typeof value === "number" && Number.isFinite(value) ? value : NaN;
109
+ return subscriptionUsageFromWindows(
110
+ ([["window", FIVE_HOURS], ["weekly", ONE_WEEK]] as const).map(([name, minutes]) => {
111
+ const raw = snapshot[name];
112
+ const window = isRecord(raw) ? raw : {};
113
+ const resetsAt = number(window.resets_at);
114
+ return {
115
+ minutes: number(window.window_duration_mins) > 0 ? Math.round(number(window.window_duration_mins)) : minutes,
116
+ used: number(window.used_percent) / 100,
117
+ resetsAt: Number.isNaN(resetsAt) ? null : new Date(resetsAt * 1000),
118
+ };
119
+ }),
120
+ now,
121
+ );
122
+ }
123
+
124
+ // OpenCode Go's windows by their usage report names; the monthly one follows
125
+ // the billing cycle.
126
+ const OPENCODE_GO_USAGE_WINDOWS = [["rolling", FIVE_HOURS], ["weekly", ONE_WEEK], ["monthly", 30 * 24 * 60]] as const;
127
+
128
+ /**
129
+ * The usage OpenCode Go reports at `GET /zen/go/v1/usage`, which OpenCode's
130
+ * own `/usage` reads: `{usage: {rolling|weekly|monthly: {status: "ok" |
131
+ * "rate-limited", percent, resetsAt}}}`, percent out of 100. A window Go
132
+ * refuses on is at its limit whatever it rounds to.
133
+ */
134
+ export function openCodeGoUsageFromReport(report: unknown, now: Date): SubscriptionUsage | null {
135
+ const usage = isRecord(report) && isRecord(report.usage) ? report.usage : {};
136
+ return subscriptionUsageFromWindows(
137
+ OPENCODE_GO_USAGE_WINDOWS.map(([name, minutes]) => {
138
+ const raw = usage[name];
139
+ const meter = isRecord(raw) ? raw : {};
140
+ const percent = typeof meter.percent === "number" ? meter.percent / 100 : NaN;
141
+ const resetsAt = typeof meter.resetsAt === "string" ? new Date(meter.resetsAt) : null;
142
+ return {
143
+ minutes,
144
+ used: meter.status === "rate-limited" && Number.isFinite(percent) ? 1 : percent,
145
+ resetsAt: resetsAt === null || Number.isNaN(resetsAt.getTime()) ? null : resetsAt,
146
+ };
147
+ }),
148
+ now,
149
+ );
150
+ }
151
+
99
152
  // Neither provider guarantees a reset time on every usage-limit response.
100
153
  // Without one, hold the subscription out for an hour rather than hammering an
101
154
  // exhausted plan on every request.
@@ -15,9 +15,18 @@ export async function freshAccessToken(
15
15
  store: SubscriptionStore,
16
16
  credential: SubscriptionCredential,
17
17
  options: { fetch: OAuthFetch; now?: Date },
18
+ ): Promise<string> {
19
+ store.touch(credential.id, options.now ?? new Date());
20
+ return await refreshedAccessToken(store, credential, options);
21
+ }
22
+
23
+ /** A usable access token without recording a use. */
24
+ export async function refreshedAccessToken(
25
+ store: SubscriptionStore,
26
+ credential: SubscriptionCredential,
27
+ options: { fetch: OAuthFetch; now?: Date },
18
28
  ): Promise<string> {
19
29
  const now = options.now ?? new Date();
20
- store.touch(credential.id, now);
21
30
  if (!expiresSoon(credential, now)) return credential.accessToken;
22
31
 
23
32
  const pending = inFlight.get(credential.id);
@@ -21,6 +21,7 @@ import {
21
21
  type SubscriptionCredential,
22
22
  type SubscriptionStore,
23
23
  } from "./store.js";
24
+ import { refreshStaleUsage } from "./usage.js";
24
25
 
25
26
  export type SubscriptionHttpDeps = {
26
27
  store: SubscriptionStore;
@@ -49,7 +50,13 @@ export async function handleSubscriptionRequest(
49
50
  const path = url.pathname.slice(BASE.length);
50
51
  const now = deps.now?.() ?? new Date();
51
52
  try {
52
- if (path === "" && request.method === "GET") return json(200, listBody(deps.store, now));
53
+ if (path === "" && request.method === "GET") {
54
+ // OpenCode Go reports usage only when asked.
55
+ if (url.searchParams.get("refresh_usage") === "true") {
56
+ await refreshStaleUsage(deps.store, { fetch: deps.fetch, now });
57
+ }
58
+ return json(200, listBody(deps.store, now));
59
+ }
53
60
  if (path === "/oauth/sessions" && request.method === "POST") {
54
61
  return json(201, await startSession(deps, await readBody(request), now));
55
62
  }
@@ -9,6 +9,9 @@
9
9
  * database file; protect that file like a secret.
10
10
  * - `access.ts`: `freshAccessToken` refreshes a token expiring within five
11
11
  * minutes before handing it out, one refresh per credential at a time.
12
+ * - `usage.ts`: `refreshStaleUsage` reads OpenCode Go plan usage from its
13
+ * usage endpoint, which its responses never report, when the accounts view
14
+ * asks.
12
15
  * - `http.ts`: `handleSubscriptionRequest` serves the credential endpoints the
13
16
  * Dari CLI uses to connect, list, rename, release, and disconnect
14
17
  * subscriptions. The caller authenticates the request first.
@@ -0,0 +1,64 @@
1
+ import { openCodeGoUsageFromReport } from "../../providers/subscription_limits.js";
2
+ import { refreshedAccessToken } from "./access.js";
3
+ import type { OAuthFetch } from "./oauth.js";
4
+ import type { SubscriptionCredential, SubscriptionStore } from "./store.js";
5
+
6
+ /**
7
+ * Claude Code, ChatGPT, and Muse Code report usage on the responses the
8
+ * gateway serves. OpenCode Go does not: it reports it from a usage endpoint
9
+ * that takes the plan's workspace, which the accounts view reads again when
10
+ * the last reading is stale.
11
+ */
12
+ // A read, failed or not, is not repeated within this interval.
13
+ const READ_INTERVAL_MS = 60_000;
14
+ const READ_TIMEOUT_MS = 8_000;
15
+ const OPENCODE_GO_USAGE_URL = "https://opencode.ai/zen/go/v1/usage";
16
+
17
+ // Reads that recorded nothing (failed, or no running window), so such a plan is
18
+ // not re-read on every listing. A recorded reading stamps the credential
19
+ // itself, which a reconnect clears.
20
+ const unrecordedAt = new Map<string, number>();
21
+
22
+ /** Read every stale OpenCode Go plan again; a failed read keeps the last one. */
23
+ export async function refreshStaleUsage(
24
+ store: SubscriptionStore,
25
+ options: { fetch: OAuthFetch; now?: Date },
26
+ ): Promise<void> {
27
+ const now = options.now ?? new Date();
28
+ const due = (at: number | undefined) => now.getTime() - (at ?? 0) >= READ_INTERVAL_MS;
29
+ const stale = store.list("opencode_go").filter((credential) =>
30
+ due(credential.usage?.observedAt.getTime()) && due(unrecordedAt.get(credential.id))
31
+ );
32
+ await Promise.all(stale.map(async (credential) => {
33
+ unrecordedAt.set(credential.id, now.getTime());
34
+ try {
35
+ await readUsage(store, credential, { ...options, now });
36
+ } catch (error) {
37
+ console.error(`subscription usage read failed for ${credential.name}:`, error instanceof Error ? error.message : error);
38
+ }
39
+ }));
40
+ }
41
+
42
+ async function readUsage(
43
+ store: SubscriptionStore,
44
+ credential: SubscriptionCredential,
45
+ options: { fetch: OAuthFetch; now: Date },
46
+ ): Promise<void> {
47
+ const token = await refreshedAccessToken(store, credential, options);
48
+ const response = await options.fetch(OPENCODE_GO_USAGE_URL, {
49
+ method: "GET",
50
+ headers: {
51
+ Accept: "application/json",
52
+ Authorization: `Bearer ${token}`,
53
+ "User-Agent": "dari-gateway",
54
+ ...(credential.accountId === null ? {} : { "x-opencode-org-id": credential.accountId }),
55
+ },
56
+ signal: AbortSignal.timeout(READ_TIMEOUT_MS),
57
+ });
58
+ // Go answers 403 for a workspace without a Go plan.
59
+ if (!response.ok) throw new Error(`OpenCode Go usage read failed with status ${response.status}.`);
60
+ const usage = openCodeGoUsageFromReport(await response.json(), options.now);
61
+ if (usage === null) return;
62
+ unrecordedAt.delete(credential.id);
63
+ store.recordUsage(credential.id, usage, options.now);
64
+ }