蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

比较工具名单、JSON 事件和 RPC 对话框

PYTHONPython 3.12、Node.js 24.22.3、Pi CLI 1.5.0、临时自编回环和扩展。modes-and-controls.py
modes-and-controls.py225 行
"""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))
本例需在 Python 3.12、Node.js 24.22.3、Pi CLI 1.5.0、临时自编回环和扩展。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Python 3.12、Node.js 24.22.3、Pi CLI 1.5.0、临时自编回环和扩展。

入口文件:projects/pi-agent-noninteractive-lab/modes-and-controls.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 modes-and-controls.py,或下载右侧课程工程包。
  2. 确认本地已准备 Python 3.12、Node.js 24.22.3、Pi CLI 1.5.0、临时自编回环和扩展。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Pi Agent

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a281.zip

下载课程关联工程包:Pi Agent

课程关联工程包(登记关联29章) · 含当前章节或实例 · mbskycom202612a267.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习