@opencode/ai 2.1.4 → 2.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (269) hide show
  1. package/README.md +283 -114
  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 +5 -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 +1426 -34
  26. package/dist/index.js +127 -24
  27. package/dist/llm.d.ts +16 -1
  28. package/dist/llm.js +34 -0
  29. package/dist/media-client.d.ts +2 -1
  30. package/dist/media-model.d.ts +3 -0
  31. package/dist/media-model.js +4 -1
  32. package/dist/media.d.ts +0 -7
  33. package/dist/media.js +0 -6
  34. package/dist/protocols/alibaba-chat.d.ts +20 -0
  35. package/dist/protocols/alibaba-images.d.ts +22 -0
  36. package/dist/protocols/alibaba-images.js +77 -0
  37. package/dist/protocols/alibaba-messages.d.ts +52 -17
  38. package/dist/protocols/alibaba-responses.d.ts +6 -3
  39. package/dist/protocols/anthropic-messages.d.ts +160 -54
  40. package/dist/protocols/anthropic-messages.js +44 -13
  41. package/dist/protocols/bedrock-converse.d.ts +110 -15
  42. package/dist/protocols/bedrock-converse.js +112 -15
  43. package/dist/protocols/bedrock-event-stream.js +1 -0
  44. package/dist/protocols/bfl-images.d.ts +9 -0
  45. package/dist/protocols/bfl-images.js +17 -15
  46. package/dist/protocols/cartesia-speech.d.ts +0 -18
  47. package/dist/protocols/cloudflare-run-decisions.d.ts +9 -0
  48. package/dist/protocols/cloudflare-run-decisions.js +36 -0
  49. package/dist/protocols/cloudflare-workers-ai-images.d.ts +23 -0
  50. package/dist/protocols/cloudflare-workers-ai-images.js +80 -0
  51. package/dist/protocols/deepgram-speech.d.ts +0 -18
  52. package/dist/protocols/elevenlabs-speech.d.ts +0 -18
  53. package/dist/protocols/fal-images.d.ts +10 -1
  54. package/dist/protocols/fal-images.js +16 -25
  55. package/dist/protocols/fal-video.js +1 -1
  56. package/dist/protocols/gemini.d.ts +3 -0
  57. package/dist/protocols/gemini.js +11 -6
  58. package/dist/protocols/google-images.d.ts +2 -2
  59. package/dist/protocols/google-images.js +8 -37
  60. package/dist/protocols/google-interactions.d.ts +4 -0
  61. package/dist/protocols/google-interactions.js +12 -5
  62. package/dist/protocols/google-speech.d.ts +0 -18
  63. package/dist/protocols/google-speech.js +0 -1
  64. package/dist/protocols/google-transcription.d.ts +0 -18
  65. package/dist/protocols/google-transcription.js +0 -1
  66. package/dist/protocols/google-video.d.ts +1 -1
  67. package/dist/protocols/google-video.js +2 -7
  68. package/dist/protocols/index.d.ts +3 -0
  69. package/dist/protocols/index.js +3 -0
  70. package/dist/protocols/meta-images.d.ts +7 -1
  71. package/dist/protocols/meta-images.js +10 -8
  72. package/dist/protocols/meta-messages.d.ts +52 -17
  73. package/dist/protocols/meta-messages.js +14 -1
  74. package/dist/protocols/meta-responses.d.ts +6 -0
  75. package/dist/protocols/meta-responses.js +29 -1
  76. package/dist/protocols/open-responses.d.ts +30 -0
  77. package/dist/protocols/open-responses.js +8 -18
  78. package/dist/protocols/openai-chat.d.ts +713 -1
  79. package/dist/protocols/openai-chat.js +35 -22
  80. package/dist/protocols/openai-compatible-chat.d.ts +22 -1
  81. package/dist/protocols/openai-compatible-responses.d.ts +8 -5
  82. package/dist/protocols/openai-decisions.d.ts +22 -0
  83. package/dist/protocols/openai-decisions.js +128 -0
  84. package/dist/protocols/openai-images.d.ts +21 -24
  85. package/dist/protocols/openai-images.js +100 -34
  86. package/dist/protocols/openai-responses.d.ts +82 -24
  87. package/dist/protocols/openai-responses.js +32 -2
  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/replicate-images.js +1 -1
  93. package/dist/protocols/runway-video.d.ts +1 -1
  94. package/dist/protocols/runway-video.js +1 -1
  95. package/dist/protocols/shared.d.ts +9 -1
  96. package/dist/protocols/shared.js +13 -2
  97. package/dist/protocols/stability-images.d.ts +5 -0
  98. package/dist/protocols/stability-images.js +4 -9
  99. package/dist/protocols/system-one.d.ts +101 -0
  100. package/dist/protocols/system-one.js +230 -0
  101. package/dist/protocols/utils/bedrock-cache.d.ts +2 -2
  102. package/dist/protocols/utils/bedrock-cache.js +7 -6
  103. package/dist/protocols/utils/cache.d.ts +14 -3
  104. package/dist/protocols/utils/cache.js +11 -4
  105. package/dist/protocols/utils/gemini-generate-content.d.ts +3 -3
  106. package/dist/protocols/utils/gemini-generate-content.js +10 -16
  107. package/dist/protocols/utils/gemini-json-schema.d.ts +5 -0
  108. package/dist/protocols/utils/gemini-json-schema.js +3 -3
  109. package/dist/protocols/utils/image-sizing.d.ts +31 -0
  110. package/dist/protocols/utils/image-sizing.js +73 -0
  111. package/dist/protocols/utils/media-input.d.ts +4 -5
  112. package/dist/protocols/utils/media-input.js +8 -5
  113. package/dist/protocols/utils/speech-stream.d.ts +0 -1
  114. package/dist/protocols/utils/speech-stream.js +0 -1
  115. package/dist/protocols/utils/tool-schema.js +15 -5
  116. package/dist/protocols/utils/tool-stream.d.ts +9 -0
  117. package/dist/protocols/venice-chat.d.ts +19 -0
  118. package/dist/protocols/venice-chat.js +1 -1
  119. package/dist/protocols/xai-images.d.ts +1 -2
  120. package/dist/protocols/xai-images.js +9 -2
  121. package/dist/protocols/xai-responses.d.ts +10 -0
  122. package/dist/protocols/xai-responses.js +28 -2
  123. package/dist/protocols/xai-video.d.ts +1 -1
  124. package/dist/protocols/xai-video.js +11 -8
  125. package/dist/protocols/zai-chat.d.ts +21 -0
  126. package/dist/protocols/zai-images.d.ts +3 -1
  127. package/dist/protocols/zai-images.js +12 -11
  128. package/dist/protocols/zai-messages.d.ts +52 -17
  129. package/dist/provider-error.js +19 -4
  130. package/dist/providers/alibaba/images.d.ts +2 -0
  131. package/dist/providers/alibaba/images.js +1 -0
  132. package/dist/providers/alibaba.d.ts +79 -18
  133. package/dist/providers/alibaba.js +16 -8
  134. package/dist/providers/amazon-bedrock-mantle.d.ts +197 -138
  135. package/dist/providers/amazon-bedrock.d.ts +34 -14
  136. package/dist/providers/amazon-bedrock.js +11 -11
  137. package/dist/providers/anthropic-compatible.d.ts +52 -17
  138. package/dist/providers/anthropic.d.ts +52 -17
  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 +50 -9
  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 +51 -1
  146. package/dist/providers/baseten.js +41 -8
  147. package/dist/providers/cerebras.d.ts +42 -0
  148. package/dist/providers/cloudflare-ai-gateway/decisions.d.ts +2 -0
  149. package/dist/providers/cloudflare-ai-gateway/decisions.js +1 -0
  150. package/dist/providers/cloudflare-ai-gateway.d.ts +177 -43
  151. package/dist/providers/cloudflare-ai-gateway.js +32 -4
  152. package/dist/providers/cloudflare-workers-ai/decisions.d.ts +2 -0
  153. package/dist/providers/cloudflare-workers-ai/decisions.js +1 -0
  154. package/dist/providers/cloudflare-workers-ai/images.d.ts +2 -0
  155. package/dist/providers/cloudflare-workers-ai/images.js +1 -0
  156. package/dist/providers/cloudflare-workers-ai.d.ts +55 -1
  157. package/dist/providers/cloudflare-workers-ai.js +45 -9
  158. package/dist/providers/cohere.d.ts +42 -0
  159. package/dist/providers/deepinfra.d.ts +42 -0
  160. package/dist/providers/deepseek.d.ts +42 -0
  161. package/dist/providers/digitalocean/decisions.d.ts +2 -0
  162. package/dist/providers/digitalocean/decisions.js +1 -0
  163. package/dist/providers/digitalocean/images.d.ts +2 -0
  164. package/dist/providers/digitalocean/images.js +1 -0
  165. package/dist/providers/digitalocean.d.ts +72 -1
  166. package/dist/providers/digitalocean.js +39 -8
  167. package/dist/providers/fireworks.d.ts +42 -0
  168. package/dist/providers/google/images.d.ts +2 -0
  169. package/dist/providers/google/images.js +1 -0
  170. package/dist/providers/google-vertex/images.d.ts +2 -0
  171. package/dist/providers/google-vertex/images.js +1 -0
  172. package/dist/providers/google-vertex-chat.d.ts +21 -0
  173. package/dist/providers/google-vertex-messages.d.ts +52 -17
  174. package/dist/providers/google-vertex-responses.d.ts +3 -0
  175. package/dist/providers/google-vertex.d.ts +3 -1
  176. package/dist/providers/google-vertex.js +30 -13
  177. package/dist/providers/google.d.ts +5 -4
  178. package/dist/providers/google.js +15 -8
  179. package/dist/providers/groq.d.ts +42 -4
  180. package/dist/providers/groq.js +0 -6
  181. package/dist/providers/meta.d.ts +197 -138
  182. package/dist/providers/minimax.d.ts +76 -17
  183. package/dist/providers/moonshot.d.ts +76 -17
  184. package/dist/providers/openai/images.d.ts +2 -0
  185. package/dist/providers/openai/images.js +1 -0
  186. package/dist/providers/openai-compatible/images.d.ts +2 -0
  187. package/dist/providers/openai-compatible/images.js +1 -0
  188. package/dist/providers/openai-compatible-responses.d.ts +3 -0
  189. package/dist/providers/openai-compatible.d.ts +24 -1
  190. package/dist/providers/openai-compatible.js +21 -9
  191. package/dist/providers/openai-options.d.ts +3 -1
  192. package/dist/providers/openai.d.ts +46 -9
  193. package/dist/providers/openai.js +20 -4
  194. package/dist/providers/opencode/decisions.d.ts +2 -0
  195. package/dist/providers/opencode/decisions.js +1 -0
  196. package/dist/providers/opencode.d.ts +9 -10
  197. package/dist/providers/opencode.js +10 -8
  198. package/dist/providers/openrouter/decisions.d.ts +2 -0
  199. package/dist/providers/openrouter/decisions.js +1 -0
  200. package/dist/providers/openrouter/images.d.ts +2 -0
  201. package/dist/providers/openrouter/images.js +1 -0
  202. package/dist/providers/openrouter.d.ts +92 -11
  203. package/dist/providers/openrouter.js +38 -16
  204. package/dist/providers/togetherai.d.ts +42 -0
  205. package/dist/providers/typesafe-ai/decisions.d.ts +2 -0
  206. package/dist/providers/typesafe-ai/decisions.js +1 -0
  207. package/dist/providers/typesafe-ai.d.ts +9 -10
  208. package/dist/providers/typesafe-ai.js +10 -8
  209. package/dist/providers/venice.d.ts +19 -0
  210. package/dist/providers/vercel-ai-gateway/decisions.d.ts +2 -0
  211. package/dist/providers/vercel-ai-gateway/decisions.js +1 -0
  212. package/dist/providers/vercel-ai-gateway/images.d.ts +2 -0
  213. package/dist/providers/vercel-ai-gateway/images.js +1 -0
  214. package/dist/providers/vercel-ai-gateway.d.ts +10 -16
  215. package/dist/providers/vercel-ai-gateway.js +31 -85
  216. package/dist/providers/xai/images.d.ts +2 -0
  217. package/dist/providers/xai/images.js +1 -0
  218. package/dist/providers/xai.d.ts +28 -5
  219. package/dist/providers/xai.js +15 -8
  220. package/dist/providers/zai/images.d.ts +2 -0
  221. package/dist/providers/zai/images.js +1 -0
  222. package/dist/providers/zai-coding-plan.d.ts +76 -17
  223. package/dist/providers/zai.d.ts +26 -4
  224. package/dist/providers/zai.js +15 -8
  225. package/dist/route/client.d.ts +2 -2
  226. package/dist/route/client.js +26 -4
  227. package/dist/route/decision.d.ts +58 -0
  228. package/dist/route/decision.js +75 -0
  229. package/dist/route/executor.d.ts +1 -1
  230. package/dist/route/framing.d.ts +2 -0
  231. package/dist/route/index.d.ts +3 -0
  232. package/dist/route/index.js +3 -0
  233. package/dist/route/media-protocol.d.ts +1 -0
  234. package/dist/route/media-protocol.js +12 -8
  235. package/dist/route/media.d.ts +5 -1
  236. package/dist/route/media.js +6 -2
  237. package/dist/route/transport/http.js +1 -0
  238. package/dist/route/transport/index.d.ts +1 -0
  239. package/dist/schema/events.d.ts +148 -6
  240. package/dist/schema/events.js +20 -0
  241. package/dist/schema/messages.d.ts +6 -2
  242. package/dist/schema/messages.js +3 -0
  243. package/dist/schema/options.d.ts +5 -3
  244. package/dist/schema/options.js +8 -3
  245. package/dist/speech-client.d.ts +5 -14
  246. package/dist/speech-client.js +0 -1
  247. package/dist/speech.d.ts +0 -135
  248. package/dist/speech.js +2 -4
  249. package/dist/testing.d.ts +25 -24
  250. package/dist/testing.js +3 -21
  251. package/dist/transcription-client.d.ts +5 -14
  252. package/dist/transcription.d.ts +0 -135
  253. package/dist/transcription.js +1 -1
  254. package/dist/utils/media-type.js +22 -1
  255. package/dist/video-client.d.ts +5 -14
  256. package/dist/video-client.js +0 -1
  257. package/dist/video.d.ts +1 -136
  258. package/dist/video.js +3 -5
  259. package/package.json +513 -11
  260. package/dist/experimental/evaluation-client.d.ts +0 -21
  261. package/dist/experimental/evaluation-client.js +0 -64
  262. package/dist/experimental/evaluation.d.ts +0 -242
  263. package/dist/experimental/evaluation.js +0 -108
  264. package/dist/experimental/system-one.d.ts +0 -16
  265. package/dist/experimental/system-one.js +0 -135
  266. package/dist/promise.d.ts +0 -1021
  267. package/dist/promise.js +0 -101
  268. package/dist/provider.d.ts +0 -23
  269. package/dist/provider.js +0 -2
