dsh-lcx-codex 0.7.0-pre.1 → 0.7.0

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/route.js CHANGED
@@ -4,7 +4,7 @@ import { SessionId } from "@deepseek-ai/dsh-session";
4
4
  import "@deepseek-ai/dsh-settings";
5
5
  import { assertUsableApiKey, attributionHeaders, LlmError, resolveRetryPolicy } from "@deepseek-ai/dsh-llm";
6
6
  import { resolveCatalogModel } from "./model-catalog.js";
7
- import { clampOpenAIPromptCacheKey } from "./pi-responses-runtime.js";
7
+ import { clampOpenAIPromptCacheKey, getCatalogModels } from "./pi-responses-runtime.js";
8
8
  import { providerSessionHeaders } from "./provider-headers.js";
9
9
  import { codedError, isPositiveFinite, isPositiveSafeInteger, isRecord } from "./util.js";
10
10
  import { DEFAULTS } from "./defaults.js";
@@ -14,6 +14,53 @@ export function normalizeBaseURL(value) {
14
14
  export function baseURLFingerprint(baseURL) {
15
15
  return createHash("sha256").update(normalizeBaseURL(baseURL), "utf8").digest("hex");
16
16
  }
17
+ function findHeaderCaseInsensitive(headers, target) {
18
+ const normalized = target.toLowerCase();
19
+ for (const [name, value] of Object.entries(headers ?? {})) {
20
+ if (name.toLowerCase() === normalized)
21
+ return String(value);
22
+ }
23
+ return undefined;
24
+ }
25
+ function effectiveCredentialIdentity(effectiveAuthorization) {
26
+ if (typeof effectiveAuthorization === "string" && /^Bearer\s+eyJ/iu.test(effectiveAuthorization.trim())) {
27
+ const token = effectiveAuthorization.trim().replace(/^Bearer\s+/iu, "");
28
+ const parts = token.split(".");
29
+ if (parts.length === 3 && parts[1]) {
30
+ try {
31
+ const payload = JSON.parse(Buffer.from(parts[1], "base64url").toString("utf8"));
32
+ const authClaim = isRecord(payload) ? payload["https://api.openai.com/auth"] : undefined;
33
+ const accountId = isRecord(authClaim) ? authClaim.chatgpt_account_id : undefined;
34
+ if (typeof accountId === "string" && accountId.trim().length > 0) {
35
+ return `chatgpt-acct:${accountId.trim()}`;
36
+ }
37
+ }
38
+ catch { }
39
+ }
40
+ }
41
+ return `auth:${effectiveAuthorization ?? ""}`;
42
+ }
43
+ function canonicalAuthorityHeaders(headers, excludeAuth = false) {
44
+ return Object.entries(headers ?? {})
45
+ .filter(([name]) => !excludeAuth || name.toLowerCase() !== "authorization")
46
+ .map(([name, value]) => [name.toLowerCase(), String(value)])
47
+ .sort(([left], [right]) => left.localeCompare(right));
48
+ }
49
+ export function requestHeaderAuthorityFingerprint(headers, credentialAuthority) {
50
+ const effectiveAuth = credentialAuthority?.effectiveAuthorization ??
51
+ findHeaderCaseInsensitive(headers, "authorization");
52
+ const authDigest = createHash("sha256")
53
+ .update(effectiveCredentialIdentity(effectiveAuth), "utf8")
54
+ .digest("hex");
55
+ return createHash("sha256")
56
+ .update(JSON.stringify({
57
+ v: 2,
58
+ apiKeyEnv: String(credentialAuthority?.apiKeyEnv ?? ""),
59
+ authDigest,
60
+ headers: canonicalAuthorityHeaders(headers, true),
61
+ }), "utf8")
62
+ .digest("hex");
63
+ }
17
64
  export function routeFingerprint(route, options = {}) {
18
65
  const includeSession = options.includeSession !== false;
19
66
  return createHash("sha256").update([
@@ -27,7 +74,7 @@ export function promptCacheSessionId(route, config = {}, ctx = undefined) {
27
74
  if (!sessionId)
28
75
  return undefined;
29
76
  const sessions = ctx?.sessions;
30
- let current = sessions?.get(SessionId(sessionId));
77
+ let current = typeof sessions?.get === "function" ? sessions.get(SessionId(sessionId)) : undefined;
31
78
  if (current?.header?.origin !== "subagent")
32
79
  return sessionId;
33
80
  const seen = new Set([sessionId]);
@@ -35,7 +82,7 @@ export function promptCacheSessionId(route, config = {}, ctx = undefined) {
35
82
  const parentId = current.header.parentSession;
36
83
  if (seen.has(parentId))
37
84
  return sessionId;
38
- const parent = sessions?.get(SessionId(parentId));
85
+ const parent = typeof sessions?.get === "function" ? sessions.get(SessionId(parentId)) : undefined;
39
86
  if (!parent)
40
87
  return sessionId;
41
88
  seen.add(parentId);
@@ -44,6 +91,8 @@ export function promptCacheSessionId(route, config = {}, ctx = undefined) {
44
91
  return current?.id ?? sessionId;
45
92
  }
46
93
  export function promptCacheKey(route, config = {}, ctx = undefined) {
94
+ if (config.responsesCompat?.promptCacheKeyMode === "disabled")
95
+ return undefined;
47
96
  return clampOpenAIPromptCacheKey(promptCacheSessionId(route, config, ctx));
48
97
  }
49
98
  /** Grok follows Pi directly: cache/affinity belongs to the selected child session. */
@@ -87,16 +136,29 @@ function configuredProviderProfile(ctx, provider) {
87
136
  return undefined;
88
137
  }
89
138
  }
90
- const RESPONSES_COMPAT_FIELDS = new Set(["supportsDeveloperRole", "sessionAffinityFormat", "supportsStrictMode", "supportsLongCacheRetention", "supportsOpenAIGrammarTools", "supportsAdditionalTools", "supportsToolSearch", "supportsExplicitPromptCacheMode", "supportsMaxOutputTokens"]);
91
- function copyResponsesCompat(target, source) {
139
+ const RESPONSES_COMPAT_FIELDS = new Set(["supportsDeveloperRole", "sessionAffinityFormat", "promptCacheKeyMode", "supportsStrictMode", "supportsLongCacheRetention", "supportsOpenAIGrammarTools", "supportsAdditionalTools", "supportsToolSearch", "supportsExplicitPromptCacheMode", "supportsMaxOutputTokens"]);
140
+ const RESPONSES_PROFILE_COMPAT_FIELDS = new Set(["supportsDeveloperRole", "supportsMaxOutputTokens", "supportsStrictMode", "supportsLongCacheRetention"]);
141
+ /** True when `model` names a Grok model (`grok-*`, `x-ai/grok-*`, or camelCase `grokCustom`/`GrOkCustomPreview`), rejecting non-Grok substrings like `vendor/grokking`. */
142
+ export function isGrokModelId(model) {
143
+ const trimmed = String(model ?? "").trim();
144
+ const terminal = trimmed.slice(trimmed.lastIndexOf("/") + 1);
145
+ return (/^grok(?:$|[-._0-9])/iu.test(terminal) ||
146
+ /^grok[A-Z]/u.test(terminal) ||
147
+ /^[gG][rR][oO][kK][A-Z][a-z]/u.test(terminal));
148
+ }
149
+ function copyResponsesCompat(target, source, allowedFields = RESPONSES_COMPAT_FIELDS) {
92
150
  if (!isRecord(source))
93
151
  return;
94
- for (const field of RESPONSES_COMPAT_FIELDS) {
152
+ for (const field of allowedFields) {
95
153
  const value = source[field];
96
154
  if (field === "sessionAffinityFormat") {
97
155
  if (value === "openai" || value === "openai-nosession" || value === "openrouter")
98
156
  target.sessionAffinityFormat = value;
99
157
  }
158
+ else if (field === "promptCacheKeyMode") {
159
+ if (value === "auto" || value === "disabled" || value === "enabled")
160
+ target.promptCacheKeyMode = value;
161
+ }
100
162
  else if (typeof value === "boolean")
101
163
  Object.assign(target, { [field]: value });
102
164
  }
@@ -179,7 +241,7 @@ export async function warmHostRecognizedModels(ctx) {
179
241
  continue;
180
242
  }
181
243
  for (const model of models) {
182
- if (!/^(?:gpt-|grok)/iu.test(model.id))
244
+ if (!/^gpt-/iu.test(model.id) && !isGrokModelId(model.id))
183
245
  continue;
184
246
  if (resolveCatalogModel(entry.provider, model.id).source === "catalog-model")
185
247
  continue;
@@ -238,8 +300,8 @@ function configuredModelProfile(profile, modelId) {
238
300
  }
239
301
  function configuredResponsesCompat(profile, modelId) {
240
302
  const compat = {};
241
- copyResponsesCompat(compat, profile?.compat);
242
- copyResponsesCompat(compat, configuredModelProfile(profile, modelId)?.compat);
303
+ copyResponsesCompat(compat, profile?.compat, RESPONSES_PROFILE_COMPAT_FIELDS);
304
+ copyResponsesCompat(compat, configuredModelProfile(profile, modelId)?.compat, RESPONSES_PROFILE_COMPAT_FIELDS);
243
305
  return Object.keys(compat).length ? compat : undefined;
244
306
  }
245
307
  const MODEL_THINKING_LEVELS = [
@@ -328,6 +390,9 @@ export function resolveResponsesRouteConfig(ctx, options, policy, assumeHostServ
328
390
  copyResponsesCompat(responsesCompat, builtin?.compat);
329
391
  copyResponsesCompat(responsesCompat, lcxCapabilityRoute ? policy.responsesCompat : undefined);
330
392
  copyResponsesCompat(responsesCompat, configuredResponsesCompat(configured, model));
393
+ if (policy.promptCacheKeyMode === "disabled" || policy.promptCacheKeyMode === "enabled") {
394
+ responsesCompat.promptCacheKeyMode = policy.promptCacheKeyMode;
395
+ }
331
396
  const promptCacheModel = lcxCapabilityRoute && policy.supportsExplicitPromptCacheMode === true ? resolveCatalogModel("openai", model).descriptor : undefined;
332
397
  const promptCacheRaw = promptCacheModel;
333
398
  const promptCacheCompat = isRecord(promptCacheRaw)
@@ -338,18 +403,30 @@ export function resolveResponsesRouteConfig(ctx, options, policy, assumeHostServ
338
403
  responsesCompat.supportsExplicitPromptCacheMode === undefined)
339
404
  responsesCompat.supportsExplicitPromptCacheMode = true;
340
405
  const resolvedCompat = Object.keys(responsesCompat).length ? responsesCompat : undefined;
341
- const supportsLongCacheRetention = resolvedCompat?.supportsLongCacheRetention ?? (lcxCapabilityRoute && policy.supportsLongCacheRetention === true);
406
+ // Pi defaults missing `supportsLongCacheRetention` to true (`model.compat?.supportsLongCacheRetention ?? true`)
407
+ // while leaving missing `cacheRetention` on `"short"` (`resolveCacheRetention`). Only explicit `lcx/gpt-5.6-*`
408
+ // capability routes retain LCX's legacy `supportsLongCacheRetention` -> `"long"` default when unconfigured.
409
+ const supportsLongCacheRetention = resolvedCompat?.supportsLongCacheRetention ??
410
+ (lcxCapabilityRoute ? policy.supportsLongCacheRetention === true : true);
342
411
  responsesCompat.supportsLongCacheRetention = supportsLongCacheRetention;
343
412
  const configuredRetention = configured.cacheRetention;
344
413
  const fallbackRetention = lcxCapabilityRoute ? policy.cacheRetention : undefined;
345
- const requestedRetention = configuredRetention === "none" || configuredRetention === "short" || configuredRetention === "long" ? configuredRetention : fallbackRetention === "none" || fallbackRetention === "short" || fallbackRetention === "long" ? fallbackRetention : undefined;
346
- const cacheRetention = requestedRetention === "long" && !supportsLongCacheRetention ? "short" : requestedRetention ?? (supportsLongCacheRetention ? "long" : "short");
414
+ const envRetention = process.env.PI_CACHE_RETENTION === "long" ? "long" : undefined;
415
+ const requestedRetention = configuredRetention === "none" || configuredRetention === "short" || configuredRetention === "long"
416
+ ? configuredRetention
417
+ : fallbackRetention === "none" || fallbackRetention === "short" || fallbackRetention === "long"
418
+ ? fallbackRetention
419
+ : envRetention;
420
+ const defaultRetention = lcxCapabilityRoute && supportsLongCacheRetention ? "long" : "short";
421
+ const cacheRetention = requestedRetention === "long" && !supportsLongCacheRetention ? "short" : (requestedRetention ?? defaultRetention);
347
422
  const declaredControls = declaredReasoningControls(configured, model);
423
+ const configuredModel = configuredModelProfile(configured, model);
348
424
  return {
349
425
  provider,
350
426
  model,
351
427
  api: "openai-responses",
352
428
  baseURL: normalizeBaseURL(baseURL),
429
+ rawBaseURL: baseURL,
353
430
  apiKeyEnv,
354
431
  ...(builtin?.headers === undefined ? {} : { catalogHeaders: { ...builtin.headers } }),
355
432
  headers: { ...(configured.headers ?? {}) },
@@ -359,6 +436,10 @@ export function resolveResponsesRouteConfig(ctx, options, policy, assumeHostServ
359
436
  // Only a declared `reasoningEfforts` is projected here; an undeclared model follows the catalog
360
437
  // and what DSH resolved for it (see `routeModelOverride`).
361
438
  ...(declaredControls === undefined ? {} : { modelControls: declaredControls }),
439
+ profileReasoning: profileReasoning(configured.reasoning),
440
+ ...(isPositiveSafeInteger(catalog.maxTokens) ? { catalogMaxTokens: catalog.maxTokens } : {}),
441
+ ...(isPositiveSafeInteger(configuredModel?.maxTokens) ? { profileModelMaxTokens: configuredModel.maxTokens } : {}),
442
+ ...(isPositiveSafeInteger(configured.defaultMaxTokens) ? { profileDefaultMaxTokens: configured.defaultMaxTokens } : {}),
362
443
  // These are explicitly LCX-owned transport and request-capability policies.
363
444
  timeoutMs: isPositiveSafeInteger(configured.timeoutMs) ? configured.timeoutMs : policy.timeoutMs,
364
445
  maxAttempts: retryAttempts(configured.retryPolicy, policy.maxAttempts),
@@ -388,11 +469,11 @@ export function diagnoseResponsesRoute(ctx, options) {
388
469
  return "api-unresolved";
389
470
  return api === "openai-responses" ? "incomplete" : "api-not-responses";
390
471
  }
391
- /** Resolve a Grok-prefixed model through its selected DSH Responses profile. */
472
+ /** Resolve a Grok model through its selected DSH Responses profile. */
392
473
  export function resolveGrokResponsesRouteConfig(ctx, options, policy) {
393
474
  const provider = String(options?.provider ?? "");
394
475
  const model = String(options?.model ?? "");
395
- if (!provider.trim() || !/^grok/iu.test(model))
476
+ if (!provider.trim() || !isGrokModelId(model))
396
477
  return undefined;
397
478
  const configured = configuredProviderProfile(ctx, provider);
398
479
  if (!isRecord(configured))
@@ -414,19 +495,28 @@ export function resolveGrokResponsesRouteConfig(ctx, options, policy) {
414
495
  const responsesCompat = {};
415
496
  copyResponsesCompat(responsesCompat, selectedBuiltin?.compat);
416
497
  copyResponsesCompat(responsesCompat, configuredResponsesCompat(configured, model));
417
- const supportsLongCacheRetention = responsesCompat.supportsLongCacheRetention === true;
498
+ if (policy.promptCacheKeyMode === "disabled" || policy.promptCacheKeyMode === "enabled") {
499
+ responsesCompat.promptCacheKeyMode = policy.promptCacheKeyMode;
500
+ }
501
+ const supportsLongCacheRetention = responsesCompat.supportsLongCacheRetention !== false;
418
502
  responsesCompat.supportsLongCacheRetention = supportsLongCacheRetention;
419
- const requestedRetention = configured.cacheRetention;
503
+ const configuredRetention = configured.cacheRetention;
504
+ const envRetention = process.env.PI_CACHE_RETENTION === "long" ? "long" : undefined;
505
+ const requestedRetention = configuredRetention === "none" || configuredRetention === "short" || configuredRetention === "long"
506
+ ? configuredRetention
507
+ : envRetention;
420
508
  const cacheRetention = requestedRetention === "none"
421
509
  ? "none"
422
510
  : requestedRetention === "long" && supportsLongCacheRetention
423
511
  ? "long"
424
512
  : "short";
513
+ const configuredModel = configuredModelProfile(configured, model);
425
514
  return {
426
515
  provider,
427
516
  model,
428
517
  api: "openai-responses",
429
518
  baseURL: normalizeBaseURL(baseURL),
519
+ rawBaseURL: baseURL,
430
520
  apiKeyEnv,
431
521
  ...(selectedBuiltin?.headers === undefined ? {} : { catalogHeaders: { ...selectedBuiltin.headers } }),
432
522
  headers: effectiveGrokProfileHeaders(configured.headers),
@@ -439,6 +529,9 @@ export function resolveGrokResponsesRouteConfig(ctx, options, policy) {
439
529
  includeEncryptedReasoning: true,
440
530
  },
441
531
  profileReasoning: profileReasoning(configured.reasoning),
532
+ ...(isPositiveSafeInteger(catalog.maxTokens) ? { catalogMaxTokens: catalog.maxTokens } : {}),
533
+ ...(isPositiveSafeInteger(configuredModel?.maxTokens) ? { profileModelMaxTokens: configuredModel.maxTokens } : {}),
534
+ ...(isPositiveSafeInteger(configured.defaultMaxTokens) ? { profileDefaultMaxTokens: configured.defaultMaxTokens } : {}),
442
535
  // Pi applies only an explicitly configured request deadline; stream liveness
443
536
  // is owned separately by the provider idle watchdog.
444
537
  timeoutMs: isPositiveSafeInteger(configured.timeoutMs)
@@ -461,6 +554,104 @@ export function resolveGrokResponsesRouteConfig(ctx, options, policy) {
461
554
  : policy.requestImageMaxBytes,
462
555
  };
463
556
  }
557
+ function positiveFiniteNumber(value) {
558
+ return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : undefined;
559
+ }
560
+ function isGrokBudgetRoute(route) {
561
+ const provider = String(route?.provider ?? "").trim();
562
+ return provider.length > 0 && isGrokModelId(route?.model);
563
+ }
564
+ export function grokBudgetInputSignature(ctx, route, requestMaxTokens) {
565
+ const provider = String(route?.provider ?? "").trim();
566
+ const model = String(route?.model ?? "").trim();
567
+ const profile = provider ? configuredProviderProfile(ctx, provider) : undefined;
568
+ const modelProfile = isRecord(profile) && model ? configuredModelProfile(profile, model) : undefined;
569
+ return JSON.stringify([
570
+ requestMaxTokens ?? null,
571
+ isRecord(profile) ? profile.defaultContextWindow ?? null : null,
572
+ modelProfile?.contextWindow ?? null,
573
+ modelProfile?.maxTokens ?? null,
574
+ Array.isArray(profile?.models) ? profile.models.map((entry) => String(entry?.id ?? "")) : null,
575
+ ]);
576
+ }
577
+ /**
578
+ * Pure pre-flight diagnostic for Grok profiles whose resolved `maxTokens >= contextWindow`.
579
+ *
580
+ * In DSH 0.2.2 (`dsh-llm-pi-ai` + `dsh-compaction-basic`), an explicit `maxTokens` on `models[]` or
581
+ * `modelOverrides` becomes `ModelInfo.defaultMaxTokens` (reserved completion tokens). When `requestMaxTokens`
582
+ * or `defaultMaxTokens >= contextWindow`, `contextWindow - reservedCompletionTokens <= 0`, blocking model
583
+ * switches to Grok with `MODEL_SWITCH_COMPACTION_FAILED`.
584
+ */
585
+ export function diagnoseGrokProfileBudget(profile, route, options) {
586
+ const provider = String(route?.provider ?? "").trim();
587
+ const model = String(route?.model ?? "").trim();
588
+ if (!provider || !isGrokBudgetRoute({ provider, model }))
589
+ return undefined;
590
+ if (isRecord(profile) && profileExcludesModel(profile, model))
591
+ return undefined;
592
+ if (!isRecord(profile) && !options?.resolvedModelInfo)
593
+ return undefined;
594
+ const modelProfile = isRecord(profile) && model ? configuredModelProfile(profile, model) : undefined;
595
+ const catalogModel = model ? getCatalogModels(provider).find((entry) => entry.id === model) : undefined;
596
+ const contextWindow = positiveFiniteNumber(options?.resolvedModelInfo?.contextWindow) ??
597
+ positiveFiniteNumber(modelProfile?.contextWindow) ??
598
+ positiveFiniteNumber(catalogModel?.contextWindow) ??
599
+ (isRecord(profile) ? positiveFiniteNumber(profile.defaultContextWindow) : undefined);
600
+ const maxTokens = positiveFiniteNumber(options?.requestMaxTokens) ??
601
+ positiveFiniteNumber(options?.resolvedModelInfo?.defaultMaxTokens) ??
602
+ positiveFiniteNumber(modelProfile?.maxTokens);
603
+ if (contextWindow === undefined || maxTokens === undefined || maxTokens < contextWindow)
604
+ return undefined;
605
+ const target = model ? `${provider}/${model}` : provider;
606
+ return `[lcx-codex] Grok route "${target}" resolves maxTokens (${maxTokens}) >= contextWindow (${contextWindow}); DSH 0.2.2 blocks switching to Grok with MODEL_SWITCH_COMPACTION_FAILED (leaving zero message budget). Set maxTokens clearly below contextWindow (for example, 64000 or 128000 for a 500000 context window) in the llm-pi-ai provider profile ("models[].maxTokens" or "modelOverrides[\\"${model}\\"].maxTokens") or pass a lower request maxTokens.`;
607
+ }
608
+ export function diagnoseGrokContextBudget(ctx, route, options) {
609
+ if (!isGrokBudgetRoute(route))
610
+ return undefined;
611
+ const provider = String(route?.provider ?? "").trim();
612
+ const profile = configuredProviderProfile(ctx, provider);
613
+ return diagnoseGrokProfileBudget(profile, route, options);
614
+ }
615
+ export function grokRouteMayNeedHostBudgetLookup(ctx, route, requestMaxTokens) {
616
+ const provider = String(route?.provider ?? "").trim();
617
+ const model = String(route?.model ?? "").trim();
618
+ if (!provider || !isGrokBudgetRoute({ provider, model }))
619
+ return false;
620
+ const profile = configuredProviderProfile(ctx, provider);
621
+ if (!isRecord(profile) || profileExcludesModel(profile, model))
622
+ return false;
623
+ const modelProfile = configuredModelProfile(profile, model);
624
+ return (positiveFiniteNumber(requestMaxTokens) !== undefined ||
625
+ positiveFiniteNumber(modelProfile?.maxTokens) !== undefined);
626
+ }
627
+ export async function diagnoseGrokContextBudgetAsync(ctx, route, options) {
628
+ const provider = String(route?.provider ?? "").trim();
629
+ const model = String(route?.model ?? "").trim();
630
+ if (!provider || !isGrokBudgetRoute({ provider, model }))
631
+ return undefined;
632
+ const profile = configuredProviderProfile(ctx, provider);
633
+ if (!isRecord(profile) || profileExcludesModel(profile, model))
634
+ return undefined;
635
+ let resolvedModelInfo;
636
+ if (typeof ctx?.llm?.resolveModelInfo === "function") {
637
+ try {
638
+ const info = await ctx.llm.resolveModelInfo(provider, model, options?.signal);
639
+ if (isRecord(info)) {
640
+ resolvedModelInfo = {
641
+ contextWindow: isRecord(info.context) ? info.context.contextWindow : undefined,
642
+ defaultMaxTokens: info.defaultMaxTokens,
643
+ };
644
+ }
645
+ }
646
+ catch {
647
+ // Fall back to configured profile + catalog metadata if host model resolution fails.
648
+ }
649
+ }
650
+ return diagnoseGrokProfileBudget(profile, route, {
651
+ requestMaxTokens: options?.requestMaxTokens,
652
+ resolvedModelInfo,
653
+ });
654
+ }
464
655
  export async function resolveApiKey(ctx, config) {
465
656
  const resolved = await ctx?.credentials.resolve(credentialRef(config.apiKeyEnv));
466
657
  // DSH's own definition of a usable key (trimmed, nothing an HTTP header cannot carry). A rejected key is
@@ -508,12 +699,18 @@ function sessionAffinityFormat(config) {
508
699
  : "openai";
509
700
  }
510
701
  /** Headers whose owners (credentials, session affinity, correlation) layer them after the contributors. */
511
- const OWNER_PROTECTED_HEADERS = new Set(["authorization", "session_id", "session-id", "x-session-id", "x-client-request-id", "x-opencode-session"]);
702
+ const OWNER_PROTECTED_HEADERS = new Set(["authorization", "cf-aig-authorization", "proxy-authorization", "x-api-key", "api-key", "cookie", "session_id", "session-id", "x-session-id", "x-client-request-id", "x-opencode-session"]);
512
703
  /** The host exposes profile headers only. Credential and routing headers are layered by their owners later. */
513
704
  export function prepareRequestHeaders(ctx, config, options = {}) {
514
705
  try {
515
- const initial = new Headers(config.headers);
516
- const request = Object.freeze({ provider: config.provider, model: config.model, baseURL: config.baseURL,
706
+ const initial = new Headers();
707
+ // Contributors must never observe explicit profile credentials or routing/session affinity headers;
708
+ // owners re-apply protected profile headers after contributors run.
709
+ for (const [name, value] of Object.entries(config.headers ?? {})) {
710
+ if (!OWNER_PROTECTED_HEADERS.has(name.toLowerCase()))
711
+ initial.set(name, value);
712
+ }
713
+ const request = Object.freeze({ provider: config.provider, model: config.model, baseURL: config.rawBaseURL ?? config.baseURL,
517
714
  ...(options.sessionId === undefined ? {} : { sessionId: options.sessionId }),
518
715
  ...(options.purpose === undefined ? {} : { purpose: options.purpose }) });
519
716
  const waterfall = ctx?.waterfall;
@@ -529,25 +726,31 @@ export function prepareRequestHeaders(ctx, config, options = {}) {
529
726
  throw new LlmError(`pi-ai request header preparation failed for provider "${config.provider}": ${diagnostic}`, "REQUEST_HEADERS", { cause: error });
530
727
  }
531
728
  }
729
+ function computeReplayAuthorityHeaders(contributorHeaders, protectedProfile) {
730
+ const attributionKeys = new Set(Object.keys(attributionHeaders()).map((name) => name.toLowerCase()));
731
+ const authorityContributors = Object.fromEntries(Object.entries(contributorHeaders).filter(([name]) => !attributionKeys.has(name.toLowerCase())));
732
+ return layerHeaders(authorityContributors, protectedProfile);
733
+ }
532
734
  /**
533
735
  * The headers of one GPT request. `sessionId` is the prompt-cache / affinity session (the root session for a
534
736
  * subagent, absent without cache retention); `providerSessionId` is the CURRENT DSH session, which is what Pi's
535
737
  * client sends in provider routing headers (`x-opencode-session`) whatever the cache policy is.
536
738
  */
537
- export async function authenticatedHeaders(ctx, config, sessionId, requestId, dynamicHeaders = {}, providerSessionId, request) {
739
+ export async function authenticatedRequestHeaders(ctx, config, sessionId, requestId, dynamicHeaders = {}, providerSessionId, request, resolvedApiKey) {
538
740
  const explicit = { ...(config.headers ?? {}) };
539
741
  const currentSessionId = providerSessionId ?? (sessionId ? String(sessionId) : undefined);
540
742
  // As on the host, the credential is resolved before contributors run: a missing one never reaches them.
541
- const apiKey = await resolveApiKey(ctx, config);
743
+ const apiKey = resolvedApiKey ?? (await resolveApiKey(ctx, config));
542
744
  const prepared = prepareRequestHeaders(ctx, config, request ?? (currentSessionId === undefined ? {} : { sessionId: currentSessionId }));
745
+ const contributorHeaders = Object.fromEntries(Object.entries(prepared).filter(([name]) => !OWNER_PROTECTED_HEADERS.has(name.toLowerCase())));
543
746
  const sid = sessionId ? String(sessionId) : undefined;
544
747
  const format = sessionAffinityFormat(config);
545
748
  // Model/provider defaults precede the contributed profile layer. Credentials and session routing
546
749
  // are owned by their later layers; attribution is re-applied last.
547
- const headers = layerHeaders(config.catalogHeaders, dynamicHeaders, prepared, { authorization: `Bearer ${apiKey}` }, providerSessionHeaders(config.provider, providerSessionId ?? sid));
750
+ const headers = layerHeaders(config.catalogHeaders, dynamicHeaders, contributorHeaders, { authorization: `Bearer ${apiKey}` }, providerSessionHeaders(config.provider, providerSessionId ?? sid));
548
751
  if (sid && !hasExplicitSessionAffinity(explicit)) {
549
752
  if (format === "openai")
550
- headers.session_id = sid;
753
+ headers["session-id"] = sid;
551
754
  else if (format === "openrouter")
552
755
  headers["x-session-id"] = sid;
553
756
  }
@@ -560,33 +763,66 @@ export async function authenticatedHeaders(ctx, config, sessionId, requestId, dy
560
763
  // session affinity, correlation) are the profile's to set over every default and never a contributor's.
561
764
  // Attribution is re-applied last, as on the host.
562
765
  const protectedProfile = Object.fromEntries(Object.entries(explicit).filter(([name]) => OWNER_PROTECTED_HEADERS.has(name.toLowerCase())));
563
- return layerHeaders(headers, protectedProfile, attributionHeaders());
766
+ const finalHeaders = layerHeaders(headers, protectedProfile, attributionHeaders());
767
+ const replayAuthorityHeaders = computeReplayAuthorityHeaders(contributorHeaders, protectedProfile);
768
+ const headerAuthorityFingerprint = requestHeaderAuthorityFingerprint(replayAuthorityHeaders, {
769
+ apiKeyEnv: config.apiKeyEnv,
770
+ effectiveAuthorization: findHeaderCaseInsensitive(finalHeaders, "authorization"),
771
+ });
772
+ return {
773
+ headers: finalHeaders,
774
+ replayAuthorityHeaders,
775
+ headerAuthorityFingerprint,
776
+ };
777
+ }
778
+ export async function authenticatedHeaders(ctx, config, sessionId, requestId, dynamicHeaders = {}, providerSessionId, request, resolvedApiKey) {
779
+ return (await authenticatedRequestHeaders(ctx, config, sessionId, requestId, dynamicHeaders, providerSessionId, request, resolvedApiKey)).headers;
564
780
  }
565
- /** Grok mirrors Pi createClient ordering without changing accepted GPT headers. */
566
- export async function authenticatedGrokHeaders(ctx, config, sessionId, dynamicHeaders = {}, providerSessionId) {
781
+ /** Grok mirrors Pi createClient ordering and request-header contributor hook without changing accepted GPT precedence. */
782
+ export async function authenticatedGrokRequestHeaders(ctx, config, sessionId, dynamicHeaders = {}, providerSessionId, request, resolvedApiKey) {
567
783
  const explicit = effectiveGrokProfileHeaders(config.headers);
568
784
  const sid = sessionId ? String(sessionId) : undefined;
569
- // The catalog model's headers come first, so DSH attribution (applied last, as the host does) replaces them.
570
- const headers = layerHeaders(config.catalogHeaders, {
571
- authorization: `Bearer ${await resolveApiKey(ctx, config)}`,
572
- }, dynamicHeaders, providerSessionHeaders(config.provider, providerSessionId ?? sid));
785
+ const currentSessionId = providerSessionId ?? sid;
786
+ // Resolve credentials before contributors run, matching authenticatedHeaders and DSH PiAiAdapter.
787
+ const apiKey = resolvedApiKey ?? (await resolveApiKey(ctx, config));
788
+ const prepared = prepareRequestHeaders(ctx, { ...config, headers: explicit }, request ?? (currentSessionId === undefined ? {} : { sessionId: currentSessionId }));
789
+ const contributorHeaders = Object.fromEntries(Object.entries(prepared).filter(([name]) => !OWNER_PROTECTED_HEADERS.has(name.toLowerCase())));
790
+ // The catalog model's headers precede contributed/dynamic layers; credentials, session affinity,
791
+ // protected profile headers, and final DSH attribution follow in owner order.
792
+ const headers = layerHeaders(config.catalogHeaders, dynamicHeaders, contributorHeaders, { authorization: `Bearer ${apiKey}` }, providerSessionHeaders(config.provider, currentSessionId));
573
793
  const format = sessionAffinityFormat(config);
574
794
  if (sid) {
575
795
  if (format === "openai")
576
- headers.session_id = sid;
796
+ headers["session-id"] = sid;
577
797
  else if (format === "openrouter")
578
798
  headers["x-session-id"] = sid;
579
799
  if (format === "openai" || format === "openai-nosession")
580
800
  headers["x-client-request-id"] = sid;
581
801
  }
582
- for (const [name, value] of Object.entries(explicit))
583
- setHeaderCaseInsensitive(headers, name, value);
584
- for (const [name, value] of Object.entries(attributionHeaders()))
585
- setHeaderCaseInsensitive(headers, name, value);
586
- return headers;
802
+ const protectedProfile = Object.fromEntries(Object.entries(explicit).filter(([name]) => OWNER_PROTECTED_HEADERS.has(name.toLowerCase())));
803
+ const finalHeaders = layerHeaders(headers, protectedProfile, attributionHeaders());
804
+ const replayAuthorityHeaders = computeReplayAuthorityHeaders(contributorHeaders, protectedProfile);
805
+ const headerAuthorityFingerprint = requestHeaderAuthorityFingerprint(replayAuthorityHeaders, {
806
+ apiKeyEnv: config.apiKeyEnv,
807
+ effectiveAuthorization: findHeaderCaseInsensitive(finalHeaders, "authorization"),
808
+ });
809
+ return {
810
+ headers: finalHeaders,
811
+ replayAuthorityHeaders,
812
+ headerAuthorityFingerprint,
813
+ };
814
+ }
815
+ export async function authenticatedGrokHeaders(ctx, config, sessionId, dynamicHeaders = {}, providerSessionId, request, resolvedApiKey) {
816
+ return (await authenticatedGrokRequestHeaders(ctx, config, sessionId, dynamicHeaders, providerSessionId, request, resolvedApiKey)).headers;
587
817
  }
588
818
  export function currentRoute(options, config) {
589
- return { provider: String(options?.provider ?? config.provider ?? ""), model: String(options?.model ?? config.model ?? ""), baseURL: normalizeBaseURL(config.baseURL), sessionId: String(options?.sessionId ?? "") };
819
+ return {
820
+ provider: String(options?.provider ?? config.provider ?? ""),
821
+ model: String(options?.model ?? config.model ?? ""),
822
+ baseURL: normalizeBaseURL(config.baseURL),
823
+ ...(config.rawBaseURL === undefined ? {} : { rawBaseURL: config.rawBaseURL }),
824
+ sessionId: String(options?.sessionId ?? ""),
825
+ };
590
826
  }
591
827
  export function generationControlsFromHeader(header, route) {
592
828
  const config = header?.config;
@@ -609,7 +845,58 @@ export function generationControlsFromSession(session, route) {
609
845
  return {};
610
846
  }
611
847
  }
848
+ export async function resolveRouteHeaderAuthorityFingerprint(ctx, route, routeConfig, request) {
849
+ const provider = String(route?.provider ?? routeConfig?.provider ?? "");
850
+ const model = String(route?.model ?? routeConfig?.model ?? "");
851
+ const baseURL = String(route?.baseURL ?? routeConfig?.baseURL ?? "");
852
+ const sessionId = String(route?.sessionId ?? "");
853
+ const resolvedFromCtx = provider && model
854
+ ? resolveResponsesRouteConfig(ctx, { provider, model }, {})
855
+ : undefined;
856
+ const rawApiKeyEnv = typeof routeConfig?.apiKeyEnv === "string" && routeConfig.apiKeyEnv.length > 0
857
+ ? routeConfig.apiKeyEnv
858
+ : resolvedFromCtx?.apiKeyEnv;
859
+ const effectiveApiKeyEnv = rawApiKeyEnv ?? "";
860
+ const effectiveHeaders = routeConfig?.headers ?? resolvedFromCtx?.headers;
861
+ if (typeof ctx?.credentials?.resolve === "function") {
862
+ const effectiveConfig = {
863
+ ...(resolvedFromCtx ?? {}),
864
+ ...(routeConfig ?? {}),
865
+ provider,
866
+ model,
867
+ api: "openai-responses",
868
+ baseURL,
869
+ apiKeyEnv: effectiveApiKeyEnv,
870
+ cacheRetention: (routeConfig?.cacheRetention ?? resolvedFromCtx?.cacheRetention ?? "short"),
871
+ supportsLongCacheRetention: Boolean(routeConfig?.supportsLongCacheRetention ?? resolvedFromCtx?.supportsLongCacheRetention),
872
+ ...(effectiveHeaders === undefined ? {} : { headers: effectiveHeaders }),
873
+ };
874
+ try {
875
+ const apiKey = await resolveApiKey(ctx, { apiKeyEnv: rawApiKeyEnv });
876
+ const cacheSessionId = promptCacheSessionId({ provider, model, baseURL, sessionId }, effectiveConfig, ctx);
877
+ return (await authenticatedRequestHeaders(ctx, effectiveConfig, cacheSessionId, cacheSessionId === undefined ? null : sessionId, {}, sessionId || undefined, request, apiKey)).headerAuthorityFingerprint;
878
+ }
879
+ catch {
880
+ return requestHeaderAuthorityFingerprint(effectiveHeaders, {
881
+ apiKeyEnv: effectiveApiKeyEnv,
882
+ });
883
+ }
884
+ }
885
+ return requestHeaderAuthorityFingerprint(effectiveHeaders, {
886
+ apiKeyEnv: effectiveApiKeyEnv,
887
+ });
888
+ }
612
889
  export function routeCompatible(record, route, ctx) {
613
890
  void ctx;
614
- return !!record && record.version === 5 && record.provider === route.provider && record.model === route.model && record.baseURLFingerprint === baseURLFingerprint(route.baseURL) && record.sourceSessionId === route.sessionId;
891
+ return (!!record &&
892
+ record.version === 5 &&
893
+ record.provider === route.provider &&
894
+ record.model === route.model &&
895
+ record.baseURLFingerprint === baseURLFingerprint(route.baseURL) &&
896
+ record.sourceSessionId === route.sessionId &&
897
+ typeof record.headerAuthorityFingerprint === "string" &&
898
+ record.headerAuthorityFingerprint.length > 0 &&
899
+ typeof route.headerAuthorityFingerprint === "string" &&
900
+ route.headerAuthorityFingerprint.length > 0 &&
901
+ record.headerAuthorityFingerprint === route.headerAuthorityFingerprint);
615
902
  }
@@ -50,6 +50,11 @@ export function planToolSurface(input) {
50
50
  const fallback = (reason) => full(messages, tools, toolHistory, mode === "addition-only" ? reason : undefined, facts.toolUpdate === "addition-only" && reason !== COMPAT_OPT_OUT);
51
51
  if (mode !== "addition-only")
52
52
  return full(messages, tools, toolHistory);
53
+ if ((tools === undefined || tools.length === 0) &&
54
+ toolHistory === undefined &&
55
+ !messages.some((message) => message.role === "developer")) {
56
+ return full(messages, tools, toolHistory);
57
+ }
53
58
  if (tools === undefined)
54
59
  return fallback("no tools");
55
60
  if (!facts.resolved)
@@ -63,6 +68,9 @@ export function planToolSurface(input) {
63
68
  return fallback(compat?.supportsAdditionalTools === false || compat?.supportsToolSearch === false ? COMPAT_OPT_OUT : COMPAT_SILENT);
64
69
  if (toolHistory === undefined)
65
70
  return fallback("no DSH tool history");
71
+ const developerIds = new Set(messages.flatMap((message) => (message.role === "developer" && typeof message.id === "string" ? [message.id] : [])));
72
+ if (toolHistory.updates.some((update) => !developerIds.has(update.messageId)))
73
+ return fallback("tool history references missing developer updates");
66
74
  const projected = projectToolUpdates(messages, tools, "addition-only", toolHistory);
67
75
  const projectedTools = projected.tools;
68
76
  if (projectedTools === undefined)
@@ -84,17 +92,42 @@ export function planToolSurface(input) {
84
92
  if (tool.deferLoading === true)
85
93
  deferred.add(tool.name);
86
94
  }
87
- // Without any deferred tool or retained addition the request equals the full list; use the ordinary path
88
- // so the common no-change turn stays byte-identical with the 0.5.1 behaviour.
89
- if (deferred.size === 0 && added.size === 0)
90
- return full(messages, tools, toolHistory);
91
95
  if (deferred.size !== added.size || [...deferred].some((name) => !added.has(name)))
92
96
  return fallback("deferred tools and retained additions disagree");
93
- // The declared surface must equal the active surface; a mismatch means the history fold and the live
94
- // header diverged (restore, fork or migration), where only the full list is known to be correct.
95
- const active = new Set(tools.map((tool) => tool.name));
96
- if (active.size !== projectedTools.length || projectedTools.some((tool) => !active.has(tool.name)))
97
+ // The declared surface must match the active normalized definitions (ignoring projection-owned
98
+ // `deferLoading`); a name or schema mismatch means history and live header diverged, where only
99
+ // the full active tool list is safe to send.
100
+ const canonicalJsonValue = (value) => {
101
+ if (Array.isArray(value))
102
+ return ["a", ...value.map(canonicalJsonValue)];
103
+ if (value !== null && typeof value === "object") {
104
+ const record = value;
105
+ const entries = [];
106
+ for (const key of Object.keys(record).sort()) {
107
+ if (!Object.hasOwn(record, key))
108
+ continue;
109
+ const child = record[key];
110
+ if (child !== undefined)
111
+ entries.push([key, canonicalJsonValue(child)]);
112
+ }
113
+ return ["o", entries];
114
+ }
115
+ return value;
116
+ };
117
+ const canonicalToolSignature = (tool) => {
118
+ const copy = { ...tool };
119
+ delete copy.deferLoading;
120
+ return JSON.stringify(canonicalJsonValue(copy));
121
+ };
122
+ const active = new Map(tools.map((tool) => [tool.name, canonicalToolSignature(tool)]));
123
+ if (active.size !== tools.length ||
124
+ active.size !== projectedTools.length ||
125
+ projectedTools.some((tool) => active.get(tool.name) !== canonicalToolSignature(tool)))
97
126
  return fallback("declared tools differ from the active tools");
127
+ // Without any deferred tool or retained addition the verified request equals the full list; use the
128
+ // ordinary path so the common no-change turn stays byte-identical with the 0.5.1 behaviour.
129
+ if (deferred.size === 0 && added.size === 0)
130
+ return full(messages, tools, toolHistory);
98
131
  return {
99
132
  messages: projected.messages,
100
133
  tools: projectedTools,