Pi Agent 非交互模式
实测 Print、JSON 和 RPC 的输入输出,检查模型、工具和会话参数。
学完这一章,你能够
- 实测 Print、JSON 和 RPC 的输入输出,检查模型、工具和会话参数。
先用 Print 完成一项固定输入任务
脚本只需要最终助手答复时,用 pi --print 加一条明确提示。Pi 完成后将文本写到 stdout 并退出。调用方可检查退出码和标准错误,再决定是否把答复交给下一步程序。
可用独立的 @文件参数传入文本或受支持的图片,也可从 stdin 管道传入文字。路径以调用所在目录为准,图片还需模型支持对应输入。要保存供后续继续的名称,可用 --name 并保留会话持久化。本章用自编文字、原生 PNG 和固定回应验证实际请求。
固定模型和推理强度
用 --provider 与 --model 精确选择,或将提供方和模型写成 provider/id。本站已观察两种命令给回环发送相同模型。模型名可追加 :xhigh 等档位后缀,只有模型支持及映射允许的值才会生效。
模型后缀与 --thinking 同时使用时,固定版以 --thinking 为本次命令的优先值。本章实测覆盖了 :xhigh 加 --thinking off 的组合。--models 用逗号分隔多个候选,既能影响启动匹配,也能限定交互轮换范围。
明确模型可调用的工具
本版常见只读工具为 read、grep、find 和 ls。write、edit、bash 可写入或执行命令。原生 Windows 仍能使用配置好的 Bash,也可显式启用 powershell。WSL 使用其 Linux 环境。用 --tools 指定任务需要的名单,并在调用前为进程设置独立的文件和网络权限。
--exclude-tools 在选定工具基础上移除匹配项。--no-builtin-tools 去掉默认内置工具,显式扩展工具仍可列出。--no-tools 让这次模型请求不携带实验工具。三个选择的效果均从回环请求实际工具名单确认,扩展的装入和模型工具选择分别管理。
用 JSONL 观察一次任务的事件
JSON 模式一次执行并输出逐行事件。首行给出当前会话格式版本、标识、时间与工作目录。后续按 type 区分消息开始、更新、结束、工具结果和运行完成。处理时逐行解码,并分别检查实际助手消息和完成状态。
用 RPC 在同一进程反复发送命令
RPC 用 stdin 写 JSONL 命令,stdout 收应答和事件。每次命令可给独立字符串 id。客户端按 id 处理应答,同时继续读取运行过程。RPC 不接收启动位置的 @文件参数,可用协议规定的输入方式传送内容。
需要自定义按钮或询问时,扩展可发 extension_ui_request。客户端按同一 id 回传 extension_ui_response。本站扩展只请求确认显示课程标记,通过本地 RPC 客户端收到确认并发出通知。这条扩展命令自行处理,未调用模型。
三种非交互输出的比较
Print 适合消费最终文本,JSON 适合解析一次任务的事件,RPC 适合需要双向控制的程序。下面是按实际本地运行绘制的输入与输出关系;交互模式仍可用于人在终端直接工作。
常用参数按使用目标选取
把模型选择、会话保存、工具和资源放在各自的参数组,并用固定示例验证输入与输出。比如命名会话并不隐含它已保存;需要继续、分叉或导出时,应先找到实际会话文件。
何时读取 JSON 事件流
| 用途 | 观察办法 |
| 事件后处理 | 逐行解析结构并筛选实际助手消息、运行结束与退出状态。 |
| 观察外部行为 | 记录工具的声明、开始、结果及错误。仅展示允许收集的事件。 |
| 接入后处理程序 | 按事件类型触发后处理,并区分成功、取消和失败。 |
何时保持长连接 RPC
| 用途 | 观察办法 |
| 编辑器客户端 | 通过命令 id 关联请求,另接收模型及扩展事件。 |
| 自定义交互界面 | 把 confirm 等扩展事件展示成界面控件,再回传同一 id 的响应。 |
| 后台子进程 | 限制资源和文件访问,按协议持续读取响应,处理超时或退出。 |
四种模式收发什么
| 模式 | 命令 | 交互 | 输出 | 用途 |
| 交互 | pi | 由终端持续接收输入。 | 终端界面 | 本地逐步处理任务。 |
| pi --print | 处理这次调用的输入,然后退出。 | 标准输出中的最终文本 | 脚本和一次性工作。 | |
| JSON | pi --mode json | 执行一批输入,输出过程中事件。 | 单向 JSONL | 分析一次调用。 |
| RPC | pi --mode rpc | 同一进程按行持续收发。 | 双向 JSONL 协议 | 编辑器、程序或独立 UI。 |
常用参数及依赖条件
| 组别 | 参数 | 作用与限制 |
| 模型 | --provider name | 限制模型查找提供方,与 --model 配合。 |
| 模型 | --model pattern | 精确名称、匹配模式或 provider/id;可以附带推理档位。 |
| 模型 | --api-key key | 传本次非持久化密钥,使用可辨识的模型;只在受控情况下使用命令行密钥。 |
| 模型 | --thinking level | 选择支持的档位,比模型名的档位后缀优先。 |
| 模型 | --models patterns | 以逗号列出模式,影响启动与循环范围。 |
| 会话 | -c 或 --continue | 恢复当前工作目录的最近会话。 |
| 会话 | -r 或 --resume | 打开已有会话选择器,再选择可读的历史会话。 |
| 会话 | --session path|id | 指定已有的会话路径或标识。 |
| 会话 | --fork path|id | 把已有会话分叉到新记录。与 --session、--continue、--resume 和 --no-session 互斥。 |
| 会话 | -n 或 --name name | 指定显示名。保留写盘才能在后续选择。 |
| 会话 | --no-session | 在内存中使用会话。 |
| 会话 | --export 输入 [输出] | 把已有会话写成 HTML。可按输入名称自动选择输出路径。 |
| 工具 | -t 或 --tools list | 列出模型可用工具。别把选定工具当作操作系统权限设置。 |
| 工具 | -xt 或 --exclude-tools list | 排除指定名称或模式匹配的工具。 |
| 工具 | -nbt 或 --no-builtin-tools | 禁用默认内置工具,独立扩展仍可提供工具。 |
| 工具 | -nt 或 --no-tools | 本次禁用模型侧工具。扩展可独立装入。 |
| 资源 | -e 或 --extension source | 明确装入一个扩展,可重复指定。执行扩展前要知道来源和权限。 |
| 资源 | --skill path | 加入指定技能文件或目录。 |
| 资源 | --theme path | 加载指定主题资源。显示效果需在对应终端核对。 |
| 其他 | -a 或 --approve | 只在本次为已检查的项目开启信任相关资源。 |
| 其他 | -nc 或 --no-context-files | 禁用自动发现的 AGENTS.md、CLAUDE.md 等上下文。 |
比较工具名单、JSON 事件和 RPC 对话框
展开查看收起
"""Exercise the real Pi CLI and RPC subprotocol with a local course fixture."""
import argparse
from base64 import b64decode
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import json
import os
from pathlib import Path
from queue import Queue
import re
import subprocess
from tempfile import TemporaryDirectory
from threading import Thread
REPLY = "COURSE MODE RESULT"
PROMPT = "Read the mode fixture."
MODEL_A, MODEL_B = "course-alpha", "course-beta"
PROVIDER = "course-modes"
def run(node, cli, extension):
cases, requests = [], []
def check(name, inputs, expected, actual):
if actual != expected:
raise RuntimeError(f"{name}: wanted {expected!r}, got {actual!r}")
cases.append(dict(name=name, input=inputs, expected=expected, actual=actual, passed=True))
class Endpoint(BaseHTTPRequestHandler):
def do_POST(self):
if self.path != "/v1/chat/completions":
self.send_error(404)
return
body = json.loads(self.rfile.read(int(self.headers["Content-Length"])))
requests.append(dict(model=body["model"], tools=sorted(t["function"]["name"] for t in body.get("tools", [])),
effort=body.get("reasoning_effort"), thinking=body.get("thinking", {}).get("type"),
history=[msg["content"] for msg in body["messages"] if msg["role"] == "user"]))
def record(delta, reason):
return dict(id="pi-modes", object="chat.completion.chunk", created=1, model=body["model"],
choices=[dict(index=0, delta=delta, finish_reason=reason)])
frames = (record(dict(role="assistant", content=REPLY), None), record({}, "stop"))
response = "".join("data: " + json.dumps(frame) + "\n\n" for frame in frames) + "data: [DONE]\n\n"
self.send_response(200)
self.send_header("Content-Type", "text/event-stream")
self.send_header("Content-Length", str(len(response)))
self.end_headers()
self.wfile.write(response.encode())
def log_message(self, fmt, *args):
pass
with TemporaryDirectory(prefix="mbsky-pi-modes-") as temp, ThreadingHTTPServer(("127.0.0.1", 0), Endpoint) as server:
root = Path(temp)
config = root / "agent"
config.mkdir()
endpoint = f"http://127.0.0.1:{server.server_port}/v1"
models = [{"id": name, "reasoning": True, "compat": {"thinkingFormat": "deepseek"},
"thinkingLevelMap": {"high": "high", "xhigh": "high"}} for name in (MODEL_A, MODEL_B)]
(config / "models.json").write_text(json.dumps({"providers": {PROVIDER: {
"baseUrl": endpoint, "api": "openai-completions", "apiKey": "fixture-only", "models": models,
}}}), encoding="utf8")
(root / "note.txt").write_text("synthetic text", encoding="utf8")
env = {name: os.environ[name] for name in ("PATH", "SystemRoot", "WINDIR", "COMSPEC", "PATHEXT",
"TEMP", "TMP", "USERPROFILE", "LOCALAPPDATA", "APPDATA") if name in os.environ}
env.update(PI_CODING_AGENT_DIR=str(config), PI_OFFLINE="1", PI_SKIP_VERSION_CHECK="1", PI_TELEMETRY="0")
base = [str(node), str(cli), "--no-session", "--no-extensions", "--no-mcp", "--no-context-files",
"--no-skills", "--no-prompt-templates", "--no-themes", "--no-approve"]
child_settings = dict(cwd=root, env=env, text=True, encoding="utf8")
thread = Thread(target=server.serve_forever, daemon=True)
thread.start()
def invoke(*args, expected_output=REPLY):
before = len(requests)
out = subprocess.run([*base, *args, PROMPT], **child_settings, input="", capture_output=True,
timeout=18)
if out.returncode:
raise RuntimeError(out.stderr or out.stdout)
if len(requests) != before + 1:
raise RuntimeError("one-shot mode yielded an unexpected number of requests")
if expected_output is not None and out.stdout.strip() != expected_output:
raise RuntimeError("Print did not emit the expected fixed text")
return requests[-1], out.stdout
try:
first, _ = invoke("--print", "--provider", PROVIDER, "--model", MODEL_A, "--no-tools")
second, _ = invoke("--print", "--model", PROVIDER + "/" + MODEL_A, "--no-tools")
check("provider_and_qualified_model_select_same", {"provider": PROVIDER}, [MODEL_A, MODEL_A],
[first["model"], second["model"]])
suffix, _ = invoke("--print", "--model", PROVIDER + "/" + MODEL_B + ":xhigh", "--no-tools")
check("thinking_suffix_maps_to_provider", {"requested": "xhigh"}, [MODEL_B, "enabled", "high"],
[suffix["model"], suffix["thinking"], suffix["effort"]])
precedence, _ = invoke("--print", "--model", PROVIDER + "/" + MODEL_B + ":xhigh", "--thinking", "off", "--no-tools")
check("explicit_thinking_overrides_suffix", {"suffix": "xhigh", "option": "off"},
["disabled", None], [precedence["thinking"], precedence["effort"]])
scoped, _ = invoke("--print", "--models", "course-b*", "--no-tools")
check("model_pattern_scopes_startup", {"pattern": "course-b*"}, MODEL_B, scoped["model"])
args = ["--print", "--provider", PROVIDER, "--model", MODEL_A]
filtered, _ = invoke(*args, "--tools", "read,write,bash", "--exclude-tools", "write,bash")
check("exclude_tools_applies_after_selection", {"allow": ["read","write","bash"], "exclude": ["write","bash"]},
["read"], filtered["tools"])
add_extension = ["--extension", str(extension)]
builtin_disabled, _ = invoke(*args, *add_extension, "--no-builtin-tools")
check("no_builtin_keeps_own_extension", {"option": "--no-builtin-tools"},
["course_marker"], builtin_disabled["tools"])
all_disabled, _ = invoke(*args, *add_extension, "--no-tools")
check("no_tools_removes_extension_tool", {"option": "--no-tools"}, [], all_disabled["tools"])
platform_tools, _ = invoke(*args, "--tools", "read,powershell")
if os.name == "nt":
check("native_windows_can_explicitly_select_powershell", {"tools": "read,powershell"},
["powershell", "read"], platform_tools["tools"])
_, payload = invoke("--mode", "json", "--model", PROVIDER + "/" + MODEL_A, "--no-tools", expected_output=None)
events = [json.loads(line) for line in payload.splitlines()]
done = next(row for row in events if row["type"] == "agent_settled")
assistant = next(row["message"] for row in events if row["type"] == "message_end" and row["message"]["role"] == "assistant")
text = next(item["text"] for item in assistant["content"] if item["type"] == "text")
check("json_records_capture_actual_assistant", {"mode": "json"},
{"header": "session", "text": REPLY, "aborted": False},
{"header": events[0]["type"], "text": text, "aborted": done["aborted"]})
excluded_attachment = subprocess.run([*base, "--mode", "rpc", "@note.txt"], **child_settings,
input="", capture_output=True, timeout=12)
check("rpc_rejects_initial_file_argument", {"argument": "@note.txt"}, True, excluded_attachment.returncode != 0)
session_dir = root / "sessions"
session_dir.mkdir()
durable = [item for item in base if item != "--no-session"]
durable += ["--session-dir", str(session_dir), "--print", "--no-tools",
"--model", PROVIDER + "/" + MODEL_A]
def saved_prompt(prompt, *options):
completed = subprocess.run([*durable, *options, prompt], **child_settings,
input="", capture_output=True, timeout=18)
if completed.returncode or completed.stdout.strip() != REPLY:
raise RuntimeError(completed.stderr or completed.stdout)
return requests[-1]["history"]
markers = ["Course history first.", "Course history second.", "Course history third."]
saved_prompt(markers[0], "--name", "Modes fixture")
original, = session_dir.glob("*.jsonl")
selected_history = saved_prompt(markers[1], "--continue")
first_text = json.dumps(selected_history, ensure_ascii=False)
check("continue_reuses_latest_owned_history", {"option": "--continue"}, [True, True],
[line in first_text for line in markers[:2]])
named_history = saved_prompt(markers[2], "--session", str(original))
second_text = json.dumps(named_history, ensure_ascii=False)
check("session_file_reuses_requested_history", {"option": "--session"},
[True, True, True], [line in second_text for line in markers])
prior = original.read_bytes()
side = "Branch only."
fork_history = saved_prompt(side, "--fork", str(original))
fork_text = json.dumps(fork_history, ensure_ascii=False)
check("fork_keeps_original_file", {"option": "--fork"},
{"surviving_files": 2, "unchanged": True, "history_preserved": True},
{"surviving_files": len(list(session_dir.glob("*.jsonl"))), "unchanged": original.read_bytes() == prior,
"history_preserved": all(line in fork_text for line in (*markers, side))})
destination = root / "session-view.html"
subprocess.run([str(node), str(cli), "--export", str(original), str(destination)],
**child_settings, input="", capture_output=True, check=True, timeout=15)
page = destination.read_text(encoding="utf8")
encoded = re.search(r'<script id="session-data" type="application/json">([A-Za-z0-9+/=]+)</script>', page)
assert encoded, "exported session data element is missing"
content = json.dumps(json.loads(b64decode(encoded.group(1))), ensure_ascii=False)
check("cli_export_preserves_original_session_content", {"option": "--export"},
{"original_prompt": True, "fork_prompt": False},
{"original_prompt": markers[0] in content, "fork_prompt": side in content})
with subprocess.Popen([*base, "--mode", "rpc", "--model", PROVIDER + "/" + MODEL_A, *add_extension],
**child_settings, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) as rpc:
events_queue = Queue()
def collect():
for line in rpc.stdout:
if line.strip():
events_queue.put(json.loads(line))
events_queue.put(None)
Thread(target=collect, daemon=True).start()
def send(message):
rpc.stdin.write(json.dumps(message) + "\n")
rpc.stdin.flush()
def receive_until(predicate):
while True:
row = events_queue.get(timeout=12)
if row is None:
raise RuntimeError("RPC closed before expected response")
if predicate(row):
return row
try:
before = len(requests)
send({"id": "state-1", "type": "get_state"})
state = receive_until(lambda row: row.get("id")=="state-1")
check("rpc_state_correlates_by_id", {"id": "state-1"}, True, state["success"])
send({"id": "dialog-cmd", "type": "prompt", "message": "/course-check"})
prompt = receive_until(lambda row: row["type"]=="extension_ui_request" and row.get("method")=="confirm")
check("rpc_extension_dialog", {"command": "/course-check"},
["Course fixture", "Display the local badge?"], [prompt["title"], prompt["message"]])
send({"id": prompt["id"], "type": "extension_ui_response", "confirmed": True})
notification = receive_until(lambda row: row["type"]=="extension_ui_request" and row.get("method")=="notify")
check("rpc_dialog_response_reaches_extension", {"response": "confirmed"}, "COURSE CONFIRMED", notification["message"])
response = receive_until(lambda row: row.get("id")=="dialog-cmd" and row["type"]=="response")
check("rpc_plugin_command_handled_locally", {"id": "dialog-cmd"}, [True, "handled", 0],
[response["success"], response["data"]["disposition"], len(requests) - before])
rpc.stdin.close()
if rpc.wait(timeout=10):
raise RuntimeError(rpc.stderr.read())
finally:
if rpc.poll() is None:
rpc.kill()
finally:
server.shutdown()
thread.join(timeout=3)
return dict(cases=cases)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("node", type=Path)
parser.add_argument("pi_cli", type=Path)
args = parser.parse_args()
extension = Path(__file__).with_name("course-ui.ts")
print(json.dumps(run(args.node.resolve(strict=True), args.pi_cli.resolve(strict=True), extension), ensure_ascii=False))
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地复跑
按 README 运行主脚本和 Print 输入脚本,逐项比较实际结果。
本章附件与实例包
常见错误与边界检查
- 确认输出来自当前模式及当前请求。
- 在命令行设置工具名单后仍应独立设置系统访问范围。
技术规范与官方资料
练习与参考解答
查看参考解答
这个工具由本章明确加载的扩展注册。禁用内置工具保留扩展工具,--no-tools 才将该工具从本次模型请求移除。