# CommonAgent **Repository Path**: zhengxuhong/common-agent ## Basic Information - **Project Name**: CommonAgent - **Description**: 智能体框架,haerness流程。 - **Primary Language**: Unknown - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2026-11-09 - **Last Updated**: 2026-11-22 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # common-agent(通用智能体框架)v10 > **一个原子模块:定义一个智能体 + 一个循环把它跑起来。** > 计划是工具,审查是 hook,编排是使用者的事。 --- ## 一、结构 ``` README.md 主文档 docs/ 决策历史(给人看) examples/ 示例能力包(业务参考) benchmarks/ 真机/审计脚本 tests/ 测试 src/task_agent/ ├── spec.py AgentOptions / Tool / Limits / LlmConfig / DEFAULT_* ├── agent_loop.py AgentLoop + run_agent(唯一执行逻辑) ├── agent.py Agent 实例(任务号 + 历史 + 压缩 + 持久化) ├── session.py Session(历史 / todos / 压缩摘要 / 归档) ├── store.py MemoryStore / SqliteStore ├── context.py 上下文压缩(照抄 DSH 参数) ├── hooks.py ReviewHook / ToolGateHook ├── preflight.py 机械预检(0 token,批内全或无) ├── tools.py 7 个基础工具 + todo_write + make_* ├── session_tools.py session_query(查历史) ├── delegate_tools.py subagent / skill(派发 + 按需加载) ├── descriptor.py 可识别对象的元数据(Anthropic 标准字段) ├── registry.py 工具/技能/子智能体共用注册表 ├── recognize.py 识别(把完整描述符给模型选) ├── retrieval.py Tool RAG(选配,默认关) ├── schema.py JSON Schema 子集校验 + 从回复抠 JSON ├── specloader.py YAML/JSON 规格 + ${ENV} 展开 ├── logging_setup.py loguru(pythonw 安全探测) └── cli.py run / validate / tools / init ``` **没有编排层。** 计划用 `todo_write` 工具,审查用 `ReviewHook`, 串联是使用者写几行代码的事。 --- ## 二、一个循环覆盖所有情况 ``` tools=[] 模型没有可调工具 → 1 次调用就回答 → 纯问答 tools=[真实工具] 模型自己决定调不调、调几次 → ReAct tools=[todo_write] 模型自己写/改计划清单 → 计划能力 ``` **不需要「纯问答分支」和「工具分支」两套代码**,也不需要 `max_steps` 之外的开关。 --- ## 三、使用 ### 1. 一次性任务 ```python from task_agent import AgentOptions, LlmConfig, builtin_tools, run_agent options = AgentOptions( name="watchdog", system_prompt="你是系统看门狗。读日志找异常,按严重程度排序。", llm=LlmConfig(base_url="https://api.deepseek.com", model="deepseek-chat", api_key="sk-..."), tools=builtin_tools(root=Path("C:/logs")), limits=Limits(max_steps=8), ) result = run_agent(options, "检查最近一小时的日志") ``` ### 2. 连续对话(任务号 + 持久化) ```python from task_agent import Agent, SqliteStore agent = Agent(options, session_id="task-001", store=SqliteStore("sessions.db")) agent.run("分析日志") agent.run("那第二段呢") # 自动带历史 agent.resume() # 跨进程恢复 ``` ### 3. 计划能力(加一个工具) ```python from task_agent import todo_write_tool options = AgentOptions(..., tools=[*builtin_tools(), todo_write_tool()]) # 用 Agent(...) 执行时,会话通过运行时上下文自动注入(DSH 的 ctx 做法) agent = Agent(options, session_id="task-1") agent.run("...") # 清单写进 session.todos,跨 run 保留 ``` 模型会自己写清单、标进度、更新状态 —— **计划存在对话历史里**,不是框架对象。 清单同时存进 `session.todos`,跨 run 保留。 ### 4. 审查(加一个 hook) ```python from task_agent import ReviewHook reviewer = AgentOptions( name="reviewer", system_prompt="你是审查者。检查回答有没有真的回应问题、有没有编造。", llm=cheap_llm, ) # 只审最终答案 AgentOptions(..., hooks=[ReviewHook(reviewer)]) # **每步强制审查**(工具执行后就审) AgentOptions(..., hooks=[ReviewHook(reviewer, mode="each_step")]) ``` **「每步强制审查」不需要另一套编排器 —— 换个 mode 就有。** ### 5. 工具闸门(高危操作前拦一道) ```python from task_agent import ToolGateHook gate = ToolGateHook( reviewer, only_for=["run_command", "write_file"], # 只拦高风险工具 max_denies=2, docs={"run_command": "会改变系统状态,执行前要确认命令是只读的"}, ) ``` 模型要调工具时,闸门会拿**完整文档**(description + 参数 schema + 补充说明) 判断这批调用是否合理;不合理就整批不执行,理由返回给模型自己改。 ### 7. 用户自己的能力包(工具 / 技能 / 子智能体) 内置能力是框架给的;**用户自己的东西按「能力包」组织**,用的时候指过来(可以多个): ```python from task_agent import load_workspaces, builtin_tools ws = load_workspaces( "C:/packs/alert", # 你的告警能力包 "D:/team/tools", # 团队共享 "./local-skills", # 项目本地 ) options = AgentOptions( name="my-agent", system_prompt="...", llm=llm, tools=[*builtin_tools(root=Path(".")), *ws.tool_list()], ) ``` **一行装进配置**(会自动合并工具 + 把技能清单注入系统提示): ```python options = ws.attach(AgentOptions( name="my-agent", system_prompt="你是助手。", llm=llm, tools=builtin_tools(root=Path(".")), )) ``` > 为什么不能只靠 `skill` 工具的描述:工具描述是「调用时才看」的, > 简单技能(用通用工具也能凑合做)模型不会想到去点它。 > 所以 `attach()` 把技能/子智能体的**完整描述符**(做什么 / 适用 / 不适用) > 直接写进系统提示(DSH 的 durable catalog 做法)。 > > 代价:每个技能约 80~120 token 常驻。换来模型真的知道有这些能力。 > 不常驻的只有正文(SKILL.md 全文 / 子智能体配置),按需加载。 **能力包结构**(有哪个目录就发现哪个,都没有就把目录当工具目录): ``` my-pack/ ├── PACK.md ← 【给人看】这个包是什么、有什么、怎么用(不进模型上下文) ├── tools/*.py ← 模块级 TOOLS = [Tool(...), ...] ├── skills/<名字>/SKILL.md ← frontmatter: name/description/when_to_use/when_not_to_use └── agents/<名字>.yaml ← 就是普通的规格文件(和 spec.yaml 同格式) ``` **模板在 `examples/capability-pack/`**(含 PACK.md、2 个技能、1 个子智能体、2 个工具)。 #### 一个入口工具管「一类」能力,不是每个技能一个工具 | 发现到 | `tool_list()` 给模型加的入口 | |---|---| | N 个工具 | N 个工具(直接调用) | | N 个技能 | **1 个** `skill` 工具(描述里列出全部技能,参数指定加载哪个) | | N 个子智能体 | **1 个** `subagent` 工具(描述里列出全部,参数指定派谁) | 所以「多个技能」能跑通 —— 模型看到 `skill` 工具的描述里有全部技能名, 调用时传 `name="greet"` 或 `name="format-report"`。 **真机验证**:2 个技能时模型正确选了 `greet`;子智能体 `researcher` 被正确派发, 自己调了 5 次工具后带回带行号依据的结论。 #### 允许模型创建子智能体(默认关闭) ```python ws.tool_list(allow_subagent_creation=False) # 默认:只能派发已配置好的 ws.tool_list(allow_subagent_creation=True) # 允许模型自己造新的 ``` 创建出来的子智能体注册进同一个 registry,之后可被 `subagent` 派发; 传 `agents_dir=` 还会同时存成 YAML(跨进程保留)。 #### 业务示例:看门狗能力包 `examples/watchdog-pack/` 演示「**业务工具放能力包,不进框架**」: | 文件 | 内容 | |---|---| | `tools/log_tools.py` | `tail_log`(读尾部,不读全文)、`count_pattern`(按正则统计) | | `skills/log-triage/SKILL.md` | 日志排查流程(先统计→再定位→后结论) | | `agents/log-analyst.yaml` | 日志分析子智能体 | | `PACK.md` | 给人看的集中说明 | #### 付费接口示例:DeepSeek 附属工具 `examples/deepseek-tools/` 封装 DeepSeek 官方全家桶独立接口: Search / Fetch / OCR / ASR / TTS。 - **默认全关**(按次计费,和 token 费用分开算);用项目 `.env` 打开: `DEEPSEEK_TOOLS_ENABLED=1` + `DEEPSEEK_SEARCH_ENABLED=1` 等 - 带**调用次数/费用上限**(`DEEPSEEK_TOOLS_MAX_CALLS` / `..._MAX_COST_CNY`) - **读项目环境的 `.env`**,不读功能包自己的 env;包内只放 `.env.example` 模板 - 调用后向 Session 记 `deepseek/tool_usage` 事件(费用可审计) ### 6. YAML 规格 ```yaml name: log-analyzer system_prompt: | 你是日志分析助手。 llm: base_url: https://api.deepseek.com model: deepseek-chat api_key: ${DEEPSEEK_API_KEY} tools: [now, read_file, list_dir, glob_files] root: C:/logs limits: max_steps: 10 max_read_bytes: 100000 # 上下文压缩(全部可配;不写就用默认) compaction: threshold_ratio: 0.8 # 触发比例 retain_ratio: 0.16 # 最近历史逐字保留比例 headroom_tokens: 65536 # 预留空间 # prune_chars: 8000 # 剪枝阈值(**默认 None = 不剪枝**,要剪才填) auto: true # 默认开启 context_window: 64000 # 模型上下文窗口 max_tokens: 32000 output_schema: # 结构化输出 type: object properties: verdict: {type: string, enum: [pass, fail]} required: [verdict] ``` --- ## 四、上下文压缩(默认开启,照抄 DSH) ``` threshold = floor(min(W × 0.8, W − O − 65536)) 保留最近 0.16 × (W − O) 逐字不动 ``` 四步:估算 → **剪枝(0 token)** → 摘要(1 次调用)→ 溢出时最大化削减重试 - ❌ system prompt 永不压缩 - ❌ 不拆散工具调用和它的结果 - ✅ 被压的消息进 `session.archived`,`session_query` 仍能查到 - ✅ 摘要失败不抛异常(fail-safe) - ✅ 手动压缩:`agent.compact(force=True)` - ✅ **用真实 token 打底**:每次跑完记下 API 给的 `prompt_tokens`, 下次压缩判断 = `真实基准 + 之后新增消息的估算`(只估增量,误差小) - ✅ 系数 `session.token_ratio` 只用来校准**增量**(跟着会话持久化) --- ## 五、工具预检(两层) | 层 | 做什么 | 成本 | 默认 | |---|---|---|---| | **机械预检** | 工具存在?必填参数齐?类型对?枚举合法? | **0 token** | **开** | | **语义闸门** | 拿完整文档判断这批调用是否合理 | 1 次调用 | 关 | **批内全或无**:一批调用有一个不合法,整批都不执行 —— 不会「执行一半」。 --- ## 六、内置工具 | id | 名称 | 只读 | |---|---|---| | `read_file` / `list_dir` / `glob_files` / `now` / `http_get` | 基础 | ✅ | | **`file_stat`** | **元信息(大小/行数/时间),不读内容** | ✅ | | **`grep_files`** | **按内容搜,返回文件名+行号+该行** | ✅ | | `write_file` / `run_command` | 会改变状态 | ❌ | | `todo_write` | 计划清单(模型自己写/改) | ❌ | | `session_query` | 查历史 | ✅ | | `subagent` | **入口工具**:列出/派发全部子智能体 | ❌ | | `skill` | **入口工具**:列出/加载任意技能(按需) | ✅ | **后四个不在 `builtin_tools` 里** —— 要用自己加。 --- ## 七、描述符(对齐 Anthropic 最佳实践) ```python Descriptor( id="log_review", name="日志审查", kind="skill", description="...(3-4 句,≥40 字,校验)", when_to_use="...", # Anthropic 明确要求 when_not_to_use="...", # Anthropic 明确要求 inputs="...", outputs="...", examples=[...], ) ``` 三类共用:工具 / 技能 / 子智能体。识别 = 把完整描述符给模型选。 --- ## 八、真机看门狗实测(真实 Windows 日志) **场景**:扫 `C:\Windows\Logs`(521 个条目),找错误、归类、判严重程度。 ### 第一次跑:**52 万 token** | 原因 | 数值 | |---|---| | `max_read_bytes=200_000` 让每次读文件返回 20 万字符 | 约 5 万 token/文件 | | **没设 `max_tool_result_chars`** → 原文全进上下文 | 6 个文件 = 30 万 token | | **每轮都重发全部历史** | 8 轮累计 → 52 万 | ### 修复后:**10.9 万 token(降 79%)** ```python limits = Limits( max_read_bytes=100_000, max_tool_result_chars=6_000, # ← 关键:限制喂回模型的字符数 max_total_tokens=150_000, # ← 关键:单次 run 预算,超了立停 ) ``` **效果**:还多抓了错误(7 条 vs 8 条但质量更高,正确判出 1 条 medium)。 ### 多样化任务审计(`benchmarks/audit_run.py`) 8 个不同类别的任务,**限制故意放宽**(max_steps=25、不截断),每步细节落盘到 `benchmarks/traces/`: | 任务 | 类别 | tokens | 工具次数 | |---|---|---|---| | 01-pure-qa | 纯问答 | 113 | 0 | | 02-single-tool | 单工具 | 6,099 | 2 | | 03-multi-step | 多步分析 | **59,244 → 6,381** | 21 | | 04-structured | 结构化输出 | 2,341 | 1 | | 05-recovery | 错误恢复(文件不存在) | 15,792 | 7 | | 06-plan | 计划任务 | **118,867 → 13,294** | 24 | | 07-long-context | 长内容理解 | 10,237 | 1 | | 08-chat | 多轮对话 | 576 | 0 | **读 trace 发现的真问题**:03/06 里模型为了「数行数」**并行读了 20 个文件全文** —— 框架没有「不读内容拿元信息」的工具。 **修复**:新增两个**通用**工具(不是业务代码): | 工具 | 作用 | |---|---| | `file_stat` | 大小 / 行数 / 修改时间,**不返回内容** | | `grep_files` | 正则搜内容,返回「文件 + 行号 + 该行」 | **效果:两个分析类任务 token 降 89%。** ### 多跑几个目录(同一套 limits) | 目录 | tokens | 结果 | |---|---|---| | PITR | 20,946 | ✅ 2 条 medium(日志被截断 / .etl 不可读) | | DISM | 9,718 | ✅ 0 条,诚实说明「只看开头 80KB」 | | NetSetup / waasmedic / PLUG / WindowsUpdate | 8K–21K | ✅ 正确报告「只有 .etl 二进制,无法解析」 | **发现的新问题**:PITR/DISM 一开始 `max_steps=6` 用尽就失败 —— 模型还在探索。 修复:**步数用尽后再给一次「只输出答案」的机会**(去掉工具收尾), `stop_reason="final_after_max_steps"`。修复后两个目录都成功了。 ### 框架为此加的三个东西 | 新增 | 作用 | |---|---| | `Limits.max_total_tokens` | 超预算即停,`stop_reason="token_budget"` | | `Result.warnings` | 工具结果 >10 万字符且没设上限时**主动提醒**(不截断,但让你知道代价) | ```python r = run_agent(options, "扫日志") if r.warnings: print(r.warnings) # ["工具 read_file 返回了 200,000 字符,且没设 max_tool_result_chars…"] ``` --- ## 九、审计发现的真实问题(已修) | # | 问题 | 严重度 | |---|---|---| | 1 | **`todo_write` 和 `session.todos` 根本没连上** —— 文档说跨 run 持久化,实际清单存在工具闭包里 | **高** | | 2 | `hook_errors()` 死代码,且「hook 异常被吞」无测试 | 中 | | 3 | `AgentOptions.compaction` 生效路径无测试 | 中 | | 4 | `dump_example` 不展示 compaction | 低 | | 5 | CLI 不显示压缩配置 | 低 | | 6 | 三份文档过时 | 低 | **教训**:v1 的老毛病(文档承诺 ≠ 实际接线)又犯了一次。现在每个「A 产出 X → B 消费 X」 的连接都有端到端测试。 --- ## 十、状态 ``` 源码 7,515 行 测试 7,321 行 / 660 passed 模块 27 个 .py(含 discovery 发现机制,全部有测试) 依赖 llm-client + pyyaml + loguru ruff All checks passed mypy Success: no issues found in 20 source files ``` --- ## 十一、默认值一览 | 项 | 默认 | |---|---| | `Limits` 所有字段 | **None(不限)** | | `max_tokens` | 32000 | | `temperature` | None(不传) | | `context_window` | 64000 | | 上下文压缩 | **开启**(0.8 / 0.16 / 65536) | | 机械预检 | **开启** | | 审查 hook | **关闭**(`mode="before_final"` 或 `"each_step"`,你自己选) | | 工具闸门 | **关闭** | | Tool RAG | **关闭** | | `todo_write` / `session_query` / `subagent` / `skill` | 需手动加入 tools | | **创建子智能体** | **关闭**(`allow_subagent_creation=False`) | --- ## 十一之二、迭代守则(重要) **业务代码不许进 `src/`。** 这条由测试守死(`tests/test_framework_purity.py`)。 | 想加的东西 | 放哪里 | |---|---| | 通用工具(读写文件、搜索、HTTP…) | `src/task_agent/tools.py` | | 某个业务场景的工具(日志/告警/数据库…) | 能力包 `tools/` | | 某个业务的流程说明 | 能力包 `skills/<名>/SKILL.md` | | 某个业务的专用智能体 | 能力包 `agents/<名>.yaml` | | 能力包的说明(给人看) | `PACK.md` | 示例:`examples/watchdog-pack/`(日志)、`examples/capability-pack/`(通用模板)、`examples/deepseek-tools/`(DeepSeek 官方搜索/抓取/OCR/ASR/TTS,付费接口带开关与预算)。 **判断标准**:这个能力换一个业务场景还用得上吗? - 用得上 → 框架(`src/`) - 用不上 → 能力包(用户目录 / `examples/`) --- ## 十三、计划模式(对齐 DSH 的 `/plan`) ```python options = AgentOptions(..., plan_mode=True) ``` 开启后自动: 1. 工具只留**只读工具 + todo_write**(写/执行工具全部挡掉) 2. 系统提示追加「计划模式」说明 3. 模型写完计划调用 `exit_plan_mode` 提交 → `stop_reason="plan_ready"` ```python result = run_agent(options, "重构前先出个方案") if result.stop_reason == "plan_ready": print(result.data["plan"]) # 确认后按计划执行 ``` ## 十四、协作式取消 ```python options = AgentOptions(..., should_stop=lambda: user_clicked_stop) ``` 每轮开始前检查;返回 True 立即停止,`stop_reason="cancelled"`,已产出的内容保留。 ## 十五、重复工具提醒(机械策略,0 token) 连续 3 次用**完全相同参数**调用同一工具时,自动注入提醒让模型换方法。 ```python limits = Limits(repeat_tool_limit=3) # 默认 3;None = 关闭 ``` ## 十六、执行器(executor) 默认执行器 = 原生语义(一次一个工具、线程池超时、异常转错误结果)。 要换调度方式(PTC / 并发 / 审计),实现一个 `execute` 塞进去: ```python class MyExecutor: def execute(self, calls, *, limits): # calls: [(Tool | None, tool_id, raw_args), ...] return [(value, ok, timed_out), ...] options = AgentOptions(..., executor=MyExecutor()) ``` `NativeExecutor` 就是默认实现,可以直接看源码对照。 ## 十七、workflow 并行 ```python workflow_tool(registry, parallel=True) ``` 按 `depends_on` 分层,同一层(依赖都满足)的步骤**并发执行**。 默认串行;并行时注意 agent 步骤各自带自己的配置(不共享会话上下文)。 ## 十八、子智能体控制面 ```python ws.tool_list(with_subagent_control=True) ``` 工具 `subagent_control`:`start`(返回 child_id)/ `list` / `status` / `cancel`。 `cancel` 通过 `should_stop` 协作式停止。 **持久化**(可选):`subagent_control_tool(registry, state_file="children.json")`, 进程重启后之前 `running` 的会标记为 `lost`(后台线程确实不在了,不假装还活着)。 ## 十九、消息事件化(事件是持久化的事实源) ``` session.events → message/append、messages/replace、todo/write、 tool/call、compaction、turn/*、goal/* ``` - `Agent.resume()` 会用事件**重建 messages**(老存档没有 message 事件则保留原样) - 压缩后写一条 `messages/replace`(整段历史被重写) - 于是 messages 和 todos 一样,都是事件的**投影** ## 二十、spill 清理策略 spill 文件写在 `%TEMP%\task_agent_spill\`,每次写入后自动清理: 只保留最近 **100 个**、且不超过 **7 天**。 ```python from task_agent import cleanup_spill_files cleanup_spill_files(keep=50, max_age_days=3) # 手动维护 ``` ## 二十一、代码质量标准 以「简洁优美」为目标,并由 `tests/test_code_quality.py` 守死: | 规则 | 上限 | |---|---| | 单个模块 | 800 行 | | 单个函数(含方法) | 340 行 | | TODO/FIXME/XXX/HACK | 0 | | 模块 docstring | 必需 | | 公开函数 docstring | 尽量全(阈值 12 个例外) | **模块职责边界**(加代码前先想清楚放哪): ``` agent_loop.py 只负责循环:调模型 -> 工具结果 -> 回调模型 tool_runtime.py 工具执行细节:解析/调用/超时/序列化/spill plan_mode.py 计划模式 tools.py 通用工具入口(具体工具在其他 *_tools.py) todo_tools.py 计划工具 discovery.py 能力包发现 orchestration.py workflow / ralph / goal session.py 会话 + 事件日志 + 投影 context.py 压缩 ```