# Tool Agent 内部接口文档 ## 目录 1. [数据模型](#1-数据模型) 2. [工具注册表格式](#2-工具注册表格式-registryjson) 3. [容器状态表格式](#3-容器状态表格式-containersjson) 4. [任务书格式](#4-任务书格式-task_spec) 5. [内部消息格式](#5-内部消息格式-agentmessage) 6. [对外 HTTP 接口](#6-对外-http-接口) 7. [Coding Agent 工具接口](#7-coding-agent-工具接口) 8. [资源监控格式](#8-资源监控格式) 9. [配置参数](#9-配置参数) 10. [工作日志格式](#10-工作日志格式) 11. [财务记录格式](#11-财务记录格式) --- ## 1. 数据模型 ### 1.1 枚举类型 | 枚举 | 值 | 说明 | |------|-----|------| | RuntimeType | `local`, `docker`, `api`, `browser` | 运行时类型 | | SchedulingMode | `cold`, `hot`, `stateless` | 调度模式 | | ToolState | `running`, `sleeping`, `stopped`, `degraded` | 工具状态 | | ToolStatus | `active`, `inactive`, `staging`, `building` | 工具生命周期 | | MessageType | `tool_request`, `tool_ready`, `tool_error`, `health_alert` | 内部消息类型 | | ContainerStatus | `running`, `destroyed` | 容器状态 | ### 1.2 ToolMeta(工具元信息) ```json { "tool_id": "image_compress_api", "name": "图片压缩 API", "category": "cv", "description": "基于 PIL 的图片压缩服务", "input_schema": { "type": "object", "properties": { "image_path": {"type": "string"}, "quality": {"type": "integer", "minimum": 1, "maximum": 100} }, "required": ["image_path"] }, "output_schema": { "type": "object", "properties": { "compressed_size": {"type": "integer"}, "compression_ratio": {"type": "number"} } }, "stream_support": false, "runtime": { "type": "docker", "entry": "", "container_id": "25e884ca6cec...", "host_dir": "C:/Users/user/staging/image_tool", "container_dir": "/app", "host_port": 9001, "internal_port": 8080, "endpoint_path": "/api/compress", "http_method": "POST", "env": {}, "resource_limits": {"cpu": "1.0", "memory_mb": 512, "gpu": false} }, "scheduling": { "mode": "hot", "idle_timeout_s": 300, "state": "running" }, "stats": { "last_used_time": "2026-03-20T10:30:00Z", "call_count": 42, "avg_latency_ms": 125.5, "error_rate": 0.02 }, "fallback_strategy": [], "status": "active" } ``` ### 1.3 RuntimeInfo(运行时信息) | 字段 | 类型 | 默认值 | 说明 | |------|------|--------|------| | `type` | RuntimeType | `"local"` | 运行环境类型 | | `container_id` | str | `""` | Docker 容器 ID | | `host_dir` | str | `""` | 宿主机工作目录 | | `container_dir` | str | `"/app"` | 容器内工作目录 | | `host_port` | int | `0` | 宿主机映射端口(Router 调用入口) | | `internal_port` | int | `0` | 容器/进程内服务端口 | | `endpoint_path` | str | `"/"` | HTTP API 路径 | | `http_method` | str | `"POST"` | HTTP 方法 | | `env` | dict | `{}` | 环境变量 | | `resource_limits` | ResourceLimits | `{}` | 资源限制 | ### 1.4 ContainerInfo(容器信息) ```json { "container_id": "25e884ca6cecfa87e19ea737315a8773d...", "tool_id": "test_git_tool", "image": "ubuntu:22.04", "port_mapping": {"8080": 9001, "3306": 9002}, "volumes": {"C:/staging/project": "/app"}, "mem_limit": "1g", "nano_cpus": 1000000000, "use_gpu": false, "gpu_count": -1, "status": "running", "created_at": "2026-03-20T07:31:50.421101Z", "last_accessed": "2026-03-20T07:33:16.214642+00:00", "destroyed_at": null } ``` --- ## 2. 工具注册表格式 (registry.json) 路径:`data/registry.json` ```json { "tools": [ { /* ToolMeta 对象,见 1.2 */ } ], "version": "1.0" } ``` ### Registry 查询接口 **get_endpoint(tool_id)** 返回格式: Docker 类型: ```json { "type": "docker", "url": "http://localhost:9001/api/compress", "host_port": 9001, "internal_port": 8080, "container_id": "abc123...", "host_dir": "C:/staging/project", "http_method": "POST" } ``` Local 类型: ```json { "type": "local", "host_dir": "C:/tools/local/my_tool", "http_method": "POST", "endpoint_path": "/" } ``` --- ## 3. 容器状态表格式 (containers.json) 路径:`data/containers.json` ```json { "containers": [ { /* ContainerInfo 对象,见 1.4 */ } ] } ``` --- ## 4. 任务书格式 (task_spec) Router Agent 生成任务书,通过 MessageBus 发送给 Coding Agent。 ### 4.1 GitHub 项目接入任务 ```json { "type": "github_deploy", "repo_url": "https://github.com/user/project", "tool_name": "project_api", "runtime": "docker", "image": "python:3.12-slim", "ports": [8080], "description": "将该项目部署为 HTTP API 工具", "requirements": { "gpu": false, "memory_mb": 512 }, "api_spec": { "endpoint_path": "/api/run", "http_method": "POST", "input_schema": { "type": "object", "properties": { "text": {"type": "string"} } } } } ``` ### 4.2 自主编写工具任务 ```json { "type": "build_tool", "tool_name": "text_summarizer_api", "runtime": "uv", "description": "编写一个文本摘要工具,接受文本输入,返回摘要", "requirements": { "gpu": false, "memory_mb": 256, "dependencies": ["transformers", "torch"] }, "api_spec": { "endpoint_path": "/summarize", "http_method": "POST", "input_schema": { "type": "object", "properties": { "text": {"type": "string", "description": "待摘要文本"}, "max_length": {"type": "integer", "description": "摘要最大长度"} }, "required": ["text"] } } } ``` ### 4.3 工具修复任务 ```json { "type": "repair_tool", "tool_id": "image_compress_api", "error": "HTTP 503: Service Unavailable", "container_id": "abc123...", "description": "工具健康检查失败,需要诊断并修复" } ``` --- ## 5. 内部消息格式 (AgentMessage) Router Agent 与 Coding Agent 通过 `asyncio.Queue` 通信。 ```json { "type": "tool_request | tool_ready | tool_error | health_alert", "payload": { } } ``` ### 5.1 tool_request(Router → Coding) ```json { "type": "tool_request", "payload": { "task_spec": "{ /* 任务书 JSON,见第 4 节 */ }", "task_id": "550e8400-e29b-41d4-a716-446655440000", "callback_url": "http://caller/callback" } } ``` ### 5.2 tool_ready(Coding → Router) ```json { "type": "tool_ready", "payload": { "tool_id": "image_compress_api", "result": "部署成功,工具已注册", "url": "http://localhost:9001/api/compress", "task_id": "550e8400-..." } } ``` ### 5.3 tool_error(Coding → Router) ```json { "type": "tool_error", "payload": { "tool_id": "failed_tool", "error": "依赖安装失败:torch 需要 CUDA 但未检测到 GPU", "task_id": "550e8400-..." } } ``` ### 5.4 health_alert(Router → Coding) ```json { "type": "health_alert", "payload": { "tool_id": "image_compress_api", "container_id": "abc123...", "error": "HTTP 503", "last_healthy": "2026-03-20T10:00:00Z" } } ``` --- ## 6. 对外 HTTP 接口 基础地址:`http://localhost:8001` ### GET /health ```json // Response {"status": "ok"} ``` ### GET /tools 返回工具目录(按类别)。 ```json // Response { "tools": [ { "tool_id": "image_compress_api", "name": "图片压缩 API", "category": "cv", "description": "基于 PIL 的图片压缩", "status": "active" } ] } ``` ### GET /tools/{tool_id}/schema ```json // Response { "tool_id": "image_compress_api", "input_schema": { /* JSON Schema */ }, "output_schema": { /* JSON Schema */ } } ``` ### POST /tools/{tool_id}/invoke ```json // Request { "params": {"image_path": "/path/to/img.jpg", "quality": 85}, "stream": false } // Response(非流式) { "status": "success", "result": {"compressed_size": 256000, "compression_ratio": 0.25}, "error": null } // Response(流式 SSE,Accept: text/event-stream) data: {"chunk": "处理中...", "done": false} data: {"chunk": "完成", "done": true} ``` ### POST /tools/request 提交新工具需求(异步)。 ```json // Request { "description": "需要一个图片压缩工具", "callback_url": "http://caller/callback" } // Response { "task_id": "550e8400-...", "status": "pending" } ``` ### GET /tasks/{task_id}/status ```json // Response { "task_id": "550e8400-...", "status": "completed", "result": {"tool_id": "image_compress_api", "url": "http://localhost:9001/api/compress"} } ``` --- ## 7. Coding Agent 工具接口 Coding Agent 通过 claude_agent_sdk 暴露以下 10 个工具: ### Docker 环境 | 工具 | 必填参数 | 可选参数 | 返回 | |------|----------|----------|------| | `create_docker_env` | `image` | `mem_limit`, `nano_cpus`, `ports`, `volumes`, `use_gpu` | `container_id`, `port_mapping` | | `run_in_docker` | `container_id`, `command` | `is_background`, `timeout` | `exit_code`, `stdout`, `stderr` 或 `log_file` | | `rebuild_docker_ports` | `container_id`, `ports` | `mem_limit`, `nano_cpus` | `new_container_id`, `port_mapping` | | `destroy_docker_env` | `container_id` | — | `status`, `message` | ### 本地 uv 环境 | 工具 | 必填参数 | 可选参数 | 返回 | |------|----------|----------|------| | `create_uv_project` | `name` | `python_version` | `project_dir` | | `run_in_uv` | `project_dir`, `command` | `timeout` | `exit_code`, `stdout`, `stderr` | | `uv_add_dependency` | `project_dir`, `package` | `dev` | `status`, `message` | ### 文件操作 | 工具 | 必填参数 | 返回 | |------|----------|------| | `write_file` | `path`, `content` | `status`, `path`, `size` | | `read_file` | `path` | `status`, `path`, `content` | ### 注册 | 工具 | 必填参数 | 可选参数 | 返回 | |------|----------|----------|------| | `register_tool` | `tool_id`, `name`, `description`, `runtime_type`, `host_port`, `internal_port` | `category`, `input_schema`, `output_schema`, `container_id`, `host_dir`, `endpoint_path`, `http_method` | `status`, `tool_id`, `url` | --- ## 8. 资源监控格式 ### SystemInfo(系统概览) ```json { "cpu_count": 16, "cpu_percent": 11.1, "memory_total_mb": 15653, "memory_available_mb": 2606, "memory_percent": 83.4, "disk_total_gb": 924.3, "disk_free_gb": 327.3 } ``` ### ResourceUsage(单工具资源占用) ```json { "cpu_cores": 1.0, "memory_mb": 512.0, "gpu_memory_mb": 0.0 } ``` ### 资源分配检查规则 - CPU:已分配 + 新请求 ≤ 系统总核数 - 内存:已分配 + 新请求 ≤ 系统总内存 × 80%(保留 20% 安全余量) --- ## 9. 配置参数 ### Settings(环境变量前缀:`TOOL_AGENT_`) | 参数 | 类型 | 默认值 | 说明 | |------|------|--------|------| | `fastapi_port` | int | `8001` | 对外 HTTP 端口 | | `mcp_port` | int | `8001` | MCP Server 端口 | | `docker_port_start` | int | `9001` | Docker 端口起始 | | `docker_base_image` | str | `"agent-sandbox:latest"` | 默认基础镜像 | | `docker_mem_limit` | str | `"1g"` | 默认容器内存 | | `docker_nano_cpus` | int | `1000000000` | 默认 CPU(1 核) | | `docker_ttl_seconds` | int | `1800` | 容器自动清理 TTL | | `cold_tool_idle_timeout_s` | int | `300` | 冷工具空闲超时 | | `hot_tool_max_containers` | int | `5` | 最大热工具容器数 | | `eviction_policy` | str | `"lru"` | 置换策略 | | `monthly_limit_usd` | float | `100.0` | 月预算上限 | | `single_tx_limit_usd` | float | `20.0` | 单笔上限 | | `require_approval_above_usd` | float | `10.0` | 需审批阈值 | | `health_check_interval_s` | int | `60` | 健康检查间隔 | ### 运行时配置覆盖 (data/config.json) ```json { "cold_tool_idle_timeout_s": 300, "hot_tool_max_containers": 5, "eviction_policy": "lru", "budget": { "monthly_limit_usd": 100, "single_tx_limit_usd": 20, "require_approval_above_usd": 10, "spent_this_month_usd": 0 } } ``` --- ## 10. 工作日志格式 ### LocalRunner 命令日志 (last_run.log) 路径:`{project_dir}/last_run.log` ``` Command: python main.py Exit Code: 0 --- STDOUT --- Server started on port 8080 --- STDERR --- WARNING: Using development server ``` ### Coding Agent 执行日志(stdout) ``` 2026-03-20 15:09:32 [tool_agent.tool.agent] INFO: [CodingAgent] Starting task: 部署 flask 项目... 2026-03-20 15:09:35 [tool_agent.tool.agent] INFO: [TOOL_USE] create_docker_env | {"image":"python:3.12-slim","ports":[8080]} 2026-03-20 15:09:40 [tool_agent.tool.agent] INFO: [TEXT] 正在创建 Docker 环境... 2026-03-20 15:10:15 [tool_agent.tool.agent] INFO: [TOOL_USE] register_tool | {"tool_id":"flask_api",...} 2026-03-20 15:10:16 [tool_agent.tool.agent] INFO: [DONE] duration=44000ms 2026-03-20 15:10:16 [tool_agent.tool.agent] INFO: [COST] $0.12 ``` --- ## 11. 财务记录格式 路径:`data/billing_log.json` ```json { "transactions": [ { "provider": "openai", "amount_usd": 5.0, "description": "API Key 充值" } ] } ``` ### 预算检查规则 | 条件 | 行为 | |------|------| | `amount ≤ single_tx_limit_usd` | Agent 自主完成 | | `amount > require_approval_above_usd` | 暂停,通知用户审批 | | `spent_this_month + amount > monthly_limit_usd` | 拒绝,通知预算超限 |