"""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))))
本例需在 Windows,Pi 1.5.0、Node.js 24.22.3、Python 和本机回环。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows,Pi 1.5.0、Node.js 24.22.3、Python 和本机回环。
入口文件:projects/pi-agent-appendix-cli-lab/run-cli-fixture.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
run-cli-fixture.py,或下载右侧课程工程包。 - 确认本地已准备 Windows,Pi 1.5.0、Node.js 24.22.3、Python 和本机回环。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联29章) · 含当前章节或实例 · mbskycom202612a267.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a261.zip