@@ -5,7 +5,7 @@ import { MediaProtocol } from "../route/media-protocol.js";
5
5
  import { MediaRoute } from "../route/media.js";
6
6
  import { mergeJsonRecords } from "../schema/index.js";
7
7
  import { ProviderShared, optionalNull } from "./shared.js";
8
- import { MediaInput } from "./utils/media-input.js";
8
+ import { ImageSizing } from "./utils/image-sizing.js";
9
9
  const route = MediaProtocol.identity({ id: "bfl-images", name: "Black Forest Labs", provider: "black-forest-labs" });
10
10
  export const DEFAULT_BASE_URL = "https://api.bfl.ai";
11
11
  // ---------------------------------------------------------------------------
@@ -43,6 +43,8 @@ const STATUS = {
43
43
  "Task not found": "expired",
44
44
  };
45
45
  const isModerated = (status) => status === "Content Moderated" || status === "Request Moderated";
46
+ const LEGACY_LIMITS = { multiple: 32, minEdge: 256, maxEdge: 1440 };
47
+ const FLUX_2_LIMITS = { multiple: 16, minEdge: 64, maxPixels: 4_194_304 };
46
48
  const capabilities = (model) => {
47
49
  if (model.startsWith("flux-pro-1.0-fill"))
48
50
  return { sizing: "none", imageField: "image", maxImages: 1, mask: true };
@@ -53,23 +55,23 @@ const capabilities = (model) => {
53
55
  if (model.startsWith("flux-pro-1.1-ultra"))
54
56
  return { sizing: "aspectRatio", imageField: "image_prompt", maxImages: 1, mask: false };
55
57
  if (model.startsWith("flux-pro-1.1") || model.startsWith("flux-dev"))
56
- return { sizing: "dimensions", imageField: "image_prompt", maxImages: 1, mask: false };
58
+ return { sizing: LEGACY_LIMITS, imageField: "image_prompt", maxImages: 1, mask: false };
57
59
  if (model.startsWith("flux-2-klein"))
58
- return { sizing: "dimensions", imageField: "input_image", maxImages: 4, mask: false };
59
- return { sizing: "dimensions", imageField: "input_image", maxImages: 8, mask: false };
60
+ return { sizing: FLUX_2_LIMITS, imageField: "input_image", maxImages: 4, mask: false };
61
+ return { sizing: FLUX_2_LIMITS, imageField: "input_image", maxImages: 8, mask: false };
60
62
  };
61
63
  const validate = (request, model) => {
62
64
  const id = request.model.id;
63
65
  const images = request.images?.length ?? 0;
64
66
  if (request.n !== undefined && request.n > 1)
65
67
  return Effect.fail(route.unsupported("media.n", `${id} generates one image per request; call it once per image`));
66
- if (request.size !== undefined && model.sizing !== "dimensions")
67
- return Effect.fail(route.unsupported("media.size", `${id} does not take size (width and height)`));
68
- if (request.aspectRatio !== undefined && model.sizing !== "aspectRatio")
69
- return Effect.fail(route.unsupported("media.aspectRatio", `${id} does not take aspectRatio`));
68
+ if (request.aspect !== undefined && model.sizing === "none")
69
+ return Effect.fail(route.unsupported("media.aspect", `${id} keeps the source image's size`));
70
+ if (request.resolution !== undefined && typeof model.sizing === "string")
71
+ return Effect.fail(route.unsupported("media.resolution", `${id} does not take resolution`));
70
72
  if (images > model.maxImages)
71
73
  return Effect.fail(route.unsupported("media.images", `${id} takes at most ${model.maxImages} images`));
72
- if (request.mask !== undefined && !model.mask)
74
+ if (request.providerOptions?.mask !== undefined && !model.mask)
73
75
  return Effect.fail(route.unsupported("media.mask", `${id} does not inpaint; use flux-pro-1.0-fill`));
74
76
  return Effect.void;
75
77
  };
@@ -87,15 +89,15 @@ const fromRequest = Effect.fn("BlackForestLabsImages.fromRequest")(function* (re
87
89
  index === 0 ? model.imageField : `${model.imageField}_${index + 1}`,
88
90
  image,
89
91
  ]);
92
+ const { mask, ...native } = request.providerOptions ?? {};
93
+ const size = typeof model.sizing === "string" ? undefined : yield* ImageSizing.exact(route, request, model.sizing);
90
94
  return MediaProtocol.json(mergeJsonRecords({
91
95
  prompt: request.prompt,
92
- ...(request.size === undefined ? {} : MediaInput.dimensions(request.size)),
93
- aspect_ratio: request.aspectRatio,
94
- seed: request.seed,
95
- output_format: request.format,
96
- mask: request.mask === undefined ? undefined : yield* imageInput(request.mask),
96
+ ...size,
97
+ aspect_ratio: model.sizing === "aspectRatio" ? request.aspect : undefined,
98
+ mask: mask === undefined ? undefined : yield* imageInput(mask),
97
99
  ...Object.fromEntries(fields),
98
- }, request.providerOptions, request.http?.body) ?? {});
100
+ }, native, request.http?.body) ?? {});
99
101
  });
