personal-bot 0.3.2 → 0.3.4

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 (318) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/.claude-plugin/plugin.json +2 -1
  3. package/DISCLAIMER.md +17 -0
  4. package/LICENSE +21 -0
  5. package/README.md +15 -5
  6. package/README.zh-CN.md +15 -5
  7. package/bin/pbot-pi-acp.mjs +1 -1
  8. package/bin/pbot.mjs +22 -2
  9. package/docs/README.md +2 -0
  10. package/docs/architecture/design.md +16 -16
  11. package/docs/architecture/extensibility.md +29 -2
  12. package/docs/architecture/model-context.md +3 -2
  13. package/docs/architecture/principles.md +2 -2
  14. package/docs/guides/capabilities.md +1 -1
  15. package/docs/guides/cross-harness-workers.md +3 -1
  16. package/docs/guides/history.md +30 -7
  17. package/docs/guides/workspace-configuration.md +20 -3
  18. package/docs/hosts/antigravity.md +1 -1
  19. package/docs/hosts/claude-code.md +1 -1
  20. package/docs/hosts/codex-qoder.md +63 -0
  21. package/docs/maintainers/architecture-governance.md +78 -0
  22. package/lib/antigravity-plugin/DISCLAIMER.md +17 -0
  23. package/lib/antigravity-plugin/LICENSE +21 -0
  24. package/lib/antigravity-plugin/bin/pbot-pi-acp.mjs +36 -0
  25. package/lib/antigravity-plugin/lib/common/files.d.ts +2 -0
  26. package/lib/antigravity-plugin/lib/common/files.js +44 -0
  27. package/lib/antigravity-plugin/lib/common/validation.d.ts +4 -0
  28. package/lib/antigravity-plugin/lib/common/validation.js +8 -0
  29. package/lib/antigravity-plugin/lib/extension/acp/member.d.ts +18 -0
  30. package/lib/antigravity-plugin/lib/extension/acp/member.js +44 -0
  31. package/lib/antigravity-plugin/lib/extension/acp-worker.js +71 -45
  32. package/lib/antigravity-plugin/lib/extension/hosts/dsh/acp-entry.d.ts +1 -0
  33. package/lib/antigravity-plugin/lib/extension/hosts/dsh/acp-entry.js +22 -0
  34. package/lib/antigravity-plugin/lib/extension/hosts/dsh/acp-member.d.ts +4 -0
  35. package/lib/antigravity-plugin/lib/extension/hosts/dsh/acp-member.js +58 -0
  36. package/lib/antigravity-plugin/lib/extension/hosts/dsh/files.d.ts +5 -0
  37. package/lib/antigravity-plugin/lib/extension/hosts/dsh/files.js +67 -0
  38. package/lib/antigravity-plugin/lib/extension/hosts/pi/acp-member.d.ts +3 -0
  39. package/lib/antigravity-plugin/lib/extension/hosts/pi/acp-member.js +100 -0
  40. package/lib/antigravity-plugin/lib/extension/hosts/plugin-runtime.d.ts +3 -1
  41. package/lib/antigravity-plugin/lib/extension/hosts/plugin-runtime.js +37 -22
  42. package/lib/antigravity-plugin/lib/extension/hosts/workspace-mcp.d.ts +6 -0
  43. package/lib/antigravity-plugin/lib/extension/hosts/workspace-mcp.js +21 -0
  44. package/lib/antigravity-plugin/lib/extension/mcp.js +2577 -2255
  45. package/lib/antigravity-plugin/lib/extension/workspace-cli.js +20171 -0
  46. package/lib/antigravity-plugin/lib/integrations/agent-resources.js +1 -1
  47. package/lib/antigravity-plugin/lib/integrations/hosts/claude/adapter.js +7 -59
  48. package/lib/antigravity-plugin/lib/integrations/hosts/codex/adapter.d.ts +2 -0
  49. package/lib/antigravity-plugin/lib/integrations/hosts/codex/adapter.js +14 -0
  50. package/lib/antigravity-plugin/lib/integrations/hosts/dsh/mcp.d.ts +4 -0
  51. package/lib/antigravity-plugin/lib/integrations/hosts/dsh/mcp.js +28 -0
  52. package/lib/antigravity-plugin/lib/integrations/hosts/dsh/messages.d.ts +36 -0
  53. package/lib/antigravity-plugin/lib/integrations/hosts/dsh/messages.js +11 -0
  54. package/lib/antigravity-plugin/lib/integrations/hosts/dsh/resources.d.ts +6 -0
  55. package/lib/antigravity-plugin/lib/integrations/hosts/dsh/resources.js +47 -0
  56. package/lib/antigravity-plugin/lib/integrations/hosts/dsh/root-agents.d.ts +4 -0
  57. package/lib/antigravity-plugin/lib/integrations/hosts/dsh/root-agents.js +3 -0
  58. package/lib/antigravity-plugin/lib/integrations/hosts/dsh/skills.d.ts +8 -0
  59. package/lib/antigravity-plugin/lib/integrations/hosts/dsh/skills.js +31 -0
  60. package/lib/antigravity-plugin/lib/integrations/hosts/pi/agent-tools.d.ts +3 -0
  61. package/lib/antigravity-plugin/lib/integrations/hosts/pi/agent-tools.js +32 -0
  62. package/lib/antigravity-plugin/lib/integrations/hosts/pi/mcp.d.ts +4 -0
  63. package/lib/antigravity-plugin/lib/integrations/hosts/pi/mcp.js +23 -0
  64. package/lib/antigravity-plugin/lib/integrations/hosts/plugin-registry.d.ts +1 -0
  65. package/lib/antigravity-plugin/lib/integrations/hosts/plugin-registry.js +8 -1
  66. package/lib/antigravity-plugin/lib/integrations/hosts/prompt-hooks.d.ts +76 -0
  67. package/lib/antigravity-plugin/lib/integrations/hosts/prompt-hooks.js +76 -0
  68. package/lib/antigravity-plugin/lib/integrations/hosts/qoder/adapter.d.ts +2 -0
  69. package/lib/antigravity-plugin/lib/integrations/hosts/qoder/adapter.js +16 -0
  70. package/lib/antigravity-plugin/lib/model/acp.d.ts +7 -3
  71. package/lib/antigravity-plugin/lib/model/acp.js +8 -0
  72. package/lib/antigravity-plugin/lib/model/agent.d.ts +121 -0
  73. package/lib/antigravity-plugin/lib/model/agent.js +4 -0
  74. package/lib/antigravity-plugin/lib/model/history.d.ts +10 -0
  75. package/lib/antigravity-plugin/lib/model/history.js +4 -1
  76. package/lib/antigravity-plugin/lib/model/plugin-host.d.ts +5 -0
  77. package/lib/antigravity-plugin/lib/model/workspace-config.d.ts +8 -12
  78. package/lib/antigravity-plugin/lib/model/workspace-config.js +2 -1
  79. package/lib/antigravity-plugin/lib/plugin.d.ts +2 -1
  80. package/lib/antigravity-plugin/lib/plugin.js +2 -2
  81. package/lib/antigravity-plugin/lib/services/history/history-capture.js +34 -22
  82. package/lib/antigravity-plugin/lib/services/history/summary-registry.js +2 -3
  83. package/lib/antigravity-plugin/lib/services/history/summary-runner.d.ts +2 -5
  84. package/lib/antigravity-plugin/lib/services/history/summary-runner.js +72 -74
  85. package/lib/antigravity-plugin/lib/services/history/workspace-history.d.ts +3 -0
  86. package/lib/antigravity-plugin/lib/services/history/workspace-history.js +6 -0
  87. package/lib/antigravity-plugin/lib/services/workspace/plugin-releases.d.ts +15 -0
  88. package/lib/antigravity-plugin/lib/services/workspace/plugin-releases.js +126 -0
  89. package/lib/antigravity-plugin/lib/services/workspace/workspace-config.js +9 -8
  90. package/lib/antigravity-plugin/lib/services/workspace/workspace-files.d.ts +2 -0
  91. package/lib/antigravity-plugin/lib/services/workspace/workspace-files.js +17 -0
  92. package/lib/antigravity-plugin/lib/services/workspace/workspace-mcp.d.ts +14 -0
  93. package/lib/antigravity-plugin/lib/services/workspace/workspace-mcp.js +193 -0
  94. package/lib/antigravity-plugin/lib/services/workspace/workspace-skills.d.ts +1 -0
  95. package/lib/antigravity-plugin/lib/services/workspace/workspace-skills.js +4 -2
  96. package/lib/antigravity-plugin/lib/storage/acp-files.d.ts +11 -0
  97. package/lib/antigravity-plugin/lib/storage/acp-files.js +75 -0
  98. package/lib/antigravity-plugin/lib/storage/agent-files.d.ts +31 -0
  99. package/lib/antigravity-plugin/lib/storage/agent-files.js +159 -0
  100. package/lib/antigravity-plugin/lib/storage/atomic-json.d.ts +3 -1
  101. package/lib/antigravity-plugin/lib/storage/atomic-json.js +43 -3
  102. package/lib/antigravity-plugin/lib/storage/history-files.d.ts +2 -1
  103. package/lib/antigravity-plugin/lib/storage/history-files.js +21 -15
  104. package/lib/antigravity-plugin/lib/storage/history-format.d.ts +2 -3
  105. package/lib/antigravity-plugin/lib/storage/history-format.js +5 -7
  106. package/lib/antigravity-plugin/package.json +1 -1
  107. package/lib/antigravity-plugin/plugin.json +1 -1
  108. package/lib/antigravity-plugin/resources/prompts/history-monthly-summary.md +13 -0
  109. package/lib/antigravity-plugin/resources/prompts/history-summary.md +13 -0
  110. package/lib/antigravity-plugin/resources/prompts/plugin-coordinator.md +1 -0
  111. package/lib/antigravity-plugin/resources/skills/.claude-plugin/plugin.json +4 -0
  112. package/lib/antigravity-plugin/resources/skills/project-maintenance/SKILL.md +35 -0
  113. package/lib/antigravity-plugin/resources/skills/provider-connections/SKILL.md +52 -0
  114. package/lib/antigravity-plugin/skills/pbot/SKILL.md +11 -1
  115. package/lib/client.js +22 -50
  116. package/lib/codex-marketplace/.agents/plugins/marketplace.json +17 -0
  117. package/lib/codex-marketplace/plugins/personal-bot/.codex-plugin/plugin.json +7 -0
  118. package/lib/codex-marketplace/plugins/personal-bot/.mcp.json +17 -0
  119. package/lib/codex-marketplace/plugins/personal-bot/DISCLAIMER.md +17 -0
  120. package/lib/codex-marketplace/plugins/personal-bot/LICENSE +21 -0
  121. package/lib/codex-marketplace/plugins/personal-bot/hooks/hooks.json +37 -0
  122. package/lib/codex-marketplace/plugins/personal-bot/skills/pbot/SKILL.md +9 -0
  123. package/lib/codex-marketplace/plugins/personal-bot/skills/pbot/agents/openai.yaml +2 -0
  124. package/lib/common/validation.d.ts +4 -0
  125. package/lib/common/validation.js +8 -0
  126. package/lib/dsh.js +2 -2
  127. package/lib/extension/acp/member.d.ts +1 -1
  128. package/lib/extension/acp-worker.js +71 -45
  129. package/lib/extension/history/command.d.ts +37 -0
  130. package/lib/extension/history/command.js +57 -0
  131. package/lib/extension/hosts/dsh/acp-entry.d.ts +1 -0
  132. package/lib/extension/hosts/dsh/acp-entry.js +22 -0
  133. package/lib/extension/hosts/dsh/acp-member.js +4 -18
  134. package/lib/extension/hosts/dsh/command.d.ts +1 -2
  135. package/lib/extension/hosts/dsh/command.js +5 -49
  136. package/lib/extension/hosts/dsh/workspace.js +13 -44
  137. package/lib/extension/hosts/pi/acp-member.d.ts +3 -0
  138. package/lib/extension/hosts/pi/acp-member.js +100 -0
  139. package/lib/extension/hosts/plugin-runtime.d.ts +3 -1
  140. package/lib/extension/hosts/plugin-runtime.js +37 -22
  141. package/lib/extension/hosts/workspace-mcp.d.ts +6 -0
  142. package/lib/extension/hosts/workspace-mcp.js +21 -0
  143. package/lib/extension/mcp/bridge.d.ts +6 -8
  144. package/lib/extension/mcp/bridge.js +66 -84
  145. package/lib/extension/mcp/tool-contract.d.ts +735 -0
  146. package/lib/extension/mcp/tool-contract.js +441 -0
  147. package/lib/extension/mcp/workers.d.ts +29 -742
  148. package/lib/extension/mcp/workers.js +75 -525
  149. package/lib/extension/mcp.js +2577 -2255
  150. package/lib/extension/setup/cli.js +15 -0
  151. package/lib/extension/setup/upgrade.js +153 -0
  152. package/lib/extension/workspace-cli.js +20171 -0
  153. package/lib/integrations/acp/agents.d.ts +2 -3
  154. package/lib/integrations/acp/harnesses/dsh.js +1 -1
  155. package/lib/integrations/acp/harnesses/presets.js +8 -0
  156. package/lib/integrations/acp/history-summary.js +2 -1
  157. package/lib/integrations/acp/launch.d.ts +2 -2
  158. package/lib/integrations/agent-resources.js +1 -1
  159. package/lib/integrations/hosts/claude/adapter.js +7 -59
  160. package/lib/integrations/hosts/codex/adapter.d.ts +2 -0
  161. package/lib/integrations/hosts/codex/adapter.js +14 -0
  162. package/lib/integrations/hosts/pi/agent-tools.d.ts +3 -0
  163. package/lib/integrations/hosts/pi/agent-tools.js +32 -0
  164. package/lib/integrations/hosts/pi/mcp.d.ts +4 -0
  165. package/lib/integrations/hosts/pi/mcp.js +23 -0
  166. package/lib/integrations/hosts/plugin-registry.d.ts +1 -0
  167. package/lib/integrations/hosts/plugin-registry.js +8 -1
  168. package/lib/integrations/hosts/prompt-hooks.d.ts +76 -0
  169. package/lib/integrations/hosts/prompt-hooks.js +76 -0
  170. package/lib/integrations/hosts/qoder/adapter.d.ts +2 -0
  171. package/lib/integrations/hosts/qoder/adapter.js +16 -0
  172. package/lib/integrations/installation/cli-update.js +146 -0
  173. package/lib/integrations/installation/upgraders/antigravity.js +67 -0
  174. package/lib/integrations/installation/upgraders/claude.js +123 -0
  175. package/lib/integrations/installation/upgraders/codex.js +73 -0
  176. package/lib/integrations/installation/upgraders/dsh.js +62 -0
  177. package/lib/integrations/installation/upgraders/pi.js +90 -0
  178. package/lib/integrations/installation/upgraders/qoder.js +67 -0
  179. package/lib/integrations/installation/upgraders/registry.js +40 -0
  180. package/lib/model/acp.d.ts +7 -3
  181. package/lib/model/acp.js +8 -0
  182. package/lib/model/agent.d.ts +18 -4
  183. package/lib/model/agent.js +4 -1
  184. package/lib/model/history.d.ts +10 -0
  185. package/lib/model/history.js +4 -1
  186. package/lib/model/installation.js +1 -0
  187. package/lib/model/plugin-host.d.ts +5 -0
  188. package/lib/model/workspace-config.d.ts +8 -12
  189. package/lib/model/workspace-config.js +2 -1
  190. package/lib/plugin.d.ts +2 -1
  191. package/lib/plugin.js +2 -2
  192. package/lib/qoder-plugin/.mcp.json +17 -0
  193. package/lib/qoder-plugin/.qoder-plugin/plugin.json +7 -0
  194. package/lib/qoder-plugin/DISCLAIMER.md +17 -0
  195. package/lib/qoder-plugin/LICENSE +21 -0
  196. package/lib/qoder-plugin/hooks/hooks.json +37 -0
  197. package/lib/qoder-plugin/skills/pbot/SKILL.md +9 -0
  198. package/lib/services/agents/agent-service.d.ts +15 -45
  199. package/lib/services/agents/agent-service.js +22 -3
  200. package/lib/services/history/history-capture.js +34 -22
  201. package/lib/services/history/history-migrate.js +26 -60
  202. package/lib/services/history/history-query.js +38 -57
  203. package/lib/services/history/summary-command.d.ts +1 -1
  204. package/lib/services/history/summary-command.js +8 -7
  205. package/lib/services/history/summary-registry.js +2 -3
  206. package/lib/services/history/summary-runner.d.ts +2 -5
  207. package/lib/services/history/summary-runner.js +72 -74
  208. package/lib/services/history/workspace-history.d.ts +3 -0
  209. package/lib/services/history/workspace-history.js +6 -0
  210. package/lib/services/installation/setup-service.js +4 -1
  211. package/lib/services/installation/upgrade-service.js +95 -0
  212. package/lib/services/workspace/plugin-releases.d.ts +15 -0
  213. package/lib/services/workspace/plugin-releases.js +126 -0
  214. package/lib/services/workspace/workspace-config.js +9 -8
  215. package/lib/services/workspace/workspace-mcp.js +22 -29
  216. package/lib/services/workspace/workspace-skills.d.ts +1 -0
  217. package/lib/services/workspace/workspace-skills.js +4 -2
  218. package/lib/storage/acp-files.js +7 -12
  219. package/lib/storage/agent-files.js +6 -5
  220. package/lib/storage/atomic-json.d.ts +3 -1
  221. package/lib/storage/atomic-json.js +43 -3
  222. package/lib/storage/history-files.d.ts +2 -1
  223. package/lib/storage/history-files.js +21 -15
  224. package/lib/storage/history-format.d.ts +2 -3
  225. package/lib/storage/history-format.js +5 -7
  226. package/lib/tools/history/contract.d.ts +3 -11
  227. package/lib/tools/history/contract.js +8 -7
  228. package/lib/ui/dsh/elements.d.ts +2 -5
  229. package/lib/ui/dsh/elements.js +3 -16
  230. package/lib/ui/dsh/management.js +9 -9
  231. package/lib/ui/dsh/styles.d.ts +1 -1
  232. package/lib/ui/dsh/styles.js +5 -33
  233. package/package.json +4 -1
  234. package/resources/antigravity/skills/pbot/SKILL.md +11 -1
  235. package/resources/claude/skills/pbot/SKILL.md +11 -1
  236. package/resources/plugin/skills/pbot/SKILL.md +9 -0
  237. package/resources/prompts/history-coordinator.md +1 -0
  238. package/resources/prompts/plugin-coordinator.md +1 -0
  239. package/scripts/README.md +3 -2
  240. package/src/common/validation.ts +10 -0
  241. package/src/dsh.ts +2 -2
  242. package/src/extension/history/command.ts +68 -0
  243. package/src/extension/hosts/dsh/acp-entry.ts +21 -0
  244. package/src/extension/hosts/dsh/acp-member.ts +4 -15
  245. package/src/extension/hosts/dsh/command.ts +6 -46
  246. package/src/extension/hosts/dsh/workspace.ts +12 -38
  247. package/src/extension/hosts/pi/acp-member.ts +4 -10
  248. package/src/extension/hosts/pi/command.ts +14 -63
  249. package/src/extension/hosts/pi/events.ts +2 -8
  250. package/src/extension/hosts/pi/lifecycle.ts +3 -2
  251. package/src/extension/hosts/plugin-runtime.ts +39 -19
  252. package/src/extension/hosts/workspace-mcp.ts +25 -0
  253. package/src/extension/mcp/bridge.ts +80 -80
  254. package/src/extension/mcp/tool-contract.ts +462 -0
  255. package/src/extension/mcp/workers.ts +81 -551
  256. package/src/extension/setup/cli.ts +11 -1
  257. package/src/extension/setup/upgrade.ts +158 -0
  258. package/src/extension/setup/workspace-cli.ts +167 -0
  259. package/src/integrations/acp/agents.ts +2 -3
  260. package/src/integrations/acp/harnesses/dsh.ts +1 -1
  261. package/src/integrations/acp/harnesses/presets.ts +8 -0
  262. package/src/integrations/acp/history-summary.ts +2 -1
  263. package/src/integrations/agent-resources.ts +1 -1
  264. package/src/integrations/hosts/claude/adapter.ts +7 -53
  265. package/src/integrations/hosts/codex/adapter.ts +16 -0
  266. package/src/integrations/hosts/plugin-registry.ts +9 -1
  267. package/src/integrations/hosts/prompt-hooks.ts +72 -0
  268. package/src/integrations/hosts/qoder/adapter.ts +19 -0
  269. package/src/integrations/installation/cli-update.ts +144 -0
  270. package/src/integrations/installation/pi-bridge.ts +1 -1
  271. package/src/integrations/installation/pi-setup.ts +1 -1
  272. package/src/integrations/installation/processes.ts +1 -1
  273. package/src/integrations/installation/upgraders/antigravity.ts +68 -0
  274. package/src/integrations/installation/upgraders/claude.ts +123 -0
  275. package/src/integrations/installation/upgraders/codex.ts +73 -0
  276. package/src/integrations/installation/upgraders/dsh.ts +63 -0
  277. package/src/integrations/installation/upgraders/pi.ts +87 -0
  278. package/src/integrations/installation/upgraders/qoder.ts +68 -0
  279. package/src/integrations/installation/upgraders/registry.ts +48 -0
  280. package/src/model/acp.ts +11 -3
  281. package/src/model/agent.ts +20 -4
  282. package/src/model/history.ts +5 -0
  283. package/src/model/installation.ts +86 -0
  284. package/src/model/plugin-host.ts +5 -1
  285. package/src/model/workspace-config.ts +6 -12
  286. package/src/pbot.ts +13 -32
  287. package/src/plugin.ts +3 -3
  288. package/src/services/agents/agent-service.ts +29 -17
  289. package/src/services/history/history-capture.ts +30 -22
  290. package/src/services/history/history-migrate.ts +23 -50
  291. package/src/services/history/history-query.ts +34 -48
  292. package/src/services/history/summary-command.ts +9 -8
  293. package/src/services/history/summary-registry.ts +2 -3
  294. package/src/services/history/summary-runner.ts +72 -81
  295. package/src/services/history/workspace-history.ts +8 -0
  296. package/src/services/installation/setup-service.ts +9 -43
  297. package/src/services/installation/upgrade-service.ts +127 -0
  298. package/src/services/workspace/plugin-releases.ts +121 -0
  299. package/src/services/workspace/workspace-config.ts +9 -8
  300. package/src/services/workspace/workspace-mcp.ts +23 -28
  301. package/src/services/workspace/workspace-skills.ts +5 -2
  302. package/src/storage/acp-files.ts +7 -12
  303. package/src/storage/agent-files.ts +6 -5
  304. package/src/storage/atomic-json.ts +31 -4
  305. package/src/storage/history-files.ts +22 -15
  306. package/src/storage/history-format.ts +6 -8
  307. package/src/tools/history/contract.ts +9 -9
  308. package/src/tools/history/pi-tool.ts +6 -4
  309. package/src/ui/dsh/elements.ts +5 -12
  310. package/src/ui/dsh/management.ts +10 -10
  311. package/src/ui/dsh/styles.ts +5 -33
  312. package/lib/antigravity-plugin/lib/services/history/history-migrate.d.ts +0 -12
  313. package/lib/antigravity-plugin/lib/services/history/history-migrate.js +0 -88
  314. package/lib/ui/presentation.d.ts +0 -3
  315. package/lib/ui/presentation.js +0 -12
  316. package/src/tools/access.ts +0 -7
  317. package/src/tools/register.ts +0 -21
  318. package/src/ui/presentation.ts +0 -12
