@remodex/rmx 1.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (588) hide show
  1. package/AGENTS_INSTALL.md +91 -0
  2. package/LICENSE +21 -0
  3. package/README.md +242 -0
  4. package/assets/architecture.png +0 -0
  5. package/assets/banner.png +0 -0
  6. package/assets/claude-code-models.gif +0 -0
  7. package/assets/codex-app-picker.png +0 -0
  8. package/bin/ocx.mjs +584 -0
  9. package/bin/package-main.mjs +9 -0
  10. package/gui/dist/assets/index-CZqebSPQ.css +1 -0
  11. package/gui/dist/assets/index-CkETtt7P.js +71 -0
  12. package/gui/dist/favicon.png +0 -0
  13. package/gui/dist/fonts/google-sans-cyrillic.woff2 +0 -0
  14. package/gui/dist/fonts/google-sans-latin.woff2 +0 -0
  15. package/gui/dist/icons.svg +24 -0
  16. package/gui/dist/index.html +25 -0
  17. package/gui/dist/logo.png +0 -0
  18. package/gui/dist/provider-icons/alibaba-color.svg +1 -0
  19. package/gui/dist/provider-icons/antigravity-color.svg +1 -0
  20. package/gui/dist/provider-icons/claude-color.svg +1 -0
  21. package/gui/dist/provider-icons/cline-color.svg +16 -0
  22. package/gui/dist/provider-icons/cloudflare-ai-gateway-color.svg +1 -0
  23. package/gui/dist/provider-icons/commandcode-color.svg +1 -0
  24. package/gui/dist/provider-icons/copilot-color.svg +1 -0
  25. package/gui/dist/provider-icons/cursor-color.svg +2 -0
  26. package/gui/dist/provider-icons/deepseek-color.svg +1 -0
  27. package/gui/dist/provider-icons/discord.svg +1 -0
  28. package/gui/dist/provider-icons/firepass-color.svg +1 -0
  29. package/gui/dist/provider-icons/fireworks-color.svg +1 -0
  30. package/gui/dist/provider-icons/gemini-color.svg +1 -0
  31. package/gui/dist/provider-icons/github-copilot-color.svg +1 -0
  32. package/gui/dist/provider-icons/gitlab-duo-color.svg +1 -0
  33. package/gui/dist/provider-icons/grok.svg +1 -0
  34. package/gui/dist/provider-icons/groq-color.svg +1 -0
  35. package/gui/dist/provider-icons/huggingface-color.svg +1 -0
  36. package/gui/dist/provider-icons/kimi-color.svg +1 -0
  37. package/gui/dist/provider-icons/kiro-color.svg +15 -0
  38. package/gui/dist/provider-icons/lm-studio-color.svg +1 -0
  39. package/gui/dist/provider-icons/mistral-color.svg +1 -0
  40. package/gui/dist/provider-icons/moonshot-color.svg +1 -0
  41. package/gui/dist/provider-icons/nvidia-color.svg +1 -0
  42. package/gui/dist/provider-icons/ollama-color.svg +1 -0
  43. package/gui/dist/provider-icons/openai.svg +1 -0
  44. package/gui/dist/provider-icons/opencode.svg +2 -0
  45. package/gui/dist/provider-icons/openrouter-color.svg +1 -0
  46. package/gui/dist/provider-icons/pi.svg +21 -0
  47. package/gui/dist/provider-icons/qianfan-color.svg +1 -0
  48. package/gui/dist/provider-icons/qwen-portal-color.svg +1 -0
  49. package/gui/dist/provider-icons/telegram.svg +1 -0
  50. package/gui/dist/provider-icons/vercel-ai-gateway-color.svg +1 -0
  51. package/gui/dist/provider-icons/vllm-color.svg +1 -0
  52. package/gui/dist/provider-icons/xiaomi-color.svg +1 -0
  53. package/package.json +118 -0
  54. package/src/AGENTS.md +28 -0
  55. package/src/adapters/anthropic-image-guard.ts +251 -0
  56. package/src/adapters/anthropic-image-normalize.ts +518 -0
  57. package/src/adapters/anthropic.ts +1205 -0
  58. package/src/adapters/azure.ts +36 -0
  59. package/src/adapters/base.ts +83 -0
  60. package/src/adapters/client-fingerprint.ts +59 -0
  61. package/src/adapters/command-code.ts +453 -0
  62. package/src/adapters/cursor/arg-codec.ts +38 -0
  63. package/src/adapters/cursor/arg-normalize.ts +104 -0
  64. package/src/adapters/cursor/cursor-errors.ts +165 -0
  65. package/src/adapters/cursor/discovery.ts +276 -0
  66. package/src/adapters/cursor/effort-map.ts +139 -0
  67. package/src/adapters/cursor/exec-policy.ts +88 -0
  68. package/src/adapters/cursor/framing.ts +250 -0
  69. package/src/adapters/cursor/gen/agent_pb.ts +15274 -0
  70. package/src/adapters/cursor/kv-store.ts +52 -0
  71. package/src/adapters/cursor/live-models.ts +153 -0
  72. package/src/adapters/cursor/live-smoke-gate.ts +41 -0
  73. package/src/adapters/cursor/live-transport.ts +1235 -0
  74. package/src/adapters/cursor/mcp-config.ts +42 -0
  75. package/src/adapters/cursor/mcp-manager.ts +333 -0
  76. package/src/adapters/cursor/message-mapper.ts +49 -0
  77. package/src/adapters/cursor/native-exec-common.ts +59 -0
  78. package/src/adapters/cursor/native-exec-desktop.ts +184 -0
  79. package/src/adapters/cursor/native-exec-fs.ts +332 -0
  80. package/src/adapters/cursor/native-exec-mcp.ts +153 -0
  81. package/src/adapters/cursor/native-exec-network.ts +43 -0
  82. package/src/adapters/cursor/native-exec-shell.ts +548 -0
  83. package/src/adapters/cursor/native-exec-tools.ts +118 -0
  84. package/src/adapters/cursor/native-exec.ts +604 -0
  85. package/src/adapters/cursor/protobuf-events.ts +735 -0
  86. package/src/adapters/cursor/protobuf-request.ts +719 -0
  87. package/src/adapters/cursor/request-builder.ts +280 -0
  88. package/src/adapters/cursor/thread-continuity.ts +67 -0
  89. package/src/adapters/cursor/tool-definitions.ts +621 -0
  90. package/src/adapters/cursor/transport-retry.ts +132 -0
  91. package/src/adapters/cursor/transport.ts +57 -0
  92. package/src/adapters/cursor/types.ts +59 -0
  93. package/src/adapters/cursor.ts +196 -0
  94. package/src/adapters/google-antigravity-replay.ts +520 -0
  95. package/src/adapters/google-antigravity-wire.ts +140 -0
  96. package/src/adapters/google-errors.ts +85 -0
  97. package/src/adapters/google-http.ts +100 -0
  98. package/src/adapters/google-tool-schema.ts +173 -0
  99. package/src/adapters/google-truncation.ts +24 -0
  100. package/src/adapters/google-wire-compiler.ts +232 -0
  101. package/src/adapters/google.ts +859 -0
  102. package/src/adapters/identity.ts +77 -0
  103. package/src/adapters/image.ts +23 -0
  104. package/src/adapters/kiro-constants.ts +16 -0
  105. package/src/adapters/kiro-errors.ts +208 -0
  106. package/src/adapters/kiro-events.ts +197 -0
  107. package/src/adapters/kiro-images.ts +129 -0
  108. package/src/adapters/kiro-retry.ts +312 -0
  109. package/src/adapters/kiro-thinking.ts +104 -0
  110. package/src/adapters/kiro-tool-fallback.ts +36 -0
  111. package/src/adapters/kiro-tools.ts +224 -0
  112. package/src/adapters/kiro-truncation.ts +33 -0
  113. package/src/adapters/kiro-wire.ts +129 -0
  114. package/src/adapters/kiro.ts +1924 -0
  115. package/src/adapters/mimo-free.ts +263 -0
  116. package/src/adapters/openai-chat.ts +1265 -0
  117. package/src/adapters/openai-responses.ts +1309 -0
  118. package/src/adapters/run-turn-queue.ts +114 -0
  119. package/src/adapters/tool-catalog-nudge.ts +71 -0
  120. package/src/adapters/upstream-http-error.ts +48 -0
  121. package/src/android-remote/assets.ts +218 -0
  122. package/src/android-remote/attachments.ts +168 -0
  123. package/src/android-remote/auth.ts +237 -0
  124. package/src/android-remote/cloudflare-provisioning.ts +409 -0
  125. package/src/android-remote/cloudflare-secret.ts +106 -0
  126. package/src/android-remote/cloudflare-tunnel.ts +488 -0
  127. package/src/android-remote/cloudflared.ts +286 -0
  128. package/src/android-remote/codex-app-server.ts +565 -0
  129. package/src/android-remote/desktop-history-page.ts +936 -0
  130. package/src/android-remote/desktop-ipc.ts +3643 -0
  131. package/src/android-remote/desktop-ownership-store.ts +98 -0
  132. package/src/android-remote/desktop-project-registration.ts +129 -0
  133. package/src/android-remote/desktop-session-stream.ts +1110 -0
  134. package/src/android-remote/desktop-workspace-state.ts +443 -0
  135. package/src/android-remote/file-change-parser.ts +112 -0
  136. package/src/android-remote/gateway.ts +9108 -0
  137. package/src/android-remote/mutation-store.ts +299 -0
  138. package/src/android-remote/projection.ts +1780 -0
  139. package/src/android-remote/queued-turn-store.ts +248 -0
  140. package/src/android-remote/session-command-recovery.ts +1384 -0
  141. package/src/android-remote/store.ts +466 -0
  142. package/src/android-remote/thread-reconciliation.ts +133 -0
  143. package/src/android-remote/thread-source-paths.ts +307 -0
  144. package/src/android-remote/thread-stream.ts +546 -0
  145. package/src/android-remote/turn-activity.ts +235 -0
  146. package/src/android-remote/user-message-identity.ts +94 -0
  147. package/src/bridge.ts +1793 -0
  148. package/src/chat/inbound.ts +295 -0
  149. package/src/chat/outbound.ts +821 -0
  150. package/src/claude/agents-inject.ts +267 -0
  151. package/src/claude/alias.ts +149 -0
  152. package/src/claude/auth-detect.ts +229 -0
  153. package/src/claude/auth-mode-migration.ts +32 -0
  154. package/src/claude/auth-mode.ts +62 -0
  155. package/src/claude/context-windows.ts +189 -0
  156. package/src/claude/desktop-3p-guard.ts +35 -0
  157. package/src/claude/desktop-3p-paths.ts +84 -0
  158. package/src/claude/desktop-3p.ts +601 -0
  159. package/src/claude/desktop-health.ts +26 -0
  160. package/src/claude/desktop-profile.ts +263 -0
  161. package/src/claude/gateway-cache.ts +70 -0
  162. package/src/claude/inbound-debug.ts +163 -0
  163. package/src/claude/inbound.ts +519 -0
  164. package/src/claude/model-info.ts +154 -0
  165. package/src/claude/outbound.ts +898 -0
  166. package/src/cli/access.ts +108 -0
  167. package/src/cli/account-api.ts +296 -0
  168. package/src/cli/account-auth.ts +250 -0
  169. package/src/cli/account-catalog-refresh.ts +14 -0
  170. package/src/cli/account-extended.ts +476 -0
  171. package/src/cli/account-main.ts +317 -0
  172. package/src/cli/account.ts +297 -0
  173. package/src/cli/agent-driven.ts +70 -0
  174. package/src/cli/agent.ts +184 -0
  175. package/src/cli/catalog-prewarm.ts +27 -0
  176. package/src/cli/claude-desktop.ts +211 -0
  177. package/src/cli/claude.ts +302 -0
  178. package/src/cli/codex-shim-autorestore.ts +45 -0
  179. package/src/cli/codex-shim-readiness.ts +69 -0
  180. package/src/cli/combo.ts +124 -0
  181. package/src/cli/config-command.ts +183 -0
  182. package/src/cli/debug.ts +228 -0
  183. package/src/cli/desktop-first-run.ts +25 -0
  184. package/src/cli/doctor.ts +1022 -0
  185. package/src/cli/export-command.ts +201 -0
  186. package/src/cli/help.ts +370 -0
  187. package/src/cli/index.ts +1565 -0
  188. package/src/cli/init.ts +224 -0
  189. package/src/cli/integrations.ts +225 -0
  190. package/src/cli/interactive-confirm.ts +133 -0
  191. package/src/cli/internal-dispatch.ts +35 -0
  192. package/src/cli/launcher-context.ts +77 -0
  193. package/src/cli/models-runtime.ts +224 -0
  194. package/src/cli/models.ts +340 -0
  195. package/src/cli/observe.ts +170 -0
  196. package/src/cli/opencode.ts +587 -0
  197. package/src/cli/provider-runtime.ts +179 -0
  198. package/src/cli/provider.ts +476 -0
  199. package/src/cli/ready.ts +301 -0
  200. package/src/cli/route-policy.ts +92 -0
  201. package/src/cli/runtime-api.ts +328 -0
  202. package/src/cli/star-prompt.ts +211 -0
  203. package/src/cli/status-oauth.ts +78 -0
  204. package/src/cli/status.ts +321 -0
  205. package/src/cli/system-command.ts +196 -0
  206. package/src/cli/system-restart-client.ts +146 -0
  207. package/src/cli/tray-proxy.ts +205 -0
  208. package/src/cli/v2.ts +200 -0
  209. package/src/cli.ts +10 -0
  210. package/src/clients/config-export.ts +1109 -0
  211. package/src/codex/account-id.ts +34 -0
  212. package/src/codex/account-label.ts +34 -0
  213. package/src/codex/account-lifecycle.ts +172 -0
  214. package/src/codex/account-namespace-match.ts +63 -0
  215. package/src/codex/account-namespaces.ts +195 -0
  216. package/src/codex/account-pause.ts +20 -0
  217. package/src/codex/account-priority.ts +83 -0
  218. package/src/codex/account-runtime-state.ts +31 -0
  219. package/src/codex/account-store.ts +517 -0
  220. package/src/codex/account-usability.ts +40 -0
  221. package/src/codex/admission.ts +263 -0
  222. package/src/codex/app-server-processes.ts +799 -0
  223. package/src/codex/auth-api.ts +2098 -0
  224. package/src/codex/auth-collision.ts +107 -0
  225. package/src/codex/auth-context.ts +480 -0
  226. package/src/codex/autostart-health.ts +156 -0
  227. package/src/codex/catalog/account-models.ts +67 -0
  228. package/src/codex/catalog/aggregation.ts +471 -0
  229. package/src/codex/catalog/bundled.ts +533 -0
  230. package/src/codex/catalog/effort.ts +432 -0
  231. package/src/codex/catalog/filesystem-evidence.ts +302 -0
  232. package/src/codex/catalog/kinds.ts +2 -0
  233. package/src/codex/catalog/metadata.ts +287 -0
  234. package/src/codex/catalog/native-models.ts +7 -0
  235. package/src/codex/catalog/parsing.ts +503 -0
  236. package/src/codex/catalog/provider-fetch.ts +2267 -0
  237. package/src/codex/catalog/sync.ts +1606 -0
  238. package/src/codex/catalog-admission.ts +197 -0
  239. package/src/codex/catalog-refresh-status.ts +87 -0
  240. package/src/codex/catalog-write-serialization.ts +242 -0
  241. package/src/codex/catalog.ts +15 -0
  242. package/src/codex/codex-write-lock.ts +384 -0
  243. package/src/codex/convergence-types.ts +593 -0
  244. package/src/codex/convergence.ts +580 -0
  245. package/src/codex/custom-model-catalog-migration.ts +176 -0
  246. package/src/codex/data/upstream-models.json +830 -0
  247. package/src/codex/desired-state.ts +230 -0
  248. package/src/codex/desktop-client-processes.ts +521 -0
  249. package/src/codex/exec-invocation.ts +22 -0
  250. package/src/codex/features.ts +1091 -0
  251. package/src/codex/generation.ts +202 -0
  252. package/src/codex/history-job.ts +347 -0
  253. package/src/codex/history-lock.ts +242 -0
  254. package/src/codex/history-migration-guardian.ts +115 -0
  255. package/src/codex/history-provider.ts +1075 -0
  256. package/src/codex/history-transition.ts +105 -0
  257. package/src/codex/history-worker.ts +204 -0
  258. package/src/codex/home.ts +206 -0
  259. package/src/codex/inject-coordination.ts +257 -0
  260. package/src/codex/inject.ts +1857 -0
  261. package/src/codex/injected-marker.ts +79 -0
  262. package/src/codex/integration-record.ts +266 -0
  263. package/src/codex/internal/catalog-writer.ts +203 -0
  264. package/src/codex/internal/history-writer.ts +105 -0
  265. package/src/codex/journal.ts +172 -0
  266. package/src/codex/main-account-cache.ts +56 -0
  267. package/src/codex/main-account.ts +40 -0
  268. package/src/codex/management-convergence.ts +114 -0
  269. package/src/codex/model-cache.ts +267 -0
  270. package/src/codex/native-main-admission.ts +47 -0
  271. package/src/codex/native-main-auth-temp.ts +187 -0
  272. package/src/codex/native-main-claim.ts +167 -0
  273. package/src/codex/native-main-lock-file.ts +162 -0
  274. package/src/codex/native-main-owner.ts +329 -0
  275. package/src/codex/native-profile-api.ts +247 -0
  276. package/src/codex/native-profile-manager.ts +1531 -0
  277. package/src/codex/native-profile-processes.ts +121 -0
  278. package/src/codex/native-profile-recovery.ts +99 -0
  279. package/src/codex/native-profile-stage-store.ts +387 -0
  280. package/src/codex/native-profile-startup.ts +348 -0
  281. package/src/codex/native-profile-store.ts +855 -0
  282. package/src/codex/native-profile-types.ts +120 -0
  283. package/src/codex/native-residue.ts +691 -0
  284. package/src/codex/paths.ts +78 -0
  285. package/src/codex/plugins-doctor.ts +242 -0
  286. package/src/codex/pool-rotation.ts +295 -0
  287. package/src/codex/project-config-warnings.ts +426 -0
  288. package/src/codex/prompt-journal.ts +311 -0
  289. package/src/codex/prompt-layers.ts +967 -0
  290. package/src/codex/prompt-lock.ts +143 -0
  291. package/src/codex/provider-adoption.ts +242 -0
  292. package/src/codex/quota-rejection.ts +224 -0
  293. package/src/codex/quota.ts +494 -0
  294. package/src/codex/refresh.ts +60 -0
  295. package/src/codex/routing.ts +1855 -0
  296. package/src/codex/runtime.ts +659 -0
  297. package/src/codex/shim.ts +1215 -0
  298. package/src/codex/subagent-defaults.ts +557 -0
  299. package/src/codex/subagent-model-fallback.ts +560 -0
  300. package/src/codex/sync.ts +238 -0
  301. package/src/codex/transition-state.ts +612 -0
  302. package/src/codex/upstream-host-health.ts +368 -0
  303. package/src/codex/user-identity.ts +374 -0
  304. package/src/codex/warmup.ts +192 -0
  305. package/src/codex/websocket-registry.ts +100 -0
  306. package/src/codex/write-coordination.ts +114 -0
  307. package/src/combos/failover.ts +140 -0
  308. package/src/combos/index.ts +44 -0
  309. package/src/combos/request.ts +64 -0
  310. package/src/combos/resolve.ts +232 -0
  311. package/src/combos/types.ts +392 -0
  312. package/src/config.ts +3270 -0
  313. package/src/generated/model-metadata.ts +144 -0
  314. package/src/github/star-state.ts +203 -0
  315. package/src/grok/inject.ts +540 -0
  316. package/src/grok/inspect.ts +45 -0
  317. package/src/grok/status.ts +127 -0
  318. package/src/grok/sync.ts +66 -0
  319. package/src/images/artifacts.ts +516 -0
  320. package/src/images/fulfill-video.ts +163 -0
  321. package/src/images/fulfill.ts +149 -0
  322. package/src/images/index.ts +4 -0
  323. package/src/images/loop.ts +922 -0
  324. package/src/images/plan.ts +133 -0
  325. package/src/images/synthetic-tool.ts +133 -0
  326. package/src/images/types.ts +41 -0
  327. package/src/images/xai-client.ts +141 -0
  328. package/src/images/xai-video-client.ts +163 -0
  329. package/src/index.ts +22 -0
  330. package/src/integrations/config-io.ts +151 -0
  331. package/src/integrations/journal.ts +315 -0
  332. package/src/integrations/merge.ts +135 -0
  333. package/src/integrations/native/ownership-preflight.ts +202 -0
  334. package/src/integrations/ownership.ts +111 -0
  335. package/src/integrations/registry.ts +108 -0
  336. package/src/integrations/serialize.ts +235 -0
  337. package/src/integrations/state.ts +290 -0
  338. package/src/integrations/store.ts +103 -0
  339. package/src/integrations/writer.ts +492 -0
  340. package/src/lib/abort.ts +146 -0
  341. package/src/lib/admin-secrets.ts +25 -0
  342. package/src/lib/admission.ts +83 -0
  343. package/src/lib/app-owned-memory-stores.ts +173 -0
  344. package/src/lib/app-owned-memory.ts +265 -0
  345. package/src/lib/bounded-body.ts +242 -0
  346. package/src/lib/bun-binary-validator.d.mts +3 -0
  347. package/src/lib/bun-binary-validator.mjs +18 -0
  348. package/src/lib/bun-runtime.ts +184 -0
  349. package/src/lib/bun-stream-caps.ts +127 -0
  350. package/src/lib/config-ownership.ts +438 -0
  351. package/src/lib/crash-guard.ts +344 -0
  352. package/src/lib/debug-log-buffer.ts +83 -0
  353. package/src/lib/debug-settings.ts +108 -0
  354. package/src/lib/debug.ts +31 -0
  355. package/src/lib/destination-policy.ts +316 -0
  356. package/src/lib/errors.ts +364 -0
  357. package/src/lib/eventstream-decoder.ts +253 -0
  358. package/src/lib/gcp-adc.ts +341 -0
  359. package/src/lib/injection-debug-log.ts +58 -0
  360. package/src/lib/local-management-attestation.ts +51 -0
  361. package/src/lib/open-url.ts +25 -0
  362. package/src/lib/pinned-http.ts +182 -0
  363. package/src/lib/privacy.ts +20 -0
  364. package/src/lib/process-control.ts +168 -0
  365. package/src/lib/provider-environment.ts +470 -0
  366. package/src/lib/provider-outbound.ts +203 -0
  367. package/src/lib/provider-url.ts +14 -0
  368. package/src/lib/proxy-env.ts +18 -0
  369. package/src/lib/redact.ts +510 -0
  370. package/src/lib/remodex-home.ts +616 -0
  371. package/src/lib/retry-after.ts +55 -0
  372. package/src/lib/service-secrets.ts +178 -0
  373. package/src/lib/shadow-call.ts +54 -0
  374. package/src/lib/sidecar-tracker.ts +52 -0
  375. package/src/lib/sse-decoder.ts +364 -0
  376. package/src/lib/state-store-registrations.ts +109 -0
  377. package/src/lib/state-store-sweeper.ts +184 -0
  378. package/src/lib/system-restart-contract.ts +73 -0
  379. package/src/lib/test-home-guard.ts +98 -0
  380. package/src/lib/token-estimate.ts +69 -0
  381. package/src/lib/translator-budget.ts +366 -0
  382. package/src/lib/upstream-reachability.ts +91 -0
  383. package/src/lib/upstream-retry.ts +508 -0
  384. package/src/lib/win-exec.ts +115 -0
  385. package/src/lib/win-paths.ts +68 -0
  386. package/src/lib/windows-elevation.ts +705 -0
  387. package/src/lib/windows-secret-acl.ts +817 -0
  388. package/src/lib/windows-user-principal.ts +283 -0
  389. package/src/lib/winsw.ts +402 -0
  390. package/src/model-sources.ts +73 -0
  391. package/src/oauth/anthropic-routing.ts +594 -0
  392. package/src/oauth/anthropic.ts +177 -0
  393. package/src/oauth/callback-server.ts +294 -0
  394. package/src/oauth/chatgpt.ts +150 -0
  395. package/src/oauth/command-code.ts +239 -0
  396. package/src/oauth/cursor.ts +231 -0
  397. package/src/oauth/github-copilot.ts +428 -0
  398. package/src/oauth/google-antigravity.ts +230 -0
  399. package/src/oauth/health.ts +443 -0
  400. package/src/oauth/index.ts +1280 -0
  401. package/src/oauth/key-providers.ts +128 -0
  402. package/src/oauth/kimi.ts +213 -0
  403. package/src/oauth/kiro-credentials.ts +726 -0
  404. package/src/oauth/kiro.ts +621 -0
  405. package/src/oauth/local-token-detect.ts +121 -0
  406. package/src/oauth/log.ts +48 -0
  407. package/src/oauth/login-cli.ts +163 -0
  408. package/src/oauth/pkce.ts +15 -0
  409. package/src/oauth/store.ts +655 -0
  410. package/src/oauth/token-guardian.ts +309 -0
  411. package/src/oauth/types.ts +62 -0
  412. package/src/oauth/xai.ts +241 -0
  413. package/src/providers/alibaba-region-backup.ts +75 -0
  414. package/src/providers/alibaba-region-migration.ts +156 -0
  415. package/src/providers/alibaba-region-startup.ts +36 -0
  416. package/src/providers/antigravity-models.ts +317 -0
  417. package/src/providers/api-keys.ts +140 -0
  418. package/src/providers/base-url-choices.ts +64 -0
  419. package/src/providers/codex-capacity.ts +288 -0
  420. package/src/providers/command-code-efforts.ts +85 -0
  421. package/src/providers/context-cap.ts +73 -0
  422. package/src/providers/derive.ts +451 -0
  423. package/src/providers/free-directory.ts +187 -0
  424. package/src/providers/github-copilot-transport.ts +56 -0
  425. package/src/providers/google-vertex-location.ts +14 -0
  426. package/src/providers/key-failover.ts +271 -0
  427. package/src/providers/kiro-models.ts +67 -0
  428. package/src/providers/label.ts +19 -0
  429. package/src/providers/model-discovery-limits.ts +16 -0
  430. package/src/providers/model-discovery.ts +361 -0
  431. package/src/providers/openai-sidecar.ts +235 -0
  432. package/src/providers/openai-tier-startup.ts +27 -0
  433. package/src/providers/openai-tiers.ts +301 -0
  434. package/src/providers/openai-virtual-models.ts +83 -0
  435. package/src/providers/openrouter-routing.ts +102 -0
  436. package/src/providers/provider-id-rewrite.ts +179 -0
  437. package/src/providers/quota.ts +1942 -0
  438. package/src/providers/reasoning-capabilities.ts +336 -0
  439. package/src/providers/registry.ts +2375 -0
  440. package/src/providers/slug-codec.ts +74 -0
  441. package/src/providers/xai-transport.ts +149 -0
  442. package/src/reasoning-effort.ts +243 -0
  443. package/src/responses/compaction.ts +124 -0
  444. package/src/responses/hosted-tool-policy.ts +9 -0
  445. package/src/responses/parser.ts +714 -0
  446. package/src/responses/reasoning-envelope.ts +60 -0
  447. package/src/responses/reasoning-replay-cache.ts +106 -0
  448. package/src/responses/schema.ts +159 -0
  449. package/src/responses/spill-store.ts +431 -0
  450. package/src/responses/state.ts +1039 -0
  451. package/src/responses/tool-groups.ts +19 -0
  452. package/src/router.ts +802 -0
  453. package/src/routing/analytics.ts +377 -0
  454. package/src/routing/capability.ts +205 -0
  455. package/src/routing/cost.ts +77 -0
  456. package/src/routing/evaluator.ts +444 -0
  457. package/src/routing/health.ts +401 -0
  458. package/src/routing/history/cursor.ts +43 -0
  459. package/src/routing/history/indexer.ts +605 -0
  460. package/src/routing/history/schema.ts +72 -0
  461. package/src/routing/profile-namespace.ts +15 -0
  462. package/src/routing/profile.ts +424 -0
  463. package/src/routing/quota.ts +145 -0
  464. package/src/routing/request-evidence.ts +45 -0
  465. package/src/routing/trace.ts +686 -0
  466. package/src/server/adapter-resolve.ts +83 -0
  467. package/src/server/auth-cors.ts +606 -0
  468. package/src/server/chat-completions.ts +379 -0
  469. package/src/server/claude-messages.ts +980 -0
  470. package/src/server/effort-policy.ts +251 -0
  471. package/src/server/github-copilot-responses-repair.ts +338 -0
  472. package/src/server/gui-static.ts +152 -0
  473. package/src/server/image-retry.ts +42 -0
  474. package/src/server/images.ts +485 -0
  475. package/src/server/index.ts +1633 -0
  476. package/src/server/lifecycle.ts +482 -0
  477. package/src/server/live.ts +609 -0
  478. package/src/server/management/agent-settings-routes.ts +1180 -0
  479. package/src/server/management/android-remote-routes.ts +390 -0
  480. package/src/server/management/api-access.ts +141 -0
  481. package/src/server/management/api-key-usage.ts +167 -0
  482. package/src/server/management/body.ts +35 -0
  483. package/src/server/management/combo-routes.ts +244 -0
  484. package/src/server/management/config-routes.ts +602 -0
  485. package/src/server/management/context.ts +88 -0
  486. package/src/server/management/integration-routes.ts +538 -0
  487. package/src/server/management/logs-usage-routes.ts +516 -0
  488. package/src/server/management/model-routes.ts +519 -0
  489. package/src/server/management/model-rows.ts +143 -0
  490. package/src/server/management/native-integration-routes.ts +781 -0
  491. package/src/server/management/oauth-account-routes.ts +573 -0
  492. package/src/server/management/provider-routes.ts +781 -0
  493. package/src/server/management/request-history-routes.ts +191 -0
  494. package/src/server/management/routing-analytics-routes.ts +74 -0
  495. package/src/server/management/routing-profile-routes.ts +384 -0
  496. package/src/server/management/shared.ts +277 -0
  497. package/src/server/management/sidebar-routes.ts +106 -0
  498. package/src/server/management/sync-response.ts +69 -0
  499. package/src/server/management/system-restart.ts +433 -0
  500. package/src/server/management/system-routes.ts +141 -0
  501. package/src/server/management/usage-summary-cache.ts +86 -0
  502. package/src/server/management-api.ts +269 -0
  503. package/src/server/management-auth.ts +353 -0
  504. package/src/server/memory-watchdog.ts +156 -0
  505. package/src/server/port-reclaim.ts +307 -0
  506. package/src/server/ports.ts +156 -0
  507. package/src/server/proxy-liveness.ts +326 -0
  508. package/src/server/proxy-stop.ts +92 -0
  509. package/src/server/readiness.ts +99 -0
  510. package/src/server/relay-eager.ts +353 -0
  511. package/src/server/relay.ts +1179 -0
  512. package/src/server/request-decompress.ts +132 -0
  513. package/src/server/request-log-conversation.ts +168 -0
  514. package/src/server/request-log.ts +1072 -0
  515. package/src/server/responses/collaboration.ts +409 -0
  516. package/src/server/responses/compact.ts +710 -0
  517. package/src/server/responses/core.ts +3561 -0
  518. package/src/server/responses/encrypted-payload.ts +308 -0
  519. package/src/server/responses/fetch-helpers.ts +171 -0
  520. package/src/server/responses/passthrough-error.ts +78 -0
  521. package/src/server/responses/policy-fallback.ts +152 -0
  522. package/src/server/responses/terminal-guard.ts +230 -0
  523. package/src/server/responses/upstream-error.ts +48 -0
  524. package/src/server/responses-image-gen-repair.ts +132 -0
  525. package/src/server/responses-item-id-repair.ts +272 -0
  526. package/src/server/responses-json-events.ts +52 -0
  527. package/src/server/responses-model-rewrite.ts +29 -0
  528. package/src/server/responses-snapshot-repair.ts +621 -0
  529. package/src/server/responses.ts +10 -0
  530. package/src/server/search.ts +181 -0
  531. package/src/server/sse-frame-buffer.ts +292 -0
  532. package/src/server/sse-payload-rewrite.ts +263 -0
  533. package/src/server/startup-action-control.ts +308 -0
  534. package/src/server/startup-health-cache.ts +119 -0
  535. package/src/server/system-env.ts +418 -0
  536. package/src/server/windows-tcp-drop.ts +184 -0
  537. package/src/server/windows-tray-control.ts +41 -0
  538. package/src/server/ws-bridge.ts +470 -0
  539. package/src/service-manager-probe.ts +824 -0
  540. package/src/service.ts +3011 -0
  541. package/src/stall-timeout.ts +20 -0
  542. package/src/storage/cleanup-job.ts +57 -0
  543. package/src/storage/cleanup.ts +3085 -0
  544. package/src/storage/policy-job.ts +457 -0
  545. package/src/storage/policy-scheduler.ts +40 -0
  546. package/src/storage/policy-worker.ts +59 -0
  547. package/src/storage/policy.ts +527 -0
  548. package/src/storage/restore-job.ts +299 -0
  549. package/src/storage/restore-worker.ts +58 -0
  550. package/src/storage/scanner.ts +238 -0
  551. package/src/storage/storage-mutation-coordinator.ts +139 -0
  552. package/src/storage/worker-lifecycle.ts +215 -0
  553. package/src/tray/assets/opencodex-tray-offline.ico +0 -0
  554. package/src/tray/assets/opencodex-tray-online.ico +0 -0
  555. package/src/tray/assets/opencodex-tray-warning.ico +0 -0
  556. package/src/tray/assets/opencodex-tray.png +0 -0
  557. package/src/tray/windows-tray.ps1 +364 -0
  558. package/src/tray/windows.ts +738 -0
  559. package/src/types.ts +1531 -0
  560. package/src/update/badge.ts +72 -0
  561. package/src/update/desktop-release.ts +1620 -0
  562. package/src/update/index.ts +402 -0
  563. package/src/update/job.ts +1906 -0
  564. package/src/update/notify.ts +261 -0
  565. package/src/update/npm-cache-preflight.d.mts +47 -0
  566. package/src/update/npm-cache-preflight.mjs +201 -0
  567. package/src/update/npm-invocation.d.mts +23 -0
  568. package/src/update/npm-invocation.mjs +94 -0
  569. package/src/update/tray-update-plan.d.mts +18 -0
  570. package/src/update/tray-update-plan.mjs +38 -0
  571. package/src/usage/cost.ts +0 -0
  572. package/src/usage/debug.ts +97 -0
  573. package/src/usage/expected-prices.ts +283 -0
  574. package/src/usage/log.ts +695 -0
  575. package/src/usage/summary.ts +585 -0
  576. package/src/usage/totals.ts +14 -0
  577. package/src/vision/anthropic-describe.ts +185 -0
  578. package/src/vision/describe.ts +127 -0
  579. package/src/vision/index.ts +558 -0
  580. package/src/vision/reasoning.ts +55 -0
  581. package/src/web-search/anthropic-executor.ts +189 -0
  582. package/src/web-search/executor.ts +105 -0
  583. package/src/web-search/format-result.ts +89 -0
  584. package/src/web-search/index.ts +196 -0
  585. package/src/web-search/loop.ts +791 -0
  586. package/src/web-search/parse.ts +235 -0
  587. package/src/web-search/progress-stream.ts +342 -0
  588. package/src/web-search/synthetic-tool.ts +47 -0
