@opencode/ai 0.0.0-dev-21741 → 0.0.0-dev-21744

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 (40) hide show
  1. package/README.md +50 -43
  2. package/dist/image.d.ts +6 -41
  3. package/dist/image.js +3 -8
  4. package/dist/index.d.ts +2 -2
  5. package/dist/index.js +1 -1
  6. package/dist/protocols/alibaba-images.d.ts +4 -1
  7. package/dist/protocols/alibaba-images.js +3 -2
  8. package/dist/protocols/bfl-images.d.ts +9 -0
  9. package/dist/protocols/bfl-images.js +17 -15
  10. package/dist/protocols/cloudflare-workers-ai-images.d.ts +7 -1
  11. package/dist/protocols/cloudflare-workers-ai-images.js +3 -3
  12. package/dist/protocols/fal-images.d.ts +10 -1
  13. package/dist/protocols/fal-images.js +15 -16
  14. package/dist/protocols/fal-video.js +1 -1
  15. package/dist/protocols/google-images.d.ts +2 -2
  16. package/dist/protocols/google-images.js +2 -4
  17. package/dist/protocols/google-video.d.ts +1 -1
  18. package/dist/protocols/google-video.js +1 -1
  19. package/dist/protocols/meta-images.d.ts +7 -1
  20. package/dist/protocols/meta-images.js +15 -4
  21. package/dist/protocols/openai-images.d.ts +6 -1
  22. package/dist/protocols/openai-images.js +45 -5
  23. package/dist/protocols/replicate-images.js +1 -1
  24. package/dist/protocols/runway-video.d.ts +1 -1
  25. package/dist/protocols/runway-video.js +1 -1
  26. package/dist/protocols/stability-images.d.ts +5 -0
  27. package/dist/protocols/stability-images.js +4 -6
  28. package/dist/protocols/utils/image-sizing.d.ts +34 -0
  29. package/dist/protocols/utils/image-sizing.js +79 -0
  30. package/dist/protocols/utils/media-input.d.ts +0 -4
  31. package/dist/protocols/utils/media-input.js +0 -4
  32. package/dist/protocols/xai-images.d.ts +1 -2
  33. package/dist/protocols/xai-images.js +15 -3
  34. package/dist/protocols/xai-video.d.ts +1 -1
  35. package/dist/protocols/xai-video.js +1 -1
  36. package/dist/protocols/zai-images.d.ts +3 -1
  37. package/dist/protocols/zai-images.js +12 -2
  38. package/dist/video.d.ts +1 -1
  39. package/dist/video.js +2 -2
  40. package/package.json +3 -3
@@ -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
  };