@@ -1,67 +1,43 @@
1
1
  import { randomUUID } from "node:crypto";
2
+ import { existsSync } from "node:fs";
2
3
  import { realpath, stat } from "node:fs/promises";
3
4
  import { homedir } from "node:os";
4
5
  import { isAbsolute, join } from "node:path";
5
6
  import { setTimeout as delay } from "node:timers/promises";
6
7
  import { object } from "../../common/json.js";
7
- import { isAcpBackend, requireThat } from "../../common/validation.js";
8
+ import { isAcpBackend, isHistoryIdentifier, isOneOf, requireThat } from "../../common/validation.js";
9
+ import { resourceRoot } from "../../common/paths.js";
8
10
  import { packageVersion } from "../../common/version.js";
9
11
  import { AcpWorkerHost } from "../../integrations/acp/agents.js";
10
12
  import { canonicalAcpBackend, inspectAcpBackends, knownAcpBackends } from "../../integrations/acp/launch.js";
13
+ import { pluginMcpWorkspaceRoot } from "../../integrations/hosts/plugin-registry.js";
11
14
  import {
12
15
  mcpWorkerToolNames,
13
16
  type AcpCommands,
14
- type AcpElicitationAction,
17
+ acpElicitationActions, isAcpElicitationValue,
15
18
  type AcpElicitationContent,
16
19
  type AcpModelSelection,
17
20
  type McpWorkerToolName,
18
21
  } from "../../model/acp.js";
