@mupt-ai/dari-gateway 1.0.338 → 1.0.339

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.
@@ -6,6 +6,7 @@ import { openAIResponsesResponse } from "../protocol/output/openai_responses.js"
6
6
  import { openAIResponsesSseStream } from "../protocol/output/openai_responses_stream.js";
7
7
  import { openAIResponsesToInteraction } from "../protocol/input/openai_responses.js";
8
8
  import { claimedClientHarness } from "./client_harness.js";
9
+ import { codexModelsEtag } from "./codex_models.js";
9
10
  import { parseJsonRequest } from "./json.js";
10
11
  import { museCodeClientId } from "./muse_code.js";
11
12
  import { handleRoutedCompletion } from "../runtime/routed_completion.js";
@@ -41,6 +42,11 @@ export async function handleResponses(request, routerId, selectorBackend) {
41
42
  }
42
43
  const harnessConversationIdentity = codexIdentity
43
44
  ?? (museClientId === undefined ? undefined : museCodeConversationIdentity(request.headers));
45
+ const clientHarness = museClientId !== undefined ? "muse_code"
46
+ // Codex describes every request in its turn metadata.
47
+ : codexContext !== undefined ? "codex"
48
+ : piContext !== undefined ? "pi"
49
+ : claimedClientHarness(request.headers);
44
50
  return await handleRoutedCompletion({
45
51
  request,
46
52
  routerId,
@@ -50,12 +56,12 @@ export async function handleResponses(request, routerId, selectorBackend) {
50
56
  streamBody: openAIResponsesSseStream,
51
57
  errorResponse,
52
58
  selectorBackend,
53
- clientHarness: museClientId !== undefined ? "muse_code"
54
- // Codex describes every request in its turn metadata.
55
- : codexContext !== undefined ? "codex"
56
- : piContext !== undefined ? "pi"
57
- : claimedClientHarness(request.headers),
59
+ clientHarness,
58
60
  harnessConversationIdentity,
61
+ // A running Codex re-reads its /model list when this changes.
62
+ ...(clientHarness === "codex"
63
+ ? { responseHeaders: (router) => ({ "X-Models-Etag": codexModelsEtag(router) }) }
64
+ : {}),
59
65
  });
60
66
  }
61
67
  catch (error) {
@@ -1,2 +1,3 @@
1
1
  import type { ResolvedRouter } from "../types.js";
2
- export declare function codexModelsResponse(router: Pick<ResolvedRouter, "enabled_models" | "model_configs" | "allow_long_context" | "autorouting_enabled" | "routing_listed" | "native_compaction">, imageInputFor: (model: string) => boolean, nativeCompactionFor?: (model: string) => boolean): Record<string, unknown>;
2
+ export declare function codexModelsResponse(router: Pick<ResolvedRouter, "enabled_models" | "model_configs" | "allow_long_context" | "autorouting_enabled" | "routing_listed" | "native_compaction">, imageInputFor: (model: string) => boolean, nativeCompactionFor?: (model: string) => boolean, direct?: boolean): Record<string, unknown>;
3
+ export declare function codexModelsEtag(router: Pick<ResolvedRouter, "enabled_models" | "model_configs" | "allow_long_context" | "autorouting_enabled" | "routing_listed">): string;
@@ -1,3 +1,4 @@
1
+ import { createHash } from "node:crypto";
1
2
  import { CANONICAL_ROUTER_MODEL, explicitModelSlug } from "../protocol/input/router_model.js";
2
3
  import { effectiveContextWindow } from "../models/context_limits.js";
3
4
  import { modelSupportsHostedWebSearch } from "../providers/model_capabilities.js";
@@ -64,38 +65,71 @@ function codexCatalogEntry(args) {
64
65
  multi_agent_version: null,
65
66
  };
66
67
  }
