@mupt-ai/dari-gateway 1.0.368 → 1.0.370

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 (114) hide show
  1. package/dist/harnesses/claude_code.d.ts +11 -0
  2. package/dist/{ingress/claude_code/request_context.js → harnesses/claude_code.js} +40 -1
  3. package/dist/harnesses/codex.d.ts +9 -0
  4. package/dist/harnesses/codex.js +112 -0
  5. package/dist/harnesses/hermes.d.ts +4 -0
  6. package/dist/harnesses/hermes.js +6 -0
  7. package/dist/harnesses/index.d.ts +34 -0
  8. package/dist/harnesses/index.js +13 -0
  9. package/dist/harnesses/muse_code.d.ts +9 -0
  10. package/dist/harnesses/muse_code.js +22 -0
  11. package/dist/harnesses/openclaw.d.ts +4 -0
  12. package/dist/harnesses/openclaw.js +6 -0
  13. package/dist/harnesses/opencode.d.ts +7 -0
  14. package/dist/harnesses/opencode.js +40 -0
  15. package/dist/harnesses/pi.d.ts +6 -0
  16. package/dist/harnesses/pi.js +23 -0
  17. package/dist/ingress/client_harness.d.ts +1 -2
  18. package/dist/ingress/client_harness.js +4 -39
  19. package/dist/ingress/harness_request.js +6 -3
  20. package/dist/ingress/models.js +2 -1
  21. package/dist/link/endpoints.js +5 -5
  22. package/dist/link/self_hosted.js +0 -1
  23. package/dist/platform/platform.d.ts +2 -0
  24. package/dist/platform/routing_contract.d.ts +1 -0
  25. package/dist/platform/routing_contract.js +4 -0
  26. package/dist/protocol/output/anthropic_messages.d.ts +1 -0
  27. package/dist/protocol/output/anthropic_messages.js +1 -1
  28. package/dist/protocol/output/anthropic_messages_output.d.ts +1 -1
  29. package/dist/protocol/output/anthropic_messages_output.js +3 -1
  30. package/dist/protocol/output/anthropic_messages_stream.d.ts +1 -0
  31. package/dist/protocol/output/anthropic_messages_stream.js +1 -1
  32. package/dist/protocol/output/chat_completions.d.ts +2 -0
  33. package/dist/protocol/output/chat_completions.js +5 -3
  34. package/dist/protocol/output/openai_responses.d.ts +1 -0
  35. package/dist/protocol/output/openai_responses.js +1 -1
  36. package/dist/protocol/output/openai_responses_output.d.ts +1 -1
  37. package/dist/protocol/output/openai_responses_output.js +3 -1
  38. package/dist/protocol/output/openai_responses_stream.d.ts +1 -0
  39. package/dist/protocol/output/openai_responses_stream.js +1 -1
  40. package/dist/providers/execution.d.ts +1 -0
  41. package/dist/providers/execution.js +29 -7
  42. package/dist/providers/provider_call.d.ts +1 -0
  43. package/dist/providers/provider_call.js +2 -0
  44. package/dist/runtime/harness_identity/extract.d.ts +0 -8
  45. package/dist/runtime/harness_identity/extract.js +2 -201
  46. package/dist/runtime/harness_identity/ids.d.ts +2 -0
  47. package/dist/runtime/harness_identity/ids.js +26 -0
  48. package/dist/runtime/harness_identity/index.d.ts +1 -1
  49. package/dist/runtime/harness_identity/index.js +1 -1
  50. package/dist/runtime/prepare_routed_completion.d.ts +1 -0
  51. package/dist/runtime/prepare_routed_completion.js +4 -0
  52. package/dist/runtime/routed_completion.js +4 -1
  53. package/dist/runtime/routed_protocol.d.ts +2 -0
  54. package/dist/self_host/config.js +1 -1
  55. package/dist/self_host/connected.d.ts +7 -3
  56. package/dist/self_host/connected.js +9 -10
  57. package/dist/self_host/hosted_sync.js +1 -1
  58. package/dist/self_host/main.d.ts +3 -2
  59. package/dist/self_host/main.js +16 -6
  60. package/dist/self_host/private_mode.d.ts +16 -0
  61. package/dist/self_host/private_mode.js +35 -0
  62. package/dist/self_host/resolve.js +5 -2
  63. package/dist/self_host/router_models.js +1 -1
  64. package/dist/self_host/subscriptions/http.js +2 -17
  65. package/dist/self_host/subscriptions/store.d.ts +7 -6
  66. package/dist/self_host/subscriptions/store.js +15 -27
  67. package/dist/telemetry/report.js +1 -0
  68. package/dist/types.d.ts +2 -1
  69. package/package.json +2 -2
  70. package/src/{ingress/claude_code/request_context.ts → harnesses/claude_code.ts} +56 -2
  71. package/src/harnesses/codex.ts +156 -0
  72. package/src/harnesses/hermes.ts +8 -0
  73. package/src/harnesses/index.ts +29 -0
  74. package/src/harnesses/muse_code.ts +30 -0
  75. package/src/harnesses/openclaw.ts +8 -0
  76. package/src/harnesses/opencode.ts +51 -0
  77. package/src/harnesses/pi.ts +28 -0
  78. package/src/ingress/client_harness.ts +4 -41
  79. package/src/ingress/harness_request.ts +9 -9
  80. package/src/ingress/models.ts +2 -1
  81. package/src/link/endpoints.ts +5 -5
  82. package/src/link/self_hosted.ts +0 -1
  83. package/src/platform/platform.ts +6 -0
  84. package/src/platform/routing_contract.ts +5 -0
  85. package/src/protocol/output/anthropic_messages.ts +2 -1
  86. package/src/protocol/output/anthropic_messages_output.ts +4 -1
  87. package/src/protocol/output/anthropic_messages_stream.ts +2 -1
  88. package/src/protocol/output/chat_completions.ts +7 -3
  89. package/src/protocol/output/openai_responses.ts +2 -1
  90. package/src/protocol/output/openai_responses_output.ts +4 -1
  91. package/src/protocol/output/openai_responses_stream.ts +2 -1
  92. package/src/providers/execution.ts +36 -7
  93. package/src/providers/provider_call.ts +5 -0
  94. package/src/runtime/harness_identity/extract.ts +2 -284
  95. package/src/runtime/harness_identity/ids.ts +41 -0
  96. package/src/runtime/harness_identity/index.ts +1 -10
  97. package/src/runtime/prepare_routed_completion.ts +4 -0
  98. package/src/runtime/routed_completion.ts +4 -1
  99. package/src/runtime/routed_protocol.ts +2 -0
  100. package/src/self_host/config.ts +1 -1
  101. package/src/self_host/connected.ts +16 -12
  102. package/src/self_host/hosted_sync.ts +1 -1
  103. package/src/self_host/main.ts +14 -6
  104. package/src/self_host/private_mode.ts +41 -0
  105. package/src/self_host/resolve.ts +4 -2
  106. package/src/self_host/router_models.ts +1 -1
  107. package/src/self_host/subscriptions/http.ts +2 -15
  108. package/src/self_host/subscriptions/store.ts +15 -34
  109. package/src/telemetry/report.ts +1 -0
  110. package/src/types.ts +5 -10
  111. package/dist/ingress/claude_code/request_context.d.ts +0 -4
  112. package/dist/ingress/muse_code.d.ts +0 -2
  113. package/dist/ingress/muse_code.js +0 -8
  114. package/src/ingress/muse_code.ts +0 -9
