personal-bot 0.2.20 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (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 +93 -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 +39 -7
  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 +42 -6
  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
@@ -0,0 +1,2715 @@
1
+ // src/mcp.ts
2
+ import { realpathSync as realpathSync4 } from "node:fs";
3
+ import { pathToFileURL as pathToFileURL2 } from "node:url";
4
+
5
+ // src/extension/mcp-workers.ts
6
+ import { randomUUID as randomUUID4 } from "node:crypto";
7
+ import { realpath, stat } from "node:fs/promises";
8
+ import { homedir } from "node:os";
9
+ import { isAbsolute as isAbsolute3, join as join10 } from "node:path";
10
+ import { setTimeout as delay3 } from "node:timers/promises";
11
+
12
+ // src/common/json.ts
13
+ function object(value) {
14
+ return value !== null && typeof value === "object" && !Array.isArray(value);
15
+ }
16
+ function canonical(value) {
17
+ if (value === null || typeof value === "boolean" || typeof value === "string") return JSON.stringify(value);
18
+ if (typeof value === "number" && Number.isFinite(value)) return JSON.stringify(value);
19
+ if (Array.isArray(value)) return "[" + value.map(canonical).join(",") + "]";
20
+ if (object(value) && (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null)) {
21
+ return "{" + Object.keys(value).sort().map((key) => JSON.stringify(key) + ":" + canonical(value[key])).join(",") + "}";
22
+ }
23
+ throw new Error("\u9700\u8981\u6709\u9650\u3001\u53EF\u5E8F\u5217\u5316\u7684 JSON \u503C\u3002");
24
+ }
25
+
26
+ // src/common/validation.ts
27
+ var acpBackendPattern = /^[a-z0-9][a-z0-9-]{0,63}$/;
28
+ function isAcpBackend(value) {
29
+ return typeof value === "string" && acpBackendPattern.test(value);
30
+ }
31
+ function requireThat(condition, message2) {
32
+ if (!condition) throw new Error(message2);
33
+ }
34
+
35
+ // src/common/version.ts
36
+ import { readFileSync } from "node:fs";
37
+ function releaseLine(version) {
38
+ const parts = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/.exec(version);
39
+ requireThat(parts, "pbot \u53D1\u5E03\u7248\u672C\u5FC5\u987B\u4F7F\u7528 MAJOR.MINOR.PATCH\u3002");
40
+ return parts[1] === "0" ? `0.${parts[2]}` : parts[1];
41
+ }
42
+ var manifest = JSON.parse(readFileSync(new URL("../../package.json", import.meta.url), "utf8"));
43
+ requireThat(object(manifest) && typeof manifest.version === "string", "pbot \u5305\u7F3A\u5C11\u53D1\u5E03\u7248\u672C\u3002");
44
+ var packageVersion = manifest.version;
45
+ releaseLine(packageVersion);
46
+
47
+ // src/integrations/acp/agents.ts
48
+ import { fork, spawnSync } from "node:child_process";
49
+ import { existsSync as existsSync2 } from "node:fs";
50
+ import { join as join7, resolve as resolve3 } from "node:path";
51
+ import { setTimeout as delay } from "node:timers/promises";
52
+
53
+ // src/storage/agent-files.ts
54
+ import { existsSync, mkdirSync as mkdirSync2, readdirSync, rmSync } from "node:fs";
55
+ import { join as join3 } from "node:path";
56
+ import { randomUUID as randomUUID2 } from "node:crypto";
57
+
58
+ // src/storage/atomic-json.ts
59
+ import {
60
+ constants,
61
+ closeSync,
62
+ fstatSync,
63
+ fsyncSync,
64
+ linkSync,
65
+ lstatSync,
66
+ openSync,
67
+ readFileSync as readFileSync2,
68
+ realpathSync,
69
+ renameSync,
70
+ unlinkSync,
71
+ writeFileSync
72
+ } from "node:fs";
73
+ import { dirname, join } from "node:path";
74
+ import { randomUUID } from "node:crypto";
75
+ function internalPath(directory, relative) {
76
+ const parts = relative.split("/");
77
+ requireThat(parts.every((part) => part && part !== "." && part !== ".." && !/[\\\x00-\x1f]/.test(part)), "\u5185\u90E8\u72B6\u6001\u8DEF\u5F84\u65E0\u6548\u3002");
78
+ const info = lstatSync(directory);
79
+ requireThat(info.isDirectory() && !info.isSymbolicLink(), "\u5185\u90E8\u72B6\u6001\u5FC5\u987B\u4F7F\u7528\u666E\u901A\u76EE\u5F55\u3002");
80
+ let path = realpathSync(directory);
81
+ for (const [index, part] of parts.entries()) {
82
+ path = join(path, part);
83
+ try {
84
+ const info2 = lstatSync(path);
85
+ requireThat(!info2.isSymbolicLink() && (index === parts.length - 1 ? info2.isFile() : info2.isDirectory()), "\u5185\u90E8\u72B6\u6001\u4E0D\u80FD\u4F7F\u7528\u7B26\u53F7\u94FE\u63A5\u6216\u7279\u6B8A\u6587\u4EF6\u3002");
86
+ } catch (error) {
87
+ if (error.code !== "ENOENT" || index !== parts.length - 1) throw error;
88
+ }
89
+ }
90
+ return path;
91
+ }
92
+ function syncDirectory(directory) {
93
+ const fd = openSync(directory, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW);
94
+ try {
95
+ fsyncSync(fd);
96
+ } finally {
97
+ closeSync(fd);
98
+ }
99
+ }
100
+ function readJsonFile(directory, relative, validate) {
101
+ const path = internalPath(directory, relative);
102
+ const fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
103
+ try {
104
+ requireThat(fstatSync(fd).isFile(), "\u5185\u90E8\u72B6\u6001\u5FC5\u987B\u662F\u666E\u901A\u6587\u4EF6\u3002");
105
+ let value;
106
+ try {
107
+ value = JSON.parse(readFileSync2(fd, "utf8"));
108
+ } catch (error) {
109
+ throw new Error("\u5185\u90E8 JSON \u6587\u4EF6\u4E0D\u53EF\u8BFB\u53D6\uFF1A" + relative, { cause: error });
110
+ }
111
+ return validate(value);
112
+ } finally {
113
+ closeSync(fd);
114
+ }
115
+ }
116
+ function writeJsonFile(directory, relative, value, validate, createOnly = false) {
117
+ const validated = validate(value);
118
+ const expected = canonical(validated);
119
+ const content = JSON.stringify(validated, null, 2) + "\n";
120
+ requireThat(canonical(JSON.parse(content)) === expected, "JSON \u5E8F\u5217\u5316\u4E0D\u80FD\u6539\u53D8\u72B6\u6001\u503C\u3002");
121
+ const path = internalPath(directory, relative), parent = dirname(path);
122
+ const temporary = join(parent, `.tmp-${randomUUID()}`);
123
+ const fd = openSync(temporary, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 384);
124
+ try {
125
+ try {
126
+ writeFileSync(fd, content, "utf8");
127
+ fsyncSync(fd);
128
+ } finally {
129
+ closeSync(fd);
130
+ }
131
+ requireThat(internalPath(directory, relative) === path, "\u5185\u90E8\u72B6\u6001\u8DEF\u5F84\u5DF2\u53D8\u5316\u3002");
132
+ if (createOnly) {
133
+ try {
134
+ linkSync(temporary, path);
135
+ } catch (error) {
136
+ if (error.code === "EEXIST") return false;
137
+ throw error;
138
+ }
139
+ } else renameSync(temporary, path);
140
+ syncDirectory(parent);
141
+ return true;
142
+ } finally {
143
+ try {
144
+ unlinkSync(temporary);
145
+ } catch (error) {
146
+ if (error.code !== "ENOENT") throw error;
147
+ }
148
+ }
149
+ }
150
+
151
+ // src/storage/file-access.ts
152
+ import { lstatSync as lstatSync2, mkdirSync } from "node:fs";
153
+ import { join as join2 } from "node:path";
154
+ function fileId(id) {
155
+ requireThat(/^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/.test(id), "\u5185\u90E8\u8BB0\u5F55 ID \u65E0\u6548\u3002");
156
+ return id;
157
+ }
158
+ function privateDirectory(root, relative) {
159
+ const parts = relative.split("/");
160
+ let parent = root;
161
+ for (const part of parts) {
162
+ fileId(part);
163
+ const path = join2(parent, part);
164
+ try {
165
+ mkdirSync(path, { mode: 448 });
166
+ syncDirectory(parent);
167
+ } catch (error) {
168
+ if (error.code !== "EEXIST") throw error;
169
+ }
170
+ requireThat(lstatSync2(path).isDirectory() && !lstatSync2(path).isSymbolicLink(), "\u5185\u90E8\u72B6\u6001\u76EE\u5F55\u65E0\u6548\u3002");
171
+ parent = path;
172
+ }
173
+ }
174
+
175
+ // src/storage/acp-files.ts
176
+ import { isAbsolute } from "node:path";
177
+ var text = (value) => typeof value === "string" && value.length > 0 && !value.includes("\0");
178
+ function acpReference(value) {
179
+ requireThat(object(value) && value.host === "acp" && isAcpBackend(value.backend) && text(value.command) && isAbsolute(value.command) && Array.isArray(value.args) && value.args.every((arg) => typeof arg === "string" && !arg.includes("\0")) && (value.sessionId === null || text(value.sessionId)), "ACP \u4F1A\u8BDD\u5F15\u7528\u65E0\u6548\u3002");
180
+ if (value.env !== void 0) {
181
+ requireThat(object(value.env) && Object.entries(value.env).every(([k, v]) => text(k) && typeof v === "string" && !v.includes("\0")), "ACP \u73AF\u5883\u53D8\u91CF\u914D\u7F6E\u65E0\u6548\u3002");
182
+ }
183
+ requireThat(value.permission === void 0 || ["ask", "allow", "deny"].includes(String(value.permission)), "ACP \u6743\u9650\u7B56\u7565\u65E0\u6548\u3002");
184
+ const capabilities = value.capabilities;
185
+ if (capabilities !== void 0) requireThat(object(capabilities) && ["resume", "load", "close"].every((key) => typeof capabilities[key] === "boolean"), "ACP \u4F1A\u8BDD\u80FD\u529B\u65E0\u6548\u3002");
186
+ return value;
187
+ }
188
+ function acpModelState(value) {
189
+ requireThat(object(value) && text(value.generation) && ["provider", "model", "resolvedModel", "thinking"].every((key) => value[key] === void 0 || text(value[key])), "ACP \u6A21\u578B\u9009\u62E9\u65E0\u6548\u3002");
190
+ return value;
191
+ }
192
+ function acpProcess(value) {
193
+ requireThat(object(value) && text(value.generation) && Number.isSafeInteger(value.pid) && Number(value.pid) > 1 && typeof value.startedAt === "number" && Number.isFinite(value.startedAt), "ACP \u8FDB\u7A0B\u8BB0\u5F55\u65E0\u6548\u3002");
194
+ return value;
195
+ }
196
+ function acpInput(value) {
197
+ requireThat(object(value) && text(value.generation) && text(value.requestId), "ACP \u8F93\u5165\u5173\u8054\u65E0\u6548\u3002");
198
+ fileId(value.requestId);
199
+ return value;
200
+ }
201
+ function acpReport(value) {
202
+ requireThat(object(value) && text(value.generation) && text(value.cycleId) && typeof value.text === "string", "ACP \u5468\u671F\u62A5\u544A\u65E0\u6548\u3002");
203
+ fileId(value.cycleId);
204
+ return value;
205
+ }
206
+ function acpPermission(value) {
207
+ acpInput(value);
208
+ requireThat(object(value) && typeof value.description === "string" && Array.isArray(value.options) && value.options.every((option) => object(option) && text(option.optionId) && text(option.name) && ["allow_once", "allow_always", "reject_once", "reject_always"].includes(String(option.kind))), "ACP \u786E\u8BA4\u8BF7\u6C42\u65E0\u6548\u3002");
209
+ return value;
210
+ }
211
+ function acpPermissionReply(value) {
212
+ acpInput(value);
213
+ requireThat(object(value) && (value.optionId === null || text(value.optionId)), "ACP \u786E\u8BA4\u7B54\u590D\u65E0\u6548\u3002");
214
+ return value;
215
+ }
216
+ function elicitationValue(value) {
217
+ return typeof value === "string" || typeof value === "number" && Number.isFinite(value) || typeof value === "boolean" || Array.isArray(value) && value.every((item) => typeof item === "string");
218
+ }
219
+ function acpElicitation(value) {
220
+ acpInput(value);
221
+ requireThat(object(value) && (value.mode === "form" || value.mode === "url") && typeof value.message === "string", "ACP \u4EA4\u4E92\u8BF7\u6C42\u65E0\u6548\u3002");
222
+ if (value.mode === "form") {
223
+ requireThat(object(value.schema) && value.url === void 0, "ACP \u8868\u5355\u4EA4\u4E92\u8BF7\u6C42\u7F3A\u5C11\u6709\u6548 schema\u3002");
224
+ } else {
225
+ requireThat(text(value.url) && value.schema === void 0, "ACP URL \u4EA4\u4E92\u8BF7\u6C42\u7F3A\u5C11\u6709\u6548 url\u3002");
226
+ }
227
+ return value;
228
+ }
229
+ function acpElicitationReply(value) {
230
+ acpInput(value);
231
+ requireThat(object(value) && ["accept", "decline", "cancel"].includes(String(value.action)), "ACP \u4EA4\u4E92\u7B54\u590D\u65E0\u6548\u3002");
232
+ if (value.content !== void 0) {
233
+ requireThat(value.action === "accept" && object(value.content) && Object.values(value.content).every(elicitationValue), "ACP \u8868\u5355\u7B54\u590D content \u65E0\u6548\u3002");
234
+ }
235
+ return value;
236
+ }
237
+
238
+ // src/storage/agent-files.ts
239
+ var text2 = (v) => typeof v === "string" && v.length > 0;
240
+ var number = (v) => typeof v === "number" && Number.isFinite(v);
241
+ function descriptor(v) {
242
+ requireThat(object(v) && text2(v.agentId) && text2(v.release) && text2(v.workspace) && text2(v.cwd) && text2(v.parentSessionId) && (v.parentLeaf === null || text2(v.parentLeaf)) && number(v.createdAt) && object(v.options), "\u5B50\u4F1A\u8BDD\u8EAB\u4EFD\u65E0\u6548\u3002");
243
+ fileId(v.agentId);
244
+ return v;
245
+ }
246
+ function launch(v) {
247
+ requireThat(object(v) && text2(v.generation) && text2(v.name) && Number.isSafeInteger(v.sequence) && typeof v.stop === "boolean" && number(v.startedAt), "\u5B50\u4F1A\u8BDD\u542F\u52A8\u72B6\u6001\u65E0\u6548\u3002");
248
+ return v;
249
+ }
250
+ function message(v) {
251
+ requireThat(object(v) && text2(v.requestId) && text2(v.generation) && Number.isSafeInteger(v.sequence) && typeof v.message === "string" && ["steer", "followUp"].includes(String(v.delivery)) && Array.isArray(v.files) && v.files.every(text2), "\u5B50\u4F1A\u8BDD\u6D88\u606F\u65E0\u6548\u3002");
252
+ return v;
253
+ }
254
+ function cycle(v) {
255
+ requireThat(object(v) && text2(v.cycleId) && text2(v.generation) && number(v.startedAt) && ["running", "completed", "failed", "cancelled", "interrupted"].includes(String(v.state)) && (v.leaf === null || text2(v.leaf)) && Array.isArray(v.requestIds) && v.requestIds.every(text2) && ["parent", "interactive", "mixed"].includes(String(v.source)) && (v.finishedAt === void 0 || number(v.finishedAt)), "\u5B50\u4F1A\u8BDD\u5468\u671F\u65E0\u6548\u3002");
256
+ return v;
257
+ }
258
+ function status(v) {
259
+ requireThat(object(v) && text2(v.generation) && ["starting", "busy", "idle", "stopping", "stopped", "error"].includes(String(v.state)) && typeof v.activity === "string" && number(v.updatedAt), "\u5B50\u4F1A\u8BDD\u72B6\u6001\u65E0\u6548\u3002");
260
+ if (v.cycle) cycle(v.cycle);
261
+ return v;
262
+ }
263
+ var AgentFiles = class {
264
+ constructor(root) {
265
+ this.root = root;
266
+ }
267
+ #failure;
268
+ check() {
269
+ if (this.#failure) throw this.#failure;
270
+ }
271
+ fail(error) {
272
+ this.#failure = error;
273
+ }
274
+ directory(id) {
275
+ return join3(this.root, fileId(id));
276
+ }
277
+ read(id, path, parse) {
278
+ return readJsonFile(this.directory(id), path, parse);
279
+ }
280
+ optional(id, path, parse) {
281
+ try {
282
+ return this.read(id, path, parse);
283
+ } catch (error) {
284
+ if (error.code === "ENOENT") return void 0;
285
+ throw error;
286
+ }
287
+ }
288
+ write(id, path, value, parse, create = false) {
289
+ this.check();
290
+ parse(value);
291
+ let published;
292
+ try {
293
+ published = writeJsonFile(this.directory(id), path, value, parse, create);
294
+ } catch (error) {
295
+ this.fail(error);
296
+ throw error;
297
+ }
298
+ requireThat(published, "\u5B50\u4F1A\u8BDD\u6587\u4EF6\u5DF2\u5B58\u5728\u3002");
299
+ }
300
+ create(value, run, acp) {
301
+ this.check();
302
+ acpReference(acp);
303
+ mkdirSync2(this.root, { recursive: true, mode: 448 });
304
+ mkdirSync2(this.directory(value.agentId), { mode: 448 });
305
+ for (const dir of ["inbox", "completions", "reports", "permissions", "elicitations"]) privateDirectory(this.directory(value.agentId), dir);
306
+ this.write(value.agentId, "descriptor.json", value, descriptor, true);
307
+ this.write(value.agentId, "launch.json", run, launch, true);
308
+ this.write(value.agentId, "acp-session.json", acp, acpReference, true);
309
+ }
310
+ list() {
311
+ if (!existsSync(this.root)) return [];
312
+ return readdirSync(this.root, { withFileTypes: true }).filter((e) => e.isDirectory() && !e.name.startsWith(".")).flatMap((e) => {
313
+ const d = this.optional(e.name, "descriptor.json", descriptor);
314
+ return d ? [d] : [];
315
+ });
316
+ }
317
+ messages(id) {
318
+ return readdirSync(join3(this.directory(id), "inbox")).filter((n) => n.endsWith(".json")).map((n) => this.read(id, "inbox/" + n, message)).sort((a, b) => a.sequence - b.sequence);
319
+ }
320
+ completions(id) {
321
+ return readdirSync(join3(this.directory(id), "completions")).filter((n) => n.endsWith(".json")).map((n) => this.read(id, "completions/" + n, cycle)).sort((a, b) => (a.finishedAt ?? 0) - (b.finishedAt ?? 0));
322
+ }
323
+ /** Permission requests of a generation that have no reply yet. */
324
+ pendingPermissions(id, generation) {
325
+ const dir = join3(this.directory(id), "permissions");
326
+ if (!existsSync(dir)) return [];
327
+ const names = readdirSync(dir);
328
+ return names.filter((n) => n.endsWith(".json") && !n.endsWith("-reply.json") && !names.includes(n.slice(0, -5) + "-reply.json")).map((n) => this.read(id, "permissions/" + n, acpPermission)).filter((item) => item.generation === generation);
329
+ }
330
+ /** Elicitation requests (forms, choices, text inputs, URL confirmations) of a generation that have no reply yet. */
331
+ pendingElicitations(id, generation) {
332
+ const dir = join3(this.directory(id), "elicitations");
333
+ if (!existsSync(dir)) return [];
334
+ const names = readdirSync(dir);
335
+ return names.filter((n) => n.endsWith(".json") && !n.endsWith("-reply.json") && !names.includes(n.slice(0, -5) + "-reply.json")).map((n) => this.read(id, "elicitations/" + n, acpElicitation)).filter((item) => item.generation === generation);
336
+ }
337
+ ensureSubdirectory(id, name) {
338
+ privateDirectory(this.directory(id), name);
339
+ }
340
+ reference(id) {
341
+ return this.read(id, "acp-session.json", acpReference);
342
+ }
343
+ /** Short controller edits are serialized; an abandoned lock fails closed. */
344
+ control(work) {
345
+ this.check();
346
+ mkdirSync2(this.root, { recursive: true, mode: 448 });
347
+ const path = join3(this.root, ".control");
348
+ try {
349
+ mkdirSync2(path, { mode: 448 });
350
+ } catch (error) {
351
+ if (error.code !== "EEXIST") throw error;
352
+ throw Object.assign(new Error("\u5B50\u4F1A\u8BDD\u63A7\u5236\u6B63\u5728\u8FDB\u884C\uFF1B\u7A0D\u540E\u91CD\u8BD5\u3002\u5D29\u6E83\u9057\u7559\u7684 .control \u9700\u505C\u6B62\u76F8\u5173\u6267\u884C\u5B9E\u4F8B\u540E\u624B\u52A8\u79FB\u9664\u3002"), { code: "PBOT_CONTROL_BUSY" });
353
+ }
354
+ try {
355
+ return work();
356
+ } finally {
357
+ rmSync(path, { recursive: true });
358
+ }
359
+ }
360
+ enqueue(id, text3, delivery, files = [], requestId = randomUUID2()) {
361
+ fileId(requestId);
362
+ const run = this.read(id, "launch.json", launch), previous = this.optional(id, "inbox/" + requestId + ".json", message);
363
+ if (previous) {
364
+ requireThat(previous.generation === run.generation && previous.message === text3 && previous.delivery === delivery && canonical(previous.files) === canonical(files), "\u8BF7\u6C42 ID \u5DF2\u88AB\u4E0D\u540C\u8F93\u5165\u4F7F\u7528\u3002");
365
+ return previous;
366
+ }
367
+ run.sequence++;
368
+ this.write(id, "launch.json", run, launch);
369
+ const value = { requestId, generation: run.generation, sequence: run.sequence, message: text3, delivery, files };
370
+ this.write(id, "inbox/" + value.requestId + ".json", value, message, true);
371
+ return value;
372
+ }
373
+ };
374
+
375
+ // src/common/paths.ts
376
+ import { fileURLToPath } from "node:url";
377
+ var resourceRoot = fileURLToPath(new URL("../../resources/", import.meta.url));
378
+
379
+ // src/integrations/acp/executable.ts
380
+ import { accessSync, constants as constants2, realpathSync as realpathSync2, statSync } from "node:fs";
381
+ import { delimiter, isAbsolute as isAbsolute2, resolve } from "node:path";
382
+ function findAcpExecutable(command) {
383
+ const candidates = isAbsolute2(command) ? [command] : (process.env.PATH ?? "").split(delimiter).filter(Boolean).map((directory) => resolve(directory, command));
384
+ for (const candidate of candidates) {
385
+ try {
386
+ accessSync(candidate, constants2.X_OK);
387
+ if (statSync(candidate).isFile()) return realpathSync2(candidate);
388
+ } catch (error) {
389
+ if (!["ENOENT", "ENOTDIR", "EACCES", "EPERM"].includes(error.code ?? "")) throw error;
390
+ }
391
+ }
392
+ return void 0;
393
+ }
394
+ function acpExecutable(command, backend, harness) {
395
+ const found = findAcpExecutable(command);
396
+ if (found) return found;
397
+ const nativePi = backend === "pi" && command === "pi";
398
+ const targetCommand = harness?.defaultCommand?.command ?? command;
399
+ const targetArgs = harness?.defaultCommand?.args ?? [];
400
+ const install = nativePi ? "npm install -g @earendil-works/pi-coding-agent" : harness?.installHint ?? `\u8BF7\u786E\u8BA4 ${backend} \u5BF9\u5E94\u7684 ACP \u53EF\u6267\u884C\u6587\u4EF6\u5DF2\u5B89\u88C5\u3002`;
401
+ const configured = JSON.stringify({ command: "/absolute/path/to/" + targetCommand, args: targetArgs });
402
+ const pathHint = nativePi ? "Pi \u5DF2\u5B89\u88C5\u4F46 PATH \u4E0D\u53EF\u89C1\u65F6\uFF0C\u542F\u52A8\u4E3B\u5BBF\u4E3B\u524D\u5C06 PI_ACP_PI_COMMAND \u8BBE\u7F6E\u4E3A pi \u7684\u7EDD\u5BF9\u8DEF\u5F84\u3002" : "\u5DF2\u5B89\u88C5\u4F46 PATH \u4E0D\u53EF\u89C1\u65F6\uFF0C\u5728 .pbot/config.json \u8BBE\u7F6E acp." + backend + "\uFF1A" + configured + "\uFF0Ccommand \u4F7F\u7528\u5B9E\u9645\u7EDD\u5BF9\u8DEF\u5F84\u3002";
403
+ throw new Error([
404
+ "\u672A\u627E\u5230\u5B50\u4EE3\u7406\u7A0B\u5E8F\uFF1A" + command + "\u3002",
405
+ "\u5B89\u88C5\u63D0\u793A\uFF1A" + install,
406
+ ...harness?.configureHint ? [harness.configureHint] : [],
407
+ "\u68C0\u67E5\u5B89\u88C5\u8DEF\u5F84\uFF1Acommand -v " + (nativePi ? "pi" : targetCommand) + (!nativePi && backend === "pi" ? "\uFF1B\u53E6\u7528 command -v pi \u68C0\u67E5 Pi\u3002" : "\u3002"),
408
+ pathHint,
409
+ "\u5B89\u88C5\u540E\u91CD\u8BD5\u539F start \u8BF7\u6C42\uFF1BPATH \u53D8\u5316\u65F6\u91CD\u542F\u4E3B\u5BBF\u4E3B\u3002\u914D\u7F6E\u4FEE\u6539\u540E\uFF0CPi \u6267\u884C /reload\uFF0Cdsh \u91CD\u542F\u5BBF\u4E3B\u3002"
410
+ ].join("\n"));
411
+ }
412
+
413
+ // src/integrations/acp/claude.ts
414
+ import { createRequire } from "node:module";
415
+ import { pathToFileURL } from "node:url";
416
+ import { basename, join as join4, resolve as resolve2 } from "node:path";
417
+ var levels = ["low", "medium", "high", "xhigh", "max"];
418
+ async function claudeOptions(command, cwd, supplied, includeSkills = true) {
419
+ const normalized = supplied?.trim().toLowerCase().replace(/[^a-z0-9]+/g, "");
420
+ const requested = normalized === "extrahigh" ? "xhigh" : normalized;
421
+ const script = command.args[0];
422
+ const anchor = ["node", "node.exe"].includes(basename(command.command)) && script && !script.startsWith("-") ? resolve2(cwd, script) : command.command;
423
+ const require2 = createRequire(pathToFileURL(anchor));
424
+ const sdk = await import(pathToFileURL(require2.resolve("@anthropic-ai/claude-agent-sdk")).href);
425
+ requireThat(object(sdk) && typeof sdk.resolveSettings === "function", "Claude ACP \u9700\u8981\u63D0\u4F9B resolveSettings \u7684\u539F\u751F SDK\u3002");
426
+ const resolved = await sdk.resolveSettings({ cwd });
427
+ requireThat(object(resolved) && object(resolved.effective), "Claude \u539F\u751F\u8BBE\u7F6E\u89E3\u6790\u5931\u8D25\u3002");
428
+ const environment = object(resolved.effective.env) ? resolved.effective.env : {};
429
+ const configured = environment.CLAUDE_CODE_EFFORT_LEVEL ?? process.env.CLAUDE_CODE_EFFORT_LEVEL;
430
+ const explicit = requested !== void 0 && requested !== "default";
431
+ requireThat(!explicit || levels.includes(requested), "Claude \u601D\u8003\u7B49\u7EA7\u4E0D\u53EF\u7528\uFF1A" + requested + "\uFF1B\u53EF\u7528\u503C\uFF1Adefault, " + levels.join(", "));
432
+ const effort = explicit ? requested : typeof configured === "string" && levels.includes(configured) ? configured : void 0;
433
+ const thinking = effort ?? (configured === "unset" ? "unset" : void 0);
434
+ return {
435
+ ...thinking ? { thinking } : {},
436
+ options: {
437
+ ...includeSkills ? { plugins: [{ type: "local", path: join4(resourceRoot, "skills") }] } : {},
438
+ ...effort ? { effort } : {},
439
+ // SDK effort alone loses to CLAUDE_CODE_EFFORT_LEVEL. A flag-tier env entry
440
+ // applies the explicit choice to this invocation and preserves other settings.
441
+ ...explicit ? { settings: { env: { CLAUDE_CODE_EFFORT_LEVEL: requested } } } : {}
442
+ }
443
+ };
444
+ }
445
+
446
+ // src/integrations/acp/harnesses/generic.ts
447
+ var piOnlyOptions = ["noExtensions", "noPromptTemplates", "noContextFiles"];
448
+ function filterStandardAcpOptions(options) {
449
+ const result = { ...options };
450
+ for (const key of piOnlyOptions) delete result[key];
451
+ delete result.noSkills;
452
+ delete result.tools;
453
+ return result;
454
+ }
455
+ function validateStandardAcpOptions(backend, options) {
456
+ for (const key of piOnlyOptions) {
457
+ requireThat(options[key] === void 0, backend + " \u5B50\u4EE3\u7406\u4E0D\u652F\u6301\u542F\u52A8\u9009\u9879\uFF1A" + key);
458
+ }
459
+ }
460
+ function defaultPrepareLaunch(context) {
461
+ return {
462
+ command: { ...context.reference, args: [...context.reference.args] },
463
+ env: { ...context.env, ...context.reference.env ?? {} }
464
+ };
465
+ }
466
+ function createGenericAcpHarness(id, preset = {}) {
467
+ return {
468
+ id,
469
+ ...preset.label ? { label: preset.label } : {},
470
+ ...preset.aliases ? { aliases: preset.aliases } : {},
471
+ ...preset.defaultCommand ? { defaultCommand: preset.defaultCommand } : {},
472
+ ...preset.installHint ? { installHint: preset.installHint } : {},
473
+ ...preset.configureHint ? { configureHint: preset.configureHint } : {},
474
+ ...preset.nativeWorkspaceSkills !== void 0 ? { nativeWorkspaceSkills: preset.nativeWorkspaceSkills } : {},
475
+ filterStartOptions: filterStandardAcpOptions,
476
+ validateStartOptions: (options) => validateStandardAcpOptions(id, options),
477
+ prepareLaunch: defaultPrepareLaunch,
478
+ parseModelValue: (value) => ({ model: value })
479
+ };
480
+ }
481
+
482
+ // src/integrations/acp/harnesses/claude.ts
483
+ var claudeAcpHarness = {
484
+ id: "claude",
485
+ label: "Claude Code",
486
+ aliases: ["claude-code", "claudecode"],
487
+ defaultCommand: { command: "claude-agent-acp", args: [] },
488
+ installHint: "npm install -g @agentclientprotocol/claude-agent-acp",
489
+ configureHint: "\u5728 Claude Code \u4E2D\u5B8C\u6210\u767B\u5F55\u6216 API \u914D\u7F6E\uFF0C\u5E76\u8BBE\u7F6E\u9ED8\u8BA4\u6A21\u578B\u3002",
490
+ requireSystemPrompt: true,
491
+ nativeWorkspaceSkills: false,
492
+ customNotificationMethod: "_claude/sdkMessage",
493
+ filterStartOptions(options) {
494
+ const filtered = filterStandardAcpOptions(options);
495
+ delete filtered.provider;
496
+ return filtered;
497
+ },
498
+ validateStartOptions(options) {
499
+ validateStandardAcpOptions("claude", options);
500
+ requireThat(options.noSkills === void 0 && options.tools === void 0, "Claude \u5B50\u4EE3\u7406\u7684\u6280\u80FD\u548C\u5DE5\u5177\u901A\u8FC7 Claude \u539F\u751F\u914D\u7F6E\u9009\u62E9\u3002");
501
+ requireThat(options.provider === void 0, "Claude \u5B50\u4EE3\u7406\u4F7F\u7528\u539F\u751F\u63D0\u4F9B\u65B9\u914D\u7F6E\uFF1B\u8BF7\u4EC5\u6307\u5B9A\u76EE\u6807 model\u3002");
502
+ },
503
+ async prepareLaunch(context) {
504
+ const base = defaultPrepareLaunch(context);
505
+ const claude = await claudeOptions(base.command, context.cwd, context.options.thinking, context.features?.skills !== false);
506
+ return {
507
+ ...base,
508
+ ...claude.thinking ? { defaultThinking: claude.thinking } : {},
509
+ sessionMeta: {
510
+ claudeCode: {
511
+ options: { ...claude.options, disallowedTools: ["Agent", "Task"] },
512
+ emitRawSDKMessages: [{ type: "system", subtype: "init" }]
513
+ }
514
+ }
515
+ };
516
+ },
517
+ parseModelValue: (value) => ({ model: value }),
518
+ parseCustomNotification(params, sessionId) {
519
+ if (!object(params) || params.sessionId !== sessionId) return void 0;
520
+ const message2 = params.message;
521
+ if (!object(message2) || message2.type !== "system" || message2.subtype !== "init" || typeof message2.model !== "string" || !message2.model) {
522
+ return void 0;
523
+ }
524
+ return { resolvedModel: message2.model };
525
+ }
526
+ };
527
+
528
+ // src/integrations/acp/harnesses/dsh.ts
529
+ import { writeFile } from "node:fs/promises";
530
+ import { join as join5 } from "node:path";
531
+ var dshAcpHarness = {
532
+ id: "dsh",
533
+ label: "DeepSeek dsh",
534
+ defaultCommand: { command: "dsh", args: ["--profile", "acp"] },
535
+ installHint: "npm install -g @deepseek-ai/dsh@latest",
536
+ configureHint: "\u6309 dsh \u539F\u751F\u65B9\u5F0F\u914D\u7F6E\u76EE\u6807 profile \u7684\u6A21\u578B\u4E0E\u8BA4\u8BC1\u3002",
537
+ exactAnswer: true,
538
+ eagerSessionId: true,
539
+ nativeWorkspaceSkills: true,
540
+ nativeWorkspaceMcp: true,
541
+ filterStartOptions: filterStandardAcpOptions,
542
+ validateStartOptions: (options) => validateStandardAcpOptions("dsh", options),
543
+ async prepareLaunch(context) {
544
+ const base = defaultPrepareLaunch(context);
545
+ const patch = join5(context.directory, "acp-dsh-patch.json");
546
+ await writeFile(
547
+ patch,
548
+ JSON.stringify([{ insert: [{ id: "pbot-acp-member", name: join5(context.packageRoot, "lib/extension/dsh/acp-member.js") }] }]) + "\n",
549
+ { mode: 384 }
550
+ );
551
+ return {
552
+ ...base,
553
+ command: { ...base.command, args: [...base.command.args, "--patch", patch] }
554
+ };
555
+ },
556
+ parseModelValue(value) {
557
+ try {
558
+ const parts = JSON.parse(value);
559
+ if (Array.isArray(parts) && parts.length === 2 && parts.every((part) => typeof part === "string" && part.length > 0)) {
560
+ return { provider: parts[0], model: parts[1] };
561
+ }
562
+ } catch {
563
+ }
564
+ return { model: value };
565
+ }
566
+ };
567
+
568
+ // src/integrations/acp/harnesses/pi.ts
569
+ import { join as join6 } from "node:path";
570
+ var piAcpHarness = {
571
+ id: "pi",
572
+ label: "Pi",
573
+ defaultCommand: { command: "pi-acp", args: [] },
574
+ installHint: "npm install -g pi-acp",
575
+ configureHint: "Pi \u4E5F\u9700\u5DF2\u5B89\u88C5\uFF1B\u8FD0\u884C pi \u5B8C\u6210\u767B\u5F55\u548C\u9ED8\u8BA4\u6A21\u578B\u914D\u7F6E\u3002",
576
+ exactAnswer: true,
577
+ nativeWorkspaceSkills: true,
578
+ nativeWorkspaceMcp: true,
579
+ filterStartOptions: (options) => ({ ...options }),
580
+ prepareLaunch(context) {
581
+ const base = defaultPrepareLaunch(context);
582
+ return {
583
+ ...base,
584
+ env: {
585
+ ...base.env,
586
+ PBOT_ACP_PI_COMMAND: process.env.PI_ACP_PI_COMMAND ?? acpExecutable("pi", "pi"),
587
+ PI_ACP_PI_COMMAND: join6(context.packageRoot, "bin/pbot-pi-acp.mjs")
588
+ }
589
+ };
590
+ },
591
+ parseModelValue(value) {
592
+ const separator = value.indexOf("/");
593
+ if (separator > 0) return { provider: value.slice(0, separator), model: value.slice(separator + 1) };
594
+ return { model: value };
595
+ },
596
+ formatModelQuery(model, provider) {
597
+ return provider ? provider + "/" + model : void 0;
598
+ }
599
+ };
600
+
601
+ // src/integrations/acp/harnesses/presets.ts
602
+ var standardAcpPresets = [
603
+ createGenericAcpHarness("antigravity", {
604
+ label: "Google Antigravity",
605
+ aliases: ["agy"],
606
+ defaultCommand: { command: "agy", args: ["acp"] },
607
+ installHint: "\u5B89\u88C5 Google Antigravity CLI\uFF08agy\uFF09",
608
+ configureHint: "\u8FD0\u884C agy \u5B8C\u6210\u767B\u5F55\u4E0E\u9ED8\u8BA4\u6A21\u578B\u914D\u7F6E\u3002",
609
+ nativeWorkspaceSkills: true
610
+ }),
611
+ createGenericAcpHarness("codex", {
612
+ label: "OpenAI Codex",
613
+ aliases: ["openai-codex", "codex-cli"],
614
+ defaultCommand: { command: "codex-acp", args: [] },
615
+ installHint: "npm install -g @agentclientprotocol/codex-acp",
616
+ configureHint: "\u5728 Codex \u4E2D\u5B8C\u6210\u767B\u5F55\u6216 API \u914D\u7F6E\u3002",
617
+ nativeWorkspaceSkills: true
618
+ })
619
+ ];
620
+
621
+ // src/integrations/acp/registry.ts
622
+ var AcpHarnessRegistry = class {
623
+ #adapters = /* @__PURE__ */ new Map();
624
+ constructor(initial = []) {
625
+ for (const adapter of initial) this.register(adapter);
626
+ }
627
+ register(adapter) {
628
+ requireThat(isAcpBackend(adapter.id), "ACP harness \u6807\u8BC6\u65E0\u6548\uFF1A" + String(adapter.id));
629
+ this.#adapters.set(adapter.id, adapter);
630
+ return this;
631
+ }
632
+ unregister(id) {
633
+ return this.#adapters.delete(id);
634
+ }
635
+ get(id) {
636
+ return this.#adapters.get(id);
637
+ }
638
+ resolve(id) {
639
+ requireThat(isAcpBackend(id), "\u65E0\u6548\u7684 ACP harness \u6807\u8BC6\uFF1A" + String(id));
640
+ return this.#adapters.get(id) ?? createGenericAcpHarness(id);
641
+ }
642
+ list() {
643
+ return [...this.#adapters.keys()];
644
+ }
645
+ /** Map a caller-supplied name ("Claude Code", "agy") to a backend ID; configured names win over aliases. */
646
+ canonical(name, configured = []) {
647
+ const normalized = name.trim().toLowerCase().replace(/[\s_]+/g, "-");
648
+ if (configured.includes(normalized) || this.#adapters.has(normalized)) return normalized;
649
+ const compact = normalized.replace(/-/g, "");
650
+ return [...this.#adapters.values()].find((adapter) => adapter.id.replace(/-/g, "") === compact || adapter.aliases?.some((alias) => alias === normalized || alias.replace(/-/g, "") === compact))?.id ?? normalized;
651
+ }
652
+ };
653
+ var acpHarnesses = new AcpHarnessRegistry([
654
+ piAcpHarness,
655
+ dshAcpHarness,
656
+ claudeAcpHarness,
657
+ ...standardAcpPresets
658
+ ]);
659
+ var resolveAcpHarness = (id) => acpHarnesses.resolve(id);
660
+
661
+ // src/integrations/acp/launch.ts
662
+ function configuredAcpCommand(backend, commands = {}) {
663
+ const entry = Object.hasOwn(commands, backend) ? commands[backend] : void 0;
664
+ const base = entry?.command ? { command: entry.command, args: entry.args ?? [] } : acpHarnesses.get(backend)?.defaultCommand;
665
+ if (!base) return void 0;
666
+ const env = { ...base.env, ...entry?.env };
667
+ return { command: base.command, args: [...base.args], ...Object.keys(env).length ? { env } : {} };
668
+ }
669
+ function acpPermissionPolicy(backend, commands = {}) {
670
+ return (Object.hasOwn(commands, backend) ? commands[backend]?.permission : void 0) ?? "ask";
671
+ }
672
+ function knownAcpBackends(commands = {}) {
673
+ return [.../* @__PURE__ */ new Set([...acpHarnesses.list(), ...Object.keys(commands)])].filter((backend) => configuredAcpCommand(backend, commands));
674
+ }
675
+ function canonicalAcpBackend(name, commands = {}) {
676
+ return acpHarnesses.canonical(name, Object.keys(commands));
677
+ }
678
+ function inspectAcpBackends(commands = {}) {
679
+ return knownAcpBackends(commands).map((backend) => {
680
+ const harness = acpHarnesses.get(backend);
681
+ const selected = configuredAcpCommand(backend, commands);
682
+ const resolved = findAcpExecutable(selected.command);
683
+ return {
684
+ backend,
685
+ ...harness?.label ? { label: harness.label } : {},
686
+ ...harness?.aliases?.length ? { aliases: [...harness.aliases] } : {},
687
+ available: Boolean(resolved),
688
+ builtin: Boolean(harness?.defaultCommand),
689
+ configured: Object.hasOwn(commands, backend),
690
+ permission: acpPermissionPolicy(backend, commands),
691
+ command: selected.command,
692
+ args: [...selected.args],
693
+ ...resolved ? { resolvedCommand: resolved } : { installHint: harness?.installHint ?? "\u5728 .pbot/config.json \u7684 acp \u5B57\u6BB5\u914D\u7F6E\u53EF\u6267\u884C\u547D\u4EE4\u3002" }
694
+ };
695
+ });
696
+ }
697
+ function filterAcpStartOptions(backend, options) {
698
+ const harness = resolveAcpHarness(backend);
699
+ return harness.filterStartOptions ? harness.filterStartOptions(options) : { ...options };
700
+ }
701
+ function acpLaunch(backend, commands, options) {
702
+ requireThat(isAcpBackend(backend), "\u672A\u77E5\u5B50\u4EE3\u7406\u7A0B\u5E8F\uFF1A" + String(backend));
703
+ const harness = resolveAcpHarness(backend);
704
+ const selected = configuredAcpCommand(backend, commands);
705
+ requireThat(selected, `\u672A\u77E5\u5B50\u4EE3\u7406\u7A0B\u5E8F\uFF1A${backend}\u3002\u53EF\u7528\u76EE\u6807\uFF1A${knownAcpBackends(commands).join(", ")}\uFF1B\u81EA\u5B9A\u4E49\u76EE\u6807\u8BF7\u5728 .pbot/config.json \u7684 acp \u5B57\u6BB5\u4E2D\u914D\u7F6E\u3002`);
706
+ requireThat(!options.provider || options.model, "provider \u9700\u8981\u540C\u65F6\u6307\u5B9A\u76EE\u6807 model\u3002");
707
+ harness.validateStartOptions?.(options);
708
+ const permission = acpPermissionPolicy(backend, commands);
709
+ return {
710
+ host: "acp",
711
+ backend,
712
+ command: acpExecutable(selected.command, backend, harness),
713
+ args: [...selected.args],
714
+ ...selected.env ? { env: { ...selected.env } } : {},
715
+ ...permission !== "ask" ? { permission } : {},
716
+ sessionId: null
717
+ };
718
+ }
719
+
720
+ // src/integrations/acp/agents.ts
721
+ var AcpWorkerHost = class {
722
+ constructor(directory, commands = {}) {
723
+ this.commands = commands;
724
+ this.files = new AgentFiles(directory);
725
+ }
726
+ files;
727
+ worker = resolve3(resourceRoot, "../lib/extension/acp-worker.js");
728
+ available(backend) {
729
+ requireThat(backend, "\u901A\u8FC7 worker_create \u59D4\u6D3E\u8DE8 Harness \u4E13\u5BB6\u65F6\u5FC5\u987B\u6307\u5B9A backend\uFF08\u4F8B\u5982 pi\u3001dsh\u3001claude\u3001antigravity\u3001codex \u6216\u81EA\u5B9A\u4E49 ACP \u540D\u79F0\uFF09\u3002");
730
+ requireThat(process.platform === "linux" || process.platform === "darwin", "ACP worker \u5F53\u524D\u652F\u6301 Linux \u548C macOS\u3002");
731
+ requireThat(existsSync2(this.worker), "\u7F3A\u5C11 ACP worker \u6784\u5EFA\u4EA7\u7269\uFF1B\u8BF7\u5148\u8FD0\u884C npm run build\u3002");
732
+ }
733
+ filterOptions(backend, options) {
734
+ return filterAcpStartOptions(backend, options);
735
+ }
736
+ prepare(backend, options) {
737
+ return acpLaunch(backend, this.commands, options);
738
+ }
739
+ /** Probe a backend's advertised model and thinking choices in an isolated ACP process without prompting. */
740
+ async inspectModels(backend, cwd, options = {}) {
741
+ this.available(backend);
742
+ const filtered = this.filterOptions(backend, options);
743
+ const reference = this.prepare(backend, filtered);
744
+ return await new Promise((resolveResult, reject) => {
745
+ const child = fork(this.worker, ["--probe"], {
746
+ cwd,
747
+ env: { ...process.env },
748
+ detached: true,
749
+ stdio: ["ignore", "ignore", "ignore", "ipc"],
750
+ execArgv: []
751
+ });
752
+ let result, failure;
753
+ const timer = setTimeout(() => {
754
+ failure = new Error("ACP \u6A21\u578B\u63A2\u6D4B\u8D85\u65F6\u3002");
755
+ if (child.pid) {
756
+ try {
757
+ process.kill(-child.pid, "SIGKILL");
758
+ } catch (error) {
759
+ if (error.code !== "ESRCH") reject(error);
760
+ }
761
+ }
762
+ }, 3e4);
763
+ child.on("message", (message2) => {
764
+ if (message2.type === "models" && message2.result) result = message2.result;
765
+ if (message2.type === "error") failure = new Error(message2.error ?? "ACP \u6A21\u578B\u63A2\u6D4B\u5931\u8D25\u3002");
766
+ });
767
+ child.once("error", (error) => {
768
+ failure = error;
769
+ });
770
+ child.once("spawn", () => {
771
+ child.send({
772
+ reference,
773
+ cwd,
774
+ ...filtered.provider ? { provider: filtered.provider } : {},
775
+ ...filtered.model ? { model: filtered.model } : {}
776
+ });
777
+ });
778
+ child.once("close", (code) => {
779
+ clearTimeout(timer);
780
+ if (result && code === 0 && !failure) resolveResult(result);
781
+ else reject(failure ?? new Error("ACP \u6A21\u578B\u63A2\u6D4B\u5931\u8D25\u3002"));
782
+ });
783
+ });
784
+ }
785
+ process(id) {
786
+ const record = this.files.optional(id, "acp-process.json", acpProcess);
787
+ if (!record || this.files.read(id, "launch.json", launch).generation !== record.generation) return;
788
+ let denied = false;
789
+ try {
790
+ process.kill(-record.pid, 0);
791
+ } catch (error) {
792
+ const code = error.code;
793
+ if (code === "ESRCH") return;
794
+ if (code !== "EPERM") throw error;
795
+ denied = true;
796
+ }
797
+ const leader = spawnSync("ps", ["-p", String(record.pid), "-o", "args="], { encoding: "utf8" });
798
+ if (leader.status === 0 && !leader.stdout.includes("--pbot-acp-agent " + id + " --generation " + record.generation) || denied && leader.status !== 0) return;
799
+ return record;
800
+ }
801
+ alive(id) {
802
+ return Boolean(this.process(id));
803
+ }
804
+ async validateSession(d, reference) {
805
+ requireThat(!this.alive(d.agentId), "ACP \u6210\u5458\u4ECD\u5728\u8FD0\u884C\uFF0C\u4E0D\u80FD\u6062\u590D\u3002");
806
+ if (reference.sessionId === null) {
807
+ requireThat(!this.files.optional(d.agentId, "acp-input.json", acpInput), "ACP \u8F93\u5165\u4EA4\u4ED8\u72B6\u6001\u4E0D\u660E\uFF1B\u8BF7\u6838\u5BF9\u539F\u8BF7\u6C42\u540E\u65B0\u5EFA\u6210\u5458\u3002");
808
+ return;
809
+ }
810
+ const generation = this.files.read(d.agentId, "launch.json", launch).generation;
811
+ await new Promise((resolveResult, reject) => {
812
+ const child = this.spawn(d, generation, true);
813
+ let validated = false, failure;
814
+ const timer = setTimeout(() => {
815
+ failure = new Error("ACP \u6062\u590D\u6821\u9A8C\u8D85\u65F6\u3002");
816
+ if (child.pid) {
817
+ try {
818
+ process.kill(-child.pid, "SIGKILL");
819
+ } catch (error) {
820
+ if (error.code !== "ESRCH") reject(error);
821
+ }
822
+ }
823
+ }, 45e3);
824
+ child.on("message", (message2) => {
825
+ if (message2.type === "validated") validated = true;
826
+ if (message2.type === "error") failure = new Error(message2.error ?? "ACP \u6062\u590D\u6821\u9A8C\u5931\u8D25\u3002");
827
+ });
828
+ child.once("error", (error) => {
829
+ failure = error;
830
+ });
831
+ child.once("close", (code) => {
832
+ clearTimeout(timer);
833
+ if (validated && code === 0 && !failure) resolveResult();
834
+ else reject(failure ?? new Error("ACP \u6062\u590D\u6821\u9A8C\u5931\u8D25\uFF1B\u539F\u4EE3\u6B21\u548C\u961F\u5217\u5DF2\u4FDD\u7559\u3002"));
835
+ });
836
+ });
837
+ }
838
+ spawn(d, generation, validate = false) {
839
+ return fork(this.worker, [
840
+ "--pbot-acp-agent",
841
+ d.agentId,
842
+ "--generation",
843
+ generation,
844
+ "--directory",
845
+ this.files.directory(d.agentId),
846
+ ...validate ? ["--validate"] : []
847
+ ], {
848
+ cwd: d.cwd,
849
+ env: { ...process.env },
850
+ detached: true,
851
+ stdio: ["ignore", "ignore", "ignore", "ipc"],
852
+ execArgv: []
853
+ });
854
+ }
855
+ async launch(d, _directory, generation, _reference, _resume, signal) {
856
+ signal.throwIfAborted();
857
+ const child = this.spawn(d, generation);
858
+ await new Promise((resolveResult, reject) => {
859
+ child.once("spawn", resolveResult);
860
+ child.once("error", reject);
861
+ });
862
+ requireThat(child.pid, "ACP worker \u6CA1\u6709\u8FDB\u7A0B\u8EAB\u4EFD\u3002");
863
+ try {
864
+ this.files.write(d.agentId, "acp-process.json", { generation, pid: child.pid, startedAt: Date.now() }, acpProcess);
865
+ } catch (error) {
866
+ try {
867
+ process.kill(-child.pid, "SIGKILL");
868
+ } catch (failure) {
869
+ if (failure.code !== "ESRCH") throw new AggregateError([error, failure], "ACP \u542F\u52A8\u4E0E\u6E05\u7406\u5931\u8D25\u3002");
870
+ }
871
+ throw error;
872
+ }
873
+ if (child.connected) child.disconnect();
874
+ child.unref();
875
+ if (signal.aborted) {
876
+ await this.release(d.agentId, generation);
877
+ signal.throwIfAborted();
878
+ }
879
+ }
880
+ async release(id, generation) {
881
+ const record = this.process(id);
882
+ if (!record || record.generation !== generation) return;
883
+ const terminate = (signal) => {
884
+ try {
885
+ process.kill(-record.pid, signal);
886
+ } catch (error) {
887
+ if (error.code !== "ESRCH") throw error;
888
+ }
889
+ };
890
+ terminate("SIGTERM");
891
+ const deadline = Date.now() + 4500;
892
+ while (Date.now() < deadline) {
893
+ const current2 = this.process(id);
894
+ if (!current2 || current2.generation !== generation || current2.pid !== record.pid) return;
895
+ await delay(100);
896
+ }
897
+ const current = this.process(id);
898
+ if (current?.generation === generation && current.pid === record.pid) terminate("SIGKILL");
899
+ }
900
+ report(d, _reference, leaf) {
901
+ requireThat(leaf.startsWith("acp:"), "ACP \u62A5\u544A\u5F15\u7528\u65E0\u6548\u3002");
902
+ const cycleId = fileId(leaf.slice(4)), report = this.files.read(d.agentId, join7("reports", cycleId + ".json"), acpReport);
903
+ requireThat(report.cycleId === cycleId, "ACP \u62A5\u544A\u5468\u671F\u4E0D\u5339\u914D\u3002");
904
+ return report.text;
905
+ }
906
+ };
907
+
908
+ // src/model/acp.ts
909
+ var mcpWorkerToolNames = [
910
+ "worker_create",
911
+ "worker_close",
912
+ "worker_request",
913
+ "worker_response",
914
+ "worker_output",
915
+ "worker_discover"
916
+ ];
917
+
918
+ // src/model/workspace-mcp.ts
919
+ var workspaceMcpToolNames = [
920
+ "workspace_mcp_discover",
921
+ "workspace_mcp_call"
922
+ ];
923
+
924
+ // src/services/agents/agent-service.ts
925
+ import { randomUUID as randomUUID3 } from "node:crypto";
926
+ import { realpathSync as realpathSync3 } from "node:fs";
927
+ import { resolve as resolve4 } from "node:path";
928
+ var AgentService = class {
929
+ constructor(root, directory, host) {
930
+ this.root = root;
931
+ this.host = host;
932
+ this.files = new AgentFiles(directory);
933
+ }
934
+ files;
935
+ #closed = false;
936
+ #preserve = false;
937
+ #starting = /* @__PURE__ */ new Map();
938
+ #launches = /* @__PURE__ */ new Set();
939
+ #closing;
940
+ #releasing = /* @__PURE__ */ new Map();
941
+ alive(id) {
942
+ return this.#starting.has(id) || this.#releasing.has(id) || this.host.alive(id);
943
+ }
944
+ check() {
945
+ requireThat(!this.#closed, "worker \u670D\u52A1\u5DF2\u5173\u95ED\u3002");
946
+ }
947
+ owned(d, owner) {
948
+ return d.workspace === this.root && d.parentSessionId === owner.sessionId && (d.parentLeaf === null || owner.branch.includes(d.parentLeaf));
949
+ }
950
+ get(id, owner) {
951
+ this.check();
952
+ const d = this.files.read(id, "descriptor.json", descriptor);
953
+ requireThat(this.owned(d, owner), "worker \u4E0D\u5C5E\u4E8E\u5F53\u524D\u4F1A\u8BDD\u3002");
954
+ requireThat(releaseLine(d.release) === releaseLine(packageVersion), "worker \u7248\u672C\u4E0D\u517C\u5BB9\uFF1B\u8BF7\u505C\u6B62\u540E\u4F7F\u7528\u5339\u914D\u7248\u672C\u3002");
955
+ return d;
956
+ }
957
+ records(owner) {
958
+ this.check();
959
+ return this.files.list().filter((d) => d.workspace === this.root && d.parentSessionId === owner.sessionId && releaseLine(d.release) === releaseLine(packageVersion));
960
+ }
961
+ list(owner) {
962
+ return this.records(owner).map((d) => this.view(d, owner));
963
+ }
964
+ view(d, owner) {
965
+ const run = this.files.read(d.agentId, "launch.json", launch);
966
+ const saved = this.files.optional(d.agentId, "status.json", status);
967
+ const current = saved?.generation === run.generation ? saved : void 0;
968
+ const alive = this.alive(d.agentId), pending = this.#starting.get(d.agentId);
969
+ const starting = pending && !pending.controller.signal.aborted;
970
+ const reference = this.files.read(d.agentId, "acp-session.json", acpReference);
971
+ const model = this.files.optional(d.agentId, "acp-model.json", acpModelState);
972
+ const selection = model?.generation === run.generation ? {
973
+ ...model.provider ? { provider: model.provider } : {},
974
+ ...model.model ? { model: model.model } : {},
975
+ ...model.resolvedModel ? { resolvedModel: model.resolvedModel } : {},
976
+ ...model.thinking ? { thinking: model.thinking } : {}
977
+ } : void 0;
978
+ const pendingRequests = alive ? [
979
+ ...this.files.pendingPermissions(d.agentId, run.generation).map((item) => ({ requestId: item.requestId, kind: "permission", description: item.description, options: item.options })),
980
+ ...this.files.pendingElicitations(d.agentId, run.generation).map((item) => item.mode === "form" ? { requestId: item.requestId, kind: "form", message: item.message, schema: item.schema ?? { type: "object", properties: {} } } : { requestId: item.requestId, kind: "url", message: item.message, url: item.url ?? "" })
981
+ ] : [];
982
+ return {
983
+ ...d,
984
+ name: run.name,
985
+ generation: run.generation,
986
+ owned: this.owned(d, owner),
987
+ alive,
988
+ backend: reference.backend,
989
+ transport: "acp",
990
+ capabilities: {
991
+ steer: false,
992
+ resume: Boolean(reference.capabilities?.resume || reference.capabilities?.load),
993
+ transcript: false
994
+ },
995
+ ...selection ? { selection } : {},
996
+ state: alive ? starting ? "starting" : run.stop || pending?.controller.signal.aborted ? "stopping" : current?.state ?? "starting" : current?.state === "error" ? "error" : "stopped",
997
+ activity: starting ? "\u542F\u52A8" : alive ? current?.activity ?? "\u542F\u52A8" : current?.error ?? "\u5DF2\u505C\u6B62",
998
+ ...current?.cycle ? { cycle: current.cycle } : {},
999
+ ...current?.error ? { error: current.error } : {},
1000
+ ...pendingRequests.length ? { pendingRequests } : {}
1001
+ };
1002
+ }
1003
+ /** Answer a pending permission or elicitation request forwarded by the worker. */
1004
+ respond(id, input, owner) {
1005
+ const d = this.get(id, owner), run = this.files.read(id, "launch.json", launch);
1006
+ const pending = this.view(d, owner).pendingRequests ?? [];
1007
+ if (!input.requestId && pending.length > 1) {
1008
+ throw new Error("\u5B58\u5728\u591A\u6761\u5F85\u56DE\u590D\u8BF7\u6C42\uFF0C\u8BF7\u6307\u5B9A requestId\uFF1A" + pending.map((item) => item.requestId).join(", "));
1009
+ }
1010
+ const target = input.requestId ? pending.find((item) => item.requestId === input.requestId) : pending[0];
1011
+ requireThat(target, input.requestId ? "\u6CA1\u6709\u5F85\u56DE\u590D\u7684\u8BF7\u6C42\uFF1A" + input.requestId + "\uFF1B\u7528 worker_discover \u67E5\u770B pendingRequests\u3002" : "\u5F53\u524D\u6CA1\u6709\u5F85\u56DE\u590D\u7684\u8BF7\u6C42\u3002");
1012
+ if (target.kind === "permission") {
1013
+ requireThat(input.content === void 0, "\u6743\u9650\u8BF7\u6C42\u4E0D\u4F7F\u7528 content\uFF1B\u8BF7\u7528 action\uFF08accept / decline / cancel\uFF09\u6216\u6307\u5B9A optionId\u3002");
1014
+ let resolved = null;
1015
+ if (input.action === "cancel") {
1016
+ requireThat(input.optionId === void 0, "action \u4E3A cancel \u65F6\u4E0D\u80FD\u540C\u65F6\u6307\u5B9A optionId\u3002");
1017
+ } else if (input.optionId !== void 0) {
1018
+ const exact = target.options.find((option) => option.optionId === input.optionId);
1019
+ const byKind = target.options.filter((option) => option.kind === input.optionId);
1020
+ const matched = exact ?? (byKind.length === 1 ? byKind[0] : void 0);
1021
+ requireThat(matched, "\u6743\u9650 optionId \u65E0\u6548\uFF1A" + input.optionId + "\uFF1B\u53EF\u9009\uFF1A" + target.options.map((option) => `${option.optionId}\uFF08${option.name}/${option.kind}\uFF09`).join(", "));
1022
+ if (input.action === "accept") {
1023
+ requireThat(!matched.kind.startsWith("reject_"), `optionId ${matched.optionId} \u662F\u62D2\u7EDD\u9009\u9879\uFF0C\u4E0E action: "accept" \u51B2\u7A81\u3002`);
1024
+ } else {
1025
+ requireThat(!matched.kind.startsWith("allow_"), `optionId ${matched.optionId} \u662F\u5141\u8BB8\u9009\u9879\uFF0C\u4E0E action: "decline" \u51B2\u7A81\u3002`);
1026
+ }
1027
+ resolved = matched.optionId;
1028
+ } else {
1029
+ const pick = (...kinds) => kinds.map((kind) => target.options.find((option) => option.kind === kind)).find(Boolean)?.optionId;
1030
+ if (input.action === "accept") {
1031
+ const chosen = pick("allow_once", "allow_always");
1032
+ requireThat(chosen, "\u8BE5\u6743\u9650\u8BF7\u6C42\u6CA1\u6709\u53EF\u5141\u8BB8\u7684\u9009\u9879\uFF1B\u53EF\u9009\uFF1A" + target.options.map((option) => option.optionId).join(", "));
1033
+ resolved = chosen;
1034
+ } else {
1035
+ resolved = pick("reject_once", "reject_always") ?? null;
1036
+ }
1037
+ }
1038
+ this.files.ensureSubdirectory(id, "permissions");
1039
+ this.files.write(
1040
+ id,
1041
+ "permissions/" + target.requestId + "-reply.json",
1042
+ { generation: run.generation, requestId: target.requestId, optionId: resolved },
1043
+ acpPermissionReply,
1044
+ true
1045
+ );
1046
+ return this.view(d, owner);
1047
+ }
1048
+ if (target.kind === "form") {
1049
+ requireThat(input.optionId === void 0, "\u95EE\u7B54/\u8868\u5355\u8BF7\u6C42\u4E0D\u4F7F\u7528 optionId\uFF1B\u8BF7\u5C06\u7B54\u6848\u586B\u5165 content\u3002");
1050
+ if (input.action !== "accept") {
1051
+ requireThat(input.content === void 0, `action \u4E3A ${input.action} \u65F6\u4E0D\u80FD\u4F20\u5165 content\u3002`);
1052
+ } else {
1053
+ requireThat(input.content === void 0 || object(input.content), "\u95EE\u7B54/\u8868\u5355\u7B54\u590D\u7684 content \u5FC5\u987B\u662F\u5BF9\u8C61\u3002");
1054
+ }
1055
+ this.files.ensureSubdirectory(id, "elicitations");
1056
+ this.files.write(id, "elicitations/" + target.requestId + "-reply.json", {
1057
+ generation: run.generation,
1058
+ requestId: target.requestId,
1059
+ action: input.action,
1060
+ ...input.action === "accept" ? { content: input.content ?? {} } : {}
1061
+ }, acpElicitationReply, true);
1062
+ return this.view(d, owner);
1063
+ }
1064
+ requireThat(input.optionId === void 0, "URL \u786E\u8BA4\u8BF7\u6C42\u4E0D\u4F7F\u7528 optionId\u3002");
1065
+ requireThat(input.content === void 0, "URL \u786E\u8BA4\u8BF7\u6C42\u4E0D\u4F7F\u7528 content\u3002");
1066
+ this.files.ensureSubdirectory(id, "elicitations");
1067
+ this.files.write(id, "elicitations/" + target.requestId + "-reply.json", {
1068
+ generation: run.generation,
1069
+ requestId: target.requestId,
1070
+ action: input.action
1071
+ }, acpElicitationReply, true);
1072
+ return this.view(d, owner);
1073
+ }
1074
+ async start(input, owner) {
1075
+ this.check();
1076
+ const { backend, ...supplied } = input;
1077
+ this.host.available(backend);
1078
+ const clean = Object.fromEntries(Object.entries(supplied).filter(([, v]) => v !== void 0));
1079
+ const options = this.host.filterOptions ? this.host.filterOptions(backend, clean) : clean;
1080
+ const reference = this.host.prepare(backend, options);
1081
+ const prepared = this.files.control(() => {
1082
+ requireThat(this.list(owner).filter((v) => v.alive).length < 50, "\u6700\u591A 50 \u4E2A\u5B58\u6D3B\u6216\u542F\u52A8\u4E2D worker\uFF1B\u8BF7\u5148\u505C\u6B62\u4E00\u4E2A\u7A7A\u95F2\u4F1A\u8BDD\u3002");
1083
+ const agentId = randomUUID3();
1084
+ const cwd = realpathSync3(resolve4(this.root, options.cwd ?? "."));
1085
+ const files = (options.files ?? []).map((p) => realpathSync3(resolve4(this.root, p)));
1086
+ const d = {
1087
+ agentId,
1088
+ release: packageVersion,
1089
+ workspace: this.root,
1090
+ cwd,
1091
+ parentSessionId: owner.sessionId,
1092
+ parentLeaf: owner.leaf,
1093
+ createdAt: Date.now(),
1094
+ options: { ...options, files, cwd }
1095
+ };
1096
+ const run = { generation: randomUUID3(), name: options.name ?? agentId.slice(0, 8), sequence: 0, stop: false, startedAt: Date.now() };
1097
+ this.files.create(d, run, reference);
1098
+ const initial = options.message ?? "";
1099
+ const request = initial || files.length ? this.files.enqueue(agentId, initial, "steer", files) : void 0;
1100
+ this.#starting.set(agentId, { generation: run.generation, controller: new AbortController(), stage: "launch" });
1101
+ return { d, run, request };
1102
+ });
1103
+ await this.launch(prepared.d, prepared.run.generation);
1104
+ return { ...this.view(prepared.d, owner), ...prepared.request ? { requestId: prepared.request.requestId, messageStatus: "queued" } : {} };
1105
+ }
1106
+ async launch(d, generation, resume = false) {
1107
+ const pending = this.#starting.get(d.agentId);
1108
+ requireThat(pending?.generation === generation, "\u542F\u52A8\u9884\u7EA6\u5DF2\u5931\u6548\u3002");
1109
+ const operation = (async () => {
1110
+ try {
1111
+ await this.host.launch(d, this.files.directory(d.agentId), generation, this.files.reference(d.agentId), resume, pending.controller.signal);
1112
+ requireThat(!this.#closed || this.#preserve, "worker \u670D\u52A1\u5DF2\u5173\u95ED\u3002");
1113
+ pending.controller.signal.throwIfAborted();
1114
+ const run = this.files.read(d.agentId, "launch.json", launch);
1115
+ requireThat(run.generation === generation && !run.stop, "worker \u542F\u52A8\u5DF2\u53D6\u6D88\u6216\u4EE3\u6B21\u53D8\u5316\u3002");
1116
+ } catch (error) {
1117
+ const run = this.files.read(d.agentId, "launch.json", launch);
1118
+ if (run.generation === generation) {
1119
+ if (this.host.alive(d.agentId)) await this.release(d.agentId);
1120
+ this.files.write(d.agentId, "status.json", {
1121
+ generation,
1122
+ state: run.stop ? "stopped" : "error",
1123
+ activity: run.stop ? "\u5DF2\u505C\u6B62" : "\u542F\u52A8\u5931\u8D25",
1124
+ updatedAt: Date.now(),
1125
+ ...run.stop ? {} : { error: String(error) }
1126
+ }, status);
1127
+ }
1128
+ throw error;
1129
+ } finally {
1130
+ if (this.#starting.get(d.agentId) === pending) this.#starting.delete(d.agentId);
1131
+ }
1132
+ })();
1133
+ this.#launches.add(operation);
1134
+ try {
1135
+ await operation;
1136
+ } finally {
1137
+ this.#launches.delete(operation);
1138
+ }
1139
+ }
1140
+ send(id, text3, delivery, owner, attachments = []) {
1141
+ const d = this.get(id, owner);
1142
+ return this.files.control(() => {
1143
+ requireThat(this.alive(id) && this.#starting.get(id)?.stage !== "validate" && !this.files.read(id, "launch.json", launch).stop, "worker \u5DF2\u505C\u6B62\u6216\u4ECD\u5728\u6062\u590D\u6821\u9A8C\uFF0C\u8BF7\u7B49\u5F85\u663E\u5F0F\u6062\u590D\u5B8C\u6210\u3002");
1144
+ const view = this.view(d, owner);
1145
+ requireThat(!(delivery === "steer" && view.state !== "idle"), "\u8BE5 ACP worker \u8FD0\u884C\u4E2D\u4E0D\u652F\u6301 steer\uFF1B\u8BF7\u7528 delivery: followUp \u6392\u961F\u3002");
1146
+ const files = attachments.map((path) => realpathSync3(resolve4(this.root, path)));
1147
+ const request = this.files.enqueue(id, text3, delivery, files);
1148
+ return { ...this.view(d, owner), requestId: request.requestId, messageStatus: "queued" };
1149
+ });
1150
+ }
1151
+ rename(id, name, owner) {
1152
+ requireThat(name.trim().length > 0 && name.length <= 64 && !/[\x00-\x1f]/.test(name), "\u540D\u79F0\u5FC5\u987B\u662F 1 \u5230 64 \u5B57\u7B26\u7684\u5355\u884C\u6587\u672C\u3002");
1153
+ const d = this.get(id, owner);
1154
+ this.files.control(() => {
1155
+ const run = this.files.read(id, "launch.json", launch);
1156
+ run.name = name;
1157
+ this.files.write(id, "launch.json", run, launch);
1158
+ });
1159
+ return this.view(d, owner);
1160
+ }
1161
+ stop(id, owner) {
1162
+ const d = this.get(id, owner);
1163
+ this.requestStop(id);
1164
+ return this.view(d, owner);
1165
+ }
1166
+ requestStop(id) {
1167
+ this.files.control(() => {
1168
+ const run = this.files.read(id, "launch.json", launch);
1169
+ run.stop = true;
1170
+ this.files.write(id, "launch.json", run, launch);
1171
+ });
1172
+ this.#starting.get(id)?.controller.abort();
1173
+ }
1174
+ async enter(id, owner) {
1175
+ const d = this.get(id, owner);
1176
+ if (this.alive(id)) {
1177
+ requireThat(!this.files.read(id, "launch.json", launch).stop, "worker \u6B63\u5728\u505C\u6B62\uFF0C\u8BF7\u7A0D\u540E\u64CD\u4F5C\u3002");
1178
+ return this.view(d, owner);
1179
+ }
1180
+ return this.restart(id, owner);
1181
+ }
1182
+ resume(id, text3, owner) {
1183
+ return this.restart(id, owner, text3);
1184
+ }
1185
+ async restart(id, owner, text3) {
1186
+ const d = this.get(id, owner), reference = this.files.reference(id);
1187
+ this.host.available(reference.backend);
1188
+ const reserved = this.files.control(() => {
1189
+ requireThat(!this.alive(id), "worker \u4ECD\u5728\u8FD0\u884C\u3002");
1190
+ requireThat(this.list(owner).filter((v) => v.alive).length < 50, "\u6700\u591A 50 \u4E2A\u5B58\u6D3B\u6216\u542F\u52A8\u4E2D worker\u3002");
1191
+ const previous = this.files.read(id, "launch.json", launch), interrupted = this.cycles(id, owner);
1192
+ const pending = { generation: previous.generation, controller: new AbortController(), stage: "validate" };
1193
+ this.#starting.set(id, pending);
1194
+ return { previous, interrupted, pending };
1195
+ });
1196
+ const operation = (async () => {
1197
+ await this.host.validateSession(d, this.files.reference(id));
1198
+ requireThat(!this.#closed || this.#preserve, "worker \u670D\u52A1\u5DF2\u5173\u95ED\u3002");
1199
+ reserved.pending.controller.signal.throwIfAborted();
1200
+ const prepared = this.files.control(() => {
1201
+ requireThat(!this.host.alive(id) && this.files.read(id, "launch.json", launch).generation === reserved.previous.generation, "worker \u5DF2\u7531\u5176\u4ED6\u64CD\u4F5C\u6062\u590D\u3002");
1202
+ for (const ended of reserved.interrupted) {
1203
+ if (ended.generation === reserved.previous.generation && !this.files.completions(id).some((c) => c.cycleId === ended.cycleId)) {
1204
+ this.files.write(id, "completions/" + ended.cycleId + ".json", ended, cycle, true);
1205
+ }
1206
+ }
1207
+ const run = { ...reserved.previous, generation: randomUUID3(), sequence: 0, stop: false, startedAt: Date.now() };
1208
+ this.files.write(id, "launch.json", run, launch);
1209
+ const request = text3 === void 0 ? void 0 : this.files.enqueue(id, text3, "steer");
1210
+ reserved.pending.generation = run.generation;
1211
+ reserved.pending.stage = "launch";
1212
+ return { run, request };
1213
+ });
1214
+ await this.launch(d, prepared.run.generation, true);
1215
+ return { ...this.view(d, owner), ...prepared.request ? { requestId: prepared.request.requestId, messageStatus: "queued" } : {} };
1216
+ })();
1217
+ this.#launches.add(operation);
1218
+ try {
1219
+ return await operation;
1220
+ } finally {
1221
+ this.#launches.delete(operation);
1222
+ if (this.#starting.get(id) === reserved.pending) this.#starting.delete(id);
1223
+ }
1224
+ }
1225
+ cycles(id, owner) {
1226
+ const d = this.get(id, owner), view = this.view(d, owner), values = this.files.completions(id);
1227
+ if (view.cycle && !values.some((c) => c.cycleId === view.cycle.cycleId)) {
1228
+ values.push(view.state === "stopped" || view.state === "error" ? { ...view.cycle, state: "interrupted", finishedAt: view.cycle.finishedAt ?? Date.now() } : view.cycle);
1229
+ }
1230
+ if (["stopped", "error"].includes(view.state)) {
1231
+ const run = this.files.read(id, "launch.json", launch), saved = this.files.optional(id, "status.json", status);
1232
+ for (const requestId of saved?.generation === run.generation ? saved.accepted ?? [] : []) {
1233
+ if (values.some((c) => c.generation === run.generation && c.requestIds.includes(requestId))) continue;
1234
+ values.push({
1235
+ cycleId: requestId,
1236
+ generation: run.generation,
1237
+ startedAt: run.startedAt,
1238
+ finishedAt: Date.now(),
1239
+ state: "interrupted",
1240
+ leaf: null,
1241
+ requestIds: [requestId],
1242
+ source: "parent",
1243
+ error: "\u9886\u53D6\u540E\u6267\u884C\u7ED3\u679C\u4E0D\u660E\uFF1B\u672A\u91CD\u8DD1\u3002"
1244
+ });
1245
+ }
1246
+ if (run.sequence > 0 && !values.some((c) => c.generation === view.generation)) {
1247
+ values.push({
1248
+ cycleId: run.generation,
1249
+ generation: run.generation,
1250
+ startedAt: run.startedAt,
1251
+ finishedAt: run.startedAt,
1252
+ state: "interrupted",
1253
+ leaf: null,
1254
+ requestIds: [],
1255
+ source: "parent",
1256
+ error: view.error ?? "\u5B50\u8FDB\u7A0B\u5728\u4EA4\u4ED8\u524D\u9000\u51FA\u3002"
1257
+ });
1258
+ }
1259
+ }
1260
+ return values;
1261
+ }
1262
+ status(id, owner) {
1263
+ const d = this.get(id, owner), latest = this.cycles(id, owner).at(-1);
1264
+ return { ...this.view(d, owner), ...latest ? { cycle: latest } : {} };
1265
+ }
1266
+ async read(id, owner, cycleId, offset = 0, limit = 16e3) {
1267
+ const d = this.get(id, owner), cycles = this.cycles(id, owner);
1268
+ const c = cycleId ? cycles.find((v) => v.cycleId === cycleId) : cycles.at(-1);
1269
+ requireThat(!cycleId || c, "\u5468\u671F\u4E0D\u5B58\u5728\u3002");
1270
+ const report = c ? await this.report(d, c) : "";
1271
+ this.check();
1272
+ requireThat(offset <= report.length, "\u5206\u9875\u4F4D\u7F6E\u8D85\u51FA\u62A5\u544A\u3002");
1273
+ return {
1274
+ ...this.view(d, owner),
1275
+ ...c ? { cycle: c } : {},
1276
+ cycles: cycles.map((v) => ({ cycleId: v.cycleId, state: v.state })),
1277
+ report: report.slice(offset, offset + limit),
1278
+ totalLength: report.length,
1279
+ nextOffset: offset + limit < report.length ? offset + limit : null
1280
+ };
1281
+ }
1282
+ report(d, c) {
1283
+ if (c.leaf === null) return "";
1284
+ return this.host.report(d, this.files.reference(d.agentId), c.leaf);
1285
+ }
1286
+ release(id) {
1287
+ let pending = this.#releasing.get(id);
1288
+ if (!pending) {
1289
+ const generation = this.files.read(id, "launch.json", launch).generation;
1290
+ pending = Promise.resolve().then(async () => {
1291
+ if (this.files.read(id, "launch.json", launch).generation === generation) await this.host.release(id, generation);
1292
+ }).finally(() => this.#releasing.delete(id));
1293
+ this.#releasing.set(id, pending);
1294
+ }
1295
+ return pending;
1296
+ }
1297
+ close(owner, preserve = false) {
1298
+ return this.#closing ??= this.dispose(owner, preserve);
1299
+ }
1300
+ async dispose(owner, preserve = false) {
1301
+ if (this.#closed) return;
1302
+ const ids = !preserve && owner ? this.list(owner).filter((v) => v.alive).map((v) => v.agentId) : [];
1303
+ this.#closed = true;
1304
+ this.#preserve = preserve;
1305
+ const errors = [];
1306
+ for (const id of ids) {
1307
+ try {
1308
+ this.requestStop(id);
1309
+ } catch (error) {
1310
+ errors.push(error);
1311
+ }
1312
+ }
1313
+ if (!preserve) for (const pending of this.#starting.values()) pending.controller.abort();
1314
+ const deadline = Date.now() + 5e3;
1315
+ while (ids.some((id) => this.alive(id)) && Date.now() < deadline) await new Promise((r) => setTimeout(r, 100));
1316
+ const released = await Promise.allSettled(ids.filter((id) => this.host.alive(id)).map((id) => this.release(id)));
1317
+ for (const value of released) if (value.status === "rejected") errors.push(value.reason);
1318
+ await Promise.allSettled([...this.#launches]);
1319
+ if (errors.length) throw new AggregateError(errors, "\u505C\u6B62\u6216\u91CA\u653E worker \u5931\u8D25\uFF1B\u8BF7\u6838\u5BF9\u4ECD\u5B58\u6D3B\u7684\u6267\u884C\u8D44\u6E90\u3002");
1320
+ }
1321
+ };
1322
+
1323
+ // src/services/workspace/workspace-config.ts
1324
+ import { mkdir, readFile } from "node:fs/promises";
1325
+ import { dirname as dirname2, join as join8 } from "node:path";
1326
+ var featureKeys = ["prompts", "skills", "mcp"];
1327
+ function config(value) {
1328
+ if (!object(value) || value.enabled !== void 0 && typeof value.enabled !== "boolean") {
1329
+ throw new Error("\u914D\u7F6E\u5FC5\u987B\u662F JSON \u5BF9\u8C61\uFF0Cenabled \u5FC5\u987B\u662F\u5E03\u5C14\u503C\u3002");
1330
+ }
1331
+ if (value.features !== void 0) {
1332
+ if (!object(value.features) || Object.entries(value.features).some(([key, entry]) => !featureKeys.includes(key) || entry !== void 0 && typeof entry !== "boolean")) {
1333
+ throw new Error("features \u5FC5\u987B\u662F JSON \u5BF9\u8C61\uFF0C\u4EC5\u652F\u6301 prompts\u3001skills\u3001mcp \u5E03\u5C14\u5F00\u5173\u3002");
1334
+ }
1335
+ }
1336
+ if (value.acp !== void 0) {
1337
+ if (!object(value.acp) || Object.keys(value.acp).some((key) => !isAcpBackend(key))) {
1338
+ throw new Error("acp \u952E\u540D\u5FC5\u987B\u4E3A\u5C0F\u5199\u5B57\u6BCD\u3001\u6570\u5B57\u548C\u8FDE\u5B57\u7B26\uFF081\u201364 \u5B57\u7B26\uFF09\u3002");
1339
+ }
1340
+ for (const command of Object.values(value.acp)) {
1341
+ const launch2 = !object(command) ? false : command.command === void 0 ? command.args === void 0 : typeof command.command === "string" && command.command.trim() && !command.command.includes("\0") && (command.args === void 0 || Array.isArray(command.args) && command.args.every((arg) => typeof arg === "string" && !arg.includes("\0")));
1342
+ if (!object(command) || !launch2 || command.env !== void 0 && (!object(command.env) || Object.entries(command.env).some(([k, v]) => !k || k.includes("\0") || typeof v !== "string" || v.includes("\0"))) || command.permission !== void 0 && !["ask", "allow", "deny"].includes(String(command.permission)) || Object.keys(command).some((key) => !["command", "args", "env", "permission"].includes(key))) {
1343
+ throw new Error("ACP \u914D\u7F6E\u9700\u8981 command\uFF08\u5185\u7F6E\u76EE\u6807\u53EF\u7701\u7565\uFF09\u53CA\u53EF\u9009 args \u5B57\u7B26\u4E32\u6570\u7EC4\u3001env \u5B57\u7B26\u4E32\u6620\u5C04\u3001permission\uFF08ask\u3001allow \u6216 deny\uFF09\u3002");
1344
+ }
1345
+ }
1346
+ }
1347
+ return value;
1348
+ }
1349
+ function workspaceFeatures(configuration) {
1350
+ const raw = configuration && "features" in configuration ? configuration.features : configuration;
1351
+ return {
1352
+ prompts: raw?.prompts !== false,
1353
+ skills: raw?.skills !== false,
1354
+ mcp: raw?.mcp !== false
1355
+ };
1356
+ }
1357
+ function workspaceConfigPath(root) {
1358
+ return join8(root, ".pbot", "config.json");
1359
+ }
1360
+ async function readWorkspaceConfig(root) {
1361
+ const path = workspaceConfigPath(root);
1362
+ let content;
1363
+ try {
1364
+ content = await readFile(path, "utf8");
1365
+ } catch (error) {
1366
+ if (error.code === "ENOENT") return { path, present: false, enabled: false };
1367
+ return { path, present: true, enabled: false, error: `\u65E0\u6CD5\u8BFB\u53D6\u5DE5\u4F5C\u533A\u914D\u7F6E ${path}: ${String(error)}` };
1368
+ }
1369
+ try {
1370
+ const value = config(JSON.parse(content));
1371
+ const settings = value;
1372
+ return {
1373
+ path,
1374
+ present: true,
1375
+ enabled: settings.enabled === true,
1376
+ ...settings.features ? { features: settings.features } : {},
1377
+ ...settings.acp ? { acp: settings.acp } : {}
1378
+ };
1379
+ } catch (error) {
1380
+ return { path, present: true, enabled: false, error: `\u5DE5\u4F5C\u533A\u914D\u7F6E\u65E0\u6548 ${path}: ${String(error)}` };
1381
+ }
1382
+ }
1383
+ function workspaceDisabledMessage(configuration) {
1384
+ return configuration.error ?? `Personal Bot \u672A\u5728\u6B64\u5DE5\u4F5C\u533A\u542F\u7528\u3002\u8BF7\u6267\u884C /pbot init \u521D\u59CB\u5316\u5E76\u542F\u7528\uFF1B\u914D\u7F6E\u6587\u4EF6\uFF1A${configuration.path}`;
1385
+ }
1386
+
1387
+ // src/extension/mcp-bridge.ts
1388
+ import { spawn } from "node:child_process";
1389
+ import { setTimeout as delay2 } from "node:timers/promises";
1390
+
1391
+ // src/services/workspace/workspace-mcp.ts
1392
+ import { mkdir as mkdir2, readFile as readFile2 } from "node:fs/promises";
1393
+ import { dirname as dirname3, join as join9, resolve as resolve5 } from "node:path";
1394
+ var serverNamePattern = /^[A-Za-z0-9][A-Za-z0-9_-]{0,31}$/;
1395
+ var reservedServerNames = /* @__PURE__ */ new Set(["pbot"]);
1396
+ var stdioKeys = /* @__PURE__ */ new Set(["command", "args", "env", "cwd", "description", "timeout", "enabled"]);
1397
+ var httpKeys = /* @__PURE__ */ new Set(["url", "headers", "description", "timeout", "enabled"]);
1398
+ var defaultTimeoutSeconds = 60;
1399
+ var envPattern = /\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g;
1400
+ function isWorkspaceMcpHttpServer(server) {
1401
+ return "url" in server && typeof server.url === "string";
1402
+ }
1403
+ function validateStringRecord(value, label) {
1404
+ requireThat(object(value), `${label} \u5FC5\u987B\u662F\u5B57\u7B26\u4E32\u6620\u5C04\u3002`);
1405
+ const result = {};
1406
+ for (const [key, entry] of Object.entries(value)) {
1407
+ requireThat(
1408
+ key.length > 0 && !key.includes("\0") && typeof entry === "string" && !entry.includes("\0"),
1409
+ `${label}.${key} \u5FC5\u987B\u662F\u975E\u7A7A\u952E\u4E0E\u65E0\u7A7A\u5B57\u8282\u5B57\u7B26\u4E32\u503C\u3002`
1410
+ );
1411
+ result[key] = entry;
1412
+ }
1413
+ return result;
1414
+ }
1415
+ function validateWorkspaceMcpServer(name, value) {
1416
+ requireThat(serverNamePattern.test(name), `MCP \u670D\u52A1\u540D\u65E0\u6548\uFF1A${name}\uFF08\u9700\u5339\u914D [A-Za-z0-9][A-Za-z0-9_-]{0,31}\uFF09\u3002`);
1417
+ requireThat(!reservedServerNames.has(name.toLowerCase()), `MCP \u670D\u52A1\u540D "${name}" \u4E3A Personal Bot \u4FDD\u7559\u540D\u79F0\u3002`);
1418
+ requireThat(object(value), `MCP \u670D\u52A1 "${name}" \u914D\u7F6E\u5FC5\u987B\u662F JSON \u5BF9\u8C61\u3002`);
1419
+ const hasCommand = value.command !== void 0;
1420
+ const hasUrl = value.url !== void 0;
1421
+ requireThat(hasCommand !== hasUrl, `MCP \u670D\u52A1 "${name}" \u5FC5\u987B\u4E14\u53EA\u80FD\u58F0\u660E command\uFF08stdio\uFF09\u6216 url\uFF08Streamable HTTP\uFF09\u4E4B\u4E00\u3002`);
1422
+ const allowed = hasCommand ? stdioKeys : httpKeys;
1423
+ const unknown = Object.keys(value).filter((key) => !allowed.has(key));
1424
+ requireThat(unknown.length === 0, `MCP \u670D\u52A1 "${name}" \u5305\u542B\u672A\u77E5\u5B57\u6BB5\uFF1A${unknown.join(", ")}\u3002`);
1425
+ if (value.description !== void 0) {
1426
+ requireThat(
1427
+ typeof value.description === "string" && !value.description.includes("\0"),
1428
+ `MCP \u670D\u52A1 "${name}" \u7684 description \u5FC5\u987B\u662F\u5B57\u7B26\u4E32\u3002`
1429
+ );
1430
+ }
1431
+ if (value.timeout !== void 0) {
1432
+ requireThat(
1433
+ typeof value.timeout === "number" && Number.isInteger(value.timeout) && value.timeout >= 1 && value.timeout <= 3600,
1434
+ `MCP \u670D\u52A1 "${name}" \u7684 timeout \u5FC5\u987B\u662F 1\u20133600 \u7684\u6574\u6570\u79D2\u3002`
1435
+ );
1436
+ }
1437
+ if (value.enabled !== void 0) {
1438
+ requireThat(typeof value.enabled === "boolean", `MCP \u670D\u52A1 "${name}" \u7684 enabled \u5FC5\u987B\u662F\u5E03\u5C14\u503C\u3002`);
1439
+ }
1440
+ const base = {
1441
+ ...value.description !== void 0 ? { description: value.description } : {},
1442
+ ...value.timeout !== void 0 ? { timeout: value.timeout } : {},
1443
+ ...value.enabled !== void 0 ? { enabled: value.enabled } : {}
1444
+ };
1445
+ if (hasCommand) {
1446
+ requireThat(
1447
+ typeof value.command === "string" && value.command.trim().length > 0 && !value.command.includes("\0"),
1448
+ `MCP \u670D\u52A1 "${name}" \u7684 command \u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32\u3002`
1449
+ );
1450
+ let args;
1451
+ if (value.args !== void 0) {
1452
+ requireThat(
1453
+ Array.isArray(value.args) && value.args.every((item) => typeof item === "string" && !item.includes("\0")),
1454
+ `MCP \u670D\u52A1 "${name}" \u7684 args \u5FC5\u987B\u662F\u5B57\u7B26\u4E32\u6570\u7EC4\u3002`
1455
+ );
1456
+ args = [...value.args];
1457
+ }
1458
+ const env = value.env !== void 0 ? validateStringRecord(value.env, `MCP \u670D\u52A1 "${name}" \u7684 env`) : void 0;
1459
+ let cwd;
1460
+ if (value.cwd !== void 0) {
1461
+ requireThat(
1462
+ typeof value.cwd === "string" && value.cwd.trim().length > 0 && !value.cwd.includes("\0"),
1463
+ `MCP \u670D\u52A1 "${name}" \u7684 cwd \u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32\u3002`
1464
+ );
1465
+ cwd = value.cwd;
1466
+ }
1467
+ const entry2 = {
1468
+ command: value.command,
1469
+ ...args ? { args } : {},
1470
+ ...env ? { env } : {},
1471
+ ...cwd ? { cwd } : {},
1472
+ ...base
1473
+ };
1474
+ return entry2;
1475
+ }
1476
+ requireThat(
1477
+ typeof value.url === "string" && value.url.trim().length > 0 && !value.url.includes("\0"),
1478
+ `MCP \u670D\u52A1 "${name}" \u7684 url \u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32\u3002`
1479
+ );
1480
+ const rawUrl = value.url.trim();
1481
+ requireThat(
1482
+ /^https?:\/\/.+/.test(rawUrl) || envPattern.test(rawUrl),
1483
+ `MCP \u670D\u52A1 "${name}" \u7684 url \u5FC5\u987B\u4EE5 http:// \u6216 https:// \u5F00\u5934\u3002`
1484
+ );
1485
+ envPattern.lastIndex = 0;
1486
+ const headers = value.headers !== void 0 ? validateStringRecord(value.headers, `MCP \u670D\u52A1 "${name}" \u7684 headers`) : void 0;
1487
+ const entry = {
1488
+ url: rawUrl,
1489
+ ...headers ? { headers } : {},
1490
+ ...base
1491
+ };
1492
+ return entry;
1493
+ }
1494
+ function validateMcpFile(value) {
1495
+ requireThat(object(value), "\u5DE5\u4F5C\u533A MCP \u914D\u7F6E\u5FC5\u987B\u662F JSON \u5BF9\u8C61\u3002");
1496
+ const rawServers = value.mcpServers;
1497
+ requireThat(rawServers !== void 0 && object(rawServers), "\u5DE5\u4F5C\u533A MCP \u914D\u7F6E\u9700\u8981 mcpServers \u5BF9\u8C61\u3002");
1498
+ const servers = {};
1499
+ for (const [name, entry] of Object.entries(rawServers)) {
1500
+ servers[name] = validateWorkspaceMcpServer(name, entry);
1501
+ }
1502
+ return { mcpServers: servers };
1503
+ }
1504
+ function workspaceMcpPath(root) {
1505
+ return join9(root, ".pbot", "mcp.json");
1506
+ }
1507
+ async function readWorkspaceMcpConfig(root) {
1508
+ const path = workspaceMcpPath(root);
1509
+ let content;
1510
+ try {
1511
+ content = await readFile2(path, "utf8");
1512
+ } catch (error) {
1513
+ if (error.code === "ENOENT") return { path, present: false, servers: {} };
1514
+ return { path, present: true, servers: {}, error: `\u65E0\u6CD5\u8BFB\u53D6\u5DE5\u4F5C\u533A MCP \u914D\u7F6E ${path}: ${String(error)}` };
1515
+ }
1516
+ try {
1517
+ const parsed = validateMcpFile(JSON.parse(content));
1518
+ return { path, present: true, servers: parsed.mcpServers };
1519
+ } catch (error) {
1520
+ return { path, present: true, servers: {}, error: `\u5DE5\u4F5C\u533A MCP \u914D\u7F6E\u65E0\u6548 ${path}: ${error instanceof Error ? error.message : String(error)}` };
1521
+ }
1522
+ }
1523
+ function expandEnvTemplate(value, env, context) {
1524
+ return value.replace(envPattern, (_match, variable) => {
1525
+ const resolved = env[variable];
1526
+ requireThat(resolved !== void 0, `${context} \u5F15\u7528\u7684\u73AF\u5883\u53D8\u91CF ${variable} \u672A\u8BBE\u7F6E\u3002`);
1527
+ return resolved;
1528
+ });
1529
+ }
1530
+ function resolveWorkspaceMcpServer(root, name, server, env = process.env) {
1531
+ const timeout = server.timeout ?? defaultTimeoutSeconds;
1532
+ if (isWorkspaceMcpHttpServer(server)) {
1533
+ const url = expandEnvTemplate(server.url, env, `MCP \u670D\u52A1 "${name}" \u7684 url`);
1534
+ requireThat(/^https?:\/\/.+/.test(url), `MCP \u670D\u52A1 "${name}" \u5C55\u5F00\u540E\u7684 url \u5FC5\u987B\u4EE5 http:// \u6216 https:// \u5F00\u5934\u3002`);
1535
+ const headers = {};
1536
+ for (const [key, value] of Object.entries(server.headers ?? {})) {
1537
+ headers[key] = expandEnvTemplate(value, env, `MCP \u670D\u52A1 "${name}" \u7684 headers.${key}`);
1538
+ }
1539
+ return {
1540
+ transport: "http",
1541
+ name,
1542
+ url,
1543
+ headers,
1544
+ ...server.description ? { description: server.description } : {},
1545
+ timeout
1546
+ };
1547
+ }
1548
+ const command = expandEnvTemplate(server.command, env, `MCP \u670D\u52A1 "${name}" \u7684 command`);
1549
+ const args = (server.args ?? []).map((arg, index) => expandEnvTemplate(arg, env, `MCP \u670D\u52A1 "${name}" \u7684 args[${index}]`));
1550
+ const resolvedEnv = {};
1551
+ for (const [key, value] of Object.entries(server.env ?? {})) {
1552
+ resolvedEnv[key] = expandEnvTemplate(value, env, `MCP \u670D\u52A1 "${name}" \u7684 env.${key}`);
1553
+ }
1554
+ const cwd = server.cwd ? resolve5(root, expandEnvTemplate(server.cwd, env, `MCP \u670D\u52A1 "${name}" \u7684 cwd`)) : root;
1555
+ return {
1556
+ transport: "stdio",
1557
+ name,
1558
+ command,
1559
+ args,
1560
+ env: resolvedEnv,
1561
+ cwd,
1562
+ ...server.description ? { description: server.description } : {},
1563
+ timeout
1564
+ };
1565
+ }
1566
+
1567
+ // src/extension/mcp-bridge.ts
1568
+ var protocolVersion = "2025-03-26";
1569
+ var maxStderrBytes = 4096;
1570
+ function rpcError(server, method, error) {
1571
+ const detail = error.data !== void 0 ? `\uFF08${JSON.stringify(error.data)}\uFF09` : "";
1572
+ return new Error(`MCP \u670D\u52A1 "${server}" \u8C03\u7528 ${method} \u5931\u8D25\uFF1A${error.message ?? "\u672A\u77E5\u9519\u8BEF"}${detail}`);
1573
+ }
1574
+ var StdioMcpClient = class {
1575
+ fingerprint;
1576
+ #server;
1577
+ #child;
1578
+ #pending = /* @__PURE__ */ new Map();
1579
+ #exited;
1580
+ #nextId = 1;
1581
+ #buffer = "";
1582
+ #stderr = "";
1583
+ #alive = true;
1584
+ #closing;
1585
+ constructor(server, fingerprint) {
1586
+ this.#server = server;
1587
+ this.fingerprint = fingerprint;
1588
+ this.#child = spawn(server.command, server.args, {
1589
+ cwd: server.cwd,
1590
+ env: { ...process.env, ...server.env },
1591
+ stdio: ["pipe", "pipe", "pipe"]
1592
+ });
1593
+ this.#exited = new Promise((resolveExit) => this.#child.once("close", () => resolveExit()));
1594
+ this.#child.stdout.setEncoding("utf8");
1595
+ this.#child.stderr.setEncoding("utf8");
1596
+ this.#child.stdin.on("error", () => {
1597
+ });
1598
+ this.#child.stderr.on("data", (chunk) => {
1599
+ this.#stderr = (this.#stderr + String(chunk)).slice(-maxStderrBytes);
1600
+ });
1601
+ this.#child.stdout.on("data", (chunk) => this.#onData(String(chunk)));
1602
+ this.#child.once("error", (error) => this.#failAll(new Error(`MCP \u670D\u52A1 "${server.name}" \u542F\u52A8\u5931\u8D25\uFF1A${error.message}`)));
1603
+ this.#child.once("exit", (code, signal) => {
1604
+ const stderr = this.#stderr.trim();
1605
+ const suffix = stderr ? `
1606
+ stderr: ${stderr}` : "";
1607
+ this.#failAll(new Error(`MCP \u670D\u52A1 "${server.name}" \u8FDB\u7A0B\u5DF2\u9000\u51FA\uFF08${signal ?? code ?? "unknown"}\uFF09\u3002${suffix}`));
1608
+ });
1609
+ }
1610
+ get alive() {
1611
+ return this.#alive && this.#child.exitCode === null && this.#child.signalCode === null;
1612
+ }
1613
+ #failAll(error) {
1614
+ this.#alive = false;
1615
+ for (const [id, entry] of this.#pending) {
1616
+ clearTimeout(entry.timer);
1617
+ entry.reject(error);
1618
+ this.#pending.delete(id);
1619
+ }
1620
+ }
1621
+ #onData(chunk) {
1622
+ this.#buffer += chunk;
1623
+ for (; ; ) {
1624
+ const nl = this.#buffer.indexOf("\n");
1625
+ if (nl < 0) break;
1626
+ const line = this.#buffer.slice(0, nl).trim();
1627
+ this.#buffer = this.#buffer.slice(nl + 1);
1628
+ if (!line) continue;
1629
+ let parsed;
1630
+ try {
1631
+ parsed = JSON.parse(line);
1632
+ } catch {
1633
+ continue;
1634
+ }
1635
+ if (!object(parsed) || typeof parsed.id !== "number") continue;
1636
+ const entry = this.#pending.get(parsed.id);
1637
+ if (!entry) continue;
1638
+ this.#pending.delete(parsed.id);
1639
+ clearTimeout(entry.timer);
1640
+ const response = parsed;
1641
+ if (response.error) entry.reject(rpcError(this.#server.name, "request", response.error));
1642
+ else entry.resolve(response.result);
1643
+ }
1644
+ }
1645
+ async initialize() {
1646
+ await this.request("initialize", {
1647
+ protocolVersion,
1648
+ capabilities: {},
1649
+ clientInfo: { name: "personal-bot", version: packageVersion }
1650
+ });
1651
+ if (this.alive) {
1652
+ this.#child.stdin.write(JSON.stringify({ jsonrpc: "2.0", method: "notifications/initialized" }) + "\n");
1653
+ }
1654
+ }
1655
+ request(method, params = {}) {
1656
+ if (!this.alive) return Promise.reject(new Error(`MCP \u670D\u52A1 "${this.#server.name}" \u8FDE\u63A5\u5DF2\u65AD\u5F00\u3002`));
1657
+ const id = this.#nextId++;
1658
+ const timeoutMs = this.#server.timeout * 1e3;
1659
+ return new Promise((resolveResponse, rejectResponse) => {
1660
+ const timer = setTimeout(() => {
1661
+ this.#pending.delete(id);
1662
+ rejectResponse(new Error(`MCP \u670D\u52A1 "${this.#server.name}" \u8C03\u7528 ${method} \u8D85\u65F6\uFF08${this.#server.timeout}s\uFF09\u3002`));
1663
+ }, timeoutMs);
1664
+ this.#pending.set(id, { resolve: resolveResponse, reject: rejectResponse, timer });
1665
+ try {
1666
+ this.#child.stdin.write(JSON.stringify({ jsonrpc: "2.0", id, method, params }) + "\n");
1667
+ } catch (error) {
1668
+ clearTimeout(timer);
1669
+ this.#pending.delete(id);
1670
+ rejectResponse(error instanceof Error ? error : new Error(String(error)));
1671
+ }
1672
+ });
1673
+ }
1674
+ close() {
1675
+ return this.#closing ??= (async () => {
1676
+ this.#alive = false;
1677
+ this.#failAll(new Error(`MCP \u670D\u52A1 "${this.#server.name}" \u5DF2\u5173\u95ED\u3002`));
1678
+ try {
1679
+ this.#child.stdin.end();
1680
+ } catch {
1681
+ }
1682
+ if (this.#child.exitCode === null && this.#child.signalCode === null) this.#child.kill("SIGTERM");
1683
+ const grace = new AbortController();
1684
+ try {
1685
+ await Promise.race([this.#exited, delay2(1500, void 0, { signal: grace.signal })]);
1686
+ } finally {
1687
+ grace.abort();
1688
+ }
1689
+ if (this.#child.exitCode === null && this.#child.signalCode === null) this.#child.kill("SIGKILL");
1690
+ this.#child.stdout.destroy();
1691
+ this.#child.stderr.destroy();
1692
+ await this.#exited;
1693
+ })();
1694
+ }
1695
+ };
1696
+ function parseSseJsonRpc(body, expectedId) {
1697
+ const blocks = body.split(/\r?\n\r?\n/);
1698
+ let fallback;
1699
+ for (const block of blocks) {
1700
+ const dataLines = block.split(/\r?\n/).filter((line) => line.startsWith("data:")).map((line) => line.slice(5).trimStart());
1701
+ if (!dataLines.length) continue;
1702
+ const payload = dataLines.join("\n").trim();
1703
+ if (!payload || payload === "[DONE]") continue;
1704
+ let parsed;
1705
+ try {
1706
+ parsed = JSON.parse(payload);
1707
+ } catch {
1708
+ continue;
1709
+ }
1710
+ if (!object(parsed)) continue;
1711
+ const message2 = parsed;
1712
+ if (message2.id === expectedId) return message2;
1713
+ if (message2.result !== void 0 || message2.error !== void 0) fallback = message2;
1714
+ }
1715
+ return fallback;
1716
+ }
1717
+ var HttpMcpClient = class {
1718
+ fingerprint;
1719
+ #server;
1720
+ #nextId = 1;
1721
+ #sessionId;
1722
+ #closed = false;
1723
+ constructor(server, fingerprint) {
1724
+ this.#server = server;
1725
+ this.fingerprint = fingerprint;
1726
+ }
1727
+ get alive() {
1728
+ return !this.#closed;
1729
+ }
1730
+ #headers() {
1731
+ return {
1732
+ "Content-Type": "application/json",
1733
+ Accept: "application/json, text/event-stream",
1734
+ ...this.#server.headers,
1735
+ ...this.#sessionId ? { "Mcp-Session-Id": this.#sessionId } : {}
1736
+ };
1737
+ }
1738
+ async initialize() {
1739
+ await this.request("initialize", {
1740
+ protocolVersion,
1741
+ capabilities: {},
1742
+ clientInfo: { name: "personal-bot", version: packageVersion }
1743
+ });
1744
+ try {
1745
+ await fetch(this.#server.url, {
1746
+ method: "POST",
1747
+ headers: this.#headers(),
1748
+ body: JSON.stringify({ jsonrpc: "2.0", method: "notifications/initialized" }),
1749
+ signal: AbortSignal.timeout(Math.min(this.#server.timeout * 1e3, 1e4))
1750
+ });
1751
+ } catch {
1752
+ }
1753
+ }
1754
+ async request(method, params = {}) {
1755
+ requireThat(!this.#closed, `MCP \u670D\u52A1 "${this.#server.name}" \u8FDE\u63A5\u5DF2\u5173\u95ED\u3002`);
1756
+ const id = this.#nextId++;
1757
+ const response = await fetch(this.#server.url, {
1758
+ method: "POST",
1759
+ headers: this.#headers(),
1760
+ body: JSON.stringify({ jsonrpc: "2.0", id, method, params }),
1761
+ signal: AbortSignal.timeout(this.#server.timeout * 1e3)
1762
+ });
1763
+ const session = response.headers.get("mcp-session-id");
1764
+ if (session) this.#sessionId = session;
1765
+ const text3 = await response.text();
1766
+ if (!response.ok) {
1767
+ throw new Error(`MCP \u670D\u52A1 "${this.#server.name}" HTTP ${response.status}\uFF1A${text3.slice(0, 500)}`);
1768
+ }
1769
+ const contentType = response.headers.get("content-type") ?? "";
1770
+ let parsed;
1771
+ if (contentType.includes("text/event-stream")) {
1772
+ parsed = parseSseJsonRpc(text3, id);
1773
+ } else if (text3.trim()) {
1774
+ const raw = JSON.parse(text3);
1775
+ if (Array.isArray(raw)) {
1776
+ parsed = raw.find((item) => object(item) && item.id === id);
1777
+ } else if (object(raw)) {
1778
+ parsed = raw;
1779
+ }
1780
+ }
1781
+ requireThat(parsed !== void 0, `MCP \u670D\u52A1 "${this.#server.name}" \u8FD4\u56DE\u7A7A\u54CD\u5E94\uFF08${method}\uFF09\u3002`);
1782
+ if (parsed.error) throw rpcError(this.#server.name, method, parsed.error);
1783
+ return parsed.result;
1784
+ }
1785
+ async close() {
1786
+ if (this.#closed) return;
1787
+ this.#closed = true;
1788
+ if (this.#sessionId) {
1789
+ try {
1790
+ await fetch(this.#server.url, {
1791
+ method: "DELETE",
1792
+ headers: this.#headers(),
1793
+ signal: AbortSignal.timeout(3e3)
1794
+ });
1795
+ } catch {
1796
+ }
1797
+ }
1798
+ }
1799
+ };
1800
+ var WorkspaceMcpBridge = class {
1801
+ #clients = /* @__PURE__ */ new Map();
1802
+ #connecting = /* @__PURE__ */ new Map();
1803
+ #closed = false;
1804
+ #key(root, name) {
1805
+ return `${root}\0${name}`;
1806
+ }
1807
+ async #connect(root, server) {
1808
+ requireThat(!this.#closed, "Workspace MCP \u6865\u63A5\u5DF2\u5173\u95ED\u3002");
1809
+ const key = this.#key(root, server.name);
1810
+ const fingerprint = JSON.stringify(server);
1811
+ const existing = this.#clients.get(key);
1812
+ if (existing && existing.alive && existing.fingerprint === fingerprint) return existing;
1813
+ if (existing) {
1814
+ this.#clients.delete(key);
1815
+ await existing.close().catch(() => {
1816
+ });
1817
+ }
1818
+ const inflight = this.#connecting.get(key);
1819
+ if (inflight) return inflight;
1820
+ const creating = (async () => {
1821
+ const client = server.transport === "http" ? new HttpMcpClient(server, fingerprint) : new StdioMcpClient(server, fingerprint);
1822
+ try {
1823
+ await client.initialize();
1824
+ if (this.#closed) {
1825
+ await client.close();
1826
+ throw new Error("Workspace MCP \u6865\u63A5\u5DF2\u5173\u95ED\u3002");
1827
+ }
1828
+ this.#clients.set(key, client);
1829
+ return client;
1830
+ } catch (error) {
1831
+ await client.close().catch(() => {
1832
+ });
1833
+ throw error;
1834
+ }
1835
+ })();
1836
+ this.#connecting.set(key, creating);
1837
+ try {
1838
+ return await creating;
1839
+ } finally {
1840
+ if (this.#connecting.get(key) === creating) this.#connecting.delete(key);
1841
+ }
1842
+ }
1843
+ async #pruneRemoved(root, activeNames) {
1844
+ const prefix = `${root}\0`;
1845
+ const stale = [];
1846
+ for (const [key, client] of this.#clients) {
1847
+ if (!key.startsWith(prefix)) continue;
1848
+ const name = key.slice(prefix.length);
1849
+ if (!activeNames.has(name)) {
1850
+ this.#clients.delete(key);
1851
+ stale.push(client);
1852
+ }
1853
+ }
1854
+ await Promise.allSettled(stale.map((client) => client.close()));
1855
+ }
1856
+ async discover(root, serverName) {
1857
+ requireThat(!this.#closed, "Workspace MCP \u6865\u63A5\u5DF2\u5173\u95ED\u3002");
1858
+ const configuration = await readWorkspaceMcpConfig(root);
1859
+ if (configuration.error) throw new Error(configuration.error);
1860
+ const enabledNames = new Set(
1861
+ Object.entries(configuration.servers).filter(([, entry]) => entry.enabled !== false).map(([name]) => name)
1862
+ );
1863
+ await this.#pruneRemoved(root, enabledNames);
1864
+ if (!serverName) {
1865
+ const servers = Object.entries(configuration.servers).map(([name, entry]) => ({
1866
+ name,
1867
+ transport: "url" in entry ? "http" : "stdio",
1868
+ enabled: entry.enabled !== false,
1869
+ ...entry.description ? { description: entry.description } : {},
1870
+ ...entry.timeout ? { timeout: entry.timeout } : {},
1871
+ ..."url" in entry ? { url: entry.url } : { command: entry.command, args: entry.args ?? [] }
1872
+ }));
1873
+ return {
1874
+ workspace: root,
1875
+ configPath: configuration.path,
1876
+ servers
1877
+ };
1878
+ }
1879
+ const raw = Object.hasOwn(configuration.servers, serverName) ? configuration.servers[serverName] : void 0;
1880
+ requireThat(raw, `\u5DE5\u4F5C\u533A\u672A\u6CE8\u518C\u540D\u4E3A "${serverName}" \u7684 MCP \u670D\u52A1\uFF08\u5DF2\u6CE8\u518C\uFF1A${Object.keys(configuration.servers).join(", ") || "\u65E0"}\uFF09\u3002`);
1881
+ requireThat(raw.enabled !== false, `\u5DE5\u4F5C\u533A MCP \u670D\u52A1 "${serverName}" \u5F53\u524D\u5DF2\u505C\u7528\uFF08enabled: false\uFF09\u3002`);
1882
+ const resolved = resolveWorkspaceMcpServer(root, serverName, raw);
1883
+ const client = await this.#connect(root, resolved);
1884
+ const tools = [];
1885
+ let cursor;
1886
+ for (; ; ) {
1887
+ const page = await client.request("tools/list", cursor ? { cursor } : {});
1888
+ if (object(page) && Array.isArray(page.tools)) tools.push(...page.tools);
1889
+ const next = object(page) && typeof page.nextCursor === "string" && page.nextCursor ? page.nextCursor : void 0;
1890
+ if (!next) break;
1891
+ cursor = next;
1892
+ }
1893
+ return {
1894
+ workspace: root,
1895
+ server: resolved.name,
1896
+ transport: resolved.transport,
1897
+ ...resolved.description ? { description: resolved.description } : {},
1898
+ tools
1899
+ };
1900
+ }
1901
+ async call(root, serverName, toolName, args = {}) {
1902
+ requireThat(!this.#closed, "Workspace MCP \u6865\u63A5\u5DF2\u5173\u95ED\u3002");
1903
+ const configuration = await readWorkspaceMcpConfig(root);
1904
+ if (configuration.error) throw new Error(configuration.error);
1905
+ const raw = Object.hasOwn(configuration.servers, serverName) ? configuration.servers[serverName] : void 0;
1906
+ requireThat(raw, `\u5DE5\u4F5C\u533A\u672A\u6CE8\u518C\u540D\u4E3A "${serverName}" \u7684 MCP \u670D\u52A1\uFF08\u5DF2\u6CE8\u518C\uFF1A${Object.keys(configuration.servers).join(", ") || "\u65E0"}\uFF09\u3002`);
1907
+ requireThat(raw.enabled !== false, `\u5DE5\u4F5C\u533A MCP \u670D\u52A1 "${serverName}" \u5F53\u524D\u5DF2\u505C\u7528\uFF08enabled: false\uFF09\u3002`);
1908
+ const resolved = resolveWorkspaceMcpServer(root, serverName, raw);
1909
+ const client = await this.#connect(root, resolved);
1910
+ const result = await client.request("tools/call", { name: toolName, arguments: args });
1911
+ if (object(result)) {
1912
+ return {
1913
+ server: resolved.name,
1914
+ tool: toolName,
1915
+ isError: result.isError === true,
1916
+ content: Array.isArray(result.content) ? result.content : [],
1917
+ ...result.structuredContent !== void 0 ? { structuredContent: result.structuredContent } : {}
1918
+ };
1919
+ }
1920
+ return {
1921
+ server: resolved.name,
1922
+ tool: toolName,
1923
+ isError: false,
1924
+ content: result === void 0 ? [] : [{ type: "text", text: JSON.stringify(result) }]
1925
+ };
1926
+ }
1927
+ async close() {
1928
+ if (this.#closed) return;
1929
+ this.#closed = true;
1930
+ const inflight = [...this.#connecting.values()];
1931
+ this.#connecting.clear();
1932
+ await Promise.allSettled(inflight);
1933
+ const clients = [...this.#clients.values()];
1934
+ this.#clients.clear();
1935
+ await Promise.allSettled(clients.map((client) => client.close()));
1936
+ }
1937
+ };
1938
+
1939
+ // src/extension/mcp-workers.ts
1940
+ var protocolVersion2 = "2025-03-26";
1941
+ var readyTimeoutMs = 45e3;
1942
+ var defaultWaitMs = 5e4;
1943
+ var maxWaitMs = 6e5;
1944
+ var reportPageSize = 16e3;
1945
+ var progressIntervalMs = 5e3;
1946
+ var responseActions = ["accept", "decline", "cancel"];
1947
+ var discoverTargets = ["overview", "workers", "backends", "models"];
1948
+ var allMcpToolNames = [...mcpWorkerToolNames, ...workspaceMcpToolNames];
1949
+ var toolParams = {
1950
+ worker_create: /* @__PURE__ */ new Set(["backend", "model", "thinking", "cwd", "workspace"]),
1951
+ worker_close: /* @__PURE__ */ new Set(["workerId", "workspace"]),
1952
+ worker_request: /* @__PURE__ */ new Set(["workerId", "message", "waitMs", "workspace"]),
1953
+ worker_response: /* @__PURE__ */ new Set(["workerId", "action", "requestId", "optionId", "content", "waitMs", "workspace"]),
1954
+ worker_output: /* @__PURE__ */ new Set(["workerId", "offset", "waitMs", "workspace"]),
1955
+ worker_discover: /* @__PURE__ */ new Set(["target", "workerId", "backend", "model", "workspace"]),
1956
+ workspace_mcp_discover: /* @__PURE__ */ new Set(["server", "workspace"]),
1957
+ workspace_mcp_call: /* @__PURE__ */ new Set(["server", "tool", "arguments", "workspace"])
1958
+ };
1959
+ var mcpInstructions = "\u7528\u4E8E\u8DE8\u4EE3\u7406\u7A0B\u5E8F\u59D4\u6D3E\u4EFB\u52A1\uFF08worker_*\uFF09\u4E0E\u8C03\u7528\u5DE5\u4F5C\u533A\u7EDF\u4E00\u6CE8\u518C\u7684\u5916\u90E8 MCP \u670D\u52A1\uFF08workspace_mcp_*\uFF09\uFF1B\u672A\u6307\u5B9A\u5176\u4ED6\u7A0B\u5E8F\u65F6\uFF0C\u4F18\u5148\u7531\u5F53\u524D\u7A0B\u5E8F\u6216\u5176\u539F\u751F\u5B50\u4EE3\u7406\u76F4\u63A5\u5B8C\u6210\u3002\n\u8DE8\u7A0B\u5E8F\u59D4\u6D3E\uFF1Aworker_create \u521B\u5EFA worker\uFF08\u6216\u7528 worker_discover \u590D\u7528\u5DF2\u6709 worker\uFF09\u2192 worker_request \u53D1\u9001\u4EFB\u52A1\u6216\u540E\u7EED\u6D88\u606F \u2192 \u7528\u5B8C\u53EF\u7528 worker_close \u5173\u95ED\uFF1B\u540E\u53F0\u7B49\u5F85\u3001\u8D85\u65F6\u7EED\u7B49\uFF08timedOut\uFF09\u6216\u957F\u62A5\u544A\u7FFB\u9875\uFF08nextOffset\uFF09\u7528 worker_output\uFF1B\u8FD4\u56DE needsResponse \u65F6\u5411\u7528\u6237\u786E\u8BA4\u540E\u7528 worker_response \u56DE\u590D\u3002\n\u5DE5\u4F5C\u533A\u7EDF\u4E00 MCP\uFF08.pbot/mcp.json\uFF09\uFF1A\u5148\u7528 workspace_mcp_discover \u67E5\u770B\u5DF2\u6CE8\u518C\u670D\u52A1\u6216\u6307\u5B9A\u670D\u52A1\u7684\u5DE5\u5177\u6E05\u5355\uFF0C\u518D\u7528 workspace_mcp_call \u8C03\u7528\u76EE\u6807\u5DE5\u5177\uFF1B\u53EF\u4E0E\u5BBF\u4E3B\u539F\u751F MCP \u540C\u65F6\u4F7F\u7528\u3002";
1960
+ function formatBackendItem(entry, defaultBackend) {
1961
+ const tags = [];
1962
+ if (entry.label) tags.push(entry.label);
1963
+ if (entry.backend === defaultBackend) tags.push("\u5F53\u524D");
1964
+ return tags.length ? `${entry.backend}\uFF08${tags.join("\uFF0C")}\uFF09` : entry.backend;
1965
+ }
1966
+ function summarizeBackends(commands = {}, defaultBackend) {
1967
+ const entries = inspectAcpBackends(commands);
1968
+ const available = entries.filter((item) => item.available);
1969
+ const unavailable = entries.filter((item) => !item.available);
1970
+ const availableText = available.map((item) => formatBackendItem(item, defaultBackend)).join("\u3001");
1971
+ const unavailableText = unavailable.map((item) => formatBackendItem(item, defaultBackend)).join("\u3001");
1972
+ const overview = available.length ? unavailable.length ? `\u53EF\u7528 backend\uFF1A${availableText}\uFF1B\u4E0D\u53EF\u7528\uFF1A${unavailableText}\u3002` : `\u53EF\u7528 backend\uFF1A${availableText}\u3002` : `\u5F53\u524D\u65E0\u53EF\u7528 backend\uFF08\u4E0D\u53EF\u7528\uFF1A${unavailableText}\uFF09\u3002`;
1973
+ const availableIds = available.map((item) => item.backend).join("\u3001");
1974
+ return { overview, availableIds };
1975
+ }
1976
+ function workspaceProperty(workspaceBound) {
1977
+ return {
1978
+ type: "string",
1979
+ description: workspaceBound ? "\u5DE5\u4F5C\u533A\u6839\u76EE\u5F55\u7EDD\u5BF9\u8DEF\u5F84\uFF1B\u5DF2\u9ED8\u8BA4\u7ED1\u5B9A\u5F53\u524D\u5DE5\u4F5C\u533A\uFF0C\u901A\u5E38\u7701\u7565\u3002" : "\u5DE5\u4F5C\u533A\u6839\u76EE\u5F55\u7EDD\u5BF9\u8DEF\u5F84\uFF08\u4E0A\u4E0B\u6587\u63D0\u4F9B workspaceRoot \u65F6\u4F20\u8BE5\u8DEF\u5F84\uFF09\uFF1B\u5F53\u524D\u672A\u9ED8\u8BA4\u7ED1\u5B9A\uFF0C\u8BF7\u663E\u5F0F\u4F20\u5165\u3002"
1980
+ };
1981
+ }
1982
+ function buildPbotWorkerTools(commands = {}, defaultBackend, workspaceBound = false) {
1983
+ const { overview, availableIds } = summarizeBackends(commands, defaultBackend);
1984
+ const modelsBackendHint = defaultBackend ? `\u7701\u7565\u65F6\u9ED8\u8BA4\u67E5 ${defaultBackend}` : "\u5FC5\u586B";
1985
+ const workspace = workspaceProperty(workspaceBound);
1986
+ return [
1987
+ {
1988
+ name: "worker_create",
1989
+ description: "\u521B\u5EFA\u4E00\u4E2A\u65B0\u7684 worker \u5E76\u8FD4\u56DE\u5176 workerId\uFF08\u4EC5\u521B\u5EFA\uFF0C\u4E0D\u53D1\u9001\u4EFB\u52A1\uFF1B\u968F\u540E\u7528 worker_request \u6D3E\u53D1\u4EFB\u52A1\uFF09\u3002\u672A\u6307\u5B9A\u5176\u4ED6\u7A0B\u5E8F\u65F6\u4F18\u5148\u7531\u5F53\u524D\u7A0B\u5E8F\u6216\u5176\u539F\u751F\u5B50\u4EE3\u7406\u5B8C\u6210\u3002\n" + overview,
1990
+ annotations: {
1991
+ title: "Create Worker",
1992
+ readOnlyHint: false,
1993
+ destructiveHint: false,
1994
+ idempotentHint: false,
1995
+ openWorldHint: true
1996
+ },
1997
+ inputSchema: {
1998
+ type: "object",
1999
+ additionalProperties: false,
2000
+ required: ["backend"],
2001
+ properties: {
2002
+ backend: {
2003
+ type: "string",
2004
+ description: "\u76EE\u6807\u4EE3\u7406\u7A0B\u5E8F\u540D\u79F0\uFF0C\u4E0D\u533A\u5206\u5927\u5C0F\u5199\uFF0C\u652F\u6301\u5E38\u89C1\u522B\u540D\uFF08\u5982 claude-code\u3001agy\uFF09\u3002"
2005
+ },
2006
+ model: {
2007
+ type: "string",
2008
+ description: '\u4EC5\u7528\u6237\u660E\u786E\u6307\u5B9A\u6A21\u578B\u65F6\u4F20\u5165\uFF08\u652F\u6301\u6A21\u578B ID\u3001\u663E\u793A\u540D\u6216 provider/model\uFF0C\u4E0D\u533A\u5206\u5927\u5C0F\u5199\uFF09\uFF1B\u4E0D\u786E\u5B9A\u5408\u6CD5\u503C\u53EF\u7528 worker_discover(target="models") \u67E5\u8BE2\uFF1B\u7701\u7565\u5219\u4F7F\u7528\u76EE\u6807\u9ED8\u8BA4\u3002'
2009
+ },
2010
+ thinking: {
2011
+ type: "string",
2012
+ description: "\u4EC5\u7528\u6237\u660E\u786E\u6307\u5B9A\u601D\u8003\u529B\u5EA6\u65F6\u4F20\u5165\uFF08\u5982 low / medium / high / xhigh / max\uFF0C\u4E0D\u533A\u5206\u5927\u5C0F\u5199\uFF09\uFF1B\u7701\u7565\u5219\u4F7F\u7528\u76EE\u6807\u9ED8\u8BA4\u3002"
2013
+ },
2014
+ cwd: {
2015
+ type: "string",
2016
+ description: "worker \u5DE5\u4F5C\u76EE\u5F55\uFF08\u76F8\u5BF9\u5DE5\u4F5C\u533A\u6839\u76EE\u5F55\u6216\u7EDD\u5BF9\u8DEF\u5F84\uFF09\uFF0C\u9ED8\u8BA4\u4E3A\u5DE5\u4F5C\u533A\u6839\u76EE\u5F55\u3002"
2017
+ },
2018
+ workspace
2019
+ }
2020
+ }
2021
+ },
2022
+ {
2023
+ name: "worker_close",
2024
+ description: "\u5173\u95ED\u6307\u5B9A worker\u3002\u82E5\u8BE5 worker \u652F\u6301\u6062\u590D\uFF08capabilities.resume \u4E3A true\uFF09\uFF0C\u540E\u7EED\u4ECD\u53EF\u76F4\u63A5\u7528 worker_request \u7EE7\u7EED\u4F1A\u8BDD\u3002",
2025
+ annotations: {
2026
+ title: "Close Worker",
2027
+ readOnlyHint: false,
2028
+ destructiveHint: true,
2029
+ idempotentHint: true,
2030
+ openWorldHint: false
2031
+ },
2032
+ inputSchema: {
2033
+ type: "object",
2034
+ additionalProperties: false,
2035
+ required: ["workerId"],
2036
+ properties: {
2037
+ workerId: {
2038
+ type: "string",
2039
+ description: "\u8981\u5173\u95ED\u7684 worker ID\uFF08\u6765\u81EA worker_create \u6216 worker_discover\uFF09\u3002"
2040
+ },
2041
+ workspace
2042
+ }
2043
+ }
2044
+ },
2045
+ {
2046
+ name: "worker_request",
2047
+ description: `\u5411\u6307\u5B9A worker \u53D1\u9001\u4EFB\u52A1\u6216\u540E\u7EED\u6D88\u606F\uFF08\u82E5\u5DF2\u5173\u95ED\u4E14\u652F\u6301\u6062\u590D\uFF0C\u4F1A\u81EA\u52A8\u7EED\u63A5\u4F1A\u8BDD\uFF09\u3002\u9ED8\u8BA4\u6700\u591A\u7B49\u5F85 ${defaultWaitMs / 1e3} \u79D2\u8FD4\u56DE\u62A5\u544A\uFF08waitMs \u8BBE\u4E3A 0 \u7ACB\u5373\u8FD4\u56DE\u5E76\u5728\u540E\u53F0\u6267\u884C\uFF09\uFF1B\u82E5\u8FD4\u56DE timedOut \u6216\u62A5\u544A\u542B nextOffset \u7528 worker_output \u7EE7\u7EED\uFF0C\u8FD4\u56DE needsResponse \u65F6\u5411\u7528\u6237\u786E\u8BA4\u540E\u7528 worker_response \u56DE\u590D\u3002`,
2048
+ annotations: {
2049
+ title: "Send Request to Worker",
2050
+ readOnlyHint: false,
2051
+ destructiveHint: false,
2052
+ idempotentHint: false,
2053
+ openWorldHint: true
2054
+ },
2055
+ inputSchema: {
2056
+ type: "object",
2057
+ additionalProperties: false,
2058
+ required: ["workerId", "message"],
2059
+ properties: {
2060
+ workerId: {
2061
+ type: "string",
2062
+ description: "\u76EE\u6807 worker ID\uFF08\u6765\u81EA worker_create \u6216 worker_discover\uFF09\u3002"
2063
+ },
2064
+ message: {
2065
+ type: "string",
2066
+ description: "\u53D1\u7ED9 worker \u7684\u4EFB\u52A1\u8BF4\u660E\u6216\u540E\u7EED\u6D88\u606F\u3002worker \u770B\u4E0D\u5230\u5F53\u524D\u5BF9\u8BDD\u5386\u53F2\uFF0C\u9996\u6B21\u6D3E\u53D1\u65F6\u8BF7\u5199\u6E05\u76EE\u6807\u3001\u76F8\u5173\u6587\u4EF6\u8DEF\u5F84\u3001\u7EA6\u675F\u548C\u4EA4\u4ED8\u8981\u6C42\u3002"
2067
+ },
2068
+ waitMs: {
2069
+ type: "integer",
2070
+ minimum: 0,
2071
+ maximum: maxWaitMs,
2072
+ description: `\u6700\u591A\u7B49\u5F85\u7684\u6BEB\u79D2\u6570\uFF08\u9ED8\u8BA4 ${defaultWaitMs}\uFF09\uFF1B\u4F20 0 \u7ACB\u5373\u8FD4\u56DE\u5E76\u5728\u540E\u53F0\u6267\u884C\u3002`
2073
+ },
2074
+ workspace
2075
+ }
2076
+ }
2077
+ },
2078
+ {
2079
+ name: "worker_response",
2080
+ description: `\u56DE\u590D worker \u8FD4\u56DE needsResponse: true \u65F6\u7684\u5F85\u5904\u7406\u8BF7\u6C42\uFF08pendingRequests\uFF09\uFF0C\u7528\u4E8E\u6743\u9650\u5BA1\u6279\uFF08kind="permission"\uFF09\u3001\u8868\u5355\u63D0\u95EE\uFF08kind="form"\uFF09\u548C URL \u786E\u8BA4\uFF08kind="url"\uFF09\u3002\u56DE\u590D\u524D\u5148\u5411\u7528\u6237\u786E\u8BA4\uFF1B\u56DE\u590D\u540E\u9ED8\u8BA4\u6700\u591A\u7B49\u5F85 ${defaultWaitMs / 1e3} \u79D2\u8FD4\u56DE\u540E\u7EED\u7ED3\u679C\uFF08waitMs \u8BBE\u4E3A 0 \u7ACB\u5373\u8FD4\u56DE\uFF09\u3002`,
2081
+ annotations: {
2082
+ title: "Respond to Worker Request",
2083
+ readOnlyHint: false,
2084
+ destructiveHint: false,
2085
+ idempotentHint: false,
2086
+ openWorldHint: true
2087
+ },
2088
+ inputSchema: {
2089
+ type: "object",
2090
+ additionalProperties: false,
2091
+ required: ["workerId", "action"],
2092
+ properties: {
2093
+ workerId: {
2094
+ type: "string",
2095
+ description: "\u5B58\u5728\u5F85\u5904\u7406\u8BF7\u6C42\u7684 worker ID\u3002"
2096
+ },
2097
+ action: {
2098
+ type: "string",
2099
+ enum: [...responseActions],
2100
+ description: "accept\uFF1A\u540C\u610F\u6743\u9650\u3001\u63D0\u4EA4\u8868\u5355\u6216\u786E\u8BA4 URL\uFF1Bdecline\uFF1A\u62D2\u7EDD\uFF1Bcancel\uFF1A\u53D6\u6D88\u3002"
2101
+ },
2102
+ requestId: {
2103
+ type: "string",
2104
+ description: "\u5F85\u56DE\u590D\u7684 pendingRequests[].requestId\uFF1B\u4EC5\u4E00\u6761\u8BF7\u6C42\u65F6\u53EF\u7701\u7565\uFF0C\u591A\u6761\u65F6\u5FC5\u586B\u3002"
2105
+ },
2106
+ optionId: {
2107
+ type: "string",
2108
+ description: '\u4EC5 kind="permission" \u4E14 action \u4E0D\u4E3A cancel \u65F6\u53EF\u7528\uFF1A\u6307\u5B9A pendingRequests[].options[].optionId\uFF08\u7701\u7565\u65F6\u9ED8\u8BA4\u5355\u6B21\u5141\u8BB8\u6216\u62D2\u7EDD\uFF09\u3002'
2109
+ },
2110
+ content: {
2111
+ type: "object",
2112
+ additionalProperties: true,
2113
+ description: '\u4EC5 kind="form" \u4E14 action="accept" \u65F6\u53EF\u7528\uFF1A\u6309 pendingRequests[].schema.properties \u586B\u5199\u7684\u7B54\u6848\u5BF9\u8C61\uFF08\u5B57\u6BB5\u503C\u652F\u6301\u5B57\u7B26\u4E32\u3001\u6570\u5B57\u3001\u5E03\u5C14\u6216\u5B57\u7B26\u4E32\u6570\u7EC4\uFF09\u3002'
2114
+ },
2115
+ waitMs: {
2116
+ type: "integer",
2117
+ minimum: 0,
2118
+ maximum: maxWaitMs,
2119
+ description: `\u56DE\u590D\u540E\u6700\u591A\u7B49\u5F85\u7684\u6BEB\u79D2\u6570\uFF08\u9ED8\u8BA4 ${defaultWaitMs}\uFF09\uFF1B\u4F20 0 \u7ACB\u5373\u8FD4\u56DE\u3002`
2120
+ },
2121
+ workspace
2122
+ }
2123
+ }
2124
+ },
2125
+ {
2126
+ name: "worker_output",
2127
+ description: "\u83B7\u53D6\u6307\u5B9A worker \u6700\u65B0\u4E00\u8F6E\u7684\u6267\u884C\u62A5\u544A\uFF1A\u4ECD\u5728\u8FD0\u884C\u65F6\u7B49\u5F85\u5176\u5B8C\u6210\uFF08\u4E5F\u53EF\u80FD\u8FD4\u56DE timedOut \u6216 needsResponse\uFF09\uFF0C\u5DF2\u7ED3\u675F\u5219\u7ACB\u5373\u8FD4\u56DE\uFF1B\u62A5\u544A\u542B nextOffset \u65F6\u4F20\u5165 offset \u7FFB\u9875\u7EED\u8BFB\u3002",
2128
+ annotations: {
2129
+ title: "Get Worker Output",
2130
+ readOnlyHint: true,
2131
+ destructiveHint: false,
2132
+ idempotentHint: true,
2133
+ openWorldHint: false
2134
+ },
2135
+ inputSchema: {
2136
+ type: "object",
2137
+ additionalProperties: false,
2138
+ required: ["workerId"],
2139
+ properties: {
2140
+ workerId: {
2141
+ type: "string",
2142
+ description: "\u8981\u7B49\u5F85\u6216\u8BFB\u53D6\u62A5\u544A\u7684 worker ID\u3002"
2143
+ },
2144
+ offset: {
2145
+ type: "integer",
2146
+ minimum: 0,
2147
+ description: "\u62A5\u544A\u5B57\u7B26\u504F\u79FB\u91CF\uFF08\u9ED8\u8BA4 0\uFF09\uFF1B\u7FFB\u9875\u7EED\u8BFB\u65F6\u4F20\u4E0A\u6B21\u8FD4\u56DE\u7684 nextOffset\u3002"
2148
+ },
2149
+ waitMs: {
2150
+ type: "integer",
2151
+ minimum: 0,
2152
+ maximum: maxWaitMs,
2153
+ description: `\u4EFB\u52A1\u4ECD\u5728\u8FD0\u884C\u65F6\u6700\u591A\u7B49\u5F85\u7684\u6BEB\u79D2\u6570\uFF08\u9ED8\u8BA4 ${defaultWaitMs}\uFF09\uFF1B\u5DF2\u7ED3\u675F\u6216\u7FFB\u9875\u65F6\u7ACB\u5373\u8FD4\u56DE\u3002`
2154
+ },
2155
+ workspace
2156
+ }
2157
+ }
2158
+ },
2159
+ {
2160
+ name: "worker_discover",
2161
+ description: '\u67E5\u8BE2\u53EF\u7528 backend\u3001\u5F53\u524D\u4F1A\u8BDD\u5DF2\u6709 worker \u7684\u72B6\u6001\uFF0C\u6216\u6307\u5B9A backend \u53EF\u9009\u7684\u6A21\u578B\u4E0E\u601D\u8003\u529B\u5EA6\u3002\u9ED8\u8BA4\uFF08target="overview"\uFF09\u8FD4\u56DE\u53EF\u7528 backend \u4E0E\u5DF2\u6709 worker\uFF1B\u4EC5\u9700\u786E\u8BA4\u6A21\u578B\u6216\u601D\u8003\u529B\u5EA6\u53EF\u9009\u503C\u65F6\u518D\u67E5 target="models"\uFF08\u8017\u65F6\u8F83\u957F\uFF09\u3002',
2162
+ annotations: {
2163
+ title: "Discover Workers, Backends & Models",
2164
+ readOnlyHint: true,
2165
+ destructiveHint: false,
2166
+ idempotentHint: true,
2167
+ openWorldHint: false
2168
+ },
2169
+ inputSchema: {
2170
+ type: "object",
2171
+ additionalProperties: false,
2172
+ required: [],
2173
+ properties: {
2174
+ target: {
2175
+ type: "string",
2176
+ enum: [...discoverTargets],
2177
+ description: '\u67E5\u8BE2\u8303\u56F4\uFF0C\u9ED8\u8BA4 "overview"\uFF08\u540C\u65F6\u8FD4\u56DE backends \u4E0E workers\uFF09\uFF1B"workers" \u67E5\u5168\u90E8\u6216\u5355\u4E2A worker \u72B6\u6001\uFF1B"backends" \u67E5\u53EF\u7528 backend \u5217\u8868\uFF1B"models" \u67E5\u6307\u5B9A backend \u7684\u53EF\u9009\u6A21\u578B\u4E0E\u601D\u8003\u529B\u5EA6\u3002'
2178
+ },
2179
+ workerId: {
2180
+ type: "string",
2181
+ description: '\u4EC5 target="workers" \u53EF\u7528\uFF1A\u6307\u5B9A\u5355\u4E2A worker ID\uFF1B\u7701\u7565\u65F6\u5217\u51FA\u5168\u90E8\u3002'
2182
+ },
2183
+ backend: {
2184
+ type: "string",
2185
+ description: availableIds ? `\u4EC5 target="models" \u53EF\u7528\uFF08${modelsBackendHint}\uFF09\uFF1A\u76EE\u6807\u4EE3\u7406\u7A0B\u5E8F\u540D\u79F0\uFF0C\u652F\u6301\u5E38\u89C1\u522B\u540D\uFF1B\u53EF\u7528\uFF1A${availableIds}\u3002` : `\u4EC5 target="models" \u53EF\u7528\uFF08${modelsBackendHint}\uFF09\uFF1A\u76EE\u6807\u4EE3\u7406\u7A0B\u5E8F\u540D\u79F0\uFF0C\u652F\u6301\u5E38\u89C1\u522B\u540D\u3002`
2186
+ },
2187
+ model: {
2188
+ type: "string",
2189
+ description: '\u4EC5 target="models" \u53EF\u7528\uFF1A\u6307\u5B9A\u6A21\u578B\u4EE5\u67E5\u8BE2\u8BE5\u6A21\u578B\u652F\u6301\u7684\u601D\u8003\u529B\u5EA6\u9009\u9879\u3002'
2190
+ },
2191
+ workspace
2192
+ }
2193
+ }
2194
+ }
2195
+ ];
2196
+ }
2197
+ function buildWorkspaceMcpTools(workspaceBound = false) {
2198
+ const workspace = workspaceProperty(workspaceBound);
2199
+ return [
2200
+ {
2201
+ name: "workspace_mcp_discover",
2202
+ description: "\u67E5\u770B\u5DE5\u4F5C\u533A .pbot/mcp.json \u4E2D\u7EDF\u4E00\u6CE8\u518C\u7684 MCP \u670D\u52A1\u5217\u8868\uFF1B\u4F20\u5165 server \u65F6\u6309\u9700\u8FDE\u63A5\u8BE5\u670D\u52A1\u5E76\u8FD4\u56DE\u5176\u5168\u90E8\u5DE5\u5177\u53CA\u53C2\u6570 schema\u3002",
2203
+ annotations: {
2204
+ title: "Discover Workspace MCP Servers & Tools",
2205
+ readOnlyHint: true,
2206
+ destructiveHint: false,
2207
+ idempotentHint: true,
2208
+ openWorldHint: true
2209
+ },
2210
+ inputSchema: {
2211
+ type: "object",
2212
+ additionalProperties: false,
2213
+ required: [],
2214
+ properties: {
2215
+ server: {
2216
+ type: "string",
2217
+ description: "\u76EE\u6807 MCP \u670D\u52A1\u540D\uFF08\u6765\u81EA .pbot/mcp.json \u7684\u952E\u540D\uFF09\uFF1B\u7701\u7565\u65F6\u4EC5\u5217\u51FA\u5DF2\u6CE8\u518C\u670D\u52A1\u6458\u8981\u3002"
2218
+ },
2219
+ workspace
2220
+ }
2221
+ }
2222
+ },
2223
+ {
2224
+ name: "workspace_mcp_call",
2225
+ description: "\u8C03\u7528\u5DE5\u4F5C\u533A .pbot/mcp.json \u4E2D\u6307\u5B9A MCP \u670D\u52A1\u7684\u5DE5\u5177\uFF08\u9996\u6B21\u8C03\u7528\u6309\u9700\u8FDE\u63A5\u5E76\u590D\u7528\u8FDE\u63A5\uFF0C\u914D\u7F6E\u53D8\u66F4\u81EA\u52A8\u70ED\u66F4\u65B0\uFF09\u3002\u4E0D\u786E\u5B9A\u5DE5\u5177\u540D\u6216\u53C2\u6570 schema \u65F6\uFF0C\u5148\u7528 workspace_mcp_discover(server) \u67E5\u8BE2\u3002",
2226
+ annotations: {
2227
+ title: "Call Workspace MCP Tool",
2228
+ readOnlyHint: false,
2229
+ destructiveHint: false,
2230
+ idempotentHint: false,
2231
+ openWorldHint: true
2232
+ },
2233
+ inputSchema: {
2234
+ type: "object",
2235
+ additionalProperties: false,
2236
+ required: ["server", "tool"],
2237
+ properties: {
2238
+ server: {
2239
+ type: "string",
2240
+ description: "\u76EE\u6807 MCP \u670D\u52A1\u540D\uFF08\u6765\u81EA .pbot/mcp.json\uFF09\u3002"
2241
+ },
2242
+ tool: {
2243
+ type: "string",
2244
+ description: "\u8981\u8C03\u7528\u7684\u4E0B\u6E38 MCP \u5DE5\u5177\u540D\u79F0\u3002"
2245
+ },
2246
+ arguments: {
2247
+ type: "object",
2248
+ additionalProperties: true,
2249
+ description: "\u4F20\u9012\u7ED9\u4E0B\u6E38 MCP \u5DE5\u5177\u7684\u53C2\u6570\u5BF9\u8C61\uFF0C\u7701\u7565\u65F6\u4E3A\u7A7A\u5BF9\u8C61\u3002"
2250
+ },
2251
+ workspace
2252
+ }
2253
+ }
2254
+ }
2255
+ ];
2256
+ }
2257
+ var pbotWorkerTools = buildPbotWorkerTools();
2258
+ function defaultWorkerDirectory() {
2259
+ if (process.env.PBOT_MCP_AGENT_DIR) return process.env.PBOT_MCP_AGENT_DIR;
2260
+ if (process.env.PLUGIN_DATA) return join10(process.env.PLUGIN_DATA, "subagents");
2261
+ return join10(homedir(), ".pbot/subagents");
2262
+ }
2263
+ function isKnownTool(name) {
2264
+ return allMcpToolNames.includes(name);
2265
+ }
2266
+ function rejectUnknownParams(tool, rawArgs) {
2267
+ const allowed = toolParams[tool];
2268
+ const unknown = Object.entries(rawArgs).filter(([key, value]) => value !== void 0 && !allowed.has(key)).map(([key]) => key);
2269
+ requireThat(unknown.length === 0, `\u672A\u77E5\u53C2\u6570\uFF1A${unknown.join(", ")}\uFF08${tool} \u53EF\u7528\u53C2\u6570\uFF1A${[...allowed].join(", ")}\uFF09\u3002`);
2270
+ }
2271
+ function asString(args, key, required = false) {
2272
+ const value = args[key];
2273
+ if (value === void 0 || value === null) {
2274
+ requireThat(!required, `\u7F3A\u5C11\u5FC5\u586B\u53C2\u6570\uFF1A${key}`);
2275
+ return void 0;
2276
+ }
2277
+ requireThat(typeof value === "string" && value.length > 0, `\u53C2\u6570 ${key} \u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32\u3002`);
2278
+ return value;
2279
+ }
2280
+ function asInt(args, key, min, max) {
2281
+ const value = args[key];
2282
+ if (value === void 0 || value === null) return void 0;
2283
+ requireThat(
2284
+ typeof value === "number" && Number.isInteger(value) && value >= min && value <= max,
2285
+ `\u53C2\u6570 ${key} \u5FC5\u987B\u662F ${min}\u2013${max} \u7684\u6574\u6570\u3002`
2286
+ );
2287
+ return value;
2288
+ }
2289
+ function asContent(args, key) {
2290
+ const value = args[key];
2291
+ if (value === void 0 || value === null) return void 0;
2292
+ requireThat(object(value), `\u53C2\u6570 ${key} \u5FC5\u987B\u662F JSON \u5BF9\u8C61\u3002`);
2293
+ for (const [field, entry] of Object.entries(value)) {
2294
+ const valid = typeof entry === "string" || typeof entry === "number" && Number.isFinite(entry) || typeof entry === "boolean" || Array.isArray(entry) && entry.every((item) => typeof item === "string");
2295
+ requireThat(valid, `\u53C2\u6570 ${key}.${field} \u5FC5\u987B\u662F\u5B57\u7B26\u4E32\u3001\u6570\u5B57\u3001\u5E03\u5C14\u503C\u6216\u5B57\u7B26\u4E32\u6570\u7EC4\u3002`);
2296
+ }
2297
+ return value;
2298
+ }
2299
+ function presentCycle(cycle2) {
2300
+ return {
2301
+ state: cycle2.state,
2302
+ ...cycle2.error ? { error: cycle2.error } : {}
2303
+ };
2304
+ }
2305
+ function presentSelection(selection) {
2306
+ if (!selection) return void 0;
2307
+ const entries = Object.entries(selection).filter(([, value]) => value !== void 0);
2308
+ return entries.length ? Object.fromEntries(entries) : void 0;
2309
+ }
2310
+ function presentWorker(value) {
2311
+ const selection = presentSelection(value.selection);
2312
+ const truncated = value.nextOffset !== void 0 && value.nextOffset !== null;
2313
+ return {
2314
+ workerId: value.agentId,
2315
+ backend: value.backend,
2316
+ state: value.state,
2317
+ activity: value.activity,
2318
+ alive: value.alive,
2319
+ ...selection ? { selection } : {},
2320
+ ...value.pendingRequests?.length ? { pendingRequests: value.pendingRequests } : {},
2321
+ ...value.cycle ? { cycle: presentCycle(value.cycle) } : {},
2322
+ ...value.report !== void 0 ? { report: value.report } : {},
2323
+ ...truncated ? { totalLength: value.totalLength, nextOffset: value.nextOffset } : {},
2324
+ ...value.error ? { error: value.error } : {}
2325
+ };
2326
+ }
2327
+ var McpWorkerRuntime = class {
2328
+ #services = /* @__PURE__ */ new Map();
2329
+ #bridge = new WorkspaceMcpBridge();
2330
+ #sessionId;
2331
+ #directory;
2332
+ #defaultBackend;
2333
+ #closed = false;
2334
+ constructor(directory = defaultWorkerDirectory(), sessionId = process.env.PBOT_MCP_SESSION_ID || "mcp-" + randomUUID4(), defaultBackend = process.env.PBOT_HOST || void 0) {
2335
+ this.#directory = directory;
2336
+ this.#sessionId = sessionId;
2337
+ this.#defaultBackend = defaultBackend?.trim() || void 0;
2338
+ }
2339
+ resolveBackend(rawArgs, commands, allowDefault) {
2340
+ const raw = asString(rawArgs, "backend") ?? (allowDefault ? this.#defaultBackend : void 0);
2341
+ requireThat(raw, `\u7F3A\u5C11\u5FC5\u586B\u53C2\u6570\uFF1Abackend\uFF08\u8BF7\u6307\u5B9A\u76EE\u6807\u7A0B\u5E8F\uFF1A${knownAcpBackends(commands).join(", ")}\uFF09\u3002`);
2342
+ const backend = canonicalAcpBackend(raw, commands);
2343
+ requireThat(isAcpBackend(backend), "\u65E0\u6548\u7684 backend \u540D\u79F0\uFF1A" + raw);
2344
+ return backend;
2345
+ }
2346
+ async resolveWorkspace(supplied) {
2347
+ const target = supplied || process.env.CLAUDE_PROJECT_DIR || process.env.PBOT_WORKSPACE_ROOT || process.cwd();
2348
+ requireThat(isAbsolute3(target), "\u5DE5\u4F5C\u533A\u9700\u8981\u7EDD\u5BF9\u8DEF\u5F84\u3002");
2349
+ const root = await realpath(target);
2350
+ requireThat((await stat(root)).isDirectory(), "\u5DE5\u4F5C\u533A\u8DEF\u5F84\u4E0D\u662F\u76EE\u5F55\u3002");
2351
+ return root;
2352
+ }
2353
+ async workspace(supplied) {
2354
+ requireThat(!this.#closed, "Personal Bot MCP \u670D\u52A1\u5DF2\u5173\u95ED\u3002");
2355
+ const root = await this.resolveWorkspace(supplied);
2356
+ const configuration = await readWorkspaceConfig(root);
2357
+ requireThat(configuration.enabled, workspaceDisabledMessage(configuration));
2358
+ let entry = this.#services.get(root);
2359
+ if (!entry) {
2360
+ const host = new AcpWorkerHost(this.#directory, configuration.acp);
2361
+ entry = {
2362
+ host,
2363
+ service: new AgentService(root, this.#directory, host),
2364
+ owner: { sessionId: this.#sessionId, leaf: null, branch: [] }
2365
+ };
2366
+ this.#services.set(root, entry);
2367
+ } else {
2368
+ Object.assign(entry.host, { commands: configuration.acp ?? {} });
2369
+ }
2370
+ return { root, configuration, ...entry };
2371
+ }
2372
+ async toolDefinitions() {
2373
+ let commands;
2374
+ let includeWorkspaceMcp = true;
2375
+ try {
2376
+ const root = await this.resolveWorkspace();
2377
+ const configuration = await readWorkspaceConfig(root);
2378
+ if (configuration.enabled) {
2379
+ commands = configuration.acp;
2380
+ includeWorkspaceMcp = workspaceFeatures(configuration).mcp;
2381
+ }
2382
+ } catch {
2383
+ }
2384
+ const defaultBackend = this.#defaultBackend ? canonicalAcpBackend(this.#defaultBackend, commands) : void 0;
2385
+ const workspaceBound = Boolean(process.env.CLAUDE_PROJECT_DIR || process.env.PBOT_WORKSPACE_ROOT);
2386
+ return [
2387
+ ...buildPbotWorkerTools(commands, defaultBackend, workspaceBound),
2388
+ ...includeWorkspaceMcp ? buildWorkspaceMcpTools(workspaceBound) : []
2389
+ ];
2390
+ }
2391
+ /** Wait until ACP handshake and model/thinking configuration finish so invalid options fail synchronously on create/resume. */
2392
+ async waitReady(service, owner, workerId, timeoutMs, progress) {
2393
+ const deadline = Date.now() + timeoutMs;
2394
+ let lastProgressAt = 0;
2395
+ let lastMarker = "";
2396
+ for (; ; ) {
2397
+ requireThat(!this.#closed, "Personal Bot MCP \u670D\u52A1\u5DF2\u5173\u95ED\u3002");
2398
+ const current = service.status(workerId, owner);
2399
+ if (current.state === "error" || current.state === "stopped") {
2400
+ throw new Error(current.error || "worker \u542F\u52A8\u5931\u8D25\u3002");
2401
+ }
2402
+ if (current.state === "idle" || current.state === "busy") return current;
2403
+ if (Date.now() >= deadline) return current;
2404
+ if (progress) {
2405
+ const marker = `${current.state}:${current.activity}`;
2406
+ const now = Date.now();
2407
+ if (marker !== lastMarker || now - lastProgressAt >= progressIntervalMs) {
2408
+ lastMarker = marker;
2409
+ lastProgressAt = now;
2410
+ progress(`${current.backend}: ${current.activity}`);
2411
+ }
2412
+ }
2413
+ await delay3(50);
2414
+ }
2415
+ }
2416
+ async waitFor(service, owner, workerId, requestId, timeoutMs, offset = 0, progress) {
2417
+ const deadline = Date.now() + timeoutMs;
2418
+ let lastProgressAt = 0;
2419
+ let lastMarker = "";
2420
+ for (; ; ) {
2421
+ requireThat(!this.#closed, "Personal Bot MCP \u670D\u52A1\u5DF2\u5173\u95ED\u3002");
2422
+ const current = service.status(workerId, owner);
2423
+ const cycles = service.cycles(workerId, owner);
2424
+ const latestRequest = requestId ?? service.files.messages(workerId).filter((item) => item.generation === current.generation).at(-1)?.requestId;
2425
+ const targetCycle = latestRequest ? cycles.find((item) => item.generation === current.generation && item.requestIds.includes(latestRequest)) : current.cycle ?? cycles.at(-1);
2426
+ const settled = targetCycle && targetCycle.state !== "running";
2427
+ const terminalWithoutCycle = !latestRequest && (current.state === "stopped" || current.state === "error" || current.state === "idle" && !targetCycle);
2428
+ const failedBeforeCycle = Boolean(latestRequest && !targetCycle && (current.state === "stopped" || current.state === "error"));
2429
+ if (settled) {
2430
+ const page = await service.read(workerId, owner, targetCycle.cycleId, offset, reportPageSize);
2431
+ return { settled: true, ...presentWorker(page) };
2432
+ }
2433
+ if (terminalWithoutCycle || failedBeforeCycle) {
2434
+ if (offset > 0) await service.read(workerId, owner, void 0, offset, reportPageSize);
2435
+ return { settled: true, ...presentWorker(current) };
2436
+ }
2437
+ if (current.pendingRequests?.length) {
2438
+ return {
2439
+ settled: false,
2440
+ needsResponse: true,
2441
+ ...presentWorker(current)
2442
+ };
2443
+ }
2444
+ if (Date.now() >= deadline) {
2445
+ return { settled: false, timedOut: true, ...presentWorker(current) };
2446
+ }
2447
+ if (progress) {
2448
+ const marker = `${current.state}:${current.activity}`;
2449
+ const now = Date.now();
2450
+ if (marker !== lastMarker || now - lastProgressAt >= progressIntervalMs) {
2451
+ lastMarker = marker;
2452
+ lastProgressAt = now;
2453
+ progress(`${current.backend}: ${current.activity}`);
2454
+ }
2455
+ }
2456
+ await delay3(100);
2457
+ }
2458
+ }
2459
+ async callTool(name, rawArgs, progress) {
2460
+ requireThat(isKnownTool(name), `\u672A\u77E5\u5DE5\u5177\uFF1A${name}\uFF08\u53EF\u7528\uFF1A${allMcpToolNames.join(", ")}\uFF09\u3002`);
2461
+ requireThat(object(rawArgs), "\u5DE5\u5177\u53C2\u6570\u5FC5\u987B\u662F\u5BF9\u8C61\u3002");
2462
+ rejectUnknownParams(name, rawArgs);
2463
+ const { root, configuration, host, service, owner } = await this.workspace(asString(rawArgs, "workspace"));
2464
+ switch (name) {
2465
+ case "workspace_mcp_discover": {
2466
+ requireThat(workspaceFeatures(configuration).mcp, `\u5DE5\u4F5C\u533A\u7EDF\u4E00 MCP \u529F\u80FD\u5DF2\u5728 ${configuration.path} \u4E2D\u505C\u7528\uFF08features.mcp: false\uFF09\u3002`);
2467
+ const server = asString(rawArgs, "server");
2468
+ return this.#bridge.discover(root, server);
2469
+ }
2470
+ case "workspace_mcp_call": {
2471
+ requireThat(workspaceFeatures(configuration).mcp, `\u5DE5\u4F5C\u533A\u7EDF\u4E00 MCP \u529F\u80FD\u5DF2\u5728 ${configuration.path} \u4E2D\u505C\u7528\uFF08features.mcp: false\uFF09\u3002`);
2472
+ const server = asString(rawArgs, "server", true);
2473
+ const tool = asString(rawArgs, "tool", true);
2474
+ const toolArgs = rawArgs.arguments === void 0 ? {} : rawArgs.arguments;
2475
+ requireThat(object(toolArgs), "\u53C2\u6570 arguments \u5FC5\u987B\u662F JSON \u5BF9\u8C61\u3002");
2476
+ return this.#bridge.call(root, server, tool, toolArgs);
2477
+ }
2478
+ case "worker_create": {
2479
+ const backend = this.resolveBackend(rawArgs, configuration.acp, false);
2480
+ const model = asString(rawArgs, "model");
2481
+ const thinking = asString(rawArgs, "thinking");
2482
+ const cwd = asString(rawArgs, "cwd");
2483
+ const created = await service.start({
2484
+ backend,
2485
+ ...model ? { model } : {},
2486
+ ...thinking ? { thinking } : {},
2487
+ ...cwd ? { cwd } : {}
2488
+ }, owner);
2489
+ const ready = await this.waitReady(service, owner, created.agentId, readyTimeoutMs, progress);
2490
+ return {
2491
+ ...presentWorker(ready),
2492
+ capabilities: { resume: ready.capabilities.resume }
2493
+ };
2494
+ }
2495
+ case "worker_close":
2496
+ return presentWorker(service.stop(asString(rawArgs, "workerId", true), owner));
2497
+ case "worker_request": {
2498
+ const workerId = asString(rawArgs, "workerId", true);
2499
+ const message2 = asString(rawArgs, "message", true);
2500
+ const waitMs = asInt(rawArgs, "waitMs", 0, maxWaitMs) ?? defaultWaitMs;
2501
+ const current = service.status(workerId, owner);
2502
+ requireThat(current.state !== "stopping", "worker \u6B63\u5728\u505C\u6B62\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002");
2503
+ if (current.alive) {
2504
+ const sent = service.send(workerId, message2, "followUp", owner);
2505
+ if (waitMs > 0) return this.waitFor(service, owner, workerId, sent.requestId, waitMs, 0, progress);
2506
+ return presentWorker(sent);
2507
+ }
2508
+ const startedAt = Date.now();
2509
+ const resumed = await service.resume(workerId, message2, owner);
2510
+ const ready = await this.waitReady(service, owner, workerId, waitMs > 0 ? Math.min(waitMs, readyTimeoutMs) : readyTimeoutMs, progress);
2511
+ if (waitMs > 0 && resumed.requestId) {
2512
+ const remaining = Math.max(0, waitMs - (Date.now() - startedAt));
2513
+ return this.waitFor(service, owner, workerId, resumed.requestId, remaining, 0, progress);
2514
+ }
2515
+ return {
2516
+ ...presentWorker(ready),
2517
+ ...ready.pendingRequests?.length ? { settled: false, needsResponse: true } : {}
2518
+ };
2519
+ }
2520
+ case "worker_response": {
2521
+ const workerId = asString(rawArgs, "workerId", true);
2522
+ const rawAction = asString(rawArgs, "action", true);
2523
+ requireThat(
2524
+ responseActions.includes(rawAction),
2525
+ `\u53C2\u6570 action \u65E0\u6548\uFF1A${rawAction}\uFF08\u53EF\u7528\uFF1A${responseActions.join(", ")}\uFF09\u3002`
2526
+ );
2527
+ const action = rawAction;
2528
+ const requestId = asString(rawArgs, "requestId");
2529
+ const optionId = asString(rawArgs, "optionId");
2530
+ const content = asContent(rawArgs, "content");
2531
+ const waitMs = asInt(rawArgs, "waitMs", 0, maxWaitMs) ?? defaultWaitMs;
2532
+ const updated = service.respond(workerId, {
2533
+ action,
2534
+ ...requestId ? { requestId } : {},
2535
+ ...optionId ? { optionId } : {},
2536
+ ...content !== void 0 ? { content } : {}
2537
+ }, owner);
2538
+ if (waitMs > 0) return this.waitFor(service, owner, workerId, void 0, waitMs, 0, progress);
2539
+ return presentWorker(updated);
2540
+ }
2541
+ case "worker_output": {
2542
+ const workerId = asString(rawArgs, "workerId", true);
2543
+ const offset = asInt(rawArgs, "offset", 0, 1e7) ?? 0;
2544
+ const waitMs = asInt(rawArgs, "waitMs", 0, maxWaitMs) ?? defaultWaitMs;
2545
+ return this.waitFor(service, owner, workerId, void 0, waitMs, offset, progress);
2546
+ }
2547
+ case "worker_discover": {
2548
+ const rawTarget = asString(rawArgs, "target") ?? "overview";
2549
+ requireThat(
2550
+ discoverTargets.includes(rawTarget),
2551
+ `\u53C2\u6570 target \u65E0\u6548\uFF1A${rawTarget}\uFF08\u53EF\u7528\uFF1A${discoverTargets.join(", ")}\uFF09\u3002`
2552
+ );
2553
+ const target = rawTarget;
2554
+ const workerId = asString(rawArgs, "workerId");
2555
+ const backendRaw = asString(rawArgs, "backend");
2556
+ const model = asString(rawArgs, "model");
2557
+ if (target !== "workers") {
2558
+ requireThat(workerId === void 0, '\u53C2\u6570 workerId \u4EC5\u5728 target="workers" \u65F6\u53EF\u7528\u3002');
2559
+ }
2560
+ if (target !== "models") {
2561
+ requireThat(backendRaw === void 0 && model === void 0, '\u53C2\u6570 backend / model \u4EC5\u5728 target="models" \u65F6\u53EF\u7528\u3002');
2562
+ }
2563
+ if (target === "overview") {
2564
+ return {
2565
+ target,
2566
+ backends: inspectAcpBackends(configuration.acp),
2567
+ workers: service.list(owner).map(presentWorker)
2568
+ };
2569
+ }
2570
+ if (target === "backends") {
2571
+ return { target, backends: inspectAcpBackends(configuration.acp) };
2572
+ }
2573
+ if (target === "workers") {
2574
+ return {
2575
+ target,
2576
+ workers: workerId ? [presentWorker(service.status(workerId, owner))] : service.list(owner).map(presentWorker)
2577
+ };
2578
+ }
2579
+ const backend = this.resolveBackend(rawArgs, configuration.acp, true);
2580
+ return {
2581
+ target,
2582
+ ...await host.inspectModels(backend, root, { ...model ? { model } : {} })
2583
+ };
2584
+ }
2585
+ }
2586
+ }
2587
+ async close(preserve = false) {
2588
+ if (this.#closed) return;
2589
+ this.#closed = true;
2590
+ const entries = [...this.#services.values()];
2591
+ this.#services.clear();
2592
+ await Promise.allSettled([
2593
+ this.#bridge.close(),
2594
+ ...entries.map(({ service, owner }) => service.close(owner, preserve))
2595
+ ]);
2596
+ }
2597
+ };
2598
+ async function handleMcpRequest(runtime, message2, notify) {
2599
+ if (!object(message2) || message2.jsonrpc !== "2.0" || typeof message2.method !== "string") {
2600
+ return { jsonrpc: "2.0", id: null, error: { code: -32600, message: "Invalid JSON-RPC request" } };
2601
+ }
2602
+ const hasId = Object.hasOwn(message2, "id") && message2.id !== void 0;
2603
+ const id = hasId ? message2.id : null;
2604
+ if (!hasId) return null;
2605
+ try {
2606
+ if (message2.method === "initialize") {
2607
+ const requested = object(message2.params) && typeof message2.params.protocolVersion === "string" ? message2.params.protocolVersion : protocolVersion2;
2608
+ return {
2609
+ jsonrpc: "2.0",
2610
+ id,
2611
+ result: {
2612
+ protocolVersion: requested || protocolVersion2,
2613
+ capabilities: { tools: {} },
2614
+ serverInfo: { name: "personal-bot", version: packageVersion },
2615
+ instructions: mcpInstructions
2616
+ }
2617
+ };
2618
+ }
2619
+ if (message2.method === "ping") return { jsonrpc: "2.0", id, result: {} };
2620
+ if (message2.method === "tools/list") {
2621
+ return { jsonrpc: "2.0", id, result: { tools: await runtime.toolDefinitions() } };
2622
+ }
2623
+ if (message2.method === "tools/call") {
2624
+ requireThat(object(message2.params) && typeof message2.params.name === "string", "tools/call \u7F3A\u5C11 name\u3002");
2625
+ const meta = object(message2.params._meta) ? message2.params._meta : void 0;
2626
+ const progressToken = meta && (typeof meta.progressToken === "string" || typeof meta.progressToken === "number") ? meta.progressToken : void 0;
2627
+ let progressStep = 0;
2628
+ const progress = progressToken !== void 0 && notify ? (statusMessage) => {
2629
+ progressStep++;
2630
+ notify({
2631
+ jsonrpc: "2.0",
2632
+ method: "notifications/progress",
2633
+ params: { progressToken, progress: progressStep, message: statusMessage }
2634
+ });
2635
+ } : void 0;
2636
+ try {
2637
+ const result = await runtime.callTool(message2.params.name, message2.params.arguments ?? {}, progress);
2638
+ return {
2639
+ jsonrpc: "2.0",
2640
+ id,
2641
+ result: {
2642
+ content: [{ type: "text", text: JSON.stringify(result, null, 2) }]
2643
+ }
2644
+ };
2645
+ } catch (error) {
2646
+ return {
2647
+ jsonrpc: "2.0",
2648
+ id,
2649
+ result: {
2650
+ isError: true,
2651
+ content: [{ type: "text", text: error instanceof Error ? error.message : String(error) }]
2652
+ }
2653
+ };
2654
+ }
2655
+ }
2656
+ return { jsonrpc: "2.0", id, error: { code: -32601, message: "Method not found: " + message2.method } };
2657
+ } catch (error) {
2658
+ return { jsonrpc: "2.0", id, error: { code: -32603, message: error instanceof Error ? error.message : String(error) } };
2659
+ }
2660
+ }
2661
+ async function serveMcpStdio(runtime = new McpWorkerRuntime()) {
2662
+ const shutdown = () => {
2663
+ void runtime.close().finally(() => process.exit(0));
2664
+ };
2665
+ process.on("SIGTERM", shutdown);
2666
+ process.on("SIGINT", shutdown);
2667
+ let buffer = "";
2668
+ const pending = /* @__PURE__ */ new Set();
2669
+ const write = (value) => {
2670
+ process.stdout.write(JSON.stringify(value) + "\n");
2671
+ };
2672
+ process.stdin.setEncoding("utf8");
2673
+ for await (const chunk of process.stdin) {
2674
+ buffer += String(chunk);
2675
+ for (; ; ) {
2676
+ const nl = buffer.indexOf("\n");
2677
+ if (nl < 0) break;
2678
+ const line = buffer.slice(0, nl).trim();
2679
+ buffer = buffer.slice(nl + 1);
2680
+ if (!line) continue;
2681
+ let parsed;
2682
+ try {
2683
+ parsed = JSON.parse(line);
2684
+ } catch {
2685
+ write({ jsonrpc: "2.0", id: null, error: { code: -32700, message: "Parse error" } });
2686
+ continue;
2687
+ }
2688
+ const task = handleMcpRequest(runtime, parsed, write).then((reply) => {
2689
+ if (reply) write(reply);
2690
+ }).catch((error) => {
2691
+ const id = object(parsed) && Object.hasOwn(parsed, "id") && parsed.id !== void 0 ? parsed.id : null;
2692
+ if (id !== null) write({ jsonrpc: "2.0", id, error: { code: -32603, message: error instanceof Error ? error.message : String(error) } });
2693
+ }).finally(() => {
2694
+ pending.delete(task);
2695
+ });
2696
+ pending.add(task);
2697
+ }
2698
+ }
2699
+ await Promise.allSettled(pending);
2700
+ await runtime.close();
2701
+ }
2702
+
2703
+ // src/mcp.ts
2704
+ function main() {
2705
+ return serveMcpStdio();
2706
+ }
2707
+ if (process.argv[1] && import.meta.url === pathToFileURL2(realpathSync4(process.argv[1])).href) {
2708
+ void main().catch((error) => {
2709
+ process.stderr.write("Personal Bot MCP: " + (error instanceof Error ? error.message : String(error)) + "\n");
2710
+ process.exitCode = 1;
2711
+ });
2712
+ }
2713
+ export {
2714
+ main
2715
+ };