@mupt-ai/dari-gateway 1.0.367 → 1.0.369

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 (80) hide show
  1. package/README.md +4 -3
  2. package/dist/link/client.d.ts +3 -1
  3. package/dist/link/client.js +4 -1
  4. package/dist/link/endpoints.js +33 -5
  5. package/dist/link/self_hosted.js +0 -1
  6. package/dist/platform/platform.d.ts +2 -0
  7. package/dist/platform/routing_contract.d.ts +1 -0
  8. package/dist/platform/routing_contract.js +4 -0
  9. package/dist/protocol/input/chat_completions.js +9 -13
  10. package/dist/protocol/input/chat_completions_validation.js +2 -7
  11. package/dist/protocol/input/openai_responses.js +3 -3
  12. package/dist/protocol/output/anthropic_messages.d.ts +1 -0
  13. package/dist/protocol/output/anthropic_messages.js +1 -1
  14. package/dist/protocol/output/anthropic_messages_output.d.ts +1 -1
  15. package/dist/protocol/output/anthropic_messages_output.js +3 -1
  16. package/dist/protocol/output/anthropic_messages_stream.d.ts +1 -0
  17. package/dist/protocol/output/anthropic_messages_stream.js +1 -1
  18. package/dist/protocol/output/chat_completions.d.ts +2 -0
  19. package/dist/protocol/output/chat_completions.js +5 -3
  20. package/dist/protocol/output/openai_responses.d.ts +1 -0
  21. package/dist/protocol/output/openai_responses.js +1 -1
  22. package/dist/protocol/output/openai_responses_output.d.ts +1 -1
  23. package/dist/protocol/output/openai_responses_output.js +3 -1
  24. package/dist/protocol/output/openai_responses_stream.d.ts +1 -0
  25. package/dist/protocol/output/openai_responses_stream.js +1 -1
  26. package/dist/providers/execution.js +2 -0
  27. package/dist/providers/provider_call.d.ts +1 -0
  28. package/dist/providers/provider_call.js +2 -0
  29. package/dist/runtime/prepare_routed_completion.d.ts +1 -0
  30. package/dist/runtime/prepare_routed_completion.js +4 -0
  31. package/dist/runtime/routed_completion.js +2 -0
  32. package/dist/runtime/routed_protocol.d.ts +2 -0
  33. package/dist/self_host/connected.d.ts +7 -3
  34. package/dist/self_host/connected.js +9 -10
  35. package/dist/self_host/hosted_sync.js +1 -1
  36. package/dist/self_host/main.d.ts +3 -2
  37. package/dist/self_host/main.js +16 -6
  38. package/dist/self_host/private_mode.d.ts +16 -0
  39. package/dist/self_host/private_mode.js +35 -0
  40. package/dist/self_host/resolve.js +5 -2
  41. package/dist/self_host/stub_gateway.d.ts +1 -0
  42. package/dist/self_host/stub_gateway.js +7 -6
  43. package/dist/self_host/stub_main.js +1 -1
  44. package/dist/self_host/subscriptions/http.js +2 -17
  45. package/dist/self_host/subscriptions/store.d.ts +7 -6
  46. package/dist/self_host/subscriptions/store.js +15 -27
  47. package/dist/telemetry/report.js +1 -0
  48. package/dist/types.d.ts +1 -0
  49. package/package.json +2 -2
  50. package/src/link/client.ts +7 -1
  51. package/src/link/endpoints.ts +38 -5
  52. package/src/link/self_hosted.ts +0 -1
  53. package/src/platform/platform.ts +6 -0
  54. package/src/platform/routing_contract.ts +5 -0
  55. package/src/protocol/input/chat_completions.ts +8 -18
  56. package/src/protocol/input/chat_completions_validation.ts +2 -9
  57. package/src/protocol/input/openai_responses.ts +3 -8
  58. package/src/protocol/output/anthropic_messages.ts +2 -1
  59. package/src/protocol/output/anthropic_messages_output.ts +4 -1
  60. package/src/protocol/output/anthropic_messages_stream.ts +2 -1
  61. package/src/protocol/output/chat_completions.ts +7 -3
  62. package/src/protocol/output/openai_responses.ts +2 -1
  63. package/src/protocol/output/openai_responses_output.ts +4 -1
  64. package/src/protocol/output/openai_responses_stream.ts +2 -1
  65. package/src/providers/execution.ts +2 -0
  66. package/src/providers/provider_call.ts +5 -0
  67. package/src/runtime/prepare_routed_completion.ts +4 -0
  68. package/src/runtime/routed_completion.ts +2 -0
  69. package/src/runtime/routed_protocol.ts +2 -0
  70. package/src/self_host/connected.ts +16 -12
  71. package/src/self_host/hosted_sync.ts +1 -1
  72. package/src/self_host/main.ts +14 -6
  73. package/src/self_host/private_mode.ts +41 -0
  74. package/src/self_host/resolve.ts +4 -2
  75. package/src/self_host/stub_gateway.ts +12 -7
  76. package/src/self_host/stub_main.ts +1 -1
  77. package/src/self_host/subscriptions/http.ts +2 -15
  78. package/src/self_host/subscriptions/store.ts +15 -34
  79. package/src/telemetry/report.ts +1 -0
  80. 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
  }
