@mupt-ai/dari-gateway 1.0.320 → 1.0.322

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.
@@ -25,6 +25,7 @@ export function linkPlatform(store, users) {
25
25
  httpRedirectHosts: users.httpRedirectHosts ?? [],
26
26
  approval: {
27
27
  sessionSecret: () => users.sessionSecret(),
28
+ ...(users.signIn === undefined ? {} : { signIn: users.signIn }),
28
29
  connectable: users.connectable,
29
30
  keyProviders: users.keyProviders,
30
31
  subscriptions: (subject) => users.plans(subject),
@@ -108,14 +109,9 @@ export function linkPlatform(store, users) {
108
109
  if (apiKey === undefined && !users.openRegistration) {
109
110
  throw new HttpError(401, "Register with a Dari API key, so the app belongs to an organization.", "authentication_error");
110
111
  }
111
- const clientSecret = confidential === true ? linkSecret(LINK_CLIENT_SECRET_PREFIX) : undefined;
112
- const app = {
113
- clientId: `lnk_${randomUUID().replaceAll("-", "")}`,
114
- name,
115
- redirectUris,
116
- confidential: clientSecret !== undefined,
117
- };
118
- await users.registerApp({ ...app, clientSecretHash: clientSecret === undefined ? null : linkHash(clientSecret) }, apiKey);
112
+ const { record, clientSecret } = newLinkApp({ name, redirectUris, confidential: confidential === true });
113
+ await users.registerApp(record, apiKey);
114
+ const { clientSecretHash: _, ...app } = record;
119
115
  return { ...app, ...(clientSecret === undefined ? {} : { clientSecret }) };
120
116
  },
121
117
  async app(clientId) {
@@ -164,6 +160,27 @@ export function linkPlatform(store, users) {
164
160
  },
165
161
  };
166
162
  }
163
+ /**
164
+ * A new app: its client id, and for a confidential one a client secret,
165
+ * returned this once, of which only the hash is kept. Every app is made here,
166
+ * whichever way it registers (hosted Dari's console included).
167
+ */
168
+ export function newLinkApp(request) {
169
+ const secret = request.confidential ? newLinkClientSecret() : null;
170
+ const record = {
171
+ clientId: `lnk_${randomUUID().replaceAll("-", "")}`,
172
+ name: request.name,
173
+ redirectUris: request.redirectUris,
174
+ confidential: secret !== null,
175
+ clientSecretHash: secret?.hash ?? null,
176
+ };
177
+ return { record, ...(secret === null ? {} : { clientSecret: secret.secret }) };
178
+ }
179
+ /** A confidential app's client secret, and the hash that is kept of it. */
180
+ export function newLinkClientSecret() {
181
+ const secret = linkSecret(LINK_CLIENT_SECRET_PREFIX);
182
+ return { secret, hash: linkHash(secret) };
183
+ }
167
184
  /**
168
185
  * The grant a link token serves a request for: null when the key is no link
169
186
  * token. Throws the 401 a dead token gets, and the 424 a grant at its budget
@@ -52,6 +52,7 @@ export declare class SqliteLinkStore implements LinkStore {
52
52
  tokens: LinkTokenIssue[];
53
53
  rotate?: string;
54
54
  now: number;
55
+ forgetBefore: number;
55
56
  }): "ok" | "race" | "revoked";
56
57
  private insertTokens;
57
58
  deleteToken(tokenHash: string): void;
@@ -1,6 +1,5 @@
1
1
  import { randomUUID } from "node:crypto";
2
2
  import { openWithoutKey } from "../self_host/secret_box.js";
3
- import { LINK_TOKEN_RETENTION_MS, } from "./grants.js";
4
3
  // Where a stored API key belongs, which its encryption is bound to.
5
4
  function keyPlace(id) {
6
5
  return `link_api_keys:${id}:api_key`;
@@ -149,10 +148,10 @@ export class SqliteLinkStore {
149
148
  }
150
149
  budgetUses(grantId, since) {
151
150
  return this.db
152
- .query(`SELECT received_at, input_tokens + output_tokens + cache_read_tokens + cache_write_tokens AS tokens
151
+ .query(`SELECT received_at, input_tokens, output_tokens, cache_read_tokens, cache_write_tokens
153
152
  FROM link_usage WHERE grant_id = ? AND received_at > ?`)
154
153
  .all(grantId, since)
155
- .map((row) => ({ at: new Date(row.received_at), tokens: row.tokens }));
154
+ .map((row) => ({ at: new Date(row.received_at), ...tokenCounts(row) }));
156
155
  }
157
156
  /** Record what one of a grant's requests used; a repeated request id is ignored. */
158
157
  recordUsage(entry) {
@@ -185,10 +184,7 @@ export class SqliteLinkStore {
185
184
  model: row.model,
186
185
  thinking: row.thinking,
187
186
  tags: JSON.parse(row.tags),
188
- inputTokens: row.input_tokens,
189
- outputTokens: row.output_tokens,
190
- cacheReadTokens: row.cache_read_tokens,
191
- cacheWriteTokens: row.cache_write_tokens,
187
+ ...tokenCounts(row),
192
188
  }));
