@mupt-ai/dari-gateway 1.0.368 → 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 (63) hide show
  1. package/dist/link/self_hosted.js +0 -1
  2. package/dist/platform/platform.d.ts +2 -0
  3. package/dist/platform/routing_contract.d.ts +1 -0
  4. package/dist/platform/routing_contract.js +4 -0
  5. package/dist/protocol/output/anthropic_messages.d.ts +1 -0
  6. package/dist/protocol/output/anthropic_messages.js +1 -1
  7. package/dist/protocol/output/anthropic_messages_output.d.ts +1 -1
  8. package/dist/protocol/output/anthropic_messages_output.js +3 -1
  9. package/dist/protocol/output/anthropic_messages_stream.d.ts +1 -0
  10. package/dist/protocol/output/anthropic_messages_stream.js +1 -1
  11. package/dist/protocol/output/chat_completions.d.ts +2 -0
  12. package/dist/protocol/output/chat_completions.js +5 -3
  13. package/dist/protocol/output/openai_responses.d.ts +1 -0
  14. package/dist/protocol/output/openai_responses.js +1 -1
  15. package/dist/protocol/output/openai_responses_output.d.ts +1 -1
  16. package/dist/protocol/output/openai_responses_output.js +3 -1
  17. package/dist/protocol/output/openai_responses_stream.d.ts +1 -0
  18. package/dist/protocol/output/openai_responses_stream.js +1 -1
  19. package/dist/providers/execution.js +2 -0
  20. package/dist/providers/provider_call.d.ts +1 -0
  21. package/dist/providers/provider_call.js +2 -0
  22. package/dist/runtime/prepare_routed_completion.d.ts +1 -0
  23. package/dist/runtime/prepare_routed_completion.js +4 -0
  24. package/dist/runtime/routed_completion.js +2 -0
  25. package/dist/runtime/routed_protocol.d.ts +2 -0
  26. package/dist/self_host/connected.d.ts +7 -3
  27. package/dist/self_host/connected.js +9 -10
  28. package/dist/self_host/hosted_sync.js +1 -1
  29. package/dist/self_host/main.d.ts +3 -2
  30. package/dist/self_host/main.js +16 -6
  31. package/dist/self_host/private_mode.d.ts +16 -0
  32. package/dist/self_host/private_mode.js +35 -0
  33. package/dist/self_host/resolve.js +5 -2
  34. package/dist/self_host/subscriptions/http.js +2 -17
  35. package/dist/self_host/subscriptions/store.d.ts +7 -6
  36. package/dist/self_host/subscriptions/store.js +15 -27
  37. package/dist/telemetry/report.js +1 -0
  38. package/dist/types.d.ts +1 -0
  39. package/package.json +2 -2
  40. package/src/link/self_hosted.ts +0 -1
  41. package/src/platform/platform.ts +6 -0
  42. package/src/platform/routing_contract.ts +5 -0
  43. package/src/protocol/output/anthropic_messages.ts +2 -1
  44. package/src/protocol/output/anthropic_messages_output.ts +4 -1
  45. package/src/protocol/output/anthropic_messages_stream.ts +2 -1
  46. package/src/protocol/output/chat_completions.ts +7 -3
  47. package/src/protocol/output/openai_responses.ts +2 -1
  48. package/src/protocol/output/openai_responses_output.ts +4 -1
  49. package/src/protocol/output/openai_responses_stream.ts +2 -1
  50. package/src/providers/execution.ts +2 -0
  51. package/src/providers/provider_call.ts +5 -0
  52. package/src/runtime/prepare_routed_completion.ts +4 -0
  53. package/src/runtime/routed_completion.ts +2 -0
  54. package/src/runtime/routed_protocol.ts +2 -0
  55. package/src/self_host/connected.ts +16 -12
  56. package/src/self_host/hosted_sync.ts +1 -1
  57. package/src/self_host/main.ts +14 -6
  58. package/src/self_host/private_mode.ts +41 -0
  59. package/src/self_host/resolve.ts +4 -2
  60. package/src/self_host/subscriptions/http.ts +2 -15
  61. package/src/self_host/subscriptions/store.ts +15 -34
  62. package/src/telemetry/report.ts +1 -0
  63. package/src/types.ts +3 -0
@@ -98,7 +98,6 @@ export function selfHostedLink(deps) {
98
98
  flow: authorization.flow,
99
99
  credentialName: null,
100
100
  owner: newSubject(),
101
- private: false,
102
101
  movingFrom: null,
103
102
  expiresAt: authorization.expiresAt,
104
103
  });
@@ -484,6 +484,7 @@ export type ResolveRouterRequest = {
484
484
  includePublicEvalCatalog?: boolean;
485
485
  clientHarness?: ClientHarness;
486
486
  clientHeaders?: Record<string, string>;
487
+ private?: boolean;
487
488
  provisional?: boolean;
488
489
  };
