@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
@@ -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,
@@ -1,5 +1,5 @@
1
1
  import { errorResponse, HttpError } from "../http/errors.js";
2
- import { CLIENT_HARNESSES } from "../ingress/client_harness.js";
2
+ import { CLIENT_HARNESSES } from "../harnesses/index.js";
3
3
  import { DEFAULT_ROUTER_ALIAS } from "../platform/routing_contract.js";
4
4
  import { DEFAULT_GATEWAY_CONFIG, parseRouterModels, } from "./config.js";
5
5
  // A router's own list is saved under no agent.
@@ -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,
@@ -37,7 +37,6 @@ export type SubscriptionCredential = {
37
37
  accountEmail: string | null;
38
38
  accountId: string | null;
39
39
  owner: string | null;
40
- private: boolean;
41
40
  accessToken: string;
42
41
  refreshToken: string;
43
42
  expiresAt: Date;
@@ -63,7 +62,6 @@ export type PendingOAuthSession = {
63
62
  flow: Record<string, string>;
64
63
  credentialName: string | null;
65
64
  owner: string | null;
66
- private: boolean;
67
65
  movingFrom: string | null;
68
66
  expiresAt: Date;
69
67
  };
@@ -86,7 +84,7 @@ export type AccountRef = {
86
84
  * other computers. `name` is the plan's handle.
87
85
  */
88
86
  export type ConnectedAccount = AccountRef & {
89
- place: "dari" | "this_computer" | "private";
87
+ place: "dari" | "this_computer";
90
88
  name: string | null;
91
89
  connectedAt?: Date;
92
90
  };
@@ -149,15 +147,18 @@ export declare class SubscriptionStore {
149
147
  * null is the gateway owner), or `elsewhere` (the owner's plans on hosted
150
148
  * Dari and other computers) holds it.
151
149
  */
152
- connect(tokens: OAuthTokens, reconnectName: string | null, now?: Date, owner?: string | null, isPrivate?: boolean, elsewhere?: ConnectedAccount[]): SubscriptionCredential | null;
150
+ connect(tokens: OAuthTokens, reconnectName: string | null, now?: Date, owner?: string | null, elsewhere?: ConnectedAccount[]): SubscriptionCredential | null;
153
151
  private refuseSecondCopy;
154
152
  /** Persist refreshed tokens. Keeps the stored account id when the refresh carries none. */
155
153
  updateTokens(id: string, tokens: OAuthTokens, now?: Date): void;
156
154
  touch(id: string, now?: Date): void;
157
155
  /** An empty label clears it. Null when the subscription is not connected. */
158
156
  rename(name: string, label: string | null, now?: Date): SubscriptionCredential | null;
159
- /** Make the gateway owner's subscription private, or not. Null when it is not connected. */
160
- setPrivate(name: string, isPrivate: boolean, now?: Date): SubscriptionCredential | null;
157
+ /**
158
+ * Clear the marks of plans connected as private, before private mode
159
+ * replaced them; true when any was marked.
160
+ */
161
+ clearLegacyPrivate(): boolean;
161
162
  /** Remove a subscription. Returns what was removed, or null when it was not connected. */
162
163
  disconnect(name: string, owner?: string | null): SubscriptionCredential | null;
163
164
  /**
@@ -40,7 +40,6 @@ const PROVIDER_LABELS = {
40
40
  const PLACE_NAMES = {
41
41
  dari: "on Dari",
42
42
  this_computer: "on This Computer",
43
- private: "Private on This Computer",
44
43
  };
45
44
  function connectedAccountMessage(account) {
46
45
  const asName = account.name === null ? "" : ` as ${account.name}`;
@@ -63,7 +62,7 @@ const ADDED_COLUMNS = {
63
62
  usage_windows: "TEXT",
64
63
  model_holds: "TEXT",
65
64
  owner: "TEXT",
66
- private: "INTEGER",
65
+ private: "INTEGER", // read once, by clearLegacyPrivate
67
66
  auto_redeem_resets: "INTEGER", // no longer read; resets follow each model's sources
68
67
  };
69
68
  export class SubscriptionStore {
@@ -115,12 +114,11 @@ export class SubscriptionStore {
115
114
  flow_json TEXT NOT NULL,
116
115
  credential_name TEXT,
117
116
  owner TEXT,
118
- private INTEGER,
119
117
  moving_from TEXT,
120
118
  expires_at INTEGER NOT NULL
121
119
  )`);
122
120
  const sessionColumns = new Set(db.query("PRAGMA table_info(subscription_oauth_sessions)").all().map((column) => column.name));
123
- for (const [column, type] of [["owner", "TEXT"], ["private", "INTEGER"], ["moving_from", "TEXT"]]) {
121
+ for (const [column, type] of [["owner", "TEXT"], ["moving_from", "TEXT"]]) {
124
122
  if (!sessionColumns.has(column))
125
123
  db.run(`ALTER TABLE subscription_oauth_sessions ADD COLUMN ${column} ${type}`);
126
124
  }
@@ -281,7 +279,7 @@ export class SubscriptionStore {
281
279
  * null is the gateway owner), or `elsewhere` (the owner's plans on hosted
282
280
  * Dari and other computers) holds it.
283
281
  */
284
- connect(tokens, reconnectName, now = new Date(), owner = null, isPrivate = false, elsewhere = []) {
282
+ connect(tokens, reconnectName, now = new Date(), owner = null, elsewhere = []) {
285
283
  const connected = this.db.transaction(() => {
286
284
  const existing = reconnectName !== null ? this.getByName(reconnectName, owner ?? null) : null;
287
285
  if (reconnectName !== null && existing?.provider !== tokens.provider)
@@ -297,7 +295,7 @@ export class SubscriptionStore {
297
295
  this.db.run(`UPDATE subscription_credentials SET access_token = ?, refresh_token = ?, expires_at = ?,
298
296
  account_id = ?, account_email = ?, unavailable_until = ?, unavailable_reason = ?,
299
297
  usage_utilization = ?, usage_resets_at = ?, usage_observed_at = ?, usage_windows = ?, model_holds = ?,
300
- private = ?, updated_at = ?
298
+ updated_at = ?
301
299
  WHERE id = ?`, [
302
300
  this.seal(tokens.accessToken, tokenPlace(existing.id, "access_token")),
303
301
  this.seal(tokens.refreshToken, tokenPlace(existing.id, "refresh_token")),
@@ -311,7 +309,6 @@ export class SubscriptionStore {
311
309
  usage?.observedAt.getTime() ?? null,
312
310
  usage === null ? null : windowsJson(usage),
313
311
  sameAccount ? modelHoldsJson(existing.modelHolds) : null,
314
- isPrivate ? 1 : 0,
315
312
  now.getTime(),
316
313
  existing.id,
317
314
  ]);
@@ -325,16 +322,15 @@ export class SubscriptionStore {
325
322
  const position = this.db
326
323
  .query("SELECT COALESCE(MAX(position), 0) + 1 AS next FROM subscription_credentials")
327
324
  .get().next;
328
- this.db.run(`INSERT INTO subscription_credentials (id, provider, name, account_email, account_id, owner, private,
325
+ this.db.run(`INSERT INTO subscription_credentials (id, provider, name, account_email, account_id, owner,
329
326
  access_token, refresh_token, expires_at, position, created_at, updated_at)
330
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, [
327
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, [
331
328
  id,
332
329
  tokens.provider,
333
330
  this.freeName(BASE_NAMES[tokens.provider]),
334
331
  tokens.accountEmail,
335
332
  tokens.accountId,
336
333
  owner,
337
- isPrivate ? 1 : 0,
338
334
  this.seal(tokens.accessToken, tokenPlace(id, "access_token")),
339
335
  this.seal(tokens.refreshToken, tokenPlace(id, "refresh_token")),
340
336
  tokens.expiresAt.getTime(),
@@ -355,7 +351,7 @@ export class SubscriptionStore {
355
351
  provider: local.provider,
356
352
  accountId: local.accountId,
357
353
  accountEmail: local.accountEmail,
358
- place: local.private ? "private" : "this_computer",
354
+ place: "this_computer",
359
355
  name: local.name,
360
356
  }));
361
357
  }
@@ -394,17 +390,12 @@ export class SubscriptionStore {
394
390
  ]);
395
391
  return this.get(credential.id);
396
392
  }
397
- /** Make the gateway owner's subscription private, or not. Null when it is not connected. */
398
- setPrivate(name, isPrivate, now = new Date()) {
399
- const credential = this.getByName(name);
400
- if (credential === null)
401
- return null;
402
- this.db.run("UPDATE subscription_credentials SET private = ?, updated_at = ? WHERE id = ?", [
403
- isPrivate ? 1 : 0,
404
- now.getTime(),
405
- credential.id,
406
- ]);
407
- return this.get(credential.id);
393
+ /**
394
+ * Clear the marks of plans connected as private, before private mode
395
+ * replaced them; true when any was marked.
396
+ */
397
+ clearLegacyPrivate() {
398
+ return this.db.run("UPDATE subscription_credentials SET private = NULL WHERE private = 1").changes > 0;
408
399
  }
409
400
  /** Remove a subscription. Returns what was removed, or null when it was not connected. */
410
401
  disconnect(name, owner = null) {
@@ -462,14 +453,13 @@ export class SubscriptionStore {
462
453
  createSession(session, now = new Date()) {
463
454
  const token = randomBytes(32).toString("base64url");
464
455
  this.db.run("DELETE FROM subscription_oauth_sessions WHERE expires_at <= ?", [now.getTime()]);
465
- this.db.run(`INSERT INTO subscription_oauth_sessions (token, provider, flow_json, credential_name, owner, private, moving_from, expires_at)
466
- VALUES (?, ?, ?, ?, ?, ?, ?, ?)`, [
456
+ this.db.run(`INSERT INTO subscription_oauth_sessions (token, provider, flow_json, credential_name, owner, moving_from, expires_at)
457
+ VALUES (?, ?, ?, ?, ?, ?, ?)`, [
467
458
  token,
468
459
  session.provider,
469
460
  this.seal(JSON.stringify(session.flow), flowPlace(token)),
470
461
  session.credentialName,
471
462
  session.owner,
472
- session.private ? 1 : 0,
473
463
  session.movingFrom,
474
464
  session.expiresAt.getTime(),
475
465
  ]);
@@ -488,7 +478,6 @@ export class SubscriptionStore {
488
478
  flow: JSON.parse(this.open(row.flow_json, flowPlace(row.token))),
489
479
  credentialName: row.credential_name,
490
480
  owner: row.owner,
491
- private: row.private === 1,
492
481
  movingFrom: row.moving_from,
493
482
  expiresAt: new Date(row.expires_at),
494
483
  };
@@ -589,7 +578,6 @@ function credentialFromRow(row) {
589
578
  accountEmail: row.account_email,
590
579
  accountId: row.account_id,
591
580
  owner: row.owner,
592
- private: row.private === 1,
593
581
  accessToken: row.access_token,
594
582
  refreshToken: row.refresh_token,
595
583
  expiresAt: new Date(row.expires_at),
@@ -457,6 +457,7 @@ export class RequestReporter {
457
457
  gatewayPlatform().recordRequest({
458
458
  ...(link === undefined ? {} : { link }),
459
459
  ...(subscriptionCredentialId === undefined ? {} : { subscriptionCredentialId }),
460
+ private: a.credentials.private === true,
460
461
  router: requestRecordRouter(a.credentials),
461
462
  candidates: a.candidates.map(({ model, reasoningEffort }) => ({ model, reasoningEffort })),
462
463
  ...(a.sessionPinKey === undefined ? {} : { sessionPinKey: a.sessionPinKey }),
package/dist/types.d.ts CHANGED
@@ -48,7 +48,7 @@ export type PublicEvalCatalogCard = Omit<RouterEval, "scores"> & {
48
48
  export type ServedDecision = RoutingDecision & {
49
49
  sessionPinned?: boolean;
50
50
  };
51
- export type ClientHarness = "claude_code" | "codex" | "muse_code" | "opencode" | "pi" | "openclaw" | "hermes";
51
+ export type { ClientHarness } from "./harnesses/index.js";
52
52
  export type ResolvedRouterModelConfig = {
53
53
  provider: string;
54
54
  native_model_id: string;
@@ -108,6 +108,7 @@ export type ResolvedRouter = {
108
108
  }> | null;
109
109
  link_tags?: Record<string, string> | null;
110
110
  zdr?: boolean;
111
+ private?: boolean;
111
112
  allow_long_context?: boolean;
112
113
  speculative_routing?: boolean;
113
114
  session_pinning?: boolean;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mupt-ai/dari-gateway",
3
- "version": "1.0.368",
3
+ "version": "1.0.370",
4
4
  "description": "Self-hostable LLM gateway for coding agents and APIs: one endpoint for Anthropic Messages, OpenAI Chat Completions, and OpenAI Responses, with subscription pooling, failover, and prompt-cache-aware routing.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -52,7 +52,7 @@
52
52
  },
53
53
  "dependencies": {
54
54
  "@aws-sdk/client-sts": "3.1063.0",
55
- "@mupt-ai/dari-router": "1.0.368",
55
+ "@mupt-ai/dari-router": "1.0.370",
56
56
  "@mupt-ai/pi-ai": "1.5.2-mupt.3"
57
57
  },
58
58
  "devDependencies": {
@@ -1,5 +1,24 @@
1
- import { HttpError } from "../../http/errors.js";
2
- import type { AgentRequestContext, AgentRequestClass } from "../../interaction/types.js";
1
+ import { HttpError } from "../http/errors.js";
2
+ import type { AgentRequestContext, AgentRequestClass } from "../interaction/types.js";
3
+ import { boundedIdentity, uuidIdentity } from "../runtime/harness_identity/ids.js";
4
+ import type { HarnessConversationIdentity } from "../runtime/harness_identity/conversation.js";
5
+ import type { Harness } from "./index.js";
6
+
7
+ export const claudeCode = {
8
+ id: "claude_code",
9
+ headers: [
10
+ "user-agent",
11
+ "x-app",
12
+ "anthropic-beta",
13
+ "x-claude-code-session-id",
14
+ "x-claude-code-request-class",
15
+ "x-claude-code-agent-id",
16
+ "x-claude-code-parent-agent-id",
17
+ "x-claude-code-agent-type",
18
+ ],
19
+ // A Claude Code plan serves only Claude Code.
20
+ ownPlanOnly: true,
21
+ } as const satisfies Harness;
3
22
 
4
23
  const REQUEST_CLASSES = new Set<AgentRequestClass>([
5
24
  "main", "subagent", "workflow", "auxiliary", "compaction", "side_reply",
@@ -51,3 +70,38 @@ function identifier(headers: Headers, name: string): string | undefined {
51
70
  }
52
71
  return value;
53
72
  }
73
+
74
+ export function claudeCodeConversationIdentity(
75
+ headers: Headers,
76
+ metadataSessionId?: string,
77
+ ): HarnessConversationIdentity | undefined {
78
+ const candidates = [
79
+ uuidIdentity(
80
+ headers.get("x-claude-code-session-id"),
81
+ "x-claude-code-session-id",
82
+ ),
83
+ uuidIdentity(
84
+ metadataSessionId,
85
+ "metadata.user_id.session_id",
86
+ ),
87
+ ].filter((value): value is string => value !== undefined);
88
+ if (candidates.length === 0) return undefined;
89
+ // Claude Code can carry a stale metadata session after a resume or fork.
90
+ // The header names the live session, so it wins over the metadata.
91
+ const [sessionId] = candidates;
92
+ // Claude Code reuses the parent session UUID for every subagent, but gives
93
+ // each subagent a stable agent header. Keep the parent thread on the bare
94
+ // session identity and scope each subagent to its own composite identity.
95
+ // Treat this as an opaque Claude identifier. Besides ordinary subagent IDs,
96
+ // Claude may send labeled agents or Agent Teams identities such as
97
+ // `reviewer@backend`; Dari only needs a stable, bounded value to hash.
98
+ const agentId = boundedIdentity(
99
+ headers.get("x-claude-code-agent-id"),
100
+ "x-claude-code-agent-id",
101
+ );
102
+ return {
103
+ kind: "claude_code_session",
104
+ value: sessionId,
105
+ ...(agentId === undefined ? {} : { qualifiers: [agentId] }),
106
+ };
107
+ }