From 00993b125cedc570fe47d24b5d7778a44dd53da7 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Wed, 11 Nov 2026 08:49:33 +0000 Subject: [PATCH 1/3] feat(module-images): markup-guided edits with --markup (#3785) Co-Authored-By: Claude Opus 5.5 --- packages/module-images/src/cli.ts | 20 ++- packages/module-images/src/markup.ts | 150 ++++++++++++++++++ .../module-images/src/providers/gemini.ts | 10 ++ .../module-images/src/providers/openai.ts | 20 ++- packages/module-images/src/routing.ts | 27 ++++ packages/module-images/src/types.ts | 7 + packages/module-images/tests/cli.test.ts | 120 ++++++++++++++ packages/module-images/tests/image-bytes.ts | 45 ++++++ .../module-images/tests/providers.test.ts | 46 ++++++ packages/module-images/tests/routing.test.ts | 26 +++ 10 files changed, 468 insertions(+), 3 deletions(-) create mode 100644 packages/module-images/src/markup.ts create mode 100644 packages/module-images/tests/image-bytes.ts diff --git a/packages/module-images/src/cli.ts b/packages/module-images/src/cli.ts index dbf8e2d03b..4aecd141c6 100644 --- a/packages/module-images/src/cli.ts +++ b/packages/module-images/src/cli.ts @@ -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 { @@ -93,6 +94,9 @@ Shape (--aspect and --resolution work on every model): Editing: --ref Reference image; repeatable --mask Alpha mask; transparent pixels mark what may change (OpenAI only) + --markup 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 @@ -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. @@ -279,11 +283,23 @@ export const imageCommand: CommandModule = { 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, diff --git a/packages/module-images/src/markup.ts b/packages/module-images/src/markup.ts new file mode 100644 index 0000000000..20a560e379 --- /dev/null +++ b/packages/module-images/src/markup.ts @@ -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; +} diff --git a/packages/module-images/src/providers/gemini.ts b/packages/module-images/src/providers/gemini.ts index 542bbc86ff..64a66909d2 100644 --- a/packages/module-images/src/providers/gemini.ts +++ b/packages/module-images/src/providers/gemini.ts @@ -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: [], @@ -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: [], @@ -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: [], @@ -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[] = [{ 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. diff --git a/packages/module-images/src/providers/openai.ts b/packages/module-images/src/providers/openai.ts index 7ce8e0e4e1..ccc7144d42 100644 --- a/packages/module-images/src/providers/openai.ts +++ b/packages/module-images/src/providers/openai.ts @@ -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 { @@ -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, @@ -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 }); } @@ -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); @@ -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); diff --git a/packages/module-images/src/routing.ts b/packages/module-images/src/routing.ts index 9b762cdf8e..e7d2450e45 100644 --- a/packages/module-images/src/routing.ts +++ b/packages/module-images/src/routing.ts @@ -153,6 +153,30 @@ export function route(input: RoutingInput): RoutingDecision { pool = masked; } + // A markup layer annotates the first reference image and replaces a mask + // rather than joining one (#3785). Only OpenAI's 2.5 and 2.6 models take it. + if (req.markup) { + if (req.mask) { + return { + kind: "impossible", + reason: "--markup and --mask are exclusive: the markup layer guides the whole edit. Drop one of them.", + }; + } + if ((req.references?.length ?? 0) === 0) { + return { kind: "impossible", reason: "--markup annotates the first --ref image; add one with --ref." }; + } + const marked = byCapability(pool, (m) => m.markupGuidance); + if (marked.length === 0) { + return { + kind: "impossible", + reason: + "Markup-guided edits need an OpenAI GPT Image 2.6 or 2.5 model — Google's image API has no " + + "annotation layer. Set OPENAI_API_KEY, or drop --markup and describe the change in words.", + }; + } + pool = marked; + } + // Complexity is a GPT Image 2.6 parameter. A stated one on any other model // would be dropped or rejected by the API, so it narrows or refuses here. if (req.complexity) { @@ -367,6 +391,9 @@ export function route(input: RoutingInput): RoutingDecision { if (req.mask) { return { kind: "resolved", model: ordered[0], reason: "only OpenAI image models accept an alpha mask" }; } + if (req.markup) { + return { kind: "resolved", model: ordered[0], reason: "only OpenAI GPT Image 2.6 and 2.5 models take a markup layer" }; + } if (req.transparent) { return { kind: "resolved", diff --git a/packages/module-images/src/types.ts b/packages/module-images/src/types.ts index b25007d990..ef28a2adcc 100644 --- a/packages/module-images/src/types.ts +++ b/packages/module-images/src/types.ts @@ -45,6 +45,11 @@ export interface ImageRequest { references?: ImageInput[]; /** Alpha mask — transparent pixels mark the editable region. OpenAI only. */ mask?: ImageInput; + /** + * Markup annotation layer (#3785): a transparent PNG the size of the first + * reference, whose strokes and notes guide the edit. Exclusive with `mask`. + */ + markup?: ImageInput; n?: number; } @@ -121,6 +126,8 @@ export interface ModelCapabilities { transparentBackground: boolean; /** Pixel-scoped inpainting with an alpha mask. */ maskInpainting: boolean; + /** Takes a `markup` annotation layer on edits: GPT Image 2.5 and 2.6 (#3785). */ + markupGuidance: boolean; /** Takes OpenAI's `complexity` (planning effort) parameter: GPT Image 2.6. */ complexityControl: boolean; /** diff --git a/packages/module-images/tests/cli.test.ts b/packages/module-images/tests/cli.test.ts index cdaf51ce2f..645c205e9a 100644 --- a/packages/module-images/tests/cli.test.ts +++ b/packages/module-images/tests/cli.test.ts @@ -9,6 +9,7 @@ import { buildTaxonomy } from "@schlessera/brain/module"; import { imageCommand } from "../src/cli"; import { configSchema } from "../src/module"; +import { jpeg, png, webp } from "./image-bytes"; const SUNBURST = "gpt-image-2.6-sunburst"; const FLARE = "gpt-image-2.6-flare"; @@ -528,3 +529,122 @@ describe("brain image — static SVG on GPT Image 2.6 (#3784)", () => { expect(report().estimatedCostUsd).toBeNull(); }); }); + +describe("brain image — markup-guided edits (#3785)", () => { + const put = (name: string, data: Uint8Array) => writeFileSync(join(root, "photos", name), data); + const edit = (...flags: string[]) => run(["circle the ship", ...flags, "--out", "edit.png"]); + + test("--ref with --markup posts a markup part to /images/edits on the default model, with no mask", async () => { + put("ithaca.png", png(1024, 768)); + put("notes.png", png(1024, 768)); + expect(await edit("--ref", "photos/ithaca.png", "--markup", "photos/notes.png")).toBe(0); + expect(calls).toHaveLength(1); + expect(calls[0].url).toEndWith("/images/edits"); + const form = calls[0].init.body as FormData; + expect(form.get("model")).toBe(SUNBURST); + const markup = form.get("markup"); + expect(markup, "IMAGE_MARKUP_PART").toBeInstanceOf(Blob); + expect(new Uint8Array(await (markup as Blob).arrayBuffer())).toEqual(png(1024, 768)); + expect((markup as Blob).type).toBe("image/png"); + expect(form.get("mask")).toBeNull(); + expect(form.getAll("image[]")).toHaveLength(1); + expect(report().reason).toMatch(/markup/); + }); + + test("a GPT Image 2.5 model takes markup too", async () => { + put("ithaca.png", png(64, 64)); + put("notes.png", png(64, 64)); + expect(await edit("--ref", "photos/ithaca.png", "--markup", "photos/notes.png", "--model", "gpt-image-2.5-flare")).toBe(0); + expect((calls[0].init.body as FormData).get("model")).toBe("gpt-image-2.5-flare"); + }); + + test("a palette PNG with a tRNS chunk counts as transparent", async () => { + put("ithaca.png", png(64, 64)); + put("notes.png", png(64, 64, { colorType: 3, trns: true })); + expect(await edit("--ref", "photos/ithaca.png", "--markup", "photos/notes.png")).toBe(0); + }); + + test("the size of a JPEG --ref is read after its EXIF orientation", async () => { + // Stored 768 wide and 1024 high, rotated 90° to display as 1024x768. + put("ithaca.jpg", jpeg(768, 1024, 6)); + put("notes.png", png(1024, 768)); + expect(await edit("--ref", "photos/ithaca.jpg", "--markup", "photos/notes.png")).toBe(0); + expect(calls).toHaveLength(1); + }); + + test("a WebP --ref's size is read from its header", async () => { + put("ithaca.webp", webp(800, 600)); + put("notes.png", png(800, 600)); + expect(await edit("--ref", "photos/ithaca.webp", "--markup", "photos/notes.png")).toBe(0); + }); + + const refused: [string, () => void, string[], RegExp][] = [ + ["no --ref", () => put("notes.png", png(64, 64)), ["--markup", "photos/notes.png"], /--ref/], + [ + "--mask", + () => (put("ithaca.png", png(64, 64)), put("notes.png", png(64, 64))), + ["--ref", "photos/ithaca.png", "--mask", "photos/mask.png", "--markup", "photos/notes.png"], + /exclusive/, + ], + [ + "a JPEG named .png", + () => (put("ithaca.png", png(64, 64)), put("notes.png", jpeg(64, 64))), + ["--ref", "photos/ithaca.png", "--markup", "photos/notes.png"], + /not a PNG/, + ], + [ + "a flattened PNG with no alpha", + () => (put("ithaca.png", png(64, 64)), put("notes.png", png(64, 64, { colorType: 2 }))), + ["--ref", "photos/ithaca.png", "--markup", "photos/notes.png"], + /alpha/, + ], + [ + "mismatched dimensions", + () => (put("ithaca.png", png(1024, 768)), put("notes.png", png(1024, 1024))), + ["--ref", "photos/ithaca.png", "--markup", "photos/notes.png"], + /1024x1024 but .*1024x768/, + ], + [ + "a JPEG --ref whose orientation swaps its edges", + () => (put("ithaca.jpg", jpeg(1024, 768, 8)), put("notes.png", png(1024, 768))), + ["--ref", "photos/ithaca.jpg", "--markup", "photos/notes.png"], + /1024x768 but .*768x1024/, + ], + [ + "a first --ref past the pixel limit", + () => (put("ithaca.png", png(4097, 4096)), put("notes.png", png(4097, 4096))), + ["--ref", "photos/ithaca.png", "--markup", "photos/notes.png"], + /16,777,216/, + ], + [ + "an unreadable first --ref", + () => (put("ithaca.png", new Uint8Array([1, 2, 3])), put("notes.png", png(64, 64))), + ["--ref", "photos/ithaca.png", "--markup", "photos/notes.png"], + /Cannot read/, + ], + ]; + for (const [label, setup, flags, said] of refused) { + test(`markup with ${label} refuses before any request`, async () => { + setup(); + expect(await edit(...flags)).toBe(1); + expect(calls, "IMAGE_MARKUP_REFUSED").toHaveLength(0); + expect(out.join("\n")).toMatch(said); + }); + } + + test("markup on Gemini refuses before any request", async () => { + process.env.GEMINI_API_KEY = "placeholder-never-sent"; + put("ithaca.png", png(64, 64)); + put("notes.png", png(64, 64)); + expect(await edit("--ref", "photos/ithaca.png", "--markup", "photos/notes.png", "--provider", "gemini")).toBe(1); + expect(calls, "IMAGE_MARKUP_GEMINI").toHaveLength(0); + expect(out.join("\n")).toMatch(/markup/i); + }); + + test("a dry run checks the markup layer too", async () => { + put("ithaca.png", png(64, 64)); + put("notes.png", png(32, 32)); + expect(await edit("--ref", "photos/ithaca.png", "--markup", "photos/notes.png", "--dry-run")).toBe(1); + expect(out.join("\n")).toMatch(/must match/); + }); +}); diff --git a/packages/module-images/tests/image-bytes.ts b/packages/module-images/tests/image-bytes.ts new file mode 100644 index 0000000000..7d7be5f0e9 --- /dev/null +++ b/packages/module-images/tests/image-bytes.ts @@ -0,0 +1,45 @@ +// Header-only image bytes for the markup checks (#3785). Each carries just +// enough of its format for a header reader: the pixels are never decoded. + +const be32 = (n: number) => [(n >>> 24) & 255, (n >>> 16) & 255, (n >>> 8) & 255, n & 255]; +const chunk = (type: string, data: number[]) => [...be32(data.length), ...Buffer.from(type), ...data, 0, 0, 0, 0]; + +/** A PNG with an IHDR of this size. Colour type 6 is RGBA; 2 is RGB. */ +export function png(width: number, height: number, opts: { colorType?: number; trns?: boolean } = {}): Uint8Array { + return new Uint8Array([ + 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, + ...chunk("IHDR", [...be32(width), ...be32(height), 8, opts.colorType ?? 6, 0, 0, 0]), + ...(opts.trns ? chunk("tRNS", [0, 0, 0, 0, 0, 0]) : []), + ...chunk("IDAT", [0]), + ...chunk("IEND", []), + ]); +} + +/** A baseline JPEG whose SOF0 stores this size, with an optional EXIF orientation. */ +export function jpeg(width: number, height: number, orientation?: number): Uint8Array { + const app1 = + orientation === undefined + ? [] + : (() => { + // "Exif\0\0", big-endian TIFF header, IFD0 with one Orientation entry. + const body = [ + ...Buffer.from("Exif"), 0, 0, + 0x4d, 0x4d, 0, 42, 0, 0, 0, 8, + 0, 1, 0x01, 0x12, 0, 3, 0, 0, 0, 1, 0, orientation, 0, 0, + 0, 0, 0, 0, + ]; + return [0xff, 0xe1, ((body.length + 2) >> 8) & 255, (body.length + 2) & 255, ...body]; + })(); + const sof = [0xff, 0xc0, 0, 11, 8, (height >> 8) & 255, height & 255, (width >> 8) & 255, width & 255, 1, 1, 0x11, 0]; + return new Uint8Array([0xff, 0xd8, ...app1, ...sof, 0xff, 0xd9]); +} + +/** An extended-format (VP8X) WebP whose canvas is this size. */ +export function webp(width: number, height: number): Uint8Array { + const le24 = (n: number) => [n & 255, (n >> 8) & 255, (n >> 16) & 255]; + return new Uint8Array([ + ...Buffer.from("RIFF"), 22, 0, 0, 0, ...Buffer.from("WEBP"), + ...Buffer.from("VP8X"), 10, 0, 0, 0, 0, 0, 0, 0, + ...le24(width - 1), ...le24(height - 1), + ]); +} diff --git a/packages/module-images/tests/providers.test.ts b/packages/module-images/tests/providers.test.ts index c05712542e..fc7065d2fe 100644 --- a/packages/module-images/tests/providers.test.ts +++ b/packages/module-images/tests/providers.test.ts @@ -11,6 +11,7 @@ import { afterEach, describe, expect, test } from "bun:test"; import { geminiProvider } from "../src/providers/gemini"; import { estimateOpenAiOutputCost, openAiCostFromUsage, openaiProvider } from "../src/providers/openai"; import { ImageProviderError, type ImageInput } from "../src/types"; +import { png } from "./image-bytes"; const realFetch = globalThis.fetch; afterEach(() => { @@ -418,3 +419,48 @@ describe("gemini provider", () => { ).rejects.toMatchObject({ opts: { retryable: true } }); }); }); + +describe("providers — markup layer guards for a direct caller (#3785)", () => { + const layer = (data = png(64, 64)): ImageInput => ({ data, mime: "image/png", label: "notes.png" }); + const base = (): ImageInput => ({ data: png(64, 64), mime: "image/png", label: "ithaca.png" }); + + test("OpenAI sends the markup part beside the first image", async () => { + const calls = stub({ data: [{ b64_json: PNG_B64 }] }); + await openaiProvider.generate(SUNBURST, { prompt: "x", references: [base()], markup: layer() }, "k"); + const form = calls[0].init.body as FormData; + expect(form.get("markup"), "IMAGE_MARKUP_PROVIDER_PART").toBeInstanceOf(Blob); + expect(form.get("mask")).toBeNull(); + }); + + const refused: [string, Parameters[1], RegExp][] = [ + ["a mask", { prompt: "x", references: [base()], markup: layer(), mask: layer() }, /exclusive/], + ["mismatched dimensions", { prompt: "x", references: [base()], markup: layer(png(64, 32)) }, /must match/], + [ + "a layer over 50 MB", + (() => { + const big = new Uint8Array(50 * 1024 * 1024 + 1); + big.set(png(64, 64)); + return { prompt: "x", references: [base()], markup: layer(big) }; + })(), + /50 MB/, + ], + ]; + for (const [label, req, said] of refused) { + test(`OpenAI refuses markup with ${label} without a request`, async () => { + const calls = stub({ data: [{ b64_json: PNG_B64 }] }); + const err = await openaiProvider.generate(SUNBURST, req, "k").catch((e) => e); + expect(err).toBeInstanceOf(ImageProviderError); + expect((err as Error).message).toMatch(said); + expect(calls, "IMAGE_MARKUP_PROVIDER_REFUSED").toHaveLength(0); + }); + } + + test("Gemini refuses a markup layer instead of ignoring it", async () => { + const calls = stub({}); + const err = await geminiProvider + .generate("gemini-3-pro-image", { prompt: "x", references: [base()], markup: layer() }, "k") + .catch((e) => e); + expect(err).toBeInstanceOf(ImageProviderError); + expect(calls, "IMAGE_MARKUP_GEMINI_PROVIDER").toHaveLength(0); + }); +}); diff --git a/packages/module-images/tests/routing.test.ts b/packages/module-images/tests/routing.test.ts index 591cc71c0c..282d98add0 100644 --- a/packages/module-images/tests/routing.test.ts +++ b/packages/module-images/tests/routing.test.ts @@ -376,3 +376,29 @@ test("a key the host withholds but relays keeps its provider's models available expect(relayed.map(model => model.id), "RELAYED_IMAGE_PROVIDER_AVAILABLE").toEqual(OPENAI_ONLY.map(model => model.id)); expect(availableModels(cfg, { BRAIN_WITHHELD_KEYS: "OPENAI_API_KEY" } as NodeJS.ProcessEnv)).toEqual([]); }); + +describe("markup layer (#3785)", () => { + test("markup with both providers routes to OpenAI and says why", () => { + const d = picked(route({ request: { prompt: "x", markup: img(), references: [img()] }, available: ALL })); + expect(d.model.provider).toBe("openai"); + expect(d.model.id).toBe(SUNBURST); + expect(d.reason).toMatch(/markup/); + }); + + test("markup with only Gemini is impossible", () => { + const d = route({ request: { prompt: "x", markup: img(), references: [img()] }, available: GEMINI_ONLY }); + expect(d.kind).toBe("impossible"); + expect((d as { reason: string }).reason).toContain("OPENAI_API_KEY"); + }); + + test("markup without a reference, or with a mask, is impossible", () => { + expect(route({ request: { prompt: "x", markup: img() }, available: ALL }).kind).toBe("impossible"); + expect( + route({ request: { prompt: "x", markup: img(), mask: img(), references: [img()] }, available: ALL }).kind + ).toBe("impossible"); + }); + + test("every OpenAI model takes markup and no Gemini model does", () => { + for (const m of ALL) expect(m.markupGuidance).toBe(m.provider === "openai"); + }); +}); From e65925c498b9103d84d48d1ab1d055ed58e71198 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Wed, 11 Nov 2026 08:50:34 +0000 Subject: [PATCH 2/3] docs(module-images): document --markup and fix moved citations (#3785) Co-Authored-By: Claude Opus 5.5 --- .changeset/gpt-image-markup.md | 5 +++++ docs/decisions/governed-writable-workers.md | 2 +- docs/hosting/paid-cli-provider-qualification.md | 2 +- packages/module-images/README.md | 11 +++++++++++ .../module-images/skills/image-gen/SKILL.md | 17 +++++++++++++++++ 5 files changed, 35 insertions(+), 2 deletions(-) create mode 100644 .changeset/gpt-image-markup.md diff --git a/.changeset/gpt-image-markup.md b/.changeset/gpt-image-markup.md new file mode 100644 index 0000000000..665af78646 --- /dev/null +++ b/.changeset/gpt-image-markup.md @@ -0,0 +1,5 @@ +--- +"@schlessera/brain-module-images": minor +--- + +`brain image --markup ` 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. diff --git a/docs/decisions/governed-writable-workers.md b/docs/decisions/governed-writable-workers.md index 555dca4309..c47e0a592d 100644 --- a/docs/decisions/governed-writable-workers.md +++ b/docs/decisions/governed-writable-workers.md @@ -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, diff --git a/docs/hosting/paid-cli-provider-qualification.md b/docs/hosting/paid-cli-provider-qualification.md index ab4bd54985..37c0836727 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: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. diff --git a/packages/module-images/README.md b/packages/module-images/README.md index eff3622280..bcc551fdc6 100644 --- a/packages/module-images/README.md +++ b/packages/module-images/README.md @@ -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 | @@ -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 ` 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 diff --git a/packages/module-images/skills/image-gen/SKILL.md b/packages/module-images/skills/image-gen/SKILL.md index bd07f30b7d..a4ef9ebeab 100644 --- a/packages/module-images/skills/image-gen/SKILL.md +++ b/packages/module-images/skills/image-gen/SKILL.md @@ -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 | @@ -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 From 4e95e0d10dce1ef6a5af672b8c77b43afea70221 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Wed, 11 Nov 2026 13:46:07 +0000 Subject: [PATCH 3/3] test(module-images): compare markup bytes as arrays for strict typecheck (#3785) Co-Authored-By: Claude Opus 5.5 --- packages/module-images/tests/cli.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/module-images/tests/cli.test.ts b/packages/module-images/tests/cli.test.ts index 645c205e9a..d5ae5b771a 100644 --- a/packages/module-images/tests/cli.test.ts +++ b/packages/module-images/tests/cli.test.ts @@ -544,7 +544,7 @@ describe("brain image — markup-guided edits (#3785)", () => { expect(form.get("model")).toBe(SUNBURST); const markup = form.get("markup"); expect(markup, "IMAGE_MARKUP_PART").toBeInstanceOf(Blob); - expect(new Uint8Array(await (markup as Blob).arrayBuffer())).toEqual(png(1024, 768)); + expect([...new Uint8Array(await (markup as Blob).arrayBuffer())]).toEqual([...png(1024, 768)]); expect((markup as Blob).type).toBe("image/png"); expect(form.get("mask")).toBeNull(); expect(form.getAll("image[]")).toHaveLength(1);