Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

feat(images): serve image generation from a signed-in ChatGPT account

vastsa6881a2bfd332
diff --git a/apps/desktop/electron/main/services/image-generation-service.ts b/apps/desktop/electron/main/services/image-generation-service.ts
index 9dcbd2b46..691abb0e4 100644
--- a/apps/desktop/electron/main/services/image-generation-service.ts
+++ b/apps/desktop/electron/main/services/image-generation-service.ts
@@ -5,7 +5,9 @@ import { createImageBinding, generateImageBatch, type ImageOperationMetadata } f
import type { ImageApi, ImageModel } from "@earendil-works/pi-ai";
import type { VendorOAuth } from "../oauth";
import {
+ CODEX_IMAGE_VENDOR_KEY,
imageGenerationPrompts,
+ imageModelOfferedByProvider,
parseImageGenerationBinding,
type AppSettings,
type ProviderPublic,
@@ -48,7 +50,7 @@ export function createImageGenerationTool(options: {
if (
!provider?.enabled ||
!provider.baseUrl ||
- !provider.models.some((model) => model.id === binding.modelId)
+ !imageModelOfferedByProvider(provider, binding.modelId)
) {
return failure(
"IMAGE_MODEL_UNAVAILABLE",
@@ -61,12 +63,18 @@ export function createImageGenerationTool(options: {
if (provider.authKind !== "none" && provider.authKind !== "oauth" && !value)
return failure("IMAGE_AUTH_FAILED", "The image provider needs an API key.");
const downloadOptions = { allowFakeIp: options.allowFakeIp?.() === true };
+ // A signed-in Codex account serves images on the vendor's Codex routes and
+ // identifies the calling client with `originator`, the header its chat
+ // traffic sends. A configured header still wins.
+ const codexImages = provider.authKind === "oauth" &&
+ provider.vendorKey === CODEX_IMAGE_VENDOR_KEY;
+ const headers = codexImages ? { originator: "pi", ...provider.headers } : provider.headers;
let imageBinding;
try {
imageBinding = createImageBinding({
nativeModel: await options.resolveImageModel?.(provider, binding.modelId),
providerId: provider.id, vendorKey: provider.vendorKey, authKind: provider.authKind,
- baseUrl: provider.baseUrl, modelId: binding.modelId, apiKey: value, headers: provider.headers,
+ baseUrl: provider.baseUrl, modelId: binding.modelId, apiKey: value, headers,
...(provider.authKind === "oauth" && options.resolveAuth
? { resolveAuth: () => options.resolveAuth!(provider.id) } : {}),
}, downloadOptions);
diff --git a/apps/desktop/src/components/settings/ImageGenerationModelRow.tsx b/apps/desktop/src/components/settings/ImageGenerationModelRow.tsx
index aa69391c2..070117fee 100644
--- a/apps/desktop/src/components/settings/ImageGenerationModelRow.tsx
+++ b/apps/desktop/src/components/settings/ImageGenerationModelRow.tsx
@@ -1,6 +1,7 @@
import { useTranslation } from "react-i18next";
import {
imageGenerationBindings,
+ vendorAccountImageCandidates,
type AppSettings,
type ImageGenerationBinding,
type ProviderPublic,
@@ -28,10 +29,15 @@ export function ImageGenerationModelRow({
const binding = settings.imageGeneration;
// An explicit candidate list is the user's selection. Do not put the stored
// default back when they cleared it; only a missing list is the legacy
- // single-binding fallback.
- const candidates = Array.isArray(settings.imageGenerationModels)
+ // single-binding fallback. A signed-in vendor account also offers the image
+ // model it answers with, which its chat model list does not carry.
+ const configured = Array.isArray(settings.imageGenerationModels)
? imageGenerationBindings(settings.imageGenerationModels, null)
: imageGenerationBindings(undefined, binding);
+ const candidates = imageGenerationBindings(
+ [...configured, ...vendorAccountImageCandidates(providers)],
+ null,
+ );
if (candidates.length === 0) return null;
const activeCandidate = binding
diff --git a/apps/desktop/src/components/settings/ModelConfigPage.tsx b/apps/desktop/src/components/settings/ModelConfigPage.tsx
index ed135d233..4a0a7ffaf 100644
--- a/apps/desktop/src/components/settings/ModelConfigPage.tsx
+++ b/apps/desktop/src/components/settings/ModelConfigPage.tsx
@@ -10,6 +10,7 @@
import { useEffect, useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import {
+ vendorAccountImageCandidates,
type ImageGenerationBinding,
type ModelBinding,
type ProviderPublic,
@@ -123,8 +124,13 @@ export function ModelConfigPage() {
}, []);
const imageGenerationCandidates = useMemo(
- () => imageCandidates(settings?.imageGenerationModels, settings?.imageGeneration),
- [settings?.imageGenerationModels, settings?.imageGeneration],
+ () => imageCandidates([
+ ...imageCandidates(settings?.imageGenerationModels, settings?.imageGeneration),
+ // A signed-in vendor account serves its image model without listing it as
+ // a chat model, so it must reach this list or the picker row never renders.
+ ...vendorAccountImageCandidates(providers),
+ ], null),
+ [settings?.imageGenerationModels, settings?.imageGeneration, providers],
);
const providerReady = (provider: ProviderPublic) =>
providerServesChatModels(provider, imageGenerationCandidates);
diff --git a/apps/desktop/src/components/settings/image-generation-default.ts b/apps/desktop/src/components/settings/image-generation-default.ts
index cb2403228..82a11bd60 100644
--- a/apps/desktop/src/components/settings/image-generation-default.ts
+++ b/apps/desktop/src/components/settings/image-generation-default.ts
@@ -11,15 +11,17 @@
* "Can run it" is one rule everywhere: this file, the picker row
* (`ImageGenerationModelRow.tsx`) and the runtime
* (`electron/main/services/image-generation-service.ts`) all require an
- * enabled, non-OAuth provider with a base URL, a usable credential and a
- * configured model exactly matching the binding. A binding that only looks
- * present — disabled provider, missing key, OAuth-only row, or a model id the
- * provider does not configure — fails at send time, so it must never be kept as
- * the default either.
+ * enabled provider with a base URL, a usable credential and a model that
+ * provider serves — either one it configures, or the image model a signed-in
+ * vendor account answers with (see `imageModelOfferedByProvider`). A binding
+ * that only looks present — disabled provider, missing credential, or a model
+ * id the provider does not serve — fails at send time, so it must never be
+ * kept as the default either.
*/
import {
MAX_IMAGE_GENERATION_MODELS,
imageGenerationBindings,
+ imageModelOfferedByProvider,
type ImageGenerationBinding,
type ProviderPublic,
modelWireIdsEqual as sameComposerModelId,
@@ -38,12 +40,11 @@ export function imageGenerationBindingAvailable(
): boolean {
if (!provider || !provider.enabled) return false;
return (
- provider.authKind !== "oauth" &&
!!provider.baseUrl &&
- (provider.hasSecret || provider.authKind === "none") &&
- // Mirror image-generation-service's exact availability guard. A different
- // case is a different outbound wire ID for a case-sensitive endpoint.
- provider.models.some((model) => model.id === modelId)
+ (provider.hasSecret || provider.hasOauth === true || provider.authKind === "none") &&
+ // Mirror image-generation-service's availability guard exactly: the same
+ // model offer, so a choice the row shows can never fail at send time.
+ imageModelOfferedByProvider(provider, modelId)
);
}
diff --git a/apps/desktop/test/image-generation-default.test.mjs b/apps/desktop/test/image-generation-default.test.mjs
index 504fe7d46..ed67add1f 100644
--- a/apps/desktop/test/image-generation-default.test.mjs
+++ b/apps/desktop/test/image-generation-default.test.mjs
@@ -8,10 +8,11 @@
* choice stops being *runnable*.
*
* "Runnable" is the strict rule the picker row and the runtime apply: enabled
- * provider, non-OAuth, base URL, a usable credential and one of the provider's
- * configured models matched exactly. `providerOffersModel` is deliberately
- * looser — it answers whether a row *names* a model for the summary line — so
- * the assertions here must not accept it as proof that a default can run.
+ * provider, base URL, a usable credential and a model the provider serves —
+ * either one it configures, or the image model a signed-in vendor account
+ * answers with. `providerOffersModel` is deliberately looser — it answers
+ * whether a row *names* a model for the summary line — so the assertions here
+ * must not accept it as proof that a default can run.
*/
import assert from "node:assert/strict";
import { register } from "node:module";
@@ -372,3 +373,46 @@ test("unchecking every image model on the active provider clears the settings ch
assert.equal(plan.imageGeneration, null);
assert.deepEqual(plan.imageGenerationModels, [binding("y", "img-y")]);
});
+
+/** The provider row a ChatGPT (Codex) login creates: OAuth only, no API key. */
+const codexAccount = (over = {}) => provider("codex", [], {
+ vendorKey: "openai-codex",
+ authKind: "oauth",
+ hasSecret: false,
+ hasOauth: true,
+ baseUrl: "https://chatgpt.com/backend-api",
+ ...over,
+});
+
+test("a signed-in Codex account runs its image model and never one of its chat models", () => {
+ const signedIn = codexAccount({ models: [{ id: "gpt-6.1-sol" }] });
+ assert.equal(imageGenerationBindingAvailable(signedIn, "gpt-image-2"), true);
+ // Being OAuth does not turn a chat model into an image model.
+ assert.equal(imageGenerationBindingAvailable(signedIn, "gpt-6.1-sol"), false);
+ // Signed out, disabled, or another vendor's OAuth row still cannot generate.
+ assert.equal(imageGenerationBindingAvailable(codexAccount({ hasOauth: false }), "gpt-image-2"), false);
+ assert.equal(imageGenerationBindingAvailable(codexAccount({ enabled: false }), "gpt-image-2"), false);
+ assert.equal(imageGenerationBindingAvailable(
+ provider("a", [], { vendorKey: "anthropic", authKind: "oauth", hasOauth: true }),
+ "gpt-image-2",
+ ), false);
+});
+
+test("the Codex image model is offered as a candidate without being stored as a model", async () => {
+ const { vendorAccountImageCandidates } = await import("@pi-desktop/shared");
+ assert.deepEqual(
+ vendorAccountImageCandidates([codexAccount(), provider("x", ["img-x"])]),
+ [
+ { providerId: "codex", modelId: "gpt-image-2.5" },
+ { providerId: "codex", modelId: "gpt-image-2" },
+ ],
+ );
+ // A chosen Codex binding survives a provider save, because the row can run it.
+ const plan = planImageGenerationDefaults(
+ { imageGeneration: binding("codex", "gpt-image-2") },
+ "codex",
+ ["gpt-image-2"],
+ [codexAccount()],
+ );
+ assert.deepEqual(plan.imageGeneration, binding("codex", "gpt-image-2"));
+});
diff --git a/apps/desktop/test/image-generation.test.mjs b/apps/desktop/test/image-generation.test.mjs
index 251d16d3b..4cba0e98a 100644
--- a/apps/desktop/test/image-generation.test.mjs
+++ b/apps/desktop/test/image-generation.test.mjs
@@ -117,3 +117,105 @@ test("the default imagegen skill is discoverable and loads in an ordinary sessio
assert.match(body, /Do not retry/);
assert.equal(loadBuiltinSkillBody("../../outside"), null);
});
+
+/** The user path for a ChatGPT (Codex) login: pick its image model, then generate. */
+test("a signed-in Codex account generates and edits through its own image routes", async (t) => {
+ const dataDir = await mkdtemp(join(tmpdir(), "pi-images-codex-"));
+ t.after(() => rm(dataDir, { recursive: true, force: true }));
+ const requests = [];
+ const server = createServer(async (request, response) => {
+ let body = "";
+ for await (const chunk of request) body += chunk.toString("utf8");
+ requests.push({
+ url: request.url,
+ body,
+ authorization: request.headers.authorization,
+ originator: request.headers.originator,
+ contentType: request.headers["content-type"],
+ });
+ response.setHeader("Content-Type", "application/json");
+ response.end(JSON.stringify({ data: [{ b64_json: png.toString("base64") }] }));
+ });
+ await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
+ t.after(() => new Promise((resolve) => server.close(resolve)));
+ const host = {
+ call: async (method) => {
+ if (method === "settings.get")
+ return {
+ defaultModelId: "gpt-6.1-sol",
+ defaultProviderId: "codex-account",
+ imageGeneration: { providerId: "codex-account", modelId: "gpt-image-2.5" },
+ };
+ if (method === "providers.get")
+ return {
+ provider: {
+ id: "codex-account",
+ enabled: true,
+ authKind: "oauth",
+ hasOauth: true,
+ vendorKey: "openai-codex",
+ // The account's chat models; its image model is not one of them.
+ models: [{ id: "gpt-6.1-sol" }],
+ baseUrl: `http://127.0.0.1:${server.address().port}/backend-api`,
+ },
+ };
+ if (method === "session.getScratchPath") return { path: join(dataDir, "scratch", "session") };
+ if (method === "session.get") return { session: {} };
+ throw new Error(method);
+ },
+ };
+ const call = (args) =>
+ createImageGenerationTool({
+ dataDir,
+ getHost: () => host,
+ resolveAuth: async () => ({ apiKey: "chatgpt-account-token" }),
+ })({ sessionId: "session", toolCallId: "call", args, signal: new AbortController().signal });
+
+ const batch = await call({ items: [{ prompt: "cover" }] });
+ assert.equal(batch.ok, true);
+ assert.deepEqual(await readFile(batch.content.results[0].path), png);
+ assert.equal(requests.length, 1);
+ assert.equal(requests[0].url, "/backend-api/codex/images/generations");
+ assert.equal(requests[0].authorization, "Bearer chatgpt-account-token");
+ assert.equal(requests[0].originator, "pi");
+ assert.deepEqual(JSON.parse(requests[0].body), { model: "gpt-image-2.5", prompt: "cover", size: "auto" });
+
+ const edited = await call({
+ items: [{ prompt: "make it blue", images: [batch.content.results[0].path] }],
+ });
+ assert.equal(edited.ok, true);
+ assert.equal(requests.at(-1).url, "/backend-api/codex/images/edits");
+ assert.equal(requests.at(-1).contentType, "application/json");
+ assert.match(requests.at(-1).body, /"image_url":"data:image\/png;base64,/);
+});
+
+test("a Codex image binding without a signed-in credential is refused", async () => {
+ const dataDir = await mkdtemp(join(tmpdir(), "pi-images-codex-empty-"));
+ await rm(dataDir, { recursive: true, force: true });
+ const host = {
+ call: async (method) => {
+ if (method === "settings.get")
+ return { imageGeneration: { providerId: "codex-account", modelId: "gpt-image-2" } };
+ if (method === "providers.get")
+ return {
+ provider: {
+ id: "codex-account",
+ enabled: true,
+ authKind: "oauth",
+ hasOauth: false,
+ vendorKey: "openai-codex",
+ models: [],
+ baseUrl: "https://chatgpt.example/backend-api",
+ },
+ };
+ throw new Error(method);
+ },
+ };
+ const result = await createImageGenerationTool({ dataDir, getHost: () => host })({
+ sessionId: "session",
+ toolCallId: "call",
+ args: { items: [{ prompt: "cover" }] },
+ signal: new AbortController().signal,
+ });
+ assert.equal(result.errorCode, "IMAGE_MODEL_UNAVAILABLE");
+});
diff --git a/docs/spec/03-runtime/21-image-generation.md b/docs/spec/03-runtime/21-image-generation.md
index 153afd9af..684bbb74d 100644
--- a/docs/spec/03-runtime/21-image-generation.md
+++ b/docs/spec/03-runtime/21-image-generation.md
@@ -9,7 +9,7 @@ image capabilities were marked or unmarked. It must not claim that an image
model was selected after deselection. Choosing an image default from the
summary menu retains the image-selection confirmation.
-Model Advanced exposes **Set as image model** alongside the image and document attachment capabilities in the model capability group, not as a separate control row. The checkbox is multi-select: saving a provider persists every checked model in `imageGenerationModels`; Cancel leaves settings unchanged. Saving candidates does not replace the default conversation model. Unchecking every image model on the provider that holds the current default clears that default, even when another provider still has a runnable candidate. The Models page drops the check and does not select the other candidate automatically. Unchecking the current model while another model on the same provider stays marked moves the default to the first runnable marked candidate. The unmarked model is available for chat again after saving and reopening settings. Saving another provider preserves a still-runnable image default. Below the default model row in the same defaults panel, **Image generation model** shows the current default and offers a menu to choose one from all marked candidates. When no candidate is configured, or none of them can be selected, the summary row is hidden. A candidate whose provider still exists but is disabled, credential-less or otherwise unusable displays only **Currently unavailable** while another marked candidate can still be selected; a candidate whose provider row is gone is dropped from the stored list on the next settings read or write instead of staying listed. OAuth accounts are not eligible; there is no fallback.
+Model Advanced exposes **Set as image model** alongside the image and document attachment capabilities in the model capability group, not as a separate control row. The checkbox is multi-select: saving a provider persists every checked model in `imageGenerationModels`; Cancel leaves settings unchanged. Saving candidates does not replace the default conversation model. Unchecking every image model on the provider that holds the current default clears that default, even when another provider still has a runnable candidate. The Models page drops the check and does not select the other candidate automatically. Unchecking the current model while another model on the same provider stays marked moves the default to the first runnable marked candidate. The unmarked model is available for chat again after saving and reopening settings. Saving another provider preserves a still-runnable image default. Below the default model row in the same defaults panel, **Image generation model** shows the current default and offers a menu to choose one from all marked candidates. When no candidate is configured, or none of them can be selected, the summary row is hidden. A candidate whose provider still exists but is disabled, credential-less or otherwise unusable displays only **Currently unavailable** while another marked candidate can still be selected; a candidate whose provider row is gone is dropped from the stored list on the next settings read or write instead of staying listed. A signed-in ChatGPT (Codex) account is eligible for its own image model, which its provider row offers next to the models it configures; every other OAuth account is not, and there is no fallback.
All marked provider/model pairs are excluded from the default conversation picker, provider quick-default action, and Composer model menu. Other providers with the same model ID remain independent. Existing conversation bindings and history are preserved; a conversation still pinned to any image candidate must select a chat model before sending. Runtime launch rejects every marked image model before inference.
### Provider model removal
@@ -133,7 +133,13 @@ workers preserve output order, propagate cancellation/timeouts, and bound downlo
sizes and URL safety. Returned text, response ID and operation usage survive the
artifact projection. Multiple images from one response count as one operation.
-The existing settings UI still excludes OAuth candidates. The internal adapter
-may accept OAuth only with an actual supported native image model and account
-auth resolver; it cannot fabricate entitlement or fall back to another account.
+A signed-in ChatGPT (Codex) account is the one OAuth candidate: its
+`gpt-image-2.5` and `gpt-image-2` models are offered next to the models a
+provider configures, even though the account's chat model list never carries
+them. Such a request goes to the
+vendor's Codex image routes (`{baseUrl}/codex/images/generations` and
+`.../images/edits`) with the account's own OAuth token, JSON on both routes and
+input images inline as data URLs. Every other OAuth account stays ineligible,
+and the adapter cannot fabricate entitlement or fall back to another account.
+The candidate disappears as soon as the account's credential is removed.
Unknown pricing remains unknown. Images never route through the chat selector.
diff --git a/packages/agent-runtime/src/image-generation/binding.ts b/packages/agent-runtime/src/image-generation/binding.ts
index a52e9a2b7..42bfdd532 100644
--- a/packages/agent-runtime/src/image-generation/binding.ts
+++ b/packages/agent-runtime/src/image-generation/binding.ts
@@ -1,7 +1,12 @@
import type { ImageApi, ImageModel, Models } from "@earendil-works/pi-ai";
import * as openrouterImages from "@earendil-works/pi-ai/api/openrouter-images";
import { createAccountModels, type RuntimeProviderConfig } from "../provider-binding.js";
-import { OPENAI_IMAGES_API, openAIImagesAdapter } from "./openai-images.js";
+import { CODEX_IMAGE_VENDOR_KEY } from "@pi-desktop/shared";
+import {
+ OPENAI_IMAGES_API,
+ codexImagesBaseUrl,
+ openAIImagesAdapter,
+} from "./openai-images.js";
import { imageError, type ImageDownloadOptions } from "./download.js";
export type ImageEndpoint = {
@@ -18,15 +23,33 @@ export type ImageEndpoint = {
};
export type ImageBinding = { models: Models; model: ImageModel<ImageApi>; accountId?: string };
+/**
+ * Whether this endpoint is a signed-in Codex (ChatGPT) account.
+ *
+ * Such an account serves image generation and editing on the vendor's Codex
+ * routes with the same OAuth access token its chat traffic uses. Its image
+ * models live outside the shared model catalog, so the catalog is not consulted
+ * and the OpenAI Images wire format is used on both routes.
+ */
+function isCodexImageEndpoint(endpoint: ImageEndpoint): boolean {
+ return endpoint.authKind === "oauth" &&
+ endpoint.vendorKey?.trim() === CODEX_IMAGE_VENDOR_KEY;
+}
+
/** An explicitly marked legacy image binding is an operation override, not chat capability inference. */
export function createImageBinding(endpoint: ImageEndpoint, downloads: ImageDownloadOptions = {}): ImageBinding {
const providerId = endpoint.vendorKey?.trim() || endpoint.providerId || "pi-desktop-images";
- const known = endpoint.nativeModel;
+ const codexImages = isCodexImageEndpoint(endpoint);
+ const known = codexImages ? undefined : endpoint.nativeModel;
if (known && (known.type !== "image" || known.id !== endpoint.modelId || known.api !== "openrouter-images" && known.api !== OPENAI_IMAGES_API))
throw imageError("IMAGE_MODEL_UNAVAILABLE");
const native = known?.api === "openrouter-images" || providerId === "openrouter";
- // OAuth must have an actual native image operation, not an invented entitlement.
- if (endpoint.authKind === "oauth" && (known?.api !== "openrouter-images" || !endpoint.resolveAuth))
+ // OAuth must have an actual image operation, not an invented entitlement:
+ // OpenRouter's native one, or the Codex routes behind the account's token.
+ const oauthImageApi = codexImages
+ ? !!endpoint.resolveAuth
+ : known?.api === "openrouter-images" && !!endpoint.resolveAuth;
+ if (endpoint.authKind === "oauth" && !oauthImageApi)
throw imageError("IMAGE_AUTH_UNSUPPORTED");
const model: ImageModel<ImageApi> = {
...(known ?? {
@@ -36,7 +59,8 @@ export function createImageBinding(endpoint: ImageEndpoint, downloads: ImageDown
}),
id: endpoint.modelId, provider: providerId,
api: native ? "openrouter-images" : OPENAI_IMAGES_API,
- baseUrl: endpoint.baseUrl, headers: endpoint.headers,
+ baseUrl: codexImages ? codexImagesBaseUrl(endpoint.baseUrl) : endpoint.baseUrl,
+ headers: endpoint.headers,
};
const models = createAccountModels({
id: endpoint.providerId ?? providerId, vendorKey: endpoint.vendorKey,
@@ -45,7 +69,11 @@ export function createImageBinding(endpoint: ImageEndpoint, downloads: ImageDown
resolveAuth: endpoint.resolveAuth, supportsReasoning: false, supportedThinkingLevels: [],
}, {
models: [model],
- images: { [model.api]: native ? openrouterImages : openAIImagesAdapter(downloads) },
+ images: {
+ [model.api]: native
+ ? openrouterImages
+ : openAIImagesAdapter(downloads, codexImages ? "codex-json" : "multipart"),
+ },
});
return { models, model, accountId: endpoint.providerId };
}
diff --git a/packages/agent-runtime/src/image-generation/openai-images.ts b/packages/agent-runtime/src/image-generation/openai-images.ts
index d4edb9a14..cd70dd709 100644
--- a/packages/agent-runtime/src/image-generation/openai-images.ts
+++ b/packages/agent-runtime/src/image-generation/openai-images.ts
@@ -16,6 +16,24 @@ export function imageGenerationUrl(baseUrl: string, edit = false): string {
return url.href;
}
+/**
+ * The Codex image routes sit under the vendor's Codex prefix, beside its chat
+ * routes: a provider stored as `https://chatgpt.com/backend-api` serves images
+ * at `.../backend-api/codex/images/...`. Already-prefixed base URLs are kept.
+ */
+export function codexImagesBaseUrl(baseUrl: string): string {
+ const trimmed = baseUrl.trim().replace(/\/+$/, "");
+ return /\/codex$/i.test(trimmed) ? trimmed : `${trimmed}/codex`;
+}
+
+/**
+ * How the images endpoint encodes its request.
+ *
+ * `multipart` is the OpenAI Images API: a form for edits, JSON for generation.
+ * `codex-json` is the Codex backend: JSON for both, input images as data URLs.
+ */
+export type ImageRequestTransport = "multipart" | "codex-json";
+
export function safeImageError(error: unknown): string {
return error && typeof error === "object" && "errorCode" in error &&
typeof error.errorCode === "string" && /^IMAGE_[A-Z0-9_]+$/.test(error.errorCode)
@@ -23,7 +41,10 @@ export function safeImageError(error: unknown): string {
}
/** Only the generations/edits protocol missing from Pi; auth and dispatch belong to Models. */
-export function openAIImagesAdapter(downloadOptions: ImageDownloadOptions = {}): ProviderImages {
+export function openAIImagesAdapter(
+ downloadOptions: ImageDownloadOptions = {},
+ transport: ImageRequestTransport = "multipart",
+): ProviderImages {
return {
async generateImages(model, context, options) {
const result: AssistantImages = {
@@ -43,7 +64,20 @@ export function openAIImagesAdapter(downloadOptions: ImageDownloadOptions = {}):
const images = context.input.filter(item => item.type === "image");
const responseFormat = /^dall-e-[23]$/i.test(model.id) ? "b64_json" : undefined;
let body: BodyInit;
- if (images.length) {
+ if (transport === "codex-json") {
+ // The shape the Codex client sends: one JSON body for generation and
+ // editing alike, input images inline as data URLs, size at the
+ // backend's own auto default.
+ headers.set("Content-Type", "application/json");
+ body = JSON.stringify({
+ model: model.id,
+ prompt,
+ size: "auto",
+ ...(images.length
+ ? { images: images.map((image) => ({ image_url: inputImageDataUrl(image.data) })) }
+ : {}),
+ });
+ } else if (images.length) {
const form = new FormData();
form.set("model", model.id);
form.set("prompt", prompt);
@@ -114,3 +148,10 @@ export function decodeImageBase64(data: string): Uint8Array {
throw imageError("IMAGE_INVALID_RESPONSE");
return Buffer.from(data, "base64");
}
+
+/** Inline data URL for one input image, the form the Codex edit route takes. */
+function inputImageDataUrl(data: string): string {
+ const bytes = decodeImageBase64(data);
+ const type = generatedImageType(bytes);
+ return `data:${type.mimeType};base64,${Buffer.from(bytes).toString("base64")}`;
+}
diff --git a/packages/agent-runtime/src/image-generation/pi-images.test.ts b/packages/agent-runtime/src/image-generation/pi-images.test.ts
index 208dbdb79..1b99671f7 100644
--- a/packages/agent-runtime/src/image-generation/pi-images.test.ts
+++ b/packages/agent-runtime/src/image-generation/pi-images.test.ts
@@ -102,3 +102,51 @@ it("bounds native data URLs and does not claim zero pricing for custom image mod
fetchImpl: async () => new Response("", { headers: { "content-length": "999999999" } }) });
expect(results[0].errorCode).toBe("IMAGE_TOO_LARGE");
});
+
+/** A signed-in ChatGPT (Codex) account: an OAuth token, no API key, no catalog entry. */
+const codexAccount = {
+ baseUrl: "https://chatgpt.example/backend-api",
+ modelId: "gpt-image-2.5",
+ vendorKey: "openai-codex",
+ authKind: "oauth",
+ resolveAuth: async () => ({ apiKey: "codex-account-token" }),
+};
+
+it("serves a signed-in Codex account's image model on the vendor's Codex routes", async () => {
+ const transport = vi.fn<typeof fetch>().mockResolvedValue(Response.json({ data: [{ b64_json: png }] }));
+ const results = await generateImageBatch({ endpoint: codexAccount, input, signal: signal(), save, fetchImpl: transport });
+ expect(results.map(result => result.status)).toEqual(["succeeded"]);
+ const [url, init] = transport.mock.calls[0];
+ expect(String(url)).toBe("https://chatgpt.example/backend-api/codex/images/generations");
+ expect(new Headers(init?.headers).get("authorization")).toBe("Bearer codex-account-token");
+ expect(JSON.parse(String(init?.body))).toEqual({ model: "gpt-image-2.5", prompt: "draw", size: "auto" });
+});
+
+it("edits a Codex account's image as inline data URLs instead of a multipart form", async () => {
+ const transport = vi.fn<typeof fetch>().mockResolvedValue(Response.json({ data: [{ b64_json: png }] }));
+ const bytes = Buffer.from(png, "base64");
+ const results = await generateImageBatch({
+ endpoint: codexAccount,
+ input: { items: [{ prompt: "draw", images: ["0.png"] }] },
+ signal: signal(), save, fetchImpl: transport,
+ loadImages: async () => [{ bytes, mimeType: "image/png", extension: "png" }],
+ });
+ expect(results.map(result => result.status)).toEqual(["succeeded"]);
+ const [url, init] = transport.mock.calls[0];
+ expect(String(url)).toBe("https://chatgpt.example/backend-api/codex/images/edits");
+ expect(new Headers(init?.headers).get("content-type")).toBe("application/json");
+ const body = JSON.parse(String(init?.body));
+ expect(Object.keys(body).sort()).toEqual(["images", "model", "prompt", "size"]);
+ expect(body.images[0].image_url).toBe(`data:image/png;base64,${png}`);
+});
+
+it("keeps an already-prefixed Codex base URL and still requires the account token", async () => {
+ const transport = vi.fn<typeof fetch>().mockResolvedValue(Response.json({ data: [{ b64_json: png }] }));
+ await generateImageBatch({
+ endpoint: { ...codexAccount, baseUrl: "https://chatgpt.example/backend-api/codex/" },
+ input, signal: signal(), save, fetchImpl: transport,
+ });
+ expect(String(transport.mock.calls[0][0])).toBe("https://chatgpt.example/backend-api/codex/images/generations");
+ expect(() => createImageBinding({ ...codexAccount, resolveAuth: undefined }))
+ .toThrow("IMAGE_AUTH_UNSUPPORTED");
+});
diff --git a/packages/shared/src/image-generation.ts b/packages/shared/src/image-generation.ts
index d00905500..2f2965ea3 100644
--- a/packages/shared/src/image-generation.ts
+++ b/packages/shared/src/image-generation.ts
@@ -135,3 +135,78 @@ export function imageGenerationItems(value: unknown): ImageGenerationItem[] {
export function imageGenerationPrompts(value: unknown): string[] {
return imageGenerationItems(value).map((item) => item.prompt);
}
+
+/**
+ * Vendors whose signed-in subscription account serves image models on the
+ * vendor backend rather than through `provider.models`.
+ *
+ * A ChatGPT (Codex) account answers image generation and editing on the Codex
+ * routes — `{baseUrl}/codex/images/generations` / `images/edits` — with the same
+ * OAuth access token its chat traffic uses, so it needs no API key. Those image
+ * models never appear in the vendor's chat model list, so the offer is defined
+ * here instead of being smuggled into `provider.models`, where a chat picker
+ * could then select an id the chat routes do not serve.
+ *
+ * The ids are ordered newest first and every one is verified against the
+ * backend, so a user can fall back when a rollout does not reach their account.
+ */
+export const CODEX_IMAGE_VENDOR_KEY = "openai-codex";
+export const CODEX_IMAGE_MODEL_IDS = ["gpt-image-2.5", "gpt-image-2"];
+
+/** The provider fields the image rules read; anything else is ignored. */
+export type ImageProviderFacts = {
+ id?: string;
+ vendorKey?: string;
+ authKind?: string;
+ /** True only once the vendor-account credential is actually stored. */
+ hasOauth?: boolean;
+ models?: readonly { id: string }[];
+};
+
+/**
+ * Image model ids this provider offers beyond the models it configures.
+ *
+ * A vendor account must be signed in: an OAuth row without a stored credential
+ * fails at send time, so it must not offer a choice either.
+ */
+export function vendorAccountImageModelIds(provider: ImageProviderFacts): string[] {
+ return provider.authKind === "oauth" &&
+ provider.hasOauth === true &&
+ provider.vendorKey === CODEX_IMAGE_VENDOR_KEY
+ ? [...CODEX_IMAGE_MODEL_IDS]
+ : [];
+}
+
+/**
+ * Whether the provider serves `modelId` for image generation.
+ *
+ * Configured models match exactly, mirroring the wire ids. A vendor account is
+ * the exception in both directions: it offers the image models this module
+ * knows its backend answers with, and it never runs one of its *chat* models —
+ * only the vendors here have an image operation behind their OAuth token, and
+ * inventing an entitlement for the rest would fail at send time.
+ */
+export function imageModelOfferedByProvider(
+ provider: ImageProviderFacts,
+ modelId: string,
+): boolean {
+ if (!modelId) return false;
+ if (vendorAccountImageModelIds(provider).includes(modelId)) return true;
+ if (provider.authKind === "oauth") return false;
+ return (provider.models ?? []).some((model) => model.id === modelId);
+}
+
+/** Vendor-account image models as picker candidates, one row per account. */
+export function vendorAccountImageCandidates(
+ providers: readonly ImageProviderFacts[],
+): ImageGenerationBinding[] {
+ const candidates: ImageGenerationBinding[] = [];
+ for (const provider of providers) {
+ const providerId = provider.id;
+ if (!providerId) continue;
+ for (const modelId of vendorAccountImageModelIds(provider)) {
+ candidates.push({ providerId, modelId });
+ }
+ }
+ return candidates;
+}