dsh-botgroup 0.6.7 → 0.7.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 (478) hide show
  1. package/README.en.md +60 -122
  2. package/README.md +59 -121
  3. package/lib/client.js +11837 -7685
  4. package/lib/client.js.map +4 -4
  5. package/lib/host/activity/first-user.js +1 -1
  6. package/lib/host/activity/preview.js +1 -1
  7. package/lib/host/activity/remote.js +1 -1
  8. package/lib/host/activity/tracker.js +1 -1
  9. package/lib/host/automation/coordinator.js +1 -1
  10. package/lib/host/automation/delivery.js +1 -1
  11. package/lib/host/automation/errors.js +1 -1
  12. package/lib/host/automation/index.js +1 -1
  13. package/lib/host/automation/remote.js +1 -1
  14. package/lib/host/automation/store.js +1 -1
  15. package/lib/host/bot-context.d.ts +3 -0
  16. package/lib/host/bot-context.js +97 -22
  17. package/lib/host/bot-context.js.map +1 -1
  18. package/lib/host/capabilities/platform.js +1 -1
  19. package/lib/host/capabilities/remote.js +1 -1
  20. package/lib/host/capabilities/service.js +1 -1
  21. package/lib/host/collaboration/remote.js +1 -1
  22. package/lib/host/collaboration/service.js +1 -1
  23. package/lib/host/common/integration-stores.js +1 -1
  24. package/lib/host/common/native-ambient-source.d.ts +7 -0
  25. package/lib/host/common/native-ambient-source.js +15 -0
  26. package/lib/host/common/native-ambient-source.js.map +1 -0
  27. package/lib/host/common/operations.js +1 -1
  28. package/lib/host/common/subagent-activation.d.ts +7 -0
  29. package/lib/host/common/subagent-activation.js +10 -0
  30. package/lib/host/common/subagent-activation.js.map +1 -0
  31. package/lib/host/composer.js +1 -1
  32. package/lib/host/connectors/remote.js +1 -1
  33. package/lib/host/connectors/service.js +1 -1
  34. package/lib/host/data-flow/agent-binding.js +1 -1
  35. package/lib/host/data-flow/connector-boundary.js +1 -1
  36. package/lib/host/data-flow/delegation.js +4 -3
  37. package/lib/host/data-flow/delegation.js.map +1 -1
  38. package/lib/host/data-flow/egress.d.ts +6 -0
  39. package/lib/host/data-flow/egress.js +32 -2
  40. package/lib/host/data-flow/egress.js.map +1 -1
  41. package/lib/host/data-flow/grants.js +1 -1
  42. package/lib/host/data-flow/graph-capability.js +1 -1
  43. package/lib/host/data-flow/labels.js +3 -2
  44. package/lib/host/data-flow/labels.js.map +1 -1
  45. package/lib/host/data-flow/lineage.js +3 -2
  46. package/lib/host/data-flow/lineage.js.map +1 -1
  47. package/lib/host/data-flow/managed-copies.d.ts +11 -3
  48. package/lib/host/data-flow/managed-copies.js +1 -1
  49. package/lib/host/data-flow/native-policy.js +1 -1
  50. package/lib/host/data-flow/outlets.d.ts +66 -1
  51. package/lib/host/data-flow/outlets.js +61 -2
  52. package/lib/host/data-flow/outlets.js.map +1 -1
  53. package/lib/host/data-flow/tool-guard.js +12 -3
  54. package/lib/host/data-flow/tool-guard.js.map +1 -1
  55. package/lib/host/delegate/continuation.js +1 -1
  56. package/lib/host/delegate/guard.js +9 -5
  57. package/lib/host/delegate/guard.js.map +1 -1
  58. package/lib/host/delegate/tool.js +29 -2
  59. package/lib/host/delegate/tool.js.map +1 -1
  60. package/lib/host/errors.js +1 -1
  61. package/lib/host/groups/concurrent.js +25 -14
  62. package/lib/host/groups/concurrent.js.map +1 -1
  63. package/lib/host/groups/context-flow.d.ts +28 -0
  64. package/lib/host/groups/context-flow.js +127 -0
  65. package/lib/host/groups/context-flow.js.map +1 -0
  66. package/lib/host/groups/data-flow.d.ts +9 -3
  67. package/lib/host/groups/data-flow.js +81 -19
  68. package/lib/host/groups/data-flow.js.map +1 -1
  69. package/lib/host/groups/export-pending.d.ts +5 -0
  70. package/lib/host/groups/export-pending.js +36 -0
  71. package/lib/host/groups/export-pending.js.map +1 -0
  72. package/lib/host/groups/export-review.d.ts +35 -0
  73. package/lib/host/groups/export-review.js +235 -0
  74. package/lib/host/groups/export-review.js.map +1 -0
  75. package/lib/host/groups/export-settings.d.ts +94 -0
  76. package/lib/host/groups/export-settings.js +78 -0
  77. package/lib/host/groups/export-settings.js.map +1 -0
  78. package/lib/host/groups/failure.js +3 -1
  79. package/lib/host/groups/failure.js.map +1 -1
  80. package/lib/host/groups/members.d.ts +105 -2
  81. package/lib/host/groups/members.js +47 -4
  82. package/lib/host/groups/members.js.map +1 -1
  83. package/lib/host/groups/memory-status.d.ts +7 -0
  84. package/lib/host/groups/memory-status.js +66 -0
  85. package/lib/host/groups/memory-status.js.map +1 -0
  86. package/lib/host/groups/messages.d.ts +90 -0
  87. package/lib/host/groups/messages.js +20 -8
  88. package/lib/host/groups/messages.js.map +1 -1
  89. package/lib/host/groups/model-selection.js +1 -1
  90. package/lib/host/groups/model.d.ts +95 -0
  91. package/lib/host/groups/model.js +21 -2
  92. package/lib/host/groups/model.js.map +1 -1
  93. package/lib/host/groups/owner-follow-up.js +1 -1
  94. package/lib/host/groups/recall-sessions.d.ts +8 -0
  95. package/lib/host/groups/recall-sessions.js +20 -1
  96. package/lib/host/groups/recall-sessions.js.map +1 -1
  97. package/lib/host/groups/recall-tool.js +1 -1
  98. package/lib/host/groups/recall.d.ts +6 -2
  99. package/lib/host/groups/recall.js +63 -16
  100. package/lib/host/groups/recall.js.map +1 -1
  101. package/lib/host/groups/remote.d.ts +531 -0
  102. package/lib/host/groups/remote.js +81 -1
  103. package/lib/host/groups/remote.js.map +1 -1
  104. package/lib/host/groups/root-guard.js +1 -1
  105. package/lib/host/groups/roots.js +1 -1
  106. package/lib/host/groups/round-robin.js +1 -1
  107. package/lib/host/groups/routing.d.ts +29 -1
  108. package/lib/host/groups/routing.js +34 -3
  109. package/lib/host/groups/routing.js.map +1 -1
  110. package/lib/host/groups/service.d.ts +662 -4
  111. package/lib/host/groups/service.js +96 -9
  112. package/lib/host/groups/service.js.map +1 -1
  113. package/lib/host/groups/state.d.ts +229 -2
  114. package/lib/host/groups/state.js +32 -3
  115. package/lib/host/groups/state.js.map +1 -1
  116. package/lib/host/groups/supergroup-admission.d.ts +87 -0
  117. package/lib/host/groups/supergroup-admission.js +99 -0
  118. package/lib/host/groups/supergroup-admission.js.map +1 -0
  119. package/lib/host/groups/team-recipes.d.ts +125 -0
  120. package/lib/host/groups/team-recipes.js +100 -0
  121. package/lib/host/groups/team-recipes.js.map +1 -0
  122. package/lib/host/groups/turn-runner.d.ts +81 -0
  123. package/lib/host/groups/turn-runner.js +88 -18
  124. package/lib/host/groups/turn-runner.js.map +1 -1
  125. package/lib/host/groups/turns.d.ts +114 -1
  126. package/lib/host/groups/turns.js +67 -20
  127. package/lib/host/groups/turns.js.map +1 -1
  128. package/lib/host/groups/worker-tool.d.ts +8 -1
  129. package/lib/host/groups/worker-tool.js +87 -9
  130. package/lib/host/groups/worker-tool.js.map +1 -1
  131. package/lib/host/home.js +1 -1
  132. package/lib/host/im/service.js +1 -1
  133. package/lib/host/index.d.ts +2 -1
  134. package/lib/host/index.js +30 -2
  135. package/lib/host/index.js.map +1 -1
  136. package/lib/host/live-persona.js +1 -1
  137. package/lib/host/main-session.d.ts +5 -2
  138. package/lib/host/main-session.js +118 -12
  139. package/lib/host/main-session.js.map +1 -1
  140. package/lib/host/memory/admission.d.ts +1 -0
  141. package/lib/host/memory/admission.js +24 -1
  142. package/lib/host/memory/admission.js.map +1 -1
  143. package/lib/host/memory/auto-share.js +1 -1
  144. package/lib/host/memory/confirmation.d.ts +21 -5
  145. package/lib/host/memory/confirmation.js +1 -1
  146. package/lib/host/memory/conflicts.js +1 -1
  147. package/lib/host/memory/consolidation-config.d.ts +12 -0
  148. package/lib/host/memory/consolidation-config.js +13 -0
  149. package/lib/host/memory/consolidation-config.js.map +1 -0
  150. package/lib/host/memory/consolidation-native.d.ts +14 -0
  151. package/lib/host/memory/consolidation-native.js +72 -0
  152. package/lib/host/memory/consolidation-native.js.map +1 -0
  153. package/lib/host/memory/consolidation-source.d.ts +4 -0
  154. package/lib/host/memory/consolidation-source.js +25 -0
  155. package/lib/host/memory/consolidation-source.js.map +1 -0
  156. package/lib/host/memory/consolidation.d.ts +80 -0
  157. package/lib/host/memory/consolidation.js +270 -0
  158. package/lib/host/memory/consolidation.js.map +1 -0
  159. package/lib/host/memory/context.js +1 -1
  160. package/lib/host/memory/domain-v2.d.ts +53 -10
  161. package/lib/host/memory/domain-v2.js +5 -3
  162. package/lib/host/memory/domain-v2.js.map +1 -1
  163. package/lib/host/memory/facade.d.ts +147 -3
  164. package/lib/host/memory/facade.js +113 -3
  165. package/lib/host/memory/facade.js.map +1 -1
  166. package/lib/host/memory/forget-preview.js +1 -1
  167. package/lib/host/memory/forget-runner.js +1 -1
  168. package/lib/host/memory/forget-service.js +1 -1
  169. package/lib/host/memory/history-proof.js +1 -1
  170. package/lib/host/memory/history.js +1 -1
  171. package/lib/host/memory/layout-upgrade.js +23 -6
  172. package/lib/host/memory/layout-upgrade.js.map +1 -1
  173. package/lib/host/memory/migration.js +1 -1
  174. package/lib/host/memory/op-log.js +1 -1
  175. package/lib/host/memory/open-v2.js +1 -1
  176. package/lib/host/memory/owner-lease.js +1 -1
  177. package/lib/host/memory/persistent-map.js +1 -1
  178. package/lib/host/memory/port.js +1 -1
  179. package/lib/host/memory/preserve-inbox.js +1 -1
  180. package/lib/host/memory/projection.js +6 -1
  181. package/lib/host/memory/projection.js.map +1 -1
  182. package/lib/host/memory/prompt.js +1 -1
  183. package/lib/host/memory/query.js +1 -1
  184. package/lib/host/memory/quota-replay.js +1 -1
  185. package/lib/host/memory/quota.d.ts +21 -5
  186. package/lib/host/memory/quota.js +1 -1
  187. package/lib/host/memory/remote.d.ts +218 -0
  188. package/lib/host/memory/remote.js +41 -1
  189. package/lib/host/memory/remote.js.map +1 -1
  190. package/lib/host/memory/retrieval-config.js +1 -1
  191. package/lib/host/memory/retrieval-rank.js +1 -1
  192. package/lib/host/memory/retrieval-text.js +1 -1
  193. package/lib/host/memory/root-instructions.js +1 -1
  194. package/lib/host/memory/secrets.js +1 -1
  195. package/lib/host/memory/service.js +1 -1
  196. package/lib/host/memory/shards.js +1 -1
  197. package/lib/host/memory/store-v2.js +5 -2
  198. package/lib/host/memory/store-v2.js.map +1 -1
  199. package/lib/host/memory/temporal.js +3 -2
  200. package/lib/host/memory/temporal.js.map +1 -1
  201. package/lib/host/memory/tool-guidance.js +1 -1
  202. package/lib/host/memory/tools.js +1 -1
  203. package/lib/host/memory/trusted-ingress.js +1 -1
  204. package/lib/host/memory/version.d.ts +20 -4
  205. package/lib/host/memory/version.js +1 -1
  206. package/lib/host/messaging/config.js +1 -1
  207. package/lib/host/messaging/core.d.ts +11 -3
  208. package/lib/host/messaging/core.js +4 -3
  209. package/lib/host/messaging/core.js.map +1 -1
  210. package/lib/host/messaging/delivery.js +3 -1
  211. package/lib/host/messaging/delivery.js.map +1 -1
  212. package/lib/host/messaging/evidence.js +1 -1
  213. package/lib/host/messaging/interrupt.js +1 -1
  214. package/lib/host/messaging/recovery.js +1 -1
  215. package/lib/host/messaging/remote.d.ts +1 -1
  216. package/lib/host/messaging/remote.js +1 -1
  217. package/lib/host/messaging/reply-routing.js +1 -1
  218. package/lib/host/messaging/safety.js +8 -3
  219. package/lib/host/messaging/safety.js.map +1 -1
  220. package/lib/host/messaging/scoped-projection.d.ts +43 -0
  221. package/lib/host/messaging/scoped-projection.js +136 -0
  222. package/lib/host/messaging/scoped-projection.js.map +1 -0
  223. package/lib/host/messaging/service.d.ts +5 -2
  224. package/lib/host/messaging/service.js +16 -6
  225. package/lib/host/messaging/service.js.map +1 -1
  226. package/lib/host/messaging/store.d.ts +45 -13
  227. package/lib/host/messaging/store.js +4 -3
  228. package/lib/host/messaging/store.js.map +1 -1
  229. package/lib/host/messaging/tool.js +24 -5
  230. package/lib/host/messaging/tool.js.map +1 -1
  231. package/lib/host/messaging/wake.js +3 -3
  232. package/lib/host/messaging/wake.js.map +1 -1
  233. package/lib/host/native-schedule/outcomes.js +1 -1
  234. package/lib/host/native-schedule/service.js +10 -7
  235. package/lib/host/native-schedule/service.js.map +1 -1
  236. package/lib/host/notifications/data-flow.js +1 -1
  237. package/lib/host/notifications/remote.js +1 -1
  238. package/lib/host/notifications/service.js +1 -1
  239. package/lib/host/notifications/time.js +1 -1
  240. package/lib/host/notifications/tool.js +1 -1
  241. package/lib/host/onboarding/coordinator.js +1 -1
  242. package/lib/host/onboarding/guard.js +1 -1
  243. package/lib/host/proactive/auto-admission.js +1 -1
  244. package/lib/host/proactive/config.js +1 -1
  245. package/lib/host/proactive/coordinator-client.js +1 -1
  246. package/lib/host/proactive/deferred-notices.js +1 -1
  247. package/lib/host/proactive/execution-prompt.js +1 -1
  248. package/lib/host/proactive/execution.js +1 -1
  249. package/lib/host/proactive/executors/command.js +1 -1
  250. package/lib/host/proactive/executors/json-command-bridge-entry.js +1 -1
  251. package/lib/host/proactive/executors/json-command-bridge.js +1 -1
  252. package/lib/host/proactive/executors/loopback.js +1 -1
  253. package/lib/host/proactive/feedback-workflow.d.ts +3 -0
  254. package/lib/host/proactive/feedback-workflow.js +8 -3
  255. package/lib/host/proactive/feedback-workflow.js.map +1 -1
  256. package/lib/host/proactive/feedback.js +1 -1
  257. package/lib/host/proactive/follow-up-events.d.ts +2 -0
  258. package/lib/host/proactive/follow-up-events.js +63 -4
  259. package/lib/host/proactive/follow-up-events.js.map +1 -1
  260. package/lib/host/proactive/follow-up-facts.js +1 -1
  261. package/lib/host/proactive/follow-up-tool.js +3 -3
  262. package/lib/host/proactive/follow-up-tool.js.map +1 -1
  263. package/lib/host/proactive/governance-artifacts.js +1 -1
  264. package/lib/host/proactive/governance-service.js +1 -1
  265. package/lib/host/proactive/group-budget.js +1 -1
  266. package/lib/host/proactive/group-follow-up.js +1 -1
  267. package/lib/host/proactive/group-repair.js +1 -1
  268. package/lib/host/proactive/index.js +1 -1
  269. package/lib/host/proactive/lifecycle.js +1 -1
  270. package/lib/host/proactive/method-evaluation.js +1 -1
  271. package/lib/host/proactive/method-package.js +1 -1
  272. package/lib/host/proactive/method-skill.js +1 -1
  273. package/lib/host/proactive/model-budget.js +1 -1
  274. package/lib/host/proactive/notice-pump.js +1 -1
  275. package/lib/host/proactive/notification-bridge.js +1 -1
  276. package/lib/host/proactive/read-query.js +1 -1
  277. package/lib/host/proactive/remote.d.ts +169 -0
  278. package/lib/host/proactive/remote.js +1 -1
  279. package/lib/host/proactive/repair.js +1 -1
  280. package/lib/host/proactive/result-journal.js +1 -1
  281. package/lib/host/proactive/service.d.ts +1729 -51
  282. package/lib/host/proactive/service.js +48 -37
  283. package/lib/host/proactive/service.js.map +1 -1
  284. package/lib/host/proactive/session-history.d.ts +3 -0
  285. package/lib/host/proactive/session-history.js +21 -0
  286. package/lib/host/proactive/session-history.js.map +1 -0
  287. package/lib/host/proactive/setup.js +1 -1
  288. package/lib/host/proactive/sources/ci-feed.js +1 -1
  289. package/lib/host/proactive/sources/ci.js +1 -1
  290. package/lib/host/proactive/sources/github-ci.js +1 -1
  291. package/lib/host/proactive/task-cost.js +1 -1
  292. package/lib/host/proactive/wire.js +1 -1
  293. package/lib/host/proactive/work-continuation.js +1 -1
  294. package/lib/host/proactive/workspace-process.js +1 -1
  295. package/lib/host/proactive/workspace-repair.js +1 -1
  296. package/lib/host/reference-memory/backend.js +1 -1
  297. package/lib/host/reference-memory/cleanup-files.js +1 -1
  298. package/lib/host/reference-memory/copies.js +1 -1
  299. package/lib/host/reference-memory/files.js +1 -1
  300. package/lib/host/reference-memory/model.js +1 -1
  301. package/lib/host/reference-memory/service.js +1 -1
  302. package/lib/host/reference-memory/writer.js +1 -1
  303. package/lib/host/registry/identity.js +1 -1
  304. package/lib/host/registry/lifecycle.d.ts +4 -1
  305. package/lib/host/registry/lifecycle.js +3 -1
  306. package/lib/host/registry/lifecycle.js.map +1 -1
  307. package/lib/host/registry/mutations.js +1 -1
  308. package/lib/host/registry/presets.js +1 -1
  309. package/lib/host/registry/types.js +1 -1
  310. package/lib/host/registry-config.d.ts +5 -1
  311. package/lib/host/registry-config.js +11 -2
  312. package/lib/host/registry-config.js.map +1 -1
  313. package/lib/host/registry.d.ts +8 -0
  314. package/lib/host/registry.js +45 -4
  315. package/lib/host/registry.js.map +1 -1
  316. package/lib/host/shadow/budget.js +1 -1
  317. package/lib/host/shadow/config.js +1 -1
  318. package/lib/host/shadow/notification-adapter.js +1 -1
  319. package/lib/host/shadow/planner.js +1 -1
  320. package/lib/host/shadow/schedule-adapter.js +1 -1
  321. package/lib/host/shadow/service.js +1 -1
  322. package/lib/host/store.js +1 -1
  323. package/lib/host/stores/activity.js +1 -1
  324. package/lib/host/stores/bots.js +1 -1
  325. package/lib/host/stores/domain.js +1 -1
  326. package/lib/host/stores/memory.js +1 -1
  327. package/lib/host/supergroup/collaboration.d.ts +99 -0
  328. package/lib/host/supergroup/collaboration.js +362 -0
  329. package/lib/host/supergroup/collaboration.js.map +1 -0
  330. package/lib/host/supergroup/config.d.ts +15 -0
  331. package/lib/host/supergroup/config.js +34 -0
  332. package/lib/host/supergroup/config.js.map +1 -0
  333. package/lib/host/supergroup/input-capability.d.ts +4 -0
  334. package/lib/host/supergroup/input-capability.js +21 -0
  335. package/lib/host/supergroup/input-capability.js.map +1 -0
  336. package/lib/host/supergroup/recovery-view.d.ts +16 -0
  337. package/lib/host/supergroup/recovery-view.js +38 -0
  338. package/lib/host/supergroup/recovery-view.js.map +1 -0
  339. package/lib/host/supergroup/remote.d.ts +2064 -0
  340. package/lib/host/supergroup/remote.js +123 -0
  341. package/lib/host/supergroup/remote.js.map +1 -0
  342. package/lib/host/supergroup/service.d.ts +987 -0
  343. package/lib/host/supergroup/service.js +945 -0
  344. package/lib/host/supergroup/service.js.map +1 -0
  345. package/lib/host/supergroup/task-support.d.ts +266 -0
  346. package/lib/host/supergroup/task-support.js +323 -0
  347. package/lib/host/supergroup/task-support.js.map +1 -0
  348. package/lib/host/supergroup/tool.d.ts +4 -0
  349. package/lib/host/supergroup/tool.js +74 -0
  350. package/lib/host/supergroup/tool.js.map +1 -0
  351. package/lib/host/tools/bot-manage.js +7 -3
  352. package/lib/host/tools/bot-manage.js.map +1 -1
  353. package/lib/host/workspace/remote.js +1 -1
  354. package/lib/host/workspace/service.js +1 -1
  355. package/lib/index.d.ts +1 -1
  356. package/lib/index.js +1 -1
  357. package/lib/module-manifest.json +288 -258
  358. package/lib/proactive-coordinator/main.mjs +236 -25
  359. package/lib/proactive-coordinator/provenance.json +1 -1
  360. package/lib/shared/activity-preview.js +1 -1
  361. package/lib/shared/activity.js +1 -1
  362. package/lib/shared/automation-contract.js +1 -1
  363. package/lib/shared/automation.js +1 -1
  364. package/lib/shared/bot-brand.js +1 -1
  365. package/lib/shared/capabilities-contract.js +1 -1
  366. package/lib/shared/collaboration-contract.js +1 -1
  367. package/lib/shared/collaboration.js +1 -1
  368. package/lib/shared/connectors.js +1 -1
  369. package/lib/shared/data-flow.d.ts +1 -0
  370. package/lib/shared/data-flow.js +3 -1
  371. package/lib/shared/data-flow.js.map +1 -1
  372. package/lib/shared/eval-budget.js +1 -1
  373. package/lib/shared/group-export-review.d.ts +3 -0
  374. package/lib/shared/group-export-review.js +12 -0
  375. package/lib/shared/group-export-review.js.map +1 -0
  376. package/lib/shared/group-limits.d.ts +4 -0
  377. package/lib/shared/group-limits.js +6 -0
  378. package/lib/shared/group-limits.js.map +1 -0
  379. package/lib/shared/group-recall-reads.js +1 -1
  380. package/lib/shared/group-recall.js +1 -1
  381. package/lib/shared/groups-contract.d.ts +3002 -3
  382. package/lib/shared/groups-contract.js +25 -2
  383. package/lib/shared/groups-contract.js.map +1 -1
  384. package/lib/shared/groups.d.ts +317 -0
  385. package/lib/shared/groups.js +69 -8
  386. package/lib/shared/groups.js.map +1 -1
  387. package/lib/shared/identity.js +1 -1
  388. package/lib/shared/ids.js +1 -1
  389. package/lib/shared/integrations-contract.js +1 -1
  390. package/lib/shared/integrations.js +1 -1
  391. package/lib/shared/managed-flow.d.ts +4 -0
  392. package/lib/shared/managed-flow.js +2 -2
  393. package/lib/shared/managed-flow.js.map +1 -1
  394. package/lib/shared/memory-consolidation.d.ts +104 -0
  395. package/lib/shared/memory-consolidation.js +23 -0
  396. package/lib/shared/memory-consolidation.js.map +1 -0
  397. package/lib/shared/memory-forget.js +1 -1
  398. package/lib/shared/memory-management.d.ts +491 -1
  399. package/lib/shared/memory-management.js +9 -1
  400. package/lib/shared/memory-management.js.map +1 -1
  401. package/lib/shared/memory-ops.d.ts +17 -1
  402. package/lib/shared/memory-ops.js +1 -1
  403. package/lib/shared/memory-tool-names.js +1 -1
  404. package/lib/shared/memory-v2.d.ts +16 -0
  405. package/lib/shared/memory-v2.js +3 -1
  406. package/lib/shared/memory-v2.js.map +1 -1
  407. package/lib/shared/messaging-contract.d.ts +1 -1
  408. package/lib/shared/messaging-contract.js +1 -1
  409. package/lib/shared/messaging.d.ts +21 -10
  410. package/lib/shared/messaging.js +3 -1
  411. package/lib/shared/messaging.js.map +1 -1
  412. package/lib/shared/native-schedule.d.ts +21 -0
  413. package/lib/shared/native-schedule.js +15 -1
  414. package/lib/shared/native-schedule.js.map +1 -1
  415. package/lib/shared/notifications.js +1 -1
  416. package/lib/shared/onboarding-source.js +1 -1
  417. package/lib/shared/onboarding.js +1 -1
  418. package/lib/shared/operation-errors.d.ts +6 -0
  419. package/lib/shared/operation-errors.js +7 -1
  420. package/lib/shared/operation-errors.js.map +1 -1
  421. package/lib/shared/proactive/activity.js +1 -1
  422. package/lib/shared/proactive/document.js +1 -1
  423. package/lib/shared/proactive/feedback.d.ts +12 -0
  424. package/lib/shared/proactive/feedback.js +2 -2
  425. package/lib/shared/proactive/feedback.js.map +1 -1
  426. package/lib/shared/proactive/follow-up.d.ts +460 -0
  427. package/lib/shared/proactive/follow-up.js +15 -1
  428. package/lib/shared/proactive/follow-up.js.map +1 -1
  429. package/lib/shared/proactive/governance.js +1 -1
  430. package/lib/shared/proactive/group-follow-up.js +1 -1
  431. package/lib/shared/proactive/group-repair.js +1 -1
  432. package/lib/shared/proactive/handoff.js +1 -1
  433. package/lib/shared/proactive/method-evaluation.d.ts +4 -0
  434. package/lib/shared/proactive/method-evaluation.js +2 -1
  435. package/lib/shared/proactive/method-evaluation.js.map +1 -1
  436. package/lib/shared/proactive/method-package.js +1 -1
  437. package/lib/shared/proactive/notices.js +1 -1
  438. package/lib/shared/proactive/outcomes.js +1 -1
  439. package/lib/shared/proactive/protocol.d.ts +651 -0
  440. package/lib/shared/proactive/protocol.js +1 -1
  441. package/lib/shared/proactive/remote-contract.d.ts +828 -0
  442. package/lib/shared/proactive/remote-contract.js +1 -1
  443. package/lib/shared/proactive/repair.js +1 -1
  444. package/lib/shared/proactive/responsibility.js +1 -1
  445. package/lib/shared/proactive/setup.d.ts +83 -0
  446. package/lib/shared/proactive/setup.js +1 -1
  447. package/lib/shared/proactive/work-progress.js +1 -1
  448. package/lib/shared/proactive/work.js +1 -1
  449. package/lib/shared/proactive/workspace-repair.js +1 -1
  450. package/lib/shared/reference-memory.js +1 -1
  451. package/lib/shared/remote-contract.d.ts +1081 -47
  452. package/lib/shared/remote-contract.js +28 -2
  453. package/lib/shared/remote-contract.js.map +1 -1
  454. package/lib/shared/routine-outcomes.js +1 -1
  455. package/lib/shared/schema.js +1 -1
  456. package/lib/shared/secrets.js +1 -1
  457. package/lib/shared/shadow.js +1 -1
  458. package/lib/shared/supergroup-contract.d.ts +7535 -0
  459. package/lib/shared/supergroup-contract.js +26 -0
  460. package/lib/shared/supergroup-contract.js.map +1 -0
  461. package/lib/shared/supergroup.d.ts +1495 -0
  462. package/lib/shared/supergroup.js +56 -0
  463. package/lib/shared/supergroup.js.map +1 -0
  464. package/lib/shared/task-materials.d.ts +200 -0
  465. package/lib/shared/task-materials.js +44 -0
  466. package/lib/shared/task-materials.js.map +1 -0
  467. package/lib/shared/team-recipes.d.ts +130 -0
  468. package/lib/shared/team-recipes.js +28 -0
  469. package/lib/shared/team-recipes.js.map +1 -0
  470. package/lib/shared/version.d.ts +1 -1
  471. package/lib/shared/version.js +2 -2
  472. package/lib/shared/workspace-contract.js +1 -1
  473. package/lib/shared/workspace.js +1 -1
  474. package/lib/typert.host.js +1 -1
  475. package/lib/typert.remote-client.js +1 -1
  476. package/locale/en.json +305 -7
  477. package/locale/zh.json +305 -7
  478. package/package.json +2 -1
