Pi Agent 包管理
从本地、npm 或 Git 安装自编资源,并验证配置范围、固定版本和清单过滤。
学完这一章,你能够
- 从本地、npm 或 Git 安装自编资源,并验证配置范围、固定版本和清单过滤。
把四类资源装入一个包
一个 Pi 包可以携带扩展、技能、提示词模板和主题。团队可通过 npm 或 Git 分发,也可以从本地目录加载。本站实验用临时项目和自编展品资源,比较包从安装到资源启用的过程。
安装和移除命令会更新对应范围的设置。pi list 查看已配置的包。安装输出随版本及资源而变化,可结合设置文件和实际发现的资源确认。下面的图按本地路径、回环 npm 和回环 Git 的实测行为绘制。

区分 npm、Git 与本地路径
npm: 前缀交给 npm 包管理器。精确版本与版本范围有不同的更新结果。本站的回环仓库同时提供 1.0.0 与 2.0.0,安装精确的 1.0.0 并更新后保持原版。包安装在相应范围的 npm 目录。
Git 来源可以用 HTTPS 或 SSH。SCP 风格地址使用 git: 前缀。分发时可指定标签、提交或分支,更新时按配置重新解析原引用。固定标签或提交与可移动分支的含义不同。本地回环实验安装 v1 标签并检查更新后仍使用 v1,默认分支已到 2.0.0。
本地包直接使用解析后的路径,无需复制。通过 CLI 安装相对路径时以当前工作目录定位,再写入对应范围的配置。手写配置中的相对路径以该配置文件所在目录为基准。-e 可为一次运行加载本地包。
清单、约定目录与画廊资料
资源符合约定目录时可用自动发现。需要缩小发现范围或调整布局时,给 package.json 写 pi 字段并指定路径,路径以包根目录为准。本站显式清单只允许两份 TS 文件,约定发现的对照包还会找到额外 JS 文件。
npm 包可添加 pi-package 关键词供官方包目录发现。image 与 video 是可选预览元数据。是否展示取决于实际发布与索引,本站实例仅用私有合成包验证清单读取。
按资源类型筛选
packages 可写源字符串,也可写包含 source 的对象。用户配置用于该代理的多个项目,项目配置由信任判定控制。-l 把声明写入项目设置。对某个资源键写 [] 会关闭该类型,省略则在已有清单范围内保留默认发现。
在包根目录按路径选择。先用 glob 指定匹配,再用 !pattern 排除。+path 可以强制包含已有候选,-path 可以强制排除。只写 +path 时默认候选仍可保留。站内实验先排除所有主题,再用 + 把一个主题加回。技能路径可指向包内技能目录。
声明依赖与配置范围
Pi 管理的 npm 与 Git 包会按所用包管理器安装依赖,研发依赖和宿主提供的 peer 依赖遵照相应安装规则。运行所需的普通库记录在 dependencies,随发布归档的依赖可按 npm 方式声明 bundledDependencies。Pi 自带的库作为 peerDependencies,避免在扩展内打包重复运行时。本站观察到管理安装未复制 typebox peer。
pi config 打开资源选择界面,可用 Tab 在用户与项目范围间切换;pi config -l 从项目范围打开。本站在临时 WinPTY 中实际验证了两种进入方式。项目范围需要符合项目信任条件。
Pi 用归一的包身份合并项目和用户声明。通常项目条目整体优先。同一包的项目条目设 autoload: false 时,只把该条列出的资源偏好叠加到用户声明。本站分别验证覆盖和增量模式。
包管理命令
| 命令 | 用途 | 示例或范围 |
|---|---|---|
| pi install <source> | 安装指定来源,写入相应范围的设置。 | pi install ./lesson-kit,项目范围加 -l。 |
| pi remove <source> | 移除该范围的包声明,管理安装的缓存按类型处理。 | pi remove -l ./lesson-kit |
| pi uninstall <source> | remove 的别名。 | pi uninstall ./lesson-kit |
| pi list | 检查当前配置可见的已安装包。 | 分别核对用户和项目声明。 |
| pi update --all | 一并更新 Pi 本体与配置包。 | 本机实验只维护现有固定版的合成包。 |
| pi update --extensions | 维护已配置的包,按来源和固定约束处理。 | 只在临时配置验证固定 Git 标签。 |
| pi update <source> | 维护一个配置包。 | 指定精确版本时仍遵循版本约束。 |
约定目录及发现规则
| 目录 | 资源 |
|---|---|
| extensions/ | 发现 .ts 和 .js 扩展。可用 pi.extensions 指定子集。 |
| skills/ | 发现带 SKILL.md 的技能目录和顶层独立 Markdown 技能。 |
| prompts/ | 读取 Markdown 提示词模板。 |
| themes/ | 发现 JSON 主题定义。 |
资源过滤规则
| 写法 | 含义 | 观察 |
|---|---|---|
| 省略类型字段 | 保留该类型默认发现。 | 省略 skills 时继续使用包声明。 |
| 设置空数组 | 关闭整个资源类型。 | prompts: [] 后示例模板未加载。 |
| !pattern | 排除匹配的资源。 | !extensions/legacy.ts 排除遗留入口。 |
| +path | 强制启用一个已允许的路径。 | +themes/ocean.json 可加回被 glob 排除的主题。 |
| -path | 强制排除指定路径。 | -skills/internal 禁用该目录对应的内部技能。 |
扩展宿主提供的依赖
| 包名 | 用途 |
|---|---|
| @earendil-works/pi-ai | 提供模型接口类型和辅助函数。 |
| @earendil-works/pi-agent-core | 提供代理工作循环与数据结构。 |
| @earendil-works/pi-coding-agent | 提供 Pi 会话和扩展接口。 |
| @earendil-works/pi-tui | 提供终端组件和渲染接口。 |
| typebox | 声明工具参数的模式,包清单声明为 peer。 |
各来源的去重身份
| 来源 | 身份依据 |
|---|---|
| npm | 用包名识别同一个包,版本另作约束。 |
| Git | 用规范化的主机名和仓库路径,ref 另作版本约束。 |
| 本地路径 | 用解析后的绝对路径,解析基准随配置范围而定。 |
用临时资源包验证安装范围和过滤
import assert from "node:assert/strict";
import {execFile} from "node:child_process";
import {mkdir, mkdtemp, readFile, readdir, rm, writeFile} from "node:fs/promises";
import {createHash} from "node:crypto";
import {createServer} from "node:http";
import {tmpdir} from "node:os";
import {basename, dirname, join, relative, resolve, sep} from "node:path";
import {pathToFileURL} from "node:url";
import {promisify} from "node:util";
const [moduleArg, npmArg] = process.argv.slice(2);
if (!moduleArg || !npmArg) throw new Error("Supply the installed node_modules and npm-cli.js paths.");
const npm = resolve(npmArg);
const pkg = resolve(moduleArg, "@earendil-works", "pi-coding-agent");
const {version, bin} = JSON.parse(await readFile(join(pkg, "package.json"), "utf8"));
const {DefaultPackageManager} = await import(pathToFileURL(join(pkg, "dist/core/package-manager.js")));
const {SettingsManager} = await import(pathToFileURL(join(pkg, "dist/core/settings-manager.js")));
const cli = join(pkg, bin.pi);
const runFile = promisify(execFile);
const base = resolve(tmpdir());
const root = await mkdtemp(join(base, "mbsky-pi-packages-"));
assert.equal(dirname(resolve(root)), base);
assert.ok(basename(root).startsWith("mbsky-pi-packages-"));
const cases = [];
function check(name, input, expected, actual) {
assert.deepStrictEqual(actual, expected, name);
cases.push({name, input, expected, actual, passed: true});
}
const npmName = "mbsky-gallery-fixture";
const servedTar = new Map();
const observedRequests = [];
const envKeys = ["PATH", "SystemRoot", "WINDIR", "COMSPEC", "PATHEXT", "TEMP", "TMP", "USERPROFILE", "LOCALAPPDATA", "APPDATA"];
const env = Object.fromEntries(envKeys.filter(key => key in process.env).map(key => [key, process.env[key]]));
const project = join(root, "work");
const profile = join(root, "profile");
const gitSource = join(root, "git-fixture");
const gitStore = join(gitSource, ".git");
const gitRequest = "/gallery/repository.git/";
const config = join(profile, "settings.json");
const projectConfig = join(project, ".pi", "settings.json");
const npmConfig = join(root, "npmrc");
const npmGlobalConfig = join(root, "npm-global");
const gitConfig = join(root, "gitconfig");
let address;
const server = createServer(async (req, res) => {
const path = new URL(req.url, address).pathname;
observedRequests.push(path);
if (req.method !== "GET") return res.writeHead(405).end();
if (path === "/" + npmName) {
const items = Object.fromEntries([...servedTar].map(([key, entry]) => [key, entry.metadata]));
res.writeHead(200, {"Content-Type": "application/json"});
return res.end(JSON.stringify({name: npmName, "dist-tags": {latest: "2.0.0"}, versions: items}));
}
const tar = [...servedTar.values()].find(entry => path === entry.path);
if (tar) {
res.writeHead(200, {"Content-Type": "application/octet-stream"});
return res.end(tar.bytes);
}
if (path.startsWith(gitRequest)) {
const tail = path.slice(gitRequest.length);
if (tail !== "HEAD" && tail !== "info/refs" && !/^objects\/(?:info\/packs|[a-f0-9]{2}\/[a-f0-9]{38}|pack\/pack-[a-f0-9]{40}\.(?:pack|idx))$/.test(tail)) {
return res.writeHead(404).end();
}
try {
const artifact = await readFile(join(gitStore, tail));
res.writeHead(200, {"Content-Type": "application/octet-stream"});
return res.end(artifact);
} catch (error) {
if (error.code !== "ENOENT") return res.writeHead(500).end();
}
}
res.writeHead(404).end();
});
const words = text => text.replace(/\s+/g, " ");
async function writeJSON(path, value) {
await writeFile(path, JSON.stringify(value, null, 2) + "\n");
}
async function settingsAt(path) {
const raw = await readFile(path, "utf8").catch(error => {
if (error.code === "ENOENT") return "{}";
throw error;
});
return JSON.parse(raw);
}
const command = (executable, argv, cwd, extras = {}) =>
runFile(executable, argv, {cwd, env: {...env, ...extras}, windowsHide: true, timeout: 22000, encoding: "utf8"});
const pi = (argv, extras) => command(process.execPath, [cli, ...argv], project, extras);
const git = argv => command("git", argv, gitSource);
const provider = scope => new DefaultPackageManager({
cwd: project, agentDir: profile, settingsManager: SettingsManager.create(project, profile, {projectTrusted: scope}),
});
const filter = (state, key) => state[key].filter(entry => entry.enabled).map(entry => basename(entry.path)).sort();
try {
await mkdir(join(project, ".pi"), {recursive: true});
for (const dir of [profile, gitSource]) await mkdir(dir);
await new Promise(done => server.listen(0, "127.0.0.1", done));
address = "http://127.0.0.1:" + server.address().port;
for (const file of [npmConfig, npmGlobalConfig, gitConfig]) await writeFile(file, "");
Object.assign(env, {
PI_CODING_AGENT_DIR: profile, PI_OFFLINE: "0", PI_SKIP_VERSION_CHECK: "1", PI_TELEMETRY: "0",
npm_config_userconfig: npmConfig, npm_config_globalconfig: npmGlobalConfig, npm_config_registry: address + "/",
npm_config_cache: join(root, "npm-cache"), npm_config_ignore_scripts: "true", npm_config_audit: "false",
npm_config_fund: "false", npm_config_fetch_retries: "0", npm_config_update_notifier: "false",
GIT_CONFIG_GLOBAL: gitConfig, GIT_CONFIG_NOSYSTEM: "1", GIT_TERMINAL_PROMPT: "0", GIT_ALLOW_PROTOCOL: "http",
});
const settingsDefaults = {npmCommand: [process.execPath, npm], defaultProjectTrust: "always"};
await writeJSON(config, settingsDefaults);
const npmVersion = (await command(process.execPath, [npm, "--version"], root)).stdout.trim();
const kit = join(project, "lesson-kit");
const ordinary = join(project, "ordinary-kit");
await mkdir(kit);
await mkdir(ordinary);
const extensionCode = name => "export default function (pi) { pi.registerCommand(" + JSON.stringify(name) +
", {description:'Gallery fixture', handler: async (_args, ctx) => ctx.ui.notify('Gallery fixture ready','info')}); }\n";
async function fixture(folder) {
for (const sub of ["extensions", "skills/catalog-note", "skills/internal", "prompts", "themes"]) {
await mkdir(join(folder, sub), {recursive: true});
}
await writeFile(join(folder, "extensions", "main.ts"), extensionCode("gallery-package"));
await writeFile(join(folder, "extensions", "legacy.ts"), extensionCode("gallery-legacy"));
await writeFile(join(folder, "extensions", "extra.js"), extensionCode("gallery-extra"));
for (const name of ["catalog-note", "internal"]) {
await writeFile(join(folder, "skills", name, "SKILL.md"), "---\nname: " + name +
"\ndescription: Local gallery teaching fixture.\n---\n\nUse the exhibit worksheet.\n");
}
await writeFile(join(folder, "skills", "standalone.md"), "---\nname: standalone\ndescription: Standalone gallery skill.\n---\n\nList the mock labels.\n");
await writeFile(join(folder, "prompts", "overview.md"), "---\ndescription: Gallery exercise prompt\n---\n\nWrite a museum label.\n");
await writeJSON(join(folder, "themes", "ocean.json"), {name: "ocean"});
await writeJSON(join(folder, "themes", "sand.json"), {name: "sand"});
}
await fixture(kit);
await fixture(ordinary);
const manifest = {name: "gallery-kit", version: "1.0.0", private: true, keywords: ["pi-package"],
peerDependencies: {typebox: "*"}, pi: {extensions: ["./extensions/main.ts", "./extensions/legacy.ts"],
skills: ["./skills"], prompts: ["./prompts"], themes: ["./themes"],
image: "https://example.invalid/gallery.png", video: "https://example.invalid/gallery.mp4"}};
await writeJSON(join(kit, "package.json"), manifest);
await writeJSON(join(ordinary, "package.json"), {name: "ordinary-gallery", version: "1.0.0", private: true});
await pi(["install", "./lesson-kit"]);
const user = await settingsAt(config);
const list = await pi(["list"]);
const resolved = await provider(true).resolve();
check("local_install_persists_and_resolves_original_path", {cli: "install ./lesson-kit"},
[1, true, true], [user.packages.length, words(list.stdout).includes("lesson-kit"),
resolved.extensions.every(entry => dirname(dirname(resolve(entry.path))) === kit)]);
check("explicit_manifest_limits_each_resource_class", {manifest: true},
[["legacy.ts","main.ts"], ["SKILL.md","SKILL.md","standalone.md"], ["overview.md"], ["ocean.json","sand.json"]],
[filter(resolved, "extensions"), filter(resolved, "skills"), filter(resolved, "prompts"), filter(resolved, "themes")]);
const conventional = await provider(true).resolveExtensionSources([ordinary], {temporary: true});
check("conventional_package_discovers_ts_js_skills_prompts_themes", {piManifest: false},
[["extra.js","legacy.ts","main.ts"], ["SKILL.md","SKILL.md","standalone.md"], ["overview.md"], ["ocean.json","sand.json"]],
[filter(conventional, "extensions"), filter(conventional, "skills"), filter(conventional, "prompts"), filter(conventional, "themes")]);
await pi(["install", "-l", "./lesson-kit"]);
const projectSettings = await settingsAt(projectConfig);
const projectInstall = await provider(true).resolve();
const untrusted = await provider(false).resolve();
check("project_install_writes_project_settings_and_uses_project_scope", {cli: "install -l"},
[1, ["project", "project"], ["user", "user"]], [projectSettings.packages.length,
projectInstall.extensions.map(entry => entry.metadata.scope), untrusted.extensions.map(entry => entry.metadata.scope)]);
const activeSettings = {...settingsDefaults, packages: [kit]};
await writeJSON(config, activeSettings);
await writeJSON(projectConfig, {packages: [{source: "../lesson-kit", extensions: ["extensions/*.ts", "!extensions/legacy.ts"],
prompts: [], themes: ["+themes/ocean.json"], skills: ["skills/**", "-skills/internal"]}]});
const filtered = await provider(true).resolve();
const skillFolders = filtered.skills.filter(entry => entry.enabled).map(entry => basename(dirname(entry.path))).sort();
check("project_filters_paths_and_respects_manifest", {filters: ["glob", "!", "[]", "+", "-"]},
[["main.ts"], [], ["ocean.json","sand.json"], ["catalog-note","skills"]],
[filter(filtered, "extensions"), filter(filtered, "prompts"), filter(filtered, "themes"), skillFolders]);
await writeJSON(projectConfig, {packages: [{source: "../lesson-kit", themes: ["!themes/*.json", "+themes/ocean.json"]}]});
const forced = await provider(true).resolve();
check("plus_path_forces_allowed_candidate_after_glob_exclusion", {filter: ["!themes/*.json", "+themes/ocean.json"]},
["ocean.json"], filter(forced, "themes"));
const deltaSource = {source: "../lesson-kit", autoload: false, extensions: ["-extensions/legacy.ts"]};
await writeJSON(projectConfig, {packages: [deltaSource]});
const delta = await provider(true).resolve();
check("autoload_false_overlays_global_resource_settings", {scope: "project", autoload: false},
[["main.ts"],["overview.md"],["ocean.json","sand.json"]],
[filter(delta, "extensions"),filter(delta, "prompts"),filter(delta, "themes")]);
const manager = provider(true);
check("package_identity_uses_name_normalized_url_or_absolute_path", {kinds: ["npm","git","local"]},
[true,true,true], [
manager.getPackageIdentity("npm:" + npmName + "@1.0.0") === manager.getPackageIdentity("npm:" + npmName + "@2.0.0"),
manager.getPackageIdentity("git:https://example.invalid/gallery/example.git@v1") ===
manager.getPackageIdentity("git:git@example.invalid:gallery/example.git@v2"),
manager.getPackageIdentity("../lesson-kit", "project") === manager.getPackageIdentity(kit, "user"),
]);
await pi(["remove", "-l", "./lesson-kit"]);
await pi(["uninstall", "./lesson-kit"]);
check("remove_and_uninstall_clear_only_declarations", {cli: ["remove -l","uninstall"]},
[0, 0, true], [(await settingsAt(config)).packages?.length ?? 0,
(await settingsAt(projectConfig)).packages?.length ?? 0, (await readdir(kit)).includes("package.json")]);
for (const version of ["1.0.0", "2.0.0"]) {
const tarFolder = join(root, "npm-" + version);
await mkdir(join(tarFolder, "extensions"), {recursive: true});
const localManifest = {name: npmName, version, peerDependencies: {typebox: "*"}, files: ["extensions"],
pi: {extensions: ["extensions/main.ts"]}};
await writeJSON(join(tarFolder, "package.json"), localManifest);
await writeFile(join(tarFolder, "extensions", "main.ts"), extensionCode("gallery-npm"));
await command(process.execPath, [npm, "pack", "--ignore-scripts"], tarFolder,
{npm_config_cache: join(root, "packing-cache")});
const tarName = npmName + "-" + version + ".tgz";
const bytes = await readFile(join(tarFolder, tarName));
const path = "/" + npmName + "/-/" + tarName;
servedTar.set(version, {path, bytes, metadata: {...localManifest,
dist: {tarball: address + path, shasum: createHash("sha1").update(bytes).digest("hex"),
integrity: "sha512-" + createHash("sha512").update(bytes).digest("base64")}}});
}
const npmSource = "npm:" + npmName + "@1.0.0";
const configured = (await command(process.execPath, [npm, "config", "get", "registry"], root)).stdout.trim();
assert.equal(configured, address + "/");
await pi(["install", npmSource]);
const npmManifest = join(profile, "npm", "node_modules", npmName, "package.json");
const npmVersionBefore = (await settingsAt(npmManifest)).version;
await pi(["update", npmSource]);
const npmVersionAfter = (await settingsAt(npmManifest)).version;
const rootInstalledModules = await readdir(join(profile, "npm", "node_modules"));
check("real_npm_install_and_pinned_update_use_loopback_registry", {fixtureVersions: ["1.0.0","2.0.0"], requested: "1.0.0"},
["1.0.0","1.0.0",true,false,false], [npmVersionBefore, npmVersionAfter,
observedRequests.includes(servedTar.get("1.0.0").path), observedRequests.includes(servedTar.get("2.0.0").path),
rootInstalledModules.includes("typebox")]);
await pi(["remove", npmSource]);
await git(["init", "-b", "main"]);
await fixture(gitSource);
await writeJSON(join(gitSource, "package.json"), {name: "gallery-git-fixture", version: "1.0.0",
pi: {extensions: ["extensions/main.ts"]}});
await git(["add", "."]);
await git(["-c","user.name=Gallery Example","-c","user.email=gallery@example.invalid","commit","-m","Fixture version 1"]);
await git(["tag", "v1"]);
await writeJSON(join(gitSource, "package.json"), {name: "gallery-git-fixture", version: "2.0.0",
pi: {extensions: ["extensions/main.ts"]}});
await git(["add", "package.json"]);
await git(["-c","user.name=Gallery Example","-c","user.email=gallery@example.invalid","commit","-m","Fixture version 2"]);
await git(["update-server-info"]);
const gitPack = "git:" + address + gitRequest.slice(0,-1) + "@v1";
await pi(["install", gitPack]);
const gitDir = provider(true).getInstalledPath(gitPack, "user");
const gitBefore = (await settingsAt(join(gitDir, "package.json"))).version;
await pi(["update", "--extensions"]);
const gitAfter = (await settingsAt(join(gitDir, "package.json"))).version;
check("real_git_install_and_extensions_update_keep_pinned_ref", {ref: "v1", defaultBranchVersion: "2.0.0"},
["1.0.0","1.0.0",true], [gitBefore, gitAfter, observedRequests.includes(gitRequest + "info/refs")]);
await pi(["remove", gitPack]);
const beforeTemp = (await settingsAt(config)).packages ?? [];
const modelConfig = {providers: {local: {baseUrl: address + "/unused", api: "openai-completions",
apiKey: "fixture-only", models: [{id: "local-model"}]}}};
await writeJSON(join(profile, "models.json"), modelConfig);
const rpc = spawnOne(["--mode","rpc","--no-session","--no-mcp","--no-context-files","--no-builtin-tools",
"--provider","local","--model","local-model","-e",kit]);
const stdout = await rpc;
const reply = stdout.split(/\r?\n/).filter(Boolean).map(JSON.parse).find(row => row.type === "response");
check("temporary_package_cli_loads_without_persisting", {cli: "-e <local fixture>"},
[true, true], [reply.data.commands.some(item => item.name === "gallery-package"),
JSON.stringify((await settingsAt(config)).packages ?? []) === JSON.stringify(beforeTemp)]);
process.stdout.write(JSON.stringify({nodeVersion: process.version, version, npmVersion, cases}) + "\n");
} finally {
if (server.listening) await new Promise(done => server.close(done));
await rm(root, {recursive: true, force: true});
}
function spawnOne(argv) {
return new Promise((done, reject) => {
const child = execFile(process.execPath, [cli, ...argv], {cwd: project, env,
windowsHide: true, timeout: 15000, encoding: "utf8"}, (err, stdout, stderr) =>
err ? reject(new Error(stderr || err.message)) : done(stdout));
child.stdin.end('{"id":"fixture","type":"get_commands"}\n');
});
}
- 本地包留在原目录,项目条目受信任开关控制。固定 npm 版本及 Git 标签维护后仍保持原值,过滤保留指定候选。
所需环境:Windows、Node.js 24.22.3、Pi 1.5.0、npm 12.2.1、Git、WinPTY 与本机回环服务。
当前源码 SHA256:76c40b26ea486b1dd0b4d755409df1bcbde694417a2a5aaec210ad36c25d2bb9
本地复跑
依照 README 分别运行包管理脚本与终端配置脚本,逐项检查 JSON 输出。
所需环境:Windows、Node.js 24.22.3、Pi 1.5.0、npm 12.2.1、Git、WinPTY 与本机回环服务。
ZIP SHA256:3884dc429a2b60211f0bccecec6758ecf3e7869894716e7d2b753fdfaeaa7c63
常见错误与边界
- 依赖暂存在临时目录,git 与 npm 的固定约束分别核对。
- 项目清单只在有效的信任范围内使用。
练习与解答
只想恢复被通配符排除的一个主题,应怎样写?
展开参考解答
在允许的主题清单内先写 !themes/*.json,再以 +themes/ocean.json 启用指定主题。