蓝色天空网mbsky.com · 知识 · 实践 · 创造Pi Agent · 本地阅读预览
教程 / AI / 智能开发 / Pi Agent

Pi Agent CLI 参考手册

按模式、模型、会话和资源查找 CLI 参数,并运行一组可复验的本地实验。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

先确定程序如何收发数据

本附录以 Pi 1.5.0 为运行基准。人在终端操作时使用持续的交互界面。脚本只取最终答复时用 Print,需要逐行事件时用 JSON,需要向同一子进程多次发命令时用 RPC。重定向后,未指定 JSON 或 RPC 的调用会采用 Print 行为。

选择本次使用的模型

先用 --list-models 筛选当前可用模型,再用 provider/id 消除同名模型的歧义。CLI 参数只覆盖本次使用的选择。模型名末尾可带推理档位,显式 --thinking 优先,实际档位取决于模型。

会话何时写盘

看最近会话用 --continue,已知文件可给 --session,需要保留原历史并开展另一条路线则用 --fork。录制可复用教学过程时建议指定会话目录与名称,并把会话文件当作可能含有敏感输入的资料。--no-session 的运行留在内存。

工具选择与资源发现

先决定模型这次需要哪些工具,再排除多余项。工具名单只决定向模型声明的接口。需要隔离文件访问时,将 Pi 放进独立工作目录和权限受限的运行环境。

资源的自动发现和显式路径可以分别配置。可关闭自动发现后,仅加载经过检查的本地扩展、Skill、模板或主题。--no-context-files 针对上下文说明文件,关闭它也会去掉原本会发送给模型的项目说明。

启动覆盖与项目信任

系统提示可替换,也能向现有提示追加内容。--tui-mode 选择交互界面如何占用终端,--use-theme 选择这次的初始主题。安装版本不同,用 pi -h 和 pi -v 对照当下的语法与版本。

需要读取已检查的项目配置时可为一次调用加 --approve,或用 --no-approve 忽略须经信任的配置。两项二选一。实验分别启动两个临时进程,核对项目工具设置的变化,并检查 trust.json 的写入情况。

包的管理范围

用 install、list、remove 和 config 管理设置中登记的包及其资源,关闭资源与移除包会产生不同结果。按命令选择全局或项目范围。执行 update 前确定目标是程序本身、包还是模型目录。

配置认证、代理与终端颜色

提供方的登录凭据、进程环境和网络设置各有用途。代理配置先核对客户端是否读取相关环境变量。调试终端色彩时检查声明的颜色能力,再考虑明确设置 truecolor。

Pi 1.5.0 的 httpProxy 由用户级代理配置目录读取,通常位于 ~/.pi/agent/settings.json。项目目录中的同名键没有这个效果。访问规则仍以目标服务的要求为准。

添加文本和图片,检查返回值

将 @note.md 作为单独参数,Pi 从当前目录读取这个文本文件。可以传入两个文本文件比较它们,也可在模型接受图片的条件下加入 @tile.png。-- 结束选项解析,此后带短横线的文本可做提示,@ 仍承担文件参数的含义。RPC 启动参数不接收这种文件输入。

下方实验使用独立的两像素宽 PNG 和固定答复。它检查图片是否以 PNG 输入到达回环服务,以及 Print 是否把返回文字写到 stdout。若要检查模型是否识别了图中物体,还需换用支持视觉且能进行实际识别的模型。

启动模式

入口行为与条件用法示意
默认交互调用终端输入与输出均为 TTY 时进入交互,标准流重定向时可转为 Print。pi
-p 或 --print处理参数给出的提示,将最终答复写到标准输出,再退出。pi --print "提取这段文字的主题"
--mode json逐行输出 JSON 事件,处理完本次提示即结束,可直接使用。pi --mode json "列出文档标题"
--mode rpc以标准流接收命令和返回应答或事件,客户端按 id 对应应答。pi --mode rpc
--export 文件 [目标]将已有 JSONL 会话写成 HTML,省略目标时在当前目录生成 pi-session-源文件短名.html。pi --export session.jsonl lesson.html

模型与推理

入口行为与条件用法示意
--provider 名称与 --model 合用,将查找限制在一个提供方。pi --provider course-local --model fixture
--model 标识或模式支持模型名匹配、provider/id 和可选 :档位 后缀。pi --model course-local/fixture
--api-key 值为这次选中的模型覆盖请求凭据,需同时明确模型;常规使用优先走凭据存储。在回环实验里传一次性自编值
--thinking 档位可选 off、minimal、low、medium、high、xhigh、max。显式值优先,按模型能力调整。pi --model supported-model --thinking low
--models 模式列表逗号分隔的范围控制启动候选与交互轮换。可用 * 匹配名称。pi --models "lab-*,review-small"
--list-models [检索词]列出当前可用模型,可按关键词检索后退出。pi --list-models course-local

