A local-first multi-agent app development platform, built on PenguinHarness
Fold the image tools into read_file and align input_command's timeout with exec_command (#588)
Yaowei Zheng2a92d55c96ae
diff --git a/changelog/unreleased/2026-09-02-backward-compatibility-read-file-images.md b/changelog/unreleased/2026-09-02-backward-compatibility-read-file-images.mdnew file mode 100644index 00000000..16fa357e--- /dev/null+++ b/changelog/unreleased/2026-09-02-backward-compatibility-read-file-images.md@@ -0,0 +1,30 @@+# Backward compatibility: stored `read_image` / `describe_image` entries and the older `read_file`++- **Date:** 2026-09-02+- **Type:** process+- **Scope:** `core`, `web`+- **PR:** [#588](https://github.com/Prism-Shadow/penguin-harness/pull/588)+- **Breaking:** yes — the `read_image` and `describe_image` tool names are gone; an existing Agent's stored entries stop assembling, and a model calling either gets the unknown-tool reply until the Agent's kernel is updated++[中文版](2026-09-02-backward-compatibility-read-file-images.zh.md)++[Image reading folds into `read_file`](2026-09-02-read-file-images.md) removes two built-in tools that every existing Agent's `system_config.yaml` lists under `tools.builtin`, and changes the definition of a third. Nothing on disk is rewritten; this entry records what an existing install sees and what, if anything, to do.++## Stored tool entries: skipped, not migrated++An Agent created before this release carries a `read_image` (`forModel: vision`) and a `describe_image` (`forModel: text-only`) entry, and a `read_file` entry with the text-only description, no `prompt` argument and a 30000 ms timeout. Chosen: the precedent set when `kill_command` / `kill_subagent` left — an entry whose name has no factory in the registry is **skipped at assembly**: not listed to the model, and a call by the old name gets the standard unknown-tool reply. No alias, no load-time rewrite. The stored `read_file` entry still assembles onto the new implementation, so its image branch already works; the model is merely told the old description, has no `prompt` in its schema, and keeps the 30000 ms timeout.++Without any action, such an Agent therefore loses its image tools by name and gains image reading under `read_file` without being told. To adopt the current definitions:++- **Kernel update** (the badge on the Agents page, or the settings page's kernel action): the kernel version advanced to `2026-09-10`, so every existing Agent is flagged. A tools tab the user never edited advances whole — the new `read_file` entry in, the two image entries out. A tools tab with any customization is kept, as always; restoring the default config or a hand edit (copy the entry from `packages/core/src/state/default-config.ts`) is the recourse there.+- Nothing else. The skip is the registry's standing behavior, not a shim: there is no compatibility code to remove later.++Alternatives not taken: a load-time migration that rewrites `tools.builtin` in place (a silent edit of a user-owned file), and keeping `read_image` / `describe_image` assembling as aliases of `read_file` for a few releases (three names on the model's tool list, and the same cleanup deferred).++## Old Traces++Traces written before this release carry `read_image` / `describe_image` tool calls. They render as before — the tool name and its arguments — and the Web tool card previews them by their `source` argument like a file path (`LEGACY_IMAGE_TOOLS` in `tool-call-card.tsx`). That mapping is display-only and can go once Traces from before 2026-09-02 no longer need rendering; nobody is scheduled to remove it.++## Compatibility++No action is required to keep working: an existing Agent reads images through `read_file` as soon as it tries, but is only told so — and only gets `prompt` and the 60000 ms timeout — after a kernel update or a default restore, and until then a model that still calls `read_image` / `describe_image` gets the unknown-tool reply. Meanwhile its image reads run under the stored 30000 ms — now the budget for the whole vision request, where the dedicated `describe_image` had 90000 ms — so a slow read ends in a tool timeout that reads as a model fault rather than a configuration one; raising the `read_file` entry's `timeoutMs` in the Agent's tools tab fixes that without a kernel update. Scripts and prompts that name those tools switch to `read_file`.diff --git a/changelog/unreleased/2026-09-02-backward-compatibility-read-file-images.zh.md b/changelog/unreleased/2026-09-02-backward-compatibility-read-file-images.zh.mdnew file mode 100644index 00000000..8f6e6b7c--- /dev/null+++ b/changelog/unreleased/2026-09-02-backward-compatibility-read-file-images.zh.md@@ -0,0 +1,30 @@+# 向后兼容:存量的 `read_image` / `describe_image` 条目与旧的 `read_file`++- **Date:** 2026-09-02+- **Type:** process+- **Scope:** `core`, `web`+- **PR:** [#588](https://github.com/Prism-Shadow/penguin-harness/pull/588)+- **Breaking:** yes — `read_image` 与 `describe_image` 两个工具名不复存在;既有 Agent 的存量条目不再装配,模型按任一旧名调用都会得到未知工具回复,直到该 Agent 更新内核++[English](2026-09-02-backward-compatibility-read-file-images.md)++[读图并入 `read_file`](2026-09-02-read-file-images.zh.md) 移除了两个内置工具——每个既有 Agent 的 `system_config.yaml` 都在 `tools.builtin` 下列着它们——并改变了第三个工具的定义。磁盘上的内容一律不改写;本条记录既有安装会看到什么,以及需要做什么(如果需要的话)。++## 存量工具条目:跳过,不迁移++本版本之前创建的 Agent 带有一条 `read_image`(`forModel: vision`)和一条 `describe_image`(`forModel: text-only`)条目,以及一条只写纯文本描述、没有 `prompt` 参数、超时 30000 ms 的 `read_file` 条目。选择:沿用 `kill_command` / `kill_subagent` 退场时的先例——注册表里没有工厂的条目在**装配时跳过**:不列给模型,按旧名调用得到标准的未知工具回复。不设别名,不在加载时改写。存量的 `read_file` 条目仍装配到新实现上,其读图分支已能工作;模型只是被告知了旧描述、schema 里没有 `prompt`,超时也仍是 30000 ms。++因此不做任何操作时,这样的 Agent 按名字失去了读图工具,却在没被告知的情况下经 `read_file` 获得了读图能力。要采纳当前定义:++- **内核更新**(Agents 页的角标,或设置页的内核操作):内核版本推进到 `2026-09-10`,每个既有 Agent 都会被标记。用户从未编辑过的工具 Tab 整体推进——新的 `read_file` 条目进来,两个读图条目出去。带有任何自定义的工具 Tab 一如既往保留;这时的出路是恢复默认配置或手工编辑(从 `packages/core/src/state/default-config.ts` 复制条目)。+- 别无其他。跳过是注册表的既定行为,不是垫片:日后没有要删的兼容代码。++未采用的方案:加载时就地改写 `tools.builtin` 的迁移(悄悄修改用户拥有的文件),以及让 `read_image` / `describe_image` 作为 `read_file` 的别名再装配几个版本(模型的工具列表上留着三个名字,同一次清理只是推迟)。++## 旧 Trace++本版本之前写下的 Trace 带有 `read_image` / `describe_image` 工具调用。它们照旧渲染——工具名与参数——Web 工具卡按其 `source` 参数像文件路径一样预览(`tool-call-card.tsx` 里的 `LEGACY_IMAGE_TOOLS`)。这个映射只管展示,待 2026-09-02 之前的 Trace 不再需要渲染时即可移除;没有人被安排去删它。++## 兼容性++无需任何操作即可继续工作:既有 Agent 一旦尝试就能经 `read_file` 读图,但只有在内核更新或恢复默认之后才会被告知这一点、才拿到 `prompt` 与 60000 ms 的超时;在那之前,仍按 `read_image` / `describe_image` 调用的模型会得到未知工具回复。其间读图走的仍是存量的 30000 ms——它现在是整个视觉请求的预算,而专职的 `describe_image` 原本有 90000 ms——因此稍慢一些的读图就以工具超时收场,看上去像模型出了问题、而非配置问题;在该 Agent 的工具 Tab 里调高 `read_file` 条目的 `timeoutMs` 即可解决,无需内核更新。点名这两个工具的脚本与提示词改用 `read_file`。diff --git a/changelog/unreleased/2026-09-02-read-file-images.md b/changelog/unreleased/2026-09-02-read-file-images.mdnew file mode 100644index 00000000..bc14c13d--- /dev/null+++ b/changelog/unreleased/2026-09-02-read-file-images.md@@ -0,0 +1,19 @@+# Image reading folds into `read_file`; `input_command` shares `exec_command`'s timeout++- **Date:** 2026-09-02+- **Type:** feature+- **Scope:** `core`, `web`, `cli`, `server`, `docs`+- **PR:** [#588](https://github.com/Prism-Shadow/penguin-harness/pull/588)++[中文版](2026-09-02-read-file-images.zh.md)++Removed the `read_image` and `describe_image` tools and taught `read_file` to read images: a png/jpeg/gif/webp file (recognized by magic number, then extension) or an http(s) URL in `file_path` comes back as image content when the Session model accepts images, and as the Project's `vision_model` answering a new optional `prompt` argument when it does not — everything the two tools did, behind one name and one schema. `read_file`'s timeout rose to 60000 ms, and `input_command`'s timeout aligned with `exec_command` at 120000 ms.++## Details++- `read_file`'s text behavior is unchanged (numbered window, `offset` / `limit`, scan cap, secret-store refusal). An image ignores `offset` / `limit`; binary content that is no supported image is still rejected with advice; a URL is only ever an image source.+- The branch is decided by the `VisionDescriberService` the SDK injects into the Environment for text-only Sessions only. Absent, the image is returned via `tool_call_output.images` with a one-line `image/png, 123.4 kB` note. Present, the image and `prompt` (default: a detailed description) go to the vision model in one one-off request whose text streams back as the tool output, nothing of that request leaking into the parent stream and the usage bookkeeping unchanged. With no `vision_model` configured the call ends `fatal` with the same explanation as before, asking the model to have the user pick one.+- The shared image loading moved from `read-image.ts` into `environment/tools/image-source.ts`; `read-image.ts` and `describe-image.ts` are gone, with their registry factories and default-config entries. The default toolset is seven tools, none carrying a `forModel` annotation — the per-model-class filter stays a config feature.+- `input_command`'s empty-poll default wait dropped from 120000 ms to 110000 ms, so a default-length poll still returns on its own under the 120000 ms timeout.+- The kernel version advanced to `2026-09-10` (the tools tab moved): the Web App's kernel update writes the new `read_file` entry and drops the two image entries from an unedited tools tab. What an existing Agent sees without it is recorded in [backward compatibility](2026-09-02-backward-compatibility-read-file-images.md).+- Web tool cards preview the `read_image` / `describe_image` calls of old Traces by their `source` argument, the way file tools are previewed by `file_path`. Model-settings copy, the CLI's vision-model help, and the docs name `read_file` as the image reader.diff --git a/changelog/unreleased/2026-09-02-read-file-images.zh.md b/changelog/unreleased/2026-09-02-read-file-images.zh.mdnew file mode 100644index 00000000..bca621f0--- /dev/null+++ b/changelog/unreleased/2026-09-02-read-file-images.zh.md@@ -0,0 +1,19 @@+# 读图并入 `read_file`;`input_command` 与 `exec_command` 共用超时++- **Date:** 2026-09-02+- **Type:** feature+- **Scope:** `core`, `web`, `cli`, `server`, `docs`+- **PR:** [#588](https://github.com/Prism-Shadow/penguin-harness/pull/588)++[English](2026-09-02-read-file-images.md)++删除了 `read_image` 与 `describe_image` 两个工具,让 `read_file` 也能读图:`file_path` 指向 png/jpeg/gif/webp 文件(先按魔数、再按扩展名识别)或 http(s) URL 时,Session 模型接受图片就返回图像内容,不接受则由 Project 的 `vision_model` 回答新增的可选参数 `prompt`——两个旧工具的能力一项不少,只是收进一个名字、一份 schema。`read_file` 的超时放宽到 60000 ms,`input_command` 的超时与 `exec_command` 对齐为 120000 ms。++## 细节++- `read_file` 的文本行为不变(带行号的窗口、`offset` / `limit`、扫描上限、拒读秘密存储)。图片忽略 `offset` / `limit`;不是受支持图片的二进制内容照旧拒读并给出建议;URL 只作图片来源。+- 分支由 SDK 仅为 text-only Session 注入 Environment 的 `VisionDescriberService` 决定。它不存在时,图片经 `tool_call_output.images` 返回,文本只有一行 `image/png, 123.4 kB`;它存在时,图片连同 `prompt`(缺省为详细描述)单发视觉模型,其文本流式回传为工具输出,该请求的任何内容都不外泄进父会话流,用量记账不变。未配置 `vision_model` 时调用以 `fatal` 收尾,说明文字与此前相同,要求模型提醒用户选一个。+- 共享的图片加载从 `read-image.ts` 移入 `environment/tools/image-source.ts`;`read-image.ts` 与 `describe-image.ts` 连同其注册表工厂和默认配置条目一并移除。默认工具集为七个工具,均不带 `forModel` 标注——按模型类别装配的过滤仍是配置能力。+- `input_command` 空轮询的缺省等待从 120000 ms 降到 110000 ms,使缺省长度的轮询仍能在 120000 ms 的超时之下自行返回。+- 内核版本推进到 `2026-09-10`(工具 Tab 变动):Web App 的内核更新会向未经编辑的工具 Tab 写入新的 `read_file` 条目并移除两个读图条目。既有 Agent 在此之前看到的样子记录在[向后兼容](2026-09-02-backward-compatibility-read-file-images.zh.md)。+- Web 工具卡按 `source` 参数预览旧 Trace 里的 `read_image` / `describe_image` 调用,与文件工具按 `file_path` 预览同一方式。模型设置的文案、CLI 的视觉模型帮助与文档改以 `read_file` 指称读图。diff --git a/packages/cli/src/i18n.ts b/packages/cli/src/i18n.tsindex bf766e9a..c07b0307 100644--- a/packages/cli/src/i18n.ts+++ b/packages/cli/src/i18n.ts@@ -634,7 +634,8 @@ const en: Messages = {addPriceOutput: "Price per 1M tokens: output (USD)",addSetDefault: "Also set as the Project default model",defaultDesc: "Set the Project default model",- visionDesc: "Set the vision model used by read_image for non-vision session models",+ visionDesc:+ "Set the vision model that reads images for non-vision session models (read_file hands images to it)",refModelId: "Upstream model id; forms the (provider, model_id) pair reference with --provider",refProvider: "Provider group of the referenced entry (see `penguin config model list`)",listDesc: "List the Project's models (API keys hidden)",@@ -1158,7 +1159,7 @@ const zh: Messages = {addPriceOutput: "每百万 token 价格:输出(USD)",addSetDefault: "同时设为该 Project 的默认模型",defaultDesc: "设置 Project 的默认模型",- visionDesc: "设置 read_image 代读用的视觉模型(供不支持图片的会话模型读图)",+ visionDesc: "设置代读图片的视觉模型(不支持图片的会话模型用 read_file 读图时由它代读)",refModelId: "上游模型 id;与 --provider 构成 (provider, model_id) 成对引用",refProvider: "引用条目的 provider 分组(见 `penguin config model list`)",listDesc: "列出当前 Project 的模型(API key 隐藏)",diff --git a/packages/cli/src/tool-render.ts b/packages/cli/src/tool-render.tsindex b4af4506..6e8552f3 100644--- a/packages/cli/src/tool-render.ts+++ b/packages/cli/src/tool-render.ts@@ -342,6 +342,8 @@ export function renderFileToolApprovalPayload(name: string, argsJson: string): sif (name === "read_file") {pushField("offset", args["offset"]);pushField("limit", args["limit"]);+ // The image branch's question is sent to the vision model, so it is part of what is approved.+ pushField("prompt", args["prompt"]);} else if (name === "edit_file") {pushField("old_string", args["old_string"]);pushField("new_string", args["new_string"]);diff --git a/packages/cli/test/tool-render.test.ts b/packages/cli/test/tool-render.test.tsindex 6b93939e..6df5d68d 100644--- a/packages/cli/test/tool-render.test.ts+++ b/packages/cli/test/tool-render.test.ts@@ -251,6 +251,13 @@ describe("renderFileToolApprovalPayload", () => {expect(renderFileToolApprovalPayload("read_file", '{"file_path":"a.txt","offset":3,"limit":5}'),).toBe(["file_path: a.txt", "offset: 3", "limit: 5"].join("\n"));+ // read_file's image branch forwards `prompt` to the vision model: it must be visible too.+ expect(+ renderFileToolApprovalPayload(+ "read_file",+ '{"file_path":"shot.png","prompt":"read the error"}',+ ),+ ).toBe(["file_path: shot.png", "prompt: read the error"].join("\n"));});it("bounds the payload to a line count with an explicit elision note", () => {diff --git a/packages/core/src/agent.ts b/packages/core/src/agent.tsindex 6e0b5c86..505f660b 100644--- a/packages/core/src/agent.ts+++ b/packages/core/src/agent.ts@@ -395,9 +395,9 @@ export class Agent {// Tool exposure is capped by depth: a (leaf) child Agent that has reached the max spawn// depth no longer gets run_subagent or input_subagent (the latter depends on the// subagent_id produced by the former, so exposing it alone is meaningless). Tool entries- // are also selected by the session model's type (marked via forModel: vision models use- // read_image, text-only models use describe_image; entries without this marker are- // unaffected).+ // are also selected by the session model's type through their forModel annotation+ // (entries without it are unaffected — the built-in set carries none; read_file decides+ // per model at runtime through the injected vision describer).const canSpawn = spec.subagentDepth < MAX_SUBAGENT_DEPTH;const baseToolConfig = buildToolConfig(state);const modelVision = spec.modelEntry.vision !== false;@@ -966,11 +966,12 @@ export class Agent {}// When the session model doesn't support images (vision=false): inject a vision- // model service for describe_image (forModel: "text-only", selected by the tool- // filter in assembleContext) — images are described by the Project config's- // vision_model (a paired reference), and the tool returns text. Even when unconfigured- // or invalid, it is still injected (modelId=null); the tool then finishes with a failed- // explanation, and images are never allowed into that session's history.+ // model service for read_file's image branch — images are described by the Project+ // config's vision_model (a paired reference), and the tool returns text instead of+ // image content. Even when unconfigured or invalid, it is still injected (modelId=null):+ // its presence is what tells read_file the session model cannot view images; the tool+ // then finishes with a failed explanation, and images are never allowed into that+ // session's history.let visionDescriber: VisionDescriberService | undefined;if (modelEntry.vision === false) {const visionRef = this.projectConfig.vision_model;diff --git a/packages/core/src/environment/environment.ts b/packages/core/src/environment/environment.tsindex 93de10ff..13660e9a 100644--- a/packages/core/src/environment/environment.ts+++ b/packages/core/src/environment/environment.ts@@ -472,9 +472,10 @@ export class Environment implements EnvironmentInterface {* Only lists tools that have been assembled (i.e. supported by the registry) — tool names* unrecognized in config are not exposed to the LLM (consistent with the constructor);* the definition (description/parameters) treats **the config entry as the single source of- * truth** — factories must not rewrite the definition at runtime; where a differentiated- * implementation is needed, use a separate explicit tool-name entry with a `forModel`- * annotation (e.g. read_image / describe_image).+ * truth** — factories must not rewrite the definition at runtime; a tool whose behavior+ * depends on the session model reads the injected services instead (read_file consults+ * `services.visionDescriber`), and a config that wants separate entries per model class+ * annotates them with `forModel`.* Only exposes `{name, description, parameters}`, dropping permission/maxOutputLength.* MCP Server tools follow the builtin list: the first call connects the configured* servers and appends their discovered tools as `mcp__<server>__<tool>` entriesdiff --git a/packages/core/src/environment/tools/command/limits.ts b/packages/core/src/environment/tools/command/limits.tsindex 7f687f41..d2c1fbad 100644--- a/packages/core/src/environment/tools/command/limits.ts+++ b/packages/core/src/environment/tools/command/limits.ts@@ -15,6 +15,8 @@ export const DEFAULT_WRITE_YIELD_MS = 250;* Default wait duration (milliseconds) for `input_command` on an empty poll: a default-length* poll waits out most builds/test runs in one call instead of ping-ponging short polls (data* still streams as it arrives — the wait only ends early on exit). Must stay below- * `input_command`'s `timeoutMs` minus the clamp margin (see ../background/limits.ts).+ * `input_command`'s default `timeoutMs` (120000, the same tier as `exec_command`) minus the+ * clamp margin (see ../background/limits.ts); the 10 s of headroom lets a default-length poll+ * return on its own instead of being cut off by the Environment's timeout fallback.*/-export const DEFAULT_EMPTY_POLL_YIELD_MS = 120_000;+export const DEFAULT_EMPTY_POLL_YIELD_MS = 110_000;diff --git a/packages/core/src/environment/tools/describe-image.ts b/packages/core/src/environment/tools/describe-image.tsdeleted file mode 100644index ab3f5ccc..00000000--- a/packages/core/src/environment/tools/describe-image.ts+++ /dev/null@@ -1,121 +0,0 @@-/**- * describe_image —— image-proxy-read tool, the text-only-model variant of read_image- * (`forModel: "text-only"`, see default-config.ts): the image itself is never fed back into- * the session model (some providers flatly 400 on a tool_result carrying an image); instead it- * is sent, together with the caller-supplied `prompt`, in a single one-off request to the- * Project-configured vision model (`vision_model`), and the vision model's text answer is- * returned as the tool's output.- *- * The tool definition (description/parameters, including `prompt`) comes entirely from the- * config entry; this implementation does no runtime rewriting — which tool is used for which- * model class is declared by the entry's `forModel` annotation, so the config file is what you get.- *- * Behavioral contract (shared with read_image): `source` supports http(s) URLs and local paths;- * validation/size limits are reused from `loadImage`; on failure, outputs explanatory text and- * finishes with `failed`, never throws; on interruption, only reports `aborted`. Messages from- * the internal one-off request never enter the parent session stream (no origin, not leaked out).- * Docs: /docs/tools § "Image tools".- */-import { imageUrlMessage, partialToolCallOutput, userText } from "../../omnimessage/index.js";-import type { OmniMessage } from "../../omnimessage/index.js";-import type {- LLMOutcome,- ToolDefinitionConfig,- VisionDescriberService,-} from "../../interfaces/index.js";-import type { BuiltinTool, ToolExecutionContext, ToolResult } from "./types.js";-import { formatSize, loadImage } from "./read-image.js";--/** Tool name constant (used only inside this tool module, not exposed to Environment). */-export const DESCRIBE_IMAGE_NAME = "describe_image";--/** Default question used when the caller doesn't supply a prompt. */-const DEFAULT_PROMPT =- "Describe this image in detail, including any visible text, numbers, UI elements and layout.";--/** Constructs the describe_image tool: definition (description/parameters) is taken as-is from the config entry. */-export function createDescribeImageTool(- definition: ToolDefinitionConfig,- describer: VisionDescriberService,-): BuiltinTool {- return {- name: DESCRIBE_IMAGE_NAME,- definition,- async *execute(- args: Record<string, unknown>,- ctx: ToolExecutionContext,- ): AsyncGenerator<OmniMessage, ToolResult | void> {- const { toolCallId, signal } = ctx;- const delta = (output: string): OmniMessage =>- partialToolCallOutput({ eventType: "delta", output, toolCallId });-- const source = args["source"];- if (typeof source !== "string" || source.length === 0) {- yield delta('Missing required argument "source" for describe_image.');- return { stopReason: "fatal" };- }- if (describer.modelId === null || describer.createLLM === undefined) {- yield delta(- "No vision model is configured for this project. The current model does not accept " +- "images; ask the user to pick a vision model in the model settings (vision_model) " +- "to enable image reading.",- );- return { stopReason: "fatal" };- }-- const res = await loadImage(source, ctx.workspaceDir, signal);- if (!res.ok) {- if (res.reason === "aborted") return { stopReason: "aborted" };- yield delta(res.message);- return { stopReason: "fatal" };- }-- const prompt =- typeof args["prompt"] === "string" && args["prompt"].trim().length > 0- ? args["prompt"]- : DEFAULT_PROMPT;- const dataUrl = `data:${res.mime};base64,${res.bytes.toString("base64")}`;-- // One-off vision model request: prompt + image are merged into a single user message;- // its text deltas (partial_text delta) are forwarded in real time as this tool's own- // output delta — the description streams out piece by piece, not buffered as a whole.- // Partial concatenation == the full message (see generative-model.ts), so the full text- // is not forwarded again; other messages like thinking/token_usage are ignored, never- // leaked into the parent session.- const llm = describer.createLLM();- const gen = llm.streamGenerate({- newMessages: [userText(prompt), imageUrlMessage(dataUrl)],- ...(signal ? { signal } : {}),- });- yield delta(- `${res.mime}, ${formatSize(res.bytes.length)} — described by ${describer.modelId}:\n`,- );- let streamedAny = false;- let outcome: LLMOutcome | undefined;- for (;;) {- const step = await gen.next();- if (step.done) {- outcome = step.value;- break;- }- const p = step.value.payload as { type?: string; event_type?: string; text?: string };- if (p.type === "partial_text" && p.event_type === "delta" && p.text) {- streamedAny = true;- yield delta(p.text);- }- }- if (signal?.aborted) return { stopReason: "aborted" };- if (!outcome || outcome.status !== "completed") {- const detail =- outcome && "errorMessage" in outcome && outcome.errorMessage- ? `: ${outcome.errorMessage}`- : "";- yield delta(- `${streamedAny ? "\n" : ""}Vision model (${describer.modelId}) request ${outcome?.status ?? "failed"}${detail}`,- );- return { stopReason: "fatal" };- }- if (!streamedAny) yield delta("[vision model returned no text]");- },- };-}diff --git a/packages/core/src/environment/tools/read-image.ts b/packages/core/src/environment/tools/image-source.tssimilarity index 61%rename from packages/core/src/environment/tools/read-image.tsrename to packages/core/src/environment/tools/image-source.tsindex ce06b8b9..bd4d6f69 100644--- a/packages/core/src/environment/tools/read-image.ts+++ b/packages/core/src/environment/tools/image-source.ts@@ -1,35 +1,14 @@/**- * read_image — image-reading tool, a builtin tool implementation (BuiltinTool).+ * Image loading for read_file's image branch: which sources count as images, how their bytes+ * are fetched (an http(s) URL through the global fetch, anything else as a path resolved+ * against the Workspace), and the validation every image passes (size cap, supported mime).*- * Reads an image and feeds it back to the model as **image content**: if `source` is an http(s)- * URL, downloads it with the global fetch (respecting the abort signal); otherwise reads it as a- * local file path (relative paths are resolved against the Workspace). Only png/jpeg/gif/webp- * are allowed (determined in order by response header / magic number / extension); errors out- * above 5MB.- *- * Division of responsibility with Environment (see environment.ts): on success, yields a brief- * descriptive delta (e.g. `image/png, 123.4 kB`), while the image itself is carried via the- * return value `ToolResult.images` (a data URL) for Environment to attach when closing out (a- * single streaming delta carries it all at once before stop, plus the final complete- * `tool_call_output`); on failure, yields explanatory text and closes with `failed`, **never- * throwing**; if interrupted, only reports `aborted` — the interruption note is appended by- * Environment.- *- * This tool is only used by sessions with a model that supports images (config entry- * `forModel: "vision"`); text-only models use describe_image instead (the image is handed to a- * configured vision model to describe, returning text — see describe-image.ts), and the image- * loading/validation logic is shared via `loadImage`.- * Docs: /docs/tools § "Image tools".+ * Detection order is magic number → response content-type (URLs only) → extension: a file+ * whose bytes say PNG is an image whatever it is called, and a `.png` path with unrecognized+ * bytes is still handed over as an image rather than dumped as text.*/import path from "node:path";-import { readFile, stat } from "node:fs/promises";-import { partialToolCallOutput } from "../../omnimessage/index.js";-import type { OmniMessage } from "../../omnimessage/index.js";-import type { ToolDefinitionConfig } from "../../interfaces/index.js";-import type { BuiltinTool, ToolExecutionContext, ToolResult } from "./types.js";--/** Tool name constant (used only within this tool module, never exposed to Environment). */-export const READ_IMAGE_NAME = "read_image";+import { open, readFile, stat } from "node:fs/promises";/*** Image size upper bound (bytes): errors out above this. Taken as the common denominator of@@ -52,8 +31,11 @@ const EXT_TO_MIME: Record<string, string> = {".webp": "image/webp",};+/** Bytes that decide every supported magic number (the WebP RIFF header is the longest). */+const SNIFF_BYTES = 12;+/** Sniffs the mime type from the file header's magic number; returns null if unrecognized. */-function sniffMime(buf: Buffer): string | null {+function sniffImageMime(buf: Buffer): string | null {if (buf.length >= 8 && buf.readUInt32BE(0) === 0x89504e47) return "image/png";if (buf.length >= 3 && buf[0] === 0xff && buf[1] === 0xd8 && buf[2] === 0xff) {return "image/jpeg";@@ -73,10 +55,40 @@ function sniffMime(buf: Buffer): string | null {}/** Infers the mime type from a path / URL pathname's extension; returns null if it can't be inferred. */-function mimeFromExt(p: string): string | null {+function imageMimeFromExt(p: string): string | null {return EXT_TO_MIME[path.extname(p).toLowerCase()] ?? null;}+/** Whether a source is an http(s) URL — the only kind of source that is never a local path. */+export function isHttpUrl(source: string): boolean {+ return /^https?:\/\//i.test(source);+}++/**+ * Whether a local file is an image: judged by its leading bytes, then by its extension. A+ * file that cannot be opened is judged by extension alone — the caller's own read reports+ * the error afterwards.+ */+export async function looksLikeImageFile(filePath: string): Promise<boolean> {+ let fd;+ try {+ fd = await open(filePath, "r");+ } catch {+ return imageMimeFromExt(filePath) !== null;+ }+ try {+ const head = Buffer.alloc(SNIFF_BYTES);+ const { bytesRead } = await fd.read(head, 0, SNIFF_BYTES, 0);+ return (+ sniffImageMime(head.subarray(0, bytesRead)) !== null || imageMimeFromExt(filePath) !== null+ );+ } catch {+ return imageMimeFromExt(filePath) !== null;+ } finally {+ await fd.close();+ }+}+/** Byte count -> human-readable size (B / kB / MB, one decimal place). */export function formatSize(bytes: number): string {if (bytes < 1024) return `${bytes} B`;@@ -98,10 +110,9 @@ export type LoadImageResult =| { ok: false; reason: "failed"; message: string };/**- * Reads and validates an image (shared by read_image and describe_image):- * an http(s) URL is downloaded with the global fetch, otherwise read as a local path (resolved- * against Workspace); validates the size upper bound and mime type (determined in order by- * response header / magic number / extension). Never throws.+ * Reads and validates an image: an http(s) URL is downloaded with the global fetch, otherwise+ * read as a local path (resolved against Workspace); validates the size upper bound and mime+ * type (determined in order by response header / magic number / extension). Never throws.*/export async function loadImage(source: string,@@ -112,7 +123,7 @@ export async function loadImage(let bytes: Buffer;let mime: string | null;- if (/^https?:\/\//i.test(source)) {+ if (isHttpUrl(source)) {// URL branch: downloads via the global fetch (abort signal passed through to the request);// mime is preferentially taken from the response header, falling back to magic number / URL// extension.@@ -155,11 +166,11 @@ export async function loadImage(const headerMime = (res.headers.get("content-type") ?? "").split(";")[0]!.trim().toLowerCase();let urlExtMime: string | null = null;try {- urlExtMime = mimeFromExt(new URL(source).pathname);+ urlExtMime = imageMimeFromExt(new URL(source).pathname);} catch {urlExtMime = null; // A URL parse failure only affects the extension fallback}- mime = SUPPORTED_MIMES.has(headerMime) ? headerMime : (sniffMime(bytes) ?? urlExtMime);+ mime = SUPPORTED_MIMES.has(headerMime) ? headerMime : (sniffImageMime(bytes) ?? urlExtMime);if (mime === null && headerMime) mime = headerMime; // Include the real response type in the error} else {// Local-path branch: relative paths are resolved against Workspace; stat first to check the@@ -189,7 +200,7 @@ export async function loadImage(message: `Failed to read image "${source}": ${message}`,};}- mime = sniffMime(bytes) ?? mimeFromExt(filePath);+ mime = sniffImageMime(bytes) ?? imageMimeFromExt(filePath);}if (signal?.aborted) return { ok: false, reason: "aborted" };@@ -207,42 +218,3 @@ export async function loadImage(}return { ok: true, bytes, mime };}--/**- * read_image builtin tool: reads a local file or downloads a URL, validates its type and size,- * then outputs a data URL image. `definition` is overridden by Environment at construction time- * with the same-named entry from ToolConfig (description/arguments/permissions/limits).- */-export function createReadImageTool(definition: ToolDefinitionConfig): BuiltinTool {- return {- name: READ_IMAGE_NAME,- definition,- async *execute(- args: Record<string, unknown>,- ctx: ToolExecutionContext,- ): AsyncGenerator<OmniMessage, ToolResult | void> {- const { toolCallId, signal } = ctx;- const delta = (output: string): OmniMessage =>- partialToolCallOutput({ eventType: "delta", output, toolCallId });-- const source = args["source"];- if (typeof source !== "string" || source.length === 0) {- yield delta('Missing required argument "source" for read_image.');- return { stopReason: "fatal" };- }-- const res = await loadImage(source, ctx.workspaceDir, signal);- if (!res.ok) {- if (res.reason === "aborted") return { stopReason: "aborted" };- yield delta(res.message);- return { stopReason: "fatal" };- }-- // Success: yield a brief one-line description as a text delta (both in the streaming and- // complete message), while the image itself is carried via the return value for- // Environment to attach.- yield delta(`${res.mime}, ${formatSize(res.bytes.length)}`);- return { images: [`data:${res.mime};base64,${res.bytes.toString("base64")}`] };- },- };-}diff --git a/packages/core/src/environment/tools/read-file.ts b/packages/core/src/environment/tools/read-file.tsindex 766ceda6..64636a8e 100644--- a/packages/core/src/environment/tools/read-file.ts+++ b/packages/core/src/environment/tools/read-file.ts@@ -1,14 +1,30 @@/**- * read_file — text-file reading tool, a builtin tool implementation (BuiltinTool).+ * read_file — file reading tool, a builtin tool implementation (BuiltinTool): a text file as+ * a numbered window, an image as image content or as a vision model's description.*- * Reads a text file and returns it in `cat -n` style (line number, tab, content), so the- * model can quote exact lines back to edit_file. Relative paths resolve against the- * Workspace; absolute paths are allowed (tools run with the user's full permissions, same- * as the shell tool). An optional 1-based `offset` and a `limit` (default 2000 lines) form- * a window for paging through long files.+ * Text files come back in `cat -n` style (line number, tab, content), so the model can quote+ * exact lines back to edit_file. Relative paths resolve against the Workspace; absolute+ * paths are allowed (tools run with the user's full permissions, same as the shell tool). An+ * optional 1-based `offset` and a `limit` (default 2000 lines) form a window for paging+ * through long files.+ *+ * Images (png/jpeg/gif/webp, ≤5MB; `file_path` may also be an http(s) URL, which is only ever+ * an image source) are recognized by magic number, then — for a URL — the response+ * content-type, then the extension, and loaded through image-source.ts. What happens next is+ * decided by the injected `services.visionDescriber`, present exactly when the session model+ * does not accept images:+ * - absent (the session model views images): yields a one-line `image/png, 123.4 kB` delta and+ * returns the image via `ToolResult.images` for Environment to attach (a single streaming+ * delta carries it whole before stop, and the complete `tool_call_output` carries it again);+ * - present: the image and the caller's `prompt` (default: a detailed description) go in one+ * one-off request to the Project's `vision_model`, whose text deltas stream back as this+ * tool's own output; nothing of that request (thinking, token_usage) leaks into the parent+ * session stream. Some providers flatly 400 on a tool_result carrying an image, which is why+ * a text-only session never gets the image itself. A describer without a model+ * (`modelId: null`) ends with a fatal explanation asking the user to configure one.** Robustness properties:- * - **Bounded read**: the file is scanned incrementally through a file handle, never loaded+ * - **Bounded read**: a text file is scanned incrementally through a file handle, never loaded* whole — a multi-GB log cannot balloon the process. A hard scan cap (8MB) turns* pathological requests (offsets deeper than the cap, files with no newlines) into a* clean failure with guidance; a window that already produced lines when the cap hits is@@ -17,22 +33,31 @@* maxOutputLength before Environment's front-keep truncation could cut the trailing* continuation note — the note (and the shown range it reports) always survives.* - Overlong single lines are truncated with a marker; CRLF files display without the `\r`- * and get an explicit note; binary content (NUL bytes) is rejected with advice; the- * secret stores (.vault.toml / .project_config.toml) are refused outright.+ * and get an explicit note; binary content that is not a supported image (NUL bytes) is+ * rejected with advice; the secret stores (.vault.toml / .project_config.toml) are refused+ * outright.*- * Division of responsibility with Environment (see environment.ts): non-streaming — yields- * the whole numbered listing as one delta; failures (missing file, directory, binary- * content, scan cap) are explanatory text finalized as `failed`; anything unexpected that- * still throws is caught by Environment and likewise finalized as failed. If interrupted,- * only reports `aborted` — the interruption note is appended by Environment.+ * Division of responsibility with Environment (see environment.ts): a text read yields the+ * whole numbered listing as one delta; failures (missing file, directory, binary content,+ * scan cap, unsupported or oversized image, vision request failure) are explanatory text+ * finalized as `failed`; anything unexpected that still throws is caught by Environment and+ * likewise finalized as failed. If interrupted, only reports `aborted` — the interruption+ * note is appended by Environment.* Docs: /docs/tools § "File tools".*/import { modelVisiblePath } from "../../internal/model-visible-path.js";import path from "node:path";import { open, realpath, stat } from "node:fs/promises";-import { partialToolCallOutput } from "../../omnimessage/index.js";+import { imageUrlMessage, partialToolCallOutput, userText } from "../../omnimessage/index.js";import type { OmniMessage } from "../../omnimessage/index.js";-import type { ToolDefinitionConfig } from "../../interfaces/index.js";+import type {+ EnvironmentServices,+ LLMInterface,+ LLMOutcome,+ ToolDefinitionConfig,+ VisionDescriberService,+} from "../../interfaces/index.js";+import { formatSize, isHttpUrl, loadImage, looksLikeImageFile } from "./image-source.js";import { missingPathHint } from "./path-hint.js";import type { BuiltinTool, ToolExecutionContext, ToolResult } from "./types.js";@@ -48,6 +73,10 @@ export const MAX_LINE_LENGTH = 2000;/** Hard cap on bytes scanned per call: beyond it the tool stops instead of grinding through a huge file. */export const READ_FILE_SCAN_CAP_BYTES = 8 * 1024 * 1024;+/** Question put to the vision model when an image is read on a text-only session without a caller `prompt`. */+export const DEFAULT_IMAGE_PROMPT =+ "Describe this image in detail, including any visible text, numbers, UI elements and layout.";+/** Bytes read per file-handle read (scan granularity; also the abort-signal check interval). */const CHUNK_BYTES = 256 * 1024;@@ -60,6 +89,15 @@ const NOTE_RESERVE = 256;/** Fallback output budget when the definition carries no maxOutputLength (mirrors the default config entry). */const DEFAULT_OUTPUT_BUDGET = 64000;+/**+ * Told to a text-only session whose Project names no usable vision model: the model is asked+ * to have the user pick one, since nothing else can make the image readable.+ */+const NO_VISION_MODEL_MESSAGE =+ "No vision model is configured for this project. The current model does not accept " ++ "images; ask the user to pick a vision model in the model settings (vision_model) " ++ "to enable image reading.";+/*** Secret stores the system prompt bans the model from reading; read_file refuses them by* basename regardless of directory. The tool needs its own guard because `permission: "r"`@@ -235,13 +273,115 @@ async function scanWindow(}}+/** A describer that can actually describe: the Project names a vision model and the service builds its LLM. */+interface ConfiguredDescriber {+ modelId: string;+ createLLM: () => LLMInterface;+}++function configuredDescriber(describer: VisionDescriberService): ConfiguredDescriber | null {+ return describer.modelId !== null && describer.createLLM !== undefined+ ? { modelId: describer.modelId, createLLM: describer.createLLM }+ : null;+}+/**- * read_file builtin tool: resolves the path against the Workspace, validates it is a- * readable text file, and outputs the requested line window with line numbers.+ * The image branch: loads and validates the image, then either returns it as image content+ * (no describer: the session model views images) or streams the vision model's answer to+ * `prompt` as text (describer present: the session model is text-only).+ */+async function* readImageSource(+ source: string,+ args: Record<string, unknown>,+ ctx: ToolExecutionContext,+ describer: VisionDescriberService | undefined,+ delta: (output: string) => OmniMessage,+): AsyncGenerator<OmniMessage, ToolResult | void> {+ const { signal } = ctx;+ let proxy: ConfiguredDescriber | null = null;+ if (describer !== undefined) {+ proxy = configuredDescriber(describer);+ if (proxy === null) {+ // Checked before loading: an unreadable image is not what stands between this session+ // and image reading, the missing vision model is.+ yield delta(NO_VISION_MODEL_MESSAGE);+ return { stopReason: "fatal" };+ }+ }++ const res = await loadImage(source, ctx.workspaceDir, signal);+ if (!res.ok) {+ if (res.reason === "aborted") return { stopReason: "aborted" };+ yield delta(res.message);+ return { stopReason: "fatal" };+ }+ const dataUrl = `data:${res.mime};base64,${res.bytes.toString("base64")}`;++ if (proxy === null) {+ // The session model views images: a brief one-line description as the text delta (both+ // in the streaming and complete message), the image itself via the return value for+ // Environment to attach.+ yield delta(`${res.mime}, ${formatSize(res.bytes.length)}`);+ return { images: [dataUrl] };+ }++ const prompt =+ typeof args["prompt"] === "string" && args["prompt"].trim().length > 0+ ? args["prompt"]+ : DEFAULT_IMAGE_PROMPT;++ // One-off vision model request: prompt + image are merged into a single user message; its+ // text deltas (partial_text delta) are forwarded in real time as this tool's own output+ // delta — the description streams out piece by piece, not buffered as a whole. Partial+ // concatenation == the full message (see generative-model.ts), so the full text is not+ // forwarded again; other messages like thinking/token_usage are ignored, never leaked into+ // the parent session.+ const llm = proxy.createLLM();+ const gen = llm.streamGenerate({+ newMessages: [userText(prompt), imageUrlMessage(dataUrl)],+ ...(signal ? { signal } : {}),+ });+ yield delta(`${res.mime}, ${formatSize(res.bytes.length)} — described by ${proxy.modelId}:\n`);+ let streamedAny = false;+ let outcome: LLMOutcome | undefined;+ for (;;) {+ const step = await gen.next();+ if (step.done) {+ outcome = step.value;+ break;+ }+ const p = step.value.payload as { type?: string; event_type?: string; text?: string };+ if (p.type === "partial_text" && p.event_type === "delta" && p.text) {+ streamedAny = true;+ yield delta(p.text);+ }+ }+ if (signal?.aborted) return { stopReason: "aborted" };+ if (!outcome || outcome.status !== "completed") {+ const detail =+ outcome && "errorMessage" in outcome && outcome.errorMessage+ ? `: ${outcome.errorMessage}`+ : "";+ yield delta(+ `${streamedAny ? "\n" : ""}Vision model (${proxy.modelId}) request ${outcome?.status ?? "failed"}${detail}`,+ );+ return { stopReason: "fatal" };+ }+ if (!streamedAny) yield delta("[vision model returned no text]");+}++/**+ * read_file builtin tool: resolves the path against the Workspace, then reads it as a text+ * window or — for an image (or an http(s) URL) — through the image branch above.* `definition` is overridden by Environment at construction time with the same-named entry- * from ToolConfig (description/arguments/permissions/limits).+ * from ToolConfig (description/arguments/permissions/limits). `services.visionDescriber`,+ * when injected, marks the session model as text-only and supplies the proxy reader.*/-export function createReadFileTool(definition: ToolDefinitionConfig): BuiltinTool {+export function createReadFileTool(+ definition: ToolDefinitionConfig,+ services?: EnvironmentServices,+): BuiltinTool {+ const describer = services?.visionDescriber;return {name: definition.name,definition,@@ -273,6 +413,11 @@ export function createReadFileTool(definition: ToolDefinitionConfig): BuiltinToo}const limit = limitArg.value;+ // A URL is only ever an image source: no path resolution, no text window.+ if (isHttpUrl(filePath)) {+ return yield* readImageSource(filePath, args, ctx, describer, delta);+ }+const resolved = path.resolve(ctx.workspaceDir, filePath);// Secret stores are refused by name: read_file is auto-approved under read-only// approval, so it needs its own guard (aligned with the system prompt's ban).@@ -319,6 +464,11 @@ export function createReadFileTool(definition: ToolDefinitionConfig): BuiltinTooreturn;}+ // Images take the image branch whatever offset/limit say; everything else is text.+ if (await looksLikeImageFile(resolved)) {+ return yield* readImageSource(filePath, args, ctx, describer, delta);+ }+let scan: ScanOutcome;try {scan = await scanWindow(resolved, offset, limit, signal);@@ -331,7 +481,7 @@ export function createReadFileTool(definition: ToolDefinitionConfig): BuiltinTooif (scan.aborted || signal?.aborted) return { stopReason: "aborted" };if (scan.binary) {yield delta(- `"${filePath}" looks like a binary file (contains NUL bytes). Use shell commands to inspect it, or read_image if it is an image.`,+ `"${filePath}" looks like a binary file (contains NUL bytes) and is not a supported image (png/jpeg/gif/webp). Use shell commands to inspect it.`,);return { stopReason: "fatal" };}diff --git a/packages/core/src/environment/tools/registry.ts b/packages/core/src/environment/tools/registry.tsindex bbd1b421..5a01eed9 100644--- a/packages/core/src/environment/tools/registry.ts+++ b/packages/core/src/environment/tools/registry.ts@@ -6,7 +6,10 @@* description/parameters/permission/maxOutputLength from config are injected into the tool's* `definition` by each factory, and the runtime tool name follows the config entry's name.* When adding a new built-in tool, just register one factory entry here — no changes to- * Environment needed.+ * Environment needed. A stored entry whose name has no factory (a tool removed since the+ * config was written, e.g. `kill_command`, `read_image`, `describe_image`) is skipped:+ * neither listed to the model nor executable, and a call by that name gets the standard+ * unknown-tool reply.** Docs: packages/docs/content/tools.{zh,en}.md (site path /docs/tools) documents every* built-in tool and the approval flow — keep the page in sync when this table changes.@@ -20,13 +23,12 @@ import { EXEC_COMMAND_NAME, createExecCommandTool } from "./exec-command.js";import { INPUT_COMMAND_NAME, createInputCommandTool } from "./input-command.js";import { SUBAGENT_NAME, createSubagentTool } from "./run-subagent.js";import { INPUT_SUBAGENT_NAME, createInputSubagentTool } from "./input-subagent.js";-import { READ_IMAGE_NAME, createReadImageTool } from "./read-image.js";-import { DESCRIBE_IMAGE_NAME, createDescribeImageTool } from "./describe-image.js";/*** A factory that constructs a BuiltinTool instance from a tool config entry; optionally* receives runtime services injected by Environment.- * Most tools ignore `services`; only a few (e.g. `run_subagent`) use it.+ * Most tools ignore `services`; a few use it (`run_subagent` for the runner, `read_file` for+ * the vision describer that tells it the session model cannot view images).*/export type BuiltinToolFactory = (definition: ToolDefinitionConfig,@@ -42,12 +44,4 @@ export const BUILTIN_TOOL_FACTORIES: Record<string, BuiltinToolFactory> = {[INPUT_COMMAND_NAME]: createInputCommandTool,[SUBAGENT_NAME]: createSubagentTool,[INPUT_SUBAGENT_NAME]: createInputSubagentTool,- [READ_IMAGE_NAME]: createReadImageTool,- // describe_image: the text-only-model variant of read_image (hands the image to the- // configured vision model for description, returns text).- // Which tool is used for which model class is declared by the config entry's forModel- // annotation; before assembly, selectBuiltinToolsForModel has already filtered out entries- // that don't apply to the session's model.- [DESCRIBE_IMAGE_NAME]: (definition, services) =>- createDescribeImageTool(definition, services?.visionDescriber ?? { modelId: null }),};diff --git a/packages/core/src/environment/tools/types.ts b/packages/core/src/environment/tools/types.tsindex b14a1229..c14df65a 100644--- a/packages/core/src/environment/tools/types.ts+++ b/packages/core/src/environment/tools/types.ts@@ -39,7 +39,7 @@ export interface ToolResult {*/note?: string;/**- * Images carried by the tool output (e.g. an image read by read_image): each entry is a+ * Images carried by the tool output (e.g. an image read by read_file): each entry is a* `data:<mime>;base64,...` data URL. Attached by Environment during close-out: a single* streaming delta carries it all at once before stop, plus the final complete* `tool_call_output` (only carried on normal completion; images are not chunked and don'tdiff --git a/packages/core/src/interfaces/environment.ts b/packages/core/src/interfaces/environment.tsindex 75c0c928..8c983516 100644--- a/packages/core/src/interfaces/environment.ts+++ b/packages/core/src/interfaces/environment.ts@@ -38,9 +38,10 @@ export interface ToolDefinitionConfig {permission?: ToolPermission;/*** Which class of session model this entry targets: `"vision"` only for models that support- * images (e.g. read_image), `"text-only"` only for text-only models (e.g. describe_image);- * omitted means available for all models. Filtered by session model at assembly time- * (see `selectBuiltinToolsForModel`).+ * images, `"text-only"` only for text-only models; omitted means available for all models.+ * Filtered by session model at assembly time (see `selectBuiltinToolsForModel`). The+ * built-in defaults set it on no entry — read_file serves both classes and decides at+ * runtime — so it is a config feature for entries that need a per-class definition.*/forModel?: "vision" | "text-only";/** Timeout for a single tool call (ms); on timeout, ends as `failed`; <=0 disables it. */@@ -206,10 +207,11 @@ export interface SubagentRunner {}/**- * Proxy-reading service for describe_image: injected when the session model doesn't support- * images (vision=false) — images are handed to the configured vision model for description and- * the tool returns text, avoiding a 400 from feeding images back into a tool_result for a- * provider that doesn't support images.+ * Proxy-reading service for read_file's image branch: injected when the session model doesn't+ * support images (vision=false) — images are handed to the configured vision model for+ * description and the tool returns text, avoiding a 400 from feeding images back into a+ * tool_result for a provider that doesn't support images. Its presence is also how read_file+ * learns the session model cannot view images: absent, an image is returned as image content.* Docs: /docs/interfaces § "VisionDescriberService".*/export interface VisionDescriberService {@@ -225,7 +227,7 @@ export interface VisionDescriberService {*/export interface EnvironmentServices {subagentRunner?: SubagentRunner;- /** Injected when the session model doesn't support images: for describe_image's single-shot vision-model proxy reading. */+ /** Injected when (and only when) the session model doesn't support images: read_file then describes an image through it instead of returning image content. */visionDescriber?: VisionDescriberService;/** Registry of long-running command sessions (shared by `exec_command` / `input_command`); constructed and injected internally by Environment. */commandSessions?: CommandSessionManager;diff --git a/packages/core/src/internal/session-support.ts b/packages/core/src/internal/session-support.tsindex cf7b0835..f2db9d23 100644--- a/packages/core/src/internal/session-support.ts+++ b/packages/core/src/internal/session-support.ts@@ -153,7 +153,7 @@ const isImage = (m: OmniMessage): boolean => (m.payload as { type?: string }).ty* session scratchpad; http(s) URLs are referenced* as-is), and the path/URL is appended to the user text (an `[attached image: …]`* line); the image message itself is removed from the input — the model views it by- * path via describe_image (read on its behalf by a vision model), and images never+ * path via read_file (which has a vision model read it on its behalf), and images never* enter that session's history directly.* Returns the input unchanged when there are no images; an image that can't be* parsed is replaced with an explanatory line rather than silently dropped.diff --git a/packages/core/src/llm/context-limits.ts b/packages/core/src/llm/context-limits.tsindex e420efac..62cb60cc 100644--- a/packages/core/src/llm/context-limits.ts+++ b/packages/core/src/llm/context-limits.ts@@ -128,7 +128,7 @@ export function approximateTokens(text: string): number {** Images appear in two shapes and both must bypass the character count: as a payload of* their own (`image_url` / `inline_data`), and as the `images` array of data URLs riding- * on a tool output (complete or partial — `read_image` and screenshot-returning tools).+ * on a tool output (complete or partial — `read_file` on an image and screenshot-returning tools).* Serializing those data URLs would count every base64 character: a 1 MB image would* estimate ≈ 262k "tokens" (~163x over) and floor the next request's output cap even on a* 128k window (PR #235 review).diff --git a/packages/core/src/omnimessage/markers/attachment-lines.ts b/packages/core/src/omnimessage/markers/attachment-lines.tsindex 683a9fc5..54137040 100644--- a/packages/core/src/omnimessage/markers/attachment-lines.ts+++ b/packages/core/src/omnimessage/markers/attachment-lines.ts@@ -12,7 +12,7 @@* itself, so the message carries their path instead):* - `[attached image: <path|URL>]` — core, when the session model has no image input: the* input images are written to the session scratchpad and the model reads them by path via- * describe_image (see internal/session-support.ts);+ * read_file (see internal/session-support.ts);* - `[attached file: <path>]` — the server, for the composer's file attachments: the upload* lands in the session scratchpad and the model opens it with its ordinary file tools* (see services/task-attachments.ts).diff --git a/packages/core/src/omnimessage/types.ts b/packages/core/src/omnimessage/types.tsindex 58ddb01e..17fb7533 100644--- a/packages/core/src/omnimessage/types.ts+++ b/packages/core/src/omnimessage/types.ts@@ -233,7 +233,7 @@ export interface ToolCallOutputPayload {output: string;/*** Images carried by the tool output (optional): each is a `data:<mime>;base64,...` data URL,- * fed back to the model alongside the text (e.g. images read by read_image). Images aren't+ * fed back to the model alongside the text (e.g. images read by read_file). Images aren't* incremental: the streaming path carries the whole set once via a single delta (see* `PartialToolCallOutputPayload.images`), and the complete message carries them again — the* streamed-and-joined result equals the complete message.diff --git a/packages/core/src/session.ts b/packages/core/src/session.tsindex 82439294..9abb7091 100644--- a/packages/core/src/session.ts+++ b/packages/core/src/session.ts@@ -111,7 +111,7 @@ export interface SessionConfig {/*** This Session's scratchpad directory: where an input image is saved when it becomes an* `[attached image: <path>]` line instead of riding the request as an image. The model- * reads it back with describe_image / read_image, and the Web turns the path into a+ * reads it back with read_file, and the Web turns the path into a* thumbnail again. Always set — each input path decides on its own whether to use it.*/imagesDir: string;diff --git a/packages/core/src/state/agent-state.ts b/packages/core/src/state/agent-state.tsindex df5702c7..1145d424 100644--- a/packages/core/src/state/agent-state.ts+++ b/packages/core/src/state/agent-state.ts@@ -932,9 +932,10 @@ export function assembleSystemPrompt(/*** Filters builtin tool entries by the session model's type: entries with `forModel: "vision"` are* only used for models that support images (vision models), `forModel: "text-only"` is only for- * text-only models (e.g. choosing between read_image / describe_image); unlabeled entries are- * available to all models.- * Docs: /docs/tools § "Image tools".+ * text-only models; unlabeled entries are available to all models. The built-in defaults label+ * no entry (read_file serves both classes), so this only acts on configs that declare their own+ * per-class entries.+ * Docs: /docs/tools § "Configuration fields".*/export function selectBuiltinToolsForModel(tools: ToolDefinitionConfig[],diff --git a/packages/core/src/state/default-config.ts b/packages/core/src/state/default-config.tsindex a5d539d0..8b56339f 100644--- a/packages/core/src/state/default-config.ts+++ b/packages/core/src/state/default-config.ts@@ -594,7 +594,10 @@ export const DEFAULT_COMPACTION_PROMPT =/*** Default built-in system tools: file reading/editing/writing first, then bash execution- * and subagent spawning.+ * and subagent spawning. No entry carries a `forModel` annotation: `read_file` serves vision+ * and text-only models alike (it reads images too, deciding at runtime whether to return+ * image content or a vision model's description), so the per-model-class filter stays a+ * config feature for entries that need it.* Docs: /docs/tools § "Built-in tools".*/function defaultBuiltinTools(): ToolDefinitionConfig[] {@@ -602,30 +605,41 @@ function defaultBuiltinTools(): ToolDefinitionConfig[] {{name: "read_file",description:- "Read a text file and return its content with line numbers (cat -n style) — the preferred " +- "way to inspect a file. Returns up to 2000 lines starting at the given offset; for longer " +- "files call again with offset to continue. Use the image tools for images and the shell " +- "tool for binary files.",+ "Read a file — the preferred way to inspect one. A text file comes back with line numbers " ++ "(cat -n style), up to 2000 lines starting at offset; for a longer file call again with " ++ "offset to continue. An image (png/jpeg/gif/webp up to 5MB; file_path may also be an " ++ "http(s) URL) is returned as image content for you to view, or — when the current model " ++ "cannot view images — described in text by the project's vision model, which answers " ++ "`prompt`. Other binary files are rejected: use the shell tool for those.",parameters: {type: "object",properties: {file_path: {type: "string",- description: "Path to the file to read; absolute, or relative to the workspace.",+ description:+ "Path to the file to read; absolute, or relative to the workspace. For an image, an http(s) URL is accepted too.",},offset: {type: "number",- description: "1-based line number to start reading from; defaults to 1.",+ description:+ "1-based line number to start reading from; defaults to 1. Ignored for images.",},limit: {type: "number",- description: "Max lines to read; defaults to 2000.",+ description: "Max lines to read; defaults to 2000. Ignored for images.",+ },+ prompt: {+ type: "string",+ description:+ "A question about an image (e.g. transcribe the text, describe the chart, locate a UI element), answered by the vision model when the current model cannot view images; defaults to a detailed description. Ignored for text files.",},},required: ["file_path"],},permission: "r",- timeoutMs: 30000,+ // Wide enough for an image read through the vision model: one download or file read plus+ // one one-shot vision request.+ timeoutMs: 60000,// Wider than the other tools' cap: a 2000-line window of code rarely fits in 16k characters.maxOutputLength: 64000,},@@ -758,15 +772,15 @@ function defaultBuiltinTools(): ToolDefinitionConfig[] {yield_time_ms: {type: "number",description:- "How long to wait for new output or exit before returning. Non-empty writes default to 250; empty polls default to 120000 so one poll waits out most builds (output still streams as it arrives, and the wait ends early on exit — pass a smaller value to peek at a long-lived process). Minimum 250, capped below the tool timeout.",+ "How long to wait for new output or exit before returning. Non-empty writes default to 250; empty polls default to 110000 so one poll waits out most builds (output still streams as it arrives, and the wait ends early on exit — pass a smaller value to peek at a long-lived process). Minimum 250, capped below the tool timeout.",},},required: ["description", "process_id"],},permission: "rw",call_description: true,- // An empty poll can wait out a build/test run (the yield ceiling is derived from timeoutMs, clamped inside the tool).- timeoutMs: 130000,+ // Same tier as exec_command; an empty poll's default wait (110000) sits under it (the yield ceiling is derived from timeoutMs, clamped inside the tool).+ timeoutMs: 120000,maxOutputLength: 16000,},{@@ -867,64 +881,6 @@ function defaultBuiltinTools(): ToolDefinitionConfig[] {timeoutMs: 600000,maxOutputLength: 16000,},- // The image-reading tools are mutually exclusive based on the session model's type- // (marked via each entry's forModel, filtered at assembly time): read_image is designed- // for vision models (the image is fed back as image content); describe_image is designed- // for text-only models (the image plus the prompt are sent to the Project's configured- // vision model, vision_model, whose text answer becomes the tool output).- {- name: "read_image",- forModel: "vision",- description:- "Read an image and return it as image content for you to view. Accepts an http(s) URL " +- "or a local file path (relative paths resolve against the workspace). " +- "Supports png/jpeg/gif/webp up to 5MB.",- parameters: {- type: "object",- properties: {- source: {- type: "string",- description:- "Image to read: an http(s) URL, or a local file path (absolute, or relative to the workspace).",- },- },- required: ["source"],- },- permission: "r",- timeoutMs: 60000,- maxOutputLength: 16000,- },- {- name: "describe_image",- forModel: "text-only",- description:- "Describe an image and return a TEXT description of it. The current model does not accept " +- "images directly, so the image is analyzed by the project's configured vision model and " +- "you get its text answer back. Use `prompt` to ask exactly what you need to know about " +- "the image (e.g. transcribe text, describe a chart, locate a UI element). Accepts an " +- "http(s) URL or a local file path (relative paths resolve against the workspace). " +- "Supports png/jpeg/gif/webp up to 5MB.",- parameters: {- type: "object",- properties: {- source: {- type: "string",- description:- "Image to read: an http(s) URL, or a local file path (absolute, or relative to the workspace).",- },- prompt: {- type: "string",- description:- "What to ask about the image; the vision model answers this. Defaults to a detailed description.",- },- },- required: ["source"],- },- permission: "r",- // Includes one vision-model request, so the timeout is slightly wider than plain image reading.- timeoutMs: 90000,- maxOutputLength: 16000,- },];}diff --git a/packages/core/src/state/kernel-history.ts b/packages/core/src/state/kernel-history.tsindex 5e34f01b..3656c03b 100644--- a/packages/core/src/state/kernel-history.ts+++ b/packages/core/src/state/kernel-history.ts@@ -22,7 +22,7 @@ import { createHash } from "node:crypto";* change without it moving. (The reverse — moving it with no default change — is inert rather* than an error: nothing is keyed by version, so there is no table to fall out of sync with.)*/-export const KERNEL_VERSION = "2026-09-03";+export const KERNEL_VERSION = "2026-09-10";function isPlainObject(value: unknown): value is Record<string, unknown> {return value !== null && typeof value === "object" && !Array.isArray(value);@@ -189,16 +189,21 @@ export function isKernelOutdated(kernelVersion: string | null | undefined): bool* upstream events, and a model that keeps its reasoning off the wire spends its whole* thinking phase inside the wait for the first one, which 120000 cut short. The runtime tab* moved.- * - `2026-09-03` (current) — the default system prompt's # File system section gained a+ * - `2026-09-03` — the default system prompt's # File system section gained a* search-scope rule: searches run from `CWD` down, never `find /` and never across the* user's home or the whole filesystem, and a path that does not resolve is narrowed by* reasoning about the project's layout instead of by widening the root. The prompt tab* moved.+ * - `2026-09-10` (current) — image reading folded into `read_file`: the `read_image` /+ * `describe_image` entries left the set, `read_file` gained the optional `prompt` argument,+ * an image-aware description and a 60000 timeout, and `input_command`'s timeout aligned+ * with `exec_command` at 120000 (its empty-poll default became 110000): the tools tab+ * moved.*/export const KERNEL_DEFAULT_TAB_HASHES: Readonly<Record<KernelTab, string>> = {prompt: "f9576833f73192d69c962bf21bd2049d0c8f5389ba4b9700ca9bd95ea545d3b0",runtime: "5dfea06a5e801950c24f44f5527e62435ae4facc311a6587e53aa69983ab0346",- tools: "c24bcf47b1377e9da4dcfb69a1f7240dcdbfff2d420df5db0a5eaec2b7d4087d",+ tools: "a5e067fe58899be651c3c0541f587b2d5999030dc3008a39737a8fe21f5f7a23",skills: "7e343aa692e5eaeadfc8add6bb375fb50ac33ef81ebe460490fc219b0f3d707f",memory: "53d190390829cc0132bb12e468a6891f2e0576ec0c4022a9b4a5d9233666900d",vault: "19bd36a6d4ab442b66583c423450602b817990a9a79bafa21c9b6137fb6b47d8",@@ -232,6 +237,7 @@ export const KERNEL_SUPERSEDED_TAB_HASHES: KernelSupersededTabHashes = {"c719f2fe8a25bc5c644a4e1a78d26cf960dd0561efc453614af2e395000ed4de", // before `max` joined the ladder"074248073c5fe89537ff257cc5d5662159288fc79ede7703eded6b440b4e38e9", // before background execution and the kill tools"8bbd336ff1f3fc283c4e11e54d43dd2bfe4ba2458577bf9eb3b6e3d7be4f3cde", // before the kill tools folded into the input tools+ "c24bcf47b1377e9da4dcfb69a1f7240dcdbfff2d420df5db0a5eaec2b7d4087d", // before the image tools folded into read_file],// The memory prompt's wording before #397 named when a fact is worth saving.memory: ["c28acdda755552967cd0c99ba4ced407eddfa843b3dce228a965da4674676dc7"],diff --git a/packages/core/src/state/model-catalog.ts b/packages/core/src/state/model-catalog.tsindex d642648f..e1456bc5 100644--- a/packages/core/src/state/model-catalog.ts+++ b/packages/core/src/state/model-catalog.ts@@ -2171,7 +2171,7 @@ export function presetModelEntries(): ModelEntry[] {...(m.clientType !== undefined ? { client_type: m.clientType } : {}),...(pricing ? { pricing: { ...pricing } } : {}),// ModelEntry.vision defaults to supported: only models that don't support images- // explicitly persist false (drives the read_image / describe_image choice and input+ // explicitly persist false (drives read_file's hand-off of images to the vision model and input// image hand-off, see project-config.ts)....(m.supportsVision ? {} : { vision: false }),...(m.baseUrl !== undefined ? { base_url: m.baseUrl } : {}),diff --git a/packages/core/src/state/project-config.ts b/packages/core/src/state/project-config.tsindex 5821bb2f..97dbc1bd 100644--- a/packages/core/src/state/project-config.ts+++ b/packages/core/src/state/project-config.ts@@ -94,9 +94,9 @@ export interface ModelEntry {/*** Whether image input is supported (vision/multimodal); defaults to supported. For a model* tagged `false` (e.g. DeepSeek): images from conversation input are saved to the session- * scratchpad and handed over as a file path spliced into the text, and the image-reading tool- * switches to describe_image (a vision model reads on its behalf) — the image never directly- * enters that session's history.+ * scratchpad and handed over as a file path spliced into the text, and read_file has the+ * Project's vision model read an image on its behalf instead of returning it — the image+ * never directly enters that session's history.*/vision?: boolean;/**@@ -173,7 +173,7 @@ export interface ProjectConfig {/** Paired reference to the default Model; must point to an entry in `models`. */default_model?: ModelRef;/**- * The vision model used by read_image to read on behalf of a session model (when a session+ * The vision model used by read_file to read images on behalf of a session model (when a session* model with `vision=false` reads an image, it's handed to this model to describe and the tool* returns text); must point to an entry in `models` (a paired reference). Unconfigured by* default — models that don't support images won't be able to read images.@@ -589,7 +589,7 @@ export async function setDefaultModel(}/**- * Sets the vision model used to read images on behalf of read_image, and saves. The target+ * Sets the vision model used to read images on behalf of read_file, and saves. The target* reference must exist in `models` and not be tagged `vision=false` (a model that doesn't support* images can't read on someone's behalf); throws otherwise.*/diff --git a/packages/core/test/agent.test.ts b/packages/core/test/agent.test.tsindex def6d891..ab5c3032 100644--- a/packages/core/test/agent.test.ts+++ b/packages/core/test/agent.test.ts@@ -733,7 +733,7 @@ describe("Agent.createSession fast mode (session requests only, never the meta oit("the entry's fast_mode reaches the session LLM and is withheld from the meta LLM", async () => {// The scoping decision the whole feature rests on: the premium tier is what the user is// waiting on, so it rides the session's own requests, while background one-shots (title- // generation here; the describe_image describer builds from the *vision* model's entry and+ // generation here; read_file's vision describer builds from the *vision* model's entry and// so cannot inherit it at all) stay on the standard tier. Without this test the split is// asserted only by comments, and a refactor that hoists fastMode into a shared config// helper would start billing every session title at premium rates with all suites green.diff --git a/packages/core/test/background-execution.test.ts b/packages/core/test/background-execution.test.tsindex 8f38602b..23f22a6a 100644--- a/packages/core/test/background-execution.test.ts+++ b/packages/core/test/background-execution.test.ts@@ -427,8 +427,8 @@ describe("background-state listener", () => {});describe("input_command defaults", () => {- it("the default empty-poll wait is 120000ms", () => {- expect(DEFAULT_EMPTY_POLL_YIELD_MS).toBe(120_000);+ it("the default empty-poll wait is 110000ms", () => {+ expect(DEFAULT_EMPTY_POLL_YIELD_MS).toBe(110_000);});});diff --git a/packages/core/test/context-limits.test.ts b/packages/core/test/context-limits.test.tsindex 60e0ad25..d1a64d00 100644--- a/packages/core/test/context-limits.test.ts+++ b/packages/core/test/context-limits.test.ts@@ -92,7 +92,7 @@ describe("approximateMessagesTokens", () => {});it("counts a tool output's `images` data URLs at the flat allowance, not as base64 text", () => {- // read_image-style outputs carry the image as tool_call_output.images (data URLs). A+ // read_file's image outputs carry the image as tool_call_output.images (data URLs). A// 1 MB base64 string serialized as text would estimate ~262k "tokens" (~163x over)// and floor the NEXT request's cap even on a 128k window.const withImage = toolCallOutput({diff --git a/packages/core/test/describe-image.test.ts b/packages/core/test/describe-image.test.tsdeleted file mode 100644index 709c499c..00000000--- a/packages/core/test/describe-image.test.ts+++ /dev/null@@ -1,241 +0,0 @@-/**- * Unit tests (offline) for the read_image "vision-model describe" variant, driven by a fake LLM:- * definition overrides (new prompt parameter, description mentioning the vision model id), a- * single image + prompt sent to the vision model, text output and failure paths (no vision model- * configured / vision model request fails), results carrying no images; and swapping on the- * Environment side (injecting visionDescriber switches to the describe variant).- */-import { afterEach, beforeEach, describe, expect, it } from "vitest";-import { mkdtemp, rm, writeFile } from "node:fs/promises";-import { tmpdir } from "node:os";-import path from "node:path";-import {- DESCRIBE_IMAGE_NAME,- createDescribeImageTool,-} from "../src/environment/tools/describe-image.js";-import { BUILTIN_TOOL_FACTORIES } from "../src/environment/tools/registry.js";-import { Environment } from "../src/environment/environment.js";-import { assistantText, partialText, toolCall } from "../src/omnimessage/index.js";-import type { OmniMessage } from "../src/omnimessage/index.js";-import type { ToolResult } from "../src/environment/tools/types.js";-import type {- GenerativeModelParameters,- LLMInterface,- LLMOutcome,- ToolDefinitionConfig,- VisionDescriberService,-} from "../src/interfaces/index.js";--/** 1x1 transparent PNG (includes magic bytes, enough for mime sniffing). */-const PNG_1X1 = Buffer.from(- "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==",- "base64",-);--/** Config entry for describe_image (forModel: "text-only"; the definition comes entirely from config, the implementation never rewrites it at runtime). */-const definition: ToolDefinitionConfig = {- name: DESCRIBE_IMAGE_NAME,- forModel: "text-only",- description: "describe image via vision model",- parameters: {- type: "object",- properties: { source: { type: "string" }, prompt: { type: "string" } },- required: ["source"],- },- permission: "r",-};--/**- * Fake vision LLM: records the received newMessages, emits output following the real streaming- * protocol (partial start -> word-by-word delta -> stop -> complete text), and finishes with the given outcome.- */-function fakeLLM(reply: string, outcome: LLMOutcome = { status: "completed" }) {- const calls: GenerativeModelParameters[] = [];- const llm: LLMInterface = {- // eslint-disable-next-line @typescript-eslint/require-await- async *streamGenerate(params: GenerativeModelParameters) {- calls.push(params);- if (reply) {- yield partialText("start");- // Split into two delta chunks to verify piecewise forwarding (rather than buffering the whole thing).- const mid = Math.ceil(reply.length / 2);- yield partialText("delta", reply.slice(0, mid));- yield partialText("delta", reply.slice(mid));- yield partialText("stop");- yield assistantText(reply);- }- return outcome;- },- };- return { llm, calls };-}--async function run(- args: Record<string, unknown>,- workspaceDir: string,- describer: VisionDescriberService,-) {- const tool = createDescribeImageTool(definition, describer);- const gen = tool.execute(args, { workspaceDir, toolCallId: "c1" });- const messages: OmniMessage[] = [];- let result: ToolResult | void;- for (;;) {- const res = await gen.next();- if (res.done) {- result = res.value;- break;- }- messages.push(res.value);- }- const text = messages.map((m) => (m.payload as { output?: string }).output ?? "").join("");- return { messages, result, text };-}--let tmp: string;--beforeEach(async () => {- tmp = await mkdtemp(path.join(tmpdir(), "penguin-descimg-"));-});--afterEach(async () => {- await rm(tmp, { recursive: true, force: true });-});--describe("describe_image (the text-only-model variant of read_image)", () => {- it("the definition is taken verbatim from the config entry (no runtime rewriting)", () => {- const tool = createDescribeImageTool(definition, { modelId: "vis-1" });- expect(tool.name).toBe(DESCRIBE_IMAGE_NAME);- expect(tool.definition).toBe(definition);- });-- it("the registry assembles by tool name; without an injected visionDescriber it finishes as failed with a note (instead of returning the image)", async () => {- const factory = BUILTIN_TOOL_FACTORIES[DESCRIBE_IMAGE_NAME]!;- await writeFile(path.join(tmp, "a.png"), PNG_1X1);- const describeTool = factory(definition, undefined);- const gen = describeTool.execute({ source: "a.png" }, { workspaceDir: tmp, toolCallId: "c1" });- let result: ToolResult | void;- let text = "";- for (;;) {- const res = await gen.next();- if (res.done) {- result = res.value;- break;- }- text += (res.value.payload as { output?: string }).output ?? "";- }- expect(result?.stopReason).toBe("fatal");- expect(text).toContain("No vision model");- });-- it("image + custom prompt is sent to the vision model in a single shot, its text comes back, the result carries no images", async () => {- await writeFile(path.join(tmp, "a.png"), PNG_1X1);- const { llm, calls } = fakeLLM("The image shows a penguin.");- const describer: VisionDescriberService = { modelId: "vis-1", createLLM: () => llm };- const { messages, result, text } = await run(- { source: "a.png", prompt: "What animal is in the image?" },- tmp,- describer,- );-- // Single message = prompt text + data URL image (same role user, merged into one request).- expect(calls).toHaveLength(1);- const payloads = calls[0]!.newMessages.map(- (m) => m.payload as { type: string; text?: string; image_url?: string },- );- expect(payloads[0]!.type).toBe("text");- expect(payloads[0]!.text).toBe("What animal is in the image?");- expect(payloads[1]!.type).toBe("image_url");- expect(payloads[1]!.image_url).toBe(`data:image/png;base64,${PNG_1X1.toString("base64")}`);-- expect(text).toContain("described by vis-1");- expect(text).toContain("The image shows a penguin.");- // Streaming forward: the header line and description deltas are emitted as separate chunks (not buffered as a whole), and the complete text is not forwarded again.- const outputs = messages.map((m) => (m.payload as { output?: string }).output ?? "");- expect(outputs.length).toBeGreaterThanOrEqual(3); // header + >=2 description delta chunks- expect(outputs[0]).toContain("described by vis-1");- expect(outputs.slice(1).join("")).toBe("The image shows a penguin.");- // Text-based description: the result carries no images (images never enter session history).- expect(result?.images).toBeUndefined();- expect(result?.stopReason).toBeUndefined(); // defaults to completed- });-- it("uses the default question when no prompt is given", async () => {- await writeFile(path.join(tmp, "a.png"), PNG_1X1);- const { llm, calls } = fakeLLM("desc");- await run({ source: "a.png" }, tmp, { modelId: "vis-1", createLLM: () => llm });- const first = calls[0]!.newMessages[0]!.payload as { text?: string };- expect(first.text).toContain("Describe this image");- });-- it("no vision model configured: failed plus an explanation of how to configure one", async () => {- await writeFile(path.join(tmp, "a.png"), PNG_1X1);- const { result, text } = await run({ source: "a.png" }, tmp, { modelId: null });- expect(result?.stopReason).toBe("fatal");- expect(text).toContain("No vision model");- expect(text).toContain("vision_model");- });-- it("vision model request failure: failed with the status and message", async () => {- await writeFile(path.join(tmp, "a.png"), PNG_1X1);- const { llm } = fakeLLM("", { status: "fatal", errorMessage: "401 unauthorized" });- const { result, text } = await run({ source: "a.png" }, tmp, {- modelId: "vis-1",- createLLM: () => llm,- });- expect(result?.stopReason).toBe("fatal");- expect(text).toContain("fatal");- expect(text).toContain("401 unauthorized");- });-- it("image validation reuses read_image: an unsupported type fails immediately without calling the vision model", async () => {- await writeFile(path.join(tmp, "a.txt"), "not an image");- const { llm, calls } = fakeLLM("desc");- const { result } = await run({ source: "a.txt" }, tmp, {- modelId: "vis-1",- createLLM: () => llm,- });- expect(result?.stopReason).toBe("fatal");- expect(calls).toHaveLength(0);- });-- it("Environment assembles the describe_image entry with the delegated-description implementation; definition matches the config", async () => {- await writeFile(path.join(tmp, "a.png"), PNG_1X1);- const { llm } = fakeLLM("delegated description result");- const env = new Environment({- workspaceDir: tmp,- toolConfig: {- // Already filtered by selectBuiltinToolsForModel per session model before assembly; only the describe entry remains here.- customTools: [definition],- mcpServers: [],- },- services: { visionDescriber: { modelId: "vis-1", createLLM: () => llm } },- });- // Tool listing matches config: describe_image carries the prompt parameter.- const tools = await env.listTools();- const describeImage = tools.find((t) => t.name === DESCRIBE_IMAGE_NAME)!;- const props = (describeImage.parameters as { properties: Record<string, unknown> }).properties;- expect(Object.keys(props)).toContain("prompt");-- // Execution goes through description: outputs text, the complete message carries no images.- const out: OmniMessage[] = [];- for await (const m of env.executeTool({- toolCall: toolCall({- name: DESCRIBE_IMAGE_NAME,- arguments: '{"source":"a.png"}',- toolCallId: "t1",- }),- })) {- out.push(m);- }- const complete = out[out.length - 1]!.payload as {- type?: string;- output?: string;- images?: string[];- stop_reason?: string;- };- expect(complete.type).toBe("tool_call_output");- expect(complete.stop_reason).toBe("completed");- expect(complete.output).toContain("delegated description result");- expect(complete.images).toBeUndefined();- });-});diff --git a/packages/core/test/environment.test.ts b/packages/core/test/environment.test.tsindex 9485cee5..6aa7860e 100644--- a/packages/core/test/environment.test.ts+++ b/packages/core/test/environment.test.ts@@ -1146,6 +1146,32 @@ describe("Environment.executeTool — timeoutMs (PRN-013)", () => {});});+describe("Environment — stored entries for tools removed since (read_image / describe_image)", () => {+ it("skips them at assembly: not listed to the model, and a call by the old name gets the unknown-tool reply", async () => {+ const stale: ToolDefinitionConfig[] = [+ { name: "read_image", description: "old", forModel: "vision", permission: "r" },+ { name: "describe_image", description: "old", forModel: "text-only", permission: "r" },+ ];+ const env = new Environment({+ workspaceDir: tmp,+ toolConfig: { customTools: [execTool(), ...stale], mcpServers: [] },+ });+ expect((await env.listTools()).map((t) => t.name)).toEqual(["exec_command"]);+ const messages = await collect(+ env.executeTool({+ toolCall: toolCall({+ name: "read_image",+ arguments: '{"source":"a.png"}',+ toolCallId: "call_stale",+ }),+ }),+ );+ const last = messages[messages.length - 1]!.payload as { output: string; stop_reason?: string };+ expect(last.stop_reason).toBe("fatal");+ expect(last.output).toContain("Unknown tool: read_image");+ });+});+describe("Environment.executeTool — robustness", () => {it("returns an explanatory output for an unknown tool name without throwing", async () => {const env = new Environment({diff --git a/packages/core/test/file-tools.test.ts b/packages/core/test/file-tools.test.tsindex bc02d621..5627ffe7 100644--- a/packages/core/test/file-tools.test.ts+++ b/packages/core/test/file-tools.test.ts@@ -3,7 +3,8 @@* every failure case, workspace-relative path resolution, offset/limit windows,* replace_all semantics, and parent-directory creation. Directly drives* BuiltinTool.execute and captures the generator's return value (same approach as- * read-image.test.ts); Environment-side framing is covered by environment.test.ts.+ * read-file-images.test.ts, which covers read_file's image branch); Environment-side framing+ * is covered by environment.test.ts.*/import { afterEach, beforeEach, describe, expect, it } from "vitest";import {@@ -189,7 +190,7 @@ describe("read_file", () => {const { result, text } = await run(tool(), { file_path: "bin.dat" }, tmp);expect(result?.stopReason).toBe("fatal");expect(text).toContain("binary");- expect(text).toContain("read_image");+ expect(text).toContain("shell commands");});it("fails when offset is past the end of the file", async () => {diff --git a/packages/core/test/llm.test.ts b/packages/core/test/llm.test.tsindex c1d1734c..c3e11171 100644--- a/packages/core/test/llm.test.ts+++ b/packages/core/test/llm.test.ts@@ -1540,7 +1540,7 @@ describe("GenerativeModel per-request output cap (window clamp, issue #218)", ()});it("counts a tool output's base64 image at the flat allowance: the next request is not floored", async () => {- // Regression for the review repro: a read_image-style tool output carrying a 1 MB+ // Regression for the review repro: a read_file image output carrying a 1 MB// data-URL image used to be serialized into the estimate (~262k "tokens"), flooring// request 2's max_tokens to the minimum even on a 128k window.const { model, configs } = windowModel({diff --git a/packages/core/test/read-file-images.test.ts b/packages/core/test/read-file-images.test.tsnew file mode 100644index 00000000..bfd2678c--- /dev/null+++ b/packages/core/test/read-file-images.test.ts@@ -0,0 +1,346 @@+/**+ * Behavior tests for read_file's image branch (no network): image detection (magic number /+ * extension / http(s) URL), the vision path (the image comes back via ToolResult.images with a+ * one-line mime/size note), the text-only path (a fake VisionDescriberService: single-shot+ * prompt + image request, streamed text, default prompt, no vision model configured, vision+ * request failure), failure cases shared by both (oversize, unsupported type, missing file,+ * empty file), the URL source (stubbed global fetch), and the Environment-side assembly with+ * and without an injected describer. Drives BuiltinTool.execute directly like+ * file-tools.test.ts; the text window itself is covered there.+ */+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { mkdtemp, rm, writeFile } from "node:fs/promises";+import { tmpdir } from "node:os";+import path from "node:path";+import { READ_FILE_NAME, createReadFileTool } from "../src/environment/tools/read-file.js";+import { MAX_IMAGE_BYTES } from "../src/environment/tools/image-source.js";+import { BUILTIN_TOOL_FACTORIES } from "../src/environment/tools/registry.js";+import { Environment } from "../src/environment/environment.js";+import { assistantText, partialText, toolCall } from "../src/omnimessage/index.js";+import type { OmniMessage } from "../src/omnimessage/index.js";+import type { ToolResult } from "../src/environment/tools/types.js";+import type {+ EnvironmentServices,+ GenerativeModelParameters,+ LLMInterface,+ LLMOutcome,+ ToolDefinitionConfig,+ VisionDescriberService,+} from "../src/interfaces/index.js";++/** 1x1 transparent PNG (full bytes: magic number for sniffing, and the data URL assertions). */+const PNG_1X1 = Buffer.from(+ "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==",+ "base64",+);+const PNG_DATA_URL = `data:image/png;base64,${PNG_1X1.toString("base64")}`;++const definition: ToolDefinitionConfig = {+ name: READ_FILE_NAME,+ description: "read file",+ parameters: {+ type: "object",+ properties: {+ file_path: { type: "string" },+ offset: { type: "number" },+ limit: { type: "number" },+ prompt: { type: "string" },+ },+ required: ["file_path"],+ },+ permission: "r",+};++/**+ * Fake vision LLM: records the received parameters, emits output following the real streaming+ * protocol (partial start -> two deltas -> stop -> complete text), and finishes with the given outcome.+ */+function fakeLLM(reply: string, outcome: LLMOutcome = { status: "completed" }) {+ const calls: GenerativeModelParameters[] = [];+ const llm: LLMInterface = {+ // eslint-disable-next-line @typescript-eslint/require-await+ async *streamGenerate(params: GenerativeModelParameters) {+ calls.push(params);+ if (reply) {+ yield partialText("start");+ const mid = Math.ceil(reply.length / 2);+ yield partialText("delta", reply.slice(0, mid));+ yield partialText("delta", reply.slice(mid));+ yield partialText("stop");+ yield assistantText(reply);+ }+ return outcome;+ },+ };+ return { llm, calls };+}++/** Runs one tool execution: collects streamed messages, concatenates text deltas, and captures the generator's return value. */+async function run(+ args: Record<string, unknown>,+ workspaceDir: string,+ services?: EnvironmentServices,+) {+ const tool = createReadFileTool(definition, services);+ const gen = tool.execute(args, { workspaceDir, toolCallId: "c1" });+ const messages: OmniMessage[] = [];+ let result: ToolResult | void;+ for (;;) {+ const res = await gen.next();+ if (res.done) {+ result = res.value;+ break;+ }+ messages.push(res.value);+ }+ const outputs = messages.map((m) => (m.payload as { output?: string }).output ?? "");+ return { messages, outputs, result, text: outputs.join("") };+}++let tmp: string;++beforeEach(async () => {+ tmp = await mkdtemp(path.join(tmpdir(), "penguin-readfile-img-"));+});++afterEach(async () => {+ vi.unstubAllGlobals();+ await rm(tmp, { recursive: true, force: true });+});++describe("read_file on an image — session model views images (no describer)", () => {+ it("returns the image via ToolResult.images with a one-line mime/size note", async () => {+ await writeFile(path.join(tmp, "img.png"), PNG_1X1);+ const { result, text } = await run({ file_path: "img.png" }, tmp);+ expect(result?.stopReason).toBeUndefined(); // defaults to completed+ expect(result?.images).toEqual([PNG_DATA_URL]);+ expect(text).toBe(`image/png, ${PNG_1X1.length} B`);+ });++ it("recognizes an image by its magic number whatever the extension says", async () => {+ await writeFile(path.join(tmp, "notes.txt"), PNG_1X1); // PNG bytes under a text extension+ const { result } = await run({ file_path: "notes.txt" }, tmp);+ expect(result?.images?.[0]).toMatch(/^data:image\/png;base64,/);+ });++ it("recognizes an image by extension when the bytes carry no known magic number", async () => {+ // The extension routes the file into the image branch, where it is handed over as its+ // extension says (the same fallback the URL branch applies to a content-type-less response).+ await writeFile(path.join(tmp, "plain.png"), Buffer.from("no magic here"));+ const { result } = await run({ file_path: "plain.png" }, tmp);+ expect(result?.images?.[0]).toMatch(/^data:image\/png;base64,/);+ });++ it("ignores offset and limit for an image", async () => {+ await writeFile(path.join(tmp, "img.png"), PNG_1X1);+ const { result } = await run({ file_path: "img.png", offset: 50, limit: 1 }, tmp);+ expect(result?.images).toEqual([PNG_DATA_URL]);+ });++ it("still reads a text file as a numbered window", async () => {+ await writeFile(path.join(tmp, "a.txt"), "alpha\nbeta\n");+ const { result, text } = await run({ file_path: "a.txt" }, tmp);+ expect(result).toBeUndefined();+ expect(text).toBe(" 1\talpha\n 2\tbeta");+ });++ it("fails with a size note above the image limit", async () => {+ const big = Buffer.alloc(MAX_IMAGE_BYTES + 1);+ PNG_1X1.copy(big); // Header carries the PNG magic number, so the failure is size, not type+ await writeFile(path.join(tmp, "big.png"), big);+ const { result, text } = await run({ file_path: "big.png" }, tmp);+ expect(result?.stopReason).toBe("fatal");+ expect(result?.images).toBeUndefined();+ expect(text).toContain("too large");+ });++ it("rejects a binary that is no supported image with advice, and a missing image path with the not-found note", async () => {+ await writeFile(path.join(tmp, "img.bmp"), Buffer.from([0x42, 0x4d, 0x00, 0x01, 0x02]));+ const bmp = await run({ file_path: "img.bmp" }, tmp);+ expect(bmp.result?.stopReason).toBe("fatal");+ expect(bmp.text).toContain("binary");+ expect(bmp.text).toContain("png/jpeg/gif/webp");++ const missing = await run({ file_path: "missing.png" }, tmp);+ expect(missing.result?.stopReason).toBe("fatal");+ expect(missing.text).toContain("File not found");+ });+});++describe("read_file on an image — text-only session model (describer injected)", () => {+ it("sends the image plus the caller's prompt to the vision model in one shot and streams its text back, with no images in the result", async () => {+ await writeFile(path.join(tmp, "a.png"), PNG_1X1);+ const { llm, calls } = fakeLLM("The image shows a penguin.");+ const visionDescriber: VisionDescriberService = { modelId: "vis-1", createLLM: () => llm };+ const { outputs, result, text } = await run(+ { file_path: "a.png", prompt: "What animal is in the image?" },+ tmp,+ { visionDescriber },+ );++ expect(calls).toHaveLength(1);+ const payloads = calls[0]!.newMessages.map(+ (m) => m.payload as { type: string; text?: string; image_url?: string },+ );+ expect(payloads[0]!.type).toBe("text");+ expect(payloads[0]!.text).toBe("What animal is in the image?");+ expect(payloads[1]!.type).toBe("image_url");+ expect(payloads[1]!.image_url).toBe(PNG_DATA_URL);++ expect(text).toContain("described by vis-1");+ expect(text).toContain("The image shows a penguin.");+ // Streamed piecewise: the header line, then the description deltas as they arrive; the+ // complete text is not forwarded a second time.+ expect(outputs.length).toBeGreaterThanOrEqual(3);+ expect(outputs[0]).toContain("described by vis-1");+ expect(outputs.slice(1).join("")).toBe("The image shows a penguin.");+ expect(result?.images).toBeUndefined();+ expect(result?.stopReason).toBeUndefined();+ });++ it("asks the default question when no prompt is given", async () => {+ await writeFile(path.join(tmp, "a.png"), PNG_1X1);+ const { llm, calls } = fakeLLM("desc");+ await run({ file_path: "a.png" }, tmp, {+ visionDescriber: { modelId: "vis-1", createLLM: () => llm },+ });+ const first = calls[0]!.newMessages[0]!.payload as { text?: string };+ expect(first.text).toContain("Describe this image");+ });++ it("no vision model configured: fatal, explaining how to configure one, without fetching the image", async () => {+ await writeFile(path.join(tmp, "a.png"), PNG_1X1);+ const local = await run({ file_path: "a.png" }, tmp, { visionDescriber: { modelId: null } });+ expect(local.result?.stopReason).toBe("fatal");+ expect(local.text).toContain("No vision model");+ expect(local.text).toContain("vision_model");+ // A URL source is not even downloaded: the missing vision model is what stands between+ // this session and image reading, not the image.+ const fetchMock = vi.fn(async () => new Response(PNG_1X1, { status: 200 }));+ vi.stubGlobal("fetch", fetchMock);+ const remote = await run({ file_path: "https://example.com/a.png" }, tmp, {+ visionDescriber: { modelId: null },+ });+ expect(remote.result?.stopReason).toBe("fatal");+ expect(remote.text).toContain("No vision model");+ expect(fetchMock).not.toHaveBeenCalled();+ });++ it("vision request failure: fatal with the status and message", async () => {+ await writeFile(path.join(tmp, "a.png"), PNG_1X1);+ const { llm } = fakeLLM("", { status: "fatal", errorMessage: "401 unauthorized" });+ const { result, text } = await run({ file_path: "a.png" }, tmp, {+ visionDescriber: { modelId: "vis-1", createLLM: () => llm },+ });+ expect(result?.stopReason).toBe("fatal");+ expect(text).toContain("fatal");+ expect(text).toContain("401 unauthorized");+ });++ it("an oversized image fails before any vision request", async () => {+ const big = Buffer.alloc(MAX_IMAGE_BYTES + 1);+ PNG_1X1.copy(big);+ await writeFile(path.join(tmp, "big.png"), big);+ const { llm, calls } = fakeLLM("desc");+ const { result } = await run({ file_path: "big.png" }, tmp, {+ visionDescriber: { modelId: "vis-1", createLLM: () => llm },+ });+ expect(result?.stopReason).toBe("fatal");+ expect(calls).toHaveLength(0);+ });++ it("text files never involve the vision model", async () => {+ await writeFile(path.join(tmp, "a.txt"), "hello\n");+ const { llm, calls } = fakeLLM("desc");+ const { text } = await run({ file_path: "a.txt", prompt: "ignored" }, tmp, {+ visionDescriber: { modelId: "vis-1", createLLM: () => llm },+ });+ expect(text).toBe(" 1\thello");+ expect(calls).toHaveLength(0);+ });+});++describe("read_file on an http(s) URL", () => {+ it("downloads via the global fetch, taking the content-type header as the mime", async () => {+ const fetchMock = vi.fn(+ async (_input: unknown) =>+ new Response(PNG_1X1, { status: 200, headers: { "content-type": "image/png" } }),+ );+ vi.stubGlobal("fetch", fetchMock);+ const { result, text } = await run({ file_path: "https://example.com/a" }, tmp);+ expect(fetchMock).toHaveBeenCalledTimes(1);+ expect(fetchMock.mock.calls[0]![0]).toBe("https://example.com/a");+ expect(result?.images).toEqual([PNG_DATA_URL]);+ expect(text).toContain("image/png");+ });++ it("fails with the status code on a non-2xx response", async () => {+ vi.stubGlobal(+ "fetch",+ vi.fn(async () => new Response("nope", { status: 404 })),+ );+ const { result, text } = await run({ file_path: "https://example.com/missing.png" }, tmp);+ expect(result?.stopReason).toBe("fatal");+ expect(text).toContain("404");+ });++ it("rejects a URL that is not an image", async () => {+ vi.stubGlobal(+ "fetch",+ vi.fn(+ async () =>+ new Response("<html></html>", { status: 200, headers: { "content-type": "text/html" } }),+ ),+ );+ const { result, text } = await run({ file_path: "https://example.com/page" }, tmp);+ expect(result?.stopReason).toBe("fatal");+ expect(text).toContain("Unsupported image type");+ });+});++describe("read_file image branch — Environment assembly", () => {+ it("the registry factory reads services.visionDescriber: with it the output is text, without it the image is carried", async () => {+ await writeFile(path.join(tmp, "a.png"), PNG_1X1);+ const factory = BUILTIN_TOOL_FACTORIES[READ_FILE_NAME]!;+ const { llm } = fakeLLM("delegated description result");+ const complete = async (env: Environment) => {+ const out: OmniMessage[] = [];+ for await (const m of env.executeTool({+ toolCall: toolCall({+ name: READ_FILE_NAME,+ arguments: '{"file_path":"a.png"}',+ toolCallId: "t1",+ }),+ })) {+ out.push(m);+ }+ return out[out.length - 1]!.payload as {+ type?: string;+ output?: string;+ images?: string[];+ stop_reason?: string;+ };+ };++ const textOnly = new Environment({+ workspaceDir: tmp,+ toolConfig: { customTools: [definition], mcpServers: [] },+ services: { visionDescriber: { modelId: "vis-1", createLLM: () => llm } },+ });+ const described = await complete(textOnly);+ expect(described.type).toBe("tool_call_output");+ expect(described.stop_reason).toBe("completed");+ expect(described.output).toContain("delegated description result");+ expect(described.images).toBeUndefined();++ const vision = new Environment({+ workspaceDir: tmp,+ toolConfig: { customTools: [definition], mcpServers: [] },+ });+ const carried = await complete(vision);+ expect(carried.stop_reason).toBe("completed");+ expect(carried.images).toEqual([PNG_DATA_URL]);+ // The same factory serves both: no per-model entry, the describer alone decides.+ expect(factory(definition, undefined).name).toBe(READ_FILE_NAME);+ });+});diff --git a/packages/core/test/read-image.test.ts b/packages/core/test/read-image.test.tsdeleted file mode 100644index a05960f5..00000000--- a/packages/core/test/read-image.test.ts+++ /dev/null@@ -1,147 +0,0 @@-/**- * Unit tests for the read_image tool (no network): local file reading (relative-path- * resolution / magic-number sniffing / missing file / over the size limit / unsupported type /- * missing argument) and http(s) URL download (stubbing global fetch: success and non-2xx).- * Directly drives BuiltinTool.execute and captures the generator's return value -- see- * environment.test.ts for the Environment-side images assembly.- */-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";-import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";-import { tmpdir } from "node:os";-import path from "node:path";-import {- MAX_IMAGE_BYTES,- READ_IMAGE_NAME,- createReadImageTool,-} from "../src/environment/tools/read-image.js";-import type { ToolResult } from "../src/environment/tools/types.js";-import type { OmniMessage } from "../src/omnimessage/index.js";-import type { ToolDefinitionConfig } from "../src/interfaces/index.js";--/** Full bytes of a 1x1 transparent PNG (including the magic number, enough for mime sniffing- * and data URL assertions). */-const PNG_1X1 = Buffer.from(- "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==",- "base64",-);--const definition: ToolDefinitionConfig = {- name: READ_IMAGE_NAME,- description: "read image",- permission: "r",-};--/** Runs one tool execution: collects streamed messages, concatenates text deltas, and captures- * the generator's return value. */-async function run(args: Record<string, unknown>, workspaceDir: string) {- const tool = createReadImageTool(definition);- const gen = tool.execute(args, { workspaceDir, toolCallId: "c1" });- const messages: OmniMessage[] = [];- let result: ToolResult | void;- for (;;) {- const res = await gen.next();- if (res.done) {- result = res.value;- break;- }- messages.push(res.value);- }- const text = messages.map((m) => (m.payload as { output?: string }).output ?? "").join("");- return { messages, result, text };-}--let tmp: string;--beforeEach(async () => {- tmp = await mkdtemp(path.join(tmpdir(), "penguin-readimg-"));-});--afterEach(async () => {- vi.unstubAllGlobals();- await rm(tmp, { recursive: true, force: true });-});--describe("read_image — local files", () => {- it("reads a png by relative path, outputs a data URL plus a one-line mime/size note", async () => {- await writeFile(path.join(tmp, "img.png"), PNG_1X1);- const { result, text } = await run({ source: "img.png" }, tmp);- expect(result?.stopReason).toBeUndefined(); // Defaults to completed- expect(result?.images).toEqual([`data:image/png;base64,${PNG_1X1.toString("base64")}`]);- expect(text).toBe(`image/png, ${PNG_1X1.length} B`);- });-- it("magic-number sniffing wins when the extension disagrees with the content", async () => {- await writeFile(path.join(tmp, "photo.jpg"), PNG_1X1); // Content is actually PNG- const { result } = await run({ source: "photo.jpg" }, tmp);- expect(result?.images?.[0]).toMatch(/^data:image\/png;base64,/);- });-- it("finishes as failed with an explanation when the file does not exist", async () => {- const { result, text } = await run({ source: "missing.png" }, tmp);- expect(result?.stopReason).toBe("fatal");- expect(result?.images).toBeUndefined();- expect(text).toContain("missing.png");- });-- it("finishes as failed when the size limit is exceeded", async () => {- const big = Buffer.alloc(MAX_IMAGE_BYTES + 1);- PNG_1X1.copy(big); // Header carries the PNG magic number, ensuring the failure is due to size, not type- await writeFile(path.join(tmp, "big.png"), big);- const { result, text } = await run({ source: "big.png" }, tmp);- expect(result?.stopReason).toBe("fatal");- expect(text).toContain("too large");- });-- it("finishes as failed for an unsupported image type", async () => {- await writeFile(path.join(tmp, "img.bmp"), Buffer.from("BM not really an image"));- const { result, text } = await run({ source: "img.bmp" }, tmp);- expect(result?.stopReason).toBe("fatal");- expect(text).toContain("Unsupported image type");- });-- it("finishes as failed with a clear note when source points to a directory (no raw EISDIR passthrough)", async () => {- await mkdir(path.join(tmp, "subdir"));- const { result, text } = await run({ source: "subdir" }, tmp);- expect(result?.stopReason).toBe("fatal");- expect(text).toContain("not a file");- expect(text).not.toContain("EISDIR");- });-- it("finishes as failed for an empty file (the extension fallback must not let empty base64 through)", async () => {- await writeFile(path.join(tmp, "empty.png"), Buffer.alloc(0));- const { result, text } = await run({ source: "empty.png" }, tmp);- expect(result?.stopReason).toBe("fatal");- expect(text).toContain("empty");- });-- it("finishes as failed when the source argument is missing", async () => {- const { result, text } = await run({}, tmp);- expect(result?.stopReason).toBe("fatal");- expect(text).toContain('"source"');- });-});--describe("read_image — http(s) URL", () => {- it("downloads via global fetch and takes the content-type response header as the mime", async () => {- const fetchMock = vi.fn(- async (_input: unknown) =>- new Response(PNG_1X1, { status: 200, headers: { "content-type": "image/png" } }),- );- vi.stubGlobal("fetch", fetchMock);- const { result, text } = await run({ source: "https://example.com/a" }, tmp);- expect(fetchMock).toHaveBeenCalledTimes(1);- expect(fetchMock.mock.calls[0]![0]).toBe("https://example.com/a");- expect(result?.images).toEqual([`data:image/png;base64,${PNG_1X1.toString("base64")}`]);- expect(text).toContain("image/png");- });-- it("finishes as failed with the status code on a non-2xx response", async () => {- vi.stubGlobal(- "fetch",- vi.fn(async () => new Response("nope", { status: 404 })),- );- const { result, text } = await run({ source: "https://example.com/missing.png" }, tmp);- expect(result?.stopReason).toBe("fatal");- expect(text).toContain("404");- });-});diff --git a/packages/core/test/state.test.ts b/packages/core/test/state.test.tsindex a6240e26..6aaf3dc0 100644--- a/packages/core/test/state.test.ts+++ b/packages/core/test/state.test.ts@@ -3,6 +3,8 @@ import os from "node:os";import path from "node:path";import { parse as parseToml } from "smol-toml";import { afterEach, beforeEach, describe, expect, it } from "vitest";+import { clampYield } from "../src/environment/tools/background/index.js";+import { DEFAULT_EMPTY_POLL_YIELD_MS } from "../src/environment/tools/command/index.js";import {AGENT_ID_PLACEHOLDER,AGENTS_MD_PLACEHOLDER,@@ -243,7 +245,7 @@ describe("loadAgentState", () => {});describe("buildToolConfig", () => {- it("exposes command, file, subagent (rw) and image (r) tools", async () => {+ it("exposes the command, file (read_file also reads images) and subagent tools with their default contracts", async () => {const state = await loadAgentState({ init: {} });const cfg = buildToolConfig(state);expect(cfg.mcpServers).toEqual([]);@@ -255,8 +257,6 @@ describe("buildToolConfig", () => {"input_command","run_subagent","input_subagent",- "read_image",- "describe_image",]);const exec = cfg.customTools.find((t) => t.name === "exec_command")!;expect(exec.permission).toBe("rw");@@ -272,21 +272,30 @@ describe("buildToolConfig", () => {const write = cfg.customTools.find((t) => t.name === "input_command")!;expect(write.permission).toBe("rw");expect(write.call_description).toBe(true);+ // Same timeout tier as exec_command; the empty-poll default has to fit under it, so a+ // default-length poll returns on its own before the Environment's timeout fires.+ expect(write.timeoutMs).toBe(120000);+ expect(clampYield(undefined, DEFAULT_EMPTY_POLL_YIELD_MS, write.timeoutMs)).toBe(+ DEFAULT_EMPTY_POLL_YIELD_MS,+ );expect((write.parameters as { required?: string[] }).required).toEqual(["description","process_id",]);- // File tools: read_file is read-only with a wider output cap; edit/write are rw.+ // File tools: read_file is read-only with a wider output cap and the image-reading+ // timeout (one vision request may sit inside a call); edit/write are rw.const readFile = cfg.customTools.find((t) => t.name === "read_file")!;expect(readFile.permission).toBe("r");- expect(readFile.timeoutMs).toBe(30000);+ expect(readFile.timeoutMs).toBe(60000);expect(readFile.maxOutputLength).toBe(64000);expect((readFile.parameters as { required?: string[] }).required).toEqual(["file_path"]);expect(Object.keys((readFile.parameters as { properties: object }).properties)).toEqual(["file_path","offset","limit",+ "prompt",]);+ expect(readFile.description).toContain("image");const editFile = cfg.customTools.find((t) => t.name === "edit_file")!;expect(editFile.permission).toBe("rw");expect(editFile.timeoutMs).toBe(30000);@@ -311,37 +320,24 @@ describe("buildToolConfig", () => {"description","subagent_id",]);- // Both image-reading tool entries are explicitly in the config, each declaring its- // applicable model kind via the forModel annotation.- const readImage = cfg.customTools.find((t) => t.name === "read_image")!;- expect(readImage.forModel).toBe("vision");- expect(readImage.permission).toBe("r");- expect(Object.keys((readImage.parameters as { properties: object }).properties)).toEqual([- "source",- ]);- const describeImage = cfg.customTools.find((t) => t.name === "describe_image")!;- expect(describeImage.forModel).toBe("text-only");- expect(describeImage.permission).toBe("r");- expect(Object.keys((describeImage.parameters as { properties: object }).properties)).toEqual([- "source",- "prompt",- ]);- expect((describeImage.parameters as { required?: string[] }).required).toEqual(["source"]);+ // No built-in entry is pinned to a model class: read_file serves both at runtime.+ expect(cfg.customTools.every((t) => t.forModel === undefined)).toBe(true);});- it("selectBuiltinToolsForModel picks the matching image tool per model kind", async () => {- const state = await loadAgentState({ init: {} });- const all = buildToolConfig(state).customTools;- // Vision model: read_image is kept, describe_image is filtered out; unannotated tools are unaffected.- const forVision = selectBuiltinToolsForModel(all, true);- expect(forVision.some((t) => t.name === "read_image")).toBe(true);- expect(forVision.some((t) => t.name === "describe_image")).toBe(false);- expect(forVision.filter((t) => t.name === "exec_command")).toHaveLength(1);- // Text-only model: describe_image is kept.- const forText = selectBuiltinToolsForModel(all, false);- expect(forText.some((t) => t.name === "read_image")).toBe(false);- expect(forText.some((t) => t.name === "describe_image")).toBe(true);- expect(forText.filter((t) => t.name === "exec_command")).toHaveLength(1);+ it("selectBuiltinToolsForModel keeps an entry annotated for the session model's class and every unannotated one", () => {+ const entries = [+ { name: "for_vision", description: "v", forModel: "vision" as const },+ { name: "for_text", description: "t", forModel: "text-only" as const },+ { name: "read_file", description: "any" },+ ];+ expect(selectBuiltinToolsForModel(entries, true).map((t) => t.name)).toEqual([+ "for_vision",+ "read_file",+ ]);+ expect(selectBuiltinToolsForModel(entries, false).map((t) => t.name)).toEqual([+ "for_text",+ "read_file",+ ]);});it("loads MCP Server config from system_config.yaml", () => {@@ -383,8 +379,6 @@ describe("buildToolConfig", () => {"input_command","run_subagent","input_subagent",- "read_image",- "describe_image",]);});});@@ -416,7 +410,7 @@ describe("buildToolConfig — per-tool call_description filter", () => {expect(required(tool)).toContain("description");}// The file tools' path argument is self-describing: no description parameter in config.- for (const name of ["read_file", "edit_file", "write_file", "read_image", "describe_image"]) {+ for (const name of ["read_file", "edit_file", "write_file"]) {const tool = cfg.customTools.find((t) => t.name === name)!;expect(properties(tool)["description"]).toBeUndefined();}diff --git a/packages/docs/content/agent-loop.en.md b/packages/docs/content/agent-loop.en.mdindex de7dbe2f..983c2170 100644--- a/packages/docs/content/agent-loop.en.md+++ b/packages/docs/content/agent-loop.en.md@@ -151,7 +151,7 @@ While a Task is running, the host can queue a user message with `session.steer(i## Input images-An input image either rides the request as an image message or becomes an `[attached image: <path>]` line pointing at a file in the session scratchpad — the model then views it with `read_image` / `describe_image`, and the Web restores the thumbnail from the path. The conversion is one function bound once per Session (it is the only layer that knows both the scratchpad and the model's capability), and **each input path decides for itself whether to apply it**:+An input image either rides the request as an image message or becomes an `[attached image: <path>]` line pointing at a file in the session scratchpad — the model then views it with `read_file`, and the Web restores the thumbnail from the path. The conversion is one function bound once per Session (it is the only layer that knows both the scratchpad and the model's capability), and **each input path decides for itself whether to apply it**:| Input | Folds when | Applied at || --- | --- | --- |diff --git a/packages/docs/content/agent-loop.zh.md b/packages/docs/content/agent-loop.zh.mdindex bb8aa91a..bc4f6545 100644--- a/packages/docs/content/agent-loop.zh.md+++ b/packages/docs/content/agent-loop.zh.md@@ -144,7 +144,7 @@ Task 运行期间,宿主可通过 `session.steer(input)` 排队一条用户消## 输入图片-一张输入图片要么以图片消息的形态跟着请求走,要么变成一行 `[attached image: <路径>]`,指向会话 scratchpad 里的文件——模型再用 `read_image` / `describe_image` 去看,Web 则从路径还原出缩略图。这个转换是每个 Session 绑定一次的同一个函数(Session 是唯一同时知道 scratchpad 目录和模型能力的层),而**是否折叠由各输入路径自己决定**:+一张输入图片要么以图片消息的形态跟着请求走,要么变成一行 `[attached image: <路径>]`,指向会话 scratchpad 里的文件——模型再用 `read_file` 去看,Web 则从路径还原出缩略图。这个转换是每个 Session 绑定一次的同一个函数(Session 是唯一同时知道 scratchpad 目录和模型能力的层),而**是否折叠由各输入路径自己决定**:| 输入 | 何时折叠 | 折叠时机 || --- | --- | --- |diff --git a/packages/docs/content/configuration.en.md b/packages/docs/content/configuration.en.mdindex 6a217b4b..eef9cfa6 100644--- a/packages/docs/content/configuration.en.md+++ b/packages/docs/content/configuration.en.md@@ -54,7 +54,7 @@ The openrouter, fireworks, siliconflow, tokendance, qwen-pay-as-you-go, qwen-tok| --- | --- || `name` | Project display name (the id is shown when unset) || `default_model` | Paired reference `{ provider, model_id }` to the default model; must point to an entry in `models` |-| `vision_model` | The vision model that reads images on behalf of text-only models (used by `describe_image`); a paired reference |+| `vision_model` | The vision model that reads images on behalf of text-only models (`read_file` hands images to it); a paired reference || `[command_policy]` | Sandbox command policy: deny rules for shell commands, applied ahead of the approval mode — see [Command policy](#command-policy) || `[[models]]` | The list of available model entries |diff --git a/packages/docs/content/configuration.zh.md b/packages/docs/content/configuration.zh.mdindex fc8a0a97..46d3f92d 100644--- a/packages/docs/content/configuration.zh.md+++ b/packages/docs/content/configuration.zh.md@@ -54,7 +54,7 @@ openrouter、fireworks、siliconflow、tokendance、qwen-pay-as-you-go、qwen-to| --- | --- || `name` | Project 展示名(缺省显示 id) || `default_model` | 缺省模型的成对引用 `{ provider, model_id }`,必须指向 `models` 中的条目 |-| `vision_model` | 代读图片的视觉模型(供纯文本模型的 `describe_image` 使用),成对引用 |+| `vision_model` | 代读图片的视觉模型(纯文本模型用 `read_file` 读图时由它代读),成对引用 || `[command_policy]` | 沙箱安全策略:针对 shell 命令的拒绝规则,先于审批模式生效——见[沙箱安全策略](#沙箱安全策略) || `[[models]]` | 可用模型条目列表 |diff --git a/packages/docs/content/interfaces.en.md b/packages/docs/content/interfaces.en.mdindex 7620ba84..19ae0aa1 100644--- a/packages/docs/content/interfaces.en.md+++ b/packages/docs/content/interfaces.en.md@@ -163,7 +163,7 @@ type ProxyEnvPolicy = { mode: "strip" } | { mode: "inject"; url: string; noProxyinterface EnvironmentServices {subagentRunner?: SubagentRunner; // needed by run_subagent- visionDescriber?: VisionDescriberService; // needed by describe_image on text-only models+ visionDescriber?: VisionDescriberService; // injected for text-only models only: read_file describes images through itcommandSessions?: CommandSessionManager; // long-running command session registry (built by Environment)subagentSessions?: SubagentSessionManager;// background subagent session registry (likewise)backgroundDone?: (event: BackgroundTaskDoneEvent) => void; // completion-report sink for run_in_background launches (likewise)@@ -209,7 +209,7 @@ interface ToolDefinitionConfig {description: string;parameters?: Record<string, unknown>; // JSON Schemapermission?: "r" | "rw";- forModel?: "vision" | "text-only"; // assembled per session-model class+ forModel?: "vision" | "text-only"; // assembled per session-model class (unset by the built-in entries)timeoutMs?: number; // default 120000; <=0 disablesmaxOutputLength?: number; // default 16000, head-kept truncation; <=0 disables}@@ -280,7 +280,7 @@ A round's input is an OmniMessage list — the same shape `steer` takes, and the## VisionDescriberService-The image proxy-reading service for text-only models (needed by `describe_image`):+The image proxy-reading service for text-only models (needed by `read_file` when the Session model cannot view images — its presence is how the tool knows):```tsinterface VisionDescriberService {diff --git a/packages/docs/content/interfaces.zh.md b/packages/docs/content/interfaces.zh.mdindex 7e574b79..1c17ee05 100644--- a/packages/docs/content/interfaces.zh.md+++ b/packages/docs/content/interfaces.zh.md@@ -163,7 +163,7 @@ type ProxyEnvPolicy = { mode: "strip" } | { mode: "inject"; url: string; noProxyinterface EnvironmentServices {subagentRunner?: SubagentRunner; // run_subagent 所需- visionDescriber?: VisionDescriberService; // text-only 模型的 describe_image 所需+ visionDescriber?: VisionDescriberService; // 仅注入 text-only 模型的 Session:read_file 经它代读图片commandSessions?: CommandSessionManager; // 长驻命令会话登记表(Environment 内部构造)subagentSessions?: SubagentSessionManager;// 后台 Subagent 会话登记表(同上)backgroundDone?: (event: BackgroundTaskDoneEvent) => void; // run_in_background 完成回报的汇聚点(同上)@@ -207,7 +207,7 @@ interface ToolDefinitionConfig {description: string;parameters?: Record<string, unknown>; // JSON Schemapermission?: "r" | "rw";- forModel?: "vision" | "text-only"; // 按 Session 模型类别装配+ forModel?: "vision" | "text-only"; // 按 Session 模型类别装配(内置条目不设)timeoutMs?: number; // 默认 120000;<=0 关闭maxOutputLength?: number; // 默认 16000,头部保留截断;<=0 关闭}@@ -278,7 +278,7 @@ interface SubagentHandle {## VisionDescriberService-text-only 模型的图像代读服务(`describe_image` 所需):+text-only 模型的图像代读服务(`read_file` 读图所需——它的存在即工具判定 Session 模型不能看图的依据):```tsinterface VisionDescriberService {diff --git a/packages/docs/content/models.en.md b/packages/docs/content/models.en.mdindex b9b3d0a1..a0240319 100644--- a/packages/docs/content/models.en.md+++ b/packages/docs/content/models.en.md@@ -30,7 +30,7 @@ Each Project's available models are recorded in the hidden `.project_config.toml| `pricing` | Three price buckets (unit `usd_per_mtok`, USD per million tokens): `cache_read` / `cache_write` / `output` || `api_key` / `base_url` | Inlined credentials, both optional; when blank, AgentHub falls back to environment variables |-A fresh Project defaults to deepseek-v4-flash-vision-exp, which reads images itself. A `vision_model` entry can additionally designate the proxy model that `describe_image` uses for text-only session models (see [Tools & Approval](/tools)); it is unset by default.+A fresh Project defaults to deepseek-v4-flash-vision-exp, which reads images itself. A `vision_model` entry can additionally designate the proxy model through which `read_file` reads images for text-only session models (see [Tools & Approval](/tools)); it is unset by default.File shape (illustrative):@@ -51,7 +51,7 @@ base_url = "https://llm.example.com/v1"api_key = "sk-..."```-For a model tagged `vision = false` (e.g. `deepseek-v4-flash`, the text-only sibling of the default), images from conversation input are saved to the Session scratchpad and handed over as a file path spliced into the text, and the image-reading tool switches to `describe_image`.+For a model tagged `vision = false` (e.g. `deepseek-v4-flash`, the text-only sibling of the default), images from conversation input are saved to the Session scratchpad and handed over as a file path spliced into the text, and `read_file` hands an image to the `vision_model` for description instead of returning it.## Built-in provider groups@@ -171,7 +171,7 @@ Two things the toggle cannot check for you:If a request does reach a client that rejects `fast_mode`, AgentHub refuses it **before any network request**: the session ends that turn immediately with the provider's message plus a pointer to the setting, and a deterministic rejection is never retried. An entry that stores `fast_mode = true` on a model that cannot serve it keeps its toggle in the dialog, marked unsupported, so it can always be switched off.-The connectivity test sends the dialog's current toggle state, so "Test connection" surfaces a fast-mode rejection before saving. Background requests (session title generation, `describe_image` proxy reads) never carry fast mode — only the session's own requests do.+The connectivity test sends the dialog's current toggle state, so "Test connection" surfaces a fast-mode rejection before saving. Background requests (session title generation, `read_file`'s vision-model proxy reads) never carry fast mode — only the session's own requests do.## Models decoupled from Agentsdiff --git a/packages/docs/content/models.zh.md b/packages/docs/content/models.zh.mdindex 00392594..4978ceff 100644--- a/packages/docs/content/models.zh.md+++ b/packages/docs/content/models.zh.md@@ -30,7 +30,7 @@ description: 经 AgentHub 单一网关接入模型,以 (provider, model_id)| `pricing` | 三档价格(单位 `usd_per_mtok`,USD 每百万 Token):`cache_read` / `cache_write` / `output` || `api_key` / `base_url` | 内联凭证,可留空;留空时 AgentHub 回退读环境变量 |-新建 Project 的默认模型是 deepseek-v4-flash-vision-exp,它自己就能读图。另可配置一条 `vision_model`,作为 text-only 模型使用 `describe_image` 时的代读模型(见 [工具与审批](/tools));默认不配置。+新建 Project 的默认模型是 deepseek-v4-flash-vision-exp,它自己就能读图。另可配置一条 `vision_model`,作为 text-only 模型用 `read_file` 读图时的代读模型(见 [工具与审批](/tools));默认不配置。文件形态(示意):@@ -51,7 +51,7 @@ base_url = "https://llm.example.com/v1"api_key = "sk-..."```-对标注 `vision = false` 的模型(如 `deepseek-v4-flash`,即默认模型的纯文本同族):对话输入中的图片会保存到 Session scratchpad,以文件路径形式拼入文本;读图工具切换为 `describe_image`。+对标注 `vision = false` 的模型(如 `deepseek-v4-flash`,即默认模型的纯文本同族):对话输入中的图片会保存到 Session scratchpad,以文件路径形式拼入文本;`read_file` 读图时改为交给 `vision_model` 代读、不再返回图片。## 内置 Provider 分组@@ -171,7 +171,7 @@ DeepSeek V4 只接受 `low`/`high`/`max`,服务端会把 `medium` 与 `xhigh`如果请求最终仍到达了拒绝 `fast_mode` 的 client,AgentHub 会在**发起网络请求之前**拒绝:该轮会话立即结束,错误信息带上厂商原文与设置入口指引,确定性的拒绝不会重试。若某个条目在不支持的模型上存有 `fast_mode = true`,弹窗仍会显示该开关并标注不支持,以便随时关闭。-连通性测试会携带弹窗当前的开关状态,因此「测试连通性」能在保存前暴露快速模式被拒的问题。后台请求(会话标题生成、`describe_image` 代读)不携带快速模式——只有会话自身的请求携带。+连通性测试会携带弹窗当前的开关状态,因此「测试连通性」能在保存前暴露快速模式被拒的问题。后台请求(会话标题生成、`read_file` 的视觉模型代读)不携带快速模式——只有会话自身的请求携带。## 模型与 Agent 解耦diff --git a/packages/docs/content/omni-message.en.md b/packages/docs/content/omni-message.en.mdindex f8d95ad5..ef7899ad 100644--- a/packages/docs/content/omni-message.en.md+++ b/packages/docs/content/omni-message.en.md@@ -94,7 +94,7 @@ interface ToolCallOutputPayload {type: "tool_call_output";role: "user";output: string;- images?: string[]; // data:<mime>;base64,… URLs (e.g. read_image results)+ images?: string[]; // data:<mime>;base64,… URLs (e.g. read_file's image results)tool_call_id: string;stop_reason?: StopReason;}diff --git a/packages/docs/content/omni-message.zh.md b/packages/docs/content/omni-message.zh.mdindex 943bd852..25542a5f 100644--- a/packages/docs/content/omni-message.zh.md+++ b/packages/docs/content/omni-message.zh.md@@ -94,7 +94,7 @@ interface ToolCallOutputPayload {type: "tool_call_output";role: "user";output: string;- images?: string[]; // data:<mime>;base64,… 列表(如 read_image 的结果)+ images?: string[]; // data:<mime>;base64,… 列表(如 read_file 读图的结果)tool_call_id: string;stop_reason?: StopReason;}diff --git a/packages/docs/content/tools.en.md b/packages/docs/content/tools.en.mdindex df14e792..f8e659a3 100644--- a/packages/docs/content/tools.en.md+++ b/packages/docs/content/tools.en.md@@ -65,28 +65,26 @@ Each tool is described by one `ToolDefinitionConfig`:| `description` | Tool description handed to the model || `parameters` | JSON Schema of the arguments || `permission` | `"r"` read-only / `"rw"` read-write |-| `forModel` | `"vision"` / `"text-only"`: selected by the Session model's class; omitted = available to all models |+| `forModel` | `"vision"` / `"text-only"`: selected by the Session model's class; omitted = available to all models (no built-in entry sets it — `read_file` serves both classes) || `timeoutMs` | Per-call timeout (ms), default 120000; `<=0` disables || `maxOutputLength` | Output length cap (characters); `<=0` disables || `call_description` | Per-tool toggle for the `description` call argument declared in `parameters` (required while on); missing = kept, `false` filters it and its `required` entry out of the schema at assembly |## Built-in tools-There are 9 built-in tools (assembled via `packages/core/src/environment/tools/registry.ts`):+There are 7 built-in tools (assembled via `packages/core/src/environment/tools/registry.ts`):| Tool | Permission | Timeout (ms) | Purpose || --- | --- | --- | --- || `exec_command` | rw | 120000 | Run a shell command in the Workspace via `bash -lc`, streaming stdout/stderr |-| `input_command` | rw | 130000 | Drive a command session by `process_id`: write stdin, send Ctrl-C, poll output, or terminate it (`kill: true`) |-| `read_file` | r | 30000 | Read a text file as a line-numbered (`cat -n`) window, paged by offset/limit |+| `input_command` | rw | 120000 | Drive a command session by `process_id`: write stdin, send Ctrl-C, poll output, or terminate it (`kill: true`) |+| `read_file` | r | 60000 | Read a text file as a line-numbered (`cat -n`) window paged by offset/limit, or an image (path or URL) as image content — described in text by the `vision_model` for a text-only model || `edit_file` | rw | 30000 | Exact-string replacement in an existing file, echoing a verification snippet || `write_file` | rw | 30000 | Create or overwrite a whole file, creating parent directories as needed || `run_subagent` | rw | 600000 | Delegate a self-contained subtask to a child Agent in the same Workspace || `input_subagent` | rw | 600000 | Poll a background subagent, steer it mid-run, stop its current run, or continue it with a follow-up prompt |-| `read_image` | r | 60000 | Read an image and return it as image content (vision models) |-| `describe_image` | r | 90000 | Have the configured `vision_model` read the image and answer in text (text-only models) |-Note that an existing agent's persisted `tools.builtin` list is frozen as written (the settings UI edits rows but adds none): agents created before this toolset do not pick up newer tools (e.g. the file tools) or newer arguments (`run_in_background`, `kill`, `abort`) automatically — and entries for since-removed tools (`kill_command`, `kill_subagent`) simply stop assembling: a model calling them gets the standard unknown-tool failure — hand-edit the agent's `system_config.yaml` and add the new entries (copy them from the default definitions in `packages/core/src/state/default-config.ts`) to adopt them.+Note that an existing agent's persisted `tools.builtin` list is frozen as written (the settings UI edits rows but adds none): agents created before this toolset do not pick up newer tools (e.g. the file tools) or newer arguments (`run_in_background`, `kill`, `abort`) automatically — and entries for since-removed tools (`kill_command`, `kill_subagent`, `read_image`, `describe_image`) simply stop assembling: a model calling them gets the standard unknown-tool failure. A stored `read_file` entry from before it read images keeps its old description and timeout (the implementation behind it already reads images) — hand-edit the agent's `system_config.yaml` (copy the entries from the default definitions in `packages/core/src/state/default-config.ts`) or run the kernel update from the agent's settings page to adopt the current definitions.### Call descriptions@@ -126,7 +124,7 @@ The tools' arguments (explicit keys):process_id: string; // required: the command-session id returned by exec_commandchars?: string; // characters for stdin; send "\u0003" alone to deliver Ctrl-C; empty = poll onlykill?: boolean; // true = terminate: kill the whole process group, return undelivered output, remove the session- yield_time_ms?: number; // wait; defaults 250 for writes, 120000 for empty polls (one poll waits out most builds; pass a smaller value to peek)+ yield_time_ms?: number; // wait; defaults 250 for writes, 110000 for empty polls (one poll waits out most builds; pass a smaller value to peek)description: string; // required while call_description is on}```@@ -137,13 +135,18 @@ On POSIX, Ctrl-C sends `SIGINT` to the session's process group, interrupting the`read_file` / `edit_file` / `write_file` run with the user's full permissions, same as the shell tool; relative paths resolve against the Workspace and absolute paths are allowed. A symlinked path is followed to the file it names — reads, edits and writes all land on that file, and the link stays a link. They are non-streaming (a single final output) and never throw — failures come back as explanatory text with `stop_reason: failed`.+`read_file` reads images as well as text. A png/jpeg/gif/webp file up to 5MB — recognized by its magic number, then by its extension — or an http(s) URL in `file_path` (a URL is only ever an image source; the response content-type is consulted first) takes the image branch, and what comes back depends on the Session model's vision flag: a model that accepts images gets the image itself as image content (the text output is a one-line `image/png, 123.4 kB`), while a text-only model gets the Project's configured `vision_model` answering `prompt` (default: a detailed description), streamed as the tool's text output — the image never enters that Session's history. Without a `vision_model`, an image read on a text-only Session fails with an explanation asking the user to pick one in the model settings. See [Models & Providers](/models). The branch is decided by the `VisionDescriberService` the SDK injects into the Environment for text-only Sessions only, so one config entry (no `forModel`) serves both model classes.+```ts-// read_file — cat -n style output (line number, tab, content); overlong single lines are-// truncated, and binary content (NUL bytes) is rejected with advice to use shell/image tools.+// read_file — cat -n style output (line number, tab, content) for text; overlong single lines+// are truncated, and binary content that is no supported image (NUL bytes) is rejected with+// advice to use the shell. An image (or an http(s) URL) returns image content or a text+// description instead, and ignores offset/limit.{- file_path: string; // required: absolute, or relative to the Workspace+ file_path: string; // required: absolute, or relative to the Workspace; an http(s) URL for an imageoffset?: number; // 1-based line to start from; default 1limit?: number; // max lines returned; default 2000 — a trailing note points at the continuation+ prompt?: string; // a question about an image, answered by the vision_model for a text-only model; default: a detailed description}// edit_file — the file must exist; old_string must occur exactly once (or set replace_all);@@ -201,23 +204,6 @@ The Web App's subagents panel drives a selected child with the **same composer a- The child Session inherits the parent Agent's approval callback, so the approval mode follows the parent.- The child Session gets its own Trace, linked from the parent by a `subagent` pointer event; child messages stream back into the parent flow tagged with `origin`. See [Sessions & Traces](/sessions-and-traces).-### Image tools--`read_image` and `describe_image` are mutually exclusive, selected by the Session model's vision flag. Both accept an http(s) URL or a Workspace path and support png/jpeg/gif/webp up to 5MB. Text-only models get `describe_image`: the image plus a prompt are forwarded to the Project's configured `vision_model`, whose text answer becomes the tool output. See [Models & Providers](/models).--```ts-// read_image (vision models)-{- source: string; // required: an http(s) URL, or a file path inside the Workspace-}--// describe_image (text-only models)-{- source: string; // required: as above- prompt?: string; // what to ask about the image; defaults to a detailed description-}-```-### Background completion reportsA task launched with `run_in_background: true` reports its completion as a **user message injected by the harness** — the model does not need to poll. The message opens with a `[background_task_done]` marker block (kind, id, status, one-line detail) followed by what ran and the tail of its yet-undelivered output (capped at 4000 characters; the Web App collapses the block into a one-line notice). Its `text` payload carries `sender: "harness"`, distinguishing it from human input in the Trace (see [OmniMessage](/omni-message)).diff --git a/packages/docs/content/tools.zh.md b/packages/docs/content/tools.zh.mdindex 7e766f54..d5d2deb7 100644--- a/packages/docs/content/tools.zh.md+++ b/packages/docs/content/tools.zh.md@@ -65,28 +65,26 @@ Recovery 文件保存 Environment 收到的未经脱敏的工具文本。误读| `description` | 提供给模型的工具说明 || `parameters` | 参数 JSON Schema || `permission` | `"r"` 只读 / `"rw"` 读写 |-| `forModel` | `"vision"` / `"text-only"`:按 Session 模型类别装配;缺省对所有模型可用 |+| `forModel` | `"vision"` / `"text-only"`:按 Session 模型类别装配;缺省对所有模型可用(内置条目均不设——`read_file` 同时服务两类模型) || `timeoutMs` | 单次调用超时(ms),默认 120000;`<=0` 关闭 || `maxOutputLength` | 输出长度上限(字符);`<=0` 关闭 || `call_description` | 条目级开关:控制 `parameters` 中声明的 `description` 调用参数(开启时为必填);缺省保留,`false` 时装配阶段将其连同 `required` 项从 schema 滤除 |## 内置工具-共 9 个内置工具(装配入口 `packages/core/src/environment/tools/registry.ts`):+共 7 个内置工具(装配入口 `packages/core/src/environment/tools/registry.ts`):| 工具 | 权限 | 超时(ms) | 用途 || --- | --- | --- | --- || `exec_command` | rw | 120000 | 在 Workspace 内以 `bash -lc` 运行命令,流式返回 stdout/stderr |-| `input_command` | rw | 130000 | 按 `process_id` 驱动命令会话:写 stdin、发 Ctrl-C、轮询输出,或终止(`kill: true`) |-| `read_file` | r | 30000 | 按 `cat -n` 风格带行号读取文本文件,以 offset/limit 分页 |+| `input_command` | rw | 120000 | 按 `process_id` 驱动命令会话:写 stdin、发 Ctrl-C、轮询输出,或终止(`kill: true`) |+| `read_file` | r | 60000 | 按 `cat -n` 风格带行号读取文本文件(以 offset/limit 分页),或读取图片(路径或 URL)作为图像内容返回——text-only 模型则由 `vision_model` 代读为文字 || `edit_file` | rw | 30000 | 对既有文件做精确字符串替换,回显校验片段 || `write_file` | rw | 30000 | 新建或整体覆写文件,按需创建父目录 || `run_subagent` | rw | 600000 | 把自包含子任务委派给同 Workspace 的子 Agent || `input_subagent` | rw | 600000 | 轮询后台 Subagent、运行中插话、停止其当前轮,或在其空闲时追加后续 Prompt |-| `read_image` | r | 60000 | 读取图片并作为图像内容返回(vision 模型) |-| `describe_image` | r | 90000 | 由 `vision_model` 代读图片并返回文字回答(text-only 模型) |-注意:既有 Agent 已落盘的 `tools.builtin` 列表按原样冻结(设置页只能编辑行、不能增行):较早创建的 Agent 不会自动获得后来新增的工具(如文件工具)与新增参数(`run_in_background`、`kill`、`abort`),已移除工具(`kill_command`、`kill_subagent`)的存量条目则不再装配——模型按旧名调用得到标准的未知工具报错;采纳新条目需手工编辑该 Agent 的 `system_config.yaml`(可从 `packages/core/src/state/default-config.ts` 的默认定义复制),或走「更新内核」。+注意:既有 Agent 已落盘的 `tools.builtin` 列表按原样冻结(设置页只能编辑行、不能增行):较早创建的 Agent 不会自动获得后来新增的工具(如文件工具)与新增参数(`run_in_background`、`kill`、`abort`),已移除工具(`kill_command`、`kill_subagent`、`read_image`、`describe_image`)的存量条目则不再装配——模型按旧名调用得到标准的未知工具报错;读图之前落盘的 `read_file` 条目保留旧描述与旧超时(其背后的实现已能读图)。采纳当前定义需手工编辑该 Agent 的 `system_config.yaml`(可从 `packages/core/src/state/default-config.ts` 的默认定义复制),或走「更新内核」。### 调用描述@@ -124,7 +122,7 @@ exec_command(cmd){process_id: string; // 必填:exec_command 返回的命令会话 idchars?: string; // 写入 stdin 的字符;单独发送 "\u0003" 传递 Ctrl-C;缺省仅轮询- yield_time_ms?: number; // 等待时长;有写入默认 250,空轮询默认 120000(一次轮询等完多数构建;想快速查看可传更小值)+ yield_time_ms?: number; // 等待时长;有写入默认 250,空轮询默认 110000(一次轮询等完多数构建;想快速查看可传更小值)description: string; // 开关开启时必填}@@ -136,13 +134,17 @@ POSIX 上 Ctrl-C 向会话进程组发送 `SIGINT`,中断前台命令。Window`read_file` / `edit_file` / `write_file` 与 Shell 工具一样以用户完整权限运行:相对路径按 Workspace 解析,也接受绝对路径。软链接路径会被解析到它指向的文件——读取、编辑、写入都落在该文件上,链接本身仍然是链接。三者均为非流式(一次性输出最终结果),从不抛异常——失败以解释性文本收尾,`stop_reason` 为 `failed`。+`read_file` 也读图片。png/jpeg/gif/webp 文件(不超过 5MB,先按魔数、再按扩展名识别)或 `file_path` 里的 http(s) URL(URL 只作图片来源,优先看响应的 content-type)走读图分支,返回什么取决于 Session 模型的 vision 标记:接受图片的模型拿到图片本身作为图像内容(文本输出只有一行 `image/png, 123.4 kB`);text-only 模型拿到的是 Project 配置的 `vision_model` 对 `prompt`(缺省为详细描述)的回答,以流式文本作为工具输出——图片不进入该 Session 的历史。未配置 `vision_model` 时,text-only Session 的读图以解释性错误失败,请用户到模型设置中选一个。见 [模型与 Provider](/models)。分支由 SDK 仅为 text-only Session 注入 Environment 的 `VisionDescriberService` 决定,因此同一条配置条目(不带 `forModel`)同时服务两类模型。+```ts-// read_file — cat -n 风格输出(行号、制表符、内容);超长单行会被截断,-// 含 NUL 字节的二进制内容被拒绝并提示改用 Shell / 图像工具。+// read_file — 文本文件按 cat -n 风格输出(行号、制表符、内容);超长单行会被截断,+// 不是受支持图片的二进制内容(含 NUL 字节)被拒绝并提示改用 Shell。图片(或 http(s) URL)+// 则返回图像内容或文字描述,并忽略 offset/limit。{- file_path: string; // 必填:绝对路径,或相对 Workspace 的路径+ file_path: string; // 必填:绝对路径,或相对 Workspace 的路径;图片亦可为 http(s) URLoffset?: number; // 起始行号(1 起);默认 1limit?: number; // 最多返回的行数;默认 2000——未读完时尾部注记提示续读+ prompt?: string; // 对图片的提问,text-only 模型时由 vision_model 回答;缺省为详细描述}// edit_file — 文件必须已存在;old_string 必须恰好出现一次(或设 replace_all);@@ -199,23 +201,6 @@ Web App 的智能体面板用**与主对话相同的 composer**(子会话变- 子 Session 继承父 Agent 的审批回调,审批模式随父生效。- 子 Session 拥有独立 Trace,父 Trace 以 `subagent` 指针事件链接;子消息带 `origin` 标记回流到父级消息流。见 [Session 与 Trace](/sessions-and-traces)。-### 图像工具--`read_image` 与 `describe_image` 互斥,按 Session 模型的 vision 标记二选一装配。两者都接受 http(s) URL 或 Workspace 路径,支持 png/jpeg/gif/webp,不超过 5MB。text-only 模型走 `describe_image`:图片连同提问转交 Project 配置的 `vision_model`,其文字回答即工具输出。见 [模型与 Provider](/models)。--```ts-// read_image(vision 模型)-{- source: string; // 必填:http(s) URL,或 Workspace 内的文件路径-}--// describe_image(text-only 模型)-{- source: string; // 必填:同上- prompt?: string; // 要对图片提出的问题;缺省为详细描述-}-```-### 后台完成回报以 `run_in_background: true` 启动的任务在结束时,以**Harness 注入的 user message** 回报完成——模型无需轮询。消息以 `[background_task_done]` 标记块开头(kind、id、status、一行 detail),其后是任务内容与尚未送达输出的尾部(上限 4000 字符;Web App 将标记块折叠为一行提示)。其 `text` payload 带 `sender: "harness"`,在 Trace 中与真人输入相区分(见 [OmniMessage](/omni-message))。diff --git a/packages/docs/content/web-app.en.md b/packages/docs/content/web-app.en.mdindex ef4970f5..a2452381 100644--- a/packages/docs/content/web-app.en.md+++ b/packages/docs/content/web-app.en.md@@ -156,7 +156,7 @@ Admin only, server-global: two sizes — the **per-file attachment cap** and theSaving takes effect immediately, with no restart: the attachment validators and the request body cap both read the setting per request. The body cap is not configured separately but derived from the total — attachments ride the request as base64 `data:` URLs, which inflates them by 4/3, so it has to rise with them or a request whose every attachment was individually legal would die at the HTTP layer instead.-Two numbers are deliberately not exposed. The per-message file **count** stays at 20: it bounds how usable the composer's chip row is, not what the server can survive — the byte budgets do that. And an inline **image** stays capped at 20MB rather than following the attachment limit up, because an image placed inline enters the conversation and the Trace, where its size is paid again on every history page and every session resume; the model side is lower still (providers commonly cap around 5MB, and the `read_image` tool at 5MB), so raising it to 100MB would only trade a clear refusal for a later, more confusing failure.+Two numbers are deliberately not exposed. The per-message file **count** stays at 20: it bounds how usable the composer's chip row is, not what the server can survive — the byte budgets do that. And an inline **image** stays capped at 20MB rather than following the attachment limit up, because an image placed inline enters the conversation and the Trace, where its size is paid again on every history page and every session resume; the model side is lower still (providers commonly cap around 5MB, and `read_file` reads an image of at most 5MB), so raising it to 100MB would only trade a clear refusal for a later, more confusing failure.## Version and Updatesdiff --git a/packages/docs/content/web-app.zh.md b/packages/docs/content/web-app.zh.mdindex afa3b0a8..af34fe69 100644--- a/packages/docs/content/web-app.zh.md+++ b/packages/docs/content/web-app.zh.md@@ -155,7 +155,7 @@ Memory 标签页的开关拨动即写入,不参与标签页的保存按钮,保存即刻生效,无需重启:附件校验与请求体上限都在每次请求时读取该设置。请求体上限本身不单独配置,而是由合计上限推导——附件以 base64 `data:` URL 随请求送达,体积膨胀 4/3,因此上限必须随之上浮,否则每个附件单独合法的请求会在 HTTP 层被拒。-有两个数值刻意不开放:单条消息的附件**数量**上限固定为 20(它约束的是输入框的可用性,而非服务器资源),对话内嵌**图片**上限固定为 20MB。图片不随附件上限放宽是有意为之——图片进入对话与轨迹,其体积在每次翻阅历史与恢复会话时被反复付出;而且模型侧另有更低的实际限制(供应商通常约 5MB,`read_image` 工具亦为 5MB),把它放宽到 100MB 只会把一个清晰的拒绝换成更靠后、更难懂的失败。+有两个数值刻意不开放:单条消息的附件**数量**上限固定为 20(它约束的是输入框的可用性,而非服务器资源),对话内嵌**图片**上限固定为 20MB。图片不随附件上限放宽是有意为之——图片进入对话与轨迹,其体积在每次翻阅历史与恢复会话时被反复付出;而且模型侧另有更低的实际限制(供应商通常约 5MB,`read_file` 读图亦为 5MB),把它放宽到 100MB 只会把一个清晰的拒绝换成更靠后、更难懂的失败。## 版本与更新diff --git a/packages/server/src/api/types.ts b/packages/server/src/api/types.tsindex d92ca2b8..ed1deed9 100644--- a/packages/server/src/api/types.ts+++ b/packages/server/src/api/types.ts@@ -431,7 +431,7 @@ export interface ModelInfo {export interface ModelsResponse {/** Paired reference to the default Model. */defaultModel?: ModelRefDto;- /** Vision model used as a proxy reader for read_image (describes images when the session model has vision=false). */+ /** Vision model used as a proxy reader for read_file (describes images when the session model has vision=false). */visionModel?: ModelRefDto;/*** When the Project's model/credential config last changed (ISO; the config file's mtime,@@ -479,7 +479,7 @@ export interface ModelUpdateEntry {export interface ModelsUpdateRequest {/** Must be included in models (matched by paired reference). */defaultModel?: ModelRefDto;- /** Vision model used as a proxy reader for read_image: must be included in models and not annotated vision=false; omitted keeps the existing value. */+ /** Vision model used as a proxy reader for read_file: must be included in models and not annotated vision=false; omitted keeps the existing value. */visionModel?: ModelRefDto;models: ModelUpdateEntry[];}diff --git a/packages/server/src/runtime/messaging/telegram-connector.ts b/packages/server/src/runtime/messaging/telegram-connector.tsindex a457a65b..b67acfb4 100644--- a/packages/server/src/runtime/messaging/telegram-connector.ts+++ b/packages/server/src/runtime/messaging/telegram-connector.ts@@ -386,7 +386,7 @@ function normalizeUpdate(//// A picture dragged in uncompressed is a `document` too, and lands as an attachment// rather than as an inline image: the sender asked for the original bytes to arrive, and- // the model opens the path with `read_image` like any other file.+ // the model opens the path with `read_file` like any other file.const doc = msg.document ?? null;const files: MessagingInboundFile[] =doc === nulldiff --git a/packages/server/src/services/attachment-limits.ts b/packages/server/src/services/attachment-limits.tsindex 349f817d..4c5782eb 100644--- a/packages/server/src/services/attachment-limits.ts+++ b/packages/server/src/services/attachment-limits.ts@@ -82,7 +82,7 @@ export const MAX_ATTACHMENT_COUNT = 20;* paste that works today stops working; it is a bound where there was none, not a new restriction.** Note this is the *transport* ceiling, not a promise the model will accept the image: providers- * impose their own per-image limits (commonly ~5MB), and core's `read_image` tool caps at 5MB.+ * impose their own per-image limits (commonly ~5MB), and core's `read_file` caps an image at 5MB.* An image between those numbers and this one uploads fine and may still be refused by the model.*/export const INLINE_IMAGE_MAX_MB = 20;diff --git a/packages/web/src/features/chat/chat-input.tsx b/packages/web/src/features/chat/chat-input.tsxindex c22cd96f..b727faca 100644--- a/packages/web/src/features/chat/chat-input.tsx+++ b/packages/web/src/features/chat/chat-input.tsx@@ -2181,7 +2181,7 @@ export function ChatInput({{/* When the model doesn't support viewing images directly: images still upload as usual,and on send the server writes them to the session's scratchpad and appends the file- path into the message text (the model views them via describe_image). A small note is+ path into the message text (the model views them via read_file). A small note isshown while images are attached. */}{!vision && images.length > 0 && (<p className="anim-fade mb-1 text-xs text-gray-400 dark:text-gray-500">diff --git a/packages/web/src/features/chat/tool-call-card.tsx b/packages/web/src/features/chat/tool-call-card.tsxindex 189ef0e0..2e7ce9d7 100644--- a/packages/web/src/features/chat/tool-call-card.tsx+++ b/packages/web/src/features/chat/tool-call-card.tsx@@ -48,6 +48,21 @@ const DESCRIBED_TOOLS = new Set([/** The three file tools: previewed by their `file_path` argument. */const FILE_TOOLS = new Set(["read_file", "edit_file", "write_file"]);+/**+ * Tool names Traces carried before `read_file` absorbed image reading (2026-09-02): their+ * image argument was `source`, previewed here like a file path so an old Trace's card still+ * reads sensibly. Display-only — nothing assembles these tools any more. Removable once+ * Traces written before that date no longer need rendering.+ */+const LEGACY_IMAGE_TOOLS = new Set(["read_image", "describe_image"]);++/** The path-like argument a tool is previewed by: `file_path` for the file tools, `source` for the historical image tools. */+function pathArgument(name: string): string | null {+ if (FILE_TOOLS.has(name)) return "file_path";+ if (LEGACY_IMAGE_TOOLS.has(name)) return "source";+ return null;+}+/*** Shortens a path for one-line display: at most one parent directory plus the filename* (`…/parent/file.ts`); paths already within that shape are shown as-is (same rule as the@@ -72,8 +87,9 @@ export function previewArguments(name: string, argsJson: string): string {const cmd = extractStringField(argsJson, "cmd");if (cmd !== null) return `$ ${cmd.value.replace(/\s+/g, " ").trim()}`;}- if (FILE_TOOLS.has(name)) {- const filePath = extractStringField(argsJson, "file_path");+ const pathArg = pathArgument(name);+ if (pathArg !== null) {+ const filePath = extractStringField(argsJson, pathArg);if (filePath !== null) return shortenPath(filePath.value.replace(/\s+/g, " ").trim());}return argsJson.replace(/\s+/g, " ").trim();@@ -108,8 +124,9 @@ export function headerSubtitle(name: string, argsJson: string, settled = true):}if (DESCRIBED_TOOLS.has(name)) return null;}- if (FILE_TOOLS.has(name)) {- const filePath = extractStringField(argsJson, "file_path");+ const pathArg = pathArgument(name);+ if (pathArg !== null) {+ const filePath = extractStringField(argsJson, pathArg);if (filePath !== null) {if (!filePath.complete && !settled) return null;const line = filePath.value.replace(/\s+/g, " ").trim();@@ -171,6 +188,8 @@ export function pendingFilePayload(name: string, argsJson: string): string | nulif (name === "read_file") {push("offset", args["offset"]);push("limit", args["limit"]);+ // The image branch's question is sent to the vision model, so it is part of what is approved.+ push("prompt", args["prompt"]);} else if (name === "edit_file") {push("old_string", args["old_string"]);push("new_string", args["new_string"]);@@ -414,7 +433,7 @@ export function ToolCallCard({ item, ctx }: { item: ToolCallItem; ctx: StreamRen{item.outputStreaming && <span className="animate-pulse">▌</span>}</pre>)}- {/* Tool output images (e.g. read_image): shown as thumbnails, click to zoom (ZoomableImage). */}+ {/* Tool output images (e.g. read_file on an image): shown as thumbnails, click to zoom (ZoomableImage). */}{item.images && item.images.length > 0 && (<div className="flex flex-wrap gap-2 border-t border-gray-100 px-3 py-2 dark:border-gray-800">{item.images.map((src, i) => (diff --git a/packages/web/src/features/models/models-page.tsx b/packages/web/src/features/models/models-page.tsxindex 205c3b53..0c1512c8 100644--- a/packages/web/src/features/models/models-page.tsx+++ b/packages/web/src/features/models/models-page.tsx@@ -631,7 +631,7 @@ export function ModelsPage() {const [rows, setRows] = useState<RowState[] | null>(null);const [defaultModel, setDefaultModel] = useState<ModelRefDto | undefined>(undefined);- // Vision model used for describe_image proxy-reads (describes images for session models with vision=false).+ // Vision model used for read_file's proxy reads (describes images for session models with vision=false).const [visionModel, setVisionModel] = useState<ModelRefDto | undefined>(undefined);/** Edit target: paired reference of an existing row. */const [editing, setEditing] = useState<ModelRefDto | null>(null);@@ -3222,7 +3222,7 @@ function ModelDialog({(read-only, so no cell at all); custom models toggle it here — an iOS-styleswitch sitting inline right next to the label (per owner: no full-row stretch,no standing explanation text). Only the OFF state shows one small muted line:- images are then read via the configured vision proxy model (describe_image). */}+ images are then read via the configured vision proxy model (read_file hands them to it). */}{showVision && (<div className={toggleCellClass}>{/* Detect sits inline after the switch — the protocol control's idiom, but nextdiff --git a/packages/web/src/features/traces/trace-event-row.tsx b/packages/web/src/features/traces/trace-event-row.tsxindex 3d2b799e..a940290c 100644--- a/packages/web/src/features/traces/trace-event-row.tsx+++ b/packages/web/src/features/traces/trace-event-row.tsx@@ -375,7 +375,7 @@ function EventBody({ msg }: { msg: OmniMessage }) {</div>);case "tool_call_output": {- // Tool output carrying images (e.g. read_image): render images below the text code block.+ // Tool output carrying images (e.g. read_file on an image): render images below the text code block.const images = Array.isArray(p.images) ? (p.images as string[]) : [];if (images.length === 0) return <pre className={codeBlock}>{String(p.output ?? "")}</pre>;return (diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.tsindex 85949b55..a5e23f7d 100644--- a/packages/web/src/lib/strings-en.ts+++ b/packages/web/src/lib/strings-en.ts@@ -864,7 +864,7 @@ export const en: Strings = {usedTokens: (v: string) => `${v} toks`,usedTokensTitle: "Tokens this model has used, all time",setVisionModel: "Set as proxy vision model",- visionModelHint: "Describes images via describe_image for models without vision",+ visionModelHint: "Describes images for models without vision when they read one with read_file",priceUnitShort: "/M tok",testConnection: "Test connection",testing: "Testing…",@@ -934,7 +934,7 @@ export const en: Strings = {},confirmVisionModelTitle: "Set as proxy vision model",confirmVisionModel: (name: string): string =>- `Make "${name}" the proxy vision model? Models without vision will read images through it via describe_image.`,+ `Make "${name}" the proxy vision model? Models without vision will read images through it when they call read_file.`,confirmSaveTitle: "Save model settings",confirmSave: (name: string): string => `Save the changes to "${name}"?`,confirmDefaultTitle: "Set as default model",@@ -1702,7 +1702,7 @@ Scenarios:imageAlt: "Image uploaded by user",toolImageAlt: "Image from tool output",imagesAsPathHint:- "This model cannot view images directly: on send, images are saved to the session scratchpad and passed as file paths (viewed via describe_image)",+ "This model cannot view images directly: on send, images are saved to the session scratchpad and passed as file paths (viewed via read_file)",infoPanel: "Session info",sessionStats: "Stats",/** Info-dropdown Session id row: the id itself is a click-to-copy button. */diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.tsindex fbd23779..bca0d484 100644--- a/packages/web/src/lib/strings.ts+++ b/packages/web/src/lib/strings.ts@@ -807,7 +807,7 @@ export const zh = {detectVisionNeedsId: "请先填写模型 id,再进行检测。",detectVisionOk: "该模型接受图片输入,已开启视觉",detectVisionNo: "该模型不接受图片输入,视觉保持关闭",- /** Shown only while the vision switch is OFF: images are then read via the configured vision proxy model (describe_image). */+ /** Shown only while the vision switch is OFF: images are then read via the configured vision proxy model (read_file hands them to it). */visionOffProxyHint: "使用视觉代理模型读图",/** Switch label for the per-model fast mode (the provider's premium faster serving tier); the switch is only rendered for models whose AgentHub client can carry the parameter. */fastMode: "快速模式",@@ -844,7 +844,7 @@ export const zh = {usedTokens: (v: string) => `${v} toks`,usedTokensTitle: "该模型累计消耗的 Token(不限时间范围)",setVisionModel: "设为视觉代理模型",- visionModelHint: "供不支持图片的模型经 describe_image 代读图片",+ visionModelHint: "供不支持图片的模型在 read_file 读图时代读",priceUnitShort: "/M tok",testConnection: "测试连通性",testing: "测试中…",@@ -916,7 +916,7 @@ export const zh = {} as Record<string, string | undefined>,confirmVisionModelTitle: "设为视觉代理模型",confirmVisionModel: (name: string): string =>- `确定把「${name}」设为视觉代理模型?不支持图片的模型将由它经 describe_image 代读图片。`,+ `确定把「${name}」设为视觉代理模型?不支持图片的模型用 read_file 读图时将由它代读。`,confirmSaveTitle: "保存模型配置",confirmSave: (name: string): string => `确定保存对「${name}」的配置修改?`,confirmDefaultTitle: "设为默认模型",@@ -1667,7 +1667,7 @@ Benchmark:imageAlt: "用户上传的图片",toolImageAlt: "工具输出的图片",imagesAsPathHint:- "当前模型不支持直接查看图片:发送时图片将保存到会话临时目录,以文件路径转交(模型经 describe_image 查看)",+ "当前模型不支持直接查看图片:发送时图片将保存到会话临时目录,以文件路径转交(模型经 read_file 查看)",infoPanel: "Session 信息",sessionStats: "统计",/** Info-dropdown Session id row: the id itself is a click-to-copy button. */diff --git a/packages/web/test/stream-model.test.ts b/packages/web/test/stream-model.test.tsindex c00d5138..0b3350f9 100644--- a/packages/web/test/stream-model.test.ts+++ b/packages/web/test/stream-model.test.ts@@ -215,7 +215,7 @@ describe("partial aggregation and full-message convergence", () => {const m = createStreamModel();pushMessage(m,- toolCall({ name: "read_image", arguments: '{"source":"a.png"}', toolCallId: "t4" }),+ toolCall({ name: "read_file", arguments: '{"file_path":"a.png"}', toolCallId: "t4" }),);const card = items(m)[0] as ToolCallItem;expect(card.images).toBeUndefined();diff --git a/packages/web/test/tool-call-preview.test.ts b/packages/web/test/tool-call-preview.test.tsindex 16cdeee7..c0da45c9 100644--- a/packages/web/test/tool-call-preview.test.ts+++ b/packages/web/test/tool-call-preview.test.ts@@ -40,6 +40,14 @@ describe("previewArguments", () => {).toBe("$ rm -rf build");});+ it("previews the historical image tools by their source argument (old Traces)", () => {+ expect(previewArguments("read_image", '{"source":"shots/home.png"}')).toBe("shots/home.png");+ expect(+ previewArguments("describe_image", '{"source":"https://x.test/a/b/c.png","prompt":"?"}'),+ ).toBe("…/b/c.png");+ expect(headerSubtitle("read_image", '{"source":"shots/home.png"}')).toBe("shots/home.png");+ });+it("falls back to the single-line raw arguments for other tools", () => {expect(previewArguments("search", '{"q": "a\n b"}')).toBe('{"q": "a b"}');});@@ -141,6 +149,10 @@ describe("pendingFilePayload", () => {expect(pendingFilePayload("read_file", '{"file_path":"a.txt","offset":3,"limit":5}')).toBe("file_path: a.txt\noffset: 3\nlimit: 5",);+ // read_file's image branch forwards `prompt` to the vision model: it must be visible too.+ expect(+ pendingFilePayload("read_file", '{"file_path":"shot.png","prompt":"read the error"}'),+ ).toBe("file_path: shot.png\nprompt: read the error");});it("returns null for non-file tools and incomplete JSON", () => {diff --git a/plugins/agent-development/skills/penguin-sdk/SKILL.md b/plugins/agent-development/skills/penguin-sdk/SKILL.mdindex b2e4b11f..260dad91 100644--- a/plugins/agent-development/skills/penguin-sdk/SKILL.md+++ b/plugins/agent-development/skills/penguin-sdk/SKILL.md@@ -112,7 +112,7 @@ import { imageUrlMessage, userText } from "@prismshadow/penguin-core";session.run([userText(question), ...images.map(imageUrlMessage)], { ... });```-Browser flow: `<input type="file" accept="image/*">` plus paste/drag-drop → `FileReader.readAsDataURL` → POST `{ question, images: [dataUrl] }` → the server maps each entry to `imageUrlMessage`. Reject non-image MIME types and cap size (a data URL rides the context window; a few MB is plenty). Whether the session model actually sees pixels is the model config's `vision` flag (`penguin config model list` prints `vision=Y/-`; set via `--vision/--no-vision` on `model add`, default supported): with `vision=false` the core folds the image into an `[attached image: <path>]` line and the built-in image tools read it through the project's configured `vision_model` (`penguin config model vision --provider <group> --model-id <id> --root <data_dir>`) — the app still works, through a description instead of direct sight.+Browser flow: `<input type="file" accept="image/*">` plus paste/drag-drop → `FileReader.readAsDataURL` → POST `{ question, images: [dataUrl] }` → the server maps each entry to `imageUrlMessage`. Reject non-image MIME types and cap size (a data URL rides the context window; a few MB is plenty). Whether the session model actually sees pixels is the model config's `vision` flag (`penguin config model list` prints `vision=Y/-`; set via `--vision/--no-vision` on `model add`, default supported): with `vision=false` the core folds the image into an `[attached image: <path>]` line and the built-in `read_file` tool reads it through the project's configured `vision_model` (`penguin config model vision --provider <group> --model-id <id> --root <data_dir>`) — the app still works, through a description instead of direct sight.**Other payloads worth handling** (always narrow with the guards first): `partial_tool_call` / `partial_tool_call_output` — surface as an activity line ("running `search`…") in apps that grant tools; `request_end` (event) — a non-`completed` `status` is the error signal (`auth` → ask for a key; `message` carries the failure detail; `retry_in_ms` announces a planned in-run retry, renderable as a countdown); `token_usage` (event) — session-cumulative and last-request counts, if the app shows cost; `compaction_begin` / `compaction_end` (events) — long-lived chats only, show a brief "context being compacted" notice. Everything else is safe to ignore.