From 2df91f49a1dce91dd86e2365251650ab0bbb5810 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 17:53:43 +0000 Subject: [PATCH 1/3] feat(images): animated GIFs from GPT Image 2.6 with --format gif, --frames and --frame-duration (#3783) The 2.6 pair now lists gif among its output formats, so routing narrows a GIF request to them and refuses it on 2.5 or Gemini with a reason naming the 2.6 models. --frames (2-16) and --frame-duration (20-2000 ms) are validated before routing, need --format gif, and are sent as frame_count and frame_duration_ms on generations and multipart edits; unset, nothing is sent and the API's defaults apply. GIF with a mask or a transparent background is refused before any request. A 4xx about GIF access carries a hint naming GIF preview access instead of the generic region/verification hints. A GIF dry run prices as unknown. The provider repeats the guards for direct callers. Also repairs two drifted citations into the image module. Co-Authored-By: Claude Opus 5.5 --- .changeset/gpt-image-2-6-gif.md | 5 + docs/decisions/governed-writable-workers.md | 2 +- .../paid-cli-provider-qualification.md | 2 +- packages/module-images/README.md | 10 ++ .../module-images/skills/image-gen/SKILL.md | 9 ++ packages/module-images/src/cli.ts | 54 ++++++++- .../module-images/src/providers/openai.ts | 42 +++++-- packages/module-images/src/routing.ts | 26 ++++ packages/module-images/src/types.ts | 31 ++++- packages/module-images/tests/cli.test.ts | 113 +++++++++++++++++- .../module-images/tests/providers.test.ts | 27 +++++ 11 files changed, 303 insertions(+), 18 deletions(-) create mode 100644 .changeset/gpt-image-2-6-gif.md diff --git a/.changeset/gpt-image-2-6-gif.md b/.changeset/gpt-image-2-6-gif.md new file mode 100644 index 0000000000..7676ace240 --- /dev/null +++ b/.changeset/gpt-image-2-6-gif.md @@ -0,0 +1,5 @@ +--- +"@schlessera/brain-module-images": minor +--- + +`brain image --format gif` makes animated GIFs with the GPT Image 2.6 models, for new images and for edits with `--ref`. `--frames` (2-16) and `--frame-duration` (20-2000 ms) set the loop; without them OpenAI applies its defaults of 9 frames at 200 ms. GIF with `--mask` or `--transparent`, GIF on a 2.5 or Gemini model, and frame flags without `--format gif` are refused before any request. OpenAI serves GIF only to organizations with GIF preview access, and a refusal for missing access says so. A dry run reports a GIF's cost as unknown. diff --git a/docs/decisions/governed-writable-workers.md b/docs/decisions/governed-writable-workers.md index 8696cf4ed9..10111c5fe2 100644 --- a/docs/decisions/governed-writable-workers.md +++ b/docs/decisions/governed-writable-workers.md @@ -4078,7 +4078,7 @@ reason through as the refusal body's `error.message` and an additive `outward_not_approved` (`const refuse`, `packages/ui-sdk/src/server/provider-relay.ts:386-391`). The OpenAI image provider no longer appends its account hint to a relay refusal -(`const relayRefusal`, `packages/module-images/src/providers/openai.ts:199-200`). +(`const relayRefusal`, `packages/module-images/src/providers/openai.ts:252-253`). A cancelled connection keeps its bare 403. The system prompt's turn-lifecycle section names these causes and what the user can do (`A blocked connection says why`, `packages/ui-sdk/src/server/system-prompt.ts:167-175`). Since #3246, diff --git a/docs/hosting/paid-cli-provider-qualification.md b/docs/hosting/paid-cli-provider-qualification.md index f8144e787c..5fe7ffd4bc 100644 --- a/docs/hosting/paid-cli-provider-qualification.md +++ b/docs/hosting/paid-cli-provider-qualification.md @@ -56,7 +56,7 @@ SDK conversion without adding a public embedding-provider seam. The image CLI preserves `bytes`, `costIsEstimate`, `costUsd`, `model`, `note`, `output`, `outputs`, `provider`, `reason` and `renamed` -(`const payload`, `packages/module-images/src/cli.ts:408-420`). Its help example +(`const payload`, `packages/module-images/src/cli.ts:466-477`). Its help example is abbreviated; it is not the complete machine contract. Internal image raw usage does not imply that this envelope exposes it. diff --git a/packages/module-images/README.md b/packages/module-images/README.md index 022629af2a..fead10cbe9 100644 --- a/packages/module-images/README.md +++ b/packages/module-images/README.md @@ -33,6 +33,7 @@ serve at all: | PNG or WebP | OpenAI | Every Gemini image model serves JPEG only | | Exact custom pixels | OpenAI | Gemini has fixed ratios; the 2.6 and 2.5 models take any size on a 16px grid up to 3840px, 3:1 and 8.3MP | | `--complexity` | OpenAI GPT Image 2.6 | Only the 2.6 models take it; it is refused anywhere else | +| Animated GIF (`--format gif`) | OpenAI GPT Image 2.6 | Only the 2.6 models return GIF; it is refused anywhere else | | Character consistency | Gemini | Narrows to models that claim it; no benchmark picks a winner | | >6 reference images | Gemini | 10 (Flash) / 14 (Lite) vs OpenAI's practical 8 | | Watermark-free | OpenAI | Gemini always applies SynthID | @@ -57,6 +58,15 @@ it with them is refused. A transparent JPEG, an unknown quality, complexity or format, a `--size` that is not `WIDTHxHEIGHT`, and a custom size outside OpenAI's rules are refused before any request. +`--format gif` asks a GPT Image 2.6 model for an animated GIF, for a new image +or an edit with `--ref`. `--frames` (2-16) and `--frame-duration` (20-2000 ms) +set its frame count and timing; without them the API uses its own defaults of 9 +frames at 200 ms. The frame flags need `--format gif`. A GIF takes no `--mask` +and no `--transparent`, and the 2.5 models and Gemini cannot return one; each of +these is refused before any request. OpenAI serves GIF only to organizations +with GIF preview access, and the refusal says so. A dry run reports a GIF's cost +as unknown, because OpenAI publishes no per-frame token count. + ### Retired models `gpt-image-2` and `gpt-image-1.5` are no longer supported. Naming either in diff --git a/packages/module-images/skills/image-gen/SKILL.md b/packages/module-images/skills/image-gen/SKILL.md index 8dab18a8bf..0e47c5f843 100644 --- a/packages/module-images/skills/image-gen/SKILL.md +++ b/packages/module-images/skills/image-gen/SKILL.md @@ -33,6 +33,7 @@ only when the user asked for something else. | More than 6 reference images | Gemini | Up to 10 (Flash) or 14 (Lite); OpenAI's practical ceiling is 8 | | Output that must carry no watermark | OpenAI | Every Gemini image carries SynthID, with no documented opt-out | | PNG or WebP output | OpenAI | Every Gemini image model serves JPEG only — verified against the live API, the docs do not say so | +| An animated GIF | `gpt-image-2.6-sunburst` or `-flare` | Only the 2.6 models return GIF | ### The cases worth knowing @@ -121,6 +122,14 @@ Without it, the 2.6 models are sent `high`. Lower it only when the user asks, or when an edit at `high` keeps changing things it should leave alone. The 2.5 models and Gemini do not take it, so naming it with them is refused. +For a moving picture, pass `--format gif`. It works for a new image and for an +edit with `--ref`. `--frames` (2-16) and `--frame-duration` (20-2000 ms) set the +loop; leave them out unless the user asks for a length or speed, and the API +uses 9 frames at 200 ms. A GIF cannot take a mask or a transparent background, +and the dry run cannot price it, so say the cost is unknown. If OpenAI answers +that the organization lacks GIF preview access, tell the user that; retrying +will not help. + `--draft` takes the cheapest model that fits. `--dry-run` prints the decision and the price without spending anything — use it when the user is likely to want a different model, and when a request is large or repeated. diff --git a/packages/module-images/src/cli.ts b/packages/module-images/src/cli.ts index 5cd5cd96cd..b8d8154ab2 100644 --- a/packages/module-images/src/cli.ts +++ b/packages/module-images/src/cli.ts @@ -25,7 +25,10 @@ import { estimateOpenAiOutputCost, openAiRequestQuality, openAiRequestSize } fro import { isRetiredModel, retiredModelMessage } from "./retired.js"; import { route, type RoutingDecision } from "./routing.js"; import { + GIF_FRAME_COUNT, + GIF_FRAME_DURATION_MS, IMAGE_COMPLEXITIES, + IMAGE_FORMATS, IMAGE_QUALITIES, ImageProviderError, type ImageComplexity, @@ -34,7 +37,15 @@ import { type ImageRequest, } from "./types.js"; -const FORMATS = ["png", "jpeg", "webp"] as const; +const FORMATS = IMAGE_FORMATS; + +/** A whole number within an inclusive range, or why not. */ +function wholeInRange(flag: string, raw: string, range: { min: number; max: number }): number | string { + const n = Number(raw); + return /^\d+$/.test(raw) && n >= range.min && n <= range.max + ? n + : `${flag} must be a whole number from ${range.min} to ${range.max} (got "${raw}")`; +} /** A per-image price, or the honest absence of one. */ const price = (usd: number | null) => (usd === null ? "cost unknown" : `~$${usd.toFixed(3)}`); @@ -49,8 +60,16 @@ Output: --scratch Write to the brain's scratch area instead (.brain/scratch/): for a draft that should not become part of the brain. Never committed; pruned after 7 days or past 1 GB. - --format png|jpeg|webp Default: whatever the chosen model returns - (every Gemini image model serves JPEG only) + --format png|jpeg|webp|gif + Default: whatever the chosen model returns + (every Gemini image model serves JPEG only). gif is an + animated GIF from GPT Image 2.6 only; it needs GIF preview + access on the OpenAI organization, takes no --mask or + --transparent, and a dry run cannot price it + +Animation (--format gif only): + --frames 2-16 frames. Default: the API's, 9 + --frame-duration 20-2000 ms per frame. Default: the API's, 200 Shape (--aspect and --resolution work on every model): --aspect 1:1 2:3 3:2 3:4 4:3 4:5 5:4 9:16 16:9 21:9 on Gemini; @@ -221,6 +240,24 @@ export const imageCommand: CommandModule = { console.error(`--format must be one of ${FORMATS.join(", ")} (got "${format}")`); return 1; } + // Frame settings are GIF settings: checked here, before routing or any + // request, so a typo never reaches a paid call (#3783). + const frameFlags = { frames: GIF_FRAME_COUNT, "frame-duration": GIF_FRAME_DURATION_MS } as const; + const frameValues: Partial> = {}; + for (const [flag, range] of Object.entries(frameFlags) as [keyof typeof frameFlags, { min: number; max: number }][]) { + const raw = parsed.flags[flag]; + if (raw === undefined) continue; + if (format !== "gif") { + console.error(`--${flag} applies to animated GIFs only; add --format gif`); + return 1; + } + const value = wholeInRange(`--${flag}`, String(raw), range); + if (typeof value === "string") { + console.error(value); + return 1; + } + frameValues[flag] = value; + } let request: ImageRequest; try { @@ -232,6 +269,8 @@ export const imageCommand: CommandModule = { quality: quality as ImageQuality | undefined, complexity: complexity as ImageComplexity | undefined, format: format as ImageRequest["format"], + frames: frameValues.frames, + frameDurationMs: frameValues["frame-duration"], transparent: parsed.flags.transparent === true, references: (parsed.repeated.ref ?? []).map((r) => loadImage(ctx.root, r)), mask: parsed.flags.mask ? loadImage(ctx.root, parsed.flags.mask as string) : undefined, @@ -324,8 +363,11 @@ export const imageCommand: CommandModule = { // The GPT Image models have no card price, but a quality (stated, or the // max default) and a size have a published output-token count; `auto` // or an unstated size stays unknown. + // GIF has no published per-frame token count, so it is never priced. const estimatedCostUsd = - model.provider === "openai" + request.format === "gif" + ? null + : model.provider === "openai" ? (estimateOpenAiOutputCost(model.id, openAiRequestQuality(request), openAiRequestSize(request, model.id)) ?? null) : model.approxCostUsd1K; const payload = { @@ -339,7 +381,9 @@ export const imageCommand: CommandModule = { if (ctx.json) console.log(JSON.stringify(payload, null, 2)); else { const cost = - estimatedCostUsd === null && model.provider === "openai" + request.format === "gif" + ? "cost unknown — OpenAI publishes no per-frame token count for GIF" + : estimatedCostUsd === null && model.provider === "openai" ? "cost unknown — pass --size or --aspect (and a quality other than auto) to price it" : price(estimatedCostUsd); console.log(`Would use ${describe(decision)}`); diff --git a/packages/module-images/src/providers/openai.ts b/packages/module-images/src/providers/openai.ts index 6e3d3f42cd..ee1c977b53 100644 --- a/packages/module-images/src/providers/openai.ts +++ b/packages/module-images/src/providers/openai.ts @@ -40,7 +40,8 @@ import { * https://developers.openai.com/api/docs/guides/image-generation * * Only the 2.6 pair takes `complexity` (low|medium|high, default high, no - * separate fee). The 2.5 pair is not deprecated upstream and stays + * separate fee) and returns animated GIFs (`output_format: "gif"`, #3783), + * which need GIF preview access on the OpenAI organization. The 2.5 pair is not deprecated upstream and stays * selectable. gpt-image-2 and gpt-image-1.5 are retired (`../retired.ts`) and * must not be re-added as a fallback. */ @@ -61,13 +62,16 @@ const GPT_IMAGE = { // not transfer by name. strongTextRendering: false, watermarked: false, - outputFormats: ["png", "jpeg", "webp"], + outputFormats: ["png", "jpeg", "webp"] as ModelCapabilities["outputFormats"], defaultFormat: "png", // Billed per token, so there is no single per-image figure to show. A dry // run with a quality and a size is priced by `estimateOpenAiOutputCost`. approxCostUsd1K: null, } satisfies Omit; +/** The 2.6 pair adds animated GIF to the shared formats (#3783). */ +const GPT_IMAGE_26_FORMATS: ModelCapabilities["outputFormats"] = [...GPT_IMAGE.outputFormats, "gif"]; + const MODELS: ModelCapabilities[] = [ { id: "gpt-image-2.6-sunburst", @@ -75,6 +79,7 @@ const MODELS: ModelCapabilities[] = [ "OpenAI's most capable image model — the default; complexity control, transparency on png/webp, masks, custom sizes, xhigh/max quality, no watermark", ...GPT_IMAGE, complexityControl: true, + outputFormats: GPT_IMAGE_26_FORMATS, }, { id: "gpt-image-2.6-flare", @@ -82,6 +87,7 @@ const MODELS: ModelCapabilities[] = [ "OpenAI's fastest 2.6 model — chosen by --model; same complexity control, transparency, masks, sizes and quality tiers as Sunburst", ...GPT_IMAGE, complexityControl: true, + outputFormats: GPT_IMAGE_26_FORMATS, }, { id: "gpt-image-2.5-sunburst", @@ -203,7 +209,7 @@ export function openAiRequestSize(req: ImageRequest, model: string): string | un ); } -async function readError(res: Response): Promise { +async function readError(res: Response, req: ImageRequest): Promise { let code: string | undefined; let message = `${res.status} ${res.statusText}`; let moderation: string | undefined; @@ -231,14 +237,21 @@ async function readError(res: Response): Promise { const retryable = res.status >= 500 || (res.status === 429 && !(code && billing.has(code))); const hints: string[] = []; + // GIF output is a preview feature: an organization without access gets a + // 4xx about it, and neither retrying nor the generic hints below help. + const gifAccess = + req.format === "gif" && (res.status === 400 || res.status === 403) && /\bgif\b|preview/i.test(message); + if (gifAccess) { + hints.push("GIF output needs GIF preview access for this model on the OpenAI organization; ask without --format gif meanwhile"); + } if (code === "moderation_blocked") { hints.push(`refused by moderation${moderation ? ` — ${moderation}` : ""}`); } // The host's provider relay refused before contacting OpenAI (#3431): its // message says why, and the account hint would point the agent elsewhere. const relayRefusal = code === "brain_provider_refused" || code === "budget_exceeded"; - if (res.status === 403 && !relayRefusal) hints.push("region not supported, or the org is not verified"); - if (res.status === 400 && /model/i.test(message)) { + if (res.status === 403 && !relayRefusal && !gifAccess) hints.push("region not supported, or the org is not verified"); + if (res.status === 400 && /model/i.test(message) && !gifAccess) { hints.push("GPT-image models require API Organization Verification"); } if (code && billing.has(code)) hints.push("billing limit — retrying will not help"); @@ -304,6 +317,16 @@ export const openaiProvider: Provider = { retryable: false, }); } + const gif = req.format === "gif"; + if (gif && !MODELS.find((m) => m.id === model)?.outputFormats.includes("gif")) { + throw new ImageProviderError(`${model} does not return GIF; the GPT Image 2.6 models do.`, { retryable: false }); + } + if (gif && (req.mask || req.transparent)) { + throw new ImageProviderError("GIF output takes no mask and no transparent background.", { retryable: false }); + } + if (!gif && (req.frames !== undefined || req.frameDurationMs !== undefined)) { + throw new ImageProviderError("Frame count and frame duration apply to GIF output only.", { retryable: false }); + } const headers = { Authorization: `Bearer ${apiKey}` }; // Without the key, the host's metered relay adds it (#1673). const send = providerRelayFetch("openai", "OPENAI_API_KEY") ?? fetch; @@ -317,6 +340,9 @@ export const openaiProvider: Provider = { // be explicit so a caller-set default cannot flatten the transparency. if (req.format) payload.output_format = req.format; else if (req.transparent) payload.output_format = "png"; + // Unset frame settings stay unsent: the API's defaults (9, 200 ms) apply. + if (req.frames !== undefined) payload.frame_count = req.frames; + if (req.frameDurationMs !== undefined) payload.frame_duration_ms = req.frameDurationMs; if (req.n && req.n > 1) payload.n = req.n; // `transparent` is only legal on models that support it; routing guarantees that. if (req.transparent) payload.background = "transparent"; @@ -326,7 +352,7 @@ export const openaiProvider: Provider = { headers: { ...headers, "Content-Type": "application/json" }, body: JSON.stringify(payload), }); - if (!res.ok) await readError(res); + if (!res.ok) await readError(res, req); return decode((await res.json()) as OpenAiImageResponse, model, req); } @@ -342,6 +368,8 @@ export const openaiProvider: Provider = { if (req.format) form.append("output_format", req.format); else if (req.transparent) form.append("output_format", "png"); if (req.transparent) form.append("background", "transparent"); + if (req.frames !== undefined) form.append("frame_count", String(req.frames)); + if (req.frameDurationMs !== undefined) form.append("frame_duration_ms", String(req.frameDurationMs)); for (const [i, ref] of (req.references ?? []).entries()) { form.append("image[]", new Blob([ref.data as BlobPart], { type: ref.mime }), ref.label ?? `image-${i}.png`); } @@ -350,7 +378,7 @@ export const openaiProvider: Provider = { } const res = await send(`${resolveEnv().openaiBaseUrl}/images/edits`, { method: "POST", headers, body: form }); - if (!res.ok) await readError(res); + if (!res.ok) await readError(res, req); return decode((await res.json()) as OpenAiImageResponse, model, req); }, }; diff --git a/packages/module-images/src/routing.ts b/packages/module-images/src/routing.ts index 0a4fd59aa5..8cd4787faa 100644 --- a/packages/module-images/src/routing.ts +++ b/packages/module-images/src/routing.ts @@ -171,6 +171,21 @@ export function route(input: RoutingInput): RoutingDecision { pool = capable; } + // GPT Image 2.6 GIF output has no masks, and transparency is documented + // for png and webp only (#3783): refuse rather than let the API decide. + if (req.format === "gif" && req.mask) { + return { + kind: "impossible", + reason: "GIF output takes no mask. Drop --mask and describe the change in the prompt, or ask for png or webp.", + }; + } + if (req.format === "gif" && req.transparent) { + return { + kind: "impossible", + reason: "A transparent background is documented for png and webp only, not GIF. Drop --transparent, or ask for png or webp.", + }; + } + if (req.transparent && req.format === "jpeg") { return { kind: "impossible", @@ -194,6 +209,17 @@ export function route(input: RoutingInput): RoutingDecision { if (req.format) { const supported = byCapability(pool, (m) => m.outputFormats.includes(req.format!)); + if (supported.length === 0 && req.format === "gif") { + const named = available.filter((m) => m.outputFormats.includes("gif")).map((m) => m.id); + return { + kind: "impossible", + reason: + `Animated GIF is a GPT Image 2.6 output, and no model in this request returns it` + + `${input.pinnedModel ? ` (${input.pinnedModel} does not)` : ""}. Use ` + + `${named.length ? named.join(" or ") : "gpt-image-2.6-sunburst or gpt-image-2.6-flare (set OPENAI_API_KEY)"}, ` + + `or ask for png, jpeg or webp.`, + }; + } if (supported.length === 0) { return { kind: "impossible", diff --git a/packages/module-images/src/types.ts b/packages/module-images/src/types.ts index 69fd64d648..7912e50aa8 100644 --- a/packages/module-images/src/types.ts +++ b/packages/module-images/src/types.ts @@ -28,7 +28,17 @@ export interface ImageRequest { * `complexityControl` take it; routing refuses it anywhere else. */ complexity?: ImageComplexity; - format?: "png" | "jpeg" | "webp"; + format?: ImageFormat; + /** + * Animated GIF frame count (`format: "gif"` only). Unset, nothing is sent + * and the API applies its own default of 9. + */ + frames?: number; + /** + * Milliseconds each GIF frame shows (`format: "gif"` only). Unset, nothing + * is sent and the API applies its own default of 200. + */ + frameDurationMs?: number; /** Transparent background (png or webp only). Only some models support it; routing enforces that. */ transparent?: boolean; /** Reference images for an edit or a composition. */ @@ -42,6 +52,21 @@ export interface ImageRequest { export const IMAGE_QUALITIES = ["low", "medium", "high", "xhigh", "max", "auto"] as const; export type ImageQuality = (typeof IMAGE_QUALITIES)[number]; +/** + * Output formats any model may return. `gif` is an animated GIF, which only + * the GPT Image 2.6 models produce (#3783). + */ +export const IMAGE_FORMATS = ["png", "jpeg", "webp", "gif"] as const; +export type ImageFormat = (typeof IMAGE_FORMATS)[number]; + +/** + * GPT Image 2.6 GIF limits from the API reference (checked 2026-11-09): + * `frame_count` 2-16 and `frame_duration_ms` 20-2000. The guide once said 64 + * frames; the API enforces 16. + */ +export const GIF_FRAME_COUNT = { min: 2, max: 16 } as const; +export const GIF_FRAME_DURATION_MS = { min: 20, max: 2000 } as const; + /** GPT Image 2.6 `complexity` values. Anything else is refused before routing. */ export const IMAGE_COMPLEXITIES = ["low", "medium", "high"] as const; export type ImageComplexity = (typeof IMAGE_COMPLEXITIES)[number]; @@ -113,8 +138,8 @@ export interface ModelCapabilities { * not the docs: every Gemini image model rejects `image/png` on the * Interactions API and serves JPEG only, which the published docs do not say. */ - outputFormats: ("png" | "jpeg" | "webp")[]; - defaultFormat: "png" | "jpeg" | "webp"; + outputFormats: ImageFormat[]; + defaultFormat: ImageFormat; /** * Approximate USD for one image at ~1K, for cost reporting and tie-breaks. * `null` when no verified per-image price exists: the GPT Image 2.5 and 2.6 diff --git a/packages/module-images/tests/cli.test.ts b/packages/module-images/tests/cli.test.ts index 5a4e884df5..8d17351303 100644 --- a/packages/module-images/tests/cli.test.ts +++ b/packages/module-images/tests/cli.test.ts @@ -137,7 +137,7 @@ describe("brain image — refused before the provider is called", () => { }); test("an unknown format", async () => { - expect(await run(["x", "--format", "gif"])).toBe(1); + expect(await run(["x", "--format", "tiff"])).toBe(1); expect(calls).toHaveLength(0); }); @@ -320,3 +320,114 @@ describe("brain image — GPT Image 2.6 defaults (#3782)", () => { expect(out.join("\n")).toContain(FLARE_26); }); }); + +describe("brain image — animated GIF on GPT Image 2.6 (#3783)", () => { + const SUNBURST_25 = "gpt-image-2.5-sunburst"; + + test("--format gif sends the GIF fields and the 2.6 defaults, and writes a .gif", async () => { + expect(await run(["a waving flag", "--format", "gif", "--frames", "12", "--frame-duration", "150", "--out", "flag.gif"])).toBe(0); + expect(calls).toHaveLength(1); + expect(calls[0].url).toEndWith("/images/generations"); + expect(sentJson(), "IMAGE_GIF_GENERATION").toMatchObject({ + model: SUNBURST, output_format: "gif", frame_count: 12, frame_duration_ms: 150, quality: "max", complexity: "high", + }); + expect(report().output).toBe("flag.gif"); + expect(report().renamed).toBeNull(); + }); + + test("the default output path ends in .gif", async () => { + expect(await run(["a waving flag", "--format", "gif"])).toBe(0); + expect(report().output).toEndWith(".gif"); + }); + + test("omitted frame flags leave the API's own defaults in charge", async () => { + expect(await run(["a waving flag", "--format", "gif", "--out", "flag.gif"])).toBe(0); + const body = sentJson(); + expect(body.output_format).toBe("gif"); + expect(body, "IMAGE_GIF_NO_FRAME_DEFAULTS").not.toHaveProperty("frame_count"); + expect(body).not.toHaveProperty("frame_duration_ms"); + }); + + test("a GIF edit with --ref carries the same fields over multipart", async () => { + expect(await run(["make the door swing", "--ref", "photos/house.png", "--format", "gif", "--frames", "12", "--frame-duration", "150", "--out", "door.gif"])).toBe(0); + expect(calls[0].url).toEndWith("/images/edits"); + const form = calls[0].init.body as FormData; + expect(form.get("model")).toBe(SUNBURST); + expect(form.get("output_format"), "IMAGE_GIF_EDIT").toBe("gif"); + expect(form.get("frame_count")).toBe("12"); + expect(form.get("frame_duration_ms")).toBe("150"); + expect(form.get("quality")).toBe("max"); + expect(form.get("complexity")).toBe("high"); + }); + + const outOfRange: [string, string[], string][] = [ + ["--frames 1", ["--frames", "1"], "2 to 16"], + ["--frames 17", ["--frames", "17"], "2 to 16"], + ["--frames 4.5", ["--frames", "4.5"], "2 to 16"], + ["--frame-duration 10", ["--frame-duration", "10"], "20 to 2000"], + ["--frame-duration 2001", ["--frame-duration", "2001"], "20 to 2000"], + ]; + for (const [label, flags, range] of outOfRange) { + test(`${label} refuses with zero requests and names the range`, async () => { + expect(await run(["x", "--format", "gif", ...flags])).toBe(1); + expect(calls, "IMAGE_GIF_FRAME_RANGE").toHaveLength(0); + expect(out.join("\n")).toContain(range); + }); + } + + for (const flags of [["--frames", "9"], ["--frame-duration", "200"]]) { + test(`${flags[0]} without --format gif refuses with zero requests`, async () => { + expect(await run(["x", ...flags])).toBe(1); + expect(calls).toHaveLength(0); + expect(out.join("\n")).toContain("--format gif"); + }); + } + + test("GIF with --mask refuses before any request", async () => { + expect(await run(["x", "--format", "gif", "--ref", "photos/house.png", "--mask", "photos/mask.png"])).toBe(1); + expect(calls, "IMAGE_GIF_MASK").toHaveLength(0); + expect(out.join("\n")).toMatch(/GIF.*mask/i); + }); + + test("GIF with --transparent refuses before any request", async () => { + expect(await run(["x", "--format", "gif", "--transparent"])).toBe(1); + expect(calls).toHaveLength(0); + expect(out.join("\n")).toMatch(/GIF.*transparen/i); + }); + + test("GIF on a 2.5 model refuses and names the 2.6 models", async () => { + expect(await run(["x", "--format", "gif", "--model", SUNBURST_25])).toBe(1); + expect(calls, "IMAGE_GIF_MODEL").toHaveLength(0); + expect(out.join("\n")).toContain(SUNBURST); + }); + + test("GIF on Gemini refuses before any request", async () => { + process.env.GEMINI_API_KEY = "placeholder-never-sent"; + expect(await run(["x", "--format", "gif", "--provider", "gemini"])).toBe(1); + expect(calls).toHaveLength(0); + expect(out.join("\n")).toMatch(/GIF/); + }); + + test("a GIF dry run reports its cost as unknown", async () => { + expect(await run(["x", "--format", "gif", "--aspect", "1:1", "--dry-run"])).toBe(0); + expect(calls).toHaveLength(0); + expect(report().model).toBe(SUNBURST); + expect(report().output).toEndWith(".gif"); + expect(report().estimatedCostUsd, "IMAGE_GIF_DRY_RUN").toBeNull(); + }); + + test("a refusal for missing GIF preview access names it and is not retryable", async () => { + globalThis.fetch = (async (url: string | URL | Request, init?: RequestInit) => { + calls.push({ url: String(url), init: init ?? {} }); + return new Response( + JSON.stringify({ error: { message: "This organization does not have access to output_format gif for this model.", type: "invalid_request_error" } }), + { status: 403, headers: { "Content-Type": "application/json" } }, + ); + }) as typeof fetch; + expect(await run(["x", "--format", "gif", "--out", "x.gif"])).toBe(1); + const said = out.join("\n"); + expect(said, "IMAGE_GIF_ACCESS_HINT").toContain("GIF preview access"); + expect(said).not.toContain("worth retrying"); + expect(said).not.toContain("region not supported"); + }); +}); diff --git a/packages/module-images/tests/providers.test.ts b/packages/module-images/tests/providers.test.ts index 9ca68f6ebb..331afe9eb8 100644 --- a/packages/module-images/tests/providers.test.ts +++ b/packages/module-images/tests/providers.test.ts @@ -263,6 +263,33 @@ describe("openai provider — 2.6 quality and complexity defaults (#3782)", () = }); }); +describe("openai provider — animated GIF (#3783)", () => { + test("only the 2.6 pair lists gif among its formats", () => { + const gif = openaiProvider.models.filter((m) => m.outputFormats.includes("gif")).map((m) => m.id); + expect(gif).toEqual([SUNBURST, FLARE]); + }); + + test("a GIF response is decoded as image/gif", async () => { + stub({ data: [{ b64_json: PNG_B64 }] }); + const result = await openaiProvider.generate(SUNBURST, { prompt: "x", format: "gif", frames: 4 }, "k"); + expect(result.images[0].mime).toBe("image/gif"); + }); + + const refusals: [string, Parameters[1], string, RegExp][] = [ + ["GIF on a 2.5 model", { prompt: "x", format: "gif" }, "gpt-image-2.5-flare", /GIF/], + ["GIF with a mask", { prompt: "x", format: "gif", references: [ref()], mask: ref() }, SUNBURST, /mask/], + ["GIF with transparency", { prompt: "x", format: "gif", transparent: true }, SUNBURST, /transparent/], + ["frames without GIF", { prompt: "x", format: "png", frames: 4 }, SUNBURST, /GIF output only/], + ]; + for (const [label, req, model, message] of refusals) { + test(`a direct call with ${label} refuses before fetch`, async () => { + const calls = stub({ data: [{ b64_json: PNG_B64 }] }); + await expect(openaiProvider.generate(model, req, "k")).rejects.toThrow(message); + expect(calls).toHaveLength(0); + }); + } +}); + describe("GPT Image 2.5 and 2.6 output-token estimate", () => { // The guide's one calculator covers both generations (checked 2026-11-09). const SUNBURST = "gpt-image-2.6-sunburst"; From d746016fbf557c822e32c14946e8cc9f136c0c8a Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 22:21:41 +0000 Subject: [PATCH 2/3] feat(images): static SVG from GPT Image 2.6 with --format svg, refusing active content (#3784) The 2.6 pair lists svg among its output formats, so routing narrows an SVG request to them and refuses it on 2.5 or Gemini. SVG is a single new image: --ref, --mask, --transparent and n above 1 are refused before any request, by routing and again by the provider for direct callers. The `svg` authoring-model object is never sent. The returned XML is checked before anything is written (src/svg.ts): it must be UTF-8 and an SVG document, with no DOCTYPE or entity, script, foreignObject, embedding element, event-handler attribute, @import, or any href, src or url() outside the document. A failing SVG throws and nothing is written. The mime is image/svg+xml and the file ends in .svg. Its cost is unknown before and after the call, since svg_usage is billed at a rate not published here. Co-Authored-By: Claude Opus 5.5 --- .changeset/gpt-image-2-6-svg.md | 5 + docs/decisions/governed-writable-workers.md | 2 +- .../paid-cli-provider-qualification.md | 2 +- packages/module-images/README.md | 13 +++ .../module-images/skills/image-gen/SKILL.md | 8 ++ packages/module-images/src/cli.ts | 18 +++- .../module-images/src/providers/openai.ts | 42 +++++++- packages/module-images/src/routing.ts | 25 ++++- packages/module-images/src/svg.ts | 41 ++++++++ packages/module-images/src/types.ts | 17 +++- packages/module-images/tests/cli.test.ts | 99 ++++++++++++++++++- .../module-images/tests/providers.test.ts | 35 +++++++ 12 files changed, 288 insertions(+), 19 deletions(-) create mode 100644 .changeset/gpt-image-2-6-svg.md create mode 100644 packages/module-images/src/svg.ts diff --git a/.changeset/gpt-image-2-6-svg.md b/.changeset/gpt-image-2-6-svg.md new file mode 100644 index 0000000000..8621820c9c --- /dev/null +++ b/.changeset/gpt-image-2-6-svg.md @@ -0,0 +1,5 @@ +--- +"@schlessera/brain-module-images": minor +--- + +`brain image --format svg` has the GPT Image 2.6 models author a static SVG for a new image, written as a `.svg` file. SVG with `--ref`, `--mask` or `--transparent`, and SVG on a 2.5 or Gemini model, are refused before any request. A returned SVG that contains a script, an event handler, a `foreignObject`, an embedding element, a DOCTYPE, an `@import`, or a reference outside the document is refused and not written. An SVG's cost is reported as unknown. diff --git a/docs/decisions/governed-writable-workers.md b/docs/decisions/governed-writable-workers.md index bebef65109..9ca0a50bb0 100644 --- a/docs/decisions/governed-writable-workers.md +++ b/docs/decisions/governed-writable-workers.md @@ -4078,7 +4078,7 @@ reason through as the refusal body's `error.message` and an additive `outward_not_approved` (`const refuse`, `packages/ui-sdk/src/server/provider-relay.ts:386-391`). The OpenAI image provider no longer appends its account hint to a relay refusal -(`const relayRefusal`, `packages/module-images/src/providers/openai.ts:252-253`). +(`const relayRefusal`, `packages/module-images/src/providers/openai.ts:255-256`). A cancelled connection keeps its bare 403. The system prompt's turn-lifecycle section names these causes and what the user can do (`A blocked connection says why`, `packages/ui-sdk/src/server/system-prompt.ts:167-175`). Since #3246, diff --git a/docs/hosting/paid-cli-provider-qualification.md b/docs/hosting/paid-cli-provider-qualification.md index 5fe7ffd4bc..ab4bd54985 100644 --- a/docs/hosting/paid-cli-provider-qualification.md +++ b/docs/hosting/paid-cli-provider-qualification.md @@ -56,7 +56,7 @@ SDK conversion without adding a public embedding-provider seam. The image CLI preserves `bytes`, `costIsEstimate`, `costUsd`, `model`, `note`, `output`, `outputs`, `provider`, `reason` and `renamed` -(`const payload`, `packages/module-images/src/cli.ts:466-477`). Its help example +(`const payload`, `packages/module-images/src/cli.ts:474-485`). Its help example is abbreviated; it is not the complete machine contract. Internal image raw usage does not imply that this envelope exposes it. diff --git a/packages/module-images/README.md b/packages/module-images/README.md index fead10cbe9..eff3622280 100644 --- a/packages/module-images/README.md +++ b/packages/module-images/README.md @@ -34,6 +34,7 @@ serve at all: | Exact custom pixels | OpenAI | Gemini has fixed ratios; the 2.6 and 2.5 models take any size on a 16px grid up to 3840px, 3:1 and 8.3MP | | `--complexity` | OpenAI GPT Image 2.6 | Only the 2.6 models take it; it is refused anywhere else | | Animated GIF (`--format gif`) | OpenAI GPT Image 2.6 | Only the 2.6 models return GIF; it is refused anywhere else | +| Static SVG (`--format svg`) | OpenAI GPT Image 2.6 | Only the 2.6 models author SVG, on new images only | | Character consistency | Gemini | Narrows to models that claim it; no benchmark picks a winner | | >6 reference images | Gemini | 10 (Flash) / 14 (Lite) vs OpenAI's practical 8 | | Watermark-free | OpenAI | Gemini always applies SynthID | @@ -67,6 +68,18 @@ these is refused before any request. OpenAI serves GIF only to organizations with GIF preview access, and the refusal says so. A dry run reports a GIF's cost as unknown, because OpenAI publishes no per-frame token count. +`--format svg` asks a GPT Image 2.6 model to author a static SVG, written as +UTF-8 XML to a `.svg` file. It works on new images only: `--ref`, `--mask`, +`--transparent`, the 2.5 models and Gemini are refused before any request. +OpenAI says the output is static, but the module checks rather than trusts it. +An SVG that is not UTF-8 or not an SVG document, or that contains a DOCTYPE, +`'], + ["an event handler", ''], + ["an event handler on a child", ''], + ["a foreignObject", '
'], + ["an external href", ''], + ["an external xlink:href", ''], + ["an embedded raster", ''], + ["a javascript: link", ''], + ["an external url()", ''], + ["a stylesheet import", ''], + ["an entity declaration", ']>&x;'], + ["something that is not SVG", "hi"], + ]; + for (const [label, svg] of active) { + test(`an SVG with ${label} is refused and nothing is written`, async () => { + serve(svg); + expect(await run(["x", "--format", "svg", "--out", "bad.svg"])).toBe(1); + expect(calls).toHaveLength(1); + expect(existsSync(join(root, "bad.svg")), "IMAGE_SVG_ACTIVE_CONTENT").toBe(false); + expect(out.join("\n")).toMatch(/SVG/); + }); + } + + test("an SVG's cost is unknown when its authoring tokens cannot be priced", async () => { + serve(CLEAN_SVG, { + usage: { output_tokens: 100, input_tokens_details: { text_tokens: 10, image_tokens: 0 } }, + svg_usage: { input_tokens: 500, output_tokens: 2000 }, + }); + expect(await run(["x", "--format", "svg", "--out", "x.svg"])).toBe(0); + expect(report().costUsd, "IMAGE_SVG_COST").toBeNull(); + }); + + test("an SVG dry run reports its cost as unknown", async () => { + expect(await run(["x", "--format", "svg", "--aspect", "1:1", "--dry-run"])).toBe(0); + expect(calls).toHaveLength(0); + expect(report().output).toEndWith(".svg"); + expect(report().estimatedCostUsd).toBeNull(); + }); +}); diff --git a/packages/module-images/tests/providers.test.ts b/packages/module-images/tests/providers.test.ts index 331afe9eb8..c05712542e 100644 --- a/packages/module-images/tests/providers.test.ts +++ b/packages/module-images/tests/providers.test.ts @@ -290,6 +290,41 @@ describe("openai provider — animated GIF (#3783)", () => { } }); +describe("openai provider — static SVG (#3784)", () => { + const svg = ''; + + test("only the 2.6 pair lists svg among its formats", () => { + expect(openaiProvider.models.filter((m) => m.outputFormats.includes("svg")).map((m) => m.id)).toEqual([SUNBURST, FLARE]); + }); + + test("an SVG response is decoded as image/svg+xml with its cost unknown", async () => { + stub({ data: [{ b64_json: Buffer.from(svg).toString("base64") }], usage: { output_tokens: 1, input_tokens_details: { text_tokens: 1, image_tokens: 0 } } }); + const result = await openaiProvider.generate(SUNBURST, { prompt: "x", format: "svg" }, "k"); + expect(result.images[0].mime).toBe("image/svg+xml"); + expect(new TextDecoder().decode(result.images[0].data)).toBe(svg); + expect(result.costUsd).toBeUndefined(); + }); + + const refusals: [string, Parameters[1], string][] = [ + ["SVG on a 2.5 model", { prompt: "x", format: "svg" }, "gpt-image-2.5-sunburst"], + ["SVG as an edit", { prompt: "x", format: "svg", references: [ref()] }, SUNBURST], + ["SVG with transparency", { prompt: "x", format: "svg", transparent: true }, SUNBURST], + ["SVG with n above 1", { prompt: "x", format: "svg", n: 2 }, SUNBURST], + ]; + for (const [label, req, model] of refusals) { + test(`a direct call with ${label} refuses before fetch`, async () => { + const calls = stub({ data: [{ b64_json: PNG_B64 }] }); + await expect(openaiProvider.generate(model, req, "k")).rejects.toThrow(/SVG/); + expect(calls).toHaveLength(0); + }); + } + + test("a direct call that gets active SVG back throws instead of returning it", async () => { + stub({ data: [{ b64_json: Buffer.from('').toString("base64") }] }); + await expect(openaiProvider.generate(SUNBURST, { prompt: "x", format: "svg" }, "k")).rejects.toThrow(/script/); + }); +}); + describe("GPT Image 2.5 and 2.6 output-token estimate", () => { // The guide's one calculator covers both generations (checked 2026-11-09). const SUNBURST = "gpt-image-2.6-sunburst"; From 3d02d288c6a68e7089d7ff684777ee0d6b3a5ff6 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Wed, 11 Nov 2026 02:35:31 +0000 Subject: [PATCH 3/3] fix(images): spell the SVG byte-order mark as an escape (#3784) Co-Authored-By: Claude Opus 5.5 --- packages/module-images/src/svg.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/module-images/src/svg.ts b/packages/module-images/src/svg.ts index c3a225a2ff..3c4575e7b6 100644 --- a/packages/module-images/src/svg.ts +++ b/packages/module-images/src/svg.ts @@ -32,7 +32,7 @@ const ACTIVE: [RegExp, string][] = [ /** Why `text` is not a static SVG, or `undefined` when it is one. */ export function staticSvgProblem(text: string): string | undefined { - const start = text.replace(/^/, "").trimStart().replace(/^<\?xml[^>]*\?>\s*/i, ""); + const start = text.replace(/^\uFEFF/, "").trimStart().replace(/^<\?xml[^>]*\?>\s*/i, ""); if (!/^<\s*svg[\s>]/i.test(start)) return "it is not an SVG document"; for (const [pattern, what] of ACTIVE) { if (pattern.test(text)) return `it contains ${what}`;