@myoldtime/opencode-codex-imagegen 0.1.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/images.js ADDED
@@ -0,0 +1,235 @@
1
+ import { lstat, mkdir, open, readFile, unlink } from "node:fs/promises"
2
+ import path from "node:path"
3
+ import { setTimeout as delay } from "node:timers/promises"
4
+ import { ProviderFailure, upstreamError } from "./errors.js"
5
+ import { codexOutputs } from "./codex.js"
6
+ import { googleOutputs, jpegToPNG } from "./google.js"
7
+
8
+ const png = Buffer.from("89504e470d0a1a0a", "hex")
9
+ function format(bytes) {
10
+ if (bytes.subarray(0, 8).equals(png)) return "png"
11
+ if (bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff) return "jpeg"
12
+ if (bytes.toString("ascii", 0, 4) === "RIFF" && bytes.toString("ascii", 8, 12) === "WEBP") return "webp"
13
+ }
14
+
15
+ const pathKey = file => process.platform === "win32" ? file.toLowerCase() : file
16
+
17
+ // Reserve exact filenames across this plugin's concurrent jobs. The exclusive open at
18
+ // write time also protects against a different process creating an approved path.
19
+ export async function reserveOutputs(first, n, reserved) {
20
+ const { dir, name, ext } = path.parse(first)
21
+ const paths = []
22
+ const release = () => paths.forEach(file => reserved.delete(pathKey(file)))
23
+ try {
24
+ for (let i = 1; i <= n; i++) {
25
+ const stem = i === 1 ? name : `${name}-${i}`
26
+ for (let v = 1; ; v++) {
27
+ const file = path.join(dir, `${stem}${v === 1 ? "" : `-v${v}`}${ext}`)
28
+ try {
29
+ await lstat(file)
30
+ continue
31
+ } catch (error) {
32
+ if (error.code !== "ENOENT") throw error
33
+ }
34
+ const key = pathKey(file)
35
+ if (reserved.has(key)) continue
36
+ reserved.add(key)
37
+ paths.push(file)
38
+ break
39
+ }
40
+ }
41
+ return { paths, release }
42
+ } catch (error) {
43
+ release()
44
+ throw error
45
+ }
46
+ }
47
+
48
+ async function writeImage(file, bytes, signal) {
49
+ signal.throwIfAborted()
50
+ await mkdir(path.dirname(file), { recursive: true })
51
+ const handle = await open(file, "wx")
52
+ try {
53
+ try {
54
+ await handle.writeFile(bytes, { signal })
55
+ } finally {
56
+ await handle.close()
57
+ }
58
+ } catch (error) {
59
+ await unlink(file)
60
+ throw error
61
+ }
62
+ }
63
+
64
+ const safeID = value => typeof value === "string" && /^[A-Za-z0-9_-]{1,160}$/.test(value)
65
+ const auth = config => ({ Authorization: `Bearer ${config.key}` })
66
+
67
+ function errorInfo(error, key) {
68
+ // Do not echo provider messages: they can contain prompts, URLs or keys.
69
+ const fields = [error?.code, error?.tid].filter(x => safeID(x) && !x.includes(key))
70
+ if (error?.code === "async_not_enabled") fields.push("请在 AIHubMix 控制台启用异步任务,或将 base_url 设为 https://aihubmix.com/v1。")
71
+ return fields.length ? ` (${fields.join("; ")})` : ""
72
+ }
73
+
74
+ async function check(response, key, stage) {
75
+ if (response.ok) return
76
+ const body = await response.json().catch(() => null)
77
+ const error = upstreamError(response.status, body?.error, stage === "提交")
78
+ error.message = `${stage} ${error.message}${errorInfo(body?.error, key)}`
79
+ throw error
80
+ }
81
+
82
+ async function api(config, url, init, signal) {
83
+ const response = await fetch(url, { ...init, headers: { ...auth(config), ...init.headers }, redirect: "error", signal })
84
+ await check(response, config.key, init.method === "POST" ? "提交" : "查询")
85
+ try {
86
+ return await response.json()
87
+ } catch {
88
+ signal.throwIfAborted()
89
+ throw new ProviderFailure("AIHubMix returned invalid JSON.")
90
+ }
91
+ }
92
+
93
+ async function source(file, signal, mask = false) {
94
+ const bytes = await readFile(file, { signal })
95
+ const type = format(bytes)
96
+ if (!type || (mask && type !== "png")) throw new Error(`Expected ${mask ? "PNG mask" : "PNG, JPEG or WebP reference"}: ${file}`)
97
+ return { bytes, type, name: path.basename(file) }
98
+ }
99
+ const dataURI = file => `data:image/${file.type};base64,${file.bytes.toString("base64")}`
100
+ const jsonPost = body => ({ method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) })
101
+
102
+ async function nativeOutputs(job, common, refs, mask, wait) {
103
+ const { config, params, signal, onTaskID } = job
104
+ const extra = { quality: params.quality, background: params.background, output_compression: params.output_compression }
105
+ const init = jsonPost({
106
+ ...common, async: true, extra,
107
+ ...(refs.length === 1 ? { image: dataURI(refs[0]) } : refs.length ? { images: refs.map(dataURI) } : {}),
108
+ ...(mask && { mask: dataURI(mask) }),
109
+ })
110
+ if (Buffer.byteLength(init.body) > 32 * 1024 * 1024) throw new ProviderFailure("AIHubMix 请求体超过 32 MiB,请缩小参考图。")
111
+ let task = await api(config, config.endpoint, init, signal)
112
+ const id = task?.id
113
+ if (safeID(id)) onTaskID?.(id)
114
+ while (task?.status === "pending" || task?.status === "in_progress") {
115
+ if (!safeID(id)) throw new ProviderFailure("AIHubMix returned an active task without a valid ID.")
116
+ await wait(15000, undefined, { signal })
117
+ task = await api(config, new URL(id, config.endpoint), { method: "GET" }, signal)
118
+ if (task?.id !== id) throw new ProviderFailure("AIHubMix returned a different task ID.")
119
+ }
120
+ if (task?.status === "failed" || task?.status === "cancelled") {
121
+ const error = upstreamError(200, task.error)
122
+ error.message = `AIHubMix task ${task.status}${errorInfo(task.error, config.key)}`
123
+ throw error
124
+ }
125
+ if (task?.status !== "completed") throw new ProviderFailure("AIHubMix returned an unrecognized task status.")
126
+ return task.output
127
+ }
128
+
129
+ async function compatibleOutputs({ config, params, signal }, common, refs, mask) {
130
+ const body = { ...common, quality: params.quality }
131
+ if (!refs.length) return (await api(config, config.endpoint, jsonPost(body), signal))?.data
132
+ const form = new FormData()
133
+ for (const [key, value] of Object.entries(body)) form.set(key, String(value))
134
+ for (const [key, file] of [["image", refs[0]], ["mask", mask]]) {
135
+ if (file) form.set(key, new Blob([file.bytes], { type: `image/${file.type}` }), file.name)
136
+ }
137
+ return (await api(config, new URL("edits", config.endpoint), { method: "POST", body: form }, signal))?.data
138
+ }
139
+
140
+ async function download(raw, config, signal) {
141
+ let url = new URL(raw, config.endpoint)
142
+ const origin = new URL(config.endpoint).origin
143
+ let authenticated = true
144
+ for (let redirects = 0; redirects <= 5; redirects++) {
145
+ authenticated &&= url.origin === origin
146
+ if (url.username || url.password || !(url.protocol === "https:" || (url.protocol === "http:" && url.origin === origin)))
147
+ throw new ProviderFailure("AIHubMix returned an invalid image download URL.")
148
+ const response = await fetch(url, { signal, redirect: "manual", headers: authenticated ? auth(config) : {} })
149
+ if ([301, 302, 303, 307, 308].includes(response.status)) {
150
+ const next = response.headers.get("location")
151
+ await response.body?.cancel()
152
+ if (!next) throw new ProviderFailure("AIHubMix image download redirect has no location.")
153
+ url = new URL(next, url)
154
+ continue
155
+ }
156
+ await check(response, config.key, "下载")
157
+ return Buffer.from(await response.arrayBuffer())
158
+ }
159
+ throw new ProviderFailure("AIHubMix returned too many image download redirects.")
160
+ }
161
+
162
+ export async function loadInputs({ sources, mask, signal }) {
163
+ const refs = []
164
+ for (const file of sources) refs.push(await source(file, signal))
165
+ return { refs, mask: mask && await source(mask, signal, true) }
166
+ }
167
+
168
+ async function openRouterOutputs({ config, params, aspect, signal }, refs) {
169
+ const { size, ...rest } = params
170
+ const init = jsonPost({
171
+ model: config.model, ...rest, ...(aspect ? { aspect_ratio: aspect } : { size }),
172
+ response_format: "b64_json",
173
+ ...(refs.length && { input_references: refs.map(file => ({ type: "image_url", image_url: { url: dataURI(file) } })) }),
174
+ })
175
+ let response, body
176
+ try {
177
+ response = await fetch(config.endpoint, { ...init, headers: { ...init.headers, ...auth(config) }, redirect: "error", signal })
178
+ body = await response.json().catch(() => null)
179
+ } catch {
180
+ throw new ProviderFailure(signal.aborted ? "请求超时或已中止" : "网络请求失败")
181
+ }
182
+ if (!response.ok || body?.error) {
183
+ const status = response.ok ? Number(body.error.code) || response.status : response.status
184
+ throw upstreamError(status, body?.error)
185
+ }
186
+ return body?.data
187
+ }
188
+
189
+ async function imageAPIOutputs(job, wait) {
190
+ const { provider, config, params, refs, mask, paths } = job
191
+ const common = { model: config.model, prompt: params.prompt, n: params.n, output_format: params.output_format, size: params.size }
192
+ const router = provider === "openrouter"
193
+ if (!router && !config.native && (refs.length > 1 || params.background !== "auto" || params.output_compression !== undefined))
194
+ throw new ProviderFailure("Use AIHubMix /ai/v1 for multiple references, explicit background or output_compression.")
195
+ const outputs = router ? await openRouterOutputs(job, refs) :
196
+ config.native ? await nativeOutputs(job, common, refs, mask, wait) : await compatibleOutputs(job, common, refs, mask)
197
+ if (!Array.isArray(outputs) || !outputs.length) throw new ProviderFailure("上游未返回图片。")
198
+ if (outputs.length > paths.length) throw new ProviderFailure("上游返回图片数超过请求数量。")
199
+ return outputs
200
+ }
201
+
202
+ function aiHubMixFailure(error) {
203
+ if (error instanceof ProviderFailure) throw error
204
+ throw new ProviderFailure("AIHubMix 网络请求失败或返回了无效的响应。")
205
+ }
206
+
207
+ async function providerOutputs(job, wait) {
208
+ if (job.provider === "codex") return codexOutputs(job)
209
+ if (job.provider === "google") return googleOutputs(job)
210
+ if (job.provider === "aihubmix") return imageAPIOutputs(job, wait).catch(aiHubMixFailure)
211
+ return imageAPIOutputs(job, wait)
212
+ }
213
+
214
+ export async function generate(job, wait = delay) {
215
+ const { provider, config, params, paths, signal, saved } = job
216
+ const outputs = await providerOutputs(job, wait)
217
+ for await (const image of outputs) {
218
+ const index = saved.length
219
+ const raw = config?.native ? image?.content_url : image?.url
220
+ let bytes
221
+ if (typeof image?.b64_json === "string" && image.b64_json) bytes = Buffer.from(image.b64_json, "base64")
222
+ else if (provider === "aihubmix" && typeof raw === "string" && raw) bytes = await download(raw, config, signal).catch(aiHubMixFailure)
223
+ else throw new ProviderFailure(`Image ${index + 1} has no usable image data.`)
224
+ const actual = format(bytes)
225
+ if (provider === "google" && image.mime_type !== undefined && image.mime_type !== `image/${actual}`)
226
+ throw new ProviderFailure("Google 返回的图片 MIME 类型与文件内容不符。")
227
+ if (provider === "google" && actual === "jpeg" && params.output_format === "png") {
228
+ signal.throwIfAborted()
229
+ bytes = await jpegToPNG(bytes)
230
+ } else if (actual !== params.output_format)
231
+ throw new ProviderFailure(`Image ${index + 1} does not match the requested ${params.output_format.toUpperCase()} format.`)
232
+ await writeImage(paths[index], bytes, signal)
233
+ saved.push(paths[index])
234
+ }
235
+ }
package/index.js CHANGED
@@ -1,61 +1,115 @@
1
1
  import path from "node:path"
