personal-bot 0.2.20 → 0.3.1

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 (343) hide show
  1. package/.claude-plugin/marketplace.json +3 -3
  2. package/.claude-plugin/plugin.json +2 -5
  3. package/.mcp.json +11 -0
  4. package/CONTEXT.md +17 -73
  5. package/README.md +41 -120
  6. package/README.zh-CN.md +41 -120
  7. package/docs/README.md +31 -23
  8. package/docs/architecture/design.md +74 -0
  9. package/docs/architecture/extensibility.md +78 -0
  10. package/docs/architecture/model-context.md +31 -0
  11. package/docs/architecture/model-instruction-guidelines.md +34 -0
  12. package/docs/architecture/principles.md +33 -0
  13. package/docs/guides/capabilities.md +36 -0
  14. package/docs/guides/cross-harness-workers.md +83 -0
  15. package/docs/guides/history.md +25 -0
  16. package/docs/guides/workspace-configuration.md +102 -0
  17. package/docs/hosts/antigravity.md +52 -0
  18. package/docs/hosts/claude-code.md +47 -0
  19. package/docs/hosts/dsh.md +67 -0
  20. package/docs/hosts/pi.md +49 -0
  21. package/docs/maintainers/release.md +59 -0
  22. package/hooks/hooks.json +0 -3
  23. package/lib/antigravity-plugin/hooks.json +23 -0
  24. package/lib/antigravity-plugin/lib/claude.d.ts +1 -0
  25. package/lib/antigravity-plugin/lib/claude.js +13 -0
  26. package/lib/antigravity-plugin/lib/common/json.d.ts +6 -0
  27. package/lib/antigravity-plugin/lib/common/json.js +16 -0
  28. package/lib/antigravity-plugin/lib/common/paths.d.ts +1 -0
  29. package/lib/antigravity-plugin/lib/common/paths.js +2 -0
  30. package/lib/antigravity-plugin/lib/common/validation.d.ts +3 -0
  31. package/lib/antigravity-plugin/lib/common/validation.js +8 -0
  32. package/lib/antigravity-plugin/lib/common/version.d.ts +3 -0
  33. package/lib/antigravity-plugin/lib/common/version.js +13 -0
  34. package/lib/antigravity-plugin/lib/extension/acp-worker.js +11597 -0
  35. package/lib/antigravity-plugin/lib/extension/mcp.js +2715 -0
  36. package/lib/antigravity-plugin/lib/extension/plugin-runtime.d.ts +10 -0
  37. package/lib/antigravity-plugin/lib/extension/plugin-runtime.js +67 -0
  38. package/lib/antigravity-plugin/lib/integrations/agent-resources.d.ts +16 -0
  39. package/lib/antigravity-plugin/lib/integrations/agent-resources.js +56 -0
  40. package/lib/antigravity-plugin/lib/integrations/hosts/antigravity.d.ts +4 -0
  41. package/lib/antigravity-plugin/lib/integrations/hosts/antigravity.js +79 -0
  42. package/lib/antigravity-plugin/lib/integrations/hosts/claude.d.ts +3 -0
  43. package/lib/antigravity-plugin/lib/integrations/hosts/claude.js +60 -0
  44. package/lib/antigravity-plugin/lib/integrations/hosts/registry.d.ts +15 -0
  45. package/lib/antigravity-plugin/lib/integrations/hosts/registry.js +34 -0
  46. package/lib/antigravity-plugin/lib/model/acp.d.ts +164 -0
  47. package/lib/antigravity-plugin/lib/model/acp.js +12 -0
  48. package/lib/antigravity-plugin/lib/model/plugin-host.d.ts +48 -0
  49. package/lib/antigravity-plugin/lib/model/workspace-config.d.ts +24 -0
  50. package/lib/antigravity-plugin/lib/model/workspace-config.js +1 -0
  51. package/lib/antigravity-plugin/lib/model/workspace-mcp.d.ts +51 -0
  52. package/lib/antigravity-plugin/lib/model/workspace-mcp.js +4 -0
  53. package/lib/antigravity-plugin/lib/plugin.d.ts +1 -0
  54. package/lib/antigravity-plugin/lib/plugin.js +17 -0
  55. package/lib/antigravity-plugin/lib/services/workspace/workspace-config.d.ts +8 -0
  56. package/lib/antigravity-plugin/lib/services/workspace/workspace-config.js +95 -0
  57. package/lib/antigravity-plugin/lib/services/workspace/workspace-preparation.d.ts +3 -0
  58. package/lib/antigravity-plugin/lib/services/workspace/workspace-preparation.js +26 -0
  59. package/lib/antigravity-plugin/lib/services/workspace/workspace-skills.d.ts +8 -0
  60. package/lib/antigravity-plugin/lib/services/workspace/workspace-skills.js +91 -0
  61. package/lib/antigravity-plugin/lib/storage/atomic-json.d.ts +11 -0
  62. package/lib/antigravity-plugin/lib/storage/atomic-json.js +101 -0
  63. package/lib/antigravity-plugin/mcp_config.json +13 -0
  64. package/lib/antigravity-plugin/package.json +6 -0
  65. package/lib/antigravity-plugin/plugin.json +7 -0
  66. package/lib/antigravity-plugin/resources/agents/coordinator.md +11 -0
  67. package/{resources/claude → lib/antigravity-plugin/resources}/agents/general-purpose.md +0 -5
  68. package/lib/antigravity-plugin/resources/prompts/plugin-coordinator.md +1 -0
  69. package/lib/antigravity-plugin/resources/prompts/workspace.md +31 -0
  70. package/lib/antigravity-plugin/resources/references/compute-finance.md +22 -0
  71. package/lib/antigravity-plugin/resources/references/compute.md +16 -0
  72. package/lib/antigravity-plugin/resources/references/task-conductor.md +25 -0
  73. package/lib/antigravity-plugin/resources/templates/workspace-agents.md +21 -0
  74. package/lib/antigravity-plugin/skills/pbot/SKILL.md +16 -0
  75. package/lib/antigravity-plugin/skills/project-maintenance/SKILL.md +35 -0
  76. package/lib/antigravity-plugin/skills/provider-connections/SKILL.md +42 -0
  77. package/lib/claude.js +4 -11
  78. package/lib/client.js +14 -531
  79. package/lib/common/markdown.js +2 -3
  80. package/lib/common/validation.d.ts +2 -0
  81. package/lib/common/validation.js +4 -0
  82. package/lib/extension/acp-member.d.ts +2 -0
  83. package/lib/extension/acp-member.js +9 -8
  84. package/lib/extension/acp-worker.js +11578 -121
  85. package/lib/extension/dsh/acp-member.js +26 -2
  86. package/lib/extension/dsh/command.js +19 -57
  87. package/lib/extension/dsh/history.js +2 -4
  88. package/lib/extension/dsh/management.d.ts +0 -2
  89. package/lib/extension/dsh/management.js +27 -126
  90. package/lib/extension/dsh/workspace.d.ts +5 -47
  91. package/lib/extension/dsh/workspace.js +76 -108
  92. package/lib/extension/mcp-bridge.d.ts +41 -0
  93. package/lib/extension/mcp-bridge.js +412 -0
  94. package/lib/extension/mcp-workers.d.ts +980 -0
  95. package/lib/extension/mcp-workers.js +882 -0
  96. package/lib/extension/mcp.js +2715 -0
  97. package/lib/extension/plugin-runtime.d.ts +10 -0
  98. package/lib/extension/plugin-runtime.js +67 -0
  99. package/lib/extension/setup-cli.js +215 -2
  100. package/lib/integrations/acp/agents.d.ts +10 -11
  101. package/lib/integrations/acp/agents.js +65 -33
  102. package/lib/integrations/acp/claude.d.ts +2 -2
  103. package/lib/integrations/acp/claude.js +5 -3
  104. package/lib/integrations/acp/connection.d.ts +17 -4
  105. package/lib/integrations/acp/connection.js +53 -27
  106. package/lib/integrations/acp/executable.d.ts +3 -0
  107. package/lib/integrations/acp/executable.js +42 -0
  108. package/lib/integrations/acp/harnesses/claude.d.ts +2 -0
  109. package/lib/integrations/acp/harnesses/claude.js +49 -0
  110. package/lib/integrations/acp/harnesses/dsh.d.ts +2 -0
  111. package/lib/integrations/acp/harnesses/dsh.js +35 -0
  112. package/lib/integrations/acp/harnesses/generic.d.ts +13 -0
  113. package/lib/integrations/acp/harnesses/generic.js +37 -0
  114. package/lib/integrations/acp/harnesses/pi.d.ts +2 -0
  115. package/lib/integrations/acp/harnesses/pi.js +34 -0
  116. package/lib/integrations/acp/harnesses/presets.d.ts +3 -0
  117. package/lib/integrations/acp/harnesses/presets.js +20 -0
  118. package/lib/integrations/acp/launch.d.ts +33 -4
  119. package/lib/integrations/acp/launch.js +60 -48
  120. package/lib/integrations/acp/mcp.d.ts +6 -0
  121. package/lib/integrations/acp/mcp.js +40 -0
  122. package/lib/integrations/acp/model-selection.d.ts +9 -2
  123. package/lib/integrations/acp/model-selection.js +73 -27
  124. package/lib/integrations/acp/registry.d.ts +18 -0
  125. package/lib/integrations/acp/registry.js +50 -0
  126. package/lib/integrations/agent-resources.d.ts +16 -1
  127. package/lib/integrations/agent-resources.js +45 -9
  128. package/lib/integrations/dsh/mcp.d.ts +4 -0
  129. package/lib/integrations/dsh/mcp.js +28 -0
  130. package/lib/integrations/dsh/resources.d.ts +3 -3
  131. package/lib/integrations/dsh/resources.js +21 -12
  132. package/lib/integrations/dsh/skills.d.ts +5 -1
  133. package/lib/integrations/dsh/skills.js +10 -6
  134. package/lib/integrations/hosts/antigravity.d.ts +4 -0
  135. package/lib/integrations/hosts/antigravity.js +79 -0
  136. package/lib/integrations/hosts/claude.d.ts +3 -0
  137. package/lib/integrations/hosts/claude.js +60 -0
  138. package/lib/integrations/hosts/registry.d.ts +15 -0
  139. package/lib/integrations/hosts/registry.js +34 -0
  140. package/lib/model/acp.d.ts +107 -2
  141. package/lib/model/acp.js +12 -1
  142. package/lib/model/agent.d.ts +35 -33
  143. package/lib/model/plugin-host.d.ts +48 -0
  144. package/lib/model/plugin-host.js +1 -0
  145. package/lib/model/workspace-config.d.ts +12 -0
  146. package/lib/model/workspace-mcp.d.ts +51 -0
  147. package/lib/model/workspace-mcp.js +4 -0
  148. package/lib/plugin.d.ts +1 -0
  149. package/lib/plugin.js +17 -0
  150. package/lib/services/agents/acp-run.d.ts +13 -1
  151. package/lib/services/agents/acp-run.js +30 -2
  152. package/lib/services/agents/agent-service.d.ts +35 -120
  153. package/lib/services/agents/agent-service.js +156 -160
  154. package/lib/services/installation/setup-service.js +17 -1
  155. package/lib/services/workspace/workspace-config.d.ts +2 -1
  156. package/lib/services/workspace/workspace-config.js +43 -9
  157. package/lib/services/workspace/workspace-mcp.d.ts +14 -0
  158. package/lib/services/workspace/workspace-mcp.js +200 -0
  159. package/lib/services/workspace/workspace-skills.d.ts +8 -0
  160. package/lib/services/workspace/workspace-skills.js +91 -0
  161. package/lib/storage/acp-files.d.ts +3 -1
  162. package/lib/storage/acp-files.js +32 -2
  163. package/lib/storage/acp-history.d.ts +3 -2
  164. package/lib/storage/acp-history.js +19 -7
  165. package/lib/storage/agent-files.d.ts +8 -8
  166. package/lib/storage/agent-files.js +27 -47
  167. package/lib/tools/history/contract.d.ts +1 -1
  168. package/lib/tools/history/contract.js +17 -11
  169. package/lib/ui/dsh/index.js +8 -3
  170. package/lib/ui/dsh/management.d.ts +1 -1
  171. package/lib/ui/dsh/management.js +24 -456
  172. package/lib/ui/dsh/remote.d.ts +0 -2
  173. package/lib/ui/dsh/remote.js +1 -1
  174. package/package.json +12 -7
  175. package/resources/agents/coordinator.md +2 -2
  176. package/resources/antigravity/skills/pbot/SKILL.md +16 -0
  177. package/resources/claude/skills/pbot/SKILL.md +1 -1
  178. package/resources/prompts/history-coordinator.md +1 -0
  179. package/resources/prompts/plugin-coordinator.md +1 -0
  180. package/resources/prompts/workspace.md +9 -8
  181. package/resources/references/compute.md +9 -11
  182. package/resources/references/task-conductor.md +12 -26
  183. package/resources/skills/project-maintenance/SKILL.md +16 -21
  184. package/resources/skills/provider-connections/SKILL.md +24 -40
  185. package/resources/templates/workspace-agents.md +4 -0
  186. package/scripts/README.md +17 -34
  187. package/src/claude.ts +4 -8
  188. package/src/common/markdown.ts +2 -3
  189. package/src/common/validation.ts +6 -0
  190. package/src/extension/acp-member.ts +9 -8
  191. package/src/extension/acp-worker.ts +239 -97
  192. package/src/extension/command.ts +38 -36
  193. package/src/extension/dsh/acp-member.ts +21 -2
  194. package/src/extension/dsh/command.ts +21 -51
  195. package/src/extension/dsh/files.ts +1 -0
  196. package/src/extension/dsh/history.ts +9 -6
  197. package/src/extension/dsh/management.ts +27 -58
  198. package/src/extension/dsh/workspace.ts +88 -99
  199. package/src/extension/events.ts +13 -10
  200. package/src/extension/history.ts +2 -50
  201. package/src/extension/lifecycle.ts +37 -22
  202. package/src/extension/mcp-bridge.ts +412 -0
  203. package/src/extension/mcp-workers.ts +941 -0
  204. package/src/extension/pi-acp-member.ts +29 -5
  205. package/src/extension/plugin-runtime.ts +63 -0
  206. package/src/extension/setup-cli.ts +186 -2
  207. package/src/integrations/acp/agents.ts +70 -24
  208. package/src/integrations/acp/claude.ts +11 -4
  209. package/src/integrations/acp/connection.ts +63 -25
  210. package/src/integrations/acp/executable.ts +41 -0
  211. package/src/integrations/acp/harnesses/claude.ts +50 -0
  212. package/src/integrations/acp/harnesses/dsh.ts +40 -0
  213. package/src/integrations/acp/harnesses/generic.ts +52 -0
  214. package/src/integrations/acp/harnesses/pi.ts +35 -0
  215. package/src/integrations/acp/harnesses/presets.ts +22 -0
  216. package/src/integrations/acp/launch.ts +69 -47
  217. package/src/integrations/acp/mcp.ts +43 -0
  218. package/src/integrations/acp/model-selection.ts +68 -25
  219. package/src/integrations/acp/registry.ts +60 -0
  220. package/src/integrations/agent-resources.ts +70 -6
  221. package/src/integrations/dsh/mcp.ts +30 -0
  222. package/src/integrations/dsh/resources.ts +28 -13
  223. package/src/integrations/dsh/skills.ts +16 -6
  224. package/src/integrations/hosts/antigravity.ts +83 -0
  225. package/src/integrations/hosts/claude.ts +62 -0
  226. package/src/integrations/hosts/registry.ts +42 -0
  227. package/src/integrations/pi/mcp.ts +26 -0
  228. package/src/mcp.ts +14 -0
  229. package/src/model/acp.ts +113 -3
  230. package/src/model/agent.ts +18 -14
  231. package/src/model/plugin-host.ts +39 -0
  232. package/src/model/workspace-config.ts +14 -0
  233. package/src/model/workspace-mcp.ts +64 -0
  234. package/src/pbot.ts +69 -20
  235. package/src/plugin.ts +19 -0
  236. package/src/services/agents/acp-run.ts +35 -3
  237. package/src/services/agents/agent-service.ts +180 -160
  238. package/src/services/installation/setup-service.ts +17 -2
  239. package/src/services/workspace/workspace-config.ts +46 -8
  240. package/src/services/workspace/workspace-mcp.ts +242 -0
  241. package/src/services/workspace/workspace-skills.ts +78 -0
  242. package/src/storage/acp-files.ts +32 -3
  243. package/src/storage/acp-history.ts +18 -7
  244. package/src/storage/agent-files.ts +27 -41
  245. package/src/tools/history/contract.ts +17 -11
  246. package/src/tools/register.ts +4 -8
  247. package/src/ui/dsh/index.ts +8 -3
  248. package/src/ui/dsh/management.ts +40 -282
  249. package/src/ui/dsh/remote.ts +2 -2
  250. package/docs/adr/0001-claude-skill-discovery.md +0 -3
  251. package/docs/adr/0002-claude-native-collaboration.md +0 -3
  252. package/docs/agent-collaboration.md +0 -190
  253. package/docs/architecture-guidelines.md +0 -37
  254. package/docs/capability-design.md +0 -55
  255. package/docs/claude-code-design.md +0 -44
  256. package/docs/claude-code.md +0 -57
  257. package/docs/dsh.md +0 -337
  258. package/docs/file-storage.md +0 -97
  259. package/docs/history.md +0 -54
  260. package/docs/installation-design.md +0 -86
  261. package/docs/interaction-design.md +0 -21
  262. package/docs/model-context.md +0 -76
  263. package/docs/model-instruction-guidelines.md +0 -51
  264. package/docs/release.md +0 -108
  265. package/docs/technical-design.md +0 -163
  266. package/docs/workspace-configuration.md +0 -79
  267. package/lib/extension/claude-hooks.d.ts +0 -9
  268. package/lib/extension/claude-hooks.js +0 -78
  269. package/lib/extension/dsh/agent-events.d.ts +0 -24
  270. package/lib/extension/dsh/agent-events.js +0 -242
  271. package/lib/extension/dsh/agent-runtime.d.ts +0 -49
  272. package/lib/extension/dsh/agent-runtime.js +0 -351
  273. package/lib/integrations/dsh/dsh-agents.d.ts +0 -30
  274. package/lib/integrations/dsh/dsh-agents.js +0 -104
  275. package/lib/integrations/dsh/input.d.ts +0 -21
  276. package/lib/integrations/dsh/input.js +0 -62
  277. package/lib/integrations/dsh/notifications.d.ts +0 -8
  278. package/lib/integrations/dsh/notifications.js +0 -55
  279. package/lib/integrations/dsh/session.d.ts +0 -14
  280. package/lib/integrations/dsh/session.js +0 -60
  281. package/lib/integrations/team-context.d.ts +0 -18
  282. package/lib/integrations/team-context.js +0 -61
  283. package/lib/model/team.d.ts +0 -85
  284. package/lib/services/agents/agent-notices.d.ts +0 -13
  285. package/lib/services/agents/agent-notices.js +0 -25
  286. package/lib/services/agents/start-options.d.ts +0 -4
  287. package/lib/services/agents/start-options.js +0 -20
  288. package/lib/services/agents/team-service.d.ts +0 -168
  289. package/lib/services/agents/team-service.js +0 -345
  290. package/lib/storage/team-files.d.ts +0 -16
  291. package/lib/storage/team-files.js +0 -111
  292. package/lib/tools/agents/actions.d.ts +0 -62
  293. package/lib/tools/agents/actions.js +0 -62
  294. package/lib/tools/agents/contract.d.ts +0 -181
  295. package/lib/tools/agents/contract.js +0 -84
  296. package/lib/tools/agents/dsh-tool.d.ts +0 -5
  297. package/lib/tools/agents/dsh-tool.js +0 -34
  298. package/lib/tools/result.d.ts +0 -18
  299. package/lib/tools/result.js +0 -10
  300. package/lib/tools/teams/actions.d.ts +0 -23
  301. package/lib/tools/teams/actions.js +0 -40
  302. package/lib/tools/teams/contract.d.ts +0 -201
  303. package/lib/tools/teams/contract.js +0 -91
  304. package/lib/tools/teams/dsh-tool.d.ts +0 -8
  305. package/lib/tools/teams/dsh-tool.js +0 -39
  306. package/lib/ui/dsh/attachments.d.ts +0 -5
  307. package/lib/ui/dsh/attachments.js +0 -39
  308. package/resources/prompts/claude-coordinator.md +0 -1
  309. package/resources/prompts/native-coordinator.md +0 -1
  310. package/resources/prompts/team-member.md +0 -7
  311. package/src/extension/agent-events.ts +0 -210
  312. package/src/extension/agents-command.ts +0 -89
  313. package/src/extension/claude-hooks.ts +0 -74
  314. package/src/extension/dsh/agent-events.ts +0 -148
  315. package/src/extension/dsh/agent-runtime.ts +0 -252
  316. package/src/extension/subagent-entry.ts +0 -270
  317. package/src/extension/teams-command.ts +0 -67
  318. package/src/integrations/dsh/dsh-agents.ts +0 -97
  319. package/src/integrations/dsh/input.ts +0 -66
  320. package/src/integrations/dsh/notifications.ts +0 -46
  321. package/src/integrations/pi/agent-context.ts +0 -18
  322. package/src/integrations/pi/agent-input.ts +0 -19
  323. package/src/integrations/pi/pi-agents.ts +0 -84
  324. package/src/integrations/pi/team-context.ts +0 -26
  325. package/src/integrations/team-context.ts +0 -64
  326. package/src/model/team.ts +0 -29
  327. package/src/services/agents/agent-notices.ts +0 -28
  328. package/src/services/agents/start-options.ts +0 -19
  329. package/src/services/agents/team-service.ts +0 -275
  330. package/src/storage/team-files.ts +0 -93
  331. package/src/tools/agents/actions.ts +0 -57
  332. package/src/tools/agents/contract.ts +0 -101
  333. package/src/tools/agents/dsh-tool.ts +0 -37
  334. package/src/tools/agents/tool.ts +0 -20
  335. package/src/tools/teams/actions.ts +0 -34
  336. package/src/tools/teams/contract.ts +0 -109
  337. package/src/tools/teams/dsh-tool.ts +0 -45
  338. package/src/tools/teams/tool.ts +0 -29
  339. package/src/ui/agent-display.ts +0 -14
  340. package/src/ui/dsh/attachments.ts +0 -42
  341. package/src/ui/pi/menu.ts +0 -37
  342. package/src/ui/pi/reader.ts +0 -46
  343. /package/lib/{model/team.js → antigravity-plugin/lib/model/plugin-host.js} +0 -0
