@bitkyc08/opencodex 2.97.0 → 2.98.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 (290) hide show
  1. package/bin/ocx.mjs +1 -1
  2. package/gui/dist/assets/App-6TFtZsUF.css +1 -0
  3. package/gui/dist/assets/App-FQ0OtiMJ.js +59 -0
  4. package/gui/dist/assets/Tray-D2d5wqLq.js +1 -0
  5. package/gui/dist/assets/WantedSansVariable.split.0-Dwvb1WRx.woff2 +0 -0
  6. package/gui/dist/assets/WantedSansVariable.split.1-1wKD2RxI.woff2 +0 -0
  7. package/gui/dist/assets/WantedSansVariable.split.10-CAKA6LIP.woff2 +0 -0
  8. package/gui/dist/assets/WantedSansVariable.split.11-k5H85R4b.woff2 +0 -0
  9. package/gui/dist/assets/WantedSansVariable.split.12-BHboLsUv.woff2 +0 -0
  10. package/gui/dist/assets/WantedSansVariable.split.13-9GV377ix.woff2 +0 -0
  11. package/gui/dist/assets/WantedSansVariable.split.14-DovDXnrj.woff2 +0 -0
  12. package/gui/dist/assets/WantedSansVariable.split.15-DTdykCig.woff2 +0 -0
  13. package/gui/dist/assets/WantedSansVariable.split.16-CKz2ccgK.woff2 +0 -0
  14. package/gui/dist/assets/WantedSansVariable.split.17-Z2RD_KRZ.woff2 +0 -0
  15. package/gui/dist/assets/WantedSansVariable.split.18-BcKtfonJ.woff2 +0 -0
  16. package/gui/dist/assets/WantedSansVariable.split.19-DEQPOSZn.woff2 +0 -0
  17. package/gui/dist/assets/WantedSansVariable.split.2-DryboyuA.woff2 +0 -0
  18. package/gui/dist/assets/WantedSansVariable.split.20-Bia5JMls.woff2 +0 -0
  19. package/gui/dist/assets/WantedSansVariable.split.21-Cr4jFw-E.woff2 +0 -0
  20. package/gui/dist/assets/WantedSansVariable.split.22-DjjB69TZ.woff2 +0 -0
  21. package/gui/dist/assets/WantedSansVariable.split.23-CvUzJskt.woff2 +0 -0
  22. package/gui/dist/assets/WantedSansVariable.split.24-i_eMg5ox.woff2 +0 -0
  23. package/gui/dist/assets/WantedSansVariable.split.25-2aKHwPX-.woff2 +0 -0
  24. package/gui/dist/assets/WantedSansVariable.split.26-B6wXoCEL.woff2 +0 -0
  25. package/gui/dist/assets/WantedSansVariable.split.27-D4h1WfGM.woff2 +0 -0
  26. package/gui/dist/assets/WantedSansVariable.split.28-kvRPCStd.woff2 +0 -0
  27. package/gui/dist/assets/WantedSansVariable.split.29-DHAiwleD.woff2 +0 -0
  28. package/gui/dist/assets/WantedSansVariable.split.3-7H--eyZi.woff2 +0 -0
  29. package/gui/dist/assets/WantedSansVariable.split.30-C66cfAY2.woff2 +0 -0
  30. package/gui/dist/assets/WantedSansVariable.split.31-FDmtiNim.woff2 +0 -0
  31. package/gui/dist/assets/WantedSansVariable.split.32-DouHt2Dd.woff2 +0 -0
  32. package/gui/dist/assets/WantedSansVariable.split.33-B8HVvkJX.woff2 +0 -0
  33. package/gui/dist/assets/WantedSansVariable.split.34-BtkRu1FN.woff2 +0 -0
  34. package/gui/dist/assets/WantedSansVariable.split.35-DBylQbtk.woff2 +0 -0
  35. package/gui/dist/assets/WantedSansVariable.split.36-Sg089Kgh.woff2 +0 -0
  36. package/gui/dist/assets/WantedSansVariable.split.37-CYtvbriS.woff2 +0 -0
  37. package/gui/dist/assets/WantedSansVariable.split.38-DKkSLf8Z.woff2 +0 -0
  38. package/gui/dist/assets/WantedSansVariable.split.39-CecotKZD.woff2 +0 -0
  39. package/gui/dist/assets/WantedSansVariable.split.4-Bv8O3ZMb.woff2 +0 -0
  40. package/gui/dist/assets/WantedSansVariable.split.40-DdCvkmOU.woff2 +0 -0
  41. package/gui/dist/assets/WantedSansVariable.split.41-ESn674Hc.woff2 +0 -0
  42. package/gui/dist/assets/WantedSansVariable.split.42-DL9V7NNV.woff2 +0 -0
  43. package/gui/dist/assets/WantedSansVariable.split.43-yipO0cyk.woff2 +0 -0
  44. package/gui/dist/assets/WantedSansVariable.split.44-6rTmLZhm.woff2 +0 -0
  45. package/gui/dist/assets/WantedSansVariable.split.45-BJAj8lrm.woff2 +0 -0
  46. package/gui/dist/assets/WantedSansVariable.split.46-BDTzMn2c.woff2 +0 -0
  47. package/gui/dist/assets/WantedSansVariable.split.47-Bxd4wGgi.woff2 +0 -0
  48. package/gui/dist/assets/WantedSansVariable.split.48-DxnFBLnH.woff2 +0 -0
  49. package/gui/dist/assets/WantedSansVariable.split.49-DnVD0aOD.woff2 +0 -0
  50. package/gui/dist/assets/WantedSansVariable.split.5-B1wI2pp5.woff2 +0 -0
  51. package/gui/dist/assets/WantedSansVariable.split.50-D9JlkZd6.woff2 +0 -0
  52. package/gui/dist/assets/WantedSansVariable.split.51-D9Vw6Bu3.woff2 +0 -0
  53. package/gui/dist/assets/WantedSansVariable.split.52-ClEJk4kn.woff2 +0 -0
  54. package/gui/dist/assets/WantedSansVariable.split.53-BSXU0vh-.woff2 +0 -0
  55. package/gui/dist/assets/WantedSansVariable.split.54-EcuxkR9v.woff2 +0 -0
  56. package/gui/dist/assets/WantedSansVariable.split.55-CYiFhQX8.woff2 +0 -0
  57. package/gui/dist/assets/WantedSansVariable.split.56--Gk9g8BK.woff2 +0 -0
  58. package/gui/dist/assets/WantedSansVariable.split.57-DnkOPZcy.woff2 +0 -0
  59. package/gui/dist/assets/WantedSansVariable.split.58-9MB8504z.woff2 +0 -0
  60. package/gui/dist/assets/WantedSansVariable.split.59-ByxIsN72.woff2 +0 -0
  61. package/gui/dist/assets/WantedSansVariable.split.6-Bmk0dRVw.woff2 +0 -0
  62. package/gui/dist/assets/WantedSansVariable.split.60-Bxwx_aWQ.woff2 +0 -0
  63. package/gui/dist/assets/WantedSansVariable.split.61-DA2z5sm7.woff2 +0 -0
  64. package/gui/dist/assets/WantedSansVariable.split.62-C5iJPJZn.woff2 +0 -0
  65. package/gui/dist/assets/WantedSansVariable.split.63-DAqrmaEc.woff2 +0 -0
  66. package/gui/dist/assets/WantedSansVariable.split.64-BgXFsljb.woff2 +0 -0
  67. package/gui/dist/assets/WantedSansVariable.split.65-DKiWujvu.woff2 +0 -0
  68. package/gui/dist/assets/WantedSansVariable.split.66-8po4vUZ4.woff2 +0 -0
  69. package/gui/dist/assets/WantedSansVariable.split.67-Cy5qyI9O.woff2 +0 -0
  70. package/gui/dist/assets/WantedSansVariable.split.68-BKny7Fy3.woff2 +0 -0
  71. package/gui/dist/assets/WantedSansVariable.split.69-B4VU4u_b.woff2 +0 -0
  72. package/gui/dist/assets/WantedSansVariable.split.7-BuqwNpgA.woff2 +0 -0
  73. package/gui/dist/assets/WantedSansVariable.split.70-BCd4n346.woff2 +0 -0
  74. package/gui/dist/assets/WantedSansVariable.split.71-CkQppaWn.woff2 +0 -0
  75. package/gui/dist/assets/WantedSansVariable.split.72-Db7vaoFs.woff2 +0 -0
  76. package/gui/dist/assets/WantedSansVariable.split.73-DI80TYWl.woff2 +0 -0
  77. package/gui/dist/assets/WantedSansVariable.split.74-tMCtDAHB.woff2 +0 -0
  78. package/gui/dist/assets/WantedSansVariable.split.75-Ciw0D5WG.woff2 +0 -0
  79. package/gui/dist/assets/WantedSansVariable.split.76-DoLjFgp-.woff2 +0 -0
  80. package/gui/dist/assets/WantedSansVariable.split.77-CpT2uvMy.woff2 +0 -0
  81. package/gui/dist/assets/WantedSansVariable.split.78-CkcJ4iZ1.woff2 +0 -0
  82. package/gui/dist/assets/WantedSansVariable.split.79-DsOUJjEM.woff2 +0 -0
  83. package/gui/dist/assets/WantedSansVariable.split.8-DsjypPd6.woff2 +0 -0
  84. package/gui/dist/assets/WantedSansVariable.split.80-C0VwHTte.woff2 +0 -0
  85. package/gui/dist/assets/WantedSansVariable.split.81-DTelu57i.woff2 +0 -0
  86. package/gui/dist/assets/WantedSansVariable.split.82-BiMndGN1.woff2 +0 -0
  87. package/gui/dist/assets/WantedSansVariable.split.83-CVcC6eDG.woff2 +0 -0
  88. package/gui/dist/assets/WantedSansVariable.split.84-DlhZVt_O.woff2 +0 -0
  89. package/gui/dist/assets/WantedSansVariable.split.85-S8I2D3pA.woff2 +0 -0
  90. package/gui/dist/assets/WantedSansVariable.split.86-DozXXpH5.woff2 +0 -0
  91. package/gui/dist/assets/WantedSansVariable.split.87-Dsn0Vuuo.woff2 +0 -0
  92. package/gui/dist/assets/WantedSansVariable.split.88-iNwxxDCr.woff2 +0 -0
  93. package/gui/dist/assets/WantedSansVariable.split.89-B63u_9CZ.woff2 +0 -0
  94. package/gui/dist/assets/WantedSansVariable.split.9-Bi3IzpMI.woff2 +0 -0
  95. package/gui/dist/assets/WantedSansVariable.split.90-ByeH1Pqf.woff2 +0 -0
  96. package/gui/dist/assets/WantedSansVariable.split.91-UQLlagpm.woff2 +0 -0
  97. package/gui/dist/assets/brand-mark-A03mw_9y.js +1 -0
  98. package/gui/dist/assets/geist-cyrillic-ext-wght-normal-DjL33-gN.woff2 +0 -0
  99. package/gui/dist/assets/geist-cyrillic-wght-normal-BEAKL7Jp.woff2 +0 -0
  100. package/gui/dist/assets/geist-latin-ext-wght-normal-DC-KSUi6.woff2 +0 -0
  101. package/gui/dist/assets/geist-latin-wght-normal-BgDaEnEv.woff2 +0 -0
  102. package/gui/dist/assets/geist-mono-cyrillic-ext-wght-normal-X_5orZeX.woff2 +0 -0
  103. package/gui/dist/assets/geist-mono-cyrillic-wght-normal-DiZS0aHC.woff2 +0 -0
  104. package/gui/dist/assets/geist-mono-latin-ext-wght-normal-Bwz-egvJ.woff2 +0 -0
  105. package/gui/dist/assets/geist-mono-latin-wght-normal-XN7g48iV.woff2 +0 -0
  106. package/gui/dist/assets/geist-mono-symbols2-wght-normal-CO5SzqOn.woff2 +0 -0
  107. package/gui/dist/assets/geist-mono-vietnamese-wght-normal-DadHysG0.woff2 +0 -0
  108. package/gui/dist/assets/geist-vietnamese-wght-normal-6IgcOCM7.woff2 +0 -0
  109. package/gui/dist/assets/index-5REODpG3.css +2 -0
  110. package/gui/dist/assets/index-BjTIN4to.js +94 -0
  111. package/gui/dist/assets/segment-thumb-features-Bf6vpwf8.js +1 -0
  112. package/gui/dist/classic/assets/App-C9Eg3nUo.js +58 -0
  113. package/gui/dist/{assets/Tray-CEw0y0jR.js → classic/assets/Tray-B8P8cokE.js} +1 -1
  114. package/gui/dist/classic/assets/index-DFAFnven.js +94 -0
  115. package/gui/dist/classic/assets/quota-summary-C-4HP4_5.js +1 -0
  116. package/gui/dist/classic/index.html +47 -0
  117. package/gui/dist/favicon.png +0 -0
  118. package/gui/dist/favicon.svg +14 -0
  119. package/gui/dist/index.html +15 -2
  120. package/package.json +1 -1
  121. package/src/adapters/anthropic.ts +17 -8
  122. package/src/adapters/google.ts +7 -7
  123. package/src/adapters/kiro/adapter.ts +18 -3
  124. package/src/adapters/kiro/conversation.ts +8 -8
  125. package/src/adapters/kiro/payload.ts +45 -12
  126. package/src/adapters/kiro/stream.ts +169 -12
  127. package/src/adapters/kiro/structured-output-json.ts +191 -0
  128. package/src/adapters/kiro/structured-output-schema.ts +542 -0
  129. package/src/adapters/kiro/structured-output.ts +367 -0
  130. package/src/adapters/kiro-constants.ts +9 -0
  131. package/src/adapters/kiro-tools.ts +14 -9
  132. package/src/adapters/kiro-wire.ts +9 -5
  133. package/src/adapters/openai-chat/messages.ts +58 -5
  134. package/src/adapters/openai-chat/mistral-image-limit.ts +50 -0
  135. package/src/adapters/openai-chat/passthrough.ts +5 -3
  136. package/src/adapters/openai-chat/tool-schema.ts +83 -13
  137. package/src/adapters/openai-responses/opengateway-input.ts +18 -6
  138. package/src/adapters/openai-responses/tool-output-recovery.ts +79 -0
  139. package/src/adapters/qoder/live-models.ts +115 -1
  140. package/src/claude/failure-verdict.ts +21 -0
  141. package/src/claude/inbound-content-options.ts +15 -2
  142. package/src/claude/inbound-model-options.ts +2 -1
  143. package/src/claude/inbound-records.ts +2 -0
  144. package/src/claude/inbound.ts +17 -11
  145. package/src/claude/outbound.ts +52 -23
  146. package/src/cli/capabilities-access-remote.ts +13 -0
  147. package/src/cli/capabilities-base.ts +1 -0
  148. package/src/cli/capabilities-provider-models.ts +3 -3
  149. package/src/cli/codex-shim-autorestore.ts +7 -0
  150. package/src/cli/config-command.ts +11 -2
  151. package/src/cli/connect.ts +17 -2
  152. package/src/cli/dispatch.ts +3 -1
  153. package/src/cli/doctor.ts +95 -7
  154. package/src/cli/index.ts +12 -7
  155. package/src/cli/link-apply-restart.ts +9 -2
  156. package/src/cli/models.ts +124 -38
  157. package/src/cli/registry.ts +1 -1
  158. package/src/cli/restart-failure.ts +17 -0
  159. package/src/cli/stop-approval.ts +2 -2
  160. package/src/cli/sync-command.ts +1 -1
  161. package/src/cli/sync-fanout.ts +15 -4
  162. package/src/cli/system-restart-client.ts +5 -0
  163. package/src/cli/uninstall-client-state.ts +12 -1
  164. package/src/cli/update-restart-child.ts +13 -3
  165. package/src/cli/update-restart-home.ts +6 -3
  166. package/src/cli/update-restart.ts +36 -19
  167. package/src/client/connect.ts +4 -1
  168. package/src/client/hub-client.ts +5 -0
  169. package/src/client/link-management-relay.ts +39 -2
  170. package/src/client/link-readiness.ts +3 -1
  171. package/src/client/machine-api.ts +2 -1
  172. package/src/client/machine-listener.ts +7 -0
  173. package/src/client/orphan-token-recovery.ts +322 -0
  174. package/src/codex/catalog/provider-models.ts +12 -4
  175. package/src/codex/native-profile-api.ts +27 -1
  176. package/src/codex/shim-diagnostics.ts +7 -0
  177. package/src/codex/shim-legacy-record.ts +290 -0
  178. package/src/codex/shim-windows-refresh.ts +9 -2
  179. package/src/codex/shim-wrapper-write.ts +7 -0
  180. package/src/codex/shim.ts +80 -21
  181. package/src/config/diagnostics.ts +9 -9
  182. package/src/config/load-degrade.ts +27 -27
  183. package/src/config/provider-validation.ts +9 -2
  184. package/src/config/removed-opencode-free-backup.ts +6 -3
  185. package/src/config/tracked-runtime-inspection.ts +3 -3
  186. package/src/generated/compatibility-version.json +219 -147
  187. package/src/images/loop.ts +2 -2
  188. package/src/lib/client-error-body.ts +37 -6
  189. package/src/lib/config-ownership-removal.ts +422 -0
  190. package/src/lib/config-ownership.ts +646 -81
  191. package/src/lib/context-overflow-verdict.ts +3 -3
  192. package/src/lib/crash-guard.ts +4 -2
  193. package/src/lib/desktop-cli-handoff.d.mts +3 -4
  194. package/src/lib/desktop-cli-handoff.mjs +7 -16
  195. package/src/lib/errors.ts +1 -0
  196. package/src/lib/local-management-capability.ts +3 -1
  197. package/src/lib/messages-error-body.ts +162 -0
  198. package/src/lib/messages-sse-error-presentation.ts +93 -0
  199. package/src/lib/passive-read.ts +9 -4
  200. package/src/lib/socks5-fetch.ts +21 -9
  201. package/src/lib/upstream-retry.ts +81 -1
  202. package/src/lib/windows-owner-acl.ts +9 -3
  203. package/src/lib/winsw.ts +5 -5
  204. package/src/lib/workflow-budget.ts +3 -1
  205. package/src/oauth/index.ts +7 -0
  206. package/src/oauth/store.ts +20 -10
  207. package/src/protocols/codecs/messages-ir.ts +15 -9
  208. package/src/protocols/encoders/adapter-events.ts +26 -7
  209. package/src/protocols/encoders/messages.ts +72 -28
  210. package/src/providers/antigravity-models.ts +45 -12
  211. package/src/providers/free-directory.ts +2 -2
  212. package/src/providers/reasoning-metadata.ts +2 -1
  213. package/src/providers/registry/entries-extended.ts +9 -0
  214. package/src/reasoning-effort.ts +7 -2
  215. package/src/remote/hub-usage.ts +3 -0
  216. package/src/server/admission-model-scope.ts +1 -1
  217. package/src/server/admitted-http-turn.ts +2 -1
  218. package/src/server/anthropic-rate-limit-headers.ts +75 -3
  219. package/src/server/claude-messages.ts +130 -67
  220. package/src/server/gui-static.ts +4 -1
  221. package/src/server/hub-usage.ts +7 -2
  222. package/src/server/index/link-management.ts +8 -0
  223. package/src/server/index/ollama-routes.ts +2 -0
  224. package/src/server/index/serve-options.ts +23 -20
  225. package/src/server/index/startup-warnings.ts +5 -12
  226. package/src/server/index/websocket-handler.ts +1 -0
  227. package/src/server/inference/client-encoder-delivery.ts +5 -1
  228. package/src/server/management/logs-usage-routes.ts +89 -4
  229. package/src/server/management/provider-routes.ts +2 -22
  230. package/src/server/management/qoder-provider-probe.ts +105 -0
  231. package/src/server/management/route-registry.ts +3 -0
  232. package/src/server/management/usage-aggregate-cache.ts +15 -5
  233. package/src/server/management/usage-source-facets.ts +38 -0
  234. package/src/server/messages-native-tool-guard.ts +11 -3
  235. package/src/server/messages-native.ts +111 -40
  236. package/src/server/messages-response-headers.ts +25 -11
  237. package/src/server/messages-shared.ts +94 -64
  238. package/src/server/messages-sse-error-filter.ts +199 -0
  239. package/src/server/request-log.ts +12 -0
  240. package/src/server/responses/adapter-continuation.ts +11 -5
  241. package/src/server/responses/adapter-delivery.ts +14 -8
  242. package/src/server/responses/adapter-dispatch.ts +8 -8
  243. package/src/server/responses/anthropic-thinking-recovery.ts +2 -2
  244. package/src/server/responses/codex-auth-error.ts +8 -4
  245. package/src/server/responses/codex-ws-wire.ts +19 -3
  246. package/src/server/responses/compact.ts +4 -1
  247. package/src/server/responses/core-auth.ts +1 -1
  248. package/src/server/responses/core-combo-failure.ts +2 -0
  249. package/src/server/responses/core-combo.ts +2 -0
  250. package/src/server/responses/core-errors.ts +5 -4
  251. package/src/server/responses/core-options.ts +2 -0
  252. package/src/server/responses/empty-completion-guard.ts +4 -1
  253. package/src/server/responses/pacing-overload.ts +1 -1
  254. package/src/server/responses/passthrough-dispatch.ts +5 -5
  255. package/src/server/responses/request-prepare.ts +3 -1
  256. package/src/server/responses/request-transport.ts +9 -8
  257. package/src/server/responses/response-effects.ts +3 -2
  258. package/src/server/responses/terminal-guard.ts +30 -0
  259. package/src/server/restart-replacement.ts +3 -1
  260. package/src/server/sse-payload-rewrite.ts +23 -11
  261. package/src/server/workflow-refusal.ts +1 -1
  262. package/src/server/ws-bridge.ts +4 -0
  263. package/src/service/definition.ts +36 -4
  264. package/src/service/launchd.ts +89 -32
  265. package/src/service/logging.ts +34 -7
  266. package/src/service/plist-xml.ts +59 -0
  267. package/src/service/state.ts +8 -0
  268. package/src/service/systemd-env.ts +2 -0
  269. package/src/service/systemd.ts +31 -7
  270. package/src/service/windows-taskxml.ts +16 -7
  271. package/src/service-manager-probe.ts +4 -10
  272. package/src/types/provider.ts +2 -0
  273. package/src/types/request.ts +13 -1
  274. package/src/update/config-preflight.ts +48 -0
  275. package/src/update/index.ts +15 -1
  276. package/src/usage/client.ts +43 -0
  277. package/src/usage/error-detail.ts +1 -1
  278. package/src/usage/log.ts +4 -0
  279. package/src/usage/source-facets.ts +51 -0
  280. package/src/usage/source-filter.ts +65 -0
  281. package/src/usage/summary.ts +50 -8
  282. package/src/web-search/anthropic-executor.ts +105 -24
  283. package/src/web-search/executor.ts +5 -3
  284. package/src/web-search/loop.ts +2 -1
  285. package/src/web-search/progress-stream.ts +64 -5
  286. package/gui/dist/assets/App-DuNhggE1.js +0 -58
  287. package/gui/dist/assets/index-CynE_Rue.js +0 -94
  288. package/gui/dist/assets/quota-summary-VHFSlUuM.js +0 -1
  289. /package/gui/dist/{assets → classic/assets}/App-B4j-Txmb.css +0 -0
  290. /package/gui/dist/{assets → classic/assets}/index-CHWwDo9L.css +0 -0