19
- import { workspaceMcpToolNames, type WorkspaceMcpToolName } from "../../model/workspace-mcp.js";
22
+ import {
23
+ buildHistoryMcpTools, buildPbotWorkerTools, buildWorkspaceMcpTools, defaultWaitMs, discoverTargets,
24
+ maxWaitMs, parseMcpToolCall,
25
+ } from "./tool-contract.js";
26
+
27
+ import { historyPageLimits } from "../../model/history.js";
20
28
  import type { AgentCycle, AgentOwner, AgentView } from "../../model/agent.js";
21
29
  import { AgentService } from "../../services/agents/agent-service.js";
22
30
  import { readWorkspaceHistory, searchWorkspaceHistory } from "../../services/history/history-query.js";
23
31
  import { readWorkspaceConfig, workspaceDisabledMessage, workspaceFeatures } from "../../services/workspace/workspace-config.js";
24
- import { isHistoryHost, isSummaryDimension } from "../../storage/history-format.js";
25
32
  import { WorkspaceMcpBridge } from "./bridge.js";
26
33
 
34
+ export { buildHistoryMcpTools, buildPbotWorkerTools, buildWorkspaceMcpTools, pbotWorkerTools } from "./tool-contract.js";
35
+
27
36
  const protocolVersion = "2025-03-26";
