@mupt-ai/dari-gateway 1.0.341 → 1.0.342

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 (34) hide show
  1. package/dist/activity/tool_exchanges.d.ts +0 -1
  2. package/dist/activity/values.d.ts +0 -1
  3. package/dist/activity/values.js +0 -4
  4. package/dist/ingress/codex_models.d.ts +2 -2
  5. package/dist/ingress/codex_models.js +34 -7
  6. package/dist/link/budget.d.ts +2 -0
  7. package/dist/link/budget.js +10 -2
  8. package/dist/link/grant_access.js +9 -4
  9. package/dist/link/grants.d.ts +0 -1
  10. package/dist/link/service.js +1 -1
  11. package/dist/platform/platform.d.ts +2 -0
  12. package/dist/providers/subscription_limits.d.ts +6 -0
  13. package/dist/providers/subscription_limits.js +14 -0
  14. package/dist/self_host/subscriptions/index.d.ts +3 -3
  15. package/dist/self_host/subscriptions/index.js +3 -3
  16. package/dist/self_host/subscriptions/usage.d.ts +1 -1
  17. package/dist/self_host/subscriptions/usage.js +28 -11
  18. package/dist/strategies/auto_routing_selector.js +7 -18
  19. package/dist/telemetry/tools/git_events.d.ts +0 -2
  20. package/dist/telemetry/tools/git_events.js +0 -4
  21. package/package.json +2 -2
  22. package/src/activity/tool_exchanges.ts +0 -1
  23. package/src/activity/values.ts +0 -5
  24. package/src/ingress/codex_models.ts +43 -10
  25. package/src/link/budget.ts +11 -3
  26. package/src/link/grant_access.ts +8 -3
  27. package/src/link/grants.ts +0 -2
  28. package/src/link/service.ts +1 -1
  29. package/src/platform/platform.ts +3 -0
  30. package/src/providers/subscription_limits.ts +18 -0
  31. package/src/self_host/subscriptions/index.ts +3 -3
  32. package/src/self_host/subscriptions/usage.ts +32 -10
  33. package/src/strategies/auto_routing_selector.ts +7 -22
  34. package/src/telemetry/tools/git_events.ts +0 -5
@@ -2,7 +2,6 @@ import { type ActivityFilters } from "./filters.js";
2
2
  import type { ActivityRoute } from "./http.js";
3
3
  import { type ActivityDb } from "./sql.js";
4
4
  export declare const EXCHANGE_STATES: readonly ["matched", "unmatched_call", "orphan_result"];
5
- export type ExchangeState = (typeof EXCHANGE_STATES)[number];
6
5
  export declare const EXCHANGE_MAX_LIMIT = 200;
