personal-bot 0.3.7 → 0.4.0

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 (111) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/README.md +5 -8
  4. package/README.zh-CN.md +5 -8
  5. package/bin/pbot-pi-acp.mjs +1 -1
  6. package/docs/architecture/design.md +2 -2
  7. package/docs/architecture/extensibility.md +1 -1
  8. package/docs/guides/cross-harness-workers.md +4 -4
  9. package/docs/guides/history.md +1 -3
  10. package/docs/guides/workspace-configuration.md +4 -4
  11. package/docs/hosts/claude-code.md +2 -2
  12. package/docs/hosts/codex-qoder.md +1 -1
  13. package/lib/antigravity-plugin/bin/pbot-pi-acp.mjs +1 -1
  14. package/lib/antigravity-plugin/lib/extension/acp/member.d.ts +1 -1
  15. package/lib/antigravity-plugin/lib/extension/acp/member.js +11 -10
  16. package/lib/antigravity-plugin/lib/extension/acp-worker.js +346 -201
  17. package/lib/antigravity-plugin/lib/extension/cli.js +563 -538
  18. package/lib/antigravity-plugin/lib/extension/hosts/dsh/acp-member.js +1 -1
  19. package/lib/antigravity-plugin/lib/extension/hosts/pi/acp-member.js +3 -4
  20. package/lib/antigravity-plugin/lib/extension/hosts/plugin-runtime.js +0 -11
  21. package/lib/antigravity-plugin/lib/extension/mcp.js +397 -278
  22. package/lib/antigravity-plugin/lib/model/acp.d.ts +29 -35
  23. package/lib/antigravity-plugin/lib/model/agent.d.ts +33 -17
  24. package/lib/antigravity-plugin/lib/model/agent.js +0 -1
  25. package/lib/antigravity-plugin/lib/storage/acp-files.d.ts +5 -8
  26. package/lib/antigravity-plugin/lib/storage/acp-files.js +34 -40
  27. package/lib/antigravity-plugin/lib/storage/agent-files.d.ts +19 -10
  28. package/lib/antigravity-plugin/lib/storage/agent-files.js +147 -43
  29. package/lib/antigravity-plugin/package.json +1 -1
  30. package/lib/antigravity-plugin/plugin.json +1 -1
  31. package/lib/codex-marketplace/plugins/personal-bot/.codex-plugin/plugin.json +1 -1
  32. package/lib/codex-marketplace/plugins/personal-bot/.mcp.json +2 -2
  33. package/lib/codex-marketplace/plugins/personal-bot/hooks/hooks.json +3 -3
  34. package/lib/codex-marketplace/plugins/personal-bot/skills/pbot/SKILL.md +1 -1
  35. package/lib/extension/acp/member.d.ts +1 -1
  36. package/lib/extension/acp/member.js +11 -10
  37. package/lib/extension/acp/worker.js +34 -33
  38. package/lib/extension/acp-worker.js +346 -201
  39. package/lib/extension/cli.js +563 -538
  40. package/lib/extension/hosts/dsh/acp-member.js +1 -1
  41. package/lib/extension/hosts/dsh/command.js +1 -1
  42. package/lib/extension/hosts/dsh/workspace.js +1 -3
  43. package/lib/extension/hosts/pi/acp-member.js +3 -4
  44. package/lib/extension/hosts/plugin-runtime.js +0 -11
  45. package/lib/extension/mcp/tool-contract.d.ts +8 -50
  46. package/lib/extension/mcp/tool-contract.js +0 -8
  47. package/lib/extension/mcp/workers.d.ts +7 -27
  48. package/lib/extension/mcp/workers.js +35 -17
  49. package/lib/extension/mcp.js +397 -278
  50. package/lib/integrations/acp/agents.d.ts +2 -3
  51. package/lib/integrations/acp/agents.js +22 -22
  52. package/lib/integrations/acp/harnesses/claude.js +1 -1
  53. package/lib/model/acp.d.ts +29 -35
  54. package/lib/model/agent.d.ts +33 -17
  55. package/lib/model/agent.js +0 -1
  56. package/lib/qoder-plugin/.mcp.json +2 -2
  57. package/lib/qoder-plugin/.qoder-plugin/plugin.json +1 -1
  58. package/lib/qoder-plugin/hooks/hooks.json +3 -3
  59. package/lib/qoder-plugin/skills/pbot/SKILL.md +1 -1
  60. package/lib/services/agents/acp-run.d.ts +6 -4
  61. package/lib/services/agents/acp-run.js +62 -43
  62. package/lib/services/agents/agent-run.d.ts +10 -6
  63. package/lib/services/agents/agent-run.js +142 -65
  64. package/lib/services/agents/agent-service.d.ts +3 -21
  65. package/lib/services/agents/agent-service.js +180 -126
  66. package/lib/storage/acp-files.d.ts +5 -8
  67. package/lib/storage/acp-files.js +34 -40
  68. package/lib/storage/agent-files.d.ts +19 -10
  69. package/lib/storage/agent-files.js +147 -43
  70. package/package.json +1 -1
  71. package/src/extension/acp/member.ts +14 -11
  72. package/src/extension/acp/worker.ts +31 -28
  73. package/src/extension/cli/commands/upgrade.ts +8 -36
  74. package/src/extension/cli/commands/workspace.ts +3 -8
  75. package/src/extension/cli/index.ts +1 -2
  76. package/src/extension/hosts/dsh/acp-member.ts +1 -1
  77. package/src/extension/hosts/dsh/command.ts +1 -1
  78. package/src/extension/hosts/dsh/workspace.ts +1 -3
  79. package/src/extension/hosts/pi/acp-member.ts +3 -4
  80. package/src/extension/hosts/pi/command.ts +1 -1
  81. package/src/extension/hosts/pi/lifecycle.ts +0 -2
  82. package/src/extension/hosts/plugin-runtime.ts +0 -10
  83. package/src/extension/mcp/tool-contract.ts +0 -8
  84. package/src/extension/mcp/workers.ts +34 -17
  85. package/src/integrations/acp/agents.ts +28 -27
  86. package/src/integrations/acp/harnesses/claude.ts +1 -1
  87. package/src/integrations/hosts/dsh/session.ts +2 -2
  88. package/src/integrations/installation/cli-update.ts +2 -2
  89. package/src/integrations/installation/installers/claude.ts +4 -4
  90. package/src/integrations/installation/installers/qoder.ts +5 -5
  91. package/src/integrations/installation/upgraders/antigravity.ts +57 -15
  92. package/src/integrations/installation/upgraders/claude.ts +1 -4
  93. package/src/integrations/installation/upgraders/codex.ts +85 -15
  94. package/src/integrations/installation/upgraders/dsh.ts +46 -24
  95. package/src/integrations/installation/upgraders/pi.ts +18 -11
  96. package/src/integrations/installation/upgraders/qoder.ts +95 -20
  97. package/src/model/acp.ts +27 -29
  98. package/src/model/agent.ts +80 -16
  99. package/src/model/installation.ts +0 -2
  100. package/src/pbot.ts +1 -1
  101. package/src/services/agents/acp-run.ts +81 -49
  102. package/src/services/agents/agent-run.ts +154 -56
  103. package/src/services/agents/agent-service.ts +204 -133
  104. package/src/services/installation/upgrade-service.ts +1 -5
  105. package/src/storage/acp-files.ts +50 -45
  106. package/src/storage/agent-files.ts +159 -46
  107. package/lib/antigravity-plugin/lib/services/workspace/plugin-releases.d.ts +0 -15
  108. package/lib/antigravity-plugin/lib/services/workspace/plugin-releases.js +0 -126
  109. package/lib/services/workspace/plugin-releases.d.ts +0 -15
  110. package/lib/services/workspace/plugin-releases.js +0 -126
  111. package/src/services/workspace/plugin-releases.ts +0 -121
