@desplega.ai/agent-swarm 2.7.8 → 2.7.10

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 (380) hide show
  1. package/dist/acp-adapter-srfhs1s9.js +16 -0
  2. package/dist/{actions-4m1ct4nh.js → actions-b8aqhrsg.js} +20 -19
  3. package/dist/{amp-adapter-txqh7eqj.js → amp-adapter-4c165vgn.js} +3 -3
  4. package/dist/{anthropic-messages-xey2skwx.js → anthropic-messages-jkva0zps.js} +68 -78
  5. package/dist/app-m9khefrh.js +20 -0
  6. package/dist/{assistant-gd08kr9e.js → assistant-rh4v3ntz.js} +22 -21
  7. package/dist/{azure-openai-responses-26t7j9ra.js → azure-openai-responses-wgtqkbr3.js} +5 -10
  8. package/dist/{boot-args-schema-tjrkpbvm.js → boot-args-schema-hwkc8bzv.js} +1 -1
  9. package/dist/{boot-reembed-21hbck22.js → boot-reembed-5y6yw9sj.js} +1 -1
  10. package/dist/{boot-reembed-mdxd3wgp.js → boot-reembed-fdyk55h4.js} +1 -1
  11. package/dist/{boot-scrub-sweep-qy0zr9t2.js → boot-scrub-sweep-r5r8kqsn.js} +4 -4
  12. package/dist/{boot-seeds-n46eaxdv.js → boot-seeds-8f9zt5cm.js} +5 -4
  13. package/dist/{boxd-nv507va8.js → boxd-qbkxy6ap.js} +1 -1
  14. package/dist/{claude-adapter-j37w2eds.js → claude-adapter-s5df247c.js} +8 -8
  15. package/dist/{claude-managed-adapter-8jvcma9a.js → claude-managed-adapter-h74d06yz.js} +4 -4
  16. package/dist/{claude-managed-setup-rzkjmgc1.js → claude-managed-setup-9gsmwzyx.js} +4 -4
  17. package/dist/{claude-sdk-session-4k7w73t0.js → claude-sdk-session-dq1j4nz9.js} +7901 -7718
  18. package/dist/{cli-s4ss5g59.js → cli-0m7rtm11.js} +5 -5
  19. package/dist/{cli-fzachfnf.js → cli-16phend6.js} +5 -5
  20. package/dist/{cli-yqefz277.js → cli-18qt3few.js} +1 -1
  21. package/dist/{cli-snpj5zbj.js → cli-1z4qggfe.js} +9 -36
  22. package/dist/{cli-s0qnd4wv.js → cli-28fq781p.js} +1 -1
  23. package/dist/{cli-1p89xny0.js → cli-2r0jcc3k.js} +1 -1
  24. package/dist/{cli-66ww7fer.js → cli-2tsfpc70.js} +1 -1
  25. package/dist/{cli-rvtm68yy.js → cli-2xv18ywz.js} +2 -2
  26. package/dist/{cli-kyr67fgx.js → cli-36wdfzgn.js} +18608 -9089
  27. package/dist/{cli-t60ajbbp.js → cli-38yww4e9.js} +20 -20
  28. package/dist/{cli-5xaqj21p.js → cli-3kd08rej.js} +1 -1
  29. package/dist/{cli-ae7mrdf9.js → cli-3vjhs18n.js} +4 -6
  30. package/dist/{cli-ssnjfg5p.js → cli-3xcwp3z8.js} +8 -10
  31. package/dist/{cli-rjknb2ae.js → cli-3xddv0rk.js} +6 -6
  32. package/dist/{cli-az48n0nr.js → cli-4caa1x7d.js} +67 -64
  33. package/dist/cli-4vwxp550.js +9321 -0
  34. package/dist/{cli-pz4rk021.js → cli-54vrpgm0.js} +1 -1
  35. package/dist/{cli-gvx71kqv.js → cli-55bkx8hh.js} +3 -3
  36. package/dist/{cli-r9jqcehk.js → cli-5mpy301f.js} +38 -2
  37. package/dist/{cli-bb0mmdk8.js → cli-5wfz00be.js} +35 -12
  38. package/dist/{cli-btfsp3mv.js → cli-5xcb8gxq.js} +9 -11
  39. package/dist/{cli-4t50yq3j.js → cli-6m6b4bep.js} +29 -12
  40. package/dist/cli-6pzk82fd.js +778 -0
  41. package/dist/{cli-8sdejs1f.js → cli-7wz05bx3.js} +797 -255
  42. package/dist/{cli-mkk9rnzz.js → cli-8bpgbr8k.js} +54 -7
  43. package/dist/{cli-fyhr5h4s.js → cli-8ewkreqd.js} +17 -13
  44. package/dist/{cli-p3vsj0d3.js → cli-an1knn2k.js} +15 -10
  45. package/dist/{cli-0ykgn1h5.js → cli-bxz823sz.js} +2 -2
  46. package/dist/{cli-jdv6ypxs.js → cli-bzvs88tv.js} +2 -2
  47. package/dist/{cli-bshb7jas.js → cli-cr14kftt.js} +3 -3
  48. package/dist/{cli-njwac61j.js → cli-cyn9v8zr.js} +12 -2
  49. package/dist/{cli-a22h291q.js → cli-d6521kb5.js} +1 -1
  50. package/dist/{cli-1b7btd38.js → cli-d84byzn8.js} +869 -5
  51. package/dist/{cli-84rj785g.js → cli-eb2azq8n.js} +9 -9
  52. package/dist/{cli-1cxrbkk6.js → cli-ed6yqpf1.js} +7 -9
  53. package/dist/{cli-wx3rhnm0.js → cli-eddnyg3t.js} +1 -1
  54. package/dist/{cli-ga786dzg.js → cli-eqk5p56g.js} +18 -17
  55. package/dist/{cli-mthwvjre.js → cli-f2zenhja.js} +1 -1
  56. package/dist/{cli-ferkkrg9.js → cli-fjggej24.js} +2 -2
  57. package/dist/{cli-g7s47cc5.js → cli-fsgttth8.js} +123 -102
  58. package/dist/{cli-269q28a1.js → cli-g1px1g2e.js} +27 -6
  59. package/dist/{cli-sq4n7af4.js → cli-h49ejvmc.js} +4 -6
  60. package/dist/{cli-5j0m12ns.js → cli-hfkwwy1h.js} +51 -15
  61. package/dist/{cli-agfm16v9.js → cli-hg42n3hx.js} +12 -12
  62. package/dist/{cli-yndmfxb3.js → cli-hxpyc9sn.js} +3 -3
  63. package/dist/{cli-w4xnbm46.js → cli-j7d73g1y.js} +414 -145
  64. package/dist/{cli-gazw7kpa.js → cli-jg24scat.js} +8 -10
  65. package/dist/{cli-5ja3b75e.js → cli-jrp1dt73.js} +1 -1
  66. package/dist/{cli-98rw5dt5.js → cli-jrzkw01m.js} +2 -2
  67. package/dist/{cli-583frbyr.js → cli-kchjb7qy.js} +1 -1
  68. package/dist/{cli-xr8908my.js → cli-kx4c8j05.js} +32 -17
  69. package/dist/{cli-fmjd0t1y.js → cli-m0cy2vyf.js} +2 -2
  70. package/dist/{cli-c0kqky8y.js → cli-m5akxq8q.js} +1 -1
  71. package/dist/{cli-ycscb2ar.js → cli-m88rpzkh.js} +2 -2
  72. package/dist/{cli-ppjxh6ah.js → cli-mp9aa8g5.js} +10 -12
  73. package/dist/{cli-xq9r2wtt.js → cli-mr97t7cc.js} +679 -247
  74. package/dist/{cli-z75yxkjh.js → cli-n07eecjs.js} +3 -3
  75. package/dist/{cli-7cx2m6t2.js → cli-n515ex5z.js} +16 -16
  76. package/dist/{cli-fy6x31ps.js → cli-n5yexkdg.js} +1 -0
  77. package/dist/{cli-bbw9wj9m.js → cli-n9abj89w.js} +17 -16
  78. package/dist/{cli-ypff1qwp.js → cli-n9ftpys4.js} +7 -7
  79. package/dist/{cli-32m9eda8.js → cli-nj3x45rw.js} +111 -109
  80. package/dist/{cli-6vcp76qk.js → cli-p74md7t8.js} +42 -23
  81. package/dist/{cli-rjcbm574.js → cli-pr0eze3x.js} +2 -2
  82. package/dist/{cli-dq8x79v8.js → cli-pyrxt9gw.js} +198 -3
  83. package/dist/{cli-m0hmeqma.js → cli-q581b386.js} +5 -5
  84. package/dist/{cli-8rpcng8j.js → cli-rjyghzg4.js} +8 -10
  85. package/dist/cli-rkc97c6a.js +39 -0
  86. package/dist/{cli-msg9m2ny.js → cli-rt0ag4x1.js} +9 -11
  87. package/dist/{cli-qd57hhhh.js → cli-rvhdmjvt.js} +6 -10
  88. package/dist/{cli-318r69gq.js → cli-t73cas91.js} +440 -9
  89. package/dist/{cli-q4ebh7h7.js → cli-td33w98c.js} +6 -6
  90. package/dist/{cli-zkky4t5g.js → cli-tmft5dz2.js} +2 -2
  91. package/dist/{cli-q26b9wre.js → cli-tph5wt3y.js} +4 -4
  92. package/dist/{cli-3e4snnzf.js → cli-ttbqe3q4.js} +1 -1
  93. package/dist/{cli-wemma3jd.js → cli-v2fwbnsk.js} +7 -7
  94. package/dist/cli-w3bk0dgv.js +5266 -0
  95. package/dist/{cli-8h0ayw8c.js → cli-x9exydey.js} +6 -6
  96. package/dist/{cli-85gzce7b.js → cli-xbtq4d6s.js} +287 -75
  97. package/dist/{cli-eyg1pa00.js → cli-xd5ebp64.js} +7 -7
  98. package/dist/{cli-g83s9ewh.js → cli-xfjrc279.js} +1 -1
  99. package/dist/{cli-7axf41jq.js → cli-xncjscpm.js} +40 -42
  100. package/dist/{cli-9m8hdawy.js → cli-xvymtmv4.js} +4 -4
  101. package/dist/{cli-81p9jd57.js → cli-yab6sh8p.js} +9 -3
  102. package/dist/{cli-srye3vdt.js → cli-ybjdc978.js} +1 -1
  103. package/dist/{cli-z1srzaf6.js → cli-yz7v0sh4.js} +70 -5
  104. package/dist/{cli-nbsf8yvn.js → cli-z9cs5m0w.js} +9 -9
  105. package/dist/{cli-k5671be5.js → cli-zcfpsfzf.js} +5 -5
  106. package/dist/{cli-vf078p3e.js → cli-zfqg6fzn.js} +1 -1
  107. package/dist/{cli-tpksw2nr.js → cli-zjphdj1a.js} +461 -108
  108. package/dist/cli.js +32 -52
  109. package/dist/{cloudflare-workers-ai-system-one-ef2a980q.js → cloudflare-workers-ai-system-one-9y1zx3pt.js} +2 -2
  110. package/dist/{codex-adapter-88z6psm4.js → codex-adapter-yr60sme6.js} +7 -7
  111. package/dist/{codex-login-74wa4hmq.js → codex-login-bcda78ge.js} +2 -2
  112. package/dist/{codex-session-runner-zwbcwzvx.js → codex-session-runner-pch8x584.js} +8 -8
  113. package/dist/{commands-7amxs716.js → commands-phjfbkv0.js} +3 -3
  114. package/dist/{controller-5rkkc37m.js → controller-jkx994pz.js} +4 -4
  115. package/dist/{controllers-connect-m7d4vxxb.js → controllers-connect-c4448kwa.js} +25 -24
  116. package/dist/{cursor-adapter-x1q18693.js → cursor-adapter-ndebqnm8.js} +2 -2
  117. package/dist/{db-athc68zt.js → db-ef32tbfc.js} +6 -2
  118. package/dist/{db-h2fsfve3.js → db-ez6egt6v.js} +3 -3
  119. package/dist/{devin-adapter-r9phbnc9.js → devin-adapter-z46ep5ph.js} +1 -1
  120. package/dist/{dispatcher-b1yz2bnn.js → dispatcher-g3tt9hs9.js} +19 -18
  121. package/dist/{docker-c1a3gqmf.js → docker-866qpzt9.js} +2 -2
  122. package/dist/{dsh-adapter-e33bkxq9.js → dsh-adapter-tcyn3099.js} +2 -2
  123. package/dist/{e2b-fr12yccx.js → e2b-jkwfhbcv.js} +2 -2
  124. package/dist/{e2b-x6ywzak3.js → e2b-s16txnpx.js} +2 -3
  125. package/dist/{easter-egg-3d-pv5qnzc8.js → easter-egg-3d-e36hk5td.js} +1 -1
  126. package/dist/{embedding-space-b4txbwrk.js → embedding-space-4kyh5qqj.js} +6 -6
  127. package/dist/{embeddings-m6zn6tad.js → embeddings-6a8v4a6t.js} +1 -1
  128. package/dist/{event-bus-g0ka3pbw.js → event-bus-e66gh7cc.js} +1 -1
  129. package/dist/{execute-68nwny8m.js → execute-3cbg0twf.js} +1 -1
  130. package/dist/{external-channel-gkckmhzh.js → external-channel-se646snz.js} +2 -2
  131. package/dist/fx-adapter-yw795hqq.js +19 -0
  132. package/dist/{google-generative-ai-v94hr7h0.js → google-generative-ai-h7s3e9kk.js} +7 -12
  133. package/dist/{google-vertex-g7vr6cf8.js → google-vertex-fhxaafzw.js} +7 -12
  134. package/dist/grok-adapter-ttmcss2j.js +19 -0
  135. package/dist/handlers-17wha3ze.js +33 -0
  136. package/dist/heartbeat-gwewgdms.js +42 -0
  137. package/dist/{hook-q5fv0jy2.js → hook-g3nhexsy.js} +16 -11
  138. package/dist/{hook-w0q2wcrv.js → hook-hq93y5ej.js} +5 -5
  139. package/dist/{http-bxat8dg3.js → http-5a9p4h6y.js} +808 -285
  140. package/dist/{index-pxn30mse.js → index-0eny15vj.js} +8 -8
  141. package/dist/{index-6cxzwfen.js → index-0rvk3vd4.js} +71 -71
  142. package/dist/{index-fvzke5kx.js → index-1qw6f2dc.js} +10 -10
  143. package/dist/{index-cqhqpgrv.js → index-3c5pxbge.js} +1 -1
  144. package/dist/{index-k7fj52d3.js → index-6haqt3v5.js} +12302 -11048
  145. package/dist/index-8arwq8mw.js +34 -0
  146. package/dist/{index-h7f61sy9.js → index-e5pfbsys.js} +3 -3
  147. package/dist/{index-bxrexmfy.js → index-hgn3c961.js} +14 -13
  148. package/dist/{index-h39zbx67.js → index-m5gx1xd6.js} +68 -68
  149. package/dist/{index-5fx3b3kw.js → index-rvccek1w.js} +9 -9
  150. package/dist/{index-fm0czesf.js → index-s72rqgsx.js} +1 -1
  151. package/dist/index-tpw054az.js +38 -0
  152. package/dist/{index-514d9pf6.js → index-w7em4ktq.js} +8 -8
  153. package/dist/index-waq75j2j.js +31 -0
  154. package/dist/{keepalive-qnt21cv0.js → keepalive-1j4n4dmk.js} +4 -4
  155. package/dist/lead-re73kdgc.js +72 -0
  156. package/dist/{llama-cpp-classify-s5c47rwh.js → llama-cpp-classify-nfgswa1m.js} +2 -2
  157. package/dist/{maintenance-btdr68y4.js → maintenance-dmghacy5.js} +1 -1
  158. package/dist/{mistral-conversations-3gjpdb4b.js → mistral-conversations-a45tx39a.js} +29 -51
  159. package/dist/{oauth-refresh-sweep-vczabeh4.js → oauth-refresh-sweep-yy06c03c.js} +3 -3
  160. package/dist/{onboard-k33ezyq8.js → onboard-52f9t5dm.js} +68 -16
  161. package/dist/{openai-codex-responses-8pbxq9h5.js → openai-codex-responses-k9gapdze.js} +7 -11
  162. package/dist/{openai-completions-rm00s912.js → openai-completions-xd579js7.js} +50 -58
  163. package/dist/{openai-decisions-8v957r2r.js → openai-decisions-q3hh60wr.js} +2 -2
  164. package/dist/{openai-responses-agxpf96k.js → openai-responses-4d5dx3c7.js} +5 -10
  165. package/dist/{opencode-adapter-3dst2ka7.js → opencode-adapter-krnh9jkn.js} +6 -6
  166. package/dist/{openrouter-images-3ecegv0d.js → openrouter-images-xr9gme9x.js} +4 -3
  167. package/dist/{otel-impl-13am7a65.js → otel-impl-xjqz6wjj.js} +2 -2
  168. package/dist/{pi-messages-pchtw4he.js → pi-messages-hjbv8v10.js} +28 -12
  169. package/dist/{pi-mono-adapter-c53de1gd.js → pi-mono-adapter-dbxyp0qv.js} +23 -26
  170. package/dist/{pricing-refresh-9fcbnq3f.js → pricing-refresh-ctdr74pd.js} +3 -3
  171. package/dist/{rbac-roles-66j5h4y5.js → rbac-roles-ehv8s10n.js} +12 -3
  172. package/dist/{rbac-roles-gw0p9h3j.js → rbac-roles-q0gr8eyj.js} +16 -2
  173. package/dist/{render-v2-fg8bmdn4.js → render-v2-5b6chvcq.js} +9 -4
  174. package/dist/{resume-1c8kr3nh.js → resume-5a5d2845.js} +7 -7
  175. package/dist/{runtime-tzf9j7tc.js → runtime-khxszyfp.js} +1 -1
  176. package/dist/{session-access-d0atq10j.js → session-access-gj0bjhqg.js} +4 -4
  177. package/dist/{session-source-backfill-0vscqmsa.js → session-source-backfill-2sy0krfk.js} +3 -3
  178. package/dist/{setup-tvfa7rwe.js → setup-7ssfakk1.js} +1 -1
  179. package/dist/{typesafe-system-one-0bmqcxfg.js → typesafe-system-one-f2en2knd.js} +2 -2
  180. package/dist/virtual-modules-pjj0knwf.js +362 -0
  181. package/dist/{work-objects-ks71xqeb.js → work-objects-bf3syvhq.js} +22 -21
  182. package/dist/{worker-follow-up-bfx0h9hg.js → worker-follow-up-38xevga6.js} +19 -18
  183. package/dist/worker-r8mz7a65.js +72 -0
  184. package/dist/{x-vmmye1kb.js → x-2fyrt5pp.js} +2 -2
  185. package/openapi.json +1169 -257
  186. package/package.json +9 -11
  187. package/src/apps/catalog.generated.json +354 -82
  188. package/src/apps/page-validator.ts +134 -2
  189. package/src/assets/key.ts +77 -4
  190. package/src/be/connector-codes.ts +21 -6
  191. package/src/be/db/session-labels.ts +57 -0
  192. package/src/be/db/session-tree.ts +51 -7
  193. package/src/be/db/slack-trees.ts +146 -0
  194. package/src/be/db/tasks/read.ts +124 -7
  195. package/src/be/db-client.ts +8 -2
  196. package/src/be/db.ts +99 -86
  197. package/src/be/event-loop-lag.ts +146 -0
  198. package/src/be/improvements.ts +416 -0
  199. package/src/be/mcp-overflow-sweep.ts +2 -1
  200. package/src/be/memory/providers/sqlite-store.ts +39 -8
  201. package/src/be/migrations/274_improvements.sql +27 -0
  202. package/src/be/migrations/275_task_dispatched_by.sql +8 -0
  203. package/src/be/migrations/278_slack_render_v2_reconcile.sql +108 -0
  204. package/src/be/rbac-roles.ts +123 -1
  205. package/src/be/swarm-config-guard.ts +3 -0
  206. package/src/be/users.ts +58 -1
  207. package/src/cli.tsx +5 -25
  208. package/src/commands/codex-login.ts +1 -1
  209. package/src/commands/context-preamble.ts +258 -0
  210. package/src/commands/e2b.ts +0 -1
  211. package/src/commands/onboard/agent-fs-version.ts +1 -1
  212. package/src/commands/onboard/compose-generator.ts +0 -1
  213. package/src/commands/onboard/dashboard-url.ts +31 -0
  214. package/src/commands/onboard/steps/generate.tsx +17 -1
  215. package/src/commands/onboard/steps/post-dashboard.tsx +9 -3
  216. package/src/commands/onboard.tsx +19 -6
  217. package/src/commands/runner.ts +117 -96
  218. package/src/extensions/catalog.generated.json +3 -3
  219. package/src/extensions/contract-types.generated.ts +1 -1
  220. package/src/heartbeat/heartbeat.ts +5 -4
  221. package/src/hooks/hook.ts +13 -5
  222. package/src/http/all-routes.ts +1 -0
  223. package/src/http/approval-requests.ts +2 -44
  224. package/src/http/auth.ts +5 -4
  225. package/src/http/codex-oauth-accounts.ts +31 -23
  226. package/src/http/codex-oauth-device.ts +1 -1
  227. package/src/http/codex-oauth-keep-warm.ts +1 -1
  228. package/src/http/core.ts +9 -3
  229. package/src/http/improvements.ts +317 -0
  230. package/src/http/index.ts +12 -6
  231. package/src/http/memory.ts +9 -4
  232. package/src/http/operator-actor.ts +2 -1
  233. package/src/http/person-responder.ts +66 -0
  234. package/src/http/sessions.ts +65 -10
  235. package/src/http/tasks.ts +1 -1
  236. package/src/http/user-roles.ts +11 -2
  237. package/src/http/users.ts +194 -104
  238. package/src/http/utils.ts +18 -0
  239. package/src/http/webhooks.ts +48 -0
  240. package/src/integrations/chat-sdk/commands.ts +167 -31
  241. package/src/integrations/chat-sdk/inbound.ts +10 -8
  242. package/src/integrations/chat-sdk/message-text.ts +117 -0
  243. package/src/providers/acp-targets.ts +1 -1
  244. package/src/providers/amp-adapter.ts +1 -1
  245. package/src/providers/codex-adapter.ts +8 -1
  246. package/src/providers/codex-models.ts +4 -3
  247. package/src/providers/codex-oauth/auth-json.ts +14 -18
  248. package/src/providers/codex-oauth/storage.ts +2 -2
  249. package/src/providers/cursor-adapter.ts +1 -1
  250. package/src/providers/dsh-adapter.ts +1 -1
  251. package/src/rbac/legacy-policy.ts +2 -0
  252. package/src/rbac/permissions.ts +10 -0
  253. package/src/scheduler/scheduler.ts +4 -1
  254. package/src/scripts-runtime/executors/quickjs-runner.ts +2 -0
  255. package/src/scripts-runtime/executors/quickjs-structured-clone.ts +180 -0
  256. package/src/scripts-runtime/quickjs-compat.ts +0 -1
  257. package/src/scripts-runtime/types/swarm-extension.d.ts +2 -0
  258. package/src/server.ts +2 -0
  259. package/src/slack/ack.ts +20 -14
  260. package/src/slack/app.ts +332 -10
  261. package/src/slack/handlers.ts +9 -2
  262. package/src/slack/index.ts +7 -1
  263. package/src/slack/lifecycle-lock.ts +29 -0
  264. package/src/slack/render-v2.ts +466 -229
  265. package/src/slack/socket-fence.ts +64 -0
  266. package/src/slack/watcher.ts +42 -8
  267. package/src/tests/api-drain-worker-e2e.test.ts +69 -2
  268. package/src/tests/apps-catalog-drift.test.ts +35 -0
  269. package/src/tests/apps-catalog-table.test.ts +203 -0
  270. package/src/tests/apps-element-assembly.test.ts +28 -0
  271. package/src/tests/apps-schema-form.test.ts +151 -0
  272. package/src/tests/apps-smart-links.test.ts +151 -0
  273. package/src/tests/apps-table-filters-migration.test.ts +96 -0
  274. package/src/tests/apps-table-selection-migration.test.ts +95 -0
  275. package/src/tests/chat-sdk-commands.test.ts +359 -2
  276. package/src/tests/chat-sdk-inbound.test.ts +20 -0
  277. package/src/tests/chat-sdk-slack.test.ts +189 -1
  278. package/src/tests/chatgpt-subscription-session-bench.test.ts +2 -2
  279. package/src/tests/claude-worker-parity.test.ts +2 -2
  280. package/src/tests/codex-adapter.test.ts +30 -0
  281. package/src/tests/codex-login.test.ts +2 -2
  282. package/src/tests/codex-oauth-accounts.test.ts +48 -12
  283. package/src/tests/codex-oauth-credential-info.test.ts +77 -1
  284. package/src/tests/codex-oauth-device.test.ts +1 -1
  285. package/src/tests/codex-oauth-keep-warm.test.ts +2 -2
  286. package/src/tests/codex-oauth.test.ts +25 -4
  287. package/src/tests/codex-pool.test.ts +2 -2
  288. package/src/tests/db-client-busy-retry.test.ts +69 -18
  289. package/src/tests/db-client.test.ts +26 -1
  290. package/src/tests/db-task-read-contract.test.ts +4 -0
  291. package/src/tests/db-task-write-contract.test.ts +2 -0
  292. package/src/tests/deploy-one-box.test.ts +39 -1
  293. package/src/tests/docs-index-footprint.test.js +3 -3
  294. package/src/tests/dsh-adapter.test.ts +1 -1
  295. package/src/tests/event-loop-lag.test.ts +184 -0
  296. package/src/tests/extensions-example-comms-adherence-gate.test.ts +115 -0
  297. package/src/tests/fixtures/onboard/content.compose.yml.txt +0 -4
  298. package/src/tests/fixtures/onboard/dev.compose.yml.txt +0 -3
  299. package/src/tests/fixtures/onboard/full-all.compose.yml.txt +0 -11
  300. package/src/tests/fixtures/onboard/full.compose.yml.txt +0 -11
  301. package/src/tests/fixtures/onboard/research.compose.yml.txt +0 -3
  302. package/src/tests/fixtures/onboard/solo.compose.yml.txt +0 -1
  303. package/src/tests/fixtures/prs-app-definition.json.txt +784 -0
  304. package/src/tests/fixtures/prs-filters-migration.patch.json.txt +318 -0
  305. package/src/tests/fixtures/prs-selection-migration.patch.json.txt +373 -0
  306. package/src/tests/fixtures/runner-identity-refresh.ts +3 -0
  307. package/src/tests/fixtures/runner-legacy-resume-prompt.ts +3 -0
  308. package/src/tests/fixtures/runner-task-start-reads.ts +140 -0
  309. package/src/tests/github-webhook-early-ack.test.ts +144 -0
  310. package/src/tests/hook-ping-me-order.test.ts +85 -0
  311. package/src/tests/http-api-integration.test.ts +2 -0
  312. package/src/tests/http-log-scrubbing.test.ts +68 -2
  313. package/src/tests/improvements-payload.test.ts +200 -0
  314. package/src/tests/improvements-route.test.ts +419 -0
  315. package/src/tests/install-sh-setup-url.test.ts +190 -0
  316. package/src/tests/kv-storage.test.ts +92 -1
  317. package/src/tests/memory-key-paths.test.ts +57 -0
  318. package/src/tests/memory-retrieval-purge.test.ts +19 -0
  319. package/src/tests/onboard-dashboard-output.test.ts +109 -0
  320. package/src/tests/onboard-dashboard-url.test.ts +83 -0
  321. package/src/tests/operator-granted-credentials.test.ts +561 -0
  322. package/src/tests/operator-granted-role-wire.test.ts +222 -0
  323. package/src/tests/quickjs-compat.test.ts +1 -1
  324. package/src/tests/rbac-engine.test.ts +2 -0
  325. package/src/tests/runner-context-preamble.test.ts +552 -0
  326. package/src/tests/runner-context-usage.test.ts +0 -1
  327. package/src/tests/runner-legacy-options.test.ts +55 -0
  328. package/src/tests/runner-slot-reconcile.test.ts +38 -0
  329. package/src/tests/runner-task-start-reads.test.ts +58 -0
  330. package/src/tests/script-connections.test.ts +3 -0
  331. package/src/tests/script-executor-conformance.test.ts +188 -0
  332. package/src/tests/send-task-dispatched-by.test.ts +129 -0
  333. package/src/tests/session-dispatched-tasks.test.ts +115 -0
  334. package/src/tests/session-sharing.test.ts +198 -9
  335. package/src/tests/sessions-tree.test.ts +133 -2
  336. package/src/tests/slack-app-icon.test.ts +4 -0
  337. package/src/tests/slack-dm-implicit-mention.test.ts +236 -0
  338. package/src/tests/slack-file-tools-attachments.test.ts +96 -3
  339. package/src/tests/slack-reaction-config.test.ts +39 -0
  340. package/src/tests/slack-read-boundaries.test.ts +4 -3
  341. package/src/tests/slack-render-v2-query-plans.test.ts +262 -3
  342. package/src/tests/slack-render-v2-reconcile.test.ts +201 -0
  343. package/src/tests/slack-render-v2.test.ts +47 -0
  344. package/src/tests/slack-socket-watchdog.test.ts +748 -0
  345. package/src/tests/submit-improvement-tool.test.ts +82 -0
  346. package/src/tests/tool-annotations.test.ts +1 -1
  347. package/src/tests/vcs-identity-inheritance.test.ts +85 -0
  348. package/src/tools/manage-user.ts +88 -58
  349. package/src/tools/send-task.ts +3 -0
  350. package/src/tools/slack-read.ts +61 -33
  351. package/src/tools/submit-improvement.ts +68 -0
  352. package/src/tools/tool-config.ts +3 -0
  353. package/src/tools/utils.ts +16 -7
  354. package/src/types.ts +5 -0
  355. package/src/utils/request-auth-context.ts +6 -1
  356. package/templates/extensions/comms-adherence-gate/README.md +25 -0
  357. package/templates/extensions/comms-adherence-gate/hooks.ts +100 -11
  358. package/templates/extensions/comms-adherence-gate/manifest.json +1 -1
  359. package/templates/skills/apps/SKILL.md +29 -11
  360. package/templates/skills/apps/content.md +29 -11
  361. package/templates/skills/swarm-scripts/SKILL.md +1 -1
  362. package/templates/skills/swarm-scripts/content.md +1 -1
  363. package/templates/skills/work-on-task/SKILL.md +1 -1
  364. package/templates/skills/work-on-task/content.md +1 -1
  365. package/dist/acp-adapter-vg5hqkvj.js +0 -16
  366. package/dist/app-e00m45gn.js +0 -17
  367. package/dist/cli-5c4hjzne.js +0 -873
  368. package/dist/cli-ae0dnfee.js +0 -20222
  369. package/dist/cli-nn3ysbqk.js +0 -428
  370. package/dist/cli-pc5znp64.js +0 -364
  371. package/dist/fx-adapter-m5jbgd5q.js +0 -19
  372. package/dist/grok-adapter-csvv7sac.js +0 -19
  373. package/dist/handlers-8x5gfbzx.js +0 -32
  374. package/dist/heartbeat-6c2y3267.js +0 -41
  375. package/dist/index-hpfte8jd.js +0 -33
  376. package/dist/index-ncf7yb5s.js +0 -30
  377. package/dist/index-vte6dyeh.js +0 -37
  378. package/dist/lead-4bvftzm6.js +0 -71
  379. package/dist/virtual-modules-efxcp740.js +0 -59
  380. package/dist/worker-e7v2bvm9.js +0 -71