193
189
  }
194
190
  addApp(app, now = new Date()) {
@@ -311,10 +307,7 @@ export class SqliteLinkStore {
311
307
  if (rotated === 0)
312
308
  return "race";
313
309
  }
314
- const stale = request.now - LINK_TOKEN_RETENTION_MS;
315
- // Rotated refresh tokens stay while the grant lives (revoking it deletes
316
- // them): presenting one again is how a stolen refresh token is caught.
317
- this.db.run("DELETE FROM link_tokens WHERE expires_at < ? OR (rotated_at < ? AND kind != 'refresh')", [stale, stale]);
310
+ this.db.run("DELETE FROM link_tokens WHERE grant_id = ? AND (expires_at < ? OR (rotated_at < ? AND kind != 'refresh'))", [request.grantId, request.forgetBefore, request.forgetBefore]);
318
311
  this.insertTokens(request.grantId, request.tokens, request.now);
319
312
  return "ok";
320
313
  })();
@@ -351,6 +344,14 @@ export class SqliteLinkStore {
351
344
  return true;
352
345
  }
353
346
  }
347
+ function tokenCounts(row) {
348
+ return {
349
+ inputTokens: row.input_tokens,
350
+ outputTokens: row.output_tokens,
351
+ cacheReadTokens: row.cache_read_tokens,
352
+ cacheWriteTokens: row.cache_write_tokens,
353
+ };
354
+ }
354
355
  // A child token's models. One minted before `pins` existed kept its one model
355
356
  // in `model` and `thinking`.
356
357
  function childPins(row) {
@@ -174,10 +174,11 @@ export type LinkPlatform = {
174
174
  }): Promise<boolean>;
175
175
  };
176
176
  /**
177
- * What the gateway's approval and connections pages need. The pages need no
178
- * account: a user connects a plan by signing in to its provider, and the
179
- * gateway remembers them in a signed cookie as a subject, so their plans are
180
- * there the next time an app asks and they manage their connections there.
177
+ * What the gateway's approval and connections pages need. The gateway
178
+ * remembers the user in a signed cookie as a subject, so their plans are there
179
+ * the next time an app asks and they manage their connections there. With
180
+ * `signIn` the subject is the account they signed in with; without it the
181
+ * pages need no account, and a user's first plan makes their subject.
181
182
  */
