@yansigit/opencodex 2.33.0 → 2.35.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.
Files changed (196) hide show
  1. package/README.md +3 -3
  2. package/gui/dist/assets/index-BjCaHxdz.js +112 -0
  3. package/gui/dist/assets/index-DLkXOXLC.css +1 -0
  4. package/gui/dist/index.html +2 -2
  5. package/package.json +1 -1
  6. package/src/adapters/anthropic.ts +79 -2
  7. package/src/adapters/command-code.ts +141 -23
  8. package/src/adapters/cursor/call-id.ts +44 -0
  9. package/src/adapters/cursor/checkpoint-store.ts +15 -10
  10. package/src/adapters/cursor/discovery.ts +60 -2
  11. package/src/adapters/cursor/effort-map.ts +79 -1
  12. package/src/adapters/cursor/envelope-echo.ts +162 -0
  13. package/src/adapters/cursor/live-models.ts +7 -2
  14. package/src/adapters/cursor/live-transport.ts +17 -1
  15. package/src/adapters/cursor/message-mapper.ts +4 -1
  16. package/src/adapters/cursor/native-exec-fs.ts +13 -12
  17. package/src/adapters/cursor/native-exec-network.ts +3 -5
  18. package/src/adapters/cursor/native-exec-policy.ts +47 -0
  19. package/src/adapters/cursor/native-exec-shell.ts +116 -31
  20. package/src/adapters/cursor/native-exec.ts +38 -10
  21. package/src/adapters/cursor/protobuf-events.ts +28 -2
  22. package/src/adapters/cursor/protobuf-request.ts +93 -41
  23. package/src/adapters/cursor/request-builder.ts +39 -10
  24. package/src/adapters/cursor/tool-definitions.ts +27 -3
  25. package/src/adapters/cursor/tool-result-normalize.ts +51 -6
  26. package/src/adapters/cursor/types.ts +23 -4
  27. package/src/adapters/cursor.ts +170 -29
  28. package/src/adapters/google-aistudio-parser.ts +49 -0
  29. package/src/adapters/google-antigravity-replay.ts +105 -25
  30. package/src/adapters/google-antigravity-wire.ts +5 -0
  31. package/src/adapters/google-errors.ts +41 -12
  32. package/src/adapters/google-http.ts +12 -11
  33. package/src/adapters/google.ts +219 -36
  34. package/src/adapters/image.ts +1 -1
  35. package/src/adapters/kiro-constants.ts +15 -0
  36. package/src/adapters/kiro-tools.ts +43 -15
  37. package/src/adapters/kiro.ts +54 -9
  38. package/src/adapters/openai-chat.ts +286 -242
  39. package/src/adapters/openai-responses.ts +335 -24
  40. package/src/adapters/run-turn-queue.ts +36 -1
  41. package/src/adapters/tool-catalog-nudge.ts +2 -2
  42. package/src/adapters/xai-tool-schema.ts +436 -0
  43. package/src/bridge.ts +67 -26
  44. package/src/chat/inbound.ts +29 -1
  45. package/src/chat/outbound.ts +15 -7
  46. package/src/claude/agents-inject.ts +8 -1
  47. package/src/claude/outbound.ts +10 -8
  48. package/src/cli/account-api.ts +27 -7
  49. package/src/cli/account-extended.ts +10 -3
  50. package/src/cli/account.ts +29 -5
  51. package/src/cli/alias.ts +66 -0
  52. package/src/cli/claude.ts +26 -1
  53. package/src/cli/dispatch.ts +13 -1
  54. package/src/cli/help.ts +1 -0
  55. package/src/cli/index.ts +6 -1
  56. package/src/cli/init.ts +1 -0
  57. package/src/cli/models-runtime.ts +95 -0
  58. package/src/cli/models.ts +13 -7
  59. package/src/cli/provider-runtime.ts +16 -2
  60. package/src/cli/registry.ts +6 -1
  61. package/src/cli/telemetry-commands.ts +25 -0
  62. package/src/cli/v2.ts +34 -10
  63. package/src/codex/account-pause.ts +2 -1
  64. package/src/codex/account-priority.ts +3 -2
  65. package/src/codex/app-server-processes.ts +80 -6
  66. package/src/codex/auth-api.ts +48 -8
  67. package/src/codex/auth-context.ts +21 -18
  68. package/src/codex/catalog/aggregation.ts +6 -0
  69. package/src/codex/catalog/model-metadata.ts +13 -1
  70. package/src/codex/catalog/native-models.ts +5 -2
  71. package/src/codex/catalog/parsing.ts +16 -0
  72. package/src/codex/catalog/provider-fetch.ts +20 -3
  73. package/src/codex/catalog/sync.ts +127 -2
  74. package/src/codex/catalog.ts +1 -1
  75. package/src/codex/codex-write-lock.ts +3 -1
  76. package/src/codex/convergence-types.ts +1 -1
  77. package/src/codex/convergence.ts +22 -2
  78. package/src/codex/desired-state.ts +2 -2
  79. package/src/codex/desktop-app-restart.ts +18 -5
  80. package/src/codex/inject-coordination.ts +83 -0
  81. package/src/codex/inject.ts +14 -1
  82. package/src/codex/log-guard/inspect.ts +22 -4
  83. package/src/codex/model-entitlements.ts +9 -2
  84. package/src/codex/prompt-layers.ts +371 -25
  85. package/src/codex/prompt-text-probe.ts +238 -0
  86. package/src/codex/quota.ts +123 -18
  87. package/src/codex/routing.ts +9 -0
  88. package/src/codex/subagent-model-fallback.ts +198 -27
  89. package/src/codex/transition-state.ts +107 -8
  90. package/src/combos/types.ts +10 -0
  91. package/src/compatibility/openai-responses.ts +33 -1
  92. package/src/config/autonomous-remediation.ts +21 -0
  93. package/src/config/provider-validation.ts +14 -0
  94. package/src/config/rebase-provenance.ts +68 -0
  95. package/src/config.ts +191 -17
  96. package/src/generated/compatibility-version.json +279 -159
  97. package/src/generated/model-metadata.ts +3 -0
  98. package/src/images/loop.ts +5 -4
  99. package/src/lab/conformance/fixtures/protocol-v1-cases.json +1 -1
  100. package/src/lab/fabric/producer-child.ts +1 -1
  101. package/src/lib/config-ownership.ts +20 -0
  102. package/src/lib/errors.ts +11 -2
  103. package/src/lib/package-tree-integrity.ts +101 -0
  104. package/src/oauth/aistudio-credentials.ts +65 -0
  105. package/src/oauth/aistudio-native-daemon.ts +116 -0
  106. package/src/oauth/aistudio-session-sync.ts +95 -0
  107. package/src/oauth/generic-account-failover.ts +231 -0
  108. package/src/oauth/google-aistudio-auth.ts +98 -0
  109. package/src/oauth/index.ts +57 -5
  110. package/src/oauth/key-providers.ts +18 -1
  111. package/src/oauth/kiro.ts +45 -0
  112. package/src/oauth/login-cli.ts +65 -1
  113. package/src/oauth/types.ts +15 -0
  114. package/src/providers/codex-capacity.ts +5 -2
  115. package/src/providers/command-code-efforts.ts +38 -6
  116. package/src/providers/context-cap.ts +4 -3
  117. package/src/providers/default-aliases.ts +65 -0
  118. package/src/providers/derive.ts +29 -1
  119. package/src/providers/fastwire.ts +7 -1
  120. package/src/providers/model-presets.ts +119 -0
  121. package/src/providers/new-model-policy.ts +146 -0
  122. package/src/providers/provider-id-rewrite.ts +2 -1
  123. package/src/providers/quota.ts +157 -46
  124. package/src/providers/registry.ts +184 -71
  125. package/src/providers/slug-codec.ts +52 -0
  126. package/src/responses/code-mode-helper-compat.ts +50 -0
  127. package/src/responses/custom-tool-compat.ts +34 -10
  128. package/src/responses/parser.ts +4 -0
  129. package/src/responses/schema.ts +5 -1
  130. package/src/responses/thought-signature-replay.ts +17 -0
  131. package/src/router.ts +43 -2
  132. package/src/routing/account-pool/cooldown.ts +8 -0
  133. package/src/routing/account-pool/index.ts +1 -0
  134. package/src/routing/analytics.ts +1 -0
  135. package/src/routing/quota.ts +10 -0
  136. package/src/server/auth-cors.ts +24 -0
  137. package/src/server/chat-completions.ts +26 -16
  138. package/src/server/chat-native-sse.ts +3 -3
  139. package/src/server/chat-native.ts +30 -11
  140. package/src/server/claude-messages.ts +1 -1
  141. package/src/server/effort-policy.ts +16 -0
  142. package/src/server/index.ts +180 -14
  143. package/src/server/lifecycle.ts +52 -1
  144. package/src/server/management/agent-settings-routes.ts +31 -15
  145. package/src/server/management/codex-prompt-routes.ts +570 -0
  146. package/src/server/management/combo-routes.ts +2 -1
  147. package/src/server/management/config-routes.ts +27 -9
  148. package/src/server/management/context.ts +9 -0
  149. package/src/server/management/logs-usage-routes.ts +11 -5
  150. package/src/server/management/model-routes.ts +266 -0
  151. package/src/server/management/oauth-account-routes.ts +13 -3
  152. package/src/server/management/provider-routes.ts +137 -3
  153. package/src/server/management/routing-profile-routes.ts +2 -2
  154. package/src/server/management-api.ts +2 -0
  155. package/src/server/port-reclaim.ts +19 -1
  156. package/src/server/relay-eager.ts +147 -20
  157. package/src/server/relay.ts +251 -19
  158. package/src/server/request-log-conversation.ts +33 -0
  159. package/src/server/request-log.ts +48 -21
  160. package/src/server/responses/collaboration.ts +42 -5
  161. package/src/server/responses/combo-stream-preflight.ts +10 -3
  162. package/src/server/responses/core.ts +575 -140
  163. package/src/server/responses/empty-completion-guard.ts +35 -0
  164. package/src/server/responses/fetch-helpers.ts +14 -6
  165. package/src/server/responses/input-admission.ts +3 -1
  166. package/src/server/responses/passthrough-error.ts +33 -9
  167. package/src/server/responses/policy-fallback.ts +1 -1
  168. package/src/server/responses/responses-field-backfill.ts +105 -13
  169. package/src/server/responses/ws-upstream.ts +35 -5
  170. package/src/server/responses-custom-tool-repair.ts +52 -7
  171. package/src/server/responses-terminal-repair.ts +25 -4
  172. package/src/server/sse-frame-buffer.ts +31 -4
  173. package/src/server/ws-bridge.ts +14 -2
  174. package/src/smoke/fingerprint-cache.ts +133 -0
  175. package/src/smoke/live-scenarios.ts +33 -0
  176. package/src/smoke/runner.ts +119 -0
  177. package/src/telemetry/dispatcher.ts +44 -0
  178. package/src/telemetry/fingerprint.ts +24 -0
  179. package/src/telemetry/hook.ts +43 -0
  180. package/src/telemetry/ledger.ts +54 -0
  181. package/src/telemetry/types.ts +23 -0
  182. package/src/types/config.ts +66 -14
  183. package/src/types/provider.ts +79 -1
  184. package/src/types/request.ts +18 -10
  185. package/src/types/tools.ts +30 -11
  186. package/src/types.ts +1 -0
  187. package/src/usage/command-code-manifest.ts +116 -0
  188. package/src/usage/cost.ts +2 -2
  189. package/src/usage/expected-prices.ts +126 -24
  190. package/src/usage/log.ts +18 -8
  191. package/src/usage/summary.ts +34 -12
  192. package/src/web-search/exa-executor.ts +40 -9
  193. package/src/web-search/index.ts +16 -8
  194. package/src/web-search/loop.ts +5 -4
  195. package/gui/dist/assets/index-DKLr4LTE.js +0 -102
  196. package/gui/dist/assets/index-DrSQdTRd.css +0 -1