@@ -3,7 +3,6 @@ import { pathToFileURL } from "node:url";
3
3
  import { gte, valid } from "semver";
4
4
  import { packageVersion } from "../../common/version.js";
5
5
  import { minimumCliRelease, runUpdatedCli } from "../../integrations/installation/cli-update.js";
6
- import { workspacePluginReleases } from "../../services/workspace/plugin-releases.js";
7
6
  import { readWorkspaceConfig } from "../../services/workspace/workspace-config.js";
8
7
  import { CliError, extractCommonFlags, resolveCliWorkspace } from "./args.js";
9
8
  import { historyCommand } from "./commands/history.js";
@@ -63,7 +62,7 @@ export function formatRootHelp(): string {
63
62
  }
64
63
 
65
64
  export async function updateForWorkspace(root: string, args: readonly string[], input?: string): Promise<number | undefined> {
66
- return runUpdatedCli(await minimumCliRelease(root, workspacePluginReleases(root)), args, input);
65
+ return runUpdatedCli(await minimumCliRelease(root), args, input);
67
66
  }
68
67
 
69
68
  export async function updateForCommand(args: readonly string[]): Promise<number | undefined> {
@@ -24,7 +24,7 @@ export async function apply(ctx: Context) {
24
24
  if (!rootAgents(ctx.agents).includes(agent)) return;
25
25
  if (source === "resume") agent.inbox.clear();
26
26
  const reference = member.files.reference(member.id);
27
- requireThat(reference.host === "acp" && reference.backend === "dsh" && agent.session.header.cwd === member.d.cwd &&
27
+ requireThat(reference.host === "acp" && reference.backend === "dsh" && agent.session.header.cwd === member.d.workspace &&
28
28
  (reference.sessionId === null || reference.sessionId === agent.id), "dsh ACP 会话身份或工作目录不匹配。");
29
29
  await agent.ctx.plugin({ name: "pbot-acp-expert", inject, apply: async scope => {
30
30
  if (member.features.skills) registerDshSkills(scope, agent, { workspaceRoot: member.d.workspace });
@@ -33,7 +33,7 @@ export function registerDshCommand(ctx: Context, workspaces: DshWorkspaces) {
33
33
  switch (verb) {
34
34
  case "worker": {
35
35
  const { tool, args } = parseWorkerCommand(rest);
36
- result = await workspace.workers.callTool(tool, { workspace: workspace.root, ...args });
36
+ result = await workspace.workers.callTool(tool, args, undefined, workspace.root);
37
37
  break;
38
38
  }
39
39
  case "history": {
@@ -10,7 +10,6 @@ import { registerDshHistoryTool } from "../../../tools/history/dsh-tool.js";
10
10
  import { requireThat } from "../../../common/validation.js";
11
11
  import { toDshMcpConfig } from "../../../integrations/hosts/dsh/mcp.js";
12
12
  import { registerDshSkills } from "../../../integrations/hosts/dsh/skills.js";
13
- import { bindWorkspacePlugin } from "../../../services/workspace/plugin-releases.js";
14
13
  import { readWorkspaceConfig, workspaceDisabledMessage, workspaceFeatures } from "../../../services/workspace/workspace-config.js";
15
14
  import { loadNativeWorkspaceServers } from "../workspace-mcp.js";
16
15
  import type { ResolvedWorkspaceFeatures, WorkspaceConfiguration } from "../../../model/workspace-config.js";
@@ -33,7 +32,7 @@ export class DshWorkspace {
33
32
  readonly component: AbortSignal,
34
33
  readonly features: ResolvedWorkspaceFeatures = workspaceFeatures(),
35
34
  ) {
36
- this.workers = new McpWorkerRuntime(defaultWorkerDirectory(), agent.id, "dsh");
35
+ this.workers = new McpWorkerRuntime(defaultWorkerDirectory(root), agent.id, "dsh");
37
36
  }
38
37
 
39
38
  check = () => { this.component.throwIfAborted(); this.lifetime.signal.throwIfAborted(); };
@@ -122,7 +121,6 @@ export class DshWorkspaces {
122
121
  }
123
122
  let workspace: DshWorkspace | undefined;
124
123
  try {
125
- bindWorkspacePlugin(root, "dsh");
126
124
  workspace = new DshWorkspace(this.ctx, root, agent, this.#lifetime.signal, workspaceFeatures(configuration));
127
125
  const owned = workspace;
128
126
  const dispose = agent.ctx.effect(() => async () => {
@@ -10,7 +10,6 @@ import { toPiMcpConfig } from "../../../integrations/hosts/pi/mcp.js";
10
10
  import { authorizeMutation } from "../../../services/workspace/workspace-files.js";
11
11
  import { loadNativeWorkspaceServers } from "../workspace-mcp.js";
12
12
  import { resourceRoot } from "../../../common/paths.js";
13
- import { launch } from "../../../storage/agent-files.js";
14
13
  import { requireThat } from "../../../common/validation.js";
15
14
 
16
15
  const isBlockedTool = (name: string) => name === "pbot_history" || isMcpWorkerTool(name);
@@ -22,7 +21,7 @@ export default async function piAcpMember(pi: ExtensionAPI) {
22
21
  let input: AcpInput | undefined, startLeaf: string | null = null;
23
22
  const checkSession = (ctx: ExtensionContext) => {
24
23
  const reference = member.files.reference(member.id);
25
- requireThat(reference.host === "acp" && reference.backend === "pi" && realpathSync(ctx.cwd) === member.d.cwd &&
24
+ requireThat(reference.host === "acp" && reference.backend === "pi" && realpathSync(ctx.cwd) === member.d.workspace &&
26
25
  (reference.sessionId === null || reference.sessionId === ctx.sessionManager.getSessionId()), "Pi ACP 会话身份或工作目录不匹配。");
27
26
  };
28
27
  const workspaceMcpServers: ResolvedWorkspaceMcpServer[] = [];
@@ -39,7 +38,7 @@ export default async function piAcpMember(pi: ExtensionAPI) {
39
38
  pi.on("session_start", (_event, ctx) => {
40
39
  checkSession(ctx);
41
40
  const active = pi.getActiveTools();
42
- for (const tool of agentFileTools(member.d.cwd, lifetime.signal, async (path, change, signal) => {
41
+ for (const tool of agentFileTools(member.d.workspace, lifetime.signal, async (path, change, signal) => {
43
42
  member.check(); await authorizeMutation(member.d.workspace, path, change, async () => false, signal); member.check();
44
43
  })) pi.registerTool(tool);
45
44
  for (const server of workspaceMcpServers) {
@@ -47,7 +46,7 @@ export default async function piAcpMember(pi: ExtensionAPI) {
47
46
  registeredMcp.push(server.name);
48
47
  }
49
48
  pi.setActiveTools(active.filter(name => !isBlockedTool(name)));
50
- pi.setSessionName(member.files.read(member.id, "launch.json", launch).name);
49
+ pi.setSessionName(member.id.slice(0, 8));
51
50
  startLeaf = ctx.sessionManager.getLeafId();
52
51
  });
53
52
  pi.on("before_agent_start", async (event, ctx) => {
@@ -96,7 +96,7 @@ export function registerCommand(pi: ExtensionAPI, lifecycle: Lifecycle, confirma
96
96
  if (command === "worker") {
97
97
  try {
98
98
  const { tool, args: payload } = parseWorkerCommand(argument);
99
- const result = await instance.workers.callTool(tool, { workspace: instance.root, ...payload });
99
+ const result = await instance.workers.callTool(tool, payload, undefined, instance.root);
100
100
  ctx.ui.notify(JSON.stringify(result, null, 2), "info");
101
101
  } catch (error) {
102
102
  ctx.ui.notify(error instanceof Error ? error.message : String(error), "error");
@@ -1,6 +1,5 @@
1
1
  import { realpath } from "node:fs/promises";
2
2
  import { requireThat } from "../../../common/validation.js";
3
- import { bindWorkspacePlugin } from "../../../services/workspace/plugin-releases.js";
4
3
  import { authorizeMutation } from "../../../services/workspace/workspace-files.js";
5
4
  import { readWorkspaceConfig, workspaceDisabledMessage, workspaceFeatures } from "../../../services/workspace/workspace-config.js";
6
5
  import type { ResolvedWorkspaceFeatures, WorkspaceConfiguration } from "../../../model/workspace-config.js";
@@ -73,7 +72,6 @@ export class Lifecycle {
73
72
  this.root = await realpath(root);
74
73
  this.configuration = await readWorkspaceConfig(this.root);
75
74
  if (!this.configuration.enabled) return;
76
- bindWorkspacePlugin(this.root, "pi");
77
75
  const instance = this.create(this.root, sessionId, this.configuration);
78
76
  this.#active = instance;
79
77
  try { await this.register(instance); }
@@ -6,7 +6,6 @@ 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, workspacePluginDrift, workspacePluginReleases } from "../../services/workspace/plugin-releases.js";
10
9
  import { readWorkspaceConfig, workspaceFeatures } from "../../services/workspace/workspace-config.js";
11
10
  import { initializeWorkspace } from "../../services/workspace/workspace-preparation.js";
12
11
  import { discoverSkills, discoverWorkspaceSkills } from "../../services/workspace/workspace-skills.js";
@@ -21,7 +20,6 @@ export async function pluginCommand(adapter: PluginHostAdapter, args: readonly s
21
20
  requireThat(["init", "status"].includes(action), adapter.usage);
22
21
  if (action === "init") {
23
22
  await initializeWorkspace(root);
24
- bindWorkspacePlugin(root, adapter.host, process.env.PBOT_PLUGIN_MANIFEST || process.env.PBOT_PLUGIN_VERSION);
25
23
  }
26
24
  const configuration = await readWorkspaceConfig(root);
27
25
  return { version: packageVersion, workspaceRoot: root, resourceRoot, configuration };
@@ -62,7 +60,6 @@ export async function pluginHook(adapter: PluginHostAdapter, payload: unknown, r
62
60
  return adapter.formatPass(payload);
63
61
  }
64
62
  if (!configuration.enabled) return adapter.formatPass(payload);
65
- if (event.kind === "inject-context") bindWorkspacePlugin(root, adapter.host, process.env.PBOT_PLUGIN_MANIFEST || process.env.PBOT_PLUGIN_VERSION);
66
63
  if (features.history && adapter.extractHistory) {
67
64
  try {
68
65
  const capture = await adapter.extractHistory(event);
@@ -80,13 +77,6 @@ export async function pluginHook(adapter: PluginHostAdapter, payload: unknown, r
80
77
  workspaceSkills.push(...await discoverSkills(directory, directory));
81
78
  }
82
79
  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
- }
90
80
  if (!includePrompts && !workspaceSkills.length && !notices.length) return adapter.formatPass(payload);
91
81
  const context = await loadWorkspaceContext({
92
82
  host: adapter.host,
@@ -76,10 +76,6 @@ export function buildPbotWorkerTools(commands: AcpCommands = {}, defaultBackend?
76
76
  type: "string",
77
77
  description: "思考深度(如 low / medium / high / xhigh / max,不区分大小写);未明确指定时省略以用默认设置。",
78
78
  },
79
- cwd: {
80
- type: "string",
81
- description: "执行目录(绝对路径或相对工作区路径),默认工作区根目录。",
82
- },
83
79
  workspace,
84
80
  },
85
81
  },
@@ -104,7 +100,6 @@ export function buildPbotWorkerTools(commands: AcpCommands = {}, defaultBackend?
104
100
  type: "string",
105
101
  description: "助手会话 ID(来自 worker_create 或 worker_discover)。",
106
102
  },
107
- workspace,
108
103
  },
109
104
  },
110
105
  },
@@ -139,7 +134,6 @@ export function buildPbotWorkerTools(commands: AcpCommands = {}, defaultBackend?
139
134
  maximum: maxWaitMs,
140
135
  description: `最多等待毫秒数(默认 ${defaultWaitMs});0 表示立即返回转后台执行。`,
141
136
  },
142
- workspace,
143
137
  },
144
138
  },
145
139
  },
@@ -188,7 +182,6 @@ export function buildPbotWorkerTools(commands: AcpCommands = {}, defaultBackend?
188
182
  maximum: maxWaitMs,
189
183
  description: `提交后最多等待毫秒数(默认 ${defaultWaitMs});0 表示立即返回。`,
190
184
  },
191
- workspace,
192
185
  },
193
186
  },
194
187
  },
@@ -223,7 +216,6 @@ export function buildPbotWorkerTools(commands: AcpCommands = {}, defaultBackend?
223
216
  maximum: maxWaitMs,
224
217
  description: `运行中最多等待毫秒数(默认 ${defaultWaitMs});已结束或翻页时立即返回。`,
225
218
  },
226
- workspace,
227
219
  },
228
220
  },
229
221
  },
@@ -1,7 +1,6 @@
1
1
  import { randomUUID } from "node:crypto";
2
2
  import { existsSync } from "node:fs";
3
3
  import { realpath, stat } from "node:fs/promises";
4
- import { homedir } from "node:os";
5
4
  import { isAbsolute, join } from "node:path";
6
5
  import { setTimeout as delay } from "node:timers/promises";
7
6
  import { object } from "../../common/json.js";
@@ -62,10 +61,9 @@ export const mcpWorkerOnlyInstructions = buildMcpInstructions({ workspaceMcp: fa
62
61
 
63
62
  export const mcpInstructions = buildMcpInstructions({ workspaceMcp: true, history: true });
64
63
 
65
- export function defaultWorkerDirectory(): string {
64
+ export function defaultWorkerDirectory(workspaceRoot: string): string {
66
65
  if (process.env.PBOT_MCP_AGENT_DIR) return process.env.PBOT_MCP_AGENT_DIR;
67
- if (process.env.PLUGIN_DATA) return join(process.env.PLUGIN_DATA, "subagents");
68
- return join(homedir(), ".pbot/subagents");
66
+ return join(workspaceRoot, ".pbot", "subagents");
69
67
  }
70
68
 
71
69
  function workerCommandTool(name: string): McpWorkerToolName | undefined {
@@ -183,16 +181,17 @@ function presentWorker(value: AgentView & {
183
181
 
184
182
  export class McpWorkerRuntime {
185
183
  readonly #services = new Map<string, { service: AgentService; host: AcpWorkerHost; owner: AgentOwner }>();
184
+ readonly #workerWorkspaces = new Map<string, string>();
186
185
  readonly #bridge = new WorkspaceMcpBridge();
187
186
  readonly #sessionId: string;
188
- readonly #directory: string;
187
+ readonly #directory: string | undefined;
189
188
  readonly #defaultBackend: string | undefined;
190
189
  readonly #nativeWorkspaceMcp: boolean;
191
190
  readonly #nativeHistory: boolean;
192
191
  #closing: Promise<void> | undefined;
193
192
 
194
193
  constructor(
195
- directory = defaultWorkerDirectory(),
194
+ directory?: string,
196
195
  sessionId = process.env.PBOT_MCP_SESSION_ID || ("mcp-" + randomUUID()),
197
196
  defaultBackend = process.env.PBOT_HOST || undefined,
198
197
  nativeWorkspaceMcp = /^(1|true)$/i.test(process.env.PBOT_NATIVE_WORKSPACE_MCP ?? ""),
@@ -216,7 +215,7 @@ export class McpWorkerRuntime {
216
215
  env: {
217
216
  PBOT_HOST: this.#defaultBackend,
218
217
  PBOT_WORKSPACE_ROOT: root,
219
- PBOT_MCP_AGENT_DIR: this.#directory,
218
+ PBOT_MCP_AGENT_DIR: this.#directory ?? defaultWorkerDirectory(root),
220
219
  PBOT_MCP_SESSION_ID: this.#sessionId,
221
220
  PBOT_NATIVE_WORKSPACE_MCP: "1",
222
221
  PBOT_NATIVE_HISTORY: "1",
@@ -248,13 +247,26 @@ export class McpWorkerRuntime {
248
247
  return root;
249
248
  }
250
249
 
250
+ private async resolveWorkerWorkspace(workerId: string, defaultWorkspace?: string): Promise<string> {
251
+ const known = this.#workerWorkspaces.get(workerId);
252
+ if (known) return known;
253
+ for (const [root, entry] of this.#services) {
254
+ if (entry.service.has(workerId, entry.owner)) {
255
+ this.#workerWorkspaces.set(workerId, root);
256
+ return root;
257
+ }
258
+ }
259
+ return this.resolveWorkspace(defaultWorkspace);
260
+ }
261
+
251
262
  private workerService(root: string, commands: AcpCommands = {}) {
252
263
  let entry = this.#services.get(root);
253
264
  if (!entry) {
254
- const host = new AcpWorkerHost(this.#directory, commands);
265
+ const directory = this.#directory ?? defaultWorkerDirectory(root);
266
+ const host = new AcpWorkerHost(directory, commands);
255
267
  entry = {
256
268
  host,
257
- service: new AgentService(root, this.#directory, host),
269
+ service: new AgentService(root, directory, host),
258
270
  owner: { sessionId: this.#sessionId, leaf: null, branch: [] },
259
271
  };
260
272
  this.#services.set(root, entry);
@@ -375,10 +387,13 @@ export class McpWorkerRuntime {
375
387
  }
376
388
  }
377
389
 
378
- async callTool(toolName: string, input: unknown, progress?: ProgressReporter): Promise<unknown> {
390
+ async callTool(toolName: string, input: unknown, progress?: ProgressReporter, defaultWorkspace?: string): Promise<unknown> {
379
391
  const { name, args: rawArgs } = parseMcpToolCall(toolName, input);
380
392
  requireThat(!this.#closing, "Personal Bot MCP 服务已关闭。");
381
- const root = await this.resolveWorkspace(asString(rawArgs, "workspace"));
393
+ const isWorkerScoped = name === "worker_close" || name === "worker_request" || name === "worker_response" || name === "worker_output";
394
+ const root = isWorkerScoped
395
+ ? await this.resolveWorkerWorkspace(asString(rawArgs, "workerId", true)!, defaultWorkspace)
396
+ : await this.resolveWorkspace(asString(rawArgs, "workspace") ?? defaultWorkspace);
382
397
  const configuration = await readWorkspaceConfig(root);
383
398
  requireThat(!this.#closing, "Personal Bot MCP 服务已关闭。");
384
399
  requireThat(configuration.enabled, workspaceDisabledMessage(configuration));
@@ -438,13 +453,12 @@ export class McpWorkerRuntime {
438
453
  const backend = this.resolveBackend(rawArgs, configuration.acp, false);
439
454
  const model = asString(rawArgs, "model");
440
455
  const thinking = asString(rawArgs, "thinking");
441
- const cwd = asString(rawArgs, "cwd");
442
456
  const created = await service.start({
443
457
  backend,
444
458
  ...(model ? { model } : {}),
445
459
  ...(thinking ? { thinking } : {}),
446
- ...(cwd ? { cwd } : {}),
447
460
  }, owner);
461
+ this.#workerWorkspaces.set(created.agentId, root);
448
462
  const ready = await this.waitReady(service, owner, created.agentId, readyTimeoutMs, progress);
449
463
  return {
450
464
  ...presentWorker(ready),
@@ -515,21 +529,23 @@ export class McpWorkerRuntime {
515
529
  requireThat(backendRaw === undefined && model === undefined, '参数 backend / model 仅在 target="models" 时可用。');
516
530
  }
517
531
  if (target === "overview") {
532
+ const workers = service.list(owner);
533
+ for (const item of workers) this.#workerWorkspaces.set(item.agentId, root);
518
534
  return {
519
535
  target,
520
536
  backends: inspectAcpBackends(configuration.acp),
521
- workers: service.list(owner).map(presentWorker),
537
+ workers: workers.map(presentWorker),
522
538
  };
523
539
  }
524
540
  if (target === "backends") {
525
541
  return { target, backends: inspectAcpBackends(configuration.acp) };
526
542
  }
527
543
  if (target === "workers") {
544
+ const workers = workerId ? [service.status(workerId, owner)] : service.list(owner);
545
+ for (const item of workers) this.#workerWorkspaces.set(item.agentId, root);
528
546
  return {
529
547
  target,
530
- workers: workerId
531
- ? [presentWorker(service.status(workerId, owner))]
532
- : service.list(owner).map(presentWorker),
548
+ workers: workers.map(presentWorker),
533
549
  };
534
550
  }
535
551
  const backend = this.resolveBackend(rawArgs, configuration.acp, true);
@@ -546,6 +562,7 @@ export class McpWorkerRuntime {
546
562
  if (this.#closing) return this.#closing;
547
563
  const entries = [...this.#services.values()];
548
564
  this.#services.clear();
565
+ this.#workerWorkspaces.clear();
549
566
  this.#closing = Promise.allSettled([
550
567
  this.#bridge.close(),
551
568
  ...entries.map(({ service, owner }) => service.close(owner, preserve)),
@@ -1,12 +1,10 @@
1
1
  import { fork, spawnSync } from "node:child_process";
2
2
  import { existsSync } from "node:fs";
3
- import { join, resolve } from "node:path";
3
+ import { resolve } from "node:path";
4
4
  import { setTimeout as delay } from "node:timers/promises";
5
- import type { AgentHost, AgentDescriptor, AgentOptions, AgentSessionReference } from "../../model/agent.js";
5
+ import type { AgentDescriptor, AgentHost, AgentOptions, AgentSessionReference } from "../../model/agent.js";
6
6
  import type { AcpBackend, AcpCommands, AcpModelsResult } from "../../model/acp.js";
7
- import { AgentFiles, launch } from "../../storage/agent-files.js";
8
- import { acpInput, acpProcess, acpReport } from "../../storage/acp-files.js";
9
- import { fileId } from "../../storage/file-access.js";
7
+ import { AgentFiles, status, workerRecord } from "../../storage/agent-files.js";
10
8
  import { requireThat } from "../../common/validation.js";
11
9
  import { resourceRoot } from "../../common/paths.js";
12
10
  import { acpLaunch, filterAcpStartOptions } from "./launch.js";
@@ -35,13 +33,13 @@ export class AcpWorkerHost implements AgentHost {
35
33
  }
36
34
 
37
35
  /** Probe a backend's advertised model and thinking choices in an isolated ACP process without prompting. */
38
- async inspectModels(backend: AcpBackend, cwd: string, options: Pick<AgentOptions, "provider" | "model"> = {}): Promise<AcpModelsResult> {
36
+ async inspectModels(backend: AcpBackend, workspace: string, options: Pick<AgentOptions, "provider" | "model"> = {}): Promise<AcpModelsResult> {
39
37
  this.available(backend);
40
38
  const filtered = this.filterOptions(backend, options);
41
39
  const reference = this.prepare(backend, filtered);
42
40
  return await new Promise<AcpModelsResult>((resolveResult, reject) => {
43
41
  const child = fork(this.worker, ["--probe"], {
44
- cwd, env: { ...process.env }, detached: true, stdio: ["ignore", "ignore", "ignore", "ipc"], execArgv: [],
42
+ cwd: workspace, env: { ...process.env }, detached: true, stdio: ["ignore", "ignore", "ignore", "ipc"], execArgv: [],
45
43
  });
46
44
  let result: AcpModelsResult | undefined, failure: Error | undefined;
47
45
  const timer = setTimeout(() => {
@@ -59,7 +57,7 @@ export class AcpWorkerHost implements AgentHost {
59
57
  child.once("spawn", () => {
60
58
  child.send({
61
59
  reference,
62
- cwd,
60
+ cwd: workspace,
63
61
  ...(filtered.provider ? { provider: filtered.provider } : {}),
64
62
  ...(filtered.model ? { model: filtered.model } : {}),
65
63
  });
@@ -72,9 +70,9 @@ export class AcpWorkerHost implements AgentHost {
72
70
  });
73
71
  }
74
72
 
75
- private process(id: string) {
76
- const record = this.files.optional(id, "acp-process.json", acpProcess);
77
- if (!record || this.files.read(id, "launch.json", launch).generation !== record.generation) return;
73
+ private process(id: string): { generation: string; pid: number } | undefined {
74
+ const record = this.files.optional(id, "worker.json", workerRecord);
75
+ if (!record?.pid) return;
78
76
  let denied = false;
79
77
  try { process.kill(-record.pid, 0); }
80
78
  catch (error) {
@@ -86,7 +84,7 @@ export class AcpWorkerHost implements AgentHost {
86
84
  const leader = spawnSync("ps", ["-p", String(record.pid), "-o", "args="], { encoding: "utf8" });
87
85
  // A dead leader can leave its group alive. A reused leader must match our exact launch identity.
88
86
  if (leader.status === 0 && !leader.stdout.includes("--pbot-acp-agent " + id + " --generation " + record.generation) || denied && leader.status !== 0) return;
89
- return record;
87
+ return { generation: record.generation, pid: record.pid };
90
88
  }
91
89
 
92
90
  alive(id: string) {
@@ -96,10 +94,11 @@ export class AcpWorkerHost implements AgentHost {
96
94
  async validateSession(d: AgentDescriptor, reference: AgentSessionReference) {
97
95
  requireThat(!this.alive(d.agentId), "ACP 成员仍在运行,不能恢复。");
98
96
  if (reference.sessionId === null) {
99
- requireThat(!this.files.optional(d.agentId, "acp-input.json", acpInput), "ACP 输入交付状态不明;请核对原请求后新建成员。");
97
+ const saved = this.files.optional(d.agentId, "state.json", status);
98
+ requireThat(!saved?.activeRequestId, "ACP 输入交付状态不明;请核对原请求后新建成员。");
100
99
  return;
101
100
  }
102
- const generation = this.files.read(d.agentId, "launch.json", launch).generation;
101
+ const generation = this.files.worker(d.agentId).generation;
103
102
  await new Promise<void>((resolveResult, reject) => {
104
103
  const child = this.spawn(d, generation, true);
105
104
  let validated = false, failure: Error | undefined;
@@ -119,7 +118,7 @@ export class AcpWorkerHost implements AgentHost {
119
118
  private spawn(d: AgentDescriptor, generation: string, validate = false) {
120
119
  return fork(this.worker, ["--pbot-acp-agent", d.agentId, "--generation", generation, "--directory", this.files.directory(d.agentId),
121
120
  ...(validate ? ["--validate"] : [])], {
122
- cwd: d.cwd, env: { ...process.env }, detached: true, stdio: ["ignore", "ignore", "ignore", "ipc"], execArgv: [],
121
+ cwd: d.workspace, env: { ...process.env }, detached: true, stdio: ["ignore", "ignore", "ignore", "ipc"], execArgv: [],
123
122
  });
124
123
  }
125
124
 
@@ -127,13 +126,22 @@ export class AcpWorkerHost implements AgentHost {
127
126
  signal.throwIfAborted();
128
127
  const child = this.spawn(d, generation);
129
128
  await new Promise<void>((resolveResult, reject) => { child.once("spawn", resolveResult); child.once("error", reject); });
130
- requireThat(child.pid, "ACP worker 没有进程身份。");
131
- try { this.files.write(d.agentId, "acp-process.json", { generation, pid: child.pid, startedAt: Date.now() }, acpProcess); }
132
- catch (error) {
133
- try { process.kill(-child.pid, "SIGKILL"); } catch (failure) { if ((failure as NodeJS.ErrnoException).code !== "ESRCH") throw new AggregateError([error, failure], "ACP 启动与清理失败。"); }
129
+ const pid = child.pid;
130
+ requireThat(pid, "ACP worker 没有进程身份。");
131
+ try {
132
+ this.files.control(() => {
133
+ const w = this.files.worker(d.agentId);
134
+ if (w.generation === generation) {
135
+ w.pid = pid;
136
+ this.files.write(d.agentId, "worker.json", w, workerRecord);
137
+ }
138
+ });
139
+ } catch (error) {
140
+ try { process.kill(-pid, "SIGKILL"); } catch (failure) { if ((failure as NodeJS.ErrnoException).code !== "ESRCH") throw new AggregateError([error, failure], "ACP 启动与清理失败。"); }
134
141
  throw error;
135
142
  }
136
- if (child.connected) child.disconnect(); child.unref();
143
+ if (child.connected) child.disconnect();
144
+ child.unref();
137
145
  if (signal.aborted) { await this.release(d.agentId, generation); signal.throwIfAborted(); }
138
146
  }
139
147
 
@@ -153,11 +161,4 @@ export class AcpWorkerHost implements AgentHost {
153
161
  const current = this.process(id);
154
162
  if (current?.generation === generation && current.pid === record.pid) terminate("SIGKILL");
155
163
  }
156
-
157
- report(d: AgentDescriptor, _reference: AgentSessionReference, leaf: string) {
158
- requireThat(leaf.startsWith("acp:"), "ACP 报告引用无效。");
159
- const cycleId = fileId(leaf.slice(4)), report = this.files.read(d.agentId, join("reports", cycleId + ".json"), acpReport);
160
- requireThat(report.cycleId === cycleId, "ACP 报告周期不匹配。");
161
- return report.text;
162
- }
163
164
  }
@@ -26,7 +26,7 @@ export const claudeAcpHarness: AcpHarnessAdapter = {
26
26
  },
27
27
  async prepareLaunch(context) {
28
28
  const base = defaultPrepareLaunch(context);
29
- const claude = await claudeOptions(base.command, context.cwd, context.options.thinking, context.features?.skills !== false);
29
+ const claude = await claudeOptions(base.command, context.workspace, context.options.thinking, context.features?.skills !== false);
30
30
  return {
31
31
  ...base,
32
32
  ...(claude.thinking ? { defaultThinking: claude.thinking } : {}),
@@ -9,7 +9,7 @@ import type { AgentDescriptor } from "../../../model/agent.js";
9
9
  import { requireThat } from "../../../common/validation.js";
10
10
 
11
11
  function validateHeader(d: AgentDescriptor, header: SessionHeader) {
12
- requireThat(header.id === d.agentId && header.cwd === d.cwd && header.parentSession === d.parentSessionId &&
12
+ requireThat(header.id === d.agentId && header.cwd === d.workspace && header.parentSession === d.parentSessionId &&
13
13
  header.origin === "subagent" && !header.isSeeded, "dsh 专家会话身份、父会话或工作目录不匹配。");
14
14
  }
15
15
 
@@ -50,7 +50,7 @@ export async function openDshAgent(ctx: Context, d: AgentDescriptor, parent: Age
50
50
  return resume
51
51
  ? ctx.agents.resume({ resumeSessionId: SessionId(d.agentId), parentAgent: parent, agentOptions, setup: compose, signal })
52
52
  : ctx.agents.create({ sessionId: SessionId(d.agentId), parentAgent: parent,
53
- meta: { cwd: d.cwd, parentSession: parent.id, origin: "subagent", delegationDepth: 1 },
53
+ meta: { cwd: d.workspace, parentSession: parent.id, origin: "subagent", delegationDepth: 1 },
54
54
  agentOptions, setup: compose, signal });
55
55
  }
56
56
 
@@ -10,8 +10,8 @@ import { requireThat } from "../../common/validation.js";
10
10
  import { packageVersion } from "../../common/version.js";
11
11
 
12
12
  /** Check exact installed manifests, never resolve dependencies in an ancestor workspace. */
13
- export async function minimumCliRelease(root: string, plugins: Record<string, string>): Promise<string | undefined> {
14
- const versions = Object.values(plugins);
13
+ export async function minimumCliRelease(root: string): Promise<string | undefined> {
14
+ const versions: string[] = [];
15
15
  if (process.env.PBOT_PLUGIN_VERSION) versions.push(process.env.PBOT_PLUGIN_VERSION);
16
16
  for (const prefix of ["", ".pi/npm"]) {
17
17
  const path = join(root, prefix, "node_modules/personal-bot/package.json");
@@ -10,20 +10,20 @@ export const claudeInstaller: HostInstaller = {
10
10
  return {
11
11
  host: this.host,
12
12
  state: context.explicit ? "failed" : "skipped",
13
- scope: "user",
13
+ scope: "project",
14
14
  detail: "未找到 Claude Code CLI(claude)。请先安装 Claude Code 后重试。",
15
15
  };
16
16
  }
17
17
  await context.run(
18
18
  claude,
19
- ["plugin", "install", "personal-bot", "--marketplace", claudeMarketplace, "--yes"],
19
+ ["plugin", "install", "personal-bot", "--marketplace", claudeMarketplace, "--scope", "project", "--yes"],
20
20
  context.workspace,
21
21
  );
22
22
  return {
23
23
  host: this.host,
24
24
  state: "installed",
25
- scope: "user",
26
- detail: `已通过 claude plugin install 从 ${claudeMarketplace} 安装 personal-bot。`,
25
+ scope: "project",
26
+ detail: `已通过 claude plugin install(project 作用域)从 ${claudeMarketplace} 安装 personal-bot。`,
27
27
  nextStep: "在 Claude Code 目标工作区执行 /personal-bot:pbot init 启用 Personal Bot。",
28
28
  };
29
29
  },
@@ -22,7 +22,7 @@ export const qoderInstaller: HostInstaller = {
22
22
  return {
23
23
  host: this.host,
24
24
  state: context.explicit ? "failed" : "skipped",
25
- scope: "user",
25
+ scope: "project",
26
26
  detail: "未找到 Qoder CLI(qodercli)。请先安装 Qoder CLI 后重试。",
27
27
  };
28
28
  }
@@ -32,17 +32,17 @@ export const qoderInstaller: HostInstaller = {
32
32
  return {
33
33
  host: this.host,
34
34
  state: "failed",
35
- scope: "user",
35
+ scope: "project",
36
36
  detail: `缺少 Qoder CLI 插件构建产物:${pluginDir}。请先运行 npm run build。`,
37
37
  };
38
38
  }
39
- await context.run(qodercli, ["plugin", "install", pluginDir], context.workspace);
39
+ await context.run(qodercli, ["plugin", "install", pluginDir, "--scope", "project"], context.workspace);
40
40
  return {
41
41
  host: this.host,
42
42
  state: "installed",
43
43
  version: bundledVersion,
44
- scope: "user",
45
- detail: `已通过 qodercli plugin install 安装 Qoder CLI 插件(${bundledVersion})。`,
44
+ scope: "project",
45
+ detail: `已通过 qodercli plugin install(project 作用域)安装 Qoder CLI 插件(${bundledVersion})。`,
46
46
  nextStep: "在目标工作区执行 pbot plugin qoder init 启用 Personal Bot。",
47
47
  };
48
48
  },