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
@@ -4,13 +4,13 @@
4
4
  "command": "sh",
5
5
  "args": [
6
6
  "-c",
7
- "if pbot --at-least 0.3.3 </dev/null >/dev/null 2>&1; then exec pbot \"$@\"; fi\nexec npx --yes --ignore-scripts --prefer-offline personal-bot@0.3.3 \"$@\"",
7
+ "if pbot --at-least 0.3.3 </dev/null >/dev/null 2>&1; then exec pbot \"$@\"; fi\nexec npx --yes --ignore-scripts --prefer-offline personal-bot@0.3.5 \"$@\"",
8
8
  "pbot",
9
9
  "mcp"
10
10
  ],
11
11
  "env": {
12
12
  "PBOT_HOST": "qoder",
13
- "PBOT_PLUGIN_VERSION": "0.3.3"
13
+ "PBOT_PLUGIN_VERSION": "0.3.5"
14
14
  }
15
15
  }
16
16
  }
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "personal-bot",
3
- "version": "0.3.3",
3
+ "version": "0.3.5",
4
4
  "description": "Personal Bot workspace context and cross-harness workers.",
5
5
  "skills": "./skills/",
6
6
  "mcpServers": "./.mcp.json"
@@ -5,7 +5,7 @@
5
5
  "hooks": [
6
6
  {
7
7
  "type": "command",
8
- "command": "PBOT_PLUGIN_VERSION=0.3.3 PBOT_PLUGIN_MANIFEST=\"${QODER_PLUGIN_ROOT:+$QODER_PLUGIN_ROOT/.qoder-plugin/plugin.json}\" sh -c 'if pbot --at-least 0.3.3 </dev/null >/dev/null 2>&1; then exec pbot \"$@\"; fi\nexec npx --yes --ignore-scripts --prefer-offline personal-bot@0.3.3 \"$@\"' pbot plugin qoder hook",
8
+ "command": "PBOT_PLUGIN_VERSION=0.3.5 PBOT_PLUGIN_MANIFEST=\"${QODER_PLUGIN_ROOT:+$QODER_PLUGIN_ROOT/.qoder-plugin/plugin.json}\" sh -c 'if pbot --at-least 0.3.3 </dev/null >/dev/null 2>&1; then exec pbot \"$@\"; fi\nexec npx --yes --ignore-scripts --prefer-offline personal-bot@0.3.5 \"$@\"' pbot plugin qoder hook",
9
9
  "timeout": 120
10
10
  }
11
11
  ]
@@ -16,7 +16,7 @@
16
16
  "hooks": [
17
17
  {
18
18
  "type": "command",
19
- "command": "PBOT_PLUGIN_VERSION=0.3.3 PBOT_PLUGIN_MANIFEST=\"${QODER_PLUGIN_ROOT:+$QODER_PLUGIN_ROOT/.qoder-plugin/plugin.json}\" sh -c 'if pbot --at-least 0.3.3 </dev/null >/dev/null 2>&1; then exec pbot \"$@\"; fi\nexec npx --yes --ignore-scripts --prefer-offline personal-bot@0.3.3 \"$@\"' pbot plugin qoder hook",
19
+ "command": "PBOT_PLUGIN_VERSION=0.3.5 PBOT_PLUGIN_MANIFEST=\"${QODER_PLUGIN_ROOT:+$QODER_PLUGIN_ROOT/.qoder-plugin/plugin.json}\" sh -c 'if pbot --at-least 0.3.3 </dev/null >/dev/null 2>&1; then exec pbot \"$@\"; fi\nexec npx --yes --ignore-scripts --prefer-offline personal-bot@0.3.5 \"$@\"' pbot plugin qoder hook",
20
20
  "timeout": 120
21
21
  }
22
22
  ]