@@ -35,6 +35,9 @@ import {
35
35
  placeholderForConfigKey,
36
36
  assertUrlSafe,
37
37
  init_credential_broker,
38
+ withLoopPath,
39
+ bindLoopPath,
40
+ init_event_loop_lag,
38
41
  isInTransaction,
39
42
  init_db_client,
40
43
  breaksJsonValidity,
@@ -45,6 +48,28 @@ import {
45
48
  getDb2,
46
49
  getDbClient2,
47
50
  init_runtime2,
51
+ CHAT_SDK_ADAPTER_NAMES,
52
+ CHAT_SDK_ADAPTER_SCHEMAS,
53
+ ChatSdkAdaptersDraftSchema,
54
+ firstIssueText,
55
+ isAdapterEntryEnabled,
56
+ init_schema,
57
+ API_DRAIN_MAX_MS_LIMIT,
58
+ init_api_drain2,
59
+ parseEnabledTools,
60
+ init_enabled_tools,
61
+ parseFollowUpGateScheduleIds,
62
+ isFollowUpGateScheduleId,
63
+ init_follow_up_gate_schedule_ids,
64
+ tierConfigKey,
65
+ init_model_tier_keys,
66
+ isInternalConfigKey,
67
+ internalConfigKeyError,
68
+ isReservedConfigKey,
69
+ reservedKeyError,
70
+ validateConfigValue,
71
+ validateExportToEnv,
72
+ init_swarm_config_guard,
48
73
  isEffectiveOutputSchema,
49
74
  init_output_schema,
50
75
  isRuntimePoolsEnabled,
@@ -91,6 +116,7 @@ import {
91
116
  getLatestTaskByContextKey2,
92
117
  getAgentWorkingOnThread2,
93
118
  getAgentWorkingOnContextKey2,
119
+ getLatestTaskByContextKeyPrefix2,
94
120
  getLatestActiveTaskByContextKey2,
95
121
  getLatestLeadTaskByContextKey2,
96
122
  findCompletedTasksInThread2,
@@ -107,28 +133,6 @@ import {
107
133
  init_model_profiles,
108
134
  onTaskStarted,
109
135
  init_task_lifecycle_events,
110
- CHAT_SDK_ADAPTER_NAMES,
111
- CHAT_SDK_ADAPTER_SCHEMAS,
112
- ChatSdkAdaptersDraftSchema,
113
- firstIssueText,
114
- isAdapterEntryEnabled,
115
- init_schema,
116
- API_DRAIN_MAX_MS_LIMIT,
117
- init_api_drain2,
118
- parseEnabledTools,
119
- init_enabled_tools,
120
- parseFollowUpGateScheduleIds,
121
- isFollowUpGateScheduleId,
122
- init_follow_up_gate_schedule_ids,
123
- tierConfigKey,
124
- init_model_tier_keys,
125
- isInternalConfigKey,
126
- internalConfigKeyError,
127
- isReservedConfigKey,
128
- reservedKeyError,
129
- validateConfigValue,
130
- validateExportToEnv,
131
- init_swarm_config_guard,
132
136
  getOAuthApp,
133
137
  getOAuthAppById,
134
138
  getOAuthAppIdByProvider,
@@ -357,17 +361,18 @@ import {
357
361
  recordInlineScriptRun2,
358
362
  exports_db,
359
363
  init_db4
360
- } from "./cli-w4xnbm46.js";
364
+ } from "./cli-j7d73g1y.js";
361
365
  import {
366
+ assertMayActOnOperatorGrantedTarget2,
362
367
  getUserGrant2,
363
368
  init_rbac_roles
364
- } from "./cli-z1srzaf6.js";
369
+ } from "./cli-yz7v0sh4.js";
365
370
  import {
366
371
  ensurePricingSeeded2,
367
372
  ensureRbacSeeded2,
368
373
  ensureModelProfilesSeeded2,
369
374
  init_boot_seeds
370
- } from "./cli-rjknb2ae.js";
375
+ } from "./cli-3xddv0rk.js";
371
376
  import {
372
377
  buildCatalogEntries,
373
378
  listModelCatalog,
@@ -379,11 +384,11 @@ import {
379
384
  requestModelCatalogRefresh2,
380
385
  startPricingRefreshLoop2,
381
386
  init_pricing_refresh
382
- } from "./cli-1cxrbkk6.js";
387
+ } from "./cli-ed6yqpf1.js";
383
388
  import {
384
389
  workflowEventBus2,
385
390
  init_event_bus
386
- } from "./cli-wx3rhnm0.js";
391
+ } from "./cli-eddnyg3t.js";
387
392
  import {
388
393
  slackCode,
389
394
  slackMissingScopeMessage,
@@ -392,10 +397,12 @@ import {
392
397
  externalChannelToolError2,
393
398
  getChannelBlockReason2,
394
399
  init_external_channel
395
- } from "./cli-0ykgn1h5.js";
400
+ } from "./cli-bxz823sz.js";
396
401
  import {
397
402
  noteSlackInboundSideEffect,
398
403
  init_inbound_dispatch,
404
+ runSlackLifecycleExclusive,
405
+ init_lifecycle_lock,
399
406
  terminalReactionEvent,
400
407
  init_reaction_events,
401
408
  withSpan2,
@@ -427,9 +434,9 @@ import {
427
434
  init_responses,
428
435
  getSlackApp2,
429
436
  startSlackApp2,
430
- stopSlackApp2,
437
+ stopSlackAppUnderLifecycleLock2,
431
438
  init_app3
432
- } from "./cli-xq9r2wtt.js";
439
+ } from "./cli-mr97t7cc.js";
433
440
  import {
434
441
  shapeApprovalResolution,
435
442
  init_approval_resolution,
@@ -453,7 +460,7 @@ import {
453
460
  resumeFromChildRun2,
454
461
  initWaitBusSubscriptions2,
455
462
  init_resume
456
- } from "./cli-nbsf8yvn.js";
463
+ } from "./cli-z9cs5m0w.js";
457
464
  import {
458
465
  FilesError,
459
466
  providerPath,
@@ -464,10 +471,14 @@ import {
464
471
  getFileStorageProvider2,
465
472
  init_registry2
466
473
  } from "./cli-3xj33nrx.js";
474
+ import {
475
+ tableToAscii2,
476
+ init_dist4
477
+ } from "./cli-n9ftpys4.js";
467
478
  import {
468
479
  getRuntimePool2,
469
480
  init_db2
470
- } from "./cli-eyg1pa00.js";
481
+ } from "./cli-xd5ebp64.js";
471
482
  import {
472
483
  duplicateGuardedQueryKey,
473
484
  parseQueryParams,
@@ -500,23 +511,23 @@ import {
500
511
  findRoute,
501
512
  route,
502
513
  init_route_def
503
- } from "./cli-fyhr5h4s.js";
514
+ } from "./cli-8ewkreqd.js";
504
515
  import {
505
516
  COMPOSIO_HTTP_METHODS,
506
517
  executeComposioRequest,
507
518
  composioArgsFromParts,
508
519
  init_composio
509
- } from "./cli-s0qnd4wv.js";
520
+ } from "./cli-28fq781p.js";
510
521
  import {
511
522
  ampPinProviderError,
512
523
  ampPinCatalogError,
513
524
  ampModelError,
514
525
  init_amp_models
515
- } from "./cli-3e4snnzf.js";
526
+ } from "./cli-ttbqe3q4.js";
516
527
  import {
517
528
  object,
518
529
  init_v4_mini
519
- } from "./cli-vf078p3e.js";
530
+ } from "./cli-zfqg6fzn.js";
520
531
  import {
521
532
  addMinutes,
522
533
  init_date_fns
@@ -529,11 +540,11 @@ import {
529
540
  init_types2,
530
541
  LlmRater,
531
542
  init_llm
532
- } from "./cli-rvtm68yy.js";
543
+ } from "./cli-2xv18ywz.js";
533
544
  import {
534
545
  loadModelsDevCache,
535
546
  init_modelsdev_cache
536
- } from "./cli-jdv6ypxs.js";
547
+ } from "./cli-bzvs88tv.js";
537
548
  import {
538
549
  require_dist2,
539
550
  ConnectionAuthInputSchema,
@@ -612,7 +623,7 @@ import {
612
623
  init_typecheck,
613
624
  parseSkillContent,
614
625
  init_skill_parser
615
- } from "./cli-tpksw2nr.js";
626
+ } from "./cli-zjphdj1a.js";
616
627
  import {
617
628
  detachedProcessGroup,
618
629
  registerProcessGroup,
@@ -627,7 +638,7 @@ import {
627
638
  ensureToken,
628
639
  ensureTokenOrThrow,
629
640
  init_ensure_token
630
- } from "./cli-fzachfnf.js";
641
+ } from "./cli-16phend6.js";
631
642
  import {
632
643
  require_fast_deep_equal
633
644
  } from "./cli-bhp11egn.js";
