@opencode/ai 0.0.0-dev-203 → 0.0.0-dev-216

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.
package/README.md CHANGED
@@ -701,13 +701,14 @@ table before swapping only the `model`:
701
701
  | Provider | `n` | `aspect` | `resolution` | `images` | Moved to `providerOptions` |
702
702
  | --------------------- | --- | -------------------- | --------------------- | -------------------------------- | -------------------------------------------------- |
703
703
  | OpenAI | ✓¹ | nearest size | nearest size | ✓ | `size`, `outputFormat`, `mask` |
704
- | Google (Gemini) | 1 | ✓ | ✓ (`imageSize`) | ✓ (no public URLs) | `seed` |
704
+ | Google (Gemini) | 1 | ✓ | ✓ (`0.5K` as `512`) | ✓ (no public URLs) | `seed` |
705
705
  | xAI | ✓ | ✓ | `1k`/`2k` | ✓ | none |
706
706
  | Meta | ✓ | ✓ (hint) | ignored | ✓ | `size`, `outputFormat` |
707
707
  | Z.ai | ✗ | width × height | width × height | ✗ | `size` |
708
708
  | Alibaba | ✓ | width × height | width × height | ✓ | `size`, `seed` |
709
709
  | MiniMax | ✓ | preset or w × h⁴ | preset or w × h⁴ | 1 (portrait subject) | `aspect_ratio`, `width`, `height`, `seed` |
710
710
  | Vercel AI Gateway | ✓ | as OpenAI³ | as OpenAI³ | per model | as OpenAI |
711
+ | OpenRouter | ✓ | ✓ (`aspect_ratio`) | tier⁵ | per model⁵ | `size`, `outputFormat` (no `mask`) |
711
712
  | Cloudflare Workers AI | 1 | width × height² | width × height² | ✗ | `width`, `height`, `seed` |
712
713
 
713
714
  ✓ lowers natively; ✗ fails whenever the field is set (including `n: 1`); `1` means `n > 1` fails. "width × height"
@@ -717,8 +718,11 @@ fixed sizes. `providerOptions.size` replaces `aspect` and `resolution`, so setti
717
718
  forwards `outputFormat` but does not apply it, so the returned bytes keep the upstream model's own format. ² Workers AI
718
719
  `@cf/black-forest-labs/flux-1-schnell` takes no size, and the provider rejects it. ³ Non-OpenAI gateway models
719
720
  (`bfl/flux-2-pro`) get a computed width × height, which the gateway passes through; models with a fixed list, such as
720
- Recraft, reject sizes outside it. ⁴ MiniMax sends its `aspect_ratio` preset for a preset aspect at about `1K` and an
721
+ Recraft, reject sizes outside it. Grok (`spacexai/*`, `xai/*`) ignores `size`, so it gets `providerOptions.xai`
722
+ `aspect_ratio` and `1k`/`2k` instead. ⁴ MiniMax sends its `aspect_ratio` preset for a preset aspect at about `1K` and an
721
723
  exact width × height (512–2048 px, steps of 8) otherwise; `image-01-live` takes only the presets, minus `21:9`.
724
+ ⁵ OpenRouter takes `512`, `768`, `1K`, `1.5K`, `2K` or `4K` rather than pixels; other values are left out. It has no
725
+ edits endpoint, so input images go to `/images/generations` as `input_references` (data URLs or http(s) URLs).
722
726
 
723
727
  `Media.Asset` is the one asset type shared by image requests, image responses, LLM messages, and tool results.
724
728
  `asset.source` is the serializable `Media.Source` (`bytes`, `base64`, `url`, or `ref`); `asset.bytes()`,