2
- import { generateImage, validateInput, pluginConfig } from "./core.mjs"
2
+ import { randomUUID } from "node:crypto"
3
+ import { setTimeout as delay } from "node:timers/promises"
4
+ import { configuredProviders, validateOptions, parameters, schema } from "./parameters.js"
5
+ import { reserveOutputs } from "./images.js"
6
+ import { route } from "./routing.js"
7
+ import { codexCandidate } from "./codex.js"
8
+
9
+ const pluginID = "opencode-auto-imagegen"
10
+
11
+ async function notify(ctx, message) {
12
+ // A stable message ID makes retry safe even if the first admission succeeded
13
+ // but its acknowledgement was lost. Never repeat the paid generation request.
14
+ for (let attempt = 1; ; attempt++) {
15
+ try {
16
+ await ctx.session.synthetic(message)
17
+ return
18
+ } catch (error) {
19
+ if (attempt === 3) throw error
20
+ await delay(250 * attempt)
21
+ }
22
+ }
23
+ }
24
+
25
+ async function run(ctx, job, sessionID, jobID, disabled, active) {
26
+ const saved = [], attempts = []
27
+ let reason, upstreamID, provider
28
+ try {
29
+ provider = await route({ ...job, sessionID, saved, onTaskID: id => { upstreamID = id } }, disabled, active, attempts)
30
+ if (saved.length < job.params.n) reason = "上游返回的图片少于请求数量。"
31
+ } catch (error) {
32
+ reason = job.signal.aborted ? job.signal.reason?.message ?? "任务已取消。" : error.message
33
+ }
34
+ const status = saved.length === job.params.n ? "完成" : saved.length ? "部分完成" : "失败"
35
+ const summary = `生图${status}(${saved.length}/${job.params.n}),任务 ${jobID}`
36
+ const routes = attempts.map(x => `${x.provider}: ${x.status}${x.reason ? `(${x.reason})` : ""}`).join(" → ")
37
+ const text = [summary, routes, reason, upstreamID && `AIHubMix 任务:${upstreamID}`, ...saved.map(file => `已保存:${file}`)].filter(Boolean).join("\n")
38
+ await notify(ctx, {
39
+ sessionID, id: `msg_${jobID}`, delivery: "queue", resume: true,
40
+ text: `${text}\n请告知用户结果;无需再次调用生图工具。`,
41
+ metadata: { plugin: pluginID, jobID, saved, attempts, ...(provider && { provider }), requested: job.params.n, ...(upstreamID && { upstreamID }) },
42
+ })
43
+ }
3
44
 
