Skip to content
Merged
5 changes: 5 additions & 0 deletions .changeset/gpt-image-markup.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@schlessera/brain-module-images": minor
---

`brain image --markup <path>` sends an annotation layer with an edit on the GPT Image 2.6 and 2.5 models: a transparent PNG the size of the first `--ref`, posted as the `markup` part of `/v1/images/edits`. Markup without a `--ref`, with `--mask`, that is not a PNG with an alpha channel, whose size differs from the first reference (measured after a JPEG's EXIF orientation), past 16,777,216 pixels or 50 MB, or on Gemini is refused before any request.
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:255-256`).
(`const relayRefusal`, `packages/module-images/src/providers/openai.ts:258-259`).
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:474-485`). Its help example
(`const payload`, `packages/module-images/src/cli.ts:490-501`). 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
11 changes: 11 additions & 0 deletions packages/module-images/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ serve at all:
| Request | Routes to | Reason |
|---|---|---|
| Masked inpainting | OpenAI | Google's image API has no mask concept |
| Markup-guided edit (`--markup`) | OpenAI GPT Image 2.6 or 2.5 | Only these models take an annotation layer; Gemini has none |
| Transparent background | OpenAI, on the selected model | Every GPT Image 2.6 and 2.5 model returns real alpha on png or webp; Gemini documents none |
| 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 |
Expand Down Expand Up @@ -80,6 +81,16 @@ 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.

`--markup <path>` sends an annotation layer with an edit: a transparent PNG,
the same width and height as the first `--ref`, whose circles, arrows and notes
show the model what to change. It needs at least one `--ref` and cannot be
combined with `--mask`. The layer is checked from the file headers before any
request: it must be a PNG with an alpha channel, it must match the first
reference's size (a JPEG reference is measured after its EXIF orientation), the
reference and the layer may hold at most 16,777,216 pixels each, and the layer
file at most 50 MB. Gemini has no annotation layer, so markup there is refused.
OpenAI charges nothing extra for it.

### Retired models

`gpt-image-2` and `gpt-image-1.5` are no longer supported. Naming either in
Expand Down
17 changes: 17 additions & 0 deletions packages/module-images/skills/image-gen/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ only when the user asked for something else.
| The request involves | Goes to | Because |
|---|---|---|
| A mask — change *this* region | OpenAI | Google's image API has no mask concept at all |
| A markup layer — circles and notes on the image | OpenAI GPT Image 2.6 or 2.5 | Only these models take an annotation layer |
| A transparent background | OpenAI, on the selected model | Every GPT Image 2.6 and 2.5 model returns real alpha, on png or webp — never jpeg |
| An exact odd pixel size | OpenAI | Gemini offers fixed ratios and 1K/2K/4K only |
| Legible text inside the image | `gpt-image-2.6-sunburst` | The default; no text-rendering benchmark covers the 2.6 models yet |
Expand Down Expand Up @@ -169,6 +170,22 @@ brain image "replace the sky with heavy storm clouds" \
- No mask? Describe the change instead. That is the only option on Gemini, and
it is often the better one for restyling a whole image.

When pointing is easier than describing, use a markup layer instead of a mask:

```sh
brain image "move the boat to where the arrow points; recolour the circled sail red" \
--ref photos/ithaca-harbour.png --markup photos/ithaca-harbour-notes.png \
--out photos/ithaca-harbour-edit.png
```

- The layer is a separate **transparent PNG, exactly the size of the first
`--ref`**, with the strokes and notes drawn on it. Never flatten it onto the
photo; a layer with no alpha channel is refused.
- `--markup` needs a `--ref` and cannot go with `--mask`. Pick one: a mask
fences off a region, markup explains the change.
- A size mismatch is refused before anything is paid for. Say which sizes
differ and offer to resize the layer.

## When it fails