会话存储、选择与分叉

入口行为与条件用法示意
-c 或 --continue继续当前工作目录最近保存的会话。pi --continue
-r 或 --resume打开会话选择器,在交互终端选择旧会话。pi --resume
--session 文件或 ID按会话的具体文件或 ID 定位;ID 前缀需足以区分记录。pi --session ./session.jsonl
--fork 文件或 ID从来源历史建立新会话,保留来源文件。它与 --session、--continue、--resume、--no-session 互斥。pi --fork ./session.jsonl
--session-dir 目录替换本次的存储与查找位置,常规默认在代理配置目录下的 sessions。pi --session-dir ./lesson-sessions
--no-session使用内存会话,退出后不会在该会话目录留下历史文件。pi --no-session
-n 或 --name 名称给会话设置便于检索的显示名称。保留会话才能之后找回。pi --name "短文检查"

工具选择

入口行为与条件用法示意
-t 或 --tools 名单使用逗号分隔的工具名单。对于局部增减,1.5.0 支持 +名和 -名形式。pi --tools read,grep
-xt 或 --exclude-tools 名单在其余选择规则之后排除工具,可匹配名称或模式。pi --tools read,grep --exclude-tools grep
-nbt 或 --no-builtin-tools禁用默认内置工具;显式扩展及自定义工具仍可以被声明。pi --no-builtin-tools
-nt 或 --no-tools让本次调用不向模型暴露工具,仍可传入会话文字以及受支持的图片。pi --print --no-tools @note.md

资源的自动发现及显式加载

入口行为与条件用法示意
-e 或 --extension 来源本次加载指定扩展文件或包;每项加一次参数。扩展可执行代码。pi -e ./owner-extension.ts
--no-extensions关闭扩展自动发现,允许显式 --extension。pi --no-extensions
--skill 路径从指定文件或目录加入 Skill,可多次指定。pi --skill ./catalog-skill/
--no-skills关闭 Skill 自动发现,允许显式 --skill。pi --no-skills
--prompt-template 路径从指定路径加入模板,可多次指定。pi --prompt-template ./read-note.md
--no-prompt-templates关闭模板自动发现,允许显式 --prompt-template。pi --no-prompt-templates
--theme 路径加载主题资源,可用多次。随后可按主题名选择。pi --theme ./course-theme.json
--no-themes关闭自定义主题自动发现,仍能显式加载和使用内置主题。pi --no-themes
-nc 或 --no-context-files停止发现和加载 AGENTS.md、CLAUDE.md 等上下文文件。pi --approve --no-context-files

进程、提示、信任和界面

入口行为与条件用法示意
--system-prompt 内容使用所给文字或文件内容替换默认系统提示。pi --system-prompt "从事实列表提取日期。"
--append-system-prompt 内容在基本系统提示后增加文字或文件内容,可重复指定。pi --append-system-prompt "每条日期单独一行。"
--tui-mode 模式选 regular 或 fullscreen。Pi 1.5.0 帮助标注 fullscreen 为默认,仍可在设置中覆盖。pi --tui-mode regular
--use-theme 名称指定本次交互界面启动时使用的主题名称。用 --theme 加载含有该名称的主题资源。pi --use-theme light
--verbose显示详细启动信息,可在排查加载过程时使用。pi --verbose
-a 或 --approve在当前调用允许加载依赖项目信任的配置。pi --approve
-na 或 --no-approve在当前调用忽略依赖项目信任的配置。pi --no-approve
--结束选项处理。此后 @文件 仍是文件输入,其余文字按位置作提示。pi --print -- @note.md "-开头也是提示文字"
-h 或 --help打印安装版本的帮助,可能包含启用扩展注册的选项。pi -h
-v 或 --version显示程序版本后退出。pi -v

包管理子命令

命令用途
pi install 来源安装并登记包。用 --local 或 -l 将其记入项目设置。
pi remove 来源移除指定安装范围中的包及其设置条目。用 -l 指定项目范围。
pi uninstall 来源remove 的别名,参数与作用范围一致。
pi list列出已登记的包和范围,便于确认其来源。
pi update [目标]无参数及 --self 更新 Pi。--extensions 更新所有已装包,具体来源或 --extension 来源 更新单个包。--models 刷新目录,--all 更新 Pi 和全部包。
pi config [-l]在终端逐项启用或禁用包内资源,支持全局和项目范围。

