A local-first multi-agent app development platform, built on PenguinHarness
fix(core): 会话里图太多时不再整条失败,只带最新的四张
lmliheng217c590815c2
diff --git a/changelog/unreleased/2026-10-23-image-budget.md b/changelog/unreleased/2026-10-23-image-budget.mdnew file mode 100644index 00000000..fdadae08--- /dev/null+++ b/changelog/unreleased/2026-10-23-image-budget.md@@ -0,0 +1,47 @@+# A conversation full of pictures no longer fails whole — only the newest four go out++- **Date:** 2026-10-23+- **Type:** fix+- **Scope:** `core`, `docs`+- **Breaking:** no++[中文](2026-10-23-image-budget.zh.md)++Abliteration accepts at most four images in one request and refuses the whole request beyond+that (`400 … media_count_exceeded`). A conversation replays its images on every later request,+so a Session that had read five pictures failed every turn from then on — the same error sitting+in the chat no matter what was typed next.++Each request is now trimmed to the model's own limit: the **oldest** images are replaced with a+one-line `[image omitted: …]` placeholder and the newest four stay (images in the new input take+their share first). The stuck conversation works again, and nothing is lost from the+conversation or its Trace.++## Details++- **The limit lives in the catalog.** `ModelCatalogEntry` gains `maxImages`; Abliteration's four+ rows carry 4, and `catalogImageLimit()` reads it by `(provider, model_id)`. Models without the+ field — every other row in the catalog — behave exactly as before.+- **Trimmed before the request** (`core/src/llm/generative-model.ts`): `streamGenerate` calls+ `fitReplayedImages` before opening the upstream stream. The new input's images are counted+ first, the remaining budget goes to the history newest-first, and when it does not fit,+ `capHistoryImages` rebuilds the history and hands it to AgentHub's `setHistory` (the objects+ `getHistory` returns are never mutated in place). A tool result's images are trimmed inside its+ own `images` array with the placeholder appended to its text. When the new input alone fills+ the budget, every replayed image becomes a placeholder.+- **The Session model carries it** (`core/src/agent.ts`): `buildLLM` looks the limit up in the+ catalog and passes it as `GenerativeModelConfig.maxImages`. A context rebuilt after compaction,+ or for a switched model, goes through the same constructor.+- Tests: `core/test/image-budget.test.ts` (counting, per-message trimming, tool-result trimming,+ no mutation of the originals, a zero budget, the untouched path with no limit, and the wiring+ that counts the new input) and `core/test/model-catalog.test.ts` (the four rows carry 4; no+ other model and no id outside the catalog does).+- Docs: the Abliteration section of `models.zh.md` / `models.en.md` states the limit and what+ the trimming does.++## Compatibility++- No new configuration and no stored data rewritten: the limit comes from the built-in catalog,+ and an existing Session works around it on its next request.+- Models with no limit send exactly what they sent before; only the four catalogued rows carry+ one.diff --git a/changelog/unreleased/2026-10-23-image-budget.zh.md b/changelog/unreleased/2026-10-23-image-budget.zh.mdnew file mode 100644index 00000000..9c985051--- /dev/null+++ b/changelog/unreleased/2026-10-23-image-budget.zh.md@@ -0,0 +1,34 @@+# 会话里的图太多时不再整条报错,只带最新的四张++- **Date:** 2026-10-23+- **Type:** fix+- **Scope:** `core`, `docs`+- **Breaking:** no++[English](2026-10-23-image-budget.md)++Abliteration 一次请求最多收四张图,超过就把整条请求拒掉(`400 … media_count_exceeded`)。而对话里的图会被之后+的每一次请求重新带上:一个会话只要读过五张图,从此每说一句话都失败,界面上一直挂着同一个错误,换个问法也没用。++现在每个请求都按模型自己的上限裁剪:**最旧的图先被换掉**,换成一行 `[image omitted: …]` 文字占位,最新的四张留+下来(新发出的图先占名额)。那条卡住的会话因此可以继续用,对话本身与 Trace 里的东西一张不少。++## 细节++- **上限记在目录里。** `ModelCatalogEntry` 新增 `maxImages`,Abliteration 的四条预置都写 4,`catalogImageLimit()`+ 按 `(provider, model_id)` 读它。没有这个字段的模型——目录里除这四条以外全部——行为完全不变。+- **请求前裁剪**(`core/src/llm/generative-model.ts`):`streamGenerate` 在打开上游流之前调用+ `fitReplayedImages`:先把本次新输入的图算进预算,剩下的额度从最新往前给历史;放不下时用 `capHistoryImages`+ 重建一份历史交给 AgentHub 的 `setHistory`(`getHistory` 交出来的对象不原地改动)。工具结果里的图按它自己的+ `images` 数组裁,占位那行追加到同一段文字后面。新输入自己就占满额度时,历史里的图全部换成占位。+- **会话模型带上它**(`core/src/agent.ts`):`buildLLM` 从目录查出上限,作为 `GenerativeModelConfig.maxImages`+ 传下去;压缩后重建、或切换模型后的新上下文都走同一个构造点。+- 测试:`core/test/image-budget.test.ts`(计数、按消息裁剪、工具结果裁剪、不改原对象、零预算、没有上限时原样+ 送出,以及把新输入的图算进预算的接线)与 `core/test/model-catalog.test.ts`(四条条目带 4,其余模型与目录外+ 的 id 都没有)。+- 文档:`models.zh.md` / `models.en.md` 的 Abliteration 一节写清这条上限与裁剪行为。++## 兼容性++- 没有新配置项,也不重写已存的数据:上限从内置目录读,老会话在下一次请求时自动绕开。+- 没有上限的模型一条请求都不变;带上限的只有目录里写明的那四条。diff --git a/docs/FORK-PROGRESS.md b/docs/FORK-PROGRESS.mdindex 4f05cecb..cc3343bb 100644--- a/docs/FORK-PROGRESS.md+++ b/docs/FORK-PROGRESS.md@@ -14452,3 +14452,41 @@ setDeleting(null); // 被拒也关安装副本再重启 `adelie-server.service`——这一步没做,等用户点头。- key 没有写进任何 Project 配置;用户说他自己来测试。- 没切版本号、没发 npm、没发安装包、没发发布汇总。++## 用户点单:会话因图太多整条失败(Abliteration 4 张上限)(2026-10-23)++### 现象与根因++用户在另一个会话里反复看到 `模型请求错误:400 This request has more images than the limit of 4. Send fewer+images and try again. (media_count_exceeded)`。那条会话(`session-2026-10-23-13-01-16-9535d94c`,模型+`abliteration / abliterated-model-large-flash`,来自上一轮刚加的分组)在 trace 里连读五张图(`d1`…`d5` 的+`tool_call_output` 各带一张),随后每一次请求都是同一条 400:AgentHub 的会话历史每轮全量重放,图数一旦超过卖家上限+就再也发不出去,改问法、只发文字都没用。++### 改了什么++- `packages/core/src/state/model-catalog.ts`:`ModelCatalogEntry` 新增 `maxImages`(每请求图片上限,卖家公布时+ 才写),Abliteration 四条预置都写 4;新增 `catalogImageLimit(provider, modelId)` 按 `(provider, model_id)` 查。+- `packages/core/src/interfaces/llm.ts`:`GenerativeModelConfig.maxImages`。+- `packages/core/src/llm/generative-model.ts`:新增 `countMessageImages` / `capHistoryImages`(纯函数,导出可测)+ 与私有 `fitReplayedImages`;`streamGenerate` 在 `refreshApiKey` 之后、打开上游流之前调用它——本次新输入的图先+ 算进预算,剩下的从最新往前留给历史,超出部分换成一行 `[image omitted: …]`(工具结果按自己的 `images` 数组裁,+ 占位追加到文字后),重建历史交给 `setHistory`,不动 `getHistory` 交出来的对象。+- `packages/core/src/agent.ts`:`buildLLM` 用目录查出上限并传给 `GenerativeModel`(压缩重建、换模型后的新上下文+ 同一条路)。+- 测试:新增 `packages/core/test/image-budget.test.ts`(8 条:计数、按消息/工具结果裁剪、不改原对象、零预算、+ 无上限原样送出、新输入的图算进预算);`packages/core/test/model-catalog.test.ts` 补四条条目带 4、其余全无、+ 目录外 id 与未给 provider 都查不到。+- 文档:`packages/docs/content/models.zh.md` / `models.en.md` 的 Abliteration 一节写明 4 张上限与裁剪规则;+ `changelog/unreleased/2026-10-23-image-budget.{md,zh.md}`。++### 验证++- `packages/core`:`npx vitest run test/image-budget.test.ts` → 8 passed;全量 `npx vitest run` → 69 个文件+ 通过 / 1418 passed、6 skipped;`npx tsc --noEmit -p tsconfig.json` 无输出;改动文件 `prettier --check` 全绿。+- 接线读的是构建产物里的 `catalogImageLimit`,不是手写的分支:目录里只有这四条返回 4。++### 没做 / 还差什么++- 现网安装副本要重新构建再重启才带上(见下一节的部署记录)。+- 没有替用户去复测那条会话:他说了自己来测,而且每次请求是真花钱的。diff --git a/packages/core/src/agent.ts b/packages/core/src/agent.tsindex 71709b9d..63b8a521 100644--- a/packages/core/src/agent.ts+++ b/packages/core/src/agent.ts@@ -99,6 +99,7 @@ import type {import { SUBAGENT_NAME } from "./environment/tools/run-subagent.js";import { INPUT_SUBAGENT_NAME } from "./environment/tools/input-subagent.js";import type { CompactionSettings, OpenContextOptions } from "./engine/context-engine.js";+import { catalogImageLimit } from "./state/model-catalog.js";import type {ApproveFn,CommandPolicyConfig,@@ -1349,6 +1350,9 @@ export class Agent {// model_id) pair as the primary key.const buildLLM = (context: AssembledContext, tools: ToolDefinition[]): GenerativeModel => {const entry = context.modelEntry;+ // The seller's per-request image cap, from the catalog (Abliteration's is 4): a+ // conversation that accumulates pictures would otherwise fail every later request.+ const imageLimit = catalogImageLimit(entry.provider, entry.model_id);return new GenerativeModel({modelId: entry.model_id,toolCallIds,@@ -1357,6 +1361,7 @@ export class Agent {tools,systemPrompt: context.systemPrompt,...(entry.context_window !== undefined ? { contextWindow: entry.context_window } : {}),+ ...(imageLimit !== undefined ? { maxImages: imageLimit } : {}),...(context.maxTokens !== undefined ? { maxTokens: context.maxTokens } : {}),// Fast mode is a session-request annotation: it rides every context's LLM object,// while the bare/meta LLM below and the vision describer deliberately skip it — theirdiff --git a/packages/core/src/interfaces/llm.ts b/packages/core/src/interfaces/llm.tsindex 44e83e55..8a59310d 100644--- a/packages/core/src/interfaces/llm.ts+++ b/packages/core/src/interfaces/llm.ts@@ -51,6 +51,18 @@ export interface GenerativeModelConfig {* llm/context-limits.ts) so small-window models never fail provider validation.*/maxTokens?: number;+ /**+ * How many images ONE request may carry, when the model's seller publishes a cap (the+ * catalog's `ModelCatalogEntry.maxImages`; Abliteration's is 4). Unset = no known cap.+ *+ * A conversation accumulates images — a `read_file` of a picture, an attached screenshot —+ * and every later request replays them, so a provider that counts images refuses the+ * conversation outright once the total passes its limit (`400 … media_count_exceeded`).+ * The implementation therefore trims the OLDEST replayed images down to this number before+ * each request, replacing each with a one-line text placeholder, and keeps the newest; the+ * messages in the Session's own history and Trace are not touched.+ */+ maxImages?: number;/*** Per-model fast mode (from the model entry's `fast_mode` annotation): when true, every* request opts into the provider's faster serving tier at premium pricing (AgentHubdiff --git a/packages/core/src/llm/generative-model.ts b/packages/core/src/llm/generative-model.tsindex c22e650e..b29ebfd0 100644--- a/packages/core/src/llm/generative-model.ts+++ b/packages/core/src/llm/generative-model.ts@@ -236,6 +236,101 @@ export function mergeOmniToUniMessage(messages: OmniMessage[]): UniMessage {return { role, content_items: contentItems };}+// ---------------------------------------------------------------------------+// Image budget (a request may carry only so many images)+// ---------------------------------------------------------------------------++/**+ * The stand-in left where an image was dropped from a request: one text item (or one appended+ * line, for a tool result's images) in the place the picture occupied, so the model knows the+ * conversation held a picture there and cannot mistake the gap for its own omission. Named in+ * the seller's own terms — the limit is the request's image count, not the picture's size.+ */+export function imageOmittedNote(limit: number): string {+ return `[image omitted: this model accepts at most ${limit} image${limit === 1 ? "" : "s"} per request]`;+}++/** Whether a content item is an image the request counts: a data URL or an inline image blob. */+function isImageItem(item: ContentItem): boolean {+ if (item.type === "image_url") return true;+ return item.type === "inline_data" && item.mime_type.startsWith("image/");+}++/** How many images one UniMessage carries — image items plus a tool result's image attachments. */+export function countMessageImages(msg: UniMessage): number {+ let count = 0;+ for (const item of msg.content_items) {+ if (isImageItem(item)) count += 1;+ else if (item.type === "tool_result") count += item.images?.length ?? 0;+ }+ return count;+}++/**+ * Keeps at most `budget` of a message's images, **the newest ones**, and replaces each older+ * one with {@link imageOmittedNote}. A message that fits is returned as-is (same object), so a+ * history made entirely of fitting messages costs nothing.+ */+function capMessageImages(msg: UniMessage, budget: number, limit: number): UniMessage {+ if (countMessageImages(msg) <= budget) return msg;+ const note = imageOmittedNote(limit);+ let left = budget;+ const kept: ContentItem[] = [];+ // Newest first: the images nearest the current request are the ones worth paying for.+ for (let i = msg.content_items.length - 1; i >= 0; i -= 1) {+ const item = msg.content_items[i]!;+ if (isImageItem(item)) {+ if (left > 0) {+ left -= 1;+ kept.push(item);+ } else {+ kept.push({ type: "text", text: note });+ }+ continue;+ }+ if (item.type === "tool_result" && (item.images?.length ?? 0) > 0) {+ const images = item.images!;+ if (images.length <= left) {+ left -= images.length;+ kept.push(item);+ } else {+ const surviving = left > 0 ? images.slice(-left) : [];+ left = 0;+ kept.push({+ ...item,+ ...(surviving.length > 0 ? { images: surviving } : { images: undefined }),+ text: item.text ? `${item.text}\n\n${note}` : note,+ });+ }+ continue;+ }+ kept.push(item);+ }+ return { ...msg, content_items: kept.reverse() };+}++/**+ * Trims a replayed history to at most `limit` images in aggregate, newest kept (see+ * {@link capMessageImages}). Returns a new array of the same length whose untouched messages+ * are the very objects it was handed.+ */+export function capHistoryImages(history: UniMessage[], limit: number): UniMessage[] {+ const counts = history.map(countMessageImages);+ const capped = new Array<UniMessage>(history.length);+ let left = limit;+ for (let i = history.length - 1; i >= 0; i -= 1) {+ const msg = history[i]!;+ const count = counts[i]!;+ if (count === 0) {+ capped[i] = msg;+ continue;+ }+ capped[i] = capMessageImages(msg, left, limit);+ left = Math.max(0, left - count);+ }+ return capped;+}+// ---------------------------------------------------------------------------// Token accounting (as defined by SKILL.md)// ---------------------------------------------------------------------------@@ -971,6 +1066,8 @@ export class GenerativeModel implements LLMInterface {private readonly toolCallIds: ToolCallIdAllocator;/** Configured output cap (`GenerativeModelConfig.maxTokens`); the per-request clamp derives the effective cap from it (see effectiveMaxTokens). */private readonly configuredMaxTokens: number | undefined;+ /** Per-request image cap (`GenerativeModelConfig.maxImages`); undefined = the seller publishes none (see fitReplayedImages). */+ private readonly maxImages: number | undefined;/** Model context window; `undefined` when unconfigured (or implausibly small, see resolveContextWindow) — the per-request clamp then disables itself rather than clamp against an assumption. */private readonly contextWindow: number | undefined;/**@@ -1023,6 +1120,10 @@ export class GenerativeModel implements LLMInterface {this.requestTimeoutMs = config.requestTimeoutMs ?? 300000;this.toolCallIds = config.toolCallIds ?? new ToolCallIdAllocator();this.configuredMaxTokens = config.maxTokens;+ this.maxImages =+ config.maxImages !== undefined && config.maxImages > 0+ ? Math.floor(config.maxImages)+ : undefined;this.contextWindow = resolveContextWindow(config.contextWindow);this.baseInputTokens =approximateTokens(config.systemPrompt ?? "") +@@ -1208,6 +1309,10 @@ export class GenerativeModel implements LLMInterface {let outcome: LLMOutcome | null = null;try {await this.refreshApiKey();+ // The seller counts images per request, not per message: a conversation that read five+ // pictures would fail every later turn with 400 media_count_exceeded, so the oldest+ // replayed ones are dropped from THIS request (the history and Trace keep them).+ this.fitReplayedImages(uniMessage);const it = this.openStream(uniMessage,ac.signal,@@ -1384,6 +1489,27 @@ export class GenerativeModel implements LLMInterface {this.client.setHistory(groupHistoryToUniMessages(history));}+ /**+ * Trims the replayed history so this request carries at most `maxImages` images in all: the+ * new input's images are counted first (they are what the user is asking about now), the+ * history keeps the rest, newest first — see capHistoryImages for the per-message rule.+ *+ * Nothing happens without a configured cap, or when the history already fits. When it does+ * not, the client's history is replaced through setHistory rather than mutated: the objects+ * getHistory hands out are the client's own. A conversation's Trace and stored history are+ * untouched — this decides what one request carries, not what the conversation is.+ */+ private fitReplayedImages(input: UniMessage): void {+ const limit = this.maxImages;+ if (limit === undefined) return;+ const budget = Math.max(0, limit - countMessageImages(input));+ const history = this.client.getHistory();+ if (history.length === 0) return;+ const total = history.reduce((sum, msg) => sum + countMessageImages(msg), 0);+ if (total <= budget) return;+ this.client.setHistory(capHistoryImages(history, budget));+ }+/*** Opens the underlying AgentHub stream (a testing seam): defaults to* `streamingResponseStateful`; unit tests can subclass and override this method, feeding in adiff --git a/packages/core/src/state/model-catalog.ts b/packages/core/src/state/model-catalog.tsindex 07558e35..5ba21647 100644--- a/packages/core/src/state/model-catalog.ts+++ b/packages/core/src/state/model-catalog.ts@@ -243,6 +243,19 @@ export interface ModelCatalogEntry {offPeakDiscount?: OffPeakDiscount;/** Whether image input (vision modality) is supported. */supportsVision: boolean;+ /**+ * How many images ONE request may carry, when the seller publishes a cap. Unset = no known+ * cap, and the request goes out with whatever the conversation holds.+ *+ * This is a request-shape fact, not a display one: a conversation accumulates images (a+ * `read_file` of a picture becomes one, and every later request replays the history), and a+ * provider that counts them refuses the request outright once the total passes its limit —+ * `400 … media_count_exceeded` from Abliteration, whose cap is 4. The Session therefore+ * trims the oldest replayed images down to this number before each request (see+ * GenerativeModel's image budget), keeping the newest; the conversation's own history and+ * Trace keep every image, so nothing is lost from the record.+ */+ maxImages?: number;/** AgentHub client protocol: required when an id cannot be auto-routed or a shared protocol must be pinned. */clientType?: string;/** Preset base URL: inlined into gateway and direct MiniMax entries so only an API key is required. */@@ -3156,6 +3169,7 @@ export const MODEL_CATALOG: ModelCatalogEntry[] = [provider: "abliteration",contextWindow: 1000000,pricing: usd(0.3, 3, 5),+ maxImages: 4,supportsVision: false,clientType: "openai-chat",baseUrl: ABLITERATION_BASE_URL,@@ -3166,6 +3180,7 @@ export const MODEL_CATALOG: ModelCatalogEntry[] = [provider: "abliteration",contextWindow: 1000000,pricing: usd(0.3, 3, 5),+ maxImages: 4,supportsVision: false,clientType: "openai-chat",baseUrl: ABLITERATION_BASE_URL,@@ -3176,6 +3191,7 @@ export const MODEL_CATALOG: ModelCatalogEntry[] = [provider: "abliteration",contextWindow: 1048576,pricing: usd(0.1, 1, 2),+ maxImages: 4,supportsVision: true,clientType: "openai-chat",baseUrl: ABLITERATION_BASE_URL,@@ -3186,6 +3202,7 @@ export const MODEL_CATALOG: ModelCatalogEntry[] = [provider: "abliteration",contextWindow: 262144,pricing: usd(0.1, 1, 3),+ maxImages: 4,supportsVision: true,clientType: "openai-chat",baseUrl: ABLITERATION_BASE_URL,@@ -3239,6 +3256,22 @@ export function providerInfo(providerId: string): ModelProviderInfo | undefinedreturn MODEL_PROVIDERS.find((p) => p.id === providerId);}+/**+ * The per-request image cap the catalog records for a model (ModelCatalogEntry.maxImages), or+ * undefined when the vendor publishes none — the case for every row but Abliteration's.+ *+ * Read from the catalog rather than stored on the Project entry: the cap is a property of the+ * seller, not a preference, so a Project that renamed or repriced the row still sends at most+ * what the seller accepts. A user-added row (no catalog entry) gets no cap.+ */+export function catalogImageLimit(+ provider: string | undefined,+ upstreamId: string,+): number | undefined {+ if (provider === undefined) return undefined;+ return catalogEntryFor(provider, upstreamId)?.maxImages;+}+/*** The protocol a group pins on every one of its entries (ModelProviderInfo.clientType), or* undefined when the group pins none — an unknown id (a user-defined group) included.diff --git a/packages/core/test/image-budget.test.ts b/packages/core/test/image-budget.test.tsnew file mode 100644index 00000000..40af3597--- /dev/null+++ b/packages/core/test/image-budget.test.ts@@ -0,0 +1,199 @@+/**+ * The per-request image budget: a conversation accumulates images (every `read_file` of a+ * picture, every attachment), every request replays them, and a seller that counts them refuses+ * the whole conversation once the total passes its limit — Abliteration answers+ * `400 This request has more images than the limit of 4 … (media_count_exceeded)` for good, so+ * the Session itself has to send fewer.+ *+ * What is checked here: the pure trimming (newest images kept, older ones replaced by a text+ * note, tool results trimmed inside their own image list) and the wiring — a configured+ * `maxImages` reaches the client's history before the request opens, and the new input's own+ * images are counted against the same budget.+ */+import { describe, expect, it, vi } from "vitest";+import type { UniEvent, UniMessage } from "@prismshadow/agenthub";+import type { OmniMessage } from "../src/omnimessage/index.js";++const state = vi.hoisted(() => ({ clients: [] as { history: UniMessage[] }[] }));++vi.mock("@prismshadow/agenthub", async (importOriginal) => {+ const mod = await importOriginal<typeof import("@prismshadow/agenthub")>();+ class FakeAutoLLMClient {+ history: UniMessage[] = [];+ constructor(_options: Record<string, unknown>) {+ state.clients.push(this);+ }+ getHistory(): UniMessage[] {+ return this.history;+ }+ setHistory(history: UniMessage[]): void {+ this.history = history;+ }+ async *streamingResponseStateful(): AsyncIterable<UniEvent> {+ // Nothing upstream: the tests only care about what the request would carry.+ }+ appendHistory(message: UniMessage): void {+ this.history = [...this.history, message];+ }+ }+ return { ...mod, AutoLLMClient: FakeAutoLLMClient };+});++const { GenerativeModel, capHistoryImages, countMessageImages, imageOmittedNote } =+ await import("../src/llm/generative-model.js");+const { imageUrlMessage, toolCallOutput, userText } = await import("../src/omnimessage/index.js");++const IMAGE = "data:image/png;base64,AAAA";++/** A user message carrying N images. */+const imageMessage = (n: number): UniMessage => ({+ role: "user",+ content_items: Array.from({ length: n }, () => ({+ type: "image_url" as const,+ image_url: IMAGE,+ })),+});++/** A tool result carrying N images, as read_file returns for a picture. */+const toolImageMessage = (n: number): UniMessage => ({+ role: "user",+ content_items: [+ {+ type: "tool_result",+ tool_call_id: "call_1",+ text: "image/png, 1 kB",+ images: Array.from({ length: n }, () => IMAGE),+ },+ ],+});++const imageCount = (history: UniMessage[]): number =>+ history.reduce((sum, msg) => sum + countMessageImages(msg), 0);++describe("countMessageImages", () => {+ it("counts image items, inline image blobs and a tool result's own images", () => {+ expect(countMessageImages(imageMessage(3))).toBe(3);+ expect(countMessageImages(toolImageMessage(2))).toBe(2);+ expect(+ countMessageImages({+ role: "user",+ content_items: [+ { type: "text", text: "hi" },+ { type: "inline_data", data: Buffer.from("x"), mime_type: "image/png" },+ // A non-image blob is not an image.+ { type: "inline_data", data: Buffer.from("x"), mime_type: "application/pdf" },+ ],+ }),+ ).toBe(1);+ });+});++describe("capHistoryImages", () => {+ it("keeps the newest images and replaces the older ones with a note", () => {+ const history = [imageMessage(2), imageMessage(2), imageMessage(1)];+ const capped = capHistoryImages(history, 4);+ expect(imageCount(capped)).toBe(4);+ // Walking backwards: the newest message (1) fits whole and message 1 fits too, which+ // leaves one image of the two in the oldest message.+ expect(capped[2]).toBe(history[2]);+ expect(capped[1]).toBe(history[1]);+ expect(countMessageImages(capped[0]!)).toBe(1);+ expect(capped[0]!.content_items).toEqual([+ { type: "text", text: imageOmittedNote(4) },+ { type: "image_url", image_url: IMAGE },+ ]);+ });++ it("trims a tool result inside its own image list and says so in its text", () => {+ const history = [toolImageMessage(3)];+ const capped = capHistoryImages(history, 1);+ const item = capped[0]!.content_items[0]!;+ expect(item.type).toBe("tool_result");+ if (item.type !== "tool_result") throw new Error("unreachable");+ expect(item.images).toEqual([IMAGE]);+ expect(item.text).toContain(imageOmittedNote(1));+ // The original message is not mutated: the same conversation may be replayed later.+ const original = history[0]!.content_items[0]!;+ if (original.type !== "tool_result") throw new Error("unreachable");+ expect(original.images).toHaveLength(3);+ expect(original.text).not.toContain("omitted");+ });++ it("leaves a fitting history alone: same array contents, same message objects", () => {+ const history = [imageMessage(1), imageMessage(2)];+ const capped = capHistoryImages(history, 4);+ expect(capped[0]).toBe(history[0]);+ expect(capped[1]).toBe(history[1]);+ });++ it("drops every replayed image when the budget is zero", () => {+ const capped = capHistoryImages([imageMessage(2), toolImageMessage(1)], 0);+ expect(imageCount(capped)).toBe(0);+ const tool = capped[1]!.content_items[0]!;+ if (tool.type !== "tool_result") throw new Error("unreachable");+ expect(tool.images).toBeUndefined();+ expect(tool.text).toContain(imageOmittedNote(0));+ });+});++describe("GenerativeModel image budget", () => {+ const build = (over: { maxImages?: number } = {}): GenerativeModel =>+ new GenerativeModel({+ modelId: "abliterated-model-large-flash",+ apiKey: "ak-test",+ clientType: "openai-chat",+ baseUrl: "https://api.abliteration.ai/v1",+ tools: [],+ ...over,+ });++ const lastClient = (): { history: UniMessage[] } => state.clients.at(-1)!;++ const run = async (model: GenerativeModel, newMessages: OmniMessage[]): Promise<void> => {+ for await (const _ of model.streamGenerate({ newMessages })) {+ // Nothing is produced — the fake stream is empty.+ }+ };++ it("trims the replayed history to the configured cap before the request opens", async () => {+ const model = build({ maxImages: 4 });+ model.setHistory([+ toolCallOutput({ toolCallId: "call_1", output: "image/png, 1 kB", images: [IMAGE] }),+ toolCallOutput({ toolCallId: "call_2", output: "image/png, 1 kB", images: [IMAGE] }),+ toolCallOutput({ toolCallId: "call_3", output: "image/png, 1 kB", images: [IMAGE] }),+ toolCallOutput({ toolCallId: "call_4", output: "image/png, 1 kB", images: [IMAGE] }),+ toolCallOutput({ toolCallId: "call_5", output: "image/png, 1 kB", images: [IMAGE] }),+ ]);+ expect(imageCount(lastClient().history)).toBe(5);+ await run(model, [userText("这几张图里哪个是红色的?")]);+ expect(imageCount(lastClient().history)).toBe(4);+ });++ it("counts the new input's images against the same budget", async () => {+ const model = build({ maxImages: 4 });+ model.setHistory([+ toolCallOutput({ toolCallId: "call_1", output: "image/png, 1 kB", images: [IMAGE] }),+ toolCallOutput({ toolCallId: "call_2", output: "image/png, 1 kB", images: [IMAGE] }),+ toolCallOutput({ toolCallId: "call_3", output: "image/png, 1 kB", images: [IMAGE] }),+ toolCallOutput({ toolCallId: "call_4", output: "image/png, 1 kB", images: [IMAGE] }),+ ]);+ // Two new pictures: the replay may keep only two of the four in history.+ await run(model, [imageUrlMessage(IMAGE), imageUrlMessage(IMAGE)]);+ expect(imageCount(lastClient().history)).toBe(2);+ });++ it("sends the history untouched when no cap is configured", async () => {+ const model = build();+ model.setHistory([+ toolCallOutput({ toolCallId: "call_1", output: "image/png, 1 kB", images: [IMAGE] }),+ toolCallOutput({ toolCallId: "call_2", output: "image/png, 1 kB", images: [IMAGE] }),+ toolCallOutput({ toolCallId: "call_3", output: "image/png, 1 kB", images: [IMAGE] }),+ toolCallOutput({ toolCallId: "call_4", output: "image/png, 1 kB", images: [IMAGE] }),+ toolCallOutput({ toolCallId: "call_5", output: "image/png, 1 kB", images: [IMAGE] }),+ ]);+ const before = lastClient().history;+ await run(model, [userText("hi")]);+ expect(lastClient().history).toBe(before);+ expect(imageCount(lastClient().history)).toBe(5);+ });+});diff --git a/packages/core/test/model-catalog.test.ts b/packages/core/test/model-catalog.test.tsindex eba2dea0..d5b41d32 100644--- a/packages/core/test/model-catalog.test.ts+++ b/packages/core/test/model-catalog.test.ts@@ -11,6 +11,7 @@ import {canonicalClientType,modelHomepageUrl,catalogEntryFor,+ catalogImageLimit,attributionHeaders,effectivePricing,offPeakAt,@@ -1049,10 +1050,24 @@ describe("model-catalog", () => {for (const m of abl) {expect(m.clientType, m.modelId).toBe("openai-chat");expect(m.baseUrl, m.modelId).toBe("https://api.abliteration.ai/v1");+ // Its per-request image cap, and the lookup the Session reads it through: four images+ // per request is the seller's own limit (`media_count_exceeded` beyond it).+ expect(m.maxImages, m.modelId).toBe(4);+ expect(catalogImageLimit("abliteration", m.modelId), m.modelId).toBe(4);// A gateway row: no promotion, so nothing sits between the list price and the bill.expect(m.discount, m.modelId).toBeUndefined();expect(m.retired, m.modelId).toBeUndefined();}+ // No other group publishes an image cap, so a request there carries every image the+ // conversation holds (and a seller with an unpublished limit keeps the language it had).+ for (const m of MODEL_CATALOG) {+ if (m.provider === "abliteration") continue;+ expect(m.maxImages, `${m.provider}/${m.modelId}`).toBeUndefined();+ expect(catalogImageLimit(m.provider, m.modelId), m.modelId).toBeUndefined();+ }+ // An id the catalog does not know — a user-added row — gets no cap either.+ expect(catalogImageLimit("abliteration", "someone/else")).toBeUndefined();+ expect(catalogImageLimit(undefined, "abliterated-model")).toBeUndefined();const gateway = [...or, ...fw, ...sf, ...td, ...qtp, ...qpayg, ...ms, ...abl];// Pricing (USD, per the 2026-08-03 models-API re-read): MiMo v2.5 and Hy3 publish a real// cache-hit price and no per-token write premium, so cache_write carries the input price.diff --git a/packages/docs/content/models.en.md b/packages/docs/content/models.en.mdindex 6d46ea7f..f4af40a3 100644--- a/packages/docs/content/models.en.md+++ b/packages/docs/content/models.en.md@@ -499,6 +499,7 @@ The preset rows carry no price. ModelScope bills for api-inference and its model- **Presets.** `abliterated-model-large-v2` (the vendor's recommended default), `abliterated-model-large`, `abliterated-model-large-flash` and `abliterated-model`. The first two take text only at a 1,000,000-token window; `flash` takes text and images at 1,048,576; `abliterated-model` takes both at 262,144.- **Protocol.** None of these ids matches a rule AgentHub routes by, so every row pins the Chat Completions client (`client_type = "openai-chat"`) and carries the endpoint on itself. The same endpoint also serves `/responses`; change the row's protocol if you prefer it. As in every gateway, a keyless row is refused rather than sent your OpenAI key.- **Prices.** Read from the service's own model list, in USD per million Tokens: input 1 or 3, output 2, 3 or 5, and cache hits read at 0.1 or 0.3. It charges no separate cache-write fee, so `cache_write` records the input rate.+- **At most four images per request.** That is the service's own limit, and a request past it is refused outright (`400 … media_count_exceeded`); because a conversation replays its images on every request, such a conversation fails for good. Adelie therefore replaces the **oldest** images with a one-line `[image omitted: …]` placeholder before each request, keeping the newest four (images in the new input count against them first). The conversation and its Trace keep every picture — only what one request carries is reduced.### Preset modelsdiff --git a/packages/docs/content/models.zh.md b/packages/docs/content/models.zh.mdindex e44b33e7..38f586c3 100644--- a/packages/docs/content/models.zh.md+++ b/packages/docs/content/models.zh.md@@ -498,6 +498,7 @@ OpenAI 兼容网关分组(openrouter / fireworks / siliconflow / tokendance /- **预置模型。** `abliterated-model-large-v2`(官方推荐的默认选择)、`abliterated-model-large`、`abliterated-model-large-flash` 与 `abliterated-model`。前两条是 1,000,000 Token 上下文、只收文本;`flash` 是 1,048,576 并接受图像;`abliterated-model` 是 262,144,也接受图像。- **协议。** 这些 id 没有一条能被 AgentHub 按名字认出来,所以每个条目都固定 Chat Completions 客户端(`client_type = "openai-chat"`)并把端点写在条目上;同一条端点上也有 `/responses`,要换协议在条目上改即可。和所有网关一样,没有 key 的条目会被拒绝,而不是把你的 OpenAI key 发过去。- **价格。** 取自服务自己的模型列表,单位是每百万 Token 多少美元:输入 1 或 3,输出 2、3 或 5,缓存命中的读价 0.1 或 0.3。它不额外收缓存写入费,所以 `cache_write` 记的就是输入价。+- **一次请求最多 4 张图。** 这是服务自己的限制,超过它会直接回 `400 … media_count_exceeded`,而对话里的图会被每一次请求重新带上——所以会话会一直失败。Adelie 因此在每次请求前把**最旧的**那几张换成一行 `[image omitted: …]` 文字占位,只保留最新的四张(新发出的图优先算进这四张)。对话本身和 Trace 里的图一张不少,改的只是这一次请求带过去的量。### 预置模型