@@ -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) {
@@ -18,6 +18,7 @@ export type PreparedStreamExecution = {
18
18
  };
19
19
  export type CompletedNonStreamingExecution = {
20
20
  choice: ProviderChoice;
21
+ requestId: string;
21
22
  output: ReturnType<typeof piMessageToInteractionOutput>;
22
23
  responseBody: Record<string, unknown>;
23
24
  reportBarrierError?: unknown;
@@ -8,6 +8,7 @@ import { credentialRejectionFromFailure, failureWithCredentialRejection, isProvi
8
8
  import { reportedExecution, } from "../runtime/runtime_reporter.js";
9
9
  import { trackBackgroundTelemetry } from "../telemetry/background.js";
10
10
  import { gatewayPlatform } from "../platform/platform.js";
11
+ import { HOSTED_DARI_PROVIDER } from "../platform/routing_contract.js";
11
12
  import { reportRoutingUsage } from "../telemetry/usage.js";
12
13
  import { primeProviderStream, scrubProviderMessage, startProviderCompletion, startProviderStream, } from "./provider_call.js";
13
14
  import { runProviderAttemptPlan, } from "./provider_attempt_runner.js";
@@ -26,7 +27,11 @@ export async function executeNonStreaming(args) {
26
27
  });
27
28
  }
28
29
  return Response.json(result.responseBody, {
29
- headers: { ...result.choice.execution.headers, ...linkUsageHeaders(result) },
30
+ headers: {
31
+ ...result.choice.execution.headers,
32
+ ...linkUsageHeaders(result),
33
+ "X-Request-Id": result.requestId,
34
+ },
30
35
  });
31
36
  }