28
37
  const readyTimeoutMs = 45_000;
29
- const defaultWaitMs = 50_000;
30
- const maxWaitMs = 600_000;
31
38
  const reportPageSize = 16_000;
32
39
  const progressIntervalMs = 5_000;
33
40
 
34
- const responseActions = ["accept", "decline", "cancel"] as const;
35
- const discoverTargets = ["overview", "workers", "backends", "models"] as const;
36
- type DiscoverTarget = typeof discoverTargets[number];
37
-
38
- const mcpHistoryToolNames = ["history_search", "history_read"] as const;
39
- type McpHistoryToolName = typeof mcpHistoryToolNames[number];
40
- type AllMcpToolName = McpWorkerToolName | WorkspaceMcpToolName | McpHistoryToolName;
41
- const allMcpToolNames: readonly AllMcpToolName[] = [...mcpWorkerToolNames, ...workspaceMcpToolNames, ...mcpHistoryToolNames];
42
-
43
- const toolParams: Record<AllMcpToolName, ReadonlySet<string>> = {
44
- worker_create: new Set(["backend", "model", "thinking", "cwd", "workspace"]),
45
- worker_close: new Set(["workerId", "workspace"]),
46
- worker_request: new Set(["workerId", "message", "waitMs", "workspace"]),
47
- worker_response: new Set(["workerId", "action", "requestId", "optionId", "content", "waitMs", "workspace"]),
48
- worker_output: new Set(["workerId", "offset", "waitMs", "workspace"]),
49
- worker_discover: new Set(["target", "workerId", "backend", "model", "workspace"]),
50
- workspace_mcp_discover: new Set(["server", "workspace"]),
51
- workspace_mcp_call: new Set(["server", "tool", "arguments", "workspace"]),
52
- history_search: new Set(["host", "dimension", "query", "sessionId", "from", "to", "offset", "limit", "workspace"]),
53
- history_read: new Set(["id", "host", "offset", "limit", "childrenOffset", "workspace"]),
54
- };
55
-
56
- const shortToolMap: Record<string, McpWorkerToolName> = {
57
- create: "worker_create",
58
- close: "worker_close",
59
- request: "worker_request",
60
- response: "worker_response",
61
- output: "worker_output",
62
- discover: "worker_discover",
63
- };
64
-
65
41
  export type ProgressReporter = (message: string) => void;
66
42
 
67
43
  export const mcpWorkerOnlyInstructions =
@@ -74,455 +50,15 @@ export const mcpInstructions =
74
50
  "2. 工作区共享外部工具(workspace_mcp_*):发现并调用当前工作区接入的外部工具服务与数据源(可与当前环境原生工具同时使用)。先用 workspace_mcp_discover 查看可用服务与工具说明,再用 workspace_mcp_call 调用。\n" +
75
51
  "3. 跨宿主历史查询(history_search / history_read):只读检索当前工作区在 Pi、dsh、Claude Code、Antigravity 等宿主中记录的历史问答与摘要归档。";
76
52
 
