@mupt-ai/dari-gateway 1.0.310 → 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.
Files changed (83) hide show
  1. package/README.md +4 -0
  2. package/dari-gateway.example.yaml +10 -0
  3. package/dist/context/provider_prompt_accounting.js +7 -0
  4. package/dist/context/routing_context.js +4 -1
  5. package/dist/interaction/system_prompt.d.ts +2 -0
  6. package/dist/interaction/system_prompt.js +21 -0
  7. package/dist/models/canonical.d.ts +2 -0
  8. package/dist/models/canonical.js +4 -0
  9. package/dist/models/catalog.js +1 -0
  10. package/dist/models/provider_defaults.js +4 -0
  11. package/dist/models/subscriptions.d.ts +4 -3
  12. package/dist/models/subscriptions.js +13 -9
  13. package/dist/platform/platform.d.ts +3 -0
  14. package/dist/providers/codex_usage.d.ts +13 -0
  15. package/dist/providers/codex_usage.js +46 -2
  16. package/dist/providers/execution.js +62 -9
  17. package/dist/providers/key_check.js +3 -0
  18. package/dist/providers/pi.js +5 -0
  19. package/dist/providers/pi_options.js +8 -0
  20. package/dist/providers/provider_call.d.ts +2 -0
  21. package/dist/providers/provider_call.js +9 -3
  22. package/dist/providers/response_capture.d.ts +4 -1
  23. package/dist/providers/response_capture.js +81 -2
  24. package/dist/providers/subscription_limits.d.ts +20 -2
  25. package/dist/providers/subscription_limits.js +115 -13
  26. package/dist/runtime/explicit_model.js +9 -4
  27. package/dist/runtime/prepare_routed_completion.d.ts +3 -1
  28. package/dist/runtime/prepare_routed_completion.js +7 -2
  29. package/dist/runtime/role_model.d.ts +8 -0
  30. package/dist/runtime/role_model.js +27 -0
  31. package/dist/runtime/routed_runtime.js +3 -1
  32. package/dist/self_host/config.d.ts +9 -1
  33. package/dist/self_host/config.js +44 -1
  34. package/dist/self_host/platform.js +7 -2
  35. package/dist/self_host/resolve.js +18 -3
  36. package/dist/self_host/subscription_test_gateway.d.ts +4 -3
  37. package/dist/self_host/subscription_test_gateway.js +11 -8
  38. package/dist/self_host/subscriptions/access.d.ts +5 -0
  39. package/dist/self_host/subscriptions/access.js +5 -1
  40. package/dist/self_host/subscriptions/http.js +16 -2
  41. package/dist/self_host/subscriptions/index.d.ts +6 -2
  42. package/dist/self_host/subscriptions/index.js +6 -2
  43. package/dist/self_host/subscriptions/oauth.d.ts +8 -4
  44. package/dist/self_host/subscriptions/oauth.js +75 -0
  45. package/dist/self_host/subscriptions/store.d.ts +17 -2
  46. package/dist/self_host/subscriptions/store.js +53 -8
  47. package/dist/self_host/subscriptions/usage.d.ts +7 -0
  48. package/dist/self_host/subscriptions/usage.js +52 -0
  49. package/dist/strategies/route_decision.js +0 -5
  50. package/dist/types.d.ts +6 -1
  51. package/package.json +2 -2
  52. package/src/context/provider_prompt_accounting.ts +7 -0
  53. package/src/context/routing_context.ts +4 -1
  54. package/src/interaction/system_prompt.ts +26 -0
  55. package/src/models/canonical.ts +5 -0
  56. package/src/models/catalog.ts +1 -0
  57. package/src/models/provider_defaults.ts +4 -0
  58. package/src/models/subscriptions.ts +14 -14
  59. package/src/platform/platform.ts +3 -0
  60. package/src/providers/codex_usage.ts +59 -2
  61. package/src/providers/execution.ts +65 -8
  62. package/src/providers/key_check.ts +2 -0
  63. package/src/providers/pi.ts +5 -0
  64. package/src/providers/pi_options.ts +7 -0
  65. package/src/providers/provider_call.ts +12 -3
  66. package/src/providers/response_capture.ts +88 -2
  67. package/src/providers/subscription_limits.ts +131 -14
  68. package/src/runtime/explicit_model.ts +9 -4
  69. package/src/runtime/prepare_routed_completion.ts +13 -3
  70. package/src/runtime/role_model.ts +35 -0
  71. package/src/runtime/routed_runtime.ts +3 -1
  72. package/src/self_host/config.ts +55 -2
  73. package/src/self_host/platform.ts +6 -3
  74. package/src/self_host/resolve.ts +15 -2
  75. package/src/self_host/subscription_test_gateway.ts +14 -8
  76. package/src/self_host/subscriptions/access.ts +10 -1
  77. package/src/self_host/subscriptions/http.ts +23 -2
  78. package/src/self_host/subscriptions/index.ts +7 -1
  79. package/src/self_host/subscriptions/oauth.ts +104 -5
  80. package/src/self_host/subscriptions/store.ts +65 -9
  81. package/src/self_host/subscriptions/usage.ts +64 -0
  82. package/src/strategies/route_decision.ts +0 -9
  83. package/src/types.ts +13 -1
