"""Reproduce a Pi installation from a cached package and lock, then remove it."""
import argparse
import json
import os
from pathlib import Path
import shutil
import subprocess
from tempfile import TemporaryDirectory
PKG = "@earendil-works/pi-coding-agent"
VERSION = "1.5.0"
ARCHIVE = f"earendil-works-pi-coding-agent-{VERSION}.tgz"
def observe(node, npm, inputs):
cases = []
def check(name, conditions, expected, actual):
if actual != expected:
raise RuntimeError(f"{name}: expected {expected!r}, got {actual!r}")
cases.append(dict(name=name, input=conditions, expected=expected, actual=actual, passed=True))
with TemporaryDirectory(prefix="mbsky-pi-offline-install-") as directory:
root = Path(directory)
app, cache, agent = (root / name for name in ("installed", "cache", "agent"))
for path in (app, cache, agent):
path.mkdir()
shutil.copyfile(inputs / ARCHIVE, root / ARCHIVE)
for name in ("package.json", "package-lock.json"):
shutil.copyfile(inputs / "installed" / name, app / name)
shutil.copytree(inputs / "cache" / "_cacache", cache / "_cacache")
user_rc, global_rc = root / "user.npmrc", root / "global.npmrc"
user_rc.touch()
global_rc.touch()
state = agent / "training-preferences.txt"
state.write_bytes(b"owned preference fixture\n")
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(PATH=str(node.parent) + os.pathsep + env.get("PATH", ""),
PI_CODING_AGENT_DIR=str(agent), PI_OFFLINE="1", PI_TELEMETRY="0", PI_SKIP_VERSION_CHECK="1",
NO_UPDATE_NOTIFIER="1")
def run(arguments):
completed = subprocess.run(arguments, cwd=app, env=env, capture_output=True, encoding="utf8",
errors="replace", timeout=115)
if completed.returncode:
raise RuntimeError(completed.stderr or completed.stdout)
return completed.stdout.strip()
def npm_run(*arguments):
return run([str(node), str(npm), *arguments, "--offline", "--ignore-scripts", "--no-audit",
"--no-fund", "--fetch-retries=0", "--cache=" + str(cache),
"--userconfig=" + str(user_rc), "--globalconfig=" + str(global_rc)])
runtime = run([str(node), "--version"])
major_minor_patch = tuple(map(int, runtime.removeprefix("v").split(".")))
check("node_version_meets_minimum", {"version": runtime}, True, major_minor_patch >= (22, 19, 0))
npm_version = npm_run("--version")
check("npm_version_queried", {"argv": ["--version"]}, True, len(npm_version.split(".")) == 3)
package_dir = app / "node_modules" / PKG
check("clean_directory", {"path": "installed/node_modules"}, False, package_dir.exists())
installed = npm_run("ci")
manifest = json.loads((package_dir / "package.json").read_bytes())
check("offline_npm_ci", {"archive": ARCHIVE, "mode": "offline and ignore-scripts"},
{"package": PKG, "version": VERSION, "engines": ">=22.19.0"},
{"package": manifest["name"], "version": manifest["version"], "engines": manifest["engines"]["node"]})
cli = package_dir / manifest["bin"]["pi"]
check("fresh_cli_version", {"entry": manifest["bin"]["pi"]}, VERSION, run([str(node), str(cli), "--version"]))
update = run([str(node), str(cli), "update", "--help"])
known = {flag: flag in update for flag in ("--self", "--all", "--models", "--force")}
check("update_help_lists_current_flags", {"argv": ["update", "--help"]}, dict.fromkeys(known, True), known)
removed = npm_run("uninstall", PKG)
new_manifest = json.loads((app / "package.json").read_bytes())
check("npm_uninstall_local_copy", {"package": PKG}, {"entry": False, "dependency": False},
{"entry": cli.exists(), "dependency": PKG in new_manifest.get("dependencies", {})})
check("config_dir_survives_uninstall", {"fixture": "training-preferences.txt"},
"owned preference fixture\n", state.read_bytes().decode("utf8"))
return dict(version=runtime, npm_version=npm_version, cases=cases,
npm_ci_stdout=installed, npm_uninstall_stdout=removed)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("node", type=Path)
parser.add_argument("npm_cli", type=Path)
parser.add_argument("cached_input_root", type=Path)
args = parser.parse_args()
print(json.dumps(observe(args.node.resolve(strict=True), args.npm_cli.resolve(strict=True),
args.cached_input_root.resolve(strict=True)), ensure_ascii=False))
本例需在 Windows、Python 3.12、Node.js 24.22.3、隔离 npm 缓存和固定 Pi 1.5.0 包。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows、Python 3.12、Node.js 24.22.3、隔离 npm 缓存和固定 Pi 1.5.0 包。
入口文件:projects/pi-agent-install-lab/offline-install.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
offline-install.py,或下载右侧课程工程包。 - 确认本地已准备 Windows、Python 3.12、Node.js 24.22.3、隔离 npm 缓存和固定 Pi 1.5.0 包。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联29章) · 含当前章节或实例 · mbskycom202612a267.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a277.zip