Call Token Plan image models on their native route, and stop sending xAI a size it rejects

Token Plan has no compatible images endpoint, and a native body with prompt_extend closed the socket before any status. Classify grok-imagine-image and wan image ids as image models, and map an xAI size onto aspect_ratio.
This commit is contained in:
2026-11-19 07:47:17 +01:00
parent b7877ad3c7
commit 2cad6cfd08
8 changed files with 186 additions and 16 deletions
+1 -1
View File
@@ -222,7 +222,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. 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). A DashScope/Model Studio host that answers 404/405 there has no compatible images route at all (the Token Plan host serves chat and the native API only), so the call falls back to Alibaba's native `multimodal-generation` on the host root (`dashscope-native-image.ts`) instead of failing the pick.
- **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. 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`).
- **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.
- **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.
- **Providers** (`src/dict/harness-provider-dict.ts`): OpenRouter default plus OpenAI-compatible ones; one adapter today (`src/harness/providers/openai-compatible/`). Keys encrypted in private `harness_providers`, falling back to the preset env.
@@ -19,8 +19,14 @@ describe("guessModelModalities", () => {
expect(outputs("sora-2-pro")).toEqual(["video"]);
expect(outputs("veo-3.1-generate-preview")).toEqual(["video"]);
expect(outputs("grok-imagine-video")).toEqual(["video"]);
expect(outputs("grok-imagine-video-1.5")).toEqual(["video"]);
expect(outputs("imagen-4.0-generate-001")).toEqual(["image"]);
expect(outputs("grok-imagine-image")).not.toEqual(["video"]);
expect(outputs("grok-imagine-image")).toEqual(["image"]);
expect(outputs("grok-imagine-image-2.0")).toEqual(["image"]);
expect(outputs("wan2.7-image")).toEqual(["image"]);
expect(outputs("wan2.7-image-pro")).toEqual(["image"]);
expect(outputs("wan3.0-video")).toEqual(["video"]);
expect(outputs("wan2.1-t2v-14b")).toEqual(["video"]);
expect(guessModelModalities({ slug: "sora-2" }).input_modalities).toEqual([
"text",
"image",
@@ -28,6 +34,14 @@ describe("guessModelModalities", () => {
expect(
guessModelModalities({ slug: "flux-video-edit" }).input_modalities,
).toEqual(["text", "image", "video"]);
expect(guessModelModalities({ slug: "grok-imagine-image" })).toEqual({
input_modalities: ["text", "image"],
output_modalities: ["image"],
supports_tools: false,
});
expect(
guessModelModalities({ slug: "wan3.0-video" }).input_modalities,
).toEqual(["text", "image", "video"]);
});
test("takes everything else for a tool-calling chat model", () => {
+10 -3
View File
@@ -11,12 +11,19 @@ type Guess = Pick<
const Transcription = /whisper|transcri|(?:^|[-_/])(stt|asr)(?=$|[-_:.])|scribe/i;
const Speech = /(?:^|[-_/])tts(?=$|[-_:.])|speech|voice/i;
const ImageOut = /dall-e|gpt-image|imagen|flux|stable-diffusion|sdxl|image-gen|qwen-image|kontext|seedream|image-edit/i;
/**
* Image models, including families whose video siblings are classified
* first (`grok-imagine-image` beside `grok-imagine-video`, `wan2.7-image`
* beside `wan3.0-video`).
*/
const ImageOut = /dall-e|gpt-image|imagen|flux|stable-diffusion|sdxl|image-gen|qwen-image|grok-imagine-image|(?:^|[-_/])wan[\d.]*-image|kontext|seedream|image-edit/i;
/**
* Video models. Checked before images: some share a family name
* (`grok-imagine-video`, `flux-video-edit`).
* (`grok-imagine-video`, `flux-video-edit`). A Wan image model
* (`wan2.7-image`) is left for the image check; a version number alone
* is not enough, since that is how those image ids are spelled.
*/
const VideoOut = /sora|(?:^|[-_/])veo(?=$|[-_:.\d])|kling|seedance|hailuo|(?:^|[-_/])wan-?\d|runway|aleph|video/i;
const VideoOut = /sora|(?:^|[-_/])veo(?=$|[-_:.\d])|kling|seedance|hailuo|(?:^|[-_/])wan(?![\d.-]*image)|runway|aleph|video/i;
/**
* Video models that take a video to change.
*/
@@ -55,10 +55,15 @@ export default async function generateImageNative({
},
],
},
/**
* Only the fields Token Plan's own sample sends. `prompt_extend`
* is their default already, and sending it (with the thinking
* pass it turns on) is what closed the socket before any status
* on the Token Plan host.
*/
parameters: {
...(n ? { n } : {}),
...(native_size ? { size: native_size } : {}),
prompt_extend: true,
watermark: false,
},
},
@@ -42,6 +42,14 @@ const base: HarnessCandidate = {
model: { slug: "qwen-image-3.0-pro", input_modalities: ["text", "image"], output_modalities: ["image"], supports_tools: false },
source: "pinned",
};
const token_plan: HarnessCandidate = {
...base,
provider: {
...base.provider,
name: "Alibaba Cloud Token Plan",
base_url: "https://token-plan.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
},
};
const maas: HarnessCandidate = {
...base,
provider: { ...base.provider, base_url: "https://ws.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1" },
@@ -110,9 +118,35 @@ describe("generateImage on DashScope/Model Studio hosts", () => {
/**
* The Token Plan host serves chat and the native API, never
* `/compatible-mode/v1/images/generations`, so the pick that worked on the
* workspace host 404s there and the picture has to come from the native call.
* `/compatible-mode/v1/images/generations`, so its call goes straight to the
* native route. A workspace host that 404s there falls back the same way.
*/
describe("generateImage on the Token Plan host", () => {
test("goes straight to the native call and sends only the documented fields", async () => {
respond = async () => ({
json: async () => ({
output: { choices: [{ message: { content: [{ image: "https://cdn.example.com/native.png" }] } }] },
}),
});
fetchImpl = async () => new Response(new Uint8Array([1, 2]), { status: 200, headers: { "content-type": "image/png" } });
const result = await generateImage({
candidate: token_plan,
prompt: "a cat",
size: "1024x1024",
n: 1,
signal,
});
expect(calls.length).toBe(1);
expect(calls[0].path).toBe("/api/v1/services/aigc/multimodal-generation/generation");
expect(calls[0].base_url).toBe("https://token-plan.ap-southeast-1.maas.aliyuncs.com");
expect(calls[0].json.parameters).toEqual({ size: "1024*1024", n: 1, watermark: false });
expect(calls[0].json.parameters.prompt_extend).toBeUndefined();
expect(result.images[0]?.data).toEqual(new Uint8Array([1, 2]));
});
});
describe("generateImage when the compatible images route is missing", () => {
const native = (overrides: any = {}) => ({
output: {
@@ -4,6 +4,7 @@ import type { HarnessAdapter, HarnessCandidate, HarnessImageOutput } from "../..
import grabProviderPreset from "../grab-provider-preset";
import downloadProviderFile from "./download-provider-file";
import generateImageNative from "./dashscope-native-image";
import imageRequestFields from "./image-request-fields";
import providerRequest from "./provider-request";
import referenceBlob from "./reference-blob";
@@ -16,10 +17,11 @@ import referenceBlob from "./reference-blob";
* `image_edit_path` (`/images/edits`). Images come back as base64, or as
* URLs that are downloaded here (DashScope only ever returns URLs).
*
* A DashScope/Model Studio host with no OpenAI-compatible images route (the
* Token Plan host answers 404 with an empty body) falls back to Alibaba's
* native `multimodal-generation` call on the host root, so the same model
* pick works either way.
* The Token Plan host (`token-plan.*.maas.aliyuncs.com`) has no compatible
* images route. Its image models are served by Alibaba's native
* `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.
*/
const generateImage: HarnessAdapter["generateImage"] = async ({
candidate,
@@ -32,15 +34,18 @@ const generateImage: HarnessAdapter["generateImage"] = async ({
const { provider } = candidate;
const preset = grabProviderPreset({ kind: provider.kind });
if (isTokenPlanHost({ base_url: provider.base_url })) {
return await generateImageNative({ candidate, prompt, n, size, references, signal });
}
let res: Response;
try {
res = await requestCompatibleImage({ candidate, prompt, n, size, references, signal });
} catch (error: unknown) {
/**
* A DashScope/Model Studio host that answers 404 or 405 on the
* compatible images route has no route there at all (the Token Plan
* host serves chat and the native API only), so the model pick is
* A workspace Model Studio host that answers 404 or 405 on the
* compatible images route has no route there, so the model pick is
* fine and the native call is where the picture comes from.
*/
const missing_route =
@@ -125,6 +130,7 @@ async function requestCompatibleImage({
const is_openrouter = provider.kind == "openrouter";
const dashscope = isDashScopeHost({ base_url: provider.base_url });
const edits = Boolean(references?.length) && !is_openrouter && !dashscope;
const fields = imageRequestFields({ provider_kind: provider.kind, size });
if (edits) {
return await providerRequest({
@@ -150,7 +156,7 @@ async function requestCompatibleImage({
model: model.slug,
prompt,
...(n ? { n } : {}),
...(size ? { size } : {}),
...fields,
...(is_openrouter && references?.length
? {
input_references: references.map((url) => ({
@@ -215,6 +221,21 @@ async function editForm({ model, prompt, n, size, references, signal }: EditForm
* workspace `maas` hosts both count; a custom provider pointed elsewhere
* keeps the standard behaviour.
*/
/**
* Alibaba's Token Plan host. Its image models are served only by the native
* call; the compatible `/images/generations` path 404s, and trying it first
* benches the model before the picture is made.
*/
export function isTokenPlanHost({ base_url }: { base_url?: string | null }) {
if (!base_url) return false;
try {
return new URL(base_url).hostname.startsWith("token-plan.");
} catch {
return false;
}
}
function isDashScopeHost({ base_url }: { base_url?: string | null }) {
if (!base_url) return false;
@@ -0,0 +1,30 @@
import { describe, expect, test } from "bun:test";
import imageRequestFields from "./image-request-fields";
describe("imageRequestFields", () => {
test("keeps a pixel size for providers that take one", () => {
expect(imageRequestFields({ provider_kind: "openai", size: "1024x1024" })).toEqual({
size: "1024x1024",
});
expect(imageRequestFields({ provider_kind: "custom", size: "1024x1024" })).toEqual({
size: "1024x1024",
});
});
test("maps xAI's size onto an aspect ratio and never sends size", () => {
expect(imageRequestFields({ provider_kind: "xai", size: "1024x1024" })).toEqual({
aspect_ratio: "1:1",
});
expect(imageRequestFields({ provider_kind: "xai", size: "1920x1080" })).toEqual({
aspect_ratio: "16:9",
});
expect(imageRequestFields({ provider_kind: "xai", size: "1080x1920" })).toEqual({
aspect_ratio: "9:16",
});
});
test("leaves a size xAI has no ratio for out of the call", () => {
expect(imageRequestFields({ provider_kind: "xai", size: "123x456" })).toEqual({});
expect(imageRequestFields({ provider_kind: "xai" })).toEqual({});
});
});
@@ -0,0 +1,59 @@
/**
* How a provider's image call takes a size the tool named as `1024x1024`.
* Each provider gets only the field it documents: OpenAI's `size`, xAI's
* `aspect_ratio` (it rejects `size` outright), Alibaba's `width*height`.
*/
export type ImageRequestFields = {
size?: string;
aspect_ratio?: string;
};
type Params = {
provider_kind: string;
size?: string;
};
const PixelSize = /^(\d+)\s*[x*]\s*(\d+)$/i;
export default function imageRequestFields({ provider_kind, size }: Params): ImageRequestFields {
if (!size?.trim()) return {};
if (provider_kind == "xai") {
const aspect_ratio = xaiAspectRatio({ size });
return aspect_ratio ? { aspect_ratio } : {};
}
return { size };
}
/**
* xAI takes a named ratio, never a pixel size. An exact pair maps; a size
* it has no ratio for is left out, which is better than a 400.
*/
function xaiAspectRatio({ size }: { size: string }): string | undefined {
const pair = size.trim().match(PixelSize);
if (!pair) return undefined;
const width = Number(pair[1]);
const height = Number(pair[2]);
if (!width || !height) return undefined;
const ratio = width / height;
const known: [number, string][] = [
[1, "1:1"],
[16 / 9, "16:9"],
[9 / 16, "9:16"],
[4 / 3, "4:3"],
[3 / 4, "3:4"],
[3 / 2, "3:2"],
[2 / 3, "2:3"],
[21 / 9, "21:9"],
[9 / 21, "9:21"],
];
const match = known.find(([value]) => Math.abs(ratio - value) < 0.02);
return match?.[1];
}