The command explains failures rather than dumping a status code, and says
Expand Down
20 changes: 18 additions & 2 deletions packages/module-images/src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import { availableModels, providerFor, PROVIDERS } from "./providers/index.js";
import { isWithheldKey, providerUnavailableNotice } from "@schlessera/brain-common/internal/provider-unavailable";
import { PROVIDER_RELAY_PLACEHOLDER, providerCredential, relayedKey } from "@schlessera/brain-common/internal/provider-relay";
import { estimateOpenAiOutputCost, openAiRequestQuality, openAiRequestSize } from "./providers/openai.js";
import { markupProblem } from "./markup.js";
import { isRetiredModel, retiredModelMessage } from "./retired.js";
import { route, type RoutingDecision } from "./routing.js";
import {
Expand Down Expand Up @@ -93,6 +94,9 @@ Shape (--aspect and --resolution work on every model):
Editing:
--ref <path> Reference image; repeatable
--mask <path> Alpha mask; transparent pixels mark what may change (OpenAI only)
--markup <path> Annotation layer: a transparent PNG the exact size of the first
--ref, whose circles, arrows and notes guide the edit. Needs a
--ref, excludes --mask; GPT Image 2.6 and 2.5 only (no fee)

Routing:
--provider openai|gemini Pin a provider
Expand All @@ -103,8 +107,8 @@ Routing:
--draft A quick throwaway illustration (gemini-3.1-flash-lite-image)
--dry-run Decide and price it, write nothing

Routing is by capability: a mask, a transparent background or an exact pixel
size forces OpenAI; heavy reference counts and character consistency favour
Routing is by capability: a mask, a markup layer, a transparent background or
an exact pixel size forces OpenAI; heavy reference counts and character consistency favour
Gemini. Otherwise the default is gpt-image-2.6-sunburst when OpenAI is
available; gpt-image-2.6-flare and the 2.5 pair are chosen by --model or
preferredModels.
Expand Down Expand Up @@ -279,11 +283,23 @@ export const imageCommand: CommandModule<ImagesConfig> = {
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,
markup: parsed.flags.markup ? loadImage(ctx.root, parsed.flags.markup as string) : undefined,
};
} catch (e) {
console.error((e as Error).message);
return 1;
}
// A markup layer is checked from the file headers before routing, so a
// mismatched or flattened layer never reaches a paid call (#3785).
if (request.markup) {
const problem = request.mask
? "--markup and --mask are exclusive: the markup layer guides the whole edit. Drop one of them."
: markupProblem(request.markup, request.references?.[0]);
if (problem) {
console.error(problem);
return 1;
}
}