@@ -0,0 +1,945 @@
1
+ import { SessionId } from '@deepseek-ai/dsh-session';
2
+ import { createUserMessage } from '@deepseek-ai/dsh-llm';
3
+ import { TaskSupport } from './task-support.js';
4
+ import { admitSupergroupInput } from './input-capability.js';
5
+ import { defineDomain, domainTable } from '@deepseek-ai/dsh-storage-domain';
6
+ import { createHash } from 'node:crypto';
7
+ import { z } from 'zod';
8
+ import { groupKey } from '../../shared/groups.js';
9
+ import { GROUP_MEMBER_LIMIT } from '../../shared/group-limits.js';
10
+ import { supergroupSendGroupInputSchema, supergroupWorkSchema } from '../../shared/supergroup.js';
11
+ import { getBotBinding } from '../data-flow/agent-binding.js';
12
+ import { outlets } from '../data-flow/tool-guard.js';
13
+ import { OperationError, Serial } from '../common/operations.js';
14
+ import { isNativeAmbientSource } from '../common/native-ambient-source.js';
15
+ import { Config } from './config.js';
16
+ import { ScopedCollaboration, getScopedCollaborationBinding } from './collaboration.js';
17
+ export const supergroupDomain = defineDomain({ name: 'dsh_bot_supergroup', version: 1,
18
+ tables: { works: domainTable(supergroupWorkSchema) } });
19
+ export const supergroupInputSchema = z.discriminatedUnion('action', [
20
+ z.strictObject({ action: z.literal('start'), memberIds: z.array(z.string().min(1)).min(2).max(16) }),
21
+ z.strictObject({ action: z.literal('continue'), workId: z.string().min(1).optional() }),
22
+ z.strictObject({ action: z.literal('status'), workId: z.string().min(1).optional() }),
23
+ z.strictObject({ action: z.literal('cancel'), workId: z.string().min(1).optional() }),
24
+ ]);
25
+ /** Same bounded, deterministic directory for model discovery and Host admission. */
26
+ export function supergroupCandidateIds(ownerId, directory, config) {
27
+ const experts = [...new Set(config.allowedBotIds.length ? config.allowedBotIds : directory.map(bot => bot.id))]
28
+ .filter(id => id !== ownerId).sort((a, b) => a.localeCompare(b));
29
+ if (config.allowedBotIds.length && experts.length > config.maxExperts)
30
+ throw new OperationError('invalid');
31
+ return [ownerId, ...(config.allowedBotIds.length ? experts : experts.slice(0, config.maxExperts))];
32
+ }
33
+ const hash = (value) => createHash('sha256').update(JSON.stringify(value)).digest('hex');
34
+ const same = (a, b) => a.botId === b.botId && a.botCreatedAt === b.botCreatedAt;
35
+ const terminal = (state) => !['creating', 'running'].includes(state);
36
+ /** Work links and admission receipts only; Groups and native Sessions own execution. */
37
+ export class Supergroup {
38
+ ctx;
39
+ registry;
40
+ groups;
41
+ domain;
42
+ serial = new Serial();
43
+ active = new Map();
44
+ groupInputTails = new Map();
45
+ capabilities = new Set();
46
+ returns = new Set();
47
+ stopped = false;
48
+ offExpert;
49
+ closing;
50
+ collaboration;
51
+ releaseCollaboration;
52
+ support;
53
+ proposedContinuations = new WeakMap();
54
+ constructor(ctx, registry, groups, domain) {
55
+ this.ctx = ctx;
56
+ this.registry = registry;
57
+ this.groups = groups;
58
+ this.domain = domain;
59
+ this.support = new TaskSupport(ctx, registry, { read: id => this.read(id), agent: work => this.ownerAgent(work),
60
+ enabled: () => !this.stopped && this.config().enabled,
61
+ valid: work => !this.stopped && this.config().enabled && work.configDigest === this.configDigest(),
62
+ change: (id, expected, update) => this.serial.run(() => {
63
+ const current = this.read(id);
64
+ if (expected !== undefined && current.revision !== expected)
65
+ throw new OperationError('conflict');
66
+ const next = update(current);
67
+ return next === current ? Promise.resolve(current) : this.put(next);
68
+ }) });
69
+ }
70
+ taskSupport(id) { return this.support.view(id); }
71
+ addMaterial(input) { return this.support.add(input); }
72
+ resumeWork(input) { return this.support.resume(input); }
73
+ async pendingTasks() {
74
+ for (const bot of await this.registry.list()) {
75
+ const main = await this.registry.mainSessions?.find(bot.id);
76
+ const agent = main && this.ctx.agents.get(SessionId(main.sessionId));
77
+ const event = agent?.session.snapshotEvents().findLast(row => row.type === 'user/message' && !isNativeAmbientSource(row.data.source.kind));
78
+ if (agent && event?.type === 'user/message' && event.data.source.kind === 'user')
79
+ await this.forSession({ sessionId: agent.id, messageId: event.data.id }).catch(() => undefined);
80
+ }
81
+ const result = [];
82
+ for (const [, work] of this.domain.table('works').entries()) {
83
+ if (!['completed', 'partial'].includes(work.state))
84
+ continue;
85
+ const value = await this.support.view(work.id).catch(() => undefined);
86
+ if (value && value.blockers.some(row => ['waiting', 'ready'].includes(row.state)))
87
+ result.push(value);
88
+ }
89
+ return result;
90
+ }
91
+ async start() {
92
+ for (const [, work] of this.domain.table('works').entries()) {
93
+ const inputs = (work.groupInputs ?? []).map(input => ({ ...input,
94
+ ...(['queued', 'running', 'stored'].includes(input.state) ? { state: 'unknown', reason: 'restart-execution-unconfirmed' } : {}),
95
+ ...(input.delivery && ['prepared', 'dispatching', 'queued'].includes(input.delivery.state)
96
+ ? { delivery: { ...input.delivery, state: 'unknown', reason: 'restart-delivery-unconfirmed' } } : {}) }));
97
+ const resumes = work.resumes?.map(row => row.state === 'dispatching' ? { ...row, state: 'unknown' } : row);
98
+ const operations = work.collaboration?.operations.map(row => row.state === 'prepared' ? { ...row, state: 'unknown' } : row);
99
+ if (!terminal(work.state) || hash(inputs) !== hash(work.groupInputs ?? []) || hash(operations ?? []) !== hash(work.collaboration?.operations ?? []) || hash(resumes ?? []) !== hash(work.resumes ?? []))
100
+ await this.put({ ...work, groupInputs: inputs, ...(resumes ? { resumes } : {}), ...(operations ? { collaboration: { ...work.collaboration, operations } } : {}), ...(!terminal(work.state) ? { state: 'unknown', reason: 'restart-execution-unconfirmed' } : {}) });
101
+ }
102
+ this.offExpert = this.groups.setExpertHandler(request => this.expert(request));
103
+ this.collaboration = new ScopedCollaboration(this.ctx, this.registry, {
104
+ authorize: (...args) => this.authorizeCollaboration(...args),
105
+ reserve: scope => this.reserveCollaborationRequest(scope),
106
+ finish: (scope, result) => this.finishCollaboration(scope, result),
107
+ });
108
+ // Older source-only fixtures omit Cordis. Real Hosts always provide this service.
109
+ this.releaseCollaboration = this.ctx.provide?.('dshBotCollaboration', this.collaboration);
110
+ }
111
+ settings() {
112
+ if (this.stopped)
113
+ throw new OperationError('unavailable');
114
+ return { enabled: this.config().enabled };
115
+ }
116
+ /** Owner Remote only. Native ConfigEditor owns persistence and volatile apply. */
117
+ async configure(value) {
118
+ const input = z.strictObject({ enabled: z.boolean(), expectedEnabled: z.boolean() }).parse(value);
119
+ const before = this.config();
120
+ if (this.stopped)
121
+ throw new OperationError('unavailable');
122
+ if (before.enabled !== input.expectedEnabled)
123
+ throw new OperationError('conflict');
124
+ if (input.enabled === before.enabled)
125
+ return this.settings();
126
+ const loader = this.ctx.get('loader'), editor = this.ctx.get('configEditor');
127
+ const id = loader?.locate(this.ctx.fiber);
128
+ if (!loader || !editor || !id)
129
+ throw new OperationError('unavailable');
130
+ const entry = loader.resolve(id), ownerUid = entry.fiber?.uid;
131
+ const scope = () => {
132
+ if (this.stopped || ownerUid === undefined || loader.locate(this.ctx.fiber) !== id || loader.resolve(id) !== entry ||
133
+ entry.options.name !== 'dsh-botgroup' || entry.fiber?.uid !== ownerUid || !editor.entries().includes(entry))
134
+ throw new OperationError('conflict');
135
+ };
136
+ scope();
137
+ await editor.edit(entry, raw => {
138
+ scope();
139
+ if (this.configDigest() !== hash(before))
140
+ throw new OperationError('conflict');
141
+ const previous = raw.supergroup ?? {};
142
+ if (typeof previous !== 'object' || previous === null || Array.isArray(previous))
143
+ throw new OperationError('invalid');
144
+ if (Config(previous).enabled !== input.expectedEnabled)
145
+ throw new OperationError('conflict');
146
+ return { ...raw, supergroup: { ...previous, enabled: input.enabled } };
147
+ });
148
+ scope();
149
+ // A successful file write without the expected live Host apply is not success.
150
+ if (this.configDigest() !== hash({ ...before, enabled: input.enabled }))
151
+ throw new OperationError('conflict');
152
+ return this.settings();
153
+ }
154
+ config() { return Config(this.registry.config.supergroup); }
155
+ groupMemberLimit() { return Math.min(this.config().maxMembers, this.registry.config.groupMaxMembers ?? GROUP_MEMBER_LIMIT); }
156
+ configDigest() { return hash(this.config()); }
157
+ read(id) {
158
+ const row = this.domain.table('works').get(id);
159
+ if (!row)
160
+ throw new OperationError('not-found');
161
+ return row;
162
+ }
163
+ async put(work) {
164
+ const value = supergroupWorkSchema.parse({ ...work, revision: work.revision + 1, updatedAt: Date.now() });
165
+ await this.domain.table('works').put(value.id, value);
166
+ this.registry.invalidate();
167
+ return value;
168
+ }
169
+ /** The latest substantive input must really be human. Ambient context is not authorization. */
170
+ async human(agent) {
171
+ const header = agent.session.header, owner = getBotBinding(agent);
172
+ if (this.stopped || !owner || header.parentSession || header.origin === 'subagent' || (header.delegationDepth ?? 0) > 0
173
+ || this.ctx.agents.get(agent.id) !== agent)
174
+ throw new OperationError('approval-denied');
175
+ const bot = await this.registry.get(owner.botId), main = await this.registry.mainSessions?.find(owner.botId);
176
+ if (bot.createdAt !== owner.botCreatedAt || main?.sessionId !== agent.id)
177
+ throw new OperationError('approval-denied');
178
+ const messaging = this.ctx.get?.('dshBotMessaging');
179
+ const event = agent.session.snapshotEvents().findLast(row => row.type === 'user/message' && !isNativeAmbientSource(row.data.source.kind) &&
180
+ !messaging?.isDisplayMessage(agent, row.data));
181
+ if (event?.type !== 'user/message' || event.data.source.kind !== 'user' || event.data.content.some(block => block.type !== 'text'))
182
+ throw new OperationError('approval-denied');
183
+ const text = event.data.content.map(block => block.type === 'text' ? block.text : '').join('\n');
184
+ if (!text.trim())
185
+ throw new OperationError('invalid');
186
+ return { owner, bot, messageId: event.data.id, text };
187
+ }
188
+ async authorizeCollaboration(agent, targetId, callId, signal, argumentDigest) {
189
+ signal.throwIfAborted();
190
+ const parent = getScopedCollaborationBinding(agent);
191
+ if (parent && parent.agent !== agent)
192
+ throw new OperationError('approval-denied');
193
+ if (parent)
194
+ await parent.scope.check();
195
+ const origin = parent?.scope.origin ?? agent, human = await this.human(origin);
196
+ const id = parent?.scope.workId ?? `supergroup:${hash([origin.id, human.messageId])}`;
197
+ let runtime, operationId;
198
+ await this.serial.run(async () => {
199
+ const config = this.config(), pool = await this.pool(human.owner);
200
+ const target = pool.find(bot => bot.id === targetId);
201
+ if (!target || parent && !parent.scope.readers.some(key => key.botId === target.id && key.botCreatedAt === target.createdAt))
202
+ throw new OperationError('approval-denied');
203
+ let work = this.domain.table('works').get(id);
204
+ if (work && (work.inputMessageId !== human.messageId || ['cancelled', 'unknown'].includes(work.state) ||
205
+ work.configDigest !== this.configDigest() || Date.now() >= work.expiresAt))
206
+ throw new OperationError('approval-denied');
207
+ if (!work) {
208
+ const now = Date.now();
209
+ work = await this.put({ id, revision: 0, owner: human.owner, originSessionId: origin.id, inputMessageId: human.messageId,
210
+ inputMessageIds: [human.messageId], configDigest: this.configDigest(), readers: pool.map(bot => ({ botId: bot.id, botCreatedAt: bot.createdAt })),
211
+ createdAt: now, updatedAt: now, expiresAt: now + config.timeoutMs, turnIds: [], groupInputs: [], experts: [], state: 'running' });
212
+ }
213
+ if (work.readers.some(key => !pool.some(bot => bot.id === key.botId && bot.createdAt === key.botCreatedAt)))
214
+ throw new OperationError('approval-denied');
215
+ runtime = this.active.get(id);
216
+ if (!runtime) {
217
+ runtime = this.runtime(work, origin, await this.support.project(work, origin, human.messageId, human.text), human.messageId, new Map(pool.map(bot => [bot.id, bot.updatedAt])), new AbortController().signal);
218
+ this.active.set(id, runtime);
219
+ runtime.timer = setTimeout(() => {
220
+ if (this.read(id).state === 'completed') {
221
+ runtime.controller.abort('deadline');
222
+ runtime.detach();
223
+ this.active.delete(id);
224
+ }
225
+ else
226
+ void this.cancelCurrent(id, 'deadline').catch(() => { });
227
+ }, Math.max(1, work.expiresAt - Date.now()));
228
+ }
229
+ await runtime.authority.check();
230
+ operationId = hash([agent.session.id, callId]);
231
+ const collaboration = work.collaboration ?? { requests: 0, operations: [] };
232
+ const prior = collaboration.operations.find(row => row.id === operationId);
233
+ if (prior) {
234
+ if (prior.digest !== argumentDigest || prior.target.botId !== target.id || prior.target.botCreatedAt !== target.createdAt)
235
+ throw new OperationError('conflict');
236
+ if (prior.state !== 'prepared')
237
+ throw new OperationError('conflict');
238
+ }
239
+ else {
240
+ if (collaboration.operations.length >= config.maxRequests)
241
+ throw new OperationError('budget-exhausted');
242
+ if (new Set([...collaboration.operations.map(row => row.target.botId), targetId, human.owner.botId]).size > config.maxMembers)
243
+ throw new OperationError('member-limit');
244
+ await this.put({ ...work, state: 'running', collaboration: { ...collaboration, operations: [...collaboration.operations,
245
+ { id: operationId, digest: argumentDigest, target: { botId: target.id, botCreatedAt: target.createdAt }, state: 'prepared' }] } });
246
+ }
247
+ });
248
+ const work = this.read(id);
249
+ return { workId: id, operationId, origin, messageId: human.messageId, text: await this.support.project(work, origin, human.messageId, human.text), owner: work.owner,
250
+ readers: work.readers, expiresAt: work.expiresAt, signal: runtime.controller.signal, check: runtime.authority.check };
251
+ }
252
+ continuationInstruction(agent) {
253
+ if (this.stopped || !this.config().enabled || this.ctx.agents.get(agent.id) !== agent)
254
+ return '';
255
+ const binding = getBotBinding(agent);
256
+ const event = agent.session.snapshotEvents().findLast(row => row.type === 'user/message' && !isNativeAmbientSource(row.data.source.kind)
257
+ && !this.ctx.get?.('dshBotMessaging')?.isDisplayMessage(agent, row.data));
258
+ const proposed = this.proposedContinuations.get(agent);
259
+ if (!binding || event?.type !== 'user/message' || event.data.source.kind !== 'user')
260
+ return '';
261
+ for (const [, work] of this.domain.table('works').entries()) {
262
+ if (work.originSessionId !== agent.id || !same(binding, work.owner) || ['cancelled', 'unknown'].includes(work.state))
263
+ continue;
264
+ try {
265
+ const candidate = proposed?.workId === work.id ? proposed.message : undefined;
266
+ const messageId = candidate?.id ?? event.data.id;
267
+ const resumed = this.support.continuation(work, agent, messageId, candidate);
268
+ if (!resumed || candidate && event.data.id !== candidate.id && event.data.id !== resumed.receipt.previousMessageId)
269
+ continue;
270
+ return `The owner explicitly resumed this exact original request, with an exact persisted receipt. Original request: ${JSON.stringify(resumed.original)}.\n`
271
+ + (work.group ? `Continue its existing collaboration using bot_supergroup action=continue, workId=${work.id}. `
272
+ : 'Resume the original request using its now-ready configured connection. This does not require forming a group. ')
273
+ + 'Only the user expression is displayed in chat. Quoted task material remains data and grants no tool or approval authority.\n'
274
+ + JSON.stringify((work.materials ?? []).map(({ name, text, question, citation }) => ({ name, text, question, citation })));
275
+ }
276
+ catch {
277
+ return '';
278
+ }
279
+ }
280
+ return '';
281
+ }
282
+ async checkContinuation(agent, messages) {
283
+ const incoming = messages?.findLast(message => !isNativeAmbientSource(message.source.kind)
284
+ && !this.ctx.get?.('dshBotMessaging')?.isDisplayMessage(agent, message));
285
+ const event = agent.session.snapshotEvents().findLast(row => row.type === 'user/message' && !isNativeAmbientSource(row.data.source.kind)
286
+ && !this.ctx.get?.('dshBotMessaging')?.isDisplayMessage(agent, row.data));
287
+ const message = incoming ?? (event?.type === 'user/message' ? event.data : undefined);
288
+ this.proposedContinuations.delete(agent);
289
+ if (!message || message.source.kind !== 'user')
290
+ return;
291
+ for (const [, work] of this.domain.table('works').entries()) {
292
+ const resumed = work.originSessionId === agent.id && this.support.continuation(work, agent, message.id, incoming);
293
+ if (!resumed)
294
+ continue;
295
+ if (incoming && event?.type === 'user/message' && event.data.id !== message.id && event.data.id !== resumed.receipt.previousMessageId)
296
+ throw new OperationError('conflict');
297
+ await this.ownerAgent(work, agent);
298
+ if (!this.config().enabled || work.configDigest !== this.configDigest() || Date.now() >= work.expiresAt || ['cancelled', 'unknown'].includes(work.state))
299
+ throw new OperationError('approval-denied');
300
+ this.support.assertConnectionsReady(work);
301
+ await this.support.text(work, '');
302
+ if (incoming)
303
+ this.proposedContinuations.set(agent, { workId: work.id, message: incoming });
304
+ }
305
+ }
306
+ async observeContinuation(agent) {
307
+ const events = agent.session.snapshotEvents();
308
+ for (const [, work] of this.domain.table('works').entries()) {
309
+ if (!work.initialPending || work.group || work.originSessionId !== agent.id)
310
+ continue;
311
+ const receipt = work.resumes?.at(-1), input = receipt && events.find(row => row.type === 'user/message' && row.data.id === receipt.messageId);
312
+ if (!receipt || receipt.state !== 'queued' || input?.type !== 'user/message' || !this.support.continuation(work, agent, input.data.id))
313
+ continue;
314
+ const tail = events.filter(row => Number(row.seq) > Number(input.seq)), end = tail.findLast(row => row.type === 'turn/end');
315
+ if (end?.type !== 'turn/end')
316
+ continue;
317
+ const answer = tail.findLast(row => row.type === 'assistant/message' && row.data.turn === end.data.turn);
318
+ const complete = end.data.reason.kind === 'completed' && answer?.type === 'assistant/message'
319
+ && !tail.some(row => row.type === 'tool/result' && row.data.message.isError);
320
+ await this.serial.run(async () => {
321
+ const current = this.read(work.id);
322
+ if (!current.initialPending || current.resumes?.at(-1)?.messageId !== receipt.messageId || ['cancelled', 'unknown'].includes(current.state))
323
+ return;
324
+ const state = complete ? 'completed' : 'partial';
325
+ if (current.state !== state)
326
+ await this.put({ ...current, state });
327
+ });
328
+ }
329
+ }
330
+ async reserveCollaborationRequest(scope) {
331
+ await scope.check();
332
+ await this.reserveWorkRequest(scope.workId);
333
+ }
334
+ async reserveWorkRequest(id) {
335
+ await this.serial.run(async () => {
336
+ const work = this.read(id), collaboration = work.collaboration ?? { requests: 0, operations: [] };
337
+ if (this.stopped || !this.config().enabled || ['cancelled', 'unknown'].includes(work.state) || Date.now() >= work.expiresAt ||
338
+ work.configDigest !== this.configDigest())
339
+ throw new OperationError('approval-denied');
340
+ if (collaboration.requests >= this.config().maxRequests)
341
+ throw new OperationError('budget-exhausted');
342
+ await this.put({ ...work, collaboration: { ...collaboration, requests: collaboration.requests + 1 } });
343
+ });
344
+ }
345
+ async finishCollaboration(scope, result) {
346
+ await this.serial.run(async () => {
347
+ const work = this.read(scope.workId), collaboration = work.collaboration;
348
+ if (!collaboration)
349
+ throw new OperationError('conflict');
350
+ const operations = collaboration.operations.map(row => row.id !== scope.operationId || row.state !== 'prepared' ? row : {
351
+ ...row, state: work.state === 'cancelled' || result.status === 'aborted' ? 'cancelled'
352
+ : result.status === 'unknown' ? 'unknown' : result.status === 'completed' ? 'completed' : 'failed',
353
+ childId: result.childId, status: result.status, resultDigest: hash(result.result),
354
+ ...(result.errorCode ? { errorCode: result.errorCode } : {}), ...(result.diagnostic ? { diagnostic: result.diagnostic } : {}),
355
+ });
356
+ const state = ['cancelled', 'unknown'].includes(work.state) || work.group ? work.state
357
+ : operations.some(row => row.state === 'prepared') ? 'running' : operations.some(row => row.state === 'unknown') ? 'unknown'
358
+ : operations.every(row => row.state === 'completed') ? 'completed' : 'partial';
359
+ await this.put({ ...work, state, ...(result.errorCode ? { reason: result.errorCode } : {}), collaboration: { ...collaboration, operations } });
360
+ });
361
+ }
362
+ async pool(owner) {
363
+ const config = this.config();
364
+ if (!config.enabled)
365
+ throw new OperationError('approval-denied');
366
+ const bots = await this.registry.list(), available = new Map(bots.map(bot => [bot.id, bot]));
367
+ const ids = supergroupCandidateIds(owner.botId, bots, config);
368
+ const status = await this.registry.status();
369
+ return ids.map(id => {
370
+ const bot = available.get(id);
371
+ if (!bot || status.find(row => row.id === id)?.preset.state !== 'ok')
372
+ throw new OperationError('unavailable');
373
+ return bot;
374
+ });
375
+ }
376
+ runtime(work, agent, text, messageId, revisions, signal, groupInput) {
377
+ const controller = new AbortController();
378
+ const abort = () => controller.abort(signal.reason);
379
+ signal.addEventListener('abort', abort, { once: true });
380
+ if (signal.aborted)
381
+ abort();
382
+ controller.signal.addEventListener('abort', () => signal.removeEventListener('abort', abort), { once: true });
383
+ const check = async () => {
384
+ controller.signal.throwIfAborted();
385
+ const current = this.read(work.id);
386
+ const input = groupInput ? { owner: work.owner, messageId } : await this.human(agent);
387
+ if (groupInput) {
388
+ await this.ownerAgent(current, agent);
389
+ const receipt = current.groupInputs.find(row => row.messageId === groupInput.messageId);
390
+ const event = groupInput.root.session.snapshotEvents().find(row => row.type === 'user/message' && row.data.id === groupInput.messageId);
391
+ if (!receipt || !['queued', 'running', 'completed'].includes(receipt.state) || receipt.seq !== groupInput.seq ||
392
+ event?.type !== 'user/message' || hash(event.data.content) !== groupInput.digest || event.data.source.kind !== 'user' || hash({ group: current.group, workId: current.id, expectedRevision: receipt.expectedRevision,
393
+ text: event.data.content.map(block => block.type === 'text' ? block.text : '').join('\n'), memberIds: receipt.memberIds ?? [], replyTo: receipt.replyTo }) !== receipt.digest)
394
+ throw new OperationError('approval-denied');
395
+ }
396
+ if (this.stopped || !this.config().enabled || current.state === 'cancelled' || current.state === 'unknown' ||
397
+ current.configDigest !== this.configDigest() || Date.now() >= current.expiresAt || input.messageId !== messageId ||
398
+ !same(input.owner, current.owner))
399
+ throw new OperationError('approval-denied');
400
+ for (const key of current.readers) {
401
+ const bot = await this.registry.get(key.botId);
402
+ if (bot.createdAt !== key.botCreatedAt || bot.updatedAt !== revisions.get(key.botId))
403
+ throw new OperationError('conflict');
404
+ }
405
+ await this.support.text(current, '');
406
+ controller.signal.throwIfAborted();
407
+ };
408
+ return { controller, text, revisions, turnIds: [], detach: () => signal.removeEventListener('abort', abort), authority: { workId: work.id, origin: agent, messageId, ...(groupInput ? { groupInput } : {}), owner: work.owner,
409
+ ...((work.materials?.length || work.resumes?.some(row => row.messageId === messageId)) ? { projectInput: (value) => this.support.project(this.read(work.id), agent, messageId, value) } : {}),
410
+ readers: work.readers, expiresAt: work.expiresAt, check, maxRequests: this.config().maxRequests,
411
+ reserveRequest: () => this.reserveWorkRequest(work.id), requestsUsed: () => this.read(work.id).collaboration?.requests ?? 0 } };
412
+ }
413
+ chosen(agent, workId) {
414
+ const binding = getBotBinding(agent);
415
+ const rows = [...this.domain.table('works').entries()].map(([, row]) => row)
416
+ .filter(row => row.originSessionId === agent.id && binding && same(binding, row.owner))
417
+ .sort((a, b) => b.updatedAt - a.updatedAt || b.id.localeCompare(a.id));
418
+ const row = workId ? rows.find(row => row.id === workId) : rows[0];
419
+ if (!row)
420
+ throw new OperationError('not-found');
421
+ return row;
422
+ }
423
+ async invoke(agent, input, signal) {
424
+ signal.throwIfAborted();
425
+ if (input.action === 'status') {
426
+ const work = this.chosen(agent, input.workId);
427
+ // Status is control metadata. Transcript bodies only leave through result().
428
+ return { workId: work.id, state: work.state, revision: work.revision, turnIds: work.turnIds,
429
+ experts: work.experts.map(({ botId, state }) => ({ botId, state })) };
430
+ }
431
+ if (input.action === 'cancel') {
432
+ const work = this.chosen(agent, input.workId);
433
+ await this.cancel(work.id, work.revision);
434
+ return { workId: work.id, state: this.read(work.id).state };
435
+ }
436
+ const human = await this.human(agent);
437
+ const resumed = [...this.domain.table('works').entries()].map(([, work]) => work).find(work => work.originSessionId === agent.id
438
+ && this.support.continuation(work, agent, human.messageId));
439
+ if (resumed && input.action === 'start' && resumed.group)
440
+ input = { action: 'continue', workId: resumed.id };
441
+ if (input.action === 'continue') {
442
+ const group = this.chosen(agent, input.workId).group;
443
+ if (group && (await this.groups.view(group)).members.filter(member => member.removedAt === undefined).length > this.groupMemberLimit())
444
+ throw new OperationError('member-limit');
445
+ }
446
+ let runtime, work;
447
+ await this.serial.run(async () => {
448
+ if (input.action === 'start') {
449
+ const id = resumed?.id ?? `supergroup:${hash([agent.id, human.messageId])}`;
450
+ const prior = resumed ?? [...this.domain.table('works').entries()].map(([, row]) => row)
451
+ .find(row => row.originSessionId === agent.id && row.inputMessageIds.includes(human.messageId));
452
+ if (prior?.group || prior && ['cancelled', 'unknown'].includes(prior.state)) {
453
+ work = prior;
454
+ runtime = this.active.get(prior.id);
455
+ return;
456
+ }
457
+ if (prior?.collaboration?.operations.some(row => row.state === 'prepared'))
458
+ throw new OperationError('conflict');
459
+ const config = this.config(), pool = await this.pool(human.owner);
460
+ if (input.memberIds.length > this.groupMemberLimit())
461
+ throw new OperationError('member-limit');
462
+ if (new Set(input.memberIds).size !== input.memberIds.length ||
463
+ input.memberIds.some(id => !pool.some(bot => bot.id === id)))
464
+ throw new OperationError('approval-denied');
465
+ if (prior && input.memberIds.some(id => !prior.readers.some(reader => reader.botId === id)))
466
+ throw new OperationError('approval-denied');
467
+ const now = Date.now();
468
+ work = prior ?? await this.put({ id, revision: 0, owner: human.owner, originSessionId: agent.id,
469
+ inputMessageId: human.messageId, inputMessageIds: [human.messageId], configDigest: this.configDigest(),
470
+ readers: pool.map(bot => ({ botId: bot.id, botCreatedAt: bot.createdAt })), createdAt: now, updatedAt: now,
471
+ expiresAt: now + config.timeoutMs, turnIds: [], groupInputs: [], experts: [], state: 'creating' });
472
+ if (work.initialPending)
473
+ work = await this.put({ ...work, initialPending: false, state: 'creating',
474
+ expiresAt: Date.now() + config.timeoutMs, inputMessageIds: [...new Set([...work.inputMessageIds, human.messageId])] });
475
+ const existing = this.active.get(work.id);
476
+ if (existing) {
477
+ clearTimeout(existing.timer);
478
+ existing.controller.abort('group-handoff');
479
+ existing.detach();
480
+ }
481
+ runtime = this.runtime(work, agent, await this.support.project(work, agent, human.messageId, human.text), human.messageId, new Map(pool.map(bot => [bot.id, bot.updatedAt])), signal);
482
+ }
483
+ else {
484
+ work = this.chosen(agent, input.workId);
485
+ if (work.inputMessageIds.includes(human.messageId)) {
486
+ runtime = this.active.get(work.id);
487
+ return;
488
+ }
489
+ if (work.groupInputs.some(row => ['queued', 'running'].includes(row.state)) || !['completed', 'partial'].includes(work.state) || !work.group || work.configDigest !== this.configDigest())
490
+ throw new OperationError('conflict');
491
+ const pool = await this.pool(human.owner);
492
+ if (work.readers.some(key => !pool.some(bot => bot.id === key.botId && bot.createdAt === key.botCreatedAt)))
493
+ throw new OperationError('approval-denied');
494
+ work = await this.put({ ...work, state: 'running', reason: undefined, expiresAt: Date.now() + this.config().timeoutMs,
495
+ inputMessageIds: [...work.inputMessageIds, human.messageId] });
496
+ runtime = this.runtime(work, agent, await this.support.project(work, agent, human.messageId, human.text), human.messageId, new Map(pool.map(bot => [bot.id, bot.updatedAt])), signal);
497
+ }
498
+ this.active.set(work.id, runtime);
499
+ const id = work.id;
500
+ runtime.timer = setTimeout(() => { void this.cancelCurrent(id, 'deadline').catch(() => { }); }, Math.max(1, work.expiresAt - Date.now()));
501
+ runtime.task = this.execute(work, runtime, input.action === 'start' ? input.memberIds : undefined)
502
+ .finally(() => { clearTimeout(runtime.timer); runtime.detach(); if (this.active.get(id) === runtime)
503
+ this.active.delete(id); });
504
+ void runtime.task.catch(() => { });
505
+ });
506
+ if (runtime?.task)
507
+ return runtime.task;
508
+ // A persisted/unknown operation is never automatically replayed or re-published.
509
+ return { workId: work.id, state: work.state, resumed: false };
510
+ }
511
+ async execute(initial, runtime, memberIds) {
512
+ try {
513
+ await runtime.authority.check();
514
+ let work = this.read(initial.id);
515
+ if (!work.group) {
516
+ const group = await this.groups.createSupergroup({ operationId: work.id, name: runtime.text.trim().slice(0, 64),
517
+ ...(runtime.authority.origin.session.header.cwd ? { cwd: runtime.authority.origin.session.header.cwd } : {}),
518
+ members: memberIds.map(id => work.readers.find(key => key.botId === id)), mode: 'natural', historyConfirmed: true }, runtime.authority);
519
+ work = await this.serial.run(() => this.put({ ...this.read(work.id), group: groupKey(group), state: 'running' }));
520
+ }
521
+ else
522
+ await this.groups.refreshSupergroupAuthority(work.group, runtime.authority);
523
+ const key = work.group;
524
+ let view = await this.groups.view(key);
525
+ runtime.roster = view.members.filter(member => member.removedAt === undefined).map(member => member.bot);
526
+ if (runtime.roster.length > this.groupMemberLimit())
527
+ throw new OperationError('member-limit');
528
+ let selected = runtime.memberIds?.length ? runtime.memberIds : view.members.filter(member => member.enabled && member.removedAt === undefined && (!memberIds || memberIds.includes(member.bot.botId))).map(member => member.id);
529
+ for (;;) {
530
+ await runtime.authority.check();
531
+ if (view.deliveries.length + selected.length > this.config().maxRequests)
532
+ throw new OperationError('approval-denied');
533
+ const turn = await this.groups.sendSupergroup(key, { operationId: `${work.id}:turn:${runtime.authority.messageId}:${runtime.turnIds.length}`,
534
+ expectedMembershipRevision: view.group.membershipRevision, text: runtime.text.trim(), memberIds: selected, ...(runtime.replyTo ? { replyTo: runtime.replyTo } : {}) }, runtime.authority);
535
+ runtime.turnIds.push(turn.id);
536
+ work = await this.serial.run(() => this.put({ ...this.read(work.id), state: 'running', turnIds: [...this.read(work.id).turnIds, turn.id] }));
537
+ await this.groups.waitForTurn(turn.id);
538
+ await runtime.authority.check();
539
+ view = await this.groups.view(key);
540
+ const pending = this.read(work.id).experts.find(expert => expert.state === 'pending');
541
+ if (!pending)
542
+ break;
543
+ const existing = view.members.filter(member => member.removedAt === undefined);
544
+ const target = work.readers.find(bot => bot.botId === pending.botId);
545
+ const alreadyMember = target && existing.find(member => same(member.bot, target));
546
+ if (!target)
547
+ throw new OperationError('approval-denied');
548
+ if (!alreadyMember && existing.length >= this.groupMemberLimit())
549
+ throw new OperationError('member-limit');
550
+ if (!alreadyMember) {
551
+ await this.groups.editSupergroup(key, { expectedRevision: view.group.revision, expectedMembershipRevision: view.group.membershipRevision,
552
+ name: view.group.name, mode: view.group.mode, members: [...existing.map(member => member.bot), target], historyConfirmed: true }, runtime.authority);
553
+ view = await this.groups.view(key);
554
+ runtime.roster = view.members.filter(member => member.removedAt === undefined).map(member => member.bot);
555
+ }
556
+ const expert = view.members.find(member => same(member.bot, target) && member.enabled && member.removedAt === undefined);
557
+ if (!expert)
558
+ throw new OperationError('recovery-needed');
559
+ work = await this.serial.run(() => this.put({ ...this.read(work.id), experts: this.read(work.id).experts.map(row => row.botId === pending.botId && row.state === 'pending' ? { ...row, memberId: expert.id, state: 'invited' } : row) }));
560
+ selected = [expert.id];
561
+ }
562
+ const facts = view.turns.filter(turn => this.read(work.id).turnIds.includes(turn.id));
563
+ const settled = facts.length > 0 && facts.every(turn => {
564
+ const deliveries = view.deliveries.filter(delivery => delivery.turnId === turn.id);
565
+ return ['completed', 'idle'].includes(turn.state) && deliveries.length > 0
566
+ && deliveries.every(delivery => ['completed', 'skipped'].includes(delivery.state))
567
+ && deliveries.some(delivery => delivery.state === 'completed');
568
+ });
569
+ work = await this.serial.run(() => this.put({ ...this.read(work.id), state: settled ? 'completed' : 'partial' }));
570
+ const result = await this.result(work, runtime, view);
571
+ if (runtime.inputOperationId)
572
+ await this.serial.run(() => this.updateInput(work.id, runtime.inputOperationId, row => ({ ...row, state: 'completed' })));
573
+ return result;
574
+ }
575
+ catch (error) {
576
+ runtime.controller.abort('execution-or-delivery-unconfirmed');
577
+ const current = this.read(initial.id);
578
+ if (runtime.inputOperationId)
579
+ await this.serial.run(() => this.updateInput(initial.id, runtime.inputOperationId, row => ({ ...row, state: current.state === 'cancelled' ? 'cancelled' : 'unknown', reason: 'execution-or-delivery-unconfirmed' })));
580
+ if (current.state !== 'cancelled')
581
+ await this.serial.run(() => this.put({ ...this.read(initial.id), state: 'unknown', reason: 'execution-or-delivery-unconfirmed' }));
582
+ if (current.group) {
583
+ const facts = await this.groups.view(current.group).catch(() => undefined);
584
+ for (const turn of facts?.turns ?? [])
585
+ if (current.turnIds.includes(turn.id) && ['accepted', 'running'].includes(turn.state))
586
+ await this.groups.cancel(current.group, turn.id, turn.revision).catch(() => { });
587
+ await this.groups.drain(current.group).catch(() => { });
588
+ }
589
+ return { workId: initial.id, state: this.read(initial.id).state, reason: 'Work or delivery could not be confirmed. Inspect the process before retrying.' };
590
+ }
591
+ }
592
+ async result(work, runtime, view) {
593
+ const flow = outlets(this.registry);
594
+ if (!flow)
595
+ throw new OperationError('unavailable');
596
+ await runtime.authority.check();
597
+ const version = `${work.id}:${runtime.authority.messageId}`;
598
+ if (this.returns.has(version))
599
+ return { workId: work.id, state: work.state, duplicate: true };
600
+ const payload = { workId: work.id, state: work.state, group: work.group, turnIds: work.turnIds,
601
+ results: view.messages.filter(message => message.authorKind === 'bot' && work.turnIds.includes(message.turnId)) };
602
+ const envelope = flow.draft('group-result', work.owner, view.group.rootSessionId, version, { kind: 'bot', bot: work.owner }, JSON.stringify(payload));
603
+ const receipt = await flow.admit(envelope, undefined, runtime.controller.signal);
604
+ await flow.inherit(runtime.authority.origin.id, envelope.label);
605
+ if (runtime.inputOperationId)
606
+ return this.deliverGroupResult(work, runtime, payload, receipt);
607
+ return flow.dispatch(receipt, () => { this.returns.add(version); return payload; }, runtime.controller.signal, runtime.authority.check);
608
+ }
609
+ async expert(request) {
610
+ return this.serial.run(async () => {
611
+ const work = this.read(request.workId), runtime = this.active.get(work.id);
612
+ if (!runtime || !work.group || work.group.groupId !== request.group.groupId || work.group.groupCreatedAt !== request.group.groupCreatedAt || work.state !== 'running')
613
+ throw new OperationError('approval-denied');
614
+ await runtime.authority.check();
615
+ const digest = hash([request.botId, request.question]), id = `supergroup-expert:${hash([work.id, request.agent.id, request.callId])}`;
616
+ const prior = work.experts.find(expert => expert.id === id);
617
+ if (prior) {
618
+ if (prior.digest !== digest)
619
+ throw new OperationError('conflict');
620
+ return { status: prior.state, requestId: id };
621
+ }
622
+ if (!work.readers.some(reader => reader.botId === request.botId) || work.experts.length >= this.config().maxExperts)
623
+ throw new OperationError('approval-denied');
624
+ const roster = runtime.roster;
625
+ if (!roster)
626
+ throw new OperationError('unavailable');
627
+ const reserved = new Set([...roster.map(bot => bot.botId),
628
+ ...work.experts.filter(expert => expert.state === 'pending').map(expert => expert.botId), request.botId]);
629
+ if (!roster.some(bot => bot.botId === request.botId) && reserved.size > this.groupMemberLimit())
630
+ throw new OperationError('member-limit');
631
+ await this.put({ ...work, experts: [...work.experts, { id, digest, botId: request.botId,
632
+ memberId: '', turnId: request.binding.turnId, childSessionId: request.agent.id, state: 'pending' }] });
633
+ return { status: 'accepted', requestId: id };
634
+ });
635
+ }
636
+ async ownerAgent(work, expected) {
637
+ const bot = await this.registry.get(work.owner.botId), main = await this.registry.mainSessions?.find(work.owner.botId);
638
+ const agent = main && this.ctx.agents.get(SessionId(main.sessionId));
639
+ if (this.stopped || bot.createdAt !== work.owner.botCreatedAt || main?.sessionId !== work.originSessionId ||
640
+ !agent || expected && agent !== expected || !getBotBinding(agent) || !same(getBotBinding(agent), work.owner) ||
641
+ agent.session.header.parentSession || agent.session.header.origin === 'subagent')
642
+ throw new OperationError('unavailable');
643
+ return agent;
644
+ }
645
+ updateInput(id, operationId, change) {
646
+ const work = this.read(id);
647
+ return this.put({ ...work, groupInputs: work.groupInputs.map(row => row.operationId === operationId ? change(row) : row) });
648
+ }
649
+ async reconcileDelivery(work) {
650
+ // Reconcile exact native input and answer references; followup() returning void is never delivery proof.
651
+ const agent = this.ctx.agents.get(SessionId(work.originSessionId));
652
+ if (agent && same(getBotBinding(agent) ?? { botId: '', botCreatedAt: -1 }, work.owner)) {
653
+ const events = agent.session.snapshotEvents();
654
+ const inputs = work.groupInputs.map(row => {
655
+ const delivery = row.delivery;
656
+ if (!delivery || ['delivered', 'cancelled', 'undeliverable'].includes(delivery.state))
657
+ return row;
658
+ const input = events.find(event => event.type === 'user/message' && event.data.id === delivery.messageId &&
659
+ event.data.source.kind === 'dsh-bot-supergroup-result' && event.data.source.deliveryId === delivery.id && hash(event.data) === delivery.digest);
660
+ if (!input)
661
+ return row;
662
+ const tail = events.filter(event => Number(event.seq) > Number(input.seq));
663
+ const nextInput = tail.find(event => event.type === 'user/message' && !['runtime-context', 'time-context', 'agent-instructions', 'tmux-context'].includes(event.data.source.kind));
664
+ const answer = tail.find(event => event.type === 'assistant/message' && (!nextInput || Number(event.seq) < Number(nextInput.seq)));
665
+ return { ...row, delivery: { ...delivery, state: answer ? 'delivered' : 'queued',
666
+ inputSeq: Number(input.seq), ...(answer?.type === 'assistant/message' ? { answerMessageId: answer.data.message.id } : {}) } };
667
+ });
668
+ if (hash(inputs) !== hash(work.groupInputs))
669
+ work = await this.put({ ...work, groupInputs: inputs });
670
+ }
671
+ return work;
672
+ }
673
+ async project(id) {
674
+ // Groups may invoke the expert handler while holding its own queue. Never
675
+ // acquire that queue while holding the work queue: expert admission needs it.
676
+ const work = await this.serial.run(() => this.reconcileDelivery(this.read(id)));
677
+ return { work, ...(work.group ? { group: await this.groups.view(work.group) } : {}) };
678
+ }
679
+ async catalog(input = {}) {
680
+ const rows = [...this.domain.table('works').entries()].map(([, row]) => row)
681
+ .filter(row => (!input.bot || same(row.owner, input.bot)) && (!input.group || row.group?.groupId === input.group.groupId && row.group.groupCreatedAt === input.group.groupCreatedAt))
682
+ .sort((a, b) => b.updatedAt - a.updatedAt || a.id.localeCompare(b.id));
683
+ const result = [];
684
+ for (const row of rows) {
685
+ const owner = await this.registry.get(row.owner.botId).catch(() => undefined);
686
+ if (!owner || owner.createdAt !== row.owner.botCreatedAt)
687
+ continue;
688
+ result.push(await this.project(row.id));
689
+ }
690
+ return result;
691
+ }
692
+ async byGroup(group) {
693
+ return (await this.catalog({ group }))[0] ?? null;
694
+ }
695
+ /** Owner Remote only. Persist the original group human event even when its revision conflicts. */
696
+ async sendGroupInput(value) {
697
+ const input = supergroupSendGroupInputSchema.parse(value);
698
+ const linked = this.read(input.workId);
699
+ if (!linked.group || JSON.stringify(linked.group) !== JSON.stringify(input.group))
700
+ throw new OperationError('approval-denied');
701
+ // Never hold the work queue while reading Groups: an in-flight expert may
702
+ // hold the Groups queue while recording its request in this work.
703
+ const view = await this.groups.view(input.group);
704
+ let workId = input.workId, receipt;
705
+ await this.serial.run(async () => {
706
+ let work = this.read(input.workId);
707
+ if (this.stopped || !this.config().enabled || work.configDigest !== this.configDigest() ||
708
+ !work.group || JSON.stringify(work.group) !== JSON.stringify(input.group))
709
+ throw new OperationError('approval-denied');
710
+ const digest = hash({ group: input.group, workId: input.workId, expectedRevision: input.expectedRevision,
711
+ text: input.text, memberIds: input.memberIds ?? [], replyTo: input.replyTo });
712
+ const prior = work.groupInputs.find(row => row.operationId === input.operationId);
713
+ if (prior) {
714
+ if (prior.digest !== digest)
715
+ throw new OperationError('conflict');
716
+ receipt = prior;
717
+ return;
718
+ }
719
+ if (view.members.filter(member => member.removedAt === undefined).length > this.groupMemberLimit())
720
+ throw new OperationError('member-limit');
721
+ if (view.group.archived || view.group.state !== 'ready' || view.group.supergroup?.workId !== work.id)
722
+ throw new OperationError('approval-denied');
723
+ if (input.memberIds && (new Set(input.memberIds).size !== input.memberIds.length || input.memberIds.some(id => !view.members.some(member => member.id === id && member.enabled && member.removedAt === undefined))))
724
+ throw new OperationError('invalid');
725
+ if (input.replyTo && !view.messages.some(message => message.id === input.replyTo))
726
+ throw new OperationError('invalid');
727
+ const root = this.ctx.agents.get(SessionId(view.group.rootSessionId));
728
+ if (!root)
729
+ throw new OperationError('unavailable');
730
+ const flow = outlets(this.registry);
731
+ if (!flow)
732
+ throw new OperationError('unavailable');
733
+ // Preserve the existing audience intersection; this is a fresh owner text, never private main history.
734
+ await flow.inherit(root.id, { readers: work.readers, originTrust: 'candidate', sourceVersions: [], restrictions: [], grants: [] });
735
+ const message = createUserMessage({ source: { kind: 'user', group: input.group, supergroupWorkId: work.id,
736
+ operationId: input.operationId, ...(input.replyTo ? { replyTo: input.replyTo } : {}) }, content: [{ type: 'text', text: input.text }] });
737
+ const conflict = work.revision !== input.expectedRevision || !['running', 'completed', 'partial'].includes(work.state);
738
+ receipt = { operationId: input.operationId, digest, messageId: message.id, expectedRevision: input.expectedRevision,
739
+ state: 'stored', ...(input.memberIds ? { memberIds: input.memberIds } : {}), ...(input.replyTo ? { replyTo: input.replyTo } : {}) };
740
+ const envelope = flow.draft('group-input', work.owner, root.id, `owner:${input.operationId}`, { kind: 'group', groupId: input.group.groupId, groupCreatedAt: input.group.groupCreatedAt, members: work.readers }, JSON.stringify(message));
741
+ const flowId = await flow.admit(envelope);
742
+ work = await flow.persist(flowId, () => this.put({ ...work, groupInputs: [...work.groupInputs, receipt] }));
743
+ try {
744
+ const event = await flow.dispatch(flowId, () => root.session.append('user/message', message, { surfaceOp: 'append' }));
745
+ if (!await this.ctx.sessions.flush(root.session))
746
+ throw new OperationError('recovery-needed');
747
+ receipt = { ...receipt, seq: Number(event.seq), state: conflict ? 'conflict' : 'queued',
748
+ ...(conflict ? { reason: 'work-revision-conflict' } : { acceptedRevision: work.revision + 1 }) };
749
+ work = await this.updateInput(work.id, input.operationId, () => receipt);
750
+ }
751
+ catch {
752
+ receipt = { ...receipt, state: 'unknown', reason: 'input-storage-unconfirmed' };
753
+ await this.updateInput(work.id, input.operationId, () => receipt);
754
+ return;
755
+ }
756
+ workId = work.id;
757
+ if (!conflict)
758
+ this.scheduleGroupInput(work.id, input.operationId);
759
+ });
760
+ return { view: await this.project(workId), receipt };
761
+ }
762
+ scheduleGroupInput(id, operationId) {
763
+ const previous = this.groupInputTails.get(id) ?? this.active.get(id)?.task ?? Promise.resolve();
764
+ const task = previous.catch(() => { }).then(async () => {
765
+ let runtime, work;
766
+ const snapshot = this.read(id);
767
+ const view = snapshot.group ? await this.groups.view(snapshot.group).catch(() => undefined) : undefined;
768
+ await this.serial.run(async () => {
769
+ work = this.read(id);
770
+ const row = work.groupInputs.find(input => input.operationId === operationId);
771
+ if (!row || row.state !== 'queued')
772
+ return;
773
+ if (this.stopped || !this.config().enabled || !['completed', 'partial', 'running'].includes(work.state) || !work.group) {
774
+ await this.updateInput(id, operationId, input => ({ ...input, state: work.state === 'cancelled' ? 'cancelled' : 'unknown', reason: 'work-not-resumable' }));
775
+ return;
776
+ }
777
+ try {
778
+ if (!view || view.group.id !== work.group.groupId || view.group.createdAt !== work.group.groupCreatedAt)
779
+ throw new OperationError('approval-denied');
780
+ const agent = await this.ownerAgent(work);
781
+ const root = this.ctx.agents.get(SessionId(view.group.rootSessionId));
782
+ const event = root?.session.snapshotEvents().find(event => event.type === 'user/message' && event.data.id === row.messageId);
783
+ if (!root || event?.type !== 'user/message' || row.seq !== Number(event.seq))
784
+ throw new OperationError('approval-denied');
785
+ const pool = await this.pool(work.owner);
786
+ if (work.readers.some(reader => !pool.some(bot => bot.id === reader.botId && bot.createdAt === reader.botCreatedAt)))
787
+ throw new OperationError('approval-denied');
788
+ work = await this.put({ ...work, state: 'running', reason: undefined, expiresAt: Date.now() + this.config().timeoutMs,
789
+ inputMessageIds: [...work.inputMessageIds, row.messageId], groupInputs: work.groupInputs.map(input => input.operationId === operationId ? { ...input, state: 'running' } : input) });
790
+ runtime = this.runtime(work, agent, await this.support.text(work, event.data.content.map(block => block.type === 'text' ? block.text : '').join('\n')), row.messageId, new Map(pool.map(bot => [bot.id, bot.updatedAt])), new AbortController().signal, { root, group: work.group, messageId: row.messageId, seq: row.seq, digest: hash(event.data.content), originMainMessageId: work.inputMessageId });
791
+ runtime.inputOperationId = operationId;
792
+ runtime.memberIds = row.memberIds;
793
+ runtime.replyTo = row.replyTo;
794
+ this.active.set(id, runtime);
795
+ const selected = runtime;
796
+ selected.timer = setTimeout(() => { void this.cancelCurrent(id, 'deadline').catch(() => { }); }, this.config().timeoutMs);
797
+ selected.task = this.execute(work, selected).finally(() => {
798
+ clearTimeout(selected.timer);
799
+ selected.detach();
800
+ if (this.active.get(id) === selected)
801
+ this.active.delete(id);
802
+ });
803
+ }
804
+ catch {
805
+ await this.updateInput(id, operationId, input => ({ ...input, state: 'unknown', reason: 'owner-or-input-unavailable' }));
806
+ }
807
+ });
808
+ if (runtime?.task)
809
+ await runtime.task;
810
+ });
811
+ // Serialize all pending group inputs, including inputs accepted before the first queued task starts.
812
+ this.groupInputTails.set(id, task);
813
+ void task.finally(() => { if (this.groupInputTails.get(id) === task)
814
+ this.groupInputTails.delete(id); }).catch(() => { });
815
+ }
816
+ async deliverGroupResult(work, runtime, payload, flowId) {
817
+ const operationId = runtime.inputOperationId, row = this.read(work.id).groupInputs.find(input => input.operationId === operationId);
818
+ if (row.delivery)
819
+ return { workId: work.id, state: work.state, delivery: row.delivery, duplicate: true };
820
+ const version = `${work.id}:${row.messageId}`, id = `supergroup-delivery:${hash([version, work.owner, work.originSessionId])}`;
821
+ const message = createUserMessage({ source: { kind: 'dsh-bot-supergroup-result', deliveryId: id,
822
+ workId: work.id, group: work.group, originSessionId: runtime.authority.groupInput.root.id,
823
+ originMessageId: row.messageId, originSeq: row.seq, resultVersion: version },
824
+ content: [{ type: 'text', text: JSON.stringify(payload) }] });
825
+ await this.serial.run(() => this.updateInput(work.id, operationId, input => ({ ...input, delivery: {
826
+ id, messageId: message.id, digest: hash(message), targetSessionId: work.originSessionId, resultVersion: version, state: 'prepared'
827
+ } })));
828
+ try {
829
+ const agent = await this.ownerAgent(work, runtime.authority.origin);
830
+ const check = async () => {
831
+ const current = this.read(work.id), receipt = current.groupInputs.find(input => input.operationId === operationId);
832
+ await this.ownerAgent(current, agent);
833
+ if (this.stopped || !this.config().enabled || current.configDigest !== this.configDigest() || current.state === 'cancelled' ||
834
+ receipt?.delivery?.messageId !== message.id || ['cancelled', 'unknown', 'undeliverable'].includes(receipt.delivery.state))
835
+ throw new OperationError('approval-denied');
836
+ };
837
+ this.capabilities.add(admitSupergroupInput(agent, message, check));
838
+ await outlets(this.registry).dispatch(flowId, async () => {
839
+ // Durable dispatch intent precedes the non-transactional native inbox call.
840
+ await this.serial.run(() => this.updateInput(work.id, operationId, input => ({ ...input, delivery: { ...input.delivery, state: 'dispatching' } })));
841
+ await check();
842
+ runtime.controller.signal.throwIfAborted();
843
+ agent.followup(message);
844
+ await this.serial.run(() => this.updateInput(work.id, operationId, input => ({ ...input, delivery: { ...input.delivery, state: 'queued' } })));
845
+ }, runtime.controller.signal, runtime.authority.check);
846
+ return { workId: work.id, state: work.state, deliveryId: id, queued: true };
847
+ }
848
+ catch {
849
+ await this.serial.run(() => this.updateInput(work.id, operationId, input => ({ ...input, delivery: { ...input.delivery,
850
+ state: this.read(work.id).state === 'cancelled' ? 'cancelled' : input.delivery?.state === 'prepared' ? 'undeliverable' : 'unknown', reason: 'native-delivery-unconfirmed' } })));
851
+ return { workId: work.id, state: work.state, deliveryId: id, queued: false };
852
+ }
853
+ }
854
+ async forSession(input) {
855
+ let work = [...this.domain.table('works').entries()].map(([, row]) => row)
856
+ .find(row => row.originSessionId === input.sessionId && row.inputMessageIds.includes(input.messageId));
857
+ if (!work) {
858
+ const agent = this.ctx.agents.get(SessionId(input.sessionId));
859
+ if (!agent)
860
+ return null;
861
+ const human = await this.human(agent).catch(() => undefined);
862
+ if (!human || human.messageId !== input.messageId || !this.support.connectionFailed(human.owner, agent, input.messageId))
863
+ return null;
864
+ const configDigest = this.configDigest(), pool = await this.pool(human.owner), now = Date.now();
865
+ work = await this.serial.run(async () => {
866
+ const currentHuman = await this.human(agent);
867
+ if (currentHuman.messageId !== input.messageId || !same(currentHuman.owner, human.owner) || this.configDigest() !== configDigest
868
+ || !this.support.connectionFailed(human.owner, agent, input.messageId))
869
+ return undefined;
870
+ const id = `supergroup:${hash([agent.id, human.messageId])}`, prior = this.domain.table('works').get(id);
871
+ if (prior)
872
+ return prior;
873
+ return this.put({ id, revision: 0, owner: human.owner, originSessionId: agent.id, inputMessageId: human.messageId,
874
+ inputMessageIds: [human.messageId], configDigest: this.configDigest(), readers: pool.map(bot => ({ botId: bot.id, botCreatedAt: bot.createdAt })),
875
+ createdAt: now, updatedAt: now, expiresAt: now + this.config().timeoutMs, turnIds: [], experts: [], groupInputs: [], state: 'partial', initialPending: true });
876
+ });
877
+ if (!work)
878
+ return null;
879
+ }
880
+ // Query the actual authority on every view; never project a cached execution board.
881
+ return { work, ...(work.group ? { group: await this.groups.view(work.group) } : {}) };
882
+ }
883
+ async cancel(id, expectedRevision) {
884
+ await this.cancelCurrent(id, 'user-stopped', expectedRevision);
885
+ }
886
+ async cancelCurrent(id, reason, expectedRevision) {
887
+ const runtime = this.active.get(id);
888
+ const work = await this.serial.run(async () => {
889
+ const current = this.read(id);
890
+ if (expectedRevision !== undefined && current.revision !== expectedRevision)
891
+ throw new OperationError('conflict');
892
+ runtime?.controller.abort(reason);
893
+ clearTimeout(runtime?.timer);
894
+ runtime?.detach();
895
+ if (this.active.get(id) === runtime)
896
+ this.active.delete(id);
897
+ if (terminal(current.state) && !current.initialPending && !current.collaboration?.operations.some(row => row.state === 'prepared') &&
898
+ !current.groupInputs.some(row => ['stored', 'queued', 'running'].includes(row.state) ||
899
+ row.delivery && ['prepared', 'dispatching', 'queued'].includes(row.delivery.state)))
900
+ return current;
901
+ return current.state === 'cancelled' ? current : this.put({ ...current, state: 'cancelled', reason,
902
+ ...(current.collaboration ? { collaboration: { ...current.collaboration, operations: current.collaboration.operations.map(row => row.state === 'prepared' ? { ...row, state: 'cancelled' } : row) } } : {}),
903
+ groupInputs: current.groupInputs.map(row => ({ ...row, ...(['stored', 'queued', 'running'].includes(row.state) ? { state: 'cancelled', reason } : {}), ...(row.delivery && !['delivered', 'unknown'].includes(row.delivery.state) ? { delivery: { ...row.delivery, state: 'cancelled' } } : {}) })) });
904
+ });
905
+ if (work.group) {
906
+ const facts = await this.groups.view(work.group);
907
+ for (const turnId of work.turnIds) {
908
+ const turn = facts.turns.find(row => row.id === turnId);
909
+ if (turn && ['accepted', 'running'].includes(turn.state))
910
+ await this.groups.cancel(work.group, turnId, turn.revision).catch(() => { });
911
+ }
912
+ await this.groups.drain(work.group);
913
+ }
914
+ }
915
+ async configChanged() {
916
+ const ids = new Set([...this.active.keys(), ...this.groupInputTails.keys(),
917
+ ...[...this.domain.table('works').entries()].filter(([, work]) => work.groupInputs.some(input => input.delivery && ['prepared', 'dispatching', 'queued'].includes(input.delivery.state))).map(([id]) => id)]);
918
+ await Promise.all([...ids].map(id => this.cancelCurrent(id, 'mode-or-scope-changed')));
919
+ this.registry.invalidate();
920
+ }
921
+ close() {
922
+ this.closing ??= (async () => {
923
+ this.stopped = true;
924
+ this.offExpert?.();
925
+ this.releaseCollaboration?.();
926
+ for (const release of this.capabilities)
927
+ release();
928
+ this.capabilities.clear();
929
+ const operations = [...this.active.entries()];
930
+ for (const [, runtime] of operations) {
931
+ clearTimeout(runtime.timer);
932
+ runtime.controller.abort('host-unloaded');
933
+ }
934
+ await this.collaboration?.close();
935
+ await Promise.allSettled(operations.map(([id]) => this.cancelCurrent(id, 'host-unloaded')));
936
+ await Promise.allSettled(operations.map(([, runtime]) => runtime.task));
937
+ await Promise.allSettled([...this.groupInputTails.values()]);
938
+ await this.serial.close();
939
+ await this.domain.close();
940
+ })();
941
+ return this.closing;
942
+ }
943
+ }
944
+ //# sourceMappingURL=service.js.map
945
+ export const DSH_BOT_MODULE_VERSION = '0.7.1';