@@ -0,0 +1,1309 @@
1
+ import { createHash } from "node:crypto";
2
+ import type { IncomingMeta, ProviderAdapter } from "./base";
3
+ import { namespacedToolName, type AdapterEvent, type OcxParsedRequest, type OcxProviderConfig, type OcxUsage } from "../types";
4
+ import { catalogModelSupportsReasoningSummaries } from "../codex/catalog";
5
+ import { COMPACT_PROMPT, decodeCompactionSummary, SUMMARY_PREFIX } from "../responses/compaction";
6
+ import { collectResponsesToolGroups } from "../responses/tool-groups";
7
+ import { isHostedToolUnsupportedForModel } from "../responses/hosted-tool-policy";
8
+ import { decodeServerSentEvents } from "../lib/sse-decoder";
9
+ import { isCanonicalOpenAiForwardProvider } from "../providers/openai-tiers";
10
+ import { OCX_REASONING_PREFIX } from "../responses/reasoning-envelope";
11
+ import { modelRecordValue } from "../reasoning-effort";
12
+ import type { TranslatorBudget } from "../lib/translator-budget";
13
+
14
+ // Headers relayed verbatim from the caller in OAuth-passthrough ("forward") mode.
15
+ // Exported so the web-search sidecar reuses the exact same forwarded-auth set for its ChatGPT call.
16
+ export const FORWARD_HEADERS = [
17
+ "authorization",
18
+ "chatgpt-account-id",
19
+ "openai-beta",
20
+ "originator",
21
+ "session_id",
22
+ "session-id",
23
+ "thread-id",
24
+ "x-client-request-id",
25
+ "x-codex-beta-features",
26
+ "x-codex-installation-id",
27
+ "x-codex-parent-thread-id",
28
+ "x-codex-turn-metadata",
29
+ "x-codex-turn-state",
30
+ "x-codex-window-id",
31
+ "x-oai-attestation",
32
+ "x-openai-subagent",
33
+ "x-responsesapi-include-timing-metrics",
34
+ ];
35
+
36
+ export function sanitizeReasoningInputContent(
37
+ body: unknown,
38
+ opts?: { preserveRawReasoningContent?: boolean },
39
+ ): unknown {
40
+ if (!body || typeof body !== "object" || Array.isArray(body)) return body;
41
+ const raw = body as Record<string, unknown>;
42
+ if (!Array.isArray(raw.input)) return body;
43
+
44
+ let changed = false;
45
+ const input = raw.input.map(item => {
46
+ if (!item || typeof item !== "object" || Array.isArray(item)) return item;
47
+ const rec = item as Record<string, unknown>;
48
+ if (rec.type !== "reasoning") return item;
49
+ const hasRawContent = Array.isArray(rec.content) && rec.content.length > 0;
50
+ // ocxr1 envelopes are proxy-minted (Anthropic signatures), not OpenAI encryption — the native
51
+ // backend cannot decrypt them and would reject the request. Strip regardless of content shape.
52
+ const hasOcxEnvelope = typeof rec.encrypted_content === "string" && rec.encrypted_content.startsWith(OCX_REASONING_PREFIX);
53
+ if (!hasRawContent && !hasOcxEnvelope) return item;
54
+ if (hasOcxEnvelope) {
55
+ changed = true;
56
+ const next: Record<string, unknown> = { ...rec };
57
+ delete next.encrypted_content;
58
+ if (!opts?.preserveRawReasoningContent) next.content = [];
59
+ return next;
60
+ }
61
+ // Routed models can produce raw `reasoning_text` output items. Codex echoes those in later
62
+ // native GPT requests, but ChatGPT's Responses backend accepts reasoning input only with empty
63
+ // `content`; keep summaries/ids and drop the raw content so native passthrough does not 400.
64
+ // DeepSeek's Responses API instead ACCEPTS plaintext reasoning replay (its compatibility
65
+ // guide merges reasoning items into the adjacent assistant message), so providers flagged
66
+ // `preserveResponsesReasoningContent` keep it — deleting valid replay content there breaks
67
+ // continuations after tool calls (issue #875 family).
68
+ if (opts?.preserveRawReasoningContent) return item;
69
+ changed = true;
70
+ return { ...rec, content: [] };
71
+ });
72
+
73
+ return changed ? { ...raw, input } : body;
74
+ }
75
+
76
+ function stripUnsupportedReasoningSummaryDelivery(body: unknown, modelId: string): unknown {
77
+ if (catalogModelSupportsReasoningSummaries(modelId) !== false) return body;
78
+ if (!isPlainObject(body) || !isPlainObject(body.stream_options)) return body;
79
+ if (!("reasoning_summary_delivery" in body.stream_options)) return body;
80
+
81
+ const streamOptions = { ...body.stream_options };
82
+ delete streamOptions.reasoning_summary_delivery;
83
+ const next = { ...body };
84
+ if (Object.keys(streamOptions).length > 0) next.stream_options = streamOptions;
85
+ else delete next.stream_options;
86
+ return next;
87
+ }
88
+
89
+ function stripInvalidItemIds(body: unknown): unknown {
90
+ if (!isPlainObject(body) || !Array.isArray(body.input)) return body;
91
+
92
+ const validPrefixes: Record<string, string> = {
93
+ message: "msg_",
94
+ agent_message: "amsg_",
95
+ reasoning: "rs_",
96
+ function_call: "fc_",
97
+ custom_tool_call: "ctc_",
98
+ tool_search_call: "tsc_",
99
+ web_search_call: "ws_",
100
+ };
101
+ let changed = false;
102
+ const input = body.input.map(item => {
103
+ if (!isPlainObject(item) || typeof item.type !== "string") return item;
104
+ const validPrefix = validPrefixes[item.type];
105
+ if (!validPrefix) return item;
106
+ if (typeof item.id === "string" && item.id.startsWith(validPrefix)) return item;
107
+ if (!("id" in item)) return item;
108
+ changed = true;
109
+ const next = { ...item };
110
+ delete next.id;
111
+ return next;
112
+ });
113
+
114
+ return changed ? { ...body, input } : body;
115
+ }
116
+
117
+ /**
118
+ * When `store` is false, the upstream API does not persist response items. Any item ID
119
+ * forwarded in `input` is then interpreted as a reference to a stored item that does not
120
+ * exist, producing a 404. Strip all item IDs in this case — `call_id` pairing is unaffected.
121
+ * Matches codex-rs behavior (core/src/client.rs:918-925).
122
+ */
123
+ function stripItemIdsWhenUnstored(body: unknown): unknown {
124
+ if (!isPlainObject(body) || body.store !== false) return body;
125
+ if (!Array.isArray(body.input)) return body;
126
+
127
+ let changed = false;
128
+ const input = body.input.map(item => {
129
+ if (!isPlainObject(item) || !("id" in item)) return item;
130
+ changed = true;
131
+ const next = { ...item };
132
+ delete next.id;
133
+ return next;
134
+ });
135
+
136
+ return changed ? { ...body, input } : body;
137
+ }
138
+
139
+ /**
140
+ * Replace proxy-minted compaction items (`encrypted_content` starting with `ocx1:`) with plain
141
+ * user messages before forwarding to the ChatGPT backend. Our envelope is transparent base64, not
142
+ * OpenAI encryption — the native backend cannot decrypt it and would reject the request. Real
143
+ * OpenAI-encrypted compaction items are forwarded untouched.
144
+ */
145
+ function scrubOcxCompactionItems(body: unknown): unknown {
146
+ if (!isPlainObject(body) || !Array.isArray(body.input)) return body;
147
+
148
+ let changed = false;
149
+ const input = body.input.map(item => {
150
+ if (!isPlainObject(item)) return item;
151
+ if (item.type !== "compaction" && item.type !== "compaction_summary" && item.type !== "context_compaction") return item;
152
+ const decoded = typeof item.encrypted_content === "string" ? decodeCompactionSummary(item.encrypted_content) : null;
153
+ if (decoded === null) return item;
154
+ changed = true;
155
+ return {
156
+ type: "message",
157
+ role: "user",
158
+ content: [{ type: "input_text", text: `${SUMMARY_PREFIX}\n\n${decoded}` }],
159
+ };
160
+ });
161
+
162
+ return changed ? { ...body, input } : body;
163
+ }
164
+
165
+ /**
166
+ * Strip unsupported `reasoning` sub-parameters for native slugs that reject them (e.g. Spark).
167
+ * codex-rs injects `reasoning.context` and `reasoning.summary` based on catalog flags; Spark's
168
+ * backend rejects both. The catalog fix prevents `use_responses_lite` from being set, but this
169
+ * is a defense-in-depth guard so stale on-disk catalogs don't break until the user runs `rmx sync`.
170
+ */
171
+ function stripUnsupportedReasoningParams(body: unknown): unknown {
172
+ if (!isPlainObject(body)) return body;
173
+ const model = typeof body.model === "string" ? body.model : "";
174
+ if (!model.includes("codex-spark")) return body;
175
+ if (!isPlainObject(body.reasoning)) return body;
176
+ const reasoning = body.reasoning as Record<string, unknown>;
177
+ // Spark supports reasoning.effort but rejects context, summary, and generate_summary.
178
+ const { context: _ctx, summary: _sum, generate_summary: _gs, ...rest } = reasoning;
179
+ if (_ctx === undefined && _sum === undefined && _gs === undefined) return body;
180
+ return { ...body, reasoning: Object.keys(rest).length > 0 ? rest : undefined };
181
+ }
182
+
183
+ /**
184
+ * A false model capability prevents Codex from emitting summary fields after the catalog refresh.
185
+ * Strip them here as well so an already-running client with a stale catalog cannot keep sending an
186
+ * upstream-rejected `reasoning_summary_delivery` value (issue #323).
187
+ */
188
+ function stripDisabledReasoningSummaries(
189
+ body: unknown,
190
+ provider: OcxProviderConfig,
191
+ modelId: string,
192
+ ): unknown {
193
+ if (modelRecordValue(provider.modelSupportsReasoningSummaries, modelId) !== false || !isPlainObject(body)) {
194
+ return body;
195
+ }
196
+
197
+ let changed = false;
198
+ let streamOptions = body.stream_options;
199
+ if (isPlainObject(streamOptions) && Object.hasOwn(streamOptions, "reasoning_summary_delivery")) {
200
+ const { reasoning_summary_delivery: _delivery, ...rest } = streamOptions;
201
+ streamOptions = rest;
202
+ changed = true;
203
+ }
204
+
205
+ let reasoning = body.reasoning;
206
+ if (isPlainObject(reasoning)) {
207
+ const { summary: _summary, generate_summary: _generateSummary, ...rest } = reasoning;
208
+ if (_summary !== undefined || _generateSummary !== undefined) {
209
+ reasoning = rest;
210
+ changed = true;
211
+ }
212
+ }
213
+
214
+ if (!changed) return body;
215
+ return {
216
+ ...body,
217
+ ...(isPlainObject(streamOptions) && Object.keys(streamOptions).length > 0
218
+ ? { stream_options: streamOptions }
219
+ : { stream_options: undefined }),
220
+ ...(isPlainObject(reasoning) && Object.keys(reasoning).length > 0
221
+ ? { reasoning }
222
+ : { reasoning: undefined }),
223
+ };
224
+ }
225
+
226
+ /**
227
+ * Normalize only the delivery enum Codex already emitted. Do not inject a field into callers that
228
+ * did not request summaries, and leave every unconfigured provider/model byte-for-byte unchanged.
229
+ */
230
+ function normalizeConfiguredReasoningSummaryDelivery(
231
+ body: unknown,
232
+ provider: OcxProviderConfig,
233
+ modelId: string,
234
+ ): unknown {
235
+ const delivery = modelRecordValue(provider.modelReasoningSummaryDelivery, modelId);
236
+ if (delivery === undefined || !isPlainObject(body) || !isPlainObject(body.stream_options)) return body;
237
+ if (!Object.hasOwn(body.stream_options, "reasoning_summary_delivery")) return body;
238
+ if (body.stream_options.reasoning_summary_delivery === delivery) return body;
239
+ return {
240
+ ...body,
241
+ stream_options: {
242
+ ...body.stream_options,
243
+ reasoning_summary_delivery: delivery,
244
+ },
245
+ };
246
+ }
247
+
248
+ /**
249
+ * Comprehensive Spark compatibility layer. codex-rs emits five tool types (function,
250
+ * namespace, tool_search, web_search, custom) plus extensions (defer_loading,
251
+ * parallel_tool_calls, tool_search_call/output items). Spark's serving path only
252
+ * supports flat function tools and hosted web_search. This function:
253
+ * - Flattens namespace tools → promotes inner functions to top level
254
+ * - Drops unsupported tool types (tool_search, custom)
255
+ * - Strips defer_loading from function tools
256
+ * - Strips namespace from input items
257
+ * - Drops tool_search_call/tool_search_output input items
258
+ * - Sets parallel_tool_calls to false
259
+ */
260
+ function stripSparkCompatibility(body: unknown): unknown {
261
+ if (!isPlainObject(body)) return body;
262
+ const model = typeof body.model === "string" ? body.model : "";
263
+ if (!model.includes("codex-spark")) return body;
264
+
265
+ let changed = false;
266
+
267
+ const SPARK_SAFE_TOOL_TYPES = new Set(["function", "web_search", "web_search_preview"]);
268
+
269
+ let tools = body.tools;
270
+ if (Array.isArray(tools)) {
271
+ const flattened: unknown[] = [];
272
+ for (const t of tools) {
273
+ if (isPlainObject(t) && t.type === "namespace") {
274
+ changed = true;
275
+ if (Array.isArray(t.tools)) {
276
+ for (const inner of t.tools) flattened.push(inner);
277
+ }
278
+ } else if (isPlainObject(t) && typeof t.type === "string" && !SPARK_SAFE_TOOL_TYPES.has(t.type)) {
279
+ changed = true;
280
+ } else {
281
+ flattened.push(t);
282
+ }
283
+ }
284
+ // Strip defer_loading from promoted/remaining function tools.
285
+ tools = flattened.map(t => {
286
+ if (isPlainObject(t) && t.type === "function" && "defer_loading" in t) {
287
+ const { defer_loading: _, ...rest } = t;
288
+ changed = true;
289
+ return rest;
290
+ }
291
+ return t;
292
+ });
293
+ }
294
+
295
+ // Clean input items: strip namespace, drop tool_search_call/tool_search_output.
296
+ const SPARK_UNSUPPORTED_INPUT_TYPES = new Set([
297
+ "tool_search_call", "tool_search_output",
298
+ "custom_tool_call", "custom_tool_call_output",
299
+ ]);
300
+ let input = body.input;
301
+ if (Array.isArray(input)) {
302
+ const cleaned: unknown[] = [];
303
+ for (const item of input) {
304
+ if (isPlainObject(item) && typeof item.type === "string" && SPARK_UNSUPPORTED_INPUT_TYPES.has(item.type)) {
305
+ changed = true;
306
+ continue;
307
+ }
308
+ // Process additional_tools items: filter their inner tools array the same way.
309
+ if (isPlainObject(item) && item.type === "additional_tools" && Array.isArray(item.tools)) {
310
+ const innerTools = item.tools as unknown[];
311
+ const filteredInner: unknown[] = [];
312
+ for (const t of innerTools) {
313
+ if (isPlainObject(t) && t.type === "namespace") {
314
+ changed = true;
315
+ if (Array.isArray(t.tools)) {
316
+ for (const fn of t.tools) filteredInner.push(fn);
317
+ }
318
+ } else if (isPlainObject(t) && typeof t.type === "string" && !SPARK_SAFE_TOOL_TYPES.has(t.type)) {
319
+ changed = true; // drop custom, tool_search, etc.
320
+ } else {
321
+ filteredInner.push(t);
322
+ }
323
+ }
324
+ // Strip defer_loading from remaining function tools.
325
+ const cleanedInner = filteredInner.map(t => {
326
+ if (isPlainObject(t) && t.type === "function" && "defer_loading" in t) {
327
+ const { defer_loading: _, ...rest } = t;
328
+ changed = true;
329
+ return rest;
330
+ }
331
+ return t;
332
+ });
333
+ cleaned.push({ ...item, tools: cleanedInner });
334
+ continue;
335
+ }
336
+ if (isPlainObject(item) && "namespace" in item) {
337
+ const { namespace: _, ...rest } = item;
338
+ changed = true;
339
+ cleaned.push(rest);
340
+ } else {
341
+ cleaned.push(item);
342
+ }
343
+ }
344
+ if (changed) input = cleaned;
345
+ }
346
+
347
+ // Force parallel_tool_calls off for Spark.
348
+ const extraOverrides: Record<string, unknown> = {};
349
+ if (body.parallel_tool_calls === true) { extraOverrides.parallel_tool_calls = false; changed = true; }
350
+
351
+ return changed
352
+ ? { ...body, ...(tools !== body.tools ? { tools } : {}), ...(input !== body.input ? { input } : {}), ...extraOverrides }
353
+ : body;
354
+ }
355
+
356
+ function isPlainObject(v: unknown): v is Record<string, unknown> {
357
+ return !!v && typeof v === "object" && !Array.isArray(v);
358
+ }
359
+
360
+ function normalizeFunctionToolSchema(tool: unknown): unknown {
361
+ if (!isPlainObject(tool) || tool.type !== "function") return tool;
362
+ if (isPlainObject(tool.parameters) && tool.parameters.type === "object") return tool;
363
+ return {
364
+ ...tool,
365
+ parameters: { ...(isPlainObject(tool.parameters) ? tool.parameters : {}), type: "object" },
366
+ };
367
+ }
368
+
369
+ function normalizeToolSchemas(body: unknown): unknown {
370
+ if (!isPlainObject(body)) return body;
371
+
372
+ const normalizeTools = (tools: unknown[]): unknown[] => {
373
+ let changed = false;
374
+ const normalized = tools.map((tool) => {
375
+ const fixed = normalizeFunctionToolSchema(tool);
376
+ if (fixed !== tool) changed = true;
377
+ return fixed;
378
+ });
379
+ return changed ? normalized : tools;
380
+ };
381
+
382
+ let normalizedBody = body;
383
+ if (Array.isArray(body.tools)) {
384
+ const tools = normalizeTools(body.tools);
385
+ if (tools !== body.tools) normalizedBody = { ...normalizedBody, tools };
386
+ }
387
+ if (Array.isArray(normalizedBody.input)) {
388
+ let inputChanged = false;
389
+ const input = normalizedBody.input.map((item) => {
390
+ if (!isPlainObject(item) || item.type !== "additional_tools" || !Array.isArray(item.tools)) return item;
391
+ const tools = normalizeTools(item.tools);
392
+ if (tools === item.tools) return item;
393
+ inputChanged = true;
394
+ return { ...item, tools };
395
+ });
396
+ if (inputChanged) normalizedBody = { ...normalizedBody, input };
397
+ }
398
+ return normalizedBody;
399
+ }
400
+
401
+ const MAX_RESPONSES_CALL_ID_LENGTH = 64;
402
+ const REPAIRED_CALL_ID_PREFIX = "call_ocx_";
403
+ const REPAIRED_CALL_ID_DIGEST_LENGTH = MAX_RESPONSES_CALL_ID_LENGTH - REPAIRED_CALL_ID_PREFIX.length;
404
+
405
+ /**
406
+ * Responses backends that enforce OpenAI's contract reject input `call_id` values longer than 64
407
+ * characters. Any routed provider can mint such an id, and Codex can later replay it through this
408
+ * adapter after a model switch.
409
+ *
410
+ * Without `previous_response_id`, the input is self-contained, so every occurrence of an oversized
411
+ * id can use one deterministic request-local alias. A stateful API-key continuation may instead
412
+ * contain only an output for a call already stored upstream under the original id; preserve those
413
+ * output-only references. Calls declared in the current input are safe to alias together with every
414
+ * matching output, even when the request also retains upstream state. Source ids have no separate
415
+ * length ceiling here: hashing always emits a fixed 64-character alias, while ordinary request-body
416
+ * admission remains the outer bound.
417
+ */
418
+ function repairOversizedCallIds(body: unknown): unknown {
419
+ if (!isPlainObject(body) || !Array.isArray(body.input)) return body;
420
+
421
+ const retainsUpstreamState = typeof body.previous_response_id === "string"
422
+ && body.previous_response_id.length > 0;
423
+ const occupied = new Set<string>();
424
+ const locallyDeclaredCallIds = new Set<string>();
425
+ for (const item of body.input) {
426
+ if (!isPlainObject(item) || typeof item.call_id !== "string") continue;
427
+ if (item.call_id.length <= MAX_RESPONSES_CALL_ID_LENGTH) occupied.add(item.call_id);
428
+ if (
429
+ retainsUpstreamState
430
+ && typeof item.type === "string"
431
+ && item.type.endsWith("_call")
432
+ ) {
433
+ locallyDeclaredCallIds.add(item.call_id);
434
+ }
435
+ }
436
+
437
+ const aliases = new Map<string, string>();
438
+ let changed = false;
439
+ const input = body.input.map(item => {
440
+ if (!isPlainObject(item) || typeof item.call_id !== "string") return item;
441
+ const original = item.call_id;
442
+ if (original.length <= MAX_RESPONSES_CALL_ID_LENGTH) return item;
443
+ if (retainsUpstreamState && !locallyDeclaredCallIds.has(original)) return item;
444
+
445
+ let alias = aliases.get(original);
446
+ if (!alias) {
447
+ let salt = 0;
448
+ do {
449
+ const hashInput = salt === 0 ? original : `${original}\0${salt}`;
450
+ const digest = createHash("sha256").update(hashInput).digest("hex");
451
+ alias = `${REPAIRED_CALL_ID_PREFIX}${digest.slice(0, REPAIRED_CALL_ID_DIGEST_LENGTH)}`;
452
+ salt += 1;
453
+ } while (occupied.has(alias));
454
+ aliases.set(original, alias);
455
+ occupied.add(alias);
456
+ }
457
+
458
+ changed = true;
459
+ return { ...item, call_id: alias };
460
+ });
461
+
462
+ return changed ? { ...body, input } : body;
463
+ }
464
+
465
+ /** Flatten a Responses tool-output `output` value (string or content-part array) to plain text. */
466
+ function toolOutputText(output: unknown): string {
467
+ if (typeof output === "string") return output;
468
+ if (!Array.isArray(output)) return JSON.stringify(output ?? "");
469
+ return output.map(part => {
470
+ if (!isPlainObject(part)) return "";
471
+ if (typeof part.text === "string") return part.text;
472
+ if (part.type === "refusal" && typeof part.refusal === "string") return `[refusal] ${part.refusal}`;
473
+ return "";
474
+ }).filter(Boolean).join("\n");
475
+ }
476
+
477
+ /**
478
+ * Repair a forward-mode input array whose continuation context was lost. When the replay
479
+ * expansion misses (proxy restart, unrecorded prior turn), previous_response_id is stripped
480
+ * (the ChatGPT backend rejects it), so the delta may carry items that reference now-absent
481
+ * prior items and 400 upstream:
482
+ * - `function_call_output`/`custom_tool_call_output` without their paired call item
483
+ * ("No tool call found for function call output with call_id ..."). Converted to user
484
+ * messages so the result text survives. `function_call_output` also pairs with
485
+ * `local_shell_call` (codex-rs emits shell outputs as function_call_output).
486
+ * - `reasoning` items ("Item 'rs_*' ... was provided without its required following item").
487
+ * Dropped, but only when `dropReasoning` (unexpanded miss): on a replay hit the prior
488
+ * reasoning chain is intact and must be preserved.
489
+ * Runs on every forward request; with intact pairs it returns the original reference.
490
+ */
491
+ /**
492
+ * Backfill `queries` on a replayed single-query `web_search_call`.
493
+ *
494
+ * `webSearchAction()` in the bridge now emits both keys, but that only helps items
495
+ * created after the fix. A conversation that already recorded
496
+ * `{type:"search", query:"..."}` replays that stored item on every subsequent turn, and
497
+ * DeepSeek's native Responses parser requires `queries` — so upgrading alone leaves
498
+ * those threads permanently 400ing with `missing field 'queries'` (#930).
499
+ *
500
+ * Runs on every Responses request, on both `input` items and the `action` nested inside
501
+ * them. Returns the original reference when nothing needs repair, so the common path
502
+ * allocates nothing.
503
+ */
504
+ function backfillWebSearchQueries(body: unknown): unknown {
505
+ if (!isPlainObject(body) || !Array.isArray(body.input)) return body;
506
+ let changed = false;
507
+ const input = body.input.map(item => {
508
+ if (!isPlainObject(item) || item.type !== "web_search_call") return item;
509
+ const action = item.action;
510
+ if (!isPlainObject(action) || action.type !== "search") return item;
511
+ if (typeof action.query !== "string" || Array.isArray(action.queries)) return item;
512
+ changed = true;
513
+ return { ...item, action: { ...action, queries: [action.query] } };
514
+ });
515
+ return changed ? { ...body, input } : body;
516
+ }
517
+
518
+ function repairOrphanedInputItems(body: unknown, dropReasoning: boolean): unknown {
519
+ if (!isPlainObject(body) || !Array.isArray(body.input)) return body;
520
+ const input = body.input;
521
+
522
+ const functionCallIds = new Set<string>();
523
+ const customCallIds = new Set<string>();
524
+ for (const item of input) {
525
+ if (!isPlainObject(item) || typeof item.call_id !== "string") continue;
526
+ if (item.type === "function_call" || item.type === "local_shell_call") functionCallIds.add(item.call_id);
527
+ else if (item.type === "custom_tool_call") customCallIds.add(item.call_id);
528
+ }
529
+
530
+ let changed = false;
531
+ const repaired: unknown[] = [];
532
+ for (const item of input) {
533
+ if (!isPlainObject(item)) { repaired.push(item); continue; }
534
+ if (dropReasoning && item.type === "reasoning") { changed = true; continue; }
535
+ const isFnOutput = item.type === "function_call_output";
536
+ const isCustomOutput = item.type === "custom_tool_call_output";
537
+ if (isFnOutput || isCustomOutput) {
538
+ const callId = typeof item.call_id === "string" ? item.call_id : "";
539
+ const paired = isFnOutput ? functionCallIds.has(callId) : customCallIds.has(callId);
540
+ if (!paired) {
541
+ changed = true;
542
+ repaired.push({
543
+ type: "message",
544
+ role: "user",
545
+ content: [{ type: "input_text", text: `[tool output for ${callId || "unknown call"}]\n${toolOutputText(item.output)}` }],
546
+ });
547
+ continue;
548
+ }
549
+ }
550
+ repaired.push(item);
551
+ }
552
+
553
+ return changed ? { ...body, input: repaired } : body;
554
+ }
555
+
556
+ /**
557
+ * Remove `previous_response_id` before forwarding. Two triggers:
558
+ * - the proxy expanded the request into a full input replay (the id is now redundant), or
559
+ * - the target is the ChatGPT backend (`authMode: "forward"`), whose Codex REST endpoint
560
+ * categorically rejects the parameter with `{"detail":"Unsupported parameter:
561
+ * previous_response_id"}` (strict allowlist; it also rejects `metadata` and
562
+ * `max_output_tokens`). Codex only sends the id on WS turns, and Remodex converts those to
563
+ * internal HTTP requests, so forwarding it upstream is a guaranteed 400 — stripping is
564
+ * strictly better even when the local replay state missed. API-key mode keeps the field on
565
+ * unexpanded requests: the platform `/v1/responses` supports real server-side storage.
566
+ */
567
+ function stripPreviousResponseId(body: unknown, strip: boolean): unknown {
568
+ if (!strip || !isPlainObject(body) || !Object.prototype.hasOwnProperty.call(body, "previous_response_id")) return body;
569
+ const { previous_response_id: _previousResponseId, ...rest } = body;
570
+ return rest;
571
+ }
572
+
573
+ /**
574
+ * Drop request parameters a stateless Responses upstream cannot implement, and pin
575
+ * `store` false.
576
+ *
577
+ * `previous_response_id` is listed here as well as in `stripPreviousResponseId`
578
+ * because that helper's strip is conditional on replay expansion, and it keeps the
579
+ * field for API-key providers on the premise that the platform offers real
580
+ * server-side storage. DeepSeek documents the opposite: "the API is stateless:
581
+ * responses and conversations are not stored on the server", so the field can never
582
+ * be honoured regardless of expansion state.
583
+ *
584
+ * `prompt` is a reference to a server-stored prompt template — the most stateful
585
+ * field in the accepted schema.
586
+ *
587
+ * `service_tier` is deliberately NOT dropped: the server writes it for fast mode
588
+ * (`responses/core.ts`), and silently deleting a configured knob inside an adapter is
589
+ * worse than forwarding a parameter the upstream ignores.
590
+ *
591
+ * MUST run before the composed sanitize chain below: `stripItemIdsWhenUnstored` keys
592
+ * off `store === false`, and a stateless upstream cannot resolve a stored item id.
593
+ * Returns a copy, so `parsed._rawBody` keeps the client's original `store` value and
594
+ * the local replay cache still records the turn.
595
+ */
596
+ function stripStatefulResponsesParams(body: unknown): unknown {
597
+ if (!isPlainObject(body)) return body;
598
+ const drop = ["previous_response_id", "conversation", "background", "metadata", "prompt"] as const;
599
+ const present = drop.some(key => Object.prototype.hasOwnProperty.call(body, key));
600
+ if (!present && body.store === false) return body;
601
+ const next: Record<string, unknown> = { ...body };
602
+ for (const key of drop) delete next[key];
603
+ next.store = false;
604
+ return next;
605
+ }
606
+
607
+ /**
608
+ * Remove top-level parameters the ChatGPT backend (`authMode: "forward"`) rejects
609
+ * with `{"detail":"Unsupported parameter: …"}` (strict allowlist). Codex CLI never
610
+ * sends these — it controls output length via `reasoning.effort` — but third-party
611
+ * Responses API clients (GJC, SDK wrappers) include `max_output_tokens` per the
612
+ * public spec. `metadata` is likewise absent from the allowlist. No-op when the
613
+ * body carries neither field, keeping the common Codex path allocation-free.
614
+ */
615
+ function stripUnsupportedForwardParams(body: unknown): unknown {
616
+ if (!isPlainObject(body)) return body;
617
+ const hasMot = Object.prototype.hasOwnProperty.call(body, "max_output_tokens");
618
+ const hasMeta = Object.prototype.hasOwnProperty.call(body, "metadata");
619
+ if (!hasMot && !hasMeta) return body;
620
+ const { max_output_tokens: _mot, metadata: _meta, ...rest } = body;
621
+ return rest;
622
+ }
623
+
624
+ const IMAGE_GEN_NAMESPACE = "image_gen";
625
+ const HOSTED_IMAGE_GENERATION_TOOL = "image_generation";
626
+ const IMAGE_GEN_DOTTED_PREFIX = `${IMAGE_GEN_NAMESPACE}.`;
627
+ const IMAGE_GEN_WIRE_PREFIX = `${IMAGE_GEN_NAMESPACE}__`;
628
+
629
+ /** Remove a supported client prefix before constructing the canonical image-gen wire alias. */
630
+ function imageGenLocalName(name: string): string {
631
+ if (name.startsWith(IMAGE_GEN_DOTTED_PREFIX)) return name.slice(IMAGE_GEN_DOTTED_PREFIX.length);
632
+ if (name.startsWith(IMAGE_GEN_WIRE_PREFIX)) return name.slice(IMAGE_GEN_WIRE_PREFIX.length);
633
+ return name;
634
+ }
635
+
636
+ /** Build the flat public-Responses name used only on the upstream wire. */
637
+ function imageGenWireName(name: string): string {
638
+ return namespacedToolName(IMAGE_GEN_NAMESPACE, imageGenLocalName(name));
639
+ }
640
+
641
+ /** Match client image-gen declarations across namespace, legacy dotted, and canonical wire forms. */
642
+ function isImageGenClientName(name: string): boolean {
643
+ return name === IMAGE_GEN_NAMESPACE
644
+ || name.startsWith(IMAGE_GEN_DOTTED_PREFIX)
645
+ || name.startsWith(IMAGE_GEN_WIRE_PREFIX);
646
+ }
647
+
648
+ /** Identify declarations that should activate image-gen request normalization. */
649
+ function declaresImageGenClientTool(tool: unknown): boolean {
650
+ if (!isPlainObject(tool) || typeof tool.name !== "string") return false;
651
+ if (tool.type === "namespace") return tool.name === IMAGE_GEN_NAMESPACE;
652
+ return isImageGenClientName(tool.name);
653
+ }
654
+
655
+ /** Rewrite client image-gen selectors to the hosted tool without widening caller restrictions. */
656
+ function preferHostedImageGenToolChoice(toolChoice: unknown): unknown {
657
+ if (!isPlainObject(toolChoice)) return toolChoice;
658
+ if ((toolChoice.type === "function" || toolChoice.type === "custom") && typeof toolChoice.name === "string") {
659
+ return isImageGenClientName(toolChoice.name) ? { type: HOSTED_IMAGE_GENERATION_TOOL } : toolChoice;
660
+ }
661
+ if (toolChoice.type !== "allowed_tools" || !Array.isArray(toolChoice.tools)) return toolChoice;
662
+ const hasHostedImageTool = toolChoice.tools.some(tool => isPlainObject(tool) && tool.type === HOSTED_IMAGE_GENERATION_TOOL);
663
+ let changed = false;
664
+ let addedHostedImageTool = false;
665
+ const tools: unknown[] = [];
666
+ for (const tool of toolChoice.tools) {
667
+ const isClientImageTool = isPlainObject(tool)
668
+ && (tool.type === "function" || tool.type === "custom")
669
+ && typeof tool.name === "string"
670
+ && isImageGenClientName(tool.name);
671
+ if (!isClientImageTool) {
672
+ tools.push(tool);
673
+ continue;
674
+ }
675
+ changed = true;
676
+ if (!hasHostedImageTool && !addedHostedImageTool) {
677
+ tools.push({ type: HOSTED_IMAGE_GENERATION_TOOL });
678
+ addedHostedImageTool = true;
679
+ }
680
+ }
681
+ return changed ? { ...toolChoice, tools } : toolChoice;
682
+ }
683
+
684
+ /**
685
+ * Some Responses-compatible gateways reserve the hosted image namespace even when the request
686
+ * does not explicitly declare `image_generation`. For an explicitly configured model, remove only
687
+ * colliding client declarations so the gateway's hosted tool can take precedence.
688
+ */
689
+ function preferConfiguredHostedTools(
690
+ body: unknown,
691
+ provider: OcxProviderConfig,
692
+ modelId: string,
693
+ selectedModelId?: string,
694
+ ): unknown {
695
+ // A virtual model's advertised id takes precedence over its resolved wire-model id.
696
+ // Read own properties only: a routed model id of `constructor`/`toString` would
697
+ // otherwise resolve to an inherited Object.prototype function and throw on the
698
+ // membership test below, failing the request before it is dispatched.
699
+ const preferenceMap = provider.modelPreferHostedTools;
700
+ const ownPreference = (key: string | undefined): string[] | undefined => {
701
+ if (!key || !preferenceMap || !Object.prototype.hasOwnProperty.call(preferenceMap, key)) return undefined;
702
+ const entry = preferenceMap[key];
703
+ return Array.isArray(entry) ? entry : undefined;
704
+ };
705
+ const preferredTools = ownPreference(selectedModelId) ?? ownPreference(modelId);
706
+ if (!preferredTools?.includes(HOSTED_IMAGE_GENERATION_TOOL) || !isPlainObject(body)) return body;
707
+
708
+ const stripGroup = (tools: unknown[]): unknown[] => {
709
+ const filtered = tools.filter(tool => !declaresImageGenClientTool(tool));
710
+ return filtered.length === tools.length ? tools : filtered;
711
+ };
712
+
713
+ let changed = false;
714
+ let tools = body.tools;
715
+ let strippedTopLevelImageGenTool = false;
716
+ if (Array.isArray(body.tools)) {
717
+ tools = stripGroup(body.tools);
718
+ strippedTopLevelImageGenTool = tools !== body.tools;
719
+ changed ||= strippedTopLevelImageGenTool;
720
+ }
721
+
722
+ let input = body.input;
723
+ const strippedAdditionalToolsIndices = new Set<number>();
724
+ if (Array.isArray(body.input)) {
725
+ let nestedChanged = false;
726
+ const mappedInput = body.input.map((item, index) => {
727
+ if (!isPlainObject(item) || item.type !== "additional_tools" || !Array.isArray(item.tools)) return item;
728
+ const nestedTools = stripGroup(item.tools);
729
+ if (nestedTools === item.tools) return item;
730
+ strippedAdditionalToolsIndices.add(index);
731
+ nestedChanged = true;
732
+ return { ...item, tools: nestedTools };
733
+ });
734
+ if (nestedChanged) {
735
+ input = mappedInput;
736
+ changed = true;
737
+ }
738
+ }
739
+
740
+ const hasToolChoice = Object.hasOwn(body, "tool_choice");
741
+ const toolChoice = hasToolChoice ? preferHostedImageGenToolChoice(body.tool_choice) : body.tool_choice;
742
+ const toolChoiceChanged = hasToolChoice && toolChoice !== body.tool_choice;
743
+ const hasHostedImageGenTool = (toolGroup: unknown): boolean => Array.isArray(toolGroup)
744
+ && toolGroup.some(tool => isPlainObject(tool) && tool.type === HOSTED_IMAGE_GENERATION_TOOL);
745
+ const hasHostedImageGenDeclaration = hasHostedImageGenTool(tools)
746
+ || (Array.isArray(input) && input.some(item => isPlainObject(item)
747
+ && item.type === "additional_tools"
748
+ && hasHostedImageGenTool(item.tools)));
749
+ if ((strippedTopLevelImageGenTool || strippedAdditionalToolsIndices.size > 0) && !hasHostedImageGenDeclaration) {
750
+ if (strippedTopLevelImageGenTool && Array.isArray(tools)) {
751
+ tools = [...tools, { type: HOSTED_IMAGE_GENERATION_TOOL }];
752
+ } else if (strippedAdditionalToolsIndices.size > 0 && Array.isArray(input)) {
753
+ // Restore into the FIRST stripped container only. Tool declarations are
754
+ // request-scoped, not container-scoped — the containers are separate carriers for
755
+ // one tool set, so a single hosted declaration covers the request. An earlier
756
+ // revision restored into every stripped container and put `image_generation` on
757
+ // the wire twice; review caught it.
758
+ const firstStripped = Math.min(...strippedAdditionalToolsIndices);
759
+ input = input.map((item, index) => index === firstStripped
760
+ && isPlainObject(item)
761
+ && Array.isArray(item.tools)
762
+ ? { ...item, tools: [...item.tools, { type: HOSTED_IMAGE_GENERATION_TOOL }] }
763
+ : item);
764
+ }
765
+ }
766
+ changed ||= toolChoiceChanged;
767
+ if (!changed) return body;
768
+ const next: Record<string, unknown> = {
769
+ ...body,
770
+ ...(Array.isArray(body.tools) ? { tools } : {}),
771
+ ...(Array.isArray(body.input) ? { input } : {}),
772
+ };
773
+ if (toolChoiceChanged) next.tool_choice = toolChoice;
774
+ return next;
775
+ }
776
+
777
+ /**
778
+ * Lower one complete Codex image-gen namespace to public Responses function tools.
779
+ *
780
+ * The public API reserves the `image_gen` namespace and restricts function names to a flat safe
781
+ * alphabet. `image_gen__<tool>` is therefore an upstream-only alias; client-facing responses are
782
+ * restored to explicit `{ namespace: "image_gen", name: "<tool>" }` calls by the server. Only a
783
+ * non-empty namespace containing named function tools is safe to lower. Malformed, empty, and
784
+ * future namespace shapes stay untouched instead of silently losing client capabilities.
785
+ */
786
+ function flattenImageGenNamespace(tool: unknown): Record<string, unknown>[] | undefined {
787
+ if (
788
+ !isPlainObject(tool)
789
+ || tool.type !== "namespace"
790
+ || tool.name !== IMAGE_GEN_NAMESPACE
791
+ || !Array.isArray(tool.tools)
792
+ || tool.tools.length === 0
793
+ ) return undefined;
794
+
795
+ for (const innerTool of tool.tools) {
796
+ if (
797
+ !isPlainObject(innerTool)
798
+ || innerTool.type !== "function"
799
+ || typeof innerTool.name !== "string"
800
+ || innerTool.name.length === 0
801
+ ) return undefined;
802
+ }
803
+
804
+ return tool.tools.map(innerTool => {
805
+ const functionTool = innerTool as Record<string, unknown> & { name: string };
806
+ return {
807
+ ...functionTool,
808
+ name: imageGenWireName(functionTool.name),
809
+ };
810
+ });
811
+ }
812
+
813
+ /** Convert a legacy dotted function declaration while preserving all other function metadata. */
814
+ function normalizeFlatImageGenFunction(tool: unknown): unknown {
815
+ if (
816
+ !isPlainObject(tool)
817
+ || tool.type !== "function"
818
+ || typeof tool.name !== "string"
819
+ || !tool.name.startsWith(IMAGE_GEN_DOTTED_PREFIX)
820
+ ) return tool;
821
+ return { ...tool, name: imageGenWireName(tool.name) };
822
+ }
823
+
824
+ /** Return the image-gen function name used for stable cross-container deduplication. */
825
+ function imageGenFunctionName(tool: unknown): string | undefined {
826
+ if (!isPlainObject(tool) || tool.type !== "function" || typeof tool.name !== "string") {
827
+ return undefined;
828
+ }
829
+ return isImageGenClientName(tool.name) ? tool.name : undefined;
830
+ }
831
+
832
+ /** True only when a declaration can yield a callable upstream-safe image-gen function alias. */
833
+ function declaresUsableImageGenAlias(tool: unknown): boolean {
834
+ if (flattenImageGenNamespace(tool)) return true;
835
+ if (!isPlainObject(tool) || tool.type !== "function" || typeof tool.name !== "string") {
836
+ return false;
837
+ }
838
+ if (tool.name.startsWith(IMAGE_GEN_DOTTED_PREFIX)) {
839
+ return tool.name.length > IMAGE_GEN_DOTTED_PREFIX.length;
840
+ }
841
+ return tool.name.startsWith(IMAGE_GEN_WIRE_PREFIX)
842
+ && tool.name.length > IMAGE_GEN_WIRE_PREFIX.length;
843
+ }
844
+
845
+ /** Collect client tool-choice names and the exact upstream aliases declared for them. */
846
+ function imageGenToolChoiceAliases(toolGroups: unknown[][]): Map<string, string> {
847
+ const aliases = new Map<string, string>();
848
+
849
+ for (const group of toolGroups) {
850
+ for (const tool of group) {
851
+ const flattened = flattenImageGenNamespace(tool);
852
+ if (flattened) {
853
+ for (const candidate of flattened) {
854
+ const wireName = candidate.name as string;
855
+ aliases.set(`${IMAGE_GEN_DOTTED_PREFIX}${imageGenLocalName(wireName)}`, wireName);
856
+ aliases.set(wireName, wireName);
857
+ }
858
+ continue;
859
+ }
860
+ if (!isPlainObject(tool) || tool.type !== "function" || typeof tool.name !== "string") {
861
+ continue;
862
+ }
863
+ if (
864
+ tool.name.startsWith(IMAGE_GEN_DOTTED_PREFIX)
865
+ && tool.name.length > IMAGE_GEN_DOTTED_PREFIX.length
866
+ ) {
867
+ aliases.set(tool.name, imageGenWireName(tool.name));
868
+ } else if (
869
+ tool.name.startsWith(IMAGE_GEN_WIRE_PREFIX)
870
+ && tool.name.length > IMAGE_GEN_WIRE_PREFIX.length
871
+ ) {
872
+ aliases.set(tool.name, tool.name);
873
+ }
874
+ }
875
+ }
876
+
877
+ return aliases;
878
+ }
879
+
880
+ /** Rewrite function selectors only when their corresponding declaration receives a wire alias. */
881
+ function normalizeImageGenToolChoice(
882
+ toolChoice: unknown,
883
+ aliases: ReadonlyMap<string, string>,
884
+ ): unknown {
885
+ if (!isPlainObject(toolChoice)) return toolChoice;
886
+
887
+ if (toolChoice.type === "function" && typeof toolChoice.name === "string") {
888
+ const alias = aliases.get(toolChoice.name);
889
+ return alias && alias !== toolChoice.name ? { ...toolChoice, name: alias } : toolChoice;
890
+ }
891
+
892
+ if (toolChoice.type !== "allowed_tools" || !Array.isArray(toolChoice.tools)) return toolChoice;
893
+ let changed = false;
894
+ const tools = toolChoice.tools.map(tool => {
895
+ if (!isPlainObject(tool) || tool.type !== "function" || typeof tool.name !== "string") {
896
+ return tool;
897
+ }
898
+ const alias = aliases.get(tool.name);
899
+ if (!alias || alias === tool.name) return tool;
900
+ changed = true;
901
+ return { ...tool, name: alias };
902
+ });
903
+ return changed ? { ...toolChoice, tools } : toolChoice;
904
+ }
905
+
906
+ /** Identify replayed image-gen calls that require upstream wire encoding. */
907
+ function declaresImageGenFunctionCall(item: unknown): boolean {
908
+ if (!isPlainObject(item) || item.type !== "function_call" || typeof item.name !== "string") {
909
+ return false;
910
+ }
911
+ return item.namespace === IMAGE_GEN_NAMESPACE || isImageGenClientName(item.name);
912
+ }
913
+
914
+ /** Encode native or legacy replay calls to the same flat name used by tool declarations. */
915
+ function normalizeImageGenFunctionCall(item: unknown): unknown {
916
+ if (!declaresImageGenFunctionCall(item) || !isPlainObject(item) || typeof item.name !== "string") {
917
+ return item;
918
+ }
919
+ if (item.namespace === IMAGE_GEN_NAMESPACE) {
920
+ const { namespace: _namespace, ...rest } = item;
921
+ return { ...rest, name: imageGenWireName(item.name) };
922
+ }
923
+ if (item.name.startsWith(IMAGE_GEN_DOTTED_PREFIX)) {
924
+ return { ...item, name: imageGenWireName(item.name) };
925
+ }
926
+ return item;
927
+ }
928
+
929
+ /**
930
+ * Normalize Codex's private image-gen tool declaration for API-key Responses providers.
931
+ *
932
+ * A complete `image_gen` namespace is flattened to safe `image_gen__<tool>` aliases even when it is
933
+ * the only image tool in the request. Replayed client calls are encoded to the same alias, including
934
+ * legacy dotted calls from older compatibility attempts. When a usable alias replaces a client
935
+ * image-gen declaration, the duplicate hosted `image_generation` entry is removed. Duplicate aliases
936
+ * are resolved in stable container order: top-level tools first, then Responses Lite
937
+ * `additional_tools` entries.
938
+ *
939
+ * This function is called only on the API-key path. ChatGPT forward mode understands the private
940
+ * namespace and must keep it. Copy-on-write preserves the original request reference when no
941
+ * namespace is flattened, hosted tool removed, or duplicate function discarded.
942
+ */
943
+ function normalizeImageGenClientTools(body: unknown): unknown {
944
+ if (!isPlainObject(body)) return body;
945
+
946
+ const toolGroups = collectResponsesToolGroups(body);
947
+ const hasImageGenClientTool = toolGroups.some(group => group.some(declaresImageGenClientTool))
948
+ || (Array.isArray(body.input) && body.input.some(declaresImageGenFunctionCall));
949
+ if (!hasImageGenClientTool) return body;
950
+ const hasUsableImageGenAlias = toolGroups.some(group => group.some(declaresUsableImageGenAlias));
951
+ const toolChoiceAliases = imageGenToolChoiceAliases(toolGroups);
952
+
953
+ const seenFunctionNames = new Set<string>();
954
+ const normalizeGroup = (tools: unknown[]): unknown[] => {
955
+ const normalized: unknown[] = [];
956
+ let groupChanged = false;
957
+
958
+ for (const tool of tools) {
959
+ if (
960
+ hasUsableImageGenAlias
961
+ && isPlainObject(tool)
962
+ && tool.type === HOSTED_IMAGE_GENERATION_TOOL
963
+ ) {
964
+ groupChanged = true;
965
+ continue;
966
+ }
967
+
968
+ const flattened = flattenImageGenNamespace(tool);
969
+ const candidates = flattened ?? [tool];
970
+ if (flattened) groupChanged = true;
971
+
972
+ for (const candidate of candidates) {
973
+ const normalizedCandidate = normalizeFlatImageGenFunction(candidate);
974
+ if (normalizedCandidate !== candidate) groupChanged = true;
975
+ const functionName = imageGenFunctionName(normalizedCandidate);
976
+ if (functionName && seenFunctionNames.has(functionName)) {
977
+ groupChanged = true;
978
+ continue;
979
+ }
980
+ if (functionName) seenFunctionNames.add(functionName);
981
+ normalized.push(normalizedCandidate);
982
+ }
983
+ }
984
+
985
+ return groupChanged ? normalized : tools;
986
+ };
987
+
988
+ let changed = false;
989
+ let tools = body.tools;
990
+ if (Array.isArray(body.tools)) {
991
+ tools = normalizeGroup(body.tools);
992
+ changed ||= tools !== body.tools;
993
+ }
994
+
995
+ let input = body.input;
996
+ if (Array.isArray(body.input)) {
997
+ let nestedChanged = false;
998
+ const mappedInput = body.input.map(item => {
999
+ if (isPlainObject(item) && item.type === "additional_tools" && Array.isArray(item.tools)) {
1000
+ const nestedTools = normalizeGroup(item.tools);
1001
+ if (nestedTools === item.tools) return item;
1002
+ nestedChanged = true;
1003
+ return { ...item, tools: nestedTools };
1004
+ }
1005
+ const normalizedCall = normalizeImageGenFunctionCall(item);
1006
+ if (normalizedCall !== item) nestedChanged = true;
1007
+ return normalizedCall;
1008
+ });
1009
+ if (nestedChanged) {
1010
+ input = mappedInput;
1011
+ changed = true;
1012
+ }
1013
+ }
1014
+
1015
+ const toolChoice = normalizeImageGenToolChoice(body.tool_choice, toolChoiceAliases);
1016
+ changed ||= toolChoice !== body.tool_choice;
1017
+
1018
+ if (!changed) return body;
1019
+ return {
1020
+ ...body,
1021
+ ...(Array.isArray(body.tools) ? { tools } : {}),
1022
+ ...(Array.isArray(body.input) ? { input } : {}),
1023
+ ...(Object.prototype.hasOwnProperty.call(body, "tool_choice") ? { tool_choice: toolChoice } : {}),
1024
+ };
1025
+ }
1026
+
1027
+ /**
1028
+ * Remove hosted tool entries the target native slug rejects, so the OAuth-passthrough body never
1029
+ * carries a tool the upstream model 400s on. No-op (returns the original reference) when nothing
1030
+ * matches, keeping the common path allocation-free.
1031
+ */
1032
+ function stripUnsupportedHostedTools(body: unknown): unknown {
1033
+ if (!isPlainObject(body) || !Array.isArray(body.tools)) return body;
1034
+ const model = typeof body.model === "string" ? body.model : "";
1035
+ const tools = body.tools.filter(t => {
1036
+ const type = isPlainObject(t) && typeof t.type === "string" ? t.type : undefined;
1037
+ return !type || !isHostedToolUnsupportedForModel(model, type);
1038
+ });
1039
+ return tools.length === body.tools.length ? body : { ...body, tools };
1040
+ }
1041
+
1042
+ /** Replace every `input_image` part under a routed-compaction body with a short marker. */
1043
+ function stripInputImagesDeep(value: unknown): unknown {
1044
+ if (Array.isArray(value)) return value.map(stripInputImagesDeep);
1045
+ if (!isPlainObject(value)) return value;
1046
+ if (value.type === "input_image") {
1047
+ return { type: "input_text", text: "[image omitted for compaction]" };
1048
+ }
1049
+ const out: Record<string, unknown> = {};
1050
+ for (const [key, entry] of Object.entries(value)) out[key] = stripInputImagesDeep(entry);
1051
+ return out;
1052
+ }
1053
+
1054
+ /**
1055
+ * Rewrite a compaction turn for an upstream that does not speak Codex's private
1056
+ * `compaction_trigger` item: drop the trigger and the whole tool surface, and ask
1057
+ * for the handoff summary in plain terms instead (#422).
1058
+ *
1059
+ * The adapter builds from `parsed._rawBody`, so the summarizer prompt that
1060
+ * handleResponses() pushed onto `parsed.context` never reaches the wire — it has to
1061
+ * be applied here. Images go too: a summary needs no pixels, and a text-only
1062
+ * gateway would reject them.
1063
+ */
1064
+ function buildRoutedCompactionBody(body: unknown): unknown {
1065
+ if (!isPlainObject(body)) return body;
1066
+ // `text` goes with the tool fields: the summary must be prose, not schema-constrained JSON.
1067
+ const { tools: _tools, tool_choice: _toolChoice, parallel_tool_calls: _parallel, text: _text, ...rest } = body;
1068
+ const input = Array.isArray(body.input) ? body.input : [];
1069
+ const kept = input.filter(item => !isPlainObject(item)
1070
+ // `additional_tools` is how Codex Desktop's responses-lite shape carries tools;
1071
+ // leaving it in would break the no-tools invariant even with `tools` removed.
1072
+ || (item.type !== "compaction_trigger" && item.type !== "additional_tools"));
1073
+ return {
1074
+ ...rest,
1075
+ input: [
1076
+ ...(stripInputImagesDeep(kept) as unknown[]),
1077
+ { type: "message", role: "user", content: [{ type: "input_text", text: COMPACT_PROMPT }] },
1078
+ ],
1079
+ };
1080
+ }
1081
+
1082
+ /** Read the Responses `usage` block, if the gateway sent one. */
1083
+ function usageFromResponsesPayload(payload: unknown): OcxUsage | undefined {
1084
+ if (!isPlainObject(payload) || !isPlainObject(payload.usage)) return undefined;
1085
+ const usage = payload.usage;
1086
+ const inputTokens = typeof usage.input_tokens === "number" ? usage.input_tokens : 0;
1087
+ const outputTokens = typeof usage.output_tokens === "number" ? usage.output_tokens : 0;
1088
+ if (inputTokens === 0 && outputTokens === 0) return undefined;
1089
+ return {
1090
+ inputTokens,
1091
+ outputTokens,
1092
+ ...(typeof usage.total_tokens === "number" ? { totalTokens: usage.total_tokens } : {}),
1093
+ };
1094
+ }
1095
+
1096
+ function responsesPayloadText(response: unknown): string {
1097
+ if (!isPlainObject(response) || !Array.isArray(response.output)) return "";
1098
+ return response.output
1099
+ .filter(item => isPlainObject(item) && item.type === "message")
1100
+ .flatMap(item => (Array.isArray((item as Record<string, unknown>).content)
1101
+ ? (item as { content: unknown[] }).content
1102
+ : []))
1103
+ .filter(part => isPlainObject(part) && part.type === "output_text")
1104
+ .map(part => String((part as { text?: unknown }).text ?? ""))
1105
+ .join("");
1106
+ }
1107
+
1108
+ function responsesErrorMessage(payload: unknown): string {
1109
+ if (!isPlainObject(payload)) return "upstream compaction failed";
1110
+ const err = payload.error;
1111
+ if (typeof err === "string") return err;
1112
+ if (isPlainObject(err) && typeof err.message === "string") return err.message;
1113
+ const incomplete = payload.incomplete_details;
1114
+ if (isPlainObject(incomplete) && typeof incomplete.reason === "string") return incomplete.reason;
1115
+ return "upstream compaction failed";
1116
+ }
1117
+
1118
+ export function createResponsesPassthroughAdapter(provider: OcxProviderConfig): ProviderAdapter & { passthrough: true } {
1119
+ return {
1120
+ name: "openai-responses",
1121
+ passthrough: true as const,
1122
+
1123
+ buildRequest(parsed: OcxParsedRequest, incoming: IncomingMeta) {
1124
+ const translatorBudget = incoming.translatorBudget;
1125
+ const headers: Record<string, string> = { "Content-Type": "application/json" };
1126
+ let url: string;
1127
+
1128
+ if (provider.authMode === "forward") {
1129
+ // OAuth passthrough: ChatGPT backend path is `${baseUrl}/responses` (no /v1).
1130
+ url = `${provider.baseUrl}/responses`;
1131
+ if (provider.headers) Object.assign(headers, provider.headers); // static headers first…
1132
+ const runtimeProvider = provider as {
1133
+ _codexAccountOverride?: { accessToken: string; chatgptAccountId: string };
1134
+ _codexAccountRequired?: boolean;
1135
+ };
1136
+ if (runtimeProvider._codexAccountRequired && !runtimeProvider._codexAccountOverride) {
1137
+ throw new Error("Codex pool account auth is required but unavailable");
1138
+ }
1139
+ for (const h of FORWARD_HEADERS) {
1140
+ const v = incoming?.headers.get(h);
1141
+ if (v) headers[h] = v; // …so forwarded auth always wins.
1142
+ }
1143
+ const override = runtimeProvider._codexAccountOverride;
1144
+ if (override) {
1145
+ headers["authorization"] = `Bearer ${override.accessToken}`;
1146
+ headers["chatgpt-account-id"] = override.chatgptAccountId;
1147
+ }
1148
+ } else {
1149
+ if (provider.responsesPath === undefined) {
1150
+ const base = provider.baseUrl.replace(/\/v1\/?$/, "");
1151
+ url = `${base}/v1/responses`;
1152
+ } else {
1153
+ const base = provider.baseUrl.replace(/\/$/, "");
1154
+ url = `${base}${provider.responsesPath}`;
1155
+ }
1156
+ if (provider.apiKey) headers["Authorization"] = `Bearer ${provider.apiKey}`;
1157
+ if (provider.headers) Object.assign(headers, provider.headers);
1158
+ }
1159
+
1160
+ const forward = provider.authMode === "forward";
1161
+ const unexpandedMiss = !!parsed.previousResponseId && parsed._previousResponseInputExpanded !== true;
1162
+ let outBody = stripPreviousResponseId(
1163
+ parsed._rawBody,
1164
+ forward || parsed._previousResponseInputExpanded === true,
1165
+ );
1166
+ const stateless = provider.statelessResponses === true;
1167
+ if (stateless) outBody = stripStatefulResponsesParams(outBody);
1168
+ // A replay miss can leave a function_call_output whose paired function_call sat
1169
+ // in the prefix that was never expanded. A stateless upstream cannot resolve the
1170
+ // pair from its own storage either, so it needs the same repair the forward
1171
+ // backend gets — dropping previous_response_id is not much use if the body that
1172
+ // reaches the wire is unparseable.
1173
+ if (forward || stateless) {
1174
+ outBody = repairOrphanedInputItems(outBody, unexpandedMiss);
1175
+ }
1176
+ if (forward) {
1177
+ outBody = stripUnsupportedForwardParams(outBody);
1178
+ } else {
1179
+ outBody = preferConfiguredHostedTools(
1180
+ outBody,
1181
+ provider,
1182
+ parsed.modelId,
1183
+ parsed._openAiVirtualSelectedModelId,
1184
+ );
1185
+ outBody = normalizeImageGenClientTools(outBody);
1186
+ }
1187
+ outBody = repairOversizedCallIds(outBody);
1188
+ outBody = stripUnsupportedReasoningSummaryDelivery(outBody, parsed.modelId);
1189
+ // Repair stored history from before the bridge emitted both keys: a conversation
1190
+ // that already recorded a single-query web_search_call replays it every turn, and
1191
+ // a strict parser rejects the whole request over it (#930).
1192
+ outBody = backfillWebSearchQueries(outBody);
1193
+ // Same predicate as the routedCompaction gate in handleResponses(): an
1194
+ // authMode check would let a noncanonical custom forward provider skip this
1195
+ // rewrite while the server still routes it as a summarizer turn (#422).
1196
+ if (parsed._compactionRequest === true && !isCanonicalOpenAiForwardProvider(provider)) {
1197
+ outBody = buildRoutedCompactionBody(outBody);
1198
+ }
1199
+ const sanitizedBody = normalizeToolSchemas(stripSparkCompatibility(stripUnsupportedReasoningParams(stripItemIdsWhenUnstored(stripInvalidItemIds(stripUnsupportedHostedTools(sanitizeReasoningInputContent(scrubOcxCompactionItems(outBody), { preserveRawReasoningContent: provider.preserveResponsesReasoningContent === true })))))));
1200
+ const body = JSON.stringify(stripDisabledReasoningSummaries(
1201
+ normalizeConfiguredReasoningSummaryDelivery(sanitizedBody, provider, parsed.modelId),
1202
+ provider,
1203
+ parsed.modelId,
1204
+ ));
1205
+ const releaseBodyObservation = translatorBudget.observeExternallyCapped(
1206
+ "passthrough_serialization",
1207
+ new TextEncoder().encode(body).byteLength,
1208
+ );
1209
+ return {
1210
+ url,
1211
+ method: "POST",
1212
+ headers,
1213
+ body,
1214
+ releaseBodyObservation,
1215
+ };
1216
+ },
1217
+
1218
+ // The passthrough normally relays the upstream stream verbatim and never parses.
1219
+ // The exception is a routed compaction turn: the server drives this adapter like
1220
+ // an ordinary one so the bridge can build the single compaction item (#422).
1221
+ async *parseStream(response: Response, budget: TranslatorBudget): AsyncGenerator<AdapterEvent> {
1222
+ if (!response.body) {
1223
+ yield { type: "error", message: "passthrough adapter received no response body" };
1224
+ return;
1225
+ }
1226
+ const budgetEncoder = new TextEncoder();
1227
+ let deltas = "";
1228
+ let doneText = "";
1229
+ let snapshot = "";
1230
+ let usage: OcxUsage | undefined;
1231
+ for await (const event of decodeServerSentEvents(response.body, { translatorBudget: budget })) {
1232
+ let payload: unknown;
1233
+ try { payload = JSON.parse(event.data); } catch { continue; }
1234
+ if (!isPlainObject(payload)) continue;
1235
+ switch (payload.type) {
1236
+ case "response.output_text.delta":
1237
+ if (typeof payload.delta === "string") {
1238
+ const next = deltas + payload.delta;
1239
+ const previousBytes = budgetEncoder.encode(deltas).byteLength;
1240
+ const reservation = budget.reserveTransient(budgetEncoder.encode(next).byteLength, { kind: "retained_collectors" });
1241
+ deltas = next;
1242
+ reservation.commitRetained();
1243
+ budget.releaseRetained(previousBytes, { kind: "retained_collectors" });
1244
+ }
1245
+ break;
1246
+ case "response.output_text.done":
1247
+ if (typeof payload.text === "string") {
1248
+ const next = doneText + payload.text;
1249
+ const previousBytes = budgetEncoder.encode(doneText).byteLength;
1250
+ const reservation = budget.reserveTransient(budgetEncoder.encode(next).byteLength, { kind: "retained_collectors" });
1251
+ doneText = next;
1252
+ reservation.commitRetained();
1253
+ budget.releaseRetained(previousBytes, { kind: "retained_collectors" });
1254
+ }
1255
+ break;
1256
+ case "response.failed":
1257
+ case "error":
1258
+ yield { type: "error", message: responsesErrorMessage(payload.response ?? payload) };
1259
+ return;
1260
+ case "response.incomplete":
1261
+ yield { type: "incomplete", reason: responsesErrorMessage(payload.response ?? payload) };
1262
+ return;
1263
+ case "response.completed":
1264
+ {
1265
+ const next = responsesPayloadText(payload.response);
1266
+ const previousBytes = budgetEncoder.encode(snapshot).byteLength;
1267
+ const reservation = budget.reserveTransient(budgetEncoder.encode(next).byteLength, { kind: "retained_collectors" });
1268
+ snapshot = next;
1269
+ reservation.commitRetained();
1270
+ budget.releaseRetained(previousBytes, { kind: "retained_collectors" });
1271
+ }
1272
+ usage = usageFromResponsesPayload(payload.response);
1273
+ break;
1274
+ }
1275
+ }
1276
+ // Gateways differ in which of these they emit; prefer the authoritative
1277
+ // completed snapshot so text is never double-counted.
1278
+ const text = snapshot || doneText || deltas;
1279
+ if (text) yield { type: "text_delta", text };
1280
+ budget.releaseRetained(budgetEncoder.encode(deltas).byteLength + budgetEncoder.encode(doneText).byteLength + budgetEncoder.encode(snapshot).byteLength, { kind: "retained_collectors" });
1281
+ yield { type: "done", ...(usage ? { usage } : {}) };
1282
+ },
1283
+
1284
+ async parseResponse(response: Response, budget: TranslatorBudget): Promise<AdapterEvent[]> {
1285
+ let payload: unknown;
1286
+ try { payload = await response.json(); } catch {
1287
+ return [{ type: "error", message: "malformed upstream compaction response" }];
1288
+ }
1289
+ budget.chargeRetained(new TextEncoder().encode(JSON.stringify(payload)).byteLength, { kind: "retained_collectors" });
1290
+ if (!isPlainObject(payload)) {
1291
+ return [{ type: "error", message: "malformed upstream compaction response" }];
1292
+ }
1293
+ if (payload.error || payload.status === "failed") {
1294
+ return [{ type: "error", message: responsesErrorMessage(payload) }];
1295
+ }
1296
+ if (payload.status === "incomplete") {
1297
+ return [{ type: "incomplete", reason: responsesErrorMessage(payload) }];
1298
+ }
1299
+ const text = responsesPayloadText(payload);
1300
+ if (!text) {
1301
+ // A completed turn with no usable text cannot become a summary; saying so is
1302
+ // better than installing an empty compaction as replacement history.
1303
+ return [{ type: "error", message: "upstream compaction returned no summary text" }];
1304
+ }
1305
+ const usage = usageFromResponsesPayload(payload);
1306
+ return [{ type: "text_delta", text }, { type: "done", ...(usage ? { usage } : {}) }];
1307
+ },
1308
+ };
1309
+ }