const decision = route({
request,
Expand Down
150 changes: 150 additions & 0 deletions packages/module-images/src/markup.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,150 @@
/**
* Markup-guided edits (#3785): the checks a markup layer must pass before any
* provider is paid, read from file headers only.
*
* OpenAI's image-generation guide (checked 2026-11-11) says the layer is a
* separate transparent PNG, sent as `markup` on `/v1/images/edits` to the GPT
* Image 2.5 and 2.6 models. It applies to the first input image, must match
* that image's width and height after orientation, and may not be combined
* with `mask`. The first image and the layer each hold at most 16,777,216
* pixels, and the layer file at most 50 MB.
* https://developers.openai.com/api/docs/guides/image-generation
*/

import type { ImageInput } from "./types.js";

export const MARKUP_LIMITS = { maxPixels: 16_777_216, maxBytes: 50 * 1024 * 1024 } as const;

const PNG_SIGNATURE = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a];

export interface ImageHeader {
format: "png" | "jpeg" | "webp";
/** As displayed: a JPEG's EXIF orientation 5-8 swaps the stored edges. */
width: number;
height: number;
/** PNG only: an alpha channel, or a tRNS chunk. */
alpha?: boolean;
}

const u16be = (d: Uint8Array, i: number) => (d[i] << 8) | d[i + 1];
const u32be = (d: Uint8Array, i: number) => ((d[i] << 24) >>> 0) + (d[i + 1] << 16) + (d[i + 2] << 8) + d[i + 3];
const u16le = (d: Uint8Array, i: number) => d[i] | (d[i + 1] << 8);
const u24le = (d: Uint8Array, i: number) => d[i] | (d[i + 1] << 8) | (d[i + 2] << 16);
const ascii = (d: Uint8Array, i: number, n: number) => String.fromCharCode(...d.subarray(i, i + n));

export function isPng(data: Uint8Array): boolean {
return data.length >= 8 && PNG_SIGNATURE.every((b, i) => data[i] === b);
}

function pngHeader(d: Uint8Array): ImageHeader | null {
if (d.length < 33 || ascii(d, 12, 4) !== "IHDR") return null;
const colorType = d[25];
let alpha = colorType === 4 || colorType === 6;
// A tRNS chunk gives palette or truecolour images transparency; it must
// come before the first IDAT.
for (let i = 8; !alpha && i + 8 <= d.length; ) {
const len = u32be(d, i);
const type = ascii(d, i + 4, 4);
if (type === "tRNS") alpha = true;
if (type === "IDAT" || type === "IEND") break;
i += 12 + len;
}
return { format: "png", width: u32be(d, 16), height: u32be(d, 20), alpha };
}

/** EXIF orientation from an APP1 segment, or 1 when absent or unreadable. */
function exifOrientation(d: Uint8Array, start: number, end: number): number {
if (ascii(d, start, 6) !== "Exif\0\0") return 1;
const tiff = start + 6;
const le = ascii(d, tiff, 2) === "II";
if (!le && ascii(d, tiff, 2) !== "MM") return 1;
const r16 = (i: number) => (le ? u16le(d, i) : u16be(d, i));
const r32 = (i: number) => (le ? (u16le(d, i) | (u16le(d, i + 2) << 16)) >>> 0 : u32be(d, i));
const ifd = tiff + r32(tiff + 4);
if (ifd + 2 > end) return 1;
const count = r16(ifd);
for (let k = 0; k < count; k++) {
const entry = ifd + 2 + k * 12;
if (entry + 12 > end) return 1;
if (r16(entry) === 0x0112) return r16(entry + 8);
}
return 1;
}

function jpegHeader(d: Uint8Array): ImageHeader | null {
let orientation = 1;
for (let i = 2; i + 4 <= d.length; ) {
if (d[i] !== 0xff) return null;
const marker = d[i + 1];
if (marker === 0xff) {
i++;
continue;
}
const len = u16be(d, i + 2);
if (marker === 0xe1) orientation = exifOrientation(d, i + 4, Math.min(d.length, i + 2 + len));
// SOF0-SOF15 carry the frame size; C4 (DHT), C8 (JPG) and CC (DAC) do not.
if (marker >= 0xc0 && marker <= 0xcf && marker !== 0xc4 && marker !== 0xc8 && marker !== 0xcc) {
if (i + 9 > d.length) return null;
const height = u16be(d, i + 5);
const width = u16be(d, i + 7);
return orientation >= 5 && orientation <= 8
? { format: "jpeg", width: height, height: width }
: { format: "jpeg", width, height };
}
i += 2 + len;
}
return null;
}

function webpHeader(d: Uint8Array): ImageHeader | null {
if (d.length < 30) return null;
const chunk = ascii(d, 12, 4);
if (chunk === "VP8X") return { format: "webp", width: u24le(d, 24) + 1, height: u24le(d, 27) + 1 };
if (chunk === "VP8L" && d[20] === 0x2f) {
const bits = d[21] | (d[22] << 8) | (d[23] << 16) | (d[24] << 24);
return { format: "webp", width: (bits & 0x3fff) + 1, height: ((bits >>> 14) & 0x3fff) + 1 };
}
if (chunk === "VP8 " && d[23] === 0x9d && d[24] === 0x01 && d[25] === 0x2a) {
return { format: "webp", width: u16le(d, 26) & 0x3fff, height: u16le(d, 28) & 0x3fff };
}
return null;
}

/** Width and height from a PNG, JPEG or WebP header, by signature, not by file name. */
export function imageHeader(data: Uint8Array): ImageHeader | null {
if (isPng(data)) return pngHeader(data);
if (data.length >= 3 && data[0] === 0xff && data[1] === 0xd8 && data[2] === 0xff) return jpegHeader(data);
if (data.length >= 12 && ascii(data, 0, 4) === "RIFF" && ascii(data, 8, 4) === "WEBP") return webpHeader(data);
return null;
}

/**
* Why a markup layer cannot go with this first reference image, or null when
* it can. Called before routing and again by the provider, so neither a CLI
* caller nor a direct one pays for a request the API would refuse.
*/
export function markupProblem(markup: ImageInput, first: ImageInput | undefined): string | null {
const name = markup.label ?? "the markup layer";
if (!first) return "--markup annotates the first --ref image; add one with --ref.";
if (markup.data.byteLength > MARKUP_LIMITS.maxBytes) {
return `${name} is ${markup.data.byteLength} bytes; a markup layer may be at most 50 MB.`;
}
if (!isPng(markup.data)) return `${name} is not a PNG; a markup layer must be a transparent PNG.`;
const layer = imageHeader(markup.data);
if (!layer) return `${name} has no readable PNG header.`;
if (!layer.alpha) {
return `${name} has no alpha channel; draw the markup on a transparent PNG, not flattened onto the image.`;
}
const refName = first.label ?? "the first --ref image";
const base = imageHeader(first.data);
if (!base) return `Cannot read the width and height of ${refName}; markup needs a PNG, JPEG or WebP first --ref.`;
for (const [what, h] of [[refName, base], [name, layer]] as const) {
if (h.width * h.height > MARKUP_LIMITS.maxPixels) {
return `${what} is ${h.width}x${h.height}, over the 16,777,216-pixel limit for markup edits.`;
}
}
if (layer.width !== base.width || layer.height !== base.height) {
return `${name} is ${layer.width}x${layer.height} but ${refName} is ${base.width}x${base.height}; the markup layer must match the first --ref exactly.`;
}
return null;
}
10 changes: 10 additions & 0 deletions packages/module-images/src/providers/gemini.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ const MODELS: ModelCapabilities[] = [
summary: "Nano Banana Pro — fallback; 4K and up to 5 characters, but below Flash at twice the price",
transparentBackground: false,
maskInpainting: false,
markupGuidance: false,
complexityControl: false,
arbitraryDimensions: false,
presetSizes: [],
Expand All @@ -44,6 +45,7 @@ const MODELS: ModelCapabilities[] = [
summary: "Nano Banana 2 — the workhorse; 10 references, 4 characters, up to 4K",
transparentBackground: false,
maskInpainting: false,
markupGuidance: false,
complexityControl: false,
arbitraryDimensions: false,
presetSizes: [],
Expand All @@ -63,6 +65,7 @@ const MODELS: ModelCapabilities[] = [
summary: "Nano Banana 2 Lite — the `--draft` tier; cheapest, 1K only, 14 references",
transparentBackground: false,
maskInpainting: false,
markupGuidance: false,
complexityControl: false,
arbitraryDimensions: false,
presetSizes: [],
Expand Down Expand Up @@ -142,6 +145,13 @@ export const geminiProvider: Provider = {
models: MODELS,

async generate(model, req, apiKey) {
// No annotation layer here (#3785): routing refuses it, and a direct
// caller must not get an edit that silently ignored its markup.
if (req.markup) {
throw new ImageProviderError("Gemini takes no markup layer; use an OpenAI GPT Image 2.6 or 2.5 model.", {
retryable: false,
});
}
const input: Record<string, unknown>[] = [{ type: "text", text: req.prompt }];
// Editing is the same call with image parts alongside the text. There is no
// mask concept in this API — routing sends masked work to OpenAI.
Expand Down
20 changes: 19 additions & 1 deletion packages/module-images/src/providers/openai.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import {
} from "../shape.js";
import { resolveEnv } from "../config/env.js";
import { providerRelayFetch } from "@schlessera/brain-common/internal/provider-relay";
import { markupProblem } from "../markup.js";
import { isRetiredModel, retiredModelMessage } from "../retired.js";
import { staticSvgProblem } from "../svg.js";
import {
Expand Down Expand Up @@ -52,6 +53,8 @@ const GPT_IMAGE = {
provider: "openai",
transparentBackground: true,
maskInpainting: true,
// Markup-guided edits are documented for the 2.5 and 2.6 pairs alike (#3785).
markupGuidance: true,
arbitraryDimensions: true,
presetSizes: PRESETS,
maxEdgePx: OPENAI_LIMITS.maxEdge,
Expand Down Expand Up @@ -356,6 +359,17 @@ export const openaiProvider: Provider = {
retryable: false,
});
}
if (req.markup) {
// Routing and the CLI have checked this already; a direct caller has not.
if (req.mask) {
throw new ImageProviderError("markup and mask are exclusive.", { retryable: false });
}
if (!MODELS.find((m) => m.id === model)?.markupGuidance) {
throw new ImageProviderError(`${model} does not take a markup layer.`, { retryable: false });
}
const problem = markupProblem(req.markup, req.references?.[0]);
if (problem) throw new ImageProviderError(problem, { 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 Expand Up @@ -390,7 +404,7 @@ export const openaiProvider: Provider = {

// Edits are multipart. Reference images repeat as `image[]`; the mask is a
// PNG whose fully transparent pixels mark what may change, and it applies
// to the FIRST image only.
// to the FIRST image only, as does a markup layer.
const form = new FormData();
form.append("model", model);
form.append("prompt", req.prompt);
Expand All @@ -408,6 +422,10 @@ export const openaiProvider: Provider = {
if (req.mask) {
form.append("mask", new Blob([req.mask.data as BlobPart], { type: "image/png" }), "mask.png");
}
// The markup layer annotates the first image; it is never sent with a mask (#3785).
if (req.markup) {
form.append("markup", new Blob([req.markup.data as BlobPart], { type: "image/png" }), "markup.png");
}

const res = await send(`${resolveEnv().openaiBaseUrl}/images/edits`, { method: "POST", headers, body: form });
if (!res.ok) await readError(res, req);
Expand Down
Loading
Loading