@mupt-ai/dari-gateway 1.0.360 → 1.0.362

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 (41) hide show
  1. package/dist/ingress/client_harness.d.ts +6 -0
  2. package/dist/ingress/client_harness.js +17 -1
  3. package/dist/ingress/models.js +0 -3
  4. package/dist/models/runtime_overrides.js +5 -0
  5. package/dist/platform/platform.d.ts +2 -1
  6. package/dist/platform/routing_contract.d.ts +1 -1
  7. package/dist/platform/routing_contract.js +3 -3
  8. package/dist/providers/pi.js +10 -2
  9. package/dist/runtime/prepare_routed_completion.d.ts +1 -0
  10. package/dist/runtime/prepare_routed_completion.js +1 -0
  11. package/dist/runtime/routed_completion.js +2 -0
  12. package/dist/self_host/connected.d.ts +29 -16
  13. package/dist/self_host/connected.js +64 -68
  14. package/dist/self_host/hosted_sync.d.ts +0 -2
  15. package/dist/self_host/hosted_sync.js +2 -10
  16. package/dist/self_host/main.d.ts +2 -2
  17. package/dist/self_host/main.js +10 -9
  18. package/dist/self_host/resolve.d.ts +7 -4
  19. package/dist/self_host/resolve.js +72 -18
  20. package/dist/self_host/subscriptions/http.js +13 -3
  21. package/dist/self_host/subscriptions/store.d.ts +3 -15
  22. package/dist/self_host/subscriptions/store.js +11 -27
  23. package/dist/telemetry/report.js +4 -0
  24. package/dist/types.d.ts +1 -0
  25. package/package.json +2 -2
  26. package/src/ingress/client_harness.ts +18 -1
  27. package/src/ingress/models.ts +0 -3
  28. package/src/models/runtime_overrides.ts +4 -0
  29. package/src/platform/platform.ts +5 -4
  30. package/src/platform/routing_contract.ts +3 -3
  31. package/src/providers/pi.ts +10 -2
  32. package/src/runtime/prepare_routed_completion.ts +2 -0
  33. package/src/runtime/routed_completion.ts +2 -0
  34. package/src/self_host/connected.ts +102 -82
  35. package/src/self_host/hosted_sync.ts +2 -13
  36. package/src/self_host/main.ts +10 -9
  37. package/src/self_host/resolve.ts +75 -19
  38. package/src/self_host/subscriptions/http.ts +12 -3
  39. package/src/self_host/subscriptions/store.ts +11 -25
  40. package/src/telemetry/report.ts +3 -0
  41. package/src/types.ts +2 -0
@@ -1,7 +1,9 @@
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 } from "../platform/routing_contract.js";
4
+ import { DEFAULT_ROUTER_ALIAS, HOSTED_DARI_PROVIDER } from "../platform/routing_contract.js";
5
+ import { explicitModelSlug } from "../protocol/input/router_model.js";
6
+ import { CLIENT_HARNESS_HEADER } from "../ingress/client_harness.js";
5
7
  import { codexModelConfig, modelSubscriptions, subscriptionClient, subscriptionModelProvider, } from "../models/subscriptions.js";
6
8
  import { CANONICAL_MODELS, otherModelProviders, providerModel } from "../models/canonical.js";
7
9
  import { gatewayFor } from "../models/gateways.js";