@@ -1,23 +1,53 @@
1
1
  import { mkdir, readFile } from "node:fs/promises";
2
2
  import { dirname, join } from "node:path";
3
3
  import { object } from "../../common/json.js";
4
+ import { isAcpBackend } from "../../common/validation.js";
4
5
  import { readJsonFile, writeJsonFile } from "../../storage/atomic-json.js";
6
+ import type { ResolvedWorkspaceFeatures, WorkspaceConfig, WorkspaceConfiguration, WorkspaceFeatures } from "../../model/workspace-config.js";
7
+
8
+ const featureKeys = ["prompts", "skills", "mcp"] as const;
5
9
 
6
10
  function config(value: unknown): Record<string, unknown> {
7
11
  if (!object(value) || value.enabled !== undefined && typeof value.enabled !== "boolean") {
8
12
  throw new Error("配置必须是 JSON 对象,enabled 必须是布尔值。");
9
13
  }
14
+ if (value.features !== undefined) {
15
+ if (!object(value.features) ||
16
+ Object.entries(value.features).some(([key, entry]) => !(featureKeys as readonly string[]).includes(key) || (entry !== undefined && typeof entry !== "boolean"))) {
17
+ throw new Error("features 必须是 JSON 对象,仅支持 prompts、skills、mcp 布尔开关。");
18
+ }
19
+ }
10
20
  if (value.acp !== undefined) {
11
- if (!object(value.acp) || Object.keys(value.acp).some(key => !["pi", "dsh", "claude"].includes(key))) throw new Error("acp 仅接受 pi、dsh 和 claude 启动配置。");
21
+ if (!object(value.acp) || Object.keys(value.acp).some(key => !isAcpBackend(key))) {
22
+ throw new Error("acp 键名必须为小写字母、数字和连字符(1–64 字符)。");
23
+ }
12
24
  for (const command of Object.values(value.acp)) {
13
- if (!object(command) || typeof command.command !== "string" || !command.command.trim() || command.command.includes("\0") ||
14
- !Array.isArray(command.args) || command.args.some(arg => typeof arg !== "string" || arg.includes("\0")) ||
15
- Object.keys(command).some(key => !["command", "args"].includes(key))) throw new Error("ACP 启动配置需要 command 和 args 字符串数组。");
25
+ // Without command, an entry keeps the registered default command and only sets env or permission.
26
+ const launch = !object(command) ? false : command.command === undefined
27
+ ? command.args === undefined
28
+ : typeof command.command === "string" && command.command.trim() && !command.command.includes("\0") &&
29
+ (command.args === undefined || (Array.isArray(command.args) && command.args.every(arg => typeof arg === "string" && !arg.includes("\0"))));
30
+ if (!object(command) || !launch ||
31
+ (command.env !== undefined && (!object(command.env) || Object.entries(command.env).some(([k, v]) => !k || k.includes("\0") || typeof v !== "string" || v.includes("\0")))) ||
32
+ (command.permission !== undefined && !["ask", "allow", "deny"].includes(String(command.permission))) ||
33
+ Object.keys(command).some(key => !["command", "args", "env", "permission"].includes(key))) {
34
+ throw new Error("ACP 配置需要 command(内置目标可省略)及可选 args 字符串数组、env 字符串映射、permission(ask、allow 或 deny)。");
35
+ }
16
36
  }
17
37
  }
18
38
  return value;
19
39
  }