@@ -27,7 +27,7 @@
27
27
  "hooks": [
28
28
  {
29
29
  "type": "command",
30
- "command": "PBOT_PLUGIN_VERSION=0.3.3 PBOT_PLUGIN_MANIFEST=\"${QODER_PLUGIN_ROOT:+$QODER_PLUGIN_ROOT/.qoder-plugin/plugin.json}\" sh -c 'if pbot --at-least 0.3.3 </dev/null >/dev/null 2>&1; then exec pbot \"$@\"; fi\nexec npx --yes --ignore-scripts --prefer-offline personal-bot@0.3.3 \"$@\"' pbot plugin qoder hook",
30
+ "command": "PBOT_PLUGIN_VERSION=0.3.5 PBOT_PLUGIN_MANIFEST=\"${QODER_PLUGIN_ROOT:+$QODER_PLUGIN_ROOT/.qoder-plugin/plugin.json}\" sh -c 'if pbot --at-least 0.3.3 </dev/null >/dev/null 2>&1; then exec pbot \"$@\"; fi\nexec npx --yes --ignore-scripts --prefer-offline personal-bot@0.3.5 \"$@\"' pbot plugin qoder hook",
31
31
  "timeout": 120
32
32
  }
33
33
  ]
@@ -6,4 +6,4 @@ disable-model-invocation: true
6
6
 
7
7
  使用当前会话的 `workspaceRoot` 作为 `--workspace`。省略子命令时使用 `status`。可执行 `init`、`status`、`history status|list|summary|migrate|search|read`。保留用户指定的维度、模型和筛选参数。
8
8
 
9
- 运行 `npx --yes personal-bot@0.3.3 <子命令> --workspace "<workspaceRoot>"`。如果 `pbot --at-least 0.3.3` 返回 0,也可以用 `pbot` 执行同一条命令。返回实际结果。
9
+ 运行 `npx --yes personal-bot@0.3.5 <子命令> --workspace "<workspaceRoot>"`。如果 `pbot --at-least 0.3.5` 返回 0,也可以用 `pbot` 执行同一条命令。返回实际结果。
@@ -1,3 +1,15 @@
1
1
  /** Each host owns its file, including when two hosts activate the same canonical workspace concurrently. */
2
2
  export declare function bindWorkspacePlugin(root: string, host: string, binding?: string): void;
3
+ export interface WorkspacePluginBinding {
4
+ version: string;
5
+ bindingPath?: string;
6
+ }
7
+ export interface WorkspacePluginDrift {
8
+ outOfSync: boolean;
9
+ highest?: string;
10
+ lowest?: string;
11
+ versions: Record<string, string>;
12
+ }
13
+ export declare function workspacePluginBindings(root: string): Record<string, WorkspacePluginBinding>;
3
14
  export declare function workspacePluginReleases(root: string): Record<string, string>;
15
+ export declare function workspacePluginDrift(releases: Record<string, string>): WorkspacePluginDrift;
@@ -7,6 +7,31 @@ import { resourceRoot } from "../../common/paths.js";
7
7
  import { requireThat } from "../../common/validation.js";
8
8
  import { releaseLine } from "../../common/version.js";
9
9
  import { readJsonFile, writeJsonFile } from "../../storage/atomic-json.js";
