Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/gpt-image-2-6-svg.md
Original file line number Diff line number Diff line change
@@ -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.
2 changes: 1 addition & 1 deletion docs/decisions/governed-writable-workers.md
Original file line number Diff line number Diff line change
Expand Up @@ -4084,7 +4084,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,
Expand Down
2 changes: 1 addition & 1 deletion docs/hosting/paid-cli-provider-qualification.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
13 changes: 13 additions & 0 deletions packages/module-images/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down Expand Up @@ -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,
`<script>`, `<foreignObject>`, an embedding element, an event-handler attribute,
an `@import`, or any `href`, `src` or `url()` that is not a `#fragment`, is
refused and nothing is written. The call has still been paid for. SVG authoring
tokens are billed at a rate this module does not know, so the cost is reported
as unknown, before and after the call. The `svg` authoring-model option is
never sent.

### Retired models

`gpt-image-2` and `gpt-image-1.5` are no longer supported. Naming either in
Expand Down
8 changes: 8 additions & 0 deletions packages/module-images/skills/image-gen/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ only when the user asked for something else.
| 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 |
| A vector SVG | `gpt-image-2.6-sunburst` or `-flare` | Only the 2.6 models author SVG, and only as a new image |

### The cases worth knowing

Expand Down Expand Up @@ -130,6 +131,13 @@ 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.

For a scalable vector picture, such as an icon, a logo or a flat illustration,
pass `--format svg`. It makes a new image only, so it cannot edit a reference,
use a mask or have a transparent background. The command refuses an SVG with
scripts, event handlers or outside references and writes nothing; if that
happens, say so, and offer to ask again or to make a png. The cost of an SVG
is always unknown, so say that before running it.