20
- import type { WorkspaceConfig, WorkspaceConfiguration } from "../../model/workspace-config.js";
40
+
41
+ export function workspaceFeatures(configuration?: Pick<WorkspaceConfiguration, "features"> | WorkspaceFeatures): ResolvedWorkspaceFeatures {
42
+ const raw: WorkspaceFeatures | undefined = configuration && "features" in configuration
43
+ ? configuration.features
44
+ : configuration as WorkspaceFeatures | undefined;
45
+ return {
46
+ prompts: raw?.prompts !== false,
47
+ skills: raw?.skills !== false,
48
+ mcp: raw?.mcp !== false,
49
+ };
50
+ }
21
51
 
22
52
  export function workspaceConfigPath(root: string): string {
23
53
  return join(root, ".pbot", "config.json");
@@ -35,7 +65,13 @@ export async function readWorkspaceConfig(root: string): Promise<WorkspaceConfig
35
65
  try {
36
66
  const value = config(JSON.parse(content));
37
67
  const settings = value as WorkspaceConfig;
38
- return { path, present: true, enabled: settings.enabled === true, ...(settings.acp ? { acp: settings.acp } : {}) };
68
+ return {
69
+ path,
70
+ present: true,
71
+ enabled: settings.enabled === true,
72
+ ...(settings.features ? { features: settings.features } : {}),
73
+ ...(settings.acp ? { acp: settings.acp } : {}),
74
+ };
39
75
  } catch (error) {
40
76
  return { path, present: true, enabled: false, error: `工作区配置无效 ${path}: ${String(error)}` };
41
77
  }
@@ -45,11 +81,13 @@ export async function readWorkspaceConfig(root: string): Promise<WorkspaceConfig
45
81
  export async function initializeWorkspaceConfig(root: string): Promise<void> {
46
82
  const current = await readWorkspaceConfig(root);
47
83
  if (current.error) throw new Error(current.error);
48
- if (current.enabled) return;
84
+ const hasExplicitFeatures = featureKeys.every(key => typeof current.features?.[key] === "boolean");
85
+ if (current.enabled && hasExplicitFeatures) return;
49
86
  const directory = dirname(current.path);
50
87
  await mkdir(directory, { recursive: true });
51
88
  const value = current.present ? readJsonFile(directory, "config.json", config) : {};
52
- const written = writeJsonFile(directory, "config.json", { ...value, enabled: true }, config, !current.present);
89
+ const features = workspaceFeatures((value as WorkspaceConfig).features);
90
+ const written = writeJsonFile(directory, "config.json", { ...value, enabled: true, features }, config, !current.present);
53
91
  if (!written) await initializeWorkspaceConfig(root);
54
92
  }
55
93
 
@@ -0,0 +1,242 @@
1
+ import { mkdir, readFile } from "node:fs/promises";
2
+ import { dirname, join, resolve } from "node:path";
3
+ import { object } from "../../common/json.js";
4
+ import { requireThat } from "../../common/validation.js";
5
+ import type {
6
+ ResolvedWorkspaceMcpServer,
7
+ WorkspaceMcpConfig,
8
+ WorkspaceMcpConfiguration,
9
+ WorkspaceMcpHttpServer,
10
+ WorkspaceMcpServer,
11
+ WorkspaceMcpStdioServer,
12
+ } from "../../model/workspace-mcp.js";
13
+ import { readJsonFile, writeJsonFile } from "../../storage/atomic-json.js";
14
+
15
+ const serverNamePattern = /^[A-Za-z0-9][A-Za-z0-9_-]{0,31}$/;
16
+ const reservedServerNames = new Set(["pbot"]);
17
+ const stdioKeys = new Set(["command", "args", "env", "cwd", "description", "timeout", "enabled"]);
18
+ const httpKeys = new Set(["url", "headers", "description", "timeout", "enabled"]);
19
+ const defaultTimeoutSeconds = 60;
20
+ const envPattern = /\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g;
21
+
22
+ export function isWorkspaceMcpServerName(name: string): boolean {
23
+ return serverNamePattern.test(name) && !reservedServerNames.has(name.toLowerCase());
24
+ }
25
+
26
+ export function isWorkspaceMcpHttpServer(server: WorkspaceMcpServer): server is WorkspaceMcpHttpServer {
27
+ return "url" in server && typeof server.url === "string";
28
+ }
29
+
30
+ function validateStringRecord(value: unknown, label: string): Record<string, string> {
31
+ requireThat(object(value), `${label} 必须是字符串映射。`);
32
+ const result: Record<string, string> = {};
33
+ for (const [key, entry] of Object.entries(value)) {
34
+ requireThat(key.length > 0 && !key.includes("\0") && typeof entry === "string" && !entry.includes("\0"),
35
+ `${label}.${key} 必须是非空键与无空字节字符串值。`);
36
+ result[key] = entry;
37
+ }
38
+ return result;
39
+ }
40
+
41
+ export function validateWorkspaceMcpServer(name: string, value: unknown): WorkspaceMcpServer {
42
+ requireThat(serverNamePattern.test(name), `MCP 服务名无效:${name}(需匹配 [A-Za-z0-9][A-Za-z0-9_-]{0,31})。`);
43
+ requireThat(!reservedServerNames.has(name.toLowerCase()), `MCP 服务名 "${name}" 为 Personal Bot 保留名称。`);
44
+ requireThat(object(value), `MCP 服务 "${name}" 配置必须是 JSON 对象。`);
45
+ const hasCommand = value.command !== undefined;
46
+ const hasUrl = value.url !== undefined;
47
+ requireThat(hasCommand !== hasUrl, `MCP 服务 "${name}" 必须且只能声明 command(stdio)或 url(Streamable HTTP)之一。`);
48
+
49
+ const allowed = hasCommand ? stdioKeys : httpKeys;
50
+ const unknown = Object.keys(value).filter(key => !allowed.has(key));
51
+ requireThat(unknown.length === 0, `MCP 服务 "${name}" 包含未知字段:${unknown.join(", ")}。`);
52
+
53
+ if (value.description !== undefined) {
54
+ requireThat(typeof value.description === "string" && !value.description.includes("\0"),
55
+ `MCP 服务 "${name}" 的 description 必须是字符串。`);
56
+ }
57
+ if (value.timeout !== undefined) {
58
+ requireThat(typeof value.timeout === "number" && Number.isInteger(value.timeout) && value.timeout >= 1 && value.timeout <= 3600,
59
+ `MCP 服务 "${name}" 的 timeout 必须是 1–3600 的整数秒。`);
60
+ }
61
+ if (value.enabled !== undefined) {
62
+ requireThat(typeof value.enabled === "boolean", `MCP 服务 "${name}" 的 enabled 必须是布尔值。`);
63
+ }
64
+
65
+ const base = {
66
+ ...(value.description !== undefined ? { description: value.description as string } : {}),
67
+ ...(value.timeout !== undefined ? { timeout: value.timeout as number } : {}),
68
+ ...(value.enabled !== undefined ? { enabled: value.enabled as boolean } : {}),
69
+ };
70
+
71
+ if (hasCommand) {
72
+ requireThat(typeof value.command === "string" && value.command.trim().length > 0 && !value.command.includes("\0"),
73
+ `MCP 服务 "${name}" 的 command 必须是非空字符串。`);
74
+ let args: string[] | undefined;
75
+ if (value.args !== undefined) {
76
+ requireThat(Array.isArray(value.args) && value.args.every(item => typeof item === "string" && !item.includes("\0")),
77
+ `MCP 服务 "${name}" 的 args 必须是字符串数组。`);
78
+ args = [...(value.args as string[])];
79
+ }
80
+ const env = value.env !== undefined ? validateStringRecord(value.env, `MCP 服务 "${name}" 的 env`) : undefined;
81
+ let cwd: string | undefined;
82
+ if (value.cwd !== undefined) {
83
+ requireThat(typeof value.cwd === "string" && value.cwd.trim().length > 0 && !value.cwd.includes("\0"),
84
+ `MCP 服务 "${name}" 的 cwd 必须是非空字符串。`);
85
+ cwd = value.cwd;
86
+ }
87
+ const entry: WorkspaceMcpStdioServer = {
88
+ command: value.command,
89
+ ...(args ? { args } : {}),
90
+ ...(env ? { env } : {}),
91
+ ...(cwd ? { cwd } : {}),
92
+ ...base,
93
+ };
94
+ return entry;
95
+ }
96
+
97
+ requireThat(typeof value.url === "string" && value.url.trim().length > 0 && !value.url.includes("\0"),
98
+ `MCP 服务 "${name}" 的 url 必须是非空字符串。`);
99
+ const rawUrl = value.url.trim();
100
+ requireThat(/^https?:\/\/.+/.test(rawUrl) || envPattern.test(rawUrl),
101
+ `MCP 服务 "${name}" 的 url 必须以 http:// 或 https:// 开头。`);
102
+ envPattern.lastIndex = 0;
103
+ const headers = value.headers !== undefined ? validateStringRecord(value.headers, `MCP 服务 "${name}" 的 headers`) : undefined;
104
+ const entry: WorkspaceMcpHttpServer = {
105
+ url: rawUrl,
106
+ ...(headers ? { headers } : {}),
107
+ ...base,
108
+ };
109
+ return entry;
110
+ }
111
+
112
+ function validateMcpFile(value: unknown): WorkspaceMcpConfig {
113
+ requireThat(object(value), "工作区 MCP 配置必须是 JSON 对象。");
114
+ const rawServers = value.mcpServers;
115
+ requireThat(rawServers !== undefined && object(rawServers), "工作区 MCP 配置需要 mcpServers 对象。");
116
+ const servers: Record<string, WorkspaceMcpServer> = {};
117
+ for (const [name, entry] of Object.entries(rawServers)) {
118
+ servers[name] = validateWorkspaceMcpServer(name, entry);
119
+ }
120
+ return { mcpServers: servers };
121
+ }
122
+
123
+ export function workspaceMcpPath(root: string): string {
124
+ return join(root, ".pbot", "mcp.json");
125
+ }
126
+
127
+ export async function readWorkspaceMcpConfig(root: string): Promise<WorkspaceMcpConfiguration> {
128
+ const path = workspaceMcpPath(root);
129
+ let content: string;
130
+ try { content = await readFile(path, "utf8"); }
131
+ catch (error) {
132
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return { path, present: false, servers: {} };
133
+ return { path, present: true, servers: {}, error: `无法读取工作区 MCP 配置 ${path}: ${String(error)}` };
134
+ }
135
+ try {
136
+ const parsed = validateMcpFile(JSON.parse(content));
137
+ return { path, present: true, servers: parsed.mcpServers };
138
+ } catch (error) {
139
+ return { path, present: true, servers: {}, error: `工作区 MCP 配置无效 ${path}: ${error instanceof Error ? error.message : String(error)}` };
140
+ }
141
+ }
142
+
143
+ export function expandEnvTemplate(value: string, env: NodeJS.ProcessEnv, context: string): string {
144
+ return value.replace(envPattern, (_match, variable: string) => {
145
+ const resolved = env[variable];
146
+ requireThat(resolved !== undefined, `${context} 引用的环境变量 ${variable} 未设置。`);
147
+ return resolved;
148
+ });
149
+ }
150
+
151
+ export function resolveWorkspaceMcpServer(
152
+ root: string,
153
+ name: string,
154
+ server: WorkspaceMcpServer,
155
+ env: NodeJS.ProcessEnv = process.env,
156
+ ): ResolvedWorkspaceMcpServer {
157
+ const timeout = server.timeout ?? defaultTimeoutSeconds;
158
+ if (isWorkspaceMcpHttpServer(server)) {
159
+ const url = expandEnvTemplate(server.url, env, `MCP 服务 "${name}" 的 url`);
160
+ requireThat(/^https?:\/\/.+/.test(url), `MCP 服务 "${name}" 展开后的 url 必须以 http:// 或 https:// 开头。`);
161
+ const headers: Record<string, string> = {};
162
+ for (const [key, value] of Object.entries(server.headers ?? {})) {
163
+ headers[key] = expandEnvTemplate(value, env, `MCP 服务 "${name}" 的 headers.${key}`);
164
+ }
165
+ return {
166
+ transport: "http",
167
+ name,
168
+ url,
169
+ headers,
170
+ ...(server.description ? { description: server.description } : {}),
171
+ timeout,
172
+ };
173
+ }
174
+
175
+ const command = expandEnvTemplate(server.command, env, `MCP 服务 "${name}" 的 command`);
176
+ const args = (server.args ?? []).map((arg, index) => expandEnvTemplate(arg, env, `MCP 服务 "${name}" 的 args[${index}]`));
177
+ const resolvedEnv: Record<string, string> = {};
178
+ for (const [key, value] of Object.entries(server.env ?? {})) {
179
+ resolvedEnv[key] = expandEnvTemplate(value, env, `MCP 服务 "${name}" 的 env.${key}`);
180
+ }
181
+ const cwd = server.cwd ? resolve(root, expandEnvTemplate(server.cwd, env, `MCP 服务 "${name}" 的 cwd`)) : root;
182
+ return {
183
+ transport: "stdio",
184
+ name,
185
+ command,
186
+ args,
187
+ env: resolvedEnv,
188
+ cwd,
189
+ ...(server.description ? { description: server.description } : {}),
190
+ timeout,
191
+ };
192
+ }
193
+
194
+ export function resolveWorkspaceMcpServers(
195
+ root: string,
196
+ configuration: WorkspaceMcpConfiguration,
197
+ env: NodeJS.ProcessEnv = process.env,
198
+ ): ResolvedWorkspaceMcpServer[] {
199
+ if (configuration.error) throw new Error(configuration.error);
200
+ const resolved: ResolvedWorkspaceMcpServer[] = [];
201
+ for (const [name, server] of Object.entries(configuration.servers)) {
202
+ if (server.enabled === false) continue;
203
+ resolved.push(resolveWorkspaceMcpServer(root, name, server, env));
204
+ }
205
+ return resolved;
206
+ }
207
+
208
+ export async function upsertWorkspaceMcpServer(
209
+ root: string,
210
+ name: string,
211
+ server: WorkspaceMcpServer,
212
+ ): Promise<WorkspaceMcpConfiguration> {
213
+ const validated = validateWorkspaceMcpServer(name, server);
214
+ const current = await readWorkspaceMcpConfig(root);
215
+ if (current.error) throw new Error(current.error);
216
+ const directory = dirname(current.path);
217
+ await mkdir(directory, { recursive: true });
218
+ const existing = current.present ? readJsonFile(directory, "mcp.json", validateMcpFile) : { mcpServers: {} };
219
+ const next: WorkspaceMcpConfig = { mcpServers: { ...existing.mcpServers, [name]: validated } };
220
+ const written = writeJsonFile(directory, "mcp.json", next, validateMcpFile, !current.present);
221
+ if (!written) return upsertWorkspaceMcpServer(root, name, server);
222
+ return readWorkspaceMcpConfig(root);
223
+ }
224
+
225
+ export async function removeWorkspaceMcpServer(
226
+ root: string,
227
+ name: string,
228
+ ): Promise<{ removed: boolean; configuration: WorkspaceMcpConfiguration }> {
229
+ const current = await readWorkspaceMcpConfig(root);
230
+ if (current.error) throw new Error(current.error);
231
+ if (!current.present || !Object.hasOwn(current.servers, name)) {
232
+ return { removed: false, configuration: current };
233
+ }
234
+ const directory = dirname(current.path);
235
+ const existing = readJsonFile(directory, "mcp.json", validateMcpFile);
236
+ if (!Object.hasOwn(existing.mcpServers, name)) {
237
+ return { removed: false, configuration: await readWorkspaceMcpConfig(root) };
238
+ }
239
+ const remaining = Object.fromEntries(Object.entries(existing.mcpServers).filter(([key]) => key !== name));
240
+ writeJsonFile(directory, "mcp.json", { mcpServers: remaining }, validateMcpFile);
241
+ return { removed: true, configuration: await readWorkspaceMcpConfig(root) };
242
+ }
@@ -0,0 +1,78 @@
1
+ import { readdir, readFile } from "node:fs/promises";
2
+ import { join } from "node:path";
3
+ import type { WorkspaceSkillMeta } from "../../model/workspace-mcp.js";
4
+
5
+ function unquoteYaml(value: string): string {
6
+ const trimmed = value.trim();
7
+ if (trimmed.length >= 2 && ((trimmed.startsWith('"') && trimmed.endsWith('"')) || (trimmed.startsWith("'") && trimmed.endsWith("'")))) {
8
+ return trimmed.slice(1, -1).trim();
9
+ }
10
+ return trimmed;
11
+ }
12
+
13
+ /** Parse YAML frontmatter fields (`name` and `description`) from a SKILL.md document. */
14
+ export function parseSkillFrontmatter(content: string): { name?: string; description?: string } | undefined {
15
+ const match = content.match(/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/);
16
+ if (!match) return undefined;
17
+ const lines = match[1]!.split(/\r?\n/);
18
+ const fields: Record<string, string> = {};
19
+ for (let i = 0; i < lines.length; i++) {
20
+ const line = lines[i]!;
21
+ const pair = line.match(/^([A-Za-z0-9_-]+)\s*:\s*(.*)$/);
22
+ if (!pair) continue;
23
+ const key = pair[1]!;
24
+ const raw = pair[2]!.trim();
25
+ if (/^[>|][+-]?$/.test(raw)) {
26
+ const folded = raw.startsWith(">");
27
+ const block: string[] = [];
28
+ let indent: number | undefined;
29
+ while (i + 1 < lines.length) {
30
+ const next = lines[i + 1]!;
31
+ if (!next.trim()) { block.push(""); i++; continue; }
32
+ const leading = next.match(/^\s+/)?.[0].length ?? 0;
33
+ if (leading === 0) break;
34
+ indent ??= leading;
35
+ block.push(next.slice(Math.min(indent, leading)).trimEnd());
36
+ i++;
37
+ }
38
+ const joined = folded
39
+ ? block.map(item => item.trim()).filter(Boolean).join(" ")
40
+ : block.join("\n").trim();
41
+ fields[key] = joined;
42
+ } else if (raw) {
43
+ fields[key] = unquoteYaml(raw);
44
+ }
45
+ }
46
+ return {
47
+ ...(fields.name ? { name: fields.name } : {}),
48
+ ...(fields.description ? { description: fields.description } : {}),
49
+ };
50
+ }
51
+
52
+ /** Scan `<workspace>/.agents/skills/<dir>/SKILL.md` for workspace-authored skills. */
53
+ export async function discoverWorkspaceSkills(root: string): Promise<WorkspaceSkillMeta[]> {
54
+ const skillsDir = join(root, ".agents", "skills");
55
+ let entries;
56
+ try { entries = await readdir(skillsDir, { withFileTypes: true }); }
57
+ catch (error) {
58
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return [];
59
+ throw error;
60
+ }
61
+ const results: WorkspaceSkillMeta[] = [];
62
+ for (const entry of entries) {
63
+ if (entry.name.startsWith(".") || (!entry.isDirectory() && !entry.isSymbolicLink())) continue;
64
+ const filePath = join(skillsDir, entry.name, "SKILL.md");
65
+ let content: string;
66
+ try { content = await readFile(filePath, "utf8"); }
67
+ catch { continue; }
68
+ const meta = parseSkillFrontmatter(content);
69
+ if (!meta?.name || !meta.description) continue;
70
+ results.push({
71
+ name: meta.name,
72
+ description: meta.description,
73
+ path: `.agents/skills/${entry.name}/SKILL.md`,
74
+ });
75
+ }
76
+ results.sort((a, b) => a.name.localeCompare(b.name));
77
+ return results;
78
+ }
@@ -1,14 +1,18 @@
1
1
  import { isAbsolute } from "node:path";
2
2
  import { object } from "../common/json.js";
3
- import { requireThat } from "../common/validation.js";
3
+ import { isAcpBackend, requireThat } from "../common/validation.js";
4
4
  import { fileId } from "./file-access.js";
5
- import type { AcpAnswer, AcpInput, AcpPermission, AcpPermissionReply, AcpModelState, AcpProcess, AcpReport, AcpSessionReference } from "../model/acp.js";
5
+ import type { AcpAnswer, AcpElicitation, AcpElicitationReply, AcpInput, AcpPermission, AcpPermissionReply, AcpModelState, AcpProcess, AcpReport, AcpSessionReference } from "../model/acp.js";
6
6
 
7
7
  const text = (value: unknown): value is string => typeof value === "string" && value.length > 0 && !value.includes("\0");
8
8
  export function acpReference(value: unknown): AcpSessionReference {
9
- requireThat(object(value) && value.host === "acp" && ["pi", "dsh", "claude"].includes(String(value.backend)) &&
9
+ requireThat(object(value) && value.host === "acp" && isAcpBackend(value.backend) &&
10
10
  text(value.command) && isAbsolute(value.command) && Array.isArray(value.args) && value.args.every(arg => typeof arg === "string" && !arg.includes("\0")) &&
11
11
  (value.sessionId === null || text(value.sessionId)), "ACP 会话引用无效。");
12
+ if (value.env !== undefined) {
13
+ requireThat(object(value.env) && Object.entries(value.env).every(([k, v]) => text(k) && typeof v === "string" && !v.includes("\0")), "ACP 环境变量配置无效。");
14
+ }
15
+ requireThat(value.permission === undefined || ["ask", "allow", "deny"].includes(String(value.permission)), "ACP 权限策略无效。");
12
16
  const capabilities = value.capabilities;
13
17
  if (capabilities !== undefined) requireThat(object(capabilities) &&
14
18
  ["resume", "load", "close"].every(key => typeof capabilities[key] === "boolean"), "ACP 会话能力无效。");
@@ -48,3 +52,28 @@ export function acpPermissionReply(value: unknown): AcpPermissionReply {
48
52
  requireThat(object(value) && (value.optionId === null || text(value.optionId)), "ACP 确认答复无效。");
49
53
  return value as unknown as AcpPermissionReply;
50
54
  }
55
+ function elicitationValue(value: unknown): boolean {
56
+ return typeof value === "string"
57
+ || (typeof value === "number" && Number.isFinite(value))
58
+ || typeof value === "boolean"
59
+ || (Array.isArray(value) && value.every(item => typeof item === "string"));
60
+ }
61
+ export function acpElicitation(value: unknown): AcpElicitation {
62
+ acpInput(value);
63
+ requireThat(object(value) && (value.mode === "form" || value.mode === "url") && typeof value.message === "string", "ACP 交互请求无效。");
64
+ if (value.mode === "form") {
65
+ requireThat(object(value.schema) && value.url === undefined, "ACP 表单交互请求缺少有效 schema。");
66
+ } else {
67
+ requireThat(text(value.url) && value.schema === undefined, "ACP URL 交互请求缺少有效 url。");
68
+ }
69
+ return value as unknown as AcpElicitation;
70
+ }
71
+ export function acpElicitationReply(value: unknown): AcpElicitationReply {
72
+ acpInput(value);
73
+ requireThat(object(value) && ["accept", "decline", "cancel"].includes(String(value.action)), "ACP 交互答复无效。");
74
+ if (value.content !== undefined) {
75
+ requireThat(value.action === "accept" && object(value.content) &&
76
+ Object.values(value.content).every(elicitationValue), "ACP 表单答复 content 无效。");
77
+ }
78
+ return value as unknown as AcpElicitationReply;
79
+ }
@@ -5,6 +5,7 @@ import { fileURLToPath } from "node:url";
5
5
  import type { HistoryHost } from "../model/history.js";
6
6
  import { readJsonFile } from "./atomic-json.js";
7
7
  import { acpReference } from "./acp-files.js";
8
+ import { isHistoryHost } from "./history-format.js";
8
9
 
9
10
  function memberDirectory(home: string, host: "pi" | "dsh") {
10
11
  if (host === "pi" && home.startsWith("file://")) return join(fileURLToPath(home), "pbot/subagents");
@@ -12,27 +13,37 @@ function memberDirectory(home: string, host: "pi" | "dsh") {
12
13
  return join(tilde ? join(homedir(), home.slice(2)) : home, "pbot/subagents");
13
14
  }
14
15
 
15
- /** A target session can be owned by either coordinator, even when its cwd belongs to another workspace. */
16
- export function acpHistorySessions(directories: { pi?: string; dsh?: string }) {
16
+ function defaultMcpWorkerDirectories(): string[] {
17
+ const dirs = [join(homedir(), ".pbot/subagents")];
18
+ if (process.env.PBOT_MCP_AGENT_DIR) dirs.push(process.env.PBOT_MCP_AGENT_DIR);
19
+ if (process.env.PLUGIN_DATA) dirs.push(join(process.env.PLUGIN_DATA, "subagents"));
20
+ return dirs;
21
+ }
22
+
23
+ /** Exclude ACP worker sessions owned by MCP or legacy Pi/dsh control directories from native history. */
24
+ export function acpHistorySessions(directories: { pi?: string; dsh?: string; mcp?: string } = {}) {
17
25
  const ids: Record<HistoryHost, Set<string>> = { pi: new Set(), dsh: new Set(), claude: new Set() };
18
26
  const warnings: string[] = [];
19
27
  const warn = (path: string, error: unknown) => {
20
28
  if ((error as NodeJS.ErrnoException).code !== "ENOENT") warnings.push(path + ": " + String(error));
21
29
  };
22
30
  const homes = { pi: process.env.PI_CODING_AGENT_DIR || "~/.pi/agent", dsh: process.env.DSH_HOME?.trim() ? process.env.DSH_HOME : "~/.dsh" };
23
- for (const host of ["pi", "dsh"] as const) {
24
- let directory = directories[host];
31
+ const scanDirs = new Set<string>([
32
+ directories.pi ?? memberDirectory(homes.pi, "pi"),
33
+ directories.dsh ?? memberDirectory(homes.dsh, "dsh"),
34
+ ...(directories.mcp ? [directories.mcp] : defaultMcpWorkerDirectories()),
35
+ ]);
36
+ for (const directory of scanDirs) {
25
37
  try {
26
- directory ??= memberDirectory(homes[host], host);
27
38
  for (const entry of readdirSync(directory, { withFileTypes: true })) {
28
39
  if (!entry.isDirectory() || entry.name.startsWith(".")) continue;
29
40
  const path = join(directory, entry.name);
30
41
  try {
31
42
  const ref = readJsonFile(path, "acp-session.json", acpReference);
32
- if (ref.sessionId !== null) ids[ref.backend].add(ref.sessionId);
43
+ if (ref.sessionId !== null && isHistoryHost(ref.backend)) ids[ref.backend].add(ref.sessionId);
33
44
  } catch (error) { warn(path, error); }
34
45
  }
35
- } catch (error) { warn(directory ?? homes[host], error); }
46
+ } catch (error) { warn(directory, error); }
36
47
  }
37
48
  return { ids, warnings };
38
49
  }
@@ -1,13 +1,13 @@
1
1
  import { existsSync, mkdirSync, readdirSync, rmSync } from "node:fs";
2
- import { isAbsolute, join } from "node:path";
2
+ import { join } from "node:path";
3
3
  import { randomUUID } from "node:crypto";
4
4
  import { canonical, object } from "../common/json.js";
5
5
  import { requireThat } from "../common/validation.js";
6
6
  import { readJsonFile, writeJsonFile } from "./atomic-json.js";
7
7
  import { fileId, privateDirectory } from "./file-access.js";
8
- import type { AgentDescriptor, AgentLaunch, AgentMessage, AgentStatus, AgentCycle, AgentSessionRef, AgentSessionReference, NativeAgentHost } from "../model/agent.js";
8
+ import type { AgentDescriptor, AgentLaunch, AgentMessage, AgentStatus, AgentCycle, AgentSessionReference } from "../model/agent.js";
9
9
  import type { AcpSessionReference } from "../model/acp.js";
10
- import { acpReference } from "./acp-files.js";
10
+ import { acpElicitation, acpPermission, acpReference } from "./acp-files.js";
11
11
 
12
12
  const text = (v: unknown): v is string => typeof v === "string" && v.length > 0;
13
13
  const number = (v: unknown): v is number => typeof v === "number" && Number.isFinite(v);
@@ -16,15 +16,6 @@ export function descriptor(v: unknown): AgentDescriptor {
16
16
  (v.parentLeaf === null || text(v.parentLeaf)) && number(v.createdAt) && object(v.options), "子会话身份无效。");
17
17
  fileId(v.agentId as string); return v as unknown as AgentDescriptor;
18
18
  }
19
- export function sessionRef(v: unknown): AgentSessionRef {
20
- requireThat(object(v) && (v.file === null || (text(v.file) && isAbsolute(v.file) && !v.file.includes("\0"))), "子会话引用无效。");
21
- return v as unknown as AgentSessionRef;
22
- }
23
- function dshSessionRef(v: unknown): Extract<AgentSessionReference, { host: "dsh" }> {
24
- requireThat(object(v) && v.host === "dsh" && text(v.sessionId), "dsh 原生会话引用无效。");
25
- fileId(v.sessionId as string);
26
- return v as unknown as Extract<AgentSessionReference, { host: "dsh" }>;
27
- }
28
19
  export function launch(v: unknown): AgentLaunch {
29
20
  requireThat(object(v) && text(v.generation) && text(v.name) && Number.isSafeInteger(v.sequence) && typeof v.stop === "boolean" && number(v.startedAt), "子会话启动状态无效。");
30
21
  return v as unknown as AgentLaunch;
@@ -48,9 +39,7 @@ export function status(v: unknown): AgentStatus {
48
39
  }
49
40
  export class AgentFiles {
50
41
  #failure: unknown;
51
- constructor(readonly root: string, readonly host: NativeAgentHost = "pi") {
52
- requireThat(host === "pi" || host === "dsh", "子会话所属宿主无效。");
53
- }
42
+ constructor(readonly root: string) {}
54
43
  check() { if (this.#failure) throw this.#failure; }
55
44
  fail(error: unknown) { this.#failure = error; }
56
45
  directory(id: string) { return join(this.root, fileId(id)); }
@@ -65,20 +54,15 @@ export class AgentFiles {
65
54
  catch (error) { this.fail(error); throw error; }
66
55
  requireThat(published, "子会话文件已存在。");
67
56
  }
68
- create(value: AgentDescriptor, run: AgentLaunch, acp?: AcpSessionReference) {
57
+ create(value: AgentDescriptor, run: AgentLaunch, acp: AcpSessionReference) {
69
58
  this.check();
70
- if (acp) acpReference(acp);
59
+ acpReference(acp);
71
60
  mkdirSync(this.root, { recursive: true, mode: 0o700 });
72
61
  mkdirSync(this.directory(value.agentId), { mode: 0o700 });
73
- for (const dir of ["inbox", "completions"]) privateDirectory(this.directory(value.agentId), dir);
62
+ for (const dir of ["inbox", "completions", "reports", "permissions", "elicitations"]) privateDirectory(this.directory(value.agentId), dir);
74
63
  this.write(value.agentId, "descriptor.json", value, descriptor, true);
75
64
  this.write(value.agentId, "launch.json", run, launch, true);
76
- if (acp) {
77
- for (const dir of ["reports", "permissions"]) privateDirectory(this.directory(value.agentId), dir);
78
- this.write(value.agentId, "acp-session.json", acp, acpReference, true);
79
- }
80
- else if (this.host === "pi") this.write(value.agentId, "session-ref.json", { file: null }, sessionRef, true);
81
- else this.write(value.agentId, "native-session.json", { host: "dsh", sessionId: value.agentId }, dshSessionRef, true);
65
+ this.write(value.agentId, "acp-session.json", acp, acpReference, true);
82
66
  }
83
67
  list() {
84
68
  if (!existsSync(this.root)) return [];
@@ -94,25 +78,27 @@ export class AgentFiles {
94
78
  return readdirSync(join(this.directory(id), "completions")).filter(n => n.endsWith(".json"))
95
79
  .map(n => this.read(id, "completions/" + n, cycle)).sort((a, b) => (a.finishedAt ?? 0) - (b.finishedAt ?? 0));
96
80
  }
97
- reference(id: string): AgentSessionReference {
98
- const acp = this.optional(id, "acp-session.json", acpReference);
99
- if (acp) return acp;
100
- if (this.host === "pi") return { host: "pi", file: this.session(id) };
101
- const ref = this.read(id, "native-session.json", dshSessionRef);
102
- requireThat(ref.sessionId === id, "dsh 原生会话身份不匹配。");
103
- return ref;
81
+ /** Permission requests of a generation that have no reply yet. */
82
+ pendingPermissions(id: string, generation: string) {
83
+ const dir = join(this.directory(id), "permissions");
84
+ if (!existsSync(dir)) return [];
85
+ const names = readdirSync(dir);
86
+ return names.filter(n => n.endsWith(".json") && !n.endsWith("-reply.json") && !names.includes(n.slice(0, -5) + "-reply.json"))
87
+ .map(n => this.read(id, "permissions/" + n, acpPermission)).filter(item => item.generation === generation);
88
+ }
89
+ /** Elicitation requests (forms, choices, text inputs, URL confirmations) of a generation that have no reply yet. */
90
+ pendingElicitations(id: string, generation: string) {
91
+ const dir = join(this.directory(id), "elicitations");
92
+ if (!existsSync(dir)) return [];
93
+ const names = readdirSync(dir);
94
+ return names.filter(n => n.endsWith(".json") && !n.endsWith("-reply.json") && !names.includes(n.slice(0, -5) + "-reply.json"))
95
+ .map(n => this.read(id, "elicitations/" + n, acpElicitation)).filter(item => item.generation === generation);
104
96
  }
105
- session(id: string): string | null {
106
- requireThat(this.host === "pi", "该宿主不使用 Pi 会话文件引用。");
107
- const ref = this.optional(id, "session-ref.json", sessionRef);
108
- requireThat(ref, "缺少原生会话引用;不导入旧记录,请重新 start。");
109
- return ref.file;
97
+ ensureSubdirectory(id: string, name: string) {
98
+ privateDirectory(this.directory(id), name);
110
99
  }
111
- /** The child fixes the native path before accepting input; never reset it to null. */
112
- bindSession(id: string, file: string) {
113
- const previous = this.session(id);
114
- requireThat(previous === null || previous === file, "子会话文件引用不匹配。");
115
- if (previous === null) this.write(id, "session-ref.json", { file }, sessionRef);
100
+ reference(id: string): AgentSessionReference {
101
+ return this.read(id, "acp-session.json", acpReference);
116
102
  }
117
103
  /** Short controller edits are serialized; an abandoned lock fails closed. */
118
104
  control<T>(work: () => T): T {