personal-bot 0.3.1 → 0.3.3

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 (436) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/.claude-plugin/plugin.json +2 -1
  3. package/DISCLAIMER.md +17 -0
  4. package/LICENSE +21 -0
  5. package/README.md +15 -5
  6. package/README.zh-CN.md +15 -5
  7. package/bin/pbot-pi-acp.mjs +27 -11
  8. package/bin/pbot.mjs +22 -2
  9. package/docs/README.md +3 -1
  10. package/docs/architecture/design.md +37 -24
  11. package/docs/architecture/extensibility.md +27 -19
  12. package/docs/architecture/model-context.md +4 -3
  13. package/docs/architecture/principles.md +5 -4
  14. package/docs/guides/capabilities.md +4 -4
  15. package/docs/guides/cross-harness-workers.md +3 -1
  16. package/docs/guides/history.md +73 -16
  17. package/docs/guides/workspace-configuration.md +35 -6
  18. package/docs/hosts/antigravity.md +2 -0
  19. package/docs/hosts/claude-code.md +1 -1
  20. package/docs/hosts/codex-qoder.md +63 -0
  21. package/docs/hosts/dsh.md +1 -1
  22. package/docs/hosts/pi.md +1 -1
  23. package/docs/maintainers/architecture-governance.md +78 -0
  24. package/hooks/hooks.json +3 -0
  25. package/lib/antigravity-plugin/DISCLAIMER.md +17 -0
  26. package/lib/antigravity-plugin/LICENSE +21 -0
  27. package/lib/antigravity-plugin/bin/pbot-pi-acp.mjs +36 -0
  28. package/lib/antigravity-plugin/hooks.json +7 -0
  29. package/lib/antigravity-plugin/lib/claude.js +2 -2
  30. package/lib/antigravity-plugin/lib/common/files.d.ts +2 -0
  31. package/lib/antigravity-plugin/lib/common/files.js +44 -0
  32. package/lib/antigravity-plugin/lib/common/validation.d.ts +4 -0
  33. package/lib/antigravity-plugin/lib/common/validation.js +8 -0
  34. package/lib/{extension/acp-member.d.ts → antigravity-plugin/lib/extension/acp/member.d.ts} +5 -5
  35. package/lib/{extension/acp-member.js → antigravity-plugin/lib/extension/acp/member.js} +6 -6
  36. package/lib/antigravity-plugin/lib/extension/acp-worker.js +222 -51
  37. package/lib/antigravity-plugin/lib/extension/hosts/dsh/acp-entry.d.ts +1 -0
  38. package/lib/antigravity-plugin/lib/extension/hosts/dsh/acp-entry.js +22 -0
  39. package/lib/{extension → antigravity-plugin/lib/extension/hosts}/dsh/acp-member.js +11 -25
  40. package/lib/{extension → antigravity-plugin/lib/extension/hosts}/dsh/files.js +3 -3
  41. package/lib/antigravity-plugin/lib/extension/hosts/pi/acp-member.d.ts +3 -0
  42. package/lib/antigravity-plugin/lib/extension/hosts/pi/acp-member.js +100 -0
  43. package/lib/antigravity-plugin/lib/extension/hosts/plugin-runtime.d.ts +12 -0
  44. package/lib/antigravity-plugin/lib/extension/hosts/plugin-runtime.js +101 -0
  45. package/lib/antigravity-plugin/lib/extension/hosts/workspace-mcp.d.ts +6 -0
  46. package/lib/antigravity-plugin/lib/extension/hosts/workspace-mcp.js +21 -0
  47. package/lib/antigravity-plugin/lib/extension/mcp.js +2705 -1348
  48. package/lib/antigravity-plugin/lib/extension/workspace-cli.js +20127 -0
  49. package/lib/antigravity-plugin/lib/integrations/agent-resources.d.ts +1 -0
  50. package/lib/antigravity-plugin/lib/integrations/agent-resources.js +6 -2
  51. package/lib/antigravity-plugin/lib/integrations/hosts/antigravity/adapter.d.ts +6 -0
  52. package/lib/antigravity-plugin/lib/integrations/hosts/antigravity/adapter.js +171 -0
  53. package/lib/antigravity-plugin/lib/integrations/hosts/{claude.d.ts → claude/adapter.d.ts} +1 -1
  54. package/lib/antigravity-plugin/lib/integrations/hosts/claude/adapter.js +36 -0
  55. package/lib/antigravity-plugin/lib/integrations/hosts/codex/adapter.d.ts +2 -0
  56. package/lib/antigravity-plugin/lib/integrations/hosts/codex/adapter.js +14 -0
  57. package/lib/{integrations → antigravity-plugin/lib/integrations/hosts}/dsh/mcp.d.ts +1 -1
  58. package/lib/{integrations → antigravity-plugin/lib/integrations/hosts}/dsh/resources.d.ts +1 -1
  59. package/lib/{integrations → antigravity-plugin/lib/integrations/hosts}/dsh/resources.js +4 -4
  60. package/lib/{integrations → antigravity-plugin/lib/integrations/hosts}/dsh/skills.js +1 -1
  61. package/lib/antigravity-plugin/lib/integrations/hosts/pi/agent-tools.d.ts +3 -0
  62. package/lib/antigravity-plugin/lib/integrations/hosts/pi/agent-tools.js +32 -0
  63. package/lib/antigravity-plugin/lib/integrations/hosts/pi/mcp.d.ts +4 -0
  64. package/lib/antigravity-plugin/lib/integrations/hosts/pi/mcp.js +23 -0
  65. package/lib/antigravity-plugin/lib/integrations/hosts/{registry.d.ts → plugin-registry.d.ts} +1 -0
  66. package/lib/{integrations/hosts/registry.js → antigravity-plugin/lib/integrations/hosts/plugin-registry.js} +10 -3
  67. package/lib/antigravity-plugin/lib/integrations/hosts/prompt-hooks.d.ts +76 -0
  68. package/lib/antigravity-plugin/lib/integrations/hosts/prompt-hooks.js +76 -0
  69. package/lib/antigravity-plugin/lib/integrations/hosts/qoder/adapter.d.ts +2 -0
  70. package/lib/antigravity-plugin/lib/integrations/hosts/qoder/adapter.js +16 -0
  71. package/lib/antigravity-plugin/lib/model/acp.d.ts +7 -3
  72. package/lib/antigravity-plugin/lib/model/acp.js +8 -0
  73. package/lib/antigravity-plugin/lib/model/agent.d.ts +121 -0
  74. package/lib/antigravity-plugin/lib/model/agent.js +4 -0
  75. package/lib/antigravity-plugin/lib/model/history.d.ts +179 -0
  76. package/lib/antigravity-plugin/lib/model/history.js +4 -0
  77. package/lib/antigravity-plugin/lib/model/plugin-host.d.ts +31 -0
  78. package/lib/antigravity-plugin/lib/model/workspace-config.d.ts +28 -7
  79. package/lib/antigravity-plugin/lib/model/workspace-config.js +2 -1
  80. package/lib/antigravity-plugin/lib/plugin.d.ts +2 -1
  81. package/lib/antigravity-plugin/lib/plugin.js +4 -4
  82. package/lib/antigravity-plugin/lib/services/history/history-capture.d.ts +4 -0
  83. package/lib/antigravity-plugin/lib/services/history/history-capture.js +98 -0
  84. package/lib/antigravity-plugin/lib/services/history/history-index.d.ts +17 -0
  85. package/lib/antigravity-plugin/lib/services/history/history-index.js +112 -0
  86. package/lib/antigravity-plugin/lib/services/history/summary-dimensions/monthly.d.ts +7 -0
  87. package/lib/antigravity-plugin/lib/services/history/summary-dimensions/monthly.js +121 -0
  88. package/lib/antigravity-plugin/lib/services/history/summary-dimensions/session.d.ts +7 -0
  89. package/lib/antigravity-plugin/lib/services/history/summary-dimensions/session.js +124 -0
  90. package/lib/antigravity-plugin/lib/services/history/summary-registry.d.ts +7 -0
  91. package/lib/antigravity-plugin/lib/services/history/summary-registry.js +35 -0
  92. package/lib/antigravity-plugin/lib/services/history/summary-runner.d.ts +34 -0
  93. package/lib/antigravity-plugin/lib/services/history/summary-runner.js +299 -0
  94. package/lib/antigravity-plugin/lib/services/history/workspace-history.d.ts +3 -0
  95. package/lib/antigravity-plugin/lib/services/history/workspace-history.js +6 -0
  96. package/lib/antigravity-plugin/lib/services/workspace/plugin-releases.d.ts +3 -0
  97. package/lib/antigravity-plugin/lib/services/workspace/plugin-releases.js +78 -0
  98. package/lib/antigravity-plugin/lib/services/workspace/workspace-config.d.ts +5 -1
  99. package/lib/antigravity-plugin/lib/services/workspace/workspace-config.js +77 -7
  100. package/lib/antigravity-plugin/lib/services/workspace/workspace-files.d.ts +2 -0
  101. package/lib/antigravity-plugin/lib/services/workspace/workspace-files.js +17 -0
  102. package/lib/antigravity-plugin/lib/services/workspace/workspace-mcp.d.ts +14 -0
  103. package/lib/antigravity-plugin/lib/services/workspace/workspace-mcp.js +193 -0
  104. package/lib/antigravity-plugin/lib/services/workspace/workspace-skills.d.ts +1 -0
  105. package/lib/antigravity-plugin/lib/services/workspace/workspace-skills.js +4 -2
  106. package/lib/antigravity-plugin/lib/storage/acp-files.d.ts +11 -0
  107. package/lib/antigravity-plugin/lib/storage/acp-files.js +75 -0
  108. package/lib/antigravity-plugin/lib/storage/agent-files.d.ts +31 -0
  109. package/lib/antigravity-plugin/lib/storage/agent-files.js +159 -0
  110. package/lib/antigravity-plugin/lib/storage/atomic-json.d.ts +3 -1
  111. package/lib/antigravity-plugin/lib/storage/atomic-json.js +43 -3
  112. package/lib/antigravity-plugin/lib/storage/file-access.d.ts +2 -0
  113. package/lib/antigravity-plugin/lib/storage/file-access.js +26 -0
  114. package/lib/antigravity-plugin/lib/storage/history-files.d.ts +55 -0
  115. package/lib/antigravity-plugin/lib/storage/history-files.js +473 -0
  116. package/lib/antigravity-plugin/lib/storage/history-format.d.ts +5 -0
  117. package/lib/antigravity-plugin/lib/storage/history-format.js +60 -0
  118. package/lib/antigravity-plugin/package.json +1 -1
  119. package/lib/antigravity-plugin/plugin.json +1 -1
  120. package/lib/antigravity-plugin/resources/prompts/history-monthly-summary.md +13 -0
  121. package/lib/antigravity-plugin/resources/prompts/history-summary.md +13 -0
  122. package/lib/antigravity-plugin/resources/prompts/plugin-coordinator.md +1 -0
  123. package/lib/antigravity-plugin/resources/skills/.claude-plugin/plugin.json +4 -0
  124. package/lib/antigravity-plugin/resources/skills/project-maintenance/SKILL.md +35 -0
  125. package/lib/antigravity-plugin/resources/skills/provider-connections/SKILL.md +52 -0
  126. package/lib/antigravity-plugin/skills/pbot/SKILL.md +11 -1
  127. package/lib/antigravity-plugin/skills/provider-connections/SKILL.md +22 -12
  128. package/lib/claude.js +2 -2
  129. package/lib/client.js +42 -60
  130. package/lib/codex-marketplace/.agents/plugins/marketplace.json +17 -0
  131. package/lib/codex-marketplace/plugins/personal-bot/.codex-plugin/plugin.json +7 -0
  132. package/lib/codex-marketplace/plugins/personal-bot/.mcp.json +17 -0
  133. package/lib/codex-marketplace/plugins/personal-bot/DISCLAIMER.md +17 -0
  134. package/lib/codex-marketplace/plugins/personal-bot/LICENSE +21 -0
  135. package/lib/codex-marketplace/plugins/personal-bot/hooks/hooks.json +37 -0
  136. package/lib/codex-marketplace/plugins/personal-bot/skills/pbot/SKILL.md +9 -0
  137. package/lib/codex-marketplace/plugins/personal-bot/skills/pbot/agents/openai.yaml +2 -0
  138. package/lib/common/validation.d.ts +4 -0
  139. package/lib/common/validation.js +8 -0
  140. package/lib/dsh.js +6 -6
  141. package/lib/extension/acp/member.d.ts +18 -0
  142. package/lib/extension/acp/member.js +44 -0
  143. package/lib/extension/acp/worker.js +384 -0
  144. package/lib/extension/acp-worker.js +222 -51
  145. package/lib/extension/history/command.d.ts +37 -0
  146. package/lib/extension/history/command.js +57 -0
  147. package/lib/extension/hosts/dsh/acp-entry.d.ts +1 -0
  148. package/lib/extension/hosts/dsh/acp-entry.js +22 -0
  149. package/lib/extension/hosts/dsh/acp-member.d.ts +4 -0
  150. package/lib/extension/hosts/dsh/acp-member.js +58 -0
  151. package/lib/extension/{dsh → hosts/dsh}/command.d.ts +1 -2
  152. package/lib/extension/{dsh → hosts/dsh}/command.js +9 -11
  153. package/lib/extension/hosts/dsh/files.d.ts +5 -0
  154. package/lib/extension/hosts/dsh/files.js +67 -0
  155. package/lib/extension/hosts/dsh/history.d.ts +4 -0
  156. package/lib/extension/hosts/dsh/history.js +62 -0
  157. package/lib/extension/{dsh → hosts/dsh}/management.d.ts +1 -1
  158. package/lib/extension/{dsh → hosts/dsh}/management.js +12 -10
  159. package/lib/extension/{dsh → hosts/dsh}/workspace.d.ts +3 -9
  160. package/lib/extension/{dsh → hosts/dsh}/workspace.js +30 -99
  161. package/lib/extension/hosts/pi/acp-member.d.ts +3 -0
  162. package/lib/extension/hosts/pi/acp-member.js +100 -0
  163. package/lib/extension/hosts/plugin-runtime.d.ts +12 -0
  164. package/lib/extension/hosts/plugin-runtime.js +101 -0
  165. package/lib/extension/hosts/workspace-mcp.d.ts +6 -0
  166. package/lib/extension/hosts/workspace-mcp.js +21 -0
  167. package/lib/extension/{mcp-bridge.d.ts → mcp/bridge.d.ts} +7 -9
  168. package/lib/extension/{mcp-bridge.js → mcp/bridge.js} +70 -88
  169. package/lib/extension/{mcp-workers.d.ts → mcp/tool-contract.d.ts} +129 -374
  170. package/lib/extension/mcp/tool-contract.js +441 -0
  171. package/lib/extension/mcp/workers.d.ts +487 -0
  172. package/lib/extension/mcp/workers.js +598 -0
  173. package/lib/extension/mcp.js +2705 -1348
  174. package/lib/extension/{setup-cli.js → setup/cli.js} +12 -9
  175. package/lib/extension/workspace-cli.js +20127 -0
  176. package/lib/integrations/acp/agents.d.ts +2 -3
  177. package/lib/integrations/acp/connection.d.ts +11 -10
  178. package/lib/integrations/acp/connection.js +6 -0
  179. package/lib/integrations/acp/harnesses/claude.js +1 -1
  180. package/lib/integrations/acp/harnesses/dsh.js +1 -1
  181. package/lib/integrations/acp/harnesses/presets.js +8 -0
  182. package/lib/integrations/acp/history-summary.d.ts +17 -0
  183. package/lib/integrations/acp/history-summary.js +101 -0
  184. package/lib/integrations/acp/launch.d.ts +2 -2
  185. package/lib/integrations/agent-resources.d.ts +1 -0
  186. package/lib/integrations/agent-resources.js +6 -2
  187. package/lib/integrations/hosts/antigravity/adapter.d.ts +6 -0
  188. package/lib/integrations/hosts/antigravity/adapter.js +171 -0
  189. package/lib/integrations/hosts/{claude.d.ts → claude/adapter.d.ts} +1 -1
  190. package/lib/integrations/hosts/claude/adapter.js +36 -0
  191. package/lib/integrations/hosts/codex/adapter.d.ts +2 -0
  192. package/lib/integrations/hosts/codex/adapter.js +14 -0
  193. package/lib/integrations/hosts/dsh/mcp.d.ts +4 -0
  194. package/lib/integrations/hosts/dsh/mcp.js +28 -0
  195. package/lib/integrations/hosts/dsh/messages.d.ts +36 -0
  196. package/lib/integrations/hosts/dsh/messages.js +11 -0
  197. package/lib/integrations/hosts/dsh/resources.d.ts +6 -0
  198. package/lib/integrations/hosts/dsh/resources.js +47 -0
  199. package/lib/integrations/hosts/dsh/root-agents.d.ts +4 -0
  200. package/lib/integrations/hosts/dsh/root-agents.js +3 -0
  201. package/lib/integrations/{dsh → hosts/dsh}/schema.js +1 -1
  202. package/lib/integrations/hosts/dsh/skills.d.ts +8 -0
  203. package/lib/integrations/hosts/dsh/skills.js +31 -0
  204. package/lib/integrations/hosts/pi/agent-tools.d.ts +3 -0
  205. package/lib/integrations/hosts/pi/agent-tools.js +32 -0
  206. package/lib/integrations/hosts/pi/mcp.d.ts +4 -0
  207. package/lib/integrations/hosts/pi/mcp.js +23 -0
  208. package/lib/integrations/hosts/{registry.d.ts → plugin-registry.d.ts} +1 -0
  209. package/lib/{antigravity-plugin/lib/integrations/hosts/registry.js → integrations/hosts/plugin-registry.js} +10 -3
  210. package/lib/integrations/hosts/prompt-hooks.d.ts +76 -0
  211. package/lib/integrations/hosts/prompt-hooks.js +76 -0
  212. package/lib/integrations/hosts/qoder/adapter.d.ts +2 -0
  213. package/lib/integrations/hosts/qoder/adapter.js +16 -0
  214. package/lib/integrations/installation/pi-setup.js +1 -1
  215. package/lib/model/acp.d.ts +7 -3
  216. package/lib/model/acp.js +8 -0
  217. package/lib/model/agent.d.ts +18 -4
  218. package/lib/model/agent.js +4 -1
  219. package/lib/model/history.d.ts +143 -34
  220. package/lib/model/history.js +4 -1
  221. package/lib/model/installation.js +1 -0
  222. package/lib/model/plugin-host.d.ts +31 -0
  223. package/lib/model/workspace-config.d.ts +28 -7
  224. package/lib/model/workspace-config.js +2 -1
  225. package/lib/plugin.d.ts +2 -1
  226. package/lib/plugin.js +4 -4
  227. package/lib/qoder-plugin/.mcp.json +17 -0
  228. package/lib/qoder-plugin/.qoder-plugin/plugin.json +7 -0
  229. package/lib/qoder-plugin/DISCLAIMER.md +17 -0
  230. package/lib/qoder-plugin/LICENSE +21 -0
  231. package/lib/qoder-plugin/hooks/hooks.json +37 -0
  232. package/lib/qoder-plugin/skills/pbot/SKILL.md +9 -0
  233. package/lib/services/agents/agent-run.d.ts +1 -1
  234. package/lib/services/agents/agent-service.d.ts +15 -45
  235. package/lib/services/agents/agent-service.js +22 -3
  236. package/lib/services/history/history-capture.d.ts +4 -0
  237. package/lib/services/history/history-capture.js +98 -0
  238. package/lib/services/history/history-index.d.ts +16 -7
  239. package/lib/services/history/history-index.js +48 -70
  240. package/lib/services/history/history-migrate.d.ts +12 -0
  241. package/lib/services/history/history-migrate.js +54 -0
  242. package/lib/services/history/history-query.d.ts +51 -0
  243. package/lib/services/history/history-query.js +352 -0
  244. package/lib/services/history/summary-command.d.ts +20 -0
  245. package/lib/services/history/summary-command.js +69 -0
  246. package/lib/services/history/summary-dimensions/monthly.d.ts +7 -0
  247. package/lib/services/history/summary-dimensions/monthly.js +121 -0
  248. package/lib/services/history/summary-dimensions/session.d.ts +7 -0
  249. package/lib/services/history/summary-dimensions/session.js +124 -0
  250. package/lib/services/history/summary-registry.d.ts +7 -0
  251. package/lib/services/history/summary-registry.js +35 -0
  252. package/lib/services/history/summary-runner.d.ts +34 -0
  253. package/lib/services/history/summary-runner.js +299 -0
  254. package/lib/services/history/workspace-history.d.ts +3 -0
  255. package/lib/services/history/workspace-history.js +6 -0
  256. package/lib/services/workspace/plugin-releases.d.ts +3 -0
  257. package/lib/services/workspace/plugin-releases.js +78 -0
  258. package/lib/services/workspace/workspace-config.d.ts +5 -1
  259. package/lib/services/workspace/workspace-config.js +77 -7
  260. package/lib/services/workspace/workspace-mcp.js +22 -29
  261. package/lib/services/workspace/workspace-skills.d.ts +1 -0
  262. package/lib/services/workspace/workspace-skills.js +4 -2
  263. package/lib/storage/acp-files.js +7 -12
  264. package/lib/storage/agent-files.js +6 -5
  265. package/lib/storage/atomic-json.d.ts +3 -1
  266. package/lib/storage/atomic-json.js +43 -3
  267. package/lib/storage/history-files.d.ts +46 -9
  268. package/lib/storage/history-files.js +382 -250
  269. package/lib/storage/history-format.d.ts +3 -13
  270. package/lib/storage/history-format.js +26 -52
  271. package/lib/tools/history/actions.d.ts +3 -68
  272. package/lib/tools/history/actions.js +7 -5
  273. package/lib/tools/history/contract.d.ts +16 -17
  274. package/lib/tools/history/contract.js +63 -22
  275. package/lib/tools/history/dsh-tool.d.ts +1 -2
  276. package/lib/tools/history/dsh-tool.js +11 -5
  277. package/lib/ui/dsh/elements.d.ts +2 -5
  278. package/lib/ui/dsh/elements.js +3 -16
  279. package/lib/ui/dsh/management.js +26 -13
  280. package/lib/ui/dsh/styles.d.ts +1 -1
  281. package/lib/ui/dsh/styles.js +5 -33
  282. package/package.json +4 -1
  283. package/resources/antigravity/skills/pbot/SKILL.md +11 -1
  284. package/resources/claude/skills/pbot/SKILL.md +11 -1
  285. package/resources/plugin/skills/pbot/SKILL.md +9 -0
  286. package/resources/prompts/history-coordinator.md +2 -1
  287. package/resources/prompts/history-monthly-summary.md +13 -0
  288. package/resources/prompts/history-summary.md +10 -4
  289. package/resources/prompts/plugin-coordinator.md +1 -0
  290. package/resources/skills/provider-connections/SKILL.md +22 -12
  291. package/scripts/README.md +3 -2
  292. package/src/claude.ts +2 -2
  293. package/src/common/validation.ts +10 -0
  294. package/src/dsh.ts +6 -6
  295. package/src/extension/{acp-member.ts → acp/member.ts} +7 -7
  296. package/src/extension/{acp-worker.ts → acp/worker.ts} +131 -17
  297. package/src/extension/history/command.ts +68 -0
  298. package/src/extension/hosts/dsh/acp-entry.ts +21 -0
  299. package/src/extension/{dsh → hosts/dsh}/acp-member.ts +12 -23
  300. package/src/extension/{dsh → hosts/dsh}/command.ts +10 -12
  301. package/src/extension/{dsh → hosts/dsh}/files.ts +3 -3
  302. package/src/extension/hosts/dsh/history.ts +67 -0
  303. package/src/extension/{dsh → hosts/dsh}/management.ts +11 -9
  304. package/src/extension/{dsh → hosts/dsh}/workspace.ts +31 -76
  305. package/src/extension/{pi-acp-member.ts → hosts/pi/acp-member.ts} +12 -18
  306. package/src/extension/{command.ts → hosts/pi/command.ts} +44 -11
  307. package/src/extension/{events.ts → hosts/pi/events.ts} +8 -4
  308. package/src/extension/hosts/pi/history.ts +45 -0
  309. package/src/extension/{lifecycle.ts → hosts/pi/lifecycle.ts} +9 -12
  310. package/src/extension/hosts/plugin-runtime.ts +96 -0
  311. package/src/extension/hosts/workspace-mcp.ts +25 -0
  312. package/src/extension/{mcp-bridge.ts → mcp/bridge.ts} +85 -85
  313. package/src/extension/mcp/tool-contract.ts +462 -0
  314. package/src/extension/{mcp-workers.ts → mcp/workers.ts} +151 -448
  315. package/src/extension/{setup-cli.ts → setup/cli.ts} +14 -11
  316. package/src/extension/setup/workspace-cli.ts +159 -0
  317. package/src/integrations/acp/agents.ts +2 -3
  318. package/src/integrations/acp/connection.ts +6 -0
  319. package/src/integrations/acp/harnesses/claude.ts +1 -1
  320. package/src/integrations/acp/harnesses/dsh.ts +1 -1
  321. package/src/integrations/acp/harnesses/presets.ts +8 -0
  322. package/src/integrations/acp/history-summary.ts +109 -0
  323. package/src/integrations/agent-resources.ts +7 -1
  324. package/src/integrations/hosts/antigravity/adapter.ts +161 -0
  325. package/src/integrations/hosts/claude/adapter.ts +39 -0
  326. package/src/integrations/hosts/codex/adapter.ts +16 -0
  327. package/src/integrations/{dsh → hosts/dsh}/mcp.ts +1 -1
  328. package/src/integrations/{dsh → hosts/dsh}/resources.ts +5 -5
  329. package/src/integrations/{dsh → hosts/dsh}/schema.ts +1 -1
  330. package/src/integrations/{dsh → hosts/dsh}/session.ts +2 -2
  331. package/src/integrations/{dsh → hosts/dsh}/skills.ts +1 -1
  332. package/src/integrations/{pi → hosts/pi}/mcp.ts +1 -1
  333. package/src/integrations/{pi → hosts/pi}/skills.ts +1 -1
  334. package/src/integrations/hosts/{registry.ts → plugin-registry.ts} +11 -3
  335. package/src/integrations/hosts/prompt-hooks.ts +72 -0
  336. package/src/integrations/hosts/qoder/adapter.ts +19 -0
  337. package/src/integrations/installation/cli-update.ts +116 -0
  338. package/src/integrations/installation/pi-bridge.ts +1 -1
  339. package/src/integrations/installation/pi-setup.ts +2 -2
  340. package/src/integrations/installation/processes.ts +1 -1
  341. package/src/mcp.ts +1 -1
  342. package/src/model/acp.ts +11 -3
  343. package/src/model/agent.ts +20 -4
  344. package/src/model/history.ts +156 -26
  345. package/src/model/installation.ts +41 -0
  346. package/src/model/plugin-host.ts +30 -2
  347. package/src/model/workspace-config.ts +31 -7
  348. package/src/pbot.ts +22 -50
  349. package/src/plugin.ts +4 -4
  350. package/src/services/agents/agent-service.ts +29 -17
  351. package/src/services/history/history-capture.ts +91 -0
  352. package/src/services/history/history-index.ts +48 -62
  353. package/src/services/history/history-migrate.ts +62 -0
  354. package/src/services/history/history-query.ts +401 -0
  355. package/src/services/history/summary-command.ts +70 -0
  356. package/src/services/history/summary-dimensions/monthly.ts +139 -0
  357. package/src/services/history/summary-dimensions/session.ts +149 -0
  358. package/src/services/history/summary-registry.ts +43 -0
  359. package/src/services/history/summary-runner.ts +343 -0
  360. package/src/services/history/workspace-history.ts +8 -0
  361. package/src/services/installation/setup-service.ts +2 -41
  362. package/src/services/workspace/plugin-releases.ts +68 -0
  363. package/src/services/workspace/workspace-config.ts +95 -8
  364. package/src/services/workspace/workspace-mcp.ts +23 -28
  365. package/src/services/workspace/workspace-skills.ts +5 -2
  366. package/src/storage/acp-files.ts +7 -12
  367. package/src/storage/agent-files.ts +6 -5
  368. package/src/storage/atomic-json.ts +31 -4
  369. package/src/storage/history-files.ts +416 -189
  370. package/src/storage/history-format.ts +45 -61
  371. package/src/tools/history/actions.ts +8 -6
  372. package/src/tools/history/contract.ts +70 -25
  373. package/src/tools/history/dsh-tool.ts +17 -8
  374. package/src/tools/history/pi-tool.ts +23 -0
  375. package/src/ui/dsh/elements.ts +5 -12
  376. package/src/ui/dsh/management.ts +36 -20
  377. package/src/ui/dsh/styles.ts +5 -33
  378. package/src/ui/{confirmation.ts → pi/confirmation.ts} +1 -1
  379. package/lib/antigravity-plugin/lib/extension/plugin-runtime.d.ts +0 -10
  380. package/lib/antigravity-plugin/lib/extension/plugin-runtime.js +0 -67
  381. package/lib/antigravity-plugin/lib/integrations/hosts/antigravity.d.ts +0 -4
  382. package/lib/antigravity-plugin/lib/integrations/hosts/antigravity.js +0 -79
  383. package/lib/antigravity-plugin/lib/integrations/hosts/claude.js +0 -60
  384. package/lib/extension/dsh/history.d.ts +0 -15
  385. package/lib/extension/dsh/history.js +0 -87
  386. package/lib/extension/mcp-workers.js +0 -882
  387. package/lib/extension/plugin-runtime.d.ts +0 -10
  388. package/lib/extension/plugin-runtime.js +0 -67
  389. package/lib/integrations/dsh/history-summary.d.ts +0 -11
  390. package/lib/integrations/dsh/history-summary.js +0 -36
  391. package/lib/integrations/dsh/history.d.ts +0 -16
  392. package/lib/integrations/dsh/history.js +0 -167
  393. package/lib/integrations/history-summary.d.ts +0 -4
  394. package/lib/integrations/history-summary.js +0 -32
  395. package/lib/integrations/hosts/antigravity.d.ts +0 -4
  396. package/lib/integrations/hosts/antigravity.js +0 -79
  397. package/lib/integrations/hosts/claude.js +0 -60
  398. package/lib/services/history/history-service.d.ts +0 -106
  399. package/lib/services/history/history-service.js +0 -242
  400. package/lib/storage/acp-history.d.ts +0 -10
  401. package/lib/storage/acp-history.js +0 -57
  402. package/lib/ui/presentation.d.ts +0 -3
  403. package/lib/ui/presentation.js +0 -12
  404. package/src/extension/dsh/history.ts +0 -74
  405. package/src/extension/history.ts +0 -26
  406. package/src/extension/plugin-runtime.ts +0 -63
  407. package/src/integrations/dsh/history-summary.ts +0 -39
  408. package/src/integrations/dsh/history.ts +0 -84
  409. package/src/integrations/history-summary.ts +0 -30
  410. package/src/integrations/hosts/antigravity.ts +0 -83
  411. package/src/integrations/hosts/claude.ts +0 -62
  412. package/src/integrations/pi/history.ts +0 -99
  413. package/src/services/history/history-service.ts +0 -195
  414. package/src/storage/acp-history.ts +0 -49
  415. package/src/tools/access.ts +0 -7
  416. package/src/tools/history/tool.ts +0 -19
  417. package/src/tools/register.ts +0 -22
  418. package/src/ui/presentation.ts +0 -12
  419. /package/lib/{extension → antigravity-plugin/lib/extension/hosts}/dsh/acp-member.d.ts +0 -0
  420. /package/lib/{extension → antigravity-plugin/lib/extension/hosts}/dsh/files.d.ts +0 -0
  421. /package/lib/{integrations → antigravity-plugin/lib/integrations/hosts}/dsh/mcp.js +0 -0
  422. /package/lib/{integrations → antigravity-plugin/lib/integrations/hosts}/dsh/messages.d.ts +0 -0
  423. /package/lib/{integrations → antigravity-plugin/lib/integrations/hosts}/dsh/messages.js +0 -0
  424. /package/lib/{integrations → antigravity-plugin/lib/integrations/hosts}/dsh/root-agents.d.ts +0 -0
  425. /package/lib/{integrations → antigravity-plugin/lib/integrations/hosts}/dsh/root-agents.js +0 -0
  426. /package/lib/{integrations → antigravity-plugin/lib/integrations/hosts}/dsh/skills.d.ts +0 -0
  427. /package/lib/extension/{acp-worker.d.ts → acp/worker.d.ts} +0 -0
  428. /package/lib/extension/{setup-guard.js → setup/guard.js} +0 -0
  429. /package/lib/integrations/acp/{claude.d.ts → claude-settings.d.ts} +0 -0
  430. /package/lib/integrations/acp/{claude.js → claude-settings.js} +0 -0
  431. /package/lib/integrations/{dsh → hosts/dsh}/schema.d.ts +0 -0
  432. /package/src/extension/{setup-guard.ts → setup/guard.ts} +0 -0
  433. /package/src/integrations/acp/{claude.ts → claude-settings.ts} +0 -0
  434. /package/src/integrations/{dsh → hosts/dsh}/messages.ts +0 -0
  435. /package/src/integrations/{dsh → hosts/dsh}/root-agents.ts +0 -0
  436. /package/src/integrations/{pi → hosts/pi}/agent-tools.ts +0 -0
