personal-bot 0.3.3 → 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 (71) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/README.md +2 -2
  4. package/README.zh-CN.md +2 -2
  5. package/bin/pbot.mjs +3 -17
  6. package/docs/architecture/design.md +8 -6
  7. package/docs/architecture/extensibility.md +21 -0
  8. package/docs/architecture/principles.md +1 -1
  9. package/docs/guides/workspace-configuration.md +13 -0
  10. package/lib/antigravity-plugin/lib/common/paths.d.ts +1 -0
  11. package/lib/antigravity-plugin/lib/common/paths.js +2 -0
  12. package/lib/antigravity-plugin/lib/extension/acp-worker.js +26 -24
  13. package/lib/antigravity-plugin/lib/extension/cli.js +22596 -0
  14. package/lib/antigravity-plugin/lib/extension/hosts/plugin-runtime.js +9 -2
  15. package/lib/antigravity-plugin/lib/extension/mcp.js +22 -20
  16. package/lib/antigravity-plugin/lib/extension/workspace-cli.js +5 -20121
  17. package/lib/antigravity-plugin/lib/services/workspace/plugin-releases.d.ts +12 -0
  18. package/lib/antigravity-plugin/lib/services/workspace/plugin-releases.js +52 -4
  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 +22596 -0
  29. package/lib/extension/hosts/plugin-runtime.js +9 -2
  30. package/lib/extension/mcp.js +22 -20
  31. package/lib/extension/workspace-cli.js +5 -20121
  32. package/lib/qoder-plugin/.mcp.json +2 -2
  33. package/lib/qoder-plugin/.qoder-plugin/plugin.json +1 -1
  34. package/lib/qoder-plugin/hooks/hooks.json +3 -3
  35. package/lib/qoder-plugin/skills/pbot/SKILL.md +1 -1
  36. package/lib/services/workspace/plugin-releases.d.ts +12 -0
  37. package/lib/services/workspace/plugin-releases.js +52 -4
  38. package/package.json +1 -1
  39. package/scripts/README.md +1 -1
  40. package/src/common/paths.ts +2 -0
  41. package/src/extension/cli/args.ts +104 -0
  42. package/src/extension/cli/commands/history.ts +81 -0
  43. package/src/extension/cli/commands/mcp.ts +165 -0
  44. package/src/extension/cli/commands/plugin.ts +33 -0
  45. package/src/extension/cli/commands/setup.ts +159 -0
  46. package/src/extension/cli/commands/upgrade.ts +158 -0
  47. package/src/extension/cli/commands/workspace.ts +71 -0
  48. package/src/extension/cli/index.ts +193 -0
  49. package/src/extension/cli/types.ts +30 -0
  50. package/src/extension/hosts/plugin-runtime.ts +9 -2
  51. package/src/integrations/installation/cli-update.ts +31 -3
  52. package/src/integrations/installation/pi-setup.ts +6 -3
  53. package/src/integrations/installation/upgraders/antigravity.ts +68 -0
  54. package/src/integrations/installation/upgraders/claude.ts +123 -0
  55. package/src/integrations/installation/upgraders/codex.ts +73 -0
  56. package/src/integrations/installation/upgraders/dsh.ts +63 -0
  57. package/src/integrations/installation/upgraders/pi.ts +87 -0
  58. package/src/integrations/installation/upgraders/qoder.ts +68 -0
  59. package/src/integrations/installation/upgraders/registry.ts +48 -0
  60. package/src/model/installation.ts +45 -0
  61. package/src/services/installation/setup-service.ts +0 -30
  62. package/src/services/installation/upgrade-service.ts +127 -0
  63. package/src/services/workspace/plugin-releases.ts +57 -4
  64. package/lib/extension/setup/cli.js +0 -352
  65. package/lib/integrations/installation/pi-setup.js +0 -193
  66. package/lib/integrations/installation/processes.js +0 -140
  67. package/lib/integrations/installation/workspace.js +0 -21
  68. package/lib/services/installation/setup-service.js +0 -137
  69. package/lib/ui/setup.js +0 -52
  70. package/src/extension/setup/cli.ts +0 -296
  71. package/src/extension/setup/workspace-cli.ts +0 -159