@@ -21,10 +23,11 @@ export const SELF_HOSTED_USER_ID = "self-hosted";
21
23
  /**
22
24
  * Resolve a configured router for one request. Each model is served by the
23
25
  * connected personal subscriptions that serve it, when the router allows them,
24
- * in plan order (see models/subscriptions.ts), then by its provider's API key:
25
- * the first available serves and the rest fail over within the request.
26
- * Models nothing can serve are left out. A coding agent with its own model
27
- * list on the router is served that list.
26
+ * in plan order (see models/subscriptions.ts), then by its provider's API key
27
+ * (on a connected gateway, by hosted Dari): the first available serves and
28
+ * the rest fail over within the request. Models nothing can serve are left
29
+ * out. A coding agent with its own model list on the router is served that
30
+ * list.
28
31
  *
29
32
  * A Dari Link token is served apart from any router, on its grant's plans and
30
33
  * API keys alone: `dari/routing` chooses among every catalog model they
@@ -161,16 +164,30 @@ export async function resolveSelfHostedRouter(deps, request) {
161
164
  },
162
165
  });
163
166
  }
164
- const candidates = await candidatesFor(sources, plans, {
165
- key: async () => {
166
- const key = await apiKey(base);
167
- if (key === undefined)
168
- return null;
169
- return { provider: base, key };
170
- },
171
- // A self-hosted gateway has no managed keys.
172
- managed: async () => null,
173
- });
167
+ let keyCandidate = async () => {
168
+ const key = await apiKey(base);
169
+ if (key === undefined)
170
+ return null;
171
+ return { provider: base, key };
172
+ };
173
+ // A self-hosted gateway has no managed keys.
174
+ let managedCandidate = async () => null;
175
+ // On a gateway connected to hosted Dari, Dari serves what no plan on this
176
+ // computer does: its own plans after this computer's, the router's key,
177
+ // and managed credits.
178
+ const hosted = deps.hosted;
179
+ if (hosted !== undefined) {
180
+ const dari = async () => hostedCandidate(hosted, request, model.id);
181
+ plans.push({ servesClient: true, candidate: dari });
182
+ keyCandidate = dari;
183
+ managedCandidate = dari;
184
+ }
185
+ const candidates = await candidatesFor(sources, plans, { key: keyCandidate, managed: managedCandidate });
186
+ // Dari walks the model's sources itself from there, so its one candidate
187
+ // ends the list.
188
+ const dariAt = candidates.findIndex((candidate) => candidate.provider === HOSTED_DARI_PROVIDER);
189
+ if (dariAt !== -1)
190
+ candidates.splice(dariAt + 1);
174
191
  if (candidates.length === 0) {
175
192
  for (const kind of heldKinds)
176
193
  exhausted.add(kind);
@@ -314,10 +331,13 @@ export function gatewayKeyIndex(keys, presented) {
314
331
  }
315
332
  return null;
316
333
  }
317
- // How a candidate runs a model: a ChatGPT plan through the Codex backend, a
318
- // provider that serves another maker's model as its own model, a configured
319
- // endpoint, or (undefined) the model's own provider as the catalog has it.
334
+ // How a candidate runs a model: hosted Dari's endpoint, a ChatGPT plan
335
+ // through the Codex backend, a provider that serves another maker's model as
336
+ // its own model, a configured endpoint, or (undefined) the model's own
337
+ // provider as the catalog has it.
320
338
  function candidateConfig(deps, modelId, candidate) {
339
+ if ("config" in candidate)
340
+ return candidate.config;
321
341
  const { provider } = candidate;
322
342
  const price = priceFor(modelId, provider);
323
343
  if ("plan" in candidate && candidate.plan.provider === "openai_codex") {
@@ -350,6 +370,40 @@ function candidateConfig(deps, modelId, candidate) {
350
370
  cost: price ?? { input: 0, output: 0 },
351
371
  };
352
372
  }
373
+ /**
374
+ * Hosted Dari as the provider of a model: the request's router on hosted Dari,
375
+ * called for `dari/model/<id>` with the user's Dari key, in Anthropic's API
376
+ * for Anthropic's models and OpenAI's Responses API for the rest, with the
377
+ * client's own identifying headers and the coding agent it named, so hosted
378
+ * sees the same client. Hosted Dari bills and logs what it serves.
379
+ */
380
+ function hostedCandidate(hosted, request, modelId) {
381
+ let routerUrl = hosted.url;
382
+ if (request.routerId !== DEFAULT_ROUTER_ALIAS)
383
+ routerUrl = `${hosted.url}/${encodeURIComponent(request.routerId)}`;
384
+ let api = "openai-responses";
385
+ let baseUrl = `${routerUrl}/v1`;
386
+ // Anthropic's client adds /v1 itself.
387
+ if (providerForModel(modelId) === "anthropic") {
388
+ api = "anthropic-messages";
389
+ baseUrl = routerUrl;
390
+ }
391
+ const headers = { ...request.clientHeaders };
392
+ if (request.clientHarness !== undefined)
393
+ headers[CLIENT_HARNESS_HEADER] = request.clientHarness;
394
+ return {
395
+ provider: HOSTED_DARI_PROVIDER,
396
+ key: hosted.apiKey,
397
+ config: {
398
+ provider: HOSTED_DARI_PROVIDER,
399
+ native_model_id: explicitModelSlug(modelId),
400
+ api,
401
+ base_url: baseUrl,
402
+ headers,
403
+ cost: registeredModelPrice(modelId) ?? { input: 0, output: 0 },
404
+ },
405
+ };
406
+ }
353
407
  // A fallback names its endpoint even on the model's own provider, as the