`--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.
Expand Down
18 changes: 13 additions & 5 deletions packages/module-images/src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ import {
IMAGE_FORMATS,
IMAGE_QUALITIES,
ImageProviderError,
mimeExtension,
type ImageComplexity,
type ImageInput,
type ImageQuality,
Expand Down Expand Up @@ -60,12 +61,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|gif
--format png|jpeg|webp|gif|svg
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
--transparent, and a dry run cannot price it.
svg is a static SVG authored by GPT Image 2.6, for a new
image only (no --ref, --mask or --transparent). One with
scripts, event handlers or outside references is refused
and not written. Its cost is reported as unknown

Animation (--format gif only):
--frames <n> 2-16 frames. Default: the API's, 9
Expand Down Expand Up @@ -363,9 +368,10 @@ export const imageCommand: CommandModule<ImagesConfig> = {
// 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.
// GIF has no published per-frame token count and SVG authoring has no
// published rate here, so neither is ever priced.
const estimatedCostUsd =
request.format === "gif"
request.format === "gif" || request.format === "svg"
? null
: model.provider === "openai"
? (estimateOpenAiOutputCost(model.id, openAiRequestQuality(request), openAiRequestSize(request, model.id)) ?? null)
Expand All @@ -383,6 +389,8 @@ export const imageCommand: CommandModule<ImagesConfig> = {
const cost =
request.format === "gif"
? "cost unknown — OpenAI publishes no per-frame token count for GIF"
: request.format === "svg"
? "cost unknown — SVG authoring is billed at a rate not published here"
: estimatedCostUsd === null && model.provider === "openai"
? "cost unknown — pass --size or --aspect (and a quality other than auto) to price it"
: price(estimatedCostUsd);
Expand Down Expand Up @@ -416,7 +424,7 @@ export const imageCommand: CommandModule<ImagesConfig> = {
// different format than the extension implies, and writing those bytes
// under the wrong name only surfaces when something tries to open it.
const [first, ...rest] = result.images;
const actualExt = first.mime.replace("image/", "").replace("jpg", "jpeg");
const actualExt = mimeExtension(first.mime);
let finalRel = outRel;
let renamed: string | undefined;
if (extname(outRel).slice(1).toLowerCase().replace("jpg", "jpeg") !== actualExt) {
Expand Down
42 changes: 37 additions & 5 deletions packages/module-images/src/providers/openai.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,9 @@ import {
import { resolveEnv } from "../config/env.js";
import { providerRelayFetch } from "@schlessera/brain-common/internal/provider-relay";
import { isRetiredModel, retiredModelMessage } from "../retired.js";
import { staticSvgProblem } from "../svg.js";
import {
formatMime,
ImageProviderError,
type ImageRequest,
type ImageResult,
Expand All @@ -41,7 +43,8 @@ import {
*
* Only the 2.6 pair takes `complexity` (low|medium|high, default high, no
* 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
* which need GIF preview access on the OpenAI organization, and author static
* SVG on generations (`output_format: "svg"`, `n` 1, #3784). 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.
*/
Expand Down Expand Up @@ -69,8 +72,8 @@ const GPT_IMAGE = {
approxCostUsd1K: null,
} satisfies Omit<ModelCapabilities, "id" | "summary" | "complexityControl">;

/** The 2.6 pair adds animated GIF to the shared formats (#3783). */
const GPT_IMAGE_26_FORMATS: ModelCapabilities["outputFormats"] = [...GPT_IMAGE.outputFormats, "gif"];
/** The 2.6 pair adds animated GIF (#3783) and authored SVG (#3784) to the shared formats. */
const GPT_IMAGE_26_FORMATS: ModelCapabilities["outputFormats"] = [...GPT_IMAGE.outputFormats, "gif", "svg"];

const MODELS: ModelCapabilities[] = [
{
Expand Down Expand Up @@ -276,16 +279,37 @@ function decode(body: OpenAiImageResponse, model: string, req: ImageRequest): Im
.filter((b): b is string => typeof b === "string" && b.length > 0)
.map((b64) => ({
data: Uint8Array.from(Buffer.from(b64, "base64")),
mime: `image/${req.format ?? "png"}`,
mime: formatMime(req.format ?? "png"),
}));
if (images.length === 0) {
throw new ImageProviderError("OpenAI returned no image data", { retryable: false });
}
if (req.format === "svg") {
// The API's "static" is a claim; the bytes are checked before anyone
// writes them (#3784). The call has been paid for either way.
for (const image of images) {
let text: string;
try {
text = new TextDecoder("utf-8", { fatal: true }).decode(image.data);
} catch {
throw new ImageProviderError("OpenAI returned an SVG that is not UTF-8; nothing was written.", { retryable: false });
}
const problem = staticSvgProblem(text);
if (problem) {
throw new ImageProviderError(
`OpenAI returned an SVG that is not static (${problem}); nothing was written. Ask again, or ask for png.`,
{ retryable: false }
);
}
}
}
return {
images,
provider: "openai",
model,
costUsd: openAiCostFromUsage(model, body.usage),
// SVG authoring tokens (`svg_usage`) are billed at the authoring model's
// rate, which is not published here, so an SVG's cost stays unknown.
costUsd: req.format === "svg" ? undefined : openAiCostFromUsage(model, body.usage),
costIsEstimate: true,
usage: body.usage,
};
Expand Down Expand Up @@ -324,6 +348,14 @@ export const openaiProvider: Provider = {
if (gif && (req.mask || req.transparent)) {
throw new ImageProviderError("GIF output takes no mask and no transparent background.", { retryable: false });
}
if (req.format === "svg" && !MODELS.find((m) => m.id === model)?.outputFormats.includes("svg")) {
throw new ImageProviderError(`${model} does not author SVG; the GPT Image 2.6 models do.`, { retryable: false });
}
if (req.format === "svg" && (isEdit || req.transparent || (req.n ?? 1) > 1)) {
throw new ImageProviderError("SVG is a single new image: no references, mask, transparent background or n above 1.", {
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 });
}
Expand Down
25 changes: 22 additions & 3 deletions packages/module-images/src/routing.ts
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,24 @@ export function route(input: RoutingInput): RoutingDecision {
};
}

// SVG is authored from one new rendering: the API takes it on generations
// only, with n 1, and documents no transparency for it (#3784).
if (req.format === "svg" && ((req.references?.length ?? 0) > 0 || req.mask)) {
return {
kind: "impossible",
reason: "SVG is authored on new images only, not edits. Drop --ref and --mask, or ask for png or webp.",
};
}
if (req.format === "svg" && req.transparent) {
return {
kind: "impossible",
reason: "A transparent background is documented for png and webp only, not SVG. Drop --transparent, or ask for png or webp.",
};
}
if (req.format === "svg" && (req.n ?? 1) > 1) {
return { kind: "impossible", reason: "SVG is authored one image at a time." };
}

if (req.transparent && req.format === "jpeg") {
return {
kind: "impossible",
Expand All @@ -209,12 +227,13 @@ 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);
if (supported.length === 0 && (req.format === "gif" || req.format === "svg")) {
const format = req.format;
const named = available.filter((m) => m.outputFormats.includes(format)).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` +
`${format === "gif" ? "Animated GIF" : "SVG"} 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.`,
Expand Down
41 changes: 41 additions & 0 deletions packages/module-images/src/svg.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
/**
* The static-SVG check for GPT Image 2.6 `output_format: "svg"` (#3784).
*
* OpenAI's image-generation guide says authored SVG is static: no scripts,
* no external resources, no embedded raster images. That is a vendor claim
* about model output, not a guarantee, and an SVG opened from the brain runs
* whatever it carries. So the text is checked before anything is written,
* and anything that could run code or fetch from elsewhere is refused.
*
* The check is deliberately textual and conservative: it scans the whole
* document, CDATA, comments and text included. A false positive refuses one
* picture with a reason; a false negative would write active content into
* the brain. `lintDocument` in render-template covers scripts and fetching
* elements for local markdown SVGs, but not event handlers, `foreignObject`
* or links, and this module does not depend on it.
*/

