personal-bot 0.3.4 → 0.3.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (86) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/README.md +191 -65
  4. package/README.zh-CN.md +189 -63
  5. package/bin/pbot.mjs +3 -17
  6. package/docs/README.md +1 -1
  7. package/docs/architecture/design.md +10 -9
  8. package/docs/architecture/extensibility.md +1 -1
  9. package/docs/architecture/principles.md +1 -1
  10. package/docs/hosts/antigravity.md +4 -2
  11. package/docs/hosts/pi.md +4 -15
  12. package/docs/maintainers/release.md +2 -2
  13. package/lib/antigravity-plugin/lib/common/paths.d.ts +1 -0
  14. package/lib/antigravity-plugin/lib/common/paths.js +2 -0
  15. package/lib/antigravity-plugin/lib/extension/acp-worker.js +26 -24
  16. package/lib/antigravity-plugin/lib/extension/cli.js +22495 -0
  17. package/lib/antigravity-plugin/lib/extension/mcp.js +22 -20
  18. package/lib/antigravity-plugin/lib/extension/workspace-cli.js +5 -20165
  19. package/lib/antigravity-plugin/package.json +1 -1
  20. package/lib/antigravity-plugin/plugin.json +1 -1
  21. package/lib/codex-marketplace/plugins/personal-bot/.codex-plugin/plugin.json +1 -1
  22. package/lib/codex-marketplace/plugins/personal-bot/.mcp.json +2 -2
  23. package/lib/codex-marketplace/plugins/personal-bot/hooks/hooks.json +3 -3
  24. package/lib/codex-marketplace/plugins/personal-bot/skills/pbot/SKILL.md +1 -1
  25. package/lib/common/paths.d.ts +1 -0
  26. package/lib/common/paths.js +2 -0
  27. package/lib/extension/acp-worker.js +26 -24
  28. package/lib/extension/cli.js +22495 -0
  29. package/lib/extension/mcp.js +22 -20
  30. package/lib/extension/workspace-cli.js +5 -20165
  31. package/lib/qoder-plugin/.mcp.json +2 -2
  32. package/lib/qoder-plugin/.qoder-plugin/plugin.json +1 -1
  33. package/lib/qoder-plugin/hooks/hooks.json +3 -3
  34. package/lib/qoder-plugin/skills/pbot/SKILL.md +1 -1
  35. package/package.json +1 -1
  36. package/scripts/README.md +1 -1
  37. package/src/common/paths.ts +2 -0
  38. package/src/extension/cli/args.ts +104 -0
  39. package/src/extension/cli/commands/history.ts +81 -0
  40. package/src/extension/cli/commands/install.ts +77 -0
  41. package/src/extension/cli/commands/mcp.ts +165 -0
  42. package/src/extension/cli/commands/plugin.ts +33 -0
  43. package/src/extension/cli/commands/upgrade.ts +158 -0
  44. package/src/extension/cli/commands/workspace.ts +71 -0
  45. package/src/extension/cli/index.ts +192 -0
  46. package/src/extension/cli/types.ts +30 -0
  47. package/src/integrations/installation/cli-update.ts +3 -3
  48. package/src/integrations/installation/installers/antigravity.ts +49 -0
  49. package/src/integrations/installation/installers/claude.ts +30 -0
  50. package/src/integrations/installation/installers/codex.ts +56 -0
  51. package/src/integrations/installation/installers/dsh.ts +25 -0
  52. package/src/integrations/installation/installers/pi.ts +26 -0
  53. package/src/integrations/installation/installers/qoder.ts +49 -0
  54. package/src/integrations/installation/installers/registry.ts +48 -0
  55. package/src/integrations/installation/processes.ts +2 -41
  56. package/src/model/installation.ts +28 -36
  57. package/src/services/installation/install-service.ts +107 -0
  58. package/lib/common/package-source.js +0 -16
  59. package/lib/extension/setup/cli.js +0 -364
  60. package/lib/extension/setup/guard.js +0 -11
  61. package/lib/extension/setup/upgrade.js +0 -153
  62. package/lib/integrations/installation/cli-update.js +0 -146
  63. package/lib/integrations/installation/pi-bridge.js +0 -131
  64. package/lib/integrations/installation/pi-setup.js +0 -193
  65. package/lib/integrations/installation/processes.js +0 -140
  66. package/lib/integrations/installation/upgraders/antigravity.js +0 -67
  67. package/lib/integrations/installation/upgraders/claude.js +0 -123
  68. package/lib/integrations/installation/upgraders/codex.js +0 -73
  69. package/lib/integrations/installation/upgraders/dsh.js +0 -62
  70. package/lib/integrations/installation/upgraders/pi.js +0 -90
  71. package/lib/integrations/installation/upgraders/qoder.js +0 -67
  72. package/lib/integrations/installation/upgraders/registry.js +0 -40
  73. package/lib/integrations/installation/workspace.js +0 -21
  74. package/lib/model/installation.js +0 -1
  75. package/lib/services/installation/setup-service.js +0 -140
  76. package/lib/services/installation/upgrade-service.js +0 -95
  77. package/lib/ui/setup.js +0 -52
  78. package/resources/installer/plugins.json +0 -16
  79. package/src/extension/setup/cli.ts +0 -303
  80. package/src/extension/setup/guard.ts +0 -12
  81. package/src/extension/setup/upgrade.ts +0 -158
  82. package/src/extension/setup/workspace-cli.ts +0 -167
  83. package/src/integrations/installation/pi-bridge.ts +0 -109
  84. package/src/integrations/installation/pi-setup.ts +0 -162
  85. package/src/services/installation/setup-service.ts +0 -126
  86. package/src/ui/setup.ts +0 -40