32
37
  // One usage shape for a Dari Link app whatever protocol it speaks: the tokens
@@ -66,13 +71,14 @@ export async function completeNonStreaming(args) {
66
71
  result,
67
72
  });
68
73
  }
69
- const { value: { completion }, choice, } = result;
74
+ const { value: { completion, responseCapture }, choice, } = result;
75
+ const requestId = servedRequestId(args.requestId, choice.execution, responseCapture);
70
76
  let output;
71
77
  let responseBody;
72
78
  try {
73
79
  output = piMessageToInteractionOutput(completion.message, completion.source, args.interaction);
74
80
  responseBody = args.protocol.responseBody({
75
- id: args.requestId,
81
+ id: requestId,
76
82
  model: choice.execution.model,
77
83
  output,
78
84
  modelCost: args.reporter.modelCost({
@@ -83,6 +89,7 @@ export async function completeNonStreaming(args) {
83
89
  request: args.interaction,
84
90
  routing: choice.decision,
85
91
  conversationId: choice.execution.conversationId,
92
+ private: choice.execution.private,
86
93
  });
87
94
  }
88
95
  catch (error) {
@@ -131,6 +138,7 @@ export async function completeNonStreaming(args) {
131
138
  await args.reporter.waitForPrefixEntryWrite();
132
139
  return {
133
140
  choice,
141
+ requestId,
134
142
  output,
135
143
  responseBody,
136
144
  ...(reportBarrierError === undefined ? {} : { reportBarrierError }),
@@ -179,7 +187,7 @@ async function runCompletionAttempt(args) {
179
187
  }
180
188
  return {
181
189
  kind: "succeeded",
182
- value: { completion },
190
+ value: { completion, responseCapture: started.responseCapture },
183
191
  latencyMs: completion.providerLatencyMs,
184
192
  };
185
193
  }
@@ -358,6 +366,7 @@ async function runStreamSetupAttempt(args) {
358
366
  source: started.providerStream.source,
359
367
  },
360
368
  customerAbort: started.customerAbort,
369
+ responseCapture: started.responseCapture,
361
370
  },
362
371
  latencyMs: 0,
363
372
  };
@@ -375,6 +384,7 @@ async function runStreamSetupAttempt(args) {
375
384
  export async function executeStreaming(args) {
376
385
  const { execution } = args.choice;
377
386
  const started = args.startedStream;
387
+ const requestId = servedRequestId(args.requestId, execution, started.responseCapture);
378
388
  args.reporter.attachServingDecision(args.choice.decision);
379
389
  const observed = observeDeliveredOutput(started.providerStream.events);
380
390
  const finalizer = createStreamFinalizer({
@@ -392,13 +402,14 @@ export async function executeStreaming(args) {
392
402
  startedAtMs: started.providerStartedMs,
393
403
  });
394
404
  return new Response(args.protocol.streamBody({
395
- id: args.requestId,
405
+ id: requestId,
396
406
  model: execution.model,
397
407
  routing: args.choice.decision,
398
408
  events: observed.events,
399
409
  source: started.providerStream.source,
400
410
  request: args.interaction,
401
411
  conversationId: execution.conversationId,
412
+ private: execution.private,
402
413
  clientSignal: args.clientSignal,
403
414
  modelCost: (message, failed) => args.reporter.modelCost({
404
415
  model: args.choice.decision.selectedModel, reasoning_effort: args.choice.decision.reasoningEffort,
@@ -413,16 +424,27 @@ export async function executeStreaming(args) {
413
424
  started.customerAbort.dispose();
414
425
  trackBackgroundTelemetry(finalizer.afterResponseDetached(outcome));
415
426
  },
416
- }), { headers: streamHeaders(execution) });
427
+ }), { headers: streamHeaders(execution, requestId) });
417
428
  }
418
- function streamHeaders(execution) {
429
+ function streamHeaders(execution, requestId) {
419
430
  return {
420
431
  "Content-Type": "text/event-stream",
421
432
  "Cache-Control": "no-cache",
422
433
  "Connection": "keep-alive",
423
434
  ...execution.headers,
435
+ "X-Request-Id": requestId,
424
436
  };
425
437
  }
438
+ /**
439
+ * The request ID the client is told, in the response and its `X-Request-Id`:
440
+ * this gateway's own, except for a request hosted Dari served. Hosted logs
441
+ * that one under the ID it answered with, and Activity finds it only by that.
442
+ */
443
+ function servedRequestId(requestId, execution, capture) {
444
+ if (execution.provider !== HOSTED_DARI_PROVIDER)
445
+ return requestId;
446
+ return capture?.succeeded?.get("x-request-id")?.trim() || requestId;
447
+ }
426
448
  function customerAbortRequested(clientSignal) {
427
449
  // A disconnected client never starts new paid work that nobody can receive.
428
450
  return clientSignal?.aborted === true;
@@ -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
  }
@@ -1,10 +1,2 @@
1
- import type { AgentRequestContext, InteractionRequestPurpose } from "../../interaction/types.js";
2
1
  import type { HarnessConversationIdentity } from "./conversation.js";
3
2
  export declare function chatCompletionsConversationIdentity(headers: Headers, promptCacheKey?: string): HarnessConversationIdentity | undefined;
4
- export declare function piRequestContext(headers: Headers): AgentRequestContext | undefined;
5
- export declare function openCodeRequestContext(headers: Headers): AgentRequestContext | undefined;
6
- export declare function codexConversationIdentity(headers: Headers, payload: Record<string, unknown>): HarnessConversationIdentity | undefined;
7
- export declare function codexRequestPurpose(headers: Headers, payload: Record<string, unknown>): InteractionRequestPurpose | undefined;
8
- export declare function codexRequestContext(headers: Headers, payload: Record<string, unknown>): AgentRequestContext | undefined;
9
- export declare function museCodeConversationIdentity(headers: Headers): HarnessConversationIdentity | undefined;
10
- export declare function claudeCodeConversationIdentity(headers: Headers, metadataSessionId?: string): HarnessConversationIdentity | undefined;
@@ -1,6 +1,5 @@
1
- import { isRecord } from "@mupt-ai/dari-router/policy-engine";
2
- import { HttpError } from "../../http/errors.js";
3
- const MAX_ID_CHARS = 200;
1
+ import { openCodeSubagentId } from "../../harnesses/opencode.js";
2
+ import { boundedIdentity } from "./ids.js";
4
3
  export function chatCompletionsConversationIdentity(headers, promptCacheKey) {
5
4
  // Pi summaries use fresh cache/affinity IDs. Its explicit session header
6
5
  // groups them with the main turns without changing provider cache affinity.
@@ -18,201 +17,3 @@ export function chatCompletionsConversationIdentity(headers, promptCacheKey) {
18
17
  ...(subagentId === undefined ? {} : { qualifiers: [subagentId] }),
19
18
  };
20
19
  }
21
- export function piRequestContext(headers) {
22
- if (boundedIdentity(headers.get("x-pi-session-id"), "x-pi-session-id") === undefined) {
23
- return undefined;
24
- }
25
- const kind = headers.get("x-pi-request-kind")?.trim();
26
- return {
27
- requestClass: kind === "turn" ? "main"
28
- : kind === "compaction" ? "compaction"
29
- // The Dari extension's web search tool: one request beside the turn,
30
- // served as background work like Claude Code's own search.
31
- : kind === "search" ? "auxiliary"
32
- : "unknown",
33
- };
34
- }
35
- // OpenCode names the session behind every request, and a subagent's parent
36
- // session too. The `dari opencode` plugin adds the request kind and agent,
37
- // which OpenCode does not send itself. Like Claude Code's headers, these are
38
- // client-supplied routing hints, never inferred from prompt text.
39
- export function openCodeRequestContext(headers) {
40
- if (boundedIdentity(headers.get("x-opencode-session-id"), "x-opencode-session-id") === undefined) {
41
- return undefined;
42
- }
43
- const kind = headers.get("x-opencode-request-kind")?.trim();
44
- const subagentId = openCodeSubagentId(headers);
45
- const requestClass = kind === "compaction" ? "compaction"
46
- : kind === "title" || kind === "generate" ? "auxiliary"
47
- : subagentId === undefined ? "main" : "subagent";
48
- return {
49
- requestClass,
50
- ...(subagentId === undefined ? {} : {
51
- agentId: subagentId,
52
- parentAgentId: boundedIdentity(headers.get("x-opencode-parent-session-id"), "x-opencode-parent-session-id"),
53
- }),
54
- agentType: boundedIdentity(headers.get("x-opencode-agent"), "x-opencode-agent"),
55
- };
56
- }
57
- function openCodeSubagentId(headers) {
58
- const parent = boundedIdentity(headers.get("x-opencode-parent-session-id"), "x-opencode-parent-session-id");
59
- return parent === undefined
60
- ? undefined
61
- : boundedIdentity(headers.get("x-opencode-session-id"), "x-opencode-session-id");
62
- }
63
- export function codexConversationIdentity(headers, payload) {
64
- const clientMetadata = isRecord(payload.client_metadata)
65
- ? payload.client_metadata
66
- : undefined;
67
- const turnMetadata = codexTurnMetadataCollection(headers, payload);
68
- if (turnMetadata.length === 0) {
69
- return undefined;
70
- }
71
- // Clients can carry a stale projection after a resume or fork. Conflicts
72
- // must not fail the request, and fields must not mix across projections:
73
- // take thread, turn, and parent from one turn metadata projection, header
74
- // first, falling back to the standalone thread fields only for the thread.
75
- const entry = turnMetadata.find((metadata) => metadata.thread_id !== undefined)
76
- ?? turnMetadata[0];
77
- const threadId = uuidIdentity(entry.thread_id, "x-codex-turn-metadata.thread_id")
78
- ?? uuidIdentity(headers.get("thread-id"), "thread-id")
79
- ?? uuidIdentity(clientMetadata?.thread_id, "client_metadata.thread_id");
80
- if (threadId === undefined) {
81
- return undefined;
82
- }
83
- const userTurnId = uuidIdentity(entry.turn_id, "x-codex-turn-metadata.turn_id");
84
- const parentThreadId = uuidIdentity(entry.parent_thread_id, "x-codex-turn-metadata.parent_thread_id");
85
- return {
86
- kind: "codex_thread",
87
- value: threadId,
88
- ...(parentThreadId === undefined ? {} : { parentThreadId }),
89
- ...(userTurnId === undefined ? {} : { userTurnId }),
90
- };
91
- }
92
- export function codexRequestPurpose(headers, payload) {
93
- const turnMetadata = codexTurnMetadataCollection(headers, payload);
94
- return turnMetadata.length > 0 && turnMetadata.every(isCodexMemoryExtraction)
95
- ? "memory_extraction"
96
- : undefined;
97
- }
98
- export function codexRequestContext(headers, payload) {
99
- const metadata = codexTurnMetadataCollection(headers, payload);
100
- if (metadata.length === 0)
101
- return undefined;
102
- // Classify from one projection, header first, skipping one that omits the
103
- // request kind so a partial header falls back to a complete body.
104
- const entry = metadata.find((candidate) => candidate.request_kind !== undefined)
105
- ?? metadata[0];
106
- const kind = entry.request_kind;
107
- const agentKind = entry.subagent_kind;
108
- const agentId = uuidIdentity(entry.thread_id, "x-codex-turn-metadata.thread_id");
109
- const requestClass = kind === "compaction" ? "compaction"
110
- : kind === "memory" || kind === "prewarm" ? "auxiliary"
111
- : kind === "turn" && agentKind === "memory_consolidation" ? "auxiliary"
112
- : kind === "turn" && agentKind === "compact" ? "compaction"
113
- : kind === "turn" && agentKind !== undefined ? "subagent"
114
- : kind === "turn" ? "main" : "unknown";
115
- return {
116
- requestClass,
117
- ...(requestClass === "subagent" && agentId !== undefined ? { agentId } : {}),
118
- parentAgentId: uuidIdentity(entry.parent_thread_id, "x-codex-turn-metadata.parent_thread_id"),
119
- agentType: boundedIdentity(agentKind, "x-codex-turn-metadata.subagent_kind"),
120
- };
121
- }
122
- // Muse Code sends its thread on every Responses request. The main agent's
123
- // thread is its session, and each subagent has its own thread, so each keeps
124
- // its own conversation and lease.
125
- export function museCodeConversationIdentity(headers) {
126
- const threadId = boundedIdentity(headers.get("x-tbh-thread-id"), "x-tbh-thread-id");
127
- return threadId === undefined ? undefined : { kind: "muse_code_thread", value: threadId };
128
- }
129
- export function claudeCodeConversationIdentity(headers, metadataSessionId) {
130
- const candidates = [
131
- uuidIdentity(headers.get("x-claude-code-session-id"), "x-claude-code-session-id"),
132
- uuidIdentity(metadataSessionId, "metadata.user_id.session_id"),
133
- ].filter((value) => value !== undefined);
134
- if (candidates.length === 0)
135
- return undefined;
136
- // Claude Code can carry a stale metadata session after a resume or fork.
137
- // The header names the live session, so it wins over the metadata.
138
- const [sessionId] = candidates;
139
- // Claude Code reuses the parent session UUID for every subagent, but gives
140
- // each subagent a stable agent header. Keep the parent thread on the bare
141
- // session identity and scope each subagent to its own composite identity.
142
- // Treat this as an opaque Claude identifier. Besides ordinary subagent IDs,
143
- // Claude may send labeled agents or Agent Teams identities such as
144
- // `reviewer@backend`; Dari only needs a stable, bounded value to hash.
145
- const agentId = boundedIdentity(headers.get("x-claude-code-agent-id"), "x-claude-code-agent-id");
146
- return {
147
- kind: "claude_code_session",
148
- value: sessionId,
149
- ...(agentId === undefined ? {} : { qualifiers: [agentId] }),
150
- };
151
- }
152
- function isCodexMemoryExtraction(metadata) {
153
- if (metadata.request_kind !== "memory" ||
154
- metadata.thread_source !== "memory_consolidation") {
155
- return false;
156
- }
157
- // Codex deliberately omits canonical turn identity for detached phase-1
158
- // memory jobs, while compatibility projections still carry the live root
159
- // thread UUID. Phase-2 consolidation agents use ordinary turn metadata and
160
- // their own thread identities, so they do not match this shape.
161
- return [
162
- "session_id",
163
- "thread_id",
164
- "turn_id",
165
- "root_turn_id",
166
- "window_id",
167
- "forked_from_thread_id",
168
- ].every((field) => metadata[field] === undefined);
169
- }
170
- function codexTurnMetadataCollection(headers, payload) {
171
- const clientMetadata = isRecord(payload.client_metadata)
172
- ? payload.client_metadata
173
- : undefined;
174
- return [
175
- codexTurnMetadata(headers.get("x-codex-turn-metadata"), "x-codex-turn-metadata"),
176
- codexTurnMetadata(clientMetadata?.["x-codex-turn-metadata"], "client_metadata.x-codex-turn-metadata"),
177
- ].filter((value) => value !== undefined);
178
- }
179
- function boundedIdentity(value, field) {
180
- if (value === undefined || value === null)
181
- return undefined;
182
- if (typeof value !== "string") {
183
- throw new HttpError(400, `${field} must be a string.`, "invalid_request_error", field);
184
- }
185
- const normalized = value.trim();
186
- if (!normalized)
187
- return undefined;
188
- if (normalized.length > MAX_ID_CHARS) {
189
- throw new HttpError(400, `${field} must not exceed ${MAX_ID_CHARS} characters.`, "invalid_request_error", field);
190
- }
191
- return normalized;
192
- }
193
- function uuidIdentity(value, field) {
194
- const normalized = boundedIdentity(value, field);
195
- if (normalized === undefined)
196
- return undefined;
197
- const canonical = normalized.toLowerCase();
198
- if (!/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/.test(canonical)) {
199
- throw new HttpError(400, `${field} must be a UUID.`, "invalid_request_error", field);
200
- }
201
- return canonical;
202
- }
203
- function codexTurnMetadata(raw, field) {
204
- if (raw === undefined || raw === null)
205
- return undefined;
206
- if (typeof raw !== "string") {
207
- throw new HttpError(400, `${field} must be a JSON string.`, "invalid_request_error", field);
208
- }
209
- try {
210
- const parsed = JSON.parse(raw);
211
- if (!isRecord(parsed))
212
- throw new Error("not an object");
213
- return parsed;
214
- }
215
- catch {
216
- throw new HttpError(400, `${field} must contain a JSON object.`, "invalid_request_error", field);
217
- }
218
- }
@@ -0,0 +1,2 @@
1
+ export declare function boundedIdentity(value: unknown, field: string): string | undefined;
2
+ export declare function uuidIdentity(value: unknown, field: string): string | undefined;
@@ -0,0 +1,26 @@
1
+ import { HttpError } from "../../http/errors.js";
2
+ const MAX_ID_CHARS = 200;
3
+ export function boundedIdentity(value, field) {
4
+ if (value === undefined || value === null)
5
+ return undefined;
6
+ if (typeof value !== "string") {
7
+ throw new HttpError(400, `${field} must be a string.`, "invalid_request_error", field);
8
+ }
9
+ const normalized = value.trim();
10
+ if (!normalized)
11
+ return undefined;
12
+ if (normalized.length > MAX_ID_CHARS) {
13
+ throw new HttpError(400, `${field} must not exceed ${MAX_ID_CHARS} characters.`, "invalid_request_error", field);
14
+ }
15
+ return normalized;
16
+ }
17
+ export function uuidIdentity(value, field) {
18
+ const normalized = boundedIdentity(value, field);
19
+ if (normalized === undefined)
20
+ return undefined;
21
+ const canonical = normalized.toLowerCase();
22
+ if (!/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/.test(canonical)) {
23
+ throw new HttpError(400, `${field} must be a UUID.`, "invalid_request_error", field);
24
+ }
25
+ return canonical;
26
+ }
@@ -1,2 +1,2 @@
1
1
  export { scopedHarnessAgentId, scopedHarnessConversationId, scopedHarnessSessionId, type HarnessConversationIdentity, type HarnessConversationScope, } from "./conversation.js";
2
- export { chatCompletionsConversationIdentity, claudeCodeConversationIdentity, codexConversationIdentity, codexRequestPurpose, codexRequestContext, museCodeConversationIdentity, openCodeRequestContext, piRequestContext, } from "./extract.js";
2
+ export { chatCompletionsConversationIdentity } from "./extract.js";
@@ -1,2 +1,2 @@
1
1
  export { scopedHarnessAgentId, scopedHarnessConversationId, scopedHarnessSessionId, } from "./conversation.js";
2
- export { chatCompletionsConversationIdentity, claudeCodeConversationIdentity, codexConversationIdentity, codexRequestPurpose, codexRequestContext, museCodeConversationIdentity, openCodeRequestContext, piRequestContext, } from "./extract.js";
2
+ export { chatCompletionsConversationIdentity } from "./extract.js";
@@ -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,
@@ -54,7 +56,8 @@ export async function handleRoutedCompletion(args) {
54
56
  for (const [name, value] of Object.entries(args.responseHeaders?.(prepared.credentials) ?? {})) {
55
57
  response.headers.set(name, value);
56
58
  }
57
- return responseWithRequestId(response, requestId);
59
+ // Its X-Request-Id is the request the client is told it made.
60
+ return response;
58
61
  }
59
62
  catch (error) {
60
63
  const terminal = prepared.reporter.freezeFailure(error);
@@ -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,5 +1,5 @@
1
1
  import { isReasoningEffort, isRecord, providerForModel, } from "@mupt-ai/dari-router/policy-engine";
2
- import { CLIENT_HARNESSES } from "../ingress/client_harness.js";
2
+ import { CLIENT_HARNESSES } from "../harnesses/index.js";
3
3
  import { checkSources, DEFAULT_RESET_MIN_HOURS } from "../models/sources.js";
4
4
  import { modelKeyProviders, otherModelProviders, providerModel } from "../models/canonical.js";
5
5
  const REDIRECT_HOST_PATTERN = /^(\*\.)?[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/;
@@ -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 {};