@desplega.ai/agent-swarm 2.8.3 → 2.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (491) hide show
  1. package/dist/acp-adapter-jqn86aam.js +16 -0
  2. package/dist/acp-targets-swxq55dr.js +23 -0
  3. package/dist/{actions-ewz7bp4g.js → actions-pb678g3e.js} +20 -19
  4. package/dist/agent-fs-provision-dmhnc38q.js +27 -0
  5. package/dist/{amp-adapter-f25tqhnf.js → amp-adapter-3pa66q27.js} +3 -3
  6. package/dist/{anthropic-messages-jkva0zps.js → anthropic-messages-x2cp5fvf.js} +41 -41
  7. package/dist/{app-mkptw0k7.js → app-17d12ev4.js} +6 -4
  8. package/dist/approval-notifications-h7vd9pmg.js +20 -0
  9. package/dist/{assistant-c47rfe77.js → assistant-t7k39ree.js} +54 -33
  10. package/dist/{azure-openai-responses-wgtqkbr3.js → azure-openai-responses-590s1eea.js} +10 -10
  11. package/dist/{boot-args-schema-4vb0xsat.js → boot-args-schema-0gqmkfbe.js} +1 -1
  12. package/dist/{boot-reembed-1ghy2sab.js → boot-reembed-f064w382.js} +1 -1
  13. package/dist/{boot-reembed-htr73hbs.js → boot-reembed-n6anc01d.js} +1 -1
  14. package/dist/{boot-scrub-sweep-yrytg42z.js → boot-scrub-sweep-ejd5dnrz.js} +84 -13
  15. package/dist/{boot-seeds-n2b3dx4e.js → boot-seeds-f99fjs5q.js} +4 -4
  16. package/dist/{boxd-jmfqgkqa.js → boxd-wn235q80.js} +7 -7
  17. package/dist/claude-adapter-gvznwxgc.js +28 -0
  18. package/dist/{claude-managed-adapter-hddmxjyj.js → claude-managed-adapter-pbrbvc64.js} +4 -4
  19. package/dist/{claude-managed-setup-hfvry1bd.js → claude-managed-setup-kdxttvc3.js} +10 -10
  20. package/dist/{claude-sdk-session-0hamqzc7.js → claude-sdk-session-0t2teq6n.js} +9386 -9196
  21. package/dist/{cli-yjdgea32.js → cli-1jx0srjt.js} +17 -17
  22. package/dist/{cli-s8p8hhty.js → cli-1tvdx9t5.js} +2 -2
  23. package/dist/{cli-s7zz734a.js → cli-25nstr34.js} +1 -1
  24. package/dist/{cli-kw44j53p.js → cli-2kg31ted.js} +45 -38
  25. package/dist/{cli-mwwmka77.js → cli-2tnbc3gw.js} +375 -127
  26. package/dist/{cli-4dpkjc2e.js → cli-3zxdz9r7.js} +9 -9
  27. package/dist/{cli-mdpbjnzq.js → cli-4ghh072d.js} +14 -14
  28. package/dist/{cli-54qr8mcd.js → cli-57pvhnyt.js} +4 -4
  29. package/dist/{cli-f1kwb5fc.js → cli-5a6pqy45.js} +333 -21
  30. package/dist/{cli-93t5s4zq.js → cli-5gpqgs8b.js} +2 -2
  31. package/dist/{cli-4ax9mvvg.js → cli-5gygrr67.js} +9 -9
  32. package/dist/{cli-t5ys4ebm.js → cli-5kcmxwxv.js} +3 -3
  33. package/dist/{cli-k96cecs7.js → cli-5ntc4we6.js} +2948 -316
  34. package/dist/{cli-15204js0.js → cli-6237rnyr.js} +1 -1
  35. package/dist/cli-6dp0jkfj.js +754 -0
  36. package/dist/{cli-k2rw11py.js → cli-7831nhaw.js} +5 -5
  37. package/dist/{cli-7c5tgqhf.js → cli-7cgf614g.js} +10 -10
  38. package/dist/{cli-z8cvws4c.js → cli-7fx9jyfs.js} +852 -55
  39. package/dist/{cli-pe4d96rb.js → cli-7zm3b3f5.js} +1 -1
  40. package/dist/{cli-0bcgyj5b.js → cli-812paz57.js} +69 -6
  41. package/dist/{cli-ztq5z4e1.js → cli-8axx8vnw.js} +4 -4
  42. package/dist/cli-8x8y70av.js +103 -0
  43. package/dist/{cli-6yygkr0w.js → cli-95930z69.js} +15 -7
  44. package/dist/{cli-sdvcrq5x.js → cli-9a2rtd77.js} +16 -14
  45. package/dist/cli-9ttx00s3.js +137 -0
  46. package/dist/{cli-6ek0hff4.js → cli-a9hfzg2r.js} +3 -3
  47. package/dist/{cli-am1ptset.js → cli-aa8s22gn.js} +19 -14
  48. package/dist/{cli-4e1hfbpq.js → cli-bk9v1xrv.js} +19 -19
  49. package/dist/{cli-e2w34h6z.js → cli-c07v0qfa.js} +98 -54
  50. package/dist/{cli-dpsfwh7n.js → cli-c5cspahx.js} +24 -24
  51. package/dist/{cli-gpz1d0t2.js → cli-cw7mc1je.js} +4 -4
  52. package/dist/{cli-qmqt520k.js → cli-dd37e0cm.js} +2 -2
  53. package/dist/cli-dqgnbnxs.js +132 -0
  54. package/dist/{cli-tnzebztn.js → cli-dx439zpg.js} +1 -1
  55. package/dist/{cli-q6mfk1ej.js → cli-dzzh58sy.js} +2 -2
  56. package/dist/{cli-knva3nmx.js → cli-e9973bf0.js} +8 -6
  57. package/dist/{cli-2znm3dzj.js → cli-eds5xnsz.js} +2 -2
  58. package/dist/{cli-crpf163n.js → cli-eepnpee7.js} +16 -26
  59. package/dist/{cli-nx2n3z6p.js → cli-eg437b5p.js} +1 -1
  60. package/dist/{cli-zdaypkq9.js → cli-faf46gdq.js} +285 -97
  61. package/dist/{cli-tas6ckky.js → cli-fgphc007.js} +2 -2
  62. package/dist/{cli-sg27rk2t.js → cli-fnh4b12r.js} +24 -18
  63. package/dist/{cli-fsgttth8.js → cli-g0vv9dg4.js} +13 -13
  64. package/dist/{cli-rqfvkx5t.js → cli-g3zzby8t.js} +13 -13
  65. package/dist/{cli-kd56bmk4.js → cli-gabsjg8x.js} +3 -1
  66. package/dist/{cli-tf79ryyy.js → cli-gddgcnav.js} +3 -3
  67. package/dist/{cli-rjvsf9qa.js → cli-h474mvp5.js} +11 -11
  68. package/dist/{cli-5a7szzfh.js → cli-hnamkvnc.js} +2 -2
  69. package/dist/{cli-8bpgbr8k.js → cli-j49yqpvh.js} +6 -6
  70. package/dist/{cli-awwptga4.js → cli-jd3kxppb.js} +1 -1
  71. package/dist/{cli-1m96dc36.js → cli-js8zrfyg.js} +3 -3
  72. package/dist/{cli-vx421edw.js → cli-k09cxm6m.js} +9 -7
  73. package/dist/{cli-n5t077me.js → cli-k7pt28ad.js} +10 -3
  74. package/dist/{cli-922z7gwm.js → cli-kaa4bd7x.js} +9 -6
  75. package/dist/cli-kj0hyr43.js +51 -0
  76. package/dist/{cli-c0xjnr8z.js → cli-kmvcm34h.js} +2 -2
  77. package/dist/{cli-0vksaxvr.js → cli-kqh27v2y.js} +2 -2
  78. package/dist/{cli-bj6qhgte.js → cli-m1fbz2wj.js} +30 -37
  79. package/dist/{cli-me0r8gzr.js → cli-mc1fx4xd.js} +27 -25
  80. package/dist/{cli-qps8je6j.js → cli-me4maa4j.js} +46 -6
  81. package/dist/{cli-504akrp9.js → cli-meydjstb.js} +3 -3
  82. package/dist/{cli-n30e0hcp.js → cli-mna6pmfx.js} +2 -2
  83. package/dist/{cli-yss07azk.js → cli-nhq5js1b.js} +3 -3
  84. package/dist/cli-nmcpzbty.js +296 -0
  85. package/dist/cli-nr46j5pw.js +78 -0
  86. package/dist/{cli-t4dv07kr.js → cli-pn1v1pb0.js} +1 -1
  87. package/dist/{cli-c71n3bxq.js → cli-pwsax0vp.js} +2 -2
  88. package/dist/{cli-9zmb7ptc.js → cli-pz1c00aa.js} +8 -753
  89. package/dist/{cli-emekyyhr.js → cli-q2d3e1k1.js} +1 -1
  90. package/dist/{cli-zeaehgyd.js → cli-q8cfh1t9.js} +2 -2
  91. package/dist/{cli-vqva1teb.js → cli-qe909n63.js} +2 -2
  92. package/dist/{cli-2d0cghfn.js → cli-qj39vrc6.js} +1 -1
  93. package/dist/{cli-0agcv1v5.js → cli-rqx70rcz.js} +2 -2
  94. package/dist/{cli-gn9y6fn7.js → cli-rts1qvb4.js} +2 -2
  95. package/dist/{cli-pxwtcgcp.js → cli-sn4pc4qx.js} +2 -2
  96. package/dist/{cli-98rwmcyc.js → cli-snxhtehz.js} +3 -3
  97. package/dist/{cli-d829z3xc.js → cli-spfz393q.js} +6 -6
  98. package/dist/{cli-6wj7p986.js → cli-spzkdgtg.js} +3 -3
  99. package/dist/{cli-m2z8jagn.js → cli-srtkr1h2.js} +18 -18
  100. package/dist/{cli-8476gtwf.js → cli-ssvdrk4y.js} +1 -1
  101. package/dist/{cli-c3ng0mb4.js → cli-svc803vq.js} +69 -816
  102. package/dist/{cli-500c09j9.js → cli-t9ga4qmb.js} +14 -14
  103. package/dist/{cli-j8cjdzan.js → cli-vs9vdpy0.js} +1 -1
  104. package/dist/{cli-bhsfbmk8.js → cli-vvgaz8t6.js} +93 -44
  105. package/dist/{cli-kmemts3w.js → cli-vw5x18yj.js} +39 -69
  106. package/dist/{cli-x3ex5bqf.js → cli-w16kwbzw.js} +1 -1
  107. package/dist/cli-w7dxb2fj.js +921 -0
  108. package/dist/{cli-x6t50dmw.js → cli-wr1h0k28.js} +3 -3
  109. package/dist/{cli-skmhsnqh.js → cli-x40a0w9j.js} +1 -1
  110. package/dist/{cli-k28wkapa.js → cli-xf1wn5ns.js} +2 -2
  111. package/dist/{cli-rh15cakt.js → cli-xwsm6xkr.js} +1 -1
  112. package/dist/{cli-h9yy18gy.js → cli-ymct0ycy.js} +262 -100
  113. package/dist/{cli-dtdht77h.js → cli-zg3z63x3.js} +2 -2
  114. package/dist/cli.js +27 -24
  115. package/dist/{codex-adapter-2brxx5ta.js → codex-adapter-44yq2fkn.js} +9 -8
  116. package/dist/{codex-hook-c930c3ea.js → codex-hook-h1zb7cfk.js} +6 -6
  117. package/dist/{codex-login-cbrs1h5w.js → codex-login-cdyrr5y1.js} +1 -1
  118. package/dist/{codex-session-runner-y9anfj0r.js → codex-session-runner-zbh26gbw.js} +10 -9
  119. package/dist/{commands-wn9q06qr.js → commands-54f02v5b.js} +3 -3
  120. package/dist/{controller-fw608czd.js → controller-9gpwcdek.js} +6 -6
  121. package/dist/{controllers-connect-63j5rdcm.js → controllers-connect-61re6k1n.js} +26 -25
  122. package/dist/{cursor-adapter-6mb9jme8.js → cursor-adapter-7e4g81vd.js} +2 -2
  123. package/dist/{db-y4wfrzbm.js → db-dg2gc7fd.js} +15 -13
  124. package/dist/{db-0m6v5tq4.js → db-wnh0qjy1.js} +3 -3
  125. package/dist/{devin-adapter-r0yx3gv8.js → devin-adapter-zp4tqq53.js} +1 -1
  126. package/dist/{dispatcher-9tq2zzdj.js → dispatcher-jrm24r43.js} +19 -18
  127. package/dist/{docker-j75atvpt.js → docker-9aq30pp2.js} +5 -5
  128. package/dist/{dsh-adapter-t09sv4tq.js → dsh-adapter-1yqk267c.js} +2 -2
  129. package/dist/{e2b-a7vzs2vj.js → e2b-3v1e745x.js} +6 -6
  130. package/dist/{e2b-7s9dscap.js → e2b-sm28k0k3.js} +6 -6
  131. package/dist/{easter-egg-3d-fbwvmwhe.js → easter-egg-3d-r4h9cs9m.js} +1 -1
  132. package/dist/{embedding-space-wh8de1t9.js → embedding-space-bafjr5f7.js} +6 -6
  133. package/dist/{embeddings-3hpbdtjr.js → embeddings-7xmgqe0e.js} +1 -1
  134. package/dist/{event-bus-tr6h3gv8.js → event-bus-xr83x566.js} +1 -1
  135. package/dist/{execute-4bdf8sdy.js → execute-d6jg5ns0.js} +1 -1
  136. package/dist/{external-channel-ts2fwqh0.js → external-channel-frq1xvq2.js} +2 -2
  137. package/dist/fx-adapter-0zrkfbkd.js +19 -0
  138. package/dist/{getMachineId-bsd-nfgrzarv.js → getMachineId-bsd-637a7rbk.js} +3 -3
  139. package/dist/{getMachineId-darwin-wz886dsk.js → getMachineId-darwin-9vytrcnn.js} +3 -3
  140. package/dist/{getMachineId-linux-1nng3p1p.js → getMachineId-linux-mkzsvyyz.js} +3 -3
  141. package/dist/{getMachineId-unsupported-a0428vw9.js → getMachineId-unsupported-4cfs2n11.js} +3 -3
  142. package/dist/{getMachineId-win-h45922nq.js → getMachineId-win-154s3qma.js} +3 -3
  143. package/dist/{google-generative-ai-h7s3e9kk.js → google-generative-ai-hh7strj3.js} +1 -1
  144. package/dist/{google-vertex-fhxaafzw.js → google-vertex-fy5bw2pm.js} +5 -5
  145. package/dist/grok-adapter-3db1c538.js +19 -0
  146. package/dist/handlers-k22n8mnn.js +33 -0
  147. package/dist/{heartbeat-2ze5fzpc.js → heartbeat-6bpa611t.js} +22 -21
  148. package/dist/{hook-ca54yd4s.js → hook-hvm5nf46.js} +5 -5
  149. package/dist/{hook-gaehe2w5.js → hook-w12k146y.js} +14 -14
  150. package/dist/{http-jfg8t2yk.js → http-43tthdvs.js} +1684 -509
  151. package/dist/{index-d6wkh8ar.js → index-1f0vypbg.js} +2 -2
  152. package/dist/{index-enn321kd.js → index-42jq9yy3.js} +3 -3
  153. package/dist/{index-khe3gp0k.js → index-4b1q8kan.js} +20 -20
  154. package/dist/{index-hjhfk3ra.js → index-585gyczt.js} +1 -1
  155. package/dist/index-8xcyd3mc.js +33 -0
  156. package/dist/index-9sy2bh6n.js +38 -0
  157. package/dist/{index-2skqtd76.js → index-b24j7t2m.js} +30 -28
  158. package/dist/{index-gjwaqaq8.js → index-cret47a5.js} +6 -6
  159. package/dist/{index-qwj6ntem.js → index-e3krvkh2.js} +4 -4
  160. package/dist/{index-csgrxedz.js → index-fn054vsf.js} +1 -1
  161. package/dist/{index-3yvzbhxd.js → index-ftywhyr0.js} +129 -142
  162. package/dist/{index-3gv6sc4z.js → index-mhq4sh5w.js} +1 -1
  163. package/dist/index-tx9mc2ap.js +570 -0
  164. package/dist/index-wjd56k1v.js +34 -0
  165. package/dist/{keepalive-k2a3qe73.js → keepalive-rk0j0jvh.js} +4 -4
  166. package/dist/lead-atxf3q6e.js +72 -0
  167. package/dist/{maintenance-gb5sd5nc.js → maintenance-g6z6kaxw.js} +1 -1
  168. package/dist/{node-252anz2h.js → node-jftbyawr.js} +4 -4
  169. package/dist/{node-ray25snp.js → node-zd6shky9.js} +3 -3
  170. package/dist/{oauth-refresh-sweep-y7rm6bkb.js → oauth-refresh-sweep-2k3g2q4w.js} +3 -3
  171. package/dist/{onboard-jmc5qerv.js → onboard-6fdbvh3v.js} +8 -8
  172. package/dist/{openai-codex-responses-k9gapdze.js → openai-codex-responses-bkcd8pjj.js} +9 -9
  173. package/dist/{openai-responses-4d5dx3c7.js → openai-responses-gbh0wfqe.js} +13 -13
  174. package/dist/{opencode-adapter-7eade9ev.js → opencode-adapter-fdbsvts7.js} +7 -6
  175. package/dist/{otel-impl-8j1xhxqd.js → otel-impl-rvwtc09q.js} +110 -110
  176. package/dist/pending-sqkrb836.js +80 -0
  177. package/dist/{pi-mono-adapter-yqmaf32x.js → pi-mono-adapter-asqayqcg.js} +12 -12
  178. package/dist/{pricing-refresh-1nj722h6.js → pricing-refresh-f5tkgmw2.js} +2 -2
  179. package/dist/{rbac-roles-b1mtr6dr.js → rbac-roles-06s555fa.js} +3 -3
  180. package/dist/{rbac-roles-n1f3frk1.js → rbac-roles-szxsg8t1.js} +10 -3
  181. package/dist/{render-v2-1gfpd8rj.js → render-v2-103p266q.js} +4 -4
  182. package/dist/{resume-w1s1eh5v.js → resume-v7kjewt9.js} +8 -7
  183. package/dist/{runtime-84g5egsc.js → runtime-f1gmk0b7.js} +1 -1
  184. package/dist/{session-access-y6z1txk4.js → session-access-6shev8ts.js} +4 -4
  185. package/dist/{session-source-backfill-gxxwfh12.js → session-source-backfill-bd7spzjd.js} +3 -3
  186. package/dist/{setup-r91gstyk.js → setup-kmxmztdb.js} +1 -1
  187. package/dist/thread-buffer-4yz236d0.js +36 -0
  188. package/dist/{virtual-modules-cgnj6kme.js → virtual-modules-57eje5wy.js} +5 -5
  189. package/dist/{work-objects-qcxzg61c.js → work-objects-zr47ygmf.js} +23 -21
  190. package/dist/{worker-follow-up-y2d2h7km.js → worker-follow-up-grrr3fda.js} +19 -18
  191. package/dist/worker-p4hbtcy3.js +72 -0
  192. package/dist/{x-qhxq2ama.js → x-wg164ss9.js} +2 -2
  193. package/openapi.json +1211 -155
  194. package/package.json +9 -6
  195. package/plugin/commands/create-pr.md +1 -1
  196. package/plugin/pi-skills/create-pr/SKILL.md +1 -1
  197. package/src/apps/action-runner.ts +21 -1
  198. package/src/apps/catalog.generated.json +626 -17
  199. package/src/apps/page-validator.ts +314 -8
  200. package/src/assets/key.ts +6 -0
  201. package/src/be/agent-fs-user-keys.ts +186 -0
  202. package/src/be/audit-user.ts +27 -13
  203. package/src/be/automation-preflight.test.ts +14 -14
  204. package/src/be/automation-preflight.ts +24 -16
  205. package/src/be/boot-scrub-sweep.ts +143 -14
  206. package/src/be/caller-session-group.ts +86 -0
  207. package/src/be/checklist.ts +375 -0
  208. package/src/be/db/agents.ts +12 -1
  209. package/src/be/db/approvals.ts +26 -0
  210. package/src/be/db/session-moves.ts +23 -0
  211. package/src/be/db/session-tree.ts +78 -19
  212. package/src/be/db/tasks/eligibility-scan.ts +14 -0
  213. package/src/be/db/tasks/slack-fold.ts +116 -0
  214. package/src/be/db/tasks/write.ts +34 -0
  215. package/src/be/db-queries/mcp-servers.ts +13 -0
  216. package/src/be/db-queries/oauth.ts +6 -0
  217. package/src/be/db-queries/task-artifacts.ts +10 -8
  218. package/src/be/db.ts +42 -15
  219. package/src/be/extensions/assets.ts +17 -13
  220. package/src/be/import/config.ts +54 -0
  221. package/src/be/import/dir-source.ts +372 -0
  222. package/src/be/import/index.ts +149 -0
  223. package/src/be/import/pending.ts +71 -0
  224. package/src/be/import/schema.ts +137 -0
  225. package/src/be/import/seeders.ts +462 -0
  226. package/src/be/migrations/297_import_ownership.sql +34 -0
  227. package/src/be/migrations/301_favorites_key_type.sql +36 -0
  228. package/src/be/migrations/302_checklist_items.sql +23 -0
  229. package/src/be/multi-runtime.ts +8 -1
  230. package/src/be/rbac-roles.ts +8 -1
  231. package/src/be/runtime-pools/demand.ts +20 -2
  232. package/src/be/runtime-pools/reachability.ts +31 -0
  233. package/src/be/runtime-pools/routing.ts +8 -1
  234. package/src/be/runtime-pools/supervisor.ts +6 -7
  235. package/src/be/savings/read.ts +8 -6
  236. package/src/be/script-credential-broker.ts +2 -2
  237. package/src/be/scripts/typecheck.ts +4 -4
  238. package/src/be/seed/agent-fs-provision.ts +104 -19
  239. package/src/be/seed/index.ts +1 -1
  240. package/src/be/seed/registry.ts +27 -8
  241. package/src/be/seed/runner.ts +1 -1
  242. package/src/be/seed/schedules-seeder.ts +24 -6
  243. package/src/be/seed/seed-toggle.ts +32 -0
  244. package/src/be/seed/types.ts +6 -0
  245. package/src/be/seed-scripts/catalog/dreaming-gather.ts +2 -2
  246. package/src/be/steering.ts +27 -4
  247. package/src/be/swarm-config-guard.ts +30 -0
  248. package/src/be/task-citations.ts +8 -5
  249. package/src/commands/onboard/agent-fs-version.ts +1 -1
  250. package/src/commands/runner.ts +61 -2
  251. package/src/e2b/env.ts +2 -0
  252. package/src/extensions/catalog.generated.json +17 -0
  253. package/src/extensions/contract-types.generated.ts +1 -1
  254. package/src/github/app.ts +10 -1
  255. package/src/github/handlers.ts +6 -3
  256. package/src/github/reactions.ts +12 -14
  257. package/src/heartbeat/heartbeat.ts +14 -4
  258. package/src/http/agents.ts +19 -10
  259. package/src/http/all-routes.ts +2 -0
  260. package/src/http/approval-requests.ts +24 -4
  261. package/src/http/apps.ts +69 -5
  262. package/src/http/checklist.ts +176 -0
  263. package/src/http/db-query-bounded.ts +256 -11
  264. package/src/http/db-query-shared.ts +9 -0
  265. package/src/http/favorites.ts +14 -2
  266. package/src/http/fs.ts +346 -1
  267. package/src/http/index.ts +29 -1
  268. package/src/http/kv.ts +13 -0
  269. package/src/http/mcp-oauth.ts +1 -1
  270. package/src/http/mcp-servers.ts +15 -2
  271. package/src/http/onboarding.ts +2 -9
  272. package/src/http/poll.ts +45 -0
  273. package/src/http/script-connections.ts +1 -0
  274. package/src/http/sessions.ts +17 -0
  275. package/src/http/slack-events.ts +101 -0
  276. package/src/http/status.ts +25 -7
  277. package/src/http/task-requester.ts +46 -0
  278. package/src/http/tasks.ts +64 -37
  279. package/src/http/users.ts +14 -0
  280. package/src/http/webhooks.ts +15 -0
  281. package/src/integrations/cards/index.ts +151 -0
  282. package/src/integrations/chat-sdk/outbound.ts +39 -13
  283. package/src/integrations/chat-sdk/runtime.ts +7 -1
  284. package/src/integrations/chat-sdk/status.ts +17 -0
  285. package/src/integrations/chat-sdk/telegram-api.ts +6 -1
  286. package/src/kv-reserved-namespaces.ts +17 -2
  287. package/src/oauth/presets.ts +29 -2
  288. package/src/prompts/base-prompt.ts +17 -4
  289. package/src/prompts/session-templates.ts +83 -6
  290. package/src/providers/acp-targets.ts +1 -1
  291. package/src/providers/amp-adapter.ts +1 -1
  292. package/src/providers/claude-managed-adapter.ts +5 -1
  293. package/src/providers/codex-adapter.ts +1 -1
  294. package/src/providers/codex-app-server.ts +2 -11
  295. package/src/providers/opencode-adapter.ts +7 -19
  296. package/src/providers/runtime-dependencies.ts +158 -0
  297. package/src/rbac/legacy-policy.ts +2 -0
  298. package/src/rbac/permissions.ts +10 -1
  299. package/src/scripts-runtime/credential-broker/default-bindings.ts +19 -11
  300. package/src/scripts-runtime/credential-broker/index.ts +1 -1
  301. package/src/scripts-runtime/egress-secrets.ts +2 -2
  302. package/src/scripts-runtime/swarm-sdk.ts +3 -2
  303. package/src/scripts-runtime/types/stdlib.d.ts +11 -4
  304. package/src/scripts-runtime/types/swarm-extension.d.ts +1 -1
  305. package/src/scripts-runtime/types/swarm-sdk.d.ts +11 -4
  306. package/src/server.ts +4 -4
  307. package/src/slack/app.ts +87 -46
  308. package/src/slack/assistant.ts +33 -7
  309. package/src/slack/handlers.ts +6 -4
  310. package/src/slack/http-receiver.ts +284 -0
  311. package/src/slack/inbound-dispatch.ts +43 -7
  312. package/src/slack/inbound-files.ts +33 -14
  313. package/src/slack/message-text.ts +47 -4
  314. package/src/slack/render-v2.ts +2 -1
  315. package/src/slack/socket-ack.ts +17 -10
  316. package/src/slack/steering.ts +5 -0
  317. package/src/slack/thread-buffer-store.ts +58 -0
  318. package/src/slack/thread-buffer.ts +341 -57
  319. package/src/tasks/context-key.ts +24 -0
  320. package/src/tasks/sibling-awareness.ts +13 -1
  321. package/src/tests/agent-fs-live-url.test.ts +15 -0
  322. package/src/tests/agent-fs-provision-seeder.test.ts +140 -0
  323. package/src/tests/agent-fs-user-keys.test.ts +483 -0
  324. package/src/tests/agentfs-proxy.test.ts +8 -8
  325. package/src/tests/approval-card-resolution.test.ts +396 -0
  326. package/src/tests/approval-requests-notifications.test.ts +1 -1
  327. package/src/tests/approval-respond-auth.test.ts +28 -0
  328. package/src/tests/apps-action-parent-task.test.ts +140 -0
  329. package/src/tests/apps-catalog-additions.test.ts +315 -0
  330. package/src/tests/apps-catalog-files.test.ts +114 -0
  331. package/src/tests/apps-catalog-hitl.test.ts +117 -0
  332. package/src/tests/apps-catalog-inputs.test.ts +86 -0
  333. package/src/tests/apps-catalog-table.test.ts +47 -0
  334. package/src/tests/apps-chart-shell.test.ts +1 -1
  335. package/src/tests/apps-element-assembly.test.ts +52 -3
  336. package/src/tests/apps-session-thread.test.ts +182 -0
  337. package/src/tests/asset-key-invariants.test.ts +14 -0
  338. package/src/tests/base-prompt.test.ts +107 -23
  339. package/src/tests/boot-scrub-sweep.test.ts +172 -0
  340. package/src/tests/caller-session-group.test.ts +199 -0
  341. package/src/tests/cards.test.ts +169 -0
  342. package/src/tests/chat-sdk-status-route.test.ts +16 -3
  343. package/src/tests/chat-sdk-telegram-token.test.ts +76 -0
  344. package/src/tests/chat-sdk-tools.test.ts +147 -0
  345. package/src/tests/checklist-nudge.test.ts +208 -0
  346. package/src/tests/checklist.test.ts +686 -0
  347. package/src/tests/codex-app-server.test.ts +16 -0
  348. package/src/tests/comb-config-guard.test.ts +21 -0
  349. package/src/tests/comb-default.test.ts +59 -97
  350. package/src/tests/comb-links.test.ts +86 -16
  351. package/src/tests/comb-status.test.ts +24 -27
  352. package/src/tests/create-page-tool.test.ts +101 -1
  353. package/src/tests/create-schedule-key.test.ts +105 -0
  354. package/src/tests/credential-broker.test.ts +2 -2
  355. package/src/tests/db-query.test.ts +87 -1
  356. package/src/tests/db-task-read-contract.test.ts +1 -0
  357. package/src/tests/db-task-write-contract.test.ts +2 -1
  358. package/src/tests/docs-index-footprint.test.js +3 -3
  359. package/src/tests/entrypoint-github-enterprise.test.ts +158 -0
  360. package/src/tests/extensions-assets.test.ts +7 -3
  361. package/src/tests/extensions-catalog.test.ts +1 -0
  362. package/src/tests/extensions-example-sql-admin-only.test.ts +198 -0
  363. package/src/tests/extensions-pre-task.test.ts +3 -3
  364. package/src/tests/extensions-steering.test.ts +14 -2
  365. package/src/tests/favorites-agent-fs-path.test.ts +124 -0
  366. package/src/tests/fetch-resolved-env.test.ts +68 -0
  367. package/src/tests/fixtures/import-package.ts +32 -0
  368. package/src/tests/fixtures/runner-missing-dependency.ts +129 -0
  369. package/src/tests/fs-routes.test.ts +505 -2
  370. package/src/tests/github-ghes-mock.test.ts +196 -0
  371. package/src/tests/github-host.test.ts +285 -0
  372. package/src/tests/heartbeat-supersede-resume.test.ts +73 -0
  373. package/src/tests/heartbeat.test.ts +56 -0
  374. package/src/tests/import-config.test.ts +209 -0
  375. package/src/tests/import.test.ts +464 -0
  376. package/src/tests/invites-http.test.ts +144 -1
  377. package/src/tests/kv-http.test.ts +11 -0
  378. package/src/tests/literal-matcher.test.ts +58 -0
  379. package/src/tests/mcp-oauth-manual-client.test.ts +1 -1
  380. package/src/tests/oauth-presets.test.ts +12 -0
  381. package/src/tests/pool-affinity.test.ts +50 -0
  382. package/src/tests/prompt-template-session.test.ts +52 -5
  383. package/src/tests/provider-registration.test.ts +2 -55
  384. package/src/tests/provider-runtime-dependencies.test.ts +212 -0
  385. package/src/tests/rbac-admission.test.ts +19 -0
  386. package/src/tests/rbac-charact-misc-tools.test.ts +31 -0
  387. package/src/tests/rbac-engine.test.ts +2 -0
  388. package/src/tests/rbac-roles.test.ts +2 -0
  389. package/src/tests/runner-missing-dependency.test.ts +61 -0
  390. package/src/tests/runtime-pool-reachability.test.ts +135 -1
  391. package/src/tests/runtime-pool-routing.test.ts +52 -0
  392. package/src/tests/runtime-stale-threshold.test.ts +40 -0
  393. package/src/tests/savings-fleet-slices.test.ts +122 -0
  394. package/src/tests/savings-read.test.ts +41 -0
  395. package/src/tests/savings-scripts.test.ts +9 -3
  396. package/src/tests/script-connections.test.ts +2 -0
  397. package/src/tests/script-executor-conformance.test.ts +41 -4
  398. package/src/tests/secret-scrub-gate.test.ts +257 -0
  399. package/src/tests/seed-registry.test.ts +142 -9
  400. package/src/tests/session-source-keys.test.ts +42 -1
  401. package/src/tests/sessions-move.test.ts +70 -0
  402. package/src/tests/sessions-tree.test.ts +98 -0
  403. package/src/tests/sessions.test.ts +69 -0
  404. package/src/tests/slack-config.test.ts +4 -18
  405. package/src/tests/slack-http-receiver.test.ts +472 -0
  406. package/src/tests/slack-inbound-logging.test.ts +64 -0
  407. package/src/tests/slack-leave-thread.test.ts +1 -1
  408. package/src/tests/slack-message-text.test.ts +104 -0
  409. package/src/tests/slack-mode-lifecycle.test.ts +6 -4
  410. package/src/tests/slack-render-v2.test.ts +48 -0
  411. package/src/tests/slack-skip-reaction.test.ts +2 -2
  412. package/src/tests/slack-steering.test.ts +22 -10
  413. package/src/tests/slack-thread-buffer-context.test.ts +1 -1
  414. package/src/tests/slack-thread-buffer-fold.test.ts +417 -0
  415. package/src/tests/slack-thread-buffer-restore.test.ts +198 -0
  416. package/src/tests/slack-thread-buffer-startup-restore.test.ts +86 -0
  417. package/src/tests/slack-thread-buffer.test.ts +34 -34
  418. package/src/tests/slack-thread-participants.test.ts +23 -5
  419. package/src/tests/slack-tool-blocks.test.ts +167 -0
  420. package/src/tests/status.test.ts +32 -6
  421. package/src/tests/steering-core.test.ts +13 -0
  422. package/src/tests/steering-enabled.test.ts +7 -1
  423. package/src/tests/steering-promotion.test.ts +24 -0
  424. package/src/tests/swarm-config-reserved-keys.test.ts +17 -0
  425. package/src/tests/system-one-hosts-ui-mirror.test.ts +67 -0
  426. package/src/tests/task-artifacts.test.ts +50 -0
  427. package/src/tests/task-session-prompts.test.ts +95 -1
  428. package/src/tests/workflow-system-one-extraction.test.ts +149 -1
  429. package/src/tools/chat-post.ts +19 -4
  430. package/src/tools/chat-reply.ts +20 -4
  431. package/src/tools/create-page.ts +21 -4
  432. package/src/tools/get-swarm.ts +18 -2
  433. package/src/tools/join-swarm.ts +2 -1
  434. package/src/tools/kv/kv-write-auth.ts +17 -1
  435. package/src/tools/schedules/create-schedule.ts +22 -4
  436. package/src/tools/slack-post.ts +40 -7
  437. package/src/tools/slack-reply.ts +50 -14
  438. package/src/types.ts +43 -2
  439. package/src/utils/constants.ts +60 -138
  440. package/src/utils/github-host.ts +217 -0
  441. package/src/utils/github-pull-request.ts +8 -5
  442. package/src/utils/literal-matcher.ts +118 -0
  443. package/src/utils/secret-scrubber.ts +331 -25
  444. package/src/utils/task-attachment-links.ts +9 -12
  445. package/src/vcs/index.ts +3 -0
  446. package/src/workflows/approval-notifications.ts +188 -12
  447. package/src/workflows/executors/system-one-extraction.ts +14 -7
  448. package/src/workflows/executors/system-one-providers.ts +22 -1
  449. package/templates/community/open-prompt-showreel/PLAYBOOK.md +1 -1
  450. package/templates/community/open-prompt-showreel/skills/open-prompt-showreel/SKILL.md +1 -1
  451. package/templates/extensions/README.md +1 -0
  452. package/templates/extensions/sql-admin-only/README.md +19 -0
  453. package/templates/extensions/sql-admin-only/hooks.ts +96 -0
  454. package/templates/extensions/sql-admin-only/manifest.json +8 -0
  455. package/templates/import/manifest.schema.json +136 -0
  456. package/templates/import/sources.schema.json +44 -0
  457. package/templates/skills/agent-browser/SKILL.md +1 -1
  458. package/templates/skills/agent-browser/content.md +1 -1
  459. package/templates/skills/apps/SKILL.md +122 -12
  460. package/templates/skills/apps/content.md +122 -12
  461. package/templates/skills/asset-namespaces/content.md +2 -1
  462. package/templates/skills/chat-sdk/content.md +17 -0
  463. package/templates/skills/db-query-guidance/content.md +2 -1
  464. package/templates/skills/scheduling/content.md +27 -0
  465. package/templates/skills/slack-interaction/content.md +12 -2
  466. package/templates/skills/swarm-docs/content.md +1 -0
  467. package/templates/skills/swarm-extensions/config.json +1 -1
  468. package/templates/skills/swarm-extensions/content.md +33 -23
  469. package/templates/skills/swarm-scripts/SKILL.md +13 -0
  470. package/templates/skills/swarm-scripts/content.md +13 -0
  471. package/templates/skills/work-on-task/SKILL.md +1 -1
  472. package/templates/skills/work-on-task/content.md +1 -1
  473. package/templates/skills/workflow-iterate/content.md +4 -7
  474. package/templates/workflows/dreaming/content.md +2 -2
  475. package/dist/acp-adapter-xq6s2z6t.js +0 -14
  476. package/dist/claude-adapter-r33pqnzx.js +0 -24
  477. package/dist/cli-dns0y538.js +0 -194
  478. package/dist/fx-adapter-1rnxnf56.js +0 -17
  479. package/dist/grok-adapter-efhmf1r8.js +0 -17
  480. package/dist/handlers-anrr3py9.js +0 -32
  481. package/dist/index-8w2aznds.js +0 -33
  482. package/dist/index-qnjvr362.js +0 -37
  483. package/dist/index-yzxd3sn9.js +0 -32
  484. package/dist/lead-zhxqbfdv.js +0 -69
  485. package/dist/worker-7j2907g6.js +0 -69
  486. package/src/tests/entrypoint-acp-target-binary.test.ts +0 -439
  487. package/dist/{cli-4caa1x7d.js → cli-tsa40663.js} +4 -4
  488. package/dist/{index-0rvk3vd4.js → index-bs7gw5fd.js} +3 -3
  489. package/dist/{mistral-conversations-a45tx39a.js → mistral-conversations-0c30em7t.js} +4 -4
  490. package/dist/{openai-completions-xd579js7.js → openai-completions-f3n69rep.js} +18 -18
  491. package/dist/{pi-messages-hjbv8v10.js → pi-messages-zebyt7gb.js} +5 -5
