hanafubuki-agent

exec --json 事件

hanafubuki-agent exec --json 输出的事件流:外层字段、每种事件及其字段、顺序和兼容性规则。

hanafubuki-agent exec --json 在标准输出上每行写一个 JSON 对象,即回合中按顺序发生的每个事件。exec 自己的提示写到标准错误,所以标准输出可以直接交给 jq 或其他程序。

外层字段

{
  "sessionId": 2,
  "turnId": 1,
  "generation": 1,
  "sequence": 4,
  "activity": null,
  "kind": { "type": "assistant_text_delta", "messageId": 2, "delta": "Hel" }
}
字段类型含义
sessionId数字会话 ID
turnId数字或 null回合 ID。属于会话而不属于回合的事件为 null:session_title_updated、session_goal_updated、execution_progress、compaction_updated
generation数字会话的代次
sequence数字事件在会话中的序号,从 1 开始递增
activity对象或 null这个事件改变的活动(回合正在做什么,用于状态行),见活动
kind对象发生了什么。kind.type 是事件种类,其余字段取决于种类

所有字段名都是 camelCase,种类名和枚举值是 snake_case。值为空的字段写作 null,不会省略。所有 ID 都是数字;时间是 Unix 毫秒数。

事件种类

下面的示例只写出 kind 对象。

回合

kind.type字段说明
turn_startedrole回合开始,在会话的角色中:角色名,default 时为 null
sampling_startedstep第 step 次请求模型(一个回合可能多次请求:每次工具调用后再请求一次)
response_startedresponseIdProvider 开始返回响应,responseId 是 Provider 的响应 ID(字符串)
turn_completedfinalAnswerMessageId回合完成;最终回答的消息 ID,没有询问模型的回合为 null
turn_cancelledreason回合被取消,reason 是 user_interrupted
turn_failedreason、message回合失败,message 是给人看的说明

turn_failed 的 reason 取值:

reason含义
model_request_retries_exhausted模型请求重试次数用尽(例如无法连接)
model_stream_retries_exhausted模型响应流中断,重试次数用尽
model_errorProvider 返回了错误
model_protocolProvider 的响应不符合协议
budget_exceeded超出了 Agent 对回合的限制
deadline_exceeded超出了回合的时限
context_window_exceeded压缩上下文后仍然超出模型的上下文窗口
internal_failureAgent 内部错误

思考

{"type":"reasoning_started","reasoningId":3,"samplingStep":1}
{"type":"reasoning_delta","reasoningId":3,"delta":"**Checking the tests**\n\n"}
{"type":"reasoning_completed","reasoningId":3,"durationMillis":1200}
kind.type字段说明
reasoning_startedreasoningId、samplingStep模型开始一段思考
reasoning_deltareasoningId、delta思考内容的下一段,Markdown 格式。按原样拼接即可:新的摘要段落以分隔的空行开头
reasoning_completedreasoningId、durationMillis这段思考结束,用时多少毫秒
reasoning_updatedreasoning回合的思考计时:samplingStep、phase(not_observed、thinking、completed)、activeSince、stepCompletedMillis、turnCompletedMillis、lastCompletedAt

思考内容是 Provider 发送的摘要或原始思考文本;Provider 什么也不发送时,一段思考可能没有任何 reasoning_delta。reasoningId 在会话中唯一。

消息

kind.type字段说明
assistant_message_startedmessageId、phase、samplingStep模型开始一条消息。phase 是 commentary(过程说明)、final_answer(最终回答)或 null
assistant_text_deltamessageId、delta消息的下一段文本
assistant_message_completedmessageId、phase消息完成
proposed_plan_started、proposed_plan_delta、proposed_plan_completedmessageId,以及 samplingStep 或 delta计划模式下模型提出的计划。exec 的会话总是默认模式,不会出现

工具

