拆解开源编程 Agent:Codex、OpenCode、goose
这一节读源码。三个项目都是开源的终端或桌面编程 Agent:OpenAI 的 Codex CLI(Rust,Apache-2.0)、OpenCode(TypeScript,MIT,读的是 2.3.0 的新架构)、goose(Rust,Apache-2.0,1.60.0,现在是 Linux 基金会旗下 AAIF 的项目)。我们在 2026 年 11 月 20 日克隆了它们,下面的文件路径和行号都对应那一版。
你会发现:核心循环和你写的几乎一样,差别都在“刹车”和“工程细节”上。
1. 循环:都是“还要工具就继续”
Codex 的循环(codex-rs/core/src/session/turn.rs)用一个变量判断要不要再来一轮:
let needs_follow_up = model_needs_follow_up || has_pending_input;模型要调工具、或者用户中途插了新话,就继续;否则 break。这和 myagent 的 if not msg.tool_calls: return 是同一件事。
OpenCode 叫 needsContinuation(这一步有本地执行的工具调用就为真),goose 叫 ends_turn(最后一条是没有工具请求的回复就结束)。
差别在刹车:
| 步数上限 | 到上限怎么办 | |
|---|---|---|
| myagent | 12 步 | 直接停,回一句“超过最大步数” |
| OpenCode | 默认不限,可以给每个 Agent 设 steps | 关掉工具(toolChoice: "none"),加一句“已到最大步数”的提示,逼模型用文字总结目前的进展 |
| goose | GOOSE_MAX_TURNS 默认 1000 | 让出控制权,问用户要不要继续 |
| Codex | 我们在源码里没有找到步数上限 | — |
OpenCode 的做法比我们的好:直接截断会丢掉进展,让模型在最后一步写总结,用户至少知道做到了哪里。
2. 权限:从 y/N 到“规则表 + 审查 + 沙箱”
查一查它们的权限……
点一个看看。
goose 的 smart_approve 和上一节 Grok Bot 的审查模型、OpenClaw 的 auto 档,是同一个思路:能自动判断的自动判断,拿不准的再问人。
3. 压缩:思路和你的 compact() 一样,多了三件事
| 何时开始压缩 | |
|---|---|
| myagent | 对话超过 24000 字 |
| Codex | 上下文窗口的 90% |
| OpenCode | 窗口减去 max(15%, 16k token) |
| goose | 窗口的 0.8 |
| OpenClaw | 约 75% 开始维护 |
生产级的做法多了三件事:
- 按 token 算,而不是按字数。
- 摘要写成“交接单”。 Codex 的压缩提示词第一句(
codex-rs/prompts/templates/compact/prompt.md):
You are performing a CONTEXT CHECKPOINT COMPACTION. Create a handoff summary for another LLM that will resume the task.
Include:
- Current progress and key decisions made
- Important context, constraints, or user preferences
- What remains to be done (clear next steps)
- Any critical data, examples, or references needed to continueOpenCode 也要求摘要“交给另一个 Agent 接着做”,并规定了目标、决定、下一步等固定小节。
- 不拆工具调用和结果。 和我们 compact() 里那个 while 循环一样,几家都有处理。
4. 说明文件和技能:AGENTS.md 和 load_skill
几乎都在读 AGENTS.md(写给 Agent 看的项目说明):
- Codex:从 git 根目录到当前目录逐层读、拼起来,总共上限 32 KiB;同一层有
AGENTS.override.md时优先读它。 - OpenCode:找 AGENTS.md,同一目录没有时退回读 CLAUDE.md。
- goose:读
.goosehints和 AGENTS.md。
技能方面,goose 的工具名和我们一模一样,就叫 load_skill(crates/oi-kit-agent/src/skills/operation.rs):
fn load_skill_tool() -> Tool {
Tool::new(
LOAD_SKILL_TOOL_NAME,
"Load a skill's full content into your context so you can follow its instructions.\n\n\
Skills are listed in your system instructions. When you need to use one, \
load it first to get the detailed instructions.",
schema_for_type::<LoadSkillParams>(),
)
}你第二章写的,就是业界的主流做法。
5. MCP:所有人的公共插座
三个项目都支持 MCP:Codex 在 config.toml 的 [mcp_servers.名字] 下配置;OpenCode 在 opencode.json 里配 local / remote;goose 最彻底,所有工具都走 MCP,每个扩展就是一个 MCP 客户端,工具名加上“扩展名__工具名”前缀。
动手:给 myagent 照着加三样
- 1?
- 2?
- 3?
按先后顺序,一个一个点。
第一样的参考写法:
agents_md = Path("AGENTS.md")
if agents_md.exists():
SYSTEM += "\n\n项目说明(AGENTS.md):\n" + agents_md.read_text(encoding="utf-8")[:8000]考考你读完三个项目的源码,Agent 的核心循环和你写的 myagent 相比如何?
检查一下
- 我能说出三个项目各自怎么处理“到达步数上限”
- 我能说出它们的压缩阈值,以及摘要为什么写成“交接单”
- 我给 myagent 加上了至少一样学来的功能
回到 常见问题,或者去 OpenClaw 课、Grok Bot 课 把这些设计用起来。