@desplega.ai/agent-swarm 2.13.3 → 2.13.5

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 (424) hide show
  1. package/dist/acp-adapter-tbt61zkm.js +17 -0
  2. package/dist/{acp-targets-k8xs4tj8.js → acp-targets-w8dbs4nr.js} +10 -10
  3. package/dist/{actions-pg5fxjer.js → actions-8zrcbjrx.js} +237 -27
  4. package/dist/{agent-fs-provision-vbk3fppw.js → agent-fs-provision-cbt2ttds.js} +4 -4
  5. package/dist/{amp-adapter-adbhxsz9.js → amp-adapter-8x6zp8w4.js} +3 -3
  6. package/dist/{anthropic-messages-88b7s3n9.js → anthropic-messages-vdd1zmha.js} +10 -10
  7. package/dist/{app-b267ggx1.js → app-zfa9dwjw.js} +7 -7
  8. package/dist/{approval-notifications-evc1a9z5.js → approval-notifications-rv92zmza.js} +8 -8
  9. package/dist/{assistant-wgz2ab84.js → assistant-q7s7rm1q.js} +25 -25
  10. package/dist/{boot-args-schema-6tpk28j4.js → boot-args-schema-g27kpzr1.js} +1 -1
  11. package/dist/{boot-reembed-r1zyvefv.js → boot-reembed-1mjs52nt.js} +1 -1
  12. package/dist/{boot-reembed-ankp369c.js → boot-reembed-m62dpdkg.js} +1 -1
  13. package/dist/{boot-scrub-sweep-cgb6r5bd.js → boot-scrub-sweep-ss1vcamw.js} +2 -2
  14. package/dist/{boot-seeds-bjceqg7b.js → boot-seeds-hwnvgbb3.js} +4 -4
  15. package/dist/{boxd-hr8rsxzq.js → boxd-y0szhp0g.js} +2 -2
  16. package/dist/{claude-adapter-knztdnff.js → claude-adapter-0rjmbhjk.js} +9 -9
  17. package/dist/{claude-managed-adapter-qwejzqkk.js → claude-managed-adapter-6k032agg.js} +4 -4
  18. package/dist/{claude-managed-setup-0vgz4d1j.js → claude-managed-setup-6czvve8q.js} +5 -5
  19. package/dist/{claude-sdk-session-c3g6dv0g.js → claude-sdk-session-pr0znb81.js} +12671 -11885
  20. package/dist/{cli-2v4xxnx2.js → cli-0h8skzss.js} +1 -1
  21. package/dist/{cli-7fa6yv98.js → cli-0qt3epg4.js} +7 -7
  22. package/dist/{cli-aytna2fm.js → cli-19d6v8er.js} +7 -7
  23. package/dist/{cli-8m6gqnf1.js → cli-1jq2em7b.js} +4 -4
  24. package/dist/{cli-fp65jdp2.js → cli-1kvcsd2f.js} +219 -155
  25. package/dist/{cli-8fj8yfmk.js → cli-2vp0z049.js} +1 -1
  26. package/dist/{cli-61p7ty8d.js → cli-2wzkvfgm.js} +3 -3
  27. package/dist/{cli-tjf1bh1v.js → cli-34fygf87.js} +6 -4
  28. package/dist/{cli-czeh7x13.js → cli-3860pmrq.js} +4 -4
  29. package/dist/{cli-dq30fq3q.js → cli-3vw6dd4g.js} +2 -2
  30. package/dist/{cli-4dyhzhpx.js → cli-4gaf3tx5.js} +1 -1
  31. package/dist/{cli-3mf04tkh.js → cli-4vynxtrb.js} +1 -1
  32. package/dist/{cli-hpxcfvdm.js → cli-55h8m1x3.js} +10 -7
  33. package/dist/{cli-hxj888w3.js → cli-5n9w2xzx.js} +2 -2
  34. package/dist/{cli-50whymxq.js → cli-5tq15aa7.js} +2 -2
  35. package/dist/{cli-8sayvj48.js → cli-5web09sb.js} +3 -3
  36. package/dist/{cli-gc715jrc.js → cli-69zzpjgh.js} +1 -1
  37. package/dist/{cli-vgh5adn9.js → cli-6msnpj1z.js} +8 -8
  38. package/dist/{cli-f8rcvf2x.js → cli-7r9tvk8v.js} +76 -3
  39. package/dist/{cli-fbmgpt72.js → cli-7ypg8hka.js} +3 -3
  40. package/dist/{cli-xc8m5cjn.js → cli-887vhew6.js} +3 -3
  41. package/dist/{cli-q8aq48v1.js → cli-8b4rpnwj.js} +1 -1
  42. package/dist/{cli-pzsedyb0.js → cli-8pd1t17c.js} +14 -14
  43. package/dist/{cli-je587f74.js → cli-94gx6ze9.js} +1 -1
  44. package/dist/{cli-h9d3sdnc.js → cli-94mxerrp.js} +1 -1
  45. package/dist/{cli-ef590376.js → cli-9n6g14vs.js} +3 -3
  46. package/dist/{cli-80d5g0fa.js → cli-abby987g.js} +3 -3
  47. package/dist/{cli-grk77aen.js → cli-avax5mp9.js} +2 -2
  48. package/dist/{cli-hd2a204w.js → cli-b42yfn17.js} +14 -14
  49. package/dist/{cli-gkjw33x5.js → cli-b9ygp1kz.js} +2 -2
  50. package/dist/{cli-bh53ppqm.js → cli-bvamr9g0.js} +4 -4
  51. package/dist/{cli-ka4tqjzd.js → cli-ced4azn1.js} +15 -12
  52. package/dist/{cli-v1v49t36.js → cli-cmbb2t8a.js} +3 -3
  53. package/dist/{cli-hhb8kbwd.js → cli-cp163xga.js} +31 -16
  54. package/dist/{cli-55fqpd9q.js → cli-ebpq3c5z.js} +8 -8
  55. package/dist/{cli-9gmkw6xn.js → cli-ehg90jd1.js} +128 -48
  56. package/dist/{cli-jg5txpm6.js → cli-emdfd8fh.js} +75 -1
  57. package/dist/{cli-gxqwm3k3.js → cli-evy3egte.js} +104 -10
  58. package/dist/{cli-a21cwm89.js → cli-ewk3sg68.js} +3 -3
  59. package/dist/{cli-syqcny89.js → cli-f7b9nyvk.js} +9 -9
  60. package/dist/{cli-268b3dgn.js → cli-f9xw9pr4.js} +5 -5
  61. package/dist/{cli-61fzwtjk.js → cli-ffn0a515.js} +9 -9
  62. package/dist/{cli-ya1cj689.js → cli-fw67mnyc.js} +1 -1
  63. package/dist/{cli-dqgnbnxs.js → cli-grbngev5.js} +6 -1
  64. package/dist/{cli-sy2ge2ye.js → cli-hd5bm1e1.js} +4 -4
  65. package/dist/{cli-rfejbpe1.js → cli-htb5bpz2.js} +1 -1
  66. package/dist/{cli-w24741sm.js → cli-j69pzrrz.js} +7 -7
  67. package/dist/{cli-g4dhd3pr.js → cli-jdq3jmny.js} +6 -23
  68. package/dist/{cli-hv3820ez.js → cli-k0nebh10.js} +1 -1
  69. package/dist/{cli-d2epqm0y.js → cli-kezzteka.js} +1 -1
  70. package/dist/{cli-h0ewec3d.js → cli-kr0jpw9c.js} +1 -1
  71. package/dist/{cli-t25rq8mg.js → cli-ks06cd0n.js} +40 -11
  72. package/dist/{cli-1gnf5c7x.js → cli-kwj3131p.js} +1 -1
  73. package/dist/{cli-wtffytm8.js → cli-m8f4379k.js} +3 -3
  74. package/dist/{cli-43dsqhcp.js → cli-n79j1vxc.js} +4 -4
  75. package/dist/{cli-b768ek79.js → cli-nrt048ys.js} +1 -0
  76. package/dist/{cli-h3drhntp.js → cli-pedm2kht.js} +2 -2
  77. package/dist/{cli-eds5xnsz.js → cli-phmy14hb.js} +2 -2
  78. package/dist/{cli-7kv5d674.js → cli-prz1p3ft.js} +5 -5
  79. package/dist/{cli-nbawx3s0.js → cli-q1h041y8.js} +6 -6
  80. package/dist/{cli-cah298e5.js → cli-q41qar56.js} +104 -119
  81. package/dist/{cli-kwm1bek7.js → cli-qmx8bnt4.js} +2 -2
  82. package/dist/{cli-1wew39p0.js → cli-qrvk9nka.js} +28 -19
  83. package/dist/{cli-v8rpjrnx.js → cli-r3dxpmyt.js} +1 -1
  84. package/dist/{cli-0j4qmc80.js → cli-ryem5cfq.js} +8 -8
  85. package/dist/{cli-8pnawt98.js → cli-s8dhq7rj.js} +5 -5
  86. package/dist/{cli-zkbz8m2q.js → cli-sejvnjvw.js} +3 -2
  87. package/dist/{cli-at67kvnp.js → cli-srktrbby.js} +1 -1
  88. package/dist/{cli-wsnradtk.js → cli-srre41gb.js} +2 -2
  89. package/dist/{cli-r6xnchva.js → cli-t0n9svkb.js} +7 -7
  90. package/dist/{cli-y0q92v4r.js → cli-t879ww0y.js} +2 -2
  91. package/dist/{cli-eetzmsy5.js → cli-t9pzz2eq.js} +2 -2
  92. package/dist/{cli-xwsm6xkr.js → cli-tgc1kgg3.js} +1 -1
  93. package/dist/{cli-dw43pnzp.js → cli-tt7dkwjj.js} +7 -7
  94. package/dist/{cli-y754psdt.js → cli-tvyt8w6n.js} +5 -5
  95. package/dist/cli-v09eza21.js +1907 -0
  96. package/dist/{cli-mgr3gatr.js → cli-vbge4rsp.js} +4 -4
  97. package/dist/{cli-ppf9ap9n.js → cli-vcpyttcw.js} +1 -1
  98. package/dist/{cli-1606qw3n.js → cli-wzecestt.js} +1100 -432
  99. package/dist/{cli-5basv0e7.js → cli-x2adbg4j.js} +71 -9
  100. package/dist/{cli-vx9acp12.js → cli-ybte1fqc.js} +1 -1
  101. package/dist/{cli-vdfngx2g.js → cli-ywy8yz6t.js} +2 -2
  102. package/dist/{cli-cpkxh68d.js → cli-z1vam71h.js} +2 -2
  103. package/dist/{cli-djwt4mtn.js → cli-z3x7h79n.js} +15 -9
  104. package/dist/cli-z40t85ms.js +27 -0
  105. package/dist/{cli-ea367bdn.js → cli-zbbtp02a.js} +104 -27
  106. package/dist/{cli-88np9va3.js → cli-zntvmqmm.js} +2 -2
  107. package/dist/{cli-snwz16eg.js → cli-zxa1vmx7.js} +2 -2
  108. package/dist/{cli-50wa8k4h.js → cli-zy9bb22b.js} +1 -2
  109. package/dist/{cli-e4gx499y.js → cli-zzq96q57.js} +273 -106
  110. package/dist/cli.js +21 -21
  111. package/dist/{codex-adapter-493vb8cv.js → codex-adapter-bn7eaxk5.js} +8 -8
  112. package/dist/{codex-hook-ej8hn6z5.js → codex-hook-nnmezjg9.js} +3 -3
  113. package/dist/{codex-login-ven5cz5j.js → codex-login-ktfg1cxk.js} +1 -1
  114. package/dist/{codex-session-runner-ps5m4z1g.js → codex-session-runner-j1e9hffc.js} +9 -9
  115. package/dist/{commands-shktk0b8.js → commands-amhpafrr.js} +3 -3
  116. package/dist/{controller-wn3vd217.js → controller-tw7g10j2.js} +4 -4
  117. package/dist/{controllers-connect-yft057ws.js → controllers-connect-2ssqz7f4.js} +25 -25
  118. package/dist/core-bwp98v4w.js +42 -0
  119. package/dist/{cursor-adapter-8fpm4dng.js → cursor-adapter-d6knjmwa.js} +2 -2
  120. package/dist/{db-0ezhdhz5.js → db-fd6xxm77.js} +3 -3
  121. package/dist/{db-84pz2w5c.js → db-sc59379z.js} +2 -2
  122. package/dist/{devin-adapter-fs90ab4v.js → devin-adapter-3bp6rape.js} +1 -1
  123. package/dist/{dispatcher-h2rz69f6.js → dispatcher-a2gdqz8c.js} +22 -22
  124. package/dist/{docker-1h33jvh9.js → docker-a59g3ebm.js} +2 -2
  125. package/dist/{dsh-adapter-g9yqv09y.js → dsh-adapter-43ygwqn7.js} +2 -2
  126. package/dist/{e2b-jnk0yeva.js → e2b-cn7cvjqy.js} +3 -3
  127. package/dist/{e2b-y7e5kmzf.js → e2b-qnxyfea6.js} +3 -3
  128. package/dist/{easter-egg-3d-m41ad78v.js → easter-egg-3d-a0pphy71.js} +1 -1
  129. package/dist/{embedding-space-yam9zwzj.js → embedding-space-qepzrach.js} +6 -6
  130. package/dist/{embeddings-g2be0y8q.js → embeddings-d7vr881x.js} +1 -1
  131. package/dist/{event-bus-08t2b4y2.js → event-bus-7gbsr0g4.js} +1 -1
  132. package/dist/{execute-hhdejgzf.js → execute-6afts2bn.js} +1 -1
  133. package/dist/{external-channel-kjt2yzfj.js → external-channel-881zq1x4.js} +2 -2
  134. package/dist/fx-adapter-cr2hq17y.js +20 -0
  135. package/dist/grok-adapter-ayddnbsc.js +20 -0
  136. package/dist/handlers-7ghs84x2.js +41 -0
  137. package/dist/{heartbeat-2e5jdexj.js → heartbeat-4c022m6a.js} +25 -25
  138. package/dist/{hook-acg9saz7.js → hook-4k84x499.js} +6 -6
  139. package/dist/{hook-34s8cmgn.js → hook-a7eh6zty.js} +9 -9
  140. package/dist/{http-ra2zr2f8.js → http-6aw5wanc.js} +456 -1864
  141. package/dist/{index-mbpxhc4w.js → index-126v2d0t.js} +1 -4
  142. package/dist/index-dtt0d634.js +44 -0
  143. package/dist/index-hmszyqkk.js +42 -0
  144. package/dist/index-j6rm1rtn.js +39 -0
  145. package/dist/{index-9q42cr54.js → index-rwwhsmjg.js} +1 -1
  146. package/dist/{index-93bw5wds.js → index-xhad0n8m.js} +1 -1
  147. package/dist/{index-2z1z7qx6.js → index-yq9hhhhy.js} +26 -26
  148. package/dist/{index-9r4j0a60.js → index-z2g9469g.js} +410 -27
  149. package/dist/{k8s-8326q0rq.js → k8s-36gfn847.js} +2 -2
  150. package/dist/{keepalive-vjnnqbkm.js → keepalive-zhbmztqw.js} +5 -5
  151. package/dist/lead-g2j4q39z.js +83 -0
  152. package/dist/{maintenance-px2g599e.js → maintenance-rsp0591h.js} +1 -1
  153. package/dist/{node-2wfcey7d.js → node-0as4n1ef.js} +3 -3
  154. package/dist/{node-zd6shky9.js → node-dhxbt01p.js} +3 -3
  155. package/dist/{node-z67yjre7.js → node-rxte5hc6.js} +290 -70
  156. package/dist/{node-hjn5n1yp.js → node-t0ct2zpw.js} +3 -5
  157. package/dist/{oauth-refresh-sweep-nkykf09m.js → oauth-refresh-sweep-w3cqmxq7.js} +4 -4
  158. package/dist/{object-webhooks-gt9xnq21.js → object-webhooks-331hay92.js} +7 -7
  159. package/dist/{onboard-1f134p65.js → onboard-n2w80m2n.js} +7 -7
  160. package/dist/{opencode-adapter-94976yab.js → opencode-adapter-z98127cz.js} +8 -8
  161. package/dist/{otel-impl-5d4p2fqs.js → otel-impl-xsk35tvf.js} +2 -2
  162. package/dist/{pending-vkk0vx6n.js → pending-2e6trkxd.js} +23 -23
  163. package/dist/{pi-mono-adapter-cyzdv5er.js → pi-mono-adapter-wh6yndtm.js} +13 -13
  164. package/dist/{pricing-refresh-jtmjwss9.js → pricing-refresh-9355dj1t.js} +2 -2
  165. package/dist/{rbac-roles-yd1fgpsn.js → rbac-roles-58y3m912.js} +3 -3
  166. package/dist/{rbac-roles-1fvmdyeb.js → rbac-roles-8eajw4s6.js} +6 -4
  167. package/dist/{render-v2-kb5s3vx4.js → render-v2-7gskkmd4.js} +7 -7
  168. package/dist/{resume-z1vs44n5.js → resume-0drnmpja.js} +10 -10
  169. package/dist/{runtime-gk6ct7r7.js → runtime-d2tcmqte.js} +1 -1
  170. package/dist/{session-access-nz6nre4d.js → session-access-0ztys6bd.js} +5 -5
  171. package/dist/{session-source-backfill-wb60zjkd.js → session-source-backfill-cdm5s046.js} +3 -3
  172. package/dist/{setup-2x8g8j4s.js → setup-pqwb9tcc.js} +1 -1
  173. package/dist/thread-buffer-epx3san4.js +42 -0
  174. package/dist/{tree-visibility-ts3z30kw.js → tree-visibility-rwz67mje.js} +2 -2
  175. package/dist/{user-merge-jobs-zetg26e0.js → user-merge-jobs-mxrhamwt.js} +3 -3
  176. package/dist/{virtual-modules-674fka8x.js → virtual-modules-71y1gsmg.js} +3 -3
  177. package/dist/{work-objects-w52yyjxm.js → work-objects-3k4ykt9j.js} +25 -25
  178. package/dist/worker-09gqn9xy.js +83 -0
  179. package/dist/{worker-follow-up-dyfxyjbj.js → worker-follow-up-y0h64xpr.js} +22 -22
  180. package/dist/{x-asbrnafg.js → x-d27jj7z7.js} +2 -2
  181. package/openapi.json +861 -33
  182. package/package.json +4 -4
  183. package/src/apps/sync.ts +20 -5
  184. package/src/azure-devops/boards-sync.ts +1 -1
  185. package/src/be/db/approvals.ts +2 -0
  186. package/src/be/db/runtime.ts +5 -0
  187. package/src/be/db/script-run-sources.ts +17 -0
  188. package/src/be/db/slack-trees.ts +12 -1
  189. package/src/be/db/tasks/read.ts +25 -1
  190. package/src/be/db/tasks/write.ts +47 -12
  191. package/src/be/db/users/avatar.ts +12 -0
  192. package/src/be/db-retention.ts +1 -1
  193. package/src/be/db.ts +149 -67
  194. package/src/be/design-system.ts +63 -0
  195. package/src/be/migrations/342_script_run_sources.sql +20 -0
  196. package/src/be/migrations/344_user_avatar.sql +4 -0
  197. package/src/be/migrations/345_task_status_kind.sql +6 -0
  198. package/src/be/migrations/runner.ts +8 -0
  199. package/src/be/migrations/script-run-sources.ts +51 -0
  200. package/src/be/primitives/object-embed.ts +2 -2
  201. package/src/be/primitives/objects.ts +2 -2
  202. package/src/be/rbac-roles.ts +2 -0
  203. package/src/be/runtime-pools/supervisor.ts +1 -0
  204. package/src/be/scripts/typecheck.ts +5 -3
  205. package/src/be/seed-scripts/catalog/design-system-seed.ts +158 -0
  206. package/src/be/seed-scripts/index.ts +9 -0
  207. package/src/be/swarm-config-guard.ts +25 -1
  208. package/src/bitbucket/handlers.ts +1 -1
  209. package/src/commands/credential-outcome-report.ts +96 -0
  210. package/src/commands/onboard/agent-fs-version.ts +1 -1
  211. package/src/commands/runner.ts +49 -3
  212. package/src/event-waits/github.ts +39 -6
  213. package/src/event-waits/index.ts +4 -2
  214. package/src/event-waits/types.ts +10 -3
  215. package/src/extensions/contract-types.generated.ts +1 -1
  216. package/src/github/app.ts +177 -13
  217. package/src/github/handlers.ts +7 -2
  218. package/src/github/pull-request-state.ts +100 -11
  219. package/src/gitlab/handlers.ts +2 -2
  220. package/src/heartbeat/heartbeat.ts +24 -5
  221. package/src/http/all-routes.ts +1 -0
  222. package/src/http/api-keys.ts +26 -0
  223. package/src/http/approval-chat-answer.ts +99 -0
  224. package/src/http/approval-requests.ts +280 -225
  225. package/src/http/asset-key-write.ts +45 -0
  226. package/src/http/assets.ts +4 -3
  227. package/src/http/design-system.ts +103 -0
  228. package/src/http/github-token.ts +27 -6
  229. package/src/http/index.ts +10 -6
  230. package/src/http/pages-public.ts +25 -10
  231. package/src/http/pages.ts +21 -10
  232. package/src/http/person-responder.ts +28 -0
  233. package/src/http/schedules.ts +6 -6
  234. package/src/http/sessions.ts +7 -2
  235. package/src/http/tasks.ts +23 -5
  236. package/src/http/users.ts +5 -0
  237. package/src/http/webhooks.ts +19 -1
  238. package/src/http/workflows.ts +5 -10
  239. package/src/integrations/chat-sdk/adapters.ts +33 -3
  240. package/src/integrations/chat-sdk/commands.ts +3 -1
  241. package/src/integrations/chat-sdk/inbound.ts +6 -18
  242. package/src/integrations/chat-sdk/mentions.ts +188 -0
  243. package/src/integrations/chat-sdk/outbound.ts +20 -3
  244. package/src/integrations/chat-sdk/router.ts +8 -0
  245. package/src/integrations/chat-sdk/telegram-thread.ts +12 -0
  246. package/src/jira/adf.ts +35 -9
  247. package/src/jira/sync.ts +1 -1
  248. package/src/kv-reserved-namespaces.ts +5 -0
  249. package/src/linear/sync.ts +5 -3
  250. package/src/pages/page-head.ts +11 -1
  251. package/src/prompts/session-templates.ts +1 -0
  252. package/src/providers/acp-targets.ts +2 -2
  253. package/src/providers/amp-adapter.ts +1 -1
  254. package/src/providers/claude-adapter.ts +5 -0
  255. package/src/providers/claude-sdk-session.ts +5 -0
  256. package/src/providers/dsh-adapter.ts +48 -13
  257. package/src/providers/runtime-dependencies.ts +1 -1
  258. package/src/rbac/legacy-policy.ts +4 -0
  259. package/src/rbac/permissions.ts +8 -0
  260. package/src/scheduler/deferred-task-waits.ts +74 -13
  261. package/src/scheduler/index.ts +1 -0
  262. package/src/scheduler/scheduler.test.ts +32 -1
  263. package/src/scheduler/scheduler.ts +24 -1
  264. package/src/script-workflows/executor.ts +6 -0
  265. package/src/script-workflows/supervisor.ts +2 -1
  266. package/src/scripts-runtime/sdk-allowlist.ts +2 -0
  267. package/src/scripts-runtime/swarm-sdk.ts +20 -24
  268. package/src/scripts-runtime/types/stdlib.d.ts +12 -2
  269. package/src/scripts-runtime/types/swarm-extension.d.ts +19 -2
  270. package/src/scripts-runtime/types/swarm-sdk.d.ts +12 -2
  271. package/src/server.ts +2 -0
  272. package/src/slack/actions.ts +4 -1
  273. package/src/slack/approval-actions.ts +148 -0
  274. package/src/slack/approval-buttons.ts +28 -0
  275. package/src/slack/render-v2.ts +148 -7
  276. package/src/tests/api-drain-worker-e2e.test.ts +0 -2
  277. package/src/tests/approval-auto-cancellation-migration.test.ts +8 -19
  278. package/src/tests/approval-card-resolution.test.ts +2 -17
  279. package/src/tests/approval-requests-notifications.test.ts +41 -27
  280. package/src/tests/approval-requests.test.ts +137 -369
  281. package/src/tests/apps-sync-engine.test.ts +5 -3
  282. package/src/tests/apps-table-filters-migration.test.ts +44 -25
  283. package/src/tests/bitbucket-handlers.test.ts +2 -0
  284. package/src/tests/chat-sdk-commands.test.ts +1 -0
  285. package/src/tests/chat-sdk-mentions.test.ts +183 -0
  286. package/src/tests/claude-adapter.test.ts +35 -0
  287. package/src/tests/codex-adapter.test.ts +3 -92
  288. package/src/tests/codex-gpt6-release.test.ts +0 -9
  289. package/src/tests/codex-oauth-credential-info.test.ts +35 -18
  290. package/src/tests/codex-oauth.test.ts +0 -6
  291. package/src/tests/codex-pool.test.ts +5 -214
  292. package/src/tests/codex-rate-limit-parse.test.ts +0 -7
  293. package/src/tests/codex-swarm-events.test.ts +11 -54
  294. package/src/tests/create-page-tool.test.ts +5 -0
  295. package/src/tests/db-client-busy-retry.test.ts +49 -16
  296. package/src/tests/defer-task.test.ts +1 -0
  297. package/src/tests/dsh-adapter.test.ts +53 -1
  298. package/src/tests/e2e-shards.test.ts +9 -9
  299. package/src/tests/enabled-tools.test.ts +0 -2
  300. package/src/tests/fixtures/base-prompt-baseline.json +6 -6
  301. package/src/tests/fixtures/compiled-source-schema-boot.ts +24 -0
  302. package/src/tests/fixtures/secret-corpus.ts +43 -1
  303. package/src/tests/github-app-worker-auth-helper.test.ts +147 -1
  304. package/src/tests/gitlab-handlers.test.ts +2 -0
  305. package/src/tests/heartbeat-jev-gate.test.ts +9 -241
  306. package/src/tests/heartbeat-reroute-decision.test.ts +2 -0
  307. package/src/tests/heartbeat-stall-thresholds.test.ts +174 -0
  308. package/src/tests/heartbeat-supersede-resume.test.ts +2 -0
  309. package/src/tests/heartbeat.test.ts +1 -0
  310. package/src/tests/jira-adf.test.ts +42 -2
  311. package/src/tests/key-usage-selection.test.ts +302 -0
  312. package/src/tests/memory-e2e.test.ts +34 -103
  313. package/src/tests/memory-key-paths.test.ts +5 -0
  314. package/src/tests/memory-rater-llm.test.ts +33 -149
  315. package/src/tests/memory-store.test.ts +24 -125
  316. package/src/tests/memory.test.ts +31 -100
  317. package/src/tests/merge-gate-detect-changes.test.ts +314 -16
  318. package/src/tests/migration-342-script-run-sources.test.ts +196 -0
  319. package/src/tests/migration-bunfs-compat.test.ts +129 -9
  320. package/src/tests/otel-service-name.test.ts +0 -9
  321. package/src/tests/otel-session-cost-metrics.test.ts +1 -38
  322. package/src/tests/pool-session-logs.test.ts +8 -42
  323. package/src/tests/pre-push-affected-tests.test.ts +106 -0
  324. package/src/tests/prompt-template-session.test.ts +3 -0
  325. package/src/tests/rbac-e2e-helpers.test.ts +10 -4
  326. package/src/tests/rbac-e2e-helpers.ts +13 -4
  327. package/src/tests/rbac-roles.test.ts +2 -0
  328. package/src/tests/runner-api-drain.test.ts +2 -17
  329. package/src/tests/runner-terminal-window-report.test.ts +132 -0
  330. package/src/tests/runtime-e2b-pools.test.ts +7 -1
  331. package/src/tests/runtime-supervisor-failures.test.ts +1 -0
  332. package/src/tests/sandboxed-process.test.ts +26 -21
  333. package/src/tests/schedule-http-triage-tools.test.ts +12 -9
  334. package/src/tests/schedule-target-type.test.ts +4 -1
  335. package/src/tests/scheduled-tasks.test.ts +14 -51
  336. package/src/tests/script-connections.test.ts +2 -0
  337. package/src/tests/script-executor-conformance.test.ts +4 -48
  338. package/src/tests/script-executor-quickjs-pool.test.ts +9 -7
  339. package/src/tests/script-native-startup.test.ts +21 -25
  340. package/src/tests/script-runs-retention.test.ts +43 -16
  341. package/src/tests/script-workflows-runtime-e2e.test.ts +56 -22
  342. package/src/tests/scripts-http.test.ts +9 -3
  343. package/src/tests/sdk-allowlist.test.ts +26 -13
  344. package/src/tests/sdk-store-progress-skipped.test.ts +12 -5
  345. package/src/tests/secret-rules.test.ts +38 -2
  346. package/src/tests/secret-scrub-gate.test.ts +7 -0
  347. package/src/tests/secret-scrubber.test.ts +62 -2
  348. package/src/tests/seed-scripts.test.ts +2 -2
  349. package/src/tests/session-logs.test.ts +1 -260
  350. package/src/tests/slack-render-v2.test.ts +5 -148
  351. package/src/tests/system-one-hosts-ui-mirror.test.ts +1 -0
  352. package/src/tests/task-cascade-fail.test.ts +1 -0
  353. package/src/tests/task-supersede-resume.test.ts +1 -0
  354. package/src/tests/test-proc.ts +5 -2
  355. package/src/tests/vcs-azure-devops.test.ts +10 -0
  356. package/src/tests/vcs-provider.test.ts +8 -0
  357. package/src/tests/window-stream-reporter.test.ts +122 -0
  358. package/src/tests/workflow-agent-task-retry.test.ts +1 -3
  359. package/src/tests/workflow-cascade-cancel.test.ts +1 -0
  360. package/src/tests/workflow-retry-v2.test.ts +34 -43
  361. package/src/tests/workflow-retry-validation.test.ts +8 -48
  362. package/src/tests/worktree-reaper.test.ts +2 -2
  363. package/src/themes/design-system.ts +163 -0
  364. package/src/themes/page-theme.ts +28 -19
  365. package/src/tools/cancel-task.ts +2 -2
  366. package/src/tools/chat-post.ts +7 -3
  367. package/src/tools/create-page.ts +3 -0
  368. package/src/tools/defer-task.ts +7 -2
  369. package/src/tools/design-system.ts +102 -0
  370. package/src/tools/get-task-details.ts +8 -4
  371. package/src/tools/get-tasks.ts +13 -2
  372. package/src/tools/manage-user.ts +9 -0
  373. package/src/tools/mcp-servers/mcp-server-get.ts +1 -1
  374. package/src/tools/mcp-servers/mcp-server-list.ts +1 -1
  375. package/src/tools/register-chat-channel.ts +11 -2
  376. package/src/tools/skills/skill-get-file.ts +1 -1
  377. package/src/tools/skills/skill-get.ts +1 -1
  378. package/src/tools/skills/skill-list.ts +1 -1
  379. package/src/tools/skills/skill-search.ts +1 -1
  380. package/src/tools/store-progress.ts +5 -3
  381. package/src/tools/utils.ts +49 -4
  382. package/src/tools/workflows/get-workflow-run.ts +1 -1
  383. package/src/tools/workflows/get-workflow.ts +1 -1
  384. package/src/tools/workflows/list-workflow-runs.ts +1 -1
  385. package/src/tools/workflows/list-workflows.ts +1 -1
  386. package/src/types.ts +158 -0
  387. package/src/utils/constants.ts +12 -0
  388. package/src/utils/credentials.ts +42 -5
  389. package/src/utils/error-tracker.ts +6 -0
  390. package/src/utils/key-usage.ts +114 -0
  391. package/src/utils/sandboxed-process.ts +1 -0
  392. package/src/utils/secret-rules.generated.ts +149 -149
  393. package/src/utils/secret-scrubber.ts +111 -5
  394. package/src/vcs/azure-devops.ts +22 -1
  395. package/src/vcs/index.ts +3 -1
  396. package/src/workflows/approval-inline.ts +122 -0
  397. package/src/workflows/approval-notifications.ts +7 -2
  398. package/src/workflows/engine.ts +6 -5
  399. package/src/workflows/executors/agent-task.ts +14 -0
  400. package/src/workflows/executors/system-one-providers.ts +23 -0
  401. package/src/workflows/resume.ts +5 -2
  402. package/templates/skills/apps/SKILL.md +2 -0
  403. package/templates/skills/apps/content.md +2 -0
  404. package/templates/skills/boards-and-sheets/content.md +4 -2
  405. package/templates/skills/pages/content.md +41 -8
  406. package/templates/skills/swarm-docs/content.md +6 -0
  407. package/templates/skills/swarm-scripts/SKILL.md +1 -0
  408. package/templates/skills/swarm-scripts/content.md +1 -0
  409. package/templates/skills/workflow-iterate/content.md +1 -1
  410. package/dist/acp-adapter-t2q6nsqv.js +0 -17
  411. package/dist/cli-kh973792.js +0 -98
  412. package/dist/core-nheayfgm.js +0 -42
  413. package/dist/fx-adapter-8g7xsp8q.js +0 -20
  414. package/dist/grok-adapter-ztk2zkz1.js +0 -20
  415. package/dist/handlers-9ywssz71.js +0 -41
  416. package/dist/index-6mgbdtv1.js +0 -44
  417. package/dist/index-hqdsn2t2.js +0 -39
  418. package/dist/index-st231bqv.js +0 -40
  419. package/dist/lead-mk0xkth2.js +0 -82
  420. package/dist/thread-buffer-d50rqpev.js +0 -42
  421. package/dist/worker-662x1vse.js +0 -82
  422. package/src/tests/apps-table-selection-migration.test.ts +0 -95
  423. package/src/tests/extensions-example-heartbeat-remediate.test.ts +0 -69
  424. package/src/tests/extensions-example-rewrite-and-suppress.test.ts +0 -70