@@ -50,7 +50,9 @@ const GoogleImageResponse = Schema.Struct({
50
50
  // ---------------------------------------------------------------------------
51
51
  const generationConfig = (request) => {
52
52
  const { thinkingLevel, includeThoughts, ...native } = request.providerOptions ?? {};
53
- const imageConfig = { aspectRatio: request.aspect, imageSize: request.resolution };
53
+ // Google names the half tier `512` and rejects `0.5K`.
54
+ const imageSize = request.resolution?.toUpperCase() === "0.5K" ? "512" : request.resolution?.toUpperCase();
55
+ const imageConfig = { aspectRatio: request.aspect, imageSize };
54
56
  const thinkingConfig = { thinkingLevel, includeThoughts };
55
57
  return (mergeJsonRecords({
56
58
  responseModalities: ["IMAGE"],
@@ -41,6 +41,15 @@ interface State {
41
41
  readonly background?: string;
42
42
  readonly usage?: Schema.Schema.Type<typeof Usage>;
43
43
  }
44
+ /** The body fields `aspect` and `resolution` lower to; gateways that read other fields than `size` pass their own. */
45
+ export type OpenAIImageSizing = (request: Request) => Record<string, unknown> | undefined;
46
+ /**
47
+ * How input images travel. `edits` is OpenAI's `/images/edits`, uploading owned bytes as multipart; `json-edits` sends
48
+ * every edit there as JSON with data URLs, for hosts that reject multipart (the ChatGPT backend); `references` keeps
49
+ * every request on `/images/generations` and lists them as `input_references`, for gateways without an edits endpoint
50
+ * (OpenRouter).
51
+ */
52
+ export type OpenAIImageInput = "edits" | "json-edits" | "references";
44
53
  export declare const protocol: MediaProtocol.Streamed<Request, {
45
54
  readonly type: "image-partial";
46
55
  readonly index: number;
@@ -86,9 +95,14 @@ export declare const protocol: MediaProtocol.Streamed<Request, {
86
95
  };
87
96
  } | undefined;
88
97
  }, Frame, State>;
89
- /** `provider` attributes models, refs, and metadata to an OpenAI-compatible host; it defaults to `openai`. */
98
+ /**
99
+ * `provider` attributes models, refs, and metadata to an OpenAI-compatible host; it defaults to `openai`. `sizing`
100
+ * replaces the `size` that `aspect` and `resolution` lower to, and `imageInput` how input images are sent.
101
+ */
90
102
  export declare const model: (input: MediaRoute.ModelInput & {
91
103
  readonly provider?: string;
104
+ readonly sizing?: OpenAIImageSizing;
105
+ readonly imageInput?: OpenAIImageInput;
92
106
  }) => ImageModel<OpenAIImageOptions>;
93
107
  export declare const OpenAIImages: {
94
108
  readonly protocol: MediaProtocol.Streamed<Request, {
@@ -137,5 +151,6 @@ export declare const OpenAIImages: {
137
151
  } | undefined;
138
152
  }, Frame, State>;
139
153
  readonly model: typeof model;
154
+ readonly pixelSize: OpenAIImageSizing;
140
155
  };
141
156
  export {};
@@ -117,11 +117,12 @@ const sizes = (model) => {
117
117
  return { multiple: 16, maxEdge: 3840, minPixels: 655_360, maxPixels: 8_294_400, maxRatio: 3 };
118
118
  return { multiple: 16 };
119
119
  };
120
- const size = (request) => {
120
+ const pixelSize = (request) => {
121
121
  if (!ImageSizing.isRequested(request))
122
122
  return undefined;
123
123
  const options = sizes(request.model.id);
124
- return "multiple" in options ? ImageSizing.fit(request, options) : ImageSizing.nearest(request, options);
124
+ const size = "multiple" in options ? ImageSizing.fit(request, options) : ImageSizing.nearest(request, options);
125
+ return { size: `${size.width}x${size.height}` };
125
126
  };
126
127
  const streamOptions = (request) => {
127
128
  if (request.mode !== "stream")
@@ -133,21 +134,35 @@ const streamOptions = (request) => {
133
134
  const isEdit = (request) => (request.images?.length ?? 0) > 0;
134
135
  const isInline = (asset) => asset.source.type === "bytes" || asset.source.type === "base64";
135
136
  const reference = (asset, provider) => ProviderShared.mediaReference(asset, provider, route.name).pipe(Effect.map((item) => (item.type === "ref" ? { file_id: item.value } : { image_url: item.value })));
136
- const fromRequest = Effect.fn("OpenAIImages.fromRequest")(function* (request) {
137
+ const fromRequest = Effect.fn("OpenAIImages.fromRequest")(function* (request, options) {
137
138
  const images = request.images ?? [];
138
139
  const mask = request.providerOptions?.mask;
140
+ if (options.imageInput === "references" && mask !== undefined)
141
+ return yield* route.unsupported("media.mask", `${request.model.provider} image edits take no mask`);
139
142
  if (mask !== undefined && images.length === 0)
140
143
  return yield* ProviderShared.invalidRequest("An OpenAI image mask requires at least one input image");
141
144
  if (request.providerOptions?.size !== undefined && ImageSizing.isRequested(request))
142
145
  return yield* ProviderShared.invalidRequest("OpenAI providerOptions.size replaces aspect and resolution; set one or the other");
143
- const chosen = size(request);
144
146
  const fields = mergeJsonRecords({
145
147
  n: request.n,
146
- size: chosen === undefined ? undefined : `${chosen.width}x${chosen.height}`,
148
+ ...options.sizing(request),
147
149
  ...(yield* streamOptions(request)),
148
150
  }, nativeOptions(request.providerOptions), request.http?.body);
149
- // Owned bytes go through multipart edits; remote URLs and file IDs use the JSON edits body instead.
150
- if (images.length > 0 && images.every(isInline) && (mask === undefined || isInline(mask))) {
151
+ if (options.imageInput === "references") {
152
+ const references = yield* Effect.forEach(images, (image) => ProviderShared.mediaReference(image, undefined, route.name));
153
+ return MediaProtocol.json(mergeJsonRecords({
154
+ model: request.model.id,
155
+ prompt: request.prompt,
156
+ input_references: references.length === 0
157
+ ? undefined
158
+ : references.map((item) => ({ type: "image_url", image_url: { url: item.value } })),
159
+ }, fields) ?? {});
160
+ }
161
+ // Owned bytes go through multipart edits; remote URLs, file IDs and `json-edits` hosts use the JSON edits body.
162
+ if (options.imageInput === "edits" &&
163
+ images.length > 0 &&
164
+ images.every(isInline) &&
165
+ (mask === undefined || isInline(mask))) {
151
166
  const form = new FormData();
152
167
  MediaInput.appendFields(form, { model: request.model.id, prompt: request.prompt }, { overlay: fields, reserved: RESERVED_FORM_FIELDS });
153
168
  const uploads = yield* Effect.forEach(images, (image) => MediaInput.inlineBytes(route.id, image));
@@ -256,8 +271,8 @@ const finish = (state, context) => {
256
271
  // ---------------------------------------------------------------------------
257
272
  // 7. Protocol and route
258
273
  // ---------------------------------------------------------------------------
259
- export const protocol = MediaProtocol.stream(route, {
260
- body: { from: fromRequest },
274
+ const makeProtocol = (options) => MediaProtocol.stream(route, {
275
+ body: { from: (request) => fromRequest(request, options) },
261
276
  frames: (bytes, context) => context.request.mode === "stream"
262
277
  ? Framing.sse.frame(bytes)
263
278
  : Framing.document.frame(bytes).pipe(Stream.map((document) => ({ document }))),
@@ -265,13 +280,24 @@ export const protocol = MediaProtocol.stream(route, {
265
280
  step,
266
281
  finish,
267
282
  });
268
- /** `provider` attributes models, refs, and metadata to an OpenAI-compatible host; it defaults to `openai`. */
269
- export const model = (input) => ImageModel.fromRoute({
270
- protocol: input.provider === undefined ? protocol : { ...protocol, provider: ProviderID.make(input.provider) },
271
- baseURL: DEFAULT_BASE_URL,
272
- path: ({ request }) => (isEdit(request) ? EDIT_PATH : PATH),
273
- }, input);
283
+ export const protocol = makeProtocol({ sizing: pixelSize, imageInput: "edits" });
284
+ /**
285
+ * `provider` attributes models, refs, and metadata to an OpenAI-compatible host; it defaults to `openai`. `sizing`
286
+ * replaces the `size` that `aspect` and `resolution` lower to, and `imageInput` how input images are sent.
287
+ */
288
+ export const model = (input) => {
289
+ const imageInput = input.imageInput ?? "edits";
290
+ const base = input.sizing === undefined && imageInput === "edits"
291
+ ? protocol
292
+ : makeProtocol({ sizing: input.sizing ?? pixelSize, imageInput });
293
+ return ImageModel.fromRoute({
294
+ protocol: input.provider === undefined ? base : { ...base, provider: ProviderID.make(input.provider) },
295
+ baseURL: DEFAULT_BASE_URL,
296
+ path: ({ request }) => (imageInput !== "references" && isEdit(request) ? EDIT_PATH : PATH),
297
+ }, input);
298
+ };
274
299
  export const OpenAIImages = {
275
300
  protocol,
276
301
  model,
302
+ pixelSize,
277
303
  };
@@ -12,9 +12,14 @@ export type XAIImageOptions = {
12
12
  readonly response_format?: OpenString<"url" | "b64_json">;
13
13
  } & Record<string, unknown>;
14
14
  export type Request = ImageRequestFor<XAIImageOptions>;
15
+ /** xAI renders `1k` or `2k`; other tiers use the nearest one. */
16
+ export declare const resolution: (request: {
17
+ readonly resolution?: string;
18
+ }) => "1k" | "2k" | undefined;
15
19
  export declare const protocol: MediaProtocol.Inline<Request, ImageResponse>;
16
20
  export declare const model: (input: MediaRoute.ModelInput) => ImageModel<XAIImageOptions>;
17
21
  export declare const XAIImages: {
18
22
  readonly protocol: MediaProtocol.Inline<Request, ImageResponse>;
19
23
  readonly model: typeof model;
24
+ readonly resolution: typeof resolution;
20
25
  };
@@ -31,7 +31,7 @@ const nativeOptions = (options) => {
31
31
  return { response_format: responseFormat ?? "b64_json", ...native };
32
32
  };
33
33
  /** xAI renders `1k` or `2k`; other tiers use the nearest one. */
34
- const resolution = (request) => {
34
+ export const resolution = (request) => {
35
35
  if (request.resolution === undefined)
36
36
  return undefined;
37
37
  return (ImageSizing.tier(request.resolution) ?? 1) < 1.5 ? "1k" : "2k";
@@ -83,4 +83,5 @@ export const model = (input) => ImageModel.fromRoute({ protocol, baseURL: DEFAUL
83
83
  export const XAIImages = {
84
84
  protocol,
85
85
  model,
86
+ resolution,
86
87
  };
@@ -0,0 +1,2 @@
1
+ export { imageModel as model } from "../meta.js";
2
+ export type { Settings } from "../meta.js";
@@ -0,0 +1 @@
1
+ export { imageModel as model } from "../meta.js";
@@ -751,4 +751,5 @@ export declare const image: (modelID: string | ModelID) => import("../image.js")
751
751
  export declare const model: ProviderPackage.Model<Settings, OpenResponsesProviderOptionsInput>;
752
752
  export declare const chatModel: ProviderPackage.Model<Settings, OpenResponsesProviderOptionsInput>;
753
753
  export declare const messagesModel: ProviderPackage.Model<Settings, MessagesOptionsInput>;
754
+ export declare const imageModel: (modelID: string, settings?: Settings) => import("../image.js").ImageModel<MetaImages.ImageOptions>;
754
755
  export * as Meta from "./meta.js";
@@ -97,6 +97,7 @@ export const image = provider.image;
97
97
  export const model = (modelID, settings) => fromSettings(settings).responses(modelID);
98
98
  export const chatModel = (modelID, settings) => fromSettings(settings).chat(modelID);
99
99
  export const messagesModel = (modelID, settings) => fromSettings(settings).messages(modelID);
100
+ export const imageModel = (modelID, settings) => fromSettings(settings).image(modelID);
100
101
  function fromSettings({ apiKey, baseURL, body, headers, ...providerOptions } = {}) {
101
102
  return configure({
102
103
  apiKey,
@@ -51,7 +51,9 @@ export const configure = (input = {}) => {
51
51
  ...deployment,
52
52
  http: mergeHttpOptions(deployment.http, input.queryParams === undefined ? undefined : new HttpOptions({ query: input.queryParams })),
53
53
  };
54
- const image = (modelID, providerOptions) => OpenAIImages.model({ ...media, id: modelID, providerOptions });
54
+ // The ChatGPT backend (ChatGPT sign-in) rejects multipart image edits with "Unsupported content type".
55
+ const imageInput = media.baseURL?.startsWith("https://chatgpt.com/") ? "json-edits" : undefined;
56
+ const image = (modelID, providerOptions) => OpenAIImages.model({ ...media, id: modelID, providerOptions, imageInput });
55
57
  const speech = (modelID) => OpenAISpeech.model({ ...media, id: modelID });
56
58
  const transcription = (modelID) => OpenAITranscription.model({ ...media, id: modelID });
57
59
  const decisionRoute = OpenAIDecisions.route.with({
@@ -83,6 +83,19 @@ const bodyOptions = (body, input, maxTokens) => {
83
83
  ...(known.reasoning !== undefined ? { reasoning: fitReasoning(known.reasoning, maxTokens) } : {}),
84
84
  };
85
85
  };
86
+ const IMAGE_RESOLUTIONS = new Set(["512", "768", "1K", "1.5K", "2K", "4K"]);
87
+ // A pixel `size` renders at the upstream's own tier (Gemini 2K comes back as 4K) and FLUX 3 rejects it, so sizing goes
88
+ // out as an aspect ratio and a resolution tier. Values OpenRouter doesn't list are left out.
89
+ const imageSizing = (request) => {
90
+ const resolution = request.resolution
91
+ ?.toUpperCase()
92
+ .replace(/^0\.5K$/, "512")
93
+ .replace(/^0\.75K$/, "768");
94
+ return {
95
+ aspect_ratio: request.aspect,
96
+ resolution: resolution !== undefined && IMAGE_RESOLUTIONS.has(resolution) ? resolution : undefined,
97
+ };
98
+ };
86
99
  export const route = Route.make({
87
100
  id: ADAPTER,
88
101
  provider: id,
@@ -116,7 +129,14 @@ export const configure = (input = {}) => {
116
129
  http: input.http,
117
130
  });
118
131
  const media = MediaRoute.deployment({ ...input, baseURL: input.baseURL ?? baseURL }, auth);
119
- const image = (modelID, providerOptions) => OpenAIImages.model({ ...media, id: modelID, provider: id, providerOptions });
132
+ const image = (modelID, providerOptions) => OpenAIImages.model({
133
+ ...media,
134
+ id: modelID,
135
+ provider: id,
136
+ providerOptions,
137
+ sizing: imageSizing,
138
+ imageInput: "references",
139
+ });
120
140
  const decision = (modelID, providerOptions) => decisionRoute.model({
121
141
  id: modelID,
122
142
  compatibility: { mediaInput: "state" },
@@ -4,6 +4,7 @@ import { OpenAIChat } from "../protocols/openai-chat.js";
4
4
  import { OpenResponses } from "../protocols/open-responses.js";
5
5
  import { OpenAIDecisions } from "../protocols/openai-decisions.js";
6
6
  import { OpenAIImages } from "../protocols/openai-images.js";
7
+ import { XAIImages } from "../protocols/xai-images.js";
7
8
  import { ProviderShared } from "../protocols/shared.js";
8
9
  import { gatewayProtocol } from "../protocols/utils/gateway-protocol.js";
9
10
  import { AuthOptions } from "../route/auth-options.js";
@@ -106,6 +107,15 @@ const chatRoute = route({
106
107
  framing: OpenAIChat.framing,
107
108
  });
108
109
  export const routes = [messagesRoute, responsesRoute, chatRoute];
110
+ // The Gateway passes `size` through to most image models, but Grok ignores it and renders 1024x1024; it only reads
111
+ // sizing from `providerOptions.xai`.
112
+ const imageSizing = (request) => {
113
+ if (!/^(spacexai|xai)\//.test(request.model.id))
114
+ return OpenAIImages.pixelSize(request);
115
+ if (request.aspect === undefined && request.resolution === undefined)
116
+ return undefined;
117
+ return { providerOptions: { xai: { aspect_ratio: request.aspect, resolution: XAIImages.resolution(request) } } };
118
+ };
109
119
  export const configure = (input = {}) => {
110
120
  const { apiKey: _apiKey, auth: _auth, baseURL: endpoint, ...defaults } = input;
111
121
  const configured = {
@@ -131,7 +141,7 @@ export const configure = (input = {}) => {
131
141
  return messages(modelID);
132
142
  };
133
143
  const media = MediaRoute.deployment({ ...input, baseURL: configured.endpoint.baseURL }, configured.auth);
134
- const image = (modelID, providerOptions) => OpenAIImages.model({ ...media, id: modelID, provider: id, providerOptions });
144
+ const image = (modelID, providerOptions) => OpenAIImages.model({ ...media, id: modelID, provider: id, providerOptions, sizing: imageSizing });
135
145
  const decisionRoute = OpenAIDecisions.route.with({
136
146
  provider: id,
137
147
  endpoint: { baseURL: configured.endpoint.baseURL },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "$schema": "https://json.schemastore.org/package.json",
3
- "version": "0.0.0-dev-203",
3
+ "version": "0.0.0-dev-216",
4
4
  "name": "@opencode/ai",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -248,6 +248,10 @@
248
248
  "import": "./dist/providers/meta/chat.js",
249
249
  "types": "./dist/providers/meta/chat.d.ts"
250
250
  },
251
+ "./providers/meta/images": {
252
+ "import": "./dist/providers/meta/images.js",
253
+ "types": "./dist/providers/meta/images.d.ts"
254
+ },
251
255
  "./providers/meta/messages": {
252
256
  "import": "./dist/providers/meta/messages.js",
253
257
  "types": "./dist/providers/meta/messages.d.ts"
@@ -512,7 +516,7 @@
512
516
  "devDependencies": {
513
517
  "@clack/prompts": "1.0.0-alpha.1",
514
518
  "@effect/platform-node": "4.0.1",
515
- "@opencode/http-recorder": "0.0.0-dev-203",
519
+ "@opencode/http-recorder": "0.0.0-dev-216",
516
520
  "@tsconfig/bun": "1.0.9",
517
521
  "@types/bun": "1.4.3",
518
522
  "@typescript/native": "npm:typescript@7.1.0-beta",
@@ -522,7 +526,7 @@
522
526
  "@aws-sdk/credential-providers": "3.1057.0",
523
527
  "@smithy/eventstream-codec": "4.2.14",
524
528
  "@smithy/util-utf8": "4.2.2",
525
- "@opencode/schema": "0.0.0-dev-203",
529
+ "@opencode/schema": "0.0.0-dev-216",
526
530
  "aws4fetch": "1.0.20",
527
531
  "effect": "4.0.1",
528
532
  "google-auth-library": "10.5.0"