@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,230 @@
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 { JsonObject, ProviderShared } from "./shared.js";
9
+ export const DEFAULT_PATH = "/systemone";
10
+ export const DEFAULT_BASE_URL = "https://api.typesafe.ai/v1";
11
+ const Probability = Schema.Number.check(Schema.isBetween({ minimum: 0, maximum: 1 }));
12
+ const Answer = Schema.Union([
13
+ Schema.Struct({ type: Schema.Literal("noul"), noul: Probability }),
14
+ Schema.Struct({
15
+ type: Schema.Literal("choice"),
16
+ choice: Schema.String,
17
+ probabilities: Schema.Record(Schema.String, Probability),
18
+ confidence: Probability,
19
+ }),
20
+ Schema.Struct({
21
+ type: Schema.Literal("score"),
22
+ score: Schema.Number,
23
+ probabilities: Schema.Record(Schema.String, Probability),
24
+ confidence: Probability,
25
+ }),
26
+ ]).pipe(Schema.toTaggedUnion("type"));
27
+ const NativeUsage = Schema.StructWithRest(Schema.Struct({
28
+ input_tokens: Schema.optional(Schema.Number),
29
+ output_tokens: Schema.optional(Schema.Number),
30
+ cost: Schema.optional(Schema.Number),
31
+ }), [JsonObject]);
32
+ export const Response = Schema.Struct({
33
+ model: Schema.String,
34
+ answers: Schema.Record(Schema.String, Answer),
35
+ usage: Schema.optional(NativeUsage),
36
+ id: Schema.optional(Schema.String),
37
+ provider: Schema.optional(Schema.String),
38
+ provider_metadata: Schema.optional(Schema.Record(Schema.String, Schema.Record(Schema.String, Schema.Unknown))),
39
+ });
40
+ const ID = "system-one";
41
+ const NAME = "System One";
42
+ /** The System One body without `model`; media goes where the model's `mediaInput` says, else `fallback`. */
43
+ export const encodeBody = Effect.fn("SystemOne.encodeBody")(function* (request, fallback) {
44
+ const questions = yield* encodeQuestions(request.questions);
45
+ const placed = yield* placeMedia(request, request.model.compatibility?.mediaInput ?? fallback);
46
+ return { ...mergeJsonRecords(request.providerOptions, request.http?.body), ...placed, questions };
47
+ });
48
+ const encodeQuestions = (questions) => Effect.forEach(questions, (question) => {
49
+ if (question.type === "predicate")
50
+ return Effect.succeed([question.name, { type: "noul", instructions: question.instructions }]);
51
+ if (question.type === "score")
52
+ return Effect.succeed([
53
+ question.name,
54
+ {
55
+ type: "score",
56
+ instructions: question.instructions,
57
+ criteria: question.levels.map((level) => level.description === undefined ? level.label : `${level.label}: ${level.description}`),
58
+ },
59
+ ]);
60
+ // Options are map keys, so `true` is sent as "true" and mapped back by `choiceValue`.
61
+ const keys = question.choices.map((choice) => String(choice.value));
62
+ if (new Set(keys).size !== keys.length)
63
+ return Effect.fail(ProviderShared.invalidRequest(`System One choice options are strings; "${question.name}" has a boolean and a string with the same text`));
64
+ return Effect.succeed([
65
+ question.name,
66
+ {
67
+ type: "choice",
68
+ instructions: question.instructions,
69
+ criteria: Object.fromEntries(question.choices.map((choice) => [String(choice.value), choice.description ?? null])),
70
+ },
71
+ ]);
72
+ }).pipe(Effect.map(Object.fromEntries));
73
+ const placeMedia = Effect.fnUntraced(function* (request, mediaInput) {
74
+ const parts = request.input;
75
+ const unsupported = (asset, accepted) => new AIError({
76
+ reason: new UnsupportedOperationError({
77
+ operation: "decision.media",
78
+ provider: request.model.provider,
79
+ route: request.model.route.id,
80
+ message: `${NAME} takes ${accepted} here; got ${asset.mediaType}`,
81
+ }),
82
+ });
83
+ const media = parts.flatMap((part) => (part.type === "media" ? [part.media] : []));
84
+ if (media.length === 0)
85
+ return { state: state(parts.map(plain)) };
86
+ if (mediaInput === "state")
87
+ return { state: yield* Effect.forEach(parts, (part) => stateItem(part, unsupported)) };
88
+ // Chat-style content in one user message: text and JSON as text parts, media as in `state`.
89
+ if (mediaInput === "state.messages")
90
+ return {
91
+ state: {
92
+ messages: [
93
+ {
94
+ role: "user",
95
+ content: yield* Effect.forEach(parts, (part) => part.type === "media"
96
+ ? stateItem(part, unsupported)
97
+ : Effect.succeed({ type: "text", text: part.type === "text" ? part.text : encodeJson(part.value) })),
98
+ },
99
+ ],
100
+ },
101
+ };
102
+ if (mediaInput === "root") {
103
+ const lists = { image: "images", audio: "audio", video: "videos" };
104
+ const unplaced = media.find((asset) => !Object.hasOwn(lists, asset.kind));
105
+ if (unplaced !== undefined)
106
+ return yield* unsupported(unplaced, "images, audio and video");
107
+ const inline = yield* Effect.forEach(media, (asset) => ProviderShared.requireInlineMedia(NAME, asset));
108
+ const fields = Object.fromEntries(Object.entries(lists).flatMap(([kind, field]) => {
109
+ const items = inline.filter((_, index) => media[index].kind === kind).map((item) => item.dataUrl);
110
+ return items.length === 0 ? [] : [[field, items]];
111
+ }));
112
+ return { state: state(parts.filter((part) => part.type !== "media").map(plain)), ...fields };
113
+ }
114
+ const unplaced = media.find((asset) => asset.kind !== "image");
115
+ if (unplaced !== undefined)
116
+ return yield* unsupported(unplaced, "images");
117
+ const inline = yield* Effect.forEach(media, (asset) => ProviderShared.requireInlineMedia(NAME, asset));
118
+ // Every occurrence of a reference string in the body is replaced with its image, so it must not be ordinary text.
119
+ const reference = (index) => `<image-${index + 1}>`;
120
+ const items = parts.reduce((acc, part) => part.type === "media"
121
+ ? { next: acc.next + 1, values: [...acc.values, reference(acc.next)] }
122
+ : { next: acc.next, values: [...acc.values, plain(part)] }, { next: 0, values: [] }).values;
123
+ return {
124
+ state: items,
125
+ assets: Object.fromEntries(inline.map((item, index) => [
126
+ reference(index),
127
+ { type: "image", format: item.mime.slice("image/".length), data_base64: item.base64 },
128
+ ])),
129
+ };
130
+ });
131
+ /** A lone text or JSON part is the state itself; several are a list. */
132
+ const state = (items) => (items.length === 1 ? items[0] : items);
133
+ const plain = (part) => {
134
+ if (part.type === "text")
135
+ return part.text;
136
+ if (part.type === "json")
137
+ return part.value;
138
+ return undefined;
139
+ };
140
+ const stateItem = (part, unsupported) => {
141
+ if (part.type !== "media")
142
+ return Effect.succeed(plain(part));
143
+ const asset = part.media;
144
+ if (asset.kind !== "image" && asset.kind !== "audio" && asset.kind !== "video")
145
+ return Effect.fail(unsupported(asset, "images, audio and video"));
146
+ return ProviderShared.requireInlineMedia(NAME, asset).pipe(Effect.map((inline) => {
147
+ if (asset.kind === "image")
148
+ return { type: "image_url", image_url: { url: inline.dataUrl } };
149
+ if (asset.kind === "video")
150
+ return { type: "video_url", video_url: { url: inline.dataUrl } };
151
+ return { type: "input_audio", input_audio: { data: inline.base64, format: inline.mime.slice("audio/".length) } };
152
+ }));
153
+ };
154
+ /** Map System One's answers, keyed by question name, back to the request's question order. */
155
+ export const toResponse = (data, request, providerMetadataKey, invalid) => {
156
+ const names = request.questions.map((question) => question.name);
157
+ if (Object.keys(data.answers).length !== names.length || !names.every((name) => Object.hasOwn(data.answers, name)))
158
+ return Effect.fail(invalid("System One answers do not match the requested questions"));
159
+ return Effect.succeed(new DecisionResponse({
160
+ answers: request.questions.map((question) => toAnswer(question, data.answers[question.name])),
161
+ usage: data.usage === undefined
162
+ ? undefined
163
+ : new DecisionUsage({
164
+ inputTokens: data.usage.input_tokens,
165
+ outputTokens: data.usage.output_tokens,
166
+ totalTokens: ProviderShared.totalTokens(data.usage.input_tokens, data.usage.output_tokens, undefined),
167
+ cost: data.usage.cost,
168
+ }),
169
+ providerMetadata: {
170
+ [providerMetadataKey]: {
171
+ model: data.model,
172
+ ...(data.usage === undefined ? {} : { usage: data.usage }),
173
+ ...(data.id === undefined ? {} : { responseId: data.id }),
174
+ ...(data.provider === undefined ? {} : { provider: data.provider }),
175
+ ...data.provider_metadata?.[providerMetadataKey],
176
+ },
177
+ },
178
+ }));
179
+ };
180
+ const toAnswer = (question, answer) => {
181
+ if (answer.type === "noul")
182
+ return { name: question.name, type: "predicate", probability: answer.noul };
183
+ if (answer.type === "choice") {
184
+ const choices = question.type === "choice" ? question.choices : [];
185
+ const value = (key) => choices.find((choice) => String(choice.value) === key)?.value ?? key;
186
+ const rank = (key) => {
187
+ const index = choices.findIndex((choice) => String(choice.value) === key);
188
+ return index === -1 ? choices.length : index;
189
+ };
190
+ return {
191
+ name: question.name,
192
+ type: "choice",
193
+ choice: value(answer.choice),
194
+ probabilities: Object.entries(answer.probabilities)
195
+ .toSorted(([a], [b]) => rank(a) - rank(b))
196
+ .map(([key, probability]) => ({ value: value(key), probability })),
197
+ confidence: answer.confidence,
198
+ };
199
+ }
200
+ const levels = question.type === "score" ? question.levels : [];
201
+ return {
202
+ name: question.name,
203
+ type: "score",
204
+ score: answer.score,
205
+ probabilities: Object.entries(answer.probabilities)
206
+ .map(([key, probability]) => ({ value: Number(key), label: levels[Number(key)]?.label ?? key, probability }))
207
+ .toSorted((a, b) => a.value - b.value),
208
+ confidence: answer.confidence,
209
+ };
210
+ };
211
+ const decodeDocument = MediaProtocol.identity({ id: ID, name: NAME, provider: "typesafe-ai" }).decodeJson(Response);
212
+ export const protocol = DecisionRoute.protocol({
213
+ id: ID,
214
+ name: NAME,
215
+ inlineMedia: true,
216
+ body: {
217
+ from: (request) => encodeBody(request, "assets").pipe(Effect.map((body) => ({ ...body, model: request.model.id }))),
218
+ },
219
+ response: {
220
+ decode: (response, context) => decodeDocument(response).pipe(Effect.flatMap((output) => toResponse(output.value, context.request, context.providerMetadataKey, output.invalid))),
221
+ },
222
+ });
223
+ /** TypeSafe's API, the reference System One host; other hosts change the endpoint and auth with `route.with(...)`. */
224
+ export const route = DecisionRoute.make({
225
+ id: ID,
226
+ provider: "typesafe-ai",
227
+ protocol,
228
+ endpoint: Endpoint.path("/systemone", { baseURL: DEFAULT_BASE_URL }),
229
+ });
230
+ export const SystemOne = { Response, encodeBody, toResponse, protocol, route };
@@ -1,9 +1,9 @@
1
1
  import { Schema } from "effect";
