opencode-gpt-imagegen 1.0.2 → 1.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/README.md +44 -5
- package/dist/index.js +184 -95
- package/package.json +4 -5
package/README.md
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
|
|
5
5
|
> **📣 `1.0.0` changes how `gpt_imagegen` is used.** `size` now accepts only seven fixed sizes, and `quality` is removed. See the [release notes](https://github.com/yuji-hatakeyama/opencode-gpt-imagegen/releases/tag/v1.0.0) for all changes.
|
|
6
6
|
|
|
7
|
-
> **📣 OpenAI API key support is on hold.** This plugin
|
|
7
|
+
> **📣 OpenAI API key support is on hold.** This plugin uses Codex OAuth with a ChatGPT subscription. If you need API key support, please share your use case in [#120](https://github.com/yuji-hatakeyama/opencode-gpt-imagegen/issues/120).
|
|
8
8
|
|
|
9
9
|
<p align="center"><img src="./ogp.png" alt="opencode-gpt-imagegen × gpt-image-2" /></p>
|
|
10
10
|
|
|
@@ -23,7 +23,18 @@
|
|
|
23
23
|
|
|
24
24
|
## Installation
|
|
25
25
|
|
|
26
|
-
|
|
26
|
+
The same package supports OpenCode V1 (1.18.29 or newer) and V2 (2.0.0 or newer).
|
|
27
|
+
|
|
28
|
+
For V2, add this plugin to your [OpenCode config](https://opencode.ai/v2/docs/plugins/):
|
|
29
|
+
|
|
30
|
+
```json
|
|
31
|
+
{
|
|
32
|
+
"$schema": "https://opencode.ai/config.json",
|
|
33
|
+
"plugins": ["opencode-gpt-imagegen"]
|
|
34
|
+
}
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
For V1, add this plugin to your [OpenCode config](https://opencode.ai/docs/plugins/) with the singular `plugin` field:
|
|
27
38
|
|
|
28
39
|
```json
|
|
29
40
|
{
|
|
@@ -32,12 +43,40 @@ Add this plugin to your [OpenCode config](https://opencode.ai/docs/plugins/). Fo
|
|
|
32
43
|
}
|
|
33
44
|
```
|
|
34
45
|
|
|
35
|
-
OpenCode
|
|
46
|
+
OpenCode installs the package automatically. Unless you use a proxy, sign in to OpenAI with Codex OAuth. On V2, run `/connect`, select OpenAI, and choose **Codex browser (legacy)** or **Codex device code (legacy)**. The **Sign in with ChatGPT** option uses token sharing, which [does not support image generation](https://developers.openai.com/siwc/token-sharing-open-source/preview-limitations).
|
|
47
|
+
|
|
48
|
+
### Sending requests through a proxy
|
|
49
|
+
|
|
50
|
+
Set `baseURL` if you reach ChatGPT through a gateway rather than signing OpenCode in to ChatGPT yourself, for example a local proxy that holds one or more ChatGPT sign-ins and spreads requests across them. In that setup OpenCode's `auth.json` usually has no ChatGPT sign-in, and calling chatgpt.com directly would bypass the gateway.
|
|
51
|
+
|
|
52
|
+
On V2, pass options with the package object:
|
|
53
|
+
|
|
54
|
+
```json
|
|
55
|
+
{
|
|
56
|
+
"plugins": [{ "package": "opencode-gpt-imagegen", "options": { "baseURL": "http://127.0.0.1:3457/v1" } }]
|
|
57
|
+
}
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
On V1, use the package-and-options tuple:
|
|
61
|
+
|
|
62
|
+
```json
|
|
63
|
+
{
|
|
64
|
+
"plugin": [["opencode-gpt-imagegen", { "baseURL": "http://127.0.0.1:3457/v1" }]]
|
|
65
|
+
}
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
With `baseURL` set, the plugin skips authentication lookup and sends the proxy no credentials on both versions. It sends the same requests it would send to ChatGPT, to `<baseURL>/images/generations`, or to `<baseURL>/images/edits` when reference images are given. Your proxy works with this option if it:
|
|
69
|
+
- accepts those two `POST` routes without an `Authorization` header;
|
|
70
|
+
- forwards the JSON body unchanged to the Codex images endpoints (`https://chatgpt.com/backend-api/codex/images/generations` and `/edits`), signed in with a ChatGPT account. The body has `prompt`, `model`, `quality`, `size` and `background`, plus `images` (a list of `{ "image_url": "data:..." }`) for edits;
|
|
71
|
+
- answers with the backend's JSON, in which `data[0].b64_json` holds the PNG. Any non-2xx status is reported as an error together with the start of the response body.
|
|
72
|
+
|
|
73
|
+
The request takes as long as the backend needs to draw the image, often 30 seconds or more, so the proxy must not time it out early.
|
|
36
74
|
|
|
37
75
|
### Updating the plugin
|
|
38
76
|
|
|
39
|
-
|
|
77
|
+
On V2, update an unpinned package with `opencode plugin update opencode-gpt-imagegen`. If you pinned an exact version, update that version in your configuration. See [OpenCode's plugin management guide](https://opencode.ai/v2/docs/plugins/#manage).
|
|
40
78
|
|
|
79
|
+
On V1, OpenCode caches npm plugins, so restarting it may keep an older version. To update this plugin:
|
|
41
80
|
1. Check the `plugin` entry in your OpenCode config. Use `"opencode-gpt-imagegen"` or `"opencode-gpt-imagegen@latest"` to request the latest version. If you pinned a version, remove the version suffix or change it to the version you want to install.
|
|
42
81
|
2. Quit OpenCode completely.
|
|
43
82
|
3. If your entry is unversioned or uses `@latest`, delete the cached directory `~/.cache/opencode/packages/opencode-gpt-imagegen@latest/`.
|
|
@@ -93,7 +132,7 @@ If you ask for an unsupported size, the tool instructs the agent to ask you whic
|
|
|
93
132
|
|
|
94
133
|
## How it works
|
|
95
134
|
|
|
96
|
-
|
|
135
|
+
This plugin calls the image generation endpoints of the OpenAI Codex backend (`images/generations`, or `images/edits` when reference images are given), the same endpoints the Codex CLI uses, and writes the returned PNG to disk. V1 reads `OPENCODE_AUTH_CONTENT` first, then OpenCode's `auth.json`. V2 resolves the active OpenAI connection through OpenCode's integration API.
|
|
97
136
|
|
|
98
137
|
## Contributing
|
|
99
138
|
|
package/dist/index.js
CHANGED
|
@@ -1,32 +1,9 @@
|
|
|
1
|
-
// src/
|
|
2
|
-
import
|
|
3
|
-
|
|
4
|
-
// src/auth.ts
|
|
5
|
-
import * as fs from "node:fs/promises";
|
|
6
|
-
import * as path from "node:path";
|
|
1
|
+
// src/v1.ts
|
|
2
|
+
import * as path3 from "node:path";
|
|
7
3
|
import { xdgData } from "xdg-basedir";
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
}
|
|
12
|
-
if (!xdgData) {
|
|
13
|
-
throw new Error("could not determine XDG data directory");
|
|
14
|
-
}
|
|
15
|
-
const raw = await fs.readFile(path.join(xdgData, "opencode", "auth.json"), "utf-8");
|
|
16
|
-
return JSON.parse(raw);
|
|
17
|
-
}
|
|
18
|
-
async function loadOpenAIAuth() {
|
|
19
|
-
try {
|
|
20
|
-
const data = await loadAuthData();
|
|
21
|
-
const entry = data.openai;
|
|
22
|
-
if (entry?.type === "oauth" && typeof entry.access === "string") {
|
|
23
|
-
return entry;
|
|
24
|
-
}
|
|
25
|
-
} catch {
|
|
26
|
-
return;
|
|
27
|
-
}
|
|
28
|
-
return;
|
|
29
|
-
}
|
|
4
|
+
|
|
5
|
+
// src/imagegen.ts
|
|
6
|
+
import { z } from "zod";
|
|
30
7
|
|
|
31
8
|
// src/size.ts
|
|
32
9
|
var IMAGE_SIZES = {
|
|
@@ -45,10 +22,24 @@ function appendSizeToPrompt(prompt, size) {
|
|
|
45
22
|
}
|
|
46
23
|
|
|
47
24
|
// src/codex.ts
|
|
48
|
-
var
|
|
49
|
-
var CODEX_IMAGES_EDITS_ENDPOINT = "https://chatgpt.com/backend-api/codex/images/edits";
|
|
25
|
+
var CODEX_IMAGES_BASE_URL = "https://chatgpt.com/backend-api/codex";
|
|
50
26
|
var CODEX_REQUEST_DEFAULTS = { model: "gpt-image-2", quality: "auto", size: "auto" };
|
|
51
|
-
|
|
27
|
+
function chatGptImagesTarget(auth) {
|
|
28
|
+
return {
|
|
29
|
+
baseURL: CODEX_IMAGES_BASE_URL,
|
|
30
|
+
headers: {
|
|
31
|
+
Authorization: `Bearer ${auth.access}`,
|
|
32
|
+
...auth.accountId ? { "ChatGPT-Account-Id": auth.accountId } : {}
|
|
33
|
+
}
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
function proxyImagesTarget(baseURL) {
|
|
37
|
+
return { baseURL, headers: {} };
|
|
38
|
+
}
|
|
39
|
+
function imagesEndpoint(baseURL, operation) {
|
|
40
|
+
return new URL(`images/${operation}`, baseURL.endsWith("/") ? baseURL : `${baseURL}/`).toString();
|
|
41
|
+
}
|
|
42
|
+
async function callViaCodexImages(target, args, inputImageDataUrls, signal) {
|
|
52
43
|
const isEdit = inputImageDataUrls.length > 0;
|
|
53
44
|
const body = {
|
|
54
45
|
prompt: appendSizeToPrompt(args.prompt, args.size),
|
|
@@ -56,15 +47,15 @@ async function callViaCodexImages(auth, args, inputImageDataUrls) {
|
|
|
56
47
|
background: args.background ?? "opaque",
|
|
57
48
|
...isEdit ? { images: inputImageDataUrls.map((dataUrl) => ({ image_url: dataUrl })) } : {}
|
|
58
49
|
};
|
|
59
|
-
const res = await fetch(isEdit ?
|
|
50
|
+
const res = await fetch(imagesEndpoint(target.baseURL, isEdit ? "edits" : "generations"), {
|
|
60
51
|
method: "POST",
|
|
61
52
|
headers: {
|
|
62
53
|
"Content-Type": "application/json",
|
|
63
|
-
|
|
64
|
-
...auth.accountId ? { "ChatGPT-Account-Id": auth.accountId } : {},
|
|
54
|
+
...target.headers,
|
|
65
55
|
originator: "opencode"
|
|
66
56
|
},
|
|
67
|
-
body: JSON.stringify(body)
|
|
57
|
+
body: JSON.stringify(body),
|
|
58
|
+
signal
|
|
68
59
|
});
|
|
69
60
|
if (!res.ok) {
|
|
70
61
|
const detail = await res.text().catch(() => "");
|
|
@@ -78,12 +69,12 @@ async function callViaCodexImages(auth, args, inputImageDataUrls) {
|
|
|
78
69
|
}
|
|
79
70
|
|
|
80
71
|
// src/input-image.ts
|
|
81
|
-
import * as
|
|
82
|
-
import * as
|
|
72
|
+
import * as fs from "node:fs/promises";
|
|
73
|
+
import * as path from "node:path";
|
|
83
74
|
import { fileTypeFromBuffer } from "file-type";
|
|
84
75
|
async function readImageAsDataUrl(filePath, ctxDir) {
|
|
85
|
-
const abs =
|
|
86
|
-
const buf = await
|
|
76
|
+
const abs = path.isAbsolute(filePath) ? filePath : path.resolve(ctxDir, filePath);
|
|
77
|
+
const buf = await fs.readFile(abs);
|
|
87
78
|
const detected = await fileTypeFromBuffer(buf);
|
|
88
79
|
if (!detected?.mime.startsWith("image/")) {
|
|
89
80
|
throw new Error(`unsupported image file type: ${abs}`);
|
|
@@ -95,12 +86,12 @@ async function readReferenceImages(paths, ctxDir) {
|
|
|
95
86
|
}
|
|
96
87
|
|
|
97
88
|
// src/output-image.ts
|
|
98
|
-
import * as
|
|
99
|
-
import * as
|
|
89
|
+
import * as fs2 from "node:fs/promises";
|
|
90
|
+
import * as path2 from "node:path";
|
|
100
91
|
var MAX_OUTPUT_VERSION_SUFFIX = 999;
|
|
101
92
|
async function pathExists(p) {
|
|
102
93
|
try {
|
|
103
|
-
await
|
|
94
|
+
await fs2.access(p);
|
|
104
95
|
return true;
|
|
105
96
|
} catch {
|
|
106
97
|
return false;
|
|
@@ -109,11 +100,11 @@ async function pathExists(p) {
|
|
|
109
100
|
async function pickNonOverwritePath(requested, maxVersion = MAX_OUTPUT_VERSION_SUFFIX) {
|
|
110
101
|
if (!await pathExists(requested))
|
|
111
102
|
return requested;
|
|
112
|
-
const dir =
|
|
113
|
-
const ext =
|
|
114
|
-
const stem =
|
|
103
|
+
const dir = path2.dirname(requested);
|
|
104
|
+
const ext = path2.extname(requested);
|
|
105
|
+
const stem = path2.basename(requested, ext);
|
|
115
106
|
for (let n = 2;n <= maxVersion; n++) {
|
|
116
|
-
const candidate =
|
|
107
|
+
const candidate = path2.join(dir, `${stem}-v${n}${ext}`);
|
|
117
108
|
if (!await pathExists(candidate))
|
|
118
109
|
return candidate;
|
|
119
110
|
}
|
|
@@ -128,25 +119,25 @@ function buildSavedMessage(savedPath, requestedPath, size) {
|
|
|
128
119
|
}
|
|
129
120
|
async function isDirectory(p) {
|
|
130
121
|
try {
|
|
131
|
-
return (await
|
|
122
|
+
return (await fs2.stat(p)).isDirectory();
|
|
132
123
|
} catch {
|
|
133
124
|
return false;
|
|
134
125
|
}
|
|
135
126
|
}
|
|
136
127
|
async function ensureDir(dir) {
|
|
137
128
|
try {
|
|
138
|
-
await
|
|
129
|
+
await fs2.mkdir(dir, { recursive: true });
|
|
139
130
|
} catch (e) {
|
|
140
131
|
if (e.code !== "EEXIST" || !await isDirectory(dir))
|
|
141
132
|
throw e;
|
|
142
133
|
}
|
|
143
134
|
}
|
|
144
135
|
async function saveGeneratedImage(out, ctxDir, base64) {
|
|
145
|
-
const requestedPath =
|
|
146
|
-
await ensureDir(
|
|
136
|
+
const requestedPath = path2.isAbsolute(out) ? out : path2.resolve(ctxDir, out);
|
|
137
|
+
await ensureDir(path2.dirname(requestedPath));
|
|
147
138
|
const savedPath = await pickNonOverwritePath(requestedPath);
|
|
148
139
|
const png = Buffer.from(base64, "base64");
|
|
149
|
-
await
|
|
140
|
+
await fs2.writeFile(savedPath, png);
|
|
150
141
|
return {
|
|
151
142
|
savedPath,
|
|
152
143
|
versioned: savedPath !== requestedPath,
|
|
@@ -154,71 +145,169 @@ async function saveGeneratedImage(out, ctxDir, base64) {
|
|
|
154
145
|
};
|
|
155
146
|
}
|
|
156
147
|
|
|
157
|
-
// src/
|
|
148
|
+
// src/imagegen.ts
|
|
158
149
|
var argsShape = {
|
|
159
|
-
prompt:
|
|
160
|
-
out:
|
|
161
|
-
size:
|
|
150
|
+
prompt: z.string().describe("Description of the image to generate."),
|
|
151
|
+
out: z.string().describe("Output file path, relative to the project directory unless absolute. The plugin writes a PNG."),
|
|
152
|
+
size: z.enum(Object.keys(IMAGE_SIZES), {
|
|
162
153
|
error: (issue) => issue.input == null ? `Missing size. Use one of: ${SIZE_CHOICES}.` : `Unsupported size "${issue.input}". Use one of: ${SIZE_CHOICES}.`
|
|
163
154
|
}).describe([
|
|
164
155
|
`Output size. Only these sizes can be generated: ${SIZE_CHOICES}.`,
|
|
165
156
|
"Typical choices: 1672x941 for a 16:9 video thumbnail, 1254x1254 for a square icon, 941x1672 for a phone wallpaper."
|
|
166
157
|
].join(" ")),
|
|
167
|
-
images:
|
|
168
|
-
background:
|
|
158
|
+
images: z.array(z.string()).max(5).nullish().describe("Optional reference image paths, up to 5, relative to the project directory unless absolute."),
|
|
159
|
+
background: z.enum(["opaque", "transparent"]).nullish().describe([
|
|
169
160
|
"Optional background of the output image. Defaults to `opaque`.",
|
|
170
161
|
"Use `transparent` when the request calls for a transparent background, including background removal or a cutout.",
|
|
171
162
|
"When editing reference images, preserve their existing transparency unless the user asks to change it."
|
|
172
163
|
].join(" "))
|
|
173
164
|
};
|
|
174
|
-
var argsSchema =
|
|
175
|
-
var
|
|
165
|
+
var argsSchema = z.object(argsShape);
|
|
166
|
+
var optionsSchema = z.object({
|
|
167
|
+
baseURL: z.url({ protocol: /^https?$/ }).refine((value) => {
|
|
168
|
+
const url = new URL(value);
|
|
169
|
+
return url.search === "" && url.hash === "";
|
|
170
|
+
}, "baseURL must not have a query or a fragment").optional()
|
|
171
|
+
});
|
|
172
|
+
async function resolveImagesTarget(options, loadOpenAIAuth) {
|
|
173
|
+
const parsed = optionsSchema.safeParse(options ?? {});
|
|
174
|
+
if (!parsed.success) {
|
|
175
|
+
throw new Error(`invalid opencode-gpt-imagegen options: ${z.prettifyError(parsed.error)}`);
|
|
176
|
+
}
|
|
177
|
+
if (parsed.data.baseURL) {
|
|
178
|
+
return proxyImagesTarget(parsed.data.baseURL);
|
|
179
|
+
}
|
|
180
|
+
const auth = await loadOpenAIAuth();
|
|
181
|
+
if (!auth) {
|
|
182
|
+
throw new Error("OpenAI ChatGPT OAuth credentials not configured.");
|
|
183
|
+
}
|
|
184
|
+
return chatGptImagesTarget(auth);
|
|
185
|
+
}
|
|
186
|
+
function createImagegenTool(options, loadOpenAIAuth) {
|
|
187
|
+
const authNote = options?.baseURL ? "Sends requests to the proxy set by the plugin's `baseURL` option instead of ChatGPT, so ChatGPT OAuth is not used." : "Requires OpenCode to be authenticated with ChatGPT OAuth.";
|
|
188
|
+
return {
|
|
189
|
+
description: [
|
|
190
|
+
"Generate raster images through the image generation endpoints of the ChatGPT Codex backend.",
|
|
191
|
+
"Use for AI-created bitmap visuals such as photos, illustrations, textures, sprites, and mockups.",
|
|
192
|
+
"Do not use when the task is better handled by editing existing SVG/vector/code-native assets, extending an established icon or logo system, or building the visual directly in HTML/CSS/canvas.",
|
|
193
|
+
"Reference images may be attached through `images`; label each image's role inline in `prompt`, for example: 'Image 1: reference image'.",
|
|
194
|
+
"For many distinct assets, invoke gpt_imagegen once per requested asset rather than relying on multi-image output; gpt_imagegen returns one image per call.",
|
|
195
|
+
`${authNote} Returns the absolute path of the saved PNG.`,
|
|
196
|
+
"Before generating, decide the size. If the user named a size that is not supported, or gave no size and the use does not clearly imply a shape, ask the user which size to use (with the question tool when available).",
|
|
197
|
+
"In that question, offer every supported size as an option labeled like `1672x941 (16:9)`, put the one you recommend first with ` (Recommended)` appended to its label, and give each option a short description of what it suits.",
|
|
198
|
+
"Do not add catch-all options such as 'Other' or 'Let me decide'.",
|
|
199
|
+
"In the question text, say that other sizes cannot be generated directly and that the image can be resized or cropped to an exact size afterwards, for example with ImageMagick.",
|
|
200
|
+
"If the use clearly implies a shape, such as a YouTube thumbnail or an app icon, pick the matching size without asking.",
|
|
201
|
+
"The saved image can differ from the requested size by 1px, so do not promise exact pixel dimensions before generating. After generating, tell the user the size reported in the tool result."
|
|
202
|
+
].join(" "),
|
|
203
|
+
schema: argsSchema,
|
|
204
|
+
async execute(input, directory, signal) {
|
|
205
|
+
const parsed = argsSchema.safeParse(input);
|
|
206
|
+
if (!parsed.success) {
|
|
207
|
+
throw new Error(z.prettifyError(parsed.error));
|
|
208
|
+
}
|
|
209
|
+
const args = parsed.data;
|
|
210
|
+
const target = await resolveImagesTarget(options, loadOpenAIAuth);
|
|
211
|
+
const inputImageDataUrls = await readReferenceImages(args.images, directory);
|
|
212
|
+
const base64 = await callViaCodexImages(target, args, inputImageDataUrls, signal);
|
|
213
|
+
return saveGeneratedImage(args.out, directory, base64);
|
|
214
|
+
}
|
|
215
|
+
};
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
// src/v1-auth.ts
|
|
219
|
+
import * as fs3 from "node:fs/promises";
|
|
220
|
+
async function loadAuthData(envContent, authFile) {
|
|
221
|
+
if (envContent) {
|
|
222
|
+
return JSON.parse(envContent);
|
|
223
|
+
}
|
|
224
|
+
if (!authFile) {
|
|
225
|
+
throw new Error("could not determine XDG data directory");
|
|
226
|
+
}
|
|
227
|
+
const raw = await fs3.readFile(authFile, "utf-8");
|
|
228
|
+
return JSON.parse(raw);
|
|
229
|
+
}
|
|
230
|
+
async function loadOpenAIAuth(envContent, authFile) {
|
|
231
|
+
try {
|
|
232
|
+
const data = await loadAuthData(envContent, authFile);
|
|
233
|
+
const entry = data.openai;
|
|
234
|
+
if (entry?.type === "oauth" && typeof entry.access === "string") {
|
|
235
|
+
return entry;
|
|
236
|
+
}
|
|
237
|
+
} catch {
|
|
238
|
+
return;
|
|
239
|
+
}
|
|
240
|
+
return;
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
// src/v1.ts
|
|
244
|
+
var server = async (_input, options) => {
|
|
245
|
+
const imagegen = createImagegenTool(options, () => loadOpenAIAuth(process.env.OPENCODE_AUTH_CONTENT, xdgData ? path3.join(xdgData, "opencode", "auth.json") : undefined));
|
|
176
246
|
return {
|
|
177
247
|
tool: {
|
|
178
|
-
gpt_imagegen:
|
|
179
|
-
description:
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
"Reference images may be attached through `images`; label each image's role inline in `prompt`, for example: 'Image 1: reference image'.",
|
|
184
|
-
"For many distinct assets, invoke gpt_imagegen once per requested asset rather than relying on multi-image output; gpt_imagegen returns one image per call.",
|
|
185
|
-
"Requires OpenCode to be authenticated with ChatGPT OAuth. Returns the absolute path of the saved PNG.",
|
|
186
|
-
"Before generating, decide the size. If the user named a size that is not supported, or gave no size and the use does not clearly imply a shape, ask the user which size to use (with the question tool when available).",
|
|
187
|
-
"In that question, offer every supported size as an option labeled like `1672x941 (16:9)`, put the one you recommend first with ` (Recommended)` appended to its label, and give each option a short description of what it suits.",
|
|
188
|
-
"Do not add catch-all options such as 'Other' or 'Let me decide'.",
|
|
189
|
-
"In the question text, say that other sizes cannot be generated directly and that the image can be resized or cropped to an exact size afterwards, for example with ImageMagick.",
|
|
190
|
-
"If the use clearly implies a shape, such as a YouTube thumbnail or an app icon, pick the matching size without asking.",
|
|
191
|
-
"The saved image can differ from the requested size by 1px, so do not promise exact pixel dimensions before generating. After generating, tell the user the size reported in the tool result."
|
|
192
|
-
].join(" "),
|
|
193
|
-
args: argsShape,
|
|
194
|
-
async execute(rawArgs, ctx) {
|
|
195
|
-
const parsed = argsSchema.safeParse(rawArgs);
|
|
196
|
-
if (!parsed.success) {
|
|
197
|
-
throw new Error(tool.schema.prettifyError(parsed.error));
|
|
198
|
-
}
|
|
199
|
-
const args = parsed.data;
|
|
200
|
-
const auth = await loadOpenAIAuth();
|
|
201
|
-
if (!auth) {
|
|
202
|
-
throw new Error("OpenAI ChatGPT OAuth credentials not configured.");
|
|
203
|
-
}
|
|
204
|
-
const inputImageDataUrls = await readReferenceImages(args.images, ctx.directory);
|
|
205
|
-
const base64 = await callViaCodexImages(auth, args, inputImageDataUrls);
|
|
206
|
-
const { savedPath, versioned, message } = await saveGeneratedImage(args.out, ctx.directory, base64);
|
|
248
|
+
gpt_imagegen: {
|
|
249
|
+
description: imagegen.description,
|
|
250
|
+
args: imagegen.schema.shape,
|
|
251
|
+
async execute(input, context) {
|
|
252
|
+
const result = await imagegen.execute(input, context.directory, context.abort);
|
|
207
253
|
return {
|
|
208
|
-
output: message,
|
|
209
|
-
metadata: {
|
|
210
|
-
out: savedPath,
|
|
211
|
-
versioned
|
|
212
|
-
}
|
|
254
|
+
output: result.message,
|
|
255
|
+
metadata: { out: result.savedPath, versioned: result.versioned }
|
|
213
256
|
};
|
|
214
257
|
}
|
|
215
|
-
}
|
|
258
|
+
}
|
|
216
259
|
}
|
|
217
260
|
};
|
|
218
261
|
};
|
|
262
|
+
|
|
263
|
+
// src/v2.ts
|
|
264
|
+
import { z as z2 } from "zod";
|
|
265
|
+
|
|
266
|
+
// src/v2-auth.ts
|
|
267
|
+
async function loadOpenAIAuth2(connections) {
|
|
268
|
+
const connection = await connections.active("openai");
|
|
269
|
+
const credential = connection ? await connections.resolve(connection) : undefined;
|
|
270
|
+
if (!credential)
|
|
271
|
+
return;
|
|
272
|
+
if (credential.type !== "oauth" || credential.methodID !== "chatgpt-browser" && credential.methodID !== "chatgpt-headless") {
|
|
273
|
+
const method = credential.type === "oauth" ? credential.methodID : credential.type;
|
|
274
|
+
throw new Error(`The OpenAI connection's sign-in method (${method}) cannot generate images. In OpenCode, connect OpenAI and choose "Codex browser (legacy)" or "Codex device code (legacy)".`);
|
|
275
|
+
}
|
|
276
|
+
const accountId = credential.metadata?.accountID;
|
|
277
|
+
return {
|
|
278
|
+
type: "oauth",
|
|
279
|
+
access: credential.access,
|
|
280
|
+
...typeof accountId === "string" ? { accountId } : {}
|
|
281
|
+
};
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
// src/v2.ts
|
|
285
|
+
var setup = async (context) => {
|
|
286
|
+
const imagegen = createImagegenTool(context.options, () => loadOpenAIAuth2(context.integration.connection));
|
|
287
|
+
const input = z2.toJSONSchema(imagegen.schema, { io: "input" });
|
|
288
|
+
await context.tool.transform((editor) => {
|
|
289
|
+
editor.add({
|
|
290
|
+
name: "gpt_imagegen",
|
|
291
|
+
description: imagegen.description,
|
|
292
|
+
input,
|
|
293
|
+
options: { codemode: false },
|
|
294
|
+
async execute(args, execution) {
|
|
295
|
+
const session = await context.session.get({ sessionID: execution.sessionID });
|
|
296
|
+
const result = await imagegen.execute(args, session.location.directory, execution.signal);
|
|
297
|
+
return {
|
|
298
|
+
content: result.message,
|
|
299
|
+
metadata: { out: result.savedPath, versioned: result.versioned }
|
|
300
|
+
};
|
|
301
|
+
}
|
|
302
|
+
});
|
|
303
|
+
});
|
|
304
|
+
};
|
|
305
|
+
|
|
306
|
+
// src/index.ts
|
|
219
307
|
var src_default = {
|
|
220
308
|
id: "opencode-gpt-imagegen",
|
|
221
|
-
server
|
|
309
|
+
server,
|
|
310
|
+
setup
|
|
222
311
|
};
|
|
223
312
|
export {
|
|
224
313
|
src_default as default
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "opencode-gpt-imagegen",
|
|
3
|
-
"version": "1.0
|
|
3
|
+
"version": "1.2.0",
|
|
4
4
|
"description": "OpenCode plugin for GPT Image 2 generation through your ChatGPT subscription, with reference images and safe PNG output.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -52,18 +52,17 @@
|
|
|
52
52
|
"bugs": {
|
|
53
53
|
"url": "https://github.com/yuji-hatakeyama/opencode-gpt-imagegen/issues"
|
|
54
54
|
},
|
|
55
|
-
"peerDependencies": {
|
|
56
|
-
"@opencode-ai/plugin": "^1.14.0"
|
|
57
|
-
},
|
|
58
55
|
"devDependencies": {
|
|
59
56
|
"@biomejs/biome": "^2.5.3",
|
|
60
57
|
"@opencode-ai/plugin": "^1.14.41",
|
|
58
|
+
"@opencode/plugin": "^2.1.4",
|
|
61
59
|
"@tsconfig/node22": "^22.0.2",
|
|
62
60
|
"@types/bun": "^1.3.14",
|
|
63
61
|
"typescript": "^7.0.2"
|
|
64
62
|
},
|
|
65
63
|
"dependencies": {
|
|
66
64
|
"file-type": "^22.0.1",
|
|
67
|
-
"xdg-basedir": "^5.1.0"
|
|
65
|
+
"xdg-basedir": "^5.1.0",
|
|
66
|
+
"zod": "4.1.8"
|
|
68
67
|
}
|
|
69
68
|
}
|