personal-bot 0.3.4 → 0.3.5

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 (62) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/bin/pbot.mjs +3 -17
  4. package/docs/architecture/design.md +8 -6
  5. package/docs/architecture/extensibility.md +1 -1
  6. package/docs/architecture/principles.md +1 -1
  7. package/lib/antigravity-plugin/lib/common/paths.d.ts +1 -0
  8. package/lib/antigravity-plugin/lib/common/paths.js +2 -0
  9. package/lib/antigravity-plugin/lib/extension/acp-worker.js +26 -24
  10. package/lib/antigravity-plugin/lib/extension/cli.js +22596 -0
  11. package/lib/antigravity-plugin/lib/extension/mcp.js +22 -20
  12. package/lib/antigravity-plugin/lib/extension/workspace-cli.js +5 -20165
  13. package/lib/antigravity-plugin/package.json +1 -1
  14. package/lib/antigravity-plugin/plugin.json +1 -1
  15. package/lib/codex-marketplace/plugins/personal-bot/.codex-plugin/plugin.json +1 -1
  16. package/lib/codex-marketplace/plugins/personal-bot/.mcp.json +2 -2
  17. package/lib/codex-marketplace/plugins/personal-bot/hooks/hooks.json +3 -3
  18. package/lib/codex-marketplace/plugins/personal-bot/skills/pbot/SKILL.md +1 -1
  19. package/lib/common/paths.d.ts +1 -0
  20. package/lib/common/paths.js +2 -0
  21. package/lib/extension/acp-worker.js +26 -24
  22. package/lib/extension/cli.js +22596 -0
  23. package/lib/extension/mcp.js +22 -20
  24. package/lib/extension/workspace-cli.js +5 -20165
  25. package/lib/qoder-plugin/.mcp.json +2 -2
  26. package/lib/qoder-plugin/.qoder-plugin/plugin.json +1 -1
  27. package/lib/qoder-plugin/hooks/hooks.json +3 -3
  28. package/lib/qoder-plugin/skills/pbot/SKILL.md +1 -1
  29. package/package.json +1 -1
  30. package/scripts/README.md +1 -1
  31. package/src/common/paths.ts +2 -0
  32. package/src/extension/cli/args.ts +104 -0
  33. package/src/extension/cli/commands/history.ts +81 -0
  34. package/src/extension/cli/commands/mcp.ts +165 -0
  35. package/src/extension/cli/commands/plugin.ts +33 -0
  36. package/src/extension/cli/commands/setup.ts +159 -0
  37. package/src/extension/cli/commands/upgrade.ts +158 -0
  38. package/src/extension/cli/commands/workspace.ts +71 -0
  39. package/src/extension/cli/index.ts +193 -0
  40. package/src/extension/cli/types.ts +30 -0
  41. package/src/integrations/installation/cli-update.ts +3 -3
  42. package/src/integrations/installation/pi-setup.ts +6 -3
  43. package/src/services/installation/setup-service.ts +0 -35
  44. package/lib/extension/setup/cli.js +0 -364
  45. package/lib/extension/setup/upgrade.js +0 -153
  46. package/lib/integrations/installation/cli-update.js +0 -146
  47. package/lib/integrations/installation/pi-setup.js +0 -193
  48. package/lib/integrations/installation/processes.js +0 -140
  49. package/lib/integrations/installation/upgraders/antigravity.js +0 -67
  50. package/lib/integrations/installation/upgraders/claude.js +0 -123
  51. package/lib/integrations/installation/upgraders/codex.js +0 -73
  52. package/lib/integrations/installation/upgraders/dsh.js +0 -62
  53. package/lib/integrations/installation/upgraders/pi.js +0 -90
  54. package/lib/integrations/installation/upgraders/qoder.js +0 -67
  55. package/lib/integrations/installation/upgraders/registry.js +0 -40
  56. package/lib/integrations/installation/workspace.js +0 -21
  57. package/lib/services/installation/setup-service.js +0 -140
  58. package/lib/services/installation/upgrade-service.js +0 -95
  59. package/lib/ui/setup.js +0 -52
  60. package/src/extension/setup/cli.ts +0 -303
  61. package/src/extension/setup/upgrade.ts +0 -158
  62. package/src/extension/setup/workspace-cli.ts +0 -167