@@ -0,0 +1,367 @@
1
+ import type { AdapterEvent, OcxParsedRequest, OcxUsage } from "../../types";
2
+ import { KIRO_STRUCTURED_OUTPUT_TOOL_NAME } from "../kiro-constants";
3
+ import { sanitizeKiroSchema } from "../kiro-tools";
4
+ import { readKiroJson } from "./structured-output-json";
5
+ import { assertKiroStrictSchemaSupported, kiroStrictSchemaProblem, rewriteKiroWrappedRefs } from "./structured-output-schema";
6
+
7
+ /**
8
+ * Structured output on Kiro, emulated through a private terminal tool.
9
+ *
10
+ * The CodeWhisperer wire has no schema-constrained response mode, which is why this adapter used to
11
+ * refuse `text.format` json_schema/json_object outright: a caller that expects parseable JSON and
12
+ * receives prose fails downstream. Refusing kept that promise but broke every caller that only asks
13
+ * for a small JSON answer — T3 Code titles each thread through a Messages `output_config.format`
14
+ * request, and Claude Code's own structured-output calls take the same path.
15
+ *
16
+ * The wire does carry tool input schemas, and a tool call's input is JSON by construction. So a
17
+ * structured-output turn advertises one tool whose input schema IS the caller's format, tells the
18
+ * model to answer by calling it, and relays the call's input as the assistant's text. The promise
19
+ * is unchanged: the client receives JSON that parsed and passed the checks below, or an error —
20
+ * never prose. A non-strict format gets light checks (root type and the root's `required` keys),
21
+ * the same position the Cursor prompt fallback takes. A `strict: true` format is validated against
22
+ * the whole schema (structured-output-schema.ts), and a strict schema that validator cannot enforce
23
+ * is refused before sending.
24
+ */
25
+ export interface KiroStructuredOutputSpec {
26
+ /** The caller's schema exactly as sent; absent when only "a JSON object" was requested. */
27
+ schema?: Record<string, unknown>;
28
+ /** True when the caller asked for `strict: true`, so the value must conform to the whole schema. */
29
+ strict?: boolean;
30
+ /** The tool input schema actually advertised: sanitized, and wrapped when `wrapped` is true. */
31
+ toolSchema: Record<string, unknown>;
32
+ /**
33
+ * True when the answer rides the tool input's `value` property instead of BEING the input.
34
+ *
35
+ * Kiro, like Bedrock, accepts only an object-typed tool input root and refuses a root
36
+ * anyOf/oneOf/allOf. kiro-tools flattens such roots for ordinary tools, which is harmless for an
37
+ * argument bag but would silently change the meaning of a caller's output contract — a root
38
+ * `anyOf` would become "any of these properties". Wrapping keeps the schema intact one level down.
39
+ */
40
+ wrapped: boolean;
41
+ name?: string;
42
+ description?: string;
43
+ }
44
+
45
+ type JsonRecord = Record<string, unknown>;
46
+
47
+ /** A plain JSON object: not null and not an array. */
48
+ function isRecord(value: unknown): value is JsonRecord {
49
+ return value !== null && typeof value === "object" && !Array.isArray(value);
50
+ }
51
+
52
+ /** An object-typed root without root composition can be the tool input schema as it stands. */
53
+ function isPlainObjectRoot(schema: JsonRecord): boolean {
54
+ return schema.type === "object"
55
+ && !["anyOf", "oneOf", "allOf", "$ref"].some(key => Object.hasOwn(schema, key));
56
+ }
57
+
58
+ /**
59
+ * The structured-output contract this turn carries, or undefined for an ordinary turn.
60
+ *
61
+ * `options.textFormat` is the source; `_structuredOutput` alone (no format object) still means the
62
+ * caller expects JSON, so it is honoured as the weakest form of the contract: a JSON object.
63
+ */
64
+ export function kiroStructuredOutputSpec(parsed: OcxParsedRequest): KiroStructuredOutputSpec | undefined {
65
+ const format = parsed.options.textFormat;
66
+ if (!format && !parsed._structuredOutput) return undefined;
67
+ const meta = {
68
+ ...(format?.type === "json_schema" && format.name ? { name: format.name } : {}),
69
+ ...(format?.type === "json_schema" && format.description ? { description: format.description } : {}),
70
+ };
71
+ const schema = format?.type === "json_schema" && isRecord(format.schema) ? format.schema : undefined;
72
+ // A Messages schema is a conformance promise even when its translation states `strict: false`.
73
+ const strict = format?.type === "json_schema" && (format.strict === true || parsed._structuredOutputConformance === true);
74
+ // A strict format promises conformance to its schema; without an object schema (absent, or a
75
+ // boolean such as `false`) there is nothing this emulation can enforce, so it is refused.
76
+ if (!schema && strict) {
77
+ throw new Error("Kiro does not support Responses structured output: a strict format needs a JSON object schema");
78
+ }
79
+ if (!schema) return { toolSchema: { type: "object" }, wrapped: false, ...meta };
80
+ if (strict) assertKiroStrictSchemaSupported(schema);
81
+ const contract = { schema, ...(strict ? { strict } : {}) };
82
+ const sanitized = sanitizeKiroSchema(schema) as JsonRecord;
83
+ if (isPlainObjectRoot(schema)) return { ...contract, toolSchema: sanitized, wrapped: false, ...meta };
84
+ // `#/$defs/...` references resolve against the document root, which is now the wrapper. Hoist the
85
+ // definitions with them so a referenced schema still resolves after it moves under `value`, and
86
+ // re-point `#` and other root-relative references at `#/properties/value`, the original root.
87
+ // A root `$id` stays at the wrapper root with the hoisted definitions, so references keep the
88
+ // same base; moved under `value` it would start a new resource.
89
+ const { $defs, definitions, $id, ...inner } = rewriteKiroWrappedRefs(sanitized) as JsonRecord;
90
+ return {
91
+ ...contract,
92
+ wrapped: true,
93
+ toolSchema: {
94
+ ...($id !== undefined ? { $id } : {}),
95
+ type: "object",
96
+ properties: { value: inner },
97
+ required: ["value"],
98
+ ...($defs !== undefined ? { $defs } : {}),
99
+ ...(definitions !== undefined ? { definitions } : {}),
100
+ },
101
+ ...meta,
102
+ };
103
+ }
104
+
105
+ /** The private terminal tool advertised for a structured-output turn, with the caller's (sanitized, possibly wrapped) schema as its input schema. */
106
+ export function kiroStructuredOutputTool(spec: KiroStructuredOutputSpec): Record<string, unknown> {
107
+ const delivery = spec.wrapped
108
+ ? "Put the complete final JSON value in `value`."
109
+ : "The tool input itself is the complete final JSON answer.";
110
+ return {
111
+ toolSpecification: {
112
+ name: KIRO_STRUCTURED_OUTPUT_TOOL_NAME,
113
+ // Same reasoning as the completion tool's description (payload.ts): this is the surface the
114
+ // model reads while choosing between tools, so it states terminality and the obligation here
115
+ // rather than leaving them to the prose contract alone.
116
+ description: `Terminal structured-output channel, not an ordinary work tool. The caller requires the final answer as JSON in exactly the format of this tool's input schema. When the task is complete, call this tool exactly once instead of writing the answer as ordinary assistant text. ${delivery} The call is complete when issued: it ends the turn, returns no tool result, and no text or tool call may follow it.`,
117
+ inputSchema: { json: spec.toolSchema },
118
+ },
119
+ };
120
+ }
121
+
122
+ /**
123
+ * The prose half of the structured-output contract, at most `maxChars` long.
124
+ *
125
+ * The caller's schema is restated verbatim because the advertised one is sanitized: Kiro's
126
+ * validator rejects `additionalProperties`, `pattern`, length and range keywords, so the tool schema
127
+ * alone would let the model miss constraints the caller wrote. A schema that does not fit the
128
+ * injected-instruction budget is dropped whole rather than cut mid-JSON.
129
+ */
130
+ export function kiroStructuredOutputInstructions(
131
+ spec: KiroStructuredOutputSpec,
132
+ hasOrdinaryTools: boolean,
133
+ maxChars: number,
134
+ ): string {
135
+ const kind = spec.schema ? "JSON matching the caller's JSON Schema" : "a single JSON object";
136
+ const delivery = spec.wrapped
137
+ ? "with the complete final JSON value in its `value` property"
138
+ : "with the complete final JSON answer as the tool input";
139
+ const base = [
140
+ `[Final response format] The caller requires this turn's final answer as ${kind}.`,
141
+ `Deliver it only by calling ${KIRO_STRUCTURED_OUTPUT_TOOL_NAME} exactly once, ${delivery}.`,
142
+ "Do not write the final answer as ordinary assistant text, Markdown, or a code fence.",
143
+ hasOrdinaryTools
144
+ ? `Ordinary assistant text is mid-task commentary and does not end the turn: keep using the other tools while work remains, and call ${KIRO_STRUCTURED_OUTPUT_TOOL_NAME} only when the task is complete.`
145
+ : undefined,
146
+ "The call is terminal: it ends the turn, returns no tool result, and no text or tool call may follow it.",
147
+ ].filter((line): line is string => line !== undefined).join(" ");
148
+ const details = [
149
+ spec.name ? `Format name: ${spec.name}.` : undefined,
150
+ spec.description ? `Format description: ${spec.description}` : undefined,
151
+ spec.schema ? `The final JSON must conform to this JSON Schema: ${JSON.stringify(spec.schema)}` : undefined,
152
+ ].filter((line): line is string => line !== undefined);
153
+ const full = details.length > 0 ? `${base}\n${details.join("\n")}` : base;
154
+ return full.length <= maxChars ? full : base;
155
+ }
156
+
157
+ /** The bounded retry's instruction when the first attempt did not deliver valid structured output. */
158
+ export function kiroStructuredOutputRetryMessage(hasOrdinaryTools: boolean): string {
159
+ return `Your previous reply did not deliver the required structured output. Do not quote this instruction. Call ${KIRO_STRUCTURED_OUTPUT_TOOL_NAME} now, exactly once, with the complete final answer as JSON matching its input schema.${hasOrdinaryTools ? " If the task genuinely needs another real tool call first, issue that tool call instead." : ""} Do not reply with ordinary text.`;
160
+ }
161
+
162
+ /** The JSON types a schema declares through `type`, as a string or an array of strings. */
163
+ function declaredTypes(schema: JsonRecord): string[] {
164
+ if (typeof schema.type === "string") return [schema.type];
165
+ return Array.isArray(schema.type) ? schema.type.filter((t): t is string => typeof t === "string") : [];
166
+ }
167
+
168
+ /** Whether a parsed JSON value has the given JSON Schema type; an unknown type keyword always matches. */
169
+ function matchesJsonType(value: unknown, type: string): boolean {
170
+ switch (type) {
171
+ case "object": return isRecord(value);
172
+ case "array": return Array.isArray(value);
173
+ case "string": return typeof value === "string";
174
+ case "number": return typeof value === "number" && Number.isFinite(value);
175
+ case "integer": return Number.isInteger(value);
176
+ case "boolean": return typeof value === "boolean";
177
+ case "null": return value === null;
178
+ // An unknown type keyword is not ours to enforce.
179
+ default: return true;
180
+ }
181
+ }
182
+
183
+ /**
184
+ * The root types a schema admits, including through a root `anyOf`/`oneOf` whose every branch
185
+ * declares a type. A composed root is exactly the wrapped case, where a model can hand back the
186
+ * answer JSON-encoded inside `value` as a string; without this, a root that admits only objects and
187
+ * arrays would accept that string because the root itself declares no `type`. A branch without a
188
+ * declared type (or a `$ref`) admits anything, so the check is skipped rather than guessed.
189
+ */
190
+ function admittedRootTypes(schema: JsonRecord): string[] {
191
+ const own = declaredTypes(schema);
192
+ if (own.length > 0) return own;
193
+ for (const key of ["anyOf", "oneOf"] as const) {
194
+ const branches = schema[key];
195
+ if (!Array.isArray(branches) || branches.length === 0) continue;
196
+ const perBranch = branches.map(branch => (isRecord(branch) ? declaredTypes(branch) : []));
197
+ if (perBranch.some(types => types.length === 0)) return [];
198
+ return [...new Set(perBranch.flat())];
199
+ }
200
+ return [];
201
+ }
202
+
203
+ /** The first reason `value` breaks the light contract, or undefined when it passes. */
204
+ function structuredValueProblem(spec: KiroStructuredOutputSpec, value: unknown): string | undefined {
205
+ const types = spec.schema ? admittedRootTypes(spec.schema) : ["object"];
206
+ if (types.length > 0 && !types.some(type => matchesJsonType(value, type))) {
207
+ return `expected a JSON ${types.join(" or ")} at the root`;
208
+ }
209
+ const required = spec.schema?.required;
210
+ if (isRecord(value) && Array.isArray(required)) {
211
+ const missing = required.find(key => typeof key === "string" && !Object.hasOwn(value, key));
212
+ // No property name: diagnostics carry fixed categories, never schema or answer text.
213
+ if (missing !== undefined) return "the root is missing a required property";
214
+ }
215
+ return undefined;
216
+ }
217
+
218
+ /**
219
+ * Strict validation of JSON `text` that already parsed: the JSON text to relay, or the problem.
220
+ *
221
+ * The strict validator reads the text again keeping every number's lexeme, so bounds, `const` and
222
+ * `enum` judge the exact bytes the client will receive. The wrapped form relays the original bytes
223
+ * of `value`, which keeps integers beyond 2^53 intact there too.
224
+ */
225
+ function strictStructuredJson(schema: JsonRecord, text: string, wrapped: boolean): { json: string } | { problem: string } {
226
+ const document = readKiroJson(text);
227
+ if (!document) return { problem: "the value nests deeper than strict validation allows" };
228
+ const root = document.value;
229
+ const value = wrapped && root.kind === "object" ? root.entries.get("value") : root;
230
+ if (!value) return { problem: "missing `value`" };
231
+ const problem = kiroStrictSchemaProblem(schema, value, document.nodes);
232
+ if (problem) return { problem };
233
+ return { json: wrapped ? text.slice(value.start, value.end) : text };
234
+ }
235
+
236
+ const FAILURE_PREFIX = "Kiro structured output did not match the requested format";
237
+
238
+ /**
239
+ * Validate the structured-output tool's input and return the JSON text to relay.
240
+ *
241
+ * Both forms relay the model's own bytes rather than a re-serialization, so integers beyond 2^53,
242
+ * numbers past the double range and key order survive exactly as written. The wrapped form relays
243
+ * the original bytes of `value`.
244
+ */
245
+ export function parseKiroStructuredToolInput(
246
+ spec: KiroStructuredOutputSpec,
247
+ raw: string,
248
+ ): { json: string } | { error: string } {
249
+ const text = raw.trim() || "{}";
250
+ let input: unknown;
251
+ try {
252
+ input = JSON.parse(text);
253
+ } catch {
254
+ return { error: "Kiro returned invalid JSON for the structured-output tool" };
255
+ }
256
+ if (!isRecord(input)) return { error: "Kiro returned a non-object input for the structured-output tool" };
257
+ if (spec.wrapped && !Object.hasOwn(input, "value")) {
258
+ return { error: `${FAILURE_PREFIX}: missing \`value\`` };
259
+ }
260
+ const value = spec.wrapped ? input.value : input;
261
+ if (spec.strict && spec.schema) {
262
+ const strict = strictStructuredJson(spec.schema, text, spec.wrapped);
263
+ return "json" in strict ? strict : { error: `${FAILURE_PREFIX}: ${strict.problem}` };
264
+ }
265
+ const problem = structuredValueProblem(spec, value);
266
+ if (problem) return { error: `${FAILURE_PREFIX}: ${problem}` };
267
+ if (!spec.wrapped) return { json: text };
268
+ const wrappedText = wrappedValueText(text);
269
+ return wrappedText === undefined
270
+ ? { error: `${FAILURE_PREFIX}: the value nests deeper than the proxy can relay exactly` }
271
+ : { json: wrappedText };
272
+ }
273
+
274
+ /**
275
+ * The original bytes of the wrapper's `value`, or undefined past the reader's nesting limit. Such a
276
+ * value is refused rather than re-serialized, because re-serializing rewrites large numbers.
277
+ */
278
+ function wrappedValueText(text: string): string | undefined {
279
+ const root = readKiroJson(text)?.value;
280
+ const span = root?.kind === "object" ? root.entries.get("value") : undefined;
281
+ return span ? text.slice(span.start, span.end) : undefined;
282
+ }
283
+
284
+ const WHOLE_FENCE = /^```[A-Za-z0-9_-]*[ \t]*\r?\n([\s\S]*?)\r?\n?```$/;
285
+
286
+ /**
287
+ * Accept a plain-text answer only when it already IS the requested JSON.
288
+ *
289
+ * A model that ignores the tool and writes the JSON as text has still answered correctly, and
290
+ * spending a second paid request to have it repeat the same bytes through a tool would be waste.
291
+ * One whole-message code fence is unwrapped because that is the most common way models present
292
+ * JSON; anything else — prose around the JSON, two fenced blocks, trailing commentary — is not JSON
293
+ * and is refused, which sends the turn to the bounded retry or to an error.
294
+ */
295
+ export function parseKiroStructuredText(spec: KiroStructuredOutputSpec, text: string): string | undefined {
296
+ const trimmed = text.trim();
297
+ const candidate = WHOLE_FENCE.exec(trimmed)?.[1]?.trim() ?? trimmed;
298
+ if (!candidate) return undefined;
299
+ let value: unknown;
300
+ try {
301
+ value = JSON.parse(candidate);
302
+ } catch {
303
+ return undefined;
304
+ }
305
+ if (spec.strict && spec.schema) {
306
+ // A text answer is the value itself, even when the tool input would have wrapped it.
307
+ return "json" in strictStructuredJson(spec.schema, candidate, false) ? candidate : undefined;
308
+ }
309
+ return structuredValueProblem(spec, value) === undefined ? candidate : undefined;
310
+ }
311
+
312
+ /**
313
+ * Whether Kiro stopped the way a finished answer stops: no stop reason, END_TURN or STOP_SEQUENCE.
314
+ *
315
+ * Every other stop reason (MAX_TOKENS, a content filter, an exhausted context window) has already
316
+ * ended the inference upstream. Text cut by one of them is never accepted as the requested JSON,
317
+ * even when its prefix parses, and a failed structured answer under one of them earns no retry:
318
+ * the retry would hit the same limit or verdict, so the stop's own terminal handling runs instead.
319
+ */
320
+ export function isKiroStructuredCleanStop(normalizedStopReason: string | undefined): boolean {
321
+ return normalizedStopReason === undefined
322
+ || normalizedStopReason === "END_TURN"
323
+ || normalizedStopReason === "STOP_SEQUENCE";
324
+ }
325
+
326
+ /** Message for a bounded retry that answered in text that is not the requested JSON. */
327
+ export const KIRO_STRUCTURED_TEXT_FAILURE = `${FAILURE_PREFIX}: the model answered with text that is not the requested JSON`;
328
+
329
+ /** Message for a bounded retry that ended without text, a tool call, or a structured answer. */
330
+ export const KIRO_STRUCTURED_EMPTY_FAILURE = `${FAILURE_PREFIX}: the bounded retry produced no answer`;
331
+
332
+ /** Stop reasons Kiro documents; only these are named in a diagnostic. */
333
+ const KNOWN_STOP_REASONS = new Set([
334
+ "MAX_TOKENS", "MODEL_CONTEXT_WINDOW_EXCEEDED", "MALFORMED_TOOL_USE", "MALFORMED_MODEL_OUTPUT",
335
+ "TOOL_USE", "CONTENT_FILTERED", "GUARDRAIL_INTERVENED",
336
+ ]);
337
+
338
+ /**
339
+ * Message for a bounded retry whose text was cut by a stop that does not end a finished answer. The
340
+ * stop reason comes from upstream, so an unrecognized one is not echoed.
341
+ */
342
+ export function kiroStructuredStopFailure(normalizedStopReason: string): string {
343
+ const stop = KNOWN_STOP_REASONS.has(normalizedStopReason) ? ` with ${normalizedStopReason}` : "";
344
+ return `${FAILURE_PREFIX}: the bounded retry stopped${stop} before a complete answer`;
345
+ }
346
+
347
+ /**
348
+ * Terminal for a turn that, after its one bounded retry, still produced no valid structured output.
349
+ *
350
+ * A hard error with `retryable: false` rather than the retryable `incomplete` the completion
351
+ * contract uses for a malformed answer: the model has already been asked twice inside this turn, so
352
+ * the proxy must not replay the whole turn on its own. The status is the 502 every other Kiro
353
+ * model-output protocol error uses, which a client's own retry policy may still act on (Claude
354
+ * outbound reports it as `overloaded_error`); that choice stays with the client. The distinct code
355
+ * lets a caller tell this apart from a transport failure.
356
+ */
357
+ export function kiroStructuredOutputFailure(message: string, usage: OcxUsage): AdapterEvent {
358
+ return {
359
+ type: "error",
360
+ message,
361
+ status: 502,
362
+ errorType: "upstream_error",
363
+ code: "invalid_kiro_structured_output",
364
+ retryable: false,
365
+ usage,
366
+ };
367
+ }
@@ -1,4 +1,13 @@
1
1
  export const KIRO_COMPLETION_TOOL_NAME = "codex_kiro_final_answer";
