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