@@ -1,303 +0,0 @@
1
- import { spawnSync } from "node:child_process";
2
- import { existsSync } from "node:fs";
3
- import { mkdir, readFile, realpath } from "node:fs/promises";
4
- import { homedir } from "node:os";
5
- import { join } from "node:path";
6
- import { fileURLToPath } from "node:url";
7
- import { executeSetup, packageChoices, parseCatalog, parseSetupArgs } from "../../services/installation/setup-service.js";
8
- import { npmName, ordinaryNpm } from "../../common/package-source.js";
9
- import type { InstalledPackage, SetupPlan } from "../../model/installation.js";
10
- import { PiBootstrapRequired, PiSetup, piPackageName } from "../../integrations/installation/pi-setup.js";
11
- import { findExecutable, inspectSystem, SetupProcesses } from "../../integrations/installation/processes.js";
12
- import { resolveWorkspace } from "../../integrations/installation/workspace.js";
13
- import type { WorkspaceMcpServer } from "../../model/workspace-mcp.js";
14
- import {
15
- readWorkspaceMcpConfig,
16
- removeWorkspaceMcpServer,
17
- upsertWorkspaceMcpServer,
18
- } from "../../services/workspace/workspace-mcp.js";
19
- import { SetupUI } from "../../ui/setup.js";
20
- import { runUpgradeCommand } from "./upgrade.js";
21
-
22
- const root = new URL("../../../", import.meta.url);
23
- const quote = (value: string) => "'" + value.replaceAll("'", "'\\''") + "'";
24
-
25
- const mcpManageUsage =
26
- "用法:\n" +
27
- " pbot mcp list [--workspace <目录>]\n" +
28
- " pbot mcp add <name> --url <url> [--header K=V]... [--description <说明>] [--timeout <秒>] [--disabled] [--workspace <目录>]\n" +
29
- " pbot mcp add <name> [--env K=V]... [--cwd <目录>] [--description <说明>] [--timeout <秒>] [--disabled] [--workspace <目录>] -- <command> [args...]\n" +
30
- " pbot mcp remove <name> [--workspace <目录>]";
31
-
32
- function parseKeyValue(raw: string, flag: string): [string, string] {
33
- const sep = raw.indexOf("=");
34
- if (sep <= 0) throw new Error(`${flag} 需要 KEY=VALUE 格式:${raw}`);
35
- return [raw.slice(0, sep), raw.slice(sep + 1)];
36
- }
37
-
38
- async function runMcpManage(mcpArgs: string[]): Promise<number> {
39
- const sub = mcpArgs[0];
40
- if (!sub || ["--help", "-h"].includes(sub)) {
41
- console.log(mcpManageUsage);
42
- return 0;
43
- }
44
- const rest = mcpArgs.slice(1);
45
- if (sub === "list") {
46
- let workspace: string | undefined;
47
- for (let i = 0; i < rest.length; i++) {
48
- if (rest[i] === "--workspace") {
49
- workspace = rest[++i];
50
- if (!workspace) throw new Error("--workspace 需要目录。");
51
- } else {
52
- throw new Error(`未知参数:${rest[i]}\n${mcpManageUsage}`);
53
- }
54
- }
55
- const target = await resolveWorkspace(workspace ?? process.cwd(), process.cwd(), homedir());
56
- const configuration = await readWorkspaceMcpConfig(target);
57
- if (configuration.error) throw new Error(configuration.error);
58
- console.log(JSON.stringify({ workspaceRoot: target, path: configuration.path, mcpServers: configuration.servers }, null, 2));
59
- return 0;
60
- }
61
- if (sub === "remove") {
62
- const name = rest[0];
63
- if (!name || name.startsWith("-")) throw new Error(`remove 需要服务名。\n${mcpManageUsage}`);
64
- let workspace: string | undefined;
65
- for (let i = 1; i < rest.length; i++) {
66
- if (rest[i] === "--workspace") {
67
- workspace = rest[++i];
68
- if (!workspace) throw new Error("--workspace 需要目录。");
69
- } else {
70
- throw new Error(`未知参数:${rest[i]}\n${mcpManageUsage}`);
71
- }
72
- }
73
- const target = await resolveWorkspace(workspace ?? process.cwd(), process.cwd(), homedir());
74
- const result = await removeWorkspaceMcpServer(target, name);
75
- console.log(JSON.stringify({ workspaceRoot: target, path: result.configuration.path, removed: result.removed, name }, null, 2));
76
- return result.removed ? 0 : 1;
77
- }
78
- if (sub === "add") {
79
- const name = rest[0];
80
- if (!name || name.startsWith("-")) throw new Error(`add 需要服务名。\n${mcpManageUsage}`);
81
- let workspace: string | undefined;
82
- let url: string | undefined;
83
- let cwd: string | undefined;
84
- let description: string | undefined;
85
- let timeout: number | undefined;
86
- let enabled: boolean | undefined;
87
- const env: Record<string, string> = {};
88
- const headers: Record<string, string> = {};
89
- let commandTokens: string[] = [];
90
- for (let i = 1; i < rest.length; i++) {
91
- const arg = rest[i]!;
92
- if (arg === "--") {
93
- commandTokens = rest.slice(i + 1);
94
- break;
95
- }
96
- if (arg === "--workspace") {
97
- workspace = rest[++i];
98
- if (!workspace) throw new Error("--workspace 需要目录。");
99
- } else if (arg === "--url") {
100
- url = rest[++i];
101
- if (!url) throw new Error("--url 需要地址。");
102
- } else if (arg === "--cwd") {
103
- cwd = rest[++i];
104
- if (!cwd) throw new Error("--cwd 需要目录。");
105
- } else if (arg === "--description") {
106
- description = rest[++i];
107
- if (description === undefined) throw new Error("--description 需要说明文本。");
108
- } else if (arg === "--timeout") {
109
- const raw = rest[++i];
110
- timeout = Number(raw);
111
- if (!raw || !Number.isInteger(timeout)) throw new Error("--timeout 需要整数秒。");
112
- } else if (arg === "--disabled") {
113
- enabled = false;
114
- } else if (arg === "--env") {
115
- const raw = rest[++i];
116
- if (!raw) throw new Error("--env 需要 KEY=VALUE。");
117
- const [k, v] = parseKeyValue(raw, "--env");
118
- env[k] = v;
119
- } else if (arg === "--header") {
120
- const raw = rest[++i];
121
- if (!raw) throw new Error("--header 需要 KEY=VALUE。");
122
- const [k, v] = parseKeyValue(raw, "--header");
123
- headers[k] = v;
124
- } else {
125
- throw new Error(`未知参数:${arg}\n${mcpManageUsage}`);
126
- }
127
- }
128
- const base = {
129
- ...(description !== undefined ? { description } : {}),
130
- ...(timeout !== undefined ? { timeout } : {}),
131
- ...(enabled !== undefined ? { enabled } : {}),
132
- };
133
- let server: WorkspaceMcpServer;
134
- if (url !== undefined) {
135
- if (commandTokens.length || Object.keys(env).length || cwd !== undefined) {
136
- throw new Error("--url(HTTP)不能与 stdio 命令/--env/--cwd 同时使用。");
137
- }
138
- server = {
139
- url,
140
- ...(Object.keys(headers).length ? { headers } : {}),
141
- ...base,
142
- };
143
- } else {
144
- const [command, ...cmdArgs] = commandTokens;
145
- if (!command) throw new Error(`stdio 服务需要通过 -- <command> [args...] 指定启动命令。\n${mcpManageUsage}`);
146
- if (Object.keys(headers).length) throw new Error("--header 仅适用于 --url(HTTP)服务。");
147
- server = {
148
- command,
149
- ...(cmdArgs.length ? { args: cmdArgs } : {}),
150
- ...(Object.keys(env).length ? { env } : {}),
151
- ...(cwd !== undefined ? { cwd } : {}),
152
- ...base,
153
- };
154
- }
155
- const target = await resolveWorkspace(workspace ?? process.cwd(), process.cwd(), homedir());
156
- const updated = await upsertWorkspaceMcpServer(target, name, server);
157
- console.log(JSON.stringify({ workspaceRoot: target, path: updated.path, name, server: updated.servers[name] }, null, 2));
158
- return 0;
159
- }
160
- throw new Error(`未知 mcp 子命令:${sub}\n${mcpManageUsage}`);
161
- }
162
-
163
- export async function main(args: string[]): Promise<number> {
164
- let options: ReturnType<typeof parseSetupArgs>;
165
- try { options = parseSetupArgs(args); }
166
- catch (error) { console.error(String(error)); return 2; }
167
- const manifest = JSON.parse(await readFile(new URL("package.json", root), "utf8")) as { version: string };
168
- if (options.action === "version") { console.log(manifest.version); return 0; }
169
- if (options.action === "help") {
170
- console.log("Personal Bot " + manifest.version + "\n\n用法:pbot setup [--workspace <目录>]\n" +
171
- " npx personal-bot@latest setup\n" +
172
- " pbot upgrade|update [--workspace <目录>] [--version <版本>] [--hosts <列表>] [--dsh-profile <名称>] [--json]\n" +
173
- " pbot init | status [--workspace <目录>] [--json]\n" +
174
- " pbot history status|list|summary|migrate|search|read [参数] [--workspace <目录>] [--json]\n" +
175
- " pbot install-antigravity\n" +
176
- " pbot plugin <host> hook|init|status\n" +
177
- " pbot mcp\n" +
178
- " pbot mcp list|add|remove ...\n\n" +
179
- "setup 安装或升级 Pi、pbot 和选中的插件,然后启动 Pi 执行 /pbot init。\n" +
180
- "upgrade|update 将全局 CLI 与当前工作区已绑定的各宿主插件统一升级到 npm 最新稳定版。\n" +
181
- "install-antigravity 通过原生 agy plugin install 安装或更新 Antigravity 插件。\n" +
182
- "mcp 无参数时启动统一 stdio MCP 服务(暴露 worker_* 与 workspace_mcp_*);带 list/add/remove 时管理工作区 .pbot/mcp.json。\n" +
183
- "支持 Linux/macOS,需要 Node.js 22.19+ 和 npm。\n--help 显示帮助;--version 显示安装器版本。");
184
- return 0;
185
- }
186
- if (options.action === "upgrade") {
187
- try { return await runUpgradeCommand(options.upgradeArgs ?? [], options.upgradeVerb ?? "upgrade"); }
188
- catch (error) { console.error(error instanceof Error ? error.message : String(error)); return 2; }
189
- }
190
- if (options.action === "mcp-manage") {
191
- try { return await runMcpManage(options.mcpArgs ?? []); }
192
- catch (error) { console.error(error instanceof Error ? error.message : String(error)); return 2; }
193
- }
194
- if (options.action === "mcp") {
195
- const entry = fileURLToPath(new URL("lib/extension/mcp.js", root));
196
- if (!existsSync(entry)) {
197
- console.error("缺少 MCP 构建产物:" + entry + "。请先运行 npm run build。");
198
- return 1;
199
- }
200
- const child = spawnSync(process.execPath, [entry], { stdio: "inherit" });
201
- if (child.error) { console.error(String(child.error)); return 1; }
202
- return child.status ?? 0;
203
- }
204
- if (options.action === "install-antigravity") {
205
- const pluginDir = fileURLToPath(new URL("lib/antigravity-plugin", root));
206
- if (!existsSync(join(pluginDir, "plugin.json"))) {
207
- console.error("缺少 Antigravity 插件构建产物:" + pluginDir + "。请先运行 npm run build。");
208
- return 1;
209
- }
210
- const agy = process.env.PBOT_AGY_COMMAND || await findExecutable("agy", process.env);
211
- if (!agy) {
212
- console.error("未找到 Antigravity CLI(agy)。请先安装 agy,然后运行:\n agy plugin install " + quote(pluginDir));
213
- return 1;
214
- }
215
- const installed = spawnSync(agy, ["plugin", "install", pluginDir], { stdio: "inherit" });
216
- if (installed.error) { console.error(String(installed.error)); return 1; }
217
- if (installed.status !== 0) return installed.status ?? 1;
218
- console.log("Antigravity 插件已安装。在目标工作区运行 /pbot init 启用 Personal Bot。");
219
- return 0;
220
- }
221
- if (!process.stdin.isTTY || !process.stdout.isTTY) {
222
- console.error("setup 需要交互终端。请在终端运行 npx personal-bot@latest setup。"); return 2;
223
- }
224
- const controller = new AbortController();
225
- const cancel = () => controller.abort(new Error("安装已取消;已完成的步骤保留。"));
226
- process.on("SIGINT", cancel); process.on("SIGTERM", cancel);
227
- const ui = new SetupUI(controller), processes = new SetupProcesses(controller.signal);
228
- try {
229
- const cwd = process.cwd();
230
- ui.text("Personal Bot " + manifest.version + " — 安装与升级\n正在检查 Node/npm 和 tmux…");
231
- const system = await inspectSystem(processes, cwd);
232
- const supplied = options.workspace ?? await ui.ask("工作区目录(当前、已有或新建目录)", cwd);
233
- const workspace = await resolveWorkspace(supplied, cwd, homedir());
234
- const host = new PiSetup(processes, system.npm, cwd);
235
- let pi = await host.inspectPi();
236
- let installed: InstalledPackage[];
237
- try { installed = await host.inspectPackages(pi, workspace); }
238
- catch (error) {
239
- if (!(error instanceof PiBootstrapRequired)) throw error;
240
- const version = await host.latest(piPackageName);
241
- ui.text(error.message + "\n需先安装 Pi 才能使用其原生接口核对这些来源。目标版本:" + version);
242
- if (!await ui.confirm("先通过 npm 安装 Pi,再继续选择工作区插件")) return 130;
243
- pi = await host.ensurePi(undefined, version);
244
- installed = await host.inspectPackages(pi, workspace);
245
- }
246
- const catalog = parseCatalog(JSON.parse(await readFile(new URL("resources/installer/plugins.json", root), "utf8")));
247
- const choices = packageChoices(catalog, installed), optional = choices.filter(choice => !choice.required);
248
- ui.text("\nPersonal Bot 必装。选择配套插件(取消勾选不会卸载已有插件):");
249
- const selected = await ui.selectMany(optional.map(choice => choice.plugin.label + " — " + choice.plugin.description),
250
- optional.flatMap((choice, index) => choice.selected ? [index] : []));
251
- optional.forEach((choice, index) => { choice.selected = selected.includes(index); });
252
- for (const choice of choices.filter(item => item.selected)) {
253
- if (choice.existing.some(pkg => !ordinaryNpm(pkg.source))) {
254
- ui.text("\n" + choice.plugin.label + " 的已有来源:\n" + choice.existing.map(pkg =>
255
- " " + pkg.scope + ": " + pkg.source + " (" + (pkg.version ?? "版本未知") + ")").join("\n"));
256
- choice.keep = !await ui.confirm("切换到 npm 最新稳定版", false);
257
- }
258
- if (choice.keep) {
259
- if (choice.existing.length !== 1 || !choice.existing[0]?.installedPath) choice.error = "保留来源未安装或存在多份来源,请先通过 Pi 原生配置处理。";
260
- } else {
261
- const others = choice.existing.filter(pkg => !npmName(pkg.source));
262
- if (others.length > 1 || others.some(pkg => pkg.scope === "user")) {
263
- choice.error = "请先用 pi config 调整全局或重复来源的加载范围,再切换到 npm。";
264
- } else {
265
- try { choice.target = await host.latest(npmName(choice.plugin.source)!); }
266
- catch (error) { controller.signal.throwIfAborted(); choice.error = String(error); }
267
- }
268
- }
269
- }
270
- const plan: SetupPlan = { workspace, piVersion: await host.latest(piPackageName), packages: choices,
271
- ...(pi ? { pi } : {}), ...(system.tmux ? { tmux: system.tmux } : {}) };
272
- ui.text("\n安装计划\n工作区:" + workspace + "\nPi:" + (pi ? pi.command + " (" + pi.version + ")" : "通过 npm 全局安装") + " → " + plan.piVersion);
273
- if (system.tmux) ui.text("tmux:" + [system.tmux.command, ...system.tmux.args].map(quote).join(" "));
274
- for (const choice of choices) {
275
- ui.text(" " + choice.plugin.label + ": " + (!choice.selected ? "本次跳过" : choice.error ??
276
- (choice.keep ? "保留 " + choice.existing[0]?.source : (choice.existing.map(pkg => pkg.version ?? "未知").join(", ") || "未安装") + " → " + choice.target)));
277
- if (choice.selected && choice.existing.some(pkg => pkg.filtered)) ui.text(" 保留已有资源过滤;如 pbot 被禁用,请通过 pi config --local 启用。");
278
- }
279
- const blocking = choices.find(choice => choice.required && choice.error);
280
- if (blocking) throw new Error(blocking.error);
281
- ui.text("升级前请停止活动 pbot 子会话。Pi 为当前用户共用,插件只处理此工作区。");
282
- if (!await ui.confirm("执行以上计划")) return 130;
283
- await mkdir(workspace, { recursive: true });
284
- if (await realpath(workspace) !== workspace) throw new Error("工作区路径已发生变化,请重新运行 setup。");
285
- const result = await executeSetup(plan, host, item => ui.text("[" + item.state + "] " + item.name + ": " + item.detail), controller.signal);
286
- const failed = result.results.some(item => item.state === "failed");
287
- if (!result.pi) return 1;
288
- ui.text("\n软件安装阶段结束。工作区初始化和外部服务的状态由 Pi/pbot/插件分别报告。");
289
- if (await ui.confirm(failed ? "部分插件失败,是否仍启动 Pi 并初始化启用工作区" : "启动 Pi 并初始化启用工作区", !failed)) {
290
- process.stdin.pause();
291
- await host.start(result.pi, workspace);
292
- } else {
293
- ui.text("稍后执行:\ncd " + quote(workspace) + "\n" + quote(result.pi.command) + " --extension " +
294
- quote(fileURLToPath(new URL("extension/setup/guard.js", new URL("../../", import.meta.url)))) + " '/pbot init'");
295
- }
296
- return failed ? 1 : 0;
297
- } catch (error) {
298
- console.error(error instanceof Error ? error.message : String(error));
299
- return controller.signal.aborted ? 130 : 1;
300
- } finally {
301
- process.off("SIGINT", cancel); process.off("SIGTERM", cancel);
302
- }
303
- }
@@ -1,158 +0,0 @@
1
- import { readFile } from "node:fs/promises";
2
- import { homedir } from "node:os";
3
- import { join } from "node:path";
4
- import { fileURLToPath } from "node:url";
5
- import { valid } from "semver";
6
- import { object } from "../../common/json.js";
7
- import { checkStableVersion } from "../../common/package-source.js";
8
- import { packageVersion } from "../../common/version.js";
9
- import { execCliEntry, upgradeManagedGlobalCli } from "../../integrations/installation/cli-update.js";
10
- import { findExecutable, SetupProcesses } from "../../integrations/installation/processes.js";
11
- import { getHostUpgrader } from "../../integrations/installation/upgraders/registry.js";
12
- import { resolveWorkspace } from "../../integrations/installation/workspace.js";
13
- import type { CliUpgradeSummary, HostUpgradeResult, WorkspaceUpgradeSummary } from "../../model/installation.js";
14
- import {
15
- executeWorkspaceUpgrade,
16
- parseUpgradeArgs,
17
- upgradeUsage,
18
- type WorkspaceUpgradeTarget,
19
- } from "../../services/installation/upgrade-service.js";
20
- import { workspacePluginBindings } from "../../services/workspace/plugin-releases.js";
21
-
22
- const packageRoot = fileURLToPath(new URL("../../../", import.meta.url));
23
-
24
- async function latestStableVersion(processes: SetupProcesses, cwd: string): Promise<string> {
25
- const npm = await findExecutable("npm", processes.env);
26
- if (!npm) throw new Error("未找到 npm,无法查询 personal-bot 最新稳定版。");
27
- const text = await processes.run(npm, ["view", "personal-bot@latest", "version", "engines", "--json",
28
- "--fetch-retries=0", "--fetch-timeout=15000"], cwd);
29
- const value = JSON.parse(text) as { version?: string; engines?: { node?: string } };
30
- if (typeof value.version !== "string") throw new Error("无法取得 personal-bot 的最新版本。");
31
- return checkStableVersion(value.version, value.engines?.node);
32
- }
33
-
34
- async function discoverWorkspaceTargets(workspace: string, requestedHosts?: readonly string[]): Promise<WorkspaceUpgradeTarget[]> {
35
- const bindings = workspacePluginBindings(workspace);
36
- const byHost = new Map<string, WorkspaceUpgradeTarget>();
37
- for (const [host, entry] of Object.entries(bindings)) {
38
- byHost.set(host, {
39
- host,
40
- currentVersion: entry.version,
41
- ...(entry.bindingPath ? { bindingPath: entry.bindingPath } : {}),
42
- });
43
- }
44
- if (!byHost.has("pi")) {
45
- const localPiManifest = join(workspace, ".pi", "npm", "node_modules", "personal-bot", "package.json");
46
- try {
47
- const manifest: unknown = JSON.parse(await readFile(localPiManifest, "utf8"));
48
- if (object(manifest) && manifest.name === "personal-bot" && typeof manifest.version === "string" && valid(manifest.version)) {
49
- byHost.set("pi", { host: "pi", currentVersion: manifest.version, bindingPath: localPiManifest });
50
- }
51
- } catch (error) {
52
- if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
53
- }
54
- }
55
- if (requestedHosts) {
56
- return requestedHosts.map(host => byHost.get(host) ?? { host });
57
- }
58
- return [...byHost.values()].sort((a, b) => a.host.localeCompare(b.host));
59
- }
60
-
61
- function formatLine(result: HostUpgradeResult): string {
62
- const transition = result.previousVersion && result.version && result.previousVersion !== result.version
63
- ? `${result.previousVersion} → ${result.version}`
64
- : result.version ?? result.previousVersion ?? "";
65
- const scope = result.scope ? ` (${result.scope})` : "";
66
- const head = `[${result.state}] ${result.host}${scope}${transition ? " " + transition : ""}: ${result.detail}`;
67
- return result.nextStep ? `${head}\n 下一步:${result.nextStep}` : head;
68
- }
69
-
70
- function printHumanSummary(summary: WorkspaceUpgradeSummary): void {
71
- console.log(`工作区:${summary.workspaceRoot}`);
72
- console.log(`目标版本:${summary.targetVersion}`);
73
- console.log(`[${summary.cli.state}] cli ${summary.cli.previousVersion} → ${summary.cli.version}: ${summary.cli.detail}`);
74
- if (!summary.results.length) {
75
- console.log("当前工作区尚未绑定任何宿主插件。如需指定宿主,可传入 --hosts <宿主列表>。");
76
- return;
77
- }
78
- for (const result of summary.results) console.log(formatLine(result));
79
- }
80
-
81
- export async function runUpgradeCommand(rawArgs: string[], rawVerb: "upgrade" | "update" = "upgrade"): Promise<number> {
82
- const options = parseUpgradeArgs(rawArgs);
83
- if (options.help) {
84
- console.log(upgradeUsage);
85
- return 0;
86
- }
87
- const controller = new AbortController();
88
- const cancel = () => controller.abort(new Error("升级已取消。"));
89
- process.on("SIGINT", cancel);
90
- process.on("SIGTERM", cancel);
91
- try {
92
- const cwd = process.cwd();
93
- const workspace = await resolveWorkspace(options.workspace ?? cwd, cwd, homedir());
94
- const processes = new SetupProcesses(controller.signal, process.env);
95
- const targetVersion = options.version ?? await latestStableVersion(processes, cwd);
96
-
97
- let cli: CliUpgradeSummary;
98
- if (process.env.PBOT_UPGRADING_CLI === targetVersion) {
99
- cli = {
100
- state: "updated",
101
- previousVersion: process.env.PBOT_UPGRADING_PREVIOUS_VERSION || packageVersion,
102
- version: packageVersion,
103
- detail: `已将全局 CLI 更新到 ${packageVersion}。`,
104
- };
105
- } else {
106
- const cliResult = await upgradeManagedGlobalCli(targetVersion, process.env);
107
- if (cliResult.state === "updated" && cliResult.globalDirectory) {
108
- const nextEnv = {
109
- ...process.env,
110
- PBOT_UPGRADING_CLI: targetVersion,
111
- PBOT_UPGRADING_PREVIOUS_VERSION: packageVersion,
112
- };
113
- return await execCliEntry(join(cliResult.globalDirectory, "bin", "pbot.mjs"), [rawVerb, ...rawArgs], nextEnv);
114
- }
115
- cli = {
116
- state: cliResult.state,
117
- previousVersion: packageVersion,
118
- version: packageVersion,
119
- detail: cliResult.detail,
120
- };
121
- }
122
-
123
- const targets = await discoverWorkspaceTargets(workspace, options.hosts);
124
- const summary = await executeWorkspaceUpgrade({
125
- workspaceRoot: workspace,
126
- targetVersion,
127
- cli,
128
- targets,
129
- resolveUpgrader: getHostUpgrader,
130
- createContext: target => ({
131
- workspace,
132
- targetVersion,
133
- ...(target.currentVersion ? { currentVersion: target.currentVersion } : {}),
134
- packageRoot,
135
- ...(target.bindingPath ? { bindingPath: target.bindingPath } : {}),
136
- env: process.env,
137
- signal: controller.signal,
138
- options: { dshProfile: options.dshProfile },
139
- run: (command, args, runCwd, runOptions) => processes.run(command, args, runCwd, runOptions),
140
- findExecutable: name => findExecutable(name, process.env),
141
- }),
142
- signal: controller.signal,
143
- });
144
-
145
- if (options.json) console.log(JSON.stringify(summary, null, 2));
146
- else printHumanSummary(summary);
147
- return summary.ok ? 0 : 1;
148
- } catch (error) {
149
- if (controller.signal.aborted) {
150
- console.error("升级已取消。");
151
- return 130;
152
- }
153
- throw error;
154
- } finally {
155
- process.off("SIGINT", cancel);
156
- process.off("SIGTERM", cancel);
157
- }
158
- }
@@ -1,167 +0,0 @@
1
- import { realpathSync } from "node:fs";
2
- import { mkdir, stat } from "node:fs/promises";
3
- import { homedir } from "node:os";
4
- import { pathToFileURL } from "node:url";
5
- import { parseArgs } from "node:util";
6
- import { gte, valid } from "semver";
7
- import { requireThat } from "../../common/validation.js";
8
- import { packageVersion } from "../../common/version.js";
9
- import { getPluginHost, pluginMcpWorkspaceRoot } from "../../integrations/hosts/plugin-registry.js";
10
- import { minimumCliRelease, runUpdatedCli } from "../../integrations/installation/cli-update.js";
11
- import { resolveWorkspace } from "../../integrations/installation/workspace.js";
12
- import { parseHistoryCommand, type ParsedHistoryCommand } from "../../services/history/summary-command.js";
13
- import { workspacePluginDrift, workspacePluginReleases } from "../../services/workspace/plugin-releases.js";
14
- import { readWorkspaceConfig, workspaceDisabledMessage, workspaceFeatures } from "../../services/workspace/workspace-config.js";
15
- import { initializeWorkspace } from "../../services/workspace/workspace-preparation.js";
16
-
17
- const usage = `pbot init | status [--workspace <目录>] [--json]
18
- pbot history status | list
19
- pbot history summary [维度...] [--force] [--backend <acp>] [--model <模型>] [--thinking <级别>]
20
- pbot history migrate [--dry-run]
21
- pbot history search [关键词] [--host <来源>] [--dimension <维度>] [--session-id <ID>] [--from <时间>] [--to <时间>] [--offset N] [--limit N]
22
- pbot history read <节点ID> [--host <来源>] [--offset N] [--limit N] [--children-offset N]
23
- 所有工作区命令支持 --workspace <目录> 和 --json。默认工作区为当前目录。`;
24
-
25
- function workspaceArgs(args: readonly string[]) {
26
- const rest: string[] = [];
27
- let workspace: string | undefined;
28
- let json = false;
29
- for (let index = 0; index < args.length; index++) {
30
- const token = args[index]!;
31
- if (token === "--") { rest.push(...args.slice(index)); break; }
32
- if (token === "--workspace" || token.startsWith("--workspace=")) {
33
- requireThat(workspace === undefined, "--workspace 只能指定一次。");
34
- workspace = token === "--workspace" ? args[++index] : token.slice("--workspace=".length);
35
- requireThat(workspace && !workspace.startsWith("-"), "--workspace 需要目录。");
36
- } else if (token === "--json") json = true;
37
- else rest.push(token);
38
- }
39
- return { workspace, json, rest };
40
- }
41
-
42
- function historyAction(args: string[]): ParsedHistoryCommand {
43
- const [action, ...rest] = args;
44
- if (action !== "search" && action !== "read") return parseHistoryCommand(args);
45
- const string = { type: "string" } as const;
46
- const { values, positionals } = parseArgs({
47
- args: rest, allowPositionals: true,
48
- options: {
49
- host: string, offset: string, limit: string,
50
- ...(action === "search" ? { dimension: string, "session-id": string, from: string, to: string } : { "children-offset": string }),
51
- },
52
- });
53
- requireThat(positionals.length <= 1 && (action === "search" || positionals[0]), usage);
54
- const input: Record<string, unknown> = { action };
55
- if (positionals.length) input[action === "search" ? "query" : "id"] = positionals[0];
56
- for (const [key, value] of Object.entries(values)) {
57
- if (["offset", "limit", "children-offset"].includes(key)) {
58
- requireThat(typeof value === "string" && /^\d+$/.test(value) && Number.isSafeInteger(Number(value)), "--" + key + " 需要非负整数。");
59
- input[key === "children-offset" ? "childrenOffset" : key] = Number(value);
60
- } else input[key === "session-id" ? "sessionId" : key] = value;
61
- }
62
- return { kind: "query", input };
63
- }
64
-
65
- export async function updateForWorkspace(root: string, args: string[], input?: string): Promise<number | undefined> {
66
- return runUpdatedCli(await minimumCliRelease(root, workspacePluginReleases(root)), args, input);
67
- }
68
-
69
- /** Hook workspaces are resolved by the adapter from the event on stdin. */
70
- export async function updateForCommand(args: string[]): Promise<number | undefined> {
71
- if (args[0] === "plugin" && args[2] === "hook") return undefined;
72
- const cwd = process.cwd();
73
- let workspace: string;
74
- if (args[0] === "plugin" && args[1]) {
75
- workspace = await getPluginHost(args[1])?.resolveRoot(cwd) ?? cwd;
76
- } else if (args[0] === "mcp" && args.length === 1) {
77
- workspace = pluginMcpWorkspaceRoot() ?? cwd;
78
- } else {
79
- workspace = workspaceArgs(args).workspace ?? cwd;
80
- }
81
- const root = await resolveWorkspace(workspace, cwd, homedir());
82
- const configuration = await readWorkspaceConfig(root);
83
- const initializing = args[0] === "plugin" && args[2] === "init" && args.length === 3;
84
- if (!configuration.enabled && !(initializing && !configuration.error)) return undefined;
85
- return updateForWorkspace(root, args);
86
- }
87
-
88
- export async function main(args: string[]): Promise<number> {
89
- if (args[0] === "--at-least") {
90
- const version = args[1];
91
- requireThat(args.length === 2 && version && valid(version), "用法:pbot --at-least <MAJOR.MINOR.PATCH>");
92
- return gte(packageVersion, version) ? 0 : 1;
93
- }
94
- const { workspace, json, rest } = workspaceArgs(args);
95
- const [verb, ...tail] = rest;
96
- const delimiter = rest.indexOf("--");
97
- if (rest.slice(0, delimiter < 0 ? rest.length : delimiter).some(token => token === "--help" || token === "-h")) {
98
- console.log(usage);
99
- return 0;
100
- }
101
- requireThat(verb === "history" || ["init", "status", "--version", "-v"].includes(verb ?? "") && !tail.length, usage);
102
- if (verb === "--version" || verb === "-v") { console.log(packageVersion); return 0; }
103
- const cwd = process.cwd();
104
- const root = await resolveWorkspace(workspace ?? cwd, cwd, homedir());
105
- let configuration = await readWorkspaceConfig(root);
106
- if (verb === "init" && configuration.error) throw new Error(configuration.error);
107
- if (verb === "history") {
108
- requireThat(configuration.enabled, workspaceDisabledMessage(configuration));
109
- requireThat(workspaceFeatures(configuration).history, "当前工作区已停用历史功能(features.history: false)。");
110
- }
111
- const checkRelease = configuration.enabled || verb === "init";
112
- const plugins = checkRelease ? workspacePluginReleases(root) : {};
113
- const required = checkRelease ? await minimumCliRelease(root, plugins) : undefined;
114
- const updated = await runUpdatedCli(required, args);
115
- if (updated !== undefined) return updated;
116
- const print = (result: unknown) => console.log(JSON.stringify(result, null, json ? undefined : 2));
117
- if (verb === "init") {
118
- await mkdir(root, { recursive: true });
119
- await initializeWorkspace(root);
120
- configuration = await readWorkspaceConfig(root);
121
- }
122
- requireThat((await stat(root)).isDirectory(), "工作区必须是目录。");
123
- if (verb !== "history") {
124
- const drift = workspacePluginDrift(plugins);
125
- print({
126
- workspaceRoot: root,
127
- version: packageVersion,
128
- plugins,
129
- outOfSync: drift.outOfSync,
130
- minimumCliVersion: required ?? null,
131
- configuration,
132
- });
133
- return configuration.error ? 1 : 0;
134
- }
135
- const command = historyAction(tail);
136
- const controller = new AbortController();
137
- let exitCode = 0;
138
- const interrupt = () => { exitCode = 130; controller.abort(); };
139
- const terminate = () => { exitCode = 143; controller.abort(); };
140
- process.on("SIGINT", interrupt);
141
- process.on("SIGTERM", terminate);
142
- try {
143
- const { runHistoryCommand } = await import("../history/command.js");
144
- const result = await runHistoryCommand({ root, features: workspaceFeatures(configuration) }, command, controller.signal, {
145
- start: backend => console.error("历史摘要生成中 (" + backend + ")"),
146
- update: event => console.error(`${event.dimension} ${event.completed}/${event.total}`),
147
- });
148
- print(result);
149
- if ("backend" in result && result.dimensions.some(dimension => dimension.failed.length)) return 1;
150
- if ("errors" in result && (result.errors.length || result.skipped.length)) return 1;
151
- return 0;
152
- } catch (error) {
153
- if (!exitCode) throw error;
154
- console.error("历史操作已取消。");
155
- return exitCode;
156
- } finally {
157
- process.off("SIGINT", interrupt);
158
- process.off("SIGTERM", terminate);
159
- }
160
- }
161
-
162
- if (process.argv[1] && import.meta.url === pathToFileURL(realpathSync(process.argv[1])).href) {
163
- main(process.argv.slice(2)).then(code => { process.exitCode = code; }).catch(error => {
164
- console.error(error instanceof Error ? error.message : String(error));
165
- process.exitCode = 1;
166
- });
167
- }