编码Agent的RPC模式详解

badlogic 发布于 2026-07-24 阅读 14

本文详细介绍了编码Agent的RPC模式,允许通过stdin/stdout上的JSON协议进行无头操作。内容包括启动RPC模式、协议概述、命令类型(提示、状态、模型、思考、队列模式、压缩、重试、bash、会话等)、事件流、扩展UI协议以及示例客户端代码。

RPC模式通过stdin/stdout上的JSON协议实现编码Agent的无头操作。这对于将Agent嵌入其他应用程序、IDE或自定义UI非常有用。

Node.js/TypeScript 用户注意:如果你正在构建Node.js应用程序,请考虑直接使用 @earendil-works/pi-coding-agent 中的 AgentSession,而不是生成子进程。API 参见 src/core/agent-session.ts。对于基于子进程的 TypeScript 客户端,参见 src/modes/rpc/rpc-client.ts

启动 RPC 模式

pi --mode rpc [options]

常用选项:

  • --provider <name>:设置LLM提供商(anthropic、openai、google等)
  • --model <pattern>:模型模式或ID(支持 provider/id 和可选的 :<thinking>
  • --name <name> / -n <name>:启动时设置会话显示名称
  • --no-session:禁用会话持久化
  • --session-dir <path>:自定义会话存储目录

协议概述

  • 命令:发送到stdin的JSON对象,每行一个
  • 响应:带有 type: "response" 的JSON对象,指示命令的成功/失败
  • 事件:代理事件以JSON行形式流式传输到stdout

所有命令支持可选的 id 字段用于请求/响应关联。如果提供,相应的响应将包含相同的 idbash_execution_update 事件也包含其原始 bash 命令的 id

帧结构

RPC模式使用严格的JSONL语义,仅以LF(\n)作为记录分隔符。

这对客户端很重要:

  • 仅根据 \n 分割记录
  • 截断尾随的 \r,以接受可选的 \r\n 输入
  • 不要使用将Unicode分隔符视为换行符的通用行读取器

特别是,Node的 readline 不符合RPC模式的协议,因为它还会在 U+2028U+2029 上分割,而这些字符在JSON字符串中是合法的。

命令

提示

prompt

向代理发送用户提示。命令响应在提示被接受、排队或处理后发出。事件在接收后继续异步流式传输。

{"id": "req-1", "type": "prompt", "message": "Hello, world!"}

带图像:

{"type": "prompt", "message": "What's in this image?", "images": [{"type": "image", "data": "base64-encoded-data", "mimeType": "image/png"}]}

流式传输期间:如果代理已经在流式传输,你必须指定 streamingBehavior 来排队消息:

{"type": "prompt", "message": "New instruction", "streamingBehavior": "steer"}
  • "steer":在代理运行时排队消息。在当前助手轮次完成执行其工具调用后,在下一次LLM调用之前传递。
  • "followUp":等待代理完成。仅当代理停止时才传递消息。

如果代理正在流式传输且未指定 streamingBehavior,命令返回错误。

扩展命令:如果消息是扩展命令(例如 /mycommand),即使在流式传输期间也会立即执行。扩展命令通过 pi.sendMessage() 自行管理LLM交互。

输入扩展:技能命令(/skill:name)和提示模板(/template)在发送/排队之前被扩展。

响应:

{"id": "req-1", "type": "response", "command": "prompt", "success": true}

success: true 表示提示已被接受、排队或立即处理。success: false 表示提示在接受前被拒绝。接受后的失败通过正常的事件和消息流报告,而不是作为同一请求ID的第二个 response

images 字段是可选的。每个图像使用 ImageContent 格式:{"type": "image", "data": "base64-encoded-data", "mimeType": "image/png"}

steer

在代理运行时排队一条引导消息。在当前助手轮次完成执行其工具调用后,在下一次LLM调用之前传递。技能命令和提示模板会被扩展。不允许使用扩展命令(请改用 prompt)。

{"type": "steer", "message": "Stop and do this instead"}

带图像:

{"type": "steer", "message": "Look at this instead", "images": [{"type": "image", "data": "base64-encoded-data", "mimeType": "image/png"}]}

images 字段是可选的。每个图像使用 ImageContent 格式(与 prompt 相同)。

响应:

{"type": "response", "command": "steer", "success": true}

参见 set_steering_mode 以控制引导消息的处理方式。

follow_up

排队一条后续消息,在代理完成后处理。仅当代理没有更多工具调用或引导消息时才会传递。技能命令和提示模板会被扩展。不允许使用扩展命令(请改用 prompt)。

{"type": "follow_up", "message": "After you're done, also do this"}

带图像:

{"type": "follow_up", "message": "Also check this image", "images": [{"type": "image", "data": "base64-encoded-data", "mimeType": "image/png"}]}

images 字段是可选的。每个图像使用 ImageContent 格式(与 prompt 相同)。

响应:

{"type": "response", "command": "follow_up", "success": true}

参见 set_follow_up_mode 以控制后续消息的处理方式。

abort

中止当前的代理操作。

{"type": "abort"}

响应:

{"type": "response", "command": "abort", "success": true}
new_session

启动一个新会话。可以通过 session_before_switch 扩展事件处理程序取消。

{"type": "new_session"}

带可选的父会话跟踪:

{"type": "new_session", "parentSession": "/path/to/parent-session.jsonl"}

响应:

{"type": "response", "command": "new_session", "success": true, "data": {"cancelled": false}}

如果扩展取消了:

{"type": "response", "command": "new_session", "success": true, "data": {"cancelled": true}}

状态

get_state

获取当前会话状态。

{"type": "get_state"}

响应:

{
  "type": "response",
  "command": "get_state",
  "success": true,
  "data": {
    "model": {...},
    "thinkingLevel": "medium",
    "isStreaming": false,
    "isCompacting": false,
    "steeringMode": "all",
    "followUpMode": "one-at-a-time",
    "sessionFile": "/path/to/session.jsonl",
    "sessionId": "abc123",
    "sessionName": "my-feature-work",
    "autoCompactionEnabled": true,
    "messageCount": 5,
    "pendingMessageCount": 0
  }
}

model 字段是一个完整的 Model 对象或 nullsessionName 字段是通过 set_session_name 设置的显示名称,如果未设置则省略。

get_messages

获取对话中的所有消息。

{"type": "get_messages"}

响应:

{
  "type": "response",
  "command": "get_messages",
  "success": true,
  "data": {"messages": [...]}
}

消息是 AgentMessage 对象(参见 消息类型)。

模型

set_model

切换到特定模型。

{"type": "set_model", "provider": "anthropic", "modelId": "claude-sonnet-4-20250514"}

响应包含完整的 Model 对象:

{
  "type": "response",
  "command": "set_model",
  "success": true,
  "data": {...}
}
cycle_model

循环到下一个可用模型。如果只有一个模型可用,则返回 null 数据。

{"type": "cycle_model"}

响应:

{
  "type": "response",
  "command": "cycle_model",
  "success": true,
  "data": {
    "model": {...},
    "thinkingLevel": "medium",
    "isScoped": false
  }
}

model 字段是一个完整的 Model 对象。

get_available_models

列出所有已配置的模型。

{"type": "get_available_models"}

响应包含一个完整的 Model 对象数组:

{
  "type": "response",
  "command": "get_available_models",
  "success": true,
  "data": {
    "models": [...]
  }
}

思考

set_thinking_level

为支持的模型设置推理/思考级别。

{"type": "set_thinking_level", "level": "high"}

级别:"off""minimal""low""medium""high""xhigh""max"

"xhigh""max" 仅在所选模型支持时暴露。某些模型(包括 GPT-5.6)同时暴露两者。

响应:

{"type": "response", "command": "set_thinking_level", "success": true}
cycle_thinking_level

循环可用思考级别。如果模型不支持思考,则返回 null 数据。

{"type": "cycle_thinking_level"}

响应:

{
  "type": "response",
  "command": "cycle_thinking_level",
  "success": true,
  "data": {"level": "high"}
}
get_available_thinking_levels

列出当前模型支持的思考级别。对于不支持推理的模型,返回 ["off"]

{"type": "get_available_thinking_levels"}

响应:

{
  "type": "response",
  "command": "get_available_thinking_levels",
  "success": true,
  "data": {
    "levels": ["off", "minimal", "low", "medium", "high"]
  }
}

队列模式

set_steering_mode

控制引导消息(来自 steer)的传递方式。

{"type": "set_steering_mode", "mode": "one-at-a-time"}

模式:

  • "all":在当前助手轮次完成执行其所有工具调用后,传递所有引导消息
  • "one-at-a-time":每个完成的助手轮次传递一条引导消息(默认)

响应:

{"type": "response", "command": "set_steering_mode", "success": true}
set_follow_up_mode

控制后续消息(来自 follow_up)的传递方式。

{"type": "set_follow_up_mode", "mode": "one-at-a-time"}

模式:

  • "all":代理完成时传递所有后续消息
  • "one-at-a-time":每次代理完成时传递一条后续消息(默认)

响应:

{"type": "response", "command": "set_follow_up_mode", "success": true}

压缩

compact

手动压缩对话上下文以减少Token使用量。

{"type": "compact"}

带自定义指令:

{"type": "compact", "customInstructions": "Focus on code changes"}

响应:

{
  "type": "response",
  "command": "compact",
  "success": true,
  "data": {
    "summary": "对话摘要...",
    "firstKeptEntryId": "abc123",
    "tokensBefore": 150000,
    "estimatedTokensAfter": 32000,
    "usage": {
      "input": 32000,
      "output": 1200,
      "cacheRead": 0,
      "cacheWrite": 0,
      "totalTokens": 33200,
      "cost": {"input": 0.01, "output": 0.02, "cacheRead": 0, "cacheWrite": 0, "total": 0.03}
    },
    "details": {}
  }
}

estimatedTokensAfter 是对压缩后重建消息上下文的启发式估计,不是提供商精确的Token计数。usage 报告用于生成摘要的LLM调用,并可能被自定义压缩处理程序省略。

set_auto_compaction

启用或禁用上下文接近满时的自动压缩。

{"type": "set_auto_compaction", "enabled": true}

响应:

{"type": "response", "command": "set_auto_compaction", "success": true}

重试

set_auto_retry

启用或禁用临时错误(过载、速率限制、5xx)的自动重试。

{"type": "set_auto_retry", "enabled": true}

响应:

{"type": "response", "command": "set_auto_retry", "success": true}
abort_retry

中止正在进行的重试(取消延迟并停止重试)。

{"type": "abort_retry"}

响应:

{"type": "response", "command": "abort_retry", "success": true}

Bash

bash

执行shell命令并将输出添加到对话上下文中。命令运行时,输出作为 bash_execution_update 事件流式传输;响应包含最终结果。

{"id": "req-1", "type": "bash", "command": "ls -la"}

包含一个 id 以将流式传输的 bash_execution_update 事件与此命令关联。

响应:

{
  "id": "req-1",
  "type": "response",
  "command": "bash",
  "success": true,
  "data": {
    "output": "total 48\ndrwxr-xr-x ...",
    "exitCode": 0,
    "cancelled": false,
    "truncated": false
  }
}

如果输出被截断,则包含 fullOutputPath

{
  "type": "response",
  "command": "bash",
  "success": true,
  "data": {
    "output": "截断的输出...",
    "exitCode": 0,
    "cancelled": false,
    "truncated": true,
    "fullOutputPath": "/tmp/pi-bash-abc123.log"
  }
}

Bash结果如何到达LLM:

bash 命令立即执行并返回一个 BashResult。内部会创建一个 BashExecutionMessage 并存储在代理的消息状态中。

当下一个 prompt 命令发送时,所有消息(包括 BashExecutionMessage)在发送到LLM之前会被转换。BashExecutionMessage 会被转换为以下格式的 UserMessage

Ran `ls -la`
```
total 48
drwxr-xr-x ...
```

这意味着:

  1. Bash输出会包含在下一次提示的LLM上下文中,而不是立即包含
  2. 可以在一个提示之前执行多个bash命令;所有输出都会被包含
abort_bash

中止正在运行的bash命令。

{"type": "abort_bash"}

响应:

{"type": "response", "command": "abort_bash", "success": true}

会话

get_session_stats

获取Token使用量、成本统计和当前上下文窗口使用情况。

{"type": "get_session_stats"}

响应:

{
  "type": "response",
  "command": "get_session_stats",
  "success": true,
  "data": {
    "sessionFile": "/path/to/session.jsonl",
    "sessionId": "abc123",
    "userMessages": 5,
    "assistantMessages": 5,
    "toolCalls": 12,
    "toolResults": 12,
    "totalMessages": 22,
    "tokens": {
      "input": 50000,
      "output": 10000,
      "cacheRead": 40000,
      "cacheWrite": 5000,
      "total": 105000
    },
    "cost": 0.45,
    "contextUsage": {
      "tokens": 60000,
      "contextWindow": 200000,
      "percent": 30
    }
  }
}

tokenscost 包含助手消息、工具报告的使用量以及整个会话中的压缩/分支摘要生成。contextUsage 包含用于压缩和页脚显示的实际当前上下文窗口估计。

当没有模型或上下文窗口时,contextUsage 被省略。contextUsage.tokenscontextUsage.percent 在压缩后立即为 null,直到新的压缩后助手响应提供有效的使用数据。

export_html

将会话导出到HTML文件。

{"type": "export_html"}

带自定义路径:

{"type": "export_html", "outputPath": "/tmp/session.html"}

响应:

{
  "type": "response",
  "command": "export_html",
  "success": true,
  "data": {"path": "/tmp/session.html"}
}
switch_session

加载不同的会话文件。可以通过 session_before_switch 扩展事件处理程序取消。

{"type": "switch_session", "sessionPath": "/path/to/session.jsonl"}

响应:

{"type": "response", "command": "switch_session", "success": true, "data": {"cancelled": false}}

如果扩展取消了切换:

{"type": "response", "command": "switch_session", "success": true, "data": {"cancelled": true}}
fork

从活动分支上的先前用户消息创建一个新分支。可以通过 session_before_fork 扩展事件处理程序取消。返回被分支消息的文本。

{"type": "fork", "entryId": "abc123"}

响应:

{
  "type": "response",
  "command": "fork",
  "success": true,
  "data": {"text": "原始提示文本...", "cancelled": false}
}

如果扩展取消了分支:

{
  "type": "response",
  "command": "fork",
  "success": true,
  "data": {"text": "原始提示文本...", "cancelled": true}
}
clone

将当前活动分支复制到当前位置的一个新会话中。可以通过 session_before_fork 扩展事件处理程序取消。

{"type": "clone"}

响应:

{
  "type": "response",
  "command": "clone",
  "success": true,
  "data": {"cancelled": false}
}

如果扩展取消了克隆:

{
  "type": "response",
  "command": "clone",
  "success": true,
  "data": {"cancelled": true}
}
get_fork_messages

获取可用于分支的用户消息。

{"type": "get_fork_messages"}

响应:

{
  "type": "response",
  "command": "get_fork_messages",
  "success": true,
  "data": {
    "messages": [
      {"entryId": "abc123", "text": "第一条提示..."},
      {"entryId": "def456", "text": "第二条提示..."}
    ]
  }
}
get_entries

按追加顺序获取所有会话条目(不包括会话标头)。会话是一个仅追加的条目树,具有稳定的ID,因此条目ID可以作为持久的游标:传递你已看到的最后一个条目ID作为 since,以仅获取严格在其之后的条目,即使在客户端重启后也是如此。与 get_messages 不同,这包括压缩前的历史和废弃的分支。

{"type": "get_entries"}

带游标:

{"type": "get_entries", "since": "abc123"}

响应:

{
  "type": "response",
  "command": "get_entries",
  "success": true,
  "data": {
    "entries": [
      {"type": "message", "id": "def456", "parentId": "abc123", "timestamp": "...", "message": {"role": "user", "...": "..."}}
    ],
    "leafId": "def456"
  }
}

leafId 是当前叶子条目的ID(对于空会话为 null),因此客户端可以在一次往返中判断活动分支是否已移动。如果 since 与任何条目ID都不匹配,则响应为 success: false

get_tree

将会话作为条目树获取。每个节点为 {entry, children, label?, labelTimestamp?}。一个格式良好的会话有一个单一根节点;孤儿条目(断开的父链)也作为根节点出现。

{"type": "get_tree"}

响应:

{
  "type": "response",
  "command": "get_tree",
  "success": true,
  "data": {
    "tree": [
      {
        "entry": {"type": "message", "id": "abc123", "parentId": null, "...": "..."},
        "children": [
          {"entry": {"type": "message", "id": "def456", "parentId": "abc123", "...": "..."}, "children": []}
        ]
      }
    ],
    "leafId": "def456"
  }
}
get_last_assistant_text

获取最后一条助手消息的文本内容。

{"type": "get_last_assistant_text"}

响应:

{
  "type": "response",
  "command": "get_last_assistant_text",
  "success": true,
  "data": {"text": "助手的响应..."}
}

如果没有助手消息,则返回 {"text": null}

set_session_name

为当前会话设置显示名称。该名称出现在会话列表中,有助于识别会话。

{"type": "set_session_name", "name": "my-feature-work"}

响应:

{
  "type": "response",
  "command": "set_session_name",
  "success": true
}

当前会话名称可通过 get_state 中的 sessionName 字段获取。要在启动RPC模式时设置初始名称,请向 pi --mode rpc 进程传递 --name <name>-n <name>

命令

get_commands

获取可用的命令(扩展命令、提示模板和技能)。这些可以通过 prompt 命令以 / 为前缀来调用。

{"type": "get_commands"}

响应:

{
  "type": "response",
  "command": "get_commands",
  "success": true,
  "data": {
    "commands": [
      {"name": "session-name", "description": "设置或清除会话名称", "source": "extension", "path": "/home/user/.pi/agent/extensions/session.ts"},
      {"name": "fix-tests", "description": "修复失败的测试", "source": "prompt", "location": "project", "path": "/home/user/myproject/.pi/agent/prompts/fix-tests.md"},
      {"name": "skill:brave-search", "description": "通过Brave API进行Web搜索", "source": "skill", "location": "user", "path": "/home/user/.pi/agent/skills/brave-search/SKILL.md"}
    ]
  }
}

每个命令包含:

  • name:命令名称(通过 /name 调用)
  • description:人类可读的描述(对于扩展命令是可选的)
  • source:命令的类型:
    • "extension":通过扩展中的 pi.registerCommand() 注册
    • "prompt":从提示模板 .md 文件加载
    • "skill":从技能目录加载(名称以 skill: 为前缀)
  • location:加载位置(可选,扩展不存在):
    • "user":用户级别(~/.pi/agent/
    • "project":项目级别(./.pi/agent/
    • "path":通过CLI或设置的显式路径
  • path:命令源的绝对文件路径(可选)

注意:内置TUI命令(/settings/hotkeys 等)不包括在内。它们仅在交互模式下处理,如果通过 prompt 发送则不会执行。

事件

在代理操作期间,事件以JSON行的形式流式传输到stdout。事件通常不包含 id 字段;bash_execution_update 在提供了 id 时包含其原始 bash 命令的 id

事件类型

事件 描述
agent_start 代理开始处理
agent_end 一个低级代理运行完成(可能仍会跟随重试、压缩或排队的延续)
agent_settled 代理运行完全稳定;没有剩余的自动重试、压缩重试或排队的延续
turn_start 新轮次开始
turn_end 轮次完成(包括助手消息和工具结果)
message_start 消息开始
message_update 流式更新(文本/思考/工具调用增量)
message_end 消息完成
bash_execution_update 直接RPC bash命令输出块
tool_execution_start 工具开始执行
tool_execution_update 工具执行进度(流式输出)
tool_execution_end 工具完成
queue_update 待处理的引导/后续队列已更改
compaction_start 压缩开始
compaction_end 压缩完成
auto_retry_start 自动重试开始(出现临时错误后)
auto_retry_end 自动重试完成(成功或最终失败)
summarization_retry_scheduled 为临时压缩或分支摘要错误安排重试
summarization_retry_attempt_start 重试的摘要请求开始
summarization_retry_finished 摘要重试循环完成
extension_error 扩展抛出错误

agent_start

当代理开始处理提示时发出。

{"type": "agent_start"}

agent_end

当一个低级代理运行完成时发出。包含此运行期间生成的所有消息。如果 willRetry 为 true,则将进行自动重试。

{
  "type": "agent_end",
  "messages": [...],
  "willRetry": false
}

agent_settled

在完整的会话级运行稳定后发出。此时Pi不会通过重试、压缩重试或排队的后续消息自动继续。

{"type": "agent_settled"}

turn_start / turn_end

一个轮次包括一个助手响应以及任何由此产生的工具调用和结果。

{"type": "turn_start"}
{
  "type": "turn_end",
  "message": {...},
  "toolResults": [...]
}

message_start / message_end

当消息开始和完成时发出。message 字段包含一个 AgentMessage

{"type": "message_start", "message": {...}}
{"type": "message_end", "message": {...}}

message_update (流式传输)

在助手消息流式传输期间发出。包含部分消息和一个流式增量事件。

{
  "type": "message_update",
  "message": {...},
  "assistantMessageEvent": {
    "type": "text_delta",
    "contentIndex": 0,
    "delta": "Hello ",
    "partial": {...}
  }
}

assistantMessageEvent 字段包含以下增量类型之一:

类型 描述
start 消息生成开始
text_start 文本内容块开始
text_delta 文本内容块
text_end 文本内容块结束
thinking_start 思考块开始
thinking_delta 思考内容块
thinking_end 思考块结束
toolcall_start 工具调用开始
toolcall_delta 工具调用参数块
toolcall_end 工具调用结束(包含完整的 toolCall 对象)
done 消息完成(原因:"stop""length""toolUse"
error 发生错误(原因:"aborted""error"

流式传输文本响应的示例:

{"type":"message_update","message":{...},"assistantMessageEvent":{"type":"text_start","contentIndex":0,"partial":{...}}}
{"type":"message_update","message":{...},"assistantMessageEvent":{"type":"text_delta","contentIndex":0,"delta":"Hello","partial":{...}}}
{"type":"message_update","message":{...},"assistantMessageEvent":{"type":"text_delta","contentIndex":0,"delta":" world","partial":{...}}}
{"type":"message_update","message":{...},"assistantMessageEvent":{"type":"text_end","contentIndex":0,"content":"Hello world","partial":{...}}}

bash_execution_update

对于来自直接 bash 命令的每个输出块发出一次。id 与命令的 id 匹配,允许客户端将输出与正确的命令关联。

事件在命令运行时流式传输所有输出,即使最终 bash 响应的 output 被截断。

{
  "type": "bash_execution_update",
  "id": "req-1",
  "delta": "total 48\n"
}

tool_execution_start / tool_execution_update / tool_execution_end

在工具开始、流式传输进度和完成执行时发出。

{
  "type": "tool_execution_start",
  "toolCallId": "call_abc123",
  "toolName": "bash",
  "args": {"command": "ls -la"}
}

执行期间,tool_execution_update 事件流式传输部分结果(例如,bash输出到达时):

{
  "type": "tool_execution_update",
  "toolCallId": "call_abc123",
  "toolName": "bash",
  "args": {"command": "ls -la"},
  "partialResult": {
    "content": [{"type": "text", "text": "到目前为止的部分输出..."}],
    "details": {"truncation": null, "fullOutputPath": null}
  }
}

完成时:

{
  "type": "tool_execution_end",
  "toolCallId": "call_abc123",
  "toolName": "bash",
  "result": {
    "content": [{"type": "text", "text": "total 48\n..."}],
    "details": {...}
  },
  "isError": false
}

使用 toolCallId 关联事件。tool_execution_update 中的 partialResult 包含迄今累积的输出(不仅仅是增量),允许客户端在每次更新时简单地替换其显示。

queue_update

每当待处理的引导或后续队列更改时发出。

{
  "type": "queue_update",
  "steering": ["关注错误处理"],
  "followUp": ["之后,总结结果"]
}

compaction_start / compaction_end

当压缩运行时发出,无论是手动还是自动。

{"type": "compaction_start", "reason": "threshold"}

reason 字段为 "manual""threshold""overflow"

{
  "type": "compaction_end",
  "reason": "threshold",
  "result": {
    "summary": "对话摘要...",
    "firstKeptEntryId": "abc123",
    "tokensBefore": 150000,
    "estimatedTokensAfter": 32000,
    "usage": {
      "input": 32000,
      "output": 1200,
      "cacheRead": 0,
      "cacheWrite": 0,
      "totalTokens": 33200,
      "cost": {"input": 0.01, "output": 0.02, "cacheRead": 0, "cacheWrite": 0, "total": 0.03}
    },
    "details": {}
  },
  "aborted": false,
  "willRetry": false
}

如果 reason"overflow" 并且压缩成功,则 willRetrytrue,代理将自动重试提示。

如果压缩被中止,则 resultnullabortedtrue

如果压缩失败(例如,API配额超出),则 resultnullabortedfalse,并且 errorMessage 包含错误描述。

auto_retry_start / auto_retry_end

当临时错误(过载、速率限制、5xx)触发自动重试时发出。

{
  "type": "auto_retry_start",
  "attempt": 1,
  "maxAttempts": 3,
  "delayMs": 2000,
  "errorMessage": "529 {\"type\":\"error\",\"error\":{\"type\":\"overloaded_error\",\"message\":\"Overloaded\"}}"
}
{
  "type": "auto_retry_end",
  "success": true,
  "attempt": 2
}

最终失败(超过最大重试次数):

{
  "type": "auto_retry_end",
  "success": false,
  "attempt": 3,
  "finalError": "529 overloaded_error: Overloaded"
}

summarization_retry_scheduled / summarization_retry_attempt_start / summarization_retry_finished

当压缩或分支摘要在临时提供商错误后重试时发出。这些事件使用与自动助手轮次重试相同的重试设置。

{
  "type": "summarization_retry_scheduled",
  "attempt": 1,
  "maxAttempts": 3,
  "delayMs": 2000,
  "errorMessage": "terminated"
}
{
  "type": "summarization_retry_attempt_start",
  "source": "compaction",
  "reason": "threshold"
}

对于分支摘要,source"branchSummary",且不存在 reason

{
  "type": "summarization_retry_finished"
}

extension_error

当扩展抛出错误时发出。

{
  "type": "extension_error",
  "extensionPath": "/path/to/extension.ts",
  "event": "tool_call",
  "error": "错误消息..."
}

扩展UI协议

扩展可以通过 ctx.ui.select()ctx.ui.confirm() 等请求用户交互。在RPC模式下,这些被转换为基于命令/事件流之上的请求/响应子协议。

扩展UI方法分为两类:

  • 对话框方法selectconfirminputeditor):在stdout上发出 extension_ui_request 并阻塞,直到客户端在stdin上发回带有匹配 idextension_ui_response
  • 即发即弃方法notifysetStatussetWidgetsetTitleset_editor_text):在stdout上发出 extension_ui_request 但不期望响应。客户端可以显示信息或忽略它。

如果对话框方法包含 timeout 字段,则代理端会在超时到期时自动解析为默认值。客户端不需要跟踪超时。

某些 ExtensionUIContext 方法在RPC模式下不支持或降级,因为它们需要直接TUI访问:

  • custom() 返回 undefined
  • setWorkingMessage()setWorkingIndicator()setFooter()setHeader()setEditorComponent()setToolsExpanded() 是无操作
  • getEditorText() 返回 ""
  • getToolsExpanded() 返回 false
  • pasteToEditor() 委托给 setEditorText()(无粘贴/折叠处理)
  • getAllThemes() 返回 []
  • getTheme() 返回 undefined
  • setTheme() 返回 { success: false, error: "..." }

注意:在RPC模式下,ctx.mode"rpc"ctx.hasUItrue,因为对话框和即发即弃方法通过扩展UI子协议起作用。使用 ctx.mode === "tui" 来保护需要真实终端的TUI特定功能(如 custom())。

扩展UI请求 (stdout)

所有请求都有 type: "extension_ui_request"、唯一的 idmethod 字段。

select

提示用户从列表中选择。带有 timeout 字段的对话框方法包含以毫秒为单位的超时时间;如果客户端未及时响应,代理自动解析为 undefined

{
  "type": "extension_ui_request",
  "id": "uuid-1",
  "method": "select",
  "title": "允许危险命令?",
  "options": ["允许", "阻止"],
  "timeout": 10000
}

预期响应:extension_ui_response 包含 value(所选选项字符串)或 cancelled: true

confirm

提示用户进行是/否确认。

{
  "type": "extension_ui_request",
  "id": "uuid-2",
  "method": "confirm",
  "title": "清除会话?",
  "message": "所有消息将丢失。",
  "timeout": 5000
}

预期响应:extension_ui_response 包含 confirmed: true/falsecancelled: true

input

提示用户输入自由格式文本。

{
  "type": "extension_ui_request",
  "id": "uuid-3",
  "method": "input",
  "title": "输入一个值",
  "placeholder": "输入内容..."
}

预期响应:extension_ui_response 包含 value(输入的文本)或 cancelled: true

editor

打开一个多行文本编辑器,带有可选的预填内容。

{
  "type": "extension_ui_request",
  "id": "uuid-4",
  "method": "editor",
  "title": "编辑文本",
  "prefill": "第1行\n第2行\n第3行"
}

预期响应:extension_ui_response 包含 value(编辑后的文本)或 cancelled: true

notify

显示通知。即发即弃,不期望响应。

{
  "type": "extension_ui_request",
  "id": "uuid-5",
  "method": "notify",
  "message": "命令被用户阻止",
  "notifyType": "warning"
}

notifyType 字段为 "info""warning""error"。如果省略,则默认为 "info"

setStatus

设置或清除页脚/状态栏中的状态条目。即发即弃。

{
  "type": "extension_ui_request",
  "id": "uuid-6",
  "method": "setStatus",
  "statusKey": "my-ext",
  "statusText": "第3轮运行中..."
}

发送 statusText: undefined(或省略它)以清除该键的状态条目。

setWidget

设置或清除显示在编辑器上方或下方的小部件(文本行块)。即发即弃。

{
  "type": "extension_ui_request",
  "id": "uuid-7",
  "method": "setWidget",
  "widgetKey": "my-ext",
  "widgetLines": ["--- 我的小部件 ---", "第1行", "第2行"],
  "widgetPlacement": "aboveEditor"
}

发送 widgetLines: undefined(或省略它)以清除小部件。widgetPlacement 字段为 "aboveEditor"(默认)或 "belowEditor"。在RPC模式下仅支持字符串数组;组件工厂被忽略。

setTitle

设置终端窗口/标签页标题。即发即弃。

{
  "type": "extension_ui_request",
  "id": "uuid-8",
  "method": "setTitle",
  "title": "pi - 我的项目"
}
set_editor_text

设置输入编辑器中的文本。即发即弃。

{
  "type": "extension_ui_request",
  "id": "uuid-9",
  "method": "set_editor_text",
  "text": "为用户预填的文本"
}

扩展UI响应 (stdin)

仅为对话框方法(selectconfirminputeditor)发送响应。id 必须与请求匹配。

值响应 (select、input、editor)
{"type": "extension_ui_response", "id": "uuid-1", "value": "Allow"}
确认响应 (confirm)
{"type": "extension_ui_response", "id": "uuid-2", "confirmed": true}
取消响应 (任何对话框)

取消任何对话框方法。扩展接收 undefined(对于 select/input/editor)或 false(对于 confirm)。

{"type": "extension_ui_response", "id": "uuid-3", "cancelled": true}

错误处理

失败的命令返回带有 success: false 的响应:

{
  "type": "response",
  "command": "set_model",
  "success": false,
  "error": "找不到模型:invalid/model"
}

解析错误:

{
  "type": "response",
  "command": "parse",
  "success": false,
  "error": "无法解析命令:意外的Token..."
}

类型

源文件:

Model

{
  "id": "claude-sonnet-4-20250514",
  "name": "Claude Sonnet 4",
  "api": "anthropic-messages",
  "provider": "anthropic",
  "baseUrl": "https://api.anthropic.com",
  "reasoning": true,
  "input": ["text", "image"],
  "contextWindow": 200000,
  "maxTokens": 16384,
  "cost": {
    "input": 3.0,
    "output": 15.0,
    "cacheRead": 0.3,
    "cacheWrite": 3.75
  }
}

UserMessage

{
  "role": "user",
  "content": "Hello!",
  "timestamp": 1733234567890,
  "attachments": []
}

content 字段可以是字符串或 TextContent/ImageContent 块的数组。

AssistantMessage

{
  "role": "assistant",
  "content": [
    {"type": "text", "text": "Hello! How can I help?"},
    {"type": "thinking", "thinking": "User is greeting me..."},
    {"type": "toolCall", "id": "call_123", "name": "bash", "arguments": {"command": "ls"}}
  ],
  "api": "anthropic-messages",
  "provider": "anthropic",
  "model": "claude-sonnet-4-20250514",
  "usage": {
    "input": 100,
    "output": 50,
    "cacheRead": 0,
    "cacheWrite": 0,
    "cost": {"input": 0.0003, "output": 0.00075, "cacheRead": 0, "cacheWrite": 0, "total": 0.00105}
  },
  "stopReason": "stop",
  "timestamp": 1733234567890
}

停止原因:"stop""length""toolUse""error""aborted"

ToolResultMessage

{
  "role": "toolResult",
  "toolCallId": "call_123",
  "toolName": "bash",
  "content": [{"type": "text", "text": "total 48\ndrwxr-xr-x ..."}],
  "usage": {
    "input": 100,
    "output": 50,
    "cacheRead": 0,
    "cacheWrite": 0,
    "totalTokens": 150,
    "cost": {"input": 0.0003, "output": 0.00075, "cacheRead": 0, "cacheWrite": 0, "total": 0.00105}
  },
  "isError": false,
  "timestamp": 1733234567890
}

usage 是可选的,报告工具执行的嵌套LLM工作。如果存在,它会贡献给会话Token和成本总计。

BashExecutionMessage

bash RPC命令创建(不是LLM工具调用):

{
  "role": "bashExecution",
  "command": "ls -la",
  "output": "total 48\ndrwxr-xr-x ...",
  "exitCode": 0,
  "cancelled": false,
  "truncated": false,
  "fullOutputPath": null,
  "timestamp": 1733234567890
}

Attachment

{
  "id": "img1",
  "type": "image",
  "fileName": "photo.jpg",
  "mimeType": "image/jpeg",
  "size": 102400,
  "content": "base64-encoded-data...",
  "extractedText": null,
  "preview": null
}

示例:基本客户端 (Python)

import subprocess
import json

proc = subprocess.Popen(
    ["pi", "--mode", "rpc", "--no-session"],
    stdin=subprocess.PIPE,
    stdout=subprocess.PIPE,
    text=True
)

def send(cmd):
    proc.stdin.write(json.dumps(cmd) + "\n")
    proc.stdin.flush()

def read_events():
    for line in proc.stdout:
        yield json.loads(line)

## 发送提示
send({"type": "prompt", "message": "Hello!"})

## 处理事件
for event in read_events():
    if event.get("type") == "message_update":
        delta = event.get("assistantMessageEvent", {})
        if delta.get("type") == "text_delta":
            print(delta["delta"], end="", flush=True)

    if event.get("type") == "agent_end":
        print()
        break

示例:交互式客户端 (Node.js)

有关完整的交互式示例,请参见 test/rpc-example.ts,或参见 src/modes/rpc/rpc-client.ts 以获取类型化客户端实现。

有关处理扩展UI协议的完整示例,请参见 examples/rpc-extension-ui.ts,它与 examples/extensions/rpc-demo.ts 扩展配对。

const { spawn } = require("child_process");
const { StringDecoder } = require("string_decoder");

const agent = spawn("pi", ["--mode", "rpc", "--no-session"]);

function attachJsonlReader(stream, onLine) {
    const decoder = new StringDecoder("utf8");
    let buffer = "";

    stream.on("data", (chunk) => {
        buffer += typeof chunk === "string" ? chunk : decoder.write(chunk);

        while (true) {
            const newlineIndex = buffer.indexOf("\n");
            if (newlineIndex === -1) break;

            let line = buffer.slice(0, newlineIndex);
            buffer = buffer.slice(newlineIndex + 1);
            if (line.endsWith("\r")) line = line.slice(0, -1);
            onLine(line);
        }
    });

    stream.on("end", () => {
        buffer += decoder.end();
        if (buffer.length > 0) {
            onLine(buffer.endsWith("\r") ? buffer.slice(0, -1) : buffer);
        }
    });
}

attachJsonlReader(agent.stdout, (line) => {
    const event = JSON.parse(line);

    if (event.type === "message_update") {
        const { assistantMessageEvent } = event;
        if (assistantMessageEvent.type === "text_delta") {
            process.stdout.write(assistantMessageEvent.delta);
        }
    }
});

// 发送提示
agent.stdin.write(JSON.stringify({ type: "prompt", message: "Hello" }) + "\n");

// 在Ctrl+C时中止
process.on("SIGINT", () => {
    agent.stdin.write(JSON.stringify({ type: "abort" }) + "\n");
});
  • 原文链接: github.com/badlogic/pi-m...
  • 登链社区 AI 助手,为大家转译优秀英文文章,如有翻译不通的地方,还请包涵~

相关文章

0 条评论