@@ -0,0 +1,26 @@
1
+ import type { InteractionItem, InteractionRequest } from "./types.js";
2
+
3
+ /* Appends text to the end of the system prompt: after the client's
4
+ instructions and its leading system or developer messages, before the
5
+ conversation. The text is the same on every turn, so the provider's cached
6
+ prefix stays stable. */
7
+ export function withSystemPromptSuffix(
8
+ interaction: InteractionRequest,
9
+ suffix: string | undefined,
10
+ ): InteractionRequest {
11
+ if (!suffix) return interaction;
12
+ const isPreamble = (item: InteractionItem) =>
13
+ item.type === "message" && (item.role === "system" || item.role === "developer");
14
+ const at = interaction.items.findIndex((item) => !isPreamble(item));
15
+ const index = at === -1 ? interaction.items.length : at;
16
+ const message: InteractionItem = {
17
+ type: "message",
18
+ role: "system",
19
+ content: [{ type: "text", text: suffix }],
20
+ contentShape: "string",
21
+ };
22
+ return {
23
+ ...interaction,
24
+ items: [...interaction.items.slice(0, index), message, ...interaction.items.slice(index)],
25
+ };
26
+ }
@@ -9,3 +9,8 @@ export type CanonicalModel = {
9
9
 
10
10
  /** The canonical models Dari serves, from the monorepo's router catalog. */
11
11
  export const CANONICAL_MODELS: readonly CanonicalModel[] = canonicalModels;
12
+
13
+ /** A model's catalog name; a model the catalog does not list keeps its id. */
14
+ export function canonicalModelName(id: string): string {
15
+ return CANONICAL_MODELS.find((model) => model.id === id)?.name ?? id;
16
+ }
@@ -67,6 +67,7 @@ export const DEFAULT_CATALOG_PROVIDERS: readonly string[] = [
67
67
  "meta",
68
68
  "xai",
69
69
  "fireworks",
70
+ "opencode-go",
70
71
  "openrouter",
71
72
  "vercel-ai-gateway",
72
73
  ];
@@ -10,6 +10,7 @@ const PROVIDER_LABELS: Record<string, string> = {
10
10
  fireworks: "Fireworks",
11
11
  meta: "Meta",
12
12
  xai: "xAI",
13
+ "opencode-go": "OpenCode Go",
13
14
  dari: "Dari",
14
15
  "amazon-bedrock": "Amazon Bedrock",
15
16
  azure: "Microsoft Azure",
@@ -33,6 +34,9 @@ const PROVIDER_BASE_URLS: Record<string, string> = {
33
34
  anthropic: "https://api.anthropic.com",
34
35
  fireworks: "https://api.fireworks.ai/inference/v1",
35
36
  xai: "https://api.x.ai/v1",
37
+ // A flat-rate plan for open models; each model keeps its own API path
38
+ // under https://opencode.ai/inference/go/, and this is chat completions.
39
+ "opencode-go": "https://opencode.ai/inference/go/openai/v1",
36
40
  // Meta's Model API serves OpenAI Responses and Chat Completions here, and
37
41
  // Anthropic Messages at https://api.meta.ai.
38
42
  meta: "https://api.meta.ai/v1",
@@ -1,18 +1,17 @@
1
- import {
2
- nativeModelId,
3
- providerForModel,
4
- type RouterModelPrice,
5
- } from "@mupt-ai/dari-router/policy-engine";
1
+ import { nativeModelId, type RouterModelPrice } from "@mupt-ai/dari-router/policy-engine";
6
2
 
7
3
  import type { ClientHarness, ResolvedRouterModelConfig, SubscriptionKind } from "../types.js";
8
4
 
9
5
  const CODEX_BACKEND_URL = "https://chatgpt.com/backend-api";
10
6
 
11
- // The model provider whose models each kind of plan serves.
12
- const SUBSCRIPTION_MODEL_PROVIDERS: Record<SubscriptionKind, string> = {
13
- openai_codex: "openai",
14
- anthropic_claude_code: "anthropic",
15
- meta_muse: "meta",
7
+ // The execution providers whose models each kind of plan serves; a ChatGPT
8
+ // plan's OpenAI models execute as `openai-codex` once resolve points them at
9
+ // the Codex backend.
10
+ const SUBSCRIPTION_MODEL_PROVIDERS: Record<SubscriptionKind, readonly string[]> = {
11
+ openai_codex: ["openai", "openai-codex"],
12
+ anthropic_claude_code: ["anthropic"],
13
+ meta_muse: ["meta"],
14
+ opencode_go: ["opencode-go"],
16
15
  };
17
16
 
18
17
  // The client each plan is limited to, as its provider limits it: a Claude Code
@@ -23,15 +22,16 @@ const SUBSCRIPTION_CLIENTS: Partial<Record<SubscriptionKind, ClientHarness>> = {
23
22
  };
24
23
 
25
24
  /**
26
- * Whether a plan may serve a model for this client: each plan serves only its
27
- * own provider's models, and only to the client its provider allows.
25
+ * Whether a plan may serve a model executed by `provider` for this client:
26
+ * each plan serves only its own provider's models, and only to the client its
27
+ * provider allows.
28
28
  */
29
29
  export function subscriptionServes(
30
30
  kind: SubscriptionKind,
31
- model: string,
31
+ provider: string,
32
32
  clientHarness: ClientHarness | undefined,
33
33
  ): boolean {
34
- if (SUBSCRIPTION_MODEL_PROVIDERS[kind] !== providerForModel(model)) return false;
34
+ if (!SUBSCRIPTION_MODEL_PROVIDERS[kind].includes(provider)) return false;
35
35
  const client = SUBSCRIPTION_CLIENTS[kind];
36
36
  return client === undefined || clientHarness === client;
37
37
  }
@@ -58,6 +58,9 @@ export type GatewayPlatform = {
58
58
  /**
59
59
  * Hold an exhausted personal subscription until it resets. Resolves whether
60
60
  * another connected subscription for the same provider can serve a retry.
61
+ * A limit naming a `model` holds only that model on the subscription, which
62
+ * keeps serving the router's other models; it resolves whether the hold
63
+ * landed, since those models then serve a retry.
61
64
  */
62
65
  markSubscriptionUnavailable(hold: SubscriptionHold): Promise<boolean>;
63
66
  /**
@@ -1,4 +1,9 @@
1
- import { CODEX_USAGE_WINDOWS, type SubscriptionUsage, subscriptionUsageFromWindows } from "./subscription_limits.js";
1
+ import {
2
+ CODEX_USAGE_WINDOWS,
3
+ DEFAULT_USAGE_LIMIT_WINDOW_MS,
4
+ type SubscriptionUsage,
5
+ subscriptionUsageFromWindows,
6
+ } from "./subscription_limits.js";
2
7
 
3
8
  // Codex calls run over a WebSocket that bypasses fetch, so a ChatGPT plan's
4
9
  // usage never reaches the gateway as response headers. The ChatGPT backend's
@@ -22,7 +27,59 @@ export async function readCodexUsage(args: {
22
27
  const last = readAt.get(args.credentialId);
23
28
  if (last !== undefined && now - last < CODEX_USAGE_INTERVAL_MS) return null;
24
29
  readAt.set(args.credentialId, now);
30
+ return codexUsageFromReport(await fetchCodexUsageReport(args), new Date(now));
31
+ }
32
+
33
+ /**
34
+ * When a ChatGPT usage-limit refusal came from a per-model cap rather than the
35
+ * plan's own limit, that cap's reset; null when the plan itself is spent or
36
+ * the report names no spent cap. The report lists those caps as
37
+ * `additional_rate_limits` beside the plan's `rate_limit`.
38
+ */
39
+ export async function readCodexModelLimitReset(args: {
40
+ accessToken: string;
41
+ baseUrl?: string;
42
+ now?: Date;
43
+ fetch?: typeof fetch;
44
+ }): Promise<Date | null> {
45
+ return codexModelLimitResetFromReport(await fetchCodexUsageReport(args), args.now ?? new Date());
46
+ }
47
+
48
+ export function codexModelLimitResetFromReport(report: unknown, now: Date): Date | null {
49
+ if (!isRecord(report) || limitSpent(report.rate_limit)) return null;
50
+ const spent = (Array.isArray(report.additional_rate_limits) ? report.additional_rate_limits : [])
51
+ .map((limit) => isRecord(limit) ? limit.rate_limit : undefined)
52
+ .filter(limitSpent);
53
+ if (spent.length === 0) return null;
54
+ const resets = spent.flatMap((limit) => limitWindows(limit))
55
+ .filter((window) => window.used >= 100 && window.resetAt !== null && window.resetAt > now)
56
+ .map((window) => window.resetAt!.getTime());
57
+ return new Date(resets.length > 0 ? Math.max(...resets) : now.getTime() + DEFAULT_USAGE_LIMIT_WINDOW_MS);
58
+ }
25
59
 
60
+ function limitSpent(limit: unknown): boolean {
61
+ if (!isRecord(limit)) return false;
62
+ return limit.limit_reached === true || limit.allowed === false
63
+ || limitWindows(limit).some((window) => window.used >= 100);
64
+ }
65
+
66
+ function limitWindows(limit: unknown): Array<{ used: number; resetAt: Date | null }> {
67
+ if (!isRecord(limit)) return [];
68
+ return CODEX_USAGE_WINDOWS.flatMap(([name]) => {
69
+ const window = limit[`${name}_window`];
70
+ if (!isRecord(window) || typeof window.used_percent !== "number") return [];
71
+ return [{
72
+ used: window.used_percent,
73
+ resetAt: typeof window.reset_at === "number" ? new Date(window.reset_at * 1000) : null,
74
+ }];
75
+ });
76
+ }
77
+
78
+ async function fetchCodexUsageReport(args: {
79
+ accessToken: string;
80
+ baseUrl?: string;
81
+ fetch?: typeof fetch;
82
+ }): Promise<unknown> {
26
83
  const accountId = codexAccountId(args.accessToken);
27
84
  const response = await (args.fetch ?? globalThis.fetch)(
28
85
  `${(args.baseUrl ?? DEFAULT_CODEX_BASE_URL).replace(/\/$/, "")}/wham/usage`,
@@ -36,7 +93,7 @@ export async function readCodexUsage(args: {
36
93
  },
37
94
  );
38
95
  if (!response.ok) throw new Error(`Codex usage report failed with status ${response.status}.`);
39
- return codexUsageFromReport(await response.json(), new Date(now));
96
+ return await response.json();
40
97
  }
41
98
 
42
99
  /** Every Codex window with a future reset, or null when the report has none. */
@@ -49,17 +49,19 @@ import {
49
49
  import type { NextSubscription } from "../platform/platform.js";
50
50
  import { providerResponseCaptureFromError, type ProviderResponseCapture } from "./response_capture.js";
51
51
  import { createStreamFinalizer } from "./stream_finalization.js";
52
- import { readCodexUsage } from "./codex_usage.js";
52
+ import { readCodexModelLimitReset, readCodexUsage } from "./codex_usage.js";
53
53
  import {
54
54
  detectSubscriptionUsageLimit,
55
55
  codexUsageLimitError,
56
56
  subscriptionOAuthProviderFor,
57
57
  subscriptionUsageFromHeaders,
58
+ museSubscriptionUsage,
58
59
  failureWithSubscriptionUsageLimit,
59
60
  retryAfterSeconds,
60
61
  subscriptionUsageLimitFromFailure,
61
62
  subscriptionSwitchedMessage,
62
63
  subscriptionUsageLimitMessage,
64
+ type SubscriptionUsageLimit,
63
65
  } from "./subscription_limits.js";
64
66
 
65
67
  export type ProviderChoice = {
@@ -718,14 +720,16 @@ async function providerFailedAttempt(
718
720
  execution: ProviderExecution,
719
721
  responseCapture: ProviderResponseCapture | undefined,
720
722
  ): Promise<ProviderAttemptFailure> {
721
- const limit = detectSubscriptionUsageLimit({
723
+ const detected = detectSubscriptionUsageLimit({
722
724
  provider: execution.provider,
723
725
  keySource: execution.providerKeySource,
726
+ model: execution.model,
724
727
  captured: responseCapture?.last,
725
728
  failure: message,
726
729
  });
727
- if (limit === null) {
730
+ if (detected === null) {
728
731
  const status = responseCapture?.last?.status;
732
+ if (execution.providerKeySource === "subscription") logUnclassifiedRefusal(execution, responseCapture);
729
733
  // The customer's own key was refused: theirs to fix, not a gateway fault.
730
734
  const rejected = execution.providerKeySource === "user" && (status === 401 || status === 403);
731
735
  return {
@@ -737,10 +741,15 @@ async function providerFailedAttempt(
737
741
  retryable: !isPromptPolicyRejection(message),
738
742
  };
739
743
  }
744
+ const limit = detected.oauthProvider === "openai_codex" && detected.model === undefined
745
+ && execution.subscriptionUserId !== undefined
746
+ ? await withCodexModelLimit(detected, execution)
747
+ : detected;
740
748
  // Retrying an exhausted plan cannot succeed. The platform learns about it
741
749
  // before this request returns so the next resolve already serves the
742
750
  // user's next subscription, or the model's API credential when the router
743
- // allows subscription API fallback for it.
751
+ // allows subscription API fallback for it. A limit on one model holds only
752
+ // that model, and the next resolve routes to the others.
744
753
  const switched = execution.subscriptionUserId !== undefined
745
754
  && await holdSubscription({
746
755
  userId: execution.subscriptionUserId,
@@ -748,8 +757,9 @@ async function providerFailedAttempt(
748
757
  limit,
749
758
  });
750
759
  // Nothing reached the client yet, so the same request is retried on the
751
- // next plan at once when the platform names it.
752
- const nextSubscription = switched
760
+ // next plan at once when the platform names it. The same plan still serves
761
+ // after a model limit, so there is no next plan to retry on.
762
+ const nextSubscription = switched && limit.model === undefined
753
763
  ? await nextSubscriptionFor(execution)
754
764
  : undefined;
755
765
  return {
@@ -808,6 +818,49 @@ function usageHasTokens(usage: unknown): boolean {
808
818
  });
809
819
  }
810
820
 
821
+ // Codex's WebSocket transport carries no headers, and a refusal over HTTP may
822
+ // carry none of the per-limit families, so the usage report tells whether the
823
+ // plan or only this model's own cap is spent. Unknown keeps the plan hold.
824
+ async function withCodexModelLimit(
825
+ limit: SubscriptionUsageLimit,
826
+ execution: ProviderExecution,
827
+ ): Promise<SubscriptionUsageLimit> {
828
+ try {
829
+ const resetsAt = await readCodexModelLimitReset({
830
+ accessToken: execution.apiKey,
831
+ baseUrl: execution.endpoint?.baseUrl ?? execution.config?.base_url ?? undefined,
832
+ });
833
+ if (resetsAt === null) return limit;
834
+ return { ...limit, model: execution.model, resetsAt, reason: `ChatGPT usage limit for ${execution.model} reached.` };
835
+ } catch (error) {
836
+ console.error("codex usage report for a usage limit failed", error);
837
+ return limit;
838
+ }
839
+ }
840
+
841
+ // A subscription refusal no rule recognizes may be a usage limit in a shape
842
+ // not seen yet (a new per-model cap). Log what identifies one, never content.
843
+ function logUnclassifiedRefusal(
844
+ execution: ProviderExecution,
845
+ responseCapture: ProviderResponseCapture | undefined,
846
+ ): void {
847
+ const captured = responseCapture?.last;
848
+ if (captured === undefined || (captured.status !== 403 && captured.status !== 429)) return;
849
+ // Claude Code's per-minute limit, a known transient refusal.
850
+ if (captured.headers.get("anthropic-ratelimit-unified-status")?.startsWith("allowed")) return;
851
+ const headers: Record<string, string> = {};
852
+ captured.headers.forEach((value, name) => {
853
+ if (/ratelimit|rate-limit|used-percent|reset|retry-after|limit-name/i.test(name)) headers[name] = value;
854
+ });
855
+ console.warn("unclassified subscription refusal", JSON.stringify({
856
+ provider: execution.provider,
857
+ model: execution.model,
858
+ status: captured.status,
859
+ headers,
860
+ body: captured.bodyText.slice(0, 500),
861
+ }));
862
+ }
863
+
811
864
  function isPromptPolicyRejection(message: Record<string, unknown>): boolean {
812
865
  const text = providerFailureMessage(message).toLowerCase();
813
866
  return text.includes("invalid prompt") && text.includes("usage policy");
@@ -862,16 +915,20 @@ function noteSubscriptionUsage(
862
915
  const fromHeaders = headers === undefined
863
916
  ? null
864
917
  : subscriptionUsageFromHeaders(execution.provider, execution.providerKeySource, headers);
918
+ const oauthProvider = subscriptionOAuthProviderFor(execution.provider, execution.providerKeySource);
865
919
  // Codex's WebSocket transport carries no headers; its usage report does.
920
+ // Muse Code's usage is the last event of its stream.
866
921
  const usage = fromHeaders !== null
867
922
  ? Promise.resolve(fromHeaders)
868
- : subscriptionOAuthProviderFor(execution.provider, execution.providerKeySource) === "openai_codex"
923
+ : oauthProvider === "openai_codex"
869
924
  ? readCodexUsage({
870
925
  credentialId,
871
926
  accessToken: execution.apiKey,
872
927
  baseUrl: execution.endpoint?.baseUrl ?? execution.config?.base_url ?? undefined,
873
928
  })
874
- : Promise.resolve(null);
929
+ : oauthProvider === "meta_muse" && responseCapture !== undefined
930
+ ? responseCapture.streamedSubscriptionUsage.then((snapshot) => museSubscriptionUsage(snapshot, new Date()))
931
+ : Promise.resolve(null);
875
932
  usage
876
933
  .then((reported) => reported === null ? undefined : record({ userId, credentialId, usage: reported }))
877
934
  .catch((error: unknown) => {
@@ -55,6 +55,8 @@ function keyCheckRequest(
55
55
  if (endpoint === undefined) {
56
56
  if (provider === "openrouter") return { url: "https://openrouter.ai/api/v1/key", headers: bearer };
57
57
  if (provider === "vercel-ai-gateway") return { url: "https://ai-gateway.vercel.sh/v1/credits", headers: bearer };
58
+ // OpenCode Go's models list is public, so it cannot tell a bad key.
59
+ if (provider === "opencode-go") return null;
58
60
  }
59
61
  const target = endpoint
60
62
  ?? (getBuiltinModels(provider as never) as unknown as ProviderKeyEndpoint[] | undefined)?.[0];
@@ -114,6 +114,11 @@ function piStreamSimple(
114
114
  ): AssistantMessageEventStream {
115
115
  const api = PI_APIS[String(model.api)];
116
116
  if (!api) throw new Error(`No Pi API implementation for ${String(model.api)}.`);
117
+ // The Anthropic SDK adds ANTHROPIC_CUSTOM_HEADERS from the process
118
+ // environment to every request. A gateway started from a Claude Code
119
+ // session inherits Dari's own `Authorization` there, which would replace
120
+ // the credential the gateway resolved; upstream headers are the gateway's.
121
+ delete process.env.ANTHROPIC_CUSTOM_HEADERS;
117
122
  return api.streamSimple(model as unknown as Model<Api>, normalizeContext(context as unknown as Context), options);
118
123
  }
119
124
 
@@ -77,6 +77,13 @@ export function buildOptions(
77
77
  if (model.provider === "meta" && request.museCodeClientId !== undefined) {
78
78
  headers["x-client-id"] = request.museCodeClientId;
79
79
  }
80
+ // OpenCode Go serves coding agents that name themselves and send a stable
81
+ // session id; a generic SDK user agent reads as abuse.
82
+ // https://opencode.ai/docs/go/
83
+ if (model.provider === "opencode-go") {
84
+ headers["user-agent"] = "dari-gateway";
85
+ if (sessionId) headers["x-opencode-session"] = sessionId;
86
+ }
80
87
  // Pi's Anthropic transport honors compat.supportsTemperature; the OpenAI
81
88
  // transports forward temperature regardless, so drop it here for models
82
89
  // that reject it instead of failing the whole request.
@@ -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,
@@ -49,6 +50,7 @@ import {
49
50
  type ProviderEventStream,
50
51
  } from "./pi.js";
51
52
  import { promptTokenEstimateFor, type PromptTokenEstimate } from "./cancel_estimate.js";
53
+ import { withSystemPromptSuffix } from "../interaction/system_prompt.js";
52
54
 
53
55
  type ProviderCallConfig = {
54
56
  model: string;
@@ -62,6 +64,8 @@ type ProviderCallConfig = {
62
64
  promptEstimate: PromptTokenEstimate | undefined;
63
65
  // A platform-supplied endpoint replacing the model's configured one.
64
66
  endpoint?: ProviderEndpoint;
67
+ // Appended to the end of the system prompt sent to the provider.
68
+ systemPromptSuffix?: string;
65
69
  };
66
70
 
67
71
  export type ProviderExecution = ProviderCallConfig & {
@@ -107,6 +111,7 @@ export function prepareProviderExecution(args: {
107
111
  promptCacheKey?: string;
108
112
  costEstimates?: readonly CandidateCostEstimate[];
109
113
  tags?: RequestTags;
114
+ systemPromptSuffix?: string;
110
115
  }): ProviderExecution {
111
116
  const model = args.decision.selectedModel;
112
117
  const promptEstimate = promptTokenEstimateFor(args.costEstimates, model, args.decision.reasoningEffort);
@@ -146,6 +151,7 @@ export function prepareProviderExecution(args: {
146
151
  : args.conversationId,
147
152
  reasoningEffort: args.decision.reasoningEffort,
148
153
  promptEstimate,
154
+ ...(args.systemPromptSuffix ? { systemPromptSuffix: args.systemPromptSuffix } : {}),
149
155
  ...(supplied?.baseUrl || supplied?.headers
150
156
  ? { endpoint: { baseUrl: supplied.baseUrl, headers: supplied.headers } }
151
157
  : {}),
@@ -208,9 +214,12 @@ export function startProviderCompletion(args: {
208
214
  function responseCaptureFor(execution: ProviderExecution): ProviderResponseCapture | undefined {
209
215
  // A subscription's failures carry its usage limit; a customer key's say
210
216
  // whether the provider refused the key itself.
217
+ // Muse Code reports its plan's usage as the stream's last event.
211
218
  return execution.providerKeySource === "managed"
212
219
  ? undefined
213
- : createProviderResponseCapture();
220
+ : createProviderResponseCapture({
221
+ watchSubscriptionUsage: subscriptionOAuthProviderFor(execution.provider, execution.providerKeySource) === "meta_muse",
222
+ });
214
223
  }
215
224
 
216
225
  export async function startProviderStream(args: {
@@ -230,7 +239,7 @@ export async function startProviderStream(args: {
230
239
  try {
231
240
  const providerStream = await streamInteractionModel({
232
241
  model: args.execution.model,
233
- request: args.interaction,
242
+ request: withSystemPromptSuffix(args.interaction, args.execution.systemPromptSuffix),
234
243
  apiKey: args.execution.apiKey,
235
244
  auth: await awsRoleCredentials.resolve(args.execution.auth),
236
245
  pricing: args.execution.pricing,
@@ -325,7 +334,7 @@ async function completeProvider(args: {
325
334
  const providerStartedAt = new Date();
326
335
  const completion = await completeInteractionModel({
327
336
  model: args.execution.model,
328
- request: args.interaction,
337
+ request: withSystemPromptSuffix(args.interaction, args.execution.systemPromptSuffix),
329
338
  apiKey: args.execution.apiKey,
330
339
  auth: await awsRoleCredentials.resolve(args.execution.auth),
331
340
  pricing: args.execution.pricing,
@@ -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();