Automation and Scale: Headless -p Into CI, Parallel Sessions and Worktrees, Writer/Reviewer Dual Sessions, Adversarial Review, Common Failure Modes; a 20-Line Minimal Agent SDK Agent
Turn Claude Code from a terminal sidekick into one stage of a pipeline: run it headless with -p in CI and parse the JSON result, run parallel sessions with worktrees, use adversarial review as a backstop, then write a 20-line minimal agent with the Agent SDK.
今日目标
- 能用 claude -p 跑一条无人值守的任务,并解析 --output-format json 的结果判断成败
- 能用 worktree 并行开多个会话,并设计一次 Writer / Reviewer 双会话的对抗式审查
- 能用 Agent SDK 写出 20 行的最小 agent,并说出五种常见失败模式的对策
前四天你一直坐在搭档旁边。今天要做的是离开座位:让它在没人看着的时候也能干活、几个它同时干活、互相检查对方的活。读完做完实验,回到顶部勾掉三条目标,这门课就结束了。
小白版讲解
无头模式:claude -p 让搭档变成一条命令
一个能干的搭档最终会遇到这样的需求:「每个 PR 提上来,你先过一遍有没有拼写错误」「每晚把今天的报错日志归个类」。这些活不需要坐在旁边聊,只需要一条可以被脚本调用的命令。
claude -p "提示词" 就是这条命令——无头模式(headless,-p 是 print 的缩写)。它不进入交互界面,把提示词跑完、把结果打到标准输出、退出;退出码 0 表示成功,非 0 表示失败,所以 shell 脚本可以直接用它分支。它还能像任何 Unix 工具一样接管道:
# 一次性提问
claude -p "这个项目是做什么的?"
# 管道喂数据:把构建日志喂进去,把解释写到文件
cat build-error.txt | claude -p "简要说明这个构建错误的根因" > explain.txt
# 当 typo linter 用:只看 diff,不需要 Bash 权限
git diff main | claude -p "你是拼写检查器。逐条报告 diff 里的拼写错误,格式 文件:行号,其余什么都不要输出。"第三条值得多看一眼:把 diff 通过管道喂进去,Claude 就不需要任何工具权限,纯靠读输入回答——这是无人值守场景里最安全的形态。CI 里跑还要加 --bare:跳过 hooks、skills、插件、MCP、CLAUDE.md 的自动发现,让每台机器上的结果一致、启动更快,也避开了 D4 结尾那个隐患——陌生仓库里别人写的 hook 在你的 CI runner 上跑起来。官方文档明确说 --bare 会成为将来 -p 的默认值。注意 --bare 不读你的订阅登录,得设 ANTHROPIC_API_KEY。
解析 JSON 结果:result、session_id、成本与轮数
脚本要判断「成功了没有、花了多少钱」,光看一段文字不够。加上 --output-format json,输出变成一个 JSON 对象,几个关键字段:
{
"type": "result",
"subtype": "success",
"is_error": false,
"result": "发现 3 处拼写错误:…",
"session_id": "3f9c…",
"num_turns": 4,
"duration_ms": 18234,
"total_cost_usd": 0.0421,
"usage": { "input_tokens": 12034, "output_tokens": 812, "cache_read_input_tokens": 9800 }
}result 是最终回答;is_error 与 subtype 告诉你成败;num_turns 是它跑了几轮「想、调工具、看结果」;total_cost_usd 是这次的估算成本(客户端估算,和账单可能有出入,但足够做预算控制);session_id 可以用 --resume 接着聊。还有一个更进一步的用法:加 --json-schema 给一份 JSON Schema,结果会多一个 structured_output 字段,严格符合你的 schema——D1 讲的结构化输出,在 CLI 层面又出现了一次。
需要逐事件处理就用 --output-format stream-json --verbose:每行一个 JSON 事件,第一行是 system/init(含模型、工具、加载的插件与 MCP server 状态——CI 可以用它检查该加载的东西是否真加载了),最后一行是同样形状的 result。写脚本时用 jq -r '.result' 取文本、jq '.total_cost_usd' 取成本,或者像今天的实验那样用一个 20 行的 TS / Python 包装器:调 claude -p、解析 JSON、超预算或出错就非零退出。
进 CI 前的三道锁:权限、预算、可复现
把搭档一个人留在办公室过夜之前,你得锁三道门。
第一道:权限。 无人值守时没有人回答「允许吗」,所以要么提前说清允许什么,要么把会问的动作全部拒掉。--allowedTools 用白名单放行具体工具:"Read,Grep" 是只读审查;"Bash(git diff *),Bash(git log *)" 只放行几条 git 命令——注意 * 前面的空格,没有空格的 git diff* 会把 git diff-index 也放进来。--permission-mode 定基线:dontAsk 是最严的 CI 模式,不在白名单里的一律拒绝;acceptEdits 允许改文件但命令仍受限;auto 让分类器模型替你审。-p 模式的起始档位在所有计划上都是 Manual,所以一定要显式传。再配 --permission-prompts none,凡是本来要问人的动作直接拒掉并告诉模型别重试。
第二道:预算。 --max-turns N 限制轮数,--max-budget-usd 0.50 限制花费,到了就停并报错。没有这两条,一个卡在循环里的任务能跑掉你一个月的额度。
第三道:可复现。 --bare 关掉本机配置的自动发现;--no-session-persistence 不落盘会话;模型、提示词、system prompt 追加(--append-system-prompt)全部写在脚本里进版本控制。合起来是这样一条命令:
gh pr diff "$PR" | claude --bare -p \
--append-system-prompt "你是一名安全审查员,只报告漏洞与风险,不评论风格。" \
--permission-mode dontAsk --permission-prompts none \
--max-turns 6 --max-budget-usd 0.50 \
--output-format json > review.json
jq -r '.result' review.json | gh pr comment "$PR" --body-file -并行会话与 worktree:几件事同时做又不互相踩
一个搭档不够用了,你想同时开三个:一个修 bug、一个写新功能、一个整理文档。问题是三个人同时改同一个目录的文件,会互相覆盖。
Git 的 worktree 解决这个问题:同一个仓库、多个独立的工作目录、各在自己的分支上。Claude Code 把它做成了一个开关:claude --worktree feature-auth(或 -w)会在 .claude/worktrees/feature-auth/ 下建一个新的 worktree、切到 worktree-feature-auth 分支,然后在里面启动会话。另开一个终端再来一条 claude --worktree fix-login,两个会话就在互不干扰的目录里各干各的。会话结束时它会检查这个 worktree 有没有未提交的改动:干净就自动删掉,有活就问你保留还是删除。
两个实用细节:把 .claude/worktrees/ 加进 .gitignore;worktree 是全新的检出,.env 这类被 gitignore 的文件不会自动带过去,在项目根放一个 .worktreeinclude 文件列出要复制的文件名就行。subagent 也能用 worktree 隔离——在 .claude/agents/<name>.md 的 frontmatter 里写 isolation: worktree,这个 subagent 每次都在自己的临时 worktree 里改文件。
并行的另一种形态不是「几件不同的事」,而是「同一件事几个人干、然后互相看」——这就是下一节。
Writer / Reviewer 与对抗式审查:让另一个上下文来挑错
让写代码的人自己审自己的代码,效果通常不好——不是态度问题,是他脑子里还装着「我为什么这么写」的全部理由,很难跳出来。对 Claude 也一样:一个刚写完实现的会话,上下文里全是它的推理过程,让它审自己,它倾向于确认而不是质疑。
解法是换一个没有这些记忆的上下文来审。最简单的形态是两个终端:
| 会话 A(Writer) | 会话 B(Reviewer) |
|---|---|
| 「给 POST /todos 加输入校验和测试」 | |
| 「审查 @src/routes/todos.ts 的校验实现。找边界情况、和现有中间件风格的不一致、遗漏的测试。只报告影响正确性的问题。」 | |
| 「这是审查意见:[会话 B 的输出]。逐条处理。」 |
会话 B 从零开始读代码,看到的只有 diff 和你给的标准,不知道 A 为什么这么写——所以它挑的是代码本身的毛病。同样的思路可以用在测试上:一个会话写测试,另一个会话写实现去通过它。
不想开两个终端,就用 D4 学的 subagent 做对抗式审查:「用一个 subagent 对照 PLAN.md 审查这次 diff:每条需求是否实现、列出的边界情况有没有测试、有没有改动超出任务范围。只报告差距,不评论风格。」subagent 的独立上下文天然就是那个「没有记忆的审查者」。Claude Code 还内置了 /code-review,在一个新的 subagent 里审当前 diff 找 bug。
一个必须知道的副作用:你让审查者找问题,它就一定会找出问题来——哪怕代码没毛病,它也会报几条,因为那是它的任务。照单全收会导致过度工程:多余的抽象层、防御不存在的情况的代码、测不可能发生的用例。所以审查提示词里要写清「只报告影响正确性或明确需求的差距,其余视为可选」,然后由你来判断哪些值得改。
五种常见失败模式与对策
五天下来,你踩过的坑大概逃不出这五种。官方 best practices 页把它们列成了清单,我按「怎么识别、怎么解」再过一遍:
- 大杂烩会话。 修 A 的时候顺手问了 B,又回头改 A,窗口里全是不相关的东西,回答质量明显下降。解:任务之间
/clear。 - 反复纠正。 同一个错纠正两次它还错,因为失败的尝试全留在上下文里继续污染。解:两次不中就
/clear,用一条吸收了教训的更好的提示词重开。 - 超长的 CLAUDE.md。 规则太多,重要的被淹没,它「不听话」。解:删到不能再删;它已经默认会做的删掉,必须百分之百的换成 hook。
- 信任但不验证。 它给出一个看起来合理的实现,边界情况没处理,你没发现就合了。解:永远给它一个可验证的检查——测试、脚本、截图;验证不了的东西不要上线。
- 无边界的探索。 「帮我调查一下 X」没有范围,它读了几百个文件把窗口填满。解:把调查范围说具体,或者交给 subagent 在独立上下文里做。
你会发现五条里有三条是在讲同一件事:上下文窗口是最稀缺的资源。这就是这门课从 D2 起一直重复的那句话。
Agent SDK:20 行拿到 Claude Code 同一套循环
最后一个话题把这门课接回 D2。claude -p 已经很像一个函数调用了,但它是命令行——要自己拼参数、自己解析 JSON、自己处理进程。如果你想在自己的程序里用上 Claude Code 的整套能力(读写文件、跑命令、搜代码、hooks、subagent、权限、会话),有一个正式的入口:Claude Agent SDK。
它和 D2 用的 @anthropic-ai/sdk / anthropic 是两个不同的东西。D2 的 SDK 是 Messages API 的客户端:你发消息、它回消息,工具要你自己定义、循环要你自己写。Agent SDK 是把 Claude Code 打包成的库:内置文件与 Bash 工具、完整的 agent 循环、上下文管理、权限系统,你只给一句任务和一组选项。20 行拿到一个会改代码的 agent:
import { query } from '@anthropic-ai/claude-agent-sdk'
// query 返回一个异步迭代器:每个消息是一段推理、一次工具调用、或最终结果
for await (const message of query({
prompt: '给 src/routes/todos.ts 的 POST /todos 补 zod 输入校验,并在 test/ 下写对应的 vitest 用例,跑到全绿。',
options: {
allowedTools: ['Read', 'Edit', 'Glob', 'Grep', 'Bash'], // 预授权的工具
permissionMode: 'acceptEdits', // 改文件不问;Bash 仍受 allowedTools 约束
maxTurns: 20, // 预算:最多 20 轮
systemPrompt: '你是一名资深 Node.js 后端工程师。只改 src/ 与 test/。', // D1 的名片
},
})) {
if (message.type === 'assistant') {
for (const block of message.message.content) {
if ('text' in block) console.log(block.text) // 它的推理
else if ('name' in block) console.log(`→ 工具:${block.name}`) // 它在调什么工具
}
} else if (message.type === 'result') {
console.log(`结束:${message.subtype}`) // success / error_max_turns …
}
}import asyncio
from claude_agent_sdk import AssistantMessage, ClaudeAgentOptions, ResultMessage, query
async def main() -> None:
# query 返回一个异步迭代器:每个消息是一段推理、一次工具调用、或最终结果
async for message in query(
prompt="给 app/routes/todos.py 的 POST /todos 补 pydantic 输入校验,并在 tests/ 下写对应的 pytest 用例,跑到全绿。",
options=ClaudeAgentOptions(
allowed_tools=["Read", "Edit", "Glob", "Grep", "Bash"], # 预授权的工具
permission_mode="acceptEdits", # 改文件不问;Bash 仍受 allowed_tools 约束
max_turns=20, # 预算:最多 20 轮
system_prompt="你是一名资深 Python 后端工程师。只改 app/ 与 tests/。", # D1 的名片
),
):
if isinstance(message, AssistantMessage):
for block in message.content:
if hasattr(block, "text"):
print(block.text) # 它的推理
elif hasattr(block, "name"):
print(f"→ 工具:{block.name}") # 它在调什么工具
elif isinstance(message, ResultMessage):
print(f"结束:{message.subtype}") # success / error_max_turns …
asyncio.run(main())分工由此清楚:要一个「问答 / 抽取 / 你自己定义工具」的模型调用,用 Messages API(D2);要一个「在文件系统里干活」的 agent,用 Agent SDK(今天);只是想在 shell 脚本里调一下,用 claude -p。 三者底下是同一个模型,差别在于谁提供循环和工具。
这门课到此结束。你现在会交代(D1)、会喂材料(D2)、会写手册和用计划(D3)、会装门禁和说明书(D4)、会让它无人值守并互相检查(D5)。下一步有两个方向:想看同一件事在 OpenAI 那边怎么做——Codex 与 Agents SDK 怎么完成同一个 TODO API 任务、两边差在哪——去对位课 《Codex 与 OpenAI Agents SDK 高效使用》,它的 D5 会用今天的任务做双工具实测对比。想往深处走,D4 里一笔带过的两样东西各有一门七天的课:mcp-7days(把工具接进任何 Agent)和 agent-skills-7days(把经验做成可复用能力),都在「即将上线」。
源码导读
动手实验
实验是一个 TS 包装器:接一个 diff(默认 git diff main),拼出带三道锁的 claude -p 命令,解析 JSON,超预算或出错就非零退出。MOCK=1 时不真的调 claude,而是返回几份固定的 JSON 场景,所以没有装 Claude Code 的读者也能把解析与判断逻辑写完、跑通。solution/ci.py 是同一件事的 Python 版。
- 在 starter 目录 pnpm install 后跑 MOCK=1 pnpm start,看到它打印一份「尚未解析」的占位输出,确认骨架能跑。
- 完成练习 1:在 buildArgs 里拼出 claude -p 的参数——bare、output-format json、permission-mode dontAsk、max-turns、max-budget-usd、append-system-prompt。
- 完成练习 2:在 parseResult 里从 JSON 取 is_error、subtype、num_turns、total_cost_usd、result,并判定成败与是否超预算。
- 完成练习 3:让三种 MOCK_SCENARIO(success / over-budget / error)分别得到正确的退出码与日志,再故意把预算改到很小,看 over-budget 分支。
- 有 claude 命令的话去掉 MOCK 真跑一次,看 review.json 里的字段;然后读一遍 .github/workflows/claude-review.yml,确认密钥来自 secrets、权限只给 pull-requests: write。
面试题
今天 3 道题在下方题库区,侧重 headless 模式进 CI 的权限与成本控制、对抗式审查为什么有效、Agent SDK 与直接调 API 的分工。展开后先看「分析过程」再看要点——照着推导练,比背要点管用。标注「国内高频 / 海外高频」方便按目标市场取舍。
检查清单与明日预告
- 能用 claude -p 跑一条无人值守的任务,并解析 --output-format json 的结果判断成败
- 能用 worktree 并行开多个会话,并设计一次 Writer / Reviewer 双会话的对抗式审查
- 能用 Agent SDK 写出 20 行的最小 agent,并说出五种常见失败模式的对策
- 能说清 Messages API、Agent SDK、claude -p 三者的分工
- 实验的 5 条验收标准全部通过
- 3 道面试题不看要点也能答出至少 2 道
这门课没有明天了,但有下一门。同一个示例任务,去 《Codex 与 OpenAI Agents SDK 高效使用》 看 OpenAI 这边怎么做、两边的工作方式差在哪——不是比谁更聪明,是比怎么带。想把 D4 里的 MCP 和 skill 各学成一门手艺,mcp-7days 与 agent-skills-7days 即将上线。五天里反复出现的那句话请带走:上下文窗口是最稀缺的资源,而可验证的检查是用好 Agent 的分水岭。
Interview questions
What three things must you control when running claude -p in CI, with which flags, and why is --bare recommended?把 claude -p 放进 CI 时要控制哪三件事?具体用哪些参数?为什么推荐加 --bare?
Common in ChinaCommon overseasIntermediate#headless#ci#permissionsHow to reason about it · think before answering
- This tests awareness of unattended risk. 'Add an API key and run it' reads as no production experience; the interviewer wants the three locks — permissions, budget, reproducibility — each with its flags.
- Permissions: nobody answers 'allow?' unattended, so either allowlist tools (--allowedTools "Read,Grep" or "Bash(git diff *)", mind the space before *) or set a baseline (--permission-mode dontAsk denies anything outside the allowlist; acceptEdits permits file edits), plus --permission-prompts none to deny anything that would have prompted. -p starts in Manual on every plan, so pass the mode explicitly.
- Budget: --max-turns caps turns, --max-budget-usd caps spend; both stop with an error. Without them a looping task can drain your quota; with a Stop hook, allow enough turns or the run ends on 'max turns' rather than 'tests pass'.
- Reproducibility: --bare skips auto-discovery of hooks, skills, plugins, MCP, and CLAUDE.md so every runner behaves the same and starts faster — and it is a security measure, since a cloned repo's hooks would otherwise run silently under -p (no trust dialog). Add --no-session-persistence and keep the prompt and --append-system-prompt in version control.
- Follow-ups: authentication under --bare — it ignores subscription login, so set ANTHROPIC_API_KEY. Judging success — is_error, subtype, and total_cost_usd from --output-format json; fail the job on a non-zero exit.
分析过程 · 先想清楚再作答
- 这题考无人值守的风险意识。答「加个 API key 就能跑」会被判没上过线;面试官想听权限、预算、可复现三道锁,以及每道锁对应的参数。
- 权限:无人值守时没人回答「允许吗」,所以要么白名单放行(--allowedTools "Read,Grep" 或 "Bash(git diff *)",注意 * 前的空格),要么定基线(--permission-mode dontAsk 一律拒绝白名单外的动作;acceptEdits 允许改文件),再加 --permission-prompts none 把本来要问人的动作直接拒掉。-p 模式的起始档位是 Manual,必须显式传。
- 预算:--max-turns 限轮数、--max-budget-usd 限花费,到了就停并报错。没有它们,一个卡在循环里的任务能耗尽额度;有 Stop hook 时要给足轮数,否则会以「轮数耗尽」而不是「测试通过」结束。
- 可复现:--bare 跳过 hooks、skills、插件、MCP、CLAUDE.md 的自动发现,让每台 runner 结果一致、启动更快;同时也是安全措施——不加它,clone 下来的陌生仓库里别人写的 hook 会在 -p 下无提示地执行(无头模式没有信任对话框)。配合 --no-session-persistence 不落盘,提示词与 --append-system-prompt 进版本控制。
- 可预期的追问:--bare 之后怎么认证?它不读订阅登录,必须设 ANTHROPIC_API_KEY;再追问怎么判断成败——--output-format json 的 is_error / subtype / total_cost_usd,退出码非零脚本就 fail。
Key points
- Permissions: --allowedTools allowlist plus --permission-mode dontAsk or acceptEdits and --permission-prompts none; -p defaults to Manual
- Budget: --max-turns and --max-budget-usd stop the run; leave headroom for Stop hooks
- Reproducibility: --bare skips local auto-discovery and keeps a cloned repo's hooks from running in CI; --no-session-persistence
- --bare requires ANTHROPIC_API_KEY; judge success from is_error in the JSON and the exit code
答题要点
- 权限:--allowedTools 白名单 + --permission-mode dontAsk / acceptEdits + --permission-prompts none;-p 默认 Manual 必须显式传
- 预算:--max-turns 与 --max-budget-usd,到了就停;有 Stop hook 时给足轮数
- 可复现:--bare 跳过本机配置自动发现,也防陌生仓库的 hook 在 CI 上跑;--no-session-persistence
- --bare 需要 ANTHROPIC_API_KEY;成败看 --output-format json 的 is_error 与退出码
Why is a Writer / Reviewer two-session review more effective than self-review in one session, and should you fix everything the reviewer reports?为什么 Writer / Reviewer 双会话的审查比同一个会话自查更有效?审查者报出来的问题要全改吗?
Common in ChinaCommon overseasIntermediate#review#subagentsHow to reason about it · think before answering
- The point is the why and the second half. 'A second pair of eyes' is common sense; explain the role of context and the side effect of review.
- Chain: the session that wrote the code has a context full of its own reasoning; asked to review, it tends to confirm rather than challenge — a context bias, not an attitude problem. A Reviewer in a fresh context sees only the diff and your criteria, not the Writer's reasons, so it critiques the code itself. Same principle as non-author code review among humans.
- Three shapes: two terminals passing output by hand; a subagent doing adversarial review (its isolated context is the memoryless reviewer, and findings land back in the main session for immediate fixing); the built-in /code-review that reviews the current diff in a fresh subagent. The idea also inverts: one session writes tests, another writes the implementation to pass them.
- The second half separates candidates: don't fix everything. A reviewer told to find gaps will report some even in sound code; accepting all of it leads to over-engineering — extra abstraction, defensive code for impossible cases, tests for unreachable paths. Tell it to flag only gaps affecting correctness or stated requirements, and let a human decide.
- Follow-ups: what does the Reviewer need? The diff, the plan or requirements, explicit criteria; feeding it the Writer's reasoning weakens independence. Can it be automated? Yes — run the Reviewer via -p and post results to the PR.
分析过程 · 先想清楚再作答
- 题眼是「为什么」和后半句。答「多一双眼睛」是常识;要说清上下文在这里扮演的角色,以及审查的副作用。
- 推导:写完实现的会话,上下文里装满了「我为什么这么写」的推理;让它自审,它倾向于确认而不是质疑——这不是态度问题,是上下文偏置。Reviewer 换一个全新的上下文,只看到 diff 和你给的标准,不知道 Writer 的理由,所以挑的是代码本身的毛病。这和人类 code review 要求「非作者审」是同一个道理。
- 形态有三种:两个终端手动传递输出;一个 subagent 做对抗式审查(独立上下文天然就是无记忆的审查者,而且结果直接回到主会话可以立刻修);内置的 /code-review 在新 subagent 里审当前 diff。同样的思路可以反过来用:一个会话写测试,另一个写实现去通过。
- 后半句是区分度:不要全改。被要求找问题的审查者一定会报出问题来,哪怕代码没毛病;照单全收会导致过度工程——多余抽象、防御不存在情况的代码、测不可能发生的用例。审查提示词里要写「只报告影响正确性或明确需求的差距,其余视为可选」,最终由人判断。
- 可预期的追问:Reviewer 需要什么输入?diff、计划或需求(PLAN.md)、明确的判据;给它 Writer 的推理过程反而会削弱独立性。再追问「能不能自动化」——能,-p 模式里一条命令跑 Reviewer,结果贴回 PR。
Key points
- Self-review suffers context bias: a session full of its own reasoning confirms rather than challenges
- A Reviewer in a fresh context sees only the diff and criteria, so it critiques the code itself
- Shapes: two terminals, an adversarial subagent, built-in /code-review; invert for test-first
- Don't fix everything: reviewers always report something; limit findings to correctness and stated requirements
答题要点
- 自审受上下文偏置:装满自己推理的会话倾向于确认而非质疑
- Reviewer 用全新上下文,只看 diff 与判据,挑的是代码本身的毛病
- 形态:双终端、subagent 对抗式审查、内置 /code-review;反向可用于测试先行
- 不要全改:审查者必报问题,照单全收导致过度工程;限定只报影响正确性的差距
When do you use the Claude Agent SDK versus the Messages API directly, and how do both relate to claude -p?Agent SDK 和直接调 Messages API 各适合什么场景?它们和 claude -p 是什么关系?
Common in ChinaCommon overseasBasic#agent-sdk#messages-apiHow to reason about it · think before answering
- This tests layered understanding: all three entry points share one model; the difference is who supplies the loop and the tools. 'The SDK is higher level' says nothing.
- Messages API (@anthropic-ai/sdk / anthropic): one request, one response; you define tools, write the loop, manage context. Fits Q&A, extraction, classification, structured output, cited document Q&A, and custom agents where you want full control of the loop.
- Agent SDK (@anthropic-ai/claude-agent-sdk / claude-agent-sdk): Claude Code packaged as a library — built-in Read/Edit/Bash/Glob/Grep, the full agent loop, context management, permissions, hooks, subagents, sessions. You pass a task and options (allowedTools, permissionMode, maxTurns, systemPrompt) and it works in the filesystem. Fits embedding a code-editing agent in your own program.
- claude -p: the CLI form of the same Claude Code capabilities, for shell scripts and CI; the Agent SDK is its library form and the docs present them together. One-line rule: model call → API; filesystem agent → Agent SDK; quick scripted call → -p.
- Production nuance: with the Agent SDK you still own deployment (it supplies the harness, not hosting); auth is ANTHROPIC_API_KEY, and claude.ai subscription login can't be offered to third-party products. Follow-up: is the Agent SDK the same as the Messages API tool runner? No — the tool runner loops over tools you define and has no built-in file tools.
分析过程 · 先想清楚再作答
- 这题考的是分层认知:三个入口底下是同一个模型,差别在于「谁提供循环和工具」。答成「SDK 更高级」没有信息量。
- Messages API(@anthropic-ai/sdk / anthropic):一次请求一次响应,工具由你定义、循环由你写、上下文由你管。适合问答、抽取、分类、结构化输出、带引用的文档问答,以及你想完全掌控循环的自定义 Agent。
- Agent SDK(@anthropic-ai/claude-agent-sdk / claude-agent-sdk):把 Claude Code 打包成库——内置 Read / Edit / Bash / Glob / Grep 等工具、完整的 agent 循环、上下文管理、权限系统、hooks、subagent、会话。你给一句任务和一组选项(allowedTools、permissionMode、maxTurns、systemPrompt),它在文件系统里干活。适合「在自己的程序里嵌一个会改代码的 agent」。
- claude -p:同一套 Claude Code 能力的命令行形态,适合 shell 脚本与 CI;Agent SDK 就是它的库形态,官方文档把两者放在同一页讲。判据一句话:要模型调用用 API,要文件系统里的 agent 用 Agent SDK,只想在脚本里调一下用 -p。
- 生产视角:Agent SDK 的部署仍是你自己的(它只提供循环,不提供托管),密钥走 ANTHROPIC_API_KEY,不能复用 claude.ai 的订阅登录给第三方产品。可预期的追问:Agent SDK 和 Messages API 里的 tool runner 是不是一回事?不是——tool runner 只帮你跑「你自己定义的工具」的循环,没有内置文件工具。
Key points
- Messages API: request/response, you write tools and the loop; for Q&A, extraction, structured output, custom agents
- Agent SDK: Claude Code as a library with built-in file/Bash tools, loop, permissions, hooks; for embedding a code-editing agent
- claude -p is the CLI form of the same capabilities, for scripts and CI
- You still own deployment; auth via ANTHROPIC_API_KEY; the tool runner is not the Agent SDK
答题要点
- Messages API:一问一答,工具与循环自己写;适合问答、抽取、结构化输出、自定义 Agent
- Agent SDK:Claude Code 的库形态,内置文件与 Bash 工具、循环、权限、hooks;适合嵌入会改代码的 agent
- claude -p 是同一能力的命令行形态,适合脚本与 CI
- 部署仍归自己,认证用 ANTHROPIC_API_KEY;tool runner 不是 Agent SDK
Comments
Sign in to join the discussion
No comments yet — be the first.