2
- import type { CacheHint, LLMRequest } from "../../schema/index.js";
2
+ import { type CacheHint, type LLMRequest } from "../../schema/index.js";
3
3
  export declare const CachePointBlock: Schema.Struct<{
4
4
  readonly cachePoint: Schema.Struct<{
5
5
  readonly type: Schema.tag<"default">;
6
- readonly ttl: Schema.optional<Schema.Literals<readonly ["5m", "1h"]>>;
6
+ readonly ttl: Schema.optional<Schema.TemplateLiteral<readonly [Schema.Number, Schema.Literals<readonly ["ms", "s", "m", "h", "d"]>]>>;
7
7
  }>;
8
8
  }>;
9
9
  export type CachePointBlock = Schema.Schema.Type<typeof CachePointBlock>;
@@ -1,12 +1,13 @@
1
1
  import { Schema } from "effect";
2
- import { newBreakpoints, ttlBucket } from "./cache.js";
2
+ import { CacheTTL } from "../../schema/index.js";
3
+ import { newBreakpoints } from "./cache.js";
3
4
  // Bedrock cache markers are positional: emit a `cachePoint` block immediately
4
5
  // after the content the caller wants treated as a cacheable prefix. Bedrock
5
- // accepts optional `ttl: "5m" | "1h"` on cachePoint.
6
+ // accepts an optional `ttl` such as "5m" or "1h" on cachePoint.
6
7
  export const CachePointBlock = Schema.Struct({
7
8
  cachePoint: Schema.Struct({
8
9
  type: Schema.tag("default"),
9
- ttl: Schema.optional(Schema.Literals(["5m", "1h"])),
10
+ ttl: Schema.optional(CacheTTL),
10
11
  }),
11
12
  });