{
  "type": "tool_started",
  "callId": "call_1",
  "name": "exec_command",
  "presentation": { "action": "exec_command", "subject": "cargo test" }
}
{
  "type": "execution_progress",
  "callId": "call_1",
  "update": {
    "type": "execution_output",
    "executionId": 4,
    "generation": 1,
    "text": "running 12 tests\n",
    "nextOffset": 17,
    "truncated": false
  }
}
kind.type字段说明
tool_startedcallId、name、presentation一次工具调用开始。presentation 有 action(标识符)和 subject:调用作用的对象,由工具的呈现器从参数中读出(命令行、路径、查询;取第一行,最多 200 个字符),或为 null
tool_execution_finishedcallId、isError工具执行结束
tool_completedcallId、isError工具的结果已经记入历史
execution_progresscallId、update进程的实时进展,turnId 为 null。callId 是报告它的工具调用:启动该进程的 exec_command,包括该调用已经返回、进程在后台继续运行之后;Agent 自己报告的(在轮次之外停止的后台进程、上一次运行留下的进程)为 null

execution_progress 的 update.type 取值:

update.type字段
execution_startedexecutionId、generation、action、status
execution_outputexecutionId、generation、text、nextOffset、truncated
execution_statusexecutionId、generation、status、exitCode、cleanupRequired
execution_disposedexecutionId、generation
execution_cleanup_failedexecutionId、generation

status 是 starting、running、exited、failed、cancelled 或 timed_out;exitCode 是整数或 null。

调用结束后显示的内容(界面排版后的输出)不在事件流中:模型读到的输出在会话的历史里,宿主向门面询问显示内容(工具呈现器)。

