@bitkyc08/opencodex 2.95.0 → 2.97.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 (276) hide show
  1. package/bin/ocx.mjs +214 -19
  2. package/gui/dist/assets/{App-8yedBkhm.js → App-DuNhggE1.js} +18 -18
  3. package/gui/dist/assets/{Tray-erSMzxPG.js → Tray-CEw0y0jR.js} +1 -1
  4. package/gui/dist/assets/index-CynE_Rue.js +94 -0
  5. package/gui/dist/assets/{quota-summary-BK4VuQNc.js → quota-summary-VHFSlUuM.js} +1 -1
  6. package/gui/dist/index.html +1 -1
  7. package/package.json +1 -1
  8. package/src/adapters/command-code.ts +15 -16
  9. package/src/adapters/cursor/transport-retry.ts +2 -2
  10. package/src/adapters/devin/cloud-direct/chat.ts +15 -6
  11. package/src/adapters/kiro/stream.ts +63 -4
  12. package/src/adapters/kiro-constants.ts +15 -1
  13. package/src/adapters/kiro-events.ts +31 -1
  14. package/src/adapters/kiro-retry.ts +3 -3
  15. package/src/adapters/ollama-native.ts +21 -7
  16. package/src/adapters/openai-responses/canonical-forward.ts +50 -13
  17. package/src/adapters/openai-responses/empty-assistant.ts +15 -3
  18. package/src/adapters/openai-responses/passthrough.ts +8 -8
  19. package/src/adapters/openai-responses/reasoning.ts +9 -4
  20. package/src/adapters/openai-responses/request-strips.ts +1 -1
  21. package/src/adapters/openai-responses/transport.ts +17 -26
  22. package/src/adapters/physical-send.ts +3 -3
  23. package/src/adapters/qoder/adapter.ts +1 -1
  24. package/src/adapters/qoder/image-input.ts +5 -2
  25. package/src/adapters/zed-openai-stream.ts +2 -1
  26. package/src/bridge/errors.ts +11 -2
  27. package/src/bridge/response-json.ts +2 -1
  28. package/src/bridge/sse.ts +14 -6
  29. package/src/chat/failure-verdict.ts +21 -0
  30. package/src/chat/outbound.ts +139 -21
  31. package/src/claude/outbound.ts +49 -2
  32. package/src/cli/agent.ts +44 -15
  33. package/src/cli/capabilities-agents-routing.ts +9 -0
  34. package/src/cli/capabilities-base.ts +25 -3
  35. package/src/cli/capabilities-command.ts +12 -3
  36. package/src/cli/capability-contracts.ts +2 -0
  37. package/src/cli/codex-launch-auth.ts +30 -1
  38. package/src/cli/codex-launcher.ts +12 -5
  39. package/src/cli/codex-shim-autorestore.ts +5 -4
  40. package/src/cli/dispatch.ts +11 -176
  41. package/src/cli/ensure-desired-integrations.ts +4 -3
  42. package/src/cli/help.ts +2 -2
  43. package/src/cli/index.ts +9 -2
  44. package/src/cli/link.ts +1 -1
  45. package/src/cli/message-command.ts +2 -1
  46. package/src/cli/message-mcp-command.ts +29 -0
  47. package/src/cli/registry.ts +12 -4
  48. package/src/cli/root.ts +8 -0
  49. package/src/cli/sync-command.ts +243 -0
  50. package/src/cli/sync-fanout-process.ts +92 -0
  51. package/src/cli/sync-fanout.ts +150 -0
  52. package/src/cli/sync-flags.ts +10 -0
  53. package/src/cli/sync-link-status.ts +39 -0
  54. package/src/cli/sync-update-guard.ts +18 -0
  55. package/src/client/connect.ts +31 -14
  56. package/src/client/link-home.ts +3 -2
  57. package/src/client/machine-listener.ts +3 -0
  58. package/src/client/restore-ownership.ts +19 -1
  59. package/src/client/runtime-restart.ts +12 -4
  60. package/src/client/runtime.ts +40 -11
  61. package/src/client/stop-routing.ts +62 -0
  62. package/src/client/sync-runtime.ts +65 -0
  63. package/src/clients/config-export.ts +32 -3
  64. package/src/codex/account-store.ts +1 -0
  65. package/src/codex/auth-context-provider.ts +15 -0
  66. package/src/codex/auth-context.ts +59 -122
  67. package/src/codex/catalog/antigravity-discovery.ts +16 -5
  68. package/src/codex/catalog/provider-models.ts +6 -8
  69. package/src/codex/forward-transport-headers.ts +65 -36
  70. package/src/codex/inject/config-toml.ts +88 -0
  71. package/src/codex/inject/multi-agent-v2.ts +30 -4
  72. package/src/codex/inject/plan.ts +34 -7
  73. package/src/codex/inject-coordination.ts +11 -0
  74. package/src/codex/inject.ts +18 -7
  75. package/src/codex/installation-id.ts +72 -0
  76. package/src/codex/lineage.ts +13 -7
  77. package/src/codex/quota.ts +22 -6
  78. package/src/codex/request-owned-affinity-key.ts +11 -0
  79. package/src/codex/request-owned-affinity.ts +118 -0
  80. package/src/codex/request-owned-main-pin.ts +86 -0
  81. package/src/codex/role-capability.ts +52 -41
  82. package/src/codex/routing/active-account.ts +13 -5
  83. package/src/codex/routing/selection.ts +40 -1
  84. package/src/codex/routing/thread-affinity-store.ts +916 -0
  85. package/src/codex/routing/thread-affinity.ts +90 -12
  86. package/src/codex/toml-source-lines.ts +72 -13
  87. package/src/combos/failover.ts +6 -109
  88. package/src/combos/request.ts +2 -2
  89. package/src/combos/resolve.ts +29 -11
  90. package/src/config/process-state.ts +5 -0
  91. package/src/config/schema/leaf-validators.ts +1 -0
  92. package/src/generated/compatibility-version.json +496 -192
  93. package/src/grok/sync.ts +10 -1
  94. package/src/images/loop.ts +2 -1
  95. package/src/lib/client-error-body.ts +184 -0
  96. package/src/lib/client-retry-after.ts +66 -0
  97. package/src/lib/config-ownership.ts +4 -0
  98. package/src/lib/context-overflow-verdict.ts +113 -0
  99. package/src/lib/desktop-cli-handoff.d.mts +1 -1
  100. package/src/lib/desktop-cli-handoff.mjs +11 -1
  101. package/src/lib/empty-tool-catalog.ts +25 -3
  102. package/src/lib/error-destination.ts +47 -0
  103. package/src/lib/failure-detail.ts +66 -0
  104. package/src/lib/model-identity.ts +44 -0
  105. package/src/lib/private-sqlite-path.ts +124 -0
  106. package/src/lib/response-service-tier.ts +17 -0
  107. package/src/lib/retry-after.ts +3 -0
  108. package/src/lib/spend-ledger-owner.ts +43 -4
  109. package/src/lib/upstream-condition.ts +142 -0
  110. package/src/lib/upstream-retry.ts +14 -11
  111. package/src/lib/windows-owner-acl.ts +13 -6
  112. package/src/lib/windows-secret-acl.ts +2 -2
  113. package/src/link/remote-platform.ts +14 -0
  114. package/src/link/remote-windows.ts +51 -9
  115. package/src/link/ssh-argv.ts +63 -10
  116. package/src/messaging/mcp-queue-rpc.ts +102 -0
  117. package/src/messaging/mcp-queue-server.ts +42 -0
  118. package/src/messaging/mcp-queue-tools.ts +39 -0
  119. package/src/oauth/anthropic-identity.ts +2 -6
  120. package/src/oauth/generic-account-failover.ts +13 -11
  121. package/src/oauth/index.ts +41 -74
  122. package/src/oauth/oauth-errors.ts +67 -0
  123. package/src/oauth/store.ts +1 -1
  124. package/src/protocols/codecs/ollama.ts +197 -0
  125. package/src/protocols/encoders/adapter-events.ts +4 -0
  126. package/src/protocols/encoders/chat.ts +18 -10
  127. package/src/protocols/trace.ts +18 -0
  128. package/src/providers/anthropic-subscription.ts +25 -0
  129. package/src/providers/claude-cli-usage.ts +15 -67
  130. package/src/providers/fastwire.ts +3 -2
  131. package/src/providers/quota/anthropic-decision-windows.ts +5 -19
  132. package/src/providers/quota/anthropic-usage-windows.ts +65 -0
  133. package/src/providers/quota/vendor-probes-key.ts +60 -24
  134. package/src/providers/request-pacing.ts +3 -2
  135. package/src/responses/apply-patch-envelope.ts +45 -19
  136. package/src/responses/compaction-history-framing.ts +5 -1
  137. package/src/responses/freeform-wrapper-scan.ts +5 -3
  138. package/src/responses/parser-tools.ts +1 -0
  139. package/src/responses/progressive-freeform-input.ts +354 -45
  140. package/src/responses/schema.ts +5 -2
  141. package/src/routing/fallback-policy.ts +3 -1
  142. package/src/server/admission-model-scope.ts +17 -6
  143. package/src/server/admitted-http-turn.ts +56 -0
  144. package/src/server/audio-dictation.ts +3 -0
  145. package/src/server/audio-live.ts +8 -2
  146. package/src/server/audio-upstream.ts +2 -0
  147. package/src/server/auth-cors.ts +5 -0
  148. package/src/server/chat-completions.ts +45 -20
  149. package/src/server/chat-native-sse.ts +52 -7
  150. package/src/server/chat-native.ts +60 -35
  151. package/src/server/claude-bridge-pool-session.ts +59 -0
  152. package/src/server/claude-messages.ts +57 -27
  153. package/src/server/context-history.ts +14 -7
  154. package/src/server/images.ts +14 -5
  155. package/src/server/inbound-body-admission.ts +11 -4
  156. package/src/server/index/live-sideband.ts +16 -2
  157. package/src/server/index/ollama-routes.ts +89 -0
  158. package/src/server/index/serve-options.ts +22 -4
  159. package/src/server/index/websocket-handler.ts +5 -3
  160. package/src/server/index.ts +6 -36
  161. package/src/server/inference/client-encoder-delivery.ts +4 -2
  162. package/src/server/json-serialized-bytes.ts +44 -0
  163. package/src/server/live.ts +30 -5
  164. package/src/server/management/agent-settings-routes.ts +24 -21
  165. package/src/server/management/codex-cli-update-routes.ts +2 -1
  166. package/src/server/management/route-registry.ts +1 -1
  167. package/src/server/messages-native-scope.ts +2 -1
  168. package/src/server/messages-native-tool-guard.ts +1 -1
  169. package/src/server/messages-native.ts +12 -7
  170. package/src/server/messages-shared.ts +6 -2
  171. package/src/server/native-final-log.ts +93 -0
  172. package/src/server/ollama-inbound.ts +349 -0
  173. package/src/server/ollama-native-paths.ts +21 -0
  174. package/src/server/ollama-route-policy.ts +73 -0
  175. package/src/server/relay.ts +22 -3
  176. package/src/server/request-decompress.ts +4 -2
  177. package/src/server/request-log-failure-attribution.ts +22 -0
  178. package/src/server/request-log-failure-detail.ts +80 -0
  179. package/src/server/request-log-terminal-status.ts +4 -2
  180. package/src/server/request-log.ts +79 -42
  181. package/src/server/response-log-body.ts +6 -1
  182. package/src/server/responses/account-change-state.ts +17 -6
  183. package/src/server/responses/adapter-continuation.ts +9 -4
  184. package/src/server/responses/adapter-delivery.ts +5 -4
  185. package/src/server/responses/adapter-dispatch.ts +36 -30
  186. package/src/server/responses/anthropic-thinking-recovery.ts +3 -0
  187. package/src/server/responses/codex-auth-error.ts +22 -17
  188. package/src/server/responses/codex-ws-exchange.ts +11 -8
  189. package/src/server/responses/codex-ws-metadata.ts +94 -21
  190. package/src/server/responses/codex-ws-request.ts +3 -1
  191. package/src/server/responses/combo-required-tool-contract.ts +24 -12
  192. package/src/server/responses/compact.ts +89 -41
  193. package/src/server/responses/compaction-recovery.ts +4 -2
  194. package/src/server/responses/compaction-routing.ts +9 -4
  195. package/src/server/responses/core-auth.ts +32 -14
  196. package/src/server/responses/core-codex-account.ts +34 -12
  197. package/src/server/responses/core-combo-failure.ts +5 -1
  198. package/src/server/responses/core-combo-native.ts +2 -1
  199. package/src/server/responses/core-combo.ts +51 -33
  200. package/src/server/responses/core-errors.ts +22 -20
  201. package/src/server/responses/core-lifetime.ts +6 -3
  202. package/src/server/responses/core-normalize.ts +8 -1
  203. package/src/server/responses/core-options.ts +7 -0
  204. package/src/server/responses/core-pipeline.ts +4 -3
  205. package/src/server/responses/fetch-helpers.ts +7 -1
  206. package/src/server/responses/input-admission.ts +28 -2
  207. package/src/server/responses/native-injection.ts +1 -1
  208. package/src/server/responses/native-response-json.ts +13 -4
  209. package/src/server/responses/native-response-output.ts +1 -2
  210. package/src/server/responses/non-replayable-error.ts +2 -1
  211. package/src/server/responses/pacing-overload.ts +3 -2
  212. package/src/server/responses/passthrough-build-error.ts +36 -0
  213. package/src/server/responses/passthrough-delivery.ts +55 -14
  214. package/src/server/responses/passthrough-dispatch.ts +26 -39
  215. package/src/server/responses/passthrough-error.ts +9 -9
  216. package/src/server/responses/policy-fallback.ts +2 -1
  217. package/src/server/responses/request-prepare.ts +67 -48
  218. package/src/server/responses/request-sidecar-auth.ts +3 -1
  219. package/src/server/responses/request-transport.ts +35 -31
  220. package/src/server/responses/run-turn-execution.ts +6 -6
  221. package/src/server/responses/sidecar-execution.ts +16 -12
  222. package/src/server/responses/spend-storage-error.ts +2 -1
  223. package/src/server/responses/ws-upstream.ts +9 -0
  224. package/src/server/responses-custom-tool-repair.ts +14 -3
  225. package/src/server/responses-terminal-repair.ts +5 -2
  226. package/src/server/responses-undeclared-tool-guard.ts +39 -16
  227. package/src/server/safe-response-headers.ts +162 -13
  228. package/src/server/search.ts +13 -4
  229. package/src/server/turn-state-handles.ts +164 -0
  230. package/src/server/workflow-refusal.ts +2 -1
  231. package/src/server/ws-bridge.ts +5 -2
  232. package/src/service/ownership-mutation-lease.d.mts +11 -2
  233. package/src/service/ownership-mutation-lease.mjs +53 -11
  234. package/src/types/config.ts +2 -0
  235. package/src/update/index.ts +133 -25
  236. package/src/update/npm-install.d.mts +8 -0
  237. package/src/update/npm-install.mjs +20 -1
  238. package/src/update/orchestrated-admission.d.mts +4 -0
  239. package/src/update/orchestrated-admission.mjs +12 -0
  240. package/src/update/orchestrated-arguments.d.mts +12 -0
  241. package/src/update/orchestrated-arguments.mjs +64 -0
  242. package/src/update/orchestrated-child.d.mts +12 -0
  243. package/src/update/orchestrated-child.mjs +70 -0
  244. package/src/update/orchestrated-entry.ts +234 -0
  245. package/src/update/orchestrated-identity-probe-entry.ts +20 -0
  246. package/src/update/orchestrated-identity.ts +53 -0
  247. package/src/update/orchestrated-live-identity.ts +48 -0
  248. package/src/update/orchestrated-node-driver.mjs +99 -0
  249. package/src/update/orchestrated-outcome.d.mts +21 -0
  250. package/src/update/orchestrated-outcome.mjs +40 -0
  251. package/src/update/orchestrated-plan.ts +49 -0
  252. package/src/update/orchestrated-pnpm.d.mts +8 -0
  253. package/src/update/orchestrated-pnpm.mjs +33 -0
  254. package/src/update/orchestrated-session.d.mts +37 -0
  255. package/src/update/orchestrated-session.mjs +264 -0
  256. package/src/update/orchestrated-token.d.mts +10 -0
  257. package/src/update/orchestrated-token.mjs +21 -0
  258. package/src/update/orchestrated-token.ts +3 -0
  259. package/src/update/orchestrated-tree.d.mts +1 -0
  260. package/src/update/orchestrated-tree.mjs +14 -0
  261. package/src/update/pnpm-global-install.d.mts +6 -0
  262. package/src/update/pnpm-global-install.mjs +9 -2
  263. package/src/update/posix-install-supervisor-entry.mjs +6 -0
  264. package/src/update/posix-install-supervisor.d.mts +10 -0
  265. package/src/update/posix-install-supervisor.mjs +88 -0
  266. package/src/update/sync-update-mutex.d.mts +10 -0
  267. package/src/update/sync-update-mutex.mjs +164 -0
  268. package/src/update/sync-update-mutex.ts +1 -0
  269. package/src/update/test-home-guard.mjs +33 -0
  270. package/src/update/transactional-install.mjs +2 -2
  271. package/src/usage/error-detail.ts +225 -0
  272. package/src/usage/log.ts +60 -27
  273. package/src/vision/describe.ts +4 -7
  274. package/src/web-search/executor.ts +4 -7
  275. package/src/web-search/loop.ts +31 -5
  276. package/gui/dist/assets/index-D7DCm5eQ.js +0 -94