489
490
  export type ProviderCredentialRequest = {
@@ -563,6 +564,7 @@ export type RequestRecord = {
563
564
  credentialId: string | null;
564
565
  };
565
566
  subscriptionCredentialId?: string;
567
+ private: boolean;
566
568
  router: RequestRecordRouter;
567
569
  candidates: Array<{
568
570
  model: string;
@@ -1,3 +1,4 @@
1
1
  export declare const DEFAULT_ROUTER_ALIAS = "default";
2
2
  export declare const ROUTING_PREFIX_HASHES_MAX_COUNT = 200;
3
3
  export declare const HOSTED_DARI_PROVIDER = "dari";
4
+ export declare const PRIVATE_HEADER = "x-dari-private";
@@ -6,3 +6,7 @@ export const ROUTING_PREFIX_HASHES_MAX_COUNT = 200;
6
6
  // The provider id of hosted Dari when a gateway connected to it calls it for
7
7
  // a model, as `dari/model/<id>` with the user's Dari key.
8
8
  export const HOSTED_DARI_PROVIDER = "dari";
9
+ // A request with this header set to `true` stays out of Activity: the
10
+ // platform keeps only what billing needs. A gateway in private mode sets it on
11
+ // every request, and on each it hands hosted Dari.
12
+ export const PRIVATE_HEADER = "x-dari-private";
@@ -8,4 +8,5 @@ export declare function anthropicMessagesResponse(args: {
8
8
  request: InteractionRequest;
9
9
  routing: RoutingDecision;
10
10
  conversationId?: string;
11
+ private?: boolean;
11
12
  }): Record<string, unknown>;
@@ -11,6 +11,6 @@ export function anthropicMessagesResponse(args) {
11
11
  // As on Chat Completions. Null means unpriced, never a fabricated free request.
12
12
  usage: { ...anthropicUsage(args.output), cost: args.modelCost ?? null },
13
13
  ...(args.output.safeguardResults ? { safeguard_results: args.output.safeguardResults } : {}),
14
- dari_routing: anthropicRouting(args.routing, args.id, args.conversationId),
14
+ dari_routing: anthropicRouting(args.routing, args.id, args.conversationId, args.private),
15
15
  };
16
16
  }
@@ -7,4 +7,4 @@ export declare function anthropicReasoningBlock(item: Extract<InteractionOutput[
7
7
  }>): Record<string, unknown>;
8
8
  export declare function anthropicStopReason(output: Pick<InteractionOutput, "stopReason">): string;
9
9
  export declare function anthropicUsage(output: Pick<InteractionOutput, "usage">): Record<string, unknown>;
10
- export declare function anthropicRouting(decision: ServedDecision, requestId: string, conversationId?: string): Record<string, unknown>;
10
+ export declare function anthropicRouting(decision: ServedDecision, requestId: string, conversationId?: string, isPrivate?: boolean): Record<string, unknown>;
@@ -111,7 +111,7 @@ export function anthropicUsage(output) {
111
111
  output_tokens: output.usage.output,
112
112
  };
113
113
  }
