@myoldtime/opencode-codex-imagegen 0.1.0 → 0.2.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/CHANGELOG.md +6 -0
- package/README.md +78 -28
- package/VALIDATION.md +12 -4
- package/core.mjs +172 -31
- package/index.js +19 -9
- package/package.json +7 -3
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,11 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.2.0
|
|
4
|
+
|
|
5
|
+
- `proxy_imagegen` 可通过 `options.provider: "google"` 调用 Google Gemini Interactions API,实现文生图和多参考图编辑,默认使用 `gemini-nano-banana-2.1`。支持 `aspect_ratio`、`image_size` 以及 PNG / JPEG 输出。
|
|
6
|
+
- Google 模式支持可选的 `options.base_url`,经由自定义反向代理转发原生 Gemini Interactions 请求;不配置时直连 Google。
|
|
7
|
+
- 默认仍使用 OpenAI;Google 需要单独的 Gemini API key,不借用宿主 OpenAI 凭据,也不会在失败时切换后端。
|
|
8
|
+
|
|
3
9
|
## 0.1.0
|
|
4
10
|
|
|
5
11
|
- 首个发布版本,包名 `@myoldtime/opencode-codex-imagegen`,插件 id `opencode-codex-imagegen`,工具名 `proxy_imagegen`(不变)。历史本地版本的 id(`local.codex-proxy-imagegen`、`myoldtime.codex-proxy-imagegen`)仅存在于迁移说明中作为旧 id 出现。
|
package/README.md
CHANGED
|
@@ -5,9 +5,9 @@
|
|
|
5
5
|
[](https://github.com/MyOldTime/opencode-codex-imagegen/releases)
|
|
6
6
|
[](LICENSE)
|
|
7
7
|
|
|
8
|
-
OpenCode V2 插件,注册 `proxy_imagegen`
|
|
8
|
+
OpenCode V2 插件,注册 `proxy_imagegen` 工具,支持文生图和参考图编辑。默认走 **OpenAI Responses API 的托管 `image_generation` 工具**(不使用 Images API);也可配置为 **Google Gemini Interactions API(Nano Banana)**,见 [Google Gemini 配置](#google-gemini-配置)。
|
|
9
9
|
|
|
10
|
-
|
|
10
|
+
OpenAI 模式下有两种凭据来源,优先级固定:
|
|
11
11
|
|
|
12
12
|
1. **显式配置**:同时提供 `options.base_url` 与 `options.key` 时,只走你自己的代理,**完全不读取宿主的任何凭据**。只提供 `key` 时默认使用 `https://api.openai.com/v1`。
|
|
13
13
|
2. **宿主托管**:两者都不配置时,每次调用通过 `ctx.integration.connection.active('openai')` + `resolve(connection)` 取得 OpenCode 已登录的 OpenAI 凭据,由 OpenCode 负责刷新,插件不读取、不写入任何凭据文件。
|
|
@@ -22,18 +22,18 @@ OpenCode V2 插件,注册 `proxy_imagegen` 工具:通过 **Responses API 的
|
|
|
22
22
|
| npm 包名(npmjs 与 GitHub Packages 使用同一个 scoped name) | `@myoldtime/opencode-codex-imagegen` |
|
|
23
23
|
| 插件 ID | `opencode-codex-imagegen` |
|
|
24
24
|
| 工具名 | `proxy_imagegen` |
|
|
25
|
-
| 版本 / 许可证 | `0.
|
|
25
|
+
| 版本 / 许可证 | `0.2.0` / MIT |
|
|
26
26
|
|
|
27
27
|
## 安装
|
|
28
28
|
|
|
29
|
-
以下在线方式需对应的版本或标签已经发布:本包为 `0.
|
|
29
|
+
以下在线方式需对应的版本或标签已经发布:本包为 `0.2.0`,tag 为 `v0.2.0`。
|
|
30
30
|
|
|
31
31
|
### 方式一:从 npmjs.org 安装(推荐)
|
|
32
32
|
|
|
33
33
|
npmjs.org 上的公开包安装不需要登录 npm,也不需要提供 token。
|
|
34
34
|
|
|
35
35
|
```powershell
|
|
36
|
-
opencode plugin add "@myoldtime/opencode-codex-imagegen@0.
|
|
36
|
+
opencode plugin add "@myoldtime/opencode-codex-imagegen@0.2.0"
|
|
37
37
|
opencode plugin list
|
|
38
38
|
```
|
|
39
39
|
|
|
@@ -44,7 +44,7 @@ opencode plugin list
|
|
|
44
44
|
```json
|
|
45
45
|
{
|
|
46
46
|
"$schema": "https://opencode.ai/config.json",
|
|
47
|
-
"plugins": ["@myoldtime/opencode-codex-imagegen@0.
|
|
47
|
+
"plugins": ["@myoldtime/opencode-codex-imagegen@0.2.0"]
|
|
48
48
|
}
|
|
49
49
|
```
|
|
50
50
|
|
|
@@ -53,11 +53,11 @@ opencode plugin list
|
|
|
53
53
|
### 方式二:从 GitHub 标签安装
|
|
54
54
|
|
|
55
55
|
```powershell
|
|
56
|
-
opencode plugin add "github:MyOldTime/opencode-codex-imagegen#v0.
|
|
56
|
+
opencode plugin add "github:MyOldTime/opencode-codex-imagegen#v0.2.0"
|
|
57
57
|
opencode plugin list
|
|
58
58
|
```
|
|
59
59
|
|
|
60
|
-
公共仓库通过该方式安装不需要 GitHub Packages token,也不经过 npm registry。仅对某个项目生效时,项目 `opencode.json` 的 `plugins` 条目可写成同一来源 `github:MyOldTime/opencode-codex-imagegen#v0.
|
|
60
|
+
公共仓库通过该方式安装不需要 GitHub Packages token,也不经过 npm registry。仅对某个项目生效时,项目 `opencode.json` 的 `plugins` 条目可写成同一来源 `github:MyOldTime/opencode-codex-imagegen#v0.2.0`。`#v0.2.0` 指向该标签当前对应的提交,标签由仓库维护者控制,需要时请自行核对。
|
|
61
61
|
|
|
62
62
|
### 方式三:从 GitHub Packages 安装
|
|
63
63
|
|
|
@@ -67,7 +67,7 @@ GitHub Packages 与本包在 npmjs.org 的同名包属于两个独立 registry
|
|
|
67
67
|
npm config set @myoldtime:registry https://npm.pkg.github.com --location=user
|
|
68
68
|
npm login --scope=@myoldtime --auth-type=legacy --registry=https://npm.pkg.github.com
|
|
69
69
|
# Username 输入 GitHub 用户名,Password 输入 token
|
|
70
|
-
opencode plugin add "@myoldtime/opencode-codex-imagegen@0.
|
|
70
|
+
opencode plugin add "@myoldtime/opencode-codex-imagegen@0.2.0"
|
|
71
71
|
opencode plugin list
|
|
72
72
|
```
|
|
73
73
|
|
|
@@ -94,7 +94,7 @@ npm ci --ignore-scripts
|
|
|
94
94
|
"$schema": "https://opencode.ai/config.json",
|
|
95
95
|
"plugins": [
|
|
96
96
|
{
|
|
97
|
-
"package": "@myoldtime/opencode-codex-imagegen@0.
|
|
97
|
+
"package": "@myoldtime/opencode-codex-imagegen@0.2.0",
|
|
98
98
|
"options": {
|
|
99
99
|
"model": "gpt-6.1-sol",
|
|
100
100
|
"reasoning_effort": "medium",
|
|
@@ -106,18 +106,19 @@ npm ci --ignore-scripts
|
|
|
106
106
|
}
|
|
107
107
|
```
|
|
108
108
|
|
|
109
|
-
>
|
|
109
|
+
> 上例为 OpenAI 配置,`package` 固定为已发布的 `@0.2.0`。若插件来自 npm 以外的来源,把这里的 `package` 换成对应值:GitHub 标签为 `github:MyOldTime/opencode-codex-imagegen#v0.2.0`,本地开发为仓库目录的绝对路径。请在原条目上配置 `options`,不要为同一个插件重复添加条目;合并配置时只增改本插件的字段,不要覆盖其它设置。
|
|
110
110
|
|
|
111
111
|
| 选项 | 默认 | 说明 |
|
|
112
112
|
|---|---|---|
|
|
113
|
-
| `
|
|
114
|
-
| `
|
|
115
|
-
| `
|
|
116
|
-
| `
|
|
117
|
-
| `
|
|
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"`。 |
|
|
118
119
|
| `timeout_ms` | `240000` | 单次请求超时(毫秒)。 |
|
|
119
120
|
|
|
120
|
-
配置校验规则(都在发网络请求之前完成):
|
|
121
|
+
OpenAI 配置校验规则(都在发网络请求之前完成):
|
|
121
122
|
|
|
122
123
|
- `base_url` 或 `key` **只要写了就必须有效**:空串、`null`、全空白、非字符串、未解析的 `{env:...}` 一律报错,不会静默回退到宿主账号或官方地址。
|
|
123
124
|
- 只给 `base_url` 不给 `key` → 报错,提示两者都配或都不配。
|
|
@@ -125,7 +126,49 @@ npm ci --ignore-scripts
|
|
|
125
126
|
- `base_url` 含用户名密码、查询串、片段或非 HTTP(S) → 报错。
|
|
126
127
|
- 两项都完全省略 → 走宿主托管凭据;宿主没有可用 OpenAI 连接时给出明确错误,不会退回到猜测的 endpoint。
|
|
127
128
|
|
|
128
|
-
|
|
129
|
+
### Google Gemini 配置
|
|
130
|
+
|
|
131
|
+
从 `0.2.0` 起支持 Google 文生图、参考图编辑及自定义代理。在 [Google AI Studio](https://aistudio.google.com/apikey) 创建 Gemini API key,把它设置为 OpenCode 环境中的 `GEMINI_API_KEY`,不要把明文 key 写进仓库。根据 [Google 官方模型文档](https://aistudio.google.com/docs/models/gemini-nano-banana-2.1),默认模型需要付费层。
|
|
132
|
+
|
|
133
|
+
在 `opencode.json(c)` 中配置已发布的 npm 插件。若已有本插件条目,请直接替换该条目:
|
|
134
|
+
|
|
135
|
+
```json
|
|
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
|
+
```
|
|
149
|
+
|
|
150
|
+
如果从 OpenAI 切换过来,请移除原先的 `base_url`、`reasoning_effort`、`fast_mode` 和 GPT `model`。可省略 `model` 使用默认模型,也可以填其他支持图片输出的 Gemini 模型 ID。保存后,在 OpenCode TUI 中输入 `/reload`。仅设置环境变量不会自动切换后端;由 `provider` 明确选择。
|
|
151
|
+
|
|
152
|
+
- **文生图**:不传 `images`。例如:`用 proxy_imagegen 画一张水彩雪景,比例 16:9,分辨率 2K,保存为 snow.png`。
|
|
153
|
+
- **图生图**:通过 `images` 传入一张或多张本地参考图。例如:`用 proxy_imagegen 参考 snow.png 和 cabin.jpg,把木屋放进雪景里,保存为 winter.jpg`。插件会将参考图按顺序发送给 Google。
|
|
154
|
+
|
|
155
|
+
实现遵循官方 [Nano Banana 生图指南](https://aistudio.google.com/docs/image-generation?hl=zh-cn) 和 [Interactions REST 文档](https://aistudio.google.com/api-reference/interactions-api/create-interaction):用 `POST` 发送 JSON,带 `x-goog-api-key`、`Content-Type: application/json` 和 `Api-Revision: 2026-05-20`。普通 `.png` 请求只发 `model` 和 `input`;仅指定比例、分辨率或 JPEG 输出时附加 `response_format`。不显式设置 `store`,交互保存策略遵循服务端默认值。响应为 JSON,从 `model_output` 读取最后一张内嵌图片;若返回 JPEG 而目标为 `.png`,在本地转码。参考图支持 PNG / JPEG / WebP,最多 14 张(部分模型更少),包含 Base64 和提示词的整个请求不超过 20 MB。
|
|
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 的三种登录方法
|
|
129
172
|
|
|
130
173
|
宿主托管模式下,凭据来自 OpenCode 的 `openai` integration。插件只接受以下三种方法,遇到未知 `methodID` 直接报错:
|
|
131
174
|
|
|
@@ -145,15 +188,16 @@ npm ci --ignore-scripts
|
|
|
145
188
|
|
|
146
189
|
## 安全与隐私
|
|
147
190
|
|
|
148
|
-
- **不读取也不写入任何凭据文件**(包括 `auth.json`),不缓存 token
|
|
191
|
+
- **不读取也不写入任何凭据文件**(包括 `auth.json`),不缓存 token,不遍历或切换账号。OpenAI 宿主托管模式每次调用都重新 `active` + `resolve`,刷新完全交给 OpenCode。
|
|
149
192
|
- 显式 `base_url` + `key` 模式不会访问 integration API,key 只发送到 `base_url` 指向的地址。
|
|
193
|
+
- Google 模式的 key 只通过请求头发送到所选地址(官方 Gemini API 或配置的代理);提示词和参考图也会发送到该地址。仅提交你有权上传的内容。
|
|
150
194
|
- 失败时**不重试、不换通道**(401/403/超时/能力受限都一样),避免重复计费。
|
|
151
195
|
- 超时或取消后,即便上游晚到并返回了合法 PNG,也会在落盘前丢弃;流读取过程中的网络错误同样归一为固定文案。
|
|
152
196
|
- 错误信息只包含 HTTP 状态码和固定白名单错误码;不会输出上游响应正文、token、账号或任意自定义 `error.code`。网络层异常也统一归一为固定文案。
|
|
153
|
-
- 调用前先经过宿主的 permission 机制:读引用图 → `read
|
|
197
|
+
- 调用前先经过宿主的 permission 机制:读引用图 → `read`,写图片 → `edit`;被宿主拒绝则不读文件、不发请求。
|
|
154
198
|
- 信号已取消(或在解析凭据期间被取消)时不发网络请求、不落盘;超时同样不落盘。
|
|
155
199
|
- 工具返回的 metadata 仅含 `out`、`versioned`、`bytes`、`route`、`method`、`model`,不含任何凭据或账户信息。
|
|
156
|
-
- 只保存 PNG
|
|
200
|
+
- OpenAI 只保存 PNG,Google 可保存 PNG 或 JPEG;校验文件内容与扩展名一致,使用独占创建及 `-v2`/`-v3` 后缀,不覆盖已有文件。
|
|
157
201
|
|
|
158
202
|
## 用法
|
|
159
203
|
|
|
@@ -166,10 +210,12 @@ npm ci --ignore-scripts
|
|
|
166
210
|
| 参数 | 必填 | 说明 |
|
|
167
211
|
|---|---|---|
|
|
168
212
|
| `prompt` | 是 | 图片描述;有参考图时按顺序说明每张图的作用。 |
|
|
169
|
-
| `out` | 是 |
|
|
170
|
-
| `
|
|
171
|
-
| `
|
|
172
|
-
| `
|
|
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`,以所选模型支持为准。 |
|
|
173
219
|
|
|
174
220
|
尺寸与画质都是"尽力而为",最终由后端决定。
|
|
175
221
|
|
|
@@ -186,7 +232,11 @@ npm ci --ignore-scripts
|
|
|
186
232
|
| `The OpenAI access token has expired and could not be refreshed` | 刷新失败,重新登录。 |
|
|
187
233
|
| `Image request failed: HTTP 401/403` | 凭据或权限问题;插件不会自动重试。 |
|
|
188
234
|
| `Image request failed: HTTP 400 (subscription_sharing_unsupported_capability)` | 已实测的 Sign in with ChatGPT 结果:上游拒绝该能力。白名单码会原样显示(如 `subscription_sharing_unsupported_capability`、`subscription_sharing_route_not_supported`),表示当前订阅/网关不支持该能力或路由。 |
|
|
189
|
-
| `Image response contained invalid JSON`
|
|
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 与内嵌数据不符,未写入文件。 |
|
|
190
240
|
| `Image request timed out` | 超过 `timeout_ms`,未写入文件。 |
|
|
191
241
|
|
|
192
242
|
## 发布流程
|
|
@@ -202,7 +252,7 @@ npm ci --ignore-scripts
|
|
|
202
252
|
|
|
203
253
|
```powershell
|
|
204
254
|
npm whoami --registry=https://registry.npmjs.org # 只读身份确认
|
|
205
|
-
npm view @myoldtime/opencode-codex-imagegen@0.
|
|
255
|
+
npm view @myoldtime/opencode-codex-imagegen@0.2.0 version --registry=https://registry.npmjs.org --@myoldtime:registry=https://registry.npmjs.org
|
|
206
256
|
npm pack --dry-run --json # 只读打包检查
|
|
207
257
|
```
|
|
208
258
|
|
|
@@ -223,7 +273,7 @@ npm test # node --test,全部离线:注入 fake fetch / fake integrat
|
|
|
223
273
|
npm pack --dry-run --json
|
|
224
274
|
```
|
|
225
275
|
|
|
226
|
-
|
|
276
|
+
测试覆盖:OpenAI 显式与宿主托管模式、三种 OAuth 路由、SSE;Google Interactions API 的文生图与多图编辑、尺寸参数、参考图限制和 PNG/JPEG 输出;两路的权限顺序、错误脱敏、取消/超时不落盘、不覆盖已有文件;另有发布元数据测试。
|
|
227
277
|
|
|
228
278
|
## License
|
|
229
279
|
|
package/VALIDATION.md
CHANGED
|
@@ -1,8 +1,16 @@
|
|
|
1
1
|
# 验证记录
|
|
2
2
|
|
|
3
|
+
## Google Gemini 适配(2026-11-26)
|
|
4
|
+
|
|
5
|
+
- 使用注入的 `fetch` 测试 Google Interactions REST 请求及 `model_output` 响应,覆盖文生图、多参考图编辑、权限、格式校验、不覆盖文件、失败不重试和取消/超时不写盘。原 OpenAI/Codex 测试一并回归。
|
|
6
|
+
- `npm run check`、`npm test`(45 项通过,其中新增 Google 测试 9 项)及 `npm pack --dry-run --json` 均通过。Google 自定义代理以模拟响应检查 URL 拼接、请求头、禁止重定向以及失败不回退。
|
|
7
|
+
- 后续经用户配置的代理实测一次:最小 `model` + `input` 请求返回 HTTP 200、`Content-Type: application/json`、`status: completed`,内嵌 JPEG。使用同一次响应的图片数据离线重放验证转码,得到 1376×768 的 PNG。未用真实请求验证可选尺寸参数或图生图。修复后 46 项离线测试通过。
|
|
8
|
+
|
|
9
|
+
## 0.1.0 历史验证
|
|
10
|
+
|
|
3
11
|
测试日期:2026-10-30。宿主 OpenCode 2.2.0,Node.js 24.18.0,Windows。
|
|
4
12
|
|
|
5
|
-
|
|
13
|
+
### 自动化测试
|
|
6
14
|
|
|
7
15
|
- `npm ci --ignore-scripts`:通过(无新增依赖,0 vulnerabilities)。
|
|
8
16
|
- `npm run check`:通过。
|
|
@@ -11,14 +19,14 @@
|
|
|
11
19
|
- 包内容使用 `package.json` 的 `files` 白名单,不包含凭据、原始响应、测试图片、测试脚本、`.github` 或机器配置。
|
|
12
20
|
- 路由测试覆盖显式 API key、宿主托管 API key 和三种 OAuth 方法;另覆盖权限、凭据刷新委托、严格配置校验、错误脱敏、流式解析、取消与超时、引用图片以及文件不覆盖。
|
|
13
21
|
|
|
14
|
-
|
|
22
|
+
### 重命名与双源发布准备(离线)
|
|
15
23
|
|
|
16
24
|
- 本轮只做元数据与文档重命名,未重新联网生成图片:`core.mjs` 逻辑未改动。改名前后的 SHA256 均为 `D04176C047A350BD2198A56EFE024385B1DDB6E862571293010D0EDEF7EFC896`;`index.js` 仅插件 ID 从 `myoldtime.codex-proxy-imagegen` 改为 `opencode-codex-imagegen`,工具名 `proxy_imagegen` 不变。
|
|
17
25
|
- 包名在 npmjs 与 GitHub Packages 统一为 `@myoldtime/opencode-codex-imagegen`,`package.json` 与 `package-lock.json` 同名同版本(0.1.0,MIT)。
|
|
18
26
|
- `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
27
|
- GitHub Actions 只在 Release `published` 时发布 GitHub Packages;npmjs 由本机已登录账号在用户未来单独确认后执行 `npm run publish:npm`。本机 npm 登录不会传入 Actions,因此没有配置 `NPM_TOKEN`,也未做 OIDC 自动授权。
|
|
20
28
|
|
|
21
|
-
|
|
29
|
+
### 真实请求(历史记录,本轮未重复执行)
|
|
22
30
|
|
|
23
31
|
下表是代码与账号能力的历史验证,不属于本轮离线重命名验证;本轮未再次联网生成,也未验证真实发布。
|
|
24
32
|
|
|
@@ -33,7 +41,7 @@
|
|
|
33
41
|
|
|
34
42
|
legacy 验证发现真实响应可能省略 Content-Type,已修复为有界前缀格式检测,并新增单字节分片回归;另外通过保留的真实响应离线重放恢复图片,未为重放重复发起请求。
|
|
35
43
|
|
|
36
|
-
|
|
44
|
+
### 发布与安装
|
|
37
45
|
|
|
38
46
|
**当前状态:尚未创建远端仓库、未 push、未打 tag、未发布 Release、未运行任何发布命令,也未切换正在使用的插件。** 本节命令只有用户未来单独确认后才会使用。
|
|
39
47
|
|
package/core.mjs
CHANGED
|
@@ -7,6 +7,15 @@ export const DEFAULT_OPENAI_BASE_URL = "https://api.openai.com/v1"
|
|
|
7
7
|
export const OPENAI_RESPONSES_URL = "https://api.openai.com/v1/responses"
|
|
8
8
|
export const CODEX_RESPONSES_URL = "https://chatgpt.com/backend-api/codex/responses"
|
|
9
9
|
|
|
10
|
+
const DEFAULT_GOOGLE_BASE_URL = "https://generativelanguage.googleapis.com"
|
|
11
|
+
const GOOGLE_API_REVISION = "2026-05-20"
|
|
12
|
+
const DEFAULT_GOOGLE_MODEL = "gemini-nano-banana-2.1"
|
|
13
|
+
const GOOGLE_INLINE_LIMIT = 20_000_000
|
|
14
|
+
const GOOGLE_INLINE_LIMIT_ERROR = "Google inline image requests must be at most 20 MB including base64; resize or compress your reference images"
|
|
15
|
+
export const GOOGLE_MAX_REFERENCES = 14
|
|
16
|
+
export const GOOGLE_ASPECT_RATIOS = Object.freeze(["1:1", "2:3", "3:2", "3:4", "4:3", "4:5", "5:4", "9:16", "16:9", "21:9", "1:4", "4:1", "1:8", "8:1"])
|
|
17
|
+
export const GOOGLE_IMAGE_SIZES = Object.freeze(["1K", "2K", "4K"])
|
|
18
|
+
|
|
10
19
|
// OAuth sign-in methods that this plugin knows how to route. Anything else is rejected
|
|
11
20
|
// instead of guessing an endpoint.
|
|
12
21
|
export const SUPPORTED_OAUTH_METHODS = ["chatgpt-token-sharing", "chatgpt-browser", "chatgpt-headless"]
|
|
@@ -32,6 +41,24 @@ const OMIT_HINT = "omit options.base_url and options.key entirely to use the Ope
|
|
|
32
41
|
|
|
33
42
|
export function pluginConfig(options = {}) {
|
|
34
43
|
if (options === null || typeof options !== "object" || Array.isArray(options)) throw new Error("Plugin options must be an object")
|
|
44
|
+
const provider = options.provider === undefined ? "openai" : options.provider
|
|
45
|
+
if (!["openai", "google"].includes(provider)) throw new Error("options.provider must be openai or google")
|
|
46
|
+
const model = options.model ?? (provider === "google" ? DEFAULT_GOOGLE_MODEL : DEFAULT_MODEL)
|
|
47
|
+
if (typeof model !== "string" || !model.trim()) throw new Error("model must be a nonempty string")
|
|
48
|
+
const timeoutMs = options.timeout_ms ?? DEFAULT_TIMEOUT_MS
|
|
49
|
+
if (!Number.isInteger(timeoutMs) || timeoutMs <= 0) throw new Error("timeout_ms must be a positive integer")
|
|
50
|
+
|
|
51
|
+
if (provider === "google") {
|
|
52
|
+
if (options.reasoning_effort !== undefined || options.fast_mode !== undefined) {
|
|
53
|
+
throw new Error("options.reasoning_effort and options.fast_mode are only supported by the OpenAI provider")
|
|
54
|
+
}
|
|
55
|
+
if (typeof options.key !== "string" || !options.key.trim() || options.key.trim().startsWith("{env:")) {
|
|
56
|
+
throw new Error("The Google provider requires a valid options.key; set GEMINI_API_KEY in the OpenCode environment and use {env:GEMINI_API_KEY}")
|
|
57
|
+
}
|
|
58
|
+
const endpoint = googleInteractionsURL(options.base_url === undefined ? DEFAULT_GOOGLE_BASE_URL : options.base_url)
|
|
59
|
+
return { provider, mode: "explicit", endpoint, apiKey: options.key.trim(), model: model.trim(), timeoutMs }
|
|
60
|
+
}
|
|
61
|
+
|
|
35
62
|
// Presence is explicit: an empty, null, blank or unresolved value is a configuration error,
|
|
36
63
|
// never a silent fallback. Only a fully omitted pair uses the host-managed account.
|
|
37
64
|
const hasBase = options.base_url !== undefined
|
|
@@ -50,20 +77,17 @@ export function pluginConfig(options = {}) {
|
|
|
50
77
|
if (hasBase && !hasKey) {
|
|
51
78
|
throw new Error("options.base_url requires options.key; configure both or omit both to use the signed-in OpenAI account")
|
|
52
79
|
}
|
|
53
|
-
const model = options.model ?? DEFAULT_MODEL
|
|
54
|
-
if (typeof model !== "string" || !model.trim()) throw new Error("model must be a nonempty string")
|
|
55
80
|
if (options.reasoning_effort !== undefined && !["none", "minimal", "low", "medium", "high", "xhigh"].includes(options.reasoning_effort)) {
|
|
56
81
|
throw new Error("reasoning_effort must be none, minimal, low, medium, high or xhigh (model support varies)")
|
|
57
82
|
}
|
|
58
83
|
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
84
|
// key only: fall back to the public OpenAI endpoint. Both present: explicit proxy. Neither: host-managed.
|
|
62
85
|
const explicit = Boolean(apiKey)
|
|
63
86
|
const explicitBase = explicit ? baseURL || DEFAULT_OPENAI_BASE_URL : undefined
|
|
64
87
|
// Fail on a malformed proxy URL before any session, permission or network work happens.
|
|
65
88
|
if (explicitBase) responsesURL(explicitBase)
|
|
66
89
|
return {
|
|
90
|
+
provider,
|
|
67
91
|
mode: explicit ? "explicit" : "managed",
|
|
68
92
|
baseURL: explicitBase,
|
|
69
93
|
apiKey: explicit ? apiKey : undefined,
|
|
@@ -84,6 +108,19 @@ export function responsesURL(baseURL) {
|
|
|
84
108
|
return url.toString()
|
|
85
109
|
}
|
|
86
110
|
|
|
111
|
+
function googleInteractionsURL(baseURL) {
|
|
112
|
+
const invalid = () => new Error("Google options.base_url must be an HTTP(S) URL without credentials, query or fragment")
|
|
113
|
+
if (typeof baseURL !== "string" || !/^https?:\/\//i.test(baseURL.trim()) || /[?#]/.test(baseURL)) throw invalid()
|
|
114
|
+
let url
|
|
115
|
+
try { url = new URL(baseURL.trim()) } catch { throw invalid() }
|
|
116
|
+
if (url.username || url.password) throw invalid()
|
|
117
|
+
const pathname = url.pathname.replace(/\/+$/, "")
|
|
118
|
+
if (pathname.endsWith("/interactions")) url.pathname = pathname
|
|
119
|
+
else if (/\/v1(?:beta)?$/.test(pathname)) url.pathname = `${pathname}/interactions`
|
|
120
|
+
else url.pathname = `${pathname}/v1beta/interactions`
|
|
121
|
+
return url.toString()
|
|
122
|
+
}
|
|
123
|
+
|
|
87
124
|
export function abortError() {
|
|
88
125
|
const error = new Error("Image generation aborted")
|
|
89
126
|
error.name = "AbortError"
|
|
@@ -113,6 +150,9 @@ function connectionError(detail) {
|
|
|
113
150
|
// Resolves the request route for this call. Explicit options never touch the host credential
|
|
114
151
|
// API; managed mode re-resolves the connection on every call so OpenCode owns refresh.
|
|
115
152
|
export async function resolveRoute(config, ctx) {
|
|
153
|
+
if (config.provider === "google") {
|
|
154
|
+
return { route: "google", method: "api-key", url: config.endpoint, access: config.apiKey }
|
|
155
|
+
}
|
|
116
156
|
if (config.mode === "explicit") {
|
|
117
157
|
return { route: "proxy", method: "options", url: responsesURL(config.baseURL), access: config.apiKey }
|
|
118
158
|
}
|
|
@@ -173,6 +213,11 @@ export async function resolveRoute(config, ctx) {
|
|
|
173
213
|
}
|
|
174
214
|
|
|
175
215
|
export function requestHeaders(route, sessionID) {
|
|
216
|
+
if (route.route === "google") return {
|
|
217
|
+
"x-goog-api-key": route.access,
|
|
218
|
+
"Api-Revision": GOOGLE_API_REVISION,
|
|
219
|
+
"Content-Type": "application/json",
|
|
220
|
+
}
|
|
176
221
|
const headers = {
|
|
177
222
|
Authorization: `Bearer ${route.access}`,
|
|
178
223
|
"Content-Type": "application/json",
|
|
@@ -197,16 +242,31 @@ function imageType(bytes) {
|
|
|
197
242
|
if (bytes[0] === 255 && bytes[1] === 216 && bytes[2] === 255) return "image/jpeg"
|
|
198
243
|
if (["GIF87a", "GIF89a"].includes(bytes.subarray(0, 6).toString())) return "image/gif"
|
|
199
244
|
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
245
|
}
|
|
202
246
|
|
|
203
|
-
|
|
247
|
+
function outputFormat(out) {
|
|
248
|
+
const extension = path.extname(out).toLowerCase()
|
|
249
|
+
if (extension === ".png") return "image/png"
|
|
250
|
+
if (extension === ".jpg" || extension === ".jpeg") return "image/jpeg"
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
export function validateInput(input, provider = "openai") {
|
|
204
254
|
if (!input || typeof input.prompt !== "string" || !input.prompt.trim()) throw new Error("prompt is required")
|
|
205
|
-
|
|
206
|
-
|
|
255
|
+
const format = typeof input.out === "string" ? outputFormat(input.out) : undefined
|
|
256
|
+
if (input.images !== undefined && (!Array.isArray(input.images) || input.images.some(p => typeof p !== "string"))) throw new Error("images must be file paths")
|
|
257
|
+
if (provider === "google") {
|
|
258
|
+
if (!format) throw new Error("out must be a .png, .jpg or .jpeg file path for Google")
|
|
259
|
+
if ((input.size !== undefined && input.size !== "auto") || (input.quality !== undefined && input.quality !== "auto")) {
|
|
260
|
+
throw new Error("The Google provider uses aspect_ratio and image_size instead of size and quality")
|
|
261
|
+
}
|
|
262
|
+
if (input.aspect_ratio !== undefined && !GOOGLE_ASPECT_RATIOS.includes(input.aspect_ratio)) throw new Error("Invalid Google aspect_ratio")
|
|
263
|
+
if (input.image_size !== undefined && !GOOGLE_IMAGE_SIZES.includes(input.image_size)) throw new Error("Google image_size must be 1K, 2K or 4K")
|
|
264
|
+
if (input.images?.length > GOOGLE_MAX_REFERENCES) throw new Error(`Google image generation accepts at most ${GOOGLE_MAX_REFERENCES} reference images; some models accept fewer`)
|
|
265
|
+
return
|
|
207
266
|
}
|
|
267
|
+
if (format !== "image/png") throw new Error("out must be a .png file path")
|
|
268
|
+
if (input.aspect_ratio !== undefined || input.image_size !== undefined) throw new Error("aspect_ratio and image_size are only supported by the Google provider")
|
|
208
269
|
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
270
|
if (input.size !== undefined && input.size !== "auto") {
|
|
211
271
|
const match = /^(\d+)x(\d+)$/.exec(input.size)
|
|
212
272
|
const w = Number(match?.[1]), h = Number(match?.[2])
|
|
@@ -321,16 +381,51 @@ export async function readImageResponse(response) {
|
|
|
321
381
|
throw new ImageResponseError("Response ended without an image_generation_call.result")
|
|
322
382
|
}
|
|
323
383
|
|
|
384
|
+
// Google returns raw Interactions steps, not the SDK's computed output_image.
|
|
385
|
+
async function readGoogleImageResponse(response) {
|
|
386
|
+
const payload = parseEvent(await response.text())
|
|
387
|
+
if (payload?.error || payload?.status !== "completed") {
|
|
388
|
+
throw new ImageResponseError("Google image interaction did not complete")
|
|
389
|
+
}
|
|
390
|
+
let image
|
|
391
|
+
for (const step of Array.isArray(payload?.steps) ? payload.steps : []) {
|
|
392
|
+
if (step?.type !== "model_output" || !Array.isArray(step.content)) continue
|
|
393
|
+
for (const part of step.content) {
|
|
394
|
+
if (part?.type === "image" && typeof part.data === "string" && part.data) image = part
|
|
395
|
+
}
|
|
396
|
+
}
|
|
397
|
+
if (!image) throw new ImageResponseError("Google response contained no generated image")
|
|
398
|
+
return image
|
|
399
|
+
}
|
|
400
|
+
|
|
324
401
|
export async function savePNG(out, directory, base64, signal) {
|
|
402
|
+
return saveImage(out, directory, base64, "image/png", signal)
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
async function saveImage(out, directory, base64, format, signal, googleImage) {
|
|
325
406
|
if (typeof base64 !== "string" || !/^[A-Za-z0-9+/]+={0,2}$/.test(base64) || base64.length % 4) throw new Error("Invalid image base64")
|
|
326
|
-
|
|
327
|
-
|
|
407
|
+
let bytes = Buffer.from(base64, "base64")
|
|
408
|
+
const actual = imageType(bytes)
|
|
409
|
+
if (googleImage?.mime_type !== undefined && googleImage.mime_type !== actual) {
|
|
410
|
+
throw new Error("Google image MIME type does not match its bytes")
|
|
411
|
+
}
|
|
412
|
+
if (googleImage && actual === "image/jpeg" && format === "image/png") {
|
|
413
|
+
abortIfNeeded(signal)
|
|
414
|
+
const [{ default: jpeg }, { PNG }] = await Promise.all([import("jpeg-js"), import("pngjs")])
|
|
415
|
+
try {
|
|
416
|
+
const raster = jpeg.decode(bytes, { maxResolutionInMP: 20, maxMemoryUsageInMB: 384, tolerantDecoding: false })
|
|
417
|
+
bytes = PNG.sync.write(raster)
|
|
418
|
+
} catch {
|
|
419
|
+
throw new Error("Could not convert Google JPEG to PNG")
|
|
420
|
+
}
|
|
421
|
+
} else if (actual !== format) throw new Error(`Backend did not return ${format === "image/png" ? "PNG" : "JPEG"}`)
|
|
328
422
|
abortIfNeeded(signal)
|
|
329
423
|
const target = path.resolve(directory, out)
|
|
330
424
|
await mkdir(path.dirname(target), { recursive: true })
|
|
331
|
-
const
|
|
425
|
+
const extension = path.extname(target)
|
|
426
|
+
const stem = target.slice(0, -extension.length)
|
|
332
427
|
for (let version = 1; ; version++) {
|
|
333
|
-
const file = version === 1 ? target : `${stem}-v${version}.
|
|
428
|
+
const file = version === 1 ? target : `${stem}-v${version}${extension.toLowerCase()}`
|
|
334
429
|
let handle
|
|
335
430
|
try { handle = await open(file, "wx") } catch (error) {
|
|
336
431
|
if (error.code === "EEXIST") continue
|
|
@@ -356,17 +451,64 @@ export async function savePNG(out, directory, base64, signal) {
|
|
|
356
451
|
}
|
|
357
452
|
}
|
|
358
453
|
|
|
454
|
+
function googleBody(input, config, references, format) {
|
|
455
|
+
const responseFormat = {
|
|
456
|
+
...(format === "image/jpeg" ? { mime_type: format } : {}),
|
|
457
|
+
...(input.aspect_ratio ? { aspect_ratio: input.aspect_ratio } : {}),
|
|
458
|
+
...(input.image_size ? { image_size: input.image_size } : {}),
|
|
459
|
+
}
|
|
460
|
+
return {
|
|
461
|
+
model: config.model,
|
|
462
|
+
input: [{ type: "text", text: input.prompt }, ...references.map(({ mime, data }) => ({ type: "image", mime_type: mime, data }))],
|
|
463
|
+
...(Object.keys(responseFormat).length ? { response_format: { type: "image", ...responseFormat } } : {}),
|
|
464
|
+
}
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
function openAIBody(input, config, references) {
|
|
468
|
+
const content = [{ type: "input_text", text: input.prompt }, ...references.map(({ mime, data }) => ({
|
|
469
|
+
type: "input_image",
|
|
470
|
+
image_url: `data:${mime};base64,${data}`,
|
|
471
|
+
}))]
|
|
472
|
+
return {
|
|
473
|
+
model: config.model,
|
|
474
|
+
instructions: INSTRUCTIONS,
|
|
475
|
+
input: [{ role: "user", content }],
|
|
476
|
+
tools: [{ type: "image_generation", output_format: "png", quality: input.quality ?? "auto", ...(input.size ? { size: input.size } : {}) }],
|
|
477
|
+
tool_choice: { type: "image_generation" },
|
|
478
|
+
stream: true,
|
|
479
|
+
store: false,
|
|
480
|
+
...(config.reasoningEffort !== undefined ? { reasoning: { effort: config.reasoningEffort } } : {}),
|
|
481
|
+
...(config.fastMode ? { service_tier: "priority" } : {}),
|
|
482
|
+
}
|
|
483
|
+
}
|
|
484
|
+
|
|
359
485
|
export async function generateImage(input, config, directory, env = {}) {
|
|
360
486
|
const { ctx, signal, sessionID, fetcher = fetch } = env
|
|
361
|
-
validateInput(input)
|
|
487
|
+
validateInput(input, config.provider)
|
|
488
|
+
const google = config.provider === "google"
|
|
489
|
+
const format = outputFormat(input.out)
|
|
362
490
|
abortIfNeeded(signal)
|
|
363
491
|
// Credentials are resolved per call; explicit options never consult the host.
|
|
364
492
|
const route = await resolveRoute(config, ctx)
|
|
365
493
|
abortIfNeeded(signal)
|
|
366
|
-
const
|
|
494
|
+
const references = []
|
|
495
|
+
let encodedBytes = 0
|
|
496
|
+
const referenceFormats = google ? ["image/png", "image/jpeg", "image/webp"] : ["image/png", "image/jpeg", "image/gif", "image/webp"]
|
|
367
497
|
for (const file of input.images ?? []) {
|
|
368
498
|
const bytes = await readFile(path.resolve(directory, file), { signal })
|
|
369
|
-
|
|
499
|
+
const mime = imageType(bytes)
|
|
500
|
+
if (!referenceFormats.includes(mime)) {
|
|
501
|
+
throw new Error(google ? "Unsupported Google reference image: use PNG, JPEG or WebP" : "Unsupported reference image: use PNG, JPEG, GIF or WebP")
|
|
502
|
+
}
|
|
503
|
+
if (google) {
|
|
504
|
+
encodedBytes += Math.ceil(bytes.length / 3) * 4
|
|
505
|
+
if (encodedBytes > GOOGLE_INLINE_LIMIT) throw new Error(GOOGLE_INLINE_LIMIT_ERROR)
|
|
506
|
+
}
|
|
507
|
+
references.push({ mime, data: bytes.toString("base64") })
|
|
508
|
+
}
|
|
509
|
+
const body = JSON.stringify(google ? googleBody(input, config, references, format) : openAIBody(input, config, references))
|
|
510
|
+
if (google && Buffer.byteLength(body) > GOOGLE_INLINE_LIMIT) {
|
|
511
|
+
throw new Error(GOOGLE_INLINE_LIMIT_ERROR)
|
|
370
512
|
}
|
|
371
513
|
const timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS
|
|
372
514
|
if (!Number.isInteger(timeoutMs) || timeoutMs <= 0) throw new Error("timeoutMs must be a positive integer")
|
|
@@ -379,17 +521,7 @@ export async function generateImage(input, config, directory, env = {}) {
|
|
|
379
521
|
signal: combinedSignal,
|
|
380
522
|
redirect: "error",
|
|
381
523
|
headers: requestHeaders(route, sessionID),
|
|
382
|
-
body
|
|
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
|
-
}),
|
|
524
|
+
body,
|
|
393
525
|
})
|
|
394
526
|
} catch {
|
|
395
527
|
if (signal?.aborted) throw abortError()
|
|
@@ -405,16 +537,25 @@ export async function generateImage(input, config, directory, env = {}) {
|
|
|
405
537
|
throw new Error("Image request failed before a response was received")
|
|
406
538
|
}
|
|
407
539
|
if (!response.ok) throw await httpError(response, { signal, combinedSignal })
|
|
408
|
-
let base64
|
|
540
|
+
let base64, googleImage
|
|
409
541
|
try {
|
|
410
|
-
|
|
542
|
+
if (google) {
|
|
543
|
+
googleImage = await readGoogleImageResponse(response)
|
|
544
|
+
base64 = googleImage.data
|
|
545
|
+
} else base64 = await readImageResponse(response)
|
|
411
546
|
} catch (error) {
|
|
412
547
|
// Our own messages pass through; every transport/stream failure is normalized.
|
|
413
|
-
if (error instanceof ImageResponseError) throw error
|
|
414
548
|
throwIfSettled(signal, combinedSignal)
|
|
549
|
+
if (error instanceof ImageResponseError) throw error
|
|
415
550
|
throw new Error("Image response stream failed")
|
|
416
551
|
}
|
|
417
552
|
throwIfSettled(signal, combinedSignal)
|
|
418
|
-
|
|
553
|
+
let saved
|
|
554
|
+
try {
|
|
555
|
+
saved = await saveImage(input.out, directory, base64, format, combinedSignal, googleImage)
|
|
556
|
+
} catch (error) {
|
|
557
|
+
throwIfSettled(signal, combinedSignal)
|
|
558
|
+
throw error
|
|
559
|
+
}
|
|
419
560
|
return { ...saved, route: route.route, method: route.method, model: config.model }
|
|
420
561
|
}
|
package/index.js
CHANGED
|
@@ -1,29 +1,37 @@
|
|
|
1
1
|
import path from "node:path"
|
|
2
|
-
import { generateImage, validateInput, pluginConfig } from "./core.mjs"
|
|
2
|
+
import { generateImage, validateInput, pluginConfig, GOOGLE_ASPECT_RATIOS, GOOGLE_IMAGE_SIZES, GOOGLE_MAX_REFERENCES } from "./core.mjs"
|
|
3
3
|
|
|
4
4
|
export default {
|
|
5
5
|
id: "opencode-codex-imagegen",
|
|
6
6
|
async setup(ctx) {
|
|
7
|
+
const google = ctx.options?.provider === "google"
|
|
7
8
|
await ctx.tool.transform(editor => {
|
|
8
9
|
editor.add({
|
|
9
10
|
name: "proxy_imagegen",
|
|
10
|
-
description:
|
|
11
|
+
description: google
|
|
12
|
+
? "Generate or edit an image through the Google Gemini API (Nano Banana by default). Omit images for text-to-image; pass local reference images to edit or combine them. Saves one PNG or JPEG without overwriting existing files."
|
|
13
|
+
: "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
14
|
input: {
|
|
12
15
|
type: "object",
|
|
13
16
|
properties: {
|
|
14
17
|
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
|
-
|
|
17
|
-
|
|
18
|
-
|
|
18
|
+
out: { type: "string", description: `${google ? "PNG or JPEG" : "PNG"} output path, relative to the current session directory or absolute.` },
|
|
19
|
+
images: { type: "array", items: { type: "string" }, ...(google ? { maxItems: GOOGLE_MAX_REFERENCES } : {}), description: `Local reference image paths (PNG, JPEG, ${google ? "" : "GIF, "}WebP).` },
|
|
20
|
+
...(google ? {
|
|
21
|
+
aspect_ratio: { type: "string", enum: GOOGLE_ASPECT_RATIOS, description: "Optional width:height ratio; model support varies." },
|
|
22
|
+
image_size: { type: "string", enum: GOOGLE_IMAGE_SIZES, description: "Optional output resolution tier; model support varies." },
|
|
23
|
+
} : {
|
|
24
|
+
quality: { type: "string", enum: ["auto", "low", "medium", "high"] },
|
|
25
|
+
size: { type: "string", description: "auto or WIDTHxHEIGHT; exact dimensions depend on the backend." },
|
|
26
|
+
}),
|
|
19
27
|
},
|
|
20
28
|
required: ["prompt", "out"],
|
|
21
29
|
additionalProperties: false,
|
|
22
30
|
},
|
|
23
31
|
async execute(input, context) {
|
|
24
|
-
validateInput(input)
|
|
25
32
|
// Options are validated before anything network- or credential-related happens.
|
|
26
33
|
const config = pluginConfig(ctx.options)
|
|
34
|
+
validateInput(input, config.provider)
|
|
27
35
|
const session = await ctx.session.get({ sessionID: context.sessionID })
|
|
28
36
|
const directory = session.location.directory
|
|
29
37
|
// Respect normal OpenCode edit rules, including external-directory approval.
|
|
@@ -35,16 +43,18 @@ export default {
|
|
|
35
43
|
action: "read",
|
|
36
44
|
resources: input.images.map(file => path.resolve(directory, file)),
|
|
37
45
|
})
|
|
46
|
+
const output = path.resolve(directory, input.out)
|
|
47
|
+
const extension = path.extname(output)
|
|
38
48
|
await ctx.permission.assert({
|
|
39
49
|
sessionID: context.sessionID,
|
|
40
50
|
agent: context.agent,
|
|
41
51
|
source,
|
|
42
52
|
action: "edit",
|
|
43
|
-
resources: [
|
|
53
|
+
resources: [output, `${output.slice(0, -extension.length)}-v*${extension.toLowerCase()}`],
|
|
44
54
|
})
|
|
45
55
|
const result = await generateImage(input, config, directory, { ctx, signal: context.signal, sessionID: context.sessionID })
|
|
46
56
|
return {
|
|
47
|
-
content: `Saved PNG: ${result.out}${result.versioned ? " (versioned; existing file preserved)" : ""}`,
|
|
57
|
+
content: `Saved ${extension.toLowerCase() === ".png" ? "PNG" : "JPEG"}: ${result.out}${result.versioned ? " (versioned; existing file preserved)" : ""}`,
|
|
48
58
|
metadata: {
|
|
49
59
|
out: result.out,
|
|
50
60
|
versioned: result.versioned,
|
package/package.json
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@myoldtime/opencode-codex-imagegen",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.0",
|
|
4
4
|
"type": "module",
|
|
5
|
-
"description": "OpenCode V2 plugin:
|
|
5
|
+
"description": "OpenCode V2 plugin: generate and edit images with OpenAI Responses (API, proxy or Codex) or Google Gemini Interactions (Nano Banana).",
|
|
6
6
|
"license": "MIT",
|
|
7
7
|
"author": "MyOldTime",
|
|
8
8
|
"repository": {
|
|
@@ -46,5 +46,9 @@
|
|
|
46
46
|
},
|
|
47
47
|
"engines": {
|
|
48
48
|
"node": ">=20.16"
|
|
49
|
+
},
|
|
50
|
+
"dependencies": {
|
|
51
|
+
"jpeg-js": "0.4.4",
|
|
52
|
+
"pngjs": "7.0.0"
|
|
49
53
|
}
|
|
50
|
-
}
|
|
54
|
+
}
|