环境变量与网络配置

入口行为与条件用法示意
ANTHROPIC_API_KEY可向 Anthropic 提供方提供 API 密钥。已有登录时按当前提供方的凭据解析规则选择认证。由本机凭据管理流程注入
HTTP_PROXY 与 HTTPS_PROXY配置支持代理环境变量的 HTTP 或 HTTPS 请求。按所用网络准备代理 URL
NO_PROXY为支持此变量的客户端指定直接连接的主机列表。localhost,127.0.0.1
COLORTERMtruecolor 可参与颜色能力检测。需要覆盖时用 PI_TRUE_COLOR=1、0 或 auto,也可设置 terminal.trueColor。COLORTERM=truecolor

核对本地 Pi 命令的输入、输出和会话

python · 阅读源码
"""Exercise Pi CLI inputs and outputs on a local, deterministic model fixture."""
from argparse import ArgumentParser
from base64 import b64decode
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import json
import os
from pathlib import Path
import re
import struct
import subprocess
from tempfile import TemporaryDirectory
from threading import Thread
import zlib

REPLY = "Observed course response."
PROMPT = "Describe the supplied material."
MODEL = "course-local/fixture"


def simple_png():
    """Generate a two-by-two blue PNG without relying on image libraries."""
    def chunk(kind, data):
        return struct.pack(">I", len(data)) + kind + data + struct.pack(">I", zlib.crc32(kind + data))
    header = struct.pack(">IIBBBBB", 2, 2, 8, 2, 0, 0, 0)
    scanline = bytes([0, 30, 100, 200, 30, 100, 200])
    return b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", header) + chunk(b"IDAT", zlib.compress(scanline * 2)) + chunk(b"IEND", b"")


