personal-bot 0.2.20 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (343) hide show
  1. package/.claude-plugin/marketplace.json +3 -3
  2. package/.claude-plugin/plugin.json +2 -5
  3. package/.mcp.json +11 -0
  4. package/CONTEXT.md +17 -73
  5. package/README.md +41 -120
  6. package/README.zh-CN.md +41 -120
  7. package/docs/README.md +31 -23
  8. package/docs/architecture/design.md +74 -0
  9. package/docs/architecture/extensibility.md +78 -0
  10. package/docs/architecture/model-context.md +31 -0
  11. package/docs/architecture/model-instruction-guidelines.md +34 -0
  12. package/docs/architecture/principles.md +33 -0
  13. package/docs/guides/capabilities.md +36 -0
  14. package/docs/guides/cross-harness-workers.md +83 -0
  15. package/docs/guides/history.md +25 -0
  16. package/docs/guides/workspace-configuration.md +102 -0
  17. package/docs/hosts/antigravity.md +52 -0
  18. package/docs/hosts/claude-code.md +47 -0
  19. package/docs/hosts/dsh.md +67 -0
  20. package/docs/hosts/pi.md +49 -0
  21. package/docs/maintainers/release.md +59 -0
  22. package/hooks/hooks.json +0 -3
  23. package/lib/antigravity-plugin/hooks.json +23 -0
  24. package/lib/antigravity-plugin/lib/claude.d.ts +1 -0
  25. package/lib/antigravity-plugin/lib/claude.js +13 -0
  26. package/lib/antigravity-plugin/lib/common/json.d.ts +6 -0
  27. package/lib/antigravity-plugin/lib/common/json.js +16 -0
  28. package/lib/antigravity-plugin/lib/common/paths.d.ts +1 -0
  29. package/lib/antigravity-plugin/lib/common/paths.js +2 -0
  30. package/lib/antigravity-plugin/lib/common/validation.d.ts +3 -0
  31. package/lib/antigravity-plugin/lib/common/validation.js +8 -0
  32. package/lib/antigravity-plugin/lib/common/version.d.ts +3 -0
  33. package/lib/antigravity-plugin/lib/common/version.js +13 -0
  34. package/lib/antigravity-plugin/lib/extension/acp-worker.js +11597 -0
  35. package/lib/antigravity-plugin/lib/extension/mcp.js +2715 -0
  36. package/lib/antigravity-plugin/lib/extension/plugin-runtime.d.ts +10 -0
  37. package/lib/antigravity-plugin/lib/extension/plugin-runtime.js +67 -0
  38. package/lib/antigravity-plugin/lib/integrations/agent-resources.d.ts +16 -0
  39. package/lib/antigravity-plugin/lib/integrations/agent-resources.js +56 -0
  40. package/lib/antigravity-plugin/lib/integrations/hosts/antigravity.d.ts +4 -0
  41. package/lib/antigravity-plugin/lib/integrations/hosts/antigravity.js +79 -0
  42. package/lib/antigravity-plugin/lib/integrations/hosts/claude.d.ts +3 -0
  43. package/lib/antigravity-plugin/lib/integrations/hosts/claude.js +60 -0
  44. package/lib/antigravity-plugin/lib/integrations/hosts/registry.d.ts +15 -0
  45. package/lib/antigravity-plugin/lib/integrations/hosts/registry.js +34 -0
  46. package/lib/antigravity-plugin/lib/model/acp.d.ts +164 -0
  47. package/lib/antigravity-plugin/lib/model/acp.js +12 -0
  48. package/lib/antigravity-plugin/lib/model/plugin-host.d.ts +48 -0
  49. package/lib/antigravity-plugin/lib/model/workspace-config.d.ts +24 -0
  50. package/lib/antigravity-plugin/lib/model/workspace-config.js +1 -0
  51. package/lib/antigravity-plugin/lib/model/workspace-mcp.d.ts +51 -0
  52. package/lib/antigravity-plugin/lib/model/workspace-mcp.js +4 -0
  53. package/lib/antigravity-plugin/lib/plugin.d.ts +1 -0
  54. package/lib/antigravity-plugin/lib/plugin.js +17 -0
  55. package/lib/antigravity-plugin/lib/services/workspace/workspace-config.d.ts +8 -0
  56. package/lib/antigravity-plugin/lib/services/workspace/workspace-config.js +95 -0
  57. package/lib/antigravity-plugin/lib/services/workspace/workspace-preparation.d.ts +3 -0
  58. package/lib/antigravity-plugin/lib/services/workspace/workspace-preparation.js +26 -0
  59. package/lib/antigravity-plugin/lib/services/workspace/workspace-skills.d.ts +8 -0
  60. package/lib/antigravity-plugin/lib/services/workspace/workspace-skills.js +91 -0
  61. package/lib/antigravity-plugin/lib/storage/atomic-json.d.ts +11 -0
  62. package/lib/antigravity-plugin/lib/storage/atomic-json.js +101 -0
  63. package/lib/antigravity-plugin/mcp_config.json +13 -0
  64. package/lib/antigravity-plugin/package.json +6 -0
  65. package/lib/antigravity-plugin/plugin.json +7 -0
  66. package/lib/antigravity-plugin/resources/agents/coordinator.md +11 -0
  67. package/{resources/claude → lib/antigravity-plugin/resources}/agents/general-purpose.md +0 -5
  68. package/lib/antigravity-plugin/resources/prompts/plugin-coordinator.md +1 -0
  69. package/lib/antigravity-plugin/resources/prompts/workspace.md +31 -0
  70. package/lib/antigravity-plugin/resources/references/compute-finance.md +22 -0
  71. package/lib/antigravity-plugin/resources/references/compute.md +16 -0
  72. package/lib/antigravity-plugin/resources/references/task-conductor.md +25 -0
  73. package/lib/antigravity-plugin/resources/templates/workspace-agents.md +21 -0
  74. package/lib/antigravity-plugin/skills/pbot/SKILL.md +16 -0
  75. package/lib/antigravity-plugin/skills/project-maintenance/SKILL.md +35 -0
  76. package/lib/antigravity-plugin/skills/provider-connections/SKILL.md +42 -0
  77. package/lib/claude.js +4 -11
  78. package/lib/client.js +14 -531
  79. package/lib/common/markdown.js +2 -3
  80. package/lib/common/validation.d.ts +2 -0
  81. package/lib/common/validation.js +4 -0
  82. package/lib/extension/acp-member.d.ts +2 -0
  83. package/lib/extension/acp-member.js +9 -8
  84. package/lib/extension/acp-worker.js +11578 -121
  85. package/lib/extension/dsh/acp-member.js +26 -2
  86. package/lib/extension/dsh/command.js +19 -57
  87. package/lib/extension/dsh/history.js +2 -4
  88. package/lib/extension/dsh/management.d.ts +0 -2
  89. package/lib/extension/dsh/management.js +27 -126
  90. package/lib/extension/dsh/workspace.d.ts +5 -47
  91. package/lib/extension/dsh/workspace.js +76 -108
  92. package/lib/extension/mcp-bridge.d.ts +41 -0
  93. package/lib/extension/mcp-bridge.js +412 -0
  94. package/lib/extension/mcp-workers.d.ts +980 -0
  95. package/lib/extension/mcp-workers.js +882 -0
  96. package/lib/extension/mcp.js +2715 -0
  97. package/lib/extension/plugin-runtime.d.ts +10 -0
  98. package/lib/extension/plugin-runtime.js +67 -0
  99. package/lib/extension/setup-cli.js +215 -2
  100. package/lib/integrations/acp/agents.d.ts +10 -11
  101. package/lib/integrations/acp/agents.js +65 -33
  102. package/lib/integrations/acp/claude.d.ts +2 -2
  103. package/lib/integrations/acp/claude.js +5 -3
  104. package/lib/integrations/acp/connection.d.ts +17 -4
  105. package/lib/integrations/acp/connection.js +53 -27
  106. package/lib/integrations/acp/executable.d.ts +3 -0
  107. package/lib/integrations/acp/executable.js +42 -0
  108. package/lib/integrations/acp/harnesses/claude.d.ts +2 -0
  109. package/lib/integrations/acp/harnesses/claude.js +49 -0
  110. package/lib/integrations/acp/harnesses/dsh.d.ts +2 -0
  111. package/lib/integrations/acp/harnesses/dsh.js +35 -0
  112. package/lib/integrations/acp/harnesses/generic.d.ts +13 -0
  113. package/lib/integrations/acp/harnesses/generic.js +37 -0
  114. package/lib/integrations/acp/harnesses/pi.d.ts +2 -0
  115. package/lib/integrations/acp/harnesses/pi.js +34 -0
  116. package/lib/integrations/acp/harnesses/presets.d.ts +3 -0
  117. package/lib/integrations/acp/harnesses/presets.js +20 -0
  118. package/lib/integrations/acp/launch.d.ts +33 -4
  119. package/lib/integrations/acp/launch.js +60 -48
  120. package/lib/integrations/acp/mcp.d.ts +6 -0
  121. package/lib/integrations/acp/mcp.js +40 -0
  122. package/lib/integrations/acp/model-selection.d.ts +9 -2
  123. package/lib/integrations/acp/model-selection.js +73 -27
  124. package/lib/integrations/acp/registry.d.ts +18 -0
  125. package/lib/integrations/acp/registry.js +50 -0
  126. package/lib/integrations/agent-resources.d.ts +16 -1
  127. package/lib/integrations/agent-resources.js +45 -9
  128. package/lib/integrations/dsh/mcp.d.ts +4 -0
  129. package/lib/integrations/dsh/mcp.js +28 -0
  130. package/lib/integrations/dsh/resources.d.ts +3 -3
  131. package/lib/integrations/dsh/resources.js +21 -12
  132. package/lib/integrations/dsh/skills.d.ts +5 -1
  133. package/lib/integrations/dsh/skills.js +10 -6
  134. package/lib/integrations/hosts/antigravity.d.ts +4 -0
  135. package/lib/integrations/hosts/antigravity.js +79 -0
  136. package/lib/integrations/hosts/claude.d.ts +3 -0
  137. package/lib/integrations/hosts/claude.js +60 -0
  138. package/lib/integrations/hosts/registry.d.ts +15 -0
  139. package/lib/integrations/hosts/registry.js +34 -0
  140. package/lib/model/acp.d.ts +107 -2
  141. package/lib/model/acp.js +12 -1
  142. package/lib/model/agent.d.ts +35 -33
  143. package/lib/model/plugin-host.d.ts +48 -0
  144. package/lib/model/plugin-host.js +1 -0
  145. package/lib/model/workspace-config.d.ts +12 -0
  146. package/lib/model/workspace-mcp.d.ts +51 -0
  147. package/lib/model/workspace-mcp.js +4 -0
  148. package/lib/plugin.d.ts +1 -0
  149. package/lib/plugin.js +17 -0
  150. package/lib/services/agents/acp-run.d.ts +13 -1
  151. package/lib/services/agents/acp-run.js +30 -2
  152. package/lib/services/agents/agent-service.d.ts +35 -120
  153. package/lib/services/agents/agent-service.js +156 -160
  154. package/lib/services/installation/setup-service.js +17 -1
  155. package/lib/services/workspace/workspace-config.d.ts +2 -1
  156. package/lib/services/workspace/workspace-config.js +43 -9
  157. package/lib/services/workspace/workspace-mcp.d.ts +14 -0
  158. package/lib/services/workspace/workspace-mcp.js +200 -0
  159. package/lib/services/workspace/workspace-skills.d.ts +8 -0
  160. package/lib/services/workspace/workspace-skills.js +91 -0
  161. package/lib/storage/acp-files.d.ts +3 -1
  162. package/lib/storage/acp-files.js +32 -2
  163. package/lib/storage/acp-history.d.ts +3 -2
  164. package/lib/storage/acp-history.js +19 -7
  165. package/lib/storage/agent-files.d.ts +8 -8
  166. package/lib/storage/agent-files.js +27 -47
  167. package/lib/tools/history/contract.d.ts +1 -1
  168. package/lib/tools/history/contract.js +17 -11
  169. package/lib/ui/dsh/index.js +8 -3
  170. package/lib/ui/dsh/management.d.ts +1 -1
  171. package/lib/ui/dsh/management.js +24 -456
  172. package/lib/ui/dsh/remote.d.ts +0 -2
  173. package/lib/ui/dsh/remote.js +1 -1
  174. package/package.json +12 -7
  175. package/resources/agents/coordinator.md +2 -2
  176. package/resources/antigravity/skills/pbot/SKILL.md +16 -0
  177. package/resources/claude/skills/pbot/SKILL.md +1 -1
  178. package/resources/prompts/history-coordinator.md +1 -0
  179. package/resources/prompts/plugin-coordinator.md +1 -0
  180. package/resources/prompts/workspace.md +9 -8
  181. package/resources/references/compute.md +9 -11
  182. package/resources/references/task-conductor.md +12 -26
  183. package/resources/skills/project-maintenance/SKILL.md +16 -21
  184. package/resources/skills/provider-connections/SKILL.md +24 -40
  185. package/resources/templates/workspace-agents.md +4 -0
  186. package/scripts/README.md +17 -34
  187. package/src/claude.ts +4 -8
  188. package/src/common/markdown.ts +2 -3
  189. package/src/common/validation.ts +6 -0
  190. package/src/extension/acp-member.ts +9 -8
  191. package/src/extension/acp-worker.ts +239 -97
  192. package/src/extension/command.ts +38 -36
  193. package/src/extension/dsh/acp-member.ts +21 -2
  194. package/src/extension/dsh/command.ts +21 -51
  195. package/src/extension/dsh/files.ts +1 -0
  196. package/src/extension/dsh/history.ts +9 -6
  197. package/src/extension/dsh/management.ts +27 -58
  198. package/src/extension/dsh/workspace.ts +88 -99
  199. package/src/extension/events.ts +13 -10
  200. package/src/extension/history.ts +2 -50
  201. package/src/extension/lifecycle.ts +37 -22
  202. package/src/extension/mcp-bridge.ts +412 -0
  203. package/src/extension/mcp-workers.ts +941 -0
  204. package/src/extension/pi-acp-member.ts +29 -5
  205. package/src/extension/plugin-runtime.ts +63 -0
  206. package/src/extension/setup-cli.ts +186 -2
  207. package/src/integrations/acp/agents.ts +70 -24
  208. package/src/integrations/acp/claude.ts +11 -4
  209. package/src/integrations/acp/connection.ts +63 -25
  210. package/src/integrations/acp/executable.ts +41 -0
  211. package/src/integrations/acp/harnesses/claude.ts +50 -0
  212. package/src/integrations/acp/harnesses/dsh.ts +40 -0
  213. package/src/integrations/acp/harnesses/generic.ts +52 -0
  214. package/src/integrations/acp/harnesses/pi.ts +35 -0
  215. package/src/integrations/acp/harnesses/presets.ts +22 -0
  216. package/src/integrations/acp/launch.ts +69 -47
  217. package/src/integrations/acp/mcp.ts +43 -0
  218. package/src/integrations/acp/model-selection.ts +68 -25
  219. package/src/integrations/acp/registry.ts +60 -0
  220. package/src/integrations/agent-resources.ts +70 -6
  221. package/src/integrations/dsh/mcp.ts +30 -0
  222. package/src/integrations/dsh/resources.ts +28 -13
  223. package/src/integrations/dsh/skills.ts +16 -6
  224. package/src/integrations/hosts/antigravity.ts +83 -0
  225. package/src/integrations/hosts/claude.ts +62 -0
  226. package/src/integrations/hosts/registry.ts +42 -0
  227. package/src/integrations/pi/mcp.ts +26 -0
  228. package/src/mcp.ts +14 -0
  229. package/src/model/acp.ts +113 -3
  230. package/src/model/agent.ts +18 -14
  231. package/src/model/plugin-host.ts +39 -0
  232. package/src/model/workspace-config.ts +14 -0
  233. package/src/model/workspace-mcp.ts +64 -0
  234. package/src/pbot.ts +69 -20
  235. package/src/plugin.ts +19 -0
  236. package/src/services/agents/acp-run.ts +35 -3
  237. package/src/services/agents/agent-service.ts +180 -160
  238. package/src/services/installation/setup-service.ts +17 -2
  239. package/src/services/workspace/workspace-config.ts +46 -8
  240. package/src/services/workspace/workspace-mcp.ts +242 -0
  241. package/src/services/workspace/workspace-skills.ts +78 -0
  242. package/src/storage/acp-files.ts +32 -3
  243. package/src/storage/acp-history.ts +18 -7
  244. package/src/storage/agent-files.ts +27 -41
  245. package/src/tools/history/contract.ts +17 -11
  246. package/src/tools/register.ts +4 -8
  247. package/src/ui/dsh/index.ts +8 -3
  248. package/src/ui/dsh/management.ts +40 -282
  249. package/src/ui/dsh/remote.ts +2 -2
  250. package/docs/adr/0001-claude-skill-discovery.md +0 -3
  251. package/docs/adr/0002-claude-native-collaboration.md +0 -3
  252. package/docs/agent-collaboration.md +0 -190
  253. package/docs/architecture-guidelines.md +0 -37
  254. package/docs/capability-design.md +0 -55
  255. package/docs/claude-code-design.md +0 -44
  256. package/docs/claude-code.md +0 -57
  257. package/docs/dsh.md +0 -337
  258. package/docs/file-storage.md +0 -97
  259. package/docs/history.md +0 -54
  260. package/docs/installation-design.md +0 -86
  261. package/docs/interaction-design.md +0 -21
  262. package/docs/model-context.md +0 -76
  263. package/docs/model-instruction-guidelines.md +0 -51
  264. package/docs/release.md +0 -108
  265. package/docs/technical-design.md +0 -163
  266. package/docs/workspace-configuration.md +0 -79
  267. package/lib/extension/claude-hooks.d.ts +0 -9
  268. package/lib/extension/claude-hooks.js +0 -78
  269. package/lib/extension/dsh/agent-events.d.ts +0 -24
  270. package/lib/extension/dsh/agent-events.js +0 -242
  271. package/lib/extension/dsh/agent-runtime.d.ts +0 -49
  272. package/lib/extension/dsh/agent-runtime.js +0 -351
  273. package/lib/integrations/dsh/dsh-agents.d.ts +0 -30
  274. package/lib/integrations/dsh/dsh-agents.js +0 -104
  275. package/lib/integrations/dsh/input.d.ts +0 -21
  276. package/lib/integrations/dsh/input.js +0 -62
  277. package/lib/integrations/dsh/notifications.d.ts +0 -8
  278. package/lib/integrations/dsh/notifications.js +0 -55
  279. package/lib/integrations/dsh/session.d.ts +0 -14
  280. package/lib/integrations/dsh/session.js +0 -60
  281. package/lib/integrations/team-context.d.ts +0 -18
  282. package/lib/integrations/team-context.js +0 -61
  283. package/lib/model/team.d.ts +0 -85
  284. package/lib/services/agents/agent-notices.d.ts +0 -13
  285. package/lib/services/agents/agent-notices.js +0 -25
  286. package/lib/services/agents/start-options.d.ts +0 -4
  287. package/lib/services/agents/start-options.js +0 -20
  288. package/lib/services/agents/team-service.d.ts +0 -168
  289. package/lib/services/agents/team-service.js +0 -345
  290. package/lib/storage/team-files.d.ts +0 -16
  291. package/lib/storage/team-files.js +0 -111
  292. package/lib/tools/agents/actions.d.ts +0 -62
  293. package/lib/tools/agents/actions.js +0 -62
  294. package/lib/tools/agents/contract.d.ts +0 -181
  295. package/lib/tools/agents/contract.js +0 -84
  296. package/lib/tools/agents/dsh-tool.d.ts +0 -5
  297. package/lib/tools/agents/dsh-tool.js +0 -34
  298. package/lib/tools/result.d.ts +0 -18
  299. package/lib/tools/result.js +0 -10
  300. package/lib/tools/teams/actions.d.ts +0 -23
  301. package/lib/tools/teams/actions.js +0 -40
  302. package/lib/tools/teams/contract.d.ts +0 -201
  303. package/lib/tools/teams/contract.js +0 -91
  304. package/lib/tools/teams/dsh-tool.d.ts +0 -8
  305. package/lib/tools/teams/dsh-tool.js +0 -39
  306. package/lib/ui/dsh/attachments.d.ts +0 -5
  307. package/lib/ui/dsh/attachments.js +0 -39
  308. package/resources/prompts/claude-coordinator.md +0 -1
  309. package/resources/prompts/native-coordinator.md +0 -1
  310. package/resources/prompts/team-member.md +0 -7
  311. package/src/extension/agent-events.ts +0 -210
  312. package/src/extension/agents-command.ts +0 -89
  313. package/src/extension/claude-hooks.ts +0 -74
  314. package/src/extension/dsh/agent-events.ts +0 -148
  315. package/src/extension/dsh/agent-runtime.ts +0 -252
  316. package/src/extension/subagent-entry.ts +0 -270
  317. package/src/extension/teams-command.ts +0 -67
  318. package/src/integrations/dsh/dsh-agents.ts +0 -97
  319. package/src/integrations/dsh/input.ts +0 -66
  320. package/src/integrations/dsh/notifications.ts +0 -46
  321. package/src/integrations/pi/agent-context.ts +0 -18
  322. package/src/integrations/pi/agent-input.ts +0 -19
  323. package/src/integrations/pi/pi-agents.ts +0 -84
  324. package/src/integrations/pi/team-context.ts +0 -26
  325. package/src/integrations/team-context.ts +0 -64
  326. package/src/model/team.ts +0 -29
  327. package/src/services/agents/agent-notices.ts +0 -28
  328. package/src/services/agents/start-options.ts +0 -19
  329. package/src/services/agents/team-service.ts +0 -275
  330. package/src/storage/team-files.ts +0 -93
  331. package/src/tools/agents/actions.ts +0 -57
  332. package/src/tools/agents/contract.ts +0 -101
  333. package/src/tools/agents/dsh-tool.ts +0 -37
  334. package/src/tools/agents/tool.ts +0 -20
  335. package/src/tools/teams/actions.ts +0 -34
  336. package/src/tools/teams/contract.ts +0 -109
  337. package/src/tools/teams/dsh-tool.ts +0 -45
  338. package/src/tools/teams/tool.ts +0 -29
  339. package/src/ui/agent-display.ts +0 -14
  340. package/src/ui/dsh/attachments.ts +0 -42
  341. package/src/ui/pi/menu.ts +0 -37
  342. package/src/ui/pi/reader.ts +0 -46
  343. /package/lib/{model/team.js → antigravity-plugin/lib/model/plugin-host.js} +0 -0