@@ -84,6 +84,7 @@ import {
84
84
  humanOnlyConfigKeyError,
85
85
  isReservedConfigKey,
86
86
  reservedKeyError,
87
+ SCHEDULER_INTERVAL_MS_BOUNDS,
87
88
  validateConfigValue,
88
89
  validateExportToEnv,
89
90
  init_swarm_config_guard,
@@ -406,27 +407,27 @@ import {
406
407
  recordInlineScriptRun2,
407
408
  exports_db,
408
409
  init_db4
409
- } from "./cli-e4gx499y.js";
410
+ } from "./cli-zzq96q57.js";
410
411
  import {
411
412
  assertMayActOnOperatorGrantedTarget2,
412
413
  getUserGrant2,
413
414
  init_rbac_roles
414
- } from "./cli-tjf1bh1v.js";
415
+ } from "./cli-34fygf87.js";
415
416
  import {
416
417
  ensurePricingSeeded2,
417
418
  ensureRbacSeeded2,
418
419
  ensureModelProfilesSeeded2,
419
420
  init_boot_seeds
420
- } from "./cli-fbmgpt72.js";
421
+ } from "./cli-7ypg8hka.js";
421
422
  import {
422
423
  requestModelCatalogRefresh2,
423
424
  startPricingRefreshLoop2,
424
425
  init_pricing_refresh
425
- } from "./cli-h3drhntp.js";
426
+ } from "./cli-pedm2kht.js";
426
427
  import {
427
428
  workflowEventBus2,
428
429
  init_event_bus
429
- } from "./cli-vx9acp12.js";
430
+ } from "./cli-ybte1fqc.js";
430
431
  import {
431
432
  slackCode,
432
433
  slackMissingScopeMessage,
@@ -435,7 +436,7 @@ import {
435
436
  externalChannelToolError2,
436
437
  getChannelBlockReason2,
437
438
  init_external_channel
438
- } from "./cli-hxj888w3.js";
439
+ } from "./cli-5n9w2xzx.js";
439
440
  import {
440
441
  tableToAscii2,
441
442
  init_dist8
@@ -498,7 +499,7 @@ import {
498
499
  startSlackApp2,
499
500
  stopSlackAppUnderLifecycleLock2,
500
501
  init_app4
501
- } from "./cli-ea367bdn.js";
502
+ } from "./cli-zbbtp02a.js";
502
503
  import {
503
504
  AGENT_MAX_TASKS_CONFIG_KEY,
504
505
  resetAgentMaxTasksMirror,
@@ -519,7 +520,7 @@ import {
519
520
  postApprovalCancellationUpdates2,
520
521
  createApprovalFollowUpTask2,
521
522
  init_approval_notifications
522
- } from "./cli-gxqwm3k3.js";
523
+ } from "./cli-evy3egte.js";
523
524
  import {
524
525
  shapeApprovalResolution,
525
526
  init_approval_resolution,
@@ -543,7 +544,7 @@ import {
543
544
  resumeFromChildRun2,
544
545
  initWaitBusSubscriptions2,
545
546
  init_resume
546
- } from "./cli-hpxcfvdm.js";
547
+ } from "./cli-55h8m1x3.js";
547
548
  import {
548
549
  getFileStorageProvider2,
549
550
  init_registry2
@@ -551,7 +552,7 @@ import {
551
552
  import {
552
553
  getRuntimePool2,
553
554
  init_db2
554
- } from "./cli-268b3dgn.js";
555
+ } from "./cli-f9xw9pr4.js";
555
556
  import {
556
557
  duplicateGuardedQueryKey,
557
558
  parseQueryParams,
@@ -584,13 +585,13 @@ import {
584
585
  findRoute,
585
586
  route,
586
587
  init_route_def
587
- } from "./cli-dw43pnzp.js";
588
+ } from "./cli-tt7dkwjj.js";
588
589
  import {
589
590
  COMPOSIO_HTTP_METHODS,
590
591
  executeComposioRequest,
591
592
  composioArgsFromParts,
592
593
  init_composio
593
- } from "./cli-3mf04tkh.js";
594
+ } from "./cli-4vynxtrb.js";
594
595
  import {
595
596
  object,
596
597
  init_v4_mini
@@ -686,7 +687,7 @@ import {
686
687
  init_typecheck,
687
688
  parseSkillContent,
688
689
  init_skill_parser
689
- } from "./cli-ka4tqjzd.js";
690
+ } from "./cli-ced4azn1.js";
690
691
  import {
691
692
  detachedProcessGroup,
692
693
  registerProcessGroup,
@@ -701,7 +702,7 @@ import {
701
702
  ensureToken,
702
703
  ensureTokenOrThrow,
703
704
  init_ensure_token
704
- } from "./cli-8sayvj48.js";
705
+ } from "./cli-5web09sb.js";
705
706
  import {
706
707
  A1Error,
707
708
  colName,
@@ -736,11 +737,11 @@ import {
736
737
  listObjects,
737
738
  reindexObjects,
738
739
  init_objects
739
- } from "./cli-w24741sm.js";
740
+ } from "./cli-j69pzrrz.js";
740
741
  import {
741
742
  agentFsClientFor,
742
743
  init_agent_fs_identity
743
- } from "./cli-snwz16eg.js";
744
+ } from "./cli-zxa1vmx7.js";
744
745
  import {
745
746
  FilesError,
746
747
  providerPath,
@@ -754,7 +755,7 @@ import {
754
755
  isSlackLeaveThreadDisabled,
755
756
  leaveSlackThread,
756
757
  init_left_threads
757
- } from "./cli-v8rpjrnx.js";
758
+ } from "./cli-r3dxpmyt.js";
758
759
  import {
759
760
  require_fast_deep_equal
760
761
  } from "./cli-bhp11egn.js";