@@ -641,7 +641,17 @@ function usageFromNative(value: JsonRecord | undefined): OcxUsage | undefined {
641
641
  const input = isFiniteNonNegativeInteger(value.prompt_eval_count) ? value.prompt_eval_count : undefined;
642
642
  const output = isFiniteNonNegativeInteger(value.eval_count) ? value.eval_count : undefined;
643
643
  if (input === undefined && output === undefined) return undefined;
644
- return { inputTokens: input ?? 0, outputTokens: output ?? 0 };
644
+ // Ollama reports prompt_eval_cached_count as the cached subset of prompt_eval_count (api/types.go;
645
+ // its CLI prints prompt_eval_count - cached as the uncached share), which is OCX's cache-read
646
+ // convention. Omitted means unknown, so no cache field is invented; a count that exceeds the
647
+ // prompt is not a subset and is ignored rather than clamped (#8101).
648
+ const cached = input !== undefined && isFiniteNonNegativeInteger(value.prompt_eval_cached_count)
649
+ && value.prompt_eval_cached_count <= input ? value.prompt_eval_cached_count : undefined;
650
+ return {
651
+ inputTokens: input ?? 0,
652
+ outputTokens: output ?? 0,
653
+ ...(cached !== undefined ? { cachedInputTokens: cached, cacheReadInputTokens: cached } : {}),
654
+ };
645
655
  }
