@desplega.ai/agent-swarm 2.7.9 → 2.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (355) hide show
  1. package/dist/acp-adapter-t949vbbp.js +15 -0
  2. package/dist/{actions-g563mbn2.js → actions-7e9czc7s.js} +19 -19
  3. package/dist/{amp-adapter-q61w05eb.js → amp-adapter-gv6cbb7d.js} +2 -3
  4. package/dist/app-b9fbkp9v.js +20 -0
  5. package/dist/{assistant-p477rjwj.js → assistant-wjb7v4c7.js} +22 -22
  6. package/dist/{boot-args-schema-h4qj462e.js → boot-args-schema-2t37e0fe.js} +1 -1
  7. package/dist/{boot-reembed-n1ehfbsw.js → boot-reembed-a35nkyr1.js} +1 -1
  8. package/dist/{boot-reembed-qw4mc0pt.js → boot-reembed-gka3zas7.js} +1 -1
  9. package/dist/{boot-scrub-sweep-9w9jp4sm.js → boot-scrub-sweep-65sdnp6c.js} +3 -3
  10. package/dist/{boot-seeds-qdaf3sdy.js → boot-seeds-x42tzytw.js} +4 -5
  11. package/dist/{claude-adapter-348p5hx9.js → claude-adapter-v221b2fd.js} +7 -8
  12. package/dist/{claude-managed-adapter-h74d06yz.js → claude-managed-adapter-29eq09wd.js} +2 -2
  13. package/dist/{claude-managed-setup-7787fxtp.js → claude-managed-setup-9m6450zk.js} +2 -2
  14. package/dist/{claude-sdk-session-hbszbt8a.js → claude-sdk-session-0q0ptaba.js} +9066 -8818
  15. package/dist/{cli-n5yexkdg.js → cli-0b4zam62.js} +1 -0
  16. package/dist/{cli-21159vea.js → cli-0jzra9ad.js} +2 -2
  17. package/dist/{cli-eqtfgfr6.js → cli-2gxeg5gr.js} +1 -1
  18. package/dist/{cli-k70e3x9e.js → cli-2wnq8jkz.js} +9 -9
  19. package/dist/{cli-cvs2r2vq.js → cli-2zp0et3v.js} +59 -6
  20. package/dist/{cli-650zv9q9.js → cli-334z18y3.js} +4 -4
  21. package/dist/{cli-12xyjhws.js → cli-3rkdne1h.js} +2 -2
  22. package/dist/{cli-2a8py3sx.js → cli-4txa0ter.js} +5 -7
  23. package/dist/{cli-jc1g9ndz.js → cli-5j88qqa8.js} +10 -5
  24. package/dist/{cli-xfjrc279.js → cli-5mrq3ake.js} +48 -14
  25. package/dist/{cli-v3cf1ts9.js → cli-6t09sdhy.js} +3 -3
  26. package/dist/{cli-qzt90yze.js → cli-6wxjceza.js} +8 -8
  27. package/dist/{cli-9aezs55w.js → cli-7b8sbmag.js} +8 -8
  28. package/dist/{cli-3xj33nrx.js → cli-7cp6aa1q.js} +10 -3
  29. package/dist/{cli-jfx48xrj.js → cli-7p1kvkck.js} +6 -6
  30. package/dist/{cli-b932gexn.js → cli-8aes17e4.js} +2 -2
  31. package/dist/{cli-3tqcamp6.js → cli-8fknbnhw.js} +14 -13
  32. package/dist/{cli-587857ys.js → cli-8kzasymh.js} +3 -3
  33. package/dist/{cli-sgs5k6yd.js → cli-a7wvp2km.js} +1 -1
  34. package/dist/{cli-varqt4d1.js → cli-abejgen1.js} +69 -22
  35. package/dist/{cli-rwymrnaz.js → cli-bsywb58a.js} +8 -8
  36. package/dist/{cli-btc9cb4c.js → cli-c55z5chy.js} +4 -6
  37. package/dist/{cli-ms5m5r1y.js → cli-deefvewm.js} +1 -1
  38. package/dist/{cli-p17970qv.js → cli-ee0b971j.js} +3 -3
  39. package/dist/cli-f3vq58d2.js +242 -0
  40. package/dist/{cli-3xcwp3z8.js → cli-ffhtssbp.js} +2 -2
  41. package/dist/{cli-hwprv9e4.js → cli-g70vxtjh.js} +2 -2
  42. package/dist/{cli-4t0fmf3z.js → cli-gxkx0zzp.js} +1 -1
  43. package/dist/{cli-neyag5p6.js → cli-h38x262p.js} +3365 -429
  44. package/dist/{cli-2ccpqyyf.js → cli-j790gp2w.js} +105 -22
  45. package/dist/{cli-f2zenhja.js → cli-kc7v1nfv.js} +1 -1
  46. package/dist/{cli-vxh6acp7.js → cli-m23zjcy2.js} +10 -10
  47. package/dist/{cli-y8nbefpb.js → cli-m28atx8q.js} +12 -10
  48. package/dist/{cli-serm8zrx.js → cli-m4dqmnbp.js} +1 -1
  49. package/dist/{cli-ybjdc978.js → cli-mrt48bx7.js} +7 -4
  50. package/dist/{cli-y5rbvxhc.js → cli-n515ex5z.js} +14 -14
  51. package/dist/{cli-ypff1qwp.js → cli-n9ftpys4.js} +7 -7
  52. package/dist/{cli-605nn699.js → cli-p1bq50aa.js} +894 -226
  53. package/dist/{cli-qkdmz8c8.js → cli-p1w18yhx.js} +1 -1
  54. package/dist/{cli-xk879m3k.js → cli-p2gfst4m.js} +52 -43
  55. package/dist/{cli-sya22y84.js → cli-pasjcnmj.js} +12 -12
  56. package/dist/{cli-0whpms1z.js → cli-qa4wdgsy.js} +5 -5
  57. package/dist/{cli-ejkvvqbe.js → cli-qfedvmcr.js} +50 -24
  58. package/dist/{cli-tqq0hspb.js → cli-qmqk2yc2.js} +1 -1
  59. package/dist/{cli-qmd3mse0.js → cli-qsnnd04k.js} +1 -1
  60. package/dist/{cli-agyaeef4.js → cli-qwca7s44.js} +3 -3
  61. package/dist/{cli-fayav105.js → cli-rfywm85n.js} +724 -792
  62. package/dist/{cli-zgv8gxgs.js → cli-rmmpt0wm.js} +6 -6
  63. package/dist/{cli-hae9j8sv.js → cli-rzsy6nc6.js} +12 -8
  64. package/dist/{cli-btf6fw39.js → cli-s7t6p9my.js} +1 -1
  65. package/dist/{cli-cseh6f8w.js → cli-sdtt3men.js} +1 -1
  66. package/dist/{cli-9r5gtwjr.js → cli-tk7cjj8h.js} +197 -2
  67. package/dist/{cli-q26b9wre.js → cli-tph5wt3y.js} +4 -4
  68. package/dist/{cli-gce09r66.js → cli-tqegb8eq.js} +3 -3
  69. package/dist/{cli-kf3pxxdg.js → cli-v1dv1r37.js} +1 -1
  70. package/dist/{cli-09kmfkmq.js → cli-wcg8x116.js} +1 -1
  71. package/dist/{cli-mnrkgg60.js → cli-wk18cm92.js} +5 -5
  72. package/dist/{cli-p0m0p34z.js → cli-x1wa213s.js} +3 -3
  73. package/dist/{cli-jrp1dt73.js → cli-xzm9vcfg.js} +1 -1
  74. package/dist/{cli-715t1gx6.js → cli-y97qxcfx.js} +9 -9
  75. package/dist/{cli-bc779n4v.js → cli-yq3zak69.js} +1 -1
  76. package/dist/cli.js +17 -17
  77. package/dist/{codex-adapter-ysq6bzha.js → codex-adapter-30j9bpzd.js} +5 -6
  78. package/dist/{codex-hook-fac6175r.js → codex-hook-h3vk6xzr.js} +1 -1
  79. package/dist/{codex-session-runner-qakzfx93.js → codex-session-runner-8vp57v8w.js} +5 -6
  80. package/dist/{commands-rs7hkv9r.js → commands-bngnz9g7.js} +3 -3
  81. package/dist/{controller-r5x9bg6e.js → controller-hxx8wwy1.js} +2 -2
  82. package/dist/{controllers-connect-498hrxvk.js → controllers-connect-e2b4gyxc.js} +20 -20
  83. package/dist/{cursor-adapter-d46qszer.js → cursor-adapter-n5nc3mfe.js} +1 -2
  84. package/dist/{db-s13dqhr6.js → db-bgm7vkc0.js} +3 -3
  85. package/dist/{db-pm96nhdb.js → db-c6np41ca.js} +12 -2
  86. package/dist/{devin-adapter-z46ep5ph.js → devin-adapter-xedz98zv.js} +1 -1
  87. package/dist/{dispatcher-j3h81t7m.js → dispatcher-jnybck15.js} +18 -18
  88. package/dist/{dsh-adapter-rw0d5rc4.js → dsh-adapter-nrhbrjz8.js} +1 -2
  89. package/dist/{easter-egg-3d-qtgfxgze.js → easter-egg-3d-533knw22.js} +1 -1
  90. package/dist/{embedding-space-xh8p4q4x.js → embedding-space-crsm2zp0.js} +6 -6
  91. package/dist/{embeddings-wp745m91.js → embeddings-e7z3f27f.js} +1 -1
  92. package/dist/{execute-2fzb9z74.js → execute-b3mrb1mv.js} +1 -1
  93. package/dist/{external-channel-ys21h3sy.js → external-channel-m77wf5z3.js} +2 -2
  94. package/dist/{fx-adapter-vz0b9z3g.js → fx-adapter-b6w0kf56.js} +7 -8
  95. package/dist/{google-generative-ai-ytpgncx9.js → google-generative-ai-h7s3e9kk.js} +1 -1
  96. package/dist/{google-vertex-tqhze5j7.js → google-vertex-fhxaafzw.js} +1 -1
  97. package/dist/{grok-adapter-spea7zkj.js → grok-adapter-4sqtebdk.js} +7 -8
  98. package/dist/handlers-kdjcyzdj.js +32 -0
  99. package/dist/heartbeat-xgb036sx.js +43 -0
  100. package/dist/{hook-amcj4s10.js → hook-5h02c9ga.js} +6 -6
  101. package/dist/{hook-bc6n49qn.js → hook-xsk1jbha.js} +5 -5
  102. package/dist/{http-7374brv5.js → http-txe7qhvn.js} +448 -165
  103. package/dist/{index-pxn30mse.js → index-0eny15vj.js} +8 -8
  104. package/dist/{index-5a9jtqde.js → index-0rvk3vd4.js} +46 -46
  105. package/dist/{index-fvzke5kx.js → index-1qw6f2dc.js} +10 -10
  106. package/dist/{index-q5cmtbz5.js → index-4a0670yh.js} +15939 -14244
  107. package/dist/index-835xdgnm.js +33 -0
  108. package/dist/index-d469300x.js +37 -0
  109. package/dist/{index-h7f61sy9.js → index-e5pfbsys.js} +3 -3
  110. package/dist/{index-hsad2t3r.js → index-m5gx1xd6.js} +38 -38
  111. package/dist/{index-5fx3b3kw.js → index-rvccek1w.js} +9 -9
  112. package/dist/index-rzqwp11g.js +32 -0
  113. package/dist/{index-w4m9z29z.js → index-tvfafeyy.js} +1 -1
  114. package/dist/{index-c9y31ytf.js → index-vk63emp7.js} +979 -35
  115. package/dist/{index-514d9pf6.js → index-w7em4ktq.js} +8 -8
  116. package/dist/{index-p4hjwbvw.js → index-ysvbhg5m.js} +1 -1
  117. package/dist/{keepalive-wy29kbrg.js → keepalive-4zsrce78.js} +3 -3
  118. package/dist/lead-yqt47dkr.js +70 -0
  119. package/dist/{maintenance-h2ds9w6c.js → maintenance-86jvartk.js} +1 -1
  120. package/dist/{oauth-refresh-sweep-q7mtbyp3.js → oauth-refresh-sweep-j52kg9pr.js} +2 -2
  121. package/dist/{onboard-vw8r2fdw.js → onboard-c2aj5p8q.js} +3 -3
  122. package/dist/{opencode-adapter-mtb0953j.js → opencode-adapter-dsagkhtw.js} +5 -6
  123. package/dist/{otel-impl-j42czw3r.js → otel-impl-yyy203z8.js} +1 -1
  124. package/dist/{pi-mono-adapter-zk8pg9jr.js → pi-mono-adapter-546cd1cc.js} +9 -9
  125. package/dist/{pricing-refresh-x7nhv23d.js → pricing-refresh-1rgzqyzz.js} +2 -3
  126. package/dist/{rbac-roles-9044425x.js → rbac-roles-e70xfeyj.js} +4 -6
  127. package/dist/{rbac-roles-bzvee6cf.js → rbac-roles-q89qe8er.js} +3 -3
  128. package/dist/{registry-hpjfmcfz.js → registry-32b1mft6.js} +1 -1
  129. package/dist/{render-v2-t7bn4skz.js → render-v2-k6tt107q.js} +9 -4
  130. package/dist/{resume-x94gemep.js → resume-cnnrjfxa.js} +6 -6
  131. package/dist/{runtime-breq6fmv.js → runtime-1hv06jsn.js} +1 -1
  132. package/dist/{session-access-q7dmqjvt.js → session-access-xkxkjw3n.js} +4 -4
  133. package/dist/{session-source-backfill-440ysamr.js → session-source-backfill-1d5pdwww.js} +2 -2
  134. package/dist/{setup-07n4727s.js → setup-se8q7gkc.js} +1 -1
  135. package/dist/{virtual-modules-z5h6mcyf.js → virtual-modules-gazyapte.js} +3 -3
  136. package/dist/{work-objects-pnq5y534.js → work-objects-1kxnbzy5.js} +22 -22
  137. package/dist/{worker-follow-up-7z1gfkr8.js → worker-follow-up-zqm8apt4.js} +18 -18
  138. package/dist/worker-j6xxtq7p.js +70 -0
  139. package/openapi.json +334 -7
  140. package/package.json +4 -4
  141. package/src/apps/catalog.generated.json +55 -0
  142. package/src/apps/definition.ts +11 -0
  143. package/src/apps/page-validator.ts +19 -0
  144. package/src/apps/store.ts +28 -8
  145. package/src/assets/key.ts +77 -4
  146. package/src/be/db/model-profiles.ts +147 -38
  147. package/src/be/db/session-labels.ts +57 -0
  148. package/src/be/db/session-tree.ts +51 -7
  149. package/src/be/db/slack-trees.ts +146 -0
  150. package/src/be/db/tasks/read.ts +107 -8
  151. package/src/be/db/workflow-run-definitions.ts +117 -0
  152. package/src/be/db-client.ts +8 -2
  153. package/src/be/db.ts +119 -87
  154. package/src/be/event-loop-lag.ts +146 -0
  155. package/src/be/mcp-overflow-sweep.ts +2 -1
  156. package/src/be/memory/constants.ts +14 -1
  157. package/src/be/memory/key-paths.ts +8 -0
  158. package/src/be/memory/providers/sqlite-store.ts +199 -18
  159. package/src/be/memory/task-learning.ts +79 -14
  160. package/src/be/memory/types.ts +24 -1
  161. package/src/be/migrations/278_slack_render_v2_reconcile.sql +108 -0
  162. package/src/be/migrations/279_backfill_learning_expiry.sql +15 -0
  163. package/src/be/migrations/281_model_profiles_pr2.sql +28 -0
  164. package/src/be/migrations/283_workflow_run_definitions.sql +14 -0
  165. package/src/be/model-profile-check.ts +284 -0
  166. package/src/be/model-tier-resolution.ts +112 -12
  167. package/src/be/multi-runtime.ts +27 -0
  168. package/src/be/runtime-pools/routing.ts +52 -4
  169. package/src/be/scripts/typecheck.ts +1 -0
  170. package/src/be/seed-scripts/catalog/dreaming-learnings.ts +552 -0
  171. package/src/be/seed-scripts/catalog/dreaming-memtax-create.ts +389 -14
  172. package/src/be/seed-scripts/catalog/dreaming-memtax.ts +6 -3
  173. package/src/be/seed-scripts/index.ts +9 -0
  174. package/src/be/steering.ts +8 -2
  175. package/src/be/swarm-config-guard.ts +2 -0
  176. package/src/commands/context-preamble.ts +258 -0
  177. package/src/commands/onboard/agent-fs-version.ts +1 -1
  178. package/src/commands/runner.ts +32 -1
  179. package/src/extensions/catalog.generated.json +3 -3
  180. package/src/fs/provider.ts +17 -3
  181. package/src/heartbeat/heartbeat.ts +17 -5
  182. package/src/heartbeat/index.ts +1 -0
  183. package/src/http/agents.ts +56 -4
  184. package/src/http/apps.ts +3 -1
  185. package/src/http/config.ts +2 -6
  186. package/src/http/core.ts +9 -3
  187. package/src/http/index.ts +12 -9
  188. package/src/http/memory.ts +9 -4
  189. package/src/http/model-profiles.ts +58 -10
  190. package/src/http/poll.ts +36 -3
  191. package/src/http/schedules.ts +42 -3
  192. package/src/http/sessions.ts +16 -3
  193. package/src/http/tasks.ts +37 -12
  194. package/src/http/utils.ts +18 -0
  195. package/src/http/webhooks.ts +48 -0
  196. package/src/http/workflows.ts +15 -2
  197. package/src/integrations/chat-sdk/commands.ts +167 -31
  198. package/src/integrations/chat-sdk/inbound.ts +10 -8
  199. package/src/integrations/chat-sdk/message-text.ts +117 -0
  200. package/src/prompts/session-templates.ts +1 -1
  201. package/src/providers/acp-targets.ts +11 -6
  202. package/src/providers/amp-adapter.ts +1 -1
  203. package/src/providers/claude-sdk-session.ts +132 -23
  204. package/src/providers/codex-skill-resolver.ts +10 -4
  205. package/src/providers/cursor-adapter.ts +1 -1
  206. package/src/providers/devin-skill-resolver.ts +5 -5
  207. package/src/providers/dsh-adapter.ts +1 -1
  208. package/src/scheduler/schedule-task.ts +1 -0
  209. package/src/scheduler/scheduler.ts +4 -1
  210. package/src/scripts-runtime/executors/quickjs-runner.ts +2 -0
  211. package/src/scripts-runtime/executors/quickjs-structured-clone.ts +180 -0
  212. package/src/scripts-runtime/quickjs-compat.ts +0 -1
  213. package/src/scripts-runtime/sdk-allowlist.ts +1 -0
  214. package/src/scripts-runtime/swarm-sdk.ts +18 -1
  215. package/src/scripts-runtime/types/stdlib.d.ts +1 -0
  216. package/src/scripts-runtime/types/swarm-sdk.d.ts +1 -0
  217. package/src/server.ts +2 -0
  218. package/src/slack/app.ts +425 -10
  219. package/src/slack/handlers.ts +9 -2
  220. package/src/slack/inbound-dispatch.ts +18 -1
  221. package/src/slack/index.ts +7 -1
  222. package/src/slack/lifecycle-lock.ts +29 -0
  223. package/src/slack/render-v2.ts +424 -212
  224. package/src/slack/socket-fence.ts +64 -0
  225. package/src/slack/watcher.ts +42 -8
  226. package/src/slack/workspace-guard.ts +345 -0
  227. package/src/tasks/task-terminal-effects.ts +4 -0
  228. package/src/tasks/worker-follow-up.ts +102 -2
  229. package/src/tests/acp-adapter.test.ts +82 -0
  230. package/src/tests/apps-icon.test.ts +120 -0
  231. package/src/tests/apps-schema-form.test.ts +151 -0
  232. package/src/tests/chained-task-follow-up.test.ts +248 -0
  233. package/src/tests/chat-sdk-commands.test.ts +359 -2
  234. package/src/tests/chat-sdk-inbound.test.ts +20 -0
  235. package/src/tests/chat-sdk-slack.test.ts +189 -1
  236. package/src/tests/check-pr-body.test.ts +40 -0
  237. package/src/tests/claude-sdk-lifecycle.test.ts +216 -1
  238. package/src/tests/claude-sdk-process.fixture.ts +57 -0
  239. package/src/tests/codex-skill-resolver.test.ts +31 -0
  240. package/src/tests/credentials-allowlist.test.ts +470 -0
  241. package/src/tests/db-client-busy-retry.test.ts +69 -18
  242. package/src/tests/db-client.test.ts +26 -1
  243. package/src/tests/db-task-read-contract.test.ts +7 -0
  244. package/src/tests/db-task-write-contract.test.ts +6 -0
  245. package/src/tests/deferred-wake-follow-up.test.ts +47 -0
  246. package/src/tests/docs-index-footprint.test.js +3 -3
  247. package/src/tests/dreaming-learnings.test.ts +1395 -0
  248. package/src/tests/dsh-adapter.test.ts +1 -1
  249. package/src/tests/event-loop-lag.test.ts +184 -0
  250. package/src/tests/explicit-model-validation.test.ts +2 -0
  251. package/src/tests/extensions-example-comms-adherence-gate.test.ts +115 -0
  252. package/src/tests/fs-provider.test.ts +42 -0
  253. package/src/tests/github-webhook-early-ack.test.ts +144 -0
  254. package/src/tests/heartbeat.test.ts +28 -1
  255. package/src/tests/http-api-integration.test.ts +2 -0
  256. package/src/tests/http-log-scrubbing.test.ts +68 -2
  257. package/src/tests/human-free-reclassify.test.ts +5 -1
  258. package/src/tests/kv-storage.test.ts +92 -1
  259. package/src/tests/list-endpoint-slimming.test.ts +17 -0
  260. package/src/tests/memory-key-paths.test.ts +57 -0
  261. package/src/tests/memory-retrieval-purge.test.ts +19 -0
  262. package/src/tests/migration-283-workflow-run-definitions.test.ts +69 -0
  263. package/src/tests/model-profile-check.test.ts +387 -0
  264. package/src/tests/model-profiles-api.test.ts +528 -1
  265. package/src/tests/profile-claim.test.ts +415 -3
  266. package/src/tests/profile-tier-alias.test.ts +382 -0
  267. package/src/tests/quickjs-compat.test.ts +1 -1
  268. package/src/tests/runner-context-preamble.test.ts +552 -0
  269. package/src/tests/schedule-profile.test.ts +359 -0
  270. package/src/tests/script-connections.test.ts +9 -0
  271. package/src/tests/script-executor-conformance.test.ts +188 -0
  272. package/src/tests/script-per-script-executor.test.ts +1 -0
  273. package/src/tests/scripts-sdk-bridge-tool-failure.test.ts +141 -0
  274. package/src/tests/seed-scripts.test.ts +2 -2
  275. package/src/tests/sessions-tree.test.ts +133 -2
  276. package/src/tests/slack-app-icon.test.ts +4 -0
  277. package/src/tests/slack-dm-implicit-mention.test.ts +236 -0
  278. package/src/tests/slack-file-tools-attachments.test.ts +1 -0
  279. package/src/tests/slack-inbound-receipts.test.ts +22 -2
  280. package/src/tests/slack-read-boundaries.test.ts +4 -3
  281. package/src/tests/slack-render-v2-query-plans.test.ts +262 -3
  282. package/src/tests/slack-render-v2-reconcile.test.ts +201 -0
  283. package/src/tests/slack-socket-ack.test.ts +16 -1
  284. package/src/tests/slack-socket-watchdog.test.ts +748 -0
  285. package/src/tests/slack-workspace-guard.test.ts +905 -0
  286. package/src/tests/steering-core.test.ts +40 -0
  287. package/src/tests/store-progress-learning.test.ts +605 -20
  288. package/src/tests/tool-annotations.test.ts +1 -1
  289. package/src/tests/vcs-identity-inheritance.test.ts +85 -0
  290. package/src/tests/workflow-convergence.test.ts +46 -40
  291. package/src/tests/workflow-definition-pinning-recovery.test.ts +552 -0
  292. package/src/tests/workflow-definition-pinning.test.ts +645 -0
  293. package/src/tests/workflow-executors.test.ts +16 -7
  294. package/src/tests/workflow-foreach.test.ts +43 -20
  295. package/src/tests/workflow-notify-slack-ready.test.ts +161 -0
  296. package/src/tests/workflow-profile.test.ts +328 -0
  297. package/src/tools/app-upsert.ts +1 -1
  298. package/src/tools/memory-edit.ts +2 -1
  299. package/src/tools/model-profiles/check-model-profile.ts +63 -0
  300. package/src/tools/schedules/create-schedule.ts +45 -4
  301. package/src/tools/schedules/patch-schedule.ts +50 -4
  302. package/src/tools/schedules/update-schedule.ts +50 -4
  303. package/src/tools/send-task.ts +17 -2
  304. package/src/tools/store-progress.ts +15 -3
  305. package/src/tools/task-action.ts +9 -1
  306. package/src/tools/templates.ts +13 -0
  307. package/src/tools/tool-config.ts +2 -1
  308. package/src/tools/utils.ts +77 -11
  309. package/src/tools/workflows/create-workflow.ts +1 -1
  310. package/src/tools/workflows/retry-workflow-run.ts +1 -1
  311. package/src/tools/workflows/update-workflow.ts +10 -1
  312. package/src/types.ts +56 -1
  313. package/src/utils/credentials.ts +89 -12
  314. package/src/workflows/engine.ts +10 -1
  315. package/src/workflows/executors/agent-task.ts +21 -2
  316. package/src/workflows/executors/foreach.ts +4 -1
  317. package/src/workflows/executors/notify.ts +62 -6
  318. package/src/workflows/executors/sub-workflow.ts +1 -1
  319. package/src/workflows/executors/swarm-script.ts +4 -1
  320. package/src/workflows/foreach-driver.ts +8 -5
  321. package/src/workflows/limits.ts +2 -1
  322. package/src/workflows/model-validation.ts +27 -2
  323. package/src/workflows/patch-definition.ts +3 -1
  324. package/src/workflows/recovery.ts +6 -6
  325. package/src/workflows/resume.ts +9 -9
  326. package/src/workflows/retry-poller.ts +2 -2
  327. package/templates/extensions/comms-adherence-gate/README.md +25 -0
  328. package/templates/extensions/comms-adherence-gate/hooks.ts +100 -11
  329. package/templates/extensions/comms-adherence-gate/manifest.json +1 -1
  330. package/templates/skills/apps/SKILL.md +9 -0
  331. package/templates/skills/apps/content.md +9 -0
  332. package/templates/skills/code-quality/content.md +12 -0
  333. package/templates/skills/memory/content.md +8 -0
  334. package/templates/skills/scheduling/config.json +1 -1
  335. package/templates/skills/scheduling/content.md +2 -2
  336. package/templates/skills/swarm-docs/content.md +4 -0
  337. package/templates/skills/swarm-extensions/content.md +1 -1
  338. package/templates/skills/swarm-scripts/SKILL.md +1 -1
  339. package/templates/skills/swarm-scripts/content.md +1 -1
  340. package/templates/skills/work-on-task/SKILL.md +2 -0
  341. package/templates/skills/work-on-task/content.md +2 -0
  342. package/templates/workflows/dreaming/content.md +174 -7
  343. package/dist/acp-adapter-dn4gdsgr.js +0 -16
  344. package/dist/app-a66ssc4k.js +0 -17
  345. package/dist/cli-530hkwdy.js +0 -779
  346. package/dist/cli-a0657jmf.js +0 -339
  347. package/dist/cli-cyn9v8zr.js +0 -748
  348. package/dist/handlers-crckt5dq.js +0 -32
  349. package/dist/heartbeat-8phn1kdq.js +0 -41
  350. package/dist/index-4x08sjtk.js +0 -30
  351. package/dist/index-8ybffts4.js +0 -37
  352. package/dist/index-nfy4kkg5.js +0 -33
  353. package/dist/lead-zdqxsvjn.js +0 -71
  354. package/dist/worker-y62rvvq3.js +0 -71
  355. package/dist/{cli-gxy8y1dt.js → cli-8bpgbr8k.js} +3 -3
