@opencode/ai 2.1.4 → 2.2.1

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 (354) hide show
  1. package/README.md +339 -166
  2. package/dist/ai-client.d.ts +2 -2
  3. package/dist/ai-client.js +2 -1
  4. package/dist/cache-policy.d.ts +4 -0
  5. package/dist/cache-policy.js +20 -6
  6. package/dist/decision-client.d.ts +21 -0
  7. package/dist/decision-client.js +55 -0
  8. package/dist/decision.d.ts +472 -0
  9. package/dist/decision.js +158 -0
  10. package/dist/effect.d.ts +38 -0
  11. package/dist/effect.js +27 -0
  12. package/dist/effort-updates.d.ts +2 -2
  13. package/dist/experimental/cloudflare-run-extraction.d.ts +13 -0
  14. package/dist/experimental/cloudflare-run-extraction.js +83 -0
  15. package/dist/experimental/extraction.d.ts +183 -0
  16. package/dist/experimental/extraction.js +102 -0
  17. package/dist/experimental/realtime.d.ts +7 -2
  18. package/dist/experimental/realtime.js +5 -5
  19. package/dist/experimental.d.ts +2 -3
  20. package/dist/experimental.js +1 -2
  21. package/dist/image-client.d.ts +50 -14
  22. package/dist/image-client.js +0 -1
  23. package/dist/image.d.ts +6 -176
  24. package/dist/image.js +4 -11
  25. package/dist/index.d.ts +1444 -34
  26. package/dist/index.js +139 -24
  27. package/dist/llm.d.ts +16 -1
  28. package/dist/llm.js +34 -0
  29. package/dist/media-client.d.ts +3 -1
  30. package/dist/media-client.js +1 -0
  31. package/dist/media-model.d.ts +3 -0
  32. package/dist/media-model.js +4 -1
  33. package/dist/media.d.ts +0 -7
  34. package/dist/media.js +0 -6
  35. package/dist/protocols/alibaba-chat.d.ts +59 -4
  36. package/dist/protocols/alibaba-images.d.ts +22 -0
  37. package/dist/protocols/alibaba-images.js +77 -0
  38. package/dist/protocols/alibaba-messages.d.ts +52 -17
  39. package/dist/protocols/alibaba-responses.d.ts +26 -6
  40. package/dist/protocols/anthropic-messages.d.ts +160 -54
  41. package/dist/protocols/anthropic-messages.js +44 -13
  42. package/dist/protocols/bedrock-converse.d.ts +110 -15
  43. package/dist/protocols/bedrock-converse.js +112 -15
  44. package/dist/protocols/bedrock-event-stream.js +1 -0
  45. package/dist/protocols/cartesia-speech.d.ts +0 -18
  46. package/dist/protocols/cloudflare-run-decisions.d.ts +9 -0
  47. package/dist/protocols/cloudflare-run-decisions.js +36 -0
  48. package/dist/protocols/cloudflare-workers-ai-images.d.ts +23 -0
  49. package/dist/protocols/cloudflare-workers-ai-images.js +80 -0
  50. package/dist/protocols/deepgram-speech.d.ts +0 -18
  51. package/dist/protocols/elevenlabs-speech.d.ts +0 -18
  52. package/dist/protocols/gemini.d.ts +3 -0
  53. package/dist/protocols/gemini.js +11 -6
  54. package/dist/protocols/google-images.d.ts +2 -2
  55. package/dist/protocols/google-images.js +10 -37
  56. package/dist/protocols/google-interactions.d.ts +4 -0
  57. package/dist/protocols/google-interactions.js +12 -5
  58. package/dist/protocols/google-speech.d.ts +0 -18
  59. package/dist/protocols/google-speech.js +0 -1
  60. package/dist/protocols/google-transcription.d.ts +0 -18
  61. package/dist/protocols/google-transcription.js +0 -1
  62. package/dist/protocols/google-video.d.ts +1 -1
  63. package/dist/protocols/google-video.js +2 -7
  64. package/dist/protocols/index.d.ts +3 -0
  65. package/dist/protocols/index.js +3 -0
  66. package/dist/protocols/meta-images.d.ts +7 -1
  67. package/dist/protocols/meta-images.js +10 -8
  68. package/dist/protocols/meta-messages.d.ts +52 -17
  69. package/dist/protocols/meta-messages.js +14 -1
  70. package/dist/protocols/meta-responses.d.ts +46 -6
  71. package/dist/protocols/meta-responses.js +29 -1
  72. package/dist/protocols/minimax-images.d.ts +25 -0
  73. package/dist/protocols/minimax-images.js +150 -0
  74. package/dist/protocols/open-responses.d.ts +212 -27
  75. package/dist/protocols/open-responses.js +116 -54
  76. package/dist/protocols/openai-chat.d.ts +1135 -31
  77. package/dist/protocols/openai-chat.js +155 -60
  78. package/dist/protocols/openai-compatible-chat.d.ts +57 -5
  79. package/dist/protocols/openai-compatible-responses.d.ts +28 -8
  80. package/dist/protocols/openai-decisions.d.ts +22 -0
  81. package/dist/protocols/openai-decisions.js +128 -0
  82. package/dist/protocols/openai-freeform.d.ts +47 -0
  83. package/dist/protocols/openai-freeform.js +54 -0
  84. package/dist/protocols/openai-images.d.ts +36 -24
  85. package/dist/protocols/openai-images.js +137 -39
  86. package/dist/protocols/openai-responses.d.ts +202 -42
  87. package/dist/protocols/openai-responses.js +49 -10
  88. package/dist/protocols/openai-speech.d.ts +0 -18
  89. package/dist/protocols/openai-speech.js +15 -5
  90. package/dist/protocols/openai-transcription.d.ts +0 -18
  91. package/dist/protocols/openai-transcription.js +3 -4
  92. package/dist/protocols/runway-video.d.ts +1 -1
  93. package/dist/protocols/runway-video.js +1 -1
  94. package/dist/protocols/shared.d.ts +9 -1
  95. package/dist/protocols/shared.js +13 -2
  96. package/dist/protocols/system-one.d.ts +101 -0
  97. package/dist/protocols/system-one.js +230 -0
  98. package/dist/protocols/utils/bedrock-cache.d.ts +2 -2
  99. package/dist/protocols/utils/bedrock-cache.js +7 -6
  100. package/dist/protocols/utils/cache.d.ts +14 -3
  101. package/dist/protocols/utils/cache.js +11 -4
  102. package/dist/protocols/utils/gemini-generate-content.d.ts +3 -3
  103. package/dist/protocols/utils/gemini-generate-content.js +10 -16
  104. package/dist/protocols/utils/gemini-json-schema.d.ts +5 -0
  105. package/dist/protocols/utils/gemini-json-schema.js +3 -3
  106. package/dist/protocols/utils/image-sizing.d.ts +31 -0
  107. package/dist/protocols/utils/image-sizing.js +73 -0
  108. package/dist/protocols/utils/media-input.d.ts +4 -5
  109. package/dist/protocols/utils/media-input.js +8 -5
  110. package/dist/protocols/utils/speech-stream.d.ts +0 -1
  111. package/dist/protocols/utils/speech-stream.js +0 -1
  112. package/dist/protocols/utils/tool-schema.js +15 -5
  113. package/dist/protocols/utils/tool-stream.d.ts +9 -0
  114. package/dist/protocols/venice-chat.d.ts +58 -4
  115. package/dist/protocols/venice-chat.js +2 -2
  116. package/dist/protocols/xai-images.d.ts +7 -2
  117. package/dist/protocols/xai-images.js +11 -5
  118. package/dist/protocols/xai-responses.d.ts +30 -3
  119. package/dist/protocols/xai-responses.js +30 -3
  120. package/dist/protocols/xai-video.d.ts +1 -1
  121. package/dist/protocols/xai-video.js +11 -8
  122. package/dist/protocols/zai-chat.d.ts +60 -4
  123. package/dist/protocols/zai-images.d.ts +3 -1
  124. package/dist/protocols/zai-images.js +12 -11
  125. package/dist/protocols/zai-messages.d.ts +52 -17
  126. package/dist/provider-error.js +23 -7
  127. package/dist/provider-package.d.ts +2 -0
  128. package/dist/providers/alibaba/images.d.ts +2 -0
  129. package/dist/providers/alibaba/images.js +1 -0
  130. package/dist/providers/alibaba.d.ts +137 -28
  131. package/dist/providers/alibaba.js +16 -8
  132. package/dist/providers/amazon-bedrock-mantle.d.ts +259 -145
  133. package/dist/providers/amazon-bedrock-mantle.js +1 -1
  134. package/dist/providers/amazon-bedrock.d.ts +34 -14
  135. package/dist/providers/amazon-bedrock.js +11 -11
  136. package/dist/providers/anthropic-compatible.d.ts +53 -18
  137. package/dist/providers/anthropic.d.ts +53 -18
  138. package/dist/providers/anthropic.js +1 -1
  139. package/dist/providers/azure/images.d.ts +2 -0
  140. package/dist/providers/azure/images.js +1 -0
  141. package/dist/providers/azure.d.ts +129 -24
  142. package/dist/providers/azure.js +19 -1
  143. package/dist/providers/baseten/decisions.d.ts +2 -0
  144. package/dist/providers/baseten/decisions.js +1 -0
  145. package/dist/providers/baseten.d.ts +124 -12
  146. package/dist/providers/baseten.js +41 -8
  147. package/dist/providers/cerebras.d.ts +115 -11
  148. package/dist/providers/cerebras.js +1 -1
  149. package/dist/providers/cloudflare-ai-gateway/decisions.d.ts +2 -0
  150. package/dist/providers/cloudflare-ai-gateway/decisions.js +1 -0
  151. package/dist/providers/cloudflare-ai-gateway.d.ts +290 -60
  152. package/dist/providers/cloudflare-ai-gateway.js +32 -4
  153. package/dist/providers/cloudflare-workers-ai/decisions.d.ts +2 -0
  154. package/dist/providers/cloudflare-workers-ai/decisions.js +1 -0
  155. package/dist/providers/cloudflare-workers-ai/images.d.ts +2 -0
  156. package/dist/providers/cloudflare-workers-ai/images.js +1 -0
  157. package/dist/providers/cloudflare-workers-ai.d.ts +128 -12
  158. package/dist/providers/cloudflare-workers-ai.js +45 -9
  159. package/dist/providers/cohere/chat.d.ts +1 -1
  160. package/dist/providers/cohere/chat.js +1 -1
  161. package/dist/providers/cohere.d.ts +115 -11
  162. package/dist/providers/cohere.js +1 -1
  163. package/dist/providers/deepinfra.d.ts +115 -11
  164. package/dist/providers/deepinfra.js +1 -1
  165. package/dist/providers/deepseek.d.ts +115 -11
  166. package/dist/providers/deepseek.js +1 -1
  167. package/dist/providers/digitalocean/decisions.d.ts +2 -0
  168. package/dist/providers/digitalocean/decisions.js +1 -0
  169. package/dist/providers/digitalocean/images.d.ts +2 -0
  170. package/dist/providers/digitalocean/images.js +1 -0
  171. package/dist/providers/digitalocean/responses.d.ts +4 -0
  172. package/dist/providers/digitalocean/responses.js +1 -0
  173. package/dist/providers/digitalocean.d.ts +390 -20
  174. package/dist/providers/digitalocean.js +53 -11
  175. package/dist/providers/fireworks.d.ts +115 -11
  176. package/dist/providers/fireworks.js +1 -1
  177. package/dist/providers/google/images.d.ts +2 -0
  178. package/dist/providers/google/images.js +1 -0
  179. package/dist/providers/google/interactions.d.ts +1 -1
  180. package/dist/providers/google/interactions.js +1 -1
  181. package/dist/providers/google-vertex/images.d.ts +2 -0
  182. package/dist/providers/google-vertex/images.js +1 -0
  183. package/dist/providers/google-vertex-chat.d.ts +57 -5
  184. package/dist/providers/google-vertex-chat.js +1 -1
  185. package/dist/providers/google-vertex-interactions.d.ts +1 -1
  186. package/dist/providers/google-vertex-interactions.js +1 -1
  187. package/dist/providers/google-vertex-messages.d.ts +53 -18
  188. package/dist/providers/google-vertex-messages.js +1 -1
  189. package/dist/providers/google-vertex-mistral.d.ts +1 -1
  190. package/dist/providers/google-vertex-mistral.js +1 -1
  191. package/dist/providers/google-vertex-responses.d.ts +24 -4
  192. package/dist/providers/google-vertex-responses.js +1 -1
  193. package/dist/providers/google-vertex.d.ts +4 -2
  194. package/dist/providers/google-vertex.js +30 -13
  195. package/dist/providers/google.d.ts +6 -5
  196. package/dist/providers/google.js +15 -8
  197. package/dist/providers/groq.d.ts +119 -15
  198. package/dist/providers/groq.js +1 -7
  199. package/dist/providers/index.d.ts +0 -4
  200. package/dist/providers/index.js +0 -4
  201. package/dist/providers/meta/images.d.ts +2 -0
  202. package/dist/providers/meta/images.js +1 -0
  203. package/dist/providers/meta.d.ts +254 -146
  204. package/dist/providers/meta.js +2 -1
  205. package/dist/providers/minimax/chat.d.ts +1 -1
  206. package/dist/providers/minimax/chat.js +1 -1
  207. package/dist/providers/minimax/images.d.ts +3 -0
  208. package/dist/providers/minimax/images.js +1 -0
  209. package/dist/providers/minimax/responses.d.ts +1 -1
  210. package/dist/providers/minimax/responses.js +1 -1
  211. package/dist/providers/minimax.d.ts +139 -26
  212. package/dist/providers/minimax.js +22 -9
  213. package/dist/providers/mistral.d.ts +3 -3
  214. package/dist/providers/mistral.js +1 -1
  215. package/dist/providers/moonshot/messages.d.ts +1 -1
  216. package/dist/providers/moonshot/messages.js +1 -1
  217. package/dist/providers/moonshot/responses.d.ts +1 -1
  218. package/dist/providers/moonshot/responses.js +1 -1
  219. package/dist/providers/moonshot.d.ts +132 -25
  220. package/dist/providers/moonshot.js +1 -1
  221. package/dist/providers/openai/images.d.ts +2 -0
  222. package/dist/providers/openai/images.js +1 -0
  223. package/dist/providers/openai-compatible/images.d.ts +2 -0
  224. package/dist/providers/openai-compatible/images.js +1 -0
  225. package/dist/providers/openai-compatible-responses.d.ts +24 -4
  226. package/dist/providers/openai-compatible.d.ts +62 -8
  227. package/dist/providers/openai-compatible.js +29 -10
  228. package/dist/providers/openai-options.d.ts +3 -1
  229. package/dist/providers/openai.d.ts +103 -18
  230. package/dist/providers/openai.js +23 -5
  231. package/dist/providers/opencode/decisions.d.ts +2 -0
  232. package/dist/providers/opencode/decisions.js +1 -0
  233. package/dist/providers/opencode.d.ts +11 -12
  234. package/dist/providers/opencode.js +10 -8
  235. package/dist/providers/openrouter/decisions.d.ts +2 -0
  236. package/dist/providers/openrouter/decisions.js +1 -0
  237. package/dist/providers/openrouter/images.d.ts +2 -0
  238. package/dist/providers/openrouter/images.js +1 -0
  239. package/dist/providers/openrouter/responses.d.ts +4 -0
  240. package/dist/providers/openrouter/responses.js +1 -0
  241. package/dist/providers/openrouter.d.ts +446 -35
  242. package/dist/providers/openrouter.js +78 -27
  243. package/dist/providers/togetherai.d.ts +115 -11
  244. package/dist/providers/togetherai.js +1 -1
  245. package/dist/providers/typesafe-ai/decisions.d.ts +2 -0
  246. package/dist/providers/typesafe-ai/decisions.js +1 -0
  247. package/dist/providers/typesafe-ai.d.ts +11 -12
  248. package/dist/providers/typesafe-ai.js +10 -8
  249. package/dist/providers/venice/responses.d.ts +4 -0
  250. package/dist/providers/venice/responses.js +1 -0
  251. package/dist/providers/venice.d.ts +261 -9
  252. package/dist/providers/venice.js +33 -17
  253. package/dist/providers/vercel-ai-gateway/decisions.d.ts +2 -0
  254. package/dist/providers/vercel-ai-gateway/decisions.js +1 -0
  255. package/dist/providers/vercel-ai-gateway/images.d.ts +2 -0
  256. package/dist/providers/vercel-ai-gateway/images.js +1 -0
  257. package/dist/providers/vercel-ai-gateway.d.ts +16 -22
  258. package/dist/providers/vercel-ai-gateway.js +41 -85
  259. package/dist/providers/xai/images.d.ts +2 -0
  260. package/dist/providers/xai/images.js +1 -0
  261. package/dist/providers/xai.d.ts +66 -12
  262. package/dist/providers/xai.js +15 -8
  263. package/dist/providers/zai/images.d.ts +2 -0
  264. package/dist/providers/zai/images.js +1 -0
  265. package/dist/providers/zai-coding-plan/messages.d.ts +1 -1
  266. package/dist/providers/zai-coding-plan/messages.js +1 -1
  267. package/dist/providers/zai-coding-plan/responses.d.ts +1 -1
  268. package/dist/providers/zai-coding-plan/responses.js +1 -1
  269. package/dist/providers/zai-coding-plan.d.ts +132 -25
  270. package/dist/providers/zai-coding-plan.js +1 -1
  271. package/dist/providers/zai.d.ts +62 -9
  272. package/dist/providers/zai.js +15 -8
  273. package/dist/route/auth.d.ts +1 -1
  274. package/dist/route/client.d.ts +2 -2
  275. package/dist/route/client.js +26 -4
  276. package/dist/route/decision.d.ts +58 -0
  277. package/dist/route/decision.js +75 -0
  278. package/dist/route/executor.d.ts +1 -1
  279. package/dist/route/framing.d.ts +2 -0
  280. package/dist/route/index.d.ts +3 -0
  281. package/dist/route/index.js +3 -0
  282. package/dist/route/media-protocol.d.ts +3 -4
  283. package/dist/route/media-protocol.js +12 -8
  284. package/dist/route/media.d.ts +6 -2
  285. package/dist/route/media.js +8 -6
  286. package/dist/route/transport/http.js +1 -0
  287. package/dist/route/transport/index.d.ts +1 -0
  288. package/dist/schema/events.d.ts +148 -6
  289. package/dist/schema/events.js +20 -0
  290. package/dist/schema/messages.d.ts +41 -3
  291. package/dist/schema/messages.js +23 -0
  292. package/dist/schema/options.d.ts +5 -3
  293. package/dist/schema/options.js +8 -3
  294. package/dist/speech-client.d.ts +53 -14
  295. package/dist/speech-client.js +0 -1
  296. package/dist/speech.d.ts +0 -135
  297. package/dist/speech.js +2 -4
  298. package/dist/testing/decision.d.ts +16 -0
  299. package/dist/testing/decision.js +20 -0
  300. package/dist/testing/image.d.ts +14 -0
  301. package/dist/testing/image.js +12 -0
  302. package/dist/testing/media.d.ts +18 -0
  303. package/dist/testing/media.js +36 -0
  304. package/dist/testing/script.d.ts +28 -0
  305. package/dist/testing/script.js +60 -0
  306. package/dist/testing/speech.d.ts +14 -0
  307. package/dist/testing/speech.js +12 -0
  308. package/dist/testing/transcription.d.ts +14 -0
  309. package/dist/testing/transcription.js +12 -0
  310. package/dist/testing/video.d.ts +14 -0
  311. package/dist/testing/video.js +12 -0
  312. package/dist/testing.d.ts +35 -45
  313. package/dist/testing.js +14 -75
  314. package/dist/tool.d.ts +12 -1
  315. package/dist/tool.js +10 -2
  316. package/dist/transcription-client.d.ts +69 -14
  317. package/dist/transcription.d.ts +0 -135
  318. package/dist/transcription.js +1 -1
  319. package/dist/utils/media-type.js +22 -1
  320. package/dist/video-client.d.ts +46 -14
  321. package/dist/video-client.js +0 -1
  322. package/dist/video.d.ts +1 -136
  323. package/dist/video.js +3 -5
  324. package/package.json +497 -11
  325. package/dist/experimental/evaluation-client.d.ts +0 -21
  326. package/dist/experimental/evaluation-client.js +0 -64
  327. package/dist/experimental/evaluation.d.ts +0 -242
  328. package/dist/experimental/evaluation.js +0 -108
  329. package/dist/experimental/system-one.d.ts +0 -16
  330. package/dist/experimental/system-one.js +0 -135
  331. package/dist/promise.d.ts +0 -1021
  332. package/dist/promise.js +0 -101
  333. package/dist/protocols/bfl-images.d.ts +0 -38
  334. package/dist/protocols/bfl-images.js +0 -153
  335. package/dist/protocols/fal-images.d.ts +0 -25
  336. package/dist/protocols/fal-images.js +0 -104
  337. package/dist/protocols/fal-video.d.ts +0 -29
  338. package/dist/protocols/fal-video.js +0 -73
  339. package/dist/protocols/replicate-images.d.ts +0 -28
  340. package/dist/protocols/replicate-images.js +0 -127
  341. package/dist/protocols/stability-images.d.ts +0 -39
  342. package/dist/protocols/stability-images.js +0 -136
  343. package/dist/protocols/utils/fal-queue.d.ts +0 -26
  344. package/dist/protocols/utils/fal-queue.js +0 -67
  345. package/dist/provider.d.ts +0 -23
  346. package/dist/provider.js +0 -2
  347. package/dist/providers/black-forest-labs.d.ts +0 -21
  348. package/dist/providers/black-forest-labs.js +0 -23
  349. package/dist/providers/fal.d.ts +0 -24
  350. package/dist/providers/fal.js +0 -26
  351. package/dist/providers/replicate.d.ts +0 -21
  352. package/dist/providers/replicate.js +0 -17
  353. package/dist/providers/stability.d.ts +0 -23
  354. package/dist/providers/stability.js +0 -18