100
102
  // ---------------------------------------------------------------------------
101
103
  // 6. Response decoding
@@ -64,15 +64,6 @@ export declare const protocol: MediaProtocol.Streamed<Request, {
64
64
  readonly [x: string]: unknown;
65
65
  } | undefined;
66
66
  } | undefined;
67
- readonly notices?: readonly {
68
- readonly type: "filtered" | "moderated" | "other";
69
- readonly message: string;
70
- readonly providerMetadata?: {
71
- readonly [x: string]: {
72
- readonly [x: string]: unknown;
73
- };
74
- } | undefined;
75
- }[] | undefined;
76
67
  readonly providerMetadata?: {
77
68
  readonly [x: string]: {
78
69
  readonly [x: string]: unknown;
@@ -123,15 +114,6 @@ export declare const CartesiaSpeech: {
123
114
  readonly [x: string]: unknown;
124
115
  } | undefined;
125
116
  } | undefined;
126
- readonly notices?: readonly {
127
- readonly type: "filtered" | "moderated" | "other";
128
- readonly message: string;
129
- readonly providerMetadata?: {
130
- readonly [x: string]: {
131
- readonly [x: string]: unknown;
132
- };
133
- } | undefined;
134
- }[] | undefined;
135
117
  readonly providerMetadata?: {
136
118
  readonly [x: string]: {
137
119
  readonly [x: string]: unknown;
@@ -0,0 +1,9 @@
1
+ import { DecisionRoute } from "../route/decision.js";
2
+ /** Posts `{ model, input }` to Cloudflare's `/ai/run` with the System One body as `input`; media defaults to Clef's top-level lists. */
3
+ export declare const protocol: DecisionRoute.Protocol;
4
+ /** Providers set the Run API base, `.../client/v4/accounts/{account}/ai/run`, with `route.with(...)`. */
5
+ export declare const route: DecisionRoute.Route;
6
+ export declare const CloudflareRunDecisions: {
7
+ readonly protocol: DecisionRoute.Protocol;
8
+ readonly route: DecisionRoute.Route;
9
+ };
@@ -0,0 +1,36 @@
1
+ import { Effect, Schema } from "effect";
2
+ import { DecisionRoute } from "../route/decision.js";
3
+ import { Endpoint } from "../route/endpoint.js";
4
+ import { MediaProtocol } from "../route/media-protocol.js";
5
+ import { SystemOne } from "./system-one.js";
6
+ const ID = "cloudflare-run-decisions";
7
+ const NAME = "Cloudflare Run";
8
+ // Workers AI models answer with the System One response; third-party models such as TypeSafe Jev wrap it in a
9
+ // completed run record.
10
+ const Envelope = Schema.Struct({
11
+ result: Schema.Union([
12
+ SystemOne.Response,
13
+ Schema.Struct({ state: Schema.Literal("Completed"), result: SystemOne.Response }),
14
+ ]),
15
+ });
16
+ const decodeEnvelope = MediaProtocol.identity({ id: ID, name: NAME, provider: "cloudflare-workers-ai" }).decodeJson(Envelope);
17
+ /** Posts `{ model, input }` to Cloudflare's `/ai/run` with the System One body as `input`; media defaults to Clef's top-level lists. */
18
+ export const protocol = DecisionRoute.protocol({
19
+ id: ID,
20
+ name: NAME,
21
+ inlineMedia: true,
22
+ body: {
23
+ from: (request) => SystemOne.encodeBody(request, "root").pipe(Effect.map((input) => ({ model: request.model.id, input }))),
24
+ },
25
+ response: {
26
+ decode: (response, context) => decodeEnvelope(response).pipe(Effect.flatMap((output) => SystemOne.toResponse("answers" in output.value.result ? output.value.result : output.value.result.result, context.request, context.providerMetadataKey, output.invalid))),
27
+ },
28
+ });
29
+ /** Providers set the Run API base, `.../client/v4/accounts/{account}/ai/run`, with `route.with(...)`. */
30
+ export const route = DecisionRoute.make({
31
+ id: ID,
32
+ provider: "cloudflare-workers-ai",
33
+ protocol,
34
+ endpoint: Endpoint.path(""),
35
+ });
36
+ export const CloudflareRunDecisions = { protocol, route };
@@ -0,0 +1,23 @@
1
+ import { ImageModel, ImageResponse, type ImageRequestFor } from "../image.js";
2
+ import { MediaProtocol } from "../route/media-protocol.js";
3
+ import type { MediaRoute } from "../route/media.js";
4
+ /**
5
+ * Native Run API inputs. Step counts are `steps` on FLUX and Lucid Origin and `num_steps` on the other models;
6
+ * `aspect` and `resolution` lower to `width` and `height`.
7
+ */
8
+ export type CloudflareWorkersAIImageOptions = {
9
+ readonly width?: number;
10
+ readonly height?: number;
11
+ readonly seed?: number;
12
+ readonly steps?: number;
13
+ readonly num_steps?: number;
14
+ readonly guidance?: number;
15
+ readonly negative_prompt?: string;
16
+ } & Record<string, unknown>;
17
+ export type Request = ImageRequestFor<CloudflareWorkersAIImageOptions>;
18
+ export declare const protocol: MediaProtocol.Inline<Request, ImageResponse>;
19
+ export declare const model: (input: MediaRoute.ModelInput) => ImageModel<CloudflareWorkersAIImageOptions>;
20
+ export declare const CloudflareWorkersAIImages: {
21
+ readonly protocol: MediaProtocol.Inline<Request, ImageResponse>;
22
+ readonly model: typeof model;
23
+ };
@@ -0,0 +1,80 @@
1
+ import { Effect, Schema } from "effect";
2
+ import { ImageModel, ImageResponse } from "../image.js";
3
+ import { Media } from "../media.js";
4
+ import { MediaProtocol } from "../route/media-protocol.js";
5
+ import { mergeJsonRecords } from "../schema/index.js";
6
+ import { ProviderShared } from "./shared.js";
7
+ import { ImageSizing } from "./utils/image-sizing.js";
8
+ import { MediaInput } from "./utils/media-input.js";
9
+ const route = MediaProtocol.identity({
10
+ id: "cloudflare-workers-ai-images",
11
+ name: "Cloudflare Workers AI",
12
+ provider: "cloudflare-workers-ai",
13
+ });
14
+ /** FLUX.2 models only accept multipart form fields, even for a prompt alone. */
15
+ const MULTIPART_MODEL_PREFIX = "@cf/black-forest-labs/flux-2-";
16
+ const RESERVED_FORM_FIELDS = new Set(["prompt"]);
17
+ // ---------------------------------------------------------------------------
18
+ // 2. Response schema
19
+ // ---------------------------------------------------------------------------
20
+ const RunResponse = Schema.Struct({
21
+ result: Schema.Struct({
22
+ image: Schema.optional(Schema.String),
23
+ usage: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)),
24
+ }),
25
+ });
26
+ // ---------------------------------------------------------------------------
27
+ // 5. Request body construction
28
+ // ---------------------------------------------------------------------------
29
+ const fromRequest = Effect.fn("CloudflareWorkersAIImages.fromRequest")(function* (request) {
30
+ if (request.n !== undefined && request.n > 1)
31
+ return yield* route.unsupported("media.n", `${route.name} generates one image per request; call it once per image`);
32
+ const fields = {
33
+ prompt: request.prompt,
34
+ ...(yield* ImageSizing.exact(route, request, { multiple: 16, minEdge: 256, maxEdge: 2048 })),
35
+ };
36
+ const native = mergeJsonRecords(request.providerOptions, request.http?.body);
37
+ const images = request.images ?? [];
38
+ if (!request.model.id.startsWith(MULTIPART_MODEL_PREFIX)) {
39
+ if (images.length > 1)
40
+ return yield* route.unsupported("media.images", `${request.model.id} takes one input image as image_b64`);
41
+ const image = images[0]?.inline();
42
+ if (images[0] !== undefined && image === undefined)
43
+ return yield* ProviderShared.inlineRequired(route.id, images[0]);
44
+ return MediaProtocol.json(mergeJsonRecords({ ...fields, image_b64: image?.base64 }, native) ?? {});
45
+ }
46
+ const body = new FormData();
47
+ MediaInput.appendFields(body, fields, { overlay: native, reserved: RESERVED_FORM_FIELDS });
48
+ yield* Effect.forEach(images, (image, index) => MediaInput.inlineBytes(route.id, image).pipe(Effect.map((bytes) => body.append(`input_image_${index}`, MediaInput.blob(bytes, image.mediaType), `image_${index}`))));
49
+ return MediaProtocol.multipart(body);
50
+ });
51
+ // ---------------------------------------------------------------------------
52
+ // 6. Response decoding
53
+ // ---------------------------------------------------------------------------
54
+ const decodeDocument = route.decodeJson(RunResponse);
55
+ // FLUX and Lucid Origin wrap base64 in the Run API envelope; the Stable Diffusion family, DreamShaper, and Phoenix
56
+ // answer with the raw image, whose declared content type does not always match the bytes.
57
+ const decodeResponse = Effect.fn("CloudflareWorkersAIImages.decodeResponse")(function* (response) {
58
+ if (!response.headers["content-type"]?.startsWith("application/json"))
59
+ return new ImageResponse({ images: [Media.bytes(yield* route.bytes(response))] });
60
+ const output = yield* decodeDocument(response);
61
+ const result = output.value.result;
62
+ if (result.image === undefined)
63
+ return yield* output.invalid(`${route.name} returned no image`);
64
+ return new ImageResponse({
65
+ images: [yield* MediaInput.decodedAsset(output.invalid, `${route.name} result`, result.image, undefined)],
66
+ providerMetadata: result.usage === undefined ? undefined : { "cloudflare-workers-ai": { usage: result.usage } },
67
+ });
68
+ });
69
+ // ---------------------------------------------------------------------------
70
+ // 7. Protocol and route
71
+ // ---------------------------------------------------------------------------
72
+ export const protocol = MediaProtocol.inline(route, {
73
+ body: { from: fromRequest },
74
+ response: { decode: decodeResponse },
75
+ });
76
+ export const model = (input) => ImageModel.fromRoute({ protocol, path: ({ request }) => `/${request.model.id}` }, input);
77
+ export const CloudflareWorkersAIImages = {
78
+ protocol,
79
+ model,
80
+ };
@@ -57,15 +57,6 @@ export declare const protocol: MediaProtocol.Streamed<Request, {
57
57
  readonly [x: string]: unknown;
58
58
  } | undefined;
59
59
  } | undefined;
