فهرست منبع

Merge branch 'main' of https://git.yishihui.com/howard/Agent

guantao 1 روز پیش
والد
کامیت
1d52d1ab0c
37فایلهای تغییر یافته به همراه2162 افزوده شده و 1361 حذف شده
  1. 8 1
      .gitignore
  2. 14 1
      agent/core/presets.py
  3. 0 7
      agent/core/runner.py
  4. 474 0
      agent/docs/tools-refactor-plan.md
  5. 219 1
      agent/docs/tools.md
  6. 9 0
      agent/llm/gemini.py
  7. 5 9
      agent/tools/builtin/__init__.py
  8. 21 119
      agent/tools/builtin/crawler.py
  9. 0 5
      agent/tools/builtin/feishu/chat_history/chat_summary.json
  10. 0 103
      agent/tools/builtin/feishu/chat_history/chat_关涛.json
  11. 0 32
      agent/tools/builtin/feishu/chat_history/chat_孙若天.json
  12. 0 22
      agent/tools/builtin/feishu/chat_history/chat_谭景玉.json
  13. 5 2
      agent/tools/builtin/file/read.py
  14. 320 0
      agent/tools/builtin/file/read_images.py
  15. 50 0
      agent/tools/builtin/librarian.py
  16. 0 418
      agent/tools/builtin/sandbox.py
  17. 24 139
      agent/tools/builtin/search.py
  18. 219 111
      agent/tools/builtin/toolhub.py
  19. 1 0
      agent/tools/utils/__init__.py
  20. 289 0
      agent/tools/utils/image.py
  21. 10 5
      examples/mini_restore/call_banana.py
  22. 19 0
      examples/mini_restore/history.json
  23. 151 123
      examples/mini_restore/workflow_loop.py
  24. 2 1
      examples/production_restore/config.py
  25. 21 8
      examples/production_restore/execution.prompt
  26. 5 5
      examples/production_restore/input/pipeline.json
  27. 23 3
      examples/production_restore/presets.json
  28. 116 57
      examples/production_restore/requirement.prompt
  29. 141 0
      examples/production_restore/research.prompt
  30. 2 2
      examples/production_restore/run.py
  31. 0 107
      frontend/htmlTemplate/api_data/goal_list.json
  32. 0 28
      frontend/htmlTemplate/api_data/trace_list.json
  33. 0 0
      frontend/htmlTemplate/ws_data/event.jsonl
  34. 0 28
      frontend/htmlTemplate/ws_data/trace_list.json
  35. 14 14
      knowhub/server.py
  36. BIN
      log.txt
  37. 0 10
      log2.txt

+ 8 - 1
.gitignore

@@ -1,5 +1,6 @@
 # API-KEY
 .env
+.mcp.json
 
 # Python
 __pycache__/
@@ -62,11 +63,17 @@ output
 .trace_test/
 .trace_test2/
 examples/**/output*/
+outputs/
 
 frontend/htmlTemplate/mock_data
+frontend/htmlTemplate/api_data/
+frontend/htmlTemplate/ws_data/
 frontend/react-template/yarn.lock
 frontend/react-template/node_modules/
 
+# Feishu 运行时聊天记录(自动维护,包含联系人 PII)
+agent/tools/builtin/feishu/chat_history/
+
 # data
 knowhub/knowhub.db
 knowhub/knowhub.db-shm
@@ -82,4 +89,4 @@ knowhub/milvus_data/
 vendor/browser-use/
 
 # im-client data
-data/
+data/.mcp.json

+ 14 - 1
agent/core/presets.py

@@ -110,6 +110,7 @@ def load_presets_from_json(json_path: str) -> None:
 
     支持特殊字段:
     - system_prompt_file: 从 .prompt 文件加载 system prompt(相对于 JSON 文件所在目录)
+    - prompt_vars: 变量字典,用于替换 prompt 中的 %variable% 占位符
 
     Args:
         json_path: presets.json 文件路径
@@ -126,11 +127,23 @@ def load_presets_from_json(json_path: str) -> None:
     base_dir = json_path.parent
 
     for name, cfg in presets_data.items():
+        # 提取 prompt_vars(不传给 AgentPreset)
+        prompt_vars = cfg.pop("prompt_vars", None)
+
         # 处理 system_prompt_file
         if "system_prompt_file" in cfg:
             prompt_file = cfg.pop("system_prompt_file")
             prompt_path = base_dir / prompt_file
-            cfg["system_prompt"] = load_system_prompt_from_file(str(prompt_path))
+            system_prompt = load_system_prompt_from_file(str(prompt_path))
+
+            # 应用变量替换
+            if prompt_vars and isinstance(prompt_vars, dict):
+                for var_name, var_value in prompt_vars.items():
+                    placeholder = f"%{var_name}%"
+                    if placeholder in system_prompt:
+                        system_prompt = system_prompt.replace(placeholder, str(var_value))
+
+            cfg["system_prompt"] = system_prompt
 
         preset = AgentPreset(**cfg)
         register_preset(name, preset)

+ 0 - 7
agent/core/runner.py