646
656
 
647
657
  function stopReasonFromNative(value: unknown): string | undefined {
@@ -1051,7 +1061,6 @@ async function* parseOllamaNativeStream(
1051
1061
  }
1052
1062
  const reader = response.body.getReader();
1053
1063
  const decoder = new TextDecoder("utf-8", { fatal: true });
1054
- const encoder = new TextEncoder();
1055
1064
  const state = streamState(allowParallelToolCalls);
1056
1065
  const issuedIds = issuedToolCallIds ?? new Set<string>();
1057
1066
  let buffer = "";
@@ -1060,15 +1069,20 @@ async function* parseOllamaNativeStream(
1060
1069
 
1061
1070
  const ingest = function* (text: string): Generator<AdapterEvent> {
1062
1071
  if (!text) return;
1072
+ const hasNewline = text.includes("\n");
1063
1073
  buffer += text;
1064
- const lines = buffer.split("\n");
1065
- buffer = lines.pop() ?? "";
1074
+ // After draining, the carry contains no newline. Only new text can complete a record.
1075
+ const lines = hasNewline ? buffer.split("\n") : [];
1076
+ if (hasNewline) buffer = lines.pop() ?? "";
1066
1077
  // The safety bound applies to the genuinely retained residual — the incomplete NDJSON record
1067
1078
  // still being assembled — and to each complete record below. It must never depend on the
1068
1079
  // transport read size (one read may carry many valid records) nor transiently charge
1069
1080
  // old + replacement together. On a ceiling violation the old reservation is left in place so
1070
1081
  // the generator's finally releases exactly what is held.
1071
- const residualBytes = encoder.encode(buffer).byteLength;
1082
+ // TextDecoder emits complete code points; fragment byte counts add without a surrogate fixup.
1083
+ const residualBytes = hasNewline
1084
+ ? Buffer.byteLength(buffer, "utf8")
1085
+ : bufferBytes + Buffer.byteLength(text, "utf8");
1072
1086
  if (residualBytes > TRANSLATOR_MAX_SSE_EVENT_BYTES) {
1073
1087
  throw new TranslatorBudgetExceededError("live_transient", TRANSLATOR_MAX_SSE_EVENT_BYTES);
1074
1088
  }
@@ -1077,7 +1091,7 @@ async function* parseOllamaNativeStream(
1077
1091
 
1078
1092
  for (const rawLine of lines) {
1079
1093
  const line = rawLine.endsWith("\r") ? rawLine.slice(0, -1) : rawLine;
1080
- const lineBytes = encoder.encode(line).byteLength;
1094
+ const lineBytes = Buffer.byteLength(line, "utf8");
1081
1095
  if (lineBytes > TRANSLATOR_MAX_SSE_EVENT_BYTES) {
1082
1096
  throw new TranslatorBudgetExceededError("live_transient", TRANSLATOR_MAX_SSE_EVENT_BYTES);
1083
1097
  }
@@ -1112,7 +1126,7 @@ async function* parseOllamaNativeStream(
1112
1126
  yield* ingest(decoder.decode());
1113
1127
  if (!state.terminal && buffer.length > 0) {
1114
1128
  const rawLine = buffer.endsWith("\r") ? buffer.slice(0, -1) : buffer;
1115
- const lineBytes = encoder.encode(rawLine).byteLength;
1129
+ const lineBytes = Buffer.byteLength(rawLine, "utf8");
1116
1130
  if (lineBytes > TRANSLATOR_MAX_SSE_EVENT_BYTES) throw new TranslatorBudgetExceededError("live_transient", TRANSLATOR_MAX_SSE_EVENT_BYTES);
1117
1131
  try {
1118
1132
  // The EOF record keeps its residual charge while it is parsed and consumed — releasing it
@@ -1,4 +1,11 @@
1
- import { namespacedToolName, type AdapterEvent, type OcxParsedRequest, type OcxProviderConfig, type OcxUsage, type TierDecision } from "../../types";
1
+ import {
2
+ namespacedToolName,
3
+ type AdapterEvent,
4
+ type OcxParsedRequest,
5
+ type OcxProviderConfig,
6
+ type OcxUsage,
7
+ type TierDecision,
8
+ } from "../../types";
2
9
  import { stripItemIdsWhenUnstored } from "./request-strips";
3
10
  import { isPlainObject } from "./internal";
4
11
  import { stripPromptCacheBreakpoints } from "./prompt-cache";
@@ -15,13 +22,21 @@ import { stripPromptCacheBreakpoints } from "./prompt-cache";
15
22
  * unexpanded requests: the platform `/v1/responses` supports real server-side storage.
16
23
  */
17
24
  export function stripPreviousResponseId(body: unknown, strip: boolean): unknown {
18
- if (!strip || !isPlainObject(body) || !Object.prototype.hasOwnProperty.call(body, "previous_response_id")) return body;
25
+ if (
26
+ !strip ||
27
+ !isPlainObject(body) ||
28
+ !Object.prototype.hasOwnProperty.call(body, "previous_response_id")
29
+ )
30
+ return body;
19
31
  const { previous_response_id: _previousResponseId, ...rest } = body;
20
32
  return rest;
21
33
  }
22
34
 
23
35
  /** Apply the settled tier only to a fresh outbound object; `_rawBody` remains caller-owned. */
24
- export function applyTierDecisionToResponsesBody(body: unknown, decision: TierDecision | undefined): unknown {
36
+ export function applyTierDecisionToResponsesBody(
37
+ body: unknown,
38
+ decision: TierDecision | undefined,
39
+ ): unknown {
25
40
  if (!decision || decision.kind === "forward-caller" || !isPlainObject(body)) return body;
26
41
  const next: Record<string, unknown> = { ...body };
27
42
  if (decision.kind === "set") next.service_tier = decision.value;
@@ -54,8 +69,14 @@ export function applyTierDecisionToResponsesBody(body: unknown, decision: TierDe
54
69
  */
55
70
  export function stripStatefulResponsesParams(body: unknown): unknown {
56
71
  if (!isPlainObject(body)) return body;
57
- const drop = ["previous_response_id", "conversation", "background", "metadata", "prompt"] as const;
58
- const present = drop.some(key => Object.prototype.hasOwnProperty.call(body, key));
72
+ const drop = [
73
+ "previous_response_id",
74
+ "conversation",
75
+ "background",
76
+ "metadata",
77
+ "prompt",
78
+ ] as const;
79
+ const present = drop.some((key) => Object.prototype.hasOwnProperty.call(body, key));
59
80
  if (!present && body.store === false) return body;
60
81
  const next: Record<string, unknown> = { ...body };
61
82
  for (const key of drop) delete next[key];
@@ -77,11 +98,19 @@ export function stripStatefulResponsesParams(body: unknown): unknown {
77
98
  * self-hosted or third-party gateway may honour it — dropping it there silently
78
99
  * removes the cap. Only the canonical ChatGPT backend rejects it outright, so only
79
100
  * `canonical` callers strip it.
101
+ *
102
+ * `safety_identifier` is the third canonical-only drop: a public OpenAI-platform
103
+ * parameter some BYOK clients (droid's registry-matched models) attach from the
104
+ * model name alone. The official API-key surface accepts it, but the canonical
105
+ * ChatGPT backend rejects it with the same strict-allowlist envelope, so only
106
+ * `canonical` callers strip it.
80
107
  */
81
108
  export function stripUnsupportedForwardParams(body: unknown, canonical: boolean): unknown {
82
109
  if (!isPlainObject(body)) return body;
83
- const drop = canonical ? (["metadata", "max_output_tokens"] as const) : (["metadata"] as const);
84
- if (!drop.some(key => Object.hasOwn(body, key))) return body;
110
+ const drop = canonical
111
+ ? (["metadata", "max_output_tokens", "safety_identifier"] as const)
112
+ : (["metadata"] as const);
113
+ if (!drop.some((key) => Object.hasOwn(body, key))) return body;
85
114
  const next: Record<string, unknown> = { ...body };
86
115
  for (const key of drop) delete next[key];
87
116
  return next;
@@ -104,7 +133,11 @@ const CANONICAL_FORWARD_UNSUPPORTED_SAMPLING = ["temperature", "top_p", "stop",
104
133
  */
105
134
  export function stripCanonicalForwardSamplingParams(body: unknown): unknown {
106
135
  if (!isPlainObject(body)) return body;
107
- if (!CANONICAL_FORWARD_UNSUPPORTED_SAMPLING.some(key => Object.prototype.hasOwnProperty.call(body, key))) {
136
+ if (
137
+ !CANONICAL_FORWARD_UNSUPPORTED_SAMPLING.some((key) =>
138
+ Object.prototype.hasOwnProperty.call(body, key),
139
+ )
140
+ ) {
108
141
  return body;
109
142
  }
110
143
  const next: Record<string, unknown> = { ...body };
@@ -130,9 +163,11 @@ function canonicalForwardSystemText(item: Record<string, unknown>): string | nul
130
163
 
131
164
  /** Only message items may carry privileged system instructions. */
132
165
  function isCanonicalForwardSystemMessage(item: unknown): item is Record<string, unknown> {
133
- return isPlainObject(item)
134
- && (item.type === undefined || item.type === "message")
135
- && item.role === "system";
166
+ return (
167
+ isPlainObject(item) &&
168
+ (item.type === undefined || item.type === "message") &&
169
+ item.role === "system"
170
+ );
136
171
  }
137
172
 
138
173
  /**
@@ -172,7 +207,7 @@ export function normalizeCanonicalForwardPromptEnvelope(body: unknown): unknown
172
207
  const next: Record<string, unknown> = { ...body };
173
208
  if (stripTruncation) delete next.truncation;
174
209
  if (sawSystemMessage && canFoldAllSystemMessages) {
175
- next.input = input.filter(item => !isCanonicalForwardSystemMessage(item));
210
+ next.input = input.filter((item) => !isCanonicalForwardSystemMessage(item));
176
211
  const folded = foldedText.join("\n\n");
177
212
  if (folded !== "") {
178
213
  const existing = typeof body.instructions === "string" ? body.instructions : "";
@@ -193,7 +228,9 @@ export function normalizeCanonicalForwardContinuationEnvelope(body: unknown): un
193
228
  let input: unknown[] = body.input;
194
229
  let changed = false;
195
230
  if (body.store === false) {
196
- const withoutReferences = input.filter(item => !isPlainObject(item) || item.type !== "item_reference");
231
+ const withoutReferences = input.filter(
232
+ (item) => !isPlainObject(item) || item.type !== "item_reference",
233
+ );
197
234
  if (withoutReferences.length !== input.length) {
198
235
  input = withoutReferences;
199
236
  changed = true;
@@ -16,11 +16,23 @@ function isEmptyAssistantMessage(item: unknown): boolean {
16
16
  return item.content === "" || (Array.isArray(item.content) && item.content.every(isEmptyTextPart));
17
17
  }
18
18
 
19
+ /** Exactly Kimi Code's native Responses endpoint; lookalike hosts and other Kimi paths do not match. */
20
+ export function isKimiCodingResponsesUrl(responseUrl: string): boolean {
21
+ let url: URL;
22
+ try { url = new URL(responseUrl); } catch { return false; }
23
+ return url.hostname === "api.kimi.com" && /^\/coding\/v1\/responses\/?$/.test(url.pathname);
24
+ }
25
+
26
+ /** The same endpoint over HTTPS on the default port only, for request rewrites scoped to Kimi Code itself. */
27
+ export function isKimiCodingResponsesHttpsUrl(responseUrl: string): boolean {
28
+ if (!isKimiCodingResponsesUrl(responseUrl)) return false;
29
+ const url = new URL(responseUrl);
30
+ return url.protocol === "https:" && url.port === "";
31
+ }
32
+
19
33
  /** Kimi Code rejects content-empty assistant messages even on its native Responses endpoint. */
20
34
  export function stripKimiEmptyAssistantMessages(body: unknown, responseUrl: string): unknown {
21
- let url: URL;
22
- try { url = new URL(responseUrl); } catch { return body; }
23
- if (url.hostname !== "api.kimi.com" || !/^\/coding\/v1\/responses\/?$/.test(url.pathname)) return body;
35
+ if (!isKimiCodingResponsesUrl(responseUrl)) return body;
24
36
  if (!isPlainObject(body) || !Array.isArray(body.input)) return body;
25
37
  const referencedIds = new Set<string>();
26
38
  for (const item of body.input) {
@@ -57,7 +57,7 @@ import { observeOutbound } from "../../usage/cache-diagnostic";
57
57
  import { normalizeMuseToolCatalog } from "./muse-tool-catalog";
58
58
  import { normalizeMuseToolChoice } from "./muse-tool-choice";
59
59
  import { declaresHostedWebSearch, projectHostedSearchHistory, renderCompactionSearchHistoryItems } from "./compaction-search-history";
60
- import { stripKimiEmptyAssistantMessages } from "./empty-assistant";
60
+ import { isKimiCodingResponsesHttpsUrl, stripKimiEmptyAssistantMessages } from "./empty-assistant";
61
61
  import { normalizeOpenGatewayResponsesInput } from "./opengateway-input";
62
62
 
63
63
  /**
@@ -358,12 +358,13 @@ export function createResponsesPassthroughAdapter(provider: OcxProviderConfig):
358
358
  // OpenCode Go speaks the same dialect, which the final model id and URL identify.
359
359
  outBody = normalizeXaiResponsesWebSearch(outBody, provider, { modelId: parsed.modelId, responseUrl: url });
360
360
  outBody = injectXaiResponsesXSearch(outBody, provider, parsed._replayPrefixLen);
361
- // xAI, Meta and Azure answer 400 for `output.encrypted_content` instead of ignoring it;
362
- // Codex Desktop asks for it on every turn (#7878).
361
+ // xAI, Meta, Azure and Kimi Code (#8075) answer 400 for `output.encrypted_content`
362
+ // instead of ignoring it; Codex Desktop asks for it on every turn (#7878).
363
363
  // Azure also rejects this exact include entry, including on plain Responses routes.
364
364
  const isAzureResponses = provider.adapter === "azure" || provider.adapter === "azure-openai"
365
365
  || new URL(url).hostname.toLowerCase().endsWith(".openai.azure.com");
366
- if (isXaiResponsesDestination(provider) || isMetaAiResponsesDestination(url) || isAzureResponses) {
366
+ if (isXaiResponsesDestination(provider) || isMetaAiResponsesDestination(url) || isAzureResponses
367
+ || isKimiCodingResponsesHttpsUrl(url)) {
367
368
  outBody = stripUnsupportedOutputInclude(outBody);
368
369
  }
369
370
  // xAI and explicitly classified compatible gateways reject these OpenAI web_search
@@ -482,10 +483,9 @@ export function createResponsesPassthroughAdapter(provider: OcxProviderConfig):
482
483
  finalBody = { ...finalBody, stream: true };
483
484
  }
484
485
  if (isCanonicalOpenAiForwardProvider(provider)) {
485
- const overrideAccountId = (provider as { _codexAccountOverride?: { chatgptAccountId?: string } })._codexAccountOverride?.chatgptAccountId
486
- ?? headers["chatgpt-account-id"];
487
- if ((provider as { _codexAccountOverride?: unknown })._codexAccountOverride && overrideAccountId) {
488
- finalBody = isolateCodexPoolClientMetadata(finalBody, overrideAccountId);
486
+ const override = (provider as { _codexAccountOverride?: { chatgptAccountId: string; kind?: string } })._codexAccountOverride;
487
+ if (override && override.kind !== "main-pool") {
488
+ finalBody = isolateCodexPoolClientMetadata(finalBody, override.chatgptAccountId);
489
489
  }
490
490
  const routingHeaders = new Headers(headers);
491
491
  applyCodexRoutingHint(routingHeaders, finalBody);
@@ -174,10 +174,15 @@ export function sanitizeReasoningInputContent(
174
174
 
175
175
  /** Assistant-authored history items: what DeepSeek merges into one assistant message. */
176
176
  function isAssistantTurnItem(item: unknown): boolean {
177
- if (!isPlainObject(item) || typeof item.type !== "string") return false;
178
- if (item.type === "reasoning") return true;
179
- if (item.type === "message") return item.role === "assistant";
180
- return item.type.endsWith("_call");
177
+ if (!isPlainObject(item)) return false;
178
+ // Responses input accepts the message shorthand without `type`. ZCode sends its assistant
179
+ // text that way, directly ahead of the same turn's function calls; reading only a typed
180
+ // `message` would split the turn and place the placeholder backfill after the text, which
181
+ // DeepSeek refuses with the same reasoning_text 400.
182
+ const type = typeof item.type === "string" ? item.type : "role" in item ? "message" : undefined;
183
+ if (type === "reasoning") return true;
184
+ if (type === "message") return item.role === "assistant";
185
+ return type?.endsWith("_call") === true;
181
186
  }
182
187
 
183
188
  function isClientToolCallItem(item: unknown): boolean {
@@ -8,7 +8,7 @@ import { activateDeferredTool } from "./tool-schema";
8
8
  import { stripOpenAiOnlyWebSearchFields } from "./web-search";
9
9
 
10
10
  /**
11
- * Codex requests output.encrypted_content, which xAI, Meta and Azure reject with HTTP 400.
11
+ * Codex requests output.encrypted_content, which xAI, Meta, Azure and Kimi Code reject with HTTP 400.
12
12
  * The caller gates this on the destination. Preserve reasoning.encrypted_content
13
13
  * for stateless replay and leave unknown or malformed values for upstream validation.
14
14
  */
@@ -1,25 +1,17 @@
1
1
  import type { IncomingMeta } from "../base";
2
2
  import type { OcxProviderConfig } from "../../types";
3
3
  import {
4
+ FORWARD_HEADERS,
4
5
  CODEX_ATTESTATION_HEADER,
5
- CODEX_INSTALLATION_ID_HEADER,
6
6
  CODEX_RESPONSES_LITE_HEADER,
7
- CODEX_TURN_METADATA_HEADER,
8
- deriveCodexAccountInstallationId,
9
- rewriteTurnMetadataInstallationId,
7
+ isolateCodexPoolAccountHeaders,
10
8
  } from "../../codex/forward-transport-headers";
11
9
  import { CODEX_FORWARD_BASE_URL, isCanonicalOpenAiForwardProvider } from "../../providers/openai-tiers-destination";
12
10
  import { normalizeForwardedClientHeaderName } from "../../lib/provider-client-headers";
13
11
  import { AGENT_ASSERTION_HEADER } from "../../lib/authorization-scheme";
14
12
  import { openaiResponsesUrl } from "../openai-responses-url";
15
13
 
16
- // Caller credentials are forwarded only to the canonical Codex destination, never by capability.
17
- export const FORWARD_HEADERS = [
18
- "authorization", "chatgpt-account-id", "openai-beta", "originator", "session_id", "session-id",
19
- "thread-id", "x-client-request-id", "x-codex-beta-features", "x-codex-installation-id",
20
- "x-codex-parent-thread-id", "x-codex-turn-metadata", "x-codex-turn-state", "x-codex-window-id",
21
- "x-oai-attestation", "x-openai-subagent", "x-responsesapi-include-timing-metrics", "version", CODEX_RESPONSES_LITE_HEADER,
22
- ];
14
+ export { FORWARD_HEADERS } from "../../codex/forward-transport-headers";
23
15
 
24
16
  /** Carry permitted client metadata across an internal compact handoff, never credentials. */
25
17
  export function copyResponsesClientMetadata(target: Headers, incoming: Headers, provider: OcxProviderConfig): void {
@@ -55,16 +47,20 @@ export function buildResponsesTransport(provider: OcxProviderConfig, incoming: P
55
47
  url = `${baseUrl}/responses`;
56
48
  if (provider.headers) Object.assign(headers, provider.headers);
57
49
  const runtimeProvider = provider as {
58
- _codexAccountOverride?: { accessToken: string; chatgptAccountId: string };
50
+ _codexAccountOverride?: { accessToken: string; chatgptAccountId: string; kind?: "pool" | "main-pool" };
59
51
  _codexAccountRequired?: boolean;
60
52
  };
61
53
  if (mayForwardCallerCredentials && runtimeProvider._codexAccountRequired && !runtimeProvider._codexAccountOverride) {
62
54
  throw new Error("Codex pool account auth is required but unavailable");
63
55
  }
64
56
  if (mayForwardCallerCredentials) {
57
+ // Caller-existence gates also apply when provider defaults use mixed casing.
58
+ for (const name of Object.keys(headers)) {
59
+ if (["x-codex-installation-id", "x-codex-turn-metadata", CODEX_ATTESTATION_HEADER].includes(name.toLowerCase())) delete headers[name];
60
+ }
65
61
  for (const name of FORWARD_HEADERS) {
66
62
  const value = incoming.headers.get(name);
67
- if (!value) continue;
63
+ if (value === null) continue;
68
64
  if (name === CODEX_RESPONSES_LITE_HEADER) {
69
65
  for (const existing of Object.keys(headers)) {
70
66
  if (existing.toLowerCase() === name) delete headers[existing];
@@ -75,19 +71,14 @@ export function buildResponsesTransport(provider: OcxProviderConfig, incoming: P
75
71
  }
76
72
  const override = runtimeProvider._codexAccountOverride;
77
73
  if (override && mayForwardCallerCredentials) {
78
- headers.authorization = `Bearer ${override.accessToken}`;
79
- headers["chatgpt-account-id"] = override.chatgptAccountId;
80
- delete headers[CODEX_ATTESTATION_HEADER];
81
- if (override.chatgptAccountId?.trim()) {
82
- const installId = headers[CODEX_INSTALLATION_ID_HEADER];
83
- if (installId && installId.trim()) {
84
- headers[CODEX_INSTALLATION_ID_HEADER] = deriveCodexAccountInstallationId(override.chatgptAccountId, installId);
85
- }
86
- const turnMeta = headers[CODEX_TURN_METADATA_HEADER];
87
- if (turnMeta) {
88
- headers[CODEX_TURN_METADATA_HEADER] = rewriteTurnMetadataInstallationId(turnMeta, override.chatgptAccountId);
89
- }
90
- }
74
+ const selected = new Headers(headers);
75
+ selected.set("authorization", `Bearer ${override.accessToken}`);
76
+ selected.set("chatgpt-account-id", override.chatgptAccountId);
77
+ selected.delete(CODEX_ATTESTATION_HEADER);
78
+ if (override.kind !== "main-pool") isolateCodexPoolAccountHeaders(selected, override.chatgptAccountId);
79
+ // Replace every casing of managed fields after static headers and caller headers merge.
80
+ for (const name of Object.keys(headers)) delete headers[name];
81
+ selected.forEach((value, name) => { headers[name] = value; });
91
82
  } else if (mayForwardCallerCredentials) {
92
83
  // dual_header runtime assertion: first-party Direct only, beside the caller's own Bearer.
93
84
  // A pool override above never carries it, and non-canonical transports never see it.
@@ -1,7 +1,7 @@
1
1
  import type { AdapterFetchContext } from "./base";
2
2
  import type { SendClass } from "../lib/request-execution-budget";
3
3
  import type { AttemptRecoveryKind } from "../usage/log";
4
- import { abortError, SendBudgetExhaustedError } from "../lib/upstream-retry";
4
+ import { abortError, SendBudgetExhaustedError, errorDestinationLabel } from "../lib/upstream-retry";
5
5
  import {
6
6
  releaseProviderRequestSlot,
7
7
  sendTrackingRequestSlot,
@@ -30,14 +30,14 @@ export function createAdapterPhysicalSend(ctx: AdapterFetchContext = {}, fallbac
30
30
  const decision = ctx.sendBudget?.reserveDispatch({
31
31
  sendClass: options.sendClass ?? "transient", targetKey: options.url,
32
32
  });
33
- if (decision && !decision.allowed) throw new SendBudgetExhaustedError(options.url);
33
+ if (decision && !decision.allowed) throw new SendBudgetExhaustedError(errorDestinationLabel(options.url));
34
34
  const permit = decision?.allowed ? decision.permit : undefined;
35
35
  let dispatched = false;
36
36
  const physicalExecutor = (async (input, init) => {
37
37
  if (ctx.abortSignal?.aborted) throw abortError(ctx.abortSignal);
38
38
  if (init?.signal?.aborted) throw abortError(init.signal);
39
39
  const run = async (): Promise<Response> => {
40
- if (dispatched || (permit && !permit.use())) throw new SendBudgetExhaustedError(options.url);
40
+ if (dispatched || (permit && !permit.use())) throw new SendBudgetExhaustedError(errorDestinationLabel(options.url));
41
41
  dispatched = true;
42
42
  ordinal += 1;
43
43
  ctx.onPhysicalSend?.({ ordinal, ...(options.recovery ? { recovery: options.recovery } : {}) });
@@ -280,7 +280,7 @@ export function createQoderAdapter(provider: OcxProviderConfig, deps: QoderAdapt
280
280
  emit({
281
281
  type: "error", status: 400, errorType: "invalid_request_error",
282
282
  code: "unsupported_input_modality", retryable: false,
283
- message: "Qoder CN raw-image routing is verified only with qoderclicn 1.1.70, DeepSeek-Flash or Qwen3.8-Flash, and one base64 PNG in a single user turn on stream-json stdin. URL, multiple-image, tool-result and history replay surfaces remain unverified; use the vision sidecar for those inputs.",
283
+ message: "Qoder CN raw-image routing is verified only with qoderclicn 1.1.70, DeepSeek-Flash or Qwen3.8-Flash, and one base64 PNG in a single user turn on stream-json stdin. The PNG must be at most 1 MiB decoded, with each edge at most 8192 pixels and at most 16,000,000 total pixels. URL, multiple-image, tool-result and history replay surfaces remain unverified; use the vision sidecar for those inputs.",
284
284
  });
285
285
  return;
286
286
  }
@@ -4,6 +4,8 @@ import { buildConversationInput } from "../coding-agent/protocol";
4
4
  // Local resource policy: #7516 verifies a 96x96 PNG, not a vendor size maximum.
5
5
  // 1 MiB leaves ample room over its 36 KiB RGBA raster while bounding stdin copies.
6
6
  const MAX_CN_PNG_BYTES = 1024 * 1024;
7
+ const MAX_CN_PNG_EDGE = 8192;
8
+ const MAX_CN_PNG_PIXELS = 16_000_000;
7
9
  const PNG_DATA_PREFIX = "data:image/png;base64,";
8
10
  const PNG_SIGNATURE = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]);
9
11
  const PNG_DEPTHS: Readonly<Record<number, readonly number[]>> = {
@@ -25,8 +27,9 @@ function boundedPngDataUrl(imageUrl: string): boolean {
25
27
  || bytes.readUInt32BE(8) !== 13 || bytes.readUInt32BE(12) !== 0x49484452) return false;
26
28
  const width = bytes.readUInt32BE(16);
27
29
  const height = bytes.readUInt32BE(20);
28
- // Minimal IHDR validation only; this does not decompress or validate all chunks.
29
- return width > 0 && width <= 0x7fffffff && height > 0 && height <= 0x7fffffff
30
+ // Bound declared raster work before the child can decode compressed pixels.
31
+ return width > 0 && width <= MAX_CN_PNG_EDGE && height > 0 && height <= MAX_CN_PNG_EDGE
32
+ && width * height <= MAX_CN_PNG_PIXELS
30
33
  && (PNG_DEPTHS[bytes[25]!] ?? []).includes(bytes[24]!)
31
34
  && bytes[26] === 0 && bytes[27] === 0 && (bytes[28] === 0 || bytes[28] === 1);
32
35
  }
@@ -1,3 +1,4 @@
1
+ import { markProxyError } from "../lib/client-error-body";
1
2
  import type { AdapterEvent, OcxMessagePhase, OcxUsage } from "../types";
2
3
  import type { TranslatorBudget } from "../lib/translator-budget";
3
4
  import { decodeServerSentEvents } from "../lib/sse-decoder";
@@ -700,7 +701,7 @@ export async function* translateZedOpenAiStream(
700
701
  yield* flushUnclosed(false);
701
702
  if (terminal) return;
702
703
  if (unfinished) {
703
- yield { type: "incomplete", reason: "adapter_eof", ...(usage ? { usage } : {}) };
704
+ yield markProxyError({ type: "incomplete" as const, reason: "adapter_eof", ...(usage ? { usage } : {}) });
704
705
  return;
705
706
  }
706
707
  const done: AdapterEvent = {
@@ -6,6 +6,7 @@ import {
6
6
  REPLAY_REFUSED_STATUS,
7
7
  retainReplayRefusal,
8
8
  } from "../lib/upstream-retry";
9
+ import { formatClientRetryAfter } from "../lib/client-retry-after";
9
10
  import {
10
11
  adapterFailureFromMessage,
11
12
  classifyError,
@@ -34,6 +35,12 @@ export function upstreamCodeForComboFailure(response: Response, bodyCode: string
34
35
  : bodyCode;
35
36
  }
36
37
 
38
+ /** Preserve formatted quota-code provenance when lifecycle helpers rebuild a response. */
39
+ export function carryFormattedQuotaSource(source: Response, target: Response): Response {
40
+ if (formattedQuotaSources.has(source)) formattedQuotaSources.set(target, formattedQuotaSources.get(source)!);
41
+ return target;
42
+ }
43
+
37
44
  export function formatErrorResponse(
38
45
  status: number,
39
46
  type: string,
@@ -93,7 +100,8 @@ export function formatErrorResponse(
93
100
  : error.code === SPEND_LEDGER_STORAGE_UNAVAILABLE_CODE ? 503
94
101
  : isReplayRefusalCode(error.code) ? REPLAY_REFUSED_STATUS : status;
95
102
  const headers = new Headers({ "Content-Type": "application/json" });
96
- const retryAfter = options?.retryAfter?.trim();
103
+ // Re-emitted as an integer this proxy formats; the incoming text is never echoed.
104
+ const retryAfter = formatClientRetryAfter(options?.retryAfter);
97
105
  if (error.code !== CYBER_POLICY_ERROR_CODE
98
106
  && !replayBlocked
99
107
  && retryAfter
@@ -155,6 +163,7 @@ export function formatUsageLimitReachedResponse(message: string, resetsAtMs: num
155
163
  ...(resetsAtMs !== null ? { resets_at: Math.ceil(resetsAtMs / 1000) } : {}),
156
164
  };
157
165
  const headers = new Headers({ "Content-Type": "application/json" });
158
- if (retryAfterSeconds !== null) headers.set("Retry-After", String(retryAfterSeconds));
166
+ const advice = retryAfterSeconds !== null ? formatClientRetryAfter(retryAfterSeconds) : undefined;
167
+ if (advice !== undefined) headers.set("Retry-After", advice);
159
168
  return new Response(JSON.stringify({ error }), { status: 429, headers });
160
169
  }
@@ -1,3 +1,4 @@
1
+ import { UNDECLARED_TOOL_CALL_MESSAGE } from "../lib/client-error-body";
1
2
  import { anthropicProgressItems } from "../responses/anthropic-progress";
2
3
  import type {
3
4
  AdapterEvent,
@@ -494,7 +495,7 @@ function buildResponseJSONWithBudget(
494
495
  ) {
495
496
  errorEvent = {
496
497
  type: "error",
497
- message: `routed provider emitted undeclared client tool "${effectiveName}"; only request-declared tools may be called`,
498
+ message: UNDECLARED_TOOL_CALL_MESSAGE,
498
499
  status: 502,
499
500
  errorType: "upstream_error",
500
501
  };
package/src/bridge/sse.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { UNDECLARED_TOOL_CALL_MESSAGE, isProxyError, rememberProxyIncomplete, carryProxyIncompleteContext } from "../lib/client-error-body";
1
2
  import { anthropicProgressItems } from "../responses/anthropic-progress";
2
3
  import type {
3
4
  AdapterEvent,
@@ -23,7 +24,7 @@ import {
23
24
  mayBecomePatchEnvelope,
24
25
  repairFreeformToolInput,
25
26
  } from "../responses/apply-patch-envelope";
26
- import { progressiveFreeformInput } from "../responses/progressive-freeform-input";
27
+ import { ProgressiveFreeformInputReader } from "../responses/progressive-freeform-input";
27
28
  import { encodeCompactionSummary, releaseCompactionCiphertextLease } from "../responses/compaction";
28
29
  import { compileCodeModeHelperInput, resolveCodeModeHelperName } from "../responses/code-mode-helper-compat";
29
30
  import { mayBecomeCodeModeShellInput } from "../responses/code-mode-shell-input";
@@ -76,6 +77,7 @@ export function bridgeToResponsesSSE(
76
77
  heartbeatMs = 2_000,
77
78
  options?: MaxOutputCompletionOptions & {
78
79
  responseId?: string;
80
+ proxyErrorContext?: object;
79
81
  /** Trusted structural grouping only; never provider state or execution authority. */
80
82
  outputItemIds?: { next(kind: "message" | "reasoning" | "function_call" | "custom_tool_call" | "tool_search_call"): string };
81
83
 
@@ -165,6 +167,7 @@ export function bridgeToResponsesSSE(
165
167
  };
166
168
  },
167
169
  ): ReadableStream<Uint8Array> {
170
+ const proxyIncompleteContext = options?.proxyErrorContext ?? {};
168
171
  const replayCacheScope = options?.replayCacheScope;
169
172
  const maxOutputCompletion = createMaxOutputCompletion(options);
170
173
  const outputItemId = (kind: "message" | "reasoning" | "function_call" | "custom_tool_call" | "tool_search_call", prefix: string): string =>
@@ -477,7 +480,7 @@ export function bridgeToResponsesSSE(
477
480
  // Full assistant text of a compaction turn (across message boundaries) — becomes the
478
481
  // synthetic compaction item's payload on done.
479
482
  let compaction = emptyChunks();
480
- let currentToolCall: { itemId: string; outputIndex: number; callId: string; name: string; args: string; argsBytes: number; namespace?: string; freeform?: boolean; toolSearch?: boolean; inputEmitted?: string; codeModeHelperName?: string; providerMetadata?: OcxProviderOpaqueToolCallMetadata } | null = null;
483
+ let currentToolCall: { itemId: string; outputIndex: number; callId: string; name: string; args: string; argsBytes: number; namespace?: string; freeform?: boolean; toolSearch?: boolean; inputEmitted?: string; freeformReader?: ProgressiveFreeformInputReader; codeModeHelperName?: string; providerMetadata?: OcxProviderOpaqueToolCallMetadata } | null = null;
481
484
  // Open native web-search cell (between begin and end). Holds the output index allocated on
482
485
  // begin so the matching done reuses it; closed as `failed` if the stream terminates early.
483
486
  let currentWebSearch: { itemId: string; eventId: string; outputIndex: number } | null = null;
@@ -1092,7 +1095,7 @@ export function bridgeToResponsesSSE(
1092
1095
  const failure = responseError(
1093
1096
  502,
1094
1097
  "upstream_error",
1095
- `routed provider emitted undeclared client tool "${effectiveName}"; only request-declared tools may be called`,
1098
+ UNDECLARED_TOOL_CALL_MESSAGE,
1096
1099
  );
1097
1100
  emit("response.failed", {
1098
1101
  response: {
@@ -1154,7 +1157,9 @@ export function bridgeToResponsesSSE(
1154
1157
  // is the same disagreement in the other direction.
1155
1158
  const ownsFreeformGrammar = currentToolCall.namespace === undefined
1156
1159
  || currentToolCall.namespace === "functions";
1157
- const full = progressiveFreeformInput(
1160
+ // One reader per call resumes where the previous delta stopped.
1161
+ currentToolCall.freeformReader ??= new ProgressiveFreeformInputReader();
1162
+ const full = currentToolCall.freeformReader.update(
1158
1163
  currentToolCall.args,
1159
1164
  ownsFreeformGrammar ? currentToolCall.name : "",
1160
1165
  );
@@ -1330,6 +1335,7 @@ export function bridgeToResponsesSSE(
1330
1335
  break;
1331
1336
  }
1332
1337
  case "incomplete": {
1338
+ if (isProxyError(event) && event.reason === "adapter_eof") rememberProxyIncomplete(proxyIncompleteContext, "adapter_eof");
1333
1339
  if (currentMsg) closeCurrentMessage();
1334
1340
  if (currentReasoning) closeCurrentReasoning();
1335
1341
  if (currentRawReasoning) closeCurrentRawReasoning();
@@ -1470,6 +1476,7 @@ export function bridgeToResponsesSSE(
1470
1476
  })) return;
1471
1477
  options?.onUsage?.(undefined);
1472
1478
  await awaitThoughtSignatureDurability();
1479
+ rememberProxyIncomplete(proxyIncompleteContext, "adapter_eof");
1473
1480
  emit("response.incomplete", {
1474
1481
  response: {
1475
1482
  ...responseSnapshot("incomplete", finishedItems),
@@ -1526,6 +1533,7 @@ export function bridgeToResponsesSSE(
1526
1533
  // barrier is not awaited on the stall-timeout kill path. The in-memory store is
1527
1534
  // already updated; only a crash between here and the queued write loses it,
1528
1535
  // which is the pre-#1926 status quo for an already-abnormal termination.
1536
+ rememberProxyIncomplete(proxyIncompleteContext, "upstream_stall_timeout");
1529
1537
  emit("response.incomplete", {
1530
1538
  response: {
1531
1539
  ...responseSnapshot("incomplete", finishedItems),
@@ -1558,7 +1566,7 @@ export function bridgeToResponsesSSE(
1558
1566
  }, heartbeatMs);
1559
1567
  };
1560
1568
 
1561
- return new ReadableStream<Uint8Array>({
1569
+ return carryProxyIncompleteContext(proxyIncompleteContext, new ReadableStream<Uint8Array>({
1562
1570
  start(streamController) {
1563
1571
  controller = streamController;
1564
1572
  startStream();
@@ -1577,5 +1585,5 @@ export function bridgeToResponsesSSE(
1577
1585
  releasePendingWebSources();
1578
1586
  disposeOwnedBudget();
1579
1587
  },
1580
- });
1588
+ }));
1581
1589
  }
@@ -0,0 +1,21 @@
1
+ import type { ClientErrorContract } from "../lib/client-error-body";
2
+ import { isCyberPolicyMessage, isTerminalRefusalCode } from "../lib/errors";
3
+ export interface FailureVerdict { status: number; type: string; code: string | null; message: string }
4
+ /** Passed explicitly through producer, lifetime wrappers and collector for one response. */
5
+ export interface FailureVerdictSink { verdict?: FailureVerdict; contract?: ClientErrorContract; proxyAuthored?: boolean }
6
+ export function legacyStreamErrorStatus(message: string): number {
7
+ const lower = message.toLowerCase();
8
+ if (isCyberPolicyMessage(lower)) return 400;
9
+ if (lower.includes("truncated")) return 502;
10
+ if (lower.includes("rate") || lower.includes("429")) return 429;
11
+ if (lower.includes("unauthor") || lower.includes("401") || lower.includes("api key")) return 401;
12
+ if (lower.includes("not found") || lower.includes("404")) return 404;
13
+ if (lower.includes("invalid") || lower.includes("400")) return 400;
14
+ return 502;
15
+ }
16
+ export function legacyFailureVerdict(payload: Record<string, unknown>): FailureVerdict {
17
+ const error = payload.error as { message: string; type: string; code: string | null };
18
+ const { message, code } = error;
19
+ return { message, code, type: code === "translation_buffer_limit" ? "upstream_error" : error.type,
20
+ status: code === "translation_buffer_limit" ? 502 : isTerminalRefusalCode(code) || isCyberPolicyMessage(message) ? 400 : legacyStreamErrorStatus(message) };
21
+ }