182
183
  export type LinkApprovalPage = {
183
184
  /**
@@ -185,6 +186,11 @@ export type LinkApprovalPage = {
185
186
  * `link_not_configured`) when the platform has none.
186
187
  */
187
188
  sessionSecret(): string;
189
+ /**
190
+ * Set on a platform whose users have accounts: the page then acts only for
191
+ * a user who signed in with one, so their plans follow them to any browser.
192
+ */
193
+ signIn?: LinkSignIn;
188
194
  /** The kinds of plan a user can connect on the page, in the order offered. */
189
195
  connectable: readonly SubscriptionKind[];
190
196
  /** The providers and gateways a user can add an API key for, in the order offered. */
@@ -229,6 +235,21 @@ export type LinkApprovalPage = {
229
235
  /** Replace one of the user's grants' budget (empty removes it); false when they have none by that id. */
230
236
  setBudget(subject: string, grantId: string, budget: LinkBudget[]): Promise<boolean>;
231
237
  };
238
+ /**
239
+ * The platform's own sign-in. The page sends the user to `url()` with `state`
240
+ * and `next`; the platform signs them in and returns them to
241
+ * `/v1/link/session` with the same `next` and a ticket for that state.
242
+ */
243
+ export type LinkSignIn = {
244
+ /** Throws HttpError(503, `link_not_configured`) when the platform has none. */
245
+ url(): string;
246
+ /** Who a ticket signed in, for which state, and when (epoch ms); null for no ticket. */
247
+ redeem(ticket: string): Promise<{
248
+ subject: string;
249
+ state: string;
250
+ issuedAt: number;
251
+ } | null>;
252
+ };
232
253
  /** A plan or API key the user added, and who they are now. */
233
254
  export type LinkPlanAdded = {
234
255
  subject: string;
@@ -18,7 +18,7 @@ const ANTHROPIC_ROUTER_MODELS = new Set([CANONICAL_ROUTER_MODEL, ...ANTHROPIC_RO
18
18
  request leaves the client (wire-captured live: Task spawns emit
19
19
  `claude-opus-5` even when the session model is dari/routing), so concrete
20
20
  Claude-family ids are synonyms too — both bare (`claude-opus-5`) and
21
- provider-prefixed (`anthropic/claude-opus-5`) forms. `dari claude --setup`
21
+ provider-prefixed (`anthropic/claude-opus-5`) forms. `dari claude --setup-desktop`
22
22
  relies on this: the Claude app lists routing as `claude-dari-routing`. */
23
23
  const ANTHROPIC_MODEL_ID_PATTERN = /^(anthropic\/)?claude-[a-z0-9][a-z0-9.-]*$/i;
24
24
  export function isAnthropicRouterModel(model) {
@@ -1,4 +1,5 @@
1
1
  import { isReasoningEffort, isRecord } from "@mupt-ai/dari-router/policy-engine";
2
+ import { isBackgroundRequest } from "../interaction/types.js";
2
3
  import { requiredCapabilitiesFor } from "../interaction/capabilities.js";
3
4
  import { toolWireName, toolsByWireName } from "../interaction/tool_identity.js";
4
5
  import { gatewayFor, payloadWithGatewayFields } from "../models/gateways.js";
@@ -95,6 +96,10 @@ export function buildOptions(request, auth, selectedModel, model, pi, sessionId,
95
96
  const webSearch = anthropicWebSearchFor(request, model);
96
97
  if (webSearch !== undefined) {
97
98
  patches.push((payload) => payloadWithWebSearchTool(payload, webSearch));
99
+ // A background search is one request whose results are read once. Like
100
+ // Claude Code against Anthropic directly, send it without prompt caching.
101
+ if (isBackgroundRequest(request))
102
+ options.cacheRetention = "none";
98
103
  }
99
104
  // Pi keeps only the content it models, so native compaction output reaches
100
105
  // the client from the provider's own output items.
@@ -2,10 +2,10 @@ import { timingSafeEqual } from "node:crypto";
2
2
  import { isReasoningEffort, nativeModelId, providerForModel, } from "@mupt-ai/dari-router/policy-engine";
3
3
  import { HttpError } from "../http/errors.js";
4
4
  import { DEFAULT_ROUTER_ALIAS } from "../platform/routing_contract.js";
5
- import { codexModelConfig, subscriptionClient, subscriptionModelProvider } from "../models/subscriptions.js";
5
+ import { codexModelConfig, subscriptionModelProvider } from "../models/subscriptions.js";
6
6
  import { CANONICAL_MODELS } from "../models/canonical.js";
7
7
  import { gatewayFor } from "../models/gateways.js";
8
- import { linkGrantUnavailableError, modelNotServed, plansExhausted, plansForAnotherClient, } from "../link/errors.js";
8
+ import { linkNothingServed, plansExhausted, providersUnavailable } from "../link/errors.js";
9
9
  import { registeredModelPrice } from "../providers/pi.js";
10
10
  import { allRouterModels, routerModelsFor, } from "./config.js";
11
11
  import { linkTokenGrant } from "../link/service.js";
@@ -87,9 +87,10 @@ export async function resolveSelfHostedRouter(deps, request) {
87
87
  // A model-specific hold tries the pool's other plans before removing the
88
88
  // model. Its provider's active plan and conversation pin stay unchanged.
89
89
  const modelCredentials = {};
90
+ // A provider the request wanted that no granted plan served.
90
91
  const linkUnavailable = grant === null
91
92
  ? {}
92
- : grantUnavailable(granted, credentials, request.clientHarness, now);
93
+ : providersUnavailable(granted.map((credential) => ({ kind: credential.provider, unavailableUntil: credential.unavailableUntil })), [...credentials].filter(([, credential]) => credential === null).map(([provider]) => provider), request.clientHarness, now);
93
94
  const models = [];
94
95
  for (const model of listed) {
95
96
  const credential = credentials.get(providerForModel(model.id));
@@ -120,11 +121,8 @@ export async function resolveSelfHostedRouter(deps, request) {
120
121
  // A grant with a gateway key serves the gateway's models by name, listed or not.
121
122
  const gatewayKeyed = [...grantedKeys.keys()].some((provider) => gatewayFor(provider) !== undefined);
122
123
  if (models.length === 0 && !gatewayKeyed) {
123
- if (grant !== null) {
124
- throw grant.pins?.length === 1
125
- ? modelNotServed({ link_unavailable: linkUnavailable }, grant.pins[0].model)
126
- : linkGrantUnavailableError(linkUnavailable);
127
- }
124
+ if (grant !== null)
125
+ throw linkNothingServed(linkUnavailable, grant.pins);
128
126
  const missing = [...credentials].filter(([, credential]) => credential == null).map(([provider]) => provider);
129
127
  throw unavailableRouterError(request.routerId, exhausted, missing);
130
128
  }
@@ -241,30 +239,6 @@ function grantModels(grant, routed, granted, grantedKeys) {
241
239
  const pinned = new Set(grant.pins.map((pin) => pin.model));
242
240
  return models.filter((model) => pinned.has(model.id)).map((model) => ({ id: model.id }));
243
241
  }
244
- /**
245
- * Why each provider with a granted plan serves nothing now: its plans serve
246
- * only another client, or are all at their usage limits.
247
- */
248
- function grantUnavailable(granted, credentials, clientHarness, now) {
249
- const unavailable = {};
250
- for (const provider of new Set(granted.map((credential) => subscriptionModelProvider(credential.provider)))) {
251
- // Only a provider the request wanted and no plan served.
252
- if (credentials.get(provider) !== null)
253
- continue;
254
- const plans = granted.filter((credential) => subscriptionModelProvider(credential.provider) === provider);
255
- const usable = plans.filter((credential) => {
256
- const client = subscriptionClient(credential.provider);
257
- return client === undefined || client === clientHarness;
258
- });
259
- if (usable.length === 0) {
260
- unavailable[provider] = plansForAnotherClient(plans.map((credential) => credential.provider));
261
- continue;
262
- }
263
- const held = usable.flatMap((credential) => credential.unavailableUntil !== null && credential.unavailableUntil > now ? [credential.unavailableUntil] : []);
264
- unavailable[provider] = plansExhausted(usable.map((credential) => credential.provider), held.length === usable.length ? new Date(Math.min(...held.map((date) => date.getTime()))) : null);
265
- }
266
- return unavailable;
267
- }
268
242
  // Configured endpoints read their own key variable, or send a placeholder
269
243
  // when they take none; known providers use their standard variable.
270
244
  export async function configuredProviderApiKey(deps, provider) {
@@ -151,13 +151,59 @@ async function completeSession(deps, body, now) {
151
151
  function summary(store, credential, now) {
152
152
  return credentialBody(credential, store.activeCredential(credential.provider, now)?.id === credential.id, now);
153
153
  }
154
- /** The fields the CLI reads from a credential, never its tokens. */
154
+ const FIVE_HOURS = 5 * 60;
155
+ const ONE_WEEK = 7 * 24 * 60;
156
+ const ONE_MONTH = 30 * 24 * 60;
157
+ // A model family's own window is named for the family's catalog models.
158
+ const MODEL_FAMILY_NAMES = { fable: "Claude Fable" };
159
+ /** What to call a window: 5 Hour, Weekly, Monthly, Claude Fable Weekly. */
160
+ function usageWindowLabel(window) {
161
+ const minutes = window.minutes;
162
+ const length = minutes === ONE_WEEK ? "Weekly"
163
+ : minutes === ONE_MONTH ? "Monthly"
164
+ : minutes % (24 * 60) === 0 ? `${minutes / (24 * 60)} Day`
165
+ : minutes % 60 === 0 ? `${minutes / 60} Hour`
166
+ : `${minutes} Minute`;
167
+ return window.modelFamily === undefined ? length : `${MODEL_FAMILY_NAMES[window.modelFamily]} ${length}`;
168
+ }
169
+ /**
170
+ * The usage to show, as the hosted API shows it: every running window, a
171
+ * held plan's window full. A hold ends when the window that ran out resets,
172
+ * so the shared window resetting with it shows full. Usage reported without
173
+ * per-window detail, and holds without a matching window, are named by how
174
+ * far off their reset is: only a weekly or monthly window resets more than
175
+ * five hours out, and only OpenCode Go's monthly one more than a week.
176
+ */
155
177
  function usageBody(credential, now) {
178
+ const inferred = (resetsAt) => {
179
+ const left = resetsAt.getTime() - now.getTime();
180
+ if (left > ONE_WEEK * 60_000)
181
+ return ONE_MONTH;
182
+ return left > FIVE_HOURS * 60_000 ? ONE_WEEK : FIVE_HOURS;
183
+ };
156
184
  const usage = currentUsage(credential, now);
157
- return usage === null ? null : {
158
- utilization: usage.utilization,
159
- resets_at: usage.resetsAt.toISOString(),
160
- windows: usage.windows.map((window) => ({
185
+ let windows = usage === null ? []
186
+ : usage.windows.length > 0 ? usage.windows
187
+ : [{ minutes: inferred(usage.resetsAt), utilization: usage.utilization, resetsAt: usage.resetsAt }];
188
+ if (isHeld(credential, now)) {
189
+ const held = credential.unavailableUntil;
190
+ const gap = (window) => Math.abs(window.resetsAt.getTime() - held.getTime());
191
+ // The hold is the plan's; it never fills a model family's window.
192
+ const closest = windows.filter((window) => window.modelFamily === undefined)
193
+ .reduce((best, window) => best === null || gap(window) < gap(best) ? window : best, null);
194
+ const minutes = closest !== null && gap(closest) < 15 * 60_000 ? closest.minutes : inferred(held);
195
+ windows = [
196
+ ...windows.filter((window) => window.modelFamily !== undefined || window.minutes !== minutes),
197
+ { minutes, utilization: 1, resetsAt: held },
198
+ ].sort((a, b) => a.minutes - b.minutes || (a.modelFamily ?? "").localeCompare(b.modelFamily ?? ""));
199
+ }
200
+ if (windows.length === 0)
201
+ return null;
202
+ return {
203
+ utilization: usage?.utilization ?? 1,
204
+ resets_at: (usage?.resetsAt ?? windows[0].resetsAt).toISOString(),
205
+ windows: windows.map((window) => ({
206
+ label: usageWindowLabel(window),
161
207
  ...(window.modelFamily === undefined ? {} : { model_family: window.modelFamily }),
162
208
  minutes: window.minutes,
163
209
  utilization: window.utilization,
@@ -188,8 +234,8 @@ function credentialBody(credential, active, now) {
188
234
  reason: hold.reason,
189
235
  })),
190
236
  subscription_active: active,
191
- // The share of its tightest window the plan last reported used, while
192
- // that window has not reset; null when it reports none.
237
+ // The share of its tightest window the plan last reported used, and
238
+ // every window as shown; null when it reports none and is not held.
193
239
  usage: usageBody(credential, now),
194
240
  // Spending banked limit resets is hosted-only.
195
241
  auto_redeem_resets: false,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mupt-ai/dari-gateway",
3
- "version": "1.0.320",
3
+ "version": "1.0.322",
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.320",
55
+ "@mupt-ai/dari-router": "1.0.322",
56
56
  "@mupt-ai/pi-ai": "1.5.2-mupt.1"
57
57
  },
58
58
  "devDependencies": {
@@ -10,13 +10,21 @@
10
10
  A window at its cap is back once enough of its oldest requests roll off to
11
11
  bring it under the cap again: `resetsAt` is when that happens. */
12
12
 
13
- import type { LinkBudget } from "../platform/platform.js";
13
+ import type { LinkBudget, LinkUsageTotals } from "../platform/platform.js";
14
14
 
15
15
  /** The windows a budget can cap: five hours and one week. */
16
16
  export const LINK_BUDGET_WINDOW_MINUTES = [300, 10080] as const;
17
17
 
18
+ /** The tokens a request used, as each kind is recorded. */
19
+ export type LinkTokenCounts = Pick<LinkUsageTotals, "inputTokens" | "outputTokens" | "cacheReadTokens" | "cacheWriteTokens">;
20
+
21
+ /** What a budget counts, and Connected Apps shows: every token, of every kind. */
22
+ export function linkTokens(counts: LinkTokenCounts): number {
23
+ return counts.inputTokens + counts.outputTokens + counts.cacheReadTokens + counts.cacheWriteTokens;
24
+ }
25
+
18
26
  /** Tokens one of a grant's requests used, and when it was received. */
19
- export type BudgetUse = { at: Date; tokens: number };
27
+ export type BudgetUse = LinkTokenCounts & { at: Date };
20
28
 
21
29
  /** A budget window as it stands for a grant; `resetsAt` is set only at the cap. */
22
30
  export type BudgetStanding = { windowMinutes: number; maxTokens: number; usedTokens: number; resetsAt: Date | null };
@@ -28,12 +36,12 @@ export function budgetStandings(budget: readonly LinkBudget[], uses: readonly Bu
28
36
  const live = uses
29
37
  .filter((use) => use.at.getTime() > now.getTime() - windowMs)
30
38
  .sort((a, b) => a.at.getTime() - b.at.getTime());
31
- const usedTokens = live.reduce((sum, use) => sum + use.tokens, 0);
39
+ const usedTokens = live.reduce((sum, use) => sum + linkTokens(use), 0);
32
40
  let resetsAt: Date | null = null;
33
41
  let remaining = usedTokens;
34
42
  for (const use of live) {
35
43
  if (remaining < entry.maxTokens) break;
36
- remaining -= use.tokens;
44
+ remaining -= linkTokens(use);
37
45
  resetsAt = new Date(use.at.getTime() + windowMs);
38
46
  }
39
47
  return { windowMinutes: entry.windowMinutes, maxTokens: entry.maxTokens, usedTokens, resetsAt };