Files
my-pi/scripts/rebuild-bundle-config.mjs
T
云服务部-叶林立andDevin <158243242+devin-ai-integration[bot]@users.noreply.github.com> 2682bd7fa7 feat: 组合包配置集中到 my-pi/ 目录并改为整体重建
- 组合包拥有、可随时重建的配置、日志与缓存统一放在
  <agentDir>/my-pi/:permission-system/(policy.jsonc、hard-guards.jsonc、
  logs/)、rtk-optimizer/config.json、tool-search/(config.json、
  catalog-v1.json)与 system-prompt-cover.md。hashline.json、lsp.json
  由外部扩展读取固定路径,是唯一例外。
- 新增 config/bundle-manifest.json 与 scripts/rebuild-bundle-config.mjs:
  先校验全部来源与目标,在临时目录构建完整树,再整体删除旧 my-pi/
  (符号链接只删链接)并原子替换,不备份。install.sh / update.sh 每次
  运行都调用它;扩展自身不再播种或迁移配置。
- update.sh 删除 pi update 失败后的 git clean 恢复逻辑:Pi 1.3.0 会在
  下一次 pi update 时依据中断标记自行恢复。同时删除 Tool Search
  settings.json 快照迁移与封面部署脚本。
- Tool Search 改为读取 my-pi/tool-search/config.json(源为
  config/tool-search.json,须与 BUNDLE_TOOL_SEARCH_DEFAULTS 一致),
  不再读写 settings.json 的 toolSearch 段,移除 bundleDefaultsVersion。
- 默认权限策略开启 debugLog。
- 旧位置的残留文件不迁移、不清理;AGENTS.md / README 同步新约束。

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-10-19 02:26:57 -07:00

175 lines
6.1 KiB
JavaScript