@@ -6,6 +6,7 @@ import { COMPACT_PROMPT, compactionItemToText, decodeCompactionSummary, isCompac
6
6
  import { collectResponsesToolGroups } from "../responses/tool-groups";
7
7
  import { isHostedToolUnsupportedForModel } from "../responses/hosted-tool-policy";
8
8
  import { decodeServerSentEvents } from "../lib/sse-decoder";
9
+ import { debugProviderDiagnostic } from "../lib/debug";
9
10
  import {
10
11
  CODEX_FORWARD_BASE_URL,
11
12
  destinationDecodesNativeCompactionBlob,
@@ -20,6 +21,11 @@ import { rewriteRoutedToolSearchForUpstream } from "../responses/tool-search-com
20
21
  import { rewriteRoutedNamespaceToolsForUpstream } from "../responses/namespace-tool-compat";
21
22
  import { openaiResponsesUrl } from "./openai-responses-url";
22
23
  import { normalizeXaiResponsesWebSearch } from "./xai-web-search";
24
+ import {
25
+ isXaiSchemaTarget,
26
+ normalizeXaiToolParameters,
27
+ XaiToolSchemaCompatibilityError,
28
+ } from "./xai-tool-schema";
23
29
  import {
24
30
  createAdapterTierMetadata,
25
31
  } from "../providers/fastwire";
@@ -38,6 +44,7 @@ export const FORWARD_HEADERS = [
38
44
  "x-codex-beta-features",
39
45
  "x-codex-installation-id",
40
46
  "x-codex-parent-thread-id",
47
+ "x-session-id",
41
48
  "x-codex-turn-metadata",
42
49
  "x-codex-turn-state",
43
50
  "x-codex-window-id",
@@ -46,6 +53,15 @@ export const FORWARD_HEADERS = [
46
53
  "x-responsesapi-include-timing-metrics",
47
54
  ];
48
55
 
56
+ /**
57
+ * Sanitize reasoning input by field policy, not by preserving each item's shape. Retaining a
58
+ * native `encrypted_content` guarantees only that blob value: `status` is always removed;
59
+ * proxy-owned `ocxr1:` envelopes are always removed; and native blobs are removed when the caller
60
+ * requests stripping after a route-identity change or opaque-blob recovery. On routed/non-OpenAI
61
+ * destinations, a present non-array `content` field is omitted. Otherwise non-empty array content
62
+ * is blanked unless raw reasoning preservation is enabled; removing an `ocxr1:` envelope selects
63
+ * the same blanking path when non-array omission is not active.
64
+ */
49
65
  export function sanitizeReasoningInputContent(
50
66
  body: unknown,
51
67
  opts?: {
@@ -77,12 +93,11 @@ export function sanitizeReasoningInputContent(
77
93
  // rather than the field it actually refused, which is why this reads as a blob failure. Drop the
78
94
  // key so the item matches the shape the upstream issued.
79
95
  //
80
- // Gated to routed destinations. An OpenAI-operated backend binds the blob to the item's exact
81
- // shape, so deleting a field there invalidates it (`The encrypted content ... could not be
82
- // verified`); the two requirements are exactly opposed, and a live regression proved it. That
83
- // gate is also why this drop may touch an item that keeps its blob: xAI demonstrably accepts its
84
- // own blob without the null channel, and the destinations that bind blobs to item shape never
85
- // reach this branch. This is independent of the output-only status removal below.
96
+ // Gated to routed destinations. An OpenAI-operated backend rejects a blob-bearing item when its
97
+ // null `content` channel is deleted (`The encrypted content ... could not be verified`); that
98
+ // live result establishes this channel constraint, not whole-item shape preservation. The gate
99
+ // is also why this drop may touch an item that keeps its blob: xAI demonstrably accepts its own
100
+ // blob without the null channel. This is independent of the output-only status removal below.
86
101
  const dropNullContentChannel = opts?.dropNullContentChannel === true
87
102
  && "content" in rec && !Array.isArray(rec.content);
88
103
  // `status` is output-only. Measured OpenAI reasoning items never contain it, and Grok accepts
@@ -368,6 +383,27 @@ function stripDisabledReasoningSummaries(
368
383
  };
369
384
  }
370
385
 
386
+ /**
387
+ * Hide a no-op Responses verbosity control from the wire as well as the catalog. This runs at
388
+ * final serialization so a stale catalog or direct caller cannot bypass the capability. Other
389
+ * `text` settings (notably structured-output `format`) remain untouched.
390
+ */
391
+ function stripDisabledVerbosity(
392
+ body: unknown,
393
+ provider: OcxProviderConfig,
394
+ modelId: string,
395
+ ): unknown {
396
+ if (modelRecordValue(provider.modelSupportsVerbosity, modelId) !== false || !isPlainObject(body)) {
397
+ return body;
398
+ }
399
+ if (!isPlainObject(body.text) || !Object.hasOwn(body.text, "verbosity")) return body;
400
+ const { verbosity: _verbosity, ...rest } = body.text;
401
+ return {
402
+ ...body,
403
+ ...(Object.keys(rest).length > 0 ? { text: rest } : { text: undefined }),
404
+ };
405
+ }
406
+
371
407
  /**
372
408
  * Normalize only the delivery enum Codex already emitted. Do not inject a field into callers that
373
409
  * did not request summaries, and leave every unconfigured provider/model byte-for-byte unchanged.
@@ -502,8 +538,12 @@ function isPlainObject(v: unknown): v is Record<string, unknown> {
502
538
  return !!v && typeof v === "object" && !Array.isArray(v);
503
539
  }
504
540
 
505
- function normalizeFunctionToolSchema(tool: unknown): unknown {
541
+ function normalizeFunctionToolSchema(tool: unknown, xaiTarget: boolean): unknown | undefined {
506
542
  if (!isPlainObject(tool) || tool.type !== "function") return tool;
543
+ if (xaiTarget) {
544
+ const parameters = normalizeXaiToolParameters(isPlainObject(tool.parameters) ? tool.parameters : {});
545
+ return parameters === undefined ? undefined : { ...tool, parameters };
546
+ }
507
547
  if (isPlainObject(tool.parameters) && tool.parameters.type === "object") return tool;
508
548
  return {
509
549
  ...tool,
@@ -511,16 +551,69 @@ function normalizeFunctionToolSchema(tool: unknown): unknown {
511
551
  };
512
552
  }
513
553
 
514
- function normalizeToolSchemas(body: unknown): unknown {
554
+ /**
555
+ * Re-point `tool_choice` after an incompatible function was dropped from the catalog. Names here
556
+ * are already wire names, because namespace lowering rewrote the declarations and the selector
557
+ * together before this runs. A selector left naming an omitted tool reaches Grok as a dangling
558
+ * reference it rejects, and silently relaxing it to `auto` is worse: the turn would quietly
559
+ * proceed without the tool the caller required. So an `allowed_tools` list drops the omitted
560
+ * entries while any remain, and a selection with nothing left to point at fails locally with the
561
+ * same 400 the caller gets for a tool catalog this proxy cannot lower.
562
+ */
563
+ function reconcileToolChoiceForOmittedTools(
564
+ body: Record<string, unknown>,
565
+ omittedFunctionNames: ReadonlySet<string>,
566
+ ): Record<string, unknown> {
567
+ if (omittedFunctionNames.size === 0) return body;
568
+ const toolChoice = body.tool_choice;
569
+ if (!isPlainObject(toolChoice)) return body;
570
+
571
+ const refuse = (name: string): never => {
572
+ throw new XaiToolSchemaCompatibilityError(
573
+ `tool_choice requires function "${name}", but its parameter schema cannot be represented for this destination; `
574
+ + "relax tool_choice or simplify the tool's parameter schema",
575
+ );
576
+ };
577
+
578
+ if (toolChoice.type === "function" && typeof toolChoice.name === "string") {
579
+ return omittedFunctionNames.has(toolChoice.name) ? refuse(toolChoice.name) : body;
580
+ }
581
+
582
+ if (toolChoice.type === "allowed_tools" && Array.isArray(toolChoice.tools)) {
583
+ const omitted = toolChoice.tools.filter(tool =>
584
+ isPlainObject(tool)
585
+ && tool.type === "function"
586
+ && typeof tool.name === "string"
587
+ && omittedFunctionNames.has(tool.name));
588
+ if (omitted.length === 0) return body;
589
+ const kept = toolChoice.tools.filter(tool => !omitted.includes(tool));
590
+ if (kept.length === 0) {
591
+ const first = omitted[0];
592
+ return refuse(isPlainObject(first) && typeof first.name === "string" ? first.name : "unknown");
593
+ }
594
+ return { ...body, tool_choice: { ...toolChoice, tools: kept } };
595
+ }
596
+
597
+ return body;
598
+ }
599
+
600
+ function normalizeToolSchemas(body: unknown, xaiTarget: boolean): unknown {
515
601
  if (!isPlainObject(body)) return body;
516
602
 
603
+ const omittedFunctionNames = new Set<string>();
517
604
  const normalizeTools = (tools: unknown[]): unknown[] => {
518
605
  let changed = false;
519
- const normalized = tools.map((tool) => {
520
- const fixed = normalizeFunctionToolSchema(tool);
606
+ const normalized: unknown[] = [];
607
+ for (const tool of tools) {
608
+ const fixed = normalizeFunctionToolSchema(tool, xaiTarget);
609
+ if (fixed === undefined) {
610
+ changed = true;
611
+ if (isPlainObject(tool) && typeof tool.name === "string") omittedFunctionNames.add(tool.name);
612
+ continue;
613
+ }
521
614
  if (fixed !== tool) changed = true;
522
- return fixed;
523
- });
615
+ normalized.push(fixed);
616
+ }
524
617
  return changed ? normalized : tools;
525
618
  };
526
619
 
@@ -540,7 +633,14 @@ function normalizeToolSchemas(body: unknown): unknown {
540
633
  });
541
634
  if (inputChanged) normalizedBody = { ...normalizedBody, input };
542
635
  }
543
- return normalizedBody;
636
+ if (omittedFunctionNames.size > 0) {
637
+ // A dropped tool is a capability the caller declared and will not get, and the only other
638
+ // trace of it is a turn that never makes the call. Name them so the cause is recoverable.
639
+ debugProviderDiagnostic("openai-responses", "tool-schema-omitted", {
640
+ omitted: [...omittedFunctionNames],
641
+ });
642
+ }
643
+ return reconcileToolChoiceForOmittedTools(normalizedBody, omittedFunctionNames);
544
644
  }
545
645
 
546
646
  function activateDeferredTool(tool: Record<string, unknown>): Record<string, unknown> {
@@ -1075,6 +1175,143 @@ function stripUnsupportedForwardParams(body: unknown): unknown {
1075
1175
  return rest;
1076
1176
  }
1077
1177
 
1178
+ /** Return the lossless text represented by one system message, or null when it is multimodal. */
1179
+ function canonicalForwardSystemText(item: Record<string, unknown>): string | null {
1180
+ const content = item.content;
1181
+ if (content === undefined) return "";
1182
+ if (typeof content === "string") return content;
1183
+ if (!Array.isArray(content)) return null;
1184
+ let text = "";
1185
+ for (const block of content) {
1186
+ if (!isPlainObject(block)) return null;
1187
+ if (block.type !== "input_text" && block.type !== "text") return null;
1188
+ if (typeof block.text !== "string") return null;
1189
+ text += block.text;
1190
+ }
1191
+ return text;
1192
+ }
1193
+
1194
+ /**
1195
+ * The public Responses API accepts input system messages and `truncation`, but the canonical
1196
+ * ChatGPT Codex forward endpoint rejects both. Fold only fully textual system messages into the
1197
+ * existing top-level instructions and remove the unsupported flag at this destination boundary.
1198
+ *
1199
+ * The fold is atomic: if any system message contains a non-text block, keep every message in
1200
+ * place so the proxy never silently drops multimodal content. The backend may still reject that
1201
+ * unsupported shape, but it will not receive a partially rewritten prompt.
1202
+ */
1203
+ function normalizeCanonicalForwardPromptEnvelope(body: unknown): unknown {
1204
+ if (!isPlainObject(body)) return body;
1205
+ const stripTruncation = Object.hasOwn(body, "truncation");
1206
+ const input = Array.isArray(body.input) ? body.input : undefined;
1207
+ if (!input) {
1208
+ if (!stripTruncation) return body;
1209
+ const { truncation: _truncation, ...rest } = body;
1210
+ return rest;
1211
+ }
1212
+
1213
+ const foldedText: string[] = [];
1214
+ let sawSystemMessage = false;
1215
+ let canFoldAllSystemMessages = true;
1216
+ for (const item of input) {
1217
+ if (!isPlainObject(item) || item.role !== "system") continue;
1218
+ sawSystemMessage = true;
1219
+ const text = canonicalForwardSystemText(item);
1220
+ if (text === null) {
1221
+ canFoldAllSystemMessages = false;
1222
+ break;
1223
+ }
1224
+ foldedText.push(text);
1225
+ }
1226
+ if (!stripTruncation && (!sawSystemMessage || !canFoldAllSystemMessages)) return body;
1227
+
1228
+ const next: Record<string, unknown> = { ...body };
1229
+ if (stripTruncation) delete next.truncation;
1230
+ if (sawSystemMessage && canFoldAllSystemMessages) {
1231
+ next.input = input.filter(item => !isPlainObject(item) || item.role !== "system");
1232
+ const folded = foldedText.join("\n\n");
1233
+ if (folded !== "") {
1234
+ const existing = typeof body.instructions === "string" ? body.instructions : "";
1235
+ next.instructions = existing !== "" ? `${existing}\n\n${folded}` : folded;
1236
+ }
1237
+ }
1238
+ return next;
1239
+ }
1240
+
1241
+ const POSIT_CACHE_MARKER_MAX_DEPTH = 64;
1242
+ const POSIT_CACHE_MARKER_MAX_NODES = 100_000;
1243
+
1244
+ type PromptCacheMarkerRewrite = {
1245
+ value: unknown;
1246
+ changed: boolean;
1247
+ complete: boolean;
1248
+ };
1249
+
1250
+ /**
1251
+ * Remove Posit/Anthropic-style prompt-cache markers without trusting request nesting. The walk
1252
+ * aborts atomically when its depth or node budget is exceeded, so a hostile extension object can
1253
+ * neither overflow the stack nor receive a partially rewritten subtree.
1254
+ */
1255
+ function stripPromptCacheBreakpoints(
1256
+ value: unknown,
1257
+ state: { nodes: number },
1258
+ depth = 0,
1259
+ ): PromptCacheMarkerRewrite {
1260
+ state.nodes += 1;
1261
+ if (depth > POSIT_CACHE_MARKER_MAX_DEPTH || state.nodes > POSIT_CACHE_MARKER_MAX_NODES) {
1262
+ return { value, changed: false, complete: false };
1263
+ }
1264
+ if (Array.isArray(value)) {
1265
+ let changed = false;
1266
+ const next: unknown[] = [];
1267
+ for (const entry of value) {
1268
+ const rewritten = stripPromptCacheBreakpoints(entry, state, depth + 1);
1269
+ if (!rewritten.complete) return { value, changed: false, complete: false };
1270
+ changed ||= rewritten.changed;
1271
+ next.push(rewritten.value);
1272
+ }
1273
+ return { value: changed ? next : value, changed, complete: true };
1274
+ }
1275
+ if (!isPlainObject(value)) return { value, changed: false, complete: true };
1276
+
1277
+ let changed = Object.hasOwn(value, "prompt_cache_breakpoint");
1278
+ const next: Record<string, unknown> = {};
1279
+ for (const [key, entry] of Object.entries(value)) {
1280
+ if (key === "prompt_cache_breakpoint") continue;
1281
+ const rewritten = stripPromptCacheBreakpoints(entry, state, depth + 1);
1282
+ if (!rewritten.complete) return { value, changed: false, complete: false };
1283
+ changed ||= rewritten.changed;
1284
+ next[key] = rewritten.value;
1285
+ }
1286
+ return { value: changed ? next : value, changed, complete: true };
1287
+ }
1288
+
1289
+ /**
1290
+ * Posit Assistant can replay client-only cache markers and stored-item references on a
1291
+ * `store: false` continuation. The canonical ChatGPT Codex backend rejects both. Remove the
1292
+ * markers recursively and drop only `item_reference` rows that cannot name persisted state;
1293
+ * ordinary item ids are handled later by stripItemIdsWhenUnstored and tool call_id pairs remain.
1294
+ */
1295
+ function normalizeCanonicalForwardContinuationEnvelope(body: unknown): unknown {
1296
+ if (!isPlainObject(body) || !Array.isArray(body.input)) return body;
1297
+ let input: unknown[] = body.input;
1298
+ let changed = false;
1299
+ if (body.store === false) {
1300
+ const withoutReferences = input.filter(item => !isPlainObject(item) || item.type !== "item_reference");
1301
+ if (withoutReferences.length !== input.length) {
1302
+ input = withoutReferences;
1303
+ changed = true;
1304
+ }
1305
+ }
1306
+
1307
+ const markerRewrite = stripPromptCacheBreakpoints(input, { nodes: 0 });
1308
+ if (markerRewrite.complete && markerRewrite.changed) {
1309
+ input = markerRewrite.value as unknown[];
1310
+ changed = true;
1311
+ }
1312
+ return changed ? { ...body, input } : body;
1313
+ }
1314
+
1078
1315
  const IMAGE_GEN_NAMESPACE = "image_gen";
1079
1316
  const HOSTED_IMAGE_GENERATION_TOOL = "image_generation";
1080
1317
  const IMAGE_GEN_DOTTED_PREFIX = `${IMAGE_GEN_NAMESPACE}.`;
@@ -1555,6 +1792,57 @@ export function stripOpenAiOnlyWebSearchFields(body: unknown): unknown {
1555
1792
  return changed ? next : body;
1556
1793
  }
1557
1794
 
1795
+ /**
1796
+ * OpenCode Zen / Go Muse Spark Responses gateway refuses `search_content_types`
1797
+ * on a plain `web_search` tool (400) but accepts it on `web_search_preview`; a
1798
+ * plain `web_search` is also accepted. Probed directly against the gateway on
1799
+ * 2026-08-26: `web_search` + `search_content_types` -> 400, `web_search_preview`
1800
+ * + `search_content_types` -> 200, plain `web_search` -> 200. Luna accepts every
1801
+ * shape, so this is Muse-only. Drop only the field the gateway refuses while
1802
+ * keeping the tool type and every other accepted option intact.
1803
+ */
1804
+ function stripMuseSparkUnsupportedWebSearchFields(body: unknown, modelId: unknown): unknown {
1805
+ if (!isPlainObject(body)) return body;
1806
+ if (typeof modelId !== "string" || modelId.trim().toLowerCase() !== "muse-spark-1.2-contributor") return body;
1807
+
1808
+ const rewriteTools = (tools: unknown[]): { tools: unknown[]; changed: boolean } => {
1809
+ let changed = false;
1810
+ const rewritten = tools.map(tool => {
1811
+ if (!isPlainObject(tool) || tool.type !== "web_search") return tool;
1812
+ if (!Object.hasOwn(tool, "search_content_types")) return tool;
1813
+ const { search_content_types: _dropped, ...rest } = tool;
1814
+ changed = true;
1815
+ return rest;
1816
+ });
1817
+ return { tools: changed ? rewritten : tools, changed };
1818
+ };
1819
+
1820
+ let next: Record<string, unknown> = body;
1821
+ let changed = false;
1822
+ if (Array.isArray(body.tools)) {
1823
+ const rewritten = rewriteTools(body.tools);
1824
+ if (rewritten.changed) {
1825
+ next = { ...next, tools: rewritten.tools };
1826
+ changed = true;
1827
+ }
1828
+ }
1829
+ if (Array.isArray(next.input)) {
1830
+ let inputChanged = false;
1831
+ const input = next.input.map(item => {
1832
+ if (!isPlainObject(item) || item.type !== "additional_tools" || !Array.isArray(item.tools)) return item;
1833
+ const rewritten = rewriteTools(item.tools);
1834
+ if (!rewritten.changed) return item;
1835
+ inputChanged = true;
1836
+ return { ...item, tools: rewritten.tools };
1837
+ });
1838
+ if (inputChanged) {
1839
+ next = { ...next, input };
1840
+ changed = true;
1841
+ }
1842
+ }
1843
+ return changed ? next : body;
1844
+ }
1845
+
1558
1846
  /** Replace every `input_image` part under a routed-compaction body with a short marker. */
1559
1847
  function stripInputImagesDeep(value: unknown): unknown {
1560
1848
  if (Array.isArray(value)) return value.map(stripInputImagesDeep);
@@ -1714,6 +2002,8 @@ export function createResponsesPassthroughAdapter(provider: OcxProviderConfig):
1714
2002
  // third-party forward gateway may still accept it, so this must not be widened.
1715
2003
  if (isCanonicalOpenAiForwardProvider(provider)) {
1716
2004
  outBody = stripDeprecatedPromptCacheRetention(outBody, parsed.modelId);
2005
+ outBody = normalizeCanonicalForwardPromptEnvelope(outBody);
2006
+ outBody = normalizeCanonicalForwardContinuationEnvelope(outBody);
1717
2007
  }
1718
2008
  } else {
1719
2009
  outBody = preferConfiguredHostedTools(
@@ -1766,6 +2056,7 @@ export function createResponsesPassthroughAdapter(provider: OcxProviderConfig):
1766
2056
  if (provider.supportsOpenAiWebSearchToolFields === false) {
1767
2057
  outBody = stripOpenAiOnlyWebSearchFields(outBody);
1768
2058
  }
2059
+ outBody = stripMuseSparkUnsupportedWebSearchFields(outBody, parsed.modelId);
1769
2060
  // Last, so promoted namespace children are also cleared of Codex-private fields.
1770
2061
  outBody = stripCanonicalOnlyToolFields(outBody, provider.supportsOpenAiWebSearchToolFields === false);
1771
2062
  }
@@ -1778,17 +2069,37 @@ export function createResponsesPassthroughAdapter(provider: OcxProviderConfig):
1778
2069
  outBody = buildRoutedCompactionBody(outBody);
1779
2070
  }
1780
2071
  const threadServingIdentityChanged = parsed._stripReasoningEncryptedContent === true;
1781
- const sanitizedBody = normalizeToolSchemas(stripSparkCompatibility(stripUnsupportedReasoningParams(stripItemIdsWhenUnstored(stripInvalidItemIds(stripUnsupportedHostedTools(sanitizeReasoningInputContent(scrubOcxCompactionItems(
1782
- outBody,
1783
- destinationDecodesNativeCompactionBlob(provider),
1784
- threadServingIdentityChanged,
1785
- ), {
1786
- preserveRawReasoningContent: provider.preserveResponsesReasoningContent === true,
1787
- dropNullContentChannel: !isOpenAiOperatedResponsesDestination(provider),
1788
- stripEncryptedContent: threadServingIdentityChanged,
1789
- })))))));
1790
- const finalBody = stripDisabledReasoningSummaries(
1791
- normalizeConfiguredReasoningSummaryDelivery(sanitizedBody, provider, parsed.modelId),
2072
+ const sanitizedBody = normalizeToolSchemas(
2073
+ stripSparkCompatibility(
2074
+ stripUnsupportedReasoningParams(
2075
+ stripItemIdsWhenUnstored(
2076
+ stripInvalidItemIds(
2077
+ stripUnsupportedHostedTools(
2078
+ sanitizeReasoningInputContent(
2079
+ scrubOcxCompactionItems(
2080
+ outBody,
2081
+ destinationDecodesNativeCompactionBlob(provider),
2082
+ threadServingIdentityChanged,
2083
+ ),
2084
+ {
2085
+ preserveRawReasoningContent: provider.preserveResponsesReasoningContent === true,
2086
+ dropNullContentChannel: !isOpenAiOperatedResponsesDestination(provider),
2087
+ stripEncryptedContent: threadServingIdentityChanged,
2088
+ },
2089
+ ),
2090
+ ),
2091
+ ),
2092
+ ),
2093
+ ),
2094
+ ),
2095
+ isXaiSchemaTarget(provider),
2096
+ );
2097
+ const finalBody = stripDisabledVerbosity(
2098
+ stripDisabledReasoningSummaries(
2099
+ normalizeConfiguredReasoningSummaryDelivery(sanitizedBody, provider, parsed.modelId),
2100
+ provider,
2101
+ parsed.modelId,
2102
+ ),
1792
2103
  provider,
1793
2104
  parsed.modelId,
1794
2105
  );
@@ -4,6 +4,13 @@ type QueueReader = (result: IteratorResult<AdapterEvent>) => void;
4
4
 
5
5
  export const PREFLIGHT_HEARTBEAT_RETAIN_LIMIT = 16;
6
6
 
7
+ /**
8
+ * Coalescing threshold for adjacent text/thinking deltas buffered with no
9
+ * waiting reader (UTF-16 code units). This is a merge-size ceiling, not a
10
+ * byte-memory cap: a single oversized incoming event stays one item.
11
+ */
12
+ export const COALESCE_MAX_CHUNK_LENGTH = 64 * 1024;
13
+
7
14
  export interface AdapterEventQueue {
8
15
  push(event: AdapterEvent): void;
9
16
  close(): void;
@@ -64,6 +71,33 @@ export function createAdapterEventQueue(opts?: {
64
71
  const maxBacklog = opts?.maxBacklog ?? 1_024;
65
72
  let closed = false;
66
73
 
74
+ // Merge an incoming delta into the buffered tail when no reader is waiting.
75
+ // The backlog cap counts events, not tokens, so a detached or briefly
76
+ // stalled consumer (e.g. a Codex app mid-reconnect whose disconnect Bun has
77
+ // not yet delivered) used to hit the cap within seconds of token-granular
78
+ // streaming and abort a healthy turn. Adjacent same-phase text deltas,
79
+ // adjacent thinking deltas, and consecutive heartbeats carry no ordering
80
+ // information between themselves, so merging them preserves every consumer
81
+ // contract while making the cap approximate buffered items again.
82
+ // Pushed objects may be retained by adapters, so the tail is REPLACED with
83
+ // a fresh object — never mutated (alias safety).
84
+ const coalesceIntoTail = (event: AdapterEvent): boolean => {
85
+ const tail = queued[queued.length - 1];
86
+ if (!tail) return false;
87
+ if (event.type === "heartbeat") return tail.type === "heartbeat";
88
+ if (event.type === "text_delta" && tail.type === "text_delta" && tail.phase === event.phase) {
89
+ if (tail.text.length + event.text.length > COALESCE_MAX_CHUNK_LENGTH) return false;
90
+ queued[queued.length - 1] = { type: "text_delta", text: tail.text + event.text, phase: tail.phase };
91
+ return true;
92
+ }
93
+ if (event.type === "thinking_delta" && tail.type === "thinking_delta") {
94
+ if (tail.thinking.length + event.thinking.length > COALESCE_MAX_CHUNK_LENGTH) return false;
95
+ queued[queued.length - 1] = { type: "thinking_delta", thinking: tail.thinking + event.thinking };
96
+ return true;
97
+ }
98
+ return false;
99
+ };
100
+
67
101
  const push = (event: AdapterEvent): void => {
68
102
  if (closed) return;
69
103
  const reader = readers.shift();
@@ -71,9 +105,10 @@ export function createAdapterEventQueue(opts?: {
71
105
  reader({ done: false, value: event });
72
106
  return;
73
107
  }
108
+ if (coalesceIntoTail(event)) return;
74
109
  if (queued.length >= maxBacklog) {
75
110
  opts?.onBacklogExceeded?.();
76
- queued.push({ type: "error", message: "consumer backlog exceeded — turn aborted" });
111
+ queued.push({ type: "error", message: "consumer stalled: adapter event backlog exceeded — turn aborted" });
77
112
  close();
78
113
  return;
79
114
  }
@@ -28,7 +28,7 @@ const NEIGHBOR_AGENT_TOOL_NAMES = ["Read", "Grep", "Glob", "Bash", "LS"] as cons
28
28
  const CODEX_UNIFIED_EXEC_TOOL_NAME = "exec";
29
29
  const CODEX_SHELL_BRIDGE_TOOL_NAMES = ["exec_command", "shell_command"] as const;
30
30
 
31
- function isCodexCodeModeExecTool(tool: Pick<OcxTool, "namespace" | "name" | "freeform">): boolean {
31
+ export function isCodexCodeModeExecTool(tool: Pick<OcxTool, "namespace" | "name" | "freeform">): boolean {
32
32
  return !tool.namespace && tool.name === CODEX_UNIFIED_EXEC_TOOL_NAME && tool.freeform === true;
33
33
  }
34
34
 
@@ -45,7 +45,7 @@ function isCodexCodeModeExecTool(tool: Pick<OcxTool, "namespace" | "name" | "fre
45
45
  * `!tool.namespace` requirement; dropping it here made the name assert a check the body did not
46
46
  * perform.
47
47
  */
48
- function isBareShellBridgeTool(tool: Pick<OcxTool, "namespace" | "name">): boolean {
48
+ export function isBareShellBridgeTool(tool: Pick<OcxTool, "namespace" | "name">): boolean {
49
49
  return !tool.namespace && (CODEX_SHELL_BRIDGE_TOOL_NAMES as readonly string[]).includes(tool.name);
50
50
  }
51
51