def run(node, cli):
    cases, requests = [], []

    def check(name, inputs, expected, actual):
        if actual != expected:
            raise RuntimeError(f"{name}: expected {expected!r}, observed {actual!r}")
        cases.append(dict(name=name, input=inputs, expected=expected, actual=actual, passed=True))

    class Fixture(BaseHTTPRequestHandler):
        def log_message(self, *_):
            pass

        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(
                override=self.headers.get("Authorization") == "Bearer local-override",
                model=body["model"],
                users=[msg["content"] for msg in body["messages"] if msg["role"] == "user"],
                system=[msg["content"] for msg in body["messages"] if msg["role"] in {"system", "developer"}],
                tools=[tool["function"]["name"] for tool in body.get("tools", [])],
            ))
            def event(delta, reason):
                return json.dumps(dict(id="course", object="chat.completion.chunk", created=1, model=body["model"],
                    choices=[dict(index=0, delta=delta, finish_reason=reason)]))
            frames = [event(dict(role="assistant", content=REPLY), None), event({}, "stop"), "[DONE]"]
            response = "".join(f"data: {frame}\n\n" for frame in frames).encode()
            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)

    with TemporaryDirectory(prefix="mbsky-pi-cli-") as temp, ThreadingHTTPServer(("127.0.0.1", 0), Fixture) as server:
        root = Path(temp)
        config, project, sessions = (root / name for name in ("agent", "project", "sessions"))
        for directory in (config, project, sessions):
            directory.mkdir()
        (config / "models.json").write_text(json.dumps({"providers": {"course-local": {
            "baseUrl": f"http://127.0.0.1:{server.server_port}/v1", "api": "openai-completions",
            "apiKey": "local-fixture", "models": [{"id": "fixture", "input": ["text", "image"]}],
        }}}), encoding="utf8")
        (config / "settings.json").write_text(json.dumps({"defaultProjectTrust": "never"}), encoding="utf8")
        (project / ".pi").mkdir()
        (project / ".pi" / "settings.json").write_text('{"defaultTools":["grep"]}', encoding="utf8")
        (project / "note.md").write_text("Local note marker.", encoding="utf8")
        (project / "first.txt").write_text("Left note marker.", encoding="utf8")
        (project / "second.txt").write_text("Right note marker.", encoding="utf8")
        (project / "tile.png").write_bytes(simple_png())
        (project / "AGENTS.md").write_text("Owner fixture guidance marker.", encoding="utf8")
        env = {key: os.environ[key] for key in ("PATH", "SystemRoot", "WINDIR", "COMSPEC", "PATHEXT",
            "TEMP", "TMP", "USERPROFILE", "LOCALAPPDATA", "APPDATA") if key 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), "--offline", "--no-extensions", "--no-skills", "--no-mcp",
                "--no-prompt-templates", "--no-themes"]
        thread = Thread(target=server.serve_forever, daemon=True)
        thread.start()

        def invoke(*options, stdin=""):
            result = subprocess.run([*base, *options], cwd=project, env=env, input=stdin,
                                    capture_output=True, encoding="utf8", timeout=22)
            if result.returncode != 0:
                raise RuntimeError(f"{options!r}: {result.stderr or result.stdout}")
            return result.stdout

        settings = ["--model", MODEL, "--session-dir", str(sessions)]
        one = ["--print", *settings, "--no-session", "--no-tools", "--no-approve"]
        try:
            out = invoke(*one, "@note.md", PROMPT, stdin="Pipeline marker.\n")
            users = json.dumps(requests[-1]["users"])
            check("print_and_text_inputs", dict(file="note.md", pipe="Pipeline marker.", prompt=PROMPT),
                  [REPLY, True, True, True, []],
                  [out.strip(), "Local note marker." in users, "Pipeline marker." in users, PROMPT in users,
                   requests[-1]["tools"]])
            invoke(*one, "@first.txt", "@second.txt", PROMPT)
            users = json.dumps(requests[-1]["users"])
            check("two_files_keep_both_contents", ["first.txt", "second.txt"], [True, True],
                  ["Left note marker." in users, "Right note marker." in users])
            out = invoke(*one, "@tile.png", PROMPT)
            parts = [part for group in requests[-1]["users"] if isinstance(group, list) for part in group]
            picture = next((p["image_url"]["url"] for p in parts if p["type"] == "image_url"), "")
            check("image_input_and_one_shot_output", dict(file="tile.png", prompt=PROMPT), [True, REPLY],
                  [picture.startswith("data:image/png;base64,"), out.strip()])
            check("no_session_is_transient", "--no-session", [], list(sessions.iterdir()))

            out = invoke(*one, "--", "@note.md", "-Prompt begins with a dash.")
            users = json.dumps(requests[-1]["users"])
            check("separator_stops_options_but_keeps_attachments", ["--", "@note.md", "-Prompt begins with a dash."],
                  [REPLY, True, True], [out.strip(), "Local note marker." in users, "-Prompt begins with a dash." in users])
            invoke(*one, "--api-key", "local-override", PROMPT)
            check("key_override_reaches_only_loopback_fixture", "temporary synthetic key", [True, "fixture"],
                  [requests[-1]["override"], requests[-1]["model"]])
            invoke(*one, PROMPT)
            check("key_override_is_per_invocation", "repeat without override", False,
                  requests[-1]["override"])
            events = [json.loads(line) for line in invoke("--mode", "json", *settings, "--no-session",
                       "--no-tools", "--no-approve", PROMPT).splitlines()]
            assistant = next(event["message"] for event in events if event["type"] == "message_end"
                             and event["message"]["role"] == "assistant")
            check("json_without_print_reports_assistant", "--mode json", ["session", REPLY, True],
                  [events[0]["type"], assistant["content"][0]["text"],
                   any(event["type"] == "agent_settled" for event in events)])
            query = {"id": "course-state", "type": "get_state"}
            rpc_out = invoke("--mode", "rpc", *settings, "--no-session", "--no-tools", "--no-approve",
                             stdin=json.dumps(query) + "\n")
            reply = next(row for row in map(json.loads, rpc_out.splitlines()) if row.get("id") == query["id"])
            check("rpc_state_uses_command_id", query, [True, "get_state", "fixture"],
                  [reply["success"], reply["command"], reply["data"]["model"]["id"]])
            model_list = invoke("--list-models", "course-local")
            check("local_model_catalog_filter", "--list-models course-local", True,
                  "course-local" in model_list and "fixture" in model_list)
            tool_list = ["--print", *settings, "--no-session", "--no-approve", "--tools", "read,grep"]
            invoke(*tool_list, PROMPT)
            check("tools_list_reaches_model", "--tools read,grep", ["grep", "read"], sorted(requests[-1]["tools"]))
            invoke(*tool_list, "--exclude-tools", "grep", PROMPT)
            check("exclude_is_applied_after_selection", "--exclude-tools grep", ["read"], requests[-1]["tools"])
            invoke(*one, "--system-prompt", "Course role.", "--append-system-prompt", "Course format.", PROMPT)
            system = json.dumps(requests[-1]["system"])
            check("system_prompt_replacement_and_append", ["Course role.", "Course format."], [True, True],
                  ["Course role." in system, "Course format." in system])
            approved = ["--print", *settings, "--no-session", "--approve"]
            invoke(*approved, PROMPT)
            context_visible = "Owner fixture guidance marker." in json.dumps(requests[-1]["system"])
            check("approve_loads_local_settings", "--approve", ["grep"], requests[-1]["tools"])
            invoke(*approved, "--no-context-files", PROMPT)
            check("no_context_files_drops_guide_only", "--approve --no-context-files", [True, False, ["grep"]],
                  [context_visible, "Owner fixture guidance marker." in json.dumps(requests[-1]["system"]), requests[-1]["tools"]])
            invoke("--print", *settings, "--no-session", "--no-approve", PROMPT)
            check("no_approve_ignores_project_tool_setting", "--no-approve", ["bash", "edit", "read", "write"],
                  sorted(requests[-1]["tools"]))
            check("trust_switches_do_not_persist_trust", ["--approve", "--no-approve"], False, (config / "trust.json").exists())

            durable = ["--print", *settings, "--no-tools", "--no-approve"]
            invoke(*durable, "--name", "Course session", "First history marker.")
            original, = sessions.glob("*.jsonl")
            persisted = [json.loads(line) for line in original.read_text(encoding="utf8").splitlines()]
            check("named_session_writes_to_override_directory", "--session-dir and --name", [True, True],
                  [original.parent == sessions, any(row.get("name") == "Course session" for row in persisted)])
            invoke(*durable, "--continue", "Second history marker.")
            check("continue_reads_durable_history", "--continue", True,
                  "First history marker." in json.dumps(requests[-1]["users"]))
            invoke(*durable, "--session", str(original), "Third history marker.")
            check("session_accepts_verified_path", "--session PATH", True,
                  "Second history marker." in json.dumps(requests[-1]["users"]))
            prior = original.read_bytes()
            invoke(*durable, "--fork", str(original), "Branch marker.")
            check("fork_keeps_original_and_writes_branch", "--fork PATH", [2, True, True],
                  [len(list(sessions.glob("*.jsonl"))), original.read_bytes() == prior,
                   "Third history marker." in json.dumps(requests[-1]["users"])])
            destination = project / "course-session.html"
            invoke("--export", str(original), str(destination))
            invoke("--export", str(original))
            automatic = project / f"pi-session-{original.stem}.html"

            def read_export(path):
                embed = re.search(r'<script id="session-data" type="application/json">([A-Za-z0-9+/=]+)</script>',
                                  path.read_text(encoding="utf8"))
                return json.dumps(json.loads(b64decode(embed.group(1))))
            check("export_carries_messages_to_html", ["explicit output", "omitted output"], [True, True, True],
                  ["First history marker." in read_export(destination),
                   "Third history marker." in read_export(automatic),
                   original.read_bytes() == prior])
            help_text = invoke("--help")
            check("help_exposes_version_specific_options", "--help", True,
                  all(option in help_text for option in ("--tui-mode", "--use-theme", "--session-dir")))
            check("version_is_fixed", "--version", "1.5.0", invoke("--version").strip())
        finally:
            server.shutdown()
            thread.join()
    return {"cases": cases}


