@mupt-ai/dari-gateway 0.3.2 → 0.3.4

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 (70) hide show
  1. package/README.md +10 -11
  2. package/dari-gateway.example.yaml +1 -1
  3. package/dist/context/interaction_fingerprint.js +10 -1
  4. package/dist/context/interaction_fingerprint_format.d.ts +4 -0
  5. package/dist/context/interaction_fingerprint_format.js +3 -0
  6. package/dist/context/provider_prompt_accounting.js +52 -4
  7. package/dist/context/routing_context.d.ts +6 -1
  8. package/dist/context/routing_context.js +40 -4
  9. package/dist/ingress/anthropic_messages.js +12 -0
  10. package/dist/ingress/codex.js +12 -7
  11. package/dist/interaction/capabilities.d.ts +1 -0
  12. package/dist/interaction/capabilities.js +6 -0
  13. package/dist/interaction/document.d.ts +2 -0
  14. package/dist/interaction/document.js +8 -0
  15. package/dist/interaction/types.d.ts +7 -1
  16. package/dist/observability/errors.js +19 -0
  17. package/dist/platform/platform.d.ts +14 -0
  18. package/dist/protocol/input/anthropic_messages.js +74 -1
  19. package/dist/protocol/input/chat_completions.js +6 -0
  20. package/dist/protocol/input/chat_completions_validation.js +8 -0
  21. package/dist/protocol/input/openai_responses.js +8 -0
  22. package/dist/protocol/output/anthropic_messages_output.js +7 -0
  23. package/dist/providers/key_check.d.ts +31 -0
  24. package/dist/providers/key_check.js +54 -0
  25. package/dist/providers/model_capabilities.d.ts +2 -0
  26. package/dist/providers/model_capabilities.js +15 -0
  27. package/dist/providers/pi_context.js +13 -5
  28. package/dist/runtime/harness_identity/conversation.d.ts +4 -0
  29. package/dist/runtime/harness_identity/extract.d.ts +1 -0
  30. package/dist/runtime/harness_identity/extract.js +7 -0
  31. package/dist/runtime/harness_identity/index.d.ts +1 -1
  32. package/dist/runtime/harness_identity/index.js +1 -1
  33. package/dist/runtime/prepare_routed_completion.js +8 -1
  34. package/dist/self_host/config.d.ts +1 -1
  35. package/dist/self_host/config.js +2 -1
  36. package/dist/self_host/main.js +38 -5
  37. package/dist/self_host/resolve.d.ts +1 -0
  38. package/dist/self_host/resolve.js +3 -3
  39. package/dist/strategies/selector_projection.js +3 -0
  40. package/dist/telemetry/report.d.ts +3 -1
  41. package/dist/telemetry/report.js +23 -0
  42. package/package.json +2 -2
  43. package/src/context/interaction_fingerprint.ts +15 -1
  44. package/src/context/interaction_fingerprint_format.ts +4 -0
  45. package/src/context/provider_prompt_accounting.ts +52 -6
  46. package/src/context/routing_context.ts +56 -2
  47. package/src/ingress/anthropic_messages.ts +15 -1
  48. package/src/ingress/codex.ts +12 -9
  49. package/src/interaction/capabilities.ts +7 -0
  50. package/src/interaction/document.ts +8 -0
  51. package/src/interaction/types.ts +8 -1
  52. package/src/observability/errors.ts +21 -0
  53. package/src/platform/platform.ts +22 -0
  54. package/src/protocol/input/anthropic_messages.ts +71 -1
  55. package/src/protocol/input/chat_completions.ts +6 -0
  56. package/src/protocol/input/chat_completions_validation.ts +8 -0
  57. package/src/protocol/input/openai_responses.ts +13 -0
  58. package/src/protocol/output/anthropic_messages_output.ts +7 -0
  59. package/src/providers/key_check.ts +76 -0
  60. package/src/providers/model_capabilities.ts +18 -0
  61. package/src/providers/pi_context.ts +14 -5
  62. package/src/runtime/harness_identity/conversation.ts +5 -0
  63. package/src/runtime/harness_identity/extract.ts +10 -0
  64. package/src/runtime/harness_identity/index.ts +1 -0
  65. package/src/runtime/prepare_routed_completion.ts +12 -1
  66. package/src/self_host/config.ts +5 -2
  67. package/src/self_host/main.ts +45 -5
  68. package/src/self_host/resolve.ts +3 -3
  69. package/src/strategies/selector_projection.ts +2 -0
  70. package/src/telemetry/report.ts +34 -1
@@ -5,6 +5,7 @@ import { parseDataImageUrl } from "../../interaction/image.js";
5
5
  import { decodeUntrustedProviderContinuationState } from "../../interaction/provider_continuation_state.js";
6
6
  import { CANONICAL_ROUTER_MODEL, explicitModelId, unsupportedModelMessage } from "./router_model.js";
7
7
  import { isProtocolToolCallId, TOOL_CALL_ID_MAX_LENGTH, toolsByWireName, } from "../../interaction/tool_identity.js";
