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(harness): team 成员接入原生多模态图片输入
openJiuwen-botdd0ddb19d279
diff --git a/jiuwenswarm/agents/harness/AGENTS.md b/jiuwenswarm/agents/harness/AGENTS.mdindex 744f779e6b..911adfc884 100644--- a/jiuwenswarm/agents/harness/AGENTS.md+++ b/jiuwenswarm/agents/harness/AGENTS.md@@ -1,5 +1,5 @@----description: 给修改/检视 agents/harness 代码的 AI 助手与工程师:七子树地图、任务规划 / 可靠性 / subagent / 中断交互 / 事件流域 specs 索引(S_01~S_21)、公开入口、架构铁律、装配点与配置消费、测试与提交约束+description: 给修改/检视 agents/harness 代码的 AI 助手与工程师:七子树地图、任务规划 / 可靠性 / subagent / 中断交互 / 事件流 / 原生多模态 specs 索引(S_01~S_22)、公开入口、架构铁律、装配点与配置消费、测试与提交约束---# harness:代理执行挂件的多域聚合目录@@ -14,16 +14,17 @@ common / code / flash——**spec 按改哪块机制切,不按目录树切**[docs/AGENTS.md](docs/AGENTS.md)。**当前 specs 覆盖任务规划域(S_01~S_06)、可靠性域(S_07~S_10)、subagent 域-(S_11~S_14)、中断交互域(S_15~S_19)与事件流域(S_20~S_21)**。未归档的域(team /-skill_selection / memory / 观测性 / …)不等于不存在,只等于还没有契约文档;动这些域时+(S_11~S_14)、中断交互域(S_15~S_19)、事件流域(S_20~S_21)与原生多模态图像输入+(S_22)**。未归档的域(team / skill_selection / memory / 观测性 / …)不等于不存在,+只等于还没有契约文档;动这些域时同样遵循"机制横跨多个子树"的找代码方式(subagent 域横跨 openjiuwen SDK 机制主体与server 装配层;中断交互域的原语层在 agent-core `openjiuwen`、守卫与结算层在 serverruntime——spec 关联模块按仓分列;事件流域的正向通道底层在 agent-core stream 队列、-消费侧在 server runtime),新增 spec 从 S_22 起编(编号跨域连续,不复用)。+消费侧在 server runtime),新增 spec 从 S_23 起编(编号跨域连续,不复用)。修改任何代码前先读对应 spec;改规约本身必须同步 specs(三条强制约束见文末)。-## Specs 索引(任务规划域 S_01~S_06 + 可靠性域 S_07~S_10 + subagent 域 S_11~S_14 + 中断交互域 S_15~S_19 + 事件流域 S_20~S_21)+## Specs 索引(任务规划域 S_01~S_06 + 可靠性域 S_07~S_10 + subagent 域 S_11~S_14 + 中断交互域 S_15~S_19 + 事件流域 S_20~S_21 + 原生多模态图像输入 S_22)- `docs/specs/S_01_todo-storage-and-toolchain.md` — todo.json 整表存储、stock 四工具行为、代际 token、todo_compat monkeypatch 装配时序- `docs/specs/S_02_task-execution-rail.md` — TaskExecutionRail 全景:状态→事件映射、串行顺序约束、auto_advance / lazy_start、产物检测、代际过滤@@ -46,6 +47,7 @@ runtime——spec 关联模块按仓分列;事件流域的正向通道底层- `docs/specs/S_19_cancellation-settlement-and-finalization.md` — 取消结算与收尾(server runtime):三级 settle 入口、纯 confirm 本地判定、合法 ToolMessage 插入(不产孤儿)、三通道降级写入、清键与持久化、`{id}#{n}` 序号代际- `docs/specs/S_20_stream-event-emission-channel.md` — 事件流主通道与发射契约:agent-core stream 底层(三 schema / END_FRAME / 队列重试与强清)、六类事件发射时机、sid 解析三序、cwd rebind 双模式、symphony 工具进度桥接、装配挂载七处、消费侧终态判定- `docs/specs/S_21_pause-checkpoints-and-context-repair.md` — 暂停检查点与上下文修复:pause/resume/abort 状态机(shell 进程树击杀)、per-session 六字典、早 checkpoint(post_agent_execute 不关流)、取消结果收集、占位检测(legacy 7 类文案)、call_goal 注入剥离(deepcopy 防泄漏)、SkillTurbo HITL 改写、上下文修复四计数+- `docs/specs/S_22_native-multimodal-image-input.md` — 原生多模态图片输入:引用行 / 上传清单通道、能力位单一真源(modalities)、发送前像素物化 / 视图剥离、预算与状态行、工具侧护栏、team 成员的 N10 三要素(能力位 + rail + 清单,含 leader 分发提示 dispatch_hint、成员确定性分发的边界提及判定与 attached/omitted 幂等、live 清单只在开新轮的请求绑定)## 统一术语表@@ -169,7 +171,7 @@ agents/harness/│ ├── rails/ # task_execution_rail(S_02)+ 可靠性域(S_07 重试与溢出恢复 / S_08 熔断 execution_guard/ / S_09 并发安全 / S_10 配额 rail 与输入守卫纯函数库)+ subagent 域(S_13 subagent_skill_authorization_rail / subagent_permission_rail、S_14 browser_task_prompt_rail)+ 中断交互域(S_15/S_17 ask_user_rail、S_17 interrupt/ 子树 interrupt_helpers 与 permissions/ 子树 config_loader / owner_scopes / tool_permission_context)+ 事件流域(S_20/S_21 stream_event_rail、symphony/tool_stream_events)+ 模型路由 / symphony 编排等│ ├── tools/ # todo_resume / todo_compat / user_todo_tool(S_01/S_05)/ deepresearch/(S_06)/ subagent_compat.py(S_12 类替换)/ subagent_executor/(S_13/S_14 授权 wiring 与委托边界)/ web_search / xiaoyi_phone_tools 等 40+ 件│ └── … # auto_harness/ auto_memory/ long_horizon/ memory/ plugins/ prompt/ recommendation/ skill_sleep/(未归档域)-├── docs/ # 归档规约 AGENTS.md + specs/(S_01~S_21)+├── docs/ # 归档规约 AGENTS.md + specs/(S_01~S_22)├── flash/ # flash profile 挂件│ ├── permissions/ # tool_policy_projection(S_05 统一名权限投影三段式)/ flash_permission_rail / skill_install│ ├── rails/ # flash_todo_rail(S_05)/ flash_subagent_rail(S_11/S_14 flash 变体三差异)/ flash_delivery_summary / flash_memory / slim_sys_operation@@ -182,7 +184,7 @@ agents/harness/## 架构铁律-从二十一份 specs 的不变量中提炼的跨 spec 最高优先级约束。逐条细则以回链 spec 为准。+从二十二份 specs 的不变量中提炼的跨 spec 最高优先级约束。逐条细则以回链 spec 为准。1. **代际 token 单向流**:agent-core 侧只读 token 打标过滤,写侧唯一 bump 点是`todo_resume.bump_todo_generation_token`。新增任何"重置任务列表"的路径必须走 bump,diff --git a/jiuwenswarm/agents/harness/common/multimodal/__init__.py b/jiuwenswarm/agents/harness/common/multimodal/__init__.pyindex 87c0e19672..327d6253da 100644--- a/jiuwenswarm/agents/harness/common/multimodal/__init__.py+++ b/jiuwenswarm/agents/harness/common/multimodal/__init__.py@@ -40,6 +40,7 @@ from .image_history import (_set_message_content,_slot_image_part,ensure_multimodal_image_filter_window_mutator,+ ensure_manifest_images_referenced,inject_image_content_from_references,remove_multimodal_image_filter_window_mutator,)@@ -90,6 +91,7 @@ from .image_reference import (_message_omitted_image_reasons,_normalize_image_file,_normalize_image_files,+ augment_message_with_reference_lines,build_image_reference_line,collect_image_references_from_messages,collect_omitted_image_paths,@@ -98,11 +100,16 @@ from .image_reference import (current_multimodal_image_files_from_agent,extract_multimodal_image_files,is_provided_image_path,+ normalize_image_mention_text,normalize_image_path,+ normalized_text_mentions_image,parse_image_references,reset_current_multimodal_image_files,set_current_multimodal_image_files,store_current_multimodal_image_files_on_agent,+ store_team_request_image_files,+ team_request_image_files,+ text_mentions_image,)__all__ = [@@ -169,6 +176,7 @@ __all__ = ["_shrink_image_to_bytes","_slot_image_part","_text_from_content_part",+ "augment_message_with_reference_lines","build_image_reference_line","collect_image_references_from_messages","collect_omitted_image_paths",@@ -177,6 +185,7 @@ __all__ = ["current_multimodal_image_files","current_multimodal_image_files_from_agent","ensure_multimodal_image_filter_window_mutator",+ "ensure_manifest_images_referenced","estimate_image_visual_tokens","extract_multimodal_image_files","filter_image_content_from_view",@@ -184,12 +193,17 @@ __all__ = ["is_image_content_block","is_provided_image_path","is_user_authored_message",+ "normalize_image_mention_text","normalize_image_path",+ "normalized_text_mentions_image","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",+ "store_team_request_image_files","strip_image_content_blocks",+ "team_request_image_files",+ "text_mentions_image",]diff --git a/jiuwenswarm/agents/harness/common/multimodal/image_history.py b/jiuwenswarm/agents/harness/common/multimodal/image_history.pyindex 07e9f8a1ff..49ac0be669 100644--- a/jiuwenswarm/agents/harness/common/multimodal/image_history.py+++ b/jiuwenswarm/agents/harness/common/multimodal/image_history.py@@ -38,7 +38,9 @@ from jiuwenswarm.agents.harness.common.multimodal.image_reference import (_normalize_image_file,build_image_reference_line,current_multimodal_image_files,+ normalize_image_mention_text,normalize_image_path,+ normalized_text_mentions_image,parse_image_references,)from jiuwenswarm.common.utils import logger@@ -397,6 +399,126 @@ def _append_image_part(message: Any, index: int, data_uri: str) -> None:)+def _processed_image_paths(messages: list[Any]) -> set[str]:+ """历史里已被处理过(``attached`` ∪ ``omitted``)的上传图路径集合。++ 为什么 ``omitted`` 也算已处理:被预算淘汰 / 读取失败写下的+ ``[image #n omitted: ...]`` 是「这张图这轮没给」的既成事实(N5 状态行就是权威+ 记录)。若只把 ``attached`` 当已处理,下一次 ``before_model_call`` 还会在上下文+ 里命中同一路径 → 再补一条引用行、再读一次盘、再写一条 ``omitted``,每次 LLM+ 迭代重复一遍,上下文无界膨胀。``omitted: duplicate`` 同理是终态(同一路径已由+ 别的消息提供过像素)。++ 状态行与引用行按消息作用域配对(同一条消息里的 index→path):压缩把老消息搬进+ 摘要后,新消息里的同号引用不会被老状态行误判成「已处理」。+ """++ processed: set[str] = set()+ for message in messages:+ if not is_user_authored_message(message):+ # 引用行只认 user 消息:tool result / assistant 文本里的同格式行不参与+ # 状态配对,否则被读到的文件内容可以伪造成「已处理」改变图片分发决策。+ continue+ text = _content_to_query_text(_message_content(message))+ if not text:+ continue+ states = _message_image_states(message)+ if not states:+ continue+ refs = {+ int(ref.get("index", -1)): str(ref.get("path") or "")+ for ref in parse_image_references(text)+ }+ for index in states:+ path = refs.get(index)+ if path:+ processed.add(normalize_image_path(path))+ return processed+++def ensure_manifest_images_referenced(+ messages: list[Any],+ image_files: list[dict[str, Any]] | None,+ *,+ max_images: int = 4,+) -> int:+ """成员侧确定性分发:清单里的图在上下文任意位置被提到时,补成引用行。++ 为什么需要:team leader 常把图片路径只写进任务看板(tool result,不物化)或只在+ 消息里留 ``[image #...] path=...`` 占位符;成员侧注入只认 user 消息里的真实引用行。+ 这里扫描**全部消息文本**(含 tool result——只用于判断"提到了哪张图",不把 tool+ result 内容当引用行来源),命中本轮上传清单的文件名 / 完整路径后,把对应引用行追加+ 到最近一条 user 消息末尾,交给 ``inject_image_content_from_references`` 统一物化。+ 提及判定走 ``normalized_text_mentions_image``(分隔符 / 大小写归一 + 边界对齐):+ ``1.png`` 不会被 ``11.png`` / ``data.png`` 误命中,Windows 反斜杠路径形态也能命中。+ 每条消息的文本只归一一次再对清单图复用——本函数每次模型调用都跑,逐图重复 lower+ 全量消息(含 60k 级 tool result)会抵消「不做全量扫描」的优化。++ 幂等:已有 ``attached`` / ``omitted`` 状态行(含 ``omitted: duplicate``)的路径是+ 终态,不重复补;``max_images`` 限单次补几张。返回本次补了几张。+ """++ files = [_normalize_image_file(item) for item in (image_files or [])]+ files = [item for item in files if item]+ if not files:+ return 0+ # 清单图全部已处理时直接返回:本函数在每次模型调用(before_model_call)都跑,+ # 把「已处理」判定提到对全部消息的文本扫描之前,稳定状态下不再做小写全量匹配。+ processed = _processed_image_paths(messages)+ files = [+ image+ for image in files+ if normalize_image_path(str(image.get("path") or "")) not in processed+ ]+ if not files:+ return 0+ used: set[int] = set()+ mentioned: list[dict[str, Any]] = []+ # 归一文本按「消息」缓存(不是按「图片」):同一段 tool result 可能很长,逐图重复+ # 替换反斜杠 + 小写会把本函数退化成 N 张图 × 全量文本的扫描。+ normalized_texts: list[str] = []+ for message in messages:+ text = _content_to_query_text(_message_content(message))+ if text:+ normalized_texts.append(normalize_image_mention_text(text))+ for ref in parse_image_references(text):+ used.add(int(ref.get("index", 0)))+ for index in _message_image_states(message):+ used.add(int(index))+ cap = max(0, int(max_images or 0))+ for image in files:+ if len(mentioned) >= cap:+ break+ path = str(image.get("path") or "").strip()+ if not path:+ continue+ if any(+ normalized_text_mentions_image(image, normalized_text)+ for normalized_text in normalized_texts+ ):+ mentioned.append(image)+ if not mentioned:+ return 0+ target = next(+ (message for message in reversed(messages) if is_user_authored_message(message)),+ None,+ )+ if target is None:+ return 0+ next_index = (max(used) + 1) if used else 1+ lines = []+ for image in mentioned:+ lines.append(build_image_reference_line(image, next_index))+ next_index += 1+ _append_parts(target, [{"type": "text", "text": "\n" + "\n".join(lines)}])+ logger.info(+ "[ensure_manifest_images_referenced] referenced %d manifest image(s)",+ len(mentioned),+ )+ return len(mentioned)+++def _collect_image_slots(messages: list[Any]) -> list[dict[str, Any]]:"""收集历史里活着的图片块及其配对状态行,供预算按「最老优先」卸载。diff --git a/jiuwenswarm/agents/harness/common/multimodal/image_reference.py b/jiuwenswarm/agents/harness/common/multimodal/image_reference.pyindex 25ab04c1ff..57de86ab1a 100644--- a/jiuwenswarm/agents/harness/common/multimodal/image_reference.py+++ b/jiuwenswarm/agents/harness/common/multimodal/image_reference.py@@ -164,12 +164,167 @@ def current_multimodal_image_files_from_agent(agent: Any) -> list[dict[str, Any]return list(value)+# 「本轮上传清单」随 build context 传给 team 成员的键。team 成员 agent 不是 adapter+# 的 ``self._instance``(agent 属性镜像拿不到),ContextVar 也跨不到成员自己的任务,+# 唯一可达通道是 ``SwarmBuildContext.request_metadata``——与 ``enable_routing`` 同一做法。+# 写侧必须在 adapter/team_helpers 里用真实上传清单覆盖写(同一键由请求 metadata 透传时+# 可能是外部输入,不能被当成清单信任)。+_TEAM_REQUEST_IMAGE_FILES_KEY = "multimodal_image_files"+++def store_team_request_image_files(+ request_metadata: Any, image_files: list[dict[str, Any]] | None+) -> None:+ """把本轮上传清单写进 ``request_metadata``(覆盖写,空列表即清除上一轮残留)。"""++ if not isinstance(request_metadata, dict):+ return+ request_metadata[_TEAM_REQUEST_IMAGE_FILES_KEY] = _normalize_image_files(+ image_files or []+ )+++def team_request_image_files(request_metadata: Any) -> list[dict[str, Any]] | None:+ """读 ``request_metadata`` 里的上传清单;从未写入 → None(调用方自行回退)。"""++ if not isinstance(request_metadata, dict):+ return None+ raw = request_metadata.get(_TEAM_REQUEST_IMAGE_FILES_KEY)+ if not isinstance(raw, list):+ return None+ return [dict(item) for item in raw if isinstance(item, dict)]++def normalize_image_path(path: str) -> str:"""把图片路径归一为可比较的 key(大小写 / 相对段 / ``~`` 展开)。"""return os.path.normcase(os.path.realpath(os.path.expanduser(str(path or "").strip())))+# 图片提及的「文件名类字符」:字母 / 数字 / 下划线 / 连字符。命中片段前后若是这些+# 字符,说明它只是另一个更长文件名的一部分(``1.png`` vs ``11.png``、``a.png`` vs+# ``data.png``),不是同一张图。+_IMAGE_MENTION_BOUNDARY = r"[0-9A-Za-z_\-]"+++def normalize_image_mention_text(text: str) -> str:+ """把任意文本归一成图片提及的比较形态:``\\`` → ``/`` 且小写。++ 为什么不用 :func:`normalize_image_path`:这里比较的是**自由文本**(消息正文 /+ 工具结果)里的片段,realpath 会把正文里的相对段 / ``~`` 一并改写;而 POSIX 上+ ``os.path.normcase`` 是恒等,无法把 Windows 反斜杠路径与正斜杠文本对齐。这里+ 只做「分隔符 + 大小写」两项归一,保证两种形态互认。+ """++ return str(text or "").replace("\\", "/").lower()+++def _image_mention_pattern(needle: str) -> re.Pattern[str] | None:+ """把路径 / 文件名编译成带边界的提及正则;空串返回 None。"""++ normalized = normalize_image_mention_text(needle).strip()+ if not normalized:+ return None+ return re.compile(+ rf"(?<!{_IMAGE_MENTION_BOUNDARY}){re.escape(normalized)}(?!{_IMAGE_MENTION_BOUNDARY})"+ )+++def normalized_text_mentions_image(image: dict[str, Any], normalized_text: str) -> bool:+ """在**已归一**的文本里判断是否提到该图(完整路径或 basename 文件名)。++ 归一(``\\`` → ``/`` + 小写)由调用方用 :func:`normalize_image_mention_text` 做一次。+ 为什么单独暴露:``ensure_manifest_images_referenced`` 要在每次模型调用、最多 N 张图+ × 全量消息(含 60k 级 tool result)上循环,逐 (image, text) 组合归一等于每张图都+ 重扫一遍大文本;先对每条消息归一一次再对多张图复用,才能保住 Nice-2 的+ 「不做全量重复小写扫描」。+ """++ path = str(image.get("path") or "").strip()+ path_pattern = _image_mention_pattern(path)+ if path_pattern is not None and path_pattern.search(normalized_text):+ return True+ # filename 按 basename 形态比较:上传方可能把带目录的名字原样透传,也可能给图改名+ # (filename 与路径 basename 不同),两种形态都只按末段文件名判定。+ filename = str(image.get("filename") or "").strip()+ if not filename:+ filename = path+ filename = os.path.basename(normalize_image_mention_text(filename))+ filename_pattern = _image_mention_pattern(filename)+ return bool(filename_pattern is not None and filename_pattern.search(normalized_text))+++def text_mentions_image(image: dict[str, Any], text: str) -> bool:+ """判断文本是否提到清单里的这张图(完整路径或文件名,边界对齐)。++ 为什么不用裸 ``in``:清单 ``1.png`` 会在 ``11.png`` / ``data.png`` 里命中(子串),+ 清单 ``C:/uploads/3.jpg`` 在 Windows 反斜杠形态的正文里又命中不了(只能靠文件名+ 兜底,路径命中整体失效)。这里先统一分隔符 / 大小写,再要求命中片段前后不是+ 文件名类字符:``请识别3.jpg`` 仍命中,``1.png`` 不再误命中 ``11.png``。+ 单条文本的便捷封装;批量场景(同一文本要对多张图判定)请先归一一次,再走+ :func:`normalized_text_mentions_image`,避免每张图重复归一同一段大文本。+ """++ normalized_text = normalize_image_mention_text(text)+ if not normalized_text:+ return False+ return normalized_text_mentions_image(image, normalized_text)+++_DISPATCH_REFERENCE_RE = re.compile(r"\[image #\d+\]\s+path=(.+?)\s+filename=")+++def augment_message_with_reference_lines(+ content: str,+ image_files: list[dict[str, Any]] | None,+ *,+ max_images: int = 4,+) -> str:+ """把成员消息里"只提了文件名 / 路径"的上传图补成完整引用行(leader 分发兜底)。++ 为什么需要:team leader 常把图片路径写进任务看板(tool result,不物化)或只写+ "识别 3.jpg",成员侧的注入只认 user 消息里的 ``[image #n] path=...`` 引用行。+ 这里按**文件名 / 完整路径**把本轮上传清单中对应的图补成引用行,追加到消息正文;+ 只有真正被提到的图才补,不会把整批上传清单塞给任意成员。提及判定走+ :func:`text_mentions_image`(分隔符 / 大小写归一 + 边界对齐),避免 ``1.png``+ 被 ``11.png`` 之类的子串误命中。++ 幂等:消息里已有同一路径的引用行时不重复追加;``max_images`` 限单条消息补几张。+ """++ if not isinstance(content, str) or not content.strip():+ return content+ images = image_files or []+ if not images:+ return content+ already: set[str] = set()+ for match in _DISPATCH_REFERENCE_RE.finditer(content):+ already.add(normalize_image_path(match.group(1)))+ next_index = 1+ used = [int(i) for i in re.findall(r"\[image #(\d+)\]", content)]+ if used:+ next_index = max(used) + 1+ appended: list[str] = []+ for image in _normalize_image_files(images):+ if len(appended) >= max(0, int(max_images or 0)):+ break+ path = str(image.get("path") or "").strip()+ if not path:+ continue+ key = normalize_image_path(path)+ if key in already:+ continue+ if not text_mentions_image(image, content):+ continue+ appended.append(build_image_reference_line(image, next_index))+ already.add(key)+ next_index += 1+ if not appended:+ return content+ return content.rstrip() + "\n" + "\n".join(appended)+++def is_provided_image_path(path: str, provided_paths: Any) -> bool:"""判断 path 是否落在「本次请求已随消息提供像素」的路径集合内。diff --git a/jiuwenswarm/agents/harness/common/rails/multimodal_image_rail.py b/jiuwenswarm/agents/harness/common/rails/multimodal_image_rail.pyindex e86386c1c5..a083fef8fa 100644--- a/jiuwenswarm/agents/harness/common/rails/multimodal_image_rail.py+++ b/jiuwenswarm/agents/harness/common/rails/multimodal_image_rail.py@@ -13,11 +13,13 @@ from openjiuwen.harness.prompts.prompt_attachment_manager import PromptAttachmenfrom openjiuwen.harness.rails.base import DeepAgentRailfrom jiuwenswarm.agents.harness.common.multimodal import (+ augment_message_with_reference_lines,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,+ ensure_manifest_images_referenced,inject_image_content_from_references,remove_multimodal_image_filter_window_mutator,)@@ -62,12 +64,24 @@ class MultimodalImageRail(DeepAgentRail):max_total_bytes: int = 0,max_visual_tokens: int = 0,max_count: int = 0,+ image_files: list[dict[str, Any]] | None = None,+ dispatch_hint: bool = False,) -> None:super().__init__()self._enable_image_multimodal = enable_image_multimodalself._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))+ # 装配期绑定的上传清单(None = 未绑定,回退 agent 实例属性)。+ # 只有「rail 在成员 agent 之外计算清单」的装配方(team 成员由 swarm+ # provider 构造)才显式传:清单在 rail 构造时快照,每轮重建即刷新。+ self._bound_image_files: list[dict[str, Any]] | None = (+ [dict(item) for item in image_files if isinstance(item, dict)]+ if image_files is not None+ else None+ )+ # leader 专用提示:把图片交给成员时如何转述引用行(否则成员拿不到像素)。+ self._dispatch_hint = bool(dispatch_hint)self._deep_agent: Any | None = Noneself._system_prompt_builder: Any | None = Noneself._attachment_manager: Any | None = None@@ -86,6 +100,23 @@ class MultimodalImageRail(DeepAgentRail):)return bool(getattr(deep_config, "enable_read_image_multimodal", False))+ def _resolve_request_image_files(self) -> list[dict[str, Any]] | None:+ """返回本次请求的上传清单;``None`` 表示未绑定、回退 ContextVar。++ team 成员(leader)的清单由 adapter 写进 build context,provider 在+ rail 构造时快照传入——成员 agent 不是 adapter 的 ``self._instance``,+ agent 属性镜像拿不到;返回 ``[]`` 是权威事实(本轮没有新上传),+ 不能让 inject 回退到 ContextVar 读到别的轮次残留。+ """+ if self._bound_image_files is not None:+ return [dict(item) for item in self._bound_image_files]+ return current_multimodal_image_files_from_agent(self._deep_agent)++ def _is_team_member_rail(self) -> bool:+ """是否是 team 成员(非 leader)的 rail:绑定清单且无 leader 分发提示。"""++ return self._bound_image_files is not None and not self._dispatch_hint+def _sync_image_policy_section(self, enabled: bool, images_sent: int) -> None:"""按「这次到底有没有把像素发出去」写策略段。@@ -105,6 +136,32 @@ class MultimodalImageRail(DeepAgentRail):# 段不存在或 builder 未实现移除时不影响本轮注入,仅记录便于定位。logger.warning("remove %s section failed", section_name, exc_info=True)if enabled and images_sent <= 0:+ if not self._is_team_member_rail():+ return+ # team 成员:还没有像素,但任务里常只给本地路径。最好走 read_file——+ # read_file 的原生读图 resolver 读 deep_config,会把图片以图像内容返回给+ # 原生模型;不引导的话成员会惯性调用 VQA/OCR(线上 trace 已多次复现)。+ path_cn = (+ "本次请求可能涉及本地图片。如果上下文中出现图片文件路径,请直接使用 "+ "read_file 读取该路径:当前模型支持原生图片理解,read_file 会返回图像内容"+ "(不要调用 visual_question_answering / image_ocr 去读取本地文件)。"+ "只有远程 URL、或读取失败导致没有像素时,才使用视觉工具兜底。"+ )+ path_en = (+ "This request may involve local image files. When a local image path appears "+ "in the context, call read_file on it directly: the current model supports "+ "native image understanding and read_file returns image content (do not use "+ "visual_question_answering / image_ocr to read local files). Use a vision tool "+ "only for remote URLs or when reading failed and no pixels are available."+ )+ try:+ builder.add_section(PromptSection(+ name=section_name,+ content={"cn": path_cn, "en": path_en},+ priority=96,+ ))+ except Exception:+ logger.warning("add %s section failed", section_name, exc_info=True)returnnative_cn = ("本次请求可能包含用户上传的图片。当前模型支持原生图片理解,"@@ -117,6 +174,20 @@ class MultimodalImageRail(DeepAgentRail):"Use your vision capability directly; do not call visual_question_answering ""or image_reading tools.")+ if self._dispatch_hint:+ # team leader 专用:图片要交给成员处理时,必须把引用行原样转述到成员能读到+ # 的消息通道(send_message)。只给绝对路径 / 只写进任务看板都不物化像素。+ native_cn += (+ "\n\n如果要把本次请求中的图片交给团队成员处理,请用 send_message 在消息正文中"+ "原样保留该图的 `[image #n] path=... filename=... mime=...` 引用行——成员据此"+ "直接查看像素。只给文件路径、或只写进任务看板正文时,成员看不到图片内容。"+ )+ native_en += (+ "\n\nTo hand one of these images to a teammate, keep its "+ "`[image #n] path=... filename=... mime=...` reference line verbatim in the "+ "send_message body — the teammate needs that line to see the pixels. A bare "+ "file path, or a path only written into the task board, gives it no image."+ )fallback_cn = ("本次请求可能包含用户上传的图片。当前模型不支持原生图片理解;""如需理解图片内容,请调用 visual_question_answering 或 image_reading 工具。"@@ -399,12 +470,26 @@ class MultimodalImageRail(DeepAgentRail):has_image_references = bool(collect_image_references_from_messages(list(messages)))+ # 成员侧确定性分发:leader 只把路径写进任务看板 / 只留占位符时,成员上下文+ # 里提到清单图(文件名 / 完整路径)也应直接看像素,而不是回退 VQA。+ if self._is_team_member_rail():+ try:+ ensured = ensure_manifest_images_referenced(+ list(messages), self._bound_image_files+ )+ if ensured:+ has_image_references = bool(+ collect_image_references_from_messages(list(messages))+ )+ except Exception as exc: # pragma: no cover - 防御:补引用失败不阻断注入+ logger.warning(+ "[MultimodalImageRail] ensure manifest image references failed: %s",+ exc,+ )try:messages, attached = inject_image_content_from_references(list(messages),- image_files=current_multimodal_image_files_from_agent(- self._deep_agent- ),+ image_files=self._resolve_request_image_files(),max_total_bytes=self._max_total_bytes,max_visual_tokens=self._max_visual_tokens,max_count=self._max_count,@@ -506,3 +591,57 @@ class MultimodalImageRail(DeepAgentRail):logger.info("[MultimodalImageRail] after_model_call final_window_images=%d", images_sent)++ async def before_tool_call(self, ctx: AgentCallbackContext) -> None:+ """leader 给成员发消息时,把"只提了文件名 / 路径"的上传图补成引用行。++ 为什么需要:提示词只要求 leader 用 send_message 保留引用行,但实测它常把+ 引用行写进任务看板(tool result,不物化)、消息里只写 "识别 3.jpg"。这里在+ 工具执行前按本轮上传清单补引用行——只有消息真正提到的图才补,广播 / 回用户+ 不补(避免把清单发给无关成员或用户)。成员侧仍由安全门按清单 ∩ 引用行物化。+ """++ if not self._dispatch_hint:+ return+ try:+ inputs = getattr(ctx, "inputs", None)+ tool_call = getattr(inputs, "tool_call", None)+ tool_name = str(+ getattr(inputs, "tool_name", "") or getattr(tool_call, "name", "") or ""+ )+ if tool_name != "send_message":+ return+ arguments = getattr(tool_call, "arguments", None)+ if not isinstance(arguments, dict):+ return+ target = arguments.get("to")+ if isinstance(target, str):+ if target.strip() in {"", "*", "user"}:+ return+ elif isinstance(target, (list, tuple)):+ names = [str(item or "").strip() for item in target]+ if not names or any(name in {"", "*", "user"} for name in names):+ return+ else:+ return+ content = arguments.get("content")+ if not isinstance(content, str) or not content.strip():+ return+ updated = augment_message_with_reference_lines(+ content, self._resolve_request_image_files()+ )+ if updated == content:+ return+ arguments["content"] = updated+ if tool_call is not None:+ tool_call.arguments = arguments+ if inputs is not None:+ inputs.tool_args = arguments+ logger.info(+ "[MultimodalImageRail] dispatch message augmented with image reference lines"+ )+ except Exception as exc: # pragma: no cover - 旁路失败不阻断工具调用+ logger.warning(+ "[MultimodalImageRail] augment dispatch message failed: %s", exc+ )+diff --git a/jiuwenswarm/agents/harness/docs/bugfix/B_05_team-native-multimodal-image-input.md b/jiuwenswarm/agents/harness/docs/bugfix/B_05_team-native-multimodal-image-input.mdnew file mode 100644index 0000000000..99fb33850b--- /dev/null+++ b/jiuwenswarm/agents/harness/docs/bugfix/B_05_team-native-multimodal-image-input.md@@ -0,0 +1,304 @@+# B_05 — team 模式原生多模态未生效:leader 没挂 rail、能力位默认 False、上传清单到不了成员++## 元信息++| 项 | 值 |+|---|---|+| 类型 | bugfix |+| 编号 / slug | B_05 / team-native-multimodal-image-input |+| 关联模块 | `jiuwenswarm/agents/swarm/config_specs.py`、`jiuwenswarm/agents/swarm/providers/multimodal.py`(新增)、`jiuwenswarm/agents/swarm/registry.py`、`jiuwenswarm/agents/harness/common/rails/multimodal_image_rail.py`、`jiuwenswarm/agents/harness/common/multimodal/image_reference.py`、`jiuwenswarm/server/runtime/agent_adapter/interface_deep.py`、`jiuwenswarm/server/runtime/agent_adapter/team_helpers.py` |+| 修复日期 | 2026-11-05 |+| 复查修复日期 | 2026-11-06(PR !9634 检视意见,见「复查修复」一节;S_22 同轮修订至 2026-11-06) |+| 关联 spec | [[S_22]](本修复为该 spec 增补 N10 / P9 / team 契约;S_22 修订日期 2026-11-05,复查后为 2026-11-06) |+| 关联测试 | `tests/agents/swarm/test_team_multimodal_image.py`、`tests/unit_tests/agents/harness/common/multimodal/test_team_image_manifest.py`、`tests/unit_tests/agents/harness/common/multimodal/test_manifest_mention_injection.py`(复查修复)、`tests/unit_tests/agents/harness/common/multimodal/test_image_reference.py`(复查修复)、`tests/unit_tests/agents/harness/common/rails/test_multimodal_image_rail_bound_files.py`、`tests/unit_tests/agentserver/test_team_multimodal_round_manifest.py`、`tests/unit_tests/agentserver/test_evolve_command_edges.py`(team 图片引用投影) |++## 复现场景++现场会话 `web_1a1aab89656_75803007d563`(`mode=team`,团队+`image-recognition-squad_2_...`)里,用户上传 `0.jpg` / `1.jpg` 并要求识别。响应表面正常+(模型描述了幼兔、水印、昵图网 ID),但 trace 显示识别全部来自+`visual_question_answering` 工具,**原生图片输入从未发生**:++- 该会话 trace(`~/.jiuwenswarm/.trace/sessions/...sqlite3`,trace id+ `9a1546c5c411d6d427091ff786c5510f`)里 9 个 `context.window.commit` 窗口(leader 4 /+ vision-analyst 5)**image 块全部为 0**;leader 的 user 消息只有+ `[image #1] path=...` 文本引用行;+- 系统提示里没有 `multimodal_image_policy` 段、运行时附件里没有+ `runtime.image_state`,即 `MultimodalImageRail.before_model_call` 在成员 agent 上从未运行;+- 对照:同机 166 个会话 trace 中,非 team 的 164 个里有 54 个出现 image 块(单 agent+ 正常),2 个 team 会话全部为 0。++**跟进复核 1(2026-11-05,`web_1a1ab96b56d_9a035826e524`,leader-only 版本)**:leader+侧已正常(9 个窗口 image 块=2、`attached` 行与"本次请求附带图片:2 张"附件齐全,leader 未再+调用 VQA/OCR,直接凭像素写出 2.jpg 描述);但同队 `image-recognizer` 10 个窗口全部+image 块=0、无引用行,仍靠 `visual_question_answering`/`image_ocr`/PIL 裁剪,并再派+general-purpose 子代理重复读图(30 次 LLM 调用)。据此把 rail 扩到全成员并补 leader+分发提示(见「修复口径」第 2、4 条)。++**跟进复核 2(2026-11-05,`web_1a1abb54384_ffb778318a1a`,全成员 rail + dispatch_hint 版本)**:+leader 仍正常(8 个窗口 image 块≥2;`create_task` 正文已带完整+`[image #2] path=...` 引用行);但 teammate(`vision-analyst`)13 个窗口 image 块全 0。+直接原因:引用行只落在 **`create_task` 任务正文**(teammate 通过 `view_task` 的 tool result+读取,不物化),而 leader 的 `send_message` 正文只有 `[image #...] path=...` **占位符**,+teammate 的 user 消息里没有任何可解析引用行 → 团员继续 VQA/OCR。+注:该 trace 的 system message 长度恒为 10266,无法从 trace 证明系统提示里有没有分发提示,+只能确认"最终 user 消息里没有引用行"这一事实。据此增加 `before_tool_call` 确定性兜底+(`send_message` 正文自动补引用行)与成员侧确定性分发(`before_model_call` 扫上下文提到+的清单图、补引用行后物化),使"模型声明原生 + 图在本轮清单内"不再依赖 leader 消息格式。++## 根因++team 成员的装配链与单 agent 不同,原生图片的三要素在这条链上**三处同时断裂**:++1. **rail 没挂**:单 agent 的 rails 在 `interface_deep._build_agent_rails` 里含+ `_multimodal_image_rail`;team 成员的 rails 由 `agents/swarm/config_specs.py` 声明式装配+ (`_COMMON_RAIL_NAMES` / `_build_team_capability_specs`),其中没有 multimodal rail,+ swarm provider 里也没有对应实现。+2. **能力位默认 False**:openjiuwen `agent_configurator` 对成员+ `enable_read_image_multimodal is None` 一律兜底 False(省掉每成员一次探测 LLM 往返),+ 而 `build_member_deep_agent_spec` 从不写该字段——即便 rail 挂上也会走非原生分支。+3. **上传清单到不了成员**:adapter team 分支只把清单镜像到 `self._instance`(adapter 自己的+ DeepAgent)并 set 请求级 ContextVar;team leader 是 Runner 另建的成员 agent,两者都拿不到,+ 而 `inject_image_content_from_references` 的安全门要求"路径必须在本次上传清单内",+ 于是所有引用行被当作 non-uploaded 跳过(静默 0 张)。++## 修复口径++三要素按 N10 成对补齐,只补其一仍会 0 张:++1. **能力位(声明式,不探测)**:`config_specs._resolve_member_native_image_enabled` 按成员+ 模型条目(成员 spec 指定模型则按名匹配 `models.defaults`,否则回退默认条目)的+ `modalities` 解析,`build_member_deep_agent_spec` 显式写+ `update["enable_read_image_multimodal"]`;blueprint 已显式写该字段时以显式值优先。+ (复查修复后:指定模型名未命中条目 → False + warning、不回落默认条目,见「复查修复」+ Nice 条。)+2. **rail(全成员)**:新增 `swarm.multimodal_image` provider+ (`agents/swarm/providers/multimodal.py`,已进 registry 与 catalog);`build_member_deep_agent_spec`+ 为**每个成员**(leader / teammate / 命名成员)声明该 RailSpec,params 携带能力位与+ `react.multimodal_image_*` 三预算。leader 额外带 `dispatch_hint=True`(见第 4 条)。+ 授权边界不在挂载处而在物化处:成员只会物化"本轮上传清单内 + 自己历史里 user-authored+ 引用行"的图;任务看板 / 工具结果里的纯路径不物化。+3. **清单(build context 通道)**:`MultimodalImageRail.__init__` 新增可选 `image_files`+ 与 `_resolve_request_image_files()`(绑定清单优先、空列表不回退 agent 属性、未绑定时+ 保持单 agent 旧行为);`image_reference` 新增+ `store_team_request_image_files` / `team_request_image_files`(覆盖写 / 读+ `request_metadata["multimodal_image_files"]`,读侧返回副本);`interface_deep` team+ 分支把 `image_files` 传入 `process_team_message_stream`;`team_helpers` 在 enrich 前+ 覆盖写 request_metadata(首轮 / 冷恢复随 fresh spec 生效),并把同一清单写进 live team+ agent 的 `harness.build_context.request_metadata`(跨轮复用 runtime 每轮据此重建+ NativeHarness,非首轮上传才能生效)。进程内 teammate 与 leader 共享同一 dict,因此+ 同轮内 spawn 的成员能读到本轮清单;子进程 / 分布式成员取 spawn 时 seed 快照(见遗留)。+4. **leader 分发提示 + 确定性兜底**:leader 的 `multimodal_image_policy` 段在原生+ 有图时追加规则:"要把图交给成员,请用 `send_message` 正文原样保留+ `[image #n] path=... filename=... mime=...` 引用行;只给路径或只写任务看板,成员看不到+ 像素。"——成员侧 rail 的物化入口仍是 user-authored 引用行,任务的工具结果通道不触发。+ 仅有提示不够(实测 leader 会把引用行只写进 `create_task`,消息里只留 `[image #...]`+ 占位符):leader rail 的 `before_tool_call` 对 `send_message` 做兜底——正文提到本轮+ 上传图的文件名 / 完整路径时,自动在正文末尾补对应引用行(广播 `to="*"` / 回用户+ `to="user"` 不改写,单条最多 4 张)。+5. **成员侧确定性分发(不依赖 leader 消息格式)**:成员 rail 在 `before_model_call`+ 扫描自身上下文(含任务看板 / `view_task` 等 tool result 文本,仅用于判断"提到了哪张+ 图"),命中本轮上传清单的文件名 / 完整路径、且该图尚未 `attached` 时,主动把引用行+ 追加到最近一条 user 消息,再走既有 inject 物化。效果:**成员模型声明原生能力 + 图在本轮+ 上传清单内**时,即使 leader 只把路径写进任务看板、消息里只有占位符,成员也能原生看图;+ 像素一旦提供,既有护栏按 S_22 N4 拒绝同一图的 VQA/OCR。幂等:已 attached 不重复补+ (复查修复后「已处理」扩为 attached ∪ omitted,见「复查修复」CR-9634-1)。+6. **成员 read_file 原生读图 + 引导**:原生开启时 `ReadFileTool` 的 resolver 每次调用读+ `deep_config.enable_read_image_multimodal`(该值已由第 1 条按成员模型写入),成员对本地+ 图片路径 `read_file` 会拿到图像内容而不是文本;成员 rail 在 `enabled` 且本轮 0 像素时写+ `multimodal_image_policy` 引导"本地路径优先 read_file,不要 VQA/OCR"。read_file 返回的+ 图片块会计入下一次 `native_images_sent`,VQA/OCR 继续被拦。这条路径弥补"清单提及未命中+ (如跨轮清单已刷新为空)"的场景。++## 验证++- 环境说明:本工作区未建 `.venv`(缺 openjiuwen / pyyaml 等),回归使用本机已装的+ 参考 Python 环境(openjiuwen 0.1.16)覆盖 rootdir 为本仓运行;目标 SDK 由 pyproject+ 指到 agent-core `dev-stable`,升级后需按 S_22 检查单复验(尤其+ `agent_configurator` 的 None 兜底与 `TeamHarness` 每轮重建语义)。+- 新增定向测试 **31 passed**:+ `tests/agents/swarm/test_team_multimodal_image.py`(11)、+ `tests/unit_tests/agents/harness/common/multimodal/test_team_image_manifest.py`(7)、+ `tests/unit_tests/agents/harness/common/rails/test_multimodal_image_rail_bound_files.py`(6)、+ `tests/unit_tests/agentserver/test_team_multimodal_round_manifest.py`(7)。+- 回归:`tests/agents/swarm` + `common/multimodal` + `common/rails` 共 **401 passed**;+ `tests/unit_tests/agentserver/test_team_helpers.py` ++ `test_deep_adapter_interrupt.py` 共 **175 passed / 1 skipped**;+ `test_evolve_command_edges.py` **22 passed**(team 图片引用 + 新增 `image_files` 传参断言);+ `tests/unit_tests/agents/harness` 全量 **435 passed / 2 failed**,失败两例为+ `test_image_tools_imports.py` 的可选依赖探测(参考环境缺 `google.genai`),与本修复无关;+ 新增 + 改动测试复跑 **72 passed**;其中分发兜底新增用例 9 条+ (`test_image_reference.py` 6 + `test_multimodal_image_rail_bound_files.py` 3)、+ 成员侧确定性分发新增 6 条(`test_manifest_mention_injection.py`)、+ 成员 read_file 引导新增 3 条(`test_multimodal_image_rail_bound_files.py`);+ 全量相关回归 **623 passed / 1 skipped**。+- 未覆盖(本机无完整依赖 / 无真实模型):端到端 team 会话真实出图;fallback notice 口径;+ 分布式 teammate 的辅助 leader(`team_manager.create_team` 的 `TeamBootstrapParams` 路径+ 不带图片清单)。++## 复查修复(PR !9634 检视意见)++首轮修复合入后收到检视意见:Should Fix 3 条(`renquanjia` 的 CR-9634-1 / CR-9634-2、+`KevinLLLove` 的 CR-9634-6)+ Nice 2 条(能力位解析)。以下按条目记录复现、根因、修复+口径与回归用例。上述改动只调整既有链路的判定与时机,**不改变**本文前面记录的+三要素装配、rail 挂载、清单通道与授权边界事实(S_22 修订日期同步为 2026-11-06)。++### CR-9634-1(Should Fix)已 `omitted` 的清单图每轮重新补引用行 + 重新物化++- **复现场景**:成员上下文里某张清单图已被预算淘汰 / 读取失败 / 判重,历史中留下+ `[image #1] path=...` 引用行 + `[image #1 omitted: request budget]` 状态行(或+ `omitted: duplicate`),而任务看板 / tool result 里仍提到该路径。下一次 LLM 迭代的+ `before_model_call` 里,成员确定性分发又补一条 `[image #2]` 引用行,+ `inject_image_content_from_references` 再读盘、缩放、编码,再写一条 `omitted`——+ 每个模型迭代重复一次,上下文无界膨胀,预算卸载过的图被反复重读重编码。+- **根因**:幂等集合由 `_attached_image_paths` 生成,只收 `attached` 状态行对应的路径;+ 预算淘汰 / 读取失败写下的 `omitted` 图(及其 `duplicate` 变体)不在集合里,因此每次+ 都被当成"还没给过"。+- **修复口径**:`_attached_image_paths` → `_processed_image_paths`,`attached` ∪ `omitted`+ (含 `omitted: duplicate`)都是终态,不再补引用行、不再物化。集合按**消息作用域**配对:+ 同一条 user 消息内用 `_message_image_states` 的状态行 index 去取同消息+ `parse_image_references` 的 index→path 映射,避免压缩把老消息搬进摘要后、新消息里的+ 同号引用被老状态行误判成"已处理";引用行仍只认 user-authored 消息(tool result /+ assistant 文本里的同格式行不得参与状态配对,否则文件内容可被伪造成"已处理")。+- **附带优化(Nice)**:`ensure_manifest_images_referenced` 先把清单按已处理集合过滤,+ 过滤后为空直接返回 0——本函数每次模型调用都跑,"清单图全部已处理"是稳定状态下的+ 常态,不必再对全部消息做归一扫描。+- **回归用例**:`test_omitted_image_is_not_rematerialized`(含 `inject_image_content_from_references`+ 断言 attached==0 且引用行未变)、`test_duplicate_omitted_image_is_not_rematerialized`。++### CR-9634-2(Should Fix)文件名裸子串匹配过宽 / Windows 路径形态命中失效++- **复现场景**:清单里是 `1.png`,tool result 出现 `11.png` 或 `data.png` → 裸 `in` 命中,+ 误补引用行并把无关图物化;反方向清单 `11.png` 也会被文本里的 `1.png` 命中。另一面:+ 清单路径 `C:/uploads/3.jpg`,正文写成 `C:\Uploads\3.JPG` 时路径比较失效(分隔符 /+ 大小写不一致),只能靠文件名兜底——图被改名(`filename` 与路径 basename 不同)即整体+ 漏判。leader 分发兜底 `augment_message_with_reference_lines` 有同类过宽匹配。+- **根因**:`hit = any(path_key in text or (filename and filename in text) ...)` 是裸子串+ 判定,既不认边界,也不做分隔符 / 大小写归一;`augment_message_with_reference_lines`+ 的 `path not in content and filename.lower() not in lower` 同理。+- **修复口径**:在 `image_reference.py` 增加共享纯函数,两个分发入口共用同一判定+ (`image_reference` 不 import `image_history`,依赖方向保持单向):+ - `normalize_image_mention_text(text)`:只做 `\` → `/` 与 lower。**不用**+ `normalize_image_path`——realpath 会改写正文里的相对段 / `~`,且 POSIX 的+ `os.path.normcase` 恒等,对齐不了 Windows 反斜杠形态;+ - `normalized_text_mentions_image(image, normalized_text)`:在**已归一**文本上按+ "完整路径 / basename" 做边界正则(`(?<![0-9A-Za-z_\-])...(?![0-9A-Za-z_\-])`),+ 供批量场景先归一一次再逐图复用;+ - `text_mentions_image(image, text)`:单条文本的便捷封装(内部归一一次)。+ 三个函数经 `multimodal/__init__.py` 导出。`ensure_manifest_images_referenced` 用前两个+ (每条消息归一一次,再对多张清单图复用);`augment_message_with_reference_lines` 改用+ `text_mentions_image`。已 attached/omitted 幂等、`max_images` 限张、序号分配、广播 /+ user 不改写等既有行为保持不变。效果:`请识别3.jpg` 仍命中(边界字符集只含 ASCII 文件名+ 类字符),`1.png` 不再命中 `11.png` / `data.png`,`C:\Uploads\3.JPG` 能命中+ `C:/uploads/3.jpg`。+- **回归用例**:`test_manifest_mention_injection.py` 的+ `test_short_filename_is_not_substring_mention`、+ `test_longer_manifest_name_is_not_matched_by_shorter_text`、+ `test_path_with_different_separator_and_case_matches`、+ `test_path_mention_matches_across_separators_without_filename_fallback`、+ `test_normalizes_each_message_text_once_for_all_images`(归一调用次数 = 消息数);+ `test_image_reference.py` 的 `test_text_mentions_image_requires_token_boundaries`、+ `test_text_mentions_image_matches_chinese_adjacent_filename`、+ `test_text_mentions_image_normalizes_separator_and_case`、+ `test_augment_ignores_substring_filename_mention`、+ `test_normalized_text_mentions_image_reuses_one_normalized_text`、+ `test_augment_matches_windows_separator_path_mention`。++### CR-9634-6(Should Fix)控制续写清空 in-flight 图片轮的 live 上传清单++- **复现场景**:"上传图片 → 成员触发权限确认 / ask_user → 用户同意继续"这一轮。控制续写+ 请求由 adapter 传 `image_files=[]`(只做作答投递、不开新轮),旧实现在 slash 处理之前+ 无条件 `await _bind_round_image_files(team_name, round_image_files)`,把 live team agent+ 的 `harness.build_context.request_metadata["multimodal_image_files"]` 覆盖写为空;随后+ 流程在 `reuse_active_waiter` 分支只把作答投递给既有 waiter 并 return。该图片轮后续新建+ 的成员 harness(或上下文溢出恢复重建)读到空清单 →+ `ensure_manifest_images_referenced` 不再补引用行、`inject_image_content_from_references`+ 把 `[image #n]` 判为"不在本轮清单内"丢弃,原生图片输入失效。slash 命令命中后的多条早退+ `return` 同理会清空。+- **根因**:清单绑定位置在任何"这个请求到底会不会开新一轮"的判定之前,且对+ `reuse_active_waiter` 没有守卫。+- **修复口径**:绑定收敛到"确实会开新一轮"的请求——移到 slash 命令处理块**之后**、投递+ query(`team_manager.interact` / `_start_team_stream_round`)**之前**,并加+ `if not reuse_active_waiter` 守卫;注释写明"为什么控制续写 / slash 不写、为什么必须在+ 投递前写"(`TeamHarness` 每轮按同一 build context 重建 NativeHarness,投递后再写赶不上+ 本轮成员的 rail 构造)。首轮 / 冷恢复(`_prepare_first_team_request` 路径的+ `request_metadata` 覆盖写)与普通 follow-up 新轮仍照常绑定;`_bind_round_image_files` /+ `_bind_round_image_files_to_agent` 自身的"覆盖写 / 空列表清除"语义不变(首轮 / 冷恢复的+ fresh spec 清理依赖它)。失败早退路径(cancel 拆除在途 / gate_closed / interact 失败)+ 仍会先写入清单,与修复前一致:这些请求不新开 round,清单不会被该轮读取,下一轮投递前+ 必再覆盖。+- **回归用例**:`test_control_continuation_keeps_live_round_manifest`(复现原故障:live+ 清单原样保留、流向 `chat.processing_status_deferred` 后 return)、+ `test_slash_command_keeps_live_round_manifest`(slash 早退不清空)、+ `test_followup_new_round_still_binds_round_manifest`(普通新轮仍在投递前绑定)。++### Nice:成员 pinned 模型名未命中不再回落默认条目++- **复现场景**:`models.defaults` 只有 `vision-model`(`modalities` 含 `image`),成员 spec+ 却 pinned 了一个未声明的模型名(拼错 / 已下线 / 只在别处声明)。旧实现按名循环未命中后+ 落到默认条目,用 `vision-model` 的能力位判 True——纯文本成员被当成视觉成员(像素塞给不+ 支持模型),反向也会把视觉成员误判成纯文本。+- **根因**:N2「模型条目是唯一依据、未声明即不支持」在"指定了模型名但查不到条目"这条分支+ 上没有落实,静默回落到"别的模型"的声明。+- **修复口径**:成员模型名按条目 `model_client_config.model_name` **或**顶层 `alias` 匹配+ (成员 spec 可能用 alias 声明);两者都未命中 → `logger.warning`(带成员模型名,便于+ 定位配置漂移)+ 返回 False,**不回落默认条目**。只有成员未指定模型时才取+ `is_default is True` 的条目(否则第一个)。显式+ `base_spec.enable_read_image_multimodal` 仍优先。+- **回归用例**:`test_unknown_pinned_model_does_not_inherit_default_modalities`(含 warning+ 文案断言)、`test_pinned_model_matches_alias`。++### Nice:能力位解析不再对模型条目 deepcopy / 解密 api_key++- **复现场景**:team 装配按「每个成员、每一轮」调用+ `_resolve_member_native_image_enabled`,旧实现每次都调 `get_default_models(config)`——+ 内部对全量模型条目 `copy.deepcopy` 并逐个解密 `api_key`,而本判定实际只需要+ `model_client_config.model_name` / `alias` / `modalities` 三个声明字段。+- **修复口径**:新增 `_declared_model_entries(config)` 直接读原始 config,选取优先级与+ `get_default_models` 一致(`models.defaults` 非空 list 优先,否则 `models.default` 单+ dict 包装;两者都没有 = env 兜底形态 → 空列表 → 能力位 False,与"未声明即不支持"一致,+ 旧 env 兜底条目本来也没有 `modalities`);移除 `get_default_models` import。`_model_entry_name`+ 接收的结构不变,仍可复用;`_multimodal_image_rail_params` / `_member_model_name` 与 rail+ 挂载逻辑不动。+- **回归用例**:`test_capability_resolution_skips_entry_copy_and_decryption`(探针对象+ `__deepcopy__` 即报错)、`test_config_without_models_section_disables_native_image`、+ `test_legacy_single_default_entry_is_honored`;既有 `test_member_model_entry_matches_by_model_name`、+ `test_leader_gets_multimodal_rail_and_capability_flag`、+ `test_explicit_spec_flag_wins_over_modalities` 等继续通过。++### 验证++- 定向复跑(`-o addopts="--asyncio-mode=auto"`):`tests/unit_tests/agents/harness/common/multimodal/`+ + `tests/unit_tests/agentserver/test_team_multimodal_round_manifest.py` ++ `tests/agents/swarm/test_team_multimodal_image.py` = **68 passed**。+- 区域回归:上述范围 + `tests/unit_tests/agents/harness/common/rails/` + `tests/agents/swarm/`+ + `tests/unit_tests/agentserver/test_team_ask_user_resend.py` = **472 passed / 2 skipped**。+- 未覆盖:与首轮修复相同——端到端真实 team 会话出图、分布式 teammate 的 spawn 快照路径+ (本复查未触及)。++## 遗留++- **teammate 原生图片的授权粒度是会话级清单 ∩ 成员引用行**:不是"按任务分配"的精确+ table——leader 若在 `send_message` 里转述了某张上传图的引用行,该成员就能看到这张图。+ 授权动作是 leader 的转述,不是 task→paths 映射;若产品要求"只有任务里指定的图才能看",+ 需另建 task→paths 授权表并在物化门里校验(不能靠放宽/收紧现有安全门实现)。+- **teammate 原生需要"图在上下文里被提到"**:成员侧确定性分发扫描文件名 / 完整路径;若+ 上下文只剩"第二张图"这类描述、任务看板也不落路径,则连 read_file 也无从定位,成员只能走+ VQA 兜底。要让这类也原生,需要 leader 在任务里落路径(提示词已要求),或另建任务↔上传关联。+- **read_file 原生读图是 tool 往返**:它依赖模型愿意调 read_file(策略段只做引导);确定性的+ 零工具轮路径仍是成员侧自动补引用行。+- **分发兜底只改单播消息**:`to="*"` 广播与 `to="user"` 不改写(避免把上传清单发给无关成员 /+ 用户);需要广播带图时由 leader 自己写引用行(成员侧仍按清单 ∩ 提及放行)。+- **成员侧扫描包含 tool result 文本**:判断"提到了哪张图"会读 tool result,但只允许清单内+ 的上传图被物化(不会内联任意本地文件);新增该行为时保持"路径必须在本轮上传清单内"这一+ 安全门,不能放宽为任意路径。+- **子进程 / 分布式 teammate 的清单是 spawn 时快照**:`build_context_seed` 在 spawn 时序列化,+ 后续轮次的新上传不会刷新到远端成员;进程内 member 共享 live dict 不受影响。+- **fallback notice 仍按主模型判定**(S_22 N8):team 分支 `_build_image_tool_fallback_notice`+ 用请求主模型能力,而实际作答是 leader 成员模型。若主模型声明 image 而 leader 模型不支持,+ 用户不会看到"已切换为图片工具"提示(本修复未改该口径)。+- **成员换模不热更新能力位**:能力位在成员 spec 装配期固定(`build_member_deep_agent_spec`),+ 运行中经 `/model` 换到另一种模态的模型不会重算;需要重建 team runtime 才生效。这与单 agent+ 侧 `image_capability_sync` 的运行时同步不同,若产品要求 team 内换模即时生效,需另立机制。+- 参考环境 openjiuwen 0.1.16 与仓内 pin 的 `dev-stable` 可能有个体差异,升级后按 S_22+ 「修改检查单」复验能力位与 rail 装配语义。diff --git a/jiuwenswarm/agents/harness/docs/specs/S_22_native-multimodal-image-input.md b/jiuwenswarm/agents/harness/docs/specs/S_22_native-multimodal-image-input.mdindex 18884db488..8704d3ed5b 100644--- a/jiuwenswarm/agents/harness/docs/specs/S_22_native-multimodal-image-input.md+++ b/jiuwenswarm/agents/harness/docs/specs/S_22_native-multimodal-image-input.md@@ -6,10 +6,10 @@|---|---|| 类型 | spec || 编号 / slug | S_22 / native-multimodal-image-input |-| 关联模块(jiuwenswarm 仓) | `jiuwenswarm/agents/harness/common/tools/model_capabilities.py`(能力解析纯函数);`.../common/prompt/user_prompt_builder.py`(引用行 / 像素注入 / 视图过滤 / 预算与状态行);`.../common/rails/multimodal_image_rail.py`(发送侧唯一决策点);`.../common/rails/stream_event_rail.py`(工具侧读图 / 视觉工具护栏);`.../common/rails/read_file_validation.py`(拦截文案与扩展名判定);`.../common/rails/concurrent_safe_rails.py`(ReadFileTool resolver 装配);`.../common/rails/progressive_tool_rail.py`(工具渐进式披露);装配点 `jiuwenswarm/server/runtime/agent_adapter/interface_deep.py`(`_resolve_enable_read_image_multimodal` / `_build_multimodal_image_rail` / `_build_image_tool_fallback_notice` / `_multimodal_image_files` 参数归一)、`interface_code.py`、`interface_flash.py`;配置 `jiuwenswarm/resources/config.yaml`(`react.multimodal_image_*` 三预算) |-| 关联模块(agent-core 仓,跨仓契约) | `openjiuwen.harness.tools.filesystem.ReadFileTool`(`enable_image_multimodal` + `image_multimodal_resolver`,调用时求值;`READ_IMAGE_MAX_BYTES` / `READ_IMAGE_MAX_DIMENSION` 为可覆盖的类属性)、`openjiuwen.harness.rails.DeepAgentRail`(`before_model_call` / `priority`)、`openjiuwen.harness.image_modality_probe`(`get_declared_image_support` 读 `ModelClientConfig.supports_vision`)、ContextWindow `model_copy` / window mutator 机制 |-| 最近一次修订日期 | 2026-11-04 |-| 关联 feature | F_01_native-multimodal-image-input.md |+| 关联模块(jiuwenswarm 仓) | `jiuwenswarm/agents/harness/common/tools/model_capabilities.py`(能力解析纯函数);`.../common/multimodal/`(`image_reference.py` 引用行 / 上传清单通道,`image_history.py` 像素物化 / 视图过滤 / 预算与状态行,`image_processing.py` 缩放编码);`.../common/rails/multimodal_image_rail.py`(发送侧唯一决策点);`.../common/rails/stream_event_rail.py`(工具侧读图 / 视觉工具护栏);`.../common/rails/read_file_validation.py`(拦截文案与扩展名判定);`.../common/rails/concurrent_safe_rails.py`(ReadFileTool resolver 装配);`.../common/rails/progressive_tool_rail.py`(工具渐进式披露);team 通道 `jiuwenswarm/agents/swarm/config_specs.py`(成员能力位 / 成员 rail 声明)与 `jiuwenswarm/agents/swarm/providers/multimodal.py`(`swarm.multimodal_image` provider);装配点 `jiuwenswarm/server/runtime/agent_adapter/interface_deep.py`(`_resolve_enable_read_image_multimodal` / `_build_multimodal_image_rail` / `_build_image_tool_fallback_notice` / `_multimodal_image_files` 参数归一)与 `.../agent_adapter/team_helpers.py`(team 轮次清单写入 build context);`interface_code.py`、`interface_flash.py`;配置 `jiuwenswarm/resources/config.yaml`(`react.multimodal_image_*` 三预算) |+| 关联模块(agent-core 仓,跨仓契约) | `openjiuwen.harness.tools.filesystem.ReadFileTool`(`enable_image_multimodal` + `image_multimodal_resolver`,调用时求值;`READ_IMAGE_MAX_BYTES` / `READ_IMAGE_MAX_DIMENSION` 为可覆盖的类属性)、`openjiuwen.harness.rails.DeepAgentRail`(`before_model_call` / `priority`)、`openjiuwen.harness.image_modality_probe`(`get_declared_image_support` 读 `ModelClientConfig.supports_vision`)、ContextWindow `model_copy` / window mutator 机制;team 侧 `openjiuwen.agent_teams.agent.agent_configurator`(成员 `enable_read_image_multimodal` None→False 兜底)、`openjiuwen.agent_teams.harness.TeamHarness`(每轮按 build context 重建 NativeHarness) |+| 最近一次修订日期 | 2026-11-06 |+| 关联 feature | B_05_team-native-multimodal-image-input.md(bugfix) |## 范围 / 边界@@ -31,11 +31,12 @@- **N2(模型条目是唯一依据)**:解析顺序——模型条目 `modalities` 含 `image` → **True**;未声明 / 不含 `image` / 其它不可识别值 → **False**(走 VQA / 视觉工具链)。不再内置模型能力表、不按模型名前缀猜测,也不接受单独的布尔开关;`coerce_modalities` 只负责把 YAML 里的列表或逗号 / 空白分隔字符串归一成规范小写列表。agent-core 另提供 `ModelClientConfig.supports_vision` 作为探针前置兜底(`get_declared_image_support`),但仅在 `deep_config.enable_read_image_multimodal` 尚未写入时生效;jiuwenswarm 链路恒由 `modalities` 解析并显式写入该值,故不构成第二真源。- **N3(发送侧唯一决策点)**:像素是否真的发给模型,只由 `MultimodalImageRail.before_model_call` 决定——enabled 时安装"物化" window mutator(把引用行替换成 image content,写进历史);disabled 时安装"视图过滤" mutator(只对本次发送的视图副本剥掉 image_url,历史里的 base64 原样保留,供后续切回视觉模型复用)。- **N4(工具侧与发送侧同源)**:原生开启时,stream rail 对 read_file 的**已提供图片路径**一律拒绝(像素已在上下文,重复读只会多一份 base64);对非图片的非文本扩展名仍拒绝;未提供的图片放行,由 `ReadFileTool` 按 resolver 内联像素。原生开启时视觉工具(`visual_question_answering` / `image_reading`)直接拒绝并提示"已提供像素";原生关闭时视觉工具是唯一读图通道,不拦截。判定细节见 [[S_10]] N13/N14。-- **N5(预算与降级可追溯)**:单次请求的图片受三预算约束(总字节 / 视觉 token / 张数,0 表示不限),超预算按**最老优先**降级为 `[image #n omitted: reason]` 文本状态行并写入历史;成功注入的记 `[image #n attached]`。状态行是模型可见的事实来源,后续轮次据此知道"这张图当时没给 / 给过"。+- **N5(预算与降级可追溯)**:单次请求的图片受三预算约束(总字节 / 视觉 token / 张数,0 表示不限),超预算按**最老优先**降级为 `[image #n omitted: reason]` 文本状态行并写入历史;成功注入的记 `[image #n attached]`。状态行是模型可见的事实来源,后续轮次据此知道"这张图当时没给 / 给过"。两类状态行都是**终态**:同一消息内 `attached` / `omitted`(含 `omitted: duplicate`)对应的路径,成员确定性分发一律不再补引用行、不再重复读盘物化——预算淘汰 / 读取失败的图不会在每次 LLM 迭代(每轮 `before_model_call`)被重新补行、重新缩放编码,否则上下文无界膨胀。- **N6(视图过滤不改历史)**:非视觉模型的剥离只发生在 `model_copy` 出的视图上,不得就地修改历史消息——否则切回视觉模型后图片永久丢失,且 checkpointer 里的原始内容被污染。- **N7(已提供图片判定不依赖 ContextVar)**:invoke 开始时把本次请求的图片路径快照写入 `ctx.extra["_jiuwenswarm_provided_image_paths"]`;工具跨任务 / 线程执行时 ContextVar 可能丢失,护栏必须读快照(路径归一化后比较,兼容绝对 / 相对 / `..` 形态)。ContextVar(`set_current_multimodal_image_files`)只在同一调用栈内的 prompt 组装侧使用。- **N8(提示一致性)**:仅当解析结果为 False 且请求确实带图片引用时,才向用户发"已切换为图片工具"提示;解析为 True 时不得再发该提示(否则与"像素已直接发送"自相矛盾)。系统提示里的 `multimodal_image_policy` 段同样按解析值二选一。- **N9(失败降级不阻断)**:单张图片读取 / 解码 / 缩放失败时跳过该图并记状态行,不让整个请求失败;rail 构建异常降级为 None(装配失败不阻断 agent 创建)。+- **N10(team 成员同源)**:team 模式下**每个成员**(leader / teammate / 命名成员)都挂 `swarm.multimodal_image` rail,三要素必须成对存在——(a) 成员的 `DeepAgentSpec.enable_read_image_multimodal` 按**该成员模型**的 `modalities` 显式写 bool(成员 None 会被 SDK 固化为 False);成员 spec 指定的模型名按条目 `model_client_config.model_name` 或 `alias` 命中,查不到条目按 N2 判 False 而**不回落**默认条目的能力位;(b) 成员挂 `swarm.multimodal_image` rail(provider 构造 `MultimodalImageRail`);(c) 本轮上传清单经 `BuildContext.request_metadata["multimodal_image_files"]` 到达 rail(adapter 的 `self._instance` 属性镜像与请求 ContextVar 都到不了成员任务)。live build context 的清单绑定只发生在**确实会开新一轮**的请求:控制续写(权限 / ask_user 作答,`reuse_active_waiter`)只向既有 waiter 投递作答、adapter 传 `image_files=[]`,不得覆盖写;slash 命令早退同样不写。否则"上传图片 → 权限确认 → 继续"会清空在该轮生效的 live 清单,本轮后续新建的成员 harness / 上下文溢出重建读到空清单,`[image #n]` 被判不在清单内丢弃。绑定位置固定在 slash 早退之后、投递 query(`team_manager.interact` / `_start_team_stream_round`)之前——`TeamHarness` 每轮按同一 build context 重建 NativeHarness,投递后再写赶不上本轮成员的 rail 构造。授权边界在物化处而不在挂载处:只有**清单内路径**且出现在该成员**自己历史中的 user-authored 引用行**才出图(任务看板正文 / 工具结果里的路径不物化);leader 把图片交给成员时须用 `send_message` 原样转述 `[image #n] path=...` 引用行,leader rail 的 `dispatch_hint` 负责把这条规则写进系统提示;并且 leader rail 在 `before_tool_call` 对 `send_message` 做**确定性兜底**——消息正文若提到本轮上传图的文件名或完整路径,自动在正文末尾补对应引用行(广播 `to="*"` / 回用户 `to="user"` 不补,单条最多补 4 张),避免模型只写任务看板或只写占位符时成员仍拿不到像素。成员侧再兜一层**确定性分发**:成员 rail 在 `before_model_call` 扫描自身上下文(含任务看板 / 工具结果等任意角色的文本)是否提到清单图(文件名或完整路径),命中且该路径**未处理**(`attached` 与 `omitted` 都是终态,见 N5)时主动把引用行补到最近一条 user 消息再物化;清单图全部已处理时直接返回,不再对全部消息做归一扫描。"提到清单图"的判定是**带边界的 token 匹配**:路径 / 文件名先统一分隔符(`\` → `/`)并忽略大小写,命中片段前后不得是 `[0-9A-Za-z_-]`(正则 lookaround),因此 `1.png` 不命中 `11.png` / `data.png`、`C:\Uploads\3.JPG` 能命中清单里的 `C:/uploads/3.jpg`、`请识别3.jpg` 仍命中;leader 分发兜底与成员确定性分发共用 `image_reference` 的同一套判定(不是裸 `in` 子串)。因此"模型声明原生能力 + 图在本轮上传清单内"时不由 leader 的消息格式决定是否出图;像素一旦提供,既有护栏会拒绝成员对同一图的 VQA/OCR(N4)。成员还有一条**超时/跨轮可用的模型可见路径**:原生开启时 `ReadFileTool` 的 resolver 每次调用读 `deep_config.enable_read_image_multimodal`,`read_file(本地图片路径)` 会把图片以图像内容返回原生模型(S_22 N4 的"未提供图片放行"分支);成员 rail 在 `enabled` 且本轮 0 像素时写策略段引导"本地路径优先 read_file,不要 VQA/OCR",且 read_file 返回的图片块会计入下一次 `native_images_sent`,从而继续拦住 VQA。清单是请求级的:进程内成员共享同一 `request_metadata` dict(跨轮刷新可见),子进程 / 分布式成员取 spawn 时的 seed 快照(不随后续轮次刷新,见遗留)。## 接口契约@@ -57,14 +58,30 @@| `ensure_multimodal_image_window_mutator(context, ...)` / `ensure_multimodal_image_filter_window_mutator(context)` | 在 ContextWindow 上安装物化 / 过滤 mutator;属性名 `_jiuwenswarm_multimodal_image_window_mutator` 防重复安装 || `estimate_image_visual_tokens(width, height)` | 512px tile 计费:85 + 170 × tiles,用于 token 预算 || `normalize_image_path(path)` / `is_provided_image_path(path, provided_paths)` | N7 的路径归一与快照比较;空路径 / 空快照一律 False |+| `normalize_image_mention_text(text)` / `normalized_text_mentions_image(image, normalized_text)` / `text_mentions_image(image, text)` | 图片提及判定单源(N10):`normalize_image_mention_text` 只做分隔符 `\` → `/` + 小写(不用 `normalize_image_path`——realpath 会改写正文片段,且 POSIX 的 `os.path.normcase` 恒等,对齐不了 Windows 反斜杠形态);`normalized_text_mentions_image` 在**已归一**文本上对"完整路径 / basename"做 lookaround 边界匹配(前后不得是 `[0-9A-Za-z_-]`),供批量场景复用一次归一;`text_mentions_image` 是单条文本的便捷封装(内部归一一次) || `set_current_multimodal_image_files` / `current_multimodal_image_files` / `reset_current_multimodal_image_files` | ContextVar 版"本次请求图片列表",仅同调用栈使用;跨任务判定走 N7 快照 |+| `store_team_request_image_files(metadata, files)` / `team_request_image_files(metadata)` | N10 team 通道:覆盖写 / 读 `BuildContext.request_metadata` 的清单;空列表是"本轮无上传"的权威事实,未写入返回 None(调用方回退 agent 属性 / ContextVar);读侧返回副本 || `strip_image_content_blocks(content)` | 纯函数:剥掉 content 里的 image 块并保留文本,返回 `(new_content, removed)`;供视图过滤复用 |-### MultimodalImageRail(`DeepAgentRail`,priority 75)+### swarm 装配(team 成员)| 成员 | 契约 ||---|---|-| `__init__(enable_image_multimodal=None, *, max_total_bytes=0, max_visual_tokens=0, max_count=0)` | 显式值优先;None 时在 `before_model_call` 读 `deep_config.enable_read_image_multimodal`(N1) |+| `_resolve_member_native_image_enabled(config, base_spec)`(`swarm/config_specs.py`) | N2 的成员侧落地:只读**原始 config 的模型条目声明**(`models.defaults` 非空 list 优先,否则 `models.default` 单 dict;两者都没有 → False),**不经 `get_default_models`**——不做 `deepcopy`、不解密 `api_key`(team 装配按「每个成员、每一轮」调用,且本判定只要 `model_name` / `alias` / `modalities` 三个声明字段)。成员 spec 指定模型名时按条目 `model_client_config.model_name` **或**顶层 `alias` 命中,两者都未命中 → `logger.warning`(带成员模型名)+ **False,不回落默认条目**;未指定模型 → `is_default is True` 的条目,否则第一个条目;未声明 / 不含 `image` → False;显式 `base_spec.enable_read_image_multimodal` 优先(不覆盖用户配置) |+| `_multimodal_image_rail_params(config, enabled)` | 把能力位与 `react.multimodal_image_*` 三预算烘进 `RailSpec.params` |+| `ensure_manifest_images_referenced(messages, image_files, *, max_images=4)` | 成员侧确定性分发:扫描全部消息文本(含 tool result,仅用于判断"提到了哪张图"),按边界判定命中清单文件名 / 完整路径且该路径**未处理**(`attached` ∪ `omitted` 都是终态,见 N5)时,把引用行补到最近一条 user 消息末尾;幂等;**清单图全部已处理 → 直接返回 0**(不做全量文本扫描);每条消息文本只归一一次供多张图复用;返回补了几张 |+| `MultimodalImageRail.before_model_call(ctx)` | enabled 分支在注入前调用上面的函数(仅绑定清单的成员、非 leader 的 `dispatch_hint` 实例),补完引用后交给 `inject_image_content_from_references` 统一物化 |+| `augment_message_with_reference_lines(content, image_files, *, max_images=4)` | leader 分发兜底纯函数:按文件名 / 完整路径把消息里提到的上传图补成引用行;提及判定复用 `text_mentions_image`(分隔符 / 大小写归一 + 边界对齐,`1.png` 不会被 `11.png` / `data.png` 误命中);已有同路径引用行不重复,返回新 content |+| `MultimodalImageRail.before_tool_call(ctx)` | 仅 `dispatch_hint` 的 leader 生效:`send_message` 且收件人为具体成员时,用上面的纯函数改写 `tool_call.arguments["content"]`(同步写回 `ctx.inputs.tool_args`);广播 / user / 非 send_message 不改写;异常只降级不阻断 |+| `swarm.multimodal_image`(`swarm/providers/multimodal.py`) | 由 config_specs 为**每个成员**声明(leader 额外带 `dispatch_hint=True`);provider 从 `context.request_metadata` 取本轮清单,构造 `MultimodalImageRail(enable_image_multimodal=..., budgets..., image_files=..., dispatch_hint=...)` |+| `team_helpers` 轮次绑定 | `request_metadata` 覆盖写(首轮 / 冷恢复随 fresh spec 生效)+ 写进 live team agent 的 `harness.build_context.request_metadata`(跨轮复用 runtime 每轮据此重建 NativeHarness)。后者**只在确实会开新一轮的请求**写:slash 命令早退之后、投递 query(`team_manager.interact` / `_start_team_stream_round`)之前,且 `reuse_active_waiter` 为假;控制续写(权限 / ask_user 作答,adapter 传 `image_files=[]`)与 slash 请求不得覆盖写,否则清空在途图片轮清单(N10) |++### MultimodalImageRail(`DeepAgentRail`,priority 82)++| 成员 | 契约 |+|---|---|+| `__init__(enable_image_multimodal=None, *, max_total_bytes=0, max_visual_tokens=0, max_count=0, image_files=None, dispatch_hint=False)` | 显式值优先;None 时在 `before_model_call` 读 `deep_config.enable_read_image_multimodal`(N1);`image_files` 非 None 时装配期绑定本轮清单(team 成员,N10),空列表不回退 agent 属性;`dispatch_hint=True`(leader)在原生策略段追加"用 send_message 转述引用行"的提示 |+| `_resolve_request_image_files()` | 顺序:装配期绑定清单 → agent 实例镜像(单 agent 旧行为)→ `None`(inject 回退 ContextVar) || `before_model_call(ctx)` | N3:enabled → 物化 mutator;disabled → 过滤 mutator;`ctx.context is None` 直接返回;同时刷新系统提示 `multimodal_image_policy` 段(N8) |### stream_event_rail / read_file_validation(工具侧)@@ -92,6 +109,7 @@- 图片项:`{"path": str, "filename": str, "mime_type": str, "size": int}`;`extract_multimodal_image_files(params)` 从请求参数归一- `ctx.extra` 键:`"_jiuwenswarm_provided_image_paths"`(invoke 级快照,list[str],路径已归一)- ContextVar:`_CURRENT_MULTIMODAL_IMAGE_FILES`(tuple[dict],同调用栈生效,用完 reset)+- `BuildContext.request_metadata` 键:`"multimodal_image_files"`(team 轮次上传清单,list[dict];team_helpers 覆盖写、成员侧 provider 读;随 `build_context_seed` 跨序列化边界)——覆盖写分两处:fresh spec 的 metadata(首轮 / 冷恢复)与 live team agent 的 `harness.build_context`(仅确实会开新一轮的请求,slash 早退后、投递前)- 配置:`react.multimodal_image_budget`(总字节,0 不限,默认 0)、`react.multimodal_image_token_budget`(视觉 token,0 不限,默认 0)、`react.multimodal_image_max_count`(张数,默认 8)- 常量:`_MAX_VISION_INLINE_IMAGE_BYTES`(10MB 单图上限)、`_MAX_VISION_INLINE_IMAGE_DIMENSION`(2048px)、质量阶梯 95/85/70/50/30/10、`_SHRINK_SCALE_STEP=0.85`、`_MIN_SHRINK_DIMENSION=32`@@ -99,26 +117,36 @@- **P1 上传 → 引用行**:请求携带 `_multimodal_image_files` → adapter 归一并传给 prompt 组装 → 在用户消息末尾追加引用行 → ContextVar 记录本次图片列表(同调用栈)。- **P2 能力解析(adapter)**:取模型条目 `modalities` → `supports_native_image` → N2 → 写 `deep_config.enable_read_image_multimodal` → `create_deep_agent` 与 `MultimodalImageRail` 收到同一值。-- **P3 发送前决策(rail 75)**:`before_model_call` → N3 安装 mutator → 系统提示策略段按解析值二选一;enabled 时 mutator 在窗口物化阶段执行 P4,disabled 时执行 P5。+- **P3 发送前决策(rail 82)**:`before_model_call` → N3 安装 mutator → 系统提示策略段按解析值二选一;enabled 时 mutator 在窗口物化阶段执行 P4,disabled 时执行 P5。- **P4 像素物化**:`collect_image_references_from_messages` → 逐图读文件 / 校验 / 缩放压缩 → 预算检查(最老优先,N5)→ 就地写多模态 content + 状态行 → 历史持久化后后续轮次复用,不重复读文件。- **P5 视图剥离**:`filter_image_content_from_view` 在发送视图副本上剥 image 块 → `strip_image_content_blocks` 保留文本 → 历史 base64 不动(N6)。- **P6 工具护栏(before_tool_call)**:读 `deep_config` 解析值 → N4 三分支(已提供图片拒绝 / 非图片二进制拒绝 / 图片放行);视觉工具在原生开启时拒绝。- **P7 失败提示**:`_build_image_tool_fallback_notice` 仅在解析 False 时发"已切换为工具"提示(N8);系统提示策略段与 rail 决策同源。- **P8 配置读取**:adapter 读 `react.multimodal_image_*` → 传给 rail 构造;0 值表示不限。+- **P9 team 成员通道(N10)**:adapter team 分支 `_prepare_multimodal_image_inputs` 生成引用行并 `pop` 出清单 → 作为 `image_files` 参数传给 `process_team_message_stream` → 覆盖写 `request_metadata["multimodal_image_files"]`(首轮 / 冷恢复随 fresh spec 的 build context 生效)→ 同一清单写进 live team agent 的 `harness.build_context.request_metadata`(跨轮复用 runtime 每轮据此重建 NativeHarness;进程内 teammate 共享同一 dict;**只在该请求确实会开新一轮时写**——slash 早退之后、投递 query 之前、`reuse_active_waiter` 为假,控制续写 / slash 命令不覆盖写)→ `swarm.multimodal_image` provider 为每个成员构造 `MultimodalImageRail(image_files=清单)` → 成员的 `before_model_call` 按 P3/P4 物化像素;SDK 侧 `enable_read_image_multimodal` 由 `config_specs` 按成员模型 `modalities` 显式写入。leader rail 的 `dispatch_hint` 在原生策略段追加"交给成员时用 send_message 保留引用行"的规则;`before_tool_call` 再对 `send_message` 做确定性兜底(正文提到上传图文件名 / 路径 → 自动补引用行);成员 rail 在 `before_model_call` 还会扫描自身上下文任意位置的清单图提及并补引用行(`ensure_manifest_images_referenced`,含任务看板 tool result 文本;边界归一判定、`attached` ∪ `omitted` 终态、清单全处理即早退),成员只在自身历史出现该引用行时才物化对应上传图。像素提供后,stream 护栏按 N4 拒绝同一图的 VQA/OCR。成员 `enabled` 且 0 像素时另写 `multimodal_image_policy` 策略段引导"本地路径用 read_file 原生读图";`read_file` 命中 resolver 后图片块进入历史,下一次模型调用 `native_images_sent>0`,同样触发 VQA/OCR 拦截。## 异常分支与退出路径-| 分型 | 触发 | 行为 |-|---|---|---|-| 模型条目 `modalities` 不含 `image`(含未声明) | 纯文本模型 / 漏配 | 解析 False(N2),走工具链,不发矛盾提示(N8) |-| 图片文件读取失败 / MIME 不支持 | 文件被删 / 非图片 | 跳过该图,写 `omitted` 状态行;其余图片继续 |-| 单图超 10MB / 解码失败 | 超大图 / 损坏文件 | 跳过并写状态行,不阻断请求 |-| 超总字节 / token / 张数预算 | 多图大图 | 最老优先降级为 `omitted` 状态行(N5) |-| `ctx.context is None` | rail 在无窗口场景调用 | 直接 return,不安装 mutator |-| rail 构造失败 | 依赖缺失 / 版本不匹配 | warning + None,agent 继续装配(N9) |-| 工具跨线程执行导致 ContextVar 丢失 | 工具在线程池 / 新任务运行 | 走 `ctx.extra` 快照(N7),不误判"图片未提供" |-| 已提供图片被 read_file 重复读取 | 模型不知道像素已在上下文 | 整批拒绝并提示直接使用像素(N4 / [[S_10]] N13) |-| 原生开启时调用视觉工具 | 模型习惯性调用 | 拒绝并提示不要调用(N4 / [[S_10]] N14) |+| 分型 | 触发 | 行为 | 测试覆盖 |+|---|---|---|---|+| 模型条目 `modalities` 不含 `image`(含未声明) | 纯文本模型 / 漏配 | 解析 False(N2),走工具链,不发矛盾提示(N8) | — |+| 图片文件读取失败 / MIME 不支持 | 文件被删 / 非图片 | 跳过该图,写 `omitted` 状态行;其余图片继续 | — |+| 单图超 10MB / 解码失败 | 超大图 / 损坏文件 | 跳过并写状态行,不阻断请求 | — |+| 超总字节 / token / 张数预算 | 多图大图 | 最老优先降级为 `omitted` 状态行(N5) | — |+| `ctx.context is None` | rail 在无窗口场景调用 | 直接 return,不安装 mutator | — |+| rail 构造失败 | 依赖缺失 / 版本不匹配 | warning + None,agent 继续装配(N9) | — |+| 工具跨线程执行导致 ContextVar 丢失 | 工具在线程池 / 新任务运行 | 走 `ctx.extra` 快照(N7),不误判"图片未提供" | — |+| 已提供图片被 read_file 重复读取 | 模型不知道像素已在上下文 | 整批拒绝并提示直接使用像素(N4 / [[S_10]] N13) | — |+| 原生开启时调用视觉工具 | 模型习惯性调用 | 拒绝并提示不要调用(N4 / [[S_10]] N14) | — |+| team leader 模型不含 `image` | 纯文本 leader + 用户传图 | 能力位 False → rail 走视图过滤;图片仍可经 VQA 工具识别,不报请求失败(N2/N10) | — |+| team 非首轮上传 | 复用中的 team runtime 收到新图 | 该请求确实开新一轮时,live build context 在投递前被覆盖写,下一轮 NativeHarness 重建时 rail 拿到新清单(N10);漏写即静默 0 张 | — |+| 控制续写(权限 / ask_user 作答) | 图片轮触发权限卡,用户点继续 | 不新开 round、不覆盖写 live 清单:清单保持上一轮内容,后续成员 harness / 溢出重建仍能物化像素(N10) | `test_control_continuation_keeps_live_round_manifest` |+| slash 命令 | `/evolve` 等命中后早退 | 同样不新开 round,早退路径不写 live 清单(N10) | `test_slash_command_keeps_live_round_manifest` |+| teammate 收到引用行(send_message) | leader 用 send_message 正文保留引用行 | teammate 挂 rail,按"清单 ∩ 自身引用行"物化像素(N10) | — |+| teammate 只拿到路径(任务看板 / 工具结果) | leader 把绝对路径写进 create_task / 任务正文 | 成员 rail 扫到清单图提及后主动补引用行并物化(N10 确定性分发);不再依赖 leader 消息格式 | `test_mention_in_tool_result_adds_reference_to_user_message` |+| teammate 上下文已 `attached` / 已 `omitted` | 跨模型调用重复进 before_model_call;预算淘汰或读取失败已写 `omitted` | `attached` ∪ `omitted`(含 `omitted: duplicate`)都是终态:不重复补引用行、不重复读盘物化(N5) | `test_already_attached_is_not_repeated`、`test_omitted_image_is_not_rematerialized` |+| 成员 pinned 模型名未声明 | 成员 spec 指定 `not-listed-model`,`models.defaults` 无该条目 | 能力位 False + warning(含成员模型名),**不回落**默认条目的 `modalities`(N2) | `test_unknown_pinned_model_does_not_inherit_default_modalities` |+| 成员只有路径(清单提及未命中,如跨轮清单已清空) | 策略段引导用 read_file 原生读图 | 不引导则惯性 VQA/OCR;read_file 返回图像块后 `native_images_sent>0` 仍会拦 VQA | `test_team_member_path_guidance_points_to_native_read_file` |## 边界 case 清单@@ -138,6 +166,25 @@| 解析 False + 请求带图 | 发"已切换为工具"提示 | 提示与事实矛盾 | `test_forced_native_path_does_not_claim_tool_fallback` 等 || 模型热切换 | resolver 调用时求值 | read_file 行为冻结在 init | `test_read_tool_resolver_follows_model_switch` || rail 显式开关 vs deep_config | 显式值优先 | 装配语义漂移 | `test_explicit_rail_flag_wins_over_deep_config` |+| team leader 能力位 | 按成员模型 `modalities` 显式写 bool | 成员 None → SDK 固化 False,rail 挂上也走非原生 | `test_leader_gets_multimodal_rail_and_capability_flag`、`test_member_model_entry_matches_by_model_name` |+| team teammate 也挂 rail | 每个成员都声明 | 无引用行时不会误注入(安全门按清单 ∩ 引用行) | `test_teammate_gets_multimodal_rail_without_dispatch_hint` |+| leader 分发提示 | `dispatch_hint` 只在 leader 生效 | 成员不知道要转发引用行 → 团员仍 0 张 | `test_leader_dispatch_hint_tells_how_to_forward_reference_line` |+| leader 消息只写文件名 | `before_tool_call` 自动补引用行 | 只写任务看板 / 占位符 → 团员看不到像素 | `test_leader_send_message_gets_missing_reference_line` |+| leader 广播 / 回用户 | 不改写 content | 把上传清单发给无关成员或用户 | `test_dispatch_augment_skips_broadcast_and_user_targets` |+| team 非首轮清单刷新 | 写 live build context | 第二轮上传静默 0 张 | `test_bind_round_image_files_writes_live_build_context`、`test_bind_round_image_files_clears_stale_manifest` |+| team 清单到达 rail | provider 读 `request_metadata` | rail 拿不到清单 → 安全门拒全部引用 | `test_provider_binds_round_manifest_from_build_context`、`test_process_team_message_stream_puts_manifest_in_request_metadata` |+| 装配期绑定清单 vs agent 镜像 | 绑定清单优先,空列表不回退 | 读到上一轮残留图 | `test_bound_manifest_wins_over_agent_attribute`、`test_empty_bound_manifest_does_not_fall_back_to_agent_attribute` |+| 清单图已 `omitted`(预算卸载 / 读取失败 / duplicate) | 视为终态:不再补引用行、不再读盘物化 | 每次 LLM 迭代重复补行重编码 → 上下文膨胀、预算抖动 | `test_omitted_image_is_not_rematerialized`、`test_duplicate_omitted_image_is_not_rematerialized` |+| 清单 `1.png` vs 文本 `11.png` / `data.png` | 边界判定不命中(不再裸子串匹配) | 误补无关图、白耗预算 | `test_short_filename_is_not_substring_mention`、`test_longer_manifest_name_is_not_matched_by_shorter_text`、`test_text_mentions_image_requires_token_boundaries`、`test_augment_ignores_substring_filename_mention` |+| 正文路径用反斜杠 / 大小写不同 | 归一后仍命中(`C:\Uploads\3.JPG` 命中 `C:/uploads/3.jpg`) | Windows 形态路径命中失效、只能靠文件名兜底(图被改名即漏判) | `test_path_with_different_separator_and_case_matches`、`test_path_mention_matches_across_separators_without_filename_fallback`、`test_text_mentions_image_normalizes_separator_and_case`、`test_augment_matches_windows_separator_path_mention` |+| 中文紧贴文件名(`请识别3.jpg`) | 命中(边界字符集只含 `[0-9A-Za-z_-]`) | 边界收紧过度导致中文前缀提及漏判 | `test_text_mentions_image_matches_chinese_adjacent_filename` |+| 同一长文本要对多张图判定 | 每条消息只归一一次,再逐图复用 | 逐 (图, 文本) 重复 lower,抵消"全量扫描早退"优化 | `test_normalizes_each_message_text_once_for_all_images`、`test_normalized_text_mentions_image_reuses_one_normalized_text` |+| 控制续写(权限确认后继续)/ slash 命令 | 不覆盖写 live 清单 | 在途图片轮清单被清空 → 后续成员 0 像素 | `test_control_continuation_keeps_live_round_manifest`、`test_slash_command_keeps_live_round_manifest` |+| 普通 follow-up 新轮 | 投递 query 前覆盖写本轮清单 | 绑定位置挪错 → 第二轮上传静默 0 张 | `test_followup_new_round_still_binds_round_manifest` |+| 成员 pinned 模型名未声明 | 能力位 False + warning,不回落默认条目 | 用别的模型能力位决定本成员是否原生看图 | `test_unknown_pinned_model_does_not_inherit_default_modalities` |+| 成员 pinned 用 alias 声明 | 按条目顶层 `alias` 命中同一份 `modalities` | alias 被当成未声明 → 视觉成员退化为工具链 | `test_pinned_model_matches_alias` |+| config 无 `models` 段 / 只有 `models.default` | 前者 False(未声明即不支持),后者按单条目声明解析 | env 兜底条目没有 `modalities` 却参与判定 | `test_config_without_models_section_disables_native_image`、`test_legacy_single_default_entry_is_honored` |+| 能力位解析对模型条目 deepcopy / 解密 | 只读声明字段,不触发 `deepcopy` / `api_key` 解密 | 每成员每轮深拷贝 + 解密纯浪费 | `test_capability_resolution_skips_entry_copy_and_decryption` |## 修改检查单@@ -150,6 +197,15 @@- 改 fallback notice → 只在解析 False 时发(N8);同时检查系统提示 `multimodal_image_policy` 段与 `ProgressiveToolRail` 的工具披露- 改 ReadFileTool 构造 → `ConcurrentSafeSysOperationRail.init` 必须同时传 `enable_image_multimodal` 与 `image_multimodal_resolver`;resolver 读 rail 显式值 → `deep_config` → False- 改上传 / 引用行格式 → `_IMAGE_REFERENCE_LINE_RE` / `parse_image_references` / `build_image_reference_line` 三处同改;旧历史里的旧格式必须仍可解析+- 改 team 原生图片(N10 三要素)→ 能力位(`config_specs` 的 `update["enable_read_image_multimodal"]`)、全成员 rail 挂载(leader 带 `dispatch_hint`)、清单通道(`team_helpers` 的 `request_metadata` 覆盖写 + live build context 刷新)三处必须同时改;只改其一 = 挂 rail 也 0 张。清单键只允许 adapter/team_helpers 覆盖写,禁止信任请求 metadata 里同名外部值+- 改成员授权边界 → 物化前提保持"清单内路径 + 该成员 user-authored 引用行"两条同时成立;任务看板 / 工具结果里的路径不得物化(否则读文件内容可被诱导成像素注入)。想收紧到"按任务分配图"需另建 task→paths 授权表,不能靠放宽安全门实现+- 改成员确定性分发的幂等口径 → "已处理"集合是 `attached` ∪ `omitted`(同消息作用域内 index→path 配对,`omitted: duplicate` 也算终态);新增状态行类型必须在此显式决定是否终态,并保留"清单图全部已处理 → 直接返回 0"的早退,否则每轮模型调用都会做全量文本扫描+- 改提及判定(分发兜底 / 成员确定性分发)→ 单源在 `image_reference` 的 `normalize_image_mention_text` / `normalized_text_mentions_image` / `text_mentions_image`:禁止恢复裸 `in` 子串匹配,"分隔符 + 大小写"归一与边界字符集 `[0-9A-Za-z_-]` 是契约;批量场景先按消息归一一次再逐图判定,不要逐 (图, 文本) 重复归一+- 改 leader 分发提示 → 同步 `MultimodalImageRail` 策略段文案与 `dispatch_hint` 装配点;提示变了要重验"leader 用 send_message 转发引用行 → 团员出图"的端到端路径+- 改分发兜底(`before_tool_call`)→ 保持"只补消息真正提到的图(文件名 / 路径)、只对具体成员单播生效、广播 / 回用户不改写";新增改写必须同步 `augment_message_with_reference_lines` 纯函数测试与 rail 参数改写测试+- 改成员 path-only 引导 → 与 `ReadFileTool` 的 resolver(`ConcurrentSafeSysOperationRail.init` 读 `deep_config.enable_read_image_multimodal`)保持一致;引导文案只在成员 `enabled` 且 0 像素时出现,像素一到位必须切回原生策略段并依靠 N4 拦 VQA/OCR+- 改成员模型能力解析 → 只读**原始 config 的模型条目声明**(`models.defaults` 非空 list 优先、否则 `models.default` 单 dict;都缺 → False),不调 `get_default_models`、不做 `deepcopy` / `api_key` 解密;匹配成员模型名时 `model_client_config.model_name` 与顶层 `alias` 都算命中,**未命中 → False + warning,禁止回落默认条目**(否则拿别的模型能力位决定本成员是否原生看图);只有未指定模型才取 `is_default` 条目;显式 `base_spec.enable_read_image_multimodal` 优先,不得用"成员一律 True"替代+- 改 team 清单绑定时机(`team_helpers`)→ live build context 只给"确实会开新一轮"的请求写:slash 命令早退之后、投递 query 之前、且 `reuse_active_waiter` 为假;控制续写(adapter 传 `image_files=[]`)与 slash 请求覆盖写会清空在途图片轮清单(N10)## 与其它 spec 的关系diff --git a/jiuwenswarm/agents/swarm/config_specs.py b/jiuwenswarm/agents/swarm/config_specs.pyindex 6d19ae4a55..e76ff88533 100644--- a/jiuwenswarm/agents/swarm/config_specs.py+++ b/jiuwenswarm/agents/swarm/config_specs.py@@ -54,6 +54,9 @@ from jiuwenswarm.common.config import (resolve_shared_ttse_bank,)from jiuwenswarm.common.utils import get_agent_workspace_dir+from jiuwenswarm.agents.harness.common.tools.model_capabilities import (+ supports_native_image,+)from jiuwenswarm.agents.harness.team.team_runtime_inheritance import (get_context_engine_enabled,resolve_model_config,@@ -515,6 +518,115 @@ def _llm_retry_enabled(config: dict[str, Any]) -> bool:return retry.get("enabled", False) is True+def _member_model_name(base_spec: DeepAgentSpec) -> str:+ """Return the member's resolved model name ("" when it uses the default model).++ The model name lives on ``ModelRequestConfig.model_name``; a few blueprint /+ legacy shapes put it on the client config dict instead, so both are checked.+ """+ model = getattr(base_spec, "model", None)+ request_config = getattr(model, "model_request_config", None)+ if isinstance(request_config, dict):+ name = str(request_config.get("model_name") or "").strip()+ if name:+ return name+ name = str(getattr(request_config, "model_name", "") or "").strip()+ if name:+ return name+ client_config = getattr(model, "model_client_config", None)+ if isinstance(client_config, dict):+ return str(client_config.get("model_name") or "").strip()+ return str(getattr(client_config, "model_name", "") or "").strip()+++def _model_entry_name(entry: dict[str, Any]) -> str:+ """Return the ``model_name`` of a ``models.defaults`` entry."""+ client_config = entry.get("model_client_config")+ if isinstance(client_config, dict):+ name = str(client_config.get("model_name") or "").strip()+ if name:+ return name+ return str(entry.get("model_name") or "").strip()+++def _model_entry_alias(entry: dict[str, Any]) -> str:+ """Return the entry's top-level ``alias`` ("" when undeclared).++ 成员 spec 的模型名可能声明的是 alias 而不是 ``model_client_config.model_name``+ (条目允许带顶层 ``alias``),因此匹配成员模型名时两个字段都算命中。+ """+ return str(entry.get("alias") or "").strip()+++def _declared_model_entries(config: dict[str, Any] | None) -> list[dict[str, Any]]:+ """Return the model entries declared by the raw config (no decryption/copy).++ 能力位解析只需要 ``model_client_config.model_name`` / ``alias`` /+ ``modalities`` 三个声明字段,而 ``get_default_models`` 会 deepcopy 全量条目+ 并逐个解密 api_key;team 装配按「每个成员、每一轮」调用本函数,走那条路径+ 纯属浪费([[S_22]] N10)。这里直接读原始 config,条目选取优先级与+ ``get_default_models`` 一致:``models.defaults``(非空 list)> ``models.default``+ (单 dict);两者都没有(env 兜底形态)→ 空列表,能力位按"未声明即不支持"处理。+ """+ models = config.get("models") if isinstance(config, dict) else None+ models = models if isinstance(models, dict) else {}+ declared = models.get("defaults")+ if isinstance(declared, list) and declared:+ return [entry for entry in declared if isinstance(entry, dict)]+ single = models.get("default")+ if isinstance(single, dict):+ return [single]+ return []+++def _resolve_member_native_image_enabled(+ config: dict[str, Any], base_spec: DeepAgentSpec+) -> bool:+ """Resolve the member's native-image capability from the declared modalities.++ Follows the adapter's single-source rule ([[S_22]] N2): only a model entry+ whose ``modalities`` contains ``image`` enables native image input — no+ built-in capability table and no model-name guessing. A member spec that+ pins a model matches that entry by name or alias; otherwise the default+ entry decides.+ """+ entries = _declared_model_entries(config)+ if not entries:+ return False+ model_name = _member_model_name(base_spec)+ if model_name:+ for entry in entries:+ if model_name in {_model_entry_name(entry), _model_entry_alias(entry)}:+ return supports_native_image(entry.get("modalities"))+ # 成员锁定了一个未声明的模型名时不得回落到默认条目:那等于拿"别的模型"的+ # 能力位决定本成员能否原生看图(可能把纯文本成员判成支持,反向亦然),+ # 违反 N2「模型条目是唯一依据、未声明即不支持」。warning 记下成员模型名,+ # 便于定位这种难以察觉的配置漂移。+ logger.warning(+ "[swarm.config_specs] member model %r is not declared in "+ "models.defaults; native image input disabled",+ model_name,+ )+ return False+ default_entry = next(+ (entry for entry in entries if entry.get("is_default") is True), entries[0]+ )+ return supports_native_image(default_entry.get("modalities"))+++def _multimodal_image_rail_params(+ config: dict[str, Any], native_image_enabled: bool+) -> dict[str, Any]:+ """Build the leader multimodal rail params (capability flag + image budgets)."""+ react = _config_section(config, "react")+ return {+ "enable_image_multimodal": bool(native_image_enabled),+ "max_total_bytes": react.get("multimodal_image_budget", 0),+ "max_visual_tokens": react.get("multimodal_image_token_budget", 0),+ "max_count": react.get("multimodal_image_max_count", 0),+ }++def _team_common_rail_names(role: str) -> tuple[str, ...]:"""Shared chat-team rails; leaders omit harness todo planning."""if role == "leader":@@ -1033,6 +1145,24 @@ def build_member_deep_agent_spec(if rail.type in {registry.STREAM_EVENT, registry.REQUEST_SCOPED_MCP_TOOLS}}merged_rails.extend(rail for rail in rails_specs if rail.type not in existing_runtime_rails)+ # 原生图片输入:team 成员都不是 adapter 的 self._instance,上传清单只能经+ # build context 到成员侧,所以由 swarm provider 给每个成员挂 rail([[S_22]] N10)。+ # 授权边界不在挂载处而在物化处:清单内的路径 + 成员自己历史里的引用行才出图,+ # leader 用 send_message 转发引用行即视为分发(任务看板里的纯路径不算)。+ explicit_native_image = getattr(base_spec, "enable_read_image_multimodal", None)+ native_image_enabled = (+ bool(explicit_native_image)+ if explicit_native_image is not None+ else _resolve_member_native_image_enabled(config, base_spec)+ )+ if not any(rail.type == registry.MULTIMODAL_IMAGE for rail in merged_rails):+ rail_params = _multimodal_image_rail_params(config, native_image_enabled)+ if role == "leader":+ # leader 多一段"怎么把图交给成员"的提示(send_message 保留引用行)。+ rail_params["dispatch_hint"] = True+ merged_rails.append(+ RailSpec(type=registry.MULTIMODAL_IMAGE, params=rail_params)+ )merged_tools = list(base_spec.tools or [])merged_tools.extend(tool_specs)merged_mcps = _merge_mcp_configs(base_spec.mcps, mcp_configs)@@ -1046,6 +1176,9 @@ def build_member_deep_agent_spec("tools": merged_tools,"mcps": merged_mcps,"kv_cache_affinity_config": _kv_cache_affinity_config(config),+ # 显式写死能力位:openjiuwen 对成员 None 一律兜底 False(省掉每成员一次+ # 探测 LLM 往返),不写这里的话 rail 即便挂上也走非原生分支。+ "enable_read_image_multimodal": native_image_enabled,}if role == "leader":# Leaders use the team task board (create_task / view_task / update_task).diff --git a/jiuwenswarm/agents/swarm/providers/multimodal.py b/jiuwenswarm/agents/swarm/providers/multimodal.pynew file mode 100644index 0000000000..c87a2013c2--- /dev/null+++ b/jiuwenswarm/agents/swarm/providers/multimodal.py@@ -0,0 +1,74 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++"""Swarm native-multimodal rail provider (team member image input).++Team members are built by openjiuwen from a declarative ``DeepAgentSpec``; a+member is **not** the adapter's ``self._instance``, so neither the+agent-attribute manifest mirror nor the request ContextVar reaches it. This+provider bridges the gap: it builds a :class:`MultimodalImageRail` on every+member and hands it the current round's upload manifest, which travels on+``SwarmBuildContext.request_metadata`` (same channel as ``enable_routing``).++The rail instance is rebuilt on every round — openjiuwen rebuilds a member's+native harness per round from the captured spec + build context — so reading the+manifest at build time is per-round fresh, provided the platform refreshes+``request_metadata`` before each round (see ``team_helpers``).++Authorization: a member only materializes images that are (a) in the current+upload manifest and (b) referenced by a ``[image #n] path=...`` line in a+**user-authored** message of its own history. The leader's ``send_message`` is+therefore the dispatch act; a bare path in task-board content is not enough.+The leader rail additionally carries ``dispatch_hint`` so the model is told how+to forward the reference line.+"""++from __future__ import annotations++from typing import Any++from openjiuwen.agent_teams.harness.manifest import ElementKind, harness_element++from jiuwenswarm.agents.harness.common.multimodal import team_request_image_files+from jiuwenswarm.agents.harness.common.rails.multimodal_image_rail import (+ MultimodalImageRail,+)+from jiuwenswarm.agents.swarm.context import SwarmBuildContext++# Swarm-owned rail type name; namespaced under "swarm.".+MULTIMODAL_IMAGE = "swarm.multimodal_image"+++@harness_element(+ kind=ElementKind.RAIL,+ name=MULTIMODAL_IMAGE,+ description=(+ "Injects uploaded-image pixels into a team member's model context (native "+ "multimodal) instead of leaving only text reference lines; leader also "+ "gets the image-dispatch hint."+ ),+)+def _build_multimodal_image_rail(+ params: dict[str, Any],+ context: SwarmBuildContext,+) -> MultimodalImageRail:+ """Build a member's native-multimodal rail with this round's manifest.++ ``params`` carries the resolved capability flag, the three image budgets+ (baked from config at spec-build time) and ``dispatch_hint`` (leader only).+ The manifest is read from the live build context so a new user upload on a+ later round is picked up without rebuilding the team spec.+ """+ image_files = team_request_image_files(+ getattr(context, "request_metadata", None)+ )+ return MultimodalImageRail(+ enable_image_multimodal=params.get("enable_image_multimodal"),+ max_total_bytes=params.get("max_total_bytes") or 0,+ max_visual_tokens=params.get("max_visual_tokens") or 0,+ max_count=params.get("max_count") or 0,+ image_files=image_files,+ dispatch_hint=bool(params.get("dispatch_hint")),+ )+++__all__ = ["MULTIMODAL_IMAGE"]diff --git a/jiuwenswarm/agents/swarm/registry.py b/jiuwenswarm/agents/swarm/registry.pyindex 22dd8db19d..82e7b89187 100644--- a/jiuwenswarm/agents/swarm/registry.py+++ b/jiuwenswarm/agents/swarm/registry.py@@ -50,6 +50,7 @@ from jiuwenswarm.agents.swarm.providers import (evolution_rails as _evolution_rails,long_horizon as _long_horizon,member_rails as _member_rails,+ multimodal as _multimodal,runtime_tools as _runtime_tools,skills as _skills,tools as _tools,@@ -89,6 +90,8 @@ A2A_OUTBOUND_TOOLKIT = _member_rails.A2A_OUTBOUND_TOOLKITDISABLED_TOOLS = _member_rails.DISABLED_TOOLSREQUEST_SCOPED_MCP_TOOLS = _member_rails.REQUEST_SCOPED_MCP_TOOLSMODEL_ROUTING = _member_rails.MODEL_ROUTING+# Leader-only native image input (uploaded pixels into the model context).+MULTIMODAL_IMAGE = _multimodal.MULTIMODAL_IMAGETEAM_PERMISSION = _member_rails.TEAM_PERMISSIONTEAM_PERMISSION_POLICY = _member_rails.TEAM_PERMISSION_POLICYTEAM_SKILL_EVOLUTION = _evolution_rails.TEAM_SKILL_EVOLUTION@@ -213,6 +216,8 @@ __all__ = ["A2A_OUTBOUND_TOOLKIT","DISABLED_TOOLS","REQUEST_SCOPED_MCP_TOOLS",+ "MODEL_ROUTING",+ "MULTIMODAL_IMAGE","TEAM_PERMISSION","TEAM_PERMISSION_POLICY","TEAM_SKILL_EVOLUTION",diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.pyindex 426cd54de4..2fbdf996bf 100644--- a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py@@ -16431,6 +16431,7 @@ class JiuWenSwarmDeepAdapter:request,inputs,self._instance,+ image_files=image_files,**team_stream_kwargs,):maybe_mark_answer_first_byte(getattr(chunk, "payload", None))diff --git a/jiuwenswarm/server/runtime/agent_adapter/team_helpers.py b/jiuwenswarm/server/runtime/agent_adapter/team_helpers.pyindex f127086ad9..8cd82f93c8 100644--- a/jiuwenswarm/server/runtime/agent_adapter/team_helpers.py+++ b/jiuwenswarm/server/runtime/agent_adapter/team_helpers.py@@ -2274,11 +2274,64 @@ async def _start_team_stream_round(return request_queue+def _bind_round_image_files_to_agent(+ team_agent: Any, image_files: list[dict[str, Any]]+) -> bool:+ """把本轮上传清单写进 live leader harness 的 build context。++ team 运行期跨轮复用:成员 agent 的 spec / build context 在首次创建时就固定,+ 后续轮次的 ``get_swarm_enriched_team_spec`` 返回值不会被 pool 里的 runtime 使用。+ 因此非首轮上传必须写进 **live** harness 的 ``request_metadata``——openjiuwen 每轮+ 从同一 build context 重建 NativeHarness,provider 在 rail 构造时读到的就是新清单。+ """+ try:+ harness = getattr(team_agent, "harness", None)+ build_context = getattr(harness, "build_context", None)+ request_metadata = getattr(build_context, "request_metadata", None)+ if not isinstance(request_metadata, dict):+ return False+ from jiuwenswarm.agents.harness.common.multimodal import (+ store_team_request_image_files,+ )++ store_team_request_image_files(request_metadata, image_files)+ return True+ except Exception:+ logger.debug(+ "[TeamHelpers] bind round image files failed: %r", team_agent, exc_info=True+ )+ return False+++def _normalize_round_image_files(image_files: Any) -> list[dict[str, Any]]:+ """Normalize the adapter-provided upload manifest for the build-context channel."""+ if not isinstance(image_files, list):+ return []+ return [dict(item) for item in image_files if isinstance(item, dict)]+++async def _bind_round_image_files(+ team_name: str, image_files: list[dict[str, Any]]+) -> None:+ """Refresh the live team runtime's upload manifest for the coming round."""+ if not team_name:+ return+ try:+ team_agent = await _current_pool_team_agent(team_name)+ except Exception:+ team_agent = None+ if team_agent is not None:+ _bind_round_image_files_to_agent(team_agent, image_files)+ # 非 pool 场景(create/cold recover)由 fresh spec 的 build_context 承载,+ # request_metadata 已在 enrich 前写好;这里无需再处理。++async def process_team_message_stream(request: Any,inputs: dict[str, Any],deep_agent: DeepAgent,*,+ image_files: list[dict[str, Any]] | None = None,config_base: dict[str, Any] | None = None,sessions_root: str | Path | None = None,rebuild_skill: Any | None = None,@@ -2393,6 +2446,15 @@ async def process_team_message_stream(request_metadata.setdefault("enable_routing", request.params.get("enable_routing") is True)+ # 原生图片输入:team 成员拿不到 adapter 的 agent 属性镜像,上传清单要随+ # build context 到成员侧;这里**覆盖写**(同键可能来自请求 metadata,不能+ # 被外部值当成可信清单),空列表即清除上一轮残留。+ round_image_files = _normalize_round_image_files(image_files)+ from jiuwenswarm.agents.harness.common.multimodal import (+ store_team_request_image_files,+ )++ store_team_request_image_files(request_metadata, round_image_files)resolved_mode = str(request_metadata.get("mode") or "").strip()# Relay-provided model_ref is authoritative for a uniform selection or# a member-level auto assignment. A name-only request remains a@@ -2556,6 +2618,20 @@ async def process_team_message_stream()return+ # 原生图片输入清单绑定:只给"确实会开新一轮"的请求刷新 live build context。+ # - slash 命令(上方各早退 return)与权限 / ask_user 控制续写都不新开 round:+ # 控制续写(reuse_active_waiter)只把作答投递给既有 waiter,其 image_files 由+ # adapter 传空,若在此覆盖写会把 live 清单清空——该图片轮后续新建的成员+ # harness / 上下文溢出重建会读到空清单,`[image #n]` 被判定不在清单内丢弃,+ # 原生图片输入失效(CR-9634-6)。+ # - 首轮 / 冷恢复与普通 follow-up 新轮必须绑定,且必须在投递 query+ # (team_manager.interact / _start_team_stream_round)之前:openjiuwen 每轮用+ # 同一 build context 重建 NativeHarness,投递后再写就赶不上本轮成员的 rail 构造。+ # - 失败早退路径(cancel 拆除在途 / gate_closed / interact 失败)仍会先写入清单,+ # 与修复前一致;这些请求不新开 round,清单不会被该轮读取,下一轮投递前必再覆盖。+ if not reuse_active_waiter:+ await _bind_round_image_files(team_name, round_image_files)+try:first_request_source = "first"if not is_first_request:diff --git a/tests/agents/swarm/test_team_multimodal_image.py b/tests/agents/swarm/test_team_multimodal_image.pynew file mode 100644index 0000000000..12dd6de9df--- /dev/null+++ b/tests/agents/swarm/test_team_multimodal_image.py@@ -0,0 +1,345 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++"""team leader 原生多模态:能力位解析、leader-only rail 挂载、上传清单随 build context。++覆盖 S_22 在 team 模式下的三个断点(原先 leader 既无 rail、能力位又默认 False、+上传清单只镜像到 adapter 的 ``self._instance``):++* ``enable_read_image_multimodal`` 按成员模型条目的 ``modalities`` 解析(声明式,+ 不探测、不按模型名猜);+* ``swarm.multimodal_image`` 只挂 leader,teammate 不挂;+* provider 从 ``SwarmBuildContext.request_metadata`` 取本轮上传清单并绑定到 rail。+"""++from __future__ import annotations++import logging++import pytest++from openjiuwen.agent_teams.schema.deep_agent_spec import (+ DeepAgentSpec,+ RailSpec,+ TeamModelConfig,+)+from openjiuwen.core.foundation.llm.schema.config import (+ ModelClientConfig,+ ModelRequestConfig,+)++from jiuwenswarm.agents.swarm import registry+from jiuwenswarm.agents.swarm.config_specs import build_member_deep_agent_spec+from jiuwenswarm.agents.swarm.context import SwarmBuildContext+++def _config(*, modalities="image", budgets=None) -> dict:+ """Minimal config: one default model entry plus optional image budgets."""+ return {+ "models": {+ "defaults": [+ {+ "model_client_config": {"model_name": "vision-model"},+ "modalities": modalities,+ "is_default": True,+ }+ ]+ },+ "react": budgets or {},+ }+++def _pinned_model_spec(model_name: str) -> DeepAgentSpec:+ return DeepAgentSpec(+ model=TeamModelConfig(+ model_client_config=ModelClientConfig(+ client_provider="openai",+ api_key="sk-unit-test",+ api_base="http://127.0.0.1:1",+ ),+ model_request_config=ModelRequestConfig(model_name=model_name),+ )+ )+++def _leader_rail(spec: DeepAgentSpec) -> RailSpec | None:+ return next(+ (rail for rail in spec.rails or [] if rail.type == registry.MULTIMODAL_IMAGE),+ None,+ )++[email protected]("mode", ["team", "code.team", "team.plan"])+def test_leader_gets_multimodal_rail_and_capability_flag(mode: str) -> None:+ """leader 必须挂 rail,且能力位按模型 modalities 写成显式 bool。"""++ config = _config(modalities=["text", "image"])++ leader = build_member_deep_agent_spec(config, mode, "leader", DeepAgentSpec())++ assert leader.enable_read_image_multimodal is True+ rail = _leader_rail(leader)+ assert rail is not None+ assert rail.params["enable_image_multimodal"] is True+ # leader 额外拿到"把图交给成员时保留引用行"的提示开关。+ assert rail.params["dispatch_hint"] is True+++def test_teammate_gets_multimodal_rail_without_dispatch_hint() -> None:+ """teammate 也挂 rail(可按引用行原生看图),但不需要"转发给成员"的提示。"""++ config = _config(modalities=["text", "image"])++ teammate = build_member_deep_agent_spec(config, "team", "teammate", DeepAgentSpec())++ assert teammate.enable_read_image_multimodal is True+ rail = _leader_rail(teammate)+ assert rail is not None+ assert rail.params["enable_image_multimodal"] is True+ assert "dispatch_hint" not in rail.params+++def test_text_only_model_disables_native_image() -> None:+ """modalities 不含 image → 能力位 False,rail 走「过滤视图」分支(N2/N3)。"""++ config = _config(modalities="text")++ leader = build_member_deep_agent_spec(config, "team", "leader", DeepAgentSpec())++ assert leader.enable_read_image_multimodal is False+ rail = _leader_rail(leader)+ assert rail is not None+ assert rail.params["enable_image_multimodal"] is False+++def test_member_model_entry_matches_by_model_name() -> None:+ """成员 spec 指定了模型时按该条目判定,而不是默认条目。"""++ config = {+ "models": {+ "defaults": [+ {+ "model_client_config": {"model_name": "vision-model"},+ "modalities": "text,image",+ "is_default": True,+ },+ {+ "model_client_config": {"model_name": "text-model"},+ "modalities": "text",+ },+ ]+ }+ }++ leader = build_member_deep_agent_spec(+ config, "team", "leader", _pinned_model_spec("text-model")+ )++ assert leader.enable_read_image_multimodal is False+++def test_unknown_pinned_model_does_not_inherit_default_modalities(+ caplog: pytest.LogCaptureFixture,+) -> None:+ """成员 pinned 的模型名未声明时判 False,不得借用默认条目的能力位(N2)。"""++ config = _config(modalities=["text", "image"])++ with caplog.at_level(+ logging.WARNING, logger="jiuwenswarm.agents.swarm.config_specs"+ ):+ leader = build_member_deep_agent_spec(+ config, "team", "leader", _pinned_model_spec("not-listed-model")+ )++ assert leader.enable_read_image_multimodal is False+ rail = _leader_rail(leader)+ assert rail is not None+ assert rail.params["enable_image_multimodal"] is False+ # warning 里带成员模型名,便于定位配置漂移。+ assert "not-listed-model" in caplog.text+++def test_pinned_model_matches_alias() -> None:+ """成员 spec 用 alias 声明模型时,按条目顶层 alias 命中同一份能力声明。"""++ config = {+ "models": {+ "defaults": [+ {+ "alias": "vision",+ "model_client_config": {"model_name": "vision-model"},+ "modalities": ["text", "image"],+ }+ ]+ }+ }++ leader = build_member_deep_agent_spec(+ config, "team", "leader", _pinned_model_spec("vision")+ )++ assert leader.enable_read_image_multimodal is True+++def test_config_without_models_section_disables_native_image() -> None:+ """无 models 段(env 兜底形态)→ 未声明即不支持,不再按 env 条目判定(N2)。"""++ leader = build_member_deep_agent_spec(+ {"react": {}}, "team", "leader", DeepAgentSpec()+ )++ assert leader.enable_read_image_multimodal is False+++def test_legacy_single_default_entry_is_honored() -> None:+ """旧格式 ``models.default`` 单对象同样按声明解析,不因缺 defaults 列表判 False。"""++ config = {+ "models": {+ "default": {+ "model_client_config": {"model_name": "vision-model"},+ "modalities": "text,image",+ }+ }+ }++ leader = build_member_deep_agent_spec(config, "team", "leader", DeepAgentSpec())++ assert leader.enable_read_image_multimodal is True+++class _DeepCopyProbe:+ """探针:模型条目一旦被 deepcopy(旧实现 ``get_default_models`` 的解密路径)即报错。"""++ def __deepcopy__(self, memo: dict[int, object]) -> _DeepCopyProbe:+ raise AssertionError("能力位解析不得对模型条目做 deepcopy / api_key 解密")+++def test_capability_resolution_skips_entry_copy_and_decryption() -> None:+ """能力位只读声明字段;不因每成员每轮调用而深拷贝 / 解密模型条目。"""++ config = _config(modalities=["text", "image"])+ config["models"]["defaults"][0]["copy_probe"] = _DeepCopyProbe()++ leader = build_member_deep_agent_spec(config, "team", "leader", DeepAgentSpec())++ assert leader.enable_read_image_multimodal is True+++def test_explicit_spec_flag_wins_over_modalities() -> None:+ """blueprint 显式写了能力位时以显式值为准(不覆盖用户配置)。"""++ config = _config(modalities=["text", "image"])+ base = DeepAgentSpec(enable_read_image_multimodal=False)++ leader = build_member_deep_agent_spec(config, "team", "leader", base)++ assert leader.enable_read_image_multimodal is False+ rail = _leader_rail(leader)+ assert rail is not None+ assert rail.params["enable_image_multimodal"] is False+++def test_rail_params_carry_image_budgets() -> None:+ """三预算从 ``react.multimodal_image_*`` 烘进 RailSpec.params(0 表示不限)。"""++ config = _config(+ modalities=["text", "image"],+ budgets={+ "multimodal_image_budget": 1048576,+ "multimodal_image_token_budget": 2048,+ "multimodal_image_max_count": 4,+ },+ )++ leader = build_member_deep_agent_spec(config, "team", "leader", DeepAgentSpec())++ assert _leader_rail(leader).params == {+ "enable_image_multimodal": True,+ "max_total_bytes": 1048576,+ "max_visual_tokens": 2048,+ "max_count": 4,+ "dispatch_hint": True,+ }+++def test_provider_binds_round_manifest_from_build_context() -> None:+ """provider 构造 rail 时快照 build context 里的本轮上传清单。"""++ config = _config(modalities=["text", "image"])+ leader = build_member_deep_agent_spec(config, "team", "leader", DeepAgentSpec())+ rail_spec = _leader_rail(leader)+ context = SwarmBuildContext(+ session_id="session-1",+ request_metadata={+ "multimodal_image_files": [+ {+ "type": "image",+ "path": "/tmp/0.jpg",+ "filename": "0.jpg",+ "mime_type": "image/jpeg",+ }+ ]+ },+ )++ rail = RailSpec(type=rail_spec.type, params=rail_spec.params).build(+ language="cn", context=context+ )++ assert rail is not None+ assert rail._bound_image_files == [+ {+ "type": "image",+ "path": "/tmp/0.jpg",+ "filename": "0.jpg",+ "mime_type": "image/jpeg",+ }+ ]+ assert rail._enable_image_multimodal is True+ assert rail._dispatch_hint is True+++def test_teammate_provider_binds_the_same_round_manifest() -> None:+ """teammate 的 rail 同样从 build context 拿到本轮清单(是否出图由引用行决定)。"""++ config = _config(modalities=["text", "image"])+ teammate = build_member_deep_agent_spec(config, "team", "teammate", DeepAgentSpec())+ rail_spec = _leader_rail(teammate)+ context = SwarmBuildContext(+ session_id="session-1",+ request_metadata={+ "multimodal_image_files": [+ {+ "type": "image",+ "path": "/tmp/1.jpg",+ "filename": "1.jpg",+ "mime_type": "image/jpeg",+ }+ ]+ },+ )++ rail = RailSpec(type=rail_spec.type, params=rail_spec.params).build(+ language="cn", context=context+ )++ assert rail is not None+ assert [item["path"] for item in rail._bound_image_files] == ["/tmp/1.jpg"]+ assert rail._dispatch_hint is False+++def test_provider_without_manifest_leaves_rail_unbound() -> None:+ """request_metadata 里没有清单时返回未绑定 rail(回退 agent 属性 / ContextVar)。"""++ config = _config(modalities=["text", "image"])+ leader = build_member_deep_agent_spec(config, "team", "leader", DeepAgentSpec())+ rail_spec = _leader_rail(leader)+ context = SwarmBuildContext(session_id="session-1")++ rail = RailSpec(type=rail_spec.type, params=rail_spec.params).build(+ language="cn", context=context+ )++ assert rail is not None+ assert rail._bound_image_files is Nonediff --git a/tests/unit_tests/agents/harness/common/multimodal/test_image_reference.py b/tests/unit_tests/agents/harness/common/multimodal/test_image_reference.pyindex e339128519..3304dc5ddd 100644--- a/tests/unit_tests/agents/harness/common/multimodal/test_image_reference.py+++ b/tests/unit_tests/agents/harness/common/multimodal/test_image_reference.py@@ -7,9 +7,13 @@ from __future__ import annotationsimport pytestfrom jiuwenswarm.agents.harness.common.multimodal.image_reference import (+ augment_message_with_reference_lines,build_image_reference_line,extract_multimodal_image_files,+ normalize_image_mention_text,+ normalized_text_mentions_image,parse_image_references,+ text_mentions_image,)@@ -135,3 +139,146 @@ def test_dedup_and_invalid_filtered() -> None:]result = extract_multimodal_image_files({"files": files})assert [r["path"] for r in result] == ["/tmp/a.png"]+++# ---------------------------------------------------------------------------+# leader 分发兜底:消息里只提文件名 / 路径时补引用行+# ---------------------------------------------------------------------------++_MANIFEST = [+ {+ "type": "image",+ "path": "/tmp/2.jpg",+ "filename": "2.jpg",+ "mime_type": "image/jpeg",+ "size_bytes": 111,+ },+ {+ "type": "image",+ "path": "/tmp/3.jpg",+ "filename": "3.jpg",+ "mime_type": "image/jpeg",+ "size_bytes": 222,+ },+]+++def test_augment_by_filename_appends_reference_line() -> None:+ text = "请识别 3.jpg 并给出描述。"++ updated = augment_message_with_reference_lines(text, _MANIFEST)++ assert updated.startswith(text)+ assert "[image #1] path=/tmp/3.jpg filename=3.jpg mime=image/jpeg size=222" in updated+ assert "2.jpg" not in updated.split("\n")[-1]+++def test_augment_by_path_appends_reference_line() -> None:+ text = "图片在 /tmp/2.jpg"++ updated = augment_message_with_reference_lines(text, _MANIFEST)++ assert "[image #1] path=/tmp/2.jpg filename=2.jpg mime=image/jpeg size=111" in updated+++def test_augment_skips_images_not_mentioned() -> None:+ text = "请识别第二张图片" # 没有文件名 / 路径,无从判断是哪张++ assert augment_message_with_reference_lines(text, _MANIFEST) == text+++def test_augment_is_idempotent_for_existing_reference_line() -> None:+ text = (+ "任务:\n"+ "[image #2] path=/tmp/3.jpg filename=3.jpg mime=image/jpeg size=222"+ )++ assert augment_message_with_reference_lines(text, _MANIFEST) == text+++def test_augment_uses_next_index_and_respects_cap() -> None:+ text = "看 [image #7] path=/other.png filename=other.png mime=image/png,识别 2.jpg 与 3.jpg"++ updated = augment_message_with_reference_lines(text, _MANIFEST, max_images=1)++ assert "[image #8] path=/tmp/2.jpg" in updated+ assert "/tmp/3.jpg" not in updated+++def test_augment_without_manifest_is_noop() -> None:+ text = "识别 3.jpg"+ assert augment_message_with_reference_lines(text, None) == text+ assert augment_message_with_reference_lines(text, []) == text+++# ---------------------------------------------------------------------------+# 提及判定(CR-9634-2):边界对齐 + 分隔符 / 大小写归一+# ---------------------------------------------------------------------------+++def test_text_mentions_image_requires_token_boundaries() -> None:+ """命中必须整名对齐:``1.png`` 不命中 ``11.png`` / ``data.png``。"""++ image = _image("/tmp/1.png", filename="1.png")++ assert text_mentions_image(image, "请识别 1.png 并描述") is True+ assert text_mentions_image(image, "请识别3.png") is False+ assert text_mentions_image(image, "见 C:/uploads/11.png") is False+ assert text_mentions_image(image, "见 data.png") is False+++def test_text_mentions_image_matches_chinese_adjacent_filename() -> None:+ """中文紧贴文件名仍是合法提及(边界按 ASCII 文件名类字符判定)。"""++ image = _image("/tmp/3.jpg", filename="3.jpg")++ assert text_mentions_image(image, "请识别3.jpg") is True+++def test_text_mentions_image_normalizes_separator_and_case() -> None:+ """路径比较前统一分隔符并忽略大小写;filename 按 basename 形态比较。"""++ image = _image("C:/uploads/3.jpg", filename="C:\\uploads\\3.jpg")++ assert text_mentions_image(image, "图片在 C:\\Uploads\\3.JPG") is True+ assert text_mentions_image(image, "图片在 c:/uploads/3.jpg") is True+ assert text_mentions_image(image, "图片在 C:/uploads/13.jpg") is False+++def test_augment_ignores_substring_filename_mention() -> None:+ """leader 兜底同样不得把 11.png / data.png 当成 1.png(裸子串过宽)。"""++ manifest = [{"type": "image", "path": "/tmp/1.png", "filename": "1.png", "mime_type": "image/png"}]++ assert augment_message_with_reference_lines("识别 11.png", manifest) == "识别 11.png"+ assert augment_message_with_reference_lines("识别 data.png", manifest) == "识别 data.png"+++def test_normalized_text_mentions_image_reuses_one_normalized_text() -> None:+ """已归一入口:调用方归一一次即可对多张图复用(批量场景不重复 lower 同一段文本)。"""++ normalized = normalize_image_mention_text("请识别 C:\\Uploads\\1.PNG")+ first = _image("/tmp/1.png", filename="1.png")+ second = _image("/tmp/11.png", filename="11.png")++ assert normalized_text_mentions_image(first, normalized) is True+ assert normalized_text_mentions_image(second, normalized) is False+++def test_augment_matches_windows_separator_path_mention() -> None:+ """正文用 Windows 反斜杠形态写路径时也能补引用行(文件名不同名时靠路径归一)。"""++ manifest = [+ {+ "type": "image",+ "path": "C:/uploads/3.jpg",+ "filename": "截图 3.jpg",+ "mime_type": "image/jpeg",+ "size_bytes": 222,+ }+ ]++ updated = augment_message_with_reference_lines("请识别 C:\\uploads\\3.jpg", manifest)++ assert "[image #1] path=C:/uploads/3.jpg" in updated+diff --git a/tests/unit_tests/agents/harness/common/multimodal/test_manifest_mention_injection.py b/tests/unit_tests/agents/harness/common/multimodal/test_manifest_mention_injection.pynew file mode 100644index 0000000000..4dd3ad71b5--- /dev/null+++ b/tests/unit_tests/agents/harness/common/multimodal/test_manifest_mention_injection.py@@ -0,0 +1,283 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++"""成员侧确定性分发:上下文任意位置提到清单图 → 补引用行(不依赖 leader 消息格式)。"""++from __future__ import annotations++from jiuwenswarm.agents.harness.common.multimodal import image_history+from jiuwenswarm.agents.harness.common.multimodal.image_history import (+ ensure_manifest_images_referenced,+ inject_image_content_from_references,+)++_MANIFEST = [+ {+ "type": "image",+ "path": "C:/uploads/3.jpg",+ "filename": "3.jpg",+ "mime_type": "image/jpeg",+ "size_bytes": 222,+ },+ {+ "type": "image",+ "path": "C:/uploads/2.jpg",+ "filename": "2.jpg",+ "mime_type": "image/jpeg",+ "size_bytes": 111,+ },+]+++def _user(text: str) -> dict:+ return {"role": "user", "content": text}+++def _tool(text: str) -> dict:+ return {"role": "tool", "content": text}+++def _plain(message: dict) -> str:+ content = message.get("content")+ if isinstance(content, str):+ return content+ if isinstance(content, list):+ return "\n".join(+ part.get("text") or ""+ for part in content+ if isinstance(part, dict) and part.get("type") == "text"+ )+ return ""+++def test_mention_in_tool_result_adds_reference_to_user_message() -> None:+ """任务看板(tool result)里的图片路径 → 补到最近 user 消息,交给 inject 物化。"""++ messages = [+ _user("团队上下文/任务通知"),+ _tool("任务内容:图片文件(绝对路径):C:/uploads/3.jpg"),+ ]++ count = ensure_manifest_images_referenced(messages, _MANIFEST)++ assert count == 1+ text = _plain(messages[0])+ assert "[image #1] path=C:/uploads/3.jpg filename=3.jpg mime=image/jpeg size=222" in text+ assert "2.jpg" not in text+++def test_mention_by_filename_in_message() -> None:+ messages = [_user("请识别 3.jpg")]++ assert ensure_manifest_images_referenced(messages, _MANIFEST) == 1+ assert "[image #1] path=C:/uploads/3.jpg" in _plain(messages[0])+++def test_no_mention_is_noop() -> None:+ messages = [_user("请识别第二张图片"), _tool("与图片无关的任务内容")]++ assert ensure_manifest_images_referenced(messages, _MANIFEST) == 0+ assert _plain(messages[0]) == "请识别第二张图片"+++def test_already_attached_is_not_repeated() -> None:+ """已有 [image #n attached] 的图不再补引用行(跨模型调用幂等)。"""++ messages = [+ _user(+ "任务\n"+ "[image #1] path=C:/uploads/3.jpg filename=3.jpg mime=image/jpeg size=222\n"+ "[image #1 attached]"+ ),+ _tool("图片文件(绝对路径):C:/uploads/3.jpg"),+ ]++ assert ensure_manifest_images_referenced(messages, _MANIFEST) == 0+++def test_respects_max_images_and_allocates_next_index() -> None:+ messages = [+ _user(+ "已有引用\n"+ "[image #5] path=C:/other.png filename=other.png mime=image/png\n"+ "以及 3.jpg 和 2.jpg"+ )+ ]++ count = ensure_manifest_images_referenced(messages, _MANIFEST, max_images=1)++ assert count == 1+ text = _plain(messages[0])+ assert "[image #6] path=C:/uploads/3.jpg" in text+ assert "2.jpg filename=2.jpg" not in text+++def test_without_manifest_is_noop() -> None:+ messages = [_user("请识别 3.jpg")]+ assert ensure_manifest_images_referenced(messages, None) == 0+ assert ensure_manifest_images_referenced(messages, []) == 0+++# ---------------------------------------------------------------------------+# CR-9634-1:omitted 是终态,不得每轮重新补引用行 / 重新读盘物化+# ---------------------------------------------------------------------------+++def test_omitted_image_is_not_rematerialized() -> None:+ """已 omitted 的清单图视为已处理:跨模型调用幂等,不再补行、不再物化。"""++ messages = [+ _user(+ "任务\n"+ "[image #1] path=C:/uploads/3.jpg filename=3.jpg mime=image/jpeg size=222\n"+ "[image #1 omitted: request budget]"+ ),+ _tool("图片文件(绝对路径):C:/uploads/3.jpg"),+ ]+ before = _plain(messages[0])++ count = ensure_manifest_images_referenced(messages, _MANIFEST)++ assert count == 0+ # 原故障:下一次 before_model_call 又补一条 [image #2] 引用行,再读盘物化一次。+ assert _plain(messages[0]) == before+ assert "[image #2]" not in _plain(messages[0])++ _, attached = inject_image_content_from_references(+ list(messages), image_files=_MANIFEST+ )+ assert attached == 0+ assert _plain(messages[0]) == before+++def test_duplicate_omitted_image_is_not_rematerialized() -> None:+ """``omitted: duplicate`` 同样是终态:同路径已由别的消息提供像素,不再补行。"""++ messages = [+ _user(+ "任务\n"+ "[image #2] path=C:/uploads/3.jpg filename=3.jpg mime=image/jpeg size=222\n"+ "[image #2 omitted: duplicate]"+ ),+ _tool("图片文件(绝对路径):C:/uploads/3.jpg"),+ ]+ before = _plain(messages[0])++ assert ensure_manifest_images_referenced(messages, _MANIFEST) == 0+ assert _plain(messages[0]) == before+++# ---------------------------------------------------------------------------+# CR-9634-2:提及判定边界(裸子串会误命中更长的文件名 / 不同路径)+# ---------------------------------------------------------------------------++_SHORT_NAME_MANIFEST = [+ {+ "type": "image",+ "path": "C:/uploads/1.png",+ "filename": "1.png",+ "mime_type": "image/png",+ },+]+++def test_short_filename_is_not_substring_mention() -> None:+ """清单 1.png 不得被 tool result 里的 11.png / data.png 误命中(裸子串过宽)。"""++ messages = [+ _user("团队上下文/任务通知"),+ _tool("任务看板:图片文件(路径):C:/uploads/11.png;另见 data.png"),+ ]++ assert ensure_manifest_images_referenced(messages, _SHORT_NAME_MANIFEST) == 0+ assert _plain(messages[0]) == "团队上下文/任务通知"+++def test_longer_manifest_name_is_not_matched_by_shorter_text() -> None:+ """反方向同样要求整名对齐:清单 11.png 不被文本里的 1.png 命中。"""++ messages = [_user("团队上下文/任务通知"), _tool("图片文件:C:/uploads/1.png")]++ assert ensure_manifest_images_referenced(messages, _MANIFEST_11) == 0+ assert _plain(messages[0]) == "团队上下文/任务通知"+++_MANIFEST_11 = [+ {+ "type": "image",+ "path": "C:/uploads/11.png",+ "filename": "11.png",+ "mime_type": "image/png",+ },+]++# 上传方可能给图改名(filename 与路径 basename 不同):此时路径命中只能靠路径归一,+# 不能依赖文件名兜底。+_RENAMED_MANIFEST = [+ {+ "type": "image",+ "path": "C:/uploads/3.jpg",+ "filename": "截图 3.jpg",+ "mime_type": "image/jpeg",+ "size_bytes": 222,+ },+]+++def test_path_with_different_separator_and_case_matches() -> None:+ """Windows 反斜杠 / 大小写形态的路径文本仍命中清单路径(归一后比较)。"""++ messages = [_user("上下文"), _tool("图片文件(绝对路径):C:\\Uploads\\3.JPG")]++ assert ensure_manifest_images_referenced(messages, _MANIFEST) == 1+ assert "[image #1] path=C:/uploads/3.jpg" in _plain(messages[0])+++def test_path_mention_matches_across_separators_without_filename_fallback() -> None:+ """filename 与路径 basename 不同时,路径归一形态必须独立命中(不能只靠文件名兜底)。"""++ messages = [_user("上下文"), _tool("图片文件(绝对路径):C:\\Uploads\\3.JPG")]++ assert ensure_manifest_images_referenced(messages, _RENAMED_MANIFEST) == 1+ assert "[image #1] path=C:/uploads/3.jpg" in _plain(messages[0])+++def test_normalizes_each_message_text_once_for_all_images(monkeypatch) -> None:+ """N 张图 × 全量消息只做「每条消息一次」归一,不逐图重复 lower 长文本。"""++ origin = image_history.normalize_image_mention_text+ normalized_calls: list[str] = []++ def _counting_normalize(text: str) -> str:+ normalized_calls.append(text)+ return origin(text)++ monkeypatch.setattr(+ image_history, "normalize_image_mention_text", _counting_normalize+ )++ manifest = [+ {+ "type": "image",+ "path": "C:/uploads/1.png",+ "filename": "1.png",+ "mime_type": "image/png",+ },+ {+ "type": "image",+ "path": "C:/uploads/2.png",+ "filename": "2.png",+ "mime_type": "image/png",+ },+ {+ "type": "image",+ "path": "C:/uploads/3.png",+ "filename": "3.png",+ "mime_type": "image/png",+ },+ ]+ long_tool_text = "任务看板:" + ("无关内容 " * 5000) + " C:/uploads/2.png"+ messages = [_user("上下文"), _tool(long_tool_text)]++ assert ensure_manifest_images_referenced(messages, manifest) == 1+ # 逐 (图, 文本) 组合归一(旧实现 / 误用便捷封装)会让这段长文本被归一 3 次。+ assert normalized_calls.count(long_tool_text) == 1diff --git a/tests/unit_tests/agents/harness/common/multimodal/test_team_image_manifest.py b/tests/unit_tests/agents/harness/common/multimodal/test_team_image_manifest.pynew file mode 100644index 0000000000..893df14c76--- /dev/null+++ b/tests/unit_tests/agents/harness/common/multimodal/test_team_image_manifest.py@@ -0,0 +1,72 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++"""team 上传清单经 ``request_metadata`` 传递(S_22 team 通道)。"""++from __future__ import annotations++import pytest++from jiuwenswarm.agents.harness.common.multimodal.image_reference import (+ store_team_request_image_files,+ team_request_image_files,+)++_IMAGES = [+ {+ "type": "image",+ "path": "/tmp/0.jpg",+ "filename": "0.jpg",+ "mime_type": "image/jpeg",+ },+ {+ "type": "image",+ "path": "/tmp/1.jpg",+ "filename": "1.jpg",+ "mime_type": "image/jpeg",+ },+]+++def test_store_then_read_round_trip() -> None:+ metadata: dict = {}++ store_team_request_image_files(metadata, _IMAGES)++ assert team_request_image_files(metadata) == _IMAGES+++def test_read_returns_copy_not_shared_list() -> None:+ """读侧返回副本:成员 rail 改动不得回写 build context 的 metadata。"""++ metadata: dict = {}+ store_team_request_image_files(metadata, _IMAGES)++ first = team_request_image_files(metadata)+ first.append(+ {"type": "image", "path": "/tmp/injected.jpg", "mime_type": "image/jpeg"}+ )++ assert len(team_request_image_files(metadata)) == 2+++def test_empty_list_is_authoritative_clear() -> None:+ """空列表是"本轮没有上传"的权威事实,不是"没写"——必须覆盖旧值。"""++ metadata = {"multimodal_image_files": _IMAGES}++ store_team_request_image_files(metadata, [])++ assert team_request_image_files(metadata) == []+++def test_read_missing_or_invalid_returns_none() -> None:+ assert team_request_image_files({}) is None+ assert team_request_image_files(None) is None+ assert team_request_image_files({"multimodal_image_files": "not-a-list"}) is None++[email protected]("metadata", [None, "text", 0])+def test_store_ignores_non_mapping(metadata) -> None:+ """非 mapping 入参静默忽略:装配链不得因为 metadata 形态异常而失败。"""++ store_team_request_image_files(metadata, _IMAGES)diff --git a/tests/unit_tests/agents/harness/common/rails/test_multimodal_image_rail_bound_files.py b/tests/unit_tests/agents/harness/common/rails/test_multimodal_image_rail_bound_files.pynew file mode 100644index 0000000000..3fcdbd952a--- /dev/null+++ b/tests/unit_tests/agents/harness/common/rails/test_multimodal_image_rail_bound_files.py@@ -0,0 +1,226 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++"""MultimodalImageRail 的「装配期绑定清单」分支(team leader 使用)。"""++from __future__ import annotations++import asyncio+from types import SimpleNamespace++from jiuwenswarm.agents.harness.common.multimodal.image_reference import (+ store_current_multimodal_image_files_on_agent,+)+from jiuwenswarm.agents.harness.common.rails.multimodal_image_rail import (+ MultimodalImageRail,+)++_AGENT_IMAGES = [+ {+ "type": "image",+ "path": "/tmp/agent-attr.jpg",+ "filename": "agent-attr.jpg",+ "mime_type": "image/jpeg",+ }+]+_BOUND_IMAGES = [+ {"type": "image", "path": "/tmp/round-upload.jpg", "filename": "round-upload.jpg"}+]+++def test_bound_manifest_wins_over_agent_attribute() -> None:+ """装配期绑定的清单优先于 agent 属性镜像(team leader 的清单只存在于 build context)。"""++ agent = SimpleNamespace()+ store_current_multimodal_image_files_on_agent(agent, _AGENT_IMAGES)+ rail = MultimodalImageRail(image_files=_BOUND_IMAGES)+ rail.init(agent)++ assert rail._resolve_request_image_files() == _BOUND_IMAGES+++def test_empty_bound_manifest_does_not_fall_back_to_agent_attribute() -> None:+ """空清单是权威事实:本轮没有新上传,不得回退读 agent 上一轮的残留。"""++ agent = SimpleNamespace()+ store_current_multimodal_image_files_on_agent(agent, _AGENT_IMAGES)+ rail = MultimodalImageRail(image_files=[])+ rail.init(agent)++ assert rail._resolve_request_image_files() == []+++def test_unbound_rail_falls_back_to_agent_attribute() -> None:+ """没传 image_files 时保持单 agent 旧行为:读 agent 实例镜像。"""++ agent = SimpleNamespace()+ store_current_multimodal_image_files_on_agent(agent, _AGENT_IMAGES)+ rail = MultimodalImageRail()+ rail.init(agent)++ assert rail._resolve_request_image_files() == _AGENT_IMAGES+++def test_unbound_rail_without_agent_mirror_returns_none() -> None:+ """单 agent 旧行为:agent 上没有镜像 → None,交给 inject 回退 ContextVar。"""++ rail = MultimodalImageRail()+ rail.init(SimpleNamespace())++ assert rail._resolve_request_image_files() is None+++class _RecordingPromptBuilder:+ """最小 PromptSection 容器:只记录 add/remove。"""++ def __init__(self) -> None:+ self.sections: dict[str, object] = {}++ def remove_section(self, name: str) -> None:+ self.sections.pop(name, None)++ def add_section(self, section) -> None:+ self.sections[section.name] = section+++def _policy_text(rail: MultimodalImageRail, images_sent: int = 2) -> str:+ builder = _RecordingPromptBuilder()+ rail.init(SimpleNamespace(system_prompt_builder=builder))+ rail._sync_image_policy_section(True, images_sent)+ return builder.sections["multimodal_image_policy"].content["cn"]+++def test_team_member_path_guidance_points_to_native_read_file() -> None:+ """成员还没拿到像素时,引导用 read_file 原生读图,而不是 VQA/OCR。"""++ rail = MultimodalImageRail(enable_image_multimodal=True, image_files=_MANIFEST)++ text = _policy_text(rail, images_sent=0)++ assert "read_file" in text+ assert "不要调用 visual_question_answering" in text+ assert "已作为图像内容直接提供" not in text+++def test_member_policy_switches_to_native_once_pixels_sent() -> None:+ """像素已提供后改用原生策略段(不再引导 read_file)。"""++ rail = MultimodalImageRail(enable_image_multimodal=True, image_files=_MANIFEST)++ text = _policy_text(rail, images_sent=2)++ assert "已作为图像内容直接提供" in text+ assert "不要调用 visual_question_answering" in text+ assert "请直接使用 read_file" not in text+++def test_leader_and_single_agent_get_no_path_guidance() -> None:+ """leader(dispatch_hint)/ 单 agent(未绑定清单)没有像素时不写该段。"""++ for rail in (+ MultimodalImageRail(enable_image_multimodal=True, dispatch_hint=True, image_files=_MANIFEST),+ MultimodalImageRail(enable_image_multimodal=True),+ ):+ builder = _RecordingPromptBuilder()+ rail.init(SimpleNamespace(system_prompt_builder=builder))+ rail._sync_image_policy_section(True, 0)+ assert "multimodal_image_policy" not in builder.sections+++def test_leader_dispatch_hint_tells_how_to_forward_reference_line() -> None:+ """leader 原生策略段要说明:交给成员时用 send_message 保留引用行。"""++ rail = MultimodalImageRail(enable_image_multimodal=True, dispatch_hint=True)++ text = _policy_text(rail)++ assert "send_message" in text+ assert "[image #n] path=" in text+ assert "任务看板" in text+++def test_dispatch_hint_absent_by_default_and_without_images() -> None:+ """默认(teammate / 单 agent)不写转发提示;0 张图时整段策略也不写。"""++ rail = MultimodalImageRail(enable_image_multimodal=True)+ text = _policy_text(rail)+ assert "任务看板" not in text++ builder = _RecordingPromptBuilder()+ rail.init(SimpleNamespace(system_prompt_builder=builder))+ rail._sync_image_policy_section(True, 0)+ assert "multimodal_image_policy" not in builder.sections+++_MANIFEST = [+ {+ "type": "image",+ "path": "/tmp/2.jpg",+ "filename": "2.jpg",+ "mime_type": "image/jpeg",+ "size_bytes": 111,+ },+ {+ "type": "image",+ "path": "/tmp/3.jpg",+ "filename": "3.jpg",+ "mime_type": "image/jpeg",+ "size_bytes": 222,+ },+]+++def _send_ctx(target, content: str) -> SimpleNamespace:+ arguments = {"to": target, "content": content}+ tool_call = SimpleNamespace(name="send_message", arguments=arguments)+ inputs = SimpleNamespace(+ tool_name="send_message", tool_call=tool_call, tool_args=arguments+ )+ return SimpleNamespace(inputs=inputs)+++def test_leader_send_message_gets_missing_reference_line() -> None:+ """leader 消息只写 "3.jpg" 时,工具执行前补成完整引用行(用户消息通道)。"""++ rail = MultimodalImageRail(+ enable_image_multimodal=True, dispatch_hint=True, image_files=_MANIFEST+ )+ rail.init(SimpleNamespace())+ ctx = _send_ctx("vision-analyst", "请识别 3.jpg 并交付描述")++ asyncio.run(rail.before_tool_call(ctx))++ content = ctx.inputs.tool_call.arguments["content"]+ assert "[image #1] path=/tmp/3.jpg filename=3.jpg mime=image/jpeg size=222" in content+ assert ctx.inputs.tool_args["content"] == content+++def test_dispatch_augment_skips_broadcast_and_user_targets() -> None:+ """广播 / 回用户不补引用行:避免把上传清单发给无关成员或用户。"""++ for target in ("*", "user", ["vision-analyst", "*"]):+ rail = MultimodalImageRail(+ enable_image_multimodal=True, dispatch_hint=True, image_files=_MANIFEST+ )+ rail.init(SimpleNamespace())+ ctx = _send_ctx(target, "请识别 3.jpg")+ asyncio.run(rail.before_tool_call(ctx))+ assert "[image #" not in ctx.inputs.tool_call.arguments["content"]+++def test_dispatch_augment_only_for_leader_and_send_message() -> None:+ """没有 dispatch_hint(teammate)或不是 send_message 时不改写参数。"""++ rail = MultimodalImageRail(enable_image_multimodal=True, image_files=_MANIFEST)+ rail.init(SimpleNamespace())+ ctx = _send_ctx("vision-analyst", "请识别 3.jpg")+ asyncio.run(rail.before_tool_call(ctx))+ assert "[image #" not in ctx.inputs.tool_call.arguments["content"]++ leader = MultimodalImageRail(+ enable_image_multimodal=True, dispatch_hint=True, image_files=_MANIFEST+ )+ leader.init(SimpleNamespace())+ ctx2 = _send_ctx("vision-analyst", "请识别 3.jpg")+ ctx2.inputs.tool_name = "create_task"+ asyncio.run(leader.before_tool_call(ctx2))+ assert "[image #" not in ctx2.inputs.tool_call.arguments["content"]diff --git a/tests/unit_tests/agentserver/test_evolve_command_edges.py b/tests/unit_tests/agentserver/test_evolve_command_edges.pyindex bf1a11f904..b2cc269292 100644--- a/tests/unit_tests/agentserver/test_evolve_command_edges.py+++ b/tests/unit_tests/agentserver/test_evolve_command_edges.py@@ -703,7 +703,18 @@ async def test_team_stream_keeps_image_reference_for_non_vision_model(request)assert tenant_workspace_key == expected_workspace_key- assert captured["runtime_context"] == {+ runtime_context = dict(captured["runtime_context"])+ # 上传清单随请求传进 team_helpers:leader 的 rail 只能在成员侧读到它+ # (adapter 的 self._instance 属性镜像到不了 team 成员)。+ assert runtime_context.pop("image_files") == [+ {+ "type": "image",+ "filename": "persisted.png",+ "path": "agent/sessions/sess-team-image/uploads/persisted.png",+ "mime_type": "image/png",+ }+ ]+ assert runtime_context == {"config_base": tenant_config,"sessions_root": resolve_tenant_sessions_dir(tenant_workspace_key,diff --git a/tests/unit_tests/agentserver/test_team_multimodal_round_manifest.py b/tests/unit_tests/agentserver/test_team_multimodal_round_manifest.pynew file mode 100644index 0000000000..8de9069046--- /dev/null+++ b/tests/unit_tests/agentserver/test_team_multimodal_round_manifest.py@@ -0,0 +1,349 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++"""team 模式上传清单进入 leader 的 build context(S_22 team 通道)。"""++from __future__ import annotations++from types import SimpleNamespace+from typing import Any++import pytest++from jiuwenswarm.server.runtime.agent_adapter import team_helpers++_IMAGES = [+ {+ "type": "image",+ "path": "/tmp/0.jpg",+ "filename": "0.jpg",+ "mime_type": "image/jpeg",+ }+]+++def _live_agent(metadata: dict) -> SimpleNamespace:+ return SimpleNamespace(+ harness=SimpleNamespace(+ build_context=SimpleNamespace(request_metadata=metadata)+ )+ )+++def test_normalize_round_image_files_filters_non_dicts() -> None:+ assert team_helpers._normalize_round_image_files(None) == []+ assert team_helpers._normalize_round_image_files("nope") == []+ assert team_helpers._normalize_round_image_files([_IMAGES[0], "x", None]) == [+ _IMAGES[0]+ ]+++def test_bind_round_image_files_writes_live_build_context() -> None:+ """跨轮复用的 live runtime 必须拿到本轮清单(fresh spec 不会被 pool 采用)。"""++ metadata: dict = {}+ agent = _live_agent(metadata)++ assert team_helpers._bind_round_image_files_to_agent(agent, _IMAGES) is True+ assert metadata["multimodal_image_files"] == _IMAGES+++def test_bind_round_image_files_clears_stale_manifest() -> None:+ metadata = {"multimodal_image_files": _IMAGES}+ agent = _live_agent(metadata)++ assert team_helpers._bind_round_image_files_to_agent(agent, []) is True+ assert metadata["multimodal_image_files"] == []+++def test_bind_round_image_files_tolerates_missing_context() -> None:+ assert team_helpers._bind_round_image_files_to_agent(SimpleNamespace(), []) is False+ assert (+ team_helpers._bind_round_image_files_to_agent(+ SimpleNamespace(harness=None), _IMAGES+ )+ is False+ )+++async def test_bind_round_image_files_resolves_pool_agent(monkeypatch) -> None:+ metadata: dict = {}+ agent = _live_agent(metadata)++ async def fake_current_agent(team_name: str):+ assert team_name == "unit_team"+ return agent++ monkeypatch.setattr(team_helpers, "_current_pool_team_agent", fake_current_agent)++ await team_helpers._bind_round_image_files("unit_team", _IMAGES)++ assert metadata["multimodal_image_files"] == _IMAGES+++async def test_bind_round_image_files_without_live_agent_is_noop(monkeypatch) -> None:+ async def fake_current_agent(team_name: str):+ return None++ monkeypatch.setattr(team_helpers, "_current_pool_team_agent", fake_current_agent)++ await team_helpers._bind_round_image_files("unit_team", _IMAGES)+++class _StopAfterEnrich(Exception):+ pass+++class _FakeTeamManager:+ """Minimal duck-typed manager: first request, capture enrichment metadata."""++ def __init__(self, captured: dict) -> None:+ self._captured = captured++ def has_stream_task(self, session_id: str) -> bool:+ return False++ def has_waiters(self, session_id: str) -> bool:+ return False++ def is_session_initialized(self, session_id: str) -> bool:+ return False++ async def get_swarm_enriched_team_spec(self, **kwargs):+ self._captured.update(kwargs["request_metadata"])+ raise _StopAfterEnrich+++async def test_process_team_message_stream_puts_manifest_in_request_metadata(+ monkeypatch,+) -> None:+ """首轮/冷恢复路径:清单必须在 enrich 前写进 request_metadata(随 build context)。"""++ captured: dict = {}+ manager = _FakeTeamManager(captured)+ monkeypatch.setattr(team_helpers, "get_team_manager", lambda channel: manager)++ request = SimpleNamespace(+ session_id="session-unit",+ request_id="rid-unit",+ channel_id="web",+ metadata={},+ params={},+ )++ chunks = []+ async for chunk in team_helpers.process_team_message_stream(+ request,+ {"query": "看看这张图"},+ None,+ image_files=_IMAGES,+ ):+ chunks.append(chunk)++ assert captured["multimodal_image_files"] == _IMAGES+ # enrich 抛错后按既有错误路径收尾(不吞异常也不泄漏半截流)。+ assert chunks and chunks[-1].is_complete is True+++class _StopAfterBind(Exception):+ """Sentinel: stop the generator right after the manifest binding."""+++class _LiveRoundTeamManager:+ """Duck-typed manager whose session already owns a live round."""++ def __init__(self, team_spec: Any, *, has_waiters: bool) -> None:+ self._team_spec = team_spec+ self._has_waiters = has_waiters+ self.interacted: list[tuple[str, Any]] = []++ def has_stream_task(self, session_id: str) -> bool:+ return True++ def has_waiters(self, session_id: str) -> bool:+ return self._has_waiters++ def is_session_initialized(self, session_id: str) -> bool:+ return True++ def get_monitor_handler(self, session_id: str) -> None:+ return None++ async def get_swarm_enriched_team_spec(self, **kwargs):+ return self._team_spec++ async def interact(self, session_id: str, query: Any) -> tuple[bool, None]:+ self.interacted.append((session_id, query))+ return True, None+++def _live_round_request() -> SimpleNamespace:+ return SimpleNamespace(+ session_id="session-unit",+ request_id="rid-unit",+ channel_id="web",+ metadata={},+ params={},+ )+++async def test_control_continuation_keeps_live_round_manifest(monkeypatch) -> None:+ """CR-9634-6:控制续写(permission / ask_user 作答)不新开 round,不得清空 live 清单。++ 控制续写由 adapter 传 ``image_files=[]``;若照常覆盖写 live build context,正在+ 进行的图片轮后续新建的成员 harness 会读到空清单,原生图片输入失效。+ """++ live_metadata: dict = {"multimodal_image_files": [dict(item) for item in _IMAGES]}+ live_agent = _live_agent(live_metadata)+ manager = _LiveRoundTeamManager(+ SimpleNamespace(team_name="unit_team"), has_waiters=True+ )++ monkeypatch.setattr(team_helpers, "get_team_manager", lambda channel: manager)+ monkeypatch.setattr(+ team_helpers, "is_team_control_continuation", lambda request, query: True+ )+ monkeypatch.setattr(+ team_helpers,+ "_persist_team_file_monitor_roots",+ lambda *args, **kwargs: None,+ )++ async def fake_slash_command(*args, **kwargs):+ return None++ async def fake_current_agent(team_name: str):+ assert team_name == "unit_team"+ return live_agent++ monkeypatch.setattr(team_helpers, "_handle_team_slash_command", fake_slash_command)+ monkeypatch.setattr(team_helpers, "_current_pool_team_agent", fake_current_agent)++ chunks = []+ async for chunk in team_helpers.process_team_message_stream(+ _live_round_request(),+ {"query": "同意,继续"},+ None,+ image_files=[],+ ):+ chunks.append(chunk)++ # 上一轮清单必须原样保留(修复前这里会被空列表覆盖写)。+ assert live_metadata["multimodal_image_files"] == _IMAGES+ assert manager.interacted and manager.interacted[0][0] == "session-unit"+ payloads = [chunk.payload for chunk in chunks if isinstance(chunk.payload, dict)]+ assert any(+ payload.get("event_type") == "chat.processing_status_deferred"+ for payload in payloads+ )+ assert chunks[-1].payload is None+ assert chunks[-1].is_complete is True++ # 该轮后续新建成员的 rail 仍从同一 build context 拿到清单(reviewer 要求:+ # 图片轮 → 权限作答控制续写 → 「后续新建成员的 rail 仍能拿到 image_files」)。+ from jiuwenswarm.agents.swarm.providers.multimodal import (+ _build_multimodal_image_rail,+ )++ member_rail = _build_multimodal_image_rail(+ {}, SimpleNamespace(request_metadata=live_metadata)+ )+ assert member_rail._bound_image_files == _IMAGES+++async def test_followup_new_round_still_binds_round_manifest(monkeypatch) -> None:+ """普通 follow-up 新轮(无 active waiter)仍须在投递前覆盖写本轮清单。"""++ manager = _LiveRoundTeamManager(+ SimpleNamespace(team_name="unit_team"), has_waiters=False+ )+ bind_calls: list[tuple[str, list[dict]]] = []++ async def fake_bind(team_name: str, image_files: list[dict]) -> None:+ bind_calls.append((team_name, image_files))+ raise _StopAfterBind++ monkeypatch.setattr(team_helpers, "get_team_manager", lambda channel: manager)+ monkeypatch.setattr(+ team_helpers, "is_team_control_continuation", lambda request, query: False+ )+ monkeypatch.setattr(+ team_helpers,+ "_persist_team_file_monitor_roots",+ lambda *args, **kwargs: None,+ )++ async def fake_slash_command(*args, **kwargs):+ return None++ monkeypatch.setattr(team_helpers, "_handle_team_slash_command", fake_slash_command)+ monkeypatch.setattr(team_helpers, "_bind_round_image_files", fake_bind)++ with pytest.raises(_StopAfterBind):+ async for _ in team_helpers.process_team_message_stream(+ _live_round_request(),+ {"query": "继续分析"},+ None,+ image_files=_IMAGES,+ ):+ pass++ assert bind_calls == [("unit_team", _IMAGES)]+++async def test_slash_command_keeps_live_round_manifest(monkeypatch) -> None:+ """slash 命令不新开 round,同样不得覆盖写 live 清单。"""++ live_metadata: dict = {"multimodal_image_files": [dict(item) for item in _IMAGES]}+ live_agent = _live_agent(live_metadata)+ manager = _LiveRoundTeamManager(+ SimpleNamespace(team_name="unit_team"), has_waiters=False+ )++ monkeypatch.setattr(team_helpers, "get_team_manager", lambda channel: manager)+ monkeypatch.setattr(+ team_helpers, "is_team_control_continuation", lambda request, query: False+ )+ monkeypatch.setattr(+ team_helpers,+ "_persist_team_file_monitor_roots",+ lambda *args, **kwargs: None,+ )++ async def fake_slash_command(*args, **kwargs):+ return {"output": "/evolve 结果", "result_type": "answer"}++ async def fake_current_agent(team_name: str):+ assert team_name == "unit_team"+ return live_agent++ monkeypatch.setattr(team_helpers, "_handle_team_slash_command", fake_slash_command)+ monkeypatch.setattr(team_helpers, "_current_pool_team_agent", fake_current_agent)++ request = SimpleNamespace(+ session_id="session-unit",+ request_id="rid-unit",+ channel_id="web",+ metadata={},+ params={"mode": "team"},+ )+ chunks = []+ async for chunk in team_helpers.process_team_message_stream(+ request,+ {"query": "/evolve some_skill"},+ None,+ image_files=[],+ ):+ chunks.append(chunk)++ assert live_metadata["multimodal_image_files"] == _IMAGES+ payloads = [chunk.payload for chunk in chunks if isinstance(chunk.payload, dict)]+ assert any(payload.get("event_type") == "chat.final" for payload in payloads)+ assert chunks[-1].payload is None+ assert chunks[-1].is_complete is True