@@ -181,7 +180,6 @@ const decodeResponse = Effect.fn("GoogleImages.decodeResponse")(function* (respo
181
180
  // 7. Protocol and route
182
181
  // ---------------------------------------------------------------------------
183
182
  export const protocol = MediaProtocol.inline(route, {
184
- unsupported: ["mask", "size", "format"],
185
183
  body: { from: fromRequest },
186
184
  response: { decode: decodeResponse },
187
185
  });
@@ -4,7 +4,7 @@ import { MediaRoute } from "../route/media.js";
4
4
  import { type OpenString } from "../schema/index.js";
5
5
  import { VideoModel, VideoResponse, type VideoRequestFor } from "../video.js";
6
6
  export declare const DEFAULT_BASE_URL = "https://generativelanguage.googleapis.com/v1beta";
7
- /** Provider-native `parameters`. Common fields (`aspectRatio`, `resolution`, `durationSeconds`, `seed`) live on the request. */
7
+ /** Provider-native `parameters`. Common fields (`aspect`, `resolution`, `durationSeconds`, `seed`) live on the request. */
8
8
  export type GoogleVideoOptions = {
9
9
  readonly personGeneration?: OpenString<"allow_all" | "allow_adult" | "dont_allow">;
10
10
  } & Record<string, unknown>;
@@ -68,7 +68,7 @@ const fromRequest = Effect.fn("GoogleVideo.fromRequest")(function* (request) {
68
68
  },
69
69
  ],
70
70
  parameters: mergeJsonRecords({
71
- aspectRatio: request.aspectRatio,
71
+ aspectRatio: request.aspect,
72
72
  resolution: request.resolution,
73
73
  durationSeconds: request.durationSeconds,
74
74
  negativePrompt: request.negativePrompt,
@@ -3,8 +3,14 @@ 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://api.meta.ai/v1";
6
- /** Provider-native options. Common fields (`n`, `size`, `format`, `images`) live on the request. */
6
+ /**
7
+ * Provider-native options. Common fields (`n`, `aspect`, `images`) live on the request; Meta picks its own output
8
+ * resolution (about 2.5 megapixels), so `resolution` is ignored with a notice.
9
+ */
7
10
  export type ImageOptions = {
11
+ /** `WIDTHxHEIGHT` aspect ratio hint; it replaces `aspect`, so setting both fails. */
12
+ readonly size?: string;
13
+ readonly outputFormat?: OpenString<"webp" | "png" | "jpeg">;
8
14
  readonly responseFormat?: OpenString<"b64_json" | "url">;
9
15
  readonly reasoningStrength?: OpenString<"low" | "high">;
10
16
  readonly toolEnablement?: {
@@ -5,6 +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 { JsonObject, ProviderShared, optionalNull } from "./shared.js";
8
+ import { ImageSizing } from "./utils/image-sizing.js";
8
9
  import { MediaInput } from "./utils/media-input.js";
9
10
  const route = MediaProtocol.identity({ id: "meta-images", name: "Meta Images", provider: "meta" });
10
11
  export const DEFAULT_BASE_URL = "https://api.meta.ai/v1";
@@ -40,14 +41,17 @@ const isEdit = (request) => (request.images?.length ?? 0) > 0;
40
41
  const reference = (asset) => ProviderShared.mediaReference(asset, undefined, route.name).pipe(Effect.map((item) => ({ image_url: item.value })));
41
42
  const fromRequest = Effect.fn("MetaImages.fromRequest")(function* (request) {
42
43
  const images = yield* Effect.forEach(request.images ?? [], reference);
43
- const { responseFormat, reasoningStrength, toolEnablement, ...native } = request.providerOptions ?? {};
44
+ const { outputFormat, responseFormat, reasoningStrength, toolEnablement, ...native } = request.providerOptions ?? {};
45
+ if (native.size !== undefined && request.aspect !== undefined)
46
+ return yield* ProviderShared.invalidRequest("Meta providerOptions.size replaces aspect; set one or the other");
47
+ const hint = request.aspect === undefined ? undefined : ImageSizing.fit({ aspect: request.aspect }, { multiple: 16 });
44
48
  const payload = yield* ProviderShared.validateWith(Schema.decodeUnknownEffect(Body))(mergeJsonRecords({
45
49
  model: request.model.id,
46
50
  prompt: request.prompt,
47
51
  images: images.length === 0 ? undefined : images,
48
52
  n: request.n,
49
- size: request.size,
50
- output_format: request.format,
53
+ size: hint === undefined ? undefined : `${hint.width}x${hint.height}`,
54
+ output_format: outputFormat,
51
55
  response_format: responseFormat,
52
56
  reasoning_strength: reasoningStrength,
53
57
  tool_enablement: toolEnablement,
@@ -71,6 +75,14 @@ const decodeResponse = Effect.fn("MetaImages.decodeResponse")(function* (respons
71
75
  return yield* output.invalid(`${route.name} returned no images`);
72
76
  return new ImageResponse({
73
77
  images,
78
+ notices: context.request.resolution === undefined
79
+ ? undefined
80
+ : [
81
+ {
82
+ type: "other",
83
+ message: `${route.name} picks its own output resolution; ignored ${context.request.resolution}`,
84
+ },
85
+ ],
74
86
  usage: decoded.usage === undefined
75
87
  ? undefined
76
88
  : {
@@ -87,7 +99,6 @@ const decodeResponse = Effect.fn("MetaImages.decodeResponse")(function* (respons
87
99
  // 7. Protocol and route
88
100
  // ---------------------------------------------------------------------------
89
101
  export const protocol = MediaProtocol.inline(route, {
90
- unsupported: ["mask", "aspectRatio", "seed"],
91
102
  body: { from: fromRequest },
92
103
  response: { decode: decodeResponse },
93
104
  });
@@ -7,8 +7,13 @@ import { type OpenString } from "../schema/index.js";
7
7
  export declare const DEFAULT_BASE_URL = "https://api.openai.com/v1";
8
8
  export declare const PATH = "/images/generations";
9
9
  export declare const EDIT_PATH = "/images/edits";
10
- /** Provider-native options. Common fields (`n`, `size`, `format`, `images`, `mask`) live on the request. */
10
+ /** Provider-native options. Common fields (`n`, `aspect`, `resolution`, `images`) live on the request. */
11
11
  export type OpenAIImageOptions = {
12
+ /** Exact `WIDTHxHEIGHT` or `auto`; it replaces `aspect` and `resolution`, so setting both fails. */
13
+ readonly size?: OpenString<"auto" | "1024x1024" | "1536x1024" | "1024x1536">;
14
+ readonly outputFormat?: OpenString<"png" | "jpeg" | "webp">;
15
+ /** Inpainting mask for the first input image. */
16
+ readonly mask?: Media.Asset;
12
17
  readonly quality?: OpenString<"auto" | "low" | "medium" | "high" | "standard" | "hd">;
13
18
  readonly background?: OpenString<"auto" | "opaque" | "transparent">;
14
19
  readonly moderation?: OpenString<"auto" | "low">;
@@ -6,6 +6,7 @@ import { MediaProtocol } from "../route/media-protocol.js";
6
6
  import { MediaRoute } from "../route/media.js";
7
7
  import { mergeJsonRecords, ProviderID } from "../schema/index.js";
8
8
  import { ProviderShared } from "./shared.js";
9
+ import { ImageSizing } from "./utils/image-sizing.js";
9
10
  import { MediaInput } from "./utils/media-input.js";
10
11
  const route = MediaProtocol.identity({ id: "openai-images", name: "OpenAI Images", provider: "openai" });
11
12
  export const DEFAULT_BASE_URL = "https://api.openai.com/v1";
@@ -62,8 +63,38 @@ const RESERVED_FORM_FIELDS = new Set(["model", "prompt", "image", "image[]", "im
62
63
  const nativeOptions = (options) => {
63
64
  if (!options)
64
65
  return undefined;
65
- const { outputCompression, partialImages: _, ...native } = options;
66
- return { output_compression: outputCompression, ...native };
66
+ const { outputCompression, outputFormat, partialImages: _, mask: __, ...native } = options;
67
+ return { output_compression: outputCompression, output_format: outputFormat, ...native };
68
+ };
69
+ /**
70
+ * `gpt-image-1`, `chatgpt-image` and DALL·E take a fixed list, `gpt-image-2` and later any size within limits. Other
71
+ * models are gateway-hosted (`bfl/flux-2-pro`); the gateway passes `size` through to them as is.
72
+ */
73
+ const sizes = (model) => {
74
+ const id = model.slice(model.lastIndexOf("/") + 1);
75
+ if (id.startsWith("dall-e-2"))
76
+ return [256, 512, 1024].map((edge) => ({ width: edge, height: edge }));
77
+ if (id.startsWith("dall-e-3"))
78
+ return [
79
+ { width: 1024, height: 1024 },
80
+ { width: 1792, height: 1024 },
81
+ { width: 1024, height: 1792 },
82
+ ];
83
+ if (/^(gpt-image-1|chatgpt-image)/.test(id))
84
+ return [
85
+ { width: 1024, height: 1024 },
86
+ { width: 1536, height: 1024 },
87
+ { width: 1024, height: 1536 },
88
+ ];
89
+ if (id.startsWith("gpt-image-"))
90
+ return { multiple: 16, maxEdge: 3840, minPixels: 655_360, maxPixels: 8_294_400, maxRatio: 3 };
91
+ return { multiple: 16 };
92
+ };
93
+ const size = (request) => {
94
+ if (!ImageSizing.isRequested(request))
95
+ return undefined;
96
+ const options = sizes(request.model.id);
97
+ return "multiple" in options ? ImageSizing.fit(request, options) : ImageSizing.nearest(request, options);
67
98
  };
68
99
  const streamOptions = (request) => {
69
100
  if (request.mode !== "stream")
@@ -77,10 +108,17 @@ const isInline = (asset) => asset.source.type === "bytes" || asset.source.type =
77
108
  const reference = (asset, provider) => ProviderShared.mediaReference(asset, provider, route.name).pipe(Effect.map((item) => (item.type === "ref" ? { file_id: item.value } : { image_url: item.value })));
78
109
  const fromRequest = Effect.fn("OpenAIImages.fromRequest")(function* (request) {
79
110
  const images = request.images ?? [];
80
- const mask = request.mask;
111
+ const mask = request.providerOptions?.mask;
81
112
  if (mask !== undefined && images.length === 0)
82
113
  return yield* ProviderShared.invalidRequest("An OpenAI image mask requires at least one input image");
83
- const fields = mergeJsonRecords({ n: request.n, size: request.size, output_format: request.format, ...(yield* streamOptions(request)) }, nativeOptions(request.providerOptions), request.http?.body);
114
+ if (request.providerOptions?.size !== undefined && ImageSizing.isRequested(request))
115
+ return yield* ProviderShared.invalidRequest("OpenAI providerOptions.size replaces aspect and resolution; set one or the other");
116
+ const chosen = size(request);
117
+ const fields = mergeJsonRecords({
118
+ n: request.n,
119
+ size: chosen === undefined ? undefined : `${chosen.width}x${chosen.height}`,
120
+ ...(yield* streamOptions(request)),
121
+ }, nativeOptions(request.providerOptions), request.http?.body);
84
122
  // Owned bytes go through multipart edits; remote URLs and file IDs use the JSON edits body instead.
85
123
  if (images.length > 0 && images.every(isInline) && (mask === undefined || isInline(mask))) {
86
124
  const form = new FormData();
@@ -166,9 +204,12 @@ const finish = (state, context) => {
166
204
  if (state.completed === 0)
167
205
  return Effect.fail(route.incomplete());
168
206
  const provider = context.request.model.provider;
207
+ const chosen = size(context.request);
208
+ const notice = chosen === undefined ? undefined : ImageSizing.notice(route.name, context.request, chosen);
169
209
  return Effect.succeed([
170
210
  ImageFinishEvent.make({
171
211
  usage: usage(state.usage, provider),
212
+ notices: notice === undefined ? undefined : [notice],
172
213
  providerMetadata: {
173
214
  [provider]: {
174
215
  outputFormat: state.format,
@@ -184,7 +225,6 @@ const finish = (state, context) => {
184
225
  // 7. Protocol and route
185
226
  // ---------------------------------------------------------------------------
186
227
  export const protocol = MediaProtocol.stream(route, {
187
- unsupported: ["aspectRatio", "seed"],
188
228
  body: { from: fromRequest },
189
229
  frames: (bytes, context) => context.request.mode === "stream"
190
230
  ? Framing.sse.frame(bytes)
@@ -110,7 +110,7 @@ const decodeResult = Effect.fn("ReplicateImages.decodeResult")(function* (respon
110
110
  // ---------------------------------------------------------------------------
111
111
  export const protocol = MediaProtocol.queued(route, {
112
112
  token: Token,
113
- unsupported: ["images", "mask", "n", "size", "aspectRatio", "seed", "format"],
113
+ unsupported: ["images", "n", "aspect", "resolution"],
114
114
  start: { body: { from: fromRequest }, decode: decodeStart },
115
115
  status: { path: (token) => token.getURL, decode: decodeStatus },
116
116
  result: { path: (token) => token.getURL, decode: decodeResult },
@@ -11,7 +11,7 @@ export declare const IMAGE_TO_VIDEO_PATH = "/image_to_video";
11
11
  export declare const VIDEO_TO_VIDEO_PATH = "/video_to_video";
12
12
  export declare const TASKS_PATH = "/tasks";
13
13
  /**
14
- * Provider-native options. Common fields lower to Runway's names: `aspectRatio` → `ratio` (Runway expects pixel
14
+ * Provider-native options. Common fields lower to Runway's names: `aspect` → `ratio` (Runway expects pixel
15
15
  * ratios such as `1280:720` for most models), `durationSeconds` → `duration`, `audio`, `negativePrompt`,
16
16
  * `resolution`, `references`, and `frames` → `promptImage`.
17
17
  */
@@ -58,7 +58,7 @@ const fromRequest = Effect.fn("RunwayVideo.fromRequest")(function* (request) {
58
58
  promptImage: promptImage.length === 0 ? undefined : promptImage,
59
59
  videoUri,
60
60
  references: references.length === 0 ? undefined : references,
61
- ratio: request.aspectRatio,
61
+ ratio: request.aspect,
62
62
  duration: request.durationSeconds,
63
63
  resolution: request.resolution,
64
64
  audio: request.audio,
@@ -5,7 +5,10 @@ import { MediaRoute } from "../route/media.js";
5
5
  import { type OpenString } from "../schema/index.js";
6
6
  export declare const DEFAULT_BASE_URL = "https://api.stability.ai";
7
7
  export type StabilityStylePreset = OpenString<"enhance" | "anime" | "photographic" | "digital-art" | "comic-book" | "fantasy-art" | "line-art" | "analog-film" | "neon-punk" | "isometric" | "low-poly" | "origami" | "modeling-compound" | "cinematic" | "3d-model" | "pixel-art" | "tile-texture">;
8
+ /** Native form fields; `aspect` lowers to `aspect_ratio`. */
8
9
  export type StabilityImageOptions = {
10
+ readonly seed?: number;
11
+ readonly output_format?: OpenString<"jpeg" | "png" | "webp">;
9
12
  readonly negative_prompt?: string;
10
13
  readonly style_preset?: StabilityStylePreset;
11
14
  readonly strength?: number;
@@ -13,6 +16,8 @@ export type StabilityImageOptions = {
13
16
  } & Record<string, unknown>;
14
17
  /** Creative upscale options; the one `images` source is the image to upscale. */
15
18
  export type StabilityUpscaleOptions = {
19
+ readonly seed?: number;
20
+ readonly output_format?: OpenString<"jpeg" | "png" | "webp">;
16
21
  readonly negative_prompt?: string;
17
22
  readonly style_preset?: StabilityStylePreset;
18
23
  readonly creativity?: number;
@@ -49,9 +49,7 @@ const fromRequest = Effect.fn("StabilityImages.fromRequest")(function* (request)
49
49
  return yield* route.unsupported("media.images", `${route.name} core is text-to-image only; use ultra or sd3.5-*`);
50
50
  return yield* form(route, {
51
51
  prompt: request.prompt,
52
- aspect_ratio: request.aspectRatio,
53
- seed: request.seed,
54
- output_format: request.format,
52
+ aspect_ratio: request.aspect,
55
53
  model: target === "sd3" ? request.model.id : undefined,
56
54
  mode: target === "sd3" && edit ? "image-to-image" : undefined,
57
55
  }, mergeJsonRecords(request.providerOptions, request.http?.body), request.images);
@@ -59,7 +57,7 @@ const fromRequest = Effect.fn("StabilityImages.fromRequest")(function* (request)
59
57
  const fromUpscaleRequest = Effect.fn("StabilityImages.fromUpscaleRequest")(function* (request) {
60
58
  if ((request.images?.length ?? 0) === 0)
61
59
  return yield* ProviderShared.invalidRequest(`${upscaleRoute.name} upscale requires the source image in images`);
62
- return yield* form(upscaleRoute, { prompt: request.prompt, seed: request.seed, output_format: request.format }, mergeJsonRecords(request.providerOptions, request.http?.body), request.images);
60
+ return yield* form(upscaleRoute, { prompt: request.prompt }, mergeJsonRecords(request.providerOptions, request.http?.body), request.images);
63
61
  });
64
62
  // ---------------------------------------------------------------------------
65
63
  // 6. Response decoding
@@ -104,13 +102,13 @@ const decodeUpscaleResult = Effect.fn("StabilityImages.decodeUpscaleResult")(fun
104
102
  // 7. Protocol and route
105
103
  // ---------------------------------------------------------------------------
106
104
  export const protocol = MediaProtocol.inline(route, {
107
- unsupported: ["size", "mask"],
105
+ unsupported: ["resolution"],
108
106
  body: { from: fromRequest },
109
107
  response: { decode: decodeResponse },
110
108
  });
111
109
  export const upscaleProtocol = MediaProtocol.queued(upscaleRoute, {
112
110
  token: Token,
113
- unsupported: ["n", "size", "aspectRatio", "mask"],
111
+ unsupported: ["n", "aspect", "resolution"],
114
112
  start: { body: { from: fromUpscaleRequest }, decode: decodeStart },
115
113
  status: { path: (token) => `${RESULTS_PATH}/${token.id}`, decode: decodeStatus },
116
114
  result: { path: (token) => `${RESULTS_PATH}/${token.id}`, decode: decodeUpscaleResult },
@@ -0,0 +1,34 @@
1
+ import { Effect } from "effect";
2
+ import type { Media } from "../../media.js";
3
+ import type { MediaProtocol } from "../../route/media-protocol.js";
4
+ export interface Size {
5
+ readonly width: number;
6
+ readonly height: number;
7
+ }
8
+ /** The shared `aspect` and `resolution` fields of an image request. */
9
+ export interface Shape {
10
+ readonly aspect?: string;
11
+ readonly resolution?: string;
12
+ }
13
+ /** What a provider accepts for free width and height. */
14
+ export interface Limits {
15
+ readonly multiple: number;
16
+ readonly minEdge?: number;
17
+ readonly maxEdge?: number;
18
+ readonly minPixels?: number;
19
+ readonly maxPixels?: number;
20
+ /** Long edge over short edge. */
21
+ readonly maxRatio?: number;
22
+ }
23
+ export declare const isRequested: (shape: Shape) => boolean;
24
+ /** `1K` is 1, `2K` is 2, `0.5K` is 0.5; anything else is not a tier. */
25
+ export declare const tier: (resolution: string) => number | undefined;
26
+ /** Free width and height: the tier sets the pixel count (`1K` is about 1024²), the aspect sets the proportions. */
27
+ export declare const fit: (shape: Shape, limits: Limits) => Size;
28
+ /** The listed size closest to the shape: nearest aspect ratio first, then nearest pixel count. */
29
+ export declare const nearest: (shape: Shape, sizes: ReadonlyArray<Size>) => Size;
30
+ /** Reports a size more than 2% off the requested aspect or more than √2 per edge off the requested tier. */
31
+ export declare const notice: (name: string, shape: Shape, size: Size) => Media.Notice | undefined;
32
+ /** Free width and height that must honor the shape; a size that misses it fails instead of returning a notice. */
33
+ export declare const exact: (route: MediaProtocol.Identity, shape: Shape, limits: Limits) => Effect.Effect<undefined, never, never> | Effect.Effect<never, import("../../index.js").AIError, never> | Effect.Effect<Size, never, never>;
34
+ export * as ImageSizing from "./image-sizing.js";
@@ -0,0 +1,79 @@
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
+ /** Reports a size more than 2% off the requested aspect or more than √2 per edge off the requested tier. */
40
+ export const notice = (name, shape, size) => {
41
+ const requested = missed(shape, size);
42
+ if (requested === undefined)
43
+ return undefined;
44
+ return { type: "other", message: `${name} doesn't offer ${requested}; used ${describe(size)}` };
45
+ };
46
+ /** Free width and height that must honor the shape; a size that misses it fails instead of returning a notice. */
47
+ export const exact = (route, shape, limits) => {
48
+ if (!isRequested(shape))
49
+ return Effect.succeed(undefined);
50
+ const size = fit(shape, limits);
51
+ const requested = missed(shape, size);
52
+ if (requested === undefined)
53
+ return Effect.succeed(size);
54
+ 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`));
55
+ };
56
+ const missed = (shape, size) => {
57
+ const aspectMissed = shape.aspect !== undefined && Math.abs(Math.log(size.width / size.height / aspectRatio(shape))) > 0.02;
58
+ const requestedTier = shape.resolution === undefined ? undefined : tier(shape.resolution);
59
+ const resolutionMissed = shape.resolution !== undefined &&
60
+ (requestedTier === undefined ||
61
+ Math.abs(Math.log2(Math.sqrt(size.width * size.height) / (requestedTier * 1024))) > 0.5);
62
+ if (!aspectMissed && !resolutionMissed)
63
+ return undefined;
64
+ return [shape.aspect, shape.resolution].filter((value) => value !== undefined).join(" at ");
65
+ };
66
+ const aspectRatio = (shape) => {
67
+ const [width, height] = (shape.aspect ?? "1:1").split(":").map(Number);
68
+ return width / height;
69
+ };
70
+ const targetPixels = (shape) => ((tier(shape.resolution ?? "1K") ?? 1) * 1024) ** 2;
71
+ const describe = (size) => {
72
+ const divisor = gcd(size.width, size.height);
73
+ const width = size.width / divisor;
74
+ const height = size.height / divisor;
75
+ const ratio = width <= 32 && height <= 32 ? `${width}:${height}` : `${(size.width / size.height).toFixed(2)}:1`;
76
+ return `${size.width}x${size.height} (${ratio})`;
77
+ };
78
+ const gcd = (a, b) => (b === 0 ? a : gcd(b, a % b));
79
+ export * as ImageSizing from "./image-sizing.js";
@@ -7,10 +7,6 @@ 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. */
@@ -27,10 +27,6 @@ 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. */
@@ -5,9 +5,8 @@ import { type OpenString } from "../schema/index.js";
5
5
  export declare const DEFAULT_BASE_URL = "https://api.x.ai/v1";
6
6
  export declare const PATH = "/images/generations";
7
7
  export declare const EDIT_PATH = "/images/edits";
8
- /** Provider-native options. Common fields (`n`, `aspectRatio`, `images`) live on the request. */
8
+ /** Provider-native options. Common fields (`n`, `aspect`, `resolution`, `images`) live on the request. */
9
9
  export type XAIImageOptions = {
10
- readonly resolution?: OpenString<"1k" | "2k">;
11
10
  readonly responseFormat?: OpenString<"url" | "b64_json">;
12
11
  readonly response_format?: OpenString<"url" | "b64_json">;
13
12
  } & Record<string, unknown>;
@@ -5,6 +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 { JsonObject, ProviderShared, lenient, optionalNull } from "./shared.js";
8
+ import { ImageSizing } from "./utils/image-sizing.js";
8
9
  import { MediaInput } from "./utils/media-input.js";
9
10
  const route = MediaProtocol.identity({ id: "xai-images", name: "xAI Images", provider: "xai" });
10
11
  export const DEFAULT_BASE_URL = "https://api.x.ai/v1";
@@ -31,6 +32,12 @@ const nativeOptions = (options) => {
31
32
  const { responseFormat, ...native } = options;
32
33
  return { response_format: responseFormat, ...native };
33
34
  };
35
+ /** xAI renders `1k` or `2k`; other tiers use the nearest one. */
36
+ const resolution = (request) => {
37
+ if (request.resolution === undefined)
38
+ return undefined;
39
+ return (ImageSizing.tier(request.resolution) ?? 1) < 1.5 ? "1k" : "2k";
40
+ };
34
41
  const isEdit = (request) => (request.images?.length ?? 0) > 0;
35
42
  const reference = (asset) => ProviderShared.mediaReference(asset, route.provider, route.name).pipe(Effect.map((item) => item.type === "ref" ? { file_id: item.value } : { url: item.value, type: "image_url" }));
36
43
  const fromRequest = Effect.fn("XAIImages.fromRequest")(function* (request) {
@@ -42,16 +49,19 @@ const fromRequest = Effect.fn("XAIImages.fromRequest")(function* (request) {
42
49
  image: references.length === 1 ? references[0] : undefined,
43
50
  images: references.length > 1 ? references : undefined,
44
51
  n: request.n,
45
- aspect_ratio: request.aspectRatio,
52
+ aspect_ratio: request.aspect,
53
+ resolution: resolution(request),
46
54
  }, nativeOptions(request.providerOptions), request.http?.body) ?? {});
47
55
  });
48
56
  // ---------------------------------------------------------------------------
49
57
  // 6. Response decoding
50
58
  // ---------------------------------------------------------------------------
51
59
  const decodeDocument = route.decodeJson(XAIImageResponse);
52
- const decodeResponse = Effect.fn("XAIImages.decodeResponse")(function* (response) {
60
+ const decodeResponse = Effect.fn("XAIImages.decodeResponse")(function* (response, context) {
53
61
  const output = yield* decodeDocument(response);
54
62
  const decoded = output.value;
63
+ const requested = context.request.resolution;
64
+ const used = resolution(context.request);
55
65
  const images = yield* Effect.forEach(decoded.data, (item, index) => MediaInput.imageOutput(output.invalid, `${route.name} result ${index}`, item, item.mime_type ?? undefined, {
56
66
  providerMetadata: item.revised_prompt === undefined || item.revised_prompt === null
57
67
  ? undefined
@@ -63,6 +73,9 @@ const decodeResponse = Effect.fn("XAIImages.decodeResponse")(function* (response
63
73
  // provider metadata.
64
74
  return new ImageResponse({
65
75
  images,
76
+ notices: requested === undefined || requested.toLowerCase() === used
77
+ ? undefined
78
+ : [{ type: "other", message: `${route.name} doesn't offer ${requested}; used ${used}` }],
66
79
  providerMetadata: decoded.usage === undefined ? undefined : { xai: { usage: decoded.usage } },
67
80
  });
68
81
  });
@@ -70,7 +83,6 @@ const decodeResponse = Effect.fn("XAIImages.decodeResponse")(function* (response
70
83
  // 7. Protocol and route
71
84
  // ---------------------------------------------------------------------------
72
85
  export const protocol = MediaProtocol.inline(route, {
73
- unsupported: ["mask", "size", "seed", "format"],
74
86
  body: { from: fromRequest },
75
87
  response: { decode: decodeResponse },
76
88
  });
@@ -8,7 +8,7 @@ export declare const EDIT_PATH = "/videos/edits";
8
8
  export declare const EXTEND_PATH = "/videos/extensions";
9
9
  export declare const STATUS_PATH = "/videos";
10
10
  /**
11
- * Provider-native options. Common fields (`frames`, `references`, `video`, `durationSeconds`, `aspectRatio`,
11
+ * Provider-native options. Common fields (`frames`, `references`, `video`, `durationSeconds`, `aspect`,
12
12
  * `resolution`, `audio`) live on the request. `mode` selects the endpoint a `video` input is sent to.
13
13
  */
14
14
  export type XAIVideoOptions = {
@@ -65,7 +65,7 @@ const fromRequest = Effect.fn("XAIVideo.fromRequest")(function* (request) {
65
65
  reference_images: references.length === 0 ? undefined : references,
66
66
  video,
67
67
  duration: request.durationSeconds,
68
- aspect_ratio: request.aspectRatio,
68
+ aspect_ratio: request.aspect,
69
69
  resolution: request.resolution,
70
70
  generate_audio: request.audio,
71
71
  }, nativeOptions(request.providerOptions), request.http?.body) ?? {});
@@ -4,8 +4,10 @@ import { MediaRoute } from "../route/media.js";
4
4
  import { type OpenString } from "../schema/index.js";
5
5
  export declare const DEFAULT_BASE_URL = "https://api.z.ai/api/paas/v4";
6
6
  export declare const PATH = "/images/generations";
7
- /** Provider-native options. The common `size` field lives on the request. */
7
+ /** Provider-native options. Common `aspect` and `resolution` lower to `size`. */
8
8
  export type ZAIImageOptions = {
9
+ /** Exact `WIDTHxHEIGHT`; it wins over `aspect` and `resolution`. */
10
+ readonly size?: string;
9
11
  readonly quality?: OpenString<"hd" | "standard">;
10
12
  readonly userID?: string;
11
13
  } & Record<string, unknown>;
@@ -3,6 +3,7 @@ import { ImageModel, ImageResponse } from "../image.js";
3
3
  import { MediaProtocol } from "../route/media-protocol.js";
4
4
  import { MediaRoute } from "../route/media.js";
5
5
  import { mergeJsonRecords } from "../schema/index.js";
6
+ import { ImageSizing } from "./utils/image-sizing.js";
6
7
  const route = MediaProtocol.identity({ id: "zai-images", name: "Z.ai Images", provider: "zai" });
7
8
  export const DEFAULT_BASE_URL = "https://api.z.ai/api/paas/v4";
8
9
  export const PATH = "/images/generations";
@@ -29,8 +30,17 @@ const nativeOptions = (options) => {
29
30
  const { userID, ...native } = options;
30
31
  return { user_id: userID, ...native };
31
32
  };
33
+ /** GLM-Image takes 1024–2048 px edges in steps of 32; CogView takes 512–2048 px in steps of 16. */
34
+ const limits = (model) => model.startsWith("glm-image")
35
+ ? { multiple: 32, minEdge: 1024, maxEdge: 2048, maxPixels: 2 ** 22 }
36
+ : { multiple: 16, minEdge: 512, maxEdge: 2048, maxPixels: 2 ** 21 };
32
37
  const fromRequest = Effect.fn("ZAIImages.fromRequest")(function* (request) {
33
- return MediaProtocol.json(mergeJsonRecords({ model: request.model.id, prompt: request.prompt, size: request.size }, nativeOptions(request.providerOptions), request.http?.body) ?? {});
38
+ const size = yield* ImageSizing.exact(route, request, limits(request.model.id));
39
+ return MediaProtocol.json(mergeJsonRecords({
40
+ model: request.model.id,
41
+ prompt: request.prompt,
42
+ size: size === undefined ? undefined : `${size.width}x${size.height}`,
43
+ }, nativeOptions(request.providerOptions), request.http?.body) ?? {});
34
44
  });
35
45
  // ---------------------------------------------------------------------------
36
46
  // 6. Response decoding
@@ -67,7 +77,7 @@ const decodeResponse = Effect.fn("ZAIImages.decodeResponse")(function* (response
67
77
  // 7. Protocol and route
68
78
  // ---------------------------------------------------------------------------
69
79
  export const protocol = MediaProtocol.inline(route, {
70
- unsupported: ["images", "mask", "n", "aspectRatio", "seed", "format"],
80
+ unsupported: ["images", "n"],
71
81
  body: { from: fromRequest },
72
82
  response: { decode: decodeResponse },
73
83
  });
package/dist/video.d.ts CHANGED
@@ -224,7 +224,7 @@ declare const VideoRequest_base: Schema.Class<VideoRequest, Schema.Struct<{
224
224
  readonly providerMetadata: Schema.optional<Schema.$Record<Schema.String, Schema.$Record<Schema.String, Schema.Unknown>>>;
225
225
  }>, never, never>>;
226
226
  readonly durationSeconds: Schema.optional<Schema.Number>;
227
- readonly aspectRatio: Schema.optional<Schema.declare<`${number}:${number}`, `${number}:${number}`>>;
227
+ readonly aspect: Schema.optional<Schema.declare<`${number}:${number}`, `${number}:${number}`>>;
228
228
  readonly resolution: Schema.optional<Schema.String>;
229
229
  /** Whether to generate an audio track; routes whose audio is always on fail typed on `false`. */
230
230
  readonly audio: Schema.optional<Schema.Boolean>;
package/dist/video.js CHANGED
@@ -3,7 +3,7 @@ import { Generation, ProgressEvent, QueuedEvent } from "./generation.js";
3
3
  import { Media } from "./media.js";
4
4
  import { MediaModel, composeRoute, tryRequest } from "./media-model.js";
5
5
  import { MediaRoute } from "./route/media.js";
6
- import { AIError, HttpOptions, MediaUsage, ProviderMetadata, ProviderOptions, } from "./schema/index.js";
6
+ import { AIError, HttpOptions, MediaUsage, ProviderMetadata, ProviderOptions } from "./schema/index.js";
7
7
  import { VideoClient, Service } from "./video-client.js";
8
8
  export class VideoModel extends MediaModel {
9
9
  static fromRoute(route, input) {
@@ -33,7 +33,7 @@ export class VideoRequest extends Schema.Class("Video.Request")({
33
33
  /** Source video for edit or extension routes. */
34
34
  video: Schema.optional(Media.AssetSchema),
35
35
  durationSeconds: Schema.optional(Schema.Number),
36
- aspectRatio: Schema.optional(VideoAspectRatio),
36
+ aspect: Schema.optional(VideoAspectRatio),
37
37
  resolution: Schema.optional(Schema.String),
38
38
  /** Whether to generate an audio track; routes whose audio is always on fail typed on `false`. */
39
39
  audio: Schema.optional(Schema.Boolean),