@@ -1,12 +1,13 @@
1
1
  // src/mcp.ts
2
- import { realpathSync as realpathSync4 } from "node:fs";
2
+ import { realpathSync as realpathSync5 } from "node:fs";
3
3
  import { pathToFileURL as pathToFileURL2 } from "node:url";
4
4
 
5
- // src/extension/mcp-workers.ts
5
+ // src/extension/mcp/workers.ts
6
6
  import { randomUUID as randomUUID4 } from "node:crypto";
7
- import { realpath, stat } from "node:fs/promises";
7
+ import { existsSync as existsSync3 } from "node:fs";
8
+ import { realpath as realpath3, stat as stat3 } from "node:fs/promises";
8
9
  import { homedir } from "node:os";
9
- import { isAbsolute as isAbsolute3, join as join10 } from "node:path";
10
+ import { isAbsolute as isAbsolute5, join as join13 } from "node:path";
10
11
  import { setTimeout as delay3 } from "node:timers/promises";
11
12
 
12
13
  // src/common/json.ts
@@ -31,6 +32,17 @@ function isAcpBackend(value) {
31
32
  function requireThat(condition, message2) {
32
33
  if (!condition) throw new Error(message2);
33
34
  }
35
+ var historyIdentifierPattern = /^[a-z0-9][a-z0-9-]{0,63}$/;
36
+ function isHistoryIdentifier(value) {
37
+ return typeof value === "string" && historyIdentifierPattern.test(value);
38
+ }
39
+ function isOneOf(value, choices) {
40
+ return typeof value === "string" && choices.includes(value);
41
+ }
42
+
43
+ // src/common/paths.ts
44
+ import { fileURLToPath } from "node:url";
45
+ var resourceRoot = fileURLToPath(new URL("../../resources/", import.meta.url));
34
46
 
35
47
  // src/common/version.ts
36
48
  import { readFileSync } from "node:fs";
@@ -51,7 +63,7 @@ import { join as join7, resolve as resolve3 } from "node:path";
51
63
  import { setTimeout as delay } from "node:timers/promises";
52
64
 
53
65
  // src/storage/agent-files.ts
54
- import { existsSync, mkdirSync as mkdirSync2, readdirSync, rmSync } from "node:fs";
66
+ import { existsSync, mkdirSync as mkdirSync3, readdirSync, rmSync } from "node:fs";
55
67
  import { join as join3 } from "node:path";
56
68
  import { randomUUID as randomUUID2 } from "node:crypto";
57
69
 
@@ -63,17 +75,19 @@ import {
63
75
  fsyncSync,
64
76
  linkSync,
65
77
  lstatSync,
78
+ mkdirSync,
66
79
  openSync,
67
80
  readFileSync as readFileSync2,
68
81
  realpathSync,
69
82
  renameSync,
83
+ rmdirSync,
70
84
  unlinkSync,
71
85
  writeFileSync
72
86
  } from "node:fs";
73
87
  import { dirname, join } from "node:path";
74
88
  import { randomUUID } from "node:crypto";
75
- function internalPath(directory, relative) {
76
- const parts = relative.split("/");
89
+ function internalPath(directory, relative3, allowMissingParents = false) {
90
+ const parts = relative3.split("/");
77
91
  requireThat(parts.every((part) => part && part !== "." && part !== ".." && !/[\\\x00-\x1f]/.test(part)), "\u5185\u90E8\u72B6\u6001\u8DEF\u5F84\u65E0\u6548\u3002");
78
92
  const info = lstatSync(directory);
79
93
  requireThat(info.isDirectory() && !info.isSymbolicLink(), "\u5185\u90E8\u72B6\u6001\u5FC5\u987B\u4F7F\u7528\u666E\u901A\u76EE\u5F55\u3002");
@@ -84,7 +98,7 @@ function internalPath(directory, relative) {
84
98
  const info2 = lstatSync(path);
85
99
  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
100
  } catch (error) {
87
- if (error.code !== "ENOENT" || index !== parts.length - 1) throw error;
101
+ if (error.code !== "ENOENT" || !allowMissingParents && index !== parts.length - 1) throw error;
88
102
  }
89
103
  }
90
104
  return path;
@@ -97,8 +111,8 @@ function syncDirectory(directory) {
97
111
  closeSync(fd);
98
112
  }
99
113
  }
100
- function readJsonFile(directory, relative, validate) {
101
- const path = internalPath(directory, relative);
114
+ function readJsonFile(directory, relative3, validate) {
115
+ const path = internalPath(directory, relative3);
102
116
  const fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
103
117
  try {
104
118
  requireThat(fstatSync(fd).isFile(), "\u5185\u90E8\u72B6\u6001\u5FC5\u987B\u662F\u666E\u901A\u6587\u4EF6\u3002");
@@ -106,19 +120,19 @@ function readJsonFile(directory, relative, validate) {
106
120
  try {
107
121
  value = JSON.parse(readFileSync2(fd, "utf8"));
108
122
  } catch (error) {
109
- throw new Error("\u5185\u90E8 JSON \u6587\u4EF6\u4E0D\u53EF\u8BFB\u53D6\uFF1A" + relative, { cause: error });
123
+ throw new Error("\u5185\u90E8 JSON \u6587\u4EF6\u4E0D\u53EF\u8BFB\u53D6\uFF1A" + relative3, { cause: error });
110
124
  }
111
125
  return validate(value);
112
126
  } finally {
113
127
  closeSync(fd);
114
128
  }
115
129
  }
116
- function writeJsonFile(directory, relative, value, validate, createOnly = false) {
130
+ function writeJsonFile(directory, relative3, value, validate, createOnly = false) {
117
131
  const validated = validate(value);
118
132
  const expected = canonical(validated);
119
133
  const content = JSON.stringify(validated, null, 2) + "\n";
120
134
  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);
135
+ const path = internalPath(directory, relative3), parent = dirname(path);
122
136
  const temporary = join(parent, `.tmp-${randomUUID()}`);
123
137
  const fd = openSync(temporary, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 384);
124
138
  try {
@@ -128,7 +142,7 @@ function writeJsonFile(directory, relative, value, validate, createOnly = false)
128
142
  } finally {
129
143
  closeSync(fd);
130
144
  }
131
- requireThat(internalPath(directory, relative) === path, "\u5185\u90E8\u72B6\u6001\u8DEF\u5F84\u5DF2\u53D8\u5316\u3002");
145
+ requireThat(internalPath(directory, relative3) === path, "\u5185\u90E8\u72B6\u6001\u8DEF\u5F84\u5DF2\u53D8\u5316\u3002");
132
146
  if (createOnly) {
133
147
  try {
134
148
  linkSync(temporary, path);
@@ -149,20 +163,20 @@ function writeJsonFile(directory, relative, value, validate, createOnly = false)
149
163
  }
150
164
 
151
165
  // src/storage/file-access.ts
152
- import { lstatSync as lstatSync2, mkdirSync } from "node:fs";
166
+ import { lstatSync as lstatSync2, mkdirSync as mkdirSync2 } from "node:fs";
153
167
  import { join as join2 } from "node:path";
154
168
  function fileId(id) {
155
169
  requireThat(/^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/.test(id), "\u5185\u90E8\u8BB0\u5F55 ID \u65E0\u6548\u3002");
156
170
  return id;
157
171
  }
158
- function privateDirectory(root, relative) {
159
- const parts = relative.split("/");
172
+ function privateDirectory(root, relative3) {
173
+ const parts = relative3.split("/");
160
174
  let parent = root;
161
175
  for (const part of parts) {
162
176
  fileId(part);
163
177
  const path = join2(parent, part);
164
178
  try {
165
- mkdirSync(path, { mode: 448 });
179
+ mkdirSync2(path, { mode: 448 });
166
180
  syncDirectory(parent);
167
181
  } catch (error) {
168
182
  if (error.code !== "EEXIST") throw error;
@@ -172,15 +186,30 @@ function privateDirectory(root, relative) {
172
186
  }
173
187
  }
174
188
 
189
+ // src/model/agent.ts
190
+ var messageDeliveries = ["steer", "followUp"];
191
+ var cycleStates = ["running", "completed", "failed", "cancelled", "interrupted"];
192
+ var cycleSources = ["parent", "interactive", "mixed"];
193
+ var agentStates = ["starting", "busy", "idle", "stopping", "stopped", "error"];
194
+
175
195
  // src/storage/acp-files.ts
176
196
  import { isAbsolute } from "node:path";
197
+
198
+ // src/model/acp.ts
199
+ var acpPermissionPolicies = ["ask", "allow", "deny"];
200
+ var acpElicitationActions = ["accept", "decline", "cancel"];
201
+ function isAcpElicitationValue(value) {
202
+ return typeof value === "string" || typeof value === "boolean" || typeof value === "number" && Number.isFinite(value) || Array.isArray(value) && value.every((item) => typeof item === "string");
203
+ }
204
+
205
+ // src/storage/acp-files.ts
177
206
  var text = (value) => typeof value === "string" && value.length > 0 && !value.includes("\0");
178
207
  function acpReference(value) {
179
208
  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
209
  if (value.env !== void 0) {
181
210
  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
211
  }
183
- requireThat(value.permission === void 0 || ["ask", "allow", "deny"].includes(String(value.permission)), "ACP \u6743\u9650\u7B56\u7565\u65E0\u6548\u3002");
212
+ requireThat(value.permission === void 0 || isOneOf(value.permission, acpPermissionPolicies), "ACP \u6743\u9650\u7B56\u7565\u65E0\u6548\u3002");
184
213
  const capabilities = value.capabilities;
185
214
  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
215
  return value;
@@ -205,7 +234,7 @@ function acpReport(value) {
205
234
  }
206
235
  function acpPermission(value) {
207
236
  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");
237
+ requireThat(object(value) && typeof value.description === "string" && Array.isArray(value.options) && value.options.every((option) => object(option) && text(option.optionId) && text(option.name) && isOneOf(option.kind, ["allow_once", "allow_always", "reject_once", "reject_always"])), "ACP \u786E\u8BA4\u8BF7\u6C42\u65E0\u6548\u3002");
209
238
  return value;
210
239
  }
211
240
  function acpPermissionReply(value) {
@@ -213,9 +242,6 @@ function acpPermissionReply(value) {
213
242
  requireThat(object(value) && (value.optionId === null || text(value.optionId)), "ACP \u786E\u8BA4\u7B54\u590D\u65E0\u6548\u3002");
214
243
  return value;
215
244
  }
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
245
  function acpElicitation(value) {
220
246
  acpInput(value);
221
247
  requireThat(object(value) && (value.mode === "form" || value.mode === "url") && typeof value.message === "string", "ACP \u4EA4\u4E92\u8BF7\u6C42\u65E0\u6548\u3002");
@@ -228,9 +254,9 @@ function acpElicitation(value) {
228
254
  }
229
255
  function acpElicitationReply(value) {
230
256
  acpInput(value);
231
- requireThat(object(value) && ["accept", "decline", "cancel"].includes(String(value.action)), "ACP \u4EA4\u4E92\u7B54\u590D\u65E0\u6548\u3002");
257
+ requireThat(object(value) && isOneOf(value.action, acpElicitationActions), "ACP \u4EA4\u4E92\u7B54\u590D\u65E0\u6548\u3002");
232
258
  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");
259
+ requireThat(value.action === "accept" && object(value.content) && Object.values(value.content).every(isAcpElicitationValue), "ACP \u8868\u5355\u7B54\u590D content \u65E0\u6548\u3002");
234
260
  }
235
261
  return value;
236
262
  }
@@ -248,15 +274,15 @@ function launch(v) {
248
274
  return v;
249
275
  }
250
276
  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");
277
+ requireThat(object(v) && text2(v.requestId) && text2(v.generation) && Number.isSafeInteger(v.sequence) && typeof v.message === "string" && isOneOf(v.delivery, messageDeliveries) && Array.isArray(v.files) && v.files.every(text2), "\u5B50\u4F1A\u8BDD\u6D88\u606F\u65E0\u6548\u3002");
252
278
  return v;
253
279
  }
254
280
  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");
281
+ requireThat(object(v) && text2(v.cycleId) && text2(v.generation) && number(v.startedAt) && isOneOf(v.state, cycleStates) && (v.leaf === null || text2(v.leaf)) && Array.isArray(v.requestIds) && v.requestIds.every(text2) && isOneOf(v.source, cycleSources) && (v.finishedAt === void 0 || number(v.finishedAt)), "\u5B50\u4F1A\u8BDD\u5468\u671F\u65E0\u6548\u3002");
256
282
  return v;
257
283
  }
258
284
  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");
285
+ requireThat(object(v) && text2(v.generation) && isOneOf(v.state, agentStates) && typeof v.activity === "string" && number(v.updatedAt), "\u5B50\u4F1A\u8BDD\u72B6\u6001\u65E0\u6548\u3002");
260
286
  if (v.cycle) cycle(v.cycle);
261
287
  return v;
262
288
  }
@@ -300,8 +326,8 @@ var AgentFiles = class {
300
326
  create(value, run, acp) {
301
327
  this.check();
302
328
  acpReference(acp);
303
- mkdirSync2(this.root, { recursive: true, mode: 448 });
304
- mkdirSync2(this.directory(value.agentId), { mode: 448 });
329
+ mkdirSync3(this.root, { recursive: true, mode: 448 });
330
+ mkdirSync3(this.directory(value.agentId), { mode: 448 });
305
331
  for (const dir of ["inbox", "completions", "reports", "permissions", "elicitations"]) privateDirectory(this.directory(value.agentId), dir);
306
332
  this.write(value.agentId, "descriptor.json", value, descriptor, true);
307
333
  this.write(value.agentId, "launch.json", run, launch, true);
@@ -343,10 +369,10 @@ var AgentFiles = class {
343
369
  /** Short controller edits are serialized; an abandoned lock fails closed. */
344
370
  control(work) {
345
371
  this.check();
346
- mkdirSync2(this.root, { recursive: true, mode: 448 });
372
+ mkdirSync3(this.root, { recursive: true, mode: 448 });
347
373
  const path = join3(this.root, ".control");
348
374
  try {
349
- mkdirSync2(path, { mode: 448 });
375
+ mkdirSync3(path, { mode: 448 });
350
376
  } catch (error) {
351
377
  if (error.code !== "EEXIST") throw error;
352
378
  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" });
@@ -372,10 +398,6 @@ var AgentFiles = class {
372
398
  }
373
399
  };
374
400
 
375
- // src/common/paths.ts
376
- import { fileURLToPath } from "node:url";
377
- var resourceRoot = fileURLToPath(new URL("../../resources/", import.meta.url));
378
-
379
401
  // src/integrations/acp/executable.ts
380
402
  import { accessSync, constants as constants2, realpathSync as realpathSync2, statSync } from "node:fs";
381
403
  import { delimiter, isAbsolute as isAbsolute2, resolve } from "node:path";
@@ -410,7 +432,7 @@ function acpExecutable(command, backend, harness) {
410
432
  ].join("\n"));
411
433
  }
412
434
 
413
- // src/integrations/acp/claude.ts
435
+ // src/integrations/acp/claude-settings.ts
414
436
  import { createRequire } from "node:module";
415
437
  import { pathToFileURL } from "node:url";
416
438
  import { basename, join as join4, resolve as resolve2 } from "node:path";
@@ -545,7 +567,7 @@ var dshAcpHarness = {
545
567
  const patch = join5(context.directory, "acp-dsh-patch.json");
546
568
  await writeFile(
547
569
  patch,
548
- JSON.stringify([{ insert: [{ id: "pbot-acp-member", name: join5(context.packageRoot, "lib/extension/dsh/acp-member.js") }] }]) + "\n",
570
+ JSON.stringify([{ insert: [{ id: "pbot-acp-member", name: join5(context.packageRoot, "lib/extension/hosts/dsh/acp-entry.js") }] }]) + "\n",
549
571
  { mode: 384 }
550
572
  );
551
573
  return {
@@ -608,6 +630,14 @@ var standardAcpPresets = [
608
630
  configureHint: "\u8FD0\u884C agy \u5B8C\u6210\u767B\u5F55\u4E0E\u9ED8\u8BA4\u6A21\u578B\u914D\u7F6E\u3002",
609
631
  nativeWorkspaceSkills: true
610
632
  }),
633
+ createGenericAcpHarness("qoder", {
634
+ label: "Qoder CLI",
635
+ aliases: ["qodercli", "qoder-cli"],
636
+ nativeWorkspaceSkills: true,
637
+ defaultCommand: { command: "qodercli", args: ["--acp"] },
638
+ installHint: "\u5B89\u88C5 Qoder CLI\uFF08qodercli\uFF09",
639
+ configureHint: "\u8FD0\u884C qodercli login \u5B8C\u6210\u767B\u5F55\u3002"
640
+ }),
611
641
  createGenericAcpHarness("codex", {
612
642
  label: "OpenAI Codex",
613
643
  aliases: ["openai-codex", "codex-cli"],
@@ -905,1368 +935,2635 @@ var AcpWorkerHost = class {
905
935
  }
906
936
  };
907
937
 
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));
938
+ // src/integrations/hosts/antigravity/adapter.ts
939
+ import { readFile, realpath, stat } from "node:fs/promises";
940
+ import { dirname as dirname2, isAbsolute as isAbsolute3, join as join8, relative, resolve as resolve4, sep } from "node:path";
941
+ var supportedEvents = ["SessionStart", "PreToolUse", "Stop"];
942
+ function cleanUserRequest(content) {
943
+ const match = content.match(/<USER_REQUEST>\s*([\s\S]*?)\s*<\/USER_REQUEST>/);
944
+ return (match ? match[1] : content).trim();
945
+ }
946
+ function projectAntigravityTranscript(sessionId, content, terminationReason) {
947
+ const exchanges = [];
948
+ const lines = content.split(/\r?\n/);
949
+ let users = [];
950
+ let answer;
951
+ const finish = (completed2) => {
952
+ if (!users.length) return;
953
+ const entryIds = [...users.map((u) => u.id), ...answer ? [answer.id] : []];
954
+ const from = users[0].time;
955
+ const to = answer?.time ?? users.at(-1).time;
956
+ const text3 = users.map((u) => "\u7528\u6237\uFF1A\n" + u.text).join("\n\n") + (answer ? "\n\n\u52A9\u624B\uFF1A\n" + answer.text : "");
957
+ exchanges.push({ entryIds, from, to, completed: completed2, text: text3 });
958
+ users = [];
959
+ answer = void 0;
960
+ };
961
+ for (const line of lines) {
962
+ const trimmed = line.trim();
963
+ if (!trimmed) continue;
964
+ let entry;
965
+ try {
966
+ entry = JSON.parse(trimmed);
967
+ } catch {
968
+ continue;
969
+ }
970
+ if (!object(entry) || typeof entry.type !== "string") continue;
971
+ const stepIndex = typeof entry.step_index === "number" ? entry.step_index : exchanges.length;
972
+ const time = typeof entry.created_at === "string" && entry.created_at ? entry.created_at : (/* @__PURE__ */ new Date()).toISOString();
973
+ if (entry.type === "USER_INPUT" && typeof entry.content === "string") {
974
+ if (answer) finish(true);
975
+ const cleaned = cleanUserRequest(entry.content);
976
+ if (cleaned) users.push({ id: `agy:${stepIndex}`, text: cleaned, time });
977
+ } else if (entry.type === "PLANNER_RESPONSE" && users.length) {
978
+ const hasToolCalls = Array.isArray(entry.tool_calls) && entry.tool_calls.length > 0;
979
+ const text3 = typeof entry.content === "string" ? entry.content.trim() : "";
980
+ if (!hasToolCalls && text3) {
981
+ answer = { id: `agy:${stepIndex}`, text: text3, time };
982
+ }
983
+ }
960
984
  }
961
- list(owner) {
962
- return this.records(owner).map((d) => this.view(d, owner));
985
+ const completed = Boolean(answer) && (!terminationReason || terminationReason === "NO_TOOL_CALL");
986
+ finish(completed);
987
+ return { sessionId, name: "", branches: exchanges.length ? [exchanges] : [] };
988
+ }
989
+ async function readAntigravityTranscript(transcriptPath) {
990
+ const fullPath = join8(dirname2(transcriptPath), "transcript_full.jsonl");
991
+ for (const path of [fullPath, transcriptPath]) {
992
+ try {
993
+ return await readFile(path, "utf8");
994
+ } catch (error) {
995
+ if (error.code !== "ENOENT") throw error;
996
+ }
963
997
  }
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
- ] : [];
998
+ return void 0;
999
+ }
1000
+ function workspaceFromPayload(cwd, payload) {
1001
+ if (object(payload) && Array.isArray(payload.workspacePaths)) {
1002
+ const first = payload.workspacePaths.find((value) => typeof value === "string" && value.length > 0);
1003
+ if (typeof first === "string") return first;
1004
+ }
1005
+ return cwd;
1006
+ }
1007
+ function skillFromReadPath(targetPath, pluginRoot = process.env.PLUGIN_ROOT || resolve4(resourceRoot, "..")) {
1008
+ const skillsRoot = resolve4(pluginRoot, "skills");
1009
+ const rel = relative(skillsRoot, resolve4(targetPath));
1010
+ if (!rel || rel.startsWith("..") || isAbsolute3(rel)) return void 0;
1011
+ const skill = rel.split(sep)[0];
1012
+ if (!skill || skill === "pbot") return void 0;
1013
+ return skill;
1014
+ }
1015
+ function isPreToolUse(payload) {
1016
+ return object(payload) && payload.hookEventName === "PreToolUse";
1017
+ }
1018
+ async function antigravityWorkspaceRoot(cwd, payload) {
1019
+ const directory = workspaceFromPayload(cwd, payload);
1020
+ requireThat(isAbsolute3(directory), "Antigravity \u5DE5\u4F5C\u533A\u9700\u8981\u7EDD\u5BF9\u8DEF\u5F84\u3002");
1021
+ const root = await realpath(directory);
1022
+ requireThat((await stat(root)).isDirectory(), "Antigravity \u5DE5\u4F5C\u533A\u9700\u8981\u76EE\u5F55\u3002");
1023
+ return root;
1024
+ }
1025
+ var antigravityAdapter = {
1026
+ host: "antigravity",
1027
+ nativeRootAgents: true,
1028
+ nativeWorkspaceSkills: true,
1029
+ coordinatorPrompt: "plugin-coordinator.md",
1030
+ initCommandHint: "/pbot init",
1031
+ usage: "\u7528\u6CD5\uFF1Anode <\u63D2\u4EF6\u76EE\u5F55>/lib/plugin.js antigravity init|status",
1032
+ resolveRoot(cwd, rawPayload) {
1033
+ return antigravityWorkspaceRoot(cwd, rawPayload);
1034
+ },
1035
+ parseEvent(value) {
1036
+ requireThat(object(value) && typeof value.hookEventName === "string", "Antigravity hook \u8F93\u5165\u65E0\u6548\u3002");
1037
+ const event = value.hookEventName;
1038
+ requireThat(supportedEvents.includes(event), "Antigravity hook \u4E8B\u4EF6\u672A\u652F\u6301\u3002");
1039
+ const cwd = typeof value.cwd === "string" && value.cwd ? value.cwd : workspaceFromPayload("", value);
1040
+ requireThat(cwd, "Antigravity hook \u7F3A\u5C11\u5DE5\u4F5C\u76EE\u5F55\u3002");
1041
+ if (event === "SessionStart") {
1042
+ return { kind: "inject-context", role: "coordinator", isSessionStart: true, cwd, raw: value };
1043
+ }
1044
+ if (event === "Stop") {
1045
+ return { kind: "record-history", cwd, raw: value };
1046
+ }
1047
+ if (!object(value.toolCall) || typeof value.toolCall.name !== "string" || !object(value.toolCall.args)) {
1048
+ return { kind: "ignore" };
1049
+ }
1050
+ const { name, args } = value.toolCall;
1051
+ if (name === "read_file" && typeof args.Path === "string") {
1052
+ const skill = skillFromReadPath(args.Path);
1053
+ if (skill) return { kind: "check-skill", skill, cwd, raw: value };
1054
+ }
1055
+ return { kind: "ignore" };
1056
+ },
1057
+ async extractHistory(event) {
1058
+ if (event.kind !== "record-history" || !object(event.raw)) return void 0;
1059
+ const sessionId = typeof event.raw.conversationId === "string" ? event.raw.conversationId.trim() : "";
1060
+ if (!sessionId) return void 0;
1061
+ const terminationReason = typeof event.raw.terminationReason === "string" ? event.raw.terminationReason : void 0;
1062
+ const transcriptPath = typeof event.raw.transcriptPath === "string" ? event.raw.transcriptPath.trim() : "";
1063
+ if (transcriptPath) {
1064
+ const content = await readAntigravityTranscript(transcriptPath);
1065
+ if (content) {
1066
+ const session = projectAntigravityTranscript(sessionId, content, terminationReason);
1067
+ if (session.branches.length) return { kind: "session", session };
1068
+ }
1069
+ }
1070
+ const lastUserInput = typeof event.raw.lastUserInput === "string" ? event.raw.lastUserInput.trim() : "";
1071
+ if (lastUserInput) return { kind: "input", sessionId, text: lastUserInput };
1072
+ return void 0;
1073
+ },
1074
+ formatPass(payload) {
1075
+ return isPreToolUse(payload) ? { decision: "allow" } : {};
1076
+ },
1077
+ formatContext(_event, context) {
982
1078
  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 } : {}
1079
+ injectSteps: [
1080
+ { systemMessage: { systemMessage: context.text } }
1081
+ ]
1001
1082
  };
1083
+ },
1084
+ formatDeny(_event, reason) {
1085
+ return { decision: "deny", reason };
1002
1086
  }
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(", "));
1087
+ };
1088
+
1089
+ // src/integrations/hosts/prompt-hooks.ts
1090
+ import { realpath as realpath2, stat as stat2 } from "node:fs/promises";
1091
+ import { isAbsolute as isAbsolute4 } from "node:path";
1092
+ async function pluginWorkspaceRoot(directory) {
1093
+ requireThat(isAbsolute4(directory), "\u63D2\u4EF6\u5DE5\u4F5C\u533A\u9700\u8981\u7EDD\u5BF9\u8DEF\u5F84\u3002");
1094
+ const root = await realpath2(directory);
1095
+ requireThat((await stat2(root)).isDirectory(), "\u63D2\u4EF6\u5DE5\u4F5C\u533A\u9700\u8981\u76EE\u5F55\u3002");
1096
+ return root;
1097
+ }
1098
+ function parsePromptEvent(value) {
1099
+ requireThat(object(value), "\u63D2\u4EF6 hook \u8F93\u5165\u65E0\u6548\u3002");
1100
+ const name = value.hook_event_name;
1101
+ if (name !== "Stop" && name !== "UserPromptSubmit" && name !== "SessionStart") return { kind: "ignore" };
1102
+ if (typeof value.agent_id === "string") return { kind: "ignore" };
1103
+ requireThat(typeof value.cwd === "string", "\u63D2\u4EF6 hook \u7F3A\u5C11\u5DE5\u4F5C\u76EE\u5F55\u3002");
1104
+ if (name === "Stop") return { kind: "record-history", cwd: value.cwd, raw: value };
1105
+ if (name === "SessionStart") {
1106
+ if (value.source === "resume" || value.source === "compact") return { kind: "ignore" };
1107
+ return { kind: "inject-context", role: "coordinator", isSessionStart: true, noticesOnly: true, cwd: value.cwd, raw: value };
1108
+ }
1109
+ return { kind: "inject-context", role: "coordinator", cwd: value.cwd, raw: value };
1110
+ }
1111
+ var promptHooks = {
1112
+ async extractHistory(event) {
1113
+ if (!object(event.raw)) return void 0;
1114
+ const sessionId = typeof event.raw.session_id === "string" ? event.raw.session_id.trim() : "";
1115
+ if (!sessionId) return void 0;
1116
+ const turnId = typeof event.raw.turn_id === "string" ? event.raw.turn_id.trim() : "";
1117
+ const identity2 = turnId ? { sessionId, turnId } : { sessionId };
1118
+ if (event.raw.hook_event_name === "UserPromptSubmit") {
1119
+ const text3 = typeof event.raw.prompt === "string" ? event.raw.prompt.trim() : "";
1120
+ if (!text3 && !turnId) return void 0;
1121
+ return { kind: "input", ...identity2, text: text3 };
1009
1122
  }
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);
1123
+ if (event.raw.hook_event_name === "Stop") {
1124
+ const assistantText = typeof event.raw.last_assistant_message === "string" ? event.raw.last_assistant_message.trim() : "";
1125
+ if (!assistantText) return void 0;
1126
+ return {
1127
+ kind: "answer",
1128
+ ...identity2,
1129
+ assistantText,
1130
+ completed: true,
1131
+ ...event.raw.stop_hook_active === true ? { isContinuation: true } : {}
1132
+ };
1047
1133
  }
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");
1134
+ return void 0;
1135
+ },
1136
+ formatPass() {
1137
+ return {};
1138
+ },
1139
+ formatContext(event, context) {
1140
+ const raw = event.raw;
1141
+ return {
1142
+ hookSpecificOutput: {
1143
+ hookEventName: raw.hook_event_name,
1144
+ additionalContext: context.text
1054
1145
  }
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);
1146
+ };
1147
+ },
1148
+ formatDeny(event, reason) {
1149
+ const raw = event.raw;
1150
+ return raw.hook_event_name === "UserPromptExpansion" ? { decision: "block", reason } : { hookSpecificOutput: { hookEventName: raw.hook_event_name, permissionDecision: "deny", permissionDecisionReason: reason } };
1151
+ }
1152
+ };
1153
+
1154
+ // src/integrations/hosts/claude/adapter.ts
1155
+ var supportedEvents2 = ["UserPromptSubmit", "PreToolUse", "UserPromptExpansion", "Stop"];
1156
+ var boundWorkspaceRoot = () => process.env.CLAUDE_PROJECT_DIR;
1157
+ async function claudeWorkspaceRoot(cwd, projectDirectory = boundWorkspaceRoot()) {
1158
+ return pluginWorkspaceRoot(projectDirectory || cwd);
1159
+ }
1160
+ var claudeAdapter = {
1161
+ host: "claude",
1162
+ nativeRootAgents: false,
1163
+ nativeWorkspaceSkills: false,
1164
+ coordinatorPrompt: "plugin-coordinator.md",
1165
+ initCommandHint: "/personal-bot:pbot init",
1166
+ usage: "\u7528\u6CD5\uFF1Anode <\u63D2\u4EF6\u76EE\u5F55>/lib/claude.js init|status",
1167
+ boundWorkspaceRoot,
1168
+ resolveRoot(cwd) {
1169
+ return claudeWorkspaceRoot(cwd);
1170
+ },
1171
+ parseEvent(value) {
1172
+ requireThat(object(value) && typeof value.hook_event_name === "string", "Claude hook \u8F93\u5165\u65E0\u6548\u3002");
1173
+ const event = value.hook_event_name;
1174
+ requireThat(supportedEvents2.includes(event), "Claude hook \u4E8B\u4EF6\u672A\u652F\u6301\u3002");
1175
+ if (event === "PreToolUse" || event === "UserPromptExpansion") {
1176
+ const skill = event === "UserPromptExpansion" ? value.expansion_type === "slash_command" ? value.command_name : void 0 : value.tool_name === "Skill" && object(value.tool_input) ? value.tool_input.skill : void 0;
1177
+ if (typeof skill !== "string" || !skill.startsWith("personal-bot:") || skill === "personal-bot:pbot") return { kind: "ignore" };
1178
+ requireThat(typeof value.cwd === "string", "Claude hook \u7F3A\u5C11\u5DE5\u4F5C\u76EE\u5F55\u3002");
1179
+ return { kind: "check-skill", skill, cwd: value.cwd, raw: value };
1063
1180
  }
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);
1181
+ return parsePromptEvent(value);
1182
+ },
1183
+ ...promptHooks
1184
+ };
1185
+
1186
+ // src/integrations/hosts/codex/adapter.ts
1187
+ var codexAdapter = {
1188
+ host: "codex",
1189
+ nativeRootAgents: true,
1190
+ nativeWorkspaceSkills: true,
1191
+ indexBundledSkills: true,
1192
+ initCommandHint: "pbot plugin codex init",
1193
+ usage: "\u7528\u6CD5\uFF1Apbot plugin codex init|status",
1194
+ resolveRoot(cwd) {
1195
+ return pluginWorkspaceRoot(cwd);
1196
+ },
1197
+ parseEvent: parsePromptEvent,
1198
+ ...promptHooks
1199
+ };
1200
+
1201
+ // src/integrations/hosts/qoder/adapter.ts
1202
+ var boundWorkspaceRoot2 = () => process.env.QODER_PROJECT_DIR || process.env.PBOT_WORKSPACE_ROOT;
1203
+ var qoderAdapter = {
1204
+ host: "qoder",
1205
+ nativeRootAgents: true,
1206
+ nativeWorkspaceSkills: true,
1207
+ indexBundledSkills: true,
1208
+ initCommandHint: "pbot plugin qoder init",
1209
+ usage: "\u7528\u6CD5\uFF1Apbot plugin qoder init|status",
1210
+ boundWorkspaceRoot: boundWorkspaceRoot2,
1211
+ resolveRoot(cwd) {
1212
+ return pluginWorkspaceRoot(boundWorkspaceRoot2() || cwd);
1213
+ },
1214
+ parseEvent: parsePromptEvent,
1215
+ ...promptHooks
1216
+ };
1217
+
1218
+ // src/integrations/hosts/plugin-registry.ts
1219
+ var PluginHostRegistry = class {
1220
+ #adapters = /* @__PURE__ */ new Map();
1221
+ constructor(initial = []) {
1222
+ for (const adapter of initial) this.register(adapter);
1073
1223
  }
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" } : {} };
1224
+ register(adapter) {
1225
+ requireThat(typeof adapter.host === "string" && adapter.host.length > 0, "\u63D2\u4EF6\u5BBF\u4E3B\u6807\u8BC6\u65E0\u6548\u3002");
1226
+ this.#adapters.set(adapter.host, adapter);
1227
+ return this;
1105
1228
  }
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);
1229
+ unregister(host) {
1230
+ return this.#adapters.delete(host);
1285
1231
  }
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;
1232
+ get(host) {
1233
+ return this.#adapters.get(host);
1296
1234
  }
1297
- close(owner, preserve = false) {
1298
- return this.#closing ??= this.dispose(owner, preserve);
1235
+ require(host) {
1236
+ const adapter = this.#adapters.get(host);
1237
+ requireThat(adapter, `\u672A\u6CE8\u518C\u7684\u63D2\u4EF6\u5BBF\u4E3B\uFF1A${host}\u3002\u53EF\u7528\u5BBF\u4E3B\uFF1A${this.list().join(", ")}`);
1238
+ return adapter;
1299
1239
  }
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");
1240
+ list() {
1241
+ return [...this.#adapters.keys()];
1320
1242
  }
1321
1243
  };
1244
+ var pluginHosts = new PluginHostRegistry([claudeAdapter, antigravityAdapter, codexAdapter, qoderAdapter]);
1245
+ function pluginMcpWorkspaceRoot() {
1246
+ const adapter = process.env.PBOT_HOST ? pluginHosts.get(process.env.PBOT_HOST) : claudeAdapter;
1247
+ return adapter?.boundWorkspaceRoot?.() || process.env.PBOT_WORKSPACE_ROOT;
1248
+ }
1322
1249
 
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;
1250
+ // src/model/history.ts
1251
+ var historyPageLimits = {
1252
+ search: { default: 20, max: 50 },
1253
+ read: { default: 12e3, max: 24e3 }
1254
+ };
1255
+
1256
+ // src/extension/mcp/tool-contract.ts
1257
+ var defaultWaitMs = 5e4;
1258
+ var maxWaitMs = 6e5;
1259
+ var discoverTargets = ["overview", "workers", "backends", "models"];
1260
+ function formatBackendItem(entry, defaultBackend) {
1261
+ const tags = [];
1262
+ if (entry.label) tags.push(entry.label);
1263
+ if (entry.backend === defaultBackend) tags.push("\u5F53\u524D");
1264
+ return tags.length ? `${entry.backend}\uFF08${tags.join("\uFF0C")}\uFF09` : entry.backend;
1348
1265
  }
1349
- function workspaceFeatures(configuration) {
1350
- const raw = configuration && "features" in configuration ? configuration.features : configuration;
1266
+ function summarizeBackends(commands = {}, defaultBackend) {
1267
+ const entries = inspectAcpBackends(commands);
1268
+ const available = entries.filter((item) => item.available);
1269
+ const unavailable = entries.filter((item) => !item.available);
1270
+ const availableText = available.map((item) => formatBackendItem(item, defaultBackend)).join("\u3001");
1271
+ const unavailableText = unavailable.map((item) => formatBackendItem(item, defaultBackend)).join("\u3001");
1272
+ const overview = available.length ? unavailable.length ? `\u5F53\u524D\u53EF\u7528\u52A9\u624B\uFF1A${availableText}\uFF1B\u6682\u4E0D\u53EF\u7528\uFF1A${unavailableText}\u3002` : `\u5F53\u524D\u53EF\u7528\u52A9\u624B\uFF1A${availableText}\u3002` : `\u5F53\u524D\u65E0\u53EF\u7528\u5916\u90E8\u52A9\u624B\uFF08\u6682\u4E0D\u53EF\u7528\uFF1A${unavailableText}\uFF09\u3002`;
1273
+ const availableIds = available.map((item) => item.backend).join("\u3001");
1274
+ return { overview, availableIds };
1275
+ }
1276
+ function workspaceProperty(workspaceBound) {
1351
1277
  return {
1352
- prompts: raw?.prompts !== false,
1353
- skills: raw?.skills !== false,
1354
- mcp: raw?.mcp !== false
1278
+ type: "string",
1279
+ description: workspaceBound ? "\u76EE\u6807\u5DE5\u4F5C\u533A\u6839\u76EE\u5F55\u7684\u7EDD\u5BF9\u8DEF\u5F84\uFF1B\u9ED8\u8BA4\u4F7F\u7528\u5F53\u524D\u5DE5\u4F5C\u533A\uFF0C\u901A\u5E38\u7701\u7565\u3002" : "\u76EE\u6807\u5DE5\u4F5C\u533A\u6839\u76EE\u5F55\u7684\u7EDD\u5BF9\u8DEF\u5F84\uFF08\u5982\u4E0A\u4E0B\u6587\u4E2D\u63D0\u4F9B\u4E86 workspaceRoot \u5219\u4F20\u8BE5\u8DEF\u5F84\uFF09\uFF1B\u8BF7\u663E\u5F0F\u4F20\u5165\u3002"
1355
1280
  };
1356
1281
  }
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)}` };
1282
+ function buildPbotWorkerTools(commands = {}, defaultBackend, workspaceBound = false) {
1283
+ const { overview, availableIds } = summarizeBackends(commands, defaultBackend);
1284
+ const modelsBackendHint = defaultBackend ? `\u7701\u7565\u65F6\u9ED8\u8BA4\u67E5 ${defaultBackend}` : "\u5FC5\u586B";
1285
+ const workspace = workspaceProperty(workspaceBound);
1286
+ return [
1287
+ {
1288
+ name: "worker_create",
1289
+ description: "\u542F\u52A8\u4E00\u4E2A\u72EC\u7ACB\u7684\u5916\u90E8 AI \u52A9\u624B\u4F1A\u8BDD\uFF08worker\uFF09\uFF0C\u7528\u4E8E\u5C06\u4EFB\u52A1\u59D4\u6D3E\u7ED9\u5176\u4ED6\u52A9\u624B\u6216\u6307\u5B9A\u6A21\u578B/\u601D\u8003\u6DF1\u5EA6\u6765\u72EC\u7ACB\u5904\u7406\uFF08\u5982\u6309\u7528\u6237\u8981\u6C42\u5207\u6362\u52A9\u624B\u3001\u83B7\u53D6\u72EC\u7ACB\u5BA1\u67E5\u6216\u7B2C\u4E8C\u610F\u89C1\u3001\u5E76\u884C\u5206\u62C5\u5B50\u4EFB\u52A1\uFF09\u3002\u672C\u5DE5\u5177\u4EC5\u5EFA\u7ACB\u4F1A\u8BDD\u5E76\u8FD4\u56DE workerId\uFF0C\u968F\u540E\u901A\u8FC7 worker_request \u53D1\u9001\u5177\u4F53\u4EFB\u52A1\u3002\u4E0D\u9700\u8981\u501F\u52A9\u5176\u4ED6\u52A9\u624B\u65F6\uFF0C\u4F18\u5148\u81EA\u884C\u5B8C\u6210\u6216\u4F7F\u7528\u5F53\u524D\u5185\u7F6E\u5B50\u4EE3\u7406\u3002\n" + overview,
1290
+ annotations: {
1291
+ title: "Create Worker",
1292
+ readOnlyHint: false,
1293
+ destructiveHint: false,
1294
+ idempotentHint: false,
1295
+ openWorldHint: true
1296
+ },
1297
+ inputSchema: {
1298
+ type: "object",
1299
+ additionalProperties: false,
1300
+ required: ["backend"],
1301
+ properties: {
1302
+ backend: {
1303
+ type: "string",
1304
+ description: "\u8981\u542F\u52A8\u7684\u5916\u90E8\u52A9\u624B\u6807\u8BC6\uFF08\u4E0D\u533A\u5206\u5927\u5C0F\u5199\uFF0C\u652F\u6301\u5E38\u89C1\u522B\u540D\uFF0C\u5982 claude-code\u3001agy\uFF09\u3002"
1305
+ },
1306
+ model: {
1307
+ type: "string",
1308
+ description: '\u4EC5\u7528\u6237\u660E\u786E\u8981\u6C42\u7279\u5B9A\u6A21\u578B\u65F6\u6307\u5B9A\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\u53EF\u7528\u503C\u65F6\u5148\u7528 worker_discover(target="models") \u67E5\u8BE2\uFF1B\u4E0D\u586B\u5219\u4F7F\u7528\u8BE5\u52A9\u624B\u9ED8\u8BA4\u6A21\u578B\u3002'
1309
+ },
1310
+ thinking: {
1311
+ type: "string",
1312
+ description: "\u4EC5\u7528\u6237\u660E\u786E\u8981\u6C42\u601D\u8003\u6DF1\u5EA6\u65F6\u6307\u5B9A\uFF08\u5982 low / medium / high / xhigh / max\uFF0C\u4E0D\u533A\u5206\u5927\u5C0F\u5199\uFF09\uFF1B\u4E0D\u586B\u5219\u4F7F\u7528\u9ED8\u8BA4\u8BBE\u7F6E\u3002"
1313
+ },
1314
+ cwd: {
1315
+ type: "string",
1316
+ description: "\u52A9\u624B\u6267\u884C\u4EFB\u52A1\u65F6\u7684\u5DE5\u4F5C\u76EE\u5F55\uFF08\u7EDD\u5BF9\u8DEF\u5F84\u6216\u76F8\u5BF9\u5DE5\u4F5C\u533A\u7684\u8DEF\u5F84\uFF09\uFF0C\u9ED8\u8BA4\u4E3A\u5F53\u524D\u5DE5\u4F5C\u533A\u6839\u76EE\u5F55\u3002"
1317
+ },
1318
+ workspace
1319
+ }
1320
+ }
1321
+ },
1322
+ {
1323
+ name: "worker_close",
1324
+ description: "\u7ED3\u675F\u4E0D\u518D\u9700\u8981\u7684\u5916\u90E8\u52A9\u624B\u4F1A\u8BDD\u5E76\u91CA\u653E\u8D44\u6E90\u3002\u82E5\u8BE5\u52A9\u624B\u652F\u6301\u4F1A\u8BDD\u6062\u590D\uFF0C\u540E\u7EED\u4ECD\u53EF\u76F4\u63A5\u7528 worker_request \u5728\u539F\u4E0A\u4E0B\u6587\u4E2D\u7EE7\u7EED\u5BF9\u8BDD\u3002",
1325
+ annotations: {
1326
+ title: "Close Worker",
1327
+ readOnlyHint: false,
1328
+ destructiveHint: true,
1329
+ idempotentHint: true,
1330
+ openWorldHint: false
1331
+ },
1332
+ inputSchema: {
1333
+ type: "object",
1334
+ additionalProperties: false,
1335
+ required: ["workerId"],
1336
+ properties: {
1337
+ workerId: {
1338
+ type: "string",
1339
+ description: "\u8981\u7ED3\u675F\u7684\u52A9\u624B\u4F1A\u8BDD ID\uFF08\u6765\u81EA worker_create \u6216 worker_discover\uFF09\u3002"
1340
+ },
1341
+ workspace
1342
+ }
1343
+ }
1344
+ },
1345
+ {
1346
+ name: "worker_request",
1347
+ description: `\u5411\u6307\u5B9A\u7684\u5916\u90E8\u52A9\u624B\u6D3E\u53D1\u4EFB\u52A1\uFF0C\u6216\u5728\u540C\u4E00\u4E0A\u4E0B\u6587\u4E2D\u8FFD\u95EE\u4E0E\u8865\u5145\u8981\u6C42\uFF0C\u5E76\u83B7\u53D6\u6267\u884C\u7ED3\u679C\uFF08\u5DF2\u5173\u95ED\u4F46\u652F\u6301\u6062\u590D\u7684\u4F1A\u8BDD\u4F1A\u81EA\u52A8\u7EED\u63A5\uFF09\u3002\u9ED8\u8BA4\u6700\u591A\u7B49\u5F85 ${defaultWaitMs / 1e3} \u79D2\u8FD4\u56DE\u7ED3\u679C\uFF1B\u5C06 waitMs \u8BBE\u4E3A 0 \u53EF\u7ACB\u5373\u8FD4\u56DE\u5E76\u8F6C\u5165\u540E\u53F0\u6267\u884C\uFF0C\u9002\u5408\u8017\u65F6\u4EFB\u52A1\u6216\u591A\u52A9\u624B\u5E76\u884C\u3002\u82E5\u8FD4\u56DE timedOut \u6216\u7ED3\u679C\u542B nextOffset\uFF0C\u7528 worker_output \u7EE7\u7EED\u7B49\u5F85\u6216\u7FFB\u9875\uFF1B\u82E5\u8FD4\u56DE needsResponse\uFF0C\u5148\u5411\u7528\u6237\u786E\u8BA4\u518D\u7528 worker_response \u56DE\u590D\u3002`,
1348
+ annotations: {
1349
+ title: "Send Request to Worker",
1350
+ readOnlyHint: false,
1351
+ destructiveHint: false,
1352
+ idempotentHint: false,
1353
+ openWorldHint: true
1354
+ },
1355
+ inputSchema: {
1356
+ type: "object",
1357
+ additionalProperties: false,
1358
+ required: ["workerId", "message"],
1359
+ properties: {
1360
+ workerId: {
1361
+ type: "string",
1362
+ description: "\u76EE\u6807\u52A9\u624B\u4F1A\u8BDD ID\uFF08\u6765\u81EA worker_create \u6216 worker_discover\uFF09\u3002"
1363
+ },
1364
+ message: {
1365
+ type: "string",
1366
+ description: "\u8981\u53D1\u9001\u7684\u4EFB\u52A1\u8BF4\u660E\u6216\u8FFD\u95EE\u5185\u5BB9\u3002\u5916\u90E8\u52A9\u624B\u770B\u4E0D\u5230\u4F60\u4E0E\u7528\u6237\u7684\u5BF9\u8BDD\u5386\u53F2\uFF0C\u9996\u6B21\u6D3E\u53D1\u65F6\u8BF7\u5199\u6E05\u80CC\u666F\u3001\u76EE\u6807\u3001\u76F8\u5173\u6587\u4EF6\u8DEF\u5F84\u3001\u7EA6\u675F\u6761\u4EF6\u548C\u671F\u671B\u4EA7\u51FA\u3002"
1367
+ },
1368
+ waitMs: {
1369
+ type: "integer",
1370
+ minimum: 0,
1371
+ maximum: maxWaitMs,
1372
+ description: `\u6700\u591A\u7B49\u5F85\u7ED3\u679C\u7684\u6BEB\u79D2\u6570\uFF08\u9ED8\u8BA4 ${defaultWaitMs}\uFF09\uFF1B\u8BBE\u4E3A 0 \u53EF\u7ACB\u5373\u8FD4\u56DE\u5E76\u5728\u540E\u53F0\u6267\u884C\u3002`
1373
+ },
1374
+ workspace
1375
+ }
1376
+ }
1377
+ },
1378
+ {
1379
+ name: "worker_response",
1380
+ description: `\u5F53\u5916\u90E8\u52A9\u624B\u5728\u6267\u884C\u8FC7\u7A0B\u4E2D\u6682\u505C\u5E76\u8BF7\u6C42\u786E\u8BA4\u6216\u8865\u5145\u4FE1\u606F\uFF08\u8FD4\u56DE needsResponse: true\uFF09\u65F6\uFF0C\u5411\u5176\u63D0\u4EA4\u51B3\u5B9A\u4EE5\u7EE7\u7EED\u6267\u884C\u3002\u652F\u6301\u4E09\u7C7B\u8BF7\u6C42\uFF1A\u64CD\u4F5C\u6388\u6743\uFF08kind="permission"\uFF09\u3001\u95EE\u7B54\u8868\u5355\uFF08kind="form"\uFF09\u548C\u94FE\u63A5\u786E\u8BA4\uFF08kind="url"\uFF09\u3002\u63D0\u4EA4\u524D\u5148\u5411\u7528\u6237\u786E\u8BA4\uFF1B\u63D0\u4EA4\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`,
1381
+ annotations: {
1382
+ title: "Respond to Worker Request",
1383
+ readOnlyHint: false,
1384
+ destructiveHint: false,
1385
+ idempotentHint: false,
1386
+ openWorldHint: true
1387
+ },
1388
+ inputSchema: {
1389
+ type: "object",
1390
+ additionalProperties: false,
1391
+ required: ["workerId", "action"],
1392
+ properties: {
1393
+ workerId: {
1394
+ type: "string",
1395
+ description: "\u7B49\u5F85\u56DE\u590D\u7684\u52A9\u624B\u4F1A\u8BDD ID\u3002"
1396
+ },
1397
+ action: {
1398
+ type: "string",
1399
+ enum: [...acpElicitationActions],
1400
+ description: "\u5904\u7406\u65B9\u5F0F\uFF1Aaccept \u8868\u793A\u540C\u610F\u6388\u6743\u3001\u63D0\u4EA4\u8868\u5355\u56DE\u7B54\u6216\u786E\u8BA4\u94FE\u63A5\uFF1Bdecline \u8868\u793A\u62D2\u7EDD\uFF1Bcancel \u8868\u793A\u53D6\u6D88\u672C\u6B21\u8BF7\u6C42\u3002"
1401
+ },
1402
+ requestId: {
1403
+ type: "string",
1404
+ description: "\u8981\u56DE\u590D\u7684\u8BF7\u6C42 ID\uFF08\u6765\u81EA pendingRequests[].requestId\uFF09\uFF1B\u4EC5\u4E00\u6761\u5F85\u5904\u7406\u8BF7\u6C42\u65F6\u53EF\u7701\u7565\uFF0C\u591A\u6761\u65F6\u5FC5\u586B\u3002"
1405
+ },
1406
+ optionId: {
1407
+ type: "string",
1408
+ description: '\u4EC5\u6388\u6743\u8BF7\u6C42\uFF08kind="permission"\uFF09\u4E14 action \u4E0D\u4E3A cancel \u65F6\u53EF\u7528\uFF1A\u6307\u5B9A\u9009\u9879 ID\uFF08\u6765\u81EA pendingRequests[].options[].optionId\uFF09\uFF0C\u7701\u7565\u65F6\u9ED8\u8BA4\u5355\u6B21\u5141\u8BB8\u6216\u62D2\u7EDD\u3002'
1409
+ },
1410
+ content: {
1411
+ type: "object",
1412
+ additionalProperties: true,
1413
+ description: '\u4EC5\u8868\u5355\u63D0\u95EE\uFF08kind="form"\uFF09\u4E14 action="accept" \u65F6\u53EF\u7528\uFF1A\u6309 pendingRequests[].schema.properties \u586B\u5199\u7684\u56DE\u7B54\u5BF9\u8C61\uFF08\u503C\u4E3A\u5B57\u7B26\u4E32\u3001\u6570\u5B57\u3001\u5E03\u5C14\u503C\u6216\u5B57\u7B26\u4E32\u6570\u7EC4\uFF09\u3002'
1414
+ },
1415
+ waitMs: {
1416
+ type: "integer",
1417
+ minimum: 0,
1418
+ maximum: maxWaitMs,
1419
+ description: `\u63D0\u4EA4\u56DE\u590D\u540E\u6700\u591A\u7B49\u5F85\u540E\u7EED\u7ED3\u679C\u7684\u6BEB\u79D2\u6570\uFF08\u9ED8\u8BA4 ${defaultWaitMs}\uFF09\uFF1B\u8BBE\u4E3A 0 \u7ACB\u5373\u8FD4\u56DE\u3002`
1420
+ },
1421
+ workspace
1422
+ }
1423
+ }
1424
+ },
1425
+ {
1426
+ name: "worker_output",
1427
+ description: "\u83B7\u53D6\u6216\u7B49\u5F85\u5916\u90E8\u52A9\u624B\u7684\u6700\u65B0\u6267\u884C\u7ED3\u679C\u3002\u7528\u4E8E\u6536\u53D6\u540E\u53F0\u4EFB\u52A1\u7684\u4EA7\u51FA\u3001\u5728\u7B49\u5F85\u8D85\u65F6\uFF08timedOut\uFF09\u540E\u7EE7\u7EED\u7B49\u5F85\uFF0C\u6216\u5728\u957F\u7ED3\u679C\u5206\u9875\uFF08\u542B nextOffset\uFF09\u65F6\u8BFB\u53D6\u540E\u7EED\u5185\u5BB9\u3002\u4EFB\u52A1\u4ECD\u5728\u8FD0\u884C\u65F6\u4F1A\u7B49\u5F85\u5176\u5B8C\u6210\uFF08\u4E5F\u53EF\u80FD\u8FD4\u56DE timedOut \u6216 needsResponse\uFF09\uFF0C\u5DF2\u7ED3\u675F\u5219\u7ACB\u5373\u8FD4\u56DE\u3002",
1428
+ annotations: {
1429
+ title: "Get Worker Output",
1430
+ readOnlyHint: true,
1431
+ destructiveHint: false,
1432
+ idempotentHint: true,
1433
+ openWorldHint: false
1434
+ },
1435
+ inputSchema: {
1436
+ type: "object",
1437
+ additionalProperties: false,
1438
+ required: ["workerId"],
1439
+ properties: {
1440
+ workerId: {
1441
+ type: "string",
1442
+ description: "\u8981\u7B49\u5F85\u6216\u83B7\u53D6\u7ED3\u679C\u7684\u52A9\u624B\u4F1A\u8BDD ID\u3002"
1443
+ },
1444
+ offset: {
1445
+ type: "integer",
1446
+ minimum: 0,
1447
+ description: "\u7ED3\u679C\u8BFB\u53D6\u8D77\u59CB\u4F4D\u7F6E\uFF08\u9ED8\u8BA4 0\uFF09\uFF1B\u7FFB\u9875\u8BFB\u53D6\u5269\u4F59\u5185\u5BB9\u65F6\u4F20\u5165\u4E0A\u6B21\u8FD4\u56DE\u7684 nextOffset\u3002"
1448
+ },
1449
+ waitMs: {
1450
+ type: "integer",
1451
+ minimum: 0,
1452
+ maximum: maxWaitMs,
1453
+ description: `\u4EFB\u52A1\u4ECD\u5728\u8FD0\u884C\u65F6\u6700\u591A\u7B49\u5F85\u7684\u6BEB\u79D2\u6570\uFF08\u9ED8\u8BA4 ${defaultWaitMs}\uFF09\uFF1B\u4EFB\u52A1\u5DF2\u7ED3\u675F\u6216\u7FFB\u9875\u8BFB\u53D6\u65F6\u4F1A\u7ACB\u5373\u8FD4\u56DE\u3002`
1454
+ },
1455
+ workspace
1456
+ }
1457
+ }
1458
+ },
1459
+ {
1460
+ name: "worker_discover",
1461
+ description: '\u4E86\u89E3\u5F53\u524D\u53EF\u4EE5\u59D4\u6D3E\u54EA\u4E9B\u5916\u90E8\u52A9\u624B\u3001\u67E5\u770B\u5DF2\u6709\u52A9\u624B\u4F1A\u8BDD\u7684\u8FD0\u884C\u72B6\u6001\u4EE5\u4FBF\u590D\u7528\uFF0C\u6216\u67E5\u8BE2\u67D0\u4E2A\u52A9\u624B\u652F\u6301\u7684\u6A21\u578B\u4E0E\u601D\u8003\u6DF1\u5EA6\u9009\u9879\u3002\u9ED8\u8BA4\uFF08target="overview"\uFF09\u540C\u65F6\u8FD4\u56DE\u53EF\u7528\u52A9\u624B\u4E0E\u5DF2\u6709\u4F1A\u8BDD\uFF1B\u4EC5\u5728\u9700\u8981\u6838\u5BF9\u6A21\u578B\u6216\u601D\u8003\u6DF1\u5EA6\u53EF\u9009\u503C\u65F6\u518D\u67E5 target="models"\uFF08\u8017\u65F6\u8F83\u957F\uFF09\u3002',
1462
+ annotations: {
1463
+ title: "Discover Workers, Backends & Models",
1464
+ readOnlyHint: true,
1465
+ destructiveHint: false,
1466
+ idempotentHint: true,
1467
+ openWorldHint: false
1468
+ },
1469
+ inputSchema: {
1470
+ type: "object",
1471
+ additionalProperties: false,
1472
+ required: [],
1473
+ properties: {
1474
+ target: {
1475
+ type: "string",
1476
+ enum: [...discoverTargets],
1477
+ description: '\u67E5\u8BE2\u8303\u56F4\uFF0C\u9ED8\u8BA4 "overview"\uFF08\u540C\u65F6\u8FD4\u56DE\u53EF\u7528\u52A9\u624B\u4E0E\u5DF2\u6709\u4F1A\u8BDD\uFF09\uFF1B"workers" \u67E5\u5168\u90E8\u6216\u5355\u4E2A\u4F1A\u8BDD\u72B6\u6001\uFF1B"backends" \u67E5\u53EF\u7528\u52A9\u624B\u5217\u8868\uFF1B"models" \u67E5\u6307\u5B9A\u52A9\u624B\u652F\u6301\u7684\u6A21\u578B\u4E0E\u601D\u8003\u6DF1\u5EA6\u3002'
1478
+ },
1479
+ workerId: {
1480
+ type: "string",
1481
+ description: '\u4EC5 target="workers" \u53EF\u7528\uFF1A\u6307\u5B9A\u5355\u4E2A\u52A9\u624B\u4F1A\u8BDD ID\uFF1B\u4E0D\u586B\u5219\u5217\u51FA\u5168\u90E8\u3002'
1482
+ },
1483
+ backend: {
1484
+ type: "string",
1485
+ description: availableIds ? `\u4EC5 target="models" \u53EF\u7528\uFF08${modelsBackendHint}\uFF09\uFF1A\u76EE\u6807\u5916\u90E8\u52A9\u624B\u6807\u8BC6\uFF0C\u652F\u6301\u5E38\u89C1\u522B\u540D\uFF1B\u5F53\u524D\u53EF\u7528\uFF1A${availableIds}\u3002` : `\u4EC5 target="models" \u53EF\u7528\uFF08${modelsBackendHint}\uFF09\uFF1A\u76EE\u6807\u5916\u90E8\u52A9\u624B\u6807\u8BC6\uFF0C\u652F\u6301\u5E38\u89C1\u522B\u540D\u3002`
1486
+ },
1487
+ model: {
1488
+ type: "string",
1489
+ description: '\u4EC5 target="models" \u53EF\u7528\uFF1A\u6307\u5B9A\u6A21\u578B\u4EE5\u67E5\u770B\u8BE5\u6A21\u578B\u652F\u6301\u7684\u601D\u8003\u6DF1\u5EA6\u9009\u9879\u3002'
1490
+ },
1491
+ workspace
1492
+ }
1493
+ }
1494
+ }
1495
+ ];
1496
+ }
1497
+ function buildWorkspaceMcpTools(workspaceBound = false) {
1498
+ const workspace = workspaceProperty(workspaceBound);
1499
+ return [
1500
+ {
1501
+ name: "workspace_mcp_discover",
1502
+ description: "\u53D1\u73B0\u5F53\u524D\u5DE5\u4F5C\u533A\u5171\u4EAB\u7684\u5916\u90E8\u5DE5\u5177\u670D\u52A1\uFF08MCP\uFF09\u53CA\u5176\u53EF\u7528\u5DE5\u5177\u3002\u4E0D\u4F20 server \u65F6\u5217\u51FA\u53EF\u7528\u670D\u52A1\uFF1B\u4F20\u5165 server \u65F6\u8FD4\u56DE\u8BE5\u670D\u52A1\u63D0\u4F9B\u7684\u5DE5\u5177\u6E05\u5355\u4E0E\u53C2\u6570\u8BF4\u660E\u3002",
1503
+ annotations: {
1504
+ title: "Discover Workspace MCP Servers & Tools",
1505
+ readOnlyHint: true,
1506
+ destructiveHint: false,
1507
+ idempotentHint: true,
1508
+ openWorldHint: true
1509
+ },
1510
+ inputSchema: {
1511
+ type: "object",
1512
+ additionalProperties: false,
1513
+ required: [],
1514
+ properties: {
1515
+ server: {
1516
+ type: "string",
1517
+ description: "\u76EE\u6807\u5DE5\u5177\u670D\u52A1\u540D\u79F0\uFF1B\u4E0D\u586B\u65F6\u5217\u51FA\u5DE5\u4F5C\u533A\u5168\u90E8\u53EF\u7528\u670D\u52A1\u3002"
1518
+ },
1519
+ workspace
1520
+ }
1521
+ }
1522
+ },
1523
+ {
1524
+ name: "workspace_mcp_call",
1525
+ description: "\u8C03\u7528\u5F53\u524D\u5DE5\u4F5C\u533A\u5171\u4EAB\u7684\u5916\u90E8\u5DE5\u5177\u670D\u52A1\uFF08MCP\uFF09\u4E2D\u7684\u6307\u5B9A\u5DE5\u5177\uFF0C\u7528\u4E8E\u8BBF\u95EE\u5DE5\u4F5C\u533A\u63A5\u5165\u7684\u5916\u90E8\u80FD\u529B\u4E0E\u6570\u636E\u6E90\u3002\u4E0D\u786E\u5B9A\u5DE5\u5177\u540D\u6216\u53C2\u6570\u683C\u5F0F\u65F6\uFF0C\u5148\u7528 workspace_mcp_discover(server) \u67E5\u8BE2\u3002",
1526
+ annotations: {
1527
+ title: "Call Workspace MCP Tool",
1528
+ readOnlyHint: false,
1529
+ destructiveHint: false,
1530
+ idempotentHint: false,
1531
+ openWorldHint: true
1532
+ },
1533
+ inputSchema: {
1534
+ type: "object",
1535
+ additionalProperties: false,
1536
+ required: ["server", "tool"],
1537
+ properties: {
1538
+ server: {
1539
+ type: "string",
1540
+ description: "\u76EE\u6807\u5DE5\u5177\u670D\u52A1\u540D\u79F0\uFF08\u53EF\u901A\u8FC7 workspace_mcp_discover \u83B7\u53D6\uFF09\u3002"
1541
+ },
1542
+ tool: {
1543
+ type: "string",
1544
+ description: "\u8981\u8C03\u7528\u7684\u5DE5\u5177\u540D\u79F0\u3002"
1545
+ },
1546
+ arguments: {
1547
+ type: "object",
1548
+ additionalProperties: true,
1549
+ description: "\u4F20\u7ED9\u76EE\u6807\u5DE5\u5177\u7684\u53C2\u6570\u5BF9\u8C61\uFF0C\u4E0D\u586B\u5219\u4E3A\u7A7A\u5BF9\u8C61\u3002"
1550
+ },
1551
+ workspace
1552
+ }
1553
+ }
1554
+ }
1555
+ ];
1556
+ }
1557
+ function buildHistoryMcpTools(workspaceBound = false) {
1558
+ const workspace = workspaceProperty(workspaceBound);
1559
+ return [
1560
+ {
1561
+ name: "history_search",
1562
+ description: "\u641C\u7D22\u5F53\u524D\u5DE5\u4F5C\u533A\u8DE8\u5BBF\u4E3B\uFF08pi\u3001dsh\u3001claude\u3001antigravity \u7B49\uFF09\u7684\u5386\u53F2\u95EE\u7B54\u4E0E\u6458\u8981\u5F52\u6863\u3002\u7701\u7565 query \u65F6\u5217\u51FA\u5404\u4F1A\u8BDD\uFF1B\u4F20\u5165 query \u6309\u4E0D\u533A\u5206\u5927\u5C0F\u5199\u7684\u8FDE\u7EED\u5173\u952E\u8BCD\u5339\u914D\u539F\u6587\u4E0E\u6458\u8981\u3002",
1563
+ annotations: {
1564
+ title: "Search Workspace History",
1565
+ readOnlyHint: true,
1566
+ destructiveHint: false,
1567
+ idempotentHint: true,
1568
+ openWorldHint: false
1569
+ },
1570
+ inputSchema: {
1571
+ type: "object",
1572
+ additionalProperties: false,
1573
+ required: [],
1574
+ properties: {
1575
+ host: {
1576
+ type: "string",
1577
+ description: "\u53EF\u9009\u6765\u6E90\u7B5B\u9009\uFF08\u5982 pi\u3001dsh\u3001claude\u3001antigravity\uFF09\uFF1B\u7701\u7565\u67E5\u5168\u90E8\u5BBF\u4E3B\u3002"
1578
+ },
1579
+ dimension: {
1580
+ type: "string",
1581
+ description: "\u53EF\u9009\u8303\u56F4\u7B5B\u9009\uFF1Araw \u8868\u793A\u4EC5\u641C\u539F\u6587\uFF0C\u6216\u6307\u5B9A\u6458\u8981\u7EF4\u5EA6\uFF08\u5982 monthly\u3001session\uFF09\uFF1B\u7701\u7565\u67E5\u5168\u90E8\u539F\u6587\u4E0E\u7EF4\u5EA6\u6458\u8981\u3002"
1582
+ },
1583
+ query: {
1584
+ type: "string",
1585
+ description: "\u4E0D\u533A\u5206\u5927\u5C0F\u5199\u7684\u8FDE\u7EED\u5173\u952E\u8BCD\uFF1B\u7701\u7565\u65F6\u5217\u51FA\u5404\u4F1A\u8BDD\uFF08\u6216\u6307\u5B9A\u7EF4\u5EA6\u6458\u8981\uFF09\u3002"
1586
+ },
1587
+ sessionId: {
1588
+ type: "string",
1589
+ description: "\u9650\u5B9A\u5728\u6307\u5B9A\u539F\u59CB\u4F1A\u8BDD ID \u5185\u641C\u7D22\u3002"
1590
+ },
1591
+ from: {
1592
+ type: "string",
1593
+ description: "ISO \u65E5\u671F\u6216\u65F6\u95F4\u4E0B\u754C\u3002"
1594
+ },
1595
+ to: {
1596
+ type: "string",
1597
+ description: "ISO \u65E5\u671F\u6216\u65F6\u95F4\u4E0A\u754C\u3002"
1598
+ },
1599
+ offset: {
1600
+ type: "integer",
1601
+ minimum: 0,
1602
+ description: "\u5339\u914D\u7ED3\u679C\u504F\u79FB\uFF0C\u9ED8\u8BA4 0\u3002"
1603
+ },
1604
+ limit: {
1605
+ type: "integer",
1606
+ minimum: 1,
1607
+ maximum: historyPageLimits.search.max,
1608
+ description: `\u6700\u591A\u8FD4\u56DE\u6761\u6570\uFF081\u2013${historyPageLimits.search.max}\uFF09\uFF0C\u9ED8\u8BA4 ${historyPageLimits.search.default}\u3002`
1609
+ },
1610
+ workspace
1611
+ }
1612
+ }
1613
+ },
1614
+ {
1615
+ name: "history_read",
1616
+ description: "\u6309\u8282\u70B9 id \u8BFB\u53D6\u5F53\u524D\u5DE5\u4F5C\u533A\u5386\u53F2\u5F52\u6863\u7684\u6B63\u6587\u4E0E\u4E0A\u4E0B\u7EA7\u8282\u70B9\uFF08monthly\u3001session\u3001summary\u3001exchange\uFF09\uFF0C\u652F\u6301\u4ECE\u6708\u5EA6\u6C47\u603B\u4E0B\u94BB\u81F3\u5355\u4F1A\u8BDD\u6458\u8981\u4E0E\u539F\u59CB\u95EE\u7B54\u3002\u6B63\u6587\u8FC7\u957F\u65F6\u7528 nextOffset \u7EED\u8BFB\uFF0C\u5B50\u8282\u70B9\u8FC7\u591A\u65F6\u7528 nextChildrenOffset \u7EED\u8BFB\u3002",
1617
+ annotations: {
1618
+ title: "Read Workspace History Node",
1619
+ readOnlyHint: true,
1620
+ destructiveHint: false,
1621
+ idempotentHint: true,
1622
+ openWorldHint: false
1623
+ },
1624
+ inputSchema: {
1625
+ type: "object",
1626
+ additionalProperties: false,
1627
+ required: ["id"],
1628
+ properties: {
1629
+ id: {
1630
+ type: "string",
1631
+ description: "history_search \u6216\u4E0A\u4E0B\u7EA7\u8FD4\u56DE\u7684\u8282\u70B9 id\u3002"
1632
+ },
1633
+ host: {
1634
+ type: "string",
1635
+ description: "\u8DE8\u6765\u6E90 ID \u51B2\u7A81\u65F6\u663E\u5F0F\u6307\u5B9A\u6765\u6E90\u5BBF\u4E3B\u3002"
1636
+ },
1637
+ offset: {
1638
+ type: "integer",
1639
+ minimum: 0,
1640
+ description: "\u6B63\u6587\u5B57\u7B26\u504F\u79FB\uFF0C\u9ED8\u8BA4 0\u3002"
1641
+ },
1642
+ limit: {
1643
+ type: "integer",
1644
+ minimum: 1,
1645
+ maximum: historyPageLimits.read.max,
1646
+ description: `\u6B63\u6587\u5B57\u7B26\u6570\uFF081\u2013${historyPageLimits.read.max}\uFF09\uFF0C\u9ED8\u8BA4 ${historyPageLimits.read.default}\u3002`
1647
+ },
1648
+ childrenOffset: {
1649
+ type: "integer",
1650
+ minimum: 0,
1651
+ description: "\u5B50\u8282\u70B9\u5217\u8868\u504F\u79FB\uFF0C\u9ED8\u8BA4 0\uFF1B\u7EED\u8BFB\u4F20\u4E0A\u9875 nextChildrenOffset\u3002"
1652
+ },
1653
+ workspace
1654
+ }
1655
+ }
1656
+ }
1657
+ ];
1658
+ }
1659
+ var pbotWorkerTools = buildPbotWorkerTools();
1660
+ var definitions = [...pbotWorkerTools, ...buildWorkspaceMcpTools(), ...buildHistoryMcpTools()];
1661
+ var toolsByName = new Map(definitions.map(({ name, inputSchema }) => [name, { name, fields: new Set(Object.keys(inputSchema.properties)) }]));
1662
+ function parseMcpToolCall(name, args) {
1663
+ const tool = toolsByName.get(name);
1664
+ requireThat(tool, `\u672A\u77E5\u5DE5\u5177\uFF1A${name}\uFF08\u53EF\u7528\uFF1A${[...toolsByName.keys()].join(", ")}\uFF09\u3002`);
1665
+ requireThat(object(args), "\u5DE5\u5177\u53C2\u6570\u5FC5\u987B\u662F\u5BF9\u8C61\u3002");
1666
+ const unknown = Object.entries(args).filter(([key, value]) => value !== void 0 && !tool.fields.has(key)).map(([key]) => key);
1667
+ requireThat(unknown.length === 0, `\u672A\u77E5\u53C2\u6570\uFF1A${unknown.join(", ")}\uFF08${name} \u53EF\u7528\u53C2\u6570\uFF1A${[...tool.fields].join(", ")}\uFF09\u3002`);
1668
+ return { name: tool.name, args };
1669
+ }
1670
+
1671
+ // src/services/agents/agent-service.ts
1672
+ import { randomUUID as randomUUID3 } from "node:crypto";
1673
+ import { realpathSync as realpathSync3 } from "node:fs";
1674
+ import { resolve as resolve5 } from "node:path";
1675
+ var AgentService = class {
1676
+ constructor(root, directory, host) {
1677
+ this.root = root;
1678
+ this.host = host;
1679
+ this.files = new AgentFiles(directory);
1680
+ }
1681
+ files;
1682
+ #closed = false;
1683
+ #preserve = false;
1684
+ #starting = /* @__PURE__ */ new Map();
1685
+ #launches = /* @__PURE__ */ new Set();
1686
+ #closing;
1687
+ #releasing = /* @__PURE__ */ new Map();
1688
+ alive(id) {
1689
+ return this.#starting.has(id) || this.#releasing.has(id) || this.host.alive(id);
1690
+ }
1691
+ check() {
1692
+ requireThat(!this.#closed, "worker \u670D\u52A1\u5DF2\u5173\u95ED\u3002");
1693
+ }
1694
+ owned(d, owner) {
1695
+ return d.workspace === this.root && d.parentSessionId === owner.sessionId && (d.parentLeaf === null || owner.branch.includes(d.parentLeaf));
1696
+ }
1697
+ get(id, owner) {
1698
+ this.check();
1699
+ const d = this.files.read(id, "descriptor.json", descriptor);
1700
+ requireThat(this.owned(d, owner), "worker \u4E0D\u5C5E\u4E8E\u5F53\u524D\u4F1A\u8BDD\u3002");
1701
+ requireThat(releaseLine(d.release) === releaseLine(packageVersion), "worker \u7248\u672C\u4E0D\u517C\u5BB9\uFF1B\u8BF7\u505C\u6B62\u540E\u4F7F\u7528\u5339\u914D\u7248\u672C\u3002");
1702
+ return d;
1703
+ }
1704
+ records(owner) {
1705
+ this.check();
1706
+ return this.files.list().filter((d) => d.workspace === this.root && d.parentSessionId === owner.sessionId && releaseLine(d.release) === releaseLine(packageVersion));
1707
+ }
1708
+ list(owner) {
1709
+ return this.records(owner).map((d) => this.view(d, owner));
1710
+ }
1711
+ view(d, owner) {
1712
+ const run = this.files.read(d.agentId, "launch.json", launch);
1713
+ const saved = this.files.optional(d.agentId, "status.json", status);
1714
+ const current = saved?.generation === run.generation ? saved : void 0;
1715
+ const alive = this.alive(d.agentId), pending = this.#starting.get(d.agentId);
1716
+ const starting = pending && !pending.controller.signal.aborted;
1717
+ const reference = this.files.read(d.agentId, "acp-session.json", acpReference);
1718
+ const model = this.files.optional(d.agentId, "acp-model.json", acpModelState);
1719
+ const selection = model?.generation === run.generation ? {
1720
+ ...model.provider ? { provider: model.provider } : {},
1721
+ ...model.model ? { model: model.model } : {},
1722
+ ...model.resolvedModel ? { resolvedModel: model.resolvedModel } : {},
1723
+ ...model.thinking ? { thinking: model.thinking } : {}
1724
+ } : void 0;
1725
+ const pendingRequests = alive ? [
1726
+ ...this.files.pendingPermissions(d.agentId, run.generation).map((item) => ({ requestId: item.requestId, kind: "permission", description: item.description, options: item.options })),
1727
+ ...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 ?? "" })
1728
+ ] : [];
1729
+ return {
1730
+ ...d,
1731
+ name: run.name,
1732
+ generation: run.generation,
1733
+ owned: this.owned(d, owner),
1734
+ alive,
1735
+ backend: reference.backend,
1736
+ transport: "acp",
1737
+ capabilities: {
1738
+ steer: false,
1739
+ resume: Boolean(reference.capabilities?.resume || reference.capabilities?.load),
1740
+ transcript: false
1741
+ },
1742
+ ...selection ? { selection } : {},
1743
+ state: alive ? starting ? "starting" : run.stop || pending?.controller.signal.aborted ? "stopping" : current?.state ?? "starting" : current?.state === "error" ? "error" : "stopped",
1744
+ activity: starting ? "\u542F\u52A8" : alive ? current?.activity ?? "\u542F\u52A8" : current?.error ?? "\u5DF2\u505C\u6B62",
1745
+ ...current?.cycle ? { cycle: current.cycle } : {},
1746
+ ...current?.error ? { error: current.error } : {},
1747
+ ...pendingRequests.length ? { pendingRequests } : {}
1748
+ };
1749
+ }
1750
+ /** Answer a pending permission or elicitation request forwarded by the worker. */
1751
+ respond(id, input, owner) {
1752
+ const d = this.get(id, owner), run = this.files.read(id, "launch.json", launch);
1753
+ const pending = this.view(d, owner).pendingRequests ?? [];
1754
+ if (!input.requestId && pending.length > 1) {
1755
+ throw new Error("\u5B58\u5728\u591A\u6761\u5F85\u56DE\u590D\u8BF7\u6C42\uFF0C\u8BF7\u6307\u5B9A requestId\uFF1A" + pending.map((item) => item.requestId).join(", "));
1756
+ }
1757
+ const target = input.requestId ? pending.find((item) => item.requestId === input.requestId) : pending[0];
1758
+ 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");
1759
+ if (target.kind === "permission") {
1760
+ 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");
1761
+ let resolved = null;
1762
+ if (input.action === "cancel") {
1763
+ requireThat(input.optionId === void 0, "action \u4E3A cancel \u65F6\u4E0D\u80FD\u540C\u65F6\u6307\u5B9A optionId\u3002");
1764
+ } else if (input.optionId !== void 0) {
1765
+ const exact = target.options.find((option) => option.optionId === input.optionId);
1766
+ const byKind = target.options.filter((option) => option.kind === input.optionId);
1767
+ const matched = exact ?? (byKind.length === 1 ? byKind[0] : void 0);
1768
+ 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(", "));
1769
+ if (input.action === "accept") {
1770
+ requireThat(!matched.kind.startsWith("reject_"), `optionId ${matched.optionId} \u662F\u62D2\u7EDD\u9009\u9879\uFF0C\u4E0E action: "accept" \u51B2\u7A81\u3002`);
1771
+ } else {
1772
+ requireThat(!matched.kind.startsWith("allow_"), `optionId ${matched.optionId} \u662F\u5141\u8BB8\u9009\u9879\uFF0C\u4E0E action: "decline" \u51B2\u7A81\u3002`);
1773
+ }
1774
+ resolved = matched.optionId;
1775
+ } else {
1776
+ const pick = (...kinds) => kinds.map((kind) => target.options.find((option) => option.kind === kind)).find(Boolean)?.optionId;
1777
+ if (input.action === "accept") {
1778
+ const chosen = pick("allow_once", "allow_always");
1779
+ 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(", "));
1780
+ resolved = chosen;
1781
+ } else {
1782
+ resolved = pick("reject_once", "reject_always") ?? null;
1783
+ }
1784
+ }
1785
+ this.files.ensureSubdirectory(id, "permissions");
1786
+ this.files.write(
1787
+ id,
1788
+ "permissions/" + target.requestId + "-reply.json",
1789
+ { generation: run.generation, requestId: target.requestId, optionId: resolved },
1790
+ acpPermissionReply,
1791
+ true
1792
+ );
1793
+ return this.view(d, owner);
1794
+ }
1795
+ if (target.kind === "form") {
1796
+ requireThat(input.optionId === void 0, "\u95EE\u7B54/\u8868\u5355\u8BF7\u6C42\u4E0D\u4F7F\u7528 optionId\uFF1B\u8BF7\u5C06\u7B54\u6848\u586B\u5165 content\u3002");
1797
+ if (input.action !== "accept") {
1798
+ requireThat(input.content === void 0, `action \u4E3A ${input.action} \u65F6\u4E0D\u80FD\u4F20\u5165 content\u3002`);
1799
+ } else {
1800
+ requireThat(input.content === void 0 || object(input.content), "\u95EE\u7B54/\u8868\u5355\u7B54\u590D\u7684 content \u5FC5\u987B\u662F\u5BF9\u8C61\u3002");
1801
+ }
1802
+ this.files.ensureSubdirectory(id, "elicitations");
1803
+ this.files.write(id, "elicitations/" + target.requestId + "-reply.json", {
1804
+ generation: run.generation,
1805
+ requestId: target.requestId,
1806
+ action: input.action,
1807
+ ...input.action === "accept" ? { content: input.content ?? {} } : {}
1808
+ }, acpElicitationReply, true);
1809
+ return this.view(d, owner);
1810
+ }
1811
+ requireThat(input.optionId === void 0, "URL \u786E\u8BA4\u8BF7\u6C42\u4E0D\u4F7F\u7528 optionId\u3002");
1812
+ requireThat(input.content === void 0, "URL \u786E\u8BA4\u8BF7\u6C42\u4E0D\u4F7F\u7528 content\u3002");
1813
+ this.files.ensureSubdirectory(id, "elicitations");
1814
+ this.files.write(id, "elicitations/" + target.requestId + "-reply.json", {
1815
+ generation: run.generation,
1816
+ requestId: target.requestId,
1817
+ action: input.action
1818
+ }, acpElicitationReply, true);
1819
+ return this.view(d, owner);
1820
+ }
1821
+ async start(input, owner) {
1822
+ this.check();
1823
+ const { backend, ...supplied } = input;
1824
+ this.host.available(backend);
1825
+ const clean = Object.fromEntries(Object.entries(supplied).filter(([, v]) => v !== void 0));
1826
+ const options = this.host.filterOptions ? this.host.filterOptions(backend, clean) : clean;
1827
+ const reference = this.host.prepare(backend, options);
1828
+ const prepared = this.files.control(() => {
1829
+ 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");
1830
+ const agentId = randomUUID3();
1831
+ const cwd = realpathSync3(resolve5(this.root, options.cwd ?? "."));
1832
+ const files = (options.files ?? []).map((p) => realpathSync3(resolve5(this.root, p)));
1833
+ const d = {
1834
+ agentId,
1835
+ release: packageVersion,
1836
+ workspace: this.root,
1837
+ cwd,
1838
+ parentSessionId: owner.sessionId,
1839
+ parentLeaf: owner.leaf,
1840
+ createdAt: Date.now(),
1841
+ options: { ...options, files, cwd }
1842
+ };
1843
+ const run = { generation: randomUUID3(), name: options.name ?? agentId.slice(0, 8), sequence: 0, stop: false, startedAt: Date.now() };
1844
+ this.files.create(d, run, reference);
1845
+ const initial = options.message ?? "";
1846
+ const request = initial || files.length ? this.files.enqueue(agentId, initial, "steer", files) : void 0;
1847
+ this.#starting.set(agentId, { generation: run.generation, controller: new AbortController(), stage: "launch" });
1848
+ return { d, run, request };
1849
+ });
1850
+ await this.launch(prepared.d, prepared.run.generation);
1851
+ return { ...this.view(prepared.d, owner), ...prepared.request ? { requestId: prepared.request.requestId, messageStatus: "queued" } : {} };
1852
+ }
1853
+ async launch(d, generation, resume = false) {
1854
+ const pending = this.#starting.get(d.agentId);
1855
+ requireThat(pending?.generation === generation, "\u542F\u52A8\u9884\u7EA6\u5DF2\u5931\u6548\u3002");
1856
+ const operation = (async () => {
1857
+ try {
1858
+ await this.host.launch(d, this.files.directory(d.agentId), generation, this.files.reference(d.agentId), resume, pending.controller.signal);
1859
+ requireThat(!this.#closed || this.#preserve, "worker \u670D\u52A1\u5DF2\u5173\u95ED\u3002");
1860
+ pending.controller.signal.throwIfAborted();
1861
+ const run = this.files.read(d.agentId, "launch.json", launch);
1862
+ requireThat(run.generation === generation && !run.stop, "worker \u542F\u52A8\u5DF2\u53D6\u6D88\u6216\u4EE3\u6B21\u53D8\u5316\u3002");
1863
+ } catch (error) {
1864
+ const run = this.files.read(d.agentId, "launch.json", launch);
1865
+ if (run.generation === generation) {
1866
+ if (this.host.alive(d.agentId)) await this.release(d.agentId);
1867
+ this.files.write(d.agentId, "status.json", {
1868
+ generation,
1869
+ state: run.stop ? "stopped" : "error",
1870
+ activity: run.stop ? "\u5DF2\u505C\u6B62" : "\u542F\u52A8\u5931\u8D25",
1871
+ updatedAt: Date.now(),
1872
+ ...run.stop ? {} : { error: String(error) }
1873
+ }, status);
1874
+ }
1875
+ throw error;
1876
+ } finally {
1877
+ if (this.#starting.get(d.agentId) === pending) this.#starting.delete(d.agentId);
1878
+ }
1879
+ })();
1880
+ this.#launches.add(operation);
1881
+ try {
1882
+ await operation;
1883
+ } finally {
1884
+ this.#launches.delete(operation);
1885
+ }
1368
1886
  }
1369
- try {
1370
- const value = config(JSON.parse(content));
1371
- const settings = value;
1887
+ send(id, text3, delivery, owner, attachments = []) {
1888
+ const d = this.get(id, owner);
1889
+ return this.files.control(() => {
1890
+ 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");
1891
+ const view = this.view(d, owner);
1892
+ requireThat(!(delivery === "steer" && view.state !== "idle"), "\u8BE5 ACP worker \u8FD0\u884C\u4E2D\u4E0D\u652F\u6301 steer\uFF1B\u8BF7\u7528 delivery: followUp \u6392\u961F\u3002");
1893
+ const files = attachments.map((path) => realpathSync3(resolve5(this.root, path)));
1894
+ const request = this.files.enqueue(id, text3, delivery, files);
1895
+ return { ...this.view(d, owner), requestId: request.requestId, messageStatus: "queued" };
1896
+ });
1897
+ }
1898
+ rename(id, name, owner) {
1899
+ 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");
1900
+ const d = this.get(id, owner);
1901
+ this.files.control(() => {
1902
+ const run = this.files.read(id, "launch.json", launch);
1903
+ run.name = name;
1904
+ this.files.write(id, "launch.json", run, launch);
1905
+ });
1906
+ return this.view(d, owner);
1907
+ }
1908
+ stop(id, owner) {
1909
+ const d = this.get(id, owner);
1910
+ this.requestStop(id);
1911
+ return this.view(d, owner);
1912
+ }
1913
+ requestStop(id) {
1914
+ this.files.control(() => {
1915
+ const run = this.files.read(id, "launch.json", launch);
1916
+ run.stop = true;
1917
+ this.files.write(id, "launch.json", run, launch);
1918
+ });
1919
+ this.#starting.get(id)?.controller.abort();
1920
+ }
1921
+ async enter(id, owner) {
1922
+ const d = this.get(id, owner);
1923
+ if (this.alive(id)) {
1924
+ requireThat(!this.files.read(id, "launch.json", launch).stop, "worker \u6B63\u5728\u505C\u6B62\uFF0C\u8BF7\u7A0D\u540E\u64CD\u4F5C\u3002");
1925
+ return this.view(d, owner);
1926
+ }
1927
+ return this.restart(id, owner);
1928
+ }
1929
+ resume(id, text3, owner) {
1930
+ return this.restart(id, owner, text3);
1931
+ }
1932
+ async restart(id, owner, text3) {
1933
+ const d = this.get(id, owner), reference = this.files.reference(id);
1934
+ this.host.available(reference.backend);
1935
+ const reserved = this.files.control(() => {
1936
+ requireThat(!this.alive(id), "worker \u4ECD\u5728\u8FD0\u884C\u3002");
1937
+ requireThat(this.list(owner).filter((v) => v.alive).length < 50, "\u6700\u591A 50 \u4E2A\u5B58\u6D3B\u6216\u542F\u52A8\u4E2D worker\u3002");
1938
+ const previous = this.files.read(id, "launch.json", launch), interrupted = this.cycles(id, owner);
1939
+ const pending = { generation: previous.generation, controller: new AbortController(), stage: "validate" };
1940
+ this.#starting.set(id, pending);
1941
+ return { previous, interrupted, pending };
1942
+ });
1943
+ const operation = (async () => {
1944
+ await this.host.validateSession(d, this.files.reference(id));
1945
+ requireThat(!this.#closed || this.#preserve, "worker \u670D\u52A1\u5DF2\u5173\u95ED\u3002");
1946
+ reserved.pending.controller.signal.throwIfAborted();
1947
+ const prepared = this.files.control(() => {
1948
+ 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");
1949
+ for (const ended of reserved.interrupted) {
1950
+ if (ended.generation === reserved.previous.generation && !this.files.completions(id).some((c) => c.cycleId === ended.cycleId)) {
1951
+ this.files.write(id, "completions/" + ended.cycleId + ".json", ended, cycle, true);
1952
+ }
1953
+ }
1954
+ const run = { ...reserved.previous, generation: randomUUID3(), sequence: 0, stop: false, startedAt: Date.now() };
1955
+ this.files.write(id, "launch.json", run, launch);
1956
+ const request = text3 === void 0 ? void 0 : this.files.enqueue(id, text3, "steer");
1957
+ reserved.pending.generation = run.generation;
1958
+ reserved.pending.stage = "launch";
1959
+ return { run, request };
1960
+ });
1961
+ await this.launch(d, prepared.run.generation, true);
1962
+ return { ...this.view(d, owner), ...prepared.request ? { requestId: prepared.request.requestId, messageStatus: "queued" } : {} };
1963
+ })();
1964
+ this.#launches.add(operation);
1965
+ try {
1966
+ return await operation;
1967
+ } finally {
1968
+ this.#launches.delete(operation);
1969
+ if (this.#starting.get(id) === reserved.pending) this.#starting.delete(id);
1970
+ }
1971
+ }
1972
+ cycles(id, owner) {
1973
+ return this.cyclesFor(this.view(this.get(id, owner), owner));
1974
+ }
1975
+ cyclesFor(view) {
1976
+ const id = view.agentId;
1977
+ const values = this.files.completions(id);
1978
+ if (view.cycle && !values.some((c) => c.cycleId === view.cycle.cycleId)) {
1979
+ values.push(view.state === "stopped" || view.state === "error" ? { ...view.cycle, state: "interrupted", finishedAt: view.cycle.finishedAt ?? Date.now() } : view.cycle);
1980
+ }
1981
+ if (["stopped", "error"].includes(view.state)) {
1982
+ const run = this.files.read(id, "launch.json", launch), saved = this.files.optional(id, "status.json", status);
1983
+ for (const requestId of saved?.generation === run.generation ? saved.accepted ?? [] : []) {
1984
+ if (values.some((c) => c.generation === run.generation && c.requestIds.includes(requestId))) continue;
1985
+ values.push({
1986
+ cycleId: requestId,
1987
+ generation: run.generation,
1988
+ startedAt: run.startedAt,
1989
+ finishedAt: Date.now(),
1990
+ state: "interrupted",
1991
+ leaf: null,
1992
+ requestIds: [requestId],
1993
+ source: "parent",
1994
+ error: "\u9886\u53D6\u540E\u6267\u884C\u7ED3\u679C\u4E0D\u660E\uFF1B\u672A\u91CD\u8DD1\u3002"
1995
+ });
1996
+ }
1997
+ if (run.sequence > 0 && !values.some((c) => c.generation === view.generation)) {
1998
+ values.push({
1999
+ cycleId: run.generation,
2000
+ generation: run.generation,
2001
+ startedAt: run.startedAt,
2002
+ finishedAt: run.startedAt,
2003
+ state: "interrupted",
2004
+ leaf: null,
2005
+ requestIds: [],
2006
+ source: "parent",
2007
+ error: view.error ?? "\u5B50\u8FDB\u7A0B\u5728\u4EA4\u4ED8\u524D\u9000\u51FA\u3002"
2008
+ });
2009
+ }
2010
+ }
2011
+ return values;
2012
+ }
2013
+ snapshot(id, owner) {
2014
+ const view = this.view(this.get(id, owner), owner);
2015
+ const cycles = this.cyclesFor(view);
2016
+ const latest = cycles.at(-1);
2017
+ return { current: latest ? { ...view, cycle: latest } : view, cycles };
2018
+ }
2019
+ status(id, owner) {
2020
+ return this.snapshot(id, owner).current;
2021
+ }
2022
+ outputStatus(id, owner, requestId) {
2023
+ const { current, cycles } = this.snapshot(id, owner);
2024
+ const request = requestId ?? this.files.messages(id).findLast((item) => item.generation === current.generation)?.requestId;
2025
+ const cycle2 = request ? cycles.find((item) => item.generation === current.generation && item.requestIds.includes(request)) : current.cycle;
2026
+ const stopped = current.state === "stopped" || current.state === "error";
2027
+ const terminal = request ? stopped && !cycle2 : stopped || current.state === "idle" && !cycle2;
2028
+ return { current, cycle: cycle2, terminal };
2029
+ }
2030
+ async read(id, owner, cycleId, offset = 0, limit = 16e3) {
2031
+ const d = this.get(id, owner), cycles = this.cycles(id, owner);
2032
+ const c = cycleId ? cycles.find((v) => v.cycleId === cycleId) : cycles.at(-1);
2033
+ requireThat(!cycleId || c, "\u5468\u671F\u4E0D\u5B58\u5728\u3002");
2034
+ const report = c ? await this.report(d, c) : "";
2035
+ this.check();
2036
+ requireThat(offset <= report.length, "\u5206\u9875\u4F4D\u7F6E\u8D85\u51FA\u62A5\u544A\u3002");
1372
2037
  return {
1373
- path,
1374
- present: true,
1375
- enabled: settings.enabled === true,
1376
- ...settings.features ? { features: settings.features } : {},
1377
- ...settings.acp ? { acp: settings.acp } : {}
2038
+ ...this.view(d, owner),
2039
+ ...c ? { cycle: c } : {},
2040
+ cycles: cycles.map((v) => ({ cycleId: v.cycleId, state: v.state })),
2041
+ report: report.slice(offset, offset + limit),
2042
+ totalLength: report.length,
2043
+ nextOffset: offset + limit < report.length ? offset + limit : null
1378
2044
  };
1379
- } catch (error) {
1380
- return { path, present: true, enabled: false, error: `\u5DE5\u4F5C\u533A\u914D\u7F6E\u65E0\u6548 ${path}: ${String(error)}` };
1381
2045
  }
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;
2046
+ report(d, c) {
2047
+ if (c.leaf === null) return "";
2048
+ return this.host.report(d, this.files.reference(d.agentId), c.leaf);
1412
2049
  }
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
- );
2050
+ release(id) {
2051
+ let pending = this.#releasing.get(id);
2052
+ if (!pending) {
2053
+ const generation = this.files.read(id, "launch.json", launch).generation;
2054
+ pending = Promise.resolve().then(async () => {
2055
+ if (this.files.read(id, "launch.json", launch).generation === generation) await this.host.release(id, generation);
2056
+ }).finally(() => this.#releasing.delete(id));
2057
+ this.#releasing.set(id, pending);
2058
+ }
2059
+ return pending;
1430
2060
  }
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
- );
2061
+ close(owner, preserve = false) {
2062
+ return this.#closing ??= this.dispose(owner, preserve);
2063
+ }
2064
+ async dispose(owner, preserve = false) {
2065
+ if (this.#closed) return;
2066
+ const ids = !preserve && owner ? this.list(owner).filter((v) => v.alive).map((v) => v.agentId) : [];
2067
+ this.#closed = true;
2068
+ this.#preserve = preserve;
2069
+ const errors = [];
2070
+ for (const id of ids) {
2071
+ try {
2072
+ this.requestStop(id);
2073
+ } catch (error) {
2074
+ errors.push(error);
2075
+ }
2076
+ }
2077
+ if (!preserve) for (const pending of this.#starting.values()) pending.controller.abort();
2078
+ const deadline = Date.now() + 5e3;
2079
+ while (ids.some((id) => this.alive(id)) && Date.now() < deadline) await new Promise((r) => setTimeout(r, 100));
2080
+ const released = await Promise.allSettled(ids.filter((id) => this.host.alive(id)).map((id) => this.release(id)));
2081
+ for (const value of released) if (value.status === "rejected") errors.push(value.reason);
2082
+ await Promise.allSettled([...this.#launches]);
2083
+ 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");
1436
2084
  }
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`);
2085
+ };
2086
+
2087
+ // src/storage/history-files.ts
2088
+ import { spawnSync as spawnSync2 } from "node:child_process";
2089
+ import { linkSync as linkSync2, lstatSync as lstatSync3, mkdirSync as mkdirSync4, readdirSync as readdirSync2, readFileSync as readFileSync3, realpathSync as realpathSync4, rmdirSync as rmdirSync2, unlinkSync as unlinkSync2 } from "node:fs";
2090
+ import { basename as basename2, dirname as dirname3, join as join9, relative as relative2, resolve as resolve6 } from "node:path";
2091
+ import { isDeepStrictEqual } from "node:util";
2092
+
2093
+ // src/storage/history-format.ts
2094
+ var strings = (value) => Array.isArray(value) && value.every((item) => typeof item === "string");
2095
+ var fields = (value, names) => Object.keys(value).every((key) => names.includes(key));
2096
+ var rawFields = ["host", "id", "sessionId", "name", "exchanges", "branches"];
2097
+ var exchangeFields = ["id", "entryIds", "text", "from", "to", "completed"];
2098
+ var summaryArtifactFields = ["id", "dimension", "host", "sessionId", "title", "text", "from", "to", "updatedAt", "source"];
2099
+ var summarySourceFields = ["rawIds", "exchangeIds", "fingerprint"];
2100
+ function identity(value) {
2101
+ requireThat(
2102
+ object(value) && isHistoryIdentifier(value.host) && typeof value.id === "string" && typeof value.sessionId === "string" && value.sessionId.length > 0,
2103
+ "\u5386\u53F2\u5F52\u6863\u8EAB\u4EFD\u65E0\u6548\u3002"
2104
+ );
2105
+ fileId(value.id);
2106
+ }
2107
+ function matchIdentity(value, expected) {
2108
+ for (const key of ["host", "id", "sessionId"]) {
2109
+ requireThat(value[key] === expected[key], `\u5386\u53F2\u5F52\u6863 ${key} \u4E0D\u5339\u914D\uFF0C\u9884\u671F ${expected[key]}\uFF0C\u5B9E\u9645 ${value[key]}\u3002`);
1439
2110
  }
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) {
2111
+ }
2112
+ function exchange(value) {
2113
+ return object(value) && typeof value.id === "string" && value.id.length > 0 && strings(value.entryIds) && typeof value.text === "string" && typeof value.from === "string" && typeof value.to === "string" && typeof value.completed === "boolean";
2114
+ }
2115
+ function rawHistory(value) {
2116
+ identity(value);
2117
+ requireThat(
2118
+ object(value) && fields(value, rawFields) && typeof value.name === "string" && Array.isArray(value.exchanges) && Array.isArray(value.branches),
2119
+ "\u5386\u53F2\u539F\u6587\u5F52\u6863\u65E0\u6548\u3002"
2120
+ );
2121
+ const ids = /* @__PURE__ */ new Set();
2122
+ for (const item of value.exchanges) {
2123
+ requireThat(exchange(item) && fields(item, exchangeFields) && item.entryIds.length > 0, "\u5386\u53F2\u95EE\u7B54\u6216\u5176\u6765\u6E90\u6D88\u606F ID \u65E0\u6548\u3002");
2124
+ requireThat(item.id !== value.id && !ids.has(item.id), "\u5386\u53F2\u95EE\u7B54 ID \u91CD\u590D\uFF1A" + item.id);
2125
+ ids.add(item.id);
2126
+ }
2127
+ for (const branch of value.branches) {
1446
2128
  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`
2129
+ strings(branch) && new Set(branch).size === branch.length && branch.every((id) => ids.has(id)),
2130
+ "\u5386\u53F2\u5206\u652F\u5305\u542B\u91CD\u590D\u6216\u672A\u77E5\u7684\u95EE\u7B54 ID\u3002"
1449
2131
  );
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
2132
  }
2133
+ return value;
2134
+ }
2135
+ function summaryArtifact(value, expectedDimension) {
2136
+ requireThat(object(value) && fields(value, summaryArtifactFields), "\u5386\u53F2\u6458\u8981\u4EA7\u7269\u683C\u5F0F\u65E0\u6548\u3002");
2137
+ requireThat(typeof value.id === "string" && value.id.length > 0, "\u5386\u53F2\u6458\u8981 ID \u65E0\u6548\u3002");
2138
+ fileId(value.id);
2139
+ requireThat(isHistoryIdentifier(value.dimension), "\u5386\u53F2\u6458\u8981\u7EF4\u5EA6\u65E0\u6548\u3002");
2140
+ if (expectedDimension !== void 0) {
2141
+ requireThat(value.dimension === expectedDimension, `\u5386\u53F2\u6458\u8981\u7EF4\u5EA6\u4E0D\u5339\u914D\uFF0C\u9884\u671F ${expectedDimension}\uFF0C\u5B9E\u9645 ${value.dimension}\u3002`);
2142
+ }
2143
+ if (value.host !== void 0) requireThat(isHistoryIdentifier(value.host), "\u5386\u53F2\u6458\u8981\u6765\u6E90 host \u65E0\u6548\u3002");
2144
+ if (value.sessionId !== void 0) requireThat(typeof value.sessionId === "string" && value.sessionId.length > 0, "\u5386\u53F2\u6458\u8981 sessionId \u65E0\u6548\u3002");
1476
2145
  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`
2146
+ typeof value.title === "string" && typeof value.text === "string" && value.text.trim().length > 0 && typeof value.from === "string" && typeof value.to === "string" && typeof value.updatedAt === "string",
2147
+ "\u5386\u53F2\u6458\u8981\u6B63\u6587\u6216\u65F6\u95F4\u5B57\u6BB5\u65E0\u6548\u3002"
1479
2148
  );
1480
- const rawUrl = value.url.trim();
2149
+ const source = value.source;
1481
2150
  requireThat(
1482
- /^https?:\/\/.+/.test(rawUrl) || envPattern.test(rawUrl),
1483
- `MCP \u670D\u52A1 "${name}" \u7684 url \u5FC5\u987B\u4EE5 http:// \u6216 https:// \u5F00\u5934\u3002`
2151
+ object(source) && fields(source, summarySourceFields) && strings(source.rawIds) && source.rawIds.length > 0 && strings(source.exchangeIds) && typeof source.fingerprint === "string" && source.fingerprint.length > 0,
2152
+ "\u5386\u53F2\u6458\u8981\u6765\u6E90\u6307\u7EB9\u65E0\u6548\u3002"
1484
2153
  );
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;
2154
+ return value;
1493
2155
  }
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);
2156
+
2157
+ // src/storage/history-files.ts
2158
+ var yearPattern = /^\d{4}$/;
2159
+ var monthPattern = /^(?:0[1-9]|1[0-2])$/;
2160
+ var monthlyIdPattern = /^(\d{4})-(0[1-9]|1[0-2])$/;
2161
+ var monthlyRelativeJsonPattern = /^(?:\d{4}\/(?:0[1-9]|1[0-2])|unknown)\/[^/]+\.json$/;
2162
+ var yearlyRelativeJsonPattern = /^(?:\d{4}|unknown)\/[^/]+\.json$/;
2163
+ var unknownHistoryBucket = "unknown";
2164
+ function ordinaryDirectory(path) {
2165
+ const stat4 = lstatSync3(path, { throwIfNoEntry: false });
2166
+ if (!stat4) return false;
2167
+ requireThat(stat4.isDirectory() && !stat4.isSymbolicLink(), "\u5386\u53F2\u76EE\u5F55\u5FC5\u987B\u4F7F\u7528\u666E\u901A\u76EE\u5F55\uFF1A" + path);
2168
+ return true;
2169
+ }
2170
+ function ordinaryFile(path) {
2171
+ const stat4 = lstatSync3(path, { throwIfNoEntry: false });
2172
+ return Boolean(stat4 && stat4.isFile() && !stat4.isSymbolicLink());
2173
+ }
2174
+ function sharedDirectory(path) {
2175
+ const parent = dirname3(path);
2176
+ return (basename2(parent) !== ".pbot" || ordinaryDirectory(parent)) && ordinaryDirectory(path);
2177
+ }
2178
+ function ensureDirectory(path) {
2179
+ if (sharedDirectory(path)) return;
2180
+ const first = mkdirSync4(path, { recursive: true, mode: 448 });
2181
+ requireThat(sharedDirectory(path), "\u65E0\u6CD5\u521B\u5EFA\u5386\u53F2\u76EE\u5F55\uFF1A" + path);
2182
+ if (first) {
2183
+ const existing = dirname3(resolve6(first));
2184
+ for (let child = resolve6(path); child !== existing && child !== dirname3(child); child = dirname3(child)) {
2185
+ syncDirectory(realpathSync4(dirname3(child)));
2186
+ }
1501
2187
  }
1502
- return { mcpServers: servers };
1503
- }
1504
- function workspaceMcpPath(root) {
1505
- return join9(root, ".pbot", "mcp.json");
1506
2188
  }
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)}` };
2189
+ function earliestTimestamp(values) {
2190
+ let bestMs;
2191
+ let bestValue;
2192
+ for (const value of values) {
2193
+ if (!value) continue;
2194
+ const ms = Date.parse(value);
2195
+ if (Number.isNaN(ms)) continue;
2196
+ if (bestMs === void 0 || ms < bestMs) {
2197
+ bestMs = ms;
2198
+ bestValue = value;
2199
+ }
1515
2200
  }
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)}` };
2201
+ return bestValue;
2202
+ }
2203
+ function historyBucketFromTimestamp(timestamp) {
2204
+ if (!timestamp) return unknownHistoryBucket;
2205
+ const ms = Date.parse(timestamp);
2206
+ if (Number.isNaN(ms)) return unknownHistoryBucket;
2207
+ const date = new Date(ms);
2208
+ const year = String(date.getUTCFullYear()).padStart(4, "0");
2209
+ const month = String(date.getUTCMonth() + 1).padStart(2, "0");
2210
+ return `${year}/${month}`;
2211
+ }
2212
+ function rawHistoryBucket(raw) {
2213
+ const earliest = earliestTimestamp(raw.exchanges.map((item) => item.from)) ?? earliestTimestamp(raw.exchanges.map((item) => item.to));
2214
+ return historyBucketFromTimestamp(earliest);
2215
+ }
2216
+ function summaryArtifactBucket(artifact) {
2217
+ if (artifact.dimension === "monthly") {
2218
+ const match = monthlyIdPattern.exec(artifact.id);
2219
+ if (match) return match[1];
2220
+ const bucket = historyBucketFromTimestamp(artifact.from || artifact.to);
2221
+ return bucket === unknownHistoryBucket ? unknownHistoryBucket : bucket.slice(0, 4);
2222
+ }
2223
+ return historyBucketFromTimestamp(artifact.from || artifact.to);
2224
+ }
2225
+ var topLevelJsonNames = (directory) => readdirSync2(directory, { withFileTypes: true }).filter((entry) => entry.isFile() && !entry.isSymbolicLink() && entry.name.endsWith(".json")).map((entry) => entry.name).sort();
2226
+ function bucketDirs(directory, depth) {
2227
+ if (!ordinaryDirectory(directory)) return [];
2228
+ const buckets = [];
2229
+ const entries = readdirSync2(directory, { withFileTypes: true });
2230
+ const years = entries.filter((entry) => entry.isDirectory() && !entry.isSymbolicLink() && yearPattern.test(entry.name)).map((entry) => entry.name).sort((a, b) => b.localeCompare(a));
2231
+ if (depth === "year") {
2232
+ buckets.push(...years);
2233
+ } else {
2234
+ for (const year of years) {
2235
+ const yearDir = join9(directory, year);
2236
+ const months = readdirSync2(yearDir, { withFileTypes: true }).filter((entry) => entry.isDirectory() && !entry.isSymbolicLink() && monthPattern.test(entry.name)).map((entry) => entry.name).sort((a, b) => b.localeCompare(a));
2237
+ for (const month of months) buckets.push(`${year}/${month}`);
2238
+ }
1521
2239
  }
2240
+ if (entries.some((entry) => entry.isDirectory() && !entry.isSymbolicLink() && entry.name === unknownHistoryBucket)) {
2241
+ buckets.push(unknownHistoryBucket);
2242
+ }
2243
+ return buckets;
1522
2244
  }
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}`);
2245
+ function listLayoutJsonFiles(directory, layout, depth = "month") {
2246
+ if (!ordinaryDirectory(directory)) return [];
2247
+ if (layout === "flat") return topLevelJsonNames(directory);
2248
+ const results = [];
2249
+ for (const bucket of bucketDirs(directory, depth)) {
2250
+ const dir = join9(directory, bucket);
2251
+ for (const name of topLevelJsonNames(dir)) {
2252
+ results.push(`${bucket}/${name}`);
1538
2253
  }
1539
- return {
1540
- transport: "http",
1541
- name,
1542
- url,
1543
- headers,
1544
- ...server.description ? { description: server.description } : {},
1545
- timeout
1546
- };
1547
2254
  }
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}`);
2255
+ return results;
2256
+ }
2257
+ function locateLayoutFile(directory, name, layout, depth = "month") {
2258
+ if (!ordinaryDirectory(directory)) return void 0;
2259
+ if (layout === "flat") {
2260
+ return ordinaryFile(join9(directory, name)) ? name : void 0;
1553
2261
  }
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
- };
2262
+ for (const bucket of bucketDirs(directory, depth)) {
2263
+ if (ordinaryFile(join9(directory, bucket, name))) return `${bucket}/${name}`;
2264
+ }
2265
+ return void 0;
1565
2266
  }
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}`);
2267
+ var filename = (id) => fileId(id) + ".json";
2268
+ var diagnostic = (path, error) => path + ": " + String(error);
2269
+ function optional(read) {
2270
+ try {
2271
+ return read();
2272
+ } catch (error) {
2273
+ if (error.code !== "ENOENT") throw error;
2274
+ }
2275
+ }
2276
+ function namedRaw(value, relPath) {
2277
+ const raw = rawHistory(value);
2278
+ requireThat(basename2(relPath) === filename(raw.id), "\u5386\u53F2\u6587\u4EF6\u540D\u4E0E\u6839 ID \u4E0D\u5339\u914D\u3002");
2279
+ return raw;
2280
+ }
2281
+ function namedSummary(value, relPath, dimension) {
2282
+ const artifact = summaryArtifact(value, dimension);
2283
+ requireThat(basename2(relPath) === filename(artifact.id), "\u5386\u53F2\u6458\u8981\u6587\u4EF6\u540D\u4E0E ID \u4E0D\u5339\u914D\u3002");
2284
+ return artifact;
2285
+ }
2286
+ function canPrefilterWithRg(query) {
2287
+ return query.length > 0 && !/["\\\n\r\t]/.test(query);
2288
+ }
2289
+ function findCandidateJsonFiles(directory, query, layout = "monthly", depth = "month") {
2290
+ if (!ordinaryDirectory(directory)) return [];
2291
+ const trimmed = query.trim();
2292
+ if (!trimmed) return listLayoutJsonFiles(directory, layout, depth);
2293
+ const relativePattern = depth === "year" ? yearlyRelativeJsonPattern : monthlyRelativeJsonPattern;
2294
+ if (canPrefilterWithRg(trimmed)) {
2295
+ const args = [
2296
+ "--ignore-case",
2297
+ "--fixed-strings",
2298
+ "--files-with-matches",
2299
+ "--glob",
2300
+ "*.json",
2301
+ "--no-ignore",
2302
+ "--hidden",
2303
+ ...layout === "flat" ? ["--max-depth", "1"] : [],
2304
+ "--",
2305
+ trimmed,
2306
+ directory
2307
+ ];
2308
+ const result = spawnSync2("rg", args, { encoding: "utf8", maxBuffer: 8 * 1024 * 1024 });
2309
+ if (!result.error && (result.status === 0 || result.status === 1)) {
2310
+ if (result.status === 1) return [];
2311
+ const base = realpathSync4(directory);
2312
+ const matched2 = [];
2313
+ for (const line of result.stdout.split(/\r?\n/)) {
2314
+ const trimmedLine = line.trim();
2315
+ if (!trimmedLine) continue;
2316
+ const rel = relative2(base, resolve6(trimmedLine)).replaceAll("\\", "/");
2317
+ if (layout === "flat") {
2318
+ if (!rel.includes("/") && rel.endsWith(".json")) matched2.push(rel);
2319
+ } else if (relativePattern.test(rel)) {
2320
+ matched2.push(rel);
2321
+ }
2322
+ }
2323
+ return matched2;
2324
+ }
2325
+ }
2326
+ const needle = trimmed.toLowerCase();
2327
+ const matched = [];
2328
+ for (const rel of listLayoutJsonFiles(directory, layout, depth)) {
2329
+ try {
2330
+ const content = readFileSync3(join9(directory, rel), "utf8");
2331
+ if (content.toLowerCase().includes(needle)) matched.push(rel);
2332
+ } catch {
2333
+ }
2334
+ }
2335
+ return matched;
1573
2336
  }
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
- });
2337
+ var HistoryFiles = class {
2338
+ constructor(directory, host = "pi", layout = "monthly") {
2339
+ this.directory = directory;
2340
+ this.host = host;
2341
+ this.layout = layout;
2342
+ requireThat(isHistoryIdentifier(host), "\u5386\u53F2\u6765\u6E90\u65E0\u6548\u3002");
1609
2343
  }
1610
- get alive() {
1611
- return this.#alive && this.#child.exitCode === null && this.#child.signalCode === null;
2344
+ #warnings = [];
2345
+ #rawWarnings = [];
2346
+ get warnings() {
2347
+ return this.#warnings;
1612
2348
  }
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
- }
2349
+ get rawWarnings() {
2350
+ return this.#rawWarnings;
1620
2351
  }
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;
2352
+ get rawDirectory() {
2353
+ return join9(this.directory, "raw");
2354
+ }
2355
+ get summariesDirectory() {
2356
+ return join9(this.directory, "summaries");
2357
+ }
2358
+ summaryDirectory(dimension) {
2359
+ requireThat(isHistoryIdentifier(dimension), "\u5386\u53F2\u6458\u8981\u7EF4\u5EA6\u65E0\u6548\uFF1A" + dimension);
2360
+ return join9(this.summariesDirectory, dimension);
2361
+ }
2362
+ withLock(lockName, label, operation) {
2363
+ ensureDirectory(this.directory);
2364
+ const lock = join9(this.directory, lockName);
2365
+ try {
2366
+ mkdirSync4(lock, { mode: 448 });
2367
+ } catch (error) {
2368
+ if (error.code === "EEXIST") {
2369
+ throw Object.assign(new Error("\u5386\u53F2\u5199\u9501\u88AB\u5360\u7528\uFF1A" + label), { code: "PBOT_HISTORY_BUSY" });
1634
2370
  }
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);
2371
+ throw error;
1643
2372
  }
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");
2373
+ try {
2374
+ return operation();
2375
+ } finally {
2376
+ rmdirSync2(lock);
1653
2377
  }
1654
2378
  }
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
- });
2379
+ /** Synchronous host write lock for raw history files. */
2380
+ control(operation) {
2381
+ return this.withLock(".write-" + this.host, this.host, operation);
2382
+ }
2383
+ /** Synchronous dimension write lock for derived summary files. */
2384
+ controlSummary(dimension, operation) {
2385
+ requireThat(isHistoryIdentifier(dimension), "\u5386\u53F2\u6458\u8981\u7EF4\u5EA6\u65E0\u6548\uFF1A" + dimension);
2386
+ return this.withLock(".write-summary-" + dimension, "summary:" + dimension, operation);
2387
+ }
2388
+ /** Synchronous migration lock for explicit layout migration. */
2389
+ controlMigration(operation) {
2390
+ return this.withLock(".write-migrate", "migrate", operation);
2391
+ }
2392
+ migrationNotice() {
2393
+ return this.layout === "monthly" ? this.detectFlatFiles().message : void 0;
2394
+ }
2395
+ /** Detect unmigrated top-level flat JSON files when running under monthly layout. */
2396
+ detectFlatFiles() {
2397
+ if (!sharedDirectory(this.directory)) return { rawCount: 0, summaryCount: 0, total: 0 };
2398
+ const rawCount = ordinaryDirectory(this.rawDirectory) ? topLevelJsonNames(this.rawDirectory).length : 0;
2399
+ let summaryCount = 0;
2400
+ for (const dim of this.listDimensions()) {
2401
+ const dir = this.summaryDirectory(dim);
2402
+ if (ordinaryDirectory(dir)) summaryCount += topLevelJsonNames(dir).length;
2403
+ }
2404
+ const total = rawCount + summaryCount;
2405
+ if (total === 0) return { rawCount: 0, summaryCount: 0, total: 0 };
2406
+ return {
2407
+ rawCount,
2408
+ summaryCount,
2409
+ total,
2410
+ message: `\u68C0\u6D4B\u5230 ${total} \u4E2A\u672A\u8FC1\u79FB\u7684\u5E73\u94FA\u5386\u53F2\u6587\u4EF6\uFF08raw ${rawCount}\uFF0Csummaries ${summaryCount}\uFF09\uFF1B\u5F53\u524D\u4E3A\u5E74\u6708\u76EE\u5F55\u5E03\u5C40\uFF08history.layout: monthly\uFF09\uFF0C\u672A\u8FC1\u79FB\u6587\u4EF6\u4E0D\u4F1A\u88AB\u8BFB\u53D6\u3002\u8BF7\u5728\u7EC8\u7AEF\u8FD0\u884C pbot history migrate \u6574\u7406\u5230 YYYY/MM/ \u76EE\u5F55\uFF08Pi/dsh \u53EF\u7528 /pbot history migrate\uFF09\uFF0C\u6216\u5728 .pbot/config.json \u4E2D\u8BBE\u7F6E "history": { "layout": "flat" } \u5207\u56DE\u5E73\u94FA\u5E03\u5C40\u3002`
2411
+ };
1673
2412
  }
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`));
2413
+ listFlatRawFiles() {
2414
+ if (!sharedDirectory(this.directory) || !ordinaryDirectory(this.rawDirectory)) return [];
2415
+ return topLevelJsonNames(this.rawDirectory);
2416
+ }
2417
+ listFlatSummaryFiles(dimension) {
2418
+ requireThat(isHistoryIdentifier(dimension), "\u5386\u53F2\u6458\u8981\u7EF4\u5EA6\u65E0\u6548\uFF1A" + dimension);
2419
+ const dir = this.summaryDirectory(dimension);
2420
+ if (!sharedDirectory(this.directory) || !ordinaryDirectory(this.summariesDirectory) || !ordinaryDirectory(dir)) return [];
2421
+ return topLevelJsonNames(dir);
2422
+ }
2423
+ readFlatRawFile(name) {
2424
+ return readJsonFile(this.directory, "raw/" + name, (value) => namedRaw(value, name));
2425
+ }
2426
+ readFlatSummaryFile(dimension, name) {
2427
+ requireThat(isHistoryIdentifier(dimension), "\u5386\u53F2\u6458\u8981\u7EF4\u5EA6\u65E0\u6548\uFF1A" + dimension);
2428
+ return readJsonFile(this.directory, `summaries/${dimension}/${name}`, (value) => namedSummary(value, name, dimension));
2429
+ }
2430
+ /** Atomically move a file within .pbot/history/ without ever overwriting an existing destination. */
2431
+ moveHistoryFile(fromRelative, toRelative, dryRun = false) {
2432
+ const src = internalPath(this.directory, fromRelative);
2433
+ if (dryRun) {
2434
+ const target = internalPath(this.directory, toRelative, true);
2435
+ return ordinaryFile(target) ? "conflict" : "moved";
2436
+ }
2437
+ const dstParentRel = dirname3(toRelative);
2438
+ if (dstParentRel && dstParentRel !== ".") {
2439
+ privateDirectory(this.directory, dstParentRel);
2440
+ }
2441
+ const dst = internalPath(this.directory, toRelative);
2442
+ try {
2443
+ linkSync2(src, dst);
2444
+ } catch (error) {
2445
+ if (error.code === "EEXIST") return "conflict";
2446
+ throw error;
2447
+ }
2448
+ syncDirectory(dirname3(dst));
2449
+ unlinkSync2(src);
2450
+ syncDirectory(dirname3(src));
2451
+ return "moved";
2452
+ }
2453
+ listRaw(filterHost, onlyFiles) {
2454
+ this.#warnings = [];
2455
+ this.#rawWarnings = [];
2456
+ if (!sharedDirectory(this.directory) || !ordinaryDirectory(this.rawDirectory)) return [];
2457
+ const files = onlyFiles ?? listLayoutJsonFiles(this.rawDirectory, this.layout);
2458
+ const results = [];
2459
+ for (const rel of files) {
2460
+ const path = join9(this.rawDirectory, rel);
1678
2461
  try {
1679
- this.#child.stdin.end();
1680
- } catch {
2462
+ const raw = readJsonFile(this.directory, "raw/" + rel, (value) => namedRaw(value, rel));
2463
+ if (filterHost !== void 0 && raw.host !== filterHost) continue;
2464
+ results.push(raw);
2465
+ } catch (error) {
2466
+ if (error.code !== "ENOENT") {
2467
+ const message2 = diagnostic(path, error);
2468
+ this.#warnings.push(message2);
2469
+ this.#rawWarnings.push(message2);
2470
+ }
1681
2471
  }
1682
- if (this.#child.exitCode === null && this.#child.signalCode === null) this.#child.kill("SIGTERM");
1683
- const grace = new AbortController();
2472
+ }
2473
+ return results;
2474
+ }
2475
+ readRaw(id) {
2476
+ const name = filename(id);
2477
+ if (!sharedDirectory(this.directory) || !ordinaryDirectory(this.rawDirectory)) return void 0;
2478
+ const rel = locateLayoutFile(this.rawDirectory, name, this.layout);
2479
+ if (!rel) return void 0;
2480
+ return optional(() => readJsonFile(this.directory, "raw/" + rel, (value) => namedRaw(value, rel)));
2481
+ }
2482
+ saveRaw(raw) {
2483
+ requireThat(isHistoryIdentifier(raw.host) && raw.host === this.host, "\u5386\u53F2\u5F52\u6863\u53EA\u5141\u8BB8\u6240\u5C5E\u6765\u6E90\u5199\u5165\u3002");
2484
+ rawHistory(raw);
2485
+ ensureDirectory(this.directory);
2486
+ const name = filename(raw.id);
2487
+ const existingRel = ordinaryDirectory(this.rawDirectory) ? locateLayoutFile(this.rawDirectory, name, this.layout) : void 0;
2488
+ const bucket = this.layout === "monthly" ? rawHistoryBucket(raw) : void 0;
2489
+ const rel = existingRel ?? (bucket ? `${bucket}/${name}` : name);
2490
+ const current = optional(() => readJsonFile(this.directory, "raw/" + rel, (value) => namedRaw(value, rel)));
2491
+ if (current) {
2492
+ matchIdentity(current, raw);
2493
+ if (isDeepStrictEqual(current, raw)) return;
2494
+ } else {
2495
+ privateDirectory(this.directory, bucket ? `raw/${bucket}` : "raw");
2496
+ }
2497
+ requireThat(writeJsonFile(this.directory, "raw/" + rel, raw, rawHistory, !current), "\u5386\u53F2\u6839 ID \u5DF2\u88AB\u5360\u7528\uFF1A" + rel);
2498
+ }
2499
+ listDimensions() {
2500
+ if (!sharedDirectory(this.directory) || !ordinaryDirectory(this.summariesDirectory)) return [];
2501
+ const entries = readdirSync2(this.summariesDirectory, { withFileTypes: true });
2502
+ return entries.filter((entry) => entry.isDirectory() && !entry.isSymbolicLink() && isHistoryIdentifier(entry.name)).map((entry) => entry.name).sort();
2503
+ }
2504
+ summaryBucketDepth(dimension) {
2505
+ return dimension === "monthly" ? "year" : "month";
2506
+ }
2507
+ listSummaries(dimension, onlyFiles) {
2508
+ requireThat(isHistoryIdentifier(dimension), "\u5386\u53F2\u6458\u8981\u7EF4\u5EA6\u65E0\u6548\uFF1A" + dimension);
2509
+ const dir = this.summaryDirectory(dimension);
2510
+ if (!sharedDirectory(this.directory) || !ordinaryDirectory(this.summariesDirectory) || !ordinaryDirectory(dir)) return [];
2511
+ const files = onlyFiles ?? listLayoutJsonFiles(dir, this.layout, this.summaryBucketDepth(dimension));
2512
+ const results = [];
2513
+ for (const rel of files) {
2514
+ const path = join9(dir, rel);
1684
2515
  try {
1685
- await Promise.race([this.#exited, delay2(1500, void 0, { signal: grace.signal })]);
1686
- } finally {
1687
- grace.abort();
2516
+ results.push(readJsonFile(this.directory, `summaries/${dimension}/${rel}`, (value) => namedSummary(value, rel, dimension)));
2517
+ } catch (error) {
2518
+ if (error.code !== "ENOENT") {
2519
+ this.#warnings.push(diagnostic(path, error));
2520
+ }
1688
2521
  }
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
- })();
2522
+ }
2523
+ return results;
2524
+ }
2525
+ readSummary(dimension, id) {
2526
+ requireThat(isHistoryIdentifier(dimension), "\u5386\u53F2\u6458\u8981\u7EF4\u5EA6\u65E0\u6548\uFF1A" + dimension);
2527
+ const dir = this.summaryDirectory(dimension);
2528
+ if (!sharedDirectory(this.directory) || !ordinaryDirectory(this.summariesDirectory) || !ordinaryDirectory(dir)) return void 0;
2529
+ const name = filename(id);
2530
+ const rel = locateLayoutFile(dir, name, this.layout, this.summaryBucketDepth(dimension));
2531
+ if (!rel) return void 0;
2532
+ return optional(() => readJsonFile(this.directory, `summaries/${dimension}/${rel}`, (value) => namedSummary(value, rel, dimension)));
2533
+ }
2534
+ saveSummary(artifact) {
2535
+ summaryArtifact(artifact);
2536
+ ensureDirectory(this.directory);
2537
+ const name = filename(artifact.id);
2538
+ const dir = this.summaryDirectory(artifact.dimension);
2539
+ const depth = this.summaryBucketDepth(artifact.dimension);
2540
+ const existingRel = ordinaryDirectory(this.summariesDirectory) && ordinaryDirectory(dir) ? locateLayoutFile(dir, name, this.layout, depth) : void 0;
2541
+ const bucket = this.layout === "monthly" ? summaryArtifactBucket(artifact) : void 0;
2542
+ const rel = existingRel ?? (bucket ? `${bucket}/${name}` : name);
2543
+ const relativePath = `summaries/${artifact.dimension}/${rel}`;
2544
+ privateDirectory(this.directory, dirname3(relativePath));
2545
+ const current = optional(() => readJsonFile(this.directory, relativePath, (value) => namedSummary(value, rel, artifact.dimension)));
2546
+ if (current && isDeepStrictEqual(current, artifact)) return;
2547
+ requireThat(
2548
+ writeJsonFile(this.directory, relativePath, artifact, (value) => summaryArtifact(value, artifact.dimension), !current),
2549
+ "\u5386\u53F2\u6458\u8981\u6587\u4EF6\u5DF2\u88AB\u5360\u7528\uFF1A" + relativePath
2550
+ );
2551
+ }
2552
+ /** Isolated read-only candidate search across raw/ and summaries/<dimension>/. */
2553
+ searchCandidateRaw(query) {
2554
+ const names = findCandidateJsonFiles(this.rawDirectory, query, this.layout, "month");
2555
+ return this.listRaw(void 0, names);
2556
+ }
2557
+ searchCandidateSummaries(dimension, query) {
2558
+ const dir = this.summaryDirectory(dimension);
2559
+ const names = findCandidateJsonFiles(dir, query, this.layout, this.summaryBucketDepth(dimension));
2560
+ return this.listSummaries(dimension, names);
1694
2561
  }
1695
2562
  };
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;
2563
+
2564
+ // src/services/history/workspace-history.ts
2565
+ import { join as join11 } from "node:path";
2566
+
2567
+ // src/services/workspace/workspace-config.ts
2568
+ import { readFileSync as readFileSync4 } from "node:fs";
2569
+ import { mkdir, readFile as readFile2 } from "node:fs/promises";
2570
+ import { dirname as dirname4, join as join10 } from "node:path";
2571
+
2572
+ // src/model/workspace-config.ts
2573
+ var summaryConcurrency = { default: 3, max: 8 };
2574
+ var historyLayouts = ["monthly", "flat"];
2575
+
2576
+ // src/services/workspace/workspace-config.ts
2577
+ var featureKeys = ["prompts", "skills", "mcp", "history"];
2578
+ var summaryKeys = ["backend", "model", "thinking", "concurrency"];
2579
+ var historyKeys = ["layout"];
2580
+ function nonEmptyString(value) {
2581
+ return typeof value === "string" && value.trim().length > 0 && !value.includes("\0");
2582
+ }
2583
+ function config(value) {
2584
+ if (!object(value) || value.enabled !== void 0 && typeof value.enabled !== "boolean") {
2585
+ throw new Error("\u914D\u7F6E\u5FC5\u987B\u662F JSON \u5BF9\u8C61\uFF0Cenabled \u5FC5\u987B\u662F\u5E03\u5C14\u503C\u3002");
2586
+ }
2587
+ if (value.features !== void 0) {
2588
+ if (!object(value.features) || Object.entries(value.features).some(([key, entry]) => !featureKeys.includes(key) || entry !== void 0 && typeof entry !== "boolean")) {
2589
+ throw new Error("features \u5FC5\u987B\u662F JSON \u5BF9\u8C61\uFF0C\u4EC5\u652F\u6301 prompts\u3001skills\u3001mcp\u3001history \u5E03\u5C14\u5F00\u5173\u3002");
1709
2590
  }
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
2591
  }
1715
- return fallback;
2592
+ if (value.acp !== void 0) {
2593
+ if (!object(value.acp) || Object.keys(value.acp).some((key) => !isAcpBackend(key))) {
2594
+ 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");
2595
+ }
2596
+ for (const command of Object.values(value.acp)) {
2597
+ 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")));
2598
+ 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 && !isOneOf(command.permission, acpPermissionPolicies) || Object.keys(command).some((key) => !["command", "args", "env", "permission"].includes(key))) {
2599
+ 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");
2600
+ }
2601
+ }
2602
+ }
2603
+ if (value.summary !== void 0) {
2604
+ if (!object(value.summary) || Object.keys(value.summary).some((key) => !summaryKeys.includes(key))) {
2605
+ throw new Error("summary \u5FC5\u987B\u662F JSON \u5BF9\u8C61\uFF0C\u4EC5\u652F\u6301 backend\u3001model\u3001thinking\u3001concurrency\u3002");
2606
+ }
2607
+ if (value.summary.backend !== void 0 && !isAcpBackend(value.summary.backend)) {
2608
+ throw new Error("summary.backend \u5FC5\u987B\u4E3A\u5C0F\u5199\u5B57\u6BCD\u3001\u6570\u5B57\u548C\u8FDE\u5B57\u7B26\uFF081\u201364 \u5B57\u7B26\uFF09\u3002");
2609
+ }
2610
+ if (value.summary.model !== void 0 && !nonEmptyString(value.summary.model)) {
2611
+ throw new Error("summary.model \u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32\u3002");
2612
+ }
2613
+ if (value.summary.thinking !== void 0 && !nonEmptyString(value.summary.thinking)) {
2614
+ throw new Error("summary.thinking \u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32\u3002");
2615
+ }
2616
+ if (value.summary.concurrency !== void 0 && (typeof value.summary.concurrency !== "number" || !Number.isInteger(value.summary.concurrency) || value.summary.concurrency < 1 || value.summary.concurrency > summaryConcurrency.max)) {
2617
+ throw new Error(`summary.concurrency \u5FC5\u987B\u662F 1 \u5230 ${summaryConcurrency.max} \u4E4B\u95F4\u7684\u6574\u6570\u3002`);
2618
+ }
2619
+ }
2620
+ if (value.history !== void 0) {
2621
+ if (!object(value.history) || Object.keys(value.history).some((key) => !historyKeys.includes(key))) {
2622
+ throw new Error("history \u5FC5\u987B\u662F JSON \u5BF9\u8C61\uFF0C\u4EC5\u652F\u6301 layout\u3002");
2623
+ }
2624
+ if (value.history.layout !== void 0 && !isOneOf(value.history.layout, historyLayouts)) {
2625
+ throw new Error('history.layout \u5FC5\u987B\u662F "monthly" \u6216 "flat"\u3002');
2626
+ }
2627
+ }
2628
+ return value;
1716
2629
  }
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;
2630
+ function workspaceFeatures(configuration) {
2631
+ const raw = configuration && "features" in configuration ? configuration.features : configuration;
2632
+ return {
2633
+ prompts: raw?.prompts !== false,
2634
+ skills: raw?.skills !== false,
2635
+ mcp: raw?.mcp !== false,
2636
+ history: raw?.history !== false
2637
+ };
2638
+ }
2639
+ function workspaceHistoryConfig(configuration) {
2640
+ const raw = configuration && "history" in configuration ? configuration.history : configuration;
2641
+ return {
2642
+ layout: raw?.layout === "flat" ? "flat" : "monthly"
2643
+ };
2644
+ }
2645
+ function workspaceConfigPath(root) {
2646
+ return join10(root, ".pbot", "config.json");
2647
+ }
2648
+ function readWorkspaceHistoryLayoutSync(root) {
2649
+ const path = workspaceConfigPath(root);
2650
+ try {
2651
+ const content = readFileSync4(path, "utf8");
2652
+ const parsed = config(JSON.parse(content));
2653
+ return workspaceHistoryConfig(parsed.history).layout;
2654
+ } catch {
2655
+ return "monthly";
1726
2656
  }
1727
- get alive() {
1728
- return !this.#closed;
2657
+ }
2658
+ async function readWorkspaceConfig(root) {
2659
+ const path = workspaceConfigPath(root);
2660
+ let content;
2661
+ try {
2662
+ content = await readFile2(path, "utf8");
2663
+ } catch (error) {
2664
+ if (error.code === "ENOENT") return { path, present: false, enabled: false };
2665
+ return { path, present: true, enabled: false, error: `\u65E0\u6CD5\u8BFB\u53D6\u5DE5\u4F5C\u533A\u914D\u7F6E ${path}: ${String(error)}` };
1729
2666
  }
1730
- #headers() {
2667
+ try {
2668
+ const value = config(JSON.parse(content));
2669
+ const settings = value;
1731
2670
  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 } : {}
2671
+ path,
2672
+ present: true,
2673
+ enabled: settings.enabled === true,
2674
+ ...settings.features ? { features: settings.features } : {},
2675
+ ...settings.acp ? { acp: settings.acp } : {},
2676
+ ...settings.summary ? { summary: settings.summary } : {},
2677
+ ...settings.history ? { history: settings.history } : {}
1736
2678
  };
2679
+ } catch (error) {
2680
+ return { path, present: true, enabled: false, error: `\u5DE5\u4F5C\u533A\u914D\u7F6E\u65E0\u6548 ${path}: ${String(error)}` };
1737
2681
  }
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))
2682
+ }
2683
+ function workspaceDisabledMessage(configuration) {
2684
+ return configuration.error ?? `Personal Bot \u672A\u5728\u6B64\u5DE5\u4F5C\u533A\u542F\u7528\u3002\u8BF7\u5728\u5DE5\u4F5C\u533A\u6839\u76EE\u5F55\u8FD0\u884C pbot init\uFF0C\u4E5F\u53EF\u5728 Pi \u6216 dsh \u4E2D\u6267\u884C /pbot init\u3002\u914D\u7F6E\u6587\u4EF6\u4F4D\u4E8E ${configuration.path}`;
2685
+ }
2686
+
2687
+ // src/services/history/workspace-history.ts
2688
+ function workspaceHistoryFiles(root, host) {
2689
+ return new HistoryFiles(join11(root, ".pbot/history"), host, readWorkspaceHistoryLayoutSync(root));
2690
+ }
2691
+
2692
+ // src/services/history/history-index.ts
2693
+ function orderedRawExchanges(raw) {
2694
+ const lookup = new Map(raw.exchanges.map((item) => [item.id, item]));
2695
+ const seen = /* @__PURE__ */ new Set();
2696
+ const ordered = [];
2697
+ for (const branch of raw.branches) {
2698
+ for (const id of branch) {
2699
+ if (seen.has(id)) continue;
2700
+ const item = lookup.get(id);
2701
+ if (!item) continue;
2702
+ seen.add(id);
2703
+ ordered.push(item);
2704
+ }
2705
+ }
2706
+ const rest = raw.exchanges.filter((item) => !seen.has(item.id)).sort((a, b) => a.from.localeCompare(b.from) || a.id.localeCompare(b.id));
2707
+ ordered.push(...rest);
2708
+ return ordered;
2709
+ }
2710
+ function rawSessionTitle(raw) {
2711
+ return raw.name.trim();
2712
+ }
2713
+ function rawSessionSpan(exchanges) {
2714
+ const dates = exchanges.flatMap((item) => [item.from, item.to]).filter(Boolean).sort();
2715
+ return {
2716
+ from: dates[0] ?? "",
2717
+ to: dates.at(-1) ?? "",
2718
+ completed: exchanges.every((item) => item.completed)
2719
+ };
2720
+ }
2721
+
2722
+ // src/services/history/history-query.ts
2723
+ var summaryIdPrefix = "summary:";
2724
+ var page = (values, offset, limit) => ({
2725
+ values: values.slice(offset, offset + limit),
2726
+ nextOffset: offset + limit < values.length ? offset + limit : null
2727
+ });
2728
+ var previewText = (text3) => text3.replace(/\s+/g, " ").trim().slice(0, 100);
2729
+ function summaryNodeId(dimension, artifactId) {
2730
+ return `${summaryIdPrefix}${dimension}:${artifactId}`;
2731
+ }
2732
+ function parseSummaryNodeId(id) {
2733
+ if (!id.startsWith(summaryIdPrefix)) return void 0;
2734
+ const rest = id.slice(summaryIdPrefix.length);
2735
+ const sep2 = rest.indexOf(":");
2736
+ if (sep2 <= 0 || sep2 === rest.length - 1) return void 0;
2737
+ return { dimension: rest.slice(0, sep2), artifactId: rest.slice(sep2 + 1) };
2738
+ }
2739
+ function parseExchangeNodeId(id) {
2740
+ const index = id.indexOf(":0:");
2741
+ if (index <= 0) return void 0;
2742
+ return { rawId: id.slice(0, index) };
2743
+ }
2744
+ function sessionBrief(raw, summaryPreview) {
2745
+ const ordered = orderedRawExchanges(raw);
2746
+ const span = rawSessionSpan(ordered);
2747
+ const name = rawSessionTitle(raw);
2748
+ return {
2749
+ host: raw.host,
2750
+ id: raw.id,
2751
+ kind: "session",
2752
+ sessionId: raw.sessionId,
2753
+ name,
2754
+ preview: summaryPreview ? previewText(summaryPreview) : previewText(name || ordered[0]?.text || ""),
2755
+ from: span.from,
2756
+ to: span.to,
2757
+ ready: true,
2758
+ completed: span.completed
2759
+ };
2760
+ }
2761
+ function exchangeBrief(raw, exchange2, title) {
2762
+ return {
2763
+ host: raw.host,
2764
+ id: exchange2.id,
2765
+ kind: "exchange",
2766
+ sessionId: raw.sessionId,
2767
+ name: title,
2768
+ preview: previewText(exchange2.text),
2769
+ from: exchange2.from,
2770
+ to: exchange2.to,
2771
+ ready: true,
2772
+ completed: exchange2.completed
2773
+ };
2774
+ }
2775
+ function summaryBrief(artifact) {
2776
+ return {
2777
+ host: artifact.host ?? "workspace",
2778
+ id: summaryNodeId(artifact.dimension, artifact.id),
2779
+ kind: "summary",
2780
+ dimension: artifact.dimension,
2781
+ sessionId: artifact.sessionId ?? artifact.id,
2782
+ name: artifact.title,
2783
+ preview: previewText(artifact.text),
2784
+ from: artifact.from,
2785
+ to: artifact.to,
2786
+ ready: true,
2787
+ completed: true
2788
+ };
2789
+ }
2790
+ function sliceSnippet(text3, needle) {
2791
+ if (!needle) return text3.slice(0, 400);
2792
+ const start = Math.max(0, text3.toLowerCase().indexOf(needle) - 80);
2793
+ return text3.slice(start, start + 400);
2794
+ }
2795
+ function inTimeRange(from, to, after, before) {
2796
+ const fromMs = from ? Date.parse(from) : NaN;
2797
+ const toMs = to ? Date.parse(to) : NaN;
2798
+ if (after !== -Infinity && !Number.isNaN(toMs) && toMs < after) return false;
2799
+ if (before !== Infinity && !Number.isNaN(fromMs) && fromMs > before) return false;
2800
+ return true;
2801
+ }
2802
+ function searchWorkspaceHistory(root, query = {}) {
2803
+ const { host, sessionId, dimension, from, to, offset = 0, limit = historyPageLimits.search.default } = query;
2804
+ const needle = (query.query ?? "").trim().toLowerCase();
2805
+ const after = from === void 0 ? -Infinity : Date.parse(from);
2806
+ const before = to === void 0 ? Infinity : Date.parse(to);
2807
+ requireThat(!Number.isNaN(after) && !Number.isNaN(before) && after <= before, "\u65F6\u95F4\u8303\u56F4\u65E0\u6548\uFF0C\u8BF7\u4F7F\u7528 ISO \u65E5\u671F\u6216\u65F6\u95F4\u3002");
2808
+ const files = workspaceHistoryFiles(root);
2809
+ const warnings = [];
2810
+ const flatNotice = files.migrationNotice();
2811
+ if (flatNotice) warnings.push(flatNotice);
2812
+ const matches = [];
2813
+ function collectSummaries(artifacts) {
2814
+ warnings.push(...files.warnings);
2815
+ for (const artifact of artifacts) {
2816
+ if (!inTimeRange(artifact.from, artifact.to, after, before)) continue;
2817
+ if (needle && !`${artifact.title}
2818
+ ${artifact.text}`.toLowerCase().includes(needle)) continue;
2819
+ const brief = summaryBrief(artifact);
2820
+ if (host && brief.host !== host || sessionId && brief.sessionId !== sessionId) continue;
2821
+ matches.push({
2822
+ ...brief,
2823
+ parents: artifact.dimension === "monthly" ? [] : artifact.source.rawIds,
2824
+ snippet: sliceSnippet(artifact.text, needle)
1750
2825
  });
1751
- } catch {
1752
2826
  }
1753
2827
  }
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)}`);
2828
+ if (!needle) {
2829
+ if (dimension && dimension !== "raw") {
2830
+ collectSummaries(files.listSummaries(dimension));
2831
+ } else {
2832
+ const raws = files.listRaw(host);
2833
+ warnings.push(...files.warnings);
2834
+ const sessionSummaries = new Map(files.listSummaries("session").map((item) => [item.id, item]));
2835
+ warnings.push(...files.warnings);
2836
+ for (const raw of raws) {
2837
+ if (sessionId && raw.sessionId !== sessionId) continue;
2838
+ const summary = sessionSummaries.get(raw.id);
2839
+ const brief = sessionBrief(raw, summary?.text);
2840
+ if (!inTimeRange(brief.from, brief.to, after, before)) continue;
2841
+ matches.push({
2842
+ ...brief,
2843
+ parents: [],
2844
+ snippet: summary ? sliceSnippet(summary.text, "") : brief.preview
2845
+ });
2846
+ }
1768
2847
  }
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;
2848
+ } else {
2849
+ const searchRaw = !dimension || dimension === "raw";
2850
+ const summaryDimensions = dimension === "raw" ? [] : dimension ? [dimension] : files.listDimensions();
2851
+ if (searchRaw) {
2852
+ const candidateRaws = files.searchCandidateRaw(needle);
2853
+ warnings.push(...files.warnings);
2854
+ for (const raw of candidateRaws) {
2855
+ if (host && raw.host !== host) continue;
2856
+ if (sessionId && raw.sessionId !== sessionId) continue;
2857
+ const ordered = orderedRawExchanges(raw);
2858
+ const title = rawSessionTitle(raw);
2859
+ for (const item of ordered) {
2860
+ if (!item.text.toLowerCase().includes(needle)) continue;
2861
+ if (!inTimeRange(item.from, item.to, after, before)) continue;
2862
+ matches.push({
2863
+ ...exchangeBrief(raw, item, title),
2864
+ parents: [raw.id],
2865
+ snippet: sliceSnippet(item.text, needle)
2866
+ });
2867
+ }
1779
2868
  }
1780
2869
  }
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;
2870
+ for (const dim of summaryDimensions) {
2871
+ collectSummaries(files.searchCandidateSummaries(dim, needle));
2872
+ }
1784
2873
  }
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 {
2874
+ matches.sort((a, b) => b.to.localeCompare(a.to) || a.id.localeCompare(b.id));
2875
+ const paged = page(matches, offset, limit);
2876
+ return {
2877
+ matches: paged.values,
2878
+ total: matches.length,
2879
+ nextOffset: paged.nextOffset,
2880
+ warnings: [...new Set(warnings)]
2881
+ };
2882
+ }
2883
+ function sliceText(text3, offset, limit) {
2884
+ requireThat(offset <= text3.length, "\u8BFB\u53D6\u4F4D\u7F6E\u8D85\u51FA\u6B63\u6587\u3002");
2885
+ let start = offset;
2886
+ if (start && /[\uDC00-\uDFFF]/.test(text3[start] ?? "")) start--;
2887
+ let end = Math.min(text3.length, start + limit);
2888
+ if (end < text3.length && /[\uD800-\uDBFF]/.test(text3[end - 1] ?? "")) end += end - start === 1 ? 1 : -1;
2889
+ return {
2890
+ text: text3.slice(start, end),
2891
+ totalLength: text3.length,
2892
+ nextOffset: end < text3.length ? end : null
2893
+ };
2894
+ }
2895
+ function findMonthlyParent(files, bucket, rawId) {
2896
+ if (files.layout !== "monthly" || bucket === unknownHistoryBucket) return void 0;
2897
+ const monthly = files.readSummary("monthly", bucket.replace("/", "-"));
2898
+ if (!monthly || !monthly.source.rawIds.includes(rawId)) return void 0;
2899
+ return summaryBrief(monthly);
2900
+ }
2901
+ function readWorkspaceHistory(root, id, offset = 0, limit = historyPageLimits.read.default, childrenOffset = 0, host) {
2902
+ const files = workspaceHistoryFiles(root);
2903
+ const baseWarnings = [];
2904
+ const flatNotice = files.migrationNotice();
2905
+ if (flatNotice) baseWarnings.push(flatNotice);
2906
+ const parsedSummary = parseSummaryNodeId(id);
2907
+ if (parsedSummary) {
2908
+ const artifact = files.readSummary(parsedSummary.dimension, parsedSummary.artifactId);
2909
+ requireThat(artifact, "\u5386\u53F2\u8282\u70B9\u4E0D\u5B58\u5728\uFF0C\u8BF7\u91CD\u65B0\u641C\u7D22\u3002");
2910
+ const brief = summaryBrief(artifact);
2911
+ requireThat(!host || brief.host === host, "\u5386\u53F2\u8282\u70B9\u4E0D\u5B58\u5728\uFF0C\u8BF7\u91CD\u65B0\u641C\u7D22\u3002");
2912
+ const parents = [];
2913
+ const children = [];
2914
+ if (artifact.dimension === "monthly") {
2915
+ for (const rawId of artifact.source.rawIds) {
2916
+ const sessionSummary = files.readSummary("session", rawId);
2917
+ if (sessionSummary) {
2918
+ children.push(summaryBrief(sessionSummary));
2919
+ continue;
2920
+ }
2921
+ const raw2 = files.readRaw(rawId);
2922
+ if (raw2) children.push(sessionBrief(raw2));
2923
+ }
2924
+ } else {
2925
+ const wantedExchanges = new Set(artifact.source.exchangeIds);
2926
+ for (const rawId of artifact.source.rawIds) {
2927
+ const raw2 = files.readRaw(rawId);
2928
+ if (!raw2) continue;
2929
+ parents.push(sessionBrief(raw2, artifact.dimension === "session" ? artifact.text : void 0));
2930
+ const ordered2 = orderedRawExchanges(raw2);
2931
+ const title2 = rawSessionTitle(raw2);
2932
+ for (const item of ordered2) {
2933
+ if (!wantedExchanges.size || wantedExchanges.has(item.id)) {
2934
+ children.push(exchangeBrief(raw2, item, title2));
2935
+ }
2936
+ }
2937
+ }
2938
+ if (artifact.dimension === "session") {
2939
+ const bucket = historyBucketFromTimestamp(artifact.from || artifact.to);
2940
+ const monthlyParent2 = findMonthlyParent(files, bucket, artifact.id);
2941
+ if (monthlyParent2) parents.push(monthlyParent2);
1796
2942
  }
1797
2943
  }
2944
+ const pagedChildren2 = page(children, childrenOffset, 20);
2945
+ const sliced2 = sliceText(artifact.text, offset, limit);
2946
+ return {
2947
+ ...brief,
2948
+ ...sliced2,
2949
+ parents,
2950
+ children: pagedChildren2.values,
2951
+ nextChildrenOffset: pagedChildren2.nextOffset,
2952
+ source: {
2953
+ host: brief.host,
2954
+ sessionId: brief.sessionId,
2955
+ entryIds: artifact.source.exchangeIds,
2956
+ dimension: artifact.dimension
2957
+ },
2958
+ warnings: [.../* @__PURE__ */ new Set([...baseWarnings, ...files.warnings])]
2959
+ };
1798
2960
  }
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}`;
2961
+ const parsedExchange = parseExchangeNodeId(id);
2962
+ if (parsedExchange) {
2963
+ const raw2 = files.readRaw(parsedExchange.rawId);
2964
+ requireThat(raw2 && (!host || raw2.host === host), "\u5386\u53F2\u8282\u70B9\u4E0D\u5B58\u5728\uFF0C\u8BF7\u91CD\u65B0\u641C\u7D22\u3002");
2965
+ const exchange2 = raw2.exchanges.find((item) => item.id === id);
2966
+ requireThat(exchange2, "\u5386\u53F2\u8282\u70B9\u4E0D\u5B58\u5728\uFF0C\u8BF7\u91CD\u65B0\u641C\u7D22\u3002");
2967
+ const title2 = rawSessionTitle(raw2);
2968
+ const parents = [sessionBrief(raw2)];
2969
+ for (const dim of files.listDimensions()) {
2970
+ if (dim === "monthly") continue;
2971
+ const artifact = files.readSummary(dim, raw2.id);
2972
+ if (artifact) parents.push(summaryBrief(artifact));
2973
+ }
2974
+ const sliced2 = sliceText(exchange2.text, offset, limit);
2975
+ return {
2976
+ ...exchangeBrief(raw2, exchange2, title2),
2977
+ ...sliced2,
2978
+ parents,
2979
+ children: [],
2980
+ nextChildrenOffset: null,
2981
+ source: {
2982
+ host: raw2.host,
2983
+ sessionId: raw2.sessionId,
2984
+ entryIds: exchange2.entryIds
2985
+ },
2986
+ warnings: [.../* @__PURE__ */ new Set([...baseWarnings, ...files.warnings])]
2987
+ };
2988
+ }
2989
+ const raw = files.readRaw(id);
2990
+ requireThat(raw && (!host || raw.host === host), "\u5386\u53F2\u8282\u70B9\u4E0D\u5B58\u5728\uFF0C\u8BF7\u91CD\u65B0\u641C\u7D22\u3002");
2991
+ const ordered = orderedRawExchanges(raw);
2992
+ const title = rawSessionTitle(raw);
2993
+ const summaryChildren = [];
2994
+ let sessionSummaryText;
2995
+ for (const dim of files.listDimensions()) {
2996
+ if (dim === "monthly") continue;
2997
+ const artifact = files.readSummary(dim, raw.id);
2998
+ if (!artifact) continue;
2999
+ if (dim === "session") sessionSummaryText = artifact.text;
3000
+ summaryChildren.push(summaryBrief(artifact));
3001
+ }
3002
+ const monthlyParent = findMonthlyParent(files, rawHistoryBucket(raw), raw.id);
3003
+ const allChildren = [
3004
+ ...summaryChildren,
3005
+ ...ordered.map((item) => exchangeBrief(raw, item, title))
3006
+ ];
3007
+ const pagedChildren = page(allChildren, childrenOffset, 20);
3008
+ const body = sessionSummaryText ? title ? `${title}
3009
+
3010
+ ${sessionSummaryText}` : sessionSummaryText : title;
3011
+ const sliced = sliceText(body, offset, limit);
3012
+ return {
3013
+ ...sessionBrief(raw, sessionSummaryText),
3014
+ ...sliced,
3015
+ parents: monthlyParent ? [monthlyParent] : [],
3016
+ children: pagedChildren.values,
3017
+ nextChildrenOffset: pagedChildren.nextOffset,
3018
+ source: {
3019
+ host: raw.host,
3020
+ sessionId: raw.sessionId,
3021
+ entryIds: ordered.flatMap((item) => item.entryIds)
3022
+ },
3023
+ warnings: [.../* @__PURE__ */ new Set([...baseWarnings, ...files.warnings])]
3024
+ };
3025
+ }
3026
+
3027
+ // src/extension/mcp/bridge.ts
3028
+ import { spawn } from "node:child_process";
3029
+ import { setTimeout as delay2 } from "node:timers/promises";
3030
+
3031
+ // src/services/workspace/workspace-mcp.ts
3032
+ import { mkdir as mkdir2, readFile as readFile3 } from "node:fs/promises";
3033
+ import { dirname as dirname5, join as join12, resolve as resolve7 } from "node:path";
3034
+ var serverNamePattern = /^[A-Za-z0-9][A-Za-z0-9_-]{0,31}$/;
3035
+ var reservedServerNames = /* @__PURE__ */ new Set(["pbot"]);
3036
+ var stdioKeys = /* @__PURE__ */ new Set(["command", "args", "env", "cwd", "description", "timeout", "enabled"]);
3037
+ var httpKeys = /* @__PURE__ */ new Set(["url", "headers", "description", "timeout", "enabled"]);
3038
+ var defaultTimeoutSeconds = 60;
3039
+ var envPattern = /\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g;
3040
+ function isWorkspaceMcpHttpServer(server) {
3041
+ return "url" in server && typeof server.url === "string";
3042
+ }
3043
+ function validateStringRecord(value, label) {
3044
+ requireThat(object(value), `${label} \u5FC5\u987B\u662F\u5B57\u7B26\u4E32\u6620\u5C04\u3002`);
3045
+ return Object.fromEntries(Object.entries(value).map(([key, entry]) => {
3046
+ requireThat(
3047
+ key.length > 0 && !key.includes("\0") && typeof entry === "string" && !entry.includes("\0"),
3048
+ `${label}.${key} \u5FC5\u987B\u662F\u975E\u7A7A\u952E\u4E0E\u65E0\u7A7A\u5B57\u8282\u5B57\u7B26\u4E32\u503C\u3002`
3049
+ );
3050
+ return [key, entry];
3051
+ }));
3052
+ }
3053
+ function validateWorkspaceMcpServer(name, value) {
3054
+ 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`);
3055
+ requireThat(!reservedServerNames.has(name.toLowerCase()), `MCP \u670D\u52A1\u540D "${name}" \u4E3A Personal Bot \u4FDD\u7559\u540D\u79F0\u3002`);
3056
+ requireThat(object(value), `MCP \u670D\u52A1 "${name}" \u914D\u7F6E\u5FC5\u987B\u662F JSON \u5BF9\u8C61\u3002`);
3057
+ const hasCommand = value.command !== void 0;
3058
+ const hasUrl = value.url !== void 0;
3059
+ 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`);
3060
+ const allowed = hasCommand ? stdioKeys : httpKeys;
3061
+ const unknown = Object.keys(value).filter((key) => !allowed.has(key));
3062
+ requireThat(unknown.length === 0, `MCP \u670D\u52A1 "${name}" \u5305\u542B\u672A\u77E5\u5B57\u6BB5\uFF1A${unknown.join(", ")}\u3002`);
3063
+ if (value.description !== void 0) {
3064
+ requireThat(
3065
+ typeof value.description === "string" && !value.description.includes("\0"),
3066
+ `MCP \u670D\u52A1 "${name}" \u7684 description \u5FC5\u987B\u662F\u5B57\u7B26\u4E32\u3002`
3067
+ );
1806
3068
  }
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
- }
3069
+ if (value.timeout !== void 0) {
3070
+ requireThat(
3071
+ typeof value.timeout === "number" && Number.isInteger(value.timeout) && value.timeout >= 1 && value.timeout <= 3600,
3072
+ `MCP \u670D\u52A1 "${name}" \u7684 timeout \u5FC5\u987B\u662F 1\u20133600 \u7684\u6574\u6570\u79D2\u3002`
3073
+ );
1842
3074
  }
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()));
3075
+ if (value.enabled !== void 0) {
3076
+ requireThat(typeof value.enabled === "boolean", `MCP \u670D\u52A1 "${name}" \u7684 enabled \u5FC5\u987B\u662F\u5E03\u5C14\u503C\u3002`);
1855
3077
  }
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)
3078
+ const base = {
3079
+ ...value.description !== void 0 ? { description: value.description } : {},
3080
+ ...value.timeout !== void 0 ? { timeout: value.timeout } : {},
3081
+ ...value.enabled !== void 0 ? { enabled: value.enabled } : {}
3082
+ };
3083
+ if (hasCommand) {
3084
+ requireThat(
3085
+ typeof value.command === "string" && value.command.trim().length > 0 && !value.command.includes("\0"),
3086
+ `MCP \u670D\u52A1 "${name}" \u7684 command \u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32\u3002`
1862
3087
  );
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
- };
3088
+ let args;
3089
+ if (value.args !== void 0) {
3090
+ requireThat(
3091
+ Array.isArray(value.args) && value.args.every((item) => typeof item === "string" && !item.includes("\0")),
3092
+ `MCP \u670D\u52A1 "${name}" \u7684 args \u5FC5\u987B\u662F\u5B57\u7B26\u4E32\u6570\u7EC4\u3002`
3093
+ );
3094
+ args = [...value.args];
1878
3095
  }
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;
3096
+ const env = value.env !== void 0 ? validateStringRecord(value.env, `MCP \u670D\u52A1 "${name}" \u7684 env`) : void 0;
3097
+ let cwd;
3098
+ if (value.cwd !== void 0) {
3099
+ requireThat(
3100
+ typeof value.cwd === "string" && value.cwd.trim().length > 0 && !value.cwd.includes("\0"),
3101
+ `MCP \u670D\u52A1 "${name}" \u7684 cwd \u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32\u3002`
3102
+ );
3103
+ cwd = value.cwd;
1892
3104
  }