/** What makes an SVG not static, each with the reason shown to the user. */
const ACTIVE: [RegExp, string][] = [
[/<!DOCTYPE|<!ENTITY/i, "a DOCTYPE or entity declaration"],
[/<\s*(?:[a-z][\w.-]*:)?script\b/i, "a <script> element"],
[/<\s*(?:[a-z][\w.-]*:)?foreignObject\b/i, "a <foreignObject> element"],
[/<\s*(?:[a-z][\w.-]*:)?(?:iframe|object|embed|audio|video|handler|listener)\b/i, "an embedding or handler element"],
// An attribute named on*: whitespace, then the name, then `=`.
[/[\s"'/]on[a-z][\w.-]*\s*=/i, "an event-handler attribute"],
// Any link that is not a same-document fragment: external, data: (an
// embedded raster) and javascript: alike.
[/(?:^|[\s"'])(?:[a-z][\w.-]*:)?(?:href|src)\s*=\s*(?!["']\s*#)/i, "a reference outside the document"],
[/url\(\s*(?!["']?\s*#)/i, "a url() reference outside the document"],
[/@import\b/i, "a stylesheet @import"],
];

/** Why `text` is not a static SVG, or `undefined` when it is one. */
export function staticSvgProblem(text: string): string | undefined {
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}`;
}
return undefined;
}
17 changes: 14 additions & 3 deletions packages/module-images/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,12 +53,23 @@ export const IMAGE_QUALITIES = ["low", "medium", "high", "xhigh", "max", "auto"]
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).
* Output formats any model may return. `gif` is an animated GIF and `svg` an
* authored static SVG; only the GPT Image 2.6 models produce either (#3783,
* #3784).
*/
export const IMAGE_FORMATS = ["png", "jpeg", "webp", "gif"] as const;
export const IMAGE_FORMATS = ["png", "jpeg", "webp", "gif", "svg"] as const;
export type ImageFormat = (typeof IMAGE_FORMATS)[number];

/** The mime type of a format: `image/<format>`, except SVG. */
export function formatMime(format: ImageFormat): string {
return format === "svg" ? "image/svg+xml" : `image/${format}`;
}

/** The file extension for a mime type: the inverse of `formatMime`. */
export function mimeExtension(mime: string): string {
return mime === "image/svg+xml" ? "svg" : mime.replace("image/", "").replace("jpg", "jpeg");
}

/**
* 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
Expand Down
Loading
Loading