12
13
  const LEGACY_CLAUDE = ["anthropic.claude-instant", "anthropic.claude-v1", "anthropic.claude-v2", "anthropic.claude-3-"];
@@ -34,8 +35,6 @@ export const breakpoints = (model) => {
34
35
  ttl1h: !short,
35
36
  };
36
37
  };
37
- const DEFAULT_5M = { cachePoint: { type: "default" } };
38
- const DEFAULT_1H = { cachePoint: { type: "default", ttl: "1h" } };
39
38
  export const block = (breakpoints, cache) => {
40
39
  if (!breakpoints.supported)
41
40
  return undefined;
@@ -46,6 +45,8 @@ export const block = (breakpoints, cache) => {
46
45
  return undefined;
47
46
  }
48
47
  breakpoints.remaining -= 1;
49
- return breakpoints.ttl1h && ttlBucket(cache.ttlSeconds) === "1h" ? DEFAULT_1H : DEFAULT_5M;
48
+ // Older Claude releases cache for five minutes only, so a one-hour request falls back to the default.
49
+ const ttl = cache.ttl === "1h" && !breakpoints.ttl1h ? undefined : cache.ttl;
50
+ return { cachePoint: { type: "default", ...(ttl === undefined ? {} : { ttl }) } };
50
51
  };