@@ -0,0 +1,128 @@
1
+ import { Effect, Schema } from "effect";
2
+ import { DecisionResponse, DecisionUsage } from "../decision.js";
3
+ import { DecisionRoute } from "../route/decision.js";
4
+ import { Endpoint } from "../route/endpoint.js";
5
+ import { MediaProtocol } from "../route/media-protocol.js";
6
+ import { AIError, UnsupportedOperationError, mergeJsonRecords } from "../schema/index.js";
7
+ import { encodeJson } from "../utils/json.js";
8
+ import { OpenResponses } from "./open-responses.js";
9
+ import { ProviderShared } from "./shared.js";
10
+ const ID = "openai-decisions";
11
+ const NAME = "OpenAI Decisions";
12
+ export const DEFAULT_BASE_URL = "https://api.openai.com/v1";
13
+ export const PATH = "/decisions";
14
+ const Options = Schema.Struct({
15
+ promptCacheKey: Schema.optional(Schema.String),
16
+ promptCacheOptions: Schema.optional(Schema.Struct({ mode: Schema.optional(Schema.String), ttl: Schema.optional(Schema.String) })),
17
+ safetyIdentifier: Schema.optional(Schema.String),
18
+ });
19
+ const Probability = Schema.Number.check(Schema.isBetween({ minimum: 0, maximum: 1 }));
20
+ const ChoiceValue = Schema.Union([Schema.String, Schema.Boolean]);
21
+ const Answer = Schema.Union([
22
+ Schema.Struct({ type: Schema.Literal("predicate"), name: Schema.String, probability: Probability }),
23
+ Schema.Struct({
24
+ type: Schema.Literal("choice"),
25
+ name: Schema.String,
26
+ choice: ChoiceValue,
27
+ probabilities: Schema.Array(Schema.Struct({ value: ChoiceValue, probability: Probability })),
28
+ confidence: Probability,
29
+ }),
30
+ Schema.Struct({
31
+ type: Schema.Literal("score"),
32
+ name: Schema.String,
33
+ score: Schema.Number,
34
+ probabilities: Schema.Array(Schema.Struct({ value: Schema.Int, label: Schema.String, probability: Probability })),
35
+ confidence: Probability,
36
+ }),
37
+ Schema.Struct({ type: Schema.Literal("refusal"), name: Schema.String, message: Schema.optional(Schema.String) }),
38
+ ]);
39
+ const Response = Schema.Struct({
40
+ model: Schema.String,
41
+ answers: Schema.Array(Answer),
42
+ usage: Schema.optional(OpenResponses.OpenResponsesUsage),
43
+ });
44
+ const decodeOptions = ProviderShared.validateWith(Schema.decodeUnknownEffect(Options));
45
+ const fromRequest = Effect.fn("OpenAIDecisions.fromRequest")(function* (request) {
46
+ const options = yield* decodeOptions(request.providerOptions ?? {});
47
+ const { promptCacheKey: _, promptCacheOptions: __, safetyIdentifier: ___, ...native } = request.providerOptions ?? {};
48
+ return {
49
+ ...mergeJsonRecords({
50
+ prompt_cache_key: options.promptCacheKey,
51
+ prompt_cache_options: options.promptCacheOptions,
52
+ safety_identifier: options.safetyIdentifier,
53
+ ...native,
54
+ }, request.http?.body),
55
+ model: request.model.id,
56
+ input: [{ role: "user", content: yield* Effect.forEach(request.input, (part) => inputPart(request, part)) }],
57
+ questions: request.questions,
58
+ };
59
+ });
60
+ // `input_json` takes an object or a list of objects; other JSON values go as text.
61
+ const inputPart = (request, part) => {
62
+ if (part.type === "text")
63
+ return Effect.succeed({ type: "input_text", text: part.text });
64
+ if (part.type === "json")
65
+ return Effect.succeed(isObject(part.value) || (Array.isArray(part.value) && part.value.every(isObject))
66
+ ? { type: "input_json", data: part.value }
67
+ : { type: "input_text", text: encodeJson(part.value) });
68
+ if (part.media.kind !== "image")
69
+ return Effect.fail(new AIError({
70
+ reason: new UnsupportedOperationError({
71
+ operation: "decision.media",
72
+ provider: request.model.provider,
73
+ route: request.model.route.id,
74
+ message: `${NAME} takes images only; got ${part.media.kind} media`,
75
+ }),
76
+ }));
77
+ return ProviderShared.mediaReference(part.media, undefined, `${NAME} image input`).pipe(Effect.map((reference) => ({ type: "input_image", image_url: reference.value })));
78
+ };
79
+ const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
80
+ const decodeDocument = MediaProtocol.identity({ id: ID, name: NAME, provider: "openai" }).decodeJson(Response);
81
+ export const protocol = DecisionRoute.protocol({
82
+ id: ID,
83
+ name: NAME,
84
+ body: { from: fromRequest },
85
+ response: {
86
+ decode: Effect.fn("OpenAIDecisions.decodeResponse")(function* (response, context) {
87
+ const output = yield* decodeDocument(response);
88
+ const answers = output.value.answers.map((answer) => answer.type === "refusal"
89
+ ? {
90
+ name: answer.name,
91
+ type: "error",
92
+ reason: "refusal",
93
+ ...(answer.message === undefined ? {} : { message: answer.message }),
94
+ }
95
+ : answer);
96
+ const byName = new Map(answers.map((answer) => [answer.name, answer]));
97
+ const ordered = context.request.questions.flatMap((question) => byName.get(question.name) ?? []);
98
+ const usage = OpenResponses.mapUsage(output.value.usage, context.providerMetadataKey);
99
+ return new DecisionResponse({
100
+ answers: ordered.length === answers.length ? ordered : answers,
101
+ usage: usage === undefined
102
+ ? undefined
103
+ : new DecisionUsage({
104
+ inputTokens: usage.inputTokens,
105
+ outputTokens: usage.outputTokens,
106
+ totalTokens: usage.totalTokens,
107
+ cost: usage.cost,
108
+ }),
109
+ providerMetadata: {
110
+ [context.providerMetadataKey]: {
111
+ model: output.value.model,
112
+ ...(output.value.usage === undefined ? {} : { usage: output.value.usage }),
113
+ },
114
+ },
115
+ });
116
+ }),
117
+ },
118
+ });
119
+ export const route = DecisionRoute.make({
120
+ id: ID,
121
+ provider: "openai",
122
+ protocol,
123
+ endpoint: Endpoint.path(PATH, { baseURL: DEFAULT_BASE_URL }),
124
+ });
125
+ export const OpenAIDecisions = {
126
+ protocol,
127
+ route,
128
+ };
@@ -0,0 +1,47 @@
1
+ import { ToolDefinition, type Freeform, type LLMEvent, type LLMRequest, type ProviderMetadata } from "../schema/index.js";
2
+ import { ToolStream } from "./utils/tool-stream.js";
3
+ export interface Custom {
4
+ /** The tool's one required string parameter, which the raw text fills. */
5
+ readonly field: string;
6
+ readonly format: Freeform;
7
+ }
8
+ /** How a tool goes out: a custom tool when it declares `freeform` with one required string parameter. */
9
+ export declare const resolve: (tool: ToolDefinition) => Custom | undefined;
10
+ /** Custom tools in this request, by flattened tool name. */
11
+ export declare const tools: (request: LLMRequest) => ReadonlyMap<string, Custom>;
12
+ /** The format's grammar, or `undefined` for unconstrained text. */
13
+ export declare const grammar: (format: Freeform) => {
14
+ syntax: "lark" | "regex";
15
+ definition: string;
16
+ } | undefined;
17
+ /** Raw text replayed for a past call: its field, or the whole input as JSON when the field is not a string. */
18
+ export declare const toRaw: (custom: Custom, input: unknown) => string;
19
+ /** JSON arguments for a raw call. A call to an undeclared custom tool fills `input`. */
20
+ export declare const fromRaw: (custom: Custom | undefined, raw: string) => string;
21
+ /** The opening fragment, `{"field":"`, followed by the escaped first text. */
22
+ export declare const streamStart: (custom: Custom | undefined, raw?: string) => string;
23
+ export declare const streamDelta: (raw: string) => string;
24
+ /**
25
+ * Close the JSON fragment of each open custom call. With a `final` raw input, a call only closes when its fragments
26
+ * decode to it, so an authoritative final input that disagrees replaces the streamed one instead.
27
+ */
28
+ export declare const close: <K extends string | number>(tools: ToolStream.State<K>, keys: Iterable<K>, final?: {
29
+ readonly custom: Custom | undefined;
30
+ readonly raw: string;
31
+ }) => {
32
+ readonly tools: ToolStream.State<K>;
33
+ readonly events: ReadonlyArray<LLMEvent>;
34
+ };
35
+ /** Provider metadata marking a call that arrived as a custom tool call. */
36
+ export declare const metadata: (itemId: string, custom: boolean) => {
37
+ itemId: string;
38
+ custom: boolean;
39
+ } | {
40
+ itemId: string;
41
+ };
42
+ /**
43
+ * Whether a replayed call keeps its item id: only when it goes out as the type it arrived as, since OpenAI item ids
44
+ * name their type (`fc_`, `ctc_`). The `call_id` always survives.
45
+ */
46
+ export declare const keepsItemID: (providerMetadata: ProviderMetadata | undefined, key: string, custom: boolean) => boolean;
47
+ export * as OpenAIFreeform from "./openai-freeform.js";
@@ -0,0 +1,54 @@
1
+ import { Option, Schema } from "effect";
2
+ import { ToolDefinition, } from "../schema/index.js";
3
+ import { encodeJson, flattenTools, isRecord } from "./shared.js";
4
+ import { ToolStream } from "./utils/tool-stream.js";
5
+ /** How a tool goes out: a custom tool when it declares `freeform` with one required string parameter. */
6
+ export const resolve = (tool) => {
7
+ const field = ToolDefinition.freeformField(tool.inputSchema);
8
+ if (tool.freeform === undefined || tool.native !== undefined || field === undefined)
9
+ return undefined;
10
+ return { field, format: tool.freeform };
11
+ };
12
+ /** Custom tools in this request, by flattened tool name. */
13
+ export const tools = (request) => new Map(flattenTools(request.tools).flatMap((tool) => {
14
+ const custom = resolve(tool);
15
+ return custom ? [[tool.name, custom]] : [];
16
+ }));
17
+ /** The format's grammar, or `undefined` for unconstrained text. */
18
+ export const grammar = (format) => format.type === "text"
19
+ ? undefined
20
+ : { syntax: format.type, definition: format.type === "regex" ? format.pattern : format.grammar };
21
+ /** Raw text replayed for a past call: its field, or the whole input as JSON when the field is not a string. */
22
+ export const toRaw = (custom, input) => {
23
+ const value = isRecord(input) ? input[custom.field] : undefined;
24
+ return typeof value === "string" ? value : encodeJson(input ?? {});
25
+ };
26
+ /** JSON arguments for a raw call. A call to an undeclared custom tool fills `input`. */
27
+ export const fromRaw = (custom, raw) => encodeJson({ [field(custom)]: raw });
28
+ const field = (custom) => custom?.field ?? "input";
29
+ // Streamed raw text is re-encoded as JSON-argument fragments, so the tool-input events match a JSON tool's.
30
+ /** The opening fragment, `{"field":"`, followed by the escaped first text. */
31
+ export const streamStart = (custom, raw = "") => `{${encodeJson(field(custom))}:"${streamDelta(raw)}`;
32
+ export const streamDelta = (raw) => encodeJson(raw).slice(1, -1);
33
+ const STREAM_END = '"}';
34
+ const decodeArguments = Schema.decodeUnknownOption(Schema.fromJsonString(Schema.Record(Schema.String, Schema.Unknown)));
35
+ /**
36
+ * Close the JSON fragment of each open custom call. With a `final` raw input, a call only closes when its fragments
37
+ * decode to it, so an authoritative final input that disagrees replaces the streamed one instead.
38
+ */
39
+ export const close = (tools, keys, final) => [...keys].reduce((result, key) => {
40
+ const pending = result.tools[key];
41
+ const streamed = pending && Option.getOrUndefined(decodeArguments(`${pending.input}${STREAM_END}`));
42
+ if (!pending || (final !== undefined && streamed?.[field(final.custom)] !== final.raw))
43
+ return result;
44
+ const appended = ToolStream.append(result.tools, key, STREAM_END);
45
+ return appended ? { tools: appended.tools, events: [...result.events, ...appended.events] } : result;
46
+ }, { tools, events: [] });
47
+ /** Provider metadata marking a call that arrived as a custom tool call. */
48
+ export const metadata = (itemId, custom) => (custom ? { itemId, custom: true } : { itemId });
49
+ /**
50
+ * Whether a replayed call keeps its item id: only when it goes out as the type it arrived as, since OpenAI item ids
51
+ * name their type (`fc_`, `ctc_`). The `call_id` always survives.
52
+ */
53
+ export const keepsItemID = (providerMetadata, key, custom) => (providerMetadata?.[key]?.custom === true) === custom;
54
+ export * as OpenAIFreeform from "./openai-freeform.js";
@@ -1,13 +1,19 @@
1
+ import { Schema } from "effect";
1
2
  import { ImageModel, type ImageRequestFor } from "../image.js";