8
+ import { parsePdfDataUrl } from "../../interaction/document.js";
8
9
  const UNSUPPORTED_INPUT_ITEM_TYPES = new Set([
9
10
  "additional_tools",
10
11
  "agent_message",
@@ -388,6 +389,13 @@ function responseContent(value, param) {
388
389
  ...(detail !== undefined ? { detail } : {}),
389
390
  };
390
391
  }
392
+ if (part.type === "input_file") {
393
+ const data = typeof part.file_data === "string" ? parsePdfDataUrl(part.file_data) : undefined;
394
+ if (data === undefined) {
395
+ throw new HttpError(400, "Responses input_file parts must carry a base64 PDF data URL in file_data; file_id and file_url are not supported.", "unsupported_file_source", `${param}.${index}`);
396
+ }
397
+ return { type: "document", mimeType: "application/pdf", data };
398
+ }
391
399
  throw new HttpError(400, `Responses content part type '${String(part.type ?? "unknown")}' is not supported.`, "unsupported_response_content", `${param}.${index}.type`);
392
400
  });
393
401
  }
@@ -51,6 +51,13 @@ export function anthropicContent(output) {
51
51
  content.push({ type: "text", text: `Referenced tool: ${part.toolName}` });
52
52
  continue;
53
53
  }
54
+ if (part.type === "document") {
55
+ content.push({
56
+ type: "document",
57
+ source: { type: "base64", media_type: part.mimeType, data: part.data },
58
+ });
59
+ continue;
60
+ }
54
61
  const image = parseDataImageUrl(part.url);
55
62
  if (!image)
56
63
  throw new Error("Anthropic output images must use base64 data URLs.");