if __name__ == "__main__":
    parser = ArgumentParser(description=__doc__)
    parser.add_argument("node", type=Path)
    parser.add_argument("cli", type=Path)
    args = parser.parse_args()
    print(json.dumps(run(args.node.resolve(strict=True), args.cli.resolve(strict=True))))
预期结果 · 待实际运行核验
  • Print 输出固定答复,JSON 保留答复与事件,RPC 按 id 返回会话状态。会话可分叉和导出,图片附件到达本机回环服务。
核对本地 Pi 命令的输入、输出和会话

所需环境:Windows,Pi 1.5.0、Node.js 24.22.3、Python 和本机回环。

当前源码 SHA256:37c2ca692b02c4b74e55301b03cc165d6f56e2f388d2499cc81675388fa95327

下载本站示例源码

复跑参考手册中的 CLI 行为

解压后按 README 运行,默认只使用临时目录和本机回环。

下载 Pi CLI 本地实验

所需环境:Windows,Pi 1.5.0、Node.js 24.22.3、Python 和本机回环。

ZIP SHA256:efc26300ff95767e9dff4340a63eeb4c8af987c5df2f4e28b6ec86476ec48a35

常见错误与边界

  • 导出前查验真实会话文件和输出目录。
  • 需要验证图像理解时,另选确实支持图片输入的模型。

练习与解答

命令行里的 -- 还会保留 @文件 的含义吗?

展开参考解答

检查回环服务是否同时收到文件内容与短横线开头的提示。

规范与官方依据