2
3
  import { Media } from "../media.js";
3
4
  import { MediaProtocol } from "../route/media-protocol.js";
4
5
  import { MediaRoute } from "../route/media.js";
5
- import { type MediaUsage, type OpenString } from "../schema/index.js";
6
+ import { type OpenString } from "../schema/index.js";
6
7
  export declare const DEFAULT_BASE_URL = "https://api.openai.com/v1";
7
8
  export declare const PATH = "/images/generations";
8
9
  export declare const EDIT_PATH = "/images/edits";
9
- /** Provider-native options. Common fields (`n`, `size`, `format`, `images`, `mask`) live on the request. */
10
+ /** Provider-native options. Common fields (`n`, `aspect`, `resolution`, `images`) live on the request. */
10
11
  export type OpenAIImageOptions = {
12
+ /** Exact `WIDTHxHEIGHT` or `auto`; it replaces `aspect` and `resolution`, so setting both fails. */
13
+ readonly size?: OpenString<"auto" | "1024x1024" | "1536x1024" | "1024x1536">;
14
+ readonly outputFormat?: OpenString<"png" | "jpeg" | "webp">;
15
+ /** Inpainting mask for the first input image. */
16
+ readonly mask?: Media.Asset;
11
17
  readonly quality?: OpenString<"auto" | "low" | "medium" | "high" | "standard" | "hd">;
12
18
  readonly background?: OpenString<"auto" | "opaque" | "transparent">;
13
19
  readonly moderation?: OpenString<"auto" | "low">;
@@ -16,10 +22,16 @@ export type OpenAIImageOptions = {
16
22
  readonly partialImages?: number;
17
23
  } & Record<string, unknown>;
18
24
  export type Request = ImageRequestFor<OpenAIImageOptions>;
19
- /** `generate` reads the whole JSON response as one frame, with the requested format for responses that omit it. */
25
+ declare const Usage: Schema.Struct<{
26
+ readonly input_tokens: Schema.optional<Schema.Number>;
27
+ readonly output_tokens: Schema.optional<Schema.Number>;
28
+ readonly total_tokens: Schema.optional<Schema.Number>;
29
+ readonly input_tokens_details: Schema.optional<Schema.$Record<Schema.String, Schema.Unknown>>;
30
+ readonly output_tokens_details: Schema.optional<Schema.$Record<Schema.String, Schema.Unknown>>;
31
+ }>;
32
+ /** `generate` reads the whole JSON response as one frame. */
20
33
  type Frame = string | {
21
34
  readonly document: string;
22
- readonly requested: string | undefined;
23
35
  };
24
36
  interface State {
25
37
  readonly completed: number;
@@ -27,8 +39,17 @@ interface State {
27
39
  readonly size?: string;
28
40
  readonly quality?: string;
29
41
  readonly background?: string;
30
- readonly usage?: MediaUsage;
42
+ readonly usage?: Schema.Schema.Type<typeof Usage>;
31
43
  }
44
+ /** The body fields `aspect` and `resolution` lower to; gateways that read other fields than `size` pass their own. */
45
+ export type OpenAIImageSizing = (request: Request) => Record<string, unknown> | undefined;
46
+ /**
47
+ * How input images travel. `edits` is OpenAI's `/images/edits`, uploading owned bytes as multipart; `json-edits` sends
48
+ * every edit there as JSON with data URLs, for hosts that reject multipart (the ChatGPT backend); `references` keeps
49
+ * every request on `/images/generations` and lists them as `input_references`, for gateways without an edits endpoint
50
+ * (OpenRouter).
51
+ */
52
+ export type OpenAIImageInput = "edits" | "json-edits" | "references";
32
53
  export declare const protocol: MediaProtocol.Streamed<Request, {
33
54
  readonly type: "image-partial";
34
55
  readonly index: number;
@@ -68,22 +89,21 @@ export declare const protocol: MediaProtocol.Streamed<Request, {
68
89
  readonly [x: string]: unknown;
69
90
  } | undefined;
70
91
  } | undefined;
71
- readonly notices?: readonly {
72
- readonly type: "filtered" | "moderated" | "other";
73
- readonly message: string;
74
- readonly providerMetadata?: {
75
- readonly [x: string]: {
76
- readonly [x: string]: unknown;
77
- };
78
- } | undefined;
79
- }[] | undefined;
80
92
  readonly providerMetadata?: {
81
93
  readonly [x: string]: {
82
94
  readonly [x: string]: unknown;
83
95
  };
84
96
  } | undefined;
85
97
  }, Frame, State>;
86
- export declare const model: (input: MediaRoute.ModelInput) => ImageModel<OpenAIImageOptions>;
98
+ /**
99
+ * `provider` attributes models, refs, and metadata to an OpenAI-compatible host; it defaults to `openai`. `sizing`
100
+ * replaces the `size` that `aspect` and `resolution` lower to, and `imageInput` how input images are sent.
101
+ */
102
+ export declare const model: (input: MediaRoute.ModelInput & {
103
+ readonly provider?: string;
104
+ readonly sizing?: OpenAIImageSizing;
105
+ readonly imageInput?: OpenAIImageInput;
106
+ }) => ImageModel<OpenAIImageOptions>;
87
107
  export declare const OpenAIImages: {
88
108
  readonly protocol: MediaProtocol.Streamed<Request, {
89
109
  readonly type: "image-partial";
@@ -124,15 +144,6 @@ export declare const OpenAIImages: {
124
144
  readonly [x: string]: unknown;
125
145
  } | undefined;
126
146
  } | undefined;
127
- readonly notices?: readonly {
128
- readonly type: "filtered" | "moderated" | "other";
129
- readonly message: string;
130
- readonly providerMetadata?: {
131
- readonly [x: string]: {
132
- readonly [x: string]: unknown;
133
- };
134
- } | undefined;
135
- }[] | undefined;
136
147
  readonly providerMetadata?: {
137
148
  readonly [x: string]: {
138
149
  readonly [x: string]: unknown;
@@ -140,5 +151,6 @@ export declare const OpenAIImages: {
140
151
  } | undefined;
141
152
  }, Frame, State>;
142
153
  readonly model: typeof model;
154
+ readonly pixelSize: OpenAIImageSizing;
143
155
  };
144
156
  export {};
@@ -1,11 +1,13 @@
1
- import { Effect, Schema, Stream } from "effect";
1
+ import { Effect, Schema, SchemaGetter, Stream } from "effect";
2
2
  import { ImageFinishEvent, ImageModel, ImageOutputEvent, ImagePartialEvent, } from "../image.js";
3
3
  import { Media } from "../media.js";
4
+ import { classifyProviderFailure } from "../provider-error.js";
4
5
  import { Framing } from "../route/framing.js";
5
6
  import { MediaProtocol } from "../route/media-protocol.js";
6
7
  import { MediaRoute } from "../route/media.js";
7
- import { mergeJsonRecords } from "../schema/index.js";
8
- import { ProviderShared } from "./shared.js";
8
+ import { AIError, mergeJsonRecords, ProviderID, tokenUsage } from "../schema/index.js";
9
+ import { optionalNull, ProviderShared } from "./shared.js";
10
+ import { ImageSizing } from "./utils/image-sizing.js";
9
11
  import { MediaInput } from "./utils/media-input.js";
10
12
  const route = MediaProtocol.identity({ id: "openai-images", name: "OpenAI Images", provider: "openai" });
11
13
  export const DEFAULT_BASE_URL = "https://api.openai.com/v1";
@@ -29,13 +31,28 @@ const Settings = {
29
31
  background: Schema.optional(Schema.String),
30
32
  };
31
33
  const OpenAIImageResponse = Schema.Struct({
32
- data: Schema.Array(Schema.Struct({ b64_json: Schema.String })),
34
+ // GPT Image models always return `b64_json`; compatible hosts that default to `url` can return either.
35
+ data: Schema.Array(Schema.Struct({ b64_json: optionalNull(Schema.String), url: optionalNull(Schema.String) })),
33
36
  ...Settings,
34
37
  usage: Schema.optional(Usage),
35
38
  });
36
39
  // ---------------------------------------------------------------------------
37
40
  // 3. Streaming event schema
38
41
  // ---------------------------------------------------------------------------
42
+ const EVENT_TYPES = new Set([
43
+ "image_generation.partial_image",
44
+ "image_edit.partial_image",
45
+ "image_generation.completed",
46
+ "image_edit.completed",
47
+ "error",
48
+ ]);
49
+ /** OpenAI may add stream event types; frames outside `EVENT_TYPES` are ignored, while a malformed known type still fails decoding. */
50
+ const UnknownEvent = Schema.Struct({
51
+ type: Schema.String.check(Schema.makeFilter((type) => !EVENT_TYPES.has(type))),
52
+ }).pipe(Schema.decodeTo(Schema.Struct({ type: Schema.Literal("unknown"), rawType: Schema.String }), {
53
+ decode: SchemaGetter.transform((event) => ({ type: "unknown", rawType: event.type })),
54
+ encode: SchemaGetter.forbidden(() => "Unknown OpenAI Images stream events are decode-only"),
55
+ }));
39
56
  const StreamEvent = Schema.Union([
40
57
  Schema.Struct({
41
58
  type: Schema.Literals(["image_generation.partial_image", "image_edit.partial_image"]),
@@ -51,6 +68,11 @@ const StreamEvent = Schema.Union([
51
68
  output_format: Schema.String,
52
69
  usage: Schema.optional(Usage),
53
70
  }),
71
+ Schema.Struct({
72
+ type: Schema.Literal("error"),
73
+ error: Schema.optional(Schema.Struct({ message: Schema.optional(Schema.String) })),
74
+ }),
75
+ UnknownEvent,
54
76
  ]);
55
77
  const decodeEvent = route.decodeFrame(StreamEvent);
56
78
  const decodeDocument = Schema.decodeUnknownEffect(Schema.fromJsonString(OpenAIImageResponse));
@@ -62,8 +84,45 @@ const RESERVED_FORM_FIELDS = new Set(["model", "prompt", "image", "image[]", "im
62
84
  const nativeOptions = (options) => {
63
85
  if (!options)
64
86
  return undefined;
65
- const { outputCompression, partialImages: _, ...native } = options;
66
- return { output_compression: outputCompression, ...native };
87
+ const { outputCompression, outputFormat, partialImages: _, mask: __, ...native } = options;
88
+ // `response_format: null` drops a provider's default, for hosts that reject the field.
89
+ return {
90
+ output_compression: outputCompression,
91
+ output_format: outputFormat,
92
+ ...native,
93
+ response_format: native.response_format ?? undefined,
94
+ };
95
+ };
96
+ /**
97
+ * `gpt-image-1`, `chatgpt-image` and DALL·E take a fixed list, `gpt-image-2` and later any size within limits. Other
98
+ * models are gateway-hosted (`bfl/flux-2-pro`); the gateway passes `size` through to them as is.
99
+ */
100
+ const sizes = (model) => {
101
+ const id = model.slice(model.lastIndexOf("/") + 1);
102
+ if (id.startsWith("dall-e-2"))
103
+ return [256, 512, 1024].map((edge) => ({ width: edge, height: edge }));
104
+ if (id.startsWith("dall-e-3"))
105
+ return [
106
+ { width: 1024, height: 1024 },
107
+ { width: 1792, height: 1024 },
108
+ { width: 1024, height: 1792 },
109
+ ];
110
+ if (/^(gpt-image-1|chatgpt-image)/.test(id))
111
+ return [
112
+ { width: 1024, height: 1024 },
113
+ { width: 1536, height: 1024 },
114
+ { width: 1024, height: 1536 },
115
+ ];
116
+ if (id.startsWith("gpt-image-"))
117
+ return { multiple: 16, maxEdge: 3840, minPixels: 655_360, maxPixels: 8_294_400, maxRatio: 3 };
118
+ return { multiple: 16 };
119
+ };
120
+ const pixelSize = (request) => {
121
+ if (!ImageSizing.isRequested(request))
122
+ return undefined;
123
+ const options = sizes(request.model.id);
124
+ const size = "multiple" in options ? ImageSizing.fit(request, options) : ImageSizing.nearest(request, options);
125
+ return { size: `${size.width}x${size.height}` };
67
126
  };
68
127
  const streamOptions = (request) => {
69
128
  if (request.mode !== "stream")
@@ -74,15 +133,36 @@ const streamOptions = (request) => {
74
133
  };
75
134
  const isEdit = (request) => (request.images?.length ?? 0) > 0;
76
135
  const isInline = (asset) => asset.source.type === "bytes" || asset.source.type === "base64";
77
- const reference = (asset) => ProviderShared.mediaReference(asset, route.provider, route.name).pipe(Effect.map((item) => (item.type === "ref" ? { file_id: item.value } : { image_url: item.value })));
78
- const fromRequest = Effect.fn("OpenAIImages.fromRequest")(function* (request) {
136
+ const reference = (asset, provider) => ProviderShared.mediaReference(asset, provider, route.name).pipe(Effect.map((item) => (item.type === "ref" ? { file_id: item.value } : { image_url: item.value })));
137
+ const fromRequest = Effect.fn("OpenAIImages.fromRequest")(function* (request, options) {
79
138
  const images = request.images ?? [];
80
- const mask = request.mask;
139
+ const mask = request.providerOptions?.mask;
140
+ if (options.imageInput === "references" && mask !== undefined)
141
+ return yield* route.unsupported("media.mask", `${request.model.provider} image edits take no mask`);
81
142
  if (mask !== undefined && images.length === 0)
82
143
  return yield* ProviderShared.invalidRequest("An OpenAI image mask requires at least one input image");
83
- const fields = mergeJsonRecords({ n: request.n, size: request.size, output_format: request.format, ...(yield* streamOptions(request)) }, nativeOptions(request.providerOptions), request.http?.body);
84
- // Owned bytes go through multipart edits; remote URLs and file IDs use the JSON edits body instead.
85
- if (images.length > 0 && images.every(isInline) && (mask === undefined || isInline(mask))) {
144
+ if (request.providerOptions?.size !== undefined && ImageSizing.isRequested(request))
145
+ return yield* ProviderShared.invalidRequest("OpenAI providerOptions.size replaces aspect and resolution; set one or the other");
146
+ const fields = mergeJsonRecords({
147
+ n: request.n,
148
+ ...options.sizing(request),
149
+ ...(yield* streamOptions(request)),
150
+ }, nativeOptions(request.providerOptions), request.http?.body);
151
+ if (options.imageInput === "references") {
152
+ const references = yield* Effect.forEach(images, (image) => ProviderShared.mediaReference(image, undefined, route.name));
153
+ return MediaProtocol.json(mergeJsonRecords({
154
+ model: request.model.id,
155
+ prompt: request.prompt,
156
+ input_references: references.length === 0
157
+ ? undefined
158
+ : references.map((item) => ({ type: "image_url", image_url: { url: item.value } })),
159
+ }, fields) ?? {});
160
+ }
161
+ // Owned bytes go through multipart edits; remote URLs, file IDs and `json-edits` hosts use the JSON edits body.
162
+ if (options.imageInput === "edits" &&
163
+ images.length > 0 &&
164
+ images.every(isInline) &&
165
+ (mask === undefined || isInline(mask))) {
86
166
  const form = new FormData();
87
167
  MediaInput.appendFields(form, { model: request.model.id, prompt: request.prompt }, { overlay: fields, reserved: RESERVED_FORM_FIELDS });
88
168
  const uploads = yield* Effect.forEach(images, (image) => MediaInput.inlineBytes(route.id, image));
@@ -91,8 +171,8 @@ const fromRequest = Effect.fn("OpenAIImages.fromRequest")(function* (request) {
91
171
  form.append("mask", MediaInput.blob(yield* MediaInput.inlineBytes(route.id, mask), mask.mediaType), "mask");
92
172
  return MediaProtocol.multipart(form);
93
173
  }
94
- const references = yield* Effect.forEach(images, reference);
95
- const maskReference = mask === undefined ? undefined : yield* reference(mask);
174
+ const references = yield* Effect.forEach(images, (image) => reference(image, request.model.provider));
175
+ const maskReference = mask === undefined ? undefined : yield* reference(mask, request.model.provider);
96
176
  return MediaProtocol.json(mergeJsonRecords({
97
177
  model: request.model.id,
98
178
  prompt: request.prompt,
@@ -103,21 +183,14 @@ const fromRequest = Effect.fn("OpenAIImages.fromRequest")(function* (request) {
103
183
  // ---------------------------------------------------------------------------
104
184
  // 6. Stream parsing
105
185
  // ---------------------------------------------------------------------------
106
- const requestedFormat = (body) => {
107
- if (body.type === "binary")
108
- return undefined;
109
- const value = body.type === "json" ? body.value.output_format : body.value.get("output_format");
110
- return typeof value === "string" ? value : undefined;
111
- };
112
- const usage = (value) => value === undefined
186
+ const usage = (value, provider) => value === undefined
113
187
  ? undefined
114
- : {
115
- type: "tokens",
188
+ : tokenUsage({
116
189
  input: value.input_tokens,
117
190
  output: value.output_tokens,
118
191
  total: value.total_tokens,
119
- details: { openai: value },
120
- };
192
+ details: { [provider]: value },
193
+ });
121
194
  /** `size` echoes the rendered `WIDTHxHEIGHT`; `auto` or any other value leaves the dimensions unknown. */
122
195
  const info = (format, size) => {
123
196
  const match = size?.match(/^(\d+)x(\d+)$/);
@@ -128,6 +201,15 @@ const eventImage = (frame, label, data, format, size) => MediaInput.decodedAsset
128
201
  });
129
202
  const onEvent = Effect.fnUntraced(function* (state, frame) {
130
203
  const event = yield* decodeEvent(frame);
204
+ if (event.type === "unknown")
205
+ return [state, []];
206
+ if (event.type === "error")
207
+ return yield* new AIError({
208
+ reason: classifyProviderFailure({
209
+ message: `${route.name} stream failed: ${event.error?.message ?? "unknown error"}`,
210
+ rawBody: frame,
211
+ }),
212
+ });
131
213
  const format = event.output_format;
132
214
  if ("partial_image_index" in event) {
133
215
  const image = yield* eventImage(frame, `${route.name} partial image`, event.b64_json, format, event.size);
@@ -141,7 +223,7 @@ const onEvent = Effect.fnUntraced(function* (state, frame) {
141
223
  size: event.size,
142
224
  quality: event.quality,
143
225
  background: event.background,
144
- usage: usage(event.usage),
226
+ usage: event.usage,
145
227
  },
146
228
  [ImageOutputEvent.make({ index: state.completed, image })],
147
229
  ];
@@ -149,8 +231,10 @@ const onEvent = Effect.fnUntraced(function* (state, frame) {
149
231
  const onDocument = Effect.fnUntraced(function* (frame) {
150
232
  const invalid = (message, cause) => route.frameError(message, frame.document, cause);
151
233
  const decoded = yield* decodeDocument(frame.document).pipe(Effect.mapError((cause) => invalid(`${route.name} returned an invalid response`, cause)));
152
- const format = decoded.output_format ?? frame.requested ?? "png";
153
- const images = yield* Effect.forEach(decoded.data, (item, index) => MediaInput.decodedAsset(invalid, `${route.name} result ${index}`, item.b64_json, `image/${format}`, {
234
+ // Compatible hosts may omit `output_format` and ignore the requested one, so the bytes decide unreported types.
235
+ const format = decoded.output_format;
236
+ const mediaType = format === undefined ? undefined : `image/${format}`;
237
+ const images = yield* Effect.forEach(decoded.data, (item, index) => MediaInput.imageOutput(invalid, `${route.name} result ${index}`, item, mediaType, {
154
238
  info: info(format, decoded.size),
155
239
  }));
156
240
  if (images.length === 0)
@@ -161,19 +245,20 @@ const onDocument = Effect.fnUntraced(function* (frame) {
161
245
  size: decoded.size,
162
246
  quality: decoded.quality,
163
247
  background: decoded.background,
164
- usage: usage(decoded.usage),
248
+ usage: decoded.usage,
165
249
  };
166
250
  return [state, images.map((image, index) => ImageOutputEvent.make({ index, image }))];
167
251
  });
168
252
  const step = (state, frame) => (typeof frame === "string" ? onEvent(state, frame) : onDocument(frame));
169
- const finish = (state) => {
253
+ const finish = (state, context) => {
170
254
  if (state.completed === 0)
171
255
  return Effect.fail(route.incomplete());
256
+ const provider = context.request.model.provider;
172
257
  return Effect.succeed([
173
258
  ImageFinishEvent.make({
174
- usage: state.usage,
259
+ usage: usage(state.usage, provider),
175
260
  providerMetadata: {
176
- openai: {
261
+ [provider]: {
177
262
  outputFormat: state.format,
178
263
  size: state.size,
179
264
  quality: state.quality,
@@ -186,20 +271,33 @@ const finish = (state) => {
186
271
  // ---------------------------------------------------------------------------
187
272
  // 7. Protocol and route
188
273
  // ---------------------------------------------------------------------------
189
- export const protocol = MediaProtocol.stream(route, {
190
- unsupported: ["aspectRatio", "seed"],
191
- body: { from: fromRequest },
274
+ const makeProtocol = (options) => MediaProtocol.stream(route, {
275
+ body: { from: (request) => fromRequest(request, options) },
192
276
  frames: (bytes, context) => context.request.mode === "stream"
193
277
  ? Framing.sse.frame(bytes)
194
- : Framing.document
195
- .frame(bytes)
196
- .pipe(Stream.map((document) => ({ document, requested: requestedFormat(context.body) }))),
278
+ : Framing.document.frame(bytes).pipe(Stream.map((document) => ({ document }))),
197
279
  initial: () => ({ completed: 0 }),
198
280
  step,
199
281
  finish,
200
282
  });
201
- export const model = (input) => ImageModel.fromRoute({ protocol, baseURL: DEFAULT_BASE_URL, path: ({ request }) => (isEdit(request) ? EDIT_PATH : PATH) }, input);
283
+ export const protocol = makeProtocol({ sizing: pixelSize, imageInput: "edits" });
284
+ /**
285
+ * `provider` attributes models, refs, and metadata to an OpenAI-compatible host; it defaults to `openai`. `sizing`
286
+ * replaces the `size` that `aspect` and `resolution` lower to, and `imageInput` how input images are sent.
287
+ */
288
+ export const model = (input) => {
289
+ const imageInput = input.imageInput ?? "edits";
290
+ const base = input.sizing === undefined && imageInput === "edits"
291
+ ? protocol
292
+ : makeProtocol({ sizing: input.sizing ?? pixelSize, imageInput });
293
+ return ImageModel.fromRoute({
294
+ protocol: input.provider === undefined ? base : { ...base, provider: ProviderID.make(input.provider) },
295
+ baseURL: DEFAULT_BASE_URL,
296
+ path: ({ request }) => (imageInput !== "references" && isEdit(request) ? EDIT_PATH : PATH),
297
+ }, input);
298
+ };
202
299
  export const OpenAIImages = {
203
300
  protocol,
204
301
  model,
302
+ pixelSize,
205
303
  };