@@ -16,6 +16,11 @@ import {
16
16
  updateScheduledTask,
17
17
  withFavoriteFlags,
18
18
  } from "../be/db";
19
+ import {
20
+ modelProfileRefError,
21
+ scheduleProfileUpdate,
22
+ taskProfileError,
23
+ } from "../be/db/model-profiles";
19
24
  import { explicitModelErrorForAgent } from "../be/model-validation";
20
25
  import { mergeScheduleTiming, validateRecurringTiming } from "../be/schedules/validate";
21
26
  import { getScript } from "../be/scripts/db";
@@ -52,6 +57,8 @@ const scheduleUpdateBodySchema = z.object({
52
57
  timezone: z.string().optional(),
53
58
  model: z.string().nullable().optional(),
54
59
  modelTier: ModelTierSchema.nullable().optional(),
60
+ /** Model profile for every fired task. Exclusive with model/modelTier; setting one clears the other. */
61
+ profile: z.string().nullable().optional(),
55
62
  /** Accept a `model` the catalog does not list (a custom id). Without it an unknown id is a 400. */
56
63
  allowCustomModel: z.boolean().optional(),
57
64
  nextRunAt: z.string().nullable().optional(),
@@ -113,6 +120,8 @@ const createSchedule = route({
113
120
  timezone: z.string().optional(),
114
121
  model: z.string().optional(),
115
122
  modelTier: ModelTierSchema.optional(),
123
+ /** Model profile for every fired task. Exclusive with model/modelTier. */
124
+ profile: z.string().optional(),
116
125
  /** Accept a `model` the catalog does not list (a custom id). Without it an unknown id is a 400. */
117
126
  allowCustomModel: z.boolean().optional(),
118
127
  scheduleType: z.enum(["recurring", "one_time"]).optional(),
@@ -411,6 +420,16 @@ export async function handleSchedules(
411
420
  jsonError(res, modelError, 400);
412
421
  return true;
413
422
  }
423
+ const profileError = await taskProfileError({
424
+ profile: body.profile,
425
+ model: body.model,
426
+ modelTier: body.modelTier,
427
+ agentId: body.targetAgentId,
428
+ });
429
+ if (profileError) {
430
+ jsonError(res, profileError, 400);
431
+ return true;
432
+ }
414
433
 
415
434
  try {
416
435
  const trustedUserId = await resolveHttpAuditUserId(req, myAgentId);
@@ -456,6 +475,7 @@ export async function handleSchedules(
456
475
  nextRunAt,
457
476
  timezone: body.timezone,
458
477
  ...splitLegacyModelAlias({ model: body.model, modelTier: body.modelTier }),
478
+ profile: body.profile?.trim() || undefined,
459
479
  scheduleType: body.scheduleType,
460
480
  targetType: body.targetType,
461
481
  workflowId: body.workflowId,
@@ -468,7 +488,12 @@ export async function handleSchedules(
468
488
  });
469
489
 
470
490
  createSchedule.respond(res, 201, schedule);
471
- } catch (_error) {
491
+ } catch (error) {
492
+ // The profile was deleted between taskProfileError and the insert.
493
+ if (modelProfileRefError(error) === "missing") {
494
+ jsonError(res, `Unknown model profile "${body.profile}".`, 400);
495
+ return true;
496
+ }
472
497
  jsonError(res, "Failed to create schedule", 500);
473
498
  }
474
499
  return true;
@@ -593,6 +618,11 @@ export async function handleSchedules(
593
618
  const agentChanged =
594
619
  parsed.body.targetAgentId !== undefined &&
595
620
  parsed.body.targetAgentId !== existing.targetAgentId;
621
+ const profileUpdate = await scheduleProfileUpdate(existing, parsed.body);
622
+ if (profileUpdate.error !== undefined) {
623
+ jsonError(res, profileUpdate.error, 400);
624
+ return true;
625
+ }
596
626
  if (parsed.body.model !== undefined || parsed.body.modelTier !== undefined) {
597
627
  const normalizedModel = splitLegacyModelAlias({
598
628
  model: parsed.body.model,
@@ -614,7 +644,7 @@ export async function handleSchedules(
614
644
  if (parsed.body.modelTier !== undefined || normalizedModel.modelTier) {
615
645
  body.modelTier = normalizedModel.modelTier ?? null;
616
646
  }
617
- } else if (agentChanged && existing.model) {
647
+ } else if (agentChanged && existing.model && !profileUpdate.fields.profile) {
618
648
  // Harness only: the stored id already passed the catalog check when it was written.
619
649
  const modelError = await explicitModelErrorForAgent({
620
650
  model: existing.model,
@@ -626,6 +656,7 @@ export async function handleSchedules(
626
656
  return true;
627
657
  }
628
658
  }
659
+ Object.assign(body, profileUpdate.fields);
629
660
 
630
661
  // Reject updates on completed one-time schedules
631
662
  if (existing.scheduleType === "one_time" && !existing.enabled && existing.lastRunAt) {
@@ -750,7 +781,15 @@ export async function handleSchedules(
750
781
 
751
782
  const updatedBy = await resolveHttpAuditUserId(req, myAgentId);
752
783
  if (updatedBy !== null) body.updatedBy = updatedBy;
753
- const schedule = await updateScheduledTask(parsed.params.id, body);
784
+ let schedule: Awaited<ReturnType<typeof updateScheduledTask>>;
785
+ try {
786
+ schedule = await updateScheduledTask(parsed.params.id, body);
787
+ } catch (error) {
788
+ // The profile was deleted between scheduleProfileUpdate and the write.
789
+ if (modelProfileRefError(error) !== "missing") throw error;
790
+ jsonError(res, `Unknown model profile "${body.profile}".`, 400);
791
+ return true;
792
+ }
754
793
  routeHandle.respond(res, 200, schedule);
755
794
  return true;
756
795
  }
@@ -3,8 +3,10 @@ import { z } from "zod";
3
3
  import {
4
4
  ASSET_KEY_MAX_LENGTH,
5
5
  defaultAssetKey,
6
+ isResourceGroupPrefix,
6
7
  normalizeAssetKey,
7
8
  parseAssetKey,
9
+ RESOURCE_GROUPS_READ_ONLY,
8
10
  } from "../assets/key";
9
11
  import { SOURCE_GROUPS_READ_ONLY, sourceMoveError, sourceOfKey } from "../assets/source-key";
10
12
  import { AssetKeyAuthorizationError, authorizeAssetKeyWrite } from "../be/asset-key-auth";
@@ -22,7 +24,7 @@ import {
22
24
  getTasksDispatchedFrom,
23
25
  listRecentSessions,
24
26
  } from "../be/db";
25
- import { getSessionLabels } from "../be/db/session-labels";
27
+ import { getResourceSessionLabels, getSessionLabels } from "../be/db/session-labels";
26
28
  import {
27
29
  listPrefixRoots,
28
30
  listSharedPrefixRoots,
@@ -1098,8 +1100,12 @@ export async function handleSessions(
1098
1100
  showSource: parsed.query.showSource,
1099
1101
  });
1100
1102
  // Labels cover hidden sources too: a pane or tab of a hidden source still names its group.
1101
- const { sourceGroups, slackChannels, threadLabels, ...counts } = tree;
1102
- const labels = { ...threadLabels, ...(await getSessionLabels(sourceGroups)) };
1103
+ const { sourceGroups, slackChannels, threadLabels, resourceGroups, ...counts } = tree;
1104
+ const [sourceLabels, resourceLabels] = await Promise.all([
1105
+ getSessionLabels(sourceGroups),
1106
+ getResourceSessionLabels(resourceGroups),
1107
+ ]);
1108
+ const labels = { ...threadLabels, ...sourceLabels, ...resourceLabels };
1103
1109
  warmSlackChannelLabels(
1104
1110
  slackChannels.map((id) => `shared/slack/${id}/`).filter((key) => labels[key] === undefined),
1105
1111
  );
@@ -1166,6 +1172,13 @@ export async function handleSessions(
1166
1172
  jsonError(res, SOURCE_GROUPS_READ_ONLY, 400);
1167
1173
  return true;
1168
1174
  }
1175
+ if (
1176
+ isResourceGroupPrefix(from) ||
1177
+ (parsed.body.to && isResourceGroupPrefix(normalizeAssetKey(parsed.body.to)))
1178
+ ) {
1179
+ jsonError(res, RESOURCE_GROUPS_READ_ONLY, 400);
1180
+ return true;
1181
+ }
1169
1182
  if (parseAssetKey(from).relativeSegments.length === 0) {
1170
1183
  jsonError(res, "Cannot move a namespace root", 400);
1171
1184
  return true;
package/src/http/tasks.ts CHANGED
@@ -39,7 +39,12 @@ import {
39
39
  updateTaskTitle,
40
40
  updateTaskVcs,
41
41
  } from "../be/db";
42
- import { modelProfileRefError, taskProfileError } from "../be/db/model-profiles";
42
+ import {
43
+ getModelProfileByName,
44
+ hasUnreadableCredentialAllowlist,
45
+ modelProfileRefError,
46
+ taskProfileError,
47
+ } from "../be/db/model-profiles";
43
48
  import { explicitModelErrorForAgent } from "../be/model-validation";
44
49
  import { getUserGrant } from "../be/rbac-roles";
45
50
  import { hasSessionAccess, type SessionAccess } from "../be/session-shares";
@@ -69,6 +74,7 @@ import {
69
74
  AgentTaskStatusSchema,
70
75
  AssetKeySchema,
71
76
  isTerminalTaskStatus,
77
+ ModelProfileCredentialsSchema,
72
78
  ModelTierSchema,
73
79
  OnUnsupportedSchema,
74
80
  ProviderNameSchema,
@@ -140,6 +146,8 @@ const AgentTaskSummarySchema = AgentTaskSchema.pick({
140
146
  modelAlias: true,
141
147
  effort: true,
142
148
  resolvedEffort: true,
149
+ profile: true,
150
+ resolvedProfile: true,
143
151
  provider: true,
144
152
  requestedByUserId: true,
145
153
  progress: true,
@@ -706,6 +714,9 @@ const listPausedTasks = route({
706
714
  // Same requester projection a fresh task_assigned trigger carries,
707
715
  // so a resumed session gets the same requester-profile prompt.
708
716
  requestedBy: TaskRequestedBySchema.optional(),
717
+ // The claimed profile's pooled-key allowlist, read again from the
718
+ // profile, so the recovery spawn picks keys as the claim did.
719
+ credentialAllowlist: ModelProfileCredentialsSchema.optional(),
709
720
  }),
710
721
  ),
711
722
  }),
@@ -1083,16 +1094,6 @@ export async function handleTasks(
1083
1094
  jsonError(res, modelError, 400);
1084
1095
  return true;
1085
1096
  }
1086
- const profileError = await taskProfileError({
1087
- profile: parsed.body.profile,
1088
- ...splitLegacyModelAlias({ model: parsed.body.model, modelTier: parsed.body.modelTier }),
1089
- agentId: defaultAgentId,
1090
- });
1091
- if (profileError) {
1092
- jsonError(res, profileError, 400);
1093
- return true;
1094
- }
1095
-
1096
1097
  const parentTask = parsed.body.parentTaskId
1097
1098
  ? await getTaskById(parsed.body.parentTaskId)
1098
1099
  : null;
@@ -1127,6 +1128,18 @@ export async function handleTasks(
1127
1128
  jsonError(res, "You don't have access to the tasks in this context.", 403);
1128
1129
  return true;
1129
1130
  }
1131
+ // The child inherits the parent's repo in createTaskExtended, and the worker
1132
+ // loads that repo's config, so the profile check judges the same pool.
1133
+ const profileError = await taskProfileError({
1134
+ profile: parsed.body.profile,
1135
+ ...splitLegacyModelAlias({ model: parsed.body.model, modelTier: parsed.body.modelTier }),
1136
+ agentId: defaultAgentId,
1137
+ vcsRepo: parentTask?.vcsRepo,
1138
+ });
1139
+ if (profileError) {
1140
+ jsonError(res, profileError, 400);
1141
+ return true;
1142
+ }
1130
1143
  let assetKey: string | undefined;
1131
1144
  try {
1132
1145
  const inheritedKey = parentTask?.key;
@@ -1930,14 +1943,26 @@ export async function handleTasks(
1930
1943
  const tasks = await Promise.all(
1931
1944
  pausedTasks.map(async (task) => {
1932
1945
  const requestedBy = await buildTaskRequestedBy(task);
1946
+ const profile = task.resolvedProfile
1947
+ ? await getModelProfileByName(task.resolvedProfile)
1948
+ : null;
1949
+ // Without an allowlist the recovery spawn picks from the whole pool, so
1950
+ // the task stays paused until the profile's credentials are set again.
1951
+ if (profile && hasUnreadableCredentialAllowlist(profile)) {
1952
+ console.warn(
1953
+ `[paused-tasks] holding task ${task.id}: profile "${profile.name}" has an unreadable credential allowlist`,
1954
+ );
1955
+ return null;
1956
+ }
1933
1957
  return {
1934
1958
  ...task,
1935
1959
  attachments: await getTaskAttachments(task.id),
1936
1960
  ...(requestedBy && { requestedBy }),
1961
+ ...(profile?.credentials && { credentialAllowlist: profile.credentials }),
1937
1962
  };
1938
1963
  }),
1939
1964
  );
1940
- listPausedTasks.respond(res, 200, { tasks });
1965
+ listPausedTasks.respond(res, 200, { tasks: tasks.filter((task) => task !== null) });
1941
1966
  return true;
1942
1967
  }
1943
1968
 
package/src/http/utils.ts CHANGED
@@ -274,6 +274,24 @@ export function redactShareTokenInPath(pathname: string): string {
274
274
  return pathname;
275
275
  }
276
276
 
277
+ /**
278
+ * Event-loop path label for an HTTP request: method plus the first three path
279
+ * segments. Segments past the third are ids, so they are left out to bound
280
+ * the label cardinality. Invite codes and share tokens are credentials, so
281
+ * the label is redacted before it can reach a log line.
282
+ */
283
+ export function loopPathForRequest(
284
+ method: string | undefined,
285
+ segments: readonly string[],
286
+ ): string {
287
+ const redacted = redactShareTokenInPath(`/${segments.join("/")}`)
288
+ .split("/")
289
+ .filter(Boolean)
290
+ .slice(0, 3)
291
+ .join("/");
292
+ return scrubSecrets(`http ${method} ${redacted}`);
293
+ }
294
+
277
295
  export function safeRequestUrlForLog(rawUrl: string | undefined): string {
278
296
  if (!rawUrl) return "";
279
297
 
@@ -142,6 +142,45 @@ async function runBlockableHandler(
142
142
  }
143
143
  }
144
144
 
145
+ /**
146
+ * GitHub events with a real handler (or a signature-checked control event).
147
+ * Every other event is a no-op today, so it is acknowledged before its body is
148
+ * read: the request span then excludes the payload upload, which dominated
149
+ * latency for large CI payloads (check_run, workflow_run, ...).
150
+ */
151
+ const GITHUB_VERIFIED_EVENTS = new Set([
152
+ "ping",
153
+ "pull_request",
154
+ "issues",
155
+ "issue_comment",
156
+ "pull_request_review_comment",
157
+ "pull_request_review",
158
+ ]);
159
+
160
+ const GITHUB_IGNORED_SUMMARY_MS = 60_000;
161
+ const githubIgnoredCounts = new Map<string, number>();
162
+ let githubIgnoredTimer: ReturnType<typeof setInterval> | null = null;
163
+
164
+ function flushGithubIgnoredCounts(): void {
165
+ if (githubIgnoredCounts.size === 0) return;
166
+ const parts = [...githubIgnoredCounts.entries()].map(([name, n]) => `${name}=${n}`);
167
+ githubIgnoredCounts.clear();
168
+ console.log(
169
+ `[GitHub] ignored events last ${GITHUB_IGNORED_SUMMARY_MS / 1000}s: ${parts.join(" ")}`,
170
+ );
171
+ }
172
+
173
+ function countGithubIgnoredEvent(eventType: string): void {
174
+ // Bound the key space: the header is unauthenticated input.
175
+ const key =
176
+ githubIgnoredCounts.has(eventType) || githubIgnoredCounts.size < 50 ? eventType : "other";
177
+ githubIgnoredCounts.set(key, (githubIgnoredCounts.get(key) ?? 0) + 1);
178
+ if (!githubIgnoredTimer) {
179
+ githubIgnoredTimer = setInterval(flushGithubIgnoredCounts, GITHUB_IGNORED_SUMMARY_MS);
180
+ githubIgnoredTimer.unref();
181
+ }
182
+ }
183
+
145
184
  const githubWebhook = route({
146
185
  method: "post",
147
186
  path: "/api/github/webhook",
@@ -398,6 +437,15 @@ export async function handleWebhooks(
398
437
  const eventType = req.headers["x-github-event"] as string | undefined;
399
438
  const signature = req.headers["x-hub-signature-256"] as string | undefined;
400
439
 
440
+ // Early ack: events nothing handles (check_run, workflow_run, push, ...) change
441
+ // no state, so skip the body read, HMAC and parse, and drain the body in the background.
442
+ if (typeof eventType === "string" && eventType && !GITHUB_VERIFIED_EVENTS.has(eventType)) {
443
+ countGithubIgnoredEvent(eventType);
444
+ githubWebhook.respond(res, 200, { created: false });
445
+ req.resume();
446
+ return true;
447
+ }
448
+
401
449
  const chunks: Buffer[] = [];
402
450
  for await (const chunk of req) {
403
451
  chunks.push(chunk);
@@ -425,6 +425,8 @@ const retryWorkflowRunRoute = route({
425
425
  path: "/api/workflow-runs/{id}/retry",
426
426
  pattern: ["api", "workflow-runs", null, "retry"],
427
427
  summary: "Retry a failed workflow run",
428
+ description:
429
+ "Retries on the definition the run started with; to use an edited workflow, trigger a new run.",
428
430
  tags: ["Workflows"],
429
431
  params: z.object({ id: z.string() }),
430
432
  responses: {
@@ -675,7 +677,9 @@ export async function handleWorkflows(
675
677
  jsonError(res, `Invalid definition: ${validation.errors.join("; ")}`, 400);
676
678
  return true;
677
679
  }
678
- const modelErrors = await workflowModelErrors(parsed.body.definition);
680
+ const modelErrors = await workflowModelErrors(parsed.body.definition, {
681
+ vcsRepo: parsed.body.vcsRepo,
682
+ });
679
683
  if (modelErrors.length > 0) {
680
684
  jsonError(res, `Invalid definition: ${modelErrors.join("; ")}`, 400);
681
685
  return true;
@@ -881,7 +885,16 @@ export async function handleWorkflows(
881
885
  jsonError(res, `Invalid definition: ${validation.errors.join("; ")}`, 400);
882
886
  return true;
883
887
  }
884
- const modelErrors = await workflowModelErrors(body.definition);
888
+ }
889
+ // A stored definition moving to another repo is judged again: its static
890
+ // profiles now check against that repo's credential pool.
891
+ const repoChanged =
892
+ body.vcsRepo !== undefined && (body.vcsRepo ?? null) !== (existing.vcsRepo ?? null);
893
+ const judged = body.definition ?? (repoChanged ? existing.definition : undefined);
894
+ if (judged) {
895
+ const modelErrors = await workflowModelErrors(judged, {
896
+ vcsRepo: body.vcsRepo === undefined ? existing.vcsRepo : body.vcsRepo,
897
+ });
885
898
  if (modelErrors.length > 0) {
886
899
  jsonError(res, `Invalid definition: ${modelErrors.join("; ")}`, 400);
887
900
  return true;
@@ -4,9 +4,11 @@ import {
4
4
  getAgentById,
5
5
  getLatestActiveTaskByContextKey,
6
6
  getLatestTaskByContextKey,
7
+ getLatestTaskByContextKeyPrefix,
7
8
  updateAgentStatusFromCapacity,
8
9
  } from "@/be/db";
9
- import { chatSdkContextKey } from "@/tasks/context-key";
10
+ import { resolveIdentity } from "@/be/identity";
11
+ import { chatSdkContextKey, chatThreadOfContextKey } from "@/tasks/context-key";
10
12
  import type { AgentTask } from "@/types";
11
13
  import { scrubSecrets } from "@/utils/secret-scrubber";
12
14
  import { resolveAdapterApiUrl } from "./adapters";
@@ -36,6 +38,12 @@ export const CHAT_COMMANDS: readonly ChatCommandSpec[] = [
36
38
  { command: "reset", description: "Start over: the next message gets no earlier context" },
37
39
  ];
38
40
 
41
+ /**
42
+ * The shipped Slack manifest declares `/agent-swarm-status` and
43
+ * `/agent-swarm-help`. They run the same commands as `/status` and `/help`.
44
+ */
45
+ const COMMAND_ALIAS_PREFIX = "agent-swarm-";
46
+
39
47
  const RESET_KEY_PREFIX = "swarm:reset:";
40
48
  const RESET_TTL_MS = 30 * 24 * 60 * 60 * 1000;
41
49
  /** Upper bound on the active tasks `/cancel` walks in one chat. */
@@ -85,8 +93,56 @@ async function assigneeLabel(task: AgentTask): Promise<string> {
85
93
  return agent ? `assigned to ${agent.name}` : "assigned to a removed agent";
86
94
  }
87
95
 
88
- async function statusText(contextKey: string): Promise<string> {
89
- const latest = await getLatestTaskByContextKey(contextKey);
96
+ /**
97
+ * Whose tasks a command may touch. `owner` is set for a command that comes from
98
+ * a place several people share (a Slack or Discord channel): it sees and
99
+ * changes only that user's tasks. Without `owner`, the thread belongs to the
100
+ * conversation (a Telegram chat, a Discord thread, a private DM).
101
+ */
102
+ interface CommandTarget {
103
+ threadId: string;
104
+ owner?: string;
105
+ }
106
+
107
+ /**
108
+ * What a chat id names, as a command reports it:
109
+ * - `conversation`: one conversation (Telegram's chat id, a Discord thread or
110
+ * DM, a Slack thread). The command acts on it directly.
111
+ * - `dm`: the channel of a Slack 1:1 DM, which a slash command reports without
112
+ * the conversation in it. Its human is the only requester, so the command
113
+ * acts on the latest conversation there whoever the sender resolves to.
114
+ * - `shared`: a Slack or Discord channel, where several people ask. The command
115
+ * sees and changes only the sender's own tasks. An adapter this does not know
116
+ * counts as shared.
117
+ */
118
+ type CommandScope = "conversation" | "dm" | "shared";
119
+
120
+ function commandScope(threadId: string): CommandScope {
121
+ const separator = threadId.indexOf(":");
122
+ const adapter = threadId.slice(0, separator);
123
+ const parts = threadId.slice(separator + 1).split(":");
124
+ switch (adapter) {
125
+ case "telegram":
126
+ return "conversation";
127
+ case "discord":
128
+ // `<guild>:<channel>[:<thread>]`; a DM has the guild `@me`.
129
+ if (parts[0] === "@me") return "conversation";
130
+ return parts.length <= 2 ? "shared" : "conversation";
131
+ case "slack":
132
+ // `<channel>[:<thread ts>]`; a 1:1 DM channel id starts with `D`.
133
+ if (parts[1]) return "conversation";
134
+ return parts[0]?.startsWith("D") ? "dm" : "shared";
135
+ default:
136
+ return "shared";
137
+ }
138
+ }
139
+
140
+ async function statusText(target: CommandTarget | null): Promise<string> {
141
+ const latest = target
142
+ ? await getLatestTaskByContextKey(chatSdkContextKey(target.threadId), {
143
+ requestedByUserId: target.owner,
144
+ })
145
+ : null;
90
146
  if (!latest) return "No task yet for this chat. Send a message to create one.";
91
147
  const lines = [
92
148
  `Latest task ${shortId(latest)}: ${latest.status}, ${await assigneeLabel(latest)}.`,
@@ -98,20 +154,25 @@ async function statusText(contextKey: string): Promise<string> {
98
154
  }
99
155
 
100
156
  async function cancelActiveTasks(
101
- contextKey: string,
102
- threadId: string,
157
+ target: CommandTarget | null,
103
158
  requestedBy: string,
104
159
  ): Promise<string> {
105
160
  const cancelled: AgentTask[] = [];
106
- for (let i = 0; i < CANCEL_LIMIT; i++) {
107
- const active = await getLatestActiveTaskByContextKey(contextKey, "chat");
108
- if (!active) break;
109
- const task = await cancelTask(active.id, `Cancelled from chat by ${requestedBy}`);
110
- if (!task) break;
111
- if (task.agentId) await updateAgentStatusFromCapacity(task.agentId);
112
- cancelled.push(task);
161
+ if (target) {
162
+ const contextKey = chatSdkContextKey(target.threadId);
163
+ for (let i = 0; i < CANCEL_LIMIT; i++) {
164
+ const active = await getLatestActiveTaskByContextKey(contextKey, "chat", target.owner);
165
+ if (!active) break;
166
+ const task = await cancelTask(active.id, `Cancelled from chat by ${requestedBy}`);
167
+ if (!task) break;
168
+ if (task.agentId) await updateAgentStatusFromCapacity(task.agentId);
169
+ cancelled.push(task);
170
+ }
171
+ // Another user's task may still run in this thread: its indicator stays.
172
+ if (!(await getLatestActiveTaskByContextKey(contextKey, "chat"))) {
173
+ stopTypingKeepalive(target.threadId);
174
+ }
113
175
  }
114
- stopTypingKeepalive(threadId);
115
176
  if (cancelled.length === 0) return "No running task in this chat.";
116
177
  const ids = cancelled.map(shortId).join(", ");
117
178
  return cancelled.length === 1
@@ -119,54 +180,129 @@ async function cancelActiveTasks(
119
180
  : `Cancelled ${cancelled.length} tasks: ${ids}.`;
120
181
  }
121
182
 
122
- /** The reply for one command. Exported for tests; the handler posts it. */
183
+ /**
184
+ * The conversation a command acts on, or null when there is none for this
185
+ * sender. Telegram hands the command its thread id, so the chat's own task is
186
+ * found at once. Slack and Discord hand it the channel, while their tasks are
187
+ * keyed `<channel>:<thread>` (a Slack thread root, a Discord thread made for a
188
+ * mention) or, when Discord cannot open a thread, by the channel itself; a
189
+ * slash command carries no thread. The command then acts on the most recent
190
+ * task in the channel (the most recent running one for `/cancel`). In a shared
191
+ * channel that is the sender's own tasks only: a channel member must not read,
192
+ * cancel or reset another user's conversation, which on Discord may be private,
193
+ * and an unknown sender gets no target. A Slack DM channel has one human, so the
194
+ * sender is not checked there (see `CommandScope`).
195
+ */
196
+ async function resolveCommandTarget(
197
+ threadId: string,
198
+ activeOnly: boolean,
199
+ senderUserId: string | undefined,
200
+ ): Promise<CommandTarget | null> {
201
+ const scope = commandScope(threadId);
202
+ if (scope === "conversation") return { threadId };
203
+ if (scope === "shared" && !senderUserId) return null;
204
+ // A shared channel filters by the sender; a DM has one human and no filter.
205
+ const owner = scope === "shared" ? senderUserId : undefined;
206
+ const contextKey = chatSdkContextKey(threadId);
207
+ const exact = activeOnly
208
+ ? await getLatestActiveTaskByContextKey(contextKey, "chat", owner)
209
+ : await getLatestTaskByContextKey(contextKey, { requestedByUserId: owner });
210
+ const threaded = await getLatestTaskByContextKeyPrefix(
211
+ `${contextKey}${encodeURIComponent(":")}`,
212
+ activeOnly
213
+ ? { activeOnly, source: "chat", requestedByUserId: owner }
214
+ : { requestedByUserId: owner },
215
+ );
216
+ const latest =
217
+ exact && threaded && threaded.createdAt > exact.createdAt ? threaded : (exact ?? threaded);
218
+ const found = chatThreadOfContextKey(latest?.contextKey)?.threadId;
219
+ if (found) return owner ? { threadId: found, owner } : { threadId: found };
220
+ // No task yet in a DM: its conversation is the channel with an empty thread
221
+ // ts, which is where the first message lands, so a reset still applies to it.
222
+ return scope === "dm" ? { threadId: `${threadId}:` } : null;
223
+ }
224
+
225
+ async function resetText(target: CommandTarget | null): Promise<string> {
226
+ if (!target) return "No conversation of yours here to reset.";
227
+ const contextKey = chatSdkContextKey(target.threadId);
228
+ // The mark covers the whole thread. When someone else also asked in it, the
229
+ // mark would cut their context too.
230
+ if (
231
+ target.owner &&
232
+ (await getLatestTaskByContextKey(contextKey, { notRequestedByUserId: target.owner }))
233
+ ) {
234
+ return "Other people also asked in your latest thread, so a reset would change their context. Nothing was reset.";
235
+ }
236
+ await markChatThreadReset(target.threadId);
237
+ const lines = ["Context reset. Your next message starts a new conversation."];
238
+ // A running task is state, not context: it keeps going, and the next task
239
+ // is still created next to it. Only /cancel stops it.
240
+ if (await getLatestActiveTaskByContextKey(contextKey, "chat")) {
241
+ lines.push("A task is still running in this chat. Send /cancel to stop it.");
242
+ }
243
+ return lines.join("\n");
244
+ }
245
+
246
+ /**
247
+ * The reply for one command. Exported for tests; the handler posts it.
248
+ * `senderUserId` is the sender's canonical user, undefined when unknown.
249
+ */
123
250
  export async function runChatCommand(
124
251
  command: string,
125
252
  threadId: string,
126
253
  requestedBy: string,
254
+ senderUserId?: string,
127
255
  ): Promise<string> {
128
- const name = command.replace(/^\//, "").toLowerCase();
256
+ let name = command.replace(/^\//, "").toLowerCase();
257
+ if (name.startsWith(COMMAND_ALIAS_PREFIX)) name = name.slice(COMMAND_ALIAS_PREFIX.length);
129
258
  if (name === "help") return helpText();
130
259
  if (name === "start") return welcomeText();
131
260
  if (!CHAT_COMMANDS.some((c) => c.command === name)) {
132
261
  return `Unknown command /${name}.\n${helpText()}`;
133
262
  }
134
- let contextKey: string;
135
263
  try {
136
- contextKey = chatSdkContextKey(threadId);
264
+ chatSdkContextKey(threadId);
137
265
  } catch {
138
266
  return "This command works only in a chat the swarm can address.";
139
267
  }
140
268
  switch (name) {
141
269
  case "status":
142
- return statusText(contextKey);
270
+ return statusText(await resolveCommandTarget(threadId, false, senderUserId));
143
271
  case "cancel":
144
- return cancelActiveTasks(contextKey, threadId, requestedBy);
145
- case "reset": {
146
- await markChatThreadReset(threadId);
147
- const lines = ["Context reset. Your next message starts a new conversation."];
148
- // A running task is state, not context: it keeps going, and the next task
149
- // is still created next to it. Only /cancel stops it.
150
- if (await getLatestActiveTaskByContextKey(contextKey, "chat")) {
151
- lines.push("A task is still running in this chat. Send /cancel to stop it.");
152
- }
153
- return lines.join("\n");
154
- }
272
+ return cancelActiveTasks(
273
+ await resolveCommandTarget(threadId, true, senderUserId),
274
+ requestedBy,
275
+ );
276
+ case "reset":
277
+ return resetText(await resolveCommandTarget(threadId, false, senderUserId));
155
278
  default:
156
279
  return helpText();
157
280
  }
158
281
  }
159
282
 
283
+ /** The sender's canonical user through the identity registry, undefined when unknown. */
284
+ async function resolveCommandSender(adapter: string, userId: string): Promise<string | undefined> {
285
+ if (!userId || userId.startsWith("chat:")) return undefined;
286
+ try {
287
+ const resolution = await resolveIdentity(adapter, userId);
288
+ return resolution.status === "resolved" ? resolution.userId : undefined;
289
+ } catch (error) {
290
+ console.warn(`[chat-sdk] Could not resolve the command sender: ${errorMessage(error)}`);
291
+ return undefined;
292
+ }
293
+ }
294
+
160
295
  async function onSlashCommand(event: SlashCommandEvent): Promise<void> {
161
296
  const adapter = event.adapter.name;
162
297
  // Telegram passes the thread id as the channel id. Slack and Discord pass
163
- // the channel, so a command there addresses the channel-level thread.
298
+ // the channel; `runChatCommand` resolves it to a thread of that channel.
164
299
  const threadId = event.channel.id;
165
300
  const requestedBy = event.user.userName || event.user.fullName || event.user.userId;
166
301
  console.log(`[chat-sdk] ${adapter} ${threadId}: command ${event.command} from ${requestedBy}`);
167
302
  let reply: string;
168
303
  try {
169
- reply = await runChatCommand(event.command, threadId, requestedBy);
304
+ const senderUserId = await resolveCommandSender(adapter, event.user.userId);
305
+ reply = await runChatCommand(event.command, threadId, requestedBy, senderUserId);
170
306
  } catch (error) {
171
307
  console.warn(
172
308
  scrubSecrets(