77
- function formatBackendItem(entry: ReturnType<typeof inspectAcpBackends>[number], defaultBackend?: string): string {
78
- const tags: string[] = [];
79
- if (entry.label) tags.push(entry.label);
80
- if (entry.backend === defaultBackend) tags.push("当前");
81
- return tags.length ? `${entry.backend}(${tags.join(",")})` : entry.backend;
82
- }
83
-
84
- function summarizeBackends(commands: AcpCommands = {}, defaultBackend?: string) {
85
- const entries = inspectAcpBackends(commands);
86
- const available = entries.filter(item => item.available);
87
- const unavailable = entries.filter(item => !item.available);
88
- const availableText = available.map(item => formatBackendItem(item, defaultBackend)).join("、");
89
- const unavailableText = unavailable.map(item => formatBackendItem(item, defaultBackend)).join("、");
90
- const overview = available.length
91
- ? unavailable.length
92
- ? `当前可用助手:${availableText};暂不可用:${unavailableText}。`
93
- : `当前可用助手:${availableText}。`
94
- : `当前无可用外部助手(暂不可用:${unavailableText})。`;
95
- const availableIds = available.map(item => item.backend).join("、");
96
- return { overview, availableIds };
97
- }
98
-
99
- function workspaceProperty(workspaceBound: boolean) {
100
- return {
101
- type: "string",
102
- description: workspaceBound
103
- ? "目标工作区根目录的绝对路径;默认使用当前工作区,通常省略。"
104
- : "目标工作区根目录的绝对路径(如上下文中提供了 workspaceRoot 则传该路径);请显式传入。",
105
- };
106
- }
107
-
108
- export function buildPbotWorkerTools(commands: AcpCommands = {}, defaultBackend?: string, workspaceBound = false) {
109
- const { overview, availableIds } = summarizeBackends(commands, defaultBackend);
110
- const modelsBackendHint = defaultBackend
111
- ? `省略时默认查 ${defaultBackend}`
112
- : "必填";
113
- const workspace = workspaceProperty(workspaceBound);
114
-
115
- return [
116
- {
117
- name: "worker_create",
118
- description:
119
- "启动一个独立的外部 AI 助手会话(worker),用于将任务委派给其他助手或指定模型/思考深度来独立处理(如按用户要求切换助手、获取独立审查或第二意见、并行分担子任务)。" +
120
- "本工具仅建立会话并返回 workerId,随后通过 worker_request 发送具体任务。不需要借助其他助手时,优先自行完成或使用当前内置子代理。\n" +
121
- overview,
122
- annotations: {
123
- title: "Create Worker",
124
- readOnlyHint: false,
125
- destructiveHint: false,
126
- idempotentHint: false,
127
- openWorldHint: true,
128
- },
129
- inputSchema: {
130
- type: "object",
131
- additionalProperties: false,
132
- required: ["backend"],
133
- properties: {
134
- backend: {
135
- type: "string",
136
- description: "要启动的外部助手标识(不区分大小写,支持常见别名,如 claude-code、agy)。",
137
- },
138
- model: {
139
- type: "string",
140
- description: "仅用户明确要求特定模型时指定(支持模型 ID、显示名或 provider/model,不区分大小写);不确定可用值时先用 worker_discover(target=\"models\") 查询;不填则使用该助手默认模型。",
141
- },
142
- thinking: {
143
- type: "string",
144
- description: "仅用户明确要求思考深度时指定(如 low / medium / high / xhigh / max,不区分大小写);不填则使用默认设置。",
145
- },
146
- cwd: {
147
- type: "string",
148
- description: "助手执行任务时的工作目录(绝对路径或相对工作区的路径),默认为当前工作区根目录。",
149
- },
150
- workspace,
151
- },
152
- },
153
- },
154
- {
155
- name: "worker_close",
156
- description:
157
- "结束不再需要的外部助手会话并释放资源。若该助手支持会话恢复,后续仍可直接用 worker_request 在原上下文中继续对话。",
158
- annotations: {
159
- title: "Close Worker",
160
- readOnlyHint: false,
161
- destructiveHint: true,
162
- idempotentHint: true,
163
- openWorldHint: false,
164
- },
165
- inputSchema: {
166
- type: "object",
167
- additionalProperties: false,
168
- required: ["workerId"],
169
- properties: {
170
- workerId: {
171
- type: "string",
172
- description: "要结束的助手会话 ID(来自 worker_create 或 worker_discover)。",
173
- },
174
- workspace,
175
- },
176
- },
177
- },
178
- {
179
- name: "worker_request",
180
- description:
181
- "向指定的外部助手派发任务,或在同一上下文中追问与补充要求,并获取执行结果(已关闭但支持恢复的会话会自动续接)。" +
182
- `默认最多等待 ${defaultWaitMs / 1000} 秒返回结果;将 waitMs 设为 0 可立即返回并转入后台执行,适合耗时任务或多助手并行。` +
183
- "若返回 timedOut 或结果含 nextOffset,用 worker_output 继续等待或翻页;若返回 needsResponse,先向用户确认再用 worker_response 回复。",
184
- annotations: {
185
- title: "Send Request to Worker",
186
- readOnlyHint: false,
187
- destructiveHint: false,
188
- idempotentHint: false,
189
- openWorldHint: true,
190
- },
191
- inputSchema: {
192
- type: "object",
193
- additionalProperties: false,
194
- required: ["workerId", "message"],
195
- properties: {
196
- workerId: {
197
- type: "string",
198
- description: "目标助手会话 ID(来自 worker_create 或 worker_discover)。",
199
- },
200
- message: {
201
- type: "string",
202
- description: "要发送的任务说明或追问内容。外部助手看不到你与用户的对话历史,首次派发时请写清背景、目标、相关文件路径、约束条件和期望产出。",
203
- },
204
- waitMs: {
205
- type: "integer",
206
- minimum: 0,
207
- maximum: maxWaitMs,
208
- description: `最多等待结果的毫秒数(默认 ${defaultWaitMs});设为 0 可立即返回并在后台执行。`,
209
- },
210
- workspace,
211
- },
212
- },
213
- },
214
- {
215
- name: "worker_response",
216
- description:
217
- "当外部助手在执行过程中暂停并请求确认或补充信息(返回 needsResponse: true)时,向其提交决定以继续执行。" +
218
- "支持三类请求:操作授权(kind=\"permission\")、问答表单(kind=\"form\")和链接确认(kind=\"url\")。" +
219
- `提交前先向用户确认;提交后默认最多等待 ${defaultWaitMs / 1000} 秒返回后续结果(waitMs 设为 0 立即返回)。`,
220
- annotations: {
221
- title: "Respond to Worker Request",
222
- readOnlyHint: false,
223
- destructiveHint: false,
224
- idempotentHint: false,
225
- openWorldHint: true,
226
- },
227
- inputSchema: {
228
- type: "object",
229
- additionalProperties: false,
230
- required: ["workerId", "action"],
231
- properties: {
232
- workerId: {
233
- type: "string",
234
- description: "等待回复的助手会话 ID。",
235
- },
236
- action: {
237
- type: "string",
238
- enum: [...responseActions],
239
- description: "处理方式:accept 表示同意授权、提交表单回答或确认链接;decline 表示拒绝;cancel 表示取消本次请求。",
240
- },
241
- requestId: {
242
- type: "string",
243
- description: "要回复的请求 ID(来自 pendingRequests[].requestId);仅一条待处理请求时可省略,多条时必填。",
244
- },
245
- optionId: {
246
- type: "string",
247
- description: "仅授权请求(kind=\"permission\")且 action 不为 cancel 时可用:指定选项 ID(来自 pendingRequests[].options[].optionId),省略时默认单次允许或拒绝。",
248
- },
249
- content: {
250
- type: "object",
251
- additionalProperties: true,
252
- description: "仅表单提问(kind=\"form\")且 action=\"accept\" 时可用:按 pendingRequests[].schema.properties 填写的回答对象(值为字符串、数字、布尔值或字符串数组)。",
253
- },
254
- waitMs: {
255
- type: "integer",
256
- minimum: 0,
257
- maximum: maxWaitMs,
258
- description: `提交回复后最多等待后续结果的毫秒数(默认 ${defaultWaitMs});设为 0 立即返回。`,
259
- },
260
- workspace,
261
- },
262
- },
263
- },
264
- {
265
- name: "worker_output",
266
- description:
267
- "获取或等待外部助手的最新执行结果。用于收取后台任务的产出、在等待超时(timedOut)后继续等待,或在长结果分页(含 nextOffset)时读取后续内容。" +
268
- "任务仍在运行时会等待其完成(也可能返回 timedOut 或 needsResponse),已结束则立即返回。",
269
- annotations: {
270
- title: "Get Worker Output",
271
- readOnlyHint: true,
272
- destructiveHint: false,
273
- idempotentHint: true,
274
- openWorldHint: false,
275
- },
276
- inputSchema: {
277
- type: "object",
278
- additionalProperties: false,
279
- required: ["workerId"],
280
- properties: {
281
- workerId: {
282
- type: "string",
283
- description: "要等待或获取结果的助手会话 ID。",
284
- },
285
- offset: {
286
- type: "integer",
287
- minimum: 0,
288
- description: "结果读取起始位置(默认 0);翻页读取剩余内容时传入上次返回的 nextOffset。",
289
- },
290
- waitMs: {
291
- type: "integer",
292
- minimum: 0,
293
- maximum: maxWaitMs,
294
- description: `任务仍在运行时最多等待的毫秒数(默认 ${defaultWaitMs});任务已结束或翻页读取时会立即返回。`,
295
- },
296
- workspace,
297
- },
298
- },
299
- },
300
- {
301
- name: "worker_discover",
302
- description:
303
- "了解当前可以委派哪些外部助手、查看已有助手会话的运行状态以便复用,或查询某个助手支持的模型与思考深度选项。" +
304
- "默认(target=\"overview\")同时返回可用助手与已有会话;仅在需要核对模型或思考深度可选值时再查 target=\"models\"(耗时较长)。",
305
- annotations: {
306
- title: "Discover Workers, Backends & Models",
307
- readOnlyHint: true,
308
- destructiveHint: false,
309
- idempotentHint: true,
310
- openWorldHint: false,
311
- },
312
- inputSchema: {
313
- type: "object",
314
- additionalProperties: false,
315
- required: [],
316
- properties: {
317
- target: {
318
- type: "string",
319
- enum: [...discoverTargets],
320
- description: "查询范围,默认 \"overview\"(同时返回可用助手与已有会话);\"workers\" 查全部或单个会话状态;\"backends\" 查可用助手列表;\"models\" 查指定助手支持的模型与思考深度。",
321
- },
322
- workerId: {
323
- type: "string",
324
- description: "仅 target=\"workers\" 可用:指定单个助手会话 ID;不填则列出全部。",
325
- },
326
- backend: {
327
- type: "string",
328
- description: availableIds
329
- ? `仅 target="models" 可用(${modelsBackendHint}):目标外部助手标识,支持常见别名;当前可用:${availableIds}。`
330
- : `仅 target="models" 可用(${modelsBackendHint}):目标外部助手标识,支持常见别名。`,
331
- },
332
- model: {
333
- type: "string",
334
- description: "仅 target=\"models\" 可用:指定模型以查看该模型支持的思考深度选项。",
335
- },
336
- workspace,
337
- },
338
- },
339
- },
340
- ];
341
- }
342
-
343
- export function buildWorkspaceMcpTools(workspaceBound = false) {
344
- const workspace = workspaceProperty(workspaceBound);
345
- return [
346
- {
347
- name: "workspace_mcp_discover",
348
- description:
349
- "发现当前工作区共享的外部工具服务(MCP)及其可用工具。不传 server 时列出可用服务;传入 server 时返回该服务提供的工具清单与参数说明。",
350
- annotations: {
351
- title: "Discover Workspace MCP Servers & Tools",
352
- readOnlyHint: true,
353
- destructiveHint: false,
354
- idempotentHint: true,
355
- openWorldHint: true,
356
- },
357
- inputSchema: {
358
- type: "object",
359
- additionalProperties: false,
360
- required: [],
361
- properties: {
362
- server: {
363
- type: "string",
364
- description: "目标工具服务名称;不填时列出工作区全部可用服务。",
365
- },
366
- workspace,
367
- },
368
- },
369
- },
370
- {
371
- name: "workspace_mcp_call",
372
- description:
373
- "调用当前工作区共享的外部工具服务(MCP)中的指定工具,用于访问工作区接入的外部能力与数据源。" +
374
- "不确定工具名或参数格式时,先用 workspace_mcp_discover(server) 查询。",
375
- annotations: {
376
- title: "Call Workspace MCP Tool",
377
- readOnlyHint: false,
378
- destructiveHint: false,
379
- idempotentHint: false,
380
- openWorldHint: true,
381
- },
382
- inputSchema: {
383
- type: "object",
384
- additionalProperties: false,
385
- required: ["server", "tool"],
386
- properties: {
387
- server: {
388
- type: "string",
389
- description: "目标工具服务名称(可通过 workspace_mcp_discover 获取)。",
390
- },
391
- tool: {
392
- type: "string",
393
- description: "要调用的工具名称。",
394
- },
395
- arguments: {
396
- type: "object",
397
- additionalProperties: true,
398
- description: "传给目标工具的参数对象,不填则为空对象。",
399
- },
400
- workspace,
401
- },
402
- },
403
- },
404
- ];
405
- }
406
-
407
- export function buildHistoryMcpTools(workspaceBound = false) {
408
- const workspace = workspaceProperty(workspaceBound);
409
- return [
410
- {
411
- name: "history_search",
412
- description:
413
- "搜索当前工作区跨宿主(pi、dsh、claude、antigravity 等)的历史问答与摘要归档。省略 query 时列出各会话;传入 query 按不区分大小写的连续关键词匹配原文与摘要。",
414
- annotations: {
415
- title: "Search Workspace History",
416
- readOnlyHint: true,
417
- destructiveHint: false,
418
- idempotentHint: true,
419
- openWorldHint: false,
420
- },
421
- inputSchema: {
422
- type: "object",
423
- additionalProperties: false,
424
- required: [],
425
- properties: {
426
- host: {
427
- type: "string",
428
- description: "可选来源筛选(如 pi、dsh、claude、antigravity);省略查全部宿主。",
429
- },
430
- dimension: {
431
- type: "string",
432
- description: "可选范围筛选:raw 表示仅搜原文,或指定摘要维度(如 monthly、session);省略查全部原文与维度摘要。",
433
- },
434
- query: {
435
- type: "string",
436
- description: "不区分大小写的连续关键词;省略时列出各会话(或指定维度摘要)。",
437
- },
438
- sessionId: {
439
- type: "string",
440
- description: "限定在指定原始会话 ID 内搜索。",
441
- },
442
- from: {
443
- type: "string",
444
- description: "ISO 日期或时间下界。",
445
- },
446
- to: {
447
- type: "string",
448
- description: "ISO 日期或时间上界。",
449
- },
450
- offset: {
451
- type: "integer",
452
- minimum: 0,
453
- description: "匹配结果偏移,默认 0。",
454
- },
455
- limit: {
456
- type: "integer",
457
- minimum: 1,
458
- maximum: 50,
459
- description: "最多返回条数(1–50),默认 20。",
460
- },
461
- workspace,
462
- },
463
- },
464
- },
465
- {
466
- name: "history_read",
467
- description:
468
- "按节点 id 读取当前工作区历史归档的正文与上下级节点(monthly、session、summary、exchange),支持从月度汇总下钻至单会话摘要与原始问答。正文过长时用 nextOffset 续读,子节点过多时用 nextChildrenOffset 续读。",
469
- annotations: {
470
- title: "Read Workspace History Node",
471
- readOnlyHint: true,
472
- destructiveHint: false,
473
- idempotentHint: true,
474
- openWorldHint: false,
475
- },
476
- inputSchema: {
477
- type: "object",
478
- additionalProperties: false,
479
- required: ["id"],
480
- properties: {
481
- id: {
482
- type: "string",
483
- description: "history_search 或上下级返回的节点 id。",
484
- },
485
- host: {
486
- type: "string",
487
- description: "跨来源 ID 冲突时显式指定来源宿主。",
488
- },
489
- offset: {
490
- type: "integer",
491
- minimum: 0,
492
- description: "正文字符偏移,默认 0。",
493
- },
494
- limit: {
495
- type: "integer",
496
- minimum: 1,
497
- maximum: 24000,
498
- description: "正文字符数(1–24000),默认 12000。",
499
- },
500
- childrenOffset: {
501
- type: "integer",
502
- minimum: 0,
503
- description: "子节点列表偏移,默认 0;续读传上页 nextChildrenOffset。",
504
- },
505
- workspace,
506
- },
507
- },
508
- },
509
- ];
510
- }
511
-
512
- export const pbotWorkerTools = buildPbotWorkerTools();
513
-
514
53
  export function defaultWorkerDirectory(): string {
515
54
  if (process.env.PBOT_MCP_AGENT_DIR) return process.env.PBOT_MCP_AGENT_DIR;
516
55
  if (process.env.PLUGIN_DATA) return join(process.env.PLUGIN_DATA, "subagents");
517
56
  return join(homedir(), ".pbot/subagents");
518
57
  }