@@ -0,0 +1,31 @@
1
+ /**
2
+ * - `valid`: the provider accepted the key.
3
+ * - `rejected`: the provider refused it (401 or 403).
4
+ * - `unchecked`: no answer either way, such as a network error, an outage, or
5
+ * a provider without a known check. Callers treat this as not rejected so a
6
+ * provider outage never blocks a key.
7
+ */
8
+ export type ProviderKeyCheckResult = {
9
+ result: "valid";
10
+ } | {
11
+ result: "rejected";
12
+ status: number;
13
+ } | {
14
+ result: "unchecked";
15
+ };
16
+ export type ProviderKeyEndpoint = {
17
+ api: string;
18
+ baseUrl: string;
19
+ };
20
+ /**
21
+ * Ask a provider whether an API key works, with the cheapest authenticated
22
+ * request its wire API offers: list models, or, where listing models needs
23
+ * no key, an endpoint that does. The self-hosted gateway runs this at startup
24
+ * and the hosted control plane before it saves a key.
25
+ */
26
+ export declare function checkProviderKey(args: {
27
+ provider: string;
28
+ key: string;
29
+ endpoint?: ProviderKeyEndpoint;
30
+ fetch: typeof fetch;
31
+ }): Promise<ProviderKeyCheckResult>;
@@ -0,0 +1,54 @@
1
+ import { getBuiltinModels } from "@mupt-ai/pi-ai/providers/all";
2
+ const CHECK_TIMEOUT_MS = 10_000;
3
+ /**
4
+ * Ask a provider whether an API key works, with the cheapest authenticated
5
+ * request its wire API offers: list models, or, where listing models needs
6
+ * no key, an endpoint that does. The self-hosted gateway runs this at startup
7
+ * and the hosted control plane before it saves a key.
8
+ */
9
+ export async function checkProviderKey(args) {
10
+ const check = keyCheckRequest(args.provider, args.key, args.endpoint);
11
+ if (check === null)
12
+ return { result: "unchecked" };
13
+ try {
14
+ const response = await args.fetch(check.url, {
15
+ headers: check.headers,
16
+ signal: AbortSignal.timeout(CHECK_TIMEOUT_MS),
17
+ });
18
+ await response.body?.cancel();
19
+ if (response.status === 401 || response.status === 403) {
20
+ return { result: "rejected", status: response.status };
21
+ }
22
+ return response.ok ? { result: "valid" } : { result: "unchecked" };
23
+ }
24
+ catch {
25
+ return { result: "unchecked" };
26
+ }
27
+ }
28
+ function keyCheckRequest(provider, key, endpoint) {
29
+ const bearer = { authorization: `Bearer ${key}` };
30
+ if (endpoint === undefined) {
31
+ if (provider === "openrouter")
32
+ return { url: "https://openrouter.ai/api/v1/key", headers: bearer };
33
+ if (provider === "vercel-ai-gateway")
34
+ return { url: "https://ai-gateway.vercel.sh/v1/credits", headers: bearer };
35
+ }
36
+ const target = endpoint
37
+ ?? getBuiltinModels(provider)?.[0];
38
+ if (target === undefined || !URL.canParse(target.baseUrl))
39
+ return null;
40
+ const base = target.baseUrl.replace(/\/+$/, "");
41
+ switch (target.api) {
42
+ case "anthropic-messages":
43
+ return { url: `${base}/v1/models`, headers: { "x-api-key": key, "anthropic-version": "2023-06-01" } };
44
+ case "google-generative-ai":
45
+ return { url: `${base}/models`, headers: { "x-goog-api-key": key } };
46
+ case "mistral-conversations":
47
+ return { url: `${base}/v1/models`, headers: bearer };
48
+ case "openai-completions":
49
+ case "openai-responses":
50
+ return { url: `${base}/models`, headers: bearer };
51
+ default:
52
+ return null;
53
+ }
54
+ }
@@ -4,6 +4,8 @@ type ModelCapabilityMetadata = {
4
4
  export declare const BEDROCK_API = "bedrock-converse-stream";
5
5
  export declare function isBedrockApi(api: unknown): boolean;
6
6
  export declare function modelSupportsImageInput(metadata: ModelCapabilityMetadata): boolean;
7
+ export declare function apiSupportsDocumentInput(api: string): boolean;
8
+ export declare function modelSupportsDocumentInput(modelId: string, metadata: ModelCapabilityMetadata): boolean;
7
9
  export declare function providerApiCanSerializeResponseFormat(metadata: ModelCapabilityMetadata): boolean;
8
10
  export declare function isOpenAIResponsesApi(api: unknown): boolean;
9
11
  export declare function modelSupportsReasoningConfigurationUpdate(metadata: ModelCapabilityMetadata): boolean;
@@ -6,6 +6,21 @@ export function isBedrockApi(api) {
6
6
  export function modelSupportsImageInput(metadata) {
7
7
  return Array.isArray(metadata.model.input) && metadata.model.input.includes("image");
8
8
  }
9
+ /* PDFs are sent natively only where the model owner documents PDF input on
10
+ that API. The same API can serve other owners (xAI and Meta on Responses,
11
+ GPT on Bedrock) whose PDF support is unverified, so both must match. */
12
+ const DOCUMENT_INPUT_APIS_BY_OWNER = {
13
+ anthropic: new Set(["anthropic-messages", "bedrock-converse-stream"]),
14
+ openai: new Set(["openai-responses", "azure-openai-responses", "openai-codex-responses"]),
15
+ };
16
+ export function apiSupportsDocumentInput(api) {
17
+ return Object.values(DOCUMENT_INPUT_APIS_BY_OWNER).some((apis) => apis.has(api));
18
+ }
19
+ export function modelSupportsDocumentInput(modelId, metadata) {
20
+ const owner = modelId.split("/", 1)[0] ?? "";
21
+ const api = metadata.model.api;
22
+ return typeof api === "string" && DOCUMENT_INPUT_APIS_BY_OWNER[owner]?.has(api) === true;
23
+ }
9
24
  export function providerApiCanSerializeResponseFormat(metadata) {
10
25
  return (metadata.model.api === "openai-responses" ||
11
26
  metadata.model.api === "azure-openai-responses" ||
@@ -5,6 +5,7 @@ import { parseDataImageUrl } from "../interaction/image.js";
5
5
  import { providerToolCallId, toolWireName } from "../interaction/tool_identity.js";
6
6
  import { compatibleProviderContinuation, sameProviderIdentity, } from "../interaction/provider_continuation_state.js";
7
7
  import { isOpenAIResponsesApi } from "./model_capabilities.js";
8
+ import { apiSupportsDocumentInput } from "./model_capabilities.js";
8
9
  const UNKNOWN_SOURCE = {
9
10
  provider: "dari",
10
11
  api: "interaction-history",
@@ -72,7 +73,7 @@ export function buildContext(request, target) {
72
73
  sawConversationItem = true;
73
74
  if (item.type === "message" && item.role === "user") {
74
75
  flushAssistant();
75
- appendUserMessage(messages, userContent(item.content, item.contentShape), timestamp);
76
+ appendUserMessage(messages, userContent(item.content, item.contentShape, target), timestamp);
76
77
  continue;
77
78
  }
78
79
  if (item.type === "tool_result") {
@@ -252,10 +253,10 @@ function thinkingContent(item, continuation) {
252
253
  redacted: true,
253
254
  };
254
255
  }
255
- function userContent(content, shape) {
256
+ function userContent(content, shape, target) {
256
257
  if (shape !== "parts")
257
258
  return content.filter((part) => part.type === "text").map((part) => part.text).join("");
258
- return content.map(contentToPi);
259
+ return content.map((part) => contentToPi(part, target));
259
260
  }
260
261
  function appendPositionalNote(messages, text, timestamp) {
261
262
  const previous = messages.at(-1);
@@ -290,13 +291,20 @@ function toolResultContent(content, target) {
290
291
  const filtered = target.api === "anthropic-messages"
291
292
  ? content.filter((part) => part.type !== "tool_reference")
292
293
  : content;
293
- return filtered.map(contentToPi);
294
+ return filtered.map((part) => contentToPi(part, target));
294
295
  }
295
- function contentToPi(content) {
296
+ function contentToPi(content, target) {
296
297
  if (content.type === "text")
297
298
  return { type: "text", text: content.text };
298
299
  if (content.type === "tool_reference")
299
300
  return { type: "text", text: `Referenced tool: ${content.toolName}` };
301
+ if (content.type === "document") {
302
+ // Routing keeps PDFs on document-capable models; this guards direct callers.
303
+ if (!apiSupportsDocumentInput(target.api)) {
304
+ throw new HttpError(400, `PDF document input is not supported by the ${target.api} API.`, "unsupported_input_modality", "input.document");
305
+ }
306
+ return { type: "document", mimeType: content.mimeType, data: content.data };
307
+ }
300
308
  const image = parseDataImageUrl(content.url);
301
309
  if (!image) {
302
310
  throw new HttpError(400, "Only base64 data URLs are supported for routed image input.", "invalid_request_error", "input.image_url");
@@ -13,6 +13,10 @@ export type HarnessConversationIdentity = {
13
13
  kind: "openai_chat_session";
14
14
  value: string;
15
15
  qualifiers?: string[];
16
+ } | {
17
+ kind: "muse_code_thread";
18
+ value: string;
19
+ qualifiers?: string[];
16
20
  };
17
21
  export type HarnessConversationScope = {
18
22
  organizationId: string;
@@ -6,4 +6,5 @@ export declare function openCodeRequestContext(headers: Headers): AgentRequestCo
6
6
  export declare function codexConversationIdentity(headers: Headers, payload: Record<string, unknown>): HarnessConversationIdentity | undefined;
7
7
  export declare function codexRequestPurpose(headers: Headers, payload: Record<string, unknown>): InteractionRequestPurpose | undefined;
8
8
  export declare function codexRequestContext(headers: Headers, payload: Record<string, unknown>): AgentRequestContext | undefined;
9
+ export declare function museCodeConversationIdentity(headers: Headers): HarnessConversationIdentity | undefined;
9
10
  export declare function claudeCodeConversationIdentity(headers: Headers, metadataSessionId?: string): HarnessConversationIdentity | undefined;
@@ -129,6 +129,13 @@ export function codexRequestContext(headers, payload) {
129
129
  agentType: boundedIdentity(agentKind, "x-codex-turn-metadata.subagent_kind"),
130
130
  };
131
131
  }
132
+ // Muse Code sends its thread on every Responses request. The main agent's
133
+ // thread is its session, and each subagent has its own thread, so each keeps
134
+ // its own conversation and lease.
135
+ export function museCodeConversationIdentity(headers) {
136
+ const threadId = boundedIdentity(headers.get("x-tbh-thread-id"), "x-tbh-thread-id");
137
+ return threadId === undefined ? undefined : { kind: "muse_code_thread", value: threadId };
138
+ }
132
139
  export function claudeCodeConversationIdentity(headers, metadataSessionId) {
133
140
  const candidates = [
134
141
  uuidIdentity(headers.get("x-claude-code-session-id"), "x-claude-code-session-id"),
@@ -1,2 +1,2 @@
1
1
  export { scopedHarnessAgentId, scopedHarnessConversationId, scopedHarnessSessionId, type HarnessConversationIdentity, type HarnessConversationScope, } from "./conversation.js";
2
- export { chatCompletionsConversationIdentity, claudeCodeConversationIdentity, codexConversationIdentity, codexRequestPurpose, codexRequestContext, openCodeRequestContext, piRequestContext, } from "./extract.js";
2
+ export { chatCompletionsConversationIdentity, claudeCodeConversationIdentity, codexConversationIdentity, codexRequestPurpose, codexRequestContext, museCodeConversationIdentity, openCodeRequestContext, piRequestContext, } from "./extract.js";
@@ -1,2 +1,2 @@
1
1
  export { scopedHarnessAgentId, scopedHarnessConversationId, scopedHarnessSessionId, } from "./conversation.js";
2
- export { chatCompletionsConversationIdentity, claudeCodeConversationIdentity, codexConversationIdentity, codexRequestPurpose, codexRequestContext, openCodeRequestContext, piRequestContext, } from "./extract.js";
2
+ export { chatCompletionsConversationIdentity, claudeCodeConversationIdentity, codexConversationIdentity, codexRequestPurpose, codexRequestContext, museCodeConversationIdentity, openCodeRequestContext, piRequestContext, } from "./extract.js";
@@ -1,4 +1,6 @@
1
1
  import { interactionConversationPrefix } from "../context/interaction_fingerprint.js";
2
+ import { clampRequestedEffort } from "../context/routing_context.js";
3
+ import { modelMetadataLookup } from "../providers/pi.js";
2
4
  import { buildRoutingContext, derivePrefixLookupHashes, } from "../context/routing_context.js";
3
5
  import { isBackgroundRequest } from "../interaction/types.js";
4
6
  import { executionProviderForModel } from "../models/execution_provider.js";
@@ -84,7 +86,10 @@ export async function prepareRoutedCompletion(args) {
84
86
  }
85
87
  const access = strictProviderAccess(credentials, args.interaction);
86
88
  credentials = access.credentials;
87
- args = { ...args, interaction: access.interaction };
89
+ args = {
90
+ ...args,
91
+ interaction: clampRequestedEffort(access.interaction, credentials, modelMetadataLookup(credentials.model_configs)),
92
+ };
88
93
  credentials = await withProviderCredentials(credentials, args.apiKey, args.clientHarness);
89
94
  const billable = true;
90
95
  const routing = await buildRoutingContext({
@@ -138,6 +143,8 @@ export async function prepareRoutedCompletion(args) {
138
143
  identityHit: routing.identityHit,
139
144
  hits: routing.hits,
140
145
  costEstimates: routing.reportingCostEstimates,
146
+ candidates: candidateResolution.candidates,
147
+ sessionPinKey: sessionPin?.key,
141
148
  pruning: reportedPruning(candidateResolution.pruning, routing.imageCapabilityPrunedModels),
142
149
  pricing: routing.pricing,
143
150
  chainByModel: routing.prefix.chainByModel,
@@ -7,7 +7,7 @@ import { type ReasoningEffort } from "@mupt-ai/dari-router/policy-engine";
7
7
  * default:
8
8
  * models:
9
9
  * - anthropic/claude-sonnet-5-5
10
- * - id: openai/gpt-5.5
10
+ * - id: openai/gpt-6.1-sol
11
11
  * thinking: [medium, high]
12
12
  * subscriptions: true # serve with connected Claude Code / ChatGPT plans
13
13
  * sessionPinning: false # route each session and subagent once, then keep its model
@@ -5,7 +5,8 @@ const MODEL_ID_PATTERN = /^[a-z0-9][a-z0-9.-]*\/\S+$/;
5
5
  export async function loadGatewayConfig(path) {
6
6
  const file = Bun.file(path);
7
7
  if (!(await file.exists())) {
8
- throw new Error(`Gateway config not found at ${path}.`);
8
+ throw new Error(`Gateway config not found at ${path}. Write one from dari-gateway.example.yaml, `
9
+ + "or set DARI_GATEWAY_CONFIG (in the container image, mount it at /config/dari-gateway.yaml).");
9
10
  }
10
11
  const text = await file.text();
11
12
  const raw = path.endsWith(".json") ? JSON.parse(text) : Bun.YAML.parse(text);
@@ -8,9 +8,11 @@ import { createRequestHandler } from "../http/handler.js";
8
8
  import { installShutdownHandlers, startServer } from "../http/serve.js";
9
9
  import { createAutoRoutingSelectorBackend } from "../strategies/auto_routing_selector.js";
10
10
  import { createPrioritySelectorBackend } from "../strategies/priority_selector.js";
11
- import { loadGatewayConfig } from "./config.js";
12
11
  import { createSelfHostedPlatform } from "./platform.js";
13
- import { gatewayKeyIndex, providersWithoutCredentials } from "./resolve.js";
12
+ import { providerForModel } from "@mupt-ai/dari-router/policy-engine";
13
+ import { checkProviderKey } from "../providers/key_check.js";
14
+ import { loadGatewayConfig } from "./config.js";
15
+ import { configuredProviderApiKey, gatewayKeyIndex, providersWithoutCredentials } from "./resolve.js";
14
16
  import { PrefixStore } from "./prefix_store.js";
15
17
  import { SessionPinStore } from "./session_pin_store.js";
16
18
  import { handleSubscriptionRequest, SubscriptionStore } from "./subscriptions/index.js";
@@ -69,6 +71,7 @@ export async function startSelfHostedGateway(env = process.env) {
69
71
  console.warn("dari-gateway router has providers without credentials; their models are not served", JSON.stringify({ router: routerId, providers: missing }));
70
72
  }
71
73
  }
74
+ await checkConfiguredProviderKeys(config, (provider) => configuredProviderApiKey({ config, providerApiKey, env }, provider));
72
75
  const autoRoutingKey = env.DARI_AUTO_ROUTING_API_KEY?.trim();
73
76
  const selectorBackend = autoRoutingKey
74
77
  ? createAutoRoutingSelectorBackend({
@@ -99,13 +102,43 @@ export async function startSelfHostedGateway(env = process.env) {
99
102
  const server = startServer(port, handler, { hostname });
100
103
  console.info("dari-gateway listening", JSON.stringify({
101
104
  hostname,
102
- port,
105
+ // The bound port, so PORT=0 reports the port the OS assigned.
106
+ port: server.port,
103
107
  routers: Object.keys(config.routers),
104
108
  auto_routing: autoRoutingKey ? "dari" : "priority",
105
109
  }));
106
110
  return { server, close: () => db.close() };
107
111
  }
112
+ /**
113
+ * Check each provider API key the routers use before serving: a key its
114
+ * provider rejects fails startup, and one no check could answer is reported.
115
+ */
116
+ async function checkConfiguredProviderKeys(config, providerApiKey) {
117
+ const providers = new Set(Object.values(config.routers).flatMap((router) => router.models.map((model) => providerForModel(model.id))));
118
+ const checks = await Promise.all([...providers].map(async (provider) => {
119
+ const endpoint = config.providers[provider];
120
+ // Endpoints configured without a key variable take no key.
121
+ if (endpoint !== undefined && endpoint.apiKeyEnv === undefined)
122
+ return null;
123
+ const key = await providerApiKey(provider);
124
+ if (key === undefined)
125
+ return null;
126
+ return { provider, ...(await checkProviderKey({ provider, key, ...(endpoint ? { endpoint } : {}), fetch })) };
127
+ }));
128
+ const rejected = checks.flatMap((check) => check?.result === "rejected" ? [`${check.provider} (${check.status})`] : []);
129
+ if (rejected.length > 0) {
130
+ throw new Error(`Provider API keys were rejected: ${rejected.join(", ")}. Fix or unset each key before starting the gateway.`);
131
+ }
132
+ const unchecked = checks.flatMap((check) => check?.result === "unchecked" ? [check.provider] : []);
133
+ if (unchecked.length > 0) {
134
+ console.warn("dari-gateway could not check these provider API keys", JSON.stringify({ providers: unchecked }));
135
+ }
136
+ }
108
137
  if (import.meta.main) {
109
- const { server, close } = await startSelfHostedGateway();
110
- installShutdownHandlers(server, async () => close());
138
+ // Startup errors are configuration mistakes: print the message, not a stack.
139
+ const started = await startSelfHostedGateway().catch((error) => {
140
+ console.error(`dari-gateway: ${error instanceof Error ? error.message : String(error)}`);
141
+ process.exit(1);
142
+ });
143
+ installShutdownHandlers(started.server, async () => started.close());
111
144
  }
@@ -25,6 +25,7 @@ export type SelfHostedResolverDeps = {
25
25
  * neither are left out.
26
26
  */
27
27
  export declare function resolveSelfHostedRouter(deps: SelfHostedResolverDeps, request: ResolveRouterRequest): Promise<ResolvedRouter>;
28
+ export declare function configuredProviderApiKey(deps: Pick<SelfHostedResolverDeps, "config" | "providerApiKey" | "env">, provider: string): Promise<string | undefined>;
28
29
  export declare function gatewayKeyIndex(keys: readonly string[], presented: string): number | null;
29
30
  /**
30
31
  * Providers a router lists that no credential can serve: no API key and no
@@ -44,7 +44,7 @@ export async function resolveSelfHostedRouter(deps, request) {
44
44
  if (subscription !== null && deps.subscriptions.list(subscription).length > 0) {
45
45
  exhausted.add(subscription);
46
46
  }
47
- const apiKey = await providerApiKey(deps, provider);
47
+ const apiKey = await configuredProviderApiKey(deps, provider);
48
48
  credentials.set(provider, apiKey ? { key: apiKey, source: "user" } : null);
49
49
  }
50
50
  const models = router.models.filter((model) => credentials.get(providerForModel(model.id)) != null);
@@ -112,7 +112,7 @@ export async function resolveSelfHostedRouter(deps, request) {
112
112
  }
113
113
  // Configured endpoints read their own key variable, or send a placeholder
114
114
  // when they take none; known providers use their standard variable.
115
- async function providerApiKey(deps, provider) {
115
+ export async function configuredProviderApiKey(deps, provider) {
116
116
  const endpoint = deps.config.providers[provider];
117
117
  if (endpoint === undefined)
118
118
  return (await deps.providerApiKey(provider))?.trim() || undefined;
@@ -172,7 +172,7 @@ export async function providersWithoutCredentials(deps, router) {
172
172
  const connected = plans.some((plan) => plan !== null && deps.subscriptions.list(plan).length > 0);
173
173
  if (connected)
174
174
  continue;
175
- const apiKey = await providerApiKey(deps, provider);
175
+ const apiKey = await configuredProviderApiKey(deps, provider);
176
176
  if (apiKey === undefined)
177
177
  missing.push(provider);
178
178
  }
@@ -145,6 +145,9 @@ function selectorContentField(content, shape, imagePart) {
145
145
  if (part.type === "tool_reference") {
146
146
  return { type: "text", text: `Referenced tool: ${part.toolName}` };
147
147
  }
148
+ // The selector model is text-only; it sees a marker, not the document bytes.
149
+ if (part.type === "document")
150
+ return { type: "text", text: "(PDF document omitted from selector input)" };
148
151
  return imagePart(part.url, part.detail);
149
152
  }),
150
153
  };
@@ -1,4 +1,4 @@
1
- import { type CandidateCostEstimate, type CandidatePruningAudit, type ChainHits, type PrefixHit, type PricingLookup, type RoutingDecision, type RoutingStrategy } from "@mupt-ai/dari-router/policy-engine";
1
+ import { type CandidateCostEstimate, type CandidatePruningAudit, type ChainHits, type PrefixHit, type PricingLookup, type RoutingCandidate, type RoutingDecision, type RoutingStrategy } from "@mupt-ai/dari-router/policy-engine";
2
2
  import type { ImageCapabilityPrunedModel } from "../context/routing_context.js";
3
3
  import { type InteractionRequest, type ProviderIdentity } from "../interaction/types.js";
4
4
  import { type RequestTags } from "../platform/platform.js";
@@ -47,6 +47,8 @@ export declare class RequestReporter {
47
47
  identityHit?: PrefixHit;
48
48
  hits: ChainHits;
49
49
  costEstimates: CandidateCostEstimate[];
50
+ candidates: readonly RoutingCandidate[];
51
+ sessionPinKey?: string;
50
52
  pruning: ReportedCandidatePruning | null;
51
53
  pricing: PricingLookup | null;
52
54
  chainByModel: ReadonlyMap<string, string[]>;
@@ -414,6 +414,9 @@ export class RequestReporter {
414
414
  touched_prefix_hash: touchedHash,
415
415
  };
416
416
  gatewayPlatform().recordRequest({
417
+ router: requestRecordRouter(a.credentials),
418
+ candidates: a.candidates.map(({ model, reasoningEffort }) => ({ model, reasoningEffort })),
419
+ ...(a.sessionPinKey === undefined ? {} : { sessionPinKey: a.sessionPinKey }),
417
420
  row: ingestPayload,
418
421
  summary: {
419
422
  request_id: a.requestId,
@@ -583,3 +586,23 @@ function usageIngest(usage, pricingKnown) {
583
586
  pricing_known: pricingKnown,
584
587
  };
585
588
  }
589
+ function requestRecordRouter(router) {
590
+ return {
591
+ enabledModels: [...router.enabled_models],
592
+ thinkingLevels: Object.fromEntries(router.enabled_models.map((model) => [
593
+ model,
594
+ [
595
+ ...(router.model_thinking_levels?.[model]
596
+ ?? router.model_configs?.[model]?.supported_thinking_levels
597
+ ?? []),
598
+ ],
599
+ ])),
600
+ defaultThinkingLevels: Object.fromEntries(router.enabled_models.flatMap((model) => {
601
+ const level = router.model_configs?.[model]?.default_thinking_level;
602
+ return level ? [[model, level]] : [];
603
+ })),
604
+ strict: router.strict === true,
605
+ speculativeRouting: router.speculative_routing === true,
606
+ sessionPinning: router.session_pinning === true,
607
+ };
608
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mupt-ai/dari-gateway",
3
- "version": "0.3.2",
3
+ "version": "0.3.4",
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": {
@@ -50,7 +50,7 @@
50
50
  "dependencies": {
51
51
  "@aws-sdk/client-sts": "3.1063.0",
52
52
  "@mupt-ai/dari-router": "0.2.5",
53
- "@mupt-ai/pi-ai": "1.4.0-mupt.2"
53
+ "@mupt-ai/pi-ai": "1.4.0-mupt.3"
54
54
  },
55
55
  "devDependencies": {
56
56
  "@types/bun": "^1.3.4",
@@ -105,7 +105,10 @@ export function interactionLooseChain(routerId: string, request: InteractionRequ
105
105
  // unrelated work reusing the same harness session gets a new group.
106
106
  export function interactionConversationPrefix(request: InteractionRequest): string {
107
107
  const firstStep = conversationFingerprintSteps(
108
- looseFingerprintSteps(request.sourceProtocol, request.items),
108
+ looseFingerprintSteps(
109
+ request.sourceProtocol,
110
+ request.items.filter((item) => !isOpenClawRuntimeContext(item)),
111
+ ),
109
112
  ).at(0);
110
113
  return sha256(stableStringify({
111
114
  version: CONVERSATION_PREFIX_VERSION,
@@ -115,6 +118,17 @@ export function interactionConversationPrefix(request: InteractionRequest): stri
115
118
  }));
116
119
  }
117
120
 
121
+ // OpenClaw appends a user message of runtime context (active exec sessions,
122
+ // subagents) to each request and drops it from later history. On a first
123
+ // turn it merges into the first transcript step, so leaving it in would give
124
+ // the first turn a different conversation than the turns after it.
125
+ const OPENCLAW_RUNTIME_CONTEXT = "<<<BEGIN_OPENCLAW_INTERNAL_CONTEXT>>>";
126
+
127
+ function isOpenClawRuntimeContext(item: InteractionItem): boolean {
128
+ return item.type === "message" && item.role === "user" && item.content.length > 0 &&
129
+ item.content.every((part) => part.type === "text" && part.text.trimStart().startsWith(OPENCLAW_RUNTIME_CONTEXT));
130
+ }
131
+
118
132
  export function interactionPrefixContext(
119
133
  routerId: string,
120
134
  request: InteractionRequest,
@@ -22,6 +22,7 @@ export type FingerprintContent =
22
22
  url: string;
23
23
  detail?: "auto" | "low" | "high" | "original";
24
24
  }
25
+ | { type: "document"; mimeType: "application/pdf"; data: string }
25
26
  | { type: "tool_reference"; toolName: string }
26
27
  >
27
28
  | null;
@@ -150,6 +151,9 @@ export function interactionFingerprintContent(
150
151
  toolName: part.toolName,
151
152
  };
152
153
  }
154
+ if (part.type === "document") {
155
+ return { type: "document" as const, mimeType: part.mimeType, data: part.data };
156
+ }
153
157
  return {
154
158
  type: "image" as const,
155
159
  url: part.url,
@@ -1,3 +1,5 @@
1
+ import { constants as zlibConstants, inflateSync } from "node:zlib";
2
+
1
3
  import {
2
4
  isRecord,
3
5
  stableStringify,
@@ -27,6 +29,42 @@ const IMAGE_ESTIMATED_TOKENS = {
27
29
  original: 2048,
28
30
  } as const;
29
31
  const CHARS_PER_ESTIMATED_TOKEN = 4;
32
+ // Anthropic bills each PDF page as its text plus a page image: 1,500-3,000
33
+ // tokens. Use the top of that range so a long PDF cannot look like it fits.
34
+ const PDF_ESTIMATED_TOKENS_PER_PAGE = 3000;
35
+ const PDF_PAGE_PATTERN = /\/Type\s*\/Page(?![a-zA-Z])/g;
36
+ const PDF_OBJECT_STREAM_START = /\/Type\s*\/ObjStm[\s\S]*?stream\r?\n/g;
37
+ // Object streams hold small dictionaries. The cap is total inflated bytes per
38
+ // PDF, so a compression bomb in a request costs at most this much memory.
39
+ const PDF_OBJECT_STREAM_INFLATE_BUDGET = 4 * 1024 * 1024;
40
+
41
+ function estimatedPdfPages(base64: string): number {
42
+ const bytes = Buffer.from(base64, "base64");
43
+ // latin1 maps each byte to one character, so string offsets are byte offsets.
44
+ const pdf = bytes.toString("latin1");
45
+ const visible = pdf.match(PDF_PAGE_PATTERN)?.length ?? 0;
46
+ if (visible > 0) return visible;
47
+ // PDF 1.5+ may keep every page dictionary in compressed object streams.
48
+ let hidden = 0;
49
+ let budget = PDF_OBJECT_STREAM_INFLATE_BUDGET;
50
+ for (const match of pdf.matchAll(PDF_OBJECT_STREAM_START)) {
51
+ const start = match.index + match[0].length;
52
+ const end = pdf.indexOf("endstream", start);
53
+ if (end === -1 || budget <= 0) break;
54
+ try {
55
+ const objects = inflateSync(bytes.subarray(start, end), {
56
+ finishFlush: zlibConstants.Z_SYNC_FLUSH,
57
+ maxOutputLength: budget,
58
+ });
59
+ budget -= objects.length;
60
+ hidden += objects.toString("latin1").match(PDF_PAGE_PATTERN)?.length ?? 0;
61
+ } catch (error) {
62
+ // Over budget: stop. Another filter or bad data: count what is readable.
63
+ if (error instanceof RangeError) break;
64
+ }
65
+ }
66
+ return Math.max(1, hidden);
67
+ }
30
68
 
31
69
  // Cost and cache-lookback estimates are candidate-specific because compatible
32
70
  // continuation state and provider serialization can change what each model
@@ -130,7 +168,7 @@ export function promptMetrics(
130
168
  0,
131
169
  ),
132
170
  serializedChars:
133
- stableStringify(prompt).length + accountingInput.imageEstimatedChars,
171
+ stableStringify(prompt).length + accountingInput.attachmentEstimatedChars,
134
172
  };
135
173
  }
136
174
 
@@ -214,14 +252,22 @@ function providerVisibleTools(
214
252
 
215
253
  function promptAccountingInput(request: InteractionRequest): {
216
254
  request: InteractionRequest;
217
- imageEstimatedChars: number;
255
+ attachmentEstimatedChars: number;
218
256
  } {
219
- let imageEstimatedChars = 0;
220
- const sanitizeContent = (parts: InteractionContent[]) =>
257
+ let attachmentEstimatedChars = 0;
258
+ // Attachments are estimated rather than serialized: their base64 is not
259
+ // what the provider bills, and a PDF must not reach the serializer of a
260
+ // model that cannot carry it.
261
+ const sanitizeContent = (parts: InteractionContent[]): InteractionContent[] =>
221
262
  parts.map((part) => {
263
+ if (part.type === "document") {
264
+ attachmentEstimatedChars +=
265
+ estimatedPdfPages(part.data) * PDF_ESTIMATED_TOKENS_PER_PAGE * CHARS_PER_ESTIMATED_TOKEN;
266
+ return { type: "text", text: "" };
267
+ }
222
268
  if (part.type !== "image") return part;
223
269
  const detail = part.detail ?? "auto";
224
- imageEstimatedChars +=
270
+ attachmentEstimatedChars +=
225
271
  IMAGE_ESTIMATED_TOKENS[detail] * CHARS_PER_ESTIMATED_TOKEN;
226
272
  return { ...part, url: ACCOUNTING_IMAGE_URL };
227
273
  });
@@ -236,6 +282,6 @@ function promptAccountingInput(request: InteractionRequest): {
236
282
  });
237
283
  return {
238
284
  request: { ...request, items },
239
- imageEstimatedChars,
285
+ attachmentEstimatedChars,
240
286
  };
241
287
  }