60
- readonly notices?: readonly {
61
- readonly type: "filtered" | "moderated" | "other";
62
- readonly message: string;
63
- readonly providerMetadata?: {
64
- readonly [x: string]: {
65
- readonly [x: string]: unknown;
66
- };
67
- } | undefined;
68
- }[] | undefined;
69
60
  readonly providerMetadata?: {
70
61
  readonly [x: string]: {
71
62
  readonly [x: string]: unknown;
@@ -116,15 +107,6 @@ export declare const DeepgramSpeech: {
116
107
  readonly [x: string]: unknown;
117
108
  } | undefined;
118
109
  } | undefined;
119
- readonly notices?: readonly {
120
- readonly type: "filtered" | "moderated" | "other";
121
- readonly message: string;
122
- readonly providerMetadata?: {
123
- readonly [x: string]: {
124
- readonly [x: string]: unknown;
125
- };
126
- } | undefined;
127
- }[] | undefined;
128
110
  readonly providerMetadata?: {
129
111
  readonly [x: string]: {
130
112
  readonly [x: string]: unknown;
@@ -60,15 +60,6 @@ export declare const protocol: MediaProtocol.Streamed<Request, {
60
60
  readonly [x: string]: unknown;
61
61
  } | undefined;
62
62
  } | undefined;
63
- readonly notices?: readonly {
64
- readonly type: "filtered" | "moderated" | "other";
65
- readonly message: string;
66
- readonly providerMetadata?: {
67
- readonly [x: string]: {
68
- readonly [x: string]: unknown;
69
- };
70
- } | undefined;
71
- }[] | undefined;
72
63
  readonly providerMetadata?: {
73
64
  readonly [x: string]: {
74
65
  readonly [x: string]: unknown;
@@ -119,15 +110,6 @@ export declare const ElevenLabsSpeech: {
119
110
  readonly [x: string]: unknown;
120
111
  } | undefined;
121
112
  } | undefined;
122
- readonly notices?: readonly {
123
- readonly type: "filtered" | "moderated" | "other";
124
- readonly message: string;
125
- readonly providerMetadata?: {
126
- readonly [x: string]: {
127
- readonly [x: string]: unknown;
128
- };
129
- } | undefined;
130
- }[] | undefined;
131
113
  readonly providerMetadata?: {
132
114
  readonly [x: string]: {
133
115
  readonly [x: string]: unknown;
@@ -1,9 +1,18 @@
1
1
  import { ImageModel, ImageResponse, type ImageRequestFor } from "../image.js";
2
+ import { Media } from "../media.js";
2
3
  import { MediaProtocol } from "../route/media-protocol.js";
3
4
  import { MediaRoute } from "../route/media.js";
4
5
  import { type OpenString } from "../schema/index.js";
6
+ /** Model-defined `input` fields; `aspect` and `resolution` lower to `image_size` or `aspect_ratio` per model. */
5
7
  export type FalImageOptions = {
6
- readonly image_size?: OpenString<"square_hd" | "square" | "portrait_4_3" | "portrait_16_9" | "landscape_4_3" | "landscape_16_9">;
8
+ readonly image_size?: OpenString<"square_hd" | "square" | "portrait_4_3" | "portrait_16_9" | "landscape_4_3" | "landscape_16_9"> | {
9
+ readonly width: number;
10
+ readonly height: number;
11
+ };
12
+ readonly seed?: number;
13
+ readonly output_format?: OpenString<"jpeg" | "png" | "webp">;
14
+ /** Inpainting mask, sent as `mask_url`. */
15
+ readonly mask?: Media.Asset;
7
16
  readonly enable_safety_checker?: boolean;
8
17
  } & Record<string, unknown>;
9
18
  export type Request = ImageRequestFor<FalImageOptions>;
@@ -4,9 +4,9 @@ import { Media } from "../media.js";
4
4
  import { MediaProtocol } from "../route/media-protocol.js";
5
5
  import { MediaRoute } from "../route/media.js";
6
6
  import { mergeJsonRecords } from "../schema/index.js";
7
- import { ProviderShared, optionalNull } from "./shared.js";
7
+ import { optionalNull } from "./shared.js";
8
8
  import { FalQueue } from "./utils/fal-queue.js";
9
- import { MediaInput } from "./utils/media-input.js";
9
+ import { ImageSizing } from "./utils/image-sizing.js";
10
10
  const route = MediaProtocol.identity({ id: "fal-images", name: "fal Images", provider: "fal" });
11
11
  // ---------------------------------------------------------------------------
12
12
  // 2. Response schema
@@ -24,8 +24,11 @@ const QueueResult = Schema.StructWithRest(Schema.Struct({
24
24
  // ---------------------------------------------------------------------------
25
25
  // 5. Request body construction
26
26
  // ---------------------------------------------------------------------------
27
+ /** Nano Banana takes `aspect_ratio` and `resolution` tiers, FLUX Ultra and Kontext only `aspect_ratio`, FLUX `image_size`. */
27
28
  const sizing = (model) => {
28
- if (/^fal-ai\/(nano-banana|flux-pro\/(v1\.1-ultra|kontext))/.test(model))
29
+ if (model.startsWith("fal-ai/nano-banana"))
30
+ return "tiers";
31
+ if (/^fal-ai\/flux-pro\/(v1\.1-ultra|kontext)/.test(model))
29
32
  return "aspect_ratio";
30
33
  if (model.startsWith("fal-ai/flux"))
31
34
  return "image_size";
@@ -33,13 +36,8 @@ const sizing = (model) => {
33
36
  };
34
37
  const validate = (request) => {
35
38
  const id = request.model.id;
36
- const field = sizing(id);
37
- if (request.size !== undefined && request.aspectRatio !== undefined)
38
- return Effect.fail(ProviderShared.invalidRequest(`${route.name} accepts either size or aspectRatio, not both`));
39
- if (request.size !== undefined && field === "aspect_ratio")
40
- return Effect.fail(route.unsupported("media.size", `${id} sizes by aspectRatio`));
41
- if (request.aspectRatio !== undefined && field === "image_size")
42
- return Effect.fail(route.unsupported("media.aspectRatio", `${id} sizes by size (image_size)`));
39
+ if (request.resolution !== undefined && sizing(id) === "aspect_ratio")
40
+ return Effect.fail(route.unsupported("media.resolution", `${id} sizes by aspect only`));
43
41
  if ((request.images?.length ?? 0) > 1 && !takesImageList(id))
44
42
  return Effect.fail(route.unsupported("media.images", `${id} takes one image_url; use an /edit or /multi endpoint for several images`));
45
43
  return Effect.void;
@@ -51,17 +49,18 @@ const fromRequest = Effect.fn("FalImages.fromRequest")(function* (request) {
51
49
  yield* validate(request);
52
50
  const images = yield* Effect.forEach(request.images ?? [], (image) => FalQueue.mediaUrl(image, route.name));
53
51
  const list = takesImageList(request.model.id);
52
+ const { mask, ...native } = request.providerOptions ?? {};
53
+ const field = sizing(request.model.id);
54
54
  return MediaProtocol.json(mergeJsonRecords({
55
55
  prompt: request.prompt,
56
56
  num_images: request.n,
57
- seed: request.seed,
58
- image_size: request.size === undefined ? undefined : MediaInput.dimensions(request.size),
59
- aspect_ratio: request.aspectRatio,
60
- output_format: request.format,
57
+ ...(field === "image_size"
58
+ ? { image_size: yield* ImageSizing.exact(route, request, { multiple: 16 }) }
59
+ : { aspect_ratio: request.aspect, resolution: request.resolution }),
61
60
  image_urls: list && images.length > 0 ? images : undefined,
62
61
  image_url: list ? undefined : images[0],
63
- mask_url: request.mask === undefined ? undefined : yield* FalQueue.mediaUrl(request.mask, route.name),
64
- }, request.providerOptions, request.http?.body) ?? {});
62
+ mask_url: mask === undefined ? undefined : yield* FalQueue.mediaUrl(mask, route.name),
63
+ }, native, request.http?.body) ?? {});
65
64
  });
66
65
  // ---------------------------------------------------------------------------
67
66
  // 6. Response decoding
@@ -69,11 +68,9 @@ const fromRequest = Effect.fn("FalImages.fromRequest")(function* (request) {
69
68
  const decodeQueueResult = route.decodeJson(QueueResult);
70
69
  const decodeResult = Effect.fn("FalImages.decodeResult")(function* (response, context) {
71
70
  const output = yield* decodeQueueResult(response);
72
- const { images, seed, has_nsfw_concepts, ...rest } = output.value;
71
+ const { images, seed, ...rest } = output.value;
73
72
  if (images.length === 0)
74
73
  return yield* output.invalid(`${route.name} returned no images`);
75
- // With the safety checker on, flagged images come back blacked out rather than omitted.
76
- const flagged = (has_nsfw_concepts ?? []).flatMap((value, index) => (value ? [index] : []));
77
74
  return new ImageResponse({
78
75
  images: images.map((image) => {
79
76
  const info = { width: image.width ?? undefined, height: image.height ?? undefined };
@@ -81,12 +78,6 @@ const decodeResult = Effect.fn("FalImages.decodeResult")(function* (response, co
81
78
  return (Media.parseDataUrl(image.url, { info }) ??
82
79
  Media.url(image.url, { mediaType: image.content_type ?? undefined, info }));
83
80
  }),
84
- notices: flagged.length === 0
85
- ? undefined
86
- : flagged.map((index) => ({
87
- type: "moderated",
88
- message: `${route.name} flagged image ${index} as NSFW`,
89
- })),
90
81
  providerMetadata: { fal: { requestId: context.token.requestID, seed: seed ?? undefined, ...rest } },
91
82
  });
92
83
  });
@@ -31,7 +31,7 @@ const fromRequest = Effect.fn("FalVideo.fromRequest")(function* (request) {
31
31
  prompt: request.prompt,
32
32
  negative_prompt: request.negativePrompt,
33
33
  seed: request.seed,
34
- aspect_ratio: request.aspectRatio,
34
+ aspect_ratio: request.aspect,
35
35
  resolution: request.resolution,
36
36
  generate_audio: request.audio,
37
37
  image_url: imageUrl,
@@ -105,6 +105,7 @@ declare const GeminiBody: Schema.Struct<{
105
105
  }>;
106
106
  export type GeminiBody = Schema.Schema.Type<typeof GeminiBody>;
107
107
  declare const GeminiUsage: Schema.Struct<{
108
+ readonly cost: Schema.optionalKey<Schema.middlewareDecoding<Schema.UndefinedOr<Schema.Finite>, never>>;
108
109
  readonly cachedContentTokenCount: Schema.optional<Schema.NullOr<Schema.Number>>;
109
110
  readonly thoughtsTokenCount: Schema.optional<Schema.NullOr<Schema.Number>>;
110
111
  readonly promptTokenCount: Schema.optional<Schema.NullOr<Schema.Number>>;
@@ -259,6 +260,7 @@ export declare const protocol: Protocol<{
259
260
  readonly safetyRatings?: unknown;
260
261
  } | null | undefined;
261
262
  readonly usageMetadata?: {
263
+ readonly cost?: number | undefined;
262
264
  readonly cachedContentTokenCount?: number | null | undefined;
263
265
  readonly thoughtsTokenCount?: number | null | undefined;
264
266
  readonly promptTokenCount?: number | null | undefined;
@@ -286,6 +288,7 @@ export declare const protocol: Protocol<{
286
288
  readonly safetyRatings?: unknown;
287
289
  } | null | undefined;
288
290
  readonly usageMetadata?: {
291
+ readonly cost?: number | undefined;
289
292
  readonly cachedContentTokenCount?: number | null | undefined;
290
293
  readonly thoughtsTokenCount?: number | null | undefined;
291
294
  readonly promptTokenCount?: number | null | undefined;
@@ -59,7 +59,6 @@ const GeminiInlineDataPart = Schema.Struct({
59
59
  }),
60
60
  thoughtSignature: optionalNull(Schema.String),
61
61
  });
62
- /** Gemini Files API reference; the only remote input Gemini accepts. */
63
62
  const GeminiFileDataPart = Schema.Struct({
64
63
  fileData: Schema.Struct({
65
64
  mimeType: Schema.String,
@@ -172,6 +171,7 @@ const GeminiUsage = Schema.Struct({
172
171
  promptTokenCount: optionalNull(Schema.Number),
173
172
  candidatesTokenCount: optionalNull(Schema.Number),
174
173
  totalTokenCount: optionalNull(Schema.Number),
174
+ ...ProviderShared.ReportedBilling.fields,
175
175
  });
176
176
  const GeminiCandidate = Schema.Struct({
177
177
  content: optionalNull(GeminiResponseContent),
@@ -329,11 +329,13 @@ const lowerMessages = Effect.fnUntraced(function* (request) {
329
329
  for (const item of content) {
330
330
  if (item.type === "text")
331
331
  continue;
332
- const value = yield* ProviderShared.requireInlineMedia("Gemini", ProviderShared.toolFileMedia(item).media);
333
- media.push({ inlineData: { mimeType: value.mime, data: value.base64 } });
332
+ const value = yield* GeminiGenerateContent.mediaPart("Gemini", GeminiGenerateContent.toolMedia(item));
333
+ // Nested fileData can be accepted without the model seeing the video, even on newer Gemini models.
334
+ if (legacyToolMedia || "fileData" in value)
335
+ (pendingMedia ??= []).push(value);
336
+ else
337
+ media.push(value);
334
338
  }
335
- if (legacyToolMedia && media.length > 0)
336
- (pendingMedia ??= []).push(...media);
337
339
  parts.push({
338
340
  functionResponse: {
339
341
  ...(omitCallIds ? {} : { id: part.id }),
@@ -342,7 +344,7 @@ const lowerMessages = Effect.fnUntraced(function* (request) {
342
344
  name: part.name,
343
345
  content: text.join("\n"),
344
346
  },
345
- parts: legacyToolMedia || media.length === 0 ? undefined : media,
347
+ parts: media.length === 0 ? undefined : media,
346
348
  },
347
349
  });
348
350
  }
@@ -430,6 +432,7 @@ const mapUsage = (usage, metadataKey, metadata = usage ?? {}) => {
430
432
  cacheReadInputTokens: cached,
431
433
  reasoningTokens: thoughts,
432
434
  totalTokens: ProviderShared.totalTokens(promptTokens, outputTokens, usage.totalTokenCount ?? undefined),
435
+ cost: usage.cost,
433
436
  providerMetadata: providerMetadata(metadataKey, metadata),
434
437
  });
435
438
  };
@@ -443,6 +446,8 @@ const mapContinuedUsage = (requests, metadataKey) => {
443
446
  cachedContentTokenCount: requests[0].cachedContentTokenCount,
444
447
  candidatesTokenCount: sum("candidatesTokenCount"),
445
448
  thoughtsTokenCount: sum("thoughtsTokenCount"),
449
+ // Every continued request is billed on its own.
450
+ cost: sum("cost"),
446
451
  }, metadataKey, {
447
452
  promptTokenCount: sum("promptTokenCount"),
448
453
  cachedContentTokenCount: sum("cachedContentTokenCount"),
@@ -3,9 +3,9 @@ import { MediaProtocol } from "../route/media-protocol.js";
3
3
  import { MediaRoute } from "../route/media.js";
4
4
  import { type OpenString } from "../schema/index.js";
5
5
  export declare const DEFAULT_BASE_URL = "https://generativelanguage.googleapis.com/v1beta";
6
- /** Provider-native options. Common fields (`aspectRatio`, `seed`, `images`) live on the request. */
6
+ /** Provider-native `generationConfig` fields. Common fields (`aspect`, `resolution`, `images`) live on the request. */
7
7
  export type GoogleImageOptions = {
8
- readonly imageSize?: OpenString<"1K" | "2K" | "4K">;
8
+ readonly seed?: number;
9
9
  readonly thinkingLevel?: OpenString<"MINIMAL" | "LOW" | "MEDIUM" | "HIGH">;
10
10
  readonly includeThoughts?: boolean;
11
11
  } & Record<string, unknown>;
@@ -2,7 +2,7 @@ import { Effect, Schema } from "effect";
2
2
  import { ImageModel, ImageResponse } from "../image.js";
3
3
  import { MediaProtocol } from "../route/media-protocol.js";
4
4
  import { MediaRoute } from "../route/media.js";
5
- import { mergeJsonRecords } from "../schema/index.js";
5
+ import { mergeJsonRecords, tokenUsage } from "../schema/index.js";
6
6
  import { ProviderShared } from "./shared.js";
7
7
  import { GeminiGenerateContent } from "./utils/gemini-generate-content.js";
8
8
  import { MediaInput } from "./utils/media-input.js";
@@ -49,13 +49,12 @@ const GoogleImageResponse = Schema.Struct({
49
49
  // 5. Request body construction
50
50
  // ---------------------------------------------------------------------------
51
51
  const generationConfig = (request) => {
52
- const { imageSize, thinkingLevel, includeThoughts, ...native } = request.providerOptions ?? {};
53
- const imageConfig = { aspectRatio: request.aspectRatio, imageSize };
52
+ const { thinkingLevel, includeThoughts, ...native } = request.providerOptions ?? {};
53
+ const imageConfig = { aspectRatio: request.aspect, imageSize: request.resolution };
54
54
  const thinkingConfig = { thinkingLevel, includeThoughts };
55
55
  return (mergeJsonRecords({
56
56
  responseModalities: ["IMAGE"],
57
57
  imageConfig: Object.values(imageConfig).some((value) => value !== undefined) ? imageConfig : undefined,
58
- seed: request.seed,
59
58
  thinkingConfig: Object.values(thinkingConfig).some((value) => value !== undefined) ? thinkingConfig : undefined,
60
59
  }, native) ?? { responseModalities: ["IMAGE"] });
61
60
  };
@@ -119,45 +118,18 @@ const decodeResponse = Effect.fn("GoogleImages.decodeResponse")(function* (respo
119
118
  }));
120
119
  if (images.length === 0) {
121
120
  const finishReasons = candidates.flatMap((candidate) => candidate.finishReason === undefined ? [] : [candidate.finishReason]);
121
+ // Safety and recitation stops are Google refusing the prompt, not a malformed response.
122
+ if (finishReasons.some(GeminiGenerateContent.contentFiltered))
123
+ return yield* output.contentPolicy(`${route.name} withheld its images (finish reasons: ${finishReasons.join(", ")})`);
122
124
  return yield* output.invalid(`${route.name} returned no final images${finishReasons.length === 0 ? "" : ` (finish reasons: ${finishReasons.join(", ")})`}; inspect body for prompt feedback and candidate details`);
123
125
  }
124
- // Candidates that stopped for a safety or policy reason are partial results, not a silent drop.
125
- const notices = [
126
- ...(decoded.promptFeedback === undefined
127
- ? []
128
- : [
129
- {
130
- type: "filtered",
131
- message: `${route.name} reported prompt feedback`,
132
- providerMetadata: { google: { promptFeedback: decoded.promptFeedback } },
133
- },
134
- ]),
135
- ...candidates.flatMap((candidate, index) => candidate.finishReason === undefined || candidate.finishReason === "STOP"
136
- ? []
137
- : [
138
- {
139
- type: "filtered",
140
- message: `${route.name} candidate ${candidate.index ?? index} finished with ${candidate.finishReason}${candidate.finishMessage === undefined ? "" : `: ${candidate.finishMessage}`}`,
141
- providerMetadata: {
142
- google: {
143
- candidateIndex: candidate.index ?? index,
144
- finishReason: candidate.finishReason,
145
- finishMessage: candidate.finishMessage,
146
- safetyRatings: candidate.safetyRatings,
147
- },
148
- },
149
- },
150
- ]),
151
- ];
152
126
  const usage = decoded.usageMetadata;
153
127
  const outputTokens = usage?.candidatesTokenCount === undefined ? undefined : usage.candidatesTokenCount + (usage.thoughtsTokenCount ?? 0);
154
128
  return new ImageResponse({
155
129
  images,
156
- notices: notices.length === 0 ? undefined : notices,
157
130
  usage: usage === undefined
158
131
  ? undefined
159
- : {
160
- type: "tokens",
132
+ : tokenUsage({
161
133
  input: usage.promptTokenCount,
162
134
  output: outputTokens,
163
135
  total: ProviderShared.totalTokens(usage.promptTokenCount, outputTokens, usage.totalTokenCount),
@@ -166,7 +138,7 @@ const decodeResponse = Effect.fn("GoogleImages.decodeResponse")(function* (respo
166
138
  cacheReadInputTokens: usage.cachedContentTokenCount,
167
139
  google: usage,
168
140
  },
169
- },
141
+ }),
170
142
  providerMetadata: {
171
143
  google: {
172
144
  modelVersion: decoded.modelVersion,
@@ -181,7 +153,6 @@ const decodeResponse = Effect.fn("GoogleImages.decodeResponse")(function* (respo
181
153
  // 7. Protocol and route
182
154
  // ---------------------------------------------------------------------------
183
155
  export const protocol = MediaProtocol.inline(route, {
184
- unsupported: ["mask", "size", "format"],
185
156
  body: { from: fromRequest },
186
157
  response: { decode: decodeResponse },
187
158
  });
@@ -165,6 +165,10 @@ export declare const protocol: Protocol<{
165
165
  readonly total_tokens?: number | null | undefined;
166
166
  readonly raw_prompt_token?: number | null | undefined;
167
167
  } | undefined;
168
+ readonly errors?: readonly {
169
+ readonly code?: string | undefined;
170
+ readonly message?: string | undefined;
171
+ }[] | undefined;
168
172
  };
169
173
  } | {
170
174
  readonly event_type: "error";