51
52
  export * as BedrockCache from "./bedrock-cache.js";
@@ -1,11 +1,22 @@
1
- import type { CacheHint } from "../../schema/index.js";
1
+ import type { CacheHint, CacheTTL } from "../../schema/index.js";
2
2
  export interface Breakpoints {
3
3
  remaining: number;
4
4
  dropped: number;
5
5
  }
6
6
  export declare const newBreakpoints: (cap: number) => Breakpoints;
7
- export declare const ttlBucket: (ttlSeconds: number | undefined) => "1h" | undefined;
8
7
  export declare const cacheControl: () => (cache: CacheHint | undefined) => {
9
8
  type: "ephemeral";
10
- ttl: "1h" | undefined;
9
+ ttl: `${number}d` | `${number}h` | `${number}m` | `${number}ms` | `${number}s` | undefined;
11
10
  } | undefined;
11
+ export declare const openAIRequestTTL: (ttl: CacheTTL | undefined) => {
12
+ prompt_cache_retention?: undefined;
13
+ prompt_cache_options?: undefined;
14
+ } | {
15
+ prompt_cache_retention: string;
16
+ prompt_cache_options?: undefined;
17
+ } | {
18
+ prompt_cache_retention?: undefined;
19
+ prompt_cache_options: {
20
+ ttl: `${number}d` | `${number}h` | `${number}m` | `${number}ms` | `${number}s`;
21
+ };
22
+ };
@@ -1,13 +1,20 @@
1
1
  export const newBreakpoints = (cap) => ({ remaining: cap, dropped: 0 });
2
- // Requests of at least one hour use the explicit `"1h"` bucket; shorter
3
- // requests omit the wire TTL and use the provider default.
4
- export const ttlBucket = (ttlSeconds) => ttlSeconds !== undefined && ttlSeconds >= 3600 ? "1h" : undefined;
5
2
  export const cacheControl = () => {
6
3
  const breakpoints = newBreakpoints(4);
7
4
  return (cache) => {
8
5
  if (cache === undefined || breakpoints.remaining === 0)
9
6
  return undefined;
10
7
  breakpoints.remaining -= 1;
11
- return { type: "ephemeral", ttl: ttlBucket(cache.ttlSeconds) };
8
+ return { type: "ephemeral", ttl: cache.ttl };
12
9
  };
13
10
  };
11
+ // OpenAI's request-level lifetime. `prompt_cache_retention` takes only "24h" (or "in_memory") and is the only
12
+ // control before GPT-5.6; every other lifetime goes to `prompt_cache_options.ttl`, which GPT-5.6+, Kimi and
13
+ // DeepInfra read.
14
+ export const openAIRequestTTL = (ttl) => {
15
+ if (ttl === undefined)
16
+ return {};
17
+ if (ttl === "24h")
18
+ return { prompt_cache_retention: ttl };
19
+ return { prompt_cache_options: { ttl } };
20
+ };
@@ -1,5 +1,6 @@
1
1
  import { Effect, Schema, type Stream } from "effect";
2
- import type { Media } from "../../media.js";
2
+ import type { Tool } from "@opencode/schema/tool";
3
+ import { Media } from "../../media.js";
3
4
  import type { MediaProtocol } from "../../route/media-protocol.js";
4
5
  import { AIError, type MediaUsage, type ProviderMetadata } from "../../schema/index.js";
