@myoldtime/opencode-codex-imagegen 0.0.0-stage → 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 +21 -0
- package/LICENSE +21 -0
- package/README.md +279 -2
- package/VALIDATION.md +50 -0
- package/core.mjs +561 -0
- package/index.js +71 -0
- package/package.json +52 -4
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
# Changelog
|
|
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
|
+
|
|
9
|
+
## 0.1.0
|
|
10
|
+
|
|
11
|
+
- 首个发布版本,包名 `@myoldtime/opencode-codex-imagegen`,插件 id `opencode-codex-imagegen`,工具名 `proxy_imagegen`(不变)。历史本地版本的 id(`local.codex-proxy-imagegen`、`myoldtime.codex-proxy-imagegen`)仅存在于迁移说明中作为旧 id 出现。
|
|
12
|
+
- 双源发布:npmjs 与 GitHub Packages 使用同一个 scoped 包名,各自通过显式 `--registry` + `--@myoldtime:registry` 发布;GitHub Actions 在 Release `published` 时发布 GitHub Packages,npmjs 由本机已登录账号在确认后执行 `npm run publish:npm`。
|
|
13
|
+
- 显式 `options.base_url` + `options.key` 优先,且完全不读取宿主凭据;仅给有效的 `key` 时默认 `https://api.openai.com/v1`。**只要写了 `base_url` / `key`,空串、`null`、全空白、未解析的 `{env:...}` 一律报错**,只有两者都完全省略才走宿主账号。
|
|
14
|
+
- 未配置凭据时通过 `ctx.integration.connection.active("openai")` + `resolve(connection)` 使用 OpenCode 托管的 OpenAI 账号,每次调用重新解析,刷新由宿主负责。
|
|
15
|
+
- 支持三种登录方法的路由:`chatgpt-token-sharing` → `https://api.openai.com/v1/responses`;`chatgpt-browser` / `chatgpt-headless` → `https://chatgpt.com/backend-api/codex/responses`;未知方法明确报错。
|
|
16
|
+
- 仍只使用 Responses 托管 `image_generation` 工具(非 Images API)。
|
|
17
|
+
- 失败不重试、不换通道;错误只暴露 HTTP 状态与白名单错误码,不输出上游正文、token 或账号。
|
|
18
|
+
- 响应体/SSE 读取期间的网络错误统一归一为固定文案;超时或取消后的晚到结果在落盘前丢弃,落盘阶段取消只清理本次新建的文件。
|
|
19
|
+
- 保留模型/画质/尺寸/推理强度/优先级/超时/参考图/PNG 独占版本保存行为。
|
|
20
|
+
- 内置自动化测试全部离线;另已实际验证 API 中转、两种 legacy 登录均出图成功。新版 Sign in with ChatGPT 被上游以 `subscription_sharing_unsupported_capability` 拒绝,限制已在文档明确说明。
|
|
21
|
+
- 兼容缺失 Content-Type 的 Codex SSE 响应,支持单字节/UTF-8 分片格式检测。
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 MyOldTime
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,280 @@
|
|
|
1
|
-
#
|
|
1
|
+
# opencode-codex-imagegen
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
[](https://github.com/MyOldTime/opencode-codex-imagegen/actions/workflows/ci.yml)
|
|
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 |
|
|
26
|
+
|
|
27
|
+
## 安装
|
|
28
|
+
|
|
29
|
+
以下在线方式需对应的版本或标签已经发布:本包为 `0.2.0`,tag 为 `v0.2.0`。
|
|
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)。
|
|
65
|
+
|
|
66
|
+
```sh
|
|
67
|
+
npm config set @myoldtime:registry https://npm.pkg.github.com --location=user
|
|
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"
|
|
71
|
+
opencode plugin list
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
token 只在 `npm login` 的交互提示中输入,由 npm 自己保存;不要写进 `opencode.json`,也不要提交到仓库。若之后改回 npmjs.org 渠道,把该 scope 指回官方 registry:
|
|
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`。必须指向目录,不能指向单个文件;插件本身无需编译。
|
|
89
|
+
|
|
90
|
+
## 配置
|
|
91
|
+
|
|
92
|
+
```json
|
|
93
|
+
{
|
|
94
|
+
"$schema": "https://opencode.ai/config.json",
|
|
95
|
+
"plugins": [
|
|
96
|
+
{
|
|
97
|
+
"package": "@myoldtime/opencode-codex-imagegen@0.2.0",
|
|
98
|
+
"options": {
|
|
99
|
+
"model": "gpt-6.1-sol",
|
|
100
|
+
"reasoning_effort": "medium",
|
|
101
|
+
"fast_mode": false,
|
|
102
|
+
"timeout_ms": 240000
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
]
|
|
106
|
+
}
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
> 上例为 OpenAI 配置,`package` 固定为已发布的 `@0.2.0`。若插件来自 npm 以外的来源,把这里的 `package` 换成对应值:GitHub 标签为 `github:MyOldTime/opencode-codex-imagegen#v0.2.0`,本地开发为仓库目录的绝对路径。请在原条目上配置 `options`,不要为同一个插件重复添加条目;合并配置时只增改本插件的字段,不要覆盖其它设置。
|
|
110
|
+
|
|
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` | 单次请求超时(毫秒)。 |
|
|
120
|
+
|
|
121
|
+
OpenAI 配置校验规则(都在发网络请求之前完成):
|
|
122
|
+
|
|
123
|
+
- `base_url` 或 `key` **只要写了就必须有效**:空串、`null`、全空白、非字符串、未解析的 `{env:...}` 一律报错,不会静默回退到宿主账号或官方地址。
|
|
124
|
+
- 只给 `base_url` 不给 `key` → 报错,提示两者都配或都不配。
|
|
125
|
+
- 只给有效的 `key` → 默认使用 `https://api.openai.com/v1`。
|
|
126
|
+
- `base_url` 含用户名密码、查询串、片段或非 HTTP(S) → 报错。
|
|
127
|
+
- 两项都完全省略 → 走宿主托管凭据;宿主没有可用 OpenAI 连接时给出明确错误,不会退回到猜测的 endpoint。
|
|
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 的三种登录方法
|
|
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
|
+
```
|
|
258
|
+
|
|
259
|
+
实际发布命令(会上传包,请确认版本与目标 registry 后再执行):
|
|
260
|
+
|
|
261
|
+
```powershell
|
|
262
|
+
npm run publish:npm # 上传到 npmjs
|
|
263
|
+
```
|
|
264
|
+
|
|
265
|
+
`publish:npm` 与 `publish:github` 分别向 npmjs 与 GitHub Packages 发布;`publishConfig` 只声明 `access: public`,项目不附带强制 registry 的 `.npmrc`。GitHub Actions 发布前会核对 tag 与 `package.json` 版本、包名和 `access`,发布后再做 `npm view` 校验。发布前请确认 `package.json` 版本与 tag 一致,并核对目标 registry。
|
|
266
|
+
|
|
267
|
+
## 开发与测试
|
|
268
|
+
|
|
269
|
+
```powershell
|
|
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
|
+
```
|
|
275
|
+
|
|
276
|
+
测试覆盖:OpenAI 显式与宿主托管模式、三种 OAuth 路由、SSE;Google Interactions API 的文生图与多图编辑、尺寸参数、参考图限制和 PNG/JPEG 输出;两路的权限顺序、错误脱敏、取消/超时不落盘、不覆盖已有文件;另有发布元数据测试。
|
|
277
|
+
|
|
278
|
+
## License
|
|
279
|
+
|
|
280
|
+
MIT © MyOldTime
|
package/VALIDATION.md
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
# 验证记录
|
|
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
|
+
|
|
11
|
+
测试日期:2026-10-30。宿主 OpenCode 2.2.0,Node.js 24.18.0,Windows。
|
|
12
|
+
|
|
13
|
+
### 自动化测试
|
|
14
|
+
|
|
15
|
+
- `npm ci --ignore-scripts`:通过(无新增依赖,0 vulnerabilities)。
|
|
16
|
+
- `npm run check`:通过。
|
|
17
|
+
- `npm test`:36 项通过,无跳过(`test.mjs` 26 项 + `release.test.mjs` 10 项)。
|
|
18
|
+
- `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`)。
|
|
19
|
+
- 包内容使用 `package.json` 的 `files` 白名单,不包含凭据、原始响应、测试图片、测试脚本、`.github` 或机器配置。
|
|
20
|
+
- 路由测试覆盖显式 API key、宿主托管 API key 和三种 OAuth 方法;另覆盖权限、凭据刷新委托、严格配置校验、错误脱敏、流式解析、取消与超时、引用图片以及文件不覆盖。
|
|
21
|
+
|
|
22
|
+
### 重命名与双源发布准备(离线)
|
|
23
|
+
|
|
24
|
+
- 本轮只做元数据与文档重命名,未重新联网生成图片:`core.mjs` 逻辑未改动。改名前后的 SHA256 均为 `D04176C047A350BD2198A56EFE024385B1DDB6E862571293010D0EDEF7EFC896`;`index.js` 仅插件 ID 从 `myoldtime.codex-proxy-imagegen` 改为 `opencode-codex-imagegen`,工具名 `proxy_imagegen` 不变。
|
|
25
|
+
- 包名在 npmjs 与 GitHub Packages 统一为 `@myoldtime/opencode-codex-imagegen`,`package.json` 与 `package-lock.json` 同名同版本(0.1.0,MIT)。
|
|
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 白名单不含凭据与测试。
|
|
27
|
+
- GitHub Actions 只在 Release `published` 时发布 GitHub Packages;npmjs 由本机已登录账号在用户未来单独确认后执行 `npm run publish:npm`。本机 npm 登录不会传入 Actions,因此没有配置 `NPM_TOKEN`,也未做 OIDC 自动授权。
|
|
28
|
+
|
|
29
|
+
### 真实请求(历史记录,本轮未重复执行)
|
|
30
|
+
|
|
31
|
+
下表是代码与账号能力的历史验证,不属于本轮离线重命名验证;本轮未再次联网生成,也未验证真实发布。
|
|
32
|
+
|
|
33
|
+
| 通道 | 当前证据 | 范围 |
|
|
34
|
+
|---|---|---|
|
|
35
|
+
| 显式 API 配置 | 成功生成 PNG,1536×1024 | 通过既有 Responses 兼容中转,非官方 API key 直连验证 |
|
|
36
|
+
| Codex browser (legacy) | 成功生成 PNG,1536×1024,约 21 秒 | 在隔离测试插件中调用生产核心,并使用真实宿主 `connection.active/resolve`,没有手动读取或刷新凭据文件;临时会话已清理 |
|
|
37
|
+
| Sign in with ChatGPT | 上游拒绝:HTTP 400 / `subscription_sharing_unsupported_capability`,约 1.8 秒 | 用户确认准备后,经真实宿主解析此登录方式并请求官方 Responses;没有生成图片,没有重试或换通道;不是生图成功 |
|
|
38
|
+
| Codex device code (legacy) | 成功生成 PNG,1536×1024,约 23 秒 | 用户确认准备后,经真实宿主 `connection.active/resolve` 解析 device-code 登录;临时会话已清理 |
|
|
39
|
+
|
|
40
|
+
实际图片尺寸可能由上游调整,不保证与请求尺寸完全一致。验证仅针对当次账号、模型和服务状态,不承诺所有订阅与未来上游版本均可用。
|
|
41
|
+
|
|
42
|
+
legacy 验证发现真实响应可能省略 Content-Type,已修复为有界前缀格式检测,并新增单字节分片回归;另外通过保留的真实响应离线重放恢复图片,未为重放重复发起请求。
|
|
43
|
+
|
|
44
|
+
### 发布与安装
|
|
45
|
+
|
|
46
|
+
**当前状态:尚未创建远端仓库、未 push、未打 tag、未发布 Release、未运行任何发布命令,也未切换正在使用的插件。** 本节命令只有用户未来单独确认后才会使用。
|
|
47
|
+
|
|
48
|
+
- 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 映射)。
|
|
49
|
+
- 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) 为准。
|
|
50
|
+
- 安装应使用固定版本,并确认宿主显示插件来源为 package 而非旧本地目录。README 中在线安装说明均标注为"发布后可用"。
|
package/core.mjs
ADDED
|
@@ -0,0 +1,561 @@
|
|
|
1
|
+
import { readFile, mkdir, open, unlink } from "node:fs/promises"
|
|
2
|
+
import path from "node:path"
|
|
3
|
+
|
|
4
|
+
// OpenAI Responses endpoints. Image generation always uses the hosted `image_generation`
|
|
5
|
+
// tool on a Responses request, never the Images API.
|
|
6
|
+
export const DEFAULT_OPENAI_BASE_URL = "https://api.openai.com/v1"
|
|
7
|
+
export const OPENAI_RESPONSES_URL = "https://api.openai.com/v1/responses"
|
|
8
|
+
export const CODEX_RESPONSES_URL = "https://chatgpt.com/backend-api/codex/responses"
|
|
9
|
+
|
|
10
|
+
const DEFAULT_GOOGLE_BASE_URL = "https://generativelanguage.googleapis.com"
|
|
11
|
+
const GOOGLE_API_REVISION = "2026-05-20"
|
|
12
|
+
const DEFAULT_GOOGLE_MODEL = "gemini-nano-banana-2.1"
|
|
13
|
+
const GOOGLE_INLINE_LIMIT = 20_000_000
|
|
14
|
+
const GOOGLE_INLINE_LIMIT_ERROR = "Google inline image requests must be at most 20 MB including base64; resize or compress your reference images"
|
|
15
|
+
export const GOOGLE_MAX_REFERENCES = 14
|
|
16
|
+
export const GOOGLE_ASPECT_RATIOS = Object.freeze(["1:1", "2:3", "3:2", "3:4", "4:3", "4:5", "5:4", "9:16", "16:9", "21:9", "1:4", "4:1", "1:8", "8:1"])
|
|
17
|
+
export const GOOGLE_IMAGE_SIZES = Object.freeze(["1K", "2K", "4K"])
|
|
18
|
+
|
|
19
|
+
// OAuth sign-in methods that this plugin knows how to route. Anything else is rejected
|
|
20
|
+
// instead of guessing an endpoint.
|
|
21
|
+
export const SUPPORTED_OAUTH_METHODS = ["chatgpt-token-sharing", "chatgpt-browser", "chatgpt-headless"]
|
|
22
|
+
const LEGACY_METHODS = new Set(["chatgpt-browser", "chatgpt-headless"])
|
|
23
|
+
|
|
24
|
+
// Only these upstream codes may appear in an error message. Everything else is reported
|
|
25
|
+
// as a generic upstream failure so account data never leaks.
|
|
26
|
+
const SAFE_ERROR_CODES = new Set([
|
|
27
|
+
"subscription_sharing_usage_limit_exceeded",
|
|
28
|
+
"subscription_sharing_user_not_eligible",
|
|
29
|
+
"subscription_sharing_unsupported_capability",
|
|
30
|
+
"subscription_sharing_route_not_supported",
|
|
31
|
+
"subscription_sharing_invalid_user",
|
|
32
|
+
"chatpass_v2_scope_not_authorized",
|
|
33
|
+
"chatpass_v2_invalid_authorization_context",
|
|
34
|
+
])
|
|
35
|
+
|
|
36
|
+
const DEFAULT_MODEL = "gpt-6.1-sol"
|
|
37
|
+
const DEFAULT_TIMEOUT_MS = 240000
|
|
38
|
+
const INSTRUCTIONS = "Generate the requested image by invoking image_generation exactly once. Do not respond with text only."
|
|
39
|
+
|
|
40
|
+
const OMIT_HINT = "omit options.base_url and options.key entirely to use the OpenAI account signed in to OpenCode"
|
|
41
|
+
|
|
42
|
+
export function pluginConfig(options = {}) {
|
|
43
|
+
if (options === null || typeof options !== "object" || Array.isArray(options)) throw new Error("Plugin options must be an object")
|
|
44
|
+
const provider = options.provider === undefined ? "openai" : options.provider
|
|
45
|
+
if (!["openai", "google"].includes(provider)) throw new Error("options.provider must be openai or google")
|
|
46
|
+
const model = options.model ?? (provider === "google" ? DEFAULT_GOOGLE_MODEL : DEFAULT_MODEL)
|
|
47
|
+
if (typeof model !== "string" || !model.trim()) throw new Error("model must be a nonempty string")
|
|
48
|
+
const timeoutMs = options.timeout_ms ?? DEFAULT_TIMEOUT_MS
|
|
49
|
+
if (!Number.isInteger(timeoutMs) || timeoutMs <= 0) throw new Error("timeout_ms must be a positive integer")
|
|
50
|
+
|
|
51
|
+
if (provider === "google") {
|
|
52
|
+
if (options.reasoning_effort !== undefined || options.fast_mode !== undefined) {
|
|
53
|
+
throw new Error("options.reasoning_effort and options.fast_mode are only supported by the OpenAI provider")
|
|
54
|
+
}
|
|
55
|
+
if (typeof options.key !== "string" || !options.key.trim() || options.key.trim().startsWith("{env:")) {
|
|
56
|
+
throw new Error("The Google provider requires a valid options.key; set GEMINI_API_KEY in the OpenCode environment and use {env:GEMINI_API_KEY}")
|
|
57
|
+
}
|
|
58
|
+
const endpoint = googleInteractionsURL(options.base_url === undefined ? DEFAULT_GOOGLE_BASE_URL : options.base_url)
|
|
59
|
+
return { provider, mode: "explicit", endpoint, apiKey: options.key.trim(), model: model.trim(), timeoutMs }
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
// Presence is explicit: an empty, null, blank or unresolved value is a configuration error,
|
|
63
|
+
// never a silent fallback. Only a fully omitted pair uses the host-managed account.
|
|
64
|
+
const hasBase = options.base_url !== undefined
|
|
65
|
+
const hasKey = options.key !== undefined
|
|
66
|
+
if (hasBase && (typeof options.base_url !== "string" || !options.base_url.trim())) {
|
|
67
|
+
throw new Error(`options.base_url must be a non-empty string; ${OMIT_HINT}`)
|
|
68
|
+
}
|
|
69
|
+
if (hasKey && (typeof options.key !== "string" || !options.key.trim())) {
|
|
70
|
+
throw new Error(`options.key must be a non-empty string; ${OMIT_HINT}`)
|
|
71
|
+
}
|
|
72
|
+
const baseURL = hasBase ? options.base_url.trim() : ""
|
|
73
|
+
const apiKey = hasKey ? options.key.trim() : ""
|
|
74
|
+
if (apiKey.startsWith("{env:")) {
|
|
75
|
+
throw new Error("options.key contains an unresolved environment substitution; load the variable into the OpenCode environment configuration (or the current session) and try again, or omit key to use the signed-in OpenAI account")
|
|
76
|
+
}
|
|
77
|
+
if (hasBase && !hasKey) {
|
|
78
|
+
throw new Error("options.base_url requires options.key; configure both or omit both to use the signed-in OpenAI account")
|
|
79
|
+
}
|
|
80
|
+
if (options.reasoning_effort !== undefined && !["none", "minimal", "low", "medium", "high", "xhigh"].includes(options.reasoning_effort)) {
|
|
81
|
+
throw new Error("reasoning_effort must be none, minimal, low, medium, high or xhigh (model support varies)")
|
|
82
|
+
}
|
|
83
|
+
if (options.fast_mode !== undefined && typeof options.fast_mode !== "boolean") throw new Error("fast_mode must be boolean")
|
|
84
|
+
// key only: fall back to the public OpenAI endpoint. Both present: explicit proxy. Neither: host-managed.
|
|
85
|
+
const explicit = Boolean(apiKey)
|
|
86
|
+
const explicitBase = explicit ? baseURL || DEFAULT_OPENAI_BASE_URL : undefined
|
|
87
|
+
// Fail on a malformed proxy URL before any session, permission or network work happens.
|
|
88
|
+
if (explicitBase) responsesURL(explicitBase)
|
|
89
|
+
return {
|
|
90
|
+
provider,
|
|
91
|
+
mode: explicit ? "explicit" : "managed",
|
|
92
|
+
baseURL: explicitBase,
|
|
93
|
+
apiKey: explicit ? apiKey : undefined,
|
|
94
|
+
model: model.trim(),
|
|
95
|
+
reasoningEffort: options.reasoning_effort,
|
|
96
|
+
fastMode: options.fast_mode ?? false,
|
|
97
|
+
timeoutMs,
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
export function responsesURL(baseURL) {
|
|
102
|
+
const url = new URL(baseURL)
|
|
103
|
+
if (!["http:", "https:"].includes(url.protocol) || url.username || url.password || url.search || url.hash) {
|
|
104
|
+
throw new Error("baseURL must be an HTTP(S) URL without credentials, query or fragment")
|
|
105
|
+
}
|
|
106
|
+
url.pathname = url.pathname.replace(/\/+$/, "")
|
|
107
|
+
if (!url.pathname.endsWith("/responses")) url.pathname += "/responses"
|
|
108
|
+
return url.toString()
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
function googleInteractionsURL(baseURL) {
|
|
112
|
+
const invalid = () => new Error("Google options.base_url must be an HTTP(S) URL without credentials, query or fragment")
|
|
113
|
+
if (typeof baseURL !== "string" || !/^https?:\/\//i.test(baseURL.trim()) || /[?#]/.test(baseURL)) throw invalid()
|
|
114
|
+
let url
|
|
115
|
+
try { url = new URL(baseURL.trim()) } catch { throw invalid() }
|
|
116
|
+
if (url.username || url.password) throw invalid()
|
|
117
|
+
const pathname = url.pathname.replace(/\/+$/, "")
|
|
118
|
+
if (pathname.endsWith("/interactions")) url.pathname = pathname
|
|
119
|
+
else if (/\/v1(?:beta)?$/.test(pathname)) url.pathname = `${pathname}/interactions`
|
|
120
|
+
else url.pathname = `${pathname}/v1beta/interactions`
|
|
121
|
+
return url.toString()
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
export function abortError() {
|
|
125
|
+
const error = new Error("Image generation aborted")
|
|
126
|
+
error.name = "AbortError"
|
|
127
|
+
return error
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
// Messages that this plugin produced itself and may be shown verbatim.
|
|
131
|
+
class ImageResponseError extends Error {}
|
|
132
|
+
|
|
133
|
+
export function timeoutError() {
|
|
134
|
+
return new Error("Image request timed out")
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
function abortIfNeeded(signal) {
|
|
138
|
+
if (signal?.aborted) throw abortError()
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
function throwIfSettled(signal, combinedSignal) {
|
|
142
|
+
if (signal?.aborted) throw abortError()
|
|
143
|
+
if (combinedSignal?.aborted) throw timeoutError()
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
function connectionError(detail) {
|
|
147
|
+
return new Error(`${detail} Configure options.base_url and options.key to use a proxy instead.`)
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
// Resolves the request route for this call. Explicit options never touch the host credential
|
|
151
|
+
// API; managed mode re-resolves the connection on every call so OpenCode owns refresh.
|
|
152
|
+
export async function resolveRoute(config, ctx) {
|
|
153
|
+
if (config.provider === "google") {
|
|
154
|
+
return { route: "google", method: "api-key", url: config.endpoint, access: config.apiKey }
|
|
155
|
+
}
|
|
156
|
+
if (config.mode === "explicit") {
|
|
157
|
+
return { route: "proxy", method: "options", url: responsesURL(config.baseURL), access: config.apiKey }
|
|
158
|
+
}
|
|
159
|
+
const integration = ctx?.integration?.connection
|
|
160
|
+
if (!integration || typeof integration.active !== "function" || typeof integration.resolve !== "function") {
|
|
161
|
+
throw connectionError("OpenCode did not expose an OpenAI connection to this plugin.")
|
|
162
|
+
}
|
|
163
|
+
let connection
|
|
164
|
+
try {
|
|
165
|
+
connection = await integration.active("openai")
|
|
166
|
+
} catch {
|
|
167
|
+
throw connectionError("OpenCode could not read the OpenAI connection.")
|
|
168
|
+
}
|
|
169
|
+
if (!connection) {
|
|
170
|
+
throw connectionError("No OpenAI account is connected in OpenCode. Sign in from OpenCode (Sign in with ChatGPT) or configure options.base_url and options.key.")
|
|
171
|
+
}
|
|
172
|
+
let credential
|
|
173
|
+
try {
|
|
174
|
+
credential = await integration.resolve(connection)
|
|
175
|
+
} catch {
|
|
176
|
+
throw connectionError("OpenCode could not provide a usable OpenAI credential; the sign-in may have expired or need attention. Sign in again.")
|
|
177
|
+
}
|
|
178
|
+
if (!credential || typeof credential !== "object") {
|
|
179
|
+
throw connectionError("OpenCode returned no OpenAI credential for the connected account. Sign in again.")
|
|
180
|
+
}
|
|
181
|
+
if (credential.type === "key") {
|
|
182
|
+
if (typeof credential.key !== "string" || !credential.key.trim()) {
|
|
183
|
+
throw connectionError("The OpenAI connection returned an empty API key.")
|
|
184
|
+
}
|
|
185
|
+
return { route: "openai-key", method: "api-key", url: OPENAI_RESPONSES_URL, access: credential.key.trim() }
|
|
186
|
+
}
|
|
187
|
+
if (credential.type !== "oauth") {
|
|
188
|
+
throw connectionError("The OpenAI connection returned an unsupported credential type.")
|
|
189
|
+
}
|
|
190
|
+
const methodID = credential.methodID
|
|
191
|
+
if (!SUPPORTED_OAUTH_METHODS.includes(methodID)) {
|
|
192
|
+
// Never echo the raw method value: it may carry arbitrary credential data.
|
|
193
|
+
throw connectionError(`Unsupported OpenAI sign-in method. Supported methods: ${SUPPORTED_OAUTH_METHODS.join(", ")}.`)
|
|
194
|
+
}
|
|
195
|
+
if (typeof credential.access !== "string" || !credential.access.trim()) {
|
|
196
|
+
throw connectionError("OpenCode returned an empty or expired OpenAI access token. Sign in again.")
|
|
197
|
+
}
|
|
198
|
+
if (typeof credential.expires === "number" && credential.expires <= Date.now()) {
|
|
199
|
+
throw connectionError("The OpenAI access token has expired and could not be refreshed. Sign in again.")
|
|
200
|
+
}
|
|
201
|
+
const access = credential.access.trim()
|
|
202
|
+
if (LEGACY_METHODS.has(methodID)) {
|
|
203
|
+
const accountID = credential.metadata?.accountID
|
|
204
|
+
return {
|
|
205
|
+
route: methodID,
|
|
206
|
+
method: methodID,
|
|
207
|
+
url: CODEX_RESPONSES_URL,
|
|
208
|
+
access,
|
|
209
|
+
accountID: typeof accountID === "string" && accountID ? accountID : undefined,
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
return { route: "chatgpt-token-sharing", method: methodID, url: OPENAI_RESPONSES_URL, access }
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
export function requestHeaders(route, sessionID) {
|
|
216
|
+
if (route.route === "google") return {
|
|
217
|
+
"x-goog-api-key": route.access,
|
|
218
|
+
"Api-Revision": GOOGLE_API_REVISION,
|
|
219
|
+
"Content-Type": "application/json",
|
|
220
|
+
}
|
|
221
|
+
const headers = {
|
|
222
|
+
Authorization: `Bearer ${route.access}`,
|
|
223
|
+
"Content-Type": "application/json",
|
|
224
|
+
Accept: "text/event-stream",
|
|
225
|
+
}
|
|
226
|
+
if (LEGACY_METHODS.has(route.route)) {
|
|
227
|
+
headers.originator = "opencode"
|
|
228
|
+
if (route.accountID) headers["ChatGPT-Account-Id"] = route.accountID
|
|
229
|
+
}
|
|
230
|
+
if (route.route !== "proxy" && route.route !== "openai-key" && typeof sessionID === "string" && sessionID) {
|
|
231
|
+
headers["session-id"] = sessionID
|
|
232
|
+
if (route.route === "chatgpt-token-sharing") {
|
|
233
|
+
headers["thread-id"] = sessionID
|
|
234
|
+
headers["x-client-request-id"] = sessionID
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
return headers
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
function imageType(bytes) {
|
|
241
|
+
if (bytes.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]))) return "image/png"
|
|
242
|
+
if (bytes[0] === 255 && bytes[1] === 216 && bytes[2] === 255) return "image/jpeg"
|
|
243
|
+
if (["GIF87a", "GIF89a"].includes(bytes.subarray(0, 6).toString())) return "image/gif"
|
|
244
|
+
if (bytes.subarray(0, 4).toString() === "RIFF" && bytes.subarray(8, 12).toString() === "WEBP") return "image/webp"
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
function outputFormat(out) {
|
|
248
|
+
const extension = path.extname(out).toLowerCase()
|
|
249
|
+
if (extension === ".png") return "image/png"
|
|
250
|
+
if (extension === ".jpg" || extension === ".jpeg") return "image/jpeg"
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
export function validateInput(input, provider = "openai") {
|
|
254
|
+
if (!input || typeof input.prompt !== "string" || !input.prompt.trim()) throw new Error("prompt is required")
|
|
255
|
+
const format = typeof input.out === "string" ? outputFormat(input.out) : undefined
|
|
256
|
+
if (input.images !== undefined && (!Array.isArray(input.images) || input.images.some(p => typeof p !== "string"))) throw new Error("images must be file paths")
|
|
257
|
+
if (provider === "google") {
|
|
258
|
+
if (!format) throw new Error("out must be a .png, .jpg or .jpeg file path for Google")
|
|
259
|
+
if ((input.size !== undefined && input.size !== "auto") || (input.quality !== undefined && input.quality !== "auto")) {
|
|
260
|
+
throw new Error("The Google provider uses aspect_ratio and image_size instead of size and quality")
|
|
261
|
+
}
|
|
262
|
+
if (input.aspect_ratio !== undefined && !GOOGLE_ASPECT_RATIOS.includes(input.aspect_ratio)) throw new Error("Invalid Google aspect_ratio")
|
|
263
|
+
if (input.image_size !== undefined && !GOOGLE_IMAGE_SIZES.includes(input.image_size)) throw new Error("Google image_size must be 1K, 2K or 4K")
|
|
264
|
+
if (input.images?.length > GOOGLE_MAX_REFERENCES) throw new Error(`Google image generation accepts at most ${GOOGLE_MAX_REFERENCES} reference images; some models accept fewer`)
|
|
265
|
+
return
|
|
266
|
+
}
|
|
267
|
+
if (format !== "image/png") throw new Error("out must be a .png file path")
|
|
268
|
+
if (input.aspect_ratio !== undefined || input.image_size !== undefined) throw new Error("aspect_ratio and image_size are only supported by the Google provider")
|
|
269
|
+
if (input.quality !== undefined && !["auto", "low", "medium", "high"].includes(input.quality)) throw new Error("Invalid quality")
|
|
270
|
+
if (input.size !== undefined && input.size !== "auto") {
|
|
271
|
+
const match = /^(\d+)x(\d+)$/.exec(input.size)
|
|
272
|
+
const w = Number(match?.[1]), h = Number(match?.[2])
|
|
273
|
+
if (!match || !w || !h || w % 16 || h % 16 || Math.max(w, h) > 3840 || Math.max(w, h) / Math.min(w, h) > 3 || w * h < 655360 || w * h > 8294400) {
|
|
274
|
+
throw new Error("size must be auto or WIDTHxHEIGHT (16px multiples, max edge 3840, aspect <= 3:1, pixels 655360–8294400)")
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
function safeCode(value) {
|
|
280
|
+
return typeof value === "string" && SAFE_ERROR_CODES.has(value) ? value : undefined
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
function safeCodeFrom(payload) {
|
|
284
|
+
return safeCode(payload?.error?.code) ?? safeCode(payload?.response?.error?.code)
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
function resultFromEvent(event) {
|
|
288
|
+
if (event.type === "error" || event.type === "response.failed" || event.type === "response.incomplete") {
|
|
289
|
+
const code = safeCodeFrom(event)
|
|
290
|
+
throw new ImageResponseError(`Image response failed${code ? ` (${code})` : ""}`)
|
|
291
|
+
}
|
|
292
|
+
if (event.type === "response.output_item.done" && event.item?.type === "image_generation_call" && event.item.result) return event.item.result
|
|
293
|
+
return event.response?.output?.find(item => item.type === "image_generation_call" && item.result)?.result
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
export function parseEvent(text) {
|
|
297
|
+
try {
|
|
298
|
+
return JSON.parse(text)
|
|
299
|
+
} catch {
|
|
300
|
+
throw new ImageResponseError("Image response contained invalid JSON")
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
async function httpError(response, { signal, combinedSignal } = {}) {
|
|
305
|
+
let text = ""
|
|
306
|
+
try {
|
|
307
|
+
text = await response.text()
|
|
308
|
+
} catch {
|
|
309
|
+
text = ""
|
|
310
|
+
}
|
|
311
|
+
throwIfSettled(signal, combinedSignal)
|
|
312
|
+
let payload
|
|
313
|
+
try {
|
|
314
|
+
payload = text ? JSON.parse(text) : undefined
|
|
315
|
+
} catch {
|
|
316
|
+
payload = undefined
|
|
317
|
+
}
|
|
318
|
+
const code = safeCodeFrom(payload)
|
|
319
|
+
return new ImageResponseError(`Image request failed: HTTP ${response.status}${code ? ` (${code})` : ""}`)
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
// SSE frames may be split anywhere, including inside UTF-8 characters and CRLF.
|
|
323
|
+
export async function readImageResponse(response) {
|
|
324
|
+
if (!response.body) throw new ImageResponseError("Empty image response")
|
|
325
|
+
// Some Codex gateways return valid SSE without a Content-Type header. Detect
|
|
326
|
+
// the wire format from a bounded prefix instead of mistaking that stream for JSON.
|
|
327
|
+
const contentType = response.headers.get("content-type")?.toLowerCase() ?? ""
|
|
328
|
+
let format = contentType.includes("text/event-stream") ? "sse" : contentType.includes("application/json") ? "json" : "detect"
|
|
329
|
+
const reader = response.body.getReader()
|
|
330
|
+
const decoder = new TextDecoder()
|
|
331
|
+
let pending = "", data = []
|
|
332
|
+
const dispatch = () => {
|
|
333
|
+
const text = data.join("\n")
|
|
334
|
+
data = []
|
|
335
|
+
if (!text || text === "[DONE]") return
|
|
336
|
+
return resultFromEvent(parseEvent(text))
|
|
337
|
+
}
|
|
338
|
+
const line = text => {
|
|
339
|
+
if (!text) return dispatch()
|
|
340
|
+
if (text === "data") data.push("")
|
|
341
|
+
else if (text.startsWith("data:")) data.push(text.slice(5).replace(/^ /, ""))
|
|
342
|
+
}
|
|
343
|
+
try {
|
|
344
|
+
while (true) {
|
|
345
|
+
const { value, done } = await reader.read()
|
|
346
|
+
pending += done ? decoder.decode() : decoder.decode(value, { stream: true })
|
|
347
|
+
if (format === "detect") {
|
|
348
|
+
const prefix = pending.trimStart()
|
|
349
|
+
if (/^[\[{]/.test(prefix)) format = "json"
|
|
350
|
+
else if (/^(?:(?:data|event|id|retry)(?::|\r?\n)|:)/.test(prefix)) {
|
|
351
|
+
format = "sse"
|
|
352
|
+
pending = prefix
|
|
353
|
+
} else if (done || pending.length > 65536 || prefix.includes("\n")) {
|
|
354
|
+
throw new ImageResponseError("Image response contained invalid JSON or SSE")
|
|
355
|
+
} else continue
|
|
356
|
+
}
|
|
357
|
+
if (format === "json") {
|
|
358
|
+
if (!done) continue
|
|
359
|
+
const result = resultFromEvent({ type: "response.completed", response: parseEvent(pending) })
|
|
360
|
+
if (!result) throw new ImageResponseError("No image_generation_call.result in JSON response")
|
|
361
|
+
return result
|
|
362
|
+
}
|
|
363
|
+
let index
|
|
364
|
+
while ((index = pending.indexOf("\n")) !== -1) {
|
|
365
|
+
const text = pending.slice(0, index).replace(/\r$/, "")
|
|
366
|
+
pending = pending.slice(index + 1)
|
|
367
|
+
const result = line(text)
|
|
368
|
+
if (result) return result
|
|
369
|
+
}
|
|
370
|
+
if (done) {
|
|
371
|
+
if (pending) line(pending.replace(/\r$/, ""))
|
|
372
|
+
const result = dispatch()
|
|
373
|
+
if (result) return result
|
|
374
|
+
break
|
|
375
|
+
}
|
|
376
|
+
}
|
|
377
|
+
} finally {
|
|
378
|
+
await reader.cancel().catch(() => {})
|
|
379
|
+
reader.releaseLock()
|
|
380
|
+
}
|
|
381
|
+
throw new ImageResponseError("Response ended without an image_generation_call.result")
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
// Google returns raw Interactions steps, not the SDK's computed output_image.
|
|
385
|
+
async function readGoogleImageResponse(response) {
|
|
386
|
+
const payload = parseEvent(await response.text())
|
|
387
|
+
if (payload?.error || payload?.status !== "completed") {
|
|
388
|
+
throw new ImageResponseError("Google image interaction did not complete")
|
|
389
|
+
}
|
|
390
|
+
let image
|
|
391
|
+
for (const step of Array.isArray(payload?.steps) ? payload.steps : []) {
|
|
392
|
+
if (step?.type !== "model_output" || !Array.isArray(step.content)) continue
|
|
393
|
+
for (const part of step.content) {
|
|
394
|
+
if (part?.type === "image" && typeof part.data === "string" && part.data) image = part
|
|
395
|
+
}
|
|
396
|
+
}
|
|
397
|
+
if (!image) throw new ImageResponseError("Google response contained no generated image")
|
|
398
|
+
return image
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
export async function savePNG(out, directory, base64, signal) {
|
|
402
|
+
return saveImage(out, directory, base64, "image/png", signal)
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
async function saveImage(out, directory, base64, format, signal, googleImage) {
|
|
406
|
+
if (typeof base64 !== "string" || !/^[A-Za-z0-9+/]+={0,2}$/.test(base64) || base64.length % 4) throw new Error("Invalid image base64")
|
|
407
|
+
let bytes = Buffer.from(base64, "base64")
|
|
408
|
+
const actual = imageType(bytes)
|
|
409
|
+
if (googleImage?.mime_type !== undefined && googleImage.mime_type !== actual) {
|
|
410
|
+
throw new Error("Google image MIME type does not match its bytes")
|
|
411
|
+
}
|
|
412
|
+
if (googleImage && actual === "image/jpeg" && format === "image/png") {
|
|
413
|
+
abortIfNeeded(signal)
|
|
414
|
+
const [{ default: jpeg }, { PNG }] = await Promise.all([import("jpeg-js"), import("pngjs")])
|
|
415
|
+
try {
|
|
416
|
+
const raster = jpeg.decode(bytes, { maxResolutionInMP: 20, maxMemoryUsageInMB: 384, tolerantDecoding: false })
|
|
417
|
+
bytes = PNG.sync.write(raster)
|
|
418
|
+
} catch {
|
|
419
|
+
throw new Error("Could not convert Google JPEG to PNG")
|
|
420
|
+
}
|
|
421
|
+
} else if (actual !== format) throw new Error(`Backend did not return ${format === "image/png" ? "PNG" : "JPEG"}`)
|
|
422
|
+
abortIfNeeded(signal)
|
|
423
|
+
const target = path.resolve(directory, out)
|
|
424
|
+
await mkdir(path.dirname(target), { recursive: true })
|
|
425
|
+
const extension = path.extname(target)
|
|
426
|
+
const stem = target.slice(0, -extension.length)
|
|
427
|
+
for (let version = 1; ; version++) {
|
|
428
|
+
const file = version === 1 ? target : `${stem}-v${version}${extension.toLowerCase()}`
|
|
429
|
+
let handle
|
|
430
|
+
try { handle = await open(file, "wx") } catch (error) {
|
|
431
|
+
if (error.code === "EEXIST") continue
|
|
432
|
+
throw error
|
|
433
|
+
}
|
|
434
|
+
// Only files created by this call (open "wx") are ever removed; pre-existing files stay untouched.
|
|
435
|
+
let stillOpen = true
|
|
436
|
+
try {
|
|
437
|
+
await handle.writeFile(bytes)
|
|
438
|
+
await handle.close()
|
|
439
|
+
stillOpen = false
|
|
440
|
+
} catch (error) {
|
|
441
|
+
if (stillOpen) await handle.close().catch(() => {})
|
|
442
|
+
await unlink(file).catch(() => {})
|
|
443
|
+
throw error
|
|
444
|
+
}
|
|
445
|
+
if (signal?.aborted) {
|
|
446
|
+
// Cancelled while persisting: remove the file we just created, never a pre-existing one.
|
|
447
|
+
await unlink(file).catch(() => {})
|
|
448
|
+
throw abortError()
|
|
449
|
+
}
|
|
450
|
+
return { out: file, versioned: version > 1, bytes: bytes.length }
|
|
451
|
+
}
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
function googleBody(input, config, references, format) {
|
|
455
|
+
const responseFormat = {
|
|
456
|
+
...(format === "image/jpeg" ? { mime_type: format } : {}),
|
|
457
|
+
...(input.aspect_ratio ? { aspect_ratio: input.aspect_ratio } : {}),
|
|
458
|
+
...(input.image_size ? { image_size: input.image_size } : {}),
|
|
459
|
+
}
|
|
460
|
+
return {
|
|
461
|
+
model: config.model,
|
|
462
|
+
input: [{ type: "text", text: input.prompt }, ...references.map(({ mime, data }) => ({ type: "image", mime_type: mime, data }))],
|
|
463
|
+
...(Object.keys(responseFormat).length ? { response_format: { type: "image", ...responseFormat } } : {}),
|
|
464
|
+
}
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
function openAIBody(input, config, references) {
|
|
468
|
+
const content = [{ type: "input_text", text: input.prompt }, ...references.map(({ mime, data }) => ({
|
|
469
|
+
type: "input_image",
|
|
470
|
+
image_url: `data:${mime};base64,${data}`,
|
|
471
|
+
}))]
|
|
472
|
+
return {
|
|
473
|
+
model: config.model,
|
|
474
|
+
instructions: INSTRUCTIONS,
|
|
475
|
+
input: [{ role: "user", content }],
|
|
476
|
+
tools: [{ type: "image_generation", output_format: "png", quality: input.quality ?? "auto", ...(input.size ? { size: input.size } : {}) }],
|
|
477
|
+
tool_choice: { type: "image_generation" },
|
|
478
|
+
stream: true,
|
|
479
|
+
store: false,
|
|
480
|
+
...(config.reasoningEffort !== undefined ? { reasoning: { effort: config.reasoningEffort } } : {}),
|
|
481
|
+
...(config.fastMode ? { service_tier: "priority" } : {}),
|
|
482
|
+
}
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
export async function generateImage(input, config, directory, env = {}) {
|
|
486
|
+
const { ctx, signal, sessionID, fetcher = fetch } = env
|
|
487
|
+
validateInput(input, config.provider)
|
|
488
|
+
const google = config.provider === "google"
|
|
489
|
+
const format = outputFormat(input.out)
|
|
490
|
+
abortIfNeeded(signal)
|
|
491
|
+
// Credentials are resolved per call; explicit options never consult the host.
|
|
492
|
+
const route = await resolveRoute(config, ctx)
|
|
493
|
+
abortIfNeeded(signal)
|
|
494
|
+
const references = []
|
|
495
|
+
let encodedBytes = 0
|
|
496
|
+
const referenceFormats = google ? ["image/png", "image/jpeg", "image/webp"] : ["image/png", "image/jpeg", "image/gif", "image/webp"]
|
|
497
|
+
for (const file of input.images ?? []) {
|
|
498
|
+
const bytes = await readFile(path.resolve(directory, file), { signal })
|
|
499
|
+
const mime = imageType(bytes)
|
|
500
|
+
if (!referenceFormats.includes(mime)) {
|
|
501
|
+
throw new Error(google ? "Unsupported Google reference image: use PNG, JPEG or WebP" : "Unsupported reference image: use PNG, JPEG, GIF or WebP")
|
|
502
|
+
}
|
|
503
|
+
if (google) {
|
|
504
|
+
encodedBytes += Math.ceil(bytes.length / 3) * 4
|
|
505
|
+
if (encodedBytes > GOOGLE_INLINE_LIMIT) throw new Error(GOOGLE_INLINE_LIMIT_ERROR)
|
|
506
|
+
}
|
|
507
|
+
references.push({ mime, data: bytes.toString("base64") })
|
|
508
|
+
}
|
|
509
|
+
const body = JSON.stringify(google ? googleBody(input, config, references, format) : openAIBody(input, config, references))
|
|
510
|
+
if (google && Buffer.byteLength(body) > GOOGLE_INLINE_LIMIT) {
|
|
511
|
+
throw new Error(GOOGLE_INLINE_LIMIT_ERROR)
|
|
512
|
+
}
|
|
513
|
+
const timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS
|
|
514
|
+
if (!Number.isInteger(timeoutMs) || timeoutMs <= 0) throw new Error("timeoutMs must be a positive integer")
|
|
515
|
+
const combinedSignal = signal ? AbortSignal.any([signal, AbortSignal.timeout(timeoutMs)]) : AbortSignal.timeout(timeoutMs)
|
|
516
|
+
abortIfNeeded(signal)
|
|
517
|
+
let response
|
|
518
|
+
try {
|
|
519
|
+
response = await fetcher(route.url, {
|
|
520
|
+
method: "POST",
|
|
521
|
+
signal: combinedSignal,
|
|
522
|
+
redirect: "error",
|
|
523
|
+
headers: requestHeaders(route, sessionID),
|
|
524
|
+
body,
|
|
525
|
+
})
|
|
526
|
+
} catch {
|
|
527
|
+
if (signal?.aborted) throw abortError()
|
|
528
|
+
if (combinedSignal.aborted) throw timeoutError()
|
|
529
|
+
throw new Error("Image request failed before a response was received")
|
|
530
|
+
}
|
|
531
|
+
// A fetcher may resolve after the deadline or after cancellation; discard that late result.
|
|
532
|
+
if (signal?.aborted || combinedSignal.aborted) {
|
|
533
|
+
await response?.body?.cancel().catch(() => {})
|
|
534
|
+
throwIfSettled(signal, combinedSignal)
|
|
535
|
+
}
|
|
536
|
+
if (!response || typeof response !== "object" || typeof response.ok !== "boolean") {
|
|
537
|
+
throw new Error("Image request failed before a response was received")
|
|
538
|
+
}
|
|
539
|
+
if (!response.ok) throw await httpError(response, { signal, combinedSignal })
|
|
540
|
+
let base64, googleImage
|
|
541
|
+
try {
|
|
542
|
+
if (google) {
|
|
543
|
+
googleImage = await readGoogleImageResponse(response)
|
|
544
|
+
base64 = googleImage.data
|
|
545
|
+
} else base64 = await readImageResponse(response)
|
|
546
|
+
} catch (error) {
|
|
547
|
+
// Our own messages pass through; every transport/stream failure is normalized.
|
|
548
|
+
throwIfSettled(signal, combinedSignal)
|
|
549
|
+
if (error instanceof ImageResponseError) throw error
|
|
550
|
+
throw new Error("Image response stream failed")
|
|
551
|
+
}
|
|
552
|
+
throwIfSettled(signal, combinedSignal)
|
|
553
|
+
let saved
|
|
554
|
+
try {
|
|
555
|
+
saved = await saveImage(input.out, directory, base64, format, combinedSignal, googleImage)
|
|
556
|
+
} catch (error) {
|
|
557
|
+
throwIfSettled(signal, combinedSignal)
|
|
558
|
+
throw error
|
|
559
|
+
}
|
|
560
|
+
return { ...saved, route: route.route, method: route.method, model: config.model }
|
|
561
|
+
}
|
package/index.js
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import path from "node:path"
|
|
2
|
+
import { generateImage, validateInput, pluginConfig, GOOGLE_ASPECT_RATIOS, GOOGLE_IMAGE_SIZES, GOOGLE_MAX_REFERENCES } from "./core.mjs"
|
|
3
|
+
|
|
4
|
+
export default {
|
|
5
|
+
id: "opencode-codex-imagegen",
|
|
6
|
+
async setup(ctx) {
|
|
7
|
+
const google = ctx.options?.provider === "google"
|
|
8
|
+
await ctx.tool.transform(editor => {
|
|
9
|
+
editor.add({
|
|
10
|
+
name: "proxy_imagegen",
|
|
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.",
|
|
14
|
+
input: {
|
|
15
|
+
type: "object",
|
|
16
|
+
properties: {
|
|
17
|
+
prompt: { type: "string", description: "Describe the image; when using references explain each image's role in order." },
|
|
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
|
+
}),
|
|
27
|
+
},
|
|
28
|
+
required: ["prompt", "out"],
|
|
29
|
+
additionalProperties: false,
|
|
30
|
+
},
|
|
31
|
+
async execute(input, context) {
|
|
32
|
+
// Options are validated before anything network- or credential-related happens.
|
|
33
|
+
const config = pluginConfig(ctx.options)
|
|
34
|
+
validateInput(input, config.provider)
|
|
35
|
+
const session = await ctx.session.get({ sessionID: context.sessionID })
|
|
36
|
+
const directory = session.location.directory
|
|
37
|
+
// Respect normal OpenCode edit rules, including external-directory approval.
|
|
38
|
+
const source = { type: "tool", messageID: context.messageID, id: context.id }
|
|
39
|
+
if (input.images?.length) await ctx.permission.assert({
|
|
40
|
+
sessionID: context.sessionID,
|
|
41
|
+
agent: context.agent,
|
|
42
|
+
source,
|
|
43
|
+
action: "read",
|
|
44
|
+
resources: input.images.map(file => path.resolve(directory, file)),
|
|
45
|
+
})
|
|
46
|
+
const output = path.resolve(directory, input.out)
|
|
47
|
+
const extension = path.extname(output)
|
|
48
|
+
await ctx.permission.assert({
|
|
49
|
+
sessionID: context.sessionID,
|
|
50
|
+
agent: context.agent,
|
|
51
|
+
source,
|
|
52
|
+
action: "edit",
|
|
53
|
+
resources: [output, `${output.slice(0, -extension.length)}-v*${extension.toLowerCase()}`],
|
|
54
|
+
})
|
|
55
|
+
const result = await generateImage(input, config, directory, { ctx, signal: context.signal, sessionID: context.sessionID })
|
|
56
|
+
return {
|
|
57
|
+
content: `Saved ${extension.toLowerCase() === ".png" ? "PNG" : "JPEG"}: ${result.out}${result.versioned ? " (versioned; existing file preserved)" : ""}`,
|
|
58
|
+
metadata: {
|
|
59
|
+
out: result.out,
|
|
60
|
+
versioned: result.versioned,
|
|
61
|
+
bytes: result.bytes,
|
|
62
|
+
route: result.route,
|
|
63
|
+
method: result.method,
|
|
64
|
+
model: result.model,
|
|
65
|
+
},
|
|
66
|
+
}
|
|
67
|
+
},
|
|
68
|
+
})
|
|
69
|
+
})
|
|
70
|
+
},
|
|
71
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,54 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@myoldtime/opencode-codex-imagegen",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"description": "
|
|
6
|
-
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"description": "OpenCode V2 plugin: generate and edit images with OpenAI Responses (API, proxy or Codex) or Google Gemini Interactions (Nano Banana).",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"author": "MyOldTime",
|
|
8
|
+
"repository": {
|
|
9
|
+
"type": "git",
|
|
10
|
+
"url": "git+https://github.com/MyOldTime/opencode-codex-imagegen.git"
|
|
11
|
+
},
|
|
12
|
+
"homepage": "https://github.com/MyOldTime/opencode-codex-imagegen#readme",
|
|
13
|
+
"bugs": {
|
|
14
|
+
"url": "https://github.com/MyOldTime/opencode-codex-imagegen/issues"
|
|
15
|
+
},
|
|
16
|
+
"keywords": [
|
|
17
|
+
"opencode",
|
|
18
|
+
"opencode-plugin",
|
|
19
|
+
"image-generation",
|
|
20
|
+
"responses-api",
|
|
21
|
+
"chatgpt",
|
|
22
|
+
"codex"
|
|
23
|
+
],
|
|
24
|
+
"main": "./index.js",
|
|
25
|
+
"exports": {
|
|
26
|
+
".": "./index.js",
|
|
27
|
+
"./core": "./core.mjs"
|
|
28
|
+
},
|
|
29
|
+
"files": [
|
|
30
|
+
"index.js",
|
|
31
|
+
"core.mjs",
|
|
32
|
+
"README.md",
|
|
33
|
+
"VALIDATION.md",
|
|
34
|
+
"LICENSE",
|
|
35
|
+
"CHANGELOG.md"
|
|
36
|
+
],
|
|
37
|
+
"publishConfig": {
|
|
38
|
+
"access": "public"
|
|
39
|
+
},
|
|
40
|
+
"scripts": {
|
|
41
|
+
"check": "node --check index.js && node --check core.mjs && node --check test.mjs && node --check release.test.mjs",
|
|
42
|
+
"test": "node --test test.mjs release.test.mjs",
|
|
43
|
+
"prepublishOnly": "npm run check && npm test",
|
|
44
|
+
"publish:npm": "npm publish --registry=https://registry.npmjs.org --@myoldtime:registry=https://registry.npmjs.org --access=public",
|
|
45
|
+
"publish:github": "npm publish --registry=https://npm.pkg.github.com --@myoldtime:registry=https://npm.pkg.github.com --access=public"
|
|
46
|
+
},
|
|
47
|
+
"engines": {
|
|
48
|
+
"node": ">=20.16"
|
|
49
|
+
},
|
|
50
|
+
"dependencies": {
|
|
51
|
+
"jpeg-js": "0.4.4",
|
|
52
|
+
"pngjs": "7.0.0"
|
|
53
|
+
}
|
|
54
|
+
}
|