@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/README.md +82 -192
- package/codex.js +167 -0
- package/errors.js +24 -0
- package/google.js +79 -0
- package/images.js +235 -0
- package/index.js +100 -46
- package/package.json +20 -11
- package/parameters.js +151 -0
- package/routing.js +46 -0
- package/CHANGELOG.md +0 -15
- package/VALIDATION.md +0 -42
- package/core.mjs +0 -420
package/routing.js
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { connection, googleOnlyRatios } from "./parameters.js"
|
|
2
|
+
import { generate, loadInputs } from "./images.js"
|
|
3
|
+
import { ProviderFailure } from "./errors.js"
|
|
4
|
+
import { codexUnsupported } from "./codex.js"
|
|
5
|
+
import { googleUnsupported } from "./google.js"
|
|
6
|
+
|
|
7
|
+
function unsupportedReason(provider, job, inputs) {
|
|
8
|
+
if (provider === "google") return googleUnsupported(job, inputs)
|
|
9
|
+
if (job.imageSize || googleOnlyRatios.includes(job.aspect)) return "本次分辨率档位或画幅需要 Google。"
|
|
10
|
+
if (provider === "codex") return codexUnsupported(job.params, inputs.mask)
|
|
11
|
+
if (provider === "openrouter" && inputs.mask) return "OpenRouter Sunburst 不支持蒙版。"
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
// The caller owns this map per session. Keep only redacted diagnostic strings,
|
|
15
|
+
// never clients, keys, request bodies, or an installation-wide "current" provider.
|
|
16
|
+
export async function route(job, disabled, active, attempts) {
|
|
17
|
+
const inputs = await loadInputs(job)
|
|
18
|
+
for (const candidate of active) {
|
|
19
|
+
const { provider, settings } = candidate
|
|
20
|
+
job.signal.throwIfAborted()
|
|
21
|
+
const entry = { provider }
|
|
22
|
+
attempts.push(entry)
|
|
23
|
+
if (disabled.has(provider)) {
|
|
24
|
+
Object.assign(entry, { status: "skipped", reason: `本会话已停用:${disabled.get(provider)}` })
|
|
25
|
+
continue
|
|
26
|
+
}
|
|
27
|
+
const unsupported = unsupportedReason(provider, job, inputs)
|
|
28
|
+
if (unsupported) {
|
|
29
|
+
Object.assign(entry, { status: "skipped", reason: unsupported })
|
|
30
|
+
continue
|
|
31
|
+
}
|
|
32
|
+
const timeout = AbortSignal.timeout(10 * 60_000)
|
|
33
|
+
try {
|
|
34
|
+
const config = provider === "codex" ? undefined : connection(provider, settings)
|
|
35
|
+
await generate({ ...job, ...inputs, signal: AbortSignal.any([job.signal, timeout]), provider, config, candidate })
|
|
36
|
+
entry.status = "succeeded"
|
|
37
|
+
return provider
|
|
38
|
+
} catch (error) {
|
|
39
|
+
job.signal.throwIfAborted()
|
|
40
|
+
Object.assign(entry, { status: "failed", reason: timeout.aborted ? "请求超时。" : error.message })
|
|
41
|
+
if (error instanceof ProviderFailure && error.disable) disabled.set(provider, entry.reason)
|
|
42
|
+
if (job.saved.length || !(error instanceof ProviderFailure) || !error.fallback) throw error
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
throw new Error("没有可完成本次请求的服务。")
|
|
46
|
+
}
|
package/CHANGELOG.md
DELETED
|
@@ -1,15 +0,0 @@
|
|
|
1
|
-
# Changelog
|
|
2
|
-
|
|
3
|
-
## 0.1.0
|
|
4
|
-
|
|
5
|
-
- 首个发布版本,包名 `@myoldtime/opencode-codex-imagegen`,插件 id `opencode-codex-imagegen`,工具名 `proxy_imagegen`(不变)。历史本地版本的 id(`local.codex-proxy-imagegen`、`myoldtime.codex-proxy-imagegen`)仅存在于迁移说明中作为旧 id 出现。
|
|
6
|
-
- 双源发布:npmjs 与 GitHub Packages 使用同一个 scoped 包名,各自通过显式 `--registry` + `--@myoldtime:registry` 发布;GitHub Actions 在 Release `published` 时发布 GitHub Packages,npmjs 由本机已登录账号在确认后执行 `npm run publish:npm`。
|
|
7
|
-
- 显式 `options.base_url` + `options.key` 优先,且完全不读取宿主凭据;仅给有效的 `key` 时默认 `https://api.openai.com/v1`。**只要写了 `base_url` / `key`,空串、`null`、全空白、未解析的 `{env:...}` 一律报错**,只有两者都完全省略才走宿主账号。
|
|
8
|
-
- 未配置凭据时通过 `ctx.integration.connection.active("openai")` + `resolve(connection)` 使用 OpenCode 托管的 OpenAI 账号,每次调用重新解析,刷新由宿主负责。
|
|
9
|
-
- 支持三种登录方法的路由:`chatgpt-token-sharing` → `https://api.openai.com/v1/responses`;`chatgpt-browser` / `chatgpt-headless` → `https://chatgpt.com/backend-api/codex/responses`;未知方法明确报错。
|
|
10
|
-
- 仍只使用 Responses 托管 `image_generation` 工具(非 Images API)。
|
|
11
|
-
- 失败不重试、不换通道;错误只暴露 HTTP 状态与白名单错误码,不输出上游正文、token 或账号。
|
|
12
|
-
- 响应体/SSE 读取期间的网络错误统一归一为固定文案;超时或取消后的晚到结果在落盘前丢弃,落盘阶段取消只清理本次新建的文件。
|
|
13
|
-
- 保留模型/画质/尺寸/推理强度/优先级/超时/参考图/PNG 独占版本保存行为。
|
|
14
|
-
- 内置自动化测试全部离线;另已实际验证 API 中转、两种 legacy 登录均出图成功。新版 Sign in with ChatGPT 被上游以 `subscription_sharing_unsupported_capability` 拒绝,限制已在文档明确说明。
|
|
15
|
-
- 兼容缺失 Content-Type 的 Codex SSE 响应,支持单字节/UTF-8 分片格式检测。
|
package/VALIDATION.md
DELETED
|
@@ -1,42 +0,0 @@
|
|
|
1
|
-
# 验证记录
|
|
2
|
-
|
|
3
|
-
测试日期:2026-10-30。宿主 OpenCode 2.2.0,Node.js 24.18.0,Windows。
|
|
4
|
-
|
|
5
|
-
## 自动化测试
|
|
6
|
-
|
|
7
|
-
- `npm ci --ignore-scripts`:通过(无新增依赖,0 vulnerabilities)。
|
|
8
|
-
- `npm run check`:通过。
|
|
9
|
-
- `npm test`:36 项通过,无跳过(`test.mjs` 26 项 + `release.test.mjs` 10 项)。
|
|
10
|
-
- `npm pack --dry-run --json`:通过,`@myoldtime/opencode-codex-imagegen@0.1.0`,7 个文件(`package.json`、`index.js`、`core.mjs`、`README.md`、`VALIDATION.md`、`CHANGELOG.md`、`LICENSE`)。
|
|
11
|
-
- 包内容使用 `package.json` 的 `files` 白名单,不包含凭据、原始响应、测试图片、测试脚本、`.github` 或机器配置。
|
|
12
|
-
- 路由测试覆盖显式 API key、宿主托管 API key 和三种 OAuth 方法;另覆盖权限、凭据刷新委托、严格配置校验、错误脱敏、流式解析、取消与超时、引用图片以及文件不覆盖。
|
|
13
|
-
|
|
14
|
-
## 本轮重命名与双源发布准备(离线)
|
|
15
|
-
|
|
16
|
-
- 本轮只做元数据与文档重命名,未重新联网生成图片:`core.mjs` 逻辑未改动。改名前后的 SHA256 均为 `D04176C047A350BD2198A56EFE024385B1DDB6E862571293010D0EDEF7EFC896`;`index.js` 仅插件 ID 从 `myoldtime.codex-proxy-imagegen` 改为 `opencode-codex-imagegen`,工具名 `proxy_imagegen` 不变。
|
|
17
|
-
- 包名在 npmjs 与 GitHub Packages 统一为 `@myoldtime/opencode-codex-imagegen`,`package.json` 与 `package-lock.json` 同名同版本(0.1.0,MIT)。
|
|
18
|
-
- `publish:npm` / `publish:github` 各自显式给出 `--registry` 与 `--@myoldtime:registry`(同一目标 URL),`publishConfig` 只保留 `access: public`,项目不含 `.npmrc`;`release.test.mjs` 断言脚本、workflow 的 registry/scope override、tag 与版本、`access`、`NODE_AUTH_TOKEN` 仅来自 `secrets.GITHUB_TOKEN`、files 白名单不含凭据与测试。
|
|
19
|
-
- GitHub Actions 只在 Release `published` 时发布 GitHub Packages;npmjs 由本机已登录账号在用户未来单独确认后执行 `npm run publish:npm`。本机 npm 登录不会传入 Actions,因此没有配置 `NPM_TOKEN`,也未做 OIDC 自动授权。
|
|
20
|
-
|
|
21
|
-
## 真实请求(历史记录,本轮未重复执行)
|
|
22
|
-
|
|
23
|
-
下表是代码与账号能力的历史验证,不属于本轮离线重命名验证;本轮未再次联网生成,也未验证真实发布。
|
|
24
|
-
|
|
25
|
-
| 通道 | 当前证据 | 范围 |
|
|
26
|
-
|---|---|---|
|
|
27
|
-
| 显式 API 配置 | 成功生成 PNG,1536×1024 | 通过既有 Responses 兼容中转,非官方 API key 直连验证 |
|
|
28
|
-
| Codex browser (legacy) | 成功生成 PNG,1536×1024,约 21 秒 | 在隔离测试插件中调用生产核心,并使用真实宿主 `connection.active/resolve`,没有手动读取或刷新凭据文件;临时会话已清理 |
|
|
29
|
-
| Sign in with ChatGPT | 上游拒绝:HTTP 400 / `subscription_sharing_unsupported_capability`,约 1.8 秒 | 用户确认准备后,经真实宿主解析此登录方式并请求官方 Responses;没有生成图片,没有重试或换通道;不是生图成功 |
|
|
30
|
-
| Codex device code (legacy) | 成功生成 PNG,1536×1024,约 23 秒 | 用户确认准备后,经真实宿主 `connection.active/resolve` 解析 device-code 登录;临时会话已清理 |
|
|
31
|
-
|
|
32
|
-
实际图片尺寸可能由上游调整,不保证与请求尺寸完全一致。验证仅针对当次账号、模型和服务状态,不承诺所有订阅与未来上游版本均可用。
|
|
33
|
-
|
|
34
|
-
legacy 验证发现真实响应可能省略 Content-Type,已修复为有界前缀格式检测,并新增单字节分片回归;另外通过保留的真实响应离线重放恢复图片,未为重放重复发起请求。
|
|
35
|
-
|
|
36
|
-
## 发布与安装
|
|
37
|
-
|
|
38
|
-
**当前状态:尚未创建远端仓库、未 push、未打 tag、未发布 Release、未运行任何发布命令,也未切换正在使用的插件。** 本节命令只有用户未来单独确认后才会使用。
|
|
39
|
-
|
|
40
|
-
- npmjs:本机 `npm whoami` 已确认为 `myoldtime`(只读检查,未登录、未读取 token);确认后执行 `npm run publish:npm`。发布前可先运行只读的 `npm view @myoldtime/opencode-codex-imagegen@0.1.0 version --registry=https://registry.npmjs.org --@myoldtime:registry=https://registry.npmjs.org` 与 `npm pack --dry-run`(查固定版本,并显式覆盖可能存在的 scope 映射)。
|
|
41
|
-
- GitHub Packages:在 <https://github.com/MyOldTime/opencode-codex-imagegen> 发布 Release(tag `v0.1.0`)后,由 [Actions](https://github.com/MyOldTime/opencode-codex-imagegen/actions) 中的 `publish.yml` 发布,并在同一 workflow 里做版本校验。实际发布状态以 Actions 与 [Release](https://github.com/MyOldTime/opencode-codex-imagegen/releases/tag/v0.1.0) 为准。
|
|
42
|
-
- 安装应使用固定版本,并确认宿主显示插件来源为 package 而非旧本地目录。README 中在线安装说明均标注为"发布后可用"。
|
package/core.mjs
DELETED
|
@@ -1,420 +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
|
-
// OAuth sign-in methods that this plugin knows how to route. Anything else is rejected
|
|
11
|
-
// instead of guessing an endpoint.
|
|
12
|
-
export const SUPPORTED_OAUTH_METHODS = ["chatgpt-token-sharing", "chatgpt-browser", "chatgpt-headless"]
|
|
13
|
-
const LEGACY_METHODS = new Set(["chatgpt-browser", "chatgpt-headless"])
|
|
14
|
-
|
|
15
|
-
// Only these upstream codes may appear in an error message. Everything else is reported
|
|
16
|
-
// as a generic upstream failure so account data never leaks.
|
|
17
|
-
const SAFE_ERROR_CODES = new Set([
|
|
18
|
-
"subscription_sharing_usage_limit_exceeded",
|
|
19
|
-
"subscription_sharing_user_not_eligible",
|
|
20
|
-
"subscription_sharing_unsupported_capability",
|
|
21
|
-
"subscription_sharing_route_not_supported",
|
|
22
|
-
"subscription_sharing_invalid_user",
|
|
23
|
-
"chatpass_v2_scope_not_authorized",
|
|
24
|
-
"chatpass_v2_invalid_authorization_context",
|
|
25
|
-
])
|
|
26
|
-
|
|
27
|
-
const DEFAULT_MODEL = "gpt-6.1-sol"
|
|
28
|
-
const DEFAULT_TIMEOUT_MS = 240000
|
|
29
|
-
const INSTRUCTIONS = "Generate the requested image by invoking image_generation exactly once. Do not respond with text only."
|
|
30
|
-
|
|
31
|
-
const OMIT_HINT = "omit options.base_url and options.key entirely to use the OpenAI account signed in to OpenCode"
|
|
32
|
-
|
|
33
|
-
export function pluginConfig(options = {}) {
|
|
34
|
-
if (options === null || typeof options !== "object" || Array.isArray(options)) throw new Error("Plugin options must be an object")
|
|
35
|
-
// Presence is explicit: an empty, null, blank or unresolved value is a configuration error,
|
|
36
|
-
// never a silent fallback. Only a fully omitted pair uses the host-managed account.
|
|
37
|
-
const hasBase = options.base_url !== undefined
|
|
38
|
-
const hasKey = options.key !== undefined
|
|
39
|
-
if (hasBase && (typeof options.base_url !== "string" || !options.base_url.trim())) {
|
|
40
|
-
throw new Error(`options.base_url must be a non-empty string; ${OMIT_HINT}`)
|
|
41
|
-
}
|
|
42
|
-
if (hasKey && (typeof options.key !== "string" || !options.key.trim())) {
|
|
43
|
-
throw new Error(`options.key must be a non-empty string; ${OMIT_HINT}`)
|
|
44
|
-
}
|
|
45
|
-
const baseURL = hasBase ? options.base_url.trim() : ""
|
|
46
|
-
const apiKey = hasKey ? options.key.trim() : ""
|
|
47
|
-
if (apiKey.startsWith("{env:")) {
|
|
48
|
-
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")
|
|
49
|
-
}
|
|
50
|
-
if (hasBase && !hasKey) {
|
|
51
|
-
throw new Error("options.base_url requires options.key; configure both or omit both to use the signed-in OpenAI account")
|
|
52
|
-
}
|
|
53
|
-
const model = options.model ?? DEFAULT_MODEL
|
|
54
|
-
if (typeof model !== "string" || !model.trim()) throw new Error("model must be a nonempty string")
|
|
55
|
-
if (options.reasoning_effort !== undefined && !["none", "minimal", "low", "medium", "high", "xhigh"].includes(options.reasoning_effort)) {
|
|
56
|
-
throw new Error("reasoning_effort must be none, minimal, low, medium, high or xhigh (model support varies)")
|
|
57
|
-
}
|
|
58
|
-
if (options.fast_mode !== undefined && typeof options.fast_mode !== "boolean") throw new Error("fast_mode must be boolean")
|
|
59
|
-
const timeoutMs = options.timeout_ms ?? DEFAULT_TIMEOUT_MS
|
|
60
|
-
if (!Number.isInteger(timeoutMs) || timeoutMs <= 0) throw new Error("timeout_ms must be a positive integer")
|
|
61
|
-
// key only: fall back to the public OpenAI endpoint. Both present: explicit proxy. Neither: host-managed.
|
|
62
|
-
const explicit = Boolean(apiKey)
|
|
63
|
-
const explicitBase = explicit ? baseURL || DEFAULT_OPENAI_BASE_URL : undefined
|
|
64
|
-
// Fail on a malformed proxy URL before any session, permission or network work happens.
|
|
65
|
-
if (explicitBase) responsesURL(explicitBase)
|
|
66
|
-
return {
|
|
67
|
-
mode: explicit ? "explicit" : "managed",
|
|
68
|
-
baseURL: explicitBase,
|
|
69
|
-
apiKey: explicit ? apiKey : undefined,
|
|
70
|
-
model: model.trim(),
|
|
71
|
-
reasoningEffort: options.reasoning_effort,
|
|
72
|
-
fastMode: options.fast_mode ?? false,
|
|
73
|
-
timeoutMs,
|
|
74
|
-
}
|
|
75
|
-
}
|
|
76
|
-
|
|
77
|
-
export function responsesURL(baseURL) {
|
|
78
|
-
const url = new URL(baseURL)
|
|
79
|
-
if (!["http:", "https:"].includes(url.protocol) || url.username || url.password || url.search || url.hash) {
|
|
80
|
-
throw new Error("baseURL must be an HTTP(S) URL without credentials, query or fragment")
|
|
81
|
-
}
|
|
82
|
-
url.pathname = url.pathname.replace(/\/+$/, "")
|
|
83
|
-
if (!url.pathname.endsWith("/responses")) url.pathname += "/responses"
|
|
84
|
-
return url.toString()
|
|
85
|
-
}
|
|
86
|
-
|
|
87
|
-
export function abortError() {
|
|
88
|
-
const error = new Error("Image generation aborted")
|
|
89
|
-
error.name = "AbortError"
|
|
90
|
-
return error
|
|
91
|
-
}
|
|
92
|
-
|
|
93
|
-
// Messages that this plugin produced itself and may be shown verbatim.
|
|
94
|
-
class ImageResponseError extends Error {}
|
|
95
|
-
|
|
96
|
-
export function timeoutError() {
|
|
97
|
-
return new Error("Image request timed out")
|
|
98
|
-
}
|
|
99
|
-
|
|
100
|
-
function abortIfNeeded(signal) {
|
|
101
|
-
if (signal?.aborted) throw abortError()
|
|
102
|
-
}
|
|
103
|
-
|
|
104
|
-
function throwIfSettled(signal, combinedSignal) {
|
|
105
|
-
if (signal?.aborted) throw abortError()
|
|
106
|
-
if (combinedSignal?.aborted) throw timeoutError()
|
|
107
|
-
}
|
|
108
|
-
|
|
109
|
-
function connectionError(detail) {
|
|
110
|
-
return new Error(`${detail} Configure options.base_url and options.key to use a proxy instead.`)
|
|
111
|
-
}
|
|
112
|
-
|
|
113
|
-
// Resolves the request route for this call. Explicit options never touch the host credential
|
|
114
|
-
// API; managed mode re-resolves the connection on every call so OpenCode owns refresh.
|
|
115
|
-
export async function resolveRoute(config, ctx) {
|
|
116
|
-
if (config.mode === "explicit") {
|
|
117
|
-
return { route: "proxy", method: "options", url: responsesURL(config.baseURL), access: config.apiKey }
|
|
118
|
-
}
|
|
119
|
-
const integration = ctx?.integration?.connection
|
|
120
|
-
if (!integration || typeof integration.active !== "function" || typeof integration.resolve !== "function") {
|
|
121
|
-
throw connectionError("OpenCode did not expose an OpenAI connection to this plugin.")
|
|
122
|
-
}
|
|
123
|
-
let connection
|
|
124
|
-
try {
|
|
125
|
-
connection = await integration.active("openai")
|
|
126
|
-
} catch {
|
|
127
|
-
throw connectionError("OpenCode could not read the OpenAI connection.")
|
|
128
|
-
}
|
|
129
|
-
if (!connection) {
|
|
130
|
-
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.")
|
|
131
|
-
}
|
|
132
|
-
let credential
|
|
133
|
-
try {
|
|
134
|
-
credential = await integration.resolve(connection)
|
|
135
|
-
} catch {
|
|
136
|
-
throw connectionError("OpenCode could not provide a usable OpenAI credential; the sign-in may have expired or need attention. Sign in again.")
|
|
137
|
-
}
|
|
138
|
-
if (!credential || typeof credential !== "object") {
|
|
139
|
-
throw connectionError("OpenCode returned no OpenAI credential for the connected account. Sign in again.")
|
|
140
|
-
}
|
|
141
|
-
if (credential.type === "key") {
|
|
142
|
-
if (typeof credential.key !== "string" || !credential.key.trim()) {
|
|
143
|
-
throw connectionError("The OpenAI connection returned an empty API key.")
|
|
144
|
-
}
|
|
145
|
-
return { route: "openai-key", method: "api-key", url: OPENAI_RESPONSES_URL, access: credential.key.trim() }
|
|
146
|
-
}
|
|
147
|
-
if (credential.type !== "oauth") {
|
|
148
|
-
throw connectionError("The OpenAI connection returned an unsupported credential type.")
|
|
149
|
-
}
|
|
150
|
-
const methodID = credential.methodID
|
|
151
|
-
if (!SUPPORTED_OAUTH_METHODS.includes(methodID)) {
|
|
152
|
-
// Never echo the raw method value: it may carry arbitrary credential data.
|
|
153
|
-
throw connectionError(`Unsupported OpenAI sign-in method. Supported methods: ${SUPPORTED_OAUTH_METHODS.join(", ")}.`)
|
|
154
|
-
}
|
|
155
|
-
if (typeof credential.access !== "string" || !credential.access.trim()) {
|
|
156
|
-
throw connectionError("OpenCode returned an empty or expired OpenAI access token. Sign in again.")
|
|
157
|
-
}
|
|
158
|
-
if (typeof credential.expires === "number" && credential.expires <= Date.now()) {
|
|
159
|
-
throw connectionError("The OpenAI access token has expired and could not be refreshed. Sign in again.")
|
|
160
|
-
}
|
|
161
|
-
const access = credential.access.trim()
|
|
162
|
-
if (LEGACY_METHODS.has(methodID)) {
|
|
163
|
-
const accountID = credential.metadata?.accountID
|
|
164
|
-
return {
|
|
165
|
-
route: methodID,
|
|
166
|
-
method: methodID,
|
|
167
|
-
url: CODEX_RESPONSES_URL,
|
|
168
|
-
access,
|
|
169
|
-
accountID: typeof accountID === "string" && accountID ? accountID : undefined,
|
|
170
|
-
}
|
|
171
|
-
}
|
|
172
|
-
return { route: "chatgpt-token-sharing", method: methodID, url: OPENAI_RESPONSES_URL, access }
|
|
173
|
-
}
|
|
174
|
-
|
|
175
|
-
export function requestHeaders(route, sessionID) {
|
|
176
|
-
const headers = {
|
|
177
|
-
Authorization: `Bearer ${route.access}`,
|
|
178
|
-
"Content-Type": "application/json",
|
|
179
|
-
Accept: "text/event-stream",
|
|
180
|
-
}
|
|
181
|
-
if (LEGACY_METHODS.has(route.route)) {
|
|
182
|
-
headers.originator = "opencode"
|
|
183
|
-
if (route.accountID) headers["ChatGPT-Account-Id"] = route.accountID
|
|
184
|
-
}
|
|
185
|
-
if (route.route !== "proxy" && route.route !== "openai-key" && typeof sessionID === "string" && sessionID) {
|
|
186
|
-
headers["session-id"] = sessionID
|
|
187
|
-
if (route.route === "chatgpt-token-sharing") {
|
|
188
|
-
headers["thread-id"] = sessionID
|
|
189
|
-
headers["x-client-request-id"] = sessionID
|
|
190
|
-
}
|
|
191
|
-
}
|
|
192
|
-
return headers
|
|
193
|
-
}
|
|
194
|
-
|
|
195
|
-
function imageType(bytes) {
|
|
196
|
-
if (bytes.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]))) return "image/png"
|
|
197
|
-
if (bytes[0] === 255 && bytes[1] === 216 && bytes[2] === 255) return "image/jpeg"
|
|
198
|
-
if (["GIF87a", "GIF89a"].includes(bytes.subarray(0, 6).toString())) return "image/gif"
|
|
199
|
-
if (bytes.subarray(0, 4).toString() === "RIFF" && bytes.subarray(8, 12).toString() === "WEBP") return "image/webp"
|
|
200
|
-
throw new Error("Unsupported reference image: use PNG, JPEG, GIF or WebP")
|
|
201
|
-
}
|
|
202
|
-
|
|
203
|
-
export function validateInput(input) {
|
|
204
|
-
if (!input || typeof input.prompt !== "string" || !input.prompt.trim()) throw new Error("prompt is required")
|
|
205
|
-
if (typeof input.out !== "string" || !input.out.trim() || path.extname(input.out).toLowerCase() !== ".png") {
|
|
206
|
-
throw new Error("out must be a .png file path")
|
|
207
|
-
}
|
|
208
|
-
if (input.quality !== undefined && !["auto", "low", "medium", "high"].includes(input.quality)) throw new Error("Invalid quality")
|
|
209
|
-
if (input.images !== undefined && (!Array.isArray(input.images) || input.images.some(p => typeof p !== "string"))) throw new Error("images must be file paths")
|
|
210
|
-
if (input.size !== undefined && input.size !== "auto") {
|
|
211
|
-
const match = /^(\d+)x(\d+)$/.exec(input.size)
|
|
212
|
-
const w = Number(match?.[1]), h = Number(match?.[2])
|
|
213
|
-
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) {
|
|
214
|
-
throw new Error("size must be auto or WIDTHxHEIGHT (16px multiples, max edge 3840, aspect <= 3:1, pixels 655360–8294400)")
|
|
215
|
-
}
|
|
216
|
-
}
|
|
217
|
-
}
|
|
218
|
-
|
|
219
|
-
function safeCode(value) {
|
|
220
|
-
return typeof value === "string" && SAFE_ERROR_CODES.has(value) ? value : undefined
|
|
221
|
-
}
|
|
222
|
-
|
|
223
|
-
function safeCodeFrom(payload) {
|
|
224
|
-
return safeCode(payload?.error?.code) ?? safeCode(payload?.response?.error?.code)
|
|
225
|
-
}
|
|
226
|
-
|
|
227
|
-
function resultFromEvent(event) {
|
|
228
|
-
if (event.type === "error" || event.type === "response.failed" || event.type === "response.incomplete") {
|
|
229
|
-
const code = safeCodeFrom(event)
|
|
230
|
-
throw new ImageResponseError(`Image response failed${code ? ` (${code})` : ""}`)
|
|
231
|
-
}
|
|
232
|
-
if (event.type === "response.output_item.done" && event.item?.type === "image_generation_call" && event.item.result) return event.item.result
|
|
233
|
-
return event.response?.output?.find(item => item.type === "image_generation_call" && item.result)?.result
|
|
234
|
-
}
|
|
235
|
-
|
|
236
|
-
export function parseEvent(text) {
|
|
237
|
-
try {
|
|
238
|
-
return JSON.parse(text)
|
|
239
|
-
} catch {
|
|
240
|
-
throw new ImageResponseError("Image response contained invalid JSON")
|
|
241
|
-
}
|
|
242
|
-
}
|
|
243
|
-
|
|
244
|
-
async function httpError(response, { signal, combinedSignal } = {}) {
|
|
245
|
-
let text = ""
|
|
246
|
-
try {
|
|
247
|
-
text = await response.text()
|
|
248
|
-
} catch {
|
|
249
|
-
text = ""
|
|
250
|
-
}
|
|
251
|
-
throwIfSettled(signal, combinedSignal)
|
|
252
|
-
let payload
|
|
253
|
-
try {
|
|
254
|
-
payload = text ? JSON.parse(text) : undefined
|
|
255
|
-
} catch {
|
|
256
|
-
payload = undefined
|
|
257
|
-
}
|
|
258
|
-
const code = safeCodeFrom(payload)
|
|
259
|
-
return new ImageResponseError(`Image request failed: HTTP ${response.status}${code ? ` (${code})` : ""}`)
|
|
260
|
-
}
|
|
261
|
-
|
|
262
|
-
// SSE frames may be split anywhere, including inside UTF-8 characters and CRLF.
|
|
263
|
-
export async function readImageResponse(response) {
|
|
264
|
-
if (!response.body) throw new ImageResponseError("Empty image response")
|
|
265
|
-
// Some Codex gateways return valid SSE without a Content-Type header. Detect
|
|
266
|
-
// the wire format from a bounded prefix instead of mistaking that stream for JSON.
|
|
267
|
-
const contentType = response.headers.get("content-type")?.toLowerCase() ?? ""
|
|
268
|
-
let format = contentType.includes("text/event-stream") ? "sse" : contentType.includes("application/json") ? "json" : "detect"
|
|
269
|
-
const reader = response.body.getReader()
|
|
270
|
-
const decoder = new TextDecoder()
|
|
271
|
-
let pending = "", data = []
|
|
272
|
-
const dispatch = () => {
|
|
273
|
-
const text = data.join("\n")
|
|
274
|
-
data = []
|
|
275
|
-
if (!text || text === "[DONE]") return
|
|
276
|
-
return resultFromEvent(parseEvent(text))
|
|
277
|
-
}
|
|
278
|
-
const line = text => {
|
|
279
|
-
if (!text) return dispatch()
|
|
280
|
-
if (text === "data") data.push("")
|
|
281
|
-
else if (text.startsWith("data:")) data.push(text.slice(5).replace(/^ /, ""))
|
|
282
|
-
}
|
|
283
|
-
try {
|
|
284
|
-
while (true) {
|
|
285
|
-
const { value, done } = await reader.read()
|
|
286
|
-
pending += done ? decoder.decode() : decoder.decode(value, { stream: true })
|
|
287
|
-
if (format === "detect") {
|
|
288
|
-
const prefix = pending.trimStart()
|
|
289
|
-
if (/^[\[{]/.test(prefix)) format = "json"
|
|
290
|
-
else if (/^(?:(?:data|event|id|retry)(?::|\r?\n)|:)/.test(prefix)) {
|
|
291
|
-
format = "sse"
|
|
292
|
-
pending = prefix
|
|
293
|
-
} else if (done || pending.length > 65536 || prefix.includes("\n")) {
|
|
294
|
-
throw new ImageResponseError("Image response contained invalid JSON or SSE")
|
|
295
|
-
} else continue
|
|
296
|
-
}
|
|
297
|
-
if (format === "json") {
|
|
298
|
-
if (!done) continue
|
|
299
|
-
const result = resultFromEvent({ type: "response.completed", response: parseEvent(pending) })
|
|
300
|
-
if (!result) throw new ImageResponseError("No image_generation_call.result in JSON response")
|
|
301
|
-
return result
|
|
302
|
-
}
|
|
303
|
-
let index
|
|
304
|
-
while ((index = pending.indexOf("\n")) !== -1) {
|
|
305
|
-
const text = pending.slice(0, index).replace(/\r$/, "")
|
|
306
|
-
pending = pending.slice(index + 1)
|
|
307
|
-
const result = line(text)
|
|
308
|
-
if (result) return result
|
|
309
|
-
}
|
|
310
|
-
if (done) {
|
|
311
|
-
if (pending) line(pending.replace(/\r$/, ""))
|
|
312
|
-
const result = dispatch()
|
|
313
|
-
if (result) return result
|
|
314
|
-
break
|
|
315
|
-
}
|
|
316
|
-
}
|
|
317
|
-
} finally {
|
|
318
|
-
await reader.cancel().catch(() => {})
|
|
319
|
-
reader.releaseLock()
|
|
320
|
-
}
|
|
321
|
-
throw new ImageResponseError("Response ended without an image_generation_call.result")
|
|
322
|
-
}
|
|
323
|
-
|
|
324
|
-
export async function savePNG(out, directory, base64, signal) {
|
|
325
|
-
if (typeof base64 !== "string" || !/^[A-Za-z0-9+/]+={0,2}$/.test(base64) || base64.length % 4) throw new Error("Invalid image base64")
|
|
326
|
-
const bytes = Buffer.from(base64, "base64")
|
|
327
|
-
if (imageType(bytes) !== "image/png") throw new Error("Backend did not return PNG")
|
|
328
|
-
abortIfNeeded(signal)
|
|
329
|
-
const target = path.resolve(directory, out)
|
|
330
|
-
await mkdir(path.dirname(target), { recursive: true })
|
|
331
|
-
const stem = target.slice(0, -4)
|
|
332
|
-
for (let version = 1; ; version++) {
|
|
333
|
-
const file = version === 1 ? target : `${stem}-v${version}.png`
|
|
334
|
-
let handle
|
|
335
|
-
try { handle = await open(file, "wx") } catch (error) {
|
|
336
|
-
if (error.code === "EEXIST") continue
|
|
337
|
-
throw error
|
|
338
|
-
}
|
|
339
|
-
// Only files created by this call (open "wx") are ever removed; pre-existing files stay untouched.
|
|
340
|
-
let stillOpen = true
|
|
341
|
-
try {
|
|
342
|
-
await handle.writeFile(bytes)
|
|
343
|
-
await handle.close()
|
|
344
|
-
stillOpen = false
|
|
345
|
-
} catch (error) {
|
|
346
|
-
if (stillOpen) await handle.close().catch(() => {})
|
|
347
|
-
await unlink(file).catch(() => {})
|
|
348
|
-
throw error
|
|
349
|
-
}
|
|
350
|
-
if (signal?.aborted) {
|
|
351
|
-
// Cancelled while persisting: remove the file we just created, never a pre-existing one.
|
|
352
|
-
await unlink(file).catch(() => {})
|
|
353
|
-
throw abortError()
|
|
354
|
-
}
|
|
355
|
-
return { out: file, versioned: version > 1, bytes: bytes.length }
|
|
356
|
-
}
|
|
357
|
-
}
|
|
358
|
-
|
|
359
|
-
export async function generateImage(input, config, directory, env = {}) {
|
|
360
|
-
const { ctx, signal, sessionID, fetcher = fetch } = env
|
|
361
|
-
validateInput(input)
|
|
362
|
-
abortIfNeeded(signal)
|
|
363
|
-
// Credentials are resolved per call; explicit options never consult the host.
|
|
364
|
-
const route = await resolveRoute(config, ctx)
|
|
365
|
-
abortIfNeeded(signal)
|
|
366
|
-
const content = [{ type: "input_text", text: input.prompt }]
|
|
367
|
-
for (const file of input.images ?? []) {
|
|
368
|
-
const bytes = await readFile(path.resolve(directory, file), { signal })
|
|
369
|
-
content.push({ type: "input_image", image_url: `data:${imageType(bytes)};base64,${bytes.toString("base64")}` })
|
|
370
|
-
}
|
|
371
|
-
const timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS
|
|
372
|
-
if (!Number.isInteger(timeoutMs) || timeoutMs <= 0) throw new Error("timeoutMs must be a positive integer")
|
|
373
|
-
const combinedSignal = signal ? AbortSignal.any([signal, AbortSignal.timeout(timeoutMs)]) : AbortSignal.timeout(timeoutMs)
|
|
374
|
-
abortIfNeeded(signal)
|
|
375
|
-
let response
|
|
376
|
-
try {
|
|
377
|
-
response = await fetcher(route.url, {
|
|
378
|
-
method: "POST",
|
|
379
|
-
signal: combinedSignal,
|
|
380
|
-
redirect: "error",
|
|
381
|
-
headers: requestHeaders(route, sessionID),
|
|
382
|
-
body: JSON.stringify({
|
|
383
|
-
model: config.model,
|
|
384
|
-
instructions: INSTRUCTIONS,
|
|
385
|
-
input: [{ role: "user", content }],
|
|
386
|
-
tools: [{ type: "image_generation", output_format: "png", quality: input.quality ?? "auto", ...(input.size ? { size: input.size } : {}) }],
|
|
387
|
-
tool_choice: { type: "image_generation" },
|
|
388
|
-
stream: true,
|
|
389
|
-
store: false,
|
|
390
|
-
...(config.reasoningEffort !== undefined ? { reasoning: { effort: config.reasoningEffort } } : {}),
|
|
391
|
-
...(config.fastMode ? { service_tier: "priority" } : {}),
|
|
392
|
-
}),
|
|
393
|
-
})
|
|
394
|
-
} catch {
|
|
395
|
-
if (signal?.aborted) throw abortError()
|
|
396
|
-
if (combinedSignal.aborted) throw timeoutError()
|
|
397
|
-
throw new Error("Image request failed before a response was received")
|
|
398
|
-
}
|
|
399
|
-
// A fetcher may resolve after the deadline or after cancellation; discard that late result.
|
|
400
|
-
if (signal?.aborted || combinedSignal.aborted) {
|
|
401
|
-
await response?.body?.cancel().catch(() => {})
|
|
402
|
-
throwIfSettled(signal, combinedSignal)
|
|
403
|
-
}
|
|
404
|
-
if (!response || typeof response !== "object" || typeof response.ok !== "boolean") {
|
|
405
|
-
throw new Error("Image request failed before a response was received")
|
|
406
|
-
}
|
|
407
|
-
if (!response.ok) throw await httpError(response, { signal, combinedSignal })
|
|
408
|
-
let base64
|
|
409
|
-
try {
|
|
410
|
-
base64 = await readImageResponse(response)
|
|
411
|
-
} catch (error) {
|
|
412
|
-
// Our own messages pass through; every transport/stream failure is normalized.
|
|
413
|
-
if (error instanceof ImageResponseError) throw error
|
|
414
|
-
throwIfSettled(signal, combinedSignal)
|
|
415
|
-
throw new Error("Image response stream failed")
|
|
416
|
-
}
|
|
417
|
-
throwIfSettled(signal, combinedSignal)
|
|
418
|
-
const saved = await savePNG(input.out, directory, base64, combinedSignal)
|
|
419
|
-
return { ...saved, route: route.route, method: route.method, model: config.model }
|
|
420
|
-
}
|