7
6
  export type ExchangeQuery = {
8
7
  states: readonly string[];
@@ -29,7 +29,6 @@ export type Decimal = {
29
29
  export declare function parseDecimal(value: string | number): Decimal;
30
30
  export declare function addDecimals(left: Decimal, right: Decimal): Decimal;
31
31
  export declare function subtractDecimals(left: Decimal, right: Decimal): Decimal;
32
- export declare function compareDecimals(left: Decimal, right: Decimal): number;
33
32
  /** Python's `str(Decimal)`. */
34
33
  export declare function formatDecimal(value: Decimal): string;
35
34
  /** Python's `decimal_text`: a numeric column's value as API text, or null. */
@@ -103,10 +103,6 @@ export function addDecimals(left, right) {
103
103
  export function subtractDecimals(left, right) {
104
104
  return addDecimals(left, { coefficient: -right.coefficient, exponent: right.exponent });
105
105
  }
106
- export function compareDecimals(left, right) {
107
- const difference = subtractDecimals(left, right).coefficient;
108
- return difference === 0n ? 0 : difference < 0n ? -1 : 1;
109
- }
110
106
  /** Python's `str(Decimal)`. */
111
107
  export function formatDecimal(value) {
112
108
  const negative = value.coefficient < 0n;
@@ -1,3 +1,3 @@
1
1
  import type { ResolvedRouter } from "../types.js";
2
- export declare function codexModelsResponse(router: Pick<ResolvedRouter, "enabled_models" | "model_configs" | "allow_long_context" | "autorouting_enabled" | "routing_listed" | "native_compaction">, imageInputFor: (model: string) => boolean, nativeCompactionFor?: (model: string) => boolean, direct?: boolean): Record<string, unknown>;
3
- export declare function codexModelsEtag(router: Pick<ResolvedRouter, "enabled_models" | "model_configs" | "allow_long_context" | "autorouting_enabled" | "routing_listed">): string;
2
+ export declare function codexModelsResponse(router: Pick<ResolvedRouter, "enabled_models" | "model_configs" | "allow_long_context" | "autorouting_enabled" | "routing_listed" | "native_compaction" | "model_thinking_levels">, imageInputFor: (model: string) => boolean, nativeCompactionFor?: (model: string) => boolean, direct?: boolean): Record<string, unknown>;
3
+ export declare function codexModelsEtag(router: Pick<ResolvedRouter, "enabled_models" | "model_configs" | "allow_long_context" | "autorouting_enabled" | "routing_listed" | "model_thinking_levels">): string;
@@ -98,14 +98,18 @@ export function codexModelsResponse(router, imageInputFor, nativeCompactionFor =
98
98
  };
99
99
  }
100
100
  /* A version of the list Codex's /model menu shows: it changes when a model
101
- is added or removed, or dari/routing comes or goes. Sent as
101
+ is added or removed, dari/routing comes or goes, or a model's thinking
102
+ levels or default change. Sent as
102
103
  `X-Models-Etag` on the catalog and on Codex's responses, it makes a running
103
104
  Codex re-read the catalog after the first turn that sees a new value,
104
105
  instead of on its next timed refresh. Codex reads it only from a successful
105
106
  response; a refused stale pick carries the menu hint instead. */
106
107
  export function codexModelsEtag(router) {
107
- const slugs = codexCatalogEntries(router, () => false).map((entry) => entry.slug);
108
- return createHash("sha256").update(slugs.join("\n")).digest("hex").slice(0, 16);
108
+ const menu = codexCatalogEntries(router, () => false).map((entry) => {
109
+ const levels = entry.supported_reasoning_levels.map((level) => level.effort);
110
+ return `${entry.slug} ${entry.default_reasoning_level ?? ""} ${levels.join(",")}`;
111
+ });
112
+ return createHash("sha256").update(menu.join("\n")).digest("hex").slice(0, 16);
109
113
  }
110
114
  function codexCatalogEntries(router, imageInputFor) {
111
115
  return [
@@ -126,10 +130,33 @@ function codexCatalogEntries(router, imageInputFor) {
126
130
  contextWindow: codexRouterContextWindow({ ...router, enabled_models: [model] }),
127
131
  hostedWebSearch: codexRouterSupportsHostedWebSearch({ ...router, enabled_models: [model] }),
128
132
  imageInput: imageInputFor(model),
129
- reasoningLevels: router.model_configs?.[model]?.supported_thinking_levels
130
- ?.map((effort) => effort === "off" ? "none" : effort),
131
- defaultReasoningLevel: router.model_configs?.[model]?.default_thinking_level === "off"
132
- ? "none" : router.model_configs?.[model]?.default_thinking_level,
133
+ ...codexThinkingChoices(router, model),
133
134
  })),
134
135
  ];
135
136
  }
137
+ const codexEffort = (effort) => effort === "off" ? "none" : effort;
138
+ /* The thinking levels a pinned `dari/model/<id>` actually serves, so Codex's
139
+ /model and /effort menus offer only levels that run as picked. The gateway
140
+ keeps a requested level only when the router enables it for the model and
141
+ the model supports it (`clampRequestedEffort`, and candidate compatibility
142
+ in the router package); otherwise it drops the level and serves the
143
+ model's default if the router enables that, else the router's first
144
+ enabled level (`pickCandidate`). The menu shows that same set and default.
145
+ A model the router sets no levels for serves every level it supports. */
146
+ function codexThinkingChoices(router, model) {
147
+ const config = router.model_configs?.[model];
148
+ const supported = config?.supported_thinking_levels;
149
+ if (!supported) {
150
+ const fallback = config?.default_thinking_level;
151
+ return { defaultReasoningLevel: fallback ? codexEffort(fallback) : fallback };
152
+ }
153
+ const configured = router.model_thinking_levels?.[model] ?? supported;
154
+ const served = configured.filter((level) => supported.includes(level));
155
+ const modelDefault = config.default_thinking_level;
156
+ const fallback = modelDefault && served.includes(modelDefault) ? modelDefault : served[0];
157
+ return {
158
+ // Codex lists levels in the order given: keep the model's low-to-high order.
159
+ reasoningLevels: supported.filter((level) => served.includes(level)).map(codexEffort),
160
+ defaultReasoningLevel: fallback ? codexEffort(fallback) : null,
161
+ };
162
+ }
@@ -52,6 +52,8 @@ export declare function limitsBody(limits: readonly LinkLimit[]): ({
52
52
  export declare function spendBody(spend: readonly LinkSpend[]): {
53
53
  credential_id: string;
54
54
  spent_usd: number;
55
+ requests: number;
56
+ tokens: number;
55
57
  monthly_usd: number | null;
56
58
  max_percent: number | null;
57
59
  used_percent: number | null;
@@ -70,10 +70,14 @@ export function grantSpend(credentialIds, limits, uses, plans, now) {
70
70
  for (const use of uses) {
71
71
  if (use.credentialId === null || use.at.getTime() < since)
72
72
  continue;
73
- spent.set(use.credentialId, (spent.get(use.credentialId) ?? 0) + use.costUsd);
73
+ const total = spent.get(use.credentialId) ?? { usd: 0, requests: 0, tokens: 0 };
74
+ total.usd += use.costUsd;
75
+ total.requests += 1;
76
+ total.tokens += use.inputTokens + use.outputTokens + use.cacheReadTokens + use.cacheWriteTokens;
77
+ spent.set(use.credentialId, total);
74
78
  }
75
79
  return [...credentialIds].map((credentialId) => {
76
- const spentUsd = spent.get(credentialId) ?? 0;
80
+ const { usd: spentUsd, requests, tokens } = spent.get(credentialId) ?? { usd: 0, requests: 0, tokens: 0 };
77
81
  const limit = limits.find((entry) => entry.credentialId === credentialId);
78
82
  const windows = (plans.find((plan) => plan.id === credentialId)?.usage ?? [])
79
83
  .filter((window) => window.modelFamily === undefined && Date.parse(window.resetsAt) > now.getTime());
@@ -90,6 +94,8 @@ export function grantSpend(credentialIds, limits, uses, plans, now) {
90
94
  return {
91
95
  credentialId,
92
96
  spentUsd,
97
+ requests,
98
+ tokens,
93
99
  monthlyUsd: limit?.monthlyUsd ?? null,
94
100
  maxPercent: limit?.maxPercent ?? null,
95
101
  usedPercent,
@@ -140,6 +146,8 @@ export function spendBody(spend) {
140
146
  return spend.map((entry) => ({
141
147
  credential_id: entry.credentialId,
142
148
  spent_usd: entry.spentUsd,
149
+ requests: entry.requests,
150
+ tokens: entry.tokens,
143
151
  monthly_usd: entry.monthlyUsd,
144
152
  max_percent: entry.maxPercent,
145
153
  used_percent: entry.usedPercent,
@@ -86,12 +86,17 @@ function clientReasoning(credentials, model, reasoning) {
86
86
  const SNAPSHOT_DATE = /-(?:\d{8}|\d{4}-\d{2}-\d{2})$/;
87
87
  /* The model id in `models` a name means: the id itself, the one id it is the
88
88
  bare form of (`claude-haiku-4-5` is `anthropic/claude-haiku-4-5`), or either
89
- of those for a dated snapshot of it. A name two models share means neither. */
89
+ of those for a dated snapshot of it. A name two models share means neither.
90
+ Names match in any case and answer the catalog's own id: some ids carry
91
+ capitals (`deepseek-ai/DeepSeek-V4.1-Flash-1017`), which a lowercased name
92
+ would never equal. */
90
93
  export function catalogModelFor(name, models) {
94
+ const lower = models.map((id) => id.toLowerCase());
91
95
  for (const candidate of new Set([name.toLowerCase(), name.toLowerCase().replace(SNAPSHOT_DATE, "")])) {
92
- if (models.includes(candidate))
93
- return candidate;
94
- const matches = models.filter((id) => id.endsWith(`/${candidate}`));
96
+ const exact = lower.indexOf(candidate);
97
+ if (exact >= 0)
98
+ return models[exact];
99
+ const matches = models.filter((_, i) => lower[i].endsWith(`/${candidate}`));
95
100
  if (matches.length === 1)
96
101
  return matches[0];
97
102
  }
@@ -141,7 +141,6 @@ export declare function linkGrants(repo: LinkRepo): {
141
141
  /** What a grant's requests used, filtered by tags and receive time. */
142
142
  usage(grantId: string, query: Omit<LinkUsageQuery, "accessToken">): Promise<Omit<LinkUsage, "completeThrough">>;
143
143
  };
144
- export type LinkGrants = ReturnType<typeof linkGrants>;
145
144
  export declare const TOKEN_PREFIX: Record<LinkTokenKind, string>;
146
145
  /** What a stored access, child, or key token is now; null when it serves nothing. */
147
146
  export declare function linkTokenAuth(record: LinkTokenRecord | null, now: Date): LinkTokenAuth | null;
@@ -27,7 +27,7 @@ export function linkPlatform(store, users) {
27
27
  const standings = async (grant, now = new Date()) => {
28
28
  const [uses, plans] = await Promise.all([
29
29
  store.budgetUses(grant.id, usesSince(grant.budget, now)),
30
- grant.limits.length === 0 ? [] : users.plansWithIds(grant.credentialIds),
30
+ users.plansWithIds(grant.credentialIds),
31
31
  ]);
32
32
  return {
33
33
  budget: budgetStandings(grant.budget, uses, now).map((standing) => ({
@@ -349,6 +349,8 @@ export type LinkLimit = {
349
349
  export type LinkSpend = {
350
350
  credentialId: string;
351
351
  spentUsd: number;
352
+ requests: number;
353
+ tokens: number;
352
354
  monthlyUsd: number | null;
353
355
  maxPercent: number | null;
354
356
  usedPercent: number | null;
@@ -48,6 +48,12 @@ export declare function subscriptionUsageFromHeaders(provider: string, keySource
48
48
  * percent that may exceed 100.
49
49
  */
50
50
  export declare function museSubscriptionUsage(snapshot: unknown, now: Date): SubscriptionUsage | null;
51
+ /**
52
+ * The Token Pass usage AI Gateway reports at `GET /v1/credits`:
53
+ * `{token_pass: {remaining, resets_at} | null}`, remaining in USD as a string,
54
+ * or null while Vercel cannot read the balance.
55
+ */
56
+ export declare function tokenPassUsageFromCredits(credits: unknown, now: Date): SubscriptionUsage | null;
51
57
  /**
52
58
  * The usage OpenCode Go reports at `GET /zen/go/v1/usage`, which OpenCode's
53
59
  * own `/usage` reads: `{usage: {rolling|weekly|monthly: {status: "ok" |
@@ -75,6 +75,20 @@ export function museSubscriptionUsage(snapshot, now) {
75
75
  // OpenCode Go's windows by their usage report names; the monthly one follows
76
76
  // the billing cycle.
77
77
  const OPENCODE_GO_USAGE_WINDOWS = [["rolling", FIVE_HOURS], ["weekly", ONE_WEEK], ["monthly", 30 * 24 * 60]];
78
+ // Each Token Pass billing period grants $150 of credit; Vercel reports only
79
+ // what remains, so usage is measured against the full grant.
80
+ const TOKEN_PASS_CREDIT_USD = 150;
81
+ /**
82
+ * The Token Pass usage AI Gateway reports at `GET /v1/credits`:
83
+ * `{token_pass: {remaining, resets_at} | null}`, remaining in USD as a string,
84
+ * or null while Vercel cannot read the balance.
85
+ */
86
+ export function tokenPassUsageFromCredits(credits, now) {
87
+ const pass = isRecord(credits) && isRecord(credits.token_pass) ? credits.token_pass : null;
88
+ if (pass === null || typeof pass.remaining !== "string" || typeof pass.resets_at !== "string")
89
+ return null;
90
+ return subscriptionUsageFromWindows([{ minutes: 30 * 24 * 60, used: 1 - Number(pass.remaining) / TOKEN_PASS_CREDIT_USD, resetsAt: new Date(pass.resets_at) }], now);
91
+ }
78
92
  /**
79
93
  * The usage OpenCode Go reports at `GET /zen/go/v1/usage`, which OpenCode's
80
94
  * own `/usage` reads: `{usage: {rolling|weekly|monthly: {status: "ok" |
@@ -10,9 +10,9 @@
10
10
  * database file; protect that file like a secret.
11
11
  * - `access.ts`: `freshAccessToken` refreshes a token expiring within five
12
12
  * minutes before handing it out, one refresh per credential at a time.
13
- * - `usage.ts`: `refreshStaleUsage` reads OpenCode Go plan usage from its
14
- * usage endpoint, which its responses never report, when the accounts view
15
- * asks.
13
+ * - `usage.ts`: `refreshStaleUsage` reads OpenCode Go and Vercel Token Pass
14
+ * plan usage from their usage endpoints, which their responses never report,
15
+ * when the accounts view asks.
16
16
  * - `http.ts`: `handleSubscriptionRequest` serves the credential endpoints the
17
17
  * Dari CLI uses to connect, list, rename, release, and disconnect
18
18
  * subscriptions. The caller authenticates the request first.
@@ -10,9 +10,9 @@
10
10
  * database file; protect that file like a secret.
11
11
  * - `access.ts`: `freshAccessToken` refreshes a token expiring within five
12
12
  * minutes before handing it out, one refresh per credential at a time.
13
- * - `usage.ts`: `refreshStaleUsage` reads OpenCode Go plan usage from its
14
- * usage endpoint, which its responses never report, when the accounts view
15
- * asks.
13
+ * - `usage.ts`: `refreshStaleUsage` reads OpenCode Go and Vercel Token Pass
14
+ * plan usage from their usage endpoints, which their responses never report,
15
+ * when the accounts view asks.
16
16
  * - `http.ts`: `handleSubscriptionRequest` serves the credential endpoints the
17
17
  * Dari CLI uses to connect, list, rename, release, and disconnect
18
18
  * subscriptions. The caller authenticates the request first.
@@ -1,6 +1,6 @@
1
1
  import type { OAuthFetch } from "./oauth.js";
2
2
  import type { SubscriptionStore } from "./store.js";
3
- /** Read every stale OpenCode Go plan again; a failed read keeps the last one. */
3
+ /** Read every stale OpenCode Go and Token Pass plan again; a failed read keeps the last one. */
4
4
  export declare function refreshStaleUsage(store: SubscriptionStore, options: {
5
5
  fetch: OAuthFetch;
6
6
  now?: Date;
@@ -1,24 +1,26 @@
1
- import { openCodeGoUsageFromReport } from "../../providers/subscription_limits.js";
1
+ import { openCodeGoUsageFromReport, tokenPassUsageFromCredits } from "../../providers/subscription_limits.js";
2
2
  import { refreshedAccessToken } from "./access.js";
3
3
  /**
4
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.
5
+ * gateway serves. OpenCode Go and Vercel Token Pass do not: Go reports it from
6
+ * a usage endpoint that takes the plan's workspace, and Token Pass its
7
+ * remaining credit from AI Gateway's credits endpoint. The accounts view reads
8
+ * these again when the last reading is stale.
8
9
  */
9
10
  // A read, failed or not, is not repeated within this interval.
10
11
  const READ_INTERVAL_MS = 60_000;
11
12
  const READ_TIMEOUT_MS = 8_000;
12
13
  const OPENCODE_GO_USAGE_URL = "https://opencode.ai/zen/go/v1/usage";
14
+ const TOKEN_PASS_CREDITS_URL = "https://ai-gateway.vercel.sh/v1/credits";
13
15
  // Reads that recorded nothing (failed, or no running window), so such a plan is
14
16
  // not re-read on every listing. A recorded reading stamps the credential
15
17
  // itself, which a reconnect clears.
16
18
  const unrecordedAt = new Map();
17
- /** Read every stale OpenCode Go plan again; a failed read keeps the last one. */
19
+ /** Read every stale OpenCode Go and Token Pass plan again; a failed read keeps the last one. */
18
20
  export async function refreshStaleUsage(store, options) {
19
21
  const now = options.now ?? new Date();
20
22
  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)));
23
+ const stale = [...store.list("opencode_go"), ...store.list("vercel_token_pass")].filter((credential) => due(credential.usage?.observedAt.getTime()) && due(unrecordedAt.get(credential.id)));
22
24
  await Promise.all(stale.map(async (credential) => {
23
25
  unrecordedAt.set(credential.id, now.getTime());
24
26
  try {
@@ -31,6 +33,15 @@ export async function refreshStaleUsage(store, options) {
31
33
  }
32
34
  async function readUsage(store, credential, options) {
33
35
  const token = await refreshedAccessToken(store, credential, options);
36
+ const usage = credential.provider === "vercel_token_pass"
37
+ ? await readTokenPassUsage(token, options)
38
+ : await readOpenCodeGoUsage(credential, token, options);
39
+ if (usage === null)
40
+ return;
41
+ unrecordedAt.delete(credential.id);
42
+ store.recordUsage(credential.id, usage, options.now);
43
+ }
44
+ async function readOpenCodeGoUsage(credential, token, options) {
34
45
  const response = await options.fetch(OPENCODE_GO_USAGE_URL, {
35
46
  method: "GET",
36
47
  headers: {
@@ -44,9 +55,15 @@ async function readUsage(store, credential, options) {
44
55
  // Go answers 403 for a workspace without a Go plan.
45
56
  if (!response.ok)
46
57
  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);
58
+ return openCodeGoUsageFromReport(await response.json(), options.now);
59
+ }
60
+ async function readTokenPassUsage(token, options) {
61
+ const response = await options.fetch(TOKEN_PASS_CREDITS_URL, {
62
+ method: "GET",
63
+ headers: { Accept: "application/json", Authorization: `Bearer ${token}`, "User-Agent": "dari-gateway" },
64
+ signal: AbortSignal.timeout(READ_TIMEOUT_MS),
65
+ });
66
+ if (!response.ok)
67
+ throw new Error(`Token Pass usage read failed with status ${response.status}.`);
68
+ return tokenPassUsageFromCredits(await response.json(), options.now);
52
69
  }
@@ -1,3 +1,4 @@
1
+ import { requestAutoRouterSelection } from "@mupt-ai/dari-router";
1
2
  import { parseSelectorDecision, SELECTOR_LEASE_TURNS } from "@mupt-ai/dari-router/policy-engine";
2
3
  import { HttpError } from "../http/errors.js";
3
4
  export const DARI_AUTO_ROUTING_ENDPOINT = "https://routing.dari.dev/v1/auto-router";
@@ -5,7 +6,6 @@ export const DARI_AUTO_ROUTING_ENDPOINT = "https://routing.dari.dev/v1/auto-rout
5
6
  // @mupt-ai/dari-router, which calls the same API.
6
7
  const AUTO_ROUTER_MODEL = "dari/auto-router";
7
8
  const AUTO_ROUTER_CONTEXT_WINDOW_CHARS = 32_000;
8
- const AUTO_ROUTER_TIMEOUT_MS = 30_000;
9
9
  /**
10
10
  * Choose among a router's models with Dari Auto Routing, the hosted routing
11
11
  * policy. Each selection is one call to the Auto Router API with a Dari API
@@ -16,10 +16,6 @@ export function createAutoRoutingSelectorBackend(config) {
16
16
  if (!apiKey) {
17
17
  throw new Error("Dari Auto Routing needs an API key.");
18
18
  }
19
- const endpoint = (config.endpoint ?? DARI_AUTO_ROUTING_ENDPOINT)
20
- .replace(/\/+$/, "")
21
- .replace(/\/select$/, "");
22
- const fetchImpl = config.fetch ?? fetch;
23
19
  return {
24
20
  selectorModel: AUTO_ROUTER_MODEL,
25
21
  contextWindowChars: async () => AUTO_ROUTER_CONTEXT_WINDOW_CHARS,
@@ -27,25 +23,18 @@ export function createAutoRoutingSelectorBackend(config) {
27
23
  // the policy rather than the runtime's stateless hold.
28
24
  negotiatedLeaseTurns: async () => SELECTOR_LEASE_TURNS,
29
25
  select: async (args) => {
30
- let response;
26
+ let outputText;
31
27
  try {
32
- response = await fetchImpl(`${endpoint}/select`, {
33
- method: "POST",
34
- headers: {
35
- Authorization: `Bearer ${apiKey}`,
36
- "Content-Type": "application/json",
37
- },
38
- body: JSON.stringify(args.selectorRequest),
39
- signal: AbortSignal.timeout(AUTO_ROUTER_TIMEOUT_MS),
28
+ outputText = await requestAutoRouterSelection({
29
+ apiKey,
30
+ endpoint: config.endpoint ?? DARI_AUTO_ROUTING_ENDPOINT,
31
+ request: args.selectorRequest,
32
+ fetch: config.fetch,
40
33
  });
41
34
  }
42
35
  catch {
43
36
  throw new HttpError(502, "Dari Auto Routing request failed.", "selector_execution_failed");
44
37
  }
45
- if (!response.ok) {
46
- throw new HttpError(502, `Dari Auto Routing returned HTTP ${response.status}.`, "selector_execution_failed");
47
- }
48
- const outputText = await response.text();
49
38
  return {
50
39
  decision: parseSelectorDecision(outputText).decision,
51
40
  selectorModel: args.selectorModel,
@@ -31,6 +31,4 @@ export type CommitEvent = {
31
31
  };
32
32
  /** The GitHub pull requests and pushes in the request's newly submitted tool results. */
33
33
  export declare function gitEvents(request: InteractionRequest, zdr: boolean): GitEventReport[];
34
- /** The GitHub pull requests and pushes in every tool result of a request, as a stored request is read. */
35
- export declare function allGitEvents(request: InteractionRequest): GitEventReport[];
36
34
  export {};
@@ -25,10 +25,6 @@ export function gitEvents(request, zdr) {
25
25
  return [];
26
26
  return gitEventsIn(request.items, newlySubmittedToolResults(request).results.map(({ ordinal }) => ordinal));
27
27
  }
28
- /** The GitHub pull requests and pushes in every tool result of a request, as a stored request is read. */
29
- export function allGitEvents(request) {
30
- return gitEventsIn(request.items, request.items.flatMap((item, ordinal) => (item.type === "tool_result" ? [ordinal] : [])));
31
- }
32
28
  function gitEventsIn(items, resultOrdinals) {
33
29
  const calls = new Map();
34
30
  for (const item of items) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mupt-ai/dari-gateway",
3
- "version": "1.0.341",
3
+ "version": "1.0.342",
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": {
@@ -52,7 +52,7 @@
52
52
  },
53
53
  "dependencies": {
54
54
  "@aws-sdk/client-sts": "3.1063.0",
55
- "@mupt-ai/dari-router": "1.0.341",
55
+ "@mupt-ai/dari-router": "1.0.342",
56
56
  "@mupt-ai/pi-ai": "1.5.2-mupt.3"
57
57
  },
58
58
  "devDependencies": {
@@ -18,7 +18,6 @@ import { join, raw, sql, type ActivityDb, type Sql } from "./sql.js";
18
18
  import { formatInstant, readInt, readOptionalInstant, readOptionalString } from "./values.js";
19
19
 
20
20
  export const EXCHANGE_STATES = ["matched", "unmatched_call", "orphan_result"] as const;
21
- export type ExchangeState = (typeof EXCHANGE_STATES)[number];
22
21
  export const EXCHANGE_MAX_LIMIT = 200;
23
22
  const EXCHANGE_MAX_REQUEST_IDS = 100;
24
23
 
@@ -119,11 +119,6 @@ export function subtractDecimals(left: Decimal, right: Decimal): Decimal {
119
119
  return addDecimals(left, { coefficient: -right.coefficient, exponent: right.exponent });
120
120
  }
121
121
 
122
- export function compareDecimals(left: Decimal, right: Decimal): number {
123
- const difference = subtractDecimals(left, right).coefficient;
124
- return difference === 0n ? 0 : difference < 0n ? -1 : 1;
125
- }
126
-
127
122
  /** Python's `str(Decimal)`. */
128
123
  export function formatDecimal(value: Decimal): string {
129
124
  const negative = value.coefficient < 0n;
@@ -1,5 +1,6 @@
1
1
  import { createHash } from "node:crypto";
2
2
 
3
+ import type { ReasoningEffort } from "@mupt-ai/dari-router/policy-engine";
3
4
  import type { ResolvedRouter } from "../types.js";
4
5
  import { CANONICAL_ROUTER_MODEL, explicitModelSlug } from "../protocol/input/router_model.js";
5
6
  import { effectiveContextWindow } from "../models/context_limits.js";
@@ -112,7 +113,7 @@ function codexReadable(entry: Record<string, unknown>): Record<string, unknown>
112
113
  that this gateway serves one, so it can point Codex at the URL instead of
113
114
  a snapshot that goes stale when the router's models change. */
114
115
  export function codexModelsResponse(
115
- router: Pick<ResolvedRouter, "enabled_models" | "model_configs" | "allow_long_context" | "autorouting_enabled" | "routing_listed" | "native_compaction">,
116
+ router: Pick<ResolvedRouter, "enabled_models" | "model_configs" | "allow_long_context" | "autorouting_enabled" | "routing_listed" | "native_compaction" | "model_thinking_levels">,
116
117
  imageInputFor: (model: string) => boolean,
117
118
  nativeCompactionFor: (model: string) => boolean = () => false,
118
119
  direct = false,
@@ -127,20 +128,24 @@ export function codexModelsResponse(
127
128
  }
128
129
 
129
130
  /* A version of the list Codex's /model menu shows: it changes when a model
130
- is added or removed, or dari/routing comes or goes. Sent as
131
+ is added or removed, dari/routing comes or goes, or a model's thinking
132
+ levels or default change. Sent as
131
133
  `X-Models-Etag` on the catalog and on Codex's responses, it makes a running
132
134
  Codex re-read the catalog after the first turn that sees a new value,
133
135
  instead of on its next timed refresh. Codex reads it only from a successful
134
136
  response; a refused stale pick carries the menu hint instead. */
135
137
  export function codexModelsEtag(
136
- router: Pick<ResolvedRouter, "enabled_models" | "model_configs" | "allow_long_context" | "autorouting_enabled" | "routing_listed">,
138
+ router: Pick<ResolvedRouter, "enabled_models" | "model_configs" | "allow_long_context" | "autorouting_enabled" | "routing_listed" | "model_thinking_levels">,
137
139
  ): string {
138
- const slugs = codexCatalogEntries(router, () => false).map((entry) => entry.slug);
139
- return createHash("sha256").update(slugs.join("\n")).digest("hex").slice(0, 16);
140
+ const menu = codexCatalogEntries(router, () => false).map((entry) => {
141
+ const levels = (entry.supported_reasoning_levels as Array<{ effort: string }>).map((level) => level.effort);
142
+ return `${entry.slug} ${entry.default_reasoning_level ?? ""} ${levels.join(",")}`;
143
+ });
144
+ return createHash("sha256").update(menu.join("\n")).digest("hex").slice(0, 16);
140
145
  }
141
146
 
142
147
  function codexCatalogEntries(
143
- router: Pick<ResolvedRouter, "enabled_models" | "model_configs" | "allow_long_context" | "autorouting_enabled" | "routing_listed">,
148
+ router: Pick<ResolvedRouter, "enabled_models" | "model_configs" | "allow_long_context" | "autorouting_enabled" | "routing_listed" | "model_thinking_levels">,
144
149
  imageInputFor: (model: string) => boolean,
145
150
  ): Record<string, unknown>[] {
146
151
  return [
@@ -162,11 +167,39 @@ function codexCatalogEntries(
162
167
  contextWindow: codexRouterContextWindow({ ...router, enabled_models: [model] }),
163
168
  hostedWebSearch: codexRouterSupportsHostedWebSearch({ ...router, enabled_models: [model] }),
164
169
  imageInput: imageInputFor(model),
165
- reasoningLevels: router.model_configs?.[model]?.supported_thinking_levels
166
- ?.map((effort) => effort === "off" ? "none" : effort),
167
- defaultReasoningLevel: router.model_configs?.[model]?.default_thinking_level === "off"
168
- ? "none" : router.model_configs?.[model]?.default_thinking_level,
170
+ ...codexThinkingChoices(router, model),
169
171
  })
170
172
  ),
171
173
  ];
172
174
  }
175
+
176
+ const codexEffort = (effort: ReasoningEffort): string => effort === "off" ? "none" : effort;
177
+
178
+ /* The thinking levels a pinned `dari/model/<id>` actually serves, so Codex's
179
+ /model and /effort menus offer only levels that run as picked. The gateway
180
+ keeps a requested level only when the router enables it for the model and
181
+ the model supports it (`clampRequestedEffort`, and candidate compatibility
182
+ in the router package); otherwise it drops the level and serves the
183
+ model's default if the router enables that, else the router's first
184
+ enabled level (`pickCandidate`). The menu shows that same set and default.
185
+ A model the router sets no levels for serves every level it supports. */
186
+ function codexThinkingChoices(
187
+ router: Pick<ResolvedRouter, "model_configs" | "model_thinking_levels">,
188
+ model: string,
189
+ ): Pick<CodexCatalogEntry, "reasoningLevels" | "defaultReasoningLevel"> {
190
+ const config = router.model_configs?.[model];
191
+ const supported = config?.supported_thinking_levels;
192
+ if (!supported) {
193
+ const fallback = config?.default_thinking_level;
194
+ return { defaultReasoningLevel: fallback ? codexEffort(fallback) : fallback };
195
+ }
196
+ const configured = router.model_thinking_levels?.[model] ?? supported;
197
+ const served = configured.filter((level) => supported.includes(level));
198
+ const modelDefault = config.default_thinking_level;
199
+ const fallback = modelDefault && served.includes(modelDefault) ? modelDefault : served[0];
200
+ return {
201
+ // Codex lists levels in the order given: keep the model's low-to-high order.
202
+ reasoningLevels: supported.filter((level) => served.includes(level)).map(codexEffort),
203
+ defaultReasoningLevel: fallback ? codexEffort(fallback) : null,
204
+ };
205
+ }
@@ -94,13 +94,17 @@ export function grantSpend(
94
94
  now: Date,
95
95
  ): LinkSpend[] {
96
96
  const since = monthStart(now).getTime();
97
- const spent = new Map<string, number>();
97
+ const spent = new Map<string, { usd: number; requests: number; tokens: number }>();
98
98
  for (const use of uses) {
99
99
  if (use.credentialId === null || use.at.getTime() < since) continue;
100
- spent.set(use.credentialId, (spent.get(use.credentialId) ?? 0) + use.costUsd);
100
+ const total = spent.get(use.credentialId) ?? { usd: 0, requests: 0, tokens: 0 };
101
+ total.usd += use.costUsd;
102
+ total.requests += 1;
103
+ total.tokens += use.inputTokens + use.outputTokens + use.cacheReadTokens + use.cacheWriteTokens;
104
+ spent.set(use.credentialId, total);
101
105
  }
102
106
  return [...credentialIds].map((credentialId) => {
103
- const spentUsd = spent.get(credentialId) ?? 0;
107
+ const { usd: spentUsd, requests, tokens } = spent.get(credentialId) ?? { usd: 0, requests: 0, tokens: 0 };
104
108
  const limit = limits.find((entry) => entry.credentialId === credentialId);
105
109
  const windows = (plans.find((plan) => plan.id === credentialId)?.usage ?? [])
106
110
  .filter((window) => window.modelFamily === undefined && Date.parse(window.resetsAt) > now.getTime());
@@ -115,6 +119,8 @@ export function grantSpend(
115
119
  return {
116
120
  credentialId,
117
121
  spentUsd,
122
+ requests,
123
+ tokens,
118
124
  monthlyUsd: limit?.monthlyUsd ?? null,
119
125
  maxPercent: limit?.maxPercent ?? null,
120
126
  usedPercent,
@@ -162,6 +168,8 @@ export function spendBody(spend: readonly LinkSpend[]) {
162
168
  return spend.map((entry) => ({
163
169
  credential_id: entry.credentialId,
164
170
  spent_usd: entry.spentUsd,
171
+ requests: entry.requests,
172
+ tokens: entry.tokens,
165
173
  monthly_usd: entry.monthlyUsd,
166
174
  max_percent: entry.maxPercent,
167
175
  used_percent: entry.usedPercent,
@@ -105,11 +105,16 @@ const SNAPSHOT_DATE = /-(?:\d{8}|\d{4}-\d{2}-\d{2})$/;
105
105
 
106
106
  /* The model id in `models` a name means: the id itself, the one id it is the
107
107
  bare form of (`claude-haiku-4-5` is `anthropic/claude-haiku-4-5`), or either
108
- of those for a dated snapshot of it. A name two models share means neither. */
108
+ of those for a dated snapshot of it. A name two models share means neither.
109
+ Names match in any case and answer the catalog's own id: some ids carry
110
+ capitals (`deepseek-ai/DeepSeek-V4.1-Flash-1017`), which a lowercased name
111
+ would never equal. */
109
112
  export function catalogModelFor(name: string, models: readonly string[]): string | null {
113
+ const lower = models.map((id) => id.toLowerCase());
110
114
  for (const candidate of new Set([name.toLowerCase(), name.toLowerCase().replace(SNAPSHOT_DATE, "")])) {
111
- if (models.includes(candidate)) return candidate;
112
- const matches = models.filter((id) => id.endsWith(`/${candidate}`));
115
+ const exact = lower.indexOf(candidate);
116
+ if (exact >= 0) return models[exact]!;
117
+ const matches = models.filter((_, i) => lower[i]!.endsWith(`/${candidate}`));
113
118
  if (matches.length === 1) return matches[0]!;
114
119
  }
115
120
  return null;
@@ -334,8 +334,6 @@ export function linkGrants(repo: LinkRepo) {
334
334
  };
335
335
  }
336
336
 
337
- export type LinkGrants = ReturnType<typeof linkGrants>;
338
-
339
337
  export const TOKEN_PREFIX: Record<LinkTokenKind, string> = {
340
338
  access: LINK_ACCESS_TOKEN_PREFIX,
341
339
  child: LINK_CHILD_TOKEN_PREFIX,
@@ -173,7 +173,7 @@ export function linkPlatform(store: LinkStore, users: LinkUsers): LinkPlatform {
173
173
  }> => {
174
174
  const [uses, plans] = await Promise.all([
175
175
  store.budgetUses(grant.id, usesSince(grant.budget, now)),
176
- grant.limits.length === 0 ? [] : users.plansWithIds(grant.credentialIds),
176
+ users.plansWithIds(grant.credentialIds),
177
177
  ]);
178
178
  return {
179
179
  budget: budgetStandings(grant.budget, uses, now).map((standing) => ({
@@ -328,6 +328,9 @@ export type LinkSpend = {
328
328
  credentialId: string;
329
329
  // What the grant spent on it this month: for a plan, at API prices.
330
330
  spentUsd: number;
331
+ // The grant's requests it served this month, and their tokens.
332
+ requests: number;
333
+ tokens: number;
331
334
  monthlyUsd: number | null;
332
335
  maxPercent: number | null;
333
336
  // A plan's most-used plan-wide window, in percent; null when unknown.
@@ -132,6 +132,24 @@ export function museSubscriptionUsage(snapshot: unknown, now: Date): Subscriptio
132
132
  // the billing cycle.
133
133
  const OPENCODE_GO_USAGE_WINDOWS = [["rolling", FIVE_HOURS], ["weekly", ONE_WEEK], ["monthly", 30 * 24 * 60]] as const;
134
134
 
135
+ // Each Token Pass billing period grants $150 of credit; Vercel reports only
136
+ // what remains, so usage is measured against the full grant.
137
+ const TOKEN_PASS_CREDIT_USD = 150;
138
+
139
+ /**
140
+ * The Token Pass usage AI Gateway reports at `GET /v1/credits`:
141
+ * `{token_pass: {remaining, resets_at} | null}`, remaining in USD as a string,
142
+ * or null while Vercel cannot read the balance.
143
+ */
144
+ export function tokenPassUsageFromCredits(credits: unknown, now: Date): SubscriptionUsage | null {
145
+ const pass = isRecord(credits) && isRecord(credits.token_pass) ? credits.token_pass : null;
146
+ if (pass === null || typeof pass.remaining !== "string" || typeof pass.resets_at !== "string") return null;
147
+ return subscriptionUsageFromWindows(
148
+ [{ minutes: 30 * 24 * 60, used: 1 - Number(pass.remaining) / TOKEN_PASS_CREDIT_USD, resetsAt: new Date(pass.resets_at) }],
149
+ now,
150
+ );
151
+ }
152
+
135
153
  /**
136
154
  * The usage OpenCode Go reports at `GET /zen/go/v1/usage`, which OpenCode's
137
155
  * own `/usage` reads: `{usage: {rolling|weekly|monthly: {status: "ok" |
@@ -10,9 +10,9 @@
10
10
  * database file; protect that file like a secret.
11
11
  * - `access.ts`: `freshAccessToken` refreshes a token expiring within five
12
12
  * minutes before handing it out, one refresh per credential at a time.
13
- * - `usage.ts`: `refreshStaleUsage` reads OpenCode Go plan usage from its
14
- * usage endpoint, which its responses never report, when the accounts view
15
- * asks.
13
+ * - `usage.ts`: `refreshStaleUsage` reads OpenCode Go and Vercel Token Pass
14
+ * plan usage from their usage endpoints, which their responses never report,
15
+ * when the accounts view asks.
16
16
  * - `http.ts`: `handleSubscriptionRequest` serves the credential endpoints the
17
17
  * Dari CLI uses to connect, list, rename, release, and disconnect
18
18
  * subscriptions. The caller authenticates the request first.
@@ -1,32 +1,34 @@
1
- import { openCodeGoUsageFromReport } from "../../providers/subscription_limits.js";
1
+ import { openCodeGoUsageFromReport, tokenPassUsageFromCredits } from "../../providers/subscription_limits.js";
2
2
  import { refreshedAccessToken } from "./access.js";
3
3
  import type { OAuthFetch } from "./oauth.js";
4
4
  import type { SubscriptionCredential, SubscriptionStore } from "./store.js";
5
5
 
6
6
  /**
7
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.
8
+ * gateway serves. OpenCode Go and Vercel Token Pass do not: Go reports it from
9
+ * a usage endpoint that takes the plan's workspace, and Token Pass its
10
+ * remaining credit from AI Gateway's credits endpoint. The accounts view reads
11
+ * these again when the last reading is stale.
11
12
  */
12
13
  // A read, failed or not, is not repeated within this interval.
13
14
  const READ_INTERVAL_MS = 60_000;
14
15
  const READ_TIMEOUT_MS = 8_000;
15
16
  const OPENCODE_GO_USAGE_URL = "https://opencode.ai/zen/go/v1/usage";
17
+ const TOKEN_PASS_CREDITS_URL = "https://ai-gateway.vercel.sh/v1/credits";
16
18
 
17
19
  // Reads that recorded nothing (failed, or no running window), so such a plan is
18
20
  // not re-read on every listing. A recorded reading stamps the credential
19
21
  // itself, which a reconnect clears.
20
22
  const unrecordedAt = new Map<string, number>();
21
23
 
22
- /** Read every stale OpenCode Go plan again; a failed read keeps the last one. */
24
+ /** Read every stale OpenCode Go and Token Pass plan again; a failed read keeps the last one. */
23
25
  export async function refreshStaleUsage(
24
26
  store: SubscriptionStore,
25
27
  options: { fetch: OAuthFetch; now?: Date },
26
28
  ): Promise<void> {
27
29
  const now = options.now ?? new Date();
28
30
  const due = (at: number | undefined) => now.getTime() - (at ?? 0) >= READ_INTERVAL_MS;
29
- const stale = store.list("opencode_go").filter((credential) =>
31
+ const stale = [...store.list("opencode_go"), ...store.list("vercel_token_pass")].filter((credential) =>
30
32
  due(credential.usage?.observedAt.getTime()) && due(unrecordedAt.get(credential.id))
31
33
  );
32
34
  await Promise.all(stale.map(async (credential) => {
@@ -45,6 +47,19 @@ async function readUsage(
45
47
  options: { fetch: OAuthFetch; now: Date },
46
48
  ): Promise<void> {
47
49
  const token = await refreshedAccessToken(store, credential, options);
50
+ const usage = credential.provider === "vercel_token_pass"
51
+ ? await readTokenPassUsage(token, options)
52
+ : await readOpenCodeGoUsage(credential, token, options);
53
+ if (usage === null) return;
54
+ unrecordedAt.delete(credential.id);
55
+ store.recordUsage(credential.id, usage, options.now);
56
+ }
57
+
58
+ async function readOpenCodeGoUsage(
59
+ credential: SubscriptionCredential,
60
+ token: string,
61
+ options: { fetch: OAuthFetch; now: Date },
62
+ ) {
48
63
  const response = await options.fetch(OPENCODE_GO_USAGE_URL, {
49
64
  method: "GET",
50
65
  headers: {
@@ -57,8 +72,15 @@ async function readUsage(
57
72
  });
58
73
  // Go answers 403 for a workspace without a Go plan.
59
74
  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);
75
+ return openCodeGoUsageFromReport(await response.json(), options.now);
76
+ }
77
+
78
+ async function readTokenPassUsage(token: string, options: { fetch: OAuthFetch; now: Date }) {
79
+ const response = await options.fetch(TOKEN_PASS_CREDITS_URL, {
80
+ method: "GET",
81
+ headers: { Accept: "application/json", Authorization: `Bearer ${token}`, "User-Agent": "dari-gateway" },
82
+ signal: AbortSignal.timeout(READ_TIMEOUT_MS),
83
+ });
84
+ if (!response.ok) throw new Error(`Token Pass usage read failed with status ${response.status}.`);
85
+ return tokenPassUsageFromCredits(await response.json(), options.now);
64
86
  }
@@ -1,3 +1,4 @@
1
+ import { requestAutoRouterSelection } from "@mupt-ai/dari-router";
1
2
  import { parseSelectorDecision, SELECTOR_LEASE_TURNS } from "@mupt-ai/dari-router/policy-engine";
2
3
  import { HttpError } from "../http/errors.js";
3
4
  import type { SelectorBackend } from "./routing.js";
@@ -7,7 +8,6 @@ export const DARI_AUTO_ROUTING_ENDPOINT = "https://routing.dari.dev/v1/auto-rout
7
8
  // @mupt-ai/dari-router, which calls the same API.
8
9
  const AUTO_ROUTER_MODEL = "dari/auto-router";
9
10
  const AUTO_ROUTER_CONTEXT_WINDOW_CHARS = 32_000;
10
- const AUTO_ROUTER_TIMEOUT_MS = 30_000;
11
11
 
12
12
  /**
13
13
  * Choose among a router's models with Dari Auto Routing, the hosted routing
@@ -23,10 +23,6 @@ export function createAutoRoutingSelectorBackend(config: {
23
23
  if (!apiKey) {
24
24
  throw new Error("Dari Auto Routing needs an API key.");
25
25
  }
26
- const endpoint = (config.endpoint ?? DARI_AUTO_ROUTING_ENDPOINT)
27
- .replace(/\/+$/, "")
28
- .replace(/\/select$/, "");
29
- const fetchImpl = config.fetch ?? fetch;
30
26
  return {
31
27
  selectorModel: AUTO_ROUTER_MODEL,
32
28
  contextWindowChars: async () => AUTO_ROUTER_CONTEXT_WINDOW_CHARS,
@@ -34,28 +30,17 @@ export function createAutoRoutingSelectorBackend(config: {
34
30
  // the policy rather than the runtime's stateless hold.
35
31
  negotiatedLeaseTurns: async () => SELECTOR_LEASE_TURNS,
36
32
  select: async (args) => {
37
- let response: Response;
33
+ let outputText: string;
38
34
  try {
39
- response = await fetchImpl(`${endpoint}/select`, {
40
- method: "POST",
41
- headers: {
42
- Authorization: `Bearer ${apiKey}`,
43
- "Content-Type": "application/json",
44
- },
45
- body: JSON.stringify(args.selectorRequest),
46
- signal: AbortSignal.timeout(AUTO_ROUTER_TIMEOUT_MS),
35
+ outputText = await requestAutoRouterSelection({
36
+ apiKey,
37
+ endpoint: config.endpoint ?? DARI_AUTO_ROUTING_ENDPOINT,
38
+ request: args.selectorRequest,
39
+ fetch: config.fetch,
47
40
  });
48
41
  } catch {
49
42
  throw new HttpError(502, "Dari Auto Routing request failed.", "selector_execution_failed");
50
43
  }
51
- if (!response.ok) {
52
- throw new HttpError(
53
- 502,
54
- `Dari Auto Routing returned HTTP ${response.status}.`,
55
- "selector_execution_failed",
56
- );
57
- }
58
- const outputText = await response.text();
59
44
  return {
60
45
  decision: parseSelectorDecision(outputText).decision,
61
46
  selectorModel: args.selectorModel,
@@ -47,11 +47,6 @@ export function gitEvents(request: InteractionRequest, zdr: boolean): GitEventRe
47
47
  return gitEventsIn(request.items, newlySubmittedToolResults(request).results.map(({ ordinal }) => ordinal));
48
48
  }
49
49
 
50
- /** The GitHub pull requests and pushes in every tool result of a request, as a stored request is read. */
51
- export function allGitEvents(request: InteractionRequest): GitEventReport[] {
52
- return gitEventsIn(request.items, request.items.flatMap((item, ordinal) => (item.type === "tool_result" ? [ordinal] : [])));
53
- }
54
-
55
50
  function gitEventsIn(items: readonly InteractionItem[], resultOrdinals: readonly number[]): GitEventReport[] {
56
51
  const calls = new Map<string, string>();
57
52
  for (const item of items) {