@@ -839,7 +840,7 @@ import {
839
840
  validateDefinition,
840
841
  applyDefinitionPatch,
841
842
  init_definition2
842
- } from "./cli-hhb8kbwd.js";
843
+ } from "./cli-cp163xga.js";
843
844
  import {
844
845
  isMultiRuntimeEnabled,
845
846
  init_multi_runtime2
@@ -862,16 +863,16 @@ import {
862
863
  import {
863
864
  canProvisionKind,
864
865
  init_runtime_providers
865
- } from "./cli-43dsqhcp.js";
866
+ } from "./cli-n79j1vxc.js";
866
867
  import {
867
868
  getSessionRoot,
868
869
  sessionAccessForRoot,
869
870
  init_session_shares
870
- } from "./cli-1gnf5c7x.js";
871
+ } from "./cli-kwj3131p.js";
871
872
  import {
872
873
  publicEndpointSsrfOptions,
873
874
  init_mcp_wrapper
874
- } from "./cli-gkjw33x5.js";
875
+ } from "./cli-b9ygp1kz.js";
875
876
  import {
876
877
  findUserById,
877
878
  findUserByExternalId,
@@ -886,13 +887,13 @@ import {
886
887
  resolveSessionToken,
887
888
  fingerprintApiKey,
888
889
  init_users
889
- } from "./cli-grk77aen.js";
890
+ } from "./cli-avax5mp9.js";
890
891
  import {
891
892
  AMP_ESTIMATE_MODELS,
892
893
  ampBillsCacheWrites,
893
894
  resolveAmpModel,
894
895
  init_amp_models
895
- } from "./cli-rfejbpe1.js";
896
+ } from "./cli-htb5bpz2.js";
896
897
  import {
897
898
  resolveGitHubHost,
898
899
  getGitHubLinkConfig,
@@ -910,12 +911,12 @@ import {
910
911
  init_task_attachment_links,
911
912
  contentSha256,
912
913
  init_profile_sync
913
- } from "./cli-aytna2fm.js";
914
+ } from "./cli-19d6v8er.js";
914
915
  import {
915
916
  getSlackConfiguration,
916
917
  isSlackConfigured,
917
- init_config4
918
- } from "./cli-eetzmsy5.js";
918
+ init_config5
919
+ } from "./cli-t9pzz2eq.js";
919
920
  import {
920
921
  isSteeringEnabled2,
921
922
  init_steering_enabled
@@ -928,7 +929,7 @@ import {
928
929
  splitCredentialPool,
929
930
  selectCredential,
930
931
  init_credentials2
931
- } from "./cli-5basv0e7.js";
932
+ } from "./cli-x2adbg4j.js";
932
933
  import {
933
934
  findInterpolationTokens,
934
935
  interpolate,
@@ -938,7 +939,7 @@ import {
938
939
  init_registry3,
939
940
  resolveTemplate,
940
941
  init_resolver
941
- } from "./cli-b768ek79.js";
942
+ } from "./cli-nrt048ys.js";
942
943
  import {
943
944
  normalizeAssetKey,
944
945
  defaultAssetKey,
@@ -967,6 +968,7 @@ import {
967
968
  splitLegacyModelAlias,
968
969
  AgentTaskStatusSchema,
969
970
  isTerminalTaskStatus,
971
+ TaskStatusKindSchema,
970
972
  RoutingReasonSchema,
971
973
  ProviderNameSchema,
972
974
  SteerModeSchema,
@@ -977,6 +979,7 @@ import {
977
979
  AttachmentInputSchema,
978
980
  AgentStatusSchema,
979
981
  AgentAvatarSchema,
982
+ UserAvatarSchema,
980
983
  AppIconSchema,
981
984
  AgentSlackIconSchema,
982
985
  ChannelTypeSchema,
@@ -1000,6 +1003,8 @@ import {
1000
1003
  PageContentTypeSchema,
1001
1004
  PageAuthModeSchema,
1002
1005
  PageThemeTokensInputSchema,
1006
+ DesignSystemSchema,
1007
+ DesignSystemInputSchema,
1003
1008
  MetricDefinitionSchema,
1004
1009
  WorkflowRunStatusSchema,
1005
1010
  ScriptRunStatusSchema,
@@ -1013,7 +1018,7 @@ import {
1013
1018
  KvNamespaceSchema,
1014
1019
  KvKeySchema,
1015
1020
  init_types5
1016
- } from "./cli-f8rcvf2x.js";
1021
+ } from "./cli-7r9tvk8v.js";
1017
1022
  import {
1018
1023
  init_zod
1019
1024
  } from "./cli-96234j5w.js";
@@ -1058,7 +1063,7 @@ import {
1058
1063
  getCombState,
1059
1064
  isAgentFsProxyEnabled,
1060
1065
  init_constants3
1061
- } from "./cli-dqgnbnxs.js";
1066
+ } from "./cli-grbngev5.js";
1062
1067
  import {
1063
1068
  parseEnvFlag,
1064
1069
  isEnvFlagEnabled,
@@ -1067,7 +1072,7 @@ import {
1067
1072
  import {
1068
1073
  init_package,
1069
1074
  package_default
1070
- } from "./cli-sy2ge2ye.js";
1075
+ } from "./cli-hd5bm1e1.js";
1071
1076
  import {
1072
1077
  getNodeEnv,
1073
1078
  isDevOrTestNodeEnv,
@@ -1087,7 +1092,7 @@ import {
1087
1092
  registerVolatileSecret,
1088
1093
  registerSensitiveKeyName,
1089
1094
  init_secret_scrubber
1090
- } from "./cli-fp65jdp2.js";
1095
+ } from "./cli-1kvcsd2f.js";
1091
1096
  import {
1092
1097
  __toESM,
1093
1098
  __commonJS,
@@ -12257,6 +12262,7 @@ function resetGitHub() {
12257
12262
  appId = null;
12258
12263
  privateKey = null;
12259
12264
  tokenCache.clear();
12265
+ installationCache.clear();
12260
12266
  }
12261
12267
  function initGitHub() {
12262
12268
  if (initialized) {
@@ -12393,27 +12399,130 @@ async function mintInstallationToken(installationId, creds, minValidityMs) {
12393
12399
  return null;
12394
12400
  }
12395
12401
  }
12396
- async function getWorkerInstallationToken() {
12402
+ function normalizeRepo(repo) {
12403
+ const trimmed = repo.trim().replace(/\/+$/, "");
12404
+ const lastTwo = trimmed.replace(/\.git$/i, "").match(/([^/:]+\/[^/:]+)$/);
12405
+ if (!lastTwo)
12406
+ return trimmed.toLowerCase();
12407
+ const [owner, name] = lastTwo[1].split("/");
12408
+ if (owner === "." || owner === ".." || name === "." || name === "..")
12409
+ return "";
12410
+ return lastTwo[1].toLowerCase();
12411
+ }
12412
+ function allowedRepoOwners() {
12413
+ return new Set((process.env.GITHUB_APP_REPO_OWNERS ?? "").split(",").map((owner) => owner.trim().toLowerCase()).filter(Boolean));
12414
+ }
12415
+ function registeredSlugOnHost(url, host) {
12416
+ const trimmed = url.trim().replace(/\/+$/, "").replace(/\.git$/i, "");
12417
+ let urlHost = null;
12418
+ let path;
12419
+ const scp = trimmed.match(/^[^@/:]+@([^:/]+):(.+)$/);
12420
+ if (scp) {
12421
+ urlHost = scp[1].toLowerCase();
12422
+ path = scp[2];
12423
+ } else if (/^[a-z][a-z0-9+.-]*:\/\//i.test(trimmed)) {
12424
+ try {
12425
+ const parsed = new URL(trimmed);
12426
+ urlHost = parsed.host.toLowerCase();
12427
+ path = parsed.pathname;
12428
+ } catch {
12429
+ return null;
12430
+ }
12431
+ } else {
12432
+ path = trimmed;
12433
+ }
12434
+ if (urlHost !== null && urlHost !== host && !(host === "github.com" && urlHost === "www.github.com")) {
12435
+ return null;
12436
+ }
12437
+ const segments = path.replace(/^\/+/, "").split("/");
12438
+ if (segments.length !== 2)
12439
+ return null;
12440
+ const slug = normalizeRepo(segments.join("/"));
12441
+ return slug || null;
12442
+ }
12443
+ async function resolveInstallationId(repo, creds, owners) {
12444
+ const cached = installationCache.get(repo);
12445
+ if (cached && cached.expiresAt > Date.now())
12446
+ return cached.id;
12447
+ const jwt = await generateAppJWT(creds);
12448
+ if (!jwt)
12449
+ return null;
12450
+ const refuse = () => {
12451
+ installationCache.set(repo, { id: null, expiresAt: Date.now() + NO_INSTALLATION_CACHE_TTL_MS });
12452
+ return null;
12453
+ };
12454
+ try {
12455
+ const response = await fetch(githubApiUrl(`/repos/${repo}/installation`), {
12456
+ headers: {
12457
+ Accept: "application/vnd.github+json",
12458
+ Authorization: `Bearer ${jwt}`,
12459
+ "X-GitHub-Api-Version": "2022-11-28"
12460
+ }
12461
+ });
12462
+ if (response.status !== 200) {
12463
+ console.log(`[GitHub] No installation for ${repo}: ${response.status}`);
12464
+ return refuse();
12465
+ }
12466
+ const data = await response.json();
12467
+ if (typeof data.id !== "number")
12468
+ return refuse();
12469
+ const account = typeof data.account?.login === "string" ? data.account.login.toLowerCase() : "";
12470
+ if (!owners.has(account)) {
12471
+ console.log(`[GitHub] Installation for ${repo} belongs to an owner that is not allowed`);
12472
+ return refuse();
12473
+ }
12474
+ installationCache.set(repo, {
12475
+ id: data.id,
12476
+ expiresAt: Date.now() + INSTALLATION_CACHE_TTL_MS
12477
+ });
12478
+ return data.id;
12479
+ } catch (error) {
12480
+ console.error("[GitHub] Error resolving the repo installation:", error);
12481
+ return null;
12482
+ }
12483
+ }
12484
+ async function getWorkerInstallationToken(repo) {
12397
12485
  if (isEnvFlagEnabled("GITHUB_DISABLE", false))
12398
12486
  return { status: "unconfigured" };
12399
12487
  const workerAppId = process.env.GITHUB_APP_ID?.trim();
12400
12488
  const rawKey = process.env.GITHUB_APP_PRIVATE_KEY?.trim();
12401
- const rawInstallation = process.env.GITHUB_APP_INSTALLATION_ID?.trim() ?? "";
12402
- if (!workerAppId || !rawKey || !/^[1-9][0-9]{0,15}$/.test(rawInstallation)) {
12489
+ if (!workerAppId || !rawKey)
12403
12490
  return { status: "unconfigured" };
12404
- }
12405
- if (!resolveGitHubHost().ok)
12491
+ const host = resolveGitHubHost();
12492
+ if (!host.ok)
12406
12493
  return { status: "error" };
12407
- const minted = await mintInstallationToken(Number(rawInstallation), { appId: workerAppId, privateKey: decodePrivateKey(rawKey) }, 600000);
12494
+ const creds = { appId: workerAppId, privateKey: decodePrivateKey(rawKey) };
12495
+ const owners = allowedRepoOwners();
12496
+ const target = repo ? normalizeRepo(repo) : "";
12497
+ const owner = target.split("/")[0] ?? "";
12498
+ let installationId;
12499
+ if (target && owners.has(owner)) {
12500
+ const registered = (await getSwarmRepos2()).some((r) => registeredSlugOnHost(r.url, host.config.host) === target);
12501
+ if (!registered)
12502
+ return { status: "forbidden" };
12503
+ const resolved = await resolveInstallationId(target, creds, owners);
12504
+ if (resolved === null)
12505
+ return { status: "error" };
12506
+ installationId = resolved;
12507
+ } else {
12508
+ const rawInstallation = process.env.GITHUB_APP_INSTALLATION_ID?.trim() ?? "";
12509
+ if (!/^[1-9][0-9]{0,15}$/.test(rawInstallation))
12510
+ return { status: "unconfigured" };
12511
+ installationId = Number(rawInstallation);
12512
+ }
12513
+ const minted = await mintInstallationToken(installationId, creds, 600000);
12408
12514
  if (!minted)
12409
12515
  return { status: "error" };
12410
12516
  return { status: "ok", token: minted.token, expiresAt: new Date(minted.expiresAt).toISOString() };
12411
12517
  }
12412
- var initialized = false, webhookSecret = null, appId = null, privateKey = null, tokenCache;
12518
+ var initialized = false, webhookSecret = null, appId = null, privateKey = null, tokenCache, INSTALLATION_CACHE_TTL_MS, NO_INSTALLATION_CACHE_TTL_MS = 60000, installationCache;
12413
12519
  var init_app = __esm(() => {
12520
+ init_db4();
12414
12521
  init_env_flag();
12415
12522
  init_github_host();
12416
12523
  tokenCache = new Map;
12524
+ INSTALLATION_CACHE_TTL_MS = 10 * 60000;
12525
+ installationCache = new Map;
12417
12526
  });
12418
12527
 
12419
12528
  // src/github/reactions.ts
@@ -20469,7 +20578,7 @@ function startRetryPoller(registry, intervalMs = 5000) {
20469
20578
  if (!waiting)
20470
20579
  continue;
20471
20580
  if (result.waitFor === "workflow.child.finished") {
20472
- const { resumeFromChildRun } = await import("./resume-z1vs44n5.js");
20581
+ const { resumeFromChildRun } = await import("./resume-0drnmpja.js");
20473
20582
  await resumeFromChildRun(step.id, registry);
20474
20583
  }
20475
20584
  } else {
@@ -21088,6 +21197,13 @@ var init_wait_poller = __esm(() => {
21088
21197
  });
21089
21198
 
21090
21199
  // src/workflows/executors/agent-task.ts
21200
+ function crashAfterTaskInsertForTest(description) {
21201
+ if (getNodeEnv() !== "test")
21202
+ return;
21203
+ const marker = process.env.E2E_CRASH_AFTER_WORKFLOW_TASK_INSERT;
21204
+ if (marker && description.includes(marker))
21205
+ process.kill(process.pid, "SIGKILL");
21206
+ }
21091
21207
  var AgentTaskConfigSchema, AgentTaskOutputSchema, AgentTaskExecutor;
21092
21208
  var init_agent_task = __esm(() => {
21093
21209
  init_zod();
@@ -21097,6 +21213,7 @@ var init_agent_task = __esm(() => {
21097
21213
  init_context_key();
21098
21214
  init_errors2();
21099
21215
  init_types5();
21216
+ init_node_env();
21100
21217
  init_base();
21101
21218
  AgentTaskConfigSchema = object2({
21102
21219
  template: string2(),
@@ -21215,6 +21332,7 @@ var init_agent_task = __esm(() => {
21215
21332
  throw error;
21216
21333
  return { status: "failed", error: `Unknown model profile "${config.profile}".` };
21217
21334
  }
21335
+ crashAfterTaskInsertForTest(preCreate.description);
21218
21336
  return {
21219
21337
  status: "success",
21220
21338
  async: true,
@@ -21305,7 +21423,7 @@ async function waitForSlackApp(getApp, signal) {
21305
21423
  var slackReadyWait, NotifyConfigSchema, NotifyOutputSchema, NotifyExecutor;
21306
21424
  var init_notify = __esm(() => {
21307
21425
  init_zod();
21308
- init_config4();
21426
+ init_config5();
21309
21427
  init_secret_scrubber();
21310
21428
  init_base();
21311
21429
  slackReadyWait = { timeoutMs: 25000, pollMs: 250 };
@@ -21348,7 +21466,7 @@ var init_notify = __esm(() => {
21348
21466
  }
21349
21467
  }
21350
21468
  case "slack": {
21351
- const { getSlackApp } = await import("./app-b267ggx1.js");
21469
+ const { getSlackApp } = await import("./app-zfa9dwjw.js");
21352
21470
  let app = getSlackApp();
21353
21471
  if (!app) {
21354
21472
  if (!isSlackConfigured()) {
@@ -22297,9 +22415,9 @@ var init_workflows = __esm(() => {
22297
22415
  });
22298
22416
 
22299
22417
  // src/github/pull-request-state.ts
22300
- async function fetchPullRequestState(repo, number) {
22418
+ async function githubGet(path, what) {
22301
22419
  const auth = await getWorkerInstallationToken();
22302
- const response = await fetch(githubApiUrl(`/repos/${repo}/pulls/${number}`), {
22420
+ const response = await fetch(githubApiUrl(path), {
22303
22421
  headers: {
22304
22422
  Accept: "application/vnd.github+json",
22305
22423
  "X-GitHub-Api-Version": "2022-11-28",
@@ -22308,13 +22426,55 @@ async function fetchPullRequestState(repo, number) {
22308
22426
  signal: AbortSignal.timeout(1e4)
22309
22427
  });
22310
22428
  if (!response.ok)
22311
- throw new Error(`GitHub returned ${response.status} for ${repo}#${number}`);
22312
- const pr = await response.json();
22429
+ throw new Error(`GitHub returned ${response.status} for ${what}`);
22430
+ return await response.json();
22431
+ }
22432
+ async function fetchPullRequestState(repo, number) {
22433
+ const pr = await githubGet(`/repos/${repo}/pulls/${number}`, `${repo}#${number}`);
22313
22434
  return {
22314
22435
  merged: pr.merged === true,
22315
- state: pr.state === "open" ? "open" : "closed"
22436
+ state: pr.state === "open" ? "open" : "closed",
22437
+ headSha: pr.head?.sha ?? "",
22438
+ baseRef: pr.base?.ref ?? ""
22316
22439
  };
22317
22440
  }
22441
+ async function fetchRequiredCheckStates(repo, baseRef, sha) {
22442
+ const rules = await githubGet(`/repos/${repo}/rules/branches/${encodeURIComponent(baseRef)}`, `${repo} rules on ${baseRef}`);
22443
+ const required = new Map;
22444
+ for (const rule of rules) {
22445
+ if (rule.type !== "required_status_checks")
22446
+ continue;
22447
+ for (const check of rule.parameters?.required_status_checks ?? [])
22448
+ required.set(check.context, check.integration_id);
22449
+ }
22450
+ if (!required.size)
22451
+ throw new Error(`${repo} has no required status checks on ${baseRef}`);
22452
+ let statuses;
22453
+ const states = [];
22454
+ for (const [name, appId] of required) {
22455
+ const runs = await githubGet(`/repos/${repo}/commits/${sha}/check-runs?check_name=${encodeURIComponent(name)}&filter=latest&per_page=100`, `${repo} check runs on ${sha}`);
22456
+ const run = (runs.check_runs ?? []).find((r) => appId === undefined || r.app?.id === appId);
22457
+ if (run) {
22458
+ states.push({
22459
+ name,
22460
+ complete: run.status === "completed",
22461
+ conclusion: run.conclusion ?? null,
22462
+ completedAt: run.completed_at ?? null
22463
+ });
22464
+ continue;
22465
+ }
22466
+ statuses ??= (await githubGet(`/repos/${repo}/commits/${sha}/status?per_page=100`, `${repo} statuses on ${sha}`)).statuses ?? [];
22467
+ const status = statuses.find((s) => s.context === name);
22468
+ const complete = status !== undefined && status.state !== "pending";
22469
+ states.push({
22470
+ name,
22471
+ complete,
22472
+ conclusion: complete ? status.state : null,
22473
+ completedAt: complete ? status.updated_at : null
22474
+ });
22475
+ }
22476
+ return states;
22477
+ }
22318
22478
  var init_pull_request_state = __esm(() => {
22319
22479
  init_github_host();
22320
22480
  init_app();
@@ -22324,6 +22484,17 @@ var init_pull_request_state = __esm(() => {
22324
22484
  function prMatch(repo, number) {
22325
22485
  return { repo: repo.toLowerCase(), number };
22326
22486
  }
22487
+ async function confirmChecksDone(repo, number) {
22488
+ const pr = await fetchPullRequestState(repo, number);
22489
+ if (!pr.headSha || !pr.baseRef)
22490
+ throw new Error(`GitHub returned no head or base for ${repo}#${number}`);
22491
+ const checks = await fetchRequiredCheckStates(repo, pr.baseRef, pr.headSha);
22492
+ const done = checks.every((check) => check.complete);
22493
+ return {
22494
+ happened: done,
22495
+ detail: done ? `head ${pr.headSha.slice(0, 12)}, ${checks.map((check) => `${check.name}=${check.conclusion} (completed ${check.completedAt})`).join(", ")}` : undefined
22496
+ };
22497
+ }
22327
22498
  var PrMatch, githubAdapter;
22328
22499
  var init_github2 = __esm(() => {
22329
22500
  init_zod();
@@ -22332,9 +22503,9 @@ var init_github2 = __esm(() => {
22332
22503
  PrMatch = object2({ repo: string2().regex(/^[\w.-]+\/[\w.-]+$/), number: number2().int().positive() }).strict();
22333
22504
  githubAdapter = {
22334
22505
  source: "github",
22335
- events: ["vcs.pr.merged"],
22506
+ events: ["vcs.pr.merged", "vcs.pr.checks_done"],
22336
22507
  matchHint: "repo (owner/name), number",
22337
- busPrefix: "github.pull_request.",
22508
+ busPrefixes: ["github.pull_request.", "github.check_run."],
22338
22509
  readsWithServerCredentials: true,
22339
22510
  isEnabled: isGitHubEnabled,
22340
22511
  parseMatch(_event, match) {
@@ -22345,13 +22516,24 @@ var init_github2 = __esm(() => {
22345
22516
  return prMatch(parsed.data.repo, parsed.data.number);
22346
22517
  },
22347
22518
  fromBusEvent(busEvent, payload) {
22519
+ if (busEvent === "github.check_run.completed") {
22520
+ const run = payload;
22521
+ if (typeof run?.repo !== "string" || !Array.isArray(run.pullRequests))
22522
+ return [];
22523
+ const repo = run.repo;
22524
+ return run.pullRequests.filter((n) => typeof n === "number").map((n) => ({ event: "vcs.pr.checks_done", match: prMatch(repo, n) }));
22525
+ }
22348
22526
  const pr = payload;
22349
22527
  if (busEvent !== "github.pull_request.closed" || pr?.merged !== true || typeof pr.repo !== "string" || typeof pr.number !== "number")
22350
22528
  return [];
22351
22529
  return [{ event: "vcs.pr.merged", match: prMatch(pr.repo, pr.number) }];
22352
22530
  },
22353
- async confirm(_event, match) {
22354
- return (await fetchPullRequestState(String(match.repo), Number(match.number))).merged;
22531
+ async confirm(event, match) {
22532
+ const repo = String(match.repo);
22533
+ const number = Number(match.number);
22534
+ if (event === "vcs.pr.checks_done")
22535
+ return await confirmChecksDone(repo, number);
22536
+ return (await fetchPullRequestState(repo, number)).merged;
22355
22537
  }
22356
22538
  };
22357
22539
  });
@@ -22364,6 +22546,9 @@ function describeEventWait(source, event, match) {
22364
22546
  const target = Object.entries(match).map(([key, value]) => `${key}=${value}`).join(", ");
22365
22547
  return `${event} on ${source} (${target})`;
22366
22548
  }
22549
+ function toConfirmResult(result) {
22550
+ return typeof result === "boolean" ? { happened: result } : result;
22551
+ }
22367
22552
  var init_types4 = () => {};
22368
22553
 
22369
22554
  // src/event-waits/index.ts
@@ -22371,9 +22556,9 @@ function getExternalEventAdapter(source) {
22371
22556
  return EXTERNAL_EVENT_ADAPTERS.find((adapter) => adapter.source === source);
22372
22557
  }
22373
22558
  function isReservedProviderEvent(name) {
22374
- return EXTERNAL_EVENT_ADAPTERS.some((adapter) => name.startsWith(adapter.busPrefix));
22559
+ return EXTERNAL_EVENT_ADAPTERS.some((adapter) => adapter.busPrefixes.some((prefix) => name.startsWith(prefix)));
22375
22560
  }
22376
- var EXTERNAL_EVENT_ADAPTERS, EXTERNAL_EVENT_NAMES, EXTERNAL_EVENTS_DOC = 'vcs.pr.merged with source "github" and match {repo (owner/name), number}';
22561
+ var EXTERNAL_EVENT_ADAPTERS, EXTERNAL_EVENT_NAMES, EXTERNAL_EVENTS_DOC = 'vcs.pr.merged or vcs.pr.checks_done (every required check of the base branch ruleset finished on the PR head, any conclusion) with source "github" and match {repo (owner/name), number}';
22377
22562
  var init_event_waits = __esm(() => {
22378
22563
  init_github2();
22379
22564
  init_types4();
@@ -22452,7 +22637,7 @@ var init_schedule_task = __esm(() => {
22452
22637
  function externalWakeReason(source, event) {
22453
22638
  return `external:${source}:${event}`;
22454
22639
  }
22455
- async function resolveWaitCause(scheduleId, reason) {
22640
+ async function resolveWaitCause(scheduleId, reason, causeDetail) {
22456
22641
  const client = getDbClient2();
22457
22642
  const wait = await client.get("SELECT * FROM deferred_task_waits WHERE scheduleId = ?", [scheduleId]);
22458
22643
  if (!wait) {
@@ -22465,7 +22650,7 @@ async function resolveWaitCause(scheduleId, reason) {
22465
22650
  return;
22466
22651
  return {
22467
22652
  table: "deferred_event_waits",
22468
- cause: describeEventWait(eventWait.source, eventWait.event, JSON.parse(eventWait.matchJson)),
22653
+ cause: `${describeEventWait(eventWait.source, eventWait.event, JSON.parse(eventWait.matchJson))}${causeDetail ? `: ${causeDetail}` : ""}`,
22469
22654
  matchedTaskIds: []
22470
22655
  };
22471
22656
  }
@@ -22502,8 +22687,8 @@ function wakeSchedule(schedule, cause) {
22502
22687
 
22503
22688
  Wake-up cause: ${cause}.` };
22504
22689
  }
22505
- async function prepareDeferredWakeTask(scheduleId, reason, extraTags) {
22506
- const resolved = await resolveWaitCause(scheduleId, reason);
22690
+ async function prepareDeferredWakeTask(scheduleId, reason, extraTags, causeDetail) {
22691
+ const resolved = await resolveWaitCause(scheduleId, reason, causeDetail);
22507
22692
  if (!resolved)
22508
22693
  return;
22509
22694
  let schedule = await getScheduledTaskById2(scheduleId);
@@ -22516,15 +22701,15 @@ async function prepareDeferredWakeTask(scheduleId, reason, extraTags) {
22516
22701
  throw new Error(`Schedule "${schedule.name}" has no taskTemplate`);
22517
22702
  return await prepareStandaloneScheduleTask(wakeSchedule(schedule, resolved.cause), extraTags);
22518
22703
  }
22519
- async function prepareDeferredTaskWait(scheduleId, reason, extraTags = []) {
22704
+ async function prepareDeferredTaskWait(scheduleId, reason, extraTags = [], causeDetail) {
22520
22705
  const client = getDbClient2();
22521
22706
  if (!await client.get(`SELECT 1 AS found FROM deferred_task_waits WHERE scheduleId = ?
22522
22707
  UNION ALL SELECT 1 FROM deferred_event_waits WHERE scheduleId = ?`, [scheduleId, scheduleId]))
22523
22708
  return;
22524
- return { task: await prepareDeferredWakeTask(scheduleId, reason, extraTags) };
22709
+ return { task: await prepareDeferredWakeTask(scheduleId, reason, extraTags, causeDetail) };
22525
22710
  }
22526
- async function dispatchDeferredTaskWait(scheduleId, reason, extraTags = [], triggerTaskId, prepared) {
22527
- const preparation = prepared ?? await prepareDeferredTaskWait(scheduleId, reason, extraTags);
22711
+ async function dispatchDeferredTaskWait(scheduleId, reason, extraTags = [], triggerTaskId, prepared, causeDetail) {
22712
+ const preparation = prepared ?? await prepareDeferredTaskWait(scheduleId, reason, extraTags, causeDetail);
22528
22713
  if (!preparation)
22529
22714
  return;
22530
22715
  const preparedForWait = preparation.task;
@@ -22532,7 +22717,7 @@ async function dispatchDeferredTaskWait(scheduleId, reason, extraTags = [], trig
22532
22717
  return {};
22533
22718
  const client = getDbClient2();
22534
22719
  return client.transaction(async () => {
22535
- const resolved = await resolveWaitCause(scheduleId, reason);
22720
+ const resolved = await resolveWaitCause(scheduleId, reason, causeDetail);
22536
22721
  if (!resolved)
22537
22722
  return {};
22538
22723
  let schedule = await getScheduledTaskById2(scheduleId);
@@ -22636,6 +22821,26 @@ async function reapSpentDeferredSchedules(now = new Date) {
22636
22821
  )`, [cutoff]);
22637
22822
  return result.changes;
22638
22823
  }
22824
+ function confirmFresh(key, read) {
22825
+ const previous = confirmFlights.get(key);
22826
+ if (previous && !previous.started)
22827
+ return previous.result;
22828
+ const flight = { started: false, result: Promise.resolve({ happened: false }) };
22829
+ const after = previous ? previous.result.then(noop, noop) : Promise.resolve();
22830
+ flight.result = after.then(() => {
22831
+ flight.started = true;
22832
+ return read();
22833
+ }).then(toConfirmResult).finally(() => {
22834
+ if (confirmFlights.get(key) === flight)
22835
+ confirmFlights.delete(key);
22836
+ });
22837
+ confirmFlights.set(key, flight);
22838
+ return flight.result;
22839
+ }
22840
+ function noop() {}
22841
+ async function hasPendingEventWait(source, event) {
22842
+ return !!await getDbClient2().get("SELECT 1 AS found FROM deferred_event_waits WHERE status = 'pending' AND source = ? AND event = ? LIMIT 1", [source, event]);
22843
+ }
22639
22844
  async function reconcileDeferredEventWaits(only, trustEvent = false) {
22640
22845
  const waits = await getDbClient2().query(`SELECT w.scheduleId, w.source, w.event, w.matchKey, w.matchJson FROM deferred_event_waits w
22641
22846
  JOIN scheduled_tasks s ON s.id = w.scheduleId
@@ -22649,9 +22854,10 @@ async function reconcileDeferredEventWaits(only, trustEvent = false) {
22649
22854
  const key = `${wait.source}|${wait.event}|${wait.matchKey}`;
22650
22855
  try {
22651
22856
  if (!satisfied.has(key))
22652
- satisfied.set(key, adapter.confirm ? await adapter.confirm(wait.event, JSON.parse(wait.matchJson)) : true);
22653
- if (satisfied.get(key))
22654
- await dispatchDeferredTaskWait(wait.scheduleId, externalWakeReason(wait.source, wait.event));
22857
+ satisfied.set(key, adapter.confirm ? await confirmFresh(key, () => adapter.confirm(wait.event, JSON.parse(wait.matchJson))) : { happened: true });
22858
+ const result = satisfied.get(key);
22859
+ if (result.happened)
22860
+ await dispatchDeferredTaskWait(wait.scheduleId, externalWakeReason(wait.source, wait.event), [], undefined, undefined, result.detail);
22655
22861
  } catch (err) {
22656
22862
  console.error(`[Scheduler] External event wake failed for ${wait.scheduleId}:`, err);
22657
22863
  }
@@ -22691,7 +22897,8 @@ async function initDeferredTaskWaits() {
22691
22897
  for (const adapter of EXTERNAL_EVENT_ADAPTERS) {
22692
22898
  const listener = externalEventListener(adapter);
22693
22899
  externalEventListeners.set(adapter, listener);
22694
- workflowEventBus2.onPrefix(adapter.busPrefix, listener);
22900
+ for (const prefix of adapter.busPrefixes)
22901
+ workflowEventBus2.onPrefix(prefix, listener);
22695
22902
  }
22696
22903
  await reconcileDeferredTaskWaits();
22697
22904
  reconcileDeferredEventWaits().catch((err) => {
@@ -22706,11 +22913,12 @@ function stopDeferredTaskWaits() {
22706
22913
  workflowEventBus2.off("task.superseded", onTaskEvent);
22707
22914
  workflowEventBus2.off("task.created", onTaskEvent);
22708
22915
  for (const [adapter, listener] of externalEventListeners) {
22709
- workflowEventBus2.offPrefix(adapter.busPrefix, listener);
22916
+ for (const prefix of adapter.busPrefixes)
22917
+ workflowEventBus2.offPrefix(prefix, listener);
22710
22918
  }
22711
22919
  externalEventListeners.clear();
22712
22920
  }
22713
- var MAX_PENDING_EVENT_WAITS_PER_AGENT = 20, WAIT_MEMBER_STATUS_SQL, DEFERRED_WAIT_WOKE_EVENT = "task_deferred_wait_woke", SPENT_DEFERRED_SCHEDULE_RETENTION_MS, externalEventListeners;
22921
+ var MAX_PENDING_EVENT_WAITS_PER_AGENT = 20, WAIT_MEMBER_STATUS_SQL, DEFERRED_WAIT_WOKE_EVENT = "task_deferred_wait_woke", SPENT_DEFERRED_SCHEDULE_RETENTION_MS, confirmFlights, externalEventListeners;
22714
22922
  var init_deferred_task_waits = __esm(() => {
22715
22923
  init_db4();
22716
22924
  init_event_waits();
@@ -22721,6 +22929,7 @@ var init_deferred_task_waits = __esm(() => {
22721
22929
  WHEN t.status = 'superseded' AND t.failureReason = '${SUPERSEDED_WORKFLOW_TASK_REASON}' THEN 'failed'
22722
22930
  ELSE t.status END`;
22723
22931
  SPENT_DEFERRED_SCHEDULE_RETENTION_MS = 30 * 24 * 60 * 60 * 1000;
22932
+ confirmFlights = new Map;
22724
22933
  externalEventListeners = new Map;
22725
22934
  });
22726
22935
 
@@ -23041,7 +23250,12 @@ async function executeSchedule(schedule, extraTags = []) {
23041
23250
  });
23042
23251
  }
23043
23252
  }
23044
- function startScheduler2(registry, intervalMs = 1e4, opts) {
23253
+ function parseSchedulerIntervalMs2(raw) {
23254
+ const value = Number(raw);
23255
+ const { min, max } = SCHEDULER_INTERVAL_MS_BOUNDS;
23256
+ return Number.isInteger(value) && value >= min && value <= max ? value : DEFAULT_SCHEDULER_INTERVAL_MS;
23257
+ }
23258
+ function startScheduler2(registry, intervalMs = DEFAULT_SCHEDULER_INTERVAL_MS, opts) {
23045
23259
  if (schedulerRun) {
23046
23260
  console.log("[Scheduler] Already running");
23047
23261
  return;
@@ -23138,7 +23352,7 @@ async function runScheduleNow2(scheduleId) {
23138
23352
  console.log(`[Scheduler] Manually executed schedule "${schedule.name}"`);
23139
23353
  }
23140
23354
  }
23141
- var import_cron_parser, schedulerInterval = null, schedulerRun = null, isProcessing = false, lastDeferredReapAt = 0, DEFERRED_REAP_INTERVAL_MS, executorRegistry = null, AutomationNeedsSetupError, ERROR_BACKOFF_MS, MAX_CONSECUTIVE_ERRORS = 5;
23355
+ var import_cron_parser, schedulerInterval = null, schedulerRun = null, isProcessing = false, lastDeferredReapAt = 0, DEFERRED_REAP_INTERVAL_MS, executorRegistry = null, AutomationNeedsSetupError, ERROR_BACKOFF_MS, MAX_CONSECUTIVE_ERRORS = 5, DEFAULT_SCHEDULER_INTERVAL_MS = 1e4;
23142
23356
  var init_scheduler = __esm(() => {
23143
23357
  init_automation_preflight_alert();
23144
23358
  init_automation_preflight();
@@ -23148,6 +23362,7 @@ var init_scheduler = __esm(() => {
23148
23362
  init_db3();
23149
23363
  init_run_credential();
23150
23364
  init_workflows_seeder();
23365
+ init_swarm_config_guard();
23151
23366
  init_telemetry();
23152
23367
  init_workflows();
23153
23368
  init_engine();
@@ -24319,6 +24534,8 @@ var init_sdk_allowlist = __esm(() => {
24319
24534
  app_upsert: "app-upsert",
24320
24535
  page_create: "create_page",
24321
24536
  page_delete: "delete-page",
24537
+ designSystem_get: "design-system-get",
24538
+ designSystem_set: "design-system-set",
24322
24539
  metric_create: "create_metric",
24323
24540
  request_humanInput: "request-human-input",
24324
24541
  approval_cancel: "cancel-approval-request",
@@ -24985,7 +25202,7 @@ function setPreloadedTools(server, names) {
24985
25202
  async function applyPreToolCall(name, args, requestInfo, inputSchema) {
24986
25203
  if (requestInfo.callOrigin !== "mcp")
24987
25204
  return { args };
24988
- const dispatcher = await import("./dispatcher-h2rz69f6.js");
25205
+ const dispatcher = await import("./dispatcher-a2gdqz8c.js");
24989
25206
  const result = await dispatcher.dispatchPre("pre.tool.call", { tool: name, args, requestInfo }, inputSchema ? {
24990
25207
  validateModify: async (data) => {
24991
25208
  const schema = normalizeObjectSchema(inputSchema) ?? inputSchema;
@@ -25020,6 +25237,18 @@ async function applyPreToolCall(name, args, requestInfo, inputSchema) {
25020
25237
  dispatcher
25021
25238
  };
25022
25239
  }
25240
+ async function refuseWriteForTerminalTask(name, annotations, requestInfo) {
25241
+ if (requestInfo.callOrigin !== "mcp" || !requestInfo.sourceTaskId)
25242
+ return;
25243
+ if (annotations?.readOnlyHint === true || TERMINAL_TASK_EXEMPT_TOOLS.has(name))
25244
+ return;
25245
+ const row = await getDbClient2().get("SELECT status FROM agent_tasks WHERE id = ?", [requestInfo.sourceTaskId]);
25246
+ if (!row || !isTerminalTaskStatus(row.status))
25247
+ return;
25248
+ return toolErr(`Task ${requestInfo.sourceTaskId} is ${row.status}, so this session can no longer call ${name}. Stop working on it.`, {
25249
+ details: "Only store-progress and read-only tools still work for a finished task. Any new work belongs to a new task."
25250
+ });
25251
+ }
25023
25252
  function dispatchPostToolCall(dispatcher, name, args, outcome, requestInfo, durationMs) {
25024
25253
  if (!dispatcher)
25025
25254
  return;
@@ -25108,6 +25337,7 @@ var scriptSdkRequestOrigins, extensionRequestOrigins, getRequestInfo = (req) =>
25108
25337
  const data = r.data;
25109
25338
  const count = data?.colorLiteralCount;
25110
25339
  const sentences = [
25340
+ data?.designSystemStatus === "none" ? "This org has no design system yet, so the page uses the default look. Ask the requester once for a site URL, a preset or a CSS block, build a preview with the design-system-seed script, and save it with design-system-set after they approve; if they say no, call design-system-set with status declined so nobody asks again." : undefined,
25111
25341
  data?.designVersion === 1 && data.usesDesignSystem === true ? "This page is on designVersion 1 (the original look), so design system classes, tokens and themes have no effect. Pass designVersion: 2." : undefined,
25112
25342
  data?.lightOnlyColors === true ? "Your themeTokens set colors for light mode only. Dark mode keeps the preset's dark colors; add a dark map (or a .dark block) to restyle it too." : undefined,
25113
25343
  typeof count === "number" && count >= COLOR_LITERAL_THRESHOLD ? `This page hardcodes ${count} color values. Use theme tokens (var(--color-primary), bg-primary, text-muted-foreground) so theme and dark-mode switches restyle it. Until then the page stays light in a dark dashboard.` : undefined
@@ -25179,7 +25409,7 @@ var scriptSdkRequestOrigins, extensionRequestOrigins, getRequestInfo = (req) =>
25179
25409
  return spilled("Payload omitted.");
25180
25410
  return fillPreviewToBudget(json, (preview) => spilled(`JSON payload head:
25181
25411
  ${preview}`));
25182
- }, FINALIZE_PIPELINE, preloadedToolsByServer, createToolRegistrar = (server) => {
25412
+ }, FINALIZE_PIPELINE, preloadedToolsByServer, TERMINAL_TASK_EXEMPT_TOOLS, createToolRegistrar = (server) => {
25183
25413
  return (name, config, cb) => {
25184
25414
  const toolConfig = preloadedToolsByServer.get(server)?.has(name) ? { ...config, _meta: { ...config._meta, "anthropic/alwaysLoad": true } } : config;
25185
25415
  if (config.inputSchema === undefined) {
@@ -25188,7 +25418,7 @@ ${preview}`));
25188
25418
  return withSpan2("mcp.tool", async (span) => {
25189
25419
  const pre = await applyPreToolCall(name, {}, requestInfo);
25190
25420
  let durationMs = 0;
25191
- let outcome = pre.blocked;
25421
+ let outcome = pre.blocked ?? await refuseWriteForTerminalTask(name, config.annotations, requestInfo);
25192
25422
  if (!outcome) {
25193
25423
  const startedAt = Date.now();
25194
25424
  try {
@@ -25211,7 +25441,7 @@ ${preview}`));
25211
25441
  const pre = await applyPreToolCall(name, args, requestInfo, config.inputSchema);
25212
25442
  const effectiveArgs = pre.args;
25213
25443
  let durationMs = 0;
25214
- let outcome = pre.blocked;
25444
+ let outcome = pre.blocked ?? await refuseWriteForTerminalTask(name, config.annotations, requestInfo);
25215
25445
  if (!outcome) {
25216
25446
  const startedAt = Date.now();
25217
25447
  try {
@@ -25332,6 +25562,7 @@ var init_utils = __esm(() => {
25332
25562
  ctxControlMiddleware
25333
25563
  ];
25334
25564
  preloadedToolsByServer = new WeakMap;
25565
+ TERMINAL_TASK_EXEMPT_TOOLS = new Set(["store-progress"]);
25335
25566
  });
25336
25567
 
25337
25568
  // src/http/mcp-bridge.ts
@@ -25745,9 +25976,13 @@ function bridgeRequestFor(name, args) {
25745
25976
  case "memory_search":
25746
25977
  return { method: "POST", path: "/api/memory/search", body };
25747
25978
  case "memory_get": {
25748
- const memoryId = typeof body.memoryId === "string" ? body.memoryId : undefined;
25749
- if (!memoryId)
25750
- throw new Error("memory_get requires string `memoryId`");
25979
+ if (body.memoryId && body.id && body.memoryId !== body.id) {
25980
+ throw new Error("memoryId and id must identify the same memory; supply only one.");
25981
+ }
25982
+ const memoryId = body.memoryId ?? body.id;
25983
+ if (typeof memoryId !== "string" || !memoryId) {
25984
+ throw new Error("Supply memoryId (or its alias id) from memory-search.");
25985
+ }
25751
25986
  const getIntent = typeof body.intent === "string" ? body.intent : "script-sdk";
25752
25987
  return {
25753
25988
  method: "GET",
@@ -25755,8 +25990,15 @@ function bridgeRequestFor(name, args) {
25755
25990
  };
25756
25991
  }
25757
25992
  case "memory_rate": {
25993
+ if (body.id && body.memoryId && body.id !== body.memoryId) {
25994
+ throw new Error("id and memoryId must identify the same memory; supply only one.");
25995
+ }
25996
+ const memoryId = body.id ?? body.memoryId;
25997
+ if (typeof memoryId !== "string" || !memoryId) {
25998
+ throw new Error("Supply id (or its alias memoryId) from memory-search.");
25999
+ }
25758
26000
  const event = {
25759
- memoryId: body.id,
26001
+ memoryId,
25760
26002
  signal: body.useful === false ? -1 : 1,
25761
26003
  weight: 1,
25762
26004
  source: "explicit-self",
@@ -25780,28 +26022,6 @@ function bridgeRequestFor(name, args) {
25780
26022
  throw new Error("task_get requires string `taskId`");
25781
26023
  return { method: "GET", path: `/api/tasks/${encodeURIComponent(taskId)}` };
25782
26024
  }
25783
- case "task_storeProgress": {
25784
- const taskId = typeof body.taskId === "string" ? body.taskId : undefined;
25785
- if (!taskId)
25786
- throw new Error("task_storeProgress requires string `taskId`");
25787
- if (body.status === "completed" || body.status === "failed" || body.status === "skipped") {
25788
- return {
25789
- method: "POST",
25790
- path: `/api/tasks/${encodeURIComponent(taskId)}/finish`,
25791
- body: {
25792
- status: body.status,
25793
- output: body.output,
25794
- failureReason: body.failureReason,
25795
- force: body.force
25796
- }
25797
- };
25798
- }
25799
- return {
25800
- method: "POST",
25801
- path: `/api/tasks/${encodeURIComponent(taskId)}/progress`,
25802
- body: { progress: body.progress ?? "" }
25803
- };
25804
- }
25805
26025
  case "task_cancel": {
25806
26026
  const taskId = typeof body.taskId === "string" ? body.taskId : undefined;
25807
26027
  if (!taskId)
@@ -28789,7 +29009,19 @@ var init_unmapped_identities = __esm(() => {
28789
29009
 
28790
29010
  // src/vcs/azure-devops.ts
28791
29011
  function isAzureDevOpsUrl(url) {
28792
- return /(^|[/@.])dev\.azure\.com[/:]|\.visualstudio\.com[/:]/i.test(url);
29012
+ const trimmed = url.trim();
29013
+ const scp = trimmed.match(/^[^@/\s:]+@([^:/\s]+):/);
29014
+ if (scp)
29015
+ return isAzureDevOpsHost(scp[1]);
29016
+ try {
29017
+ return isAzureDevOpsHost(new URL(trimmed).hostname);
29018
+ } catch {
29019
+ return /^(?:ssh\.)?dev\.azure\.com(\/|$)|^[\w.-]+\.visualstudio\.com(\/|$)/i.test(trimmed);
29020
+ }
29021
+ }
29022
+ function isAzureDevOpsHost(hostname) {
29023
+ const host = hostname.toLowerCase();
29024
+ return host === "dev.azure.com" || host === "ssh.dev.azure.com" || host.endsWith(".visualstudio.com");
28793
29025
  }
28794
29026
  function canonicalAzureDevOpsRepoUrl(url) {
28795
29027
  const trimmed = url.trim();
@@ -29701,7 +29933,7 @@ async function handleWorkItemDeleted(event) {
29701
29933
  return { created: false };
29702
29934
  const task = sync.swarmId && !sync.swarmId.startsWith("pending:") ? await getTaskById2(sync.swarmId) : null;
29703
29935
  if (task && !isTerminalTaskStatus(task.status)) {
29704
- await cancelTask2(task.id, DELETED_REASON);
29936
+ await cancelTask2(task.id, DELETED_REASON, { statusKind: "external" });
29705
29937
  console.log(`[AzureDevOps] Cancelled task ${task.id} (work item #${item.id} deleted)`);
29706
29938
  }
29707
29939
  await markTrackerDelivery(PROVIDER, "task", externalId, event.id);
@@ -30572,7 +30804,7 @@ async function handlePullRequestClosed(body, outcome) {
30572
30804
  const reason = outcome === "merged" ? "PR was merged" : "PR was declined";
30573
30805
  for (const task of await findActiveTasksByVcs2(repository.full_name, pr.id, "bitbucket")) {
30574
30806
  console.log(`[Bitbucket] Cancelling task ${task.id} — ${reason}`);
30575
- await failTask2(task.id, reason);
30807
+ await failTask2(task.id, reason, { statusKind: "external" });
30576
30808
  }
30577
30809
  return { created: false };
30578
30810
  }
@@ -31233,7 +31465,9 @@ async function handlePullRequest(event) {
31233
31465
  console.log(`[GitHub] No active task found for PR #${pr.number} to cancel`);
31234
31466
  return { created: false };
31235
31467
  }
31236
- const cancelledTask = await failTask2(task.id, `Unassigned from GitHub PR #${pr.number}`);
31468
+ const cancelledTask = await failTask2(task.id, `Unassigned from GitHub PR #${pr.number}`, {
31469
+ statusKind: "external"
31470
+ });
31237
31471
  if (cancelledTask) {
31238
31472
  console.log(`[GitHub] Cancelled task ${task.id} for PR #${pr.number} (unassigned)`);
31239
31473
  return { created: false, taskId: task.id };
@@ -31305,7 +31539,7 @@ async function handlePullRequest(event) {
31305
31539
  console.log(`[GitHub] No active task found for PR #${pr.number} to cancel`);
31306
31540
  return { created: false };
31307
31541
  }
31308
- const cancelledTask = await failTask2(task.id, `Review request removed from GitHub PR #${pr.number}`);
31542
+ const cancelledTask = await failTask2(task.id, `Review request removed from GitHub PR #${pr.number}`, { statusKind: "external" });
31309
31543
  if (cancelledTask) {
31310
31544
  console.log(`[GitHub] Cancelled task ${task.id} for PR #${pr.number} (review request removed)`);
31311
31545
  return { created: false, taskId: task.id };
@@ -31483,7 +31717,9 @@ async function handleIssue(event) {
31483
31717
  console.log(`[GitHub] No active task found for issue #${issue.number} to cancel`);
31484
31718
  return { created: false };
31485
31719
  }
31486
- const cancelledTask = await failTask2(task.id, `Unassigned from GitHub issue #${issue.number}`);
31720
+ const cancelledTask = await failTask2(task.id, `Unassigned from GitHub issue #${issue.number}`, {
31721
+ statusKind: "external"
31722
+ });
31487
31723
  if (cancelledTask) {
31488
31724
  console.log(`[GitHub] Cancelled task ${task.id} for issue #${issue.number} (unassigned)`);
31489
31725
  return { created: false, taskId: task.id };
@@ -32316,7 +32552,7 @@ async function handleMergeRequest(event) {
32316
32552
  const tasks = await findActiveTasksByVcs2(repo, mr.iid, "gitlab");
32317
32553
  for (const task of tasks.filter((t) => isScopedTask(t, "mr", mrContextKey))) {
32318
32554
  console.log(`[GitLab] Cancelling task ${task.id} — ${reason}`);
32319
- await failTask2(task.id, reason);
32555
+ await failTask2(task.id, reason, { statusKind: "external" });
32320
32556
  }
32321
32557
  return { created: false };
32322
32558
  }
@@ -32403,7 +32639,7 @@ async function handleIssue2(event) {
32403
32639
  const existingTask = (await findActiveTasksByVcs2(repo, issue.iid, "gitlab")).find((t) => isScopedTask(t, "issue", issueContextKey));
32404
32640
  if (existingTask) {
32405
32641
  console.log(`[GitLab] Cancelling task ${existingTask.id} — issue closed`);
32406
- await failTask2(existingTask.id, "Issue was closed");
32642
+ await failTask2(existingTask.id, "Issue was closed", { statusKind: "external" });
32407
32643
  }
32408
32644
  return { created: false };
32409
32645
  }
@@ -32728,7 +32964,7 @@ function readApiUrlOverrides() {
32728
32964
  }
32729
32965
  }
32730
32966
  var ChatSdkConfigError, RESOLVER_FIELDS;
32731
- var init_config = __esm(() => {
32967
+ var init_config2 = __esm(() => {
32732
32968
  init_config_refs();
32733
32969
  init_db4();
32734
32970
  init_swarm_config_guard();
@@ -32872,6 +33108,100 @@ var init_logger = __esm(() => {
32872
33108
  init_secret_scrubber();
32873
33109
  });
32874
33110
 
33111
+ // src/integrations/chat-sdk/mentions.ts
33112
+ function escapeRegex(value) {
33113
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
33114
+ }
33115
+ function stripBotMention(text, forms) {
33116
+ let out = text;
33117
+ const names = [...new Set(forms.names.map((name) => name.trim()).filter(Boolean))];
33118
+ names.sort((a, b) => b.length - a.length);
33119
+ for (const name of names) {
33120
+ out = out.replace(new RegExp(`(?<!\\w)@${escapeRegex(name)}(?![\\w-])`, "gi"), "");
33121
+ }
33122
+ for (const id of new Set(forms.ids.filter(Boolean))) {
33123
+ const escaped = escapeRegex(id);
33124
+ out = out.replace(new RegExp(`<@!?${escaped}>`, "g"), "");
33125
+ out = out.replace(new RegExp(`(?<![\\w<&])@${escaped}(?!\\w)`, "g"), "");
33126
+ }
33127
+ return out.trim();
33128
+ }
33129
+ function teamsIdTail(id) {
33130
+ return id.slice(id.lastIndexOf(":") + 1).toLowerCase();
33131
+ }
33132
+ function teamsBotMentionNames(raw, botUserId) {
33133
+ if (!botUserId || !raw || typeof raw !== "object")
33134
+ return [];
33135
+ const entities = raw.entities;
33136
+ if (!Array.isArray(entities))
33137
+ return [];
33138
+ const bot = teamsIdTail(botUserId);
33139
+ const names = [];
33140
+ for (const entity of entities) {
33141
+ if (entity?.type !== "mention")
33142
+ continue;
33143
+ const id = entity.mentioned?.id;
33144
+ if (typeof id !== "string" || teamsIdTail(id) !== bot)
33145
+ continue;
33146
+ if (typeof entity.mentioned?.name === "string")
33147
+ names.push(entity.mentioned.name);
33148
+ if (typeof entity.text === "string") {
33149
+ const label = /<at\b[^>]*>(.*?)<\/at>/is.exec(entity.text)?.[1];
33150
+ if (label)
33151
+ names.push(decodeTeamsLabel(label));
33152
+ }
33153
+ }
33154
+ return names;
33155
+ }
33156
+ function decodeTeamsLabel(label) {
33157
+ return label.replace(/<[^>]*>/g, "").replace(/&quot;/g, '"').replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&amp;/g, "&").trim();
33158
+ }
33159
+ function resolveDiscordMentions(content, botUserId, lookup) {
33160
+ return content.replace(/<(@!?|@&|#)(\d+)>/g, (markup, kind, id) => {
33161
+ if (kind === "#") {
33162
+ const name = lookup.channel(id);
33163
+ return name ? `#${name}` : markup;
33164
+ }
33165
+ if (kind === "@&") {
33166
+ const name = lookup.role(id);
33167
+ return name ? `@${name}` : markup;
33168
+ }
33169
+ if (id === botUserId)
33170
+ return markup;
33171
+ const name = lookup.user(id);
33172
+ return name ? `@${name}` : markup;
33173
+ });
33174
+ }
33175
+ function safeName(read) {
33176
+ try {
33177
+ const value = read();
33178
+ return typeof value === "string" && value.trim() ? value : undefined;
33179
+ } catch {
33180
+ return;
33181
+ }
33182
+ }
33183
+ function discordJsMentionLookup(mentions) {
33184
+ return {
33185
+ user: (id) => safeName(() => mentions?.members?.get(id)?.displayName) ?? safeName(() => mentions?.users?.get(id)?.displayName) ?? safeName(() => mentions?.users?.get(id)?.username),
33186
+ role: (id) => safeName(() => mentions?.roles?.get(id)?.name),
33187
+ channel: (id) => safeName(() => mentions?.channels?.get(id)?.name)
33188
+ };
33189
+ }
33190
+ async function botMentionForms(adapter, message) {
33191
+ const names = [adapter.userName];
33192
+ const ids = adapter.botUserId ? [adapter.botUserId] : [];
33193
+ if (adapter.name === "teams")
33194
+ names.push(...teamsBotMentionNames(message.raw, adapter.botUserId));
33195
+ if (adapter.name === "slack" && adapter.botUserId) {
33196
+ const lookup = adapter.lookupUser;
33197
+ const bot = await lookup?.call(adapter, adapter.botUserId).catch(() => null);
33198
+ if (bot?.displayName)
33199
+ names.push(bot.displayName);
33200
+ }
33201
+ return { names, ids };
33202
+ }
33203
+ var init_mentions2 = () => {};
33204
+
32875
33205
  // src/integrations/chat-sdk/test-hooks.ts
32876
33206
  function getChatSdkTestHooks() {
32877
33207
  return hooks;
@@ -32917,8 +33247,21 @@ async function loadAdapter(name, config, logger) {
32917
33247
  });
32918
33248
  }
32919
33249
  case "discord": {
32920
- const { createDiscordAdapter } = await import("./index-mbpxhc4w.js");
32921
- return createDiscordAdapter({
33250
+ const { DiscordAdapter } = await import("./index-126v2d0t.js");
33251
+
33252
+ class SwarmDiscordAdapter extends DiscordAdapter {
33253
+ handleGatewayMessage(message, isMentioned) {
33254
+ const content = resolveDiscordMentions(message.content, this.botUserId, discordJsMentionLookup(message.mentions));
33255
+ if (content === message.content) {
33256
+ return super.handleGatewayMessage(message, isMentioned);
33257
+ }
33258
+ const view = new Proxy(message, {
33259
+ get: (target, prop) => prop === "content" ? content : Reflect.get(target, prop, target)
33260
+ });
33261
+ return super.handleGatewayMessage(view, isMentioned);
33262
+ }
33263
+ }
33264
+ return new SwarmDiscordAdapter({
32922
33265
  ...base,
32923
33266
  logger: withInfoFilter(logger, keepDiscordInfoLine),
32924
33267
  respondToChannelIds: config.respondToChannelIds ?? [],
@@ -32958,9 +33301,10 @@ function watchSocketConnection(adapter, logger) {
32958
33301
  }
32959
33302
  var DEFAULT_BOT_USER_NAME = "swarm", DEFAULT_API_URLS, DISCORD_NOISY_INFO_PREFIXES;
32960
33303
  var init_adapters = __esm(() => {
32961
- init_config();
33304
+ init_config2();
32962
33305
  init_facts();
32963
33306
  init_logger();
33307
+ init_mentions2();
32964
33308
  init_test_hooks();
32965
33309
  DEFAULT_API_URLS = {
32966
33310
  telegram: "https://api.telegram.org",
@@ -33232,7 +33576,7 @@ function assertTrustedTeamsServiceUrl(serviceUrl) {
33232
33576
  }
33233
33577
  var TRUSTED_TEAMS_SERVICE_HOSTS, UntrustedTeamsServiceUrlError;
33234
33578
  var init_teams_origin = __esm(() => {
33235
- init_config();
33579
+ init_config2();
33236
33580
  TRUSTED_TEAMS_SERVICE_HOSTS = new Set([
33237
33581
  "smba.trafficmanager.net",
33238
33582
  "smba.infra.gcc.teams.microsoft.com",
@@ -33383,7 +33727,9 @@ async function cancelActiveTasks(target, requestedBy) {
33383
33727
  const active = await getLatestActiveTaskByContextKey2(contextKey, "chat", target.owner);
33384
33728
  if (!active)
33385
33729
  break;
33386
- const task = await cancelTask2(active.id, `Cancelled from chat by ${requestedBy}`);
33730
+ const task = await cancelTask2(active.id, `Cancelled from chat by ${requestedBy}`, {
33731
+ statusKind: "user"
33732
+ });
33387
33733
  if (!task)
33388
33734
  break;
33389
33735
  if (task.agentId)
@@ -34246,6 +34592,220 @@ var init_limits = __esm(() => {
34246
34592
  TELEGRAM_PHOTO_LIMIT = 10 * MB2;
34247
34593
  });
34248
34594
 
34595
+ // src/be/runtime-pools/demand.ts
34596
+ async function pendingWorkForAgent(agentId) {
34597
+ const rows = await getDbClient2().query(`SELECT * FROM agent_tasks WHERE (agentId = ? AND status = 'pending')
34598
+ OR (offeredTo = ? AND status = 'offered') ORDER BY priority DESC, createdAt, rowid`, [agentId, agentId]);
34599
+ const tasks = [];
34600
+ for (const row of rows) {
34601
+ const task = rowToAgentTask(row);
34602
+ if (task.status === "offered" || (await checkDependencies2(task.id)).ready)
34603
+ tasks.push(task);
34604
+ }
34605
+ const mentions = await getDbClient2().get(`SELECT COUNT(DISTINCT m.channelId) AS count FROM channel_messages m
34606
+ JOIN channels c ON c.id = m.channelId
34607
+ LEFT JOIN channel_read_state s ON s.channelId = m.channelId AND s.agentId = ?
34608
+ WHERE m.mentions LIKE ? AND s.processing_since IS NULL
34609
+ AND (s.lastReadAt IS NULL OR m.createdAt > s.lastReadAt)`, [agentId, `%"${agentId}"%`]);
34610
+ return { work: tasks.length + (mentions?.count ?? 0), topTask: tasks[0] ?? null };
34611
+ }
34612
+ function agentRuntimeLimit(maxTasks, slotsPerRuntime) {
34613
+ return Math.floor(maxTasks / slotsPerRuntime);
34614
+ }
34615
+ function countPoolRuntimes(runtimes, now, staleMinutes) {
34616
+ return runtimes.filter((r) => r.status === "provisioning" || r.status === "active" && Date.parse(r.lastSeenAt) >= now.getTime() - staleMinutes * 60000).length;
34617
+ }
34618
+ function computeDesired(pool, agents) {
34619
+ const desired = new Map;
34620
+ let remaining = Math.max(0, (pool.maxRuntimes ?? Infinity) - agents.reduce((n, a) => n + a.current, 0));
34621
+ for (const agent of agents) {
34622
+ const uncovered = Math.max(0, agent.work - agent.freeSlots - agent.provisioning * pool.slotsPerRuntime);
34623
+ const limit = agentRuntimeLimit(agent.maxTasks, pool.slotsPerRuntime);
34624
+ const count = Math.min(limit, Math.max(pool.minRuntimes, agent.current + Math.ceil(uncovered / pool.slotsPerRuntime)));
34625
+ const added = Math.min(remaining, Math.max(0, count - agent.current));
34626
+ desired.set(agent.agentId, Math.min(count, agent.current + added));
34627
+ remaining -= added;
34628
+ }
34629
+ return desired;
34630
+ }
34631
+ var init_demand = __esm(() => {
34632
+ init_db4();
34633
+ init_read();
34634
+ });
34635
+
34636
+ // src/be/runtime-pools/reachability.ts
34637
+ function isRuntimePoolWakeable(pool, now = new Date) {
34638
+ if (!pool.enabled || pool.circuitOpenUntil && Date.parse(pool.circuitOpenUntil) > now.getTime())
34639
+ return false;
34640
+ return canProvisionKind(pool.kind) && pool.maxRuntimes !== 0 && Boolean(pool.resolvedImage ?? pool.image);
34641
+ }
34642
+ async function isAgentReachable(agent) {
34643
+ if (agent.status !== "offline")
34644
+ return true;
34645
+ if (!isRuntimePoolsEnabled() || !agent.runtimePoolId)
34646
+ return false;
34647
+ const pool = await getRuntimePool2(agent.runtimePoolId);
34648
+ if (!pool?.enabled)
34649
+ return false;
34650
+ if (isRuntimePoolWakeable(pool))
34651
+ return true;
34652
+ return await getDbClient2().get(`SELECT id FROM runtime_instances WHERE agent_id = ? AND pool_id = ?
34653
+ AND status = 'provisioning' AND draining = 0 LIMIT 1`, [agent.id, pool.id]) !== null;
34654
+ }
34655
+ async function isAgentOnDemand(agent, now = new Date) {
34656
+ if (agent.status !== "offline" || !agent.runtimePoolId)
34657
+ return false;
34658
+ if (!isRuntimePoolsEnabled() || !isMultiRuntimeEnabled())
34659
+ return false;
34660
+ const pool = await getRuntimePool2(agent.runtimePoolId);
34661
+ if (!pool?.enabled)
34662
+ return false;
34663
+ const runtimes = await listRuntimeInstancesForPool(pool.id);
34664
+ const own = runtimes.filter((r) => r.agentId === agent.id);
34665
+ if (own.some((r) => r.status === "provisioning" && !r.draining))
34666
+ return true;
34667
+ if (!isRuntimePoolWakeable(pool, now))
34668
+ return false;
34669
+ const staleMinutes = runtimeStaleThresholdMinutes();
34670
+ const limit = agentRuntimeLimit(agent.maxTasks ?? 1, pool.slotsPerRuntime);
34671
+ if (countPoolRuntimes(own, now, staleMinutes) >= limit)
34672
+ return false;
34673
+ if (pool.maxRuntimes === null)
34674
+ return true;
34675
+ return countPoolRuntimes(runtimes, now, staleMinutes) < pool.maxRuntimes;
34676
+ }
34677
+ var init_reachability = __esm(() => {
34678
+ init_runtime_providers();
34679
+ init_multi_runtime2();
34680
+ init_runtime_pools_flag();
34681
+ init_db4();
34682
+ init_multi_runtime();
34683
+ init_db2();
34684
+ init_demand();
34685
+ });
34686
+
34687
+ // src/integrations/chat-sdk/telegram-thread.ts
34688
+ function assertTelegramTopicThreadId(threadId, channelId) {
34689
+ const match = /^telegram:([^:]+):([1-9]\d*)$/.exec(threadId);
34690
+ if (!match || match[1] === "biz" || !Number.isSafeInteger(Number(match[2]))) {
34691
+ throw new Error("Invalid Telegram topic threadId. Use telegram:<chatId>:<positive integer topicId>.");
34692
+ }
34693
+ if (channelId !== undefined && `telegram:${match[1]}` !== channelId) {
34694
+ throw new Error("The default Telegram topic must belong to the registered channel.");
34695
+ }
34696
+ }
34697
+ var init_telegram_thread = () => {};
34698
+
34699
+ // src/integrations/chat-sdk/router.ts
34700
+ function chatChannelKey(adapter, channelId) {
34701
+ return channelId.startsWith(`${adapter}:`) ? channelId : `${adapter}:${channelId}`;
34702
+ }
34703
+ async function getChatChannelMapping(adapter, channelId) {
34704
+ const row = await getKv2(CHAT_CHANNELS_NAMESPACE, chatChannelKey(adapter, channelId));
34705
+ if (!row || typeof row.value !== "object" || row.value === null)
34706
+ return null;
34707
+ return row.value;
34708
+ }
34709
+ async function putChatChannelMapping(adapter, channelId, mapping) {
34710
+ const key = chatChannelKey(adapter, channelId);
34711
+ if (mapping.defaultThreadId !== undefined) {
34712
+ if (adapter !== "telegram") {
34713
+ throw new Error("Default topics are supported only for Telegram channels.");
34714
+ }
34715
+ assertTelegramTopicThreadId(mapping.defaultThreadId, key);
34716
+ }
34717
+ await upsertKv2({
34718
+ namespace: CHAT_CHANNELS_NAMESPACE,
34719
+ key,
34720
+ value: mapping,
34721
+ valueType: "json",
34722
+ expiresAt: null
34723
+ });
34724
+ return key;
34725
+ }
34726
+ async function deleteChatChannelMapping(adapter, channelId) {
34727
+ return deleteKv2(CHAT_CHANNELS_NAMESPACE, chatChannelKey(adapter, channelId));
34728
+ }
34729
+ function hasRoutingToken(text) {
34730
+ return /swarm#(?:[a-f0-9-]{36}|all)/i.test(text);
34731
+ }
34732
+ function stripRoutingTokens(text) {
34733
+ return text.replace(/swarm#[a-f0-9-]{36}/gi, "").replace(/swarm#all/gi, "").trim();
34734
+ }
34735
+ function chatOwnerWindowStart(now = Date.now()) {
34736
+ const raw = process.env.CHAT_SDK_OWNER_WINDOW_MIN?.trim();
34737
+ const value = raw ? Number(raw) : Number.NaN;
34738
+ const minutes = Number.isFinite(value) && value >= 0 ? value : DEFAULT_OWNER_WINDOW_MINUTES;
34739
+ return new Date(now - minutes * 60000).toISOString();
34740
+ }
34741
+ async function leadMatch(reachable, matchedText) {
34742
+ const lead = reachable.find((agent) => agent.isLead) ?? await getLeadAgent2();
34743
+ return { agent: lead, reason: "skill", matchedText };
34744
+ }
34745
+ async function routeChatMessage(text, ctx) {
34746
+ const allAgents = await getAllAgents2();
34747
+ const reachableFlags = await Promise.all(allAgents.map((agent) => isAgentReachable(agent)));
34748
+ const reachable = allAgents.filter((_, index) => reachableFlags[index]);
34749
+ const matches = [];
34750
+ for (const match of text.matchAll(/swarm#([a-f0-9-]{36})/gi)) {
34751
+ const agentId = match[1];
34752
+ if (!agentId || matches.some((m) => m.agent?.id === agentId))
34753
+ continue;
34754
+ const agent = await getAgentById2(agentId);
34755
+ if (agent && await isAgentReachable(agent)) {
34756
+ matches.push({ agent, reason: "human_pinned", matchedText: match[0] });
34757
+ }
34758
+ }
34759
+ if (/swarm#all/i.test(text)) {
34760
+ for (const agent of reachable) {
34761
+ if (agent.isLead || matches.some((m) => m.agent?.id === agent.id))
34762
+ continue;
34763
+ matches.push({ agent, reason: "human_pinned", matchedText: "swarm#all" });
34764
+ }
34765
+ }
34766
+ if (matches.length > 0)
34767
+ return { kind: "agents", matches };
34768
+ const mapping = await getChatChannelMapping(ctx.adapter, ctx.channelId);
34769
+ if (mapping?.workflowId && (ctx.botMentioned || ctx.isDirectMessage)) {
34770
+ return { kind: "workflow", workflowId: mapping.workflowId };
34771
+ }
34772
+ if (mapping?.agentId) {
34773
+ const agent = await getAgentById2(mapping.agentId);
34774
+ if (agent) {
34775
+ return {
34776
+ kind: "agents",
34777
+ matches: [{ agent, reason: "human_pinned", matchedText: "channel mapping" }]
34778
+ };
34779
+ }
34780
+ console.warn(scrubSecrets(`[chat-sdk] Channel mapping for ${ctx.channelId} names unknown agent ${mapping.agentId}; using the default route`));
34781
+ }
34782
+ const owner = await getAgentWorkingOnContextKey2(chatSdkContextKey(ctx.threadId), "chat", ctx.adapter === "telegram" && !ctx.isDirectMessage ? chatOwnerWindowStart() : undefined);
34783
+ if (owner && await isAgentReachable(owner)) {
34784
+ return {
34785
+ kind: "agents",
34786
+ matches: [{ agent: owner, reason: "continuity", matchedText: "thread follow-up" }]
34787
+ };
34788
+ }
34789
+ if (owner) {
34790
+ return {
34791
+ kind: "agents",
34792
+ matches: [await leadMatch(reachable, "thread follow-up (lead fallback)")]
34793
+ };
34794
+ }
34795
+ if (ctx.botMentioned || ctx.isDirectMessage) {
34796
+ return { kind: "agents", matches: [await leadMatch(reachable, "@bot")] };
34797
+ }
34798
+ return null;
34799
+ }
34800
+ var CHAT_CHANNELS_NAMESPACE = "integrations:chat:channels", DEFAULT_OWNER_WINDOW_MINUTES = 15;
34801
+ var init_router2 = __esm(() => {
34802
+ init_db4();
34803
+ init_reachability();
34804
+ init_context_key();
34805
+ init_secret_scrubber();
34806
+ init_telegram_thread();
34807
+ });
34808
+
34249
34809
  // src/integrations/chat-sdk/outbound.ts
34250
34810
  function emitChatMessageSent(event) {
34251
34811
  workflowEventBus2.emit("chat.message.sent", { ...event, text: scrubSecrets(event.text) });
@@ -34411,7 +34971,18 @@ function scrubCard(card) {
34411
34971
  return JSON.parse(JSON.stringify(card, (_key, value) => typeof value === "string" ? scrubSecrets(value) : value));
34412
34972
  }
34413
34973
  async function postChatMessage(args) {
34414
- assertTrustedChatTarget(args.threadId ?? args.channelId ?? "");
34974
+ let threadId = args.threadId;
34975
+ if (!threadId && args.channelId && args.adapter === "telegram") {
34976
+ const mapping = await getChatChannelMapping(args.adapter, args.channelId);
34977
+ if (mapping?.defaultThreadId !== undefined) {
34978
+ assertTelegramTopicThreadId(mapping.defaultThreadId, args.channelId);
34979
+ threadId = mapping.defaultThreadId;
34980
+ }
34981
+ }
34982
+ if (args.adapter === "telegram" && threadId?.split(":").length === 3 && !threadId.startsWith("telegram:biz:")) {
34983
+ assertTelegramTopicThreadId(threadId);
34984
+ }
34985
+ assertTrustedChatTarget(threadId ?? args.channelId ?? "");
34415
34986
  const chat = getChatInstance(args.adapter);
34416
34987
  if (!chat)
34417
34988
  throw new ChatAdapterUnavailableError(args.adapter);
@@ -34422,8 +34993,8 @@ async function postChatMessage(args) {
34422
34993
  `) || (card?.title ?? "");
34423
34994
  let result;
34424
34995
  let target;
34425
- if (args.threadId) {
34426
- const thread = chat.thread(args.threadId);
34996
+ if (threadId) {
34997
+ const thread = chat.thread(threadId);
34427
34998
  target = thread;
34428
34999
  const replyTo = args.replyToMessageId;
34429
35000
  const sent = await postChunks(args.adapter, thread, parts, replyTo && thread.adapter.reply ? (message) => thread.reply(replyTo, message) : undefined, card);
@@ -34475,8 +35046,10 @@ var init_outbound2 = __esm(() => {
34475
35046
  init_attachments();
34476
35047
  init_limits();
34477
35048
  init_logger();
35049
+ init_router2();
34478
35050
  init_runtime();
34479
35051
  init_teams_origin();
35052
+ init_telegram_thread();
34480
35053
  ChatAdapterUnavailableError = class ChatAdapterUnavailableError extends Error {
34481
35054
  constructor(adapter) {
34482
35055
  super(`Chat SDK adapter '${adapter}' is not running`);
@@ -34495,201 +35068,6 @@ var init_outbound2 = __esm(() => {
34495
35068
  NON_HEADING_HASH = /^( {0,3}(?:>[ \t]?)*[ \t]*(?:(?:[-*+]|\d{1,9}[.)])[ \t]+(?:\[[ xX]\][ \t]+)?)?)(#{7,}|#{1,6}(?=[^\s#]))/;
34496
35069
  });
34497
35070
 
34498
- // src/be/runtime-pools/demand.ts
34499
- async function pendingWorkForAgent(agentId) {
34500
- const rows = await getDbClient2().query(`SELECT * FROM agent_tasks WHERE (agentId = ? AND status = 'pending')
34501
- OR (offeredTo = ? AND status = 'offered') ORDER BY priority DESC, createdAt, rowid`, [agentId, agentId]);
34502
- const tasks = [];
34503
- for (const row of rows) {
34504
- const task = rowToAgentTask(row);
34505
- if (task.status === "offered" || (await checkDependencies2(task.id)).ready)
34506
- tasks.push(task);
34507
- }
34508
- const mentions = await getDbClient2().get(`SELECT COUNT(DISTINCT m.channelId) AS count FROM channel_messages m
34509
- JOIN channels c ON c.id = m.channelId
34510
- LEFT JOIN channel_read_state s ON s.channelId = m.channelId AND s.agentId = ?
34511
- WHERE m.mentions LIKE ? AND s.processing_since IS NULL
34512
- AND (s.lastReadAt IS NULL OR m.createdAt > s.lastReadAt)`, [agentId, `%"${agentId}"%`]);
34513
- return { work: tasks.length + (mentions?.count ?? 0), topTask: tasks[0] ?? null };
34514
- }
34515
- function agentRuntimeLimit(maxTasks, slotsPerRuntime) {
34516
- return Math.floor(maxTasks / slotsPerRuntime);
34517
- }
34518
- function countPoolRuntimes(runtimes, now, staleMinutes) {
34519
- return runtimes.filter((r) => r.status === "provisioning" || r.status === "active" && Date.parse(r.lastSeenAt) >= now.getTime() - staleMinutes * 60000).length;
34520
- }
34521
- function computeDesired(pool, agents) {
34522
- const desired = new Map;
34523
- let remaining = Math.max(0, (pool.maxRuntimes ?? Infinity) - agents.reduce((n, a) => n + a.current, 0));
34524
- for (const agent of agents) {
34525
- const uncovered = Math.max(0, agent.work - agent.freeSlots - agent.provisioning * pool.slotsPerRuntime);
34526
- const limit = agentRuntimeLimit(agent.maxTasks, pool.slotsPerRuntime);
34527
- const count = Math.min(limit, Math.max(pool.minRuntimes, agent.current + Math.ceil(uncovered / pool.slotsPerRuntime)));
34528
- const added = Math.min(remaining, Math.max(0, count - agent.current));
34529
- desired.set(agent.agentId, Math.min(count, agent.current + added));
34530
- remaining -= added;
34531
- }
34532
- return desired;
34533
- }
34534
- var init_demand = __esm(() => {
34535
- init_db4();
34536
- init_read();
34537
- });
34538
-
34539
- // src/be/runtime-pools/reachability.ts
34540
- function isRuntimePoolWakeable(pool, now = new Date) {
34541
- if (!pool.enabled || pool.circuitOpenUntil && Date.parse(pool.circuitOpenUntil) > now.getTime())
34542
- return false;
34543
- return canProvisionKind(pool.kind) && pool.maxRuntimes !== 0 && Boolean(pool.resolvedImage ?? pool.image);
34544
- }
34545
- async function isAgentReachable(agent) {
34546
- if (agent.status !== "offline")
34547
- return true;
34548
- if (!isRuntimePoolsEnabled() || !agent.runtimePoolId)
34549
- return false;
34550
- const pool = await getRuntimePool2(agent.runtimePoolId);
34551
- if (!pool?.enabled)
34552
- return false;
34553
- if (isRuntimePoolWakeable(pool))
34554
- return true;
34555
- return await getDbClient2().get(`SELECT id FROM runtime_instances WHERE agent_id = ? AND pool_id = ?
34556
- AND status = 'provisioning' AND draining = 0 LIMIT 1`, [agent.id, pool.id]) !== null;
34557
- }
34558
- async function isAgentOnDemand(agent, now = new Date) {
34559
- if (agent.status !== "offline" || !agent.runtimePoolId)
34560
- return false;
34561
- if (!isRuntimePoolsEnabled() || !isMultiRuntimeEnabled())
34562
- return false;
34563
- const pool = await getRuntimePool2(agent.runtimePoolId);
34564
- if (!pool?.enabled)
34565
- return false;
34566
- const runtimes = await listRuntimeInstancesForPool(pool.id);
34567
- const own = runtimes.filter((r) => r.agentId === agent.id);
34568
- if (own.some((r) => r.status === "provisioning" && !r.draining))
34569
- return true;
34570
- if (!isRuntimePoolWakeable(pool, now))
34571
- return false;
34572
- const staleMinutes = runtimeStaleThresholdMinutes();
34573
- const limit = agentRuntimeLimit(agent.maxTasks ?? 1, pool.slotsPerRuntime);
34574
- if (countPoolRuntimes(own, now, staleMinutes) >= limit)
34575
- return false;
34576
- if (pool.maxRuntimes === null)
34577
- return true;
34578
- return countPoolRuntimes(runtimes, now, staleMinutes) < pool.maxRuntimes;
34579
- }
34580
- var init_reachability = __esm(() => {
34581
- init_runtime_providers();
34582
- init_multi_runtime2();
34583
- init_runtime_pools_flag();
34584
- init_db4();
34585
- init_multi_runtime();
34586
- init_db2();
34587
- init_demand();
34588
- });
34589
-
34590
- // src/integrations/chat-sdk/router.ts
34591
- function chatChannelKey(adapter, channelId) {
34592
- return channelId.startsWith(`${adapter}:`) ? channelId : `${adapter}:${channelId}`;
34593
- }
34594
- async function getChatChannelMapping(adapter, channelId) {
34595
- const row = await getKv2(CHAT_CHANNELS_NAMESPACE, chatChannelKey(adapter, channelId));
34596
- if (!row || typeof row.value !== "object" || row.value === null)
34597
- return null;
34598
- return row.value;
34599
- }
34600
- async function putChatChannelMapping(adapter, channelId, mapping) {
34601
- const key = chatChannelKey(adapter, channelId);
34602
- await upsertKv2({
34603
- namespace: CHAT_CHANNELS_NAMESPACE,
34604
- key,
34605
- value: mapping,
34606
- valueType: "json",
34607
- expiresAt: null
34608
- });
34609
- return key;
34610
- }
34611
- async function deleteChatChannelMapping(adapter, channelId) {
34612
- return deleteKv2(CHAT_CHANNELS_NAMESPACE, chatChannelKey(adapter, channelId));
34613
- }
34614
- function hasRoutingToken(text) {
34615
- return /swarm#(?:[a-f0-9-]{36}|all)/i.test(text);
34616
- }
34617
- function stripRoutingTokens(text) {
34618
- return text.replace(/swarm#[a-f0-9-]{36}/gi, "").replace(/swarm#all/gi, "").trim();
34619
- }
34620
- function chatOwnerWindowStart(now = Date.now()) {
34621
- const raw = process.env.CHAT_SDK_OWNER_WINDOW_MIN?.trim();
34622
- const value = raw ? Number(raw) : Number.NaN;
34623
- const minutes = Number.isFinite(value) && value >= 0 ? value : DEFAULT_OWNER_WINDOW_MINUTES;
34624
- return new Date(now - minutes * 60000).toISOString();
34625
- }
34626
- async function leadMatch(reachable, matchedText) {
34627
- const lead = reachable.find((agent) => agent.isLead) ?? await getLeadAgent2();
34628
- return { agent: lead, reason: "skill", matchedText };
34629
- }
34630
- async function routeChatMessage(text, ctx) {
34631
- const allAgents = await getAllAgents2();
34632
- const reachableFlags = await Promise.all(allAgents.map((agent) => isAgentReachable(agent)));
34633
- const reachable = allAgents.filter((_, index) => reachableFlags[index]);
34634
- const matches = [];
34635
- for (const match of text.matchAll(/swarm#([a-f0-9-]{36})/gi)) {
34636
- const agentId = match[1];
34637
- if (!agentId || matches.some((m) => m.agent?.id === agentId))
34638
- continue;
34639
- const agent = await getAgentById2(agentId);
34640
- if (agent && await isAgentReachable(agent)) {
34641
- matches.push({ agent, reason: "human_pinned", matchedText: match[0] });
34642
- }
34643
- }
34644
- if (/swarm#all/i.test(text)) {
34645
- for (const agent of reachable) {
34646
- if (agent.isLead || matches.some((m) => m.agent?.id === agent.id))
34647
- continue;
34648
- matches.push({ agent, reason: "human_pinned", matchedText: "swarm#all" });
34649
- }
34650
- }
34651
- if (matches.length > 0)
34652
- return { kind: "agents", matches };
34653
- const mapping = await getChatChannelMapping(ctx.adapter, ctx.channelId);
34654
- if (mapping?.workflowId && (ctx.botMentioned || ctx.isDirectMessage)) {
34655
- return { kind: "workflow", workflowId: mapping.workflowId };
34656
- }
34657
- if (mapping?.agentId) {
34658
- const agent = await getAgentById2(mapping.agentId);
34659
- if (agent) {
34660
- return {
34661
- kind: "agents",
34662
- matches: [{ agent, reason: "human_pinned", matchedText: "channel mapping" }]
34663
- };
34664
- }
34665
- console.warn(scrubSecrets(`[chat-sdk] Channel mapping for ${ctx.channelId} names unknown agent ${mapping.agentId}; using the default route`));
34666
- }
34667
- const owner = await getAgentWorkingOnContextKey2(chatSdkContextKey(ctx.threadId), "chat", ctx.adapter === "telegram" && !ctx.isDirectMessage ? chatOwnerWindowStart() : undefined);
34668
- if (owner && await isAgentReachable(owner)) {
34669
- return {
34670
- kind: "agents",
34671
- matches: [{ agent: owner, reason: "continuity", matchedText: "thread follow-up" }]
34672
- };
34673
- }
34674
- if (owner) {
34675
- return {
34676
- kind: "agents",
34677
- matches: [await leadMatch(reachable, "thread follow-up (lead fallback)")]
34678
- };
34679
- }
34680
- if (ctx.botMentioned || ctx.isDirectMessage) {
34681
- return { kind: "agents", matches: [await leadMatch(reachable, "@bot")] };
34682
- }
34683
- return null;
34684
- }
34685
- var CHAT_CHANNELS_NAMESPACE = "integrations:chat:channels", DEFAULT_OWNER_WINDOW_MINUTES = 15;
34686
- var init_router2 = __esm(() => {
34687
- init_db4();
34688
- init_reachability();
34689
- init_context_key();
34690
- init_secret_scrubber();
34691
- });
34692
-
34693
35071
  // src/integrations/chat-sdk/reactions.ts
34694
35072
  function chatAdapterReacts(adapter) {
34695
35073
  return adapter in CHAT_REACTIONS;
@@ -34894,19 +35272,6 @@ var init_templates9 = __esm(() => {
34894
35272
  });
34895
35273
 
34896
35274
  // src/integrations/chat-sdk/inbound.ts
34897
- function escapeRegex(value) {
34898
- return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
34899
- }
34900
- function stripBotMention(text, adapter) {
34901
- let out = text;
34902
- if (adapter.userName) {
34903
- out = out.replace(new RegExp(`(?<!\\w)@${escapeRegex(adapter.userName)}(?![\\w-])`, "gi"), "");
34904
- }
34905
- if (adapter.botUserId) {
34906
- out = out.replace(new RegExp(`<@${escapeRegex(adapter.botUserId)}>`, "g"), "");
34907
- }
34908
- return out.trim();
34909
- }
34910
35275
  function adapterOf(threadId) {
34911
35276
  const i = threadId.indexOf(":");
34912
35277
  return i === -1 ? threadId : threadId.slice(0, i);
@@ -34921,7 +35286,7 @@ async function handleChatInbound(thread, message, kind) {
34921
35286
  text: message.text,
34922
35287
  messageId: message.id
34923
35288
  });
34924
- let text = stripBotMention(chatMessageText(message), thread.adapter);
35289
+ let text = stripBotMention(chatMessageText(message), await botMentionForms(thread.adapter, message));
34925
35290
  const immediate = /^!now\b/i.test(text);
34926
35291
  if (immediate)
34927
35292
  text = text.replace(/^!now\s*/i, "").trim();
@@ -35315,6 +35680,7 @@ var init_inbound = __esm(() => {
35315
35680
  init_commands();
35316
35681
  init_facts();
35317
35682
  init_logger();
35683
+ init_mentions2();
35318
35684
  init_message_text2();
35319
35685
  init_outbound2();
35320
35686
  init_reactions3();
@@ -35905,7 +36271,7 @@ var init_runtime = __esm(() => {
35905
36271
  init_adapters();
35906
36272
  init_background();
35907
36273
  init_commands();
35908
- init_config();
36274
+ init_config2();
35909
36275
  init_discord_gateway();
35910
36276
  init_handlers6();
35911
36277
  init_logger();
@@ -35941,7 +36307,7 @@ function extractText(adf) {
35941
36307
  if (!isNode(adf))
35942
36308
  return "";
35943
36309
  const out = [];
35944
- const visit = (node) => {
36310
+ const visit = (node, marker) => {
35945
36311
  const type = typeof node.type === "string" ? node.type : "";
35946
36312
  switch (type) {
35947
36313
  case "text": {
@@ -35972,14 +36338,21 @@ function extractText(adf) {
35972
36338
  `);
35973
36339
  return;
35974
36340
  }
35975
- case "bulletList":
35976
- case "orderedList": {
36341
+ case "bulletList": {
35977
36342
  for (const child of asNodeArray(node.content))
35978
- visit(child);
36343
+ visit(child, "- ");
36344
+ return;
36345
+ }
36346
+ case "orderedList": {
36347
+ const order = node.attrs?.order;
36348
+ const start = typeof order === "number" && Number.isInteger(order) && order >= 0 ? order : 1;
36349
+ asNodeArray(node.content).forEach((child, index) => {
36350
+ visit(child, `${start + index}. `);
36351
+ });
35979
36352
  return;
35980
36353
  }
35981
36354
  case "listItem": {
35982
- out.push("- ");
36355
+ out.push(marker ?? "- ");
35983
36356
  for (const child of asNodeArray(node.content))
35984
36357
  visit(child);
35985
36358
  if (out.length > 0 && !out[out.length - 1]?.endsWith(`
@@ -35989,6 +36362,17 @@ function extractText(adf) {
35989
36362
  }
35990
36363
  return;
35991
36364
  }
36365
+ case "inlineCard":
36366
+ case "blockCard":
36367
+ case "embedCard": {
36368
+ const url = node.attrs?.url;
36369
+ if (typeof url === "string" && url.length > 0)
36370
+ out.push(url);
36371
+ if (type !== "inlineCard")
36372
+ out.push(`
36373
+ `);
36374
+ return;
36375
+ }
35992
36376
  case "doc": {
35993
36377
  for (const child of asNodeArray(node.content))
35994
36378
  visit(child);
@@ -36612,7 +36996,7 @@ async function handleIssueDeleteEvent(event) {
36612
36996
  return;
36613
36997
  const task = sync.swarmId ? await getTaskById2(sync.swarmId) : null;
36614
36998
  if (task && !isTerminalTaskStatus(task.status)) {
36615
- await cancelTask2(sync.swarmId, "Jira issue deleted");
36999
+ await cancelTask2(sync.swarmId, "Jira issue deleted", { statusKind: "external" });
36616
37000
  console.log(`[Jira Sync] Cancelled task ${sync.swarmId} (Jira issue ${issue.key ?? issue.id} deleted)`);
36617
37001
  }
36618
37002
  }
@@ -36722,7 +37106,7 @@ async function notifySlack(text) {
36722
37106
  return;
36723
37107
  }
36724
37108
  try {
36725
- const { getSlackApp } = await import("./app-b267ggx1.js");
37109
+ const { getSlackApp } = await import("./app-zfa9dwjw.js");
36726
37110
  const app = getSlackApp();
36727
37111
  if (!app) {
36728
37112
  console.warn("[Jira webhook keepalive] Slack not available, cannot send notification");
@@ -36793,7 +37177,7 @@ async function deleteJiraWebhook(webhookId) {
36793
37177
  console.log(`[Jira webhook keepalive] Deleted webhook id=${webhookId}`);
36794
37178
  }
36795
37179
  async function overwriteWebhookIds(next) {
36796
- const { getDbClient } = await import("./db-84pz2w5c.js");
37180
+ const { getDbClient } = await import("./db-sc59379z.js");
36797
37181
  await getDbClient().transaction(async (tx) => {
36798
37182
  const row = await tx.get("SELECT metadata FROM oauth_apps WHERE provider = 'jira'");
36799
37183
  if (!row) {
@@ -109104,7 +109488,7 @@ async function handleIssueUpdate(event, deliveryId) {
109104
109488
  if (swarmStatus === "cancelled") {
109105
109489
  const task = await getTaskById2(sync.swarmId);
109106
109490
  if (task && !isTerminalTaskStatus(task.status)) {
109107
- await cancelTask2(sync.swarmId, `Linear issue cancelled`);
109491
+ await cancelTask2(sync.swarmId, `Linear issue cancelled`, { statusKind: "external" });
109108
109492
  console.log(`[Linear Sync] Cancelled task ${sync.swarmId} (Linear issue ${data.identifier ?? issueId} cancelled)`);
109109
109493
  }
109110
109494
  return;
@@ -109127,7 +109511,7 @@ async function handleIssueDelete(event) {
109127
109511
  return;
109128
109512
  const task = await getTaskById2(sync.swarmId);
109129
109513
  if (task && !isTerminalTaskStatus(task.status)) {
109130
- await cancelTask2(sync.swarmId, "Linear issue deleted");
109514
+ await cancelTask2(sync.swarmId, "Linear issue deleted", { statusKind: "external" });
109131
109515
  console.log(`[Linear Sync] Cancelled task ${sync.swarmId} (Linear issue ${issueId} deleted)`);
109132
109516
  }
109133
109517
  }
@@ -109156,7 +109540,9 @@ async function handleAgentSessionPrompted(event) {
109156
109540
  if (existing) {
109157
109541
  const existingTask = await getTaskById2(existing.swarmId);
109158
109542
  if (existingTask && !isTerminalTaskStatus(existingTask.status)) {
109159
- await cancelTask2(existing.swarmId, "Stopped by user from Linear");
109543
+ await cancelTask2(existing.swarmId, "Stopped by user from Linear", {
109544
+ statusKind: "user"
109545
+ });
109160
109546
  console.log(`[Linear Sync] Cancelled task ${existing.swarmId} (stop signal from Linear)`);
109161
109547
  }
109162
109548
  }
@@ -110287,7 +110673,7 @@ async function loadGlobalConfigsIntoEnv2(override = false) {
110287
110673
  if (updated.length > 0) {
110288
110674
  refreshSecretScrubberCache();
110289
110675
  }
110290
- const { syncSlackTreeVisibility } = await import("./tree-visibility-ts3z30kw.js");
110676
+ const { syncSlackTreeVisibility } = await import("./tree-visibility-rwz67mje.js");
110291
110677
  await syncSlackTreeVisibility();
110292
110678
  return updated;
110293
110679
  }
@@ -110295,7 +110681,7 @@ async function reloadGlobalConfigsAndIntegrations2() {
110295
110681
  return runWithoutRequestAuth(() => runSlackLifecycleExclusive(() => reloadGlobalConfigsAndIntegrationsInner()));
110296
110682
  }
110297
110683
  async function reloadGlobalConfigsAndIntegrationsInner() {
110298
- const { getEmbeddingProvider, resetEmbeddingProvider } = await import("./index-9q42cr54.js");
110684
+ const { getEmbeddingProvider, resetEmbeddingProvider } = await import("./index-rwwhsmjg.js");
110299
110685
  const wasEmbeddingsConfigured = getEmbeddingProvider().isConfigured();
110300
110686
  const updated = await loadGlobalConfigsIntoEnv2(true);
110301
110687
  await syncTelemetryEnabled("settings").catch((err) => {
@@ -110311,7 +110697,7 @@ async function reloadGlobalConfigsAndIntegrationsInner() {
110311
110697
  integrations.push("embeddings");
110312
110698
  }
110313
110699
  if (isEmbeddingsConfigured) {
110314
- import("./embedding-space-yam9zwzj.js").then(({ runEmbeddingMaintenance }) => runEmbeddingMaintenance({ backfill: !wasEmbeddingsConfigured })).catch((err) => {
110700
+ import("./embedding-space-qepzrach.js").then(({ runEmbeddingMaintenance }) => runEmbeddingMaintenance({ backfill: !wasEmbeddingsConfigured })).catch((err) => {
110315
110701
  console.error("[config-reload] embedding maintenance failed (non-fatal):", err);
110316
110702
  });
110317
110703
  }
@@ -111840,13 +112226,22 @@ async function runAppSync(input) {
111840
112226
  if (pairs.length === 0) {
111841
112227
  return { ok: false, passes: [], issues: [noPairIssue(input)] };
111842
112228
  }
111843
- const passes = [];
111844
- for (const pair of pairs) {
111845
- passes.push(await runPass({ appId: app.id, ...pair, invokedBy: input.invokedBy }));
111846
- }
112229
+ const passes = new Array(pairs.length);
112230
+ let next = 0;
112231
+ const worker = async () => {
112232
+ while (next < pairs.length) {
112233
+ const i = next++;
112234
+ passes[i] = await runPass({
112235
+ appId: app.id,
112236
+ ...pairs[i],
112237
+ invokedBy: input.invokedBy
112238
+ });
112239
+ }
112240
+ };
112241
+ await Promise.all(Array.from({ length: Math.min(SYNC_PASS_CONCURRENCY, pairs.length) }, worker));
111847
112242
  return { ok: passes.every((pass) => pass.error === undefined), passes };
111848
112243
  }
111849
- var MAX_PULL_RECORDS = 500, MAX_PASS_WARNINGS = 20, MAX_TASK_LIMIT = 200, DEFAULT_TASK_LIMIT = 100, MAX_TASK_PROMPT_CHARS = 1000, MAX_ERROR_DETAIL_CHARS = 500, SyncPassError, TransformError, SourceRecordSchema, PullPayloadSchema, TASK_CONFIG_KEYS, RECONCILE_CHUNK_SIZE = 200, inFlight3;
112244
+ var MAX_PULL_RECORDS = 500, MAX_PASS_WARNINGS = 20, MAX_TASK_LIMIT = 200, DEFAULT_TASK_LIMIT = 100, MAX_TASK_PROMPT_CHARS = 1000, MAX_ERROR_DETAIL_CHARS = 500, SyncPassError, TransformError, SourceRecordSchema, PullPayloadSchema, TASK_CONFIG_KEYS, RECONCILE_CHUNK_SIZE = 200, inFlight3, SYNC_PASS_CONCURRENCY = 3;
111850
112245
  var init_sync3 = __esm(() => {
111851
112246
  init_zod();
111852
112247
  init_db4();
@@ -117667,7 +118062,7 @@ async function getTaskDetailsHandler(ctx, { taskId, include }) {
117667
118062
  const data = origin === "script-sdk" || origin === "extension" ? full : fitToBudget(full, new Set(include ?? []));
117668
118063
  const reducedParts = data.fitted?.include ?? [];
117669
118064
  const fitNote = reducedParts.length ? ` Fitted to the size budget; include ${JSON.stringify(reducedParts)} for the rest.` : "";
117670
- return toolOk(`Task "${taskId}" (${task.status}) details retrieved.${fitNote}`, {
118065
+ return toolOk(`Task "${taskId}" (${task.status}${task.statusKind ? `, ${task.statusKind}` : ""}) details retrieved.${fitNote}`, {
117671
118066
  details: JSON.stringify(data),
117672
118067
  data
117673
118068
  });
@@ -117726,6 +118121,7 @@ var init_get_task_details = __esm(() => {
117726
118121
  lastUpdatedAt: string2().optional(),
117727
118122
  finishedAt: string2().optional(),
117728
118123
  notifiedAt: string2().optional(),
118124
+ statusKind: string2().optional(),
117729
118125
  failureReason: string2().optional(),
117730
118126
  output: string2().optional(),
117731
118127
  progress: string2().optional(),
@@ -117891,7 +118287,7 @@ async function cancelTaskHandler(ctx, { taskId, reason }) {
117891
118287
  message: "Only the lead or task creator can cancel tasks."
117892
118288
  };
117893
118289
  }
117894
- const cancelled = await cancelTask2(taskId, reason);
118290
+ const cancelled = await cancelTask2(taskId, reason, { statusKind: "agent" });
117895
118291
  if (!cancelled) {
117896
118292
  return {
117897
118293
  success: false,
@@ -117917,7 +118313,7 @@ async function cancelTaskHandler(ctx, { taskId, reason }) {
117917
118313
  const ownershipError = assertOwnsTask(ctx, existingTask, "task.cancel.own");
117918
118314
  if (ownershipError)
117919
118315
  return ownershipError;
117920
- const cancelled = await cancelTask2(taskId, reason);
118316
+ const cancelled = await cancelTask2(taskId, reason, { statusKind: "user" });
117921
118317
  if (!cancelled) {
117922
118318
  return {
117923
118319
  success: false,
@@ -118044,7 +118440,7 @@ var registerChatOpenDmTool = (server) => {
118044
118440
  };
118045
118441
  var init_chat_open_dm = __esm(() => {
118046
118442
  init_zod();
118047
- init_config();
118443
+ init_config2();
118048
118444
  init_logger();
118049
118445
  init_runtime();
118050
118446
  init_teams_origin();
@@ -118139,12 +118535,12 @@ var init_cards = __esm(() => {
118139
118535
  var registerChatPostTool = (server) => {
118140
118536
  createToolRegistrar(server)("chat-post", {
118141
118537
  title: "Post to a chat thread or channel",
118142
- description: "Lead only. Post a message to any Chat SDK thread or channel (Telegram, Slack, Discord, Teams), outside the thread of your current task. Give threadId to reply in a thread, or channelId to start a new message in a channel. Ids carry the adapter prefix, such as telegram:12345. To answer the user of your current chat task, use chat-reply instead. For a structured result (key figures, a table, charts, links), send a `card`; it posts after the text as a native card.",
118538
+ description: "Lead only. Post a message to any Chat SDK thread or channel (Telegram, Slack, Discord, Teams), outside the thread of your current task. Give threadId to reply in a thread or Telegram topic, or channelId to use its registered default topic (otherwise the channel). Ids carry the adapter prefix, such as telegram:12345 or telegram:-100123:42 for topic 42. To answer the user of your current chat task, use chat-reply instead. For a structured result (key figures, a table, charts, links), send a `card`; it posts after the text as a native card.",
118143
118539
  annotations: { openWorldHint: true },
118144
118540
  inputSchema: object2({
118145
118541
  adapter: _enum2(CHAT_SDK_ADAPTER_NAMES).describe("Chat SDK adapter name."),
118146
- threadId: string2().min(1).optional().describe("Full SDK thread id, such as telegram:12345 or slack:C123:1700000000.000100."),
118147
- channelId: string2().min(1).optional().describe("Full SDK channel id, such as slack:C123. Ignored when threadId is set."),
118542
+ threadId: string2().min(1).optional().describe("Full SDK thread id, such as telegram:12345, telegram:-100123:42 (positive integer topic id), or slack:C123:1700000000.000100. Overrides the channel default."),
118543
+ channelId: string2().min(1).optional().describe("Full SDK channel id, such as telegram:-100123 or slack:C123. Uses its registered default Telegram topic when set. Ignored when threadId is set."),
118148
118544
  text: string2().min(1).max(20000).optional().describe("Markdown text to post. Required unless card is given."),
118149
118545
  card: cardSpecInputSchema.optional(),
118150
118546
  attachments: chatAttachmentsSchema
@@ -118207,7 +118603,7 @@ var registerChatPostTool = (server) => {
118207
118603
  var init_chat_post = __esm(() => {
118208
118604
  init_zod();
118209
118605
  init_cards();
118210
- init_config();
118606
+ init_config2();
118211
118607
  init_logger();
118212
118608
  init_outbound2();
118213
118609
  init_outbound_files();
@@ -119346,37 +119742,6 @@ var init_page_versions = __esm(() => {
119346
119742
  init_runtime2();
119347
119743
  });
119348
119744
 
119349
- // src/pages/version.ts
119350
- async function snapshotPage(pageId, changedByAgentId) {
119351
- const page = await getPage2(pageId);
119352
- if (!page) {
119353
- throw new Error(`Page ${pageId} not found — cannot create snapshot`);
119354
- }
119355
- const nextVersion = await getPageEditCounter(pageId);
119356
- const snapshot = {
119357
- title: page.title,
119358
- description: page.description,
119359
- contentType: page.contentType,
119360
- authMode: page.authMode,
119361
- passwordHash: page.passwordHash,
119362
- body: page.body,
119363
- needsCredentials: page.needsCredentials,
119364
- theme: page.theme,
119365
- themeTokens: page.themeTokens,
119366
- designVersion: page.designVersion
119367
- };
119368
- return createPageVersion2({
119369
- pageId,
119370
- version: nextVersion,
119371
- snapshot,
119372
- changedByAgentId
119373
- });
119374
- }
119375
- var init_version3 = __esm(() => {
119376
- init_db4();
119377
- init_page_versions();
119378
- });
119379
-
119380
119745
  // src/themes/classics.ts
119381
119746
  var CLASSIC_THEME_PRESETS;
119382
119747
  var init_classics = __esm(() => {
@@ -120594,6 +120959,198 @@ var init_presets = __esm(() => {
120594
120959
  THEME_PRESET_IDS = THEME_PRESETS.map((preset) => preset.id);
120595
120960
  });
120596
120961
 
120962
+ // src/themes/design-system.ts
120963
+ function readHttpsUrl(value, label, host) {
120964
+ let url;
120965
+ try {
120966
+ url = new URL(value);
120967
+ } catch {
120968
+ throw new DesignSystemError(`${label} must be an absolute https URL`);
120969
+ }
120970
+ if (url.protocol !== "https:" || UNSAFE_URL_CHARACTERS.test(value)) {
120971
+ throw new DesignSystemError(`${label} must be an absolute https URL`);
120972
+ }
120973
+ if (host && url.hostname !== host) {
120974
+ throw new DesignSystemError(`${label} must be on https://${host}`);
120975
+ }
120976
+ return url.href;
120977
+ }
120978
+ function readColor(value, index) {
120979
+ try {
120980
+ const { tokens } = importThemeTokens({ light: { "--color-chart-1": value } });
120981
+ const color = tokens.light["--color-chart-1"];
120982
+ if (color === undefined)
120983
+ throw new ThemeImportError("not a color value");
120984
+ return color;
120985
+ } catch (err) {
120986
+ if (err instanceof ThemeImportError) {
120987
+ throw new DesignSystemError(`chartPalette[${index}]: ${err.message}`);
120988
+ }
120989
+ throw err;
120990
+ }
120991
+ }
120992
+ function buildDesignSystem(input, actor, now = new Date) {
120993
+ const stamp = {
120994
+ source: input.source ?? { kind: "manual" },
120995
+ updatedBy: actor.userId,
120996
+ ...actor.agentId ? { updatedByAgentId: actor.agentId } : {},
120997
+ updatedAt: now.toISOString()
120998
+ };
120999
+ if (input.status === "declined") {
121000
+ return {
121001
+ record: {
121002
+ v: 1,
121003
+ status: "declined",
121004
+ basePreset: DEFAULT_THEME_ID,
121005
+ tokens: { light: {}, dark: {} },
121006
+ mode: "viewer",
121007
+ ...stamp
121008
+ },
121009
+ ignored: []
121010
+ };
121011
+ }
121012
+ const basePreset = input.basePreset ?? DEFAULT_THEME_ID;
121013
+ if (!isThemePresetId(basePreset)) {
121014
+ throw new DesignSystemError(`Unknown basePreset "${basePreset}". Use one of: ${THEME_PRESET_IDS.join(", ")}`);
121015
+ }
121016
+ let imported = {
121017
+ tokens: { light: {}, dark: {} },
121018
+ ignored: []
121019
+ };
121020
+ if (input.themeTokens) {
121021
+ try {
121022
+ imported = importThemeTokens(input.themeTokens);
121023
+ } catch (err) {
121024
+ if (err instanceof ThemeImportError) {
121025
+ throw new DesignSystemError(`Invalid themeTokens: ${err.message}`);
121026
+ }
121027
+ throw err;
121028
+ }
121029
+ }
121030
+ const record = {
121031
+ v: 1,
121032
+ status: "active",
121033
+ basePreset,
121034
+ tokens: imported.tokens,
121035
+ ...input.fontsHref ? { fontsHref: readHttpsUrl(input.fontsHref, "fontsHref", FONTS_HOST) } : {},
121036
+ ...input.logo ? { logo: { url: readHttpsUrl(input.logo.url, "logo.url"), alt: input.logo.alt } } : {},
121037
+ mode: input.mode ?? "viewer",
121038
+ ...input.chartPalette ? { chartPalette: input.chartPalette.map(readColor) } : {},
121039
+ ...stamp
121040
+ };
121041
+ return { record, ignored: imported.ignored };
121042
+ }
121043
+ function readDesignSystem(value) {
121044
+ if (value === undefined || value === null)
121045
+ return null;
121046
+ const result = DesignSystemSchema.safeParse(value);
121047
+ if (!result.success)
121048
+ return { invalid: "stored design system is not a valid v1 record" };
121049
+ const parsed = result.data;
121050
+ try {
121051
+ const { record } = buildDesignSystem({
121052
+ status: parsed.status,
121053
+ basePreset: parsed.basePreset,
121054
+ themeTokens: parsed.tokens,
121055
+ fontsHref: parsed.fontsHref,
121056
+ logo: parsed.logo,
121057
+ mode: parsed.mode,
121058
+ chartPalette: parsed.chartPalette,
121059
+ source: parsed.source
121060
+ }, { userId: parsed.updatedBy, agentId: parsed.updatedByAgentId });
121061
+ return { record: { ...record, updatedAt: parsed.updatedAt } };
121062
+ } catch (err) {
121063
+ if (err instanceof DesignSystemError)
121064
+ return { invalid: err.message };
121065
+ throw err;
121066
+ }
121067
+ }
121068
+ var DESIGN_SYSTEM_NAMESPACE = "design-system", DESIGN_SYSTEM_KEY = "org", DESIGN_SYSTEM_PREVIOUS_KEY = "org.prev", FONTS_HOST = "fonts.googleapis.com", UNSAFE_URL_CHARACTERS, DesignSystemError;
121069
+ var init_design_system = __esm(() => {
121070
+ init_types5();
121071
+ init_import();
121072
+ init_presets();
121073
+ UNSAFE_URL_CHARACTERS = /["'<>\s\\]/;
121074
+ DesignSystemError = class DesignSystemError extends Error {
121075
+ name = "DesignSystemError";
121076
+ };
121077
+ });
121078
+
121079
+ // src/be/design-system.ts
121080
+ function toStored(value) {
121081
+ const read = readDesignSystem(value);
121082
+ if (!read)
121083
+ return { status: "none" };
121084
+ if ("invalid" in read)
121085
+ return { status: "invalid", reason: read.invalid };
121086
+ return { status: read.record.status, record: read.record };
121087
+ }
121088
+ async function getDesignSystem() {
121089
+ const [current, previous] = await Promise.all([
121090
+ getKv2(DESIGN_SYSTEM_NAMESPACE, DESIGN_SYSTEM_KEY),
121091
+ getKv2(DESIGN_SYSTEM_NAMESPACE, DESIGN_SYSTEM_PREVIOUS_KEY)
121092
+ ]);
121093
+ return { current: toStored(current?.value), previous: toStored(previous?.value) };
121094
+ }
121095
+ async function getActiveDesignSystem() {
121096
+ const stored = toStored((await getKv2(DESIGN_SYSTEM_NAMESPACE, DESIGN_SYSTEM_KEY))?.value);
121097
+ return "record" in stored && stored.record.status === "active" ? stored.record : null;
121098
+ }
121099
+ async function saveDesignSystem(record) {
121100
+ await getDbClient2().transaction(async () => {
121101
+ const current = await getKv2(DESIGN_SYSTEM_NAMESPACE, DESIGN_SYSTEM_KEY);
121102
+ if (current) {
121103
+ await upsertKv2({
121104
+ namespace: DESIGN_SYSTEM_NAMESPACE,
121105
+ key: DESIGN_SYSTEM_PREVIOUS_KEY,
121106
+ value: current.value,
121107
+ valueType: "json"
121108
+ });
121109
+ }
121110
+ await upsertKv2({
121111
+ namespace: DESIGN_SYSTEM_NAMESPACE,
121112
+ key: DESIGN_SYSTEM_KEY,
121113
+ value: record,
121114
+ valueType: "json"
121115
+ });
121116
+ });
121117
+ }
121118
+ var init_design_system2 = __esm(() => {
121119
+ init_design_system();
121120
+ init_db4();
121121
+ });
121122
+
121123
+ // src/pages/version.ts
121124
+ async function snapshotPage(pageId, changedByAgentId) {
121125
+ const page = await getPage2(pageId);
121126
+ if (!page) {
121127
+ throw new Error(`Page ${pageId} not found — cannot create snapshot`);
121128
+ }
121129
+ const nextVersion = await getPageEditCounter(pageId);
121130
+ const snapshot = {
121131
+ title: page.title,
121132
+ description: page.description,
121133
+ contentType: page.contentType,
121134
+ authMode: page.authMode,
121135
+ passwordHash: page.passwordHash,
121136
+ body: page.body,
121137
+ needsCredentials: page.needsCredentials,
121138
+ theme: page.theme,
121139
+ themeTokens: page.themeTokens,
121140
+ designVersion: page.designVersion
121141
+ };
121142
+ return createPageVersion2({
121143
+ pageId,
121144
+ version: nextVersion,
121145
+ snapshot,
121146
+ changedByAgentId
121147
+ });
121148
+ }
121149
+ var init_version3 = __esm(() => {
121150
+ init_db4();
121151
+ init_page_versions();
121152
+ });
121153
+
120597
121154
  // src/themes/page-fields.ts
120598
121155
  function readThemeFields(input) {
120599
121156
  if (typeof input.theme === "string" && !isThemePresetId(input.theme)) {
@@ -120667,6 +121224,7 @@ var SWARM_CLASS, COLOR_TOKEN_REFERENCE, PAGE_COLOR_TOKENS, registerCreatePageToo
120667
121224
  colorLiteralCount: number2().optional(),
120668
121225
  usesDesignSystem: boolean().optional(),
120669
121226
  lightOnlyColors: boolean().optional(),
121227
+ designSystemStatus: string2().optional(),
120670
121228
  movedSessionRootId: string2().optional()
120671
121229
  })
120672
121230
  }, async (input, requestInfo, _meta) => {
@@ -120758,6 +121316,7 @@ var SWARM_CLASS, COLOR_TOKEN_REFERENCE, PAGE_COLOR_TOKENS, registerCreatePageToo
120758
121316
  const designFlags = fresh.contentType === "text/html" ? {
120759
121317
  usesDesignSystem: typeof input.theme === "string" || Boolean(input.themeTokens) || bodyUsesDesignSystem(fresh.body),
120760
121318
  lightOnlyColors: hasLightOnlyColors(fresh.themeTokens),
121319
+ designSystemStatus: (await getDesignSystem()).current.status,
120761
121320
  ...fresh.designVersion >= 2 ? { colorLiteralCount: countColorLiterals(fresh.body) } : {}
120762
121321
  } : {};
120763
121322
  const { ignored } = themeFields;
@@ -120793,6 +121352,7 @@ var init_create_page = __esm(() => {
120793
121352
  init_caller_session_group();
120794
121353
  init_db4();
120795
121354
  init_page_versions();
121355
+ init_design_system2();
120796
121356
  init_color_literals();
120797
121357
  init_version3();
120798
121358
  init_page_fields();
@@ -123360,8 +123920,11 @@ async function admitExternalWait(event, source, rawMatch) {
123360
123920
  }
123361
123921
  if (adapter.confirm) {
123362
123922
  try {
123363
- if (await adapter.confirm(event, match)) {
123364
- return { error: `${target} already happened; read its result instead of deferring.` };
123923
+ const already = toConfirmResult(await adapter.confirm(event, match));
123924
+ if (already.happened) {
123925
+ return {
123926
+ error: `${target} already happened${already.detail ? ` (${already.detail})` : ""}; read its result instead of deferring.`
123927
+ };
123365
123928
  }
123366
123929
  } catch (error) {
123367
123930
  return {
@@ -123627,7 +124190,8 @@ Deferred until ${nextRunAt} (schedule ${schedule.id}). Pending: ${note}${checksB
123627
124190
  const terminalOutput = task.outputSchema ? output : renderHumanFacingDeferral(nextRunAt, requesterTz, isFallbackTz, admitted && eventWait ? describeEventWait(admitted.adapter.source, eventWait.event, admitted.match) : wakeOn ? renderWaitingOn(watchedAgentNames, watchedTaskIds.length) : undefined);
123628
124191
  const completed = await completeTask2(taskId, terminalOutput, {
123629
124192
  addTags: ["deferred"],
123630
- deferredAt: new Date().toISOString()
124193
+ deferredAt: new Date().toISOString(),
124194
+ statusKind: "deferred"
123631
124195
  });
123632
124196
  if (!completed) {
123633
124197
  throw new DeferAbortedError(`Task ${taskId} reached a terminal state before this deferral committed.`);
@@ -123856,6 +124420,87 @@ var init_delete_page = __esm(() => {
123856
124420
  });
123857
124421
  });
123858
124422
 
124423
+ // src/tools/design-system.ts
124424
+ var outputSchema, registerDesignSystemTools = (server) => {
124425
+ const register = createToolRegistrar(server);
124426
+ register("design-system-get", {
124427
+ title: "Get the org design system",
124428
+ description: 'Returns the org design system that restyles every HTML page without its own theme. status is "none" (nobody asked yet), "declined" (the requester said no; do not ask again), "active", or "invalid" (the stored record fails validation and pages ignore it). previous is the value the last design-system-set replaced, for a one-step undo.',
124429
+ annotations: { readOnlyHint: true },
124430
+ inputSchema: object2({}),
124431
+ outputSchema
124432
+ }, async () => {
124433
+ const { current, previous } = await getDesignSystem();
124434
+ return toolOk(`Design system status: ${current.status}.`, {
124435
+ data: {
124436
+ status: current.status,
124437
+ ..."record" in current ? { designSystem: current.record } : {},
124438
+ ..."reason" in current ? { invalidReason: current.reason } : {},
124439
+ ..."record" in previous ? { previous: previous.record } : {}
124440
+ }
124441
+ });
124442
+ });
124443
+ register("design-system-set", {
124444
+ title: "Set the org design system",
124445
+ description: 'Saves the org design system: a base preset plus token overrides, fonts, logo, mode lock and chart palette. Every HTML page without its own theme picks it up on its next view. Save only what the requester approved, after they saw a preview (the design-system-seed script builds one). To record a "no", pass status "declined". dryRun: true validates and returns the normalized record without saving. The replaced value is kept as previous (see design-system-get).',
124446
+ annotations: { destructiveHint: false },
124447
+ rbac: { permission: "design-system.write" },
124448
+ inputSchema: DesignSystemInputSchema.extend({
124449
+ dryRun: boolean().optional().describe("Validate and return the normalized record without saving.")
124450
+ }),
124451
+ outputSchema
124452
+ }, async ({ dryRun, ...input }, requestInfo) => {
124453
+ if (!requestInfo.agentId)
124454
+ return toolErr('Agent ID not found. Set the "X-Agent-ID" header.');
124455
+ const agent = await getAgentById2(requestInfo.agentId);
124456
+ const decision = can({
124457
+ principal: { kind: "agent", agentId: requestInfo.agentId, isLead: agent?.isLead ?? false },
124458
+ verb: "design-system.write",
124459
+ source: "mcp"
124460
+ });
124461
+ if (!decision.allow)
124462
+ return toolErr(decision.reason);
124463
+ const userId = await resolveTaskAuditUserId(requestInfo.sourceTaskId, requestInfo.agentId);
124464
+ let built;
124465
+ try {
124466
+ built = buildDesignSystem(input, { userId, agentId: requestInfo.agentId });
124467
+ } catch (err) {
124468
+ if (err instanceof DesignSystemError)
124469
+ return toolErr(err.message);
124470
+ throw err;
124471
+ }
124472
+ if (!dryRun)
124473
+ await saveDesignSystem(built.record);
124474
+ const { record, ignored } = built;
124475
+ return toolOk(`${dryRun ? "Validated" : "Saved"} ${record.status} design system (basePreset=${record.basePreset}, mode=${record.mode}).` + (ignored.length > 0 ? ` Ignored tokens: ${ignored.join(", ")}.` : ""), {
124476
+ data: {
124477
+ status: record.status,
124478
+ designSystem: record,
124479
+ saved: !dryRun,
124480
+ ...ignored.length > 0 ? { ignoredTokens: ignored } : {}
124481
+ }
124482
+ });
124483
+ });
124484
+ };
124485
+ var init_design_system3 = __esm(() => {
124486
+ init_zod();
124487
+ init_audit_user();
124488
+ init_db4();
124489
+ init_design_system2();
124490
+ init_rbac();
124491
+ init_design_system();
124492
+ init_utils();
124493
+ init_types5();
124494
+ outputSchema = swarmToolOutputSchema({
124495
+ status: string2().optional(),
124496
+ designSystem: unknown().optional(),
124497
+ previous: unknown().optional(),
124498
+ invalidReason: string2().optional(),
124499
+ ignoredTokens: array2(string2()).optional(),
124500
+ saved: boolean().optional()
124501
+ });
124502
+ });
124503
+
123859
124504
  // src/tools/script-common.ts
123860
124505
  function stripAnsi(text) {
123861
124506
  return text.replace(/\x1b\[[0-9;]*m/g, "");
@@ -124459,7 +125104,7 @@ function renderTaskSummaries(tasks) {
124459
125104
  const rows = tasks.map((task) => {
124460
125105
  const cells = [
124461
125106
  task.id,
124462
- task.status,
125107
+ task.statusKind ? `${task.status} (${task.statusKind})` : task.status,
124463
125108
  task.priority,
124464
125109
  task.agentId,
124465
125110
  task.taskPreview ?? task.task
@@ -124471,6 +125116,7 @@ function renderTaskSummaries(tasks) {
124471
125116
  }
124472
125117
  async function getTasksHandler(ctx, {
124473
125118
  status,
125119
+ statusKind,
124474
125120
  mineOnly,
124475
125121
  unassigned,
124476
125122
  offeredToMe,
@@ -124489,6 +125135,7 @@ async function getTasksHandler(ctx, {
124489
125135
  const agentId = ctx.kind === "owner" ? ctx.agentId : undefined;
124490
125136
  const taskFilters = {
124491
125137
  status,
125138
+ statusKind,
124492
125139
  agentId: ctx.kind === "owner" && mineOnly ? agentId ?? undefined : undefined,
124493
125140
  unassigned: ctx.kind === "owner" ? unassigned : undefined,
124494
125141
  offeredTo: ctx.kind === "owner" && offeredToMe ? agentId ?? undefined : undefined,
@@ -124511,6 +125158,7 @@ async function getTasksHandler(ctx, {
124511
125158
  agentId: t.agentId,
124512
125159
  ...includeFull ? { task: t.task } : { taskPreview: t.task },
124513
125160
  status: t.status,
125161
+ statusKind: t.statusKind,
124514
125162
  taskType: t.taskType,
124515
125163
  tags: t.tags,
124516
125164
  priority: t.priority,
@@ -124524,6 +125172,8 @@ async function getTasksHandler(ctx, {
124524
125172
  const filters = [];
124525
125173
  if (status)
124526
125174
  filters.push(`status='${status}'`);
125175
+ if (statusKind)
125176
+ filters.push(`statusKind='${statusKind}'`);
124527
125177
  if (ctx.kind === "owner" && mineOnly)
124528
125178
  filters.push("mine only");
124529
125179
  if (ctx.kind === "owner" && unassigned)
@@ -124578,6 +125228,7 @@ var init_get_tasks = __esm(() => {
124578
125228
  task: string2().optional(),
124579
125229
  taskPreview: string2().optional(),
124580
125230
  status: AgentTaskStatusSchema.optional(),
125231
+ statusKind: string2().optional(),
124581
125232
  taskType: string2().optional(),
124582
125233
  tags: array2(string2()).optional(),
124583
125234
  priority: number2().optional(),
@@ -124590,6 +125241,7 @@ var init_get_tasks = __esm(() => {
124590
125241
  });
124591
125242
  getTasksInputSchema = object2({
124592
125243
  status: AgentTaskStatusSchema.optional().describe("Filter by task status (unassigned, offered, pending, in_progress, completed, failed)."),
125244
+ statusKind: TaskStatusKindSchema.optional().describe("Filter by why the task ended. Pair with status, e.g. status 'failed' + statusKind 'error' (crash, rate limit, exit code) vs 'agent' (the agent chose to fail)."),
124593
125245
  mineOnly: boolean().optional().describe("Only return tasks assigned to you."),
124594
125246
  unassigned: boolean().optional().describe("Only return unassigned tasks in the pool."),
124595
125247
  offeredToMe: boolean().optional().describe("Only return tasks offered to you (awaiting accept/reject)."),
@@ -124814,6 +125466,10 @@ var init_kv_reserved_namespaces = __esm(() => {
124814
125466
  RESERVED_FAMILIES = new Map([
124815
125467
  ["apps", "namespace is reserved for swarm apps; use the app row endpoints"],
124816
125468
  ["comb", "namespace is reserved for Comb; use POST /api/comb/review-batches"],
125469
+ [
125470
+ "design-system",
125471
+ "namespace is reserved for the org design system; use design-system-set or PUT /api/design-system"
125472
+ ],
124817
125473
  ["heartbeat-checklist", "namespace is reserved for heartbeat checklist receipts"],
124818
125474
  ["worker", "namespace is reserved for worker nudges"],
124819
125475
  ["slack-external-alert", "namespace is reserved for Slack external channel alerts"],
@@ -125476,6 +126132,7 @@ var userOutputShape, IdentityEntry, InputSchema, registerManageUserTool = (serve
125476
126132
  timezone: input.timezone,
125477
126133
  dailyBudgetUsd: input.dailyBudgetUsd ?? undefined,
125478
126134
  status: input.status,
126135
+ avatar: input.avatar,
125479
126136
  metadata
125480
126137
  });
125481
126138
  for (const ident of input.identities ?? []) {
@@ -125518,6 +126175,7 @@ var userOutputShape, IdentityEntry, InputSchema, registerManageUserTool = (serve
125518
126175
  timezone: input.timezone,
125519
126176
  dailyBudgetUsd: input.dailyBudgetUsd,
125520
126177
  status: input.status,
126178
+ avatar: input.avatar,
125521
126179
  metadata
125522
126180
  });
125523
126181
  if (!updated)
@@ -125581,6 +126239,7 @@ var init_manage_user = __esm(() => {
125581
126239
  init_users();
125582
126240
  init_rbac();
125583
126241
  init_utils();
126242
+ init_types5();
125584
126243
  userOutputShape = looseObject({
125585
126244
  id: string2().optional(),
125586
126245
  name: string2().optional(),
@@ -125593,6 +126252,7 @@ var init_manage_user = __esm(() => {
125593
126252
  metadata: record2(string2(), unknown()).optional(),
125594
126253
  dailyBudgetUsd: number2().nullable().optional(),
125595
126254
  status: _enum2(["invited", "active", "suspended"]).optional(),
126255
+ avatar: looseObject({}).nullable().optional(),
125596
126256
  createdAt: string2().optional(),
125597
126257
  lastUpdatedAt: string2().optional()
125598
126258
  });
@@ -125614,6 +126274,7 @@ var init_manage_user = __esm(() => {
125614
126274
  dailyBudgetUsd: number2().nullable().optional().describe("Daily budget in USD (null clears the cap)"),
125615
126275
  status: _enum2(["invited", "active", "suspended"]).optional().describe("User status — invited / active / suspended"),
125616
126276
  metadata: record2(string2(), unknown()).nullable().optional().describe("Free-form JSON metadata (null clears the field)"),
126277
+ avatar: UserAvatarSchema.nullable().optional().describe("Custom avatar, one of: { type: 'lucide', icon: '<kebab-case-lucide-name>', color?: '#RRGGBB' }; { type: 'url', url: 'https://…' } (https image, no credentials); { type: 'agent-fs', path: '/users/<id>/avatar.png', orgId?, driveId? } (an image in agent-fs; pass both IDs or neither for the swarm drive). Pass null to reset to initials."),
125617
126278
  comms: object2({
125618
126279
  tone: string2().nullable().optional(),
125619
126280
  language: string2().nullable().optional(),
@@ -125784,7 +126445,7 @@ var init_mcp_server_delete = __esm(() => {
125784
126445
  var registerMcpServerGetTool = (server) => {
125785
126446
  createToolRegistrar(server)("mcp-server-get", {
125786
126447
  title: "Get MCP Server",
125787
- annotations: { destructiveHint: false },
126448
+ annotations: { readOnlyHint: true },
125788
126449
  description: "Get MCP server details by ID or name. Name resolution uses scope cascade: agent > swarm > global.",
125789
126450
  inputSchema: object2({
125790
126451
  id: string2().optional().describe("MCP server ID"),
@@ -125898,7 +126559,7 @@ function renderServerLines(servers) {
125898
126559
  var registerMcpServerListTool = (server) => {
125899
126560
  createToolRegistrar(server)("mcp-server-list", {
125900
126561
  title: "List MCP Servers",
125901
- annotations: { destructiveHint: false },
126562
+ annotations: { readOnlyHint: true },
125902
126563
  description: "List MCP servers with optional filters. Use installedOnly to see servers installed for the calling agent.",
125903
126564
  inputSchema: object2({
125904
126565
  scope: _enum2(["global", "swarm", "agent"]).optional().describe("Filter by scope"),
@@ -128254,13 +128915,14 @@ var registerRegisterChatChannelTool = (server) => {
128254
128915
  createToolRegistrar(server)("register-chat-channel", {
128255
128916
  title: "Route a chat channel to an agent or workflow",
128256
128917
  annotations: { idempotentHint: true },
128257
- description: "Lead-only. Route every swarm-addressed message from one Chat SDK channel (a Telegram group, Slack channel, Discord channel or Teams chat) to a fixed agent or workflow instead of the lead. Give exactly one of agentId or workflowId. A swarm#<agentId> token in a message still wins over the mapping. Remove it with unregister-chat-channel.",
128918
+ description: "Lead-only. Route every swarm-addressed message from one Chat SDK channel (a Telegram group, Slack channel, Discord channel or Teams chat) to a fixed agent or workflow instead of the lead. Give exactly one of agentId or workflowId. For Telegram, defaultThreadId sets the topic used by channel-only chat-post calls. Re-registering replaces the mapping; omit defaultThreadId to clear it. A swarm#<agentId> token in a message still wins over the mapping. Remove it with unregister-chat-channel.",
128258
128919
  inputSchema: object2({
128259
128920
  adapter: _enum2(CHAT_SDK_ADAPTER_NAMES).describe("Chat SDK adapter name."),
128260
128921
  channelId: string2().min(1).describe("SDK channel id, such as telegram:-100123 or slack:C123 (prefix optional)."),
128261
128922
  agentId: string2().optional().describe("Agent that receives the channel's tasks."),
128262
128923
  workflowId: string2().optional().describe("Workflow whose webhook trigger receives the channel's messages."),
128263
- name: string2().max(200).optional().describe("Display name for the mapping.")
128924
+ name: string2().max(200).optional().describe("Display name for the mapping."),
128925
+ defaultThreadId: string2().min(1).optional().describe("Telegram topic used when chat-post gives only channelId, such as telegram:-100123:42. Must belong to this channel. Explicit threadId and chat-reply ignore this default.")
128264
128926
  }),
128265
128927
  outputSchema: swarmToolOutputSchema({
128266
128928
  yourAgentId: string2().optional(),
@@ -128268,11 +128930,12 @@ var registerRegisterChatChannelTool = (server) => {
128268
128930
  mapping: looseObject({
128269
128931
  agentId: string2().optional(),
128270
128932
  workflowId: string2().optional(),
128933
+ defaultThreadId: string2().optional(),
128271
128934
  name: string2().optional(),
128272
128935
  createdAt: string2().optional()
128273
128936
  }).optional()
128274
128937
  })
128275
- }, async ({ adapter, channelId, agentId, workflowId, name }, requestInfo) => {
128938
+ }, async ({ adapter, channelId, agentId, workflowId, name, defaultThreadId }, requestInfo) => {
128276
128939
  const data = { yourAgentId: requestInfo.agentId };
128277
128940
  try {
128278
128941
  if (!await canManageChatChannels(requestInfo)) {
@@ -128293,6 +128956,7 @@ var registerRegisterChatChannelTool = (server) => {
128293
128956
  ...agentId ? { agentId } : {},
128294
128957
  ...workflowId ? { workflowId } : {},
128295
128958
  ...name ? { name } : {},
128959
+ ...defaultThreadId ? { defaultThreadId } : {},
128296
128960
  createdAt: new Date().toISOString()
128297
128961
  };
128298
128962
  const key = await putChatChannelMapping(adapter, channelId, mapping);
@@ -128333,7 +128997,7 @@ var registerRegisterChatChannelTool = (server) => {
128333
128997
  var init_register_chat_channel = __esm(() => {
128334
128998
  init_zod();
128335
128999
  init_db4();
128336
- init_config();
129000
+ init_config2();
128337
129001
  init_logger();
128338
129002
  init_router2();
128339
129003
  init_rbac();
@@ -128557,7 +129221,7 @@ async function markKapsoMessageSeen(messageId) {
128557
129221
  });
128558
129222
  }
128559
129223
  var KAPSO_NUMBERS_NAMESPACE = "integrations:kapso:numbers", KAPSO_DEDUPE_NAMESPACE = "integrations:kapso:dedupe", KAPSO_DEDUPE_TTL_MS, DEFAULT_KAPSO_API_BASE_URL = "https://api.kapso.ai";
128560
- var init_config2 = __esm(() => {
129224
+ var init_config3 = __esm(() => {
128561
129225
  init_db4();
128562
129226
  KAPSO_DEDUPE_TTL_MS = 24 * 60 * 60 * 1000;
128563
129227
  });
@@ -128694,7 +129358,7 @@ var init_register_kapso_number = __esm(() => {
128694
129358
  init_zod();
128695
129359
  init_db4();
128696
129360
  init_client();
128697
- init_config2();
129361
+ init_config3();
128698
129362
  init_rbac();
128699
129363
  init_utils();
128700
129364
  init_constants3();
@@ -129056,7 +129720,7 @@ function getCombConfig() {
129056
129720
  driveId: getAgentFsDefaultDriveId() ?? null
129057
129721
  };
129058
129722
  }
129059
- var init_config3 = __esm(() => {
129723
+ var init_config4 = __esm(() => {
129060
129724
  init_constants3();
129061
129725
  });
129062
129726
 
@@ -129238,7 +129902,7 @@ var init_auth2 = __esm(() => {
129238
129902
  init_db4();
129239
129903
  init_rbac_roles();
129240
129904
  init_session_shares();
129241
- init_config3();
129905
+ init_config4();
129242
129906
  init_kv_overflow();
129243
129907
  init_kv_reserved_namespaces();
129244
129908
  init_rbac();
@@ -139436,7 +140100,7 @@ async function refusing2(agentId, run) {
139436
140100
  throw error;
139437
140101
  }
139438
140102
  }
139439
- var objectOutputSchema2, CellValue, Grid, RANGE_HELP = "A1 range such as `Tasks!B2:C3`, `A1:C10` (first tab), `'My tab'!A:A` (whole column, capped to the used range) or `B2`.", dataShape, outputSchema, ID2 = "Object id (from sheet-create or sheet-list).", PATH = "Drive path of the `.sheet.json` file, instead of `id`.", WRITE, registerSheetCreateTool = (server) => {
140103
+ var objectOutputSchema2, CellValue, Grid, RANGE_HELP = "A1 range such as `Tasks!B2:C3`, `A1:C10` (first tab), `'My tab'!A:A` (whole column, capped to the used range) or `B2`.", dataShape, outputSchema2, ID2 = "Object id (from sheet-create or sheet-list).", PATH = "Drive path of the `.sheet.json` file, instead of `id`.", WRITE, registerSheetCreateTool = (server) => {
139440
140104
  createToolRegistrar(server)("sheet-create", {
139441
140105
  title: "Create sheet",
139442
140106
  annotations: WRITE,
@@ -139446,7 +140110,7 @@ var objectOutputSchema2, CellValue, Grid, RANGE_HELP = "A1 range such as `Tasks!
139446
140110
  title: string2().max(200).optional(),
139447
140111
  tabs: array2(object2({ name: string2().min(1).max(31), rows: Grid.optional() })).optional().describe("Tabs to create, each with an optional `rows` grid written from A1.")
139448
140112
  }),
139449
- outputSchema
140113
+ outputSchema: outputSchema2
139450
140114
  }, async ({ path, title, tabs }, requestInfo) => {
139451
140115
  const result = await refusing2(requestInfo.agentId, () => createSheet({ agentId: requestInfo.agentId, path, title, tabs }));
139452
140116
  if ("error" in result)
@@ -139465,7 +140129,7 @@ var objectOutputSchema2, CellValue, Grid, RANGE_HELP = "A1 range such as `Tasks!
139465
140129
  id: string2().min(1).optional().describe(ID2),
139466
140130
  path: string2().min(1).optional().describe(PATH)
139467
140131
  }),
139468
- outputSchema
140132
+ outputSchema: outputSchema2
139469
140133
  }, async ({ id, path }, requestInfo) => {
139470
140134
  const result = await refusing2(requestInfo.agentId, () => getSheet({ agentId: requestInfo.agentId, id, path }));
139471
140135
  if ("error" in result)
@@ -139485,7 +140149,7 @@ var objectOutputSchema2, CellValue, Grid, RANGE_HELP = "A1 range such as `Tasks!
139485
140149
  limit: number2().int().positive().max(200).optional(),
139486
140150
  offset: number2().int().nonnegative().optional()
139487
140151
  }),
139488
- outputSchema
140152
+ outputSchema: outputSchema2
139489
140153
  }, async ({ prefix, limit, offset }, requestInfo) => {
139490
140154
  const result = await refusing2(requestInfo.agentId, () => listSheets({ agentId: requestInfo.agentId, prefix, limit, offset }));
139491
140155
  if ("error" in result)
@@ -139508,7 +140172,7 @@ var objectOutputSchema2, CellValue, Grid, RANGE_HELP = "A1 range such as `Tasks!
139508
140172
  range: string2().min(1).describe(RANGE_HELP),
139509
140173
  formulas: boolean().optional().describe("Also return `formulas[][]`: the formula text where a cell has one, else the value.")
139510
140174
  }),
139511
- outputSchema
140175
+ outputSchema: outputSchema2
139512
140176
  }, async ({ id, path, range, formulas }, requestInfo) => {
139513
140177
  const result = await refusing2(requestInfo.agentId, () => getSheetRange({ agentId: requestInfo.agentId, id, path, range, formulas }));
139514
140178
  if ("error" in result)
@@ -139528,7 +140192,7 @@ var objectOutputSchema2, CellValue, Grid, RANGE_HELP = "A1 range such as `Tasks!
139528
140192
  range: string2().min(1).describe(RANGE_HELP),
139529
140193
  values: Grid.describe("Rows of cell values, all the same length (at most 10,000 cells).")
139530
140194
  }),
139531
- outputSchema
140195
+ outputSchema: outputSchema2
139532
140196
  }, async ({ id, path, range, values }, requestInfo) => {
139533
140197
  const result = await refusing2(requestInfo.agentId, () => setSheetRange({ agentId: requestInfo.agentId, id, path, range, values }));
139534
140198
  if ("error" in result)
@@ -139547,7 +140211,7 @@ var objectOutputSchema2, CellValue, Grid, RANGE_HELP = "A1 range such as `Tasks!
139547
140211
  tab: string2().min(1).describe("Tab name."),
139548
140212
  rows: Grid.describe("Rows to append (at most 10,000 cells).")
139549
140213
  }),
139550
- outputSchema
140214
+ outputSchema: outputSchema2
139551
140215
  }, async ({ id, path, tab, rows }, requestInfo) => {
139552
140216
  const result = await refusing2(requestInfo.agentId, () => appendSheetRows({ agentId: requestInfo.agentId, id, path, tab, rows }));
139553
140217
  if ("error" in result)
@@ -139566,7 +140230,7 @@ var objectOutputSchema2, CellValue, Grid, RANGE_HELP = "A1 range such as `Tasks!
139566
140230
  path: string2().min(1).optional().describe(PATH),
139567
140231
  range: string2().min(1).describe(RANGE_HELP)
139568
140232
  }),
139569
- outputSchema
140233
+ outputSchema: outputSchema2
139570
140234
  }, async ({ id, path, range }, requestInfo) => {
139571
140235
  const result = await refusing2(requestInfo.agentId, () => clearSheetRange({ agentId: requestInfo.agentId, id, path, range }));
139572
140236
  if ("error" in result)
@@ -139587,7 +140251,7 @@ var objectOutputSchema2, CellValue, Grid, RANGE_HELP = "A1 range such as `Tasks!
139587
140251
  name: string2().min(1).max(31).describe("New tab name."),
139588
140252
  after: string2().optional().describe("Insert after this tab; default: at the end.")
139589
140253
  }),
139590
- outputSchema
140254
+ outputSchema: outputSchema2
139591
140255
  }, async ({ id, path, name, after }, requestInfo) => {
139592
140256
  const result = await refusing2(requestInfo.agentId, () => addSheetTab({ agentId: requestInfo.agentId, id, path, name, after }));
139593
140257
  if ("error" in result)
@@ -139606,7 +140270,7 @@ var objectOutputSchema2, CellValue, Grid, RANGE_HELP = "A1 range such as `Tasks!
139606
140270
  path: string2().min(1).describe("Drive path for the new sheet, ending in `.sheet.json`."),
139607
140271
  title: string2().max(200).optional()
139608
140272
  }),
139609
- outputSchema
140273
+ outputSchema: outputSchema2
139610
140274
  }, async ({ sourcePath, path, title }, requestInfo) => {
139611
140275
  const result = await refusing2(requestInfo.agentId, () => importSheetXlsx({ agentId: requestInfo.agentId, sourcePath, path, title }));
139612
140276
  if ("error" in result)
@@ -139625,7 +140289,7 @@ var objectOutputSchema2, CellValue, Grid, RANGE_HELP = "A1 range such as `Tasks!
139625
140289
  targetPath: string2().min(1).describe("Drive path for the new file, ending in `.xlsx`."),
139626
140290
  overwrite: boolean().optional().describe("Replace `targetPath` when it exists.")
139627
140291
  }),
139628
- outputSchema
140292
+ outputSchema: outputSchema2
139629
140293
  }, async ({ id, path, targetPath, overwrite }, requestInfo) => {
139630
140294
  const result = await refusing2(requestInfo.agentId, () => exportSheetXlsx({ agentId: requestInfo.agentId, id, path, targetPath, overwrite }));
139631
140295
  if ("error" in result)
@@ -139667,7 +140331,7 @@ var init_sheets = __esm(() => {
139667
140331
  path: string2().optional(),
139668
140332
  dropped: array2(string2()).optional()
139669
140333
  };
139670
- outputSchema = swarmToolOutputSchema(dataShape);
140334
+ outputSchema2 = swarmToolOutputSchema(dataShape);
139671
140335
  WRITE = { readOnlyHint: false, idempotentHint: false };
139672
140336
  });
139673
140337
 
@@ -139824,7 +140488,7 @@ var init_skill_name_resolution = __esm(() => {
139824
140488
  var registerSkillGetTool = (server) => {
139825
140489
  createToolRegistrar(server)("skill-get", {
139826
140490
  title: "Get Skill",
139827
- annotations: { destructiveHint: false },
140491
+ annotations: { readOnlyHint: true },
139828
140492
  description: "Get full skill content by ID or name. Name resolution checks agent scope first, then swarm, then global. In swarm scope the ownerless skill wins, then your own, then the only agent-owned one; when several other agents own that name, it errors with their IDs: pass skillId instead.",
139829
140493
  inputSchema: object2({
139830
140494
  skillId: string2().optional().describe("Skill ID"),
@@ -139878,7 +140542,7 @@ var init_skill_get = __esm(() => {
139878
140542
  var registerSkillGetFileTool = (server) => {
139879
140543
  createToolRegistrar(server)("skill-get-file", {
139880
140544
  title: "Get Skill File",
139881
- annotations: { destructiveHint: false },
140545
+ annotations: { readOnlyHint: true },
139882
140546
  description: "Fetch a bundled reference file from a complex skill by skillId and relative path. Use this when the file is not available on disk.",
139883
140547
  inputSchema: object2({
139884
140548
  skillId: string2().describe("Skill ID"),
@@ -140099,7 +140763,7 @@ function renderSkillList(skills) {
140099
140763
  var registerSkillListTool = (server) => {
140100
140764
  createToolRegistrar(server)("skill-list", {
140101
140765
  title: "List Skills",
140102
- annotations: { destructiveHint: false },
140766
+ annotations: { readOnlyHint: true },
140103
140767
  description: "List available skills with optional filters.",
140104
140768
  inputSchema: object2({
140105
140769
  type: _enum2(["remote", "personal"]).optional().describe("Filter by type"),
@@ -140229,7 +140893,7 @@ function renderSkillList2(skills) {
140229
140893
  var registerSkillSearchTool = (server) => {
140230
140894
  createToolRegistrar(server)("skill-search", {
140231
140895
  title: "Search Skills",
140232
- annotations: { destructiveHint: false },
140896
+ annotations: { readOnlyHint: true },
140233
140897
  description: "Search skills by keyword (name and description).",
140234
140898
  inputSchema: object2({
140235
140899
  query: string2().min(1).describe("Search query"),
@@ -143122,7 +143786,7 @@ async function readScriptActionAllowlist() {
143122
143786
  const [row] = await getSwarmConfigs2({ scope: "global", key: UI_SPEC_SCRIPT_ACTIONS_KEY });
143123
143787
  if (row)
143124
143788
  return row.value;
143125
- const { getDeploymentEnvValue } = await import("./core-nheayfgm.js");
143789
+ const { getDeploymentEnvValue } = await import("./core-bwp98v4w.js");
143126
143790
  return getDeploymentEnvValue(UI_SPEC_SCRIPT_ACTIONS_KEY);
143127
143791
  }
143128
143792
  async function loadScriptActionLookups() {
@@ -143678,7 +144342,7 @@ This check refuses once per task; the next completion is accepted without the sp
143678
144342
  }
143679
144343
  }
143680
144344
  if (status === "completed") {
143681
- const result = await completeTask2(taskId, output);
144345
+ const result = await completeTask2(taskId, output, { statusKind: "agent" });
143682
144346
  if (result && uiSpecToStore)
143683
144347
  await upsertTaskUiSpec(taskId, uiSpecToStore);
143684
144348
  if (result) {
@@ -143705,7 +144369,9 @@ This check refuses once per task; the next completion is accepted without the sp
143705
144369
  }
143706
144370
  }
143707
144371
  } else if (status === "failed") {
143708
- const result = await failTask2(taskId, failureReason ?? "Unknown failure");
144372
+ const result = await failTask2(taskId, failureReason ?? "Unknown failure", {
144373
+ statusKind: "agent"
144374
+ });
143709
144375
  if (result) {
143710
144376
  updatedTask = result;
143711
144377
  getDbClient2().afterCommit(() => {
@@ -143730,7 +144396,7 @@ This check refuses once per task; the next completion is accepted without the sp
143730
144396
  }
143731
144397
  }
143732
144398
  } else if (status === "skipped") {
143733
- const result = await skipTask2(taskId, skipReason);
144399
+ const result = await skipTask2(taskId, skipReason, { statusKind: "agent" });
143734
144400
  if (result) {
143735
144401
  updatedTask = result;
143736
144402
  if (existingTask.agentId) {
@@ -145009,7 +145675,7 @@ async function emitBudgetRefusalSideEffects(ctx, inserted) {
145009
145675
  console.warn(`[budget-refusal-notify] Failed to create follow-up task for budget refusal (task=${ctx.task.id.slice(0, 8)}): ${err}`);
145010
145676
  }
145011
145677
  }
145012
- import("./event-bus-08t2b4y2.js").then(({ workflowEventBus }) => {
145678
+ import("./event-bus-7gbsr0g4.js").then(({ workflowEventBus }) => {
145013
145679
  workflowEventBus.emit("task.budget_refused", {
145014
145680
  taskId: ctx.task.id,
145015
145681
  agentId: ctx.agentId,
@@ -146017,7 +146683,7 @@ async function sendAndFormat(params, agentId, contextMessageId) {
146017
146683
  return toolErr(errorMessage, { data: { yourAgentId: agentId } });
146018
146684
  }
146019
146685
  }
146020
- var SESSION_WINDOW_HINT = 'Outside the 24h WhatsApp session window — free-form text is rejected. Use a pre-approved template message (see the `kapso-whatsapp` skill, "Send a template").', outputSchema2, registerSendWhatsappMessageTool = (server) => {
146686
+ var SESSION_WINDOW_HINT = 'Outside the 24h WhatsApp session window — free-form text is rejected. Use a pre-approved template message (see the `kapso-whatsapp` skill, "Send a template").', outputSchema3, registerSendWhatsappMessageTool = (server) => {
146021
146687
  createToolRegistrar(server)("send-whatsapp-message", {
146022
146688
  title: "Send WhatsApp Message",
146023
146689
  annotations: { openWorldHint: true },
@@ -146028,7 +146694,7 @@ var SESSION_WINDOW_HINT = 'Outside the 24h WhatsApp session window — free-form
146028
146694
  body: string2().min(1).describe("Message text."),
146029
146695
  previewUrl: boolean().optional().describe("Render a link preview for URLs in the body (default false).")
146030
146696
  }),
146031
- outputSchema: outputSchema2
146697
+ outputSchema: outputSchema3
146032
146698
  }, async ({ phoneNumberId, to, body, previewUrl }, requestInfo) => {
146033
146699
  return sendAndFormat({ phoneNumberId, to, body, previewUrl }, requestInfo.agentId, undefined);
146034
146700
  });
@@ -146043,7 +146709,7 @@ var SESSION_WINDOW_HINT = 'Outside the 24h WhatsApp session window — free-form
146043
146709
  inReplyTo: string2().min(1).describe("The inbound WAMID to quote-reply (set as context.message_id)."),
146044
146710
  body: string2().min(1).describe("Reply text.")
146045
146711
  }),
146046
- outputSchema: outputSchema2
146712
+ outputSchema: outputSchema3
146047
146713
  }, async ({ phoneNumberId, to, inReplyTo, body }, requestInfo) => {
146048
146714
  return sendAndFormat({ phoneNumberId, to, body }, requestInfo.agentId, inReplyTo);
146049
146715
  });
@@ -146051,9 +146717,9 @@ var SESSION_WINDOW_HINT = 'Outside the 24h WhatsApp session window — free-form
146051
146717
  var init_whatsapp_message = __esm(() => {
146052
146718
  init_zod();
146053
146719
  init_client();
146054
- init_config2();
146720
+ init_config3();
146055
146721
  init_utils();
146056
- outputSchema2 = swarmToolOutputSchema({
146722
+ outputSchema3 = swarmToolOutputSchema({
146057
146723
  yourAgentId: string2().optional(),
146058
146724
  messageId: string2().optional(),
146059
146725
  sessionWindowExpired: boolean().optional()
@@ -146277,7 +146943,7 @@ var init_delete_workflow = __esm(() => {
146277
146943
  var registerGetWorkflowTool = (server) => {
146278
146944
  createToolRegistrar(server)("get-workflow", {
146279
146945
  title: "Get Workflow",
146280
- annotations: { destructiveHint: false },
146946
+ annotations: { readOnlyHint: true },
146281
146947
  description: "Get a workflow by ID, including its definition, triggers, cooldown, input, and auto-generated edges for UI rendering.",
146282
146948
  inputSchema: object2({
146283
146949
  id: string2().uuid().describe("Workflow ID")
@@ -146337,7 +147003,7 @@ function renderSteps(steps) {
146337
147003
  var STEP_VALUE_CAP = 400, registerGetWorkflowRunTool = (server) => {
146338
147004
  createToolRegistrar(server)("get-workflow-run", {
146339
147005
  title: "Get Workflow Run",
146340
- annotations: { destructiveHint: false },
147006
+ annotations: { readOnlyHint: true },
146341
147007
  description: "Get details of a workflow run by ID, including all steps and their statuses.",
146342
147008
  inputSchema: object2({
146343
147009
  id: string2().uuid().describe("Workflow run ID"),
@@ -146428,7 +147094,7 @@ async function listWorkflowRunsHandler({
146428
147094
  var DEFAULT_RUN_LIMIT = 20, TRIGGER_DATA_SUMMARY_CAP = 400, listWorkflowRunsInputSchema, registerListWorkflowRunsTool = (server) => {
146429
147095
  createToolRegistrar(server)("list-workflow-runs", {
146430
147096
  title: "List Workflow Runs",
146431
- annotations: { destructiveHint: false },
147097
+ annotations: { readOnlyHint: true },
146432
147098
  description: "List execution runs for a workflow with offset pagination (default 20, max 100), optionally filtered by status. Returns SLIM rows WITHOUT the full `context` or trigger data — each row carries a bounded `triggerDataSummary` instead. To inspect a run's context and steps, call `get-workflow-run` by id, or pass `includeContext: true` here.",
146433
147099
  inputSchema: listWorkflowRunsInputSchema,
146434
147100
  outputSchema: swarmToolOutputSchema({
@@ -146461,7 +147127,7 @@ var init_list_workflow_runs = __esm(() => {
146461
147127
  var registerListWorkflowsTool = (server) => {
146462
147128
  createToolRegistrar(server)("list-workflows", {
146463
147129
  title: "List Workflows",
146464
- annotations: { destructiveHint: false },
147130
+ annotations: { readOnlyHint: true },
146465
147131
  description: "List all automation workflows, optionally filtered by enabled status. Returns SLIM rows WITHOUT the full `definition` (DAG) — each row carries a `nodeCount` instead. To inspect or patch a workflow's nodes/triggers, call `get-workflow` by id, or pass `includeFull: true` here.",
146466
147132
  inputSchema: object2({
146467
147133
  enabled: boolean().optional().describe("Filter by enabled status (omit to return all)"),
@@ -147334,6 +148000,7 @@ async function createServer(opts = {}) {
147334
148000
  registerAppUpsertTool(server);
147335
148001
  registerCreatePageTool(server);
147336
148002
  registerDeletePageTool(server);
148003
+ registerDesignSystemTools(server);
147337
148004
  }
147338
148005
  if (hasCapability("metrics")) {
147339
148006
  registerCreateMetricTool(server);
@@ -147439,11 +148106,11 @@ var init_server = __esm(() => {
147439
148106
  init_steering2();
147440
148107
  init_task_reactions();
147441
148108
  init_core();
147442
- init_config();
148109
+ init_config2();
147443
148110
  init_mcp_limits();
147444
148111
  init_resolver();
147445
148112
  init_rbac();
147446
- init_config4();
148113
+ init_config5();
147447
148114
  init_left_threads();
147448
148115
  init_accept_steer();
147449
148116
  init_app_action_run();
@@ -147474,6 +148141,7 @@ var init_server = __esm(() => {
147474
148141
  init_defer_task();
147475
148142
  init_delete_channel();
147476
148143
  init_delete_page();
148144
+ init_design_system3();
147477
148145
  init_extension_activate_version();
147478
148146
  init_extension_catalog();
147479
148147
  init_extension_delete();
@@ -147606,4 +148274,4 @@ var init_server = __esm(() => {
147606
148274
  loggedToolAllowlistWarnings = new Set;
147607
148275
  });
147608
148276
 
147609
- export { safeParse, getObjectShape, getLiteralValue, init_zod_compat, LATEST_PROTOCOL_VERSION, DEFAULT_NEGOTIATED_PROTOCOL_VERSION, SUPPORTED_PROTOCOL_VERSIONS, isJSONRPCRequest, isJSONRPCResultResponse, ErrorCode, isJSONRPCErrorResponse, JSONRPCMessageSchema, EmptyResultSchema, isInitializeRequest, InitializeResultSchema, CreateTaskResultSchema, ListResourcesResultSchema, ListResourceTemplatesResultSchema, ReadResourceResultSchema, ResourceListChangedNotificationSchema, ListPromptsResultSchema, GetPromptResultSchema, PromptListChangedNotificationSchema, ListToolsResultSchema, CallToolResultSchema, ToolListChangedNotificationSchema, ListChangedOptionsBaseSchema, CreateMessageRequestSchema, CreateMessageResultSchema, CreateMessageResultWithToolsSchema, ElicitRequestSchema, ElicitResultSchema, CompleteResultSchema, McpError, init_types, Protocol, mergeCapabilities, init_protocol, AjvJsonSchemaValidator, init_ajv_provider, assertToolsCallTaskCapability, assertClientRequestTaskCapability, init_helpers, McpServer, init_mcp, referencedBundlePaths, skillDirs, init_manifest_format, recoverIncompleteRuns, init_recovery, handleWebhookTrigger, verifyHmacSignature, decodeStandardWebhookSecret, verifyStandardWebhookSignature, verifyTokenEquality, WebhookError, init_triggers, snapshotAndUpdateWorkflow, init_version, applyPreTaskCreate, init_apply_task_create, RawLlmConfigSchema, RawLlmOutputSchema, executeRawLlm, init_raw_llm, getExecutorRegistry2, initWorkflows2, init_workflows, isGitHubEnabled, initGitHub, verifyWebhookSignature, getWorkerInstallationToken, init_app, isReservedProviderEvent, init_event_waits, stripSiblingBlock, init_sibling_block, createTaskWithSiblingAwareness, init_sibling_awareness, dispatchScheduleTarget, calculateNextRun2, startScheduler2, stopScheduler2, runScheduleNow2, init_scheduler, ExtensionAssetConflictError, hashOf, scriptHash, liveScriptSpec, liveWorkflowSpec, skillSpecOf, liveSkillSpec, skillHash, 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, retry, init_retry, 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, hasNativeToolHandlers2, listRegistered2, dispatchPre2, dispatchPost2, init_dispatcher, resolveIdentity, renderIdentity, init_identity, dismissedNamespace, dismissUnmappedIdentity, restoreUnmappedIdentity, recordUnmappedIdentity, init_unmapped_identities, getDeliveredSlackMessageTs, foldIntoPendingSlackTask, init_slack_fold, MAX_TASK_ATTACHMENT_BYTES, recordTaskAttachmentUpload, scopeFromAttachment, backingProviderId, init_task_attachment_store, transcribeAudioNotes, init_transcription, init_templates, buildEffectiveText, bufferedFileFailures, fetchSlackFiles, createSlackTaskWithFiles, attachSlackFilesToDraft, notifySlackFileFailures, init_inbound_files, pendingWorkForAgent, countPoolRuntimes, computeDesired, init_demand, isRuntimePoolWakeable, isAgentReachable, isAgentOnDemand, init_reachability, isAddressedToOtherUser, broadcastMatches, routeMessage, extractTaskFromMessage, init_router, extractSlackMessageText, slackInboundMessageText, collectSlackMessageFiles, init_message_text, createAdditiveBuffer, init_additive_buffer, isAgentMailEnabled, initAgentMail, verifyAgentMailWebhook, isInboxAllowed, isSenderAllowed, handleMessageReceived, init_agentmail, isAzureDevOpsEnabled, initAzureDevOps, verifyAzureDevOpsWebhook, repointTrackerSyncBySwarmId, init_tracker, 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_app2, handleJiraWebhook, init_webhook, init_jira, handleAgentSessionEvent, handleIssueUpdate, handleIssueDelete, handleAgentSessionPrompted, init_sync, isLinearEnabled, initLinear, init_app3, init_linear, init_slack, verifyPageSession, LEGACY_PAGE_SESSION_COOKIE, isCookieSafePageId, extractPageSession, extractLegacyPageSession, extractAndVerifyCookie, isLocalDevPageRequest, pageSessionSetCookies, init_page_session, resolveHttpRequestAuth, init_auth, getDeploymentEnvValue2, loadGlobalConfigsIntoEnv2, reloadGlobalConfigsAndIntegrations2, scheduleIntegrationsReload2, handleCore2, init_core, runTaskUiScriptAction, init_script_actions, REBOOT_RETRY_PIN_TAG2, getPinCandidateAgent2, resolveLeadOnlyRecoveryAssignment2, getResumeGeneration2, getNextResumeGeneration2, inheritedModelSelection2, nextFallback2, createWorkerTaskFollowUp2, createResumeFollowUp2, createRerouteDecisionTask2, createPoolStarvationDecisionTask2, init_worker_follow_up, MCP_MAX_TOOL_INPUT_ELEMENTS, MCP_MAX_REQUEST_BODY_BYTES, init_mcp_limits, userCtx, init_task_tool_ctx, resolveRequestPrincipal, requestPrincipal, agentFirstPrincipal, requireAuthKind, rejectGuest, init_request_principal, resolveTaskRequester, init_task_requester, handleApps, init_apps, parseScene, init_elements, MAX_OBJECT_BYTES, init_write_object, cancelApprovalRequest, cancelApprovalRequestAndRun, init_approval_cancel, getUserCommsPrefs, init_requester_comms, getTaskDetailsInputSchema, getTaskDetailsOutputSchema, getTaskDetailsHandler, init_get_task_details, cancelTaskInputSchema, cancelTaskOutputSchema, cancelTaskHandler, init_cancel_task, DbQueryTimeoutError, DbQueryConcurrencyCapError, executeReadOnlyQuery, getDbQueryHttpBudgetMs, init_db_query_shared, assertSelectOnlyQuery, executeReadOnlyQueryGated, 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, scriptNameSchema, scriptToolOutputSchema, scriptsApiToolResult, init_script_common, getTasksInputSchema, getTasksOutputSchema, getTasksHandler, init_get_tasks, requiresLeadToWrite, 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, attachDemotionEvidence, init_demotion_evidence, expandCandidatesWithGraph, init_graph_expansion, isApiDraining, drainApi, init_api_drain, markKapsoMessageRead, sendKapsoReaction, init_client, getKapsoConfig, getKapsoNumberMapping, markKapsoMessageSeen, init_config2, changesMergePolicy, 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, changesScheduleTarget, init_validate, renderTypeBlobs, init_script_query_types, renderRunOutput, init_script_run, renderSearchResults, searchSuccessMessage, init_script_search, followUpThreadForSourceTask, evaluateFollowUpRedelegation, init_follow_up_redelegation_guard, checkOutputSchemaShape, sendTaskOutputSchema, sendTaskHandler, init_send_task, setSheetRange, appendSheetRows, clearSheetRange, init_service, 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, recomputeSessionCost, init_session_cost_recompute, canClaim, init_budget_admission, emitBudgetRefusalSideEffects, init_budget_refusal_notify, workflowModelErrors, init_model_validation, patchWorkflowDefinition, init_patch_definition, idempotencyKeyHeader, readIdempotencyKey, replayAcceptedOperation, init_idempotency_key, resolveScriptsOnlyMode, init_scripts_only_mode, ALL_CAPABILITIES, hasCapability, getEnabledCapabilities, createServer, init_server };
148277
+ export { safeParse, getObjectShape, getLiteralValue, init_zod_compat, LATEST_PROTOCOL_VERSION, DEFAULT_NEGOTIATED_PROTOCOL_VERSION, SUPPORTED_PROTOCOL_VERSIONS, isJSONRPCRequest, isJSONRPCResultResponse, ErrorCode, isJSONRPCErrorResponse, JSONRPCMessageSchema, EmptyResultSchema, isInitializeRequest, InitializeResultSchema, CreateTaskResultSchema, ListResourcesResultSchema, ListResourceTemplatesResultSchema, ReadResourceResultSchema, ResourceListChangedNotificationSchema, ListPromptsResultSchema, GetPromptResultSchema, PromptListChangedNotificationSchema, ListToolsResultSchema, CallToolResultSchema, ToolListChangedNotificationSchema, ListChangedOptionsBaseSchema, CreateMessageRequestSchema, CreateMessageResultSchema, CreateMessageResultWithToolsSchema, ElicitRequestSchema, ElicitResultSchema, CompleteResultSchema, McpError, init_types, Protocol, mergeCapabilities, init_protocol, AjvJsonSchemaValidator, init_ajv_provider, assertToolsCallTaskCapability, assertClientRequestTaskCapability, init_helpers, McpServer, init_mcp, referencedBundlePaths, skillDirs, init_manifest_format, recoverIncompleteRuns, init_recovery, handleWebhookTrigger, verifyHmacSignature, decodeStandardWebhookSecret, verifyStandardWebhookSignature, verifyTokenEquality, WebhookError, init_triggers, snapshotAndUpdateWorkflow, init_version, applyPreTaskCreate, init_apply_task_create, RawLlmConfigSchema, RawLlmOutputSchema, executeRawLlm, init_raw_llm, getExecutorRegistry2, initWorkflows2, init_workflows, isGitHubEnabled, initGitHub, verifyWebhookSignature, getWorkerInstallationToken, init_app, isReservedProviderEvent, init_event_waits, stripSiblingBlock, init_sibling_block, createTaskWithSiblingAwareness, init_sibling_awareness, hasPendingEventWait, init_deferred_task_waits, dispatchScheduleTarget, calculateNextRun2, parseSchedulerIntervalMs2, startScheduler2, stopScheduler2, runScheduleNow2, init_scheduler, ExtensionAssetConflictError, hashOf, scriptHash, liveScriptSpec, liveWorkflowSpec, skillSpecOf, liveSkillSpec, skillHash, 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, retry, init_retry, 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, hasNativeToolHandlers2, listRegistered2, dispatchPre2, dispatchPost2, init_dispatcher, resolveIdentity, renderIdentity, init_identity, dismissedNamespace, dismissUnmappedIdentity, restoreUnmappedIdentity, recordUnmappedIdentity, init_unmapped_identities, getDeliveredSlackMessageTs, foldIntoPendingSlackTask, init_slack_fold, MAX_TASK_ATTACHMENT_BYTES, recordTaskAttachmentUpload, scopeFromAttachment, backingProviderId, init_task_attachment_store, transcribeAudioNotes, init_transcription, init_templates, buildEffectiveText, bufferedFileFailures, fetchSlackFiles, createSlackTaskWithFiles, attachSlackFilesToDraft, notifySlackFileFailures, init_inbound_files, pendingWorkForAgent, countPoolRuntimes, computeDesired, init_demand, isRuntimePoolWakeable, isAgentReachable, isAgentOnDemand, init_reachability, isAddressedToOtherUser, broadcastMatches, routeMessage, extractTaskFromMessage, init_router, extractSlackMessageText, slackInboundMessageText, collectSlackMessageFiles, init_message_text, createAdditiveBuffer, init_additive_buffer, isAgentMailEnabled, initAgentMail, verifyAgentMailWebhook, isInboxAllowed, isSenderAllowed, handleMessageReceived, init_agentmail, isAzureDevOpsEnabled, initAzureDevOps, verifyAzureDevOpsWebhook, repointTrackerSyncBySwarmId, init_tracker, 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_config2, 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_app2, handleJiraWebhook, init_webhook, init_jira, handleAgentSessionEvent, handleIssueUpdate, handleIssueDelete, handleAgentSessionPrompted, init_sync, isLinearEnabled, initLinear, init_app3, init_linear, init_slack, verifyPageSession, LEGACY_PAGE_SESSION_COOKIE, isCookieSafePageId, extractPageSession, extractLegacyPageSession, extractAndVerifyCookie, isLocalDevPageRequest, pageSessionSetCookies, init_page_session, resolveHttpRequestAuth, init_auth, getDeploymentEnvValue2, loadGlobalConfigsIntoEnv2, reloadGlobalConfigsAndIntegrations2, scheduleIntegrationsReload2, handleCore2, init_core, runTaskUiScriptAction, init_script_actions, cancelApprovalRequest, cancelApprovalRequestAndRun, init_approval_cancel, resolveRequestPrincipal, requestPrincipal, agentFirstPrincipal, requireAuthKind, rejectGuest, init_request_principal, REBOOT_RETRY_PIN_TAG2, getPinCandidateAgent2, resolveLeadOnlyRecoveryAssignment2, getResumeGeneration2, getNextResumeGeneration2, inheritedModelSelection2, nextFallback2, createWorkerTaskFollowUp2, createResumeFollowUp2, createRerouteDecisionTask2, createPoolStarvationDecisionTask2, init_worker_follow_up, MCP_MAX_TOOL_INPUT_ELEMENTS, MCP_MAX_REQUEST_BODY_BYTES, init_mcp_limits, userCtx, init_task_tool_ctx, resolveTaskRequester, init_task_requester, handleApps, init_apps, parseScene, init_elements, MAX_OBJECT_BYTES, init_write_object, getUserCommsPrefs, init_requester_comms, getTaskDetailsInputSchema, getTaskDetailsOutputSchema, getTaskDetailsHandler, init_get_task_details, cancelTaskInputSchema, cancelTaskOutputSchema, cancelTaskHandler, init_cancel_task, DbQueryTimeoutError, DbQueryConcurrencyCapError, executeReadOnlyQuery, getDbQueryHttpBudgetMs, init_db_query_shared, assertSelectOnlyQuery, executeReadOnlyQueryGated, handleDbQuery, init_db_query, snapshotMetric, init_version2, AssetKeyAuthorizationError, authorizeAssetKeyWrite, init_asset_key_auth, getPageEditCounter, init_page_versions, DEFAULT_THEME_ID, THEME_PRESET_IDS, getThemePreset, init_presets, DesignSystemError, buildDesignSystem, init_design_system, getDesignSystem, getActiveDesignSystem, saveDesignSystem, init_design_system2, snapshotPage, init_version3, 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, scriptNameSchema, scriptToolOutputSchema, scriptsApiToolResult, init_script_common, getTasksInputSchema, getTasksOutputSchema, getTasksHandler, init_get_tasks, requiresLeadToWrite, 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, attachDemotionEvidence, init_demotion_evidence, expandCandidatesWithGraph, init_graph_expansion, isApiDraining, drainApi, init_api_drain, markKapsoMessageRead, sendKapsoReaction, init_client, getKapsoConfig, getKapsoNumberMapping, markKapsoMessageSeen, init_config3, changesMergePolicy, init_repo_merge_policy, updateSwarmRepoChecked, init_repo_checked_update, getCombConfig, init_config4, 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, changesScheduleTarget, init_validate, renderTypeBlobs, init_script_query_types, renderRunOutput, init_script_run, renderSearchResults, searchSuccessMessage, init_script_search, followUpThreadForSourceTask, evaluateFollowUpRedelegation, init_follow_up_redelegation_guard, checkOutputSchemaShape, sendTaskOutputSchema, sendTaskHandler, init_send_task, setSheetRange, appendSheetRows, clearSheetRange, init_service, 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, recomputeSessionCost, init_session_cost_recompute, canClaim, init_budget_admission, emitBudgetRefusalSideEffects, init_budget_refusal_notify, workflowModelErrors, init_model_validation, patchWorkflowDefinition, init_patch_definition, idempotencyKeyHeader, readIdempotencyKey, replayAcceptedOperation, init_idempotency_key, resolveScriptsOnlyMode, init_scripts_only_mode, ALL_CAPABILITIES, hasCapability, getEnabledCapabilities, createServer, init_server };