@myagentroam/agent 0.11.33 → 0.11.34

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 (856) hide show
  1. package/dist/cli/catalog-file.d.ts +78 -0
  2. package/dist/cli/catalog-file.js +102 -0
  3. package/dist/cli/codex-auth-file.d.ts +1 -1
  4. package/dist/cli/codex-auth-file.js +9 -10
  5. package/dist/cli/main.js +44 -54
  6. package/dist/error.d.ts +15 -0
  7. package/dist/error.js +74 -0
  8. package/dist/extensions/agents.d.ts +100 -0
  9. package/dist/extensions/agents.js +121 -0
  10. package/dist/extensions/capabilities.d.ts +4 -0
  11. package/dist/extensions/commands.d.ts +23 -0
  12. package/dist/extensions/commands.js +45 -0
  13. package/dist/extensions/compaction.d.ts +36 -0
  14. package/dist/extensions/contracts.d.ts +147 -0
  15. package/dist/extensions/data.d.ts +81 -0
  16. package/dist/extensions/data.js +78 -0
  17. package/dist/extensions/environment.d.ts +39 -0
  18. package/dist/extensions/environment.js +52 -0
  19. package/dist/extensions/files.d.ts +68 -0
  20. package/dist/extensions/files.js +26 -0
  21. package/dist/extensions/hooks.d.ts +32 -0
  22. package/dist/extensions/host-ports.d.ts +24 -0
  23. package/dist/extensions/manager.d.ts +42 -0
  24. package/dist/extensions/manager.js +457 -0
  25. package/dist/extensions/mcp.d.ts +116 -0
  26. package/dist/extensions/mcp.js +434 -0
  27. package/dist/extensions/model-request.d.ts +65 -0
  28. package/dist/extensions/model-request.js +197 -0
  29. package/dist/extensions/model-stream.d.ts +18 -0
  30. package/dist/extensions/model-stream.js +108 -0
  31. package/dist/extensions/models.d.ts +46 -0
  32. package/dist/extensions/models.js +7 -0
  33. package/dist/extensions/network.d.ts +40 -0
  34. package/dist/extensions/network.js +97 -0
  35. package/dist/extensions/operation.d.ts +32 -0
  36. package/dist/extensions/processes.d.ts +64 -0
  37. package/dist/extensions/processes.js +284 -0
  38. package/dist/extensions/prompt-composition.d.ts +38 -0
  39. package/dist/extensions/prompt-composition.js +100 -0
  40. package/dist/extensions/prompt-input.d.ts +30 -0
  41. package/dist/extensions/prompt-input.js +48 -0
  42. package/dist/extensions/prompts.d.ts +31 -0
  43. package/dist/extensions/prompts.js +88 -0
  44. package/dist/extensions/resources.d.ts +26 -0
  45. package/dist/extensions/resources.js +221 -0
  46. package/dist/extensions/services.d.ts +31 -0
  47. package/dist/extensions/services.js +61 -0
  48. package/dist/extensions/session-api.d.ts +6 -0
  49. package/dist/extensions/session-api.js +52 -0
  50. package/dist/extensions/session-input.d.ts +184 -0
  51. package/dist/extensions/session-input.js +422 -0
  52. package/dist/extensions/session-messages.d.ts +41 -0
  53. package/dist/extensions/session-messages.js +76 -0
  54. package/dist/extensions/session-tools.d.ts +32 -0
  55. package/dist/extensions/session-tools.js +208 -0
  56. package/dist/extensions/session.d.ts +60 -0
  57. package/dist/extensions/session.js +265 -0
  58. package/dist/extensions/settings.d.ts +76 -0
  59. package/dist/extensions/settings.js +115 -0
  60. package/dist/extensions/store.d.ts +10 -0
  61. package/dist/extensions/store.js +131 -0
  62. package/dist/extensions/tool-runtime.d.ts +16 -0
  63. package/dist/extensions/tools.d.ts +80 -0
  64. package/dist/extensions/tools.js +270 -0
  65. package/dist/extensions.d.ts +22 -0
  66. package/dist/host/contracts.d.ts +58 -0
  67. package/dist/host/contracts.js +18 -0
  68. package/dist/host/description.d.ts +19 -0
  69. package/dist/host/local-agent-host.d.ts +96 -0
  70. package/dist/host/local-agent-host.js +429 -0
  71. package/dist/host/local-exec-tool.d.ts +26 -0
  72. package/dist/host/local-exec-tool.js +686 -0
  73. package/dist/host/local-file-access.d.ts +30 -0
  74. package/dist/host/local-file-access.js +107 -0
  75. package/dist/host/local-network-access.d.ts +6 -0
  76. package/dist/host/local-network-access.js +101 -0
  77. package/dist/host/local-process-executor.d.ts +5 -0
  78. package/dist/host/local-process-executor.js +17 -0
  79. package/dist/host/local-session-environment.d.ts +18 -0
  80. package/dist/host/local-shell.d.ts +3 -0
  81. package/dist/host/local-tool-registry.d.ts +34 -0
  82. package/dist/host/local-tool-registry.js +134 -0
  83. package/dist/host/network.d.ts +5 -0
  84. package/dist/host/network.js +42 -0
  85. package/dist/host/process-control.d.ts +2 -0
  86. package/dist/host/process-control.js +26 -0
  87. package/dist/host/skill-contract.d.ts +6 -0
  88. package/dist/host.d.ts +17 -0
  89. package/dist/host.js +3 -0
  90. package/dist/index.d.ts +26 -51
  91. package/dist/index.js +9 -12
  92. package/dist/model/anthropic-messages.d.ts +10 -0
  93. package/dist/model/anthropic-messages.js +692 -0
  94. package/dist/model/anthropic-thinking.js +33 -0
  95. package/dist/model/configuration.d.ts +111 -0
  96. package/dist/model/configuration.js +201 -0
  97. package/dist/model/contracts.d.ts +229 -0
  98. package/dist/model/http.d.ts +13 -0
  99. package/dist/model/http.js +119 -0
  100. package/dist/model/image-contract.d.ts +10 -0
  101. package/dist/model/image.d.ts +9 -0
  102. package/dist/model/inline-media-budget.d.ts +7 -0
  103. package/dist/model/inline-media-budget.js +36 -0
  104. package/dist/model/input-images.d.ts +3 -0
  105. package/dist/model/input-images.js +16 -0
  106. package/dist/model/openai-responses.d.ts +59 -0
  107. package/dist/model/openai-responses.js +1586 -0
  108. package/dist/model/recovery.js +80 -0
  109. package/dist/model/request-configuration.d.ts +17 -0
  110. package/dist/model/request-configuration.js +47 -0
  111. package/dist/model/responses-event-projection.d.ts +24 -0
  112. package/dist/model/responses-event-projection.js +194 -0
  113. package/dist/model/responses-request.d.ts +5 -0
  114. package/dist/model/responses-request.js +363 -0
  115. package/dist/model/responses-session-cache.d.ts +33 -0
  116. package/dist/model/responses-session-cache.js +64 -0
  117. package/dist/model/runtime-credential.d.ts +1 -0
  118. package/dist/model/runtime-credential.js +1 -0
  119. package/dist/model/sse.js +281 -0
  120. package/dist/model/text-blocks.js +40 -0
  121. package/dist/model/tool-declarations.d.ts +4 -0
  122. package/dist/model/tool-definition-projection.d.ts +6 -0
  123. package/dist/model/tool-definition-projection.js +11 -0
  124. package/dist/model/tool-schema.d.ts +2 -0
  125. package/dist/model/tool-schema.js +17 -0
  126. package/dist/model/transport-test.d.ts +10 -0
  127. package/dist/model/transport-test.js +27 -0
  128. package/dist/model/usage-observer.d.ts +5 -0
  129. package/dist/model/usage.d.ts +40 -0
  130. package/dist/network/credential-runtime.d.ts +8 -0
  131. package/dist/network/credential-runtime.js +72 -0
  132. package/dist/network/credentials.d.ts +20 -0
  133. package/dist/network/credentials.js +18 -0
  134. package/dist/network/http.d.ts +20 -0
  135. package/dist/network/http.js +421 -0
  136. package/dist/network/product-user-agent.d.ts +5 -0
  137. package/dist/network/product-user-agent.js +22 -0
  138. package/dist/network/transport-error.d.ts +5 -0
  139. package/dist/network/transport-error.js +31 -0
  140. package/dist/process/contracts.d.ts +26 -0
  141. package/dist/prompts/index.d.ts +20 -0
  142. package/dist/prompts/index.js +49 -0
  143. package/dist/prompts/prompt-sections.d.ts +6 -0
  144. package/dist/prompts/prompt-sections.js +6 -0
  145. package/dist/prompts/read-context.js +152 -0
  146. package/dist/runtime/compaction/contracts.d.ts +23 -0
  147. package/dist/runtime/compaction/coordinator.js +88 -0
  148. package/dist/runtime/compaction/generate.d.ts +31 -0
  149. package/dist/runtime/compaction/generate.js +84 -0
  150. package/dist/runtime/compaction/history.d.ts +16 -0
  151. package/dist/runtime/compaction/operation.d.ts +30 -0
  152. package/dist/runtime/compaction/operation.js +131 -0
  153. package/dist/runtime/compaction/requests.d.ts +16 -0
  154. package/dist/runtime/compaction/requests.js +114 -0
  155. package/dist/runtime/compaction/retained-context.d.ts +6 -0
  156. package/dist/runtime/compaction/retained-context.js +48 -0
  157. package/dist/runtime/compaction/smart.d.ts +14 -0
  158. package/dist/runtime/compaction/smart.js +59 -0
  159. package/dist/runtime/context/contextual-blocks.d.ts +31 -0
  160. package/dist/runtime/context/contextual-blocks.js +158 -0
  161. package/dist/runtime/context/environment.d.ts +5 -0
  162. package/dist/runtime/context/gc-candidates-code.d.ts +6 -0
  163. package/dist/runtime/context/gc-candidates-code.js +102 -0
  164. package/dist/runtime/context/gc-candidates-exec.d.ts +6 -0
  165. package/dist/runtime/context/gc-candidates-exec.js +131 -0
  166. package/dist/runtime/context/gc-candidates-read-patch.d.ts +7 -0
  167. package/dist/runtime/context/gc-candidates-read-patch.js +118 -0
  168. package/dist/runtime/context/gc-candidates-subagent.d.ts +6 -0
  169. package/dist/runtime/context/gc-candidates-subagent.js +100 -0
  170. package/dist/runtime/context/gc-candidates-web.d.ts +6 -0
  171. package/dist/runtime/context/gc-candidates-web.js +58 -0
  172. package/dist/runtime/context/gc-candidates.d.ts +12 -0
  173. package/dist/runtime/context/gc-candidates.js +192 -0
  174. package/dist/runtime/context/gc-contracts.d.ts +57 -0
  175. package/dist/runtime/context/gc-economics.d.ts +48 -0
  176. package/dist/runtime/context/gc-economics.js +161 -0
  177. package/dist/runtime/context/gc-runtime.d.ts +43 -0
  178. package/dist/runtime/context/gc-tokens.d.ts +26 -0
  179. package/dist/runtime/context/gc-tokens.js +106 -0
  180. package/dist/runtime/context/gc.d.ts +7 -0
  181. package/dist/runtime/context/gc.js +552 -0
  182. package/dist/runtime/context/instructions.d.ts +37 -0
  183. package/dist/runtime/context/instructions.js +297 -0
  184. package/dist/runtime/context/normalize.d.ts +5 -0
  185. package/dist/runtime/context/projection.d.ts +23 -0
  186. package/dist/runtime/context/projection.js +284 -0
  187. package/dist/runtime/context/request-budget.d.ts +5 -0
  188. package/dist/runtime/context/request-budget.js +25 -0
  189. package/dist/runtime/context/restore.d.ts +27 -0
  190. package/dist/runtime/context/restore.js +186 -0
  191. package/dist/runtime/context/usage.d.ts +17 -0
  192. package/dist/runtime/context/usage.js +124 -0
  193. package/dist/runtime/context/world-state.d.ts +34 -0
  194. package/dist/runtime/context/world-state.js +232 -0
  195. package/dist/runtime/contracts.d.ts +29 -0
  196. package/dist/runtime/event-projection.d.ts +14 -0
  197. package/dist/runtime/event-projection.js +87 -0
  198. package/dist/runtime/events.d.ts +195 -0
  199. package/dist/runtime/execution-handle.d.ts +12 -0
  200. package/dist/runtime/execution-handle.js +1 -0
  201. package/dist/runtime/execution.d.ts +55 -0
  202. package/dist/runtime/execution.js +444 -0
  203. package/dist/runtime/model-progress.js +85 -0
  204. package/dist/runtime/resource-publication.d.ts +27 -0
  205. package/dist/runtime/resource-publication.js +60 -0
  206. package/dist/runtime/tool-round-contract.d.ts +19 -0
  207. package/dist/runtime/tool-round-contract.js +1 -0
  208. package/dist/runtime/wait.js +82 -0
  209. package/dist/sandbox/linux/bubblewrap-sandbox-executor.d.ts +1 -1
  210. package/dist/sandbox/linux/bubblewrap-sandbox-executor.js +8 -8
  211. package/dist/sdk/agent.d.ts +7 -0
  212. package/dist/sdk/agent.js +321 -0
  213. package/dist/sdk/execution-code-mode.d.ts +18 -0
  214. package/dist/sdk/execution-code-mode.js +51 -0
  215. package/dist/sdk/execution-compact-commit.d.ts +23 -0
  216. package/dist/sdk/execution-compact-commit.js +41 -0
  217. package/dist/sdk/execution-compact-extension.d.ts +12 -0
  218. package/dist/sdk/execution-compact-extension.js +46 -0
  219. package/dist/sdk/execution-compact-generation.d.ts +17 -0
  220. package/dist/sdk/execution-compact-generation.js +30 -0
  221. package/dist/sdk/execution-compaction-flight.d.ts +31 -0
  222. package/dist/sdk/execution-compaction-flight.js +50 -0
  223. package/dist/sdk/execution-compaction.d.ts +47 -0
  224. package/dist/sdk/execution-compaction.js +121 -0
  225. package/dist/sdk/execution-context-coordinator.d.ts +56 -0
  226. package/dist/sdk/execution-context-coordinator.js +102 -0
  227. package/dist/sdk/execution-input.d.ts +58 -0
  228. package/dist/sdk/execution-input.js +266 -0
  229. package/dist/sdk/execution-model-context.d.ts +52 -0
  230. package/dist/sdk/execution-model-context.js +156 -0
  231. package/dist/sdk/execution-model-lifecycle.d.ts +39 -0
  232. package/dist/sdk/execution-model-lifecycle.js +73 -0
  233. package/dist/sdk/execution-model-request.d.ts +40 -0
  234. package/dist/sdk/execution-model-request.js +45 -0
  235. package/dist/sdk/execution-round-preparation.d.ts +11 -0
  236. package/dist/sdk/execution-round-preparation.js +18 -0
  237. package/dist/sdk/execution-round-request.d.ts +30 -0
  238. package/dist/sdk/execution-round-request.js +31 -0
  239. package/dist/sdk/execution-tool-catalog.d.ts +46 -0
  240. package/dist/sdk/execution-tool-catalog.js +103 -0
  241. package/dist/sdk/execution-tool-scope.d.ts +67 -0
  242. package/dist/sdk/execution-tool-scope.js +147 -0
  243. package/dist/sdk/extension-agent-controller.d.ts +3 -0
  244. package/dist/sdk/extension-agent-controller.js +69 -0
  245. package/dist/sdk/extension-agents.d.ts +9 -0
  246. package/dist/sdk/extension-agents.js +58 -0
  247. package/dist/sdk/extension-models.d.ts +17 -0
  248. package/dist/sdk/extension-models.js +142 -0
  249. package/dist/sdk/extension-session-launch.d.ts +18 -0
  250. package/dist/sdk/extension-session-launch.js +73 -0
  251. package/dist/sdk/extension-session.d.ts +30 -0
  252. package/dist/sdk/extension-session.js +107 -0
  253. package/dist/sdk/extension-tool-runtime.d.ts +2 -0
  254. package/dist/sdk/extension-tool-runtime.js +14 -0
  255. package/dist/sdk/extension-tools.d.ts +16 -0
  256. package/dist/sdk/extension-tools.js +126 -0
  257. package/dist/sdk/model-input-projection.d.ts +4 -0
  258. package/dist/sdk/model-input-projection.js +27 -0
  259. package/dist/sdk/model-runtime.d.ts +21 -0
  260. package/dist/sdk/model-runtime.js +91 -0
  261. package/dist/sdk/native-steer.d.ts +20 -0
  262. package/dist/sdk/native-steer.js +84 -0
  263. package/dist/sdk/request-preparation.d.ts +9 -0
  264. package/dist/sdk/resource-input.d.ts +33 -0
  265. package/dist/sdk/resource-input.js +402 -0
  266. package/dist/sdk/session-catalog.d.ts +2 -0
  267. package/dist/sdk/session-catalog.js +12 -0
  268. package/dist/sdk/session-composition.d.ts +54 -0
  269. package/dist/sdk/session-composition.js +1 -0
  270. package/dist/sdk/session-execution-factory.d.ts +43 -0
  271. package/dist/sdk/session-execution-factory.js +937 -0
  272. package/dist/sdk/session-execution.d.ts +163 -0
  273. package/dist/sdk/session-execution.js +388 -0
  274. package/dist/sdk/session-extension-messages.d.ts +16 -0
  275. package/dist/sdk/session-extension-messages.js +64 -0
  276. package/dist/sdk/session-extension-prompt.d.ts +35 -0
  277. package/dist/sdk/session-extension-prompt.js +62 -0
  278. package/dist/sdk/session-maintenance.d.ts +25 -0
  279. package/dist/sdk/session-maintenance.js +205 -0
  280. package/dist/sdk/session-model-adapters.d.ts +28 -0
  281. package/dist/sdk/session-model-adapters.js +96 -0
  282. package/dist/sdk/session-open.d.ts +22 -0
  283. package/dist/sdk/session-open.js +44 -0
  284. package/dist/sdk/session-registry.d.ts +17 -0
  285. package/dist/sdk/session-registry.js +83 -0
  286. package/dist/sdk/session-runtime.d.ts +72 -0
  287. package/dist/sdk/session-runtime.js +205 -0
  288. package/dist/sdk/session.d.ts +3 -0
  289. package/dist/sdk/session.js +313 -0
  290. package/dist/sdk/subagent-backend.d.ts +3 -0
  291. package/dist/sdk/subagent-backend.js +49 -0
  292. package/dist/sdk/types.d.ts +80 -0
  293. package/dist/sdk/types.js +1 -0
  294. package/dist/session/catalog.d.ts +70 -0
  295. package/dist/session/catalog.js +194 -0
  296. package/dist/session/code-observation-contract.d.ts +40 -0
  297. package/dist/session/code-observation-contract.js +1 -0
  298. package/dist/session/code-observation-projection.d.ts +54 -0
  299. package/dist/session/code-observation-projection.js +165 -0
  300. package/dist/session/code-state.d.ts +27 -0
  301. package/dist/session/code-state.js +89 -0
  302. package/dist/session/context-gc-checkpoint.d.ts +26 -0
  303. package/dist/session/context-gc-checkpoint.js +935 -0
  304. package/dist/session/context-gc-contract.d.ts +141 -0
  305. package/dist/session/context-gc-contract.js +1 -0
  306. package/dist/session/context-gc-observations.d.ts +58 -0
  307. package/dist/session/context-gc-observations.js +187 -0
  308. package/dist/session/context-gc-replacements.d.ts +63 -0
  309. package/dist/session/context-gc-subagent.d.ts +54 -0
  310. package/dist/session/deferred-input.d.ts +5 -0
  311. package/dist/session/deferred-input.js +74 -0
  312. package/dist/session/extension-checkpoint.d.ts +8 -0
  313. package/dist/session/extension-checkpoint.js +30 -0
  314. package/dist/session/history-input-limits.d.ts +4 -0
  315. package/dist/session/history-input-limits.js +4 -0
  316. package/dist/session/inline-media-contract.d.ts +16 -0
  317. package/dist/session/inline-media-contract.js +1 -0
  318. package/dist/session/inline-media.d.ts +26 -0
  319. package/dist/session/inline-media.js +138 -0
  320. package/dist/session/model-request.d.ts +14 -0
  321. package/dist/session/model-request.js +1 -0
  322. package/dist/session/record-contract.d.ts +19 -0
  323. package/dist/session/record-contract.js +1 -0
  324. package/dist/session/record-projection.d.ts +6 -0
  325. package/dist/session/record-projection.js +80 -0
  326. package/dist/session/resource-contract.d.ts +9 -0
  327. package/dist/session/resource-contract.js +1 -0
  328. package/dist/session/rollback.d.ts +13 -0
  329. package/dist/session/rollback.js +46 -0
  330. package/dist/session/store/contracts.d.ts +160 -0
  331. package/dist/session/store/contracts.js +1 -0
  332. package/dist/session/store/current-state.d.ts +17 -0
  333. package/dist/session/store/current-state.js +53 -0
  334. package/dist/session/store/execution-state.d.ts +13 -0
  335. package/dist/session/store/execution-state.js +103 -0
  336. package/dist/session/store/index.d.ts +4 -0
  337. package/dist/session/store/index.js +2 -0
  338. package/dist/session/store/jsonl/directory-index.d.ts +26 -0
  339. package/dist/session/store/jsonl/directory-index.js +283 -0
  340. package/dist/session/store/jsonl/fs-durability.d.ts +3 -0
  341. package/dist/session/store/jsonl/fs-durability.js +17 -0
  342. package/dist/session/store/jsonl/history-replacement.d.ts +48 -0
  343. package/dist/session/store/jsonl/history-replacement.js +147 -0
  344. package/dist/session/store/jsonl/history.d.ts +25 -0
  345. package/dist/session/store/jsonl/history.js +181 -0
  346. package/dist/session/store/jsonl/images.d.ts +19 -0
  347. package/dist/session/store/jsonl/images.js +122 -0
  348. package/dist/session/store/jsonl/index-transaction.d.ts +13 -0
  349. package/dist/session/store/jsonl/index-transaction.js +87 -0
  350. package/dist/session/store/jsonl/jsonl-admission.d.ts +10 -0
  351. package/dist/session/store/jsonl/jsonl-admission.js +205 -0
  352. package/dist/session/store/jsonl/jsonl-codec.d.ts +11 -0
  353. package/dist/session/store/jsonl/jsonl-codec.js +138 -0
  354. package/dist/session/store/jsonl/jsonl-migration.d.ts +12 -0
  355. package/dist/session/store/jsonl/jsonl-migration.js +105 -0
  356. package/dist/session/store/jsonl/jsonl-store.d.ts +171 -0
  357. package/dist/session/store/jsonl/jsonl-store.js +2482 -0
  358. package/dist/session/store/jsonl/open-recovery.d.ts +13 -0
  359. package/dist/session/store/jsonl/open-recovery.js +131 -0
  360. package/dist/session/store/jsonl/read-pins.d.ts +4 -0
  361. package/dist/session/store/jsonl/read-pins.js +131 -0
  362. package/dist/session/store/jsonl/record-append.d.ts +16 -0
  363. package/dist/session/store/jsonl/record-append.js +49 -0
  364. package/dist/session/store/jsonl/records.d.ts +30 -0
  365. package/dist/session/store/jsonl/records.js +313 -0
  366. package/dist/session/store/jsonl/resources.d.ts +19 -0
  367. package/dist/session/store/jsonl/resources.js +209 -0
  368. package/dist/session/store/jsonl/store-pool.d.ts +12 -0
  369. package/dist/session/store/jsonl/store-pool.js +55 -0
  370. package/dist/session/store/jsonl/transaction-recovery.d.ts +48 -0
  371. package/dist/session/store/jsonl/transaction-recovery.js +374 -0
  372. package/dist/session/store/jsonl/tree-maintenance.d.ts +12 -0
  373. package/dist/session/store/jsonl/tree-maintenance.js +59 -0
  374. package/dist/session/store/types.d.ts +69 -0
  375. package/dist/session/store/types.js +1 -0
  376. package/dist/session/summary.d.ts +18 -0
  377. package/dist/session/summary.js +1 -0
  378. package/dist/session/todo.d.ts +11 -0
  379. package/dist/session/todo.js +30 -0
  380. package/dist/session/tool-result-resources.d.ts +27 -0
  381. package/dist/session/tool-result-resources.js +255 -0
  382. package/dist/session/types.js +1 -0
  383. package/dist/session/user-history.d.ts +17 -0
  384. package/dist/session/user-history.js +1 -0
  385. package/dist/session-store.d.ts +2 -0
  386. package/dist/session-store.js +1 -0
  387. package/dist/shared/auto-title.d.ts +3 -3
  388. package/dist/shared/auto-title.js +6 -6
  389. package/dist/shared/model-text.d.ts +8 -8
  390. package/dist/shared/model-text.js +8 -7
  391. package/dist/storage/file-lock.js +83 -0
  392. package/dist/subagent/contracts.d.ts +107 -0
  393. package/dist/subagent/contracts.js +1 -0
  394. package/dist/subagent/limits.d.ts +17 -0
  395. package/dist/subagent/limits.js +17 -0
  396. package/dist/subagent/model-update.js +81 -0
  397. package/dist/subagent/session-controller.d.ts +148 -0
  398. package/dist/subagent/session-controller.js +1761 -0
  399. package/dist/subagent/wait-targets.d.ts +10 -0
  400. package/dist/subagent/wait-targets.js +26 -0
  401. package/dist/subagent/wait.d.ts +26 -0
  402. package/dist/subagent/wait.js +73 -0
  403. package/dist/tools/agent/agent-cancel.d.ts +7 -0
  404. package/dist/tools/agent/agent-cancel.js +29 -0
  405. package/dist/tools/agent/agent-message.d.ts +7 -0
  406. package/dist/tools/agent/agent-message.js +57 -0
  407. package/dist/tools/agent/agent-start.d.ts +12 -0
  408. package/dist/tools/agent/agent-start.js +106 -0
  409. package/dist/tools/agent/agent-wait.d.ts +7 -0
  410. package/dist/tools/agent/agent-wait.js +91 -0
  411. package/dist/tools/agent/question.d.ts +7 -0
  412. package/dist/tools/agent/question.js +125 -0
  413. package/dist/tools/agent/skill.d.ts +11 -0
  414. package/dist/tools/agent/skill.js +38 -0
  415. package/dist/tools/agent/sleep.d.ts +9 -0
  416. package/dist/tools/agent/sleep.js +54 -0
  417. package/dist/tools/agent/smart-compact.d.ts +9 -0
  418. package/dist/tools/agent/smart-compact.js +23 -0
  419. package/dist/tools/agent/todo-read.d.ts +14 -0
  420. package/dist/tools/agent/todo-write.d.ts +14 -0
  421. package/dist/tools/agent/todo-write.js +66 -0
  422. package/dist/tools/agent/todo.d.ts +25 -0
  423. package/dist/tools/agent/todo.js +32 -0
  424. package/dist/tools/callers.d.ts +7 -0
  425. package/dist/tools/callers.js +39 -0
  426. package/dist/tools/code-mode/cells.d.ts +29 -0
  427. package/dist/tools/code-mode/cells.js +338 -0
  428. package/dist/tools/code-mode/dispatch.d.ts +20 -0
  429. package/dist/tools/code-mode/dispatch.js +80 -0
  430. package/dist/tools/code-mode/engine.d.ts +60 -0
  431. package/dist/tools/code-mode/engine.js +1 -0
  432. package/dist/tools/code-mode/index.d.ts +31 -0
  433. package/dist/tools/code-mode/index.js +751 -0
  434. package/dist/tools/code-mode/observations.d.ts +8 -0
  435. package/dist/tools/code-mode/observations.js +64 -0
  436. package/dist/tools/code-mode/worker.d.ts +1 -0
  437. package/dist/tools/contracts.d.ts +193 -0
  438. package/dist/tools/contracts.js +1 -0
  439. package/dist/tools/definition-projection.d.ts +1 -0
  440. package/dist/tools/definition-projection.js +1 -0
  441. package/dist/tools/execution-limits.d.ts +69 -0
  442. package/dist/tools/execution-limits.js +58 -0
  443. package/dist/tools/execution.d.ts +30 -0
  444. package/dist/tools/execution.js +191 -0
  445. package/dist/tools/local/apply-patch-parser.js +177 -0
  446. package/dist/tools/local/apply-patch.d.ts +19 -0
  447. package/dist/tools/local/apply-patch.js +489 -0
  448. package/dist/tools/local/exec.d.ts +28 -0
  449. package/dist/tools/local/exec.js +194 -0
  450. package/dist/tools/local/image-processing.js +146 -0
  451. package/dist/tools/local/read.d.ts +43 -0
  452. package/dist/tools/local/read.js +470 -0
  453. package/dist/tools/local/view-image.d.ts +15 -0
  454. package/dist/tools/local/view-image.js +317 -0
  455. package/dist/tools/mcp/catalog.js +220 -0
  456. package/dist/tools/mcp/history.d.ts +4 -0
  457. package/dist/tools/mcp/tool-search.d.ts +45 -0
  458. package/dist/tools/mcp/tool-search.js +294 -0
  459. package/dist/tools/output-projection.d.ts +18 -0
  460. package/dist/tools/output-projection.js +341 -0
  461. package/dist/tools/permission-contract.d.ts +25 -0
  462. package/dist/tools/permission-contract.js +1 -0
  463. package/dist/tools/permissions.d.ts +61 -0
  464. package/dist/tools/permissions.js +237 -0
  465. package/dist/tools/registry.d.ts +7 -0
  466. package/dist/tools/result-extension-contract.d.ts +37 -0
  467. package/dist/tools/result-extension-contract.js +32 -0
  468. package/dist/tools/result-extensions.d.ts +12 -0
  469. package/dist/tools/result-extensions.js +104 -0
  470. package/dist/tools/runtime-context.d.ts +89 -0
  471. package/dist/tools/runtime-context.js +1 -0
  472. package/dist/tools/runtime-resource-handles.js +28 -0
  473. package/dist/tools/runtime.js +77 -0
  474. package/dist/tools/scheduler.d.ts +12 -0
  475. package/dist/tools/shared/path-resolver.js +133 -0
  476. package/dist/tools/wait.d.ts +1 -0
  477. package/dist/tools/wait.js +1 -0
  478. package/package.json +15 -3
  479. package/dist/agent-core/error.d.ts +0 -15
  480. package/dist/agent-core/error.js +0 -74
  481. package/dist/agent-core/extensions/agents.d.ts +0 -79
  482. package/dist/agent-core/extensions/agents.js +0 -186
  483. package/dist/agent-core/extensions/compaction.d.ts +0 -48
  484. package/dist/agent-core/extensions/contracts.d.ts +0 -265
  485. package/dist/agent-core/extensions/data.d.ts +0 -84
  486. package/dist/agent-core/extensions/data.js +0 -83
  487. package/dist/agent-core/extensions/environment.d.ts +0 -27
  488. package/dist/agent-core/extensions/environment.js +0 -52
  489. package/dist/agent-core/extensions/files.d.ts +0 -64
  490. package/dist/agent-core/extensions/files.js +0 -26
  491. package/dist/agent-core/extensions/hooks.d.ts +0 -32
  492. package/dist/agent-core/extensions/manager.d.ts +0 -39
  493. package/dist/agent-core/extensions/manager.js +0 -458
  494. package/dist/agent-core/extensions/mcp.d.ts +0 -99
  495. package/dist/agent-core/extensions/mcp.js +0 -433
  496. package/dist/agent-core/extensions/model-request.d.ts +0 -56
  497. package/dist/agent-core/extensions/model-request.js +0 -197
  498. package/dist/agent-core/extensions/model-stream.d.ts +0 -9
  499. package/dist/agent-core/extensions/model-stream.js +0 -108
  500. package/dist/agent-core/extensions/models.d.ts +0 -43
  501. package/dist/agent-core/extensions/network.d.ts +0 -32
  502. package/dist/agent-core/extensions/network.js +0 -97
  503. package/dist/agent-core/extensions/operation.d.ts +0 -30
  504. package/dist/agent-core/extensions/processes.d.ts +0 -52
  505. package/dist/agent-core/extensions/processes.js +0 -284
  506. package/dist/agent-core/extensions/prompt-composition.d.ts +0 -24
  507. package/dist/agent-core/extensions/prompt-composition.js +0 -106
  508. package/dist/agent-core/extensions/prompt-input.d.ts +0 -23
  509. package/dist/agent-core/extensions/prompt-input.js +0 -48
  510. package/dist/agent-core/extensions/resources.d.ts +0 -27
  511. package/dist/agent-core/extensions/resources.js +0 -221
  512. package/dist/agent-core/extensions/services.d.ts +0 -31
  513. package/dist/agent-core/extensions/services.js +0 -61
  514. package/dist/agent-core/extensions/session-input.d.ts +0 -163
  515. package/dist/agent-core/extensions/session-input.js +0 -411
  516. package/dist/agent-core/extensions/session-messages.d.ts +0 -41
  517. package/dist/agent-core/extensions/session-messages.js +0 -76
  518. package/dist/agent-core/extensions/session.d.ts +0 -69
  519. package/dist/agent-core/extensions/session.js +0 -607
  520. package/dist/agent-core/extensions/settings.d.ts +0 -59
  521. package/dist/agent-core/extensions/settings.js +0 -115
  522. package/dist/agent-core/extensions/store.d.ts +0 -10
  523. package/dist/agent-core/extensions/store.js +0 -131
  524. package/dist/agent-core/extensions/tools.d.ts +0 -61
  525. package/dist/agent-core/extensions/tools.js +0 -269
  526. package/dist/agent-core/host/contracts.d.ts +0 -100
  527. package/dist/agent-core/host/contracts.js +0 -18
  528. package/dist/agent-core/host/local-agent-host.d.ts +0 -96
  529. package/dist/agent-core/host/local-agent-host.js +0 -425
  530. package/dist/agent-core/host/local-file-access.d.ts +0 -30
  531. package/dist/agent-core/host/local-file-access.js +0 -107
  532. package/dist/agent-core/host/local-network-access.d.ts +0 -6
  533. package/dist/agent-core/host/local-network-access.js +0 -101
  534. package/dist/agent-core/host/local-process-executor.d.ts +0 -29
  535. package/dist/agent-core/host/local-process-executor.js +0 -41
  536. package/dist/agent-core/host/local-session-environment.d.ts +0 -18
  537. package/dist/agent-core/host/local-shell.d.ts +0 -3
  538. package/dist/agent-core/host/network.d.ts +0 -4
  539. package/dist/agent-core/host/network.js +0 -6
  540. package/dist/agent-core/model/anthropic-messages.d.ts +0 -10
  541. package/dist/agent-core/model/anthropic-messages.js +0 -707
  542. package/dist/agent-core/model/anthropic-thinking.js +0 -33
  543. package/dist/agent-core/model/catalog-file.d.ts +0 -80
  544. package/dist/agent-core/model/catalog-file.js +0 -103
  545. package/dist/agent-core/model/configuration.d.ts +0 -127
  546. package/dist/agent-core/model/configuration.js +0 -168
  547. package/dist/agent-core/model/contracts.d.ts +0 -229
  548. package/dist/agent-core/model/http.d.ts +0 -27
  549. package/dist/agent-core/model/http.js +0 -534
  550. package/dist/agent-core/model/image.d.ts +0 -17
  551. package/dist/agent-core/model/openai-responses.d.ts +0 -77
  552. package/dist/agent-core/model/openai-responses.js +0 -2123
  553. package/dist/agent-core/model/product-user-agent.d.ts +0 -5
  554. package/dist/agent-core/model/product-user-agent.js +0 -22
  555. package/dist/agent-core/model/recovery.js +0 -80
  556. package/dist/agent-core/model/request-configuration.d.ts +0 -17
  557. package/dist/agent-core/model/request-configuration.js +0 -47
  558. package/dist/agent-core/model/runtime-credential.d.ts +0 -8
  559. package/dist/agent-core/model/runtime-credential.js +0 -72
  560. package/dist/agent-core/model/sse.js +0 -281
  561. package/dist/agent-core/model/text-blocks.js +0 -40
  562. package/dist/agent-core/model/tool-declarations.d.ts +0 -4
  563. package/dist/agent-core/model/transport-test.d.ts +0 -3
  564. package/dist/agent-core/model/transport-test.js +0 -23
  565. package/dist/agent-core/model/usage-observer.d.ts +0 -31
  566. package/dist/agent-core/prompts/index.d.ts +0 -20
  567. package/dist/agent-core/prompts/index.js +0 -49
  568. package/dist/agent-core/runtime/compaction/coordinator.js +0 -88
  569. package/dist/agent-core/runtime/compaction/generate.d.ts +0 -28
  570. package/dist/agent-core/runtime/compaction/generate.js +0 -84
  571. package/dist/agent-core/runtime/compaction/history.d.ts +0 -16
  572. package/dist/agent-core/runtime/compaction/operation.d.ts +0 -29
  573. package/dist/agent-core/runtime/compaction/operation.js +0 -131
  574. package/dist/agent-core/runtime/compaction/requests.d.ts +0 -16
  575. package/dist/agent-core/runtime/compaction/requests.js +0 -114
  576. package/dist/agent-core/runtime/compaction/retained-context.d.ts +0 -6
  577. package/dist/agent-core/runtime/compaction/retained-context.js +0 -47
  578. package/dist/agent-core/runtime/compaction/smart.d.ts +0 -14
  579. package/dist/agent-core/runtime/compaction/smart.js +0 -59
  580. package/dist/agent-core/runtime/context/contextual-blocks.d.ts +0 -30
  581. package/dist/agent-core/runtime/context/contextual-blocks.js +0 -146
  582. package/dist/agent-core/runtime/context/environment.d.ts +0 -5
  583. package/dist/agent-core/runtime/context/gc-runtime.d.ts +0 -38
  584. package/dist/agent-core/runtime/context/gc-tokens.d.ts +0 -25
  585. package/dist/agent-core/runtime/context/gc-tokens.js +0 -103
  586. package/dist/agent-core/runtime/context/gc.d.ts +0 -75
  587. package/dist/agent-core/runtime/context/gc.js +0 -1386
  588. package/dist/agent-core/runtime/context/instructions.d.ts +0 -37
  589. package/dist/agent-core/runtime/context/instructions.js +0 -297
  590. package/dist/agent-core/runtime/context/normalize.d.ts +0 -5
  591. package/dist/agent-core/runtime/context/projection.d.ts +0 -23
  592. package/dist/agent-core/runtime/context/projection.js +0 -284
  593. package/dist/agent-core/runtime/context/request-budget.d.ts +0 -4
  594. package/dist/agent-core/runtime/context/request-budget.js +0 -25
  595. package/dist/agent-core/runtime/context/restore.d.ts +0 -25
  596. package/dist/agent-core/runtime/context/restore.js +0 -186
  597. package/dist/agent-core/runtime/context/usage.d.ts +0 -17
  598. package/dist/agent-core/runtime/context/usage.js +0 -124
  599. package/dist/agent-core/runtime/context/world-state.d.ts +0 -33
  600. package/dist/agent-core/runtime/context/world-state.js +0 -232
  601. package/dist/agent-core/runtime/contracts.d.ts +0 -41
  602. package/dist/agent-core/runtime/event-projection.d.ts +0 -14
  603. package/dist/agent-core/runtime/event-projection.js +0 -87
  604. package/dist/agent-core/runtime/events.d.ts +0 -197
  605. package/dist/agent-core/runtime/execution-handle.d.ts +0 -12
  606. package/dist/agent-core/runtime/execution.d.ts +0 -50
  607. package/dist/agent-core/runtime/execution.js +0 -445
  608. package/dist/agent-core/runtime/model-progress.js +0 -85
  609. package/dist/agent-core/runtime/resource-publication.d.ts +0 -8
  610. package/dist/agent-core/runtime/resource-publication.js +0 -60
  611. package/dist/agent-core/sdk/agent.d.ts +0 -11
  612. package/dist/agent-core/sdk/agent.js +0 -474
  613. package/dist/agent-core/sdk/extension-agents.d.ts +0 -9
  614. package/dist/agent-core/sdk/extension-agents.js +0 -58
  615. package/dist/agent-core/sdk/extension-models.d.ts +0 -13
  616. package/dist/agent-core/sdk/extension-models.js +0 -137
  617. package/dist/agent-core/sdk/extension-session.d.ts +0 -30
  618. package/dist/agent-core/sdk/extension-session.js +0 -105
  619. package/dist/agent-core/sdk/extension-tools.d.ts +0 -16
  620. package/dist/agent-core/sdk/extension-tools.js +0 -126
  621. package/dist/agent-core/sdk/model-runtime.d.ts +0 -18
  622. package/dist/agent-core/sdk/model-runtime.js +0 -93
  623. package/dist/agent-core/sdk/native-steer.d.ts +0 -20
  624. package/dist/agent-core/sdk/native-steer.js +0 -84
  625. package/dist/agent-core/sdk/request-preparation.d.ts +0 -7
  626. package/dist/agent-core/sdk/resource-input.d.ts +0 -32
  627. package/dist/agent-core/sdk/resource-input.js +0 -403
  628. package/dist/agent-core/sdk/session.d.ts +0 -94
  629. package/dist/agent-core/sdk/session.js +0 -2377
  630. package/dist/agent-core/sdk/subagent-backend.d.ts +0 -3
  631. package/dist/agent-core/sdk/subagent-backend.js +0 -49
  632. package/dist/agent-core/sdk/types.d.ts +0 -81
  633. package/dist/agent-core/session/catalog.d.ts +0 -99
  634. package/dist/agent-core/session/catalog.js +0 -200
  635. package/dist/agent-core/session/context-gc-checkpoint.d.ts +0 -165
  636. package/dist/agent-core/session/context-gc-checkpoint.js +0 -935
  637. package/dist/agent-core/session/context-gc-observations.d.ts +0 -60
  638. package/dist/agent-core/session/context-gc-observations.js +0 -187
  639. package/dist/agent-core/session/context-gc-replacements.d.ts +0 -62
  640. package/dist/agent-core/session/context-gc-subagent.d.ts +0 -53
  641. package/dist/agent-core/session/deferred-input.d.ts +0 -5
  642. package/dist/agent-core/session/deferred-input.js +0 -74
  643. package/dist/agent-core/session/inline-media.d.ts +0 -45
  644. package/dist/agent-core/session/inline-media.js +0 -163
  645. package/dist/agent-core/session/rollback.d.ts +0 -13
  646. package/dist/agent-core/session/rollback.js +0 -46
  647. package/dist/agent-core/session/store/contracts.d.ts +0 -158
  648. package/dist/agent-core/session/store/current-state.d.ts +0 -17
  649. package/dist/agent-core/session/store/current-state.js +0 -53
  650. package/dist/agent-core/session/store/directory-index.d.ts +0 -18
  651. package/dist/agent-core/session/store/directory-index.js +0 -169
  652. package/dist/agent-core/session/store/execution-state.d.ts +0 -18
  653. package/dist/agent-core/session/store/execution-state.js +0 -175
  654. package/dist/agent-core/session/store/history.d.ts +0 -25
  655. package/dist/agent-core/session/store/history.js +0 -181
  656. package/dist/agent-core/session/store/images.d.ts +0 -19
  657. package/dist/agent-core/session/store/images.js +0 -110
  658. package/dist/agent-core/session/store/index.d.ts +0 -4
  659. package/dist/agent-core/session/store/index.js +0 -2
  660. package/dist/agent-core/session/store/jsonl-store.d.ts +0 -171
  661. package/dist/agent-core/session/store/jsonl-store.js +0 -2078
  662. package/dist/agent-core/session/store/records.d.ts +0 -23
  663. package/dist/agent-core/session/store/records.js +0 -261
  664. package/dist/agent-core/session/store/resources.d.ts +0 -26
  665. package/dist/agent-core/session/store/resources.js +0 -197
  666. package/dist/agent-core/session/store/types.d.ts +0 -82
  667. package/dist/agent-core/session/tool-result-resources.d.ts +0 -26
  668. package/dist/agent-core/session/tool-result-resources.js +0 -256
  669. package/dist/agent-core/session/transaction-recovery.d.ts +0 -16
  670. package/dist/agent-core/session/transaction-recovery.js +0 -135
  671. package/dist/agent-core/storage/file-lock.js +0 -83
  672. package/dist/agent-core/subagent/contracts.d.ts +0 -117
  673. package/dist/agent-core/subagent/model-update.js +0 -81
  674. package/dist/agent-core/subagent/scheduler.d.ts +0 -135
  675. package/dist/agent-core/subagent/scheduler.js +0 -369
  676. package/dist/agent-core/subagent/session-controller.d.ts +0 -138
  677. package/dist/agent-core/subagent/session-controller.js +0 -1594
  678. package/dist/agent-core/subagent/wait.d.ts +0 -14
  679. package/dist/agent-core/subagent/wait.js +0 -32
  680. package/dist/agent-core/tools/agent/agent-cancel.d.ts +0 -7
  681. package/dist/agent-core/tools/agent/agent-cancel.js +0 -29
  682. package/dist/agent-core/tools/agent/agent-message.d.ts +0 -7
  683. package/dist/agent-core/tools/agent/agent-message.js +0 -57
  684. package/dist/agent-core/tools/agent/agent-start.d.ts +0 -12
  685. package/dist/agent-core/tools/agent/agent-start.js +0 -106
  686. package/dist/agent-core/tools/agent/agent-wait.d.ts +0 -7
  687. package/dist/agent-core/tools/agent/agent-wait.js +0 -91
  688. package/dist/agent-core/tools/agent/question.d.ts +0 -7
  689. package/dist/agent-core/tools/agent/question.js +0 -125
  690. package/dist/agent-core/tools/agent/skill.d.ts +0 -11
  691. package/dist/agent-core/tools/agent/skill.js +0 -38
  692. package/dist/agent-core/tools/agent/sleep.d.ts +0 -12
  693. package/dist/agent-core/tools/agent/sleep.js +0 -54
  694. package/dist/agent-core/tools/agent/smart-compact.d.ts +0 -9
  695. package/dist/agent-core/tools/agent/smart-compact.js +0 -23
  696. package/dist/agent-core/tools/agent/todo-read.d.ts +0 -14
  697. package/dist/agent-core/tools/agent/todo-write.d.ts +0 -14
  698. package/dist/agent-core/tools/agent/todo-write.js +0 -66
  699. package/dist/agent-core/tools/agent/todo.d.ts +0 -26
  700. package/dist/agent-core/tools/agent/todo.js +0 -60
  701. package/dist/agent-core/tools/callers.d.ts +0 -6
  702. package/dist/agent-core/tools/callers.js +0 -39
  703. package/dist/agent-core/tools/code-mode/cells.d.ts +0 -29
  704. package/dist/agent-core/tools/code-mode/cells.js +0 -337
  705. package/dist/agent-core/tools/code-mode/dispatch.d.ts +0 -20
  706. package/dist/agent-core/tools/code-mode/dispatch.js +0 -80
  707. package/dist/agent-core/tools/code-mode/engine.d.ts +0 -60
  708. package/dist/agent-core/tools/code-mode/index.d.ts +0 -29
  709. package/dist/agent-core/tools/code-mode/index.js +0 -749
  710. package/dist/agent-core/tools/code-mode/observations.d.ts +0 -98
  711. package/dist/agent-core/tools/code-mode/observations.js +0 -228
  712. package/dist/agent-core/tools/code-mode/state.d.ts +0 -9
  713. package/dist/agent-core/tools/code-mode/state.js +0 -82
  714. package/dist/agent-core/tools/contracts.d.ts +0 -211
  715. package/dist/agent-core/tools/definition-projection.d.ts +0 -7
  716. package/dist/agent-core/tools/definition-projection.js +0 -26
  717. package/dist/agent-core/tools/execution-limits.d.ts +0 -69
  718. package/dist/agent-core/tools/execution-limits.js +0 -69
  719. package/dist/agent-core/tools/execution.d.ts +0 -46
  720. package/dist/agent-core/tools/execution.js +0 -191
  721. package/dist/agent-core/tools/local/apply-patch-parser.js +0 -177
  722. package/dist/agent-core/tools/local/apply-patch.d.ts +0 -19
  723. package/dist/agent-core/tools/local/apply-patch.js +0 -489
  724. package/dist/agent-core/tools/local/exec.d.ts +0 -53
  725. package/dist/agent-core/tools/local/exec.js +0 -877
  726. package/dist/agent-core/tools/local/image-processing.js +0 -146
  727. package/dist/agent-core/tools/local/read-context.js +0 -152
  728. package/dist/agent-core/tools/local/read.d.ts +0 -43
  729. package/dist/agent-core/tools/local/read.js +0 -470
  730. package/dist/agent-core/tools/local/registry.d.ts +0 -34
  731. package/dist/agent-core/tools/local/registry.js +0 -132
  732. package/dist/agent-core/tools/local/view-image.d.ts +0 -15
  733. package/dist/agent-core/tools/local/view-image.js +0 -317
  734. package/dist/agent-core/tools/local/workspace-tools.d.ts +0 -12
  735. package/dist/agent-core/tools/local/workspace-tools.js +0 -28
  736. package/dist/agent-core/tools/mcp/catalog.js +0 -220
  737. package/dist/agent-core/tools/mcp/history.d.ts +0 -4
  738. package/dist/agent-core/tools/mcp/tool-search.d.ts +0 -45
  739. package/dist/agent-core/tools/mcp/tool-search.js +0 -294
  740. package/dist/agent-core/tools/output-projection.d.ts +0 -18
  741. package/dist/agent-core/tools/output-projection.js +0 -341
  742. package/dist/agent-core/tools/permissions.d.ts +0 -85
  743. package/dist/agent-core/tools/permissions.js +0 -237
  744. package/dist/agent-core/tools/registry.d.ts +0 -7
  745. package/dist/agent-core/tools/result-extensions.d.ts +0 -46
  746. package/dist/agent-core/tools/result-extensions.js +0 -134
  747. package/dist/agent-core/tools/runtime-context.d.ts +0 -74
  748. package/dist/agent-core/tools/runtime-resource-handles.js +0 -28
  749. package/dist/agent-core/tools/runtime.js +0 -77
  750. package/dist/agent-core/tools/scheduler.d.ts +0 -12
  751. package/dist/agent-core/tools/shared/path-resolver.js +0 -133
  752. package/dist/agent-core/tools/wait.js +0 -82
  753. /package/dist/{agent-core/extensions/models.js → extensions/capabilities.js} +0 -0
  754. /package/dist/{agent-core/extensions → extensions}/compaction.js +0 -0
  755. /package/dist/{agent-core/model → extensions}/contracts.js +0 -0
  756. /package/dist/{agent-core/extensions → extensions}/hooks.js +0 -0
  757. /package/dist/{agent-core/runtime/context/contracts.js → extensions/host-ports.js} +0 -0
  758. /package/dist/{agent-core/extensions → extensions}/operation.js +0 -0
  759. /package/dist/{agent-core/runtime/contracts.js → extensions/tool-runtime.js} +0 -0
  760. /package/dist/{agent-core/extensions/contracts.js → extensions.js} +0 -0
  761. /package/dist/{agent-core/runtime/events.js → host/description.js} +0 -0
  762. /package/dist/{agent-core/host → host}/local-session-environment.js +0 -0
  763. /package/dist/{agent-core/host → host}/local-shell.js +0 -0
  764. /package/dist/{agent-core/runtime/execution-handle.js → host/skill-contract.js} +0 -0
  765. /package/dist/{agent-core/model → model}/anthropic-thinking.d.ts +0 -0
  766. /package/dist/{agent-core/model → model}/attempt-diagnostics.d.ts +0 -0
  767. /package/dist/{agent-core/model → model}/attempt-diagnostics.js +0 -0
  768. /package/dist/{agent-core/session/store → model}/contracts.js +0 -0
  769. /package/dist/{agent-core/sdk/types.js → model/image-contract.js} +0 -0
  770. /package/dist/{agent-core/model → model}/image.js +0 -0
  771. /package/dist/{agent-core/model → model}/native-context.d.ts +0 -0
  772. /package/dist/{agent-core/model → model}/native-context.js +0 -0
  773. /package/dist/{agent-core/model → model}/recovery.d.ts +0 -0
  774. /package/dist/{agent-core/model → model}/sse.d.ts +0 -0
  775. /package/dist/{agent-core/model → model}/text-blocks.d.ts +0 -0
  776. /package/dist/{agent-core/model → model}/tool-declarations.js +0 -0
  777. /package/dist/{agent-core/model → model}/tool-input.d.ts +0 -0
  778. /package/dist/{agent-core/model → model}/tool-input.js +0 -0
  779. /package/dist/{agent-core/model → model}/usage-observer.js +0 -0
  780. /package/dist/{agent-core/session/store/types.js → model/usage.js} +0 -0
  781. /package/dist/{agent-core/subagent → process}/contracts.js +0 -0
  782. /package/dist/{agent-core/prompts → prompts}/compact.d.ts +0 -0
  783. /package/dist/{agent-core/prompts → prompts}/compact.js +0 -0
  784. /package/dist/{agent-core/prompts → prompts}/core.d.ts +0 -0
  785. /package/dist/{agent-core/prompts → prompts}/core.js +0 -0
  786. /package/dist/{agent-core/prompts → prompts}/markup.d.ts +0 -0
  787. /package/dist/{agent-core/prompts → prompts}/markup.js +0 -0
  788. /package/dist/{agent-core/prompts → prompts}/modes.d.ts +0 -0
  789. /package/dist/{agent-core/prompts → prompts}/modes.js +0 -0
  790. /package/dist/{agent-core/prompts → prompts}/output.d.ts +0 -0
  791. /package/dist/{agent-core/prompts → prompts}/output.js +0 -0
  792. /package/dist/{agent-core/prompts → prompts}/permissions.d.ts +0 -0
  793. /package/dist/{agent-core/prompts → prompts}/permissions.js +0 -0
  794. /package/dist/{agent-core/tools/local → prompts}/read-context.d.ts +0 -0
  795. /package/dist/{agent-core/prompts → prompts}/resources.d.ts +0 -0
  796. /package/dist/{agent-core/prompts → prompts}/resources.js +0 -0
  797. /package/dist/{agent-core/prompts → prompts}/subagent.d.ts +0 -0
  798. /package/dist/{agent-core/prompts → prompts}/subagent.js +0 -0
  799. /package/dist/{agent-core/prompts → prompts}/workflow.d.ts +0 -0
  800. /package/dist/{agent-core/prompts → prompts}/workflow.js +0 -0
  801. /package/dist/{agent-core/runtime → runtime}/async-queue.d.ts +0 -0
  802. /package/dist/{agent-core/runtime → runtime}/async-queue.js +0 -0
  803. /package/dist/{agent-core/tools → runtime/compaction}/contracts.js +0 -0
  804. /package/dist/{agent-core/runtime → runtime}/compaction/coordinator.d.ts +0 -0
  805. /package/dist/{agent-core/runtime → runtime}/compaction/history.js +0 -0
  806. /package/dist/{agent-core/runtime → runtime}/context/contracts.d.ts +0 -0
  807. /package/dist/{agent-core/session/types.js → runtime/context/contracts.js} +0 -0
  808. /package/dist/{agent-core/runtime → runtime}/context/environment.js +0 -0
  809. /package/dist/{agent-core/tools/code-mode/engine.js → runtime/context/gc-contracts.js} +0 -0
  810. /package/dist/{agent-core/runtime → runtime}/context/gc-runtime.js +0 -0
  811. /package/dist/{agent-core/runtime → runtime}/context/normalize.js +0 -0
  812. /package/dist/{agent-core/tools/code-mode/worker.d.ts → runtime/contracts.js} +0 -0
  813. /package/dist/{agent-core/tools/runtime-context.js → runtime/events.js} +0 -0
  814. /package/dist/{agent-core/runtime → runtime}/execution-policy.d.ts +0 -0
  815. /package/dist/{agent-core/runtime → runtime}/execution-policy.js +0 -0
  816. /package/dist/{agent-core/runtime → runtime}/model-generation-timing.d.ts +0 -0
  817. /package/dist/{agent-core/runtime → runtime}/model-generation-timing.js +0 -0
  818. /package/dist/{agent-core/runtime → runtime}/model-progress.d.ts +0 -0
  819. /package/dist/{agent-core/runtime → runtime}/plan-output.d.ts +0 -0
  820. /package/dist/{agent-core/runtime → runtime}/plan-output.js +0 -0
  821. /package/dist/{agent-core/tools/public-metadata.d.ts → runtime/public-tool-metadata.d.ts} +0 -0
  822. /package/dist/{agent-core/tools/public-metadata.js → runtime/public-tool-metadata.js} +0 -0
  823. /package/dist/{agent-core/runtime → runtime}/token-budget.d.ts +0 -0
  824. /package/dist/{agent-core/runtime → runtime}/token-budget.js +0 -0
  825. /package/dist/{agent-core/tools → runtime}/wait.d.ts +0 -0
  826. /package/dist/{agent-core/sdk → sdk}/request-preparation.js +0 -0
  827. /package/dist/{agent-core/session → session}/context-gc-markup.d.ts +0 -0
  828. /package/dist/{agent-core/session → session}/context-gc-markup.js +0 -0
  829. /package/dist/{agent-core/session → session}/context-gc-replacements.js +0 -0
  830. /package/dist/{agent-core/session → session}/context-gc-subagent.js +0 -0
  831. /package/dist/{agent-core/session → session}/types.d.ts +0 -0
  832. /package/dist/{agent-core/storage → storage}/file-lock.d.ts +0 -0
  833. /package/dist/{agent-core/subagent → subagent}/model-update.d.ts +0 -0
  834. /package/dist/{agent-core/tools → tools}/agent/todo-read.js +0 -0
  835. /package/dist/{agent-core/tools → tools}/code-mode/quickjs-engine.d.ts +0 -0
  836. /package/dist/{agent-core/tools → tools}/code-mode/quickjs-engine.js +0 -0
  837. /package/dist/{agent-core/tools → tools}/code-mode/text-output.d.ts +0 -0
  838. /package/dist/{agent-core/tools → tools}/code-mode/text-output.js +0 -0
  839. /package/dist/{agent-core/tools → tools}/code-mode/worker.js +0 -0
  840. /package/dist/{agent-core/tools → tools}/file-change-diff.d.ts +0 -0
  841. /package/dist/{agent-core/tools → tools}/file-change-diff.js +0 -0
  842. /package/dist/{agent-core/tools → tools}/input-diagnostics/source-preview.d.ts +0 -0
  843. /package/dist/{agent-core/tools → tools}/input-diagnostics/source-preview.js +0 -0
  844. /package/dist/{agent-core/tools → tools}/input.d.ts +0 -0
  845. /package/dist/{agent-core/tools → tools}/input.js +0 -0
  846. /package/dist/{agent-core/tools → tools}/local/apply-patch-parser.d.ts +0 -0
  847. /package/dist/{agent-core/tools → tools}/local/image-processing.d.ts +0 -0
  848. /package/dist/{agent-core/tools → tools}/mcp/catalog.d.ts +0 -0
  849. /package/dist/{agent-core/tools → tools}/mcp/history.js +0 -0
  850. /package/dist/{agent-core/tools → tools}/registry.js +0 -0
  851. /package/dist/{agent-core/tools → tools}/runtime-resource-handles.d.ts +0 -0
  852. /package/dist/{agent-core/tools → tools}/runtime.d.ts +0 -0
  853. /package/dist/{agent-core/tools → tools}/scheduler.js +0 -0
  854. /package/dist/{agent-core/tools → tools}/shared/patch-result.d.ts +0 -0
  855. /package/dist/{agent-core/tools → tools}/shared/patch-result.js +0 -0
  856. /package/dist/{agent-core/tools → tools}/shared/path-resolver.d.ts +0 -0