2
+ /**
3
+ * Private terminal channel for Responses structured output (`text.format` json_schema/json_object).
4
+ *
5
+ * The CodeWhisperer wire has no schema-constrained response mode, but it does carry tool input
6
+ * schemas, and a tool call's input is JSON by construction. A turn that asks for structured output
7
+ * therefore advertises this tool INSTEAD of `KIRO_COMPLETION_TOOL_NAME` and relays its input as the
8
+ * assistant's text. Reserved in the same collision domain so a client tool can never claim it.
9
+ */
10
+ export const KIRO_STRUCTURED_OUTPUT_TOOL_NAME = "codex_kiro_structured_output";
2
11
 
3
12
  /**
4
13
  * Request-scoped CodeWhisperer service profile for AWS Builder ID accounts.
@@ -60,25 +60,30 @@ const KIRO_REJECTED_SCHEMA_KEYS = new Set([
60
60
  // "format"/"pattern" would be deleted. We recurse into the value schemas but keep every name intact.
61
61
  const SCHEMA_MAP_KEYS = new Set(["properties", "$defs", "definitions"]);
62
62
 
63
+ // Keys whose values are JSON data rather than schemas. Recursing into them would strip
64
+ // keyword-named keys from the data itself and turn `const: {"format":"pdf"}` into `const: {}`,
65
+ // silently changing the value a tool argument must equal.
66
+ const SCHEMA_LITERAL_KEYS = new Set(["const", "enum", "default", "examples"]);
67
+
63
68
  function sanitizeSchemaMap(value: unknown): unknown {
64
69
  if (!value || typeof value !== "object" || Array.isArray(value)) return sanitizeKiroSchema(value);
65
- const out: Record<string, unknown> = {};
66
- for (const [name, child] of Object.entries(value as Record<string, unknown>)) {
67
- out[name] = sanitizeKiroSchema(child);
68
- }
69
- return out;
70
+ // fromEntries defines own properties: a property named "__proto__" stays a property instead of
71
+ // hitting the prototype setter and vanishing from the advertised schema.
72
+ return Object.fromEntries(Object.entries(value as Record<string, unknown>).map(([name, child]) => [name, sanitizeKiroSchema(child)]));
70
73
  }
71
74
 
72
- function sanitizeKiroSchema(value: unknown): unknown {
75
+ /** Strip the keywords Kiro's tool-spec validator rejects, everywhere in a schema tree. */
76
+ export function sanitizeKiroSchema(value: unknown): unknown {
73
77
  if (Array.isArray(value)) return value.map(sanitizeKiroSchema);
74
78
  if (!value || typeof value !== "object") return value;
75
- const out: Record<string, unknown> = {};
79
+ const out: Array<[string, unknown]> = [];
76
80
  for (const [key, child] of Object.entries(value as Record<string, unknown>)) {
77
81
  if (KIRO_REJECTED_SCHEMA_KEYS.has(key)) continue;
78
82
  if (key === "required" && Array.isArray(child) && child.length === 0) continue;
79
- out[key] = SCHEMA_MAP_KEYS.has(key) ? sanitizeSchemaMap(child) : sanitizeKiroSchema(child);
83
+ if (SCHEMA_LITERAL_KEYS.has(key)) out.push([key, child]);
84
+ else out.push([key, SCHEMA_MAP_KEYS.has(key) ? sanitizeSchemaMap(child) : sanitizeKiroSchema(child)]);
80
85
  }
81
- return out;
86
+ return Object.fromEntries(out);
82
87
  }