68
+ /* What Codex needs to parse an entry it fetched itself: it rejects the whole
69
+ catalog over a null web-search type, leaving /model empty, so the entry
70
+ names one, and the two nullable fields it may not accept as null are left
71
+ out. The `dari` launchers make the same changes to the catalog they hand
72
+ Codex; they read the nulls first to decide whether to turn web search off. */
73
+ function codexReadable(entry) {
74
+ const { tool_mode, multi_agent_version, ...rest } = entry;
75
+ return {
76
+ ...rest,
77
+ web_search_tool_type: entry.web_search_tool_type ?? "text",
78
+ ...(tool_mode === null ? {} : { tool_mode }),
79
+ ...(multi_agent_version === null ? {} : { multi_agent_version }),
80
+ };
81
+ }
67
82
  /* `dari/routing` comes first while the router may autoroute (the Codex
68
83
  launcher patches it); each enabled model follows as `dari/model/<id>` so
69
84
  Codex's /model menu can switch to it. The `dari` launchers build every
70
85
  agent's model menu from this list. `remote_compaction` tells the
71
- launcher which Codex provider compaction protocol the router accepts. */
72
- export function codexModelsResponse(router, imageInputFor, nativeCompactionFor = () => false) {
86
+ launcher which Codex provider compaction protocol the router accepts.
87
+ `direct` is a catalog for Codex's own fetch (its `model_catalog_url`),
88
+ which nothing patches on the way: `codex_direct` tells `dari setup codex`
89
+ that this gateway serves one, so it can point Codex at the URL instead of
90
+ a snapshot that goes stale when the router's models change. */
91
+ export function codexModelsResponse(router, imageInputFor, nativeCompactionFor = () => false, direct = false) {
73
92
  const remoteCompaction = router.native_compaction === true && router.enabled_models.some(nativeCompactionFor);
93
+ const models = codexCatalogEntries(router, imageInputFor);
74
94
  return {
75
95
  remote_compaction: remoteCompaction ? "v2" : "unsupported",
76
- models: [
77
- ...(router.autorouting_enabled === false || router.routing_listed === false ? [] : [codexCatalogEntry({
78
- slug: CANONICAL_ROUTER_MODEL,
79
- displayName: "Dari Routing",
80
- description: "Routes Codex HTTP Responses requests through the configured Dari model router.",
81
- priority: 0,
82
- contextWindow: codexRouterContextWindow(router),
83
- hostedWebSearch: codexRouterSupportsHostedWebSearch(router),
84
- imageInput: router.enabled_models.some(imageInputFor),
85
- })]),
86
- ...router.enabled_models.map((model, index) => codexCatalogEntry({
87
- slug: explicitModelSlug(model),
88
- displayName: model,
89
- description: `Serves ${model} directly, without routing.`,
90
- priority: index + 1,
91
- contextWindow: codexRouterContextWindow({ ...router, enabled_models: [model] }),
92
- hostedWebSearch: codexRouterSupportsHostedWebSearch({ ...router, enabled_models: [model] }),
93
- imageInput: imageInputFor(model),
94
- reasoningLevels: router.model_configs?.[model]?.supported_thinking_levels
95
- ?.map((effort) => effort === "off" ? "none" : effort),
96
- defaultReasoningLevel: router.model_configs?.[model]?.default_thinking_level === "off"
97
- ? "none" : router.model_configs?.[model]?.default_thinking_level,
98
- })),
99
- ],
96
+ ...(direct ? { codex_direct: true } : {}),
97
+ models: direct ? models.map(codexReadable) : models,
100
98
  };
101
99
  }
100
+ /* A version of the list Codex's /model menu shows: it changes when a model
101
+ is added or removed, or dari/routing comes or goes. Sent as
102
+ `X-Models-Etag` on the catalog and on Codex's responses, it makes a running
103
+ Codex re-read the catalog after the first turn that sees a new value,
104
+ instead of on its next timed refresh. Codex reads it only from a successful
105
+ response; a refused stale pick carries the menu hint instead. */
106
+ export function codexModelsEtag(router) {
107
+ const slugs = codexCatalogEntries(router, () => false).map((entry) => entry.slug);
108
+ return createHash("sha256").update(slugs.join("\n")).digest("hex").slice(0, 16);
109
+ }
110
+ function codexCatalogEntries(router, imageInputFor) {
111
+ return [
112
+ ...(router.autorouting_enabled === false || router.routing_listed === false ? [] : [codexCatalogEntry({
113
+ slug: CANONICAL_ROUTER_MODEL,
114
+ displayName: "Dari Routing",
115
+ description: "Routes Codex HTTP Responses requests through the configured Dari model router.",
116
+ priority: 0,
117
+ contextWindow: codexRouterContextWindow(router),
118
+ hostedWebSearch: codexRouterSupportsHostedWebSearch(router),
119
+ imageInput: router.enabled_models.some(imageInputFor),
120
+ })]),
121
+ ...router.enabled_models.map((model, index) => codexCatalogEntry({
122
+ slug: explicitModelSlug(model),
123
+ displayName: model,
124
+ description: `Serves ${model} directly, without routing.`,
125
+ priority: index + 1,
126
+ contextWindow: codexRouterContextWindow({ ...router, enabled_models: [model] }),
127
+ hostedWebSearch: codexRouterSupportsHostedWebSearch({ ...router, enabled_models: [model] }),
128
+ imageInput: imageInputFor(model),
129
+ reasoningLevels: router.model_configs?.[model]?.supported_thinking_levels
130
+ ?.map((effort) => effort === "off" ? "none" : effort),
131
+ defaultReasoningLevel: router.model_configs?.[model]?.default_thinking_level === "off"
132
+ ? "none" : router.model_configs?.[model]?.default_thinking_level,
133
+ })),
134
+ ];
135
+ }
@@ -16,7 +16,7 @@ import { modelMetadataLookup } from "../providers/pi.js";
16
16
  import { resolveRouter } from "../strategies/routing.js";
17
17
  import { anthropicModelsResponse } from "./anthropic_models.js";
18
18
  import { namedClientHarness } from "./client_harness.js";
19
- import { codexModelsResponse } from "./codex_models.js";
19
+ import { codexModelsEtag, codexModelsResponse } from "./codex_models.js";
20
20
  import { CANONICAL_ROUTER_MODEL, explicitModelSlug, LINK_CHILD_TOKEN_PREFIX } from "../protocol/input/router_model.js";
21
21
  export async function handleModels(request, routerId) {
22
22
  // Anthropic SDK clients always send anthropic-version, and API-key probes
@@ -30,7 +30,12 @@ export async function handleModels(request, routerId) {
30
30
  // when the response body (Anthropic shape) does not depend on it.
31
31
  // A model list is for the agent the Dari CLI names: it changes only what
32
32
  // is listed, and each request is still recognized by its own headers.
33
- const clientHarness = namedClientHarness(request.headers);
33
+ const query = new URL(request.url).searchParams;
34
+ // Codex itself reads this URL as its provider's `model_catalog_url`, and
35
+ // refreshes from it while it runs. It cannot send the CLI's header; it
36
+ // names its own version in the query, as only Codex does.
37
+ const codexDirect = !anthropicClient && query.has("client_version");
38
+ const clientHarness = namedClientHarness(request.headers) ?? (codexDirect ? "codex" : undefined);
34
39
  let router;
35
40
  try {
36
41
  router = await resolveRouter({ routerId, apiKey, ...(clientHarness ? { clientHarness } : {}) });
@@ -43,7 +48,6 @@ export async function handleModels(request, routerId) {
43
48
  }
44
49
  throw error;
45
50
  }
46
- const query = new URL(request.url).searchParams;
47
51
  if (query.get("detail") === "1") {
48
52
  const providers = query.get("provider")?.split(",").map((id) => id.trim()).filter(Boolean);
49
53
  const data = await listModelCatalog({
@@ -68,9 +72,10 @@ export async function handleModels(request, routerId) {
68
72
  const metadataLookup = modelMetadataLookup(router.model_configs);
69
73
  const imageInputFor = (model) => modelSupportsImageInput(metadataLookup(model));
70
74
  const nativeCompactionFor = (model) => modelSupportsNativeCompaction(metadataLookup(model));
71
- return Response.json(codexModelsResponse(router, imageInputFor, nativeCompactionFor), {
75
+ return Response.json(codexModelsResponse(router, imageInputFor, nativeCompactionFor, codexDirect), {
72
76
  headers: {
73
77
  "Cache-Control": "no-store",
78
+ "X-Models-Etag": codexModelsEtag(router),
74
79
  },
75
80
  });
76
81
  }
@@ -0,0 +1,2 @@
1
+ import type { ClientHarness } from "../types.js";
2
+ export declare function withModelMenuHint(error: unknown, clientHarness: ClientHarness | undefined): unknown;
@@ -0,0 +1,13 @@
1
+ import { errorResponseHeaders, HttpError, normalizeError } from "../http/errors.js";
2
+ /* Codex fills its /model menu from the router's model list and keeps the
3
+ copy it read: one read before the router's models changed still offers a
4
+ model the router no longer serves. Codex shows the user this error's
5
+ message, so for Codex the message says how to bring the menu up to date. */
6
+ export function withModelMenuHint(error, clientHarness) {
7
+ if (clientHarness !== "codex")
8
+ return error;
9
+ const { status, message, code, param } = normalizeError(error);
10
+ if (code !== "model_not_enabled")
11
+ return error;
12
+ return new HttpError(status, `${message} Codex's /model list may be out of date: run \`dari setup codex --refresh\`.`, code, param, errorResponseHeaders(error), error instanceof HttpError ? error.body : undefined);
13
+ }
@@ -1,6 +1,6 @@
1
1
  import { type InteractionRequest } from "../interaction/types.js";
2
2
  import type { SelectorBackend } from "../strategies/routing.js";
3
- import type { ClientHarness } from "../types.js";
3
+ import type { ClientHarness, ResolvedRouter } from "../types.js";
4
4
  import type { HarnessConversationIdentity } from "./harness_identity/index.js";
5
5
  import type { RoutedProtocol } from "./routed_protocol.js";
6
6
  export declare function handleRoutedCompletion(args: {
@@ -14,4 +14,5 @@ export declare function handleRoutedCompletion(args: {
14
14
  selectorBackend: SelectorBackend;
15
15
  clientHarness?: ClientHarness;
16
16
  harnessConversationIdentity?: HarnessConversationIdentity;
17
+ responseHeaders?: (router: ResolvedRouter) => Record<string, string>;
17
18
  }): Promise<Response>;
@@ -3,6 +3,7 @@ import { isBackgroundRequest } from "../interaction/types.js";
3
3
  import { explicitModelId } from "../protocol/input/router_model.js";
4
4
  import { captureRequestError } from "../observability/errors.js";
5
5
  import { assertAutoroutingAllowed, assertCreditAvailableBeforeRouting, routerSelectsModels } from "../telemetry/usage.js";
6
+ import { withModelMenuHint } from "./model_menu_hint.js";
6
7
  import { prepareRoutedCompletion } from "./prepare_routed_completion.js";
7
8
  import { runPreparedRoutedCompletion } from "./routed_runtime.js";
8
9
  export async function handleRoutedCompletion(args) {
@@ -24,7 +25,7 @@ export async function handleRoutedCompletion(args) {
24
25
  harnessConversationIdentity: args.harnessConversationIdentity,
25
26
  }).catch((error) => ({ error }));
26
27
  if ("error" in prepared) {
27
- const response = args.errorResponse(prepared.error);
28
+ const response = args.errorResponse(withModelMenuHint(prepared.error, args.clientHarness));
28
29
  captureRequestError(prepared.error, {
29
30
  request: args.request,
30
31
  routerId: args.routerId,
@@ -48,12 +49,15 @@ export async function handleRoutedCompletion(args) {
48
49
  selectorBackend: args.selectorBackend,
49
50
  clientSignal: args.request.signal,
50
51
  });
52
+ for (const [name, value] of Object.entries(args.responseHeaders?.(prepared.credentials) ?? {})) {
53
+ response.headers.set(name, value);
54
+ }
51
55
  return responseWithRequestId(response, requestId);
52
56
  }
53
57
  catch (error) {
54
58
  const terminal = prepared.reporter.freezeFailure(error);
55
59
  terminal.report();
56
- let response = args.errorResponse(error);
60
+ let response = args.errorResponse(withModelMenuHint(error, args.clientHarness));
57
61
  // Provider retries may already have consumed tokens before the HTTP error.
58
62
  // Return the same model-only cost as successful OpenAI-compatible responses.
59
63
  if (args.payload.sourceProtocol === "openai_chat") {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mupt-ai/dari-gateway",
3
- "version": "1.0.338",
3
+ "version": "1.0.339",
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.338",
55
+ "@mupt-ai/dari-router": "1.0.339",
56
56
  "@mupt-ai/pi-ai": "1.5.2-mupt.3"
57
57
  },
58
58
  "devDependencies": {
@@ -6,6 +6,7 @@ import { openAIResponsesResponse } from "../protocol/output/openai_responses.js"
6
6
  import { openAIResponsesSseStream } from "../protocol/output/openai_responses_stream.js";
7
7
  import { openAIResponsesToInteraction } from "../protocol/input/openai_responses.js";
8
8
  import { claimedClientHarness } from "./client_harness.js";
9
+ import { codexModelsEtag } from "./codex_models.js";
9
10
  import { parseJsonRequest } from "./json.js";
10
11
  import { museCodeClientId } from "./muse_code.js";
11
12
  import { handleRoutedCompletion } from "../runtime/routed_completion.js";
@@ -53,6 +54,11 @@ export async function handleResponses(
53
54
  }
54
55
  const harnessConversationIdentity = codexIdentity
55
56
  ?? (museClientId === undefined ? undefined : museCodeConversationIdentity(request.headers));
57
+ const clientHarness = museClientId !== undefined ? "muse_code"
58
+ // Codex describes every request in its turn metadata.
59
+ : codexContext !== undefined ? "codex"
60
+ : piContext !== undefined ? "pi"
61
+ : claimedClientHarness(request.headers);
56
62
  return await handleRoutedCompletion({
57
63
  request,
58
64
  routerId,
@@ -62,12 +68,12 @@ export async function handleResponses(
62
68
  streamBody: openAIResponsesSseStream,
63
69
  errorResponse,
64
70
  selectorBackend,
65
- clientHarness: museClientId !== undefined ? "muse_code"
66
- // Codex describes every request in its turn metadata.
67
- : codexContext !== undefined ? "codex"
68
- : piContext !== undefined ? "pi"
69
- : claimedClientHarness(request.headers),
71
+ clientHarness,
70
72
  harnessConversationIdentity,
73
+ // A running Codex re-reads its /model list when this changes.
74
+ ...(clientHarness === "codex"
75
+ ? { responseHeaders: (router) => ({ "X-Models-Etag": codexModelsEtag(router) }) }
76
+ : {}),
71
77
  });
72
78
  } catch (error) {
73
79
  const response = errorResponse(error);
@@ -1,3 +1,5 @@
1
+ import { createHash } from "node:crypto";
2
+
1
3
  import type { ResolvedRouter } from "../types.js";
2
4
  import { CANONICAL_ROUTER_MODEL, explicitModelSlug } from "../protocol/input/router_model.js";
3
5
  import { effectiveContextWindow } from "../models/context_limits.js";
@@ -85,44 +87,86 @@ function codexCatalogEntry(args: CodexCatalogEntry): Record<string, unknown> {
85
87
  };
86
88
  }
87
89
 
90
+ /* What Codex needs to parse an entry it fetched itself: it rejects the whole
91
+ catalog over a null web-search type, leaving /model empty, so the entry
92
+ names one, and the two nullable fields it may not accept as null are left
93
+ out. The `dari` launchers make the same changes to the catalog they hand
94
+ Codex; they read the nulls first to decide whether to turn web search off. */
95
+ function codexReadable(entry: Record<string, unknown>): Record<string, unknown> {
96
+ const { tool_mode, multi_agent_version, ...rest } = entry;
97
+ return {
98
+ ...rest,
99
+ web_search_tool_type: entry.web_search_tool_type ?? "text",
100
+ ...(tool_mode === null ? {} : { tool_mode }),
101
+ ...(multi_agent_version === null ? {} : { multi_agent_version }),
102
+ };
103
+ }
104
+
88
105
  /* `dari/routing` comes first while the router may autoroute (the Codex
89
106
  launcher patches it); each enabled model follows as `dari/model/<id>` so
90
107
  Codex's /model menu can switch to it. The `dari` launchers build every
91
108
  agent's model menu from this list. `remote_compaction` tells the
92
- launcher which Codex provider compaction protocol the router accepts. */
109
+ launcher which Codex provider compaction protocol the router accepts.
110
+ `direct` is a catalog for Codex's own fetch (its `model_catalog_url`),
111
+ which nothing patches on the way: `codex_direct` tells `dari setup codex`
112
+ that this gateway serves one, so it can point Codex at the URL instead of
113
+ a snapshot that goes stale when the router's models change. */
93
114
  export function codexModelsResponse(
94
115
  router: Pick<ResolvedRouter, "enabled_models" | "model_configs" | "allow_long_context" | "autorouting_enabled" | "routing_listed" | "native_compaction">,
95
116
  imageInputFor: (model: string) => boolean,
96
117
  nativeCompactionFor: (model: string) => boolean = () => false,
118
+ direct = false,
97
119
  ): Record<string, unknown> {
98
120
  const remoteCompaction = router.native_compaction === true && router.enabled_models.some(nativeCompactionFor);
121
+ const models = codexCatalogEntries(router, imageInputFor);
99
122
  return {
100
123
  remote_compaction: remoteCompaction ? "v2" : "unsupported",
101
- models: [
102
- ...(router.autorouting_enabled === false || router.routing_listed === false ? [] : [codexCatalogEntry({
103
- slug: CANONICAL_ROUTER_MODEL,
104
- displayName: "Dari Routing",
105
- description: "Routes Codex HTTP Responses requests through the configured Dari model router.",
106
- priority: 0,
107
- contextWindow: codexRouterContextWindow(router),
108
- hostedWebSearch: codexRouterSupportsHostedWebSearch(router),
109
- imageInput: router.enabled_models.some(imageInputFor),
110
- })]),
111
- ...router.enabled_models.map((model, index) =>
112
- codexCatalogEntry({
113
- slug: explicitModelSlug(model),
114
- displayName: model,
115
- description: `Serves ${model} directly, without routing.`,
116
- priority: index + 1,
117
- contextWindow: codexRouterContextWindow({ ...router, enabled_models: [model] }),
118
- hostedWebSearch: codexRouterSupportsHostedWebSearch({ ...router, enabled_models: [model] }),
119
- imageInput: imageInputFor(model),
120
- reasoningLevels: router.model_configs?.[model]?.supported_thinking_levels
121
- ?.map((effort) => effort === "off" ? "none" : effort),
122
- defaultReasoningLevel: router.model_configs?.[model]?.default_thinking_level === "off"
123
- ? "none" : router.model_configs?.[model]?.default_thinking_level,
124
- })
125
- ),
126
- ],
124
+ ...(direct ? { codex_direct: true } : {}),
125
+ models: direct ? models.map(codexReadable) : models,
127
126
  };
128
127
  }
128
+
129
+ /* A version of the list Codex's /model menu shows: it changes when a model
130
+ is added or removed, or dari/routing comes or goes. Sent as
131
+ `X-Models-Etag` on the catalog and on Codex's responses, it makes a running
132
+ Codex re-read the catalog after the first turn that sees a new value,
133
+ instead of on its next timed refresh. Codex reads it only from a successful
134
+ response; a refused stale pick carries the menu hint instead. */
135
+ export function codexModelsEtag(
136
+ router: Pick<ResolvedRouter, "enabled_models" | "model_configs" | "allow_long_context" | "autorouting_enabled" | "routing_listed">,
137
+ ): string {
138
+ const slugs = codexCatalogEntries(router, () => false).map((entry) => entry.slug);
139
+ return createHash("sha256").update(slugs.join("\n")).digest("hex").slice(0, 16);
140
+ }
141
+
142
+ function codexCatalogEntries(
143
+ router: Pick<ResolvedRouter, "enabled_models" | "model_configs" | "allow_long_context" | "autorouting_enabled" | "routing_listed">,
144
+ imageInputFor: (model: string) => boolean,
145
+ ): Record<string, unknown>[] {
146
+ return [
147
+ ...(router.autorouting_enabled === false || router.routing_listed === false ? [] : [codexCatalogEntry({
148
+ slug: CANONICAL_ROUTER_MODEL,
149
+ displayName: "Dari Routing",
150
+ description: "Routes Codex HTTP Responses requests through the configured Dari model router.",
151
+ priority: 0,
152
+ contextWindow: codexRouterContextWindow(router),
153
+ hostedWebSearch: codexRouterSupportsHostedWebSearch(router),
154
+ imageInput: router.enabled_models.some(imageInputFor),
155
+ })]),
156
+ ...router.enabled_models.map((model, index) =>
157
+ codexCatalogEntry({
158
+ slug: explicitModelSlug(model),
159
+ displayName: model,
160
+ description: `Serves ${model} directly, without routing.`,
161
+ priority: index + 1,
162
+ contextWindow: codexRouterContextWindow({ ...router, enabled_models: [model] }),
163
+ hostedWebSearch: codexRouterSupportsHostedWebSearch({ ...router, enabled_models: [model] }),
164
+ imageInput: imageInputFor(model),
165
+ reasoningLevels: router.model_configs?.[model]?.supported_thinking_levels
166
+ ?.map((effort) => effort === "off" ? "none" : effort),
167
+ defaultReasoningLevel: router.model_configs?.[model]?.default_thinking_level === "off"
168
+ ? "none" : router.model_configs?.[model]?.default_thinking_level,
169
+ })
170
+ ),
171
+ ];
172
+ }
@@ -17,7 +17,7 @@ import { modelMetadataLookup } from "../providers/pi.js";
17
17
  import { resolveRouter } from "../strategies/routing.js";
18
18
  import { anthropicModelsResponse } from "./anthropic_models.js";
19
19
  import { namedClientHarness } from "./client_harness.js";
20
- import { codexModelsResponse } from "./codex_models.js";
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
22
 
23
23
  export async function handleModels(request: Request, routerId: string): Promise<Response> {
@@ -33,7 +33,12 @@ export async function handleModels(request: Request, routerId: string): Promise<
33
33
  // when the response body (Anthropic shape) does not depend on it.
34
34
  // A model list is for the agent the Dari CLI names: it changes only what
35
35
  // is listed, and each request is still recognized by its own headers.
36
- const clientHarness = namedClientHarness(request.headers);
36
+ const query = new URL(request.url).searchParams;
37
+ // Codex itself reads this URL as its provider's `model_catalog_url`, and
38
+ // refreshes from it while it runs. It cannot send the CLI's header; it
39
+ // names its own version in the query, as only Codex does.
40
+ const codexDirect = !anthropicClient && query.has("client_version");
41
+ const clientHarness = namedClientHarness(request.headers) ?? (codexDirect ? "codex" : undefined);
37
42
  let router;
38
43
  try {
39
44
  router = await resolveRouter({ routerId, apiKey, ...(clientHarness ? { clientHarness } : {}) });
@@ -45,7 +50,6 @@ export async function handleModels(request: Request, routerId: string): Promise<
45
50
  }
46
51
  throw error;
47
52
  }
48
- const query = new URL(request.url).searchParams;
49
53
  if (query.get("detail") === "1") {
50
54
  const providers = query.get("provider")?.split(",").map((id) => id.trim()).filter(Boolean);
51
55
  const data = await listModelCatalog({
@@ -70,9 +74,10 @@ export async function handleModels(request: Request, routerId: string): Promise<
70
74
  const metadataLookup = modelMetadataLookup(router.model_configs);
71
75
  const imageInputFor = (model: string) => modelSupportsImageInput(metadataLookup(model));
72
76
  const nativeCompactionFor = (model: string) => modelSupportsNativeCompaction(metadataLookup(model));
73
- return Response.json(codexModelsResponse(router, imageInputFor, nativeCompactionFor), {
77
+ return Response.json(codexModelsResponse(router, imageInputFor, nativeCompactionFor, codexDirect), {
74
78
  headers: {
75
79
  "Cache-Control": "no-store",
80
+ "X-Models-Etag": codexModelsEtag(router),
76
81
  },
77
82
  });
78
83
  } catch (error) {
@@ -0,0 +1,20 @@
1
+ import { errorResponseHeaders, HttpError, normalizeError } from "../http/errors.js";
2
+ import type { ClientHarness } from "../types.js";
3
+
4
+ /* Codex fills its /model menu from the router's model list and keeps the
5
+ copy it read: one read before the router's models changed still offers a
6
+ model the router no longer serves. Codex shows the user this error's
7
+ message, so for Codex the message says how to bring the menu up to date. */
8
+ export function withModelMenuHint(error: unknown, clientHarness: ClientHarness | undefined): unknown {
9
+ if (clientHarness !== "codex") return error;
10
+ const { status, message, code, param } = normalizeError(error);
11
+ if (code !== "model_not_enabled") return error;
12
+ return new HttpError(
13
+ status,
14
+ `${message} Codex's /model list may be out of date: run \`dari setup codex --refresh\`.`,
15
+ code,
16
+ param,
17
+ errorResponseHeaders(error),
18
+ error instanceof HttpError ? error.body : undefined,
19
+ );
20
+ }
@@ -4,10 +4,11 @@ import { isBackgroundRequest, type InteractionRequest } from "../interaction/typ
4
4
  import { explicitModelId } from "../protocol/input/router_model.js";
5
5
  import { captureRequestError } from "../observability/errors.js";
6
6
  import type { SelectorBackend } from "../strategies/routing.js";
7
- import type { ClientHarness } from "../types.js";
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 { withModelMenuHint } from "./model_menu_hint.js";
11
12
  import { prepareRoutedCompletion } from "./prepare_routed_completion.js";
12
13
  import type { RoutedProtocol } from "./routed_protocol.js";
13
14
  import { runPreparedRoutedCompletion } from "./routed_runtime.js";
@@ -23,6 +24,8 @@ export async function handleRoutedCompletion(args: {
23
24
  selectorBackend: SelectorBackend;
24
25
  clientHarness?: ClientHarness;
25
26
  harnessConversationIdentity?: HarnessConversationIdentity;
27
+ // Headers the client reads from a successful response, from its router.
28
+ responseHeaders?: (router: ResolvedRouter) => Record<string, string>;
26
29
  }): Promise<Response> {
27
30
  const requestId = randomUUID();
28
31
  const clientRequestId = normalizedClientRequestId(args.request.headers.get("x-request-id"));
@@ -42,7 +45,7 @@ export async function handleRoutedCompletion(args: {
42
45
  harnessConversationIdentity: args.harnessConversationIdentity,
43
46
  }).catch((error: unknown) => ({ error }));
44
47
  if ("error" in prepared) {
45
- const response = args.errorResponse(prepared.error);
48
+ const response = args.errorResponse(withModelMenuHint(prepared.error, args.clientHarness));
46
49
  captureRequestError(prepared.error, {
47
50
  request: args.request,
48
51
  routerId: args.routerId,
@@ -68,11 +71,14 @@ export async function handleRoutedCompletion(args: {
68
71
  selectorBackend: args.selectorBackend,
69
72
  clientSignal: args.request.signal,
70
73
  });
74
+ for (const [name, value] of Object.entries(args.responseHeaders?.(prepared.credentials) ?? {})) {
75
+ response.headers.set(name, value);
76
+ }
71
77
  return responseWithRequestId(response, requestId);
72
78
  } catch (error) {
73
79
  const terminal = prepared.reporter.freezeFailure(error);
74
80
  terminal.report();
75
- let response = args.errorResponse(error);
81
+ let response = args.errorResponse(withModelMenuHint(error, args.clientHarness));
76
82
  // Provider retries may already have consumed tokens before the HTTP error.
77
83
  // Return the same model-only cost as successful OpenAI-compatible responses.
78
84
  if (args.payload.sourceProtocol === "openai_chat") {