@myoldtime/opencode-codex-imagegen 0.1.0 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,230 +1,120 @@
1
- # opencode-codex-imagegen
1
+ # opencode-auto-imagegen
2
2
 
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 |
3
+ 一个 OpenCode V2 后台生图工具 `auto_imagegen`,按 **Codex → OpenRouter → AIHubMix → Google Gemini** 的顺序选择有凭据且支持本次参数的服务。前台拿到本地任务 ID 后可继续对话,完成时原会话收到实际服务商、切换原因及保存路径。
26
4
 
27
5
  ## 安装
28
6
 
29
- 以下在线方式需对应的版本或标签已经发布:本包为 `0.1.0`,tag 为 `v0.1.0`。
7
+ 在 OpenCode V2 中安装 [npm 包](https://www.npmjs.com/package/@myoldtime/opencode-codex-imagegen):
30
8
 
31
- ### 方式一:从 npmjs.org 安装(推荐)
32
-
33
- npmjs.org 上的公开包安装不需要登录 npm,也不需要提供 token。
34
-
35
- ```powershell
36
- opencode plugin add "@myoldtime/opencode-codex-imagegen@0.1.0"
9
+ ```sh
10
+ opencode plugin add "@myoldtime/opencode-codex-imagegen@1.0.0"
37
11
  opencode plugin list
38
12
  ```
39
13
 
40
- 固定版本便于复现,`opencode plugin list` 用于确认已登记。
14
+ 也可从 [GitHub 仓库](https://github.com/MyOldTime/opencode-codex-imagegen) 的 `v1.0.0` 标签加载源码:在插件目录运行 `npm ci --ignore-scripts`,将下方 `package` 改为该目录的绝对路径。
15
+
16
+ ## 配置
41
17
 
42
- `opencode plugin add` 默认写入全局 OpenCode 配置。若只想在某个项目使用,改用该项目的 `opencode.json`:
18
+ 在项目或全局 `opencode.jsonc` 的 `plugins` 中配置插件;已安装时直接编辑同一条目。**只需一家可用凭据**,示例中不使用的服务段可以省略。Codex 可以复用 OpenCode 已连接的 OpenAI 账号,也可以使用独立 key;其余服务使用各自的 key。没有可用凭据时不创建后台任务。
43
19
 
44
- ```json
20
+ ```jsonc
45
21
  {
46
22
  "$schema": "https://opencode.ai/config.json",
47
- "plugins": ["@myoldtime/opencode-codex-imagegen@0.1.0"]
23
+ "plugins": [
24
+ {
25
+ "package": "@myoldtime/opencode-codex-imagegen@1.0.0",
26
+ "options": {
27
+ "codex": {
28
+ "disabled": false,
29
+ "model": "gpt-6.2-sol" // 对话模型 ID;不填 key 和 base_url 时使用 OpenCode 的 OpenAI 登录
30
+ },
31
+ "openrouter": {
32
+ "disabled": false,
33
+ "base_url": "https://openrouter.ai/api/v1",
34
+ "key": "{env:OPENROUTER_API_KEY}",
35
+ "model": "openai/gpt-image-2.5-sunburst" // 可选:填写 OpenRouter 上的生图模型 ID
36
+ },
37
+ "aihubmix": {
38
+ "disabled": false,
39
+ "base_url": "https://aihubmix.com/ai/v1",
40
+ "key": "{env:AIHUBMIX_API_KEY}",
41
+ "model": "gpt-image-2.5-sunburst" // 可选:填写 AIHubMix 上的生图模型 ID
42
+ },
43
+ "google": {
44
+ "disabled": false,
45
+ "base_url": "https://generativelanguage.googleapis.com",
46
+ "key": "{env:GEMINI_API_KEY}",
47
+ "model": "gemini-nano-banana-2.1"
48
+ }
49
+ }
50
+ }
51
+ ]
48
52
  }
49
53
  ```
50
54
 
51
- 安装或修改配置后,可在 OpenCode TUI 输入 `/reload` 重新加载;这是界面内的斜杠命令,不是操作系统 shell 命令。
55
+ 每个服务的 `disabled` 都是可选布尔值,默认 `false`。设为 `true` 后,该服务完全不参与首选或容错,不需要删除 key,也不会读取它的环境密钥或宿主登录。其余服务保持原有顺序;若全部禁用,工具会直接提示,不提交任务。
52
56
 
53
- ### 方式二:从 GitHub 标签安装
57
+ `model` 的含义按服务区分:
54
58
 
55
- ```powershell
56
- opencode plugin add "github:MyOldTime/opencode-codex-imagegen#v0.1.0"
57
- opencode plugin list
59
+ - **`codex.model` 是对话模型**,省略时默认 `gpt-6.2-sol`。它作为 Responses 请求的顶层 `model`,由 `tool_choice: {"type":"image_generation"}` 指定调用托管生图工具。实际生图模型由后端选择。`size` 和 `quality` 传给工具,不作为对话模型的配置。
60
+ - **`openrouter.model` 和 `aihubmix.model` 是生图模型**,默认分别是 `openai/gpt-image-2.5-sunburst` 和 `gpt-image-2.5-sunburst`。切换时使用目标服务自己的模型,不会带入 Codex 对话模型 ID。
61
+ - **`google.model` 是支持图片输出的 Gemini 模型**,默认 `gemini-nano-banana-2.1`。
62
+
63
+ **Codex 的凭据**:省略 `codex` 整段或只填写 `codex.model` 时,插件通过宿主查询当前 OpenAI 连接。支持宿主管理的 API key、Sign in with ChatGPT 和 legacy Codex 登录;账号不具备生图能力时进入容错流程。要用显式 API key 或 Responses 代理,可以改成:
64
+
65
+ ```jsonc
66
+ "codex": {
67
+ "base_url": "https://api.openai.com/v1", // 可换成支持 Responses 托管生图工具的代理
68
+ "key": "{env:OPENAI_API_KEY}",
69
+ "model": "gpt-6.2-sol"
70
+ }
58
71
  ```
59
72
 
60
- 公共仓库通过该方式安装不需要 GitHub Packages token,也不经过 npm registry。仅对某个项目生效时,项目 `opencode.json` 的 `plugins` 条目可写成同一来源 `github:MyOldTime/opencode-codex-imagegen#v0.1.0`。`#v0.1.0` 指向该标签当前对应的提交,标签由仓库维护者控制,需要时请自行核对。
73
+ 显式 Codex key 不读取宿主凭据,只给 key 时使用官方 `/v1/responses`。配置代理地址却没给 key 时跳过 Codex,不会向代理发送宿主 token。若已登录但想跳过 Codex,写 `"codex": {"disabled": true}`。Codex 另支持可选的 `reasoning_effort` 和 `fast_mode`。
61
74
 
62
- ### 方式三:从 GitHub Packages 安装
75
+ OpenRouter、AIHubMix 和 Google 使用官方地址时,省略服务配置也可读取 OpenCode 服务进程中对应的环境变量;显式填写空字符串或纯空白 `key` 则不启用该服务。使用代理时须显式指定 `key`。
63
76
 
64
- GitHub Packages 与本包在 npmjs.org 的同名包属于两个独立 registry,同一版本需要分别发布。按 GitHub 的规则,即使包是公有的,安装也需要具有 `read:packages` 权限的 personal access token (classic)。
77
+ AIHubMix 默认接口需要在[控制台开启异步任务](https://console.aihubmix.com/async-tasks)。也可填 `https://aihubmix.com/v1` 使用兼容端点(文生图及单图编辑)。两种接口都不会阻塞前台。
65
78
 
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
- ```
79
+ ### Google Gemini
73
80
 
74
- token 只在 `npm login` 的交互提示中输入,由 npm 自己保存;不要写进 `opencode.json`,也不要提交到仓库。若之后改回 npmjs.org 渠道,把该 scope 指回官方 registry:
81
+ 使用官方接口时,只要 OpenCode 服务进程中有 `GEMINI_API_KEY`,就可以省略整个 `google` 配置。只有 Google 有凭据时,普通文生图和参考图编辑会直接使用 Google。要通过代理调用,设置 `google.base_url` 和 `google.key`;例如 `https://proxy.example/gemini` 会请求 `/gemini/v1beta/interactions`,也可以直接填完整的 Interactions 端点。代理需支持 [Gemini Interactions REST](https://aistudio.google.com/api-reference/interactions-api/create-interaction) 的 JSON 协议,并转发 `x-goog-api-key` 和 `Api-Revision` 请求头。
75
82
 
76
- ```sh
77
- npm config set @myoldtime:registry https://registry.npmjs.org --location=user
78
- ```
83
+ 例如「用 `auto_imagegen` 参考 `街景.png` 画一张 16:9、2K 的水彩画,保存为 `街景水彩.jpg`」:工具可用 `aspect_ratio: "16:9"` 和 `image_size: "2K"`。显式指定 `image_size`(`1K` / `2K` / `4K`)或 Google 专用画幅(`1:4`、`4:1`、`1:8`、`8:1`)时,前三家会跳过,不会降低要求改用默认尺寸。
79
84
 
80
- ### 本地开发安装
85
+ Google 支持最多 14 张按顺序传入的 PNG、JPEG 或 WebP 参考图;含提示词和 Base64 图片的整个请求最多 20 MB。输出支持 PNG、JPEG,目标为 PNG 而上游返回 JPEG 时会在本地转码。精确像素 `size`、蒙版、WebP 输出、非自动质量或背景、显式压缩参数均不走 Google。
81
86
 
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
+ ## 切换和会话隔离
87
88
 
88
- 在 OpenCode 配置中把 `package` 指向这个目录的**绝对路径**,例如 Unix 风格 `/path/to/opencode-codex-imagegen`,Windows 的 JSON 中可写成 `C:/path/to/opencode-codex-imagegen`。必须指向目录,不能指向单个文件;插件本身无需编译。
89
+ | 情况 | 本次 | 同一会话的下一次 |
90
+ | --- | --- | --- |
91
+ | 首选服务成功 | 保存并通知 | 从首个可用服务开始 |
92
+ | 只有一家有凭据 | 直接使用该服务;未配置的服务不参与路由,也不记为失败 | 按调用时的凭据选择服务 |
93
+ | 401、欠费 402、已识别的密钥额度/停用错误 | 标记失效;有已配置的备用服务时切换 | 跳过已确认失效的服务 |
94
+ | 限流 429、临时并发预算不足、5xx、网络异常、无可用图片 | 尚未保存图片时按顺序切到下一家 | 重新从首个可用服务开始 |
95
+ | 已配置服务均不可用 | 发一条失败通知,列出各自原因 | 仅尝试未被标记失效的服务 |
96
+ | 本地权限/文件错误、明确的内容策略拒绝、已有部分图片 | 报告错误或已保存的图片,不另开生成请求 | 不改变服务状态 |
89
97
 
90
- ## 配置
98
+ 失效标记仅在**当前插件实例的内存中按 `sessionID` 保存**。同一会话跨回合保留(空闲不清除);新会话、分支会话互不继承。归档、删除会话或重载插件会清掉对应标记。没有写入磁盘的路由状态,也不修改全局配置。任务通知仍按 OpenCode 的普通会话历史保留。更新密钥/充值后,开新会话或重载插件即可重新尝试。
91
99
 
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
- ```
100
+ 每个任务按顺序经过每家至多一次;Codex 和 Google 每次生成一张,`n > 1` 时逐张请求并立即保存。Codex 支持 PNG、自动背景、无蒙版,质量 `auto/low/medium/high`;其余需求直接交给后续支持的服务,不标记 Codex 失效。已保存部分图片时不切换去补单。每个服务总时限为 10 分钟。网络中断时远端是否已接单可能无法确认,自动切换有可能导致多个服务产生费用。卸载插件停止本地等待。
108
101
 
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
- ```
102
+ ## 使用
208
103
 
209
- 实际发布命令(会上传包,请确认版本与目标 registry 后再执行):
104
+ > 用 `auto_imagegen` 画 3 张精细的 9:16 手机壁纸,主题是雨夜花店,第一张保存到 `壁纸.png`。
210
105
 
211
- ```powershell
212
- npm run publish:npm # 上传到 npmjs
213
- ```
106
+ 工具可以选择 `quality: "high"`、`n: 3`、`aspect_ratio: "9:16"`。OpenRouter 接收画幅比例;若发生切换,AIHubMix 收到相同提示词、数量、参考图及对应的 `size: "864x1536"`。没有特别要求时默认自动画幅、自动质量、1 张 PNG。输出默认位于会话目录 `images/`,支持指定 `out`,遇到同名文件自动使用新名字。
214
107
 
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。
108
+ 可传 `images`(最多 16 张本地 PNG/JPEG/WebP)、`size` 或 `aspect_ratio`、`n`(1–10)、`quality`、`output_format`、`background`、`output_compression`。带 PNG `mask` 的编辑直接使用支持蒙版的 AIHubMix,不会影响同会话其他请求的优先级。AIHubMix `/v1` 模式不支持多参考图、显式背景或压缩参数;如需这些能力请使用默认 `/ai/v1`。
216
109
 
217
- ## 开发与测试
110
+ ## 验证
218
111
 
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
112
+ ```sh
113
+ npm run check
114
+ npm test
115
+ npm pack --dry-run
224
116
  ```
225
117
 
226
- 测试覆盖:显式配置优先且不触碰 integration、三种 OAuth 方法的精确 URL/请求头/请求体、key 回退、每次调用重新 resolve、空白与半配置、未知方法与过期凭据、刷新/解析失败、HTTP/SSE/JSON 错误不泄密、参考图与 PNG 不覆盖、预取消与超时不落盘、插件注册 id/工具/权限顺序;另有发布元数据测试(包名、id、仓库链接、双 registry 与 scope override、workflow 校验、files 白名单)。
227
-
228
- ## License
118
+ 测试模拟四家服务及宿主凭据,覆盖四方切换、会话隔离、部分成功、后台通知、Codex Responses、AIHubMix 异步下载、Gemini Interactions 及图片转码,不消耗真实额度。
229
119
 
230
- MIT © MyOldTime
120
+ 协议参考:[OpenRouter Sunburst](https://openrouter.ai/openai/gpt-image-2.5-sunburst?output_modalities=image&view=api) · [AIHubMix Sunburst](https://aihubmix.com/model/gpt-image-2.5-sunburst/llms.txt) · [AIHubMix 端点 Schema](https://aihubmix.com/call/schema/models/gpt-image-2.5-sunburst/endpoints)
package/codex.js ADDED
@@ -0,0 +1,167 @@
1
+ import { ProviderFailure, upstreamError } from "./errors.js"
2
+
3
+ const official = "https://api.openai.com/v1/responses"
4
+ const legacy = "https://chatgpt.com/backend-api/codex/responses"
5
+ const defaultChatModel = "gpt-6.2-sol"
6
+ const legacyMethods = new Set(["chatgpt-browser", "chatgpt-headless"])
7
+ const usableKey = key => typeof key === "string" && key.trim() && !key.trim().startsWith("{env:")
8
+
9
+ // Explicit endpoints must never inherit a credential from the host. For managed
10
+ // connections only check availability here; OpenCode resolves/refreshes at use.
11
+ export async function codexCandidate(settings = {}, integration, sessionDisabled = false) {
12
+ if (settings.disabled === true) return
13
+ if (settings.key !== undefined || settings.base_url !== undefined) {
14
+ return usableKey(settings.key) ? { provider: "codex", settings } : undefined
15
+ }
16
+ if (sessionDisabled) return { provider: "codex", settings }
17
+ if (!integration?.active || !integration?.resolve) return
18
+ let account
19
+ try { account = await integration.active("openai") } catch { return }
20
+ if (account) return { provider: "codex", settings, resolveCredential: () => integration.resolve(account) }
21
+ }
22
+
23
+ export function codexUnsupported(params, mask) {
24
+ if (mask || params.output_format !== "png" || params.background !== "auto" || !["auto", "low", "medium", "high"].includes(params.quality))
25
+ return "Codex 通道支持无蒙版、自动背景的 PNG,质量为 auto/low/medium/high;本次参数交给下一家。"
26
+ }
27
+
28
+ async function codexConnection(candidate, sessionID) {
29
+ const { settings, resolveCredential } = candidate
30
+ const headers = { "Content-Type": "application/json", Accept: "text/event-stream" }
31
+ let endpoint = official, access
32
+ if (settings.key !== undefined) {
33
+ let url
34
+ try { url = new URL(settings.base_url ?? official) } catch { throw new ProviderFailure("Codex base_url 无效。") }
35
+ if (!["http:", "https:"].includes(url.protocol) || url.username || url.password || url.hash || url.search)
36
+ throw new ProviderFailure("Codex base_url 必须为不含凭据、查询参数或片段的 HTTP(S) 地址。")
37
+ const prefix = url.pathname.replace(/\/+$/, "")
38
+ url.pathname = prefix.endsWith("/responses") ? prefix : `${prefix}/responses`
39
+ endpoint = url.href
40
+ access = settings.key
41
+ } else {
42
+ let cred
43
+ try { cred = await resolveCredential() } catch { throw new ProviderFailure("OpenCode 无法解析 OpenAI 登录凭据。") }
44
+ if (cred?.type === "key") access = cred.key
45
+ else if (cred?.type === "oauth" && (legacyMethods.has(cred.methodID) || cred.methodID === "chatgpt-token-sharing")) {
46
+ if (typeof cred.expires === "number" && cred.expires <= Date.now()) throw new ProviderFailure("Codex 登录凭据已过期。")
47
+ access = cred.access
48
+ headers["session-id"] = sessionID
49
+ if (legacyMethods.has(cred.methodID)) {
50
+ endpoint = legacy
51
+ headers.originator = "opencode"
52
+ if (typeof cred.metadata?.accountID === "string" && cred.metadata.accountID) headers["ChatGPT-Account-Id"] = cred.metadata.accountID
53
+ } else {
54
+ headers["thread-id"] = sessionID
55
+ headers["x-client-request-id"] = sessionID
56
+ }
57
+ } else throw new ProviderFailure("不支持的 OpenAI 登录方式。")
58
+ }
59
+ if (!usableKey(access) || /[^\x21-\x7e]/.test(access.trim())) throw new ProviderFailure("Codex 凭据无效。", { disable: true })
60
+ return { endpoint, headers: { ...headers, Authorization: `Bearer ${access.trim()}` } }
61
+ }
62
+
63
+ function failure(status, error) {
64
+ if (["subscription_sharing_unsupported_capability", "subscription_sharing_route_not_supported",
65
+ "subscription_sharing_user_not_eligible", "subscription_sharing_usage_limit_exceeded",
66
+ "chatpass_v2_scope_not_authorized"].includes(error?.code))
67
+ return new ProviderFailure(`Codex 账号不可用(${error.code})。`, { disable: true })
68
+ return upstreamError(status, error)
69
+ }
70
+
71
+ function result(event) {
72
+ const response = event?.response ?? event
73
+ if (event?.type === "error" || response?.error || ["failed", "incomplete", "cancelled"].includes(response?.status) ||
74
+ ["response.failed", "response.incomplete"].includes(event?.type)) {
75
+ const error = response?.error ?? (response?.incomplete_details ? { code: response.incomplete_details.reason } : event)
76
+ throw failure(Number(error?.status) || 200, error)
77
+ }
78
+ const items = event?.type === "response.output_item.done" ? [event.item] : response?.output
79
+ if (event?.type?.startsWith("response.refusal.") || (Array.isArray(items) && items.some(i => i?.content?.some?.(c => c?.type === "refusal"))))
80
+ throw new ProviderFailure("Codex 拒绝了本次请求。", { fallback: false })
81
+ if (Array.isArray(items)) return items.find(i => i?.type === "image_generation_call" && typeof i.result === "string" && i.result)?.result
82
+ }
83
+
84
+ // Some Codex gateways omit Content-Type. Accept both full Responses JSON and
85
+ // SSE, dispatching complete frames (not individual TCP chunks or partial images).
86
+ async function imageResult(response) {
87
+ if (!response.body) throw new ProviderFailure("Codex 返回空响应。")
88
+ const ct = response.headers.get("content-type") ?? ""
89
+ let mode = ct.includes("text/event-stream") ? "sse" : ct.includes("application/json") ? "json" : null
90
+ let pending = "", data = []
91
+ const reader = response.body.getReader(), decoder = new TextDecoder()
92
+ function line(value) {
93
+ if (!value) {
94
+ const text = data.join("\n")
95
+ data = []
96
+ if (text && text !== "[DONE]") return result(JSON.parse(text))
97
+ } else if (value.startsWith("data:")) data.push(value.slice(5).replace(/^ /, ""))
98
+ }
99
+ try {
100
+ for (;;) {
101
+ const { value, done } = await reader.read()
102
+ pending += done ? decoder.decode() : decoder.decode(value, { stream: true })
103
+ if (!mode) {
104
+ const prefix = pending.trimStart()
105
+ if (prefix.startsWith("{") || prefix.startsWith("[")) mode = "json"
106
+ else if (/^(?:(?:data|event|id|retry)(?::|\r?\n)|:)/.test(prefix)) { mode = "sse"; pending = prefix }
107
+ else if (done || pending.length > 65536 || prefix.includes("\n")) break
108
+ else continue
109
+ }
110
+ if (mode === "json") {
111
+ if (!done) continue
112
+ const image = result(JSON.parse(pending))
113
+ if (image) return image
114
+ break
115
+ }
116
+ let i
117
+ while ((i = pending.indexOf("\n")) >= 0) {
118
+ const image = line(pending.slice(0, i).replace(/\r$/, ""))
119
+ pending = pending.slice(i + 1)
120
+ if (image) return image
121
+ }
122
+ if (done) {
123
+ const image = (pending && line(pending.replace(/\r$/, ""))) || line("")
124
+ if (image) return image
125
+ break
126
+ }
127
+ }
128
+ } finally {
129
+ await reader.cancel().catch(() => {})
130
+ reader.releaseLock()
131
+ }
132
+ throw new ProviderFailure("Codex 响应中没有 image_generation_call.result。")
133
+ }
134
+
135
+ // One hosted tool call produces one image. Yield each result before requesting
136
+ // the next, so a later failure cannot cause the paid batch to be regenerated.
137
+ export async function* codexOutputs({ candidate, sessionID, params, refs, signal }) {
138
+ const { settings } = candidate
139
+ const model = settings.model === undefined ? defaultChatModel : settings.model
140
+ if (typeof model !== "string" || !model.trim()) throw new ProviderFailure("codex.model 必须是非空对话模型 ID。")
141
+ const { endpoint, headers } = await codexConnection(candidate, sessionID)
142
+ const content = [{ type: "input_text", text: params.prompt }, ...refs.map(ref => ({
143
+ type: "input_image", image_url: `data:image/${ref.type};base64,${ref.bytes.toString("base64")}`,
144
+ }))]
145
+ const body = JSON.stringify({
146
+ model: model.trim(), instructions: "Generate the requested image by invoking image_generation exactly once. Do not respond with text only.",
147
+ input: [{ role: "user", content }],
148
+ tools: [{ type: "image_generation", output_format: "png", quality: params.quality, size: params.size }],
149
+ tool_choice: { type: "image_generation" }, stream: true, store: false,
150
+ ...(settings.reasoning_effort !== undefined && { reasoning: { effort: settings.reasoning_effort } }),
151
+ ...(settings.fast_mode && { service_tier: "priority" }),
152
+ })
153
+ for (let i = 0; i < params.n; i++) {
154
+ let base64
155
+ try {
156
+ signal.throwIfAborted()
157
+ const res = await fetch(endpoint, { method: "POST", body, headers, redirect: "error", signal })
158
+ if (!res.ok) throw failure(res.status, (await res.json().catch(() => null))?.error)
159
+ base64 = await imageResult(res)
160
+ } catch (error) {
161
+ if (error instanceof ProviderFailure) throw error
162
+ throw new ProviderFailure(signal.aborted ? "Codex 请求超时或已中止。" : "Codex 请求或响应流异常。")
163
+ }
164
+ if (!/^[A-Za-z0-9+/]+={0,2}$/.test(base64) || base64.length % 4) throw new ProviderFailure("Codex 返回无效的图片数据。")
165
+ yield { b64_json: base64 }
166
+ }
167
+ }
package/errors.js ADDED
@@ -0,0 +1,24 @@
1
+ // Only provider-side failures are eligible for routing. Filesystem and permission
2
+ // errors are deliberately not reclassified as provider failures.
3
+ export class ProviderFailure extends Error {
4
+ constructor(message, { disable = false, fallback = true } = {}) {
5
+ super(message)
6
+ this.disable = disable
7
+ this.fallback = fallback
8
+ }
9
+ }
10
+
11
+ export function upstreamError(status, error = {}, submission = true) {
12
+ const code = String(error?.code ?? "").toLowerCase()
13
+ const source = error?.metadata?.limit_source
14
+ const policy = status === 422 || /moderation|content[_ -]?(policy|filter)|safety|output_blocked|policy_violation/i.test(`${code} ${String(error?.message ?? "")}`)
15
+ const temporary = source === "openrouter_in_flight_budget" || ["rate_limited", "upstream_rate_limited"].includes(code)
16
+ const keyBlocked = status === 403 && /(?:key|account).{0,24}(?:disabled|suspended|spend(?:ing)? limit)|spend(?:ing)? limit.{0,16}reached/i.test(String(error?.message ?? ""))
17
+ const account = status === 401 || status === 402 || keyBlocked || source === "openrouter_key_limit" ||
18
+ ["invalid_api_key", "authentication_failed", "insufficient_quota", "insufficient_user_quota", "async_not_enabled", "key_disabled"].includes(code)
19
+ const disable = submission && account && !temporary && !policy
20
+ const hint = policy ? "内容或策略限制" : temporary || status === 429 ? "临时限流或预算限制" :
21
+ code === "async_not_enabled" ? "账户未启用 AIHubMix 异步任务" :
22
+ status === 401 ? "密钥无效" : status === 402 ? "额度不足" : status === 403 ? "访问受限" : "上游请求失败"
23
+ return new ProviderFailure(`HTTP ${status}(${hint})`, { disable, fallback: !policy })
24
+ }
package/google.js ADDED
@@ -0,0 +1,79 @@
1
+ import { ProviderFailure, upstreamError } from "./errors.js"
2
+
3
+ export const googleRatios = ["1:1", "2:3", "3:2", "3:4", "4:3", "4:5", "5:4", "9:16", "16:9", "21:9", "1:4", "4:1", "1:8", "8:1"]
4
+ const inlineLimit = 20_000_000
5
+
6
+ export function googleUnsupported({ params, aspect }, { refs, mask }) {
7
+ if (refs.length > 14) return "Google 最多支持 14 张参考图。"
8
+ if (!aspect || (aspect !== "auto" && !googleRatios.includes(aspect))) return "Google 不支持指定的精确像素尺寸或画幅。"
9
+ if (mask || params.quality !== "auto" || params.background !== "auto" || params.output_compression !== undefined || params.output_format === "webp")
10
+ return "Google 支持无蒙版的 PNG/JPEG 输出,不支持显式质量、背景或压缩参数。"
11
+ }
12
+
13
+ function interactionBody({ config, params, refs, aspect, imageSize }) {
14
+ const limitError = "Google 内联请求不能超过 20 MB,请缩小参考图。"
15
+ const encodedLength = refs.reduce((total, ref) => total + 4 * Math.ceil(ref.bytes.length / 3), 0)
16
+ if (encodedLength > inlineLimit) throw new ProviderFailure(limitError)
17
+ const format = {
18
+ ...(aspect !== "auto" && { aspect_ratio: aspect }),
19
+ ...(imageSize && { image_size: imageSize }),
20
+ ...(params.output_format === "jpeg" && { mime_type: "image/jpeg" }),
21
+ }
22
+ const body = JSON.stringify({
23
+ model: config.model,
24
+ input: [{ type: "text", text: params.prompt }, ...refs.map(ref => ({
25
+ type: "image", mime_type: `image/${ref.type}`, data: ref.bytes.toString("base64"),
26
+ }))],
27
+ ...(Object.keys(format).length && { response_format: { type: "image", ...format } }),
28
+ })
29
+ if (Buffer.byteLength(body) > inlineLimit) throw new ProviderFailure(limitError)
30
+ return body
31
+ }
32
+
33
+ function googleFailure(status, error) {
34
+ const invalidKey = Array.isArray(error?.details) && error.details.some(item => item?.reason === "API_KEY_INVALID")
35
+ if (invalidKey || /API key not valid/i.test(error?.message ?? ""))
36
+ return new ProviderFailure("Google API key 无效。", { disable: true })
37
+ return upstreamError(status, { code: error?.status ?? error?.code, message: error?.message })
38
+ }
39
+
40
+ export async function* googleOutputs(job) {
41
+ const { config, params, signal } = job
42
+ const body = interactionBody(job)
43
+ const headers = { "x-goog-api-key": config.key, "Content-Type": "application/json", "Api-Revision": "2026-05-20" }
44
+ for (let i = 0; i < params.n; i++) {
45
+ let response, payload
46
+ try {
47
+ signal.throwIfAborted()
48
+ response = await fetch(config.endpoint, { method: "POST", headers, body, signal, redirect: "error" })
49
+ payload = await response.json().catch(() => null)
50
+ } catch {
51
+ throw new ProviderFailure("Google 请求超时、中止或网络异常。")
52
+ }
53
+ if (!response.ok || payload?.error) {
54
+ const status = response.ok && Number.isInteger(payload?.error?.code) ? payload.error.code : response.status
55
+ throw googleFailure(status, payload?.error)
56
+ }
57
+ if (payload?.status !== "completed") throw new ProviderFailure("Google 图像交互未完成。")
58
+ let image
59
+ for (const step of Array.isArray(payload.steps) ? payload.steps : []) {
60
+ if (step?.type !== "model_output" || !Array.isArray(step.content)) continue
61
+ for (const part of step.content) {
62
+ if (part?.type === "image" && typeof part.data === "string" && part.data) image = part
63
+ }
64
+ }
65
+ if (!image) throw new ProviderFailure("Google model_output 未返回图片。")
66
+ if (image.data.length % 4 || !/^[A-Za-z0-9+/]+={0,2}$/.test(image.data)) throw new ProviderFailure("Google 返回无效的图片数据。")
67
+ yield { b64_json: image.data, mime_type: image.mime_type }
68
+ }
69
+ }
70
+
71
+ // Gemini may return JPEG even for the default (PNG) request.
72
+ export async function jpegToPNG(bytes) {
73
+ const [{ default: jpeg }, { PNG }] = await Promise.all([import("jpeg-js"), import("pngjs")])
74
+ try {
75
+ return PNG.sync.write(jpeg.decode(bytes, { maxResolutionInMP: 20, maxMemoryUsageInMB: 384, tolerantDecoding: false }))
76
+ } catch {
77
+ throw new ProviderFailure("Google 返回的 JPEG 无法转为 PNG。")
78
+ }
79
+ }