#!/usr/bin/env node
/**
* Rebuilds the bundle-owned config directory inside the Pi agent directory.
*
* Every piece of bundle-owned, rebuildable state lives under
* `<agentDir>/my-pi/` (policy files, Tool Search config, the system prompt
* cover, permission logs). `config/bundle-manifest.json` is the authoritative
* source→target list: this helper builds the full tree in a sibling temp
* directory, deletes any existing `my-pi/` wholesale — no backup — and renames
* the fresh tree into place, so a rebuild can never half-apply.
*
* Nothing outside `my-pi/` is read or removed; leftovers at the old locations
* are ignored rather than migrated.
*/
import { realpathSync } from "node:fs";
import { chmod, copyFile, lstat, mkdir, readFile, rename, rm, unlink } from "node:fs/promises";
import { dirname, isAbsolute, join, resolve, sep } from "node:path";
import { fileURLToPath } from "node:url";
const scriptPath = fileURLToPath(import.meta.url);
const bundleRoot = dirname(dirname(scriptPath));
export const BUNDLE_ROOT = bundleRoot;
export const MANIFEST_PATH = join(bundleRoot, "config", "bundle-manifest.json");
/** Thrown for an unusable agentDir argument; maps to CLI exit code 2. */
export class RebuildUsageError extends Error {}
function isObject(value) {
return value !== null && typeof value === "object" && !Array.isArray(value);
}
/**
* Load and validate the manifest.
*
* Every source must be a readable repo-relative file and every target a
* relative path that stays inside the bundle directory — a `..` or absolute
* target would escape `my-pi/` during the rebuild, so it is rejected before
* anything is touched.
*
* @param {string} manifestPath
* @returns {Promise<{ directory: string, files: Array<{ source: string, target: string }> }>}
*/
export async function loadManifest(manifestPath) {
let manifest;
try {
manifest = JSON.parse(await readFile(manifestPath, "utf8"));
} catch (error) {
throw new Error(
`cannot read bundle manifest at ${manifestPath}: ${
error instanceof Error ? error.message : String(error)
}`,
);
}
if (!isObject(manifest) || manifest.directory !== "my-pi" || !Array.isArray(manifest.files)) {
throw new Error(`bundle manifest at ${manifestPath} is malformed`);
}
const files = manifest.files.map((entry, index) => {
if (!isObject(entry) || typeof entry.source !== "string" || typeof entry.target !== "string") {
throw new Error(`bundle manifest entry ${index} lacks source/target strings`);
}
const directoryBase = resolve(manifest.directory);
const resolved = resolve(directoryBase, entry.target);
if (
isAbsolute(entry.target) ||
resolved === directoryBase ||
!resolved.startsWith(directoryBase + sep)
) {
throw new Error(
`bundle manifest target ${entry.target} escapes the ${manifest.directory}/ directory`,
);
}
const sourcePath = join(bundleRoot, entry.source);
return { source: entry.source, sourcePath, target: entry.target };
});
// Fail before deleting anything: a missing source must not wipe the live tree.
for (const file of files) {
try {
await readFile(file.sourcePath);
} catch (error) {
throw new Error(
`cannot read manifest source ${file.source}: ${
error instanceof Error ? error.message : String(error)
}`,
);
}
}
return { directory: manifest.directory, files };
}
/**
* Rebuild `<agentDir>/my-pi` from the bundle manifest.
*
* The tree is staged in `<agentDir>/.my-pi.rebuild-<pid>-<rand>` (dirs 0700,
* files 0600), then the existing `my-pi` is removed — a symlink is unlinked,
* never followed — and the stage is renamed into place. Any failure removes
* the stage and throws.
*
* @param {string} agentDir - Absolute Pi agent directory.
* @param {{ manifestPath?: string }} [options]
* @returns {Promise<{ targetDir: string }>}
*/
export async function rebuildBundleConfig(agentDir, { manifestPath = MANIFEST_PATH } = {}) {
if (typeof agentDir !== "string" || agentDir.length === 0 || !isAbsolute(agentDir)) {
throw new RebuildUsageError("rebuild-bundle-config requires an absolute agentDir argument");
}
const manifest = await loadManifest(manifestPath);
const targetDir = join(agentDir, manifest.directory);
const stageDir = join(
agentDir,
`.${manifest.directory}.rebuild-${process.pid}-${Math.random().toString(16).slice(2)}`,
);
try {
await mkdir(agentDir, { recursive: true, mode: 0o700 });
await mkdir(stageDir, { mode: 0o700 });
for (const file of manifest.files) {
const destination = join(stageDir, file.target);
await mkdir(dirname(destination), { recursive: true, mode: 0o700 });
// copyFile keeps the source mode on some platforms; pin owner-only.
await copyFile(file.sourcePath, destination);
await chmod(destination, 0o600);
}
// Never follow a symlink: unlink the link itself, never its target.
try {
const stats = await lstat(targetDir);
if (stats.isSymbolicLink()) {
await unlink(targetDir);
} else {
await rm(targetDir, { recursive: true, force: true });
}
} catch (error) {
if (error?.code !== "ENOENT") throw error;
}
await rename(stageDir, targetDir);
return { targetDir };
} catch (error) {
await rm(stageDir, { recursive: true, force: true }).catch(() => {});
throw error;
}
}
function isMainModule() {
if (!process.argv[1]) return false;
try {
return fileURLToPath(import.meta.url) === realpathSync(process.argv[1]);
} catch {
return false;
}
}
async function main() {
const agentDir = process.argv[2] ?? "";
if (agentDir.length === 0 || !isAbsolute(agentDir)) {
console.error("usage: rebuild-bundle-config.mjs <absolute-agent-dir>");
process.exitCode = 2;
return;
}
const { targetDir } = await rebuildBundleConfig(agentDir);
process.stdout.write(`rebuilt:${targetDir}\n`);
}
if (isMainModule()) {
main().catch((error) => {
console.error(error instanceof Error ? error.message : String(error));
process.exitCode = error instanceof RebuildUsageError ? 2 : 1;
});
}