@mupt-ai/dari-gateway 1.0.366 → 1.0.368

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/README.md +4 -3
  2. package/dist/activity/conversation_detail.js +8 -0
  3. package/dist/link/client.d.ts +3 -1
  4. package/dist/link/client.js +4 -1
  5. package/dist/link/endpoints.js +38 -30
  6. package/dist/link/service.d.ts +1 -3
  7. package/dist/link/service.js +0 -1
  8. package/dist/platform/platform.d.ts +1 -11
  9. package/dist/protocol/input/anthropic_messages.js +3 -4
  10. package/dist/protocol/input/chat_completions.js +9 -13
  11. package/dist/protocol/input/chat_completions_validation.js +2 -7
  12. package/dist/protocol/input/openai_responses.js +3 -3
  13. package/dist/providers/execution.js +1 -0
  14. package/dist/providers/provider_call.d.ts +1 -0
  15. package/dist/providers/provider_call.js +1 -0
  16. package/dist/runtime/runtime_reporter.d.ts +1 -0
  17. package/dist/runtime/runtime_reporter.js +1 -0
  18. package/dist/self_host/connected.d.ts +5 -4
  19. package/dist/self_host/hosted_sync.d.ts +14 -23
  20. package/dist/self_host/hosted_sync.js +56 -120
  21. package/dist/self_host/main.js +0 -3
  22. package/dist/self_host/platform.js +2 -0
  23. package/dist/self_host/resolve.js +2 -1
  24. package/dist/self_host/stub_gateway.d.ts +1 -0
  25. package/dist/self_host/stub_gateway.js +7 -6
  26. package/dist/self_host/stub_main.js +1 -1
  27. package/dist/self_host/subscriptions/index.d.ts +1 -1
  28. package/dist/self_host/subscriptions/index.js +1 -1
  29. package/dist/self_host/subscriptions/store.d.ts +8 -6
  30. package/dist/self_host/subscriptions/store.js +8 -16
  31. package/dist/telemetry/report.js +8 -1
  32. package/dist/types.d.ts +1 -0
  33. package/package.json +2 -2
  34. package/src/activity/conversation_detail.ts +8 -0
  35. package/src/link/client.ts +7 -1
  36. package/src/link/endpoints.ts +42 -34
  37. package/src/link/service.ts +0 -4
  38. package/src/platform/platform.ts +2 -9
  39. package/src/protocol/input/anthropic_messages.ts +3 -9
  40. package/src/protocol/input/chat_completions.ts +8 -18
  41. package/src/protocol/input/chat_completions_validation.ts +2 -9
  42. package/src/protocol/input/openai_responses.ts +3 -8
  43. package/src/providers/execution.ts +1 -0
  44. package/src/providers/provider_call.ts +3 -0
  45. package/src/runtime/runtime_reporter.ts +3 -1
  46. package/src/self_host/connected.ts +5 -4
  47. package/src/self_host/hosted_sync.ts +51 -121
  48. package/src/self_host/main.ts +0 -3
  49. package/src/self_host/platform.ts +2 -1
  50. package/src/self_host/resolve.ts +2 -0
  51. package/src/self_host/stub_gateway.ts +12 -7
  52. package/src/self_host/stub_main.ts +1 -1
  53. package/src/self_host/subscriptions/index.ts +1 -0
  54. package/src/self_host/subscriptions/store.ts +14 -18
  55. package/src/telemetry/report.ts +8 -1
  56. package/src/types.ts +3 -0
