dsh-lcx-codex 0.6.0-pre.1 → 0.6.0-pre.2

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.
package/lib/index.js CHANGED
@@ -15,8 +15,10 @@ import { fetchJsonWithRetry } from "./transport.js";
15
15
  import { DEFAULT_TOOL_UPDATES, planToolSurface, withoutDeferLoading } from "./tool-surface.js";
16
16
  import { agentSessionId, agentUsesSession, compactionConfigState, compactionPatchCandidate, installCompactionPatch, patchCompactionConfig, patchToolResultPruner, readAgentRouteState, readSelectedAgentRouteState, recordAgentRouteEvent, resolveAgentService, resolveContextService, resolveScopedService, restoreCompactionConfig, restoreCompactionPatches, restoreToolResultPruner, sessionFor, sessionFromAgent, scopedToolRuntime, onScopedToolExecute, tokenMeterTotal, toolResultPrunerState, } from "./dsh-compat.js";
17
17
  import { InvocationPolicyScope } from "./invocation-policy-scope.js";
18
- import { authenticatedGrokHeaders, authenticatedHeaders, currentRoute, generationControlsFromSession, grokPromptCacheSessionId, promptCacheKey, promptCacheRetention, promptCacheSessionId, resolveGrokResponsesRouteConfig, resolveResponsesRouteConfig, routeFingerprint, } from "./route.js";
19
- import { DEFAULT_MAX_REQUEST_IMAGE_BYTES, DEFAULT_REQUEST_IMAGE_PIXEL_BUDGET, DEFAULT_REQUEST_IMAGE_MAX_BYTES, assertAggregateImageBudget, hydrateNativeImageReferences, inputImageBase64Lengths, resolveRouteModelFacts, hasMidHistoryPromptSnapshot, responseInputItems, serializeDshMessages, } from "./dsh-responses.js";
18
+ import { providerDynamicHeaders } from "./provider-headers.js";
19
+ import { resolveCatalogModel } from "./model-catalog.js";
20
+ import { authenticatedGrokHeaders, authenticatedHeaders, currentRoute, generationControlsFromSession, grokPromptCacheSessionId, promptCacheKey, promptCacheRetention, promptCacheSessionId, resolveGrokResponsesRouteConfig, diagnoseResponsesRoute, markHostRecognizedModel, warmHostRecognizedModels, resolveResponsesRouteConfig, routeFingerprint, } from "./route.js";
21
+ import { DEFAULT_MAX_REQUEST_IMAGE_BYTES, DEFAULT_REQUEST_IMAGE_PIXEL_BUDGET, DEFAULT_REQUEST_IMAGE_MAX_BYTES, assertAggregateImageBudget, hydrateNativeImageReferences, inputImageBase64Lengths, resolveRouteModelFacts, routeModelOverride, hasMidHistoryPromptSnapshot, responseInputItems, serializeDshMessages, } from "./dsh-responses.js";
20
22
  import { mergeFeatureHeader, requestNativeCompaction } from "./compact-v2.js";
21
23
  import { buildResponsesBody } from "./responses-request.js";
22
24
  import { managedFailureChunk, streamResponsesRequest, } from "./responses-stream.js";
