@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.
@@ -176,10 +176,11 @@ export type LinkPlatform = {
176
176
  };
177
177
 
178
178
  /**
179
- * What the gateway's approval and connections pages need. The pages need no
180
- * account: a user connects a plan by signing in to its provider, and the
181
- * gateway remembers them in a signed cookie as a subject, so their plans are
182
- * there the next time an app asks and they manage their connections there.
179
+ * What the gateway's approval and connections pages need. The gateway
180
+ * remembers the user in a signed cookie as a subject, so their plans are there
181
+ * the next time an app asks and they manage their connections there. With
182
+ * `signIn` the subject is the account they signed in with; without it the
183
+ * pages need no account, and a user's first plan makes their subject.
183
184
  */
184
185
  export type LinkApprovalPage = {
185
186
  /**
@@ -187,6 +188,11 @@ export type LinkApprovalPage = {
187
188
  * `link_not_configured`) when the platform has none.
188
189
  */
189
190
  sessionSecret(): string;
191
+ /**
192
+ * Set on a platform whose users have accounts: the page then acts only for
193
+ * a user who signed in with one, so their plans follow them to any browser.
194
+ */
195
+ signIn?: LinkSignIn;
190
196
  /** The kinds of plan a user can connect on the page, in the order offered. */
191
197
  connectable: readonly SubscriptionKind[];
192
198
  /** The providers and gateways a user can add an API key for, in the order offered. */
@@ -230,6 +236,18 @@ export type LinkApprovalPage = {
230
236
  setBudget(subject: string, grantId: string, budget: LinkBudget[]): Promise<boolean>;
231
237
  };
232
238
 
239
+ /**
240
+ * The platform's own sign-in. The page sends the user to `url()` with `state`
241
+ * and `next`; the platform signs them in and returns them to
242
+ * `/v1/link/session` with the same `next` and a ticket for that state.
243
+ */
244
+ export type LinkSignIn = {
245
+ /** Throws HttpError(503, `link_not_configured`) when the platform has none. */
246
+ url(): string;
247
+ /** Who a ticket signed in, for which state, and when (epoch ms); null for no ticket. */
248
+ redeem(ticket: string): Promise<{ subject: string; state: string; issuedAt: number } | null>;
249
+ };
250
+
233
251
  /** A plan or API key the user added, and who they are now. */
234
252
  export type LinkPlanAdded = { subject: string; credentialId: string };
235
253
 
@@ -22,7 +22,7 @@ const ANTHROPIC_ROUTER_MODELS = new Set<string>([CANONICAL_ROUTER_MODEL, ...ANTH
22
22
  request leaves the client (wire-captured live: Task spawns emit
23
23
  `claude-opus-5` even when the session model is dari/routing), so concrete
24
24
  Claude-family ids are synonyms too — both bare (`claude-opus-5`) and
25
- provider-prefixed (`anthropic/claude-opus-5`) forms. `dari claude --setup`
25
+ provider-prefixed (`anthropic/claude-opus-5`) forms. `dari claude --setup-desktop`
26
26
  relies on this: the Claude app lists routing as `claude-dari-routing`. */
27
27
  const ANTHROPIC_MODEL_ID_PATTERN = /^(anthropic\/)?claude-[a-z0-9][a-z0-9.-]*$/i;
28
28
 
@@ -1,5 +1,6 @@
1
1
  import type { BedrockOptions } from "@mupt-ai/pi-ai/api/bedrock-converse-stream";
2
2
  import { isReasoningEffort, isRecord, type ReasoningEffort } from "@mupt-ai/dari-router/policy-engine";
3
+ import { isBackgroundRequest } from "../interaction/types.js";
3
4
  import type { InteractionRequest, InteractionResponseFormat, InteractionToolChoice } from "../interaction/types.js";
4
5
  import { requiredCapabilitiesFor } from "../interaction/capabilities.js";
5
6
  import { toolWireName, toolsByWireName } from "../interaction/tool_identity.js";
@@ -127,6 +128,9 @@ export function buildOptions(
127
128
  const webSearch = anthropicWebSearchFor(request, model);
128
129
  if (webSearch !== undefined) {
129
130
  patches.push((payload) => payloadWithWebSearchTool(payload, webSearch));
131
+ // A background search is one request whose results are read once. Like
132
+ // Claude Code against Anthropic directly, send it without prompt caching.
133
+ if (isBackgroundRequest(request)) options.cacheRetention = "none";
130
134
  }
131
135
 
132
136
  // Pi keeps only the content it models, so native compaction output reaches
@@ -10,15 +10,10 @@ import {
10
10
  import { HttpError } from "../http/errors.js";
11
11
  import type { ResolveRouterRequest } from "../platform/platform.js";
12
12
  import { DEFAULT_ROUTER_ALIAS } from "../platform/routing_contract.js";
13
- import { codexModelConfig, subscriptionClient, subscriptionModelProvider } from "../models/subscriptions.js";
13
+ import { codexModelConfig, subscriptionModelProvider } from "../models/subscriptions.js";
14
14
  import { CANONICAL_MODELS } from "../models/canonical.js";
15
15
  import { gatewayFor } from "../models/gateways.js";
16
- import {
17
- linkGrantUnavailableError,
18
- modelNotServed,
19
- plansExhausted,
20
- plansForAnotherClient,
21
- } from "../link/errors.js";
16
+ import { linkNothingServed, plansExhausted, providersUnavailable } from "../link/errors.js";
22
17
  import { registeredModelPrice } from "../providers/pi.js";
23
18
  import type { LinkUnavailable, ProviderCredential as SuppliedProviderCredential, ProviderKeySource, ResolvedRouter } from "../types.js";
24
19
  import {
@@ -152,9 +147,15 @@ export async function resolveSelfHostedRouter(
152
147
  // A model-specific hold tries the pool's other plans before removing the
153
148
  // model. Its provider's active plan and conversation pin stay unchanged.
154
149
  const modelCredentials: Record<string, SuppliedProviderCredential> = {};
150
+ // A provider the request wanted that no granted plan served.
155
151
  const linkUnavailable = grant === null
156
152
  ? {}
157
- : grantUnavailable(granted, credentials, request.clientHarness, now);
153
+ : providersUnavailable(
154
+ granted.map((credential) => ({ kind: credential.provider, unavailableUntil: credential.unavailableUntil })),
155
+ [...credentials].filter(([, credential]) => credential === null).map(([provider]) => provider),
156
+ request.clientHarness,
157
+ now,
158
+ );
158
159
  const models = [];
159
160
  for (const model of listed) {
160
161
  const credential = credentials.get(providerForModel(model.id));
@@ -185,11 +186,7 @@ export async function resolveSelfHostedRouter(
185
186
  // A grant with a gateway key serves the gateway's models by name, listed or not.
186
187
  const gatewayKeyed = [...grantedKeys.keys()].some((provider) => gatewayFor(provider) !== undefined);
187
188
  if (models.length === 0 && !gatewayKeyed) {
188
- if (grant !== null) {
189
- throw grant.pins?.length === 1
190
- ? modelNotServed({ link_unavailable: linkUnavailable }, grant.pins[0]!.model)
191
- : linkGrantUnavailableError(linkUnavailable);
192
- }
189
+ if (grant !== null) throw linkNothingServed(linkUnavailable, grant.pins);
193
190
  const missing = [...credentials].filter(([, credential]) => credential == null).map(([provider]) => provider);
194
191
  throw unavailableRouterError(request.routerId, exhausted, missing);
195
192
  }
@@ -312,40 +309,6 @@ function grantModels(
312
309
  return models.filter((model) => pinned.has(model.id)).map((model) => ({ id: model.id }));
313
310
  }
314
311
 
315
- /**
316
- * Why each provider with a granted plan serves nothing now: its plans serve
317
- * only another client, or are all at their usage limits.
318
- */
319
- function grantUnavailable(
320
- granted: readonly SubscriptionCredential[],
321
- credentials: ReadonlyMap<string, ProviderCredential | null>,
322
- clientHarness: ResolveRouterRequest["clientHarness"],
323
- now: Date,
324
- ): Record<string, LinkUnavailable> {
325
- const unavailable: Record<string, LinkUnavailable> = {};
326
- for (const provider of new Set(granted.map((credential) => subscriptionModelProvider(credential.provider)))) {
327
- // Only a provider the request wanted and no plan served.
328
- if (credentials.get(provider) !== null) continue;
329
- const plans = granted.filter((credential) => subscriptionModelProvider(credential.provider) === provider);
330
- const usable = plans.filter((credential) => {
331
- const client = subscriptionClient(credential.provider);
332
- return client === undefined || client === clientHarness;
333
- });
334
- if (usable.length === 0) {
335
- unavailable[provider] = plansForAnotherClient(plans.map((credential) => credential.provider));
336
- continue;
337
- }
338
- const held = usable.flatMap((credential) =>
339
- credential.unavailableUntil !== null && credential.unavailableUntil > now ? [credential.unavailableUntil] : []
340
- );
341
- unavailable[provider] = plansExhausted(
342
- usable.map((credential) => credential.provider),
343
- held.length === usable.length ? new Date(Math.min(...held.map((date) => date.getTime()))) : null,
344
- );
345
- }
346
- return unavailable;
347
- }
348
-
349
312
  // Configured endpoints read their own key variable, or send a placeholder
350
313
  // when they take none; known providers use their standard variable.
351
314
  export async function configuredProviderApiKey(
@@ -14,6 +14,7 @@ import {
14
14
  type SubscriptionProvider,
15
15
  } from "./oauth.js";
16
16
  import { canonicalModelName } from "../../models/canonical.js";
17
+ import type { SubscriptionUsageWindow } from "../../providers/subscription_limits.js";
17
18
  import {
18
19
  activeModelHolds,
19
20
  currentUsage,
@@ -174,13 +175,60 @@ function summary(store: SubscriptionStore, credential: SubscriptionCredential, n
174
175
  return credentialBody(credential, store.activeCredential(credential.provider, now)?.id === credential.id, now);
175
176
  }
176
177
 
177
- /** The fields the CLI reads from a credential, never its tokens. */
178
+ const FIVE_HOURS = 5 * 60;
179
+ const ONE_WEEK = 7 * 24 * 60;
180
+ const ONE_MONTH = 30 * 24 * 60;
181
+
182
+ // A model family's own window is named for the family's catalog models.
183
+ const MODEL_FAMILY_NAMES = { fable: "Claude Fable" } as const;
184
+
185
+ /** What to call a window: 5 Hour, Weekly, Monthly, Claude Fable Weekly. */
186
+ function usageWindowLabel(window: SubscriptionUsageWindow): string {
187
+ const minutes = window.minutes;
188
+ const length = minutes === ONE_WEEK ? "Weekly"
189
+ : minutes === ONE_MONTH ? "Monthly"
190
+ : minutes % (24 * 60) === 0 ? `${minutes / (24 * 60)} Day`
191
+ : minutes % 60 === 0 ? `${minutes / 60} Hour`
192
+ : `${minutes} Minute`;
193
+ return window.modelFamily === undefined ? length : `${MODEL_FAMILY_NAMES[window.modelFamily]} ${length}`;
194
+ }
195
+
196
+ /**
197
+ * The usage to show, as the hosted API shows it: every running window, a
198
+ * held plan's window full. A hold ends when the window that ran out resets,
199
+ * so the shared window resetting with it shows full. Usage reported without
200
+ * per-window detail, and holds without a matching window, are named by how
201
+ * far off their reset is: only a weekly or monthly window resets more than
202
+ * five hours out, and only OpenCode Go's monthly one more than a week.
203
+ */
178
204
  function usageBody(credential: SubscriptionCredential, now: Date) {
205
+ const inferred = (resetsAt: Date) => {
206
+ const left = resetsAt.getTime() - now.getTime();
207
+ if (left > ONE_WEEK * 60_000) return ONE_MONTH;
208
+ return left > FIVE_HOURS * 60_000 ? ONE_WEEK : FIVE_HOURS;
209
+ };
179
210
  const usage = currentUsage(credential, now);
180
- return usage === null ? null : {
181
- utilization: usage.utilization,
182
- resets_at: usage.resetsAt.toISOString(),
183
- windows: usage.windows.map((window) => ({
211
+ let windows: SubscriptionUsageWindow[] = usage === null ? []
212
+ : usage.windows.length > 0 ? usage.windows
213
+ : [{ minutes: inferred(usage.resetsAt), utilization: usage.utilization, resetsAt: usage.resetsAt }];
214
+ if (isHeld(credential, now)) {
215
+ const held = credential.unavailableUntil!;
216
+ const gap = (window: SubscriptionUsageWindow) => Math.abs(window.resetsAt.getTime() - held.getTime());
217
+ // The hold is the plan's; it never fills a model family's window.
218
+ const closest = windows.filter((window) => window.modelFamily === undefined)
219
+ .reduce<SubscriptionUsageWindow | null>((best, window) => best === null || gap(window) < gap(best) ? window : best, null);
220
+ const minutes = closest !== null && gap(closest) < 15 * 60_000 ? closest.minutes : inferred(held);
221
+ windows = [
222
+ ...windows.filter((window) => window.modelFamily !== undefined || window.minutes !== minutes),
223
+ { minutes, utilization: 1, resetsAt: held },
224
+ ].sort((a, b) => a.minutes - b.minutes || (a.modelFamily ?? "").localeCompare(b.modelFamily ?? ""));
225
+ }
226
+ if (windows.length === 0) return null;
227
+ return {
228
+ utilization: usage?.utilization ?? 1,
229
+ resets_at: (usage?.resetsAt ?? windows[0]!.resetsAt).toISOString(),
230
+ windows: windows.map((window) => ({
231
+ label: usageWindowLabel(window),
184
232
  ...(window.modelFamily === undefined ? {} : { model_family: window.modelFamily }),
185
233
  minutes: window.minutes,
186
234
  utilization: window.utilization,
@@ -212,8 +260,8 @@ function credentialBody(credential: SubscriptionCredential, active: boolean, now
212
260
  reason: hold.reason,
213
261
  })),
214
262
  subscription_active: active,
215
- // The share of its tightest window the plan last reported used, while
216
- // that window has not reset; null when it reports none.
263
+ // The share of its tightest window the plan last reported used, and
264
+ // every window as shown; null when it reports none and is not held.
217
265
  usage: usageBody(credential, now),
218
266
  // Spending banked limit resets is hosted-only.
219
267
  auto_redeem_resets: false,