opencode-gpt-imagegen 1.0.1 → 1.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.
Files changed (3) hide show
  1. package/README.md +19 -1
  2. package/dist/index.js +60 -14
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -32,7 +32,25 @@ Add this plugin to your [OpenCode config](https://opencode.ai/docs/plugins/). Fo
32
32
  }
33
33
  ```
34
34
 
35
- OpenCode auto-installs the package via Bun on next launch — no separate `npm install` step is needed. The plugin requires OpenCode to be authenticated with ChatGPT.
35
+ OpenCode auto-installs the package via Bun on next launch — no separate `npm install` step is needed. The plugin requires OpenCode to be authenticated with ChatGPT, unless you send requests through a proxy as described in [Sending requests through a proxy](#sending-requests-through-a-proxy).
36
+
37
+ ### Sending requests through a proxy
38
+
39
+ 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.
40
+
41
+ ```json
42
+ {
43
+ "plugin": [["opencode-gpt-imagegen", { "baseURL": "http://127.0.0.1:3457/v1" }]]
44
+ }
45
+ ```
46
+
47
+ With `baseURL` set, the plugin does not read `auth.json` and sends the proxy no credentials. 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:
48
+
49
+ - accepts those two `POST` routes without an `Authorization` header;
50
+ - 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;
51
+ - 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.
52
+
53
+ 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
54
 
37
55
  ### Updating the plugin
38
56
 
package/dist/index.js CHANGED
@@ -45,10 +45,24 @@ function appendSizeToPrompt(prompt, size) {
45
45
  }
46
46
 
47
47
  // src/codex.ts
48
- var CODEX_IMAGES_GENERATIONS_ENDPOINT = "https://chatgpt.com/backend-api/codex/images/generations";
49
- var CODEX_IMAGES_EDITS_ENDPOINT = "https://chatgpt.com/backend-api/codex/images/edits";
48
+ var CODEX_IMAGES_BASE_URL = "https://chatgpt.com/backend-api/codex";
50
49
  var CODEX_REQUEST_DEFAULTS = { model: "gpt-image-2", quality: "auto", size: "auto" };
51
- async function callViaCodexImages(auth, args, inputImageDataUrls) {
50
+ function chatGptImagesTarget(auth) {
51
+ return {
52
+ baseURL: CODEX_IMAGES_BASE_URL,
53
+ headers: {
54
+ Authorization: `Bearer ${auth.access}`,
55
+ ...auth.accountId ? { "ChatGPT-Account-Id": auth.accountId } : {}
56
+ }
57
+ };
58
+ }
59
+ function proxyImagesTarget(baseURL) {
60
+ return { baseURL, headers: {} };
61
+ }
62
+ function imagesEndpoint(baseURL, operation) {
63
+ return new URL(`images/${operation}`, baseURL.endsWith("/") ? baseURL : `${baseURL}/`).toString();
64
+ }
65
+ async function callViaCodexImages(target, args, inputImageDataUrls) {
52
66
  const isEdit = inputImageDataUrls.length > 0;
53
67
  const body = {
54
68
  prompt: appendSizeToPrompt(args.prompt, args.size),
@@ -56,12 +70,11 @@ async function callViaCodexImages(auth, args, inputImageDataUrls) {
56
70
  background: args.background ?? "opaque",
57
71
  ...isEdit ? { images: inputImageDataUrls.map((dataUrl) => ({ image_url: dataUrl })) } : {}
58
72
  };
59
- const res = await fetch(isEdit ? CODEX_IMAGES_EDITS_ENDPOINT : CODEX_IMAGES_GENERATIONS_ENDPOINT, {
73
+ const res = await fetch(imagesEndpoint(target.baseURL, isEdit ? "edits" : "generations"), {
60
74
  method: "POST",
61
75
  headers: {
62
76
  "Content-Type": "application/json",
63
- Authorization: `Bearer ${auth.access}`,
64
- ...auth.accountId ? { "ChatGPT-Account-Id": auth.accountId } : {},
77
+ ...target.headers,
65
78
  originator: "opencode"
66
79
  },
67
80
  body: JSON.stringify(body)
@@ -126,9 +139,24 @@ function buildSavedMessage(savedPath, requestedPath, size) {
126
139
  const versionNote = savedPath !== requestedPath ? ` (the requested path ${requestedPath} already existed; the new image was versioned to avoid overwriting it)` : "";
127
140
  return `Generated image saved to ${savedPath}${versionNote}. The image is ${size.width}x${size.height} pixels.`;
128
141
  }
142
+ async function isDirectory(p) {
143
+ try {
144
+ return (await fs3.stat(p)).isDirectory();
145
+ } catch {
146
+ return false;
147
+ }
148
+ }
149
+ async function ensureDir(dir) {
150
+ try {
151
+ await fs3.mkdir(dir, { recursive: true });
152
+ } catch (e) {
153
+ if (e.code !== "EEXIST" || !await isDirectory(dir))
154
+ throw e;
155
+ }
156
+ }
129
157
  async function saveGeneratedImage(out, ctxDir, base64) {
130
158
  const requestedPath = path3.isAbsolute(out) ? out : path3.resolve(ctxDir, out);
131
- await fs3.mkdir(path3.dirname(requestedPath), { recursive: true });
159
+ await ensureDir(path3.dirname(requestedPath));
132
160
  const savedPath = await pickNonOverwritePath(requestedPath);
133
161
  const png = Buffer.from(base64, "base64");
134
162
  await fs3.writeFile(savedPath, png);
@@ -157,7 +185,28 @@ var argsShape = {
157
185
  ].join(" "))
158
186
  };
159
187
  var argsSchema = tool.schema.object(argsShape);
160
- var GptImagePlugin = async (_input) => {
188
+ var optionsSchema = tool.schema.object({
189
+ baseURL: tool.schema.url({ protocol: /^https?$/ }).refine((value) => {
190
+ const url = new URL(value);
191
+ return url.search === "" && url.hash === "";
192
+ }, "baseURL must not have a query or a fragment").optional()
193
+ });
194
+ async function resolveImagesTarget(options) {
195
+ const parsed = optionsSchema.safeParse(options ?? {});
196
+ if (!parsed.success) {
197
+ throw new Error(`invalid opencode-gpt-imagegen options: ${tool.schema.prettifyError(parsed.error)}`);
198
+ }
199
+ if (parsed.data.baseURL) {
200
+ return proxyImagesTarget(parsed.data.baseURL);
201
+ }
202
+ const auth = await loadOpenAIAuth();
203
+ if (!auth) {
204
+ throw new Error("OpenAI ChatGPT OAuth credentials not configured.");
205
+ }
206
+ return chatGptImagesTarget(auth);
207
+ }
208
+ var GptImagePlugin = async (_input, options) => {
209
+ 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.";
161
210
  return {
162
211
  tool: {
163
212
  gpt_imagegen: tool({
@@ -167,7 +216,7 @@ var GptImagePlugin = async (_input) => {
167
216
  "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.",
168
217
  "Reference images may be attached through `images`; label each image's role inline in `prompt`, for example: 'Image 1: reference image'.",
169
218
  "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.",
170
- "Requires OpenCode to be authenticated with ChatGPT OAuth. Returns the absolute path of the saved PNG.",
219
+ `${authNote} Returns the absolute path of the saved PNG.`,
171
220
  "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).",
172
221
  "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.",
173
222
  "Do not add catch-all options such as 'Other' or 'Let me decide'.",
@@ -182,12 +231,9 @@ var GptImagePlugin = async (_input) => {
182
231
  throw new Error(tool.schema.prettifyError(parsed.error));
183
232
  }
184
233
  const args = parsed.data;
185
- const auth = await loadOpenAIAuth();
186
- if (!auth) {
187
- throw new Error("OpenAI ChatGPT OAuth credentials not configured.");
188
- }
234
+ const target = await resolveImagesTarget(options);
189
235
  const inputImageDataUrls = await readReferenceImages(args.images, ctx.directory);
190
- const base64 = await callViaCodexImages(auth, args, inputImageDataUrls);
236
+ const base64 = await callViaCodexImages(target, args, inputImageDataUrls);
191
237
  const { savedPath, versioned, message } = await saveGeneratedImage(args.out, ctx.directory, base64);
192
238
  return {
193
239
  output: message,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-gpt-imagegen",
3
- "version": "1.0.1",
3
+ "version": "1.1.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",