@@ -13,8 +13,11 @@ import {
13
13
  workflowContextKey,
14
14
  agentContextKey,
15
15
  pageContextKey,
16
+ APP_SESSION_KEY_PATTERN,
17
+ appSessionContextKey,
16
18
  init_context_key,
17
19
  sessionSourceKey,
20
+ sourceOfKey,
18
21
  init_source_key,
19
22
  checkSlackRoutingCoherence,
20
23
  init_slack_routing,
@@ -99,9 +102,60 @@ import {
99
102
  updateAgentStatusFromCapacity2,
100
103
  buildRoutingAffinityFromAgent2,
101
104
  isAgentEligibleForTask2,
102
- computeContentHash2,
103
- getContextVersion2,
104
- getContextVersionHistory2,
105
+ getWorkflowRunTriggeredByAgentId,
106
+ getWorkflowRunSummary,
107
+ getWorkflowRunStepsSlimByRunId,
108
+ getRunLineageBlock,
109
+ getWorkflowRunStatus,
110
+ disarmWorkflowTreeRetries,
111
+ getRunningSubWorkflowSteps,
112
+ getSettledChildRunParentSteps,
113
+ init_workflow_runs,
114
+ LEARNING_TTL_DAYS,
115
+ LEARNING_DUPLICATE_MIN_SIMILARITY,
116
+ CANDIDATE_SET_MULTIPLIER,
117
+ isGraphExpansionEnabled,
118
+ init_constants2,
119
+ LONGTERM_ROOT,
120
+ LEARNINGS_ROOT,
121
+ MEMORY_KEY_PATTERN,
122
+ MEMORY_KEY_PATTERN_MESSAGE,
123
+ MEMORY_KEY_MAX_LENGTH,
124
+ isLongtermKey,
125
+ longtermKeyError,
126
+ isConsolidatedKey,
127
+ consolidatedKeyMessage,
128
+ resolveStoreKey,
129
+ init_key_paths,
130
+ computeScore,
131
+ rerank,
132
+ init_reranker,
133
+ searchMemoryCandidates,
134
+ init_search_candidates,
135
+ rowToCandidate,
136
+ init_sqlite_store,
137
+ getEmbeddingProvider2,
138
+ getMemoryStore2,
139
+ init_memory,
140
+ embedScript2,
141
+ init_embeddings,
142
+ upsertScriptByName,
143
+ getScript,
144
+ getScriptById,
145
+ getScriptVersion,
146
+ deleteScript,
147
+ touchScratchScriptLastUsed,
148
+ restoreScratchScriptLastUsedIfUnchanged,
149
+ init_db3,
150
+ getOAuthApp,
151
+ getOAuthAppById,
152
+ getOAuthAppIdByProvider,
153
+ createOAuthApp,
154
+ upsertOAuthApp,
155
+ listAuthorizationsForApp,
156
+ getAuthorizationById,
157
+ getOAuthTokens,
158
+ init_oauth,
105
159
  taskModelPin,
106
160
  init_model_pin,
107
161
  upsertModelCatalogOverlay,
@@ -110,6 +164,7 @@ import {
110
164
  init_model_validation2,
111
165
  checkProfileForAgent,
112
166
  init_model_profile_check,
167
+ rowToAgentTask,
113
168
  getTaskById2,
114
169
  hasNonTerminalRerouteDecisionChild2,
115
170
  getAgentCurrentTask2,
@@ -143,68 +198,21 @@ import {
143
198
  taskProfileError,
144
199
  scheduleProfileUpdate,
145
200
  init_model_profiles,
146
- onTaskStarted,
147
- init_task_lifecycle_events,
148
- getOAuthApp,
149
- getOAuthAppById,
150
- getOAuthAppIdByProvider,
151
- createOAuthApp,
152
- upsertOAuthApp,
153
- listAuthorizationsForApp,
154
- getAuthorizationById,
155
- getOAuthTokens,
156
- init_oauth,
157
- LEARNING_TTL_DAYS,
158
- LEARNING_DUPLICATE_MIN_SIMILARITY,
159
- CANDIDATE_SET_MULTIPLIER,
160
- isGraphExpansionEnabled,
161
- init_constants2,
162
- LONGTERM_ROOT,
163
- LEARNINGS_ROOT,
164
- MEMORY_KEY_PATTERN,
165
- MEMORY_KEY_PATTERN_MESSAGE,
166
- MEMORY_KEY_MAX_LENGTH,
167
- isLongtermKey,
168
- longtermKeyError,
169
- isConsolidatedKey,
170
- consolidatedKeyMessage,
171
- resolveStoreKey,
172
- init_key_paths,
173
- computeScore,
174
- rerank,
175
- init_reranker,
176
- searchMemoryCandidates,
177
- init_search_candidates,
178
- rowToCandidate,
179
- init_sqlite_store,
180
- getEmbeddingProvider2,
181
- getMemoryStore2,
182
- init_memory,
183
- embedScript2,
184
- init_embeddings,
185
- upsertScriptByName,
186
- getScript,
187
- getScriptById,
188
- getScriptVersion,
189
- deleteScript,
190
- touchScratchScriptLastUsed,
191
- restoreScratchScriptLastUsedIfUnchanged,
192
- init_db3,
193
- getWorkflowRunTriggeredByAgentId,
194
- getWorkflowRunSummary,
195
- getWorkflowRunStepsSlimByRunId,
196
- getRunLineageBlock,
197
- getWorkflowRunStatus,
198
- disarmWorkflowTreeRetries,
199
- getRunningSubWorkflowSteps,
200
- getSettledChildRunParentSteps,
201
- init_workflow_runs,
202
201
  SteeringRequestError,
203
202
  SteeringBlockedError,
204
203
  isSteeringEnabled,
205
204
  carryUnhandledSteering,
206
205
  requestSteering,
207
206
  init_steering2,
207
+ computeContentHash2,
208
+ getContextVersion2,
209
+ getContextVersionHistory2,
210
+ AssetKeyMovesBlockedError2,
211
+ assertAssetKeyMovesAllowed2,
212
+ moveSessionChains,
213
+ init_session_moves,
214
+ onTaskStarted,
215
+ init_task_lifecycle_events,
208
216
  getPendingTaskForAgent2,
209
217
  startTask2,
210
218
  updateTaskClaudeSessionId2,
@@ -357,6 +365,7 @@ import {
357
365
  createUser2,
358
366
  updateUser2,
359
367
  deleteUser2,
368
+ getRootTaskChain2,
360
369
  getBudget2,
361
370
  getDailySpendForAgent2,
362
371
  getDailySpendGlobal2,
@@ -376,27 +385,27 @@ import {
376
385
  recordInlineScriptRun2,
377
386
  exports_db,
378
387
  init_db4
379
- } from "./cli-h9yy18gy.js";
388
+ } from "./cli-ymct0ycy.js";
380
389
  import {
381
390
  assertMayActOnOperatorGrantedTarget2,
382
391
  getUserGrant2,
383
392
  init_rbac_roles
384
- } from "./cli-n5t077me.js";
393
+ } from "./cli-k7pt28ad.js";
385
394
  import {
386
395
  ensurePricingSeeded2,
387
396
  ensureRbacSeeded2,
388
397
  ensureModelProfilesSeeded2,
389
398
  init_boot_seeds
390
- } from "./cli-k2rw11py.js";
399
+ } from "./cli-7831nhaw.js";
391
400
  import {
392
401
  requestModelCatalogRefresh2,
393
402
  startPricingRefreshLoop2,
394
403
  init_pricing_refresh
395
- } from "./cli-0vksaxvr.js";
404
+ } from "./cli-kqh27v2y.js";
396
405
  import {
397
406
  workflowEventBus2,
398
407
  init_event_bus
399
- } from "./cli-emekyyhr.js";
408
+ } from "./cli-q2d3e1k1.js";
400
409
  import {
401
410
  slackCode,
402
411
  slackMissingScopeMessage,
@@ -405,7 +414,7 @@ import {
405
414
  externalChannelToolError2,
406
415
  getChannelBlockReason2,
407
416
  init_external_channel
408
- } from "./cli-zeaehgyd.js";
417
+ } from "./cli-q8cfh1t9.js";
409
418
  import {
410
419
  noteSlackInboundSideEffect,
411
420
  init_inbound_dispatch,
@@ -444,7 +453,28 @@ import {
444
453
  startSlackApp2,
445
454
  stopSlackAppUnderLifecycleLock2,
446
455
  init_app3
447
- } from "./cli-mwwmka77.js";
456
+ } from "./cli-2tnbc3gw.js";
457
+ import {
458
+ AGENT_MAX_TASKS_CONFIG_KEY,
459
+ resetAgentMaxTasksMirror,
460
+ upsertSwarmConfigWithPolicyMirror,
461
+ runtimeStaleThresholdMinutes,
462
+ getRuntimeInstanceById,
463
+ markRuntimeTerminated,
464
+ touchRuntimeInstance,
465
+ markRuntimeInstanceOffline,
466
+ reconcileAgentStatusFromRuntimes,
467
+ listRuntimeInstancesForPool,
468
+ init_multi_runtime,
469
+ ConfigQuestionSettingsSchema,
470
+ normalizeApprovalQuestions,
471
+ init_approval_config_question,
472
+ resolveSlackConversationId,
473
+ init_dm,
474
+ postApprovalCancellationUpdates2,
475
+ createApprovalFollowUpTask2,
476
+ init_approval_notifications
477
+ } from "./cli-w7dxb2fj.js";
448
478
  import {
449
479
  shapeApprovalResolution,
450
480
  init_approval_resolution,
@@ -468,7 +498,7 @@ import {
468
498
  resumeFromChildRun2,
469
499
  initWaitBusSubscriptions2,
470
500
  init_resume
471
- } from "./cli-sdvcrq5x.js";
501
+ } from "./cli-9a2rtd77.js";
472
502
  import {
473
503
  FilesError,
474
504
  providerPath,
@@ -482,11 +512,11 @@ import {
482
512
  import {
483
513
  tableToAscii2,
484
514
  init_dist4
485
- } from "./cli-x6t50dmw.js";
515
+ } from "./cli-wr1h0k28.js";
486
516
  import {
487
517
  getRuntimePool2,
488
518
  init_db2
489
- } from "./cli-rjvsf9qa.js";
519
+ } from "./cli-h474mvp5.js";
490
520
  import {
491
521
  duplicateGuardedQueryKey,
492
522
  parseQueryParams,
@@ -500,7 +530,10 @@ import {
500
530
  getSessionRoot,
501
531
  sessionAccessForRoot,
502
532
  init_session_shares,
533
+ resolveCallerTask,
534
+ resolveTaskGroupKey,
503
535
  resolveTaskAuditUserId,
536
+ resolveHttpAuditUserId,
504
537
  init_audit_user,
505
538
  resolveHttpFavoriteOwner,
506
539
  init_favorite_owner,
@@ -519,13 +552,13 @@ import {
519
552
  findRoute,
520
553
  route,
521
554
  init_route_def
522
- } from "./cli-sg27rk2t.js";
555
+ } from "./cli-fnh4b12r.js";
523
556
  import {
524
557
  COMPOSIO_HTTP_METHODS,
525
558
  executeComposioRequest,
526
559
  composioArgsFromParts,
527
560
  init_composio
528
- } from "./cli-pe4d96rb.js";
561
+ } from "./cli-7zm3b3f5.js";
529
562
  import {
530
563
  object,
531
564
  init_v4_mini
@@ -544,7 +577,7 @@ import {
544
577
  init_llm
545
578
  } from "./cli-2xv18ywz.js";
546
579
  import {
547
- require_dist2,
580
+ require_dist,
548
581
  ConnectionAuthInputSchema,
549
582
  listRelationalCredentialBindings,
550
583
  upsertCredentialBinding,
@@ -621,7 +654,7 @@ import {
621
654
  init_typecheck,
622
655
  parseSkillContent,
623
656
  init_skill_parser
624
- } from "./cli-z8cvws4c.js";
657
+ } from "./cli-7fx9jyfs.js";
625
658
  import {
626
659
  detachedProcessGroup,
627
660
  registerProcessGroup,
@@ -636,10 +669,24 @@ import {
636
669
  ensureToken,
637
670
  ensureTokenOrThrow,
638
671
  init_ensure_token
639
- } from "./cli-s8p8hhty.js";
672
+ } from "./cli-1tvdx9t5.js";
640
673
  import {
641
674
  require_fast_deep_equal
642
675
  } from "./cli-bhp11egn.js";
676
+ import {
677
+ ZodFirstPartyTypeKind,
678
+ objectType,
679
+ init_v3
680
+ } from "./cli-ytyvpye5.js";
681
+ import {
682
+ init_v4
683
+ } from "./cli-3kd08rej.js";
684
+ import {
685
+ SLACK_LEAVE_THREAD_DISABLE,
686
+ isSlackLeaveThreadDisabled,
687
+ leaveSlackThread,
688
+ init_left_threads
689
+ } from "./cli-25nstr34.js";
643
690
  import {
644
691
  notifyAutomationPreflightFailure,
645
692
  init_automation_preflight_alert,
@@ -652,23 +699,6 @@ import {
652
699
  init_automation_preflight,
653
700
  BaseExecutor,
654
701
  init_base,
655
- AGENT_MAX_TASKS_CONFIG_KEY,
656
- resetAgentMaxTasksMirror,
657
- upsertSwarmConfigWithPolicyMirror,
658
- getRuntimeInstanceById,
659
- markRuntimeTerminated,
660
- touchRuntimeInstance,
661
- markRuntimeInstanceOffline,
662
- reconcileAgentStatusFromRuntimes,
663
- init_multi_runtime,
664
- ConfigQuestionSettingsSchema,
665
- normalizeApprovalQuestions,
666
- init_approval_config_question,
667
- resolveSlackConversationId,
668
- init_dm,
669
- postApprovalCancellationUpdates,
670
- createApprovalFollowUpTask,
671
- init_approval_notifications,
672
702
  HumanInTheLoopExecutor,
673
703
  init_human_in_the_loop,
674
704
  resolveWorkflowLlmConfig,
@@ -731,36 +761,26 @@ import {
731
761
  validateDefinition,
732
762
  applyDefinitionPatch,
733
763
  init_definition2
734
- } from "./cli-c3ng0mb4.js";
764
+ } from "./cli-svc803vq.js";
735
765
  import {
736
766
  isMultiRuntimeEnabled,
737
767
  init_multi_runtime2
738
768
  } from "./cli-mdb054w3.js";
739
769
  import {
740
- ZodFirstPartyTypeKind,
741
- objectType,
742
- init_v3
743
- } from "./cli-ytyvpye5.js";
744
- import {
745
- init_v4
746
- } from "./cli-3kd08rej.js";
770
+ require_dist2
771
+ } from "./cli-xf1wn5ns.js";
747
772
  import {
748
- require_dist3
749
- } from "./cli-k28wkapa.js";
773
+ getApiKey,
774
+ init_api_key
775
+ } from "./cli-pax9q4ff.js";
750
776
  import {
751
- SLACK_LEAVE_THREAD_DISABLE,
752
- isSlackLeaveThreadDisabled,
753
- leaveSlackThread,
754
- init_left_threads
755
- } from "./cli-s7zz734a.js";
777
+ canProvisionKind,
778
+ init_runtime_providers
779
+ } from "./cli-5kcmxwxv.js";
756
780
  import {
757
781
  publicEndpointSsrfOptions,
758
782
  init_mcp_wrapper
759
- } from "./cli-qmqt520k.js";
760
- import {
761
- canProvisionKind,
762
- init_runtime_providers
763
- } from "./cli-t5ys4ebm.js";
783
+ } from "./cli-dd37e0cm.js";
764
784
  import {
765
785
  findUserById,
766
786
  findUserByExternalId,
@@ -775,10 +795,12 @@ import {
775
795
  resolveSessionToken,
776
796
  fingerprintApiKey,
777
797
  init_users
778
- } from "./cli-c71n3bxq.js";
798
+ } from "./cli-pwsax0vp.js";
779
799
  import {
780
800
  normalizeAssetKey,
801
+ defaultAssetKey,
781
802
  SESSION_RESOURCE_KINDS,
803
+ isGroupKey,
782
804
  sessionResourceGroupOf,
783
805
  sessionGroupKey,
784
806
  parseAssetKey,
@@ -843,8 +865,15 @@ import {
843
865
  KvValueTypeSchema,
844
866
  KvNamespaceSchema,
845
867
  KvKeySchema,
846
- init_types4
847
- } from "./cli-qps8je6j.js";
868
+ init_types5
869
+ } from "./cli-me4maa4j.js";
870
+ import {
871
+ resolveGitHubHost,
872
+ getGitHubLinkConfig,
873
+ getGitHubGraphqlUrl,
874
+ githubApiUrl,
875
+ init_github_host
876
+ } from "./cli-9ttx00s3.js";
848
877
  import {
849
878
  generateDefaultClaudeMd2,
850
879
  generateDefaultSoulMd2,
@@ -855,7 +884,7 @@ import {
855
884
  init_task_attachment_links,
856
885
  contentSha256,
857
886
  init_profile_sync
858
- } from "./cli-am1ptset.js";
887
+ } from "./cli-aa8s22gn.js";
859
888
  import {
860
889
  getSlackConfiguration,
861
890
  isSlackConfigured,
@@ -868,7 +897,7 @@ import {
868
897
  import {
869
898
  selectCredential,
870
899
  init_credentials2
871
- } from "./cli-t4dv07kr.js";
900
+ } from "./cli-pn1v1pb0.js";
872
901
  import {
873
902
  findInterpolationTokens,
874
903
  interpolate,
@@ -878,7 +907,7 @@ import {
878
907
  init_registry3,
879
908
  resolveTemplate,
880
909
  init_resolver
881
- } from "./cli-0bcgyj5b.js";
910
+ } from "./cli-812paz57.js";
882
911
  import {
883
912
  init_zod
884
913
  } from "./cli-zcfpsfzf.js";
@@ -895,6 +924,7 @@ import {
895
924
  unknown,
896
925
  array2,
897
926
  object2,
927
+ strictObject2,
898
928
  looseObject,
899
929
  union3,
900
930
  discriminatedUnion,
@@ -904,20 +934,13 @@ import {
904
934
  literal2,
905
935
  ZodOptional,
906
936
  optional2,
937
+ lazy,
907
938
  custom,
908
939
  preprocess,
909
940
  ZodIssueCode,
910
941
  datetime,
911
942
  number3
912
943
  } from "./cli-hg42n3hx.js";
913
- import {
914
- init_package,
915
- package_default
916
- } from "./cli-922z7gwm.js";
917
- import {
918
- realtimeBus,
919
- init_bus
920
- } from "./cli-syfdvhkc.js";
921
944
  import {
922
945
  MAX_PROFILE_FILE_LENGTH,
923
946
  getConfiguredAppUrls,
@@ -930,21 +953,25 @@ import {
930
953
  getCombState,
931
954
  isAgentFsProxyEnabled,
932
955
  init_constants3
933
- } from "./cli-dns0y538.js";
956
+ } from "./cli-dqgnbnxs.js";
934
957
  import {
935
958
  parseEnvFlag,
936
959
  isEnvFlagEnabled,
937
960
  init_env_flag
938
961
  } from "./cli-cebvbc9t.js";
962
+ import {
963
+ init_package,
964
+ package_default
965
+ } from "./cli-kaa4bd7x.js";
939
966
  import {
940
967
  getNodeEnv,
941
968
  isDevOrTestNodeEnv,
942
969
  init_node_env
943
970
  } from "./cli-rgeadyvq.js";
944
971
  import {
945
- getApiKey,
946
- init_api_key
947
- } from "./cli-pax9q4ff.js";
972
+ realtimeBus,
973
+ init_bus
974
+ } from "./cli-syfdvhkc.js";
948
975
  import {
949
976
  openAICompatibleProviderIds,
950
977
  init_src2,
@@ -955,7 +982,7 @@ import {
955
982
  registerVolatileSecret,
956
983
  registerSensitiveKeyName,
957
984
  init_secret_scrubber
958
- } from "./cli-f1kwb5fc.js";
985
+ } from "./cli-5a6pqy45.js";
959
986
  import {
960
987
  __toESM,
961
988
  __commonJS,
@@ -10702,7 +10729,7 @@ var require_limit = __commonJS(function(exports) {
10702
10729
  });
10703
10730
 
10704
10731
  // node_modules/ajv-formats/dist/index.js
10705
- var require_dist = __commonJS(function(exports, module) {
10732
+ var require_dist3 = __commonJS(function(exports, module) {
10706
10733
  Object.defineProperty(exports, "__esModule", { value: true });
10707
10734
  var formats_1 = require_formats();
10708
10735
  var limit_1 = require_limit();
@@ -10780,7 +10807,7 @@ class AjvJsonSchemaValidator {
10780
10807
  var import_ajv, import_ajv_formats;
10781
10808
  var init_ajv_provider = __esm(() => {
10782
10809
  import_ajv = __toESM(require_ajv(), 1);
10783
- import_ajv_formats = __toESM(require_dist(), 1);
10810
+ import_ajv_formats = __toESM(require_dist3(), 1);
10784
10811
  });
10785
10812
 
10786
10813
  // node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/server.js
@@ -12132,6 +12159,14 @@ function initGitHub() {
12132
12159
  console.log("[GitHub] Disabled via GITHUB_DISABLE");
12133
12160
  return false;
12134
12161
  }
12162
+ const host = resolveGitHubHost();
12163
+ if (!host.ok) {
12164
+ console.error(`[GitHub] ${host.error}; GitHub integration disabled`);
12165
+ return false;
12166
+ }
12167
+ if (host.warning)
12168
+ console.warn(`[GitHub] ${host.warning}`);
12169
+ console.log(`[GitHub] Host: web ${host.config.webUrl}, API ${host.config.apiUrl}`);
12135
12170
  webhookSecret = process.env.GITHUB_WEBHOOK_SECRET ?? null;
12136
12171
  if (!webhookSecret) {
12137
12172
  console.log("[GitHub] Missing GITHUB_WEBHOOK_SECRET, GitHub integration disabled");
@@ -12226,7 +12261,7 @@ async function getInstallationToken(installationId) {
12226
12261
  return null;
12227
12262
  }
12228
12263
  try {
12229
- const response = await fetch(`https://api.github.com/app/installations/${installationId}/access_tokens`, {
12264
+ const response = await fetch(githubApiUrl(`/app/installations/${installationId}/access_tokens`), {
12230
12265
  method: "POST",
12231
12266
  headers: {
12232
12267
  Accept: "application/vnd.github+json",
@@ -12252,6 +12287,7 @@ async function getInstallationToken(installationId) {
12252
12287
  var initialized = false, webhookSecret = null, appId = null, privateKey = null, tokenCache;
12253
12288
  var init_app4 = __esm(() => {
12254
12289
  init_env_flag();
12290
+ init_github_host();
12255
12291
  tokenCache = new Map;
12256
12292
  });
12257
12293
 
@@ -12274,7 +12310,7 @@ async function postRestReaction(repo, target, reaction, installationId, label) {
12274
12310
  if (!token)
12275
12311
  return false;
12276
12312
  try {
12277
- const response = await fetch(`https://api.github.com/repos/${repo}/${target}/reactions`, {
12313
+ const response = await fetch(githubApiUrl(`/repos/${repo}/${target}/reactions`), {
12278
12314
  method: "POST",
12279
12315
  headers: {
12280
12316
  Accept: "application/vnd.github+json",
@@ -12310,7 +12346,7 @@ async function addGraphQLReaction(nodeId, reaction, installationId) {
12310
12346
  if (!token)
12311
12347
  return false;
12312
12348
  try {
12313
- const response = await fetch("https://api.github.com/graphql", {
12349
+ const response = await fetch(getGitHubGraphqlUrl(), {
12314
12350
  method: "POST",
12315
12351
  headers: {
12316
12352
  Authorization: `Bearer ${token}`,
@@ -12345,6 +12381,7 @@ async function addGraphQLReaction(nodeId, reaction, installationId) {
12345
12381
  }
12346
12382
  }
12347
12383
  var init_reactions = __esm(() => {
12384
+ init_github_host();
12348
12385
  init_secret_scrubber();
12349
12386
  init_app4();
12350
12387
  });
@@ -19352,8 +19389,8 @@ var require_HttpErrors = __commonJS(function(exports) {
19352
19389
  var require_webhook = __commonJS(function(exports) {
19353
19390
  Object.defineProperty(exports, "__esModule", { value: true });
19354
19391
  exports.Webhook = exports.WebhookVerificationError = undefined;
19355
- var standardwebhooks_1 = require_dist3();
19356
- var standardwebhooks_2 = require_dist3();
19392
+ var standardwebhooks_1 = require_dist2();
19393
+ var standardwebhooks_2 = require_dist2();
19357
19394
  Object.defineProperty(exports, "WebhookVerificationError", { enumerable: true, get: function() {
19358
19395
  return standardwebhooks_2.WebhookVerificationError;
19359
19396
  } });
@@ -19894,7 +19931,7 @@ ${issues.join(`
19894
19931
  return parsed.data;
19895
19932
  }
19896
19933
  var init_manifest_format = __esm(() => {
19897
- init_types4();
19934
+ init_types5();
19898
19935
  });
19899
19936
 
19900
19937
  // src/workflows/recovery.ts
@@ -20303,7 +20340,7 @@ function startRetryPoller(registry, intervalMs = 5000) {
20303
20340
  if (!waiting)
20304
20341
  continue;
20305
20342
  if (result.waitFor === "workflow.child.finished") {
20306
- const { resumeFromChildRun } = await import("./resume-w1s1eh5v.js");
20343
+ const { resumeFromChildRun } = await import("./resume-v7kjewt9.js");
20307
20344
  await resumeFromChildRun(step.id, registry);
20308
20345
  }
20309
20346
  } else {
@@ -20775,7 +20812,7 @@ var init_wait_poller = __esm(() => {
20775
20812
 
20776
20813
  // src/tasks/errors.ts
20777
20814
  var TaskCreationBlockedError;
20778
- var init_errors2 = __esm(() => {
20815
+ var init_errors = __esm(() => {
20779
20816
  TaskCreationBlockedError = class TaskCreationBlockedError extends Error {
20780
20817
  reason;
20781
20818
  extension;
@@ -20796,8 +20833,8 @@ var init_agent_task = __esm(() => {
20796
20833
  init_model_validation2();
20797
20834
  init_apply_task_create();
20798
20835
  init_context_key();
20799
- init_errors2();
20800
- init_types4();
20836
+ init_errors();
20837
+ init_types5();
20801
20838
  init_base();
20802
20839
  AgentTaskConfigSchema = object2({
20803
20840
  template: string2(),
@@ -21049,7 +21086,7 @@ var init_notify = __esm(() => {
21049
21086
  }
21050
21087
  }
21051
21088
  case "slack": {
21052
- const { getSlackApp } = await import("./app-mkptw0k7.js");
21089
+ const { getSlackApp } = await import("./app-17d12ev4.js");
21053
21090
  let app = getSlackApp();
21054
21091
  if (!app) {
21055
21092
  if (!isSlackConfigured()) {
@@ -21192,7 +21229,7 @@ async function executeRawLlm(config) {
21192
21229
  });
21193
21230
  const model = provider(llmConfig.model);
21194
21231
  if (config.schema) {
21195
- const { generateObject, jsonSchema } = await import("./index-0rvk3vd4.js");
21232
+ const { generateObject, jsonSchema } = await import("./index-bs7gw5fd.js");
21196
21233
  const { object } = await generateObject({
21197
21234
  model,
21198
21235
  schema: jsonSchema(config.schema),
@@ -21206,7 +21243,7 @@ async function executeRawLlm(config) {
21206
21243
  output: { result: object, model: modelName }
21207
21244
  };
21208
21245
  }
21209
- const { generateText } = await import("./index-0rvk3vd4.js");
21246
+ const { generateText } = await import("./index-bs7gw5fd.js");
21210
21247
  const { text } = await generateText({
21211
21248
  model,
21212
21249
  prompt: config.prompt
@@ -21767,7 +21804,7 @@ var init_validate2 = __esm(() => {
21767
21804
  const outputStr = typeof targetOutput === "string" ? targetOutput : JSON.stringify(targetOutput);
21768
21805
  try {
21769
21806
  const { createOpenAI } = await import("./index-m5gx1xd6.js");
21770
- const { generateObject, jsonSchema } = await import("./index-0rvk3vd4.js");
21807
+ const { generateObject, jsonSchema } = await import("./index-bs7gw5fd.js");
21771
21808
  const llmConfig = await resolveWorkflowLlmConfig();
21772
21809
  const provider = createOpenAI({
21773
21810
  baseURL: llmConfig.baseURL,
@@ -22686,7 +22723,7 @@ var init_scheduler = __esm(() => {
22686
22723
  init_deferred_task_waits();
22687
22724
  init_schedule_task();
22688
22725
  init_schedule_task();
22689
- import_cron_parser = __toESM(require_dist2(), 1);
22726
+ import_cron_parser = __toESM(require_dist(), 1);
22690
22727
  DEFERRED_REAP_INTERVAL_MS = 60 * 60 * 1000;
22691
22728
  AutomationNeedsSetupError = class AutomationNeedsSetupError extends Error {
22692
22729
  failureReason;
@@ -22762,7 +22799,7 @@ function liveWorkflowSpec(workflow) {
22762
22799
  triggerSchema: workflow.triggerSchema ?? null
22763
22800
  };
22764
22801
  }
22765
- function skillSpecOf(content, parsed) {
22802
+ function skillSpecOf(content, parsed, hasFiles) {
22766
22803
  return {
22767
22804
  name: parsed.name,
22768
22805
  description: parsed.description,
@@ -22781,7 +22818,7 @@ function skillSpecOf(content, parsed) {
22781
22818
  sourcePath: null,
22782
22819
  sourceBranch: "main",
22783
22820
  sourceHash: null,
22784
- isComplex: false
22821
+ isComplex: hasFiles
22785
22822
  };
22786
22823
  }
22787
22824
  function liveSkillSpec(skill) {
@@ -22917,7 +22954,7 @@ async function preflightAssets(manifest, files) {
22917
22954
  path: path.slice(filesPrefix.length),
22918
22955
  content: fileContent
22919
22956
  })).sort((a, b) => a.path.localeCompare(b.path));
22920
- const spec = skillSpecOf(content, parsed);
22957
+ const spec = skillSpecOf(content, parsed, skillFiles.length > 0);
22921
22958
  skills.push({
22922
22959
  kind: "skill",
22923
22960
  name: parsed.name,
@@ -24473,7 +24510,7 @@ function setPreloadedTools(server, names) {
24473
24510
  async function applyPreToolCall(name, args, requestInfo, inputSchema) {
24474
24511
  if (requestInfo.callOrigin !== "mcp")
24475
24512
  return { args };
24476
- const dispatcher = await import("./dispatcher-9tq2zzdj.js");
24513
+ const dispatcher = await import("./dispatcher-jrm24r43.js");
24477
24514
  const result = await dispatcher.dispatchPre("pre.tool.call", { tool: name, args, requestInfo }, inputSchema ? {
24478
24515
  validateModify: async (data) => {
24479
24516
  const schema = normalizeObjectSchema(inputSchema) ?? inputSchema;
@@ -24725,7 +24762,7 @@ var init_utils = __esm(() => {
24725
24762
  init_otel();
24726
24763
  init_color_literals();
24727
24764
  init_types3();
24728
- init_types4();
24765
+ init_types5();
24729
24766
  init_secret_scrubber();
24730
24767
  scriptSdkRequestOrigins = new WeakSet;
24731
24768
  extensionRequestOrigins = new WeakSet;
@@ -25666,7 +25703,7 @@ async function bridgeFetch(url, init, { repeatSafe, readOnly }, signal) {
25666
25703
  }
25667
25704
  const delay = backoffMs(attempt, BRIDGE_MIN_DELAY_MS, BRIDGE_MAX_DELAY_MS);
25668
25705
  const aborted = signal?.aborted || error instanceof Error && error.name === "AbortError";
25669
- if (aborted || !repeatSafe || attempt > BRIDGE_MAX_RETRIES || !fits(delay))
25706
+ if (aborted || !repeatSafe || attempt > BRIDGE_MAX_RETRIES || readOnly && !fits(delay))
25670
25707
  throw error;
25671
25708
  previous = { error };
25672
25709
  await sleep2(delay, signal);
@@ -25678,7 +25715,7 @@ async function bridgeFetch(url, init, { repeatSafe, readOnly }, signal) {
25678
25715
  if (!retryable || attempt > BRIDGE_MAX_RETRIES || signal?.aborted)
25679
25716
  return res;
25680
25717
  const delay = (res.status === 429 ? retryAfterMs(res.headers.get("retry-after")) : undefined) ?? backoffMs(attempt, BRIDGE_MIN_DELAY_MS, BRIDGE_MAX_DELAY_MS);
25681
- if (!fits(delay))
25718
+ if ((readOnly || res.status === 429) && !fits(delay))
25682
25719
  return res;
25683
25720
  await res.body?.cancel().catch(() => {});
25684
25721
  previous = { response: res };
@@ -25979,7 +26016,7 @@ var EXTENSIONS_TMP_PARENT, EXTENSIONS_TMP_ROOT, ExtensionConfigError, successful
25979
26016
  var init_loader = __esm(() => {
25980
26017
  init_db();
25981
26018
  init_native();
25982
- init_types4();
26019
+ init_types5();
25983
26020
  init_secret_scrubber();
25984
26021
  init_bundle_path();
25985
26022
  EXTENSIONS_TMP_PARENT = `${tmpdir()}/swarm-extensions`;
@@ -26565,7 +26602,7 @@ var init_lifecycle = __esm(() => {
26565
26602
  init_db4();
26566
26603
  init_assets();
26567
26604
  init_db();
26568
- init_types4();
26605
+ init_types5();
26569
26606
  init_secret_scrubber();
26570
26607
  init_dispatcher();
26571
26608
  init_identity2();
@@ -27188,7 +27225,7 @@ async function applyPreTaskCreate(args) {
27188
27225
  var MODIFIABLE_OPTION_KEYS, MODIFIABLE_OPTION_KEY_SET;
27189
27226
  var init_apply_task_create = __esm(() => {
27190
27227
  init_model_validation2();
27191
- init_types4();
27228
+ init_types5();
27192
27229
  init_secret_scrubber();
27193
27230
  init_event_bus();
27194
27231
  init_dispatcher();
@@ -27328,6 +27365,14 @@ var init_sibling_block = __esm(() => {
27328
27365
  });
27329
27366
 
27330
27367
  // src/tasks/sibling-awareness.ts
27368
+ function withoutThreadContext(description) {
27369
+ if (!description.startsWith("<thread_context>"))
27370
+ return description;
27371
+ const close = `
27372
+ </thread_context>`;
27373
+ const end = description.indexOf(close);
27374
+ return end === -1 ? description : description.slice(end + close.length).trimStart();
27375
+ }
27331
27376
  async function toSiblingTaskInfo(task) {
27332
27377
  const agent = task.agentId ? await getAgentById2(task.agentId) : null;
27333
27378
  return {
@@ -27335,7 +27380,7 @@ async function toSiblingTaskInfo(task) {
27335
27380
  status: task.status,
27336
27381
  agentId: task.agentId,
27337
27382
  agentName: agent?.name ?? null,
27338
- description: stripSiblingBlock(task.task),
27383
+ description: withoutThreadContext(stripSiblingBlock(task.task)),
27339
27384
  updatedAt: task.lastUpdatedAt,
27340
27385
  createdAt: task.createdAt
27341
27386
  };
@@ -27396,7 +27441,7 @@ async function createTaskWithSiblingAwareness(description, options, args = {}) {
27396
27441
  var init_sibling_awareness = __esm(() => {
27397
27442
  init_db4();
27398
27443
  init_apply_task_create();
27399
- init_errors2();
27444
+ init_errors();
27400
27445
  init_sibling_block();
27401
27446
  });
27402
27447
 
@@ -29117,7 +29162,7 @@ var init_boards_sync = __esm(() => {
29117
29162
  init_resolver();
29118
29163
  init_context_key();
29119
29164
  init_sibling_awareness();
29120
- init_types4();
29165
+ init_types5();
29121
29166
  init_event_bus();
29122
29167
  init_api();
29123
29168
  init_auth3();
@@ -31025,7 +31070,7 @@ async function fetchPaginatedReviewComments(initialUrl, headers) {
31025
31070
  }
31026
31071
  }
31027
31072
  async function fetchReviewScopedComments(repo, prNumber, reviewId, headers) {
31028
- const url = `https://api.github.com/repos/${repo}/pulls/${prNumber}/reviews/${reviewId}/comments?per_page=100`;
31073
+ const url = githubApiUrl(`/repos/${repo}/pulls/${prNumber}/reviews/${reviewId}/comments?per_page=100`);
31029
31074
  let result = await fetchPaginatedReviewComments(url, headers);
31030
31075
  if (result.degraded || result.comments.length > 0) {
31031
31076
  return result;
@@ -31040,7 +31085,7 @@ async function fetchReviewScopedComments(repo, prNumber, reviewId, headers) {
31040
31085
  return result;
31041
31086
  }
31042
31087
  async function fetchPrLevelReviewComments(repo, prNumber, reviewId, headers) {
31043
- const url = `https://api.github.com/repos/${repo}/pulls/${prNumber}/comments?per_page=100`;
31088
+ const url = githubApiUrl(`/repos/${repo}/pulls/${prNumber}/comments?per_page=100`);
31044
31089
  const result = await fetchPaginatedReviewComments(url, headers);
31045
31090
  return {
31046
31091
  comments: result.comments.filter((comment) => comment.pull_request_review_id === reviewId),
@@ -31124,7 +31169,7 @@ async function fetchPrReviewActionCounts(repo, prNumber, installationId) {
31124
31169
  if (!token || !owner || !name)
31125
31170
  return null;
31126
31171
  try {
31127
- const response = await fetch("https://api.github.com/graphql", {
31172
+ const response = await fetch(getGitHubGraphqlUrl(), {
31128
31173
  method: "POST",
31129
31174
  headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json" },
31130
31175
  body: JSON.stringify({
@@ -31278,6 +31323,7 @@ var init_handlers4 = __esm(() => {
31278
31323
  init_context_key();
31279
31324
  init_sibling_awareness();
31280
31325
  init_env_flag();
31326
+ init_github_host();
31281
31327
  init_app4();
31282
31328
  init_mentions();
31283
31329
  init_task_reactions();
@@ -32212,7 +32258,7 @@ async function loadAdapter(name, config, logger) {
32212
32258
  const base = { ...config, apiUrl, logger };
32213
32259
  switch (name) {
32214
32260
  case "telegram": {
32215
- const { TelegramAdapter } = await import("./index-gjwaqaq8.js");
32261
+ const { TelegramAdapter } = await import("./index-cret47a5.js");
32216
32262
 
32217
32263
  class SwarmTelegramAdapter extends TelegramAdapter {
32218
32264
  isBotMentioned(message, text) {
@@ -32226,7 +32272,7 @@ async function loadAdapter(name, config, logger) {
32226
32272
  });
32227
32273
  }
32228
32274
  case "slack": {
32229
- const { createSlackAdapter } = await import("./index-2skqtd76.js");
32275
+ const { createSlackAdapter } = await import("./index-b24j7t2m.js");
32230
32276
  return createSlackAdapter({
32231
32277
  ...base,
32232
32278
  signingSecret: config.signingSecret ?? "",
@@ -32236,7 +32282,7 @@ async function loadAdapter(name, config, logger) {
32236
32282
  });
32237
32283
  }
32238
32284
  case "discord": {
32239
- const { createDiscordAdapter } = await import("./index-d6wkh8ar.js");
32285
+ const { createDiscordAdapter } = await import("./index-1f0vypbg.js");
32240
32286
  return createDiscordAdapter({
32241
32287
  ...base,
32242
32288
  logger: withInfoFilter(logger, keepDiscordInfoLine),
@@ -32245,7 +32291,7 @@ async function loadAdapter(name, config, logger) {
32245
32291
  });
32246
32292
  }
32247
32293
  case "teams": {
32248
- const { createTeamsAdapter } = await import("./index-khe3gp0k.js");
32294
+ const { createTeamsAdapter } = await import("./index-4b1q8kan.js");
32249
32295
  const { teamsWebhookVerifier, teamsToken } = getChatSdkTestHooks();
32250
32296
  return createTeamsAdapter({
32251
32297
  ...base,
@@ -32454,7 +32500,7 @@ async function readPersistedThreadHistory(threadId) {
32454
32500
  const rows = await new SqliteChatState().getList(`${SDK_THREAD_HISTORY_PREFIX}${threadId}`);
32455
32501
  if (rows.length === 0)
32456
32502
  return [];
32457
- const { Message: MessageClass } = await import("./index-hjhfk3ra.js");
32503
+ const { Message: MessageClass } = await import("./index-585gyczt.js");
32458
32504
  return rows.map((row) => MessageClass.fromJSON(row));
32459
32505
  }
32460
32506
  var SDK_THREAD_HISTORY_PREFIX = "msg-history:";
@@ -32481,7 +32527,7 @@ async function callTelegramBotApi(baseUrl, token, method, body) {
32481
32527
  const payload = await response.json().catch(() => null);
32482
32528
  if (!response.ok || !payload?.ok) {
32483
32529
  const description = payload?.description ?? `HTTP ${response.status}`;
32484
- throw new TelegramBotApiError(`Telegram ${method} failed: ${scrubSecrets(description.replaceAll(token, "[REDACTED]"))}`);
32530
+ throw new TelegramBotApiError(`Telegram ${method} failed: ${scrubSecrets(description.replaceAll(token, "[REDACTED]"))}`, response.status);
32485
32531
  }
32486
32532
  return payload.result;
32487
32533
  }
@@ -32490,8 +32536,10 @@ var init_telegram_api = __esm(() => {
32490
32536
  init_secret_scrubber();
32491
32537
  init_logger();
32492
32538
  TelegramBotApiError = class TelegramBotApiError extends Error {
32493
- constructor(message) {
32539
+ status;
32540
+ constructor(message, status) {
32494
32541
  super(message);
32542
+ this.status = status;
32495
32543
  this.name = "TelegramBotApiError";
32496
32544
  }
32497
32545
  };
@@ -33611,12 +33659,16 @@ function escapeTelegramHashLines(markdown) {
33611
33659
  }).join(`
33612
33660
  `);
33613
33661
  }
33614
- async function postChunks(adapter, target, parts, replyFirst) {
33662
+ async function postChunks(adapter, target, parts, replyFirst, card) {
33615
33663
  const messageIds = [];
33616
33664
  let threadId;
33617
33665
  const limit = chatMessageLimit(adapter);
33618
- for (const chunk of parts.flatMap((part) => splitChatMessage(part, limit))) {
33619
- const message = { markdown: adapter === "telegram" ? escapeTelegramHashLines(chunk) : chunk };
33666
+ const messages = parts.flatMap((part) => splitChatMessage(part, limit)).map((chunk) => ({
33667
+ markdown: adapter === "telegram" ? escapeTelegramHashLines(chunk) : chunk
33668
+ }));
33669
+ if (card)
33670
+ messages.push(card);
33671
+ for (const message of messages) {
33620
33672
  const sent = replyFirst && messageIds.length === 0 ? await replyFirst(message) : await target.post(message);
33621
33673
  messageIds.push(sent.id);
33622
33674
  threadId ??= sent.threadId;
@@ -33742,22 +33794,26 @@ function formatUnsentFilesNote(unsent) {
33742
33794
  return [`Could not send ${count}:`, ...lines].join(`
33743
33795
  `);
33744
33796
  }
33797
+ function scrubCard(card) {
33798
+ return JSON.parse(JSON.stringify(card, (_key, value) => typeof value === "string" ? scrubSecrets(value) : value));
33799
+ }
33745
33800
  async function postChatMessage(args) {
33746
33801
  assertTrustedChatTarget(args.threadId ?? args.channelId ?? "");
33747
33802
  const chat = getChatInstance(args.adapter);
33748
33803
  if (!chat)
33749
33804
  throw new ChatAdapterUnavailableError(args.adapter);
33750
33805
  const parts = (typeof args.text === "string" ? [args.text] : args.text).map(scrubSecrets);
33806
+ const card = args.card && scrubCard(args.card);
33751
33807
  const text = parts.join(`
33752
33808
 
33753
- `);
33809
+ `) || (card?.title ?? "");
33754
33810
  let result;
33755
33811
  let target;
33756
33812
  if (args.threadId) {
33757
33813
  const thread = chat.thread(args.threadId);
33758
33814
  target = thread;
33759
33815
  const replyTo = args.replyToMessageId;
33760
- const sent = await postChunks(args.adapter, thread, parts, replyTo && thread.adapter.reply ? (message) => thread.reply(replyTo, message) : undefined);
33816
+ const sent = await postChunks(args.adapter, thread, parts, replyTo && thread.adapter.reply ? (message) => thread.reply(replyTo, message) : undefined, card);
33761
33817
  result = {
33762
33818
  adapter: args.adapter,
33763
33819
  threadId: thread.id,
@@ -33768,7 +33824,7 @@ async function postChatMessage(args) {
33768
33824
  } else if (args.channelId) {
33769
33825
  const channel = chat.channel(args.channelId);
33770
33826
  target = channel;
33771
- const sent = await postChunks(args.adapter, channel, parts);
33827
+ const sent = await postChunks(args.adapter, channel, parts, undefined, card);
33772
33828
  result = {
33773
33829
  adapter: args.adapter,
33774
33830
  threadId: sent.threadId ?? channel.id,
@@ -33826,6 +33882,47 @@ var init_outbound2 = __esm(() => {
33826
33882
  NON_HEADING_HASH = /^( {0,3}(?:>[ \t]?)*[ \t]*(?:(?:[-*+]|\d{1,9}[.)])[ \t]+(?:\[[ xX]\][ \t]+)?)?)(#{7,}|#{1,6}(?=[^\s#]))/;
33827
33883
  });
33828
33884
 
33885
+ // src/be/runtime-pools/demand.ts
33886
+ async function pendingWorkForAgent(agentId) {
33887
+ const rows = await getDbClient2().query(`SELECT * FROM agent_tasks WHERE (agentId = ? AND status = 'pending')
33888
+ OR (offeredTo = ? AND status = 'offered') ORDER BY priority DESC, createdAt, rowid`, [agentId, agentId]);
33889
+ const tasks = [];
33890
+ for (const row of rows) {
33891
+ const task = rowToAgentTask(row);
33892
+ if (task.status === "offered" || (await checkDependencies2(task.id)).ready)
33893
+ tasks.push(task);
33894
+ }
33895
+ const mentions = await getDbClient2().get(`SELECT COUNT(DISTINCT m.channelId) AS count FROM channel_messages m
33896
+ JOIN channels c ON c.id = m.channelId
33897
+ LEFT JOIN channel_read_state s ON s.channelId = m.channelId AND s.agentId = ?
33898
+ WHERE m.mentions LIKE ? AND s.processing_since IS NULL
33899
+ AND (s.lastReadAt IS NULL OR m.createdAt > s.lastReadAt)`, [agentId, `%"${agentId}"%`]);
33900
+ return { work: tasks.length + (mentions?.count ?? 0), topTask: tasks[0] ?? null };
33901
+ }
33902
+ function agentRuntimeLimit(maxTasks, slotsPerRuntime) {
33903
+ return Math.floor(maxTasks / slotsPerRuntime);
33904
+ }
33905
+ function countPoolRuntimes(runtimes, now, staleMinutes) {
33906
+ return runtimes.filter((r) => r.status === "provisioning" || r.status === "active" && Date.parse(r.lastSeenAt) >= now.getTime() - staleMinutes * 60000).length;
33907
+ }
33908
+ function computeDesired(pool, agents) {
33909
+ const desired = new Map;
33910
+ let remaining = Math.max(0, (pool.maxRuntimes ?? Infinity) - agents.reduce((n, a) => n + a.current, 0));
33911
+ for (const agent of agents) {
33912
+ const uncovered = Math.max(0, agent.work - agent.freeSlots - agent.provisioning * pool.slotsPerRuntime);
33913
+ const limit = agentRuntimeLimit(agent.maxTasks, pool.slotsPerRuntime);
33914
+ const count = Math.min(limit, Math.max(pool.minRuntimes, agent.current + Math.ceil(uncovered / pool.slotsPerRuntime)));
33915
+ const added = Math.min(remaining, Math.max(0, count - agent.current));
33916
+ desired.set(agent.agentId, Math.min(count, agent.current + added));
33917
+ remaining -= added;
33918
+ }
33919
+ return desired;
33920
+ }
33921
+ var init_demand = __esm(() => {
33922
+ init_db4();
33923
+ init_read();
33924
+ });
33925
+
33829
33926
  // src/be/runtime-pools/reachability.ts
33830
33927
  function isRuntimePoolWakeable(pool, now = new Date) {
33831
33928
  if (!pool.enabled || pool.circuitOpenUntil && Date.parse(pool.circuitOpenUntil) > now.getTime())
@@ -33845,11 +33942,36 @@ async function isAgentReachable(agent) {
33845
33942
  return await getDbClient2().get(`SELECT id FROM runtime_instances WHERE agent_id = ? AND pool_id = ?
33846
33943
  AND status = 'provisioning' AND draining = 0 LIMIT 1`, [agent.id, pool.id]) !== null;
33847
33944
  }
33945
+ async function isAgentOnDemand(agent, now = new Date) {
33946
+ if (agent.status !== "offline" || !agent.runtimePoolId)
33947
+ return false;
33948
+ if (!isRuntimePoolsEnabled() || !isMultiRuntimeEnabled())
33949
+ return false;
33950
+ const pool = await getRuntimePool2(agent.runtimePoolId);
33951
+ if (!pool?.enabled)
33952
+ return false;
33953
+ const runtimes = await listRuntimeInstancesForPool(pool.id);
33954
+ const own = runtimes.filter((r) => r.agentId === agent.id);
33955
+ if (own.some((r) => r.status === "provisioning" && !r.draining))
33956
+ return true;
33957
+ if (!isRuntimePoolWakeable(pool, now))
33958
+ return false;
33959
+ const staleMinutes = runtimeStaleThresholdMinutes();
33960
+ const limit = agentRuntimeLimit(agent.maxTasks ?? 1, pool.slotsPerRuntime);
33961
+ if (countPoolRuntimes(own, now, staleMinutes) >= limit)
33962
+ return false;
33963
+ if (pool.maxRuntimes === null)
33964
+ return true;
33965
+ return countPoolRuntimes(runtimes, now, staleMinutes) < pool.maxRuntimes;
33966
+ }
33848
33967
  var init_reachability = __esm(() => {
33849
33968
  init_runtime_providers();
33969
+ init_multi_runtime2();
33850
33970
  init_runtime_pools_flag();
33851
33971
  init_db4();
33972
+ init_multi_runtime();
33852
33973
  init_db2();
33974
+ init_demand();
33853
33975
  });
33854
33976
 
33855
33977
  // src/integrations/chat-sdk/router.ts
@@ -34567,7 +34689,7 @@ var init_inbound = __esm(() => {
34567
34689
  init_dispatcher();
34568
34690
  init_resolver();
34569
34691
  init_context_key();
34570
- init_errors2();
34692
+ init_errors();
34571
34693
  init_secret_scrubber();
34572
34694
  init_workflows();
34573
34695
  init_event_bus();
@@ -34965,6 +35087,9 @@ async function startAdapter(name, config, state, ChatClass) {
34965
35087
  try {
34966
35088
  await registerTelegramCommands(config);
34967
35089
  } catch (error) {
35090
+ if (error instanceof TelegramBotApiError && error.status === 401) {
35091
+ throw new Error(`Telegram rejected the bot token: ${errorMessage(error)}`);
35092
+ }
34968
35093
  logger.warn(`Could not register the Telegram commands: ${errorMessage(error)}`);
34969
35094
  }
34970
35095
  }
@@ -34999,7 +35124,7 @@ async function startChatSdk() {
34999
35124
  for (const [name, reason] of Object.entries(config.incomplete ?? {})) {
35000
35125
  console.warn(`[chat-sdk] ${name} not started, incomplete: ${scrubSecrets(reason)}`);
35001
35126
  }
35002
- const { Chat: ChatClass } = await import("./index-hjhfk3ra.js");
35127
+ const { Chat: ChatClass } = await import("./index-585gyczt.js");
35003
35128
  const state = new SqliteChatState;
35004
35129
  startChatRelayWatcher();
35005
35130
  await Promise.all(CHAT_SDK_ADAPTER_NAMES.map(async (name) => {
@@ -35105,6 +35230,7 @@ var init_runtime = __esm(() => {
35105
35230
  init_logger();
35106
35231
  init_relay();
35107
35232
  init_state();
35233
+ init_telegram_api();
35108
35234
  init_test_hooks();
35109
35235
  init_thread_buffer();
35110
35236
  init_typing();
@@ -35880,7 +36006,7 @@ var init_sync2 = __esm(() => {
35880
36006
  init_resolver();
35881
36007
  init_context_key();
35882
36008
  init_sibling_awareness();
35883
- init_types4();
36009
+ init_types5();
35884
36010
  init_adf();
35885
36011
  init_metadata();
35886
36012
  init_templates10();
@@ -35906,7 +36032,7 @@ async function notifySlack(text) {
35906
36032
  return;
35907
36033
  }
35908
36034
  try {
35909
- const { getSlackApp } = await import("./app-mkptw0k7.js");
36035
+ const { getSlackApp } = await import("./app-17d12ev4.js");
35910
36036
  const app = getSlackApp();
35911
36037
  if (!app) {
35912
36038
  console.warn("[Jira webhook keepalive] Slack not available, cannot send notification");
@@ -35977,7 +36103,7 @@ async function deleteJiraWebhook(webhookId) {
35977
36103
  console.log(`[Jira webhook keepalive] Deleted webhook id=${webhookId}`);
35978
36104
  }
35979
36105
  async function overwriteWebhookIds(next) {
35980
- const { getDbClient } = await import("./db-y4wfrzbm.js");
36106
+ const { getDbClient } = await import("./db-dg2gc7fd.js");
35981
36107
  await getDbClient().transaction(async (tx) => {
35982
36108
  const row = await tx.get("SELECT metadata FROM oauth_apps WHERE provider = 'jira'");
35983
36109
  if (!row) {
@@ -108473,7 +108599,7 @@ var init_sync = __esm(() => {
108473
108599
  init_resolver();
108474
108600
  init_context_key();
108475
108601
  init_sibling_awareness();
108476
- init_types4();
108602
+ init_types5();
108477
108603
  init_gate();
108478
108604
  init_templates11();
108479
108605
  taskSessionMap = new Map;
@@ -109472,7 +109598,7 @@ async function reloadGlobalConfigsAndIntegrations() {
109472
109598
  return runWithoutRequestAuth(() => runSlackLifecycleExclusive(() => reloadGlobalConfigsAndIntegrationsInner()));
109473
109599
  }
109474
109600
  async function reloadGlobalConfigsAndIntegrationsInner() {
109475
- const { getEmbeddingProvider, resetEmbeddingProvider } = await import("./index-csgrxedz.js");
109601
+ const { getEmbeddingProvider, resetEmbeddingProvider } = await import("./index-fn054vsf.js");
109476
109602
  const wasEmbeddingsConfigured = getEmbeddingProvider().isConfigured();
109477
109603
  const updated = await loadGlobalConfigsIntoEnv(true);
109478
109604
  await syncTelemetryEnabled("settings").catch((err) => {
@@ -109488,7 +109614,7 @@ async function reloadGlobalConfigsAndIntegrationsInner() {
109488
109614
  integrations.push("embeddings");
109489
109615
  }
109490
109616
  if (isEmbeddingsConfigured) {
109491
- import("./embedding-space-wh8de1t9.js").then(({ runEmbeddingMaintenance }) => runEmbeddingMaintenance({ backfill: !wasEmbeddingsConfigured })).catch((err) => {
109617
+ import("./embedding-space-bafjr5f7.js").then(({ runEmbeddingMaintenance }) => runEmbeddingMaintenance({ backfill: !wasEmbeddingsConfigured })).catch((err) => {
109492
109618
  console.error("[config-reload] embedding maintenance failed (non-fatal):", err);
109493
109619
  });
109494
109620
  }
@@ -110996,7 +111122,7 @@ var init_sync3 = __esm(() => {
110996
111122
  init_script_connections();
110997
111123
  init_db3();
110998
111124
  init_run_saved();
110999
- init_types4();
111125
+ init_types5();
111000
111126
  init_secret_scrubber();
111001
111127
  init_definition();
111002
111128
  init_row_store();
@@ -111041,6 +111167,9 @@ async function runAppAction({
111041
111167
  name,
111042
111168
  input = {},
111043
111169
  parentTaskId,
111170
+ followUp,
111171
+ requestedByUserId,
111172
+ contextKey,
111044
111173
  caller,
111045
111174
  actor
111046
111175
  }) {
@@ -111127,8 +111256,10 @@ async function runAppAction({
111127
111256
  routingReason: action.agentId ? "human_pinned" : lead ? "skill" : undefined,
111128
111257
  routingSource: action.agentId || lead ? "engine_default" : undefined,
111129
111258
  key: normalizeAssetKey(`shared/app:${app.id}/action:${name}/`),
111130
- ...actor.startsWith("user:") ? { requestedByUserId: actor.slice("user:".length) } : {},
111131
- ...parentTaskId ? { parentTaskId } : {}
111259
+ requestedByUserId: requestedByUserId ?? (actor.startsWith("user:") ? actor.slice("user:".length) : undefined),
111260
+ ...parentTaskId ? { parentTaskId } : {},
111261
+ followUpConfig: followUp === false ? { disabled: true } : undefined,
111262
+ contextKey
111132
111263
  }, { origin: "app" });
111133
111264
  return {
111134
111265
  status: 200,
@@ -112391,6 +112522,28 @@ var init_request_principal = __esm(() => {
112391
112522
  init_utils2();
112392
112523
  });
112393
112524
 
112525
+ // src/http/task-requester.ts
112526
+ async function resolveTaskRequester(req, myAgentId, bodyUserId, trustedUserId) {
112527
+ const trusted = trustedUserId === undefined ? await resolveHttpAuditUserId(req, myAgentId) : trustedUserId;
112528
+ if (trusted)
112529
+ return trusted;
112530
+ if (process.env.TRUST_BODY_REQUESTED_BY_USER_ID === "false" || !bodyUserId)
112531
+ return;
112532
+ const mayAssign = can({
112533
+ principal: await agentFirstPrincipal(req, myAgentId),
112534
+ verb: "task.requester.assign",
112535
+ resource: { kind: "none" },
112536
+ source: "http"
112537
+ }).allow;
112538
+ return mayAssign ? (await findUserById(bodyUserId))?.id : undefined;
112539
+ }
112540
+ var init_task_requester = __esm(() => {
112541
+ init_audit_user();
112542
+ init_users();
112543
+ init_rbac();
112544
+ init_request_principal();
112545
+ });
112546
+
112394
112547
  // src/http/apps.ts
112395
112548
  async function authorizeAppCaller(req, res, myAgentId, verb, resource) {
112396
112549
  const auth = getRequestAuth(req);
@@ -112928,9 +113081,9 @@ async function handleApps(req, res, pathSegments, queryParams, myAgentId) {
112928
113081
  }
112929
113082
  if (definitionNeedsRepair(res, app))
112930
113083
  return true;
113084
+ const actions = app.definition.actions;
113085
+ const action = actions && Object.hasOwn(actions, parsed.params.name) ? actions[parsed.params.name] : undefined;
112931
113086
  if (parsed.body.parentTaskId) {
112932
- const actions = app.definition.actions;
112933
- const action = actions && Object.hasOwn(actions, parsed.params.name) ? actions[parsed.params.name] : undefined;
112934
113087
  if (action && action.kind !== "task") {
112935
113088
  jsonError(res, "parentTaskId is only supported for task-kind actions", 400);
112936
113089
  return true;
@@ -112946,11 +113099,34 @@ async function handleApps(req, res, pathSegments, queryParams, myAgentId) {
112946
113099
  return true;
112947
113100
  }
112948
113101
  }
113102
+ const requestedByUserId = action?.kind === "task" ? await resolveTaskRequester(req, myAgentId, parsed.body.requestedByUserId) : undefined;
113103
+ let contextKey;
113104
+ const session = parsed.body.session;
113105
+ if (session && action?.kind === "task") {
113106
+ if (session.scope === "shared") {
113107
+ jsonError(res, 'session scope "shared" is not supported yet', 400);
113108
+ return true;
113109
+ }
113110
+ if (!requestedByUserId) {
113111
+ jsonError(res, "A user-scoped session needs a requesting user: sign in or pick an identity", 400);
113112
+ return true;
113113
+ }
113114
+ if (!parsed.body.parentTaskId) {
113115
+ contextKey = appSessionContextKey({
113116
+ appId: app.id,
113117
+ sessionKey: session.key,
113118
+ userId: requestedByUserId
113119
+ });
113120
+ }
113121
+ }
112949
113122
  const output = await runAppAction({
112950
113123
  app,
112951
113124
  name: parsed.params.name,
112952
113125
  input: parsed.body.input,
112953
113126
  parentTaskId: parsed.body.parentTaskId,
113127
+ followUp: parsed.body.followUp,
113128
+ requestedByUserId,
113129
+ contextKey,
112954
113130
  caller,
112955
113131
  actor
112956
113132
  });
@@ -113296,13 +113472,15 @@ var init_apps = __esm(() => {
113296
113472
  init_version4();
113297
113473
  init_db4();
113298
113474
  init_rbac();
113299
- init_types4();
113475
+ init_context_key();
113476
+ init_types5();
113300
113477
  init_request_auth_context();
113301
113478
  init_secret_scrubber();
113302
113479
  init_favorite_owner();
113303
113480
  init_request_principal();
113304
113481
  init_route_def();
113305
113482
  init_session_access();
113483
+ init_task_requester();
113306
113484
  init_utils2();
113307
113485
  MAX_APP_BODY_BYTES = 5 * 1024 * 1024;
113308
113486
  MAX_APP_ROW_BODY_BYTES = 1 * 1024 * 1024;
@@ -113764,7 +113942,13 @@ var init_apps = __esm(() => {
113764
113942
  params: object2({ id: string2().min(1), name: AppNameSchema }),
113765
113943
  body: object2({
113766
113944
  input: record2(string2(), unknown()).optional(),
113767
- parentTaskId: string2().min(1).optional()
113945
+ parentTaskId: string2().min(1).optional(),
113946
+ followUp: boolean().optional(),
113947
+ requestedByUserId: string2().min(1).optional(),
113948
+ session: object2({
113949
+ key: string2().regex(APP_SESSION_KEY_PATTERN),
113950
+ scope: _enum2(["user", "shared"]).optional()
113951
+ }).optional()
113768
113952
  }),
113769
113953
  responses: {
113770
113954
  200: { description: "Action invoked", schema: runActionResultSchema },
@@ -114707,7 +114891,7 @@ async function cancelApprovalRequestAndRun(id, data) {
114707
114891
  });
114708
114892
  if (!timedOut)
114709
114893
  return null;
114710
- await createApprovalFollowUpTask(timedOut, "hitl.timeout");
114894
+ await createApprovalFollowUpTask2(timedOut, "hitl.timeout");
114711
114895
  return { timedOut };
114712
114896
  }
114713
114897
  const request = await cancelApprovalRequestById2(id, {
@@ -114729,7 +114913,7 @@ async function cancelApprovalRequestAndRun(id, data) {
114729
114913
  }
114730
114914
  const slackReason = data.slackReason ?? data.reason;
114731
114915
  client.afterCommit(async () => {
114732
- await postApprovalCancellationUpdates([request], slackReason);
114916
+ await postApprovalCancellationUpdates2([request], slackReason);
114733
114917
  if (runCancelled) {
114734
114918
  await postTreeApprovalCancellations2(treeRunIds, data.reason, {
114735
114919
  exceptRequestId: request.id
@@ -114863,7 +115047,7 @@ var init_get_task_details = __esm(() => {
114863
115047
  init_db4();
114864
115048
  init_task_tool_ctx();
114865
115049
  init_utils();
114866
- init_types4();
115050
+ init_types5();
114867
115051
  init_requester_comms();
114868
115052
  getTaskDetailsInputSchema = object2({
114869
115053
  taskId: uuid().describe("The ID of the task to get details for.")
@@ -115211,17 +115395,1998 @@ var init_chat_open_dm = __esm(() => {
115211
115395
  init_utils();
115212
115396
  });
115213
115397
 
115398
+ // node_modules/@json-render/chat/node_modules/@json-render/core/dist/chunk-FVP4K5MD.mjs
115399
+ function unescapeJsonPointer(token) {
115400
+ return token.replace(/~1/g, "/").replace(/~0/g, "~");
115401
+ }
115402
+ function parseJsonPointer(path) {
115403
+ const raw = path.startsWith("/") ? path.slice(1).split("/") : path.split("/");
115404
+ return raw.map(unescapeJsonPointer);
115405
+ }
115406
+ function getByPath(obj, path) {
115407
+ if (!path || path === "/") {
115408
+ return obj;
115409
+ }
115410
+ const segments = parseJsonPointer(path);
115411
+ let current = obj;
115412
+ for (const segment of segments) {
115413
+ if (current === null || current === undefined) {
115414
+ return;
115415
+ }
115416
+ if (Array.isArray(current)) {
115417
+ const index = parseInt(segment, 10);
115418
+ current = current[index];
115419
+ } else if (typeof current === "object" && Object.hasOwn(current, segment)) {
115420
+ current = current[segment];
115421
+ } else {
115422
+ return;
115423
+ }
115424
+ }
115425
+ return current;
115426
+ }
115427
+ function resolveRepeatStatePath(statePath, repeatBasePath) {
115428
+ if (typeof statePath === "string") {
115429
+ return statePath;
115430
+ }
115431
+ if (repeatBasePath == null) {
115432
+ return;
115433
+ }
115434
+ if (statePath.$item === "" || statePath.$item === "/") {
115435
+ return repeatBasePath;
115436
+ }
115437
+ return joinStatePath(repeatBasePath, statePath.$item);
115438
+ }
115439
+ function resolveRepeatItemStatePath(statePath, index) {
115440
+ return joinStatePath(statePath, String(index));
115441
+ }
115442
+ function joinStatePath(basePath, childPath) {
115443
+ const child = childPath.startsWith("/") ? childPath.slice(1) : childPath;
115444
+ if (basePath === "" || basePath === "/") {
115445
+ return `/${child}`;
115446
+ }
115447
+ return `${basePath}/${child}`;
115448
+ }
115449
+ var DynamicValueSchema, DynamicStringSchema, DynamicNumberSchema, DynamicBooleanSchema, SPEC_DATA_PART = "spec", SPEC_DATA_PART_TYPE;
115450
+ var init_chunk_FVP4K5MD = __esm(() => {
115451
+ init_zod();
115452
+ DynamicValueSchema = union3([
115453
+ string2(),
115454
+ number2(),
115455
+ boolean(),
115456
+ _null(),
115457
+ object2({ $state: string2() })
115458
+ ]);
115459
+ DynamicStringSchema = union3([
115460
+ string2(),
115461
+ object2({ $state: string2() })
115462
+ ]);
115463
+ DynamicNumberSchema = union3([
115464
+ number2(),
115465
+ object2({ $state: string2() })
115466
+ ]);
115467
+ DynamicBooleanSchema = union3([
115468
+ boolean(),
115469
+ object2({ $state: string2() })
115470
+ ]);
115471
+ SPEC_DATA_PART_TYPE = `data-${SPEC_DATA_PART}`;
115472
+ });
115473
+
115474
+ // node_modules/@json-render/chat/node_modules/@json-render/core/dist/index.mjs
115475
+ function conditionUsesItemScope(condition) {
115476
+ if (condition === undefined || typeof condition === "boolean")
115477
+ return false;
115478
+ if (Array.isArray(condition))
115479
+ return condition.some(conditionUsesItemScope);
115480
+ if (typeof condition !== "object" || condition === null)
115481
+ return false;
115482
+ if ("$item" in condition || "$index" in condition)
115483
+ return true;
115484
+ if ("$and" in condition)
115485
+ return condition.$and.some(conditionUsesItemScope);
115486
+ if ("$or" in condition)
115487
+ return condition.$or.some(conditionUsesItemScope);
115488
+ return false;
115489
+ }
115490
+ function splitRepeatVisibility(condition) {
115491
+ if (condition === undefined || !conditionUsesItemScope(condition)) {
115492
+ return { container: condition, itemFilter: undefined };
115493
+ }
115494
+ const partition = (parts) => {
115495
+ const container = parts.filter((part) => !conditionUsesItemScope(part));
115496
+ const item = parts.filter((part) => conditionUsesItemScope(part));
115497
+ return {
115498
+ container: container.length > 0 ? { $and: container } : undefined,
115499
+ itemFilter: item.length > 0 ? { $and: item } : undefined
115500
+ };
115501
+ };
115502
+ if (Array.isArray(condition))
115503
+ return partition(condition);
115504
+ if (typeof condition === "object" && condition !== null && "$and" in condition) {
115505
+ return partition(condition.$and);
115506
+ }
115507
+ return { container: undefined, itemFilter: condition };
115508
+ }
115509
+ function resolveComparisonValue(value, ctx) {
115510
+ if (typeof value === "object" && value !== null) {
115511
+ if ("$state" in value && typeof value.$state === "string") {
115512
+ return getByPath(ctx.stateModel, value.$state);
115513
+ }
115514
+ }
115515
+ return value;
115516
+ }
115517
+ function isItemCondition(cond) {
115518
+ return "$item" in cond;
115519
+ }
115520
+ function isIndexCondition(cond) {
115521
+ return "$index" in cond;
115522
+ }
115523
+ function resolveConditionValue(cond, ctx) {
115524
+ if (isIndexCondition(cond)) {
115525
+ return ctx.repeatIndex;
115526
+ }
115527
+ if (isItemCondition(cond)) {
115528
+ if (ctx.repeatItem === undefined)
115529
+ return;
115530
+ return cond.$item === "" ? ctx.repeatItem : getByPath(ctx.repeatItem, cond.$item);
115531
+ }
115532
+ return getByPath(ctx.stateModel, cond.$state);
115533
+ }
115534
+ function evaluateCondition2(cond, ctx) {
115535
+ const value = resolveConditionValue(cond, ctx);
115536
+ let result;
115537
+ if (cond.eq !== undefined) {
115538
+ const rhs = resolveComparisonValue(cond.eq, ctx);
115539
+ result = value === rhs;
115540
+ } else if (cond.neq !== undefined) {
115541
+ const rhs = resolveComparisonValue(cond.neq, ctx);
115542
+ result = value !== rhs;
115543
+ } else if (cond.gt !== undefined) {
115544
+ const rhs = resolveComparisonValue(cond.gt, ctx);
115545
+ result = typeof value === "number" && typeof rhs === "number" ? value > rhs : false;
115546
+ } else if (cond.gte !== undefined) {
115547
+ const rhs = resolveComparisonValue(cond.gte, ctx);
115548
+ result = typeof value === "number" && typeof rhs === "number" ? value >= rhs : false;
115549
+ } else if (cond.lt !== undefined) {
115550
+ const rhs = resolveComparisonValue(cond.lt, ctx);
115551
+ result = typeof value === "number" && typeof rhs === "number" ? value < rhs : false;
115552
+ } else if (cond.lte !== undefined) {
115553
+ const rhs = resolveComparisonValue(cond.lte, ctx);
115554
+ result = typeof value === "number" && typeof rhs === "number" ? value <= rhs : false;
115555
+ } else {
115556
+ result = Boolean(value);
115557
+ }
115558
+ return cond.not === true ? !result : result;
115559
+ }
115560
+ function isAndCondition(condition) {
115561
+ return typeof condition === "object" && condition !== null && !Array.isArray(condition) && "$and" in condition;
115562
+ }
115563
+ function isOrCondition(condition) {
115564
+ return typeof condition === "object" && condition !== null && !Array.isArray(condition) && "$or" in condition;
115565
+ }
115566
+ function evaluateVisibility(condition, ctx) {
115567
+ if (condition === undefined) {
115568
+ return true;
115569
+ }
115570
+ if (typeof condition === "boolean") {
115571
+ return condition;
115572
+ }
115573
+ if (Array.isArray(condition)) {
115574
+ return condition.every((c) => evaluateCondition2(c, ctx));
115575
+ }
115576
+ if (isAndCondition(condition)) {
115577
+ return condition.$and.every((child) => evaluateVisibility(child, ctx));
115578
+ }
115579
+ if (isOrCondition(condition)) {
115580
+ return condition.$or.some((child) => evaluateVisibility(child, ctx));
115581
+ }
115582
+ return evaluateCondition2(condition, ctx);
115583
+ }
115584
+ function findDirective(value, directives) {
115585
+ if (!directives || directives.size === 0)
115586
+ return;
115587
+ let match;
115588
+ for (const [key, def] of directives) {
115589
+ if (key in value) {
115590
+ if (match) {
115591
+ throw new Error(`Ambiguous directive: object has multiple directive keys ("${match.name}" and "${key}")`);
115592
+ }
115593
+ match = def;
115594
+ }
115595
+ }
115596
+ return match;
115597
+ }
115598
+ function isStateExpression(value) {
115599
+ return typeof value === "object" && value !== null && "$state" in value && typeof value.$state === "string";
115600
+ }
115601
+ function isItemExpression(value) {
115602
+ return typeof value === "object" && value !== null && "$item" in value && typeof value.$item === "string";
115603
+ }
115604
+ function isIndexExpression(value) {
115605
+ return typeof value === "object" && value !== null && "$index" in value && value.$index === true;
115606
+ }
115607
+ function isBindStateExpression(value) {
115608
+ return typeof value === "object" && value !== null && "$bindState" in value && typeof value.$bindState === "string";
115609
+ }
115610
+ function isBindItemExpression(value) {
115611
+ return typeof value === "object" && value !== null && "$bindItem" in value && typeof value.$bindItem === "string";
115612
+ }
115613
+ function isCondExpression(value) {
115614
+ return typeof value === "object" && value !== null && "$cond" in value && "$then" in value && "$else" in value;
115615
+ }
115616
+ function isComputedExpression(value) {
115617
+ return typeof value === "object" && value !== null && "$computed" in value && typeof value.$computed === "string";
115618
+ }
115619
+ function isTemplateExpression(value) {
115620
+ return typeof value === "object" && value !== null && "$template" in value && typeof value.$template === "string";
115621
+ }
115622
+ function resolveBindItemPath(itemPath, ctx) {
115623
+ if (ctx.repeatBasePath == null) {
115624
+ console.warn(`$bindItem used outside repeat scope: "${itemPath}"`);
115625
+ return;
115626
+ }
115627
+ if (itemPath === "")
115628
+ return ctx.repeatBasePath;
115629
+ return ctx.repeatBasePath + "/" + itemPath;
115630
+ }
115631
+ function resolvePropValue(value, ctx) {
115632
+ if (value === null || value === undefined) {
115633
+ return value;
115634
+ }
115635
+ if (isStateExpression(value)) {
115636
+ return getByPath(ctx.stateModel, value.$state);
115637
+ }
115638
+ if (isItemExpression(value)) {
115639
+ if (ctx.repeatItem === undefined)
115640
+ return;
115641
+ return value.$item === "" ? ctx.repeatItem : getByPath(ctx.repeatItem, value.$item);
115642
+ }
115643
+ if (isIndexExpression(value)) {
115644
+ return ctx.repeatIndex;
115645
+ }
115646
+ if (isBindStateExpression(value)) {
115647
+ return getByPath(ctx.stateModel, value.$bindState);
115648
+ }
115649
+ if (isBindItemExpression(value)) {
115650
+ const resolvedPath = resolveBindItemPath(value.$bindItem, ctx);
115651
+ if (resolvedPath === undefined)
115652
+ return;
115653
+ return getByPath(ctx.stateModel, resolvedPath);
115654
+ }
115655
+ if (isCondExpression(value)) {
115656
+ const result = evaluateVisibility(value.$cond, ctx);
115657
+ return resolvePropValue(result ? value.$then : value.$else, ctx);
115658
+ }
115659
+ if (isComputedExpression(value)) {
115660
+ const fn = ctx.functions?.[value.$computed];
115661
+ if (!fn) {
115662
+ if (!warnedComputedFns.has(value.$computed)) {
115663
+ if (warnedComputedFns.size < WARNED_COMPUTED_MAX) {
115664
+ warnedComputedFns.add(value.$computed);
115665
+ }
115666
+ console.warn(`Unknown $computed function: "${value.$computed}"`);
115667
+ }
115668
+ return;
115669
+ }
115670
+ const resolvedArgs = {};
115671
+ if (value.args) {
115672
+ for (const [key, arg] of Object.entries(value.args)) {
115673
+ resolvedArgs[key] = resolvePropValue(arg, ctx);
115674
+ }
115675
+ }
115676
+ return fn(resolvedArgs);
115677
+ }
115678
+ if (isTemplateExpression(value)) {
115679
+ return value.$template.replace(/\$\{([^}]+)\}/g, (_match, rawPath) => {
115680
+ if (rawPath.startsWith("/")) {
115681
+ const resolved2 = getByPath(ctx.stateModel, rawPath);
115682
+ return resolved2 != null ? String(resolved2) : "";
115683
+ }
115684
+ if (ctx.repeatItem !== undefined) {
115685
+ const fromItem = getByPath(ctx.repeatItem, rawPath);
115686
+ if (fromItem != null)
115687
+ return String(fromItem);
115688
+ }
115689
+ const resolved = getByPath(ctx.stateModel, "/" + rawPath);
115690
+ return resolved != null ? String(resolved) : "";
115691
+ });
115692
+ }
115693
+ if (Array.isArray(value)) {
115694
+ return value.map((item) => resolvePropValue(item, ctx));
115695
+ }
115696
+ if (typeof value === "object") {
115697
+ const directive = findDirective(value, ctx.directives);
115698
+ if (directive) {
115699
+ return directive.resolve(value, ctx);
115700
+ }
115701
+ const resolved = {};
115702
+ for (const [key, val] of Object.entries(value)) {
115703
+ resolved[key] = resolvePropValue(val, ctx);
115704
+ }
115705
+ return resolved;
115706
+ }
115707
+ return value;
115708
+ }
115709
+ function resolveElementProps(props, ctx) {
115710
+ const resolved = {};
115711
+ for (const [key, value] of Object.entries(props)) {
115712
+ resolved[key] = resolvePropValue(value, ctx);
115713
+ }
115714
+ return resolved;
115715
+ }
115716
+ function normalizeModes(config) {
115717
+ if (!config?.modes?.length)
115718
+ return DEFAULT_MODES;
115719
+ return config.modes;
115720
+ }
115721
+ function jsonPatchInstructions() {
115722
+ return [
115723
+ "PATCH MODE (RFC 6902 JSON Patch):",
115724
+ "Output one JSON object per line. Each line is a patch operation.",
115725
+ '- Add: {"op":"add","path":"/elements/new-key","value":{...}}',
115726
+ '- Replace: {"op":"replace","path":"/elements/existing-key","value":{...}}',
115727
+ '- Remove: {"op":"remove","path":"/elements/old-key"}',
115728
+ "Only output patches for what needs to change."
115729
+ ].join(`
115730
+ `);
115731
+ }
115732
+ function jsonMergeInstructions() {
115733
+ return [
115734
+ "MERGE MODE (RFC 7396 JSON Merge Patch):",
115735
+ "Output a single JSON object on one line with __json_edit set to true.",
115736
+ "Include only the keys that changed. Unmentioned keys are preserved.",
115737
+ "Set a key to null to delete it.",
115738
+ "",
115739
+ "Example (update a title and add an element):",
115740
+ '{"__json_edit":true,"elements":{"main":{"props":{"title":"New Title"}},"new-el":{"type":"Card","props":{},"children":[]}}}',
115741
+ "",
115742
+ "Example (delete an element):",
115743
+ '{"__json_edit":true,"elements":{"old-widget":null}}'
115744
+ ].join(`
115745
+ `);
115746
+ }
115747
+ function jsonDiffInstructions() {
115748
+ return [
115749
+ "DIFF MODE (unified diff):",
115750
+ "Output a unified diff inside a ```diff code fence.",
115751
+ "The diff applies against the JSON-serialized current spec.",
115752
+ "",
115753
+ "Example:",
115754
+ "```diff",
115755
+ "--- a/spec.json",
115756
+ "+++ b/spec.json",
115757
+ "@@ -3,1 +3,1 @@",
115758
+ '- "title": "Login"',
115759
+ '+ "title": "Welcome Back"',
115760
+ "```"
115761
+ ].join(`
115762
+ `);
115763
+ }
115764
+ function yamlPatchInstructions() {
115765
+ return [
115766
+ "PATCH MODE (RFC 6902 JSON Patch):",
115767
+ "Output RFC 6902 JSON Patch lines inside a ```yaml-patch code fence.",
115768
+ "Each line is one JSON patch operation.",
115769
+ "",
115770
+ "Example:",
115771
+ "```yaml-patch",
115772
+ '{"op":"replace","path":"/elements/main/props/title","value":"New Title"}',
115773
+ '{"op":"add","path":"/elements/new-el","value":{"type":"Card","props":{},"children":[]}}',
115774
+ "```"
115775
+ ].join(`
115776
+ `);
115777
+ }
115778
+ function yamlMergeInstructions() {
115779
+ return [
115780
+ "MERGE MODE (RFC 7396 JSON Merge Patch):",
115781
+ "Output only the changed parts in a ```yaml-edit code fence.",
115782
+ "Uses deep merge semantics: only keys you include are updated. Unmentioned elements and props are preserved.",
115783
+ "Set a key to null to delete it.",
115784
+ "",
115785
+ "Example edit (update title, add a new element):",
115786
+ "```yaml-edit",
115787
+ "elements:",
115788
+ " main:",
115789
+ " props:",
115790
+ " title: Updated Title",
115791
+ " new-chart:",
115792
+ " type: Card",
115793
+ " props: {}",
115794
+ " children: []",
115795
+ "```",
115796
+ "",
115797
+ "Example deletion:",
115798
+ "```yaml-edit",
115799
+ "elements:",
115800
+ " old-widget: null",
115801
+ "```"
115802
+ ].join(`
115803
+ `);
115804
+ }
115805
+ function yamlDiffInstructions() {
115806
+ return [
115807
+ "DIFF MODE (unified diff):",
115808
+ "Output a unified diff inside a ```diff code fence.",
115809
+ "The diff applies against the YAML-serialized current spec.",
115810
+ "",
115811
+ "Example:",
115812
+ "```diff",
115813
+ "--- a/spec.yaml",
115814
+ "+++ b/spec.yaml",
115815
+ "@@ -6,1 +6,1 @@",
115816
+ "- title: Login",
115817
+ "+ title: Welcome Back",
115818
+ "```"
115819
+ ].join(`
115820
+ `);
115821
+ }
115822
+ function modeSelectionGuidance(modes) {
115823
+ if (modes.length === 1)
115824
+ return "";
115825
+ const parts = ["Choose the best edit strategy for the requested change:"];
115826
+ if (modes.includes("patch")) {
115827
+ parts.push("- PATCH: best for precise, targeted single-field updates");
115828
+ }
115829
+ if (modes.includes("merge")) {
115830
+ parts.push("- MERGE: best for structural changes (add/remove elements, reparent children, update multiple props at once)");
115831
+ }
115832
+ if (modes.includes("diff")) {
115833
+ parts.push("- DIFF: best for small text-level changes when you can see the exact lines to change");
115834
+ }
115835
+ return parts.join(`
115836
+ `);
115837
+ }
115838
+ function buildEditInstructions(config, format) {
115839
+ const modes = normalizeModes(config);
115840
+ const sections = [];
115841
+ sections.push("EDITING EXISTING SPECS:");
115842
+ sections.push("");
115843
+ const guidance = modeSelectionGuidance(modes);
115844
+ if (guidance) {
115845
+ sections.push(guidance);
115846
+ sections.push("");
115847
+ }
115848
+ for (const mode of modes) {
115849
+ if (format === "json") {
115850
+ switch (mode) {
115851
+ case "patch":
115852
+ sections.push(jsonPatchInstructions());
115853
+ break;
115854
+ case "merge":
115855
+ sections.push(jsonMergeInstructions());
115856
+ break;
115857
+ case "diff":
115858
+ sections.push(jsonDiffInstructions());
115859
+ break;
115860
+ }
115861
+ } else {
115862
+ switch (mode) {
115863
+ case "patch":
115864
+ sections.push(yamlPatchInstructions());
115865
+ break;
115866
+ case "merge":
115867
+ sections.push(yamlMergeInstructions());
115868
+ break;
115869
+ case "diff":
115870
+ sections.push(yamlDiffInstructions());
115871
+ break;
115872
+ }
115873
+ }
115874
+ sections.push("");
115875
+ }
115876
+ return sections.join(`
115877
+ `);
115878
+ }
115879
+ function createBuilder() {
115880
+ return {
115881
+ string: () => ({ kind: "string" }),
115882
+ number: () => ({ kind: "number" }),
115883
+ boolean: () => ({ kind: "boolean" }),
115884
+ array: (item) => ({ kind: "array", inner: item }),
115885
+ object: (shape) => ({ kind: "object", inner: shape }),
115886
+ record: (value) => ({ kind: "record", inner: value }),
115887
+ any: () => ({ kind: "any" }),
115888
+ zod: () => ({ kind: "zod" }),
115889
+ ref: (path) => ({ kind: "ref", inner: path }),
115890
+ propsOf: (path) => ({ kind: "propsOf", inner: path }),
115891
+ map: (entryShape) => ({ kind: "map", inner: entryShape }),
115892
+ optional: () => ({ optional: true })
115893
+ };
115894
+ }
115895
+ function defineSchema(builder, options) {
115896
+ const s = createBuilder();
115897
+ const definition = builder(s);
115898
+ return {
115899
+ definition,
115900
+ promptTemplate: options?.promptTemplate,
115901
+ defaultRules: options?.defaultRules,
115902
+ builtInActions: options?.builtInActions,
115903
+ createCatalog(catalog) {
115904
+ return createCatalogFromSchema(this, catalog);
115905
+ }
115906
+ };
115907
+ }
115908
+ function createCatalogFromSchema(schema, catalogData) {
115909
+ const components = catalogData.components;
115910
+ const actions = catalogData.actions;
115911
+ const componentNames = components ? Object.keys(components) : [];
115912
+ const actionNames = actions ? Object.keys(actions) : [];
115913
+ const zodSchema = buildZodSchemaFromDefinition(schema.definition, catalogData);
115914
+ return {
115915
+ schema,
115916
+ data: catalogData,
115917
+ componentNames,
115918
+ actionNames,
115919
+ prompt(options = {}) {
115920
+ return generatePrompt(this, options);
115921
+ },
115922
+ jsonSchema(options = {}) {
115923
+ return zodToJsonSchema3(zodSchema, options.strict ?? false);
115924
+ },
115925
+ validate(spec) {
115926
+ const result = zodSchema.safeParse(spec);
115927
+ if (result.success) {
115928
+ return {
115929
+ success: true,
115930
+ data: result.data
115931
+ };
115932
+ }
115933
+ return { success: false, error: result.error };
115934
+ },
115935
+ zodSchema() {
115936
+ return zodSchema;
115937
+ },
115938
+ get _specType() {
115939
+ throw new Error("_specType is only for type inference");
115940
+ }
115941
+ };
115942
+ }
115943
+ function buildZodSchemaFromDefinition(definition, catalogData) {
115944
+ return buildZodType(definition.spec, catalogData);
115945
+ }
115946
+ function buildZodType(schemaType, catalogData) {
115947
+ switch (schemaType.kind) {
115948
+ case "string":
115949
+ return string2();
115950
+ case "number":
115951
+ return number2();
115952
+ case "boolean":
115953
+ return boolean();
115954
+ case "any":
115955
+ return any();
115956
+ case "array": {
115957
+ const inner = buildZodType(schemaType.inner, catalogData);
115958
+ return array2(inner);
115959
+ }
115960
+ case "object": {
115961
+ const shape = schemaType.inner;
115962
+ const zodShape = {};
115963
+ for (const [key, value] of Object.entries(shape)) {
115964
+ let zodType = buildZodType(value, catalogData);
115965
+ if (value.optional) {
115966
+ zodType = zodType.optional();
115967
+ }
115968
+ zodShape[key] = zodType;
115969
+ }
115970
+ return object2(zodShape);
115971
+ }
115972
+ case "record": {
115973
+ const inner = buildZodType(schemaType.inner, catalogData);
115974
+ return record2(string2(), inner);
115975
+ }
115976
+ case "ref": {
115977
+ const path = schemaType.inner;
115978
+ const keys = getKeysFromPath(path, catalogData);
115979
+ if (keys.length === 0) {
115980
+ return string2();
115981
+ }
115982
+ if (keys.length === 1) {
115983
+ return literal2(keys[0]);
115984
+ }
115985
+ return _enum2(keys);
115986
+ }
115987
+ case "propsOf": {
115988
+ const path = schemaType.inner;
115989
+ const propsSchemas = getPropsFromPath(path, catalogData);
115990
+ if (propsSchemas.length === 0) {
115991
+ return record2(string2(), unknown());
115992
+ }
115993
+ if (propsSchemas.length === 1) {
115994
+ return propsSchemas[0];
115995
+ }
115996
+ return record2(string2(), unknown());
115997
+ }
115998
+ default:
115999
+ return unknown();
116000
+ }
116001
+ }
116002
+ function getKeysFromPath(path, catalogData) {
116003
+ const parts = path.split(".");
116004
+ let current = { catalog: catalogData };
116005
+ for (const part of parts) {
116006
+ if (current && typeof current === "object") {
116007
+ current = current[part];
116008
+ } else {
116009
+ return [];
116010
+ }
116011
+ }
116012
+ if (current && typeof current === "object") {
116013
+ return Object.keys(current);
116014
+ }
116015
+ return [];
116016
+ }
116017
+ function getPropsFromPath(path, catalogData) {
116018
+ const parts = path.split(".");
116019
+ let current = { catalog: catalogData };
116020
+ for (const part of parts) {
116021
+ if (current && typeof current === "object") {
116022
+ current = current[part];
116023
+ } else {
116024
+ return [];
116025
+ }
116026
+ }
116027
+ if (current && typeof current === "object") {
116028
+ return Object.values(current).map((entry) => entry.props).filter((props) => props !== undefined);
116029
+ }
116030
+ return [];
116031
+ }
116032
+ function generatePrompt(catalog, options) {
116033
+ if (catalog.schema.promptTemplate) {
116034
+ const context = {
116035
+ catalog: catalog.data,
116036
+ componentNames: catalog.componentNames,
116037
+ actionNames: catalog.actionNames,
116038
+ options,
116039
+ formatZodType
116040
+ };
116041
+ return catalog.schema.promptTemplate(context);
116042
+ }
116043
+ const {
116044
+ system = "You are a UI generator that outputs JSON.",
116045
+ customRules = [],
116046
+ mode: rawMode = "standalone"
116047
+ } = options;
116048
+ const mode = rawMode === "chat" ? (console.warn('[json-render] mode "chat" is deprecated, use "inline" instead'), "inline") : rawMode === "generate" ? (console.warn('[json-render] mode "generate" is deprecated, use "standalone" instead'), "standalone") : rawMode;
116049
+ const lines = [];
116050
+ lines.push(system);
116051
+ lines.push("");
116052
+ if (mode === "inline") {
116053
+ lines.push("OUTPUT FORMAT (text + JSONL, RFC 6902 JSON Patch):");
116054
+ lines.push("You respond conversationally. When generating UI, first write a brief explanation (1-3 sentences), then output JSONL patch lines wrapped in a ```spec code fence.");
116055
+ lines.push("The JSONL lines use RFC 6902 JSON Patch operations to build a UI tree. Always wrap them in a ```spec fence block:");
116056
+ lines.push(" ```spec");
116057
+ lines.push(' {"op":"add","path":"/root","value":"main"}');
116058
+ lines.push(' {"op":"add","path":"/elements/main","value":{"type":"Card","props":{"title":"Hello"},"children":[]}}');
116059
+ lines.push(" ```");
116060
+ lines.push("If the user's message does not require a UI (e.g. a greeting or clarifying question), respond with text only — no JSONL.");
116061
+ } else {
116062
+ lines.push("OUTPUT FORMAT (JSONL, RFC 6902 JSON Patch):");
116063
+ lines.push("Output JSONL (one JSON object per line) using RFC 6902 JSON Patch operations to build a UI tree.");
116064
+ }
116065
+ lines.push("Each line is a JSON patch operation (add, remove, replace). Start with /root, then stream /elements and /state patches interleaved so the UI fills in progressively as it streams.");
116066
+ lines.push("");
116067
+ lines.push("Example output (each line is a separate JSON object):");
116068
+ lines.push("");
116069
+ const allComponents = catalog.data.components;
116070
+ const specDefinition = catalog.schema.definition.spec;
116071
+ const specShape = specDefinition.kind === "object" ? specDefinition.inner : undefined;
116072
+ const elementsDefinition = specShape?.elements;
116073
+ const elementDefinition = elementsDefinition?.kind === "record" ? elementsDefinition.inner : undefined;
116074
+ const elementShape = elementDefinition?.kind === "object" ? elementDefinition.inner : undefined;
116075
+ const supportsNamedSlots = elementShape?.slots !== undefined;
116076
+ const cn = catalog.componentNames;
116077
+ const comp1 = cn[0] || "Component";
116078
+ const comp2 = cn.length > 1 ? cn[1] : comp1;
116079
+ const comp1Def = allComponents?.[comp1];
116080
+ const comp2Def = allComponents?.[comp2];
116081
+ const comp1Props = comp1Def ? getExampleProps(comp1Def) : {};
116082
+ const comp2Props = comp2Def ? getExampleProps(comp2Def) : {};
116083
+ const dynamicPropName = comp2Def?.props ? findFirstStringProp(comp2Def.props) : null;
116084
+ const dynamicProps = dynamicPropName ? { ...comp2Props, [dynamicPropName]: { $item: "title" } } : comp2Props;
116085
+ const exampleOutput = [
116086
+ JSON.stringify({ op: "add", path: "/root", value: "main" }),
116087
+ JSON.stringify({
116088
+ op: "add",
116089
+ path: "/elements/main",
116090
+ value: {
116091
+ type: comp1,
116092
+ props: comp1Props,
116093
+ children: ["child-1", "list"]
116094
+ }
116095
+ }),
116096
+ JSON.stringify({
116097
+ op: "add",
116098
+ path: "/elements/child-1",
116099
+ value: { type: comp2, props: comp2Props, children: [] }
116100
+ }),
116101
+ JSON.stringify({
116102
+ op: "add",
116103
+ path: "/elements/list",
116104
+ value: {
116105
+ type: comp1,
116106
+ props: comp1Props,
116107
+ repeat: { statePath: "/items", key: "id" },
116108
+ children: ["item"]
116109
+ }
116110
+ }),
116111
+ JSON.stringify({
116112
+ op: "add",
116113
+ path: "/elements/item",
116114
+ value: { type: comp2, props: dynamicProps, children: [] }
116115
+ }),
116116
+ JSON.stringify({ op: "add", path: "/state/items", value: [] }),
116117
+ JSON.stringify({
116118
+ op: "add",
116119
+ path: "/state/items/0",
116120
+ value: { id: "1", title: "First Item" }
116121
+ }),
116122
+ JSON.stringify({
116123
+ op: "add",
116124
+ path: "/state/items/1",
116125
+ value: { id: "2", title: "Second Item" }
116126
+ })
116127
+ ].join(`
116128
+ `);
116129
+ lines.push(`${exampleOutput}
116130
+
116131
+ Note: state patches appear right after the elements that use them, so the UI fills in as it streams. ONLY use component types from the AVAILABLE COMPONENTS list below.`);
116132
+ lines.push("");
116133
+ lines.push("INITIAL STATE:");
116134
+ lines.push("Specs include a /state field to seed the state model. Components with { $bindState } or { $bindItem } read from and write to this state, and $state expressions read from it.");
116135
+ lines.push("CRITICAL: You MUST include state patches whenever your UI displays data via $state, $bindState, $bindItem, $item, or $index expressions, or uses repeat to iterate over arrays. Without state, these references resolve to nothing and repeat lists render zero items.");
116136
+ lines.push("Output state patches right after the elements that reference them, so the UI fills in progressively as it streams.");
116137
+ lines.push("Stream state progressively - output one patch per array item instead of one giant blob:");
116138
+ lines.push(' For arrays: {"op":"add","path":"/state/posts/0","value":{"id":"1","title":"First Post",...}} then /state/posts/1, /state/posts/2, etc.');
116139
+ lines.push(' For scalars: {"op":"add","path":"/state/newTodoText","value":""}');
116140
+ lines.push(' Initialize the array first if needed: {"op":"add","path":"/state/posts","value":[]}');
116141
+ lines.push('When content comes from the state model, use { "$state": "/some/path" } dynamic props to display it instead of hardcoding the same value in both state and props. The state model is the single source of truth.');
116142
+ lines.push("Include realistic sample data in state. For blogs: 3-4 posts with titles, excerpts, authors, dates. For product lists: 3-5 items with names, prices, descriptions. Never leave arrays empty.");
116143
+ lines.push("");
116144
+ lines.push("DYNAMIC LISTS (repeat field):");
116145
+ lines.push('Any element can have a top-level "repeat" field to render its children once per item in a state array: { "repeat": { "statePath": "/arrayPath", "key": "id" } }.');
116146
+ lines.push('The element itself renders once (as the container), and its children are expanded once per array item. "statePath" is the state array path. "key" is an optional field name on each item for stable React keys.');
116147
+ lines.push('For nested lists, an inner repeat can read an array from the enclosing item with { "statePath": { "$item": "field" } }. This form is valid only inside another repeat. Use an empty field to repeat over the enclosing item itself.');
116148
+ lines.push(`Example: ${JSON.stringify({ type: comp1, props: comp1Props, repeat: { statePath: "/todos", key: "id" }, children: ["todo-item"] })}`);
116149
+ lines.push('Inside children of a repeated element, use { "$item": "field" } to read a field from the current item, and { "$index": true } to get the current array index. For two-way binding to an item field use { "$bindItem": "completed" } on the appropriate prop.');
116150
+ lines.push("ALWAYS use the repeat field for lists backed by state arrays. NEVER hardcode individual elements for each array item.");
116151
+ lines.push('IMPORTANT: "repeat" is a top-level field on the element (sibling of type/props/children), NOT inside props.');
116152
+ lines.push("");
116153
+ lines.push("ARRAY STATE ACTIONS:");
116154
+ lines.push('Use action "pushState" to append items to arrays. Params: { statePath: "/arrayPath", value: { ...item }, clearStatePath: "/inputPath" }.');
116155
+ lines.push('Values inside pushState can contain { "$state": "/statePath" } references to read current state (e.g. the text from an input field).');
116156
+ lines.push('Use "$id" inside a pushState value to auto-generate a unique ID.');
116157
+ lines.push('Example: on: { "press": { "action": "pushState", "params": { "statePath": "/todos", "value": { "id": "$id", "title": { "$state": "/newTodoText" }, "completed": false }, "clearStatePath": "/newTodoText" } } }');
116158
+ lines.push(`Use action "removeState" to remove items from arrays by index. Params: { statePath: "/arrayPath", index: N }. Inside a repeated element's children, use { "$index": true } for the current item index. Action params support the same expressions as props: { "$item": "field" } resolves to the absolute state path, { "$index": true } resolves to the index number, and { "$state": "/path" } reads a value from state.`);
116159
+ lines.push("For lists where users can add/remove items (todos, carts, etc.), use pushState and removeState instead of hardcoding with setState.");
116160
+ lines.push("");
116161
+ lines.push('IMPORTANT: State paths use RFC 6901 JSON Pointer syntax (e.g. "/todos/0/title"). Do NOT use JavaScript-style dot notation (e.g. "/todos.length" is WRONG). To generate unique IDs for new items, use "$id" instead of trying to read array length.');
116162
+ lines.push("");
116163
+ const components = allComponents;
116164
+ if (components) {
116165
+ lines.push(`AVAILABLE COMPONENTS (${catalog.componentNames.length}):`);
116166
+ lines.push("");
116167
+ for (const [name, def] of Object.entries(components)) {
116168
+ const propsStr = def.props ? formatZodType(def.props) : "{}";
116169
+ const slotNames = def.slots ?? [];
116170
+ const namedSlotNames = slotNames.filter((slot) => slot !== "default");
116171
+ const acceptsChildren = slotNames.includes("default");
116172
+ const slotsStr = supportsNamedSlots ? [
116173
+ acceptsChildren ? "accepts children" : "",
116174
+ namedSlotNames.length > 0 ? `slots: ${namedSlotNames.join(", ")}` : ""
116175
+ ].filter(Boolean).join("; ") : slotNames.length > 0 ? "accepts children" : "";
116176
+ const slotsSuffix = slotsStr ? ` [${slotsStr}]` : "";
116177
+ const eventsStr = def.events && def.events.length > 0 ? ` [events: ${def.events.join(", ")}]` : "";
116178
+ const descStr = def.description ? ` - ${def.description}` : "";
116179
+ lines.push(`- ${name}: ${propsStr}${descStr}${slotsSuffix}${eventsStr}`);
116180
+ }
116181
+ lines.push("");
116182
+ }
116183
+ const actions = catalog.data.actions;
116184
+ const builtInActions = catalog.schema.builtInActions ?? [];
116185
+ const hasCustomActions = actions && catalog.actionNames.length > 0;
116186
+ const hasBuiltInActions = builtInActions.length > 0;
116187
+ if (hasCustomActions || hasBuiltInActions) {
116188
+ lines.push("AVAILABLE ACTIONS:");
116189
+ lines.push("");
116190
+ for (const action2 of builtInActions) {
116191
+ lines.push(`- ${action2.name}: ${action2.description} [built-in]`);
116192
+ }
116193
+ if (hasCustomActions) {
116194
+ for (const [name, def] of Object.entries(actions)) {
116195
+ lines.push(`- ${name}${def.description ? `: ${def.description}` : ""}`);
116196
+ }
116197
+ }
116198
+ lines.push("");
116199
+ }
116200
+ lines.push("EVENTS (the `on` field):");
116201
+ lines.push("Elements can have an optional `on` field to bind events to actions. The `on` field is a top-level field on the element (sibling of type/props/children), NOT inside props.");
116202
+ lines.push('Each key in `on` is an event name (from the component\'s supported events), and the value is an action binding: `{ "action": "<actionName>", "params": { ... } }`.');
116203
+ lines.push("");
116204
+ lines.push("Example:");
116205
+ lines.push(` ${JSON.stringify({ type: comp1, props: comp1Props, on: { press: { action: "setState", params: { statePath: "/saved", value: true } } }, children: [] })}`);
116206
+ lines.push("");
116207
+ lines.push('Action params can use dynamic references to read from state: { "$state": "/statePath" }.');
116208
+ lines.push("IMPORTANT: Do NOT put action/actionParams inside props. Always use the `on` field for event bindings.");
116209
+ lines.push("");
116210
+ lines.push("VISIBILITY CONDITIONS:");
116211
+ lines.push("Elements can have an optional `visible` field to conditionally show/hide based on state. IMPORTANT: `visible` is a top-level field on the element object (sibling of type/props/children), NOT inside props.");
116212
+ lines.push(`Correct: ${JSON.stringify({ type: comp1, props: comp1Props, visible: { $state: "/activeTab", eq: "home" }, children: ["..."] })}`);
116213
+ lines.push('- `{ "$state": "/path" }` - visible when state at path is truthy');
116214
+ lines.push('- `{ "$state": "/path", "not": true }` - visible when state at path is falsy');
116215
+ lines.push('- `{ "$state": "/path", "eq": "value" }` - visible when state equals value');
116216
+ lines.push('- `{ "$state": "/path", "neq": "value" }` - visible when state does not equal value');
116217
+ lines.push('- `{ "$state": "/path", "gt": N }` / `gte` / `lt` / `lte` - numeric comparisons');
116218
+ lines.push("- Use ONE operator per condition (eq, neq, gt, gte, lt, lte). Do not combine multiple operators.");
116219
+ lines.push('- Any condition can add `"not": true` to invert its result');
116220
+ lines.push("- `[condition, condition]` - all conditions must be true (implicit AND)");
116221
+ lines.push('- `{ "$and": [condition, condition] }` - explicit AND (use when nesting inside $or)');
116222
+ lines.push('- `{ "$or": [condition, condition] }` - at least one must be true (OR)');
116223
+ lines.push("- `true` / `false` - always visible/hidden");
116224
+ lines.push("");
116225
+ lines.push("Use a component with on.press bound to setState to update state and drive visibility.");
116226
+ lines.push(`Example: A ${comp1} with on: { "press": { "action": "setState", "params": { "statePath": "/activeTab", "value": "home" } } } sets state, then a container with visible: { "$state": "/activeTab", "eq": "home" } shows only when that tab is active.`);
116227
+ lines.push("");
116228
+ lines.push('For tab patterns where the first/default tab should be visible when no tab is selected yet, use $or to handle both cases: visible: { "$or": [{ "$state": "/activeTab", "eq": "home" }, { "$state": "/activeTab", "not": true }] }. This ensures the first tab is visible both when explicitly selected AND when /activeTab is not yet set.');
116229
+ lines.push("");
116230
+ lines.push("DYNAMIC PROPS:");
116231
+ lines.push("Any prop value can be a dynamic expression that resolves based on state. Three forms are supported:");
116232
+ lines.push("");
116233
+ lines.push('1. Read-only state: `{ "$state": "/statePath" }` - resolves to the value at that state path (one-way read).');
116234
+ lines.push(' Example: `"color": { "$state": "/theme/primary" }` reads the color from state.');
116235
+ lines.push("");
116236
+ lines.push('2. Two-way binding: `{ "$bindState": "/statePath" }` - resolves to the value at the state path AND enables write-back. Use on form input props (value, checked, pressed, etc.).');
116237
+ lines.push(' Example: `"value": { "$bindState": "/form/email" }` binds the input value to /form/email.');
116238
+ lines.push(' Inside repeat scopes: `"checked": { "$bindItem": "completed" }` binds to the current item\'s completed field.');
116239
+ lines.push("");
116240
+ lines.push('3. Conditional: `{ "$cond": <condition>, "$then": <value>, "$else": <value> }` - evaluates the condition (same syntax as visibility conditions) and picks the matching value.');
116241
+ lines.push(' Example: `"color": { "$cond": { "$state": "/activeTab", "eq": "home" }, "$then": "#007AFF", "$else": "#8E8E93" }`');
116242
+ lines.push("");
116243
+ lines.push("Use $bindState for form inputs (text fields, checkboxes, selects, sliders, etc.) and $state for read-only data display. Inside repeat scopes, use $bindItem for form inputs bound to the current item. Use dynamic props instead of duplicating elements with opposing visible conditions when only prop values differ.");
116244
+ lines.push("");
116245
+ lines.push('4. Template: `{ "$template": "Hello, ${/name}!" }` - interpolates references in the string. Absolute paths like `${/path}` resolve against the state model. Bare names like `${field}` resolve against the current repeat item first, then fall back to the state model at `/<field>`.');
116246
+ lines.push(' Example: `"label": { "$template": "Items: ${/cart/count} | Total: ${/cart/total}" }` renders "Items: 3 | Total: 42.00" when /cart/count is 3 and /cart/total is 42.00. Inside a repeat, `{ "$template": "${name} - ${email}" }` reads name and email from each item.');
116247
+ lines.push("");
116248
+ const catalogFunctions = catalog.data.functions;
116249
+ if (catalogFunctions && Object.keys(catalogFunctions).length > 0) {
116250
+ lines.push('5. Computed: `{ "$computed": "<functionName>", "args": { "key": <expression> } }` - calls a registered function with resolved args and returns the result.');
116251
+ lines.push(' Example: `"value": { "$computed": "fullName", "args": { "first": { "$state": "/form/firstName" }, "last": { "$state": "/form/lastName" } } }`');
116252
+ lines.push(" Available functions:");
116253
+ for (const name of Object.keys(catalogFunctions)) {
116254
+ lines.push(` - ${name}`);
116255
+ }
116256
+ lines.push("");
116257
+ }
116258
+ const directives = options.directives;
116259
+ if (directives && directives.length > 0) {
116260
+ lines.push("CUSTOM DYNAMIC VALUES:");
116261
+ lines.push("");
116262
+ for (const d of directives) {
116263
+ const desc = d.description ? ` (${d.description})` : "";
116264
+ lines.push(`- ${d.name}${desc}: ${formatZodType(d.schema)}`);
116265
+ }
116266
+ lines.push("");
116267
+ lines.push("Directives compose: any value field can contain another directive or a $state expression, resolved inside-out.");
116268
+ lines.push("");
116269
+ }
116270
+ const hasChecksComponents = allComponents ? Object.entries(allComponents).some(([, def]) => {
116271
+ if (!def.props)
116272
+ return false;
116273
+ const formatted = formatZodType(def.props);
116274
+ return formatted.includes("checks");
116275
+ }) : false;
116276
+ if (hasChecksComponents) {
116277
+ lines.push("VALIDATION:");
116278
+ lines.push("Form components that accept a `checks` prop support client-side validation.");
116279
+ lines.push('Each check is an object: { "type": "<name>", "message": "...", "args": { ... } }');
116280
+ lines.push("");
116281
+ lines.push("Built-in validation types:");
116282
+ lines.push(" - required — value must be non-empty");
116283
+ lines.push(" - email — valid email format");
116284
+ lines.push(' - minLength — minimum string length (args: { "min": N })');
116285
+ lines.push(' - maxLength — maximum string length (args: { "max": N })');
116286
+ lines.push(' - pattern — match a regex (args: { "pattern": "regex" })');
116287
+ lines.push(' - min — minimum numeric value (args: { "min": N })');
116288
+ lines.push(' - max — maximum numeric value (args: { "max": N })');
116289
+ lines.push(" - numeric — value must be a number");
116290
+ lines.push(" - url — valid URL format");
116291
+ lines.push(' - matches — must equal another field (args: { "other": { "$state": "/path" } })');
116292
+ lines.push(' - equalTo — alias for matches (args: { "other": { "$state": "/path" } })');
116293
+ lines.push(' - lessThan — value must be less than another field (args: { "other": { "$state": "/path" } })');
116294
+ lines.push(' - greaterThan — value must be greater than another field (args: { "other": { "$state": "/path" } })');
116295
+ lines.push(' - requiredIf — required only when another field is truthy (args: { "field": { "$state": "/path" } })');
116296
+ lines.push("");
116297
+ lines.push("Example:");
116298
+ lines.push(' "checks": [{ "type": "required", "message": "Email is required" }, { "type": "email", "message": "Invalid email" }]');
116299
+ lines.push("");
116300
+ lines.push("IMPORTANT: When using checks, the component must also have a { $bindState } or { $bindItem } on its value/checked prop for two-way binding.");
116301
+ lines.push("Always include validation checks on form inputs for a good user experience (e.g. required, email, minLength).");
116302
+ lines.push("");
116303
+ }
116304
+ if (hasCustomActions || hasBuiltInActions) {
116305
+ lines.push("STATE WATCHERS:");
116306
+ lines.push("Elements can have an optional `watch` field to react to state changes and trigger actions. The `watch` field is a top-level field on the element (sibling of type/props/children), NOT inside props.");
116307
+ lines.push("Maps state paths (JSON Pointers) to action bindings. When the value at a watched path changes, the bound actions fire automatically.");
116308
+ lines.push("");
116309
+ lines.push("Example (cascading select — country changes trigger city loading):");
116310
+ lines.push(` ${JSON.stringify({ type: "Select", props: { value: { $bindState: "/form/country" }, options: ["US", "Canada", "UK"] }, watch: { "/form/country": { action: "loadCities", params: { country: { $state: "/form/country" } } } }, children: [] })}`);
116311
+ lines.push("");
116312
+ lines.push("Use `watch` for cascading dependencies where changing one field should trigger side effects (loading data, resetting dependent fields, computing derived values).");
116313
+ lines.push("IMPORTANT: `watch` is a top-level field on the element (sibling of type/props/children), NOT inside props. Watchers only fire when the value changes, not on initial render.");
116314
+ lines.push("");
116315
+ }
116316
+ const editModes = options.editModes;
116317
+ if (editModes && editModes.length > 0) {
116318
+ lines.push(buildEditInstructions({ modes: editModes }, "json"));
116319
+ }
116320
+ lines.push("RULES:");
116321
+ const baseRules = mode === "inline" ? [
116322
+ "When generating UI, wrap all JSONL patches in a ```spec code fence - one JSON object per line inside the fence",
116323
+ "Write a brief conversational response before any JSONL output",
116324
+ 'First set root: {"op":"add","path":"/root","value":"<root-key>"}',
116325
+ 'Then add each element: {"op":"add","path":"/elements/<key>","value":{...}}',
116326
+ "Output /state patches right after the elements that use them, one per array item for progressive loading. REQUIRED whenever using $state, $bindState, $bindItem, $item, $index, or repeat.",
116327
+ "ONLY use components listed above",
116328
+ "Each element value needs: type, props, children (array of child keys)",
116329
+ "Use unique keys for the element map entries (e.g., 'header', 'metric-1', 'chart-revenue')"
116330
+ ] : [
116331
+ "Output ONLY JSONL patches - one JSON object per line, no markdown, no code fences",
116332
+ 'First set root: {"op":"add","path":"/root","value":"<root-key>"}',
116333
+ 'Then add each element: {"op":"add","path":"/elements/<key>","value":{...}}',
116334
+ "Output /state patches right after the elements that use them, one per array item for progressive loading. REQUIRED whenever using $state, $bindState, $bindItem, $item, $index, or repeat.",
116335
+ "ONLY use components listed above",
116336
+ "Each element value needs: type, props, children (array of child keys)",
116337
+ "Use unique keys for the element map entries (e.g., 'header', 'metric-1', 'chart-revenue')"
116338
+ ];
116339
+ const schemaRules = catalog.schema.defaultRules ?? [];
116340
+ const allRules = [...baseRules, ...schemaRules, ...customRules];
116341
+ allRules.forEach((rule, i) => {
116342
+ lines.push(`${i + 1}. ${rule}`);
116343
+ });
116344
+ return lines.join(`
116345
+ `);
116346
+ }
116347
+ function getExampleProps(def) {
116348
+ if (def.example && Object.keys(def.example).length > 0) {
116349
+ return def.example;
116350
+ }
116351
+ if (def.props) {
116352
+ return generateExamplePropsFromZod(def.props);
116353
+ }
116354
+ return {};
116355
+ }
116356
+ function generateExamplePropsFromZod(schema) {
116357
+ if (!schema || !schema._def)
116358
+ return {};
116359
+ const def = schema._def;
116360
+ const typeName = getZodTypeName(schema);
116361
+ if (typeName !== "ZodObject" && typeName !== "object")
116362
+ return {};
116363
+ const shape = typeof def.shape === "function" ? def.shape() : def.shape;
116364
+ if (!shape)
116365
+ return {};
116366
+ const result = {};
116367
+ for (const [key, value] of Object.entries(shape)) {
116368
+ const innerTypeName = getZodTypeName(value);
116369
+ if (innerTypeName === "ZodOptional" || innerTypeName === "optional" || innerTypeName === "ZodNullable" || innerTypeName === "nullable") {
116370
+ continue;
116371
+ }
116372
+ result[key] = generateExampleValue(value);
116373
+ }
116374
+ return result;
116375
+ }
116376
+ function generateExampleValue(schema) {
116377
+ if (!schema || !schema._def)
116378
+ return "...";
116379
+ const def = schema._def;
116380
+ const typeName = getZodTypeName(schema);
116381
+ switch (typeName) {
116382
+ case "ZodString":
116383
+ case "string":
116384
+ return "example";
116385
+ case "ZodNumber":
116386
+ case "number":
116387
+ return 0;
116388
+ case "ZodBoolean":
116389
+ case "boolean":
116390
+ return true;
116391
+ case "ZodLiteral":
116392
+ case "literal":
116393
+ return def.value;
116394
+ case "ZodEnum":
116395
+ case "enum": {
116396
+ if (Array.isArray(def.values) && def.values.length > 0)
116397
+ return def.values[0];
116398
+ if (def.entries && typeof def.entries === "object") {
116399
+ const values = Object.values(def.entries);
116400
+ return values.length > 0 ? values[0] : "example";
116401
+ }
116402
+ return "example";
116403
+ }
116404
+ case "ZodOptional":
116405
+ case "optional":
116406
+ case "ZodNullable":
116407
+ case "nullable":
116408
+ case "ZodDefault":
116409
+ case "default": {
116410
+ const inner = def.innerType ?? def.wrapped;
116411
+ return inner ? generateExampleValue(inner) : null;
116412
+ }
116413
+ case "ZodArray":
116414
+ case "array":
116415
+ return [];
116416
+ case "ZodObject":
116417
+ case "object":
116418
+ return generateExamplePropsFromZod(schema);
116419
+ case "ZodUnion":
116420
+ case "union": {
116421
+ const options = def.options;
116422
+ return options && options.length > 0 ? generateExampleValue(options[0]) : "...";
116423
+ }
116424
+ default:
116425
+ return "...";
116426
+ }
116427
+ }
116428
+ function findFirstStringProp(schema) {
116429
+ if (!schema || !schema._def)
116430
+ return null;
116431
+ const def = schema._def;
116432
+ const typeName = getZodTypeName(schema);
116433
+ if (typeName !== "ZodObject" && typeName !== "object")
116434
+ return null;
116435
+ const shape = typeof def.shape === "function" ? def.shape() : def.shape;
116436
+ if (!shape)
116437
+ return null;
116438
+ for (const [key, value] of Object.entries(shape)) {
116439
+ const innerTypeName = getZodTypeName(value);
116440
+ if (innerTypeName === "ZodOptional" || innerTypeName === "optional" || innerTypeName === "ZodNullable" || innerTypeName === "nullable") {
116441
+ continue;
116442
+ }
116443
+ if (innerTypeName === "ZodString" || innerTypeName === "string") {
116444
+ return key;
116445
+ }
116446
+ }
116447
+ return null;
116448
+ }
116449
+ function getZodTypeName(schema) {
116450
+ if (!schema || !schema._def)
116451
+ return "";
116452
+ const def = schema._def;
116453
+ return def.typeName ?? def.type ?? "";
116454
+ }
116455
+ function formatZodType(schema) {
116456
+ if (!schema || !schema._def)
116457
+ return "unknown";
116458
+ const def = schema._def;
116459
+ const typeName = getZodTypeName(schema);
116460
+ switch (typeName) {
116461
+ case "ZodString":
116462
+ case "string":
116463
+ return "string";
116464
+ case "ZodNumber":
116465
+ case "number":
116466
+ return "number";
116467
+ case "ZodBoolean":
116468
+ case "boolean":
116469
+ return "boolean";
116470
+ case "ZodLiteral":
116471
+ case "literal": {
116472
+ const litValues = def.values;
116473
+ const litValue = litValues?.[0] ?? def.value;
116474
+ return JSON.stringify(litValue);
116475
+ }
116476
+ case "ZodEnum":
116477
+ case "enum": {
116478
+ let values;
116479
+ if (Array.isArray(def.values)) {
116480
+ values = def.values;
116481
+ } else if (def.entries && typeof def.entries === "object") {
116482
+ values = Object.values(def.entries);
116483
+ } else {
116484
+ return "enum";
116485
+ }
116486
+ return values.map((v) => `"${v}"`).join(" | ");
116487
+ }
116488
+ case "ZodArray":
116489
+ case "array": {
116490
+ const inner = typeof def.element === "object" ? def.element : typeof def.type === "object" ? def.type : undefined;
116491
+ return inner ? `Array<${formatZodType(inner)}>` : "Array<unknown>";
116492
+ }
116493
+ case "ZodObject":
116494
+ case "object": {
116495
+ const shape = typeof def.shape === "function" ? def.shape() : def.shape;
116496
+ if (!shape)
116497
+ return "object";
116498
+ const props = Object.entries(shape).map(([key, value]) => {
116499
+ const innerTypeName = getZodTypeName(value);
116500
+ const isOptional = innerTypeName === "ZodOptional" || innerTypeName === "ZodNullable" || innerTypeName === "optional" || innerTypeName === "nullable";
116501
+ return `${key}${isOptional ? "?" : ""}: ${formatZodType(value)}`;
116502
+ }).join(", ");
116503
+ return `{ ${props} }`;
116504
+ }
116505
+ case "ZodOptional":
116506
+ case "optional":
116507
+ case "ZodNullable":
116508
+ case "nullable": {
116509
+ const inner = def.innerType ?? def.wrapped;
116510
+ return inner ? formatZodType(inner) : "unknown";
116511
+ }
116512
+ case "ZodUnion":
116513
+ case "union": {
116514
+ const options = def.options;
116515
+ return options ? options.map((opt) => formatZodType(opt)).join(" | ") : "unknown";
116516
+ }
116517
+ case "ZodRecord":
116518
+ case "record": {
116519
+ const keyType = def.keyType ?? undefined;
116520
+ const valueType = def.valueType ?? def.element ?? undefined;
116521
+ const keyStr = keyType ? formatZodType(keyType) : "string";
116522
+ const valueStr = valueType ? formatZodType(valueType) : "unknown";
116523
+ return `Record<${keyStr}, ${valueStr}>`;
116524
+ }
116525
+ case "ZodDefault":
116526
+ case "default": {
116527
+ const inner = def.innerType ?? def.wrapped;
116528
+ return inner ? formatZodType(inner) : "unknown";
116529
+ }
116530
+ default:
116531
+ return "unknown";
116532
+ }
116533
+ }
116534
+ function zodTypeName(def) {
116535
+ if (typeof def.type === "string")
116536
+ return def.type;
116537
+ if (typeof def.typeName === "string")
116538
+ return def.typeName;
116539
+ return "";
116540
+ }
116541
+ function normalizeTypeName(raw) {
116542
+ if (raw.startsWith("Zod")) {
116543
+ return raw.slice(3).toLowerCase();
116544
+ }
116545
+ return raw.toLowerCase();
116546
+ }
116547
+ function zodToJsonSchema3(schema, strict = false) {
116548
+ const def = schema._def;
116549
+ const kind = normalizeTypeName(zodTypeName(def));
116550
+ switch (kind) {
116551
+ case "string":
116552
+ return { type: "string" };
116553
+ case "number":
116554
+ return { type: "number" };
116555
+ case "boolean":
116556
+ return { type: "boolean" };
116557
+ case "literal": {
116558
+ const values = def.values;
116559
+ const value = values ? values[0] : def.value;
116560
+ return { const: value };
116561
+ }
116562
+ case "enum": {
116563
+ const entries = def.entries;
116564
+ const values = entries ? Object.values(entries) : def.values;
116565
+ return { enum: values ?? [] };
116566
+ }
116567
+ case "array": {
116568
+ const inner = def.element ?? def.type;
116569
+ return {
116570
+ type: "array",
116571
+ items: inner ? zodToJsonSchema3(inner, strict) : {}
116572
+ };
116573
+ }
116574
+ case "object": {
116575
+ const rawShape = def.shape;
116576
+ const shape = typeof rawShape === "function" ? rawShape() : rawShape;
116577
+ if (!shape) {
116578
+ if (strict) {
116579
+ return {
116580
+ type: "object",
116581
+ properties: {},
116582
+ required: [],
116583
+ additionalProperties: false
116584
+ };
116585
+ }
116586
+ return { type: "object" };
116587
+ }
116588
+ const properties = {};
116589
+ const required = [];
116590
+ for (const [key, value] of Object.entries(shape)) {
116591
+ const innerDef = value._def;
116592
+ const innerKind = normalizeTypeName(zodTypeName(innerDef));
116593
+ const isOptional = innerKind === "optional" || innerKind === "nullable";
116594
+ if (strict) {
116595
+ required.push(key);
116596
+ if (isOptional) {
116597
+ const unwrapped = zodToJsonSchema3(value, strict);
116598
+ properties[key] = { anyOf: [unwrapped, { type: "null" }] };
116599
+ } else {
116600
+ properties[key] = zodToJsonSchema3(value, strict);
116601
+ }
116602
+ } else {
116603
+ properties[key] = zodToJsonSchema3(value);
116604
+ if (!isOptional) {
116605
+ required.push(key);
116606
+ }
116607
+ }
116608
+ }
116609
+ return {
116610
+ type: "object",
116611
+ properties,
116612
+ required: required.length > 0 ? required : undefined,
116613
+ additionalProperties: false
116614
+ };
116615
+ }
116616
+ case "record": {
116617
+ const valueType = def.valueType;
116618
+ if (strict) {
116619
+ return {
116620
+ type: "object",
116621
+ properties: {},
116622
+ required: [],
116623
+ additionalProperties: false
116624
+ };
116625
+ }
116626
+ return {
116627
+ type: "object",
116628
+ additionalProperties: valueType ? zodToJsonSchema3(valueType) : true
116629
+ };
116630
+ }
116631
+ case "optional":
116632
+ case "nullable": {
116633
+ const inner = def.innerType;
116634
+ return inner ? zodToJsonSchema3(inner, strict) : {};
116635
+ }
116636
+ case "union": {
116637
+ const options = def.options;
116638
+ return options ? { anyOf: options.map((o) => zodToJsonSchema3(o, strict)) } : {};
116639
+ }
116640
+ case "any":
116641
+ case "unknown":
116642
+ if (strict) {
116643
+ return {
116644
+ type: "object",
116645
+ properties: {},
116646
+ required: [],
116647
+ additionalProperties: false
116648
+ };
116649
+ }
116650
+ return {};
116651
+ default:
116652
+ return {};
116653
+ }
116654
+ }
116655
+ var numericOrStateRef, comparisonOps, StateConditionSchema, ItemConditionSchema, IndexConditionSchema, SingleConditionSchema, VisibilityConditionSchema, StrictSingleConditionSchema, VisibilityConditionStrictSchema, WARNED_COMPUTED_MAX = 100, warnedComputedFns, ActionConfirmSchema, ActionOnSuccessSchema, ActionOnErrorSchema, ActionBindingSchema, ValidationCheckSchema, ValidationConfigSchema, DEFAULT_MODES, seedSchema, compositionActionSchema, probability, responseSchema;
116656
+ var init_dist2 = __esm(() => {
116657
+ init_chunk_FVP4K5MD();
116658
+ init_zod();
116659
+ init_zod();
116660
+ init_zod();
116661
+ init_zod();
116662
+ init_zod();
116663
+ init_zod();
116664
+ init_zod();
116665
+ numericOrStateRef = union3([
116666
+ number2(),
116667
+ object2({ $state: string2() })
116668
+ ]);
116669
+ comparisonOps = {
116670
+ eq: unknown().optional(),
116671
+ neq: unknown().optional(),
116672
+ gt: numericOrStateRef.optional(),
116673
+ gte: numericOrStateRef.optional(),
116674
+ lt: numericOrStateRef.optional(),
116675
+ lte: numericOrStateRef.optional(),
116676
+ not: literal2(true).optional()
116677
+ };
116678
+ StateConditionSchema = object2({
116679
+ $state: string2(),
116680
+ ...comparisonOps
116681
+ });
116682
+ ItemConditionSchema = object2({
116683
+ $item: string2(),
116684
+ ...comparisonOps
116685
+ });
116686
+ IndexConditionSchema = object2({
116687
+ $index: literal2(true),
116688
+ ...comparisonOps
116689
+ });
116690
+ SingleConditionSchema = union3([
116691
+ StateConditionSchema,
116692
+ ItemConditionSchema,
116693
+ IndexConditionSchema
116694
+ ]);
116695
+ VisibilityConditionSchema = lazy(() => union3([
116696
+ boolean(),
116697
+ SingleConditionSchema,
116698
+ array2(SingleConditionSchema),
116699
+ object2({ $and: array2(VisibilityConditionSchema) }),
116700
+ object2({ $or: array2(VisibilityConditionSchema) })
116701
+ ]));
116702
+ StrictSingleConditionSchema = union3([
116703
+ strictObject2({ $state: string2(), ...comparisonOps }),
116704
+ strictObject2({ $item: string2(), ...comparisonOps }),
116705
+ strictObject2({ $index: literal2(true), ...comparisonOps })
116706
+ ]);
116707
+ VisibilityConditionStrictSchema = lazy(() => union3([
116708
+ boolean(),
116709
+ StrictSingleConditionSchema,
116710
+ array2(StrictSingleConditionSchema),
116711
+ strictObject2({ $and: array2(VisibilityConditionStrictSchema) }),
116712
+ strictObject2({ $or: array2(VisibilityConditionStrictSchema) })
116713
+ ]));
116714
+ warnedComputedFns = /* @__PURE__ */ new Set;
116715
+ ActionConfirmSchema = object2({
116716
+ title: string2(),
116717
+ message: string2(),
116718
+ confirmLabel: string2().optional(),
116719
+ cancelLabel: string2().optional(),
116720
+ variant: _enum2(["default", "danger"]).optional()
116721
+ });
116722
+ ActionOnSuccessSchema = union3([
116723
+ object2({ navigate: string2() }),
116724
+ object2({ set: record2(string2(), unknown()) }),
116725
+ object2({
116726
+ action: string2(),
116727
+ params: record2(string2(), DynamicValueSchema).optional()
116728
+ })
116729
+ ]);
116730
+ ActionOnErrorSchema = union3([
116731
+ object2({ set: record2(string2(), unknown()) }),
116732
+ object2({
116733
+ action: string2(),
116734
+ params: record2(string2(), DynamicValueSchema).optional()
116735
+ })
116736
+ ]);
116737
+ ActionBindingSchema = object2({
116738
+ action: string2(),
116739
+ params: record2(string2(), DynamicValueSchema).optional(),
116740
+ confirm: ActionConfirmSchema.optional(),
116741
+ onSuccess: ActionOnSuccessSchema.optional(),
116742
+ onError: ActionOnErrorSchema.optional(),
116743
+ preventDefault: boolean().optional()
116744
+ });
116745
+ ValidationCheckSchema = object2({
116746
+ type: string2(),
116747
+ args: record2(string2(), DynamicValueSchema).optional(),
116748
+ message: string2()
116749
+ });
116750
+ ValidationConfigSchema = object2({
116751
+ checks: array2(ValidationCheckSchema).optional(),
116752
+ validateOn: _enum2(["change", "blur", "submit"]).optional(),
116753
+ enabled: VisibilityConditionSchema.optional()
116754
+ });
116755
+ DEFAULT_MODES = ["patch"];
116756
+ seedSchema = object2({
116757
+ root: string2().min(1),
116758
+ elements: record2(string2(), object2({
116759
+ type: string2(),
116760
+ props: record2(string2(), unknown()),
116761
+ children: array2(string2()).optional(),
116762
+ slots: record2(string2(), array2(string2())).optional(),
116763
+ on: record2(string2(), unknown()).optional(),
116764
+ visible: unknown().optional()
116765
+ }).strict()),
116766
+ state: record2(string2(), unknown()).optional()
116767
+ }).strict();
116768
+ compositionActionSchema = ActionBindingSchema.extend({
116769
+ params: record2(string2(), unknown()).optional(),
116770
+ onSuccess: unknown().optional(),
116771
+ onError: unknown().optional()
116772
+ }).strict();
116773
+ probability = number2().min(0).max(1);
116774
+ responseSchema = object2({
116775
+ answers: record2(string2(), object2({ type: literal2("choice"), choice: string2() })),
116776
+ providerMetadata: object2({
116777
+ typesafe: object2({ confidence: record2(string2(), probability) }).optional()
116778
+ }).optional(),
116779
+ usage: object2({ inputTokens: number2().int().nonnegative().optional() }).optional()
116780
+ });
116781
+ });
116782
+
116783
+ // node_modules/@json-render/chat/dist/index.mjs
116784
+ function normalizeTableRows(props) {
116785
+ if (!Array.isArray(props.rows) || !Array.isArray(props.headers))
116786
+ return props;
116787
+ const headers = props.headers.map((h) => normalizeKey(String(h)));
116788
+ const rows = props.rows.map((row) => {
116789
+ if (!row || typeof row !== "object" || Array.isArray(row))
116790
+ return row;
116791
+ const entries = Object.entries(row).map(([k, v]) => [normalizeKey(k), v]);
116792
+ const byKey = new Map(entries);
116793
+ const unmatched = entries.filter(([k]) => !headers.includes(k));
116794
+ const rest = [
116795
+ ...unmatched.filter(([k]) => !ID_KEYS.has(k)),
116796
+ ...unmatched.filter(([k]) => ID_KEYS.has(k))
116797
+ ];
116798
+ return headers.map((h) => byKey.has(h) ? byKey.get(h) : rest.shift()?.[1]);
116799
+ });
116800
+ return { ...props, rows };
116801
+ }
116802
+ function validateProps(elements, defs) {
116803
+ const issues = [];
116804
+ for (const [key, el] of Object.entries(elements)) {
116805
+ const def = defs[el.type];
116806
+ if (!def) {
116807
+ issues.push(`${key}: unknown component "${el.type}"`);
116808
+ continue;
116809
+ }
116810
+ const props = el.type === "Table" ? normalizeTableRows(el.props ?? {}) : el.props ?? {};
116811
+ const parsed = def.props.safeParse(props);
116812
+ if (!parsed.success) {
116813
+ for (const issue of parsed.error.issues)
116814
+ issues.push(`${key}.props.${issue.path.join(".")}: ${issue.message}`);
116815
+ } else {
116816
+ el.props = parsed.data;
116817
+ }
116818
+ }
116819
+ return issues;
116820
+ }
116821
+ function validateStructure(spec, elements, defs) {
116822
+ const issues = [];
116823
+ const root = elements[spec.root];
116824
+ if (!root)
116825
+ issues.push(`root "${spec.root}" is not an element`);
116826
+ else if (root.type !== "Card")
116827
+ issues.push("root must be a Card");
116828
+ for (const [key, el] of Object.entries(elements)) {
116829
+ if (el.children.length && !defs[el.type]?.slots?.length)
116830
+ issues.push(`${key}: ${el.type} cannot have children`);
116831
+ for (const childKey of el.children) {
116832
+ const child = elements[childKey];
116833
+ if (!child) {
116834
+ issues.push(`${key}: missing child "${childKey}"`);
116835
+ continue;
116836
+ }
116837
+ if (el.type === "Fields" && child.type !== "Field")
116838
+ issues.push(`${key}: Fields only holds Field elements`);
116839
+ if (el.type === "Actions" && !["Button", "LinkButton"].includes(child.type))
116840
+ issues.push(`${key}: Actions only holds Button and LinkButton elements`);
116841
+ }
116842
+ if (el.type === "Table") {
116843
+ const width = el.props.headers.length;
116844
+ el.props.rows.forEach((row, i) => {
116845
+ if (row.length !== width)
116846
+ issues.push(`${key}: row ${i} has ${row.length} cells, expected ${width}`);
116847
+ });
116848
+ }
116849
+ if (el.type === "Chart" && el.props.chart.type !== "pie") {
116850
+ const count = el.props.chart.categories.length;
116851
+ for (const series of el.props.chart.series)
116852
+ if (series.values.length !== count)
116853
+ issues.push(`${key}: series "${series.name}" has ${series.values.length} values, expected ${count}`);
116854
+ }
116855
+ }
116856
+ return issues;
116857
+ }
116858
+ function validateLimits(elements, limits) {
116859
+ const issues = [];
116860
+ const all = Object.entries(elements);
116861
+ const count = (type) => all.filter(([, el]) => el.type === type).length;
116862
+ const over = (value, max) => max !== undefined && value > max;
116863
+ if (over(count("Table"), limits.tables))
116864
+ issues.push(`at most ${limits.tables} Table per message`);
116865
+ if (over(count("Chart"), limits.charts))
116866
+ issues.push(`at most ${limits.charts} Chart per message`);
116867
+ for (const [key, el] of all) {
116868
+ const p = el.props;
116869
+ if (el.type === "Fields" && over(el.children.length, limits.fields))
116870
+ issues.push(`${key}: at most ${limits.fields} fields`);
116871
+ if (el.type === "Table") {
116872
+ if (over(p.rows.length + 1, limits.tableRows))
116873
+ issues.push(`${key}: at most ${limits.tableRows} rows including the header`);
116874
+ if (over(p.headers.length, limits.tableColumns))
116875
+ issues.push(`${key}: at most ${limits.tableColumns} columns`);
116876
+ }
116877
+ if (el.type === "Chart") {
116878
+ const c = p.chart;
116879
+ if (over(p.title.length, limits.chartTitle))
116880
+ issues.push(`${key}: title longer than ${limits.chartTitle} characters`);
116881
+ const labels = c.type === "pie" ? c.segments.map((s) => s.label) : [...c.categories, ...c.series.map((s) => s.name)];
116882
+ for (const label of labels)
116883
+ if (over(label.length, limits.chartLabel))
116884
+ issues.push(`${key}: label "${label}" longer than ${limits.chartLabel} characters`);
116885
+ const groups = c.type === "pie" ? c.segments.length : c.series.length;
116886
+ if (over(groups, limits.chartSeries))
116887
+ issues.push(`${key}: at most ${limits.chartSeries} series or segments`);
116888
+ if (c.type !== "pie" && over(c.categories.length, limits.chartPoints))
116889
+ issues.push(`${key}: at most ${limits.chartPoints} categories`);
116890
+ }
116891
+ }
116892
+ return issues;
116893
+ }
116894
+ function toChild(key, elements) {
116895
+ const el = elements[key];
116896
+ const p = el.props;
116897
+ const children = () => el.children.map((k) => elements[k]);
116898
+ switch (el.type) {
116899
+ case "Section":
116900
+ return section(el.children.map((k) => toChild(k, elements)));
116901
+ case "Card":
116902
+ return section([
116903
+ ...p.title ? [text2(p.title, "bold")] : [],
116904
+ ...p.subtitle ? [text2(p.subtitle, "muted")] : [],
116905
+ ...el.children.map((k) => toChild(k, elements))
116906
+ ]);
116907
+ case "Text":
116908
+ return text2(p.content, p.style ?? undefined);
116909
+ case "Divider":
116910
+ return divider();
116911
+ case "Image":
116912
+ return image(p.url, p.alt);
116913
+ case "Fields":
116914
+ return fields(children().map((f) => field2(f.props.label, f.props.value)));
116915
+ case "Table":
116916
+ return table({
116917
+ headers: p.headers,
116918
+ rows: p.rows,
116919
+ align: p.align ?? undefined,
116920
+ caption: p.caption ?? undefined
116921
+ });
116922
+ case "Chart": {
116923
+ const c = p.chart;
116924
+ return chart({
116925
+ title: p.title,
116926
+ chart: c.type === "pie" ? { type: "pie", segments: c.segments } : {
116927
+ type: c.type,
116928
+ categories: c.categories,
116929
+ xLabel: c.xLabel ?? undefined,
116930
+ yLabel: c.yLabel ?? undefined,
116931
+ series: c.series.map((s) => ({
116932
+ name: s.name,
116933
+ data: s.values.map((value, i) => ({
116934
+ label: c.categories[i],
116935
+ value
116936
+ }))
116937
+ }))
116938
+ }
116939
+ });
116940
+ }
116941
+ case "Actions":
116942
+ return actions(children().map((b) => b.type === "LinkButton" ? linkButton({ label: b.props.label, url: b.props.url }) : button({
116943
+ id: b.props.id,
116944
+ label: b.props.label,
116945
+ style: b.props.style ?? undefined,
116946
+ value: b.props.value ?? undefined
116947
+ })));
116948
+ default:
116949
+ throw new CardSpecError([`${key}: ${el.type} cannot be nested here`]);
116950
+ }
116951
+ }
116952
+ function materialize(spec, maxElements) {
116953
+ const source = spec.elements ?? {};
116954
+ const stateModel = spec.state ?? {};
116955
+ const out = {};
116956
+ const missing = [];
116957
+ const seen = /* @__PURE__ */ new Set;
116958
+ let budget = maxElements;
116959
+ let overflow = false;
116960
+ const spend = () => {
116961
+ if (budget <= 0) {
116962
+ overflow = true;
116963
+ return false;
116964
+ }
116965
+ budget -= 1;
116966
+ return true;
116967
+ };
116968
+ const itemsAt = (repeat, ctx) => {
116969
+ const path = resolveRepeatStatePath(repeat.statePath, ctx.repeatBasePath);
116970
+ const items = path ? getByPath(stateModel, path) : undefined;
116971
+ return { path: path ?? "", items: Array.isArray(items) ? items : [] };
116972
+ };
116973
+ const itemContext = (path, item, index) => ({
116974
+ stateModel,
116975
+ repeatItem: item,
116976
+ repeatIndex: index,
116977
+ repeatBasePath: resolveRepeatItemStatePath(path, index)
116978
+ });
116979
+ const visit = (key, outKey, ctx) => {
116980
+ const el = source[key];
116981
+ if (!el?.type) {
116982
+ missing.push(key);
116983
+ return false;
116984
+ }
116985
+ if (seen.has(outKey))
116986
+ return false;
116987
+ const { container, itemFilter } = el.repeat && ctx.repeatIndex === undefined ? splitRepeatVisibility(el.visible) : { container: el.visible, itemFilter: undefined };
116988
+ if (container !== undefined && !evaluateVisibility(container, ctx))
116989
+ return false;
116990
+ if (!spend())
116991
+ return false;
116992
+ seen.add(outKey);
116993
+ const props = el.props ?? {};
116994
+ const childKeys = el.children ?? [];
116995
+ const children = [];
116996
+ const repeat = el.repeat;
116997
+ const keep = (path, item, index) => itemFilter === undefined || evaluateVisibility(itemFilter, itemContext(path, item, index));
116998
+ if (repeat && el.type === "Table" && Array.isArray(props.rows)) {
116999
+ const { path, items } = itemsAt(repeat, ctx);
117000
+ const rows = [];
117001
+ for (let index = 0;index < items.length && !overflow; index++) {
117002
+ if (!keep(path, items[index], index))
117003
+ continue;
117004
+ const itemCtx = itemContext(path, items[index], index);
117005
+ for (const row of props.rows) {
117006
+ if (!spend())
117007
+ break;
117008
+ rows.push(resolveElementProps({ row }, itemCtx).row);
117009
+ }
117010
+ }
117011
+ out[outKey] = {
117012
+ type: el.type,
117013
+ props: { ...resolveElementProps(props, ctx), rows },
117014
+ children: []
117015
+ };
117016
+ return true;
117017
+ }
117018
+ if (repeat) {
117019
+ const { path, items } = itemsAt(repeat, ctx);
117020
+ const scope = outKey === key ? "" : `${outKey}.`;
117021
+ for (let index = 0;index < items.length && !overflow; index++) {
117022
+ if (!keep(path, items[index], index))
117023
+ continue;
117024
+ const itemCtx = itemContext(path, items[index], index);
117025
+ for (const child of childKeys) {
117026
+ const childOut = `${child}#${scope}${index}`;
117027
+ if (visit(child, childOut, itemCtx))
117028
+ children.push(childOut);
117029
+ }
117030
+ }
117031
+ } else {
117032
+ const suffix = outKey.slice(key.length);
117033
+ for (const child of childKeys)
117034
+ if (visit(child, child + suffix, ctx))
117035
+ children.push(child + suffix);
117036
+ }
117037
+ out[outKey] = {
117038
+ type: el.type,
117039
+ props: resolveElementProps(props, ctx),
117040
+ children
117041
+ };
117042
+ return true;
117043
+ };
117044
+ if (spec.root)
117045
+ visit(spec.root, spec.root, { stateModel });
117046
+ return { elements: out, missing, overflow };
117047
+ }
117048
+ function prune(elements, rootKey) {
117049
+ const kept = /* @__PURE__ */ new Map;
117050
+ const visit = (key) => {
117051
+ const cached = kept.get(key);
117052
+ if (cached !== undefined)
117053
+ return cached;
117054
+ kept.set(key, false);
117055
+ const el = elements[key];
117056
+ if (!el)
117057
+ return false;
117058
+ const accepts = ACCEPTS[el.type];
117059
+ el.children = el.children.filter((child) => elements[child] !== undefined && (!accepts || accepts.includes(elements[child].type)) && visit(child));
117060
+ const keep = key === rootKey || (GROUPS.has(el.type) ? el.children.length > 0 : el.type !== "Card" || hasContent(el));
117061
+ kept.set(key, keep);
117062
+ return keep;
117063
+ };
117064
+ visit(rootKey);
117065
+ }
117066
+ function buildCard(root, elements, keys) {
117067
+ return card({
117068
+ title: root.props.title ?? undefined,
117069
+ subtitle: root.props.subtitle ?? undefined,
117070
+ imageUrl: root.props.imageUrl ?? undefined,
117071
+ children: keys.map((k) => toChild(k, elements))
117072
+ });
117073
+ }
117074
+ function toCard(spec, options = {}) {
117075
+ const defs = options.components ?? standardComponentDefinitions;
117076
+ if (!spec || typeof spec.root !== "string" || !spec.elements)
117077
+ throw new CardSpecError(["spec needs a root and elements"]);
117078
+ const maxElements = options.maxElements ?? DEFAULT_MAX_ELEMENTS;
117079
+ const { elements, missing, overflow } = materialize(spec, maxElements);
117080
+ if (overflow)
117081
+ throw new CardSpecError([
117082
+ `the spec expands to more than ${maxElements} elements and table rows`
117083
+ ]);
117084
+ let issues = validateProps(elements, defs);
117085
+ if (!issues.length)
117086
+ issues = [
117087
+ ...missing.map((key) => `missing element "${key}"`),
117088
+ ...validateStructure(spec, elements, defs)
117089
+ ];
117090
+ if (!issues.length) {
117091
+ prune(elements, spec.root);
117092
+ if (!hasContent(elements[spec.root]))
117093
+ issues.push("the Card needs a title, an image or at least one child");
117094
+ }
117095
+ if (!issues.length && options.limits)
117096
+ issues = validateLimits(elements, options.limits);
117097
+ if (issues.length)
117098
+ throw new CardSpecError(issues);
117099
+ const root = elements[spec.root];
117100
+ return buildCard(root, elements, root.children);
117101
+ }
117102
+ var schema, displayText, pieChart, seriesChart, standardComponentDefinitions, card = (options) => ({ type: "card", ...options }), text2 = (content, style) => ({ type: "text", content, style }), image = (url, alt) => ({
117103
+ type: "image",
117104
+ url,
117105
+ alt
117106
+ }), divider = () => ({ type: "divider" }), section = (children) => ({
117107
+ type: "section",
117108
+ children
117109
+ }), field2 = (label, value) => ({
117110
+ type: "field",
117111
+ label,
117112
+ value
117113
+ }), fields = (children) => ({
117114
+ type: "fields",
117115
+ children
117116
+ }), table = (options) => ({
117117
+ type: "table",
117118
+ ...options
117119
+ }), chart = (options) => ({
117120
+ type: "chart",
117121
+ ...options
117122
+ }), button = (options) => ({ type: "button", ...options }), linkButton = (options) => ({ type: "link-button", ...options }), actions = (children) => ({ type: "actions", children }), DEFAULT_MAX_ELEMENTS = 1000, CardSpecError, normalizeKey = (value) => value.toLowerCase().replace(/[^a-z0-9]/g, ""), ID_KEYS, ACCEPTS, GROUPS, hasContent = (el) => Boolean(el.props.title || el.props.subtitle || el.props.imageUrl || el.children.length);
117123
+ var init_dist3 = __esm(() => {
117124
+ init_dist2();
117125
+ init_zod();
117126
+ init_dist2();
117127
+ init_dist2();
117128
+ schema = defineSchema((s) => ({
117129
+ spec: s.object({
117130
+ root: s.string(),
117131
+ elements: s.record(s.object({
117132
+ type: s.ref("catalog.components"),
117133
+ props: s.propsOf("catalog.components"),
117134
+ children: s.array(s.string()),
117135
+ visible: { ...s.any(), ...s.optional() },
117136
+ repeat: { ...s.any(), ...s.optional() }
117137
+ }))
117138
+ }),
117139
+ catalog: s.object({
117140
+ components: s.map({
117141
+ props: s.zod(),
117142
+ slots: s.array(s.string()),
117143
+ description: s.string(),
117144
+ example: s.any()
117145
+ })
117146
+ })
117147
+ }), {
117148
+ defaultRules: [
117149
+ "The root element MUST be a Card. Every other element is a descendant of it. To group items inside the message, use Section, not another Card.",
117150
+ "Messages are static once posted. $state, $item, $index, $template, repeat and visible are resolved when the card is built, but there are no inputs, so do not use $bindState or $bindItem.",
117151
+ "Pick components by the shape of the data: Fields for a few key numbers, Table for row data, Chart for a trend or a share of a whole, Actions for next steps.",
117152
+ 'For a Table backed by state, set rows to { "$state": "/path" } where the path holds an array of rows (arrays or objects with one value per header).',
117153
+ "Text content uses markdown: **bold**, _italic_, `code` and [label](https://url). Do not use headings inside Text.",
117154
+ "Field elements MUST be children of a Fields element. Button and LinkButton elements MUST be children of an Actions element.",
117155
+ "Every series in a bar, line or area Chart has exactly one value per category, in category order.",
117156
+ 'Every element MUST include a "children" array. Leaf elements use "children": [].'
117157
+ ]
117158
+ });
117159
+ displayText = union3([string2(), number2()]).transform(String);
117160
+ pieChart = object2({
117161
+ type: literal2("pie"),
117162
+ segments: array2(object2({ label: string2().min(1), value: number2().positive() })).min(1)
117163
+ });
117164
+ seriesChart = object2({
117165
+ type: _enum2(["bar", "line", "area"]),
117166
+ categories: array2(string2().min(1)).min(1),
117167
+ series: array2(object2({ name: string2().min(1), values: array2(number2()) })).min(1),
117168
+ xLabel: string2().nullish(),
117169
+ yLabel: string2().nullish()
117170
+ });
117171
+ standardComponentDefinitions = {
117172
+ Card: {
117173
+ props: object2({
117174
+ title: string2().nullish(),
117175
+ subtitle: string2().nullish(),
117176
+ imageUrl: string2().url().nullish()
117177
+ }),
117178
+ slots: ["default"],
117179
+ description: "Root of a message. Title renders as the card header, subtitle as secondary text.",
117180
+ example: { title: "Weekly deploys", subtitle: "Oct 27 to Nov 2" }
117181
+ },
117182
+ Section: {
117183
+ props: object2({}),
117184
+ slots: ["default"],
117185
+ description: "Groups related elements.",
117186
+ example: {}
117187
+ },
117188
+ Text: {
117189
+ props: object2({
117190
+ content: string2().min(1),
117191
+ style: _enum2(["plain", "bold", "muted"]).nullish()
117192
+ }),
117193
+ slots: [],
117194
+ description: "A paragraph of markdown text. Use muted for footnotes.",
117195
+ example: { content: "Deploys are **up 12%** week over week." }
117196
+ },
117197
+ Fields: {
117198
+ props: object2({}),
117199
+ slots: ["default"],
117200
+ description: "Grid of label and value pairs. Children are Field elements.",
117201
+ example: {}
117202
+ },
117203
+ Field: {
117204
+ props: object2({ label: string2().min(1), value: displayText }),
117205
+ slots: [],
117206
+ description: "One label and value pair inside Fields. Good for KPIs.",
117207
+ example: { label: "Deploys", value: "1,284" }
117208
+ },
117209
+ Table: {
117210
+ props: object2({
117211
+ headers: array2(string2()).min(1),
117212
+ rows: array2(array2(displayText)),
117213
+ align: array2(_enum2(["left", "center", "right"])).nullish(),
117214
+ caption: string2().nullish()
117215
+ }),
117216
+ slots: [],
117217
+ description: "Table for row data. Every row has one cell per header. Right-align numeric columns.",
117218
+ example: {
117219
+ headers: ["Project", "Deploys"],
117220
+ rows: [
117221
+ ["web", "412"],
117222
+ ["api", "203"]
117223
+ ],
117224
+ align: ["left", "right"]
117225
+ }
117226
+ },
117227
+ Chart: {
117228
+ props: object2({
117229
+ title: string2().min(1),
117230
+ chart: union3([pieChart, seriesChart])
117231
+ }),
117232
+ slots: [],
117233
+ description: "Chart. pie for shares of a whole, bar, line or area for series over categories.",
117234
+ example: {
117235
+ title: "Deploys per day",
117236
+ chart: {
117237
+ type: "bar",
117238
+ categories: ["Mon", "Tue", "Wed"],
117239
+ series: [{ name: "Deploys", values: [180, 210, 195] }]
117240
+ }
117241
+ }
117242
+ },
117243
+ Divider: {
117244
+ props: object2({}),
117245
+ slots: [],
117246
+ description: "Separator between groups.",
117247
+ example: {}
117248
+ },
117249
+ Image: {
117250
+ props: object2({ url: string2().url(), alt: string2().min(1) }),
117251
+ slots: [],
117252
+ description: "Image from a public https URL.",
117253
+ example: { url: "https://picsum.photos/600/300", alt: "Preview" }
117254
+ },
117255
+ Actions: {
117256
+ props: object2({}),
117257
+ slots: ["default"],
117258
+ description: "Row of Button and LinkButton elements.",
117259
+ example: {}
117260
+ },
117261
+ Button: {
117262
+ props: object2({
117263
+ id: string2().min(1),
117264
+ label: string2().min(1),
117265
+ style: _enum2(["primary", "danger", "default"]).nullish(),
117266
+ value: string2().nullish()
117267
+ }),
117268
+ slots: [],
117269
+ description: "Interactive button. id is the action id the bot handles with onAction.",
117270
+ example: { id: "approve", label: "Approve", style: "primary" }
117271
+ },
117272
+ LinkButton: {
117273
+ props: object2({ label: string2().min(1), url: string2().url() }),
117274
+ slots: [],
117275
+ description: "Button that opens a URL.",
117276
+ example: { label: "Open dashboard", url: "https://vercel.com" }
117277
+ }
117278
+ };
117279
+ CardSpecError = class extends Error {
117280
+ constructor(issues) {
117281
+ super(issues.join(`
117282
+ `));
117283
+ this.issues = issues;
117284
+ this.name = "CardSpecError";
117285
+ }
117286
+ };
117287
+ ID_KEYS = /* @__PURE__ */ new Set(["id", "key", "uuid"]);
117288
+ ACCEPTS = {
117289
+ Fields: ["Field"],
117290
+ Actions: ["Button", "LinkButton"]
117291
+ };
117292
+ GROUPS = /* @__PURE__ */ new Set(["Fields", "Actions", "Section"]);
117293
+ });
117294
+
117295
+ // src/integrations/cards/index.ts
117296
+ function renderCard(spec) {
117297
+ let card;
117298
+ try {
117299
+ card = toCard(spec, { components: chatCardComponents, limits: CARD_LIMITS });
117300
+ } catch (error) {
117301
+ if (error instanceof CardSpecError)
117302
+ return { issues: error.issues };
117303
+ throw error;
117304
+ }
117305
+ const issues = cardChildren(card).filter((child) => child.type === "table").flatMap((table) => {
117306
+ const chars = [table.headers, ...table.rows].flat().reduce((sum, cell) => sum + cell.length, 0);
117307
+ return chars > TABLE_MAX_CELL_CHARS ? [`Table: ${chars} characters in its cells, at most ${TABLE_MAX_CELL_CHARS}`] : [];
117308
+ });
117309
+ return issues.length ? { issues } : { card };
117310
+ }
117311
+ function cardChildren(card) {
117312
+ return card.children.flatMap((child) => child.type === "section" ? [child, ...cardChildren(child)] : [child]);
117313
+ }
117314
+ function cardIssuesMessage(issues) {
117315
+ return `Invalid card spec. Fix it and retry:
117316
+ ${issues.map((issue) => `- ${issue}`).join(`
117317
+ `)}`;
117318
+ }
117319
+ async function cardToSlack(card) {
117320
+ const { cardToBlockKit, cardToFallbackText } = await import("./index-b24j7t2m.js");
117321
+ const issues = cardChildren(card).flatMap((child) => {
117322
+ const native = NATIVE_SLACK_BLOCKS[child.type];
117323
+ if (!native)
117324
+ return [];
117325
+ const [block] = cardToBlockKit({ type: "card", children: [child] });
117326
+ return block && native.includes(String(block.type)) ? [] : [`${child.type === "table" ? "Table" : "Chart"}: Slack cannot render it natively`];
117327
+ });
117328
+ if (issues.length)
117329
+ return { issues };
117330
+ return {
117331
+ blocks: cardToBlockKit(card),
117332
+ text: cardToFallbackText(card)
117333
+ };
117334
+ }
117335
+ async function renderCardFor(adapter, spec) {
117336
+ const rendered = renderCard(spec);
117337
+ if ("issues" in rendered || adapter !== "slack")
117338
+ return rendered;
117339
+ const slack = await cardToSlack(rendered.card);
117340
+ return "issues" in slack ? slack : rendered;
117341
+ }
117342
+ function slackFallbackText(message, cardText) {
117343
+ return [message, cardText].filter(Boolean).join(`
117344
+
117345
+ `);
117346
+ }
117347
+ var _button, standard, chatCardComponents, CARD_LIMITS, TABLE_MAX_CELL_CHARS = 1e4, catalogLines, CARD_RULES = 'Every element has "children" (leaves use []). Field goes inside Fields, LinkButton inside Actions. A bar, line or area Chart has one value per category per series; a pie Chart uses {"type":"pie","segments":[{"label","value"}]}.', cardSpecInputSchema, NATIVE_SLACK_BLOCKS;
117348
+ var init_cards = __esm(() => {
117349
+ init_dist3();
117350
+ init_zod();
117351
+ ({ Button: _button, ...standard } = standardComponentDefinitions);
117352
+ chatCardComponents = {
117353
+ ...standard,
117354
+ Actions: { ...standard.Actions, description: "Row of LinkButton elements." }
117355
+ };
117356
+ CARD_LIMITS = {
117357
+ tables: 1,
117358
+ charts: 2,
117359
+ fields: 10,
117360
+ tableRows: 101,
117361
+ tableColumns: 20,
117362
+ chartTitle: 50,
117363
+ chartLabel: 20,
117364
+ chartSeries: 12,
117365
+ chartPoints: 20
117366
+ };
117367
+ catalogLines = Object.entries(chatCardComponents).map(([name, def]) => `${name}: ${def.description} Props e.g. ${JSON.stringify(def.example)}.`).join(" ");
117368
+ cardSpecInputSchema = looseObject({
117369
+ root: string2().min(1).describe("Id of the root element. It must be a Card."),
117370
+ elements: record2(string2(), unknown()).describe('Map of element id to { type, props, children: [ids] }. Example: {"root":"c","elements":{"c":{"type":"Card","props":{"title":"Deploy"},"children":["f"]},"f":{"type":"Fields","props":{},"children":["f1"]},"f1":{"type":"Field","props":{"label":"Status","value":"green"},"children":[]}}}')
117371
+ }).describe(`Optional json-render card spec, rendered as a native card. Use it for structured results: key figures, a table, up to ${CARD_LIMITS.charts} charts, links. At most ${CARD_LIMITS.tables} table, of up to ${CARD_LIMITS.tableRows - 1} rows, ${CARD_LIMITS.tableColumns} columns and ${TABLE_MAX_CELL_CHARS} characters in all. ${CARD_RULES} Components: ${catalogLines}`);
117372
+ NATIVE_SLACK_BLOCKS = {
117373
+ table: ["table", "data_table"],
117374
+ chart: ["data_visualization"]
117375
+ };
117376
+ });
117377
+
115214
117378
  // src/tools/chat-post.ts
115215
117379
  var registerChatPostTool = (server) => {
115216
117380
  createToolRegistrar(server)("chat-post", {
115217
117381
  title: "Post to a chat thread or channel",
115218
- 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.",
117382
+ 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.",
115219
117383
  annotations: { openWorldHint: true },
115220
117384
  inputSchema: object2({
115221
117385
  adapter: _enum2(CHAT_SDK_ADAPTER_NAMES).describe("Chat SDK adapter name."),
115222
117386
  threadId: string2().min(1).optional().describe("Full SDK thread id, such as telegram:12345 or slack:C123:1700000000.000100."),
115223
117387
  channelId: string2().min(1).optional().describe("Full SDK channel id, such as slack:C123. Ignored when threadId is set."),
115224
- text: string2().min(1).max(20000).describe("Markdown text to post."),
117388
+ text: string2().min(1).max(20000).optional().describe("Markdown text to post. Required unless card is given."),
117389
+ card: cardSpecInputSchema.optional(),
115225
117390
  attachments: chatAttachmentsSchema
115226
117391
  }),
115227
117392
  outputSchema: swarmToolOutputSchema({
@@ -115232,17 +117397,25 @@ var registerChatPostTool = (server) => {
115232
117397
  channelId: string2().optional(),
115233
117398
  unsentFiles: array2(looseObject({ name: string2().optional(), reason: string2().optional() })).optional()
115234
117399
  })
115235
- }, async ({ adapter, threadId, channelId, text, attachments }, requestInfo) => {
117400
+ }, async ({ adapter, threadId, channelId, text, card, attachments }, requestInfo) => {
115236
117401
  const data = { yourAgentId: requestInfo.agentId };
115237
117402
  const target = threadId ?? channelId;
115238
117403
  if (!target)
115239
117404
  return toolErr("Give a threadId or a channelId.", { data });
117405
+ if (!text && !card)
117406
+ return toolErr("Provide text or a card.", { data });
115240
117407
  if (adapterOfChatId(target) !== adapter) {
115241
117408
  return toolErr(`The id ${target} does not belong to the ${adapter} adapter.`, { data });
115242
117409
  }
115243
117410
  if (!await canUseChatVerb(requestInfo, "integration.chat.post")) {
115244
117411
  return toolErr("Permission denied. Only the lead can post outside the thread of its task. Use chat-reply for the thread of your current task.", { data });
115245
117412
  }
117413
+ const rendered = card ? await renderCardFor(adapter, card) : undefined;
117414
+ if (rendered && "issues" in rendered) {
117415
+ return toolErr(cardIssuesMessage(rendered.issues), {
117416
+ data: { ...data, issues: rendered.issues }
117417
+ });
117418
+ }
115246
117419
  const resolved = await resolveChatAttachmentRefs(attachments ?? [], requestInfo.sourceTaskId, requestInfo.agentId);
115247
117420
  if ("error" in resolved)
115248
117421
  return toolErr(resolved.error, { data });
@@ -115250,7 +117423,8 @@ var registerChatPostTool = (server) => {
115250
117423
  const sent = await postChatMessage({
115251
117424
  adapter,
115252
117425
  ...threadId ? { threadId } : { channelId },
115253
- text,
117426
+ text: text ?? [],
117427
+ card: rendered?.card,
115254
117428
  taskId: requestInfo.sourceTaskId,
115255
117429
  files: resolved.files
115256
117430
  });
@@ -115272,6 +117446,7 @@ var registerChatPostTool = (server) => {
115272
117446
  };
115273
117447
  var init_chat_post = __esm(() => {
115274
117448
  init_zod();
117449
+ init_cards();
115275
117450
  init_config();
115276
117451
  init_logger();
115277
117452
  init_outbound2();
@@ -115355,10 +117530,11 @@ var init_chat_read_thread = __esm(() => {
115355
117530
  var registerChatReplyTool = (server) => {
115356
117531
  createToolRegistrar(server)("chat-reply", {
115357
117532
  title: "Reply in the chat thread of this task",
115358
- description: "Post a message to the Telegram, Slack, Discord or Teams thread your current task came from. Works only on a task whose contextKey starts with task:chat-sdk:. The task's final output is posted to the thread automatically when the task ends, so use this only for a question to the user, a short progress note on long work, or to send files (attachments). Markdown is supported; long text is split into several messages. When the final output of a task is posted, the files attached to that task go with it.",
117533
+ description: "Post a message to the Telegram, Slack, Discord or Teams thread your current task came from. Works only on a task whose contextKey starts with task:chat-sdk:. The task's final output is posted to the thread automatically when the task ends, so use this only for a question to the user, a short progress note on long work, or to send files (attachments). Markdown is supported; long text is split into several messages. When the final output of a task is posted, the files attached to that task go with it. For a structured result (key figures, a table, charts, links), send a `card`; it posts after the text as a native card.",
115359
117534
  annotations: { openWorldHint: true },
115360
117535
  inputSchema: object2({
115361
- text: string2().min(1).max(20000).describe("Markdown text to post to the thread."),
117536
+ text: string2().min(1).max(20000).optional().describe("Markdown text to post to the thread. Required unless card is given."),
117537
+ card: cardSpecInputSchema.optional(),
115362
117538
  attachments: chatAttachmentsSchema
115363
117539
  }),
115364
117540
  outputSchema: swarmToolOutputSchema({
@@ -115368,10 +117544,12 @@ var registerChatReplyTool = (server) => {
115368
117544
  threadId: string2().optional(),
115369
117545
  unsentFiles: array2(looseObject({ name: string2().optional(), reason: string2().optional() })).optional()
115370
117546
  })
115371
- }, async ({ text, attachments }, requestInfo) => {
117547
+ }, async ({ text, card, attachments }, requestInfo) => {
115372
117548
  if (!requestInfo.agentId)
115373
117549
  return toolErr("Agent ID not found.");
115374
117550
  const data = { yourAgentId: requestInfo.agentId };
117551
+ if (!text && !card)
117552
+ return toolErr("Provide text or a card.", { data });
115375
117553
  const task = requestInfo.sourceTaskId ? await getTaskById2(requestInfo.sourceTaskId) : await getAgentCurrentTask2(requestInfo.agentId);
115376
117554
  if (!task)
115377
117555
  return toolErr("No current task found for chat-reply.", { data });
@@ -115382,6 +117560,12 @@ var registerChatReplyTool = (server) => {
115382
117560
  if (!thread) {
115383
117561
  return toolErr(`Task ${task.id} did not come from a chat thread (no task:chat-sdk contextKey). Use the tool of the channel the task came from.`, { data });
115384
117562
  }
117563
+ const rendered = card ? await renderCardFor(thread.adapter, card) : undefined;
117564
+ if (rendered && "issues" in rendered) {
117565
+ return toolErr(cardIssuesMessage(rendered.issues), {
117566
+ data: { ...data, issues: rendered.issues }
117567
+ });
117568
+ }
115385
117569
  const resolved = await resolveChatAttachmentRefs(attachments ?? [], task.id, requestInfo.agentId);
115386
117570
  if ("error" in resolved)
115387
117571
  return toolErr(resolved.error, { data });
@@ -115389,7 +117573,8 @@ var registerChatReplyTool = (server) => {
115389
117573
  const sent = await postChatMessage({
115390
117574
  adapter: thread.adapter,
115391
117575
  threadId: thread.threadId,
115392
- text,
117576
+ text: text ?? [],
117577
+ card: rendered?.card,
115393
117578
  taskId: task.id,
115394
117579
  files: resolved.files,
115395
117580
  replyToMessageId: task.mentionMessageId
@@ -115412,6 +117597,7 @@ var registerChatReplyTool = (server) => {
115412
117597
  var init_chat_reply = __esm(() => {
115413
117598
  init_zod();
115414
117599
  init_db4();
117600
+ init_cards();
115415
117601
  init_logger();
115416
117602
  init_outbound2();
115417
117603
  init_outbound_files();
@@ -115547,7 +117733,7 @@ var init_create_channel = __esm(() => {
115547
117733
  init_zod();
115548
117734
  init_db4();
115549
117735
  init_utils();
115550
- init_types4();
117736
+ init_types5();
115551
117737
  ChannelOutputSchema = looseObject({
115552
117738
  id: string2().optional(),
115553
117739
  name: string2().optional(),
@@ -115664,6 +117850,9 @@ function executeReadOnlyQuery(sql, params = [], maxRows) {
115664
117850
  function isDbQueryBoundedEnabled(env = process.env) {
115665
117851
  return isEnvFlagEnabled("DB_QUERY_BOUNDED_ENABLED", true, env);
115666
117852
  }
117853
+ function isDbQueryWorkerPoolEnabled(env = process.env) {
117854
+ return isEnvFlagEnabled("DB_QUERY_WORKER_POOL_ENABLED", true, env);
117855
+ }
115667
117856
  function readPositiveIntEnv(key, defaultValue, env = process.env, maxValue = Number.MAX_SAFE_INTEGER) {
115668
117857
  const raw = env[key];
115669
117858
  if (raw === undefined)
@@ -115755,7 +117944,8 @@ async function executeReadOnlyQueryBounded(sql, params = [], budgetMs, maxRows)
115755
117944
  assertNoDeniedTables(sql);
115756
117945
  acquireBoundedQuerySlot();
115757
117946
  try {
115758
- return await runBoundedQueryChild(sql, params, budgetMs, maxRows);
117947
+ const run = isDbQueryWorkerPoolEnabled() ? runPooledQuery : runBoundedQueryChild;
117948
+ return await run(sql, params, budgetMs, maxRows);
115759
117949
  } finally {
115760
117950
  releaseBoundedQuerySlot();
115761
117951
  }
@@ -115763,8 +117953,8 @@ async function executeReadOnlyQueryBounded(sql, params = [], budgetMs, maxRows)
115763
117953
  function isReportableTimeout(timedOut, exitCode, stdout) {
115764
117954
  return timedOut && !(exitCode === 0 && stdout.length > 0);
115765
117955
  }
115766
- async function runBoundedQueryChild(sql, params, budgetMs, maxRows) {
115767
- const payload = {
117956
+ function buildPayload(sql, params, budgetMs, maxRows) {
117957
+ return {
115768
117958
  file: getDb2().filename,
115769
117959
  sql,
115770
117960
  params,
@@ -115772,6 +117962,16 @@ async function runBoundedQueryChild(sql, params, budgetMs, maxRows) {
115772
117962
  maxRows,
115773
117963
  busyTimeoutMs: budgetMs
115774
117964
  };
117965
+ }
117966
+ function timeoutError(budgetMs) {
117967
+ return new DbQueryTimeoutError(`Query exceeded the ${budgetMs}ms budget and was terminated. Filter on an indexed column and add a LIMIT. Aggregates such as COUNT(*), SUM(...) or typeof() over session_logs, agent_log, events or task_context_snapshots read every row in range and cannot be made cheap by chunking on rowid.`);
117968
+ }
117969
+ function isMissingExecutable(err) {
117970
+ const message = err instanceof Error ? err.message : String(err);
117971
+ return /executable not found/i.test(message) || /enoent/i.test(message);
117972
+ }
117973
+ async function runBoundedQueryChild(sql, params, budgetMs, maxRows) {
117974
+ const payload = buildPayload(sql, params, budgetMs, maxRows);
115775
117975
  let proc;
115776
117976
  try {
115777
117977
  proc = Bun.spawn(["bun", "-e", CHILD_SCRIPT], {
@@ -115780,10 +117980,8 @@ async function runBoundedQueryChild(sql, params, budgetMs, maxRows) {
115780
117980
  stderr: "pipe"
115781
117981
  });
115782
117982
  } catch (err) {
115783
- const message = err instanceof Error ? err.message : String(err);
115784
- if (!/executable not found/i.test(message) && !/enoent/i.test(message)) {
117983
+ if (!isMissingExecutable(err))
115785
117984
  throw err;
115786
- }
115787
117985
  warnDbQuerySpawnUnavailableOnce();
115788
117986
  return executeReadOnlyQuery(sql, params, maxRows);
115789
117987
  }
@@ -115807,7 +118005,7 @@ async function runBoundedQueryChild(sql, params, budgetMs, maxRows) {
115807
118005
  clearTimeout(timer);
115808
118006
  }
115809
118007
  if (isReportableTimeout(timedOut, exitCode, stdout)) {
115810
- throw new DbQueryTimeoutError(`Query exceeded the ${budgetMs}ms budget and was terminated. Filter on an indexed column and add a LIMIT. Aggregates such as COUNT(*), SUM(...) or typeof() over session_logs, agent_log, events or task_context_snapshots read every row in range and cannot be made cheap by chunking on rowid.`);
118008
+ throw timeoutError(budgetMs);
115811
118009
  }
115812
118010
  if (exitCode === WRITE_REJECTED_EXIT_CODE) {
115813
118011
  throw new Error(stderr.trim() || "Only read-only queries are allowed");
@@ -115823,7 +118021,180 @@ async function runBoundedQueryChild(sql, params, budgetMs, maxRows) {
115823
118021
  total: parsed.total
115824
118022
  };
115825
118023
  }
115826
- var WRITE_REJECTED_EXIT_CODE = 2, CHILD_SCRIPT, activeBoundedQueryCount = 0;
118024
+ function retireWorker(w) {
118025
+ clearTimeout(w.idleTimer);
118026
+ const i = idleWorkers.indexOf(w);
118027
+ if (i >= 0)
118028
+ idleWorkers.splice(i, 1);
118029
+ w.proc.kill("SIGKILL");
118030
+ }
118031
+ async function pumpWorker(w) {
118032
+ const decoder = new TextDecoder;
118033
+ let partial = "";
118034
+ try {
118035
+ for await (const chunk of w.proc.stdout) {
118036
+ const text = decoder.decode(chunk, { stream: true });
118037
+ let from = 0;
118038
+ let nl = text.indexOf(`
118039
+ `, from);
118040
+ while (nl >= 0) {
118041
+ const line = partial + text.slice(from, nl);
118042
+ partial = "";
118043
+ from = nl + 1;
118044
+ w.onLine?.(line);
118045
+ nl = text.indexOf(`
118046
+ `, from);
118047
+ }
118048
+ partial += text.slice(from);
118049
+ }
118050
+ } catch {}
118051
+ const code = await w.proc.exited;
118052
+ const stderr = (await w.stderr).trim();
118053
+ retireWorker(w);
118054
+ w.onExit?.(stderr || `db-query worker exited with code ${code}`);
118055
+ }
118056
+ function spawnWorker() {
118057
+ const proc = Bun.spawn(["bun", "-e", WORKER_SCRIPT], {
118058
+ stdin: "pipe",
118059
+ stdout: "pipe",
118060
+ stderr: "pipe"
118061
+ });
118062
+ proc.unref();
118063
+ const w = { proc, queries: 0, stderr: new Response(proc.stderr).text() };
118064
+ pumpWorker(w);
118065
+ return w;
118066
+ }
118067
+ async function runPooledQuery(sql, params, budgetMs, maxRows) {
118068
+ let worker = idleWorkers.pop();
118069
+ if (worker) {
118070
+ clearTimeout(worker.idleTimer);
118071
+ } else {
118072
+ try {
118073
+ worker = spawnWorker();
118074
+ } catch (err) {
118075
+ if (!isMissingExecutable(err))
118076
+ throw err;
118077
+ warnDbQuerySpawnUnavailableOnce();
118078
+ return executeReadOnlyQuery(sql, params, maxRows);
118079
+ }
118080
+ }
118081
+ const w = worker;
118082
+ const request = `${JSON.stringify(buildPayload(sql, params, budgetMs, maxRows))}
118083
+ `;
118084
+ let reply;
118085
+ try {
118086
+ reply = await new Promise((resolve, reject) => {
118087
+ const timer = setTimeout(() => {
118088
+ retireWorker(w);
118089
+ reject(timeoutError(budgetMs));
118090
+ }, budgetMs);
118091
+ w.onLine = (line) => {
118092
+ clearTimeout(timer);
118093
+ resolve(line);
118094
+ };
118095
+ w.onExit = (reason) => {
118096
+ clearTimeout(timer);
118097
+ reject(new Error(reason));
118098
+ };
118099
+ w.proc.stdin.write(request);
118100
+ w.proc.stdin.flush();
118101
+ });
118102
+ } catch (err) {
118103
+ retireWorker(w);
118104
+ throw err;
118105
+ } finally {
118106
+ w.onLine = undefined;
118107
+ w.onExit = undefined;
118108
+ }
118109
+ w.queries++;
118110
+ if (w.queries >= POOL_MAX_QUERIES_PER_WORKER || reply.length > POOL_MAX_PARKED_REPLY_CHARS) {
118111
+ retireWorker(w);
118112
+ } else {
118113
+ w.idleTimer = setTimeout(() => retireWorker(w), POOL_IDLE_REAP_MS);
118114
+ idleWorkers.push(w);
118115
+ }
118116
+ const parsed = JSON.parse(reply);
118117
+ if (parsed.error !== undefined)
118118
+ throw new Error(parsed.error);
118119
+ return {
118120
+ columns: parsed.columns,
118121
+ rows: parsed.rows,
118122
+ elapsed: parsed.elapsed,
118123
+ total: parsed.total
118124
+ };
118125
+ }
118126
+ var WRITE_REJECTED_EXIT_CODE = 2, CHILD_SCRIPT, activeBoundedQueryCount = 0, POOL_MAX_QUERIES_PER_WORKER = 500, POOL_IDLE_REAP_MS = 60000, POOL_MAX_PARKED_REPLY_CHARS, WORKER_SCRIPT = `
118127
+ const { Database } = require("bun:sqlite");
118128
+
118129
+ let db = null;
118130
+ let dbFile = null;
118131
+
118132
+ function run(req) {
118133
+ const { file, sql, params, vecExtensionPath, maxRows, busyTimeoutMs } = req;
118134
+ if (!db || dbFile !== file) {
118135
+ if (db) db.close();
118136
+ db = null;
118137
+ const opened = new Database(file, { readonly: true });
118138
+ if (vecExtensionPath) {
118139
+ try {
118140
+ opened.loadExtension(vecExtensionPath);
118141
+ } catch {
118142
+ // Non-fatal: only queries that reference vec0 tables/functions need it.
118143
+ }
118144
+ }
118145
+ db = opened;
118146
+ dbFile = file;
118147
+ }
118148
+ db.exec("PRAGMA busy_timeout = " + Math.trunc(busyTimeoutMs) + ";");
118149
+ const stmt = db.prepare(sql);
118150
+ try {
118151
+ if (stmt.columnNames.length === 0) throw new Error("Only read-only queries are allowed");
118152
+ const columns = stmt.columnNames;
118153
+ const start = performance.now();
118154
+ const rowArrays = [];
118155
+ let total = 0;
118156
+ for (const row of stmt.iterate(...(params || []))) {
118157
+ total++;
118158
+ if (!maxRows || rowArrays.length < maxRows) {
118159
+ rowArrays.push(
118160
+ columns.map((col) => {
118161
+ const value = row[col];
118162
+ return value instanceof Uint8Array ? Array.from(value) : value;
118163
+ }),
118164
+ );
118165
+ }
118166
+ }
118167
+ return { columns, rows: rowArrays, elapsed: Math.round(performance.now() - start), total };
118168
+ } finally {
118169
+ // Finalize so no read transaction stays open and blocks WAL checkpoints.
118170
+ stmt.finalize();
118171
+ }
118172
+ }
118173
+
118174
+ function handle(line) {
118175
+ let out;
118176
+ try {
118177
+ out = JSON.stringify(run(JSON.parse(line)));
118178
+ } catch (err) {
118179
+ out = JSON.stringify({ error: err && err.message ? err.message : String(err) });
118180
+ }
118181
+ process.stdout.write(out + "\\n");
118182
+ }
118183
+
118184
+ (async () => {
118185
+ const decoder = new TextDecoder();
118186
+ let buf = "";
118187
+ for await (const chunk of Bun.stdin.stream()) {
118188
+ buf += decoder.decode(chunk, { stream: true });
118189
+ let nl;
118190
+ while ((nl = buf.indexOf("\\n")) >= 0) {
118191
+ const line = buf.slice(0, nl);
118192
+ buf = buf.slice(nl + 1);
118193
+ if (line) handle(line);
118194
+ }
118195
+ }
118196
+ })();
118197
+ `, idleWorkers;
115827
118198
  var init_db_query_bounded = __esm(() => {
115828
118199
  init_db4();
115829
118200
  init_db_query_shared();
@@ -115884,6 +118255,8 @@ const { Database } = require("bun:sqlite");
115884
118255
  }
115885
118256
  })();
115886
118257
  `;
118258
+ POOL_MAX_PARKED_REPLY_CHARS = 8 * 1024 * 1024;
118259
+ idleWorkers = [];
115887
118260
  });
115888
118261
 
115889
118262
  // src/http/db-query.ts
@@ -116105,7 +118478,7 @@ var init_create_metric = __esm(() => {
116105
118478
  init_db_query();
116106
118479
  init_version2();
116107
118480
  init_utils();
116108
- init_types4();
118481
+ init_types5();
116109
118482
  init_constants3();
116110
118483
  });
116111
118484
 
@@ -116142,6 +118515,68 @@ var init_asset_key_auth = __esm(() => {
116142
118515
  };
116143
118516
  });
116144
118517
 
118518
+ // src/be/caller-session-group.ts
118519
+ async function fileCallerSessionIntoGroup(input) {
118520
+ if (!input.agentId || !isGroupKey(input.key) || sourceOfKey(input.key))
118521
+ return null;
118522
+ try {
118523
+ const task = await resolveCallerTask(input.sourceTaskId, input.agentId);
118524
+ if (!task)
118525
+ return null;
118526
+ const root = await getSessionRoot(task.id);
118527
+ if (!root)
118528
+ return null;
118529
+ const rootKey = defaultAssetKey("task", root.id);
118530
+ const hasDefaultKey = (entry) => entry.key === rootKey || entry.key === defaultAssetKey("task", entry.id);
118531
+ if (!hasDefaultKey(task))
118532
+ return null;
118533
+ const chain = await getRootTaskChain2(root.id);
118534
+ if (chain[0]?.id !== root.id || chain[0].key !== rootKey)
118535
+ return null;
118536
+ const agent = await getAgentById2(input.agentId);
118537
+ const principal = {
118538
+ kind: "agent",
118539
+ agentId: input.agentId,
118540
+ isLead: agent?.isLead ?? false
118541
+ };
118542
+ const movable = chain.filter(hasDefaultKey);
118543
+ const allowed = movable.every((entry) => can({
118544
+ principal,
118545
+ verb: "task.fs.mutate",
118546
+ resource: {
118547
+ kind: "task",
118548
+ taskId: entry.id,
118549
+ agentId: entry.agentId,
118550
+ creatorAgentId: entry.creatorAgentId
118551
+ },
118552
+ source: "mcp"
118553
+ }).allow);
118554
+ if (!allowed)
118555
+ return null;
118556
+ await assertAssetKeyMovesAllowed2();
118557
+ const moved = await moveSessionChains({
118558
+ moves: [{ rootId: root.id, taskIds: movable.map((entry) => entry.id), key: input.key }],
118559
+ changedBy: input.changedBy
118560
+ });
118561
+ return moved.includes(root.id) ? root.id : null;
118562
+ } catch (error) {
118563
+ if (error instanceof AssetKeyMovesBlockedError2)
118564
+ return null;
118565
+ console.warn("[caller-session-group] Session move failed:", scrubSecrets(error instanceof Error ? error.message : String(error)));
118566
+ return null;
118567
+ }
118568
+ }
118569
+ var init_caller_session_group = __esm(() => {
118570
+ init_key();
118571
+ init_source_key();
118572
+ init_rbac();
118573
+ init_secret_scrubber();
118574
+ init_audit_user();
118575
+ init_db4();
118576
+ init_session_moves();
118577
+ init_session_shares();
118578
+ });
118579
+
116145
118580
  // src/be/db/page-versions.ts
116146
118581
  async function getPageEditCounter(pageId) {
116147
118582
  const row = await getDbClient2().get("SELECT MAX(version) AS latest FROM page_versions WHERE pageId = ?", [pageId]);
@@ -117447,7 +119882,7 @@ var SWARM_CLASS, COLOR_TOKEN_REFERENCE, PAGE_COLOR_TOKENS, registerCreatePageToo
117447
119882
  description: "Stores an HTML or JSON page in the swarm and returns shareable URLs. " + "Calls are upsert-by-(agent, slug): if you previously created a page " + "with the same slug, its prior state is snapshotted and the row is " + "updated. Use this for static reports, dashboards, or JSON action " + "specs that don't need a long-lived process. " + "HTML pages use the swarm design system (designVersion 2): theme " + "tokens such as var(--color-primary), the swarm-* primitives, and " + "Tailwind v4 utilities such as bg-card and text-muted-foreground. " + "Set `theme` to a preset id or pass `themeTokens` (a token map, or a " + 'CSS variable block with format "css") to restyle the whole page. ' + "Do not hardcode colors: inside the dashboard the page follows the " + "viewer's theme and dark mode. Pages created before designVersion 2 " + "keep the old look; pass designVersion: 2 when you rewrite one.",
117448
119883
  annotations: { destructiveHint: false },
117449
119884
  inputSchema: object2({
117450
- key: AssetKeySchema.optional().describe("Logical namespace. Defaults to a shared/page:<id>/ resource key."),
119885
+ key: AssetKeySchema.optional().describe("Logical namespace. Defaults to the calling task's group key when it has one, else shared/page:<id>/. An explicit use-case group key also files the calling task's session into that group while the session still has its default key."),
117451
119886
  title: string2().min(1).describe("Human-readable title shown in listings."),
117452
119887
  slug: string2().min(1).optional().describe("URL slug. Defaults to the kebab-cased title. Same slug → updates the existing row."),
117453
119888
  body: string2().min(1).describe("Full page body (HTML document, SVG image, or JSON-render spec, per contentType)."),
@@ -117471,7 +119906,8 @@ var SWARM_CLASS, COLOR_TOKEN_REFERENCE, PAGE_COLOR_TOKENS, registerCreatePageToo
117471
119906
  ignoredTokens: array2(string2()).optional(),
117472
119907
  colorLiteralCount: number2().optional(),
117473
119908
  usesDesignSystem: boolean().optional(),
117474
- lightOnlyColors: boolean().optional()
119909
+ lightOnlyColors: boolean().optional(),
119910
+ movedSessionRootId: string2().optional()
117475
119911
  })
117476
119912
  }, async (input, requestInfo, _meta) => {
117477
119913
  if (!requestInfo.agentId) {
@@ -117493,7 +119929,8 @@ var SWARM_CLASS, COLOR_TOKEN_REFERENCE, PAGE_COLOR_TOKENS, registerCreatePageToo
117493
119929
  let assetKey;
117494
119930
  try {
117495
119931
  if (input.key !== undefined || !existing) {
117496
- assetKey = input.key ? await authorizeAssetKeyWrite(input.key, trustedUserId) : undefined;
119932
+ const resolvedKey = input.key ?? await resolveTaskGroupKey(requestInfo.sourceTaskId, requestInfo.agentId);
119933
+ assetKey = resolvedKey ? await authorizeAssetKeyWrite(resolvedKey, trustedUserId) : undefined;
117497
119934
  }
117498
119935
  } catch (error) {
117499
119936
  const msg = error instanceof Error ? error.message : String(error);
@@ -117564,7 +120001,13 @@ var SWARM_CLASS, COLOR_TOKEN_REFERENCE, PAGE_COLOR_TOKENS, registerCreatePageToo
117564
120001
  ...fresh.designVersion >= 2 ? { colorLiteralCount: countColorLiterals(fresh.body) } : {}
117565
120002
  } : {};
117566
120003
  const { ignored } = themeFields;
117567
- return toolOk(`Page "${input.title}" saved (slug=${finalSlug}, version=${version}, designVersion=${fresh.designVersion}).` + (ignored.length > 0 ? " Some theme tokens were ignored (outside the page token contract or referencing a variable outside it)." : ""), {
120004
+ const movedSessionRootId = input.key !== undefined && assetKey ? await fileCallerSessionIntoGroup({
120005
+ sourceTaskId: requestInfo.sourceTaskId,
120006
+ agentId: requestInfo.agentId,
120007
+ key: assetKey,
120008
+ changedBy: trustedUserId ?? undefined
120009
+ }) : null;
120010
+ return toolOk(`Page "${input.title}" saved (slug=${finalSlug}, version=${version}, designVersion=${fresh.designVersion}).` + (ignored.length > 0 ? " Some theme tokens were ignored (outside the page token contract or referencing a variable outside it)." : "") + (movedSessionRootId ? ` This session moved into ${assetKey}.` : ""), {
117568
120011
  details: `API: ${apiUrl}
117569
120012
  App: ${appUrl}` + (ignored.length > 0 ? `
117570
120013
  Ignored theme tokens: ${ignored.join(", ")}` : ""),
@@ -117577,7 +120020,8 @@ var SWARM_CLASS, COLOR_TOKEN_REFERENCE, PAGE_COLOR_TOKENS, registerCreatePageToo
117577
120020
  api_url: apiUrl,
117578
120021
  designVersion: fresh.designVersion,
117579
120022
  ...ignored.length > 0 ? { ignoredTokens: ignored } : {},
117580
- ...designFlags
120023
+ ...designFlags,
120024
+ ...movedSessionRootId ? { movedSessionRootId } : {}
117581
120025
  }
117582
120026
  });
117583
120027
  });
@@ -117586,6 +120030,7 @@ var init_create_page = __esm(() => {
117586
120030
  init_zod();
117587
120031
  init_asset_key_auth();
117588
120032
  init_audit_user();
120033
+ init_caller_session_group();
117589
120034
  init_db4();
117590
120035
  init_page_versions();
117591
120036
  init_color_literals();
@@ -117593,7 +120038,7 @@ var init_create_page = __esm(() => {
117593
120038
  init_page_fields();
117594
120039
  init_tokens2();
117595
120040
  init_utils();
117596
- init_types4();
120041
+ init_types5();
117597
120042
  init_constants3();
117598
120043
  SWARM_CLASS = /(?:^|\s)swarm-/;
117599
120044
  COLOR_TOKEN_REFERENCE = /var\(\s*--color-/i;
@@ -117619,13 +120064,28 @@ var init_app_validation = __esm(() => {
117619
120064
 
117620
120065
  // src/oauth/presets.ts
117621
120066
  function listOAuthPresets() {
117622
- return OAUTH_PRESETS.map((preset) => ({ ...preset }));
120067
+ return OAUTH_PRESETS.map(withGitHubHost);
120068
+ }
120069
+ function withGitHubHost(preset) {
120070
+ if (preset.id !== "github")
120071
+ return { ...preset };
120072
+ const { webUrl, apiUrl, enterprise } = getGitHubLinkConfig();
120073
+ if (!enterprise)
120074
+ return { ...preset };
120075
+ return {
120076
+ ...preset,
120077
+ authorizeUrl: `${webUrl}/login/oauth/authorize`,
120078
+ tokenUrl: `${webUrl}/login/oauth/access_token`,
120079
+ userinfoUrl: `${apiUrl}/user`,
120080
+ setupHints: preset.setupHints.map((hint) => hint.replace("github.com/settings/developers", `${webUrl}/settings/developers`))
120081
+ };
117623
120082
  }
117624
120083
  function listOAuthPresetIds() {
117625
120084
  return OAUTH_PRESETS.map((preset) => preset.id);
117626
120085
  }
117627
120086
  function getOAuthPreset(id) {
117628
- return OAUTH_PRESETS.find((preset) => preset.id === id) ?? null;
120087
+ const preset = OAUTH_PRESETS.find((candidate) => candidate.id === id);
120088
+ return preset ? withGitHubHost(preset) : null;
117629
120089
  }
117630
120090
  function mergeExtraParams(base, override) {
117631
120091
  if (!base && !override)
@@ -117651,6 +120111,7 @@ function hydrateOAuthAppFromPreset(preset, overrides = {}) {
117651
120111
  }
117652
120112
  var OAUTH_PRESETS;
117653
120113
  var init_presets2 = __esm(() => {
120114
+ init_github_host();
117654
120115
  OAUTH_PRESETS = [
117655
120116
  {
117656
120117
  id: "google",
@@ -117708,6 +120169,7 @@ var init_presets2 = __esm(() => {
117708
120169
  },
117709
120170
  {
117710
120171
  id: "jira",
120172
+ hiddenInCatalog: true,
117711
120173
  displayName: "Jira (Atlassian)",
117712
120174
  provider: "jira",
117713
120175
  authorizeUrl: "https://auth.atlassian.com/authorize",
@@ -117727,6 +120189,7 @@ var init_presets2 = __esm(() => {
117727
120189
  },
117728
120190
  {
117729
120191
  id: "linear",
120192
+ hiddenInCatalog: true,
117730
120193
  displayName: "Linear",
117731
120194
  provider: "linear",
117732
120195
  authorizeUrl: "https://linear.app/oauth/authorize",
@@ -119839,7 +122302,7 @@ var init_worker_follow_up = __esm(() => {
119839
122302
  init_dispatcher();
119840
122303
  init_resolver();
119841
122304
  init_deferred_task_waits();
119842
- init_types4();
122305
+ init_types5();
119843
122306
  init_env_flag();
119844
122307
  init_task_attachment_links();
119845
122308
  init_context_key();
@@ -120052,7 +122515,7 @@ async function guardTerminalTaskResultWrite(task, write) {
120052
122515
  }
120053
122516
  var init_terminal_result_guard = __esm(() => {
120054
122517
  init_db4();
120055
- init_types4();
122518
+ init_types5();
120056
122519
  init_output_schema();
120057
122520
  init_secret_scrubber();
120058
122521
  init_json_schema_validator();
@@ -120341,7 +122804,7 @@ var init_defer_task = __esm(() => {
120341
122804
  init_terminal_result_guard();
120342
122805
  init_task_tool_ctx();
120343
122806
  init_utils();
120344
- init_types4();
122807
+ init_types5();
120345
122808
  init_business_use();
120346
122809
  DeferAbortedError = class DeferAbortedError extends Error {
120347
122810
  };
@@ -120931,7 +123394,7 @@ var EXTENSION_INSTALL_DESCRIPTION = "Install an extension from the catalog by `t
120931
123394
  var init_extension_install = __esm(() => {
120932
123395
  init_zod();
120933
123396
  init_utils();
120934
- init_types4();
123397
+ init_types5();
120935
123398
  init_extension_common();
120936
123399
  extensionInstallInputSchema = object2({
120937
123400
  template: string2().min(1).optional().describe("Name of a predefined extension from extension-catalog. Mutually exclusive with manifest and files."),
@@ -121045,8 +123508,11 @@ var agentOutputShape, registerGetSwarmTool = (server) => {
121045
123508
  agents: array2(agentOutputShape).optional()
121046
123509
  })
121047
123510
  }, async ({ includeFull }, requestInfo, _meta) => {
121048
- const agents = await getAllAgents2({ slim: !includeFull });
121049
- const agentList = agents.map((a) => `- ${a.name} (${a.status}${a.isLead ? ", lead" : ""}) — id: ${a.id}`).join(`
123511
+ const agents = await Promise.all((await getAllAgents2({ slim: !includeFull })).map(async (a) => await isAgentOnDemand(a) ? { ...a, onDemand: true } : a));
123512
+ const agentList = agents.map((a) => {
123513
+ const onDemand = "onDemand" in a ? ", on demand: send-task starts it" : "";
123514
+ return `- ${a.name} (${a.status}${onDemand}${a.isLead ? ", lead" : ""}) — id: ${a.id}`;
123515
+ }).join(`
121050
123516
  `);
121051
123517
  return toolOk(`Found ${agents.length} agent(s) in the swarm. Requested by session: ${requestInfo.sessionId}`, {
121052
123518
  details: agentList || undefined,
@@ -121057,13 +123523,15 @@ var agentOutputShape, registerGetSwarmTool = (server) => {
121057
123523
  var init_get_swarm = __esm(() => {
121058
123524
  init_zod();
121059
123525
  init_db4();
123526
+ init_reachability();
121060
123527
  init_utils();
121061
- init_types4();
123528
+ init_types5();
121062
123529
  agentOutputShape = looseObject({
121063
123530
  id: string2().optional(),
121064
123531
  name: string2().optional(),
121065
123532
  isLead: boolean().optional(),
121066
123533
  status: AgentStatusSchema.optional(),
123534
+ onDemand: boolean().optional().describe("True when the agent is offline but its runtime pool will start a runtime for it (multi-runtime on, pool capacity left, maxTasks fits one runtime). send-task to it starts a runtime."),
121067
123535
  description: string2().optional(),
121068
123536
  role: string2().optional(),
121069
123537
  capabilities: array2(string2()).optional(),
@@ -121212,7 +123680,7 @@ var init_get_tasks = __esm(() => {
121212
123680
  init_db4();
121213
123681
  init_task_tool_ctx();
121214
123682
  init_utils();
121215
- init_types4();
123683
+ init_types5();
121216
123684
  TaskSummarySchema = looseObject({
121217
123685
  id: string2().optional(),
121218
123686
  key: string2().optional(),
@@ -121392,7 +123860,7 @@ var agentOutputShape2, registerJoinSwarmTool = (server) => {
121392
123860
  capabilities,
121393
123861
  claudeMd: defaultClaudeMd,
121394
123862
  soulMd: defaultSoulMd,
121395
- identityMd: defaultIdentityMd
123863
+ identityMd: agent.identityMd || defaultIdentityMd
121396
123864
  });
121397
123865
  return updatedAgent ?? agent;
121398
123866
  });
@@ -121409,7 +123877,7 @@ var init_join_swarm = __esm(() => {
121409
123877
  init_db4();
121410
123878
  init_defaults();
121411
123879
  init_utils();
121412
- init_types4();
123880
+ init_types5();
121413
123881
  agentOutputShape2 = looseObject({
121414
123882
  id: string2().optional(),
121415
123883
  name: string2().optional(),
@@ -121439,6 +123907,9 @@ var init_join_swarm = __esm(() => {
121439
123907
  });
121440
123908
 
121441
123909
  // src/kv-reserved-namespaces.ts
123910
+ function requiresLeadToWrite(namespace) {
123911
+ return LEAD_ONLY_FAMILIES.has(namespace.split(":", 1)[0] ?? "");
123912
+ }
121442
123913
  function reservedNamespaceError(namespace) {
121443
123914
  return RESERVED_FAMILIES.get(namespace.split(":", 1)[0] ?? "") ?? null;
121444
123915
  }
@@ -121448,7 +123919,7 @@ function privateNamespaceError(namespace) {
121448
123919
  function reservedRoomKeyError(key) {
121449
123920
  return key.startsWith("_room/") ? "room snapshot keys are reserved; use the room endpoints" : null;
121450
123921
  }
121451
- var RESERVED_FAMILIES, PRIVATE_FAMILIES;
123922
+ var RESERVED_FAMILIES, PRIVATE_FAMILIES, LEAD_ONLY_FAMILIES;
121452
123923
  var init_kv_reserved_namespaces = __esm(() => {
121453
123924
  RESERVED_FAMILIES = new Map([
121454
123925
  ["apps", "namespace is reserved for swarm apps; use the app row endpoints"],
@@ -121457,12 +123928,14 @@ var init_kv_reserved_namespaces = __esm(() => {
121457
123928
  ["worker", "namespace is reserved for worker nudges"],
121458
123929
  ["slack-external-alert", "namespace is reserved for Slack external channel alerts"],
121459
123930
  ["slack-left-thread", "namespace is reserved for left Slack threads; use slack-leave-thread"],
123931
+ ["slack-thread-buffer", "namespace is reserved for the Slack thread buffer"],
121460
123932
  [
121461
123933
  "session-labels",
121462
123934
  "namespace is reserved for session source labels; GET /api/session-tree returns them"
121463
123935
  ]
121464
123936
  ]);
121465
- PRIVATE_FAMILIES = new Set(["session-labels"]);
123937
+ PRIVATE_FAMILIES = new Set(["session-labels", "slack-thread-buffer"]);
123938
+ LEAD_ONLY_FAMILIES = new Set(["usecase"]);
121466
123939
  });
121467
123940
 
121468
123941
  // src/tools/kv/kv-write-auth.ts
@@ -121481,6 +123954,17 @@ async function kvWriteAuthError(namespace, info, key) {
121481
123954
  if (namespace.startsWith("task:page:")) {
121482
123955
  return "task:page:* writes require a page-proxy request, not an MCP call";
121483
123956
  }
123957
+ if (requiresLeadToWrite(namespace)) {
123958
+ const agent = info.agentId ? await getAgentById2(info.agentId) : null;
123959
+ const allowed = info.agentId != null && can({
123960
+ principal: { kind: "agent", agentId: info.agentId, isLead: agent?.isLead ?? false },
123961
+ verb: "kv.write.any",
123962
+ resource: { kind: "kv-namespace", namespace },
123963
+ source: "mcp"
123964
+ }).allow;
123965
+ if (!allowed)
123966
+ return "writes to this namespace require lead";
123967
+ }
121484
123968
  if (namespace.startsWith("task:agent:")) {
121485
123969
  const ownNamespace = info.agentId != null && namespace === `task:agent:${info.agentId}`;
121486
123970
  const agent = !ownNamespace && info.agentId ? await getAgentById2(info.agentId) : null;
@@ -121569,7 +124053,7 @@ var init_kv_delete = __esm(() => {
121569
124053
  init_zod();
121570
124054
  init_db4();
121571
124055
  init_utils();
121572
- init_types4();
124056
+ init_types5();
121573
124057
  init_kv_write_auth();
121574
124058
  init_resolve_namespace();
121575
124059
  });
@@ -121693,7 +124177,7 @@ var init_kv_get = __esm(() => {
121693
124177
  init_db4();
121694
124178
  init_kv_view();
121695
124179
  init_utils();
121696
- init_types4();
124180
+ init_types5();
121697
124181
  init_kv_read_auth();
121698
124182
  init_resolve_namespace();
121699
124183
  kvEntryOutputSchema = looseObject({
@@ -121764,7 +124248,7 @@ var init_kv_incr = __esm(() => {
121764
124248
  init_zod();
121765
124249
  init_db4();
121766
124250
  init_utils();
121767
- init_types4();
124251
+ init_types5();
121768
124252
  init_kv_write_auth();
121769
124253
  init_resolve_namespace();
121770
124254
  kvEntryOutputSchema2 = looseObject({
@@ -121839,7 +124323,7 @@ var init_kv_list = __esm(() => {
121839
124323
  init_zod();
121840
124324
  init_db4();
121841
124325
  init_utils();
121842
- init_types4();
124326
+ init_types5();
121843
124327
  init_kv_read_auth();
121844
124328
  init_resolve_namespace();
121845
124329
  kvEntryOutputSchema3 = looseObject({
@@ -121945,7 +124429,7 @@ var init_kv_set = __esm(() => {
121945
124429
  init_zod();
121946
124430
  init_db4();
121947
124431
  init_utils();
121948
- init_types4();
124432
+ init_types5();
121949
124433
  init_kv_write_auth();
121950
124434
  init_resolve_namespace();
121951
124435
  MAX_KV_BODY_BYTES = 2 * 1024 * 1024;
@@ -121994,7 +124478,7 @@ var init_list_channels = __esm(() => {
121994
124478
  init_zod();
121995
124479
  init_db4();
121996
124480
  init_utils();
121997
- init_types4();
124481
+ init_types5();
121998
124482
  ChannelOutputSchema2 = looseObject({
121999
124483
  id: string2().optional(),
122000
124484
  name: string2().optional(),
@@ -122941,7 +125425,7 @@ var init_memory_edit = __esm(() => {
122941
125425
  init_link_resolver();
122942
125426
  init_rbac();
122943
125427
  init_utils();
122944
- init_types4();
125428
+ init_types5();
122945
125429
  agentMemoryOutputSchema = looseObject({
122946
125430
  id: string2().optional(),
122947
125431
  agentId: string2().nullable().optional(),
@@ -123139,7 +125623,7 @@ var init_memory_get = __esm(() => {
123139
125623
  init_links_store();
123140
125624
  init_retrieval();
123141
125625
  init_utils();
123142
- init_types4();
125626
+ init_types5();
123143
125627
  NUDGE_ELIGIBLE_SOURCES = new Set(["manual", "file_index"]);
123144
125628
  agentMemoryOutputSchema2 = looseObject({
123145
125629
  id: string2().optional(),
@@ -123514,7 +125998,7 @@ var init_memory_search = __esm(() => {
123514
125998
  init_reranker();
123515
125999
  init_search_candidates();
123516
126000
  init_utils();
123517
- init_types4();
126001
+ init_types5();
123518
126002
  NUDGE_ELIGIBLE_SOURCES2 = new Set(["manual", "file_index"]);
123519
126003
  memorySearchOutputSchema = swarmToolOutputSchema({
123520
126004
  yourAgentId: string2().optional(),
@@ -123615,7 +126099,7 @@ var init_memory_store = __esm(() => {
123615
126099
  init_key_guard();
123616
126100
  init_key_paths();
123617
126101
  init_utils();
123618
- init_types4();
126102
+ init_types5();
123619
126103
  });
123620
126104
 
123621
126105
  // src/tools/model-catalog/index.ts
@@ -123811,7 +126295,7 @@ var init_list_model_profiles = __esm(() => {
123811
126295
  init_zod();
123812
126296
  init_model_profiles();
123813
126297
  init_utils();
123814
- init_types4();
126298
+ init_types5();
123815
126299
  });
123816
126300
 
123817
126301
  // src/tools/my-agent-info.ts
@@ -123844,7 +126328,7 @@ var init_my_agent_info = __esm(() => {
123844
126328
  init_zod();
123845
126329
  init_db4();
123846
126330
  init_utils();
123847
- init_types4();
126331
+ init_types5();
123848
126332
  agentOutputShape3 = looseObject({
123849
126333
  id: string2().optional(),
123850
126334
  name: string2().optional(),
@@ -124472,7 +126956,7 @@ var init_list = __esm(() => {
124472
126956
  init_zod();
124473
126957
  init_db4();
124474
126958
  init_utils();
124475
- init_types4();
126959
+ init_types5();
124476
126960
  promptTemplateOutputShape2 = looseObject({
124477
126961
  id: string2().optional(),
124478
126962
  eventType: string2().optional(),
@@ -124596,7 +127080,7 @@ var init_set2 = __esm(() => {
124596
127080
  init_zod();
124597
127081
  init_db4();
124598
127082
  init_utils();
124599
- init_types4();
127083
+ init_types5();
124600
127084
  promptTemplateOutputShape3 = looseObject({
124601
127085
  id: string2().optional(),
124602
127086
  eventType: string2().optional(),
@@ -125422,7 +127906,7 @@ var init_update_repo = __esm(() => {
125422
127906
  init_repo_checked_update();
125423
127907
  init_rbac();
125424
127908
  init_utils();
125425
- init_types4();
127909
+ init_types5();
125426
127910
  swarmRepoOutputShape2 = looseObject({
125427
127911
  id: string2().optional(),
125428
127912
  url: string2().optional(),
@@ -126316,7 +128800,7 @@ class StringDecoder {
126316
128800
  return res;
126317
128801
  }
126318
128802
  }
126319
- var errorUnexpectedEndOfArray, errorIntegerOutOfRange, createDecoder = (uint8Array) => new Decoder(uint8Array), hasContent = (decoder) => decoder.pos !== decoder.arr.length, readUint8Array = (decoder, len) => {
128803
+ var errorUnexpectedEndOfArray, errorIntegerOutOfRange, createDecoder = (uint8Array) => new Decoder(uint8Array), hasContent2 = (decoder) => decoder.pos !== decoder.arr.length, readUint8Array = (decoder, len) => {
126320
128804
  const view = new Uint8Array(decoder.arr.buffer, decoder.pos + decoder.arr.byteOffset, len);
126321
128805
  decoder.pos += len;
126322
128806
  return view;
@@ -126433,7 +128917,7 @@ var init_decoding = __esm(() => {
126433
128917
  read() {
126434
128918
  if (this.count === 0) {
126435
128919
  this.s = this.reader(this);
126436
- if (hasContent(this)) {
128920
+ if (hasContent2(this)) {
126437
128921
  this.count = readVarUint(this) + 1;
126438
128922
  } else {
126439
128923
  this.count = -1;
@@ -131122,7 +133606,7 @@ function yToJson(value, depth = 0) {
131122
133606
  throw new Error("room document contains a non-JSON value");
131123
133607
  return value;
131124
133608
  }
131125
- function materialize(doc) {
133609
+ function materialize2(doc) {
131126
133610
  return yToJson(doc.getMap("root"));
131127
133611
  }
131128
133612
  function pathLabel(path) {
@@ -131277,7 +133761,7 @@ function applyOperations(doc, operations) {
131277
133761
  try {
131278
133762
  applyUpdate(candidate, encodeStateAsUpdate(doc));
131279
133763
  applyUnchecked(candidate, parsed);
131280
- materialize(candidate);
133764
+ materialize2(candidate);
131281
133765
  } finally {
131282
133766
  candidate.destroy();
131283
133767
  }
@@ -131502,7 +133986,7 @@ function validateDocument(doc) {
131502
133986
  if (key !== "root")
131503
133987
  throw new Error(`room update contains unsupported shared type "${key}"`);
131504
133988
  }
131505
- materialize(doc);
133989
+ materialize2(doc);
131506
133990
  }
131507
133991
  function decodeRoomSnapshot(value) {
131508
133992
  const envelope = parseEnvelope(value);
@@ -131513,7 +133997,7 @@ function decodeRoomSnapshot(value) {
131513
133997
  return {
131514
133998
  schemaVersion: envelope.schemaVersion,
131515
133999
  generation: envelope.generation,
131516
- state: materialize(doc)
134000
+ state: materialize2(doc)
131517
134001
  };
131518
134002
  } finally {
131519
134003
  doc.destroy();
@@ -131527,7 +134011,7 @@ function roomView(room, requestedVersion = room.schemaVersion) {
131527
134011
  schemaVersion: room.schemaVersion,
131528
134012
  generation: room.generation,
131529
134013
  stale: requestedVersion !== room.schemaVersion,
131530
- state: materialize(room.doc),
134014
+ state: materialize2(room.doc),
131531
134015
  snapshot: envelope.snapshot,
131532
134016
  bytes: envelopeBytes(envelope)
131533
134017
  };
@@ -131982,7 +134466,7 @@ var init_rooms2 = __esm(() => {
131982
134466
  init_document();
131983
134467
  init_rooms();
131984
134468
  init_utils();
131985
- init_types4();
134469
+ init_types5();
131986
134470
  roomInput = object2({
131987
134471
  name: string2().regex(/^[a-zA-Z0-9_-]{1,64}$/).default("default"),
131988
134472
  namespace: KvNamespaceSchema.optional(),
@@ -132105,7 +134589,7 @@ var registerRuntimePoolCreateAgentTool = (server) => {
132105
134589
  };
132106
134590
  var init_runtime_pool_create_agent = __esm(() => {
132107
134591
  init_zod();
132108
- init_types4();
134592
+ init_types5();
132109
134593
  init_runtime_pool_common();
132110
134594
  init_utils();
132111
134595
  });
@@ -132181,7 +134665,7 @@ var registerRuntimePoolUpsertTool = (server) => {
132181
134665
  };
132182
134666
  var init_runtime_pool_upsert = __esm(() => {
132183
134667
  init_zod();
132184
- init_types4();
134668
+ init_types5();
132185
134669
  init_runtime_pool_common();
132186
134670
  init_utils();
132187
134671
  });
@@ -132201,7 +134685,8 @@ var import_cron_parser2, createScheduleInputSchema, scheduleDataShape, registerC
132201
134685
  outputSchema: swarmToolOutputSchema({
132202
134686
  yourAgentId: string2().optional(),
132203
134687
  schedule: looseObject(scheduleDataShape).optional(),
132204
- modelTierDeprecated: modelTierDeprecatedOutputSchema.optional()
134688
+ modelTierDeprecated: modelTierDeprecatedOutputSchema.optional(),
134689
+ movedSessionRootId: string2().optional()
132205
134690
  })
132206
134691
  }, async ({
132207
134692
  key,
@@ -132327,7 +134812,8 @@ var import_cron_parser2, createScheduleInputSchema, scheduleDataShape, registerC
132327
134812
  nextRunAt = calculateNextRun2(tempSchedule, new Date);
132328
134813
  }
132329
134814
  const createdBy = await resolveTaskAuditUserId(requestInfo.sourceTaskId, requestInfo.agentId) ?? undefined;
132330
- const assetKey = key ? await authorizeAssetKeyWrite(key, createdBy) : undefined;
134815
+ const resolvedKey = key ?? await resolveTaskGroupKey(requestInfo.sourceTaskId, requestInfo.agentId);
134816
+ const assetKey = resolvedKey ? await authorizeAssetKeyWrite(resolvedKey, createdBy) : undefined;
132331
134817
  const schedule = await createScheduledTask2({
132332
134818
  key: assetKey,
132333
134819
  name,
@@ -132353,13 +134839,21 @@ var import_cron_parser2, createScheduleInputSchema, scheduleDataShape, registerC
132353
134839
  scheduleType: scheduleType ?? "recurring",
132354
134840
  createdBy
132355
134841
  });
134842
+ const movedSessionRootId = key !== undefined && assetKey ? await fileCallerSessionIntoGroup({
134843
+ sourceTaskId: requestInfo.sourceTaskId,
134844
+ agentId: requestInfo.agentId,
134845
+ key: assetKey,
134846
+ changedBy: createdBy
134847
+ }) : null;
132356
134848
  const scheduleDesc = isOneTime ? `one-time at ${schedule.nextRunAt}` : cronExpression || `every ${intervalMs}ms`;
132357
134849
  const modelTierDeprecated = modelTierDeprecation(modelTier, targetHarness);
132358
- return toolOk(`Created schedule "${name}" (${scheduleDesc}). Next run: ${schedule.nextRunAt || "disabled"}`, {
134850
+ const movedNote = movedSessionRootId ? `. This session moved into ${assetKey}.` : "";
134851
+ return toolOk(`Created schedule "${name}" (${scheduleDesc}). Next run: ${schedule.nextRunAt || "disabled"}${movedNote}`, {
132359
134852
  data: {
132360
134853
  yourAgentId: requestInfo.agentId,
132361
134854
  schedule,
132362
- ...modelTierDeprecated ? { modelTierDeprecated } : {}
134855
+ ...modelTierDeprecated ? { modelTierDeprecated } : {},
134856
+ ...movedSessionRootId ? { movedSessionRootId } : {}
132363
134857
  }
132364
134858
  });
132365
134859
  } catch (error) {
@@ -132379,16 +134873,17 @@ var init_create_schedule = __esm(() => {
132379
134873
  init_zod();
132380
134874
  init_asset_key_auth();
132381
134875
  init_audit_user();
134876
+ init_caller_session_group();
132382
134877
  init_db4();
132383
134878
  init_model_profiles();
132384
134879
  init_model_validation2();
132385
134880
  init_db3();
132386
134881
  init_scheduler2();
132387
134882
  init_utils();
132388
- init_types4();
132389
- import_cron_parser2 = __toESM(require_dist2(), 1);
134883
+ init_types5();
134884
+ import_cron_parser2 = __toESM(require_dist(), 1);
132390
134885
  createScheduleInputSchema = object2({
132391
- key: AssetKeySchema.optional().describe("Logical namespace. Defaults to a shared/schedule:<id>/ resource key."),
134886
+ key: AssetKeySchema.optional().describe("Logical namespace. Defaults to the calling task's group key when it has one, else shared/schedule:<id>/. An explicit use-case group key also files the calling task's session into that group while the session still has its default key, so the planning session, the schedule and its runs share one key."),
132392
134887
  name: string2().min(1).max(100).describe("Unique name for the schedule (e.g., 'daily-cleanup')"),
132393
134888
  taskTemplate: string2().min(1).optional().describe("The task description that will be created each time. Required when targetType is 'agent-task' (the default)."),
132394
134889
  targetType: ScheduledTaskTargetTypeSchema.default("agent-task").optional().describe("Execution target. Use 'workflow' + workflowId when the schedule only starts a workflow; " + "use 'script' + scriptName/scriptArgs when it only runs a catalog script; " + "use 'agent-task' only when a reasoning agent genuinely needs to be in the loop. " + "Do not create an agent-task whose taskTemplate just tells an agent to trigger a workflow or script."),
@@ -133005,7 +135500,7 @@ var init_list_schedules = __esm(() => {
133005
135500
  init_zod();
133006
135501
  init_db4();
133007
135502
  init_utils();
133008
- init_types4();
135503
+ init_types5();
133009
135504
  scheduleRowShape = {
133010
135505
  id: string2().optional(),
133011
135506
  key: AssetKeySchema.optional(),
@@ -133287,8 +135782,8 @@ var init_patch_schedule = __esm(() => {
133287
135782
  init_rbac();
133288
135783
  init_scheduler2();
133289
135784
  init_utils();
133290
- init_types4();
133291
- import_cron_parser3 = __toESM(require_dist2(), 1);
135785
+ init_types5();
135786
+ import_cron_parser3 = __toESM(require_dist(), 1);
133292
135787
  patchScheduleInputSchema = object2({
133293
135788
  key: AssetKeySchema.optional().describe("Move to a logical namespace."),
133294
135789
  scheduleId: string2().uuid().optional().describe("Schedule ID to patch"),
@@ -133645,8 +136140,8 @@ var init_update_schedule = __esm(() => {
133645
136140
  init_rbac();
133646
136141
  init_scheduler2();
133647
136142
  init_utils();
133648
- init_types4();
133649
- import_cron_parser4 = __toESM(require_dist2(), 1);
136143
+ init_types5();
136144
+ import_cron_parser4 = __toESM(require_dist(), 1);
133650
136145
  updateScheduleInputSchema = object2({
133651
136146
  key: AssetKeySchema.optional().describe("Move to a logical namespace."),
133652
136147
  scheduleId: string2().uuid().optional().describe("Schedule ID to update"),
@@ -134443,7 +136938,7 @@ var LAUNCH_SCRIPT_RUN_DESCRIPTION = "Launch a durable one-off script workflow ru
134443
136938
  var init_script_runs = __esm(() => {
134444
136939
  init_zod();
134445
136940
  init_utils();
134446
- init_types4();
136941
+ init_types5();
134447
136942
  init_script_common();
134448
136943
  });
134449
136944
 
@@ -135036,7 +137531,7 @@ var init_send_task = __esm(() => {
135036
137531
  init_task_dedup();
135037
137532
  init_task_tool_ctx();
135038
137533
  init_utils();
135039
- init_types4();
137534
+ init_types5();
135040
137535
  init_json_schema_validator();
135041
137536
  init_reachability();
135042
137537
  init_get_task_details();
@@ -136237,6 +138732,22 @@ function isTableBlock(block) {
136237
138732
  function decodeMrkdwn(text) {
136238
138733
  return text.replace(/<[^<>]*>/g, "").replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&amp;/g, "&");
136239
138734
  }
138735
+ function decodeEntities(text) {
138736
+ return text.replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&amp;/g, "&");
138737
+ }
138738
+ function collapseWhitespace(text) {
138739
+ return text.replace(/\s+/g, " ").trim();
138740
+ }
138741
+ function containsOnWordBoundaries(haystack, needle) {
138742
+ const WORD = "[\\p{L}\\p{N}\\p{M}_]";
138743
+ const isWord = (char) => char !== undefined && new RegExp(WORD, "u").test(char);
138744
+ const first = needle.codePointAt(0);
138745
+ const startsWord = first !== undefined && isWord(String.fromCodePoint(first));
138746
+ const endsWord = isWord(Array.from(needle).at(-1));
138747
+ const escaped = needle.replace(/[.*+?^${}()|[\]\\/]/g, "\\$&");
138748
+ const pattern = `${startsWord ? `(?<!${WORD})` : ""}${escaped}${endsWord ? `(?!${WORD})` : ""}`;
138749
+ return new RegExp(pattern, "u").test(haystack);
138750
+ }
136240
138751
  function normalizeForDedupe(text) {
136241
138752
  return text.replace(/:[a-z0-9_+'-]+:/gi, "").replace(/^[ \t]*(?:>|[•◦▪‣-]|\d+\.)[ \t]*/gm, "").replace(/[*_~`]/g, "").replace(/\s+/g, "");
136242
138753
  }
@@ -136288,6 +138799,7 @@ function extractSlackMessageText(msg) {
136288
138799
  }
136289
138800
  const blockParts = [];
136290
138801
  const richTextRanges = [];
138802
+ const tableParts = new Set;
136291
138803
  if (Array.isArray(msg.blocks) && msg.blocks.length > 0) {
136292
138804
  for (const rawBlock of msg.blocks) {
136293
138805
  if (rawBlock == null || typeof rawBlock !== "object")
@@ -136312,8 +138824,10 @@ function extractSlackMessageText(msg) {
136312
138824
  richTextRanges.push([start, blockParts.length]);
136313
138825
  } else if (isTableBlock(block)) {
136314
138826
  const table = renderTableBlock(block);
136315
- if (table)
138827
+ if (table) {
138828
+ tableParts.add(blockParts.length);
136316
138829
  blockParts.push(table);
138830
+ }
136317
138831
  } else if (block.type === "header") {
136318
138832
  if (block.text?.text)
136319
138833
  blockParts.push(block.text.text);
@@ -136342,20 +138856,29 @@ function extractSlackMessageText(msg) {
136342
138856
  }
136343
138857
  }
136344
138858
  }
136345
- let bodyBlockParts = blockParts;
138859
+ const dropped = new Set;
136346
138860
  if (topText && richTextRanges.length > 0) {
136347
138861
  const richText = richTextRanges.map(([start, end]) => blockParts.slice(start, end).join(`
136348
138862
  `)).join(`
136349
138863
  `);
136350
138864
  if (normalizeForDedupe(richText) === normalizeForDedupe(decodeMrkdwn(topText))) {
136351
- const dropped = new Set;
136352
138865
  for (const [start, end] of richTextRanges) {
136353
138866
  for (let i = start;i < end; i++)
136354
138867
  dropped.add(i);
136355
138868
  }
136356
- bodyBlockParts = blockParts.filter((_, i) => !dropped.has(i));
136357
138869
  }
136358
138870
  }
138871
+ if (topText) {
138872
+ const covered = collapseWhitespace(decodeEntities(topText));
138873
+ blockParts.forEach((part, i) => {
138874
+ if (tableParts.has(i))
138875
+ return;
138876
+ const normalized = collapseWhitespace(decodeEntities(part));
138877
+ if (normalized && containsOnWordBoundaries(covered, normalized))
138878
+ dropped.add(i);
138879
+ });
138880
+ }
138881
+ const bodyBlockParts = blockParts.filter((_, i) => !dropped.has(i));
136359
138882
  const bodyText = [...attachmentParts, ...bodyBlockParts].filter(Boolean).join(`
136360
138883
  `);
136361
138884
  const bodyLines = new Set(bodyText.split(`
@@ -136474,6 +138997,77 @@ var init_slack_delete = __esm(() => {
136474
138997
  init_utils();
136475
138998
  });
136476
138999
 
139000
+ // src/be/db/tasks/slack-fold.ts
139001
+ async function getDeliveredSlackMessageTs(channelId, threadTs) {
139002
+ const rows = await getDbClient2().query(`SELECT slackTriggerMessageTs AS ts FROM agent_tasks
139003
+ WHERE slackChannelId = ? AND slackThreadTs = ? AND slackTriggerMessageTs IS NOT NULL
139004
+ UNION
139005
+ SELECT CASE WHEN json_valid(l.metadata) THEN json_extract(l.metadata, '$.slackMessageTs') END AS ts
139006
+ FROM agent_log l
139007
+ JOIN agent_tasks t ON t.id = l.taskId
139008
+ WHERE t.slackChannelId = ? AND t.slackThreadTs = ?
139009
+ AND l.eventType = 'task_steering' AND l.newValue = 'slack_reaction'`, [channelId, threadTs, channelId, threadTs]);
139010
+ return new Set(rows.flatMap((row) => row.ts ? [row.ts] : []));
139011
+ }
139012
+ async function foldIntoPendingSlackTask(args) {
139013
+ return await getDbClient2().transaction(async (tx) => {
139014
+ const result = await tx.run(`UPDATE agent_tasks
139015
+ SET task = ?,
139016
+ status = CASE WHEN ? THEN 'draft' ELSE status END,
139017
+ slackParticipants = COALESCE(?, slackParticipants),
139018
+ lastUpdatedAt = ?
139019
+ WHERE id = ? AND status = 'pending' AND task = ?`, [
139020
+ args.nextTask,
139021
+ args.toDraft ? 1 : 0,
139022
+ args.slackParticipants ? JSON.stringify(args.slackParticipants) : null,
139023
+ new Date().toISOString(),
139024
+ args.taskId,
139025
+ args.expectedTask
139026
+ ]);
139027
+ if (result.changes === 0)
139028
+ return false;
139029
+ if (args.toDraft) {
139030
+ await createLogEntry2({
139031
+ eventType: "task_status_change",
139032
+ taskId: args.taskId,
139033
+ oldValue: "pending",
139034
+ newValue: "draft"
139035
+ });
139036
+ }
139037
+ for (const messageTs of args.messageTs) {
139038
+ await createLogEntry2({
139039
+ eventType: "task_steering",
139040
+ taskId: args.taskId,
139041
+ newValue: "slack_reaction",
139042
+ metadata: { slackChannelId: args.slackChannelId, slackMessageTs: messageTs, folded: true }
139043
+ });
139044
+ }
139045
+ return true;
139046
+ });
139047
+ }
139048
+ async function createSlackTaskCarryingMessages(prepared, carried) {
139049
+ return await getDbClient2().transaction(async () => {
139050
+ const task = await createTaskExtended2(prepared.description, prepared.options);
139051
+ for (const messageTs of carried.messageTs) {
139052
+ await createLogEntry2({
139053
+ eventType: "task_steering",
139054
+ taskId: task.id,
139055
+ newValue: "slack_reaction",
139056
+ metadata: {
139057
+ slackChannelId: carried.slackChannelId,
139058
+ slackMessageTs: messageTs,
139059
+ buffered: true
139060
+ }
139061
+ });
139062
+ }
139063
+ return task;
139064
+ });
139065
+ }
139066
+ var init_slack_fold = __esm(() => {
139067
+ init_db4();
139068
+ init_runtime2();
139069
+ });
139070
+
136477
139071
  // src/slack/templates.ts
136478
139072
  var init_templates = __esm(() => {
136479
139073
  init_registry3();
@@ -136693,25 +139287,28 @@ async function downloadSlackFile(file, token, path) {
136693
139287
  return `download failed (${errorText2(error)})`;
136694
139288
  }
136695
139289
  }
136696
- async function createSlackTaskWithFiles(description, options, inbound, slack) {
139290
+ async function createSlackTaskWithFiles(description, options, inbound, slack, carriedMessageTs = []) {
136697
139291
  noteSlackInboundSideEffect("task_created");
136698
139292
  const context = { origin: "slack", slack };
139293
+ const create = async (createOptions) => carriedMessageTs.length === 0 || !createOptions.slackChannelId ? await createTaskWithSiblingAwareness(description, createOptions, context) : await createSlackTaskCarryingMessages(await prepareTaskWithSiblingAwareness(description, createOptions, context), { slackChannelId: createOptions.slackChannelId, messageTs: carriedMessageTs });
136699
139294
  if (inbound.fetched.length === 0) {
136700
- const task = await createTaskWithSiblingAwareness(description, options, context);
139295
+ const task = await create(options);
136701
139296
  return { task, unattached: inbound.failed };
136702
139297
  }
136703
- const task = await createTaskWithSiblingAwareness(description, { ...options, status: "draft" }, context);
136704
- const unattached = [...inbound.failed];
139298
+ const task = await create({ ...options, status: "draft" });
139299
+ const unattached = [...inbound.failed, ...await attachSlackFilesToDraft(task.id, inbound)];
139300
+ return { task, unattached };
139301
+ }
139302
+ async function attachSlackFilesToDraft(taskId, inbound) {
136705
139303
  const lease = setInterval(() => {
136706
- refreshDraftTaskLease2(task.id).catch((error) => console.warn(`[Slack] could not renew the draft lease of task ${task.id}: ${errorText2(error)}`));
139304
+ refreshDraftTaskLease2(taskId).catch((error) => console.warn(`[Slack] could not renew the draft lease of task ${taskId}: ${errorText2(error)}`));
136707
139305
  }, draftLeaseRefreshMs);
136708
139306
  try {
136709
- unattached.push(...(await attachSlackFilesToTask(task.id, inbound.fetched, null)).unattached);
139307
+ return (await attachSlackFilesToTask(taskId, inbound.fetched, null)).unattached;
136710
139308
  } finally {
136711
139309
  clearInterval(lease);
136712
- await promoteDraftTask2(task.id);
139310
+ await promoteDraftTask2(taskId);
136713
139311
  }
136714
- return { task, unattached };
136715
139312
  }
136716
139313
  async function attachSlackFilesToTask(taskId, fetched, agentId) {
136717
139314
  const existing = await getTaskAttachments2(taskId);
@@ -136815,6 +139412,7 @@ async function notifySlackFileFailures(client, channel, threadTs, failures) {
136815
139412
  var DOWNLOAD_TIMEOUT_MS = 30000, SIGNED_OUT_REASON = "Slack returned its sign-in page instead of the file (is the files:read scope granted?)", SIGN_IN_MARKERS, SIGN_IN_SNIFF_BYTES = 4096, draftLeaseRefreshMs = 60000, SHARED_FILE_INTENT2 = "user-upload", FETCHED_FILE_INTENT = "slack-file", BUFFERED_REASON = "follow-ups queued by ADDITIVE_SLACK carry the file name only";
136816
139413
  var init_inbound_files = __esm(() => {
136817
139414
  init_db4();
139415
+ init_slack_fold();
136818
139416
  init_task_attachment_store();
136819
139417
  init_provider();
136820
139418
  init_registry2();
@@ -137177,18 +139775,19 @@ var init_slack_list_channels = __esm(() => {
137177
139775
  var registerSlackPostTool = (server) => {
137178
139776
  createToolRegistrar(server)("slack-post", {
137179
139777
  title: "Post message to Slack channel",
137180
- description: "Post a message to a Slack channel. By default creates a new top-level message; pass `threadTs` to post as a threaded reply under an existing message (obtain the ts from `slack-start-thread`). Requires lead privileges.",
139778
+ description: "Post a message to a Slack channel. By default creates a new top-level message; pass `threadTs` to post as a threaded reply under an existing message (obtain the ts from `slack-start-thread`). For a structured result (key figures, a table, charts, links), send a `card` instead of hand-built `blocks`. Requires lead privileges.",
137181
139779
  annotations: { openWorldHint: true },
137182
139780
  inputSchema: object2({
137183
139781
  channelId: string2().min(1).describe("The Slack channel ID to post to. A user ID (U…/W…) posts in the bot's DM with that user."),
137184
- message: string2().min(1).max(4000).describe("The message content to post."),
137185
- blocks: array2(record2(string2(), unknown())).max(50).optional().describe("Optional Block Kit blocks. When omitted, a mrkdwn section is generated."),
139782
+ message: string2().min(1).max(4000).optional().describe("The message content to post. Required unless card is given; with a card it renders above it."),
139783
+ blocks: array2(record2(string2(), unknown())).max(50).optional().describe("Optional raw Block Kit blocks. When omitted, a mrkdwn section is generated. Prefer card."),
139784
+ card: cardSpecInputSchema.optional(),
137186
139785
  threadTs: string2().optional().describe("Optional parent message ts to thread under. Obtain via `slack-start-thread`. When omitted, posts as a new top-level message.")
137187
139786
  }),
137188
139787
  outputSchema: swarmToolOutputSchema({
137189
139788
  messageTs: string2().optional()
137190
139789
  })
137191
- }, async ({ channelId: requestedChannelId, message, threadTs, blocks }, requestInfo, _meta) => {
139790
+ }, async ({ channelId: requestedChannelId, message, threadTs, blocks, card }, requestInfo, _meta) => {
137192
139791
  if (!requestInfo.agentId) {
137193
139792
  return toolErr("Agent ID not found.");
137194
139793
  }
@@ -137205,6 +139804,19 @@ var registerSlackPostTool = (server) => {
137205
139804
  if (!decision.allow) {
137206
139805
  return toolErr("Posting to Slack channels requires lead privileges.");
137207
139806
  }
139807
+ if (blocks && card)
139808
+ return toolErr("Provide either blocks or card, not both.");
139809
+ if (!message && !card)
139810
+ return toolErr("Provide a message or a card.");
139811
+ let cardSlack;
139812
+ if (card) {
139813
+ const rendered = renderCard(card);
139814
+ const slack = "card" in rendered ? await cardToSlack(rendered.card) : rendered;
139815
+ if ("issues" in slack) {
139816
+ return toolErr(cardIssuesMessage(slack.issues), { data: { issues: slack.issues } });
139817
+ }
139818
+ cardSlack = slack;
139819
+ }
137208
139820
  const app = getSlackApp2();
137209
139821
  if (!app) {
137210
139822
  return toolErr("Slack not configured.");
@@ -137221,12 +139833,13 @@ var registerSlackPostTool = (server) => {
137221
139833
  return toolErr(externalChannelToolError2(channelId, blockReason));
137222
139834
  }
137223
139835
  try {
137224
- const slackMessage = markdownToSlack(message);
139836
+ const slackMessage = message ? markdownToSlack(message) : "";
137225
139837
  const sourceTask = requestInfo.sourceTaskId ? await getTaskById2(requestInfo.sourceTaskId) : undefined;
137226
139838
  const contextKey = sourceTask?.contextKey;
137227
139839
  const tree = threadTs ? await getSlackTreeMessageByThread2(channelId, threadTs) : null;
137228
139840
  const messageBlocks = [
137229
- ...blocks ?? buildMrkdwnSectionBlocks(slackMessage)
139841
+ ...cardSlack && slackMessage ? buildMrkdwnSectionBlocks(slackMessage) : [],
139842
+ ...cardSlack?.blocks ?? blocks ?? buildMrkdwnSectionBlocks(slackMessage)
137230
139843
  ];
137231
139844
  if (sourceTask && tree) {
137232
139845
  if (messageBlocks.length >= 50) {
@@ -137244,7 +139857,7 @@ var registerSlackPostTool = (server) => {
137244
139857
  }
137245
139858
  const result = await withAutoJoin(app.client, channelId, () => app.client.chat.postMessage({
137246
139859
  channel: channelId,
137247
- text: slackMessage,
139860
+ text: slackFallbackText(slackMessage, cardSlack?.text),
137248
139861
  unfurl_links: false,
137249
139862
  unfurl_media: false,
137250
139863
  username: getAgentDisplayName(agent),
@@ -137279,6 +139892,7 @@ var registerSlackPostTool = (server) => {
137279
139892
  var init_slack_post = __esm(() => {
137280
139893
  init_zod();
137281
139894
  init_db4();
139895
+ init_cards();
137282
139896
  init_rbac();
137283
139897
  init_app3();
137284
139898
  init_blocks();
@@ -137550,18 +140164,19 @@ var init_slack_read = __esm(() => {
137550
140164
  var registerSlackReplyTool = (server) => {
137551
140165
  createToolRegistrar(server)("slack-reply", {
137552
140166
  title: "Reply to Slack thread",
137553
- description: "Send a reply to a Slack thread. Use inboxMessageId for inbox messages, or taskId for task-related threads. The engine already publishes the task tree and outcome card, so send only a distinct agent-authored message. Prefer one reply per task over several, do not post progress, receipt, or acknowledgment messages, and match its length to what the user asked for.",
140167
+ description: "Send a reply to a Slack thread. Use inboxMessageId for inbox messages, or taskId for task-related threads. The engine already publishes the task tree and outcome card, so send only a distinct agent-authored message. Prefer one reply per task over several, do not post progress, receipt, or acknowledgment messages, and match its length to what the user asked for. For a structured result (key figures, a table, charts, links), send a `card` instead of hand-built `blocks`.",
137554
140168
  annotations: { openWorldHint: true },
137555
140169
  inputSchema: object2({
137556
140170
  inboxMessageId: uuid().optional().describe("The inbox message ID to reply to (for leads responding to inbox)."),
137557
140171
  taskId: uuid().optional().describe("The task ID with Slack context (for task-related threads)."),
137558
- message: string2().min(1).max(4000).describe("The message to send to the Slack thread."),
137559
- blocks: array2(record2(string2(), unknown())).max(50).optional().describe("Optional Block Kit blocks. When omitted, a mrkdwn section is generated.")
140172
+ message: string2().min(1).max(4000).optional().describe("The message to send to the Slack thread. Required unless card is given; with a card it renders above it."),
140173
+ blocks: array2(record2(string2(), unknown())).max(50).optional().describe("Optional raw Block Kit blocks. When omitted, a mrkdwn section is generated. Prefer card."),
140174
+ card: cardSpecInputSchema.optional()
137560
140175
  }),
137561
140176
  outputSchema: swarmToolOutputSchema({
137562
140177
  messageTs: string2().optional()
137563
140178
  })
137564
- }, async ({ inboxMessageId, taskId, message, blocks }, requestInfo, _meta) => {
140179
+ }, async ({ inboxMessageId, taskId, message, blocks, card }, requestInfo, _meta) => {
137565
140180
  if (!requestInfo.agentId) {
137566
140181
  return toolErr("Agent ID not found.");
137567
140182
  }
@@ -137575,6 +140190,19 @@ var registerSlackReplyTool = (server) => {
137575
140190
  if (inboxMessageId && taskId) {
137576
140191
  return toolErr("Provide either inboxMessageId or taskId, not both.");
137577
140192
  }
140193
+ if (blocks && card)
140194
+ return toolErr("Provide either blocks or card, not both.");
140195
+ if (!message && !card)
140196
+ return toolErr("Provide a message or a card.");
140197
+ let cardSlack;
140198
+ if (card) {
140199
+ const rendered = renderCard(card);
140200
+ const slack = "card" in rendered ? await cardToSlack(rendered.card) : rendered;
140201
+ if ("issues" in slack) {
140202
+ return toolErr(cardIssuesMessage(slack.issues), { data: { issues: slack.issues } });
140203
+ }
140204
+ cardSlack = slack;
140205
+ }
137578
140206
  if (inboxMessageId) {
137579
140207
  const inboxMsg = await getInboxMessageById2(inboxMessageId);
137580
140208
  if (!inboxMsg) {
@@ -137585,7 +140213,7 @@ var registerSlackReplyTool = (server) => {
137585
140213
  }
137586
140214
  slackChannelId = inboxMsg.slackChannelId;
137587
140215
  slackThreadTs = inboxMsg.slackThreadTs;
137588
- await markInboxMessageResponded2(inboxMessageId, message);
140216
+ await markInboxMessageResponded2(inboxMessageId, slackFallbackText(message ?? "", cardSlack?.text));
137589
140217
  } else if (taskId) {
137590
140218
  const task = await getTaskById2(taskId);
137591
140219
  if (!task) {
@@ -137613,13 +140241,16 @@ var registerSlackReplyTool = (server) => {
137613
140241
  }
137614
140242
  try {
137615
140243
  const citations = taskId ? await getTaskCitations(taskId) : [];
137616
- const slackMessage = renderTaskCitations(markdownToSlack(message), citations, "slack", false);
137617
- const renderedBlocks = blocks?.map((block) => JSON.parse(JSON.stringify(block, (key, value) => key === "text" && typeof value === "string" ? stripInvalidTaskCitations(value, citations) : value?.type === "mrkdwn" && typeof value.text === "string" ? { ...value, text: renderTaskCitations(value.text, citations, "slack", false) } : value)));
140244
+ const slackMessage = message ? renderTaskCitations(markdownToSlack(message), citations, "slack", false) : "";
140245
+ const customBlocks = cardSlack?.blocks ?? blocks;
140246
+ const renderedBlocks = customBlocks?.map((block) => JSON.parse(JSON.stringify(block, (key, value) => key === "text" && typeof value === "string" ? stripInvalidTaskCitations(value, citations) : value?.type === "mrkdwn" && typeof value.text === "string" ? { ...value, text: renderTaskCitations(value.text, citations, "slack", false) } : value)));
137618
140247
  const tree = await getSlackTreeMessageByThread2(slackChannelId, slackThreadTs);
137619
140248
  const messageBlocks = [
140249
+ ...cardSlack && slackMessage ? buildMrkdwnSectionBlocks(slackMessage) : [],
137620
140250
  ...renderedBlocks ?? buildMrkdwnSectionBlocks(slackMessage)
137621
140251
  ];
137622
- for (const group of taskCitationSourceGroups(blocks ? JSON.stringify(blocks) : message, citations)) {
140252
+ for (const group of taskCitationSourceGroups(cardSlack ? `${message ?? ""}
140253
+ ${JSON.stringify(cardSlack.blocks)}` : blocks ? JSON.stringify(blocks) : message ?? "", citations)) {
137623
140254
  const caption = buildCaptionBlock(group.items, {
137624
140255
  heading: group.heading,
137625
140256
  ...taskId ? { moreUrl: getTaskUrl(taskId) } : {}
@@ -137646,7 +140277,7 @@ var registerSlackReplyTool = (server) => {
137646
140277
  const result = await withAutoJoin(app.client, slackChannelId, () => app.client.chat.postMessage({
137647
140278
  channel: slackChannelId,
137648
140279
  thread_ts: slackThreadTs,
137649
- text: slackMessage,
140280
+ text: slackFallbackText(slackMessage, cardSlack?.text),
137650
140281
  unfurl_links: false,
137651
140282
  unfurl_media: false,
137652
140283
  username: getAgentDisplayName(agent),
@@ -137683,6 +140314,7 @@ var init_slack_reply = __esm(() => {
137683
140314
  init_zod();
137684
140315
  init_db4();
137685
140316
  init_task_citations2();
140317
+ init_cards();
137686
140318
  init_app3();
137687
140319
  init_blocks();
137688
140320
  init_channel_join();
@@ -138168,7 +140800,7 @@ var init_steer_task = __esm(() => {
138168
140800
  init_rbac();
138169
140801
  init_task_tool_ctx();
138170
140802
  init_utils();
138171
- init_types4();
140803
+ init_types5();
138172
140804
  steerTaskInputSchema = object2({
138173
140805
  taskId: uuid().describe("The ID of the running task to steer."),
138174
140806
  message: string2().min(1).describe("The message to send to the task."),
@@ -138779,7 +141411,7 @@ var init_store_progress = __esm(() => {
138779
141411
  init_task_terminal_effects();
138780
141412
  init_terminal_result_guard();
138781
141413
  init_utils();
138782
- init_types4();
141414
+ init_types5();
138783
141415
  init_secret_scrubber();
138784
141416
  init_task_citations();
138785
141417
  init_business_use();
@@ -139275,7 +141907,7 @@ var init_get_config = __esm(() => {
139275
141907
  init_swarm_config_guard();
139276
141908
  init_rbac();
139277
141909
  init_utils();
139278
- init_types4();
141910
+ init_types5();
139279
141911
  init_secret_scrubber();
139280
141912
  configEntryShape = looseObject({
139281
141913
  id: string2().optional(),
@@ -139371,7 +142003,7 @@ var init_list_config = __esm(() => {
139371
142003
  init_swarm_config_guard();
139372
142004
  init_rbac();
139373
142005
  init_utils();
139374
- init_types4();
142006
+ init_types5();
139375
142007
  init_secret_scrubber();
139376
142008
  configEntryShape2 = looseObject({
139377
142009
  id: string2().optional(),
@@ -139483,7 +142115,7 @@ var init_set_config = __esm(() => {
139483
142115
  init_core();
139484
142116
  init_rbac();
139485
142117
  init_utils();
139486
- init_types4();
142118
+ init_types5();
139487
142119
  configEntryShape3 = looseObject({
139488
142120
  id: string2().optional(),
139489
142121
  scope: SwarmConfigScopeSchema.optional(),
@@ -139769,7 +142401,7 @@ async function emitBudgetRefusalSideEffects(ctx, inserted) {
139769
142401
  console.warn(`[budget-refusal-notify] Failed to create follow-up task for budget refusal (task=${ctx.task.id.slice(0, 8)}): ${err}`);
139770
142402
  }
139771
142403
  }
139772
- import("./event-bus-tr6h3gv8.js").then(({ workflowEventBus }) => {
142404
+ import("./event-bus-xr83x566.js").then(({ workflowEventBus }) => {
139773
142405
  workflowEventBus.emit("task.budget_refused", {
139774
142406
  taskId: ctx.task.id,
139775
142407
  agentId: ctx.agentId,
@@ -140249,7 +142881,7 @@ var init_task_action = __esm(() => {
140249
142881
  init_apply_task_create();
140250
142882
  init_task_tool_ctx();
140251
142883
  init_utils();
140252
- init_types4();
142884
+ init_types5();
140253
142885
  init_multi_runtime2();
140254
142886
  init_get_task_details();
140255
142887
  TaskActionSchema = _enum2([
@@ -140714,7 +143346,7 @@ var init_update_profile = __esm(() => {
140714
143346
  init_db4();
140715
143347
  init_rbac();
140716
143348
  init_utils();
140717
- init_types4();
143349
+ init_types5();
140718
143350
  init_constants3();
140719
143351
  agentOutputShape4 = looseObject({
140720
143352
  id: string2().optional(),
@@ -140896,7 +143528,7 @@ async function workflowModelErrors(def, { vcsRepo } = {}) {
140896
143528
  var init_model_validation = __esm(() => {
140897
143529
  init_model_profiles();
140898
143530
  init_model_validation2();
140899
- init_types4();
143531
+ init_types5();
140900
143532
  });
140901
143533
 
140902
143534
  // src/tools/workflows/create-workflow.ts
@@ -140992,7 +143624,7 @@ var init_create_workflow = __esm(() => {
140992
143624
  init_audit_user();
140993
143625
  init_db4();
140994
143626
  init_utils();
140995
- init_types4();
143627
+ init_types5();
140996
143628
  init_workflows();
140997
143629
  init_definition2();
140998
143630
  init_model_validation();
@@ -141201,7 +143833,7 @@ var init_list_workflow_runs = __esm(() => {
141201
143833
  init_zod();
141202
143834
  init_db4();
141203
143835
  init_utils();
141204
- init_types4();
143836
+ init_types5();
141205
143837
  listWorkflowRunsInputSchema = object2({
141206
143838
  workflowId: string2().uuid().describe("Workflow ID to list runs for"),
141207
143839
  status: WorkflowRunStatusSchema.optional().describe("Filter by run status (running, waiting, completed, failed, skipped, cancelled)"),
@@ -141242,7 +143874,7 @@ var init_list_workflows = __esm(() => {
141242
143874
  init_zod();
141243
143875
  init_db4();
141244
143876
  init_utils();
141245
- init_types4();
143877
+ init_types5();
141246
143878
  });
141247
143879
 
141248
143880
  // src/workflows/patch-definition.ts
@@ -141388,7 +144020,7 @@ var init_patch_workflow = __esm(() => {
141388
144020
  init_asset_key_auth();
141389
144021
  init_audit_user();
141390
144022
  init_utils();
141391
- init_types4();
144023
+ init_types5();
141392
144024
  init_workflows();
141393
144025
  init_patch_definition();
141394
144026
  init_readiness();
@@ -141452,7 +144084,7 @@ var init_patch_workflow_node = __esm(() => {
141452
144084
  init_zod();
141453
144085
  init_audit_user();
141454
144086
  init_utils();
141455
- init_types4();
144087
+ init_types5();
141456
144088
  init_workflows();
141457
144089
  init_patch_definition();
141458
144090
  init_readiness();
@@ -141781,7 +144413,7 @@ var init_update_workflow = __esm(() => {
141781
144413
  init_audit_user();
141782
144414
  init_db4();
141783
144415
  init_utils();
141784
- init_types4();
144416
+ init_types5();
141785
144417
  init_workflows();
141786
144418
  init_definition2();
141787
144419
  init_model_validation();
@@ -141826,7 +144458,7 @@ function getEnabledCapabilities() {
141826
144458
  if (isChatSdkEnabled())
141827
144459
  capabilities.push("chat-sdk");
141828
144460
  const slack = getSlackConfiguration();
141829
- return slack.mode === "socket" && !slack.disabled ? capabilities : capabilities.filter((capability) => capability !== "slack");
144461
+ return slack.mode !== null && !slack.disabled ? capabilities : capabilities.filter((capability) => capability !== "slack");
141830
144462
  }
141831
144463
  function isScriptsOnlyMcp() {
141832
144464
  return resolveScriptsOnlyMode({ env: process.env.SCRIPTS_ONLY_MCP });
@@ -142309,4 +144941,4 @@ var init_server = __esm(() => {
142309
144941
  loggedToolAllowlistWarnings = new Set;
142310
144942
  });
142311
144943
 
142312
- export { DEFAULT_NEGOTIATED_PROTOCOL_VERSION, SUPPORTED_PROTOCOL_VERSIONS, isJSONRPCRequest, isJSONRPCResultResponse, isJSONRPCErrorResponse, JSONRPCMessageSchema, isInitializeRequest, init_types, McpServer, init_mcp, repointTrackerSyncBySwarmId, init_tracker, isRuntimePoolWakeable, isAgentReachable, init_reachability, referencedBundlePaths, skillDirs, init_manifest_format, TaskCreationBlockedError, init_errors2, resolveIdentity, renderIdentity, init_identity, recordUnmappedIdentity, init_unmapped_identities, MAX_TASK_ATTACHMENT_BYTES, recordTaskAttachmentUpload, scopeFromAttachment, backingProviderId, init_task_attachment_store, stripSiblingBlock, init_sibling_block, createTaskWithSiblingAwareness, init_sibling_awareness, transcribeAudioNotes, init_transcription, init_templates, buildEffectiveText, bufferedFileFailures, fetchSlackFiles, createSlackTaskWithFiles, notifySlackFileFailures, init_inbound_files, isAddressedToOtherUser, broadcastMatches, routeMessage, extractTaskFromMessage, init_router, extractSlackMessageText, slackInboundMessageText, collectSlackMessageFiles, init_message_text, createAdditiveBuffer, init_additive_buffer, recoverIncompleteRuns, init_recovery, handleWebhookTrigger, verifyHmacSignature, WebhookError, init_triggers, snapshotAndUpdateWorkflow, init_version, RawLlmConfigSchema, RawLlmOutputSchema, executeRawLlm, init_raw_llm, getExecutorRegistry2, initWorkflows2, init_workflows, dispatchScheduleTarget, calculateNextRun2, startScheduler2, stopScheduler2, runScheduleNow2, init_scheduler, ExtensionAssetConflictError, init_assets, ExtensionOwnershipError, getExtensionFiles, getExtensionById, getExtensionByName, listExtensions, listExtensionVersions, updateExtensionMeta, listExtensionRuns, init_db, SDK_ALLOWLIST, mcpToolNameForSdkMethod, init_sdk_allowlist, MCP_OVERFLOW_NAMESPACE, mcpOverflowAuthError, init_kv_overflow, hasKvViewArgs, resolveKvView, init_kv_view, COLOR_LITERAL_THRESHOLD, countColorLiterals, init_color_literals, toolErr, createToolRegistrar, init_utils, handleMcpBridge, init_mcp_bridge, Redacted, init_redacted, SCRIPT_SDK_RESPONSE_LIMIT_BYTES, readScriptSdkJsonResponse, init_response_limit, 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, listRegistered2, dispatchPre2, dispatchPost2, init_dispatcher, REBOOT_RETRY_PIN_TAG2, getPinCandidateAgent2, resolveLeadOnlyRecoveryAssignment2, getResumeGeneration2, getNextResumeGeneration2, inheritedModelSelection2, nextFallback2, createWorkerTaskFollowUp2, createResumeFollowUp2, createRerouteDecisionTask2, createPoolStarvationDecisionTask2, init_worker_follow_up, isGitHubEnabled, initGitHub, verifyWebhookSignature, isAgentMailEnabled, initAgentMail, verifyAgentMailWebhook, isInboxAllowed, isSenderAllowed, handleMessageReceived, init_agentmail, isAzureDevOpsEnabled, initAzureDevOps, verifyAzureDevOpsWebhook, isAzureDevOpsUrl, canonicalAzureDevOpsRepoUrl, parseAzureDevOpsRepoUrl, init_azure_devops, createdPullRequestOf, commentedPayloadOf, handlePullRequestCreated, handlePullRequestCommented, handleWorkItemCreated, handleWorkItemUpdated, handleWorkItemCommented, handleWorkItemDeleted, handleWorkItemRestored, initAzureDevOpsOutbound, init_azure_devops2, enqueueAuditRow, enqueueAdmissionRow, flushAuditBuffer, startAuditWriter, stopAuditWriter, startAuditGc, stopAuditGc, init_rbac_audit, getTelemetryIngestAnchor, init_telemetry_ingest_anchor, initApiTelemetry, syncTelemetryEnabled, init_telemetry_enable, isBitbucketEnabled, initBitbucket, verifyBitbucketWebhook, isDuplicateDelivery, markDeliveryProcessed, pullRequestEventOf, pullRequestCommentEventOf, handlePullRequestCreated2, handlePullRequestCommentCreated, handlePullRequestClosed, init_bitbucket, handlePullRequest, handleIssue, handleComment, handlePullRequestReview, handleCheckRun, handleCheckSuite, handleWorkflowRun, init_github, isGitLabEnabled, initGitLab, verifyGitLabWebhook, handleMergeRequest, handleIssue2, handleNote, handlePipeline, init_gitlab, isChatSdkEnabled, getChatSdkConfig, init_config, errorMessage, init_logger, resolveAdapterApiUrl, init_adapters, trackBackground, init_background, TelegramBotApiError, callTelegramBotApi, init_telegram_api, isTrustedTeamsServiceUrl, init_teams_origin, getSessionLabels, rememberSessionLabel, getResourceSessionLabels, init_session_labels, isChatSdkStopping, startChatSdk, getChatInstance, isChatAdapterConfigured, getChatSdkHealth, stopChatSdk, init_runtime, getJiraMetadata, updateJiraMetadata, clearJiraMetadata, init_metadata, registerJiraWebhook, deleteJiraWebhook, init_webhook_lifecycle, isJiraEnabled, initJira, init_app, handleJiraWebhook, init_webhook, init_jira, handleAgentSessionEvent, handleIssueUpdate, handleIssueDelete, handleAgentSessionPrompted, init_sync, isLinearEnabled, initLinear, init_app2, init_linear, init_slack, verifyPageSession, LEGACY_PAGE_SESSION_COOKIE, isCookieSafePageId, extractPageSession, extractLegacyPageSession, extractAndVerifyCookie, isLocalDevPageRequest, pageSessionSetCookies, init_page_session, resolveHttpRequestAuth, init_auth, getDeploymentEnvValue, loadGlobalConfigsIntoEnv, reloadGlobalConfigsAndIntegrations, scheduleIntegrationsReload, handleCore, init_core, MCP_MAX_TOOL_INPUT_ELEMENTS, MCP_MAX_REQUEST_BODY_BYTES, init_mcp_limits, userCtx, init_task_tool_ctx, requestPrincipal, agentFirstPrincipal, requireAuthKind, rejectGuest, init_request_principal, handleApps, init_apps, cancelApprovalRequest, cancelApprovalRequestAndRun, init_approval_cancel, getUserCommsPrefs, init_requester_comms, getTaskDetailsInputSchema, getTaskDetailsOutputSchema, getTaskDetailsHandler, init_get_task_details, cancelTaskInputSchema, cancelTaskOutputSchema, cancelTaskHandler, init_cancel_task, 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, getTasksInputSchema, getTasksOutputSchema, getTasksHandler, init_get_tasks, reservedNamespaceError, privateNamespaceError, reservedRoomKeyError, init_kv_reserved_namespaces, updateMcpServerChecked, init_mcp_server_checked_update, updateTouchesStdioExecution, init_mcp_server_stdio_gate, canReadMemory, init_access, getLinksForMemory, init_links_store, expandCandidatesWithGraph, init_graph_expansion, isApiDraining, drainApi, init_api_drain, markKapsoMessageRead, sendKapsoReaction, init_client, getKapsoConfig, getKapsoNumberMapping, markKapsoMessageSeen, init_config2, changesAllowMerge, init_repo_merge_policy, updateSwarmRepoChecked, init_repo_checked_update, getCombConfig, init_config3, resolveRoomNamespace, roomRequestInfo, authorizeRoomNamespace, sessionAccessTopic, sessionPresenceRoot, init_auth2, RoomOperationSchema, init_document, removeAwarenessStates, init_awareness, roomTopic, decodeRoomSnapshot, roomView, getRoom, changeRoom, applyRoomUpdate, resetRoom, sweepRooms, closeRooms, removeNamespaceRooms, init_rooms, init_scheduler2, MEMORY_KEYS_DEFAULT_PREFIX, MEMORY_KEYS_MAX_LIMIT, estimateTokens, posteriorMean, listMemoryKeys, checkChunkIntegrity, getMemoryChunks, getPosteriorsByIds, init_key_browser, createEvent, createEventsBatch, getEventCountsFiltered, getEventsFiltered, init_events, mergeScheduleTiming, validateRecurringTiming, init_validate, followUpThreadForSourceTask, evaluateFollowUpRedelegation, init_follow_up_redelegation_guard, checkOutputSchemaShape, sendTaskOutputSchema, sendTaskHandler, init_send_task, steerTaskUserInputSchema, steerTaskOutputSchema, steerTaskHandler, init_steer_task, skipReasonFrom, finalizeSkippedTaskReaction, init_task_skip, IMPROVEMENT_TEXT_MAX, IMPROVEMENT_STATUSES, IMPROVEMENT_SOURCES, ImprovementError, isImprovementsEnabled, getImprovement, listImprovements, createImprovement, approveAndSend, discardImprovement, improvementLeakHints, init_improvements, canClaim, init_budget_admission, emitBudgetRefusalSideEffects, init_budget_refusal_notify, workflowModelErrors, init_model_validation, patchWorkflowDefinition, init_patch_definition, idempotencyKeyHeader, readIdempotencyKey, replayAcceptedOperation, init_idempotency_key, resolveScriptsOnlyMode, init_scripts_only_mode, ALL_CAPABILITIES, hasCapability, getEnabledCapabilities, createServer, init_server };
144944
+ export { DEFAULT_NEGOTIATED_PROTOCOL_VERSION, SUPPORTED_PROTOCOL_VERSIONS, isJSONRPCRequest, isJSONRPCResultResponse, isJSONRPCErrorResponse, JSONRPCMessageSchema, isInitializeRequest, init_types, McpServer, init_mcp, referencedBundlePaths, skillDirs, init_manifest_format, recoverIncompleteRuns, init_recovery, handleWebhookTrigger, verifyHmacSignature, WebhookError, init_triggers, snapshotAndUpdateWorkflow, init_version, applyPreTaskCreate, init_apply_task_create, TaskCreationBlockedError, init_errors, RawLlmConfigSchema, RawLlmOutputSchema, executeRawLlm, init_raw_llm, getExecutorRegistry2, initWorkflows2, init_workflows, 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, listRegistered2, dispatchPre2, dispatchPost2, init_dispatcher, resolveIdentity, renderIdentity, init_identity, 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, repointTrackerSyncBySwarmId, init_tracker, REBOOT_RETRY_PIN_TAG2, getPinCandidateAgent2, resolveLeadOnlyRecoveryAssignment2, getResumeGeneration2, getNextResumeGeneration2, inheritedModelSelection2, nextFallback2, createWorkerTaskFollowUp2, createResumeFollowUp2, createRerouteDecisionTask2, createPoolStarvationDecisionTask2, init_worker_follow_up, isGitHubEnabled, initGitHub, verifyWebhookSignature, isAgentMailEnabled, initAgentMail, verifyAgentMailWebhook, isInboxAllowed, isSenderAllowed, handleMessageReceived, init_agentmail, isAzureDevOpsEnabled, initAzureDevOps, verifyAzureDevOpsWebhook, isAzureDevOpsUrl, canonicalAzureDevOpsRepoUrl, parseAzureDevOpsRepoUrl, init_azure_devops, createdPullRequestOf, commentedPayloadOf, handlePullRequestCreated, handlePullRequestCommented, handleWorkItemCreated, handleWorkItemUpdated, handleWorkItemCommented, handleWorkItemDeleted, handleWorkItemRestored, initAzureDevOpsOutbound, init_azure_devops2, enqueueAuditRow, enqueueAdmissionRow, flushAuditBuffer, startAuditWriter, stopAuditWriter, startAuditGc, stopAuditGc, init_rbac_audit, getTelemetryIngestAnchor, init_telemetry_ingest_anchor, initApiTelemetry, syncTelemetryEnabled, init_telemetry_enable, isBitbucketEnabled, initBitbucket, verifyBitbucketWebhook, isDuplicateDelivery, markDeliveryProcessed, pullRequestEventOf, pullRequestCommentEventOf, handlePullRequestCreated2, handlePullRequestCommentCreated, handlePullRequestClosed, init_bitbucket, handlePullRequest, handleIssue, handleComment, handlePullRequestReview, handleCheckRun, handleCheckSuite, handleWorkflowRun, init_github, isGitLabEnabled, initGitLab, verifyGitLabWebhook, handleMergeRequest, handleIssue2, handleNote, handlePipeline, init_gitlab, isChatSdkEnabled, getChatSdkConfig, init_config, errorMessage, init_logger, resolveAdapterApiUrl, init_adapters, trackBackground, init_background, TelegramBotApiError, callTelegramBotApi, init_telegram_api, isTrustedTeamsServiceUrl, init_teams_origin, getSessionLabels, rememberSessionLabel, getResourceSessionLabels, init_session_labels, isChatSdkStopping, startChatSdk, getChatInstance, isChatAdapterConfigured, getChatSdkHealth, stopChatSdk, init_runtime, getJiraMetadata, updateJiraMetadata, clearJiraMetadata, init_metadata, registerJiraWebhook, deleteJiraWebhook, init_webhook_lifecycle, isJiraEnabled, initJira, init_app, handleJiraWebhook, init_webhook, init_jira, handleAgentSessionEvent, handleIssueUpdate, handleIssueDelete, handleAgentSessionPrompted, init_sync, isLinearEnabled, initLinear, init_app2, init_linear, init_slack, verifyPageSession, LEGACY_PAGE_SESSION_COOKIE, isCookieSafePageId, extractPageSession, extractLegacyPageSession, extractAndVerifyCookie, isLocalDevPageRequest, pageSessionSetCookies, init_page_session, resolveHttpRequestAuth, init_auth, getDeploymentEnvValue, loadGlobalConfigsIntoEnv, reloadGlobalConfigsAndIntegrations, scheduleIntegrationsReload, handleCore, init_core, MCP_MAX_TOOL_INPUT_ELEMENTS, MCP_MAX_REQUEST_BODY_BYTES, init_mcp_limits, userCtx, init_task_tool_ctx, resolveRequestPrincipal, requestPrincipal, agentFirstPrincipal, requireAuthKind, rejectGuest, init_request_principal, resolveTaskRequester, init_task_requester, handleApps, init_apps, cancelApprovalRequest, cancelApprovalRequestAndRun, init_approval_cancel, getUserCommsPrefs, init_requester_comms, getTaskDetailsInputSchema, getTaskDetailsOutputSchema, getTaskDetailsHandler, init_get_task_details, cancelTaskInputSchema, cancelTaskOutputSchema, cancelTaskHandler, init_cancel_task, 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, 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, expandCandidatesWithGraph, init_graph_expansion, isApiDraining, drainApi, init_api_drain, markKapsoMessageRead, sendKapsoReaction, init_client, getKapsoConfig, getKapsoNumberMapping, markKapsoMessageSeen, init_config2, changesAllowMerge, init_repo_merge_policy, updateSwarmRepoChecked, init_repo_checked_update, getCombConfig, init_config3, resolveRoomNamespace, roomRequestInfo, authorizeRoomNamespace, sessionAccessTopic, sessionPresenceRoot, init_auth2, RoomOperationSchema, init_document, removeAwarenessStates, init_awareness, roomTopic, decodeRoomSnapshot, roomView, getRoom, changeRoom, applyRoomUpdate, resetRoom, sweepRooms, closeRooms, removeNamespaceRooms, init_rooms, init_scheduler2, MEMORY_KEYS_DEFAULT_PREFIX, MEMORY_KEYS_MAX_LIMIT, estimateTokens, posteriorMean, listMemoryKeys, checkChunkIntegrity, getMemoryChunks, getPosteriorsByIds, init_key_browser, createEvent, createEventsBatch, getEventCountsFiltered, getEventsFiltered, init_events, mergeScheduleTiming, validateRecurringTiming, init_validate, followUpThreadForSourceTask, evaluateFollowUpRedelegation, init_follow_up_redelegation_guard, checkOutputSchemaShape, sendTaskOutputSchema, sendTaskHandler, init_send_task, steerTaskUserInputSchema, steerTaskOutputSchema, steerTaskHandler, init_steer_task, skipReasonFrom, finalizeSkippedTaskReaction, init_task_skip, IMPROVEMENT_TEXT_MAX, IMPROVEMENT_STATUSES, IMPROVEMENT_SOURCES, ImprovementError, isImprovementsEnabled, getImprovement, listImprovements, createImprovement, approveAndSend, discardImprovement, improvementLeakHints, init_improvements, canClaim, init_budget_admission, emitBudgetRefusalSideEffects, init_budget_refusal_notify, workflowModelErrors, init_model_validation, patchWorkflowDefinition, init_patch_definition, idempotencyKeyHeader, readIdempotencyKey, replayAcceptedOperation, init_idempotency_key, resolveScriptsOnlyMode, init_scripts_only_mode, ALL_CAPABILITIES, hasCapability, getEnabledCapabilities, createServer, init_server };