@@ -0,0 +1,159 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import { existsSync } from "node:fs";
3
+ import { mkdir, readFile, realpath } from "node:fs/promises";
4
+ import { join } from "node:path";
5
+ import { npmName, ordinaryNpm } from "../../../common/package-source.js";
6
+ import { packageRoot } from "../../../common/paths.js";
7
+ import { packageVersion } from "../../../common/version.js";
8
+ import { PiBootstrapRequired, PiSetup, piPackageName } from "../../../integrations/installation/pi-setup.js";
9
+ import { findExecutable, inspectSystem, SetupProcesses } from "../../../integrations/installation/processes.js";
10
+ import type { InstalledPackage, SetupPlan } from "../../../model/installation.js";
11
+ import { executeSetup, packageChoices, parseCatalog } from "../../../services/installation/setup-service.js";
12
+ import { SetupUI } from "../../../ui/setup.js";
13
+ import { CliError, requireNoExtraArgs, resolveCliWorkspace, withSignals } from "../args.js";
14
+ import type { CliCommand } from "../types.js";
15
+
16
+ const quote = (value: string) => "'" + value.replaceAll("'", "'\\''") + "'";
17
+
18
+ const setupUsage =
19
+ "用法:pbot setup [--workspace <目录>]\n" +
20
+ "安装或升级 Pi、Personal Bot 和选中的配套插件,然后启动 Pi 执行 /pbot init。";
21
+
22
+ const installAntigravityUsage =
23
+ "用法:pbot install-antigravity\n" +
24
+ "通过原生 agy plugin install 安装或更新 Antigravity 插件。";
25
+
26
+ export const setupCommand: CliCommand = {
27
+ name: "setup",
28
+ summary: "交互式安装或升级 Pi 与工作区插件",
29
+ usage: setupUsage,
30
+ updatePolicy: "none",
31
+ supportsWorkspaceFlag: true,
32
+ async run(ctx) {
33
+ requireNoExtraArgs(ctx.args, setupUsage);
34
+ if (!process.stdin.isTTY || !process.stdout.isTTY) {
35
+ throw new CliError("setup 需要交互终端。请在终端运行 npx personal-bot@latest setup。", 2);
36
+ }
37
+ const outcome = await withSignals(
38
+ async controller => {
39
+ const ui = new SetupUI(controller);
40
+ const processes = new SetupProcesses(controller.signal);
41
+ const cwd = ctx.cwd;
42
+ ui.text("Personal Bot " + packageVersion + " — 安装与升级\n正在检查 Node/npm 和 tmux…");
43
+ const system = await inspectSystem(processes, cwd);
44
+ const supplied = ctx.workspace ?? await ui.ask("工作区目录(当前、已有或新建目录)", cwd);
45
+ const workspace = await resolveCliWorkspace(supplied, cwd);
46
+ const host = new PiSetup(processes, system.npm, cwd);
47
+ let pi = await host.inspectPi();
48
+ let installed: InstalledPackage[];
49
+ try {
50
+ installed = await host.inspectPackages(pi, workspace);
51
+ } catch (error) {
52
+ if (!(error instanceof PiBootstrapRequired)) throw error;
53
+ const version = await host.latest(piPackageName);
54
+ ui.text(error.message + "\n需先安装 Pi 才能使用其原生接口核对这些来源。目标版本:" + version);
55
+ if (!await ui.confirm("先通过 npm 安装 Pi,再继续选择工作区插件")) return 130;
56
+ pi = await host.ensurePi(undefined, version);
57
+ installed = await host.inspectPackages(pi, workspace);
58
+ }
59
+ const catalog = parseCatalog(JSON.parse(await readFile(join(packageRoot, "resources/installer/plugins.json"), "utf8")));
60
+ const choices = packageChoices(catalog, installed);
61
+ const optional = choices.filter(choice => !choice.required);
62
+ ui.text("\nPersonal Bot 必装。选择配套插件(取消勾选不会卸载已有插件):");
63
+ const selected = await ui.selectMany(
64
+ optional.map(choice => choice.plugin.label + " — " + choice.plugin.description),
65
+ optional.flatMap((choice, index) => choice.selected ? [index] : []),
66
+ );
67
+ optional.forEach((choice, index) => { choice.selected = selected.includes(index); });
68
+ for (const choice of choices.filter(item => item.selected)) {
69
+ if (choice.existing.some(pkg => !ordinaryNpm(pkg.source))) {
70
+ ui.text("\n" + choice.plugin.label + " 的已有来源:\n" + choice.existing.map(pkg =>
71
+ " " + pkg.scope + ": " + pkg.source + " (" + (pkg.version ?? "版本未知") + ")").join("\n"));
72
+ choice.keep = !await ui.confirm("切换到 npm 最新稳定版", false);
73
+ }
74
+ if (choice.keep) {
75
+ if (choice.existing.length !== 1 || !choice.existing[0]?.installedPath) {
76
+ choice.error = "保留来源未安装或存在多份来源,请先通过 Pi 原生配置处理。";
77
+ }
78
+ } else {
79
+ const others = choice.existing.filter(pkg => !npmName(pkg.source));
80
+ if (others.length > 1 || others.some(pkg => pkg.scope === "user")) {
81
+ choice.error = "请先用 pi config 调整全局或重复来源的加载范围,再切换到 npm。";
82
+ } else {
83
+ try {
84
+ choice.target = await host.latest(npmName(choice.plugin.source)!);
85
+ } catch (error) {
86
+ controller.signal.throwIfAborted();
87
+ choice.error = String(error);
88
+ }
89
+ }
90
+ }
91
+ }
92
+ const plan: SetupPlan = {
93
+ workspace,
94
+ piVersion: await host.latest(piPackageName),
95
+ packages: choices,
96
+ ...(pi ? { pi } : {}),
97
+ ...(system.tmux ? { tmux: system.tmux } : {}),
98
+ };
99
+ ui.text("\n安装计划\n工作区:" + workspace + "\nPi:" + (pi ? pi.command + " (" + pi.version + ")" : "通过 npm 全局安装") + " → " + plan.piVersion);
100
+ if (system.tmux) ui.text("tmux:" + [system.tmux.command, ...system.tmux.args].map(quote).join(" "));
101
+ for (const choice of choices) {
102
+ ui.text(" " + choice.plugin.label + ": " + (!choice.selected ? "本次跳过" : choice.error ??
103
+ (choice.keep ? "保留 " + choice.existing[0]?.source : (choice.existing.map(pkg => pkg.version ?? "未知").join(", ") || "未安装") + " → " + choice.target)));
104
+ if (choice.selected && choice.existing.some(pkg => pkg.filtered)) {
105
+ ui.text(" 保留已有资源过滤;如 pbot 被禁用,请通过 pi config --local 启用。");
106
+ }
107
+ }
108
+ const blocking = choices.find(choice => choice.required && choice.error);
109
+ if (blocking) throw new Error(blocking.error);
110
+ ui.text("升级前请停止活动 pbot 子会话。Pi 为当前用户共用,插件只处理此工作区。");
111
+ if (!await ui.confirm("执行以上计划")) return 130;
112
+ await mkdir(workspace, { recursive: true });
113
+ if (await realpath(workspace) !== workspace) throw new Error("工作区路径已发生变化,请重新运行 setup。");
114
+ const result = await executeSetup(plan, host, item => ui.text("[" + item.state + "] " + item.name + ": " + item.detail), controller.signal);
115
+ const failed = result.results.some(item => item.state === "failed");
116
+ if (!result.pi) return 1;
117
+ ui.text("\n软件安装阶段结束。工作区初始化和外部服务的状态由 Pi/pbot/插件分别报告。");
118
+ if (await ui.confirm(failed ? "部分插件失败,是否仍启动 Pi 并初始化启用工作区" : "启动 Pi 并初始化启用工作区", !failed)) {
119
+ process.stdin.pause();
120
+ await host.start(result.pi, workspace);
121
+ } else {
122
+ ui.text("稍后执行:\ncd " + quote(workspace) + "\n" + quote(result.pi.command) + " --extension " +
123
+ quote(join(packageRoot, "lib/extension/setup/guard.js")) + " '/pbot init'");
124
+ }
125
+ return failed ? 1 : 0;
126
+ },
127
+ () => console.error("安装已取消;已完成的步骤保留。"),
128
+ );
129
+ return outcome.ok ? outcome.value : outcome.exitCode;
130
+ },
131
+ };
132
+
133
+ export const installAntigravityCommand: CliCommand = {
134
+ name: "install-antigravity",
135
+ summary: "安装或更新 Antigravity 插件",
136
+ usage: installAntigravityUsage,
137
+ updatePolicy: "none",
138
+ async run(ctx) {
139
+ requireNoExtraArgs(ctx.args, installAntigravityUsage);
140
+ const pluginDir = join(packageRoot, "lib/antigravity-plugin");
141
+ if (!existsSync(join(pluginDir, "plugin.json"))) {
142
+ console.error("缺少 Antigravity 插件构建产物:" + pluginDir + "。请先运行 npm run build。");
143
+ return 1;
144
+ }
145
+ const agy = process.env.PBOT_AGY_COMMAND || await findExecutable("agy", process.env);
146
+ if (!agy) {
147
+ console.error("未找到 Antigravity CLI(agy)。请先安装 agy,然后运行:\n agy plugin install " + quote(pluginDir));
148
+ return 1;
149
+ }
150
+ const installed = spawnSync(agy, ["plugin", "install", pluginDir], { stdio: "inherit" });
151
+ if (installed.error) {
152
+ console.error(String(installed.error));
153
+ return 1;
154
+ }
155
+ if (installed.status !== 0) return installed.status ?? 1;
156
+ console.log("Antigravity 插件已安装。在目标工作区运行 /pbot init 启用 Personal Bot。");
157
+ return 0;
158
+ },
159
+ };
@@ -0,0 +1,158 @@
1
+ import { readFile } from "node:fs/promises";
2
+ import { join } from "node:path";
3
+ import { valid } from "semver";
4
+ import { object } from "../../../common/json.js";
5
+ import { checkStableVersion } from "../../../common/package-source.js";
6
+ import { packageRoot } from "../../../common/paths.js";
7
+ import { packageVersion } from "../../../common/version.js";
8
+ import { execCliEntry, upgradeManagedGlobalCli } from "../../../integrations/installation/cli-update.js";
9
+ import { findExecutable, SetupProcesses } from "../../../integrations/installation/processes.js";
10
+ import { getHostUpgrader } from "../../../integrations/installation/upgraders/registry.js";
11
+ import type { CliUpgradeSummary, HostUpgradeResult, WorkspaceUpgradeSummary } from "../../../model/installation.js";
12
+ import {
13
+ executeWorkspaceUpgrade,
14
+ parseUpgradeArgs,
15
+ upgradeUsage,
16
+ type WorkspaceUpgradeTarget,
17
+ } from "../../../services/installation/upgrade-service.js";
18
+ import { workspacePluginBindings } from "../../../services/workspace/plugin-releases.js";
19
+ import { CliError, resolveCliWorkspace, withSignals } from "../args.js";
20
+ import type { CliCommand } from "../types.js";
21
+
22
+ async function latestStableVersion(processes: SetupProcesses, cwd: string): Promise<string> {
23
+ const npm = await findExecutable("npm", processes.env);
24
+ if (!npm) throw new Error("未找到 npm,无法查询 personal-bot 最新稳定版。");
25
+ const text = await processes.run(npm, ["view", "personal-bot@latest", "version", "engines", "--json",
26
+ "--fetch-retries=0", "--fetch-timeout=15000"], cwd);
27
+ const value = JSON.parse(text) as { version?: string; engines?: { node?: string } };
28
+ if (typeof value.version !== "string") throw new Error("无法取得 personal-bot 的最新版本。");
29
+ return checkStableVersion(value.version, value.engines?.node);
30
+ }
31
+
32
+ async function discoverWorkspaceTargets(workspace: string, requestedHosts?: readonly string[]): Promise<WorkspaceUpgradeTarget[]> {
33
+ const bindings = workspacePluginBindings(workspace);
34
+ const byHost = new Map<string, WorkspaceUpgradeTarget>();
35
+ for (const [host, entry] of Object.entries(bindings)) {
36
+ byHost.set(host, {
37
+ host,
38
+ currentVersion: entry.version,
39
+ ...(entry.bindingPath ? { bindingPath: entry.bindingPath } : {}),
40
+ });
41
+ }
42
+ if (!byHost.has("pi")) {
43
+ const localPiManifest = join(workspace, ".pi", "npm", "node_modules", "personal-bot", "package.json");
44
+ try {
45
+ const manifest: unknown = JSON.parse(await readFile(localPiManifest, "utf8"));
46
+ if (object(manifest) && manifest.name === "personal-bot" && typeof manifest.version === "string" && valid(manifest.version)) {
47
+ byHost.set("pi", { host: "pi", currentVersion: manifest.version, bindingPath: localPiManifest });
48
+ }
49
+ } catch (error) {
50
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
51
+ }
52
+ }
53
+ if (requestedHosts) {
54
+ return requestedHosts.map(host => byHost.get(host) ?? { host });
55
+ }
56
+ return [...byHost.values()].sort((a, b) => a.host.localeCompare(b.host));
57
+ }
58
+
59
+ function formatLine(result: HostUpgradeResult): string {
60
+ const transition = result.previousVersion && result.version && result.previousVersion !== result.version
61
+ ? `${result.previousVersion} → ${result.version}`
62
+ : result.version ?? result.previousVersion ?? "";
63
+ const scope = result.scope ? ` (${result.scope})` : "";
64
+ const head = `[${result.state}] ${result.host}${scope}${transition ? " " + transition : ""}: ${result.detail}`;
65
+ return result.nextStep ? `${head}\n 下一步:${result.nextStep}` : head;
66
+ }
67
+
68
+ function printHumanSummary(summary: WorkspaceUpgradeSummary): void {
69
+ console.log(`工作区:${summary.workspaceRoot}`);
70
+ console.log(`目标版本:${summary.targetVersion}`);
71
+ console.log(`[${summary.cli.state}] cli ${summary.cli.previousVersion} → ${summary.cli.version}: ${summary.cli.detail}`);
72
+ if (!summary.results.length) {
73
+ console.log("当前工作区尚未绑定任何宿主插件。如需指定宿主,可传入 --hosts <宿主列表>。");
74
+ return;
75
+ }
76
+ for (const result of summary.results) console.log(formatLine(result));
77
+ }
78
+
79
+ export const upgradeCommand: CliCommand = {
80
+ name: "upgrade",
81
+ aliases: ["update"],
82
+ summary: "统一升级全局 CLI 与当前工作区已绑定的各宿主插件",
83
+ usage: upgradeUsage,
84
+ updatePolicy: "none",
85
+ supportsWorkspaceFlag: true,
86
+ supportsJsonFlag: true,
87
+ async run(ctx) {
88
+ let parsed: ReturnType<typeof parseUpgradeArgs>;
89
+ try {
90
+ parsed = parseUpgradeArgs(ctx.args);
91
+ } catch (error) {
92
+ throw new CliError(error instanceof Error ? error.message : String(error), 2);
93
+ }
94
+ const workspaceArg = ctx.workspace ?? parsed.workspace;
95
+ const json = ctx.json || parsed.json;
96
+ const outcome = await withSignals(
97
+ async controller => {
98
+ const workspace = await resolveCliWorkspace(workspaceArg, ctx.cwd);
99
+ const processes = new SetupProcesses(controller.signal, process.env);
100
+ const targetVersion = parsed.version ?? await latestStableVersion(processes, ctx.cwd);
101
+
102
+ let cli: CliUpgradeSummary;
103
+ if (process.env.PBOT_UPGRADING_CLI === targetVersion) {
104
+ cli = {
105
+ state: "updated",
106
+ previousVersion: process.env.PBOT_UPGRADING_PREVIOUS_VERSION || packageVersion,
107
+ version: packageVersion,
108
+ detail: `已将全局 CLI 更新到 ${packageVersion}。`,
109
+ };
110
+ } else {
111
+ const cliResult = await upgradeManagedGlobalCli(targetVersion, process.env);
112
+ if (cliResult.state === "updated" && cliResult.globalDirectory) {
113
+ const nextEnv = {
114
+ ...process.env,
115
+ PBOT_UPGRADING_CLI: targetVersion,
116
+ PBOT_UPGRADING_PREVIOUS_VERSION: packageVersion,
117
+ };
118
+ return execCliEntry(join(cliResult.globalDirectory, "bin", "pbot.mjs"), ctx.rawArgs, nextEnv);
119
+ }
120
+ cli = {
121
+ state: cliResult.state,
122
+ previousVersion: packageVersion,
123
+ version: packageVersion,
124
+ detail: cliResult.detail,
125
+ };
126
+ }
127
+
128
+ const targets = await discoverWorkspaceTargets(workspace, parsed.hosts);
129
+ const summary = await executeWorkspaceUpgrade({
130
+ workspaceRoot: workspace,
131
+ targetVersion,
132
+ cli,
133
+ targets,
134
+ resolveUpgrader: getHostUpgrader,
135
+ createContext: target => ({
136
+ workspace,
137
+ targetVersion,
138
+ ...(target.currentVersion ? { currentVersion: target.currentVersion } : {}),
139
+ packageRoot,
140
+ ...(target.bindingPath ? { bindingPath: target.bindingPath } : {}),
141
+ env: process.env,
142
+ signal: controller.signal,
143
+ options: { dshProfile: parsed.dshProfile },
144
+ run: (command, args, runCwd, runOptions) => processes.run(command, args, runCwd, runOptions),
145
+ findExecutable: name => findExecutable(name, process.env),
146
+ }),
147
+ signal: controller.signal,
148
+ });
149
+
150
+ if (json) console.log(JSON.stringify(summary, null, 2));
151
+ else printHumanSummary(summary);
152
+ return summary.ok ? 0 : 1;
153
+ },
154
+ () => console.error("升级已取消。"),
155
+ );
156
+ return outcome.ok ? outcome.value : outcome.exitCode;
157
+ },
158
+ };
@@ -0,0 +1,71 @@
1
+ import { mkdir, stat } from "node:fs/promises";
2
+ import { requireThat } from "../../../common/validation.js";
3
+ import { packageVersion } from "../../../common/version.js";
4
+ import { minimumCliRelease } from "../../../integrations/installation/cli-update.js";
5
+ import { workspacePluginDrift, workspacePluginReleases } from "../../../services/workspace/plugin-releases.js";
6
+ import { readWorkspaceConfig } from "../../../services/workspace/workspace-config.js";
7
+ import { initializeWorkspace } from "../../../services/workspace/workspace-preparation.js";
8
+ import { printJson, requireNoExtraArgs, resolveCliWorkspace } from "../args.js";
9
+ import type { CliCommand } from "../types.js";
10
+
11
+ const initUsage = "用法:pbot init [--workspace <目录>] [--json]\n初始化共享工作区资料并启用 Personal Bot。";
12
+ const statusUsage = "用法:pbot status [--workspace <目录>] [--json]\n查看工作区根目录、CLI 版本、各宿主插件版本、同步状态与配置。";
13
+
14
+ async function reportWorkspaceStatus(root: string, compact: boolean, checkRelease: boolean): Promise<number> {
15
+ const configuration = await readWorkspaceConfig(root);
16
+ const active = checkRelease || configuration.enabled;
17
+ const plugins = active ? workspacePluginReleases(root) : {};
18
+ const required = active ? await minimumCliRelease(root, plugins) : undefined;
19
+ const drift = workspacePluginDrift(plugins);
20
+ printJson({
21
+ workspaceRoot: root,
22
+ version: packageVersion,
23
+ plugins,
24
+ outOfSync: drift.outOfSync,
25
+ minimumCliVersion: required ?? null,
26
+ configuration,
27
+ }, compact);
28
+ return configuration.error ? 1 : 0;
29
+ }
30
+
31
+ export const initCommand: CliCommand = {
32
+ name: "init",
33
+ summary: "初始化共享资料并启用工作区",
34
+ usage: initUsage,
35
+ updatePolicy: "workspace",
36
+ supportsWorkspaceFlag: true,
37
+ supportsJsonFlag: true,
38
+ allowUninitializedUpdate: () => true,
39
+ beforeUpdate(ctx, _root, configuration) {
40
+ requireNoExtraArgs(ctx.args, initUsage);
41
+ if (configuration.error) throw new Error(configuration.error);
42
+ },
43
+ async run(ctx) {
44
+ requireNoExtraArgs(ctx.args, initUsage);
45
+ const root = await resolveCliWorkspace(ctx.workspace, ctx.cwd);
46
+ const existing = await readWorkspaceConfig(root);
47
+ if (existing.error) throw new Error(existing.error);
48
+ await mkdir(root, { recursive: true });
49
+ await initializeWorkspace(root);
50
+ requireThat((await stat(root)).isDirectory(), "工作区必须是目录。");
51
+ return reportWorkspaceStatus(root, ctx.json, true);
52
+ },
53
+ };
54
+
55
+ export const statusCommand: CliCommand = {
56
+ name: "status",
57
+ summary: "查看工作区状态、插件版本与配置",
58
+ usage: statusUsage,
59
+ updatePolicy: "workspace",
60
+ supportsWorkspaceFlag: true,
61
+ supportsJsonFlag: true,
62
+ beforeUpdate(ctx) {
63
+ requireNoExtraArgs(ctx.args, statusUsage);
64
+ },
65
+ async run(ctx) {
66
+ requireNoExtraArgs(ctx.args, statusUsage);
67
+ const root = await resolveCliWorkspace(ctx.workspace, ctx.cwd);
68
+ requireThat((await stat(root)).isDirectory(), "工作区必须是目录。");
69
+ return reportWorkspaceStatus(root, ctx.json, false);
70
+ },
71
+ };
@@ -0,0 +1,193 @@
1
+ import { realpathSync } from "node:fs";
2
+ import { pathToFileURL } from "node:url";
3
+ import { gte, valid } from "semver";
4
+ import { packageVersion } from "../../common/version.js";
5
+ import { minimumCliRelease, runUpdatedCli } from "../../integrations/installation/cli-update.js";
6
+ import { workspacePluginReleases } from "../../services/workspace/plugin-releases.js";
7
+ import { readWorkspaceConfig } from "../../services/workspace/workspace-config.js";
8
+ import { CliError, extractCommonFlags, resolveCliWorkspace } from "./args.js";
9
+ import { historyCommand } from "./commands/history.js";
10
+ import { mcpCommand } from "./commands/mcp.js";
11
+ import { pluginCommand } from "./commands/plugin.js";
12
+ import { installAntigravityCommand, setupCommand } from "./commands/setup.js";
13
+ import { upgradeCommand } from "./commands/upgrade.js";
14
+ import { initCommand, statusCommand } from "./commands/workspace.js";
15
+ import type { CliCommand, CliContext } from "./types.js";
16
+
17
+ const commands: readonly CliCommand[] = [
18
+ initCommand,
19
+ statusCommand,
20
+ historyCommand,
21
+ upgradeCommand,
22
+ mcpCommand,
23
+ pluginCommand,
24
+ setupCommand,
25
+ installAntigravityCommand,
26
+ ];
27
+
28
+ const commandIndex = new Map<string, CliCommand>();
29
+ for (const command of commands) {
30
+ commandIndex.set(command.name, command);
31
+ for (const alias of command.aliases ?? []) commandIndex.set(alias, command);
32
+ }
33
+
34
+ export function listCommands(): readonly CliCommand[] {
35
+ return commands;
36
+ }
37
+
38
+ export function resolveCommand(name: string | undefined): CliCommand | undefined {
39
+ return name ? commandIndex.get(name) : undefined;
40
+ }
41
+
42
+ export function formatRootHelp(): string {
43
+ const lines = [
44
+ `Personal Bot ${packageVersion}`,
45
+ "",
46
+ "用法:pbot <命令> [选项] [参数]",
47
+ "",
48
+ "命令:",
49
+ ...commands.map(cmd => {
50
+ const label = cmd.aliases?.length ? `${cmd.name}|${cmd.aliases.join("|")}` : cmd.name;
51
+ return ` ${label.padEnd(22)} ${cmd.summary}`;
52
+ }),
53
+ "",
54
+ "通用选项:",
55
+ " --workspace <目录> 指定工作区根目录(默认当前目录,适用于工作区命令)",
56
+ " --json 输出 JSON(init/status/history/mcp 输出单行 JSON)",
57
+ " -h, --help 显示帮助(可配合具体命令使用:pbot <命令> --help)",
58
+ " -v, --version 显示当前 CLI 版本",
59
+ " --at-least <版本> 检查当前 CLI 是否满足最低版本要求",
60
+ "",
61
+ "支持 Linux/macOS,需要 Node.js 22.19+ 和 npm。",
62
+ ];
63
+ return lines.join("\n");
64
+ }
65
+
66
+ export async function updateForWorkspace(root: string, args: readonly string[], input?: string): Promise<number | undefined> {
67
+ return runUpdatedCli(await minimumCliRelease(root, workspacePluginReleases(root)), args, input);
68
+ }
69
+
70
+ export async function updateForCommand(args: readonly string[]): Promise<number | undefined> {
71
+ if (!args.length) return undefined;
72
+ if (["--version", "-v", "--at-least", "--help", "-h", "help"].includes(args[0]!)) return undefined;
73
+ const parsed = extractCommonFlags(args);
74
+ if (parsed.help || !parsed.rest.length) return undefined;
75
+ const [verb, ...rest] = parsed.rest;
76
+ const command = resolveCommand(verb);
77
+ if (!command) return undefined;
78
+ const ctx: CliContext = {
79
+ verb: verb!,
80
+ rawArgs: args,
81
+ args: rest,
82
+ ...(parsed.workspace !== undefined ? { workspace: parsed.workspace } : {}),
83
+ json: parsed.json,
84
+ cwd: process.cwd(),
85
+ };
86
+ const policy = typeof command.updatePolicy === "function" ? command.updatePolicy(ctx) : command.updatePolicy;
87
+ if (policy !== "workspace") return undefined;
88
+ const root = command.resolveWorkspaceRoot
89
+ ? await command.resolveWorkspaceRoot(ctx)
90
+ : await resolveCliWorkspace(ctx.workspace, ctx.cwd);
91
+ const configuration = await readWorkspaceConfig(root);
92
+ command.beforeUpdate?.(ctx, root, configuration);
93
+ const initializing = command.allowUninitializedUpdate?.(ctx) ?? false;
94
+ if (!configuration.enabled && !(initializing && !configuration.error)) return undefined;
95
+ return updateForWorkspace(root, args);
96
+ }
97
+
98
+ export async function main(args: readonly string[]): Promise<number> {
99
+ try {
100
+ // Fast local probes: never touch workspace config or npm.
101
+ if (args[0] === "--at-least") {
102
+ const version = args[1];
103
+ if (args.length !== 2 || !version || !valid(version)) {
104
+ throw new CliError("用法:pbot --at-least <MAJOR.MINOR.PATCH>", 1);
105
+ }
106
+ return gte(packageVersion, version) ? 0 : 1;
107
+ }
108
+ if (args.length === 1 && (args[0] === "--version" || args[0] === "-v")) {
109
+ console.log(packageVersion);
110
+ return 0;
111
+ }
112
+
113
+ const parsed = extractCommonFlags(args);
114
+ const [verb, ...rest] = parsed.rest;
115
+
116
+ // Top-level help or `pbot help [command]`
117
+ if (!verb) {
118
+ if (parsed.help || args.length === 0) {
119
+ console.log(formatRootHelp());
120
+ return 0;
121
+ }
122
+ throw new CliError(`缺少命令。\n\n${formatRootHelp()}`, 2);
123
+ }
124
+ if (verb === "help") {
125
+ const target = resolveCommand(rest[0]);
126
+ if (rest.length > 1 || (rest[0] && !target)) {
127
+ throw new CliError(`未知命令:${rest.join(" ")}\n\n${formatRootHelp()}`, 2);
128
+ }
129
+ console.log(target ? target.usage : formatRootHelp());
130
+ return 0;
131
+ }
132
+
133
+ const command = resolveCommand(verb);
134
+ if (!command) {
135
+ if (parsed.help) {
136
+ console.log(formatRootHelp());
137
+ return 0;
138
+ }
139
+ throw new CliError(`未知命令:${verb}\n\n${formatRootHelp()}`, 2);
140
+ }
141
+
142
+ if (parsed.help) {
143
+ console.log(command.usage);
144
+ return 0;
145
+ }
146
+
147
+ if (parsed.workspace !== undefined && !command.supportsWorkspaceFlag) {
148
+ throw new CliError(`命令 ${command.name} 不支持 --workspace 参数。\n${command.usage}`, 2);
149
+ }
150
+ if (parsed.json && !command.supportsJsonFlag) {
151
+ throw new CliError(`命令 ${command.name} 不支持 --json 参数。\n${command.usage}`, 2);
152
+ }
153
+
154
+ const ctx: CliContext = {
155
+ verb,
156
+ rawArgs: args,
157
+ args: rest,
158
+ ...(parsed.workspace !== undefined ? { workspace: parsed.workspace } : {}),
159
+ json: parsed.json,
160
+ cwd: process.cwd(),
161
+ };
162
+
163
+ const policy = typeof command.updatePolicy === "function" ? command.updatePolicy(ctx) : command.updatePolicy;
164
+ if (policy === "workspace") {
165
+ const root = command.resolveWorkspaceRoot
166
+ ? await command.resolveWorkspaceRoot(ctx)
167
+ : await resolveCliWorkspace(ctx.workspace, ctx.cwd);
168
+ const configuration = await readWorkspaceConfig(root);
169
+ command.beforeUpdate?.(ctx, root, configuration);
170
+ const initializing = command.allowUninitializedUpdate?.(ctx) ?? false;
171
+ if (configuration.enabled || (initializing && !configuration.error)) {
172
+ const updated = await updateForWorkspace(root, args);
173
+ if (updated !== undefined) return updated;
174
+ }
175
+ }
176
+
177
+ return await command.run(ctx, { updateForWorkspace });
178
+ } catch (error) {
179
+ if (error instanceof CliError) {
180
+ console.error(error.message);
181
+ return error.exitCode;
182
+ }
183
+ console.error(error instanceof Error ? error.message : String(error));
184
+ return 1;
185
+ }
186
+ }
187
+
188
+ if (process.argv[1] && import.meta.url === pathToFileURL(realpathSync(process.argv[1])).href) {
189
+ main(process.argv.slice(2)).then(code => { process.exitCode = code; }).catch(error => {
190
+ console.error(error instanceof Error ? error.message : String(error));
191
+ process.exitCode = 1;
192
+ });
193
+ }
@@ -0,0 +1,30 @@
1
+ import type { WorkspaceConfiguration } from "../../model/workspace-config.js";
2
+
3
+ export type CliUpdatePolicy = "none" | "workspace" | "hook";
4
+
5
+ export interface CliContext {
6
+ readonly verb: string;
7
+ readonly rawArgs: readonly string[];
8
+ readonly args: string[];
9
+ readonly workspace?: string;
10
+ readonly json: boolean;
11
+ readonly cwd: string;
12
+ }
13
+
14
+ export interface CliCommand {
15
+ readonly name: string;
16
+ readonly aliases?: readonly string[];
17
+ readonly summary: string;
18
+ readonly usage: string;
19
+ readonly updatePolicy: CliUpdatePolicy | ((ctx: CliContext) => CliUpdatePolicy);
20
+ readonly supportsWorkspaceFlag?: boolean;
21
+ readonly supportsJsonFlag?: boolean;
22
+ readonly resolveWorkspaceRoot?: (ctx: CliContext) => Promise<string>;
23
+ readonly allowUninitializedUpdate?: (ctx: CliContext) => boolean;
24
+ readonly beforeUpdate?: (ctx: CliContext, root: string, configuration: WorkspaceConfiguration) => void;
25
+ readonly run: (ctx: CliContext, helpers: CliRuntimeHelpers) => Promise<number>;
26
+ }
27
+
28
+ export interface CliRuntimeHelpers {
29
+ readonly updateForWorkspace: (root: string, args: readonly string[], input?: string) => Promise<number | undefined>;
30
+ }
@@ -6,7 +6,7 @@ import { loadWorkspaceContext } from "../../integrations/agent-resources.js";
6
6
  import type { PluginHostAdapter } from "../../model/plugin-host.js";
