Skip to main content

RPC 模式

RPC 模式通过 stdin/stdout 上的 JSON 协议实现 Pi 的无头操作,适用于将 Agent 嵌入其他应用、IDE 或自定义 UI。


启动 RPC 模式

pi --mode rpc [options]

常用选项:

  • --provider <name>:设置 LLM Provider
  • --model <pattern>:模型模式或 ID
  • --no-session:禁用会话持久化
  • --session-dir <path>:自定义会话存储目录

协议概述

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

核心命令

prompt — 发送提示

{"type": "prompt", "message": "Hello!"}

带图片:

{"type": "prompt", "message": "图片里有什么?", "images": [{"type": "image", "data": "base64...", "mimeType": "image/png"}]}

流式行为:

  • streamingBehavior: "steer" — 排队,工具调用完成后发送
  • streamingBehavior: "followUp" — 等待 Agent 停止后发送

steer — 转向消息

队列转向消息,在当前工具调用完成后、下一次 LLM 调用前发送:

{"type": "steer", "message": "停下来做这个"}

abort — 中止

中止当前操作:

{"type": "abort"}

set_steering_mode — 设置转向模式

{"type": "set_steering_mode", "mode": "steer"}

模式:steer(默认)或 followUp


Node.js 用户注意

如果构建 Node.js 应用,考虑直接使用 AgentSession 而不是生成子进程:

import { AgentSession } from "@mariozechner/pi-coding-agent";

协议注意事项

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

不要使用 readline,因为它也按 U+2028U+2029 分割,而它们在 JSON 字符串内是有效的。


翻译自 pi-coding-agent/docs/rpc.md