@@ -1118,8 +1118,8 @@ function oauthError(
1118
1118
  * secret alone: no state or PKCE for the app to keep. JSON body:
1119
1119
  * `client_id`, `secret` (or HTTP Basic), and optionally `redirect_uri` (one
1120
1120
  * the app registered; default its first), `plans`, `client`, `key_providers`
1121
- * (arrays), `purposes` ({ any_app, claude_code, muse_code }), and `grant_id`
1122
- * for update mode.
1121
+ * (arrays), `purposes` ({ any_app, claude_code, muse_code }), `allow_pooling`
1122
+ * (true), and `grant_id` for update mode.
1123
1123
  */
1124
1124
  async function createLinkToken(link: LinkPlatform, request: Request): Promise<Response> {
1125
1125
  let body: Record<string, unknown>;
@@ -1143,6 +1143,7 @@ async function createLinkToken(link: LinkPlatform, request: Request): Promise<Re
1143
1143
  ...(list("plans") ? { plans: list("plans") } : {}),
1144
1144
  ...(list("client") ? { client: list("client") } : {}),
1145
1145
  ...(list("key_providers") ? { key_providers: list("key_providers") } : {}),
1146
+ ...(body.allow_pooling === true ? { allow_pooling: "true" } : {}),
1146
1147
  ...(typeof body.grant_id === "string" ? { grant_id: body.grant_id } : {}),
1147
1148
  ...Object.fromEntries(PLAN_AUDIENCES.flatMap((audience) =>
1148
1149
  typeof purposes[audience] === "string" ? [[`purpose_${audience}`, purposes[audience] as string]] : []
@@ -1210,6 +1211,9 @@ type AuthorizeRequest = {
1210
1211
  keyProviders: string[] | null;
1211
1212
  // What the app says it does with each audience's plans, shown beside them.
1212
1213
  purposes: Partial<Record<PlanAudience, string>>;
1214
+ // Whether the user may share several accounts of one provider, which Dari
1215
+ // then pools; by default one per provider.
1216
+ allowPooling: boolean;
1213
1217
  // Update mode: the user's grant for this app whose plans to change in place.
1214
1218
  grantId: string | null;
1215
1219
  };
@@ -1282,6 +1286,10 @@ async function authorizeRequest(link: LinkPlatform, params: URLSearchParams): Pr
1282
1286
  const purpose = params.get(`purpose_${audience}`)?.trim();
1283
1287
  if (purpose) purposes[audience] = purpose.slice(0, MAX_PURPOSE_CHARS);
1284
1288
  }
1289
+ const allowPooling = params.get("allow_pooling");
1290
+ if (allowPooling !== null && allowPooling !== "true" && allowPooling !== "false") {
1291
+ return badRequest("allow_pooling is true or false.");
1292
+ }
1285
1293
  const grantId = params.get("grant_id");
1286
1294
  if (grantId !== null && !GRANT_ID.test(grantId)) {
1287
1295
  return badRequest("grant_id names one of the user's grants for this app.");
@@ -1296,6 +1304,7 @@ async function authorizeRequest(link: LinkPlatform, params: URLSearchParams): Pr
1296
1304
  plans: plans.length === 0 ? null : plans as OfferKind[],
1297
1305
  keyProviders: keyProviders.length === 0 ? null : keyProviders,
1298
1306
  purposes,
1307
+ allowPooling: allowPooling === "true",
1299
1308
  grantId,
1300
1309
  };
1301
1310
  }
@@ -1324,32 +1333,9 @@ async function homePage(approval: LinkApprovalPage, authorize: AuthorizeRequest,
1324
1333
  if (current instanceof Response) return current;
1325
1334
  if (session === null) return introPage(approval, authorize);
1326
1335
  const subscriptions = await approval.subscriptions(session.subject);
1327
- const onComputers = await plansOnComputersNote(approval, authorize, session.subject, subscriptions);
1328
1336
  return shareable(authorize, subscriptions).length > 0
1329
- ? choosePage(authorize, session, subscriptions, current, undefined, onComputers)
1330
- : introPage(approval, authorize, onComputers);
1331
- }
1332
-
1333
- // Where the user keeps a plan the app could use on one of their computers,
1334
- // for each kind they have no plan of here: apps reach only the platform's.
1335
- async function plansOnComputersNote(
1336
- approval: LinkApprovalPage,
1337
- authorize: AuthorizeRequest,
1338
- subject: string,
1339
- subscriptions: LinkSubscription[],
1340
- ): Promise<string> {
1341
- if (approval.plansOnComputers === undefined) return "";
1342
- const here = new Set(subscriptions.map((subscription) => subscription.provider));
1343
- const usable = new Set(connectKinds(approval, authorize));
1344
- const computers = new Map<SubscriptionKind, string[]>();
1345
- for (const plan of await approval.plansOnComputers(subject)) {
1346
- if (here.has(plan.provider) || !usable.has(plan.provider)) continue;
1347
- const names = computers.get(plan.provider) ?? [];
1348
- if (!names.includes(plan.computer)) names.push(plan.computer);
1349
- computers.set(plan.provider, names);
1350
- }
1351
- return [...computers].map(([kind, names]) =>
1352
- `<p class="hint">Your ${KINDS[kind].name} plan is on ${escapeHtml(names.join(" and "))}. Apps can only use plans on Dari.</p>`).join("\n");
1337
+ ? choosePage(authorize, session, subscriptions, current)
1338
+ : introPage(approval, authorize);
1353
1339
  }
1354
1340
 
1355
1341
  // In update mode, the grant being changed. A grant this browser's user does
@@ -1451,6 +1437,12 @@ async function authorizeSubmit(link: LinkPlatform, request: Request, form: URLSe
1451
1437
  if (!credentialIds.every((id) => usable.has(id))) {
1452
1438
  return choosePage(authorize, session, subscriptions, current, `${authorize.app.name} cannot use one of the plans you chose.`);
1453
1439
  }
1440
+ const pooled = authorize.allowPooling ? undefined : subscriptions.find((subscription, index) =>
1441
+ credentialIds.includes(subscription.id)
1442
+ && subscriptions.slice(0, index).some((other) => credentialIds.includes(other.id) && pool(other) === pool(subscription)));
1443
+ if (pooled !== undefined) {
1444
+ return choosePage(authorize, session, subscriptions, current, `${authorize.app.name} uses one account per provider: choose one ${planName(pooled)}${pooled.apiKeyProvider === undefined ? " account" : ""}.`);
1445
+ }
1454
1446
  const limits = limitsFromForm(form, credentialIds);
1455
1447
  if (limits === null) return choosePage(authorize, session, subscriptions, current, LIMITS_ERROR);
1456
1448
  try {
@@ -1887,7 +1879,7 @@ const KINDS: Record<SubscriptionKind, { name: string; plan: string; at: string;
1887
1879
  };
1888
1880
 
1889
1881
  // The first page a new user sees: what connecting means, and one button.
1890
- function introPage(approval: LinkApprovalPage, authorize: AuthorizeRequest, onComputers = ""): Response {
1882
+ function introPage(approval: LinkApprovalPage, authorize: AuthorizeRequest): Response {
1891
1883
  const app = escapeHtml(authorize.app.name);
1892
1884
  const kinds = connectKinds(approval, authorize);
1893
1885
  const keys = keyProviders(approval, authorize);
@@ -1909,7 +1901,7 @@ function introPage(approval: LinkApprovalPage, authorize: AuthorizeRequest, onCo
1909
1901
  <ul class="points">
1910
1902
  <li>${ICONS.zap}<div><strong>Connect In Seconds</strong><p>${kinds.length > 0 ? `Use what you already pay for: ${escapeHtml(ways)}.` : "Add the API key you already have."}</p></div></li>
1911
1903
  <li>${ICONS.shield}<div><strong>You Stay In Control</strong><p>${app} can only send model requests on what you share. It sees each shared plan's account email, never a key or your other plans, and you can disconnect it any time.</p></div></li>
1912
- </ul>${onComputers}`,
1904
+ </ul>`,
1913
1905
  footer: `<button class="btn primary" type="submit" name="decision" value="select">Continue</button>`,
1914
1906
  });
1915
1907
  }
@@ -2006,12 +1998,16 @@ function choosePage(
2006
1998
  subscriptions: LinkSubscription[],
2007
1999
  current: GrantToUpdate | null,
2008
2000
  error?: string,
2009
- onComputers = "",
2010
2001
  ): Response {
2011
2002
  const app = escapeHtml(authorize.app.name);
2012
2003
  const plans = shareable(authorize, subscriptions);
2013
- // A new connection starts with every plan ticked; an update, with the plans it shares now.
2014
- const ticked = new Set(current?.credentialIds ?? plans.map((plan) => plan.id));
2004
+ // A new connection starts with every plan ticked; an update, with the plans
2005
+ // it shares now. Without pooling, only the first of each provider's, so an
2006
+ // update of a grant made with pooling saves as it opens.
2007
+ const candidates = plans.filter((plan) => current === null || current.credentialIds.includes(plan.id));
2008
+ const ticked = new Set(candidates
2009
+ .filter((plan, index) => authorize.allowPooling || !candidates.slice(0, index).some((other) => pool(other) === pool(plan)))
2010
+ .map((plan) => plan.id));
2015
2011
  return pane(authorize, {
2016
2012
  title: current === null ? `Connect ${authorize.app.name}` : `Update Plans For ${authorize.app.name}`,
2017
2013
  step: "choose_plans",
@@ -2021,7 +2017,6 @@ function choosePage(
2021
2017
  <!-- First in the form, so Enter in a limit field allows rather than pressing Connect Another. -->
2022
2018
  <button type="submit" name="decision" value="approve" tabindex="-1" aria-hidden="true" style="position:absolute;left:-9999px"></button>
2023
2019
  ${plans.map((plan) => planOption(authorize, plan, ticked.has(plan.id))).join("\n")}
2024
- ${onComputers}
2025
2020
  <details${current?.limits.length ? " open" : ""}><summary>Set Limits</summary>
2026
2021
  ${plans.map((plan) => {
2027
2022
  const set = current?.limits.find((limit) => limit.credentialId === plan.id);
@@ -2035,8 +2030,15 @@ ${plans.map((plan) => {
2035
2030
  });
2036
2031
  }
2037
2032
 
2033
+ // Plans and keys of one pool: one kind of plan, or one provider's API keys.
2034
+ function pool(subscription: LinkSubscription): string {
2035
+ return subscription.apiKeyProvider === undefined ? subscription.provider : `api_key:${subscription.apiKeyProvider}`;
2036
+ }
2037
+
2038
2038
  function planOption(authorize: AuthorizeRequest, subscription: LinkSubscription, ticked: boolean): string {
2039
- const box = `<input type="checkbox" name="credential_id" value="${escapeHtml(subscription.id)}"${ticked ? " checked" : ""}>`;
2039
+ // Without pooling, ticking one of a pool unticks the rest (see `page`).
2040
+ const pooled = authorize.allowPooling ? "" : ` data-pool="${escapeHtml(pool(subscription))}"`;
2041
+ const box = `<input type="checkbox"${pooled} name="credential_id" value="${escapeHtml(subscription.id)}"${ticked ? " checked" : ""}>`;
2040
2042
  if (subscription.apiKeyProvider !== undefined) {
2041
2043
  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>`;
2042
2044
  }
@@ -2081,6 +2083,7 @@ function authorizeFields(authorize: AuthorizeRequest): Record<string, string> {
2081
2083
  ...(authorize.clients.length > 0 ? { client: authorize.clients.join(" ") } : {}),
2082
2084
  ...(authorize.plans !== null ? { plans: authorize.plans.join(" ") } : {}),
2083
2085
  ...(authorize.keyProviders !== null ? { key_providers: authorize.keyProviders.join(" ") } : {}),
2086
+ ...(authorize.allowPooling ? { allow_pooling: "true" } : {}),
2084
2087
  ...Object.fromEntries(Object.entries(authorize.purposes).map(([audience, purpose]) => [`purpose_${audience}`, purpose])),
2085
2088
  ...(authorize.grantId !== null ? { grant_id: authorize.grantId } : {}),
2086
2089
  };
@@ -2141,6 +2144,11 @@ function page(
2141
2144
  const button = event.submitter;
2142
2145
  if (!(button instanceof HTMLButtonElement) || button.form?.target) return;
2143
2146
  setTimeout(() => { button.disabled = true; button.setAttribute("aria-busy", "true"); button.prepend(Object.assign(document.createElement("span"), { className: "spin" })); });
2147
+ });
2148
+ document.addEventListener("change", (event) => {
2149
+ const box = event.target;
2150
+ if (!(box instanceof HTMLInputElement) || !box.checked || !box.dataset.pool) return;
2151
+ for (const other of box.form?.querySelectorAll("input[data-pool]") ?? []) if (other !== box && other.dataset.pool === box.dataset.pool) other.checked = false;
2144
2152
  });</script>`;
2145
2153
  options = { ...options, scriptNonce: busyNonce };
2146
2154
  if (options.event !== undefined) {
@@ -22,7 +22,6 @@ import type {
22
22
  LinkLimit,
23
23
  LinkManagedGrant,
24
24
  LinkPlanAdded,
25
- LinkPlanOnComputer,
26
25
  LinkPlatform,
27
26
  LinkSignIn,
28
27
  LinkSpend,
@@ -150,8 +149,6 @@ export type LinkUsers = {
150
149
  completeThrough(grantId: string): string | null;
151
150
  /** A user's plans and API keys, oldest first. */
152
151
  plans(subject: string): Promise<LinkSubscription[]>;
153
- /** See `LinkApprovalPage.plansOnComputers`. */
154
- plansOnComputers?(subject: string): Promise<LinkPlanOnComputer[]>;
155
152
  /** The plans and API keys with these ids, whoever added them. */
156
153
  plansWithIds(ids: readonly string[]): Promise<LinkSubscription[]>;
157
154
  /** See `LinkApprovalPage.addKey`; the provider is one of `keyProviders`. */
@@ -241,7 +238,6 @@ export function linkPlatform(store: LinkStore, users: LinkUsers): LinkPlatform {
241
238
  connectable: users.connectable,
242
239
  keyProviders: users.keyProviders,
243
240
  subscriptions: (subject) => users.plans(subject),
244
- ...(users.plansOnComputers === undefined ? {} : { plansOnComputers: users.plansOnComputers }),
245
241
  async addKey(subject, provider, apiKey) {
246
242
  if (!users.keyProviders.some((candidate) => candidate.id === provider)) {
247
243
  throw new HttpError(400, "Choose a provider to add a key for.", "invalid_request");
@@ -242,12 +242,6 @@ export type LinkApprovalPage = {
242
242
  addKey(subject: string | null, provider: string, apiKey: string): Promise<LinkPlanAdded>;
243
243
  /** The plans this user connected and the API keys they added, which an approval chooses among. */
244
244
  subscriptions(subject: string): Promise<LinkSubscription[]>;
245
- /**
246
- * The user's plans that live on one of their computers rather than on the
247
- * platform, which apps cannot use; the page says where each is. Absent on
248
- * a platform where every plan is its own.
249
- */
250
- plansOnComputers?(subject: string): Promise<LinkPlanOnComputer[]>;
251
245
  /** Start the provider's sign-in for a plan of this kind. */
252
246
  startConnect(kind: SubscriptionKind): Promise<LinkConnect>;
253
247
  /**
@@ -296,9 +290,6 @@ export type LinkSignIn = {
296
290
  redeem(ticket: string): Promise<{ subject: string; state: string; issuedAt: number } | null>;
297
291
  };
298
292
 
299
- /** A plan kept on one of the user's computers: its kind and the computer's name. */
300
- export type LinkPlanOnComputer = { provider: SubscriptionKind; computer: string };
301
-
302
293
  /** A plan or API key the user added, and who they are now. */
303
294
  export type LinkPlanAdded = { subject: string; credentialId: string };
304
295
 
@@ -592,6 +583,8 @@ export type NextSubscriptionRequest = {
592
583
 
593
584
  export type NextSubscription = {
594
585
  credentialId: string;
586
+ // The plan's name, as ProviderCredential.account.
587
+ account?: string;
595
588
  // The plan's access token, sent as the bearer credential.
596
589
  apiKey: string;
597
590
  };
@@ -384,17 +384,11 @@ function anthropicReasoningItem(
384
384
  type === "thinking" ? block.signature : block.data,
385
385
  `${param}.${type === "thinking" ? "signature" : "data"}`
386
386
  );
387
+ // A conversation begun on Anthropic directly carries raw signatures. They
388
+ // name no provider or model, so they cannot be replayed; the turn keeps its
389
+ // readable thinking and the conversation continues.
387
390
  const continuation = decodeUntrustedProviderContinuationState(encoded);
388
391
  const portable = continuation ? null : decodeUntrustedPortableReasoningState(encoded);
389
- if (!continuation && !portable) {
390
- const field = type === "thinking" ? "signature" : "data";
391
- throw new HttpError(
392
- 400,
393
- `${param}.${field} must be a Dari reasoning-state envelope; raw provider state has no recoverable provider/model provenance.`,
394
- "invalid_provider_continuation_state",
395
- `${param}.${field}`,
396
- );
397
- }
398
392
  const thinking = type === "thinking" ? requiredStringAllowEmpty(block.thinking, `${param}.thinking`) : "";
399
393
  const reasoning: Extract<InteractionItem, { type: "reasoning" }> = {
400
394
  type: "reasoning",
@@ -43,7 +43,7 @@ export function internalChatCompletionsToInteraction(request: ChatCompletionRequ
43
43
  continue;
44
44
  }
45
45
 
46
- const reasoningItems = chatReasoningItems(message, messageIndex);
46
+ const reasoningItems = chatReasoningItems(message);
47
47
  items.push(...reasoningItems);
48
48
  items.push({
49
49
  type: "message",
@@ -171,17 +171,17 @@ function hostedToolCallStatus(
171
171
  throw new HttpError(400, `${param} is not supported.`, "invalid_request_error", param);
172
172
  }
173
173
 
174
- function chatReasoningItems(message: ChatMessage, messageIndex: number): InteractionItem[] {
174
+ function chatReasoningItems(message: ChatMessage): InteractionItem[] {
175
175
  if (message.role !== "assistant") return [];
176
176
  const readable = [message.reasoning_content, message.reasoning, message.reasoning_text]
177
177
  .find((value) => typeof value === "string" && value.length > 0);
178
- const continuations = (message.reasoning_details ?? []).map((detail, detailIndex) => {
179
- if (detail.type !== "reasoning.encrypted" || typeof detail.data !== "string") {
180
- throw invalidChatContinuation(messageIndex, detailIndex);
181
- }
178
+ // A conversation begun on another provider carries that provider's reasoning
179
+ // details. They name no provider or model, so they cannot be replayed; the
180
+ // turn keeps its readable reasoning and the conversation continues.
181
+ const continuations = (message.reasoning_details ?? []).flatMap((detail) => {
182
+ if (detail.type !== "reasoning.encrypted" || typeof detail.data !== "string") return [];
182
183
  const continuation = decodeUntrustedProviderContinuationState(detail.data);
183
- if (!continuation) throw invalidChatContinuation(messageIndex, detailIndex);
184
- return continuation;
184
+ return continuation ? [continuation] : [];
185
185
  });
186
186
  if (continuations.length === 0) {
187
187
  return readable
@@ -197,16 +197,6 @@ function chatReasoningItems(message: ChatMessage, messageIndex: number): Interac
197
197
  }));
198
198
  }
199
199
 
200
- function invalidChatContinuation(messageIndex: number, detailIndex: number): HttpError {
201
- const param = `messages.${messageIndex}.reasoning_details.${detailIndex}.data`;
202
- return new HttpError(
203
- 400,
204
- `${param} must be a Dari provider continuation envelope; raw provider state has no recoverable provider/model provenance.`,
205
- "invalid_provider_continuation_state",
206
- param,
207
- );
208
- }
209
-
210
200
  function contentShape(content: ChatMessage["content"]): InteractionMessage["contentShape"] {
211
201
  if (content === undefined) return "absent";
212
202
  if (content === null) return "null";
@@ -83,17 +83,10 @@ function validateMessageReasoning(message: Record<string, unknown>, messageIndex
83
83
  );
84
84
  }
85
85
  for (const [detailIndex, detail] of message.reasoning_details.entries()) {
86
- if (
87
- !isRecord(detail) ||
88
- detail.type !== "reasoning.encrypted" ||
89
- typeof detail.id !== "string" ||
90
- !detail.id ||
91
- typeof detail.data !== "string" ||
92
- !detail.data
93
- ) {
86
+ if (!isRecord(detail)) {
94
87
  throw new HttpError(
95
88
  400,
96
- `messages[${messageIndex}].reasoning_details[${detailIndex}] is not a supported encrypted reasoning detail.`,
89
+ `messages[${messageIndex}].reasoning_details[${detailIndex}] must be an object.`,
97
90
  "invalid_request_error",
98
91
  `messages.${messageIndex}.reasoning_details.${detailIndex}`
99
92
  );
@@ -383,16 +383,11 @@ function clientTurnId(
383
383
  }
384
384
 
385
385
  function reasoningItem(value: Record<string, unknown>): InteractionItem {
386
+ // A conversation begun on OpenAI directly carries raw ciphertext. It names
387
+ // no provider or model, so it cannot be replayed; the item keeps its
388
+ // readable summary and the conversation continues.
386
389
  const encoded = optionalString(value.encrypted_content, "input.reasoning.encrypted_content");
387
390
  const continuation = encoded ? decodeUntrustedProviderContinuationState(encoded) : null;
388
- if (encoded && !continuation) {
389
- throw new HttpError(
390
- 400,
391
- "input.reasoning.encrypted_content must be a Dari provider continuation envelope; raw provider ciphertext has no recoverable provider/model provenance.",
392
- "invalid_provider_continuation_state",
393
- "input.reasoning.encrypted_content"
394
- );
395
- }
396
391
  return {
397
392
  type: "reasoning",
398
393
  id: optionalString(value.id, "input.reasoning.id"),
@@ -942,6 +942,7 @@ function onNextSubscription(choice: ProviderChoice, next: NextSubscription): Pro
942
942
  apiKey: next.apiKey,
943
943
  auth: { type: "bearer", apiKey: next.apiKey },
944
944
  subscriptionCredentialId: next.credentialId,
945
+ subscriptionAccount: next.account,
945
946
  },
946
947
  };
947
948
  }
@@ -79,6 +79,8 @@ export type ProviderExecution = ProviderCallConfig & {
79
79
  // subscriptions it is; undefined for router-owned keys.
80
80
  subscriptionUserId?: string;
81
81
  subscriptionCredentialId?: string;
82
+ // That plan's name, as ProviderCredential.account.
83
+ subscriptionAccount?: string;
82
84
  // The Dari Link grant whose subscriptions alone may serve this call.
83
85
  subscriptionLinkGrantId?: string;
84
86
  // The model's sources and the router's reset threshold, carried onto the
@@ -177,6 +179,7 @@ export function prepareProviderExecution(args: {
177
179
  ...(args.credentials.link_grant_id ? { subscriptionLinkGrantId: args.credentials.link_grant_id } : {}),
178
180
  }
179
181
  : {}),
182
+ ...(providerKeySource === "subscription" && supplied?.account ? { subscriptionAccount: supplied.account } : {}),
180
183
  thinkingLevel,
181
184
  usageContext: usageContextFor({
182
185
  billable: args.billable,
@@ -9,8 +9,9 @@ export type ReportedProviderExecution = {
9
9
  providerKeySource: ProviderKeySource;
10
10
  // The thinking the provider was sent, as X-Dari-Thinking-Level reports it.
11
11
  thinkingLevel?: string;
12
- // The user's subscription that served it.
12
+ // The user's subscription that served it, and its name.
13
13
  subscriptionCredentialId?: string;
14
+ subscriptionAccount?: string;
14
15
  };
15
16
 
16
17
  export function reportedExecution(
@@ -24,6 +25,7 @@ export function reportedExecution(
24
25
  ...(execution.subscriptionCredentialId === undefined
25
26
  ? {}
26
27
  : { subscriptionCredentialId: execution.subscriptionCredentialId }),
28
+ ...(execution.subscriptionAccount === undefined ? {} : { subscriptionAccount: execution.subscriptionAccount }),
27
29
  };
28
30
  }
29
31
 
@@ -26,10 +26,11 @@ import { gatewayKeyIndex, resolveSelfHostedRouter } from "./resolve.js";
26
26
  * Dari key (resolve.ts).
27
27
  * - Every other path the gateway does not manage itself, such as commit
28
28
  * reports, goes to hosted with the user's Dari key.
29
- * - The plans and the requests served here sync to hosted (hosted_sync.ts),
30
- * which shows them in Accounts and Activity. Private plans serve, but
31
- * neither they nor their requests sync; requests hosted Dari served are
32
- * hosted's to log. Dari Link and Activity are hosted's, not served here.
29
+ * - The requests served here sync to hosted Activity (hosted_sync.ts), each
30
+ * naming the plan that served it. The plans themselves never leave this
31
+ * computer. A private plan's requests do not sync either; requests hosted
32
+ * Dari served are hosted's to log. Dari Link and Activity are hosted's, not
33
+ * served here.
33
34
  */
34
35
  export type HostedConnection = {
35
36
  // The hosted routing service, e.g. https://routing.dari.dev.