@@ -722,7 +733,7 @@ import {
722
733
  validateDefinition,
723
734
  applyDefinitionPatch,
724
735
  init_definition2
725
- } from "./cli-7axf41jq.js";
736
+ } from "./cli-xncjscpm.js";
726
737
  import {
727
738
  isMultiRuntimeEnabled,
728
739
  init_multi_runtime2
@@ -734,7 +745,7 @@ import {
734
745
  } from "./cli-ytyvpye5.js";
735
746
  import {
736
747
  init_v4
737
- } from "./cli-5xaqj21p.js";
748
+ } from "./cli-3kd08rej.js";
738
749
  import {
739
750
  require_dist3
740
751
  } from "./cli-k28wkapa.js";
@@ -743,15 +754,24 @@ import {
743
754
  isSlackLeaveThreadDisabled,
744
755
  leaveSlackThread,
745
756
  init_left_threads
746
- } from "./cli-66ww7fer.js";
757
+ } from "./cli-2tsfpc70.js";
747
758
  import {
748
759
  publicEndpointSsrfOptions,
749
760
  init_mcp_wrapper
750
- } from "./cli-s4ss5g59.js";
761
+ } from "./cli-0m7rtm11.js";
751
762
  import {
752
763
  canProvisionKind,
753
764
  init_runtime_providers
754
- } from "./cli-yndmfxb3.js";
765
+ } from "./cli-hxpyc9sn.js";
766
+ import {
767
+ isRbacEnabled,
768
+ decideAdmission,
769
+ grantLeadEquivalence,
770
+ revokeLeadEquivalence,
771
+ init_elevated_agents,
772
+ can,
773
+ init_rbac
774
+ } from "./cli-cyn9v8zr.js";
755
775
  import {
756
776
  findUserById,
757
777
  findUserByExternalId,
@@ -762,22 +782,15 @@ import {
762
782
  findOrCreateUserByEmail,
763
783
  linkIdentity,
764
784
  unlinkIdentity,
765
- resolveUserByToken,
785
+ resolveUserToken,
766
786
  resolveSessionToken,
767
787
  fingerprintApiKey,
768
788
  init_users
769
- } from "./cli-269q28a1.js";
770
- import {
771
- isRbacEnabled,
772
- decideAdmission,
773
- grantLeadEquivalence,
774
- revokeLeadEquivalence,
775
- init_elevated_agents,
776
- can,
777
- init_rbac
778
- } from "./cli-njwac61j.js";
789
+ } from "./cli-g1px1g2e.js";
779
790
  import {
780
791
  normalizeAssetKey,
792
+ SESSION_RESOURCE_KINDS,
793
+ sessionResourceGroupOf,
781
794
  sessionGroupKey,
782
795
  parseAssetKey,
783
796
  canWriteAssetKey,
@@ -791,7 +804,7 @@ import {
791
804
  init_import,
792
805
  $OpenAPIRegistry,
793
806
  $OpenApiGeneratorV31,
794
- init_dist6,
807
+ init_dist7,
795
808
  init_zod_openapi,
796
809
  AssetKeySchema,
797
810
  ModelTierSchema,
@@ -843,7 +856,7 @@ import {
843
856
  KvNamespaceSchema,
844
857
  KvKeySchema,
845
858
  init_types4
846
- } from "./cli-5j0m12ns.js";
859
+ } from "./cli-hfkwwy1h.js";
847
860
  import {
848
861
  generateDefaultClaudeMd2,
849
862
  generateDefaultSoulMd2,
@@ -854,7 +867,7 @@ import {
854
867
  init_task_attachment_links,
855
868
  contentSha256,
856
869
  init_profile_sync
857
- } from "./cli-dq8x79v8.js";
870
+ } from "./cli-pyrxt9gw.js";
858
871
  import {
859
872
  getSlackConfiguration,
860
873
  init_config4
@@ -866,7 +879,7 @@ import {
866
879
  import {
867
880
  selectCredential,
868
881
  init_credentials2
869
- } from "./cli-g83s9ewh.js";
882
+ } from "./cli-xfjrc279.js";
870
883
  import {
871
884
  findInterpolationTokens,
872
885
  interpolate,
@@ -879,7 +892,7 @@ import {
879
892
  } from "./cli-kf3pxxdg.js";
880
893
  import {
881
894
  init_zod
882
- } from "./cli-k5671be5.js";
895
+ } from "./cli-zcfpsfzf.js";
883
896
  import {
884
897
  safeParse,
885
898
  safeParseAsync,
@@ -894,7 +907,7 @@ import {
894
907
  array2,
895
908
  object2,
896
909
  looseObject,
897
- union2,
910
+ union3,
898
911
  discriminatedUnion,
899
912
  intersection,
900
913
  record2,
@@ -907,11 +920,11 @@ import {
907
920
  ZodIssueCode,
908
921
  datetime,
909
922
  number3
910
- } from "./cli-agfm16v9.js";
923
+ } from "./cli-hg42n3hx.js";
911
924
  import {
912
925
  init_package,
913
926
  package_default
914
- } from "./cli-msg9m2ny.js";
927
+ } from "./cli-rt0ag4x1.js";
915
928
  import {
916
929
  realtimeBus,
917
930
  init_bus
@@ -943,15 +956,6 @@ import {
943
956
  getApiKey,
944
957
  init_api_key
945
958
  } from "./cli-pax9q4ff.js";
946
- import {
947
- scrubSecrets,
948
- scrubObject,
949
- createValueScrubber,
950
- refreshSecretScrubberCache,
951
- registerVolatileSecret,
952
- registerSensitiveKeyName,
953
- init_secret_scrubber
954
- } from "./cli-1b7btd38.js";
955
959
  import {
956
960
  chatgptSubscriptionModelId,
957
961
  isAlias,
@@ -965,8 +969,15 @@ import {
965
969
  harnessModelMismatch,
966
970
  openAICompatibleProviderIds,
967
971
  claudeCatalogModelId,
968
- init_src2
969
- } from "./cli-5c4hjzne.js";
972
+ init_src2,
973
+ scrubSecrets,
974
+ scrubObject,
975
+ createValueScrubber,
976
+ refreshSecretScrubberCache,
977
+ registerVolatileSecret,
978
+ registerSensitiveKeyName,
979
+ init_secret_scrubber
980
+ } from "./cli-d84byzn8.js";
970
981
  import {
971
982
  __toESM,
972
983
  __commonJS,
@@ -1157,7 +1168,7 @@ var init_types = __esm(() => {
1157
1168
  init_v4();
1158
1169
  SUPPORTED_PROTOCOL_VERSIONS = [LATEST_PROTOCOL_VERSION, "2025-06-18", "2025-03-26", "2024-11-05", "2024-10-07"];
1159
1170
  AssertObjectSchema = custom((v) => v !== null && (typeof v === "object" || typeof v === "function"));
1160
- ProgressTokenSchema = union2([string2(), number2().int()]);
1171
+ ProgressTokenSchema = union3([string2(), number2().int()]);
1161
1172
  CursorSchema = string2();
1162
1173
  TaskCreationParamsSchema = looseObject({
1163
1174
  ttl: number2().optional(),
@@ -1193,7 +1204,7 @@ var init_types = __esm(() => {
1193
1204
  ResultSchema = looseObject({
1194
1205
  _meta: RequestMetaSchema.optional()
1195
1206
  });
1196
- RequestIdSchema = union2([string2(), number2().int()]);
1207
+ RequestIdSchema = union3([string2(), number2().int()]);
1197
1208
  JSONRPCRequestSchema = object2({
1198
1209
  jsonrpc: literal2(JSONRPC_VERSION),
1199
1210
  id: RequestIdSchema,
@@ -1227,13 +1238,13 @@ var init_types = __esm(() => {
1227
1238
  data: unknown().optional()
1228
1239
  })
1229
1240
  }).strict();
1230
- JSONRPCMessageSchema = union2([
1241
+ JSONRPCMessageSchema = union3([
1231
1242
  JSONRPCRequestSchema,
1232
1243
  JSONRPCNotificationSchema,
1233
1244
  JSONRPCResultResponseSchema,
1234
1245
  JSONRPCErrorResponseSchema
1235
1246
  ]);
1236
- JSONRPCResponseSchema = union2([JSONRPCResultResponseSchema, JSONRPCErrorResponseSchema]);
1247
+ JSONRPCResponseSchema = union3([JSONRPCResultResponseSchema, JSONRPCErrorResponseSchema]);
1237
1248
  EmptyResultSchema = ResultSchema.strict();
1238
1249
  CancelledNotificationParamsSchema = NotificationsParamsSchema.extend({
1239
1250
  requestId: RequestIdSchema.optional(),
@@ -1378,7 +1389,7 @@ var init_types = __esm(() => {
1378
1389
  TaskSchema = object2({
1379
1390
  taskId: string2(),
1380
1391
  status: TaskStatusSchema,
1381
- ttl: union2([number2(), _null()]),
1392
+ ttl: union3([number2(), _null()]),
1382
1393
  createdAt: string2(),
1383
1394
  lastUpdatedAt: string2(),
1384
1395
  pollInterval: optional2(number2()),
@@ -1484,7 +1495,7 @@ var init_types = __esm(() => {
1484
1495
  params: ReadResourceRequestParamsSchema
1485
1496
  });
1486
1497
  ReadResourceResultSchema = ResultSchema.extend({
1487
- contents: array2(union2([TextResourceContentsSchema, BlobResourceContentsSchema]))
1498
+ contents: array2(union3([TextResourceContentsSchema, BlobResourceContentsSchema]))
1488
1499
  });
1489
1500
  ResourceListChangedNotificationSchema = NotificationSchema.extend({
1490
1501
  method: literal2("notifications/resources/list_changed"),
@@ -1562,14 +1573,14 @@ var init_types = __esm(() => {
1562
1573
  });
1563
1574
  EmbeddedResourceSchema = object2({
1564
1575
  type: literal2("resource"),
1565
- resource: union2([TextResourceContentsSchema, BlobResourceContentsSchema]),
1576
+ resource: union3([TextResourceContentsSchema, BlobResourceContentsSchema]),
1566
1577
  annotations: AnnotationsSchema.optional(),
1567
1578
  _meta: record2(string2(), unknown()).optional()
1568
1579
  });
1569
1580
  ResourceLinkSchema = ResourceSchema.extend({
1570
1581
  type: literal2("resource_link")
1571
1582
  });
1572
- ContentBlockSchema = union2([
1583
+ ContentBlockSchema = union3([
1573
1584
  TextContentSchema,
1574
1585
  ImageContentSchema,
1575
1586
  AudioContentSchema,
@@ -1693,7 +1704,7 @@ var init_types = __esm(() => {
1693
1704
  ]);
1694
1705
  SamplingMessageSchema = object2({
1695
1706
  role: RoleSchema,
1696
- content: union2([SamplingMessageContentBlockSchema, array2(SamplingMessageContentBlockSchema)]),
1707
+ content: union3([SamplingMessageContentBlockSchema, array2(SamplingMessageContentBlockSchema)]),
1697
1708
  _meta: record2(string2(), unknown()).optional()
1698
1709
  });
1699
1710
  CreateMessageRequestParamsSchema = TaskAugmentedRequestParamsSchema.extend({
@@ -1722,7 +1733,7 @@ var init_types = __esm(() => {
1722
1733
  model: string2(),
1723
1734
  stopReason: optional2(_enum2(["endTurn", "stopSequence", "maxTokens", "toolUse"]).or(string2())),
1724
1735
  role: RoleSchema,
1725
- content: union2([SamplingMessageContentBlockSchema, array2(SamplingMessageContentBlockSchema)])
1736
+ content: union3([SamplingMessageContentBlockSchema, array2(SamplingMessageContentBlockSchema)])
1726
1737
  });
1727
1738
  BooleanSchemaSchema = object2({
1728
1739
  type: literal2("boolean"),
@@ -1772,7 +1783,7 @@ var init_types = __esm(() => {
1772
1783
  enumNames: array2(string2()).optional(),
1773
1784
  default: string2().optional()
1774
1785
  });
1775
- SingleSelectEnumSchemaSchema = union2([UntitledSingleSelectEnumSchemaSchema, TitledSingleSelectEnumSchemaSchema]);
1786
+ SingleSelectEnumSchemaSchema = union3([UntitledSingleSelectEnumSchemaSchema, TitledSingleSelectEnumSchemaSchema]);
1776
1787
  UntitledMultiSelectEnumSchemaSchema = object2({
1777
1788
  type: literal2("array"),
1778
1789
  title: string2().optional(),
@@ -1799,9 +1810,9 @@ var init_types = __esm(() => {
1799
1810
  }),
1800
1811
  default: array2(string2()).optional()
1801
1812
  });
1802
- MultiSelectEnumSchemaSchema = union2([UntitledMultiSelectEnumSchemaSchema, TitledMultiSelectEnumSchemaSchema]);
1803
- EnumSchemaSchema = union2([LegacyTitledEnumSchemaSchema, SingleSelectEnumSchemaSchema, MultiSelectEnumSchemaSchema]);
1804
- PrimitiveSchemaDefinitionSchema = union2([EnumSchemaSchema, BooleanSchemaSchema, StringSchemaSchema, NumberSchemaSchema]);
1813
+ MultiSelectEnumSchemaSchema = union3([UntitledMultiSelectEnumSchemaSchema, TitledMultiSelectEnumSchemaSchema]);
1814
+ EnumSchemaSchema = union3([LegacyTitledEnumSchemaSchema, SingleSelectEnumSchemaSchema, MultiSelectEnumSchemaSchema]);
1815
+ PrimitiveSchemaDefinitionSchema = union3([EnumSchemaSchema, BooleanSchemaSchema, StringSchemaSchema, NumberSchemaSchema]);
1805
1816
  ElicitRequestFormParamsSchema = TaskAugmentedRequestParamsSchema.extend({
1806
1817
  mode: literal2("form").optional(),
1807
1818
  message: string2(),
@@ -1817,7 +1828,7 @@ var init_types = __esm(() => {
1817
1828
  elicitationId: string2(),
1818
1829
  url: string2().url()
1819
1830
  });
1820
- ElicitRequestParamsSchema = union2([ElicitRequestFormParamsSchema, ElicitRequestURLParamsSchema]);
1831
+ ElicitRequestParamsSchema = union3([ElicitRequestFormParamsSchema, ElicitRequestURLParamsSchema]);
1821
1832
  ElicitRequestSchema = RequestSchema.extend({
1822
1833
  method: literal2("elicitation/create"),
1823
1834
  params: ElicitRequestParamsSchema
@@ -1831,7 +1842,7 @@ var init_types = __esm(() => {
1831
1842
  });
1832
1843
  ElicitResultSchema = ResultSchema.extend({
1833
1844
  action: _enum2(["accept", "decline", "cancel"]),
1834
- content: preprocess((val) => val === null ? undefined : val, record2(string2(), union2([string2(), number2(), boolean(), array2(string2())])).optional())
1845
+ content: preprocess((val) => val === null ? undefined : val, record2(string2(), union3([string2(), number2(), boolean(), array2(string2())])).optional())
1835
1846
  });
1836
1847
  ResourceTemplateReferenceSchema = object2({
1837
1848
  type: literal2("ref/resource"),
@@ -1842,7 +1853,7 @@ var init_types = __esm(() => {
1842
1853
  name: string2()
1843
1854
  });
1844
1855
  CompleteRequestParamsSchema = BaseRequestParamsSchema.extend({
1845
- ref: union2([PromptReferenceSchema, ResourceTemplateReferenceSchema]),
1856
+ ref: union3([PromptReferenceSchema, ResourceTemplateReferenceSchema]),
1846
1857
  argument: object2({
1847
1858
  name: string2(),
1848
1859
  value: string2()
@@ -1878,7 +1889,7 @@ var init_types = __esm(() => {
1878
1889
  method: literal2("notifications/roots/list_changed"),
1879
1890
  params: NotificationsParamsSchema.optional()
1880
1891
  });
1881
- ClientRequestSchema = union2([
1892
+ ClientRequestSchema = union3([
1882
1893
  PingRequestSchema,
1883
1894
  InitializeRequestSchema,
1884
1895
  CompleteRequestSchema,
@@ -1897,14 +1908,14 @@ var init_types = __esm(() => {
1897
1908
  ListTasksRequestSchema,
1898
1909
  CancelTaskRequestSchema
1899
1910
  ]);
1900
- ClientNotificationSchema = union2([
1911
+ ClientNotificationSchema = union3([
1901
1912
  CancelledNotificationSchema,
1902
1913
  ProgressNotificationSchema,
1903
1914
  InitializedNotificationSchema,
1904
1915
  RootsListChangedNotificationSchema,
1905
1916
  TaskStatusNotificationSchema
1906
1917
  ]);
1907
- ClientResultSchema = union2([
1918
+ ClientResultSchema = union3([
1908
1919
  EmptyResultSchema,
1909
1920
  CreateMessageResultSchema,
1910
1921
  CreateMessageResultWithToolsSchema,
@@ -1914,7 +1925,7 @@ var init_types = __esm(() => {
1914
1925
  ListTasksResultSchema,
1915
1926
  CreateTaskResultSchema
1916
1927
  ]);
1917
- ServerRequestSchema = union2([
1928
+ ServerRequestSchema = union3([
1918
1929
  PingRequestSchema,
1919
1930
  CreateMessageRequestSchema,
1920
1931
  ElicitRequestSchema,
@@ -1924,7 +1935,7 @@ var init_types = __esm(() => {
1924
1935
  ListTasksRequestSchema,
1925
1936
  CancelTaskRequestSchema
1926
1937
  ]);
1927
- ServerNotificationSchema = union2([
1938
+ ServerNotificationSchema = union3([
1928
1939
  CancelledNotificationSchema,
1929
1940
  ProgressNotificationSchema,
1930
1941
  LoggingMessageNotificationSchema,
@@ -1935,7 +1946,7 @@ var init_types = __esm(() => {
1935
1946
  TaskStatusNotificationSchema,
1936
1947
  ElicitationCompleteNotificationSchema
1937
1948
  ]);
1938
- ServerResultSchema = union2([
1949
+ ServerResultSchema = union3([
1939
1950
  EmptyResultSchema,
1940
1951
  InitializeResultSchema,
1941
1952
  CompleteResultSchema,
@@ -20908,7 +20919,7 @@ function startRetryPoller(registry, intervalMs = 5000) {
20908
20919
  if (!waiting)
20909
20920
  continue;
20910
20921
  if (result.waitFor === "workflow.child.finished") {
20911
- const { resumeFromChildRun } = await import("./resume-1c8kr3nh.js");
20922
+ const { resumeFromChildRun } = await import("./resume-5a5d2845.js");
20912
20923
  await resumeFromChildRun(step.id, registry);
20913
20924
  }
20914
20925
  } else {
@@ -21621,7 +21632,7 @@ var init_notify = __esm(() => {
21621
21632
  }
21622
21633
  }
21623
21634
  case "slack": {
21624
- const { getSlackApp } = await import("./app-e00m45gn.js");
21635
+ const { getSlackApp } = await import("./app-m9khefrh.js");
21625
21636
  const app = getSlackApp();
21626
21637
  if (!app) {
21627
21638
  return {
@@ -21739,7 +21750,7 @@ var init_property_match = __esm(() => {
21739
21750
  async function executeRawLlm(config) {
21740
21751
  let modelName = config.model ?? "google/gemini-3-flash-preview";
21741
21752
  try {
21742
- const { createOpenAI } = await import("./index-h39zbx67.js");
21753
+ const { createOpenAI } = await import("./index-m5gx1xd6.js");
21743
21754
  const llmConfig = await resolveWorkflowLlmConfig(config.model);
21744
21755
  modelName = llmConfig.model;
21745
21756
  const provider = createOpenAI({
@@ -21749,7 +21760,7 @@ async function executeRawLlm(config) {
21749
21760
  });
21750
21761
  const model = provider(llmConfig.model);
21751
21762
  if (config.schema) {
21752
- const { generateObject, jsonSchema } = await import("./index-6cxzwfen.js");
21763
+ const { generateObject, jsonSchema } = await import("./index-0rvk3vd4.js");
21753
21764
  const { object } = await generateObject({
21754
21765
  model,
21755
21766
  schema: jsonSchema(config.schema),
@@ -21763,7 +21774,7 @@ async function executeRawLlm(config) {
21763
21774
  output: { result: object, model: modelName }
21764
21775
  };
21765
21776
  }
21766
- const { generateText } = await import("./index-6cxzwfen.js");
21777
+ const { generateText } = await import("./index-0rvk3vd4.js");
21767
21778
  const { text } = await generateText({
21768
21779
  model,
21769
21780
  prompt: config.prompt
@@ -22320,8 +22331,8 @@ var init_validate2 = __esm(() => {
22320
22331
  const interpolatedPrompt = this.deps.interpolate(prompt, context);
22321
22332
  const outputStr = typeof targetOutput === "string" ? targetOutput : JSON.stringify(targetOutput);
22322
22333
  try {
22323
- const { createOpenAI } = await import("./index-h39zbx67.js");
22324
- const { generateObject, jsonSchema } = await import("./index-6cxzwfen.js");
22334
+ const { createOpenAI } = await import("./index-m5gx1xd6.js");
22335
+ const { generateObject, jsonSchema } = await import("./index-0rvk3vd4.js");
22325
22336
  const llmConfig = await resolveWorkflowLlmConfig();
22326
22337
  const provider = createOpenAI({
22327
22338
  baseURL: llmConfig.baseURL,
@@ -22395,7 +22406,7 @@ var init_vcs = __esm(() => {
22395
22406
  });
22396
22407
  VcsOutputSchema = object2({
22397
22408
  url: string2(),
22398
- id: union2([string2(), number2()])
22409
+ id: union3([string2(), number2()])
22399
22410
  });
22400
22411
  VcsExecutor = class VcsExecutor extends BaseExecutor {
22401
22412
  type = "vcs";
@@ -23134,7 +23145,7 @@ function startScheduler2(registry, intervalMs = 1e4, opts) {
23134
23145
  if (schedulerRun !== run)
23135
23146
  return;
23136
23147
  schedulerInterval = setInterval(() => {
23137
- processSchedules().catch((err) => console.error("[Scheduler] Poll failed:", err));
23148
+ withLoopPath("scheduler.poll", () => processSchedules()).catch((err) => console.error("[Scheduler] Poll failed:", err));
23138
23149
  }, intervalMs);
23139
23150
  await processSchedules();
23140
23151
  }).catch((err) => console.error("[Scheduler] Poll failed:", err));
@@ -23232,6 +23243,7 @@ var init_scheduler = __esm(() => {
23232
23243
  init_workflows();
23233
23244
  init_engine();
23234
23245
  init_triggers();
23246
+ init_event_loop_lag();
23235
23247
  init_business_use();
23236
23248
  init_secret_scrubber();
23237
23249
  init_deferred_task_waits();
@@ -25016,7 +25028,7 @@ function setPreloadedTools(server, names) {
25016
25028
  async function applyPreToolCall(name, args, requestInfo, inputSchema) {
25017
25029
  if (requestInfo.callOrigin !== "mcp")
25018
25030
  return { args };
25019
- const dispatcher = await import("./dispatcher-b1yz2bnn.js");
25031
+ const dispatcher = await import("./dispatcher-g3tt9hs9.js");
25020
25032
  const result = await dispatcher.dispatchPre("pre.tool.call", { tool: name, args, requestInfo }, inputSchema ? {
25021
25033
  validateModify: async (data) => {
25022
25034
  const schema = normalizeObjectSchema(inputSchema) ?? inputSchema;
@@ -25201,7 +25213,7 @@ ${preview}`));
25201
25213
  return (name, config, cb) => {
25202
25214
  const toolConfig = preloadedToolsByServer.get(server)?.has(name) ? { ...config, _meta: { ...config._meta, "anthropic/alwaysLoad": true } } : config;
25203
25215
  if (config.inputSchema === undefined) {
25204
- return server.registerTool(name, toolConfig, async (meta) => {
25216
+ const handler = async (meta) => {
25205
25217
  const requestInfo = getRequestInfo(meta);
25206
25218
  return withSpan2("mcp.tool", async (span) => {
25207
25219
  const pre = await applyPreToolCall(name, {}, requestInfo);
@@ -25220,9 +25232,10 @@ ${preview}`));
25220
25232
  span.setAttributes(toolResultAttributes(result));
25221
25233
  return result;
25222
25234
  }, toolRequestAttributes(name, requestInfo));
25223
- });
25235
+ };
25236
+ return server.registerTool(name, toolConfig, bindLoopPath(`mcp.tool ${name}`, handler));
25224
25237
  }
25225
- return server.registerTool(name, toolConfig, async (args, meta) => {
25238
+ const handler = async (args, meta) => {
25226
25239
  const requestInfo = getRequestInfo(meta);
25227
25240
  return withSpan2(`mcp.tool ${name}`, async (span) => {
25228
25241
  const pre = await applyPreToolCall(name, args, requestInfo, config.inputSchema);
@@ -25242,13 +25255,15 @@ ${preview}`));
25242
25255
  span.setAttributes(toolResultAttributes(result));
25243
25256
  return result;
25244
25257
  }, toolRequestAttributes(name, requestInfo, args));
25245
- });
25258
+ };
25259
+ return server.registerTool(name, toolConfig, bindLoopPath(`mcp.tool ${name}`, handler));
25246
25260
  };
25247
25261
  };
25248
25262
  var init_utils = __esm(() => {
25249
25263
  init_zod_compat();
25250
25264
  init_zod();
25251
25265
  init_db4();
25266
+ init_event_loop_lag();
25252
25267
  init_kv_overflow();
25253
25268
  init_kv_view();
25254
25269
  init_otel();
@@ -32494,7 +32509,7 @@ async function loadAdapter(name, config, logger) {
32494
32509
  const base = { ...config, apiUrl, logger };
32495
32510
  switch (name) {
32496
32511
  case "telegram": {
32497
- const { TelegramAdapter } = await import("./index-5fx3b3kw.js");
32512
+ const { TelegramAdapter } = await import("./index-rvccek1w.js");
32498
32513
 
32499
32514
  class SwarmTelegramAdapter extends TelegramAdapter {
32500
32515
  isBotMentioned(message, text) {
@@ -32508,7 +32523,7 @@ async function loadAdapter(name, config, logger) {
32508
32523
  });
32509
32524
  }
32510
32525
  case "slack": {
32511
- const { createSlackAdapter } = await import("./index-pxn30mse.js");
32526
+ const { createSlackAdapter } = await import("./index-0eny15vj.js");
32512
32527
  return createSlackAdapter({
32513
32528
  ...base,
32514
32529
  signingSecret: config.signingSecret ?? "",
@@ -32518,7 +32533,7 @@ async function loadAdapter(name, config, logger) {
32518
32533
  });
32519
32534
  }
32520
32535
  case "discord": {
32521
- const { createDiscordAdapter } = await import("./index-514d9pf6.js");
32536
+ const { createDiscordAdapter } = await import("./index-w7em4ktq.js");
32522
32537
  return createDiscordAdapter({
32523
32538
  ...base,
32524
32539
  logger: withInfoFilter(logger, keepDiscordInfoLine),
@@ -32527,7 +32542,7 @@ async function loadAdapter(name, config, logger) {
32527
32542
  });
32528
32543
  }
32529
32544
  case "teams": {
32530
- const { createTeamsAdapter } = await import("./index-fvzke5kx.js");
32545
+ const { createTeamsAdapter } = await import("./index-1qw6f2dc.js");
32531
32546
  const { teamsWebhookVerifier, teamsToken } = getChatSdkTestHooks();
32532
32547
  return createTeamsAdapter({
32533
32548
  ...base,
@@ -32736,7 +32751,7 @@ async function readPersistedThreadHistory(threadId) {
32736
32751
  const rows = await new SqliteChatState().getList(`${SDK_THREAD_HISTORY_PREFIX}${threadId}`);
32737
32752
  if (rows.length === 0)
32738
32753
  return [];
32739
- const { Message: MessageClass } = await import("./index-h7f61sy9.js");
32754
+ const { Message: MessageClass } = await import("./index-e5pfbsys.js");
32740
32755
  return rows.map((row) => MessageClass.fromJSON(row));
32741
32756
  }
32742
32757
  var SDK_THREAD_HISTORY_PREFIX = "msg-history:";
@@ -32927,8 +32942,29 @@ async function assigneeLabel(task) {
32927
32942
  const agent = await getAgentById2(task.agentId);
32928
32943
  return agent ? `assigned to ${agent.name}` : "assigned to a removed agent";
32929
32944
  }
32930
- async function statusText(contextKey) {
32931
- const latest = await getLatestTaskByContextKey2(contextKey);
32945
+ function commandScope(threadId) {
32946
+ const separator = threadId.indexOf(":");
32947
+ const adapter = threadId.slice(0, separator);
32948
+ const parts = threadId.slice(separator + 1).split(":");
32949
+ switch (adapter) {
32950
+ case "telegram":
32951
+ return "conversation";
32952
+ case "discord":
32953
+ if (parts[0] === "@me")
32954
+ return "conversation";
32955
+ return parts.length <= 2 ? "shared" : "conversation";
32956
+ case "slack":
32957
+ if (parts[1])
32958
+ return "conversation";
32959
+ return parts[0]?.startsWith("D") ? "dm" : "shared";
32960
+ default:
32961
+ return "shared";
32962
+ }
32963
+ }
32964
+ async function statusText(target) {
32965
+ const latest = target ? await getLatestTaskByContextKey2(chatSdkContextKey(target.threadId), {
32966
+ requestedByUserId: target.owner
32967
+ }) : null;
32932
32968
  if (!latest)
32933
32969
  return "No task yet for this chat. Send a message to create one.";
32934
32970
  const lines = [
@@ -32940,27 +32976,65 @@ async function statusText(contextKey) {
32940
32976
  return lines.join(`
32941
32977
  `);
32942
32978
  }
32943
- async function cancelActiveTasks(contextKey, threadId, requestedBy) {
32979
+ async function cancelActiveTasks(target, requestedBy) {
32944
32980
  const cancelled = [];
32945
- for (let i = 0;i < CANCEL_LIMIT; i++) {
32946
- const active = await getLatestActiveTaskByContextKey2(contextKey, "chat");
32947
- if (!active)
32948
- break;
32949
- const task = await cancelTask2(active.id, `Cancelled from chat by ${requestedBy}`);
32950
- if (!task)
32951
- break;
32952
- if (task.agentId)
32953
- await updateAgentStatusFromCapacity2(task.agentId);
32954
- cancelled.push(task);
32981
+ if (target) {
32982
+ const contextKey = chatSdkContextKey(target.threadId);
32983
+ for (let i = 0;i < CANCEL_LIMIT; i++) {
32984
+ const active = await getLatestActiveTaskByContextKey2(contextKey, "chat", target.owner);
32985
+ if (!active)
32986
+ break;
32987
+ const task = await cancelTask2(active.id, `Cancelled from chat by ${requestedBy}`);
32988
+ if (!task)
32989
+ break;
32990
+ if (task.agentId)
32991
+ await updateAgentStatusFromCapacity2(task.agentId);
32992
+ cancelled.push(task);
32993
+ }
32994
+ if (!await getLatestActiveTaskByContextKey2(contextKey, "chat")) {
32995
+ stopTypingKeepalive(target.threadId);
32996
+ }
32955
32997
  }
32956
- stopTypingKeepalive(threadId);
32957
32998
  if (cancelled.length === 0)
32958
32999
  return "No running task in this chat.";
32959
33000
  const ids = cancelled.map(shortId).join(", ");
32960
33001
  return cancelled.length === 1 ? `Cancelled task ${ids}.` : `Cancelled ${cancelled.length} tasks: ${ids}.`;
32961
33002
  }
32962
- async function runChatCommand(command, threadId, requestedBy) {
32963
- const name = command.replace(/^\//, "").toLowerCase();
33003
+ async function resolveCommandTarget(threadId, activeOnly, senderUserId) {
33004
+ const scope = commandScope(threadId);
33005
+ if (scope === "conversation")
33006
+ return { threadId };
33007
+ if (scope === "shared" && !senderUserId)
33008
+ return null;
33009
+ const owner = scope === "shared" ? senderUserId : undefined;
33010
+ const contextKey = chatSdkContextKey(threadId);
33011
+ const exact = activeOnly ? await getLatestActiveTaskByContextKey2(contextKey, "chat", owner) : await getLatestTaskByContextKey2(contextKey, { requestedByUserId: owner });
33012
+ const threaded = await getLatestTaskByContextKeyPrefix2(`${contextKey}${encodeURIComponent(":")}`, activeOnly ? { activeOnly, source: "chat", requestedByUserId: owner } : { requestedByUserId: owner });
33013
+ const latest = exact && threaded && threaded.createdAt > exact.createdAt ? threaded : exact ?? threaded;
33014
+ const found = chatThreadOfContextKey(latest?.contextKey)?.threadId;
33015
+ if (found)
33016
+ return owner ? { threadId: found, owner } : { threadId: found };
33017
+ return scope === "dm" ? { threadId: `${threadId}:` } : null;
33018
+ }
33019
+ async function resetText(target) {
33020
+ if (!target)
33021
+ return "No conversation of yours here to reset.";
33022
+ const contextKey = chatSdkContextKey(target.threadId);
33023
+ if (target.owner && await getLatestTaskByContextKey2(contextKey, { notRequestedByUserId: target.owner })) {
33024
+ return "Other people also asked in your latest thread, so a reset would change their context. Nothing was reset.";
33025
+ }
33026
+ await markChatThreadReset(target.threadId);
33027
+ const lines = ["Context reset. Your next message starts a new conversation."];
33028
+ if (await getLatestActiveTaskByContextKey2(contextKey, "chat")) {
33029
+ lines.push("A task is still running in this chat. Send /cancel to stop it.");
33030
+ }
33031
+ return lines.join(`
33032
+ `);
33033
+ }
33034
+ async function runChatCommand(command, threadId, requestedBy, senderUserId) {
33035
+ let name = command.replace(/^\//, "").toLowerCase();
33036
+ if (name.startsWith(COMMAND_ALIAS_PREFIX))
33037
+ name = name.slice(COMMAND_ALIAS_PREFIX.length);
32964
33038
  if (name === "help")
32965
33039
  return helpText();
32966
33040
  if (name === "start")
@@ -32969,30 +33043,33 @@ async function runChatCommand(command, threadId, requestedBy) {
32969
33043
  return `Unknown command /${name}.
32970
33044
  ${helpText()}`;
32971
33045
  }
32972
- let contextKey;
32973
33046
  try {
32974
- contextKey = chatSdkContextKey(threadId);
33047
+ chatSdkContextKey(threadId);
32975
33048
  } catch {
32976
33049
  return "This command works only in a chat the swarm can address.";
32977
33050
  }
32978
33051
  switch (name) {
32979
33052
  case "status":
32980
- return statusText(contextKey);
33053
+ return statusText(await resolveCommandTarget(threadId, false, senderUserId));
32981
33054
  case "cancel":
32982
- return cancelActiveTasks(contextKey, threadId, requestedBy);
32983
- case "reset": {
32984
- await markChatThreadReset(threadId);
32985
- const lines = ["Context reset. Your next message starts a new conversation."];
32986
- if (await getLatestActiveTaskByContextKey2(contextKey, "chat")) {
32987
- lines.push("A task is still running in this chat. Send /cancel to stop it.");
32988
- }
32989
- return lines.join(`
32990
- `);
32991
- }
33055
+ return cancelActiveTasks(await resolveCommandTarget(threadId, true, senderUserId), requestedBy);
33056
+ case "reset":
33057
+ return resetText(await resolveCommandTarget(threadId, false, senderUserId));
32992
33058
  default:
32993
33059
  return helpText();
32994
33060
  }
32995
33061
  }
33062
+ async function resolveCommandSender(adapter, userId) {
33063
+ if (!userId || userId.startsWith("chat:"))
33064
+ return;
33065
+ try {
33066
+ const resolution = await resolveIdentity(adapter, userId);
33067
+ return resolution.status === "resolved" ? resolution.userId : undefined;
33068
+ } catch (error) {
33069
+ console.warn(`[chat-sdk] Could not resolve the command sender: ${errorMessage(error)}`);
33070
+ return;
33071
+ }
33072
+ }
32996
33073
  async function onSlashCommand(event) {
32997
33074
  const adapter = event.adapter.name;
32998
33075
  const threadId = event.channel.id;
@@ -33000,7 +33077,8 @@ async function onSlashCommand(event) {
33000
33077
  console.log(`[chat-sdk] ${adapter} ${threadId}: command ${event.command} from ${requestedBy}`);
33001
33078
  let reply;
33002
33079
  try {
33003
- reply = await runChatCommand(event.command, threadId, requestedBy);
33080
+ const senderUserId = await resolveCommandSender(adapter, event.user.userId);
33081
+ reply = await runChatCommand(event.command, threadId, requestedBy, senderUserId);
33004
33082
  } catch (error) {
33005
33083
  console.warn(scrubSecrets(`[chat-sdk] ${threadId}: command ${event.command} failed: ${errorMessage(error)}`));
33006
33084
  reply = "The command failed. Check the API log.";
@@ -33029,9 +33107,10 @@ async function registerTelegramCommands(config) {
33029
33107
  commands: CHAT_COMMANDS.map((c) => ({ command: c.command, description: c.description }))
33030
33108
  });
33031
33109
  }
33032
- var CHAT_COMMANDS, RESET_KEY_PREFIX = "swarm:reset:", RESET_TTL_MS, CANCEL_LIMIT = 20;
33110
+ var CHAT_COMMANDS, COMMAND_ALIAS_PREFIX = "agent-swarm-", RESET_KEY_PREFIX = "swarm:reset:", RESET_TTL_MS, CANCEL_LIMIT = 20;
33033
33111
  var init_commands = __esm(() => {
33034
33112
  init_db4();
33113
+ init_identity();
33035
33114
  init_context_key();
33036
33115
  init_secret_scrubber();
33037
33116
  init_adapters();
@@ -33173,9 +33252,47 @@ async function rememberSessionLabel(key, label, ttlMs) {
33173
33252
  expiresAt: ttlMs === undefined ? null : Date.now() + ttlMs
33174
33253
  });
33175
33254
  }
33176
- var NAMESPACE = "session-labels";
33255
+ async function getResourceSessionLabels(keys) {
33256
+ const groups = keys.flatMap((key) => {
33257
+ const resource = sessionResourceGroupOf(key);
33258
+ return resource ? [{ key, resource }] : [];
33259
+ });
33260
+ const labels = {};
33261
+ for (const { key, resource } of groups) {
33262
+ if (resource.action)
33263
+ labels[key] = resource.action;
33264
+ }
33265
+ const rowId = (resource) => resource.kind === "fs" ? resource.id.slice(resource.id.lastIndexOf(":") + 1) : resource.id;
33266
+ await Promise.all(SESSION_RESOURCE_KINDS.map(async (kind) => {
33267
+ const wanted = groups.filter(({ resource }) => resource.kind === kind && !resource.action);
33268
+ if (wanted.length === 0)
33269
+ return;
33270
+ const ids = [...new Set(wanted.map(({ resource }) => rowId(resource)))];
33271
+ const { table, column } = RESOURCE_NAMES[kind];
33272
+ const rows = await getDbClient2().query(`SELECT lower(id) AS id, NULLIF(trim(${column}), '') AS name FROM ${table}
33273
+ WHERE id IN (${ids.map(() => "?").join(", ")})`, ids);
33274
+ const names = new Map(rows.map((row) => [row.id, row.name]));
33275
+ for (const { key, resource } of wanted) {
33276
+ const name = names.get(rowId(resource));
33277
+ if (!name)
33278
+ continue;
33279
+ labels[key] = kind === "fs" ? name.replace(/\/+$/, "").split("/").pop() || name : name;
33280
+ }
33281
+ }));
33282
+ return labels;
33283
+ }
33284
+ var NAMESPACE = "session-labels", RESOURCE_NAMES;
33177
33285
  var init_session_labels = __esm(() => {
33286
+ init_key();
33178
33287
  init_db4();
33288
+ RESOURCE_NAMES = {
33289
+ page: { table: "pages", column: "title" },
33290
+ workflow: { table: "workflows", column: "name" },
33291
+ schedule: { table: "scheduled_tasks", column: "name" },
33292
+ app: { table: "apps", column: "name" },
33293
+ script: { table: "scripts", column: "name" },
33294
+ fs: { table: "asset_key_mappings", column: "provider_key" }
33295
+ };
33179
33296
  });
33180
33297
 
33181
33298
  // src/be/unmapped-identities.ts
@@ -33626,6 +33743,95 @@ var init_attachments = __esm(() => {
33626
33743
  CHAT_INBOUND_FILE_LIMITS = { telegram: 20 * MB };
33627
33744
  });
33628
33745
 
33746
+ // src/integrations/chat-sdk/message-text.ts
33747
+ function chatMessageText(message) {
33748
+ try {
33749
+ const rendered = message.formatted ? renderBlocks(message.formatted).trim() : "";
33750
+ if (rendered)
33751
+ return rendered;
33752
+ } catch {}
33753
+ return message.text ?? "";
33754
+ }
33755
+ function renderBlocks(node) {
33756
+ return (node.children ?? []).map(render).join(`
33757
+
33758
+ `);
33759
+ }
33760
+ function renderInline(node) {
33761
+ return (node.children ?? []).map(render).join("");
33762
+ }
33763
+ function inlineCode(value) {
33764
+ const longest = Math.max(0, ...(value.match(/`+/g) ?? []).map((run) => run.length));
33765
+ const fence = "`".repeat(longest + 1);
33766
+ const pad = value.startsWith("`") || value.endsWith("`") ? " " : "";
33767
+ return `${fence}${pad}${value}${pad}${fence}`;
33768
+ }
33769
+ function codeBlock(value, lang) {
33770
+ const longest = Math.max(2, ...(value.match(/`{3,}/gm) ?? []).map((run) => run.length));
33771
+ const fence = "`".repeat(longest + 1);
33772
+ return `${fence}${lang ?? ""}
33773
+ ${value}
33774
+ ${fence}`;
33775
+ }
33776
+ function renderList(node) {
33777
+ const start = node.start ?? 1;
33778
+ return (node.children ?? []).map((item, index) => {
33779
+ const marker = node.ordered ? `${start + index}. ` : "- ";
33780
+ const pad = " ".repeat(marker.length);
33781
+ const [first = "", ...rest] = (item.children ?? []).map(render).join(`
33782
+ `).split(`
33783
+ `);
33784
+ return [`${marker}${first}`, ...rest.map((line) => line ? pad + line : line)].join(`
33785
+ `);
33786
+ }).join(`
33787
+ `);
33788
+ }
33789
+ function render(node) {
33790
+ switch (node.type) {
33791
+ case "text":
33792
+ case "html":
33793
+ return node.value ?? "";
33794
+ case "inlineCode":
33795
+ return inlineCode(node.value ?? "");
33796
+ case "code":
33797
+ return codeBlock(node.value ?? "", node.lang);
33798
+ case "link": {
33799
+ const label = renderInline(node);
33800
+ return !label || label === node.url ? node.url ?? "" : `[${label}](${node.url ?? ""})`;
33801
+ }
33802
+ case "image":
33803
+ return `![${node.alt ?? ""}](${node.url ?? ""})`;
33804
+ case "strong":
33805
+ return `**${renderInline(node)}**`;
33806
+ case "emphasis":
33807
+ return `_${renderInline(node)}_`;
33808
+ case "delete":
33809
+ return `~~${renderInline(node)}~~`;
33810
+ case "break":
33811
+ return `
33812
+ `;
33813
+ case "thematicBreak":
33814
+ return "---";
33815
+ case "heading":
33816
+ return `${"#".repeat(node.depth ?? 1)} ${renderInline(node)}`;
33817
+ case "blockquote":
33818
+ return renderBlocks(node).split(`
33819
+ `).map((line) => `> ${line}`.trimEnd()).join(`
33820
+ `);
33821
+ case "list":
33822
+ return renderList(node);
33823
+ case "table":
33824
+ return codeBlock(tableToAscii2(node), null);
33825
+ case "paragraph":
33826
+ return renderInline(node);
33827
+ default:
33828
+ return node.children ? renderBlocks(node) : node.value ?? "";
33829
+ }
33830
+ }
33831
+ var init_message_text2 = __esm(() => {
33832
+ init_dist4();
33833
+ });
33834
+
33629
33835
  // src/integrations/chat-sdk/limits.ts
33630
33836
  function chatMessageLimit(adapter) {
33631
33837
  return CHAT_MESSAGE_LIMITS[adapter] ?? FALLBACK_LIMIT;
@@ -34276,7 +34482,7 @@ async function handleChatInbound(thread, message, kind) {
34276
34482
  text: message.text,
34277
34483
  messageId: message.id
34278
34484
  });
34279
- let text = stripBotMention(message.text ?? "", thread.adapter);
34485
+ let text = stripBotMention(chatMessageText(message), thread.adapter);
34280
34486
  const immediate = /^!now\b/i.test(text);
34281
34487
  if (immediate)
34282
34488
  text = text.replace(/^!now\s*/i, "").trim();
@@ -34403,12 +34609,12 @@ async function getChatThreadContext(thread, exclude, since) {
34403
34609
  byId.set(m.id, m);
34404
34610
  for (const m of thread.recentMessages)
34405
34611
  byId.set(m.id, m);
34406
- return [...byId.values()].sort((a, b) => a.metadata.dateSent.getTime() - b.metadata.dateSent.getTime()).filter((m) => !exclude.has(m.id) && m.text.trim() !== "").filter((m) => since === null || m.metadata.dateSent.getTime() > since.getTime()).slice(-THREAD_CONTEXT_LIMIT).map((m) => {
34612
+ return [...byId.values()].sort((a, b) => a.metadata.dateSent.getTime() - b.metadata.dateSent.getTime()).map((m) => ({ m, text: chatMessageText(m) })).filter(({ m, text }) => !exclude.has(m.id) && text.trim() !== "").filter(({ m }) => since === null || m.metadata.dateSent.getTime() > since.getTime()).slice(-THREAD_CONTEXT_LIMIT).map(({ m, text }) => {
34407
34613
  if (m.author.isMe || m.author.isBot === true) {
34408
- const truncated = m.text.length > AGENT_MESSAGE_TRUNCATE ? `${m.text.slice(0, AGENT_MESSAGE_TRUNCATE)}...` : m.text;
34614
+ const truncated = text.length > AGENT_MESSAGE_TRUNCATE ? `${text.slice(0, AGENT_MESSAGE_TRUNCATE)}...` : text;
34409
34615
  return `[Agent]: ${truncated}`;
34410
34616
  }
34411
- return `${m.author.userName || m.author.fullName || m.author.userId}: ${m.text}`;
34617
+ return `${m.author.userName || m.author.fullName || m.author.userId}: ${text}`;
34412
34618
  }).join(`
34413
34619
  `);
34414
34620
  } catch (error) {
@@ -34666,6 +34872,7 @@ var init_inbound = __esm(() => {
34666
34872
  init_commands();
34667
34873
  init_facts();
34668
34874
  init_logger();
34875
+ init_message_text2();
34669
34876
  init_outbound2();
34670
34877
  init_reactions3();
34671
34878
  init_router2();
@@ -35088,7 +35295,7 @@ async function startChatSdk() {
35088
35295
  for (const [name, reason] of Object.entries(config.incomplete ?? {})) {
35089
35296
  console.warn(`[chat-sdk] ${name} not started, incomplete: ${scrubSecrets(reason)}`);
35090
35297
  }
35091
- const { Chat: ChatClass } = await import("./index-h7f61sy9.js");
35298
+ const { Chat: ChatClass } = await import("./index-e5pfbsys.js");
35092
35299
  const state = new SqliteChatState;
35093
35300
  startChatRelayWatcher();
35094
35301
  await Promise.all(CHAT_SDK_ADAPTER_NAMES.map(async (name) => {
@@ -35995,7 +36202,7 @@ async function notifySlack(text) {
35995
36202
  return;
35996
36203
  }
35997
36204
  try {
35998
- const { getSlackApp } = await import("./app-e00m45gn.js");
36205
+ const { getSlackApp } = await import("./app-m9khefrh.js");
35999
36206
  const app = getSlackApp();
36000
36207
  if (!app) {
36001
36208
  console.warn("[Jira webhook keepalive] Slack not available, cannot send notification");
@@ -36066,7 +36273,7 @@ async function deleteJiraWebhook(webhookId) {
36066
36273
  console.log(`[Jira webhook keepalive] Deleted webhook id=${webhookId}`);
36067
36274
  }
36068
36275
  async function overwriteWebhookIds(next) {
36069
- const { getDbClient } = await import("./db-athc68zt.js");
36276
+ const { getDbClient } = await import("./db-ef32tbfc.js");
36070
36277
  await getDbClient().transaction(async (tx) => {
36071
36278
  const row = await tx.get("SELECT metadata FROM oauth_apps WHERE provider = 'jira'");
36072
36279
  if (!row) {
@@ -109373,9 +109580,10 @@ async function resolveHttpRequestAuth(req, apiKey, options = {}) {
109373
109580
  return { kind: "operator", fingerprint: fingerprintApiKey(bearer) };
109374
109581
  }
109375
109582
  if (bearer.startsWith("aswt_")) {
109376
- const user = await resolveUserByToken(bearer);
109377
- if (isActiveUser(user)) {
109378
- return { kind: "user", userId: user.id, user };
109583
+ const resolved = await resolveUserToken(bearer);
109584
+ const user = resolved?.user ?? null;
109585
+ if (resolved && isActiveUser(user)) {
109586
+ return { kind: "user", userId: user.id, user, tokenId: resolved.tokenId };
109379
109587
  }
109380
109588
  }
109381
109589
  if (bearer.startsWith("aseph_")) {
@@ -109506,7 +109714,7 @@ var ErrorResponseSchema, cachedSpec = null, SCALAR_HTML = `<!DOCTYPE html>
109506
109714
  </body>
109507
109715
  </html>`;
109508
109716
  var init_openapi = __esm(() => {
109509
- init_dist6();
109717
+ init_dist7();
109510
109718
  init_constants3();
109511
109719
  init_zod_openapi();
109512
109720
  init_route_def();
@@ -109557,16 +109765,16 @@ async function loadGlobalConfigsIntoEnv(override = false) {
109557
109765
  return updated;
109558
109766
  }
109559
109767
  async function reloadGlobalConfigsAndIntegrations() {
109560
- return runWithoutRequestAuth(() => reloadGlobalConfigsAndIntegrationsInner());
109768
+ return runWithoutRequestAuth(() => runSlackLifecycleExclusive(() => reloadGlobalConfigsAndIntegrationsInner()));
109561
109769
  }
109562
109770
  async function reloadGlobalConfigsAndIntegrationsInner() {
109563
- const { getEmbeddingProvider, resetEmbeddingProvider } = await import("./index-cqhqpgrv.js");
109771
+ const { getEmbeddingProvider, resetEmbeddingProvider } = await import("./index-3c5pxbge.js");
109564
109772
  const wasEmbeddingsConfigured = getEmbeddingProvider().isConfigured();
109565
109773
  const updated = await loadGlobalConfigsIntoEnv(true);
109566
109774
  await syncTelemetryEnabled("settings").catch((err) => {
109567
109775
  console.error("[config-reload] telemetry re-init failed (non-fatal):", err);
109568
109776
  });
109569
- await stopSlackApp2();
109777
+ await stopSlackAppUnderLifecycleLock2();
109570
109778
  const { resetFileStorageProvider } = await import("./registry-hpjfmcfz.js");
109571
109779
  resetFileStorageProvider();
109572
109780
  resetEmbeddingProvider();
@@ -109576,7 +109784,7 @@ async function reloadGlobalConfigsAndIntegrationsInner() {
109576
109784
  integrations.push("embeddings");
109577
109785
  }
109578
109786
  if (isEmbeddingsConfigured) {
109579
- import("./embedding-space-b4txbwrk.js").then(({ runEmbeddingMaintenance }) => runEmbeddingMaintenance({ backfill: !wasEmbeddingsConfigured })).catch((err) => {
109787
+ import("./embedding-space-4kyh5qqj.js").then(({ runEmbeddingMaintenance }) => runEmbeddingMaintenance({ backfill: !wasEmbeddingsConfigured })).catch((err) => {
109580
109788
  console.error("[config-reload] embedding maintenance failed (non-fatal):", err);
109581
109789
  });
109582
109790
  }
@@ -109970,6 +110178,7 @@ var init_core = __esm(() => {
109970
110178
  init_linear();
109971
110179
  init_rbac();
109972
110180
  init_slack();
110181
+ init_lifecycle_lock();
109973
110182
  init_multi_runtime2();
109974
110183
  init_request_auth_context();
109975
110184
  init_secret_scrubber();
@@ -111098,10 +111307,10 @@ var init_sync3 = __esm(() => {
111098
111307
  TransformError = class TransformError extends Error {
111099
111308
  };
111100
111309
  SourceRecordSchema = object2({
111101
- key: union2([string2().min(1), number2()]).transform(String),
111310
+ key: union3([string2().min(1), number2()]).transform(String),
111102
111311
  fields: record2(string2(), unknown())
111103
111312
  });
111104
- PullPayloadSchema = union2([
111313
+ PullPayloadSchema = union3([
111105
111314
  array2(SourceRecordSchema),
111106
111315
  object2({ records: array2(SourceRecordSchema), complete: boolean().optional() })
111107
111316
  ]);
@@ -111925,14 +112134,14 @@ var init_schema_migrate = __esm(() => {
111925
112134
  init_format_upgrades();
111926
112135
  init_row_store();
111927
112136
  init_sync3();
111928
- MigrationValueSchema = union2([
112137
+ MigrationValueSchema = union3([
111929
112138
  string2(),
111930
112139
  number2(),
111931
112140
  boolean(),
111932
112141
  record2(string2(), unknown()),
111933
112142
  array2(unknown())
111934
112143
  ]);
111935
- AppMigrationDirectiveSchema = union2([
112144
+ AppMigrationDirectiveSchema = union3([
111936
112145
  object2({ set: MigrationValueSchema }).strict(),
111937
112146
  object2({
111938
112147
  from: AppNameSchema,
@@ -113410,7 +113619,7 @@ var init_apps = __esm(() => {
113410
113619
  });
113411
113620
  valuesSchema = record2(string2(), unknown());
113412
113621
  AppValidationIssueSchema = object2({ path: string2(), message: string2() });
113413
- JsonValueSchema = union2([
113622
+ JsonValueSchema = union3([
113414
113623
  record2(string2(), unknown()),
113415
113624
  array2(unknown()),
113416
113625
  string2(),
@@ -113477,10 +113686,10 @@ var init_apps = __esm(() => {
113477
113686
  markedStale: number2(),
113478
113687
  error: string2().optional()
113479
113688
  });
113480
- UserConfigValuesSchema = record2(string2(), union2([string2(), number2(), boolean(), _null()]));
113689
+ UserConfigValuesSchema = record2(string2(), union3([string2(), number2(), boolean(), _null()]));
113481
113690
  AppUserConfigFieldSchema = object2({
113482
113691
  kind: ScalarColumnKindSchema,
113483
- default: union2([string2(), number2(), boolean()]).optional(),
113692
+ default: union3([string2(), number2(), boolean()]).optional(),
113484
113693
  enum: array2(string2()).optional(),
113485
113694
  label: string2().optional()
113486
113695
  });
@@ -113834,7 +114043,7 @@ var init_apps = __esm(() => {
113834
114043
  error: string2().optional(),
113835
114044
  durationMs: number2()
113836
114045
  });
113837
- runActionResultSchema = union2([
114046
+ runActionResultSchema = union3([
113838
114047
  runActionScriptResultSchema,
113839
114048
  runActionTaskResultSchema,
113840
114049
  runActionSyncResultSchema
@@ -113958,7 +114167,7 @@ ${JSON.stringify(syncStatus, null, 2)}` : JSON.stringify(app, null, 2);
113958
114167
  inputSchema: object2({
113959
114168
  appId: string2().min(1).describe("App ID containing the named query."),
113960
114169
  query: string2().min(1).describe("Declared query name."),
113961
- params: record2(string2(), union2([string2(), number2(), boolean()])).optional().describe("Values for any $param filters declared by the named query.")
114170
+ params: record2(string2(), union3([string2(), number2(), boolean()])).optional().describe("Values for any $param filters declared by the named query.")
113962
114171
  }),
113963
114172
  outputSchema: swarmToolOutputSchema({
113964
114173
  rows: array2(looseObject({})).optional(),
@@ -114480,7 +114689,7 @@ var init_app_rows = __esm(() => {
114480
114689
  base = { appId: string2().min(1), model: AppNameSchema };
114481
114690
  rowId = string2().min(1);
114482
114691
  values = record2(string2(), unknown());
114483
- equals = record2(string2(), union2([string2(), number2(), boolean()]));
114692
+ equals = record2(string2(), union3([string2(), number2(), boolean()]));
114484
114693
  limit = number2().int().min(1).max(1000);
114485
114694
  rowOutput = { row: looseObject({}).optional() };
114486
114695
  rowsOutput = { rows: array2(looseObject({})).optional() };
@@ -122039,21 +122248,25 @@ var userOutputShape, IdentityEntry, InputSchema, registerManageUserTool = (serve
122039
122248
  }
122040
122249
  try {
122041
122250
  const metadata = mergeComms(input.metadata, input.comms) ?? undefined;
122042
- const user = await createUser2({
122043
- name: input.name,
122044
- email: input.email,
122045
- role: input.role,
122046
- notes: input.notes,
122047
- emailAliases: input.emailAliases,
122048
- preferredChannel: input.preferredChannel,
122049
- timezone: input.timezone,
122050
- dailyBudgetUsd: input.dailyBudgetUsd ?? undefined,
122051
- status: input.status,
122052
- metadata
122251
+ const name = input.name;
122252
+ const user = await getDbClient2().transaction(async () => {
122253
+ const created = await createUser2({
122254
+ name,
122255
+ email: input.email,
122256
+ role: input.role,
122257
+ notes: input.notes,
122258
+ emailAliases: input.emailAliases,
122259
+ preferredChannel: input.preferredChannel,
122260
+ timezone: input.timezone,
122261
+ dailyBudgetUsd: input.dailyBudgetUsd ?? undefined,
122262
+ status: input.status,
122263
+ metadata
122264
+ });
122265
+ for (const ident of input.identities ?? []) {
122266
+ await linkIdentity(created.id, ident.kind, ident.externalId, operatorActor);
122267
+ }
122268
+ return created;
122053
122269
  });
122054
- for (const ident of input.identities ?? []) {
122055
- await linkIdentity(user.id, ident.kind, ident.externalId, operatorActor);
122056
- }
122057
122270
  return toolOk(`User created: "${user.name}" (${user.id}).`, {
122058
122271
  details: JSON.stringify(user, null, 2),
122059
122272
  data: { user }
@@ -122073,46 +122286,56 @@ var userOutputShape, IdentityEntry, InputSchema, registerManageUserTool = (serve
122073
122286
  return toolErr(`User ${input.userId} not found.`);
122074
122287
  }
122075
122288
  const metadata = mergeComms(input.comms !== undefined && input.metadata === undefined ? before.metadata : input.metadata, input.comms);
122076
- const user = await updateUser2(input.userId, {
122077
- name: input.name,
122078
- email: input.email,
122079
- role: input.role,
122080
- notes: input.notes,
122081
- emailAliases: input.emailAliases,
122082
- preferredChannel: input.preferredChannel,
122083
- timezone: input.timezone,
122084
- dailyBudgetUsd: input.dailyBudgetUsd,
122085
- status: input.status,
122086
- metadata
122087
- });
122088
- if (!user) {
122089
- return toolErr(`User ${input.userId} not found.`);
122090
- }
122091
- if (input.identities !== undefined) {
122092
- const current = await getUserIdentities(input.userId);
122093
- const currentSet = new Set(current.map((i) => `${i.kind}:${i.externalId}`));
122094
- const desiredSet = new Set(input.identities.map((i) => `${i.kind}:${i.externalId}`));
122095
- for (const ident of input.identities) {
122096
- if (!currentSet.has(`${ident.kind}:${ident.externalId}`)) {
122097
- await linkIdentity(input.userId, ident.kind, ident.externalId, operatorActor);
122098
- }
122289
+ const userId = input.userId;
122290
+ const bindsIdentity = input.identities !== undefined || input.email !== undefined || input.emailAliases !== undefined;
122291
+ const user = await getDbClient2().transaction(async () => {
122292
+ if (bindsIdentity) {
122293
+ await assertMayActOnOperatorGrantedTarget2({ kind: "agent", id: callerAgent.id }, userId);
122099
122294
  }
122100
- for (const ident of current) {
122101
- if (!desiredSet.has(`${ident.kind}:${ident.externalId}`)) {
122102
- await unlinkIdentity(input.userId, ident.kind, ident.externalId, operatorActor);
122295
+ const updated = await updateUser2(userId, {
122296
+ name: input.name,
122297
+ email: input.email,
122298
+ role: input.role,
122299
+ notes: input.notes,
122300
+ emailAliases: input.emailAliases,
122301
+ preferredChannel: input.preferredChannel,
122302
+ timezone: input.timezone,
122303
+ dailyBudgetUsd: input.dailyBudgetUsd,
122304
+ status: input.status,
122305
+ metadata
122306
+ });
122307
+ if (!updated)
122308
+ return null;
122309
+ if (input.identities !== undefined) {
122310
+ const current = await getUserIdentities(userId);
122311
+ const currentSet = new Set(current.map((i) => `${i.kind}:${i.externalId}`));
122312
+ const desiredSet = new Set(input.identities.map((i) => `${i.kind}:${i.externalId}`));
122313
+ for (const ident of input.identities) {
122314
+ if (!currentSet.has(`${ident.kind}:${ident.externalId}`)) {
122315
+ await linkIdentity(userId, ident.kind, ident.externalId, operatorActor);
122316
+ }
122317
+ }
122318
+ for (const ident of current) {
122319
+ if (!desiredSet.has(`${ident.kind}:${ident.externalId}`)) {
122320
+ await unlinkIdentity(userId, ident.kind, ident.externalId, operatorActor);
122321
+ }
122103
122322
  }
122104
122323
  }
122105
- }
122106
- if (input.emailAliases !== undefined) {
122107
- const { added, removed } = diffAliases(before.emailAliases, input.emailAliases);
122108
- for (const alias of added) {
122109
- await recordIdentityEvent(input.userId, "email_added", operatorActor, null, {
122110
- alias
122111
- });
122112
- }
122113
- for (const alias of removed) {
122114
- await recordIdentityEvent(input.userId, "email_removed", operatorActor, { alias }, null);
122324
+ if (input.emailAliases !== undefined) {
122325
+ const { added, removed } = diffAliases(before.emailAliases, input.emailAliases);
122326
+ for (const alias of added) {
122327
+ await recordIdentityEvent(userId, "email_added", operatorActor, null, {
122328
+ alias
122329
+ });
122330
+ }
122331
+ for (const alias of removed) {
122332
+ await recordIdentityEvent(userId, "email_removed", operatorActor, { alias }, null);
122333
+ }
122115
122334
  }
122335
+ return updated;
122336
+ });
122337
+ if (!user) {
122338
+ return toolErr(`User ${input.userId} not found.`);
122116
122339
  }
122117
122340
  return toolOk(`User updated: "${user.name}" (${user.id}).`, {
122118
122341
  details: JSON.stringify(user, null, 2),
@@ -122138,6 +122361,7 @@ var userOutputShape, IdentityEntry, InputSchema, registerManageUserTool = (serve
122138
122361
  var init_manage_user = __esm(() => {
122139
122362
  init_zod();
122140
122363
  init_db4();
122364
+ init_rbac_roles();
122141
122365
  init_users();
122142
122366
  init_rbac();
122143
122367
  init_utils();
@@ -123477,7 +123701,7 @@ var registerMemoryStoreTool = (server) => {
123477
123701
  content: string2().min(1).describe("The memory body. Markdown is fine. State the fact, the context it applies to, and the evidence."),
123478
123702
  name: string2().min(1).max(200).optional().describe("Short title used in search results and the UI. Defaults to the first non-empty content line (up to 200 characters). A name that starts with /longterm/ is also used as the key when no key is given."),
123479
123703
  scope: AgentMemoryScopeSchema.default("agent").describe("'agent' (default): only you can recall it. 'swarm': every agent can recall it."),
123480
- tags: union2([array2(string2()), string2()]).optional().describe("Free-form tags as an array or a comma-separated string, for example a repo name or a topic."),
123704
+ tags: union3([array2(string2()), string2()]).optional().describe("Free-form tags as an array or a comma-separated string, for example a repo name or a topic."),
123481
123705
  taskId: uuid().optional().describe("The task this learning came from, when there is one."),
123482
123706
  intent: string2().min(1).optional().describe("Why this is worth remembering. Kept in the audit trail."),
123483
123707
  key: string2().max(MEMORY_KEY_MAX_LENGTH).regex(MEMORY_KEY_PATTERN, MEMORY_KEY_PATTERN_MESSAGE).optional().describe("Optional logical path for this memory, for example '/longterm/facts/swarm-runtime/sqlite-busy-retry'. Lowercase segments joined by '/', starting with '/'. Search it with memory-search keyPrefix and move it with memory-edit newKey. Fails when you already have a memory with this key in this scope. A key under /longterm marks the memory as curated: it never expires and is protected from cleanup. It must start with /longterm/company-story, /longterm/entities/people, /longterm/entities/customers, /longterm/facts, /longterm/decisions, /longterm/workstreams or /longterm/timeline. Paths under /longterm/company-story, /longterm/entities and /longterm/timeline are lead-only. Defaults to an auto key, which makes the memory inbox material.")
@@ -131176,7 +131400,7 @@ var init_document = __esm(() => {
131176
131400
  init_yjs();
131177
131401
  init_zod();
131178
131402
  UNSAFE_KEYS = new Set(["__proto__", "constructor", "prototype"]);
131179
- pathSegmentSchema = union2([
131403
+ pathSegmentSchema = union3([
131180
131404
  string2().min(1).max(512).refine((value) => !UNSAFE_KEYS.has(value), "unsafe path key"),
131181
131405
  number2().int().nonnegative()
131182
131406
  ]);
@@ -134646,6 +134870,7 @@ async function sendTaskHandler(ctx, {
134646
134870
  requestedByUserId,
134647
134871
  source: "mcp",
134648
134872
  sourceTaskId,
134873
+ dispatchedByTaskId: sourceTaskId,
134649
134874
  taskType,
134650
134875
  tags,
134651
134876
  priority,
@@ -137089,7 +137314,7 @@ var init_slack_post = __esm(() => {
137089
137314
  });
137090
137315
 
137091
137316
  // src/tools/slack-read.ts
137092
- var AUTO_DOWNLOAD_DIR = "/app/shared/downloads/slack", SlackFileSchema, SlackMessageSchema, registerSlackReadTool = (server) => {
137317
+ var AUTO_DOWNLOAD_DIR = "/app/shared/downloads/slack", USERS_INFO_CONCURRENCY = 4, SlackFileSchema, SlackMessageSchema, registerSlackReadTool = (server) => {
137093
137318
  createToolRegistrar(server)("slack-read", {
137094
137319
  title: "Read Slack thread/channel history",
137095
137320
  description: "Read messages from a Slack thread or channel. Use inboxMessageId or taskId to read from a thread you have context for, or provide channelId directly for channel history (leads only). From a task, files in the messages are stored as attachments of that task, each with a ready-to-run `fetchCommand`.",
@@ -137180,31 +137405,34 @@ var AUTO_DOWNLOAD_DIR = "/app/shared/downloads/slack", SlackFileSchema, SlackMes
137180
137405
  });
137181
137406
  }
137182
137407
  try {
137408
+ let getUserDisplayName = function(userId) {
137409
+ let name = userNameCache.get(userId);
137410
+ if (!name) {
137411
+ name = client.users.info({ user: userId }).then((result) => result.user?.profile?.display_name || result.user?.real_name || userId).catch(() => userId);
137412
+ userNameCache.set(userId, name);
137413
+ }
137414
+ return name;
137415
+ };
137183
137416
  const client = app.client;
137184
- let rawMessages = [];
137185
- if (slackThreadTs) {
137186
- const result = await withAutoJoin(client, slackChannelId, () => client.conversations.replies({ channel: slackChannelId, ts: slackThreadTs, limit }));
137187
- rawMessages = result.messages || [];
137188
- } else {
137189
- const result = await withAutoJoin(client, slackChannelId, () => client.conversations.history({ channel: slackChannelId, limit }));
137190
- rawMessages = result.messages || [];
137191
- }
137192
- const authResult = await client.auth.test();
137193
- const botUserId = authResult.user_id;
137417
+ const [fetchedSettled, authSettled] = await Promise.allSettled([
137418
+ slackThreadTs ? withAutoJoin(client, slackChannelId, () => client.conversations.replies({ channel: slackChannelId, ts: slackThreadTs, limit })) : withAutoJoin(client, slackChannelId, () => client.conversations.history({ channel: slackChannelId, limit })),
137419
+ client.auth.test()
137420
+ ]);
137421
+ if (fetchedSettled.status === "rejected")
137422
+ throw fetchedSettled.reason;
137423
+ if (authSettled.status === "rejected")
137424
+ throw authSettled.reason;
137425
+ const rawMessages = fetchedSettled.value.messages || [];
137426
+ const botUserId = authSettled.value.user_id;
137194
137427
  const userNameCache = new Map;
137195
- async function getUserDisplayName(userId) {
137196
- if (userNameCache.has(userId)) {
137197
- return userNameCache.get(userId);
137198
- }
137199
- try {
137200
- const result = await client.users.info({ user: userId });
137201
- const name = result.user?.profile?.display_name || result.user?.real_name || userId;
137202
- userNameCache.set(userId, name);
137203
- return name;
137204
- } catch {
137205
- return userId;
137428
+ const authorIds = [
137429
+ ...new Set(rawMessages.flatMap((m) => m.user && m.user !== botUserId && m.bot_id === undefined && m.subtype !== "bot_message" && (extractSlackMessageText(m) || collectSlackMessageFiles(m).length > 0) ? [m.user] : []))
137430
+ ];
137431
+ await Promise.all(Array.from({ length: Math.min(USERS_INFO_CONCURRENCY, authorIds.length) }, async () => {
137432
+ for (let id = authorIds.shift();id; id = authorIds.shift()) {
137433
+ await getUserDisplayName(id);
137206
137434
  }
137207
- }
137435
+ }));
137208
137436
  const token = process.env.SLACK_BOT_TOKEN;
137209
137437
  const attachTo = contextTask ?? await attachableTask(agent.id, taskId ?? requestInfo.sourceTaskId);
137210
137438
  if (taskId && !attachTo) {
@@ -138175,7 +138403,7 @@ var BLOCKED_WAITING_PATTERN, BLOCKED_WAITING_MIN_ELAPSED_MS, storeProgressOutput
138175
138403
  failureReason: string2().optional().describe("The reason for failure (used when failing), or the one-line reason for a skip (required with status 'skipped')."),
138176
138404
  attachments: array2(AttachmentInputSchema).max(20).optional().describe("Pointer-based artifacts produced by this step — agent-fs path, URL, shared-fs path, or swarm Page. No inline file data; upload to agent-fs first and attach by path. Agent-fs pointers are verified before task state changes, using the explicit org/drive pair or the registering agent's configured defaults. May be sent on any call (progress or completion) and accumulates across calls; duplicates are de-duped by sha256 (when present) or by (kind, pointer, name)."),
138177
138405
  citations: array2(CitationInputSchema).max(MAX_TASK_CITATIONS).catch([]).optional().describe('Claim sources, upserted by index across calls. Use only for factual claims the reader cannot already see in the thread or task tree, 1-2 sources; none on delegation, routing, acks, or status replies. Reference each one in output with [citation:N], or set general: true for a source that backs the whole answer (it renders under "General sources"). ref per kind: task = task UUID; memory = memory UUID (optional quote must appear verbatim in it); github = owner/repo#N, owner/repo@<sha>, or a github.com pull, issues, or commit URL; slack = permalink or channel/ts; agent-fs = file path; page = page id; script-run = script run id; url = http(s) URL. The first completing call is refused, and the task stays in progress, if a marker has no entry, a citation fails validation, or a non-general citation is unreferenced; the response lists each problem. After one refusal, completion proceeds and those markers and sources are dropped from rendered output. At most 50 citations per call/task, refs up to 2048 characters, labels up to 200. Invalid or oversized batches are ignored; existing indices can still be updated at capacity.'),
138178
- learning: union2([
138406
+ learning: union3([
138179
138407
  string2(),
138180
138408
  object2({
138181
138409
  text: string2(),
@@ -138568,6 +138796,318 @@ var init_store_progress = __esm(() => {
138568
138796
  });
138569
138797
  });
138570
138798
 
138799
+ // src/be/improvements.ts
138800
+ function isValidImprovementEmail(value) {
138801
+ const trimmed = value?.trim() ?? "";
138802
+ return trimmed.length > 0 && trimmed.length <= EMAIL_MAX && VALID_EMAIL_RE.test(trimmed);
138803
+ }
138804
+ function toImprovement(row) {
138805
+ return {
138806
+ id: row.id,
138807
+ text: row.text,
138808
+ email: row.email,
138809
+ status: row.status,
138810
+ source: row.source,
138811
+ requestedByAgentId: row.requested_by_agent_id,
138812
+ approvedBy: row.approved_by,
138813
+ approvedAt: row.approved_at,
138814
+ sentAt: row.sent_at,
138815
+ proxyStatus: row.proxy_status,
138816
+ proxyId: row.proxy_id,
138817
+ proxyError: row.proxy_error,
138818
+ createdAt: row.created_at,
138819
+ updatedAt: row.updated_at
138820
+ };
138821
+ }
138822
+ async function globalValue(key) {
138823
+ const stored = (await getSwarmConfigs2({ scope: "global", key }))?.[0]?.value;
138824
+ return (stored ?? process.env[key])?.trim() || undefined;
138825
+ }
138826
+ async function isImprovementsEnabled() {
138827
+ return parseEnvFlag(await globalValue(IMPROVEMENTS_ENABLED_KEY), true);
138828
+ }
138829
+ async function assertEnabled() {
138830
+ if (!await isImprovementsEnabled()) {
138831
+ throw new ImprovementError("improvements_disabled", "Improvements are turned off (IMPROVEMENTS_ENABLED=false).");
138832
+ }
138833
+ }
138834
+ function buildImprovementPayload(input) {
138835
+ return { install_id: input.installId, text: input.text, email: input.email };
138836
+ }
138837
+ async function improvementInstallId() {
138838
+ return getDbClient2().transaction(async () => {
138839
+ const existing = await globalValue(INSTALL_ID_KEY);
138840
+ if (existing)
138841
+ return existing;
138842
+ const minted = `install_${crypto.randomUUID().replace(/-/g, "").slice(0, 16)}`;
138843
+ await upsertSwarmConfig2({ scope: "global", key: INSTALL_ID_KEY, value: minted });
138844
+ return minted;
138845
+ });
138846
+ }
138847
+ async function getImprovement(id) {
138848
+ const row = await getDbClient2().get("SELECT * FROM improvements WHERE id = ?", [
138849
+ id
138850
+ ]);
138851
+ return row ? toImprovement(row) : null;
138852
+ }
138853
+ async function listImprovements(historyLimit = 100) {
138854
+ const rows = await getDbClient2().query(`SELECT * FROM improvements WHERE status IN ('pending_approval', 'failed')
138855
+ UNION ALL
138856
+ SELECT * FROM (
138857
+ SELECT * FROM improvements WHERE status NOT IN ('pending_approval', 'failed')
138858
+ ORDER BY created_at DESC, id DESC LIMIT ?
138859
+ )
138860
+ ORDER BY created_at DESC, id DESC`, [historyLimit]);
138861
+ return rows.map(toImprovement);
138862
+ }
138863
+ async function createImprovement(input) {
138864
+ await assertEnabled();
138865
+ const trimmed = input.text.trim();
138866
+ const scrubbed = scrubSecrets(trimmed);
138867
+ if (scrubbed.length === 0 || scrubbed.length > IMPROVEMENT_TEXT_MAX) {
138868
+ throw new ImprovementError("invalid_text", `Text must be 1 to ${IMPROVEMENT_TEXT_MAX} characters after trimming.`);
138869
+ }
138870
+ const id = crypto.randomUUID();
138871
+ const now = new Date().toISOString();
138872
+ await getDbClient2().run(`INSERT INTO improvements
138873
+ (id, text, status, source, requested_by_agent_id, created_at, updated_at, created_by, updated_by)
138874
+ VALUES (?, ?, 'pending_approval', ?, ?, ?, ?, ?, ?)`, [
138875
+ id,
138876
+ scrubbed,
138877
+ input.source,
138878
+ input.requestedByAgentId ?? null,
138879
+ now,
138880
+ now,
138881
+ input.createdBy ?? null,
138882
+ input.createdBy ?? null
138883
+ ]);
138884
+ const improvement = await getImprovement(id);
138885
+ if (!improvement)
138886
+ throw new Error(`Improvement ${id} vanished after insert`);
138887
+ return { improvement, scrubChanged: scrubbed !== trimmed };
138888
+ }
138889
+ async function approveAndSend(id, approval) {
138890
+ await assertEnabled();
138891
+ if (!isValidImprovementEmail(approval.email)) {
138892
+ throw new ImprovementError("invalid_email", "A valid email is required to send.");
138893
+ }
138894
+ const email = approval.email.trim();
138895
+ const installId = await improvementInstallId();
138896
+ const approvedAt = new Date().toISOString();
138897
+ const claimed = await getDbClient2().transaction(async (tx) => {
138898
+ const result = await tx.run(`UPDATE improvements
138899
+ SET status = 'sending', approved_by = ?, approved_at = ?, email = ?,
138900
+ proxy_status = NULL, proxy_id = NULL, proxy_error = NULL,
138901
+ updated_at = ?, updated_by = ?
138902
+ WHERE id = ? AND status IN ('pending_approval', 'failed')`, [approval.approvedBy, approvedAt, email, approvedAt, approval.updatedBy ?? null, id]);
138903
+ if (result.changes === 1) {
138904
+ return tx.get("SELECT * FROM improvements WHERE id = ?", [id]);
138905
+ }
138906
+ return null;
138907
+ });
138908
+ if (!claimed) {
138909
+ const existing = await getImprovement(id);
138910
+ if (!existing)
138911
+ throw new ImprovementError("not_found", `Improvement ${id} not found.`);
138912
+ throw new ImprovementError("conflict", `Improvement ${id} is ${existing.status}; only pending or failed improvements can be approved.`);
138913
+ }
138914
+ const payload = buildImprovementPayload({
138915
+ installId,
138916
+ text: claimed.text,
138917
+ email
138918
+ });
138919
+ let proxyStatus = null;
138920
+ let proxyId = null;
138921
+ let proxyError = null;
138922
+ try {
138923
+ const response = await fetch(approval.endpoint, {
138924
+ method: "POST",
138925
+ headers: { "Content-Type": "application/json" },
138926
+ body: JSON.stringify(payload),
138927
+ signal: AbortSignal.timeout(SEND_TIMEOUT_MS)
138928
+ });
138929
+ proxyStatus = response.status;
138930
+ const body = await response.text().catch(() => "");
138931
+ if (response.ok) {
138932
+ try {
138933
+ const parsed = JSON.parse(body);
138934
+ proxyId = typeof parsed.id === "string" ? parsed.id : null;
138935
+ } catch {
138936
+ proxyId = null;
138937
+ }
138938
+ } else {
138939
+ proxyError = body || `HTTP ${response.status}`;
138940
+ }
138941
+ } catch (error) {
138942
+ proxyError = error instanceof Error ? error.message : String(error);
138943
+ }
138944
+ const sent = proxyStatus !== null && proxyStatus >= 200 && proxyStatus < 300;
138945
+ const finishedAt = new Date().toISOString();
138946
+ await getDbClient2().run(`UPDATE improvements
138947
+ SET status = ?, sent_at = ?, proxy_status = ?, proxy_id = ?, proxy_error = ?, updated_at = ?
138948
+ WHERE id = ?`, [
138949
+ sent ? "sent" : "failed",
138950
+ sent ? finishedAt : null,
138951
+ proxyStatus,
138952
+ proxyId,
138953
+ proxyError ? scrubSecrets(proxyError).slice(0, PROXY_ERROR_MAX) : null,
138954
+ finishedAt,
138955
+ id
138956
+ ]);
138957
+ const finished = await getImprovement(id);
138958
+ if (!finished)
138959
+ throw new Error(`Improvement ${id} vanished after send`);
138960
+ return finished;
138961
+ }
138962
+ async function discardImprovement(id, options) {
138963
+ await assertEnabled();
138964
+ const now = new Date().toISOString();
138965
+ const result = await getDbClient2().run(`UPDATE improvements SET status = 'discarded', updated_at = ?, updated_by = ?
138966
+ WHERE id = ? AND status IN ('pending_approval', 'failed')`, [now, options?.updatedBy ?? null, id]);
138967
+ const existing = await getImprovement(id);
138968
+ if (!existing)
138969
+ throw new ImprovementError("not_found", `Improvement ${id} not found.`);
138970
+ if (result.changes !== 1) {
138971
+ throw new ImprovementError("conflict", `Improvement ${id} is ${existing.status}; only pending or failed improvements can be discarded.`);
138972
+ }
138973
+ return existing;
138974
+ }
138975
+ function hostOf(value) {
138976
+ if (!value)
138977
+ return null;
138978
+ try {
138979
+ return new URL(value.includes("://") ? value : `https://${value}`).host || null;
138980
+ } catch {
138981
+ return null;
138982
+ }
138983
+ }
138984
+ async function improvementLeakHints(text) {
138985
+ const client = getDbClient2();
138986
+ const [agents, repos, users] = await Promise.all([
138987
+ client.query("SELECT name FROM agents"),
138988
+ client.query("SELECT name, url FROM swarm_repos"),
138989
+ client.query("SELECT email FROM users WHERE email IS NOT NULL")
138990
+ ]);
138991
+ const terms = new Set;
138992
+ const add = (value) => {
138993
+ const trimmed = value?.trim();
138994
+ if (trimmed && trimmed.length >= 3)
138995
+ terms.add(trimmed);
138996
+ };
138997
+ for (const agent of agents)
138998
+ add(agent.name);
138999
+ for (const repo of repos) {
139000
+ add(repo.name);
139001
+ add(repo.url);
139002
+ }
139003
+ for (const user of users)
139004
+ add(user.email);
139005
+ add(hostOf(process.env.MCP_BASE_URL));
139006
+ add(hostOf(process.env.APP_URL));
139007
+ const orgName = await globalValue("SWARM_ORG_NAME");
139008
+ const orgWebsite = await globalValue("SWARM_ORG_WEBSITE");
139009
+ add(orgName);
139010
+ add(orgWebsite);
139011
+ add(hostOf(orgWebsite));
139012
+ const hits = [];
139013
+ const seen = new Set;
139014
+ const push = (hit) => {
139015
+ const key = hit.toLowerCase();
139016
+ if (seen.has(key) || hits.length >= LEAK_HINTS_MAX)
139017
+ return;
139018
+ seen.add(key);
139019
+ hits.push(hit);
139020
+ };
139021
+ const lower = text.toLowerCase();
139022
+ for (const term of terms) {
139023
+ const at = lower.indexOf(term.toLowerCase());
139024
+ if (at >= 0)
139025
+ push(text.slice(at, at + term.length));
139026
+ }
139027
+ for (const match of text.matchAll(URL_RE))
139028
+ push(match[0]);
139029
+ for (const match of text.matchAll(EMAIL_RE))
139030
+ push(match[0]);
139031
+ return hits;
139032
+ }
139033
+ var IMPROVEMENTS_ENABLED_KEY = "IMPROVEMENTS_ENABLED", IMPROVEMENT_TEXT_MAX = 4000, SEND_TIMEOUT_MS = 1e4, PROXY_ERROR_MAX = 1024, LEAK_HINTS_MAX = 50, INSTALL_ID_KEY = "telemetry_installation_id", EMAIL_MAX = 320, VALID_EMAIL_RE, IMPROVEMENT_STATUSES, IMPROVEMENT_SOURCES, ImprovementError, URL_RE, EMAIL_RE;
139034
+ var init_improvements = __esm(() => {
139035
+ init_env_flag();
139036
+ init_secret_scrubber();
139037
+ init_db4();
139038
+ VALID_EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
139039
+ IMPROVEMENT_STATUSES = [
139040
+ "pending_approval",
139041
+ "sending",
139042
+ "sent",
139043
+ "failed",
139044
+ "discarded"
139045
+ ];
139046
+ IMPROVEMENT_SOURCES = ["mcp", "api", "ui"];
139047
+ ImprovementError = class ImprovementError extends Error {
139048
+ code;
139049
+ constructor(code, message) {
139050
+ super(message);
139051
+ this.code = code;
139052
+ this.name = "ImprovementError";
139053
+ }
139054
+ };
139055
+ URL_RE = /\bhttps?:\/\/[^\s<>"')]+/gi;
139056
+ EMAIL_RE = /[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/g;
139057
+ });
139058
+
139059
+ // src/tools/submit-improvement.ts
139060
+ var submitImprovementInputSchema, submitImprovementOutputSchema, registerSubmitImprovementTool = (server) => {
139061
+ createToolRegistrar(server)("submit-improvement", {
139062
+ title: "Draft a product improvement",
139063
+ description: "Draft a short product improvement for the agent-swarm team at desplega. It is stored as a pending draft and is never sent by this tool: a person must approve it from the Improvements button in the dashboard header. Only the text you write, the install id and the approver's email are sent.",
139064
+ annotations: { destructiveHint: false },
139065
+ inputSchema: submitImprovementInputSchema,
139066
+ outputSchema: submitImprovementOutputSchema
139067
+ }, async ({ text }, info) => {
139068
+ if (info.callOrigin === "script-sdk" || info.callOrigin === "extension") {
139069
+ return toolErr("Scripts and extensions cannot draft improvements.");
139070
+ }
139071
+ if (!info.agentId) {
139072
+ return toolErr('Agent ID not found. Set the "X-Agent-ID" header.');
139073
+ }
139074
+ const agent = await getAgentById2(info.agentId);
139075
+ const decision = can({
139076
+ principal: { kind: "agent", agentId: info.agentId, isLead: agent?.isLead ?? false },
139077
+ verb: "improvement.submit",
139078
+ source: "mcp"
139079
+ });
139080
+ if (!decision.allow)
139081
+ return toolErr(decision.reason);
139082
+ try {
139083
+ const { improvement } = await createImprovement({
139084
+ text,
139085
+ source: "mcp",
139086
+ requestedByAgentId: info.agentId
139087
+ });
139088
+ return toolOk(`Drafted improvement ${improvement.id}. A person must approve it from the Improvements button in the dashboard header before anything is sent.`, { data: { id: improvement.id, status: improvement.status } });
139089
+ } catch (error) {
139090
+ if (error instanceof ImprovementError)
139091
+ return toolErr(error.message);
139092
+ throw error;
139093
+ }
139094
+ });
139095
+ };
139096
+ var init_submit_improvement = __esm(() => {
139097
+ init_zod();
139098
+ init_db4();
139099
+ init_improvements();
139100
+ init_rbac();
139101
+ init_utils();
139102
+ submitImprovementInputSchema = object2({
139103
+ text: string2().min(1).max(IMPROVEMENT_TEXT_MAX).describe("The product improvement for desplega, in plain words. Do not include names, repos, hosts, customer details or secrets.")
139104
+ });
139105
+ submitImprovementOutputSchema = swarmToolOutputSchema({
139106
+ id: string2().optional(),
139107
+ status: string2().optional()
139108
+ });
139109
+ });
139110
+
138571
139111
  // src/tools/swarm-config/delete-config.ts
138572
139112
  var registerDeleteConfigTool = (server) => {
138573
139113
  createToolRegistrar(server)("delete-config", {
@@ -139031,7 +139571,7 @@ var init_swarm_x = __esm(() => {
139031
139571
  init_zod();
139032
139572
  init_composio();
139033
139573
  init_utils();
139034
- primitiveQueryValueSchema = union2([string2(), number2(), boolean()]);
139574
+ primitiveQueryValueSchema = union3([string2(), number2(), boolean()]);
139035
139575
  });
139036
139576
 
139037
139577
  // src/tools/system-one-decide.ts
@@ -139043,7 +139583,7 @@ var registerSystemOneDecideTool = (server) => {
139043
139583
  inputSchema: object2({
139044
139584
  provider: _enum2(SYSTEM_ONE_PROVIDER_IDS).optional().describe("Decision host (default: the SYSTEM_ONE_DEFAULT_PROVIDER global config, typesafe when unset)"),
139045
139585
  model: string2().min(1).optional().describe("Provider model id (default: the provider's)"),
139046
- state: union2([string2(), array2(string2()), record2(string2(), unknown())]).describe("The state to decide on"),
139586
+ state: union3([string2(), array2(string2()), record2(string2(), unknown())]).describe("The state to decide on"),
139047
139587
  questions: record2(string2(), record2(string2(), unknown())).describe("Questions by id, each `{ type: 'noul' | 'choice' | 'score', instructions, criteria }`"),
139048
139588
  timeoutMs: number2().int().optional().describe("Time budget for the call, retries included (default 30000)"),
139049
139589
  maxRetries: number2().int().optional().describe("Retries on transient failures inside the time budget (default 2)")
@@ -139218,7 +139758,7 @@ async function emitBudgetRefusalSideEffects(ctx, inserted) {
139218
139758
  console.warn(`[budget-refusal-notify] Failed to create follow-up task for budget refusal (task=${ctx.task.id.slice(0, 8)}): ${err}`);
139219
139759
  }
139220
139760
  }
139221
- import("./event-bus-g0ka3pbw.js").then(({ workflowEventBus }) => {
139761
+ import("./event-bus-e66gh7cc.js").then(({ workflowEventBus }) => {
139222
139762
  workflowEventBus.emit("task.budget_refused", {
139223
139763
  taskId: ctx.task.id,
139224
139764
  agentId: ctx.agentId,
@@ -140737,7 +141277,7 @@ var registerPatchWorkflowTool = (server) => {
140737
141277
  type: string2(),
140738
141278
  config: record2(string2(), unknown()),
140739
141279
  label: string2().optional(),
140740
- next: union2([string2(), array2(string2()), record2(string2(), string2())]).optional(),
141280
+ next: union3([string2(), array2(string2()), record2(string2(), string2())]).optional(),
140741
141281
  inputs: record2(string2(), string2()).optional()
140742
141282
  })).optional().describe("New nodes to add"),
140743
141283
  onNodeFailure: _enum2(["fail", "continue"]).optional().describe("Update onNodeFailure behavior"),
@@ -141352,6 +141892,7 @@ async function createServer(opts = {}) {
141352
141892
  registerStoreProgressTool(server);
141353
141893
  registerMyAgentInfoTool(server);
141354
141894
  registerCancelTaskTool(server);
141895
+ registerSubmitImprovementTool(server);
141355
141896
  registerResolveUserTool(server);
141356
141897
  registerManageUserTool(server);
141357
141898
  registerDbQueryTool(server);
@@ -141671,6 +142212,7 @@ var init_server = __esm(() => {
141671
142212
  init_slack_upload_file();
141672
142213
  init_steer_task();
141673
142214
  init_store_progress();
142215
+ init_submit_improvement();
141674
142216
  init_swarm_config2();
141675
142217
  init_swarm_x();
141676
142218
  init_system_one_decide();
@@ -141728,4 +142270,4 @@ var init_server = __esm(() => {
141728
142270
  loggedToolAllowlistWarnings = new Set;
141729
142271
  });
141730
142272
 
141731
- export { DEFAULT_NEGOTIATED_PROTOCOL_VERSION, SUPPORTED_PROTOCOL_VERSIONS, isJSONRPCRequest, isJSONRPCResultResponse, isJSONRPCErrorResponse, JSONRPCMessageSchema, isInitializeRequest, init_types, McpServer, init_mcp, repointTrackerSyncBySwarmId, init_tracker, isRuntimePoolWakeable, isAgentReachable, init_reachability, referencedBundlePaths, skillDirs, init_manifest_format, TaskCreationBlockedError, init_errors2, resolveIdentity, renderIdentity, init_identity, recordUnmappedIdentity, init_unmapped_identities, MAX_TASK_ATTACHMENT_BYTES, recordTaskAttachmentUpload, scopeFromAttachment, backingProviderId, init_task_attachment_store, taskModelPin, resumedTaskModelSelection, init_model_pin, listHarnessModelSupport, recordHarnessModelSupport, agentRanModel, getAgentHarnessCliVersion, setAgentHarnessCliVersion, init_harness_model_support, sanitizeModelTierOverrides, parseModelTierOverridesHeader, setAgentModelTierOverrides, previewModelTiers, recordClaimModelResolution, init_model_tier_resolution, harnessModelErrorFor, poolTaskRunsOnHarness, explicitModelError, explicitModelErrorForAgent, init_model_validation, stripSiblingBlock, init_sibling_block, createTaskWithSiblingAwareness, init_sibling_awareness, transcribeAudioNotes, init_transcription, init_templates, buildEffectiveText, bufferedFileFailures, fetchSlackFiles, createSlackTaskWithFiles, notifySlackFileFailures, init_inbound_files, isAddressedToOtherUser, broadcastMatches, routeMessage, extractTaskFromMessage, init_router, extractSlackMessageText, slackInboundMessageText, collectSlackMessageFiles, init_message_text, createAdditiveBuffer, init_additive_buffer, recoverIncompleteRuns, init_recovery, handleWebhookTrigger, verifyHmacSignature, WebhookError, init_triggers, snapshotAndUpdateWorkflow, init_version, RawLlmConfigSchema, RawLlmOutputSchema, executeRawLlm, init_raw_llm, getExecutorRegistry2, initWorkflows2, init_workflows, dispatchScheduleTarget, calculateNextRun2, startScheduler2, stopScheduler2, runScheduleNow2, init_scheduler, ExtensionAssetConflictError, init_assets, ExtensionOwnershipError, getExtensionFiles, getExtensionById, getExtensionByName, listExtensions, listExtensionVersions, updateExtensionMeta, listExtensionRuns, init_db, SDK_ALLOWLIST, mcpToolNameForSdkMethod, init_sdk_allowlist, MCP_OVERFLOW_NAMESPACE, mcpOverflowAuthError, init_kv_overflow, hasKvViewArgs, resolveKvView, init_kv_view, COLOR_LITERAL_THRESHOLD, countColorLiterals, init_color_literals, toolErr, createToolRegistrar, init_utils, handleMcpBridge, init_mcp_bridge, Redacted, init_redacted, SCRIPT_SDK_RESPONSE_LIMIT_BYTES, readScriptSdkJsonResponse, init_response_limit, ExtensionConfigError, init_loader, ExtensionLifecycleError, setExtensionLoopbackBaseUrl, enableExtension, disableExtension, activateVersion, ExtensionAssetsInvalidError, installExtensionWithAssets, uninstallExtension, reloadExtension, loadEnabledExtensions, stopExtensionRuntime, init_lifecycle, ExtensionAbortedError2, isRegistered2, isExtensionAgentId2, getExtensionBridgeToken2, resolveBridgeCallOrigin2, extensionIdForAgent2, runContext2, registerLoaded2, unregister2, listRegistered2, dispatchPre2, dispatchPost2, init_dispatcher, REBOOT_RETRY_PIN_TAG2, getPinCandidateAgent2, resolveLeadOnlyRecoveryAssignment2, getResumeGeneration2, getNextResumeGeneration2, inheritedModelSelection2, createWorkerTaskFollowUp2, createResumeFollowUp2, createRerouteDecisionTask2, createPoolStarvationDecisionTask2, init_worker_follow_up, isGitHubEnabled, initGitHub, verifyWebhookSignature, isAgentMailEnabled, initAgentMail, verifyAgentMailWebhook, isInboxAllowed, isSenderAllowed, handleMessageReceived, init_agentmail, isAzureDevOpsEnabled, initAzureDevOps, verifyAzureDevOpsWebhook, isAzureDevOpsUrl, canonicalAzureDevOpsRepoUrl, parseAzureDevOpsRepoUrl, init_azure_devops, createdPullRequestOf, commentedPayloadOf, handlePullRequestCreated, handlePullRequestCommented, handleWorkItemCreated, handleWorkItemUpdated, handleWorkItemCommented, handleWorkItemDeleted, handleWorkItemRestored, initAzureDevOpsOutbound, init_azure_devops2, enqueueAuditRow, enqueueAdmissionRow, flushAuditBuffer, startAuditWriter, stopAuditWriter, startAuditGc, stopAuditGc, init_rbac_audit, getTelemetryIngestAnchor, init_telemetry_ingest_anchor, initApiTelemetry, syncTelemetryEnabled, init_telemetry_enable, isBitbucketEnabled, initBitbucket, verifyBitbucketWebhook, isDuplicateDelivery, markDeliveryProcessed, pullRequestEventOf, pullRequestCommentEventOf, handlePullRequestCreated2, handlePullRequestCommentCreated, handlePullRequestClosed, init_bitbucket, handlePullRequest, handleIssue, handleComment, handlePullRequestReview, handleCheckRun, handleCheckSuite, handleWorkflowRun, init_github, isGitLabEnabled, initGitLab, verifyGitLabWebhook, handleMergeRequest, handleIssue2, handleNote, handlePipeline, init_gitlab, isChatSdkEnabled, getChatSdkConfig, init_config, errorMessage, init_logger, resolveAdapterApiUrl, init_adapters, trackBackground, init_background, TelegramBotApiError, callTelegramBotApi, init_telegram_api, isTrustedTeamsServiceUrl, init_teams_origin, getSessionLabels, rememberSessionLabel, init_session_labels, isChatSdkStopping, startChatSdk, getChatInstance, isChatAdapterConfigured, getChatSdkHealth, stopChatSdk, init_runtime, getJiraMetadata, updateJiraMetadata, clearJiraMetadata, init_metadata, registerJiraWebhook, deleteJiraWebhook, init_webhook_lifecycle, isJiraEnabled, initJira, init_app, handleJiraWebhook, init_webhook, init_jira, handleAgentSessionEvent, handleIssueUpdate, handleIssueDelete, handleAgentSessionPrompted, init_sync, isLinearEnabled, initLinear, init_app2, init_linear, init_slack, verifyPageSession, LEGACY_PAGE_SESSION_COOKIE, isCookieSafePageId, extractPageSession, extractLegacyPageSession, extractAndVerifyCookie, isLocalDevPageRequest, pageSessionSetCookies, init_page_session, resolveHttpRequestAuth, init_auth, getDeploymentEnvValue, loadGlobalConfigsIntoEnv, reloadGlobalConfigsAndIntegrations, scheduleIntegrationsReload, handleCore, init_core, MCP_MAX_TOOL_INPUT_ELEMENTS, MCP_MAX_REQUEST_BODY_BYTES, init_mcp_limits, userCtx, init_task_tool_ctx, requestPrincipal, agentFirstPrincipal, requireAuthKind, rejectGuest, init_request_principal, handleApps, init_apps, cancelApprovalRequest, cancelApprovalRequestAndRun, init_approval_cancel, getUserCommsPrefs, init_requester_comms, getTaskDetailsInputSchema, getTaskDetailsOutputSchema, getTaskDetailsHandler, init_get_task_details, cancelTaskInputSchema, cancelTaskOutputSchema, cancelTaskHandler, init_cancel_task, executeReadOnlyQuery, assertSelectOnlyQuery, handleDbQuery, init_db_query, snapshotMetric, init_version2, AssetKeyAuthorizationError, authorizeAssetKeyWrite, init_asset_key_auth, getPageEditCounter, init_page_versions, snapshotPage, init_version3, DEFAULT_THEME_ID, THEME_PRESET_IDS, getThemePreset, init_presets, readThemeFields, init_page_fields, assertOAuthAppUrlsSafe, assertOAuthEgressUrlSafe, init_app_validation, listOAuthPresets, listOAuthPresetIds, getOAuthPreset, hydrateOAuthAppFromPreset, init_presets2, scopedResourceScopeIdSchema, resolveScopedResourceId, init_scoped_resource, MemoryKeyError, init_key_guard, refreshLinks, init_link_resolver, indexMemoryContent, init_index_content, dedupeMemoryDocumentIds, recordMemoryAccesses, recordRetrievals, init_retrieval, ExplicitSelfDuplicateError, applyRating, init_store, shouldPersistAutomaticTaskMemory, init_automatic_task_gate, guardTerminalTaskResultWrite, init_terminal_result_guard, getTasksInputSchema, getTasksOutputSchema, getTasksHandler, init_get_tasks, reservedNamespaceError, privateNamespaceError, reservedRoomKeyError, init_kv_reserved_namespaces, updateMcpServerChecked, init_mcp_server_checked_update, updateTouchesStdioExecution, init_mcp_server_stdio_gate, canReadMemory, init_access, getLinksForMemory, init_links_store, expandCandidatesWithGraph, init_graph_expansion, isApiDraining, drainApi, init_api_drain, markKapsoMessageRead, sendKapsoReaction, init_client, getKapsoConfig, getKapsoNumberMapping, markKapsoMessageSeen, init_config2, changesAllowMerge, init_repo_merge_policy, updateSwarmRepoChecked, init_repo_checked_update, getCombConfig, init_config3, resolveRoomNamespace, roomRequestInfo, authorizeRoomNamespace, sessionAccessTopic, sessionPresenceRoot, init_auth2, RoomOperationSchema, init_document, removeAwarenessStates, init_awareness, roomTopic, decodeRoomSnapshot, roomView, getRoom, changeRoom, applyRoomUpdate, resetRoom, sweepRooms, closeRooms, removeNamespaceRooms, init_rooms, init_scheduler2, MEMORY_KEYS_DEFAULT_PREFIX, MEMORY_KEYS_MAX_LIMIT, estimateTokens, posteriorMean, listMemoryKeys, checkChunkIntegrity, getMemoryChunks, getPosteriorsByIds, init_key_browser, createEvent, createEventsBatch, getEventCountsFiltered, getEventsFiltered, init_events, mergeScheduleTiming, validateRecurringTiming, init_validate, followUpThreadForSourceTask, evaluateFollowUpRedelegation, init_follow_up_redelegation_guard, checkOutputSchemaShape, sendTaskOutputSchema, sendTaskHandler, init_send_task, steerTaskUserInputSchema, steerTaskOutputSchema, steerTaskHandler, init_steer_task, skipReasonFrom, finalizeSkippedTaskReaction, init_task_skip, canClaim, init_budget_admission, emitBudgetRefusalSideEffects, init_budget_refusal_notify, workflowModelErrors, init_model_validation2, patchWorkflowDefinition, init_patch_definition, idempotencyKeyHeader, readIdempotencyKey, replayAcceptedOperation, init_idempotency_key, resolveScriptsOnlyMode, init_scripts_only_mode, ALL_CAPABILITIES, hasCapability, getEnabledCapabilities, createServer, init_server };
142273
+ export { DEFAULT_NEGOTIATED_PROTOCOL_VERSION, SUPPORTED_PROTOCOL_VERSIONS, isJSONRPCRequest, isJSONRPCResultResponse, isJSONRPCErrorResponse, JSONRPCMessageSchema, isInitializeRequest, init_types, McpServer, init_mcp, repointTrackerSyncBySwarmId, init_tracker, isRuntimePoolWakeable, isAgentReachable, init_reachability, referencedBundlePaths, skillDirs, init_manifest_format, TaskCreationBlockedError, init_errors2, resolveIdentity, renderIdentity, init_identity, recordUnmappedIdentity, init_unmapped_identities, MAX_TASK_ATTACHMENT_BYTES, recordTaskAttachmentUpload, scopeFromAttachment, backingProviderId, init_task_attachment_store, taskModelPin, resumedTaskModelSelection, init_model_pin, listHarnessModelSupport, recordHarnessModelSupport, agentRanModel, getAgentHarnessCliVersion, setAgentHarnessCliVersion, init_harness_model_support, sanitizeModelTierOverrides, parseModelTierOverridesHeader, setAgentModelTierOverrides, previewModelTiers, recordClaimModelResolution, init_model_tier_resolution, harnessModelErrorFor, poolTaskRunsOnHarness, explicitModelError, explicitModelErrorForAgent, init_model_validation, stripSiblingBlock, init_sibling_block, createTaskWithSiblingAwareness, init_sibling_awareness, transcribeAudioNotes, init_transcription, init_templates, buildEffectiveText, bufferedFileFailures, fetchSlackFiles, createSlackTaskWithFiles, notifySlackFileFailures, init_inbound_files, isAddressedToOtherUser, broadcastMatches, routeMessage, extractTaskFromMessage, init_router, extractSlackMessageText, slackInboundMessageText, collectSlackMessageFiles, init_message_text, createAdditiveBuffer, init_additive_buffer, recoverIncompleteRuns, init_recovery, handleWebhookTrigger, verifyHmacSignature, WebhookError, init_triggers, snapshotAndUpdateWorkflow, init_version, RawLlmConfigSchema, RawLlmOutputSchema, executeRawLlm, init_raw_llm, getExecutorRegistry2, initWorkflows2, init_workflows, dispatchScheduleTarget, calculateNextRun2, startScheduler2, stopScheduler2, runScheduleNow2, init_scheduler, ExtensionAssetConflictError, init_assets, ExtensionOwnershipError, getExtensionFiles, getExtensionById, getExtensionByName, listExtensions, listExtensionVersions, updateExtensionMeta, listExtensionRuns, init_db, SDK_ALLOWLIST, mcpToolNameForSdkMethod, init_sdk_allowlist, MCP_OVERFLOW_NAMESPACE, mcpOverflowAuthError, init_kv_overflow, hasKvViewArgs, resolveKvView, init_kv_view, COLOR_LITERAL_THRESHOLD, countColorLiterals, init_color_literals, toolErr, createToolRegistrar, init_utils, handleMcpBridge, init_mcp_bridge, Redacted, init_redacted, SCRIPT_SDK_RESPONSE_LIMIT_BYTES, readScriptSdkJsonResponse, init_response_limit, ExtensionConfigError, init_loader, ExtensionLifecycleError, setExtensionLoopbackBaseUrl, enableExtension, disableExtension, activateVersion, ExtensionAssetsInvalidError, installExtensionWithAssets, uninstallExtension, reloadExtension, loadEnabledExtensions, stopExtensionRuntime, init_lifecycle, ExtensionAbortedError2, isRegistered2, isExtensionAgentId2, getExtensionBridgeToken2, resolveBridgeCallOrigin2, extensionIdForAgent2, runContext2, registerLoaded2, unregister2, listRegistered2, dispatchPre2, dispatchPost2, init_dispatcher, REBOOT_RETRY_PIN_TAG2, getPinCandidateAgent2, resolveLeadOnlyRecoveryAssignment2, getResumeGeneration2, getNextResumeGeneration2, inheritedModelSelection2, createWorkerTaskFollowUp2, createResumeFollowUp2, createRerouteDecisionTask2, createPoolStarvationDecisionTask2, init_worker_follow_up, isGitHubEnabled, initGitHub, verifyWebhookSignature, isAgentMailEnabled, initAgentMail, verifyAgentMailWebhook, isInboxAllowed, isSenderAllowed, handleMessageReceived, init_agentmail, isAzureDevOpsEnabled, initAzureDevOps, verifyAzureDevOpsWebhook, isAzureDevOpsUrl, canonicalAzureDevOpsRepoUrl, parseAzureDevOpsRepoUrl, init_azure_devops, createdPullRequestOf, commentedPayloadOf, handlePullRequestCreated, handlePullRequestCommented, handleWorkItemCreated, handleWorkItemUpdated, handleWorkItemCommented, handleWorkItemDeleted, handleWorkItemRestored, initAzureDevOpsOutbound, init_azure_devops2, enqueueAuditRow, enqueueAdmissionRow, flushAuditBuffer, startAuditWriter, stopAuditWriter, startAuditGc, stopAuditGc, init_rbac_audit, getTelemetryIngestAnchor, init_telemetry_ingest_anchor, initApiTelemetry, syncTelemetryEnabled, init_telemetry_enable, isBitbucketEnabled, initBitbucket, verifyBitbucketWebhook, isDuplicateDelivery, markDeliveryProcessed, pullRequestEventOf, pullRequestCommentEventOf, handlePullRequestCreated2, handlePullRequestCommentCreated, handlePullRequestClosed, init_bitbucket, handlePullRequest, handleIssue, handleComment, handlePullRequestReview, handleCheckRun, handleCheckSuite, handleWorkflowRun, init_github, isGitLabEnabled, initGitLab, verifyGitLabWebhook, handleMergeRequest, handleIssue2, handleNote, handlePipeline, init_gitlab, isChatSdkEnabled, getChatSdkConfig, init_config, errorMessage, init_logger, resolveAdapterApiUrl, init_adapters, trackBackground, init_background, TelegramBotApiError, callTelegramBotApi, init_telegram_api, isTrustedTeamsServiceUrl, init_teams_origin, getSessionLabels, rememberSessionLabel, getResourceSessionLabels, init_session_labels, isChatSdkStopping, startChatSdk, getChatInstance, isChatAdapterConfigured, getChatSdkHealth, stopChatSdk, init_runtime, getJiraMetadata, updateJiraMetadata, clearJiraMetadata, init_metadata, registerJiraWebhook, deleteJiraWebhook, init_webhook_lifecycle, isJiraEnabled, initJira, init_app, handleJiraWebhook, init_webhook, init_jira, handleAgentSessionEvent, handleIssueUpdate, handleIssueDelete, handleAgentSessionPrompted, init_sync, isLinearEnabled, initLinear, init_app2, init_linear, init_slack, verifyPageSession, LEGACY_PAGE_SESSION_COOKIE, isCookieSafePageId, extractPageSession, extractLegacyPageSession, extractAndVerifyCookie, isLocalDevPageRequest, pageSessionSetCookies, init_page_session, resolveHttpRequestAuth, init_auth, getDeploymentEnvValue, loadGlobalConfigsIntoEnv, reloadGlobalConfigsAndIntegrations, scheduleIntegrationsReload, handleCore, init_core, MCP_MAX_TOOL_INPUT_ELEMENTS, MCP_MAX_REQUEST_BODY_BYTES, init_mcp_limits, userCtx, init_task_tool_ctx, requestPrincipal, agentFirstPrincipal, requireAuthKind, rejectGuest, init_request_principal, handleApps, init_apps, cancelApprovalRequest, cancelApprovalRequestAndRun, init_approval_cancel, getUserCommsPrefs, init_requester_comms, getTaskDetailsInputSchema, getTaskDetailsOutputSchema, getTaskDetailsHandler, init_get_task_details, cancelTaskInputSchema, cancelTaskOutputSchema, cancelTaskHandler, init_cancel_task, executeReadOnlyQuery, assertSelectOnlyQuery, handleDbQuery, init_db_query, snapshotMetric, init_version2, AssetKeyAuthorizationError, authorizeAssetKeyWrite, init_asset_key_auth, getPageEditCounter, init_page_versions, snapshotPage, init_version3, DEFAULT_THEME_ID, THEME_PRESET_IDS, getThemePreset, init_presets, readThemeFields, init_page_fields, assertOAuthAppUrlsSafe, assertOAuthEgressUrlSafe, init_app_validation, listOAuthPresets, listOAuthPresetIds, getOAuthPreset, hydrateOAuthAppFromPreset, init_presets2, scopedResourceScopeIdSchema, resolveScopedResourceId, init_scoped_resource, MemoryKeyError, init_key_guard, refreshLinks, init_link_resolver, indexMemoryContent, init_index_content, dedupeMemoryDocumentIds, recordMemoryAccesses, recordRetrievals, init_retrieval, ExplicitSelfDuplicateError, applyRating, init_store, shouldPersistAutomaticTaskMemory, init_automatic_task_gate, guardTerminalTaskResultWrite, init_terminal_result_guard, getTasksInputSchema, getTasksOutputSchema, getTasksHandler, init_get_tasks, reservedNamespaceError, privateNamespaceError, reservedRoomKeyError, init_kv_reserved_namespaces, updateMcpServerChecked, init_mcp_server_checked_update, updateTouchesStdioExecution, init_mcp_server_stdio_gate, canReadMemory, init_access, getLinksForMemory, init_links_store, expandCandidatesWithGraph, init_graph_expansion, isApiDraining, drainApi, init_api_drain, markKapsoMessageRead, sendKapsoReaction, init_client, getKapsoConfig, getKapsoNumberMapping, markKapsoMessageSeen, init_config2, changesAllowMerge, init_repo_merge_policy, updateSwarmRepoChecked, init_repo_checked_update, getCombConfig, init_config3, resolveRoomNamespace, roomRequestInfo, authorizeRoomNamespace, sessionAccessTopic, sessionPresenceRoot, init_auth2, RoomOperationSchema, init_document, removeAwarenessStates, init_awareness, roomTopic, decodeRoomSnapshot, roomView, getRoom, changeRoom, applyRoomUpdate, resetRoom, sweepRooms, closeRooms, removeNamespaceRooms, init_rooms, init_scheduler2, MEMORY_KEYS_DEFAULT_PREFIX, MEMORY_KEYS_MAX_LIMIT, estimateTokens, posteriorMean, listMemoryKeys, checkChunkIntegrity, getMemoryChunks, getPosteriorsByIds, init_key_browser, createEvent, createEventsBatch, getEventCountsFiltered, getEventsFiltered, init_events, mergeScheduleTiming, validateRecurringTiming, init_validate, followUpThreadForSourceTask, evaluateFollowUpRedelegation, init_follow_up_redelegation_guard, checkOutputSchemaShape, sendTaskOutputSchema, sendTaskHandler, init_send_task, steerTaskUserInputSchema, steerTaskOutputSchema, steerTaskHandler, init_steer_task, skipReasonFrom, finalizeSkippedTaskReaction, init_task_skip, IMPROVEMENT_TEXT_MAX, IMPROVEMENT_STATUSES, IMPROVEMENT_SOURCES, ImprovementError, isImprovementsEnabled, getImprovement, listImprovements, createImprovement, approveAndSend, discardImprovement, improvementLeakHints, init_improvements, canClaim, init_budget_admission, emitBudgetRefusalSideEffects, init_budget_refusal_notify, workflowModelErrors, init_model_validation2, patchWorkflowDefinition, init_patch_definition, idempotencyKeyHeader, readIdempotencyKey, replayAcceptedOperation, init_idempotency_key, resolveScriptsOnlyMode, init_scripts_only_mode, ALL_CAPABILITIES, hasCapability, getEnabledCapabilities, createServer, init_server };