@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/README.md +79 -239
- package/codex.js +167 -0
- package/errors.js +24 -0
- package/google.js +79 -0
- package/images.js +235 -0
- package/index.js +100 -56
- package/package.json +15 -10
- package/parameters.js +151 -0
- package/routing.js +46 -0
- package/CHANGELOG.md +0 -21
- package/VALIDATION.md +0 -50
- package/core.mjs +0 -561
package/README.md
CHANGED
|
@@ -1,280 +1,120 @@
|
|
|
1
|
-
# opencode-
|
|
1
|
+
# opencode-auto-imagegen
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
[](https://www.npmjs.com/package/@myoldtime/opencode-codex-imagegen)
|
|
5
|
-
[](https://github.com/MyOldTime/opencode-codex-imagegen/releases)
|
|
6
|
-
[](LICENSE)
|
|
7
|
-
|
|
8
|
-
OpenCode V2 插件,注册 `proxy_imagegen` 工具,支持文生图和参考图编辑。默认走 **OpenAI Responses API 的托管 `image_generation` 工具**(不使用 Images API);也可配置为 **Google Gemini Interactions API(Nano Banana)**,见 [Google Gemini 配置](#google-gemini-配置)。
|
|
9
|
-
|
|
10
|
-
OpenAI 模式下有两种凭据来源,优先级固定:
|
|
11
|
-
|
|
12
|
-
1. **显式配置**:同时提供 `options.base_url` 与 `options.key` 时,只走你自己的代理,**完全不读取宿主的任何凭据**。只提供 `key` 时默认使用 `https://api.openai.com/v1`。
|
|
13
|
-
2. **宿主托管**:两者都不配置时,每次调用通过 `ctx.integration.connection.active('openai')` + `resolve(connection)` 取得 OpenCode 已登录的 OpenAI 凭据,由 OpenCode 负责刷新,插件不读取、不写入任何凭据文件。
|
|
14
|
-
|
|
15
|
-
> 仓库内置测试默认全部离线(注入 fake fetch / fake integration),不会消耗生图额度。真实账号验证与自动化协议测试分开记录,详见 [验证记录](VALIDATION.md)。新版 **Sign in with ChatGPT** 在实测中被上游以 `subscription_sharing_unsupported_capability` 拒绝生图;能识别该登录方式不等于它可用,请使用显式 API 或可用的 legacy 登录。
|
|
16
|
-
|
|
17
|
-
## 名称对照
|
|
18
|
-
|
|
19
|
-
| 项 | 值 |
|
|
20
|
-
|---|---|
|
|
21
|
-
| 项目 / GitHub 仓库 | `opencode-codex-imagegen`([`MyOldTime/opencode-codex-imagegen`](https://github.com/MyOldTime/opencode-codex-imagegen)) |
|
|
22
|
-
| npm 包名(npmjs 与 GitHub Packages 使用同一个 scoped name) | `@myoldtime/opencode-codex-imagegen` |
|
|
23
|
-
| 插件 ID | `opencode-codex-imagegen` |
|
|
24
|
-
| 工具名 | `proxy_imagegen` |
|
|
25
|
-
| 版本 / 许可证 | `0.2.0` / MIT |
|
|
3
|
+
一个 OpenCode V2 后台生图工具 `auto_imagegen`,按 **Codex → OpenRouter → AIHubMix → Google Gemini** 的顺序选择有凭据且支持本次参数的服务。前台拿到本地任务 ID 后可继续对话,完成时原会话收到实际服务商、切换原因及保存路径。
|
|
26
4
|
|
|
27
5
|
## 安装
|
|
28
6
|
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
### 方式一:从 npmjs.org 安装(推荐)
|
|
32
|
-
|
|
33
|
-
npmjs.org 上的公开包安装不需要登录 npm,也不需要提供 token。
|
|
34
|
-
|
|
35
|
-
```powershell
|
|
36
|
-
opencode plugin add "@myoldtime/opencode-codex-imagegen@0.2.0"
|
|
37
|
-
opencode plugin list
|
|
38
|
-
```
|
|
39
|
-
|
|
40
|
-
固定版本便于复现,`opencode plugin list` 用于确认已登记。
|
|
41
|
-
|
|
42
|
-
`opencode plugin add` 默认写入全局 OpenCode 配置。若只想在某个项目使用,改用该项目的 `opencode.json`:
|
|
43
|
-
|
|
44
|
-
```json
|
|
45
|
-
{
|
|
46
|
-
"$schema": "https://opencode.ai/config.json",
|
|
47
|
-
"plugins": ["@myoldtime/opencode-codex-imagegen@0.2.0"]
|
|
48
|
-
}
|
|
49
|
-
```
|
|
50
|
-
|
|
51
|
-
安装或修改配置后,可在 OpenCode TUI 输入 `/reload` 重新加载;这是界面内的斜杠命令,不是操作系统 shell 命令。
|
|
52
|
-
|
|
53
|
-
### 方式二:从 GitHub 标签安装
|
|
54
|
-
|
|
55
|
-
```powershell
|
|
56
|
-
opencode plugin add "github:MyOldTime/opencode-codex-imagegen#v0.2.0"
|
|
57
|
-
opencode plugin list
|
|
58
|
-
```
|
|
59
|
-
|
|
60
|
-
公共仓库通过该方式安装不需要 GitHub Packages token,也不经过 npm registry。仅对某个项目生效时,项目 `opencode.json` 的 `plugins` 条目可写成同一来源 `github:MyOldTime/opencode-codex-imagegen#v0.2.0`。`#v0.2.0` 指向该标签当前对应的提交,标签由仓库维护者控制,需要时请自行核对。
|
|
61
|
-
|
|
62
|
-
### 方式三:从 GitHub Packages 安装
|
|
63
|
-
|
|
64
|
-
GitHub Packages 与本包在 npmjs.org 的同名包属于两个独立 registry,同一版本需要分别发布。按 GitHub 的规则,即使包是公有的,安装也需要具有 `read:packages` 权限的 personal access token (classic)。
|
|
7
|
+
在 OpenCode V2 中安装 [npm 包](https://www.npmjs.com/package/@myoldtime/opencode-codex-imagegen):
|
|
65
8
|
|
|
66
9
|
```sh
|
|
67
|
-
|
|
68
|
-
npm login --scope=@myoldtime --auth-type=legacy --registry=https://npm.pkg.github.com
|
|
69
|
-
# Username 输入 GitHub 用户名,Password 输入 token
|
|
70
|
-
opencode plugin add "@myoldtime/opencode-codex-imagegen@0.2.0"
|
|
10
|
+
opencode plugin add "@myoldtime/opencode-codex-imagegen@1.0.0"
|
|
71
11
|
opencode plugin list
|
|
72
12
|
```
|
|
73
13
|
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
```sh
|
|
77
|
-
npm config set @myoldtime:registry https://registry.npmjs.org --location=user
|
|
78
|
-
```
|
|
79
|
-
|
|
80
|
-
### 本地开发安装
|
|
81
|
-
|
|
82
|
-
```sh
|
|
83
|
-
git clone https://github.com/MyOldTime/opencode-codex-imagegen.git
|
|
84
|
-
cd opencode-codex-imagegen
|
|
85
|
-
npm ci --ignore-scripts
|
|
86
|
-
```
|
|
87
|
-
|
|
88
|
-
在 OpenCode 配置中把 `package` 指向这个目录的**绝对路径**,例如 Unix 风格 `/path/to/opencode-codex-imagegen`,Windows 的 JSON 中可写成 `C:/path/to/opencode-codex-imagegen`。必须指向目录,不能指向单个文件;插件本身无需编译。
|
|
14
|
+
也可从 [GitHub 仓库](https://github.com/MyOldTime/opencode-codex-imagegen) 的 `v1.0.0` 标签加载源码:在插件目录运行 `npm ci --ignore-scripts`,将下方 `package` 改为该目录的绝对路径。
|
|
89
15
|
|
|
90
16
|
## 配置
|
|
91
17
|
|
|
92
|
-
|
|
18
|
+
在项目或全局 `opencode.jsonc` 的 `plugins` 中配置插件;已安装时直接编辑同一条目。**只需一家可用凭据**,示例中不使用的服务段可以省略。Codex 可以复用 OpenCode 已连接的 OpenAI 账号,也可以使用独立 key;其余服务使用各自的 key。没有可用凭据时不创建后台任务。
|
|
19
|
+
|
|
20
|
+
```jsonc
|
|
93
21
|
{
|
|
94
22
|
"$schema": "https://opencode.ai/config.json",
|
|
95
23
|
"plugins": [
|
|
96
24
|
{
|
|
97
|
-
"package": "@myoldtime/opencode-codex-imagegen@0.
|
|
25
|
+
"package": "@myoldtime/opencode-codex-imagegen@1.0.0",
|
|
98
26
|
"options": {
|
|
99
|
-
"
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
27
|
+
"codex": {
|
|
28
|
+
"disabled": false,
|
|
29
|
+
"model": "gpt-6.2-sol" // 对话模型 ID;不填 key 和 base_url 时使用 OpenCode 的 OpenAI 登录
|
|
30
|
+
},
|
|
31
|
+
"openrouter": {
|
|
32
|
+
"disabled": false,
|
|
33
|
+
"base_url": "https://openrouter.ai/api/v1",
|
|
34
|
+
"key": "{env:OPENROUTER_API_KEY}",
|
|
35
|
+
"model": "openai/gpt-image-2.5-sunburst" // 可选:填写 OpenRouter 上的生图模型 ID
|
|
36
|
+
},
|
|
37
|
+
"aihubmix": {
|
|
38
|
+
"disabled": false,
|
|
39
|
+
"base_url": "https://aihubmix.com/ai/v1",
|
|
40
|
+
"key": "{env:AIHUBMIX_API_KEY}",
|
|
41
|
+
"model": "gpt-image-2.5-sunburst" // 可选:填写 AIHubMix 上的生图模型 ID
|
|
42
|
+
},
|
|
43
|
+
"google": {
|
|
44
|
+
"disabled": false,
|
|
45
|
+
"base_url": "https://generativelanguage.googleapis.com",
|
|
46
|
+
"key": "{env:GEMINI_API_KEY}",
|
|
47
|
+
"model": "gemini-nano-banana-2.1"
|
|
48
|
+
}
|
|
103
49
|
}
|
|
104
50
|
}
|
|
105
51
|
]
|
|
106
52
|
}
|
|
107
53
|
```
|
|
108
54
|
|
|
109
|
-
|
|
55
|
+
每个服务的 `disabled` 都是可选布尔值,默认 `false`。设为 `true` 后,该服务完全不参与首选或容错,不需要删除 key,也不会读取它的环境密钥或宿主登录。其余服务保持原有顺序;若全部禁用,工具会直接提示,不提交任务。
|
|
110
56
|
|
|
111
|
-
|
|
112
|
-
|---|---|---|
|
|
113
|
-
| `provider` | `openai` | `openai` 或 `google`,每个插件配置只选择一个后端。 |
|
|
114
|
-
| `base_url` | 对应服务的官方地址(未配 OpenAI key 时走宿主账号) | 可选代理地址。OpenAI 可写到 `/v1`,自动补 `/responses`;Google 可写代理域名或 API 路径,见下方示例。**必须同时给 `key`**。 |
|
|
115
|
-
| `key` | 无 | OpenAI:Bearer key,可省略以使用宿主账号。Google:必填 Gemini API key,建议写 `{env:GEMINI_API_KEY}`。 |
|
|
116
|
-
| `model` | OpenAI:`gpt-6.1-sol`;Google:`gemini-nano-banana-2.1` | OpenAI 对话模型或 Google 图片模型。 |
|
|
117
|
-
| `reasoning_effort` | 不下发 | 仅 OpenAI:`none` / `minimal` / `low` / `medium` / `high` / `xhigh`,模型支持情况各异。 |
|
|
118
|
-
| `fast_mode` | `false` | 仅 OpenAI:`true` 时下发 `service_tier: "priority"`。 |
|
|
119
|
-
| `timeout_ms` | `240000` | 单次请求超时(毫秒)。 |
|
|
57
|
+
`model` 的含义按服务区分:
|
|
120
58
|
|
|
121
|
-
|
|
59
|
+
- **`codex.model` 是对话模型**,省略时默认 `gpt-6.2-sol`。它作为 Responses 请求的顶层 `model`,由 `tool_choice: {"type":"image_generation"}` 指定调用托管生图工具。实际生图模型由后端选择。`size` 和 `quality` 传给工具,不作为对话模型的配置。
|
|
60
|
+
- **`openrouter.model` 和 `aihubmix.model` 是生图模型**,默认分别是 `openai/gpt-image-2.5-sunburst` 和 `gpt-image-2.5-sunburst`。切换时使用目标服务自己的模型,不会带入 Codex 对话模型 ID。
|
|
61
|
+
- **`google.model` 是支持图片输出的 Gemini 模型**,默认 `gemini-nano-banana-2.1`。
|
|
122
62
|
|
|
123
|
-
|
|
124
|
-
- 只给 `base_url` 不给 `key` → 报错,提示两者都配或都不配。
|
|
125
|
-
- 只给有效的 `key` → 默认使用 `https://api.openai.com/v1`。
|
|
126
|
-
- `base_url` 含用户名密码、查询串、片段或非 HTTP(S) → 报错。
|
|
127
|
-
- 两项都完全省略 → 走宿主托管凭据;宿主没有可用 OpenAI 连接时给出明确错误,不会退回到猜测的 endpoint。
|
|
63
|
+
**Codex 的凭据**:省略 `codex` 整段或只填写 `codex.model` 时,插件通过宿主查询当前 OpenAI 连接。支持宿主管理的 API key、Sign in with ChatGPT 和 legacy Codex 登录;账号不具备生图能力时进入容错流程。要用显式 API key 或 Responses 代理,可以改成:
|
|
128
64
|
|
|
129
|
-
|
|
65
|
+
```jsonc
|
|
66
|
+
"codex": {
|
|
67
|
+
"base_url": "https://api.openai.com/v1", // 可换成支持 Responses 托管生图工具的代理
|
|
68
|
+
"key": "{env:OPENAI_API_KEY}",
|
|
69
|
+
"model": "gpt-6.2-sol"
|
|
70
|
+
}
|
|
71
|
+
```
|
|
130
72
|
|
|
131
|
-
|
|
73
|
+
显式 Codex key 不读取宿主凭据,只给 key 时使用官方 `/v1/responses`。配置代理地址却没给 key 时跳过 Codex,不会向代理发送宿主 token。若已登录但想跳过 Codex,写 `"codex": {"disabled": true}`。Codex 另支持可选的 `reasoning_effort` 和 `fast_mode`。
|
|
132
74
|
|
|
133
|
-
|
|
75
|
+
OpenRouter、AIHubMix 和 Google 使用官方地址时,省略服务配置也可读取 OpenCode 服务进程中对应的环境变量;显式填写空字符串或纯空白 `key` 则不启用该服务。使用代理时须显式指定 `key`。
|
|
134
76
|
|
|
135
|
-
|
|
136
|
-
{
|
|
137
|
-
"$schema": "https://opencode.ai/config.json",
|
|
138
|
-
"plugins": [
|
|
139
|
-
{
|
|
140
|
-
"package": "@myoldtime/opencode-codex-imagegen@0.2.0",
|
|
141
|
-
"options": {
|
|
142
|
-
"provider": "google",
|
|
143
|
-
"key": "{env:GEMINI_API_KEY}"
|
|
144
|
-
}
|
|
145
|
-
}
|
|
146
|
-
]
|
|
147
|
-
}
|
|
148
|
-
```
|
|
77
|
+
AIHubMix 默认接口需要在[控制台开启异步任务](https://console.aihubmix.com/async-tasks)。也可填 `https://aihubmix.com/v1` 使用兼容端点(文生图及单图编辑)。两种接口都不会阻塞前台。
|
|
149
78
|
|
|
150
|
-
|
|
79
|
+
### Google Gemini
|
|
151
80
|
|
|
152
|
-
|
|
153
|
-
- **图生图**:通过 `images` 传入一张或多张本地参考图。例如:`用 proxy_imagegen 参考 snow.png 和 cabin.jpg,把木屋放进雪景里,保存为 winter.jpg`。插件会将参考图按顺序发送给 Google。
|
|
81
|
+
使用官方接口时,只要 OpenCode 服务进程中有 `GEMINI_API_KEY`,就可以省略整个 `google` 配置。只有 Google 有凭据时,普通文生图和参考图编辑会直接使用 Google。要通过代理调用,设置 `google.base_url` 和 `google.key`;例如 `https://proxy.example/gemini` 会请求 `/gemini/v1beta/interactions`,也可以直接填完整的 Interactions 端点。代理需支持 [Gemini Interactions REST](https://aistudio.google.com/api-reference/interactions-api/create-interaction) 的 JSON 协议,并转发 `x-goog-api-key` 和 `Api-Revision` 请求头。
|
|
154
82
|
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
#### Google 自定义代理地址
|
|
158
|
-
|
|
159
|
-
要经由反向代理请求 Gemini,在同一个 `options` 中加入 `"base_url": "https://proxy.example.com"`:
|
|
160
|
-
|
|
161
|
-
| `base_url` | 实际请求地址 |
|
|
162
|
-
|---|---|
|
|
163
|
-
| 省略 | `https://generativelanguage.googleapis.com/v1beta/interactions` |
|
|
164
|
-
| `https://proxy.example.com` | `https://proxy.example.com/v1beta/interactions` |
|
|
165
|
-
| `https://proxy.example.com/gemini` | `https://proxy.example.com/gemini/v1beta/interactions` |
|
|
166
|
-
| `https://proxy.example.com/gemini/v1beta` | `https://proxy.example.com/gemini/v1beta/interactions` |
|
|
167
|
-
| `https://proxy.example.com/gemini/v1/interactions` | `https://proxy.example.com/gemini/v1/interactions` |
|
|
168
|
-
|
|
169
|
-
代理需要原样转发 Gemini Interactions POST 请求及 `x-goog-api-key`、`Api-Revision` 请求头。这不是用于配置 HTTP CONNECT 或 SOCKS 的选项,不会把协议改成 `generateContent` 或 OpenAI 兼容格式。代理出错不会回退到官方地址。远程代理请使用可信的 HTTPS 地址,因为代理会收到 API Key、提示词和参考图。
|
|
170
|
-
|
|
171
|
-
## OpenAI 的三种登录方法
|
|
172
|
-
|
|
173
|
-
宿主托管模式下,凭据来自 OpenCode 的 `openai` integration。插件只接受以下三种方法,遇到未知 `methodID` 直接报错:
|
|
174
|
-
|
|
175
|
-
| 方法 label | `methodID` | 请求地址 | 附加请求头 |
|
|
176
|
-
|---|---|---|---|
|
|
177
|
-
| Sign in with ChatGPT | `chatgpt-token-sharing` | `https://api.openai.com/v1/responses` | `session-id`、`thread-id`、`x-client-request-id` |
|
|
178
|
-
| Codex browser (legacy) | `chatgpt-browser` | `https://chatgpt.com/backend-api/codex/responses` | `originator: opencode`、`session-id`、可选 `ChatGPT-Account-Id` |
|
|
179
|
-
| Codex device code (legacy) | `chatgpt-headless` | `https://chatgpt.com/backend-api/codex/responses` | 同上 |
|
|
180
|
-
|
|
181
|
-
说明:
|
|
182
|
-
|
|
183
|
-
- 两种 legacy 方法的 `metadata.accountID` 会作为 `ChatGPT-Account-Id` 发送;新方法不发送该头。
|
|
184
|
-
- `type: "key"` 的宿主连接按官方 API key 处理,走 `https://api.openai.com/v1/responses`。
|
|
185
|
-
- `chatgpt-token-sharing` 使用官方 `/v1/responses`。真实账号测试返回 HTTP 400 / `subscription_sharing_unsupported_capability`,因此**不承诺此方式可以生图**。插件不会把其 Token 发送到 legacy Codex 地址,也不会擅自切换其他已存账号;应使用 API 配置或在 OpenCode 中选择可用的 legacy 登录。
|
|
186
|
-
- 三种方法共用同一套请求体(`stream: true`、`store: false`、`tools: [{ type: "image_generation", ... }]`、`tool_choice`、`instructions`),差异仅在 endpoint 与少量请求头。
|
|
187
|
-
- 兼容普通 Responses JSON,以及带或不带 `Content-Type: text/event-stream` 的 SSE(部分 Codex 网关会省略该响应头)。
|
|
188
|
-
|
|
189
|
-
## 安全与隐私
|
|
190
|
-
|
|
191
|
-
- **不读取也不写入任何凭据文件**(包括 `auth.json`),不缓存 token,不遍历或切换账号。OpenAI 宿主托管模式每次调用都重新 `active` + `resolve`,刷新完全交给 OpenCode。
|
|
192
|
-
- 显式 `base_url` + `key` 模式不会访问 integration API,key 只发送到 `base_url` 指向的地址。
|
|
193
|
-
- Google 模式的 key 只通过请求头发送到所选地址(官方 Gemini API 或配置的代理);提示词和参考图也会发送到该地址。仅提交你有权上传的内容。
|
|
194
|
-
- 失败时**不重试、不换通道**(401/403/超时/能力受限都一样),避免重复计费。
|
|
195
|
-
- 超时或取消后,即便上游晚到并返回了合法 PNG,也会在落盘前丢弃;流读取过程中的网络错误同样归一为固定文案。
|
|
196
|
-
- 错误信息只包含 HTTP 状态码和固定白名单错误码;不会输出上游响应正文、token、账号或任意自定义 `error.code`。网络层异常也统一归一为固定文案。
|
|
197
|
-
- 调用前先经过宿主的 permission 机制:读引用图 → `read`,写图片 → `edit`;被宿主拒绝则不读文件、不发请求。
|
|
198
|
-
- 信号已取消(或在解析凭据期间被取消)时不发网络请求、不落盘;超时同样不落盘。
|
|
199
|
-
- 工具返回的 metadata 仅含 `out`、`versioned`、`bytes`、`route`、`method`、`model`,不含任何凭据或账户信息。
|
|
200
|
-
- OpenAI 只保存 PNG,Google 可保存 PNG 或 JPEG;校验文件内容与扩展名一致,使用独占创建及 `-v2`/`-v3` 后缀,不覆盖已有文件。
|
|
201
|
-
|
|
202
|
-
## 用法
|
|
203
|
-
|
|
204
|
-
> 用 proxy_imagegen 生成一只水彩风格的狐狸,保存为 fox.png
|
|
205
|
-
>
|
|
206
|
-
> 用 proxy_imagegen 参考 fox.png,改成雪景版本,保存为 fox-snow.png
|
|
207
|
-
|
|
208
|
-
参数:
|
|
209
|
-
|
|
210
|
-
| 参数 | 必填 | 说明 |
|
|
211
|
-
|---|---|---|
|
|
212
|
-
| `prompt` | 是 | 图片描述;有参考图时按顺序说明每张图的作用。 |
|
|
213
|
-
| `out` | 是 | 输出路径(相对当前会话目录或绝对路径)。OpenAI 支持 `.png`;Google 支持 `.png` / `.jpg` / `.jpeg`。 |
|
|
214
|
-
| `images` | 否 | 本地参考图路径数组。两者支持 PNG / JPEG / WebP;仅 OpenAI 支持 GIF。 |
|
|
215
|
-
| `quality` | 否 | 仅 OpenAI:`auto` / `low` / `medium` / `high`。 |
|
|
216
|
-
| `size` | 否 | 仅 OpenAI:`auto` 或 `宽x高`(16 的倍数,最长边 ≤ 3840,长宽比 ≤ 3:1,总像素 655360–8294400)。 |
|
|
217
|
-
| `aspect_ratio` | 否 | 仅 Google:宽高比,例如 `1:1`、`16:9` 或 `9:16`,以所选模型支持为准。 |
|
|
218
|
-
| `image_size` | 否 | 仅 Google:`1K` / `2K` / `4K`,以所选模型支持为准。 |
|
|
219
|
-
|
|
220
|
-
尺寸与画质都是"尽力而为",最终由后端决定。
|
|
221
|
-
|
|
222
|
-
## 故障排查
|
|
223
|
-
|
|
224
|
-
| 报错 | 含义与处理 |
|
|
225
|
-
|---|---|
|
|
226
|
-
| `options.base_url requires options.key` | 只配了一半,补齐或两者都删掉改用宿主账号。 |
|
|
227
|
-
| `options.key contains an unresolved environment substitution` | `{env:...}` 没解析:把变量加入 OpenCode 的环境配置并重新加载该配置(或新开一个会话使其生效),或删掉 `key`。 |
|
|
228
|
-
| `OpenCode did not expose an OpenAI connection to this plugin` | 当前 OpenCode 版本没有提供 integration API,请配置 `base_url` + `key`。 |
|
|
229
|
-
| `No OpenAI account is connected in OpenCode` | 去 OpenCode 里完成 Sign in with ChatGPT(或 legacy 方法)。 |
|
|
230
|
-
| `OpenCode could not provide a usable OpenAI credential` | 登录可能已过期或需要重新授权。 |
|
|
231
|
-
| `Unsupported OpenAI sign-in method. Supported methods: ...` | 当前 OpenCode 提供了插件未适配的方法;错误只列出受支持的方法,不回显原始方法值,属于版本不匹配,请升级插件。 |
|
|
232
|
-
| `The OpenAI access token has expired and could not be refreshed` | 刷新失败,重新登录。 |
|
|
233
|
-
| `Image request failed: HTTP 401/403` | 凭据或权限问题;插件不会自动重试。 |
|
|
234
|
-
| `Image request failed: HTTP 400 (subscription_sharing_unsupported_capability)` | 已实测的 Sign in with ChatGPT 结果:上游拒绝该能力。白名单码会原样显示(如 `subscription_sharing_unsupported_capability`、`subscription_sharing_route_not_supported`),表示当前订阅/网关不支持该能力或路由。 |
|
|
235
|
-
| `Image response contained invalid JSON` | 上游返回的 JSON 无法解析。 |
|
|
236
|
-
| `Response ended without an image_generation_call.result` | OpenAI 没有按 Responses 协议返回图片。 |
|
|
237
|
-
| `The Google provider requires a valid options.key` | 检查 OpenCode 能否解析 `{env:GEMINI_API_KEY}`,以及是否使用从 AI Studio 创建的 Gemini API key。 |
|
|
238
|
-
| `Google response contained no generated image` | Gemini 没有返回可保存的图片;确认 `model` 支持图片输出,检查提示词与参考图。 |
|
|
239
|
-
| `Google image MIME type does not match its bytes` | JSON 中的图片 MIME 与内嵌数据不符,未写入文件。 |
|
|
240
|
-
| `Image request timed out` | 超过 `timeout_ms`,未写入文件。 |
|
|
241
|
-
|
|
242
|
-
## 发布流程
|
|
243
|
-
|
|
244
|
-
两个渠道互相独立,都由同一个 `@myoldtime/opencode-codex-imagegen` 包名发布到各自的 registry:
|
|
245
|
-
|
|
246
|
-
| 渠道 | 触发方式 | 说明 |
|
|
247
|
-
|---|---|---|
|
|
248
|
-
| GitHub Packages | 在 GitHub 发布 Release(`published`)后由 Actions 发布 | `.github/workflows/publish.yml` 只发布到 `npm.pkg.github.com`,`NODE_AUTH_TOKEN` 来自 workflow 的 `secrets.GITHUB_TOKEN`,不会使用本机 npm 登录 |
|
|
249
|
-
| npmjs | 在已登录 npmjs 账号的环境执行 `npm run publish:npm` | 只影响 npmjs;本机的 npm 登录不会传入 GitHub Actions,因此 CI 需要自己的凭据来源 |
|
|
250
|
-
|
|
251
|
-
发布前可运行以下只读检查(不会上传任何包):
|
|
252
|
-
|
|
253
|
-
```powershell
|
|
254
|
-
npm whoami --registry=https://registry.npmjs.org # 只读身份确认
|
|
255
|
-
npm view @myoldtime/opencode-codex-imagegen@0.2.0 version --registry=https://registry.npmjs.org --@myoldtime:registry=https://registry.npmjs.org
|
|
256
|
-
npm pack --dry-run --json # 只读打包检查
|
|
257
|
-
```
|
|
83
|
+
例如「用 `auto_imagegen` 参考 `街景.png` 画一张 16:9、2K 的水彩画,保存为 `街景水彩.jpg`」:工具可用 `aspect_ratio: "16:9"` 和 `image_size: "2K"`。显式指定 `image_size`(`1K` / `2K` / `4K`)或 Google 专用画幅(`1:4`、`4:1`、`1:8`、`8:1`)时,前三家会跳过,不会降低要求改用默认尺寸。
|
|
258
84
|
|
|
259
|
-
|
|
85
|
+
Google 支持最多 14 张按顺序传入的 PNG、JPEG 或 WebP 参考图;含提示词和 Base64 图片的整个请求最多 20 MB。输出支持 PNG、JPEG,目标为 PNG 而上游返回 JPEG 时会在本地转码。精确像素 `size`、蒙版、WebP 输出、非自动质量或背景、显式压缩参数均不走 Google。
|
|
260
86
|
|
|
261
|
-
|
|
262
|
-
npm run publish:npm # 上传到 npmjs
|
|
263
|
-
```
|
|
87
|
+
## 切换和会话隔离
|
|
264
88
|
|
|
265
|
-
|
|
89
|
+
| 情况 | 本次 | 同一会话的下一次 |
|
|
90
|
+
| --- | --- | --- |
|
|
91
|
+
| 首选服务成功 | 保存并通知 | 从首个可用服务开始 |
|
|
92
|
+
| 只有一家有凭据 | 直接使用该服务;未配置的服务不参与路由,也不记为失败 | 按调用时的凭据选择服务 |
|
|
93
|
+
| 401、欠费 402、已识别的密钥额度/停用错误 | 标记失效;有已配置的备用服务时切换 | 跳过已确认失效的服务 |
|
|
94
|
+
| 限流 429、临时并发预算不足、5xx、网络异常、无可用图片 | 尚未保存图片时按顺序切到下一家 | 重新从首个可用服务开始 |
|
|
95
|
+
| 已配置服务均不可用 | 发一条失败通知,列出各自原因 | 仅尝试未被标记失效的服务 |
|
|
96
|
+
| 本地权限/文件错误、明确的内容策略拒绝、已有部分图片 | 报告错误或已保存的图片,不另开生成请求 | 不改变服务状态 |
|
|
266
97
|
|
|
267
|
-
|
|
98
|
+
失效标记仅在**当前插件实例的内存中按 `sessionID` 保存**。同一会话跨回合保留(空闲不清除);新会话、分支会话互不继承。归档、删除会话或重载插件会清掉对应标记。没有写入磁盘的路由状态,也不修改全局配置。任务通知仍按 OpenCode 的普通会话历史保留。更新密钥/充值后,开新会话或重载插件即可重新尝试。
|
|
268
99
|
|
|
269
|
-
|
|
270
|
-
npm ci --ignore-scripts
|
|
271
|
-
npm run check # node --check
|
|
272
|
-
npm test # node --test,全部离线:注入 fake fetch / fake integration
|
|
273
|
-
npm pack --dry-run --json
|
|
274
|
-
```
|
|
100
|
+
每个任务按顺序经过每家至多一次;Codex 和 Google 每次生成一张,`n > 1` 时逐张请求并立即保存。Codex 支持 PNG、自动背景、无蒙版,质量 `auto/low/medium/high`;其余需求直接交给后续支持的服务,不标记 Codex 失效。已保存部分图片时不切换去补单。每个服务总时限为 10 分钟。网络中断时远端是否已接单可能无法确认,自动切换有可能导致多个服务产生费用。卸载插件停止本地等待。
|
|
275
101
|
|
|
276
|
-
|
|
102
|
+
## 使用
|
|
103
|
+
|
|
104
|
+
> 用 `auto_imagegen` 画 3 张精细的 9:16 手机壁纸,主题是雨夜花店,第一张保存到 `壁纸.png`。
|
|
105
|
+
|
|
106
|
+
工具可以选择 `quality: "high"`、`n: 3`、`aspect_ratio: "9:16"`。OpenRouter 接收画幅比例;若发生切换,AIHubMix 收到相同提示词、数量、参考图及对应的 `size: "864x1536"`。没有特别要求时默认自动画幅、自动质量、1 张 PNG。输出默认位于会话目录 `images/`,支持指定 `out`,遇到同名文件自动使用新名字。
|
|
107
|
+
|
|
108
|
+
可传 `images`(最多 16 张本地 PNG/JPEG/WebP)、`size` 或 `aspect_ratio`、`n`(1–10)、`quality`、`output_format`、`background`、`output_compression`。带 PNG `mask` 的编辑直接使用支持蒙版的 AIHubMix,不会影响同会话其他请求的优先级。AIHubMix `/v1` 模式不支持多参考图、显式背景或压缩参数;如需这些能力请使用默认 `/ai/v1`。
|
|
109
|
+
|
|
110
|
+
## 验证
|
|
111
|
+
|
|
112
|
+
```sh
|
|
113
|
+
npm run check
|
|
114
|
+
npm test
|
|
115
|
+
npm pack --dry-run
|
|
116
|
+
```
|
|
277
117
|
|
|
278
|
-
|
|
118
|
+
测试模拟四家服务及宿主凭据,覆盖四方切换、会话隔离、部分成功、后台通知、Codex Responses、AIHubMix 异步下载、Gemini Interactions 及图片转码,不消耗真实额度。
|
|
279
119
|
|
|
280
|
-
|
|
120
|
+
协议参考:[OpenRouter Sunburst](https://openrouter.ai/openai/gpt-image-2.5-sunburst?output_modalities=image&view=api) · [AIHubMix Sunburst](https://aihubmix.com/model/gpt-image-2.5-sunburst/llms.txt) · [AIHubMix 端点 Schema](https://aihubmix.com/call/schema/models/gpt-image-2.5-sunburst/endpoints)
|
package/codex.js
ADDED
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
import { ProviderFailure, upstreamError } from "./errors.js"
|
|
2
|
+
|
|
3
|
+
const official = "https://api.openai.com/v1/responses"
|
|
4
|
+
const legacy = "https://chatgpt.com/backend-api/codex/responses"
|
|
5
|
+
const defaultChatModel = "gpt-6.2-sol"
|
|
6
|
+
const legacyMethods = new Set(["chatgpt-browser", "chatgpt-headless"])
|
|
7
|
+
const usableKey = key => typeof key === "string" && key.trim() && !key.trim().startsWith("{env:")
|
|
8
|
+
|
|
9
|
+
// Explicit endpoints must never inherit a credential from the host. For managed
|
|
10
|
+
// connections only check availability here; OpenCode resolves/refreshes at use.
|
|
11
|
+
export async function codexCandidate(settings = {}, integration, sessionDisabled = false) {
|
|
12
|
+
if (settings.disabled === true) return
|
|
13
|
+
if (settings.key !== undefined || settings.base_url !== undefined) {
|
|
14
|
+
return usableKey(settings.key) ? { provider: "codex", settings } : undefined
|
|
15
|
+
}
|
|
16
|
+
if (sessionDisabled) return { provider: "codex", settings }
|
|
17
|
+
if (!integration?.active || !integration?.resolve) return
|
|
18
|
+
let account
|
|
19
|
+
try { account = await integration.active("openai") } catch { return }
|
|
20
|
+
if (account) return { provider: "codex", settings, resolveCredential: () => integration.resolve(account) }
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export function codexUnsupported(params, mask) {
|
|
24
|
+
if (mask || params.output_format !== "png" || params.background !== "auto" || !["auto", "low", "medium", "high"].includes(params.quality))
|
|
25
|
+
return "Codex 通道支持无蒙版、自动背景的 PNG,质量为 auto/low/medium/high;本次参数交给下一家。"
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
async function codexConnection(candidate, sessionID) {
|
|
29
|
+
const { settings, resolveCredential } = candidate
|
|
30
|
+
const headers = { "Content-Type": "application/json", Accept: "text/event-stream" }
|
|
31
|
+
let endpoint = official, access
|
|
32
|
+
if (settings.key !== undefined) {
|
|
33
|
+
let url
|
|
34
|
+
try { url = new URL(settings.base_url ?? official) } catch { throw new ProviderFailure("Codex base_url 无效。") }
|
|
35
|
+
if (!["http:", "https:"].includes(url.protocol) || url.username || url.password || url.hash || url.search)
|
|
36
|
+
throw new ProviderFailure("Codex base_url 必须为不含凭据、查询参数或片段的 HTTP(S) 地址。")
|
|
37
|
+
const prefix = url.pathname.replace(/\/+$/, "")
|
|
38
|
+
url.pathname = prefix.endsWith("/responses") ? prefix : `${prefix}/responses`
|
|
39
|
+
endpoint = url.href
|
|
40
|
+
access = settings.key
|
|
41
|
+
} else {
|
|
42
|
+
let cred
|
|
43
|
+
try { cred = await resolveCredential() } catch { throw new ProviderFailure("OpenCode 无法解析 OpenAI 登录凭据。") }
|
|
44
|
+
if (cred?.type === "key") access = cred.key
|
|
45
|
+
else if (cred?.type === "oauth" && (legacyMethods.has(cred.methodID) || cred.methodID === "chatgpt-token-sharing")) {
|
|
46
|
+
if (typeof cred.expires === "number" && cred.expires <= Date.now()) throw new ProviderFailure("Codex 登录凭据已过期。")
|
|
47
|
+
access = cred.access
|
|
48
|
+
headers["session-id"] = sessionID
|
|
49
|
+
if (legacyMethods.has(cred.methodID)) {
|
|
50
|
+
endpoint = legacy
|
|
51
|
+
headers.originator = "opencode"
|
|
52
|
+
if (typeof cred.metadata?.accountID === "string" && cred.metadata.accountID) headers["ChatGPT-Account-Id"] = cred.metadata.accountID
|
|
53
|
+
} else {
|
|
54
|
+
headers["thread-id"] = sessionID
|
|
55
|
+
headers["x-client-request-id"] = sessionID
|
|
56
|
+
}
|
|
57
|
+
} else throw new ProviderFailure("不支持的 OpenAI 登录方式。")
|
|
58
|
+
}
|
|
59
|
+
if (!usableKey(access) || /[^\x21-\x7e]/.test(access.trim())) throw new ProviderFailure("Codex 凭据无效。", { disable: true })
|
|
60
|
+
return { endpoint, headers: { ...headers, Authorization: `Bearer ${access.trim()}` } }
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function failure(status, error) {
|
|
64
|
+
if (["subscription_sharing_unsupported_capability", "subscription_sharing_route_not_supported",
|
|
65
|
+
"subscription_sharing_user_not_eligible", "subscription_sharing_usage_limit_exceeded",
|
|
66
|
+
"chatpass_v2_scope_not_authorized"].includes(error?.code))
|
|
67
|
+
return new ProviderFailure(`Codex 账号不可用(${error.code})。`, { disable: true })
|
|
68
|
+
return upstreamError(status, error)
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function result(event) {
|
|
72
|
+
const response = event?.response ?? event
|
|
73
|
+
if (event?.type === "error" || response?.error || ["failed", "incomplete", "cancelled"].includes(response?.status) ||
|
|
74
|
+
["response.failed", "response.incomplete"].includes(event?.type)) {
|
|
75
|
+
const error = response?.error ?? (response?.incomplete_details ? { code: response.incomplete_details.reason } : event)
|
|
76
|
+
throw failure(Number(error?.status) || 200, error)
|
|
77
|
+
}
|
|
78
|
+
const items = event?.type === "response.output_item.done" ? [event.item] : response?.output
|
|
79
|
+
if (event?.type?.startsWith("response.refusal.") || (Array.isArray(items) && items.some(i => i?.content?.some?.(c => c?.type === "refusal"))))
|
|
80
|
+
throw new ProviderFailure("Codex 拒绝了本次请求。", { fallback: false })
|
|
81
|
+
if (Array.isArray(items)) return items.find(i => i?.type === "image_generation_call" && typeof i.result === "string" && i.result)?.result
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
// Some Codex gateways omit Content-Type. Accept both full Responses JSON and
|
|
85
|
+
// SSE, dispatching complete frames (not individual TCP chunks or partial images).
|
|
86
|
+
async function imageResult(response) {
|
|
87
|
+
if (!response.body) throw new ProviderFailure("Codex 返回空响应。")
|
|
88
|
+
const ct = response.headers.get("content-type") ?? ""
|
|
89
|
+
let mode = ct.includes("text/event-stream") ? "sse" : ct.includes("application/json") ? "json" : null
|
|
90
|
+
let pending = "", data = []
|
|
91
|
+
const reader = response.body.getReader(), decoder = new TextDecoder()
|
|
92
|
+
function line(value) {
|
|
93
|
+
if (!value) {
|
|
94
|
+
const text = data.join("\n")
|
|
95
|
+
data = []
|
|
96
|
+
if (text && text !== "[DONE]") return result(JSON.parse(text))
|
|
97
|
+
} else if (value.startsWith("data:")) data.push(value.slice(5).replace(/^ /, ""))
|
|
98
|
+
}
|
|
99
|
+
try {
|
|
100
|
+
for (;;) {
|
|
101
|
+
const { value, done } = await reader.read()
|
|
102
|
+
pending += done ? decoder.decode() : decoder.decode(value, { stream: true })
|
|
103
|
+
if (!mode) {
|
|
104
|
+
const prefix = pending.trimStart()
|
|
105
|
+
if (prefix.startsWith("{") || prefix.startsWith("[")) mode = "json"
|
|
106
|
+
else if (/^(?:(?:data|event|id|retry)(?::|\r?\n)|:)/.test(prefix)) { mode = "sse"; pending = prefix }
|
|
107
|
+
else if (done || pending.length > 65536 || prefix.includes("\n")) break
|
|
108
|
+
else continue
|
|
109
|
+
}
|
|
110
|
+
if (mode === "json") {
|
|
111
|
+
if (!done) continue
|
|
112
|
+
const image = result(JSON.parse(pending))
|
|
113
|
+
if (image) return image
|
|
114
|
+
break
|
|
115
|
+
}
|
|
116
|
+
let i
|
|
117
|
+
while ((i = pending.indexOf("\n")) >= 0) {
|
|
118
|
+
const image = line(pending.slice(0, i).replace(/\r$/, ""))
|
|
119
|
+
pending = pending.slice(i + 1)
|
|
120
|
+
if (image) return image
|
|
121
|
+
}
|
|
122
|
+
if (done) {
|
|
123
|
+
const image = (pending && line(pending.replace(/\r$/, ""))) || line("")
|
|
124
|
+
if (image) return image
|
|
125
|
+
break
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
} finally {
|
|
129
|
+
await reader.cancel().catch(() => {})
|
|
130
|
+
reader.releaseLock()
|
|
131
|
+
}
|
|
132
|
+
throw new ProviderFailure("Codex 响应中没有 image_generation_call.result。")
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
// One hosted tool call produces one image. Yield each result before requesting
|
|
136
|
+
// the next, so a later failure cannot cause the paid batch to be regenerated.
|
|
137
|
+
export async function* codexOutputs({ candidate, sessionID, params, refs, signal }) {
|
|
138
|
+
const { settings } = candidate
|
|
139
|
+
const model = settings.model === undefined ? defaultChatModel : settings.model
|
|
140
|
+
if (typeof model !== "string" || !model.trim()) throw new ProviderFailure("codex.model 必须是非空对话模型 ID。")
|
|
141
|
+
const { endpoint, headers } = await codexConnection(candidate, sessionID)
|
|
142
|
+
const content = [{ type: "input_text", text: params.prompt }, ...refs.map(ref => ({
|
|
143
|
+
type: "input_image", image_url: `data:image/${ref.type};base64,${ref.bytes.toString("base64")}`,
|
|
144
|
+
}))]
|
|
145
|
+
const body = JSON.stringify({
|
|
146
|
+
model: model.trim(), instructions: "Generate the requested image by invoking image_generation exactly once. Do not respond with text only.",
|
|
147
|
+
input: [{ role: "user", content }],
|
|
148
|
+
tools: [{ type: "image_generation", output_format: "png", quality: params.quality, size: params.size }],
|
|
149
|
+
tool_choice: { type: "image_generation" }, stream: true, store: false,
|
|
150
|
+
...(settings.reasoning_effort !== undefined && { reasoning: { effort: settings.reasoning_effort } }),
|
|
151
|
+
...(settings.fast_mode && { service_tier: "priority" }),
|
|
152
|
+
})
|
|
153
|
+
for (let i = 0; i < params.n; i++) {
|
|
154
|
+
let base64
|
|
155
|
+
try {
|
|
156
|
+
signal.throwIfAborted()
|
|
157
|
+
const res = await fetch(endpoint, { method: "POST", body, headers, redirect: "error", signal })
|
|
158
|
+
if (!res.ok) throw failure(res.status, (await res.json().catch(() => null))?.error)
|
|
159
|
+
base64 = await imageResult(res)
|
|
160
|
+
} catch (error) {
|
|
161
|
+
if (error instanceof ProviderFailure) throw error
|
|
162
|
+
throw new ProviderFailure(signal.aborted ? "Codex 请求超时或已中止。" : "Codex 请求或响应流异常。")
|
|
163
|
+
}
|
|
164
|
+
if (!/^[A-Za-z0-9+/]+={0,2}$/.test(base64) || base64.length % 4) throw new ProviderFailure("Codex 返回无效的图片数据。")
|
|
165
|
+
yield { b64_json: base64 }
|
|
166
|
+
}
|
|
167
|
+
}
|
package/errors.js
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
// Only provider-side failures are eligible for routing. Filesystem and permission
|
|
2
|
+
// errors are deliberately not reclassified as provider failures.
|
|
3
|
+
export class ProviderFailure extends Error {
|
|
4
|
+
constructor(message, { disable = false, fallback = true } = {}) {
|
|
5
|
+
super(message)
|
|
6
|
+
this.disable = disable
|
|
7
|
+
this.fallback = fallback
|
|
8
|
+
}
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export function upstreamError(status, error = {}, submission = true) {
|
|
12
|
+
const code = String(error?.code ?? "").toLowerCase()
|
|
13
|
+
const source = error?.metadata?.limit_source
|
|
14
|
+
const policy = status === 422 || /moderation|content[_ -]?(policy|filter)|safety|output_blocked|policy_violation/i.test(`${code} ${String(error?.message ?? "")}`)
|
|
15
|
+
const temporary = source === "openrouter_in_flight_budget" || ["rate_limited", "upstream_rate_limited"].includes(code)
|
|
16
|
+
const keyBlocked = status === 403 && /(?:key|account).{0,24}(?:disabled|suspended|spend(?:ing)? limit)|spend(?:ing)? limit.{0,16}reached/i.test(String(error?.message ?? ""))
|
|
17
|
+
const account = status === 401 || status === 402 || keyBlocked || source === "openrouter_key_limit" ||
|
|
18
|
+
["invalid_api_key", "authentication_failed", "insufficient_quota", "insufficient_user_quota", "async_not_enabled", "key_disabled"].includes(code)
|
|
19
|
+
const disable = submission && account && !temporary && !policy
|
|
20
|
+
const hint = policy ? "内容或策略限制" : temporary || status === 429 ? "临时限流或预算限制" :
|
|
21
|
+
code === "async_not_enabled" ? "账户未启用 AIHubMix 异步任务" :
|
|
22
|
+
status === 401 ? "密钥无效" : status === 402 ? "额度不足" : status === 403 ? "访问受限" : "上游请求失败"
|
|
23
|
+
return new ProviderFailure(`HTTP ${status}(${hint})`, { disable, fallback: !policy })
|
|
24
|
+
}
|
package/google.js
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import { ProviderFailure, upstreamError } from "./errors.js"
|
|
2
|
+
|
|
3
|
+
export const googleRatios = ["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"]
|
|
4
|
+
const inlineLimit = 20_000_000
|
|
5
|
+
|
|
6
|
+
export function googleUnsupported({ params, aspect }, { refs, mask }) {
|
|
7
|
+
if (refs.length > 14) return "Google 最多支持 14 张参考图。"
|
|
8
|
+
if (!aspect || (aspect !== "auto" && !googleRatios.includes(aspect))) return "Google 不支持指定的精确像素尺寸或画幅。"
|
|
9
|
+
if (mask || params.quality !== "auto" || params.background !== "auto" || params.output_compression !== undefined || params.output_format === "webp")
|
|
10
|
+
return "Google 支持无蒙版的 PNG/JPEG 输出,不支持显式质量、背景或压缩参数。"
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
function interactionBody({ config, params, refs, aspect, imageSize }) {
|
|
14
|
+
const limitError = "Google 内联请求不能超过 20 MB,请缩小参考图。"
|
|
15
|
+
const encodedLength = refs.reduce((total, ref) => total + 4 * Math.ceil(ref.bytes.length / 3), 0)
|
|
16
|
+
if (encodedLength > inlineLimit) throw new ProviderFailure(limitError)
|
|
17
|
+
const format = {
|
|
18
|
+
...(aspect !== "auto" && { aspect_ratio: aspect }),
|
|
19
|
+
...(imageSize && { image_size: imageSize }),
|
|
20
|
+
...(params.output_format === "jpeg" && { mime_type: "image/jpeg" }),
|
|
21
|
+
}
|
|
22
|
+
const body = JSON.stringify({
|
|
23
|
+
model: config.model,
|
|
24
|
+
input: [{ type: "text", text: params.prompt }, ...refs.map(ref => ({
|
|
25
|
+
type: "image", mime_type: `image/${ref.type}`, data: ref.bytes.toString("base64"),
|
|
26
|
+
}))],
|
|
27
|
+
...(Object.keys(format).length && { response_format: { type: "image", ...format } }),
|
|
28
|
+
})
|
|
29
|
+
if (Buffer.byteLength(body) > inlineLimit) throw new ProviderFailure(limitError)
|
|
30
|
+
return body
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function googleFailure(status, error) {
|
|
34
|
+
const invalidKey = Array.isArray(error?.details) && error.details.some(item => item?.reason === "API_KEY_INVALID")
|
|
35
|
+
if (invalidKey || /API key not valid/i.test(error?.message ?? ""))
|
|
36
|
+
return new ProviderFailure("Google API key 无效。", { disable: true })
|
|
37
|
+
return upstreamError(status, { code: error?.status ?? error?.code, message: error?.message })
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export async function* googleOutputs(job) {
|
|
41
|
+
const { config, params, signal } = job
|
|
42
|
+
const body = interactionBody(job)
|
|
43
|
+
const headers = { "x-goog-api-key": config.key, "Content-Type": "application/json", "Api-Revision": "2026-05-20" }
|
|
44
|
+
for (let i = 0; i < params.n; i++) {
|
|
45
|
+
let response, payload
|
|
46
|
+
try {
|
|
47
|
+
signal.throwIfAborted()
|
|
48
|
+
response = await fetch(config.endpoint, { method: "POST", headers, body, signal, redirect: "error" })
|
|
49
|
+
payload = await response.json().catch(() => null)
|
|
50
|
+
} catch {
|
|
51
|
+
throw new ProviderFailure("Google 请求超时、中止或网络异常。")
|
|
52
|
+
}
|
|
53
|
+
if (!response.ok || payload?.error) {
|
|
54
|
+
const status = response.ok && Number.isInteger(payload?.error?.code) ? payload.error.code : response.status
|
|
55
|
+
throw googleFailure(status, payload?.error)
|
|
56
|
+
}
|
|
57
|
+
if (payload?.status !== "completed") throw new ProviderFailure("Google 图像交互未完成。")
|
|
58
|
+
let image
|
|
59
|
+
for (const step of Array.isArray(payload.steps) ? payload.steps : []) {
|
|
60
|
+
if (step?.type !== "model_output" || !Array.isArray(step.content)) continue
|
|
61
|
+
for (const part of step.content) {
|
|
62
|
+
if (part?.type === "image" && typeof part.data === "string" && part.data) image = part
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
if (!image) throw new ProviderFailure("Google model_output 未返回图片。")
|
|
66
|
+
if (image.data.length % 4 || !/^[A-Za-z0-9+/]+={0,2}$/.test(image.data)) throw new ProviderFailure("Google 返回无效的图片数据。")
|
|
67
|
+
yield { b64_json: image.data, mime_type: image.mime_type }
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
// Gemini may return JPEG even for the default (PNG) request.
|
|
72
|
+
export async function jpegToPNG(bytes) {
|
|
73
|
+
const [{ default: jpeg }, { PNG }] = await Promise.all([import("jpeg-js"), import("pngjs")])
|
|
74
|
+
try {
|
|
75
|
+
return PNG.sync.write(jpeg.decode(bytes, { maxResolutionInMP: 20, maxMemoryUsageInMB: 384, tolerantDecoding: false }))
|
|
76
|
+
} catch {
|
|
77
|
+
throw new ProviderFailure("Google 返回的 JPEG 无法转为 PNG。")
|
|
78
|
+
}
|
|
79
|
+
}
|