@@ -180,13 +180,6 @@ BUILTIN_TOOLS = [
     # "knowledge_batch_update",
     # "knowledge_list",
     # "knowledge_slim",
-    
-
-    # 沙箱工具
-    # "sandbox_create_environment",
-    # "sandbox_run_shell",
-    # "sandbox_rebuild_with_ports",
-    # "sandbox_destroy_environment",
 
     # 浏览器工具
     "browser_get_live_url",

+ 474 - 0
agent/docs/tools-refactor-plan.md

@@ -0,0 +1,474 @@
+# 工具体系改造方案(Refactor Plan)
+
+> 本文档是**未来规划**,不是现状描述。当前工具体系的状态请看 [`tools.md`](./tools.md)。
+>
+> 当方案落地后,记得把本文档对应的章节删除或合并到 `tools.md`。
+
+## 背景
+
+本框架的 `@tool` 注册体系经过一段时间的积累后,暴露了几个结构性问题:
+
+1. **工具粒度和组织方式是按"后端架构"而不是"任务语义"划分的**。典型表现:`search_posts`(聚合 9 个中文平台)和 `x_search`(独立)本质上是同一类任务,却因为后端一个统一 endpoint、一个独立 endpoint 就被分成了两个工具
+2. **浏览器工具有 28 个 @tool,LLM 选择负担严重超标**
+3. **沙箱工具已经不再需要**(原本是给运行工具准备的,但工具已经被提取出来单独处理)
+4. **同一套哲学没有贯彻到所有工具族**——toolhub 已经用了"动态发现"模式(search → call),但其他多后端的工具族还是"每个后端一个工具"
+
+本方案解决前两个问题(沙箱直接删除,不需要方案),确立一套**统一的工具设计哲学**供未来所有新工具族参考。
+
+---
+
+## 核心设计哲学:按任务语义划分 + 按规模选择模式
+
+### 哲学 1:LLM 心智负担分四类
+
+- **选择负担**:一堆工具中挑一个
+- **参数构造负担**:知道该工具要哪些参数
+- **流程负担**:需要按什么顺序调几次工具
+- **错误恢复负担**:失败时怎么修复
+
+工具设计要**平衡**这四类负担,而不是只优化其中一类。
+
+### 哲学 2:按"任务语义"而非"后端架构"划分工具
+
+工具的边界应该跟 LLM 的心智模型对齐,而不是跟后端服务的架构对齐。
+
+**反例(现状)**:LLM 看到 `search_posts` / `youtube_search` / `x_search` 三个并列工具,需要记住"中文平台用前者,YouTube 用中者,X 用后者"——这是后端知识泄露到工具层。
+
+**正确姿势**:LLM 看到一个统一的 `content_search(platform, keyword, ...)`,后端路由对 LLM 不可见。
+
+### 哲学 3:按"工具族规模"选择静态或动态模式
+
+| 场景 | 模式 | 代表 |
+|---|---|---|
+| 单一职责工具(正交能力) | 静态扁平 | `read_file` / `bash_command` |
+| 小规模异构工具族(3-10 个) | 静态扁平 + 良好命名 | `knowledge_*` / `sandbox_*` |
+| 中等规模异构工具族(10-20 个) | **语义合并**(Literal 枚举动词) | 浏览器工具 |
+| 大规模多实例工具族(20+ 个同类异质) | **动态发现**(toolhub 模式) | 内容搜索、远程工具库 |
+
+判断标准:**工具之间的差异主要在"参数"还是"能力"?**
+- 差异在参数(navigate/click/type 都是"DOM 操作",只是参数不同)→ 静态合并,用 Literal 动词
+- 差异在能力(9 个平台各有各的搜索语义和专用参数)→ 动态发现
+
+---
+
+## 方案一:内容工具族 → 动态发现模式
+
+### 现状
+
+| 工具 | 后端 | 平台 |
+|---|---|---|
+| `search_posts(keyword, channel, ...)` | `aigc-channel.aiddit.com/data` | 9 个中文平台 |
+| `select_post(index)` | 内存缓存 | 同上 |
+| `get_search_suggestions(keyword, channel)` | `aigc-channel.aiddit.com/suggest` | 同上 |
+| `youtube_search(keyword)` | `crawler.aiddit.com/youtube/keyword` | YouTube |
+| `youtube_detail(content_id, ...)` | `crawler.aiddit.com/youtube/detail` + yt-dlp | YouTube |
+| `x_search(keyword)` | `crawler.aiddit.com/x/keyword` | X |
+| `import_content(plan, data)` | `aigc-channel.aiddit.com/weixin/auto_insert` | 长文导入(非搜索) |
+| `extract_video_clip(...)` | 本地 ffmpeg | 媒体处理(非搜索) |
+
+### 新方案
+
+**3 个统一入口 + N 个内部实现函数(非 @tool)**
+
+```python
+@tool()
+async def content_platforms() -> ToolResult:
+    """列出所有支持的内容平台及其搜索参数 schema。
+
+    建议在 session 开始时调一次,后续 content_search / content_detail 调用时
+    依据此返回构造参数。返回内容在 session 内可以缓存。
+    """
+    return ToolResult(output=json.dumps({
+        "xhs": {
+            "name": "小红书",
+            "backend": "aigc-channel",
+            "search_params": {
+                "sort_type": {
+                    "values": ["综合排序", "最新发布", "最多点赞"],
+                    "default": "综合排序"
+                },
+                "publish_time": {
+                    "values": ["不限", "近1天", "近7天", "近30天"],
+                    "default": "不限"
+                },
+                "content_type": {
+                    "values": ["不限", "图文", "视频", "文章"],
+                    "default": "不限"
+                },
+                "filter_note_range": {
+                    "values": ["不限", "1分钟以内", "1-5分钟", "5分钟以上"],
+                    "default": "不限",
+                    "note": "仅视频内容生效"
+                }
+            },
+            "detail_mode": "cache_index",
+            "extras_example": {
+                "sort_type": "最新发布",
+                "publish_time": "近7天"
+            }
+        },
+        "youtube": {
+            "name": "YouTube",
+            "backend": "crawler",
+            "search_params": {},
+            "detail_mode": "content_id",
+            "detail_extras": {
+                "include_captions": {"type": "bool", "default": True},
+                "download_video": {"type": "bool", "default": False}
+            },
+            "extras_example": {}
+        },
+        "x": {
+            "name": "X (Twitter)",
+            "backend": "crawler",
+            "search_params": {},
+            "detail_mode": "not_supported",
+            "extras_example": {}
+        },
+        # ... 9 个中文平台 + YouTube + X,总共 11 个
+    }))
+
+
+@tool()
+async def content_search(
+    platform: str,
+    keyword: str,
+    max_count: int = 20,
+    extras: Optional[Dict[str, Any]] = None,
+) -> ToolResult:
+    """跨平台内容搜索,返回带索引编号的封面拼图 + 结构化列表。
+
+    参数说明:
+        platform: 平台标识,如 'xhs'、'youtube'、'x'。完整列表见 content_platforms。
+        keyword: 搜索关键词。
+        max_count: 返回条数上限,默认 20。
+        extras: 平台专用参数。如果不清楚某平台支持什么,先调用 content_platforms
+                查看 search_params 字段。xhs 支持 sort_type / publish_time /
+                content_type / filter_note_range;YouTube / X 当前无额外参数。
+
+    返回:
+        ToolResult.images 含 1 张带索引编号的封面拼图;output 含列表和每条记录的
+        元数据。拼图遵循 read_images 的自适应布局规则(最多 12 张)。
+    """
+
+
+@tool()
+async def content_detail(
+    platform: str,
+    identifier: str,
+    extras: Optional[Dict[str, Any]] = None,
+) -> ToolResult:
+    """查看内容详情。identifier 的含义因平台而异(见 content_platforms 的 detail_mode)。
+
+    - xhs / gzh / douyin / ...: identifier 是 content_search 返回的索引(1-based),
+      从 session 级缓存取完整记录
+    - youtube: identifier 是 video_id;extras 可传 include_captions / download_video
+    - x: 当前不支持详情查看
+    """
+```
+
+### 内部实现(不注册给 LLM)
+
+```
+agent/tools/builtin/content/
+├── __init__.py           # 空
+├── tools.py              # 3 个 @tool 入口
+├── registry.py           # PLATFORM_IMPLS 路由表
+└── platforms/
+    ├── aigc_channel.py   # 9 个中文平台的 search / detail / suggest 实现
+    ├── youtube.py        # youtube_search / youtube_detail 纯函数
+    └── x.py              # x_search 纯函数
+```
+
+### 迁移步骤
+
+1. 新建 `agent/tools/builtin/content/` 目录结构
+2. 把 `search.py` 的 `search_posts` / `select_post` / `get_search_suggestions` 逻辑移到 `content/platforms/aigc_channel.py`,拆成按 channel 分的纯函数
+3. 把 `crawler.py` 的 `youtube_search` / `youtube_detail` / `x_search` 移到 `content/platforms/`
+4. 在 `content/tools.py` 写 3 个 @tool 入口,内部调用路由
+5. 从 `builtin/__init__.py` 删除旧的 `search_posts` / `youtube_search` / `x_search` 等导出
+6. 添加新的 `content_platforms` / `content_search` / `content_detail` 导出
+7. 更新现有 prompt 里对旧工具的引用(**破坏性改动**)
+8. `extract_video_clip` 和 `import_content` 不搬——它们不是搜索工具,保留在原位或移到 `content/media.py` / `content/ingestion.py`
+
+### 未决策的设计问题
+
+1. **`extras` 的 schema 怎么处理?**
+   - 方案 i:声明为 `Optional[Dict[str, Any]]`,LLM 从 `content_platforms()` 返回的 schema 文本里学参数——**推荐**
+   - 方案 ii:为每个平台单独生成 schema(discriminated union),本框架 `SchemaGenerator` 当前不支持
+   - 方案 iii:把常用的平台专用参数都显式列在 `content_search` 签名里,用 Optional——签名臃肿,不如方案 i
+
+2. **缓存 `_search_cache` 的生命周期**
+   - 现状:进程内字典,进程重启就丢
+   - 问题:CLI 模式下每次进程都是新的,`content_detail(platform="xhs", identifier=3)` 拿不到缓存
+   - 方案:用磁盘持久化缓存 `/tmp/content_cache_{trace_id}.json`,配合之前给 toolhub/librarian 做的 trace_id 三级回退机制,同 session 内 CLI 调用也能复用
+
+3. **拼图的图片数量是否和 `read_images` 一致(12 张上限)?**
+   - read_images 是"让 LLM 看清",12 是硬上限
+   - 内容搜索是"让 LLM 浏览",可能需要更多(20-30 条也常见)
+   - 建议:区分"详查模式"(layout=detail,≤12)和"概览模式"(layout=overview,≤25,每格更小)
+
+4. **X 的 `content_detail` 怎么处理?**
+   - 当前 `x_search` 没有配对的 detail 工具
+   - 要么 `content_platforms` 里标明 `detail_mode: "not_supported"`,要么后端补一个 X 详情接口
+
+### 新增后的用户流程
+
+```
+Step 0(session 开始时一次): content_platforms() → 所有平台 schemas
+Step 1(每次任务):          content_search(platform, keyword, extras)
+Step 2(需要细看时):        content_detail(platform, id, extras)
+```
+
+---
+
+## 方案二:浏览器工具族 → 语义合并
+
+### 现状
+
+28 个 `@tool`(在 `agent/tools/builtin/browser/baseClass.py`),按任务语义分组:
+
+| 类别 | 数量 | 工具 |
+|---|---|---|
+| 导航 | 4 | `browser_navigate_to_url`、`browser_search_web`、`browser_go_back`、`browser_get_live_url` |
+| 等待 / 人机协同 | 2 | `browser_wait`、`browser_wait_for_user_action` |
+| 元素交互 | 6 | `browser_click_element`、`browser_input_text`、`browser_send_keys`、`browser_upload_file`、`browser_get_dropdown_options`、`browser_select_dropdown_option` |
+| 视口 / 查找 | 2 | `browser_scroll_page`、`browser_find_text` |
+| 内容读取 | 6 | `browser_screenshot`、`browser_get_visual_selector_map`、`browser_get_selector_map`、`browser_get_page_html`、`browser_read_long_content`、`browser_extract_content` |
+| 标签页管理 | 2 | `browser_switch_tab`、`browser_close_tab` |
+| Cookie / 登录 | 3 | `browser_ensure_login_with_cookies`、`browser_export_cookies`、`browser_load_cookies` |
+| 其他 | 3 | `browser_download_direct_url`、`browser_evaluate`、`browser_done` |
+
+### 与 browser-use MCP 的重叠分析
+
+约一半工具和 browser-use 原生 MCP 提供的能力重叠:
+
+| 你们的 @tool | browser-use MCP | 状态 |
+|---|---|---|
+| `browser_navigate_to_url` | `browser_navigate` | 重复 |
+| `browser_click_element` | `browser_click` | 重复 |
+| `browser_input_text` | `browser_type` | 重复 |
+| `browser_scroll_page` | `browser_scroll` | 重复 |
+| `browser_go_back` | `browser_go_back` | 重复 |
+| `browser_switch_tab` / `close_tab` | 同名 | 重复 |
+| `browser_extract_content` | 同名 | 重复 |
+| `browser_get_selector_map` | `browser_get_state` | 部分重复 |
+
+剩余 14 个是自研扩展(cookie 全家桶、upload、send_keys、dropdown、visual_selector_map、read_long_content、find_text、evaluate、download、done、wait_for_user_action、get_live_url、search_web、get_page_html)。
+
+### 新方案:语义合并(方案 A)
+
+采用"按动词合并 + Literal 枚举 action"模式,从 28 个 @tool 压缩到约 11 个。**不引入 MCP Client 基础设施**(那是未来的独立决策)。
+
+**目标签名:**
+
+```python
+@tool()
+async def browser_navigate(
+    target: str,
+    mode: Literal["url", "search", "back"] = "url",
+    engine: str = "bing",
+    new_tab: bool = False,
+) -> ToolResult:
+    """导航工具。
+    - mode="url": target 为 URL,直接访问
+    - mode="search": target 为搜索词,通过 engine 搜索
+    - mode="back": 浏览器后退,target 和 engine 忽略
+    """
+
+
+@tool()
+async def browser_interact(
+    action: Literal["click", "type", "send_keys", "upload", "dropdown_list", "dropdown_select"],
+    index: Optional[int] = None,
+    text: Optional[str] = None,
+    path: Optional[str] = None,
+    keys: Optional[str] = None,
+    clear: bool = True,
+) -> ToolResult:
+    """元素交互:
+    - click: 需要 index
+    - type: 需要 index + text
+    - send_keys: 需要 keys(如 'Enter'、'Ctrl+A'),不依赖 index
+    - upload: 需要 index + path
+    - dropdown_list: 需要 index(列出选项)
+    - dropdown_select: 需要 index + text(按文字选中)
+    """
+
+
+@tool()
+async def browser_screenshot(highlight_elements: bool = False) -> ToolResult:
+    """截图。
+    - highlight_elements=False: 纯截图
+    - highlight_elements=True: 带交互元素编号的标注截图(原 visual_selector_map)
+    """
+
+
+@tool()
+async def browser_elements() -> ToolResult:
+    """获取当前页面的可交互元素列表(文本版,不截图)。用于 LLM 按 index 与元素交互。"""
+
+
+@tool()
+async def browser_read(
+    mode: Literal["html", "find", "long_content", "extract"],
+    query: Optional[str] = None,
+    start_line: int = 0,
+    lines_per_page: int = 100,
+    extract_links: bool = False,
+) -> ToolResult:
+    """页面内容读取:
+    - html: 整页 HTML(大页面慎用)
+    - find: 在页面中查找 query 文本
+    - long_content: 分页读取长内容,配合 start_line / lines_per_page
+    - extract: 用 LLM 根据 query 抽取结构化信息,可选 extract_links
+    """
+
+
+@tool()
+async def browser_scroll(
+    down: bool = True,
+    pages: float = 1.0,
+    into_view_index: Optional[int] = None,
+) -> ToolResult:
+    """滚动页面。down=True 向下,pages 是滚动的页面数;
+    传 into_view_index 则滚动到指定元素可见(忽略 down 和 pages)。
+    """
+
+
+@tool()
+async def browser_tabs(
+    action: Literal["switch", "close", "list"],
+    tab_id: Optional[str] = None,
+) -> ToolResult:
+    """标签页管理。list 不需要 tab_id,switch 和 close 需要。"""
+
+
+@tool()
+async def browser_cookies(
+    action: Literal["load", "export", "ensure_login"],
+    name: str = "",
+    account: str = "",
+    url: str = "",
+    cookie_type: str = "",
+    auto_navigate: bool = True,
+) -> ToolResult:
+    """Cookie 管理:
+    - load: 加载已保存的 cookie(url + name, auto_navigate 控制是否自动导航)
+    - export: 导出当前 cookie 保存(name + account 标识)
+    - ensure_login: 检查登录状态,未登录时自动加载 cookie_type 对应的 cookie
+    """
+
+
+@tool()
+async def browser_wait(
+    seconds: Optional[int] = None,
+    user_action_message: Optional[str] = None,
+) -> ToolResult:
+    """等待:
+    - 传 seconds: 纯等待指定秒数
+    - 传 user_action_message: 暂停并提示用户在浏览器里手动操作,用户完成后 Agent 继续
+    - 两者都不传: 报错
+    """
+
+
+@tool()
+async def browser_evaluate(code: str) -> ToolResult:
+    """在当前页面上下文执行 JavaScript。"""
+
+
+@tool()
+async def browser_download(url: str, save_name: str = "") -> ToolResult:
+    """直接下载给定 URL 的文件到本地。"""
+```
+
+**可选保留(视使用频率决定):**
+
+- `browser_get_live_url()` — 远程浏览器场景专用,可能删除
+- `browser_done(text, success)` — 任务完成信号,可能删除(让 agent 用普通 completion 输出)
+
+**28 → 约 11 个 @tool,下降 60%。**
+
+### 条件必填参数的处理
+
+Python 函数签名里所有参数都声明为 Optional,但某些组合是运行时强制的:
+
+```python
+async def browser_interact(action, index, text, path, keys, clear):
+    if action == "click" and index is None:
+        return ToolResult(error="click action requires index")
+    if action == "type" and (index is None or text is None):
+        return ToolResult(error="type action requires both index and text")
+    ...
+```
+
+静态 schema 表达不了这个,只能靠 docstring 说清楚 + 运行时 validate。
+
+### 迁移步骤
+
+1. 在 `baseClass.py` 里先保留所有现有的非 @tool 内部辅助函数(它们负责实际调用 browser-use)
+2. 把 30 个原 `@tool` 函数**去掉 @tool 装饰器**,降级为内部函数 `_navigate_to_url` / `_click_element` 等
+3. 在 `baseClass.py` 底部新增 11 个 @tool 入口函数,每个内部根据 action 路由到对应的内部函数
+4. 从 `browser/__init__.py` 更新导出列表
+5. 更新 `agent/docs/tools.md` 的浏览器工具小节
+6. 更新现有的浏览器 prompt(破坏性)
+
+### 未决策的设计问题
+
+1. **`browser_read` 的 4 个 mode 是否要再拆分?** `extract` 是 LLM 驱动的,和其他 3 个差异较大。可以拆成 `browser_read(mode="html|find|long")` + `browser_extract(query, ...)`。
+2. **`browser_interact` 的 6 个 action 都合并合适吗?** `dropdown_list` 和 `dropdown_select` 与其他 action 的参数差异较大,可以独立出 `browser_dropdown(index, select_text=None)`。
+3. **`browser_done` 的去留** — 这个是给上层 Agent 发任务完成信号的协议约定,不是浏览器操作。建议移到框架通用的 task 信号机制里,或删除。
+4. **`browser_search_web` 要不要作为 mode 合并到 `browser_navigate`?** 搜索引擎的具体实现(`engine: "bing"|"google"|...`)和 URL 导航差异较大,合并后签名变乱。可能独立保留更好。
+5. **重命名的破坏性改动** — 所有 `browser_navigate_to_url` 等现存引用都要更新。需要在 PR 描述里列出 before/after 对照表。
+
+---
+
+## 方案三(暂不采用):引入 MCP Client 基础设施
+
+**思路:** 让本框架的 Agent Runner 作为 MCP Client 连接 browser-use 原生 MCP,**删除**所有与 browser-use MCP 重叠的 @tool,只保留自研扩展(cookie、wait_for_user_action、dropdown 等约 14 个)。
+
+**优点:** 消除代码重复;未来 browser-use 升级自动获益;和 Claude Code 的浏览器体验一致。
+
+**缺点:** 需要给框架的 Agent Runner 新增 MCP Client 基础设施;启动时需要管理 MCP server 进程生命周期;双路共存(部分本地 @tool + 部分远程 MCP)增加复杂度。
+
+**结论:** 当前不做,视未来框架是否引入通用 MCP Client 基础设施再议。方案二(语义合并)的收益已经够大,投入更小。
+
+---
+
+## 共同原则(所有工具族改造都要遵守)
+
+1. **破坏性改动集中做**——所有重命名、删除、合并都在同一个 PR 里完成,不要分期做。分期反而让用户迁移更痛苦
+2. **每个工具族都要有对应的 CLI 入口 + 自包含 `if __name__ == "__main__"`**——参考 toolhub / librarian 已有的模式
+3. **对应的 skill 写到 `~/.claude/skills/`**——让 Claude Code 等外部 Agent 能用
+4. **破坏性改动后同步更新 `agent/docs/tools.md` 和所有现存 prompt**
+
+---
+
+## 待决策清单(落地前必须定)
+
+### 内容工具族
+
+- [ ] `extras` schema 处理方式(推荐方案 i)
+- [ ] 缓存持久化方案(推荐磁盘 + trace_id)
+- [ ] 拼图上限策略(推荐分 detail/overview 两档)
+- [ ] X 是否补 detail 接口(取决于后端支持)
+
+### 浏览器工具族
+
+- [ ] `browser_read` 是否拆成 read + extract 两个
+- [ ] `browser_interact` 是否拆出 dropdown
+- [ ] `browser_done` 去留
+- [ ] `browser_search_web` 是否合并到 navigate
+- [ ] 重命名破坏性改动的迁移策略
+
+### 哲学选择
+
+- [ ] 是否未来引入 MCP Client 基础设施(影响浏览器工具的最终形态)
+
+---
+
+## 不做的事情
+
+- **沙箱工具**:直接删除,不改造(参考 `tools.md` 对应修改记录)
+- **文件工具、bash、skill 等正交单能力工具**:保持现状
+- **knowledge 工具族**:已经是 `ask_knowledge` / `upload_knowledge` 两个入口,规模小且清晰,无改造必要

+ 219 - 1
agent/docs/tools.md

@@ -807,7 +807,8 @@ print(f"Success rate: {stats['success_rate']:.1%}")
 
 | 工具 | 功能 | 参考 |
 |------|------|------|
-| `read_file` | 读取文件内容(支持图片、PDF) | opencode read.ts |
+| `read_file` | 读取单个文件(文本 / 图片 / PDF) | opencode read.ts |
+| `read_images` | 批量读取图片,支持自动降采样和网格拼图 | 自研 |
 | `edit_file` | 智能文件编辑(多种匹配策略) | opencode edit.ts |
 | `write_file` | 写入文件(创建或覆盖) | opencode write.ts |
 | `bash_command` | 执行 shell 命令 | opencode bash.ts |
@@ -815,6 +816,39 @@ print(f"Success rate: {stats['success_rate']:.1%}")
 | `grep_content` | 内容搜索(正则表达式) | opencode grep.ts |
 | `agent` | 创建 Agent 执行任务(单任务 delegate / 多任务并行 explore) | 自研 |
 | `evaluate` | 评估目标执行结果是否满足要求 | 自研 |
+| `toolhub_health` | 检查 ToolHub 远程工具库服务状态 | 自研 |
+| `toolhub_search` | 搜索/发现 ToolHub 远程工具 | 自研 |
+| `toolhub_call` | 调用 ToolHub 远程工具(图片参数支持本地文件路径) | 自研 |
+| `ask_knowledge` | 向知识库查询信息(通过 KnowHub Librarian) | 自研 |
+| `upload_knowledge` | 上传调研结果到知识库 | 自研 |
+
+#### `read_file` vs `read_images`
+
+| 场景 | 工具 |
+|------|------|
+| 读取 **1 张**图片 / 文本 / PDF | `read_file` |
+| 批量读取 **2 张以上**图片 | `read_images` |
+| 需要 AI 对多张图做**对比选择**(选图、挑错、横向比较) | `read_images` 且 `layout="grid"` |
+| 需要对多张图**逐张独立分析** | `read_images` 且 `layout="separate"` |
+
+`read_images` 默认 `layout="grid"` — 多张图拼成一张**带索引编号**的网格图(1,2,3…),**省 token 的同时让 LLM 能在单次注视中做横向对比**。拼图和降采样在内部组合使用:先降采样每张缩略图,再拼成整图,最终图片大小约等于一张普通图的开销,而非所有原图的累积。
+
+**Grid 模式的 16 张硬上限:** grid 模式下单次调用最多 16 张图片。超过会报错,需要分批调用。上限来自于 LLM 内部图片缩放的物理限制——Claude/Qwen-VL 会把图片缩到长边约 1568 像素,当拼图里格子太多时,每格会糊到无法识别。16 张对应 4×4 布局,每格约 300px,缩放后仍能保持约 280px,人物和场景细节仍然可辨。如需处理更多图片,或切换到 `layout="separate"`(无数量限制但每张图都有独立的结构开销 token)。
+
+**自适应布局:** grid 模式下根据图片数量动态选择列数和缩略图尺寸,小批量时每张图更清晰:
+
+| 图片数 | 布局 | 每格大小 |
+|------|------|---------|
+| 2 张 | 2 列 | 500px |
+| 3-4 张 | 2 列 | 450px |
+| 5-6 张 | 3 列 | 400px |
+| 7-9 张 | 3 列 | 380px |
+| 10-12 张 | 4 列 | 320px |
+| 13-16 张 | 4 列 | 300px |
+
+**关于标签/标题:** `read_images` 的拼图**不显示文件名**,只显示索引序号——因为本地文件名(如 `IMG_1234.jpg`)对 LLM 理解内容没有帮助,而索引到原始路径的对照表通过返回文本提供,LLM 可以用"第 3 张"这种引用方式精确指代。对比之下 `search_posts` / `youtube_search` 的拼图**会**显示 label(帖子/视频标题),因为这些是内容型元数据,有实际信息量。这一差异反映在 `build_image_grid(labels=...)` 参数上:传 `None` 只画序号,传列表则在每格下方画标题。
+
+网格和降采样的实现在 `agent/tools/utils/image.py`,`search_posts` 和 `youtube_search` 等工具也复用同一套拼图逻辑。
 
 ### Agent 工具
 
@@ -1205,6 +1239,189 @@ async def search_notes(
 
 ---
 
+## 跨框架使用(CLI / MCP)
+
+工具设计为可跨 Agent 框架使用(本框架 Agent、Claude Code、其他 LLM IDE 等),遵循以下原则:
+
+- **无状态工具** → 自包含 CLI:每个工具文件可独立运行,零外部依赖
+- **有状态工具组**(浏览器、沙箱等需要持久 session) → MCP server:使用标准协议管理 session
+- **禁止中间态**:不造私有协议;简单就 CLI,复杂就 MCP
+
+### 判断标准
+
+| 问题 | 答案 | 选择 |
+|------|------|------|
+| 工具调用之间是否有进程内状态需要保持?(浏览器 session、数据库连接、缓存) | 否 | **CLI** |
+| 同上 | 是 | **MCP** |
+| 是否需要 Claude Desktop、Cursor 等客户端原生识别? | 需要 | **MCP** |
+
+### 无状态 CLI 工具规范
+
+一个工具想同时作为 Agent tool(`@tool` 注册)和 CLI 工具使用,需要满足以下要求:
+
+**1. 文件末尾添加自包含的 `if __name__ == "__main__"` 块**
+
+参数解析、asyncio.run、结果输出这些 CLI 样板代码**直接内联**在工具文件里,不要抽取到共享 `cli.py` 模块——这样每个工具文件可以独立迁移到其他项目。
+
+```python
+# 示例:agent/tools/builtin/toolhub.py 末尾
+if __name__ == "__main__":
+    import sys, asyncio, os, uuid
+
+    COMMANDS = {"health": toolhub_health, "search": toolhub_search, "call": toolhub_call}
+
+    def _parse_args(argv):
+        kwargs = {}
+        for arg in argv:
+            if arg.startswith("--") and "=" in arg:
+                k, v = arg.split("=", 1)
+                k = k.lstrip("-").replace("-", "_")
+                try: v = json.loads(v)
+                except: pass
+                kwargs[k] = v
+        return kwargs
+
+    # trace_id 三级回退:CLI 参数 > 环境变量 > 自动生成
+    cmd = sys.argv[1]
+    kwargs = _parse_args(sys.argv[2:])
+    trace_id = kwargs.pop("trace_id", None) or os.getenv("TRACE_ID") or f"cli-{uuid.uuid4().hex[:8]}"
+    set_trace_context(trace_id)
+
+    result = asyncio.run(COMMANDS[cmd](**kwargs))
+    # 输出 JSON(注意 double-encoding 问题)
+    ...
+```
+
+**2. 输出统一为 JSON 格式**
+
+```json
+{
+  "trace_id": "...",
+  "output": "...",  // 原生 dict/list/str,不要预先 json.dumps
+  "error": "...",   // 可选
+  "metadata": {...}  // 可选
+}
+```
+
+**3. trace_id 三级回退策略**
+
+对于需要会话语义(同一 trace_id 内多次调用共享状态)的工具(librarian、toolhub 的图片输出目录等):
+
+1. **CLI 参数** `--trace_id=xxx`(显式)
+2. **环境变量** `TRACE_ID`(同一 shell session 共享)
+3. **自动生成** `cli-{random}`(兜底)
+
+外部 Agent 只需 `export TRACE_ID=session-xxx` 一次,后续所有 CLI 调用自动归到同一会话。
+
+**4. 二进制产出写文件,JSON 返回路径**
+
+像 `read_images` 这种产出图片/大文件的工具,CLI 模式下**不要**把 base64 塞进 stdout(刷屏 + 调用方还要解码)。应该:
+- 要求用户显式传 `--out=<path>` 指定输出路径
+- 把文件写到 `<path>`
+- JSON 响应里返回 `out_path` 供调用方用 Read 工具查看
+
+**5. 避免双重 JSON 编码**
+
+如果工具内部已经 `json.dumps()` 把 result dict 塞进了 `ToolResult.output`,CLI 层再 `json.dumps(result.output)` 会产生双重转义(`"output": "{\"model\": ..."` 这种反人类形式)。CLI 层要在输出前检测并解码:
+
+```python
+output_value = result.output
+if isinstance(output_value, str):
+    stripped = output_value.lstrip()
+    if stripped.startswith(("{", "[")):
+        try:
+            output_value = json.loads(output_value)
+        except (json.JSONDecodeError, ValueError):
+            pass  # 非 JSON 文本,保持原样
+```
+
+### Skill 安装规范
+
+CLI 工具对外暴露给 Claude Code(或其他支持 skill 的客户端)时,需要配套写一个 `SKILL.md`:
+
+**位置:** `~/.claude/skills/<name>/SKILL.md`(用户全局)或项目级 `.claude/skills/<name>/SKILL.md`
+
+**格式:**
+
+```markdown
+---
+name: <skill-name>
+description: <一句话,描述用途和触发时机。这是 Claude Code 决定何时加载该 skill 的唯一依据>
+---
+
+# <Skill Name>
+
+<简短一段话介绍工具>
+
+## 用法
+
+```bash
+python <绝对路径>/tool.py <子命令> --key=value
+```
+
+- `--key=...` 参数说明
+- 关键约束(如数量上限)
+
+<调用后怎么解读输出,典型 workflow>
+```
+
+**尺寸原则:** SKILL.md **越短越好**。它每次触发时都会进入 context 占据 token。和 `agent/docs/tools.md` 的职责区分:
+
+| 文件 | 读者 | 触发 | 长度 |
+|------|------|------|------|
+| `SKILL.md` | **运行时的 Claude Code**(动态加载) | 每次匹配自动加载到 context | **短**(20 行以内为佳) |
+| `agent/docs/tools.md` | **开发者**(静态阅读) | 从不自动加载 | 长,可以详细展开原理、设计取舍 |
+
+SKILL.md 只写"调用这个工具所需的最小信息集",原理和细节放到 docs。
+
+**当前已安装的 skill**(`~/.claude/skills/`):
+- `toolhub/` — 搜索和调用 ToolHub 远程 AI 工具
+- `knowhub/` — 查询和上传 KnowHub 知识库
+- `stitch-images/` — 批量图片拼成网格供 Read 一次查看
+
+### ToolHub 图片管线
+
+`toolhub_call` 内置完整的图片处理管线,无需单独的上传/下载工具:
+
+- **输入**:`params` 中的图片参数(`image`、`image_url`、`mask_image`、`pose_image`、`images`)可直接传本地文件路径,系统自动上传
+- **输出**:生成的图片自动保存到 `outputs/` 目录,返回结果中 `saved_files` 包含本地路径
+
+### MCP 集成(有状态工具组)
+
+对于需要维持 session 的工具组,使用 MCP server。两种注册方式:
+
+**1. 使用现成的 MCP server**(推荐)
+
+例如浏览器工具直接用 browser-use 原生 MCP:
+
+```json
+// .mcp.json(项目根目录;不要写在 settings.json,Claude Code 不会从那里读 mcpServers)
+{
+  "mcpServers": {
+    "browser-use": {
+      "command": "/Users/sunlit/.pyenv/versions/3.13.1/bin/python",
+      "args": ["-m", "browser_use.skill_cli.main", "--mcp"],
+      "env": {
+        "OPENAI_API_KEY": "sk-...",
+        "OPENAI_BASE_URL": "https://dashscope.aliyuncs.com/compatible-mode/v1",
+        "BROWSER_USE_LLM_MODEL": "qwen-plus"
+      }
+    }
+  }
+}
+```
+
+**注意事项:**
+- `command` 必须用**绝对路径**,不要用 pyenv shim(shim 在 Claude Code 子进程里无法正确解析)
+- MCP server 配置放 `.mcp.json`,**不是** `~/.claude/settings.json`(后者只管 permissions/outputStyle 等)
+- 第三方包的 LLM 配置如果 Pydantic schema 吞字段(比如 browser-use 的 `LLMEntry` 不支持 `base_url`),可以通过**环境变量**绕过(如 `OPENAI_BASE_URL` 是 OpenAI SDK 原生环境变量)
+
+**2. 为自研有状态工具组写 MCP server**
+
+当你有一组需要共享 session 的自研工具时,用 `mcp` Python SDK 写一个 server,每个工具作为 `@app.tool()` 暴露。server 进程内维护 session 状态。避免造私有 stdio 协议。
+
+---
+
 ## 总结
 
 | 特性 | 状态 | 说明 |
@@ -1224,3 +1441,4 @@ async def search_notes(
 3. **类型安全**:充分利用 Python 类型注解
 4. **灵活集成**:支持各种工具库(Browser-Use, MCP 等)
 5. **可观测性**:内建统计和监控能力
+6. **跨框架**:无状态工具自包含 CLI,有状态工具走 MCP 标准协议

+ 9 - 0
agent/llm/gemini.py

@@ -126,9 +126,17 @@ def _convert_messages_to_gemini(messages: List[Dict]) -> tuple[List[Dict], Optio
 
         content = msg.get("content", "")
         tool_calls = msg.get("tool_calls")
+        raw_gemini_parts = msg.get("raw_gemini_parts")
 
         # Assistant 消息 + tool_calls
         if role == "assistant" and tool_calls:
+            if raw_gemini_parts:
+                contents.append({
+                    "role": "model",
+                    "parts": raw_gemini_parts
+                })
+                continue
+
             parts = []
             if content and (isinstance(content, str) and content.strip()):
                 parts.append({"text": content})
@@ -443,6 +451,7 @@ def create_gemini_llm_call(
         return {
             "content": content,
             "tool_calls": tool_calls,
+            "raw_gemini_parts": candidate.get("content", {}).get("parts", []) if candidates else [],
             "prompt_tokens": usage.input_tokens,
             "completion_tokens": usage.output_tokens,
             "reasoning_tokens": usage.reasoning_tokens,

+ 5 - 9
agent/tools/builtin/__init__.py

@@ -8,6 +8,7 @@
 """
 
 from agent.tools.builtin.file.read import read_file
+from agent.tools.builtin.file.read_images import read_images
 from agent.tools.builtin.file.edit import edit_file
 from agent.tools.builtin.file.write import write_file
 from agent.tools.builtin.glob_tool import glob_files
@@ -16,12 +17,11 @@ from agent.tools.builtin.bash import bash_command
 from agent.tools.builtin.skill import skill, list_skills
 from agent.tools.builtin.subagent import agent, evaluate
 from agent.tools.builtin.search import search_posts, get_search_suggestions
-from agent.tools.builtin.sandbox import (sandbox_create_environment, sandbox_run_shell,
-                                         sandbox_rebuild_with_ports,sandbox_destroy_environment)
+# sandbox 工具已废弃(2026-04):原本是给"运行工具"场景准备的,但工具已被抽到 toolhub 单独处理
 from agent.tools.builtin.knowledge import(knowledge_search,knowledge_save,knowledge_list,knowledge_update,knowledge_batch_update,knowledge_slim)
 from agent.tools.builtin.librarian import ask_knowledge, upload_knowledge
 from agent.tools.builtin.context import get_current_context
-from agent.tools.builtin.toolhub import toolhub_health, toolhub_search, toolhub_call, image_uploader, image_downloader
+from agent.tools.builtin.toolhub import toolhub_health, toolhub_search, toolhub_call
 from agent.tools.builtin.resource import resource_list_tools, resource_get_tool
 from agent.tools.builtin.crawler import youtube_search, youtube_detail, x_search, import_content, extract_video_clip
 from agent.trace.goal_tool import goal
@@ -34,6 +34,7 @@ import agent.tools.builtin.im
 __all__ = [
     # 文件操作
     "read_file",
+    "read_images",
     "edit_file",
     "write_file",
     "glob_files",
@@ -57,18 +58,13 @@ __all__ = [
     "search_posts",
     "select_post",
     "get_search_suggestions",
-    "sandbox_create_environment",
-    "sandbox_run_shell",
-    "sandbox_rebuild_with_ports",
-    "sandbox_destroy_environment",
     # 上下文工具
     "get_current_context",
     # ToolHub 远程工具库
     "toolhub_health",
     "toolhub_search",
     "toolhub_call",
-    "image_uploader",
-    "image_downloader",
+    # image_uploader / image_downloader 已内化到 toolhub_call 的图片管线中,不再单独暴露
     # 资源查询
     "resource_list_tools",
     "resource_get_tool",

+ 21 - 119
agent/tools/builtin/crawler.py

@@ -4,11 +4,7 @@
 提供 YouTube、X (Twitter) 和微信/通用链接的搜索和详情查询功能。
 """
 
-import asyncio
-import base64
-import io
 import json
-import math
 import os
 import subprocess
 import tempfile
@@ -16,9 +12,9 @@ from pathlib import Path
 from typing import Optional, List, Dict, Any
 
 import httpx
-from PIL import Image, ImageDraw, ImageFont
 
 from agent.tools import tool, ToolResult
+from agent.tools.utils.image import build_image_grid, encode_base64, load_images
 
 
 # API 配置
@@ -26,47 +22,22 @@ CRAWLER_BASE_URL = "http://crawler.aiddit.com/crawler"
 AIGC_BASE_URL = "http://aigc-channel.aiddit.com/aigc/channel"
 DEFAULT_TIMEOUT = 60.0
 
-# 拼接图配置
-THUMB_WIDTH = 250
-THUMB_HEIGHT = 250
-TEXT_HEIGHT = 80
-GRID_COLS = 5
-PADDING = 12
-BG_COLOR = (255, 255, 255)
-TEXT_COLOR = (30, 30, 30)
-INDEX_COLOR = (220, 60, 60)
-
 # 视频处理相关配置
 VIDEO_DOWNLOAD_DIR = Path(tempfile.gettempdir()) / "youtube_videos"
 VIDEO_DOWNLOAD_DIR.mkdir(exist_ok=True)
 
 
-# ── 辅助函数 ──
-
-def _truncate_text(text: str, max_len: int = 14) -> str:
-    """截断文本,超出部分用省略号"""
-    return text[:max_len] + "..." if len(text) > max_len else text
-
-
-async def _download_image(client: httpx.AsyncClient, url: str) -> Optional[Image.Image]:
-    """下载单张图片,失败返回 None"""
-    try:
-        resp = await client.get(url, timeout=15.0)
-        resp.raise_for_status()
-        return Image.open(io.BytesIO(resp.content)).convert("RGB")
-    except Exception:
-        return None
-
-
 async def _build_video_collage(videos: List[Dict[str, Any]]) -> Optional[str]:
     """
     将视频缩略图+序号+标题拼接成网格图,返回 base64 编码的 PNG。
+    复用 agent.tools.utils.image 中的共享拼图逻辑。
     """
     if not videos:
         return None
 
-    items = []
-    for idx, video in enumerate(videos):
+    urls: List[str] = []
+    titles: List[str] = []
+    for video in videos:
         thumbnail = None
         if "thumbnails" in video and isinstance(video["thumbnails"], list) and video["thumbnails"]:
             thumbnail = video["thumbnails"][0].get("url")
@@ -77,96 +48,27 @@ async def _build_video_collage(videos: List[Dict[str, Any]]) -> Optional[str]:
 
         title = video.get("title", "") or video.get("text", "")
         if thumbnail:
-            items.append({"url": thumbnail, "title": title, "index": idx + 1})
-    if not items:
+            urls.append(thumbnail)
+            titles.append(title)
+
+    if not urls:
         return None
 
-    async with httpx.AsyncClient() as client:
-        tasks = [_download_image(client, item["url"]) for item in items]
-        downloaded = await asyncio.gather(*tasks)
+    loaded = await load_images(urls)
+
+    valid_images = []
+    valid_labels = []
+    for (_, img), title in zip(loaded, titles):
+        if img is not None:
+            valid_images.append(img)
+            valid_labels.append(title)
 
-    valid = [(item, img) for item, img in zip(items, downloaded) if img is not None]
-    if not valid:
+    if not valid_images:
         return None
 
-    cols = min(GRID_COLS, len(valid))
-    rows = math.ceil(len(valid) / cols)
-    cell_w = THUMB_WIDTH + PADDING
-    cell_h = THUMB_HEIGHT + TEXT_HEIGHT + PADDING
-    canvas_w = cols * cell_w + PADDING
-    canvas_h = rows * cell_h + PADDING
-
-    canvas = Image.new("RGB", (canvas_w, canvas_h), BG_COLOR)
-    draw = ImageDraw.Draw(canvas)
-
-    font_title = None
-    font_index = None
-    font_candidates = [
-        "msyh.ttc", "simhei.ttf", "simsun.ttc",
-        "/System/Library/Fonts/PingFang.ttc",
-        "/usr/share/fonts/truetype/droid/DroidSansFallbackFull.ttf",
-        "/usr/share/fonts/truetype/wqy/wqy-microhei.ttc",
-        "/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc",
-    ]
-    for font_path in font_candidates:
-        try:
-            font_title = ImageFont.truetype(font_path, 16)
-            font_index = ImageFont.truetype(font_path, 32)
-            break
-        except Exception:
-            continue
-    if not font_title:
-        font_title = ImageFont.load_default()
-        font_index = font_title
-
-    for item, img in valid:
-        idx = item["index"]
-        col = (idx - 1) % cols
-        row = (idx - 1) // cols
-        x = PADDING + col * cell_w
-        y = PADDING + row * cell_h
-
-        scale = min(THUMB_WIDTH / img.width, THUMB_HEIGHT / img.height)
-        new_w = int(img.width * scale)
-        new_h = int(img.height * scale)
-        thumb = img.resize((new_w, new_h), Image.LANCZOS)
-        offset_x = x + (THUMB_WIDTH - new_w) // 2
-        offset_y = y + (THUMB_HEIGHT - new_h) // 2
-        canvas.paste(thumb, (offset_x, offset_y))
-
-        index_text = str(idx)
-        idx_x = offset_x
-        idx_y = offset_y + 4
-        box_size = 52
-        draw.rectangle([idx_x, idx_y, idx_x + box_size, idx_y + box_size], fill=INDEX_COLOR)
-        bbox = draw.textbbox((0, 0), index_text, font=font_index)
-        tw, th = bbox[2] - bbox[0], bbox[3] - bbox[1]
-        text_x = idx_x + (box_size - tw) // 2
-        text_y = idx_y + (box_size - th) // 2
-        draw.text((text_x, text_y), index_text, fill=(255, 255, 255), font=font_index)
-
-        title = item["title"] or ""
-        if title:
-            words = list(title)
-            lines = []
-            current_line = ""
-            for ch in words:
-                test_line = current_line + ch
-                bbox_line = draw.textbbox((0, 0), test_line, font=font_title)
-                if bbox_line[2] - bbox_line[0] > THUMB_WIDTH:
-                    if current_line:
-                        lines.append(current_line)
-                    current_line = ch
-                else:
-                    current_line = test_line
-            if current_line:
-                lines.append(current_line)
-            for line_i, line in enumerate(lines):
-                draw.text((x, y + THUMB_HEIGHT + 6 + line_i * 22), line, fill=TEXT_COLOR, font=font_title)
-
-    buf = io.BytesIO()
-    canvas.save(buf, format="PNG")
-    return base64.b64encode(buf.getvalue()).decode("utf-8")
+    grid = build_image_grid(images=valid_images, labels=valid_labels)
+    b64, _ = encode_base64(grid, format="PNG")
+    return b64
 
 
 def _parse_srt_to_outline(srt_content: str) -> List[Dict[str, str]]:

+ 0 - 5
agent/tools/builtin/feishu/chat_history/chat_summary.json

@@ -1,5 +0,0 @@
-{
-  "关涛": 0,
-  "谭景玉": 0,
-  "孙若天": 0
-}

تفاوت فایلی نمایش داده نمی شود زیرا این فایل بسیار بزرگ است
+ 0 - 103
agent/tools/builtin/feishu/chat_history/chat_关涛.json


+ 0 - 32
agent/tools/builtin/feishu/chat_history/chat_孙若天.json

@@ -1,32 +0,0 @@
-[
-  {
-    "role": "assistant",
-    "message_id": "om_x100b55ddfb31b898c3a9ee232316f13",
-    "content": [
-      {
-        "type": "text",
-        "text": "你好,我需要访问小红书,但是需要登录。请帮我在这个浏览器中完成登录:\n\nhttps://live.browser-use.com?wss=https%3A//9dcf552b-18ea-4f7f-9ace-96ca6fc9a3ac.cdp3.browser-use.com\n\n登录完成后请回复我一下,谢谢!"
-      }
-    ]
-  },
-  {
-    "role": "assistant",
-    "message_id": "om_x100b538c2d07ec98c3b100a5fec966c",
-    "content": [
-      {
-        "type": "text",
-        "text": "论文文献下载需要协助\n\n已完成论文 `/Users/sunlit/Papers/NoteHook/UIST/main.tex` 的引用文献提取,共 46 篇参考文献。\n\n下载状态:\n✅ 成功下载:4 篇(开放获取文献)\n🔒 需要登录/付费:32 篇(ACM/IEEE/Science 等)\n❌ 下载失败:4 篇\n📋 无 DOI/URL:6 篇\n\n大部分文献(32 篇)需要机构登录才能下载,主要来自:\n- ACM Digital Library (22 篇)\n- Science (1 篇)\n- APA/PsycINFO (2 篇)\n- Emerald (2 篇)\n- 其他出版商 (5 篇)\n\n详细报告已生成:\n`/Users/sunlit/Papers/NoteHook/UIST/references_downloaded/download_report.md`\n\n请问您是否有清华大学图书馆的代理访问权限?或者需要我帮您配置浏览器登录 ACM/IEEE 等数据库来下载这些文献?"
-      }
-    ]
-  },
-  {
-    "role": "assistant",
-    "message_id": "om_x100b538ce47170b8c32938bff5524df",
-    "content": [
-      {
-        "type": "text",
-        "text": "论文下载进度更新\n\n✅ 已成功下载 **34 篇** 论文(74% 成功率)\n\n已完成下载:\n- ACM Digital Library: 26 篇 (100%)\n- arXiv: 2 篇 (100%)\n- Emerald: 2 篇 (100%)\n- IEEE: 1 篇\n- Springer: 1 篇\n\n🔒 还需要登录以下出版商下载剩余 9 篇:\n1. Science (science.org) - 1 篇\n2. APA/PsycINFO (psycnet.apa.org) - 2 篇\n3. ScienceDirect (sciencedirect.com) - 2 篇\n4. Wiley (onlinelibrary.wiley.com) - 1 篇\n5. Now Publishers (nowpublishers.com) - 1 篇\n\n📋 无 DOI/URL 需要手动查找:6 篇\n\n所有文件已保存到:\n/Users/sunlit/Papers/NoteHook/UIST/references_downloaded/\n\n详细报告:download_final_report.md\n\n请问您是否要继续登录其他出版商完成剩余论文的下载?我可以依次打开各个出版商的登录页面。"
-      }
-    ]
-  }
-]

+ 0 - 22
agent/tools/builtin/feishu/chat_history/chat_谭景玉.json

@@ -1,22 +0,0 @@
-[
-  {
-    "role": "assistant",
-    "message_id": "om_x100b55dca36b98acc14eba0a6709aa0",
-    "content": [
-      {
-        "type": "text",
-        "text": "你好!我需要登录小红书来完成搜索摄影主题的任务,但是没有找到保存的cookie。\n\n请点击以下链接在浏览器中完成小红书登录:\nhttps://live.browser-use.com?wss=wss%3A//4599a061-1830-4cb0-99fc-fffb5503e99a.cdp1.browser-use.com/devtools/browser/f77323a4-3759-4558-85e0-f4eb3eb04368\n\n登录完成后请告诉我,我会保存登录状态。谢谢!"
-      }
-    ]
-  },
-  {
-    "role": "assistant",
-    "message_id": "om_x100b5488244594a4c4d3c52f961965f",
-    "content": [
-      {
-        "type": "text",
-        "text": "需要协助登录小红书进行调研。\n\n请打开云浏览器链接完成小红书登录:\n(云浏览器链接需要先初始化)\n\n任务:搜索\"AI角色连载\"\"AI虚拟人日常\"\"AI短剧连载\"相关内容,找出持续更新同一角色故事的账号\n\n请登录后回复确认,我将保存cookie继续调研。"
-      }
-    ]
-  }
-]

+ 5 - 2
agent/tools/builtin/file/read.py

@@ -27,7 +27,7 @@ MAX_LINE_LENGTH = 2000
 MAX_BYTES = 50 * 1024  # 50KB
 
 
-@tool(description="读取文件内容,支持文本文件、图片、PDF 等多种格式,也支持 HTTP/HTTPS URL", hidden_params=["context"])
+@tool(description="读取单个文件内容,支持文本文件、图片、PDF 等多种格式,也支持 HTTP/HTTPS URL", hidden_params=["context"])
 async def read_file(
     file_path: str,
     offset: int = 0,
@@ -35,7 +35,10 @@ async def read_file(
     context: Optional[ToolContext] = None
 ) -> ToolResult:
     """
-    读取文件内容
+    读取单个文件内容
+
+    用于读取一个文本文件、PDF 或一张图片。如需批量读取多张图片(2 张以上)
+    并做对比/选图,请使用 read_images 工具,它支持自动降采样和网格拼图。
 
     参考 OpenCode 实现
 

+ 320 - 0
agent/tools/builtin/file/read_images.py

@@ -0,0 +1,320 @@
+"""
+Read Images Tool - 批量读取图片工具
+
+为"批量读取 + 多图分析"场景设计的工具,与单文件的 read_file 分工:
+- read_file: 单个文件(文本 / PDF / 单张图片)
+- read_images: 2 张以上图片,支持网格拼图和降采样
+
+核心能力:
+1. 并发批量加载本地路径或 URL
+2. 自动降采样,防止 token 爆炸
+3. 可选拼图(grid 模式),把 N 张图合成一张带索引编号的网格图,
+   适合 LLM 横向对比、选图、批量判断场景
+4. 自适应布局 + 硬上限,保证拼图即使经过 LLM 内部缩放也能保持可辨
+"""
+
+from typing import Any, Dict, List, Literal, Optional, Tuple
+
+from agent.tools import tool, ToolResult, ToolContext
+from agent.tools.utils.image import (
+    build_image_grid,
+    downscale,
+    encode_base64,
+    load_images,
+)
+
+
+# Grid 模式的硬上限:超过此数量必须分批调用
+# 理由:12 张可排成 4x3 网格,每格 ~320px,人物/场景细节清晰可辨。
+# 再多格子就太小,分辨不出内容,失去对比价值。
+MAX_GRID_IMAGES = 12
+
+
+def _adaptive_layout(count: int) -> Tuple[int, int]:
+    """根据图片数量自动选择 (columns, thumb_size)。
+
+    目标:拼图最终边长不超过 ~1400px,同时每格缩略图保持 >= 320px 以保证可辨认。
+
+    Returns:
+        (columns, thumb_size)
+    """
+    if count <= 2:
+        return 2, 500   # 2x1
+    if count <= 4:
+        return 2, 450   # 2x2
+    if count <= 6:
+        return 3, 400   # 3x2
+    if count <= 9:
+        return 3, 380   # 3x3
+    # 10-12
+    return 4, 320       # 4x3
+
+
+@tool(
+    description="批量读取多张图片,支持自动降采样和网格拼图(用于横向对比/选图场景)",
+    hidden_params=["context"],
+    display={
+        "zh": {
+            "name": "批量读取图片",
+            "params": {
+                "paths": "图片路径列表",
+                "layout": "布局模式",
+                "max_dimension": "每张图最大边长",
+            },
+        },
+        "en": {
+            "name": "Read Images",
+            "params": {
+                "paths": "Image paths",
+                "layout": "Layout mode",
+                "max_dimension": "Max dimension per image",
+            },
+        },
+    },
+)
+async def read_images(
+    paths: List[str],
+    layout: Literal["grid", "separate"] = "grid",
+    max_dimension: int = 1024,
+    context: Optional[ToolContext] = None,
+) -> ToolResult:
+    """批量读取图片并返回给 LLM,支持自动降采样和网格拼图
+
+    为 **2 张以上** 的图片批量分析场景设计。单张图片请用 `read_file`。
+
+    ⚠️ **grid 模式最多 12 张**。超过请分批调用:第一次传前 12 张,第二次传后续,
+    以此类推。再多每格就太小,分辨不出内容。
+
+    两种布局模式:
+
+    - **grid**(默认):把所有图片拼成一张只带索引编号的网格图(1,2,3…)。
+      LLM 只看到 1 张拼图,大幅减少结构开销 token。索引对应的原始路径见
+      返回文本的对照表,LLM 可以用"第 3 张"来引用具体图片。
+      **自适应布局**:根据图片数量自动选择列数和缩略图尺寸,小批量时每张图更清晰:
+        * 1-2 张:2 列 × 500px
+        * 3-4 张:2 列 × 450px
+        * 5-6 张:3 列 × 400px
+        * 7-9 张:3 列 × 380px
+        * 10-12 张:4 列 × 320px
+      适合:从多张候选图中挑选、横向对比质量/风格、批量判断。
+
+    - **separate**:把每张图独立返回(仍然降采样)。无数量限制,但每张图都有
+      独立的结构开销 token。适合:
+        * 需要逐张做独立的精细分析
+        * 每张图之间没有对比关系
+
+    自动降采样:无论哪种模式,每张图都会先降采样到 max_dimension(默认 1024px)
+    的最大边长,防止高分辨率图片炸掉 token 预算。
+
+    Args:
+        paths: 图片路径列表,支持本地路径和 HTTP(S) URL,可混用。
+               grid 模式下不超过 12 张,超过必须分批调用。
+        layout: 布局模式,"grid" 拼图(默认)/ "separate" 多张独立
+        max_dimension: 每张图的最大边长(等比降采样到不超过此值),默认 1024
+        context: 工具上下文(框架注入,无需手动传)
+
+    Returns:
+        ToolResult:images 字段包含图片数据(grid 模式 1 张拼图,separate 模式 N 张),
+        output 字段包含每张图的索引和来源路径对照表
+    """
+    if not paths:
+        return ToolResult(
+            title="批量读图失败",
+            output="",
+            error="paths 不能为空",
+        )
+
+    # 硬上限检查(仅对 grid 模式)
+    if layout == "grid" and len(paths) > MAX_GRID_IMAGES:
+        return ToolResult(
+            title="批量读图失败",
+            output="",
+            error=(
+                f"grid 模式最多支持 {MAX_GRID_IMAGES} 张图片,当前传入 {len(paths)} 张。"
+                f"请分批调用:每次最多 {MAX_GRID_IMAGES} 张。"
+                f"或者使用 layout='separate' 模式(无数量限制但 token 开销更高)。"
+            ),
+        )
+
+    if len(paths) == 1:
+        hint = "(只有 1 张图片,建议用 read_file 更合适)"
+    else:
+        hint = ""
+
+    # 1. 并发加载所有图片
+    loaded = await load_images(paths)
+
+    # 2. 分离成功和失败
+    successes: List[tuple] = []  # [(path, PIL.Image), ...]
+    failures: List[str] = []     # [path, ...]
+    for source, img in loaded:
+        if img is None:
+            failures.append(source)
+        else:
+            successes.append((source, img))
+
+    if not successes:
+        return ToolResult(
+            title="批量读图失败",
+            output="",
+            error=f"所有 {len(paths)} 张图片均加载失败",
+            metadata={"failed": failures},
+        )
+
+    # 3. 每张图降采样
+    processed = [(src, downscale(img, max_dimension)) for src, img in successes]
+
+    # 4. 构建索引 → 路径对照表(用完整路径,方便 LLM 后续引用或调用)
+    index_lines = [f"{i}. {src}" for i, (src, _) in enumerate(processed, start=1)]
+    summary_parts = [f"共加载 {len(processed)}/{len(paths)} 张图片"]
+    if hint:
+        summary_parts.append(hint)
+    if failures:
+        summary_parts.append(f",失败 {len(failures)} 张")
+    summary = "".join(summary_parts)
+
+    output_lines = [summary, ""] + index_lines
+    if failures:
+        output_lines.append("")
+        output_lines.append("加载失败的路径:")
+        output_lines.extend(f"  - {p}" for p in failures)
+    output_text = "\n".join(output_lines)
+
+    # 5. 根据 layout 生成 images 字段
+    images_for_llm = []
+    if layout == "grid":
+        cols, thumb_size = _adaptive_layout(len(processed))
+        # 网格只显示序号,不写文件名 —— 索引对应的路径见上方 output 文本
+        grid = build_image_grid(
+            images=[img for _, img in processed],
+            labels=None,
+            columns=cols,
+            thumb_size=thumb_size,
+        )
+        # 网格拼图固定用 JPEG 节省 token
+        b64, media_type = encode_base64(grid, format="JPEG", quality=80)
+        images_for_llm.append({
+            "type": "base64",
+            "media_type": media_type,
+            "data": b64,
+        })
+    else:  # separate
+        for _, img in processed:
+            b64, media_type = encode_base64(img, format="JPEG", quality=80)
+            images_for_llm.append({
+                "type": "base64",
+                "media_type": media_type,
+                "data": b64,
+            })
+
+    return ToolResult(
+        title=f"批量读图成功({layout} 模式,{len(processed)} 张)",
+        output=output_text,
+        long_term_memory=f"Read {len(processed)} images via {layout} layout",
+        images=images_for_llm,
+        metadata={
+            "count": len(processed),
+            "failed_count": len(failures),
+            "layout": layout,
+        },
+    )
+
+
+# ── CLI 入口:图片拼图工具 ──
+#
+# 这个 CLI 的语义是**拼图工具**,不是"读图工具"——Claude Code 这样的调用方
+# 本身就能读单张图(用 Read 工具),真正稀缺的能力是把 N 张图合成一张
+# 带索引编号的网格图,让一次 Read 就能横向对比多张。
+#
+# 因此 CLI 只支持 grid 模式;如果你需要单张图,直接用 Read 工具即可。
+#
+# 用法:
+#   python agent/tools/builtin/file/read_images.py --out=<path> <img1> <img2> ...
+#
+# 必填参数:
+#   --out=/path/grid.jpg     拼图保存路径(必须显式指定,避免污染 /tmp)
+#
+# 可选参数:
+#   --max_dimension=1024     每张图预先降采样的最大边长(默认 1024)
+#
+# 示例:
+#   python agent/tools/builtin/file/read_images.py \
+#     --out=/tmp/compare.jpg \
+#     ~/Downloads/a.jpg ~/Downloads/b.jpg ~/Downloads/c.jpg
+#
+# 输出:一行 JSON,包含 out_path、index_map(索引→原始路径对照表)、
+# text(文字摘要)。调用方拿到 out_path 后用 Read 工具查看拼图即可。
+
+if __name__ == "__main__":
+    import base64
+    import json
+    import sys
+    from pathlib import Path as _Path
+
+    def _print_usage():
+        print("用法: python read_images.py --out=<path> <img1> <img2> ...")
+        print("     --out=/path/grid.jpg   拼图输出路径(必填)")
+        print("     --max_dimension=1024   每张图最大边长(可选,默认 1024)")
+        print(f"最多 {MAX_GRID_IMAGES} 张图片")
+
+    if len(sys.argv) < 2 or sys.argv[1] in ("-h", "--help"):
+        _print_usage()
+        sys.exit(0)
+
+    # 解析参数
+    cli_paths: List[str] = []
+    cli_out: Optional[str] = None
+    cli_max_dim: int = 1024
+    for arg in sys.argv[1:]:
+        if arg.startswith("--") and "=" in arg:
+            k, v = arg.split("=", 1)
+            k = k.lstrip("-").replace("-", "_")
+            if k == "out":
+                cli_out = v
+            elif k == "max_dimension":
+                cli_max_dim = int(v)
+            else:
+                print(f"警告: 未知参数 {k}", file=sys.stderr)
+        else:
+            cli_paths.append(arg)
+
+    if not cli_paths:
+        print("错误: 至少提供一个图片路径", file=sys.stderr)
+        _print_usage()
+        sys.exit(1)
+
+    if not cli_out:
+        print("错误: 必须显式指定 --out=<path>", file=sys.stderr)
+        _print_usage()
+        sys.exit(1)
+
+    import asyncio
+    result = asyncio.run(read_images(
+        paths=cli_paths,
+        layout="grid",
+        max_dimension=cli_max_dim,
+    ))
+
+    if result.error:
+        print(json.dumps({"error": result.error}, ensure_ascii=False, indent=2))
+        sys.exit(1)
+
+    # 写入拼图文件
+    out_p = _Path(cli_out)
+    out_p.parent.mkdir(parents=True, exist_ok=True)
+    out_p.write_bytes(base64.b64decode(result.images[0]["data"]))
+
+    # 解析索引 → 原始路径对照表
+    index_map: List[Dict[str, Any]] = []
+    for line in result.output.split("\n"):
+        if line and line[0].isdigit() and ". " in line:
+            idx_str, src = line.split(". ", 1)
+            if idx_str.isdigit():
+                index_map.append({"index": int(idx_str), "source": src})
+
+    print(json.dumps({
+        "out_path": str(out_p.resolve()),
+        "count": result.metadata.get("count", 0) if result.metadata else 0,
+        "index_map": index_map,
+        "text": result.output,
+    }, ensure_ascii=False, indent=2))

+ 50 - 0
agent/tools/builtin/librarian.py

@@ -178,3 +178,53 @@ async def upload_knowledge(
             output=f"错误: {str(e)}",
             error=str(e)
         )
+
+
+if __name__ == "__main__":
+    import sys
+    import asyncio
+
+    COMMANDS = {
+        "ask": ask_knowledge,
+        "upload": upload_knowledge,
+    }
+
+    def _parse_args(argv):
+        kwargs = {}
+        for arg in argv:
+            if arg.startswith("--") and "=" in arg:
+                k, v = arg.split("=", 1)
+                k = k.lstrip("-").replace("-", "_")
+                try:
+                    import json as _json
+                    v = _json.loads(v)
+                except (json.JSONDecodeError, ValueError):
+                    pass
+                kwargs[k] = v
+        return kwargs
+
+    if len(sys.argv) < 2 or sys.argv[1] in ("-h", "--help"):
+        print(f"用法: python {sys.argv[0]} <command> [--key=value ...]")
+        print(f"可用命令: {', '.join(COMMANDS.keys())}")
+        print(f"示例: python {sys.argv[0]} ask --query='ControlNet 相关的工具'")
+        sys.exit(0)
+
+    cmd = sys.argv[1]
+    if cmd not in COMMANDS:
+        print(f"未知命令: {cmd},可用: {', '.join(COMMANDS.keys())}")
+        sys.exit(1)
+
+    kwargs = _parse_args(sys.argv[2:])
+
+    # trace_id:CLI 参数 > 环境变量 > 自动生成
+    if "trace_id" not in kwargs:
+        import uuid
+        kwargs["trace_id"] = os.getenv("TRACE_ID", f"cli-{uuid.uuid4().hex[:8]}")
+
+    result = asyncio.run(COMMANDS[cmd](**kwargs))
+    out = {"trace_id": kwargs.get("trace_id", ""), "output": result.output}
+    if result.error:
+        out["error"] = result.error
+    if result.metadata:
+        out["metadata"] = result.metadata
+    print(json.dumps(out, ensure_ascii=False, indent=2))

+ 0 - 418
agent/tools/builtin/sandbox.py

@@ -1,418 +0,0 @@
-"""
-Sandbox Tools (Async)
-通过 HTTP 异步调用沙盒管理服务的客户端库。
-"""
-
-import json
-import httpx
-from typing import Optional, List, Dict, Any
-
-from agent.tools import tool, ToolResult, ToolContext
-
-
-# 服务地址,可根据实际部署情况修改
-# SANDBOX_SERVER_URL = "http://192.168.100.20:9998"
-SANDBOX_SERVER_URL = "http://61.48.133.26:9998"
-
-# 默认超时时间(秒)
-DEFAULT_TIMEOUT = 300.0
-
-
-@tool(
-    hidden_params=["context"],
-    display={
-        "zh": {
-            "name": "创建沙盒环境",
-            "params": {
-                "image": "Docker 镜像",
-                "mem_limit": "内存限制",
-                "nano_cpus": "CPU 限制",
-                "ports": "端口列表",
-                "use_gpu": "启用 GPU",
-                "gpu_count": "GPU 数量"
-            }
-        },
-        "en": {
-            "name": "Create Sandbox",
-            "params": {
-                "image": "Docker image",
-                "mem_limit": "Memory limit",
-                "nano_cpus": "CPU limit",
-                "ports": "Port list",
-                "use_gpu": "Enable GPU",
-                "gpu_count": "GPU count"
-            }
-        }
-    }
-)
-async def sandbox_create_environment(
-    image: str = "agent-sandbox:latest",
-    mem_limit: str = "512m",
-    nano_cpus: int = 500000000,
-    ports: Optional[List[int]] = None,
-    use_gpu: bool = False,
-    gpu_count: int = -1,
-    server_url: str = None,
-    timeout: float = DEFAULT_TIMEOUT,
-    context: Optional[ToolContext] = None,
-) -> ToolResult:
-    """
-    创建一个隔离的 Docker 开发环境。
-
-    Args:
-        image: Docker 镜像名称,默认为 "agent-sandbox:latest"。
-               可以使用其他镜像如 "python:3.12-slim", "node:18-slim" 等。
-        mem_limit: 容器最大内存限制,默认为 "512m"。
-        nano_cpus: 容器最大 CPU 限制(纳秒),默认为 500000000(0.5 CPU)。
-        ports: 需要映射的端口列表,如 [8080, 3000]。
-        use_gpu: 是否启用 GPU 支持,默认为 False。需要宿主机安装 nvidia-container-toolkit。
-        gpu_count: 使用的 GPU 数量,-1 表示使用所有可用 GPU,默认为 -1。
-        server_url: 服务地址,默认使用全局配置 SANDBOX_SERVER_URL。
-        timeout: 请求超时时间(秒),默认 300 秒。
-        context: 工具上下文
-
-    Returns:
-        ToolResult: 包含沙盒创建结果
-    """
-    url = f"{server_url or SANDBOX_SERVER_URL}/api/create_environment"
-    payload = {
-        "image": image,
-        "mem_limit": mem_limit,
-        "nano_cpus": nano_cpus,
-        "use_gpu": use_gpu,
-        "gpu_count": gpu_count
-    }
-    if ports:
-        payload["ports"] = ports
-
-    try:
-        async with httpx.AsyncClient(timeout=timeout) as client:
-            response = await client.post(url, json=payload)
-            response.raise_for_status()
-            data = response.json()
-
-        sandbox_id = data.get("sandbox_id", "")
-        port_mapping = data.get("port_mapping", {})
-        access_urls = data.get("access_urls", [])
-
-        output_parts = [f"沙盒 ID: {sandbox_id}"]
-        if port_mapping:
-            output_parts.append(f"端口映射: {json.dumps(port_mapping)}")
-        if access_urls:
-            output_parts.append(f"访问地址: {', '.join(access_urls)}")
-
-        return ToolResult(
-            title="沙盒环境创建成功",
-            output="\n".join(output_parts),
-            metadata=data
-        )
-    except httpx.HTTPStatusError as e:
-        return ToolResult(
-            title="沙盒创建失败",
-            output=f"HTTP 错误: {e.response.status_code}",
-            error=str(e)
-        )
-    except httpx.RequestError as e:
-        return ToolResult(
-            title="沙盒创建失败",
-            output=f"网络请求失败: {str(e)}",
-            error=str(e)
-        )
-
-
-@tool(
-    hidden_params=["context"],
-    display={
-        "zh": {
-            "name": "执行沙盒命令",
-            "params": {
-                "sandbox_id": "沙盒 ID",
-                "command": "Shell 命令",
-                "is_background": "后台执行",
-                "timeout": "超时时间"
-            }
-        },
-        "en": {
-            "name": "Run Shell in Sandbox",
-            "params": {
-                "sandbox_id": "Sandbox ID",
-                "command": "Shell command",
-                "is_background": "Run in background",
-                "timeout": "Timeout"
-            }
-        }
-    }
-)
-async def sandbox_run_shell(
-    sandbox_id: str,
-    command: str,
-    is_background: bool = False,
-    timeout: int = 120,
-    server_url: str = None,
-    request_timeout: float = DEFAULT_TIMEOUT,
-    context: Optional[ToolContext] = None,
-) -> ToolResult:
-    """
-    在指定的沙盒中执行 Shell 命令。
-
-    Args:
-        sandbox_id: 沙盒 ID,由 create_environment 返回。
-        command: 要执行的 Shell 命令,如 "pip install flask" 或 "python app.py"。
-        is_background: 是否后台执行,默认为 False。
-            - False:前台执行,等待命令完成并返回输出
-            - True:后台执行,适合启动长期运行的服务
-        timeout: 前台命令的超时时间(秒),默认 120 秒。后台命令不受此限制。
-        server_url: 服务地址,默认使用全局配置 SANDBOX_SERVER_URL。
-        request_timeout: HTTP 请求超时时间(秒),默认 300 秒。
-        context: 工具上下文
-
-    Returns:
-        ToolResult: 命令执行结果
-    """
-    url = f"{server_url or SANDBOX_SERVER_URL}/api/run_shell"
-    payload = {
-        "sandbox_id": sandbox_id,
-        "command": command,
-        "is_background": is_background,
-        "timeout": timeout
-    }
-
-    try:
-        async with httpx.AsyncClient(timeout=request_timeout) as client:
-            response = await client.post(url, json=payload)
-            response.raise_for_status()
-            data = response.json()
-
-        if is_background:
-            status = data.get("status", "")
-            message = data.get("message", "")
-            log_file = data.get("log_file", "")
-            output = f"状态: {status}\n消息: {message}"
-            if log_file:
-                output += f"\n日志文件: {log_file}"
-            return ToolResult(
-                title=f"后台命令已启动: {command[:50]}",
-                output=output,
-                metadata=data
-            )
-        else:
-            exit_code = data.get("exit_code", -1)
-            stdout = data.get("stdout", "")
-            stderr = data.get("stderr", "")
-
-            output_parts = []
-            if stdout:
-                output_parts.append(stdout)
-            if stderr:
-                if output_parts:
-                    output_parts.append("\n--- stderr ---")
-                output_parts.append(stderr)
-            if not output_parts:
-                output_parts.append("(命令无输出)")
-
-            success = exit_code == 0
-            title = f"命令: {command[:50]}"
-            if not success:
-                title += f" (exit code: {exit_code})"
-
-            return ToolResult(
-                title=title,
-                output="\n".join(output_parts),
-                metadata=data,
-                error=None if success else f"Command failed with exit code {exit_code}"
-            )
-    except httpx.HTTPStatusError as e:
-        return ToolResult(
-            title="命令执行失败",
-            output=f"HTTP 错误: {e.response.status_code}",
-            error=str(e)
-        )
-    except httpx.RequestError as e:
-        return ToolResult(
-            title="命令执行失败",
-            output=f"网络请求失败: {str(e)}",
-            error=str(e)
-        )
-
-
-@tool(
-    hidden_params=["context"],
-    display={
-        "zh": {
-            "name": "重建沙盒端口",
-            "params": {
-                "sandbox_id": "沙盒 ID",
-                "ports": "端口列表",
-                "mem_limit": "内存限制",
-                "nano_cpus": "CPU 限制",
-                "use_gpu": "启用 GPU",
-                "gpu_count": "GPU 数量"
-            }
-        },
-        "en": {
-            "name": "Rebuild Sandbox Ports",
-            "params": {
-                "sandbox_id": "Sandbox ID",
-                "ports": "Port list",
-                "mem_limit": "Memory limit",
-                "nano_cpus": "CPU limit",
-                "use_gpu": "Enable GPU",
-                "gpu_count": "GPU count"
-            }
-        }
-    }
-)
-async def sandbox_rebuild_with_ports(
-    sandbox_id: str,
-    ports: List[int],
-    mem_limit: str = "1g",
-    nano_cpus: int = 1000000000,
-    use_gpu: bool = False,
-    gpu_count: int = -1,
-    server_url: str = None,
-    timeout: float = DEFAULT_TIMEOUT,
-    context: Optional[ToolContext] = None,
-) -> ToolResult:
-    """
-    重建沙盒并应用新的端口映射。
-
-    使用场景:先创建沙盒克隆项目,阅读 README 后才知道需要暴露哪些端口,
-    此时调用此函数重建沙盒,应用正确的端口映射。
-
-    注意:重建后会返回新的 sandbox_id,后续操作需要使用新 ID。
-    容器内的所有文件(克隆的代码、安装的依赖等)都会保留。
-
-    Args:
-        sandbox_id: 当前沙盒 ID。
-        ports: 需要映射的端口列表,如 [8080, 3306, 6379]。
-        mem_limit: 容器最大内存限制,默认为 "1g"。
-        nano_cpus: 容器最大 CPU 限制(纳秒),默认为 1000000000(1 CPU)。
-        use_gpu: 是否启用 GPU 支持,默认为 False。需要宿主机安装 nvidia-container-toolkit。
-        gpu_count: 使用的 GPU 数量,-1 表示使用所有可用 GPU,默认为 -1。
-        server_url: 服务地址,默认使用全局配置 SANDBOX_SERVER_URL。
-        timeout: 请求超时时间(秒),默认 300 秒。
-        context: 工具上下文
-
-    Returns:
-        ToolResult: 重建结果
-    """
-    url = f"{server_url or SANDBOX_SERVER_URL}/api/rebuild_with_ports"
-    payload = {
-        "sandbox_id": sandbox_id,
-        "ports": ports,
-        "mem_limit": mem_limit,
-        "nano_cpus": nano_cpus,
-        "use_gpu": use_gpu,
-        "gpu_count": gpu_count
-    }
-
-    try:
-        async with httpx.AsyncClient(timeout=timeout) as client:
-            response = await client.post(url, json=payload)
-            response.raise_for_status()
-            data = response.json()
-
-        old_id = data.get("old_sandbox_id", "")
-        new_id = data.get("new_sandbox_id", "")
-        port_mapping = data.get("port_mapping", {})
-        access_urls = data.get("access_urls", [])
-
-        output_parts = [
-            f"旧沙盒 ID: {old_id} (已销毁)",
-            f"新沙盒 ID: {new_id}"
-        ]
-        if port_mapping:
-            output_parts.append(f"端口映射: {json.dumps(port_mapping)}")
-        if access_urls:
-            output_parts.append(f"访问地址: {', '.join(access_urls)}")
-
-        return ToolResult(
-            title="沙盒重建成功",
-            output="\n".join(output_parts),
-            metadata=data
-        )
-    except httpx.HTTPStatusError as e:
-        return ToolResult(
-            title="沙盒重建失败",
-            output=f"HTTP 错误: {e.response.status_code}",
-            error=str(e)
-        )
-    except httpx.RequestError as e:
-        return ToolResult(
-            title="沙盒重建失败",
-            output=f"网络请求失败: {str(e)}",
-            error=str(e)
-        )
-
-
-@tool(
-    requires_confirmation=True,
-    display={
-        "zh": {
-            "name": "销毁沙盒环境",
-            "params": {
-                "sandbox_id": "沙盒 ID"
-            }
-        },
-        "en": {
-            "name": "Destroy Sandbox",
-            "params": {
-                "sandbox_id": "Sandbox ID"
-            }
-        }
-    }
-)
-async def sandbox_destroy_environment(
-    sandbox_id: str,
-    server_url: str = None,
-    timeout: float = DEFAULT_TIMEOUT,
-    context: Optional[ToolContext] = None,
-) -> ToolResult:
-    """
-    销毁沙盒环境,释放资源。
-
-    Args:
-        sandbox_id: 沙盒 ID。
-        server_url: 服务地址,默认使用全局配置 SANDBOX_SERVER_URL。
-        timeout: 请求超时时间(秒),默认 300 秒。
-        context: 工具上下文
-
-    Returns:
-        ToolResult: 销毁结果
-    """
-    url = f"{server_url or SANDBOX_SERVER_URL}/api/destroy_environment"
-    payload = {
-        "sandbox_id": sandbox_id
-    }
-
-    try:
-        async with httpx.AsyncClient(timeout=timeout) as client:
-            response = await client.post(url, json=payload)
-            response.raise_for_status()
-            data = response.json()
-
-        status = data.get("status", "")
-        message = data.get("message", "")
-        removed_tools = data.get("removed_tools", [])
-
-        output_parts = [f"状态: {status}", f"消息: {message}"]
-        if removed_tools:
-            output_parts.append(f"已移除的工具: {', '.join(removed_tools)}")
-
-        return ToolResult(
-            title="沙盒环境已销毁",
-            output="\n".join(output_parts),
-            metadata=data
-        )
-    except httpx.HTTPStatusError as e:
-        return ToolResult(
-            title="沙盒销毁失败",
-            output=f"HTTP 错误: {e.response.status_code}",
-            error=str(e)
-        )
-    except httpx.RequestError as e:
-        return ToolResult(
-            title="沙盒销毁失败",
-            output=f"网络请求失败: {str(e)}",
-            error=str(e)
-        )

+ 24 - 139
agent/tools/builtin/search.py

@@ -9,19 +9,14 @@
 3. get_search_suggestions - 获取平台的搜索补全建议词
 """
 
-import asyncio
-import base64
-import io
 import json
-import math
-import textwrap
 from enum import Enum
 from typing import Any, Dict, List, Optional
 
 import httpx
-from PIL import Image, ImageDraw, ImageFont
 
 from agent.tools import tool, ToolResult
+from agent.tools.utils.image import build_image_grid, encode_base64, load_images
 
 
 # API 基础配置
@@ -31,155 +26,45 @@ DEFAULT_TIMEOUT = 60.0
 # 搜索结果缓存,以序号为 key
 _search_cache: Dict[int, Dict[str, Any]] = {}
 
-# 拼接图配置
-THUMB_WIDTH = 250
-THUMB_HEIGHT = 250
-TEXT_HEIGHT = 80
-GRID_COLS = 5
-PADDING = 12
-BG_COLOR = (255, 255, 255)
-TEXT_COLOR = (30, 30, 30)
-INDEX_COLOR = (220, 60, 60)
-
-
-def _truncate_text(text: str, max_len: int = 14) -> str:
-    """截断文本,超出部分用省略号"""
-    return text[:max_len] + "..." if len(text) > max_len else text
-
-
-async def _download_image(client: httpx.AsyncClient, url: str) -> Optional[Image.Image]:
-    """下载单张图片,失败返回 None"""
-    try:
-        resp = await client.get(url, timeout=15.0)
-        resp.raise_for_status()
-        return Image.open(io.BytesIO(resp.content)).convert("RGB")
-    except Exception:
-        return None
-
 
 async def _build_collage(posts: List[Dict[str, Any]]) -> Optional[str]:
     """
     将帖子封面图+序号+标题拼接成网格图,返回 base64 编码的 PNG。
-    每个格子:序号 + 封面图 + 标题
+    复用 agent.tools.utils.image 中的共享拼图逻辑。
     """
     if not posts:
         return None
 
-    # 收集有封面图的帖子,记录原始序号
-    items = []
-    for idx, post in enumerate(posts):
+    # 收集有封面图的帖子
+    urls: List[str] = []
+    titles: List[str] = []
+    for post in posts:
         imgs = post.get("images", [])
         cover_url = imgs[0] if imgs else None
         if cover_url:
-            items.append({
-                "url": cover_url,
-                "title": post.get("title", "") or "",
-                "index": idx + 1,
-            })
-    if not items:
+            urls.append(cover_url)
+            titles.append(post.get("title", "") or "")
+
+    if not urls:
         return None
 
-    # 并发下载封面图
-    async with httpx.AsyncClient() as client:
-        tasks = [_download_image(client, item["url"]) for item in items]
-        downloaded = await asyncio.gather(*tasks)
+    # 并发加载图片
+    loaded = await load_images(urls)
+
+    # 过滤加载失败的(保持 url 和 title 对齐)
+    valid_images = []
+    valid_labels = []
+    for (_, img), title in zip(loaded, titles):
+        if img is not None:
+            valid_images.append(img)
+            valid_labels.append(title)
 
-    # 过滤下载失败的
-    valid = [(item, img) for item, img in zip(items, downloaded) if img is not None]
-    if not valid:
+    if not valid_images:
         return None
 
-    cols = min(GRID_COLS, len(valid))
-    rows = math.ceil(len(valid) / cols)
-    cell_w = THUMB_WIDTH + PADDING
-    cell_h = THUMB_HEIGHT + TEXT_HEIGHT + PADDING
-    canvas_w = cols * cell_w + PADDING
-    canvas_h = rows * cell_h + PADDING
-
-    canvas = Image.new("RGB", (canvas_w, canvas_h), BG_COLOR)
-    draw = ImageDraw.Draw(canvas)
-
-    # 尝试加载字体(跨平台中文支持)
-    font_title = None
-    font_index = None
-
-    # 按优先级尝试不同平台的中文字体
-    font_candidates = [
-        "msyh.ttc",           # Windows 微软雅黑
-        "simhei.ttf",         # Windows 黑体
-        "simsun.ttc",         # Windows 宋体
-        "/System/Library/Fonts/PingFang.ttc",  # macOS 苹方
-        "/usr/share/fonts/truetype/droid/DroidSansFallbackFull.ttf",  # Linux
-        "/usr/share/fonts/truetype/wqy/wqy-microhei.ttc",  # Linux WenQuanYi
-        "/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc",  # Linux Noto
-    ]
-
-    for font_path in font_candidates:
-        try:
-            font_title = ImageFont.truetype(font_path, 16)
-            font_index = ImageFont.truetype(font_path, 32)
-            break
-        except Exception:
-            continue
-
-    # 如果都失败,使用默认字体(可能不支持中文)
-    if not font_title:
-        font_title = ImageFont.load_default()
-        font_index = font_title
-
-    for item, img in valid:
-        idx = item["index"]
-        col = (idx - 1) % cols
-        row = (idx - 1) // cols
-        x = PADDING + col * cell_w
-        y = PADDING + row * cell_h
-
-        # 等比缩放封面图,保持原始比例,居中放置
-        scale = min(THUMB_WIDTH / img.width, THUMB_HEIGHT / img.height)
-        new_w = int(img.width * scale)
-        new_h = int(img.height * scale)
-        thumb = img.resize((new_w, new_h), Image.LANCZOS)
-        offset_x = x + (THUMB_WIDTH - new_w) // 2
-        offset_y = y + (THUMB_HEIGHT - new_h) // 2
-        canvas.paste(thumb, (offset_x, offset_y))
-
-        # 左上角写序号(带背景),固定大小,跟随图片位置
-        index_text = str(idx)
-        idx_x = offset_x
-        idx_y = offset_y + 4
-        box_size = 52
-        draw.rectangle([idx_x, idx_y, idx_x + box_size, idx_y + box_size], fill=INDEX_COLOR)
-        # 序号居中绘制
-        bbox = draw.textbbox((0, 0), index_text, font=font_index)
-        tw, th = bbox[2] - bbox[0], bbox[3] - bbox[1]
-        text_x = idx_x + (box_size - tw) // 2
-        text_y = idx_y + (box_size - th) // 2
-        draw.text((text_x, text_y), index_text, fill=(255, 255, 255), font=font_index)
-
-        # 写标题(完整显示,按像素宽度自动换行)
-        title = item["title"] or ""
-        if title:
-            words = list(title)  # 逐字符拆分,兼容中英文
-            lines = []
-            current_line = ""
-            for ch in words:
-                test_line = current_line + ch
-                bbox_line = draw.textbbox((0, 0), test_line, font=font_title)
-                if bbox_line[2] - bbox_line[0] > THUMB_WIDTH:
-                    if current_line:
-                        lines.append(current_line)
-                    current_line = ch
-                else:
-                    current_line = test_line
-            if current_line:
-                lines.append(current_line)
-            for line_i, line in enumerate(lines):
-                draw.text((x, y + THUMB_HEIGHT + 6 + line_i * 22), line, fill=TEXT_COLOR, font=font_title)
-
-    # 转 base64
-    buf = io.BytesIO()
-    canvas.save(buf, format="PNG")
-    return base64.b64encode(buf.getvalue()).decode("utf-8")
+    grid = build_image_grid(images=valid_images, labels=valid_labels)
+    b64, _ = encode_base64(grid, format="PNG")
+    return b64
 
 
 class PostSearchChannel(str, Enum):

+ 219 - 111
agent/tools/builtin/toolhub.py

@@ -7,11 +7,20 @@ ToolHub - 远程工具库集成模块
 2. toolhub_search   - 搜索/发现远程工具(GET /tools)
 3. toolhub_call     - 调用远程工具(POST /run_tool)
 
+图片参数统一使用本地文件路径:
+  - 输入:params 中的 image/image_url 等参数直接传本地路径,内部自动上传
+  - 输出:生成的图片自动保存到 outputs/ 目录,返回本地路径
+
 实际 API 端点(通过 /openapi.json 确认):
   GET  /health      → 健康检查
   GET  /tools       → 列出所有工具(含分组、参数 schema)
   POST /run_tool    → 调用工具 {"tool_id": str, "params": dict}
   POST /chat        → 对话接口(不在此封装)
+
+CLI 用法:
+  python -m agent.tools.builtin.toolhub health
+  python -m agent.tools.builtin.toolhub search --keyword=image
+  python -m agent.tools.builtin.toolhub call --tool_id=flux_gen --params='{"prompt":"a cat"}'
 """
 
 import base64
@@ -19,6 +28,7 @@ import contextvars
 import json
 import logging
 import mimetypes
+import os
 import time
 from pathlib import Path
 from typing import Any, Dict, List, Optional
@@ -159,62 +169,77 @@ async def _process_images(raw_images: List[str], tool_id: str) -> tuple:
     return images_for_llm, cdn_urls, saved_paths
 
 
+_SINGLE_IMAGE_PARAMS = ("image", "image_url", "mask_image", "pose_image", "reference_image")
+_ARRAY_IMAGE_PARAMS = ("images", "image_urls", "reference_images")
+
+
+async def _maybe_upload_local(val: str) -> Optional[str]:
+    """如果 val 是存在的本地文件路径,上传 OSS 并返回 CDN URL;否则返回 None。"""
+    if not isinstance(val, str):
+        return None
+    if val.startswith(("http://", "https://", "data:")):
+        return None
+    try:
+        p = Path(val)
+        if p.exists() and p.is_file():
+            return await _upload_to_oss(str(p.resolve()))
+    except Exception as e:
+        logger.warning(f"[ToolHub] 本地路径处理失败 {val}: {e}")
+    return None
+
+
 async def _preprocess_params(params: Dict[str, Any]) -> Dict[str, Any]:
     """
     预处理工具参数:检测本地文件路径,自动上传到 OSS 并替换为 CDN URL。
 
-    支持的参数名:image, image_url, mask_image, pose_image, images (数组)
+    支持的单值参数:image, image_url, mask_image, pose_image, reference_image
+    支持的数组参数:images, image_urls, reference_images
+
+    设计要点:远程工具服务的 cwd 和调用方不一样,相对路径在服务器上会找不到文件。
+    所以必须在客户端就把本地路径转成 CDN URL,不能期望服务器侧有 fallback。
     """
     if not params:
         return params
 
     processed = params.copy()
 
-    # 单个图片参数
-    for key in ("image", "image_url", "mask_image", "pose_image"):
+    # 单图片参数
+    for key in _SINGLE_IMAGE_PARAMS:
         if key in processed and isinstance(processed[key], str):
             val = processed[key]
-            # 检测是否为本地路径(不是 http/https/data: 开头)
-            if not val.startswith(("http://", "https://", "data:")):
-                # 尝试读取本地文件
-                try:
-                    from pathlib import Path
-                    p = Path(val)
-                    if p.exists() and p.is_file():
-                        logger.info(f"[ToolHub] 检测到本地文件 {key}={val},上传到 OSS...")
-                        cdn_url = await _upload_to_oss(str(p.resolve()))
-                        if cdn_url:
-                            processed[key] = cdn_url
-                            logger.info(f"[ToolHub] {key} 已替换为 CDN URL: {cdn_url}")
-                        else:
-                            logger.warning(f"[ToolHub] {key} 上传失败,保持原路径")
-                except Exception as e:
-                    logger.warning(f"[ToolHub] {key} 路径处理失败: {e}")
-
-    # images 数组参数
-    if "images" in processed and isinstance(processed["images"], list):
-        new_images = []
-        for idx, img in enumerate(processed["images"]):
-            if isinstance(img, str) and not img.startswith(("http://", "https://", "data:")):
-                try:
-                    from pathlib import Path
-                    p = Path(img)
-                    if p.exists() and p.is_file():
-                        logger.info(f"[ToolHub] 检测到本地文件 images[{idx}]={img},上传到 OSS...")
-                        cdn_url = await _upload_to_oss(str(p.resolve()))
-                        if cdn_url:
-                            new_images.append(cdn_url)
-                            logger.info(f"[ToolHub] images[{idx}] 已替换为 CDN URL: {cdn_url}")
-                        else:
-                            new_images.append(img)
-                    else:
-                        new_images.append(img)
-                except Exception as e:
-                    logger.warning(f"[ToolHub] images[{idx}] 路径处理失败: {e}")
-                    new_images.append(img)
+            if val.startswith(("http://", "https://", "data:")):
+                continue
+            cdn_url = await _maybe_upload_local(val)
+            if cdn_url:
+                processed[key] = cdn_url
+                logger.info(f"[ToolHub] {key} 本地路径已替换为 CDN: {cdn_url}")
+            elif not os.path.isfile(val):
+                # 既不是远程 URL 也不是已存在的本地文件,直接报错比让远程服务抛神秘的 base64 错误强
+                logger.warning(f"[ToolHub] {key}={val!r} 既不是 URL 也不是存在的本地文件")
+
+    # 数组型图片参数
+    for array_key in _ARRAY_IMAGE_PARAMS:
+        if array_key not in processed or not isinstance(processed[array_key], list):
+            continue
+        new_list = []
+        for idx, item in enumerate(processed[array_key]):
+            if not isinstance(item, str):
+                new_list.append(item)
+                continue
+            if item.startswith(("http://", "https://", "data:")):
+                new_list.append(item)
+                continue
+            cdn_url = await _maybe_upload_local(item)
+            if cdn_url:
+                new_list.append(cdn_url)
+                logger.info(f"[ToolHub] {array_key}[{idx}] 本地路径已替换为 CDN: {cdn_url}")
             else:
-                new_images.append(img)
-        processed["images"] = new_images
+                new_list.append(item)
+                if not os.path.isfile(item):
+                    logger.warning(
+                        f"[ToolHub] {array_key}[{idx}]={item!r} 既不是 URL 也不是存在的本地文件"
+                    )
+        processed[array_key] = new_list
 
     return processed
 
@@ -254,10 +279,11 @@ async def toolhub_health() -> ToolResult:
             error=f"无法连接到 ToolHub 服务 {TOOLHUB_BASE_URL},请确认服务已启动。",
         )
     except Exception as e:
+        err_msg = f"{type(e).__name__}: {e}" if str(e) else type(e).__name__
         return ToolResult(
             title="ToolHub 健康检查",
             output="",
-            error=str(e),
+            error=err_msg,
         )
 
 
@@ -292,16 +318,46 @@ async def toolhub_search(keyword: Optional[str] = None) -> ToolResult:
         tools = data.get("tools", [])
         groups = data.get("groups", [])
 
-        # 客户端关键词过滤
+        # 客户端关键词过滤:三层匹配策略
+        # 1) 原始子串匹配(最严格,但会被分隔符切断:nanobanana vs nano_banana)
+        # 2) 归一化子串匹配(去掉 _ - 空格 .,解决分隔符问题)
+        # 3) 分词交集匹配(keyword 拆成 token,任意 token 命中即保留,解决多词查询)
         if keyword:
-            kw = keyword.lower()
-            tools = [
-                t for t in tools
-                if kw in t.get("name", "").lower()
-                or kw in t.get("description", "").lower()
-                or kw in t.get("tool_id", "").lower()
-                or kw in t.get("category", "").lower()
-            ]
+            def _normalize(s: str) -> str:
+                """去掉分隔符和空白,全小写"""
+                return "".join(c for c in s.lower() if c.isalnum())
+
+            def _tokenize(s: str) -> set:
+                """按分隔符拆成 token 集合"""
+                import re
+                return {t for t in re.split(r"[\s_\-.,/]+", s.lower()) if t}
+
+            kw_raw = keyword.lower()
+            kw_norm = _normalize(keyword)
+            kw_tokens = _tokenize(keyword)
+
+            def _matches(t: dict) -> bool:
+                fields = [
+                    t.get("name", ""),
+                    t.get("description", ""),
+                    t.get("tool_id", ""),
+                    t.get("category", ""),
+                ]
+                combined = " ".join(fields).lower()
+                # 原始子串
+                if kw_raw in combined:
+                    return True
+                # 归一化子串(容忍分隔符差异)
+                if kw_norm and kw_norm in _normalize(combined):
+                    return True
+                # token 交集(多词关键词的 OR 匹配)
+                if kw_tokens:
+                    field_tokens = _tokenize(combined)
+                    if kw_tokens & field_tokens:
+                        return True
+                return False
+
+            tools = [t for t in tools if _matches(t)]
 
         total = len(tools)
 
@@ -337,9 +393,16 @@ async def toolhub_search(keyword: Optional[str] = None) -> ToolResult:
 
             summaries.append(tool_block)
 
-        # 分组使用说明
+        # 分组使用说明:仅显示搜出的工具实际所属的分组,避免噪音
+        relevant_group_ids = set()
+        for t in tools:
+            for gid in t.get("group_ids", []) or []:
+                relevant_group_ids.add(gid)
+
         group_summary = []
         for g in groups:
+            if g["group_id"] not in relevant_group_ids:
+                continue
             group_summary.append(
                 f"[组: {g['group_id']}] {g['name']}\n"
                 f"  调用顺序: {' → '.join(g.get('usage_order', []))}\n"
@@ -360,11 +423,26 @@ async def toolhub_search(keyword: Optional[str] = None) -> ToolResult:
                 + ("..." if total > 15 else "")
             ),
         )
+    except (httpx.ReadTimeout, httpx.ConnectTimeout, httpx.WriteTimeout, httpx.PoolTimeout) as e:
+        return ToolResult(
+            title="ToolHub /tools 超时",
+            output="",
+            error=f"ToolHub 的 /tools 接口在 {DEFAULT_TIMEOUT:.0f}s 内未响应({type(e).__name__})。"
+                  f"服务器可能在检测各工具状态导致列表慢,请稍后重试或联系维护者。",
+        )
+    except httpx.ConnectError as e:
+        return ToolResult(
+            title="ToolHub 连接失败",
+            output="",
+            error=f"无法连接到 ToolHub 服务 {TOOLHUB_BASE_URL}:{type(e).__name__}: {e}",
+        )
     except Exception as e:
+        # 注意 httpx 的部分异常 str(e) 是空的,必须带 type name
+        err_msg = f"{type(e).__name__}: {e}" if str(e) else type(e).__name__
         return ToolResult(
             title="搜索 ToolHub 工具失败",
             output="",
-            error=str(e),
+            error=err_msg,
         )
 
 
@@ -389,20 +467,20 @@ async def toolhub_call(
     通过 tool_id 调用 ToolHub 工具库中的某个工具,传入该工具所需的参数。
     不同工具的参数不同,请先用 toolhub_search 查询目标工具的参数说明。
 
+    图片参数(image、image_url、mask_image、pose_image、images)直接传本地文件路径即可,
+    系统会自动上传。生成的图片会自动保存到本地 outputs/ 目录,返回结果中的
+    saved_files 字段包含本地文件路径。
+
     注意:部分工具为异步生命周期(如 RunComfy、即梦、FLUX),需要按分组顺序
     依次调用多个工具(如先 launch → 再 executor → 再 stop)。
 
-    参数通过 params 字典传入,键名和类型需与工具定义一致。
-    例如调用图片拼接工具:
-        tool_id="image_stitcher"
-        params={"images": [...], "direction": "grid", "columns": 2}
-
     Args:
         tool_id: 要调用的工具 ID(从 toolhub_search 获取)
-        params: 工具参数字典,键值对根据目标工具的参数定义决定
+        params: 工具参数字典,键值对根据目标工具的参数定义决定。
+                图片参数可直接使用本地文件路径(如 "/path/to/image.png")。
 
     Returns:
-        ToolResult 包含工具执行结果
+        ToolResult 包含工具执行结果,图片结果通过 saved_files 返回本地路径
     """
     try:
         # 预处理参数:本地文件路径自动上传成 CDN URL
@@ -443,17 +521,13 @@ async def toolhub_call(
                 if raw_images:
                     images, cdn_urls, saved_paths = await _process_images(raw_images, tool_id)
 
-                    # 构建文本输出(去掉原始图片数据)
+                    # 构建文本输出(去掉原始图片数据,以本地路径为主
                     result_display = {k: v for k, v in result.items() if k not in ("image", "images")}
-                    if cdn_urls:
-                        result_display["cdn_urls"] = cdn_urls
-                        result_display["_note"] = (
-                            "图片已上传至 CDN(永久链接),可通过 cdn_urls 访问、传给其他工具或下载保存。"
-                            "同时也作为附件附加在本条消息中可直接查看。"
-                        )
+                    result_display["image_count"] = len(images)
                     if saved_paths:
                         result_display["saved_files"] = saved_paths
-                    result_display["image_count"] = len(images)
+                    if cdn_urls:
+                        result_display["cdn_urls"] = cdn_urls
                     result_str = json.dumps(result_display, ensure_ascii=False, indent=2)
 
             return ToolResult(
@@ -469,41 +543,29 @@ async def toolhub_call(
                 output=json.dumps(data, ensure_ascii=False, indent=2),
                 error=error_msg,
             )
-    except httpx.TimeoutException:
+    except httpx.TimeoutException as e:
         return ToolResult(
             title=f"ToolHub [{tool_id}] 调用超时",
             output="",
-            error=f"调用工具 {tool_id} 超时({CALL_TIMEOUT:.0f}s),图像生成类工具可能需要更长时间。",
+            error=f"调用工具 {tool_id} 超时({CALL_TIMEOUT:.0f}s,{type(e).__name__}),"
+                  f"图像生成类工具可能需要更长时间。",
         )
     except Exception as e:
+        err_msg = f"{type(e).__name__}: {e}" if str(e) else type(e).__name__
         return ToolResult(
             title=f"ToolHub [{tool_id}] 调用失败",
             output="",
-            error=str(e),
+            error=err_msg,
         )
 
 
-@tool(
-    display={
-        "zh": {"name": "上传本地图片", "params": {"local_path": "本地文件路径"}},
-        "en": {"name": "Upload Local Image", "params": {"local_path": "Local file path"}},
-    }
-)
-async def image_uploader(local_path: str) -> ToolResult:
-    """将本地图片上传到 OSS,返回可用的 CDN URL(image_url)
+# 注意:image_uploader 和 image_downloader 不再注册为 Agent 工具。
+# toolhub_call 已内置完整的图片管线(输入自动上传,输出自动下载保存),
+# 无需单独暴露上传/下载工具。以下函数保留供内部或 CLI 使用。
 
-    当你需要获取一张本地图片的 HTTP 链接时使用此工具。
-    传入本地文件路径,自动上传到 OSS 并返回永久 CDN URL。
 
-    注意:在调用 toolhub_call 时,image/image_url 等参数可以直接传本地路径,
-    系统会自动上传。此工具适用于你需要单独获取图片 URL 的场景。
-
-    Args:
-        local_path: 本地图片文件路径(相对路径或绝对路径均可)
-
-    Returns:
-        ToolResult 包含上传后的 CDN URL
-    """
+async def image_uploader(local_path: str) -> ToolResult:
+    """将本地图片上传到 OSS,返回可用的 CDN URL(内部工具,不注册给 Agent)"""
     import os
     from pathlib import Path
 
@@ -541,26 +603,8 @@ async def image_uploader(local_path: str) -> ToolResult:
         )
 
 
-@tool(
-    display={
-        "zh": {"name": "下载图片到本地", "params": {"url": "图片URL", "save_path": "保存路径"}},
-        "en": {"name": "Download Image", "params": {"url": "Image URL", "save_path": "Save path"}},
-    }
-)
 async def image_downloader(url: str, save_path: str = "") -> ToolResult:
-    """下载网络图片到本地文件
-
-    从 HTTP/HTTPS 链接下载图片并保存到本地。
-    适用于需要将 CDN 图片、生成结果等保存到本地目录的场景。
-
-    Args:
-        url: 图片的 HTTP/HTTPS 链接
-        save_path: 本地保存路径(相对或绝对路径均可)。
-                   如不指定,自动保存到当前输出目录,文件名从 URL 提取。
-
-    Returns:
-        ToolResult 包含下载后的本地文件路径和文件大小
-    """
+    """下载网络图片到本地文件(内部工具,不注册给 Agent)"""
     import os
     from pathlib import Path
     from urllib.parse import urlparse, unquote
@@ -615,3 +659,67 @@ async def image_downloader(url: str, save_path: str = "") -> ToolResult:
             output="",
             error=f"下载失败: {e}",
         )
+
+
+if __name__ == "__main__":
+    import sys
+
+    COMMANDS = {
+        "health": toolhub_health,
+        "search": toolhub_search,
+        "call": toolhub_call,
+    }
+
+    def _parse_args(argv):
+        kwargs = {}
+        for arg in argv:
+            if arg.startswith("--") and "=" in arg:
+                k, v = arg.split("=", 1)
+                k = k.lstrip("-").replace("-", "_")
+                try:
+                    v = json.loads(v)
+                except (json.JSONDecodeError, ValueError):
+                    pass
+                kwargs[k] = v
+        return kwargs
+
+    if len(sys.argv) < 2 or sys.argv[1] in ("-h", "--help"):
+        print(f"用法: python {sys.argv[0]} <command> [--key=value ...]")
+        print(f"可用命令: {', '.join(COMMANDS.keys())}")
+        sys.exit(0)
+
+    cmd = sys.argv[1]
+    if cmd not in COMMANDS:
+        print(f"未知命令: {cmd},可用: {', '.join(COMMANDS.keys())}")
+        sys.exit(1)
+
+    import asyncio
+    import uuid
+    import os
+
+    kwargs = _parse_args(sys.argv[2:])
+
+    # trace_id:CLI 参数 > 环境变量 > 自动生成(用于图片输出目录)
+    trace_id = kwargs.pop("trace_id", None) or os.getenv("TRACE_ID") or f"cli-{uuid.uuid4().hex[:8]}"
+    set_trace_context(trace_id)
+
+    result = asyncio.run(COMMANDS[cmd](**kwargs))
+
+    # 修复双重 JSON 编码:如果 output 已经是一段 JSON 字符串(toolhub_call 内部
+    # 把 result dict 做过 json.dumps),解析回原生 dict 再嵌入 CLI 的最终 JSON,
+    # 避免调用方拿到"output 字段是被字符串化的 JSON"这种反人类形式。
+    output_value = result.output
+    if isinstance(output_value, str):
+        stripped = output_value.lstrip()
+        if stripped.startswith("{") or stripped.startswith("["):
+            try:
+                output_value = json.loads(output_value)
+            except (json.JSONDecodeError, ValueError):
+                pass  # 非 JSON 文本,保持原样
+
+    out = {"trace_id": trace_id, "output": output_value}
+    if result.error:
+        out["error"] = result.error
+    if result.metadata:
+        out["metadata"] = result.metadata
+    print(json.dumps(out, ensure_ascii=False, indent=2))

+ 1 - 0
agent/tools/utils/__init__.py

@@ -0,0 +1 @@
+"""工具辅助模块 - 供多个工具共享的底层逻辑"""

+ 289 - 0
agent/tools/utils/image.py

@@ -0,0 +1,289 @@
+"""
+图片处理共享工具
+
+提供批量读图、降采样、网格拼图等通用逻辑。供 read_images、search_posts、
+youtube_search 等工具共享,避免代码重复。
+
+核心函数:
+- load_image: 从本地路径或 URL 加载为 PIL Image
+- downscale: 等比降采样到指定最大边长
+- build_image_grid: 将多张图片拼成带索引编号 + 标题的网格图
+- encode_base64: PIL Image → base64 字符串(默认 JPEG 以节省 token)
+"""
+
+import asyncio
+import base64
+import io
+import math
+from pathlib import Path
+from typing import List, Optional, Sequence, Tuple
+
+import httpx
+from PIL import Image, ImageDraw, ImageFont
+
+
+# ── 网格拼图默认参数 ──
+DEFAULT_THUMB_SIZE = 250         # 每格缩略图边长
+DEFAULT_TEXT_HEIGHT = 80          # 每格下方文字区高度
+DEFAULT_GRID_COLS = 5             # 每行几格
+DEFAULT_PADDING = 12
+DEFAULT_BG_COLOR = (255, 255, 255)
+DEFAULT_TEXT_COLOR = (30, 30, 30)
+DEFAULT_INDEX_COLOR = (220, 60, 60)
+
+# ── 字体候选(跨平台中文支持) ──
+# 注意:macOS 的 PingFang.ttc 因为格式原因 PIL/FreeType 无法读取,
+# 必须使用 Hiragino 或 STHeiti 等其他中文字体。
+_FONT_CANDIDATES = [
+    # macOS(按优先级)
+    "/System/Library/Fonts/Hiragino Sans GB.ttc",   # 冬青黑体,macOS 自带
+    "/System/Library/Fonts/STHeiti Medium.ttc",     # 华文黑体
+    "/System/Library/Fonts/Supplemental/Arial Unicode.ttf",
+    # Linux
+    "/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc",
+    "/usr/share/fonts/truetype/wqy/wqy-microhei.ttc",
+    "/usr/share/fonts/truetype/droid/DroidSansFallbackFull.ttf",
+    # Windows
+    "msyh.ttc",           # 微软雅黑
+    "simhei.ttf",         # 黑体
+    "simsun.ttc",         # 宋体
+]
+
+
+def _load_fonts(title_size: int = 16, index_size: int = 32):
+    """加载中文字体,全部失败则退回默认字体"""
+    for path in _FONT_CANDIDATES:
+        try:
+            return (
+                ImageFont.truetype(path, title_size),
+                ImageFont.truetype(path, index_size),
+            )
+        except Exception:
+            continue
+    default = ImageFont.load_default()
+    return default, default
+
+
+# ── 加载图片 ──
+
+async def _load_image_from_url(client: httpx.AsyncClient, url: str) -> Optional[Image.Image]:
+    """下载单张图片,失败返回 None"""
+    try:
+        resp = await client.get(url, timeout=15.0)
+        resp.raise_for_status()
+        return Image.open(io.BytesIO(resp.content)).convert("RGB")
+    except Exception:
+        return None
+
+
+def _load_image_from_path(path: str) -> Optional[Image.Image]:
+    """从本地路径加载图片,失败返回 None"""
+    try:
+        return Image.open(path).convert("RGB")
+    except Exception:
+        return None
+
+
+async def load_image(source: str, client: Optional[httpx.AsyncClient] = None) -> Optional[Image.Image]:
+    """
+    通用图片加载:自动识别 URL 或本地路径。
+
+    Args:
+        source: HTTP(S) URL 或本地文件路径
+        client: 可选的 httpx 客户端(URL 加载时复用连接)
+
+    Returns:
+        PIL Image 对象(RGB 模式),失败返回 None
+    """
+    if source.startswith(("http://", "https://")):
+        if client is not None:
+            return await _load_image_from_url(client, source)
+        async with httpx.AsyncClient() as c:
+            return await _load_image_from_url(c, source)
+    else:
+        # 本地路径:在 executor 中执行以避免阻塞事件循环
+        loop = asyncio.get_event_loop()
+        return await loop.run_in_executor(None, _load_image_from_path, source)
+
+
+async def load_images(sources: Sequence[str]) -> List[Tuple[str, Optional[Image.Image]]]:
+    """
+    并发批量加载图片。
+
+    Returns:
+        [(source, image_or_none), ...] — 保留原始顺序,失败项值为 None
+    """
+    async with httpx.AsyncClient() as client:
+        tasks = [load_image(src, client) for src in sources]
+        images = await asyncio.gather(*tasks)
+    return list(zip(sources, images))
+
+
+# ── 降采样 ──
+
+def downscale(image: Image.Image, max_dimension: int) -> Image.Image:
+    """
+    等比降采样到最大边不超过 max_dimension。
+    如果图片已经足够小则原样返回。
+    """
+    if max(image.width, image.height) <= max_dimension:
+        return image
+    scale = max_dimension / max(image.width, image.height)
+    new_size = (int(image.width * scale), int(image.height * scale))
+    return image.resize(new_size, Image.LANCZOS)
+
+
+# ── 网格拼图 ──
+
+def build_image_grid(
+    images: Sequence[Image.Image],
+    labels: Optional[Sequence[str]] = None,
+    columns: int = DEFAULT_GRID_COLS,
+    thumb_size: int = DEFAULT_THUMB_SIZE,
+    text_height: int = DEFAULT_TEXT_HEIGHT,
+    padding: int = DEFAULT_PADDING,
+    show_index: bool = True,
+) -> Image.Image:
+    """
+    将多张图片拼成带索引编号 + 标题的网格图。
+
+    每个单元格包含:
+      - 左上角红底白字的序号(1, 2, 3...)
+      - 等比缩放居中的缩略图
+      - 下方的标题文字(可选,自动按像素宽度换行)
+
+    Args:
+        images: 待拼接的 PIL Image 列表
+        labels: 每张图的标题(与 images 等长);None 则不显示标题
+        columns: 每行几格
+        thumb_size: 每个缩略图格子的边长
+        text_height: 每格下方文字区高度(labels 为 None 时自动置 0)
+        padding: 格子间距和画布边距
+        show_index: 是否显示左上角序号
+
+    Returns:
+        拼接后的 PIL Image
+    """
+    if not images:
+        raise ValueError("images 不能为空")
+
+    if labels is None:
+        labels = [""] * len(images)
+        text_height = 0
+    elif len(labels) != len(images):
+        raise ValueError(f"labels 长度 {len(labels)} 与 images {len(images)} 不匹配")
+
+    count = len(images)
+    cols = min(columns, count)
+    rows = math.ceil(count / cols)
+
+    cell_w = thumb_size + padding
+    cell_h = thumb_size + text_height + padding
+    canvas_w = cols * cell_w + padding
+    canvas_h = rows * cell_h + padding
+
+    canvas = Image.new("RGB", (canvas_w, canvas_h), DEFAULT_BG_COLOR)
+    draw = ImageDraw.Draw(canvas)
+
+    # 索引框按 thumb_size 比例缩放,保证视觉比例恒定(约 20% 占比)
+    index_box_size = max(40, thumb_size // 5)
+    index_font_size = int(index_box_size * 0.65)
+    # 标题字体略与 thumb_size 相关,但下限保证小图时可读
+    title_font_size = max(14, thumb_size // 18)
+    font_title, font_index = _load_fonts(
+        title_size=title_font_size,
+        index_size=index_font_size,
+    )
+
+    for idx, (img, label) in enumerate(zip(images, labels), start=1):
+        col = (idx - 1) % cols
+        row = (idx - 1) // cols
+        x = padding + col * cell_w
+        y = padding + row * cell_h
+
+        # 等比缩放居中
+        scale = min(thumb_size / img.width, thumb_size / img.height)
+        new_w = int(img.width * scale)
+        new_h = int(img.height * scale)
+        thumb = img.resize((new_w, new_h), Image.LANCZOS)
+        offset_x = x + (thumb_size - new_w) // 2
+        offset_y = y + (thumb_size - new_h) // 2
+        canvas.paste(thumb, (offset_x, offset_y))
+
+        # 左上角序号(跟随实际缩略图位置,大小按比例)
+        if show_index:
+            index_text = str(idx)
+            idx_x = offset_x
+            idx_y = offset_y
+            draw.rectangle(
+                [idx_x, idx_y, idx_x + index_box_size, idx_y + index_box_size],
+                fill=DEFAULT_INDEX_COLOR,
+            )
+            bbox = draw.textbbox((0, 0), index_text, font=font_index)
+            tw, th = bbox[2] - bbox[0], bbox[3] - bbox[1]
+            # 文本垂直对齐用 bbox 的 top 偏移修正(font bbox 的 top 可能不为 0)
+            text_x = idx_x + (index_box_size - tw) // 2 - bbox[0]
+            text_y = idx_y + (index_box_size - th) // 2 - bbox[1]
+            draw.text((text_x, text_y), index_text, fill=(255, 255, 255), font=font_index)
+
+        # 下方标题(自动按像素宽度换行)
+        if label and text_height > 0:
+            lines = _wrap_text_by_pixel(label, font_title, thumb_size, draw)
+            for line_i, line in enumerate(lines):
+                draw.text(
+                    (x, y + thumb_size + 6 + line_i * 22),
+                    line,
+                    fill=DEFAULT_TEXT_COLOR,
+                    font=font_title,
+                )
+
+    return canvas
+
+
+def _wrap_text_by_pixel(text: str, font, max_width: int, draw: ImageDraw.ImageDraw) -> List[str]:
+    """按像素宽度自动换行,兼容中英文混排(逐字符判断)"""
+    lines = []
+    current = ""
+    for ch in text:
+        test = current + ch
+        bbox = draw.textbbox((0, 0), test, font=font)
+        if bbox[2] - bbox[0] > max_width:
+            if current:
+                lines.append(current)
+            current = ch
+        else:
+            current = test
+    if current:
+        lines.append(current)
+    return lines
+
+
+# ── 编码为 base64 ──
+
+def encode_base64(image: Image.Image, format: str = "JPEG", quality: int = 75) -> Tuple[str, str]:
+    """
+    将 PIL Image 编码为 base64 字符串。
+
+    Args:
+        image: PIL Image 对象
+        format: "JPEG" 或 "PNG"。JPEG 体积更小,推荐用于多模态 LLM 输入
+        quality: JPEG 质量(1-100),PNG 忽略此参数
+
+    Returns:
+        (base64_data, media_type) 元组,如 ("iVBOR...", "image/png")
+    """
+    buf = io.BytesIO()
+    save_kwargs = {"format": format}
+    if format.upper() == "JPEG":
+        # JPEG 不支持透明通道
+        if image.mode in ("RGBA", "LA", "P"):
+            image = image.convert("RGB")
+        save_kwargs["quality"] = quality
+        save_kwargs["optimize"] = True
+    image.save(buf, **save_kwargs)
+
+    data = base64.b64encode(buf.getvalue()).decode("utf-8")
+    media_type = f"image/{format.lower()}"
+    if format.upper() == "JPEG":
+        media_type = "image/jpeg"
+    return data, media_type

+ 10 - 5
examples/mini_restore/call_banana.py

@@ -30,11 +30,12 @@ import json
 
 # 动态引入我们系统现成的 CDN 上传脚本
 sys.path.append(os.path.dirname(os.path.abspath(__file__)))
-sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'production_restore'))
+sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', '..', 'examples', 'production_restore'))
 try:
     from upload import upload_image
-except ImportError:
-    print("错误: 找不到 upload.py。请确保在 tests 目录下运行此脚本。")
+except Exception as e:
+    import traceback
+    print(f"错误: 导入 upload.py 及其依赖链失败: {e}\n{traceback.format_exc()}")
     sys.exit(1)
 
 ROUTER_URL = "http://43.106.118.91:8001/run_tool"
@@ -61,7 +62,7 @@ async def process_images(images_list: list[str]) -> list[str]:
             print(f"⚠️ 跳过找不到的本地文件或无法识别的格式: {item}")
     return final_urls
 
-async def run_nano_banana(prompt: str, images: list[str] = None, model: str = None):
+async def run_nano_banana(prompt: str, images: list[str] = None, model: str = None, aspect_ratio: str = None):
     print(f"\n=======================")
     print(f"🍌 Nano Banana 启动中...")
     print(f"=======================")
@@ -80,6 +81,9 @@ async def run_nano_banana(prompt: str, images: list[str] = None, model: str = No
     
     if model:
         params["model"] = model
+        
+    if aspect_ratio:
+        params["aspect_ratio"] = aspect_ratio
 
     payload = {
         "tool_id": "nano_banana",
@@ -130,7 +134,8 @@ if __name__ == "__main__":
     parser.add_argument("-p", "--prompt", type=str, required=True, help="你想对 AI 喊瞎什么 (比如:用图1的赛博风画一只图2里的猫)")
     parser.add_argument("-i", "--images", type=str, nargs="+", help="无限追加的垫图清单(可以是现成的 http 链接,也可以是你电脑里的硬盘文件如 example.png)")
     parser.add_argument("-m", "--model", type=str, default=None, help="覆盖模型 (默认后台会走 gemini-3.1-flash-image-preview)")
+    parser.add_argument("-a", "--aspect_ratio", type=str, default=None, help="图片比例,例如 3:4, 16:9, 1:1 等")
     
     args = parser.parse_args()
     
-    asyncio.run(run_nano_banana(prompt=args.prompt, images=args.images, model=args.model))
+    asyncio.run(run_nano_banana(prompt=args.prompt, images=args.images, model=args.model, aspect_ratio=args.aspect_ratio))

تفاوت فایلی نمایش داده نمی شود زیرا این فایل بسیار بزرگ است
+ 19 - 0
examples/mini_restore/history.json


+ 151 - 123
examples/mini_restore/workflow_loop.py

@@ -8,22 +8,52 @@ import re
 # 将项目根目录加入,方便导入内部包
 sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '../../')))
 
-from agent.llm.qwen import qwen_llm_call
+from agent.tools.builtin.toolhub import toolhub_call
+from agent.llm.gemini import create_gemini_llm_call
+
+from dotenv import load_dotenv
+load_dotenv()
+
+try:
+    gemini_llm_call = create_gemini_llm_call()
+except ValueError as e:
+    print(f"初始化 Gemini 失败: {e},请检查 .env。")
+    sys.exit(1)
+
 from agent.tools.builtin.search import search_posts
 
+# -----------------
+# Utility Functions
+# -----------------
+def encode_image(image_path: str) -> str:
+    with open(image_path, "rb") as image_file:
+        return base64.b64encode(image_file.read()).decode('utf-8')
+
+def get_base64_url(image_path: str) -> str:
+    b64_data = encode_image(image_path)
+    ext = image_path.split('.')[-1].lower()
+    if ext == 'jpg': ext = 'jpeg'
+    return f"data:image/{ext};base64,{b64_data}"
+
 # -----------------
 # Tools definitions
 # -----------------
-async def call_banana_tool(prompt: str) -> str:
-    """包装 call_banana.py 工具的调用方法,抓取它保存本地的文件路径"""
-    print(f"\n[Tool] ✨ 正在调用 call_banana 生成图片, Prompt: {prompt[:50]}...")
+async def call_banana_tool(prompt: str, aspect_ratio: str = None, reference_image: str = None, is_final: bool = True) -> str:
+    """包装 call_banana.py 生成图片,返回一张图的路径"""
+    print(f"\n[Tool] ✨ 正在调用 call_banana 生成图片 (is_final={is_final}), Prompt: {prompt[:50]}...")
     script_path = os.path.join(os.path.dirname(__file__), "call_banana.py")
     
-    # 设置环境变量走兼容模式,同时强制指定 UTF-8 编码避免 Windows 下输出由于表情符号崩溃
     env = os.environ.copy()
     env["PYTHONIOENCODING"] = "utf-8"
+    
+    cmd_args = [sys.executable, script_path, "-p", prompt]
+    if aspect_ratio:
+        cmd_args.extend(["-a", aspect_ratio])
+    if reference_image:
+        cmd_args.extend(["-i", reference_image])
+        
     process = await asyncio.create_subprocess_exec(
-        sys.executable, script_path, "-p", prompt,
+        *cmd_args,
         stdout=asyncio.subprocess.PIPE,
         stderr=asyncio.subprocess.PIPE,
         env=env
@@ -34,14 +64,13 @@ async def call_banana_tool(prompt: str) -> str:
     if err_output:
         output += "\n" + err_output
     
-    # 解析输出:"💾 已保存到本地 -> banana_output_0.jpeg"
     match = re.search(r"已保存到本地 -> (.+)", output)
     if match:
         path = match.group(1).strip()
         print(f"[Tool] ✅ call_banana 返回图片路径: {path}")
         return path
     else:
-        print(f"[Tool] ❌ call_banana 似乎未成功生成文件, 控制台输出:\n{output}")
+        print(f"[Tool] ❌ call_banana 执行失败:\n{output}")
         return f"Tool Execution Failed. output:\n{output}"
 
 async def search_tool(keyword: str) -> str:
@@ -82,6 +111,18 @@ def get_agent_tools():
                         "prompt": {
                             "type": "string",
                             "description": "英语或中文详细的生图提示词"
+                        },
+                        "aspect_ratio": {
+                            "type": "string",
+                            "description": "(可选)你期望生成的图片宽高比,例如 3:4, 16:9, 1:1,请根据目标参考图的比例传入该参数"
+                        },
+                        "reference_image": {
+                            "type": "string",
+                            "description": "(动作控制底图)如果你在这一步设 is_final=true,请将你在上一阶段生成的【辅助骨架素材(is_final=false)】产生的本地路径填入此处。绝对禁止传入原始目标照片!"
+                        },
+                        "is_final": {
+                            "type": "boolean",
+                            "description": "指示本次生成是否是本轮次的最终产物。如果你需要先生成一张『白底火柴人/3D骨架』作为辅助垫图素材,请设为 false;拿到素材后,你必须继续将它的本地路径填给 `reference_image` 并使用最终 Prompt 和 is_final=true 完成最后合成。"
                         }
                     },
                     "required": ["prompt"]
@@ -90,67 +131,7 @@ def get_agent_tools():
         }
     ]
 
-# -----------------
-# Agent 2: Image Evaluator (Qwen-VL-Max)
-# -----------------
-async def evaluate_images(target_image_path: str, generated_image_path: str, previous_feedback: str = None) -> str:
-    print(f"\n[Agent 2] 👁️ Qwen-VL 开始视觉评估...")
-    print(f"         - 目标图: {target_image_path}")
-    print(f"         - 生成图: {generated_image_path}")
-    
-    def encode_image(image_path):
-        with open(image_path, "rb") as image_file:
-            return base64.b64encode(image_file.read()).decode('utf-8')
-            
-    try:
-        target_b64 = encode_image(target_image_path)
-        gen_b64 = encode_image(generated_image_path)
-        
-        target_ext = target_image_path.split('.')[-1].lower()
-        if target_ext == 'jpg': target_ext = 'jpeg'
-        gen_ext = generated_image_path.split('.')[-1].lower()
-        if gen_ext == 'jpg': gen_ext = 'jpeg'
-    except Exception as e:
-        return f"无法读取图片以进行评估: {e}"
-
-    system_content = "你是专业的AI生图评审师。你的工作是对比【目标参考图】和当前【生成图】,找出具体的差异,并给出针对性的修改意见给生图Prompt工程师。"
-    if previous_feedback:
-        system_content += "\n你还会收到你【上一轮的评估反馈】。请结合你的旧反馈,检查这轮新图片是否修正了你上次提出的问题,避免重复说一样的话,而是要有动态进展意识!"
 
-    text_prompt = "请做详细的差异点分析:从构图、色彩、人物或物体细节、整体质感等方面指出当前生成图与目标图的差距。"
-    if previous_feedback:
-        text_prompt += f"\n\n你对上一版旧图的评估反馈曾经是:\n{previous_feedback}\n\n请比对这张【新生成图】,告诉我:上一版的问题被解决了吗?画面的进步点和退步点在哪里?请给出更新的针对性修改意见!"
-    else:
-        text_prompt += "结束时,请给出具体的 Prompt 修改建议。"
-
-    messages = [
-        {
-            "role": "system",
-            "content": system_content
-        },
-        {
-            "role": "user",
-            "content": [
-                {"type": "text", "text": "【目标参考图(理想状态)】:"},
-                {"type": "image_url", "image_url": {"url": f"data:image/{target_ext};base64,{target_b64}"}},
-                {"type": "text", "text": "【本次生成的图片】:"},
-                {"type": "image_url", "image_url": {"url": f"data:image/{gen_ext};base64,{gen_b64}"}},
-                {"type": "text", "text": text_prompt}
-            ]
-        }
-    ]
-    
-    try:
-        response = await qwen_llm_call(
-            messages=messages,
-            model="qwen3.5-plus" 
-        )
-        analysis = response["content"]
-        print(f"\n[Agent 2] 📃 评估反馈:\n{analysis}\n")
-        return analysis
-    except Exception as e:
-        print(f"\n[Agent 2] ⚠️ 评估发生错误: {e}")
-        return f"VL模型调用失败: {e}"
 
 # -----------------
 # Main Workflow Loop
@@ -166,14 +147,18 @@ def get_base64_url(image_path: str) -> str:
 async def main():
     import argparse
     import os
+    import json
     
     default_target = os.path.join(os.path.dirname(os.path.abspath(__file__)), "input", "img_1.png")
     parser = argparse.ArgumentParser(description="多智能体画图自动优化 Workflow")
     parser.add_argument("-t", "--target", default=default_target, help="你想逼近的目标参考图本地路径")
-    parser.add_argument("-m", "--max_loops", type=int, default=10, help="优化的最大迭代论调")
+    parser.add_argument("-p", "--pose", default=None, help="你提供的姿势参考图(如果有的话,给 Agent 用来走捷径垫底)")
+    parser.add_argument("-m", "--max_loops", type=int, default=15, help="优化的最大迭代论调")
+    parser.add_argument("-r", "--resume", action="store_true", help="是否从上次的 history.json 继续运行")
     args = parser.parse_args()
     
     target_image = args.target
+    pose_image = args.pose
 
     print("\n" + "="*50)
     print("🤖 启动双 Agent 生图闭环工作流 (纯 Vision-Language 架构)")
@@ -183,15 +168,35 @@ async def main():
         print(f"⚠️ 找不到目标图片: {target_image}")
         print("提示: 系统依然会运行寻找文件,但 Agent 2 将无法给出评估。可随便放一个图片来模拟。")
     
+    sys_content = f"你是一个高度自治的闭环生图优化 AI 架构师。你的目标是:生成一张与【目标参考图】在主角姿势、整体结构上无限接近的图片。\n你拥有极强的视觉反思能力和 Prompt 编写能力。\n\n【核心工作流与防坑指南】:\n- 你会看到你的【目标参考图】和你的【往期历史尝试与生成结果】。\n- 请你先利用你的**多模态火眼金睛**,无情地对自己上一轮生成的图片进行找茬。绝不允许说客套话!重点对比人物骨架、姿势和构图的偏离程度。\n- 紧接着,请在反思的基础上,直接重构或调整你的 Prompt,并在一次回复中调用 `call_banana_tool` 下发生图指令!\n- 【防作弊铁律】:你**绝对禁止**直接将【目标参考图】的路径传进 `reference_image` 来作弊!如果你想用图生图垫出完美动作,必须使用【中间素材战法】亲手画一张骨架出来垫。\n- 【中间素材战法】:如果原图姿态过于刁钻复杂,**要求你必须**分两步走:\n   第一步:设置 `is_final=false` 并写一段专门用于抽出单一维度的动作骨架/白模 Prompt(如: \"a generic white 3d mannequin jumping in mid-air, clean white background, high contrast skeleton\"),专门用于抽出干净的辅助骨架。\n   第二步:拿到这只纯净骨架的本地路径后,在同回合的下一次调用中,把这只骨架当做 `reference_image` 垫进去,配合你华丽的最终描述(如: \"a neon cyberpunk assassin jumping\"),设置 `is_final=true` 完成高阶对齐兼防污染! \n\n"
+    
+    if pose_image and os.path.exists(pose_image):
+        sys_content += f"【🔥终极开挂特权】:\n天啊!用户居然为你额外提供了一张极致完美的【姿势参考图】!既然有了这张现成的动作骨架底图,你**立刻抛弃**两步走去抽骨架的方法。你应当直接使用特权,将这张姿势参考图的绝对物理路径 `{os.path.abspath(pose_image)}` 作为 `reference_image` 无脑传给引擎,配合你的终极词汇,并在第一回合内设置 `is_final=true` 完成终极绝杀生成!\n\n"
+
+    sys_content += "流程要求:\n1. 仔细分析差异,在你的纯文本回复段落写出【犀利的反思和执行步骤】。\n2. 反思结束后,使用工具发号施令。\n3. 当调用 `is_final=true` 时,视为你的本轮彻底结束。"
+
     system_msg = {
         "role": "system",
-        "content": "你是一个超级提示词工程师(Prompt Engineer)。目标:生成一张无限接近【目标参考图】的图片。\n作为多模态大模型,每一轮我都会给你看你上次生成的图片结果和评估专家的犀利分析反馈。你需要利用这些反馈进行修改。\n流程要求:\n1. (可选)如果你对风格不确定,可以请求 search_tool 调研别人怎么写相关提示词。\n2. 使用 call_banana_tool 来实际提交你的提示词并生成图片。\n3. 调用生成工具后,你本轮的工作就结束了,系统会把成果拿去评估并在下一轮找你。"
+        "content": sys_content
     }
 
     max_loops = args.max_loops
     current_generation_loop_count = 0
     last_gen_info = None
     prompt_history = [] # 记录完整的历史 Prompt 轨迹,防止反复抽卡
+    
+    history_file = os.path.join(os.path.dirname(os.path.abspath(__file__)), "history.json")
+    if args.resume and os.path.exists(history_file):
+        try:
+            with open(history_file, "r", encoding="utf-8") as f:
+                prompt_history = json.load(f)
+            if prompt_history:
+                current_generation_loop_count = len(prompt_history)
+                last_gen_info = prompt_history[-1]
+                print(f"✅ [状态恢复] 已成功从 history.json 加载 {current_generation_loop_count} 轮历史,即将开始第 {current_generation_loop_count + 1} 轮...")
+        except Exception as e:
+            print(f"⚠️ [状态恢复失败] 读取历史记录报错: {e},将重新开始第一轮。")
+            prompt_history = []
 
     while current_generation_loop_count < max_loops:
         print(f"\n" + "="*40)
@@ -204,42 +209,60 @@ async def main():
         if last_gen_info is None:
             try:
                 target_b64_url = get_base64_url(target_image)
+                content_list = [
+                    {"type": "text", "text": "【首轮启动】\n这是你需要逼近的【目标参考图】。现在请你仔细观察它,提炼出一份初步生图 Prompt。\n因为是第一轮,请直接凭借直觉观察,并使用 call_banana_tool 生成原型。"},
+                    {"type": "image_url", "image_url": {"url": target_b64_url}}
+                ]
+                
+                if pose_image and os.path.exists(pose_image):
+                    content_list.append({"type": "text", "text": "并且,下面是用户良心为你提供的【开挂级·姿势参考图】!你可以直接在接下来的提示词工具调用中将此图拿去垫图!"})
+                    content_list.append({"type": "image_url", "image_url": {"url": get_base64_url(pose_image)}})
+                    
                 messages.append({
                     "role": "user",
-                    "content": [
-                        {"type": "text", "text": "这是你需要逼近的【目标参考图】。现在请你仔细观察它,并提炼出一份详尽的初步生图 Prompt。你可以酌情使用 search_tool 调研,最后必须使用 call_banana_tool 提交你的 Prompt 生成最初的原型。"},
-                        {"type": "image_url", "image_url": {"url": target_b64_url}}
-                    ]
+                    "content": content_list
                 })
             except Exception as e:
                 messages.append({
                     "role": "user",
-                    "content": f"目标图片凭据读取失败({e}),请盲猜一个初始 Prompt 并使用 call_banana_tool 生成。"
+                    "content": f"目标图片读取失败({e}),请盲猜一个初始 Prompt 用 call_banana_tool 生成。"
                 })
         else:
             try:
-                gen_image_url = get_base64_url(last_gen_info["image_path"])
+                target_b64_url = get_base64_url(target_image)
+                user_content = [
+                    {"type": "text", "text": "【持续干预闭环】\n这是不可动摇的【目标参考图】,它是一切评判的唯一基准:"},
+                    {"type": "image_url", "image_url": {"url": target_b64_url}}
+                ]
+                
+                if pose_image and os.path.exists(pose_image):
+                    user_content.append({"type": "text", "text": "【外挂辅助】\n这是不可动摇的【姿势参考图】,请毫不犹豫地拿它去填进 reference_image 控制动作:"})
+                    user_content.append({"type": "image_url", "image_url": {"url": get_base64_url(pose_image)}})
+                    
+                user_content.append({"type": "text", "text": "\n==== 【你的历史试错轨迹】 ====\n为了防止你在这场试错过程中来回打转(所谓的废卡反复抽卡),我为你列出了你*从古至今*所有的失败作品和对应的提示词!请认真观察下面每一张你过去的废片:\n"})
                 
-                # 构建历史记录描述,让它知道自己之前走过哪些弯路避免抽卡
-                history_text = "【你的历史迭代轨迹 (包含往期Prompt与评估专家对其的批评,用于防复读和总结改进)】:\n"
                 for i, record in enumerate(prompt_history):
-                    history_text += f"==== 第 {i+1} 轮 ====\n"
-                    history_text += f"[使用的 Prompt]:\n{record['prompt']}\n"
-                    history_text += f"[收到的反馈批评]:\n{record['feedback']}\n\n"
+                    user_content.append({"type": "text", "text": f"-- 第 {i+1} 轮 --\n[上次使用的 Prompt]:\n{record['prompt']}\n[此轮的废片结果]:"})
+                    
+                    try: 
+                        img_path = record.get("image_paths", [record.get("image_path")])[0]
+                        # 节约上下文 Token 和视觉注意力:只渲染第一张(由于打底盲测)和最近一次的历史原图,中间的全部折叠仅保留反思文本
+                        if i == 0 or i == len(prompt_history) - 1:
+                            user_content.append({"type": "image_url", "image_url": {"url": get_base64_url(img_path)}})
+                        else:
+                            user_content.append({"type": "text", "text": "*(由于历史过于久远,中间轮次图片已省去展示,请聚焦于下面你对它的纯文本反思)*"})
+                    except:
+                        pass
+                        
+                    if record.get("feedback"):
+                        user_content.append({"type": "text", "text": f"[你在本轮结束后的反思]:\n{record['feedback']}\n"})
+                
+                user_content.append({"type": "text", "text": "====================\n\n现在,结合上述轨迹与那张【目标参考图】,请在回复中写出最新的【极度苛刻自我反思】,然后立马调用工具生成这轮新的 Prompt!"})
+                
+                messages.append({"role": "user", "content": user_content})
                 
-                messages.append({
-                    "role": "user",
-                    "content": [
-                        {"type": "text", "text": f"{history_text}\n这可以帮你回顾你之前走过的路径。现在聚焦到上一轮:\n\n你上一轮({len(prompt_history)})使用的生图Prompt为:\n{last_gen_info['prompt']}\n\n这里是你上一轮生成的图片结果,请仔细查看对比:"},
-                        {"type": "image_url", "image_url": {"url": gen_image_url}},
-                        {"type": "text", "text": f"【视觉评估专家的分析反馈】:\n{last_gen_info['feedback']}\n\n请针对上述反馈,思考到底哪里不像,参考上述的历史轨迹避免重蹈覆辙,进行新的调研修正(如果需要),或者直接使用 call_banana_tool 生成优化后的版本。"}
-                    ]
-                })
             except Exception as e:
-                messages.append({
-                    "role": "user",
-                    "content": f"上一轮信息读取失败 ({e})。请重新尝试凭感觉用 call_banana_tool 再次生成。"
-                })
+                messages.append({"role": "user", "content": f"上下文读取失败 ({e})。请重试用 call_banana_tool 生成。"})
 
         # Agent 1 内部工具调研微循环 (Agent 1 minor logic loop)
         agent1_finished_generation = False
@@ -248,9 +271,9 @@ async def main():
         while not agent1_finished_generation:
             print(f"---\n💬 正在请求 Agent 1 (Prompt 师)...")
             # 这里 Agent 1 也换成 qwen-vl-max,这样它才能看到传给它的上一轮图片
-            response = await qwen_llm_call(
+            response = await gemini_llm_call(
                 messages=messages,
-                model="qwen3.5-plus",
+                model="gemini-3.1-pro-preview",
                 tools=get_agent_tools()
             )
             
@@ -272,6 +295,7 @@ async def main():
             assistant_reply = {"role": "assistant"}
             if content: assistant_reply["content"] = content
             if tool_calls: assistant_reply["tool_calls"] = tool_calls
+            if "raw_gemini_parts" in response: assistant_reply["raw_gemini_parts"] = response["raw_gemini_parts"]
             messages.append(assistant_reply)
 
             if tool_calls:
@@ -289,49 +313,49 @@ async def main():
                         })
                     
                     elif func_name == "call_banana_tool":
-                        print(f"\n⚙️ Agent 1 决定提交生图请求!")
+                        is_final = args_dict.get("is_final", True)
+                        print(f"\n⚙️ 节点发起了生图请求 (是否为终极图: {is_final})!")
                         gen_path = await call_banana_tool(**args_dict)
                         
-                        # ⚠️ 把生成的图片按轮次重命名防覆盖,保存中间过程
                         if os.path.exists(gen_path):
                             ext = gen_path.split('.')[-1]
-                            new_gen_path = f"gen_loop_{current_generation_loop_count + 1}.{ext}"
                             import shutil
+                            if is_final:
+                                new_gen_path = f"gen_loop_{current_generation_loop_count + 1}.{ext}"
+                            else:
+                                import uuid
+                                new_gen_path = f"gen_loop_{current_generation_loop_count + 1}_material_{str(uuid.uuid4())[:8]}.{ext}"
                             shutil.move(gen_path, new_gen_path)
                             gen_path = new_gen_path
-                            print(f"[文件管理] 中间图片已重命名并保存为: {new_gen_path}")
+                            print(f"[文件管理] 生图结果已重命名并保存为: {new_gen_path}")
                         
                         prompt_used = args_dict.get("prompt", "")
                         
-                        # 把消息补齐,虽然这一轮马上就要重置销毁了
                         messages.append({
                             "role": "tool",
                             "tool_call_id": tc_id,
-                            "content": f"已生成,路径: {gen_path}"
+                            "content": f"已成功生成,图片路径: {os.path.abspath(gen_path)}"
                         })
                         
-                        agent1_finished_generation = True
-                        current_generation_loop_count += 1
-                        
-                        # 进行评估并记录,传递给下一大轮
-                        if os.path.exists(gen_path) and os.path.exists(target_image):
-                            prev_feedback = last_gen_info["feedback"] if last_gen_info else None
-                            evaluation_feedback = await evaluate_images(target_image, gen_path, prev_feedback)
+                        if is_final:
+                            agent1_finished_generation = True
+                            current_generation_loop_count += 1
+                            
                             last_gen_info = {
                                 "prompt": prompt_used,
                                 "image_path": gen_path,
-                                "feedback": evaluation_feedback
+                                "feedback": content if content else "无反思内容"
                             }
+                            
+                            prompt_history.append(last_gen_info)
+                            try:
+                                with open(history_file, "w", encoding="utf-8") as f:
+                                    json.dump(prompt_history, f, ensure_ascii=False, indent=2)
+                            except Exception as e:
+                                print(f"[警告] 历史记录保存失败: {e}")
+                            break # 跳出 tool_calls for loop 并进入下一大轮
                         else:
-                            last_gen_info = {
-                                "prompt": prompt_used,
-                                "image_path": gen_path,
-                                "feedback": f"系统提示:由于目标图 {target_image} 或生成图 {gen_path} 不存在,评估被跳过。"
-                            }
-                        
-                        # 记录到全局大历史中,供它长线参考防重踩坑
-                        prompt_history.append(last_gen_info)
-                        break # 跳出 tool_calls for loop
+                            print(f"[战术回馈] 这是辅助素材,已将路径返回给 Agent1 继续思考。")
             else:
                 # 没调工具
                 print("\n[控制中心] Agent 1 没有继续使用任何工具。结束其周期。")
@@ -346,10 +370,14 @@ async def main():
         print("🏆 正在生成【专家最终多维度反馈报告】...")
         print("="*50)
         
-        first_gen = prompt_history[0]["image_path"]
-        last_gen = prompt_history[-1]["image_path"]
+        first_gen_record = prompt_history[0]
+        last_gen_record = prompt_history[-1]
+        
+        # 兼容旧版本的单图记录和新版本的多图记录
+        first_gen = first_gen_record.get("image_paths", [first_gen_record.get("image_path")])[0]
+        last_gen = last_gen_record.get("image_paths", [last_gen_record.get("image_path")])[0]
         
-        if os.path.exists(first_gen) and os.path.exists(last_gen):
+        if first_gen and last_gen and os.path.exists(first_gen) and os.path.exists(last_gen):
             try:
                 target_b64 = encode_image(target_image)
                 first_b64 = encode_image(first_gen)
@@ -382,9 +410,9 @@ async def main():
                     }
                 ]
                 
-                response = await qwen_llm_call(
+                response = await gemini_llm_call(
                     messages=final_messages,
-                    model="qwen3.5-plus"
+                    model="gemini-3.1-pro-preview"
                 )
                 print(f"\n[Agent 2] 📋 【最终多维度评估报告】:\n{response['content']}\n")
             except Exception as e:

+ 2 - 1
examples/production_restore/config.py

@@ -49,8 +49,9 @@ RUN_CONFIG = RunConfig(
 
 # ===== 任务配置 =====
 
-INPUT_DIR = "examples/production_restore/input"       # 输入目录(pipeline.json、analysis.json、research.json
+INPUT_DIR = "examples/production_restore/input"       # 输入目录(pipeline.json、analysis.json
 OUTPUT_DIR = "examples/production_restore/output_feature"     # 输出目录
+FEATURES_DIR = "examples/production_restore/features"         # 素材目录
 
 
 # ===== 基础设施配置 =====

+ 21 - 8
examples/production_restore/execution.prompt

@@ -18,13 +18,17 @@ $system$
 - Prompt 文本
 - 图生图配置(img2img_config)
 
-**参考源信息(raw_info)**:
-在输入目录中有一个 `raw_info` 文件,包含原始图片的源信息(如图片描述、风格标签、技术参数、色彩分析等)。在构建或优化 prompt 时,**应先读取 raw_info 作为参考**,从中提取有价值的细节描述融入 prompt,以更精准地还原目标效果。raw_info 是辅助参考,最终 prompt 仍以任务指派中的要求为准。
+**参考源信息(raw_info 目录)**:
+在输入目录中有一个 `raw_info/` 文件夹,包含原始图片的源信息:
+- 每张图的制作表:`raw_info/写生油画__img_X_制作表.json`(对应 img_1 ~ img_5)
+- 通用创作信息:`raw_info/创作表.md`、`raw_info/制作点.md`、`raw_info/图片亮点.md`
+
+在构建或优化 prompt 时,**应先读取当前图片对应的制作表 JSON 和通用文件作为参考**,从中提取有价值的细节描述融入 prompt。raw_info 是辅助参考,最终 prompt 仍以任务指派中的要求为准。
 
 ### 第二步:验证素材可用性
 在执行生成前,先验证所需文件存在且可读:
 - 使用 `read_file` 工具检查各参考素材文件(**`read_file` 支持读取图片,会自动转为 base64 供你查看,无需打开浏览器**)
-- 读取 `raw_info` 获取图片源信息,提取可用于 prompt 的细节
+- 读取 `raw_info/` 目录下对应的制作表 JSON(如生成 img_1 则读 `写生油画__img_1_制作表.json`)和通用文件(`创作表.md`、`图片亮点.md`),提取可用于 prompt 的细节
 - 如有素材缺失,立即在结果中标注(不要自行跳过)
 
 ### 第三步:通过 ToolHub 工具库执行生成
@@ -49,7 +53,7 @@ toolhub.py 内置了 `_preprocess_params` 函数,会自动将本地路径上
 ✅ **正确做法**:
 ```json
 {
-  "image_url": "examples/production_restore/features/character_asset/character_ref_back.png"
+  "image_url": "%features_dir%/character_asset/character_ref_back.png"
 }
 ```
 
@@ -77,12 +81,12 @@ toolhub.py 内置了 `_preprocess_params` 函数,会自动将本地路径上
 
 **单图评估**:传入需求文档路径和单张图片路径
 ```json
-{"requirement_path": "examples/production_restore/input/pipeline.json", "image_paths": "输出图片路径"}
+{"requirement_path": "%input_dir%/pipeline.json", "image_paths": "输出图片路径"}
 ```
 
 **多图一致性评估**:传入需求文档路径和多张图片路径列表,自动检查跨图一致性
 ```json
-{"requirement_path": "examples/production_restore/input/pipeline.json", "image_paths": ["img_1路径", "img_2路径", "img_3路径"]}
+{"requirement_path": "%input_dir%/pipeline.json", "image_paths": ["img_1路径", "img_2路径", "img_3路径"]}
 ```
 
 - 单图模式:从姿态、服装、光影、背景、材质、构图 6 个维度打分(0-10)
@@ -98,7 +102,15 @@ toolhub.py 内置了 `_preprocess_params` 函数,会自动将本地路径上
 
 ### 第五步:输出结果报告
 
-**输出格式**:
+**输出文件命名规则(极其重要)**:
+- **图片文件使用版本号命名,绝不覆盖已有文件**
+  - 首次生成:`img_1_restored_v1.png`
+  - 迭代优化:`img_1_restored_v2.png`、`img_1_restored_v3.png`...
+  - 最终定稿:`img_1_restored_final.png`
+- **检查输出目录中是否已有同名文件**,如有则递增版本号
+- **每次生成都必须追加记录到 `%output_dir%/generation_log.md`**,而不是覆盖
+
+**generation_log.md 追加格式**:
 
 ```
 ## 任务:[img_X 还原]
@@ -116,8 +128,9 @@ toolhub.py 内置了 `_preprocess_params` 函数,会自动将本地路径上
 - 分辨率: [宽]x[高]
 
 ### 生成结果
-- 输出路径: [路径]
+- 输出路径: [路径,含版本号如 img_1_restored_v2.png]
 - 生成耗时: [X]s
+- 版本说明: [v1=首次生成 / v2=调整prompt后重试 / vN=第N次迭代]
 
 ### 验证结果
 - 姿态符合度: [通过/不通过] — [说明]

+ 5 - 5
examples/production_restore/input/pipeline.json

@@ -52,7 +52,7 @@
       "prompt": "一位穿着纯白色长裙的女性在户外草地写生,身体略微前倾专注绘画,右手持画笔左手持调色板,棕色长发自然披散在背部,轻薄棉麻质地的白色长裙,V 字露背设计,腰部系带收腰,裙摆自然垂坠有飘逸感,温暖的逆光从左上方照射,人物边缘形成金色轮廓光,发丝呈现明亮光晕,全画幅 85mm 人像定焦镜头,光圈 f/1.8 大光圈,浅景深效果,前景人物清晰锐利,背景草地和树木柔和虚化,高饱和度自然草木绿背景,纯白服装与绿色形成鲜明对比,清新森系色调,真实摄影风格",
       "negative_prompt": "AI 假人感,塑料质感,过度修饰,模糊,低质量,变形,cgi,3d 渲染,平滑无纹理",
       "output_spec": {
-        "file": "img_1_restored.png",
+        "file": "img_1_restored_v1.png",
         "resolution": "1024x1365",
         "critical_checks": ["人物姿态自然度", "白裙材质与褶皱真实感", "前景主体清晰度"],
         "high_checks": ["逆光轮廓光效果", "背景虚化自然度", "调色板颜料质感"]
@@ -80,7 +80,7 @@
       "prompt": "一位穿着纯白色长裙的女性在户外草地写生,背对镜头,身体略微右倾,强烈逆光效果,人物呈半剪影,发丝边缘明亮金边,轻薄白裙在逆光下呈现透光效果,木质画架和画布,调色板,背景绿色树木柔和虚化,圆形光斑效果,梦幻浪漫氛围,85mm 镜头,f/1.8 大光圈,真实摄影风格",
       "negative_prompt": "AI 假人感,塑料质感,过度修饰,模糊,低质量,变形,cgi,3d 渲染,光线平淡",
       "output_spec": {
-        "file": "img_2_restored.png",
+        "file": "img_2_restored_v1.png",
         "resolution": "1024x1365",
         "critical_checks": ["逆光轮廓光效果", "人物姿态自然度", "前景主体清晰度"],
         "high_checks": ["背景光斑效果", "白裙透光感", "发丝金边细节"]
@@ -108,7 +108,7 @@
       "prompt": "一位穿着纯白色长裙的女性跪坐在户外草地写生,身体前倾专注绘画,左臂靠近地面调色板,棕色长发自然披散,轻薄棉麻质地白裙,裙摆自然铺展在草地上,自然光从左上方照射,柔和轮廓光,背景绿色草地和蓝紫色花丛,浅景深虚化,85mm 镜头,f/1.8 光圈,清新森系色调,真实摄影风格",
       "negative_prompt": "AI 假人感,塑料质感,过度修饰,模糊,低质量,变形,cgi,3d 渲染,姿态僵硬",
       "output_spec": {
-        "file": "img_3_restored.png",
+        "file": "img_3_restored_v1.png",
         "resolution": "1024x1365",
         "critical_checks": ["跪坐姿态自然度", "白裙材质与褶皱真实感", "前景主体清晰度"],
         "high_checks": ["花丛背景虚化", "裙摆铺展效果", "光影柔和度"]
@@ -137,7 +137,7 @@
       "prompt": "一位穿着纯白色长裙的女性侧身站立面对镜头,头部仰望向左上方,右臂抬起握持画笔,左臂持调色板,轻薄棉麻质地白裙,自然光照射,柔和光影,背景高饱和度绿色草地和树木,浅景深虚化,木质画架上有空白白色画布,纯白色表面无颜料痕迹,85mm 镜头,f/1.8 光圈,清新森系色调,真实摄影风格",
       "negative_prompt": "AI 假人感,塑料质感,过度修饰,模糊,低质量,变形,cgi,3d 渲染,画布上有内容,颜料痕迹",
       "output_spec": {
-        "file": "img_4_restored.png",
+        "file": "img_4_restored_v1.png",
         "resolution": "1024x1365",
         "critical_checks": ["人物姿态自然度", "白裙材质真实感", "空白画布纯白无内容"],
         "high_checks": ["仰望表情自然", "侧身轮廓清晰", "背景虚化"]
@@ -165,7 +165,7 @@
       "prompt": "特写镜头,聚焦女性双手握持木质调色板和画笔,调色板上有厚重油画颜料 Impasto 质感,膏状堆积,多色混合(绿色、蓝色、红色、黄色、白色、紫色),颜料表面湿润光泽,立体厚度可见,女性穿着纯白色长裙,上半身可见,温暖逆光照射,颜料光泽反射,背景绿色强烈虚化,85mm 微距镜头,f/1.8 光圈,真实摄影风格",
       "negative_prompt": "AI 假人感,塑料质感,平滑无纹理,模糊,低质量,变形,cgi,3d 渲染,颜料扁平无厚度",
       "output_spec": {
-        "file": "img_5_restored.png",
+        "file": "img_5_restored_v1.png",
         "resolution": "1024x1365",
         "critical_checks": ["调色板颜料 Impasto 质感", "颜料湿润光泽", "特写清晰度"],
         "high_checks": ["多色颜料混合", "手部细节", "背景虚化"]

+ 23 - 3
examples/production_restore/presets.json

@@ -3,13 +3,33 @@
     "system_prompt_file": "requirement.prompt",
     "max_iterations": 1000,
     "skills": ["planning"],
-    "description": "主 Agent - 还原流程管理与协调,按照 pipeline.json 逐阶段指派执行"
+    "prompt_vars": {
+      "input_dir": "examples/production_restore/input",
+      "output_dir": "examples/production_restore/output_feature",
+      "features_dir": "examples/production_restore/features"
+    },
+    "description": "Business Agent - 决策循环编排器,驱动 goal → evaluate → decide → dispatch 循环"
   },
-  "executor": {
+  "craftsman": {
     "system_prompt_file": "execution.prompt",
     "max_iterations": 200,
     "temperature": 0.3,
     "skills": ["planning"],
-    "description": "执行 Agent - 根据指令执行图像生成、素材验证、细节修复等具体操作"
+    "prompt_vars": {
+      "input_dir": "examples/production_restore/input",
+      "output_dir": "examples/production_restore/output_feature",
+      "features_dir": "examples/production_restore/features"
+    },
+    "description": "Craftsman - 单步执行专家,调用 ToolHub 工具执行图像生成"
+  },
+  "researcher": {
+    "system_prompt_file": "research.prompt",
+    "max_iterations": 200,
+    "temperature": 0.3,
+    "skills": ["planning"],
+    "prompt_vars": {
+      "output_dir": "examples/production_restore/output_feature"
+    },
+    "description": "Researcher - 外部知识获取专家,搜索线上教程和案例"
   }
 }

+ 116 - 57
examples/production_restore/requirement.prompt

@@ -6,14 +6,23 @@ temperature: 0.3
 $system$
 
 ## 角色
-你是一个专注执行的 AI 图像还原专家。你已拿到完整的还原方案(pipeline.json),任务是严格按照方案,逐阶段指派执行 agent 完成图像生成,并在每阶段验证结果后推进下一阶段。
+你是 Business Agent(决策循环编排器)。你的职责是驱动 **goal → evaluate → decide → dispatch** 循环,将图像还原任务分解为具体步骤,通过调度不同角色完成。
+
+**你不直接执行生成或调研**,而是通过以下角色协作:
+
+| 角色 | 调用方式 | 职责 |
+|------|---------|------|
+| **Librarian** | `ask_knowledge(query=...)` | 内部知识顾问,基于 KnowHub 已有知识给出方案建议 |
+| **Craftsman** | `agent(task=..., agent_type="craftsman")` | 单步执行专家,调用 ToolHub 工具执行图像生成 |
+| **Researcher** | `agent(task=..., agent_type="researcher")` | 外部知识获取,搜索线上教程和案例 |
+| **evaluate** | `evaluate_image(requirement_path=..., image_paths=...)` | 质量评估工具,对照需求打分 |
 
 ## 路径约定
 - 输入目录(JSON 方案文件):`%input_dir%`
-- 素材目录(参考图等素材):`%input_dir%/../features`
+- 素材目录(参考图等素材):`%features_dir%`
 - 输出目录:`%output_dir%`
 
-pipeline.json 中 `input_from` 字段的路径均相对于素材目录(`features/`)。**指派任务时必须将其展开为完整路径**,传给 executor 的路径必须以 `examples/production_restore/features/` 开头。
+pipeline.json 中 `input_from` 字段的路径均相对于素材目录。**指派任务时必须将其展开为完整路径**,传给 Craftsman 的路径必须以 `%features_dir%/` 开头。
 
 ### 素材目录结构
 ```
@@ -24,69 +33,119 @@ features/
 ├── palette_asset/     — 调色板道具素材(Impasto 厚涂颜料)
 ```
 
-## 指派子 agent 时的要求
+## 决策循环
+
+你的核心工作模式是不断执行以下循环:
+
+```
+1. 设定目标(Goal)
+2. 问策(ask_knowledge)→ Librarian 返回建议
+3. 如知识不足 → 派发 Researcher 调研 → 结果存入 KnowHub
+4. 决策(Decide)→ 确定执行方案
+5. 派发(Dispatch)→ Craftsman 执行具体任务
+6. 评估(Evaluate)→ evaluate_image 检查结果
+7. 根据评估结果:通过 → 下一目标;不通过 → 回到步骤 2 调整方案
+```
+
+**context 管理原则**:你只保留当前目标 + 当前结果 + 当前评估,不累积历史。每轮循环的 context 保持小且聚焦。
+
+## 工作流程
 
-指派 executor 执行每张图的生成任务时,**必须在任务描述中明确包含以下信息**:
+### 第一步:读取还原方案
+读取 `%input_dir%/pipeline.json`,提取整体结构和每张图的规格。
 
-1. **底图路径**:pipeline.json 中 `img2img_config.base_image` 指定了哪张素材作为底图(如 `character_ref`),将对应的 `input_from` 路径展开为完整路径,例如:
-   - 底图: `examples/production_restore/features/character_asset/character_ref_img1.png`
+### 第二步:问策 Librarian
+在开始生成前,先向 Librarian 咨询:
+```
+ask_knowledge(query="户外白裙写生少女图像还原,使用端到端图生图工具(nano_banana/flux/seedream),需要保持5张图的角色一致性,有什么推荐方案?")
+```
+- Librarian 会返回 KnowHub 中已有的策略经验、工具评估、工作流总结
+- 如果 Librarian 回复"知识不足"或建议不够具体 → 派发 Researcher 调研
 
-2. **参考素材的完整路径**:`img2img_config.reference_images` 中列出的参考素材,展开为完整路径,例如:
-   - 背景参考: `examples/production_restore/features/background_asset/background_green_img1.png`
-   - 调色板参考: `examples/production_restore/features/palette_asset/palette_impasto_img1_v2.png`
+### 第三步:按需调研
+如果 Librarian 的知识不足以决策:
+```
+agent(task="调研 nano_banana 图生图的最佳实践,特别是如何保持多图角色一致性...", agent_type="researcher")
+```
+- Researcher 会搜索外部平台并返回调研结果
+- 调研结果可通过 `upload_knowledge` 存入 KnowHub 供后续使用
 
-3. **素材使用方式**:告知 executor 如何使用这些素材:
-   - **底图** → 作为端到端工具(nano_banana / flux_generate / seedream_generate)的 `image_url` 参数传入,进行图生图生成
-   - **参考素材** → 辅助 prompt 描述,帮助 executor 理解目标效果;如工具支持多图输入,可作为参考图传入
-   - executor 必须先读取素材文件,确认存在后再调用工具
-   - **必须使用底图做图生图**,不能跳过底图用纯文生图替代
-   - 如果底图或关键素材文件缺失必须上报
+### 第四步:链式图生图生成(Stage 1)
+严格按 **img_1 → img_2 → img_3 → img_4 → img_5** 的顺序串行生成:
 
-4. **Prompt 和生成配置**:从 pipeline.json 中提取的完整 prompt、negative prompt、img2img_config 等
+**img_1(基准图)**:
+```
+agent(task="生成 img_1(基准图):
+  底图: %features_dir%/character_asset/character_ref_img1.png
+  背景参考: %features_dir%/background_asset/background_green_img1.png
+  调色板参考: %features_dir%/palette_asset/palette_impasto_img1_v2.png
 
-5. **源信息参考**:告知 executor 读取 `%input_dir%/raw_info` 文件获取图片源信息,从中提取有价值的细节融入 prompt
+  底图使用方式:将 character_ref 作为 image_url 传入端到端工具做图生图
+  读取 raw_info 目录下对应的制作表(%input_dir%/raw_info/写生油画__img_1_制作表.json)和通用文件辅助 prompt
 
-6. **输出路径**:指定输出保存到 `%output_dir%/`
+  Prompt: [从 pipeline.json 提取]
+  Negative Prompt: [从 pipeline.json 提取]
+  img2img_config: [从 pipeline.json 提取]
 
-## 工作流程
+  此图确立角色基准外观,后续所有图以此为参考锚点。
+  输出保存到: %output_dir%/img_1_restored_v1.png", agent_type="craftsman")
+```
 
-### 第一步:读取还原方案
-读取 `%input_dir%/pipeline.json`,提取每张图的 `required_spec`、`input_from`、`img2img_config` 和 prompt,直接进入生成阶段。
-
-### 第二步:链式图生图生成(Stage 1)
-按照 pipeline.json 的 stage_1,**严格按 img_1 → img_2 → img_3 → img_4 → img_5 的顺序串行生成**,不可并行:
-
-1. **img_1(基准图)**:以 `img2img_config.base_image` 指定的参考素材为底图生成。此图确立角色基准外观(面部、发型、肤色、服装),后续所有图都以此为参考锚点
-2. **img_2 ~ img_5(链式传递)**:每张图的 `img2img_config.chain_from` 字段指向前一张图(如 img_2 的 chain_from = img_1)。生成时,**必须将 chain_from 指向的前一张图的生成结果(CDN URL 或本地路径)作为额外的参考图传给 executor**,确保角色一致性
-
-每张图的指派流程:
-- 以 `img2img_config.base_image` 指定的参考素材为底图,传入工具的 `image_url` 参数
-- 如有 `chain_from`,将前一张图的生成结果路径也传给 executor,说明"此为前序图的生成结果,请保持角色、服装、色调一致"
-- 将该图的 `required_spec`、`input_from`(转换为完整路径后)、prompt、`img2img_config` 一并传给 executor
-- **必须在任务描述中列出底图、前序结果图和所有参考素材的完整路径**
-- 指定输出路径到 `%output_dir%`
-- 根据该图的 `output_spec` 评估返回结果
-- 不满足 → 用 `continue_from` 追问同一 executor,说明问题并建议调整方向
-- 满足 → 记录生成结果路径(供下一张图的 chain_from 使用),将生成参数追加记录到 `%output_dir%/stage1_generation_log.md`,进入下一张图
-
-### 第三步:迭代优化(Stage 2)
-Stage 1 全部完成后,对每张图评估是否需要进一步优化:
-- 以 Stage 1 的生成结果作为新的底图,再次图生图迭代,增强材质、光影、细节
-- 记录到 `%output_dir%/stage2_optimization_log.md`
-
-### 第四步:跨图一致性检查(Stage 3)
-- 指派 executor 对比 5 张生成图,检查 pipeline.json stage_3 中所列的一致性要求
-- 对有问题的图,以当前结果为底图重新图生图优化
-- 记录检查报告(`%output_dir%/stage3_consistency_report.md`)
-
-### 第五步:细节修复与输出(Stage 4)
-按照 pipeline.json 的 stage_4,逐项检查并修复。以当前结果为底图,结合定向 prompt 进行图生图修复。最终成品保存至 `%output_dir%/`。记录修复报告(`%output_dir%/stage4_repair_report.md`)。
-
-### 评估原则
-在评估每个 executor 的返回结果时,重点关注 analysis.json 中的优先级:
-1. **Critical 下限点**:不满足必须重做
-2. **High 下限点**:不满足尽量修复
-3. **上限点**:尽力还原,但不影响下限点完成的情况下接受次优
+**img_2 ~ img_5(链式传递)**:每张图的 `chain_from` 字段指向前一张。指派时必须将前一张的生成结果路径传给 Craftsman,说明"此为前序图的生成结果,请保持角色、服装、色调一致"。
+
+每张图生成后,立即用 evaluate_image 评估:
+```
+evaluate_image(requirement_path="%input_dir%/pipeline.json", image_paths="%output_dir%/img_1_restored_v1.png")
+```
+- 评分 ≥ 7 → 通过,进入下一张
+- 评分 < 7 → 分析反馈,问策 Librarian 调整方案,重新派发 Craftsman(输出为 `img_X_restored_v2.png`,版本号递增,不覆盖上一版)
+
+### 第五步:迭代优化(Stage 2)
+Stage 1 全部完成后,对评分较低的图(<8 分),以 Stage 1 结果为底图再次图生图优化。
+
+### 第六步:跨图一致性检查(Stage 3)
+用 evaluate_image 的多图模式检查所有图(使用每张图的最新版本):
+```
+evaluate_image(requirement_path="%input_dir%/pipeline.json", image_paths=["%output_dir%/img_1_restored_v1.png", "%output_dir%/img_2_restored_v1.png", ...])
+```
+- 对不一致的图,以当前结果为底图重新图生图
+- 如一致性问题严重,问策 Librarian 是否需要调研新的一致性保持技巧
+
+### 第七步:细节修复与输出(Stage 4)
+按 pipeline.json 的 repair_items 逐项检查修复。最终成品保存至 `%output_dir%/`。
+
+### 知识回流
+每个阶段完成后,将有价值的经验存入 KnowHub:
+```
+upload_knowledge(data="使用 nano_banana 图生图时,strength=0.6 + 链式传递前序图效果最好...", source_type="experience")
+```
+
+## 输出文件命名规则
+
+**图片版本管理**:每次生成的图片使用版本号命名,**绝不覆盖**已有文件:
+- 首次生成:`img_X_restored_v1.png`
+- 迭代重试:`img_X_restored_v2.png`、`img_X_restored_v3.png`...
+- 最终定稿:`img_X_restored_final.png`(Stage 4 修复完成后)
+
+**生成日志**:每次生成都追加到 `%output_dir%/generation_log.md`,记录完整参数、工具、评估结果。
+
+指派 Craftsman 时,**必须指定带版本号的输出文件名**,并告知当前是第几次迭代。
+
+## 指派 Craftsman 时的要求
+
+任务描述中**必须明确包含**:
+1. **底图路径**(完整路径)
+2. **参考素材路径**(完整路径)
+3. **前序结果路径**(chain_from,如有)
+4. **素材使用方式**:底图 → image_url,参考素材 → 辅助 prompt
+5. **Prompt 和生成配置**
+6. **源信息参考**:提醒 Craftsman 读取 `%input_dir%/raw_info/` 目录下对应图片的制作表 JSON(如 `写生油画__img_1_制作表.json`)和通用文件(`创作表.md`、`图片亮点.md`)
+7. **输出路径**
+
+## 评估原则
+1. **Critical 下限点**:不满足必须重做(评分 < 6)
+2. **High 下限点**:不满足尽量修复(评分 6-7)
+3. **上限点**:尽力还原,接受次优(评分 ≥ 7)
 
 $user$
 请读取输入目录中的还原方案,开始执行完整的图像还原流程:

+ 141 - 0
examples/production_restore/research.prompt

@@ -0,0 +1,141 @@
+---
+model: sonnet-4.6
+temperature: 0.3
+---
+
+$system$
+## 角色
+你是一个调研专家,负责根据指令搜索并如实记录调研发现。
+
+**你的边界**:只负责搜索和记录,不负责制定策略。发现的工序流程、方案、案例都要如实记录,但不要自己设计工序。
+**调研结果的形式可以多样**:单个工具、工序流程、真实案例都可以。但无论哪种形式,**必须落到具体工具**——每个步骤用什么工具来执行,需要明确。
+
+## 可用工具
+### 内容搜索工具
+- `search_posts(keyword, channel, cursor="0", max_count=20)`: 搜索帖子
+  - **channel 参数**:xhs(小红书), gzh(公众号), zhihu(知乎), bili(B站), douyin(抖音), toutiao(头条), weibo(微博)
+  - 示例:`search_posts("flux 2.0", channel="xhs", max_count=20)`
+- `select_post(index)`: 查看帖子详情(需先调用 search_posts)
+  - 示例:`select_post(index=1)`
+- `youtube_search(keyword)`: 搜索 YouTube 视频
+  - 示例:`youtube_search("flux 2.0 tutorial")`
+- `youtube_detail(content_id, include_captions=True)`: 获取 YouTube 视频详情和字幕
+  - 示例:`youtube_detail("视频ID", include_captions=True)`
+- `x_search(keyword)`: 搜索 X (Twitter) 内容
+  - 示例:`x_search("flux 2.0 max")`
+- `ask_knowledge`: 搜索知识库
+- `browser-use`: 浏览器搜索(search_posts 不好用时使用)
+
+## 执行流程
+
+### 第一步:理解调研目标
+
+### 第二步:执行搜索
+
+**调研渠道策略**:
+1. **官网** - 获取官方介绍、技术规格、API 文档
+2. **内容平台** - 获取真实用例和使用经验
+   - 公众号:`search_posts(keyword="...", channel="gzh")`
+   - X:`x_search(keyword="...")`
+   - 知乎:`search_posts(keyword="...", channel="zhihu")`
+   - 小红书:`search_posts(keyword="...", channel="xhs")`
+3. **视频平台** - 获取用法教程和实操演示
+   - YouTube:`youtube_search(keyword="...")` → `youtube_detail(content_id="...")`
+   - B站:`search_posts(keyword="...", channel="bili")`
+
+**重要**:
+- **必须优先使用专用搜索工具**(search_posts、youtube_search、x_search)
+- **禁止使用 browser-use 搜索公众号、知乎、小红书、B站等已有专用工具的平台**
+- browser-use 仅用于搜索没有专用工具的平台或官网
+
+**Query 策略**(从以下角度搜索):
+1. **找官网** - "[工具名] 官网"、"[工具名] official website"
+2. **找用例** - "[工具名] 用例"、"[工具名] 使用案例"、"[工具名] tutorial"
+3. **找评测** - "[工具名] 评测"、"[工具名] review"、"[工具名] 测试"
+4. **找竞品讨论** - "[工具名] vs [竞品]"、"[工具名] 和 [竞品] 谁更强"
+5. **找排行** - "2026 年最强 [领域] 工具"、"[领域] 工具排行"
+
+**搜索优先级**:
+1. **知识库优先**:用 `ask_knowledge` 按需求关键词搜索,查看已有策略经验、工具评估、工作流总结
+2. **线上调研**:知识库结果不充分时,进行线上搜索
+
+### 第三步:反思与调整
+
+在搜索过程中,你需要主动进行反思和调整:
+每完成 1-2 轮搜索后,在继续前先评估:
+- 当前方向是否有效?是否偏离需求?
+- 结果质量如何?下一轮应该调整 query 还是换角度?
+- 可选调用 `reflect` 工具辅助判断
+根据反思结果调整后续搜索策略,直到你认为信息充分或遇到明确的阻塞。
+
+### 第四步:结束与输出
+
+**何时结束**:
+- 信息已充分覆盖调研目标
+- 搜索结果开始重复,无新信息
+- 方向不明确,需要用户指导
+
+**如何结束**:
+1. **必须**使用 `write_file` 将调研结果按照下面的 JSON 格式写入到任务指定的输出路径
+2. 输出文件路径由调用方在 task 中指定,如未指定则输出到 `%output_dir%/research_result.json`
+
+
+## 输出格式
+
+**Schema**:
+
+```jsonschema
+{
+  "搜索主题": "string — 本次搜索主题",
+  "搜索轨迹": "string — 搜索过程:尝试了哪些 query、如何调整方向等",
+  "调研发现": [
+    {
+      "名称": "string — 发现项名称(工具名/方案名/案例名)",
+      "类型": "tool | workflow | case — 单个工具 / 工序流程或整体方案 / 真实案例",
+      "来源": "string — 来源(knowledge_id / URL / 帖子链接)",
+      "核心描述": "string — 核心思路或能力描述",
+      "工序步骤": [
+        {
+          "步骤名称": "string — 步骤名称(如:生成线稿、角色一致性处理)",
+          "使用工具": "string — 该步骤使用的具体工具名称",
+          "说明": "string — 该步骤的操作说明"
+        }
+      ],
+      "工具信息": {
+        "工具名称": "string — 工具名称(类型为 tool 时必填)",
+        "仓库或链接": "string — 仓库或官网链接",
+        "输入格式": "string — 输入格式",
+        "输出格式": "string — 输出格式",
+        "最近更新": "string — 最近更新时间",
+        "能力": ["string — 工具能力"],
+        "限制": ["string — 工具限制"]
+      },
+      "外部评价": {
+        "专家或KOL推荐": ["string — 来源 + 评价摘要"],
+        "社区反馈": ["string — 来源 + 反馈摘要"],
+        "热度指标": "string — 提及次数、榜单排名、帖子热度等"
+      },
+      "使用案例": [
+        {
+          "描述": "string — 用例描述",
+          "来源链接": "string — 来源链接",
+          "相似度": "high | medium | low"
+        }
+      ],
+      "优点": ["string"],
+      "缺点": ["string"],
+      "风险": ["string"]
+    }
+  ]
+}
+```
+
+**字段说明**:
+- `工序步骤`:类型为 `workflow` 或 `case` 时填写,逐步骤记录用了什么工具
+- `工具信息`:类型为 `tool` 时必填;`workflow`/`case` 类型中,如果整体方案依赖某个核心工具(如 ComfyUI),也可填写
+- `外部评价`:尽量填写,是主 agent 选择工具时的重要参考;找不到可留空
+
+
+## 注意事项
+- `search_posts` 不好用时改用 `browser-use`
+- 如果调研过程中遇到不确定的问题,要停下来询问用户

+ 2 - 2
examples/production_restore/run.py

@@ -46,7 +46,7 @@ from agent.tools.builtin.toolhub import toolhub_health, toolhub_search, toolhub_
 from evaluate_tool import evaluate_image  # noqa: F401
 
 # 导入项目配置
-from config import RUN_CONFIG, SKILLS_DIR, TRACE_STORE_PATH, DEBUG, LOG_LEVEL, LOG_FILE, BROWSER_TYPE, HEADLESS, INPUT_DIR, OUTPUT_DIR
+from config import RUN_CONFIG, SKILLS_DIR, TRACE_STORE_PATH, DEBUG, LOG_LEVEL, LOG_FILE, BROWSER_TYPE, HEADLESS, INPUT_DIR, OUTPUT_DIR, FEATURES_DIR
 
 
 async def main():
@@ -86,7 +86,7 @@ async def main():
     print("4. 构建任务消息...")
     print(f"   - 输入目录: {INPUT_DIR}")
     print(f"   - 输出目录: {OUTPUT_DIR}")
-    messages = prompt.build_messages(input_dir=INPUT_DIR, output_dir=OUTPUT_DIR)
+    messages = prompt.build_messages(input_dir=INPUT_DIR, output_dir=OUTPUT_DIR, features_dir=FEATURES_DIR)
 
     # 5. 初始化浏览器
     browser_mode_names = {"cloud": "云浏览器", "local": "本地浏览器", "container": "容器浏览器"}

+ 0 - 107
frontend/htmlTemplate/api_data/goal_list.json

@@ -1,107 +0,0 @@
-{
-  "trace": {
-    "trace_id": "ffc7e6e8-6725-4bd3-8cd1-5c212856feff",
-    "mode": "agent",
-    "prompt_name": null,
-    "task": "[图片和特征描述已包含在 messages 中]",
-    "agent_type": "default",
-    "parent_trace_id": null,
-    "parent_goal_id": null,
-    "status": "completed",
-    "total_messages": 20,
-    "total_tokens": 145867,
-    "total_cost": 0.0,
-    "total_duration_ms": 0,
-    "last_sequence": 20,
-    "last_event_id": 25,
-    "uid": null,
-    "context": {
-      "model": "anthropic/claude-sonnet-4.5",
-      "temperature": 0.3
-    },
-    "current_goal_id": null,
-    "created_at": "2026-02-05T19:20:17.456366",
-    "completed_at": "2026-02-05T19:23:34.789135"
-  },
-  "goal_tree": {
-    "mission": "[图片和特征描述已包含在 messages 中]",
-    "goals": [
-      {
-        "id": "1",
-        "description": "调研构图特征的表示方案",
-        "reason": "需要系统性地调研、设计并输出构图特征表示方案",
-        "parent_id": null,
-        "type": "normal",
-        "status": "completed",
-        "summary": "基于计算机视觉领域的标准实践,构图特征应采用结构化+数值化的混合表示方式",
-        "sub_trace_ids": null,
-        "agent_call_mode": null,
-        "self_stats": {
-          "message_count": 6,
-          "total_tokens": 19265,
-          "total_cost": 0.0,
-          "preview": null
-        },
-        "cumulative_stats": {
-          "message_count": 6,
-          "total_tokens": 19265,
-          "total_cost": 0.0,
-          "preview": null
-        },
-        "created_at": "2026-02-05T19:20:26.177225"
-      },
-      {
-        "id": "2",
-        "description": "设计精简的特征表示结构",
-        "reason": "需要分步完成以确保质量",
-        "parent_id": null,
-        "type": "normal",
-        "status": "completed",
-        "summary": "已设计完整的特征表示结构,包含JSON schema、转换工具和示例",
-        "sub_trace_ids": null,
-        "agent_call_mode": null,
-        "self_stats": {
-          "message_count": 10,
-          "total_tokens": 92011,
-          "total_cost": 0.0,
-          "preview": null
-        },
-        "cumulative_stats": {
-          "message_count": 10,
-          "total_tokens": 92011,
-          "total_cost": 0.0,
-          "preview": null
-        },
-        "created_at": "2026-02-05T19:20:26.177233"
-      },
-      {
-        "id": "3",
-        "description": "输出最终方案文档",
-        "reason": "",
-        "parent_id": null,
-        "type": "normal",
-        "status": "pending",
-        "summary": null,
-        "sub_trace_ids": null,
-        "agent_call_mode": null,
-        "self_stats": {
-          "message_count": 2,
-          "total_tokens": 28740,
-          "total_cost": 0.0,
-          "preview": null
-        },
-        "cumulative_stats": {
-          "message_count": 2,
-          "total_tokens": 28740,
-          "total_cost": 0.0,
-          "preview": null
-        },
-        "created_at": "2026-02-05T19:20:26.177238"
-      }
-    ],
-    "current_id": null,
-    "_next_id": 1,
-    "created_at": "2026-02-05T19:20:17.456826"
-  },
-  "sub_traces": {}
-}

+ 0 - 28
frontend/htmlTemplate/api_data/trace_list.json

@@ -1,28 +0,0 @@
-{
-  "traces": [
-    {
-      "trace_id": "ffc7e6e8-6725-4bd3-8cd1-5c212856feff",
-      "mode": "agent",
-      "prompt_name": null,
-      "task": "[图片和特征描述已包含在 messages 中]",
-      "agent_type": "default",
-      "parent_trace_id": null,
-      "parent_goal_id": null,
-      "status": "completed",
-      "total_messages": 20,
-      "total_tokens": 145867,
-      "total_cost": 0.0,
-      "total_duration_ms": 0,
-      "last_sequence": 20,
-      "last_event_id": 25,
-      "uid": null,
-      "context": {
-        "model": "anthropic/claude-sonnet-4.5",
-        "temperature": 0.3
-      },
-      "current_goal_id": null,
-      "created_at": "2026-02-05T19:20:17.456366",
-      "completed_at": "2026-02-05T19:23:34.789135"
-    }
-  ]
-}

تفاوت فایلی نمایش داده نمی شود زیرا این فایل بسیار بزرگ است
+ 0 - 0
frontend/htmlTemplate/ws_data/event.jsonl


+ 0 - 28
frontend/htmlTemplate/ws_data/trace_list.json

@@ -1,28 +0,0 @@
-{
-  "traces": [
-    {
-      "trace_id": "ffc7e6e8-6725-4bd3-8cd1-5c212856feff",
-      "mode": "agent",
-      "prompt_name": null,
-      "task": "[图片和特征描述已包含在 messages 中]",
-      "agent_type": "default",
-      "parent_trace_id": null,
-      "parent_goal_id": null,
-      "status": "completed",
-      "total_messages": 20,
-      "total_tokens": 145867,
-      "total_cost": 0.0,
-      "total_duration_ms": 0,
-      "last_sequence": 20,
-      "last_event_id": 25,
-      "uid": null,
-      "context": {
-        "model": "anthropic/claude-sonnet-4.5",
-        "temperature": 0.3
-      },
-      "current_goal_id": null,
-      "created_at": "2026-02-05T19:20:17.456366",
-      "completed_at": "2026-02-05T19:23:34.789135"
-    }
-  ]
-}

+ 14 - 14
knowhub/server.py

@@ -145,24 +145,24 @@ def decrypt_content(resource_id: str, encrypted_text: str, provided_key: Optiona
         return "[ENCRYPTED]"
 
 
-def serialize_milvus_result(data):
-    """将 Milvus 返回的数据转换为可序列化的字典"""
+def to_serializable(data):
+    """通用序列化工具:把任意 Python 对象转换为 JSON 可序列化的原生类型"""
     # 基本类型直接返回
     if data is None or isinstance(data, (str, int, float, bool)):
         return data
 
     # 字典类型递归处理
     if isinstance(data, dict):
-        return {k: serialize_milvus_result(v) for k, v in data.items()}
+        return {k: to_serializable(v) for k, v in data.items()}
 
     # 列表/元组类型递归处理
     if isinstance(data, (list, tuple)):
-        return [serialize_milvus_result(item) for item in data]
+        return [to_serializable(item) for item in data]
 
     # 尝试转换为字典(对于有 to_dict 方法的对象)
     if hasattr(data, 'to_dict') and callable(getattr(data, 'to_dict')):
         try:
-            return serialize_milvus_result(data.to_dict())
+            return to_serializable(data.to_dict())
         except:
             pass
 
@@ -172,7 +172,7 @@ def serialize_milvus_result(data):
             # 强制转换为列表并递归处理
             result = []
             for item in data:
-                result.append(serialize_milvus_result(item))
+                result.append(to_serializable(item))
             return result
         except:
             pass
@@ -180,7 +180,7 @@ def serialize_milvus_result(data):
     # 尝试获取对象的属性字典
     if hasattr(data, '__dict__'):
         try:
-            return serialize_milvus_result(vars(data))
+            return to_serializable(vars(data))
         except:
             pass
 
@@ -1136,7 +1136,7 @@ async def search_knowledge_api(
             return {"results": [], "count": 0, "reranked": False}
 
         # 转换为可序列化的格式
-        serialized_candidates = [serialize_milvus_result(c) for c in candidates]
+        serialized_candidates = [to_serializable(c) for c in candidates]
 
         # 为了保证搜索的极致速度,直接返回向量召回的 top-k(跳过缓慢的 LLM 精排)
         return {"results": serialized_candidates[:top_k], "count": len(serialized_candidates[:top_k]), "reranked": False}
@@ -1279,7 +1279,7 @@ def list_knowledge(
         results = pg_store.query(filter_expr, limit=max_limit)
 
         # 转换为可序列化的格式
-        serialized_results = [serialize_milvus_result(r) for r in results]
+        serialized_results = [to_serializable(r) for r in results]
 
         # 按 created_at 降序排序(最新的在前)
         serialized_results.sort(key=lambda x: x.get('created_at', 0), reverse=True)
@@ -1316,7 +1316,7 @@ def get_all_tags():
         all_tags = set()
         for item in results:
             # 转换为标准字典
-            serialized_item = serialize_milvus_result(item)
+            serialized_item = to_serializable(item)
             tags_dict = serialized_item.get("tags", {})
             if isinstance(tags_dict, dict):
                 for key in tags_dict.keys():
@@ -1337,7 +1337,7 @@ def get_pending_knowledge(limit: int = Query(default=50, ge=1, le=200)):
             'status == "pending" or status == "processing" or status == "dedup_passed" or status == "analyzing"',
             limit=limit
         )
-        serialized = [serialize_milvus_result(r) for r in pending]
+        serialized = [to_serializable(r) for r in pending]
         return {"results": serialized, "count": len(serialized)}
     except Exception as e:
         print(f"[Pending] 错误: {e}")
@@ -1377,7 +1377,7 @@ def get_knowledge_status(knowledge_id: str):
         result = pg_store.get_by_id(knowledge_id)
         if not result:
             raise HTTPException(status_code=404, detail=f"Knowledge not found: {knowledge_id}")
-        serialized = serialize_milvus_result(result)
+        serialized = to_serializable(result)
         return {
             "id": knowledge_id,
             "status": serialized.get("status", "approved"),
@@ -1400,7 +1400,7 @@ def get_knowledge(knowledge_id: str):
         if not result:
             raise HTTPException(status_code=404, detail=f"Knowledge not found: {knowledge_id}")
 
-        return serialize_milvus_result(result)
+        return to_serializable(result)
 
     except HTTPException:
         raise
@@ -1743,7 +1743,7 @@ async def slim_knowledge(model: str = "google/gemini-2.5-flash-lite"):
         # 获取所有知识
         all_knowledge = pg_store.query('id != ""', limit=10000)
         # 转换为可序列化的格式
-        all_knowledge = [serialize_milvus_result(item) for item in all_knowledge]
+        all_knowledge = [to_serializable(item) for item in all_knowledge]
 
         if len(all_knowledge) < 2:
             return {"status": "ok", "message": f"知识库仅有 {len(all_knowledge)} 条,无需瘦身"}

BIN
log.txt


+ 0 - 10
log2.txt

@@ -1,10 +0,0 @@
-Usage:
-  Upload: python upload.py <file_path>
-  Download: python upload.py download <url> <save_path>
-
---- Running Self Test ---
-Uploading img_1_gen.png to aigc-crawler/crawler/image...
-Upload SDK Response: {'oss_object_key': 'crawler/image/img_1_gen.png', 'save_oss_timestamp': 1775658352873}
-
-Extracted URL: https://res.cybertogether.net/crawler/image/img_1_gen.png
-Downloading from https://res.cybertogether.net/crawler/image/img_1_gen.png to downloaded_dummy.png...

برخی فایل ها در این مقایسه diff نمایش داده نمی شوند زیرا تعداد فایل ها بسیار زیاد است