@myoldtime/opencode-codex-imagegen 0.2.0 → 1.0.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.
package/core.mjs DELETED
@@ -1,561 +0,0 @@
1
- import { readFile, mkdir, open, unlink } from "node:fs/promises"
2
- import path from "node:path"
3
-
4
- // OpenAI Responses endpoints. Image generation always uses the hosted `image_generation`
5
- // tool on a Responses request, never the Images API.
6
- export const DEFAULT_OPENAI_BASE_URL = "https://api.openai.com/v1"
7
- export const OPENAI_RESPONSES_URL = "https://api.openai.com/v1/responses"
8
- export const CODEX_RESPONSES_URL = "https://chatgpt.com/backend-api/codex/responses"
9
-
10
- const DEFAULT_GOOGLE_BASE_URL = "https://generativelanguage.googleapis.com"
11
- const GOOGLE_API_REVISION = "2026-05-20"
12
- const DEFAULT_GOOGLE_MODEL = "gemini-nano-banana-2.1"
13
- const GOOGLE_INLINE_LIMIT = 20_000_000
14
- const GOOGLE_INLINE_LIMIT_ERROR = "Google inline image requests must be at most 20 MB including base64; resize or compress your reference images"
15
- export const GOOGLE_MAX_REFERENCES = 14
16
- export const GOOGLE_ASPECT_RATIOS = Object.freeze(["1:1", "2:3", "3:2", "3:4", "4:3", "4:5", "5:4", "9:16", "16:9", "21:9", "1:4", "4:1", "1:8", "8:1"])
17
- export const GOOGLE_IMAGE_SIZES = Object.freeze(["1K", "2K", "4K"])
18
-
19
- // OAuth sign-in methods that this plugin knows how to route. Anything else is rejected
20
- // instead of guessing an endpoint.
21
- export const SUPPORTED_OAUTH_METHODS = ["chatgpt-token-sharing", "chatgpt-browser", "chatgpt-headless"]
22
- const LEGACY_METHODS = new Set(["chatgpt-browser", "chatgpt-headless"])
23
-
24
- // Only these upstream codes may appear in an error message. Everything else is reported
25
- // as a generic upstream failure so account data never leaks.
26
- const SAFE_ERROR_CODES = new Set([
27
- "subscription_sharing_usage_limit_exceeded",
28
- "subscription_sharing_user_not_eligible",
29
- "subscription_sharing_unsupported_capability",
30
- "subscription_sharing_route_not_supported",
31
- "subscription_sharing_invalid_user",
32
- "chatpass_v2_scope_not_authorized",
33
- "chatpass_v2_invalid_authorization_context",
34
- ])
35
-
36
- const DEFAULT_MODEL = "gpt-6.1-sol"
37
- const DEFAULT_TIMEOUT_MS = 240000
38
- const INSTRUCTIONS = "Generate the requested image by invoking image_generation exactly once. Do not respond with text only."
39
-
40
- const OMIT_HINT = "omit options.base_url and options.key entirely to use the OpenAI account signed in to OpenCode"
41
-
42
- export function pluginConfig(options = {}) {
43
- if (options === null || typeof options !== "object" || Array.isArray(options)) throw new Error("Plugin options must be an object")
44
- const provider = options.provider === undefined ? "openai" : options.provider
45
- if (!["openai", "google"].includes(provider)) throw new Error("options.provider must be openai or google")
46
- const model = options.model ?? (provider === "google" ? DEFAULT_GOOGLE_MODEL : DEFAULT_MODEL)
47
- if (typeof model !== "string" || !model.trim()) throw new Error("model must be a nonempty string")
48
- const timeoutMs = options.timeout_ms ?? DEFAULT_TIMEOUT_MS
49
- if (!Number.isInteger(timeoutMs) || timeoutMs <= 0) throw new Error("timeout_ms must be a positive integer")
50
-
51
- if (provider === "google") {
52
- if (options.reasoning_effort !== undefined || options.fast_mode !== undefined) {
53
- throw new Error("options.reasoning_effort and options.fast_mode are only supported by the OpenAI provider")
54
- }
55
- if (typeof options.key !== "string" || !options.key.trim() || options.key.trim().startsWith("{env:")) {
56
- throw new Error("The Google provider requires a valid options.key; set GEMINI_API_KEY in the OpenCode environment and use {env:GEMINI_API_KEY}")
57
- }
58
- const endpoint = googleInteractionsURL(options.base_url === undefined ? DEFAULT_GOOGLE_BASE_URL : options.base_url)
59
- return { provider, mode: "explicit", endpoint, apiKey: options.key.trim(), model: model.trim(), timeoutMs }
60
- }
61
-
62
- // Presence is explicit: an empty, null, blank or unresolved value is a configuration error,
63
- // never a silent fallback. Only a fully omitted pair uses the host-managed account.
64
- const hasBase = options.base_url !== undefined
65
- const hasKey = options.key !== undefined
66
- if (hasBase && (typeof options.base_url !== "string" || !options.base_url.trim())) {
67
- throw new Error(`options.base_url must be a non-empty string; ${OMIT_HINT}`)
68
- }
69
- if (hasKey && (typeof options.key !== "string" || !options.key.trim())) {
70
- throw new Error(`options.key must be a non-empty string; ${OMIT_HINT}`)
71
- }
72
- const baseURL = hasBase ? options.base_url.trim() : ""
73
- const apiKey = hasKey ? options.key.trim() : ""
74
- if (apiKey.startsWith("{env:")) {
75
- throw new Error("options.key contains an unresolved environment substitution; load the variable into the OpenCode environment configuration (or the current session) and try again, or omit key to use the signed-in OpenAI account")
76
- }
77
- if (hasBase && !hasKey) {
78
- throw new Error("options.base_url requires options.key; configure both or omit both to use the signed-in OpenAI account")
79
- }
80
- if (options.reasoning_effort !== undefined && !["none", "minimal", "low", "medium", "high", "xhigh"].includes(options.reasoning_effort)) {
81
- throw new Error("reasoning_effort must be none, minimal, low, medium, high or xhigh (model support varies)")
82
- }
83
- if (options.fast_mode !== undefined && typeof options.fast_mode !== "boolean") throw new Error("fast_mode must be boolean")
84
- // key only: fall back to the public OpenAI endpoint. Both present: explicit proxy. Neither: host-managed.
85
- const explicit = Boolean(apiKey)
86
- const explicitBase = explicit ? baseURL || DEFAULT_OPENAI_BASE_URL : undefined
87
- // Fail on a malformed proxy URL before any session, permission or network work happens.
88
- if (explicitBase) responsesURL(explicitBase)
89
- return {
90
- provider,
91
- mode: explicit ? "explicit" : "managed",
92
- baseURL: explicitBase,
93
- apiKey: explicit ? apiKey : undefined,
94
- model: model.trim(),
95
- reasoningEffort: options.reasoning_effort,
96
- fastMode: options.fast_mode ?? false,
97
- timeoutMs,
98
- }
99
- }
100
-
101
- export function responsesURL(baseURL) {
102
- const url = new URL(baseURL)
103
- if (!["http:", "https:"].includes(url.protocol) || url.username || url.password || url.search || url.hash) {
104
- throw new Error("baseURL must be an HTTP(S) URL without credentials, query or fragment")
105
- }
106
- url.pathname = url.pathname.replace(/\/+$/, "")
107
- if (!url.pathname.endsWith("/responses")) url.pathname += "/responses"
108
- return url.toString()
109
- }
110
-
111
- function googleInteractionsURL(baseURL) {
112
- const invalid = () => new Error("Google options.base_url must be an HTTP(S) URL without credentials, query or fragment")
113
- if (typeof baseURL !== "string" || !/^https?:\/\//i.test(baseURL.trim()) || /[?#]/.test(baseURL)) throw invalid()
114
- let url
115
- try { url = new URL(baseURL.trim()) } catch { throw invalid() }
116
- if (url.username || url.password) throw invalid()
117
- const pathname = url.pathname.replace(/\/+$/, "")
118
- if (pathname.endsWith("/interactions")) url.pathname = pathname
119
- else if (/\/v1(?:beta)?$/.test(pathname)) url.pathname = `${pathname}/interactions`
120
- else url.pathname = `${pathname}/v1beta/interactions`
121
- return url.toString()
122
- }
123
-
124
- export function abortError() {
125
- const error = new Error("Image generation aborted")
126
- error.name = "AbortError"
127
- return error
128
- }
129
-
130
- // Messages that this plugin produced itself and may be shown verbatim.
131
- class ImageResponseError extends Error {}
132
-
133
- export function timeoutError() {
134
- return new Error("Image request timed out")
135
- }
136
-
137
- function abortIfNeeded(signal) {
138
- if (signal?.aborted) throw abortError()
139
- }
140
-
141
- function throwIfSettled(signal, combinedSignal) {
142
- if (signal?.aborted) throw abortError()
143
- if (combinedSignal?.aborted) throw timeoutError()
144
- }
145
-
146
- function connectionError(detail) {
147
- return new Error(`${detail} Configure options.base_url and options.key to use a proxy instead.`)
148
- }
149
-
150
- // Resolves the request route for this call. Explicit options never touch the host credential
151
- // API; managed mode re-resolves the connection on every call so OpenCode owns refresh.
152
- export async function resolveRoute(config, ctx) {
153
- if (config.provider === "google") {
154
- return { route: "google", method: "api-key", url: config.endpoint, access: config.apiKey }
155
- }
156
- if (config.mode === "explicit") {
157
- return { route: "proxy", method: "options", url: responsesURL(config.baseURL), access: config.apiKey }
158
- }
159
- const integration = ctx?.integration?.connection
160
- if (!integration || typeof integration.active !== "function" || typeof integration.resolve !== "function") {
161
- throw connectionError("OpenCode did not expose an OpenAI connection to this plugin.")
162
- }
163
- let connection
164
- try {
165
- connection = await integration.active("openai")
166
- } catch {
167
- throw connectionError("OpenCode could not read the OpenAI connection.")
168
- }
169
- if (!connection) {
170
- throw connectionError("No OpenAI account is connected in OpenCode. Sign in from OpenCode (Sign in with ChatGPT) or configure options.base_url and options.key.")
171
- }
172
- let credential
173
- try {
174
- credential = await integration.resolve(connection)
175
- } catch {
176
- throw connectionError("OpenCode could not provide a usable OpenAI credential; the sign-in may have expired or need attention. Sign in again.")
177
- }
178
- if (!credential || typeof credential !== "object") {
179
- throw connectionError("OpenCode returned no OpenAI credential for the connected account. Sign in again.")
180
- }
181
- if (credential.type === "key") {
182
- if (typeof credential.key !== "string" || !credential.key.trim()) {
183
- throw connectionError("The OpenAI connection returned an empty API key.")
184
- }
185
- return { route: "openai-key", method: "api-key", url: OPENAI_RESPONSES_URL, access: credential.key.trim() }
186
- }
187
- if (credential.type !== "oauth") {
188
- throw connectionError("The OpenAI connection returned an unsupported credential type.")
189
- }
190
- const methodID = credential.methodID
191
- if (!SUPPORTED_OAUTH_METHODS.includes(methodID)) {
192
- // Never echo the raw method value: it may carry arbitrary credential data.
193
- throw connectionError(`Unsupported OpenAI sign-in method. Supported methods: ${SUPPORTED_OAUTH_METHODS.join(", ")}.`)
194
- }
195
- if (typeof credential.access !== "string" || !credential.access.trim()) {
196
- throw connectionError("OpenCode returned an empty or expired OpenAI access token. Sign in again.")
197
- }
198
- if (typeof credential.expires === "number" && credential.expires <= Date.now()) {
199
- throw connectionError("The OpenAI access token has expired and could not be refreshed. Sign in again.")
200
- }
201
- const access = credential.access.trim()
202
- if (LEGACY_METHODS.has(methodID)) {
203
- const accountID = credential.metadata?.accountID
204
- return {
205
- route: methodID,
206
- method: methodID,
207
- url: CODEX_RESPONSES_URL,
208
- access,
209
- accountID: typeof accountID === "string" && accountID ? accountID : undefined,
210
- }
211
- }
212
- return { route: "chatgpt-token-sharing", method: methodID, url: OPENAI_RESPONSES_URL, access }
213
- }
214
-
215
- export function requestHeaders(route, sessionID) {
216
- if (route.route === "google") return {
217
- "x-goog-api-key": route.access,
218
- "Api-Revision": GOOGLE_API_REVISION,
219
- "Content-Type": "application/json",
220
- }
221
- const headers = {
222
- Authorization: `Bearer ${route.access}`,
223
- "Content-Type": "application/json",
224
- Accept: "text/event-stream",
225
- }
226
- if (LEGACY_METHODS.has(route.route)) {
227
- headers.originator = "opencode"
228
- if (route.accountID) headers["ChatGPT-Account-Id"] = route.accountID
229
- }
230
- if (route.route !== "proxy" && route.route !== "openai-key" && typeof sessionID === "string" && sessionID) {
231
- headers["session-id"] = sessionID
232
- if (route.route === "chatgpt-token-sharing") {
233
- headers["thread-id"] = sessionID
234
- headers["x-client-request-id"] = sessionID
235
- }
236
- }
237
- return headers
238
- }
239
-
240
- function imageType(bytes) {
241
- if (bytes.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]))) return "image/png"
242
- if (bytes[0] === 255 && bytes[1] === 216 && bytes[2] === 255) return "image/jpeg"
243
- if (["GIF87a", "GIF89a"].includes(bytes.subarray(0, 6).toString())) return "image/gif"
244
- if (bytes.subarray(0, 4).toString() === "RIFF" && bytes.subarray(8, 12).toString() === "WEBP") return "image/webp"
245
- }
246
-
247
- function outputFormat(out) {
248
- const extension = path.extname(out).toLowerCase()
249
- if (extension === ".png") return "image/png"
250
- if (extension === ".jpg" || extension === ".jpeg") return "image/jpeg"
251
- }
252
-
253
- export function validateInput(input, provider = "openai") {
254
- if (!input || typeof input.prompt !== "string" || !input.prompt.trim()) throw new Error("prompt is required")
255
- const format = typeof input.out === "string" ? outputFormat(input.out) : undefined
256
- if (input.images !== undefined && (!Array.isArray(input.images) || input.images.some(p => typeof p !== "string"))) throw new Error("images must be file paths")
257
- if (provider === "google") {
258
- if (!format) throw new Error("out must be a .png, .jpg or .jpeg file path for Google")
259
- if ((input.size !== undefined && input.size !== "auto") || (input.quality !== undefined && input.quality !== "auto")) {
260
- throw new Error("The Google provider uses aspect_ratio and image_size instead of size and quality")
261
- }
262
- if (input.aspect_ratio !== undefined && !GOOGLE_ASPECT_RATIOS.includes(input.aspect_ratio)) throw new Error("Invalid Google aspect_ratio")
263
- if (input.image_size !== undefined && !GOOGLE_IMAGE_SIZES.includes(input.image_size)) throw new Error("Google image_size must be 1K, 2K or 4K")
264
- if (input.images?.length > GOOGLE_MAX_REFERENCES) throw new Error(`Google image generation accepts at most ${GOOGLE_MAX_REFERENCES} reference images; some models accept fewer`)
265
- return
266
- }
267
- if (format !== "image/png") throw new Error("out must be a .png file path")
268
- if (input.aspect_ratio !== undefined || input.image_size !== undefined) throw new Error("aspect_ratio and image_size are only supported by the Google provider")
269
- if (input.quality !== undefined && !["auto", "low", "medium", "high"].includes(input.quality)) throw new Error("Invalid quality")
270
- if (input.size !== undefined && input.size !== "auto") {
271
- const match = /^(\d+)x(\d+)$/.exec(input.size)
272
- const w = Number(match?.[1]), h = Number(match?.[2])
273
- if (!match || !w || !h || w % 16 || h % 16 || Math.max(w, h) > 3840 || Math.max(w, h) / Math.min(w, h) > 3 || w * h < 655360 || w * h > 8294400) {
274
- throw new Error("size must be auto or WIDTHxHEIGHT (16px multiples, max edge 3840, aspect <= 3:1, pixels 655360–8294400)")
275
- }
276
- }
277
- }
278
-
279
- function safeCode(value) {
280
- return typeof value === "string" && SAFE_ERROR_CODES.has(value) ? value : undefined
281
- }
282
-
283
- function safeCodeFrom(payload) {
284
- return safeCode(payload?.error?.code) ?? safeCode(payload?.response?.error?.code)
285
- }
286
-
287
- function resultFromEvent(event) {
288
- if (event.type === "error" || event.type === "response.failed" || event.type === "response.incomplete") {
289
- const code = safeCodeFrom(event)
290
- throw new ImageResponseError(`Image response failed${code ? ` (${code})` : ""}`)
291
- }
292
- if (event.type === "response.output_item.done" && event.item?.type === "image_generation_call" && event.item.result) return event.item.result
293
- return event.response?.output?.find(item => item.type === "image_generation_call" && item.result)?.result
294
- }
295
-
296
- export function parseEvent(text) {
297
- try {
298
- return JSON.parse(text)
299
- } catch {
300
- throw new ImageResponseError("Image response contained invalid JSON")
301
- }
302
- }
303
-
304
- async function httpError(response, { signal, combinedSignal } = {}) {
305
- let text = ""
306
- try {
307
- text = await response.text()
308
- } catch {
309
- text = ""
310
- }
311
- throwIfSettled(signal, combinedSignal)
312
- let payload
313
- try {
314
- payload = text ? JSON.parse(text) : undefined
315
- } catch {
316
- payload = undefined
317
- }
318
- const code = safeCodeFrom(payload)
319
- return new ImageResponseError(`Image request failed: HTTP ${response.status}${code ? ` (${code})` : ""}`)
320
- }
321
-
322
- // SSE frames may be split anywhere, including inside UTF-8 characters and CRLF.
323
- export async function readImageResponse(response) {
324
- if (!response.body) throw new ImageResponseError("Empty image response")
325
- // Some Codex gateways return valid SSE without a Content-Type header. Detect
326
- // the wire format from a bounded prefix instead of mistaking that stream for JSON.
327
- const contentType = response.headers.get("content-type")?.toLowerCase() ?? ""
328
- let format = contentType.includes("text/event-stream") ? "sse" : contentType.includes("application/json") ? "json" : "detect"
329
- const reader = response.body.getReader()
330
- const decoder = new TextDecoder()
331
- let pending = "", data = []
332
- const dispatch = () => {
333
- const text = data.join("\n")
334
- data = []
335
- if (!text || text === "[DONE]") return
336
- return resultFromEvent(parseEvent(text))
337
- }
338
- const line = text => {
339
- if (!text) return dispatch()
340
- if (text === "data") data.push("")
341
- else if (text.startsWith("data:")) data.push(text.slice(5).replace(/^ /, ""))
342
- }
343
- try {
344
- while (true) {
345
- const { value, done } = await reader.read()
346
- pending += done ? decoder.decode() : decoder.decode(value, { stream: true })
347
- if (format === "detect") {
348
- const prefix = pending.trimStart()
349
- if (/^[\[{]/.test(prefix)) format = "json"
350
- else if (/^(?:(?:data|event|id|retry)(?::|\r?\n)|:)/.test(prefix)) {
351
- format = "sse"
352
- pending = prefix
353
- } else if (done || pending.length > 65536 || prefix.includes("\n")) {
354
- throw new ImageResponseError("Image response contained invalid JSON or SSE")
355
- } else continue
356
- }
357
- if (format === "json") {
358
- if (!done) continue
359
- const result = resultFromEvent({ type: "response.completed", response: parseEvent(pending) })
360
- if (!result) throw new ImageResponseError("No image_generation_call.result in JSON response")
361
- return result
362
- }
363
- let index
364
- while ((index = pending.indexOf("\n")) !== -1) {
365
- const text = pending.slice(0, index).replace(/\r$/, "")
366
- pending = pending.slice(index + 1)
367
- const result = line(text)
368
- if (result) return result
369
- }
370
- if (done) {
371
- if (pending) line(pending.replace(/\r$/, ""))
372
- const result = dispatch()
373
- if (result) return result
374
- break
375
- }
376
- }
377
- } finally {
378
- await reader.cancel().catch(() => {})
379
- reader.releaseLock()
380
- }
381
- throw new ImageResponseError("Response ended without an image_generation_call.result")
382
- }
383
-
384
- // Google returns raw Interactions steps, not the SDK's computed output_image.
385
- async function readGoogleImageResponse(response) {
386
- const payload = parseEvent(await response.text())
387
- if (payload?.error || payload?.status !== "completed") {
388
- throw new ImageResponseError("Google image interaction did not complete")
389
- }
390
- let image
391
- for (const step of Array.isArray(payload?.steps) ? payload.steps : []) {
392
- if (step?.type !== "model_output" || !Array.isArray(step.content)) continue
393
- for (const part of step.content) {
394
- if (part?.type === "image" && typeof part.data === "string" && part.data) image = part
395
- }
396
- }
397
- if (!image) throw new ImageResponseError("Google response contained no generated image")
398
- return image
399
- }
400
-
401
- export async function savePNG(out, directory, base64, signal) {
402
- return saveImage(out, directory, base64, "image/png", signal)
403
- }
404
-
405
- async function saveImage(out, directory, base64, format, signal, googleImage) {
406
- if (typeof base64 !== "string" || !/^[A-Za-z0-9+/]+={0,2}$/.test(base64) || base64.length % 4) throw new Error("Invalid image base64")
407
- let bytes = Buffer.from(base64, "base64")
408
- const actual = imageType(bytes)
409
- if (googleImage?.mime_type !== undefined && googleImage.mime_type !== actual) {
410
- throw new Error("Google image MIME type does not match its bytes")
411
- }
412
- if (googleImage && actual === "image/jpeg" && format === "image/png") {
413
- abortIfNeeded(signal)
414
- const [{ default: jpeg }, { PNG }] = await Promise.all([import("jpeg-js"), import("pngjs")])
415
- try {
416
- const raster = jpeg.decode(bytes, { maxResolutionInMP: 20, maxMemoryUsageInMB: 384, tolerantDecoding: false })
417
- bytes = PNG.sync.write(raster)
418
- } catch {
419
- throw new Error("Could not convert Google JPEG to PNG")
420
- }
421
- } else if (actual !== format) throw new Error(`Backend did not return ${format === "image/png" ? "PNG" : "JPEG"}`)
422
- abortIfNeeded(signal)
423
- const target = path.resolve(directory, out)
424
- await mkdir(path.dirname(target), { recursive: true })
425
- const extension = path.extname(target)
426
- const stem = target.slice(0, -extension.length)
427
- for (let version = 1; ; version++) {
428
- const file = version === 1 ? target : `${stem}-v${version}${extension.toLowerCase()}`
429
- let handle
430
- try { handle = await open(file, "wx") } catch (error) {
431
- if (error.code === "EEXIST") continue
432
- throw error
433
- }
434
- // Only files created by this call (open "wx") are ever removed; pre-existing files stay untouched.
435
- let stillOpen = true
436
- try {
437
- await handle.writeFile(bytes)
438
- await handle.close()
439
- stillOpen = false
440
- } catch (error) {
441
- if (stillOpen) await handle.close().catch(() => {})
442
- await unlink(file).catch(() => {})
443
- throw error
444
- }
445
- if (signal?.aborted) {
446
- // Cancelled while persisting: remove the file we just created, never a pre-existing one.
447
- await unlink(file).catch(() => {})
448
- throw abortError()
449
- }
450
- return { out: file, versioned: version > 1, bytes: bytes.length }
451
- }
452
- }
453
-
454
- function googleBody(input, config, references, format) {
455
- const responseFormat = {
456
- ...(format === "image/jpeg" ? { mime_type: format } : {}),
457
- ...(input.aspect_ratio ? { aspect_ratio: input.aspect_ratio } : {}),
458
- ...(input.image_size ? { image_size: input.image_size } : {}),
459
- }
460
- return {
461
- model: config.model,
462
- input: [{ type: "text", text: input.prompt }, ...references.map(({ mime, data }) => ({ type: "image", mime_type: mime, data }))],
463
- ...(Object.keys(responseFormat).length ? { response_format: { type: "image", ...responseFormat } } : {}),
464
- }
465
- }
466
-
467
- function openAIBody(input, config, references) {
468
- const content = [{ type: "input_text", text: input.prompt }, ...references.map(({ mime, data }) => ({
469
- type: "input_image",
470
- image_url: `data:${mime};base64,${data}`,
471
- }))]
472
- return {
473
- model: config.model,
474
- instructions: INSTRUCTIONS,
475
- input: [{ role: "user", content }],
476
- tools: [{ type: "image_generation", output_format: "png", quality: input.quality ?? "auto", ...(input.size ? { size: input.size } : {}) }],
477
- tool_choice: { type: "image_generation" },
478
- stream: true,
479
- store: false,
480
- ...(config.reasoningEffort !== undefined ? { reasoning: { effort: config.reasoningEffort } } : {}),
481
- ...(config.fastMode ? { service_tier: "priority" } : {}),
482
- }
483
- }
484
-
485
- export async function generateImage(input, config, directory, env = {}) {
486
- const { ctx, signal, sessionID, fetcher = fetch } = env
487
- validateInput(input, config.provider)
488
- const google = config.provider === "google"
489
- const format = outputFormat(input.out)
490
- abortIfNeeded(signal)
491
- // Credentials are resolved per call; explicit options never consult the host.
492
- const route = await resolveRoute(config, ctx)
493
- abortIfNeeded(signal)
494
- const references = []
495
- let encodedBytes = 0
496
- const referenceFormats = google ? ["image/png", "image/jpeg", "image/webp"] : ["image/png", "image/jpeg", "image/gif", "image/webp"]
497
- for (const file of input.images ?? []) {
498
- const bytes = await readFile(path.resolve(directory, file), { signal })
499
- const mime = imageType(bytes)
500
- if (!referenceFormats.includes(mime)) {
501
- throw new Error(google ? "Unsupported Google reference image: use PNG, JPEG or WebP" : "Unsupported reference image: use PNG, JPEG, GIF or WebP")
502
- }
503
- if (google) {
504
- encodedBytes += Math.ceil(bytes.length / 3) * 4
505
- if (encodedBytes > GOOGLE_INLINE_LIMIT) throw new Error(GOOGLE_INLINE_LIMIT_ERROR)
506
- }
507
- references.push({ mime, data: bytes.toString("base64") })
508
- }
509
- const body = JSON.stringify(google ? googleBody(input, config, references, format) : openAIBody(input, config, references))
510
- if (google && Buffer.byteLength(body) > GOOGLE_INLINE_LIMIT) {
511
- throw new Error(GOOGLE_INLINE_LIMIT_ERROR)
512
- }
513
- const timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS
514
- if (!Number.isInteger(timeoutMs) || timeoutMs <= 0) throw new Error("timeoutMs must be a positive integer")
515
- const combinedSignal = signal ? AbortSignal.any([signal, AbortSignal.timeout(timeoutMs)]) : AbortSignal.timeout(timeoutMs)
516
- abortIfNeeded(signal)
517
- let response
518
- try {
519
- response = await fetcher(route.url, {
520
- method: "POST",
521
- signal: combinedSignal,
522
- redirect: "error",
523
- headers: requestHeaders(route, sessionID),
524
- body,
525
- })
526
- } catch {
527
- if (signal?.aborted) throw abortError()
528
- if (combinedSignal.aborted) throw timeoutError()
529
- throw new Error("Image request failed before a response was received")
530
- }
531
- // A fetcher may resolve after the deadline or after cancellation; discard that late result.
532
- if (signal?.aborted || combinedSignal.aborted) {
533
- await response?.body?.cancel().catch(() => {})
534
- throwIfSettled(signal, combinedSignal)
535
- }
536
- if (!response || typeof response !== "object" || typeof response.ok !== "boolean") {
537
- throw new Error("Image request failed before a response was received")
538
- }
539
- if (!response.ok) throw await httpError(response, { signal, combinedSignal })
540
- let base64, googleImage
541
- try {
542
- if (google) {
543
- googleImage = await readGoogleImageResponse(response)
544
- base64 = googleImage.data
545
- } else base64 = await readImageResponse(response)
546
- } catch (error) {
547
- // Our own messages pass through; every transport/stream failure is normalized.
548
- throwIfSettled(signal, combinedSignal)
549
- if (error instanceof ImageResponseError) throw error
550
- throw new Error("Image response stream failed")
551
- }
552
- throwIfSettled(signal, combinedSignal)
553
- let saved
554
- try {
555
- saved = await saveImage(input.out, directory, base64, format, combinedSignal, googleImage)
556
- } catch (error) {
557
- throwIfSettled(signal, combinedSignal)
558
- throw error
559
- }
560
- return { ...saved, route: route.route, method: route.method, model: config.model }
561
- }