7
7
  import { recordHistoryCapture } from "../../services/history/history-capture.js";
8
8
  import { historyStartupNotices } from "../../services/history/summary-runner.js";
9
- import { bindWorkspacePlugin } from "../../services/workspace/plugin-releases.js";
9
+ import { bindWorkspacePlugin, workspacePluginDrift, workspacePluginReleases } from "../../services/workspace/plugin-releases.js";
10
10
  import { readWorkspaceConfig, workspaceFeatures } from "../../services/workspace/workspace-config.js";
11
11
  import { initializeWorkspace } from "../../services/workspace/workspace-preparation.js";
12
12
  import { discoverSkills, discoverWorkspaceSkills } from "../../services/workspace/workspace-skills.js";
@@ -79,7 +79,14 @@ export async function pluginHook(adapter: PluginHostAdapter, payload: unknown, r
79
79
  const directory = join(resourceRoot, "skills");
80
80
  workspaceSkills.push(...await discoverSkills(directory, directory));
81
81
  }
82
- const notices = event.isSessionStart && features.history ? historyStartupNotices(root) : [];
82
+ const notices = event.isSessionStart && features.history ? [...historyStartupNotices(root)] : [];
83
+ if (event.isSessionStart) {
84
+ const drift = workspacePluginDrift(workspacePluginReleases(root));
85
+ if (drift.outOfSync) {
86
+ const summary = Object.entries(drift.versions).map(([host, version]) => `${host}=${version}`).join(", ");
87
+ notices.push(`检测到当前工作区各宿主 Personal Bot 插件版本不一致(${summary}),可在终端运行 pbot upgrade 统一升级。`);
88
+ }
89
+ }
83
90
  if (!includePrompts && !workspaceSkills.length && !notices.length) return adapter.formatPass(payload);
84
91
  const context = await loadWorkspaceContext({
85
92
  host: adapter.host,