@mupt-ai/dari-gateway 1.0.323 → 1.0.325

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.
@@ -968,7 +968,7 @@ async function authorizeSubmit(link, request, form) {
968
968
  if (decision === "deny")
969
969
  return redirect(back, { error: "access_denied" }, [endConnect]);
970
970
  if (decision === "sign_out")
971
- return seeAuthorize(authorize, signOutCookies(request));
971
+ return signOut(request, approval, `${AUTHORIZE_PATH}?${authorizeQuery(authorize)}`);
972
972
  if (decision === "select")
973
973
  return selectPage(approval, authorize, undefined, [endConnect]);
974
974
  if (decision === "connect") {
@@ -1012,16 +1012,6 @@ async function authorizeSubmit(link, request, form) {
1012
1012
  if (decision === "complete" && connect !== null) {
1013
1013
  return await finishConnect(approval, request, authorize, session, connect, form.get("authorization_response")?.trim() ?? "");
1014
1014
  }
1015
- // Removing a plan or key asks once, then deletes what Dari stored for it.
1016
- const removing = form.get("remove") ?? form.get("remove_id");
1017
- if (removing !== null && session !== null) {
1018
- const subscription = (await approval.subscriptions(session.subject)).find((candidate) => candidate.id === removing);
1019
- if (subscription !== undefined && decision !== "remove")
1020
- return removePage(authorize, session, subscription);
1021
- if (subscription !== undefined && sameText(form.get("csrf") ?? "", session.csrf))
1022
- await approval.remove(session.subject, removing);
1023
- return seeAuthorize(authorize, [endConnect]);
1024
- }
1025
1015
  // Anything else goes back to where the user stands.
1026
1016
  if (decision !== "approve" || session === null)
1027
1017
  return seeAuthorize(authorize, [endConnect]);
@@ -1141,12 +1131,8 @@ async function connectionsSubmit(approval, request, form) {
1141
1131
  if (session === null || !sameText(form.get("csrf") ?? "", session.csrf))
1142
1132
  return back;
1143
1133
  const decision = form.get("decision");
1144
- if (decision === "sign_out") {
1145
- const headers = new Headers({ Location: CONNECTIONS_PATH, "Cache-Control": "no-store" });
1146
- for (const cookie of signOutCookies(request))
1147
- headers.append("Set-Cookie", cookie);
1148
- return new Response(null, { status: 303, headers });
1149
- }
1134
+ if (decision === "sign_out")
1135
+ return signOut(request, approval, CONNECTIONS_PATH);
1150
1136
  const grantId = form.get("grant_id") ?? "";
1151
1137
  if (decision === "disconnect") {
1152
1138
  await approval.disconnect(session.subject, grantId);
@@ -1312,9 +1298,20 @@ function userCookie(request, approval, subject) {
1312
1298
  ? signedCookie(request, approval.sessionSecret(), USER_COOKIE, { sub: subject }, USER_SECONDS)
1313
1299
  : signedCookie(request, approval.sessionSecret(), USER_COOKIE, { sub: subject, account: true }, ACCOUNT_SECONDS);
1314
1300
  }
1315
- // Signing out leaves nothing of the user's: not who they are, nor a provider sign-in under way.
1316
- function signOutCookies(request) {
1317
- return [clearCookie(request, USER_COOKIE), clearCookie(request, CONNECT_COOKIE)];
1301
+ // Signing out leaves nothing of the user's: not who they are, nor a provider
1302
+ // sign-in under way. A platform with accounts ends its own sign-in too, then
1303
+ // returns the user to `next`, so the next sign-in can be another account.
1304
+ function signOut(request, approval, next) {
1305
+ let location = next;
1306
+ if (approval.signIn !== undefined) {
1307
+ const url = new URL(approval.signIn.signOutUrl());
1308
+ url.searchParams.set("next", next);
1309
+ location = url.toString();
1310
+ }
1311
+ const headers = new Headers({ Location: location, "Cache-Control": "no-store" });
1312
+ headers.append("Set-Cookie", clearCookie(request, USER_COOKIE));
1313
+ headers.append("Set-Cookie", clearCookie(request, CONNECT_COOKIE));
1314
+ return new Response(null, { status: 303, headers });
1318
1315
  }
1319
1316
  function clearCookie(request, cookie) {
1320
1317
  return `${cookie}=; Path=${COOKIE_PATH}; Max-Age=0; HttpOnly; SameSite=Lax${isHttps(request) ? "; Secure" : ""}`;
@@ -1478,48 +1475,38 @@ function choosePage(authorize, session, subscriptions, current, error) {
1478
1475
  body: `<h1>${current === null ? `Share With ${app}` : `Update Plans For ${app}`}</h1>
1479
1476
  <input type="hidden" name="csrf" value="${session.csrf}">
1480
1477
  ${plans.map((plan) => planOption(authorize, plan, ticked.has(plan.id))).join("\n")}
1481
- <button class="btn ghost" type="submit" name="decision" value="select" formnovalidate>${ICONS.plus}Connect Another</button>
1482
- ${session.account ? SIGN_OUT : ""}`,
1478
+ <div class="actions"><button class="btn ghost" type="submit" name="decision" value="select" formnovalidate>${ICONS.plus}Connect Another</button><span><a class="btn ghost" href="${CONNECTIONS_PATH}" target="_blank" rel="noopener">Manage</a>${session.account ? SIGN_OUT : ""}</span></div>`,
1483
1479
  footer: `<button class="btn primary" type="submit" name="decision" value="approve">${current === null ? "Allow" : "Save"}</button>
1484
1480
  <p class="fine">${app} keeps access until you or it disconnect. Its requests fail while a plan is at its usage limit.</p>`,
1485
1481
  });
1486
1482
  }
1487
- // What the user is about to delete, and the one button that deletes it.
1488
- function removePage(authorize, session, subscription) {
1489
- const key = subscription.apiKeyProvider;
1490
- const name = key === undefined ? KINDS[subscription.provider]?.name ?? subscription.name : subscription.name;
1491
- return pane(authorize, {
1492
- title: `Remove ${name}`,
1493
- step: "choose_plans",
1494
- back: "home",
1495
- body: `<span class="who">${logo(key ?? subscription.provider, name)}</span>
1496
- <h1>Remove ${escapeHtml(name)}${key === undefined ? "" : " API Key"}</h1>
1497
- <p>${escapeHtml(planLabel(subscription))}</p>
1498
- <p>Dari deletes ${key === undefined ? "the sign-in it holds for this plan" : "this key"}. Every app you shared it with stops using it.</p>
1499
- <input type="hidden" name="csrf" value="${session.csrf}">
1500
- <input type="hidden" name="remove_id" value="${escapeHtml(subscription.id)}">`,
1501
- footer: `<button class="btn danger" type="submit" name="decision" value="remove">Remove</button>`,
1502
- });
1503
- }
1504
1483
  function planOption(authorize, subscription, ticked) {
1505
- const box = `<input type="checkbox" name="credential_id" value="${escapeHtml(subscription.id)}"${ticked ? " checked" : ""}><button class="nav drop" type="submit" name="remove" value="${escapeHtml(subscription.id)}" formnovalidate aria-label="Remove">${ICONS.trash}</button>`;
1484
+ const box = `<input type="checkbox" name="credential_id" value="${escapeHtml(subscription.id)}"${ticked ? " checked" : ""}>`;
1506
1485
  if (subscription.apiKeyProvider !== undefined) {
1507
1486
  return `<label class="option pick">${logo(subscription.apiKeyProvider, subscription.name)}<span class="grow"><strong>${escapeHtml(subscription.name)}</strong><small>API key &middot; ${escapeHtml(planLabel(subscription))}</small></span>${box}</label>`;
1508
1487
  }
1509
1488
  const kind = subscription.provider;
1510
1489
  const only = subscriptionClient(kind);
1490
+ // What the app says it does with the plan, on hover.
1511
1491
  const purpose = authorize.purposes[only === "claude_code" || only === "muse_code" ? only : "any_app"];
1512
- const binding = subscription.usage.filter((window) => window.modelFamily === undefined).reduce((most, window) => most === null || window.utilization > most.utilization ? window : most, null);
1513
- const notes = [
1514
- planLabel(subscription),
1515
- ...(subscription.unavailableUntil
1516
- ? [`At its usage limit until ${new Date(subscription.unavailableUntil).toUTCString()}`]
1517
- : binding !== null
1518
- ? [`${Math.round(binding.utilization * 100)}% of its quota used`]
1519
- : []),
1520
- ...(purpose ? [`${authorize.app.name} says: ${purpose.replace(/[.\s]+$/, "")}`] : []),
1521
- ];
1522
- return `<label class="option pick">${logo(kind, KINDS[kind].name)}<span class="grow"><strong>${KINDS[kind].name}</strong><small>${notes.map(escapeHtml).join(" &middot; ")}</small></span>${box}</label>`;
1492
+ return `<label class="option pick"${purpose === undefined ? "" : ` title="${escapeHtml(purpose)}"`}>${logo(kind, KINDS[kind].name)}<span class="grow"><strong>${KINDS[kind].name}</strong>${meter(subscription, planLabel(subscription))}</span>${box}</label>`;
1493
+ }
1494
+ // The plan's account, and how much of its quota it used as the dashboard
1495
+ // shows it: a bar for its fullest shared window that has not reset, red at
1496
+ // the limit.
1497
+ function meter(subscription, account) {
1498
+ const now = Date.now();
1499
+ const held = subscription.unavailableUntil !== null && Date.parse(subscription.unavailableUntil) > now ? subscription.unavailableUntil : null;
1500
+ const fullest = subscription.usage
1501
+ .filter((window) => window.modelFamily === undefined && Date.parse(window.resetsAt) > now)
1502
+ .reduce((most, window) => most === null || window.utilization > most.utilization ? window : most, null);
1503
+ const shown = held !== null
1504
+ ? { percent: 100, until: held }
1505
+ : fullest === null ? null : { percent: Math.min(100, Math.round(fullest.utilization * 100)), until: fullest.resetsAt };
1506
+ if (shown === null)
1507
+ return `<small>${escapeHtml(account)}</small>`;
1508
+ const full = shown.percent >= 100;
1509
+ return `<span class="meter${full ? " full" : ""}" title="${full ? "Until" : "Resets"} ${escapeHtml(new Date(shown.until).toUTCString())}"><small>${escapeHtml(account)}</small><span class="pct">${full ? "Limit Reached" : `${shown.percent}%`}</span><span class="bar" role="meter" aria-label="Quota Used" aria-valuenow="${shown.percent}" aria-valuemin="0" aria-valuemax="100"><span style="width:${Math.max(shown.percent, 1)}%"></span></span></span>`;
1523
1510
  }
1524
1511
  // A provider's mark, or without one the first letter of its name.
1525
1512
  function logo(id, name) {
@@ -1635,9 +1622,9 @@ small{display:block;color:var(--faint);font-size:12px;line-height:1.4;overflow-w
1635
1622
  .option strong{display:block;font-size:14px;line-height:1.35}
1636
1623
  .option.slim{flex-direction:row;align-items:center;gap:10px;padding:10px 12px}.slim .logo{width:16px;height:16px}.slim strong{font-size:13px}
1637
1624
  .option.pick{flex-direction:row;align-items:center;margin:0 0 8px;padding:12px}.grow{flex:1;min-width:0}
1638
- input[type=checkbox]{appearance:none;-webkit-appearance:none;flex:none;display:grid;place-content:center;width:16px;height:16px;margin:0;border:1px solid rgba(237,237,237,.3);border-radius:4px;background:transparent;cursor:pointer}
1625
+ input[type=checkbox]{appearance:none;-webkit-appearance:none;flex:none;display:grid;place-content:center;width:20px;height:20px;margin:0 0 0 4px;border:1.5px solid rgba(237,237,237,.25);border-radius:50%;background:transparent;cursor:pointer;transition:background-color .15s,border-color .15s}
1639
1626
  input[type=checkbox]:checked{border-color:var(--ink);background:var(--ink)}
1640
- input[type=checkbox]:checked::after{content:"";width:8px;height:4px;margin-top:-2px;border:solid var(--page);border-width:0 0 2px 2px;transform:rotate(-45deg)}
1627
+ input[type=checkbox]:checked::after{content:"";width:9px;height:5px;margin-top:-2px;border:solid var(--card);border-width:0 0 2px 2px;transform:rotate(-45deg)}
1641
1628
  .who{display:inline-flex;align-items:center;justify-content:center;width:40px;height:40px;margin:0 0 16px;border:1px solid var(--rule);border-radius:6px;background:var(--page)}
1642
1629
  .step{display:flex;gap:12px;margin:0 0 20px}.step>div{flex:1;min-width:0}.step p,.step label{display:block;color:var(--muted);margin:0 0 10px}
1643
1630
  .n{flex:none;display:inline-flex;align-items:center;justify-content:center;width:20px;height:20px;border-radius:4px;background:rgba(237,237,237,.07);color:var(--muted);font-size:12px}
@@ -1656,6 +1643,10 @@ input[type=text]:focus-visible,input[type=password]:focus-visible{outline:1px so
1656
1643
  .nav.drop{position:static;flex:none;width:28px;height:28px;margin:0 -4px 0 0;color:var(--faint)}
1657
1644
  .btn.outline{border-color:var(--edge)}.btn.outline:hover{border-color:rgba(237,237,237,.4);background:var(--hover)}
1658
1645
  .btn.ghost{height:32px;margin:4px 0 0 -8px;padding:0 10px 0 8px;font-size:13px;color:var(--muted)}.btn.ghost:hover{background:rgba(237,237,237,.06);color:var(--ink)}
1646
+ .meter{display:flex;flex-wrap:wrap;align-items:baseline;gap:0 8px}.meter small{flex:1;min-width:0}
1647
+ .pct{flex:none;color:var(--muted);font-size:12px;font-variant-numeric:tabular-nums}.full .pct{color:#e5484d}
1648
+ .bar{flex:0 0 100%;height:4px;margin:8px 0 2px;border-radius:999px;background:rgba(237,237,237,.08);overflow:hidden}.bar>span{display:block;height:100%;border-radius:999px;background:var(--mint)}.full .bar>span{background:#d64548}
1649
+ .actions{display:flex;justify-content:space-between;margin:4px -8px 0}.actions .btn.ghost{margin:0}.actions span{display:flex}
1659
1650
  .fine{color:var(--faint);font-size:12px;margin:12px 0 0;text-align:center}
1660
1651
  .card{display:block;margin:0 0 12px;padding:14px 12px;border:1px solid var(--rule);border-radius:6px}.card>small{margin:2px 0 0}.card .field{margin:16px 0 8px}
1661
1652
  .row{display:flex;gap:8px;margin:16px 0 0}.row .btn{flex:1}
@@ -239,10 +239,15 @@ export type LinkApprovalPage = {
239
239
  * The platform's own sign-in. The page sends the user to `url()` with `state`
240
240
  * and `next`; the platform signs them in and returns them to
241
241
  * `/v1/link/session` with the same `next` and a ticket for that state.
242
+ * Signing out sends the user to `signOutUrl()` with `next`; the platform ends
243
+ * its own sign-in and returns them to `next`, so the next sign-in can be
244
+ * another account.
242
245
  */
243
246
  export type LinkSignIn = {
244
247
  /** Throws HttpError(503, `link_not_configured`) when the platform has none. */
245
248
  url(): string;
249
+ /** Throws HttpError(503, `link_not_configured`) when the platform has none. */
250
+ signOutUrl(): string;
246
251
  /** Who a ticket signed in, for which state, and when (epoch ms); null for no ticket. */
247
252
  redeem(ticket: string): Promise<{
248
253
  subject: string;
@@ -20,6 +20,7 @@ import { providerIdentityFromModel } from "../interaction/provider_continuation_
20
20
  import { buildOptions, supportedThinkingLevels } from "./pi_options.js";
21
21
  import { eventsWithSafeguardResults, forwardsAnthropicSafeguards, messageWithSafeguardResults, safeguardResultsTap, } from "./anthropic_safeguards.js";
22
22
  import { anthropicWebSearchFor, eventsWithWebSearchResults, messageWithWebSearchResults, webSearchResultsTap, } from "./anthropic_web_search.js";
23
+ import { chargesWebSearch, eventsWithWebSearchFee, messageWithWebSearchFee, webSearchCountTap } from "./web_search_fee.js";
23
24
  import { eventsWithProviderReportedCost, messageWithProviderReportedCost, providerReportedCostTap, reportsProviderCost, } from "./provider_reported_cost.js";
24
25
  import { eventsWithSubscriptionCacheWrites, messageWithSubscriptionCacheWrites, modelPricingFromPiModel, } from "./subscription_usage.js";
25
26
  // Pi's built-in providers stream through these API implementations unchanged.
@@ -64,13 +65,17 @@ export async function completeInteractionModel(args) {
64
65
  const webSearch = anthropicWebSearchFor(args.request, model)
65
66
  ? webSearchResultsTap(safeguards?.fetch ?? costTap?.fetch ?? args.fetch)
66
67
  : undefined;
67
- const options = buildOptions(args.request, args.auth ?? args.apiKey, args.model, model, pi, args.sessionId, args.selectedReasoningEffort, args.timeoutMs, args.signal, webSearch?.fetch ?? safeguards?.fetch ?? costTap?.fetch ?? args.fetch);
68
+ const searchCount = chargesWebSearch(args.request)
69
+ ? webSearchCountTap(webSearch?.fetch ?? safeguards?.fetch ?? costTap?.fetch ?? args.fetch)
70
+ : undefined;
71
+ const options = buildOptions(args.request, args.auth ?? args.apiKey, args.model, model, pi, args.sessionId, args.selectedReasoningEffort, args.timeoutMs, args.signal, searchCount?.fetch ?? webSearch?.fetch ?? safeguards?.fetch ?? costTap?.fetch ?? args.fetch);
68
72
  const usageContext = subscriptionUsageContext(args.model, model, source);
69
73
  const message = options.emitProviderEvents === true
70
74
  ? await completeProviderEventStream(pi.streamSimple(model, context, options))
71
75
  : await pi.completeSimple(model, context, options);
72
76
  return {
73
- message: messageWithProviderReportedCost(messageWithSubscriptionCacheWrites(messageWithWebSearchResults(messageWithSafeguardResults(message, safeguards?.results()), webSearch?.results() ?? []), usageContext), costTap?.cost()),
77
+ // The search fee goes on last, over whatever cost the steps before set.
78
+ message: messageWithWebSearchFee(messageWithProviderReportedCost(messageWithSubscriptionCacheWrites(messageWithWebSearchResults(messageWithSafeguardResults(message, safeguards?.results()), webSearch?.results() ?? []), usageContext), costTap?.cost()), searchCount?.searches() ?? 0),
74
79
  source,
75
80
  };
76
81
  }
@@ -127,14 +132,18 @@ export async function streamInteractionModel(args) {
127
132
  const webSearch = anthropicWebSearchFor(args.request, model)
128
133
  ? webSearchResultsTap(safeguards?.fetch ?? costTap?.fetch ?? args.fetch)
129
134
  : undefined;
130
- const events = pi.streamSimple(model, buildContext(args.request, source), buildOptions(args.request, args.auth ?? args.apiKey, args.model, model, pi, args.sessionId, args.selectedReasoningEffort, undefined, args.signal, webSearch?.fetch ?? safeguards?.fetch ?? costTap?.fetch ?? args.fetch));
135
+ const searchCount = chargesWebSearch(args.request)
136
+ ? webSearchCountTap(webSearch?.fetch ?? safeguards?.fetch ?? costTap?.fetch ?? args.fetch)
137
+ : undefined;
138
+ const events = pi.streamSimple(model, buildContext(args.request, source), buildOptions(args.request, args.auth ?? args.apiKey, args.model, model, pi, args.sessionId, args.selectedReasoningEffort, undefined, args.signal, searchCount?.fetch ?? webSearch?.fetch ?? safeguards?.fetch ?? costTap?.fetch ?? args.fetch));
131
139
  const withSafeguardResults = safeguards ? eventsWithSafeguardResults(events, safeguards) : events;
132
140
  const withWebSearchResults = webSearch
133
141
  ? eventsWithWebSearchResults(withSafeguardResults, webSearch)
134
142
  : withSafeguardResults;
135
143
  const withCacheWrites = eventsWithSubscriptionCacheWrites(withWebSearchResults, subscriptionUsageContext(args.model, model, source));
144
+ const withReportedCost = costTap ? eventsWithProviderReportedCost(withCacheWrites, costTap) : withCacheWrites;
136
145
  return {
137
- events: costTap ? eventsWithProviderReportedCost(withCacheWrites, costTap) : withCacheWrites,
146
+ events: searchCount ? eventsWithWebSearchFee(withReportedCost, searchCount) : withReportedCost,
138
147
  source,
139
148
  };
140
149
  }
@@ -0,0 +1,11 @@
1
+ import type { InteractionRequest } from "../interaction/types.js";
2
+ import type { ProviderFetch } from "./response_capture.js";
3
+ export declare const WEB_SEARCH_USD_PER_SEARCH = 0.01;
4
+ export declare function chargesWebSearch(request: Pick<InteractionRequest, "tools" | "toolChoice" | "items">): boolean;
5
+ export type WebSearchCountTap = {
6
+ fetch: ProviderFetch;
7
+ searches: () => number;
8
+ };
9
+ export declare function webSearchCountTap(fetch?: ProviderFetch): WebSearchCountTap;
10
+ export declare function messageWithWebSearchFee(message: Record<string, unknown>, searches: number): Record<string, unknown>;
11
+ export declare function eventsWithWebSearchFee(events: AsyncIterable<Record<string, unknown>>, tap: WebSearchCountTap): AsyncIterable<Record<string, unknown>>;
@@ -0,0 +1,73 @@
1
+ import { isRecord } from "@mupt-ai/dari-router/policy-engine";
2
+ import { requiredCapabilitiesFor } from "../interaction/capabilities.js";
3
+ import { sseEventScanner } from "./anthropic_safeguards.js";
4
+ // Anthropic and OpenAI charge for each web search on top of tokens: $10 per
5
+ // 1,000 searches, a search that fails is not charged.
6
+ // https://platform.claude.com/docs/en/agents-and-tools/tool-use/web-search-tool#usage-and-pricing
7
+ // https://developers.openai.com/api/docs/pricing
8
+ export const WEB_SEARCH_USD_PER_SEARCH = 0.01;
9
+ // Whether the request can make the provider run a web search it charges for.
10
+ export function chargesWebSearch(request) {
11
+ const capabilities = requiredCapabilitiesFor(request);
12
+ return capabilities.includes("anthropic_web_search") || capabilities.includes("openai_hosted_web_search");
13
+ }
14
+ // Counts the searches the provider charged for, from its own stream:
15
+ // Anthropic's usage reports them (`server_tool_use.web_search_requests`, the
16
+ // running total for the response), and OpenAI lists each completed
17
+ // `web_search_call`.
18
+ export function webSearchCountTap(fetch = globalThis.fetch) {
19
+ let anthropic = 0;
20
+ let openai = new Set();
21
+ return {
22
+ searches: () => anthropic + openai.size,
23
+ fetch: async (input, init) => {
24
+ const response = await fetch(input, init);
25
+ if (!response.ok || response.body === null)
26
+ return response;
27
+ anthropic = 0;
28
+ openai = new Set();
29
+ return new Response(response.body.pipeThrough(sseEventScanner("\"web_search", (event) => {
30
+ const usage = event.type === "message_delta" ? event.usage
31
+ : event.type === "message_start" && isRecord(event.message) ? event.message.usage
32
+ : undefined;
33
+ const requests = isRecord(usage) && isRecord(usage.server_tool_use)
34
+ ? usage.server_tool_use.web_search_requests
35
+ : undefined;
36
+ if (typeof requests === "number" && Number.isFinite(requests) && requests >= 0) {
37
+ anthropic = Math.max(anthropic, Math.trunc(requests));
38
+ }
39
+ const item = event.type === "response.output_item.done" ? event.item : undefined;
40
+ if (isRecord(item) && item.type === "web_search_call" && item.status === "completed" && typeof item.id === "string") {
41
+ openai.add(item.id);
42
+ }
43
+ })), { status: response.status, statusText: response.statusText, headers: response.headers });
44
+ },
45
+ };
46
+ }
47
+ // Adds the searches' fee to the message's cost, which is what a managed key
48
+ // is billed. Keys the customer owns and subscriptions are not billed here.
49
+ export function messageWithWebSearchFee(message, searches) {
50
+ if (searches <= 0 || !isRecord(message.usage) || !isRecord(message.usage.cost))
51
+ return message;
52
+ const cost = message.usage.cost;
53
+ const total = typeof cost.total === "number" && Number.isFinite(cost.total) ? cost.total : 0;
54
+ return {
55
+ ...message,
56
+ usage: { ...message.usage, cost: { ...cost, total: total + searches * WEB_SEARCH_USD_PER_SEARCH } },
57
+ };
58
+ }
59
+ // Aborted and failed calls end in an error event carrying the partial
60
+ // message; a search the provider completed before the end is still charged.
61
+ export async function* eventsWithWebSearchFee(events, tap) {
62
+ for await (const event of events) {
63
+ if (event.type === "done" && isRecord(event.message)) {
64
+ yield { ...event, message: messageWithWebSearchFee(event.message, tap.searches()) };
65
+ continue;
66
+ }
67
+ if (event.type === "error" && isRecord(event.error)) {
68
+ yield { ...event, error: messageWithWebSearchFee(event.error, tap.searches()) };
69
+ continue;
70
+ }
71
+ yield event;
72
+ }
73
+ }
@@ -1,14 +1,27 @@
1
- import { routingCandidateKey, } from "@mupt-ai/dari-router/policy-engine";
1
+ import { previousDecisionFromHit, routingCandidateKey, } from "@mupt-ai/dari-router/policy-engine";
2
2
  import { isBackgroundRequest } from "../../interaction/types.js";
3
3
  import { HttpError } from "../../http/errors.js";
4
4
  import { assertCreditAvailableBeforeRouting } from "../../telemetry/usage.js";
5
- // Explicit background classes bypass the selector and every lease path.
6
- // Keep the existing deterministic cheapest-input-cost serving policy.
5
+ // Explicit background classes bypass the selector and every lease path. As
6
+ // Claude Code does against Anthropic, work for an agent (compaction, side
7
+ // questions, prompt suggestions) runs on the model that agent is on. Claude
8
+ // Code names its small model itself, so the rest that reaches routing (a
9
+ // safety check, a web search) runs on the cheapest model.
7
10
  export function auxiliaryDecision(prepared) {
8
11
  if (!isBackgroundRequest(prepared.interaction))
9
12
  return null;
10
13
  assertCreditAvailableBeforeRouting(prepared.billable, prepared.credentials);
11
14
  const requestClass = prepared.interaction.agentContext.requestClass;
15
+ const agent = agentCandidate(prepared);
16
+ if (agent) {
17
+ return {
18
+ decision: {
19
+ selectedModel: agent.model,
20
+ reasoningEffort: agent.reasoningEffort,
21
+ reason: `${requestClass} request served on its agent's model without selection.`,
22
+ },
23
+ };
24
+ }
12
25
  const cheapest = cheapestCandidate(prepared);
13
26
  if (!cheapest) {
14
27
  throw new HttpError(503, "Background requests require a routable model with known pricing.", "background_model_unavailable");
@@ -20,6 +33,24 @@ export function auxiliaryDecision(prepared) {
20
33
  };
21
34
  return { decision };
22
35
  }
36
+ /* The pair the agent is on (its lease target, else what it was last served)
37
+ or, when this request cannot take that pair (a forced tool rules out
38
+ thinking), one of those models at a level it can. */
39
+ function agentCandidate(prepared) {
40
+ const row = prepared.agentRow;
41
+ if (row === undefined)
42
+ return null;
43
+ const candidates = prepared.routing.candidateResolution.candidates;
44
+ const pair = previousDecisionFromHit(row, candidates);
45
+ if (pair)
46
+ return { model: pair.model, reasoningEffort: pair.reasoningEffort };
47
+ for (const model of [row.next_model, row.model]) {
48
+ const candidate = candidates.find((candidate) => candidate.model === model);
49
+ if (candidate)
50
+ return candidate;
51
+ }
52
+ return null;
53
+ }
23
54
  /* Ranked on estimated input cost: these requests carry a whole transcript in
24
55
  and a sentence out, so the prompt dominates. Estimates cover the configured
25
56
  roster, so they are narrowed to the candidates pruning actually left
@@ -1,3 +1,4 @@
1
+ import { type RouterPrefixHit } from "@mupt-ai/dari-router/policy-engine";
1
2
  import { type RoutingContext } from "../context/routing_context.js";
2
3
  import { type InteractionRequest } from "../interaction/types.js";
3
4
  import { type RequestTags, type SessionPin } from "../platform/platform.js";
@@ -22,6 +23,7 @@ export type PreparedRoutedCompletion = {
22
23
  };
23
24
  role?: RouterRole;
24
25
  rolePrompt?: string;
26
+ agentRow?: RouterPrefixHit;
25
27
  reporter: RoutedRuntimeReporter;
26
28
  };
27
29
  export declare function prepareRoutedCompletion(args: {
@@ -1,3 +1,4 @@
1
+ import { newestConversationHit, } from "@mupt-ai/dari-router/policy-engine";
1
2
  import { interactionConversationPrefix } from "../context/interaction_fingerprint.js";
2
3
  import { clampRequestedEffort } from "../context/routing_context.js";
3
4
  import { modelMetadataLookup } from "../providers/pi.js";
@@ -6,7 +7,7 @@ import { isBackgroundRequest } from "../interaction/types.js";
6
7
  import { executionProviderForModel } from "../models/execution_provider.js";
7
8
  import { codexModelConfig, subscriptionServes } from "../models/subscriptions.js";
8
9
  import { explicitModelId } from "../protocol/input/router_model.js";
9
- import { gatewayPlatform } from "../platform/platform.js";
10
+ import { gatewayPlatform, } from "../platform/platform.js";
10
11
  import { resolveRouter } from "../strategies/routing.js";
11
12
  import { RequestReporter } from "../telemetry/report.js";
12
13
  import { RoutingBillingFinalization } from "../telemetry/billing_finalization.js";
@@ -88,6 +89,20 @@ export async function prepareRoutedCompletion(args) {
88
89
  }
89
90
  credentials = conversationCredentials;
90
91
  }
92
+ // Claude Code runs compaction, side questions and its other forked work on
93
+ // the model of the agent they serve. On routing, that is the model the
94
+ // agent's conversation is on, read from its latest row.
95
+ const agentRow = background
96
+ && args.harnessConversationIdentity !== undefined
97
+ && credentials.strict !== true
98
+ && explicitModelId(args.interaction.model) === null
99
+ ? await agentConversationRow({
100
+ resolveRequest: { routerId: args.routerId, apiKey: args.apiKey, clientHarness: args.clientHarness },
101
+ identity: args.harnessConversationIdentity,
102
+ interaction: args.interaction,
103
+ scope: harnessScope,
104
+ })
105
+ : undefined;
91
106
  const roleModel = withRoleModel(credentials, args.interaction);
92
107
  const prompt = rolePrompt(credentials, args.interaction);
93
108
  const strictAccess = strictProviderAccess(credentials, roleModel.interaction);
@@ -176,9 +191,35 @@ export async function prepareRoutedCompletion(args) {
176
191
  ...(sessionPin === undefined ? {} : { sessionPin }),
177
192
  ...(roleModel.role === undefined ? {} : { role: roleModel.role }),
178
193
  ...(prompt === undefined ? {} : { rolePrompt: prompt }),
194
+ ...(agentRow === undefined ? {} : { agentRow }),
179
195
  reporter,
180
196
  };
181
197
  }
198
+ /* The latest row of the conversation a background request works for. Forked
199
+ work carries that agent's transcript, so it names the same conversation
200
+ under the agent's own request class. An agent with an id is usually a
201
+ subagent, which Claude Code may have run as a workflow agent, but may be a
202
+ main agent (an Agent Teams teammate). Other background work
203
+ (a web search, a safety check) carries its own transcript and finds none. */
204
+ async function agentConversationRow(args) {
205
+ const namedAgent = (args.identity.qualifiers?.length ?? 0) > 0
206
+ || (args.identity.kind === "codex_thread" && args.identity.parentThreadId !== undefined);
207
+ const prefix = interactionConversationPrefix(args.interaction);
208
+ for (const requestClass of namedAgent ? ["subagent", "workflow", "main"] : ["main"]) {
209
+ const conversationId = scopedHarnessConversationId({
210
+ identity: args.identity,
211
+ sourceProtocol: args.interaction.sourceProtocol,
212
+ scope: args.scope,
213
+ conversationPrefix: JSON.stringify([requestClass, prefix]),
214
+ });
215
+ // Read-only: none of this resolve's credentials serve the request.
216
+ const resolved = await resolveRouter({ ...args.resolveRequest, conversationId, provisional: true });
217
+ const row = newestConversationHit(resolved.prefix_hits, conversationId)?.entry;
218
+ if (row !== undefined)
219
+ return row;
220
+ }
221
+ return undefined;
222
+ }
182
223
  // Ask the platform for each enabled model's credential up front, so provider
183
224
  // execution stays synchronous.
184
225
  async function withProviderCredentials(credentials, apiKey, clientHarness) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mupt-ai/dari-gateway",
3
- "version": "1.0.323",
3
+ "version": "1.0.325",
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.323",
55
+ "@mupt-ai/dari-router": "1.0.325",
56
56
  "@mupt-ai/pi-ai": "1.5.2-mupt.1"
57
57
  },
58
58
  "devDependencies": {
@@ -62,6 +62,7 @@ import type {
62
62
  LinkGrantDetail,
63
63
  LinkKeyProvider,
64
64
  LinkUsageTotals,
65
+ LinkUsageWindow,
65
66
  LinkPlatform,
66
67
  LinkSignIn,
67
68
  LinkBudget,
@@ -1099,7 +1100,7 @@ async function authorizeSubmit(link: LinkPlatform, request: Request, form: URLSe
1099
1100
  }
1100
1101
  const decision = kind !== null ? "connect" : form.get("decision");
1101
1102
  if (decision === "deny") return redirect(back, { error: "access_denied" }, [endConnect]);
1102
- if (decision === "sign_out") return seeAuthorize(authorize, signOutCookies(request));
1103
+ if (decision === "sign_out") return signOut(request, approval, `${AUTHORIZE_PATH}?${authorizeQuery(authorize)}`);
1103
1104
  if (decision === "select") return selectPage(approval, authorize, undefined, [endConnect]);
1104
1105
  if (decision === "connect") {
1105
1106
  if (!connectKinds(approval, authorize).includes(kind as SubscriptionKind)) {
@@ -1142,14 +1143,6 @@ async function authorizeSubmit(link: LinkPlatform, request: Request, form: URLSe
1142
1143
  if (decision === "complete" && connect !== null) {
1143
1144
  return await finishConnect(approval, request, authorize, session, connect, form.get("authorization_response")?.trim() ?? "");
1144
1145
  }
1145
- // Removing a plan or key asks once, then deletes what Dari stored for it.
1146
- const removing = form.get("remove") ?? form.get("remove_id");
1147
- if (removing !== null && session !== null) {
1148
- const subscription = (await approval.subscriptions(session.subject)).find((candidate) => candidate.id === removing);
1149
- if (subscription !== undefined && decision !== "remove") return removePage(authorize, session, subscription);
1150
- if (subscription !== undefined && sameText(form.get("csrf") ?? "", session.csrf)) await approval.remove(session.subject, removing);
1151
- return seeAuthorize(authorize, [endConnect]);
1152
- }
1153
1146
  // Anything else goes back to where the user stands.
1154
1147
  if (decision !== "approve" || session === null) return seeAuthorize(authorize, [endConnect]);
1155
1148
  if (!sameText(form.get("csrf") ?? "", session.csrf)) {
@@ -1276,11 +1269,7 @@ async function connectionsSubmit(approval: LinkApprovalPage, request: Request, f
1276
1269
  const back = new Response(null, { status: 303, headers: { Location: CONNECTIONS_PATH, "Cache-Control": "no-store" } });
1277
1270
  if (session === null || !sameText(form.get("csrf") ?? "", session.csrf)) return back;
1278
1271
  const decision = form.get("decision");
1279
- if (decision === "sign_out") {
1280
- const headers = new Headers({ Location: CONNECTIONS_PATH, "Cache-Control": "no-store" });
1281
- for (const cookie of signOutCookies(request)) headers.append("Set-Cookie", cookie);
1282
- return new Response(null, { status: 303, headers });
1283
- }
1272
+ if (decision === "sign_out") return signOut(request, approval, CONNECTIONS_PATH);
1284
1273
  const grantId = form.get("grant_id") ?? "";
1285
1274
  if (decision === "disconnect") {
1286
1275
  await approval.disconnect(session.subject, grantId);
@@ -1465,9 +1454,20 @@ function userCookie(request: Request, approval: LinkApprovalPage, subject: strin
1465
1454
  : signedCookie(request, approval.sessionSecret(), USER_COOKIE, { sub: subject, account: true }, ACCOUNT_SECONDS);
1466
1455
  }
1467
1456
 
1468
- // Signing out leaves nothing of the user's: not who they are, nor a provider sign-in under way.
1469
- function signOutCookies(request: Request): string[] {
1470
- return [clearCookie(request, USER_COOKIE), clearCookie(request, CONNECT_COOKIE)];
1457
+ // Signing out leaves nothing of the user's: not who they are, nor a provider
1458
+ // sign-in under way. A platform with accounts ends its own sign-in too, then
1459
+ // returns the user to `next`, so the next sign-in can be another account.
1460
+ function signOut(request: Request, approval: LinkApprovalPage, next: string): Response {
1461
+ let location = next;
1462
+ if (approval.signIn !== undefined) {
1463
+ const url = new URL(approval.signIn.signOutUrl());
1464
+ url.searchParams.set("next", next);
1465
+ location = url.toString();
1466
+ }
1467
+ const headers = new Headers({ Location: location, "Cache-Control": "no-store" });
1468
+ headers.append("Set-Cookie", clearCookie(request, USER_COOKIE));
1469
+ headers.append("Set-Cookie", clearCookie(request, CONNECT_COOKIE));
1470
+ return new Response(null, { status: 303, headers });
1471
1471
  }
1472
1472
 
1473
1473
  function clearCookie(request: Request, cookie: string): string {
@@ -1671,53 +1671,39 @@ function choosePage(
1671
1671
  body: `<h1>${current === null ? `Share With ${app}` : `Update Plans For ${app}`}</h1>
1672
1672
  <input type="hidden" name="csrf" value="${session.csrf}">
1673
1673
  ${plans.map((plan) => planOption(authorize, plan, ticked.has(plan.id))).join("\n")}
1674
- <button class="btn ghost" type="submit" name="decision" value="select" formnovalidate>${ICONS.plus}Connect Another</button>
1675
- ${session.account ? SIGN_OUT : ""}`,
1674
+ <div class="actions"><button class="btn ghost" type="submit" name="decision" value="select" formnovalidate>${ICONS.plus}Connect Another</button><span><a class="btn ghost" href="${CONNECTIONS_PATH}" target="_blank" rel="noopener">Manage</a>${session.account ? SIGN_OUT : ""}</span></div>`,
1676
1675
  footer: `<button class="btn primary" type="submit" name="decision" value="approve">${current === null ? "Allow" : "Save"}</button>
1677
1676
  <p class="fine">${app} keeps access until you or it disconnect. Its requests fail while a plan is at its usage limit.</p>`,
1678
1677
  });
1679
1678
  }
1680
1679
 
1681
- // What the user is about to delete, and the one button that deletes it.
1682
- function removePage(authorize: AuthorizeRequest, session: Session, subscription: LinkSubscription): Response {
1683
- const key = subscription.apiKeyProvider;
1684
- const name = key === undefined ? KINDS[subscription.provider as SubscriptionKind]?.name ?? subscription.name : subscription.name;
1685
- return pane(authorize, {
1686
- title: `Remove ${name}`,
1687
- step: "choose_plans",
1688
- back: "home",
1689
- body: `<span class="who">${logo(key ?? subscription.provider, name)}</span>
1690
- <h1>Remove ${escapeHtml(name)}${key === undefined ? "" : " API Key"}</h1>
1691
- <p>${escapeHtml(planLabel(subscription))}</p>
1692
- <p>Dari deletes ${key === undefined ? "the sign-in it holds for this plan" : "this key"}. Every app you shared it with stops using it.</p>
1693
- <input type="hidden" name="csrf" value="${session.csrf}">
1694
- <input type="hidden" name="remove_id" value="${escapeHtml(subscription.id)}">`,
1695
- footer: `<button class="btn danger" type="submit" name="decision" value="remove">Remove</button>`,
1696
- });
1697
- }
1698
-
1699
1680
  function planOption(authorize: AuthorizeRequest, subscription: LinkSubscription, ticked: boolean): string {
1700
- const box = `<input type="checkbox" name="credential_id" value="${escapeHtml(subscription.id)}"${ticked ? " checked" : ""}><button class="nav drop" type="submit" name="remove" value="${escapeHtml(subscription.id)}" formnovalidate aria-label="Remove">${ICONS.trash}</button>`;
1681
+ const box = `<input type="checkbox" name="credential_id" value="${escapeHtml(subscription.id)}"${ticked ? " checked" : ""}>`;
1701
1682
  if (subscription.apiKeyProvider !== undefined) {
1702
1683
  return `<label class="option pick">${logo(subscription.apiKeyProvider, subscription.name)}<span class="grow"><strong>${escapeHtml(subscription.name)}</strong><small>API key &middot; ${escapeHtml(planLabel(subscription))}</small></span>${box}</label>`;
1703
1684
  }
1704
1685
  const kind = subscription.provider as SubscriptionKind;
1705
1686
  const only = subscriptionClient(kind);
1687
+ // What the app says it does with the plan, on hover.
1706
1688
  const purpose = authorize.purposes[only === "claude_code" || only === "muse_code" ? only : "any_app"];
1707
- const binding = subscription.usage.filter((window) => window.modelFamily === undefined).reduce<LinkSubscription["usage"][number] | null>(
1708
- (most, window) => most === null || window.utilization > most.utilization ? window : most,
1709
- null,
1710
- );
1711
- const notes = [
1712
- planLabel(subscription),
1713
- ...(subscription.unavailableUntil
1714
- ? [`At its usage limit until ${new Date(subscription.unavailableUntil).toUTCString()}`]
1715
- : binding !== null
1716
- ? [`${Math.round(binding.utilization * 100)}% of its quota used`]
1717
- : []),
1718
- ...(purpose ? [`${authorize.app.name} says: ${purpose.replace(/[.\s]+$/, "")}`] : []),
1719
- ];
1720
- return `<label class="option pick">${logo(kind, KINDS[kind].name)}<span class="grow"><strong>${KINDS[kind].name}</strong><small>${notes.map(escapeHtml).join(" &middot; ")}</small></span>${box}</label>`;
1689
+ return `<label class="option pick"${purpose === undefined ? "" : ` title="${escapeHtml(purpose)}"`}>${logo(kind, KINDS[kind].name)}<span class="grow"><strong>${KINDS[kind].name}</strong>${meter(subscription, planLabel(subscription))}</span>${box}</label>`;
1690
+ }
1691
+
1692
+ // The plan's account, and how much of its quota it used as the dashboard
1693
+ // shows it: a bar for its fullest shared window that has not reset, red at
1694
+ // the limit.
1695
+ function meter(subscription: LinkSubscription, account: string): string {
1696
+ const now = Date.now();
1697
+ const held = subscription.unavailableUntil !== null && Date.parse(subscription.unavailableUntil) > now ? subscription.unavailableUntil : null;
1698
+ const fullest = subscription.usage
1699
+ .filter((window) => window.modelFamily === undefined && Date.parse(window.resetsAt) > now)
1700
+ .reduce<LinkUsageWindow | null>((most, window) => most === null || window.utilization > most.utilization ? window : most, null);
1701
+ const shown = held !== null
1702
+ ? { percent: 100, until: held }
1703
+ : fullest === null ? null : { percent: Math.min(100, Math.round(fullest.utilization * 100)), until: fullest.resetsAt };
1704
+ if (shown === null) return `<small>${escapeHtml(account)}</small>`;
1705
+ const full = shown.percent >= 100;
1706
+ return `<span class="meter${full ? " full" : ""}" title="${full ? "Until" : "Resets"} ${escapeHtml(new Date(shown.until).toUTCString())}"><small>${escapeHtml(account)}</small><span class="pct">${full ? "Limit Reached" : `${shown.percent}%`}</span><span class="bar" role="meter" aria-label="Quota Used" aria-valuenow="${shown.percent}" aria-valuemin="0" aria-valuemax="100"><span style="width:${Math.max(shown.percent, 1)}%"></span></span></span>`;
1721
1707
  }
1722
1708
 
1723
1709
  // A provider's mark, or without one the first letter of its name.
@@ -1859,9 +1845,9 @@ small{display:block;color:var(--faint);font-size:12px;line-height:1.4;overflow-w
1859
1845
  .option strong{display:block;font-size:14px;line-height:1.35}
1860
1846
  .option.slim{flex-direction:row;align-items:center;gap:10px;padding:10px 12px}.slim .logo{width:16px;height:16px}.slim strong{font-size:13px}
1861
1847
  .option.pick{flex-direction:row;align-items:center;margin:0 0 8px;padding:12px}.grow{flex:1;min-width:0}
1862
- input[type=checkbox]{appearance:none;-webkit-appearance:none;flex:none;display:grid;place-content:center;width:16px;height:16px;margin:0;border:1px solid rgba(237,237,237,.3);border-radius:4px;background:transparent;cursor:pointer}
1848
+ input[type=checkbox]{appearance:none;-webkit-appearance:none;flex:none;display:grid;place-content:center;width:20px;height:20px;margin:0 0 0 4px;border:1.5px solid rgba(237,237,237,.25);border-radius:50%;background:transparent;cursor:pointer;transition:background-color .15s,border-color .15s}
1863
1849
  input[type=checkbox]:checked{border-color:var(--ink);background:var(--ink)}
1864
- input[type=checkbox]:checked::after{content:"";width:8px;height:4px;margin-top:-2px;border:solid var(--page);border-width:0 0 2px 2px;transform:rotate(-45deg)}
1850
+ input[type=checkbox]:checked::after{content:"";width:9px;height:5px;margin-top:-2px;border:solid var(--card);border-width:0 0 2px 2px;transform:rotate(-45deg)}
1865
1851
  .who{display:inline-flex;align-items:center;justify-content:center;width:40px;height:40px;margin:0 0 16px;border:1px solid var(--rule);border-radius:6px;background:var(--page)}
1866
1852
  .step{display:flex;gap:12px;margin:0 0 20px}.step>div{flex:1;min-width:0}.step p,.step label{display:block;color:var(--muted);margin:0 0 10px}
1867
1853
  .n{flex:none;display:inline-flex;align-items:center;justify-content:center;width:20px;height:20px;border-radius:4px;background:rgba(237,237,237,.07);color:var(--muted);font-size:12px}
@@ -1880,6 +1866,10 @@ input[type=text]:focus-visible,input[type=password]:focus-visible{outline:1px so
1880
1866
  .nav.drop{position:static;flex:none;width:28px;height:28px;margin:0 -4px 0 0;color:var(--faint)}
1881
1867
  .btn.outline{border-color:var(--edge)}.btn.outline:hover{border-color:rgba(237,237,237,.4);background:var(--hover)}
1882
1868
  .btn.ghost{height:32px;margin:4px 0 0 -8px;padding:0 10px 0 8px;font-size:13px;color:var(--muted)}.btn.ghost:hover{background:rgba(237,237,237,.06);color:var(--ink)}
1869
+ .meter{display:flex;flex-wrap:wrap;align-items:baseline;gap:0 8px}.meter small{flex:1;min-width:0}
1870
+ .pct{flex:none;color:var(--muted);font-size:12px;font-variant-numeric:tabular-nums}.full .pct{color:#e5484d}
1871
+ .bar{flex:0 0 100%;height:4px;margin:8px 0 2px;border-radius:999px;background:rgba(237,237,237,.08);overflow:hidden}.bar>span{display:block;height:100%;border-radius:999px;background:var(--mint)}.full .bar>span{background:#d64548}
1872
+ .actions{display:flex;justify-content:space-between;margin:4px -8px 0}.actions .btn.ghost{margin:0}.actions span{display:flex}
1883
1873
  .fine{color:var(--faint);font-size:12px;margin:12px 0 0;text-align:center}
1884
1874
  .card{display:block;margin:0 0 12px;padding:14px 12px;border:1px solid var(--rule);border-radius:6px}.card>small{margin:2px 0 0}.card .field{margin:16px 0 8px}
1885
1875
  .row{display:flex;gap:8px;margin:16px 0 0}.row .btn{flex:1}
@@ -240,10 +240,15 @@ export type LinkApprovalPage = {
240
240
  * The platform's own sign-in. The page sends the user to `url()` with `state`
241
241
  * and `next`; the platform signs them in and returns them to
242
242
  * `/v1/link/session` with the same `next` and a ticket for that state.
243
+ * Signing out sends the user to `signOutUrl()` with `next`; the platform ends
244
+ * its own sign-in and returns them to `next`, so the next sign-in can be
245
+ * another account.
243
246
  */
244
247
  export type LinkSignIn = {
245
248
  /** Throws HttpError(503, `link_not_configured`) when the platform has none. */
246
249
  url(): string;
250
+ /** Throws HttpError(503, `link_not_configured`) when the platform has none. */
251
+ signOutUrl(): string;
247
252
  /** Who a ticket signed in, for which state, and when (epoch ms); null for no ticket. */
248
253
  redeem(ticket: string): Promise<{ subject: string; state: string; issuedAt: number } | null>;
249
254
  };
@@ -53,6 +53,7 @@ import {
53
53
  messageWithWebSearchResults,
54
54
  webSearchResultsTap,
55
55
  } from "./anthropic_web_search.js";
56
+ import { chargesWebSearch, eventsWithWebSearchFee, messageWithWebSearchFee, webSearchCountTap } from "./web_search_fee.js";
56
57
  import {
57
58
  eventsWithProviderReportedCost,
58
59
  messageWithProviderReportedCost,
@@ -161,6 +162,9 @@ export async function completeInteractionModel(args: {
161
162
  const webSearch = anthropicWebSearchFor(args.request, model)
162
163
  ? webSearchResultsTap(safeguards?.fetch ?? costTap?.fetch ?? args.fetch)
163
164
  : undefined;
165
+ const searchCount = chargesWebSearch(args.request)
166
+ ? webSearchCountTap(webSearch?.fetch ?? safeguards?.fetch ?? costTap?.fetch ?? args.fetch)
167
+ : undefined;
164
168
  const options = buildOptions(
165
169
  args.request,
166
170
  args.auth ?? args.apiKey,
@@ -171,22 +175,26 @@ export async function completeInteractionModel(args: {
171
175
  args.selectedReasoningEffort,
172
176
  args.timeoutMs,
173
177
  args.signal,
174
- webSearch?.fetch ?? safeguards?.fetch ?? costTap?.fetch ?? args.fetch,
178
+ searchCount?.fetch ?? webSearch?.fetch ?? safeguards?.fetch ?? costTap?.fetch ?? args.fetch,
175
179
  );
176
180
  const usageContext = subscriptionUsageContext(args.model, model, source);
177
181
  const message = options.emitProviderEvents === true
178
182
  ? await completeProviderEventStream(pi.streamSimple(model, context, options))
179
183
  : await pi.completeSimple(model, context, options);
180
184
  return {
181
- message: messageWithProviderReportedCost(
182
- messageWithSubscriptionCacheWrites(
183
- messageWithWebSearchResults(
184
- messageWithSafeguardResults(message, safeguards?.results()),
185
- webSearch?.results() ?? [],
185
+ // The search fee goes on last, over whatever cost the steps before set.
186
+ message: messageWithWebSearchFee(
187
+ messageWithProviderReportedCost(
188
+ messageWithSubscriptionCacheWrites(
189
+ messageWithWebSearchResults(
190
+ messageWithSafeguardResults(message, safeguards?.results()),
191
+ webSearch?.results() ?? [],
192
+ ),
193
+ usageContext
186
194
  ),
187
- usageContext
195
+ costTap?.cost(),
188
196
  ),
189
- costTap?.cost(),
197
+ searchCount?.searches() ?? 0,
190
198
  ),
191
199
  source,
192
200
  };
@@ -266,6 +274,9 @@ export async function streamInteractionModel(args: {
266
274
  const webSearch = anthropicWebSearchFor(args.request, model)
267
275
  ? webSearchResultsTap(safeguards?.fetch ?? costTap?.fetch ?? args.fetch)
268
276
  : undefined;
277
+ const searchCount = chargesWebSearch(args.request)
278
+ ? webSearchCountTap(webSearch?.fetch ?? safeguards?.fetch ?? costTap?.fetch ?? args.fetch)
279
+ : undefined;
269
280
  const events = pi.streamSimple(
270
281
  model,
271
282
  buildContext(args.request, source),
@@ -279,7 +290,7 @@ export async function streamInteractionModel(args: {
279
290
  args.selectedReasoningEffort,
280
291
  undefined,
281
292
  args.signal,
282
- webSearch?.fetch ?? safeguards?.fetch ?? costTap?.fetch ?? args.fetch,
293
+ searchCount?.fetch ?? webSearch?.fetch ?? safeguards?.fetch ?? costTap?.fetch ?? args.fetch,
283
294
  )
284
295
  );
285
296
  const withSafeguardResults = safeguards ? eventsWithSafeguardResults(events, safeguards) : events;
@@ -290,8 +301,9 @@ export async function streamInteractionModel(args: {
290
301
  withWebSearchResults,
291
302
  subscriptionUsageContext(args.model, model, source)
292
303
  );
304
+ const withReportedCost = costTap ? eventsWithProviderReportedCost(withCacheWrites, costTap) : withCacheWrites;
293
305
  return {
294
- events: costTap ? eventsWithProviderReportedCost(withCacheWrites, costTap) : withCacheWrites,
306
+ events: searchCount ? eventsWithWebSearchFee(withReportedCost, searchCount) : withReportedCost,
295
307
  source,
296
308
  };
297
309
  }
@@ -0,0 +1,93 @@
1
+ import { isRecord } from "@mupt-ai/dari-router/policy-engine";
2
+
3
+ import { requiredCapabilitiesFor } from "../interaction/capabilities.js";
4
+ import type { InteractionRequest } from "../interaction/types.js";
5
+ import { sseEventScanner } from "./anthropic_safeguards.js";
6
+ import type { ProviderFetch } from "./response_capture.js";
7
+
8
+ // Anthropic and OpenAI charge for each web search on top of tokens: $10 per
9
+ // 1,000 searches, a search that fails is not charged.
10
+ // https://platform.claude.com/docs/en/agents-and-tools/tool-use/web-search-tool#usage-and-pricing
11
+ // https://developers.openai.com/api/docs/pricing
12
+ export const WEB_SEARCH_USD_PER_SEARCH = 0.01;
13
+
14
+ // Whether the request can make the provider run a web search it charges for.
15
+ export function chargesWebSearch(request: Pick<InteractionRequest, "tools" | "toolChoice" | "items">): boolean {
16
+ const capabilities = requiredCapabilitiesFor(request);
17
+ return capabilities.includes("anthropic_web_search") || capabilities.includes("openai_hosted_web_search");
18
+ }
19
+
20
+ export type WebSearchCountTap = {
21
+ fetch: ProviderFetch;
22
+ searches: () => number;
23
+ };
24
+
25
+ // Counts the searches the provider charged for, from its own stream:
26
+ // Anthropic's usage reports them (`server_tool_use.web_search_requests`, the
27
+ // running total for the response), and OpenAI lists each completed
28
+ // `web_search_call`.
29
+ export function webSearchCountTap(fetch: ProviderFetch = globalThis.fetch): WebSearchCountTap {
30
+ let anthropic = 0;
31
+ let openai = new Set<string>();
32
+ return {
33
+ searches: () => anthropic + openai.size,
34
+ fetch: async (input, init) => {
35
+ const response = await fetch(input, init);
36
+ if (!response.ok || response.body === null) return response;
37
+ anthropic = 0;
38
+ openai = new Set();
39
+ return new Response(
40
+ response.body.pipeThrough(sseEventScanner("\"web_search", (event) => {
41
+ const usage = event.type === "message_delta" ? event.usage
42
+ : event.type === "message_start" && isRecord(event.message) ? event.message.usage
43
+ : undefined;
44
+ const requests = isRecord(usage) && isRecord(usage.server_tool_use)
45
+ ? usage.server_tool_use.web_search_requests
46
+ : undefined;
47
+ if (typeof requests === "number" && Number.isFinite(requests) && requests >= 0) {
48
+ anthropic = Math.max(anthropic, Math.trunc(requests));
49
+ }
50
+ const item = event.type === "response.output_item.done" ? event.item : undefined;
51
+ if (isRecord(item) && item.type === "web_search_call" && item.status === "completed" && typeof item.id === "string") {
52
+ openai.add(item.id);
53
+ }
54
+ })),
55
+ { status: response.status, statusText: response.statusText, headers: response.headers },
56
+ );
57
+ },
58
+ };
59
+ }
60
+
61
+ // Adds the searches' fee to the message's cost, which is what a managed key
62
+ // is billed. Keys the customer owns and subscriptions are not billed here.
63
+ export function messageWithWebSearchFee(
64
+ message: Record<string, unknown>,
65
+ searches: number,
66
+ ): Record<string, unknown> {
67
+ if (searches <= 0 || !isRecord(message.usage) || !isRecord(message.usage.cost)) return message;
68
+ const cost = message.usage.cost;
69
+ const total = typeof cost.total === "number" && Number.isFinite(cost.total) ? cost.total : 0;
70
+ return {
71
+ ...message,
72
+ usage: { ...message.usage, cost: { ...cost, total: total + searches * WEB_SEARCH_USD_PER_SEARCH } },
73
+ };
74
+ }
75
+
76
+ // Aborted and failed calls end in an error event carrying the partial
77
+ // message; a search the provider completed before the end is still charged.
78
+ export async function* eventsWithWebSearchFee(
79
+ events: AsyncIterable<Record<string, unknown>>,
80
+ tap: WebSearchCountTap,
81
+ ): AsyncIterable<Record<string, unknown>> {
82
+ for await (const event of events) {
83
+ if (event.type === "done" && isRecord(event.message)) {
84
+ yield { ...event, message: messageWithWebSearchFee(event.message, tap.searches()) };
85
+ continue;
86
+ }
87
+ if (event.type === "error" && isRecord(event.error)) {
88
+ yield { ...event, error: messageWithWebSearchFee(event.error, tap.searches()) };
89
+ continue;
90
+ }
91
+ yield event;
92
+ }
93
+ }
@@ -1,6 +1,8 @@
1
1
  import {
2
+ previousDecisionFromHit,
2
3
  routingCandidateKey,
3
4
  type CandidateCostEstimate,
5
+ type RoutingCandidate,
4
6
  type RoutingDecision,
5
7
  } from "@mupt-ai/dari-router/policy-engine";
6
8
 
@@ -10,14 +12,27 @@ import { HttpError } from "../../http/errors.js";
10
12
  import { assertCreditAvailableBeforeRouting } from "../../telemetry/usage.js";
11
13
  import type { PreparedRoutedCompletion } from "../prepare_routed_completion.js";
12
14
 
13
- // Explicit background classes bypass the selector and every lease path.
14
- // Keep the existing deterministic cheapest-input-cost serving policy.
15
+ // Explicit background classes bypass the selector and every lease path. As
16
+ // Claude Code does against Anthropic, work for an agent (compaction, side
17
+ // questions, prompt suggestions) runs on the model that agent is on. Claude
18
+ // Code names its small model itself, so the rest that reaches routing (a
19
+ // safety check, a web search) runs on the cheapest model.
15
20
  export function auxiliaryDecision(
16
21
  prepared: PreparedRoutedCompletion,
17
22
  ): RoutedDecision | null {
18
23
  if (!isBackgroundRequest(prepared.interaction)) return null;
19
24
  assertCreditAvailableBeforeRouting(prepared.billable, prepared.credentials);
20
25
  const requestClass = prepared.interaction.agentContext!.requestClass;
26
+ const agent = agentCandidate(prepared);
27
+ if (agent) {
28
+ return {
29
+ decision: {
30
+ selectedModel: agent.model,
31
+ reasoningEffort: agent.reasoningEffort,
32
+ reason: `${requestClass} request served on its agent's model without selection.`,
33
+ },
34
+ };
35
+ }
21
36
  const cheapest = cheapestCandidate(prepared);
22
37
  if (!cheapest) {
23
38
  throw new HttpError(503, "Background requests require a routable model with known pricing.",
@@ -32,6 +47,22 @@ export function auxiliaryDecision(
32
47
  return { decision };
33
48
  }
34
49
 
50
+ /* The pair the agent is on (its lease target, else what it was last served)
51
+ or, when this request cannot take that pair (a forced tool rules out
52
+ thinking), one of those models at a level it can. */
53
+ function agentCandidate(prepared: PreparedRoutedCompletion): RoutingCandidate | null {
54
+ const row = prepared.agentRow;
55
+ if (row === undefined) return null;
56
+ const candidates = prepared.routing.candidateResolution.candidates;
57
+ const pair = previousDecisionFromHit(row, candidates);
58
+ if (pair) return { model: pair.model, reasoningEffort: pair.reasoningEffort };
59
+ for (const model of [row.next_model, row.model]) {
60
+ const candidate = candidates.find((candidate) => candidate.model === model);
61
+ if (candidate) return candidate;
62
+ }
63
+ return null;
64
+ }
65
+
35
66
  /* Ranked on estimated input cost: these requests carry a whole transcript in
36
67
  and a sentence out, so the prompt dominates. Estimates cover the configured
37
68
  roster, so they are narrowed to the candidates pruning actually left
@@ -1,4 +1,8 @@
1
- import type { CandidatePruningAudit } from "@mupt-ai/dari-router/policy-engine";
1
+ import {
2
+ newestConversationHit,
3
+ type CandidatePruningAudit,
4
+ type RouterPrefixHit,
5
+ } from "@mupt-ai/dari-router/policy-engine";
2
6
 
3
7
  import { interactionConversationPrefix } from "../context/interaction_fingerprint.js";
4
8
  import { clampRequestedEffort } from "../context/routing_context.js";
@@ -13,7 +17,12 @@ import { isBackgroundRequest, type InteractionRequest } from "../interaction/typ
13
17
  import { executionProviderForModel } from "../models/execution_provider.js";
14
18
  import { codexModelConfig, subscriptionServes } from "../models/subscriptions.js";
15
19
  import { explicitModelId } from "../protocol/input/router_model.js";
16
- import { gatewayPlatform, type RequestTags, type SessionPin } from "../platform/platform.js";
20
+ import {
21
+ gatewayPlatform,
22
+ type RequestTags,
23
+ type ResolveRouterRequest,
24
+ type SessionPin,
25
+ } from "../platform/platform.js";
17
26
  import { resolveRouter } from "../strategies/routing.js";
18
27
  import { RequestReporter, type ReportedCandidatePruning } from "../telemetry/report.js";
19
28
  import { RoutingBillingFinalization } from "../telemetry/billing_finalization.js";
@@ -29,6 +38,7 @@ import {
29
38
  scopedHarnessConversationId,
30
39
  scopedHarnessSessionId,
31
40
  type HarnessConversationIdentity,
41
+ type HarnessConversationScope,
32
42
  } from "./harness_identity/index.js";
33
43
 
34
44
  export type PreparedRoutedCompletion = {
@@ -50,6 +60,9 @@ export type PreparedRoutedCompletion = {
50
60
  // The router's prompt for this request's role, appended to the system
51
61
  // prompt sent to the provider. Routing and prefix matching never see it.
52
62
  rolePrompt?: string;
63
+ // For routed background work: the latest row of the conversation of the
64
+ // agent it works for, naming the model that agent is on.
65
+ agentRow?: RouterPrefixHit;
53
66
  reporter: RoutedRuntimeReporter;
54
67
  };
55
68
 
@@ -143,6 +156,20 @@ export async function prepareRoutedCompletion(args: {
143
156
  }
144
157
  credentials = conversationCredentials;
145
158
  }
159
+ // Claude Code runs compaction, side questions and its other forked work on
160
+ // the model of the agent they serve. On routing, that is the model the
161
+ // agent's conversation is on, read from its latest row.
162
+ const agentRow = background
163
+ && args.harnessConversationIdentity !== undefined
164
+ && credentials.strict !== true
165
+ && explicitModelId(args.interaction.model) === null
166
+ ? await agentConversationRow({
167
+ resolveRequest: { routerId: args.routerId, apiKey: args.apiKey, clientHarness: args.clientHarness },
168
+ identity: args.harnessConversationIdentity,
169
+ interaction: args.interaction,
170
+ scope: harnessScope,
171
+ })
172
+ : undefined;
146
173
  const roleModel = withRoleModel(credentials, args.interaction);
147
174
  const prompt = rolePrompt(credentials, args.interaction);
148
175
  const strictAccess = strictProviderAccess(credentials, roleModel.interaction);
@@ -241,10 +268,41 @@ export async function prepareRoutedCompletion(args: {
241
268
  ...(sessionPin === undefined ? {} : { sessionPin }),
242
269
  ...(roleModel.role === undefined ? {} : { role: roleModel.role }),
243
270
  ...(prompt === undefined ? {} : { rolePrompt: prompt }),
271
+ ...(agentRow === undefined ? {} : { agentRow }),
244
272
  reporter,
245
273
  };
246
274
  }
247
275
 
276
+ /* The latest row of the conversation a background request works for. Forked
277
+ work carries that agent's transcript, so it names the same conversation
278
+ under the agent's own request class. An agent with an id is usually a
279
+ subagent, which Claude Code may have run as a workflow agent, but may be a
280
+ main agent (an Agent Teams teammate). Other background work
281
+ (a web search, a safety check) carries its own transcript and finds none. */
282
+ async function agentConversationRow(args: {
283
+ resolveRequest: Pick<ResolveRouterRequest, "routerId" | "apiKey" | "clientHarness">;
284
+ identity: HarnessConversationIdentity;
285
+ interaction: InteractionRequest;
286
+ scope: HarnessConversationScope;
287
+ }): Promise<RouterPrefixHit | undefined> {
288
+ const namedAgent = (args.identity.qualifiers?.length ?? 0) > 0
289
+ || (args.identity.kind === "codex_thread" && args.identity.parentThreadId !== undefined);
290
+ const prefix = interactionConversationPrefix(args.interaction);
291
+ for (const requestClass of namedAgent ? ["subagent", "workflow", "main"] : ["main"]) {
292
+ const conversationId = scopedHarnessConversationId({
293
+ identity: args.identity,
294
+ sourceProtocol: args.interaction.sourceProtocol,
295
+ scope: args.scope,
296
+ conversationPrefix: JSON.stringify([requestClass, prefix]),
297
+ });
298
+ // Read-only: none of this resolve's credentials serve the request.
299
+ const resolved = await resolveRouter({ ...args.resolveRequest, conversationId, provisional: true });
300
+ const row = newestConversationHit(resolved.prefix_hits, conversationId)?.entry;
301
+ if (row !== undefined) return row;
302
+ }
303
+ return undefined;
304
+ }
305
+
248
306
  // Ask the platform for each enabled model's credential up front, so provider
249
307
  // execution stays synchronous.
250
308
  async function withProviderCredentials(