text 是终端文本,应按顺序渲染:管道的输出是进程写出的原样,包括转义序列;伪终端的输出是它屏幕上显示的样子,各行以换行结束,一行中带颜色或属性的每一段放在它的 SGR 序列(ESC [ … m)和一个重置 ESC [0m 之间,上一条更新留下的未完成的一行在 \r 和 ESC [2K 之后重新写出。无论哪种情况,历史中模型读到的工具结果都是纯文本。

审批

kind.type字段说明
approval_requestedrequest一次工具调用需要审批
approval_resolvedrequestId、resolution审批有了结果
permission_review_startedreviewId、callId、action、startedAtauto-review 模式下自动审查开始
permission_review_completedreviewId、callId、actionSummary、status、assessment、startedAt、completedAt自动审查结束

request 的字段:

字段含义
requestId审批 ID(数字)
operationId对应工具调用的 callId
action要审批的操作,见下表
requestedAtMs、expiresAtMs请求时间和过期时间
offersAllowForSession是否可以回答“本会话内都允许”

action 的字段:kind(操作类型)、risk(low、medium、high、critical)、origin({"type":"user"}、{"type":"model"} 或来自 Skill 的 {"type":"skill",...})、summary(摘要)、digest(操作的哈希)和 details(null 或带 type 的详细信息,例如命令的 program、argv、cwd);模型请求在沙箱之外运行的命令还有 sandboxEscalation,即 {"justification":"…"}(模型没有给出理由时 justification 为 null),其他情况下没有这个字段。kind 的取值:

command_execution、shell_execution、code_execution、interactive_execution、file_read、file_write、file_patch、file_move、file_delete、mcp_tool_call、plugin_tool_call、skill_management、domain_mutation。

resolution 的字段:requestId、decision、source、resolvedAtMs。decision 是 allow_once、allow_for_session、deny、aborted 或 timed_out;在这个事件中,source 是 user(由 exec 按 --approve 回答),或者在超时和中止时是 system。

自动审查的 status 是 reviewing、approved、denied、timed_out、failed 或 aborted。assessment 只在 approved 和 denied 时有值,包含 riskLevel、userAuthorization(explicit、implicit、absent、conflicting)、outcome(allow、deny)和 rationale。

提问与计划

kind.type字段说明
user_input_requestedrequest模型提问:requestId、callId、questions(每个有 id、header、question、options),选项有 id、label、description
user_input_resolvedresolution回答:requestId、answers(每个有 questionId、optionId)、resolvedAt
task_plan_updatedplan模型更新了任务计划:explanation 和 plan(每步有 step 和 status:pending、in_progress、completed)

会话与上下文

kind.type字段说明
session_title_updatedtitle会话标题:value 和 source(automatic 或 user)。turnId 为 null
session_goal_updatedgoal会话的目标变化了(模型设置或更新了它,或计入了用量):objective、status(active、paused、blocked、budget_limited、complete)、origin(user 或 model)、tokenBudget 和 timeBudgetSeconds(设置了时)、tokensUsed、timeUsedSeconds、createdAt 和 updatedAt(毫秒);清除时为 null。turnId 为 null
history_committedstartIndex、itemCount、usage一批记录写入了历史。usage 只在模型响应的提交上有值:lastResponseInputTokens、lastResponseOutputTokens、cumulativeInputTokens、cumulativeOutputTokens、contextWindowTokens、contextConsumedTokens、source(provider_reported 或 estimated),以及 Provider 的提示缓存:lastResponseCacheReadTokens 与 lastResponseCacheWriteTokens(响应未报告时为 null)、cumulativeCacheReadTokens、cumulativeCacheWriteTokens 和 cacheReportingResponses(报告了其中之一的响应数)。各协议的输入 token 都是提示总量:未缓存的输入、缓存读取与缓存写入之和。contextConsumedTokens 是上一次响应的提示总量(压缩之后是对下一次请求的估算);0.3 之前,Anthropic 的这个值只计未缓存的输入
compaction_updatedcompaction上下文压缩的进展:trigger(manual、automatic)、phase(/compact 为 standalone_turn,以及 pre_turn、mid_turn、background)、reason(user_requested、context_limit、new_context_requested)、implementation(local_summary、responses_compact、responses_compact_v2)、status(reserved、running、ready_to_install、completed、failed、cancelled)、summary、usage(inputTokens、outputTokens、source)、lastError 等。在后台运行的压缩只发送一个事件,即回合安装它时:status 为 completed,phase 为 background。turnId 为 null
context_compressedcallId、blocksCreated、tokensCompressed、tier分层压缩的一次 compress 调用折叠了部分上下文:它生成的块数、这些块替换掉的 token 数,以及它生成或重新折叠的块中最高的层级(1 到 3)。什么也没折叠的调用不发送此事件。它紧跟在该调用输出的 history_committed 之后、tool_completed 之前
context_compression_failedmessage分层压缩在这次请求中失败(其算法发生 panic):请求带上完整历史,回合余下部分按 standard 策略运行。每个回合至多一次,在这一步的 reasoning_updated 之后
model_retry_scheduledstage、currentRetry、maximumRetries、delayMillis、reason将要重试模型请求。stage 是 response_stream、image_input_fallback 或 reasoning_fallback
model_context_window_learnedtokens、previousProvider 以超出模型上下文窗口为由拒绝了请求,会话采用由此学到的窗口:tokens 是拒绝中写明的窗口,否则是被拒请求的估算大小,取代 previous(null:未知)。它在随后的压缩和重试之前到达,且只在会话采用这个窗口时发送:你配置的窗口不会发送。此后该模型上的会话都从这个窗口开始(上下文窗口与压缩)
steering_accepted、steering_consumed补充消息的序号回合进行中补充的消息被接受、被模型读取。exec 不会补充消息,因此不会出现
continuation_hook_started、continuation_hook_completedproviderId、hookId,以及 outcome插件的继续钩子,例如用户的 Stop 钩子(providerId 为 hooks,hookId 为 stop),或活动目标的钩子(goal、continue)。outcome 是 passed、continued、stopped、ignored_failure 或 failed
hook_started、hook_completedproviderId、hookId、callId、event,以及 outcome插件在工具调用 callId 前后的钩子,例如用户的 PreToolUse 与 PostToolUse 钩子(providerId 为 hooks,hookId 为 tool-use)。event 是 pre_tool_use 或 post_tool_use;outcome 是 passed、denied(调用没有运行)、added_context、failed 或 timed_out(没有效果)。只报告适用于该调用的钩子

事件流中没有会话对象,会话的角色改变时也没有事件:角色只在回合之间改变,所以每个回合的 turn_started 给出整个回合所用的角色(role,default 时为 null;对 exec 来说就是 --role 给的角色)。sessions list --json 把它作为会话摘要中的 role 给出,default 时不出现。

usage.contextEstimatedTokens 存在时,是与 contextConsumedTokens 配对的请求原始估算值。自动压缩只在该已报告的提示用量上加上此后估算的增长量。尚未校准、完成压缩或切换模型路由后没有该字段。

活动

activity 在开始或改变一项活动的事件上有值:sampling_started、response_started、model_retry_scheduled、history_committed、工具事件、审批事件、user_input_requested 和 execution_progress。其他事件为 null。

字段含义
id、revision活动的 ID 和修订号
kindsampling、tool_invocation、approval、continuation_hook 或 execution
phaserunning、waiting_for_approval、waiting_for_cleanup、waiting_for_user_input、succeeded、failed、cancelled 或 interrupted
presentationaction 和 subject,与 tool_started 的相同
attempt重试的次数,或 null
startedAt、updatedAt、finishedAt时间;finishedAt 在活动结束前为 null
execution、output进程活动的状态和输出摘要,或 null

执行活动的 execution.initiatingCallId(若有)标识启动进程的调用。后续 write_stdin 报告保留最初的身份,kind.callId 仍标识本次报告的调用。旧的持久活动或启动调用未知时,该可选字段缺省。

顺序

  • 回合以 turn_started 开始,接着是记录你的消息的 history_committed,新会话随后是 session_title_updated。
  • 每次请求模型:sampling_started、reasoning_updated、response_started,然后是模型的输出。
  • 一段思考是 reasoning_started、零个或多个 reasoning_delta、reasoning_completed,都在这一步的 history_committed 之前。它的 reasoning_completed 最迟出现在它之后的输出(回答的 assistant_message_started 或文本、工具调用)的第一个事件之前,之后不再有它的 reasoning_delta。回合在响应流中途失败时,不会有 reasoning_completed。
  • 一条消息是 assistant_message_started、若干 assistant_text_delta,然后是这一步的 history_committed,最后是 assistant_message_completed。
  • 一步中的工具调用:先按调用顺序为每个调用发出 tool_started;每个调用执行中可能有它的钩子的 hook_started 与 hook_completed(调用运行之前和之后)、审批、提问或计划事件,结束时有 tool_execution_finished(按完成顺序);之后按调用顺序是 history_committed 和 tool_completed(折叠成功的 compress 调用在两者之间还有 context_compressed);最后,如果钩子在调用之后添加了上下文,是它的 history_committed。
  • execution_progress 可能穿插在任何位置。需要严格顺序时,按 sequence 排序。

最后一行总是 turn_completed、turn_cancelled 或 turn_failed:exec 在收到它后停止输出,之后会话中的事件(例如稍后生成的标题)不会出现。回合完成时如果会话的子代理仍在工作,exec 会继续运行为它们的报告唤醒会话的回合:每个回合都是一组和任何回合一样的事件,从它的 turn_started 到它的最后一行,它的第一个 history_committed 写入的是更新(background_events 条目),而不是你的消息。最后一行于是是最后一个回合的。

子代理的审批和问题通过后台事件流处理。使用 --json 时,其可读提示写到标准错误;子代理的事件不会混入根会话的 JSON 事件流。

兼容性

事件的格式就是 Agent 内部事件类型的序列化结果,会随 Agent 一起变化:

  • 任何版本都可能增加新的事件种类、字段或枚举值(如 compaction_updated 的 phase 为 background,或 context_compressed)。读取方应当跳过不认识的种类、字段和值。
  • 在 1.0 之前,删除一个字段或种类、改变其含义,只会在次版本号(如 0.1 到 0.2)变化时发生。

本页目录