import assert from "node:assert/strict";
import {execFile, spawn} from "node:child_process";
import {mkdir, mkdtemp, readFile, rm, writeFile} from "node:fs/promises";
import {tmpdir} from "node:os";
import {basename, dirname, join, resolve} from "node:path";
import {pathToFileURL} from "node:url";
import {createInterface} from "node:readline";
import {promisify} from "node:util";
const modules = process.argv[2];
if (!modules) throw new Error("Supply the installed node_modules location.");
const pkg = resolve(modules, "@earendil-works", "pi-coding-agent");
const {version, bin} = JSON.parse(await readFile(join(pkg, "package.json"), "utf8"));
const cli = join(pkg, bin.pi);
const {parseArgs} = await import(pathToFileURL(join(pkg, "dist/cli/args.js")));
const {KeybindingsManager} = await import(pathToFileURL(join(pkg, "dist/core/keybindings.js")));
const {createPowerShellToolDefinition} = await import(pathToFileURL(join(pkg, "dist/core/tools/powershell.js")));
const {getShellConfig, getPowerShellConfig} = await import(pathToFileURL(join(pkg, "dist/utils/shell.js")));
const base = resolve(tmpdir());
const root = await mkdtemp(join(base, "mbsky-pi-platform-"));
assert.equal(dirname(resolve(root)), base);
assert.ok(basename(root).startsWith("mbsky-pi-platform-"));
const exec = promisify(execFile);
const cases = [];
function check(name, input, expected, actual) {
assert.deepStrictEqual(actual, expected, name);
cases.push({name, input, expected, actual, passed: true});
}
const selected = Object.fromEntries(["PATH", "SystemRoot", "WINDIR", "COMSPEC", "PATHEXT", "TEMP", "TMP",
"USERPROFILE", "LOCALAPPDATA", "APPDATA", "ProgramFiles", "ProgramFiles(x86)"].filter(k => k in process.env).map(k => [k, process.env[k]]));
const profile = join(root, "profile");
const project = join(root, "work");
const env = {...selected, PI_CODING_AGENT_DIR: profile, PI_OFFLINE: "1", PI_SKIP_VERSION_CHECK: "1", PI_TELEMETRY: "0"};
const writeJson = (file, value) => writeFile(file, JSON.stringify(value, null, 2) + "\n");
async function observeBash(command, settings) {
await writeJson(join(profile, "settings.json"), settings);
const args = ["--mode", "rpc", "--no-session", "--no-extensions", "--no-mcp", "--no-context-files",
"--no-skills", "--no-themes", "--no-prompt-templates", "--no-builtin-tools",
"--provider", "platform", "--model", "platform-test"];
const child = spawn(process.execPath, [cli, ...args], {cwd: project, env, windowsHide: true, stdio: ["pipe","pipe","pipe"]});
const closed = new Promise(done => child.once("close", done));
let errors = "";
child.stderr.on("data", chunk => errors += chunk);
child.stdin.on("error", () => {});
const timeout = setTimeout(() => child.kill(), 10000);
const stream = createInterface({input: child.stdout});
try {
child.stdin.write(JSON.stringify({id: "bash", type: "bash", command}) + "\n");
for await (const row of stream) {
const msg = JSON.parse(row);
if (msg.type === "response" && msg.id === "bash") return msg;
}
throw new Error(errors);
} finally {
child.stdin.end();
await closed;
clearTimeout(timeout);
stream.close();
}
}
try {
assert.equal(process.platform, "win32");
await mkdir(profile);
await mkdir(project);
await writeJson(join(profile, "models.json"), {providers: {platform: {baseUrl: "http://127.0.0.1:1/v1",
api: "openai-completions", apiKey: "fixture-only", models: [{id: "platform-test"}]}}});
const cliVersion = await exec(process.execPath, [cli, "--version"], {cwd: project, env, windowsHide: true, timeout: 7000});
check("native_windows_cli_reports_pinned_version", {mode: "native Windows"}, ["win32", "1.5.0"],
[process.platform, cliVersion.stdout.trim()]);
const shell = getShellConfig();
const gitPath = (await exec("where.exe", ["git.exe"], {cwd: project, env, windowsHide: true, timeout: 5000})).stdout.trim().split(/\r?\n/)[0];
const gitBash = join(dirname(dirname(gitPath)), "bin", "bash.exe");
const explicit = await observeBash("printf '%s' 'WINDOWS BASH READY'", {shellPath: gitBash});
check("native_rpc_bash_runs_explicit_git_bash", {source: "native RPC bash", explicitShell: "Git Bash"},
[true, 0, "WINDOWS BASH READY"], [explicit.success, explicit.data.exitCode, explicit.data.output.trim()]);
await writeFile(join(project, "gallery-env.sh"), "shopt -s expand_aliases\nalias gallery_label='printf GALLERY_ALIAS_READY'\n");
const without = await observeBash("gallery_label", {shellPath: gitBash});
const withAlias = await observeBash("gallery_label", {shellPath: gitBash, shellCommandPrefix: "source ./gallery-env.sh"});
check("explicit_shell_and_prefix_enable_noninteractive_alias", {shellPathConfigured: true, prefix: "source ./gallery-env.sh"},
[127, 0, "GALLERY_ALIAS_READY"], [without.data.exitCode, withAlias.data.exitCode, withAlias.data.output.trim()]);
const powerShell = getPowerShellConfig();
const tool = createPowerShellToolDefinition(project);
const result = await tool.execute("platform-fixture", {command: "Write-Output ('GALLERY_PS_' + $PSVersionTable.PSEdition)"});
const shellText = result.content.find(item => item.type === "text").text.trim();
check("native_powershell_tool_reports_actual_edition", {tool: "powershell", command: "Write-Output"},
["GALLERY_PS_Core", true], [shellText, /pwsh\.exe$/i.test(powerShell.shell)]);
const cliArgs = parseArgs(["--name", "Exhibit label", "-c", "-r", "--fork", "example.jsonl",
"--no-session", "--tools", "read,grep,find,ls", "-p", "Describe a display"]);
check("native_parser_supports_session_and_tool_alias_targets", {parserInput: "flags for independent shell shortcuts"},
["Exhibit label", true, true, "example.jsonl", true, ["read","grep","find","ls"], true, ["Describe a display"]],
[cliArgs.name, cliArgs.continue, cliArgs.resume, cliArgs.fork, cliArgs.noSession, cliArgs.tools, cliArgs.print, cliArgs.messages]);
const keys = new KeybindingsManager();
check("native_windows_stock_keybindings_distinguish_terminal_settings", {platform: "Windows"},
[["alt+v"],["shift+enter","ctrl+j"],["ctrl+q"],["alt+q"],["ctrl+z"]],
["app.clipboard.pasteImage","tui.input.newLine","app.message.followUp","app.message.dequeue","tui.editor.undo"].map(id => keys.getKeys(id)));
const color = await observeBash("printf '%s' \"${COLORTERM:-unset}\"", {shellPath: gitBash,
shellCommandPrefix: "export COLORTERM=truecolor"});
check("color_environment_probe_reports_declaration", {shellEnv: "COLORTERM=truecolor"},
[0,"truecolor"], [color.data.exitCode,color.data.output.trim()]);
const availability = {};
for (const [name,args] of [["wsl.exe",["--list","--quiet"]],["tmux",["-V"]]]) {
try {
const probed = await exec(name,args,{cwd:project,env,windowsHide:true,timeout:4500,encoding:"buffer"});
availability[name] = {exitCode: 0, discoveredDistributions: name === "wsl.exe"
? probed.stdout.toString("utf16le").split(/\r?\n/).filter(Boolean).length : undefined};
} catch (error) {
availability[name] = {exitCode: typeof error.code === "number" ? error.code : null, reason: typeof error.code==="string" ? error.code : null,
timedOut:Boolean(error.killed)};
}
}
process.stdout.write(JSON.stringify({nodeVersion:process.version, packageVersion:version,
os:process.platform, selectedShells:{autoBash:shell.shell,explicitGitBash:gitBash,powershell:powerShell.shell}, cases, availability}) + "\n");
} finally {
await rm(root,{recursive:true,force:true});
}
本例需在 Windows、Node.js 24.22.3、Pi 1.5.0、Git Bash、PowerShell、PyWinPTY 3.1.2。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows、Node.js 24.22.3、Pi 1.5.0、Git Bash、PowerShell、PyWinPTY 3.1.2。
入口文件:projects/pi-agent-platforms-lab/windows-platforms-extended.mjs
本地运行步骤快速上手
- 点击上方“保存源码”保存为
windows-platforms-extended.mjs,或下载右侧课程工程包。 - 确认本地已准备 Windows、Node.js 24.22.3、Pi 1.5.0、Git Bash、PowerShell、PyWinPTY 3.1.2。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a284.zip
课程关联工程包(登记关联29章) · 含当前章节或实例 · mbskycom202612a267.zip