@@ -1,2123 +0,0 @@
1
- import { observeModelRequestUsage } from './usage-observer.js';
2
- import { observationModelParts } from '../tools/code-mode/observations.js';
3
- import { modelImageKey, modelImageUrl } from './image.js';
4
- import { stableToolSchema } from '../tools/definition-projection.js';
5
- import { isDeepStrictEqual } from 'node:util';
6
- import { createHash, randomUUID } from 'node:crypto';
7
- import { describeMarAgentError, MarAgentError } from '../error.js';
8
- import { assertInlineMediaBudget } from '../session/inline-media.js';
9
- import { marAgentReasoningEffortSchema, resolveModelDefaultReasoningEffort, usesResponsesConfigurationUpdates } from './configuration.js';
10
- import WebSocket from 'ws';
11
- import { isRetryableUpstreamOverloadCode, number, parseSse, record, text, observeModelStreamEvent, modelStreamEventObservedAt } from './sse.js';
12
- import { connectSocks5Target, fetchModelResponse, isRetryableModelHttpStatus, isRetryableModelTransportError, modelRetryMaxAttempts, isRetryableModelRequestError, modelRetryDelay, waitForModelRetry } from './http.js';
13
- import { acquireModelCredential, appendModelCredentialHeaders, modelCredentialSensitiveValues } from './runtime-credential.js';
14
- import { resolveModelTextBlocks } from './text-blocks.js';
15
- import { jsonToolInput } from './tool-input.js';
16
- import { reportModelAttempt } from './attempt-diagnostics.js';
17
- import { productUserAgent } from './product-user-agent.js';
18
- const WEBSOCKET_IDLE_TIMEOUT_MS = 300_000;
19
- const WEBSOCKET_SEND_FRAME_BYTES = 1024 * 1024;
20
- export const OPENAI_RESPONSES_EARLY_EOF_REASON = 'OPENAI_RESPONSES_EARLY_EOF';
21
- export const OPENAI_RESPONSES_WEBSOCKET_CONNECTION_LIMIT_REASON = 'OPENAI_RESPONSES_WEBSOCKET_CONNECTION_LIMIT';
22
- const X_CODEX_TURN_STATE = 'x-codex-turn-state';
23
- export class OpenAiResponsesAdapter {
24
- #cachedState = {};
25
- #cacheLeased = false;
26
- #closed = false;
27
- #configuration;
28
- constructor(configuration) {
29
- this.#configuration = configuration;
30
- }
31
- get configuration() {
32
- return this.#configuration;
33
- }
34
- prepareReconfigure(configuration) {
35
- if (!sameResponsesAdapterConfiguration(this.#configuration, configuration))
36
- return undefined;
37
- return () => {
38
- this.#configuration = configuration;
39
- };
40
- }
41
- async *start(request, signal) {
42
- const turn = new OpenAiResponsesTurnSession(this, {}, false);
43
- try {
44
- yield* turn.start(request, signal);
45
- }
46
- finally {
47
- await turn.close();
48
- }
49
- }
50
- createTurnSession() {
51
- if (this.#closed)
52
- throw new MarAgentError('MAR_AGENT_DISPOSED', 'Model adapter is disposed.');
53
- const cacheLease = !this.#cacheLeased;
54
- const state = cacheLease ? this.#cachedState : {};
55
- if (cacheLease) {
56
- this.#cachedState = {};
57
- this.#cacheLeased = true;
58
- }
59
- return new OpenAiResponsesTurnSession(this, state, cacheLease);
60
- }
61
- async close() {
62
- if (this.#closed)
63
- return;
64
- this.#closed = true;
65
- invalidateResponsesWebSocket(this.#cachedState, true);
66
- }
67
- releaseTurnSession(state, cacheLease) {
68
- if (!cacheLease || this.#closed) {
69
- invalidateResponsesWebSocket(state, true);
70
- return;
71
- }
72
- if (state.socket !== undefined && state.socket.readyState !== WebSocket.OPEN) {
73
- invalidateResponsesWebSocket(state, false);
74
- clearResponsesContinuation(state);
75
- }
76
- this.#cachedState = state;
77
- this.#cacheLeased = false;
78
- }
79
- async *startTurn(request, signal, turn, prepared) {
80
- let useContinuation = prepared.continuation;
81
- let requestBody = prepared.body;
82
- let credentialReason = 'REQUEST';
83
- let unauthorizedRetryUsed = false;
84
- let invalidContinuationFallbackUsed = false;
85
- const retryState = request.retryState ?? { attempts: 0 };
86
- const maxAttempts = modelRetryMaxAttempts(retryState);
87
- let resetOutputTiming = false;
88
- while (retryState.attempts < maxAttempts) {
89
- if (resetOutputTiming)
90
- yield { type: 'output.reset' };
91
- resetOutputTiming = false;
92
- const attempt = retryState.attempts++;
93
- const attemptNumber = attempt + 1;
94
- const attemptStartedAt = Date.now();
95
- const attemptContinuation = useContinuation;
96
- const attemptCredentialReason = credentialReason;
97
- const attemptTransport = this.configuration.responsesTransport?.transport === 'WEBSOCKET' ? 'WEBSOCKET' : 'HTTP';
98
- const requestPrefixDiagnostic = request.onAttemptDiagnostic
99
- ? {
100
- requestInputItems: prepared.inputItemCount
101
- }
102
- : {};
103
- const prelude = [];
104
- let sawSemanticEvent = false;
105
- let firstSemanticEventType;
106
- turn.beginAttempt();
107
- await reportModelAttempt(request, {
108
- protocol: 'OPENAI_RESPONSES',
109
- transport: attemptTransport,
110
- state: 'STARTED',
111
- attempt: attemptNumber,
112
- maxAttempts,
113
- continuation: attemptContinuation,
114
- credentialReason: attemptCredentialReason,
115
- ...requestPrefixDiagnostic
116
- });
117
- try {
118
- for await (const event of observeModelRequestUsage(() => this.startAttempt(request, signal, requestBody, useContinuation, credentialReason, turn), request, this.configuration, signal)) {
119
- if (event.type.startsWith('output.')) {
120
- resetOutputTiming = true;
121
- yield event;
122
- continue;
123
- }
124
- if (!sawSemanticEvent && !isSemanticEvent(event)) {
125
- prelude.push(event);
126
- continue;
127
- }
128
- if (!sawSemanticEvent) {
129
- sawSemanticEvent = true;
130
- firstSemanticEventType = event.type;
131
- for (const pending of prelude)
132
- yield pending;
133
- prelude.length = 0;
134
- }
135
- yield event;
136
- }
137
- await reportModelAttempt(request, {
138
- protocol: 'OPENAI_RESPONSES',
139
- transport: attemptTransport,
140
- state: 'SUCCEEDED',
141
- attempt: attemptNumber,
142
- maxAttempts,
143
- continuation: attemptContinuation,
144
- credentialReason: attemptCredentialReason,
145
- ...requestPrefixDiagnostic,
146
- semanticEventObserved: sawSemanticEvent,
147
- ...(firstSemanticEventType === undefined ? {} : { firstSemanticEventType }),
148
- ...turn.connectionDiagnostic(),
149
- durationMs: Math.max(0, Date.now() - attemptStartedAt)
150
- });
151
- return;
152
- }
153
- catch (error) {
154
- const reportFailure = async (willRetry, options = {}) => reportModelAttempt(request, {
155
- protocol: 'OPENAI_RESPONSES',
156
- transport: attemptTransport,
157
- state: 'FAILED',
158
- attempt: attemptNumber,
159
- maxAttempts,
160
- continuation: attemptContinuation,
161
- credentialReason: attemptCredentialReason,
162
- ...requestPrefixDiagnostic,
163
- semanticEventObserved: sawSemanticEvent,
164
- ...(firstSemanticEventType === undefined ? {} : { firstSemanticEventType }),
165
- ...turn.connectionDiagnostic(),
166
- durationMs: Math.max(0, Date.now() - attemptStartedAt),
167
- ...openAiResponsesAttemptError(error),
168
- willRetry,
169
- ...(options.retryDelayMs === undefined ? {} : { retryDelayMs: options.retryDelayMs }),
170
- ...(options.retryReason === undefined ? {} : { retryReason: options.retryReason })
171
- });
172
- if (!signal.aborted &&
173
- !sawSemanticEvent &&
174
- useContinuation &&
175
- !invalidContinuationFallbackUsed &&
176
- isLocalContinuationReset(error)) {
177
- invalidContinuationFallbackUsed = true;
178
- useContinuation = false;
179
- requestBody = prepared.fullBody;
180
- turn.resetContinuation();
181
- turn.invalidateWebSocket();
182
- retryState.attempts = Math.max(0, retryState.attempts - 1);
183
- credentialReason = 'RECONNECT';
184
- await reportFailure(true, {
185
- retryDelayMs: 0,
186
- retryReason: 'INVALID_CONTINUATION'
187
- });
188
- continue;
189
- }
190
- if (!signal.aborted &&
191
- attemptNumber < maxAttempts &&
192
- !sawSemanticEvent &&
193
- useContinuation &&
194
- !invalidContinuationFallbackUsed &&
195
- isInvalidPreviousResponseError(error)) {
196
- invalidContinuationFallbackUsed = true;
197
- useContinuation = false;
198
- requestBody = prepared.fullBody;
199
- turn.resetContinuation();
200
- turn.invalidateWebSocket();
201
- credentialReason = 'RECONNECT';
202
- await reportFailure(true, {
203
- retryDelayMs: 0,
204
- retryReason: 'INVALID_CONTINUATION'
205
- });
206
- continue;
207
- }
208
- if (!signal.aborted &&
209
- attemptNumber < maxAttempts &&
210
- !sawSemanticEvent &&
211
- !unauthorizedRetryUsed &&
212
- this.configuration.credentialProvider !== undefined &&
213
- isModelAuthenticationFailure(error)) {
214
- const revision = credentialRevision(error);
215
- if (revision !== undefined)
216
- await this.configuration.credentialProvider.invalidate(revision);
217
- unauthorizedRetryUsed = true;
218
- credentialReason = 'UNAUTHORIZED';
219
- await reportFailure(true, {
220
- retryDelayMs: 0,
221
- retryReason: 'UNAUTHORIZED'
222
- });
223
- continue;
224
- }
225
- const willRetry = !(signal.aborted ||
226
- (sawSemanticEvent && request.retryState === undefined) ||
227
- !(isRetryableModelRequestError(error) || isOpenAiResponsesRecoverableStreamError(error)) ||
228
- attemptNumber >= maxAttempts);
229
- if (!willRetry) {
230
- await reportFailure(false);
231
- throw error;
232
- }
233
- const delayMs = modelRetryDelay(retryAfter(error), attempt);
234
- await reportFailure(true, {
235
- retryDelayMs: delayMs,
236
- retryReason: 'STREAM'
237
- });
238
- if (sawSemanticEvent) {
239
- retryState.retryDelayMs = delayMs;
240
- throw error;
241
- }
242
- credentialReason =
243
- error instanceof MarAgentError && error.details?.transport === 'WEBSOCKET'
244
- ? 'RECONNECT'
245
- : 'REQUEST';
246
- useContinuation = false;
247
- requestBody = prepared.fullBody;
248
- if (error instanceof MarAgentError && error.details?.transport === 'WEBSOCKET')
249
- turn.invalidateWebSocket();
250
- await waitForModelRetry(retryAfter(error), attempt, signal, delayMs);
251
- }
252
- }
253
- }
254
- async *startAttempt(request, signal, body, continuation, credentialReason, turn) {
255
- let latestCredentialRevision;
256
- let diagnosticSecrets = [];
257
- const fetchResponse = async (requestBody) => {
258
- const serializedBody = JSON.stringify(requestBody);
259
- return await fetchModelResponse(responsesEndpoint(this.configuration.baseUrl), async () => {
260
- const credential = await acquireResponsesCredential(this.configuration, credentialReason, signal);
261
- latestCredentialRevision = credential.revision;
262
- diagnosticSecrets = modelCredentialSensitiveValues(credential);
263
- return {
264
- request: {
265
- method: 'POST',
266
- headers: responsesHeaders(credential, request.promptCacheKey, turn.currentTurnState()),
267
- body: serializedBody,
268
- redirect: 'manual'
269
- },
270
- httpVersion: this.configuration.responsesTransport?.transport === 'HTTP'
271
- ? this.configuration.responsesTransport.httpVersion
272
- : '1.1',
273
- ...(credential.socks5Url === undefined
274
- ? {}
275
- : { socks5Url: credential.socks5Url.reveal() })
276
- };
277
- }, signal, 1);
278
- };
279
- let response;
280
- let rawEvents;
281
- try {
282
- if (this.configuration.responsesTransport?.transport === 'WEBSOCKET')
283
- rawEvents = webSocketResponseEvents({
284
- configuration: this.configuration,
285
- body,
286
- promptCacheKey: request.promptCacheKey,
287
- reason: credentialReason,
288
- signal,
289
- continuation,
290
- turn,
291
- credentialAcquired: (revision) => (latestCredentialRevision = revision)
292
- });
293
- else {
294
- response = await fetchResponse(body);
295
- turn.captureTurnState(response.headers.get(X_CODEX_TURN_STATE));
296
- rawEvents = parseOpenAiResponsesSse(response, signal, continuation, diagnosticSecrets);
297
- }
298
- }
299
- catch (error) {
300
- if (this.configuration.responsesTransport?.transport === 'WEBSOCKET')
301
- turn.invalidateWebSocket();
302
- throw withCredentialRevision(withResponsesAttemptDetails(error, continuation, this.configuration.responsesTransport?.transport), latestCredentialRevision);
303
- }
304
- let completed = false;
305
- const functionCalls = new Map();
306
- const customCalls = new Map();
307
- const textPhases = new Map();
308
- const pendingCompletedText = new Map();
309
- const emittedCompletedText = new Set();
310
- const emittedReasoning = new Set();
311
- const emittedFunctionCalls = new Set();
312
- const hostedWebCalls = new Map();
313
- try {
314
- for await (const raw of rawEvents) {
315
- const event = record(raw);
316
- const type = text(event.type) ?? 'unknown';
317
- if (type === 'response.output_item.added' &&
318
- ['reasoning', 'message', 'function_call', 'custom_tool_call'].includes(text(record(event.item).type) ?? ''))
319
- yield observeModelStreamEvent({ type: 'output.started' }, modelStreamEventObservedAt(raw));
320
- if (type === 'response.web_search_call.searching')
321
- yield observeModelStreamEvent({ type: 'output.paused' }, modelStreamEventObservedAt(raw));
322
- if (type === 'response.output_item.done') {
323
- const item = responseItem(event.item);
324
- if (item)
325
- yield observeModelStreamEvent({ type: 'response.item', provider: 'OPENAI_RESPONSES', item }, modelStreamEventObservedAt(raw));
326
- }
327
- if (type === 'response.output_item.added' && text(record(event.item).type) === 'message') {
328
- const item = record(event.item);
329
- const itemId = text(item.id);
330
- const phase = messagePhase(item.phase);
331
- if (itemId && phase)
332
- textPhases.set(itemId, phase);
333
- }
334
- else if (type === 'response.output_item.done' &&
335
- text(record(event.item).type) === 'message') {
336
- const item = record(event.item);
337
- const itemId = text(item.id) ?? text(event.item_id) ?? 'text';
338
- const phase = messagePhase(item.phase) ?? textPhases.get(itemId) ?? 'final_answer';
339
- textPhases.set(itemId, phase);
340
- const completedText = pendingCompletedText.get(itemId) ?? responseMessageText(item);
341
- if (completedText !== undefined && !emittedCompletedText.has(itemId)) {
342
- emittedCompletedText.add(itemId);
343
- pendingCompletedText.delete(itemId);
344
- yield observeModelStreamEvent({ type: 'text.completed', itemId, phase, text: completedText }, modelStreamEventObservedAt(raw));
345
- }
346
- }
347
- else if (type === 'response.output_item.added' &&
348
- text(record(event.item).type) === 'function_call') {
349
- const item = record(event.item);
350
- const itemId = text(item.id);
351
- if (itemId)
352
- functionCalls.set(itemId, {
353
- callId: text(item.call_id) ?? itemId,
354
- name: text(item.name) ?? 'unknown'
355
- });
356
- }
357
- else if (type === 'response.output_item.added' &&
358
- text(record(event.item).type) === 'custom_tool_call') {
359
- const item = record(event.item);
360
- const itemId = text(item.id);
361
- if (itemId)
362
- customCalls.set(itemId, {
363
- callId: text(item.call_id) ?? itemId,
364
- name: text(item.name) ?? 'unknown',
365
- input: text(item.input) ?? ''
366
- });
367
- }
368
- else if ((type === 'response.output_item.added' || type === 'response.output_item.done') &&
369
- text(record(event.item).type) === 'reasoning') {
370
- // Native reasoning context is retained above; its lifecycle is not visible output.
371
- continue;
372
- }
373
- else if (type === 'response.custom_tool_call_input.delta') {
374
- const itemId = text(event.item_id) ?? '';
375
- const known = customCalls.get(itemId);
376
- const delta = text(event.delta) ?? '';
377
- if (known)
378
- known.input += delta;
379
- if (delta.length > 0)
380
- yield observeModelStreamEvent({ type: 'output.delta' }, modelStreamEventObservedAt(raw));
381
- }
382
- else if (type === 'response.function_call_arguments.delta' ||
383
- type === 'response.reasoning_text.delta' ||
384
- type === 'response.reasoning_summary_text.delta') {
385
- if ((text(event.delta)?.length ?? 0) > 0)
386
- yield observeModelStreamEvent({ type: 'output.delta' }, modelStreamEventObservedAt(raw));
387
- }
388
- else if (type === 'response.created')
389
- yield observeModelStreamEvent({
390
- type: 'response.started',
391
- responseId: responseEventId(event) ?? 'unknown',
392
- ...(text(record(event.response).model)
393
- ? { modelId: text(record(event.response).model) }
394
- : {})
395
- }, modelStreamEventObservedAt(raw));
396
- else if (type === 'response.output_text.delta')
397
- yield observeModelStreamEvent({
398
- type: 'text.delta',
399
- itemId: text(event.item_id) ?? 'text',
400
- phase: messagePhase(event.phase) ??
401
- textPhases.get(text(event.item_id) ?? '') ??
402
- 'commentary',
403
- delta: text(event.delta) ?? ''
404
- }, modelStreamEventObservedAt(raw));
405
- else if (type === 'response.output_text.done') {
406
- const itemId = text(event.item_id) ?? 'text';
407
- const completedText = text(event.text) ?? '';
408
- const phase = messagePhase(event.phase) ?? textPhases.get(itemId);
409
- if (emittedCompletedText.has(itemId))
410
- continue;
411
- if (phase) {
412
- emittedCompletedText.add(itemId);
413
- yield observeModelStreamEvent({ type: 'text.completed', itemId, phase, text: completedText }, modelStreamEventObservedAt(raw));
414
- }
415
- else
416
- pendingCompletedText.set(itemId, completedText);
417
- }
418
- else if (type === 'response.reasoning_summary_text.done') {
419
- const itemId = JSON.stringify([
420
- text(event.item_id) ?? `reasoning-${event.output_index ?? 0}`,
421
- event.summary_index ?? 0
422
- ]);
423
- const summary = text(event.text) ?? '';
424
- if (!summary.trim() || emittedReasoning.has(itemId))
425
- continue;
426
- emittedReasoning.add(itemId);
427
- yield observeModelStreamEvent({
428
- type: 'reasoning.completed',
429
- itemId,
430
- representation: 'summary',
431
- text: summary
432
- }, modelStreamEventObservedAt(raw));
433
- }
434
- else if (type === 'response.output_item.done' &&
435
- text(record(event.item).type) === 'tool_search_call') {
436
- const item = record(event.item);
437
- const callId = text(item.call_id) ?? text(item.id) ?? 'unknown';
438
- let arguments_ = item.arguments ?? {};
439
- let argumentError;
440
- if (typeof arguments_ === 'string')
441
- try {
442
- arguments_ = JSON.parse(arguments_);
443
- }
444
- catch {
445
- argumentError = 'Tool Search arguments are invalid JSON.';
446
- }
447
- if (!emittedFunctionCalls.has(callId)) {
448
- emittedFunctionCalls.add(callId);
449
- yield observeModelStreamEvent({
450
- type: 'client_tool.call',
451
- callId,
452
- name: 'tool_search',
453
- arguments: arguments_,
454
- ...(argumentError ? { argumentError } : {})
455
- }, modelStreamEventObservedAt(raw));
456
- }
457
- }
458
- else if (type === 'response.function_call_arguments.done' ||
459
- (type === 'response.output_item.done' &&
460
- text(record(event.item).type) === 'function_call')) {
461
- const item = record(event.item);
462
- const known = functionCalls.get(text(event.item_id) ?? text(item.id) ?? '');
463
- let args = {};
464
- let argumentError;
465
- try {
466
- args = JSON.parse(text(event.arguments) ?? text(item.arguments) ?? '{}');
467
- }
468
- catch {
469
- argumentError = 'Function arguments are invalid JSON.';
470
- }
471
- const callId = text(event.call_id) ??
472
- text(item.call_id) ??
473
- known?.callId ??
474
- text(event.item_id) ??
475
- text(item.id) ??
476
- 'unknown';
477
- if (!emittedFunctionCalls.has(callId)) {
478
- emittedFunctionCalls.add(callId);
479
- yield observeModelStreamEvent({
480
- type: 'client_tool.call',
481
- callId,
482
- name: text(event.name) ?? text(item.name) ?? known?.name ?? 'unknown',
483
- arguments: args,
484
- ...(argumentError ? { argumentError } : {})
485
- }, modelStreamEventObservedAt(raw));
486
- }
487
- }
488
- else if (type === 'response.custom_tool_call_input.done' ||
489
- (type === 'response.output_item.done' &&
490
- text(record(event.item).type) === 'custom_tool_call')) {
491
- const item = record(event.item);
492
- const itemId = text(event.item_id) ?? text(item.id) ?? '';
493
- const known = customCalls.get(itemId);
494
- const callId = text(event.call_id) ?? text(item.call_id) ?? known?.callId ?? itemId;
495
- if (!emittedFunctionCalls.has(callId)) {
496
- emittedFunctionCalls.add(callId);
497
- yield observeModelStreamEvent({
498
- type: 'client_tool.call',
499
- callId,
500
- name: text(event.name) ?? text(item.name) ?? known?.name ?? 'unknown',
501
- arguments: text(event.input) ?? text(item.input) ?? known?.input ?? '',
502
- inputMode: 'freeform'
503
- }, modelStreamEventObservedAt(raw));
504
- }
505
- }
506
- else if (type.includes('web_search_call') ||
507
- text(record(event.item).type) === 'web_search_call') {
508
- const item = record(event.item);
509
- const itemId = text(event.item_id) ?? text(item.id) ?? 'web';
510
- const previous = hostedWebCalls.get(itemId);
511
- const action = record(Object.keys(record(event.action)).length ? event.action : item.action);
512
- const actionType = text(action.type);
513
- const kind = actionType === 'open_page' || actionType === 'find_in_page'
514
- ? 'WEB_FETCH'
515
- : (previous?.kind ?? 'WEB_SEARCH');
516
- const summary = { ...previous?.summary, ...hostedWebActionSummary(action) };
517
- const projected = hostedWebActionInput(action);
518
- const input = { ...previous?.input, ...projected.input };
519
- const truncated = previous?.truncated === true || projected.truncated;
520
- hostedWebCalls.set(itemId, { kind, summary, input, truncated });
521
- const output = {
522
- ...(summary.title === undefined ? {} : { title: summary.title }),
523
- ...(summary.sources === undefined ? {} : { sources: summary.sources }),
524
- ...(summary.sourcesTruncated === undefined
525
- ? {}
526
- : { sourcesTruncated: summary.sourcesTruncated })
527
- };
528
- yield observeModelStreamEvent({
529
- type: 'hosted_tool',
530
- itemId,
531
- kind,
532
- toolName: 'web_search',
533
- ...(Object.keys(input).length ? { input } : {}),
534
- ...(Object.keys(output).length ? { output } : {}),
535
- ...(truncated || summary.sourcesTruncated === true ? { truncated: true } : {}),
536
- status: type.endsWith('.failed')
537
- ? 'FAILED'
538
- : type.endsWith('.completed') || type === 'response.output_item.done'
539
- ? 'COMPLETED'
540
- : 'RUNNING',
541
- summary
542
- }, modelStreamEventObservedAt(raw));
543
- }
544
- else if (type === 'response.output_text.annotation.added') {
545
- const annotation = record(event.annotation);
546
- const url = text(annotation.url);
547
- if (url)
548
- yield observeModelStreamEvent({
549
- type: 'citation',
550
- citation: {
551
- id: text(annotation.id) ??
552
- `${text(event.item_id) ?? 'text'}-${number(event.annotation_index) ?? 0}`,
553
- url,
554
- ...(text(annotation.title) ? { title: text(annotation.title) } : {})
555
- }
556
- }, modelStreamEventObservedAt(raw));
557
- }
558
- else if (type === 'response.completed' || type === 'response.incomplete') {
559
- yield observeModelStreamEvent({ type: 'output.completed' }, modelStreamEventObservedAt(raw));
560
- const responseData = record(event.response);
561
- if (type === 'response.completed')
562
- turn.captureCompletedResponseId(responseEventId(event));
563
- for (const [itemId, completedText] of pendingCompletedText) {
564
- if (emittedCompletedText.has(itemId))
565
- continue;
566
- emittedCompletedText.add(itemId);
567
- yield observeModelStreamEvent({
568
- type: 'text.completed',
569
- itemId,
570
- phase: textPhases.get(itemId) ?? 'final_answer',
571
- text: completedText
572
- }, modelStreamEventObservedAt(raw));
573
- }
574
- pendingCompletedText.clear();
575
- for (const citation of responseCitations(responseData))
576
- yield observeModelStreamEvent({ type: 'citation', citation }, modelStreamEventObservedAt(raw));
577
- const usage = record(responseData.usage);
578
- const inputDetails = record(usage.input_tokens_details);
579
- const rolloutBudgetUnits = optionalRolloutBudgetUnits(usage.codex_rollout_budget_units);
580
- yield observeModelStreamEvent({
581
- type: 'usage',
582
- final: true,
583
- usage: {
584
- inputTokens: number(usage.input_tokens),
585
- totalInputTokens: number(usage.input_tokens),
586
- reasoningTokens: number(record(usage.output_tokens_details).reasoning_tokens),
587
- contextInputTokens: number(usage.input_tokens),
588
- outputTokens: number(usage.output_tokens),
589
- cacheReadTokens: number(inputDetails.cached_tokens),
590
- cacheWriteTokens: number(inputDetails.cache_write_tokens),
591
- ...(rolloutBudgetUnits === undefined ? {} : { rolloutBudgetUnits })
592
- }
593
- }, modelStreamEventObservedAt(raw));
594
- yield observeModelStreamEvent({
595
- type: 'completed',
596
- reason: type === 'response.incomplete' ? 'max_output' : 'completed'
597
- }, modelStreamEventObservedAt(raw));
598
- completed = true;
599
- }
600
- else if (type === 'error' ||
601
- type === 'response.failed' ||
602
- (event.type === undefined && event.error !== undefined)) {
603
- const topLevel = record(event.error);
604
- const nested = record(record(event.response).error);
605
- const code = boundedError(text(event.code) ??
606
- text(topLevel.code) ??
607
- text(topLevel.type) ??
608
- text(nested.code) ??
609
- text(nested.type), 80);
610
- const message = boundedError(text(event.message) ??
611
- text(topLevel.message) ??
612
- text(nested.message) ??
613
- text(event.error), 1_000);
614
- const status = upstreamHttpStatus(event.status, topLevel.status, record(event.response).status, nested.status);
615
- const connectionLimit = this.configuration.responsesTransport?.transport === 'WEBSOCKET' &&
616
- isWebSocketConnectionLimitCode(code);
617
- const retryable = connectionLimit || isRetryableResponsesUpstreamError(code, message);
618
- throw new MarAgentError(code ?? 'MAR_AGENT_MODEL_PROTOCOL_ERROR', message ?? 'OpenAI Responses request failed.', {
619
- details: {
620
- ...(status === undefined ? {} : { status }),
621
- ...(connectionLimit
622
- ? { reason: OPENAI_RESPONSES_WEBSOCKET_CONNECTION_LIMIT_REASON }
623
- : {}),
624
- ...(retryable ? { retryAfter: response?.headers.get('retry-after') ?? null } : {}),
625
- continuation,
626
- ...(this.configuration.responsesTransport?.transport === 'WEBSOCKET'
627
- ? { transport: 'WEBSOCKET' }
628
- : {})
629
- },
630
- ...(retryable ? { retryable: true } : {})
631
- });
632
- }
633
- else if (!isNonSemanticOpenAiResponsesEvent(type))
634
- yield observeModelStreamEvent({ type: 'unknown', nativeType: type }, modelStreamEventObservedAt(raw));
635
- }
636
- }
637
- catch (error) {
638
- if (this.configuration.responsesTransport?.transport === 'WEBSOCKET')
639
- turn.invalidateWebSocket();
640
- throw withCredentialRevision(withResponsesAttemptDetails(error, continuation, this.configuration.responsesTransport?.transport), latestCredentialRevision);
641
- }
642
- if (!completed)
643
- throw new MarAgentError('MAR_AGENT_MODEL_PROTOCOL_ERROR', 'OpenAI Responses stream ended without a terminal event.', {
644
- details: {
645
- reason: OPENAI_RESPONSES_EARLY_EOF_REASON,
646
- retryAfter: response?.headers.get('retry-after') ?? null,
647
- continuation,
648
- ...(this.configuration.responsesTransport?.transport === 'WEBSOCKET'
649
- ? { transport: 'WEBSOCKET' }
650
- : {})
651
- },
652
- retryable: true
653
- });
654
- }
655
- }
656
- function sameResponsesAdapterConfiguration(current, next) {
657
- const { apiKey: currentApiKey, credentialProvider: currentCredentialProvider, ...currentTransport } = current;
658
- const { apiKey: nextApiKey, credentialProvider: nextCredentialProvider, ...nextTransport } = next;
659
- const credentialsAreRebindable = (currentCredentialProvider !== undefined && nextCredentialProvider !== undefined) ||
660
- (currentApiKey !== undefined &&
661
- nextApiKey !== undefined &&
662
- currentApiKey.reveal() === nextApiKey.reveal());
663
- return credentialsAreRebindable && isDeepStrictEqual(currentTransport, nextTransport);
664
- }
665
- class OpenAiResponsesTurnSession {
666
- adapter;
667
- state;
668
- cacheLease;
669
- #active = false;
670
- #closed = false;
671
- #turnState;
672
- #completedResponseId;
673
- #connectionDiagnostic;
674
- #webSocketDiagnostic;
675
- constructor(adapter, state, cacheLease) {
676
- this.adapter = adapter;
677
- this.state = state;
678
- this.cacheLease = cacheLease;
679
- }
680
- async *start(request, signal) {
681
- if (this.#closed)
682
- throw new MarAgentError('MAR_AGENT_DISPOSED', 'Model turn session is disposed.');
683
- if (this.#active)
684
- throw new MarAgentError('MAR_AGENT_MODEL_PROTOCOL_ERROR', 'Model turn session already has an active request.');
685
- this.#active = true;
686
- let responseId;
687
- const outputItems = [];
688
- let completed = false;
689
- let sawUnrepresentedOutput = false;
690
- let outputMessageCount = 0;
691
- try {
692
- const prepared = this.prepareRequest(request);
693
- this.#completedResponseId = undefined;
694
- for await (const event of this.adapter.startTurn(request, signal, this, prepared)) {
695
- if (event.type === 'response.item' ||
696
- event.type === 'text.completed' ||
697
- event.type === 'client_tool.call')
698
- outputMessageCount++;
699
- if (event.type === 'response.started' && event.responseId !== 'unknown')
700
- responseId = event.responseId;
701
- else if (event.type === 'response.item')
702
- outputItems.push(JSON.parse(JSON.stringify(event.item)));
703
- else if (event.type === 'text.delta' ||
704
- event.type === 'output.delta' ||
705
- event.type === 'text.completed' ||
706
- event.type === 'reasoning.completed' ||
707
- event.type === 'client_tool.call' ||
708
- event.type === 'hosted_tool' ||
709
- event.type === 'citation' ||
710
- event.type === 'unknown')
711
- sawUnrepresentedOutput = true;
712
- else if (event.type === 'completed')
713
- completed = event.reason === 'completed' || event.reason === 'tool_use';
714
- yield event;
715
- }
716
- responseId = this.#completedResponseId ?? responseId;
717
- if (responsesContinuationEnabled(this.adapter.configuration) &&
718
- completed &&
719
- responseId !== undefined &&
720
- (outputItems.length > 0 || !sawUnrepresentedOutput)) {
721
- this.state.lastRequest =
722
- this.adapter.configuration.responsesTransport?.transport === 'WEBSOCKET'
723
- ? { ...prepared.body, input: [] }
724
- : prepared.fullBody;
725
- this.state.lastMessageCount = request.messages.length + outputMessageCount;
726
- this.state.lastInputItemCount = prepared.inputItemCount;
727
- this.state.lastSystem = JSON.stringify([request.system, request.systemBlocks]);
728
- this.state.lastResponse = { responseId, outputItems };
729
- }
730
- else
731
- clearResponsesContinuation(this.state);
732
- }
733
- catch (error) {
734
- clearResponsesContinuation(this.state);
735
- throw error;
736
- }
737
- finally {
738
- this.#completedResponseId = undefined;
739
- this.#active = false;
740
- }
741
- }
742
- async close() {
743
- if (this.#closed)
744
- return;
745
- this.#closed = true;
746
- this.adapter.releaseTurnSession(this.state, this.cacheLease);
747
- }
748
- resetContinuation() {
749
- clearResponsesContinuation(this.state);
750
- }
751
- continuationInputCount() {
752
- return this.state.lastMessageCount ?? 0;
753
- }
754
- commitContinuationInput(messageCount) {
755
- if (this.state.lastResponse !== undefined)
756
- this.state.lastMessageCount = messageCount;
757
- }
758
- captureCompletedResponseId(responseId) {
759
- if (responseId !== undefined)
760
- this.#completedResponseId = responseId;
761
- }
762
- prepareRequest(request) {
763
- assertInlineMediaBudget(request);
764
- if (this.adapter.configuration.responsesTransport?.transport === 'WEBSOCKET' &&
765
- this.state.socket !== undefined &&
766
- this.state.socket.readyState !== WebSocket.OPEN) {
767
- invalidateResponsesWebSocket(this.state, false);
768
- clearResponsesContinuation(this.state);
769
- }
770
- // The continuation baseline must not share mutable schemas or items with callers.
771
- const snapshot = (body) => JSON.parse(JSON.stringify(body));
772
- let full;
773
- const fullBody = () => (full ??= snapshot(responsesRequestBody(this.adapter.configuration, request, request.messages)));
774
- if (responsesContinuationEnabled(this.adapter.configuration)) {
775
- const websocket = this.adapter.configuration.responsesTransport?.transport === 'WEBSOCKET';
776
- const suffixMessages = websocket && this.state.lastMessageCount !== undefined
777
- ? request.messages.slice(this.state.lastMessageCount)
778
- : undefined;
779
- const suffixBody = websocket &&
780
- this.state.lastResponse !== undefined &&
781
- suffixMessages !== undefined &&
782
- this.state.lastRequest !== undefined &&
783
- this.state.lastSystem === JSON.stringify([request.system, request.systemBlocks]) &&
784
- // Top-level images attach to the last real user, which must be in this suffix.
785
- (!request.images?.length || suffixMessages.some(isRealUserMessage))
786
- ? snapshot(responsesRequestBody(this.adapter.configuration, { ...request, system: '', systemBlocks: [] }, suffixMessages, this.state.lastResponse.outputItems))
787
- : undefined;
788
- const incremental = websocket
789
- ? suffixBody !== undefined &&
790
- responsesContinuationPropertiesMatch(this.state.lastRequest, suffixBody)
791
- ? suffixBody.input
792
- : undefined
793
- : incrementalResponsesInput(this.state, fullBody());
794
- if (incremental !== undefined) {
795
- const responseId = this.state.lastResponse.responseId;
796
- const inputItemCount = websocket
797
- ? (this.state.lastInputItemCount ?? 0) +
798
- this.state.lastResponse.outputItems.length +
799
- incremental.length
800
- : fullBody().input.length;
801
- delete this.state.lastResponse;
802
- return {
803
- get fullBody() {
804
- return fullBody();
805
- },
806
- inputItemCount,
807
- body: {
808
- ...(suffixBody ?? fullBody()),
809
- input: incremental,
810
- previous_response_id: responseId
811
- },
812
- continuation: true
813
- };
814
- }
815
- }
816
- return {
817
- fullBody: fullBody(),
818
- inputItemCount: fullBody().input.length,
819
- body: fullBody(),
820
- continuation: false
821
- };
822
- }
823
- currentTurnState() {
824
- return this.#turnState;
825
- }
826
- beginAttempt() {
827
- this.#connectionDiagnostic = undefined;
828
- this.#webSocketDiagnostic = undefined;
829
- }
830
- captureWebSocketDiagnostic(diagnostic) {
831
- this.#webSocketDiagnostic = diagnostic;
832
- }
833
- connectionDiagnostic() {
834
- return { ...this.#connectionDiagnostic, ...this.#webSocketDiagnostic };
835
- }
836
- captureTurnState(value) {
837
- if (this.#turnState !== undefined || typeof value !== 'string')
838
- return;
839
- const bounded = boundedError(value.trim(), 8_192);
840
- if (bounded)
841
- this.#turnState = bounded;
842
- }
843
- withTurnStateMetadata(body) {
844
- if (this.#turnState === undefined)
845
- return body;
846
- return {
847
- ...body,
848
- client_metadata: {
849
- ...record(body.client_metadata),
850
- [X_CODEX_TURN_STATE]: this.#turnState
851
- }
852
- };
853
- }
854
- invalidateWebSocket() {
855
- invalidateResponsesWebSocket(this.state, true);
856
- }
857
- async webSocketForRequest(input) {
858
- const endpoint = webSocketEndpoint(input.configuration.baseUrl);
859
- const existingSocket = this.state.socket;
860
- if (existingSocket !== undefined &&
861
- (existingSocket.readyState !== WebSocket.OPEN || this.state.endpoint !== endpoint)) {
862
- invalidateResponsesWebSocket(this.state, false);
863
- if (input.continuation) {
864
- clearResponsesContinuation(this.state);
865
- throw localContinuationReset();
866
- }
867
- }
868
- if (input.continuation && this.state.socket === undefined) {
869
- clearResponsesContinuation(this.state);
870
- throw localContinuationReset();
871
- }
872
- if (this.state.socket === undefined) {
873
- const handshakeCredential = await acquireResponsesCredential(input.configuration, input.reason, input.signal);
874
- input.credentialAcquired(handshakeCredential.revision);
875
- await this.connectWebSocket(endpoint, handshakeCredential, input.promptCacheKey, input.signal);
876
- }
877
- const requestCredential = await acquireResponsesCredential(input.configuration, input.reason, input.signal);
878
- input.credentialAcquired(requestCredential.revision);
879
- if (requestCredential.revision !== this.state.credentialRevision ||
880
- responsesCredentialFingerprint(requestCredential) !== this.state.credentialFingerprint) {
881
- invalidateResponsesWebSocket(this.state, false);
882
- if (input.continuation) {
883
- clearResponsesContinuation(this.state);
884
- throw localContinuationReset();
885
- }
886
- await this.connectWebSocket(endpoint, requestCredential, input.promptCacheKey, input.signal);
887
- }
888
- if (input.signal.aborted) {
889
- invalidateResponsesWebSocket(this.state, true);
890
- throw input.signal.reason;
891
- }
892
- const socket = this.state.socket;
893
- if (socket?.readyState !== WebSocket.OPEN) {
894
- invalidateResponsesWebSocket(this.state, true);
895
- throw new MarAgentError('MAR_AGENT_MODEL_CONNECTION_FAILED', 'OpenAI Responses WebSocket connection is unavailable.', {
896
- details: {
897
- transport: 'WEBSOCKET',
898
- continuation: input.continuation,
899
- reason: 'MODEL_TRANSPORT_FAILURE'
900
- },
901
- retryable: true
902
- });
903
- }
904
- if (this.#connectionDiagnostic === undefined &&
905
- this.state.connectionId !== undefined &&
906
- this.state.proxyType !== undefined)
907
- this.#connectionDiagnostic = {
908
- connectionId: this.state.connectionId,
909
- connectionReused: true,
910
- proxyType: this.state.proxyType
911
- };
912
- return socket;
913
- }
914
- async connectWebSocket(endpoint, credential, promptCacheKey, signal) {
915
- const parsedEndpoint = new URL(endpoint);
916
- const connectionId = randomUUID();
917
- const proxyType = credential.socks5Url === undefined ? 'DIRECT' : 'SOCKS5';
918
- this.#connectionDiagnostic = { connectionId, connectionReused: false, proxyType };
919
- const socket = new WebSocket(parsedEndpoint, {
920
- headers: Object.fromEntries(webSocketHeaders(credential, promptCacheKey)),
921
- perMessageDeflate: false,
922
- maxPayload: 16 * 1024 * 1024,
923
- handshakeTimeout: 30_000,
924
- ...(credential.socks5Url === undefined
925
- ? {}
926
- : {
927
- createConnection: socks5WebSocketConnection(credential.socks5Url.reveal(), parsedEndpoint, signal)
928
- })
929
- });
930
- try {
931
- await waitForWebSocketOpen(socket, signal);
932
- }
933
- catch (error) {
934
- terminateWebSocket(socket);
935
- throw error;
936
- }
937
- this.state.socket = socket;
938
- this.state.endpoint = endpoint;
939
- this.state.credentialRevision = credential.revision;
940
- this.state.credentialFingerprint = responsesCredentialFingerprint(credential);
941
- this.state.connectionId = connectionId;
942
- this.state.proxyType = proxyType;
943
- }
944
- }
945
- function localContinuationReset() {
946
- return new MarAgentError('MAR_AGENT_RESPONSES_CONTINUATION_RESET', 'The Responses connection changed before the incremental request was sent.');
947
- }
948
- function isLocalContinuationReset(error) {
949
- return error instanceof MarAgentError && error.code === 'MAR_AGENT_RESPONSES_CONTINUATION_RESET';
950
- }
951
- function responsesRequestBody(configuration, request, messages, previousOutputItems = []) {
952
- const systemBlocks = resolveModelTextBlocks(request.system, request.systemBlocks ?? []);
953
- if ((request.systemBlocks !== undefined && systemBlocks.some((block) => block.cache)) ||
954
- messages.some((message) => message.textBlocks !== undefined &&
955
- resolveModelTextBlocks(message.content, message.textBlocks).some((block) => block.cache)))
956
- throw new MarAgentError('MAR_AGENT_MODEL_CAPABILITY_UNAVAILABLE', 'This model protocol does not support explicit text-block cache markers.');
957
- const tools = request.allowTools === false
958
- ? []
959
- : request.tools.map((tool) => tool.nativeType === 'tool_search' &&
960
- configuration.responsesOptionalParameters?.nativeTools !== false
961
- ? {
962
- type: 'tool_search',
963
- execution: 'client',
964
- description: tool.description,
965
- parameters: stableToolSchema(strictFunctionSchema(stableToolSchema(tool.inputSchema)))
966
- }
967
- : responsesFunctionTool(tool, configuration.responsesOptionalParameters?.nativeTools !== false));
968
- if (configuration.responsesToolNamespace && tools.length > 0) {
969
- const native = tools.filter((tool) => record(tool).type === 'tool_search');
970
- const nested = tools.filter((tool) => record(tool).type !== 'tool_search');
971
- tools.splice(0, tools.length, ...native);
972
- if (nested.length)
973
- tools.push({
974
- type: 'namespace',
975
- name: configuration.responsesToolNamespace,
976
- description: 'Client-side agent tools.',
977
- tools: nested
978
- });
979
- }
980
- if (request.allowTools !== false &&
981
- request.allowHostedTools !== false &&
982
- configuration.hostedWebSearch)
983
- tools.push({ type: 'web_search' });
984
- const toolChoice = request.toolChoice ?? 'auto';
985
- const input = openAiInput(messages, request.images, configuration.id, true, usesResponsesConfigurationUpdates(configuration), configuration.responsesOptionalParameters?.nativeTools !== false, request.tools, previousOutputItems);
986
- const systemInput = responsesSystemInput(request, systemBlocks);
987
- if (systemInput !== undefined)
988
- input.unshift(systemInput);
989
- return {
990
- model: configuration.modelId,
991
- ...(request.outputLimit === undefined
992
- ? {}
993
- : {
994
- max_output_tokens: Math.min(request.outputLimit, configuration.maxOutputTokens)
995
- }),
996
- ...(configuration.serviceTier !== undefined
997
- ? { service_tier: configuration.serviceTier }
998
- : configuration.fastMode === true
999
- ? { service_tier: 'priority' }
1000
- : {}),
1001
- tools,
1002
- ...(tools.length > 0 ? { tool_choice: toolChoice, parallel_tool_calls: true } : {}),
1003
- input,
1004
- stream: true,
1005
- store: configuration.responsesPreviousResponseId === true &&
1006
- configuration.responsesTransport?.transport !== 'WEBSOCKET',
1007
- ...(configuration.responsesOptionalParameters?.textVerbosity === false
1008
- ? {}
1009
- : { text: { verbosity: 'low' } }),
1010
- include: [
1011
- 'reasoning.encrypted_content',
1012
- ...(configuration.hostedWebSearch &&
1013
- request.allowTools !== false &&
1014
- request.allowHostedTools !== false &&
1015
- toolChoice !== 'none'
1016
- ? ['web_search_call.action.sources']
1017
- : [])
1018
- ],
1019
- ...(request.promptCacheKey &&
1020
- configuration.responsesOptionalParameters?.promptCacheKey !== false
1021
- ? { prompt_cache_key: request.promptCacheKey }
1022
- : {}),
1023
- ...(configuration.responsesOptionalParameters?.reasoningEffort === false &&
1024
- configuration.responsesOptionalParameters?.reasoningSummary === false
1025
- ? {}
1026
- : {
1027
- reasoning: {
1028
- ...(configuration.responsesOptionalParameters?.reasoningEffort === false
1029
- ? {}
1030
- : {
1031
- effort: request.requestReasoningEffort?.trim() ||
1032
- request.reasoningEffort?.trim() ||
1033
- resolveModelDefaultReasoningEffort(configuration)
1034
- }),
1035
- ...(configuration.responsesOptionalParameters?.reasoningSummary === false
1036
- ? {}
1037
- : { summary: 'auto' })
1038
- }
1039
- })
1040
- };
1041
- }
1042
- function responsesSystemInput(request, blocks = resolveModelTextBlocks(request.system, request.systemBlocks ?? [])) {
1043
- if (blocks.length === 0)
1044
- return undefined;
1045
- return {
1046
- role: 'developer',
1047
- content: blocks.map((block) => ({ type: 'input_text', text: block.text }))
1048
- };
1049
- }
1050
- function incrementalResponsesInput(state, current) {
1051
- const previous = state.lastRequest;
1052
- const completion = state.lastResponse;
1053
- if (previous === undefined || completion === undefined)
1054
- return undefined;
1055
- if (!responsesContinuationPropertiesMatch(previous, current))
1056
- return undefined;
1057
- const baseline = [...previous.input, ...completion.outputItems];
1058
- if (current.input.length < baseline.length)
1059
- return undefined;
1060
- for (let index = 0; index < baseline.length; index++)
1061
- if (JSON.stringify(baseline[index]) !== JSON.stringify(current.input[index]))
1062
- return undefined;
1063
- return current.input.slice(baseline.length);
1064
- }
1065
- function responsesContinuationPropertiesMatch(previous, current) {
1066
- return (JSON.stringify({ ...previous, input: undefined, previous_response_id: undefined }) ===
1067
- JSON.stringify({ ...current, input: undefined, previous_response_id: undefined }));
1068
- }
1069
- function clearResponsesContinuation(state) {
1070
- delete state.lastRequest;
1071
- delete state.lastMessageCount;
1072
- delete state.lastInputItemCount;
1073
- delete state.lastSystem;
1074
- delete state.lastResponse;
1075
- }
1076
- function hashResponsesValue(value) {
1077
- return createHash('sha256').update(JSON.stringify(value)).digest('hex');
1078
- }
1079
- function responsesContinuationEnabled(configuration) {
1080
- return configuration.responsesPreviousResponseId === true;
1081
- }
1082
- function responsesCredentialFingerprint(credential) {
1083
- return hashResponsesValue({
1084
- bearer: credential.bearer.reveal(),
1085
- headers: Object.fromEntries(Object.entries(credential.headers).map(([name, value]) => [
1086
- name,
1087
- typeof value === 'string' ? value : value.reveal()
1088
- ])),
1089
- socks5Url: credential.socks5Url?.reveal()
1090
- });
1091
- }
1092
- function invalidateResponsesWebSocket(state, clearContinuation) {
1093
- const socket = state.socket;
1094
- delete state.socket;
1095
- delete state.endpoint;
1096
- delete state.credentialRevision;
1097
- delete state.credentialFingerprint;
1098
- delete state.connectionId;
1099
- delete state.proxyType;
1100
- if (clearContinuation)
1101
- clearResponsesContinuation(state);
1102
- if (socket !== undefined &&
1103
- socket.readyState !== WebSocket.CLOSED &&
1104
- socket.readyState !== WebSocket.CLOSING)
1105
- terminateWebSocket(socket);
1106
- }
1107
- function turnStateFromEvent(event) {
1108
- for (const headers of [
1109
- record(event.headers),
1110
- record(record(event.response).headers),
1111
- record(record(event.metadata).headers)
1112
- ]) {
1113
- for (const [name, value] of Object.entries(headers))
1114
- if (name.toLowerCase() === X_CODEX_TURN_STATE && typeof value === 'string')
1115
- return value;
1116
- }
1117
- return undefined;
1118
- }
1119
- async function* parseOpenAiResponsesSse(response, signal, continuation, sensitiveValues) {
1120
- try {
1121
- yield* parseSse(response, signal, undefined, undefined, sensitiveValues);
1122
- }
1123
- catch (cause) {
1124
- if (response.ok && !signal.aborted && isRetryableOpenAiStreamReadError(cause))
1125
- throw new MarAgentError('MAR_AGENT_MODEL_PROTOCOL_ERROR', 'OpenAI Responses stream was interrupted.', {
1126
- details: {
1127
- reason: OPENAI_RESPONSES_EARLY_EOF_REASON,
1128
- retryAfter: response.headers.get('retry-after'),
1129
- continuation
1130
- },
1131
- retryable: true,
1132
- cause
1133
- });
1134
- throw cause;
1135
- }
1136
- }
1137
- async function* webSocketResponseEvents(input) {
1138
- const body = input.turn.withTurnStateMetadata(input.body);
1139
- const payload = Buffer.from(JSON.stringify({ type: 'response.create', ...body }), 'utf8');
1140
- const diagnostic = webSocketRequestDiagnostic(body, payload.length);
1141
- input.turn.captureWebSocketDiagnostic(diagnostic);
1142
- const socket = await input.turn.webSocketForRequest({
1143
- configuration: input.configuration,
1144
- promptCacheKey: input.promptCacheKey,
1145
- reason: input.reason,
1146
- signal: input.signal,
1147
- continuation: input.continuation,
1148
- credentialAcquired: input.credentialAcquired
1149
- });
1150
- const messages = webSocketMessages(socket, input.signal, (code) => {
1151
- diagnostic.webSocketCloseCode = code;
1152
- });
1153
- try {
1154
- diagnostic.webSocketPhase = 'SEND';
1155
- await sendWebSocketMessage(socket, payload, input.signal, () => {
1156
- diagnostic.sentFrameCount = (diagnostic.sentFrameCount ?? 0) + 1;
1157
- });
1158
- diagnostic.webSocketPhase = 'RECEIVE';
1159
- let terminal = false;
1160
- for await (const item of messages) {
1161
- const event = record(item);
1162
- const type = text(event.type);
1163
- input.turn.captureTurnState(turnStateFromEvent(event));
1164
- if (type !== 'response.metadata' && type !== 'codex.response.metadata')
1165
- yield item;
1166
- if (type === 'response.completed' ||
1167
- type === 'response.incomplete' ||
1168
- type === 'response.failed' ||
1169
- type === 'error') {
1170
- terminal = true;
1171
- return;
1172
- }
1173
- }
1174
- // Intentionally treat a close without a terminal model event as retryable EOF,
1175
- // including close code 1009. Close codes remain diagnostic evidence rather than
1176
- // a separate model-error classification. The shared attempt budget still bounds
1177
- // retries; this policy does not shrink the request or guarantee recovery.
1178
- if (!terminal && !input.signal.aborted)
1179
- throw new MarAgentError('MAR_AGENT_MODEL_PROTOCOL_ERROR', 'OpenAI Responses WebSocket closed before a terminal event.', {
1180
- details: {
1181
- reason: OPENAI_RESPONSES_EARLY_EOF_REASON,
1182
- transport: 'WEBSOCKET',
1183
- continuation: input.continuation
1184
- },
1185
- retryable: true
1186
- });
1187
- }
1188
- finally {
1189
- messages.dispose();
1190
- }
1191
- }
1192
- function webSocketRequestDiagnostic(body, requestBytes) {
1193
- let imageCount = 0;
1194
- let imageBytes = 0;
1195
- for (const item of body.input) {
1196
- const entry = record(item);
1197
- const parts = Array.isArray(entry.content)
1198
- ? entry.content
1199
- : Array.isArray(entry.output)
1200
- ? entry.output
1201
- : [];
1202
- for (const value of parts) {
1203
- const part = record(value);
1204
- if (part.type !== 'input_image')
1205
- continue;
1206
- imageCount++;
1207
- const url = text(part.image_url);
1208
- if (url === undefined)
1209
- continue;
1210
- const marker = url.indexOf(';base64,');
1211
- if (url.startsWith('data:') && marker >= 0)
1212
- imageBytes += Buffer.byteLength(url.slice(marker + 8), 'base64');
1213
- }
1214
- }
1215
- return {
1216
- requestBytes,
1217
- imageCount,
1218
- imageBytes,
1219
- requestFrameCount: Math.ceil(requestBytes / WEBSOCKET_SEND_FRAME_BYTES),
1220
- sentFrameCount: 0,
1221
- webSocketPhase: 'CONNECT'
1222
- };
1223
- }
1224
- async function waitForWebSocketOpen(socket, signal) {
1225
- if (signal.aborted) {
1226
- terminateWebSocket(socket);
1227
- throw signal.reason;
1228
- }
1229
- await new Promise((resolve, reject) => {
1230
- const cleanup = () => {
1231
- signal.removeEventListener('abort', abort);
1232
- socket.off('open', open);
1233
- socket.off('error', error);
1234
- socket.off('close', close);
1235
- socket.off('unexpected-response', unexpectedResponse);
1236
- };
1237
- const settle = (operation) => {
1238
- cleanup();
1239
- operation();
1240
- };
1241
- const abort = () => settle(() => {
1242
- terminateWebSocket(socket);
1243
- reject(signal.reason);
1244
- });
1245
- const open = () => settle(resolve);
1246
- const error = (cause) => settle(() => reject(new MarAgentError('MAR_AGENT_MODEL_CONNECTION_FAILED', 'OpenAI Responses WebSocket connection failed.', {
1247
- details: { reason: 'MODEL_TRANSPORT_FAILURE', transport: 'WEBSOCKET' },
1248
- retryable: true,
1249
- cause
1250
- })));
1251
- const close = () => settle(() => reject(new MarAgentError('MAR_AGENT_MODEL_CONNECTION_FAILED', 'OpenAI Responses WebSocket closed during connection.', {
1252
- details: { reason: 'MODEL_TRANSPORT_FAILURE', transport: 'WEBSOCKET' },
1253
- retryable: true
1254
- })));
1255
- const unexpectedResponse = (_request, response) => settle(() => {
1256
- const status = response.statusCode ?? 0;
1257
- response.resume();
1258
- terminateWebSocket(socket);
1259
- const retryable = status !== 401 && isRetryableModelHttpStatus(status);
1260
- const retryAfter = response.headers['retry-after'];
1261
- const retryAfterValue = Array.isArray(retryAfter) ? retryAfter[0] : retryAfter;
1262
- reject(new MarAgentError(status === 401 ? 'MAR_AGENT_MODEL_AUTH_FAILED' : 'MAR_AGENT_MODEL_CONNECTION_FAILED', status === 401
1263
- ? 'OpenAI Responses WebSocket authentication failed.'
1264
- : 'OpenAI Responses WebSocket handshake failed.', {
1265
- details: {
1266
- status,
1267
- transport: 'WEBSOCKET',
1268
- ...(retryAfterValue === undefined ? {} : { retryAfter: retryAfterValue })
1269
- },
1270
- ...(retryable ? { retryable: true } : {})
1271
- }));
1272
- });
1273
- signal.addEventListener('abort', abort, { once: true });
1274
- socket.once('open', open);
1275
- socket.once('error', error);
1276
- socket.once('close', close);
1277
- socket.once('unexpected-response', unexpectedResponse);
1278
- });
1279
- }
1280
- async function sendWebSocketMessage(socket, payload, signal, frameSent) {
1281
- for (let offset = 0; offset < payload.length; offset += WEBSOCKET_SEND_FRAME_BYTES) {
1282
- if (signal.aborted)
1283
- throw signal.reason;
1284
- const end = Math.min(payload.length, offset + WEBSOCKET_SEND_FRAME_BYTES);
1285
- await new Promise((resolve, reject) => {
1286
- let settled = false;
1287
- const cleanup = () => {
1288
- settled = true;
1289
- signal.removeEventListener('abort', abort);
1290
- socket.off('error', error);
1291
- socket.off('close', close);
1292
- };
1293
- const abort = () => {
1294
- cleanup();
1295
- socket.terminate();
1296
- reject(signal.reason);
1297
- };
1298
- const error = (cause) => {
1299
- cleanup();
1300
- reject(webSocketReceiveError(cause));
1301
- };
1302
- const close = () => error(new Error('WebSocket closed while sending the request.'));
1303
- signal.addEventListener('abort', abort, { once: true });
1304
- socket.once('error', error);
1305
- socket.once('close', close);
1306
- try {
1307
- socket.send(payload.subarray(offset, end), { binary: false, fin: end === payload.length }, (cause) => {
1308
- if (settled)
1309
- return;
1310
- cleanup();
1311
- if (cause)
1312
- reject(webSocketReceiveError(cause));
1313
- else if (signal.aborted)
1314
- reject(signal.reason);
1315
- else {
1316
- frameSent();
1317
- resolve();
1318
- }
1319
- });
1320
- }
1321
- catch (cause) {
1322
- cleanup();
1323
- reject(webSocketReceiveError(cause));
1324
- }
1325
- });
1326
- }
1327
- }
1328
- function webSocketMessages(socket, signal, closed) {
1329
- const queue = [];
1330
- let resume;
1331
- const push = (item) => {
1332
- queue.push(item);
1333
- resume?.();
1334
- resume = undefined;
1335
- };
1336
- const message = (value) => push({
1337
- type: 'message',
1338
- value,
1339
- observedAt: performance.now()
1340
- });
1341
- const close = (code) => {
1342
- closed(code);
1343
- push({ type: 'closed' });
1344
- };
1345
- const error = (cause) => push({
1346
- type: 'error',
1347
- error: webSocketReceiveError(cause)
1348
- });
1349
- const abort = () => {
1350
- terminateWebSocket(socket);
1351
- push({ type: 'error', error: signal.reason });
1352
- };
1353
- if (signal.aborted) {
1354
- terminateWebSocket(socket);
1355
- throw signal.reason;
1356
- }
1357
- socket.on('message', message);
1358
- socket.on('close', close);
1359
- socket.on('error', error);
1360
- signal.addEventListener('abort', abort, { once: true });
1361
- const dispose = () => {
1362
- signal.removeEventListener('abort', abort);
1363
- socket.off('message', message);
1364
- socket.off('close', close);
1365
- socket.off('error', error);
1366
- };
1367
- return {
1368
- dispose,
1369
- async *[Symbol.asyncIterator]() {
1370
- try {
1371
- let idleDeadline = Date.now() + WEBSOCKET_IDLE_TIMEOUT_MS;
1372
- while (true) {
1373
- if (Date.now() >= idleDeadline)
1374
- throw webSocketIdleError(socket);
1375
- if (queue.length === 0)
1376
- await new Promise((resolve, reject) => {
1377
- const timer = setTimeout(() => {
1378
- resume = undefined;
1379
- reject(webSocketIdleError(socket));
1380
- }, Math.max(0, idleDeadline - Date.now()));
1381
- resume = () => {
1382
- clearTimeout(timer);
1383
- resolve();
1384
- };
1385
- });
1386
- const item = queue.shift();
1387
- if (item === undefined)
1388
- continue;
1389
- if (item.type === 'closed')
1390
- return;
1391
- if (item.type === 'error')
1392
- throw item.error;
1393
- const text = await webSocketMessageText(item.value);
1394
- if (Buffer.byteLength(text) > 16 * 1024 * 1024)
1395
- throw new MarAgentError('MAR_AGENT_MODEL_PROTOCOL_ERROR', 'Model response exceeded the size limit.');
1396
- try {
1397
- const event = JSON.parse(text);
1398
- if (!isWebSocketNonProgressEvent(event))
1399
- idleDeadline = Date.now() + WEBSOCKET_IDLE_TIMEOUT_MS;
1400
- yield observeModelStreamEvent(event, item.observedAt);
1401
- }
1402
- catch (cause) {
1403
- throw new MarAgentError('MAR_AGENT_MODEL_PROTOCOL_ERROR', 'Model WebSocket contained invalid JSON.', { cause });
1404
- }
1405
- }
1406
- }
1407
- finally {
1408
- dispose();
1409
- }
1410
- }
1411
- };
1412
- }
1413
- function webSocketIdleError(socket) {
1414
- terminateWebSocket(socket);
1415
- return new MarAgentError('MAR_AGENT_MODEL_TIMEOUT', 'OpenAI Responses WebSocket was idle for too long.', {
1416
- details: { reason: OPENAI_RESPONSES_EARLY_EOF_REASON, transport: 'WEBSOCKET' },
1417
- retryable: true
1418
- });
1419
- }
1420
- function isWebSocketNonProgressEvent(value) {
1421
- const type = text(record(value).type);
1422
- return (type === 'response.metadata' ||
1423
- type === 'codex.response.metadata' ||
1424
- type === 'responsesapi.websocket_timing' ||
1425
- type === 'response.queued' ||
1426
- type === 'response.in_progress');
1427
- }
1428
- async function webSocketMessageText(value) {
1429
- if (typeof value === 'string')
1430
- return value;
1431
- if (Buffer.isBuffer(value))
1432
- return value.toString('utf8');
1433
- if (value instanceof ArrayBuffer)
1434
- return Buffer.from(value).toString('utf8');
1435
- if (ArrayBuffer.isView(value))
1436
- return Buffer.from(value.buffer, value.byteOffset, value.byteLength).toString('utf8');
1437
- if (Array.isArray(value) && value.every((part) => Buffer.isBuffer(part)))
1438
- return Buffer.concat(value).toString('utf8');
1439
- throw new MarAgentError('MAR_AGENT_MODEL_PROTOCOL_ERROR', 'Model WebSocket returned an unsupported frame.');
1440
- }
1441
- function webSocketHeaders(credential, promptCacheKey) {
1442
- const headers = responsesHeaders(credential, promptCacheKey);
1443
- headers.delete('accept');
1444
- headers.delete('content-type');
1445
- headers.set('openai-beta', 'responses_websockets=2026-02-06');
1446
- return headers;
1447
- }
1448
- function webSocketEndpoint(baseUrl) {
1449
- const endpoint = new URL(responsesEndpoint(baseUrl));
1450
- endpoint.protocol = endpoint.protocol === 'https:' ? 'wss:' : 'ws:';
1451
- return endpoint.toString();
1452
- }
1453
- function socks5WebSocketConnection(socks5Url, endpoint, signal) {
1454
- return ((_options, callback) => {
1455
- if (callback === undefined)
1456
- throw new MarAgentError('MAR_AGENT_MODEL_CONNECTION_FAILED', 'WebSocket connection callback is unavailable.');
1457
- void connectSocks5Target({
1458
- socks5Url,
1459
- targetHost: endpoint.hostname,
1460
- targetPort: Number(endpoint.port || (endpoint.protocol === 'wss:' ? 443 : 80)),
1461
- tls: endpoint.protocol === 'wss:',
1462
- servername: endpoint.hostname,
1463
- ...(endpoint.protocol === 'wss:' ? { alpnProtocols: ['http/1.1'] } : {}),
1464
- signal
1465
- }).then((socket) => callback(null, socket), (error) => callback(error instanceof Error
1466
- ? error
1467
- : new Error('SOCKS5 WebSocket connection failed.', { cause: error })));
1468
- return undefined;
1469
- });
1470
- }
1471
- function terminateWebSocket(socket) {
1472
- if (socket.readyState === WebSocket.CONNECTING)
1473
- socket.once('error', () => undefined);
1474
- socket.terminate();
1475
- }
1476
- function webSocketReceiveError(cause) {
1477
- const code = cause.code;
1478
- if (typeof code === 'string' && code.startsWith('WS_ERR_'))
1479
- return new MarAgentError('MAR_AGENT_MODEL_PROTOCOL_ERROR', code === 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH'
1480
- ? 'Model response exceeded the size limit.'
1481
- : 'Model WebSocket protocol is invalid.', { cause });
1482
- return new MarAgentError('MAR_AGENT_MODEL_PROTOCOL_ERROR', 'OpenAI Responses WebSocket was interrupted.', {
1483
- details: {
1484
- reason: OPENAI_RESPONSES_EARLY_EOF_REASON,
1485
- transport: 'WEBSOCKET'
1486
- },
1487
- retryable: true,
1488
- cause
1489
- });
1490
- }
1491
- function isSemanticEvent(event) {
1492
- if (event.type.startsWith('output.'))
1493
- return false;
1494
- if (event.type === 'response.started' || event.type === 'usage' || event.type === 'response.item')
1495
- return false;
1496
- if (event.type === 'text.delta')
1497
- return event.delta.length > 0;
1498
- if (event.type === 'text.completed' || event.type === 'reasoning.completed')
1499
- return event.text.length > 0;
1500
- return true;
1501
- }
1502
- function isNonSemanticOpenAiResponsesEvent(type) {
1503
- return NON_SEMANTIC_OPENAI_RESPONSES_EVENTS.has(type);
1504
- }
1505
- const NON_SEMANTIC_OPENAI_RESPONSES_EVENTS = new Set([
1506
- 'codex.response.metadata',
1507
- 'response.content_part.added',
1508
- 'response.content_part.done',
1509
- 'response.in_progress',
1510
- 'response.metadata',
1511
- 'response.queued',
1512
- 'response.reasoning_summary_part.added',
1513
- 'response.reasoning_summary_part.done',
1514
- 'responsesapi.websocket_timing'
1515
- ]);
1516
- function isRetryableResponsesUpstreamError(code, message) {
1517
- if (isRetryableUpstreamOverloadCode(code))
1518
- return true;
1519
- if (code !== 'invalid_request_error')
1520
- return false;
1521
- // Exact compatibility exception, not a general access/authentication retry rule.
1522
- const summary = message?.startsWith(`${code}: `) ? message.slice(code.length + 2) : message;
1523
- return summary === 'Unable to verify Daybreak Blue access. Please try again.';
1524
- }
1525
- export function isOpenAiResponsesRecoverableStreamError(error) {
1526
- return (error instanceof MarAgentError &&
1527
- error.retryable &&
1528
- (error.details?.reason === OPENAI_RESPONSES_EARLY_EOF_REASON ||
1529
- error.details?.reason === OPENAI_RESPONSES_WEBSOCKET_CONNECTION_LIMIT_REASON ||
1530
- isRetryableResponsesUpstreamError(error.code, error.message)));
1531
- }
1532
- function isWebSocketConnectionLimitCode(code) {
1533
- return code?.trim().toLowerCase() === 'websocket_connection_limit_reached';
1534
- }
1535
- function isRetryableOpenAiStreamReadError(error) {
1536
- return (isRetryableModelTransportError(error) ||
1537
- (error instanceof MarAgentError &&
1538
- error.code === 'MAR_AGENT_MODEL_TIMEOUT' &&
1539
- error.details?.reason === 'MODEL_STREAM_IDLE_TIMEOUT'));
1540
- }
1541
- function retryAfter(error) {
1542
- const value = error.details?.retryAfter;
1543
- return typeof value === 'string' ? value : null;
1544
- }
1545
- function openAiResponsesAttemptError(error) {
1546
- const diagnostic = describeMarAgentError(error, 'MAR_AGENT_MODEL_ATTEMPT_FAILED');
1547
- const causeCode = deepestCauseCode(error);
1548
- const reason = error instanceof MarAgentError && typeof error.details?.reason === 'string'
1549
- ? error.details.reason
1550
- : undefined;
1551
- return {
1552
- errorCode: diagnostic.code,
1553
- errorMessage: diagnostic.message,
1554
- ...(causeCode === undefined || causeCode === diagnostic.code ? {} : { causeCode }),
1555
- ...(reason === undefined ? {} : { reason }),
1556
- retryable: error instanceof MarAgentError && error.retryable
1557
- };
1558
- }
1559
- function deepestCauseCode(error) {
1560
- const seen = new Set();
1561
- let current = error;
1562
- let code;
1563
- while (current !== undefined && current !== null && !seen.has(current) && seen.size < 8) {
1564
- seen.add(current);
1565
- const candidate = current instanceof MarAgentError
1566
- ? current.code
1567
- : typeof current === 'object' && 'code' in current
1568
- ? current.code
1569
- : undefined;
1570
- if (typeof candidate === 'string' && candidate.trim())
1571
- code = boundedError(candidate, 80) ?? code;
1572
- current =
1573
- typeof current === 'object' && 'cause' in current
1574
- ? current.cause
1575
- : undefined;
1576
- }
1577
- return code;
1578
- }
1579
- function responsesEndpoint(baseUrl) {
1580
- const normalized = baseUrl.replace(/\/$/, '');
1581
- if (new URL(normalized).pathname.endsWith('/backend-api/codex'))
1582
- return `${normalized}/responses`;
1583
- return `${normalized.endsWith('/v1') ? normalized : `${normalized}/v1`}/responses`;
1584
- }
1585
- async function acquireResponsesCredential(configuration, reason, signal) {
1586
- return acquireModelCredential(configuration, reason, 'OpenAI Responses requires a model credential.', signal);
1587
- }
1588
- const RESERVED_CREDENTIAL_HEADERS = new Set([
1589
- 'accept',
1590
- 'authorization',
1591
- 'connection',
1592
- 'content-length',
1593
- 'content-type',
1594
- 'host',
1595
- 'openai-beta',
1596
- 'proxy-authorization',
1597
- 'sec-websocket-accept',
1598
- 'sec-websocket-extensions',
1599
- 'sec-websocket-key',
1600
- 'sec-websocket-protocol',
1601
- 'sec-websocket-version',
1602
- 'session-id',
1603
- 'thread-id',
1604
- 'transfer-encoding',
1605
- 'upgrade',
1606
- 'x-client-request-id',
1607
- X_CODEX_TURN_STATE,
1608
- 'x-openai-internal-codex-responses-lite'
1609
- ]);
1610
- function responsesHeaders(credential, promptCacheKey, turnState) {
1611
- const headers = new Headers({
1612
- authorization: `Bearer ${credential.bearer.reveal()}`,
1613
- 'content-type': 'application/json',
1614
- accept: 'text/event-stream',
1615
- 'user-agent': productUserAgent(),
1616
- 'x-client-request-id': randomUUID(),
1617
- ...(promptCacheKey
1618
- ? {
1619
- 'session-id': promptCacheKey,
1620
- 'thread-id': promptCacheKey
1621
- }
1622
- : {})
1623
- });
1624
- if (turnState)
1625
- headers.set(X_CODEX_TURN_STATE, turnState);
1626
- return appendModelCredentialHeaders(headers, credential, RESERVED_CREDENTIAL_HEADERS);
1627
- }
1628
- function withCredentialRevision(error, revision) {
1629
- if (!(error instanceof MarAgentError) || revision === undefined)
1630
- return error;
1631
- const prefix = `${error.code}: `;
1632
- return new MarAgentError(error.code, error.message.startsWith(prefix) ? error.message.slice(prefix.length) : error.message, {
1633
- details: { ...error.details, credentialRevision: revision },
1634
- retryable: error.retryable,
1635
- cause: error
1636
- });
1637
- }
1638
- function withResponsesAttemptDetails(error, continuation, transport) {
1639
- if (!(error instanceof MarAgentError))
1640
- return error;
1641
- const prefix = `${error.code}: `;
1642
- return new MarAgentError(error.code, error.message.startsWith(prefix) ? error.message.slice(prefix.length) : error.message, {
1643
- details: {
1644
- ...error.details,
1645
- continuation,
1646
- ...(transport === 'WEBSOCKET' ? { transport: 'WEBSOCKET' } : {})
1647
- },
1648
- retryable: error.retryable,
1649
- cause: error
1650
- });
1651
- }
1652
- function isModelAuthenticationFailure(error) {
1653
- if (!(error instanceof MarAgentError))
1654
- return false;
1655
- if (typeof error.details?.status === 'number')
1656
- return error.details.status === 401;
1657
- const code = error.code.toLowerCase();
1658
- return code === 'unauthorized';
1659
- }
1660
- function credentialRevision(error) {
1661
- const revision = error.details?.credentialRevision;
1662
- return typeof revision === 'number' && Number.isSafeInteger(revision) && revision >= 0
1663
- ? revision
1664
- : undefined;
1665
- }
1666
- function boundedError(value, maximum) {
1667
- const normalized = value?.trim();
1668
- if (!normalized)
1669
- return undefined;
1670
- return [...normalized].slice(0, maximum).join('');
1671
- }
1672
- function upstreamHttpStatus(...values) {
1673
- for (const value of values) {
1674
- const candidate = typeof value === 'string' && /^\d{3}$/u.test(value) ? Number(value) : number(value);
1675
- if (candidate !== undefined &&
1676
- Number.isInteger(candidate) &&
1677
- candidate >= 100 &&
1678
- candidate <= 599)
1679
- return candidate;
1680
- }
1681
- return undefined;
1682
- }
1683
- function optionalRolloutBudgetUnits(value) {
1684
- if (value === undefined)
1685
- return undefined;
1686
- const units = number(value);
1687
- if (units !== undefined && units >= 0)
1688
- return units;
1689
- throw new MarAgentError('MAR_AGENT_MODEL_PROTOCOL_ERROR', 'Provider rollout budget units are invalid.');
1690
- }
1691
- function messagePhase(value) {
1692
- return value === 'commentary' || value === 'final_answer' ? value : undefined;
1693
- }
1694
- function responseMessageText(item) {
1695
- const content = Array.isArray(item.content) ? item.content : [];
1696
- const parts = content
1697
- .map(record)
1698
- .filter((part) => text(part.type) === 'output_text')
1699
- .map((part) => text(part.text) ?? '');
1700
- return parts.length ? parts.join('') : undefined;
1701
- }
1702
- function isInvalidPreviousResponseError(error) {
1703
- if (!(error instanceof MarAgentError))
1704
- return false;
1705
- const status = error.details?.status;
1706
- if (typeof status === 'number' && ![400, 404, 410].includes(status))
1707
- return false;
1708
- return isInvalidPreviousResponseFields(error.code, error.message);
1709
- }
1710
- function isInvalidPreviousResponseFields(code, message) {
1711
- const normalizedCode = code?.trim().toLowerCase();
1712
- // OpenAI Responses and compatible providers use these missing-reference codes.
1713
- if (normalizedCode === 'previous_response_not_found' ||
1714
- normalizedCode === 'invalid_previous_response_id')
1715
- return true;
1716
- const normalizedMessage = message?.toLowerCase().replaceAll('`', '') ?? '';
1717
- // xAI/Grok WSS uses api_error with a gRPC prefix; HTTP may return a plain
1718
- // error string, normalized by the SSE boundary to MAR_AGENT_MODEL_PROTOCOL_ERROR.
1719
- // Do not treat account/model lookup failures as a missing response reference.
1720
- if ((normalizedCode === 'api_error' ||
1721
- normalizedCode === 'mar_agent_model_protocol_error' ||
1722
- normalizedCode === undefined) &&
1723
- /^(?:(?:mar_agent_model_protocol_error|api_error): )?(?:grpc error: )?response with id=\S+ not found[.!]?$/u.test(normalizedMessage))
1724
- return true;
1725
- // Compatibility gateways use these unsupported-parameter discriminators.
1726
- if ((normalizedCode === 'unsupported_parameter' ||
1727
- normalizedCode === 'unsupported_previous_response_id') &&
1728
- normalizedMessage.includes('previous_response_id'))
1729
- return true;
1730
- // OpenAI-style request errors and generic compatibility envelopes may only
1731
- // name the rejected parameter. Explicit auth, permission, overload or other
1732
- // error codes take precedence even when their message mentions continuation.
1733
- if (normalizedCode !== undefined &&
1734
- normalizedCode !== 'invalid_request_error' &&
1735
- normalizedCode !== 'api_error' &&
1736
- normalizedCode !== 'mar_agent_model_protocol_error')
1737
- return false;
1738
- return (normalizedMessage.includes('previous_response_id') &&
1739
- (normalizedMessage.includes('invalid') ||
1740
- normalizedMessage.includes('not found') ||
1741
- normalizedMessage.includes('does not exist') ||
1742
- normalizedMessage.includes('expired') ||
1743
- normalizedMessage.includes('not supported') ||
1744
- normalizedMessage.includes('unsupported') ||
1745
- normalizedMessage.includes('unavailable')));
1746
- }
1747
- const RESPONSE_ITEM_TYPES = new Set([
1748
- 'message',
1749
- 'reasoning',
1750
- 'function_call',
1751
- 'custom_tool_call',
1752
- 'tool_search_call',
1753
- 'tool_search_output',
1754
- 'web_search_call'
1755
- ]);
1756
- // A freeform patch item can contain the complete 4 MiB patch plus its JSON envelope.
1757
- const MAX_RESPONSE_ITEM_BYTES = 5 * 1024 * 1024;
1758
- function hostedWebActionInput(action) {
1759
- const input = {};
1760
- let truncated = false;
1761
- for (const [key, limit] of [
1762
- ['type', 128],
1763
- ['query', 10_000],
1764
- ['url', 2_048],
1765
- ['pattern', 10_000]
1766
- ]) {
1767
- const value = action[key];
1768
- if (typeof value !== 'string')
1769
- continue;
1770
- input[key] = value.slice(0, limit);
1771
- truncated ||= value.length > limit;
1772
- }
1773
- if (Array.isArray(action.queries)) {
1774
- const queries = action.queries.filter((value) => typeof value === 'string');
1775
- input.queries = queries.slice(0, 10).map((value) => value.slice(0, 10_000));
1776
- truncated ||=
1777
- queries.length > 10 || queries.slice(0, 10).some((value) => value.length > 10_000);
1778
- }
1779
- return { input, truncated };
1780
- }
1781
- function hostedWebActionSummary(action) {
1782
- const queries = Array.isArray(action.queries)
1783
- ? action.queries
1784
- .slice(0, 10)
1785
- .filter((query) => typeof query === 'string' && query.length > 0)
1786
- : [];
1787
- const query = text(action.query) || queries.join('\n');
1788
- const url = text(action.url);
1789
- const title = text(action.title);
1790
- const sources = Array.isArray(action.sources)
1791
- ? action.sources
1792
- .slice(0, 20)
1793
- .map((source) => {
1794
- const value = record(source);
1795
- const sourceUrl = text(value.url);
1796
- if (!sourceUrl)
1797
- return undefined;
1798
- const sourceTitle = text(value.title);
1799
- const snippet = text(value.snippet);
1800
- return {
1801
- url: sourceUrl.slice(0, 2048),
1802
- ...(sourceTitle ? { title: sourceTitle.slice(0, 256) } : {}),
1803
- ...(snippet ? { snippet: snippet.slice(0, 2000) } : {})
1804
- };
1805
- })
1806
- .filter((source) => source !== undefined)
1807
- : [];
1808
- return {
1809
- ...(query ? { query: query.slice(0, 10_000) } : {}),
1810
- ...(url ? { url: url.slice(0, 2048) } : {}),
1811
- ...(title ? { title: title.slice(0, 256) } : {}),
1812
- ...(Array.isArray(action.sources) ? { sources } : {}),
1813
- ...(Array.isArray(action.sources) && action.sources.length > 20
1814
- ? { sourcesTruncated: true }
1815
- : {})
1816
- };
1817
- }
1818
- function responseItem(value) {
1819
- const item = record(value);
1820
- const itemType = text(item.type);
1821
- if (!itemType || !RESPONSE_ITEM_TYPES.has(itemType))
1822
- return undefined;
1823
- const serialized = JSON.stringify(item);
1824
- if (Buffer.byteLength(serialized) > MAX_RESPONSE_ITEM_BYTES)
1825
- throw new MarAgentError('MAR_AGENT_MODEL_PROTOCOL_ERROR', 'Responses output item exceeds the context record limit.');
1826
- return JSON.parse(serialized);
1827
- }
1828
- function strictFunctionSchema(value, optional = false) {
1829
- if (value === null || typeof value !== 'object' || Array.isArray(value))
1830
- return value;
1831
- const schema = value;
1832
- const supportedSchema = Object.fromEntries(Object.entries(schema).filter(([keyword]) => keyword !== 'propertyNames' && keyword !== 'uniqueItems'));
1833
- if (optional && Array.isArray(schema.enum) && !schema.enum.includes(null))
1834
- supportedSchema.enum = [...schema.enum, null];
1835
- if (schema.type === 'object') {
1836
- const properties = record(schema.properties);
1837
- const required = new Set(Array.isArray(schema.required) ? schema.required : []);
1838
- return {
1839
- ...supportedSchema,
1840
- ...(optional ? { type: ['object', 'null'] } : {}),
1841
- properties: Object.fromEntries(Object.entries(properties).map(([name, property]) => [
1842
- name,
1843
- strictFunctionSchema(property, !required.has(name))
1844
- ])),
1845
- required: Object.keys(properties),
1846
- additionalProperties: false
1847
- };
1848
- }
1849
- if (schema.type === 'array')
1850
- return {
1851
- ...supportedSchema,
1852
- ...(schema.items === undefined ? {} : { items: strictFunctionSchema(schema.items) }),
1853
- ...(optional ? { type: ['array', 'null'] } : {})
1854
- };
1855
- if (!optional)
1856
- return supportedSchema;
1857
- if (typeof schema.type === 'string')
1858
- return { ...supportedSchema, type: [schema.type, 'null'] };
1859
- if (Array.isArray(schema.type))
1860
- return {
1861
- ...supportedSchema,
1862
- type: schema.type.includes('null') ? schema.type : [...schema.type, 'null']
1863
- };
1864
- if (Array.isArray(schema.enum))
1865
- return supportedSchema;
1866
- return { anyOf: [supportedSchema, { type: 'null' }] };
1867
- }
1868
- function responseCitations(response) {
1869
- const citations = new Map();
1870
- for (const output of Array.isArray(response.output) ? response.output : []) {
1871
- const item = record(output);
1872
- for (const content of Array.isArray(item.content) ? item.content : []) {
1873
- const part = record(content);
1874
- for (const value of Array.isArray(part.annotations) ? part.annotations : []) {
1875
- const annotation = record(value);
1876
- const url = text(annotation.url);
1877
- if (!url)
1878
- continue;
1879
- const id = text(annotation.id) ?? `${text(item.id) ?? 'text'}-${citations.size}`;
1880
- const title = text(annotation.title);
1881
- citations.set(`${id}:${url}`, {
1882
- id,
1883
- url,
1884
- ...(title ? { title } : {})
1885
- });
1886
- }
1887
- }
1888
- }
1889
- return [...citations.values()];
1890
- }
1891
- function responseEventId(event) {
1892
- return text(record(event.response).id);
1893
- }
1894
- export function openAiInput(messages, images, modelId, requireEncryptedReasoning, configurationUpdates = true, nativeTools = true, tools = [], previousOutputItems = []) {
1895
- const compatibleMessages = messages.filter((message) => message.role !== 'provider' ||
1896
- (message.provider === 'OPENAI_RESPONSES' &&
1897
- (message.providerModelId === undefined || message.providerModelId === modelId) &&
1898
- (configurationUpdates || message.item?.type !== 'configuration_update') &&
1899
- (nativeTools ||
1900
- !['custom_tool_call', 'tool_search_call', 'tool_search_output'].includes(String(message.item?.type))) &&
1901
- (!requireEncryptedReasoning ||
1902
- message.item?.type !== 'reasoning' ||
1903
- typeof message.item.encrypted_content === 'string')));
1904
- const lastUser = compatibleMessages.findLast(isRealUserMessage);
1905
- const providerCallIds = new Set();
1906
- const functionCallIds = new Set();
1907
- const customCallIds = new Set();
1908
- const providerMessageTexts = new Set();
1909
- // Incremental input omits the calls already retained by the WebSocket response.
1910
- for (const item of previousOutputItems) {
1911
- if (typeof item.call_id !== 'string')
1912
- continue;
1913
- if (item.type === 'function_call')
1914
- functionCallIds.add(item.call_id);
1915
- if (nativeTools && item.type === 'custom_tool_call')
1916
- customCallIds.add(item.call_id);
1917
- }
1918
- for (const message of compatibleMessages) {
1919
- if (message.role !== 'provider' || !message.item)
1920
- continue;
1921
- if (message.item.type === 'function_call' && typeof message.item.call_id === 'string') {
1922
- providerCallIds.add(message.item.call_id);
1923
- functionCallIds.add(message.item.call_id);
1924
- }
1925
- if (message.item.type === 'tool_search_call' && typeof message.item.call_id === 'string')
1926
- providerCallIds.add(message.item.call_id);
1927
- if (message.item.type === 'custom_tool_call' && typeof message.item.call_id === 'string') {
1928
- providerCallIds.add(message.item.call_id);
1929
- customCallIds.add(message.item.call_id);
1930
- }
1931
- if (message.item.type === 'message') {
1932
- const content = Array.isArray(message.item.content) ? message.item.content : [];
1933
- const value = content
1934
- .map((part) => {
1935
- const item = record(part);
1936
- return text(item.text) ?? '';
1937
- })
1938
- .join('');
1939
- if (value)
1940
- providerMessageTexts.add(value);
1941
- }
1942
- }
1943
- for (const message of compatibleMessages)
1944
- if (nativeTools &&
1945
- message.role === 'tool_call' &&
1946
- message.inputMode === 'freeform' &&
1947
- message.callId)
1948
- customCallIds.add(message.callId);
1949
- const orderedMessages = [];
1950
- for (const message of compatibleMessages) {
1951
- if (message.role === 'provider' && message.item?.type === 'configuration_update') {
1952
- const userIndex = orderedMessages.findLastIndex(isRealUserMessage);
1953
- if (userIndex >= 0) {
1954
- orderedMessages.splice(userIndex, 0, message);
1955
- continue;
1956
- }
1957
- }
1958
- orderedMessages.push(message);
1959
- }
1960
- // SDK records the update after the user input; the wire item must precede
1961
- // that user message so the new effort applies to the response.
1962
- return orderedMessages
1963
- .filter((message) => !(message.role === 'tool_call' && message.callId && providerCallIds.has(message.callId)) &&
1964
- !(message.role === 'assistant' && providerMessageTexts.has(message.content)))
1965
- .map((message) => openAiInputItem(message, message === lastUser ? images : undefined, customCallIds, functionCallIds, nativeTools, tools));
1966
- }
1967
- function openAiInputItem(message, images, customCallIds = new Set(), functionCallIds = new Set(), nativeTools = true, tools = []) {
1968
- const userImages = message.role === 'user' ? uniqueModelImages(message.images, images) : [];
1969
- if (message.role === 'provider') {
1970
- if (message.provider !== 'OPENAI_RESPONSES' || !message.item)
1971
- throw new MarAgentError('MAR_AGENT_MODEL_PROTOCOL_ERROR', 'Provider context item is invalid.');
1972
- if (message.item.type === 'configuration_update') {
1973
- const effort = marAgentReasoningEffortSchema.safeParse(record(message.item.reasoning).effort);
1974
- if (effort.success)
1975
- return { type: 'configuration_update', reasoning: { effort: effort.data } };
1976
- }
1977
- const item = responseItem(message.item);
1978
- if (!item)
1979
- throw new MarAgentError('MAR_AGENT_MODEL_PROTOCOL_ERROR', 'Provider context item type is unsupported.');
1980
- return item;
1981
- }
1982
- if (nativeTools && message.role === 'tool_call' && message.inputMode === 'freeform')
1983
- return {
1984
- type: 'custom_tool_call',
1985
- call_id: message.callId,
1986
- name: message.name,
1987
- input: String(message.arguments ?? '')
1988
- };
1989
- if (nativeTools && message.role === 'tool_call' && message.name === 'tool_search')
1990
- return {
1991
- type: 'tool_search_call',
1992
- call_id: message.callId,
1993
- status: 'completed',
1994
- execution: 'client',
1995
- arguments: message.arguments ?? {}
1996
- };
1997
- if (message.role === 'tool_call')
1998
- return {
1999
- type: 'function_call',
2000
- call_id: message.callId,
2001
- name: message.name,
2002
- arguments: JSON.stringify(message.inputMode === 'freeform'
2003
- ? jsonToolInput(message, tools.find((tool) => tool.name === message.name))
2004
- : (message.arguments ?? {}))
2005
- };
2006
- if (message.role === 'tool' &&
2007
- nativeTools &&
2008
- message.toolSearchTools &&
2009
- !functionCallIds.has(message.callId ?? ''))
2010
- return {
2011
- type: 'tool_search_output',
2012
- call_id: message.callId,
2013
- status: 'completed',
2014
- execution: 'client',
2015
- tools: message.toolSearchTools.map((tool) => responsesFunctionTool(tool))
2016
- };
2017
- if (message.role === 'tool')
2018
- return {
2019
- type: customCallIds.has(message.callId ?? '')
2020
- ? 'custom_tool_call_output'
2021
- : 'function_call_output',
2022
- call_id: message.callId,
2023
- output: observationModelParts(message)?.map((part) => part.type === 'text'
2024
- ? { type: 'input_text', text: part.text }
2025
- : {
2026
- type: 'input_image',
2027
- image_url: modelImageUrl(part.image)
2028
- }) ??
2029
- (message.textBlocks !== undefined
2030
- ? [
2031
- ...resolveModelTextBlocks(message.content, message.textBlocks).map((block) => ({
2032
- type: 'input_text',
2033
- text: block.text
2034
- })),
2035
- ...(message.images ?? []).map((image) => ({
2036
- type: 'input_image',
2037
- image_url: modelImageUrl(image)
2038
- }))
2039
- ]
2040
- : message.images?.length
2041
- ? [
2042
- { type: 'input_text', text: message.content },
2043
- ...message.images.map((image) => ({
2044
- type: 'input_image',
2045
- image_url: modelImageUrl(image)
2046
- }))
2047
- ]
2048
- : message.content)
2049
- };
2050
- return {
2051
- role: message.role === 'user' && contextualAuthority(message) === 'instruction'
2052
- ? 'developer'
2053
- : message.role,
2054
- content: message.textBlocks !== undefined
2055
- ? [
2056
- ...resolveModelTextBlocks(message.content, message.textBlocks).map((block) => ({
2057
- type: message.role === 'assistant' ? 'output_text' : 'input_text',
2058
- text: block.text
2059
- })),
2060
- ...userImages.map((image) => ({
2061
- type: 'input_image',
2062
- image_url: modelImageUrl(image)
2063
- }))
2064
- ]
2065
- : userImages.length > 0
2066
- ? [
2067
- { type: 'input_text', text: message.content },
2068
- ...userImages.map((image) => ({
2069
- type: 'input_image',
2070
- image_url: modelImageUrl(image)
2071
- }))
2072
- ]
2073
- : message.content
2074
- };
2075
- }
2076
- function contextualAuthority(message) {
2077
- return message.contextualBlock?.authority;
2078
- }
2079
- function isRealUserMessage(message) {
2080
- return (message.role === 'user' &&
2081
- message.contextKind === undefined &&
2082
- message.contextualBlock === undefined);
2083
- }
2084
- function responsesFunctionTool(tool, nativeTools = true) {
2085
- const strict = !hasOpenFunctionObject(tool.inputSchema);
2086
- return tool.inputMode === 'freeform' && nativeTools
2087
- ? { type: 'custom', name: tool.name, description: tool.description }
2088
- : {
2089
- type: 'function',
2090
- name: tool.name,
2091
- description: tool.description,
2092
- parameters: stableToolSchema(strict ? strictFunctionSchema(stableToolSchema(tool.inputSchema)) : tool.inputSchema),
2093
- strict
2094
- };
2095
- }
2096
- function hasOpenFunctionObject(value) {
2097
- if (value === null || typeof value !== 'object' || Array.isArray(value))
2098
- return false;
2099
- const schema = record(value);
2100
- if ((schema.type === 'object' || (Array.isArray(schema.type) && schema.type.includes('object'))) &&
2101
- (schema.additionalProperties === true ||
2102
- (schema.additionalProperties !== null && typeof schema.additionalProperties === 'object') ||
2103
- (schema.properties === undefined && schema.additionalProperties !== false)))
2104
- return true;
2105
- const children = [
2106
- ...Object.values(record(schema.properties)),
2107
- ...Object.values(record(schema.$defs)),
2108
- ...Object.values(record(schema.definitions)),
2109
- schema.items,
2110
- ...[schema.anyOf, schema.oneOf, schema.allOf].flatMap((items) => Array.isArray(items) ? items : [])
2111
- ];
2112
- return children.some(hasOpenFunctionObject);
2113
- }
2114
- function uniqueModelImages(...groups) {
2115
- const seen = new Set();
2116
- return groups.flatMap((group) => (group ?? []).flatMap((image) => {
2117
- const key = modelImageKey(image);
2118
- if (seen.has(key))
2119
- return [];
2120
- seen.add(key);
2121
- return [image];
2122
- }));
2123
- }