1893
- return {
1894
- workspace: root,
1895
- server: resolved.name,
1896
- transport: resolved.transport,
1897
- ...resolved.description ? { description: resolved.description } : {},
1898
- tools
3105
+ const entry2 = {
3106
+ command: value.command,
3107
+ ...args ? { args } : {},
3108
+ ...env ? { env } : {},
3109
+ ...cwd ? { cwd } : {},
3110
+ ...base
1899
3111
  };
3112
+ return entry2;
1900
3113
  }
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
- };
3114
+ requireThat(
3115
+ typeof value.url === "string" && value.url.trim().length > 0 && !value.url.includes("\0"),
3116
+ `MCP \u670D\u52A1 "${name}" \u7684 url \u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32\u3002`
3117
+ );
3118
+ const rawUrl = value.url.trim();
3119
+ requireThat(
3120
+ /^https?:\/\/.+/.test(rawUrl) || envPattern.test(rawUrl),
3121
+ `MCP \u670D\u52A1 "${name}" \u7684 url \u5FC5\u987B\u4EE5 http:// \u6216 https:// \u5F00\u5934\u3002`
3122
+ );
3123
+ envPattern.lastIndex = 0;
3124
+ const headers = value.headers !== void 0 ? validateStringRecord(value.headers, `MCP \u670D\u52A1 "${name}" \u7684 headers`) : void 0;
3125
+ const entry = {
3126
+ url: rawUrl,
3127
+ ...headers ? { headers } : {},
3128
+ ...base
3129
+ };
3130
+ return entry;
3131
+ }
3132
+ function validateMcpFile(value) {
3133
+ requireThat(object(value), "\u5DE5\u4F5C\u533A MCP \u914D\u7F6E\u5FC5\u987B\u662F JSON \u5BF9\u8C61\u3002");
3134
+ const rawServers = value.mcpServers;
3135
+ requireThat(rawServers !== void 0 && object(rawServers), "\u5DE5\u4F5C\u533A MCP \u914D\u7F6E\u9700\u8981 mcpServers \u5BF9\u8C61\u3002");
3136
+ const servers = {};
3137
+ for (const [name, entry] of Object.entries(rawServers)) {
3138
+ servers[name] = validateWorkspaceMcpServer(name, entry);
1926
3139
  }
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()));
3140
+ return { ...value, mcpServers: servers };
3141
+ }
3142
+ function workspaceMcpPath(root) {
3143
+ return join12(root, ".pbot", "mcp.json");
3144
+ }
3145
+ async function readWorkspaceMcpConfig(root) {
3146
+ const path = workspaceMcpPath(root);
3147
+ let content;
3148
+ try {
3149
+ content = await readFile3(path, "utf8");
3150
+ } catch (error) {
3151
+ if (error.code === "ENOENT") return { path, present: false, servers: {} };
3152
+ return { path, present: true, servers: {}, error: `\u65E0\u6CD5\u8BFB\u53D6\u5DE5\u4F5C\u533A MCP \u914D\u7F6E ${path}: ${String(error)}` };
3153
+ }
3154
+ try {
3155
+ const parsed = validateMcpFile(JSON.parse(content));
3156
+ return { path, present: true, servers: parsed.mcpServers };
3157
+ } catch (error) {
3158
+ return { path, present: true, servers: {}, error: `\u5DE5\u4F5C\u533A MCP \u914D\u7F6E\u65E0\u6548 ${path}: ${error instanceof Error ? error.message : String(error)}` };
1936
3159
  }
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
3160
  }
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 };
3161
+ function expandEnvTemplate(value, env, context) {
3162
+ return value.replace(envPattern, (_match, variable) => {
3163
+ const resolved = env[variable];
3164
+ requireThat(resolved !== void 0, `${context} \u5F15\u7528\u7684\u73AF\u5883\u53D8\u91CF ${variable} \u672A\u8BBE\u7F6E\u3002`);
3165
+ return resolved;
3166
+ });
1975
3167
  }