354
408
  // catalog has it; undefined when the catalog has none.
355
409
  function registryConfig(modelId, provider) {
@@ -117,7 +117,7 @@ export async function handleSubscriptionRequest(request, deps) {
117
117
  function listBody(store, now) {
118
118
  const active = new Set(SUBSCRIPTION_PROVIDERS.map((provider) => store.activeCredential(provider, now)?.id));
119
119
  return {
120
- credentials: store.list(undefined, true).map((credential) => credentialBody(credential, active.has(credential.id), now)),
120
+ credentials: store.list().map((credential) => credentialBody(credential, active.has(credential.id), now)),
121
121
  // Plan gating is hosted-only; a self-hosted gateway always allows routing.
122
122
  autorouting_allowed: true,
123
123
  };
@@ -139,7 +139,7 @@ async function startSession(deps, body, now) {
139
139
  const isPrivate = body.private ?? reconnecting?.private ?? false;
140
140
  if (typeof isPrivate !== "boolean")
141
141
  throw new HttpError(400, "private must be true or false.");
142
- // `dari accounts subscription move` names the hosted plan it moves here.
142
+ // `dari accounts subscription connect` names the hosted plan it moves here.
143
143
  const movingFrom = body.moving_from ?? null;
144
144
  if (movingFrom !== null && (typeof movingFrom !== "string" || !movingFrom.trim())) {
145
145
  throw new HttpError(400, "moving_from must be a non-empty string.");
@@ -265,13 +265,23 @@ function usageBody(credential, now) {
265
265
  })),
266
266
  };
267
267
  }
268
+ function safeMetadata(credential) {
269
+ const metadata = {};
270
+ if (credential.accountEmail !== null)
271
+ metadata.account_email = credential.accountEmail;
272
+ if (credential.accountId !== null)
273
+ metadata.account_id = credential.accountId;
274
+ return metadata;
275
+ }
268
276
  function credentialBody(credential, active, now) {
269
277
  const held = isHeld(credential, now);
270
278
  return {
271
279
  id: credential.id,
272
280
  name: credential.name,
273
281
  label: credential.label,
274
- safe_metadata: credential.accountEmail === null ? {} : { account_email: credential.accountEmail },
282
+ // The account, as hosted Dari shows a plan's: its email and, where the
283
+ // provider names one, its account (a ChatGPT workspace).
284
+ safe_metadata: safeMetadata(credential),
275
285
  // Hosted organizations also hold organization-scoped secrets; every
276
286
  // subscription here belongs to the gateway's one user.
277
287
  credential_scope: "user",
@@ -93,33 +93,21 @@ export declare function sameConnectedAccount(a: AccountRef, b: AccountRef): bool
93
93
  export declare class SubscriptionStore {
94
94
  private readonly db;
95
95
  private readonly box;
96
- private readonly options;
97
96
  /**
98
97
  * Told of each change hosted Dari's copy of the plans would show: `plans`
99
98
  * for a plan connected, removed, renamed, moved, held, or released, and
100
99
  * `usage` for reported usage or use.
101
100
  */
102
101
  onChange: ((change: "plans" | "usage") => void) | undefined;
103
- /**
104
- * `privatePlansServe: false` (a gateway connected to hosted Dari) leaves
105
- * private plans out of routing and `list`; `list(provider, true)` still
106
- * shows them.
107
- */
108
- constructor(db: Database, box?: SecretBox | null, options?: {
109
- privatePlansServe?: boolean;
110
- });
102
+ constructor(db: Database, box?: SecretBox | null);
111
103
  /** Whether stored tokens are encrypted. */
112
104
  get encrypted(): boolean;
113
105
  private encryptStored;
114
106
  private seal;
115
107
  private open;
116
108
  private credential;
117
- /**
118
- * The gateway owner's subscriptions that serve, grouped by provider, in
119
- * connection order; with `includePrivate`, private ones too even where they
120
- * do not serve.
121
- */
122
- list(provider?: SubscriptionProvider, includePrivate?: boolean): SubscriptionCredential[];
109
+ /** The gateway owner's subscriptions, grouped by provider, in connection order. */
110
+ list(provider?: SubscriptionProvider): SubscriptionCredential[];
123
111
  /** The subscriptions a Dari Link user connected. */
124
112
  owned(owner: string): SubscriptionCredential[];
125
113
  /** The subscriptions with these ids, whoever connected them. */
@@ -29,18 +29,14 @@ const PROVIDER_LABELS = {
29
29
  xai_grok: "Grok",
30
30
  vercel_token_pass: "Vercel Token Pass",
31
31
  };
32
+ const PLACE_NAMES = {
33
+ dari: "on Dari",
34
+ this_computer: "on This Computer",
35
+ private: "Private on This Computer",
36
+ };
32
37
  function connectedAccountMessage(account) {
33
- const label = PROVIDER_LABELS[account.provider];
34
- const handle = account.name ?? "NAME";
35
- const asName = account.name === null ? "" : ` as ${handle}`;
36
- switch (account.place) {
37
- case "dari":
38
- return `This ${label} account is already connected on Dari${asName}. Move it with \`dari accounts subscription move ${handle} --on computer\`, or disconnect it first.`;
39
- case "this_computer":
40
- return `This ${label} account is already connected on This Computer${asName}. Move it with \`dari accounts subscription move ${handle} --on dari\`, or disconnect it first.`;
41
- case "private":
42
- return `This ${label} account is already connected Private on This Computer${asName}. Move it with \`dari accounts subscription move ${handle} --on dari\` or \`--on computer\`, or disconnect it first.`;
43
- }
38
+ const asName = account.name === null ? "" : ` as ${account.name}`;
39
+ return `This ${PROVIDER_LABELS[account.provider]} account is already connected ${PLACE_NAMES[account.place]}${asName}. Run \`dari accounts subscription connect\` again and choose Move, or disconnect it first.`;
44
40
  }
45
41
  const BASE_NAMES = {
46
42
  anthropic_claude_code: "ANTHROPIC_CLAUDE_CODE_OAUTH_TOKEN",
@@ -65,22 +61,15 @@ const ADDED_COLUMNS = {
65
61
  export class SubscriptionStore {
66
62
  db;
67
63
  box;
68
- options;
69
64
  /**
70
65
  * Told of each change hosted Dari's copy of the plans would show: `plans`
71
66
  * for a plan connected, removed, renamed, moved, held, or released, and
72
67
  * `usage` for reported usage or use.
73
68
  */
74
69
  onChange;
75
- /**
76
- * `privatePlansServe: false` (a gateway connected to hosted Dari) leaves
77
- * private plans out of routing and `list`; `list(provider, true)` still
78
- * shows them.
79
- */
80
- constructor(db, box = null, options = {}) {
70
+ constructor(db, box = null) {
81
71
  this.db = db;
82
72
  this.box = box;
83
- this.options = options;
84
73
  db.run(`CREATE TABLE IF NOT EXISTS subscription_credentials (
85
74
  id TEXT PRIMARY KEY,
86
75
  provider TEXT NOT NULL,
@@ -184,14 +173,9 @@ export class SubscriptionStore {
184
173
  refresh_token: this.open(row.refresh_token, tokenPlace(row.id, "refresh_token")),
185
174
  });
186
175
  }
187
- /**
188
- * The gateway owner's subscriptions that serve, grouped by provider, in
189
- * connection order; with `includePrivate`, private ones too even where they
190
- * do not serve.
191
- */
192
- list(provider, includePrivate = false) {
193
- const privateShown = includePrivate || this.options.privatePlansServe !== false;
194
- return this.every(provider).filter((credential) => credential.owner === null && (privateShown || !credential.private));
176
+ /** The gateway owner's subscriptions, grouped by provider, in connection order. */
177
+ list(provider) {
178
+ return this.every(provider).filter((credential) => credential.owner === null);
195
179
  }
196
180
  /** The subscriptions a Dari Link user connected. */
197
181
  owned(owner) {
@@ -444,8 +444,12 @@ export class RequestReporter {
444
444
  },
445
445
  }),
446
446
  };
447
+ let subscriptionCredentialId;
448
+ if (keySource === "subscription")
449
+ subscriptionCredentialId = outcome.providerExecution?.subscriptionCredentialId;
447
450
  gatewayPlatform().recordRequest({
448
451
  ...(link === undefined ? {} : { link }),
452
+ ...(subscriptionCredentialId === undefined ? {} : { subscriptionCredentialId }),
449
453
  router: requestRecordRouter(a.credentials),
450
454
  candidates: a.candidates.map(({ model, reasoningEffort }) => ({ model, reasoningEffort })),
451
455
  ...(a.sessionPinKey === undefined ? {} : { sessionPinKey: a.sessionPinKey }),
package/dist/types.d.ts CHANGED
@@ -53,6 +53,7 @@ export type ResolvedRouterModelConfig = {
53
53
  native_model_id: string;
54
54
  api: string;
55
55
  base_url?: string | null;
56
+ headers?: Record<string, string>;
56
57
  context_window?: number | null;
57
58
  standard_context_limit?: number | null;
58
59
  allow_long_context?: boolean;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mupt-ai/dari-gateway",
3
- "version": "1.0.360",
3
+ "version": "1.0.362",
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.360",
55
+ "@mupt-ai/dari-router": "1.0.362",
56
56
  "@mupt-ai/pi-ai": "1.5.2-mupt.3"
57
57
  },
58
58
  "devDependencies": {
@@ -1,6 +1,6 @@
1
1
  import type { ClientHarness } from "../types.js";
2
2
 
3
- const CLIENT_HARNESS_HEADER = "x-dari-client-harness";
3
+ export const CLIENT_HARNESS_HEADER = "x-dari-client-harness";
4
4
 
5
5
  export const CLIENT_HARNESSES: readonly string[] = [
6
6
  "claude_code",
@@ -12,6 +12,23 @@ export const CLIENT_HARNESSES: readonly string[] = [
12
12
  "hermes",
13
13
  ] satisfies ClientHarness[];
14
14
 
15
+ // The headers a coding agent names itself with: Claude Code's user agent,
16
+ // app, session, and betas, and Muse Code's client id.
17
+ const CLIENT_HEADERS = ["user-agent", "x-app", "x-claude-code-session-id", "anthropic-beta", "x-client-id"];
18
+
19
+ /**
20
+ * The headers of `CLIENT_HEADERS` the request carries, as the client sent
21
+ * them, so hosted Dari serving it for a connected gateway sees the same client.
22
+ */
23
+ export function clientHeaders(headers: Headers): Record<string, string> {
24
+ const found: Record<string, string> = {};
25
+ for (const name of CLIENT_HEADERS) {
26
+ const value = headers.get(name);
27
+ if (value !== null) found[name] = value;
28
+ }
29
+ return found;
30
+ }
31
+
15
32
  /**
16
33
  * The coding agent `x-dari-client-harness` names, as the Dari CLI does for a
17
34
  * model list. The header is a claim, not proof.
@@ -19,7 +19,6 @@ import { anthropicModelsResponse } from "./anthropic_models.js";
19
19
  import { namedClientHarness } from "./client_harness.js";
20
20
  import { codexModelsEtag, codexModelsResponse } from "./codex_models.js";
21
21
  import { CANONICAL_ROUTER_MODEL, explicitModelSlug, LINK_CHILD_TOKEN_PREFIX } from "../protocol/input/router_model.js";
22
- import { GATEWAY_ID_HEADER } from "../platform/routing_contract.js";
23
22
 
24
23
  export async function handleModels(request: Request, routerId: string): Promise<Response> {
25
24
  // Anthropic SDK clients always send anthropic-version, and API-key probes
@@ -40,14 +39,12 @@ export async function handleModels(request: Request, routerId: string): Promise<
40
39
  // names its own version in the query, as only Codex does.
41
40
  const codexDirect = !anthropicClient && query.has("client_version");
42
41
  const clientHarness = namedClientHarness(request.headers) ?? (codexDirect ? "codex" : undefined);
43
- const gatewayId = request.headers.get(GATEWAY_ID_HEADER)?.trim();
44
42
  let router;
45
43
  try {
46
44
  router = await resolveRouter({
47
45
  routerId,
48
46
  apiKey,
49
47
  ...(clientHarness ? { clientHarness } : {}),
50
- ...(gatewayId ? { gatewayId } : {}),
51
48
  });
52
49
  } catch (error) {
53
50
  // A Dari Link grant that can serve this client nothing now lists no
@@ -1,5 +1,6 @@
1
1
  import { canonicalModelId, isRecord } from "@mupt-ai/dari-router/policy-engine";
2
2
 
3
+ import { HOSTED_DARI_PROVIDER } from "../platform/routing_contract.js";
3
4
  import { gatewayFor } from "./gateways.js";
4
5
 
5
6
  const MODEL_CONTEXT_OVERRIDES: Record<string, number> = {
@@ -231,6 +232,9 @@ export function inputModalitiesOverride(modelId: string): string[] | undefined {
231
232
  }
232
233
 
233
234
  export function runtimeCompat(provider: string, registered: Record<string, unknown> | undefined, modelId?: string): unknown {
235
+ // Hosted Dari reads the thinking level from Anthropic's adaptive effort and
236
+ // calls the provider itself, so no model's own wire settings apply.
237
+ if (provider === HOSTED_DARI_PROVIDER) return { forceAdaptiveThinking: true };
234
238
  const canonical = modelId ? canonicalModelId(modelId) : undefined;
235
239
  const compatOverride = canonical
236
240
  ? PROVIDER_MODEL_COMPAT_OVERRIDES[provider]?.[canonical] ?? MODEL_COMPAT_OVERRIDES[canonical]
@@ -513,10 +513,9 @@ export type ResolveRouterRequest = {
513
513
  conversationId?: string;
514
514
  includePublicEvalCatalog?: boolean;
515
515
  clientHarness?: ClientHarness;
516
- // The connected gateway listing this router's models: a model a plan on
517
- // that gateway serves is listed though hosted Dari holds no plan for it.
518
- // Model lists only; that gateway serves those models itself.
519
- gatewayId?: string;
516
+ // The client's own identifying headers (ingress/client_harness.ts), for a
517
+ // platform that hands the request on.
518
+ clientHeaders?: Record<string, string>;
520
519
  // A later resolve with this request's `conversationId` replaces this one's
521
520
  // credentials, so none from it serve the request: a platform should not
522
521
  // mark a credential used or refresh it for this resolve.
@@ -620,6 +619,8 @@ export type RequestRecord = {
620
619
  // Set for a Dari Link token's request: its grant, and the thinking the
621
620
  // provider was sent (as X-Dari-Thinking-Level reports it).
622
621
  link?: { grantId: string; thinking: string | null; costUsd: number | null; credentialId: string | null };
622
+ // The user's plan that served the request, when one did.
623
+ subscriptionCredentialId?: string;
623
624
  // The router's non-secret routing settings, for embedders that compare or
624
625
  // replay routing decisions.
625
626
  router: RequestRecordRouter;
@@ -5,6 +5,6 @@ export const DEFAULT_ROUTER_ALIAS = "default";
5
5
  // The most prefix hashes one router resolution looks up.
6
6
  export const ROUTING_PREFIX_HASHES_MAX_COUNT = 200;
7
7
 
8
- // Names the gateway connected to hosted Dari that sent a request, so a model
9
- // list counts the plans that gateway keeps on its computer.
10
- export const GATEWAY_ID_HEADER = "x-dari-gateway-id";
8
+ // The provider id of hosted Dari when a gateway connected to it calls it for
9
+ // a model, as `dari/model/<id>` with the user's Dari key.
10
+ export const HOSTED_DARI_PROVIDER = "dari";
@@ -27,6 +27,7 @@ import {
27
27
  type RouterModelPrice,
28
28
  } from "@mupt-ai/dari-router/policy-engine";
29
29
  import { HttpError } from "../http/errors.js";
30
+ import { HOSTED_DARI_PROVIDER } from "../platform/routing_contract.js";
30
31
  import { effectiveContextWindow } from "../models/context_limits.js";
31
32
  import { defaultBaseUrl } from "../models/provider_defaults.js";
32
33
  import {
@@ -370,8 +371,14 @@ export function buildModel(
370
371
  ): Record<string, unknown> {
371
372
  const provider = config?.provider ?? providerForModel(modelId);
372
373
  const nativeId = config?.native_model_id ?? nativeModelId(modelId);
373
- const registered = resolveModelMetadata(pi, provider, modelId, nativeId);
374
- const id = registered?.id ?? (provider === "anthropic" ? nativeId.replace(/(?<=\d)\.(?=\d)/g, "-") : nativeId);
374
+ let registered = resolveModelMetadata(pi, provider, modelId, nativeId);
375
+ let id = registered?.id ?? (provider === "anthropic" ? nativeId.replace(/(?<=\d)\.(?=\d)/g, "-") : nativeId);
376
+ if (provider === HOSTED_DARI_PROVIDER) {
377
+ // Hosted Dari serves a model under its Dari id, as the model's own
378
+ // provider describes it.
379
+ registered = resolveModelMetadata(pi, providerForModel(modelId), modelId, nativeModelId(modelId));
380
+ id = nativeId;
381
+ }
375
382
  const price = executionPricing(pricing, config);
376
383
  const configuredThinkingLevels = config?.supported_thinking_levels;
377
384
  // A null catalog value delegates to Pi's registry when it knows the model.
@@ -419,6 +426,7 @@ export function buildModel(
419
426
  ...(effectiveThinkingLevels
420
427
  ? { supportedThinkingLevels: [...effectiveThinkingLevels] }
421
428
  : {}),
429
+ ...(config?.headers ? { headers: config.headers } : {}),
422
430
  fastMode: config?.fast_mode ?? false,
423
431
  zeroDataRetention: config?.zdr ?? false,
424
432
  };
@@ -77,6 +77,7 @@ export async function prepareRoutedCompletion(args: {
77
77
  clientRequestId: string | null;
78
78
  tagsHeader: string | null;
79
79
  clientHarness?: ClientHarness;
80
+ clientHeaders?: Record<string, string>;
80
81
  harnessConversationIdentity?: HarnessConversationIdentity;
81
82
  }): Promise<PreparedRoutedCompletion> {
82
83
  const tags = requestTags(args.tagsHeader);
@@ -86,6 +87,7 @@ export async function prepareRoutedCompletion(args: {
86
87
  routerId: args.routerId,
87
88
  apiKey: args.apiKey,
88
89
  includePublicEvalCatalog: true,
90
+ clientHeaders: args.clientHeaders,
89
91
  };
90
92
  // Direct /v1 callers are authenticated by API key, so their canonical
91
93
  // organization router is not known until this resolve completes. Fingerprint
@@ -8,6 +8,7 @@ import type { ClientHarness, ResolvedRouter } from "../types.js";
8
8
  import { assertAutoroutingAllowed, assertCreditAvailableBeforeRouting, routerSelectsModels } from "../telemetry/usage.js";
9
9
  import type { HarnessConversationIdentity } from "./harness_identity/index.js";
10
10
  import { CustomerDisconnectedError } from "./customer_disconnect.js";
11
+ import { clientHeaders } from "../ingress/client_harness.js";
11
12
  import { withModelMenuHint } from "./model_menu_hint.js";
12
13
  import { prepareRoutedCompletion } from "./prepare_routed_completion.js";
13
14
  import type { RoutedProtocol } from "./routed_protocol.js";
@@ -42,6 +43,7 @@ export async function handleRoutedCompletion(args: {
42
43
  clientRequestId,
43
44
  tagsHeader: args.request.headers.get("x-dari-tags"),
44
45
  clientHarness: args.clientHarness,
46
+ clientHeaders: clientHeaders(args.request.headers),
45
47
  harnessConversationIdentity: args.harnessConversationIdentity,
46
48
  }).catch((error: unknown) => ({ error }));
47
49
  if ("error" in prepared) {