Compare commits

..
2 Commits
Author SHA1 Message Date
tbenandClaude Opus 5.5 23187f160c Bump version to 0.28.25
CI / check (push) Waiting to run
Release image / image (release) Waiting to run
Release image / computer-image (release) Waiting to run
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-12-06 12:00:24 +01:00
tbenandClaude Opus 5.5 942fba5bf1 Generate images on Cloudflare Workers AI through its native run route
Cloudflare's /ai/v1 has no images route, so every image call there failed
with 7000 No route for that URI. Image models now go to
<account>/ai/run/<model>: FLUX.2 as a multipart form with references as
input_image_<n>, the rest as JSON, retrying without width/height when a
model refuses them, and reading either the base64 envelope or raw bytes.
Only FLUX.2 models are catalogued as taking reference images.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-12-06 11:51:33 +01:00
8 changed files with 462 additions and 8 deletions
+1 -1
View File
@@ -233,7 +233,7 @@ Read-only browser of every volume (`src/utils/storage-volumes.ts`: bots, workspa
### Harness (the model layer, `src/harness/`)
- **Harnesses** (`src/dict/harness-dict.ts`): `text` (always on), `vision`, `transcription`, `speech`, `image`, `image_edit`, `video`, `video_edit`, `embedding`. One `harness_settings` row each (provider, pinned model or automatic, `fallback`, `enabled`, `options`). Transcription, speech, video and embedding have no automatic picks: unavailable until a model is picked.
- **Images:** `generate_image` attaches what it makes to the reply unless `attach: false` (a coordinator once asked a user to judge three versions they were never sent). It takes reference images (`references` as `[file:ID]`, `reference_media_ids` for uploads, checked like a picture source by `loadReferenceImages`). With references the call goes to `image_edit` (no automatic picks; only while its `fallback` is on does `HarnessFallbacks` hand it to `image`, both while it is unpicked or off and after its pick fails), and only models that take image input are tried (`orderImageCandidates`), never one that would drop them: the Models page's Image group says so when its pick can't take one, naming the edit model a reference call goes to, and a failure carries that note (`referenceModelNote`). One provider timeout (`HarnessError.timed_out`, the 3-minute header timeout) makes `generate_image` refuse the run's later calls instead of waiting the same span again (four attempts once took 29 minutes). OpenRouter takes references on `/images` (`input_references`), other providers as multipart on `image_edit_path` (`/images/edits`); DashScope/Model Studio hosts (`dashscope*.aliyuncs.com`, `*.maas.aliyuncs.com`) take them as the `image` extension field on `/images/generations` instead (they have no multipart edits endpoint) and always answer with URLs, ignoring `b64_json` (`isDashScopeHost` in the adapter). The Token Plan host (`token-plan.*.maas.aliyuncs.com`) has no compatible images route, so its call goes straight to Alibaba's native `multimodal-generation` on the host root (`dashscope-native-image.ts`, the documented body: `size` as `width*height`, no `prompt_extend`); a workspace host that answers 404/405 on the compatible route falls back to the same call. xAI takes no `size` (`imageRequestFields` maps one onto `aspect_ratio`).
- **Images:** `generate_image` attaches what it makes to the reply unless `attach: false` (a coordinator once asked a user to judge three versions they were never sent). It takes reference images (`references` as `[file:ID]`, `reference_media_ids` for uploads, checked like a picture source by `loadReferenceImages`). With references the call goes to `image_edit` (no automatic picks; only while its `fallback` is on does `HarnessFallbacks` hand it to `image`, both while it is unpicked or off and after its pick fails), and only models that take image input are tried (`orderImageCandidates`), never one that would drop them: the Models page's Image group says so when its pick can't take one, naming the edit model a reference call goes to, and a failure carries that note (`referenceModelNote`). One provider timeout (`HarnessError.timed_out`, the 3-minute header timeout) makes `generate_image` refuse the run's later calls instead of waiting the same span again (four attempts once took 29 minutes). OpenRouter takes references on `/images` (`input_references`), other providers as multipart on `image_edit_path` (`/images/edits`); DashScope/Model Studio hosts (`dashscope*.aliyuncs.com`, `*.maas.aliyuncs.com`) take them as the `image` extension field on `/images/generations` instead (they have no multipart edits endpoint) and always answer with URLs, ignoring `b64_json` (`isDashScopeHost` in the adapter). The Token Plan host (`token-plan.*.maas.aliyuncs.com`) has no compatible images route, so its call goes straight to Alibaba's native `multimodal-generation` on the host root (`dashscope-native-image.ts`, the documented body: `size` as `width*height`, no `prompt_extend`); a workspace host that answers 404/405 on the compatible route falls back to the same call. xAI takes no `size` (`imageRequestFields` maps one onto `aspect_ratio`). Cloudflare's AI API (`api.cloudflare.com/.../ai/v1`) has no images route either (`7000 No route for that URI`): its image models go to the native `<account>/ai/run/<model>` (`cloudflare-native-image.ts`), FLUX.2 as a multipart form with references as `input_image_<n>` (the only ones that take any, so the catalog gives only them image input), the rest as JSON, a model that refuses `width`/`height` asked again without them, the answer read from `result.image` base64 or raw image bytes.
- **Videos:** `generate_video` (`src/harness/video/`), offered only while `video` or `video_edit` has a model for the bot there (no video model is free). A video is a job at the provider: asked for at `video_path`, checked every `AppData.VideoPollIntervalMs` for at most `VideoMaxWaitMs` (below the tool timeout), downloaded from the provider itself (`<video_path>/<id>/content`, never a URL it hands back, so the key stays home). Still images go as first/last frames or references; videos to change (inline `data:` URLs, `VideoSourceMaxBytes`) go to `video_edit`'s pick, which hands over to the `video` models that take videos like `image_edit` does (`orderVideoCandidates`). OpenRouter takes JSON (`frame_images`, `input_references` with `video_url`); other providers get OpenAI's (Sora) form with one start image and no videos.
- **Transcription:** `transcribeAudio` -> `src/harness/providers/openai-compatible/transcribe.ts`. An OpenAI-compatible host gets multipart `/audio/transcriptions`; a DashScope host (`dashscope-hosts.ts`: `isDashScopeHost`, `isTokenPlanHost`, the Token Plan included) has no such route, so an ASR model there goes to `dashscope-native-transcribe.ts` (JSON `input_audio` as a `data:` URL of the bytes, `parameters.format`, at the host root's `/api/v1/services/aigc/multimodal-generation/generation`), and an async-only slug (filetrans, paraformer) is refused unretryably naming the synchronous model to pick instead. Vercel AI Gateway (`ai-gateway.vercel.sh`, `vercel-gateway-hosts.ts`) has no `/v1/audio/*` either: transcription and speech go to its own `/v4/ai/transcription-model` and `/v4/ai/speech-model` on the host root, the model in the `ai-model-id` header and the audio as base64 JSON (`vercel-gateway-transcribe.ts`, `vercel-gateway-speak.ts`). Every transcript is cleaned before it is used (`cleanTranscript` in `transcribeAudio`): speaker tokens (`<|speaker:0|>`) and bracketed sound events (`[laughs]`) that Fish Audio and ElevenLabs write are dropped, so only the words reach the composer or the bot.
- **Transforming images without a model:** `transform_image` (never "edit": that word is the `image_edit` harness) (`src/harness/image/transform-image.ts`, sharp) runs ordered steps (crop, resize, rotate, flip, grayscale, blur, sharpen, adjust, trim) on raw pixels, so the order is the bot's, after turning the source upright by EXIF. Source checked like a picture (`grabPictureSource`), never SVG. Saves a new file and shows the bot a preview so it checks the crop.
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "cobble",
"version": "0.28.24",
"version": "0.28.25",
"module": "index.ts",
"type": "module",
"private": true,
@@ -69,4 +69,22 @@ describe("cloudflareModelToCatalog", () => {
}),
).toBeNull();
});
test("only the multipart FLUX.2 image models take reference images", () => {
expect(
cloudflareModelToCatalog({
model: { name: "@cf/black-forest-labs/flux-2-klein-9b", task: { name: "Text-to-Image" } },
})?.input_modalities,
).toEqual(["text", "image"]);
expect(
cloudflareModelToCatalog({
model: { name: "@cf/leonardo/lucid-origin", task: { name: "Text-to-Image" } },
})?.input_modalities,
).toEqual(["text"]);
expect(
cloudflareModelToCatalog({
model: { name: "@cf/black-forest-labs/flux-1-schnell", task: { name: "Text-to-Image" } },
})?.input_modalities,
).toEqual(["text"]);
});
});
@@ -1,5 +1,6 @@
import guessModelModalities from "../../catalog/guess-model-modalities";
import type { HarnessCatalogModel } from "../../types";
import isCloudflareMultipartImageModel from "./cloudflare-multipart-image-model";
/**
* One row of Cloudflare's `ai/models/search`.
@@ -21,7 +22,7 @@ const TaskModalities: Record<string, Modalities> = {
"text generation": { input_modalities: ["text"], output_modalities: ["text"] },
"image-to-text": { input_modalities: ["text", "image"], output_modalities: ["text"] },
"text embeddings": { input_modalities: ["text"], output_modalities: ["embeddings"] },
"text-to-image": { input_modalities: ["text", "image"], output_modalities: ["image"] },
"text-to-image": { input_modalities: ["text"], output_modalities: ["image"] },
"automatic speech recognition": { input_modalities: ["audio"], output_modalities: ["transcription"] },
"text-to-speech": { input_modalities: ["text"], output_modalities: ["speech"] },
};
@@ -38,7 +39,9 @@ function truthy(value: unknown) {
* A Cloudflare model as the catalog keeps it, or null for a task no harness
* calls. The task decides the modalities (the id alone misreads many
* `@cf/...` names); a chat model calls tools only when Cloudflare says it
* does function calling, and reads images when the id says so.
* does function calling, and reads images when the id says so. An image
* model takes reference images only when it is one of the multipart FLUX.2
* models, so a reference call never goes to one that would drop them.
*/
export default function cloudflareModelToCatalog({
model,
@@ -55,10 +58,11 @@ export default function cloudflareModelToCatalog({
const is_chat = modalities.output_modalities.includes("text");
const context = Number(property({ model, id: "context_window" }));
const input_modalities =
is_chat && guessModelModalities({ slug }).input_modalities.includes("image")
? ["text", "image"]
: modalities.input_modalities;
const reads_images = is_chat
? guessModelModalities({ slug }).input_modalities.includes("image")
: modalities.output_modalities.includes("image") &&
isCloudflareMultipartImageModel({ slug });
const input_modalities = reads_images ? ["text", "image"] : modalities.input_modalities;
return {
slug,
@@ -0,0 +1,11 @@
/**
* Whether a Workers AI image model takes its input as a multipart form
* rather than JSON. The FLUX.2 models (`@cf/black-forest-labs/flux-2-dev`,
* `flux-2-klein-4b`, `flux-2-klein-9b`) declare only a `multipart` input and
* refuse a JSON body ("required properties at '/' are 'multipart'"); they are
* also the only ones that take reference images (`input_image_0`...). Every
* other text-to-image model there reads a JSON body and no reference.
*/
export default function isCloudflareMultipartImageModel({ slug }: { slug: string }) {
return /^@cf\/black-forest-labs\/flux-2-/i.test(slug.trim());
}
@@ -0,0 +1,148 @@
import { afterAll, beforeEach, describe, expect, mock, test } from "bun:test";
import HarnessError from "../../harness-error";
import type { HarnessCandidate } from "../../types";
/**
* Workers AI makes images only at `<account>/ai/run/<model>` (its `/ai/v1`
* has no images route), and its models differ: FLUX.2 takes a multipart form
* with references as `input_image_<n>`, the rest JSON; most answer a base64
* envelope, some the bytes themselves; flux-1-schnell refuses a size.
*/
let calls: any[] = [];
let respond: (params: any) => Promise<any>;
mock.module("./provider-request", () => ({
default: async (params: any) => {
calls.push(params);
return await respond(params);
},
}));
const { default: generateImage } = await import("./generate-image");
afterAll(() => mock.restore());
const jpeg = Uint8Array.from([0xff, 0xd8, 0xff, 0xe0, 1, 2, 3]);
const envelope = () =>
new Response(JSON.stringify({ result: { image: Buffer.from(jpeg).toString("base64") }, success: true }), {
headers: { "content-type": "application/json" },
});
const signal = new AbortController().signal;
const candidate = (slug: string): HarnessCandidate => ({
key: `18:${slug}`,
provider: {
kind: "custom",
name: "Cloudflare",
base_url: "https://api.cloudflare.com/client/v4/accounts/abc123/ai/v1",
},
model: { slug, input_modalities: ["text"], output_modalities: ["image"], supports_tools: false },
source: "pinned",
});
const reference = `data:image/png;base64,${Buffer.from("ref-bytes").toString("base64")}`;
beforeEach(() => {
calls = [];
respond = async () => envelope();
});
describe("generateImage on Cloudflare Workers AI", () => {
test("FLUX.2 posts a multipart form to the native run route", async () => {
const out = await generateImage({
candidate: candidate("@cf/black-forest-labs/flux-2-klein-9b"),
prompt: "a cube",
size: "512x768",
references: [reference],
signal,
});
expect(calls[0].base_url).toBe("https://api.cloudflare.com/client/v4/accounts/abc123/ai");
expect(calls[0].path).toBe("/run/@cf/black-forest-labs/flux-2-klein-9b");
expect(calls[0].json).toBeUndefined();
const form: FormData = calls[0].form;
expect(form.get("prompt")).toBe("a cube");
expect(form.get("width")).toBe("512");
expect(form.get("height")).toBe("768");
expect(form.get("input_image_0")).toBeInstanceOf(Blob);
expect(out.images[0]).toEqual({ data: jpeg, media_type: "image/jpeg" });
});
test("other models get JSON, and raw image bytes are read as they are", async () => {
respond = async () => new Response(jpeg, { headers: { "content-type": "image/jpeg" } });
const out = await generateImage({
candidate: candidate("@cf/leonardo/phoenix-1.0"),
prompt: "a cube",
size: "1024x1024",
signal,
});
expect(calls[0].json).toEqual({ prompt: "a cube", width: 1024, height: 1024 });
expect(out.images[0]).toEqual({ data: jpeg, media_type: "image/jpeg" });
});
test("a model that refuses the size is asked again without it, and remembered", async () => {
respond = async (params) => {
if (params.json.width) {
throw new HarnessError({
message:
"Cloudflare: AiError: Bad input: Error: Additional or unevaluated properties '/width, /height' at '/' not allowed",
status: 400,
retryable: false,
});
}
return envelope();
};
const model = candidate("@cf/black-forest-labs/flux-1-schnell");
await generateImage({ candidate: model, prompt: "a cube", size: "512x512", signal });
expect(calls.map((call) => call.json)).toEqual([
{ prompt: "a cube", width: 512, height: 512 },
{ prompt: "a cube" },
]);
calls = [];
await generateImage({ candidate: model, prompt: "a cube", size: "512x512", signal });
expect(calls.map((call) => call.json)).toEqual([{ prompt: "a cube" }]);
});
test("n images are n calls", async () => {
const out = await generateImage({
candidate: candidate("@cf/leonardo/lucid-origin"),
prompt: "a cube",
n: 2,
signal,
});
expect(calls).toHaveLength(2);
expect(out.images).toHaveLength(2);
});
test("references to a model that takes none are refused, not dropped", async () => {
const failure = await generateImage({
candidate: candidate("@cf/leonardo/lucid-origin"),
prompt: "a cube",
references: [reference],
signal,
}).catch((error) => error);
expect(failure).toBeInstanceOf(HarnessError);
expect(failure.retryable).toBe(false);
expect(calls).toHaveLength(0);
});
test("an answer with no image is a retryable failure", async () => {
respond = async () => new Response(JSON.stringify({ result: {} }), { headers: { "content-type": "application/json" } });
const failure = await generateImage({
candidate: candidate("@cf/leonardo/lucid-origin"),
prompt: "a cube",
signal,
}).catch((error) => error);
expect(failure).toBeInstanceOf(HarnessError);
expect(failure.retryable).toBe(true);
});
});
@@ -0,0 +1,254 @@
import { AppData } from "@/src/data/app-data";
import HarnessError from "../../harness-error";
import type { HarnessCandidate, HarnessImageOutput } from "../../types";
import isCloudflareMultipartImageModel from "./cloudflare-multipart-image-model";
import providerRequest from "./provider-request";
import referenceBlob from "./reference-blob";
type Params = {
candidate: HarnessCandidate;
/**
* `https://api.cloudflare.com/client/v4/accounts/<account>/ai`.
*/
root: string;
prompt: string;
n?: number;
size?: string;
references?: string[];
signal: AbortSignal;
};
const PixelSize = /^(\d+)\s*[x*]\s*(\d+)$/i;
const MaxImagesPerCall = 4;
/**
* Models that refused `width`/`height` in this process
* (`@cf/black-forest-labs/flux-1-schnell` answers "Additional or unevaluated
* properties '/width, /height' at '/' not allowed"), so their next call
* leaves the size out instead of spending a refusal on it again.
*/
const NoSizeModels = new Set<string>();
/**
* Image generation on Cloudflare's Workers AI. Its OpenAI-compatible
* `/ai/v1` has no images route (`7000 No route for that URI`), so the call
* goes to the native `POST <account>/ai/run/<model>`, which differs by model:
* the FLUX.2 models take a multipart form (references as `input_image_0`...),
* the rest a JSON body; most answer `{ result: { image: <base64> } }`, some
* (`@cf/leonardo/phoenix-1.0`) the image bytes themselves. Each call makes
* one image, so `n` is that many calls.
*/
export default async function generateImageCloudflare({
candidate,
root,
prompt,
n,
size,
references = [],
signal,
}: Params): Promise<{ images: HarnessImageOutput[] }> {
const { provider, model } = candidate;
const name = provider.name || "Cloudflare";
const multipart = isCloudflareMultipartImageModel({ slug: model.slug });
if (references.length && !multipart) {
throw new HarnessError({
message: `${name}: ${model.slug} takes no reference images on Workers AI. Pick a FLUX.2 model (@cf/black-forest-labs/flux-2-...) for image editing in Settings > Models.`,
retryable: false,
candidate_key: candidate.key,
});
}
const count = Math.min(Math.max(Math.floor(n || 1), 1), MaxImagesPerCall);
const images: HarnessImageOutput[] = [];
for (let index = 0; index < count; index++) {
images.push(
await runImageModel({ candidate, root, prompt, size, references, multipart, signal }),
);
}
return { images };
}
type RunParams = {
candidate: HarnessCandidate;
root: string;
prompt: string;
size?: string;
references: string[];
multipart: boolean;
signal: AbortSignal;
};
/**
* One `ai/run` call, retried once without the size when the model's schema
* refuses `width`/`height`.
*/
async function runImageModel(params: RunParams): Promise<HarnessImageOutput> {
const { candidate } = params;
const pixels = NoSizeModels.has(candidate.model.slug) ? undefined : pixelSize(params);
try {
return await requestImage({ ...params, pixels });
} catch (error: unknown) {
if (!pixels || !refusedSize({ error })) throw error;
NoSizeModels.add(candidate.model.slug);
return await requestImage({ ...params, pixels: undefined });
}
}
async function requestImage({
candidate,
root,
prompt,
references,
multipart,
signal,
pixels,
}: RunParams & { pixels?: { width: number; height: number } }): Promise<HarnessImageOutput> {
const { provider, model } = candidate;
const path = `/run/${model.slug}`;
const res = multipart
? await providerRequest({
provider,
base_url: root,
path,
form: await imageForm({ prompt, pixels, references, signal }),
signal,
candidate_key: candidate.key,
})
: await providerRequest({
provider,
base_url: root,
path,
json: { prompt, ...(pixels || {}) },
signal,
candidate_key: candidate.key,
});
return await readImage({ res, candidate });
}
/**
* The FLUX.2 form: the prompt, the size and each reference as
* `input_image_<n>` (a plain `image` field is ignored, not refused).
*/
async function imageForm({
prompt,
pixels,
references,
signal,
}: {
prompt: string;
pixels?: { width: number; height: number };
references: string[];
signal: AbortSignal;
}) {
const form = new FormData();
form.append("prompt", prompt);
if (pixels) {
form.append("width", String(pixels.width));
form.append("height", String(pixels.height));
}
const kept = references.slice(0, AppData.ImageReferenceMaxCount);
for (let index = 0; index < kept.length; index++) {
const { blob, ext } = await referenceBlob({ url: kept[index]!, signal });
form.append(`input_image_${index}`, blob, `reference-${index + 1}.${ext}`);
}
return form;
}
/**
* The picture from either answer: the bytes themselves under an `image/*`
* content type, or the JSON envelope's base64 `result.image`.
*/
async function readImage({
res,
candidate,
}: {
res: Response;
candidate: HarnessCandidate;
}): Promise<HarnessImageOutput> {
const name = candidate.provider.name || "Cloudflare";
const type = (res.headers.get("content-type") || "").split(";")[0]!.trim().toLowerCase();
if (type.startsWith("image/")) {
const data = new Uint8Array(await res.arrayBuffer());
if (data.length > AppData.HarnessImageDownloadMaxBytes) {
throw new HarnessError({
message: `${name}: the image ${candidate.model.slug} sent is larger than the app keeps.`,
retryable: false,
candidate_key: candidate.key,
});
}
if (data.length) return { data, media_type: type };
} else {
const json: any = await res.json().catch(() => null);
const encoded =
typeof json?.result?.image == "string"
? json.result.image
: typeof json?.result == "string"
? json.result
: "";
if (encoded) {
const data = Uint8Array.from(Buffer.from(encoded, "base64"));
return { data, media_type: sniffImageType({ data }) };
}
}
throw new HarnessError({
message: `${name}: no image came back from ${candidate.model.slug}.`,
retryable: true,
candidate_key: candidate.key,
});
}
function pixelSize({ size }: { size?: string }) {
const pair = size?.trim().match(PixelSize);
if (!pair) return undefined;
const width = Number(pair[1]);
const height = Number(pair[2]);
return width > 0 && height > 0 ? { width, height } : undefined;
}
/**
* Workers AI's schema refusal of the size fields, e.g. `5006 Bad input:
* Additional or unevaluated properties '/width, /height' at '/' not allowed`.
*/
function refusedSize({ error }: { error: unknown }) {
if (!(error instanceof HarnessError) || error.status != 400) return false;
const refused = error.message.match(/unevaluated properties '([^']*)'/i)?.[1] || "";
return /\/(width|height)\b/.test(refused);
}
/**
* The image type from its first bytes: the base64 answer names none, and the
* FLUX models send JPEG.
*/
function sniffImageType({ data }: { data: Uint8Array }) {
if (data[0] == 0xff && data[1] == 0xd8) return "image/jpeg";
if (data[0] == 0x89 && data[1] == 0x50 && data[2] == 0x4e && data[3] == 0x47) return "image/png";
if (data[0] == 0x52 && data[1] == 0x49 && data[2] == 0x46 && data[3] == 0x46 && data[8] == 0x57)
return "image/webp";
return "image/png";
}
@@ -2,6 +2,8 @@ import { AppData } from "@/src/data/app-data";
import HarnessError from "../../harness-error";
import type { HarnessAdapter, HarnessCandidate, HarnessImageOutput } from "../../types";
import grabProviderPreset from "../grab-provider-preset";
import cloudflareAiRoot from "./cloudflare-ai-hosts";
import generateImageCloudflare from "./cloudflare-native-image";
import { isDashScopeHost, isTokenPlanHost } from "./dashscope-hosts";
import downloadProviderFile from "./download-provider-file";
import generateImageNative from "./dashscope-native-image";
@@ -23,6 +25,9 @@ import referenceBlob from "./reference-blob";
* `multimodal-generation` call at the host root, so that call goes there
* directly. A workspace Model Studio host that answers 404 or 405 on the
* compatible route falls back to the same native call.
*
* Cloudflare's AI API has no images route under `/ai/v1` either: its image
* models answer only at the native `<account>/ai/run/<model>`.
*/
const generateImage: HarnessAdapter["generateImage"] = async ({
candidate,
@@ -35,6 +40,20 @@ const generateImage: HarnessAdapter["generateImage"] = async ({
const { provider } = candidate;
const preset = grabProviderPreset({ kind: provider.kind });
const cloudflare_root = cloudflareAiRoot({ base_url: provider.base_url });
if (cloudflare_root) {
return await generateImageCloudflare({
candidate,
root: cloudflare_root,
prompt,
n,
size,
references,
signal,
});
}
if (isTokenPlanHost({ base_url: provider.base_url })) {
return await generateImageNative({ candidate, prompt, n, size, references, signal });
}