1976
- function workspaceProperty(workspaceBound) {
3168
+ function expandEnvRecord(values, env, context) {
3169
+ return Object.fromEntries(Object.entries(values ?? {}).map(([key, value]) => [key, expandEnvTemplate(value, env, `${context}.${key}`)]));
3170
+ }
3171
+ function resolveWorkspaceMcpServer(root, name, server, env = process.env) {
3172
+ const timeout = server.timeout ?? defaultTimeoutSeconds;
3173
+ if (isWorkspaceMcpHttpServer(server)) {
3174
+ const url = expandEnvTemplate(server.url, env, `MCP \u670D\u52A1 "${name}" \u7684 url`);
3175
+ requireThat(/^https?:\/\/.+/.test(url), `MCP \u670D\u52A1 "${name}" \u5C55\u5F00\u540E\u7684 url \u5FC5\u987B\u4EE5 http:// \u6216 https:// \u5F00\u5934\u3002`);
3176
+ return {
3177
+ transport: "http",
3178
+ name,
3179
+ url,
3180
+ headers: expandEnvRecord(server.headers, env, `MCP \u670D\u52A1 "${name}" \u7684 headers`),
3181
+ ...server.description ? { description: server.description } : {},
3182
+ timeout
3183
+ };
3184
+ }
3185
+ const command = expandEnvTemplate(server.command, env, `MCP \u670D\u52A1 "${name}" \u7684 command`);
3186
+ const args = (server.args ?? []).map((arg, index) => expandEnvTemplate(arg, env, `MCP \u670D\u52A1 "${name}" \u7684 args[${index}]`));
3187
+ const cwd = server.cwd ? resolve7(root, expandEnvTemplate(server.cwd, env, `MCP \u670D\u52A1 "${name}" \u7684 cwd`)) : root;
1977
3188
  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"
3189
+ transport: "stdio",
3190
+ name,
3191
+ command,
3192
+ args,
3193
+ env: expandEnvRecord(server.env, env, `MCP \u670D\u52A1 "${name}" \u7684 env`),
3194
+ cwd,
3195
+ ...server.description ? { description: server.description } : {},
3196
+ timeout
1980
3197
  };
1981
3198
  }
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
- }
3199
+
3200
+ // src/extension/mcp/bridge.ts
3201
+ var protocolVersion = "2025-03-26";
3202
+ var maxStderrBytes = 4096;
3203
+ function rpcError(server, method, error) {
3204
+ const detail = error.data !== void 0 ? `\uFF08${JSON.stringify(error.data)}\uFF09` : "";
3205
+ return new Error(`MCP \u670D\u52A1 "${server}" \u8C03\u7528 ${method} \u5931\u8D25\uFF1A${error.message ?? "\u672A\u77E5\u9519\u8BEF"}${detail}`);
3206
+ }
3207
+ var StdioMcpClient = class {
3208
+ fingerprint;
3209
+ #server;
3210
+ #child;
3211
+ #pending = /* @__PURE__ */ new Map();
3212
+ #exited;
3213
+ #nextId = 1;
3214
+ #buffer = "";
3215
+ #stderr = "";
3216
+ #alive = true;
3217
+ #closing;
3218
+ constructor(server, fingerprint) {
3219
+ this.#server = server;
3220
+ this.fingerprint = fingerprint;
3221
+ this.#child = spawn(server.command, server.args, {
3222
+ cwd: server.cwd,
3223
+ env: { ...process.env, ...server.env },
3224
+ stdio: ["pipe", "pipe", "pipe"]
3225
+ });
3226
+ this.#exited = new Promise((resolveExit) => this.#child.once("close", () => resolveExit()));
3227
+ this.#child.stdout.setEncoding("utf8");
3228
+ this.#child.stderr.setEncoding("utf8");
3229
+ this.#child.stdin.on("error", () => {
3230
+ });
3231
+ this.#child.stderr.on("data", (chunk) => {
3232
+ this.#stderr = (this.#stderr + String(chunk)).slice(-maxStderrBytes);
3233
+ });
3234
+ this.#child.stdout.on("data", (chunk) => this.#onData(String(chunk)));
3235
+ this.#child.once("error", (error) => this.#failAll(new Error(`MCP \u670D\u52A1 "${server.name}" \u542F\u52A8\u5931\u8D25\uFF1A${error.message}`)));
3236
+ this.#child.once("exit", (code, signal) => {
3237
+ const stderr = this.#stderr.trim();
3238
+ const suffix = stderr ? `
3239
+ stderr: ${stderr}` : "";
3240
+ this.#failAll(new Error(`MCP \u670D\u52A1 "${server.name}" \u8FDB\u7A0B\u5DF2\u9000\u51FA\uFF08${signal ?? code ?? "unknown"}\uFF09\u3002${suffix}`));
3241
+ });
3242
+ }
3243
+ get alive() {
3244
+ return this.#alive && this.#child.exitCode === null && this.#child.signalCode === null;
3245
+ }
3246
+ #failAll(error) {
3247
+ this.#alive = false;
3248
+ for (const [id, entry] of this.#pending) {
3249
+ clearTimeout(entry.timer);
3250
+ entry.reject(error);
3251
+ this.#pending.delete(id);
3252
+ }
3253
+ }
3254
+ #onData(chunk) {
3255
+ this.#buffer += chunk;
3256
+ for (; ; ) {
3257
+ const nl = this.#buffer.indexOf("\n");
3258
+ if (nl < 0) break;
3259
+ const line = this.#buffer.slice(0, nl).trim();
3260
+ this.#buffer = this.#buffer.slice(nl + 1);
3261
+ if (!line) continue;
3262
+ let parsed;
3263
+ try {
3264
+ parsed = JSON.parse(line);
3265
+ } catch {
3266
+ continue;
2020
3267
  }
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
- }
3268
+ if (!object(parsed) || typeof parsed.id !== "number") continue;
3269
+ const entry = this.#pending.get(parsed.id);
3270
+ if (!entry) continue;
3271
+ this.#pending.delete(parsed.id);
3272
+ clearTimeout(entry.timer);
3273
+ const response = parsed;
3274
+ if (response.error) entry.reject(rpcError(this.#server.name, "request", response.error));
3275
+ else entry.resolve(response.result);
3276
+ }
3277
+ }
3278
+ async initialize() {
3279
+ await this.request("initialize", {
3280
+ protocolVersion,
3281
+ capabilities: {},
3282
+ clientInfo: { name: "personal-bot", version: packageVersion }
3283
+ });
3284
+ if (this.alive) {
3285
+ this.#child.stdin.write(JSON.stringify({ jsonrpc: "2.0", method: "notifications/initialized" }) + "\n");
3286
+ }
3287
+ }
3288
+ request(method, params = {}) {
3289
+ if (!this.alive) return Promise.reject(new Error(`MCP \u670D\u52A1 "${this.#server.name}" \u8FDE\u63A5\u5DF2\u65AD\u5F00\u3002`));
3290
+ const id = this.#nextId++;
3291
+ const timeoutMs = this.#server.timeout * 1e3;
3292
+ return new Promise((resolveResponse, rejectResponse) => {
3293
+ const timer = setTimeout(() => {
3294
+ this.#pending.delete(id);
3295
+ rejectResponse(new Error(`MCP \u670D\u52A1 "${this.#server.name}" \u8C03\u7528 ${method} \u8D85\u65F6\uFF08${this.#server.timeout}s\uFF09\u3002`));
3296
+ }, timeoutMs);
3297
+ this.#pending.set(id, { resolve: resolveResponse, reject: rejectResponse, timer });
3298
+ try {
3299
+ this.#child.stdin.write(JSON.stringify({ jsonrpc: "2.0", id, method, params }) + "\n");
3300
+ } catch (error) {
3301
+ clearTimeout(timer);
3302
+ this.#pending.delete(id);
3303
+ rejectResponse(error instanceof Error ? error : new Error(String(error)));
2043
3304
  }
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
- }
3305
+ });
3306
+ }
3307
+ close() {
3308
+ return this.#closing ??= (async () => {
3309
+ this.#alive = false;
3310
+ this.#failAll(new Error(`MCP \u670D\u52A1 "${this.#server.name}" \u5DF2\u5173\u95ED\u3002`));
3311
+ try {
3312
+ this.#child.stdin.end();
3313
+ } catch {
2076
3314
  }
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
- }
3315
+ if (this.#child.exitCode === null && this.#child.signalCode === null) this.#child.kill("SIGTERM");
3316
+ const grace = new AbortController();
3317
+ try {
3318
+ await Promise.race([this.#exited, delay2(1500, void 0, { signal: grace.signal })]);
3319
+ } finally {
3320
+ grace.abort();
2123
3321
  }
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
- }
3322
+ if (this.#child.exitCode === null && this.#child.signalCode === null) this.#child.kill("SIGKILL");
3323
+ this.#child.stdout.destroy();
3324
+ this.#child.stderr.destroy();
3325
+ await this.#exited;
3326
+ })();
3327
+ }
3328
+ };
3329
+ function parseSseJsonRpc(body, expectedId) {
3330
+ const blocks = body.split(/\r?\n\r?\n/);
3331
+ let fallback;
3332
+ for (const block of blocks) {
3333
+ const dataLines = block.split(/\r?\n/).filter((line) => line.startsWith("data:")).map((line) => line.slice(5).trimStart());
3334
+ if (!dataLines.length) continue;
3335
+ const payload = dataLines.join("\n").trim();
3336
+ if (!payload || payload === "[DONE]") continue;
3337
+ let parsed;
3338
+ try {
3339
+ parsed = JSON.parse(payload);
3340
+ } catch {
3341
+ continue;
3342
+ }
3343
+ if (!object(parsed)) continue;
3344
+ const message2 = parsed;
3345
+ if (message2.id === expectedId) return message2;
3346
+ if (message2.result !== void 0 || message2.error !== void 0) fallback = message2;
3347
+ }
3348
+ return fallback;
3349
+ }
3350
+ var HttpMcpClient = class {
3351
+ fingerprint;
3352
+ #server;
3353
+ #nextId = 1;
3354
+ #sessionId;
3355
+ #closed = false;
3356
+ constructor(server, fingerprint) {
3357
+ this.#server = server;
3358
+ this.fingerprint = fingerprint;
3359
+ }
3360
+ get alive() {
3361
+ return !this.#closed;
3362
+ }
3363
+ #headers() {
3364
+ return {
3365
+ "Content-Type": "application/json",
3366
+ Accept: "application/json, text/event-stream",
3367
+ ...this.#server.headers,
3368
+ ...this.#sessionId ? { "Mcp-Session-Id": this.#sessionId } : {}
3369
+ };
3370
+ }
3371
+ async initialize() {
3372
+ await this.request("initialize", {
3373
+ protocolVersion,
3374
+ capabilities: {},
3375
+ clientInfo: { name: "personal-bot", version: packageVersion }
3376
+ });
3377
+ try {
3378
+ await fetch(this.#server.url, {
3379
+ method: "POST",
3380
+ headers: this.#headers(),
3381
+ body: JSON.stringify({ jsonrpc: "2.0", method: "notifications/initialized" }),
3382
+ signal: AbortSignal.timeout(Math.min(this.#server.timeout * 1e3, 1e4))
3383
+ });
3384
+ } catch {
3385
+ }
3386
+ }
3387
+ async request(method, params = {}) {
3388
+ requireThat(!this.#closed, `MCP \u670D\u52A1 "${this.#server.name}" \u8FDE\u63A5\u5DF2\u5173\u95ED\u3002`);
3389
+ const id = this.#nextId++;
3390
+ const response = await fetch(this.#server.url, {
3391
+ method: "POST",
3392
+ headers: this.#headers(),
3393
+ body: JSON.stringify({ jsonrpc: "2.0", id, method, params }),
3394
+ signal: AbortSignal.timeout(this.#server.timeout * 1e3)
3395
+ });
3396
+ const session = response.headers.get("mcp-session-id");
3397
+ if (session) this.#sessionId = session;
3398
+ const text3 = await response.text();
3399
+ if (!response.ok) {
3400
+ throw new Error(`MCP \u670D\u52A1 "${this.#server.name}" HTTP ${response.status}\uFF1A${text3.slice(0, 500)}`);
3401
+ }
3402
+ const contentType = response.headers.get("content-type") ?? "";
3403
+ let parsed;
3404
+ if (contentType.includes("text/event-stream")) {
3405
+ parsed = parseSseJsonRpc(text3, id);
3406
+ } else if (text3.trim()) {
3407
+ const raw = JSON.parse(text3);
3408
+ if (Array.isArray(raw)) {
3409
+ parsed = raw.find((item) => object(item) && item.id === id);
3410
+ } else if (object(raw)) {
3411
+ parsed = raw;
2157
3412
  }
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
- }
3413
+ }
3414
+ requireThat(parsed !== void 0, `MCP \u670D\u52A1 "${this.#server.name}" \u8FD4\u56DE\u7A7A\u54CD\u5E94\uFF08${method}\uFF09\u3002`);
3415
+ if (parsed.error) throw rpcError(this.#server.name, method, parsed.error);
3416
+ return parsed.result;
3417
+ }
3418
+ async close() {
3419
+ if (this.#closed) return;
3420
+ this.#closed = true;
3421
+ if (this.#sessionId) {
3422
+ try {
3423
+ await fetch(this.#server.url, {
3424
+ method: "DELETE",
3425
+ headers: this.#headers(),
3426
+ signal: AbortSignal.timeout(3e3)
3427
+ });
3428
+ } catch {
2193
3429
  }
2194
3430
  }
2195
- ];
3431
+ }
3432
+ };
3433
+ function configuredServer(root, configuration, serverName) {
3434
+ const raw = Object.hasOwn(configuration.servers, serverName) ? configuration.servers[serverName] : void 0;
3435
+ 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`);
3436
+ requireThat(raw.enabled !== false, `\u5DE5\u4F5C\u533A MCP \u670D\u52A1 "${serverName}" \u5F53\u524D\u5DF2\u505C\u7528\uFF08enabled: false\uFF09\u3002`);
3437
+ return resolveWorkspaceMcpServer(root, serverName, raw);
2196
3438
  }
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
- }
3439
+ var WorkspaceMcpBridge = class {
3440
+ #connections = /* @__PURE__ */ new Set();
3441
+ #closing;
3442
+ #close(connection) {
3443
+ return connection.closing ??= connection.ready.catch(() => {
3444
+ }).then(() => connection.client.close()).finally(() => this.#connections.delete(connection));
3445
+ }
3446
+ #retire(connection) {
3447
+ connection.retired = true;
3448
+ if (!connection.users) return this.#close(connection);
3449
+ }
3450
+ async #withClient(root, server, operation) {
3451
+ requireThat(!this.#closing, "Workspace MCP \u6865\u63A5\u5DF2\u5173\u95ED\u3002");
3452
+ const key = `${root}\0${server.name}`;
3453
+ const fingerprint = JSON.stringify(server);
3454
+ let connection = [...this.#connections].find((entry) => entry.key === key && !entry.retired);
3455
+ if (connection && (!connection.client.alive || connection.client.fingerprint !== fingerprint)) {
3456
+ void this.#retire(connection)?.catch(() => {
3457
+ });
3458
+ connection = void 0;
3459
+ }
3460
+ if (!connection) {
3461
+ const client = server.transport === "http" ? new HttpMcpClient(server, fingerprint) : new StdioMcpClient(server, fingerprint);
3462
+ connection = { key, client, ready: client.initialize(), users: 0, retired: false };
3463
+ this.#connections.add(connection);
3464
+ }
3465
+ connection.users++;
3466
+ try {
3467
+ try {
3468
+ await connection.ready;
3469
+ } catch (error) {
3470
+ connection.retired = true;
3471
+ throw error;
2221
3472
  }
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
- }
3473
+ requireThat(!this.#closing, "Workspace MCP \u6865\u63A5\u5DF2\u5173\u95ED\u3002");
3474
+ return await operation(connection.client);
3475
+ } finally {
3476
+ connection.users--;
3477
+ if (connection.retired && !connection.users) await this.#close(connection).catch(() => {
3478
+ });
3479
+ }
3480
+ }
3481
+ async #pruneRemoved(root, activeNames) {
3482
+ const prefix = `${root}\0`;
3483
+ await Promise.allSettled([...this.#connections].filter((entry) => entry.key.startsWith(prefix) && !activeNames.has(entry.key.slice(prefix.length))).map((entry) => this.#retire(entry)));
3484
+ }
3485
+ async discover(root, serverName) {
3486
+ requireThat(!this.#closing, "Workspace MCP \u6865\u63A5\u5DF2\u5173\u95ED\u3002");
3487
+ const configuration = await readWorkspaceMcpConfig(root);
3488
+ if (configuration.error) throw new Error(configuration.error);
3489
+ const enabledNames = new Set(
3490
+ Object.entries(configuration.servers).filter(([, entry]) => entry.enabled !== false).map(([name]) => name)
3491
+ );
3492
+ await this.#pruneRemoved(root, enabledNames);
3493
+ if (!serverName) {
3494
+ const servers = Object.entries(configuration.servers).map(([name, entry]) => ({
3495
+ name,
3496
+ transport: "url" in entry ? "http" : "stdio",
3497
+ enabled: entry.enabled !== false,
3498
+ ...entry.description ? { description: entry.description } : {},
3499
+ ...entry.timeout ? { timeout: entry.timeout } : {},
3500
+ ..."url" in entry ? { url: entry.url } : { command: entry.command, args: entry.args ?? [] }
3501
+ }));
3502
+ return {
3503
+ workspace: root,
3504
+ configPath: configuration.path,
3505
+ servers
3506
+ };
3507
+ }
3508
+ const resolved = configuredServer(root, configuration, serverName);
3509
+ return this.#withClient(root, resolved, async (client) => {
3510
+ const tools = [];
3511
+ let cursor;
3512
+ for (; ; ) {
3513
+ const page2 = await client.request("tools/list", cursor ? { cursor } : {});
3514
+ if (object(page2) && Array.isArray(page2.tools)) tools.push(...page2.tools);
3515
+ const next = object(page2) && typeof page2.nextCursor === "string" && page2.nextCursor ? page2.nextCursor : void 0;
3516
+ if (!next) break;
3517
+ cursor = next;
2253
3518
  }
3519
+ return {
3520
+ workspace: root,
3521
+ server: resolved.name,
3522
+ transport: resolved.transport,
3523
+ ...resolved.description ? { description: resolved.description } : {},
3524
+ tools
3525
+ };
3526
+ });
3527
+ }
3528
+ async call(root, serverName, toolName, args = {}) {
3529
+ requireThat(!this.#closing, "Workspace MCP \u6865\u63A5\u5DF2\u5173\u95ED\u3002");
3530
+ const configuration = await readWorkspaceMcpConfig(root);
3531
+ if (configuration.error) throw new Error(configuration.error);
3532
+ const resolved = configuredServer(root, configuration, serverName);
3533
+ const result = await this.#withClient(root, resolved, (client) => client.request("tools/call", { name: toolName, arguments: args }));
3534
+ if (object(result)) {
3535
+ return {
3536
+ server: resolved.name,
3537
+ tool: toolName,
3538
+ isError: result.isError === true,
3539
+ content: Array.isArray(result.content) ? result.content : [],
3540
+ ...result.structuredContent !== void 0 ? { structuredContent: result.structuredContent } : {}
3541
+ };
2254
3542
  }
2255
- ];
2256
- }
2257
- var pbotWorkerTools = buildPbotWorkerTools();
3543
+ return {
3544
+ server: resolved.name,
3545
+ tool: toolName,
3546
+ isError: false,
3547
+ content: result === void 0 ? [] : [{ type: "text", text: JSON.stringify(result) }]
3548
+ };
3549
+ }
3550
+ close() {
3551
+ return this.#closing ??= Promise.allSettled([...this.#connections].map((entry) => this.#close(entry))).then(() => {
3552
+ });
3553
+ }
3554
+ };
3555
+
3556
+ // src/extension/mcp/workers.ts
3557
+ var protocolVersion2 = "2025-03-26";
3558
+ var readyTimeoutMs = 45e3;
3559
+ var reportPageSize = 16e3;
3560
+ var progressIntervalMs = 5e3;
3561
+ var mcpWorkerOnlyInstructions = "\u63D0\u4F9B\u8DE8\u52A9\u624B\u534F\u4F5C\u80FD\u529B\uFF08worker_*\uFF09\uFF1A\u53EF\u542F\u52A8\u5E76\u8C03\u5EA6\u5176\u4ED6\u5916\u90E8 AI \u52A9\u624B\u5728\u5F53\u524D\u5DE5\u4F5C\u533A\u4E2D\u72EC\u7ACB\u6267\u884C\u4EFB\u52A1\uFF0C\u9002\u7528\u4E8E\u7528\u6237\u6307\u5B9A\u5176\u4ED6\u52A9\u624B\u3001\u9700\u8981\u7279\u5B9A\u6A21\u578B\u6216\u601D\u8003\u6DF1\u5EA6\u3001\u83B7\u53D6\u72EC\u7ACB\u5BA1\u67E5/\u7B2C\u4E8C\u610F\u89C1\uFF0C\u6216\u5E76\u884C\u5904\u7406\u5B50\u4EFB\u52A1\u3002\u4E0D\u9700\u8981\u501F\u52A9\u5176\u4ED6\u52A9\u624B\u65F6\uFF0C\u4F18\u5148\u81EA\u884C\u5B8C\u6210\u6216\u4F7F\u7528\u5F53\u524D\u5185\u7F6E\u5B50\u4EE3\u7406\u3002\n\u4F7F\u7528\u6D41\u7A0B\uFF1A\u7528 worker_create \u542F\u52A8\u76EE\u6807\u52A9\u624B\uFF08\u6216\u7528 worker_discover \u590D\u7528\u5DF2\u6709\u4F1A\u8BDD\uFF09\u2192 \u7528 worker_request \u6D3E\u53D1\u4EFB\u52A1\u6216\u7EE7\u7EED\u8FFD\u95EE \u2192 \u4EFB\u52A1\u5B8C\u6210\u540E\u53EF\u7528 worker_close \u7ED3\u675F\u4F1A\u8BDD\u3002\u540E\u53F0\u7B49\u5F85\u3001\u8D85\u65F6\u7EED\u7B49\uFF08timedOut\uFF09\u6216\u957F\u7ED3\u679C\u7FFB\u9875\uFF08nextOffset\uFF09\u7528 worker_output\uFF1B\u52A9\u624B\u8BF7\u6C42\u6388\u6743\u6216\u63D0\u95EE\uFF08needsResponse\uFF09\u65F6\uFF0C\u5148\u5411\u7528\u6237\u786E\u8BA4\uFF0C\u518D\u7528 worker_response \u56DE\u590D\u3002";
3562
+ var mcpInstructions = "\u63D0\u4F9B\u4E09\u7C7B\u80FD\u529B\uFF1A\n1. \u8DE8\u52A9\u624B\u534F\u4F5C\uFF08worker_*\uFF09\uFF1A\u542F\u52A8\u5E76\u8C03\u5EA6\u5176\u4ED6\u5916\u90E8 AI \u52A9\u624B\u5728\u5F53\u524D\u5DE5\u4F5C\u533A\u4E2D\u72EC\u7ACB\u6267\u884C\u4EFB\u52A1\uFF0C\u9002\u7528\u4E8E\u7528\u6237\u6307\u5B9A\u5176\u4ED6\u52A9\u624B\u3001\u9700\u8981\u7279\u5B9A\u6A21\u578B\u6216\u601D\u8003\u6DF1\u5EA6\u3001\u83B7\u53D6\u72EC\u7ACB\u5BA1\u67E5/\u7B2C\u4E8C\u610F\u89C1\uFF0C\u6216\u5E76\u884C\u5904\u7406\u5B50\u4EFB\u52A1\u3002\u4E0D\u9700\u8981\u501F\u52A9\u5176\u4ED6\u52A9\u624B\u65F6\uFF0C\u4F18\u5148\u81EA\u884C\u5B8C\u6210\u6216\u4F7F\u7528\u5F53\u524D\u5185\u7F6E\u5B50\u4EE3\u7406\u3002\u4F7F\u7528\u6D41\u7A0B\uFF1Aworker_create \u542F\u52A8\u52A9\u624B\uFF08\u6216 worker_discover \u590D\u7528\u5DF2\u6709\u4F1A\u8BDD\uFF09\u2192 worker_request \u6D3E\u53D1\u4EFB\u52A1\u6216\u8FFD\u95EE \u2192 \u5B8C\u6210\u540E worker_close \u7ED3\u675F\uFF1B\u540E\u53F0\u7B49\u5F85\u3001\u8D85\u65F6\u7EED\u7B49\uFF08timedOut\uFF09\u6216\u957F\u7ED3\u679C\u7FFB\u9875\uFF08nextOffset\uFF09\u7528 worker_output\uFF1B\u8FD4\u56DE needsResponse \u65F6\u5148\u5411\u7528\u6237\u786E\u8BA4\uFF0C\u518D\u7528 worker_response \u56DE\u590D\u3002\n2. \u5DE5\u4F5C\u533A\u5171\u4EAB\u5916\u90E8\u5DE5\u5177\uFF08workspace_mcp_*\uFF09\uFF1A\u53D1\u73B0\u5E76\u8C03\u7528\u5F53\u524D\u5DE5\u4F5C\u533A\u63A5\u5165\u7684\u5916\u90E8\u5DE5\u5177\u670D\u52A1\u4E0E\u6570\u636E\u6E90\uFF08\u53EF\u4E0E\u5F53\u524D\u73AF\u5883\u539F\u751F\u5DE5\u5177\u540C\u65F6\u4F7F\u7528\uFF09\u3002\u5148\u7528 workspace_mcp_discover \u67E5\u770B\u53EF\u7528\u670D\u52A1\u4E0E\u5DE5\u5177\u8BF4\u660E\uFF0C\u518D\u7528 workspace_mcp_call \u8C03\u7528\u3002\n3. \u8DE8\u5BBF\u4E3B\u5386\u53F2\u67E5\u8BE2\uFF08history_search / history_read\uFF09\uFF1A\u53EA\u8BFB\u68C0\u7D22\u5F53\u524D\u5DE5\u4F5C\u533A\u5728 Pi\u3001dsh\u3001Claude Code\u3001Antigravity \u7B49\u5BBF\u4E3B\u4E2D\u8BB0\u5F55\u7684\u5386\u53F2\u95EE\u7B54\u4E0E\u6458\u8981\u5F52\u6863\u3002";
2258
3563
  function defaultWorkerDirectory() {
2259
3564
  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`);