5
6
  declare const UsageMetadata: Schema.Struct<{
@@ -51,12 +52,11 @@ export declare const blocked: (name: string, chunk: Chunk, frame: string) => AIE
51
52
  export declare const contentFiltered: (finishReason: string | undefined) => boolean;
52
53
  /** Callers check that the response produced no output: a policy stop after output is a partial result instead. */
53
54
  export declare const withheld: (name: string, chunk: Chunk, frame: string) => AIError | undefined;
54
- /** Any finish reason other than `STOP` means the output may be cut short, so it is surfaced rather than dropped. */
55
- export declare const notices: (name: string, state: Metadata) => ReadonlyArray<Media.Notice> | undefined;
56
55
  export declare const usage: (usage: UsageMetadata | undefined) => MediaUsage | undefined;
57
56
  export declare const providerMetadata: (state: Metadata) => ProviderMetadata;
58
57
  export declare const path: (model: string, mode: MediaProtocol.Mode) => string;
59
58
  export declare const frames: (bytes: Stream.Stream<Uint8Array, AIError>, mode: MediaProtocol.Mode) => Stream.Stream<string, AIError, never>;
59
+ export declare const toolMedia: (item: Tool.FileContent) => Media.Asset;
60
60
  export declare const mediaPart: (route: string, asset: Media.Asset) => Effect.Effect<{
61
61
  readonly fileData: {
62
62
  readonly mimeType: string;
@@ -1,6 +1,7 @@
1
1
  import { Effect, Schema } from "effect";
2
+ import { Media } from "../../media.js";
2
3
  import { Framing } from "../../route/framing.js";
3
- import { AIError, ContentPolicyError, ProviderID } from "../../schema/index.js";
4
+ import { AIError, ContentPolicyError, ProviderID, tokenUsage, } from "../../schema/index.js";
4
5
  import { ProviderShared } from "../shared.js";
5
6
  import { MediaInput } from "./media-input.js";
6
7
  const PROVIDER = ProviderID.make("google");
@@ -63,34 +64,27 @@ export const withheld = (name, chunk, frame) => {
63
64
  reason: new ContentPolicyError({ message: `${name} withheld its output (${finishReason})`, body: frame }),
64
65
  });
65
66
  };
66
- /** Any finish reason other than `STOP` means the output may be cut short, so it is surfaced rather than dropped. */
67
- export const notices = (name, state) => state.finishReason === undefined || state.finishReason === "STOP"
68
- ? undefined
69
- : [
70
- {
71
- type: contentFiltered(state.finishReason) ? "filtered" : "other",
72
- message: `${name} finished with ${state.finishReason}`,
73
- providerMetadata: { google: { finishReason: state.finishReason } },
74
- },
75
- ];
76
67
  export const usage = (usage) => usage === undefined
77
68
  ? undefined
78
- : {
79
- type: "tokens",
69
+ : tokenUsage({
80
70
  input: usage.promptTokenCount,
81
71
  output: usage.candidatesTokenCount,
82
72
  total: ProviderShared.totalTokens(usage.promptTokenCount, usage.candidatesTokenCount, usage.totalTokenCount),
83
73
  details: { google: usage },
84
- };
74
+ });
85
75
  export const providerMetadata = (state) => ({
86
76
  google: { finishReason: state.finishReason, modelVersion: state.modelVersion, responseId: state.responseId },
87
77
  });
88
78
  export const path = (model, mode) => mode === "stream" ? `/models/${model}:streamGenerateContent?alt=sse` : `/models/${model}:generateContent`;
89
79
  // `generateContent` answers with one document shaped exactly like a streamed chunk, so it is a single frame.
90
80
  export const frames = (bytes, mode) => mode === "stream" ? Framing.sse.frame(bytes) : Framing.document.frame(bytes);
91
- // Gemini does not fetch public URLs; inline payloads and Gemini Files references are the accepted inputs.
81
+ export const toolMedia = (item) => item.mime.startsWith("video/") && item.uri.startsWith("gs://")
82
+ ? Media.ref(PROVIDER, item.uri, item.mime)
83
+ : ProviderShared.toolFileMedia(item).media;
92
84
  export const mediaPart = (route, asset) => {
93
- const fileUri = MediaInput.refID(asset, PROVIDER);
85
+ const fileUri = asset.kind === "video" && asset.source.type === "url" && /^https?:\/\//i.test(asset.source.url)
86
+ ? asset.source.url
87
+ : MediaInput.refID(asset, PROVIDER);
94
88
  if (fileUri !== undefined)
95
89
  return Effect.succeed({ fileData: { mimeType: asset.mediaType, fileUri } });
96
90
  return ProviderShared.requireInlineMedia(route, asset).pipe(Effect.map((media) => ({ inlineData: { mimeType: media.mime, data: media.base64 } })));
@@ -1,3 +1,8 @@
1
1
  import type { JsonSchema } from "../../schema/index.js";
2
+ export declare const SCHEMA_MAPS: Set<string>;
3
+ export declare const VALUES: Set<string>;
4
+ export declare const mapValues: (record: Record<string, unknown>, map: (value: unknown, key: string) => unknown) => {
5
+ [k: string]: unknown;
6
+ };
2
7
  export declare const normalize: (schema: JsonSchema) => JsonSchema;
3
8
  export * as GeminiJsonSchema from "./gemini-json-schema.js";
@@ -1,7 +1,7 @@
1
1
  import { isRecord } from "../../utils/record.js";
2
2
  // Gemini's `parametersJsonSchema` accepts standard JSON Schema, but rejects a few shapes that
3
3
  // published tool schemas commonly contain. Rewrite only those and send everything else unchanged.
4
- const SCHEMA_MAPS = new Set([
4
+ export const SCHEMA_MAPS = new Set([
5
5
  "properties",
6
6
  "patternProperties",
7
7
  "$defs",
@@ -9,8 +9,8 @@ const SCHEMA_MAPS = new Set([
9
9
  "dependentSchemas",
10
10
  "dependencies",
11
11
  ]);
12
- const VALUES = new Set(["const", "default", "enum", "examples", "dependentRequired"]);
13
- const mapValues = (record, map) => Object.fromEntries(Object.entries(record).map(([key, value]) => [key, map(value, key)]));
12
+ export const VALUES = new Set(["const", "default", "enum", "examples", "dependentRequired"]);
13
+ export const mapValues = (record, map) => Object.fromEntries(Object.entries(record).map(([key, value]) => [key, map(value, key)]));
14
14
  const normalizeNode = (schema) => {
15
15
  if (Array.isArray(schema))
16
16
  return schema.map(normalizeNode);
@@ -0,0 +1,31 @@
1
+ import { Effect } from "effect";
2
+ import type { MediaProtocol } from "../../route/media-protocol.js";
3
+ export interface Size {
4
+ readonly width: number;
5
+ readonly height: number;
6
+ }
7
+ /** The shared `aspect` and `resolution` fields of an image request. */
8
+ export interface Shape {
9
+ readonly aspect?: string;
10
+ readonly resolution?: string;
11
+ }
12
+ /** What a provider accepts for free width and height. */
13
+ export interface Limits {
14
+ readonly multiple: number;
15
+ readonly minEdge?: number;
16
+ readonly maxEdge?: number;
17
+ readonly minPixels?: number;
18
+ readonly maxPixels?: number;
19
+ /** Long edge over short edge. */
20
+ readonly maxRatio?: number;
21
+ }
22
+ export declare const isRequested: (shape: Shape) => boolean;
23
+ /** `1K` is 1, `2K` is 2, `0.5K` is 0.5; anything else is not a tier. */
24
+ export declare const tier: (resolution: string) => number | undefined;
25
+ /** Free width and height: the tier sets the pixel count (`1K` is about 1024²), the aspect sets the proportions. */
26
+ export declare const fit: (shape: Shape, limits: Limits) => Size;
27
+ /** The listed size closest to the shape: nearest aspect ratio first, then nearest pixel count. */
28
+ export declare const nearest: (shape: Shape, sizes: ReadonlyArray<Size>) => Size;
29
+ /** Free width and height that must honor the shape; a size that misses it fails. */
30
+ export declare const exact: (route: MediaProtocol.Identity, shape: Shape, limits: Limits) => Effect.Effect<undefined, never, never> | Effect.Effect<never, import("../../effect.js").AIError, never> | Effect.Effect<Size, never, never>;
31
+ export * as ImageSizing from "./image-sizing.js";
@@ -0,0 +1,73 @@
1
+ import { Effect } from "effect";
2
+ export const isRequested = (shape) => shape.aspect !== undefined || shape.resolution !== undefined;
3
+ /** `1K` is 1, `2K` is 2, `0.5K` is 0.5; anything else is not a tier. */
4
+ export const tier = (resolution) => {
5
+ const match = /^(\d+(?:\.\d+)?)k$/i.exec(resolution);
6
+ return match === null ? undefined : Number(match[1]);
7
+ };
8
+ /** Free width and height: the tier sets the pixel count (`1K` is about 1024²), the aspect sets the proportions. */
9
+ export const fit = (shape, limits) => {
10
+ const maxRatio = limits.maxRatio ?? Infinity;
11
+ const ratio = Math.min(maxRatio, Math.max(1 / maxRatio, aspectRatio(shape)));
12
+ const area = targetPixels(shape);
13
+ const width = Math.sqrt(area * ratio);
14
+ const height = Math.sqrt(area / ratio);
15
+ const up = Math.max((limits.minEdge ?? 0) / Math.min(width, height), Math.sqrt((limits.minPixels ?? 0) / area));
16
+ const scaled = Math.max(1, up);
17
+ const down = Math.min((limits.maxEdge ?? Infinity) / (Math.max(width, height) * scaled), Math.sqrt((limits.maxPixels ?? Infinity) / area) / scaled);
18
+ // Round away from a limit the size reached, including one it lands on exactly, so it never crosses it.
19
+ const round = down <= 1 ? Math.floor : up >= 1 ? Math.ceil : Math.round;
20
+ const snap = (edge) => Math.max(limits.multiple, round(Number(((edge * scaled * Math.min(1, down)) / limits.multiple).toFixed(6))) * limits.multiple);
21
+ return { width: snap(width), height: snap(height) };
22
+ };
23
+ /** The listed size closest to the shape: nearest aspect ratio first, then nearest pixel count. */
24
+ export const nearest = (shape, sizes) => {
25
+ const ratio = Math.log(aspectRatio(shape));
26
+ const area = Math.log(targetPixels(shape));
27
+ const distance = (size) => [
28
+ Math.abs(Math.log(size.width / size.height) - ratio),
29
+ Math.abs(Math.log(size.width * size.height) - area),
30
+ ];
31
+ return sizes.reduce((best, size) => {
32
+ const [sizeRatio, sizeArea] = distance(size);
33
+ const [bestRatio, bestArea] = distance(best);
34
+ if (Math.abs(sizeRatio - bestRatio) > 1e-9)
35
+ return sizeRatio < bestRatio ? size : best;
36
+ return sizeArea < bestArea ? size : best;
37
+ });
38
+ };
39
+ /** Free width and height that must honor the shape; a size that misses it fails. */
40
+ export const exact = (route, shape, limits) => {
41
+ if (!isRequested(shape))
42
+ return Effect.succeed(undefined);
43
+ const size = fit(shape, limits);
44
+ const requested = missed(shape, size);
45
+ if (requested === undefined)
46
+ return Effect.succeed(size);
47
+ return Effect.fail(route.unsupported(shape.resolution === undefined ? "media.aspect" : "media.resolution", `${route.name} can't render ${requested}; the closest size it takes is ${describe(size)}. Change aspect or resolution, or set the size in providerOptions`));
48
+ };
49
+ /** A size more than 2% off the requested aspect or more than √2 per edge off the requested tier. */
50
+ const missed = (shape, size) => {
51
+ const aspectMissed = shape.aspect !== undefined && Math.abs(Math.log(size.width / size.height / aspectRatio(shape))) > 0.02;
52
+ const requestedTier = shape.resolution === undefined ? undefined : tier(shape.resolution);
53
+ const resolutionMissed = shape.resolution !== undefined &&
54
+ (requestedTier === undefined ||
55
+ Math.abs(Math.log2(Math.sqrt(size.width * size.height) / (requestedTier * 1024))) > 0.5);
56
+ if (!aspectMissed && !resolutionMissed)
57
+ return undefined;
58
+ return [shape.aspect, shape.resolution].filter((value) => value !== undefined).join(" at ");
59
+ };
60
+ const aspectRatio = (shape) => {
61
+ const [width, height] = (shape.aspect ?? "1:1").split(":").map(Number);
62
+ return width / height;
63
+ };
64
+ const targetPixels = (shape) => ((tier(shape.resolution ?? "1K") ?? 1) * 1024) ** 2;
65
+ const describe = (size) => {
66
+ const divisor = gcd(size.width, size.height);
67
+ const width = size.width / divisor;
68
+ const height = size.height / divisor;
69
+ const ratio = width <= 32 && height <= 32 ? `${width}:${height}` : `${(size.width / size.height).toFixed(2)}:1`;
70
+ return `${size.width}x${size.height} (${ratio})`;
71
+ };
72
+ const gcd = (a, b) => (b === 0 ? a : gcd(b, a % b));
73
+ export * as ImageSizing from "./image-sizing.js";
@@ -7,15 +7,14 @@ export declare const inlineBytes: (route: string, asset: Media.Asset) => Effect.
7
7
  /** Copied because `BlobPart` requires a plain `ArrayBuffer`. */
8
8
  export declare const blob: (data: Uint8Array, mediaType: string) => Blob;
9
9
  export declare const query: (route: string, values: Record<string, unknown>) => Effect.Effect<MediaProtocol.Query, AIError>;
10
- export declare const dimensions: (size: string) => {
11
- width: number;
12
- height: number;
13
- };
14
10
  /** Provider file handle when the ref belongs to this provider; refs from other providers are never forwarded. */
15
11
  export declare const refID: (asset: Media.Asset, provider: ProviderID) => string | undefined;
16
12
  /** Decode a provider's base64 output once into an owned `bytes` asset, sniffing the type when it is not declared. */
17
13
  export declare const decodedAsset: (invalid: (message: string, cause?: unknown) => AIError, label: string, data: string, mediaType: string | undefined, options?: Media.AssetOptions) => Effect.Effect<Media.Asset, AIError, never>;
18
- /** One image of an OpenAI-shaped `data` array, which carries either `b64_json` or a `url`. */
14
+ /**
15
+ * One image of an OpenAI-shaped `data` array, which carries `b64_json`, a `url`, or both. `b64_json` wins; a `data:`
16
+ * URL decodes inline with its own media type, and any other URL stays a URL asset for the caller to download.
17
+ */
19
18
  export declare const imageOutput: (invalid: (message: string, cause?: unknown) => AIError, label: string, item: {
20
19
  readonly b64_json?: string | null;
21
20
  readonly url?: string | null;
@@ -27,18 +27,21 @@ export const query = (route, values) => {
27
27
  return Effect.fail(ProviderShared.invalidRequest(`${route} cannot send "${invalid[0]}" as a query parameter`));
28
28
  return Effect.succeed(Object.fromEntries(entries.map(([key, value]) => [key, Array.isArray(value) ? value.map(String) : String(value)])));
29
29
  };
30
- export const dimensions = (size) => {
31
- const [width, height] = size.split("x").map(Number);
32
- return { width, height };
33
- };
34
30
  /** Provider file handle when the ref belongs to this provider; refs from other providers are never forwarded. */
35
31
  export const refID = (asset, provider) => asset.source.type === "ref" && asset.source.provider === provider ? asset.source.id : undefined;
36
32
  /** Decode a provider's base64 output once into an owned `bytes` asset, sniffing the type when it is not declared. */
37
33
  export const decodedAsset = (invalid, label, data, mediaType, options) => Effect.fromResult(Base64.decode(data)).pipe(Effect.mapError((cause) => invalid(`${label} contains invalid base64 data`, cause)), Effect.map((bytes) => Media.bytes(bytes, mediaType, options)));
38
- /** One image of an OpenAI-shaped `data` array, which carries either `b64_json` or a `url`. */
34
+ /**
35
+ * One image of an OpenAI-shaped `data` array, which carries `b64_json`, a `url`, or both. `b64_json` wins; a `data:`
36
+ * URL decodes inline with its own media type, and any other URL stays a URL asset for the caller to download.
37
+ */
39
38
  export const imageOutput = (invalid, label, item, mediaType, options) => {
40
39
  if (item.b64_json)
41
40
  return decodedAsset(invalid, label, item.b64_json, mediaType, options);
41
+ if (item.url?.startsWith("data:")) {
42
+ const asset = Media.parseDataUrl(item.url, options);
43
+ return asset === undefined ? Effect.fail(invalid(`${label} has an invalid data URL`)) : Effect.succeed(asset);
44
+ }
42
45
  if (item.url)
43
46
  return Effect.succeed(Media.url(item.url, { ...options, mediaType }));
44
47
  return Effect.fail(invalid(`${label} has neither image data nor a URL`));
@@ -42,7 +42,6 @@ export declare const finish: (route: MediaProtocol.Identity, state: Audio, outpu
42
42
  readonly mediaType: string | undefined;
43
43
  readonly info?: Media.Info;
44
44
  readonly usage?: MediaUsage;
45
- readonly notices?: ReadonlyArray<Media.Notice>;
46
45
  readonly providerMetadata?: ProviderMetadata;
47
46
  readonly detail?: string;
48
47
  }) => Effect.Effect<ReadonlyArray<SpeechEvent>, AIError>;
@@ -51,7 +51,6 @@ export const finish = (route, state, output) => {
51
51
  SpeechFinishEvent.make({
52
52
  audio: Media.bytes(concatBytes(state.chunks), output.mediaType, { info: output.info }),
53
53
  usage: output.usage,
54
- notices: output.notices,
55
54
  providerMetadata: output.providerMetadata,
56
55
  }),
57
56
  ]);
@@ -1,6 +1,7 @@
1
1
  import { ToolDefinition } from "../../schema/index.js";
2
2
  import { isRecord } from "../../utils/record.js";
3
3
  import { GeminiJsonSchema } from "./gemini-json-schema.js";
4
+ const { SCHEMA_MAPS, VALUES, mapValues } = GeminiJsonSchema;
4
5
  const tupleItemsSchema = (items) => {
5
6
  const projected = items.map(moonshotNode);
6
7
  if (projected.length === 0)
@@ -31,12 +32,21 @@ const moonshotNode = (schema) => {
31
32
  return Object.fromEntries([
32
33
  ...(type === undefined ? [] : [["type", type]]),
33
34
  ...Object.entries(schema).flatMap(([key, value]) => {
34
- if (key === "items" && Array.isArray(value))
35
- return [[key, tupleItemsSchema(value)]];
36
- if (key === "prefixItems") {
37
- if ("items" in schema)
35
+ if (VALUES.has(key))
36
+ return [[key, value]];
37
+ if (SCHEMA_MAPS.has(key) && isRecord(value))
38
+ return [[key, mapValues(value, moonshotNode)]];
39
+ if (key === "items") {
40
+ if (Array.isArray(schema.prefixItems))
38
41
  return [];
39
- return [["items", tupleItemsSchema(Array.isArray(value) ? value : [])]];
42
+ if (Array.isArray(value))
43
+ return [[key, tupleItemsSchema(value)]];
44
+ }
45
+ if (key === "prefixItems") {
46
+ if (!Array.isArray(value))
47
+ return "items" in schema ? [] : [["items", {}]];
48
+ const rest = isRecord(schema.items) ? [schema.items] : Array.isArray(schema.items) ? schema.items : [];
49
+ return [["items", tupleItemsSchema([...value, ...rest])]];
40
50
  }
41
51
  if (key === "unevaluatedItems")
42
52
  return [];