Skip to content

Commit 09f24d4

Browse files
committed
fix(mistral): keep replayed images within each model's per-request cap
Mistral rejects requests that carry more images than a model accepts, counting the whole replayed history: most vision models refuse a ninth image with HTTP 400, and DeepSeek V4.1 Flash answers an opaque HTTP 503 (code 3800) past 20. A screenshot-heavy session then fails on every turn. First-party Mistral Chat requests now keep the newest images within the model's cap and replace older ones with a text note in the outbound body only. The cap is the operator's modelCapabilities.<id>.mistralMaxImages, then a measured per-model cap, then the documented 8.
1 parent 0a30c55 commit 09f24d4

14 files changed

Lines changed: 255 additions & 18 deletions

File tree

‎docs-site/src/content/docs/reference/configuration/providers.md‎

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,24 @@ have a 60-second upload deadline, a 128 MiB input cap and at most two simultaneo
3333
provider pacing/concurrency still applies. Oversized text or unconvertible images still need
3434
compaction; this transport repair does not extend the model's context window.
3535

36+
## Mistral: images per request
37+
38+
Mistral caps how many images one API request may carry, counting every turn of the replayed
39+
history. Its [vision guide](https://docs.mistral.ai/capabilities/vision/) documents 8, and most
40+
Mistral vision models refuse a ninth with HTTP 400. Some models accept more: measured caps are
41+
20 for `deepseek-v4-1-flash-1017` (which answers an opaque HTTP 503, code `3800`, past it), 100
42+
for `mistral-large-4`, and no refusal through 256 for `zai-glm-5-3-flash`. Without pruning, a long
43+
session with many screenshots fails on every turn while its token context still has room.
44+
45+
For the first-party Chat destination (`https://api.mistral.ai/v1/chat/completions`), opencodex
46+
keeps the newest images within the cap and replaces older ones with a short text note in the
47+
outbound request only; client history, token usage and compaction stay unchanged. Images
48+
promoted from tool results count like any other. Models with a measured cap use it; any other
49+
model uses 8. Declare a model's own cap with
50+
`modelCapabilities: { "mistral-small-2603": { mistralMaxImages: 8 } }` (an integer from 1 to
51+
1000); the declaration outranks the measured cap, and PATCH `null` on the axis removes it. Nothing is uploaded
52+
or persisted, and other destinations are unchanged.
53+
3654
## GPT-6.1 Terra
3755

3856
[GPT-6.1 Terra](https://openai.com/index/introducing-gpt-6-1-terra/) was released on October 26, 2026 as the successor to GPT-5.6 Terra. `gpt-6.1-terra` is available alongside `gpt-5.6-terra`; no default model or sub-agent roster changes. GitHub Copilot uses Responses; OpenRouter lists `openai/gpt-6.1-terra` with 1,050,000 context and $1.00 input / $5.00 output per 1M tokens.
@@ -1805,7 +1823,7 @@ contracts.
18051823

18061824
### Per-model capability declarations
18071825

1808-
`modelCapabilities` stores explicit declarations keyed by exact upstream model ID. IDs preserve case and must not contain surrounding whitespace. Each entry may contain `inputModalities` (`text`, `image`, `audio`, `video`), `contextTier` (`default`, `long_context`), `video.processing` (`static`, `agentic`) and `deepseekImageFiles` (`boolean`; see [DeepSeek image bytes](#deepseek-tokens-versus-image-bytes)). These are operator declarations, not proof of provider support. Context-tier and video fields currently record intent only and do not activate upstream behavior or increase catalog windows.
1826+
`modelCapabilities` stores explicit declarations keyed by exact upstream model ID. IDs preserve case and must not contain surrounding whitespace. Each entry may contain `inputModalities` (`text`, `image`, `audio`, `video`), `contextTier` (`default`, `long_context`), `video.processing` (`static`, `agentic`) `deepseekImageFiles` (`boolean`; see [DeepSeek image bytes](#deepseek-tokens-versus-image-bytes)) and `mistralMaxImages` (integer 1–1000; see [Mistral images per request](#mistral-images-per-request)). These are operator declarations, not proof of provider support. Context-tier and video fields currently record intent only and do not activate upstream behavior or increase catalog windows.
18091827

18101828
The raw provider editor and provider API expose this map. POST/PUT replace an explicitly supplied map and reject null entries. PATCH merges individual axes; null clears a map, model, axis or video processing value, while `{}` makes no change. Omitted provider overwrites preserve the existing map. Malformed hand-edited files retain valid independent axes and treat malformed explicit input modalities as text-only, with a diagnostic.
18111829

‎scripts/test-layout/layout-providers.json‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,5 +5,6 @@
55
"xai-loaded-tool-provenance.test.ts": "providers/xai",
66
"free-directory-runcrate.test.ts": "providers",
77
"cc-switch-import.test.ts": "providers",
8-
"kiro-completion-with-real-tools.test.ts": "providers/kiro"
8+
"kiro-completion-with-real-tools.test.ts": "providers/kiro",
9+
"mistral-image-limit.test.ts": "providers"
910
}

‎src/config/provider-validation.ts‎

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -478,7 +478,7 @@ export function modelCapabilitiesConfigError(value: unknown, allowTombstones = f
478478
if (allowTombstones && row === null) continue;
479479
if (!capabilityRecord(row)) return "modelCapabilities rows must be plain objects";
480480
for (const [axis, declaration] of Object.entries(row)) {
481-
if (!["inputModalities", "contextTier", "video", "deepseekImageFiles", "supportsReasoning", "supportsThinkingToggle", "supportsReasoningEffort", "defaultThinkingEnabled"].includes(axis)) return "modelCapabilities contains an unknown axis";
481+
if (!["inputModalities", "contextTier", "video", "deepseekImageFiles", "mistralMaxImages", "supportsReasoning", "supportsThinkingToggle", "supportsReasoningEffort", "defaultThinkingEnabled"].includes(axis)) return "modelCapabilities contains an unknown axis";
482482
if (allowTombstones && declaration === null) continue;
483483
if (axis === "inputModalities") {
484484
if (!Array.isArray(declaration) || declaration.length === 0
@@ -487,6 +487,10 @@ export function modelCapabilitiesConfigError(value: unknown, allowTombstones = f
487487
}
488488
} else if (axis === "contextTier") {
489489
if (declaration !== "default" && declaration !== "long_context") return "modelCapabilities contextTier must be default or long_context";
490+
} else if (axis === "mistralMaxImages") {
491+
if (typeof declaration !== "number" || !Number.isSafeInteger(declaration) || declaration < 1 || declaration > 1000) {
492+
return "modelCapabilities mistralMaxImages must be an integer from 1 to 1000";
493+
}
490494
} else if (["deepseekImageFiles", "supportsReasoning", "supportsThinkingToggle", "supportsReasoningEffort", "defaultThinkingEnabled"].includes(axis)) {
491495
if (typeof declaration !== "boolean") return `modelCapabilities ${axis} must be a boolean`;
492496
} else {
@@ -521,6 +525,9 @@ export function mergeModelCapabilities(
521525
} else if (axis === "deepseekImageFiles") {
522526
if (value === null) delete row.deepseekImageFiles;
523527
else row.deepseekImageFiles = value as boolean;
528+
} else if (axis === "mistralMaxImages") {
529+
if (value === null) delete row.mistralMaxImages;
530+
else row.mistralMaxImages = value as number;
524531
} else if (axis === "supportsReasoning" || axis === "supportsThinkingToggle" || axis === "supportsReasoningEffort" || axis === "defaultThinkingEnabled") {
525532
if (value === null) delete row[axis];
526533
else row[axis] = value as boolean;
@@ -551,7 +558,7 @@ export function sanitizeModelCapabilitiesForLoad(value: unknown): Record<string,
551558
for (const [id, raw] of Object.entries(value).slice(0, MODEL_DISCOVERY_MAX_MODELS)) {
552559
if (!capabilityRecord(raw) || !isValidModelDiscoveryModelId(id) || ["__proto__", "prototype", "constructor"].includes(id)) continue;
553560
const row: Record<string, unknown> = {};
554-
for (const axis of ["inputModalities", "contextTier", "video", "deepseekImageFiles", "supportsReasoning", "supportsThinkingToggle", "supportsReasoningEffort", "defaultThinkingEnabled"] as const) {
561+
for (const axis of ["inputModalities", "contextTier", "video", "deepseekImageFiles", "mistralMaxImages", "supportsReasoning", "supportsThinkingToggle", "supportsReasoningEffort", "defaultThinkingEnabled"] as const) {
555562
if (!Object.hasOwn(raw, axis)) continue;
556563
const declaration = raw[axis];
557564
if (modelCapabilitiesConfigError({ [id]: { [axis]: declaration } }) === null) row[axis] = declaration;
Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
import type { TranslatorBudget } from "../../lib/translator-budget";
2+
import type { AdapterRequest } from "../../adapters/base";
3+
4+
// https://docs.mistral.ai/capabilities/vision/ documents 8 images per API request, and most
5+
// Mistral vision models refuse a ninth with HTTP 400 ("Total number of images exceeds the maximum
6+
// allowed of 8"). Some models accept more; DeepSeek V4.1 Flash answers an opaque HTTP 503 (code
7+
// 3800) past its cap. Operators declare a model's cap with `modelCapabilities.<id>.mistralMaxImages`.
8+
export const MISTRAL_DEFAULT_MAX_IMAGES = 8;
9+
/**
10+
* Caps measured on api.mistral.ai (2026-11-04) for models above the documented 8: the largest
11+
* accepted count before refusal, or for GLM the largest count tried without one.
12+
*/
13+
const MEASURED_MAX_IMAGES: Readonly<Record<string, number>> = {
14+
"deepseek-v4-1-flash-1017": 20,
15+
"mistral-large-4": 100,
16+
"mistral-large-4-0": 100,
17+
"zai-glm-5-3-flash": 256,
18+
};
19+
20+
/** The operator's declaration, then a measured cap, then the documented default. */
21+
export function mistralMaxImages(model: string, declared?: number): number {
22+
return declared ?? (Object.hasOwn(MEASURED_MAX_IMAGES, model) ? MEASURED_MAX_IMAGES[model]! : MISTRAL_DEFAULT_MAX_IMAGES);
23+
}
24+
25+
const NOTE = "[image omitted: Mistral accepts a limited number of images per request; older images were dropped]";
26+
27+
/** Narrow parsed JSON objects without treating arrays as image or message records. */
28+
function record(value: unknown): value is Record<string, unknown> {
29+
return value !== null && typeof value === "object" && !Array.isArray(value);
30+
}
31+
32+
/** Only the first-party Chat destination, never a similarly named gateway. */
33+
export function isMistralChatRequest(request: AdapterRequest): boolean {
34+
try {
35+
const url = new URL(request.url);
36+
return url.origin === "https://api.mistral.ai" && url.pathname === "/v1/chat/completions" && request.method === "POST";
37+
} catch { return false; }
38+
}
39+
40+
/**
41+
* Keep the newest images a Mistral request may carry and replace older ones with a text note,
42+
* across every message (including promoted tool-result images). The client history stays intact;
43+
* only this outbound body is pruned. Returns undefined when nothing needs to change.
44+
*/
45+
export function mistralImageLimitBody(
46+
request: AdapterRequest,
47+
options: { maxImages: number; budget?: TranslatorBudget },
48+
): string | undefined {
49+
if (!isMistralChatRequest(request)) return undefined;
50+
// Cheap bound before parsing: a request with no more image parts than the cap is never rewritten.
51+
let occurrences = 0;
52+
for (let at = request.body.indexOf('"image_url"'); at !== -1; at = request.body.indexOf('"image_url"', at + 1)) {
53+
if (++occurrences > options.maxImages) break;
54+
}
55+
if (occurrences <= options.maxImages) return undefined;
56+
const requestBytes = Buffer.byteLength(request.body, "utf8");
57+
const releaseCopy = options.budget?.observeAcceptedRequestCopy(requestBytes * 2);
58+
try {
59+
const body: unknown = JSON.parse(request.body);
60+
if (!record(body) || !Array.isArray(body.messages)) return undefined;
61+
const images: Array<{ parts: unknown[]; index: number }> = [];
62+
for (const message of body.messages) {
63+
if (!record(message) || !Array.isArray(message.content)) continue;
64+
message.content.forEach((part, index) => {
65+
if (record(part) && part.type === "image_url") images.push({ parts: message.content as unknown[], index });
66+
});
67+
}
68+
const excess = images.length - options.maxImages;
69+
if (excess <= 0) return undefined;
70+
for (const { parts, index } of images.slice(0, excess)) parts[index] = { type: "text", text: NOTE };
71+
const releaseSerialization = options.budget?.observeExternallyCapped("passthrough_serialization", requestBytes);
72+
try { return JSON.stringify(body); } finally { releaseSerialization?.(); }
73+
} finally { releaseCopy?.(); }
74+
}

‎src/server/responses/request-transport.ts‎

Lines changed: 21 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,7 @@ import { codexWsExecutorBinding, fetchWithHeaderTimeout, physicalSendObserverIni
8585
import { resolveConnectTimeoutMs } from "../../stall-timeout";
8686
import { isLocalUpstream } from "../../lib/local-upstream";
8787
import { deepSeekImageFileBody, needsDeepSeekImageFiles } from "./deepseek-image-files";
88+
import { isMistralChatRequest, mistralImageLimitBody, mistralMaxImages } from "./mistral-image-limit";
8889
import type { ProviderFetchOptions } from "./fetch-helpers";
8990
import { captureConfigGeneration } from "../../lib/state-store-sweeper";
9091
import { recordAnthropicAccountQuotaFromHeadersForInstance, hasPassiveAccountQuota } from "../../providers/quota";
@@ -643,6 +644,17 @@ export async function prepareResponsesTransport(
643644
const fileConsentGeneration = captureConfigGeneration();
644645
resolved.buildRequest = async (requestParsed, incoming) => {
645646
const request = await build(requestParsed, incoming);
647+
/** Swap in a rewritten body, keeping its byte observation and dropping a stale length. */
648+
const replaceBody = (body: string): void => {
649+
request.releaseBodyObservation?.();
650+
request.body = body;
651+
const headers = new Headers(request.headers);
652+
headers.delete("content-length");
653+
request.headers = Object.fromEntries(headers);
654+
request.releaseBodyObservation = incoming.translatorBudget.observeExternallyCapped(
655+
"passthrough_serialization", Buffer.byteLength(body, "utf8"),
656+
);
657+
};
646658
// Capture at adapter creation, never from mutable serving state after an await.
647659
if (binding) requestBindings.set(request, binding);
648660
const allowedImageFileModels = fileProvider.modelCapabilities
@@ -681,18 +693,17 @@ export async function prepareResponsesTransport(
681693
uploadSignal, {
682694
allowedModels: allowedImageFileModels, budget: incoming.translatorBudget,
683695
});
684-
if (body !== undefined) {
685-
request.releaseBodyObservation?.();
686-
request.body = body;
687-
const headers = new Headers(request.headers);
688-
headers.delete("content-length");
689-
request.headers = Object.fromEntries(headers);
690-
request.releaseBodyObservation = incoming.translatorBudget.observeExternallyCapped(
691-
"passthrough_serialization", Buffer.byteLength(body, "utf8"),
692-
);
693-
}
696+
if (body !== undefined) replaceBody(body);
694697
} catch (error) { request.releaseBodyObservation?.(); throw error; }
695698
}
699+
if (isMistralChatRequest(request)) {
700+
const model = request.outboundModelId ?? requestParsed.modelId;
701+
const body = mistralImageLimitBody(request, {
702+
maxImages: mistralMaxImages(model, fileProvider.modelCapabilities?.[model]?.mistralMaxImages),
703+
budget: incoming.translatorBudget,
704+
});
705+
if (body !== undefined) replaceBody(body);
706+
}
696707
return request;
697708
};
698709
if (resolved.runTurn) {

‎src/types/provider.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -294,6 +294,8 @@ export interface ModelCapabilities extends ReasoningCapabilities {
294294
video?: { processing?: "static" | "agentic" };
295295
/** Opt in exact first-party DeepSeek models to one-hour image file persistence. */
296296
deepseekImageFiles?: boolean;
297+
/** Images a first-party Mistral Chat request may carry for this model; older ones are pruned. */
298+
mistralMaxImages?: number;
297299
}
298300

299301
/**

‎structure/config.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -559,7 +559,7 @@ The optional `autoReviewOverride` block stores a global approval reviewer select
559559
Display-name validation retains prototype-shaped model IDs as data; reviewer-target map validation remains separate and rejects its reserved keys.
560560
## Explicit per-model capability declarations
561561

562-
Provider-wide `inputModalities` is an optional nonempty array of `text`, `image`, `audio`, or `video`. `providerInputModalitiesConfigError` in `src/config/provider-validation.ts` validates both the config schema and management writes; malformed file values degrade to `["text"]` before parsing without rewriting the file or dropping the provider. Registry defaults remain runtime-only and apply only at the registry destination; exact model declarations outrank the provider fallback. `modelCapabilities` on `src/types/provider.ts` stores exact model-ID entries with optional inputModalities, contextTier, video.processing, deepseekImageFiles and reasoning axes. The reasoning axes are strict optional booleans: `supportsReasoning`, `supportsThinkingToggle`, `supportsReasoningEffort` and `defaultThinkingEnabled`. Each merges independently over the registry row matched by case-insensitive model ID; an unrelated operator axis does not erase registry reasoning facts. Omitted axes may inherit registry or supported legacy evidence; absent evidence stays unknown. Explicit false is retained, and `supportsReasoning: false` suppresses both controls and the thinking default. These facts are separate from the `thinkingToggleModels` wire declaration and from client-only effort aliases; see [reasoning capability resolution](providers-and-adapters.md).
562+
Provider-wide `inputModalities` is an optional nonempty array of `text`, `image`, `audio`, or `video`. `providerInputModalitiesConfigError` in `src/config/provider-validation.ts` validates both the config schema and management writes; malformed file values degrade to `["text"]` before parsing without rewriting the file or dropping the provider. Registry defaults remain runtime-only and apply only at the registry destination; exact model declarations outrank the provider fallback. `modelCapabilities` on `src/types/provider.ts` stores exact model-ID entries with optional inputModalities, contextTier, video.processing, deepseekImageFiles, mistralMaxImages (integer 1–1000) and reasoning axes. The reasoning axes are strict optional booleans: `supportsReasoning`, `supportsThinkingToggle`, `supportsReasoningEffort` and `defaultThinkingEnabled`. Each merges independently over the registry row matched by case-insensitive model ID; an unrelated operator axis does not erase registry reasoning facts. Omitted axes may inherit registry or supported legacy evidence; absent evidence stays unknown. Explicit false is retained, and `supportsReasoning: false` suppresses both controls and the thinking default. These facts are separate from the `thinkingToggleModels` wire declaration and from client-only effort aliases; see [reasoning capability resolution](providers-and-adapters.md).
563563

564564
`src/config/provider-validation.ts` strictly validates writes and merges PATCH axes without sharing live objects; null map/model/axis/processing tombstones delete, while empty PATCH objects do nothing. Complete POST/PUT replacements reject tombstones. File reads retain valid sibling axes when a reasoning boolean is malformed; malformed explicit modalities restrict to text with a diagnostic. The two catalog writers receive explicit config and gather fingerprints include the map. This storage contract alone does not activate a context tier, advertise a larger window or enable video processing. Separately, `modelContextTiers` actively selects `default` or `long_context` for GitHub Copilot models: config and management writes validate exact IDs, PATCH merges entries and null clears the map, CLI edit writes the map, and OAuth login preserves it.
565565

‎structure/transports/byte-accounting.md‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,16 @@ workspace and replacement serialization; all temporary observations release on s
3737
and cancellation. These are externally capped observations, not permission to exceed arbitrary
3838
translator collector limits. The original request and final retained wire body retain their existing owners.
3939

40+
### Mistral image count
41+
42+
First-party Mistral Chat POSTs (`https://api.mistral.ai/v1/chat/completions`) pass through
43+
`src/server/responses/mistral-image-limit.ts` after the adapter builds the body. Bodies whose
44+
`image_url` part count exceeds the model's cap (`modelCapabilities.<id>.mistralMaxImages`, then
45+
the measured caps in that module, then the documented 8) keep the newest images and replace older parts with a text note across all messages,
46+
including promoted tool-result images. A substring count bounds the work before parsing; the
47+
parsed copy and replacement serialization are observed in the translator budget and released
48+
in `finally`. Nothing is uploaded or persisted, and the client history is unchanged.
49+
4050
Uploads use the selected provider transport, pacing and physical credential-generation fence.
4151
A queued dispatch rebuild already holds its enclosing provider concurrency lease: only that nested
4252
upload skips a second concurrency acquisition but still acquires an interval-only pacing slot,

0 commit comments

Comments
 (0)