import assert from "node:assert/strict";
import { spawn, spawnSync } from "node:child_process";
import { mkdtemp, mkdir, readFile, readdir, realpath, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { basename, dirname, join, resolve } from "node:path";
import { createInterface } from "node:readline";
import { fileURLToPath } from "node:url";
const root = dirname(fileURLToPath(import.meta.url));
const cli = resolve(process.argv[2] || "");
assert(process.argv[2], "Supply the path to the pinned Pi CLI");
const moduleName = "harbor-note";
const base = await mkdtemp(join(tmpdir(), "mbsky-pi-"));
const agent = join(base, "config");
const work = join(base, "work");
const extension = resolve(process.argv[3] || join(root, "harbor_extension.ts"));
const env = Object.fromEntries(Object.entries(process.env).filter(([name]) =>
["systemroot","windir","comspec","path","pathext","appdata","localappdata","systemdrive"].includes(name.toLowerCase())));
Object.assign(env, { PI_CODING_AGENT_DIR: agent, PI_SKIP_VERSION_CHECK: "1", TEMP: base, TMP: base });
const cases = [];
function observe(name, input, operation, expected, actual) {
assert.deepEqual(actual, expected, name);
cases.push({name,input,operation,expected,actual});
}
function call(args) {
return spawnSync(process.execPath, [cli,...args], {cwd:work,env,encoding:"utf8",timeout:20000});
}
async function rpc(args, evaluate) {
const child = spawn(process.execPath,[cli,"--mode","rpc","--no-session","--no-skills","--no-tools","--no-mcp",...args],
{cwd:work,env,stdio:["pipe","pipe","pipe"]});
let diagnostics = "";
child.stderr.on("data",chunk => { diagnostics += chunk.toString(); });
const closed = new Promise(resolve => child.once("close", (code,signal) => resolve({code,signal})));
child.stdin.on("error", () => {});
const lines = createInterface({input:child.stdout});
const pending = new Map();
let counter = 0;
lines.on("line", line => {
let event;
try { event = JSON.parse(line); } catch { return; }
const match = pending.get(event.id);
if (event.type === "response" && match) {
pending.delete(event.id);
clearTimeout(match.timer);
match.resolve(event);
}
});
function request(type, data = {}) {
const id = "lab-" + (++counter);
return new Promise((resolve,reject) => {
const timer = setTimeout(() => {
pending.delete(id);
reject(new Error(`RPC did not respond to ${type}: ${diagnostics}`));
},12000);
pending.set(id,{resolve,timer});
child.stdin.write(JSON.stringify({id,type,...data})+"\n");
});
}
try {
return await evaluate(request);
} finally {
child.stdin.end();
const timer = setTimeout(() => child.kill(),6000);
await closed;
clearTimeout(timer);
}
}
try {
await mkdir(agent);
await mkdir(work);
await writeFile(join(agent,"settings.json"),JSON.stringify({defaultProjectTrust:"never"}));
const version = call(["--version"]);
const help = call(["--help"]);
const flags = ["--mode","--no-session","--no-tools","--no-mcp"];
observe("pi_native_cli_flags",["--version","--help"],"启动真实 CLI,核对版本和列出的本地隔离选项",
[0,"1.5.0",0,[true,true,true,true]],[version.status,version.stdout.trim(),help.status,flags.map(flag => help.stdout.includes(flag))]);
await rpc(["--no-extensions"], async request => {
const state = await request("get_state");
const messages = await request("get_messages");
const next = await request("new_session");
const again = await request("get_messages");
observe("pi_native_rpc_session",["get_state","get_messages","new_session","get_messages"],
"通过真实 JSON Lines 往返请求,观察空会话与新建状态",
[true,0,true,false,0],
[state.success,messages.data.messages.length,next.success,next.data.cancelled,again.data.messages.length]);
});
const project = join(work,".pi","extensions");
await mkdir(project,{recursive:true});
await writeFile(join(project,"harbor_extension.ts"),await readFile(extension));
const commands = result => result.data.commands.map(item => item.name);
await rpc([],async request => {
const listing = await request("get_commands");
observe("pi_native_untrusted_extension","defaultProjectTrust=never","项目扩展存在但不在 RPC 可用命令中",
[true,false],[listing.success,commands(listing).includes(moduleName)]);
});
await rpc(["--approve"],async request => {
const listing = await request("get_commands");
observe("pi_native_approved_extension","--approve 用于本站空白项目",
"临时许可后项目扩展出现在实际 RPC 命令列表",
[true,true],[listing.success,commands(listing).includes(moduleName)]);
});
await rpc(["--no-extensions","-e",extension],async request => {
const listing = await request("get_commands");
const listed = listing.data.commands.find(item => item.name === moduleName);
const outcome = await request("prompt",{message:"/harbor-note sealed"});
observe("pi_native_explicit_extension","显式加载本站扩展并执行 /harbor-note sealed",
"检查扩展命令的真实来源与本机独立目录文件字节",
[true,"extension",true,"sealed\n"],[listing.success,listed?.source,outcome.success,await readFile(join(work,"harbor-note.txt"),"utf8")]);
});
const sample = join(base,"sample-session.jsonl");
const exported = join(base,"sample-session.html");
const at = "2026-11-09T00:00:00.000Z";
const journal = [
{type:"session",version:3,id:"6cf949b1-d935-439e-ad68-45761abc888c",timestamp:at,cwd:work},
{type:"message",id:"a1",parentId:null,timestamp:at,message:{role:"user",content:"Harbor note for local export",timestamp:Date.parse(at)}},
{type:"message",id:"a2",parentId:"a1",timestamp:at,message:{role:"user",content:"Harbor branch B",timestamp:Date.parse(at)}},
{type:"message",id:"a3",parentId:"a1",timestamp:at,message:{role:"user",content:"Harbor branch C",timestamp:Date.parse(at)}},
].map(entry => JSON.stringify(entry)).join("\n")+"\n";
await writeFile(sample,journal);
const exportRun=call(["--export",sample,exported]);
assert.equal(exportRun.status,0,exportRun.stderr || exportRun.stdout);
const output=await readFile(exported,"utf8");
observe("pi_native_session_export","站内 3 版 JSONL 会话,两个条目同父节点",
"用真实 Pi 导出 HTML 并确认原会话字节未改变",
[0,true,true],[exportRun.status,/<html/i.test(output),(await readFile(sample,"utf8"))===journal]);
if (process.argv[4] && process.argv[5]) {
const python = resolve(process.argv[4]);
const server = resolve(process.argv[5]);
const siteDir = process.env.MBSKY_MCP_SITE;
const extras = siteDir ? ["--env","MBSKY_MCP_SITE="+siteDir] : [];
const add = call(["mcp","add","harbor","--env","PYTHONUTF8=1",...extras,"--",python,"-B",server]);
const listed = call(["mcp","list","--json"]);
assert.equal(add.status,0,add.stderr || add.stdout);
assert.equal(listed.status,0,listed.stderr || listed.stdout);
const info = JSON.parse(listed.stdout);
const row = (Array.isArray(info) ? info : info.servers).find(item => item.name === "harbor");
assert(row,JSON.stringify(info));
observe("pi_native_mcp_list","隔离配置中添加 stdio 服务器",
"连接真实 MCP 服务并枚举本站的只读工具",
[0,0,"harbor",true],[add.status,listed.status,row.name,JSON.stringify(row).includes("harbor_reference")]);
const remove = call(["mcp","remove","harbor"]);
const empty = call(["mcp","list","--json"]);
observe("pi_native_mcp_remove","仅从隔离配置移除 harbor",
"重新枚举确认服务与工具均不再可用",
[0,0,false],[remove.status,empty.status,empty.stdout.includes("harbor_reference")]);
}
const sessionFiles = await readdir(agent,{recursive:true});
observe("pi_native_no_session_files","--no-session","完成 RPC 会话和扩展操作后检查配置目录没有会话文件",
false,sessionFiles.some(file => file.endsWith(".jsonl")));
console.log(JSON.stringify({node:process.version,cases}));
} finally {
const target = await realpath(base);
assert.equal(dirname(target), await realpath(tmpdir()));
assert(basename(target).startsWith("mbsky-pi-"));
await rm(target,{recursive:true,force:true,maxRetries:2});
}
本例需在 Node.js 24、Pi 1.5.0、独立配置目录、Edge 与本地 MCP stdio。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Node.js 24、Pi 1.5.0、独立配置目录、Edge 与本地 MCP stdio。
入口文件:projects/ai-agent-pi/pi_rpc_lab.mjs
本地运行步骤快速上手
- 点击上方“保存源码”保存为
pi_rpc_lab.mjs,或下载右侧课程工程包。 - 确认本地已准备 Node.js 24、Pi 1.5.0、独立配置目录、Edge 与本地 MCP stdio。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联48章) · 含当前章节或实例 · mbskycom202612a3073.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a3097.zip