@@ -1,89 +0,0 @@
1
- import { spawn } from "node:child_process";
2
- import type { ExtensionAPI, ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
3
- import { Text, type TUI } from "@earendil-works/pi-tui";
4
- import type { WorkspaceInstance } from "./lifecycle.js";
5
- import { agentOwner } from "../integrations/pi/agent-context.js";
6
- import { tmuxName } from "../integrations/pi/pi-agents.js";
7
- import { agentSummary } from "../ui/agent-display.js";
8
- import { readPage } from "../ui/pi/reader.js";
9
- import { choose } from "../ui/pi/menu.js";
10
- import { stateLabel } from "../ui/presentation.js";
11
- import type { Confirmations } from "../ui/confirmation.js";
12
-
13
- export async function showAgents(_pi: ExtensionAPI, instance: WorkspaceInstance, ctx: ExtensionCommandContext, confirmations: Confirmations, agentIds?: string[]) {
14
- instance.check();
15
- const owner = () => agentOwner(ctx), views = () => instance.agents.list(owner()).filter(v => !agentIds || agentIds.includes(v.agentId));
16
- if (ctx.mode !== "tui") { ctx.ui.notify(JSON.stringify(views()), "info"); return; }
17
- if (confirmations.presenting) { ctx.ui.notify("请先处理待确认操作。", "info"); return; }
18
- for (;;) {
19
- instance.check(); const values = views();
20
- if (!values.length) { ctx.ui.notify("还没有专家。告诉主助手需要什么专家即可创建。", "info"); return; }
21
- const options = values.map(v => agentSummary(v) + (v.owned ? "" : " · 其他分支"));
22
- const selected = await choose(ctx, "专家", options), picked = values[options.indexOf(selected ?? "")]; if (!picked) return;
23
- if (!picked.owned) { ctx.ui.notify("请返回所属分支操作。", "info"); continue; }
24
- for (;;) {
25
- instance.check(); const value = instance.agents.status(picked.agentId, owner()), inTmux = Boolean(process.env.TMUX);
26
- const enterTui = value.transport === "acp" ? "查看任务与报告" : value.alive ? "进入会话" : "打开原会话(待命)";
27
- const action = await choose(ctx, `${value.name} · ${stateLabel(value.state)}`, [enterTui, "详情", ...(value.alive ? ["补充要求"] : value.transport === "acp" ? ["携新要求恢复"] : []), "重命名", ...(value.alive ? ["停止"] : [])]);
28
- if (!action) break;
29
- instance.check();
30
- try {
31
- if (action === "详情") {
32
- const selected = value.selection ?? value.options;
33
- const model = [selected.provider, selected.model].filter(Boolean).join("/") || "目标宿主配置", resolved = value.selection?.resolvedModel;
34
- await readPage(ctx, value.name, [`状态 ${stateLabel(value.state)}`, `活动 ${value.activity}`, `模型 ${model}${resolved && resolved !== model ? " → " + resolved : ""}`,
35
- `思考 ${selected.thinking ?? "宿主默认"}`, `目录 ${value.cwd}`, `ID ${value.agentId}`, ...(value.backend ? [`宿主 ${value.backend}`] : []), ...(value.error ? ["", value.error] : []),
36
- ...(value.transport === "acp" ? [] : ["", `返回主会话:Ctrl+B → ${inTmux ? "l" : "d"}`])].join("\n")); continue;
37
- }
38
- if (action === "停止") { instance.agents.stop(value.agentId, owner()); ctx.ui.notify("已请求停止。", "info"); continue; }
39
- if (action === "重命名") {
40
- const name = await ctx.ui.input("新名称", value.name); instance.check();
41
- if (name?.trim()) { instance.agents.rename(value.agentId, name.trim(), owner()); ctx.ui.notify("名称已更新。", "info"); } continue;
42
- }
43
- if (action === "补充要求") {
44
- const message = await ctx.ui.editor("补充要求"); instance.check();
45
- if (message?.trim()) { instance.agents.send(value.agentId, message, value.transport === "acp" ? "followUp" : "steer", owner()); ctx.ui.notify("要求已排队。", "info"); } continue;
46
- }
47
- if (action === "携新要求恢复") {
48
- const message = await ctx.ui.editor("新要求"); instance.check();
49
- if (message?.trim()) await instance.agents.resume(value.agentId, message, owner());
50
- continue;
51
- }
52
- if (action !== enterTui) continue;
53
- if (value.transport === "acp") {
54
- const data = await instance.agents.recordPage(value.agentId, owner(), { limit: 100 });
55
- const records = ("records" in data ? data.records : []) ?? [];
56
- await readPage(ctx, value.name, records.map(record => [record.type === "acp/input" ? "任务" : "报告",
57
- record.state, new Date(record.time).toLocaleString(), "", record.preview].join("\n")).join("\n\n") || "还没有任务。");
58
- const cycles = instance.agents.cycles(value.agentId, owner());
59
- if (cycles.length) {
60
- const titles = cycles.map(cycle => cycle.cycleId + " · " + cycle.state);
61
- const selected = await choose(ctx, "读取周期报告", titles), cycle = cycles[titles.indexOf(selected ?? "")];
62
- if (cycle) {
63
- const chunks: string[] = []; let offset = 0;
64
- for (;;) {
65
- const page = await instance.agents.read(value.agentId, owner(), cycle.cycleId, offset);
66
- chunks.push(page.report); if (page.nextOffset === null) break; offset = page.nextOffset;
67
- }
68
- await readPage(ctx, value.name, chunks.join(""));
69
- }
70
- }
71
- continue;
72
- }
73
- ctx.ui.notify(`返回主会话:Ctrl+B → ${inTmux ? "l" : "d"}`, "info");
74
- let tui: TUI | undefined;
75
- await ctx.ui.custom<void>((terminal, _theme, _keys, done) => { tui = terminal; queueMicrotask(() => done()); return new Text("", 0, 0); });
76
- if (!tui) return;
77
- instance.check(); await instance.agents.enter(value.agentId, owner()); const terminal = tui; terminal.stop();
78
- try {
79
- const code = await new Promise<number | null>(resolve => {
80
- const child = spawn("tmux", [inTmux ? "switch-client" : "attach-session", "-t", "=" + tmuxName(value.agentId)], { stdio: "inherit" });
81
- child.on("error", () => resolve(null)); child.on("close", resolve);
82
- });
83
- if (code !== 0) ctx.ui.notify("无法进入专家会话。", "error");
84
- } finally { terminal.start(); terminal.requestRender(true); }
85
- return;
86
- } catch (error) { ctx.ui.notify(error instanceof Error ? error.message : String(error), "error"); }
87
- }
88
- }
89
- }
@@ -1,74 +0,0 @@
1
- import { readFile, realpath, stat } from "node:fs/promises";
2
- import { isAbsolute, join } from "node:path";
3
- import { object } from "../common/json.js";
4
- import { resourceRoot } from "../common/paths.js";
5
- import { packageVersion } from "../common/version.js";
6
- import { requireThat } from "../common/validation.js";
7
- import { agentText } from "../integrations/agent-resources.js";
8
- import { readWorkspaceConfig } from "../services/workspace/workspace-config.js";
9
- import { initializeWorkspace } from "../services/workspace/workspace-preparation.js";
10
-
11
- export async function claudeWorkspaceRoot(cwd: string, projectDirectory = process.env.CLAUDE_PROJECT_DIR): Promise<string> {
12
- const directory = projectDirectory || cwd;
13
- requireThat(isAbsolute(directory), "Claude 工作区需要绝对路径。");
14
- const root = await realpath(directory);
15
- requireThat((await stat(root)).isDirectory(), "Claude 工作区需要目录。");
16
- return root;
17
- }
18
-
19
- function disabled(configuration: Awaited<ReturnType<typeof readWorkspaceConfig>>) {
20
- return configuration.error ?? "Personal Bot 未在此工作区启用。运行 /personal-bot:pbot init;配置文件:" + configuration.path;
21
- }
22
-
23
- export async function claudeCommand(args: readonly string[], cwd: string) {
24
- const root = await claudeWorkspaceRoot(cwd);
25
- const action = args.join(" ");
26
- requireThat(["init", "status"].includes(action), "用法:node <插件目录>/lib/claude.js init|status");
27
- if (action === "init") await initializeWorkspace(root);
28
- const configuration = await readWorkspaceConfig(root);
29
- return { version: packageVersion, workspaceRoot: root, resourceRoot, configuration };
30
- }
31
-
32
- /** Standard command hooks consume documented stdin fields; native sessions remain entirely host-owned. */
33
- export async function claudeHook(value: unknown): Promise<Record<string, unknown>> {
34
- requireThat(object(value) && typeof value.hook_event_name === "string", "Claude hook 输入无效。");
35
- if (process.env.PBOT_SUBAGENT_RUN_ID) return {};
36
- const event = value.hook_event_name;
37
- requireThat(["UserPromptSubmit", "SubagentStart", "PreToolUse", "UserPromptExpansion"].includes(event), "Claude hook 事件未支持。");
38
- const skillCheck = event === "PreToolUse" || event === "UserPromptExpansion";
39
- if (skillCheck) {
40
- const skill = event === "UserPromptExpansion"
41
- ? value.expansion_type === "slash_command" ? value.command_name : undefined
42
- : value.tool_name === "Skill" && object(value.tool_input) ? value.tool_input.skill : undefined;
43
- if (typeof skill !== "string" || !skill.startsWith("personal-bot:") || skill === "personal-bot:pbot") return {};
44
- }
45
- requireThat(typeof value.cwd === "string", "Claude hook 缺少工作目录。");
46
- const root = await claudeWorkspaceRoot(value.cwd);
47
- const configuration = await readWorkspaceConfig(root);
48
- if (skillCheck) {
49
- if (configuration.enabled) return {};
50
- return event === "UserPromptExpansion" ? { decision: "block", reason: disabled(configuration) } : { hookSpecificOutput: {
51
- hookEventName: event, permissionDecision: "deny", permissionDecisionReason: disabled(configuration),
52
- } };
53
- }
54
- if (!configuration.enabled) return event === "SubagentStart" ? {} : {
55
- hookSpecificOutput: { hookEventName: event, additionalContext: disabled(configuration) },
56
- };
57
- if (event === "SubagentStart" && value.agent_type !== "personal-bot:general-purpose") return {};
58
- const member = event === "SubagentStart" || typeof value.agent_id === "string";
59
- const role = event === "SubagentStart" ? readFile(join(root, "agents/general-purpose.md"), "utf8").catch(error => {
60
- if ((error as NodeJS.ErrnoException).code === "ENOENT") return "";
61
- throw error;
62
- }) : agentText(member ? "general-purpose" : "coordinator", root, "claude");
63
- const [workspace, duties, agents] = await Promise.all([
64
- readFile(join(resourceRoot, "prompts/workspace.md"), "utf8"),
65
- role,
66
- readFile(join(root, "AGENTS.md"), "utf8").catch(error => {
67
- if ((error as NodeJS.ErrnoException).code === "ENOENT") return "";
68
- throw error;
69
- }),
70
- ]);
71
- return { hookSpecificOutput: { hookEventName: event, additionalContext: [
72
- workspace, duties, agents, JSON.stringify({ workspaceRoot: root, resourceRoot }),
73
- ].filter(Boolean).join("\n\n") } };
74
- }
@@ -1,148 +0,0 @@
1
- import { randomUUID } from "node:crypto";
2
- import type { Context } from "@deepseek-ai/cordis";
3
- import { createUserMessage, type UserMessage } from "@deepseek-ai/dsh-llm";
4
- import { agentNotice, teamNotice } from "../../services/agents/agent-notices.js";
5
- import { deliveredDshNotices, pendingDshNotices } from "../../integrations/dsh/notifications.js";
6
- import { flushDshAgent } from "../../integrations/dsh/session.js";
7
- import type { Agent } from "@deepseek-ai/dsh-agent";
8
- import type { AgentService } from "../../services/agents/agent-service.js";
9
- import type { TeamService } from "../../services/agents/team-service.js";
10
- import type { AgentOwner, AgentCompletion } from "../../model/agent.js";
11
- import type { TeamInput } from "../../model/team.js";
12
-
13
- /** Server-owned scheduling survives browser disconnects; native cancellation pauses dispatch. */
14
- export class DshAgentEvents {
15
- readonly #dispatching = new Map<string, TeamInput>();
16
- readonly #signals = new Map<AbortSignal, () => void>();
17
- #timer: ReturnType<typeof setInterval> | undefined;
18
- #scan: Promise<void> | undefined;
19
- #closed = false;
20
- #pausePending = false;
21
- #paused = false;
22
- #error: string | undefined;
23
- #errorKey: string | undefined;
24
- #busySince: number | undefined;
25
- #recovery: "retry" | "repair" | "reload" | undefined;
26
- #completed: AgentCompletion[] = [];
27
- #autoWake = false;
28
- constructor(readonly ctx: Context, readonly agent: Agent, readonly agents: AgentService,
29
- readonly teams: TeamService, readonly owner: AgentOwner, readonly check: () => void) {}
30
- get error() { return this.#error; }
31
- start() {
32
- this.teams.recover(this.owner);
33
- this.ctx.on("agent/pre-step", async ({ signal }, next) => {
34
- if (!this.#signals.has(signal)) {
35
- const cancel = () => { if (!this.#closed) {
36
- this.#paused = true; this.#autoWake = false; this.#pausePending = true;
37
- try { this.pauseTeams(); } catch (error) { this.recordError(error); }
38
- void this.refresh();
39
- } };
40
- this.#signals.set(signal, cancel); signal.addEventListener("abort", cancel, { once: true });
41
- if (signal.aborted) cancel();
42
- }
43
- await this.refresh(); this.check();
44
- const decision = await next(); this.check();
45
- if (decision.kind !== "enter" || this.#paused) return decision;
46
- const note = this.notice(decision.messages);
47
- return note ? { ...decision, messages: [...decision.messages, note] } : decision;
48
- });
49
- this.ctx.on("session/event", (session, event) => {
50
- if (session !== this.agent.session || this.#closed) return;
51
- if (event.type === "agent/inbox/spliced" && event.data.inserted.some(message => message.source.kind === "user")) { this.#paused = false; this.#autoWake = true; }
52
- if (event.type === "user/message" && event.data.source.kind === "pbot-results") this.#autoWake = true;
53
- if (event.type === "turn/end") {
54
- for (const [signal, cancel] of this.#signals) signal.removeEventListener("abort", cancel); this.#signals.clear();
55
- if (event.data.reason.kind === "aborted") {
56
- this.#paused = true; this.#autoWake = false; this.#pausePending = true;
57
- try { this.pauseTeams(); } catch (error) { this.recordError(error); }
58
- }
59
- void this.refresh();
60
- }
61
- });
62
- this.#timer = setInterval(() => { void this.refresh(); }, 1000); this.#timer.unref();
63
- this.ctx.effect(() => () => this.close());
64
- }
65
- private pauseTeams() {
66
- if (!this.#pausePending) return;
67
- try { this.teams.pauseAll(this.owner, "主会话中断"); this.#pausePending = false; this.#dispatching.clear(); }
68
- catch (error) {
69
- if ((error as NodeJS.ErrnoException).code !== "PBOT_CONTROL_BUSY") { this.teams.fail(error); this.#dispatching.clear(); }
70
- throw error;
71
- }
72
- }
73
- private recordError(error: unknown) {
74
- if (this.#closed || (error as Error).name === "AbortError") return;
75
- if ((error as NodeJS.ErrnoException).code === "PBOT_CONTROL_BUSY") {
76
- this.#busySince ??= Date.now(); if (Date.now() - this.#busySince < 5000) return;
77
- } else this.#busySince = undefined;
78
- const message = String(error);
79
- let recovery: "retry" | "repair" | "reload" = (error as NodeJS.ErrnoException).code === "PBOT_CONTROL_BUSY" ? "retry" : "repair";
80
- try { this.teams.check(); } catch { recovery = "reload"; }
81
- if (message !== this.#error || recovery !== this.#recovery) {
82
- this.ctx.logger.warn("pbot 协作扫描失败:" + message);
83
- this.#errorKey = "agent-error:" + randomUUID();
84
- }
85
- this.#error = message; this.#recovery = recovery;
86
- }
87
- private notice(proposed: readonly UserMessage[] = []) {
88
- const known = new Set([...deliveredDshNotices(this.agent.session.snapshotEvents()),
89
- ...pendingDshNotices([...this.agent.inbox.nextTurn, ...this.agent.inbox.nextStep, ...proposed])]);
90
- let value: { keys: string[]; content: string } | undefined;
91
- if (this.#error && this.#errorKey) {
92
- if (!known.has(this.#errorKey)) value = { keys: [this.#errorKey], content: "# 协作扫描故障\n\n" + this.#error +
93
- "\n\n先查看控制记录和原生报告,再决定是否重试,避免重复执行。" +
94
- (this.#recovery === "reload" ? "团队服务已停用;修复文件后还需重载服务端 personal-bot 插件。" :
95
- this.#recovery === "retry" ? "控制锁持续占用,后台会继续重试;不会自动删除锁或重新提交任务。" : "报告或控制记录读取失败,修复后后台会重试扫描。") +
96
- (this.#pausePending ? "\n\n团队暂停尚未确认,不能据此开始成员私人任务。" : "") };
97
- } else {
98
- value = teamNotice(this.teams.notifications(this.owner, this.agents.list(this.owner)), known) ??
99
- agentNotice(this.#completed, this.teams.links(), known);
100
- }
101
- return value ? createUserMessage({ content: [{ type: "text", text: value.content }],
102
- source: { kind: "pbot-results", form: "notice", summary: "Personal Bot 协作更新", keys: value.keys } }) : undefined;
103
- }
104
- refresh() {
105
- if (this.#closed || this.#scan) return this.#scan ?? Promise.resolve();
106
- this.#scan = (async () => {
107
- try { await this.scan(); } catch (error) { this.recordError(error); }
108
- if (this.#closed || this.#paused || !this.#autoWake || this.agent.status !== "idle") return;
109
- try {
110
- this.check(); const note = this.notice();
111
- if (note) {
112
- // A failed admission cannot start an automatic retry loop. Actual receipt or new human input re-arms wakeup.
113
- this.#autoWake = false; this.agent.followup(note); await flushDshAgent(this.agent);
114
- }
115
- } catch (error) { this.recordError(error); }
116
- })().finally(() => { this.#scan = undefined; });
117
- return this.#scan;
118
- }
119
- private async scan() {
120
- this.check(); this.pauseTeams(); await this.agents.refresh(this.owner);
121
- if (this.#closed) return; this.check();
122
- const completed = await this.agents.completions(this.owner);
123
- if (this.#closed) return; this.check(); this.#completed = completed;
124
- try {
125
- this.pauseTeams();
126
- for (const input of this.teams.advance(this.owner, this.agents.list(this.owner), completed)) this.#dispatching.set(input.requestId, input);
127
- for (const [id, input] of this.#dispatching) {
128
- try { this.agents.enqueueTeam(input, this.owner); this.#dispatching.delete(id); }
129
- catch (error) {
130
- const code = (error as NodeJS.ErrnoException).code;
131
- if (code === "PBOT_CONTROL_BUSY") throw error;
132
- if (code !== "TEAM_INPUT_STALE") throw error;
133
- this.teams.pauseMember(input.agentId, "安排失效;未自动重发"); this.#dispatching.delete(id);
134
- }
135
- }
136
- } catch (error) {
137
- if ((error as NodeJS.ErrnoException).code !== "PBOT_CONTROL_BUSY") { this.teams.fail(error); this.#dispatching.clear(); }
138
- throw error;
139
- }
140
- this.#error = undefined; this.#errorKey = undefined; this.#busySince = undefined; this.#recovery = undefined;
141
- }
142
- async close() {
143
- this.#closed = true;
144
- if (this.#timer) clearInterval(this.#timer); this.#timer = undefined;
145
- for (const [signal, cancel] of this.#signals) signal.removeEventListener("abort", cancel); this.#signals.clear();
146
- await this.#scan; this.#dispatching.clear();
147
- }
148
- }
@@ -1,252 +0,0 @@
1
- import type { Context } from "@deepseek-ai/cordis";
2
- import type { Agent, InboxTarget } from "@deepseek-ai/dsh-agent";
3
- import { foldConsumedWork } from "@deepseek-ai/dsh-agent";
4
- import { createUserMessage, type UserMessage, type FileBlock, type ImageBlock } from "@deepseek-ai/dsh-llm";
5
- import type { SessionEvent } from "@deepseek-ai/dsh-session";
6
- import { AgentRun } from "../../services/agents/agent-run.js";
7
- import type { TeamService } from "../../services/agents/team-service.js";
8
- import { AgentFiles, launch } from "../../storage/agent-files.js";
9
- import type { AgentDescriptor } from "../../model/agent.js";
10
- import type { TeamLink } from "../../model/team.js";
11
- import { requireThat } from "../../common/validation.js";
12
- import { dshInput, dshHumanInput } from "../../integrations/dsh/input.js";
13
- import { requestSource, finalDshAnswer } from "../../integrations/dsh/messages.js";
14
- import { flushDshAgent } from "../../integrations/dsh/session.js";
15
- import { createTeamContext, teamBrief } from "../../integrations/team-context.js";
16
-
17
- /** One expert's native event adapter. AgentRun and TeamService own durable business state. */
18
- export class DshAgentRuntime {
19
- readonly execution: AgentRun;
20
- readonly #lifetime = new AbortController();
21
- readonly #inbox: Record<InboxTarget, UserMessage[]> = { "next-turn": [], "next-step": [] };
22
- readonly #seen = new Map<string, Set<number>>();
23
- #events = Promise.resolve();
24
- #turnEvents: SessionEvent[] = [];
25
- #answer = "";
26
- #hasAnswer = false;
27
- #activeTeam: TeamLink | undefined;
28
- #teamBriefed = false;
29
- #pendingPause: string | undefined;
30
- #pump: Promise<void> | undefined;
31
- #timer: ReturnType<typeof setInterval> | undefined;
32
- #stopping: Promise<void> | undefined;
33
- #closing = false;
34
- #failure: unknown;
35
- #ready = false;
36
- #teamTool = false;
37
- constructor(readonly ctx: Context, readonly agent: Agent, readonly d: AgentDescriptor, readonly generation: string,
38
- readonly files: AgentFiles, readonly teams: TeamService, readonly owner: { check(): void; release(): Promise<void> }) {
39
- this.execution = new AgentRun(files, d.agentId, generation);
40
- }
41
- check = () => {
42
- this.#lifetime.signal.throwIfAborted(); this.owner.check(); this.files.check();
43
- const run = this.files.read(this.d.agentId, "launch.json", launch);
44
- requireThat(run.generation === this.generation && !run.stop, "专家已停止或启动代次变化。");
45
- };
46
- actor = () => ({ kind: "member" as const, agentId: this.d.agentId, generation: this.generation,
47
- ...(this.#activeTeam && this.execution.current?.source === "parent" ? { requestId: this.#activeTeam.request.requestId } : {}) });
48
- private current() { return this.files.read(this.d.agentId, "launch.json", launch).generation === this.generation; }
49
- private pause(reason: string) {
50
- this.#pendingPause = reason;
51
- try { this.teams.pauseMember(this.d.agentId, reason); this.#pendingPause = undefined; }
52
- catch (error) { if ((error as NodeJS.ErrnoException).code !== "PBOT_CONTROL_BUSY") throw error; }
53
- }
54
- private enqueue(work: () => void | Promise<void>) {
55
- this.#events = this.#events.then(work).catch(error => this.fail(error));
56
- }
57
- private fail(error: unknown) {
58
- if (this.#failure) return;
59
- this.#failure = error; this.#lifetime.abort();
60
- try {
61
- if (this.current()) {
62
- this.teams.files.setReady(this.d.agentId, this.generation, false);
63
- this.execution.save({ state: "error", activity: "控制失败", error: String(error) });
64
- this.pause("专家控制失败");
65
- }
66
- } catch (failure) { this.ctx.logger.error("pbot 专家状态保存失败", failure); }
67
- void this.owner.release().catch(failure => this.ctx.logger.error("pbot 专家释放失败", failure));
68
- }
69
- initialize(teamTool: boolean) {
70
- this.check(); this.#teamTool = teamTool;
71
- this.teams.files.setReady(this.d.agentId, this.generation, false);
72
- this.pause("专家载入:旧批次不自动恢复");
73
- this.execution.recover();
74
- for (const event of this.agent.session.snapshotEvents()) if (event.type === "user/message" && event.data.source.kind === "pbot-team-context") {
75
- const { teamId, seqs } = event.data.source, seen = this.#seen.get(teamId) ?? new Set<number>();
76
- for (const seq of seqs) seen.add(seq); this.#seen.set(teamId, seen);
77
- }
78
- this.ctx.on("session/event", (session, event) => {
79
- if (session === this.agent.session) this.enqueue(() => this.event(event));
80
- });
81
- this.ctx.on("agent/status", ({ agent, status }) => {
82
- if (agent !== this.agent) return;
83
- this.enqueue(() => {
84
- if (!this.current() || this.#closing || this.#failure) return;
85
- this.execution.save({ state: status === "idle" ? "idle" : "busy", activity: status === "idle" ? "空闲" : "执行" });
86
- });
87
- });
88
- this.ctx.on("agent/pre-step", async (_payload, next) => {
89
- await this.#events; this.check();
90
- if (this.#activeTeam && !this.humanPending() && this.execution.current?.source === "parent" && Date.now() >= this.#activeTeam.run.deadlineAt) {
91
- this.pause("已到期限"); this.agent.cancel({ kind: "hook", reason: "团队请求已到期限" });
92
- return { kind: "reject" };
93
- }
94
- const decision = await next();
95
- this.check();
96
- if (decision.kind !== "enter" || !this.#activeTeam || this.execution.current?.source !== "parent" || this.humanPending() ||
97
- decision.messages.some(message => message.source.kind === "user")) return decision;
98
- const link = this.teams.links().get(this.#activeTeam.request.requestId);
99
- requireThat(link, "团队关联不可读取。");
100
- const seen = this.#seen.get(link.team.teamId) ?? new Set<number>();
101
- const context = createTeamContext(link, seen);
102
- if (this.#teamBriefed && !context) return decision;
103
- const text = [...(this.#teamBriefed ? [] : [teamBrief(link)]), ...(context ? [context.content] : [])].join("\n\n");
104
- return { ...decision, messages: [...decision.messages, createUserMessage({ content: [{ type: "text", text }],
105
- source: { kind: "pbot-team-context", form: "relay", teamId: link.team.teamId, seqs: context?.seqs ?? [] } })] };
106
- });
107
- this.execution.save({ state: "idle", activity: "空闲" });
108
- this.ctx.effect(() => () => this.stop());
109
- }
110
- /** Called only after native Agent creation has resolved, never from setup. */
111
- start() {
112
- this.check();
113
- this.#timer = setInterval(() => { void this.pump(); }, 250); this.#timer.unref();
114
- void this.pump();
115
- }
116
- async interact(text: string, delivery: "steer" | "followUp" = "steer", files: readonly string[] = [],
117
- attachments: readonly (ImageBlock | FileBlock)[] = [], caller?: AbortSignal) {
118
- this.check(); requireThat((text.trim().length > 0 || files.length || attachments.length) && text.length <= 24000, "请输入消息或附加文件;消息最多 24000 字符。");
119
- const signal = caller ? AbortSignal.any([caller, this.#lifetime.signal]) : this.#lifetime.signal;
120
- const message = await dshHumanInput(this.ctx, this.d.cwd, text, files, attachments, signal);
121
- this.check(); signal.throwIfAborted();
122
- this.teams.pauseMember(this.d.agentId, "成员由人工接管");
123
- if (delivery === "followUp") this.agent.followup(message); else this.agent.steer(message);
124
- // Native inbox admission transfers ownership to the expert, independently of the UI request.
125
- await flushDshAgent(this.agent);
126
- return { status: "queued" as const, messageId: message.id };
127
- }
128
- private async event(event: SessionEvent) {
129
- if (!this.current()) return;
130
- if (event.type === "turn/start") {
131
- this.#turnEvents = []; this.#answer = ""; this.#hasAnswer = false; this.#teamBriefed = false;
132
- this.execution.begin();
133
- }
134
- if (this.execution.current) this.#turnEvents.push(event);
135
- if (event.type === "agent/inbox/spliced") {
136
- const change = event.data;
137
- const removed = this.#inbox[change.target].splice(change.start, change.removedCount ?? 0, ...change.inserted);
138
- if (change.inserted.some(message => message.source.kind === "user")) this.pause("成员由人工接管");
139
- for (const message of removed) {
140
- if (message.source.kind === "user" && change.outcome !== "canceled") this.execution.enterHuman();
141
- const source = requestSource(message, this.generation);
142
- if (!source) continue;
143
- if (change.outcome === "canceled") {
144
- this.execution.cancelQueued(source.requestId);
145
- if (this.#activeTeam?.request.requestId === source.requestId && !this.execution.current?.requestIds.includes(source.requestId)) this.#activeTeam = undefined;
146
- } else this.execution.enter(source.requestId);
147
- }
148
- }
149
- if (event.type === "user/message") {
150
- const source = requestSource(event.data, this.generation);
151
- if (source) this.execution.consume(source.requestId);
152
- if (event.data.source.kind === "user") this.execution.humanInput();
153
- if (event.data.source.kind === "pbot-team-context") {
154
- const { teamId, seqs } = event.data.source, seen = this.#seen.get(teamId) ?? new Set<number>();
155
- if (this.#activeTeam?.team.teamId === teamId) this.#teamBriefed = true;
156
- for (const seq of seqs) seen.add(seq); this.#seen.set(teamId, seen);
157
- }
158
- }
159
- if (event.type === "assistant/message") {
160
- this.#answer = finalDshAnswer(event); this.#hasAnswer = true;
161
- }
162
- if (event.type === "turn/end") {
163
- const accounted = foldConsumedWork(this.#turnEvents).end?.seq === event.seq;
164
- await flushDshAgent(this.agent);
165
- const reason = event.data.reason;
166
- this.execution.finish({
167
- state: reason.kind === "aborted" ? "cancelled" : reason.kind === "interrupted" || reason.kind === "forked" ? "interrupted"
168
- : reason.kind === "completed" && accounted ? "completed" : "failed",
169
- position: this.#hasAnswer ? "dsh:" + event.seq : null,
170
- answer: this.#answer,
171
- ...(reason.kind === "error" ? { error: reason.error.message } : !["completed", "aborted"].includes(reason.kind) ? { error: reason.kind } : {}),
172
- });
173
- this.#activeTeam = undefined; this.#turnEvents = [];
174
- }
175
- }
176
- private humanPending() { return [...this.agent.inbox.nextTurn, ...this.agent.inbox.nextStep].some(message => message.source.kind === "user"); }
177
- private pump() {
178
- if (this.#pump || this.#closing) return this.#pump ?? Promise.resolve();
179
- this.#pump = this.deliver().catch(error => {
180
- if ((error as NodeJS.ErrnoException).code === "PBOT_CONTROL_BUSY" || (this.#closing && this.#lifetime.signal.aborted)) return;
181
- this.fail(error);
182
- }).finally(() => { this.#pump = undefined; });
183
- return this.#pump;
184
- }
185
- private async deliver() {
186
- const run = this.files.read(this.d.agentId, "launch.json", launch);
187
- if (run.generation !== this.generation || run.stop) { void this.owner.release().catch(error => this.fail(error)); return; }
188
- await this.#events; this.check();
189
- if (this.#pendingPause) { this.pause(this.#pendingPause); if (this.#pendingPause) return; }
190
- const capable = this.#teamTool && !!this.ctx.tools.get("pbot_team_message", this.agent);
191
- if (capable !== this.#ready) {
192
- this.teams.files.setReady(this.d.agentId, this.generation, capable); this.#ready = capable;
193
- if (!capable) this.pause("成员团队工具已停用");
194
- }
195
- if (this.#activeTeam) {
196
- if (Date.now() >= this.#activeTeam.run.deadlineAt) {
197
- this.pause("已到期限");
198
- if (!this.humanPending() && !this.execution.interactive && this.execution.current?.source !== "mixed" && this.execution.current?.source !== "interactive") this.agent.cancel({ kind: "hook", reason: "团队请求已到期限" });
199
- }
200
- return;
201
- }
202
- const links = this.teams.links();
203
- const idle = () => this.agent.status === "idle" && !this.agent.inbox.nextTurn.length && !this.agent.inbox.nextStep.length && !this.execution.current && !this.execution.pending && !this.execution.interactive;
204
- for (const request of this.files.messages(this.d.agentId)) {
205
- if (request.generation !== this.generation || this.execution.accepted(request.requestId)) continue;
206
- const link = links.get(request.requestId);
207
- if (link && (link.team.closed || link.run.state !== "running" || link.run.deadlineAt <= Date.now())) continue;
208
- if (link && !idle()) break;
209
- const message = await dshInput(this.ctx, this.d, request, this.#lifetime.signal);
210
- this.check();
211
- const submit = async () => {
212
- this.check();
213
- const accept = () => this.execution.claim(request.requestId);
214
- if (link) {
215
- if (!idle()) return;
216
- this.#activeTeam = this.teams.claim(this.d.agentId, this.generation, request.requestId, accept);
217
- if (!this.#activeTeam) return;
218
- } else accept();
219
- if (request.delivery === "followUp") this.agent.followup(message); else this.agent.steer(message);
220
- await flushDshAgent(this.agent);
221
- };
222
- if (link) {
223
- // Public status stays idle during native maintenance. Its idle admission is authoritative.
224
- let entered = false;
225
- try { await this.agent.runMaintenance(async signal => { entered = true; signal.throwIfAborted(); await submit(); }); }
226
- catch (error) { if (entered) throw error; this.check(); }
227
- } else await submit();
228
- break;
229
- }
230
- }
231
- stop() {
232
- if (this.#stopping) return this.#stopping;
233
- this.#closing = true; this.#lifetime.abort();
234
- if (this.#timer) clearInterval(this.#timer); this.#timer = undefined;
235
- this.#stopping = (async () => {
236
- try {
237
- if (this.current()) {
238
- this.files.control(() => {
239
- const run = this.files.read(this.d.agentId, "launch.json", launch);
240
- if (run.generation === this.generation && !run.stop) { run.stop = true; this.files.write(this.d.agentId, "launch.json", run, launch); }
241
- });
242
- this.teams.files.setReady(this.d.agentId, this.generation, false); this.#ready = false;
243
- this.pause("专家停止");
244
- if (!this.#failure) this.execution.save({ state: "stopping", activity: "停止" });
245
- }
246
- } finally { this.agent.cancel({ kind: "disposed" }); }
247
- await this.agent.whenIdle(); await this.#pump; await this.#events;
248
- if (this.current() && !this.#failure) this.execution.save({ state: "stopped", activity: "已停止" });
249
- })();
250
- return this.#stopping;
251
- }
252
- }