83
88
 
84
89
  function ensureRootObjectType(schema: unknown): Record<string, unknown> {
@@ -2,7 +2,7 @@ import { createHash, randomUUID } from "node:crypto";
2
2
  import { hostname, userInfo } from "node:os";
3
3
  import { normalizeKiroModelId } from "../providers/kiro-models";
4
4
  import type { OcxParsedRequest } from "../types";
5
- import { KIRO_COMPLETION_TOOL_NAME } from "./kiro-constants";
5
+ import { KIRO_COMPLETION_TOOL_NAME, KIRO_STRUCTURED_OUTPUT_TOOL_NAME } from "./kiro-constants";
6
6
 
7
7
  let cachedFp: string | undefined;
8
8
 
@@ -77,15 +77,19 @@ export interface KiroToolNameRegistry {
77
77
  readonly nameMap: Map<string, string>;
78
78
  }
79
79
 
80
- /** One collision domain for advertised tools, replayed calls, and the private completion tool. */
80
+ /** Proxy-owned terminal tools; neither may be claimed by a client tool or a replayed call. */
81
+ const KIRO_RESERVED_TOOL_NAMES: readonly string[] = [KIRO_COMPLETION_TOOL_NAME, KIRO_STRUCTURED_OUTPUT_TOOL_NAME];
82
+
83
+ /** One collision domain for advertised tools, replayed calls, and the private terminal tools. */
81
84
  export function createKiroToolNameRegistry(): KiroToolNameRegistry {
82
- const used = new Set<string>([KIRO_COMPLETION_TOOL_NAME]);
85
+ const used = new Set<string>(KIRO_RESERVED_TOOL_NAMES);
83
86
  const wireToKiro = new Map<string, string>();
84
87
  const nameMap = new Map<string, string>();
85
88
  return {
89
+ /** Return the Kiro-safe alias for a wire tool name, registering it on first use; reserved names are refused. */
86
90
  alias(wireName: string): string {
87
- if (wireName === KIRO_COMPLETION_TOOL_NAME) {
88
- throw new Error(`Kiro reserves the tool name ${JSON.stringify(KIRO_COMPLETION_TOOL_NAME)}`);
91
+ if (KIRO_RESERVED_TOOL_NAMES.includes(wireName)) {
92
+ throw new Error(`Kiro reserves the tool name ${JSON.stringify(wireName)}`);
89
93
  }
90
94
  const existing = wireToKiro.get(wireName);
91
95
  if (existing) return existing;
@@ -2,6 +2,7 @@ import { isMistralChatTarget, isNativeOpenAIChatTarget, stripBracketedModelSuffi
2
2
  import { reasoningDetailSegmentForWire } from "./response-events";
3
3
  import { translatedChatDeveloperWireRole } from "./developer-role";
4
4
  import { singleLeadingSystemMessages } from "./single-system";
5
+ import { limitMistralChatImages } from "./mistral-image-limit";
5
6
  import { isVolcengineArkPaygChatTarget } from "./tool-schema";
6
7
  import { contentPartsToText } from "../image";
7
8
  import { EMPTY_TOOL_OUTPUT_ANNOTATION, isWhitespaceOnlyTextPartArray } from "../empty-tool-output-annotation";
@@ -112,6 +113,12 @@ export function messagesToChatFormat(parsed: OcxParsedRequest, provider: OcxProv
112
113
  let pendingToolResultAudioParts: unknown[] = [];
113
114
  let mintedIdSeq = 0;
114
115
  const seenWireCallIds = new Set<string>();
116
+ // One call id can arrive with more than one result: Codex code mode records the yield marker
117
+ // for a running cell, then each late `notify()`/wait output as a further result for the same
118
+ // call. OpenAI-compatible chat providers reject the second `role:"tool"` reply for an id that
119
+ // was already answered ("Duplicate tool output for call_id"), so the repeats stay out of the
120
+ // wire body and their text is appended to the result that already answered the call.
121
+ const answeredToolResults = new Map<string, { content: unknown }>();
115
122
 
116
123
  const mintCallId = (): string => {
117
124
  let id = "";
@@ -167,6 +174,20 @@ export function messagesToChatFormat(parsed: OcxParsedRequest, provider: OcxProv
167
174
  releaseDeferredBarriers();
168
175
  };
169
176
 
177
+ /** Append a repeated result for an already-answered call to the answer that call already got. */
178
+ const appendAnsweredToolResultText = (
179
+ message: { content: unknown },
180
+ text: string,
181
+ ): void => {
182
+ if (text.length === 0) return;
183
+ const current = message.content;
184
+ // `toolResultTextForWire` always returns text for a `role:"tool"` reply, so the answer is a
185
+ // string; an unexpected shape still keeps both halves rather than dropping the repeat.
186
+ message.content = typeof current === "string" && current.length > 0
187
+ ? `${current}\n\n${text}`
188
+ : typeof current === "string" ? text : [current, text];
189
+ };
190
+
170
191
  const nativeOpenAI = isNativeOpenAIChatTarget(provider);
171
192
  // Leading-system chat templates reject non-leading system and every developer role while a
172
193
  // later user renders in place: Qwen3.8-27B, Flash-Next, and the OrcaSAQ-2-Cyber-27B GGUF family.
@@ -369,11 +390,13 @@ export function messagesToChatFormat(parsed: OcxParsedRequest, provider: OcxProv
369
390
  let toolCallId = msg.toolCallId;
370
391
  const matchIdx = toolCallId ? pendingToolCalls.findIndex(c => c.id === toolCallId) : -1;
371
392
  if (matchIdx >= 0 && toolCallId) {
372
- out.push({
393
+ const toolMsg = {
373
394
  role: "tool",
374
395
  tool_call_id: toolCallId,
375
396
  content: toolResultTextForWire(msg.content, provider.annotateEmptyToolOutputs === true),
376
- });
397
+ };
398
+ out.push(toolMsg);
399
+ answeredToolResults.set(toolCallId, toolMsg);
377
400
  pendingToolResultImageParts.push(...toolResultImageChatParts(msg.content));
378
401
  pendingToolResultAudioParts.push(...toolResultAudioChatParts(msg.content));
379
402
  pendingToolCalls.splice(matchIdx, 1);
@@ -382,6 +405,34 @@ export function messagesToChatFormat(parsed: OcxParsedRequest, provider: OcxProv
382
405
  flushToolResultAudio();
383
406
  releaseDeferredBarriers();
384
407
  }
408
+ } else if (
409
+ toolCallId
410
+ && answeredToolResults.has(toolCallId)
411
+ && !pendingToolCalls.some(c => c.id === toolCallId)
412
+ ) {
413
+ const answer = answeredToolResults.get(toolCallId)!;
414
+ const text = toolResultTextForWire(msg.content, provider.annotateEmptyToolOutputs === true);
415
+ if (out[out.length - 1] === answer && deferredBarrierMessages.length === 0) {
416
+ // Adjacent results can share one reply without moving anything across a later turn.
417
+ appendAnsweredToolResultText(answer, text);
418
+ pendingToolResultImageParts.push(...toolResultImageChatParts(msg.content));
419
+ pendingToolResultAudioParts.push(...toolResultAudioChatParts(msg.content));
420
+ if (pendingToolCalls.length === 0) {
421
+ flushToolResultImages();
422
+ flushToolResultAudio();
423
+ }
424
+ } else {
425
+ // Chat cannot repeat a tool reply. Keep late text and media together at their
426
+ // recorded position, identified by call ID; an open tool block must close first.
427
+ const media = typeof msg.content === "string" ? [] : msg.content.flatMap(part => [
428
+ ...toolResultImageChatParts([part]), ...toolResultAudioChatParts([part]),
429
+ ]);
430
+ const carrier = { role: "user", content: [
431
+ { type: "text", text: `[ocx] additional output for tool call ${toolCallId}:\n${text}` },
432
+ ...media,
433
+ ] };
434
+ (pendingToolCalls.length > 0 ? deferredBarrierMessages : out).push(carrier);
435
+ }
385
436
  } else {
386
437
  if (!toolCallId) toolCallId = `call_orphan_${out.length}`;
387
438
  flushPendingToolCalls();
@@ -422,11 +473,13 @@ export function messagesToChatFormat(parsed: OcxParsedRequest, provider: OcxProv
422
473
  }],
423
474
  });
424
475
  seenWireCallIds.add(toolCallId);
425
- out.push({
476
+ const toolMsg = {
426
477
  role: "tool",
427
478
  tool_call_id: toolCallId,
428
479
  content: toolResultTextForWire(msg.content, provider.annotateEmptyToolOutputs === true),
429
- });
480
+ };
481
+ out.push(toolMsg);
482
+ answeredToolResults.set(toolCallId, toolMsg);
430
483
  pendingToolResultImageParts.push(...toolResultImageChatParts(msg.content));
431
484
  pendingToolResultAudioParts.push(...toolResultAudioChatParts(msg.content));
432
485
  flushToolResultImages();
@@ -439,7 +492,7 @@ export function messagesToChatFormat(parsed: OcxParsedRequest, provider: OcxProv
439
492
 
440
493
  flushPendingToolCalls();
441
494
  releaseDeferredBarriers();
442
- return singleLeadingSystemMessages(out, provider) as unknown[];
495
+ return limitMistralChatImages(singleLeadingSystemMessages(out, provider), provider, parsed.modelId) as unknown[];
443
496
  }
444
497
 
445
498
  export function safeToolName(name: string | undefined): string {
@@ -0,0 +1,50 @@
1
+ import type { OcxProviderConfig } from "../../types";
2
+ import { declaredModelCapabilities, mergeReasoningModelCapabilities } from "../../providers/reasoning-capabilities";
3
+ import { registryEntryForProviderDestination } from "../../providers/registry";
4
+ import { isMistralChatTarget } from "./wire";
5
+
6
+ /**
7
+ * Mistral counts every image in the replayed history against a per-request cap. Its vision guide
8
+ * (https://docs.mistral.ai/capabilities/vision/) documents 8, and most vision models refuse a ninth
9
+ * with HTTP 400 ("Total number of images exceeds the maximum allowed of 8"). Models that accept more
10
+ * declare `modelCapabilities.<id>.mistralMaxImages`: the registry row carries measured caps, matched
11
+ * by destination so a renamed Mistral row keeps them, and an operator declaration outranks it.
12
+ */
13
+ export const MISTRAL_DEFAULT_MAX_IMAGES = 8;
14
+
15
+ /** The images one Chat request may carry for this model at this destination. */
16
+ export function mistralMaxImages(provider: OcxProviderConfig, modelId: string): number {
17
+ const rows = mergeReasoningModelCapabilities(registryEntryForProviderDestination(provider)?.modelCapabilities, provider.modelCapabilities);
18
+ return declaredModelCapabilities(rows, modelId)?.mistralMaxImages ?? MISTRAL_DEFAULT_MAX_IMAGES;
19
+ }
20
+
21
+ function isRecord(value: unknown): value is Record<string, unknown> {
22
+ return value !== null && typeof value === "object" && !Array.isArray(value);
23
+ }
24
+
25
+ /**
26
+ * Keep the newest images a first-party Mistral request may carry and replace older ones with a
27
+ * text note, across every message (promoted tool-result images included). Normalizes the outbound
28
+ * copy only: messages that change are copied, so history and other destinations stay intact.
29
+ */
30
+ export function limitMistralChatImages(messages: unknown, provider: OcxProviderConfig, modelId: string): unknown {
31
+ if (!isMistralChatTarget(provider) || !Array.isArray(messages)) return messages;
32
+ const maxImages = mistralMaxImages(provider, modelId);
33
+ const images: Array<{ message: number; part: number }> = [];
34
+ messages.forEach((message, index) => {
35
+ if (!isRecord(message) || !Array.isArray(message.content)) return;
36
+ message.content.forEach((part, partIndex) => {
37
+ if (isRecord(part) && part.type === "image_url") images.push({ message: index, part: partIndex });
38
+ });
39
+ });
40
+ const excess = images.length - maxImages;
41
+ if (excess <= 0) return messages;
42
+ const note = { type: "text", text: `[image omitted: Mistral accepts at most ${maxImages} images per request for this model; older images were dropped]` };
43
+ const out = [...messages];
44
+ for (const { message, part } of images.slice(0, excess)) {
45
+ const original = messages[message] as Record<string, unknown>;
46
+ if (out[message] === original) out[message] = { ...original, content: [...(original.content as unknown[])] };
47
+ ((out[message] as Record<string, unknown>).content as unknown[])[part] = note;
48
+ }
49
+ return out;
50
+ }
@@ -4,6 +4,7 @@ import type { AdapterRequest } from "../base";
4
4
  import { frameAgentRouterMessages } from "../agentrouter";
5
5
  import { applyExplicitChatDeveloperRole } from "./developer-role";
6
6
  import { singleLeadingSystemMessages } from "./single-system";
7
+ import { limitMistralChatImages } from "./mistral-image-limit";
7
8
  import { openRouterProviderPayload, resolveOpenRouterRouting } from "../../providers/openrouter-routing";
8
9
  import { resolveVercelGatewayRouting, vercelGatewayProviderPayload } from "../../providers/vercel-gateway-routing";
9
10
  import { fastPolicyForModel } from "../../providers/service-tier";
@@ -78,11 +79,12 @@ export function buildOpenAIChatPassthroughRequest(
78
79
  // and the conversion changes the role of those messages and nothing else, so the position
79
80
  // of every message and every other field survive unchanged. Missing thinking history is
80
81
  // repaired below using the same preserve policy as the translated Chat builder.
81
- // The explicit single-system policy can then merge instruction slots.
82
- messages: singleLeadingSystemMessages(applyExplicitChatDeveloperRole(
82
+ // The explicit single-system policy can then merge instruction slots, and Mistral's
83
+ // per-request image cap applies as it does to translated Chat.
84
+ messages: limitMistralChatImages(singleLeadingSystemMessages(applyExplicitChatDeveloperRole(
83
85
  frameAgentRouterMessages(provider.baseUrl, rawBody.messages),
84
86
  provider,
85
- ), provider),
87
+ ), provider), provider, modelId),
86
88
  stream,
87
89
  };
88
90
  for (const field of CHAT_PASSTHROUGH_FIELDS) {