Skip to content

JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.

Python

fix: 支持原生多模态能力

openJiuwen-bot9050bcb4eb4c
diff --git a/jiuwenswarm/agents/harness/common/auto_harness/scheduler.py b/jiuwenswarm/agents/harness/common/auto_harness/scheduler.py
index 54929b5bbc..34ec2a037a 100644
--- a/jiuwenswarm/agents/harness/common/auto_harness/scheduler.py
+++ b/jiuwenswarm/agents/harness/common/auto_harness/scheduler.py
@@ -73,13 +73,12 @@ class Scheduler:
"""Build model cache from jiuwenswarm config.yaml (reuse interface_deep logic)."""
try:
from jiuwenswarm.common.config import get_config, get_default_models
- from jiuwenswarm.server.runtime.agent_adapter.interface_deep import JiuWenSwarmDeepAdapter
+ from jiuwenswarm.server.runtime.agent_adapter.interface_deep import (
+ _build_model_from_entry as build_model_from_entry,
+ )
config = get_config()
- # Use the same model building method as interface_deep
- build_model_from_entry = getattr(JiuWenSwarmDeepAdapter, '_build_model_from_entry')
-
# Build from models.defaults list
for entry in get_default_models(config):
mcc = entry.get("model_client_config") or {}
@@ -87,7 +86,14 @@ class Scheduler:
if not model_name:
continue
mco = entry.get("model_config_obj") or {}
- self._model_cache[model_name] = build_model_from_entry(mcc, mco)
+ # 与 agent_ws_server / interface_deep 保持一致:模型条目的能力声明
+ # (modalities)必须透传,否则同样配置经 scheduler
+ # 路径构建的缓存会静默丢失看图能力(S_22 铁律 46)。
+ self._model_cache[model_name] = build_model_from_entry(
+ mcc,
+ mco,
+ modalities=entry.get("modalities"),
+ )
# Fallback to legacy format if needed (same as interface_deep._build_model_cache_legacy)
if not self._model_cache:
@@ -106,7 +112,13 @@ class Scheduler:
or react_config.get("model_config_obj")
or {}
)
- self._model_cache[model_name] = build_model_from_entry(mcc, mco)
+ self._model_cache[model_name] = build_model_from_entry(
+ mcc,
+ mco,
+ modalities=default_model_config.get("modalities")
+ if default_model_config.get("modalities") is not None
+ else react_config.get("modalities"),
+ )
# Set default model (first one)
if self._model_cache:
diff --git a/jiuwenswarm/agents/harness/common/multimodal/__init__.py b/jiuwenswarm/agents/harness/common/multimodal/__init__.py
new file mode 100644
index 0000000000..87c0e19672
--- /dev/null
+++ b/jiuwenswarm/agents/harness/common/multimodal/__init__.py
@@ -0,0 +1,195 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.
+
+"""Multimodal image input package (native image blocks for chat-model context).
+
+拆分自原 ``common/prompt/user_prompt_builder.py``:内容原语(``image_content``)/
+图片处理与计量(``image_processing``)/ 引用行与状态行(``image_reference``)/
+历史注入与预算(``image_history``)。依赖方向单向:content、processing 无本地依赖,
+reference 依赖前两者,history 依赖三者,本模块只做显式汇总(不使用 ``import *``)。
+"""
+
+from __future__ import annotations
+
+from .image_content import (
+ _IMAGE_CONTENT_TYPES,
+ IMAGE_CONTENT_OMITTED,
+ _content_to_query_text,
+ _copy_message_with_content,
+ _message_content,
+ _message_role,
+ _part_with_text,
+ _text_from_content_part,
+ count_image_content_blocks,
+ filter_image_content_from_view,
+ is_image_content_block,
+ is_user_authored_message,
+ strip_image_content_blocks,
+)
+from .image_history import (
+ _MULTIMODAL_IMAGE_WINDOW_MUTATOR_ATTR,
+ _append_image_part,
+ _append_parts,
+ _append_state_marker,
+ _apply_image_budget,
+ _apply_image_evictions,
+ _collect_image_slots,
+ _message_parts,
+ _precompute_pending_data_uris,
+ _replace_attached_state_line,
+ _rewrite_reference_line_index,
+ _set_message_content,
+ _slot_image_part,
+ ensure_multimodal_image_filter_window_mutator,
+ inject_image_content_from_references,
+ remove_multimodal_image_filter_window_mutator,
+)
+from .image_processing import (
+ _IMAGE_EXT_TO_MIME,
+ _IMAGE_FORMAT_TO_MIME,
+ _IMAGE_VISUAL_TOKEN_CACHE,
+ _IMAGE_VISUAL_TOKEN_CACHE_LIMIT,
+ _JPEG_QUALITY_STEPS,
+ _MAX_IMAGE_SOURCE_BYTES,
+ _MAX_VISION_INLINE_IMAGE_BYTES,
+ _MAX_VISION_INLINE_IMAGE_DIMENSION,
+ _MIN_SHRINK_DIMENSION,
+ _SHRINK_SCALE_STEP,
+ _VISION_BASE_TOKENS,
+ _VISION_INLINE_IMAGE_MIME_TYPES,
+ _VISION_TILE_SIZE,
+ _VISION_TOKENS_PER_TILE,
+ _WEBP_QUALITY_STEPS,
+ _build_data_uri,
+ _clamp_sent_dimensions,
+ _data_uri_bytes,
+ _data_uri_visual_tokens,
+ _encode_within_bytes,
+ _image_block_bytes,
+ _image_block_visual_tokens,
+ _image_data_uri_from_path,
+ _image_file_size_bytes,
+ _image_file_visual_tokens,
+ _prepare_for_resize,
+ _read_image_dimensions,
+ _resize_to_max_dimension,
+ _save_image,
+ _shrink_image_local,
+ _shrink_image_to_bytes,
+ estimate_image_visual_tokens,
+ shrink_image,
+)
+from .image_reference import (
+ _CURRENT_MULTIMODAL_IMAGE_FILES,
+ _IMAGE_ATTACHED_LINE_RE,
+ _IMAGE_REFERENCE_LINE_RE,
+ _IMAGE_STATE_LINE_RE,
+ _READ_FILE_IMAGE_TEXT_RE,
+ _build_image_state_line,
+ _iter_text_values,
+ _message_image_states,
+ _message_omitted_image_reasons,
+ _normalize_image_file,
+ _normalize_image_files,
+ build_image_reference_line,
+ collect_image_references_from_messages,
+ collect_omitted_image_paths,
+ collect_provided_image_paths,
+ current_multimodal_image_files,
+ current_multimodal_image_files_from_agent,
+ extract_multimodal_image_files,
+ is_provided_image_path,
+ normalize_image_path,
+ parse_image_references,
+ reset_current_multimodal_image_files,
+ set_current_multimodal_image_files,
+ store_current_multimodal_image_files_on_agent,
+)
+
+__all__ = [
+ "IMAGE_CONTENT_OMITTED",
+ "_CURRENT_MULTIMODAL_IMAGE_FILES",
+ "_IMAGE_ATTACHED_LINE_RE",
+ "_IMAGE_CONTENT_TYPES",
+ "_IMAGE_EXT_TO_MIME",
+ "_IMAGE_FORMAT_TO_MIME",
+ "_IMAGE_REFERENCE_LINE_RE",
+ "_IMAGE_STATE_LINE_RE",
+ "_IMAGE_VISUAL_TOKEN_CACHE",
+ "_IMAGE_VISUAL_TOKEN_CACHE_LIMIT",
+ "_JPEG_QUALITY_STEPS",
+ "_MAX_IMAGE_SOURCE_BYTES",
+ "_MAX_VISION_INLINE_IMAGE_BYTES",
+ "_MAX_VISION_INLINE_IMAGE_DIMENSION",
+ "_MIN_SHRINK_DIMENSION",
+ "_MULTIMODAL_IMAGE_WINDOW_MUTATOR_ATTR",
+ "_READ_FILE_IMAGE_TEXT_RE",
+ "_SHRINK_SCALE_STEP",
+ "_VISION_BASE_TOKENS",
+ "_VISION_INLINE_IMAGE_MIME_TYPES",
+ "_VISION_TILE_SIZE",
+ "_VISION_TOKENS_PER_TILE",
+ "_WEBP_QUALITY_STEPS",
+ "_append_image_part",
+ "_append_parts",
+ "_append_state_marker",
+ "_apply_image_budget",
+ "_apply_image_evictions",
+ "_build_data_uri",
+ "_build_image_state_line",
+ "_clamp_sent_dimensions",
+ "_collect_image_slots",
+ "_content_to_query_text",
+ "_copy_message_with_content",
+ "_data_uri_bytes",
+ "_data_uri_visual_tokens",
+ "_encode_within_bytes",
+ "_image_block_bytes",
+ "_image_block_visual_tokens",
+ "_image_data_uri_from_path",
+ "_image_file_size_bytes",
+ "_image_file_visual_tokens",
+ "_iter_text_values",
+ "_message_content",
+ "_message_image_states",
+ "_message_omitted_image_reasons",
+ "_message_parts",
+ "_message_role",
+ "_normalize_image_file",
+ "_normalize_image_files",
+ "_part_with_text",
+ "_precompute_pending_data_uris",
+ "_prepare_for_resize",
+ "_read_image_dimensions",
+ "_replace_attached_state_line",
+ "_resize_to_max_dimension",
+ "_rewrite_reference_line_index",
+ "_save_image",
+ "_set_message_content",
+ "_shrink_image_local",
+ "_shrink_image_to_bytes",
+ "_slot_image_part",
+ "_text_from_content_part",
+ "build_image_reference_line",
+ "collect_image_references_from_messages",
+ "collect_omitted_image_paths",
+ "collect_provided_image_paths",
+ "count_image_content_blocks",
+ "current_multimodal_image_files",
+ "current_multimodal_image_files_from_agent",
+ "ensure_multimodal_image_filter_window_mutator",
+ "estimate_image_visual_tokens",
+ "extract_multimodal_image_files",
+ "filter_image_content_from_view",
+ "inject_image_content_from_references",
+ "is_image_content_block",
+ "is_provided_image_path",
+ "is_user_authored_message",
+ "normalize_image_path",
+ "parse_image_references",
+ "remove_multimodal_image_filter_window_mutator",
+ "reset_current_multimodal_image_files",
+ "set_current_multimodal_image_files",
+ "shrink_image",
+ "store_current_multimodal_image_files_on_agent",
+ "strip_image_content_blocks",
+]
diff --git a/jiuwenswarm/agents/harness/common/multimodal/image_content.py b/jiuwenswarm/agents/harness/common/multimodal/image_content.py
new file mode 100644
index 0000000000..e81fd74185
--- /dev/null
+++ b/jiuwenswarm/agents/harness/common/multimodal/image_content.py
@@ -0,0 +1,161 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.
+
+"""Content-level helpers for image blocks in conversation messages.
+
+无本地依赖的纯函数层:图片块判定、视图剥离、消息角色与文本抽取。``reference`` /
+``history`` 复用这里的消息访问原语;本模块不 import 包内其它模块,也不 import PIL。
+"""
+
+from __future__ import annotations
+
+import copy
+from typing import Any
+
+IMAGE_CONTENT_OMITTED = (
+ "[Image content omitted from chat-model context. Use the original image "
+ "path or a vision tool when image analysis is required.]"
+)
+
+
+_IMAGE_CONTENT_TYPES = frozenset({"image", "image_url", "input_image"})
+
+
+def is_image_content_block(part: Any) -> bool:
+ if not isinstance(part, dict):
+ return False
+ block_type = str(part.get("type") or "").strip().lower()
+ if block_type in _IMAGE_CONTENT_TYPES:
+ return True
+ return "image_url" in part or "image" in part
+
+
+def strip_image_content_blocks(content: Any) -> tuple[Any, int]:
+ if not isinstance(content, list):
+ return content, 0
+
+ kept_parts: list[Any] = []
+ removed = 0
+ for part in content:
+ if is_image_content_block(part):
+ removed += 1
+ continue
+ kept_parts.append(part)
+
+ if not removed:
+ return content, 0
+ if not kept_parts:
+ return IMAGE_CONTENT_OMITTED, removed
+
+ text_parts: list[str] = []
+ for part in kept_parts:
+ text = _text_from_content_part(part)
+ if text is None:
+ return kept_parts, removed
+ if text:
+ text_parts.append(text)
+ return "\n".join(text_parts).strip() or IMAGE_CONTENT_OMITTED, removed
+
+
+def count_image_content_blocks(messages: Any) -> int:
+ """统计历史里实际存在的 ``image_url`` 块数量(= 模型这次能看到的图片张数)。
+
+ 注入后的视图口径:``inject_image_content_from_references`` 的 ``attached`` 只是
+ 本轮**新增**张数,同一轮第二次 LLM 调用为 0;而策略段与视觉工具护栏要判断的是
+ "视图里到底有没有像素",因此按历史实际块计数。
+ """
+
+ total = 0
+ for message in messages or ():
+ content = message.get("content") if isinstance(message, dict) else getattr(
+ message, "content", None
+ )
+ if not isinstance(content, list):
+ continue
+ total += sum(1 for part in content if is_image_content_block(part))
+ return total
+
+
+def _message_content(message: Any) -> Any:
+ if isinstance(message, dict):
+ return message.get("content")
+ return getattr(message, "content", None)
+
+
+def _message_role(message: Any) -> str:
+ if isinstance(message, dict):
+ role = message.get("role")
+ else:
+ role = getattr(message, "role", None)
+ return str(role or "").strip().lower()
+
+
+def is_user_authored_message(message: Any) -> bool:
+ """Whether the message text comes from the user (reference lines are user-only).
+
+ 引用行只由上传入口写入 user 消息;tool result / assistant / web_fetch 正文里的
+ 同名格式行不得触发本地图片内联(否则内容注入可绕过 file_guard 外带磁盘图片)。
+ """
+
+ return _message_role(message) in {"user", "human"}
+
+
+def filter_image_content_from_view(messages: list[Any]) -> tuple[list[Any], int]:
+ """Return a new message list with image content blocks stripped from view copies.
+
+ Historical messages are never modified: each affected message is replaced by a
+ view copy produced via ``_copy_message_with_content``.
+ """
+
+ view_messages = list(messages)
+ removed_total = 0
+ for index, message in enumerate(view_messages):
+ sanitized_content, removed = strip_image_content_blocks(_message_content(message))
+ if not removed:
+ continue
+ view_messages[index] = _copy_message_with_content(message, sanitized_content)
+ removed_total += removed
+ return view_messages, removed_total
+
+
+def _part_with_text(part: Any, text: str) -> Any:
+ if isinstance(part, str):
+ return text
+ if isinstance(part, dict):
+ return {**part, "text": text}
+ return part
+
+
+def _content_to_query_text(content: Any) -> str:
+ if isinstance(content, str):
+ return content
+ if isinstance(content, list):
+ texts: list[str] = []
+ for part in content:
+ text = _text_from_content_part(part)
+ if text:
+ texts.append(text)
+ return "\n".join(texts)
+ if content is None:
+ return ""
+ return str(content)
+
+
+def _text_from_content_part(part: Any) -> str | None:
+ if isinstance(part, str):
+ return part
+ if isinstance(part, dict) and isinstance(part.get("text"), str):
+ return part["text"]
+ return None
+
+
+def _copy_message_with_content(message: Any, content: Any) -> Any:
+ if isinstance(message, dict):
+ updated = dict(message)
+ updated["content"] = content
+ return updated
+ model_copy = getattr(message, "model_copy", None)
+ if callable(model_copy):
+ return model_copy(update={"content": content})
+ updated = copy.copy(message)
+ updated.content = content
+ return updated
diff --git a/jiuwenswarm/agents/harness/common/multimodal/image_history.py b/jiuwenswarm/agents/harness/common/multimodal/image_history.py
new file mode 100644
index 0000000000..07e9f8a1ff
--- /dev/null
+++ b/jiuwenswarm/agents/harness/common/multimodal/image_history.py
@@ -0,0 +1,582 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.
+
+"""Injection, budgeting and eviction of image content in conversation history.
+
+发送侧写入历史的最高层:把引用行物化成 ``image_url`` 块、按三预算「最老优先」降级、
+维护 ``attached`` / ``omitted`` 状态行,以及非视觉模型分支的视图过滤 mutator。依赖
+``image_content`` / ``image_processing`` / ``image_reference``。
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+from jiuwenswarm.agents.harness.common.multimodal.image_content import (
+ _content_to_query_text,
+ _message_content,
+ _part_with_text,
+ _text_from_content_part,
+ filter_image_content_from_view,
+ is_image_content_block,
+ is_user_authored_message,
+)
+from jiuwenswarm.agents.harness.common.multimodal.image_processing import (
+ _data_uri_bytes,
+ _data_uri_visual_tokens,
+ _image_block_bytes,
+ _image_block_visual_tokens,
+ _image_data_uri_from_path,
+ _image_file_size_bytes,
+ _image_file_visual_tokens,
+)
+from jiuwenswarm.agents.harness.common.multimodal.image_reference import (
+ _IMAGE_ATTACHED_LINE_RE,
+ _IMAGE_REFERENCE_LINE_RE,
+ _READ_FILE_IMAGE_TEXT_RE,
+ _build_image_state_line,
+ _message_image_states,
+ _normalize_image_file,
+ build_image_reference_line,
+ current_multimodal_image_files,
+ normalize_image_path,
+ parse_image_references,
+)
+from jiuwenswarm.common.utils import logger
+
+_MULTIMODAL_IMAGE_WINDOW_MUTATOR_ATTR = "_jiuwenswarm_multimodal_image_window_mutator"
+
+
+def inject_image_content_from_references(
+ messages: list[Any],
+ *,
+ image_files: list[dict[str, Any]] | None = None,
+ max_total_bytes: int = 0,
+ max_visual_tokens: int = 0,
+ max_count: int = 0,
+) -> tuple[list[Any], int]:
+ """Materialize referenced images into the conversation history as ``image_url`` blocks.
+
+ 在 ``before_model_call`` 里、窗口构建(含压缩处理器)之前调用,因此:
+
+ - 本轮新上传的图片从**第一次** LLM 调用起就按视觉 token 计入窗口,
+ 压缩判定看到的是含图片的上下文,而不是下一轮才看到;
+ - 图像内容写入历史本身(就地修改传入的 message 对象),后续轮次直接复用
+ 这条消息里的 base64,不再重新读文件、不再重新缩小;
+ - 每条 ``[image #n] path=...`` 引用行只处理一次,处理结果记录为
+ ``[image #n attached]`` / ``[image #n omitted: ...]`` 状态行;状态行判定
+ 按消息作用域(同一条消息里的引用行与状态行配对),压缩摘要搬走消息后不会
+ 把老图重新加回;
+ - 预算按「最老优先」裁剪**本次请求**的全部图片(含 read_file 注入的图),
+ 被裁的图片改成文字说明并记入历史,之后不会再被自动加回;
+ - 计量口径是「实际发出去的图」:视觉 token 按缩小后的发送尺寸(最长边
+ ``_MAX_VISION_INLINE_IMAGE_DIMENSION``)估算,字节数默认取文件元数据,
+ 配置了总字节预算时改为预先编码后的精确发送字节;
+ - 引用序号撞车(adapter 重建后从 1 重新计数、或用户重新上传同一文件)时,
+ 就地改写引用行为新序号再注入,不再静默丢图;
+ - 历史中的原引用行与磁盘原文件都保留,需要更高清晰度时可让模型再次
+ ``read_file`` 原文件重新出图(读图护栏对 omitted 图片留出例外);
+ - 安全边界:只有**本次请求上传清单**(``current_multimodal_image_files()``,
+ adapter 在 invoke 内绑定)里的路径才会被读盘物化。引用行是模型可见的纯文本,
+ 用户可以手写任意服务器路径;若只校验 MIME 与文件存在性,就能把 file_guard /
+ 沙箱之外的本地图片内联进模型请求。清单为空时一律不物化任何新像素。
+ """
+
+ messages_list = list(messages)
+ # 上传清单与引用路径两侧都用 normalize_image_path 归一后比较,口径与
+ # is_provided_image_path 一致(大小写 / 相对段 / ~ 形态不同不影响判定)。
+ # 显式传入 image_files 时优先用它(rail 从 agent 实例读,跨请求→agent 任务边界),
+ # 否则回退 ContextVar(同调用栈场景)。
+ manifest = (
+ list(image_files)
+ if image_files is not None
+ else current_multimodal_image_files()
+ )
+ uploaded_paths = {
+ normalize_image_path(str(item.get("path") or ""))
+ for item in manifest
+ if str(item.get("path") or "").strip()
+ }
+ # 清单为空时本轮不物化任何新像素;但历史图片的预算重算仍要执行
+ # (N5:预算每轮重算、最老优先降级),因此不在入口整体提前返回。
+ refs_by_message: list[tuple[Any, list[dict[str, Any]]]] = []
+ states_by_message: dict[int, dict[int, str]] = {}
+ # 序号 → 引用/状态行所在消息,用于判定"这个序号是否已被别的消息占用":
+ # 本消息自己的引用不算撞号,别的消息里的同号引用/状态才算。
+ index_owners: dict[int, set[int]] = {}
+ for message in messages_list:
+ if not is_user_authored_message(message):
+ # 引用行只认用户消息:tool result / assistant 文本里的同格式行不物化像素,
+ # 避免被读到的文件内容把本地图片内联进模型请求(绕过 file_guard)。
+ continue
+ message_key = id(message)
+ text = _content_to_query_text(_message_content(message))
+ refs = parse_image_references(text) if text else []
+ refs_by_message.append((message, refs))
+ states_by_message[message_key] = _message_image_states(message)
+ for ref in refs:
+ index = int(ref["index"])
+ index_owners.setdefault(index, set()).add(message_key)
+ for index in states_by_message[message_key]:
+ index_owners.setdefault(index, set()).add(message_key)
+
+ used_indices: set[int] = set(index_owners)
+ next_index = (max(used_indices) + 1) if used_indices else 1
+
+ pending: list[tuple[Any, dict[str, Any]]] = []
+ seen_paths: set[str] = set()
+ renumbered = 0
+ for message, refs in refs_by_message:
+ message_key = id(message)
+ local_states = states_by_message[message_key]
+ for ref in refs:
+ index = int(ref["index"])
+ if index in local_states:
+ # 本消息已处理过这张图(附过像素或被预算卸载过),不再重复处理。
+ continue
+ image = _normalize_image_file(ref)
+ if not image:
+ logger.info(
+ "[inject_image_content] skip unusable image ref: index=%d path=%s mime=%s",
+ index,
+ ref.get("path"),
+ ref.get("mime_type"),
+ )
+ continue
+ path = image["path"]
+ path_key = normalize_image_path(path)
+ if path_key not in uploaded_paths:
+ # 安全门(N12 的延伸):引用行只是模型可见的纯文本,任何能写 user
+ # 消息的人都能伪造一行指向服务器任意可读图片的引用。只有本次上传
+ # 清单内的路径才允许读盘物化;清单为空时整轮都不物化新像素。
+ logger.warning(
+ "[inject_image_content] skip non-uploaded image ref: index=%d path=%s",
+ index,
+ path,
+ )
+ continue
+ if index_owners.get(index, set()) - {message_key}:
+ # 序号在别的消息里已被占用:adapter 重建后重新从 1 计数,或用户重新
+ # 上传同一张图。换新序号并改写引用行,否则会与历史状态行撞号丢图。
+ new_index = next_index
+ next_index += 1
+ if not _rewrite_reference_line_index(
+ message, index, str(ref.get("path") or ""), new_index
+ ):
+ logger.warning(
+ "[inject_image_content] renumber failed: index=%d path=%s",
+ index,
+ path,
+ )
+ continue
+ used_indices.add(new_index)
+ index_owners.setdefault(new_index, set()).add(message_key)
+ image["index"] = new_index
+ index = new_index
+ renumbered += 1
+ if path_key in seen_paths:
+ # 同一请求内同一路径被两条 user 消息重复引用(或同一消息重复写):
+ # 只为第一条物化像素。跳过项必须补一条状态行,否则下一轮它仍是
+ # 「未处理」状态,会再被注入一份 base64(像素块重复、预算白占)。
+ _append_state_marker(
+ message,
+ _build_image_state_line(index, "omitted", "duplicate"),
+ )
+ continue
+ seen_paths.add(path_key)
+ pending.append((message, image))
+
+ logger.info(
+ "[inject_image_content] refs_pending=%d renumbered=%d max_total_bytes=%d max_visual_tokens=%d max_count=%d",
+ len(pending),
+ renumbered,
+ max_total_bytes,
+ max_visual_tokens,
+ max_count,
+ )
+ has_budget = max_total_bytes > 0 or max_visual_tokens > 0 or max_count > 0
+ if not pending and not has_budget:
+ return messages_list, 0
+
+ # 先完成窗口计量,再读取像素组:默认预算(三项全 0 = 不限)只用文件元数据
+ # (字节数 + 头部尺寸折算发送尺寸)计量,不读像素组(需求「先完成窗口计量,
+ # 再读取像素组请求」)。配置了总字节预算时,缩小后的发送态字节数无法由元数据
+ # 推出,只能预先编码拿到精确值——这是该预算下的必要代价,编码结果随后直接复用,
+ # 不会重复编码。
+ # 预算每轮都跑:历史里的图片(含 read_file 注入的)同样受本次请求预算约束,
+ # 不是只有「本轮有新上传」才裁剪。
+ existing = _collect_image_slots(messages_list)
+ precomputed = _precompute_pending_data_uris(pending) if max_total_bytes > 0 else {}
+ pending_sizes: list[tuple[int, int, int]] = []
+ for _, image in pending:
+ index = image["index"]
+ data_uri = precomputed.get(index)
+ size_bytes = _data_uri_bytes(data_uri) if data_uri else _image_file_size_bytes(image)
+ if max_visual_tokens <= 0:
+ visual_tokens = 0
+ elif data_uri:
+ visual_tokens = _data_uri_visual_tokens(data_uri)
+ else:
+ visual_tokens = _image_file_visual_tokens(image)
+ pending_sizes.append((index, size_bytes, visual_tokens))
+ dropped = _apply_image_budget(
+ existing,
+ pending_sizes,
+ max_total_bytes=max_total_bytes,
+ max_visual_tokens=max_visual_tokens,
+ max_count=max_count,
+ )
+
+ attached = 0
+ for message, image in pending:
+ if image["index"] in dropped:
+ _append_state_marker(
+ message,
+ _build_image_state_line(image["index"], "omitted", "request budget"),
+ )
+ continue
+ data_uri = precomputed.get(image["index"]) or _image_data_uri_from_path(
+ image["path"], image["mime_type"]
+ )
+ if data_uri:
+ _append_image_part(message, image["index"], data_uri)
+ attached += 1
+ else:
+ _append_state_marker(
+ message,
+ _build_image_state_line(image["index"], "omitted", "unreadable"),
+ )
+
+ logger.info(
+ "[inject_image_content] attached=%d dropped=%d evicted=%d existing=%d",
+ attached,
+ len(dropped),
+ sum(1 for slot in existing if slot.get("evicted")),
+ len(existing),
+ )
+ return messages_list, attached
+
+
+def _precompute_pending_data_uris(
+ pending: list[tuple[Any, dict[str, Any]]],
+) -> dict[int, str]:
+ """字节预算下预先编码待注入图片,拿到缩小后的精确发送态字节数。
+
+ 只在配置了总字节预算时调用:默认(0 = 不限)不读像素,保持"先计量后读图"。
+ 编码结果按图片序号返回,注入阶段直接复用,一张图只编码一次。
+ """
+
+ data_uris: dict[int, str] = {}
+ for _, image in pending:
+ data_uri = _image_data_uri_from_path(image["path"], image["mime_type"])
+ if data_uri:
+ data_uris[image["index"]] = data_uri
+ return data_uris
+
+
+def remove_multimodal_image_filter_window_mutator(context: Any) -> bool:
+ """摘掉非视觉模型分支安装的视图过滤 mutator,返回是否真的摘掉。
+
+ 同一 agent 的 ContextEngine / ModelContext 跨请求复用:上一轮按非视觉模型
+ 安装的 mutator 若不撤销,会把本轮 enabled 分支刚注入历史的像素在视图层再
+ 剥掉,模型实际收不到图,只能退回视觉工具或重复 read_file。模型能力每次
+ 请求都可能随模型切换变化,mutator 生命周期必须跟随当前解析值,而不是首次
+ 安装时的值。
+ """
+
+ mutators = getattr(context, "_window_mutators", None)
+ if not isinstance(mutators, list):
+ return False
+ before = len(mutators)
+ mutators[:] = [
+ mutator
+ for mutator in mutators
+ if not bool(getattr(mutator, _MULTIMODAL_IMAGE_WINDOW_MUTATOR_ATTR, False))
+ ]
+ return len(mutators) != before
+
+
+def ensure_multimodal_image_filter_window_mutator(context: Any) -> bool:
+ mutators = getattr(context, "_window_mutators", None)
+ if not isinstance(mutators, list):
+ logger.info(
+ "[ensure_multimodal_image_filter_window_mutator] _window_mutators not a list: %r",
+ mutators,
+ )
+ return False
+
+ # 幂等:重装前先摘旧实例,避免重复追加;同时把「之前是 enabled、现在是
+ # disabled」的切换也收敛成恰好一个过滤 mutator。
+ remove_multimodal_image_filter_window_mutator(context)
+
+ async def multimodal_image_filter_window_mutator(_context: Any, window: Any) -> Any:
+ context_messages = list(getattr(window, "context_messages", []) or [])
+ view_messages, removed = filter_image_content_from_view(context_messages)
+ if not removed:
+ return window
+ model_copy = getattr(window, "model_copy", None)
+ if callable(model_copy):
+ return model_copy(update={"context_messages": view_messages})
+ return window
+
+ setattr(
+ multimodal_image_filter_window_mutator,
+ _MULTIMODAL_IMAGE_WINDOW_MUTATOR_ATTR,
+ True,
+ )
+ mutators.append(multimodal_image_filter_window_mutator)
+ return True
+
+
+def _rewrite_reference_line_index(message: Any, index: int, path: str, new_index: int) -> bool:
+ """把消息里的 ``[image #index] path=...`` 引用行改写成 ``#new_index``。
+
+ 序号撞车时使用:让历史里的引用行、状态行、实际注入序号三者保持一致,
+ 后续轮次才能按状态行判定"已处理",不会每轮重复注入。
+ """
+
+ parts = _message_parts(message)
+ changed = False
+ for part_index, part in enumerate(parts):
+ text = _text_from_content_part(part)
+ if not text:
+ continue
+ lines = text.splitlines()
+ rebuilt: list[str] = []
+ for line in lines:
+ match = _IMAGE_REFERENCE_LINE_RE.match(line.strip())
+ if match and int(match.group(1)) == index and match.group(2) == path:
+ record: dict[str, Any] = {
+ "path": path,
+ "filename": match.group(3),
+ "mime_type": match.group(4),
+ }
+ if match.group(5) is not None:
+ record["size_bytes"] = int(match.group(5))
+ rebuilt.append(build_image_reference_line(record, new_index))
+ changed = True
+ else:
+ rebuilt.append(line)
+ if rebuilt != lines:
+ parts[part_index] = _part_with_text(part, "\n".join(rebuilt))
+ if changed:
+ _set_message_content(message, parts)
+ return changed
+
+
+def _message_parts(message: Any) -> list[Any]:
+ content = _message_content(message)
+ if isinstance(content, list):
+ return list(content)
+ if content is None:
+ return []
+ return [{"type": "text", "text": str(content)}]
+
+
+def _set_message_content(message: Any, content: Any) -> None:
+ if isinstance(message, dict):
+ message["content"] = content
+ else:
+ message.content = content
+
+
+def _append_parts(message: Any, parts: list[Any]) -> None:
+ _set_message_content(message, _message_parts(message) + parts)
+
+
+def _append_state_marker(message: Any, line: str) -> None:
+ _append_parts(message, [{"type": "text", "text": line}])
+
+
+def _append_image_part(message: Any, index: int, data_uri: str) -> None:
+ _append_parts(
+ message,
+ [
+ {"type": "text", "text": _build_image_state_line(index, "attached")},
+ {"type": "image_url", "image_url": {"url": data_uri}},
+ ],
+ )
+
+
+def _collect_image_slots(messages: list[Any]) -> list[dict[str, Any]]:
+ """收集历史里活着的图片块及其配对状态行,供预算按「最老优先」卸载。
+
+ 每条 slot 记录:消息对象、图片块下标、配对的 ``[image #n attached]`` 状态行下标
+ (read_file 注入的图没有状态行 → None,靠前面的 ``Image loaded from read_file:``
+ 文本行识别来源)、字节数。视觉 token 延迟到需要时才算(解码 base64 有成本)。
+ """
+
+ slots: list[dict[str, Any]] = []
+ for message in messages:
+ content = _message_content(message)
+ if not isinstance(content, list):
+ continue
+ pending_state: tuple[int, int] | None = None
+ last_source_path: str | None = None
+ for part_index, part in enumerate(content):
+ text = _text_from_content_part(part)
+ if text is not None:
+ # 逐行匹配:压缩等链路会把多个文本 part 合并成一个多行 part,
+ # 状态行不一定独占整段文本。与 ``_message_image_states`` 的
+ # splitlines 口径保持一致,否则已 attached 的图会被当成
+ # read_file 来源图(没有状态行)而误配对 / 误改名。
+ for line in text.splitlines():
+ stripped = line.strip()
+ match = _IMAGE_ATTACHED_LINE_RE.match(stripped)
+ if match:
+ # 最近一条状态行配对下一个 image block(保持既有语义)。
+ pending_state = (int(match.group(1)), part_index)
+ source_match = _READ_FILE_IMAGE_TEXT_RE.match(stripped)
+ if source_match:
+ last_source_path = source_match.group(1).strip()
+ continue
+ if not is_image_content_block(part):
+ continue
+ index = pending_state[0] if pending_state else None
+ state_part_index = pending_state[1] if pending_state else None
+ pending_state = None
+ slots.append(
+ {
+ "message": message,
+ "part_index": part_index,
+ "index": index,
+ "state_part_index": state_part_index,
+ "source_path": None if index is not None else last_source_path,
+ "bytes": _image_block_bytes(part),
+ "tokens": 0,
+ }
+ )
+ last_source_path = None
+ return slots
+
+
+def _slot_image_part(slot: dict[str, Any]) -> Any:
+ content = _message_content(slot["message"])
+ part_index = slot["part_index"]
+ if isinstance(content, list) and 0 <= part_index < len(content):
+ return content[part_index]
+ return None
+
+
+def _replace_attached_state_line(part: Any, index: int) -> Any:
+ """把文本 part 里的 ``[image #n attached]`` 行改写成 ``omitted``,保留其它行。
+
+ 状态行不一定独占整个文本 part:压缩链路会把多条文本合并成一个多行 part。
+ 整段替换会连用户正文一起吞掉,所以按行定位、只改命中的那一行。
+ """
+
+ replacement = _build_image_state_line(index, "omitted", "request budget")
+ text = _text_from_content_part(part)
+ if text is None:
+ return {"type": "text", "text": replacement}
+ rebuilt: list[str] = []
+ replaced = False
+ for line in text.splitlines():
+ match = _IMAGE_ATTACHED_LINE_RE.match(line.strip())
+ if match and int(match.group(1)) == index:
+ rebuilt.append(replacement)
+ replaced = True
+ else:
+ rebuilt.append(line)
+ if not replaced:
+ # 状态行与图片块配对了却定位不到行(极端历史脏数据):至少把事实追加到末尾。
+ rebuilt.append(replacement)
+ return _part_with_text(part, "\n".join(rebuilt))
+
+
+def _apply_image_evictions(slots: list[dict[str, Any]]) -> None:
+ """把预算裁掉的图片块改写成文字说明并记入历史(同一条消息只重建一次)。"""
+
+ buckets: dict[int, dict[str, Any]] = {}
+ for slot in slots:
+ bucket = buckets.setdefault(
+ id(slot["message"]),
+ {"message": slot["message"], "image_parts": {}, "state_parts": {}},
+ )
+ bucket["image_parts"][slot["part_index"]] = slot["index"]
+ if slot["index"] is not None and slot["state_part_index"] is not None:
+ bucket["state_parts"][slot["state_part_index"]] = slot["index"]
+
+ for bucket in buckets.values():
+ message = bucket["message"]
+ parts = _message_parts(message)
+ rebuilt: list[Any] = []
+ for part_index, part in enumerate(parts):
+ if part_index in bucket["image_parts"]:
+ index = bucket["image_parts"][part_index]
+ if index is None or index not in bucket["state_parts"].values():
+ # read_file 注入的图没有状态行,就地换成省略说明;前面的路径说明行
+ # 保留,模型可以再用 read_file 按原文件重新出图。
+ rebuilt.append({"type": "text", "text": "[image omitted: request budget]"})
+ # 有配对状态行时由状态行承载事实(改写为 omitted),像素块直接摘除,
+ # 避免同一张图同时留下 attached / omitted 两条互相矛盾的状态。
+ continue
+ if part_index in bucket["state_parts"]:
+ index = bucket["state_parts"][part_index]
+ rebuilt.append(_replace_attached_state_line(part, index))
+ continue
+ rebuilt.append(part)
+ _set_message_content(message, rebuilt)
+
+
+def _apply_image_budget(
+ slots: list[dict[str, Any]],
+ pending_sizes: list[tuple[int, int, int]],
+ *,
+ max_total_bytes: int,
+ max_visual_tokens: int,
+ max_count: int,
+) -> set[int]:
+ """按「最老的图片先卸载」裁剪单次请求的图片预算,返回不注入的新图序号。
+
+ ``slots`` 是历史里活着的图片块(含 read_file 注入的图);``pending_sizes``
+ 元素为 ``(index, size_bytes, visual_tokens)``:默认取文件元数据(大小 + 头部尺寸
+ 折算发送尺寸),配置了总字节预算时由调用方预编码后传入精确发送字节与视觉 token。
+
+ 预算对「本次请求会看到的全部图片」生效,不区分本轮是否有新上传:否则没有
+ 新图的轮次会把历史图片无限期留在窗口里。
+ """
+
+ dropped: set[int] = set()
+ if max_total_bytes <= 0 and max_visual_tokens <= 0 and max_count <= 0:
+ return dropped
+
+ if max_visual_tokens > 0:
+ for slot in slots:
+ slot["tokens"] = _image_block_visual_tokens(_slot_image_part(slot))
+
+ total_bytes = sum(slot["bytes"] for slot in slots)
+ total_tokens = sum(slot["tokens"] for slot in slots)
+ total_count = len(slots) + len(pending_sizes)
+ pending_bytes = sum(size for _, size, _tokens in pending_sizes)
+ pending_tokens = sum(tokens for _, _size, tokens in pending_sizes)
+
+ def over_budget() -> bool:
+ if max_count > 0 and total_count > max_count:
+ return True
+ if max_total_bytes > 0 and (total_bytes + pending_bytes) > max_total_bytes:
+ return True
+ return max_visual_tokens > 0 and (total_tokens + pending_tokens) > max_visual_tokens
+
+ evicted: list[dict[str, Any]] = []
+ slot_index = 0
+ while over_budget() and slot_index < len(slots):
+ slot = slots[slot_index]
+ slot_index += 1
+ evicted.append(slot)
+ slot["evicted"] = True
+ total_bytes -= slot["bytes"]
+ total_tokens -= slot["tokens"]
+ total_count -= 1
+
+ if evicted:
+ _apply_image_evictions(evicted)
+
+ for index, size, tokens in pending_sizes:
+ if not over_budget():
+ break
+ dropped.add(index)
+ pending_bytes -= size
+ pending_tokens -= tokens
+ total_count -= 1
+
+ return dropped
diff --git a/jiuwenswarm/agents/harness/common/multimodal/image_processing.py b/jiuwenswarm/agents/harness/common/multimodal/image_processing.py
new file mode 100644
index 0000000000..58b057b26a
--- /dev/null
+++ b/jiuwenswarm/agents/harness/common/multimodal/image_processing.py
@@ -0,0 +1,390 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.
+
+"""Image shrinking and visual-token measurement.
+
+本包唯一持有 PIL 的模块:图片缩小/编码、data URI 构造、视觉 token 估算与字节计量。
+不 import 包内其它模块(``base64`` / ``hashlib`` / ``PIL`` 之外只依赖日志)。
+"""
+
+from __future__ import annotations
+
+import base64
+import hashlib
+import io
+from collections import OrderedDict
+from pathlib import Path
+from typing import Any
+
+from PIL import Image
+
+from jiuwenswarm.common.utils import logger
+
+_VISION_INLINE_IMAGE_MIME_TYPES = frozenset({
+ "image/png",
+ "image/jpeg",
+ "image/webp",
+ "image/gif",
+})
+_MAX_VISION_INLINE_IMAGE_BYTES = 10 * 1024 * 1024
+_MAX_VISION_INLINE_IMAGE_DIMENSION = 1536
+
+_IMAGE_FORMAT_TO_MIME = {
+ "PNG": "image/png",
+ "JPEG": "image/jpeg",
+ "WEBP": "image/webp",
+ "GIF": "image/gif",
+}
+
+_IMAGE_EXT_TO_MIME = {
+ ".png": "image/png",
+ ".jpg": "image/jpeg",
+ ".jpeg": "image/jpeg",
+ ".webp": "image/webp",
+ ".gif": "image/gif",
+}
+
+_JPEG_QUALITY_STEPS = (95, 85, 70, 50, 30, 10)
+_WEBP_QUALITY_STEPS = (95, 85, 70, 50, 30, 10)
+_SHRINK_SCALE_STEP = 0.85
+_MIN_SHRINK_DIMENSION = 32
+
+
+# 源文件大小硬上限:先 stat 再读,超过直接拒绝。否则超大文件会在
+# ``read_bytes()`` 里整体进内存,一次请求就可能把进程打爆。
+_MAX_IMAGE_SOURCE_BYTES = 64 * 1024 * 1024
+
+
+# 历史图片块的视觉 token 缓存。预算每轮都会遍历历史图,而 data URI 可达数 MB,
+# 不能拿大字符串当 ``lru_cache`` 的 key(常驻内存 + 哈希成本都在大字符串上);
+# 这里按 payload 的 sha256 摘要缓存,命中直接返回、不再 base64 解码 + PIL 开图。
+# 上限 64 条并做 LRU 淘汰:单请求窗口外的旧图自然淘汰,不会无界增长。
+_IMAGE_VISUAL_TOKEN_CACHE_LIMIT = 64
+_IMAGE_VISUAL_TOKEN_CACHE: OrderedDict[bytes, int] = OrderedDict()
+
+
+# 视觉 token 计量(OpenAI GPT-4o 风格 tile 算法):图片在上下文窗口中的占用
+# 按分辨率估算,而不是按 base64 字符长度或文件字节数。
+# 这是**预算裁剪用的近似值**,不参与正确性判定:不同厂商的视觉 token 定价不同
+# (Gemini / Claude / Qwen-VL 与 GPT-4o 有差异),统一按同一系数估算只会让
+# `multimodal_image_token_budget` 的裁剪点偏松或偏紧,不会改变发送内容与状态行语义。
+_VISION_TILE_SIZE = 512
+_VISION_BASE_TOKENS = 85
+_VISION_TOKENS_PER_TILE = 170
+
+
+def _image_block_bytes(part: Any) -> int:
+ if not isinstance(part, dict):
+ return 0
+ image_url = part.get("image_url")
+ url = image_url.get("url") if isinstance(image_url, dict) else image_url
+ if not isinstance(url, str) or not url:
+ return 0
+ if not url.startswith("data:"):
+ # 远程 URL 的图片字节数无法从字符串推断;不能把 URL 文本当 base64 估算
+ # (会得到 len(url)*3//4 这种无意义的小数字,破坏字节预算)。
+ return 0
+ payload = url.partition("base64,")[2]
+ return len(payload) * 3 // 4
+
+
+def _data_uri_bytes(data_uri: str) -> int:
+ payload = data_uri.partition("base64,")[2] if data_uri.startswith("data:") else data_uri
+ return len(payload) * 3 // 4
+
+
+def _image_file_size_bytes(image: dict[str, Any]) -> int:
+ """图片元数据字节数:优先用记录里的 ``size_bytes``,否则 stat 磁盘文件。
+
+ 只读元数据、不读像素,供预算计量在读取像素组之前使用。
+ """
+
+ size = image.get("size_bytes")
+ if isinstance(size, int) and size > 0:
+ return size
+ try:
+ return Path(str(image.get("path") or "")).stat().st_size
+ except OSError:
+ return 0
+
+
+def estimate_image_visual_tokens(width: int, height: int) -> int:
+ """按分辨率估算图片的视觉 token 占用(OpenAI GPT-4o 风格 tile 算法)。
+
+ 图片在上下文窗口里的占用应按视觉 token 计,而不是 base64 字符长度或
+ 文件字节数:一张高分辨率图即便字节很小,其视觉 token 也很大。
+
+ 入参必须是**实际发送尺寸**:发送前的缩小链路会把最长边压到
+ ``_MAX_VISION_INLINE_IMAGE_DIMENSION``,按原图尺寸计价会高估数倍。
+ """
+
+ if width <= 0 or height <= 0:
+ return 0
+ tiles_x = (width + _VISION_TILE_SIZE - 1) // _VISION_TILE_SIZE
+ tiles_y = (height + _VISION_TILE_SIZE - 1) // _VISION_TILE_SIZE
+ return _VISION_BASE_TOKENS + _VISION_TOKENS_PER_TILE * tiles_x * tiles_y
+
+
+def _clamp_sent_dimensions(width: int, height: int) -> tuple[int, int]:
+ """把原图尺寸折算成发送前的缩小尺寸(最长边不超过内联上限,等比缩放)。
+
+ 与 :func:`_image_data_uri_from_path` / agent-core ``shrink_image_bytes`` 使用
+ 同一个上限:预算计量按「实际发出去的像素」算,否则原图 4000×3000 会被
+ 缩到 1536×1152,而计量仍按原尺寸多算约 5 倍。
+ """
+
+ longest = max(width, height)
+ if longest <= _MAX_VISION_INLINE_IMAGE_DIMENSION:
+ return width, height
+ scale = _MAX_VISION_INLINE_IMAGE_DIMENSION / longest
+ return max(1, round(width * scale)), max(1, round(height * scale))
+
+
+def _read_image_dimensions(path: str) -> tuple[int, int]:
+ """轻量读取图片像素尺寸:只读头部元数据,不解码像素组。
+
+ 返回 ``(width, height)``,读取失败返回 ``(0, 0)``。
+ """
+
+ try:
+ with Image.open(path) as image:
+ return image.size
+ except Exception:
+ return (0, 0)
+
+
+def _image_file_visual_tokens(image: dict[str, Any]) -> int:
+ """图片的视觉 token 估算(按发送态尺寸):优先记录宽高,否则读文件头部。"""
+
+ width = image.get("width")
+ height = image.get("height")
+ if not (isinstance(width, int) and isinstance(height, int) and width > 0 and height > 0):
+ width, height = _read_image_dimensions(str(image.get("path") or ""))
+ return estimate_image_visual_tokens(*_clamp_sent_dimensions(width, height))
+
+
+def _image_block_visual_tokens(part: Any) -> int:
+ """已注入历史里的 ``image_url`` 块的视觉 token:从 data URI 头部读尺寸。
+
+ 每轮预算都会遍历全部历史图,而单张 data URI 可达数 MB:不缓存的话每轮都要
+ base64 解码 + PIL 开图。按 payload 的 sha256 摘要做有界 LRU 缓存,命中后直接
+ 返回 token 数,不再解码。失败结果不缓存,避免一次坏数据永久污染。
+ """
+
+ if not isinstance(part, dict):
+ return 0
+ image_url = part.get("image_url")
+ url = image_url.get("url") if isinstance(image_url, dict) else image_url
+ if not isinstance(url, str) or not url.startswith("data:"):
+ return 0
+ payload = url.partition("base64,")[2]
+ if not payload:
+ return 0
+ cache_key = hashlib.sha256(payload.encode("ascii", "replace")).digest()
+ cached = _IMAGE_VISUAL_TOKEN_CACHE.get(cache_key)
+ if cached is not None:
+ _IMAGE_VISUAL_TOKEN_CACHE.move_to_end(cache_key)
+ return cached
+ try:
+ with Image.open(io.BytesIO(base64.b64decode(payload))) as image:
+ width, height = image.size
+ except Exception:
+ return 0
+ tokens = estimate_image_visual_tokens(width, height)
+ _IMAGE_VISUAL_TOKEN_CACHE[cache_key] = tokens
+ while len(_IMAGE_VISUAL_TOKEN_CACHE) > _IMAGE_VISUAL_TOKEN_CACHE_LIMIT:
+ _IMAGE_VISUAL_TOKEN_CACHE.popitem(last=False)
+ return tokens
+
+
+def _data_uri_visual_tokens(data_uri: str) -> int:
+ """已缩小 data URI 的视觉 token:头部尺寸即发送尺寸,无需再折算。"""
+
+ return _image_block_visual_tokens({"image_url": {"url": data_uri}})
+
+
+def shrink_image(path: str, *, max_bytes: int, max_dimension: int) -> str:
+ """Return a base64 ``data:`` URI for ``path``, shrinking the image when needed.
+
+ agent-core 提供 ``image_shrink`` 时复用它(该模块由 core !3521 / 本地提交
+ b5275fe4b 引入;锁定 ``uv.lock`` 版本尚无该模块,自动回退本地实现),保证
+ 上传图与 read_file 图走同一套缩小链路:够小原样送出,超限才按质量从高到低
+ 逐档压缩,第一档放得下就停。只产出内存副本,源文件永不修改;读不到或无法
+ 解码时返回空串。
+
+ 这里的跨仓依赖是「同名同签名的可选模块」:core 尚未发布时导入失败,未来签名
+ 漂移时调用失败,两种情况都回退本地实现并记日志,不让单张图片的编码细节把整个
+ 请求打挂(N9:失败降级不阻断)。
+
+ 入口先做源文件大小预检(与 ``_shrink_image_local`` 同一阈值):无论最终走 core
+ 还是本地实现,超大文件都不得整体读进内存。
+ """
+
+ try:
+ if Path(path).stat().st_size > _MAX_IMAGE_SOURCE_BYTES:
+ logger.warning(
+ "image source too large, skip: path=%s limit=%d",
+ path,
+ _MAX_IMAGE_SOURCE_BYTES,
+ )
+ return ""
+ except OSError:
+ # stat 失败由具体实现走各自的失败降级(返回空串),这里只负责大小门禁。
+ pass
+ try:
+ from openjiuwen.harness.tools.multimodal.image_shrink import (
+ shrink_image_to_data_uri,
+ )
+ except (ImportError, AttributeError) as exc:
+ # 锁定版本(uv.lock 的 rev 尚无该模块)走这里:回退是常态,不是异常。
+ logger.debug(
+ "agent-core image_shrink unavailable, fall back to local shrink: %s", exc
+ )
+ return _shrink_image_local(
+ path, max_bytes=max_bytes, max_dimension=max_dimension
+ )
+ try:
+ return shrink_image_to_data_uri(
+ path,
+ max_bytes=max_bytes,
+ max_dimension=max_dimension,
+ )
+ except TypeError as exc:
+ # 未来 core 改了同名函数签名时不得让请求失败:回退本地实现。
+ logger.warning(
+ "agent-core image_shrink signature mismatch, fall back to local shrink: %s",
+ exc,
+ )
+ return _shrink_image_local(
+ path, max_bytes=max_bytes, max_dimension=max_dimension
+ )
+
+
+def _shrink_image_local(path: str, *, max_bytes: int, max_dimension: int) -> str:
+ """读取并缩小本地图片;先 stat 做大小预检,超大源文件直接拒绝。"""
+
+ file_path = Path(path)
+ if not file_path.is_file():
+ return ""
+ try:
+ if file_path.stat().st_size > _MAX_IMAGE_SOURCE_BYTES:
+ logger.warning(
+ "image source too large, skip: path=%s limit=%d",
+ file_path,
+ _MAX_IMAGE_SOURCE_BYTES,
+ )
+ return ""
+ except OSError:
+ return ""
+ try:
+ data = file_path.read_bytes()
+ except OSError:
+ return ""
+ if not data:
+ return ""
+
+ try:
+ with Image.open(file_path) as image:
+ image.load()
+ mime_type = _IMAGE_FORMAT_TO_MIME.get(image.format or "") or _IMAGE_EXT_TO_MIME.get(
+ file_path.suffix.lower(), ""
+ )
+ if not mime_type:
+ return ""
+
+ width, height = image.size
+ if len(data) <= max_bytes and max(width, height) <= max_dimension:
+ return _build_data_uri(data, mime_type)
+
+ encoded_bytes = _shrink_image_to_bytes(image, mime_type, max_bytes, max_dimension)
+ if encoded_bytes:
+ return _build_data_uri(encoded_bytes, mime_type)
+ except Exception:
+ logger.debug(
+ "image pre-encode failed: path=%s", file_path, exc_info=True
+ )
+ return ""
+
+
+def _build_data_uri(data: bytes, mime_type: str) -> str:
+ encoded = base64.b64encode(data).decode("ascii")
+ return f"data:{mime_type};base64,{encoded}"
+
+
+def _shrink_image_to_bytes(
+ image: Any,
+ mime_type: str,
+ max_bytes: int,
+ max_dimension: int,
+) -> bytes | None:
+ current = _resize_to_max_dimension(_prepare_for_resize(image), max_dimension)
+ encoded = _encode_within_bytes(current, mime_type, max_bytes)
+ if encoded is not None:
+ return encoded
+
+ while max(current.size) > _MIN_SHRINK_DIMENSION:
+ next_dimension = int(max(current.size) * _SHRINK_SCALE_STEP)
+ current = _resize_to_max_dimension(current, next_dimension)
+ encoded = _encode_within_bytes(current, mime_type, max_bytes)
+ if encoded is not None:
+ return encoded
+ return None
+
+
+def _prepare_for_resize(image: Any) -> Any:
+ if image.mode in ("RGB", "RGBA", "L"):
+ return image
+ if image.mode in ("LA", "PA") or (image.mode == "P" and "transparency" in image.info):
+ return image.convert("RGBA")
+ return image.convert("RGB")
+
+
+def _resize_to_max_dimension(image: Any, max_dimension: int) -> Any:
+ width, height = image.size
+ longest = max(width, height)
+ if longest <= max_dimension:
+ return image
+ ratio = max_dimension / longest
+ size = (max(1, round(width * ratio)), max(1, round(height * ratio)))
+ return image.resize(size, Image.Resampling.LANCZOS)
+
+
+def _encode_within_bytes(image: Any, mime_type: str, max_bytes: int) -> bytes | None:
+ if mime_type == "image/png":
+ encoded = _save_image(image, image_format="PNG", optimize=True)
+ return encoded if len(encoded) <= max_bytes else None
+ if mime_type == "image/jpeg":
+ rgb = image.convert("RGB")
+ for quality in _JPEG_QUALITY_STEPS:
+ encoded = _save_image(rgb, image_format="JPEG", quality=quality, optimize=True)
+ if len(encoded) <= max_bytes:
+ return encoded
+ return None
+ if mime_type == "image/webp":
+ for quality in _WEBP_QUALITY_STEPS:
+ encoded = _save_image(image, image_format="WEBP", quality=quality)
+ if len(encoded) <= max_bytes:
+ return encoded
+ return None
+ if mime_type == "image/gif":
+ encoded = _save_image(image.convert("RGB"), image_format="GIF", optimize=True)
+ return encoded if len(encoded) <= max_bytes else None
+ return None
+
+
+def _save_image(image: Any, *, image_format: str, **kwargs: Any) -> bytes:
+ buf = io.BytesIO()
+ image.save(buf, format=image_format, **kwargs)
+ return buf.getvalue()
+
+
+def _image_data_uri_from_path(path_text: str, mime_type: str) -> str:
+ path = Path(path_text.strip())
+ if not path.is_file():
+ return ""
+ if mime_type not in _VISION_INLINE_IMAGE_MIME_TYPES:
+ return ""
+ return shrink_image(
+ str(path),
+ max_bytes=_MAX_VISION_INLINE_IMAGE_BYTES,
+ max_dimension=_MAX_VISION_INLINE_IMAGE_DIMENSION,
+ )
diff --git a/jiuwenswarm/agents/harness/common/multimodal/image_reference.py b/jiuwenswarm/agents/harness/common/multimodal/image_reference.py
new file mode 100644
index 0000000000..25ab04c1ff
--- /dev/null
+++ b/jiuwenswarm/agents/harness/common/multimodal/image_reference.py
@@ -0,0 +1,382 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.
+
+"""Image reference lines, upload-file normalization and history state lines.
+
+引用行是模型可见的历史契约(``[image #n] path=... filename=... mime=...``),状态行是
+「给过/没给」的事实来源(``[image #n attached|omitted]``)。本模块还负责上传清单
+ContextVar 与路径归一。依赖 ``image_content`` / ``image_processing``;不 import ``history``。
+"""
+
+from __future__ import annotations
+
+import mimetypes
+import os
+import re
+from contextvars import ContextVar
+from pathlib import Path
+from typing import Any
+
+from jiuwenswarm.agents.harness.common.multimodal.image_content import (
+ _content_to_query_text,
+ _message_content,
+ is_user_authored_message,
+)
+from jiuwenswarm.agents.harness.common.multimodal.image_processing import (
+ _VISION_INLINE_IMAGE_MIME_TYPES,
+)
+
+_CURRENT_MULTIMODAL_IMAGE_FILES: ContextVar[tuple[dict[str, Any], ...]] = ContextVar(
+ "jiuwenswarm_current_multimodal_image_files",
+ default=(),
+)
+
+
+# 引用行是模型可见的历史契约。path / filename 用「到下一个 key 为止」的写法解析,
+# 允许文件名含空格(Windows 截图名、含空格的下载目录);旧格式(无空格)同样命中。
+# 值本身含字面量 `` filename=`` / `` mime=`` 的极端路径无法区分,属可接受边界。
+_IMAGE_REFERENCE_LINE_RE = re.compile(
+ r"^\[image #(\d+)\]\s+"
+ r"path=(.+?)\s+"
+ r"filename=(.+?)\s+"
+ r"mime=(\S+)"
+ r"(?:\s+size=(\d+))?\s*$"
+)
+
+
+def build_image_reference_line(image_file: dict[str, Any], index: int) -> str:
+ """Format an image-file record as a plain-text reference line."""
+
+ segments = [
+ "[image #{}] path={} filename={} mime={}".format(
+ index,
+ image_file.get("path", ""),
+ image_file.get("filename", ""),
+ image_file.get("mime_type", ""),
+ )
+ ]
+ size_bytes = image_file.get("size_bytes")
+ if size_bytes is not None:
+ segments.append("size={}".format(size_bytes))
+ return " ".join(segments)
+
+
+def parse_image_references(text: str) -> list[dict[str, Any]]:
+ """Parse image reference lines out of free-form text."""
+
+ refs: list[dict[str, Any]] = []
+ for line in text.splitlines():
+ match = _IMAGE_REFERENCE_LINE_RE.match(line.strip())
+ if not match:
+ continue
+ ref: dict[str, Any] = {
+ "index": int(match.group(1)),
+ "path": match.group(2),
+ "filename": match.group(3),
+ "mime_type": match.group(4),
+ }
+ size_bytes = match.group(5)
+ if size_bytes is not None:
+ ref["size_bytes"] = int(size_bytes)
+ refs.append(ref)
+ return refs
+
+
+def extract_multimodal_image_files(params: Any) -> list[dict[str, Any]]:
+ """Return normalized image-file records from a request payload."""
+
+ if not isinstance(params, dict):
+ return []
+
+ candidates: list[Any] = []
+ raw_media_items = params.get("media_items")
+ if isinstance(raw_media_items, list):
+ candidates.extend(raw_media_items)
+
+ files = params.get("files")
+ if isinstance(files, list):
+ # relay 通道下发的 files 固定是 list(web 才走 dict 信封);list 形态必须
+ # 直接收进候选,否则原生图片块注入在 relay 主链路(单 agent 与 team)永不激活。
+ candidates.extend(files)
+ elif isinstance(files, dict):
+ uploaded_images = files.get("uploaded_images")
+ if isinstance(uploaded_images, list):
+ candidates.extend(uploaded_images)
+
+ normalized: list[dict[str, Any]] = []
+ seen_paths: set[str] = set()
+ for item in candidates:
+ image = _normalize_image_file(item)
+ if not image:
+ continue
+ path = image["path"]
+ if path in seen_paths:
+ continue
+ seen_paths.add(path)
+ normalized.append(image)
+ return normalized
+
+
+def set_current_multimodal_image_files(image_files: list[dict[str, Any]]) -> Any:
+ """Bind request image files to the current Core model-call task."""
+
+ return _CURRENT_MULTIMODAL_IMAGE_FILES.set(tuple(_normalize_image_files(image_files)))
+
+
+def reset_current_multimodal_image_files(token: Any) -> None:
+ _CURRENT_MULTIMODAL_IMAGE_FILES.reset(token)
+
+
+def current_multimodal_image_files() -> list[dict[str, Any]]:
+ return list(_CURRENT_MULTIMODAL_IMAGE_FILES.get())
+
+
+# 上传清单的 agent 实例镜像。ContextVar 不跨「请求协程 → agent 任务」边界:适配器在
+# 请求入口 set,而 send_input 只是把消息入队,before_model_call 在 agent 自己的任务里
+# 跑,读不到请求协程 set 的值(N12 安全门因此把合法上传判成 non-uploaded)。所以把
+# 清单同时镜像到 DeepAgent 实例上——适配器(self._instance)与 rail(self._deep_agent)
+# 拿到的是同一对象,注入时从实例读即可跨边界。同调用栈仍优先走 ContextVar,跨任务走实例。
+_CURRENT_MULTIMODAL_IMAGE_FILES_AGENT_ATTR = "_jiuwenswarm_current_image_files"
+
+
+def store_current_multimodal_image_files_on_agent(
+ agent: Any, image_files: list[dict[str, Any]]
+) -> None:
+ """把本次请求上传清单镜像到 agent 实例(覆盖写,空列表即清除上一请求残留)。"""
+
+ if agent is None:
+ return
+ try:
+ setattr(
+ agent,
+ _CURRENT_MULTIMODAL_IMAGE_FILES_AGENT_ATTR,
+ tuple(_normalize_image_files(image_files)),
+ )
+ except Exception: # pragma: no cover - 冻结对象 / 属性拦截时降级为只靠 ContextVar
+ pass
+
+
+def current_multimodal_image_files_from_agent(agent: Any) -> list[dict[str, Any]] | None:
+ """读 agent 实例上的上传清单镜像;未存储 → None(调用方回退 ContextVar)。"""
+
+ value = getattr(agent, _CURRENT_MULTIMODAL_IMAGE_FILES_AGENT_ATTR, None)
+ if value is None:
+ return None
+ return list(value)
+
+
+def normalize_image_path(path: str) -> str:
+ """把图片路径归一为可比较的 key(大小写 / 相对段 / ``~`` 展开)。"""
+
+ return os.path.normcase(os.path.realpath(os.path.expanduser(str(path or "").strip())))
+
+
+def is_provided_image_path(path: str, provided_paths: Any) -> bool:
+ """判断 path 是否落在「本次请求已随消息提供像素」的路径集合内。
+
+ ``provided_paths`` 是路径字符串列表。调用方(rail)从 ctx.extra 传入,
+ 不依赖 ContextVar——工具执行可能跨任务 / 线程,请求级 ContextVar 会丢。
+ """
+
+ candidate = str(path or "").strip()
+ if not candidate or not provided_paths:
+ return False
+ target = normalize_image_path(candidate)
+ return any(
+ normalize_image_path(str(item)) == target
+ for item in provided_paths
+ if str(item or "").strip()
+ )
+
+
+def collect_image_references_from_messages(messages: list[Any]) -> list[dict[str, Any]]:
+ """Collect image reference lines from user-authored message text.
+
+ 只扫 user 角色:引用行是上传入口写入用户消息的历史契约,工具输出 / 抓取正文
+ 里的同名文本不得被当成本次请求的图片引用。
+ """
+
+ refs: list[dict[str, Any]] = []
+ for message in messages:
+ if not is_user_authored_message(message):
+ continue
+ text = _content_to_query_text(_message_content(message))
+ if text:
+ refs.extend(parse_image_references(text))
+ return refs
+
+
+def _normalize_image_files(image_files: list[dict[str, Any]] | tuple[Any, ...]) -> list[dict[str, Any]]:
+ normalized: list[dict[str, Any]] = []
+ seen_paths: set[str] = set()
+ for item in image_files:
+ image = _normalize_image_file(item)
+ if not image:
+ continue
+ path = image["path"]
+ if path in seen_paths:
+ continue
+ seen_paths.add(path)
+ normalized.append(image)
+ return normalized
+
+
+def _normalize_image_file(item: Any) -> dict[str, Any] | None:
+ if not isinstance(item, dict):
+ return None
+ item_type = item.get("type")
+ if item_type is not None and item_type != "image":
+ return None
+
+ path = str(item.get("path") or "").strip()
+ if not path:
+ return None
+
+ mime_type = str(item.get("mime_type") or item.get("mimeType") or "").strip().lower()
+ if not mime_type:
+ mime_type = mimetypes.guess_type(path)[0] or ""
+ if mime_type not in _VISION_INLINE_IMAGE_MIME_TYPES:
+ return None
+
+ filename = str(item.get("filename") or Path(path).name).strip() or Path(path).name
+ image: dict[str, Any] = {
+ "type": "image",
+ "filename": filename,
+ "path": path,
+ "mime_type": mime_type,
+ }
+ index = item.get("index")
+ if isinstance(index, int):
+ # 引用序号:注入/预算卸载按 [image #index] 写状态行,必须透传。
+ image["index"] = index
+ size_bytes = item.get("size_bytes")
+ if isinstance(size_bytes, int):
+ image["size_bytes"] = size_bytes
+ return image
+
+
+# 状态行:``[image #n attached]`` / ``[image #n omitted]`` / ``[image #n omitted: reason]``。
+# 捕获 reason 供 read_file 重出图护栏区分「预算卸载 / 不可读」与「重复引用」:
+# 后者该 path 已在别的消息随像素提供,不能再放行一次重读。
+_IMAGE_STATE_LINE_RE = re.compile(
+ r"^\[image #(\d+) (attached|omitted)(?:: ([^\]]*))?\]$"
+)
+_IMAGE_ATTACHED_LINE_RE = re.compile(r"^\[image #(\d+) attached\]$")
+# read_file 注入的像素块前面有一行路径说明(agent-core 生成),预算卸载时保留它,
+# 模型据此知道"这张图可以用 read_file 重新出图"。
+_READ_FILE_IMAGE_TEXT_RE = re.compile(r"^Image loaded from read_file:\s*(.+)$")
+
+
+def _build_image_state_line(index: int, state: str, reason: str = "") -> str:
+ if state == "attached":
+ return f"[image #{index} attached]"
+ if reason:
+ return f"[image #{index} omitted: {reason}]"
+ return f"[image #{index} omitted]"
+
+
+def _iter_text_values(content: Any):
+ if isinstance(content, str):
+ yield content
+ return
+ if not isinstance(content, list):
+ return
+ for part in content:
+ if isinstance(part, str):
+ yield part
+ elif isinstance(part, dict) and isinstance(part.get("text"), str):
+ yield part["text"]
+
+
+def _message_image_states(message: Any) -> dict[int, str]:
+ """单条消息内的图片状态行。
+
+ 引用行与它的状态行写在同一批内容里(注入时就地追加到引用行所在消息),
+ 因此状态判定按消息作用域:压缩把老消息搬进摘要后,新消息里的同号引用
+ 不会被老状态行误判成"已处理",也不会把老图重新加回。
+ """
+
+ states: dict[int, str] = {}
+ for text in _iter_text_values(_message_content(message)):
+ for line in text.splitlines():
+ match = _IMAGE_STATE_LINE_RE.match(line.strip())
+ if match:
+ states[int(match.group(1))] = match.group(2)
+ return states
+
+
+def _message_omitted_image_reasons(message: Any) -> dict[int, str]:
+ """单条消息内 ``omitted`` 状态行的序号 → 原因(归一小写,无原因为空串)。"""
+
+ reasons: dict[int, str] = {}
+ for text in _iter_text_values(_message_content(message)):
+ for line in text.splitlines():
+ match = _IMAGE_STATE_LINE_RE.match(line.strip())
+ if not match or match.group(2) != "omitted":
+ continue
+ reasons[int(match.group(1))] = str(match.group(3) or "").strip().lower()
+ return reasons
+
+
+def collect_omitted_image_paths(messages: list[Any]) -> list[str]:
+ """收集历史里被卸载(``omitted``)的图片路径。
+
+ 被预算卸载 / 读取失败的图片像素已经不在上下文里,允许模型按原文件重新出图
+ (``read_file`` 重读原图 → 重新缩小编码 → 新的像素块),而不是靠放大已压糊的
+ 像素。同一路径只返回一次。
+
+ ``omitted: duplicate`` 例外:它只是「同一请求里同 path 已在另一条消息随像素
+ 提供过」的去重标记,像素并没有缺失;若也算进来,read_file 会对同一路径再放行
+ 一次重出图,白占预算。
+ """
+
+ paths: list[str] = []
+ for message in messages:
+ if not is_user_authored_message(message):
+ continue
+ text = _content_to_query_text(_message_content(message))
+ if not text:
+ continue
+ refs = {
+ int(ref["index"]): str(ref.get("path") or "")
+ for ref in parse_image_references(text)
+ }
+ if not refs:
+ continue
+ for index, reason in _message_omitted_image_reasons(message).items():
+ if reason == "duplicate":
+ continue
+ path = refs.get(index)
+ if path and path not in paths:
+ paths.append(path)
+ return paths
+
+
+def collect_provided_image_paths(messages: list[Any]) -> list[str]:
+ """收集历史里**像素已经随消息提供**的图片路径(``attached`` 状态)。
+
+ 与 :func:`collect_omitted_image_paths` 相反:只有注入成功、像素块确实写进
+ 历史的图片才算「已提供」。read_file 护栏必须按这个集合拒绝重复读——用上传
+ 清单会把"本轮上传了但注入失败 / 预算全卸载"的图片也算成已提供,模型既看不到
+ 像素又被禁止 read_file,图片彻底不可得。
+ """
+
+ paths: list[str] = []
+ for message in messages:
+ if not is_user_authored_message(message):
+ continue
+ text = _content_to_query_text(_message_content(message))
+ if not text:
+ continue
+ refs = {
+ int(ref["index"]): str(ref.get("path") or "")
+ for ref in parse_image_references(text)
+ }
+ if not refs:
+ continue
+ for index, state in _message_image_states(message).items():
+ if state != "attached":
+ continue
+ path = refs.get(index)
+ if path and path not in paths:
+ paths.append(path)
+ return paths
diff --git a/jiuwenswarm/agents/harness/common/prompt/user_prompt_builder.py b/jiuwenswarm/agents/harness/common/prompt/user_prompt_builder.py
deleted file mode 100644
index 146696e97c..0000000000
--- a/jiuwenswarm/agents/harness/common/prompt/user_prompt_builder.py
+++ /dev/null
@@ -1,364 +0,0 @@
-# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.
-
-"""User prompt helpers for multimodal image attachments."""
-
-from __future__ import annotations
-
-import base64
-import copy
-import json
-import mimetypes
-from contextvars import ContextVar
-from pathlib import Path
-from typing import Any
-
-IMAGE_CONTENT_OMITTED = (
- "[Image content omitted from chat-model context. Use the original image "
- "path or a vision tool when image analysis is required.]"
-)
-
-_IMAGE_CONTENT_TYPES = frozenset({"image", "image_url", "input_image"})
-_VISION_INLINE_IMAGE_MIME_TYPES = frozenset({
- "image/png",
- "image/jpeg",
- "image/webp",
- "image/gif",
-})
-_MAX_VISION_INLINE_IMAGE_BYTES = 10 * 1024 * 1024
-_MULTIMODAL_IMAGE_WINDOW_MUTATOR_ATTR = "_jiuwenswarm_multimodal_image_window_mutator"
-_CURRENT_MULTIMODAL_IMAGE_FILES: ContextVar[tuple[dict[str, Any], ...]] = ContextVar(
- "jiuwenswarm_current_multimodal_image_files",
- default=(),
-)
-
-
-def is_image_content_block(part: Any) -> bool:
- if not isinstance(part, dict):
- return False
- block_type = str(part.get("type") or "").strip().lower()
- if block_type in _IMAGE_CONTENT_TYPES:
- return True
- return "image_url" in part or "image" in part
-
-
-def extract_multimodal_image_files(params: Any) -> list[dict[str, Any]]:
- """Return normalized image-file records from a request payload."""
-
- if not isinstance(params, dict):
- return []
-
- candidates: list[Any] = []
- raw_media_items = params.get("media_items")
- if isinstance(raw_media_items, list):
- candidates.extend(raw_media_items)
-
- files = params.get("files")
- if isinstance(files, dict):
- uploaded_images = files.get("uploaded_images")
- if isinstance(uploaded_images, list):
- candidates.extend(uploaded_images)
-
- normalized: list[dict[str, Any]] = []
- seen_paths: set[str] = set()
- for item in candidates:
- image = _normalize_image_file(item)
- if not image:
- continue
- path = image["path"]
- if path in seen_paths:
- continue
- seen_paths.add(path)
- normalized.append(image)
- return normalized
-
-
-def set_current_multimodal_image_files(image_files: list[dict[str, Any]]) -> Any:
- """Bind request image files to the current Core model-call task."""
-
- return _CURRENT_MULTIMODAL_IMAGE_FILES.set(tuple(_normalize_image_files(image_files)))
-
-
-def reset_current_multimodal_image_files(token: Any) -> None:
- _CURRENT_MULTIMODAL_IMAGE_FILES.reset(token)
-
-
-def current_multimodal_image_files() -> list[dict[str, Any]]:
- return list(_CURRENT_MULTIMODAL_IMAGE_FILES.get())
-
-
-def prepare_multimodal_image_messages(
- messages: list[Any],
- image_files: list[dict[str, Any]] | None = None,
-) -> tuple[list[Any], int]:
- images = _normalize_image_files(image_files or current_multimodal_image_files())
- if not images:
- return messages, 0
-
- target_index = _latest_user_message_index(messages)
- if target_index < 0:
- return messages, 0
-
- message = messages[target_index]
- content = (
- message.get("content")
- if isinstance(message, dict)
- else getattr(message, "content", None)
- )
- updated_content, injected = _append_image_files_to_content(content, images)
- if not injected:
- return messages, 0
-
- updated_messages = list(messages)
- updated_messages[target_index] = _copy_message_with_content(message, updated_content)
- return updated_messages, injected
-
-
-def strip_image_content_blocks(content: Any) -> tuple[Any, int]:
- if not isinstance(content, list):
- return content, 0
-
- kept_parts: list[Any] = []
- removed = 0
- for part in content:
- if is_image_content_block(part):
- removed += 1
- continue
- kept_parts.append(part)
-
- if not removed:
- return content, 0
- if not kept_parts:
- return IMAGE_CONTENT_OMITTED, removed
-
- text_parts: list[str] = []
- for part in kept_parts:
- text = _text_from_content_part(part)
- if text is None:
- return kept_parts, removed
- if text:
- text_parts.append(text)
- return "\n".join(text_parts).strip() or IMAGE_CONTENT_OMITTED, removed
-
-
-def strip_image_content_from_model_context(context: Any) -> int:
- removed_total = 0
- for message in context.get_messages():
- sanitized_content, removed = strip_image_content_blocks(
- getattr(message, "content", None)
- )
- if not removed:
- continue
- message.content = sanitized_content
- removed_total += removed
- return removed_total
-
-
-def prepare_multimodal_image_context_window(
- window: Any,
- image_files: list[dict[str, Any]] | None = None,
-) -> tuple[Any, int]:
- context_messages = list(getattr(window, "context_messages", []) or [])
- updated_messages, injected = prepare_multimodal_image_messages(
- context_messages,
- image_files,
- )
- if not injected:
- return window, 0
-
- model_copy = getattr(window, "model_copy", None)
- if callable(model_copy):
- return model_copy(update={"context_messages": updated_messages}), injected
- window.context_messages = updated_messages
- return window, injected
-
-
-def ensure_multimodal_image_window_mutator(
- context: Any,
- image_files: list[dict[str, Any]] | None = None,
-) -> bool:
- mutators = getattr(context, "_window_mutators", None)
- if not isinstance(mutators, list):
- return False
-
- images = _normalize_image_files(
- image_files if image_files is not None else current_multimodal_image_files()
- )
- mutators[:] = [
- mutator
- for mutator in mutators
- if not bool(getattr(mutator, _MULTIMODAL_IMAGE_WINDOW_MUTATOR_ATTR, False))
- ]
- if not images:
- return False
-
- async def multimodal_image_window_mutator(_context: Any, window: Any) -> Any:
- return prepare_multimodal_image_context_window(window, images)[0]
-
- setattr(
- multimodal_image_window_mutator,
- _MULTIMODAL_IMAGE_WINDOW_MUTATOR_ATTR,
- True,
- )
- mutators.append(multimodal_image_window_mutator)
- return True
-
-
-def _normalize_image_files(image_files: list[dict[str, Any]] | tuple[Any, ...]) -> list[dict[str, Any]]:
- normalized: list[dict[str, Any]] = []
- seen_paths: set[str] = set()
- for item in image_files:
- image = _normalize_image_file(item)
- if not image:
- continue
- path = image["path"]
- if path in seen_paths:
- continue
- seen_paths.add(path)
- normalized.append(image)
- return normalized
-
-
-def _normalize_image_file(item: Any) -> dict[str, Any] | None:
- if not isinstance(item, dict):
- return None
- item_type = item.get("type")
- if item_type is not None and item_type != "image":
- return None
-
- path = str(item.get("path") or "").strip()
- if not path:
- return None
-
- mime_type = str(item.get("mime_type") or item.get("mimeType") or "").strip().lower()
- if not mime_type:
- mime_type = mimetypes.guess_type(path)[0] or ""
- if mime_type not in _VISION_INLINE_IMAGE_MIME_TYPES:
- return None
-
- filename = str(item.get("filename") or Path(path).name).strip() or Path(path).name
- image: dict[str, Any] = {
- "type": "image",
- "filename": filename,
- "path": path,
- "mime_type": mime_type,
- }
- size_bytes = item.get("size_bytes")
- if isinstance(size_bytes, int):
- image["size_bytes"] = size_bytes
- return image
-
-
-def _latest_user_message_index(messages: list[Any]) -> int:
- for index in range(len(messages) - 1, -1, -1):
- if _is_user_message(messages[index]):
- return index
- return -1
-
-
-def _is_user_message(message: Any) -> bool:
- role = (
- message.get("role")
- if isinstance(message, dict)
- else getattr(message, "role", None)
- )
- if str(role or "").lower() == "user":
- return True
- return message.__class__.__name__ == "UserMessage"
-
-
-def _append_image_files_to_content(
- content: Any,
- image_files: list[dict[str, Any]],
-) -> tuple[Any, int]:
- image_url_parts: list[Any] = []
- injected_files: list[dict[str, Any]] = []
- for image_file in image_files:
- data_uri = _image_data_uri_from_path(image_file["path"], image_file["mime_type"])
- if _append_image_url_part(image_url_parts, data_uri):
- injected_files.append(image_file)
- if not injected_files:
- return content, 0
-
- parts: list[Any] = [{"type": "text", "text": _build_query_file_text(content, injected_files)}]
- parts.extend(image_url_parts)
- return parts, len(injected_files)
-
-
-def _build_query_file_text(content: Any, image_files: list[dict[str, Any]]) -> str:
- """Serialize the user query and attached images as a ``{query, file}`` JSON text block.
-
- The multimodal image content parts are appended separately; this text block gives the
- model both the original query and the image file paths in a single serialized payload.
- """
-
- payload = {
- "query": _content_to_query_text(content),
- "file": [
- {
- "filename": image_file["filename"],
- "path": image_file["path"],
- "mime_type": image_file["mime_type"],
- }
- for image_file in image_files
- ],
- }
- return json.dumps(payload, ensure_ascii=False)
-
-
-def _content_to_query_text(content: Any) -> str:
- if isinstance(content, str):
- return content
- if isinstance(content, list):
- texts: list[str] = []
- for part in content:
- text = _text_from_content_part(part)
- if text:
- texts.append(text)
- return "\n".join(texts)
- if content is None:
- return ""
- return str(content)
-
-
-def _text_from_content_part(part: Any) -> str | None:
- if isinstance(part, str):
- return part
- if isinstance(part, dict) and isinstance(part.get("text"), str):
- return part["text"]
- return None
-
-
-def _image_data_uri_from_path(path_text: str, mime_type: str) -> str:
- path = Path(path_text.strip())
- if not path.is_file():
- return ""
- if mime_type not in _VISION_INLINE_IMAGE_MIME_TYPES:
- return ""
- try:
- data = path.read_bytes()
- except OSError:
- return ""
- if not data or len(data) > _MAX_VISION_INLINE_IMAGE_BYTES:
- return ""
- encoded = base64.b64encode(data).decode("ascii")
- return f"data:{mime_type};base64,{encoded}"
-
-
-def _append_image_url_part(parts: list[Any], data_uri: str) -> bool:
- if not data_uri.startswith("data:image/"):
- return False
- parts.append({"type": "image_url", "image_url": {"url": data_uri}})
- return True
-
-
-def _copy_message_with_content(message: Any, content: Any) -> Any:
- if isinstance(message, dict):
- updated = dict(message)
- updated["content"] = content
- return updated
- model_copy = getattr(message, "model_copy", None)
- if callable(model_copy):
- return model_copy(update={"content": content})
- updated = copy.copy(message)
- updated.content = content
- return updated
diff --git a/jiuwenswarm/agents/harness/common/rails/concurrent_safe_rails.py b/jiuwenswarm/agents/harness/common/rails/concurrent_safe_rails.py
index 9223772352..267117df22 100644
--- a/jiuwenswarm/agents/harness/common/rails/concurrent_safe_rails.py
+++ b/jiuwenswarm/agents/harness/common/rails/concurrent_safe_rails.py
@@ -44,6 +44,9 @@ from openjiuwen.harness.tools.todo import (
)
from openjiuwen.harness.workspace.workspace import WorkspaceNode
+from jiuwenswarm.agents.harness.common.read_file_image_support import (
+ build_read_file_image_kwargs,
+)
from jiuwenswarm.agents.harness.common.tools.todo_resume import is_persistent_todo
logger = logging.getLogger(__name__)
@@ -62,17 +65,24 @@ class ConcurrentSafeSysOperationRail(SysOperationRail):
lang = getattr(agent.system_prompt_builder, "language", None) or "cn"
agent_id = getattr(getattr(agent, "card", None), "id", None)
workspace_path = str(self.workspace.root_path) if self.workspace else None
- enable_read_image_multimodal = self._enable_read_image_multimodal
- if enable_read_image_multimodal is None:
- deep_config = getattr(agent, "deep_config", None)
- enable_read_image_multimodal = bool(
- getattr(deep_config, "enable_read_image_multimodal", True)
- )
+
+ def resolve_enable_read_image_multimodal() -> bool:
+ # ReadFileTool 在每次 read_file 调用时回调 resolver,跟随模型热切换;
+ # rail 构造时的 deep_config 值只是初始态,不是最终能力结论。
+ value = self._enable_read_image_multimodal
+ if value is None:
+ deep_config = getattr(agent, "deep_config", None)
+ value = getattr(deep_config, "enable_read_image_multimodal", False)
+ return bool(value)
+
read_tool = ReadFileTool(
self.sys_operation,
lang,
agent_id,
- enable_image_multimodal=enable_read_image_multimodal,
+ **build_read_file_image_kwargs(
+ resolve_enable_read_image_multimodal,
+ enable_image_multimodal=resolve_enable_read_image_multimodal(),
+ ),
)
write_tool = WriteFileTool(self.sys_operation, lang, agent_id, workspace_path=workspace_path)
edit_tool = EditFileTool(self.sys_operation, lang, agent_id, workspace_path=workspace_path)
diff --git a/jiuwenswarm/agents/harness/common/rails/model_routing/capability.py b/jiuwenswarm/agents/harness/common/rails/model_routing/capability.py
index 9679a8f0bf..f6999576d3 100644
--- a/jiuwenswarm/agents/harness/common/rails/model_routing/capability.py
+++ b/jiuwenswarm/agents/harness/common/rails/model_routing/capability.py
@@ -76,7 +76,15 @@ def _build_cap_from_entry(
model_obj: Optional[Any] = None
if model_builder is not None and mcc:
try:
- model_obj = model_builder(mcc, mco)
+ # 能力声明(modalities)必须透传:否则自动路由构造的 Model 丢看图能力,
+ # 视觉候选经路由后必被判"不支持"(S_22 铁律 46)。
+ modalities = entry.get("modalities") if isinstance(entry, dict) else None
+ try:
+ model_obj = model_builder(mcc, mco, modalities)
+ except TypeError:
+ # 2 参旧 builder(如 _default_model_builder)兜底:不传能力位,
+ # 按"未声明即不支持"处理。
+ model_obj = model_builder(mcc, mco)
except Exception as exc:
logger.debug("[ModelRouting] model_builder failed for %s: %s", name, exc)
model_obj = None
diff --git a/jiuwenswarm/agents/harness/common/rails/model_routing/image_capability_sync.py b/jiuwenswarm/agents/harness/common/rails/model_routing/image_capability_sync.py
new file mode 100644
index 0000000000..726a0f0756
--- /dev/null
+++ b/jiuwenswarm/agents/harness/common/rails/model_routing/image_capability_sync.py
@@ -0,0 +1,46 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""主对话换模后,把 ``deep_config.enable_read_image_multimodal`` 同步到新模型能力。
+
+根因:换模有两条路径——adapter 的 ``interface_deep._apply_model_to_react_agent``
+会同步看图能力位,但 ``ModelRoutingRail._emit_decision`` 的自动路由在 ``before_invoke``
+阶段直接 ``set_llm``,只换模型对象与名称,**不**同步能力位。入口模型声明支持图片、
+自动路由随后切到文本模型时,``enable_read_image_multimodal`` 仍沿用旧值 True,导致
+MultimodalImageRail 误注入像素 + 摘掉 VQA,最终文本模型收到不支持的输入。
+
+因此这里提供单一入口,所有换模路径(adapter / 自动路由)都必须经它收敛,避免再漏
+新入口。看图能力只由逐模型 ``modalities``(是否含 ``image``)决定(未声明即不支持),
+与 ``model_factory._resolve_enable_read_image_multimodal`` 同口径。
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+from jiuwenswarm.agents.harness.common.tools.model_capabilities import (
+ supports_native_image,
+)
+
+
+def sync_agent_image_capability(host: Any, model: Any) -> bool:
+ """把 ``host`` 的 ``deep_config.enable_read_image_multimodal`` 对齐到模型能力。
+
+ ``host`` 是挂着 ``_deep_config`` / ``deep_config`` 的 DeepAgent(或包装对象),
+ ``model`` 是 ``set_llm`` 之后生效的新模型。返回是否真正写入了能力位。
+
+ 自动路由构造的新模型若未显式携带 ``modalities``(``Model`` 构造默认无此字段),
+ ``supports_native_image`` 归 False → 按"不支持"处理,对文本目标(如 glm-5.3)是
+ 正确结论;视觉目标若走该路径,须由构造方显式带上 ``modalities``(含 ``image``)。
+ """
+
+ if host is None or model is None:
+ return False
+ deep_config = getattr(host, "_deep_config", None) or getattr(host, "deep_config", None)
+ if deep_config is None:
+ return False
+ enabled = supports_native_image(getattr(model, "modalities", None))
+ try:
+ deep_config.enable_read_image_multimodal = enabled
+ except Exception:
+ return False
+ return True
diff --git a/jiuwenswarm/agents/harness/common/rails/model_routing/model_routing_rail.py b/jiuwenswarm/agents/harness/common/rails/model_routing/model_routing_rail.py
index a132d58e4a..a18bdfbc97 100644
--- a/jiuwenswarm/agents/harness/common/rails/model_routing/model_routing_rail.py
+++ b/jiuwenswarm/agents/harness/common/rails/model_routing/model_routing_rail.py
@@ -11,6 +11,7 @@ from jiuwenswarm.common.utils import logger
from .capability import ModelCapability
from .classifier import CONTINUATION_CATEGORY, estimate_tokens, validate_score
from .compressor_sync import sync_agent_compressor_models
+from .image_capability_sync import sync_agent_image_capability
from .types import (
PriorModelCall, TaskAnalysis, RoutingDecision,
_agent_model_name, _extract_agent_info, _new_trace_id,
@@ -486,6 +487,12 @@ class ModelRoutingRail(DeepAgentRail):
setattr(ctx.agent, "model_name", mname)
except Exception as exc:
logger.debug("[ModelRouting] setattr model_name failed: %s", exc)
+ # 换模必须同步看图能力位:自动路由直接 set_llm,若漏掉会沿用旧模型的
+ # enable_read_image_multimodal(视觉入口模型切文本模型后仍 True →
+ # rail 误注入 + 摘掉 VQA)。与 adapter 的换模入口共用同一 helper。
+ capability_synced = sync_agent_image_capability(
+ ctx.agent, recommended_cap.model
+ )
# 主对话换模后,同步已缓存的上下文压缩器 / 会话记忆的 Model。它们
# 在 agent 创建时把 model_config 烤了进去,不跟着换就会继续拿旧 id
# 调上游 → 模型无效、压缩 noop、上下文膨胀。
@@ -496,9 +503,10 @@ class ModelRoutingRail(DeepAgentRail):
previous_model=previous_model,
)
logger.info(
- "[ModelRouting] applied set_llm -> %s compressor_synced=%s",
+ "[ModelRouting] applied set_llm -> %s compressor_synced=%s capability_synced=%s",
mname or "unknown",
synced,
+ capability_synced,
)
except Exception as exc:
logger.warning("[ModelRouting] set_llm failed: %s", exc)
diff --git a/jiuwenswarm/agents/harness/common/rails/multimodal_image_rail.py b/jiuwenswarm/agents/harness/common/rails/multimodal_image_rail.py
index ce18d68998..9d45e69534 100644
--- a/jiuwenswarm/agents/harness/common/rails/multimodal_image_rail.py
+++ b/jiuwenswarm/agents/harness/common/rails/multimodal_image_rail.py
@@ -7,28 +7,73 @@ from __future__ import annotations
from typing import Any
from openjiuwen.core.single_agent.rail.base import AgentCallbackContext
+from openjiuwen.harness.prompts import PromptSection
+from openjiuwen.harness.prompts.prompt_attachment_manager import PromptAttachmentKind
from openjiuwen.harness.rails.base import DeepAgentRail
-from jiuwenswarm.agents.harness.common.prompt.user_prompt_builder import (
- current_multimodal_image_files,
- ensure_multimodal_image_window_mutator,
- strip_image_content_from_model_context,
+from jiuwenswarm.agents.harness.common.multimodal import (
+ collect_image_references_from_messages,
+ collect_provided_image_paths,
+ count_image_content_blocks,
+ current_multimodal_image_files_from_agent,
+ ensure_multimodal_image_filter_window_mutator,
+ inject_image_content_from_references,
+ remove_multimodal_image_filter_window_mutator,
+)
+from jiuwenswarm.agents.harness.common.rails.multimodal_image_state import (
+ mark_native_images_sent,
+ mark_provided_image_paths,
)
from jiuwenswarm.common.utils import logger
+# 运行时附件里承载「本次模型调用到底带了几张图」的 section。系统提示里的策略段落在
+# 提示尾部、是否渲染不可观测,而运行时附件每次调用重建且模型必读,用它兜住负载事实。
+_IMAGE_STATE_ATTACHMENT_SECTION = "runtime.image_state"
+_IMAGE_STATE_ATTACHMENT_SOURCE = "jiuwenswarm.multimodal_image_rail"
+
class MultimodalImageRail(DeepAgentRail):
- """Prepare image attachments for native multimodal model input."""
+ """Prepare image attachments for native multimodal model input.
+
+ 发送侧唯一决策点:``before_model_call`` 在 agent-core 构建窗口(含压缩处理器)
+ **之前**把本轮引用行物化成历史里的 ``image_url`` 块,因此新上传的图片从第一次
+ LLM 调用起就按视觉 token 计入窗口,压缩判定看到的是含图上下文;模型不支持
+ 原生看图时历史不动,只在视图副本上剥离(由 agent-core 发送侧策略兜底)。
+
+ 时序约束(priority=82):agent-core 按 priority **降序**执行 rail 回调
+ (``framework.py`` ``sort(..., reverse=True)``;``AgentRail.priority`` 文档
+ "higher = first")。本 rail 是"本次到底发了几张像素"的唯一写入方,所有读该
+ 事实的消费者都必须在它之后跑:``ProgressiveToolRail`` 的 ``before_model_call``
+ 要按张数把视觉工具从 schema 摘掉、``JiuSwarmStreamEventRail`` 的工具钩子要按
+ 张数放行/拦截 read_file 与视觉工具。若本 rail 排在它们之后,首次 LLM 调用时
+ ``_jiuwenswarm_native_images_sent`` 仍是 ``before_invoke`` 归零后的 0,像素虽
+ 随后注入成功,视觉工具第一次也不会被摘除(模型会白调一轮 VQA/OCR)。82 的取值
+ 避开 deepresearch(81) 与 task_execution(85),确保严格中间位、无并列不确定顺序。
+ """
- priority = 75
+ priority = 82
- def __init__(self, enable_image_multimodal: bool | None = None) -> None:
+ def __init__(
+ self,
+ enable_image_multimodal: bool | None = None,
+ *,
+ max_total_bytes: int = 0,
+ max_visual_tokens: int = 0,
+ max_count: int = 0,
+ ) -> None:
super().__init__()
self._enable_image_multimodal = enable_image_multimodal
+ self._max_total_bytes = max(0, int(max_total_bytes or 0))
+ self._max_visual_tokens = max(0, int(max_visual_tokens or 0))
+ self._max_count = max(0, int(max_count or 0))
self._deep_agent: Any | None = None
+ self._system_prompt_builder: Any | None = None
+ self._attachment_manager: Any | None = None
def init(self, agent: Any) -> None:
self._deep_agent = agent
+ self._system_prompt_builder = getattr(agent, "system_prompt_builder", None)
+ self._attachment_manager = getattr(agent, "prompt_attachment_manager", None)
def _read_image_multimodal_enabled(self) -> bool:
if self._enable_image_multimodal is not None:
@@ -39,25 +84,314 @@ class MultimodalImageRail(DeepAgentRail):
)
return bool(getattr(deep_config, "enable_read_image_multimodal", False))
+ def _sync_image_policy_section(self, enabled: bool, images_sent: int) -> None:
+ """按「这次到底有没有把像素发出去」写策略段。
+
+ ``enabled=True`` 只说明模型**能**看图,不代表这次真发了。预算 / 引用行解析
+ 失败时视图里可能一张图都没有,此时再写"图片已作为图像内容直接提供、不要调用
+ VQA"就是与真实负载相反的信号——模型会既看不到图、又不敢用兜底工具,最后
+ 只能拿 OCR 文本作答。原生模式下没有像素时干脆不写本段,让视觉工具兜底。
+ """
+
+ builder = self._system_prompt_builder
+ if builder is None:
+ return
+ section_name = "multimodal_image_policy"
+ try:
+ builder.remove_section(section_name)
+ except Exception:
+ # 段不存在或 builder 未实现移除时不影响本轮注入,仅记录便于定位。
+ logger.warning("remove %s section failed", section_name, exc_info=True)
+ if enabled and images_sent <= 0:
+ return
+ native_cn = (
+ "本次请求可能包含用户上传的图片。当前模型支持原生图片理解,"
+ "图片已作为图像内容直接提供;请直接使用你的视觉能力查看图片,"
+ "不要调用 visual_question_answering 或 image_reading 工具。"
+ )
+ native_en = (
+ "This request may contain user-uploaded images. The current model supports "
+ "native image understanding and the images are provided as image content. "
+ "Use your vision capability directly; do not call visual_question_answering "
+ "or image_reading tools."
+ )
+ fallback_cn = (
+ "本次请求可能包含用户上传的图片。当前模型不支持原生图片理解;"
+ "如需理解图片内容,请调用 visual_question_answering 或 image_reading 工具。"
+ )
+ fallback_en = (
+ "This request may contain user-uploaded images. The current model does not "
+ "support native image understanding; to understand image content, call the "
+ "visual_question_answering or image_reading tool."
+ )
+ try:
+ builder.add_section(PromptSection(
+ name=section_name,
+ content={"cn": native_cn if enabled else fallback_cn,
+ "en": native_en if enabled else fallback_en},
+ priority=96,
+ ))
+ except Exception:
+ # 策略段是提示增强,写失败只降级(模型仍能靠运行时附件拿到负载事实),
+ # 不得让 before_model_call 整体失败——那会连像素注入一起丢。
+ logger.warning("add %s section failed", section_name, exc_info=True)
+
+ def _mark_images_sent(self, ctx: AgentCallbackContext, count: int) -> None:
+ """把「本次实际附带张数」写给工具护栏(stream rail / progressive rail)。"""
+
+ mark_native_images_sent(ctx, self._deep_agent, count)
+
+ def _snapshot_provided_image_paths(
+ self, ctx: AgentCallbackContext, messages: list[Any] | None
+ ) -> list[str]:
+ """把「本次实际随消息提供像素的图片路径」固化到 ``ctx.extra``(N7)。
+
+ 与上传清单不同:预算淘汰 / 引用行解析失败 / 读文件失败都可能让上传的图
+ 一张都没进消息,此时 read_file 必须放行(模型只能靠重读拿图)。因此快照
+ 按注入后的历史实际 ``attached`` 状态计算,``messages=None``(读历史失败 /
+ 无 context)与解析异常一律写空列表——"这次确实没有像素"是权威事实。
+ """
+
+ paths: list[str] = []
+ if messages is not None:
+ try:
+ paths = collect_provided_image_paths(list(messages))
+ except Exception: # pragma: no cover - 防御:解析异常按"没有像素"处理
+ logger.warning(
+ "[MultimodalImageRail] collect provided image paths failed",
+ exc_info=True,
+ )
+ paths = []
+ return mark_provided_image_paths(ctx, paths, agent=self._deep_agent)
+
+ def _attachment_language(self) -> str:
+ return str(getattr(self._system_prompt_builder, "language", "") or "cn")
+
+ def _build_image_state_attachment(self, *, enabled: bool, images_sent: int) -> str:
+ """构造「本次请求图片负载」附件正文。
+
+ 只陈述事实 + 与该事实一致的下一步:有像素就直说可以直接看、别再调视觉/OCR
+ 工具;没像素就直说这次没图、需要时用视觉工具。经验库里的 TIP 是按旧模型写的,
+ 模型只有看到这条事实才不用靠经验猜(B_01:切原生后首轮仍调 VQA,白花一轮)。
+ """
+
+ if self._attachment_language() == "en":
+ if enabled and images_sent > 0:
+ return (
+ "# Images In This Request\n\n"
+ f"- This request carries {images_sent} image(s), already provided as image "
+ "content: inspect the pixels directly to answer.\n"
+ "- Do not call visual_question_answering / image_reading / image_ocr to look "
+ "again, and do not read_file the same image; text, watermarks and IDs in the "
+ "image should be read from the pixels you received."
+ )
+ return (
+ "# Images In This Request\n\n"
+ "- This request carries 0 images as image content (no pixels were attached).\n"
+ "- To understand image content, call a vision tool such as "
+ "visual_question_answering; do not guess from context."
+ )
+ if enabled and images_sent > 0:
+ return (
+ "# 本次请求的图片\n\n"
+ f"- 本次请求附带图片:{images_sent} 张,已作为图像内容直接提供,"
+ "可直接查看像素作答。\n"
+ "- 不要调用 visual_question_answering / image_reading / image_ocr 再「看一遍」,"
+ "也不要 read_file 读取同一张图;图中文字、水印、编号以你收到的像素为准。"
+ )
+ return (
+ "# 本次请求的图片\n\n"
+ "- 本次请求附带图片:0 张(图片未作为像素附带)。\n"
+ "- 需要理解图片内容时请调用 visual_question_answering 等图片理解工具,"
+ "不要凭上下文猜测。"
+ )
+
+ async def _sync_image_state_attachment(
+ self,
+ ctx: AgentCallbackContext,
+ *,
+ enabled: bool,
+ images_sent: int,
+ has_image_references: bool,
+ ) -> None:
+ """把负载事实写进运行时附件(best-effort,写失败不阻断模型调用)。"""
+
+ manager = self._attachment_manager
+ if manager is None:
+ # DeepAgent 把同一个 PromptAttachmentManager 同时挂到内层 ReActAgent,两处
+ # 取到的实例一致;优先用 init 时捕获的那份(与 RuntimePromptRail 同源)。
+ manager = getattr(ctx.agent, "prompt_attachment_manager", None)
+ if manager is None:
+ return
+ try:
+ writer = manager.bind_context(ctx)
+ if not has_image_references and images_sent <= 0:
+ # 附件按会话存续:本轮没有图必须清掉上一轮的行,否则模型读到过期负载。
+ await writer.clear_section(_IMAGE_STATE_ATTACHMENT_SECTION)
+ return
+ await writer.add_section(
+ _IMAGE_STATE_ATTACHMENT_SECTION,
+ self._build_image_state_attachment(
+ enabled=enabled, images_sent=images_sent
+ ),
+ PromptAttachmentKind.RUNTIME,
+ _IMAGE_STATE_ATTACHMENT_SOURCE,
+ priority=96,
+ content_kind="text/markdown",
+ )
+ except ValueError as exc:
+ logger.warning(
+ "[MultimodalImageRail] skip image state attachment (no session id): %s", exc
+ )
+ except Exception as exc: # pragma: no cover - 旁路失败不阻断
+ logger.warning("[MultimodalImageRail] write image state attachment failed: %s", exc)
+
async def before_model_call(self, ctx: AgentCallbackContext) -> None:
+ enabled = self._read_image_multimodal_enabled()
+ logger.info(
+ "[MultimodalImageRail] before_model_call ctx_present=%s context_present=%s enabled=%s",
+ ctx is not None,
+ ctx is not None and ctx.context is not None,
+ enabled,
+ )
if ctx.context is None:
- return
- if self._read_image_multimodal_enabled():
- image_files = current_multimodal_image_files()
- installed = ensure_multimodal_image_window_mutator(
- ctx.context,
- image_files,
+ logger.info("[MultimodalImageRail] skip install: ctx.context is None")
+ self._mark_images_sent(ctx, 0)
+ # 无 context 时无法确认历史里的像素负载:按"这次没有像素"写快照,
+ # read_file 重读放行(模型手里没有图,不能既不给图又禁止取图)。
+ self._snapshot_provided_image_paths(ctx, None)
+ self._sync_image_policy_section(enabled, 0)
+ await self._sync_image_state_attachment(
+ ctx, enabled=enabled, images_sent=0, has_image_references=False
)
- if installed:
+ return
+ if enabled:
+ # 先摘掉上一轮按非视觉模型安装的视图过滤 mutator:同一 ContextEngine
+ # 跨模型热切换时不撤销,会把下面刚注入的像素在视图层再剥掉,模型实际
+ # 收不到图(表现为绕过原生能力去调 VQA / read_file)。
+ if remove_multimodal_image_filter_window_mutator(ctx.context):
logger.info(
- "Installed multimodal image context-window adapter for %d image attachment(s)",
- len(image_files),
+ "[MultimodalImageRail] removed stale image filter mutator "
+ "after switching to native image input"
+ )
+ # 在窗口构建之前就地写入历史:像素进入本次请求的 token 计量,压缩判定
+ # 才能看到本轮新上传的图片(需求「压缩之前按视觉 token 把图片计入窗口」)。
+ try:
+ messages = ctx.context.get_messages()
+ except Exception as exc: # pragma: no cover - defensive context guard
+ logger.warning("[MultimodalImageRail] read messages failed: %s", exc)
+ self._mark_images_sent(ctx, 0)
+ self._snapshot_provided_image_paths(ctx, None)
+ self._sync_image_policy_section(enabled, 0)
+ await self._sync_image_state_attachment(
+ ctx, enabled=enabled, images_sent=0, has_image_references=False
+ )
+ return
+ has_image_references = bool(
+ collect_image_references_from_messages(list(messages))
+ )
+ try:
+ messages, attached = inject_image_content_from_references(
+ list(messages),
+ image_files=current_multimodal_image_files_from_agent(
+ self._deep_agent
+ ),
+ max_total_bytes=self._max_total_bytes,
+ max_visual_tokens=self._max_visual_tokens,
+ max_count=self._max_count,
+ )
+ except Exception as exc: # pragma: no cover - 失败降级不阻断(N9)
+ logger.warning("[MultimodalImageRail] image injection failed: %s", exc)
+ self._mark_images_sent(ctx, 0)
+ # 注入中途失败:无法确认哪几张写进了历史,按"没有像素"处理(放行重读),
+ # 比误判"已提供"导致图既看不到又读不到安全。
+ self._snapshot_provided_image_paths(ctx, None)
+ self._sync_image_policy_section(enabled, 0)
+ await self._sync_image_state_attachment(
+ ctx,
+ enabled=enabled,
+ images_sent=0,
+ has_image_references=has_image_references,
)
+ return
+ # attached 只是本轮新增;策略段 / 视觉工具护栏要的是「视图里有没有像素」,
+ # 同一轮第二次 LLM 调用 attached=0 但历史里像素仍在,所以按实际块计数。
+ images_sent = count_image_content_blocks(messages)
+ self._mark_images_sent(ctx, images_sent)
+ # read_file 护栏按"实际物化成功"的路径集合判定重复读:上传了但没进消息的
+ # 图(预算淘汰 / 读取失败)不能被当成已提供,否则模型既看不到像素又被禁止
+ # 重读,图彻底不可得。
+ provided_paths = self._snapshot_provided_image_paths(ctx, messages)
+ self._sync_image_policy_section(enabled, images_sent)
+ await self._sync_image_state_attachment(
+ ctx,
+ enabled=enabled,
+ images_sent=images_sent,
+ has_image_references=has_image_references,
+ )
+ logger.info(
+ "[MultimodalImageRail] injected attached=%d visible=%d provided=%s "
+ "budget_bytes=%s budget_visual_tokens=%s budget_count=%s",
+ attached,
+ images_sent,
+ provided_paths,
+ self._max_total_bytes,
+ self._max_visual_tokens,
+ self._max_count,
+ )
return
- removed = strip_image_content_from_model_context(ctx.context)
- if removed:
+ self._mark_images_sent(ctx, 0)
+ # 非原生分支不向消息写像素(历史里的 image 块只在视图副本上剥离),快照写空。
+ self._snapshot_provided_image_paths(ctx, None)
+ self._sync_image_policy_section(enabled, 0)
+ has_image_references = False
+ try:
+ has_image_references = bool(
+ collect_image_references_from_messages(list(ctx.context.get_messages()))
+ )
+ except Exception as exc: # pragma: no cover - defensive context guard
+ logger.warning("[MultimodalImageRail] read messages failed: %s", exc)
+ await self._sync_image_state_attachment(
+ ctx,
+ enabled=enabled,
+ images_sent=0,
+ has_image_references=has_image_references,
+ )
+ installed = ensure_multimodal_image_filter_window_mutator(ctx.context)
+ logger.info("[MultimodalImageRail] filter mutator installed=%s", installed)
+ if installed:
logger.info(
- "Removed %d image content block(s) from chat-model context",
- removed,
+ "Installed multimodal image filter window mutator (view-level)"
)
+
+ async def after_model_call(self, ctx: AgentCallbackContext) -> None:
+ """窗口(含压缩)+ 发送侧策略之后、本轮工具调用之前,按最终窗口重算图片负载。
+
+ ``before_model_call`` 在 ``get_context_window`` 之前按**完整历史**算
+ ``images_sent`` / ``provided_paths``;若压缩随后把含图历史搬走(FullCompact),
+ 缓存仍宣称"模型已收到图"——模型既看不到像素、read_file 又被重复读护栏拒绝,
+ 图片彻底不可得。``ctx.inputs.messages`` 在 ``_railed_model_call`` 里已被更新为
+ 实际发出去的消息(压缩 + ``_apply_image_input_policy`` 之后),这里按它重算,
+ 让工具钩子(read_file 重复读 / 视觉工具拦截)看到最终窗口的事实。
+ """
+
+ if not self._read_image_multimodal_enabled():
+ # 非原生分支从未物化像素,before_model_call 已写 0 / 空,无需重算。
+ return
+ messages = getattr(getattr(ctx, "inputs", None), "messages", None)
+ if not isinstance(messages, list):
+ return
+ try:
+ images_sent = count_image_content_blocks(list(messages))
+ self._mark_images_sent(ctx, images_sent)
+ self._snapshot_provided_image_paths(ctx, messages)
+ except Exception as exc: # pragma: no cover - 防御:读不到最终窗口时保留较早快照
+ logger.warning(
+ "[MultimodalImageRail] recompute final-window image state failed: %s",
+ exc,
+ )
+ return
+ logger.info(
+ "[MultimodalImageRail] after_model_call final_window_images=%d", images_sent
+ )
diff --git a/jiuwenswarm/agents/harness/common/rails/multimodal_image_state.py b/jiuwenswarm/agents/harness/common/rails/multimodal_image_state.py
new file mode 100644
index 0000000000..c616732a96
--- /dev/null
+++ b/jiuwenswarm/agents/harness/common/rails/multimodal_image_state.py
@@ -0,0 +1,180 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""原生多模态「本次请求实际附带了几张图」的跨 rail 状态。
+
+为什么需要这个模块:能力位(``deep_config.enable_read_image_multimodal``)只说明
+模型**能**看图,不代表**这次**真的把像素发出去了。像素注入可能因预算 / 引用行解析 /
+读取失败而产出 0 张,此时模型看不到图,视觉工具(VQA / image_reading)是唯一兜底,
+按能力位一律拦截等于把唯一可用路径封死。所以:
+
+- 发送侧(``MultimodalImageRail.before_model_call``)注入后写入实际张数;
+- 消费侧(stream rail 的 ``before_tool_call`` 与 progressive rail 的
+ ``tools_search`` / ``invoke_tool``)只认这个张数,>0 才认为像素已到模型手里。
+
+写入两个位置,因为消费侧拿到的 ctx 不一样:
+- ``ctx.extra``:agent-core 的 tool ctx 与 ReAct ctx 共享同一个 extra dict,
+ 工具钩子里可直接读;
+- agent 属性:``invoke_tool`` 走 ProgressiveToolRail 的工具执行,没有 rail ctx,
+ 只能从 agent 实例上读。
+
+可见范围:两个位置都是"每轮模型调用刷新 + ``before_invoke`` 归零",因此不会跨请求
+残留(否则上一张图会把这一轮的 VQA 也拦掉)。
+
+同一模块也承载「本次实际物化成功的图片路径」请求级快照
+(``PROVIDED_IMAGE_PATHS_KEY`` / ``mark_provided_image_paths`` /
+``provided_image_paths``):read_file 护栏按它判定"这张图已随消息提供像素、别重复读"。
+快照只写 ``ctx.extra``(没有跨任务读的 agent 属性需求),且写入点是内层
+``before_model_call``(N7),空列表表示"这次确实没有像素"(放行重读)。
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+from jiuwenswarm.common.utils import logger
+
+# ctx.extra 键与 agent 属性同名,便于排障时一处 grep。
+NATIVE_IMAGES_SENT_KEY = "_jiuwenswarm_native_images_sent"
+
+# ctx.extra 键:本次模型调用**实际物化成功**的图片路径快照(list[str])。
+# 与"上传清单"(ContextVar ``_CURRENT_MULTIMODAL_IMAGE_FILES``)不同:上传了不代表
+# 像素进了消息(预算淘汰 / 引用行解析失败 / 读文件失败都可能 0 张),read_file 护栏
+# 只有看到这张图真的 attached 才能拒绝重复读。
+PROVIDED_IMAGE_PATHS_KEY = "_jiuwenswarm_provided_image_paths"
+
+_AGENT_OWNER_ATTRS = ("_deep_agent", "_config_agent", "_runtime_agent")
+
+
+def mark_provided_image_paths(
+ ctx: Any, paths: list[str] | None, agent: Any = None
+) -> list[str]:
+ """把「本次模型调用实际附带像素的图片路径」写入 ``ctx.extra`` 快照。
+
+ 空列表是**权威事实**(这次确实没有像素),不是"没写"——调用方据此放行 read_file
+ 重读;``None`` 只表示入参缺省(归一成空列表),不是"未知"。
+
+ 与 ``native_images_sent`` 同理由,镜像到 agent 属性:``invoke_tool`` /
+ ``tools_search`` 执行时没有 rail ctx,视觉工具护栏只能从 agent 实例上读。
+ """
+
+ normalized: list[str] = []
+ for item in paths or []:
+ text = str(item or "").strip()
+ if text and text not in normalized:
+ normalized.append(text)
+ extra = getattr(ctx, "extra", None)
+ if isinstance(extra, dict):
+ extra[PROVIDED_IMAGE_PATHS_KEY] = normalized
+ targets = [agent, getattr(ctx, "agent", None)]
+ for target in targets:
+ if target is None:
+ continue
+ try:
+ setattr(target, PROVIDED_IMAGE_PATHS_KEY, normalized)
+ except Exception: # pragma: no cover - 冻结对象 / 属性拦截时降级为只写 extra
+ logger.debug(
+ "[multimodal_image_state] set provided paths attr failed: %r", target
+ )
+ return normalized
+
+
+def provided_image_paths(ctx: Any = None, agent: Any = None) -> list[str] | None:
+ """读取已提供图片路径快照;``None`` 表示本次请求尚未写入(调用方自行回退)。
+
+ 空列表与 ``None`` 语义不同:空列表 = 已确认这次没有像素;``None`` = 未知。
+ 优先读 ``ctx.extra``,读不到再回退 agent 属性(invoke_tool 无 ctx 场景)。
+ """
+
+ extra = getattr(ctx, "extra", None) if ctx is not None else None
+ if isinstance(extra, dict):
+ cached = extra.get(PROVIDED_IMAGE_PATHS_KEY)
+ if isinstance(cached, list):
+ return [str(item).strip() for item in cached if str(item or "").strip()]
+ for target in (agent, getattr(ctx, "agent", None) if ctx is not None else None):
+ if target is None:
+ continue
+ value = _agent_list_attr(target, PROVIDED_IMAGE_PATHS_KEY)
+ if value is not None:
+ return value
+ return None
+
+
+def mark_native_images_sent(
+ ctx: Any = None,
+ agent: Any = None,
+ count: int = 0,
+) -> int:
+ """记录本次模型调用实际附带(视图中可见)的图片张数。
+
+ ``count`` 由发送侧按注入后的历史统计,含历史里已有的图片块,因此同一轮第二次
+ LLM 调用(``attached=0``)也能得到正确的"视图里有图"结论。
+ """
+
+ value = max(0, int(count or 0))
+ extra = getattr(ctx, "extra", None)
+ if isinstance(extra, dict):
+ extra[NATIVE_IMAGES_SENT_KEY] = value
+ targets = [agent, getattr(ctx, "agent", None)]
+ for target in targets:
+ if target is None:
+ continue
+ try:
+ setattr(target, NATIVE_IMAGES_SENT_KEY, value)
+ except Exception: # pragma: no cover - 冻结对象 / 属性拦截时降级为只写 extra
+ logger.debug(
+ "[multimodal_image_state] set agent attr failed: %r", target
+ )
+ return value
+
+
+def native_images_sent(ctx: Any = None, agent: Any = None) -> int:
+ """读取当前请求实际附带的图片张数;未知一律按 0(= 没发出去)。"""
+
+ extra = getattr(ctx, "extra", None)
+ if isinstance(extra, dict):
+ cached = extra.get(NATIVE_IMAGES_SENT_KEY)
+ if isinstance(cached, (int, float)):
+ return max(0, int(cached))
+ for target in (agent, getattr(ctx, "agent", None)):
+ value = _agent_attr(target)
+ if value is not None:
+ return value
+ return 0
+
+
+def _iter_agent_owners(agent: Any) -> list[Any]:
+ """把 agent 及其可能持有 deep_config 的包装对象铺平,供属性读取去重遍历。"""
+
+ if agent is None:
+ return []
+ owners: list[Any] = [agent]
+ for attr in _AGENT_OWNER_ATTRS:
+ owners.append(getattr(agent, attr, None))
+ owners.append(getattr(agent, "react_agent", None))
+ owners.append(getattr(agent, "_react_agent", None))
+ seen: set[int] = set()
+ deduped: list[Any] = []
+ for owner in owners:
+ if owner is None or id(owner) in seen:
+ continue
+ seen.add(id(owner))
+ deduped.append(owner)
+ return deduped
+
+
+def _agent_attr(agent: Any) -> int | None:
+ for owner in _iter_agent_owners(agent):
+ value = getattr(owner, NATIVE_IMAGES_SENT_KEY, None)
+ if isinstance(value, (int, float)):
+ return max(0, int(value))
+ return None
+
+
+def _agent_list_attr(agent: Any, key: str) -> list[str] | None:
+ """读 agent 树上的 list 属性(如 provided image paths),命中即返回归一列表。"""
+
+ for owner in _iter_agent_owners(agent):
+ value = getattr(owner, key, None)
+ if isinstance(value, list):
+ return [str(item).strip() for item in value if str(item or "").strip()]
+ return None
diff --git a/jiuwenswarm/agents/harness/common/rails/progressive_tool_rail.py b/jiuwenswarm/agents/harness/common/rails/progressive_tool_rail.py
index 18897fddb9..e4a5eca3f9 100644
--- a/jiuwenswarm/agents/harness/common/rails/progressive_tool_rail.py
+++ b/jiuwenswarm/agents/harness/common/rails/progressive_tool_rail.py
@@ -27,6 +27,15 @@ from openjiuwen.harness.prompts import PromptSection
from openjiuwen.harness.prompts.sections import SectionName
from openjiuwen.harness.rails.base import DeepAgentRail
+from jiuwenswarm.agents.harness.common.rails.multimodal_image_state import (
+ native_images_sent,
+ provided_image_paths,
+)
+from jiuwenswarm.agents.harness.common.rails.read_file_validation import (
+ build_native_image_tool_error,
+ is_vision_tool,
+ vision_tool_targets_all_provided,
+)
from jiuwenswarm.agents.harness.common.tools.invoke_tool_tool import (
InvokeToolInput,
InvokeToolTool,
@@ -177,6 +186,7 @@ class ProgressiveToolRail(DeepAgentRail):
self._deep_agent: Any = None
self._runtime_agent: Any = None
+ self._config_agent: Any = None
self._meta_tools: list[Any] | None = None
self._meta_active = False
self._owned_tool_ids: set[str] = set()
@@ -522,6 +532,10 @@ class ProgressiveToolRail(DeepAgentRail):
self.update_agent_card_id(resolved_card_id)
self._deep_agent = agent
self._runtime_agent = agent
+ # init() 注入的是持有 ``deep_config`` 的 DeepAgent;``_deep_agent`` 会在
+ # _resolve_runtime_agent 里被 ctx.agent(可能是包装对象)覆盖,这里单独
+ # 留一份稳定引用给模型能力判定使用。
+ self._config_agent = agent
self.invalidate_deferred_tool_cache()
def uninit(self, agent: Any) -> None:
@@ -529,6 +543,7 @@ class ProgressiveToolRail(DeepAgentRail):
self._remove_navigation_section(agent)
self._deep_agent = None
self._runtime_agent = None
+ self._config_agent = None
self._meta_tools = None
def invalidate_deferred_tool_cache(self) -> None:
@@ -566,6 +581,71 @@ class ProgressiveToolRail(DeepAgentRail):
self.invalidate_deferred_tool_cache()
return agent
+ def _native_image_input_enabled(self, agent: Any = None) -> bool:
+ """当前模型是否原生接收图片像素。
+
+ ``deep_config.enable_read_image_multimodal`` 由当前模型能力解析得出,
+ 是单一真源。该值开启时视觉理解工具(VQA/image_reading)只是降级替代,
+ 必须从模型可见工具中移除并在调用点拦截。
+
+ 注意:``ctx.agent`` 可能是包装对象,不持有 ``deep_config``;而
+ ``init()`` 注入的 agent 与 MultimodalImageRail 用的是同一个 DeepAgent,
+ 那里才有每次请求刷新的 ``deep_config``。``_deep_agent`` 会被
+ ``_resolve_runtime_agent`` 改写成运行期 agent,因此优先用
+ ``_config_agent`` 这个稳定引用。
+ """
+ candidates: list[Any] = [
+ getattr(self, "_config_agent", None),
+ self._deep_agent,
+ self._runtime_agent,
+ ]
+ if agent is not None:
+ candidates.append(agent)
+ for candidate in candidates:
+ if candidate is None:
+ continue
+ owners = (
+ candidate,
+ getattr(candidate, "react_agent", None),
+ getattr(candidate, "_react_agent", None),
+ )
+ for owner in owners:
+ if owner is None:
+ continue
+ deep_config = getattr(owner, "deep_config", None) or getattr(
+ owner, "_deep_config", None
+ )
+ if deep_config is None:
+ continue
+ value = getattr(deep_config, "enable_read_image_multimodal", None)
+ if isinstance(value, bool):
+ return value
+ return False
+
+ def _native_image_pixels_sent(self, agent: Any = None) -> bool:
+ """原生看图且本次请求真的发出了像素(披露面 / 拦截点的统一判据)。
+
+ 只看能力位会误拦"模型能看图、但这次图没发出去"的场景——那时视觉工具是
+ 唯一兜底,拦掉就只能拿 OCR 文本作答。张数由
+ ``MultimodalImageRail.before_model_call`` 每轮写入。
+ """
+
+ if not self._native_image_input_enabled(agent):
+ return False
+ # 张数写在 agent 实例上(invoke_tool 执行时没有 rail ctx)。ctx.agent 通常是
+ # 包装对象、不持有能力与张数,因此按能力解析同一套候选逐个读,取最大值。
+ candidates = [
+ agent,
+ getattr(self, "_config_agent", None),
+ getattr(self, "_deep_agent", None),
+ getattr(self, "_runtime_agent", None),
+ ]
+ return any(
+ native_images_sent(agent=candidate) > 0
+ for candidate in candidates
+ if candidate is not None
+ )
+
async def before_tool_call(self, ctx: AgentCallbackContext) -> None:
"""Enforce skill gates, then bind trusted direct-tool context."""
inputs = getattr(ctx, "inputs", None)
@@ -645,6 +725,15 @@ class ProgressiveToolRail(DeepAgentRail):
]
return self._meta_tools
+ def _meta_tool_names(self) -> set[str]:
+ """tools_search / invoke_tool 的名称集合。"""
+ names: set[str] = set()
+ for tool in self._meta_tool_instances():
+ name = str(getattr(getattr(tool, "card", None), "name", "") or "")
+ if name:
+ names.add(name)
+ return names
+
def _register_meta_tool_in_resource_mgr(self, tool: Any) -> None:
"""Register or replace session-scoped meta tool in resource_mgr."""
qualified_id = str(tool.card.id)
@@ -783,6 +872,10 @@ class ProgressiveToolRail(DeepAgentRail):
original_count = len(tools)
active_skill = self._current_active_skill()
+ # 绕过 lazy load 时 meta 工具已从 resource_mgr 卸载,但 inputs.tools 里
+ # 仍带着它们;模型调用会得到 "Ability not found: invoke_tool"。直接从
+ # schema 摘掉,避免一次必然失败的往返。
+ unavailable_meta = set() if lazy_load_active else self._meta_tool_names()
active_gated_names: list[str] = []
filtered_tools = []
for tool in tools:
@@ -793,6 +886,8 @@ class ProgressiveToolRail(DeepAgentRail):
declared, required_skill = _required_skill_requirement(live_card)
if name in disabled:
continue
+ if name in unavailable_meta:
+ continue
if declared:
if (
live_card is not None
@@ -851,6 +946,44 @@ class ProgressiveToolRail(DeepAgentRail):
by_name[name] = tool
return [by_name[name] for name in ordered_names if name in by_name]
+ def _visible_deferred_tool_infos(self, agent: Any = None) -> list[Any]:
+ """返回导航 / 搜索可见的按需工具。
+
+ 视觉理解工具**不再从披露面摘除**:原生看图只覆盖"已随消息提供像素"的本地图,
+ 远程图片 / 未提供的本地图仍需 VQA / OCR 兜底。一刀切摘除会让模型连远程图片
+ 都查不到工具。重复调用改由 ``invoke_tool`` / ``before_tool_call`` 按目标图片
+ 逐一拦截。
+ """
+
+ return list(self._cached_deferred_tool_infos)
+
+ def _vision_tool_target_provided(
+ self, tool_name: str, arguments: Any = None, agent: Any = None
+ ) -> bool:
+ """视觉工具的目标图片是否**全部**已在最终窗口随消息提供像素。
+
+ ``arguments`` 缺省 / 远程 URL / 未提供像素的本地目标都返回 False(放行)——
+ 那正是保留的兜底路径,不能既拦调用又让模型拿不到图。
+ """
+
+ if not is_vision_tool(tool_name) or not self._native_image_pixels_sent(agent):
+ return False
+ # provided 快照与 native_images_sent 同口径镜像在 agent 树上;按同一候选集
+ # 逐个读,命中权威快照即停止(空列表 = 这次确实没有像素 → 放行)。
+ for candidate in (
+ agent,
+ getattr(self, "_config_agent", None),
+ getattr(self, "_deep_agent", None),
+ getattr(self, "_runtime_agent", None),
+ ):
+ provided = provided_image_paths(agent=candidate)
+ if provided is None:
+ continue
+ if not provided:
+ return False
+ return vision_tool_targets_all_provided(tool_name, arguments, provided)
+ return False
+
@staticmethod
def _deferred_name_fingerprint(tools: list[Any]) -> frozenset[str]:
"""Return a name-only fingerprint for TOOL_NAVIGATION cache stability.
@@ -885,7 +1018,8 @@ class ProgressiveToolRail(DeepAgentRail):
return
spb = getattr(ctx.agent, "system_prompt_builder", None)
- name_fp = self._deferred_name_fingerprint(self._cached_deferred_tool_infos)
+ visible_tools = self._visible_deferred_tool_infos(ctx.agent)
+ name_fp = self._deferred_name_fingerprint(visible_tools)
section_present = bool(
spb is not None
and hasattr(spb, "has_section")
@@ -934,7 +1068,7 @@ class ProgressiveToolRail(DeepAgentRail):
async def _build_navigation_section(self) -> PromptSection | None:
"""Build navigation prompt section for deferred tools."""
- if not self._cached_deferred_tool_infos:
+ if not self._visible_deferred_tool_infos():
return None
entries_cn = await self._build_navigation_entries(language="cn")
@@ -955,7 +1089,7 @@ class ProgressiveToolRail(DeepAgentRail):
) -> list[str]:
"""Build navigation entries for deferred tools."""
sorted_tools = sorted(
- self._cached_deferred_tool_infos,
+ self._visible_deferred_tool_infos(),
key=lambda t: str(getattr(t, "name", "") or ""),
)
@@ -1551,6 +1685,16 @@ class ProgressiveToolRail(DeepAgentRail):
"tool_name": tool_name,
}
+ # 视觉理解工具只拦"目标图片已在最终窗口提供"的重复调用(远程 URL / 未知
+ # 目标 / 未提供像素的本地图保留兜底)。ProgressiveToolRail 直接 invoke 目标
+ # 工具,不经过 agent 的 before_tool_call 链路,因此必须在这里拦一次。
+ if self._vision_tool_target_provided(tool_name, arguments=arguments):
+ return {
+ "success": False,
+ "error": build_native_image_tool_error(language=self.language),
+ "tool_name": tool_name,
+ }
+
registered_card = self._tool_by_name(
getattr(self, "_cached_all_tool_infos", ()),
tool_name,
diff --git a/jiuwenswarm/agents/harness/common/rails/read_file_validation.py b/jiuwenswarm/agents/harness/common/rails/read_file_validation.py
index 082b772ff5..62ca2ffb79 100644
--- a/jiuwenswarm/agents/harness/common/rails/read_file_validation.py
+++ b/jiuwenswarm/agents/harness/common/rails/read_file_validation.py
@@ -93,6 +93,26 @@ _BINARY_RESULT_MARKERS = (
_PATH_KEYS = ("path", "file_path", "file", "target_file")
+# 视觉理解工具:主模型可原生看图时这些工具应被跳过,图片像素已随消息提供。
+# ``image_ocr`` 是 agent-core 的真实工具名(``vision.py`` 的
+# ``build_tool_card("image_ocr", ...)``),``ImageOCR`` 是前端 / 权限投影里的显示名。
+# 本仓 multimodal_image_rail 的提示、permission_rail、code_agent_rail 归一后都用前者;
+# 漏登记会让"原生看图仍去调 OCR"的矛盾态从这个工具复活。
+VISION_TOOL_NAMES = frozenset(
+ {
+ "visual_question_answering",
+ "vision_qa",
+ "VisionQA",
+ "image_reading",
+ "image_ocr",
+ "ImageOCR",
+ }
+)
+
+
+def is_vision_tool(tool_name: str) -> bool:
+ return str(tool_name or "").strip() in VISION_TOOL_NAMES
+
def is_read_file_tool(tool_name: str) -> bool:
return str(tool_name or "").strip() in READ_FILE_TOOL_NAMES
@@ -129,6 +149,30 @@ def extract_path_from_arguments(arguments: Any) -> str | None:
return None
+def extract_paths_from_arguments(arguments: Any) -> list[str]:
+ """Extract all file paths from tool arguments, including ``file_paths`` lists."""
+ data = _coerce_arguments_dict(arguments)
+ if data is None:
+ single = extract_path_from_arguments(arguments)
+ return [single] if single else []
+
+ paths: list[str] = []
+ raw_paths = data.get("file_paths")
+ if isinstance(raw_paths, (list, tuple)):
+ paths.extend(
+ str(item).strip()
+ for item in raw_paths
+ if isinstance(item, str) and item.strip()
+ )
+ elif isinstance(raw_paths, str) and raw_paths.strip():
+ paths.append(raw_paths.strip())
+ for key in _PATH_KEYS:
+ value = data.get(key)
+ if isinstance(value, str) and value.strip():
+ paths.append(value.strip())
+ return list(dict.fromkeys(paths))
+
+
def is_image_file_path(path: str) -> bool:
if not path:
return False
@@ -144,6 +188,66 @@ def is_non_text_file_path(path: str) -> bool:
return False
+# 视觉工具的目标参数键:``image_ocr`` / ``visual_question_answering`` 用
+# ``image_path_or_url``(本地路径或公网 http(s) URL),``image_reading`` 用
+# ``local_url`` / ``remote_url``。这里只取字符串值,缺参 / 非字符串一律视为
+# "没有目标"。
+_VISION_TOOL_TARGET_KEYS = (
+ "image_path_or_url",
+ "image_url",
+ "image_path",
+ "local_url",
+ "remote_url",
+)
+
+
+def is_remote_image_url(value: str) -> bool:
+ """HTTP(S) 地址是远程图片,主模型原生像素不可能已随消息提供。
+
+ 远程图片只能由视觉工具自行拉取分析,不能因为"本轮提供了本地图片"就封禁
+ 对它调用 VQA / OCR 的兜底路径。
+ """
+ text = str(value or "").strip().lower()
+ return text.startswith("http://") or text.startswith("https://")
+
+
+def vision_tool_image_targets(tool_name: str, arguments: Any) -> list[str]:
+ """返回视觉工具本次调用要分析的目标图片(本地路径或 URL)列表。
+
+ 提取不到目标(未附带图片 / 参数缺失 / 非字符串)时返回空列表,调用方按
+ "未知目标"放行——不能既拦调用又让模型拿不到兜底路径。
+ """
+ data = _coerce_arguments_dict(arguments)
+ if data is None:
+ return []
+ targets: list[str] = []
+ for key in _VISION_TOOL_TARGET_KEYS:
+ value = data.get(key)
+ if isinstance(value, str) and value.strip():
+ targets.append(value.strip())
+ return targets
+
+
+def vision_tool_targets_all_provided(
+ tool_name: str, arguments: Any, provided_paths: Any
+) -> bool:
+ """视觉工具调用是否**全部**落在"已随消息提供像素"的本地路径上。
+
+ 仅当至少有一个目标、且每个目标都是已提供的本地路径时返回 True(该调用是对
+ 已到手像素的重复分析)。远程 URL / 未知目标 / 未提供的本地路径 → False(放行,
+ 保留视觉工具兜底路径)。
+ """
+ targets = vision_tool_image_targets(tool_name, arguments)
+ if not targets:
+ return False
+ from jiuwenswarm.agents.harness.common.multimodal import is_provided_image_path
+
+ return all(
+ not is_remote_image_url(target) and is_provided_image_path(target, provided_paths)
+ for target in targets
+ )
+
+
def build_non_text_read_error(path: str, *, language: str = "cn") -> str:
target = path or "<unknown>"
if language == "cn":
@@ -170,6 +274,46 @@ def is_read_file_error_message(message: str) -> bool:
return text.startswith(READ_FILE_ERROR_PREFIX)
+def build_provided_image_read_error(path: str, *, language: str = "cn") -> str:
+ """拒绝读取已随消息提供像素的图片。"""
+
+ target = path or "<unknown>"
+ if language == "cn":
+ return (
+ f"{READ_FILE_ERROR_PREFIX} 「{target}」已作为图像内容随本次消息直接提供,"
+ "无需再调用 read_file 读取;请直接使用已提供的图片像素。"
+ )
+ return (
+ f"{READ_FILE_ERROR_PREFIX} '{target}' is already provided as image content "
+ "in this request; do not call read_file for it. Use the provided image pixels directly."
+ )
+
+
+def build_native_image_tool_error(*, language: str = "cn") -> str:
+ """拒绝在原生看图模型下调用视觉理解工具(VQA / image_reading / image_ocr)。"""
+
+ if language == "cn":
+ return (
+ "[VISION_TOOL_SKIPPED] 当前模型支持原生看图,用户上传的图片已作为图像内容"
+ "随消息直接提供,无需调用 visual_question_answering、image_reading 或 "
+ "image_ocr。"
+ "请直接使用已提供的图片像素回答;其他本地图片请用 read_file 读取。"
+ )
+ return (
+ "[VISION_TOOL_SKIPPED] The current model supports native image understanding and "
+ "user-uploaded images are provided directly as image content. "
+ "Do not call visual_question_answering, image_reading or image_ocr. "
+ "Answer using the provided image pixels; for other local images use read_file."
+ )
+
+
+def reject_vision_tool_for_native_image(
+ ctx: "AgentCallbackContext", *, language: str = "cn"
+) -> None:
+ """Skip a vision tool call when the main model already received the pixels."""
+ reject_read_file(ctx, build_native_image_tool_error(language=language))
+
+
def _unwrap_tool_output(result: Any) -> Any:
"""ToolOutput(duck-typed:success/data/error)规整为等价 dict。"""
if isinstance(result, (str, dict)) or result is None:
diff --git a/jiuwenswarm/agents/harness/common/rails/stream_event_rail.py b/jiuwenswarm/agents/harness/common/rails/stream_event_rail.py
index 1bd17bea88..9a972018bb 100644
--- a/jiuwenswarm/agents/harness/common/rails/stream_event_rail.py
+++ b/jiuwenswarm/agents/harness/common/rails/stream_event_rail.py
@@ -37,9 +37,6 @@ from openjiuwen.harness.workspace.workspace import WorkspaceNode
from jiuwenswarm.agents.harness.common.rails.interrupt.interrupt_helpers import (
convert_interactions_to_ask_user_question,
)
-from jiuwenswarm.agents.harness.common.prompt.user_prompt_builder import (
- strip_image_content_from_model_context,
-)
from jiuwenswarm.agents.harness.common.rails.symphony import (
SymphonyToolStreamHandler,
)
@@ -49,10 +46,26 @@ from jiuwenswarm.agents.harness.common.rails.path_whitespace_fix import (
fix_whitespace_path_arguments,
)
from jiuwenswarm.agents.harness.common.rails.read_file_validation import (
+ build_non_text_read_error,
+ build_provided_image_read_error,
extract_path_from_arguments,
+ extract_paths_from_arguments,
handle_read_file_before_tool_call,
+ is_image_file_path,
+ is_non_text_file_path,
is_read_file_tool,
+ is_vision_tool,
normalize_read_file_tool_outcome,
+ reject_read_file,
+ reject_vision_tool_for_native_image,
+ vision_tool_targets_all_provided,
+)
+from jiuwenswarm.agents.harness.common.rails.multimodal_image_state import (
+ PROVIDED_IMAGE_PATHS_KEY,
+ mark_native_images_sent,
+ mark_provided_image_paths,
+ native_images_sent,
+ provided_image_paths,
)
from jiuwenswarm.agents.harness.common.rails.task_execution_rail import (
SKILL_TURBO_OUTER_TODO_ACTIVE_EXTRA_KEY,
@@ -81,6 +94,9 @@ from jiuwenswarm.common.utils import fix_json_arguments, logger
_TODO_TOOL_NAMES = frozenset(["todo_create", "todo_get", "todo_list", "todo_modify", "todo"])
_EARLY_CHECKPOINT_EXTRA_KEY = "_jiuwenswarm_early_checkpoint_done"
_WHITESPACE_PATH_FIXES_EXTRA_KEY = "_jiuwenswarm_whitespace_path_fixes"
+_PROVIDED_IMAGE_PATHS_EXTRA_KEY = PROVIDED_IMAGE_PATHS_KEY
+# 已按原文件重新出图的路径(invoke 级):同一张图只允许重读一次,避免重复 base64。
+_RE_READ_IMAGE_PATHS_EXTRA_KEY = "_jiuwenswarm_re_read_image_paths"
_EARLY_CHECKPOINT_ENV = "JIUWENCLAW_EARLY_CHECKPOINT"
@@ -657,13 +673,122 @@ class JiuSwarmStreamEventRail(DeepAgentRail):
"language", None,
) or "cn"
- def _read_image_multimodal_enabled(self) -> bool:
- deep_config = (
- getattr(self._deep_agent, "deep_config", None)
- or getattr(self._deep_agent, "_deep_config", None)
+ def _native_read_image_enabled(self) -> bool:
+ """Whether read_file should inline image bytes into the main model.
+
+ ``deep_config.enable_read_image_multimodal`` is the single resolved
+ source of truth (already derived from the model's declared image
+ capability). When it is on, the read_file_validation pre-check must
+ not reject image paths — the actual ReadFileTool will attach pixels.
+ """
+ deep_config = getattr(self._deep_agent, "deep_config", None) or getattr(
+ self._deep_agent, "_deep_config", None
)
return bool(getattr(deep_config, "enable_read_image_multimodal", False))
+ def _native_image_pixels_sent(self, ctx: AgentCallbackContext | None = None) -> bool:
+ """原生看图**且**本次请求确实把像素发出去了。
+
+ 视觉工具护栏只在这种情况拦截:能力位为真但像素没到(注入失败 / 预算全
+ 卸载)时模型看不见图,VQA 是唯一兜底,必须放行。
+ """
+
+ if not self._native_read_image_enabled():
+ return False
+ # 张数由发送侧写在 agent 树上;ctx.agent 可能是包装对象,rail 自己持的
+ # _deep_agent 才是稳定的写入目标,两处都读一遍取较大值。
+ candidates = [getattr(ctx, "agent", None), getattr(self, "_deep_agent", None)]
+ return any(
+ native_images_sent(ctx=ctx, agent=candidate) > 0
+ for candidate in candidates
+ if candidate is not None
+ )
+
+ def _provided_image_paths(self, ctx: AgentCallbackContext) -> list[str]:
+ """本次请求已随消息提供**像素**的图片路径(请求级快照)。
+
+ 只读 ContextVar(上传清单)在两种场景下会说谎:工具跨任务 / 线程执行时
+ ContextVar 会丢;而"上传了"不等于"像素进了消息"(预算淘汰 / 引用行没解析 /
+ 读文件失败都会 0 张)。因此权威快照由 ``MultimodalImageRail.before_model_call``
+ (内层 ctx,与工具钩子共享同一个 extra)按注入后的历史实际 ``attached`` 集合
+ 写入;缺失时才就地按历史计算一次并回填。
+ """
+
+ cached = provided_image_paths(ctx)
+ if cached is not None:
+ # 空列表也是权威事实(这次确实没有像素),据此放行 read_file 重读。
+ return cached
+ return self._compute_provided_image_paths(ctx)
+
+ def _compute_provided_image_paths(self, ctx: AgentCallbackContext) -> list[str]:
+ """快照缺失时的回退:按当前历史里 ``attached`` 的图片路径现算一次。
+
+ 读不到历史(``ctx.context is None`` / 读取异常)时**不写**快照——无法确认
+ 负载,留给下一个 ``before_model_call`` 的权威写入点;此刻按"未知即空"返回,
+ 宁可放行 read_file(模型最多多读一张图)也不误判"已提供"。
+ """
+
+ from jiuwenswarm.agents.harness.common.multimodal import (
+ collect_provided_image_paths,
+ )
+
+ context = getattr(ctx, "context", None)
+ if context is None:
+ return []
+ try:
+ messages = list(context.get_messages() or [])
+ except Exception:
+ logger.debug(
+ "[StreamEventRail] read messages for provided image paths failed",
+ exc_info=True,
+ )
+ return []
+ try:
+ paths = collect_provided_image_paths(messages)
+ except Exception:
+ logger.debug(
+ "[StreamEventRail] collect provided image paths failed",
+ exc_info=True,
+ )
+ return []
+ return mark_provided_image_paths(ctx, paths)
+
+ def _re_read_image_paths(self, ctx: AgentCallbackContext) -> list[str]:
+ """本次 invoke 已放行"重新出图"的图片路径(可原地 append 的可变列表)。"""
+
+ extra = getattr(ctx, "extra", None)
+ if not isinstance(extra, dict):
+ return []
+ cached = extra.get(_RE_READ_IMAGE_PATHS_EXTRA_KEY)
+ if isinstance(cached, list):
+ return cached
+ created: list[str] = []
+ extra[_RE_READ_IMAGE_PATHS_EXTRA_KEY] = created
+ return created
+
+ def _omitted_image_paths(self, ctx: AgentCallbackContext) -> list[str]:
+ """历史里像素已被卸载的图片路径。
+
+ 不缓存成 invoke 级快照:预算卸载发生在本轮 ``before_model_call``,同一轮
+ 内随后的 ``read_file`` 就应该能按原文件重新出图。消息文本扫描成本很低。
+ """
+
+ context = getattr(ctx, "context", None)
+ if context is None:
+ return []
+ try:
+ messages = context.get_messages()
+ except Exception: # pragma: no cover - defensive context guard
+ return []
+ from jiuwenswarm.agents.harness.common.multimodal import (
+ collect_omitted_image_paths,
+ )
+
+ try:
+ return collect_omitted_image_paths(list(messages))
+ except Exception: # pragma: no cover - 护栏失败放行原始判定
+ return []
+
def _tool_interrupted_message(self, tool_name: str) -> str:
"""Build a language-aware tool interruption message."""
if self._get_prompt_language() == "en":
@@ -957,6 +1082,12 @@ class JiuSwarmStreamEventRail(DeepAgentRail):
# ------------------------------------------------------------------
async def before_invoke(self, ctx: AgentCallbackContext) -> None:
+ # 已提供图片快照**不能**在这里写:BEFORE_INVOKE 是 DeepAgent 外层事件,
+ # 而 BEFORE_MODEL_CALL / BEFORE_TOOL_CALL 经 _BRIDGE_EVENTS 桥接到内层
+ # ReActAgent,两边 ctx.extra 是两个不同 dict——写在外层等于工具钩子永远
+ # 读不到(现场"已提供图片重复读未拦"就是这么漏的)。权威快照在
+ # before_model_call(内层 ctx)写;这里只把跨请求残留的张数归零。
+ mark_native_images_sent(agent=getattr(ctx, "agent", None), count=0)
if not isinstance(ctx.inputs, InvokeInputs):
return
# Subagents have no session on their before_invoke (ctx.session is None);
@@ -1030,6 +1161,9 @@ class JiuSwarmStreamEventRail(DeepAgentRail):
# ------------------------------------------------------------------
async def before_model_call(self, ctx: AgentCallbackContext) -> None:
+ # 请求级图片路径快照不在这里预写:此时像素还没注入,按上传清单 / 历史现状写
+ # 只会固化成错误事实。权威写入点是 ``MultimodalImageRail.before_model_call``
+ # (注入后按实际 attached 集合写,内层 ctx 与工具钩子共享同一个 extra)。
sid = self._resolve_sid(ctx, ctx.session)
await self._get_pause_event(sid).wait()
if self._abort_requested.get(sid, False):
@@ -1043,8 +1177,6 @@ class JiuSwarmStreamEventRail(DeepAgentRail):
self._ensure_tool_call_goal_prompt()
if ctx.context is not None:
- if not self._read_image_multimodal_enabled():
- strip_image_content_from_model_context(ctx.context)
await self._fix_incomplete_tool_context(ctx)
await self._maybe_early_checkpoint(ctx)
@@ -1257,9 +1389,98 @@ class JiuSwarmStreamEventRail(DeepAgentRail):
# entries are popped in after_tool_call keyed by tool_call_id.
ctx.extra.setdefault(_WHITESPACE_PATH_FIXES_EXTRA_KEY, {})[tool_call_id] = fixes
if is_read_file_tool(tool_name):
- path = extract_path_from_arguments(getattr(tc, "arguments", {}))
- if path:
- handle_read_file_before_tool_call(ctx, path)
+ arguments = getattr(tc, "arguments", {})
+ paths = extract_paths_from_arguments(arguments)
+ native_image_enabled = self._native_read_image_enabled()
+ if native_image_enabled:
+ from jiuwenswarm.agents.harness.common.multimodal import (
+ is_provided_image_path,
+ )
+
+ provided_paths = self._provided_image_paths(ctx)
+ omitted_paths = self._omitted_image_paths(ctx)
+ re_read_paths = self._re_read_image_paths(ctx)
+ duplicate = []
+ re_read: list[str] = []
+ for path in paths:
+ if not is_provided_image_path(path, provided_paths):
+ continue
+ if is_provided_image_path(path, omitted_paths) and not (
+ is_provided_image_path(path, re_read_paths)
+ or is_provided_image_path(path, re_read)
+ ):
+ # 这张图的像素已被预算卸载 / 读取失败:允许按原文件重新
+ # 出图(重新缩小编码),而不是放大已压糊的历史像素。
+ re_read.append(path)
+ continue
+ duplicate.append(path)
+ if re_read:
+ re_read_paths.extend(re_read)
+ logger.info(
+ "[stream_event_rail] allow image re-read from original file: %s",
+ re_read,
+ )
+ if duplicate:
+ # 本次请求已随消息提供像素,禁止重复读取同一张图(含
+ # file_paths 批量读里的任意一项)——重复读只会多一份 base64。
+ reject_read_file(
+ ctx,
+ build_provided_image_read_error(
+ duplicate[0],
+ language=self._get_prompt_language(),
+ ),
+ )
+ else:
+ # 原生开启时放行 read_file 对图片的读取,交给 ReadFileTool
+ # 内联像素;非图片二进制路径仍拒绝纯文本读取。
+ blocking = None
+ for path in paths:
+ if is_non_text_file_path(path) and not is_image_file_path(path):
+ blocking = path
+ break
+ if blocking:
+ reject_read_file(
+ ctx,
+ build_non_text_read_error(
+ blocking,
+ language=self._get_prompt_language(),
+ ),
+ )
+ else:
+ path = extract_path_from_arguments(arguments)
+ if path and not is_image_file_path(path):
+ handle_read_file_before_tool_call(ctx, path)
+ else:
+ path = extract_path_from_arguments(arguments)
+ if path:
+ handle_read_file_before_tool_call(ctx, path)
+ else:
+ # 批量读没有单一路径时,逐个检查 file_paths 里的非文本项。
+ blocking = next(
+ (item for item in paths if is_non_text_file_path(item)),
+ None,
+ )
+ if blocking:
+ reject_read_file(
+ ctx,
+ build_non_text_read_error(
+ blocking,
+ language=self._get_prompt_language(),
+ ),
+ )
+ if is_vision_tool(tool_name) and self._native_image_pixels_sent(ctx):
+ # 视觉工具只拦"目标图片已在最终窗口提供"的重复调用。远程 URL /
+ # 未知目标 / 未随消息提供像素的本地图必须保留兜底路径:模型已经收到
+ # 图 A 再调 VQA 分析远程图 B 是必要调用,拦掉等于封死远程图片输入
+ # (read_file 不能替代 HTTP(S) 地址)。判定按最终窗口的 provided
+ # 快照逐目标比对,而不是"本轮存在任意图片"的一刀切。
+ arguments = getattr(tc, "arguments", {}) if tc else {}
+ if vision_tool_targets_all_provided(
+ tool_name, arguments, self._provided_image_paths(ctx)
+ ):
+ reject_vision_tool_for_native_image(
+ ctx, language=self._get_prompt_language()
+ )
# 主模型随 tool_call 产出的目标文案(call_goal):取出后剥掉,避免 schema 拒收。
# 绝不碰 display_name(team 成员名等业务字段)。
model_display, cleaned_args = extract_call_goal(
diff --git a/jiuwenswarm/agents/harness/common/read_file_image_support.py b/jiuwenswarm/agents/harness/common/read_file_image_support.py
new file mode 100644
index 0000000000..8988d7b842
--- /dev/null
+++ b/jiuwenswarm/agents/harness/common/read_file_image_support.py
@@ -0,0 +1,84 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""agent-core ``ReadFileTool`` 图片内联能力的跨版本接线。
+
+agent-core 的 ``ReadFileTool(image_multimodal_resolver=...)``(调用时求值)与
+``_image_multimodal_enabled()`` 尚未进入 ``uv.lock`` 锁定的 dev-stable(8215f2c)。
+本模块按构造函数签名探测一次,避免把该参数无条件传给旧版本 core:
+``TypeError: __init__() got an unexpected keyword argument`` 会让整条 rail 装配失败。
+
+- core 支持:resolver 透传,read_file 每次调用时求值,模型热切换立即跟随;
+- core 不支持:只在构造时求值(装配时的能力值),退回既有的静态语义。
+
+core 侧 resolver 合入并刷新 ``uv.lock`` 后,本模块自动走支持分支,无需再改调用点。
+"""
+
+from __future__ import annotations
+
+import inspect
+import logging
+from collections.abc import Callable
+from typing import Any
+
+logger = logging.getLogger(__name__)
+
+IMAGE_MULTIMODAL_RESOLVER_PARAM = "image_multimodal_resolver"
+
+_supports_resolver: bool | None = None
+
+
+def supports_read_file_image_resolver() -> bool:
+ """Whether the installed openjiuwen ``ReadFileTool`` accepts a resolver kwarg."""
+
+ global _supports_resolver
+ if _supports_resolver is None:
+ try:
+ from openjiuwen.harness.tools.filesystem import ReadFileTool
+ except ImportError:
+ # 不缓存:openjiuwen 可能稍后才可用(局部导入 / 测试替身)。
+ return False
+ try:
+ parameters = inspect.signature(ReadFileTool.__init__).parameters
+ except (TypeError, ValueError):
+ _supports_resolver = False
+ else:
+ _supports_resolver = IMAGE_MULTIMODAL_RESOLVER_PARAM in parameters or any(
+ parameter.kind is inspect.Parameter.VAR_KEYWORD
+ for parameter in parameters.values()
+ )
+ return bool(_supports_resolver)
+
+
+def build_read_file_image_kwargs(
+ resolver: Callable[[], bool] | None = None,
+ *,
+ enable_image_multimodal: bool,
+) -> dict[str, Any]:
+ """ReadFileTool 的图片能力关键字参数(无 resolver 的 core 只收静态 bool)。"""
+
+ kwargs: dict[str, Any] = {
+ "enable_image_multimodal": bool(enable_image_multimodal),
+ }
+ if resolver is not None and supports_read_file_image_resolver():
+ kwargs[IMAGE_MULTIMODAL_RESOLVER_PARAM] = resolver
+ return kwargs
+
+
+def read_file_image_multimodal_enabled(tool: Any) -> bool:
+ """工具当前的图片内联开关:新 core 有调用时方法,旧 core 退回实例属性。"""
+
+ checker = getattr(tool, "_image_multimodal_enabled", None)
+ if callable(checker):
+ try:
+ return bool(checker())
+ except Exception: # 诊断辅助:探测失败退回静态属性,不影响工具构造
+ logger.debug("read_file image resolver probe failed", exc_info=True)
+ return bool(getattr(tool, "enable_image_multimodal", False))
+
+
+__all__ = [
+ "IMAGE_MULTIMODAL_RESOLVER_PARAM",
+ "build_read_file_image_kwargs",
+ "read_file_image_multimodal_enabled",
+ "supports_read_file_image_resolver",
+]
diff --git a/jiuwenswarm/agents/harness/common/tools/model_capabilities.py b/jiuwenswarm/agents/harness/common/tools/model_capabilities.py
new file mode 100644
index 0000000000..deb652cc79
--- /dev/null
+++ b/jiuwenswarm/agents/harness/common/tools/model_capabilities.py
@@ -0,0 +1,51 @@
+# coding: utf-8
+"""模型原生能力(modalities)的配置归一。
+
+纯函数模块:不引入 I/O,不读取历史,不处理 base64。
+
+每个模型条目的原生能力由 ``modalities`` 列表声明(OpenAI 风格),例如
+``modalities: [text, image]``。是否支持原生图片输入只由该列表是否含 ``image``
+决定:
+
+- 列表含 ``image`` → 支持原生看图(原生图片输入);
+- 缺失 / 未声明 / 其它不可识别值 → 不支持(走 VQA / 视觉工具链)。
+
+不再内置模型能力表,也不按模型名前缀猜测。
+"""
+
+from __future__ import annotations
+
+
+def coerce_modalities(value: object) -> list[str] | None:
+ """把配置里的 ``modalities`` 规范成小写去重列表;无法识别 → None(未声明)。
+
+ YAML 里 ``modalities: [text, image]`` 会被解析成字符串列表;也可能被写成
+ 单个字符串或逗号/空白分隔字符串(``"text,image"``)。这里统一成规范模态列表,
+ 去空白、去重、保序;空列表 / 空串 / 其它非字符串容器一律归 None。
+ """
+
+ if value is None:
+ return None
+ if isinstance(value, str):
+ tokens: list[str] = [p for p in value.replace(",", " ").split() if p]
+ elif isinstance(value, (list, tuple, set, frozenset)):
+ tokens = [item.strip() for item in value if isinstance(item, str)]
+ else:
+ return None
+ if not tokens:
+ return None
+ normalized: list[str] = []
+ seen: set[str] = set()
+ for token in tokens:
+ canonical = token.strip().lower()
+ if not canonical or canonical in seen:
+ continue
+ seen.add(canonical)
+ normalized.append(canonical)
+ return normalized or None
+
+
+def supports_native_image(value: object) -> bool:
+ """给定模型条目的 ``modalities`` 声明,判定是否支持原生图片输入。"""
+
+ return "image" in (coerce_modalities(value) or ())
diff --git a/jiuwenswarm/agents/harness/flash/rails/slim_sys_operation_rail.py b/jiuwenswarm/agents/harness/flash/rails/slim_sys_operation_rail.py
index c7ac87ea9a..e3333e8c03 100644
--- a/jiuwenswarm/agents/harness/flash/rails/slim_sys_operation_rail.py
+++ b/jiuwenswarm/agents/harness/flash/rails/slim_sys_operation_rail.py
@@ -39,17 +39,30 @@ class SlimSysOperationRail(SysOperationRail):
from ..tools.flash_glob_tool import FlashGlobTool
from ..tools.flash_read_tool import FlashReadFileTool
+ from jiuwenswarm.agents.harness.common.read_file_image_support import (
+ build_read_file_image_kwargs,
+ )
+
lang = agent.system_prompt_builder.language
agent_id = getattr(getattr(agent, "card", None), "id", None)
- enable_read_image_multimodal = should_enable_read_image_multimodal(
- agent,
- self._enable_read_image_multimodal,
- )
+
+ def _image_multimodal_resolver() -> bool:
+ # 调用时求值:切模型后 read_file 的内联行为跟随当前模型能力。
+ return should_enable_read_image_multimodal(
+ agent,
+ self._enable_read_image_multimodal,
+ )
+
read_tool = FlashReadFileTool(
self.sys_operation,
lang,
agent_id,
- enable_image_multimodal=enable_read_image_multimodal,
+ # resolver 仅在 core 提供 image_multimodal_resolver 参数时透传;锁定 core
+ # (8215f2c 的 enable_image_multimodal 是纯 bool)退回构造时求值的静态值。
+ **build_read_file_image_kwargs(
+ _image_multimodal_resolver,
+ enable_image_multimodal=_image_multimodal_resolver(),
+ ),
)
write_tool = WriteFileTool(self.sys_operation, lang, agent_id)
edit_tool = FlashEditFileTool(self.sys_operation, lang, agent_id)
diff --git a/jiuwenswarm/agents/harness/flash/tools/flash_bash_tool.py b/jiuwenswarm/agents/harness/flash/tools/flash_bash_tool.py
index 3358cf6bc5..e36e35a000 100644
--- a/jiuwenswarm/agents/harness/flash/tools/flash_bash_tool.py
+++ b/jiuwenswarm/agents/harness/flash/tools/flash_bash_tool.py
@@ -23,6 +23,9 @@ from openjiuwen.harness.tools.base_tool import ToolOutput
from openjiuwen.harness.tools.shell.bash._tool import BashTool
from openjiuwen.harness.tools.filesystem import _parse_rm_targets
+from jiuwenswarm.agents.harness.common.read_file_image_support import (
+ build_read_file_image_kwargs,
+)
from jiuwenswarm.agents.harness.common.tools.command_tools import (
_build_subprocess_env,
_windows_not_found_hint,
@@ -212,7 +215,11 @@ class FlashBashSysOperationRail(SysOperationRail):
super().init(agent)
if self.tools is None:
return
+ from openjiuwen.harness.rails._multimodal import (
+ should_enable_read_image_multimodal,
+ )
from openjiuwen.harness.tools.filesystem import ReadFileTool
+
from jiuwenswarm.agents.harness.flash.tools.flash_read_tool import (
FlashReadFileTool,
)
@@ -236,8 +243,46 @@ class FlashBashSysOperationRail(SysOperationRail):
elif isinstance(tool, ReadFileTool) and not isinstance(
tool, FlashReadFileTool
):
+ # 新 core 的 stock init 会把"调用时求值"的 resolver 装到
+ # _image_multimodal_resolver;替换成 flash 增强版时必须一起继承,否则
+ # read_file 退回 init 期默认值 True——纯文本模型也读像素、切模型不生效。
+ image_resolver = getattr(tool, "_image_multimodal_resolver", None)
+ if not callable(image_resolver):
+ # 锁定 core(8215f2c 的 enable_image_multimodal 是纯 bool)没有该
+ # 属性;从 agent 重派生同一 resolver,待 core 合入
+ # image_multimodal_resolver 后 build_read_file_image_kwargs 才透传它
+ # (锁定 core 上退回构造时求值的静态 bool,热切换能力未启用)。
+ def _lock_core_image_resolver() -> bool:
+ return should_enable_read_image_multimodal(
+ agent,
+ self._enable_read_image_multimodal,
+ )
+
+ image_resolver = _lock_core_image_resolver
+ if callable(image_resolver):
+ try:
+ image_enabled = bool(image_resolver())
+ except Exception:
+ image_enabled = bool(
+ getattr(tool, "enable_image_multimodal", True)
+ )
+ else:
+ image_enabled = bool(
+ getattr(tool, "enable_image_multimodal", True)
+ )
swap_targets.append(
- (idx, FlashReadFileTool(self.sys_operation, lang, agent_id))
+ (
+ idx,
+ FlashReadFileTool(
+ self.sys_operation,
+ lang,
+ agent_id,
+ **build_read_file_image_kwargs(
+ image_resolver,
+ enable_image_multimodal=image_enabled,
+ ),
+ ),
+ )
)
for idx, replacement in swap_targets:
self.tools[idx] = replacement
diff --git a/jiuwenswarm/agents/harness/flash/tools/flash_read_tool.py b/jiuwenswarm/agents/harness/flash/tools/flash_read_tool.py
index d14ace773a..6044b03e6b 100644
--- a/jiuwenswarm/agents/harness/flash/tools/flash_read_tool.py
+++ b/jiuwenswarm/agents/harness/flash/tools/flash_read_tool.py
@@ -25,7 +25,7 @@ import asyncio
import logging
import os
import re
-from typing import Any, Dict, List, Optional
+from typing import Any, Callable, Dict, List, Optional
from openjiuwen.core.common.exception.codes import StatusCode
from openjiuwen.harness.tools.base_tool import ToolOutput
@@ -36,6 +36,10 @@ from openjiuwen.harness.tools.filesystem import (
_resolve_tool_file_path,
)
+from jiuwenswarm.agents.harness.common.read_file_image_support import (
+ build_read_file_image_kwargs,
+)
+
from .flash_file_meta import detect_encoding, record_file_meta
logger = logging.getLogger(__name__)
@@ -135,12 +139,16 @@ class FlashReadFileTool(ReadFileTool):
language: str = "cn",
agent_id: Optional[str] = None,
enable_image_multimodal: bool = True,
+ image_multimodal_resolver: Optional[Callable[[], bool]] = None,
) -> None:
super().__init__(
operation,
language,
agent_id=agent_id,
- enable_image_multimodal=enable_image_multimodal,
+ **build_read_file_image_kwargs(
+ image_multimodal_resolver,
+ enable_image_multimodal=enable_image_multimodal,
+ ),
)
lang = language or "cn"
self.card.description = FLASH_READ_DESCRIPTION.get(
diff --git a/jiuwenswarm/common/utils.py b/jiuwenswarm/common/utils.py
index 3f0851ac67..71d7547ed2 100644
--- a/jiuwenswarm/common/utils.py
+++ b/jiuwenswarm/common/utils.py
@@ -67,7 +67,8 @@ except ImportError:
jsonlogger = None
# read_file 工具:False 时不把图片字节注入主模型对话,改走 image_reading / VQA 等视觉工具。
-# 用于 create_deep_agent(enable_read_image_multimodal=...) 与 MultimodalImageRail(enable_image_multimodal=...)。
+# 仅用于无请求模型上下文的旁路装配(wiki_tools / auto_memory extraction_runner);
+# 主链路(deep/code/flash adapter)按当前模型能力逐请求解析,不读这个常量。
DEFAULT_ENABLE_READ_IMAGE_MULTIMODAL: bool = False
_LOG_FILE_MAX_BYTES = 20 * 1024 * 1024
diff --git a/jiuwenswarm/gateway/media_attachments.py b/jiuwenswarm/gateway/media_attachments.py
index ef92a14628..1cb2777a58 100644
--- a/jiuwenswarm/gateway/media_attachments.py
+++ b/jiuwenswarm/gateway/media_attachments.py
@@ -23,7 +23,37 @@ _SUPPORTED_IMAGE_MIME_TYPES = {
"image/gif": ".gif",
}
_MAX_IMAGE_BYTES = 10 * 1024 * 1024
-_MAX_IMAGE_COUNT = 8
+# 与 ``react.multimodal_image_max_count`` 的默认值保持一致;运行时以配置为准,这里只是
+# 读不到配置时的兜底(上传侧先按张数截断,模型侧预算仍会按最老优先再裁一次)。
+_DEFAULT_MAX_IMAGE_COUNT = 8
+
+
+def _max_image_count() -> int:
+ """上传侧图片张数上限:跟随 ``react.multimodal_image_max_count``(默认 8)。
+
+ 语义与 rail / 模型侧预算一致:``0 = 不限``(不截断上传件)。只有缺失、负数或
+ 非整数配置才回退默认值——把显式 0 当成 8 会让「用户按说明配 0」在不知不觉中
+ 丢掉第 9 张之后的图,而模型侧预算还以为不限。
+ """
+
+ try:
+ from jiuwenswarm.common.config import get_config
+
+ react_cfg = (get_config() or {}).get("react") or {}
+ value = react_cfg.get("multimodal_image_max_count")
+ except Exception:
+ return _DEFAULT_MAX_IMAGE_COUNT
+ if value is None:
+ return _DEFAULT_MAX_IMAGE_COUNT
+ # 非整数的浮点(如 0.5)会被 int() 静默截断成 0,而 0 是「不限」——
+ # 一次配置笔误就把上传侧限流关掉。按 docstring 承诺回退默认值。
+ if isinstance(value, float) and not value.is_integer():
+ return _DEFAULT_MAX_IMAGE_COUNT
+ try:
+ parsed = int(value)
+ except (TypeError, ValueError):
+ return _DEFAULT_MAX_IMAGE_COUNT
+ return parsed if parsed >= 0 else _DEFAULT_MAX_IMAGE_COUNT
def normalize_chat_media_attachments(params: dict[str, Any], session_id: str | None) -> None:
@@ -40,7 +70,10 @@ def normalize_chat_media_attachments(params: dict[str, Any], session_id: str | N
return
stored: list[dict[str, Any]] = []
- for index, item in enumerate(raw_items[:_MAX_IMAGE_COUNT]):
+ limit = _max_image_count()
+ # 0 = 不限:不能切成 raw_items[:0] 把所有上传件都丢掉。
+ items = raw_items if limit <= 0 else raw_items[:limit]
+ for index, item in enumerate(items):
if not isinstance(item, dict):
continue
if item.get("type") != "image":
diff --git a/jiuwenswarm/resources/config.yaml b/jiuwenswarm/resources/config.yaml
index 04b02a895c..f68c3cb592 100644
--- a/jiuwenswarm/resources/config.yaml
+++ b/jiuwenswarm/resources/config.yaml
@@ -328,6 +328,9 @@ models:
# 值取自环境变量 LLM_MAX_TOKENS
# 未设置时回落 32768;jiuwenswarm 自身 .env 的同名变量优先级更高
max_tokens: ${LLM_MAX_TOKENS:-32768}
+ # 该主模型的原生能力模态(OpenAI 风格):只有 modalities 含 image 才走原生看图;
+ # 未声明 / 不含 image / 其它值一律按不支持处理(走 VQA / 视觉工具链),不再内置能力表猜测。
+ # modalities: [text, image]
is_default: true
video:
model_client_config:
@@ -614,6 +617,17 @@ react:
enable_task_execution_rail: true
max_iterations: 100
model_name: ${MODEL_NAME}
+ # 原生图片输入没有 react 级开关:是否走原生看图由每个模型条目自己的
+ # modalities 是否含 image 决定(含 image 才开启,其余一律走 VQA 工具链,见 models.defaults)。
+ # 单次请求图片预算(与模型无关):超出时把最老的图片替换成文字说明并写入历史,
+ # 之后不再自动加回。字节数 0 = 不限;张数 0 = 不限(默认 8 张;gateway 上传侧
+ # 同读该张数配置截断上传件)。
+ multimodal_image_budget: 0
+ # 图片视觉 token 预算:按分辨率(OpenAI tile 算法)计量图片在上下文窗口的占用,
+ # 而不是按 base64 字符长度;计量按**缩小后的发送尺寸**(最长边 1536)折算。
+ # 0 = 不限。
+ multimodal_image_token_budget: 0
+ multimodal_image_max_count: 8
skill_mode: all
# Per-skill credential env vars injected into shell tools when a skill is active.
# OfficeClaw sync writes real values here (e.g. hwocr HWOCR_AK/HWOCR_SK). Empty {} is a
@@ -735,6 +749,10 @@ react:
enable_reload: true # 卸载重载:开启后模型可通过 [[HANDLE:xxx]] 标记把已卸载的大消息原文拉回上下文
enable_context_debug: false # 上下文压缩 debug 模式:开启后各处理器在阈值判断、片段切分、压缩重试、 前后对比等每个阶段落盘 JSONL 记录,便于排查压缩问题。关闭时零开销。默认关闭
+ # 精确 token 计数(tiktoken BPE):false 时用字符估算,但图片块已按像素视觉 token
+ # 计价(不会把 base64 当文本算)。true 时文本走 BPE、图片仍按像素;首次加载可能
+ # 需要下载词表(agent-core 有后台预热)。默认关闭。
+ # enable_tiktoken_counter: false
# debug 记录目录;留空则按环境变量 OPENJIUWEN_CONTEXT_DEBUG_DIR,
# 再缺省落到 {workspace}/context/{session_id}_context/context_debug/
# context_debug_dir:
diff --git a/jiuwenswarm/server/agent_ws_server.py b/jiuwenswarm/server/agent_ws_server.py
index 993ce4555e..fd8e135e5a 100644
--- a/jiuwenswarm/server/agent_ws_server.py
+++ b/jiuwenswarm/server/agent_ws_server.py
@@ -1878,13 +1878,12 @@ class AgentWebSocketServer:
def _build_model_cache(self) -> None:
"""Build model cache from jiuwenswarm config.yaml (reuse interface_deep logic)."""
- from jiuwenswarm.server.runtime.agent_adapter.interface_deep import JiuWenSwarmDeepAdapter
+ from jiuwenswarm.server.runtime.agent_adapter.interface_deep import (
+ _build_model_from_entry as build_model_from_entry,
+ )
config = get_config()
- # Use the same model building method as interface_deep
- build_model_from_entry = getattr(JiuWenSwarmDeepAdapter, '_build_model_from_entry')
-
# Build from models.defaults list
for entry in get_default_models(config):
mcc = entry.get("model_client_config") or {}
@@ -1892,7 +1891,11 @@ class AgentWebSocketServer:
if not model_name:
continue
mco = entry.get("model_config_obj") or {}
- self._model_cache[model_name] = build_model_from_entry(mcc, mco)
+ self._model_cache[model_name] = build_model_from_entry(
+ mcc,
+ mco,
+ modalities=entry.get("modalities"),
+ )
# Fallback to legacy format if needed (same as interface_deep._build_model_cache_legacy)
if not self._model_cache:
@@ -1911,7 +1914,13 @@ class AgentWebSocketServer:
or react_config.get("model_config_obj")
or {}
)
- self._model_cache[model_name] = build_model_from_entry(mcc, mco)
+ self._model_cache[model_name] = build_model_from_entry(
+ mcc,
+ mco,
+ modalities=default_model_config.get("modalities")
+ if default_model_config.get("modalities") is not None
+ else react_config.get("modalities"),
+ )
# Set default model (first one)
if self._model_cache:
diff --git a/jiuwenswarm/server/runtime/agent_adapter/deep/model_factory.py b/jiuwenswarm/server/runtime/agent_adapter/deep/model_factory.py
index 3748bb84ac..acc83985c7 100644
--- a/jiuwenswarm/server/runtime/agent_adapter/deep/model_factory.py
+++ b/jiuwenswarm/server/runtime/agent_adapter/deep/model_factory.py
@@ -30,7 +30,6 @@ from jiuwenswarm.agents.harness.common.tools.multimodal_config import (
)
from jiuwenswarm.common.reasoning_injector import build_reasoning_model_request_kwargs
from jiuwenswarm.common.schema.agent import AgentRequest
-from jiuwenswarm.common.utils import DEFAULT_ENABLE_READ_IMAGE_MULTIMODAL
from jiuwenswarm.server.runtime.agent_adapter.deep.pure_helpers import _normalize_reload_value
logger = logging.getLogger(__name__)
@@ -317,7 +316,7 @@ def _system_prompt_reload_fingerprint(deep_cfg: Any | None) -> str | None:
_DEFAULT_STREAM_IDLE_TIMEOUT_SECONDS = 180.0
-def _build_model_from_entry(mcc: dict, mco: dict) -> Model:
+def _build_model_from_entry(mcc: dict, mco: dict, modalities: Any = None) -> Model:
"""根据单个模型条目的 model_client_config / model_config_obj 构建 Model 实例。"""
name = mcc.get("model_name", "")
# models.json 在 relay spawn 前落盘;未登录时 maas 条目 api_base/api_key 为空,
@@ -411,7 +410,17 @@ def _build_model_from_entry(mcc: dict, mco: dict) -> Model:
model_name=name,
)
)
- return Model(model_client_config=ModelClientConfig(**mcc_fields), model_config=m_config)
+ model = Model(model_client_config=ModelClientConfig(**mcc_fields), model_config=m_config)
+ # 能力声明按条目原文可能是 ``modalities: [text, image]`` 列表,也可能被写成
+ # 逗号/空白分隔字符串;downstream 只认规范列表——不归一就会把字符串当列表遍历,
+ # 让 ``image`` 判定失真。归一后挂到 Model 上,供看图判定与换模同步共用。
+ from jiuwenswarm.agents.harness.common.tools.model_capabilities import (
+ coerce_modalities,
+ )
+
+ # 单模型「原生能力模态」显式配置;None / 未声明一律按不支持看图处理(不再回退内置表)。
+ model.modalities = coerce_modalities(modalities)
+ return model
def _models_config_fingerprint(config: dict) -> str:
@@ -463,8 +472,9 @@ def _prepare_multimodal_image_inputs(
request: AgentRequest,
inputs: dict[str, Any],
) -> dict[str, Any]:
- from jiuwenswarm.agents.harness.common.prompt.user_prompt_builder import (
+ from jiuwenswarm.agents.harness.common.multimodal import (
extract_multimodal_image_files,
+ build_image_reference_line,
)
image_files = extract_multimodal_image_files(request.params)
@@ -473,6 +483,15 @@ def _prepare_multimodal_image_inputs(
updated = dict(inputs)
updated["_multimodal_image_files"] = image_files
+
+ # 把引用行写进用户 query:MultimodalImageRail 注入时靠它定位「本次要物化哪些图」。
+ # 「拆分第二刀」把这层逻辑精简掉了,导致模型看不到图片、只能 fallback 去 read_file。
+ query = updated.get("query")
+ if isinstance(query, str):
+ lines = [build_image_reference_line(f, i) for i, f in enumerate(image_files, start=1)]
+ if lines:
+ updated["query"] = (query + "\n" + "\n".join(lines)).strip()
+
logger.info(
"[JiuWenSwarmDeepAdapter] Prepared %d image attachment(s) "
"for Core multimodal context-window injection",
@@ -481,92 +500,22 @@ def _prepare_multimodal_image_inputs(
return updated
-def _prepare_react_image_tool_prompt(
- request: AgentRequest,
- inputs: dict[str, Any],
- *,
- enable_read_image_multimodal: bool,
-) -> dict[str, Any]:
- """Add image file paths to the ReAct prompt when native image input is off."""
- if enable_read_image_multimodal:
- return inputs
-
- query = inputs.get("query")
- if not isinstance(query, str) or "jiuwenswarm_image_tool_context" in query:
- return inputs
-
- from jiuwenswarm.agents.harness.common.prompt.user_prompt_builder import (
- extract_multimodal_image_files,
- )
-
- image_files = inputs.get("_multimodal_image_files")
- if not isinstance(image_files, list) or not image_files:
- image_files = extract_multimodal_image_files(request.params)
- if not image_files:
- return inputs
-
- params = request.params if isinstance(request.params, dict) else {}
- raw_question = params.get("query")
- if not isinstance(raw_question, str) or not raw_question.strip():
- raw_question = params.get("content")
- question = raw_question.strip() if isinstance(raw_question, str) else ""
- first_path = str(image_files[0].get("path") or "").strip()
- if not first_path:
- return inputs
-
- media_items = []
- for image_file in image_files:
- path = str(image_file.get("path") or "").strip()
- if not path:
- continue
- media_items.append(
- {
- "type": "image",
- "filename": image_file.get("filename") or Path(path).name,
- "mediaPath": path,
- "mimeType": image_file.get("mime_type") or image_file.get("mimeType"),
- }
- )
- if not media_items:
- return inputs
-
- tool_context = {
- "marker": "jiuwenswarm_image_tool_context",
- "mediaPath": first_path,
- "mediaItems": media_items,
- "question": question,
- "toolHint": (
- "当前主模型未启用原生图片输入。如果需要理解图片内容,请调用图片理解工具;"
- "优先使用 image_reading(local_url=mediaPath, prompt=question),"
- "或使用 visual_question_answering(image_path_or_url=mediaPath, question=question)。"
- ),
- }
-
- updated = dict(inputs)
- updated.pop("_multimodal_image_files", None)
- updated["query"] = (
- query
- + "\n\n图片附件上下文(供 ReAct 选择图片理解工具使用):\n"
- + json.dumps(tool_context, ensure_ascii=False)
- )
- return updated
-
-
def _build_image_tool_fallback_notice(
request: AgentRequest,
*,
enable_read_image_multimodal: bool,
model: Any | None,
+ query: str | None = None,
) -> dict[str, Any] | None:
if enable_read_image_multimodal:
return None
- from jiuwenswarm.agents.harness.common.prompt.user_prompt_builder import (
- extract_multimodal_image_files,
+ from jiuwenswarm.agents.harness.common.multimodal import (
+ parse_image_references,
)
- image_files = extract_multimodal_image_files(request.params)
- if not image_files:
+ image_references = parse_image_references(query) if isinstance(query, str) else []
+ if not image_references:
return None
model_config = getattr(model, "model_config", None)
@@ -580,27 +529,39 @@ def _build_image_tool_fallback_notice(
"content": content,
"request_id": request.request_id,
"session_id": request.session_id,
- "image_count": len(image_files),
+ "image_count": len(image_references),
}
if model_name:
notice["model_name"] = model_name
return notice
-def _resolve_enable_read_image_multimodal(config: dict[str, Any]) -> bool:
- configured = config.get("enable_read_image_multimodal")
- if isinstance(configured, bool):
- return configured
- return DEFAULT_ENABLE_READ_IMAGE_MULTIMODAL
+def _resolve_enable_read_image_multimodal(config: dict[str, Any], model: Any | None = None) -> bool:
+ """看图能力只由逐模型 modalities 是否含 ``image`` 决定,未声明即不支持(S_22 N2)。"""
+
+ if model is None:
+ return False
+ from jiuwenswarm.agents.harness.common.tools.model_capabilities import (
+ supports_native_image,
+ )
+
+ return supports_native_image(getattr(model, "modalities", None))
def _build_multimodal_image_rail(
enable_image_multimodal: bool | None = None,
+ *,
+ max_total_bytes: int = 0,
+ max_visual_tokens: int = 0,
+ max_count: int = 0,
) -> MultimodalImageRail | None:
"""Build MultimodalImageRail."""
try:
multimodal_image_rail = MultimodalImageRail(
enable_image_multimodal=enable_image_multimodal,
+ max_total_bytes=max_total_bytes,
+ max_visual_tokens=max_visual_tokens,
+ max_count=max_count,
)
logger.info("[JiuWenSwarmDeepAdapter] MultimodalImageRail create success")
except Exception as exc:
diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_code.py b/jiuwenswarm/server/runtime/agent_adapter/interface_code.py
index 6dd114581c..105d108d99 100644
--- a/jiuwenswarm/server/runtime/agent_adapter/interface_code.py
+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_code.py
@@ -55,6 +55,7 @@ from jiuwenswarm.server.runtime.agent_adapter.interface_deep import (
_CRON_TOOL_CHANNEL_ID,
_RailBuildInfo,
_agent_ras_kwargs_from_config,
+ _build_multimodal_image_rail,
_deep_agent_kv_cache_affinity_config,
_optional_enable_subagent_runtime,
_resolve_instance_config_base,
@@ -98,7 +99,6 @@ from jiuwenswarm.common.coding_memory_paths import (
)
from jiuwenswarm.server.runtime.agent_adapter.code_agent_rail import CodeAgentRail
from jiuwenswarm.common.utils import (
- DEFAULT_ENABLE_READ_IMAGE_MULTIMODAL,
get_agent_workspace_dir,
get_default_project_session_workspace_dir,
)
@@ -642,7 +642,7 @@ class JiuwenSwarmCodeAdapter(JiuWenSwarmDeepAdapter):
workspace=workspace,
sys_operation=sys_operation,
language=self._resolve_runtime_language(),
- enable_read_image_multimodal=DEFAULT_ENABLE_READ_IMAGE_MULTIMODAL,
+ enable_read_image_multimodal=self._resolve_enable_read_image_multimodal(config, model),
kv_cache_affinity_config=_deep_agent_kv_cache_affinity_config(config, model),
auto_create_workspace=is_enterprise(),
completion_timeout=config.get("completion_timeout", 3600.0),
@@ -726,6 +726,17 @@ class JiuwenSwarmCodeAdapter(JiuWenSwarmDeepAdapter):
_RailBuildInfo("_request_summary_rail", self._build_request_summary_rail),
_RailBuildInfo("_runtime_prompt_rail", self._build_runtime_prompt_rail),
_RailBuildInfo("_response_prompt_rail", self._build_response_prompt_rail),
+ _RailBuildInfo(
+ "_multimodal_image_rail",
+ _build_multimodal_image_rail,
+ {
+ # 与 DeepAdapter 对齐:请求时回退到 deep_config.enable_read_image_multimodal。
+ "enable_image_multimodal": None,
+ "max_total_bytes": config.get("multimodal_image_budget"),
+ "max_visual_tokens": config.get("multimodal_image_token_budget"),
+ "max_count": config.get("multimodal_image_max_count"),
+ },
+ ),
_RailBuildInfo("_skill_retrieval_prompt_rail", self._build_skill_retrieval_prompt_rail),
_RailBuildInfo("_stream_event_rail", self._build_stream_event_rail),
_RailBuildInfo(
diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
index b87a7928ca..69aaf380b4 100644
--- a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
@@ -259,7 +259,6 @@ from jiuwenswarm.server.runtime.agent_adapter.deep.model_factory import (
_model_reload_fingerprint,
_models_config_fingerprint,
_prepare_multimodal_image_inputs,
- _prepare_react_image_tool_prompt,
_resolve_enable_read_image_multimodal,
_stable_reload_fingerprint,
_system_prompt_reload_fingerprint,
@@ -907,7 +906,6 @@ from jiuwenswarm.server.runtime.skill.skill_prebuilt import (
parse_agent_skill_prebuilt,
)
from jiuwenswarm.common.utils import (
- DEFAULT_ENABLE_READ_IMAGE_MULTIMODAL,
fill_template_defaults,
get_agent_evolution_trajectories_dir,
get_agent_root_dir,
@@ -4721,6 +4719,7 @@ class JiuWenSwarmDeepAdapter:
model = _build_model_from_entry(
mcc,
entry.get("model_config_obj") or {},
+ entry.get("modalities"),
)
except Exception as exc:
logger.warning(
@@ -4828,7 +4827,13 @@ class JiuWenSwarmDeepAdapter:
or {}
)
try:
- model = _build_model_from_entry(mcc, mco)
+ model = _build_model_from_entry(
+ mcc,
+ mco,
+ modalities=default_model_config.get("modalities")
+ if default_model_config.get("modalities") is not None
+ else react_config.get("modalities"),
+ )
self._model_cache[model_name] = model
model_ref = build_model_identity_reference(model_name, mcc)
self._model_identity_to_keys.setdefault(model_ref, []).append(model_name)
@@ -4919,7 +4924,7 @@ class JiuWenSwarmDeepAdapter:
mcc = entry.get("model_client_config") or {}
model_name = str(mcc.get("model_name") or "")
try:
- model = _build_model_from_entry(mcc, entry.get("model_config_obj") or {})
+ model = _build_model_from_entry(mcc, entry.get("model_config_obj") or {}, entry.get("modalities"))
except Exception as exc: # noqa: BLE001
logger.warning(
"[JiuWenSwarmDeepAdapter] 保留重载前模型失败 %s: %s", model_name, exc
@@ -5113,10 +5118,43 @@ class JiuWenSwarmDeepAdapter:
return model
+ @staticmethod
+ def _resolve_enable_read_image_multimodal(
+ config: dict[str, Any], model: Any | None = None
+ ) -> bool:
+ """薄封装:唯一真源在 ``deep.model_factory``,保留类方法供子类/测试调用。"""
+ return _resolve_enable_read_image_multimodal(config, model)
+
def _native_image_input_enabled(self, config: dict[str, Any], model: Any | None) -> bool:
- # read_file 默认不读取图片:不把图片字节内联进主模型对话,改走 image_reading / VQA 工具。
- # 仅当 config.yaml 显式设置 enable_read_image_multimodal 时遵从配置;模型名启发式已移除。
- return _resolve_enable_read_image_multimodal(config)
+ # 看图能力只由逐模型 modalities 是否含 image 决定(未声明即不支持)。
+ return _resolve_enable_read_image_multimodal(config, model)
+
+ @staticmethod
+ def _validate_checkpointer_consistency(
+ freeze_checkpointer: Any,
+ recover_checkpointer: Any,
+ ) -> None:
+ """冻结侧(实例级)与恢复侧(session/进程默认)checkpointer 不一致时告警。
+
+ 纯检查 + 日志,不改变任何赋值/绑定/创建逻辑。实例相同或底层 ``_kv_store``
+ 相同视为一致,不告警。
+ """
+ if freeze_checkpointer is None or recover_checkpointer is None:
+ return
+ if freeze_checkpointer is recover_checkpointer:
+ return
+ freeze_kv = getattr(freeze_checkpointer, "_kv_store", None)
+ recover_kv = getattr(recover_checkpointer, "_kv_store", None)
+ if freeze_kv is None or recover_kv is None:
+ return
+ if freeze_kv is recover_kv:
+ return
+ logger.warning(
+ "[JiuWenSwarmDeepAdapter] checkpointer consistency mismatch on "
+ "freeze/recover: freeze_kv=%r recover_kv=%r",
+ freeze_kv,
+ recover_kv,
+ )
def _apply_model_to_react_agent(self, model: Model) -> None:
@@ -5179,6 +5217,21 @@ class JiuWenSwarmDeepAdapter:
"[JiuWenSwarmDeepAdapter] failed to sync deep_config.model",
exc_info=True,
)
+ # 主模型切换后必须同步看图能力位:否则文本模型会继承上一个视觉模型的
+ # enable_read_image_multimodal=True,导致 rail 误注入 + 摘掉 VQA。
+ # 与自动路由(ModelRoutingRail.before_invoke 直接 set_llm)共用同一 helper
+ # 收敛,避免换模入口漏同步。
+ try:
+ from jiuwenswarm.agents.harness.common.rails.model_routing.image_capability_sync import (
+ sync_agent_image_capability,
+ )
+
+ sync_agent_image_capability(self._instance, model)
+ except Exception:
+ logger.debug(
+ "[JiuWenSwarmDeepAdapter] failed to sync deep_config.enable_read_image_multimodal",
+ exc_info=True,
+ )
def restore_skill_turbo_model_from_resume_ctx(
self, resume_ctx: dict[str, Any]
@@ -7873,7 +7926,11 @@ class JiuWenSwarmDeepAdapter:
"_multimodal_image_rail",
_build_multimodal_image_rail,
{
- "enable_image_multimodal": _resolve_enable_read_image_multimodal(config),
+ # 请求时回退到 deep_config.enable_read_image_multimodal(由模型能力解析写入)。
+ "enable_image_multimodal": None,
+ "max_total_bytes": config.get("multimodal_image_budget"),
+ "max_visual_tokens": config.get("multimodal_image_token_budget"),
+ "max_count": config.get("multimodal_image_max_count"),
},
),
_RailBuildInfo(
@@ -8152,7 +8209,7 @@ class JiuWenSwarmDeepAdapter:
rails=rails,
vision_model_config=self._vision_model_config,
audio_model_config=self._audio_model_config,
- enable_read_image_multimodal=_resolve_enable_read_image_multimodal(config),
+ enable_read_image_multimodal=_resolve_enable_read_image_multimodal(config, model),
completion_timeout=config.get("completion_timeout", 21600.0),
**_optional_enable_subagent_runtime(
self._resolve_enable_subagent_runtime(config_base),
@@ -9116,7 +9173,7 @@ class JiuWenSwarmDeepAdapter:
kv_cache_affinity_config=_deep_agent_kv_cache_affinity_config(config, model),
vision_model_config=self._vision_model_config,
audio_model_config=self._audio_model_config,
- enable_read_image_multimodal=_resolve_enable_read_image_multimodal(config),
+ enable_read_image_multimodal=_resolve_enable_read_image_multimodal(config, model),
enable_llm_retry_rail=((config_base.get("execution_guard") or {}).get("llm_retry_rail") or {}).get(
"enabled", False
),
@@ -10819,6 +10876,10 @@ class JiuWenSwarmDeepAdapter:
return
if not _cron_session_has_context(cron_inner):
try:
+ self._validate_checkpointer_consistency(
+ self._get_adapter_checkpointer(),
+ _cron_execution_checkpointer(cron_inner),
+ )
await _cron_execution_checkpointer(cron_inner).pre_agent_execute(
cron_inner, None
)
@@ -11502,6 +11563,13 @@ class JiuWenSwarmDeepAdapter:
if context_engine is not None and freeze_session is not None:
actual_session = getattr(freeze_session, "_parent", freeze_session) or freeze_session
await context_engine.save_contexts(actual_session)
+ recover_inner = getattr(
+ getattr(self._instance, "_interaction_session", None), "_inner", None
+ )
+ self._validate_checkpointer_consistency(
+ self._get_adapter_checkpointer(),
+ _cron_execution_checkpointer(recover_inner),
+ )
await post_agent_execute_for_session(freeze_session, self._checkpointer)
except Exception as exc:
logger.warning(
@@ -15390,18 +15458,15 @@ class JiuWenSwarmDeepAdapter:
self._config_cache,
resolved_model,
)
- inputs = _prepare_react_image_tool_prompt(
- request,
- inputs,
- enable_read_image_multimodal=enable_read_image_multimodal,
- )
- from jiuwenswarm.agents.harness.common.prompt.user_prompt_builder import (
+ from jiuwenswarm.agents.harness.common.multimodal import (
set_current_multimodal_image_files,
+ store_current_multimodal_image_files_on_agent,
)
- image_files_token = set_current_multimodal_image_files(
- inputs.pop("_multimodal_image_files", []) or []
- )
+ image_files = inputs.pop("_multimodal_image_files", []) or []
+ image_files_token = set_current_multimodal_image_files(image_files)
+ # ContextVar 不跨「请求协程 → agent 任务」边界,镜像到 DeepAgent 实例跨边界读。
+ store_current_multimodal_image_files_on_agent(self._instance, image_files)
# Sync single-agent / coding-agent observability with current
# config before running, and open a root span so OtelCallbackHandler
# has a parent for LLM/tool spans (see streaming path for details).
@@ -15544,7 +15609,7 @@ class JiuWenSwarmDeepAdapter:
("run_span", lambda: close_agent_run_span(_run_span, session_id=session_id))
)
if image_files_token is not None:
- from jiuwenswarm.agents.harness.common.prompt.user_prompt_builder import (
+ from jiuwenswarm.agents.harness.common.multimodal import (
reset_current_multimodal_image_files,
)
cleanup_steps.append(
@@ -16004,6 +16069,7 @@ class JiuWenSwarmDeepAdapter:
mode=mode,
)
perf_summary_status = "ok"
+ team_image_files_token = None
try:
resolved_model = self._resolve_model_for_request(request)
self._apply_model_to_react_agent(resolved_model)
@@ -16012,11 +16078,27 @@ class JiuWenSwarmDeepAdapter:
self._config_cache,
resolved_model,
)
- inputs = _prepare_react_image_tool_prompt(
+ image_tool_fallback_notice = _build_image_tool_fallback_notice(
request,
- inputs,
enable_read_image_multimodal=enable_read_image_multimodal,
+ model=resolved_model,
+ query=inputs.get("query") if isinstance(inputs.get("query"), str) else None,
)
+ from jiuwenswarm.agents.harness.common.multimodal import (
+ set_current_multimodal_image_files,
+ store_current_multimodal_image_files_on_agent,
+ )
+
+ image_files = inputs.pop("_multimodal_image_files", []) or []
+ team_image_files_token = set_current_multimodal_image_files(image_files)
+ store_current_multimodal_image_files_on_agent(self._instance, image_files)
+ if image_tool_fallback_notice is not None:
+ yield AgentResponseChunk(
+ request_id=rid,
+ channel_id=cid,
+ payload=image_tool_fallback_notice,
+ is_complete=False,
+ )
resolved_language = self._resolve_runtime_language()
resolved_channel = str(cid or self._resolve_prompt_channel(session_id) or "web").strip() or "web"
if self._runtime_prompt_rail:
@@ -16084,6 +16166,12 @@ class JiuWenSwarmDeepAdapter:
_LLM_TRACE_REQUEST_ID.reset(token_trace_rid)
_LLM_TRACE_ITERATION.reset(token_trace_iter)
_LLM_TRACE_MODEL_NAME.reset(token_trace_model)
+ if team_image_files_token is not None:
+ from jiuwenswarm.agents.harness.common.multimodal import (
+ reset_current_multimodal_image_files,
+ )
+
+ reset_current_multimodal_image_files(team_image_files_token)
return
# Auto-Harness 模式处理
@@ -16638,11 +16726,7 @@ class JiuWenSwarmDeepAdapter:
request,
enable_read_image_multimodal=enable_read_image_multimodal,
model=resolved_model,
- )
- inputs = _prepare_react_image_tool_prompt(
- request,
- inputs,
- enable_read_image_multimodal=enable_read_image_multimodal,
+ query=inputs.get("query") if isinstance(inputs.get("query"), str) else None,
)
if image_tool_fallback_notice is not None:
yield AgentResponseChunk(
@@ -16651,13 +16735,15 @@ class JiuWenSwarmDeepAdapter:
payload=image_tool_fallback_notice,
is_complete=False,
)
- from jiuwenswarm.agents.harness.common.prompt.user_prompt_builder import (
+ from jiuwenswarm.agents.harness.common.multimodal import (
set_current_multimodal_image_files,
+ store_current_multimodal_image_files_on_agent,
)
- image_files_token = set_current_multimodal_image_files(
- inputs.pop("_multimodal_image_files", []) or []
- )
+ image_files = inputs.pop("_multimodal_image_files", []) or []
+ image_files_token = set_current_multimodal_image_files(image_files)
+ # ContextVar 不跨「请求协程 → agent 任务」边界,镜像到 DeepAgent 实例跨边界读。
+ store_current_multimodal_image_files_on_agent(self._instance, image_files)
# Resolve debug-trace settings early: its otel_enabled drives the
# OTel force-enable below. Best-effort (config read never raises).
from jiuwenswarm.server.runtime.debug_trace.config import (
@@ -17642,7 +17728,7 @@ class JiuWenSwarmDeepAdapter:
)
)
if image_files_token is not None:
- from jiuwenswarm.agents.harness.common.prompt.user_prompt_builder import (
+ from jiuwenswarm.agents.harness.common.multimodal import (
reset_current_multimodal_image_files,
)
cleanup_steps.append(
diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_flash.py b/jiuwenswarm/server/runtime/agent_adapter/interface_flash.py
index 654ba898b7..c096c9ad8a 100644
--- a/jiuwenswarm/server/runtime/agent_adapter/interface_flash.py
+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_flash.py
@@ -243,6 +243,9 @@ class JiuwenSwarmFlashAdapter(JiuWenSwarmDeepAdapter):
"_runtime_prompt_rail",
"_response_prompt_rail",
"_stream_event_rail",
+ # 上传图片进主模型:MultimodalImageRail 把引用行物化为像素并写入历史;
+ # 漏掉它 flash 只能靠 read_file 现读上传图。
+ "_multimodal_image_rail",
# deepresearch_execute 依赖此 rail 绑定执行上下文并桥接原生 HITL。
"_deepresearch_execution_rail",
diff --git a/tests/test_single_agent_model_identity.py b/tests/test_single_agent_model_identity.py
index 7cbf7f6c60..41770cf669 100644
--- a/tests/test_single_agent_model_identity.py
+++ b/tests/test_single_agent_model_identity.py
@@ -98,8 +98,14 @@ def test_legacy_cache_build_populates_identity_index(monkeypatch):
adapter = object.__new__(JiuWenSwarmDeepAdapter)
adapter._model_cache = {}
adapter._model_identity_to_keys = {}
- monkeypatch.setattr(
- "jiuwenswarm.server.runtime.agent_adapter.interface_deep._build_model_from_entry", lambda mcc, mco: model)
+ capability_kwargs: dict = {}
+
+ def _build(mcc, mco, **kwargs):
+ capability_kwargs.update(kwargs)
+ return model
+
+ # builder 已从类方法提升到 deep.model_factory,interface_deep 命名空间持有该符号
+ monkeypatch.setattr(interface_deep, "_build_model_from_entry", _build)
adapter._build_model_cache_legacy(
{
@@ -111,11 +117,15 @@ def test_legacy_cache_build_populates_identity_index(monkeypatch):
"client_provider": "OpenAI",
},
"model_config_obj": {},
+ # legacy 段也必须把图片能力声明透传给 Model,否则回退路径丢能力
+ "modalities": ["text"],
}
}
}
)
+ assert capability_kwargs == {"modalities": ["text"]}
+
ref = build_model_identity_reference(
"glm-5.3",
{
@@ -135,7 +145,7 @@ def _registry_adapter():
adapter._model_identity_to_keys, adapter._model_identity_owners = {}, {}
adapter._model_entry_by_ref = {}
adapter._tier_model_cache = {}
- interface_deep._build_model_from_entry = lambda mcc, mco: SimpleNamespace(
+ interface_deep._build_model_from_entry = lambda mcc, mco, *args, **kwargs: SimpleNamespace(
model_client_config=SimpleNamespace(
api_key=mcc.get("api_key"),
custom_headers=dict(mcc.get("custom_headers") or {}),
diff --git a/tests/unit_tests/agents/harness/common/multimodal/test_image_reference.py b/tests/unit_tests/agents/harness/common/multimodal/test_image_reference.py
new file mode 100644
index 0000000000..e339128519
--- /dev/null
+++ b/tests/unit_tests/agents/harness/common/multimodal/test_image_reference.py
@@ -0,0 +1,137 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""图片引用行构造/解析 + ``extract_multimodal_image_files`` 的 files 形态归一。"""
+
+from __future__ import annotations
+
+import pytest
+
+from jiuwenswarm.agents.harness.common.multimodal.image_reference import (
+ build_image_reference_line,
+ extract_multimodal_image_files,
+ parse_image_references,
+)
+
+
+def _image(path: str = "a.png", **overrides):
+ item = {"type": "image", "filename": "a.png", "path": path, "mime_type": "image/png"}
+ item.update(overrides)
+ return item
+
+
+# ---------------------------------------------------------------------------
+# 引用行 build → parse 往返(S_22 数据结构契约)
+# ---------------------------------------------------------------------------
+
+# 引用行是 S_22「数据结构」里的模型可见契约;size 段可缺(旧历史 / 元数据缺失),
+# 用 build→parse 往返覆盖带 size / 不带 size 两档,格式只在这张表里钉一次。
+# 第三档钉住「上传文件名含空格」:Windows 截图名、含空格的下载目录都很常见。
+_ROUND_TRIP = [
+ (
+ {"path": "/a/home.png", "filename": "home.png", "mime_type": "image/png", "size_bytes": 614400},
+ 1,
+ "[image #1] path=/a/home.png filename=home.png mime=image/png size=614400",
+ ),
+ (
+ {"path": "/a/home.png", "filename": "home.png", "mime_type": "image/png"},
+ 2,
+ "[image #2] path=/a/home.png filename=home.png mime=image/png",
+ ),
+ (
+ {
+ "path": "/a/team docs/我的 图片.png",
+ "filename": "screen shot 2026.png",
+ "mime_type": "image/png",
+ "size_bytes": 2048,
+ },
+ 3,
+ "[image #3] path=/a/team docs/我的 图片.png filename=screen shot 2026.png "
+ "mime=image/png size=2048",
+ ),
+]
+
+
+ ("image_file", "index", "expected_line"),
+ _ROUND_TRIP,
+ ids=["with-size", "without-size", "paths-with-spaces"],
+)
+def test_reference_line_build_parse_round_trip(image_file, index, expected_line):
+ line = build_image_reference_line(image_file, index)
+ assert line == expected_line
+ assert parse_image_references(line) == [{"index": index, **image_file}]
+
+
+def test_parse_reference_lines_from_multiline_text():
+ text = (
+ "对比一下\n"
+ "[image #1] path=/a/home.png filename=home.png mime=image/png size=614400\n"
+ "[image #2] path=/a/d.png filename=d.png mime=image/png size=409600"
+ )
+ refs = parse_image_references(text)
+ assert [r["index"] for r in refs] == [1, 2]
+ assert refs[0]["path"] == "/a/home.png"
+
+
+def test_parse_reference_line_with_spaces_in_path_and_filename():
+ """含空格的路径 / 文件名不得整行解析失败(图片静默丢失)。"""
+
+ text = (
+ "[image #1] path=/data/upload/team docs/屏幕 截图.png "
+ "filename=屏幕 截图.png mime=image/png size=4096"
+ )
+ refs = parse_image_references(text)
+ assert refs == [
+ {
+ "index": 1,
+ "path": "/data/upload/team docs/屏幕 截图.png",
+ "filename": "屏幕 截图.png",
+ "mime_type": "image/png",
+ "size_bytes": 4096,
+ }
+ ]
+
+
+def test_parse_ignores_non_reference_text():
+ # 正文里的普通路径不得被当成图片引用(过度解析会把用户提问切成假引用)。
+ assert parse_image_references("普通文本 /data/image/x.png") == []
+
+
+# ---------------------------------------------------------------------------
+# extract_multimodal_image_files 的 files 形态归一
+# ---------------------------------------------------------------------------
+
+
+def test_extract_from_files_list() -> None:
+ """relay 通道的 files 是 list 形态,必须被识别(否则原生多模态在 relay 主链路失效)。"""
+
+ files = [_image("/tmp/a.png"), _image("/tmp/b.png")]
+ result = extract_multimodal_image_files({"files": files})
+ assert [r["path"] for r in result] == ["/tmp/a.png", "/tmp/b.png"]
+
+
+def test_extract_from_files_dict() -> None:
+ """web 通道的 files 是 dict 信封:uploaded_images 列表被识别。"""
+
+ files = {"uploaded_images": [_image("/tmp/a.png")]}
+ result = extract_multimodal_image_files({"files": files})
+ assert [r["path"] for r in result] == ["/tmp/a.png"]
+
+
+def test_extract_from_media_items() -> None:
+ """media_items 列表形态依旧生效(web normalize 后的等价入口)。"""
+
+ result = extract_multimodal_image_files({"media_items": [_image("/tmp/a.png")]})
+ assert [r["path"] for r in result] == ["/tmp/a.png"]
+
+
+def test_dedup_and_invalid_filtered() -> None:
+ """重复路径去重;非 image 项被 _normalize_image_file 过滤。"""
+
+ files = [
+ _image("/tmp/a.png"),
+ _image("/tmp/a.png"),
+ {"type": "file", "path": "/tmp/x.pdf", "mime_type": "application/pdf"},
+ ]
+ result = extract_multimodal_image_files({"files": files})
+ assert [r["path"] for r in result] == ["/tmp/a.png"]
diff --git a/tests/unit_tests/agents/harness/common/rails/test_image_capability_sync.py b/tests/unit_tests/agents/harness/common/rails/test_image_capability_sync.py
new file mode 100644
index 0000000000..75e1550407
--- /dev/null
+++ b/tests/unit_tests/agents/harness/common/rails/test_image_capability_sync.py
@@ -0,0 +1,48 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""换模后看图能力位同步(interface_deep 与自动路由共用入口)。"""
+
+from __future__ import annotations
+
+from types import SimpleNamespace
+
+from jiuwenswarm.agents.harness.common.rails.model_routing.image_capability_sync import (
+ sync_agent_image_capability,
+)
+
+
+def _model(modalities) -> SimpleNamespace:
+ return SimpleNamespace(modalities=modalities)
+
+
+def _host(enabled: bool) -> SimpleNamespace:
+ return SimpleNamespace(deep_config=SimpleNamespace(enable_read_image_multimodal=enabled))
+
+
+def test_sync_sets_false_when_model_declares_no_image_support() -> None:
+ """入口视觉模型切到文本模型后,能力位必须回落 False(否则 rail 误注入像素)。"""
+
+ host = _host(enabled=True)
+
+ assert sync_agent_image_capability(host, _model(["text"])) is True
+ assert host.deep_config.enable_read_image_multimodal is False
+
+
+def test_sync_keeps_true_for_vision_model() -> None:
+ host = _host(enabled=False)
+
+ assert sync_agent_image_capability(host, _model(["text", "image"])) is True
+ assert host.deep_config.enable_read_image_multimodal is True
+
+
+def test_sync_treats_unset_support_as_unsupported() -> None:
+ """自动路由构造的新模型未携带 modalities 时按不支持处理(对文本目标正确)。"""
+
+ host = _host(enabled=True)
+
+ assert sync_agent_image_capability(host, _model(None)) is True
+ assert host.deep_config.enable_read_image_multimodal is False
+
+
+def test_sync_noop_without_deep_config() -> None:
+ assert sync_agent_image_capability(SimpleNamespace(), _model(["text", "image"])) is False
diff --git a/tests/unit_tests/agents/harness/common/rails/test_model_routing_capability.py b/tests/unit_tests/agents/harness/common/rails/test_model_routing_capability.py
new file mode 100644
index 0000000000..f5722cd8bf
--- /dev/null
+++ b/tests/unit_tests/agents/harness/common/rails/test_model_routing_capability.py
@@ -0,0 +1,51 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""_build_cap_from_entry 的能力声明(modalities)透传。"""
+
+from __future__ import annotations
+
+from types import SimpleNamespace
+
+from jiuwenswarm.agents.harness.common.rails.model_routing.capability import (
+ _build_cap_from_entry,
+)
+
+
+def test_build_cap_passes_modalities_to_three_arg_builder() -> None:
+ """视觉候选经能力表构建后,其 Model 必须携带 modalities(含 image)。
+
+ 否则 sync_agent_image_capability 会把它判成"不支持",视觉候选经自动路由后
+ 能力位被写成 False(CR-17 的镜像缺陷)。
+ """
+
+ captured = {}
+
+ def builder(mcc, mco, modalities=None):
+ captured["modalities"] = modalities
+ return SimpleNamespace(modalities=modalities)
+
+ entry = {
+ "model_client_config": {"model_name": "vision-x", "api_base": "https://v"},
+ "model_config_obj": {},
+ "modalities": ["text", "image"],
+ }
+ cap = _build_cap_from_entry(entry, builder)
+
+ assert captured["modalities"] == ["text", "image"]
+ assert cap.model.modalities == ["text", "image"]
+
+
+def test_build_cap_falls_back_to_two_arg_builder() -> None:
+ """2 参旧 builder(无能力位参数)不应因三参调用而崩:TypeError 兜底退回 2 参。"""
+
+ def builder(mcc, mco):
+ return SimpleNamespace()
+
+ entry = {
+ "model_client_config": {"model_name": "glm-5.3", "api_base": "https://v"},
+ "model_config_obj": {},
+ "modalities": ["text"],
+ }
+ cap = _build_cap_from_entry(entry, builder)
+
+ assert cap.model is not None
diff --git a/tests/unit_tests/agents/harness/common/rails/test_multimodal_image_rail_final_window.py b/tests/unit_tests/agents/harness/common/rails/test_multimodal_image_rail_final_window.py
new file mode 100644
index 0000000000..98921ddd2e
--- /dev/null
+++ b/tests/unit_tests/agents/harness/common/rails/test_multimodal_image_rail_final_window.py
@@ -0,0 +1,84 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""MultimodalImageRail 在最终窗口确定后重算图片负载(压缩后护栏不再误拦)。
+
+回归焦点:``before_model_call`` 在 ``get_context_window`` 压缩**之前**按完整历史
+写入 ``images_sent`` / ``provided_paths``;若随后压缩把含图历史搬走,缓存仍宣称
+"模型已收到图",read_file 会被重复读护栏拒绝。``after_model_call`` 按
+``ctx.inputs.messages``(最终窗口)重算,覆盖旧快照。
+"""
+
+from __future__ import annotations
+
+import asyncio
+from types import SimpleNamespace
+
+from jiuwenswarm.agents.harness.common.rails.multimodal_image_rail import (
+ MultimodalImageRail,
+)
+from jiuwenswarm.agents.harness.common.rails.multimodal_image_state import (
+ mark_native_images_sent,
+ mark_provided_image_paths,
+ native_images_sent,
+ provided_image_paths,
+)
+
+
+def _ctx(messages: list) -> SimpleNamespace:
+ return SimpleNamespace(inputs=SimpleNamespace(messages=messages), extra={}, agent=None)
+
+
+def _image_block_message() -> dict:
+ return {
+ "role": "user",
+ "content": [
+ {"type": "text", "text": "[image #1] path=/tmp/a.png"},
+ {"type": "image_url", "image_url": {"url": "data:image/png;base64,AAAA"}},
+ ],
+ }
+
+
+def test_after_model_call_resets_to_zero_when_compaction_dropped_images() -> None:
+ """压缩后最终窗口无图:张数与已提供路径必须归零,否则 read_file 被误拒。"""
+
+ rail = MultimodalImageRail(enable_image_multimodal=True)
+ ctx = _ctx(messages=[])
+
+ # 模拟压缩前 before_model_call 记录"1 张图 + 已提供路径 A"。
+ mark_native_images_sent(ctx, None, 1)
+ mark_provided_image_paths(ctx, ["/tmp/a.png"])
+
+ asyncio.run(rail.after_model_call(ctx))
+
+ assert native_images_sent(ctx=ctx) == 0
+ assert provided_image_paths(ctx=ctx) == []
+
+
+def test_after_model_call_keeps_count_from_final_window() -> None:
+ """最终窗口仍带像素时按真实块数重算,不直写为 0。"""
+
+ rail = MultimodalImageRail(enable_image_multimodal=True)
+ ctx = _ctx(messages=[_image_block_message()])
+
+ mark_native_images_sent(ctx, None, 0)
+ mark_provided_image_paths(ctx, [])
+
+ asyncio.run(rail.after_model_call(ctx))
+
+ assert native_images_sent(ctx=ctx) == 1
+
+
+def test_after_model_call_skips_when_disabled() -> None:
+ """非原生分支不物化像素,重算不覆盖 before_model_call 已写的空快照。"""
+
+ rail = MultimodalImageRail(enable_image_multimodal=False)
+ ctx = _ctx(messages=[_image_block_message()])
+
+ # 非原生时 before_model_call 写 0 / 空;after_model_call 应保持不动。
+ mark_native_images_sent(ctx, None, 0)
+ mark_provided_image_paths(ctx, [])
+
+ asyncio.run(rail.after_model_call(ctx))
+
+ assert native_images_sent(ctx=ctx) == 0
+ assert provided_image_paths(ctx=ctx) == []
diff --git a/tests/unit_tests/agents/harness/common/rails/test_native_image_tool_wiring.py b/tests/unit_tests/agents/harness/common/rails/test_native_image_tool_wiring.py
new file mode 100644
index 0000000000..834cff6183
--- /dev/null
+++ b/tests/unit_tests/agents/harness/common/rails/test_native_image_tool_wiring.py
@@ -0,0 +1,159 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""原生图片输入([[S_22]])读图工具能力接线。
+
+回归焦点:``read_file`` 的内联像素判定跟随主模型切换的前提是 core 提供
+``image_multimodal_resolver``(调用时求值)。锁定 core(``uv.lock`` 的 8215f2c)
+只有静态 ``enable_image_multimodal: bool``,构造时求值后即冻结——这是该版本的固有
+语义,不是本模块的缺陷;core 合入 resolver 并刷新 uv.lock 后自动获得热切换。
+
+deep 走 ``FlashBashSysOperationRail``(替换 stock ReadFileTool)、flash 走
+``SlimSysOperationRail``(自建 FlashReadFileTool),新 core 上两条路径都必须把
+resolver 透传下去;锁定 core 上退回构造时求值。
+"""
+
+from __future__ import annotations
+
+import pytest
+from types import SimpleNamespace
+
+from jiuwenswarm.agents.harness.common import read_file_image_support as support
+from jiuwenswarm.agents.harness.common.read_file_image_support import (
+ build_read_file_image_kwargs,
+ read_file_image_multimodal_enabled,
+)
+from jiuwenswarm.agents.harness.flash.rails.slim_sys_operation_rail import (
+ SlimSysOperationRail,
+)
+from jiuwenswarm.agents.harness.flash.tools.flash_bash_tool import (
+ FlashBashSysOperationRail,
+)
+from jiuwenswarm.agents.harness.flash.tools.flash_read_tool import FlashReadFileTool
+
+
+class _FakeAbilityManager:
+ def __init__(self) -> None:
+ self.tools: dict[str, object] = {}
+
+ def add_ability(self, card, tool) -> None:
+ self.tools[getattr(card, "name", str(id(tool)))] = tool
+
+ def remove_ability(self, name: str) -> None:
+ self.tools.pop(name, None)
+
+
+def _fake_agent(enable: bool) -> SimpleNamespace:
+ return SimpleNamespace(
+ system_prompt_builder=SimpleNamespace(language="cn"),
+ card=SimpleNamespace(id="agent-native-image-test"),
+ ability_manager=_FakeAbilityManager(),
+ deep_config=SimpleNamespace(enable_read_image_multimodal=enable),
+ )
+
+
+def _flash_read_tool(rail) -> FlashReadFileTool:
+ for tool in rail.tools or []:
+ if isinstance(tool, FlashReadFileTool):
+ return tool
+ raise AssertionError("rail 未注册 FlashReadFileTool")
+
+
+# ---------------------------------------------------------------------------
+# build_read_file_image_kwargs:跨 core 版本的 resolver 透传
+# ---------------------------------------------------------------------------
+
+
+def test_kwargs_without_resolver_is_static_bool() -> None:
+ assert build_read_file_image_kwargs(enable_image_multimodal=False) == {
+ "enable_image_multimodal": False,
+ }
+ assert build_read_file_image_kwargs(enable_image_multimodal=True) == {
+ "enable_image_multimodal": True,
+ }
+
+
+def test_kwargs_passes_resolver_to_dedicated_param_when_core_supports(
+ monkeypatch,
+) -> None:
+ """新 core:resolver 走专用 image_multimodal_resolver 键 + 静态兜底。"""
+
+ monkeypatch.setattr(support, "_supports_resolver", True)
+
+ def resolver() -> bool:
+ return False
+
+ assert build_read_file_image_kwargs(resolver, enable_image_multimodal=True) == {
+ "enable_image_multimodal": True,
+ support.IMAGE_MULTIMODAL_RESOLVER_PARAM: resolver,
+ }
+
+
+def test_kwargs_omits_resolver_when_core_locked(monkeypatch) -> None:
+ """锁定 core(无 image_multimodal_resolver):resolver 被丢弃,退回构造时求值。"""
+
+ monkeypatch.setattr(support, "_supports_resolver", False)
+
+ def resolver() -> bool:
+ return False
+
+ assert build_read_file_image_kwargs(resolver, enable_image_multimodal=False) == {
+ "enable_image_multimodal": False,
+ }
+
+
+# ---------------------------------------------------------------------------
+# rail 集成:resolver 透传后 read_file 跟随模型热切换
+# ---------------------------------------------------------------------------
+
+
+ not support.supports_read_file_image_resolver(),
+ reason="锁定 core(8215f2c)无 image_multimodal_resolver,热切换能力未启用",
+)
+def test_flash_bash_rail_read_file_follows_model_switch() -> None:
+ """deep profile:新 core 替换 stock ReadFileTool 时继承 resolver,切模型后行为跟随。"""
+
+ agent = _fake_agent(enable=True)
+ rail = FlashBashSysOperationRail()
+ rail.sys_operation = SimpleNamespace()
+
+ rail.init(agent)
+
+ read_tool = _flash_read_tool(rail)
+ assert read_file_image_multimodal_enabled(read_tool) is True
+
+ agent.deep_config.enable_read_image_multimodal = False
+ assert read_file_image_multimodal_enabled(read_tool) is False
+
+
+ not support.supports_read_file_image_resolver(),
+ reason="锁定 core(8215f2c)无 image_multimodal_resolver,热切换能力未启用",
+)
+def test_slim_rail_read_file_follows_model_switch() -> None:
+ """flash profile:新 core 下 init 不冻结能力值,切模型后 read_file 行为跟随。"""
+
+ agent = _fake_agent(enable=False)
+ rail = SlimSysOperationRail()
+ rail.sys_operation = SimpleNamespace()
+
+ rail.init(agent)
+
+ read_tool = _flash_read_tool(rail)
+ assert read_file_image_multimodal_enabled(read_tool) is False
+
+ agent.deep_config.enable_read_image_multimodal = True
+ assert read_file_image_multimodal_enabled(read_tool) is True
+
+
+def test_slim_rail_explicit_flag_still_wins_over_model_capability() -> None:
+ """显式 enable_read_image_multimodal=False 是合法降级,不被模型能力覆盖。"""
+
+ agent = _fake_agent(enable=True)
+ rail = SlimSysOperationRail(enable_read_image_multimodal=False)
+ rail.sys_operation = SimpleNamespace()
+
+ rail.init(agent)
+
+ read_tool = _flash_read_tool(rail)
+ assert read_file_image_multimodal_enabled(read_tool) is False
diff --git a/tests/unit_tests/agents/harness/common/rails/test_read_file_validation.py b/tests/unit_tests/agents/harness/common/rails/test_read_file_validation.py
index e77b38af88..86fe8f5029 100644
--- a/tests/unit_tests/agents/harness/common/rails/test_read_file_validation.py
+++ b/tests/unit_tests/agents/harness/common/rails/test_read_file_validation.py
@@ -4,13 +4,21 @@
from __future__ import annotations
+import pytest
from openjiuwen.harness.tools.base_tool import ToolOutput
from jiuwenswarm.agents.harness.common.rails.read_file_validation import (
_looks_like_binary_payload,
+ build_native_image_tool_error,
+ build_provided_image_read_error,
+ extract_paths_from_arguments,
is_image_file_path,
is_non_text_file_path,
+ is_remote_image_url,
+ is_vision_tool,
validate_read_file_result,
+ vision_tool_image_targets,
+ vision_tool_targets_all_provided,
)
_SVG_WITH_BASE64 = (
@@ -122,6 +130,67 @@ def test_empty_result_still_rejected() -> None:
assert ok is False
+ ("language", "forbidden_phrase"),
+ [("cn", "无需再调用 read_file"), ("en", "do not call read_file")],
+ ids=["cn", "en"],
+)
+def test_provided_image_read_error_forbids_read_file(language, forbidden_phrase) -> None:
+ error = build_provided_image_read_error("/uploads/home.png", language=language)
+
+ assert error.startswith("[READ_FILE_ERROR]")
+ assert "/uploads/home.png" in error
+ assert forbidden_phrase in error
+
+
+ ("arguments", "expected"),
+ [
+ ({"file_paths": ["/uploads/a.png", "/uploads/b.png"]}, ["/uploads/a.png", "/uploads/b.png"]),
+ ({"file_path": "/uploads/a.png"}, ["/uploads/a.png"]),
+ ],
+ ids=["batch", "single"],
+)
+def test_extract_paths_from_arguments_covers_single_and_batch(arguments, expected) -> None:
+ # 批量拒绝(N4)依赖这里把 file_paths 摊平成路径列表。
+ assert extract_paths_from_arguments(arguments) == expected
+
+
+ ("tool_name", "expected"),
+ [
+ ("visual_question_answering", True),
+ ("vision_qa", True),
+ ("VisionQA", True),
+ ("image_reading", True),
+ # agent-core 的真实 OCR 工具名 + 前端 / 权限投影的显示名别名。
+ ("image_ocr", True),
+ ("ImageOCR", True),
+ (" image_ocr ", True),
+ ("read_file", False),
+ ("bash", False),
+ ("", False),
+ ],
+)
+def test_is_vision_tool_recognizes_vqa_and_ocr_names(tool_name, expected) -> None:
+ """``image_ocr`` 漏登记会让原生看图仍去调 OCR(CR-8);别名两侧都要认。"""
+
+ assert is_vision_tool(tool_name) is expected
+
+
+ ("language", "required_phrase"),
+ [("cn", "像素"), ("en", "Do not call")],
+ ids=["cn", "en"],
+)
+def test_native_image_tool_error_is_language_aware(language, required_phrase) -> None:
+ error = build_native_image_tool_error(language=language)
+
+ assert error.startswith("[VISION_TOOL_SKIPPED]")
+ assert "visual_question_answering" in error
+ assert required_phrase in error
+
+
def test_svg_is_read_as_text_not_image() -> None:
"""SVG 是文本 XML:前置拦截与后置校验都不应把它当图片。"""
assert is_image_file_path("diagram.svg") is False
@@ -143,3 +212,67 @@ def test_image_extensions_still_blocked() -> None:
assert ok is False
assert error is not None
+
+
+ ("value", "expected"),
+ [
+ ("https://example.com/a.png", True),
+ ("http://example.com/a.png", True),
+ (" HTTP://example.com/a.png ", True),
+ ("/uploads/a.png", False),
+ ("C:\\work\\a.png", False),
+ ("", False),
+ ],
+)
+def test_is_remote_image_url_detects_http(value, expected) -> None:
+ """远程 HTTP(S) 图片的目标不能按"已提供像素"拦截,read_file 无法替代抓取。"""
+
+ assert is_remote_image_url(value) is expected
+
+
+ ("tool_name", "arguments", "expected"),
+ [
+ ("visual_question_answering", {"image_path_or_url": "/u/a.png", "question": "?"}, ["/u/a.png"]),
+ ("image_ocr", {"image_path_or_url": "https://x/a.png", "prompt": "ocr"}, ["https://x/a.png"]),
+ ("image_reading", {"local_url": "/u/a.png"}, ["/u/a.png"]),
+ ("image_reading", {"remote_url": "https://x/a.png"}, ["https://x/a.png"]),
+ # 未附带图片 / 缺参 → 未知目标
+ ("visual_question_answering", {"question": "?"}, []),
+ ("visual_question_answering", {}, []),
+ ("image_ocr", None, []),
+ ],
+)
+def test_vision_tool_image_targets_extracts_path_or_url(tool_name, arguments, expected) -> None:
+ assert vision_tool_image_targets(tool_name, arguments) == expected
+
+
+def test_vision_tool_targets_all_provided_blocks_only_provided_local_path(tmp_path) -> None:
+ """已提供的本地目标→拦;远程 / 未知 / 未提供目标→放行(ND:避免误封远程图片)。"""
+ provided = tmp_path / "a.png"
+ provided.write_bytes(b"fake")
+
+ assert vision_tool_targets_all_provided(
+ "visual_question_answering",
+ {"image_path_or_url": str(provided), "question": "?"},
+ [str(provided)],
+ ) is True
+
+ assert vision_tool_targets_all_provided(
+ "visual_question_answering",
+ {"image_path_or_url": "https://cdn.example.com/b.png", "question": "?"},
+ [str(provided)],
+ ) is False
+
+ assert vision_tool_targets_all_provided(
+ "visual_question_answering",
+ {"image_path_or_url": str(tmp_path / "unknown.png"), "question": "?"},
+ [str(provided)],
+ ) is False
+
+ assert vision_tool_targets_all_provided(
+ "visual_question_answering",
+ {"question": "no image arg"},
+ [str(provided)],
+ ) is False
diff --git a/tests/unit_tests/agents/harness/common/test_read_file_image_support.py b/tests/unit_tests/agents/harness/common/test_read_file_image_support.py
new file mode 100644
index 0000000000..5ad43d496c
--- /dev/null
+++ b/tests/unit_tests/agents/harness/common/test_read_file_image_support.py
@@ -0,0 +1,62 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""跨版本 ReadFileTool 图片能力接线:锁定 core 无 resolver 参数时不得 TypeError。
+
+``uv.lock`` 锁定的 agent-core(8215f2c)只有 ``enable_image_multimodal`` 静态参数;
+agent-core 的 ``image_multimodal_resolver`` 尚未合入 dev-stable。这里验证兼容层:
+- 探测结果与实际 ``ReadFileTool.__init__`` 签名一致;
+- core 不支持时关键字参数里只有静态 bool(构造不炸,退回构造时求值);
+- core 支持时把 resolver 透传下去(合入后自动启用调用时求值)。
+"""
+
+from __future__ import annotations
+
+import inspect
+
+import pytest
+from openjiuwen.harness.tools.filesystem import ReadFileTool
+
+from jiuwenswarm.agents.harness.common import read_file_image_support as support
+
+
+def test_support_flag_matches_installed_core_signature() -> None:
+ parameters = inspect.signature(ReadFileTool.__init__).parameters
+ expected = support.IMAGE_MULTIMODAL_RESOLVER_PARAM in parameters or any(
+ parameter.kind is inspect.Parameter.VAR_KEYWORD
+ for parameter in parameters.values()
+ )
+ assert support.supports_read_file_image_resolver() is expected
+
+
+def test_kwargs_omit_resolver_when_core_is_locked(monkeypatch) -> None:
+ monkeypatch.setattr(support, "_supports_resolver", False)
+ kwargs = support.build_read_file_image_kwargs(
+ lambda: True, enable_image_multimodal=False
+ )
+ assert kwargs == {"enable_image_multimodal": False}
+
+
+def test_kwargs_pass_resolver_when_core_supports(monkeypatch) -> None:
+ monkeypatch.setattr(support, "_supports_resolver", True)
+ def resolver() -> bool:
+ return False
+
+ kwargs = support.build_read_file_image_kwargs(
+ resolver, enable_image_multimodal=True
+ )
+ assert kwargs["enable_image_multimodal"] is True
+ assert kwargs[support.IMAGE_MULTIMODAL_RESOLVER_PARAM] is resolver
+
+
+ ("tool", "expected"),
+ [
+ (type("LegacyTool", (), {"enable_image_multimodal": False})(), False),
+ (type("LegacyTool", (), {"enable_image_multimodal": True})(), True),
+ ],
+ ids=["legacy-off", "legacy-on"],
+)
+def test_enabled_reader_falls_back_to_instance_attribute(tool, expected) -> None:
+ """旧 core 没有 ``_image_multimodal_enabled()`` 时读静态属性。"""
+
+ assert support.read_file_image_multimodal_enabled(tool) is expected
\ No newline at end of file
diff --git a/tests/unit_tests/agents/harness/common/tools/test_model_capabilities.py b/tests/unit_tests/agents/harness/common/tools/test_model_capabilities.py
new file mode 100644
index 0000000000..3386046372
--- /dev/null
+++ b/tests/unit_tests/agents/harness/common/tools/test_model_capabilities.py
@@ -0,0 +1,33 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""模型原生能力(modalities)的配置归一:只认 modalities 是否含 image([[S_22]])。"""
+
+from __future__ import annotations
+
+from jiuwenswarm.agents.harness.common.tools.model_capabilities import (
+ coerce_modalities,
+ supports_native_image,
+)
+
+
+def test_coerce_modalities_normalizes_yaml_literals():
+ """modalities 可能是列表,也可能是逗号/空白分隔字符串;统一成小写去重列表。"""
+ assert coerce_modalities(["text", "image"]) == ["text", "image"]
+ assert coerce_modalities(("text", "image")) == ["text", "image"]
+ assert coerce_modalities("text,image") == ["text", "image"]
+ assert coerce_modalities(" text image ") == ["text", "image"]
+ assert coerce_modalities(["TEXT", "IMAGE", "text"]) == ["text", "image"]
+ # 无法识别 / 空 → None(未声明),调用方按不支持处理。
+ assert coerce_modalities("") is None
+ assert coerce_modalities([]) is None
+ assert coerce_modalities(123) is None
+ assert coerce_modalities(None) is None
+
+
+def test_supports_native_image_only_when_image_present():
+ """只有 modalities 含 image 才支持原生看图;未声明/纯文本一律不支持。"""
+ assert supports_native_image(["text", "image"]) is True
+ assert supports_native_image("text,image") is True
+ assert supports_native_image(["text"]) is False
+ assert supports_native_image(None) is False
+ assert supports_native_image("") is False
\ No newline at end of file
diff --git a/tests/unit_tests/agentserver/test_code_adapter_context_overflow_recovery_rail.py b/tests/unit_tests/agentserver/test_code_adapter_context_overflow_recovery_rail.py
index df6f8c2be6..6edb5b4403 100644
--- a/tests/unit_tests/agentserver/test_code_adapter_context_overflow_recovery_rail.py
+++ b/tests/unit_tests/agentserver/test_code_adapter_context_overflow_recovery_rail.py
@@ -27,10 +27,33 @@ from jiuwenswarm.agents.harness.common.rails.context_overflow_recovery_rail impo
_RAIL_BUILD_NAMES = getattr(_ic_mod, "_RAIL_BUILD_NAMES")
_RailBuildInfo = getattr(_ic_mod, "_RailBuildInfo")
+_build_multimodal_image_rail = getattr(_ic_mod, "_build_multimodal_image_rail")
JiuwenSwarmCodeAdapter = _ic_mod.JiuwenSwarmCodeAdapter
_FIXED_RAIL_NAMES = getattr(JiuwenSwarmCodeAdapter, "_FIXED_RAIL_NAMES")
+def _capture_rail_infos():
+ """桩掉 _instantiate_rails,返回 _build_agent_rails 组装的 RailBuildInfo 列表。
+
+ _build_agent_rails 末尾会调 _instantiate_rails 把 RailBuildInfo 列表实例化成
+ rail 列表;桩成原样返回可避免真实 rail 构造的重依赖,只校验条目本身。
+ """
+ adapter = JiuwenSwarmCodeAdapter()
+ captured: list = []
+ real_instantiate = adapter._instantiate_rails
+
+ def _passthrough_instantiate(rail_infos, config_base, *args, **kwargs):
+ captured.extend(rail_infos)
+ return rail_infos
+
+ object.__setattr__(adapter, "_instantiate_rails", _passthrough_instantiate)
+ try:
+ adapter._build_agent_rails(config={}, config_base={}, mode="code")
+ finally:
+ object.__setattr__(adapter, "_instantiate_rails", real_instantiate)
+ return adapter, captured
+
+
# ─── TC-001: _FIXED_RAIL_NAMES 含 ContextOverflowRecoveryRail ─────────────
@@ -69,23 +92,7 @@ def test_build_agent_rails_includes_context_overflow_recovery_rail_entry():
rail 列表,因此桩掉 _instantiate_rails 让它原样返回 rail_infos,避免触发真实
rail 构造的重依赖,只校验 RailBuildInfo 的 attr_name 与 build_func。
"""
- adapter = JiuwenSwarmCodeAdapter()
-
- # 桩 _instantiate_rails:直接返回传入的 rail_infos(不实例化),便于检查条目
- captured: list = []
- real_instantiate = adapter._instantiate_rails
-
- def _passthrough_instantiate(rail_infos, config_base, *args, **kwargs):
- captured.extend(rail_infos)
- return rail_infos
-
- object.__setattr__(adapter, "_instantiate_rails", _passthrough_instantiate)
- try:
- adapter._build_agent_rails(config={}, config_base={}, mode="code")
- finally:
- object.__setattr__(adapter, "_instantiate_rails", real_instantiate)
-
- rail_infos = captured
+ adapter, rail_infos = _capture_rail_infos()
attr_names = [ri.attr_name for ri in rail_infos]
assert "_context_overflow_recovery_rail" in attr_names, (
"fixed rail list should contain _context_overflow_recovery_rail entry"
@@ -98,11 +105,7 @@ def test_build_agent_rails_includes_context_overflow_recovery_rail_entry():
f"_context_processor_rail (got proc_idx={proc_idx}, recovery_idx={recovery_idx})"
)
# build_func 应复用父类 _build_context_overflow_recovery_rail(静态方法)
- recovery_info = rail_infos[recovery_idx]
- assert recovery_info.build_func == adapter._build_context_overflow_recovery_rail, (
- "recovery rail build_func should be the inherited parent static method "
- "_build_context_overflow_recovery_rail"
- )
+ assert rail_infos[recovery_idx].build_func == adapter._build_context_overflow_recovery_rail
# ─── TC-004: _build_context_overflow_recovery_rail 可调用且返回 rail/None ──
@@ -126,3 +129,22 @@ def test_build_context_overflow_recovery_rail_callable_returns_rail_or_none():
assert result._max_recovery_attempts == 3, (
"ContextOverflowRecoveryRail should be built with max_recovery_attempts=3"
)
+
+
+# ─── TC-005: code 模式固定列表含 MultimodalImageRail ────────────────────────
+
+
+def test_build_agent_rails_includes_multimodal_image_rail_entry():
+ """CodeAdapter 的会话必须挂 MultimodalImageRail,否则上传图片进不了主模型。
+
+ 回归:web 会话走 CodeAdapter,固定 rail 列表漏了该 rail,导致上传图只以
+ 引用行路径出现,模型只能调用 read_file 现读图片。
+ """
+ _, captured = _capture_rail_infos()
+ attr_names = [ri.attr_name for ri in captured]
+ assert "_multimodal_image_rail" in attr_names, (
+ "code mode fixed rails should contain _multimodal_image_rail"
+ )
+ # builder 已从类方法提升到 deep.model_factory,interface_code 直接引用模块级实现
+ multimodal_info = captured[attr_names.index("_multimodal_image_rail")]
+ assert multimodal_info.build_func == _build_multimodal_image_rail
diff --git a/tests/unit_tests/agentserver/test_deep_adapter_interrupt.py b/tests/unit_tests/agentserver/test_deep_adapter_interrupt.py
index e75552f31b..0d9e44c312 100644
--- a/tests/unit_tests/agentserver/test_deep_adapter_interrupt.py
+++ b/tests/unit_tests/agentserver/test_deep_adapter_interrupt.py
@@ -212,13 +212,11 @@ async def test_team_stream_binds_a2a_resource_context(
monkeypatch.setattr(adapter, "_inject_extension_config_into_inputs", lambda _inputs: None)
monkeypatch.setattr(adapter, "_deepresearch_artifact_output_dir", lambda _path: None)
monkeypatch.setattr(
- "jiuwenswarm.server.runtime.agent_adapter.interface_deep._prepare_multimodal_image_inputs", lambda _request, inputs: inputs
+ interface_deep,
+ "_prepare_multimodal_image_inputs",
+ lambda _request, inputs: inputs,
)
monkeypatch.setattr(adapter, "_native_image_input_enabled", lambda *_args: False)
- monkeypatch.setattr(
- "jiuwenswarm.server.runtime.agent_adapter.interface_deep._prepare_react_image_tool_prompt",
- lambda _request, inputs, **_kwargs: inputs,
- )
monkeypatch.setattr(adapter, "_resolve_runtime_language", lambda: "zh")
monkeypatch.setattr(adapter, "_resolve_prompt_channel", lambda _session: "web")
monkeypatch.setattr(adapter, "_write_runtime_state", lambda **_kwargs: None)
diff --git a/tests/unit_tests/agentserver/test_evolve_command_edges.py b/tests/unit_tests/agentserver/test_evolve_command_edges.py
index c1a6d952ae..bf1a11f904 100644
--- a/tests/unit_tests/agentserver/test_evolve_command_edges.py
+++ b/tests/unit_tests/agentserver/test_evolve_command_edges.py
@@ -609,14 +609,14 @@ async def test_agent_stream_slash_followup_continues_into_runner(monkeypatch):
("acp", None, None, "workspace_acp"),
],
)
-async def test_team_stream_injects_image_tool_context_for_non_vision_model(
+async def test_team_stream_keeps_image_reference_for_non_vision_model(
monkeypatch,
channel_id,
service_id,
agent_id,
expected_workspace_key,
):
- """Team mode must preserve the same local-image tool context as agent mode."""
+ """Team mode must preserve the same local-image reference lines as agent mode."""
adapter = JiuWenSwarmDeepAdapter()
adapter._instance = SimpleNamespace() # pylint: disable=protected-access
adapter._is_session_scoped_adapter = True # pylint: disable=protected-access
@@ -667,11 +667,35 @@ async def test_team_stream_injects_image_tool_context_for_non_vision_model(
is_stream=True,
)
- async for _ in adapter.process_message_stream_impl(request, {"query": "解析图片内容"}):
- pass
+ chunks = []
+ async for chunk in adapter.process_message_stream_impl(
+ request, {"query": "解析图片内容"}
+ ):
+ chunks.append(chunk)
- assert "jiuwenswarm_image_tool_context" in captured["query"]
+ # 非视觉模型:query 保留 [image #n] 引用行(可按原文件出图);
+ # 原生 vs VQA 的多模态策略由 MultimodalImageRail 按模型能力写入系统提示,
+ # 不再向 query 注入 jiuwenswarm_image_tool_context 工具上下文。
+ assert "jiuwenswarm_image_tool_context" not in captured["query"]
assert "agent/sessions/sess-team-image/uploads/persisted.png" in captured["query"]
+
+ # 团队路径与单代理路径一致:解析为不支持原生图片时下发 fallback notice,
+ # 且本次请求绑定的图片快照在请求结束后复位。
+ notices = [
+ chunk.payload
+ for chunk in chunks
+ if isinstance(getattr(chunk, "payload", None), dict)
+ and chunk.payload.get("notice_type") == "image_tool_fallback"
+ ]
+ assert len(notices) == 1
+ assert notices[0]["image_count"] == 1
+ assert notices[0]["request_id"] == "req-team-image"
+
+ from jiuwenswarm.agents.harness.common.multimodal import (
+ current_multimodal_image_files,
+ )
+
+ assert current_multimodal_image_files() == []
from jiuwenswarm.common.utils import resolve_tenant_sessions_dir
from jiuwenswarm.server.runtime.tenant_agent_pool import TenantAgentPool
diff --git a/tests/unit_tests/agentserver/test_flash_adapter_rails.py b/tests/unit_tests/agentserver/test_flash_adapter_rails.py
index 36f9b470d8..0a7393dadd 100644
--- a/tests/unit_tests/agentserver/test_flash_adapter_rails.py
+++ b/tests/unit_tests/agentserver/test_flash_adapter_rails.py
@@ -173,6 +173,14 @@ def test_ask_user_rail_is_in_keep_to_avoid_churn():
assert "_ask_user_rail" in JiuwenSwarmFlashAdapter._FLASH_RAIL_KEEP
+def test_multimodal_image_rail_is_in_keep():
+ """上传图片必须由 MultimodalImageRail 直接送入主模型,而不是退化成 read_file。"""
+ adapter = JiuwenSwarmFlashAdapter()
+ assert "_multimodal_image_rail" in adapter._FLASH_RAIL_KEEP
+ filtered = adapter._filter_rail_infos_by_keep([_info("_multimodal_image_rail")])
+ assert [info.attr_name for info in filtered] == ["_multimodal_image_rail"]
+
+
# ---------------------------------------------------------------------------
# #4 _update_rails_for_mode does not penetrate the whitelist
# ---------------------------------------------------------------------------
diff --git a/tests/unit_tests/agentserver/test_model_cache_reload_retention.py b/tests/unit_tests/agentserver/test_model_cache_reload_retention.py
index 2950a69d2f..51124d5d8d 100644
--- a/tests/unit_tests/agentserver/test_model_cache_reload_retention.py
+++ b/tests/unit_tests/agentserver/test_model_cache_reload_retention.py
@@ -58,7 +58,7 @@ def _adapter(monkeypatch) -> tuple[JiuWenSwarmDeepAdapter, list[str]]:
adapter._instance = SimpleNamespace(_react_agent=SimpleNamespace())
built: list[str] = []
- def _build(mcc, _mco):
+ def _build(mcc, _mco, *_args, **_kwargs):
built.append(mcc["model_name"])
return Model(
model_client_config=ModelClientConfig(
diff --git a/tests/unit_tests/agentserver/test_progressive_disabled_tools_filter.py b/tests/unit_tests/agentserver/test_progressive_disabled_tools_filter.py
index dd7af318b0..5aee662950 100644
--- a/tests/unit_tests/agentserver/test_progressive_disabled_tools_filter.py
+++ b/tests/unit_tests/agentserver/test_progressive_disabled_tools_filter.py
@@ -141,3 +141,31 @@ def test_build_progressive_rail_passes_disabled_tools():
)
assert rail is not None
assert rail._disabled_tools == {"memory_search", "web_search"}
+
+
+# ─── 从 test_progressive_vision_tool_guard.py 移入:与视觉能力无关,属渐进披露域 ──
+
+
+async def test_meta_tools_removed_from_schema_when_lazy_load_bypassed():
+ """lazy-load 旁路时 meta 工具已卸载,但 inputs.tools 仍带着它们,必须摘除。
+
+ 回归:不摘会让模型调用得到 "Ability not found: invoke_tool"。
+ """
+ rail = ProgressiveToolRail(eager_tools=["tools_search", "invoke_tool", "bash"])
+ rail._lazy_load_active_for_ctx = lambda ctx: False
+ tools = [_card("bash"), _card("tools_search"), _card("invoke_tool")]
+ spb = SimpleNamespace(
+ sections=[], add_section=lambda section: spb.sections.append(section)
+ )
+ agent = SimpleNamespace(
+ ability_manager=SimpleNamespace(list=lambda: list(tools)),
+ system_prompt_builder=spb,
+ deep_config=SimpleNamespace(enable_read_image_multimodal=False),
+ )
+ rail._deep_agent = agent
+ ctx = SimpleNamespace(agent=agent, inputs=SimpleNamespace(tools=list(tools)))
+
+ await rail.before_model_call(ctx)
+
+ assert [tool.name for tool in ctx.inputs.tools] == ["bash"]
diff --git a/tests/unit_tests/agentserver/test_stream_event_rail_symphony.py b/tests/unit_tests/agentserver/test_stream_event_rail_symphony.py
index c3b995bc93..53508084b2 100644
--- a/tests/unit_tests/agentserver/test_stream_event_rail_symphony.py
+++ b/tests/unit_tests/agentserver/test_stream_event_rail_symphony.py
@@ -80,58 +80,6 @@ def _model_ctx(messages):
)
-async def test_stream_event_rail_strips_image_blocks_when_read_image_multimodal_disabled():
- rail = JiuSwarmStreamEventRail()
- message = UserMessage(
- content=[
- {"type": "text", "text": "Image loaded from read_file: C:/tmp/blog.png"},
- {
- "type": "image_url",
- "image_url": {"url": "data:image/png;base64,abc"},
- },
- ],
- )
- ctx = SimpleNamespace(
- session=None,
- inputs=SimpleNamespace(tools=[]),
- context=_ModelContext([message]),
- extra={},
- )
-
- await rail.before_model_call(ctx)
-
- assert message.content == "Image loaded from read_file: C:/tmp/blog.png"
-
-
-async def test_stream_event_rail_keeps_image_blocks_when_read_image_multimodal_enabled():
- rail = JiuSwarmStreamEventRail()
- rail.init(
- SimpleNamespace(
- deep_config=SimpleNamespace(enable_read_image_multimodal=True),
- )
- )
- content = [
- {"type": "text", "text": "Image loaded from read_file: C:/tmp/blog.png"},
- {
- "type": "image_url",
- "image_url": {"url": "data:image/png;base64,abc"},
- },
- ]
- message = UserMessage(content=list(content))
- ctx = SimpleNamespace(
- session=None,
- inputs=SimpleNamespace(tools=[]),
- context=_ModelContext([message]),
- extra={},
- )
-
- await rail.before_model_call(ctx)
-
- assert message.content == content
-
-
@pytest.mark.asyncio
async def test_stream_event_rail_does_not_enable_symphony_status_events_for_plan_tool():
rail = JiuSwarmStreamEventRail()
diff --git a/tests/unit_tests/agentserver/test_subagent_model_tier.py b/tests/unit_tests/agentserver/test_subagent_model_tier.py
index b724c891d4..8eb5e96741 100644
--- a/tests/unit_tests/agentserver/test_subagent_model_tier.py
+++ b/tests/unit_tests/agentserver/test_subagent_model_tier.py
@@ -52,10 +52,10 @@ def _adapter_with_tier_models() -> JiuWenSwarmDeepAdapter:
"default-model": default,
}
- def _build_from_entry(mcc, _mco):
+ def _build_from_entry(mcc, _mco, *_args, **_kwargs):
return built[mcc["model_name"]]
- adapter._build_model_from_entry = _build_from_entry # type: ignore[method-assign]
+ # builder 已提升到 deep.model_factory,缓存构建经 interface_deep 命名空间调用
previous_builder = interface_deep._build_model_from_entry
interface_deep._build_model_from_entry = _build_from_entry
try:
diff --git a/tests/unit_tests/gateway/test_media_attachments.py b/tests/unit_tests/gateway/test_media_attachments.py
new file mode 100644
index 0000000000..91397ce4f7
--- /dev/null
+++ b/tests/unit_tests/gateway/test_media_attachments.py
@@ -0,0 +1,144 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""上传侧图片张数上限必须跟随 ``react.multimodal_image_max_count``。
+
+写死 8 会让「前端能传 8 张、模型侧预算只给 N 张」这类漂移无人察觉:配置调小后
+多传的图仍会落盘并被引用,随后才在发送侧被预算裁掉,用户看到的是静默丢图。
+
+反向同样成立:``0 = 不限``(与 rail / 模型侧三预算同语义),只有缺失、负数或
+非整数配置才回退默认值。旧用例只上传 3 张(< 默认 8),「配置 0 保留 3 张」与
+「配置 8 保留 3 张」结果相同,根本无法区分 8 与不限——回归必须用超过默认上限的
+12 张上传件才能钉住语义(检视 CR-7)。
+"""
+
+from __future__ import annotations
+
+import base64
+import io
+
+import pytest
+from PIL import Image
+
+from jiuwenswarm.gateway import media_attachments
+
+# 必须大于默认上限 8:否则「截断到 8」与「不截断」在上传数量上不可区分。
+_UPLOAD_COUNT = 12
+_DEFAULT_MAX_IMAGE_COUNT = 8
+
+
+def _image_item(index: int) -> dict:
+ image = Image.new("RGB", (8, 8), (index * 20 % 255, 60, 90))
+ buf = io.BytesIO()
+ image.save(buf, format="PNG")
+ return {
+ "type": "image",
+ "filename": f"img{index}.png",
+ "mimeType": "image/png",
+ "base64Data": base64.b64encode(buf.getvalue()).decode(),
+ }
+
+
+def _patch_react_config(monkeypatch, react_config: dict) -> None:
+ """固定 ``react`` 段配置(``_max_image_count`` 在函数体内导入 get_config)。"""
+
+ monkeypatch.setattr(
+ "jiuwenswarm.common.config.get_config",
+ lambda: {"react": react_config},
+ )
+
+
+def _run(monkeypatch, tmp_path, count: int) -> list[dict]:
+ monkeypatch.setattr(media_attachments, "get_agent_sessions_dir", lambda: tmp_path)
+ params = {"media_items": [_image_item(i) for i in range(count)]}
+ media_attachments.normalize_chat_media_attachments(params, "session-1")
+ return params.get("media_items") or []
+
+
+def test_upload_count_follows_small_react_config(monkeypatch, tmp_path):
+ _patch_react_config(monkeypatch, {"multimodal_image_max_count": 2})
+
+ stored = _run(monkeypatch, tmp_path, 4)
+
+ assert len(stored) == 2
+
+
+ ("react_config", "expected_count"),
+ [
+ # 0 = 不限:12 张全部保留,不能切成 raw_items[:0] 全部丢掉。
+ pytest.param({"multimodal_image_max_count": 0}, _UPLOAD_COUNT, id="zero-means-unlimited"),
+ # 显式 8:与默认值同数,但语义是「截断」,只保留最老的 8 张。
+ pytest.param({"multimodal_image_max_count": 8}, 8, id="explicit-eight-truncates"),
+ # 配置大于上传数量:不截断。
+ pytest.param({"multimodal_image_max_count": 20}, _UPLOAD_COUNT, id="above-upload-count"),
+ # 缺失 / YAML 空值 / 非法 / 负数 → 默认 8(不是拒收,也不是不限)。
+ pytest.param({}, _DEFAULT_MAX_IMAGE_COUNT, id="config-missing"),
+ pytest.param(
+ {"multimodal_image_max_count": None},
+ _DEFAULT_MAX_IMAGE_COUNT,
+ id="yaml-null-falls-back-to-default",
+ ),
+ pytest.param(
+ {"multimodal_image_max_count": "eight"},
+ _DEFAULT_MAX_IMAGE_COUNT,
+ id="invalid-string-falls-back-to-default",
+ ),
+ pytest.param(
+ {"multimodal_image_max_count": -1},
+ _DEFAULT_MAX_IMAGE_COUNT,
+ id="negative-falls-back-to-default",
+ ),
+ pytest.param(
+ {"multimodal_image_max_count": 0.5},
+ _DEFAULT_MAX_IMAGE_COUNT,
+ id="non-integral-float-falls-back-to-default",
+ ),
+ ],
+)
+def test_upload_count_semantics_with_twelve_uploads(
+ monkeypatch, tmp_path, react_config, expected_count
+):
+ """12 张上传件下,0=不限 / 8=截断 / 缺失与非法/负数=默认 8 三种语义可区分。"""
+
+ _patch_react_config(monkeypatch, react_config)
+
+ stored = _run(monkeypatch, tmp_path, _UPLOAD_COUNT)
+
+ assert len(stored) == expected_count
+ # 截断保留最老(上传顺序)的前 N 张,与模型侧「最老优先降级」方向一致。
+ assert [item["filename"] for item in stored] == [
+ f"img{index}.png" for index in range(expected_count)
+ ]
+
+
+def test_max_image_count_zero_is_unlimited_not_default(monkeypatch):
+ """``_max_image_count()`` 本身就是 0:不能把 0 归一成默认 8。"""
+
+ _patch_react_config(monkeypatch, {"multimodal_image_max_count": 0})
+
+ assert media_attachments._max_image_count() == 0
+
+
+ "react_config",
+ [
+ pytest.param({}, id="config-missing"),
+ pytest.param({"multimodal_image_max_count": None}, id="config-null"),
+ pytest.param({"multimodal_image_max_count": -1}, id="config-negative"),
+ pytest.param({"multimodal_image_max_count": -8}, id="config-negative-default"),
+ pytest.param({"multimodal_image_max_count": "eight"}, id="config-non-numeric"),
+ pytest.param({"multimodal_image_max_count": 0.5}, id="config-non-integral"),
+ ],
+)
+def test_max_image_count_falls_back_to_default(monkeypatch, react_config):
+ """缺失 / null / 负数 / 非法 / 非整数 → 默认 8(0 是唯一「不限」语义)。"""
+
+ _patch_react_config(monkeypatch, react_config)
+
+ assert media_attachments._max_image_count() == _DEFAULT_MAX_IMAGE_COUNT
+
+
+def test_max_image_count_passes_through_positive_value(monkeypatch):
+ _patch_react_config(monkeypatch, {"multimodal_image_max_count": 3})
+
+ assert media_attachments._max_image_count() == 3
\ No newline at end of file