@yansigit/opencodex 2.33.1 → 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 (177) 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 -3
  6. package/src/adapters/anthropic.ts +79 -2
  7. package/src/adapters/command-code.ts +40 -3
  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 +9 -9
  13. package/src/adapters/cursor/live-models.ts +7 -2
  14. package/src/adapters/cursor/live-transport.ts +14 -0
  15. package/src/adapters/cursor/message-mapper.ts +4 -1
  16. package/src/adapters/cursor/native-exec-shell.ts +103 -6
  17. package/src/adapters/cursor/native-exec.ts +20 -0
  18. package/src/adapters/cursor/protobuf-request.ts +74 -39
  19. package/src/adapters/cursor/request-builder.ts +32 -10
  20. package/src/adapters/cursor/tool-definitions.ts +13 -10
  21. package/src/adapters/cursor/tool-result-normalize.ts +35 -3
  22. package/src/adapters/cursor/types.ts +16 -4
  23. package/src/adapters/cursor.ts +97 -70
  24. package/src/adapters/google-antigravity-replay.ts +105 -25
  25. package/src/adapters/google-antigravity-wire.ts +5 -0
  26. package/src/adapters/google-errors.ts +41 -12
  27. package/src/adapters/google-http.ts +12 -11
  28. package/src/adapters/google.ts +156 -65
  29. package/src/adapters/image.ts +1 -1
  30. package/src/adapters/kiro-constants.ts +15 -0
  31. package/src/adapters/kiro-tools.ts +43 -15
  32. package/src/adapters/kiro.ts +54 -9
  33. package/src/adapters/openai-chat.ts +286 -242
  34. package/src/adapters/openai-responses.ts +334 -24
  35. package/src/adapters/run-turn-queue.ts +36 -1
  36. package/src/adapters/tool-catalog-nudge.ts +2 -2
  37. package/src/adapters/xai-tool-schema.ts +436 -0
  38. package/src/bridge.ts +67 -26
  39. package/src/chat/inbound.ts +14 -1
  40. package/src/chat/outbound.ts +15 -7
  41. package/src/claude/agents-inject.ts +8 -1
  42. package/src/claude/outbound.ts +10 -8
  43. package/src/cli/account-api.ts +27 -7
  44. package/src/cli/account-extended.ts +10 -3
  45. package/src/cli/account.ts +29 -5
  46. package/src/cli/alias.ts +66 -0
  47. package/src/cli/claude.ts +26 -1
  48. package/src/cli/dispatch.ts +13 -1
  49. package/src/cli/help.ts +1 -0
  50. package/src/cli/index.ts +5 -0
  51. package/src/cli/init.ts +1 -0
  52. package/src/cli/models-runtime.ts +95 -0
  53. package/src/cli/models.ts +13 -7
  54. package/src/cli/provider-runtime.ts +16 -2
  55. package/src/cli/registry.ts +6 -1
  56. package/src/cli/telemetry-commands.ts +25 -0
  57. package/src/cli/v2.ts +34 -10
  58. package/src/codex/account-pause.ts +2 -1
  59. package/src/codex/account-priority.ts +3 -2
  60. package/src/codex/app-server-processes.ts +80 -6
  61. package/src/codex/auth-api.ts +48 -8
  62. package/src/codex/auth-context.ts +21 -18
  63. package/src/codex/catalog/aggregation.ts +6 -0
  64. package/src/codex/catalog/model-metadata.ts +13 -1
  65. package/src/codex/catalog/native-models.ts +5 -2
  66. package/src/codex/catalog/parsing.ts +16 -0
  67. package/src/codex/catalog/provider-fetch.ts +20 -37
  68. package/src/codex/catalog/sync.ts +127 -2
  69. package/src/codex/catalog.ts +1 -1
  70. package/src/codex/codex-write-lock.ts +3 -1
  71. package/src/codex/convergence-types.ts +1 -1
  72. package/src/codex/convergence.ts +22 -2
  73. package/src/codex/desired-state.ts +2 -2
  74. package/src/codex/desktop-app-restart.ts +18 -5
  75. package/src/codex/inject-coordination.ts +83 -0
  76. package/src/codex/inject.ts +14 -1
  77. package/src/codex/log-guard/inspect.ts +22 -4
  78. package/src/codex/model-entitlements.ts +9 -2
  79. package/src/codex/prompt-layers.ts +371 -25
  80. package/src/codex/prompt-text-probe.ts +238 -0
  81. package/src/codex/quota.ts +123 -18
  82. package/src/codex/routing.ts +9 -0
  83. package/src/codex/subagent-model-fallback.ts +198 -27
  84. package/src/codex/transition-state.ts +107 -8
  85. package/src/combos/types.ts +10 -0
  86. package/src/compatibility/openai-responses.ts +33 -1
  87. package/src/config/autonomous-remediation.ts +21 -0
  88. package/src/config/provider-validation.ts +14 -0
  89. package/src/config/rebase-provenance.ts +68 -0
  90. package/src/config.ts +191 -17
  91. package/src/generated/compatibility-version.json +229 -153
  92. package/src/images/loop.ts +5 -4
  93. package/src/lab/conformance/fixtures/protocol-v1-cases.json +1 -1
  94. package/src/lab/fabric/producer-child.ts +1 -1
  95. package/src/lib/config-ownership.ts +20 -0
  96. package/src/lib/errors.ts +11 -2
  97. package/src/lib/package-tree-integrity.ts +101 -0
  98. package/src/oauth/aistudio-credentials.ts +65 -0
  99. package/src/oauth/aistudio-native-daemon.ts +54 -0
  100. package/src/oauth/generic-account-failover.ts +231 -0
  101. package/src/oauth/index.ts +57 -5
  102. package/src/oauth/key-providers.ts +10 -1
  103. package/src/oauth/kiro.ts +45 -0
  104. package/src/oauth/login-cli.ts +19 -20
  105. package/src/oauth/types.ts +15 -0
  106. package/src/providers/codex-capacity.ts +5 -2
  107. package/src/providers/command-code-efforts.ts +38 -6
  108. package/src/providers/context-cap.ts +4 -3
  109. package/src/providers/default-aliases.ts +65 -0
  110. package/src/providers/derive.ts +28 -0
  111. package/src/providers/fastwire.ts +7 -1
  112. package/src/providers/model-presets.ts +119 -0
  113. package/src/providers/new-model-policy.ts +146 -0
  114. package/src/providers/provider-id-rewrite.ts +2 -1
  115. package/src/providers/quota.ts +73 -14
  116. package/src/providers/registry.ts +160 -68
  117. package/src/providers/slug-codec.ts +52 -0
  118. package/src/responses/code-mode-helper-compat.ts +50 -0
  119. package/src/responses/custom-tool-compat.ts +34 -10
  120. package/src/responses/parser.ts +4 -0
  121. package/src/responses/schema.ts +5 -1
  122. package/src/responses/thought-signature-replay.ts +17 -0
  123. package/src/router.ts +40 -2
  124. package/src/routing/analytics.ts +1 -0
  125. package/src/routing/quota.ts +10 -0
  126. package/src/server/auth-cors.ts +23 -0
  127. package/src/server/chat-completions.ts +24 -16
  128. package/src/server/chat-native-sse.ts +3 -3
  129. package/src/server/chat-native.ts +30 -11
  130. package/src/server/claude-messages.ts +1 -1
  131. package/src/server/effort-policy.ts +16 -0
  132. package/src/server/index.ts +152 -80
  133. package/src/server/lifecycle.ts +52 -1
  134. package/src/server/management/agent-settings-routes.ts +31 -15
  135. package/src/server/management/codex-prompt-routes.ts +570 -0
  136. package/src/server/management/combo-routes.ts +2 -1
  137. package/src/server/management/config-routes.ts +27 -9
  138. package/src/server/management/context.ts +9 -0
  139. package/src/server/management/logs-usage-routes.ts +1 -1
  140. package/src/server/management/model-routes.ts +266 -0
  141. package/src/server/management/provider-routes.ts +137 -3
  142. package/src/server/management/routing-profile-routes.ts +2 -2
  143. package/src/server/management-api.ts +2 -0
  144. package/src/server/relay-eager.ts +147 -20
  145. package/src/server/relay.ts +251 -19
  146. package/src/server/request-log-conversation.ts +21 -0
  147. package/src/server/request-log.ts +46 -20
  148. package/src/server/responses/collaboration.ts +42 -5
  149. package/src/server/responses/combo-stream-preflight.ts +10 -3
  150. package/src/server/responses/core.ts +571 -137
  151. package/src/server/responses/empty-completion-guard.ts +35 -0
  152. package/src/server/responses/fetch-helpers.ts +14 -6
  153. package/src/server/responses/input-admission.ts +3 -1
  154. package/src/server/responses/passthrough-error.ts +33 -9
  155. package/src/server/responses/responses-field-backfill.ts +105 -13
  156. package/src/server/responses/ws-upstream.ts +35 -5
  157. package/src/server/responses-custom-tool-repair.ts +52 -7
  158. package/src/server/responses-terminal-repair.ts +25 -4
  159. package/src/server/sse-frame-buffer.ts +31 -4
  160. package/src/server/ws-bridge.ts +15 -4
  161. package/src/telemetry/dispatcher.ts +44 -0
  162. package/src/telemetry/fingerprint.ts +24 -0
  163. package/src/telemetry/hook.ts +43 -0
  164. package/src/telemetry/ledger.ts +54 -0
  165. package/src/telemetry/types.ts +23 -0
  166. package/src/types/config.ts +66 -14
  167. package/src/types/provider.ts +77 -0
  168. package/src/types/request.ts +16 -10
  169. package/src/types/tools.ts +20 -25
  170. package/src/types.ts +1 -0
  171. package/src/usage/expected-prices.ts +43 -24
  172. package/src/usage/log.ts +17 -7
  173. package/src/web-search/exa-executor.ts +40 -9
  174. package/src/web-search/loop.ts +5 -4
  175. package/gui/dist/assets/index-CIDo4y4k.js +0 -102
  176. package/gui/dist/assets/index-DrSQdTRd.css +0 -1
  177. package/src/server/aistudio-ws-hub.ts +0 -295
