"""Local Pi diagnostics for command lookup, HTTP errors and session locations."""
from argparse import ArgumentParser
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from http.client import HTTPConnection
import json
import os
from pathlib import Path
import subprocess
from tempfile import TemporaryDirectory
from threading import Thread
from time import monotonic, sleep
REPLY = "Local diagnostic path works."
def observe(node, npm, cli, pwsh):
cases = []
def verify(name, inputs, expected, actual):
if expected != actual:
raise RuntimeError(f"{name}: expected {expected!r}, got {actual!r}")
cases.append(dict(name=name, input=inputs, expected=expected, actual=actual, passed=True))
class Probe(BaseHTTPRequestHandler):
def log_message(self, *_):
pass
def do_GET(self):
if self.path == "/delayed":
sleep(0.18)
self.send_response(200)
elif self.path == "/restricted" and self.headers.get("Authorization") != "Bearer teaching-only":
self.send_response(401)
else:
self.send_response(200)
self.send_header("Content-Length", "2")
self.end_headers()
self.wfile.write(b"ok")
def do_POST(self):
assert self.path == "/v1/chat/completions"
payload = json.loads(self.rfile.read(int(self.headers["Content-Length"])))
if self.headers.get("Authorization") != "Bearer teaching-only":
self.send_error(401)
return
def frame(delta, reason):
return dict(id="course-diagnostic", object="chat.completion.chunk", created=1, model=payload["model"],
choices=[dict(index=0, delta=delta, finish_reason=reason)])
events = [frame({"role": "assistant", "content": REPLY}, None), frame({}, "stop")]
body = ("".join("data: " + json.dumps(event) + "\n\n" for event in events) + "data: [DONE]\n\n").encode()
self.send_response(200)
self.send_header("Content-Type", "text/event-stream")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
with TemporaryDirectory(prefix="mbsky-pi-diagnostics-") as temp, ThreadingHTTPServer(("127.0.0.1", 0), Probe) as server:
root = Path(temp)
profile, old, new, prefix = (root / name for name in ("profile", "sessions-a", "sessions-b", "npm-prefix"))
for folder in (profile, old, new, prefix):
folder.mkdir()
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(profile), PI_OFFLINE="1", PI_SKIP_VERSION_CHECK="1", PI_TELEMETRY="0")
kwargs = dict(cwd=root, env=env, capture_output=True, encoding="utf8", input="", timeout=18)
def execute(args, **overrides):
return subprocess.run([str(arg) for arg in args], **(kwargs | overrides))
def success(args):
result = execute(args)
if result.returncode:
raise RuntimeError(result.stderr or result.stdout)
return result.stdout.strip()
node_version = success([node, "--version"])
engine = json.loads((cli.parents[2] / "package.json").read_text(encoding="utf8"))["engines"]["node"]
version_tuple = lambda text: tuple(map(int, text.split(".")))
verify("node_satisfies_package_engine", {"node": node_version, "packageEngine": engine}, [True, True],
[engine.startswith(">="), version_tuple(node_version[1:]) >= version_tuple(engine[2:].strip())])
actual_prefix = success([node, npm, "--offline", "--prefix", prefix, "prefix", "-g"])
verify("npm_reports_isolated_global_prefix", "npm --offline --prefix <temporary> prefix -g", True,
Path(actual_prefix).resolve() == prefix.resolve())
# Windows npm shims normally live directly inside the global prefix.
shim = prefix / "pi.cmd"
shim.write_text(f'@echo off\n"{node}" "{cli}" %*\n', encoding="utf8")
script = 'if (Get-Command pi.cmd -ErrorAction SilentlyContinue) {"found"} else {"absent"}'
minimal = dict(env, PATH=str(root))
augmented = dict(env, PATH=str(prefix) + os.pathsep + str(root))
without = execute([pwsh, "-NoProfile", "-Command", script], env=minimal)
with_path = execute([pwsh, "-NoProfile", "-Command", script], env=augmented)
verify("powershell_path_absence_and_presence", "Get-Command with two disposable PATH values",
["absent", "found"], [without.stdout.strip(), with_path.stdout.strip()])
command = execute([pwsh, "-NoProfile", "-Command", "pi.cmd --version"], env=augmented)
verify("located_shim_runs_fixed_pi", "pi.cmd --version", [0, "1.5.0"], [command.returncode, command.stdout.strip()])
thread = Thread(target=server.serve_forever, daemon=True)
thread.start()
try:
def inspect_http(path, key=None):
connection = HTTPConnection("127.0.0.1", server.server_port, timeout=5)
try:
started = monotonic()
headers = {} if key is None else {"Authorization": "Bearer " + key}
connection.request("GET", path, headers=headers)
with connection.getresponse() as reply:
first_byte_seconds = monotonic() - started
return reply.status, reply.read().decode(), first_byte_seconds
finally:
connection.close()
missing = inspect_http("/restricted")
valid = inspect_http("/restricted", "teaching-only")
delayed = inspect_http("/delayed")
verify("http_status_separates_auth_from_reachability", ["same host without credentials", "synthetic key"],
[401, 200, "ok"], [missing[0], valid[0], valid[1]])
verify("slow_first_byte_can_have_success_status", "handler adds 180 ms before responding", [200, True],
[delayed[0], delayed[2] >= 0.15])
provider = {"baseUrl": f"http://127.0.0.1:{server.server_port}/v1", "api": "openai-completions",
"apiKey": "teaching-only", "models": [{"id": "diagnostic-model"}]}
(profile / "models.json").write_text(json.dumps({"providers": {"course-check": provider}}), encoding="utf8")
(profile / "settings.json").write_text(json.dumps({"compaction": {"enabled": False}}), encoding="utf8")
disks = ["--offline", "--no-tools", "--no-extensions", "--no-mcp", "--no-skills", "--no-themes",
"--no-prompt-templates", "--no-context-files", "--no-approve"]
base = [node, cli, *disks, "--model", "course-check/diagnostic-model"]
first = success([*base, "--session-dir", old, "--name", "Owned diagnostic follow-up",
"--print", "Write the first marker."])
session, = old.glob("*.jsonl")
original = session.read_bytes()
second = success([*base, "--session-dir", new, "--print", "Write a separate marker."])
verify("changed_session_dir_keeps_original_and_changes_listing", ["sessions-a", "sessions-b"],
[REPLY, REPLY, 1, 1, True], [first, second, len(list(old.glob("*.jsonl"))),
len(list(new.glob("*.jsonl"))), session.read_bytes() == original])
opened = success([*base, "--session-dir", new, "--session", session, "--print", "Append to original."])
verify("explicit_session_path_recovers_prior_history", "absolute session path", [REPLY, True, True],
[opened, b"Write the first marker." in session.read_bytes(),
b"Append to original." in session.read_bytes()])
verify("searchable_fixture_model_is_listed", "pi --list-models course-check", True,
"diagnostic-model" in success([node, cli, *disks, "--list-models", "course-check"]))
finally:
server.shutdown()
thread.join()
return {"nodeVersion": node_version, "cases": cases}
if __name__ == "__main__":
arguments = ArgumentParser(description=__doc__)
for name in ("node", "npm", "cli", "pwsh"):
arguments.add_argument(name, type=Path)
paths = vars(arguments.parse_args())
print(json.dumps(observe(**{name: path.resolve(strict=True) for name, path in paths.items()})))
本例需在 Windows、固定 Pi 与 npm、临时 PATH 和 127.0.0.1。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows、固定 Pi 与 npm、临时 PATH 和 127.0.0.1。
入口文件:projects/pi-agent-appendix-troubleshooting-lab/diagnose-local.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
diagnose-local.py,或下载右侧课程工程包。 - 确认本地已准备 Windows、固定 Pi 与 npm、临时 PATH 和 127.0.0.1。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a265.zip
课程关联工程包(登记关联29章) · 含当前章节或实例 · mbskycom202612a267.zip