10
+ function compareSemver(a, b) {
11
+ const parse = (value) => {
12
+ const match = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([0-9A-Za-z.-]+))?/.exec(value);
13
+ return match
14
+ ? { major: Number(match[1]), minor: Number(match[2]), patch: Number(match[3]), pre: match[4] ?? "" }
15
+ : undefined;
16
+ };
17
+ const left = parse(a);
18
+ const right = parse(b);
19
+ if (!left || !right)
20
+ return a.localeCompare(b);
21
+ if (left.major !== right.major)
22
+ return left.major - right.major;
23
+ if (left.minor !== right.minor)
24
+ return left.minor - right.minor;
25
+ if (left.patch !== right.patch)
26
+ return left.patch - right.patch;
27
+ if (left.pre === right.pre)
28
+ return 0;
29
+ if (!left.pre)
30
+ return 1;
31
+ if (!right.pre)
32
+ return -1;
33
+ return left.pre.localeCompare(right.pre);
34
+ }
10
35
  function bindingDirectory(root) {
11
36
  const key = createHash("sha256").update(root).digest("hex");
12
37
  return join(homedir(), ".pbot", "workspaces", key);
@@ -44,7 +69,7 @@ export function bindWorkspacePlugin(root, host, binding = resolve(resourceRoot,
44
69
  throw error;
45
70
  }
46
71
  }
47
- export function workspacePluginReleases(root) {
72
+ export function workspacePluginBindings(root) {
48
73
  const directory = bindingDirectory(root);
49
74
  let files;
50
75
  try {
@@ -55,24 +80,47 @@ export function workspacePluginReleases(root) {
55
80
  return {};
56
81
  throw error;
57
82
  }
58
- const releases = Object.create(null);
83
+ const bindings = Object.create(null);
59
84
  for (const file of files.filter(name => name.endsWith(".json"))) {
60
85
  const host = decodeURIComponent(file.slice(0, -5));
61
86
  try {
62
87
  const binding = readJsonFile(directory, file, pluginBinding);
63
88
  if (!isAbsolute(binding)) {
64
- releases[host] = binding;
89
+ bindings[host] = { version: binding };
65
90
  continue;
66
91
  }
67
92
  const manifest = JSON.parse(readFileSync(binding, "utf8"));
68
93
  requireThat(object(manifest) && typeof manifest.version === "string", "无效的插件安装清单:" + binding);
69
94
  releaseLine(manifest.version);
70
- releases[host] = manifest.version;
95
+ bindings[host] = { version: manifest.version, bindingPath: binding };
71
96
  }
72
97
  catch (error) {
73
98
  if (error.code !== "ENOENT" && !permissionDenied(error))
74
99
  throw error;
75
100
  }
76
101
  }
102
+ return bindings;
103
+ }
104
+ export function workspacePluginReleases(root) {
105
+ const bindings = workspacePluginBindings(root);
106
+ const releases = Object.create(null);
107
+ for (const [host, entry] of Object.entries(bindings))
108
+ releases[host] = entry.version;
77
109
  return releases;
78
110
  }
111
+ export function workspacePluginDrift(releases) {
112
+ let highest;
113
+ let lowest;
114
+ for (const version of Object.values(releases)) {
115
+ if (!highest || compareSemver(version, highest) > 0)
116
+ highest = version;
117
+ if (!lowest || compareSemver(version, lowest) < 0)
118
+ lowest = version;
119
+ }
120
+ return {
121
+ outOfSync: Boolean(highest && lowest && highest !== lowest),
122
+ ...(highest ? { highest } : {}),
123
+ ...(lowest ? { lowest } : {}),
124
+ versions: releases,
125
+ };
126
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "personal-bot",
3
- "version": "0.3.3",
3
+ "version": "0.3.5",
4
4
  "license": "MIT",
5
5
  "repository": {
6
6
  "type": "git",
package/scripts/README.md CHANGED
@@ -5,7 +5,7 @@
5
5
  | 命令 | 作用 |
6
6
  | --- | --- |
7
7
  | `npm run build` | 清理 `dist`,编译测试模块,再依次构建 CLI、dsh 与插件产物 |
8
- | `npm run build:cli` | 清理 `lib`,编译安装器、Pi 检查桥接与启动保护,打包工作区 CLI(`init`、`status`、`history`) |
8
+ | `npm run build:cli` | 清理 `lib`,编译 Pi 检查桥接与启动保护,打包统一 CLI(`lib/extension/cli.js` 与 `workspace-cli.js` 兼容入口) |
9
9
  | `npm run build:dsh` | 编译 Host,将 TypeBox 与许可证纳入 `lib`,再构建原生 Web Loader 模块 |
10
10
  | `npm run build:plugins`(`build:claude` 别名) | 在临时目录编译一次共享插件运行时(`lib/plugin.js`、`lib/claude.js`),通过 `esbuild` 打包零外部依赖的 `lib/extension/mcp.js` 与 `lib/extension/acp-worker.js`,并执行各已注册插件宿主构建目标(同步 Claude 清单、组装自包含 `lib/antigravity-plugin/`、生成 `lib/codex-marketplace/` 与 `lib/qoder-plugin/`) |
11
11
 
@@ -1,3 +1,5 @@
1
+ import { resolve } from "node:path";
1
2
  import { fileURLToPath } from "node:url";
2
3
 
3
4
  export const resourceRoot = fileURLToPath(new URL("../../resources/", import.meta.url));
5
+ export const packageRoot = resolve(resourceRoot, "..");
@@ -0,0 +1,104 @@
1
+ import { homedir } from "node:os";
2
+ import { requireThat } from "../../common/validation.js";
3
+ import { resolveWorkspace } from "../../integrations/installation/workspace.js";
4
+
5
+ export class CliError extends Error {
6
+ constructor(message: string, readonly exitCode: number = 1) {
7
+ super(message);
8
+ this.name = "CliError";
9
+ }
10
+ }
11
+
12
+ export interface ExtractedCommonFlags {
13
+ workspace?: string;
14
+ json: boolean;
15
+ help: boolean;
16
+ rest: string[];
17
+ }
18
+
19
+ /** Extract global CLI flags (--workspace, --json, --help/-h) before `--`. */
20
+ export function extractCommonFlags(args: readonly string[]): ExtractedCommonFlags {
21
+ const rest: string[] = [];
22
+ let workspace: string | undefined;
23
+ let json = false;
24
+ let help = false;
25
+ for (let index = 0; index < args.length; index++) {
26
+ const token = args[index]!;
27
+ if (token === "--") {
28
+ rest.push(...args.slice(index));
29
+ break;
30
+ }
31
+ if (token === "--workspace" || token.startsWith("--workspace=")) {
32
+ if (workspace !== undefined) throw new CliError("--workspace 只能指定一次。", 2);
33
+ const value = token === "--workspace" ? args[++index] : token.slice("--workspace=".length);
34
+ if (!value || value.startsWith("-") || /[\x00-\x1f\x7f]/.test(value)) {
35
+ throw new CliError("--workspace 需要目录。", 2);
36
+ }
37
+ workspace = value;
38
+ continue;
39
+ }
40
+ if (token === "--json") {
41
+ json = true;
42
+ continue;
43
+ }
44
+ if (token === "--help" || token === "-h") {
45
+ help = true;
46
+ continue;
47
+ }
48
+ rest.push(token);
49
+ }
50
+ return {
51
+ ...(workspace !== undefined ? { workspace } : {}),
52
+ json,
53
+ help,
54
+ rest,
55
+ };
56
+ }
57
+
58
+ export function parseKeyValue(raw: string, flag: string): [string, string] {
59
+ const sep = raw.indexOf("=");
60
+ if (sep <= 0) throw new CliError(`${flag} 需要 KEY=VALUE 格式:${raw}`, 2);
61
+ return [raw.slice(0, sep), raw.slice(sep + 1)];
62
+ }
63
+
64
+ export function printJson(value: unknown, compact: boolean): void {
65
+ console.log(JSON.stringify(value, null, compact ? undefined : 2));
66
+ }
67
+
68
+ export function resolveCliWorkspace(workspace: string | undefined, cwd: string): Promise<string> {
69
+ return resolveWorkspace(workspace ?? cwd, cwd, homedir());
70
+ }
71
+
72
+ export function requireNoExtraArgs(args: readonly string[], usage: string): void {
73
+ if (args.length > 0) throw new CliError(`不支持的参数:${args[0]}\n${usage}`, 2);
74
+ }
75
+
76
+ export function requireNonNegativeInt(raw: unknown, flag: string): number {
77
+ requireThat(typeof raw === "string" && /^\d+$/.test(raw) && Number.isSafeInteger(Number(raw)), `${flag} 需要非负整数。`);
78
+ return Number(raw);
79
+ }
80
+
81
+ export async function withSignals<T>(
82
+ run: (controller: AbortController) => Promise<T>,
83
+ onCancel?: (code: number) => void,
84
+ ): Promise<{ ok: true; value: T } | { ok: false; exitCode: number }> {
85
+ const controller = new AbortController();
86
+ let signalCode = 0;
87
+ const onInterrupt = () => { signalCode = 130; controller.abort(new Error("操作已取消。")); };
88
+ const onTerminate = () => { signalCode = 143; controller.abort(new Error("操作已取消。")); };
89
+ process.on("SIGINT", onInterrupt);
90
+ process.on("SIGTERM", onTerminate);
91
+ try {
92
+ return { ok: true, value: await run(controller) };
93
+ } catch (error) {
94
+ if (signalCode || controller.signal.aborted) {
95
+ const code = signalCode || 130;
96
+ onCancel?.(code);
97
+ return { ok: false, exitCode: code };
98
+ }
99
+ throw error;
100
+ } finally {
101
+ process.off("SIGINT", onInterrupt);
102
+ process.off("SIGTERM", onTerminate);
103
+ }
104
+ }
@@ -0,0 +1,81 @@
1
+ import { stat } from "node:fs/promises";
2
+ import { parseArgs } from "node:util";
3
+ import { requireThat } from "../../../common/validation.js";
4
+ import { parseHistoryCommand, type ParsedHistoryCommand } from "../../../services/history/summary-command.js";
5
+ import { readWorkspaceConfig, workspaceDisabledMessage, workspaceFeatures } from "../../../services/workspace/workspace-config.js";
6
+ import { printJson, requireNonNegativeInt, resolveCliWorkspace, withSignals } from "../args.js";
7
+ import type { CliCommand } from "../types.js";
8
+
9
+ const historyUsage = `用法:
10
+ pbot history status | list
11
+ pbot history summary [维度...] [--force] [--backend <acp>] [--model <模型>] [--thinking <级别>]
12
+ pbot history migrate [--dry-run]
13
+ pbot history search [关键词] [--host <来源>] [--dimension <维度>] [--session-id <ID>] [--from <时间>] [--to <时间>] [--offset N] [--limit N]
14
+ pbot history read <节点ID> [--host <来源>] [--offset N] [--limit N] [--children-offset N]
15
+ 所有历史命令支持 --workspace <目录> 和 --json。默认工作区为当前目录。`;
16
+
17
+ function parseHistoryAction(args: string[]): ParsedHistoryCommand {
18
+ const [action, ...rest] = args;
19
+ if (action !== "search" && action !== "read") return parseHistoryCommand(args);
20
+ const string = { type: "string" } as const;
21
+ const { values, positionals } = parseArgs({
22
+ args: rest,
23
+ allowPositionals: true,
24
+ options: {
25
+ host: string,
26
+ offset: string,
27
+ limit: string,
28
+ ...(action === "search"
29
+ ? { dimension: string, "session-id": string, from: string, to: string }
30
+ : { "children-offset": string }),
31
+ },
32
+ });
33
+ requireThat(positionals.length <= 1 && (action === "search" || positionals[0]), historyUsage);
34
+ const input: Record<string, unknown> = { action };
35
+ if (positionals.length) input[action === "search" ? "query" : "id"] = positionals[0];
36
+ for (const [key, value] of Object.entries(values)) {
37
+ if (["offset", "limit", "children-offset"].includes(key)) {
38
+ input[key === "children-offset" ? "childrenOffset" : key] = requireNonNegativeInt(value, "--" + key);
39
+ } else {
40
+ input[key === "session-id" ? "sessionId" : key] = value;
41
+ }
42
+ }
43
+ return { kind: "query", input };
44
+ }
45
+
46
+ export const historyCommand: CliCommand = {
47
+ name: "history",
48
+ summary: "管理与检索跨宿主工作区历史",
49
+ usage: historyUsage,
50
+ updatePolicy: "workspace",
51
+ supportsWorkspaceFlag: true,
52
+ supportsJsonFlag: true,
53
+ beforeUpdate(_ctx, _root, configuration) {
54
+ requireThat(configuration.enabled, workspaceDisabledMessage(configuration));
55
+ requireThat(workspaceFeatures(configuration).history, "当前工作区已停用历史功能(features.history: false)。");
56
+ },
57
+ async run(ctx) {
58
+ const root = await resolveCliWorkspace(ctx.workspace, ctx.cwd);
59
+ const configuration = await readWorkspaceConfig(root);
60
+ requireThat(configuration.enabled, workspaceDisabledMessage(configuration));
61
+ requireThat(workspaceFeatures(configuration).history, "当前工作区已停用历史功能(features.history: false)。");
62
+ requireThat((await stat(root)).isDirectory(), "工作区必须是目录。");
63
+ const command = parseHistoryAction(ctx.args);
64
+ const outcome = await withSignals(
65
+ async controller => {
66
+ const { runHistoryCommand } = await import("../../history/command.js");
67
+ return runHistoryCommand({ root, features: workspaceFeatures(configuration) }, command, controller.signal, {
68
+ start: backend => console.error("历史摘要生成中 (" + backend + ")"),
69
+ update: event => console.error(`${event.dimension} ${event.completed}/${event.total}`),
70
+ });
71
+ },
72
+ () => console.error("历史操作已取消。"),
73
+ );
74
+ if (!outcome.ok) return outcome.exitCode;
75
+ const result = outcome.value;
76
+ printJson(result, ctx.json);
77
+ if ("backend" in result && result.dimensions.some(dimension => dimension.failed.length)) return 1;
78
+ if ("errors" in result && (result.errors.length || result.skipped.length)) return 1;
79
+ return 0;
80
+ },
81
+ };
@@ -0,0 +1,165 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import { existsSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ import { packageRoot } from "../../../common/paths.js";
5
+ import { pluginMcpWorkspaceRoot } from "../../../integrations/hosts/plugin-registry.js";
6
+ import type { WorkspaceMcpServer } from "../../../model/workspace-mcp.js";
7
+ import {
8
+ readWorkspaceMcpConfig,
9
+ removeWorkspaceMcpServer,
10
+ upsertWorkspaceMcpServer,
11
+ } from "../../../services/workspace/workspace-mcp.js";
12
+ import { CliError, parseKeyValue, printJson, resolveCliWorkspace } from "../args.js";
13
+ import type { CliCommand } from "../types.js";
14
+
15
+ const mcpUsage =
16
+ "用法:\n" +
17
+ " pbot mcp\n" +
18
+ " pbot mcp list [--workspace <目录>] [--json]\n" +
19
+ " pbot mcp add <name> --url <url> [--header K=V]... [--description <说明>] [--timeout <秒>] [--disabled] [--workspace <目录>]\n" +
20
+ " pbot mcp add <name> [--env K=V]... [--cwd <目录>] [--description <说明>] [--timeout <秒>] [--disabled] [--workspace <目录>] -- <command> [args...]\n" +
21
+ " pbot mcp remove <name> [--workspace <目录>]\n\n" +
22
+ "无参数时启动统一 stdio MCP 服务(暴露 worker_* 与 workspace_mcp_*);带 list/add/remove 时管理工作区 .pbot/mcp.json。";
23
+
24
+ async function runMcpServer(): Promise<number> {
25
+ const entry = join(packageRoot, "lib/extension/mcp.js");
26
+ if (!existsSync(entry)) {
27
+ console.error("缺少 MCP 构建产物:" + entry + "。请先运行 npm run build。");
28
+ return 1;
29
+ }
30
+ const child = spawnSync(process.execPath, [entry], { stdio: "inherit" });
31
+ if (child.error) {
32
+ console.error(String(child.error));
33
+ return 1;
34
+ }
35
+ return child.status ?? 0;
36
+ }
37
+
38
+ async function runMcpManage(args: string[], workspace: string | undefined, cwd: string, compact: boolean): Promise<number> {
39
+ const [sub, ...rest] = args;
40
+ if (sub === "list") {
41
+ if (rest.length > 0) throw new CliError(`未知参数:${rest[0]}\n${mcpUsage}`, 2);
42
+ const target = await resolveCliWorkspace(workspace, cwd);
43
+ const configuration = await readWorkspaceMcpConfig(target);
44
+ if (configuration.error) throw new CliError(configuration.error, 2);
45
+ printJson({ workspaceRoot: target, path: configuration.path, mcpServers: configuration.servers }, compact);
46
+ return 0;
47
+ }
48
+ if (sub === "remove") {
49
+ const name = rest[0];
50
+ if (!name || name.startsWith("-")) throw new CliError(`remove 需要服务名。\n${mcpUsage}`, 2);
51
+ if (rest.length > 1) throw new CliError(`未知参数:${rest[1]}\n${mcpUsage}`, 2);
52
+ const target = await resolveCliWorkspace(workspace, cwd);
53
+ const result = await removeWorkspaceMcpServer(target, name);
54
+ printJson({ workspaceRoot: target, path: result.configuration.path, removed: result.removed, name }, compact);
55
+ return result.removed ? 0 : 1;
56
+ }
57
+ if (sub === "add") {
58
+ const name = rest[0];
59
+ if (!name || name.startsWith("-")) throw new CliError(`add 需要服务名。\n${mcpUsage}`, 2);
60
+ let url: string | undefined;
61
+ let serverCwd: string | undefined;
62
+ let description: string | undefined;
63
+ let timeout: number | undefined;
64
+ let enabled: boolean | undefined;
65
+ const env: Record<string, string> = {};
66
+ const headers: Record<string, string> = {};
67
+ let commandTokens: string[] = [];
68
+ for (let i = 1; i < rest.length; i++) {
69
+ const arg = rest[i]!;
70
+ if (arg === "--") {
71
+ commandTokens = rest.slice(i + 1);
72
+ break;
73
+ }
74
+ if (arg === "--url") {
75
+ url = rest[++i];
76
+ if (!url) throw new CliError("--url 需要地址。", 2);
77
+ } else if (arg === "--cwd") {
78
+ serverCwd = rest[++i];
79
+ if (!serverCwd) throw new CliError("--cwd 需要目录。", 2);
80
+ } else if (arg === "--description") {
81
+ description = rest[++i];
82
+ if (description === undefined) throw new CliError("--description 需要说明文本。", 2);
83
+ } else if (arg === "--timeout") {
84
+ const raw = rest[++i];
85
+ timeout = Number(raw);
86
+ if (!raw || !Number.isInteger(timeout)) throw new CliError("--timeout 需要整数秒。", 2);
87
+ } else if (arg === "--disabled") {
88
+ enabled = false;
89
+ } else if (arg === "--env") {
90
+ const raw = rest[++i];
91
+ if (!raw) throw new CliError("--env 需要 KEY=VALUE。", 2);
92
+ const [k, v] = parseKeyValue(raw, "--env");
93
+ env[k] = v;
94
+ } else if (arg === "--header") {
95
+ const raw = rest[++i];
96
+ if (!raw) throw new CliError("--header 需要 KEY=VALUE。", 2);
97
+ const [k, v] = parseKeyValue(raw, "--header");
98
+ headers[k] = v;
99
+ } else {
100
+ throw new CliError(`未知参数:${arg}\n${mcpUsage}`, 2);
101
+ }
102
+ }
103
+ const base = {
104
+ ...(description !== undefined ? { description } : {}),
105
+ ...(timeout !== undefined ? { timeout } : {}),
106
+ ...(enabled !== undefined ? { enabled } : {}),
107
+ };
108
+ let server: WorkspaceMcpServer;
109
+ if (url !== undefined) {
110
+ if (commandTokens.length || Object.keys(env).length || serverCwd !== undefined) {
111
+ throw new CliError("--url(HTTP)不能与 stdio 命令/--env/--cwd 同时使用。", 2);
112
+ }
113
+ server = {
114
+ url,
115
+ ...(Object.keys(headers).length ? { headers } : {}),
116
+ ...base,
117
+ };
118
+ } else {
119
+ const [command, ...cmdArgs] = commandTokens;
120
+ if (!command) throw new CliError(`stdio 服务需要通过 -- <command> [args...] 指定启动命令。\n${mcpUsage}`, 2);
121
+ if (Object.keys(headers).length) throw new CliError("--header 仅适用于 --url(HTTP)服务。", 2);
122
+ server = {
123
+ command,
124
+ ...(cmdArgs.length ? { args: cmdArgs } : {}),
125
+ ...(Object.keys(env).length ? { env } : {}),
126
+ ...(serverCwd !== undefined ? { cwd: serverCwd } : {}),
127
+ ...base,
128
+ };
129
+ }
130
+ const target = await resolveCliWorkspace(workspace, cwd);
131
+ const updated = await upsertWorkspaceMcpServer(target, name, server);
132
+ printJson({ workspaceRoot: target, path: updated.path, name, server: updated.servers[name] }, compact);
133
+ return 0;
134
+ }
135
+ throw new CliError(`未知 mcp 子命令:${sub}\n${mcpUsage}`, 2);
136
+ }
137
+
138
+ export const mcpCommand: CliCommand = {
139
+ name: "mcp",
140
+ summary: "启动统一 stdio MCP 服务或管理工作区 .pbot/mcp.json",
141
+ usage: mcpUsage,
142
+ updatePolicy: "workspace",
143
+ supportsWorkspaceFlag: true,
144
+ supportsJsonFlag: true,
145
+ beforeUpdate(ctx) {
146
+ if (ctx.args.length === 0 && (ctx.workspace !== undefined || ctx.json)) {
147
+ throw new CliError(`启动 MCP 服务时不接受 --workspace 或 --json 参数。\n${mcpUsage}`, 2);
148
+ }
149
+ },
150
+ async resolveWorkspaceRoot(ctx) {
151
+ if (ctx.args.length === 0 && !ctx.workspace) {
152
+ return resolveCliWorkspace(pluginMcpWorkspaceRoot() ?? ctx.cwd, ctx.cwd);
153
+ }
154
+ return resolveCliWorkspace(ctx.workspace, ctx.cwd);
155
+ },
156
+ async run(ctx) {
157
+ if (ctx.args.length === 0) {
158
+ if (ctx.workspace !== undefined || ctx.json) {
159
+ throw new CliError(`启动 MCP 服务时不接受 --workspace 或 --json 参数。\n${mcpUsage}`, 2);
160
+ }
161
+ return runMcpServer();
162
+ }
163
+ return runMcpManage(ctx.args, ctx.workspace, ctx.cwd, ctx.json);
164
+ },
165
+ };
@@ -0,0 +1,33 @@
1
+ import { requireThat } from "../../../common/validation.js";
2
+ import { getPluginHost, listPluginHosts, pluginHosts } from "../../../integrations/hosts/plugin-registry.js";
3
+ import { runPluginHost } from "../../hosts/plugin-runtime.js";
4
+ import { resolveCliWorkspace } from "../args.js";
5
+ import type { CliCommand } from "../types.js";
6
+
7
+ function pluginUsage(): string {
8
+ return `用法:pbot plugin <${listPluginHosts().join("|")}> hook|init|status\n运行插件宿主命令或无状态 hook。`;
9
+ }
10
+
11
+ export const pluginCommand: CliCommand = {
12
+ name: "plugin",
13
+ summary: "运行插件宿主命令(hook / init / status)",
14
+ get usage() { return pluginUsage(); },
15
+ updatePolicy: ctx => (ctx.args[1] === "hook" ? "hook" : "workspace"),
16
+ allowUninitializedUpdate: ctx => ctx.args[1] === "init" && ctx.args.length === 2,
17
+ async resolveWorkspaceRoot(ctx) {
18
+ const host = ctx.args[0];
19
+ const resolved = host ? await getPluginHost(host)?.resolveRoot(ctx.cwd) : undefined;
20
+ return resolveCliWorkspace(resolved ?? ctx.cwd, ctx.cwd);
21
+ },
22
+ async run(ctx, helpers) {
23
+ const [host, ...rest] = ctx.args;
24
+ const adapter = host ? pluginHosts.get(host) : undefined;
25
+ requireThat(adapter, pluginUsage());
26
+ const previousCode = process.exitCode;
27
+ process.exitCode = undefined;
28
+ await runPluginHost(adapter, rest, (root, input) => helpers.updateForWorkspace(root, ctx.rawArgs, input));
29
+ const exitCode = typeof process.exitCode === "number" ? process.exitCode : 0;
30
+ process.exitCode = previousCode;
31
+ return exitCode;
32
+ },
33
+ };