4
45
  export default {
5
- id: "opencode-codex-imagegen",
46
+ id: pluginID,
6
47
  async setup(ctx) {
48
+ const options = ctx.options ?? {}
49
+ validateOptions(options)
50
+ const sessions = new Map()
51
+ const reserved = new Set()
52
+ const running = new Set()
53
+ const lifecycle = new AbortController()
7
54
  await ctx.tool.transform(editor => {
8
55
  editor.add({
9
- name: "proxy_imagegen",
10
- description: "Generate or edit an image with OpenAI's Responses hosted image_generation tool. Uses explicit options.base_url/options.key when configured; otherwise routes through the OpenAI account signed in to OpenCode (Sign in with ChatGPT, or the legacy Codex browser/device-code methods). Supports reference images; saves one PNG and never overwrites existing files. Size and quality are best-effort; the backend selects the actual image model.",
11
- input: {
12
- type: "object",
13
- properties: {
14
- prompt: { type: "string", description: "Describe the image; when using references explain each image's role in order." },
15
- out: { type: "string", description: "PNG output path, relative to the current session directory or absolute." },
16
- quality: { type: "string", enum: ["auto", "low", "medium", "high"] },
17
- size: { type: "string", description: "auto or WIDTHxHEIGHT; exact dimensions depend on the backend." },
18
- images: { type: "array", items: { type: "string" }, description: "Local reference image paths (PNG, JPEG, GIF, WebP)." },
19
- },
20
- required: ["prompt", "out"],
21
- additionalProperties: false,
22
- },
56
+ name: "auto_imagegen",
57
+ options: { codemode: false },
58
+ description: "Generate or edit images in the background. Try available providers in order: Codex (a chat model calling the hosted image_generation tool), OpenRouter, AIHubMix, Google Gemini. Choose parameters from the user's intent. Submit once; the originating session receives the actual provider, paths or failure. Do not poll or resubmit.",
59
+ input: schema,
23
60
  async execute(input, context) {
24
- validateInput(input)
25
- // Options are validated before anything network- or credential-related happens.
26
- const config = pluginConfig(ctx.options)
27
- const session = await ctx.session.get({ sessionID: context.sessionID })
28
- const directory = session.location.directory
29
- // Respect normal OpenCode edit rules, including external-directory approval.
30
- const source = { type: "tool", messageID: context.messageID, id: context.id }
31
- if (input.images?.length) await ctx.permission.assert({
32
- sessionID: context.sessionID,
33
- agent: context.agent,
34
- source,
35
- action: "read",
36
- resources: input.images.map(file => path.resolve(directory, file)),
37
- })
38
- await ctx.permission.assert({
39
- sessionID: context.sessionID,
40
- agent: context.agent,
41
- source,
42
- action: "edit",
43
- resources: [path.resolve(directory, input.out), path.resolve(directory, input.out).slice(0, -4) + "-v*.png"],
61
+ const params = parameters(input)
62
+ const { sessionID } = context
63
+ const active = configuredProviders(options)
64
+ const codex = await codexCandidate(options.codex, ctx.integration?.connection, sessions.get(sessionID)?.has("codex"))
65
+ if (codex) active.unshift(codex)
66
+ if (!active.length) throw new Error("没有可用的生图服务:请启用至少一家服务,并登录 Codex 或配置 Codex、OpenRouter、AIHubMix 或 Google 任意一家的 key。")
67
+ const jobID = randomUUID()
68
+ const { location } = await ctx.session.get({ sessionID })
69
+ const sources = (input.images ?? []).map(file => path.resolve(location.directory, file))
70
+ const mask = input.mask && path.resolve(location.directory, input.mask)
71
+ const assert = (action, resources) => ctx.permission.assert({
72
+ sessionID, agent: context.agent, action, resources,
73
+ source: { type: "tool", messageID: context.messageID, id: context.id },
44
74
  })
45
- const result = await generateImage(input, config, directory, { ctx, signal: context.signal, sessionID: context.sessionID })
75
+ if (sources.length) await assert("read", mask ? [...sources, mask] : sources)
76
+ const first = path.resolve(location.directory, input.out ?? `images/imagegen-${jobID}.${params.output_format}`)
77
+ const { paths, release } = await reserveOutputs(first, params.n, reserved)
78
+ try {
79
+ await assert("edit", paths)
80
+ context.signal.throwIfAborted()
81
+ lifecycle.signal.throwIfAborted()
82
+ } catch (error) {
83
+ release()
84
+ throw error
85
+ }
86
+
87
+ // The tool call's signal ends with the foreground turn. Only plugin
88
+ // unload and the job's own deadline should stop an admitted job.
89
+ if (!sessions.has(sessionID)) sessions.set(sessionID, new Map())
90
+ const aspect = input.size && input.size !== "auto" ? undefined : input.aspect_ratio ?? "auto"
91
+ const task = run(ctx, { params, aspect, imageSize: input.image_size, sources, mask, paths, signal: lifecycle.signal }, sessionID, jobID, sessions.get(sessionID), active)
92
+ .catch(() => console.error(`[${pluginID}] Could not notify session ${sessionID} for job ${jobID}. Planned outputs: ${paths.join(", ")}`))
93
+ .finally(() => { release(); running.delete(task) })
94
+ running.add(task)
46
95
  return {
47
- content: `Saved PNG: ${result.out}${result.versioned ? " (versioned; existing file preserved)" : ""}`,
48
- metadata: {
49
- out: result.out,
50
- versioned: result.versioned,
51
- bytes: result.bytes,
52
- route: result.route,
53
- method: result.method,
54
- model: result.model,
55
- },
96
+ content: `后台生图任务已提交:${jobID}(请求 ${params.n} 张)。完成后会通知本会话,无需等待或轮询。`,
97
+ metadata: { jobID, status: "submitted", requested: params.n },
56
98
  }
57
99
  },
58
100
  })
59
101
  })
102
+ // Archive/delete clear this session only. A detached job retains its old
103
+ // map, so even a late 401 cannot recreate state for a removed session.
104
+ const events = (async () => {
105
+ for await (const event of ctx.event.subscribe({ types: ["session.archived", "session.deleted"], signal: lifecycle.signal })) {
106
+ sessions.delete(event.data.sessionID)
107
+ }
108
+ })().catch(() => { if (!lifecycle.signal.aborted) console.error(`[${pluginID}] Session lifecycle subscription ended.`) })
109
+ return async () => {
110
+ lifecycle.abort(new Error("插件已卸载,后台任务已取消。"))
111
+ sessions.clear()
112
+ await Promise.allSettled([...running, events])
113
+ }
60
114
  },
61
115
  }
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "@myoldtime/opencode-codex-imagegen",
3
- "version": "0.1.0",
3
+ "version": "1.0.0",
4
4
  "type": "module",
5
- "description": "OpenCode V2 plugin: proxy_imagegen generates images through the Responses hosted image_generation tool, using an explicit proxy or the OpenAI account managed by OpenCode (Sign in with ChatGPT and the legacy Codex methods).",
5
+ "description": "OpenCode V2 background image generation and editing with session-scoped Codex, OpenRouter, AIHubMix and Google Gemini failover.",
6
6
  "license": "MIT",
7
7
  "author": "MyOldTime",
8
8
  "repository": {
@@ -19,26 +19,31 @@
19
19
  "image-generation",
20
20
  "responses-api",
21
21
  "chatgpt",
22
- "codex"
22
+ "codex",
23
+ "openrouter",
24
+ "aihubmix",
25
+ "gemini"
23
26
  ],
24
27
  "main": "./index.js",
25
28
  "exports": {
26
- ".": "./index.js",
27
- "./core": "./core.mjs"
29
+ ".": "./index.js"
28
30
  },
29
31
  "files": [
30
32
  "index.js",
31
- "core.mjs",
33
+ "parameters.js",
34
+ "images.js",
35
+ "codex.js",
36
+ "google.js",
37
+ "routing.js",
38
+ "errors.js",
32
39
  "README.md",
33
- "VALIDATION.md",
34
- "LICENSE",
35
- "CHANGELOG.md"
40
+ "LICENSE"
36
41
  ],
37
42
  "publishConfig": {
38
43
  "access": "public"
39
44
  },
40
45
  "scripts": {
41
- "check": "node --check index.js && node --check core.mjs && node --check test.mjs && node --check release.test.mjs",
46
+ "check": "node --check index.js && node --check parameters.js && node --check images.js && node --check codex.js && node --check google.js && node --check routing.js && node --check errors.js && node --check test.mjs && node --check release.test.mjs",
42
47
  "test": "node --test test.mjs release.test.mjs",
43
48
  "prepublishOnly": "npm run check && npm test",
44
49
  "publish:npm": "npm publish --registry=https://registry.npmjs.org --@myoldtime:registry=https://registry.npmjs.org --access=public",
@@ -46,5 +51,9 @@
46
51
  },
47
52
  "engines": {
48
53
  "node": ">=20.16"
54
+ },
55
+ "dependencies": {
56
+ "jpeg-js": "0.4.4",
57
+ "pngjs": "7.0.0"
49
58
  }
50
- }
59
+ }
package/parameters.js ADDED
@@ -0,0 +1,151 @@
1
+ import path from "node:path"
2
+ import { ProviderFailure } from "./errors.js"
3
+ import { googleRatios } from "./google.js"
4
+
5
+ const defaultModel = "gpt-image-2.5-sunburst"
6
+ const providers = {
7
+ openrouter: { origin: "https://openrouter.ai", envKey: "OPENROUTER_API_KEY" },
8
+ aihubmix: { origin: "https://aihubmix.com", envKey: "AIHUBMIX_API_KEY" },
9
+ google: { origin: "https://generativelanguage.googleapis.com", envKey: "GEMINI_API_KEY" },
10
+ }
11
+ // Sunburst accepts pixel dimensions rather than an API aspect_ratio field.
12
+ const ratioSizes = {
13
+ auto: "auto", "1:1": "1024x1024", "3:2": "1536x1024", "2:3": "1024x1536",
14
+ "4:3": "1280x960", "3:4": "960x1280", "16:9": "1536x864", "9:16": "864x1536",
15
+ "21:9": "1792x768", "4:5": "1024x1280", "5:4": "1280x1024",
16
+ "2:1": "1536x768", "1:2": "768x1536", "3:1": "1920x640", "1:3": "640x1920",
17
+ }
18
+ export const googleOnlyRatios = googleRatios.filter(ratio => !Object.hasOwn(ratioSizes, ratio))
19
+ const qualities = ["auto", "low", "medium", "high", "xhigh", "max"]
20
+ const formats = ["png", "jpeg", "webp"]
21
+ const backgrounds = ["auto", "opaque", "transparent"]
22
+ const pixels = "^(auto|[1-9][0-9]{0,3}x[1-9][0-9]{0,3})$"
23
+
24
+ export const schema = {
25
+ type: "object",
26
+ properties: {
27
+ prompt: { type: "string", minLength: 1, maxLength: 32000, description: "Describe the desired image or edits. For multiple references, describe the role of each in order." },
28
+ out: { type: "string", description: "Optional first output filename (.png, .jpg, .jpeg, .webp), absolute or relative to this session. Otherwise a unique name under images/ is used. Extra outputs are numbered." },
29
+ images: { type: "array", maxItems: 16, items: { type: "string" }, description: "Local PNG, JPEG or WebP reference paths, in order. Omit for text-to-image." },
30
+ mask: { type: "string", description: "Optional local PNG edit mask, with reference image(s). Masked edits require AIHubMix; omit for ordinary generation and unmasked edits." },
31
+ quality: { type: "string", enum: qualities, default: "auto", description: "Use auto normally, low for a quick draft, high for a polished final. Reserve xhigh/max for an explicit request for maximum detail." },
32
+ aspect_ratio: { type: "string", enum: [...Object.keys(ratioSizes), ...googleOnlyRatios], description: "16:9 for a banner, 9:16 for a phone wallpaper, 1:1 for an avatar. Omit when specifying exact pixels. 1:4, 4:1, 1:8, 8:1 require Google." },
33
+ image_size: { type: "string", enum: ["1K", "2K", "4K"], description: "Google Gemini resolution tier, when explicitly requested. May accompany aspect_ratio. Omit for automatic provider selection; do not combine with exact pixel size." },
34
+ size: { type: "string", pattern: pixels, description: "Default auto. For a specific size use WIDTHxHEIGHT, e.g. 1536x1024. Each side must be a multiple of 16 and at most 3840; area 655360–8294400 pixels; ratio between 1:3 and 3:1. Leave out if using aspect_ratio." },
35
+ n: { type: "integer", minimum: 1, maximum: 10, default: 1, description: "Number of variations of this prompt. Default 1. When the user asks for multiple versions, request them together (1–10). The provider may return fewer." },
36
+ output_format: { type: "string", enum: formats, description: "Defaults to out's extension or PNG. Choose PNG for lossless graphics, JPEG for photographs, WebP for compact web assets." },
37
+ background: { type: "string", enum: backgrounds, default: "auto", description: "Use transparent for a cutout or sticker (PNG/WebP only); otherwise leave auto unless a solid background is requested." },
38
+ output_compression: { type: "integer", minimum: 0, maximum: 100, description: "Optional 0–100 API compression setting for JPEG/WebP. Omit for the provider default or for PNG." },
39
+ },
40
+ required: ["prompt"],
41
+ additionalProperties: false,
42
+ }
43
+
44
+ const text = value => typeof value === "string" && value.trim().length > 0
45
+ function rejectUnknown(value, keys, message) {
46
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("Expected an object.")
47
+ for (const key of Object.keys(value)) if (!keys.includes(key)) throw new Error(`${message}: ${key}`)
48
+ }
49
+
50
+ export function validateOptions(options = {}) {
51
+ rejectUnknown(options, ["codex", ...Object.keys(providers)], "Unknown provider")
52
+ for (const [provider, value] of Object.entries(options)) {
53
+ const keys = ["base_url", "key", "model", "disabled"]
54
+ if (provider === "codex") keys.push("reasoning_effort", "fast_mode")
55
+ rejectUnknown(value, keys, "Unknown plugin option (generation settings belong in the tool call)")
56
+ if (value.disabled !== undefined && typeof value.disabled !== "boolean") throw new Error(`${provider}.disabled must be boolean.`)
57
+ }
58
+ const codex = options.codex
59
+ if (codex?.reasoning_effort !== undefined && !["none", "minimal", "low", "medium", "high", "xhigh"].includes(codex.reasoning_effort))
60
+ throw new Error("Invalid codex.reasoning_effort.")
61
+ if (codex?.fast_mode !== undefined && typeof codex.fast_mode !== "boolean") throw new Error("codex.fast_mode must be boolean.")
62
+ }
63
+
64
+ function effectiveKey(provider, options, env) {
65
+ if (options.key != null) return options.key
66
+ const { origin, envKey } = providers[provider]
67
+ // Only the official origin may inherit a key from the server environment.
68
+ try { if (new URL(options.base_url ?? origin).origin === origin) return env[envKey] } catch {}
69
+ }
70
+
71
+ export function configuredProviders(options = {}, env = process.env) {
72
+ const active = []
73
+ for (const provider of Object.keys(providers)) {
74
+ const { disabled = false, ...settings } = options[provider] ?? {}
75
+ if (disabled) continue
76
+ const key = effectiveKey(provider, settings, env)
77
+ if (text(key) && !key.trim().startsWith("{env:")) active.push({ provider, settings: { ...settings, key } })
78
+ }
79
+ return active
80
+ }
81
+
82
+ export function connection(provider, options = {}, env = process.env) {
83
+ rejectUnknown(options, ["base_url", "key", "model"], "Unknown plugin option (generation settings belong in the tool call)")
84
+ const router = provider === "openrouter"
85
+ const { origin: baseURL, envKey: keyName } = providers[provider]
86
+ for (const [name, value] of Object.entries(options)) if (name !== "key" && !text(value)) throw new ProviderFailure(`options.${provider}.${name} must be a non-empty string.`)
87
+ const address = options.base_url?.trim() ?? baseURL
88
+ let url
89
+ try { url = new URL(address) }
90
+ catch { throw new ProviderFailure("Invalid base_url.") }
91
+ if (!/^https?:\/\//i.test(address) || url.username || url.password || /[?#]/.test(address))
92
+ throw new ProviderFailure("base_url must be an HTTP(S) API base without credentials, query or fragment.")
93
+ const key = effectiveKey(provider, options, env)
94
+ if (!text(key) || key.trim().startsWith("{env:") || /[^\x21-\x7e]/.test(key.trim())) throw new ProviderFailure(`缺少或无效的 key(${keyName})。`, { disable: true })
95
+ if (provider === "google") {
96
+ const prefix = url.pathname.replace(/\/+$/, "")
97
+ if (prefix.endsWith("/interactions")) url.pathname = prefix
98
+ else if (/\/v1(?:beta)?$/.test(prefix)) url.pathname = `${prefix}/interactions`
99
+ else url.pathname = `${prefix}/v1beta/interactions`
100
+ return { endpoint: url.href, key: key.trim(), model: options.model?.trim() ?? "gemini-nano-banana-2.1" }
101
+ }
102
+ if (router) {
103
+ const prefix = url.pathname.replace(/\/+$/, "")
104
+ url.pathname = prefix.endsWith("/images") ? prefix : `${prefix || "/api/v1"}/images`
105
+ return { endpoint: url.href, key: key.trim(), model: options.model?.trim() ?? `openai/${defaultModel}` }
106
+ }
107
+ const prefix = url.pathname.replace(/\/+$/, "").replace(/\/images(?:\/(?:generations|edits))?$/, "") || "/ai/v1"
108
+ if (!prefix.endsWith("/v1")) throw new ProviderFailure("Use the AIHubMix host, /ai/v1, /v1, or a full image endpoint as base_url.")
109
+ url.pathname = `${prefix}/images/generations`
110
+ return { endpoint: url.href, native: prefix.endsWith("/ai/v1"), key: key.trim(), model: options.model?.trim() ?? defaultModel }
111
+ }
112
+
113
+ // Validate again at execution: a tool can also be called by a programmatic client.
114
+ export function parameters(input) {
115
+ rejectUnknown(input, Object.keys(schema.properties), "Unknown image generation argument")
116
+ if (!text(input.prompt)) throw new Error("prompt is required.")
117
+ if ([...input.prompt].length > 32000) throw new Error("prompt must not exceed 32000 characters.")
118
+ if (input.out !== undefined && !text(input.out)) throw new Error("out must be a filename.")
119
+ if (input.images !== undefined && (!Array.isArray(input.images) || input.images.length > 16 || !input.images.every(text)))
120
+ throw new Error("images must be a list of up to 16 local image paths.")
121
+ if (input.mask !== undefined && (!text(input.mask) || !input.images?.length)) throw new Error("mask requires a local path and at least one reference image.")
122
+ for (const [key, spec] of Object.entries(schema.properties)) {
123
+ if (input[key] === undefined) continue
124
+ if (spec.enum && !spec.enum.includes(input[key])) throw new Error(`${key} must be one of ${spec.enum.join(", ")}.`)
125
+ if (spec.type === "integer" && !(Number.isInteger(input[key]) && input[key] >= spec.minimum && input[key] <= spec.maximum))
126
+ throw new Error(`${key} must be an integer from ${spec.minimum} to ${spec.maximum}.`)
127
+ }
128
+ if (input.size !== undefined && (typeof input.size !== "string" || !new RegExp(pixels).test(input.size)))
129
+ throw new Error("size must be auto or WIDTHxHEIGHT.")
130
+ if (input.size && input.aspect_ratio) throw new Error("Choose either size or aspect_ratio.")
131
+ if (input.image_size && input.size && input.size !== "auto") throw new Error("Choose either image_size or exact pixel size.")
132
+ const size = input.size ?? ratioSizes[input.aspect_ratio ?? "auto"] ?? "auto"
133
+ if (size !== "auto") {
134
+ const [w, h] = size.split("x").map(Number)
135
+ if (w % 16 || h % 16 || Math.max(w,h) > 3840 || w*h < 655360 || w*h > 8294400 || w > 3*h || h > 3*w)
136
+ throw new Error("size is outside the Sunburst pixel, aspect ratio or multiple-of-16 limits.")
137
+ }
138
+ const ext = input.out && path.extname(input.out).slice(1).toLowerCase()
139
+ const fromPath = ext === "jpg" ? "jpeg" : ext
140
+ if (input.out && !formats.includes(fromPath)) throw new Error("out must end in .png, .jpg, .jpeg or .webp.")
141
+ const output_format = input.output_format ?? fromPath ?? "png"
142
+ if (fromPath && fromPath !== output_format) throw new Error("out extension must match output_format.")
143
+ if (output_format === "jpeg" && input.background === "transparent") throw new Error("Transparent images require PNG or WebP.")
144
+ if (output_format === "png" && input.output_compression !== undefined) throw new Error("output_compression requires JPEG or WebP.")
145
+ return {
146
+ prompt: input.prompt, n: input.n ?? 1, quality: input.quality ?? "auto",
147
+ output_format, background: input.background ?? "auto",
148
+ size,
149
+ ...(input.output_compression === undefined ? {} : { output_compression: input.output_compression }),
150
+ }
151
+ }