3565
+ if (process.env.PLUGIN_DATA) return join13(process.env.PLUGIN_DATA, "subagents");
3566
+ return join13(homedir(), ".pbot/subagents");
2270
3567
  }
2271
3568
  function asString(args, key, required = false) {
2272
3569
  const value = args[key];
@@ -2291,8 +3588,7 @@ function asContent(args, key) {
2291
3588
  if (value === void 0 || value === null) return void 0;
2292
3589
  requireThat(object(value), `\u53C2\u6570 ${key} \u5FC5\u987B\u662F JSON \u5BF9\u8C61\u3002`);
2293
3590
  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`);
3591
+ requireThat(isAcpElicitationValue(entry), `\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
3592
  }
2297
3593
  return value;
2298
3594
  }
@@ -2330,11 +3626,39 @@ var McpWorkerRuntime = class {
2330
3626
  #sessionId;
2331
3627
  #directory;
2332
3628
  #defaultBackend;
2333
- #closed = false;
2334
- constructor(directory = defaultWorkerDirectory(), sessionId = process.env.PBOT_MCP_SESSION_ID || "mcp-" + randomUUID4(), defaultBackend = process.env.PBOT_HOST || void 0) {
3629
+ #nativeWorkspaceMcp;
3630
+ #nativeHistory;
3631
+ #closing;
3632
+ constructor(directory = defaultWorkerDirectory(), sessionId = process.env.PBOT_MCP_SESSION_ID || "mcp-" + randomUUID4(), defaultBackend = process.env.PBOT_HOST || void 0, nativeWorkspaceMcp = /^(1|true)$/i.test(process.env.PBOT_NATIVE_WORKSPACE_MCP ?? ""), nativeHistory = /^(1|true)$/i.test(process.env.PBOT_NATIVE_HISTORY ?? "")) {
2335
3633
  this.#directory = directory;
2336
3634
  this.#sessionId = sessionId;
2337
3635
  this.#defaultBackend = defaultBackend?.trim() || void 0;
3636
+ this.#nativeWorkspaceMcp = nativeWorkspaceMcp;
3637
+ this.#nativeHistory = nativeHistory;
3638
+ }
3639
+ /** Mount the stdio sibling with the same worker ownership as the native host command. */
3640
+ nativeServer(root) {
3641
+ const entry = join13(resourceRoot, "../lib/extension/mcp.js");
3642
+ if (!existsSync3(entry)) return void 0;
3643
+ requireThat(this.#defaultBackend, "\u539F\u751F MCP \u6302\u8F7D\u9700\u8981\u5BBF\u4E3B\u540D\u79F0\u3002");
3644
+ return {
3645
+ command: process.execPath,
3646
+ args: [entry],
3647
+ env: {
3648
+ PBOT_HOST: this.#defaultBackend,
3649
+ PBOT_WORKSPACE_ROOT: root,
3650
+ PBOT_MCP_AGENT_DIR: this.#directory,
3651
+ PBOT_MCP_SESSION_ID: this.#sessionId,
3652
+ PBOT_NATIVE_WORKSPACE_MCP: "1",
3653
+ PBOT_NATIVE_HISTORY: "1"
3654
+ }
3655
+ };
3656
+ }
3657
+ get nativeWorkspaceMcp() {
3658
+ return this.#nativeWorkspaceMcp;
3659
+ }
3660
+ get nativeHistory() {
3661
+ return this.#nativeHistory;
2338
3662
  }
2339
3663
  resolveBackend(rawArgs, commands, allowDefault) {
2340
3664
  const raw = asString(rawArgs, "backend") ?? (allowDefault ? this.#defaultBackend : void 0);
@@ -2344,20 +3668,16 @@ var McpWorkerRuntime = class {
2344
3668
  return backend;
2345
3669
  }
2346
3670
  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");
3671
+ const target = supplied || pluginMcpWorkspaceRoot() || process.cwd();
3672
+ requireThat(isAbsolute5(target), "\u5DE5\u4F5C\u533A\u9700\u8981\u7EDD\u5BF9\u8DEF\u5F84\u3002");
3673
+ const root = await realpath3(target);
3674
+ requireThat((await stat3(root)).isDirectory(), "\u5DE5\u4F5C\u533A\u8DEF\u5F84\u4E0D\u662F\u76EE\u5F55\u3002");
2351
3675
  return root;
2352
3676
  }
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));
3677
+ workerService(root, commands = {}) {
2358
3678
  let entry = this.#services.get(root);
2359
3679
  if (!entry) {
2360
- const host = new AcpWorkerHost(this.#directory, configuration.acp);
3680
+ const host = new AcpWorkerHost(this.#directory, commands);
2361
3681
  entry = {
2362
3682
  host,
2363
3683
  service: new AgentService(root, this.#directory, host),
@@ -2365,27 +3685,31 @@ var McpWorkerRuntime = class {
2365
3685
  };
2366
3686
  this.#services.set(root, entry);
2367
3687
  } else {
2368
- Object.assign(entry.host, { commands: configuration.acp ?? {} });
3688
+ entry.host.commands = commands;
2369
3689
  }
2370
- return { root, configuration, ...entry };
3690
+ return entry;
2371
3691
  }
2372
3692
  async toolDefinitions() {
2373
3693
  let commands;
2374
- let includeWorkspaceMcp = true;
3694
+ let includeWorkspaceMcp = !this.#nativeWorkspaceMcp;
3695
+ let includeHistory = !this.#nativeHistory;
2375
3696
  try {
2376
3697
  const root = await this.resolveWorkspace();
2377
3698
  const configuration = await readWorkspaceConfig(root);
2378
3699
  if (configuration.enabled) {
2379
3700
  commands = configuration.acp;
2380
- includeWorkspaceMcp = workspaceFeatures(configuration).mcp;
3701
+ const features = workspaceFeatures(configuration);
3702
+ includeWorkspaceMcp = !this.#nativeWorkspaceMcp && features.mcp;
3703
+ includeHistory = !this.#nativeHistory && features.history;
2381
3704
  }
2382
3705
  } catch {
2383
3706
  }
2384
3707
  const defaultBackend = this.#defaultBackend ? canonicalAcpBackend(this.#defaultBackend, commands) : void 0;
2385
- const workspaceBound = Boolean(process.env.CLAUDE_PROJECT_DIR || process.env.PBOT_WORKSPACE_ROOT);
3708
+ const workspaceBound = Boolean(pluginMcpWorkspaceRoot());
2386
3709
  return [
2387
3710
  ...buildPbotWorkerTools(commands, defaultBackend, workspaceBound),
2388
- ...includeWorkspaceMcp ? buildWorkspaceMcpTools(workspaceBound) : []
3711
+ ...includeWorkspaceMcp ? buildWorkspaceMcpTools(workspaceBound) : [],
3712
+ ...includeHistory ? buildHistoryMcpTools(workspaceBound) : []
2389
3713
  ];
2390
3714
  }
2391
3715
  /** Wait until ACP handshake and model/thinking configuration finish so invalid options fail synchronously on create/resume. */
@@ -2394,7 +3718,7 @@ var McpWorkerRuntime = class {
2394
3718
  let lastProgressAt = 0;
2395
3719
  let lastMarker = "";
2396
3720
  for (; ; ) {
2397
- requireThat(!this.#closed, "Personal Bot MCP \u670D\u52A1\u5DF2\u5173\u95ED\u3002");
3721
+ requireThat(!this.#closing, "Personal Bot MCP \u670D\u52A1\u5DF2\u5173\u95ED\u3002");
2398
3722
  const current = service.status(workerId, owner);
2399
3723
  if (current.state === "error" || current.state === "stopped") {
2400
3724
  throw new Error(current.error || "worker \u542F\u52A8\u5931\u8D25\u3002");
@@ -2418,19 +3742,13 @@ var McpWorkerRuntime = class {
2418
3742
  let lastProgressAt = 0;
2419
3743
  let lastMarker = "";
2420
3744
  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) };
3745
+ requireThat(!this.#closing, "Personal Bot MCP \u670D\u52A1\u5DF2\u5173\u95ED\u3002");
3746
+ const { current, cycle: cycle2, terminal } = service.outputStatus(workerId, owner, requestId);
3747
+ if (cycle2 && cycle2.state !== "running") {
3748
+ const page2 = await service.read(workerId, owner, cycle2.cycleId, offset, reportPageSize);
3749
+ return { settled: true, ...presentWorker(page2) };
2432
3750
  }
2433
- if (terminalWithoutCycle || failedBeforeCycle) {
3751
+ if (terminal) {
2434
3752
  if (offset > 0) await service.read(workerId, owner, void 0, offset, reportPageSize);
2435
3753
  return { settled: true, ...presentWorker(current) };
2436
3754
  }
@@ -2456,25 +3774,63 @@ var McpWorkerRuntime = class {
2456
3774
  await delay3(100);
2457
3775
  }
2458
3776
  }
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"));
3777
+ async callTool(toolName, input, progress) {
3778
+ const { name, args: rawArgs } = parseMcpToolCall(toolName, input);
3779
+ requireThat(!this.#closing, "Personal Bot MCP \u670D\u52A1\u5DF2\u5173\u95ED\u3002");
3780
+ const root = await this.resolveWorkspace(asString(rawArgs, "workspace"));
3781
+ const configuration = await readWorkspaceConfig(root);
3782
+ requireThat(!this.#closing, "Personal Bot MCP \u670D\u52A1\u5DF2\u5173\u95ED\u3002");
3783
+ requireThat(configuration.enabled, workspaceDisabledMessage(configuration));
2464
3784
  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
- }
3785
+ case "workspace_mcp_discover":
2470
3786
  case "workspace_mcp_call": {
3787
+ requireThat(!this.#nativeWorkspaceMcp, "\u5F53\u524D\u5BBF\u4E3B\u5DF2\u539F\u751F\u6302\u8F7D\u5DE5\u4F5C\u533A .pbot/mcp.json \u670D\u52A1\uFF0C\u8BF7\u76F4\u63A5\u8C03\u7528\u5BF9\u5E94\u539F\u751F MCP \u5DE5\u5177\uFF0C\u52FF\u91CD\u590D\u7ECF\u7531 workspace_mcp_* \u6865\u63A5\u3002");
2471
3788
  requireThat(workspaceFeatures(configuration).mcp, `\u5DE5\u4F5C\u533A\u7EDF\u4E00 MCP \u529F\u80FD\u5DF2\u5728 ${configuration.path} \u4E2D\u505C\u7528\uFF08features.mcp: false\uFF09\u3002`);
3789
+ if (name === "workspace_mcp_discover") return this.#bridge.discover(root, asString(rawArgs, "server"));
2472
3790
  const server = asString(rawArgs, "server", true);
2473
3791
  const tool = asString(rawArgs, "tool", true);
2474
3792
  const toolArgs = rawArgs.arguments === void 0 ? {} : rawArgs.arguments;
2475
3793
  requireThat(object(toolArgs), "\u53C2\u6570 arguments \u5FC5\u987B\u662F JSON \u5BF9\u8C61\u3002");
2476
3794
  return this.#bridge.call(root, server, tool, toolArgs);
2477
3795
  }
3796
+ case "history_search": {
3797
+ requireThat(!this.#nativeHistory, "\u5F53\u524D\u5BBF\u4E3B\u5DF2\u63D0\u4F9B\u539F\u751F pbot_history \u5DE5\u5177\uFF0C\u8BF7\u76F4\u63A5\u8C03\u7528 pbot_history\u3002");
3798
+ requireThat(workspaceFeatures(configuration).history, `\u5DE5\u4F5C\u533A\u5386\u53F2\u529F\u80FD\u5DF2\u5728 ${configuration.path} \u4E2D\u505C\u7528\uFF08features.history: false\uFF09\u3002`);
3799
+ const hostFilter = asString(rawArgs, "host");
3800
+ if (hostFilter !== void 0) requireThat(isHistoryIdentifier(hostFilter), "\u65E0\u6548\u7684 host \u6765\u6E90\uFF1A" + hostFilter);
3801
+ const dimension = asString(rawArgs, "dimension");
3802
+ if (dimension !== void 0) requireThat(isHistoryIdentifier(dimension), "\u65E0\u6548\u7684 dimension\uFF1A" + dimension);
3803
+ const query = asString(rawArgs, "query");
3804
+ const sessionId = asString(rawArgs, "sessionId");
3805
+ const from = asString(rawArgs, "from");
3806
+ const to = asString(rawArgs, "to");
3807
+ const offset = asInt(rawArgs, "offset", 0, 1e7) ?? 0;
3808
+ const limit = asInt(rawArgs, "limit", 1, historyPageLimits.search.max) ?? historyPageLimits.search.default;
3809
+ return searchWorkspaceHistory(root, {
3810
+ ...hostFilter ? { host: hostFilter } : {},
3811
+ ...dimension ? { dimension } : {},
3812
+ ...query ? { query } : {},
3813
+ ...sessionId ? { sessionId } : {},
3814
+ ...from ? { from } : {},
3815
+ ...to ? { to } : {},
3816
+ offset,
3817
+ limit
3818
+ });
3819
+ }
3820
+ case "history_read": {
3821
+ requireThat(!this.#nativeHistory, "\u5F53\u524D\u5BBF\u4E3B\u5DF2\u63D0\u4F9B\u539F\u751F pbot_history \u5DE5\u5177\uFF0C\u8BF7\u76F4\u63A5\u8C03\u7528 pbot_history\u3002");
3822
+ requireThat(workspaceFeatures(configuration).history, `\u5DE5\u4F5C\u533A\u5386\u53F2\u529F\u80FD\u5DF2\u5728 ${configuration.path} \u4E2D\u505C\u7528\uFF08features.history: false\uFF09\u3002`);
3823
+ const id = asString(rawArgs, "id", true);
3824
+ const hostFilter = asString(rawArgs, "host");
3825
+ if (hostFilter !== void 0) requireThat(isHistoryIdentifier(hostFilter), "\u65E0\u6548\u7684 host \u6765\u6E90\uFF1A" + hostFilter);
3826
+ const offset = asInt(rawArgs, "offset", 0, 1e7) ?? 0;
3827
+ const limit = asInt(rawArgs, "limit", 1, historyPageLimits.read.max) ?? historyPageLimits.read.default;
3828
+ const childrenOffset = asInt(rawArgs, "childrenOffset", 0, 1e7) ?? 0;
3829
+ return { node: readWorkspaceHistory(root, id, offset, limit, childrenOffset, hostFilter) };
3830
+ }
3831
+ }
3832
+ const { host, service, owner } = this.workerService(root, configuration.acp);
3833
+ switch (name) {
2478
3834
  case "worker_create": {
2479
3835
  const backend = this.resolveBackend(rawArgs, configuration.acp, false);
2480
3836
  const model = asString(rawArgs, "model");
@@ -2519,12 +3875,11 @@ var McpWorkerRuntime = class {
2519
3875
  }
2520
3876
  case "worker_response": {
2521
3877
  const workerId = asString(rawArgs, "workerId", true);
2522
- const rawAction = asString(rawArgs, "action", true);
3878
+ const action = asString(rawArgs, "action", true);
2523
3879
  requireThat(
2524
- responseActions.includes(rawAction),
2525
- `\u53C2\u6570 action \u65E0\u6548\uFF1A${rawAction}\uFF08\u53EF\u7528\uFF1A${responseActions.join(", ")}\uFF09\u3002`
3880
+ isOneOf(action, acpElicitationActions),
3881
+ `\u53C2\u6570 action \u65E0\u6548\uFF1A${action}\uFF08\u53EF\u7528\uFF1A${acpElicitationActions.join(", ")}\uFF09\u3002`
2526
3882
  );
2527
- const action = rawAction;
2528
3883
  const requestId = asString(rawArgs, "requestId");
2529
3884
  const optionId = asString(rawArgs, "optionId");
2530
3885
  const content = asContent(rawArgs, "content");
@@ -2547,7 +3902,7 @@ var McpWorkerRuntime = class {
2547
3902
  case "worker_discover": {
2548
3903
  const rawTarget = asString(rawArgs, "target") ?? "overview";
2549
3904
  requireThat(
2550
- discoverTargets.includes(rawTarget),
3905
+ isOneOf(rawTarget, discoverTargets),
2551
3906
  `\u53C2\u6570 target \u65E0\u6548\uFF1A${rawTarget}\uFF08\u53EF\u7528\uFF1A${discoverTargets.join(", ")}\uFF09\u3002`
2552
3907
  );
2553
3908
  const target = rawTarget;
@@ -2583,16 +3938,18 @@ var McpWorkerRuntime = class {
2583
3938
  };
2584
3939
  }
2585
3940
  }
3941
+ throw new Error(`\u672A\u77E5\u5DE5\u5177\uFF1A${name}`);
2586
3942
  }
2587
- async close(preserve = false) {
2588
- if (this.#closed) return;
2589
- this.#closed = true;
3943
+ close(preserve = false) {
3944
+ if (this.#closing) return this.#closing;
2590
3945
  const entries = [...this.#services.values()];
2591
3946
  this.#services.clear();
2592
- await Promise.allSettled([
3947
+ this.#closing = Promise.allSettled([
2593
3948
  this.#bridge.close(),
2594
3949
  ...entries.map(({ service, owner }) => service.close(owner, preserve))
2595
- ]);
3950
+ ]).then(() => {
3951
+ });
3952
+ return this.#closing;
2596
3953
  }
2597
3954
  };
2598
3955
  async function handleMcpRequest(runtime, message2, notify) {
@@ -2612,7 +3969,7 @@ async function handleMcpRequest(runtime, message2, notify) {
2612
3969
  protocolVersion: requested || protocolVersion2,
2613
3970
  capabilities: { tools: {} },
2614
3971
  serverInfo: { name: "personal-bot", version: packageVersion },
2615
- instructions: mcpInstructions
3972
+ instructions: runtime.nativeWorkspaceMcp ? mcpWorkerOnlyInstructions : mcpInstructions
2616
3973
  }
2617
3974
  };
2618
3975
  }
@@ -2704,7 +4061,7 @@ async function serveMcpStdio(runtime = new McpWorkerRuntime()) {
2704
4061
  function main() {
2705
4062
  return serveMcpStdio();
2706
4063
  }
2707
- if (process.argv[1] && import.meta.url === pathToFileURL2(realpathSync4(process.argv[1])).href) {
4064
+ if (process.argv[1] && import.meta.url === pathToFileURL2(realpathSync5(process.argv[1])).href) {
2708
4065
  void main().catch((error) => {
2709
4066
  process.stderr.write("Personal Bot MCP: " + (error instanceof Error ? error.message : String(error)) + "\n");
2710
4067
  process.exitCode = 1;