@@ -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";
@@ -47,6 +53,15 @@ export const FORWARD_HEADERS = [
47
53
  "x-responsesapi-include-timing-metrics",
48
54
  ];
49
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
+ */
50
65
  export function sanitizeReasoningInputContent(
51
66
  body: unknown,
52
67
  opts?: {
@@ -78,12 +93,11 @@ export function sanitizeReasoningInputContent(
78
93
  // rather than the field it actually refused, which is why this reads as a blob failure. Drop the
79
94
  // key so the item matches the shape the upstream issued.
80
95
  //
81
- // Gated to routed destinations. An OpenAI-operated backend binds the blob to the item's exact
82
- // shape, so deleting a field there invalidates it (`The encrypted content ... could not be
83
- // verified`); the two requirements are exactly opposed, and a live regression proved it. That
84
- // gate is also why this drop may touch an item that keeps its blob: xAI demonstrably accepts its
85
- // own blob without the null channel, and the destinations that bind blobs to item shape never
86
- // 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.
87
101
  const dropNullContentChannel = opts?.dropNullContentChannel === true
88
102
  && "content" in rec && !Array.isArray(rec.content);
89
103
  // `status` is output-only. Measured OpenAI reasoning items never contain it, and Grok accepts
@@ -369,6 +383,27 @@ function stripDisabledReasoningSummaries(
369
383
  };
370
384
  }
371
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
+
372
407
  /**
373
408
  * Normalize only the delivery enum Codex already emitted. Do not inject a field into callers that
374
409
  * did not request summaries, and leave every unconfigured provider/model byte-for-byte unchanged.
@@ -503,8 +538,12 @@ function isPlainObject(v: unknown): v is Record<string, unknown> {
503
538
  return !!v && typeof v === "object" && !Array.isArray(v);
504
539
  }
505
540
 
506
- function normalizeFunctionToolSchema(tool: unknown): unknown {
541
+ function normalizeFunctionToolSchema(tool: unknown, xaiTarget: boolean): unknown | undefined {
507
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
+ }
508
547
  if (isPlainObject(tool.parameters) && tool.parameters.type === "object") return tool;
509
548
  return {
510
549
  ...tool,
@@ -512,16 +551,69 @@ function normalizeFunctionToolSchema(tool: unknown): unknown {
512
551
  };
513
552
  }
514
553
 
515
- 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 {
516
601
  if (!isPlainObject(body)) return body;
517
602
 
603
+ const omittedFunctionNames = new Set<string>();
518
604
  const normalizeTools = (tools: unknown[]): unknown[] => {
519
605
  let changed = false;
520
- const normalized = tools.map((tool) => {
521
- 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
+ }
522
614
  if (fixed !== tool) changed = true;
523
- return fixed;
524
- });
615
+ normalized.push(fixed);
616
+ }
525
617
  return changed ? normalized : tools;
526
618
  };
527
619
 
@@ -541,7 +633,14 @@ function normalizeToolSchemas(body: unknown): unknown {
541
633
  });
542
634
  if (inputChanged) normalizedBody = { ...normalizedBody, input };
543
635
  }
544
- 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);
545
644
  }
546
645
 
547
646
  function activateDeferredTool(tool: Record<string, unknown>): Record<string, unknown> {
@@ -1076,6 +1175,143 @@ function stripUnsupportedForwardParams(body: unknown): unknown {
1076
1175
  return rest;
1077
1176
  }
1078
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
+
1079
1315
  const IMAGE_GEN_NAMESPACE = "image_gen";
1080
1316
  const HOSTED_IMAGE_GENERATION_TOOL = "image_generation";
1081
1317
  const IMAGE_GEN_DOTTED_PREFIX = `${IMAGE_GEN_NAMESPACE}.`;
@@ -1556,6 +1792,57 @@ export function stripOpenAiOnlyWebSearchFields(body: unknown): unknown {
1556
1792
  return changed ? next : body;
1557
1793
  }
1558
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
+
1559
1846
  /** Replace every `input_image` part under a routed-compaction body with a short marker. */
1560
1847
  function stripInputImagesDeep(value: unknown): unknown {
1561
1848
  if (Array.isArray(value)) return value.map(stripInputImagesDeep);
@@ -1715,6 +2002,8 @@ export function createResponsesPassthroughAdapter(provider: OcxProviderConfig):
1715
2002
  // third-party forward gateway may still accept it, so this must not be widened.
1716
2003
  if (isCanonicalOpenAiForwardProvider(provider)) {
1717
2004
  outBody = stripDeprecatedPromptCacheRetention(outBody, parsed.modelId);
2005
+ outBody = normalizeCanonicalForwardPromptEnvelope(outBody);
2006
+ outBody = normalizeCanonicalForwardContinuationEnvelope(outBody);
1718
2007
  }
1719
2008
  } else {
1720
2009
  outBody = preferConfiguredHostedTools(
@@ -1767,6 +2056,7 @@ export function createResponsesPassthroughAdapter(provider: OcxProviderConfig):
1767
2056
  if (provider.supportsOpenAiWebSearchToolFields === false) {
1768
2057
  outBody = stripOpenAiOnlyWebSearchFields(outBody);
1769
2058
  }
2059
+ outBody = stripMuseSparkUnsupportedWebSearchFields(outBody, parsed.modelId);
1770
2060
  // Last, so promoted namespace children are also cleared of Codex-private fields.
1771
2061
  outBody = stripCanonicalOnlyToolFields(outBody, provider.supportsOpenAiWebSearchToolFields === false);
1772
2062
  }
@@ -1779,17 +2069,37 @@ export function createResponsesPassthroughAdapter(provider: OcxProviderConfig):
1779
2069
  outBody = buildRoutedCompactionBody(outBody);
1780
2070
  }
1781
2071
  const threadServingIdentityChanged = parsed._stripReasoningEncryptedContent === true;
1782
- const sanitizedBody = normalizeToolSchemas(stripSparkCompatibility(stripUnsupportedReasoningParams(stripItemIdsWhenUnstored(stripInvalidItemIds(stripUnsupportedHostedTools(sanitizeReasoningInputContent(scrubOcxCompactionItems(
1783
- outBody,
1784
- destinationDecodesNativeCompactionBlob(provider),
1785
- threadServingIdentityChanged,
1786
- ), {
1787
- preserveRawReasoningContent: provider.preserveResponsesReasoningContent === true,
1788
- dropNullContentChannel: !isOpenAiOperatedResponsesDestination(provider),
1789
- stripEncryptedContent: threadServingIdentityChanged,
1790
- })))))));
1791
- const finalBody = stripDisabledReasoningSummaries(
1792
- 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
+ ),
1793
2103
  provider,
1794
2104
  parsed.modelId,
1795
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