@@ -28,6 +30,7 @@ import { AlphaCapabilityStore, alphaCapabilityFingerprint, alphaCapabilityUsable
28
30
  import { AlphaRefStore } from "./web-search-ref-store.js";
29
31
  import { ServiceMutex } from "./service-mutex.js";
30
32
  import { GROK_NATIVE_SERVER_TOOL_TYPES, grokNativeSearchEnabled, grokVisibleFunctionTools, isGrokNativeServerToolItem, grokWireTools, restoreGrokNativeReplay, } from "./grok-native-search.js";
33
+ import { DEFAULTS } from "./defaults.js";
31
34
  export const name = "lcx-codex";
32
35
  export const inject = ["llm", "web", "sessions", "tools", "settings", "credentials", "attachments", "fs"];
33
36
  const ADVANCED_HOSTED_TOOL = "websearch_gpt_advanced";
@@ -72,9 +75,6 @@ function grokReplayRoute(route, config) {
72
75
  function isRecord(value) {
73
76
  return value !== null && typeof value === "object";
74
77
  }
75
- function asAbortSignal(value) {
76
- return value instanceof AbortSignal ? value : undefined;
77
- }
78
78
  function errorDetails(value) {
79
79
  return isRecord(value)
80
80
  ? {
@@ -109,21 +109,21 @@ export const Config = z.object({
109
109
  alphaRefPath: z.string().default(""),
110
110
  alphaProfile: z.string().default(""),
111
111
  alphaGroup: z.string().default(""),
112
- alphaMaxOutputTokens: z.number().default(2500),
113
- webSearchProvider: z.string().default("lcx-responses"),
114
- webMaxResults: z.number().default(8),
115
- timeoutMs: z.number().default(300000),
116
- maxResponseBytes: z.number().default(8 * 1024 * 1024),
117
- maxAttempts: z.number().default(3),
112
+ alphaMaxOutputTokens: z.number().default(DEFAULTS.alphaMaxOutputTokens),
113
+ webSearchProvider: z.string().default(DEFAULTS.webSearchProvider),
114
+ webMaxResults: z.number().default(DEFAULTS.webMaxResults),
115
+ timeoutMs: z.number().default(DEFAULTS.requestTimeoutMs),
116
+ maxResponseBytes: z.number().default(DEFAULTS.maxResponseBytes),
117
+ maxAttempts: z.number().default(DEFAULTS.maxAttempts),
118
118
  maxRequestImageBytes: z.number().default(DEFAULT_MAX_REQUEST_IMAGE_BYTES),
119
119
  requestImagePixelBudget: z
120
120
  .number()
121
121
  .default(DEFAULT_REQUEST_IMAGE_PIXEL_BUDGET),
122
122
  requestImageMaxBytes: z.number().default(DEFAULT_REQUEST_IMAGE_MAX_BYTES),
123
- portableReplayMaxChars: z.number().default(80_000),
124
- nativeRetentionTokenBudget: z.number().default(64_000),
125
- assistantRetentionTokenReserve: z.number().default(24_000),
126
- assistantRetentionPerMessageTokenCap: z.number().default(3_000),
123
+ portableReplayMaxChars: z.number().default(DEFAULTS.portableReplayMaxChars),
124
+ nativeRetentionTokenBudget: z.number().default(DEFAULTS.nativeRetentionTokenBudget),
125
+ assistantRetentionTokenReserve: z.number().default(DEFAULTS.assistantRetentionTokenReserve),
126
+ assistantRetentionPerMessageTokenCap: z.number().default(DEFAULTS.assistantRetentionPerMessageTokenCap),
127
127
  });
128
128
  function normalizeConfig(input = {}) {
129
129
  return {
@@ -133,23 +133,23 @@ function normalizeConfig(input = {}) {
133
133
  alphaRefPath: stringValue(input.alphaRefPath, defaultAlphaRefPath()),
134
134
  alphaProfile: String(input.alphaProfile ?? ""),
135
135
  alphaGroup: String(input.alphaGroup ?? ""),
136
- alphaMaxOutputTokens: positiveInteger(input.alphaMaxOutputTokens, 2500, 32_000),
137
- webSearchProvider: stringValue(input.webSearchProvider, "lcx-responses"),
138
- webMaxResults: positiveInteger(input.webMaxResults, 8),
139
- timeoutMs: positiveInteger(input.timeoutMs, 300000),
140
- maxResponseBytes: positiveInteger(input.maxResponseBytes, 8 * 1024 * 1024),
141
- maxAttempts: positiveInteger(input.maxAttempts, 3, 6),
136
+ alphaMaxOutputTokens: positiveInteger(input.alphaMaxOutputTokens, DEFAULTS.alphaMaxOutputTokens, DEFAULTS.alphaMaxOutputTokensCap),
137
+ webSearchProvider: stringValue(input.webSearchProvider, DEFAULTS.webSearchProvider),
138
+ webMaxResults: positiveInteger(input.webMaxResults, DEFAULTS.webMaxResults),
139
+ timeoutMs: positiveInteger(input.timeoutMs, DEFAULTS.requestTimeoutMs),
140
+ maxResponseBytes: positiveInteger(input.maxResponseBytes, DEFAULTS.maxResponseBytes),
141
+ maxAttempts: positiveInteger(input.maxAttempts, DEFAULTS.maxAttempts, DEFAULTS.maxAttemptsCap),
142
142
  maxRequestImageBytes: positiveInteger(input.maxRequestImageBytes, DEFAULT_MAX_REQUEST_IMAGE_BYTES),
143
143
  requestImagePixelBudget: positiveInteger(input.requestImagePixelBudget, DEFAULT_REQUEST_IMAGE_PIXEL_BUDGET),
144
144
  requestImageMaxBytes: positiveInteger(input.requestImageMaxBytes, DEFAULT_REQUEST_IMAGE_MAX_BYTES),
145
- portableReplayMaxChars: positiveInteger(input.portableReplayMaxChars, 80_000),
146
- nativeRetentionTokenBudget: positiveInteger(input.nativeRetentionTokenBudget, 64_000),
145
+ portableReplayMaxChars: positiveInteger(input.portableReplayMaxChars, DEFAULTS.portableReplayMaxChars),
146
+ nativeRetentionTokenBudget: positiveInteger(input.nativeRetentionTokenBudget, DEFAULTS.nativeRetentionTokenBudget),
147
147
  assistantRetentionTokenReserve: typeof input.assistantRetentionTokenReserve === "number" &&
148
148
  Number.isSafeInteger(input.assistantRetentionTokenReserve) &&
149
149
  input.assistantRetentionTokenReserve >= 0
150
150
  ? input.assistantRetentionTokenReserve
151
- : 24_000,
152
- assistantRetentionPerMessageTokenCap: positiveInteger(input.assistantRetentionPerMessageTokenCap, 3_000),
151
+ : DEFAULTS.assistantRetentionTokenReserve,
152
+ assistantRetentionPerMessageTokenCap: positiveInteger(input.assistantRetentionPerMessageTokenCap, DEFAULTS.assistantRetentionPerMessageTokenCap),
153
153
  toolUpdates: DEFAULT_TOOL_UPDATES,
154
154
  };
155
155
  }
@@ -227,7 +227,8 @@ class LcxResponsesSearchProvider {
227
227
  if (!active)
228
228
  return false;
229
229
  const config = this.getConfig();
230
- const route = resolveResponsesRouteConfig(this.ctx, active, config);
230
+ // Tool-assembly question, answered before DSH can be asked: see `assumeHostServes` in route.ts.
231
+ const route = resolveResponsesRouteConfig(this.ctx, active, config, true);
231
232
  return this.enabled() && Boolean(route);
232
233
  }
233
234
  async search(request, signal) {
@@ -321,7 +322,9 @@ function disposeGptToolsForAgent(agent, registrations) {
321
322
  function syncGptToolsForAgent(ctx, agent, state, getConfig, provider, registrations) {
322
323
  const config = getConfig();
323
324
  const active = selectedAgentRoute(agent);
324
- const route = resolveResponsesRouteConfig(ctx, active, config);
325
+ // Registering the tools cannot wait for DSH's answer about a model only its own catalog knows: the optimistic
326
+ // answer is exact (see `assumeHostServes` in route.ts), and the stream awaits DSH before LCX takes the request.
327
+ const route = resolveResponsesRouteConfig(ctx, active, config, true);
325
328
  const webSearch = state.enabled && state.webSearch && Boolean(route);
326
329
  const advanced = webSearch && state.advancedHostedSearch;
327
330
  if (!webSearch && !advanced) {
@@ -574,19 +577,6 @@ function locateSupersededItems(original, restored, positions) {
574
577
  }
575
578
  return located;
576
579
  }
577
- /**
578
- * The reasoning projection a GPT route serializes and sends with. A profile's declared
579
- * `reasoningEfforts` wins (wire mapping, or `false` for a non-reasoning model); otherwise the catalog
580
- * entry stands, and a model with no catalog entry follows what DSH itself resolved for it instead of
581
- * being assumed to reason.
582
- */
583
- function gptModelOverride(routeConfig, facts) {
584
- if (routeConfig.modelControls !== undefined)
585
- return { ...routeConfig.modelControls };
586
- if (!facts.resolved)
587
- return undefined;
588
- return { reasoning: facts.reasoning !== undefined };
589
- }
590
580
  /** Refuse an effort DSH does not offer for this model, the way the DSH adapter and the Grok route do. */
591
581
  function assertSupportedReasoningEffort(effort, facts) {
592
582
  if (effort === undefined || !facts.resolved)
@@ -604,7 +594,7 @@ const reportedToolSurfaceFallbacks = new Set();
604
594
  */
605
595
  function reportToolSurfaceFallback(ctx, route, surface) {
606
596
  const reason = surface.fallbackReason ?? "unknown";
607
- const key = `${route.sessionId}${reason}`;
597
+ const key = `${route.sessionId}\u001f${reason}`;
608
598
  if (reportedToolSurfaceFallbacks.has(key))
609
599
  return;
610
600
  if (reportedToolSurfaceFallbacks.size >= 256)
@@ -616,16 +606,33 @@ function reportToolSurfaceFallback(ctx, route, surface) {
616
606
  else
617
607
  ctx.logger?.debug?.(message);
618
608
  }
609
+ const reportedCatalogGaps = new Set();
610
+ /**
611
+ * Say once per route model that LCX's bundled Pi catalog does not describe it, so its wire capabilities
612
+ * (strict tools, grammar tools, cache mode) come from the profile and from what DSH declares instead.
613
+ */
614
+ function reportCatalogGap(ctx, route) {
615
+ const source = resolveCatalogModel(route.provider, route.model, true).source;
616
+ if (source !== "catalog-provider-default")
617
+ return;
618
+ const key = `${route.provider}/${route.model}`;
619
+ if (reportedCatalogGaps.has(key))
620
+ return;
621
+ if (reportedCatalogGaps.size >= 256)
622
+ reportedCatalogGaps.clear();
623
+ reportedCatalogGaps.add(key);
624
+ ctx.logger?.debug?.(`[lcx-codex] ${key} is not described by LCX's bundled model catalog; its wire capabilities follow the profile and what DSH declares for the model`);
625
+ }
619
626
  async function serializeNativeAware(rawMessages, route, routeConfig, ctx, options) {
620
627
  const session = sessionFor(ctx, route.sessionId);
621
628
  // One adapter-owned lookup supplies image support and the route's system-prompt update mode. On an
622
629
  // "in-history" route DSH appends a changed prompt as a later full system message; it must reach the
623
630
  // model in place with instruction authority instead of being demoted to user context.
624
631
  const modelFacts = await resolveRouteModelFacts(ctx, route, options.signal);
632
+ if (options.grokNativeReplayRoute === undefined)
633
+ reportCatalogGap(ctx, route);
625
634
  const { imageSupport, systemPromptUpdate, resolved } = modelFacts;
626
- const modelOverride = options.grokNativeReplayRoute === undefined
627
- ? gptModelOverride(routeConfig, modelFacts)
628
- : undefined;
635
+ const modelOverride = routeModelOverride(routeConfig, modelFacts, options.grokNativeReplayRoute !== undefined);
629
636
  let messages = rawMessages;
630
637
  let tools = options.tools;
631
638
  let anchoredTools = false;
@@ -797,7 +804,7 @@ async function* remoteCompactionStream(options, routeConfig, ctx, next) {
797
804
  toolSurface: { history: options.toolHistory },
798
805
  });
799
806
  const cacheSessionId = promptCacheSessionId(route, routeConfig, ctx);
800
- const headers = await authenticatedHeaders(ctx, routeConfig, cacheSessionId, cacheSessionId === undefined ? null : route.sessionId);
807
+ const headers = await authenticatedHeaders(ctx, routeConfig, cacheSessionId, cacheSessionId === undefined ? null : route.sessionId, providerDynamicHeaders(routeConfig.provider, options.messages), route.sessionId || undefined);
801
808
  const generation = generationControlsFromSession(sessionFor(ctx, route.sessionId), route);
802
809
  const result = await requestNativeCompaction({
803
810
  baseURL: routeConfig.baseURL,
@@ -1100,7 +1107,7 @@ async function* managedResponsesStream(options, routeConfig, ctx) {
1100
1107
  });
1101
1108
  assertSupportedReasoningEffort(options.reasoningEffort, prepared.modelFacts);
1102
1109
  const cacheSessionId = promptCacheSessionId(route, routeConfig, ctx);
1103
- const headers = await authenticatedHeaders(ctx, routeConfig, cacheSessionId, cacheSessionId === undefined ? null : route.sessionId);
1110
+ const headers = await authenticatedHeaders(ctx, routeConfig, cacheSessionId, cacheSessionId === undefined ? null : route.sessionId, providerDynamicHeaders(routeConfig.provider, options.messages), route.sessionId || undefined);
1104
1111
  const body = buildResponsesBody({
1105
1112
  model: prepared.model,
1106
1113
  input: prepared.input,
@@ -1152,7 +1159,7 @@ async function* managedGrokNativeSearchStream(options, routeConfig, nativeSearch
1152
1159
  grokNativeReplayRoute: nativeReplayRoute,
1153
1160
  });
1154
1161
  const cacheSessionId = grokPromptCacheSessionId(route, routeConfig);
1155
- const headers = await authenticatedGrokHeaders(ctx, routeConfig, cacheSessionId);
1162
+ const headers = await authenticatedGrokHeaders(ctx, routeConfig, cacheSessionId, providerDynamicHeaders(routeConfig.provider, options.messages), route.sessionId || undefined);
1156
1163
  const model = {
1157
1164
  ...prepared.model,
1158
1165
  ...routeConfig.modelDefaults,
@@ -1214,8 +1221,41 @@ async function* managedGrokNativeSearchStream(options, routeConfig, nativeSearch
1214
1221
  function isGptLifecycleTarget(options) {
1215
1222
  return /^gpt-/iu.test(String(options.model ?? ""));
1216
1223
  }
1217
- async function* unavailableManagedRouteStream(options) {
1218
- yield managedFailureChunk(Object.assign(new Error("LCX is enabled but the selected DSH route cannot be resolved as an authenticated OpenAI Responses wire route"), { code: "LCX_RESPONSES_ROUTE_UNAVAILABLE" }), options.signal);
1224
+ async function* unavailableManagedRouteStream(options, diagnosis = "incomplete") {
1225
+ // DSH names no protocol for a model its catalog lacks and the profile sets no `api`: say what to change.
1226
+ const apiUnresolved = diagnosis === "api-unresolved";
1227
+ yield managedFailureChunk(Object.assign(new Error(apiUnresolved
1228
+ ? "LCX could not determine the wire protocol of the selected GPT route: the provider profile sets no api and LCX could not infer one for this model. Add api: openai-responses to the provider profile, or select another model"
1229
+ : "LCX is enabled but the selected DSH route cannot be resolved as an authenticated OpenAI Responses wire route"), { code: apiUnresolved ? "LCX_RESPONSES_API_UNRESOLVED" : "LCX_RESPONSES_ROUTE_UNAVAILABLE" }), options.signal);
1230
+ }
1231
+ /**
1232
+ * Re-resolve a route whose protocol LCX could not infer after asking DSH whether it resolves the exact model.
1233
+ * DSH resolving it counts as the profile declaring it: the provider-wide protocol then applies, as in DSH.
1234
+ */
1235
+ async function* hostRecognizedRouteStream(options, ctx, policy, next) {
1236
+ const facts = await resolveRouteModelFacts(ctx, options, options.signal);
1237
+ if (facts.resolved)
1238
+ markHostRecognizedModel(ctx, options.provider, options.model);
1239
+ const routeConfig = facts.resolved
1240
+ ? resolveResponsesRouteConfig(ctx, options, policy())
1241
+ : undefined;
1242
+ if (!routeConfig) {
1243
+ yield* unavailableManagedRouteStream(options, diagnoseResponsesRoute(ctx, options));
1244
+ return;
1245
+ }
1246
+ yield* options.purpose === "compaction"
1247
+ ? remoteCompactionStream(options, routeWithPolicies(routeConfig, policy()), ctx, next)
1248
+ : managedResponsesStream(options, routeWithPolicies(routeConfig, policy()), ctx);
1249
+ }
1250
+ /** The Grok counterpart of `hostRecognizedRouteStream`: DSH not resolving the model is DSH's to report. */
1251
+ async function* hostRecognizedGrokStream(options, ctx, policy, nativeSearch, next) {
1252
+ const facts = await resolveRouteModelFacts(ctx, options, options.signal);
1253
+ if (facts.resolved)
1254
+ markHostRecognizedModel(ctx, options.provider, options.model);
1255
+ const grokRoute = facts.resolved ? resolveGrokResponsesRouteConfig(ctx, options, policy()) : undefined;
1256
+ yield* grokRoute
1257
+ ? managedGrokNativeSearchStream(options, routeWithPolicies(grokRoute, policy()), nativeSearch, ctx)
1258
+ : next();
1219
1259
  }
1220
1260
  function installInjected(ctx, configInput) {
1221
1261
  installSearchUsage(ctx);
@@ -1276,15 +1316,37 @@ function installInjected(ctx, configInput) {
1276
1316
  : baseConfig;
1277
1317
  refreshTools();
1278
1318
  };
1319
+ /**
1320
+ * Tool ownership is decided synchronously when an agent's tools are assembled, but whether DSH serves a model
1321
+ * that LCX's bundled catalog does not describe is only known by asking DSH. So ask ahead of time, at start and
1322
+ * whenever the provider configuration or the provider set changes, and resynchronise the tools when the
1323
+ * remembered answers change; a first request on such a model then already carries the LCX tools.
1324
+ */
1325
+ const prewarmHostModels = () => {
1326
+ void warmHostRecognizedModels(ctx)
1327
+ .then((changed) => {
1328
+ if (changed)
1329
+ refreshTools();
1330
+ })
1331
+ .catch((error) => ctx.logger?.debug?.(`[lcx-codex] host model prewarm skipped: ${String(error)}`));
1332
+ };
1279
1333
  syncSettings();
1280
- ctx.on("loader/volatile-update", syncSettings);
1281
- ctx.on("settings/document-updated", refreshTools);
1334
+ prewarmHostModels();
1335
+ ctx.on("loader/volatile-update", () => {
1336
+ syncSettings();
1337
+ prewarmHostModels();
1338
+ });
1339
+ ctx.on("settings/document-updated", () => {
1340
+ refreshTools();
1341
+ prewarmHostModels();
1342
+ });
1343
+ ctx.on("llm/adapters-updated", prewarmHostModels);
1282
1344
  ctx.inject(["compaction"], (compactionCtx) => {
1283
1345
  patchCompactionPressureService(resolveContextService(compactionCtx, "compaction"), state, () => runtimeConfig, ctx, compactionPatchRecords);
1284
1346
  });
1285
1347
  /**
1286
1348
  * LCX instrumentation is optional capability, never a creation precondition.
1287
- * DSH 0.1.6 awaits `agent/created` serially, so an escaping failure would make
1349
+ * DSH awaits `agent/created` serially, so an escaping failure would make
1288
1350
  * an otherwise valid Agent uncreatable; `agent/status` stays a contained emit.
1289
1351
  * Both edges therefore fail closed locally: the Agent runs uninstrumented and
1290
1352
  * the reason is logged, rather than propagating into the host lifecycle.
@@ -1301,7 +1363,7 @@ function installInjected(ctx, configInput) {
1301
1363
  ctx.logger?.warn?.(`[lcx-codex] agent instrumentation skipped on ${edge}: ${String(error)}`);
1302
1364
  }
1303
1365
  };
1304
- /** DSH 0.1.6 lifecycle source, recorded for diagnostics only. */
1366
+ /** DSH lifecycle source, recorded for diagnostics only. */
1305
1367
  const startSource = (value) => typeof value === "string" && /^[a-z]+$/u.test(value) ? value : "unknown";
1306
1368
  ctx.on("agent/created", (payload) => {
1307
1369
  const agent = payload?.agent;
@@ -1329,17 +1391,32 @@ function installInjected(ctx, configInput) {
1329
1391
  const grokRoute = resolveGrokResponsesRouteConfig(ctx, options, runtimeConfig);
1330
1392
  if (grokRoute)
1331
1393
  return managedGrokNativeSearchStream(options, routeWithPolicies(grokRoute, runtimeConfig), grokNativeSearch, ctx);
1394
+ // A Grok model only DSH's own catalog may know: ask DSH now, so the first request is not left to a race.
1395
+ if (/^grok/iu.test(String(options.model ?? "")) && diagnoseResponsesRoute(ctx, options) === "api-unresolved")
1396
+ return hostRecognizedGrokStream(options, ctx, () => runtimeConfig, grokNativeSearch, next);
1332
1397
  }
1333
1398
  if (!state.enabled || !isGptLifecycleTarget(options))
1334
1399
  return next();
1335
1400
  const routeConfig = resolveResponsesRouteConfig(ctx, options, runtimeConfig);
1401
+ if (!routeConfig) {
1402
+ const diagnosis = diagnoseResponsesRoute(ctx, options);
1403
+ // DSH owns these calls: a model the provider's models list leaves out (DSH serves only the listed
1404
+ // models and answers UNKNOWN_MODEL, nothing is sent) and a provider whose authentication only Pi's own
1405
+ // client can perform (see HOST_AUTH_PROVIDERS). LCX does not own a route it cannot serve like DSH.
1406
+ if (diagnosis === "model-not-configured" || diagnosis === "host-auth")
1407
+ return next();
1408
+ }
1409
+ // The profile names no api and LCX's catalog does not describe the model: DSH's own catalog may still
1410
+ // resolve it, which only a lookup tells (once per failing request; resolving routes never pay it).
1411
+ if (!routeConfig && diagnoseResponsesRoute(ctx, options) === "api-unresolved")
1412
+ return hostRecognizedRouteStream(options, ctx, () => runtimeConfig, next);
1336
1413
  if (options.purpose === "compaction") {
1337
1414
  if (!routeConfig)
1338
- return unavailableManagedRouteStream(options);
1415
+ return unavailableManagedRouteStream(options, diagnoseResponsesRoute(ctx, options));
1339
1416
  return remoteCompactionStream(options, routeWithPolicies(routeConfig, runtimeConfig), ctx, next);
1340
1417
  }
1341
1418
  if (!routeConfig)
1342
- return unavailableManagedRouteStream(options);
1419
+ return unavailableManagedRouteStream(options, diagnoseResponsesRoute(ctx, options));
1343
1420
  return managedResponsesStream(options, routeWithPolicies(routeConfig, runtimeConfig), ctx);
1344
1421
  });
1345
1422
  ctx.effect?.(() => async () => {
@@ -0,0 +1,46 @@
1
+ import { getCatalogModels } from "./pi-responses-runtime.js";
2
+ const providerDefaultsCache = new Map();
3
+ function sharedValue(values) {
4
+ const distinct = new Set(values);
5
+ const [only] = distinct;
6
+ return distinct.size === 1 && typeof only === "string" && only.length > 0 ? only : undefined;
7
+ }
8
+ function providerDefaults(provider) {
9
+ const cached = providerDefaultsCache.get(provider);
10
+ if (cached !== undefined)
11
+ return cached;
12
+ const models = getCatalogModels(provider);
13
+ const defaults = {
14
+ api: sharedValue(models.map((model) => model.api)),
15
+ baseUrl: sharedValue(models.map((model) => model.baseUrl)),
16
+ };
17
+ providerDefaultsCache.set(provider, defaults);
18
+ return defaults;
19
+ }
20
+ /**
21
+ * Resolve a route model's protocol, endpoint and catalog descriptor from the bundled Pi catalog.
22
+ * @param dshServes DSH serves this model although the bundled catalog does not describe it: the provider profile
23
+ * lists it in `models`, or DSH's own catalog resolves it (`resolveModelInfo` succeeds). Only then may the
24
+ * provider-wide default apply.
25
+ */
26
+ export function resolveCatalogModel(provider, modelId, dshServes = false) {
27
+ const providerName = String(provider ?? "");
28
+ const id = String(modelId ?? "");
29
+ const exact = getCatalogModels(providerName).find((model) => model.id === id);
30
+ if (exact !== undefined)
31
+ return {
32
+ source: "catalog-model",
33
+ api: exact.api,
34
+ baseUrl: exact.baseUrl,
35
+ descriptor: exact.api === "openai-responses" ? exact : undefined,
36
+ };
37
+ const defaults = providerDefaults(providerName);
38
+ if (dshServes && defaults.api !== undefined)
39
+ return {
40
+ source: "catalog-provider-default",
41
+ api: defaults.api,
42
+ baseUrl: defaults.baseUrl,
43
+ descriptor: undefined,
44
+ };
45
+ return { source: "unknown", api: undefined, baseUrl: undefined, descriptor: undefined };
46
+ }