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

通过真实终端核对斜杠命令和会话

PYTHONWindows,Pi 1.5.0,Node.js 24.22.3,WinPTY、本机回环和 Git Bash。terminal-slash-lab.py
terminal-slash-lab.py192 行
"""Exercise Pi's real terminal with temporary sessions and two benign shell commands."""
import argparse
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from importlib.metadata import version
import json
import os
from pathlib import Path
from queue import Empty, Queue
import re
from tempfile import TemporaryDirectory
from threading import Thread
from time import monotonic, sleep

from winpty import PtyProcess

ANSI = re.compile(r"\x1b(?:\[[0-?]*[ -/]*[@-~]|\][^\x07]*?(?:\x07|\x1b\\)|[@-_])")
FIRST_REPLY = "Observed local teaching response."
SHARED = "course-visible-shell-mark"
PRIVATE = "course-terminal-only-mark"
TITLE = "Pi appendix local session"


def exercise(node, cli, shell):
    cases, prompts = [], []

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

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

        def do_POST(self):
            if self.path != "/v1/chat/completions":
                self.send_error(404)
                return
            request = json.loads(self.rfile.read(int(self.headers["Content-Length"])))
            prompts.append(json.dumps(request["messages"], ensure_ascii=False))
            def chunk(delta, finish_reason):
                return dict(id="local-slash-lab", object="chat.completion.chunk", created=1, model=request["model"],
                    choices=[dict(index=0, delta=delta, finish_reason=finish_reason)])
            frames = [chunk(dict(role="assistant", content=FIRST_REPLY), None), chunk({}, "stop")]
            response = ("".join("data: " + json.dumps(event) + "\n\n" for event in frames)
                        + "data: [DONE]\n\n").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-slash-lab-") as temp, ThreadingHTTPServer(("127.0.0.1", 0), Endpoint) as server:
        root = Path(temp)
        agent, project = root / "profile", root / "work"
        agent.mkdir()
        project.mkdir()
        sessions = root / "sessions"
        sessions.mkdir()
        settings = {"tuiMode": "regular", "quietStartup": False, "shellPath": shell.as_posix(),
                    "defaultProjectTrust": "never"}
        (agent / "settings.json").write_text(json.dumps(settings), encoding="utf8")
        model_provider = {
            "baseUrl": f"http://127.0.0.1:{server.server_port}/v1", "api": "openai-completions",
            "apiKey": "only-local", "models": [{"id": "slash-local-test", "name": "Slash local test"}],
        }
        (agent / "models.json").write_text(json.dumps({"providers": {"course-slash": model_provider}}), encoding="utf8")
        extension = project / "appendix-command.mjs"
        extension.write_text(
            'export default function (pi) {\n'
            '  pi.registerCommand("course-check", {description: "Show a local marker",\n'
            '    handler: async (_args, ctx) => ctx.ui.notify("APPENDIX COMMAND OK", "info")});\n'
            '}\n', encoding="utf8")
        permitted = ("PATH", "SystemRoot", "WINDIR", "COMSPEC", "PATHEXT",
                     "TEMP", "TMP", "USERPROFILE", "LOCALAPPDATA", "APPDATA")
        env = {name: os.environ[name] for name in permitted if name in os.environ}
        env.update(PI_CODING_AGENT_DIR=str(agent), PI_OFFLINE="1", PI_SKIP_VERSION_CHECK="1",
                   PI_TELEMETRY="0", TERM="xterm-256color", COLORTERM="truecolor", FORCE_COLOR="1")
        flags = ["--offline", "--no-extensions", "--no-mcp", "--no-context-files", "--no-builtin-tools",
                 "--no-skills", "--no-prompt-templates", "--no-themes", "--no-approve", "--session-dir", str(sessions),
                 "--model", "course-slash/slash-local-test", "-e", str(extension)]
        thread = Thread(target=server.serve_forever, daemon=True)
        thread.start()
        child = None
        queue = Queue()
        raw = ""

        def collect():
            try:
                while True:
                    message = child.read(8192)
                    if not message:
                        break
                    queue.put(message)
            except (EOFError, OSError):
                pass
            finally:
                queue.put(None)

        def wait_for(marker, after=0, timeout=12):
            nonlocal raw
            expires = monotonic() + timeout
            while monotonic() < expires:
                visible = ANSI.sub("", raw[after:]).casefold()
                if marker.casefold() in visible:
                    return visible
                try:
                    message = queue.get(timeout=0.15)
                except Empty:
                    continue
                if message is None:
                    break
                raw += message
            raise RuntimeError(f"{marker!r} not seen: {ANSI.sub('', raw[after:])[-1400:]!r}")

        def submit(text):
            before = len(raw)
            child.write(text)
            sleep(0.15)
            child.write("\r")
            return before

        try:
            child = PtyProcess.spawn([str(node), str(cli), *flags], cwd=str(project), env=env, dimensions=(38, 112))
            Thread(target=collect, daemon=True).start()
            wait_for("slash-local-test")
            seen = wait_for("APPENDIX COMMAND OK", submit("/course-check"))
            check("own_slash_command_dispatches", "/course-check", True, "appendix command ok" in seen)
            keys = wait_for("Keyboard Shortcuts", submit("/hotkeys"))
            check("hotkeys_reports_active_terminal_bindings", "/hotkeys", True, "keyboard shortcuts" in keys)

            wait_for(FIRST_REPLY, submit("Summarize the isolated fixture."))
            sleep(0.3)
            wait_for("Session name set: " + TITLE, submit("/name " + TITLE))
            wait_for("Session name: " + TITLE, submit("/name"))
            original, = sessions.glob("*.jsonl")
            saved = [json.loads(line) for line in original.read_text(encoding="utf8").splitlines()]
            check("name_is_visible_and_persisted", ["/name TITLE", "/name"], [TITLE, True],
                [TITLE, any(row.get("name") == TITLE for row in saved)])
            info = wait_for("Cache Warming", submit("/session"))
            check("session_displays_statistics", "/session", [True, True, True],
                ["session info" in info, "messages" in info, "tokens" in info])
            exported = project / "course-history.jsonl"
            wait_for("Session exported to:", submit("/export course-history.jsonl"))
            check("export_jsonl_preserves_original_prompt", "relative JSONL destination",
                [True, True], [exported.is_file(), "Summarize the isolated fixture." in exported.read_text(encoding="utf8")])

            # Use the same local command twice, with no side effects outside the terminal fixture.
            wait_for(SHARED, submit("!echo " + SHARED))
            sleep(0.45)
            wait_for(PRIVATE, submit("!!echo " + PRIVATE))
            sleep(0.45)
            submit("Check the shell notes I supplied.")
            expires = monotonic() + 10
            while len(prompts) < 2 and monotonic() < expires:
                sleep(0.08)
            assert len(prompts) == 2
            check("shell_prefixes_differ_in_next_request_context", ["!echo", "!!echo", "next prompt"],
                [True, False], [SHARED in prompts[-1], PRIVATE in prompts[-1]])
            expires = monotonic() + 12
            while b"Check the shell notes I supplied." not in original.read_bytes() and monotonic() < expires:
                sleep(0.08)
            assert b"Check the shell notes I supplied." in original.read_bytes()
            sleep(0.3)
            wait_for("New session started", submit("/new"))
            check("new_preserves_the_previous_session_file", "/new", [True, True],
                [original.is_file(), TITLE in original.read_text(encoding="utf8")])
            wait_for(TITLE, submit("/resume"))
            child.write("\r")
            history = wait_for("Summarize the isolated fixture.", len(raw), timeout=10)
            check("resume_selects_an_existing_session", "/resume then Enter", True, "summarize the isolated fixture." in history)

            submit("/quit")
            expires = monotonic() + 9
            while child.isalive() and monotonic() < expires:
                sleep(0.1)
            check("quit_exits_and_preserves_session", "/quit", [False, True], [child.isalive(), original.is_file()])
        finally:
            if child is not None and child.isalive():
                child.terminate(force=True)
            server.shutdown()
            thread.join()
    return dict(terminal="WinPTY", pywinpty=version("pywinpty"), cases=cases)


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    for name in ("node", "cli", "shell"):
        parser.add_argument(name, type=Path)
    arguments = vars(parser.parse_args())
    print(json.dumps(exercise(**{name: path.resolve(strict=True) for name, path in arguments.items()})))
本例需在 Windows,Pi 1.5.0,Node.js 24.22.3,WinPTY、本机回环和 Git Bash。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows,Pi 1.5.0,Node.js 24.22.3,WinPTY、本机回环和 Git Bash。

入口文件:projects/pi-agent-appendix-slash-lab/terminal-slash-lab.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 terminal-slash-lab.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows,Pi 1.5.0,Node.js 24.22.3,WinPTY、本机回环和 Git Bash。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

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

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

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

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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