@@ -1428,6 +1437,12 @@ async function authorizeSubmit(link: LinkPlatform, request: Request, form: URLSe
1428
1437
  if (!credentialIds.every((id) => usable.has(id))) {
1429
1438
  return choosePage(authorize, session, subscriptions, current, `${authorize.app.name} cannot use one of the plans you chose.`);
1430
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
+ }
1431
1446
  const limits = limitsFromForm(form, credentialIds);
1432
1447
  if (limits === null) return choosePage(authorize, session, subscriptions, current, LIMITS_ERROR);
1433
1448
  try {
@@ -1986,8 +2001,13 @@ function choosePage(
1986
2001
  ): Response {
1987
2002
  const app = escapeHtml(authorize.app.name);
1988
2003
  const plans = shareable(authorize, subscriptions);
1989
- // A new connection starts with every plan ticked; an update, with the plans it shares now.
1990
- 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));
1991
2011
  return pane(authorize, {
1992
2012
  title: current === null ? `Connect ${authorize.app.name}` : `Update Plans For ${authorize.app.name}`,
1993
2013
  step: "choose_plans",
@@ -2010,8 +2030,15 @@ ${plans.map((plan) => {
2010
2030
  });
2011
2031
  }
2012
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
+
2013
2038
  function planOption(authorize: AuthorizeRequest, subscription: LinkSubscription, ticked: boolean): string {
2014
- 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" : ""}>`;
2015
2042
  if (subscription.apiKeyProvider !== undefined) {
2016
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>`;
2017
2044
  }
@@ -2056,6 +2083,7 @@ function authorizeFields(authorize: AuthorizeRequest): Record<string, string> {
2056
2083
  ...(authorize.clients.length > 0 ? { client: authorize.clients.join(" ") } : {}),
2057
2084
  ...(authorize.plans !== null ? { plans: authorize.plans.join(" ") } : {}),
2058
2085
  ...(authorize.keyProviders !== null ? { key_providers: authorize.keyProviders.join(" ") } : {}),
2086
+ ...(authorize.allowPooling ? { allow_pooling: "true" } : {}),
2059
2087
  ...Object.fromEntries(Object.entries(authorize.purposes).map(([audience, purpose]) => [`purpose_${audience}`, purpose])),
2060
2088
  ...(authorize.grantId !== null ? { grant_id: authorize.grantId } : {}),
2061
2089
  };
@@ -2116,6 +2144,11 @@ function page(
2116
2144
  const button = event.submitter;
2117
2145
  if (!(button instanceof HTMLButtonElement) || button.form?.target) return;
2118
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;
2119
2152
  });</script>`;
2120
2153
  options = { ...options, scriptNonce: busyNonce };
2121
2154
  if (options.event !== undefined) {
@@ -120,7 +120,6 @@ export function selfHostedLink(
120
120
  flow: authorization.flow,
121
121
  credentialName: null,
122
122
  owner: newSubject(),
123
- private: false,
124
123
  movingFrom: null,
125
124
  expiresAt: authorization.expiresAt,
126
125
  });
@@ -507,6 +507,9 @@ export type ResolveRouterRequest = {
507
507
  // The client's own identifying headers (ingress/client_harness.ts), for a
508
508
  // platform that hands the request on.
509
509
  clientHeaders?: Record<string, string>;
510
+ // The request asked to stay out of Activity, as ResolvedRouter.private; a
511
+ // platform that hands it on asks the same.
512
+ private?: boolean;
510
513
  // A later resolve with this request's `conversationId` replaces this one's
511
514
  // credentials, so none from it serve the request: a platform should not
512
515
  // mark a credential used or refresh it for this resolve.
@@ -614,6 +617,9 @@ export type RequestRecord = {
614
617
  link?: { grantId: string; thinking: string | null; costUsd: number | null; credentialId: string | null };
615
618
  // The user's plan that served the request, when one did.
616
619
  subscriptionCredentialId?: string;
620
+ // The request asked to stay out of Activity (ResolvedRouter.private): only
621
+ // what billing needs may be kept.
622
+ private: boolean;
617
623
  // The router's non-secret routing settings, for embedders that compare or
618
624
  // replay routing decisions.
619
625
  router: RequestRecordRouter;
@@ -8,3 +8,8 @@ export const ROUTING_PREFIX_HASHES_MAX_COUNT = 200;
8
8
  // The provider id of hosted Dari when a gateway connected to it calls it for
9
9
  // a model, as `dari/model/<id>` with the user's Dari key.
10
10
  export const HOSTED_DARI_PROVIDER = "dari";
11
+
12
+ // A request with this header set to `true` stays out of Activity: the
13
+ // platform keeps only what billing needs. A gateway in private mode sets it on
14
+ // every request, and on each it hands hosted Dari.
15
+ export const PRIVATE_HEADER = "x-dari-private";
@@ -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"),
@@ -17,6 +17,7 @@ export function anthropicMessagesResponse(args: {
17
17
  request: InteractionRequest;
18
18
  routing: RoutingDecision;
19
19
  conversationId?: string;
20
+ private?: boolean;
20
21
  }): Record<string, unknown> {
21
22
  return {
22
23
  id: anthropicMessageId(args.id),
@@ -29,6 +30,6 @@ export function anthropicMessagesResponse(args: {
29
30
  // As on Chat Completions. Null means unpriced, never a fabricated free request.
30
31
  usage: { ...anthropicUsage(args.output), cost: args.modelCost ?? null },
31
32
  ...(args.output.safeguardResults ? { safeguard_results: args.output.safeguardResults } : {}),
32
- dari_routing: anthropicRouting(args.routing, args.id, args.conversationId),
33
+ dari_routing: anthropicRouting(args.routing, args.id, args.conversationId, args.private),
33
34
  };
34
35
  }
@@ -120,7 +120,8 @@ export function anthropicUsage(output: Pick<InteractionOutput, "usage">): Record
120
120
  export function anthropicRouting(
121
121
  decision: ServedDecision,
122
122
  requestId: string,
123
- conversationId?: string
123
+ conversationId?: string,
124
+ isPrivate?: boolean
124
125
  ): Record<string, unknown> {
125
126
  return {
126
127
  requested_model: "dari/routing",
@@ -129,6 +130,8 @@ export function anthropicRouting(
129
130
  reason: decision.reason,
130
131
  request_id: requestId,
131
132
  ...(conversationId ? { conversation_id: conversationId } : {}),
133
+ // Kept out of Activity, so no link to it there.
134
+ ...(isPrivate ? { private: true } : {}),
132
135
  ...(decision.leaseTurnsRemaining === undefined
133
136
  ? {}
134
137
  : { lease_turns_remaining: decision.leaseTurnsRemaining }),
@@ -24,6 +24,7 @@ export function anthropicMessagesSseStream(args: {
24
24
  source: ProviderIdentity;
25
25
  request: InteractionRequest;
26
26
  conversationId?: string;
27
+ private?: boolean;
27
28
  onFinal?: (outcome: ProviderStreamOutcome) => void;
28
29
  modelCost?: (message: Record<string, unknown>, failed: boolean) => number | null;
29
30
  beforeClose?: (outcome: ProviderStreamOutcome) => Promise<void> | void;
@@ -59,7 +60,7 @@ export function anthropicMessagesSseStream(args: {
59
60
  stop_reason: null,
60
61
  stop_sequence: null,
61
62
  usage: { input_tokens: 0, output_tokens: 0 },
62
- dari_routing: anthropicRouting(args.routing, args.id, args.conversationId),
63
+ dari_routing: anthropicRouting(args.routing, args.id, args.conversationId, args.private),
63
64
  },
64
65
  });
65
66
 
@@ -20,6 +20,7 @@ export function chatCompletionResponse(args: {
20
20
  modelCost?: number | null;
21
21
  routing: RoutingDecision;
22
22
  conversationId?: string;
23
+ private?: boolean;
23
24
  }): Record<string, unknown> {
24
25
  return {
25
26
  id: completionId(args.id),
@@ -34,7 +35,7 @@ export function chatCompletionResponse(args: {
34
35
  },
35
36
  ],
36
37
  usage: usagePayload(args.output, args.modelCost),
37
- dari_routing: routingPayload(args.routing, args.id, args.conversationId),
38
+ dari_routing: routingPayload(args.routing, args.id, args.conversationId, args.private),
38
39
  };
39
40
  }
40
41
 
@@ -46,6 +47,7 @@ export function chatCompletionsSseStream(args: {
46
47
  source: ProviderIdentity;
47
48
  request: InteractionRequest;
48
49
  conversationId?: string;
50
+ private?: boolean;
49
51
  onFinal?: (outcome: ProviderStreamOutcome) => void;
50
52
  modelCost?: (message: Record<string, unknown>, failed: boolean) => number | null;
51
53
  // Optional terminal barrier. Streaming deltas are unaffected, but [DONE]
@@ -75,7 +77,7 @@ export function chatCompletionsSseStream(args: {
75
77
  usage: usagePayload(message, args.modelCost?.(message, true)) });
76
78
  };
77
79
 
78
- send(chunk({ completion, created, model: args.model, delta: {}, finishReason: null, routing: routingPayload(args.routing, args.id, args.conversationId) }));
80
+ send(chunk({ completion, created, model: args.model, delta: {}, finishReason: null, routing: routingPayload(args.routing, args.id, args.conversationId, args.private) }));
79
81
  send(chunk({ completion, created, model: args.model, delta: { role: "assistant" }, finishReason: null }));
80
82
 
81
83
  const argumentDeltaSeen = new Set<string>();
@@ -208,7 +210,7 @@ export function chatCompletionsSseStream(args: {
208
210
  });
209
211
  }
210
212
 
211
- function routingPayload(decision: RoutingDecision, requestId: string, conversationId?: string): Record<string, unknown> {
213
+ function routingPayload(decision: RoutingDecision, requestId: string, conversationId?: string, isPrivate?: boolean): Record<string, unknown> {
212
214
  return {
213
215
  requested_model: "dari/routing",
214
216
  selected_model: decision.selectedModel,
@@ -216,6 +218,8 @@ function routingPayload(decision: RoutingDecision, requestId: string, conversati
216
218
  reason: decision.reason,
217
219
  request_id: requestId,
218
220
  ...(conversationId ? { conversation_id: conversationId } : {}),
221
+ // Kept out of Activity, so no link to it there.
222
+ ...(isPrivate ? { private: true } : {}),
219
223
  };
220
224
  }
221
225
 
@@ -15,6 +15,7 @@ export function openAIResponsesResponse(args: {
15
15
  request: InteractionRequest;
16
16
  routing: RoutingDecision;
17
17
  conversationId?: string;
18
+ private?: boolean;
18
19
  }): Record<string, unknown> {
19
20
  return {
20
21
  id: openAIResponsesResponseId(args.id),
@@ -26,7 +27,7 @@ export function openAIResponsesResponse(args: {
26
27
  // As on Chat Completions. Null means unpriced, never a fabricated free request.
27
28
  usage: { ...openAIResponsesUsage(args.output), cost: args.modelCost ?? null },
28
29
  parallel_tool_calls: args.request.parallelToolCalls ?? true,
29
- dari_routing: openAIResponsesRouting(args.routing, args.id, args.conversationId),
30
+ dari_routing: openAIResponsesRouting(args.routing, args.id, args.conversationId, args.private),
30
31
  };
31
32
  }
32
33
  import type { RoutingDecision } from "@mupt-ai/dari-router/policy-engine";
@@ -46,7 +46,8 @@ export function openAIResponsesUsage(output: Pick<InteractionOutput, "usage">):
46
46
  export function openAIResponsesRouting(
47
47
  decision: RoutingDecision,
48
48
  requestId: string,
49
- conversationId?: string
49
+ conversationId?: string,
50
+ isPrivate?: boolean
50
51
  ): Record<string, unknown> {
51
52
  return {
52
53
  requested_model: "dari/routing",
@@ -55,6 +56,8 @@ export function openAIResponsesRouting(
55
56
  reason: decision.reason,
56
57
  request_id: requestId,
57
58
  ...(conversationId ? { conversation_id: conversationId } : {}),
59
+ // Kept out of Activity, so no link to it there.
60
+ ...(isPrivate ? { private: true } : {}),
58
61
  };
59
62
  }
60
63
 
@@ -29,6 +29,7 @@ type StreamArgs = {
29
29
  source: ProviderIdentity;
30
30
  request: InteractionRequest;
31
31
  conversationId?: string;
32
+ private?: boolean;
32
33
  onFinal?: (outcome: ProviderStreamOutcome) => void;
33
34
  modelCost?: (message: Record<string, unknown>, failed: boolean) => number | null;
34
35
  // Optional terminal barrier. Streaming deltas are unaffected, but the
@@ -623,7 +624,7 @@ function responseEnvelope(
623
624
  parallel_tool_calls: args.request.parallelToolCalls ?? true,
624
625
  // `cost` as on Chat Completions: null means unpriced.
625
626
  ...(interaction ? { usage: { ...openAIResponsesUsage(interaction), cost: cost ?? null } } : {}),
626
- dari_routing: openAIResponsesRouting(args.routing, args.id, args.conversationId),
627
+ dari_routing: openAIResponsesRouting(args.routing, args.id, args.conversationId, args.private),
627
628
  };
628
629
  }
629
630
 
@@ -193,6 +193,7 @@ export async function completeNonStreaming(args: {
193
193
  request: args.interaction,
194
194
  routing: choice.decision,
195
195
  conversationId: choice.execution.conversationId,
196
+ private: choice.execution.private,
196
197
  });
197
198
  } catch (error) {
198
199
  await reportTerminalProviderFailure({
@@ -678,6 +679,7 @@ export async function executeStreaming(args: {
678
679
  source: started.providerStream.source,
679
680
  request: args.interaction,
680
681
  conversationId: execution.conversationId,
682
+ private: execution.private,
681
683
  clientSignal: args.clientSignal,
682
684
  modelCost: (message, failed) => args.reporter.modelCost({
683
685
  model: args.choice.decision.selectedModel, reasoning_effort: args.choice.decision.reasoningEffort,
@@ -89,6 +89,9 @@ export type ProviderExecution = ProviderCallConfig & {
89
89
  subscriptionResetMinHours?: number;
90
90
  // The thinking the provider was sent, as X-Dari-Thinking-Level reports it.
91
91
  thinkingLevel: string;
92
+ // The request stays out of Activity (ResolvedRouter.private); the response
93
+ // says so, for status lines that would otherwise link to it.
94
+ private?: boolean;
92
95
  usageContext: RoutingUsageContext | undefined;
93
96
  headers: Record<string, string>;
94
97
  };
@@ -181,6 +184,7 @@ export function prepareProviderExecution(args: {
181
184
  : {}),
182
185
  ...(providerKeySource === "subscription" && supplied?.account ? { subscriptionAccount: supplied.account } : {}),
183
186
  thinkingLevel,
187
+ ...(args.credentials.private === true ? { private: true } : {}),
184
188
  usageContext: usageContextFor({
185
189
  billable: args.billable,
186
190
  credentials: args.credentials,
@@ -198,6 +202,7 @@ export function prepareProviderExecution(args: {
198
202
  ? {}
199
203
  : { "X-Dari-Lease-Turns-Remaining": String(args.decision.leaseTurnsRemaining) }),
200
204
  ...(args.decision.sessionPinned === true ? { "X-Dari-Session-Pinned": "true" } : {}),
205
+ ...(args.credentials.private === true ? { "X-Dari-Private": "true" } : {}),
201
206
  },
202
207
  };
203
208
  }
@@ -76,6 +76,7 @@ export async function prepareRoutedCompletion(args: {
76
76
  requestId: string;
77
77
  clientRequestId: string | null;
78
78
  tagsHeader: string | null;
79
+ privateRequest?: boolean;
79
80
  clientHarness?: ClientHarness;
80
81
  clientHeaders?: Record<string, string>;
81
82
  harnessConversationIdentity?: HarnessConversationIdentity;
@@ -88,6 +89,7 @@ export async function prepareRoutedCompletion(args: {
88
89
  apiKey: args.apiKey,
89
90
  includePublicEvalCatalog: true,
90
91
  clientHeaders: args.clientHeaders,
92
+ ...(args.privateRequest ? { private: true } : {}),
91
93
  };
92
94
  // Direct /v1 callers are authenticated by API key, so their canonical
93
95
  // organization router is not known until this resolve completes. Fingerprint
@@ -177,6 +179,8 @@ export async function prepareRoutedCompletion(args: {
177
179
  const strictAccess = strictProviderAccess(credentials, roleModel.interaction);
178
180
  const access = linkGrantAccess(strictAccess.credentials, strictAccess.interaction);
179
181
  credentials = access.credentials;
182
+ // A Dari Link app's usage is read back from its requests, so they are kept.
183
+ if (args.privateRequest && !credentials.link_grant_id) credentials = { ...credentials, private: true };
180
184
  // A child token's tags label every request it makes, whatever the request says.
181
185
  Object.assign(tags, credentials.link_tags);
182
186
  args = {
@@ -1,6 +1,7 @@
1
1
  import { randomUUID } from "node:crypto";
2
2
 
3
3
  import { isBackgroundRequest, type InteractionRequest } from "../interaction/types.js";
4
+ import { PRIVATE_HEADER } from "../platform/routing_contract.js";
4
5
  import { explicitModelId } from "../protocol/input/router_model.js";
5
6
  import { captureRequestError } from "../observability/errors.js";
6
7
  import type { SelectorBackend } from "../strategies/routing.js";
@@ -42,6 +43,7 @@ export async function handleRoutedCompletion(args: {
42
43
  requestId,
43
44
  clientRequestId,
44
45
  tagsHeader: args.request.headers.get("x-dari-tags"),
46
+ privateRequest: args.request.headers.get(PRIVATE_HEADER) === "true",
45
47
  clientHarness: args.clientHarness,
46
48
  clientHeaders: clientHeaders(args.request.headers),
47
49
  harnessConversationIdentity: args.harnessConversationIdentity,
@@ -10,6 +10,7 @@ export type RoutedCompletionResponseArgs = {
10
10
  request: InteractionRequest;
11
11
  routing: RoutingDecision;
12
12
  conversationId?: string;
13
+ private?: boolean;
13
14
  };
14
15
 
15
16
  export type RoutedCompletionStreamArgs = {
@@ -20,6 +21,7 @@ export type RoutedCompletionStreamArgs = {
20
21
  source: ProviderIdentity;
21
22
  request: InteractionRequest;
22
23
  conversationId?: string;
24
+ private?: boolean;
23
25
  onFinal?: (outcome: ProviderStreamOutcome) => void;
24
26
  modelCost?: (message: Record<string, unknown>, failed: boolean) => number | null;
25
27
  beforeClose?: (outcome: ProviderStreamOutcome) => Promise<void> | void;
@@ -5,10 +5,11 @@ import { anthropicToken, bearerToken } from "../http/auth.js";
5
5
  import { errorResponse, HttpError } from "../http/errors.js";
6
6
  import { anthropicErrorResponse } from "../ingress/anthropic_messages.js";
7
7
  import type { GatewayPlatform } from "../platform/platform.js";
8
- import { DEFAULT_ROUTER_ALIAS, HOSTED_DARI_PROVIDER } from "../platform/routing_contract.js";
8
+ import { DEFAULT_ROUTER_ALIAS, HOSTED_DARI_PROVIDER, PRIVATE_HEADER } from "../platform/routing_contract.js";
9
9
  import type { Source } from "../models/sources.js";
10
10
  import { parseGatewayConfig, type RouterConfig } from "./config.js";
11
11
  import type { HostedSync } from "./hosted_sync.js";
12
+ import type { PrivateMode } from "./private_mode.js";
12
13
  import { createSelfHostedPlatform } from "./platform.js";
13
14
  import { gatewayKeyIndex, resolveSelfHostedRouter } from "./resolve.js";
14
15
 
@@ -28,9 +29,11 @@ import { gatewayKeyIndex, resolveSelfHostedRouter } from "./resolve.js";
28
29
  * reports, goes to hosted with the user's Dari key.
29
30
  * - The requests served here sync to hosted Activity (hosted_sync.ts), each
30
31
  * 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.
32
+ * computer. Requests hosted Dari served are hosted's to log. Dari Link and
33
+ * Activity are hosted's, not served here.
34
+ * - In private mode (private_mode.ts) every request is private
35
+ * (PRIVATE_HEADER): none syncs, and hosted Dari keeps only what billing
36
+ * needs of those it serves.
34
37
  */
35
38
  export type HostedConnection = {
36
39
  // The hosted routing service, e.g. https://routing.dari.dev.
@@ -81,14 +84,9 @@ export function createConnectedPlatform(deps: SelfHostedPlatformDeps & {
81
84
  },
82
85
  recordRequest(record) {
83
86
  console.info("routing request", JSON.stringify(record.summary));
84
- // Hosted Dari logs the requests it served itself.
85
- if (record.summary.selected_provider === HOSTED_DARI_PROVIDER) return;
86
- // A private plan's requests stay on this computer, as the plan does; so
87
- // does one whose plan is gone, since it may have been private.
88
- if (record.subscriptionCredentialId !== undefined) {
89
- const plan = deps.subscriptions.get(record.subscriptionCredentialId);
90
- if (plan === null || plan.private) return;
91
- }
87
+ // Hosted Dari logs the requests it served itself, and private ones
88
+ // stay on this computer.
89
+ if (record.summary.selected_provider === HOSTED_DARI_PROVIDER || record.private) return;
92
90
  try {
93
91
  deps.sync.enqueue(record.row);
94
92
  } catch (error) {
@@ -185,9 +183,15 @@ export function connectedHandler(deps: {
185
183
  gatewayKeys: readonly string[];
186
184
  hosted: HostedConnection;
187
185
  hostedRouter: HostedRouters;
186
+ privateMode: PrivateMode;
188
187
  fetch: typeof fetch;
189
188
  }): (request: Request) => Promise<Response> {
190
189
  return async (request) => {
190
+ if (deps.privateMode.on) {
191
+ const headers = new Headers(request.headers);
192
+ headers.set(PRIVATE_HEADER, "true");
193
+ request = new Request(request, { headers });
194
+ }
191
195
  const { pathname } = new URL(request.url);
192
196
  if (pathname === "/healthz" || pathname === "/health" || pathname === "/api/hello") {
193
197
  return await deps.gateway(request);
@@ -94,7 +94,7 @@ export class HostedSync {
94
94
  const onDari = await readHostedAccounts(this.hosted, this.fetch);
95
95
  this.accountsFailures = 0;
96
96
  for (const plan of this.subscriptions.list()) {
97
- if (plan.owner !== null || plan.private || plan.accountId === null) continue;
97
+ if (plan.owner !== null || plan.accountId === null) continue;
98
98
  const moved = onDari.some((account) => account.provider === plan.provider
99
99
  && account.accountId === plan.accountId
100
100
  && account.connectedAt !== undefined && account.connectedAt > plan.createdAt);
@@ -36,6 +36,7 @@ import {
36
36
  servedRouterIds,
37
37
  type ServedRouters,
38
38
  } from "./router_specs.js";
39
+ import { handlePrivateModeRequest, PRIVATE_MODE_ROUTE, PrivateMode } from "./private_mode.js";
39
40
  import { SessionPinStore } from "./session_pin_store.js";
40
41
  import { handleSubscriptionRequest, SubscriptionStore } from "./subscriptions/index.js";
41
42
  import { providerBaseUrls } from "./subscriptions/resets.js";
@@ -44,8 +45,8 @@ import { refreshStaleUsage } from "./subscriptions/usage.js";
44
45
  const SUBSCRIPTION_ROUTES = "/v1/organizations/current/credentials";
45
46
  // The models Dari serves, which the Dari CLI's model picker offers.
46
47
  const CANONICAL_MODELS_ROUTE = "/v1/canonical-models";
47
- // How often a connected gateway reads idle plans' usage, so hosted Dari's
48
- // meters move without a request here.
48
+ // How often a connected gateway reads idle plans' usage, so their meters move
49
+ // without a request here.
49
50
  const IDLE_USAGE_INTERVAL_MS = 5 * 60_000;
50
51
 
51
52
  /**
@@ -76,8 +77,9 @@ const IDLE_USAGE_INTERVAL_MS = 5 * 60_000;
76
77
  * - `DARI_HOSTED_URL` and `DARI_HOSTED_API_KEY`: connect the gateway to hosted
77
78
  * Dari (connected.ts), with `DARI_GATEWAY_ID`, `DARI_GATEWAY_NAME`, and
78
79
  * `DARI_GATEWAY_ENCRYPTION_KEY`. It then serves the user's hosted routers on
79
- * its own plans and then on hosted Dari, and syncs its plans and requests
80
- * there; Dari Link and Activity are hosted's.
80
+ * its own plans and then on hosted Dari, and syncs its requests there unless
81
+ * private mode is on (`/v1/gateway/private`); Dari Link and Activity are
82
+ * hosted's.
81
83
  */
82
84
  export async function startSelfHostedGateway(env: Record<string, string> = process.env as Record<string, string>) {
83
85
  const hosted = hostedConnectionFromEnv(env);
@@ -103,6 +105,10 @@ export async function startSelfHostedGateway(env: Record<string, string> = proce
103
105
  );
104
106
  }
105
107
  const subscriptions = new SubscriptionStore(db, secrets);
108
+ const privateMode = new PrivateMode(db);
109
+ // Plans marked private before private mode kept their requests out of
110
+ // Activity; the gateway now keeps all of them out instead.
111
+ if (subscriptions.clearLegacyPrivate()) privateMode.set(true);
106
112
  const prefixes = new PrefixStore(db);
107
113
  const sessionPins = new SessionPinStore(db);
108
114
  const routerModels = new RouterModelStore(db);
@@ -180,7 +186,7 @@ export async function startSelfHostedGateway(env: Record<string, string> = proce
180
186
  const routed = createRequestHandler({ platform, selectorBackend });
181
187
  const gateway = hosted === null || sync === null || hostedRouter === null
182
188
  ? routed
183
- : connectedHandler({ gateway: routed, gatewayKeys, hosted, hostedRouter, fetch });
189
+ : connectedHandler({ gateway: routed, gatewayKeys, hosted, hostedRouter, privateMode, fetch });
184
190
 
185
191
  // Subscriptions, model lists, and router specs are managed with any gateway
186
192
  // key; every other path is the gateway's own.
@@ -190,7 +196,8 @@ export async function startSelfHostedGateway(env: Record<string, string> = proce
190
196
  || pathname.startsWith(`${SUBSCRIPTION_ROUTES}/`)
191
197
  || pathname === CANONICAL_MODELS_ROUTE
192
198
  || ROUTER_MODELS_ROUTE.test(pathname)
193
- || ROUTERS_ROUTE.test(pathname);
199
+ || ROUTERS_ROUTE.test(pathname)
200
+ || pathname === PRIVATE_MODE_ROUTE;
194
201
  if (!manages) return await gateway(request);
195
202
  try {
196
203
  if (gatewayKeyIndex(gatewayKeys, bearerToken(request.headers)) === null) {
@@ -199,6 +206,7 @@ export async function startSelfHostedGateway(env: Record<string, string> = proce
199
206
  } catch (error) {
200
207
  return errorResponse(error);
201
208
  }
209
+ if (pathname === PRIVATE_MODE_ROUTE) return await handlePrivateModeRequest(request, privateMode).catch(errorResponse);
202
210
  if (pathname === CANONICAL_MODELS_ROUTE && request.method === "GET") {
203
211
  return Response.json({ data: CANONICAL_MODELS }, { headers: { "Cache-Control": "no-store" } });
204
212
  }