@@ -1,109 +0,0 @@
1
- import { readFileSync } from "node:fs";
2
- import { readFile, stat } from "node:fs/promises";
3
- import { join, resolve } from "node:path";
4
- import { fileURLToPath, pathToFileURL } from "node:url";
5
- import type { InstalledPackage } from "../../model/installation.js";
6
- import { npmName } from "../../common/package-source.js";
7
-
8
- type PiSdk = typeof import("@earendil-works/pi-coding-agent");
9
- async function sdkAt(root: string): Promise<PiSdk> {
10
- const manifest = JSON.parse(await readFile(join(root, "package.json"), "utf8"));
11
- if (manifest.name !== "@earendil-works/pi-coding-agent") throw new Error("不是支持的 Pi 安装。");
12
- return import(pathToFileURL(join(root, "dist/index.js")).href) as Promise<PiSdk>;
13
- }
14
- const sourceOf = (entry: unknown): string => {
15
- if (typeof entry === "string") return entry;
16
- if (entry && typeof entry === "object" && "source" in entry && typeof entry.source === "string") return entry.source;
17
- throw new Error("无效的 Pi packages 声明。");
18
- };
19
-
20
- export async function inspectPackages(root: string, workspace: string): Promise<InstalledPackage[]> {
21
- const sdk = await sdkAt(root), agentDir = sdk.getAgentDir();
22
- // Inspect project declarations as data only. This does not load extensions, execute
23
- // project npmCommand, grant project trust, or persist migrated settings.
24
- const settings = sdk.SettingsManager.fromStorage({ withLock(scope, read) {
25
- const file = scope === "global" ? join(agentDir, "settings.json") : join(workspace, sdk.CONFIG_DIR_NAME, "settings.json");
26
- let content: string | undefined;
27
- try { content = readFileSync(file, "utf8"); }
28
- catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; }
29
- if (content !== undefined) {
30
- const value: unknown = JSON.parse(content);
31
- if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error(`无效的 Pi 配置:${file}`);
32
- const packages = (value as { packages?: unknown }).packages;
33
- if (packages !== undefined) {
34
- if (!Array.isArray(packages)) throw new Error(`packages 必须是数组:${file}`);
35
- packages.forEach(sourceOf);
36
- }
37
- }
38
- if (read(content) !== undefined) throw new Error("安装检查不得修改 Pi 配置。");
39
- } }, { projectTrusted: true });
40
- const errors = settings.drainErrors();
41
- if (errors.length) throw new Error(errors.map(item => `${item.scope}: ${item.error.message}`).join("\n"));
42
- const manager = new sdk.DefaultPackageManager({ cwd: workspace, agentDir, settingsManager: settings });
43
- const result: InstalledPackage[] = [];
44
- for (const pkg of manager.listConfiguredPackages()) {
45
- const entries = (pkg.scope === "project" ? settings.getProjectSettings() : settings.getGlobalSettings()).packages ?? [];
46
- const entry = entries.find(item => sourceOf(item) === pkg.source);
47
- let name = npmName(pkg.source), version: string | undefined, singleFile = false;
48
- if (pkg.installedPath) {
49
- const info = await stat(pkg.installedPath);
50
- singleFile = info.isFile(); // An existing standalone extension has no npm identity.
51
- if (info.isDirectory()) {
52
- try {
53
- const manifest = JSON.parse(await readFile(join(pkg.installedPath, "package.json"), "utf8")) as { name?: string; version?: string };
54
- if (name && manifest.name !== name) throw new Error(`安装包身份不匹配:${pkg.source}`);
55
- name = typeof manifest.name === "string" && manifest.name.trim() ? manifest.name : name;
56
- version = typeof manifest.version === "string" ? manifest.version : undefined;
57
- } catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; }
58
- }
59
- }
60
- if (!name && !singleFile) {
61
- throw new Error(`无法辨认 ${pkg.scope} 来源的包身份:${pkg.source}。请先通过 Pi 原生配置恢复或修正该来源,再重新运行 setup。`);
62
- }
63
- result.push({ source: pkg.source, scope: pkg.scope, filtered: pkg.filtered, entry,
64
- ...(pkg.installedPath ? { installedPath: pkg.installedPath } : {}), ...(name ? { name } : {}), ...(version ? { version } : {}) });
65
- }
66
- return result;
67
- }
68
-
69
- export async function replaceProjectSource(root: string, workspace: string, old: InstalledPackage, target: string): Promise<void> {
70
- const fromProject = old.scope === "project" && !npmName(old.source);
71
- const fromUser = old.scope === "user" && !!npmName(old.source);
72
- if (!fromProject && !fromUser) throw new Error("此操作只替换工作区自定义来源,或继承全局 npm 资源过滤。");
73
- const sdk = await sdkAt(root);
74
- const settings = sdk.SettingsManager.create(workspace, sdk.getAgentDir(), { projectTrusted: true });
75
- const errors = settings.drainErrors();
76
- if (errors.length) throw new Error(errors.map(item => item.error.message).join("\n"));
77
- const packages = settings.getProjectSettings().packages ?? [];
78
- const originals = fromProject ? packages : settings.getGlobalSettings().packages ?? [];
79
- const previous = originals.find(entry => sourceOf(entry) === old.source);
80
- if (previous === undefined || JSON.stringify(previous) !== JSON.stringify(old.entry)) throw new Error("插件配置已发生变化,请重新运行 setup。");
81
- if (!packages.some(entry => sourceOf(entry) === target)) throw new Error("目标包尚未安装,保留原声明。");
82
- const manager = new sdk.DefaultPackageManager({ cwd: workspace, agentDir: sdk.getAgentDir(), settingsManager: settings });
83
- const installed = manager.getInstalledPath(target, "project");
84
- if (!installed || !npmName(target)) throw new Error("目标 npm 包尚未安装,保留原声明。");
85
- const manifest = JSON.parse(await readFile(join(installed, "package.json"), "utf8"));
86
- if (manifest.name !== npmName(target)) throw new Error("目标安装包身份不符,保留原声明。");
87
- // Change only declarations; do not call remove(), which deletes managed git caches.
88
- const replacement = typeof previous === "string" ? target : { ...previous, source: target };
89
- const next = fromProject
90
- ? packages.filter(entry => sourceOf(entry) !== target).map(entry => sourceOf(entry) === old.source ? replacement : entry)
91
- : packages.map(entry => sourceOf(entry) === target ? replacement : entry);
92
- settings.setProjectPackages(next);
93
- await settings.flush();
94
- const failures = settings.drainErrors();
95
- if (failures.length) throw new Error(failures.map(item => item.error.message).join("\n"));
96
- }
97
-
98
- async function main() {
99
- const [action, root, workspace, input] = process.argv.slice(2);
100
- if (!root || !workspace) throw new Error("缺少 Pi 路径或工作区。");
101
- if (action === "inspect") console.log(JSON.stringify(await inspectPackages(root, workspace)));
102
- else if (action === "replace" && input) {
103
- const { old, target } = JSON.parse(input) as { old: InstalledPackage; target: string };
104
- await replaceProjectSource(root, workspace, old, target);
105
- } else throw new Error("无效的安装检查操作。");
106
- }
107
- if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
108
- await main().catch(error => { console.error(error instanceof Error ? error.message : String(error)); process.exitCode = 1; });
109
- }
@@ -1,162 +0,0 @@
1
- import { access, readFile, realpath } from "node:fs/promises";
2
- import { constants } from "node:fs";
3
- import { dirname, join, resolve } from "node:path";
4
- import { homedir } from "node:os";
5
- import { fileURLToPath } from "node:url";
6
- import { checkStableVersion, npmName } from "../../common/package-source.js";
7
- import type { InstalledPackage, PackageChoice, PiInstallation, SetupOperations, SystemCommand } from "../../model/installation.js";
8
- import { findExecutable, npmGlobalBinary, SetupProcesses } from "./processes.js";
9
-
10
- export const piPackageName = "@earendil-works/pi-coding-agent";
11
- export class PiBootstrapRequired extends Error {}
12
- const bridge = fileURLToPath(new URL("./pi-bridge.js", import.meta.url));
13
- const guard = fileURLToPath(new URL("../../extension/setup/guard.js", import.meta.url));
14
-
15
- async function packageRoot(command: string, version: string, env: NodeJS.ProcessEnv): Promise<string> {
16
- const resolved = await realpath(command);
17
- let directory = dirname(resolved);
18
- while (true) {
19
- try {
20
- const pkg = JSON.parse(await readFile(join(directory, "package.json"), "utf8"));
21
- if (pkg.name === piPackageName && pkg.version === version) return directory;
22
- } catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; }
23
- const parent = dirname(directory);
24
- if (parent === directory) break;
25
- directory = parent;
26
- }
27
- const roots = [join(dirname(dirname(resolved)), "install"), env.PI_MANAGED_INSTALL_ROOT].filter((root): root is string => !!root);
28
- for (const root of roots) {
29
- try {
30
- // The native managed launcher resides beside install/. Only accept a matching
31
- // launcher, not an unrelated PI_MANAGED_INSTALL_ROOT inherited from another Pi.
32
- const launcher = await realpath(join(dirname(root), "bin/pi"));
33
- if (launcher !== resolved) continue;
34
- const current = (await readFile(join(root, "current-version"), "utf8")).trim();
35
- if (current !== version || !/^\d+\.\d+\.\d+(?:-[\w.-]+)?$/.test(current)) continue;
36
- const candidate = join(root, "releases", current, "node_modules", piPackageName);
37
- const pkg = JSON.parse(await readFile(join(candidate, "package.json"), "utf8"));
38
- if (pkg.name === piPackageName && pkg.version === version) return candidate;
39
- } catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; }
40
- }
41
- throw new Error(`无法定位 ${command} 对应的 Pi 包。请先按此 Pi 的原生安装方式修复,不会覆盖该命令。`);
42
- }
43
-
44
- export class PiSetup implements SetupOperations {
45
- constructor(readonly processes: SetupProcesses, readonly npm: string, readonly cwd: string) {}
46
-
47
- async inspectPi(command?: string): Promise<PiInstallation | undefined> {
48
- const executable = command ?? await findExecutable("pi", this.processes.env);
49
- if (!executable) return undefined;
50
- const version = await this.processes.run(executable, ["--version"], this.cwd);
51
- if (!/^\d+\.\d+\.\d+(?:-[\w.-]+)?$/.test(version)) throw new Error(`PATH 中的 ${executable} 不是可识别的 Pi。`);
52
- return { command: executable, version, root: await packageRoot(executable, version, this.processes.env) };
53
- }
54
-
55
- async latest(name: string): Promise<string> {
56
- const text = await this.processes.run(this.npm, ["view", `${name}@latest`, "version", "engines", "--json",
57
- "--fetch-retries=0", "--fetch-timeout=15000"], this.cwd);
58
- const value = JSON.parse(text) as { version?: string; engines?: { node?: string } };
59
- if (typeof value.version !== "string") throw new Error(`无法取得 ${name} 的最新版本。`);
60
- return checkStableVersion(value.version, value.engines?.node);
61
- }
62
-
63
- async inspectPackages(pi: PiInstallation | undefined, workspace: string): Promise<InstalledPackage[]> {
64
- if (!pi) {
65
- // A fresh machine can be planned without loading a Pi SDK. Existing declarations
66
- // require Pi's own resolver; don't guess git cache paths or package identities.
67
- const agentDir = this.processes.env.PI_CODING_AGENT_DIR ?? join(this.processes.env.HOME ?? homedir(), ".pi/agent");
68
- for (const file of [join(agentDir, "settings.json"), join(workspace, ".pi/settings.json")]) {
69
- try {
70
- const settings: unknown = JSON.parse(await readFile(file, "utf8"));
71
- if (!settings || typeof settings !== "object" || Array.isArray(settings)) throw new Error(`无效的 Pi 配置:${file}`);
72
- const packages = (settings as { packages?: unknown }).packages;
73
- if (packages !== undefined && !Array.isArray(packages)) throw new Error(`packages 必须是数组:${file}`);
74
- if (Array.isArray(packages) && packages.length > 0) {
75
- throw new PiBootstrapRequired(`已有插件配置但未找到 Pi:${file}`);
76
- }
77
- } catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; }
78
- }
79
- return [];
80
- }
81
- const data = await this.processes.run(process.execPath, [bridge, "inspect", pi.root, workspace], this.cwd);
82
- return JSON.parse(data) as InstalledPackage[];
83
- }
84
-
85
- async installTmux(command: SystemCommand): Promise<void> {
86
- await this.processes.run(command.command, command.args, this.cwd, { interactive: true });
87
- const tmux = await findExecutable("tmux", this.processes.env);
88
- if (!tmux) throw new Error("tmux 安装后仍不在 PATH 中,请修复 PATH 后重试。");
89
- await this.processes.run(tmux, ["-V"], this.cwd);
90
- }
91
-
92
- async ensurePi(existing: PiInstallation | undefined, version: string): Promise<PiInstallation> {
93
- if (existing) {
94
- if (existing.version !== version) await this.processes.run(existing.command, ["update"], this.cwd, { interactive: true });
95
- const installed = await this.inspectPi(existing.command);
96
- if (!installed || installed.version !== version) throw new Error(`Pi 实际版本 ${installed?.version ?? "未知"} 与目标 ${version} 不同。请用原安装方式更新后重试。`);
97
- return installed;
98
- }
99
- const prefix = await this.processes.run(this.npm, ["prefix", "--global"], this.cwd);
100
- if (!prefix || !prefix.startsWith("/")) throw new Error("无法确定 npm 全局安装目录。");
101
- try { await access(prefix, constants.W_OK); }
102
- catch { throw new Error(`npm 全局目录不可写:${prefix}。请先配置当前用户的 npm prefix 或 Node.js 版本管理器。`); }
103
- await this.processes.run(this.npm, ["install", "--global", "--ignore-scripts", "--engine-strict",
104
- `${piPackageName}@${version}`], this.cwd, { interactive: true });
105
- const installed = await this.inspectPi(npmGlobalBinary(prefix));
106
- if (!installed || installed.version !== version) throw new Error("Pi 安装版本验证失败。");
107
- const onPath = await findExecutable("pi", this.processes.env);
108
- if (!onPath || await realpath(onPath) !== await realpath(installed.command)) {
109
- throw new Error(`Pi 已安装到 ${installed.command},请把 ${join(prefix, "bin")} 加入 PATH 后重新运行 setup。`);
110
- }
111
- return installed;
112
- }
113
-
114
- async verifyKeptPackage(pi: PiInstallation, workspace: string, choice: PackageChoice): Promise<string> {
115
- const old = choice.existing[0];
116
- if (choice.existing.length !== 1 || !old) throw new Error("保留来源不可用或存在多份来源,请先通过 pi config 处理。");
117
- const current = (await this.inspectPackages(pi, workspace)).find(pkg => pkg.source === old.source && pkg.scope === old.scope);
118
- if (!current?.installedPath || current.name !== npmName(choice.plugin.source) || JSON.stringify(current.entry) !== JSON.stringify(old.entry)) {
119
- throw new Error("保留来源已变化或不可读取,请重新运行 setup。");
120
- }
121
- return current.source;
122
- }
123
-
124
- async installPackage(pi: PiInstallation, workspace: string, choice: PackageChoice): Promise<string> {
125
- const name = npmName(choice.plugin.source);
126
- if (!name || !choice.target) throw new Error("缺少目标包或目标版本。");
127
- // Re-read just before mutation so a stale plan cannot replace a changed source.
128
- const current = (await this.inspectPackages(pi, workspace)).filter(pkg => pkg.name === name);
129
- for (const old of choice.existing) {
130
- const actual = current.find(pkg => pkg.scope === old.scope && pkg.source === old.source);
131
- if (!actual || JSON.stringify(actual.entry) !== JSON.stringify(old.entry)) throw new Error(`${name} 配置已改变,请重新运行 setup。`);
132
- }
133
- if (current.some(pkg => !choice.existing.some(old => old.scope === pkg.scope && old.source === pkg.source) &&
134
- !(pkg.scope === "user" && npmName(pkg.source) && choice.existing.some(old => old.scope === "project" && npmName(old.source))))) {
135
- throw new Error(`${name} 出现新的来源,请重新运行 setup。`);
136
- }
137
- const otherSources = choice.existing.filter(pkg => !npmName(pkg.source));
138
- if (otherSources.length > 1 || otherSources.some(pkg => pkg.scope === "user")) {
139
- throw new Error("存在不同身份的全局来源或多份自定义来源。请先用 pi config 调整加载范围后重试。");
140
- }
141
- const globals = choice.existing.filter(pkg => pkg.scope === "user" && npmName(pkg.source));
142
- if (globals.length > 1 && globals.some(pkg => pkg.filtered)) throw new Error("存在多份全局 npm 资源过滤,请先用 pi config 调整后重试。");
143
- const template = otherSources[0] ?? globals.find(pkg => pkg.filtered);
144
- const target = `npm:${name}@latest`;
145
- await this.processes.run(pi.command, ["install", "--local", target], workspace, { interactive: true });
146
- const records = await this.inspectPackages(pi, workspace);
147
- const installed = records.find(pkg => pkg.scope === "project" && pkg.source === target);
148
- if (!installed?.installedPath || installed.version !== choice.target) {
149
- throw new Error(`${name} 实际版本 ${installed?.version ?? "未知"} 与目标 ${choice.target} 不同,请检查 registry 后重试。`);
150
- }
151
- if (template) {
152
- await this.processes.run(process.execPath, [bridge, "replace", pi.root, workspace,
153
- JSON.stringify({ old: template, target })], this.cwd);
154
- }
155
- return installed.version;
156
- }
157
-
158
- async start(pi: PiInstallation, workspace: string): Promise<void> {
159
- await access(guard, constants.R_OK);
160
- await this.processes.run(pi.command, ["--extension", guard, "/pbot init"], resolve(workspace), { interactive: true, timeoutMs: 0 });
161
- }
162
- }
@@ -1,126 +0,0 @@
1
- import { npmName, ordinaryNpm } from "../../common/package-source.js";
2
- import type { InstalledPackage, PackageChoice, PiInstallation, PluginSpec, SetupOperations, SetupPlan, SetupResult } from "../../model/installation.js";
3
-
4
- export type { InstalledPackage, PackageChoice, PiInstallation, PluginSpec, SetupOperations, SetupPlan, SetupResult, SystemCommand } from "../../model/installation.js";
5
-
6
- export const pbotPackage: PluginSpec = {
7
- id: "pbot", label: "Personal Bot", description: "工作区个人助手", source: "npm:personal-bot", defaultSelected: true,
8
- };
9
- export function parseCatalog(value: unknown): PluginSpec[] {
10
- if (!Array.isArray(value)) throw new Error("插件清单必须是数组。");
11
- const ids = new Set(["pbot"]), names = new Set(["personal-bot"]);
12
- return value.map((item: unknown) => {
13
- if (!item || typeof item !== "object") throw new Error("无效插件清单项。");
14
- const entry = item as Record<string, unknown>;
15
- for (const field of ["id", "label", "description", "source"]) {
16
- if (typeof entry[field] !== "string" || !entry[field].trim() || /[\x00-\x1f\x7f]/.test(entry[field])) {
17
- throw new Error(`无效插件字段:${field}`);
18
- }
19
- }
20
- const plugin = entry as unknown as PluginSpec;
21
- const name = npmName(plugin.source);
22
- if (!/^[a-z0-9-]+$/.test(plugin.id) || !name || !ordinaryNpm(plugin.source) ||
23
- typeof plugin.defaultSelected !== "boolean" || ids.has(plugin.id) || names.has(name)) {
24
- throw new Error(`无效或重复的插件:${plugin.id}`);
25
- }
26
- ids.add(plugin.id); names.add(name);
27
- return { id: plugin.id, label: plugin.label, description: plugin.description,
28
- source: `npm:${name}`, defaultSelected: plugin.defaultSelected };
29
- });
30
- }
31
- export function packageChoices(catalog: PluginSpec[], installed: InstalledPackage[]): PackageChoice[] {
32
- const first = !installed.some(pkg => pkg.name === "personal-bot");
33
- return [pbotPackage, ...catalog].map(plugin => {
34
- const matches = installed.filter(pkg => pkg.name === npmName(plugin.source));
35
- // A project npm entry overrides the same npm identity in user settings. Different
36
- // git/local identities still need an explicit decision before changing sources.
37
- const localNpm = matches.some(pkg => pkg.scope === "project" && npmName(pkg.source));
38
- const existing = matches.filter(pkg => !(localNpm && pkg.scope === "user" && npmName(pkg.source)));
39
- const custom = existing.some(pkg => !ordinaryNpm(pkg.source));
40
- return { plugin, required: plugin.id === "pbot", existing,
41
- selected: plugin.id === "pbot" || (first ? plugin.defaultSelected : existing.length > 0), keep: custom };
42
- });
43
- }
44
- export function parseSetupArgs(args: string[]): {
45
- action: "help" | "version" | "setup" | "upgrade" | "install-antigravity" | "mcp" | "mcp-manage";
46
- workspace?: string;
47
- mcpArgs?: string[];
48
- upgradeArgs?: string[];
49
- upgradeVerb?: "upgrade" | "update";
50
- } {
51
- if (!args.length || args.length === 1 && ["--help", "-h"].includes(args[0]!)) return { action: "help" };
52
- if (args.length === 1 && ["--version", "-v"].includes(args[0]!)) return { action: "version" };
53
- if (args[0] === "upgrade" || args[0] === "update") {
54
- return { action: "upgrade", upgradeArgs: args.slice(1), upgradeVerb: args[0] };
55
- }
56
- if (args[0] === "install-antigravity") {
57
- if (args.length === 1) return { action: "install-antigravity" };
58
- if (args.length === 2 && ["--help", "-h"].includes(args[1]!)) return { action: "help" };
59
- throw new Error("用法:pbot install-antigravity");
60
- }
61
- if (args[0] === "mcp") {
62
- if (args.length === 1) return { action: "mcp" };
63
- if (args.length === 2 && ["--help", "-h"].includes(args[1]!)) return { action: "help" };
64
- if (["list", "add", "remove"].includes(args[1]!)) return { action: "mcp-manage", mcpArgs: args.slice(1) };
65
- throw new Error("用法:pbot mcp [list|add|remove ...]");
66
- }
67
- if (args[0] !== "setup") throw new Error("用法:pbot setup [--workspace <目录>] | pbot upgrade|update [--workspace <目录>] | pbot install-antigravity | pbot mcp [list|add|remove ...]");
68
- let workspace: string | undefined;
69
- for (let index = 1; index < args.length; index++) {
70
- const arg = args[index]!;
71
- if ((arg === "--help" || arg === "-h") && args.length === 2) return { action: "help" };
72
- if (arg !== "--workspace" || workspace !== undefined) throw new Error(`不支持的参数:${arg}`);
73
- const value = args[++index];
74
- if (!value || value.startsWith("--") || /[\x00-\x1f\x7f]/.test(value)) throw new Error("--workspace 需要目录。");
75
- workspace = value;
76
- }
77
- return workspace === undefined ? { action: "setup" } : { action: "setup", workspace };
78
- }
79
-
80
- export async function executeSetup(plan: SetupPlan, operations: SetupOperations,
81
- report: (result: SetupResult) => void, signal: AbortSignal): Promise<{ pi?: PiInstallation; results: SetupResult[] }> {
82
- const results: SetupResult[] = [];
83
- const add = (result: SetupResult) => { results.push(result); report(result); };
84
- let pi: PiInstallation;
85
- try {
86
- signal.throwIfAborted();
87
- if (plan.tmux) { await operations.installTmux(plan.tmux); add({ name: "tmux", state: "done", detail: "已安装" }); }
88
- signal.throwIfAborted();
89
- pi = await operations.ensurePi(plan.pi, plan.piVersion);
90
- add({ name: "Pi", state: "done", detail: pi.version });
91
- } catch (error) {
92
- signal.throwIfAborted();
93
- add({ name: "运行环境", state: "failed", detail: String(error) });
94
- return { results };
95
- }
96
- for (const choice of plan.packages) {
97
- signal.throwIfAborted();
98
- const name = choice.plugin.label;
99
- if (!choice.selected) { add({ name, state: "skipped", detail: "本次不处理" }); continue; }
100
- if (choice.error) {
101
- add({ name, state: "failed", detail: choice.error });
102
- if (choice.required) return { results };
103
- continue;
104
- }
105
- if (choice.keep) {
106
- try {
107
- const source = await operations.verifyKeptPackage(pi, plan.workspace, choice);
108
- add({ name, state: "kept", detail: source });
109
- } catch (error) {
110
- signal.throwIfAborted();
111
- add({ name, state: "failed", detail: String(error) });
112
- if (choice.required) return { results };
113
- }
114
- continue;
115
- }
116
- try {
117
- const version = await operations.installPackage(pi, plan.workspace, choice);
118
- add({ name, state: "done", detail: version });
119
- } catch (error) {
120
- signal.throwIfAborted();
121
- add({ name, state: "failed", detail: String(error) });
122
- if (choice.required) return { results };
123
- }
124
- }
125
- return { pi, results };
126
- }
package/src/ui/setup.ts DELETED
@@ -1,40 +0,0 @@
1
- import { createInterface } from "node:readline/promises";
2
-
3
- export class SetupUI {
4
- constructor(private readonly controller: AbortController) {}
5
- text(value: string) { console.log(value); }
6
- async ask(label: string, fallback = ""): Promise<string> {
7
- this.controller.signal.throwIfAborted();
8
- const reader = createInterface({ input: process.stdin, output: process.stdout, terminal: true });
9
- reader.on("SIGINT", () => this.controller.abort(new Error("安装已取消。")));
10
- reader.on("close", () => { if (!answered) this.controller.abort(new Error("输入已关闭。")); });
11
- let answered = false;
12
- try {
13
- const value = await reader.question(label + (fallback ? " [" + fallback + "]" : "") + ": ", { signal: this.controller.signal });
14
- answered = true;
15
- return value.trim() || fallback;
16
- } finally { answered = true; reader.close(); }
17
- }
18
- async confirm(label: string, fallback = true): Promise<boolean> {
19
- while (true) {
20
- const answer = (await this.ask(label + (fallback ? " [Y/n]" : " [y/N]"))).toLowerCase();
21
- if (!answer) return fallback;
22
- if (["y", "yes", "是"].includes(answer)) return true;
23
- if (["n", "no", "否"].includes(answer)) return false;
24
- this.text("请输入 y 或 n。");
25
- }
26
- }
27
- async selectMany(labels: string[], defaults: number[]): Promise<number[]> {
28
- labels.forEach((label, index) => this.text(" " + (defaults.includes(index) ? "[x] " : "[ ] ") + (index + 1) + ". " + label));
29
- while (true) {
30
- const answer = await this.ask("选择插件编号(逗号分隔,回车保留默认,0 不选)");
31
- if (!answer) return defaults;
32
- if (answer === "0") return [];
33
- const parts = answer.split(/[,,\s]+/);
34
- if (parts.every(part => /^\d+$/.test(part) && Number(part) >= 1 && Number(part) <= labels.length)) {
35
- return [...new Set(parts.map(part => Number(part) - 1))];
36
- }
37
- this.text("请输入列表中的编号。");
38
- }
39
- }
40
- }