114
- export function anthropicRouting(decision, requestId, conversationId) {
114
+ export function anthropicRouting(decision, requestId, conversationId, isPrivate) {
115
115
  return {
116
116
  requested_model: "dari/routing",
117
117
  selected_model: decision.selectedModel,
@@ -119,6 +119,8 @@ export function anthropicRouting(decision, requestId, conversationId) {
119
119
  reason: decision.reason,
120
120
  request_id: requestId,
121
121
  ...(conversationId ? { conversation_id: conversationId } : {}),
122
+ // Kept out of Activity, so no link to it there.
123
+ ...(isPrivate ? { private: true } : {}),
122
124
  ...(decision.leaseTurnsRemaining === undefined
123
125
  ? {}
124
126
  : { lease_turns_remaining: decision.leaseTurnsRemaining }),
@@ -8,6 +8,7 @@ export declare function anthropicMessagesSseStream(args: {
8
8
  source: ProviderIdentity;
9
9
  request: InteractionRequest;
10
10
  conversationId?: string;
11
+ private?: boolean;
11
12
  onFinal?: (outcome: ProviderStreamOutcome) => void;
12
13
  modelCost?: (message: Record<string, unknown>, failed: boolean) => number | null;
13
14
  beforeClose?: (outcome: ProviderStreamOutcome) => Promise<void> | void;
@@ -33,7 +33,7 @@ export function anthropicMessagesSseStream(args) {
33
33
  stop_reason: null,
34
34
  stop_sequence: null,
35
35
  usage: { input_tokens: 0, output_tokens: 0 },
36
- dari_routing: anthropicRouting(args.routing, args.id, args.conversationId),
36
+ dari_routing: anthropicRouting(args.routing, args.id, args.conversationId, args.private),
37
37
  },
38
38
  });
39
39
  const argumentDeltaIndexes = new Set();
@@ -8,6 +8,7 @@ export declare function chatCompletionResponse(args: {
8
8
  modelCost?: number | null;
9
9
  routing: RoutingDecision;
10
10
  conversationId?: string;
11
+ private?: boolean;
11
12
  }): Record<string, unknown>;
12
13
  export declare function chatCompletionsSseStream(args: {
13
14
  id: string;
@@ -17,6 +18,7 @@ export declare function chatCompletionsSseStream(args: {
17
18
  source: ProviderIdentity;
18
19
  request: InteractionRequest;
19
20
  conversationId?: string;
21
+ private?: boolean;
20
22
  onFinal?: (outcome: ProviderStreamOutcome) => void;
21
23
  modelCost?: (message: Record<string, unknown>, failed: boolean) => number | null;
22
24
  beforeClose?: (outcome: ProviderStreamOutcome) => Promise<void> | void;
@@ -19,7 +19,7 @@ export function chatCompletionResponse(args) {
19
19
  },
20
20
  ],
21
21
  usage: usagePayload(args.output, args.modelCost),
22
- dari_routing: routingPayload(args.routing, args.id, args.conversationId),
22
+ dari_routing: routingPayload(args.routing, args.id, args.conversationId, args.private),
23
23
  };
24
24
  }
25
25
  export function chatCompletionsSseStream(args) {
@@ -45,7 +45,7 @@ export function chatCompletionsSseStream(args) {
45
45
  send({ ...errorChunk({ completion, created, model: args.model, message: providerFailureMessage(message) }),
46
46
  usage: usagePayload(message, args.modelCost?.(message, true)) });
47
47
  };
48
- send(chunk({ completion, created, model: args.model, delta: {}, finishReason: null, routing: routingPayload(args.routing, args.id, args.conversationId) }));
48
+ send(chunk({ completion, created, model: args.model, delta: {}, finishReason: null, routing: routingPayload(args.routing, args.id, args.conversationId, args.private) }));
49
49
  send(chunk({ completion, created, model: args.model, delta: { role: "assistant" }, finishReason: null }));
50
50
  const argumentDeltaSeen = new Set();
51
51
  const toolCallIdsSeen = new Set();
@@ -189,7 +189,7 @@ export function chatCompletionsSseStream(args) {
189
189
  },
190
190
  });
191
191
  }
192
- function routingPayload(decision, requestId, conversationId) {
192
+ function routingPayload(decision, requestId, conversationId, isPrivate) {
193
193
  return {
194
194
  requested_model: "dari/routing",
195
195
  selected_model: decision.selectedModel,
@@ -197,6 +197,8 @@ function routingPayload(decision, requestId, conversationId) {
197
197
  reason: decision.reason,
198
198
  request_id: requestId,
199
199
  ...(conversationId ? { conversation_id: conversationId } : {}),
200
+ // Kept out of Activity, so no link to it there.
201
+ ...(isPrivate ? { private: true } : {}),
200
202
  };
201
203
  }
202
204
  function chunk(args) {
@@ -7,5 +7,6 @@ export declare function openAIResponsesResponse(args: {
7
7
  request: InteractionRequest;
8
8
  routing: RoutingDecision;
9
9
  conversationId?: string;
10
+ private?: boolean;
10
11
  }): Record<string, unknown>;
11
12
  import type { RoutingDecision } from "@mupt-ai/dari-router/policy-engine";
@@ -10,6 +10,6 @@ export function openAIResponsesResponse(args) {
10
10
  // As on Chat Completions. Null means unpriced, never a fabricated free request.
11
11
  usage: { ...openAIResponsesUsage(args.output), cost: args.modelCost ?? null },
12
12
  parallel_tool_calls: args.request.parallelToolCalls ?? true,
13
- dari_routing: openAIResponsesRouting(args.routing, args.id, args.conversationId),
13
+ dari_routing: openAIResponsesRouting(args.routing, args.id, args.conversationId, args.private),
14
14
  };
15
15
  }
@@ -9,6 +9,6 @@ export declare function openAIResponsesTerminal(output: Pick<InteractionOutput,
9
9
  export declare function openAIResponsesOutputItems(output: InteractionOutput): Array<Record<string, unknown>>;
10
10
  export declare function openAIResponsesOutputItem(output: InteractionOutput, item: InteractionOutput["items"][number], index: number): Record<string, unknown>;
11
11
  export declare function openAIResponsesUsage(output: Pick<InteractionOutput, "usage">): Record<string, unknown>;
12
- export declare function openAIResponsesRouting(decision: RoutingDecision, requestId: string, conversationId?: string): Record<string, unknown>;
12
+ export declare function openAIResponsesRouting(decision: RoutingDecision, requestId: string, conversationId?: string, isPrivate?: boolean): Record<string, unknown>;
13
13
  export declare function responseMessageOutputItem(id: string, text: string): Record<string, unknown>;
14
14
  import type { RoutingDecision } from "@mupt-ai/dari-router/policy-engine";
@@ -33,7 +33,7 @@ export function openAIResponsesUsage(output) {
33
33
  total_tokens: output.usage.totalTokens || inputTokens + output.usage.output,
34
34
  };
35
35
  }
36
- export function openAIResponsesRouting(decision, requestId, conversationId) {
36
+ export function openAIResponsesRouting(decision, requestId, conversationId, isPrivate) {
37
37
  return {
38
38
  requested_model: "dari/routing",
39
39
  selected_model: decision.selectedModel,
@@ -41,6 +41,8 @@ export function openAIResponsesRouting(decision, requestId, conversationId) {
41
41
  reason: decision.reason,
42
42
  request_id: requestId,
43
43
  ...(conversationId ? { conversation_id: conversationId } : {}),
44
+ // Kept out of Activity, so no link to it there.
45
+ ...(isPrivate ? { private: true } : {}),
44
46
  };
45
47
  }
46
48
  export function responseMessageOutputItem(id, text) {
@@ -8,6 +8,7 @@ type StreamArgs = {
8
8
  source: ProviderIdentity;
9
9
  request: InteractionRequest;
10
10
  conversationId?: string;
11
+ private?: boolean;
11
12
  onFinal?: (outcome: ProviderStreamOutcome) => void;
12
13
  modelCost?: (message: Record<string, unknown>, failed: boolean) => number | null;
13
14
  beforeClose?: (outcome: ProviderStreamOutcome) => Promise<void> | void;
@@ -547,7 +547,7 @@ function responseEnvelope(args, id, createdAt, status, output, interaction, cost
547
547
  parallel_tool_calls: args.request.parallelToolCalls ?? true,
548
548
  // `cost` as on Chat Completions: null means unpriced.
549
549
  ...(interaction ? { usage: { ...openAIResponsesUsage(interaction), cost: cost ?? null } } : {}),
550
- dari_routing: openAIResponsesRouting(args.routing, args.id, args.conversationId),
550
+ dari_routing: openAIResponsesRouting(args.routing, args.id, args.conversationId, args.private),
551
551
  };
552
552
  }
553
553
  function sendFailure(send, args, responseId, createdAt, accumulator, error) {
@@ -83,6 +83,7 @@ export async function completeNonStreaming(args) {
83
83
  request: args.interaction,
84
84
  routing: choice.decision,
85
85
  conversationId: choice.execution.conversationId,
86
+ private: choice.execution.private,
86
87
  });
87
88
  }
88
89
  catch (error) {
@@ -399,6 +400,7 @@ export async function executeStreaming(args) {
399
400
  source: started.providerStream.source,
400
401
  request: args.interaction,
401
402
  conversationId: execution.conversationId,
403
+ private: execution.private,
402
404
  clientSignal: args.clientSignal,
403
405
  modelCost: (message, failed) => args.reporter.modelCost({
404
406
  model: args.choice.decision.selectedModel, reasoning_effort: args.choice.decision.reasoningEffort,
@@ -32,6 +32,7 @@ export type ProviderExecution = ProviderCallConfig & {
32
32
  subscriptionSources?: Source[];
33
33
  subscriptionResetMinHours?: number;
34
34
  thinkingLevel: string;
35
+ private?: boolean;
35
36
  usageContext: RoutingUsageContext | undefined;
36
37
  headers: Record<string, string>;
37
38
  };
@@ -64,6 +64,7 @@ export function prepareProviderExecution(args) {
64
64
  : {}),
65
65
  ...(providerKeySource === "subscription" && supplied?.account ? { subscriptionAccount: supplied.account } : {}),
66
66
  thinkingLevel,
67
+ ...(args.credentials.private === true ? { private: true } : {}),
67
68
  usageContext: usageContextFor({
68
69
  billable: args.billable,
69
70
  credentials: args.credentials,
@@ -81,6 +82,7 @@ export function prepareProviderExecution(args) {
81
82
  ? {}
82
83
  : { "X-Dari-Lease-Turns-Remaining": String(args.decision.leaseTurnsRemaining) }),
83
84
  ...(args.decision.sessionPinned === true ? { "X-Dari-Session-Pinned": "true" } : {}),
85
+ ...(args.credentials.private === true ? { "X-Dari-Private": "true" } : {}),
84
86
  },
85
87
  };
86
88
  }
@@ -36,6 +36,7 @@ export declare function prepareRoutedCompletion(args: {
36
36
  requestId: string;
37
37
  clientRequestId: string | null;
38
38
  tagsHeader: string | null;
39
+ privateRequest?: boolean;
39
40
  clientHarness?: ClientHarness;
40
41
  clientHeaders?: Record<string, string>;
41
42
  harnessConversationIdentity?: HarnessConversationIdentity;
@@ -25,6 +25,7 @@ export async function prepareRoutedCompletion(args) {
25
25
  apiKey: args.apiKey,
26
26
  includePublicEvalCatalog: true,
27
27
  clientHeaders: args.clientHeaders,
28
+ ...(args.privateRequest ? { private: true } : {}),
28
29
  };
29
30
  // Direct /v1 callers are authenticated by API key, so their canonical
30
31
  // organization router is not known until this resolve completes. Fingerprint
@@ -109,6 +110,9 @@ export async function prepareRoutedCompletion(args) {
109
110
  const strictAccess = strictProviderAccess(credentials, roleModel.interaction);
110
111
  const access = linkGrantAccess(strictAccess.credentials, strictAccess.interaction);
111
112
  credentials = access.credentials;
113
+ // A Dari Link app's usage is read back from its requests, so they are kept.
114
+ if (args.privateRequest && !credentials.link_grant_id)
115
+ credentials = { ...credentials, private: true };
112
116
  // A child token's tags label every request it makes, whatever the request says.
113
117
  Object.assign(tags, credentials.link_tags);
114
118
  args = {
@@ -1,5 +1,6 @@
1
1
  import { randomUUID } from "node:crypto";
2
2
  import { isBackgroundRequest } from "../interaction/types.js";
3
+ import { PRIVATE_HEADER } from "../platform/routing_contract.js";
3
4
  import { explicitModelId } from "../protocol/input/router_model.js";
4
5
  import { captureRequestError } from "../observability/errors.js";
5
6
  import { assertAutoroutingAllowed, assertCreditAvailableBeforeRouting, routerSelectsModels } from "../telemetry/usage.js";
@@ -22,6 +23,7 @@ export async function handleRoutedCompletion(args) {
22
23
  requestId,
23
24
  clientRequestId,
24
25
  tagsHeader: args.request.headers.get("x-dari-tags"),
26
+ privateRequest: args.request.headers.get(PRIVATE_HEADER) === "true",
25
27
  clientHarness: args.clientHarness,
26
28
  clientHeaders: clientHeaders(args.request.headers),
27
29
  harnessConversationIdentity: args.harnessConversationIdentity,
@@ -9,6 +9,7 @@ export type RoutedCompletionResponseArgs = {
9
9
  request: InteractionRequest;
10
10
  routing: RoutingDecision;
11
11
  conversationId?: string;
12
+ private?: boolean;
12
13
  };
13
14
  export type RoutedCompletionStreamArgs = {
14
15
  id: string;
@@ -18,6 +19,7 @@ export type RoutedCompletionStreamArgs = {
18
19
  source: ProviderIdentity;
19
20
  request: InteractionRequest;
20
21
  conversationId?: string;
22
+ private?: boolean;
21
23
  onFinal?: (outcome: ProviderStreamOutcome) => void;
22
24
  modelCost?: (message: Record<string, unknown>, failed: boolean) => number | null;
23
25
  beforeClose?: (outcome: ProviderStreamOutcome) => Promise<void> | void;
@@ -1,6 +1,7 @@
1
1
  import type { GatewayPlatform } from "../platform/platform.js";
2
2
  import { type RouterConfig } from "./config.js";
3
3
  import type { HostedSync } from "./hosted_sync.js";
4
+ import type { PrivateMode } from "./private_mode.js";
4
5
  import { createSelfHostedPlatform } from "./platform.js";
5
6
  /**
6
7
  * A self-hosted gateway connected to hosted Dari (the Dari CLI runs one for
@@ -18,9 +19,11 @@ import { createSelfHostedPlatform } from "./platform.js";
18
19
  * reports, goes to hosted with the user's Dari key.
19
20
  * - The requests served here sync to hosted Activity (hosted_sync.ts), each
20
21
  * naming the plan that served it. The plans themselves never leave this
21
- * computer. A private plan's requests do not sync either; requests hosted
22
- * Dari served are hosted's to log. Dari Link and Activity are hosted's, not
23
- * served here.
22
+ * computer. Requests hosted Dari served are hosted's to log. Dari Link and
23
+ * Activity are hosted's, not served here.
24
+ * - In private mode (private_mode.ts) every request is private
25
+ * (PRIVATE_HEADER): none syncs, and hosted Dari keeps only what billing
26
+ * needs of those it serves.
24
27
  */
25
28
  export type HostedConnection = {
26
29
  url: string;
@@ -60,6 +63,7 @@ export declare function connectedHandler(deps: {
60
63
  gatewayKeys: readonly string[];
61
64
  hosted: HostedConnection;
62
65
  hostedRouter: HostedRouters;
66
+ privateMode: PrivateMode;
63
67
  fetch: typeof fetch;
64
68
  }): (request: Request) => Promise<Response>;
65
69
  export {};
@@ -2,7 +2,7 @@ import { hostname } from "node:os";
2
2
  import { anthropicToken, bearerToken } from "../http/auth.js";
3
3
  import { errorResponse, HttpError } from "../http/errors.js";
4
4
  import { anthropicErrorResponse } from "../ingress/anthropic_messages.js";
5
- import { DEFAULT_ROUTER_ALIAS, HOSTED_DARI_PROVIDER } from "../platform/routing_contract.js";
5
+ import { DEFAULT_ROUTER_ALIAS, HOSTED_DARI_PROVIDER, PRIVATE_HEADER } from "../platform/routing_contract.js";
6
6
  import { parseGatewayConfig } from "./config.js";
7
7
  import { createSelfHostedPlatform } from "./platform.js";
8
8
  import { gatewayKeyIndex, resolveSelfHostedRouter } from "./resolve.js";
@@ -41,16 +41,10 @@ export function createConnectedPlatform(deps) {
41
41
  },
42
42
  recordRequest(record) {
43
43
  console.info("routing request", JSON.stringify(record.summary));
44
- // Hosted Dari logs the requests it served itself.
45
- if (record.summary.selected_provider === HOSTED_DARI_PROVIDER)
44
+ // Hosted Dari logs the requests it served itself, and private ones
45
+ // stay on this computer.
46
+ if (record.summary.selected_provider === HOSTED_DARI_PROVIDER || record.private)
46
47
  return;
47
- // A private plan's requests stay on this computer, as the plan does; so
48
- // does one whose plan is gone, since it may have been private.
49
- if (record.subscriptionCredentialId !== undefined) {
50
- const plan = deps.subscriptions.get(record.subscriptionCredentialId);
51
- if (plan === null || plan.private)
52
- return;
53
- }
54
48
  try {
55
49
  deps.sync.enqueue(record.row);
56
50
  }
@@ -122,6 +116,11 @@ const LOCAL_CALL = /^(?:\/[^/]+)?(?:\/v1)?\/(?:chat\/completions|responses|messa
122
116
  */
123
117
  export function connectedHandler(deps) {
124
118
  return async (request) => {
119
+ if (deps.privateMode.on) {
120
+ const headers = new Headers(request.headers);
121
+ headers.set(PRIVATE_HEADER, "true");
122
+ request = new Request(request, { headers });
123
+ }
125
124
  const { pathname } = new URL(request.url);
126
125
  if (pathname === "/healthz" || pathname === "/health" || pathname === "/api/hello") {
127
126
  return await deps.gateway(request);
@@ -82,7 +82,7 @@ export class HostedSync {
82
82
  const onDari = await readHostedAccounts(this.hosted, this.fetch);
83
83
  this.accountsFailures = 0;
84
84
  for (const plan of this.subscriptions.list()) {
85
- if (plan.owner !== null || plan.private || plan.accountId === null)
85
+ if (plan.owner !== null || plan.accountId === null)
86
86
  continue;
87
87
  const moved = onDari.some((account) => account.provider === plan.provider
88
88
  && account.accountId === plan.accountId
@@ -27,8 +27,9 @@
27
27
  * - `DARI_HOSTED_URL` and `DARI_HOSTED_API_KEY`: connect the gateway to hosted
28
28
  * Dari (connected.ts), with `DARI_GATEWAY_ID`, `DARI_GATEWAY_NAME`, and
29
29
  * `DARI_GATEWAY_ENCRYPTION_KEY`. It then serves the user's hosted routers on
30
- * its own plans and then on hosted Dari, and syncs its plans and requests
31
- * there; Dari Link and Activity are hosted's.
30
+ * its own plans and then on hosted Dari, and syncs its requests there unless
31
+ * private mode is on (`/v1/gateway/private`); Dari Link and Activity are
32
+ * hosted's.
32
33
  */
33
34
  export declare function startSelfHostedGateway(env?: Record<string, string>): Promise<{
34
35
  server: import("../http/http2_server.js").Http2RoutingServer | Bun.Server<undefined>;
@@ -21,6 +21,7 @@ import { secretBoxFromEnv } from "./secret_box.js";
21
21
  import { PrefixStore } from "./prefix_store.js";
22
22
  import { handleRouterModelsRequest, ROUTER_MODELS_ROUTE, RouterModelStore } from "./router_models.js";
23
23
  import { handleRouterSpecsRequest, loadRouterSpecDirectory, ROUTERS_ROUTE, RouterSpecStore, servedRouter, servedRouterIds, } from "./router_specs.js";
24
+ import { handlePrivateModeRequest, PRIVATE_MODE_ROUTE, PrivateMode } from "./private_mode.js";
24
25
  import { SessionPinStore } from "./session_pin_store.js";
25
26
  import { handleSubscriptionRequest, SubscriptionStore } from "./subscriptions/index.js";
26
27
  import { providerBaseUrls } from "./subscriptions/resets.js";
@@ -28,8 +29,8 @@ import { refreshStaleUsage } from "./subscriptions/usage.js";
28
29
  const SUBSCRIPTION_ROUTES = "/v1/organizations/current/credentials";
29
30
  // The models Dari serves, which the Dari CLI's model picker offers.
30
31
  const CANONICAL_MODELS_ROUTE = "/v1/canonical-models";
31
- // How often a connected gateway reads idle plans' usage, so hosted Dari's
32
- // meters move without a request here.
32
+ // How often a connected gateway reads idle plans' usage, so their meters move
33
+ // without a request here.
33
34
  const IDLE_USAGE_INTERVAL_MS = 5 * 60_000;
34
35
  /**
35
36
  * Start a self-hosted Dari Gateway from environment variables:
@@ -59,8 +60,9 @@ const IDLE_USAGE_INTERVAL_MS = 5 * 60_000;
59
60
  * - `DARI_HOSTED_URL` and `DARI_HOSTED_API_KEY`: connect the gateway to hosted
60
61
  * Dari (connected.ts), with `DARI_GATEWAY_ID`, `DARI_GATEWAY_NAME`, and
61
62
  * `DARI_GATEWAY_ENCRYPTION_KEY`. It then serves the user's hosted routers on
62
- * its own plans and then on hosted Dari, and syncs its plans and requests
63
- * there; Dari Link and Activity are hosted's.
63
+ * its own plans and then on hosted Dari, and syncs its requests there unless
64
+ * private mode is on (`/v1/gateway/private`); Dari Link and Activity are
65
+ * hosted's.
64
66
  */
65
67
  export async function startSelfHostedGateway(env = process.env) {
66
68
  const hosted = hostedConnectionFromEnv(env);
@@ -85,6 +87,11 @@ export async function startSelfHostedGateway(env = process.env) {
85
87
  console.warn("dari-gateway stores subscription tokens unencrypted; set DARI_GATEWAY_ENCRYPTION_KEY (openssl rand -base64 32) to encrypt them");
86
88
  }
87
89
  const subscriptions = new SubscriptionStore(db, secrets);
90
+ const privateMode = new PrivateMode(db);
91
+ // Plans marked private before private mode kept their requests out of
92
+ // Activity; the gateway now keeps all of them out instead.
93
+ if (subscriptions.clearLegacyPrivate())
94
+ privateMode.set(true);
88
95
  const prefixes = new PrefixStore(db);
89
96
  const sessionPins = new SessionPinStore(db);
90
97
  const routerModels = new RouterModelStore(db);
@@ -156,7 +163,7 @@ export async function startSelfHostedGateway(env = process.env) {
156
163
  const routed = createRequestHandler({ platform, selectorBackend });
157
164
  const gateway = hosted === null || sync === null || hostedRouter === null
158
165
  ? routed
159
- : connectedHandler({ gateway: routed, gatewayKeys, hosted, hostedRouter, fetch });
166
+ : connectedHandler({ gateway: routed, gatewayKeys, hosted, hostedRouter, privateMode, fetch });
160
167
  // Subscriptions, model lists, and router specs are managed with any gateway
161
168
  // key; every other path is the gateway's own.
162
169
  const handler = async (request) => {
@@ -165,7 +172,8 @@ export async function startSelfHostedGateway(env = process.env) {
165
172
  || pathname.startsWith(`${SUBSCRIPTION_ROUTES}/`)
166
173
  || pathname === CANONICAL_MODELS_ROUTE
167
174
  || ROUTER_MODELS_ROUTE.test(pathname)
168
- || ROUTERS_ROUTE.test(pathname);
175
+ || ROUTERS_ROUTE.test(pathname)
176
+ || pathname === PRIVATE_MODE_ROUTE;
169
177
  if (!manages)
170
178
  return await gateway(request);
171
179
  try {
@@ -176,6 +184,8 @@ export async function startSelfHostedGateway(env = process.env) {
176
184
  catch (error) {
177
185
  return errorResponse(error);
178
186
  }
187
+ if (pathname === PRIVATE_MODE_ROUTE)
188
+ return await handlePrivateModeRequest(request, privateMode).catch(errorResponse);
179
189
  if (pathname === CANONICAL_MODELS_ROUTE && request.method === "GET") {
180
190
  return Response.json({ data: CANONICAL_MODELS }, { headers: { "Cache-Control": "no-store" } });
181
191
  }
@@ -0,0 +1,16 @@
1
+ import type { Database } from "bun:sqlite";
2
+ /** `GET` reads private mode and `PUT {"private": true|false}` sets it. */
3
+ export declare const PRIVATE_MODE_ROUTE = "/v1/gateway/private";
4
+ /**
5
+ * Private mode of a gateway connected to hosted Dari, kept in its database:
6
+ * on, none of its requests reach Activity, whichever plan or Dari serves them.
7
+ * It sends none to hosted Activity, and asks hosted Dari to keep only what
8
+ * billing needs of each it serves (PRIVATE_HEADER).
9
+ */
10
+ export declare class PrivateMode {
11
+ private readonly db;
12
+ constructor(db: Database);
13
+ get on(): boolean;
14
+ set(on: boolean): void;
15
+ }
16
+ export declare function handlePrivateModeRequest(request: Request, mode: PrivateMode): Promise<Response>;
@@ -0,0 +1,35 @@
1
+ import { HttpError } from "../http/errors.js";
2
+ import { parseJsonRequest } from "../ingress/json.js";
3
+ /** `GET` reads private mode and `PUT {"private": true|false}` sets it. */
4
+ export const PRIVATE_MODE_ROUTE = "/v1/gateway/private";
5
+ /**
6
+ * Private mode of a gateway connected to hosted Dari, kept in its database:
7
+ * on, none of its requests reach Activity, whichever plan or Dari serves them.
8
+ * It sends none to hosted Activity, and asks hosted Dari to keep only what
9
+ * billing needs of each it serves (PRIVATE_HEADER).
10
+ */
11
+ export class PrivateMode {
12
+ db;
13
+ constructor(db) {
14
+ this.db = db;
15
+ db.run("CREATE TABLE IF NOT EXISTS gateway_settings (key TEXT PRIMARY KEY, value TEXT NOT NULL)");
16
+ }
17
+ get on() {
18
+ return this.db.query("SELECT value FROM gateway_settings WHERE key = 'private'").get()?.value === "1";
19
+ }
20
+ set(on) {
21
+ this.db.run("INSERT INTO gateway_settings (key, value) VALUES ('private', ?) ON CONFLICT (key) DO UPDATE SET value = excluded.value", [on ? "1" : "0"]);
22
+ }
23
+ }
24
+ export async function handlePrivateModeRequest(request, mode) {
25
+ if (request.method === "PUT") {
26
+ const body = await parseJsonRequest(request);
27
+ if (typeof body.private !== "boolean")
28
+ throw new HttpError(400, "private must be true or false.", "invalid_request_error");
29
+ mode.set(body.private);
30
+ }
31
+ else if (request.method !== "GET") {
32
+ throw new HttpError(405, "Use GET or PUT.", "method_not_allowed");
33
+ }
34
+ return Response.json({ private: mode.on }, { headers: { "Cache-Control": "no-store" } });
35
+ }
@@ -1,7 +1,7 @@
1
1
  import { timingSafeEqual } from "node:crypto";
2
2
  import { isReasoningEffort, nativeModelId, providerForModel, } from "@mupt-ai/dari-router/policy-engine";
3
3
  import { HttpError } from "../http/errors.js";
4
- import { DEFAULT_ROUTER_ALIAS, HOSTED_DARI_PROVIDER } from "../platform/routing_contract.js";
4
+ import { DEFAULT_ROUTER_ALIAS, HOSTED_DARI_PROVIDER, PRIVATE_HEADER } from "../platform/routing_contract.js";
5
5
  import { explicitModelSlug } from "../protocol/input/router_model.js";
6
6
  import { CLIENT_HARNESS_HEADER } from "../ingress/client_harness.js";
7
7
  import { codexModelConfig, modelSubscriptions, subscriptionClient, subscriptionModelProvider, } from "../models/subscriptions.js";
@@ -382,7 +382,8 @@ function candidateConfig(deps, modelId, candidate) {
382
382
  * called for `dari/model/<id>` with the user's Dari key, in Anthropic's API
383
383
  * for Anthropic's models and OpenAI's Responses API for the rest, with the
384
384
  * client's own identifying headers and the coding agent it named, so hosted
385
- * sees the same client. Hosted Dari bills and logs what it serves.
385
+ * sees the same client. Hosted Dari bills and logs what it serves; a private
386
+ * request asks it to keep only what billing needs.
386
387
  */
387
388
  function hostedCandidate(hosted, request, modelId) {
388
389
  let routerUrl = hosted.url;
@@ -398,6 +399,8 @@ function hostedCandidate(hosted, request, modelId) {
398
399
  const headers = { ...request.clientHeaders };
399
400
  if (request.clientHarness !== undefined)
400
401
  headers[CLIENT_HARNESS_HEADER] = request.clientHarness;
402
+ if (request.private === true)
403
+ headers[PRIVATE_HEADER] = "true";
401
404
  return {
402
405
  provider: HOSTED_DARI_PROVIDER,
403
406
  key: hosted.apiKey,
@@ -12,7 +12,7 @@ import { refreshStaleUsage } from "./usage.js";
12
12
  const BASE = "/v1/organizations/current/credentials";
13
13
  // Subscription names are env-var-style, which keeps other credential routes
14
14
  // such as `provider-credentials/...` out of these matches.
15
- const NAMED = /^\/([A-Za-z_][A-Za-z0-9_]*)(\/label|\/mark-available|\/private|\/resets|\/resets\/[^/]+\/use)?$/;
15
+ const NAMED = /^\/([A-Za-z_][A-Za-z0-9_]*)(\/label|\/mark-available|\/resets|\/resets\/[^/]+\/use)?$/;
16
16
  class HttpError extends Error {
17
17
  status;
18
18
  constructor(status, message) {
@@ -70,14 +70,6 @@ export async function handleSubscriptionRequest(request, deps) {
70
70
  }
71
71
  return json(200, summary(deps.store, found(renamed, name), now));
72
72
  }
73
- if (action === "/private" && request.method === "PUT") {
74
- // Private plans stay off hosted Dari: a connected gateway neither
75
- // serves nor reports them.
76
- const body = await readBody(request);
77
- if (typeof body.private !== "boolean")
78
- throw new HttpError(400, "private must be true or false.");
79
- return json(200, summary(deps.store, found(deps.store.setPrivate(name, body.private, now), name), now));
80
- }
81
73
  if (action === "/mark-available" && request.method === "POST") {
82
74
  return json(200, summary(deps.store, found(deps.store.markAvailable(name, now), name), now));
83
75
  }
@@ -135,10 +127,6 @@ async function startSession(deps, body, now) {
135
127
  if (credentialName !== null && reconnecting?.provider !== provider) {
136
128
  throw new HttpError(404, `Unknown subscription credential ${JSON.stringify(credentialName)}.`);
137
129
  }
138
- // A reconnected plan stays where it was unless the caller says otherwise.
139
- const isPrivate = body.private ?? reconnecting?.private ?? false;
140
- if (typeof isPrivate !== "boolean")
141
- throw new HttpError(400, "private must be true or false.");
142
130
  // `dari accounts subscription connect` names the hosted plan it moves here.
143
131
  const movingFrom = body.moving_from ?? null;
144
132
  if (movingFrom !== null && (typeof movingFrom !== "string" || !movingFrom.trim())) {
@@ -150,7 +138,6 @@ async function startSession(deps, body, now) {
150
138
  flow: authorization.flow,
151
139
  credentialName,
152
140
  owner: null,
153
- private: isPrivate,
154
141
  movingFrom,
155
142
  expiresAt: authorization.expiresAt,
156
143
  }, now);
@@ -196,7 +183,7 @@ async function completeSession(deps, body, now) {
196
183
  console.error("hosted account check failed", error instanceof Error ? error.message : String(error));
197
184
  }
198
185
  }
199
- const stored = deps.store.connect(tokens, session.credentialName, now, null, session.private, elsewhere);
186
+ const stored = deps.store.connect(tokens, session.credentialName, now, null, elsewhere);
200
187
  if (stored === null) {
201
188
  throw new HttpError(404, `Unknown subscription credential ${JSON.stringify(session.credentialName)}.`);
202
189
  }
@@ -286,8 +273,6 @@ function credentialBody(credential, active, now) {
286
273
  // subscription here belongs to the gateway's one user.
287
274
  credential_scope: "user",
288
275
  oauth_provider: credential.provider,
289
- // Kept off hosted Dari (`dari accounts subscription connect --on private`).
290
- private: credential.private,
291
276
  created_at: credential.createdAt.toISOString(),
292
277
  last_used_at: credential.lastUsedAt?.toISOString() ?? null,
293
278
  unavailable_until: held ? credential.unavailableUntil.toISOString() : null,