519
58
 
520
- function isKnownWorkerTool(name: string): name is McpWorkerToolName {
521
- return (mcpWorkerToolNames as readonly string[]).includes(name);
522
- }
523
-
524
- function isKnownTool(name: string): name is AllMcpToolName {
525
- return (allMcpToolNames as readonly string[]).includes(name);
59
+ function workerCommandTool(name: string): McpWorkerToolName | undefined {
60
+ const full = name.startsWith("worker_") ? name : `worker_${name}`;
61
+ return isOneOf(full, mcpWorkerToolNames) ? full : undefined;
526
62
  }
527
63
 
528
64
  /** Parse Pi/dsh `/pbot worker ...` CLI arguments into a canonical MCP tool call. */
@@ -554,8 +90,7 @@ export function parseWorkerCommand(raw: string): { tool: McpWorkerToolName; args
554
90
  if (trimmed.startsWith("{")) {
555
91
  const parsed: unknown = JSON.parse(trimmed);
556
92
  requireThat(object(parsed), 'worker 参数必须是 JSON 对象,例如:/pbot worker create {"backend":"codex"}');
557
- const rawTool = typeof parsed.tool === "string" ? parsed.tool : undefined;
558
- const resolved = rawTool ? (isKnownWorkerTool(rawTool) ? rawTool : shortToolMap[rawTool]) : undefined;
93
+ const resolved = typeof parsed.tool === "string" ? workerCommandTool(parsed.tool) : undefined;
559
94
  requireThat(resolved, `JSON 形式需包含有效 tool 字段(${mcpWorkerToolNames.join(", ")}),或使用 /pbot worker <工具名> <JSON>。`);
560
95
  const rest = Object.fromEntries(Object.entries(parsed).filter(([key]) => key !== "tool"));
561
96
  return { tool: resolved, args: rest };
@@ -563,22 +98,14 @@ export function parseWorkerCommand(raw: string): { tool: McpWorkerToolName; args
563
98
  const match = trimmed.match(/^(\S+)(?:\s+([\s\S]*))?$/);
564
99
  const verb = match?.[1] ?? "";
565
100
  const rest = (match?.[2] ?? "").trim();
566
- const tool = isKnownWorkerTool(verb) ? verb : shortToolMap[verb];
567
- requireThat(tool, `未知 worker 命令:${verb}(支持:overview | status | backends | models | create | request | response | output | close | discover)。`);
101
+ const tool = workerCommandTool(verb);
102
+ requireThat(tool, `未知 worker 命令:${verb}(支持:overview | status | backends | models | ${mcpWorkerToolNames.map(name => name.slice("worker_".length)).join(" | ")})。`);
568
103
  if (!rest) return { tool, args: {} };
569
104
  const parsed: unknown = JSON.parse(rest);
570
105
  requireThat(object(parsed), `${tool} 的参数必须是 JSON 对象。`);
571
106
  return { tool, args: parsed };
572
107
  }
573
108
 
574
- function rejectUnknownParams(tool: AllMcpToolName, rawArgs: Record<string, unknown>) {
575
- const allowed = toolParams[tool];
576
- const unknown = Object.entries(rawArgs)
577
- .filter(([key, value]) => value !== undefined && !allowed.has(key))
578
- .map(([key]) => key);
579
- requireThat(unknown.length === 0, `未知参数:${unknown.join(", ")}(${tool} 可用参数:${[...allowed].join(", ")})。`);
580
- }
581
-
582
109
  function asString(args: Record<string, unknown>, key: string, required = false): string | undefined {
583
110
  const value = args[key];
584
111
  if (value === undefined || value === null) {
@@ -602,11 +129,7 @@ function asContent(args: Record<string, unknown>, key: string): AcpElicitationCo
602
129
  if (value === undefined || value === null) return undefined;
603
130
  requireThat(object(value), `参数 ${key} 必须是 JSON 对象。`);
604
131
  for (const [field, entry] of Object.entries(value)) {
605
- const valid = typeof entry === "string"
606
- || (typeof entry === "number" && Number.isFinite(entry))
607
- || typeof entry === "boolean"
608
- || (Array.isArray(entry) && entry.every(item => typeof item === "string"));
609
- requireThat(valid, `参数 ${key}.${field} 必须是字符串、数字、布尔值或字符串数组。`);
132
+ requireThat(isAcpElicitationValue(entry), `参数 ${key}.${field} 必须是字符串、数字、布尔值或字符串数组。`);
610
133
  }
611
134
  return value as AcpElicitationContent;
612
135
  }
@@ -654,7 +177,7 @@ export class McpWorkerRuntime {
654
177
  readonly #defaultBackend: string | undefined;
655
178
  readonly #nativeWorkspaceMcp: boolean;
656
179
  readonly #nativeHistory: boolean;
657
- #closed = false;
180
+ #closing: Promise<void> | undefined;
658
181
 
659
182
  constructor(
660
183
  directory = defaultWorkerDirectory(),
@@ -670,6 +193,25 @@ export class McpWorkerRuntime {
670
193
  this.#nativeHistory = nativeHistory;
671
194
  }
672
195
 
196
+ /** Mount the stdio sibling with the same worker ownership as the native host command. */
197
+ nativeServer(root: string) {
198
+ const entry = join(resourceRoot, "../lib/extension/mcp.js");
199
+ if (!existsSync(entry)) return undefined;
200
+ requireThat(this.#defaultBackend, "原生 MCP 挂载需要宿主名称。");
201
+ return {
202
+ command: process.execPath,
203
+ args: [entry],
204
+ env: {
205
+ PBOT_HOST: this.#defaultBackend,
206
+ PBOT_WORKSPACE_ROOT: root,
207
+ PBOT_MCP_AGENT_DIR: this.#directory,
208
+ PBOT_MCP_SESSION_ID: this.#sessionId,
209
+ PBOT_NATIVE_WORKSPACE_MCP: "1",
210
+ PBOT_NATIVE_HISTORY: "1",
211
+ },
212
+ };
213
+ }
214
+
673
215
  get nativeWorkspaceMcp(): boolean {
674
216
  return this.#nativeWorkspaceMcp;
675
217
  }
@@ -687,21 +229,17 @@ export class McpWorkerRuntime {
687
229
  }
688
230
 
689
231
  private async resolveWorkspace(supplied?: string): Promise<string> {
690
- const target = supplied || process.env.CLAUDE_PROJECT_DIR || process.env.PBOT_WORKSPACE_ROOT || process.cwd();
232
+ const target = supplied || pluginMcpWorkspaceRoot() || process.cwd();
691
233
  requireThat(isAbsolute(target), "工作区需要绝对路径。");
692
234
  const root = await realpath(target);
693
235
  requireThat((await stat(root)).isDirectory(), "工作区路径不是目录。");
694
236
  return root;
695
237
  }
696
238
 
697
- private async workspace(supplied?: string) {
698
- requireThat(!this.#closed, "Personal Bot MCP 服务已关闭。");
699
- const root = await this.resolveWorkspace(supplied);
700
- const configuration = await readWorkspaceConfig(root);
701
- requireThat(configuration.enabled, workspaceDisabledMessage(configuration));
239
+ private workerService(root: string, commands: AcpCommands = {}) {
702
240
  let entry = this.#services.get(root);
703
241
  if (!entry) {
704
- const host = new AcpWorkerHost(this.#directory, configuration.acp);
242
+ const host = new AcpWorkerHost(this.#directory, commands);
705
243
  entry = {
706
244
  host,
707
245
  service: new AgentService(root, this.#directory, host),
@@ -709,9 +247,9 @@ export class McpWorkerRuntime {
709
247
  };
710
248
  this.#services.set(root, entry);
711
249
  } else {
712
- Object.assign(entry.host, { commands: configuration.acp ?? {} });
250
+ entry.host.commands = commands;
713
251
  }
714
- return { root, configuration, ...entry };
252
+ return entry;
715
253
  }
716
254
 
717
255
  async toolDefinitions() {
@@ -729,7 +267,7 @@ export class McpWorkerRuntime {
729
267
  }
730
268
  } catch { /* Fall back to registered built-in harnesses when cwd is outside an enabled workspace. */ }
731
269
  const defaultBackend = this.#defaultBackend ? canonicalAcpBackend(this.#defaultBackend, commands) : undefined;
732
- const workspaceBound = Boolean(process.env.CLAUDE_PROJECT_DIR || process.env.PBOT_WORKSPACE_ROOT);
270
+ const workspaceBound = Boolean(pluginMcpWorkspaceRoot());
733
271
  return [
734
272
  ...buildPbotWorkerTools(commands, defaultBackend, workspaceBound),
735
273
  ...(includeWorkspaceMcp ? buildWorkspaceMcpTools(workspaceBound) : []),
@@ -749,7 +287,7 @@ export class McpWorkerRuntime {
749
287
  let lastProgressAt = 0;
750
288
  let lastMarker = "";
751
289
  for (;;) {
752
- requireThat(!this.#closed, "Personal Bot MCP 服务已关闭。");
290
+ requireThat(!this.#closing, "Personal Bot MCP 服务已关闭。");
753
291
  const current = service.status(workerId, owner);
754
292
  if (current.state === "error" || current.state === "stopped") {
755
293
  throw new Error(current.error || "worker 启动失败。");
@@ -782,23 +320,13 @@ export class McpWorkerRuntime {
782
320
  let lastProgressAt = 0;
783
321
  let lastMarker = "";
784
322
  for (;;) {
785
- requireThat(!this.#closed, "Personal Bot MCP 服务已关闭。");
786
- const current = service.status(workerId, owner);
787
- const cycles = service.cycles(workerId, owner);
788
- const latestRequest = requestId ?? service.files.messages(workerId)
789
- .filter(item => item.generation === current.generation)
790
- .at(-1)?.requestId;
791
- const targetCycle = latestRequest
792
- ? cycles.find(item => item.generation === current.generation && item.requestIds.includes(latestRequest))
793
- : current.cycle ?? cycles.at(-1);
794
- const settled = targetCycle && targetCycle.state !== "running";
795
- const terminalWithoutCycle = !latestRequest && (current.state === "stopped" || current.state === "error" || (current.state === "idle" && !targetCycle));
796
- const failedBeforeCycle = Boolean(latestRequest && !targetCycle && (current.state === "stopped" || current.state === "error"));
797
- if (settled) {
798
- const page = await service.read(workerId, owner, targetCycle.cycleId, offset, reportPageSize);
323
+ requireThat(!this.#closing, "Personal Bot MCP 服务已关闭。");
324
+ const { current, cycle, terminal } = service.outputStatus(workerId, owner, requestId);
325
+ if (cycle && cycle.state !== "running") {
326
+ const page = await service.read(workerId, owner, cycle.cycleId, offset, reportPageSize);
799
327
  return { settled: true, ...presentWorker(page) };
800
328
  }
801
- if (terminalWithoutCycle || failedBeforeCycle) {
329
+ if (terminal) {
802
330
  if (offset > 0) await service.read(workerId, owner, undefined, offset, reportPageSize);
803
331
  return { settled: true, ...presentWorker(current) };
804
332
  }
@@ -825,22 +353,20 @@ export class McpWorkerRuntime {
825
353
  }
826
354
  }
827
355
 
828
- async callTool(name: string, rawArgs: unknown, progress?: ProgressReporter): Promise<unknown> {
829
- requireThat(isKnownTool(name), `未知工具:${name}(可用:${allMcpToolNames.join(", ")})。`);
830
- requireThat(object(rawArgs), "工具参数必须是对象。");
831
- rejectUnknownParams(name, rawArgs);
832
- const { root, configuration, host, service, owner } = await this.workspace(asString(rawArgs, "workspace"));
356
+ async callTool(toolName: string, input: unknown, progress?: ProgressReporter): Promise<unknown> {
357
+ const { name, args: rawArgs } = parseMcpToolCall(toolName, input);
358
+ requireThat(!this.#closing, "Personal Bot MCP 服务已关闭。");
359
+ const root = await this.resolveWorkspace(asString(rawArgs, "workspace"));
360
+ const configuration = await readWorkspaceConfig(root);
361
+ requireThat(!this.#closing, "Personal Bot MCP 服务已关闭。");
362
+ requireThat(configuration.enabled, workspaceDisabledMessage(configuration));
833
363
 
834
364
  switch (name) {
835
- case "workspace_mcp_discover": {
836
- requireThat(!this.#nativeWorkspaceMcp, "当前宿主已原生挂载工作区 .pbot/mcp.json 服务,请直接调用对应原生 MCP 工具,勿重复经由 workspace_mcp_* 桥接。");
837
- requireThat(workspaceFeatures(configuration).mcp, `工作区统一 MCP 功能已在 ${configuration.path} 中停用(features.mcp: false)。`);
838
- const server = asString(rawArgs, "server");
839
- return this.#bridge.discover(root, server);
840
- }
365
+ case "workspace_mcp_discover":
841
366
  case "workspace_mcp_call": {
842
367
  requireThat(!this.#nativeWorkspaceMcp, "当前宿主已原生挂载工作区 .pbot/mcp.json 服务,请直接调用对应原生 MCP 工具,勿重复经由 workspace_mcp_* 桥接。");
843
368
  requireThat(workspaceFeatures(configuration).mcp, `工作区统一 MCP 功能已在 ${configuration.path} 中停用(features.mcp: false)。`);
369
+ if (name === "workspace_mcp_discover") return this.#bridge.discover(root, asString(rawArgs, "server"));
844
370
  const server = asString(rawArgs, "server", true)!;
845
371
  const tool = asString(rawArgs, "tool", true)!;
846
372
  const toolArgs = rawArgs.arguments === undefined ? {} : rawArgs.arguments;
@@ -851,15 +377,15 @@ export class McpWorkerRuntime {
851
377
  requireThat(!this.#nativeHistory, "当前宿主已提供原生 pbot_history 工具,请直接调用 pbot_history。");
852
378
  requireThat(workspaceFeatures(configuration).history, `工作区历史功能已在 ${configuration.path} 中停用(features.history: false)。`);
853
379
  const hostFilter = asString(rawArgs, "host");
854
- if (hostFilter !== undefined) requireThat(isHistoryHost(hostFilter), "无效的 host 来源:" + hostFilter);
380
+ if (hostFilter !== undefined) requireThat(isHistoryIdentifier(hostFilter), "无效的 host 来源:" + hostFilter);
855
381
  const dimension = asString(rawArgs, "dimension");
856
- if (dimension !== undefined) requireThat(isSummaryDimension(dimension), "无效的 dimension:" + dimension);
382
+ if (dimension !== undefined) requireThat(isHistoryIdentifier(dimension), "无效的 dimension:" + dimension);
857
383
  const query = asString(rawArgs, "query");
858
384
  const sessionId = asString(rawArgs, "sessionId");
859
385
  const from = asString(rawArgs, "from");
860
386
  const to = asString(rawArgs, "to");
861
387
  const offset = asInt(rawArgs, "offset", 0, 10_000_000) ?? 0;
862
- const limit = asInt(rawArgs, "limit", 1, 50) ?? 20;
388
+ const limit = asInt(rawArgs, "limit", 1, historyPageLimits.search.max) ?? historyPageLimits.search.default;
863
389
  return searchWorkspaceHistory(root, {
864
390
  ...(hostFilter ? { host: hostFilter } : {}),
865
391
  ...(dimension ? { dimension } : {}),
@@ -876,12 +402,16 @@ export class McpWorkerRuntime {
876
402
  requireThat(workspaceFeatures(configuration).history, `工作区历史功能已在 ${configuration.path} 中停用(features.history: false)。`);
877
403
  const id = asString(rawArgs, "id", true)!;
878
404
  const hostFilter = asString(rawArgs, "host");
879
- if (hostFilter !== undefined) requireThat(isHistoryHost(hostFilter), "无效的 host 来源:" + hostFilter);
405
+ if (hostFilter !== undefined) requireThat(isHistoryIdentifier(hostFilter), "无效的 host 来源:" + hostFilter);
880
406
  const offset = asInt(rawArgs, "offset", 0, 10_000_000) ?? 0;
881
- const limit = asInt(rawArgs, "limit", 1, 24000) ?? 12000;
407
+ const limit = asInt(rawArgs, "limit", 1, historyPageLimits.read.max) ?? historyPageLimits.read.default;
882
408
  const childrenOffset = asInt(rawArgs, "childrenOffset", 0, 10_000_000) ?? 0;
883
409
  return { node: readWorkspaceHistory(root, id, offset, limit, childrenOffset, hostFilter) };
884
410
  }
411
+ }
412
+
413
+ const { host, service, owner } = this.workerService(root, configuration.acp);
414
+ switch (name) {
885
415
  case "worker_create": {
886
416
  const backend = this.resolveBackend(rawArgs, configuration.acp, false);
887
417
  const model = asString(rawArgs, "model");
@@ -926,10 +456,9 @@ export class McpWorkerRuntime {
926
456
  }
927
457
  case "worker_response": {
928
458
  const workerId = asString(rawArgs, "workerId", true)!;
929
- const rawAction = asString(rawArgs, "action", true)!;
930
- requireThat((responseActions as readonly string[]).includes(rawAction),
931
- `参数 action 无效:${rawAction}(可用:${responseActions.join(", ")})。`);
932
- const action = rawAction as AcpElicitationAction;
459
+ const action = asString(rawArgs, "action", true)!;
460
+ requireThat(isOneOf(action, acpElicitationActions),
461
+ `参数 action 无效:${action}(可用:${acpElicitationActions.join(", ")})。`);
933
462
  const requestId = asString(rawArgs, "requestId");
934
463
  const optionId = asString(rawArgs, "optionId");
935
464
  const content = asContent(rawArgs, "content");
@@ -951,9 +480,9 @@ export class McpWorkerRuntime {
951
480
  }
952
481
  case "worker_discover": {
953
482
  const rawTarget = asString(rawArgs, "target") ?? "overview";
954
- requireThat((discoverTargets as readonly string[]).includes(rawTarget),
483
+ requireThat(isOneOf(rawTarget, discoverTargets),
955
484
  `参数 target 无效:${rawTarget}(可用:${discoverTargets.join(", ")})。`);
956
- const target = rawTarget as DiscoverTarget;
485
+ const target = rawTarget;
957
486
  const workerId = asString(rawArgs, "workerId");
958
487
  const backendRaw = asString(rawArgs, "backend");
959
488
  const model = asString(rawArgs, "model");
@@ -988,17 +517,18 @@ export class McpWorkerRuntime {
988
517
  };
989
518
  }
990
519
  }
520
+ throw new Error(`未知工具:${name satisfies never}`);
991
521
  }
992
522
 
993
- async close(preserve = false): Promise<void> {
994
- if (this.#closed) return;
995
- this.#closed = true;
523
+ close(preserve = false): Promise<void> {
524
+ if (this.#closing) return this.#closing;
996
525
  const entries = [...this.#services.values()];
997
526
  this.#services.clear();
998
- await Promise.allSettled([
527
+ this.#closing = Promise.allSettled([
999
528
  this.#bridge.close(),
1000
529
  ...entries.map(({ service, owner }) => service.close(owner, preserve)),
1001
- ]);
530
+ ]).then(() => {});
531
+ return this.#closing;
1002
532
  }
1003
533
  }
1004
534