@desplega.ai/agent-swarm 2.8.3 → 2.9.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (597) hide show
  1. package/dist/acp-adapter-g909b5hw.js +16 -0
  2. package/dist/acp-targets-ny75x1qy.js +23 -0
  3. package/dist/{actions-ewz7bp4g.js → actions-b9qgrmeq.js} +82 -21
  4. package/dist/agent-fs-provision-b5dhdsbd.js +27 -0
  5. package/dist/{amp-adapter-f25tqhnf.js → amp-adapter-vtax2c9s.js} +3 -3
  6. package/dist/{anthropic-messages-jkva0zps.js → anthropic-messages-r5xf5hqw.js} +37 -37
  7. package/dist/{app-mkptw0k7.js → app-g2z15hax.js} +9 -4
  8. package/dist/approval-notifications-yt13wp8r.js +23 -0
  9. package/dist/{assistant-c47rfe77.js → assistant-2cgfxsgk.js} +56 -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-3gwy0f60.js} +1 -1
  12. package/dist/{boot-reembed-htr73hbs.js → boot-reembed-92g7s5zp.js} +1 -1
  13. package/dist/{boot-reembed-1ghy2sab.js → boot-reembed-mywmyp4s.js} +1 -1
  14. package/dist/{boot-scrub-sweep-yrytg42z.js → boot-scrub-sweep-7dkdzqxx.js} +84 -13
  15. package/dist/{boot-seeds-n2b3dx4e.js → boot-seeds-ce7rvgq1.js} +4 -4
  16. package/dist/{boxd-jmfqgkqa.js → boxd-wn235q80.js} +7 -7
  17. package/dist/claude-adapter-3m4q7735.js +28 -0
  18. package/dist/{claude-managed-adapter-hddmxjyj.js → claude-managed-adapter-t8nfgcgz.js} +4 -4
  19. package/dist/{claude-managed-setup-hfvry1bd.js → claude-managed-setup-c217draw.js} +10 -10
  20. package/dist/{claude-sdk-session-0hamqzc7.js → claude-sdk-session-7fbqm51z.js} +9386 -9196
  21. package/dist/{cli-yjdgea32.js → cli-1jx0srjt.js} +17 -17
  22. package/dist/{cli-sdvcrq5x.js → cli-1jykg0py.js} +18 -14
  23. package/dist/{cli-k96cecs7.js → cli-2czxfnvj.js} +1221 -357
  24. package/dist/{cli-qmqt520k.js → cli-2dq9yv8p.js} +2 -2
  25. package/dist/{cli-e2w34h6z.js → cli-2xs8tsf7.js} +132 -85
  26. package/dist/{cli-z8cvws4c.js → cli-2yjj3e31.js} +907 -56
  27. package/dist/{cli-mdpbjnzq.js → cli-32djehja.js} +42 -42
  28. package/dist/{cli-gpz1d0t2.js → cli-3j873zxq.js} +4 -4
  29. package/dist/cli-43ms35q9.js +270 -0
  30. package/dist/cli-47hz21se.js +25584 -0
  31. package/dist/{cli-n515ex5z.js → cli-4ymxrwg5.js} +16 -16
  32. package/dist/{cli-f1kwb5fc.js → cli-5a6pqy45.js} +333 -21
  33. package/dist/{cli-93t5s4zq.js → cli-5gpqgs8b.js} +2 -2
  34. package/dist/{cli-15204js0.js → cli-6237rnyr.js} +1 -1
  35. package/dist/{cli-4ax9mvvg.js → cli-67mwzr35.js} +9 -9
  36. package/dist/{cli-t5ys4ebm.js → cli-6945ywhr.js} +3 -3
  37. package/dist/{cli-0bcgyj5b.js → cli-6ehs4mta.js} +87 -8
  38. package/dist/{cli-6yygkr0w.js → cli-6ym4jhzp.js} +15 -7
  39. package/dist/{cli-8bpgbr8k.js → cli-7evph51z.js} +5 -5
  40. package/dist/{cli-dtdht77h.js → cli-7mv4h3sn.js} +2 -2
  41. package/dist/{cli-nx2n3z6p.js → cli-7sf9sb0w.js} +3 -2
  42. package/dist/{cli-pe4d96rb.js → cli-7zm3b3f5.js} +1 -1
  43. package/dist/cli-8zh9nrew.js +78 -0
  44. package/dist/cli-9ttx00s3.js +137 -0
  45. package/dist/{cli-x6t50dmw.js → cli-9w8712tq.js} +620 -281
  46. package/dist/{cli-8476gtwf.js → cli-b6px1k1q.js} +1 -1
  47. package/dist/{cli-k2rw11py.js → cli-b91nz213.js} +5 -5
  48. package/dist/{cli-7c5tgqhf.js → cli-bg63qmsx.js} +10 -10
  49. package/dist/{cli-qps8je6j.js → cli-bkjdknnp.js} +54 -10
  50. package/dist/{cli-gn9y6fn7.js → cli-bnqncekd.js} +2 -2
  51. package/dist/{cli-s7zz734a.js → cli-br0924pw.js} +1 -1
  52. package/dist/{cli-h9yy18gy.js → cli-ctx0b85j.js} +5484 -5078
  53. package/dist/{cli-0vksaxvr.js → cli-dgs10ttj.js} +2 -2
  54. package/dist/cli-dqgnbnxs.js +132 -0
  55. package/dist/{cli-q6mfk1ej.js → cli-dzzh58sy.js} +2 -2
  56. package/dist/{cli-2znm3dzj.js → cli-eds5xnsz.js} +2 -2
  57. package/dist/{cli-c0xjnr8z.js → cli-f3jyzq4g.js} +2 -2
  58. package/dist/cli-f8x9drqr.js +84 -0
  59. package/dist/{cli-ztq5z4e1.js → cli-f9gz2vyj.js} +6 -6
  60. package/dist/{cli-bhsfbmk8.js → cli-fh97xn30.js} +93 -44
  61. package/dist/cli-fkef327x.js +103 -0
  62. package/dist/{cli-fsgttth8.js → cli-g0vv9dg4.js} +13 -13
  63. package/dist/{cli-kd56bmk4.js → cli-gabsjg8x.js} +3 -1
  64. package/dist/{cli-1m96dc36.js → cli-gfy38pvt.js} +3 -3
  65. package/dist/{cli-922z7gwm.js → cli-h9yqfzx9.js} +15 -11
  66. package/dist/{cli-5a7szzfh.js → cli-hnamkvnc.js} +2 -2
  67. package/dist/{cli-c3ng0mb4.js → cli-j7svy295.js} +71 -818
  68. package/dist/{cli-yss07azk.js → cli-jaw5v1sy.js} +3 -3
  69. package/dist/cli-jkw6ptfw.js +921 -0
  70. package/dist/{cli-s8p8hhty.js → cli-jm0hvmz2.js} +2 -2
  71. package/dist/{cli-knva3nmx.js → cli-jwampxxq.js} +8 -6
  72. package/dist/cli-kj0hyr43.js +51 -0
  73. package/dist/{cli-tnzebztn.js → cli-kpgcm7xy.js} +13 -1
  74. package/dist/{cli-9zmb7ptc.js → cli-kxx4k2jw.js} +8 -753
  75. package/dist/{cli-am1ptset.js → cli-m7c2380k.js} +208 -194
  76. package/dist/{cli-kw44j53p.js → cli-m7zvgt57.js} +45 -38
  77. package/dist/{cli-504akrp9.js → cli-meydjstb.js} +3 -3
  78. package/dist/{cli-54qr8mcd.js → cli-mhapr559.js} +4 -4
  79. package/dist/{cli-tf79ryyy.js → cli-mjw0yf82.js} +3 -3
  80. package/dist/{cli-rjvsf9qa.js → cli-mkwkwq81.js} +14 -11
  81. package/dist/{cli-n30e0hcp.js → cli-mna6pmfx.js} +2 -2
  82. package/dist/{cli-awwptga4.js → cli-mw620q3n.js} +1 -1
  83. package/dist/{cli-6wj7p986.js → cli-n3qe7tyr.js} +172 -168
  84. package/dist/{cli-4dpkjc2e.js → cli-nafvvsp8.js} +9 -9
  85. package/dist/{cli-sg27rk2t.js → cli-nbt14he0.js} +25 -19
  86. package/dist/{cli-7akn6ze9.js → cli-nh7x3133.js} +7 -28
  87. package/dist/{cli-zdaypkq9.js → cli-p4kckx1z.js} +285 -97
  88. package/dist/{cli-n5t077me.js → cli-pb2ay3sh.js} +10 -3
  89. package/dist/{cli-t4dv07kr.js → cli-psffsanb.js} +4 -3
  90. package/dist/{cli-mwwmka77.js → cli-pyjn0qhk.js} +2712 -268
  91. package/dist/{cli-emekyyhr.js → cli-q2d3e1k1.js} +1 -1
  92. package/dist/{cli-vqva1teb.js → cli-qe909n63.js} +2 -2
  93. package/dist/{cli-2d0cghfn.js → cli-qj39vrc6.js} +1 -1
  94. package/dist/{cli-tas6ckky.js → cli-rq5rpv6k.js} +2 -2
  95. package/dist/{cli-0agcv1v5.js → cli-rqx70rcz.js} +2 -2
  96. package/dist/{cli-kmemts3w.js → cli-sn650d7x.js} +39 -69
  97. package/dist/{cli-98rwmcyc.js → cli-snxhtehz.js} +3 -3
  98. package/dist/{cli-d829z3xc.js → cli-spfz393q.js} +6 -6
  99. package/dist/{cli-500c09j9.js → cli-t9ga4qmb.js} +14 -14
  100. package/dist/{cli-me0r8gzr.js → cli-td9tb872.js} +27 -25
  101. package/dist/cli-tvc4jag9.js +754 -0
  102. package/dist/{cli-6ek0hff4.js → cli-ty3gha1p.js} +4 -4
  103. package/dist/{cli-c71n3bxq.js → cli-v57d7fmm.js} +2 -2
  104. package/dist/{cli-j8cjdzan.js → cli-vs9vdpy0.js} +1 -1
  105. package/dist/cli-vt89089n.js +296 -0
  106. package/dist/{cli-pxwtcgcp.js → cli-vyff45ve.js} +2 -2
  107. package/dist/{cli-x3ex5bqf.js → cli-w16kwbzw.js} +1 -1
  108. package/dist/{cli-bj6qhgte.js → cli-w4n323t3.js} +197 -45
  109. package/dist/{cli-rqfvkx5t.js → cli-wn13hhdt.js} +13 -13
  110. package/dist/{cli-skmhsnqh.js → cli-x40a0w9j.js} +1 -1
  111. package/dist/{cli-zeaehgyd.js → cli-xag7btpe.js} +2 -2
  112. package/dist/{cli-k28wkapa.js → cli-xf1wn5ns.js} +2 -2
  113. package/dist/{cli-rh15cakt.js → cli-xwsm6xkr.js} +1 -1
  114. package/dist/{cli-dpsfwh7n.js → cli-y2ewxhth.js} +56 -31
  115. package/dist/{cli-vx421edw.js → cli-ysvspf5e.js} +9 -7
  116. package/dist/{cli-crpf163n.js → cli-zh0e5x7p.js} +16 -26
  117. package/dist/{cli-4e1hfbpq.js → cli-zr6qy15y.js} +24 -24
  118. package/dist/cli.js +33 -29
  119. package/dist/{codex-adapter-2brxx5ta.js → codex-adapter-n656pvb8.js} +9 -8
  120. package/dist/{codex-hook-c930c3ea.js → codex-hook-59atdwd8.js} +6 -6
  121. package/dist/{codex-login-cbrs1h5w.js → codex-login-a239g1ah.js} +1 -1
  122. package/dist/{codex-session-runner-y9anfj0r.js → codex-session-runner-p0fbv5y9.js} +10 -9
  123. package/dist/{commands-wn9q06qr.js → commands-gwea8z5p.js} +3 -3
  124. package/dist/{controller-fw608czd.js → controller-t67c3grh.js} +9 -6
  125. package/dist/{controllers-connect-63j5rdcm.js → controllers-connect-ks155r0h.js} +28 -25
  126. package/dist/{cursor-adapter-6mb9jme8.js → cursor-adapter-ygwrtmkv.js} +2 -2
  127. package/dist/{db-y4wfrzbm.js → db-kpmx06s9.js} +21 -13
  128. package/dist/{db-0m6v5tq4.js → db-rb2xqdb1.js} +3 -3
  129. package/dist/{devin-adapter-r0yx3gv8.js → devin-adapter-zp4tqq53.js} +1 -1
  130. package/dist/{dispatcher-9tq2zzdj.js → dispatcher-31sm0ej2.js} +21 -18
  131. package/dist/{docker-j75atvpt.js → docker-09tkkg0n.js} +47 -8
  132. package/dist/{dsh-adapter-t09sv4tq.js → dsh-adapter-qyxh0w31.js} +2 -2
  133. package/dist/{e2b-a7vzs2vj.js → e2b-3v1e745x.js} +6 -6
  134. package/dist/{e2b-7s9dscap.js → e2b-sm28k0k3.js} +6 -6
  135. package/dist/{easter-egg-3d-fbwvmwhe.js → easter-egg-3d-00wjscn6.js} +1 -1
  136. package/dist/{embedding-space-wh8de1t9.js → embedding-space-qhw4g68n.js} +6 -6
  137. package/dist/{embeddings-3hpbdtjr.js → embeddings-zdv9ke6x.js} +1 -1
  138. package/dist/{event-bus-tr6h3gv8.js → event-bus-xr83x566.js} +1 -1
  139. package/dist/{execute-4bdf8sdy.js → execute-zna8wwr7.js} +1 -1
  140. package/dist/{external-channel-ts2fwqh0.js → external-channel-1ac6t56s.js} +2 -2
  141. package/dist/fx-adapter-sk7n0fzc.js +19 -0
  142. package/dist/{getMachineId-bsd-nfgrzarv.js → getMachineId-bsd-637a7rbk.js} +3 -3
  143. package/dist/{getMachineId-darwin-wz886dsk.js → getMachineId-darwin-9vytrcnn.js} +3 -3
  144. package/dist/{getMachineId-linux-1nng3p1p.js → getMachineId-linux-mkzsvyyz.js} +3 -3
  145. package/dist/{getMachineId-unsupported-a0428vw9.js → getMachineId-unsupported-4cfs2n11.js} +3 -3
  146. package/dist/{getMachineId-win-h45922nq.js → getMachineId-win-154s3qma.js} +3 -3
  147. package/dist/{google-generative-ai-h7s3e9kk.js → google-generative-ai-maq6c9bf.js} +1 -1
  148. package/dist/{google-vertex-fhxaafzw.js → google-vertex-2jgsw2nb.js} +5 -5
  149. package/dist/grok-adapter-sjbcm5ew.js +19 -0
  150. package/dist/handlers-yzy0c87x.js +35 -0
  151. package/dist/{heartbeat-2ze5fzpc.js → heartbeat-2f6z4kdx.js} +24 -21
  152. package/dist/{hook-gaehe2w5.js → hook-8y0gvtp1.js} +14 -14
  153. package/dist/{hook-ca54yd4s.js → hook-w1skzaqc.js} +5 -5
  154. package/dist/{http-jfg8t2yk.js → http-wghxvpef.js} +2333 -589
  155. package/dist/{index-d6wkh8ar.js → index-0h6qd4p1.js} +34 -24
  156. package/dist/index-25pvya7q.js +40 -0
  157. package/dist/index-2t4859r5.js +35 -0
  158. package/dist/{index-enn321kd.js → index-42jq9yy3.js} +3 -3
  159. package/dist/{index-khe3gp0k.js → index-4k7m5dgj.js} +645 -370
  160. package/dist/index-620y7jzq.js +15 -0
  161. package/dist/{index-gjwaqaq8.js → index-8p0j4h4j.js} +506 -43
  162. package/dist/{index-3gv6sc4z.js → index-8zn8nxn5.js} +1 -1
  163. package/dist/{index-m5gx1xd6.js → index-9myfj74s.js} +40 -40
  164. package/dist/{index-3yvzbhxd.js → index-9zkchs9t.js} +336 -193
  165. package/dist/{index-0rvk3vd4.js → index-b5wgnm78.js} +47 -47
  166. package/dist/index-cxca2t8y.js +36 -0
  167. package/dist/{index-qwj6ntem.js → index-e3krvkh2.js} +4 -4
  168. package/dist/{index-hjhfk3ra.js → index-pe3d8jfy.js} +3 -3
  169. package/dist/index-rv89fvzf.js +572 -0
  170. package/dist/{index-csgrxedz.js → index-s71ez27v.js} +1 -1
  171. package/dist/{keepalive-k2a3qe73.js → keepalive-sh02349h.js} +4 -4
  172. package/dist/lead-gk4h5eg7.js +74 -0
  173. package/dist/{maintenance-gb5sd5nc.js → maintenance-yj0dcjja.js} +1 -1
  174. package/dist/{node-252anz2h.js → node-dqm4xgxw.js} +4 -4
  175. package/dist/{node-ray25snp.js → node-zd6shky9.js} +3 -3
  176. package/dist/{oauth-refresh-sweep-y7rm6bkb.js → oauth-refresh-sweep-d9xedk66.js} +3 -3
  177. package/dist/{onboard-jmc5qerv.js → onboard-dpgjn03r.js} +8 -8
  178. package/dist/{openai-codex-responses-k9gapdze.js → openai-codex-responses-bkcd8pjj.js} +9 -9
  179. package/dist/{openai-responses-4d5dx3c7.js → openai-responses-gbh0wfqe.js} +13 -13
  180. package/dist/{opencode-adapter-7eade9ev.js → opencode-adapter-2d31cpjc.js} +7 -6
  181. package/dist/{otel-impl-8j1xhxqd.js → otel-impl-1skarpfq.js} +110 -110
  182. package/dist/pending-bfmxtx0g.js +82 -0
  183. package/dist/{pi-mono-adapter-yqmaf32x.js → pi-mono-adapter-gvppnasy.js} +43 -16
  184. package/dist/{pricing-refresh-1nj722h6.js → pricing-refresh-c6b325mk.js} +2 -2
  185. package/dist/{rbac-roles-b1mtr6dr.js → rbac-roles-h80qbdbs.js} +3 -3
  186. package/dist/{rbac-roles-n1f3frk1.js → rbac-roles-zfcx68tx.js} +10 -3
  187. package/dist/{render-v2-1gfpd8rj.js → render-v2-nx20t3rb.js} +7 -4
  188. package/dist/{resume-w1s1eh5v.js → resume-5ep8agan.js} +11 -7
  189. package/dist/{runtime-84g5egsc.js → runtime-r3pj4mce.js} +1 -1
  190. package/dist/{session-access-y6z1txk4.js → session-access-n7p3m15b.js} +4 -4
  191. package/dist/{session-source-backfill-gxxwfh12.js → session-source-backfill-v8mt0zwn.js} +4 -4
  192. package/dist/{setup-r91gstyk.js → setup-z1psaqhe.js} +1 -1
  193. package/dist/thread-buffer-a1re2r9r.js +38 -0
  194. package/dist/{virtual-modules-cgnj6kme.js → virtual-modules-rrbjdpxn.js} +5 -5
  195. package/dist/{work-objects-qcxzg61c.js → work-objects-4aghh73z.js} +31 -23
  196. package/dist/worker-3dyyb8ev.js +74 -0
  197. package/dist/{worker-follow-up-y2d2h7km.js → worker-follow-up-166zmex1.js} +21 -18
  198. package/dist/{x-qhxq2ama.js → x-wg164ss9.js} +2 -2
  199. package/openapi.json +2561 -131
  200. package/package.json +15 -11
  201. package/plugin/commands/create-pr.md +1 -1
  202. package/plugin/pi-skills/create-pr/SKILL.md +1 -1
  203. package/src/apps/action-runner.ts +21 -1
  204. package/src/apps/catalog.generated.json +667 -18
  205. package/src/apps/page-validator.ts +341 -8
  206. package/src/assets/key.ts +6 -0
  207. package/src/be/agent-fs-user-keys.ts +186 -0
  208. package/src/be/audit-user.ts +27 -13
  209. package/src/be/automation-preflight.test.ts +14 -14
  210. package/src/be/automation-preflight.ts +24 -16
  211. package/src/be/boot-scrub-sweep.ts +143 -14
  212. package/src/be/caller-session-group.ts +86 -0
  213. package/src/be/checklist.ts +375 -0
  214. package/src/be/db/agents.ts +12 -1
  215. package/src/be/db/approvals.ts +26 -0
  216. package/src/be/db/model-profiles.ts +4 -1
  217. package/src/be/db/session-costs.ts +219 -0
  218. package/src/be/db/session-log-reasoning.ts +36 -0
  219. package/src/be/db/session-moves.ts +23 -0
  220. package/src/be/db/session-tree.ts +78 -19
  221. package/src/be/db/tasks/eligibility-scan.ts +14 -0
  222. package/src/be/db/tasks/read.ts +7 -3
  223. package/src/be/db/tasks/slack-fold.ts +116 -0
  224. package/src/be/db/tasks/write.ts +67 -1
  225. package/src/be/db-queries/mcp-servers.ts +13 -0
  226. package/src/be/db-queries/oauth.ts +6 -0
  227. package/src/be/db-queries/task-artifacts.ts +10 -8
  228. package/src/be/db.ts +242 -319
  229. package/src/be/extensions/assets.ts +17 -13
  230. package/src/be/import/config.ts +54 -0
  231. package/src/be/import/dir-source.ts +372 -0
  232. package/src/be/import/index.ts +149 -0
  233. package/src/be/import/pending.ts +71 -0
  234. package/src/be/import/schema.ts +137 -0
  235. package/src/be/import/seeders.ts +462 -0
  236. package/src/be/key-window-usage.ts +385 -0
  237. package/src/be/migrations/297_import_ownership.sql +34 -0
  238. package/src/be/migrations/301_favorites_key_type.sql +36 -0
  239. package/src/be/migrations/302_checklist_items.sql +23 -0
  240. package/src/be/migrations/303_task_ui_specs.sql +28 -0
  241. package/src/be/migrations/306_provider_account_telemetry.sql +1 -0
  242. package/src/be/migrations/307_session_cost_credential_attribution.sql +23 -0
  243. package/src/be/migrations/310_session_logs_reasoning.sql +12 -0
  244. package/src/be/multi-runtime.ts +8 -1
  245. package/src/be/rbac-roles.ts +8 -1
  246. package/src/be/runtime-pools/db.ts +3 -0
  247. package/src/be/runtime-pools/demand.ts +20 -2
  248. package/src/be/runtime-pools/reachability.ts +31 -0
  249. package/src/be/runtime-pools/routing.ts +8 -1
  250. package/src/be/runtime-pools/supervisor.ts +6 -7
  251. package/src/be/savings/read.ts +8 -6
  252. package/src/be/script-credential-broker.ts +2 -2
  253. package/src/be/scripts/typecheck.ts +4 -4
  254. package/src/be/seed/agent-fs-provision.ts +104 -19
  255. package/src/be/seed/index.ts +1 -1
  256. package/src/be/seed/registry.ts +27 -8
  257. package/src/be/seed/runner.ts +1 -1
  258. package/src/be/seed/schedules-seeder.ts +24 -6
  259. package/src/be/seed/seed-toggle.ts +32 -0
  260. package/src/be/seed/types.ts +6 -0
  261. package/src/be/seed-scripts/catalog/boot-triage.inline.ts +1 -0
  262. package/src/be/seed-scripts/catalog/boot-triage.ts +1 -0
  263. package/src/be/seed-scripts/catalog/dreaming-gather.ts +2 -2
  264. package/src/be/seed-scripts/catalog/wait-for-task.ts +5 -1
  265. package/src/be/seed-skills/index.ts +3 -0
  266. package/src/be/steering.ts +27 -4
  267. package/src/be/swarm-config-guard.ts +54 -1
  268. package/src/be/task-citations.ts +8 -5
  269. package/src/be/task-ui-spec.ts +158 -0
  270. package/src/commands/controller.ts +3 -0
  271. package/src/commands/credential-outcome-report.ts +13 -3
  272. package/src/commands/onboard/agent-fs-version.ts +1 -1
  273. package/src/commands/rate-limit-outcome.ts +6 -0
  274. package/src/commands/runner.ts +95 -55
  275. package/src/e2b/env.ts +2 -0
  276. package/src/extensions/catalog.generated.json +17 -0
  277. package/src/extensions/contract-types.generated.ts +1 -1
  278. package/src/github/app.ts +10 -1
  279. package/src/github/handlers.ts +6 -3
  280. package/src/github/reactions.ts +12 -14
  281. package/src/heartbeat/heartbeat.ts +14 -4
  282. package/src/http/agents.ts +19 -10
  283. package/src/http/all-routes.ts +2 -0
  284. package/src/http/api-keys.ts +258 -30
  285. package/src/http/approval-requests.ts +24 -4
  286. package/src/http/apps.ts +69 -5
  287. package/src/http/checklist.ts +176 -0
  288. package/src/http/db-query-bounded.ts +256 -11
  289. package/src/http/db-query-shared.ts +9 -0
  290. package/src/http/favorites.ts +14 -2
  291. package/src/http/fs.ts +346 -1
  292. package/src/http/index.ts +29 -1
  293. package/src/http/kv.ts +13 -0
  294. package/src/http/mcp-oauth.ts +1 -1
  295. package/src/http/mcp-servers.ts +15 -2
  296. package/src/http/onboarding.ts +2 -9
  297. package/src/http/poll.ts +45 -0
  298. package/src/http/script-connections.ts +1 -0
  299. package/src/http/session-data.ts +74 -23
  300. package/src/http/sessions.ts +23 -2
  301. package/src/http/slack-events.ts +101 -0
  302. package/src/http/status.ts +25 -7
  303. package/src/http/task-requester.ts +46 -0
  304. package/src/http/tasks.ts +169 -42
  305. package/src/http/users.ts +14 -0
  306. package/src/http/webhooks.ts +15 -0
  307. package/src/integrations/cards/index.ts +151 -0
  308. package/src/integrations/chat-sdk/outbound.ts +39 -13
  309. package/src/integrations/chat-sdk/relay.ts +87 -0
  310. package/src/integrations/chat-sdk/runtime.ts +7 -1
  311. package/src/integrations/chat-sdk/status.ts +17 -0
  312. package/src/integrations/chat-sdk/telegram-api.ts +6 -1
  313. package/src/jira/outbound.ts +5 -3
  314. package/src/kv-reserved-namespaces.ts +17 -2
  315. package/src/linear/outbound.ts +5 -1
  316. package/src/oauth/presets.ts +29 -2
  317. package/src/prompts/base-prompt.ts +25 -4
  318. package/src/prompts/session-templates.ts +102 -8
  319. package/src/providers/acp-targets.ts +1 -1
  320. package/src/providers/amp-adapter.ts +1 -1
  321. package/src/providers/claude-adapter.ts +27 -4
  322. package/src/providers/claude-flag-settings.ts +39 -1
  323. package/src/providers/claude-managed-adapter.ts +5 -1
  324. package/src/providers/codex-adapter.ts +86 -4
  325. package/src/providers/codex-app-server.ts +11 -16
  326. package/src/providers/codex-oauth/auth-json.ts +1 -0
  327. package/src/providers/opencode-adapter.ts +7 -19
  328. package/src/providers/pi-mono-adapter.ts +35 -2
  329. package/src/providers/pricing-sources.md +32 -0
  330. package/src/providers/runtime-dependencies.ts +158 -0
  331. package/src/providers/types.ts +11 -0
  332. package/src/rbac/legacy-policy.ts +2 -0
  333. package/src/rbac/permissions.ts +10 -1
  334. package/src/runtime-providers/docker.ts +65 -1
  335. package/src/scheduler/deferred-task-waits.ts +18 -5
  336. package/src/scripts-runtime/credential-broker/default-bindings.ts +19 -11
  337. package/src/scripts-runtime/credential-broker/index.ts +1 -1
  338. package/src/scripts-runtime/egress-secrets.ts +2 -2
  339. package/src/scripts-runtime/swarm-sdk.ts +3 -2
  340. package/src/scripts-runtime/types/stdlib.d.ts +11 -4
  341. package/src/scripts-runtime/types/swarm-extension.d.ts +9 -9
  342. package/src/scripts-runtime/types/swarm-sdk.d.ts +11 -4
  343. package/src/server.ts +4 -4
  344. package/src/slack/actions.ts +56 -0
  345. package/src/slack/app.ts +107 -59
  346. package/src/slack/assistant.ts +33 -7
  347. package/src/slack/handlers.ts +6 -4
  348. package/src/slack/http-receiver.ts +284 -0
  349. package/src/slack/inbound-dispatch.ts +43 -7
  350. package/src/slack/inbound-files.ts +35 -14
  351. package/src/slack/message-text.ts +47 -4
  352. package/src/slack/render-v2.ts +109 -24
  353. package/src/slack/responses.ts +3 -2
  354. package/src/slack/socket-ack.ts +17 -10
  355. package/src/slack/steering.ts +5 -0
  356. package/src/slack/thread-buffer-store.ts +58 -0
  357. package/src/slack/thread-buffer.ts +341 -57
  358. package/src/slack/work-objects.ts +4 -1
  359. package/src/tasks/context-key.ts +24 -0
  360. package/src/tasks/errors.ts +5 -0
  361. package/src/tasks/sibling-awareness.ts +13 -1
  362. package/src/tests/acp-adapter.test.ts +4 -6
  363. package/src/tests/agent-fs-live-url.test.ts +15 -0
  364. package/src/tests/agent-fs-provision-seeder.test.ts +140 -0
  365. package/src/tests/agent-fs-user-keys.test.ts +483 -0
  366. package/src/tests/agentfs-proxy.test.ts +8 -8
  367. package/src/tests/api-key-tracking.test.ts +0 -72
  368. package/src/tests/api-keys-status-model-limits.test.ts +93 -1
  369. package/src/tests/api-keys-validation.test.ts +42 -0
  370. package/src/tests/approval-card-resolution.test.ts +402 -0
  371. package/src/tests/approval-requests-notifications.test.ts +12 -2
  372. package/src/tests/approval-respond-auth.test.ts +28 -0
  373. package/src/tests/apps-action-parent-task.test.ts +140 -0
  374. package/src/tests/apps-catalog-additions.test.ts +315 -0
  375. package/src/tests/apps-catalog-files.test.ts +114 -0
  376. package/src/tests/apps-catalog-hitl.test.ts +117 -0
  377. package/src/tests/apps-catalog-inputs.test.ts +86 -0
  378. package/src/tests/apps-catalog-page-frame.test.ts +49 -0
  379. package/src/tests/apps-catalog-table.test.ts +47 -0
  380. package/src/tests/apps-chart-shell.test.ts +1 -1
  381. package/src/tests/apps-element-assembly.test.ts +52 -3
  382. package/src/tests/apps-session-thread.test.ts +261 -0
  383. package/src/tests/asset-key-invariants.test.ts +14 -0
  384. package/src/tests/base-prompt.test.ts +213 -23
  385. package/src/tests/boot-scrub-sweep.test.ts +172 -0
  386. package/src/tests/caller-session-group.test.ts +199 -0
  387. package/src/tests/cards.test.ts +169 -0
  388. package/src/tests/chat-sdk-relay.test.ts +149 -1
  389. package/src/tests/chat-sdk-status-route.test.ts +16 -3
  390. package/src/tests/chat-sdk-telegram-token.test.ts +76 -0
  391. package/src/tests/chat-sdk-tools.test.ts +147 -0
  392. package/src/tests/checklist-nudge.test.ts +208 -0
  393. package/src/tests/checklist.test.ts +686 -0
  394. package/src/tests/claude-adapter-binary.test.ts +67 -6
  395. package/src/tests/claude-flag-settings.test.ts +29 -0
  396. package/src/tests/claude-sdk-lifecycle.test.ts +5 -0
  397. package/src/tests/codex-adapter.test.ts +340 -2
  398. package/src/tests/codex-app-server.test.ts +32 -0
  399. package/src/tests/codex-oauth.test.ts +3 -1
  400. package/src/tests/codex-rate-limits.test.ts +384 -0
  401. package/src/tests/comb-config-guard.test.ts +21 -0
  402. package/src/tests/comb-default.test.ts +59 -97
  403. package/src/tests/comb-links.test.ts +86 -16
  404. package/src/tests/comb-status.test.ts +24 -27
  405. package/src/tests/create-page-tool.test.ts +101 -1
  406. package/src/tests/create-schedule-key.test.ts +105 -0
  407. package/src/tests/credential-broker.test.ts +2 -2
  408. package/src/tests/credential-outcome-report.test.ts +20 -0
  409. package/src/tests/db-query.test.ts +87 -1
  410. package/src/tests/db-task-read-contract.test.ts +4 -0
  411. package/src/tests/db-task-write-contract.test.ts +6 -1
  412. package/src/tests/deferred-task-wake.test.ts +63 -1
  413. package/src/tests/docker-isolation-config-guard.test.ts +29 -0
  414. package/src/tests/docs-index-footprint.test.js +11 -3
  415. package/src/tests/e2e-visuals-comment.test.ts +82 -0
  416. package/src/tests/e2e-visuals-verify-pr.test.ts +138 -0
  417. package/src/tests/entrypoint-github-enterprise.test.ts +158 -0
  418. package/src/tests/extensions-assets.test.ts +7 -3
  419. package/src/tests/extensions-catalog.test.ts +1 -0
  420. package/src/tests/extensions-example-sql-admin-only.test.ts +201 -0
  421. package/src/tests/extensions-pre-task.test.ts +3 -3
  422. package/src/tests/extensions-steering.test.ts +14 -2
  423. package/src/tests/favorites-agent-fs-path.test.ts +124 -0
  424. package/src/tests/fetch-resolved-env.test.ts +68 -0
  425. package/src/tests/fixtures/import-package.ts +32 -0
  426. package/src/tests/fixtures/runner-missing-dependency.ts +129 -0
  427. package/src/tests/fixtures/ui-spec-slack/deploys.json +121 -0
  428. package/src/tests/fixtures/ui-spec-slack/incident.json +183 -0
  429. package/src/tests/fixtures/ui-spec-slack/three-charts-stale.json +196 -0
  430. package/src/tests/fixtures/ui-spec-slack/video-rejected-by-slack.json +183 -0
  431. package/src/tests/fixtures/ui-spec-slack/video.json +446 -0
  432. package/src/tests/fs-routes.test.ts +505 -2
  433. package/src/tests/github-ghes-mock.test.ts +196 -0
  434. package/src/tests/github-host.test.ts +285 -0
  435. package/src/tests/gitleaks-download-retry.test.ts +85 -0
  436. package/src/tests/heartbeat-supersede-resume.test.ts +73 -0
  437. package/src/tests/heartbeat.test.ts +56 -0
  438. package/src/tests/human-thread-routing.test.ts +187 -0
  439. package/src/tests/import-config.test.ts +209 -0
  440. package/src/tests/import.test.ts +464 -0
  441. package/src/tests/invites-http.test.ts +144 -1
  442. package/src/tests/jira-outbound-sync.test.ts +33 -1
  443. package/src/tests/key-window-usage.test.ts +831 -0
  444. package/src/tests/kv-http.test.ts +11 -0
  445. package/src/tests/linear-outbound-sync.test.ts +30 -1
  446. package/src/tests/literal-matcher.test.ts +58 -0
  447. package/src/tests/mcp-oauth-manual-client.test.ts +1 -1
  448. package/src/tests/oauth-presets.test.ts +12 -0
  449. package/src/tests/pi-mono-adapter.test.ts +79 -0
  450. package/src/tests/pool-affinity.test.ts +50 -0
  451. package/src/tests/preload-env.test.ts +2 -0
  452. package/src/tests/preload.ts +3 -1
  453. package/src/tests/prompt-template-session.test.ts +53 -5
  454. package/src/tests/provider-quota-persistence.test.ts +362 -0
  455. package/src/tests/provider-registration.test.ts +2 -55
  456. package/src/tests/provider-runtime-dependencies.test.ts +212 -0
  457. package/src/tests/rate-limit-event.test.ts +22 -0
  458. package/src/tests/rbac-admission.test.ts +19 -0
  459. package/src/tests/rbac-charact-misc-tools.test.ts +31 -0
  460. package/src/tests/rbac-engine.test.ts +2 -0
  461. package/src/tests/rbac-roles.test.ts +2 -0
  462. package/src/tests/reasoning-events.test.ts +164 -0
  463. package/src/tests/routing-affinity-inventory.test.ts +22 -0
  464. package/src/tests/runner-missing-dependency.test.ts +61 -0
  465. package/src/tests/runtime-pool-reachability.test.ts +135 -1
  466. package/src/tests/runtime-pool-routing.test.ts +52 -0
  467. package/src/tests/runtime-providers-docker.test.ts +91 -0
  468. package/src/tests/runtime-stale-threshold.test.ts +40 -0
  469. package/src/tests/savings-fleet-slices.test.ts +122 -0
  470. package/src/tests/savings-read.test.ts +41 -0
  471. package/src/tests/savings-scripts.test.ts +9 -3
  472. package/src/tests/script-connections.test.ts +7 -0
  473. package/src/tests/script-executor-conformance.test.ts +41 -4
  474. package/src/tests/secret-canary-sweep.test.ts +41 -5
  475. package/src/tests/secret-scrub-gate.test.ts +257 -0
  476. package/src/tests/seed-registry.test.ts +142 -9
  477. package/src/tests/seed-scripts.test.ts +23 -0
  478. package/src/tests/session-cost-attribution.test.ts +748 -0
  479. package/src/tests/session-costs.test.ts +14 -15
  480. package/src/tests/session-logs.test.ts +83 -0
  481. package/src/tests/session-source-keys.test.ts +42 -1
  482. package/src/tests/sessions-detail-batch.test.ts +7 -0
  483. package/src/tests/sessions-move.test.ts +70 -0
  484. package/src/tests/sessions-tree.test.ts +98 -0
  485. package/src/tests/sessions.test.ts +69 -0
  486. package/src/tests/slack-config.test.ts +4 -18
  487. package/src/tests/slack-http-receiver.test.ts +472 -0
  488. package/src/tests/slack-inbound-logging.test.ts +64 -0
  489. package/src/tests/slack-leave-thread.test.ts +1 -1
  490. package/src/tests/slack-message-text.test.ts +104 -0
  491. package/src/tests/slack-mode-lifecycle.test.ts +6 -4
  492. package/src/tests/slack-render-v2.test.ts +405 -0
  493. package/src/tests/slack-skip-reaction.test.ts +2 -2
  494. package/src/tests/slack-start-reload-race.test.ts +67 -0
  495. package/src/tests/slack-steering.test.ts +22 -10
  496. package/src/tests/slack-thread-buffer-context.test.ts +1 -1
  497. package/src/tests/slack-thread-buffer-fold.test.ts +417 -0
  498. package/src/tests/slack-thread-buffer-restore.test.ts +198 -0
  499. package/src/tests/slack-thread-buffer-startup-restore.test.ts +86 -0
  500. package/src/tests/slack-thread-buffer.test.ts +34 -34
  501. package/src/tests/slack-thread-participants.test.ts +23 -5
  502. package/src/tests/slack-tool-blocks.test.ts +167 -0
  503. package/src/tests/status.test.ts +32 -6
  504. package/src/tests/steering-core.test.ts +13 -0
  505. package/src/tests/steering-enabled.test.ts +7 -1
  506. package/src/tests/steering-promotion.test.ts +24 -0
  507. package/src/tests/subscription-plans.test.ts +20 -1
  508. package/src/tests/swarm-config-reserved-keys.test.ts +17 -0
  509. package/src/tests/system-one-hosts-ui-mirror.test.ts +67 -0
  510. package/src/tests/task-artifacts.test.ts +50 -0
  511. package/src/tests/task-session-prompts.test.ts +95 -1
  512. package/src/tests/task-ui-action-route.test.ts +191 -0
  513. package/src/tests/task-ui-actions.test.ts +195 -0
  514. package/src/tests/task-ui-spec-fallback.test.ts +65 -0
  515. package/src/tests/task-ui-spec.test.ts +368 -0
  516. package/src/tests/workflow-agent-task-retry.test.ts +34 -1
  517. package/src/tests/workflow-system-one-extraction.test.ts +149 -1
  518. package/src/tools/chat-post.ts +19 -4
  519. package/src/tools/chat-reply.ts +20 -4
  520. package/src/tools/create-page.ts +21 -4
  521. package/src/tools/defer-task.ts +1 -1
  522. package/src/tools/get-swarm.ts +18 -2
  523. package/src/tools/join-swarm.ts +2 -1
  524. package/src/tools/kv/kv-write-auth.ts +17 -1
  525. package/src/tools/schedules/create-schedule.ts +22 -4
  526. package/src/tools/slack-post.ts +40 -7
  527. package/src/tools/slack-reply.ts +50 -14
  528. package/src/tools/store-progress.ts +69 -3
  529. package/src/types.ts +50 -4
  530. package/src/ui-spec/actions.ts +86 -0
  531. package/src/ui-spec/fallback.ts +19 -0
  532. package/src/ui-spec/slack.ts +17 -0
  533. package/src/ui-spec/validate.ts +169 -0
  534. package/src/utils/codex-rate-limits.ts +159 -0
  535. package/src/utils/constants.ts +60 -138
  536. package/src/utils/credentials.ts +2 -0
  537. package/src/utils/error-tracker.ts +19 -0
  538. package/src/utils/github-host.ts +217 -0
  539. package/src/utils/github-pull-request.ts +8 -5
  540. package/src/utils/literal-matcher.ts +118 -0
  541. package/src/utils/provider-account-telemetry.ts +331 -0
  542. package/src/utils/reasoning-events.ts +107 -0
  543. package/src/utils/secret-scrubber.ts +331 -25
  544. package/src/utils/subscription-plans.ts +11 -59
  545. package/src/utils/task-attachment-links.ts +9 -12
  546. package/src/utils/task-ui-spec.ts +67 -0
  547. package/src/vcs/index.ts +3 -0
  548. package/src/workflows/approval-notifications.ts +188 -12
  549. package/src/workflows/executors/system-one-extraction.ts +14 -7
  550. package/src/workflows/executors/system-one-providers.ts +22 -1
  551. package/src/workflows/task-step-routing.ts +8 -3
  552. package/templates/community/open-prompt-showreel/PLAYBOOK.md +1 -1
  553. package/templates/community/open-prompt-showreel/skills/open-prompt-showreel/SKILL.md +1 -1
  554. package/templates/extensions/README.md +1 -0
  555. package/templates/extensions/sql-admin-only/README.md +20 -0
  556. package/templates/extensions/sql-admin-only/hooks.ts +100 -0
  557. package/templates/extensions/sql-admin-only/manifest.json +8 -0
  558. package/templates/import/manifest.schema.json +136 -0
  559. package/templates/import/sources.schema.json +44 -0
  560. package/templates/skills/agent-browser/SKILL.md +1 -1
  561. package/templates/skills/agent-browser/content.md +1 -1
  562. package/templates/skills/apps/SKILL.md +151 -14
  563. package/templates/skills/apps/content.md +151 -14
  564. package/templates/skills/asset-namespaces/content.md +2 -1
  565. package/templates/skills/chat-sdk/content.md +17 -0
  566. package/templates/skills/db-query-guidance/content.md +2 -1
  567. package/templates/skills/scheduling/content.md +27 -0
  568. package/templates/skills/slack-interaction/content.md +12 -2
  569. package/templates/skills/swarm-docs/content.md +1 -0
  570. package/templates/skills/swarm-extensions/config.json +1 -1
  571. package/templates/skills/swarm-extensions/content.md +33 -23
  572. package/templates/skills/swarm-scripts/SKILL.md +13 -0
  573. package/templates/skills/swarm-scripts/content.md +13 -0
  574. package/templates/skills/ui-spec/config.json +14 -0
  575. package/templates/skills/ui-spec/content.md +127 -0
  576. package/templates/skills/work-on-task/SKILL.md +1 -1
  577. package/templates/skills/work-on-task/content.md +1 -1
  578. package/templates/skills/workflow-iterate/content.md +4 -7
  579. package/templates/workflows/dreaming/content.md +2 -2
  580. package/dist/acp-adapter-xq6s2z6t.js +0 -14
  581. package/dist/claude-adapter-r33pqnzx.js +0 -24
  582. package/dist/cli-dns0y538.js +0 -194
  583. package/dist/cli-m2z8jagn.js +0 -12078
  584. package/dist/fx-adapter-1rnxnf56.js +0 -17
  585. package/dist/grok-adapter-efhmf1r8.js +0 -17
  586. package/dist/handlers-anrr3py9.js +0 -32
  587. package/dist/index-2skqtd76.js +0 -12795
  588. package/dist/index-8w2aznds.js +0 -33
  589. package/dist/index-qnjvr362.js +0 -37
  590. package/dist/index-yzxd3sn9.js +0 -32
  591. package/dist/lead-zhxqbfdv.js +0 -69
  592. package/dist/worker-7j2907g6.js +0 -69
  593. package/src/tests/entrypoint-acp-target-binary.test.ts +0 -439
  594. package/dist/{cli-4caa1x7d.js → cli-tsa40663.js} +4 -4
  595. package/dist/{mistral-conversations-a45tx39a.js → mistral-conversations-0c30em7t.js} +4 -4
  596. package/dist/{openai-completions-xd579js7.js → openai-completions-f3n69rep.js} +18 -18
  597. package/dist/{pi-messages-hjbv8v10.js → pi-messages-zebyt7gb.js} +5 -5
@@ -1,19 +1,25 @@
1
1
  import {
2
- slackContextKey,
3
- init_context_key,
4
2
  encryptSecret,
5
3
  decryptSecret,
6
4
  getEncryptionKey,
7
5
  init_crypto,
8
6
  bindLoopPath,
9
7
  init_event_loop_lag,
8
+ scrubJsonValue,
9
+ init_scrub_json,
10
10
  getDbClient2,
11
+ slackContextKey,
12
+ init_context_key,
11
13
  SLACK_REACTION_DEFAULTS,
12
14
  SLACK_REACTION_CONFIG_KEYS,
13
15
  reactionName,
14
16
  completedStatusIcon,
15
17
  init_reaction_shortcode,
16
18
  getAgentById2,
19
+ closeSlackTreeIfSettled,
20
+ getSlackThreadsOfTasks,
21
+ slackThreadHasOutcomeWork,
22
+ init_slack_trees,
17
23
  getTaskById2,
18
24
  getChildTasks2,
19
25
  getPendingSlackRelayTasks2,
@@ -22,10 +28,6 @@ import {
22
28
  markFinalizedSlackRelaysDelivered2,
23
29
  getInProgressSlackTasks2,
24
30
  getSlackTasksMissingTree2,
25
- closeSlackTreeIfSettled,
26
- getSlackThreadsOfTasks,
27
- slackThreadHasOutcomeWork,
28
- init_slack_trees,
29
31
  ensureSlackRenderV2Activation2,
30
32
  ensureSlackDelegationActivation2,
31
33
  isPendingSlackMessage2,
@@ -56,45 +58,52 @@ import {
56
58
  checkDependencies2,
57
59
  emitBuiltInIntegrationConnectedOnce2,
58
60
  init_db4
59
- } from "./cli-h9yy18gy.js";
61
+ } from "./cli-ctx0b85j.js";
60
62
  import {
61
63
  getChannelBlockReason2,
62
64
  init_external_channel
63
- } from "./cli-zeaehgyd.js";
65
+ } from "./cli-xag7btpe.js";
66
+ import {
67
+ require_dist6,
68
+ require_is_electron,
69
+ require_is_stream,
70
+ require_dist7,
71
+ require_eventemitter3,
72
+ require_dist8,
73
+ require_src2,
74
+ cardToBlockKit2,
75
+ cardToFallbackText2,
76
+ init_dist6
77
+ } from "./cli-47hz21se.js";
64
78
  import {
65
79
  workflowEventBus2,
66
80
  init_event_bus
67
- } from "./cli-emekyyhr.js";
81
+ } from "./cli-q2d3e1k1.js";
68
82
  import {
69
83
  require_jsonwebtoken,
70
- require_dist6,
84
+ require_dist9,
71
85
  require_raw_body,
72
86
  require_express
73
- } from "./cli-yjdgea32.js";
74
- import {
75
- require_dist7,
76
- require_is_electron,
77
- require_is_stream,
78
- require_dist8,
79
- require_eventemitter3,
80
- require_dist9,
81
- require_src
82
- } from "./cli-m2z8jagn.js";
87
+ } from "./cli-1jx0srjt.js";
83
88
  import {
84
89
  require_form_data,
85
90
  require_follow_redirects
86
- } from "./cli-504akrp9.js";
91
+ } from "./cli-meydjstb.js";
87
92
  import {
88
93
  require_p_retry
89
94
  } from "./cli-952zgdwp.js";
90
95
  import {
91
96
  isTerminalTaskStatus,
92
- init_types4
93
- } from "./cli-qps8je6j.js";
97
+ init_types5
98
+ } from "./cli-bkjdknnp.js";
99
+ import {
100
+ getGitHubLinkConfig,
101
+ init_github_host
102
+ } from "./cli-9ttx00s3.js";
94
103
  import {
95
104
  taskAttachmentDisplayUrl,
96
105
  init_task_attachment_links
97
- } from "./cli-am1ptset.js";
106
+ } from "./cli-m7c2380k.js";
98
107
  import {
99
108
  getSlackConfiguration,
100
109
  init_config4
@@ -106,13 +115,22 @@ import {
106
115
  string2,
107
116
  number2,
108
117
  boolean,
118
+ _null,
119
+ any,
120
+ unknown,
121
+ array2,
109
122
  object2,
110
- _enum2
123
+ strictObject2,
124
+ union3,
125
+ record2,
126
+ _enum2,
127
+ literal2,
128
+ lazy
111
129
  } from "./cli-hg42n3hx.js";
112
130
  import {
113
131
  getAppUrl,
114
132
  init_constants3
115
- } from "./cli-dns0y538.js";
133
+ } from "./cli-dqgnbnxs.js";
116
134
  import {
117
135
  isEnvFlagEnabled,
118
136
  init_env_flag
@@ -125,7 +143,7 @@ import {
125
143
  scrubSecrets,
126
144
  scrubObject,
127
145
  init_secret_scrubber
128
- } from "./cli-f1kwb5fc.js";
146
+ } from "./cli-5a6pqy45.js";
129
147
  import {
130
148
  __toESM,
131
149
  __commonJS,
@@ -354,8 +372,8 @@ var require_logger = __commonJS(function(exports) {
354
372
  Object.defineProperty(exports, "__esModule", { value: true });
355
373
  exports.LogLevel = undefined;
356
374
  exports.getLogger = getLogger;
357
- var logger_1 = require_dist7();
358
- var logger_2 = require_dist7();
375
+ var logger_1 = require_dist6();
376
+ var logger_2 = require_dist6();
359
377
  Object.defineProperty(exports, "LogLevel", { enumerable: true, get: function() {
360
378
  return logger_2.LogLevel;
361
379
  } });
@@ -1164,7 +1182,7 @@ var require_axios = __commonJS(function(exports, module) {
1164
1182
  forcedJSONParsing: true,
1165
1183
  clarifyTimeoutError: false
1166
1184
  };
1167
- var URLSearchParams = url__default["default"].URLSearchParams;
1185
+ var URLSearchParams2 = url__default["default"].URLSearchParams;
1168
1186
  var ALPHA = "abcdefghijklmnopqrstuvwxyz";
1169
1187
  var DIGIT = "0123456789";
1170
1188
  var ALPHABET = {
@@ -1185,7 +1203,7 @@ var require_axios = __commonJS(function(exports, module) {
1185
1203
  var platform$1 = {
1186
1204
  isNode: true,
1187
1205
  classes: {
1188
- URLSearchParams,
1206
+ URLSearchParams: URLSearchParams2,
1189
1207
  FormData: FormData__default["default"],
1190
1208
  Blob: typeof Blob !== "undefined" && Blob || null
1191
1209
  },
@@ -4537,7 +4555,7 @@ var require_methods = __commonJS(function(exports) {
4537
4555
  }
4538
4556
  }
4539
4557
  exports.Methods = Methods;
4540
- __exportStar(require_dist9(), exports);
4558
+ __exportStar(require_dist8(), exports);
4541
4559
  });
4542
4560
 
4543
4561
  // node_modules/@slack/web-api/dist/WebClient.js
@@ -4706,7 +4724,7 @@ var require_WebClient = __commonJS(function(exports) {
4706
4724
  var form_data_1 = __importDefault(require_form_data());
4707
4725
  var is_electron_1 = __importDefault(require_is_electron());
4708
4726
  var is_stream_1 = __importDefault(require_is_stream());
4709
- var p_queue_1 = __importDefault(require_dist8());
4727
+ var p_queue_1 = __importDefault(require_dist7());
4710
4728
  var p_retry_1 = __importStar(require_p_retry());
4711
4729
  var chat_stream_1 = require_chat_stream();
4712
4730
  var errors_1 = require_errors();
@@ -6644,8 +6662,8 @@ var require_logger2 = __commonJS(function(exports) {
6644
6662
  Object.defineProperty(exports, "__esModule", { value: true });
6645
6663
  exports.LogLevel = undefined;
6646
6664
  exports.getLogger = getLogger;
6647
- var logger_1 = require_dist7();
6648
- var logger_2 = require_dist7();
6665
+ var logger_1 = require_dist6();
6666
+ var logger_2 = require_dist6();
6649
6667
  Object.defineProperty(exports, "LogLevel", { enumerable: true, get: function() {
6650
6668
  return logger_2.LogLevel;
6651
6669
  } });
@@ -6933,7 +6951,7 @@ var require_file_state_store = __commonJS(function(exports) {
6933
6951
  var node_fs_1 = __importDefault(__require("node:fs"));
6934
6952
  var node_os_1 = __require("node:os");
6935
6953
  var node_path_1 = __importDefault(__require("node:path"));
6936
- var logger_1 = require_dist7();
6954
+ var logger_1 = require_dist6();
6937
6955
  var errors_1 = require_errors3();
6938
6956
  var FileStateStore = function() {
6939
6957
  function FileStateStore(args) {
@@ -8333,9 +8351,9 @@ var require_HTTPReceiver = __commonJS(function(exports) {
8333
8351
  var node_http_1 = __require("node:http");
8334
8352
  var node_https_1 = __require("node:https");
8335
8353
  var node_url_1 = __require("node:url");
8336
- var logger_1 = require_dist7();
8354
+ var logger_1 = require_dist6();
8337
8355
  var oauth_1 = require_dist();
8338
- var path_to_regexp_1 = require_dist6();
8356
+ var path_to_regexp_1 = require_dist9();
8339
8357
  var errors_1 = require_errors2();
8340
8358
  var httpFunc = __importStar(require_HTTPModuleFunctions());
8341
8359
  var HTTPResponseAck_1 = require_HTTPResponseAck();
@@ -8700,10 +8718,10 @@ var require_SocketModeReceiver = __commonJS(function(exports) {
8700
8718
  Object.defineProperty(exports, "__esModule", { value: true });
8701
8719
  var node_http_1 = __require("node:http");
8702
8720
  var node_url_1 = __require("node:url");
8703
- var logger_1 = require_dist7();
8721
+ var logger_1 = require_dist6();
8704
8722
  var oauth_1 = require_dist();
8705
- var socket_mode_1 = require_src();
8706
- var path_to_regexp_1 = require_dist6();
8723
+ var socket_mode_1 = require_src2();
8724
+ var path_to_regexp_1 = require_dist9();
8707
8725
  var SocketModeFunctions_1 = require_SocketModeFunctions();
8708
8726
  var SocketModeResponseAck_1 = require_SocketModeResponseAck();
8709
8727
  var custom_routes_1 = require_custom_routes();
@@ -9123,7 +9141,7 @@ var require_App = __commonJS(function(exports) {
9123
9141
  Object.defineProperty(exports, "__esModule", { value: true });
9124
9142
  exports.LogLevel = undefined;
9125
9143
  var node_util_1 = __importDefault(__require("node:util"));
9126
- var logger_1 = require_dist7();
9144
+ var logger_1 = require_dist6();
9127
9145
  var web_api_1 = require_dist4();
9128
9146
  var axios_1 = __importDefault(require_axios());
9129
9147
  var CustomFunction_1 = require_CustomFunction();
@@ -9139,7 +9157,7 @@ var require_App = __commonJS(function(exports) {
9139
9157
  var packageJson = require_package2();
9140
9158
  var validViewTypes = ["view_closed", "view_submission"];
9141
9159
  var tokenUsage = "Apps used in a single workspace can be initialized with a token. Apps used in many workspaces " + "should be initialized with oauth installer options or authorize.";
9142
- var logger_2 = require_dist7();
9160
+ var logger_2 = require_dist6();
9143
9161
  Object.defineProperty(exports, "LogLevel", { enumerable: true, get: function() {
9144
9162
  return logger_2.LogLevel;
9145
9163
  } });
@@ -9933,7 +9951,7 @@ var require_ExpressReceiver = __commonJS(function(exports) {
9933
9951
  var node_http_1 = __require("node:http");
9934
9952
  var node_https_1 = __require("node:https");
9935
9953
  var node_querystring_1 = __importDefault(__require("node:querystring"));
9936
- var logger_1 = require_dist7();
9954
+ var logger_1 = require_dist6();
9937
9955
  var oauth_1 = require_dist();
9938
9956
  var express_1 = __importStar(require_express());
9939
9957
  var raw_body_1 = __importDefault(require_raw_body());
@@ -10284,7 +10302,7 @@ var require_AwsLambdaReceiver = __commonJS(function(exports) {
10284
10302
  Object.defineProperty(exports, "__esModule", { value: true });
10285
10303
  var node_crypto_1 = __importDefault(__require("node:crypto"));
10286
10304
  var node_querystring_1 = __importDefault(__require("node:querystring"));
10287
- var logger_1 = require_dist7();
10305
+ var logger_1 = require_dist6();
10288
10306
  var tsscmp_1 = __importDefault(require_lib());
10289
10307
  var errors_1 = require_errors2();
10290
10308
 
@@ -11036,7 +11054,7 @@ var require_dist5 = __commonJS(function(exports) {
11036
11054
  Object.defineProperty(exports, "FileInstallationStore", { enumerable: true, get: function() {
11037
11055
  return oauth_1.FileInstallationStore;
11038
11056
  } });
11039
- exports.types = __importStar(require_dist9());
11057
+ exports.types = __importStar(require_dist8());
11040
11058
  exports.webApi = __importStar(require_dist4());
11041
11059
  });
11042
11060
 
@@ -11657,10 +11675,13 @@ function recordOutcome(transport, outcome) {
11657
11675
  console.warn(`[Slack] inbound ${transport} delivery ${outcome.state}: ${outcome.code}`);
11658
11676
  }
11659
11677
  }
11678
+ function recordSlackInboundWithheld(transport, code) {
11679
+ recordOutcome(transport, { state: "ignored", code });
11680
+ }
11660
11681
  function recordSlackSocketAckNotReady() {
11661
11682
  counters.socket.ackNotReady += 1;
11662
11683
  }
11663
- function slackInboundOutcomeMiddleware() {
11684
+ function slackInboundOutcomeMiddleware(transport = "socket") {
11664
11685
  return async ({ next, body }) => {
11665
11686
  const identity = getCachedSlackWorkspaceIdentity();
11666
11687
  const ownership = checkInboundWorkspace(body, identity);
@@ -11682,21 +11703,21 @@ function slackInboundOutcomeMiddleware() {
11682
11703
  }
11683
11704
  return;
11684
11705
  }
11685
- const state = newDeliveryState("socket", false);
11706
+ const state = newDeliveryState(transport, false);
11686
11707
  state.dispatched = true;
11687
11708
  if (!ownership.own) {
11688
11709
  state.ignoredReasons.push(ownership.reason);
11689
- recordOutcome("socket", resolveSlackInboundOutcome(state));
11710
+ recordOutcome(transport, resolveSlackInboundOutcome(state));
11690
11711
  return;
11691
11712
  }
11692
11713
  await deliveryStorage.run(state, async () => {
11693
11714
  try {
11694
11715
  await next();
11695
11716
  } catch (error) {
11696
- recordOutcome("socket", resolveSlackInboundOutcome(state, error));
11717
+ recordOutcome(transport, resolveSlackInboundOutcome(state, error));
11697
11718
  throw error;
11698
11719
  }
11699
- recordOutcome("socket", resolveSlackInboundOutcome(state));
11720
+ recordOutcome(transport, resolveSlackInboundOutcome(state));
11700
11721
  });
11701
11722
  };
11702
11723
  }
@@ -11758,12 +11779,15 @@ async function isSlackSocketEventStored(body, now = new Date) {
11758
11779
  return key ? touchSlackInboundDuplicate(key.dedupKey, now) : false;
11759
11780
  }
11760
11781
  async function recordSlackSocketEventRanInline(body, retry = {}, now = new Date) {
11782
+ return recordSlackEventRanInline("socket", body, retry, now);
11783
+ }
11784
+ async function recordSlackEventRanInline(transport, body, retry = {}, now = new Date) {
11761
11785
  const key = socketEventKey(body);
11762
11786
  if (!key)
11763
11787
  return "invalid";
11764
11788
  return recordSlackInboundInline({
11765
11789
  dedupKey: key.dedupKey,
11766
- transport: "socket",
11790
+ transport,
11767
11791
  kind: "event",
11768
11792
  payloadType: key.payloadType,
11769
11793
  apiAppId: key.apiAppId,
@@ -11914,7 +11938,18 @@ async function getSlackInboundDiagnostics() {
11914
11938
  limits: SLACK_INBOUND_LIMITS
11915
11939
  };
11916
11940
  }
11917
- var deliveryStorage, counters, defaultTimer = (fn, delayMs) => {
11941
+ var import_bolt3, deliveryStorage, counters, ignoreSelfAsIgnored = async (args) => {
11942
+ let passed = false;
11943
+ await import_bolt3.ignoreSelf({
11944
+ ...args,
11945
+ next: async () => {
11946
+ passed = true;
11947
+ await args.next();
11948
+ }
11949
+ });
11950
+ if (!passed)
11951
+ ignoreSlackInbound("self_event");
11952
+ }, defaultTimer = (fn, delayMs) => {
11918
11953
  const handle = setTimeout(fn, delayMs);
11919
11954
  handle.unref?.();
11920
11955
  return () => clearTimeout(handle);
@@ -11925,6 +11960,7 @@ var init_inbound_dispatch = __esm(() => {
11925
11960
  init_secret_scrubber();
11926
11961
  init_config4();
11927
11962
  init_workspace_guard();
11963
+ import_bolt3 = __toESM(require_dist5(), 1);
11928
11964
  deliveryStorage = new AsyncLocalStorage;
11929
11965
  counters = {
11930
11966
  socket: emptyCounters(),
@@ -11932,30 +11968,6 @@ var init_inbound_dispatch = __esm(() => {
11932
11968
  };
11933
11969
  });
11934
11970
 
11935
- // src/slack/lifecycle-lock.ts
11936
- async function runSlackLifecycleExclusive(fn) {
11937
- holders += 1;
11938
- const previous = tail;
11939
- let release;
11940
- tail = new Promise((resolve) => {
11941
- release = resolve;
11942
- });
11943
- try {
11944
- await previous;
11945
- return await fn();
11946
- } finally {
11947
- holders -= 1;
11948
- release();
11949
- }
11950
- }
11951
- function isSlackLifecycleBusy() {
11952
- return holders > 0;
11953
- }
11954
- var tail, holders = 0;
11955
- var init_lifecycle_lock = __esm(() => {
11956
- tail = Promise.resolve();
11957
- });
11958
-
11959
11971
  // src/slack/socket-ack.ts
11960
11972
  function isSocketNotReadyError(error) {
11961
11973
  return error instanceof Error && error.message === NOT_READY_MESSAGE;
@@ -12052,8 +12064,8 @@ async function rememberInline(payload, envelope) {
12052
12064
  console.warn("[Slack] could not remember unacked inline event:", storeError);
12053
12065
  }
12054
12066
  }
12055
- function installSocketAckRecovery(client, app) {
12056
- const drain = createSlackInboundDrain(async ({ receipt, rawBody }) => {
12067
+ function createBoltInboundDrain(app) {
12068
+ return createSlackInboundDrain(async ({ receipt, rawBody }) => {
12057
12069
  await app.processEvent({
12058
12070
  body: JSON.parse(rawBody),
12059
12071
  ack: async () => {},
@@ -12061,6 +12073,9 @@ function installSocketAckRecovery(client, app) {
12061
12073
  retryReason: receipt.retryReason ?? undefined
12062
12074
  });
12063
12075
  }, { requireBoltDispatch: true });
12076
+ }
12077
+ function installSocketAckRecovery(client, app) {
12078
+ const drain = createBoltInboundDrain(app);
12064
12079
  tolerateSocketNotReadyAcks(client, { onAdmitted: () => void drain.wake() });
12065
12080
  return drain;
12066
12081
  }
@@ -12070,6 +12085,219 @@ var init_socket_ack = __esm(() => {
12070
12085
  ORDER_DEPENDENT_EVENTS = new Set(["assistant_thread_context_changed"]);
12071
12086
  });
12072
12087
 
12088
+ // src/slack/http-receiver.ts
12089
+ function jsonResult(status, body, headers) {
12090
+ return { status, body: JSON.stringify(body), contentType: "application/json", headers };
12091
+ }
12092
+ function refuse(status, error, headers) {
12093
+ return jsonResult(status, { error }, headers);
12094
+ }
12095
+ function parseSlackBody(text, contentType) {
12096
+ const type = (contentType ?? "").split(";")[0]?.trim().toLowerCase();
12097
+ try {
12098
+ if (type === "application/json") {
12099
+ const body = JSON.parse(text);
12100
+ return body && typeof body === "object" && !Array.isArray(body) ? { kind: "json", body } : null;
12101
+ }
12102
+ if (type === "application/x-www-form-urlencoded") {
12103
+ const form = new URLSearchParams(text);
12104
+ if (form.has("ssl_check"))
12105
+ return { kind: "ssl_check" };
12106
+ const payload = form.get("payload");
12107
+ if (payload !== null) {
12108
+ const body = JSON.parse(payload);
12109
+ return body && typeof body === "object" && !Array.isArray(body) ? { kind: "live", body } : null;
12110
+ }
12111
+ if (form.has("command"))
12112
+ return { kind: "live", body: Object.fromEntries(form) };
12113
+ }
12114
+ } catch {}
12115
+ return null;
12116
+ }
12117
+ function parseRetryNum(value) {
12118
+ if (!value || !/^\d{1,3}$/.test(value))
12119
+ return null;
12120
+ return Number(value);
12121
+ }
12122
+ function ackResult(response) {
12123
+ if (response === undefined || response === null || response === "")
12124
+ return EMPTY_OK;
12125
+ if (typeof response === "string") {
12126
+ return { status: 200, body: response, contentType: "text/plain; charset=utf-8" };
12127
+ }
12128
+ return jsonResult(200, response);
12129
+ }
12130
+
12131
+ class SwarmHttpReceiver {
12132
+ onAdmitted;
12133
+ app = null;
12134
+ ready = false;
12135
+ constructor(onAdmitted) {
12136
+ this.onAdmitted = onAdmitted;
12137
+ }
12138
+ init(app) {
12139
+ this.app = app;
12140
+ }
12141
+ markReady() {
12142
+ this.ready = true;
12143
+ }
12144
+ async start() {}
12145
+ async stop() {}
12146
+ async handle(input, now = Date.now()) {
12147
+ if (!input.signature || !input.timestamp || !/^\d{1,12}$/.test(input.timestamp)) {
12148
+ return refuse(401, "invalid_signature");
12149
+ }
12150
+ const timestampSec = Number(input.timestamp);
12151
+ if (Math.abs(now / 1000 - timestampSec) > MAX_TIMESTAMP_SKEW_SEC) {
12152
+ return refuse(401, "invalid_signature");
12153
+ }
12154
+ const text = input.rawBody.toString("utf8");
12155
+ try {
12156
+ import_bolt4.verifySlackRequest({
12157
+ signingSecret: input.signingSecret,
12158
+ body: text,
12159
+ headers: {
12160
+ "x-slack-signature": input.signature,
12161
+ "x-slack-request-timestamp": timestampSec
12162
+ },
12163
+ nowMilliseconds: now
12164
+ });
12165
+ } catch {
12166
+ return refuse(401, "invalid_signature");
12167
+ }
12168
+ const parsed = parseSlackBody(text, input.contentType);
12169
+ if (!parsed)
12170
+ return refuse(400, "malformed_body");
12171
+ if (parsed.kind === "ssl_check")
12172
+ return EMPTY_OK;
12173
+ const { body } = parsed;
12174
+ if (parsed.kind === "json" && body.type === "url_verification") {
12175
+ return typeof body.challenge === "string" ? jsonResult(200, { challenge: body.challenge }) : refuse(400, "malformed_body");
12176
+ }
12177
+ if (parsed.kind === "json" && body.type !== "event_callback")
12178
+ return EMPTY_OK;
12179
+ const identity = getCachedSlackWorkspaceIdentity();
12180
+ const app = this.app;
12181
+ if (!identity || !app || !this.ready) {
12182
+ return refuse(503, "workspace_unverified", { "Retry-After": RETRY_AFTER_SEC });
12183
+ }
12184
+ const ownership = checkInboundWorkspace(body, identity);
12185
+ if (!ownership.own) {
12186
+ recordSlackInboundWithheld("http", ownership.reason);
12187
+ return refuse(403, "foreign_workspace");
12188
+ }
12189
+ const retryNum = parseRetryNum(input.retryNum);
12190
+ const retryReason = input.retryReason?.slice(0, 128) || null;
12191
+ if (parsed.kind === "live")
12192
+ return this.runLive(app, body, retryNum, retryReason);
12193
+ return this.admitEvent(app, text, body, retryNum, retryReason);
12194
+ }
12195
+ async admitEvent(app, rawBody, body, retryNum, retryReason) {
12196
+ try {
12197
+ if (isOrderDependentEvent(body)) {
12198
+ const stored = await recordSlackEventRanInline("http", body, {
12199
+ retryNum,
12200
+ retryReason
12201
+ }).catch(() => "invalid");
12202
+ if (stored !== "duplicate") {
12203
+ app.processEvent({
12204
+ body,
12205
+ ack: async () => {},
12206
+ retryNum: retryNum ?? undefined,
12207
+ retryReason: retryReason ?? undefined
12208
+ }).catch((error) => logDispatchError(error));
12209
+ }
12210
+ return EMPTY_OK;
12211
+ }
12212
+ const result = await admitSlackInbound({
12213
+ transport: "http",
12214
+ kind: "event",
12215
+ rawBody,
12216
+ body,
12217
+ retryNum,
12218
+ retryReason
12219
+ });
12220
+ switch (result.status) {
12221
+ case "admitted":
12222
+ this.onAdmitted();
12223
+ return EMPTY_OK;
12224
+ case "duplicate":
12225
+ return EMPTY_OK;
12226
+ case "invalid":
12227
+ return refuse(400, result.reason);
12228
+ case "rejected":
12229
+ return result.reason === "payload_too_large" ? refuse(413, "payload_too_large") : refuse(503, "backlog_full", { "Retry-After": RETRY_AFTER_SEC });
12230
+ }
12231
+ } catch (error) {
12232
+ console.error(`[Slack] HTTP event could not be stored: ${scrubSecrets(String(error))}`);
12233
+ return refuse(503, "store_unavailable", { "Retry-After": RETRY_AFTER_SEC });
12234
+ }
12235
+ }
12236
+ runLive(app, body, retryNum, retryReason) {
12237
+ return new Promise((resolve) => {
12238
+ const timer = setTimeout(() => {
12239
+ console.warn("[Slack] HTTP handler did not ack in time; answered an empty 200");
12240
+ resolve(EMPTY_OK);
12241
+ }, SLACK_HTTP_ACK_TIMEOUT_MS);
12242
+ const ack = async (response) => {
12243
+ clearTimeout(timer);
12244
+ resolve(ackResult(response));
12245
+ };
12246
+ app.processEvent({
12247
+ body,
12248
+ ack,
12249
+ retryNum: retryNum ?? undefined,
12250
+ retryReason: retryReason ?? undefined
12251
+ }).then(() => {
12252
+ clearTimeout(timer);
12253
+ resolve(EMPTY_OK);
12254
+ }).catch((error) => {
12255
+ clearTimeout(timer);
12256
+ logDispatchError(error);
12257
+ resolve(refuse(500, "handler_failed"));
12258
+ });
12259
+ });
12260
+ }
12261
+ }
12262
+ function logDispatchError(error) {
12263
+ const message = error instanceof Error ? error.message : String(error);
12264
+ console.error(`[Slack] HTTP dispatch failed: ${scrubSecrets(message)}`);
12265
+ }
12266
+ var import_bolt4, MAX_TIMESTAMP_SKEW_SEC, SLACK_HTTP_ACK_TIMEOUT_MS = 2500, RETRY_AFTER_SEC = "5", EMPTY_OK;
12267
+ var init_http_receiver = __esm(() => {
12268
+ init_secret_scrubber();
12269
+ init_inbound_dispatch();
12270
+ init_socket_ack();
12271
+ init_workspace_guard();
12272
+ import_bolt4 = __toESM(require_dist5(), 1);
12273
+ MAX_TIMESTAMP_SKEW_SEC = 5 * 60;
12274
+ EMPTY_OK = { status: 200 };
12275
+ });
12276
+
12277
+ // src/slack/lifecycle-lock.ts
12278
+ async function runSlackLifecycleExclusive(fn) {
12279
+ holders += 1;
12280
+ const previous = tail;
12281
+ let release;
12282
+ tail = new Promise((resolve) => {
12283
+ release = resolve;
12284
+ });
12285
+ try {
12286
+ await previous;
12287
+ return await fn();
12288
+ } finally {
12289
+ holders -= 1;
12290
+ release();
12291
+ }
12292
+ }
12293
+ function isSlackLifecycleBusy() {
12294
+ return holders > 0;
12295
+ }
12296
+ var tail, holders = 0;
12297
+ var init_lifecycle_lock = __esm(() => {
12298
+ tail = Promise.resolve();
12299
+ });
12300
+
12073
12301
  // src/slack/socket-fence.ts
12074
12302
  function fenceSocketModeClient(client) {
12075
12303
  let retired = false;
@@ -12155,7 +12383,7 @@ async function initOtel(serviceRole = process.env.AGENT_ROLE || "api") {
12155
12383
  return;
12156
12384
  initialized = true;
12157
12385
  try {
12158
- const impl = await import("./otel-impl-8j1xhxqd.js");
12386
+ const impl = await import("./otel-impl-1skarpfq.js");
12159
12387
  await impl.boot(serviceRole, {
12160
12388
  exportConsoleLogs: serviceRole === "api" && isApiLogExportEnabled()
12161
12389
  });
@@ -12401,7 +12629,7 @@ var init_ack = __esm(() => {
12401
12629
  init_db4();
12402
12630
  init_reaction_events();
12403
12631
  init_otel();
12404
- init_types4();
12632
+ init_types5();
12405
12633
  init_secret_scrubber();
12406
12634
  init_app3();
12407
12635
  init_reaction_shortcode();
@@ -12868,15 +13096,17 @@ var init_task_citations = __esm(() => {
12868
13096
 
12869
13097
  // src/be/task-citations.ts
12870
13098
  function githubCitationUrl(ref) {
13099
+ const { host, webUrl } = getGitHubLinkConfig();
13100
+ const hostRe = host.replace(/[.]/g, "\\.");
12871
13101
  const repo = "([\\w.-]+)\\/([\\w.-]+)";
12872
13102
  const short = ref.trim().match(new RegExp(`^${repo}(?:#(\\d+)|@([0-9a-f]{7,40}))$`, "i"));
12873
13103
  if (short) {
12874
- return short[3] ? `https://github.com/${short[1]}/${short[2]}/issues/${short[3]}` : `https://github.com/${short[1]}/${short[2]}/commit/${short[4].toLowerCase()}`;
13104
+ return short[3] ? `${webUrl}/${short[1]}/${short[2]}/issues/${short[3]}` : `${webUrl}/${short[1]}/${short[2]}/commit/${short[4].toLowerCase()}`;
12875
13105
  }
12876
- const full = ref.trim().match(new RegExp(`^https?:\\/\\/(?:www\\.)?github\\.com\\/${repo}\\/(?:(pull|issues)\\/(\\d+)|commit\\/([0-9a-f]{7,40}))(?:[/?#].*)?$`, "i"));
13106
+ const full = ref.trim().match(new RegExp(`^https?:\\/\\/(?:www\\.)?${hostRe}\\/${repo}\\/(?:(pull|issues)\\/(\\d+)|commit\\/([0-9a-f]{7,40}))(?:[/?#].*)?$`, "i"));
12877
13107
  if (!full)
12878
13108
  return null;
12879
- return full[3] ? `https://github.com/${full[1]}/${full[2]}/${full[3].toLowerCase()}/${full[4]}` : `https://github.com/${full[1]}/${full[2]}/commit/${full[5].toLowerCase()}`;
13109
+ return full[3] ? `${webUrl}/${full[1]}/${full[2]}/${full[3].toLowerCase()}/${full[4]}` : `${webUrl}/${full[1]}/${full[2]}/commit/${full[5].toLowerCase()}`;
12880
13110
  }
12881
13111
  function buildCitationUrl(citation) {
12882
13112
  try {
@@ -12976,6 +13206,7 @@ var MAX_TASK_CITATIONS = 50, CitationInputSchema, TaskCitationSchema, TASK_ID_CH
12976
13206
  var init_task_citations2 = __esm(() => {
12977
13207
  init_zod();
12978
13208
  init_constants3();
13209
+ init_github_host();
12979
13210
  init_task_attachment_links();
12980
13211
  init_task_citations();
12981
13212
  init_db4();
@@ -12995,121 +13226,2229 @@ var init_task_citations2 = __esm(() => {
12995
13226
  });
12996
13227
  });
12997
13228
 
12998
- // node_modules/@desplega.ai/business-use/dist/index.js
12999
- function initialize(options) {
13000
- if (_state.initialized) {
13001
- log2.warn("SDK already initialized");
13002
- return;
13003
- }
13004
- try {
13005
- const finalApiKey = options?.apiKey ?? process.env.BUSINESS_USE_API_KEY;
13006
- if (!finalApiKey) {
13007
- log2.error("API key not provided. Set apiKey parameter or BUSINESS_USE_API_KEY environment variable");
13008
- return;
13009
- }
13010
- const finalUrl = options?.url ?? process.env.BUSINESS_USE_URL ?? "http://localhost:13370";
13011
- const baseUrl = finalUrl.replace(/\/$/, "");
13012
- const batchSize = options?.batchSize ?? 100;
13013
- const batchInterval = options?.batchInterval ?? 5000;
13014
- const maxQueueSize = options?.maxQueueSize ?? batchSize * 10;
13015
- if (!_checkConnection(finalApiKey, baseUrl)) {
13016
- log2.error("Connection check failed - SDK entering no-op mode");
13017
- return;
13018
- }
13019
- _state.batchProcessor = new BatchProcessor({
13020
- apiKey: finalApiKey,
13021
- baseUrl,
13022
- batchSize,
13023
- batchInterval,
13024
- maxQueueSize
13025
- });
13026
- _state.initialized = true;
13027
- log2.info("Business-Use SDK initialized successfully");
13028
- } catch (error) {
13029
- log2.error(`Failed to initialize SDK: ${error}`);
13030
- _state.initialized = false;
13229
+ // src/be/task-ui-spec.ts
13230
+ function rowToTaskUiSpec(row) {
13231
+ const value = { spec: JSON.parse(row.spec), fallbackText: row.fallbackText };
13232
+ if (row.actions !== null)
13233
+ value.actions = JSON.parse(row.actions);
13234
+ return value;
13235
+ }
13236
+ async function getTaskUiSpec(taskId) {
13237
+ const row = await getDbClient2().get(`SELECT task_id AS taskId, spec, actions, fallback_text AS fallbackText
13238
+ FROM task_ui_specs WHERE task_id = ?`, [taskId]);
13239
+ return row ? rowToTaskUiSpec(row) : null;
13240
+ }
13241
+ async function getTaskUiSpecsForTasks(taskIds) {
13242
+ const ids = [...new Set(taskIds)];
13243
+ const byTask = new Map(ids.map((id) => [id, null]));
13244
+ for (let i = 0;i < ids.length; i += TASK_ID_CHUNK2) {
13245
+ const chunk = ids.slice(i, i + TASK_ID_CHUNK2);
13246
+ const rows = await getDbClient2().query(`SELECT task_id AS taskId, spec, actions, fallback_text AS fallbackText
13247
+ FROM task_ui_specs WHERE task_id IN (${chunk.map(() => "?").join(",")})`, chunk);
13248
+ for (const row of rows)
13249
+ byTask.set(row.taskId, rowToTaskUiSpec(row));
13031
13250
  }
13251
+ return byTask;
13032
13252
  }
13033
- function ensure2(options) {
13034
- _enqueueEvent({
13035
- type: options.validator ? "assert" : "act",
13036
- id: options.id,
13037
- flow: options.flow,
13038
- runId: options.runId,
13039
- data: options.data,
13040
- filter: options.filter,
13041
- depIds: options.depIds,
13042
- description: options.description,
13043
- validator: options.validator,
13044
- conditions: options.conditions,
13045
- additional_meta: options.additional_meta
13253
+ async function upsertTaskUiSpec(taskId, value, userId) {
13254
+ await getDbClient2().run(`INSERT INTO task_ui_specs (task_id, spec, actions, fallback_text, created_by, updated_by)
13255
+ VALUES (?, ?, ?, ?, ?, ?)
13256
+ ON CONFLICT(task_id) DO UPDATE SET
13257
+ spec=excluded.spec, actions=excluded.actions, fallback_text=excluded.fallback_text,
13258
+ updated_by=excluded.updated_by, updated_at=strftime('%Y-%m-%dT%H:%M:%fZ', 'now')`, [
13259
+ taskId,
13260
+ scrubJsonValue(value.spec),
13261
+ value.actions === undefined ? null : scrubJsonValue(value.actions),
13262
+ scrubSecrets(value.fallbackText),
13263
+ userId ?? null,
13264
+ userId ?? null
13265
+ ]);
13266
+ }
13267
+ async function reserveTaskUiActionRun({
13268
+ taskId,
13269
+ actionId,
13270
+ surface,
13271
+ slackUserId,
13272
+ userId
13273
+ }) {
13274
+ const { changes } = await getDbClient2().run(`INSERT INTO task_ui_action_runs
13275
+ (task_id, action_id, surface, slack_user_id, created_by, updated_by)
13276
+ VALUES (?, ?, ?, ?, ?, ?)
13277
+ ON CONFLICT(task_id, action_id) DO NOTHING`, [taskId, actionId, surface, slackUserId ?? null, userId ?? null, userId ?? null]);
13278
+ return changes === 1 ? "reserved" : "exists";
13279
+ }
13280
+ async function releaseTaskUiActionRun(taskId, actionId) {
13281
+ await getDbClient2().run(`DELETE FROM task_ui_action_runs
13282
+ WHERE task_id = ? AND action_id = ? AND result_task_id IS NULL`, [taskId, actionId]);
13283
+ }
13284
+ async function setTaskUiActionResult(taskId, actionId, resultTaskId) {
13285
+ await getDbClient2().run(`UPDATE task_ui_action_runs SET result_task_id = ?,
13286
+ updated_at = strftime('%Y-%m-%dT%H:%M:%fZ', 'now')
13287
+ WHERE task_id = ? AND action_id = ?`, [resultTaskId, taskId, actionId]);
13288
+ }
13289
+ async function hasTaskUiSpecCheckRefusal(taskId) {
13290
+ return Boolean(await getDbClient2().get("SELECT id FROM agent_log WHERE taskId = ? AND eventType = 'task_ui_spec_check_refused' LIMIT 1", [taskId]));
13291
+ }
13292
+ var TaskUiSpecSchema, TASK_ID_CHUNK2 = 500;
13293
+ var init_task_ui_spec = __esm(() => {
13294
+ init_zod();
13295
+ init_secret_scrubber();
13296
+ init_db4();
13297
+ init_scrub_json();
13298
+ TaskUiSpecSchema = object2({
13299
+ spec: object2({
13300
+ root: string2(),
13301
+ elements: record2(string2(), unknown()),
13302
+ state: record2(string2(), unknown()).optional()
13303
+ }),
13304
+ actions: record2(string2(), object2({ kind: literal2("follow_up"), prompt: string2() })).optional(),
13305
+ fallbackText: string2()
13046
13306
  });
13307
+ });
13308
+
13309
+ // node_modules/@json-render/core/dist/chunk-FVP4K5MD.mjs
13310
+ function unescapeJsonPointer(token) {
13311
+ return token.replace(/~1/g, "/").replace(/~0/g, "~");
13047
13312
  }
13048
- function _enqueueEvent(options) {
13049
- if (!_state.initialized || !_state.batchProcessor) {
13050
- return;
13313
+ function parseJsonPointer(path) {
13314
+ const raw = path.startsWith("/") ? path.slice(1).split("/") : path.split("/");
13315
+ return raw.map(unescapeJsonPointer);
13316
+ }
13317
+ function getByPath(obj, path) {
13318
+ if (!path || path === "/") {
13319
+ return obj;
13051
13320
  }
13052
- try {
13053
- if (typeof options.runId === "function" && isAsyncFunction(options.runId)) {
13054
- log2.error(`Event ${options.id}: runId cannot be an async function`);
13055
- return;
13056
- }
13057
- if (options.filter !== undefined && typeof options.filter === "function" && isAsyncFunction(options.filter)) {
13058
- log2.error(`Event ${options.id}: filter cannot be an async function`);
13059
- return;
13060
- }
13061
- if (options.depIds !== undefined && typeof options.depIds === "function" && isAsyncFunction(options.depIds)) {
13062
- log2.error(`Event ${options.id}: depIds cannot be an async function`);
13063
- return;
13064
- }
13065
- if (options.validator !== undefined && isAsyncFunction(options.validator)) {
13066
- log2.error(`Event ${options.id}: validator cannot be an async function`);
13321
+ const segments = parseJsonPointer(path);
13322
+ let current = obj;
13323
+ for (const segment of segments) {
13324
+ if (current === null || current === undefined) {
13067
13325
  return;
13068
13326
  }
13069
- if (options.conditions !== undefined && typeof options.conditions === "function" && isAsyncFunction(options.conditions)) {
13070
- log2.error(`Event ${options.id}: conditions cannot be an async function`);
13327
+ if (Array.isArray(current)) {
13328
+ const index = parseInt(segment, 10);
13329
+ current = current[index];
13330
+ } else if (typeof current === "object" && Object.hasOwn(current, segment)) {
13331
+ current = current[segment];
13332
+ } else {
13071
13333
  return;
13072
13334
  }
13073
- const event = {
13074
- type: options.type,
13075
- id: options.id,
13076
- flow: options.flow,
13077
- run_id: options.runId,
13078
- data: options.data,
13079
- filter: options.filter,
13080
- dep_ids: options.depIds,
13081
- description: options.description,
13082
- validator: options.validator,
13083
- conditions: options.conditions,
13084
- additional_meta: options.additional_meta
13085
- };
13086
- _state.batchProcessor.enqueue(event);
13087
- } catch (error) {
13088
- log2.error(`Failed to enqueue event ${options.id}: ${error}`);
13089
13335
  }
13336
+ return current;
13090
13337
  }
13091
- function _checkConnection(_apiKey, _baseUrl) {
13092
- try {
13093
- log2.info("Connection check successful (deferred to first batch)");
13094
- return true;
13095
- } catch (error) {
13096
- log2.error(`Connection check failed: ${error}`);
13097
- return false;
13338
+ function resolveRepeatStatePath(statePath, repeatBasePath) {
13339
+ if (typeof statePath === "string") {
13340
+ return statePath;
13341
+ }
13342
+ if (repeatBasePath == null) {
13343
+ return;
13344
+ }
13345
+ if (statePath.$item === "" || statePath.$item === "/") {
13346
+ return repeatBasePath;
13098
13347
  }
13348
+ return joinStatePath(repeatBasePath, statePath.$item);
13099
13349
  }
13100
- function isAsyncFunction(fn) {
13101
- return fn.constructor.name === "AsyncFunction";
13350
+ function resolveRepeatItemStatePath(statePath, index) {
13351
+ return joinStatePath(statePath, String(index));
13102
13352
  }
13103
- var log, BatchProcessor = class {
13104
- _apiKey;
13105
- _baseUrl;
13106
- _batchSize;
13107
- _batchInterval;
13108
- _maxQueueSize;
13109
- _queue = [];
13110
- _timer = null;
13111
- _isShuttingDown = false;
13112
- constructor(options) {
13353
+ function joinStatePath(basePath, childPath) {
13354
+ const child = childPath.startsWith("/") ? childPath.slice(1) : childPath;
13355
+ if (basePath === "" || basePath === "/") {
13356
+ return `/${child}`;
13357
+ }
13358
+ return `${basePath}/${child}`;
13359
+ }
13360
+ var DynamicValueSchema, DynamicStringSchema, DynamicNumberSchema, DynamicBooleanSchema, SPEC_DATA_PART = "spec", SPEC_DATA_PART_TYPE;
13361
+ var init_chunk_FVP4K5MD = __esm(() => {
13362
+ init_zod();
13363
+ DynamicValueSchema = union3([
13364
+ string2(),
13365
+ number2(),
13366
+ boolean(),
13367
+ _null(),
13368
+ object2({ $state: string2() })
13369
+ ]);
13370
+ DynamicStringSchema = union3([
13371
+ string2(),
13372
+ object2({ $state: string2() })
13373
+ ]);
13374
+ DynamicNumberSchema = union3([
13375
+ number2(),
13376
+ object2({ $state: string2() })
13377
+ ]);
13378
+ DynamicBooleanSchema = union3([
13379
+ boolean(),
13380
+ object2({ $state: string2() })
13381
+ ]);
13382
+ SPEC_DATA_PART_TYPE = `data-${SPEC_DATA_PART}`;
13383
+ });
13384
+
13385
+ // node_modules/@json-render/core/dist/index.mjs
13386
+ function conditionUsesItemScope(condition) {
13387
+ if (condition === undefined || typeof condition === "boolean")
13388
+ return false;
13389
+ if (Array.isArray(condition))
13390
+ return condition.some(conditionUsesItemScope);
13391
+ if (typeof condition !== "object" || condition === null)
13392
+ return false;
13393
+ if ("$item" in condition || "$index" in condition)
13394
+ return true;
13395
+ if ("$and" in condition)
13396
+ return condition.$and.some(conditionUsesItemScope);
13397
+ if ("$or" in condition)
13398
+ return condition.$or.some(conditionUsesItemScope);
13399
+ return false;
13400
+ }
13401
+ function splitRepeatVisibility(condition) {
13402
+ if (condition === undefined || !conditionUsesItemScope(condition)) {
13403
+ return { container: condition, itemFilter: undefined };
13404
+ }
13405
+ const partition = (parts) => {
13406
+ const container = parts.filter((part) => !conditionUsesItemScope(part));
13407
+ const item = parts.filter((part) => conditionUsesItemScope(part));
13408
+ return {
13409
+ container: container.length > 0 ? { $and: container } : undefined,
13410
+ itemFilter: item.length > 0 ? { $and: item } : undefined
13411
+ };
13412
+ };
13413
+ if (Array.isArray(condition))
13414
+ return partition(condition);
13415
+ if (typeof condition === "object" && condition !== null && "$and" in condition) {
13416
+ return partition(condition.$and);
13417
+ }
13418
+ return { container: undefined, itemFilter: condition };
13419
+ }
13420
+ function resolveComparisonValue(value, ctx) {
13421
+ if (typeof value === "object" && value !== null) {
13422
+ if ("$state" in value && typeof value.$state === "string") {
13423
+ return getByPath(ctx.stateModel, value.$state);
13424
+ }
13425
+ }
13426
+ return value;
13427
+ }
13428
+ function isItemCondition(cond) {
13429
+ return "$item" in cond;
13430
+ }
13431
+ function isIndexCondition(cond) {
13432
+ return "$index" in cond;
13433
+ }
13434
+ function resolveConditionValue(cond, ctx) {
13435
+ if (isIndexCondition(cond)) {
13436
+ return ctx.repeatIndex;
13437
+ }
13438
+ if (isItemCondition(cond)) {
13439
+ if (ctx.repeatItem === undefined)
13440
+ return;
13441
+ return cond.$item === "" ? ctx.repeatItem : getByPath(ctx.repeatItem, cond.$item);
13442
+ }
13443
+ return getByPath(ctx.stateModel, cond.$state);
13444
+ }
13445
+ function evaluateCondition(cond, ctx) {
13446
+ const value = resolveConditionValue(cond, ctx);
13447
+ let result;
13448
+ if (cond.eq !== undefined) {
13449
+ const rhs = resolveComparisonValue(cond.eq, ctx);
13450
+ result = value === rhs;
13451
+ } else if (cond.neq !== undefined) {
13452
+ const rhs = resolveComparisonValue(cond.neq, ctx);
13453
+ result = value !== rhs;
13454
+ } else if (cond.gt !== undefined) {
13455
+ const rhs = resolveComparisonValue(cond.gt, ctx);
13456
+ result = typeof value === "number" && typeof rhs === "number" ? value > rhs : false;
13457
+ } else if (cond.gte !== undefined) {
13458
+ const rhs = resolveComparisonValue(cond.gte, ctx);
13459
+ result = typeof value === "number" && typeof rhs === "number" ? value >= rhs : false;
13460
+ } else if (cond.lt !== undefined) {
13461
+ const rhs = resolveComparisonValue(cond.lt, ctx);
13462
+ result = typeof value === "number" && typeof rhs === "number" ? value < rhs : false;
13463
+ } else if (cond.lte !== undefined) {
13464
+ const rhs = resolveComparisonValue(cond.lte, ctx);
13465
+ result = typeof value === "number" && typeof rhs === "number" ? value <= rhs : false;
13466
+ } else {
13467
+ result = Boolean(value);
13468
+ }
13469
+ return cond.not === true ? !result : result;
13470
+ }
13471
+ function isAndCondition(condition) {
13472
+ return typeof condition === "object" && condition !== null && !Array.isArray(condition) && "$and" in condition;
13473
+ }
13474
+ function isOrCondition(condition) {
13475
+ return typeof condition === "object" && condition !== null && !Array.isArray(condition) && "$or" in condition;
13476
+ }
13477
+ function evaluateVisibility(condition, ctx) {
13478
+ if (condition === undefined) {
13479
+ return true;
13480
+ }
13481
+ if (typeof condition === "boolean") {
13482
+ return condition;
13483
+ }
13484
+ if (Array.isArray(condition)) {
13485
+ return condition.every((c) => evaluateCondition(c, ctx));
13486
+ }
13487
+ if (isAndCondition(condition)) {
13488
+ return condition.$and.every((child) => evaluateVisibility(child, ctx));
13489
+ }
13490
+ if (isOrCondition(condition)) {
13491
+ return condition.$or.some((child) => evaluateVisibility(child, ctx));
13492
+ }
13493
+ return evaluateCondition(condition, ctx);
13494
+ }
13495
+ function findDirective(value, directives) {
13496
+ if (!directives || directives.size === 0)
13497
+ return;
13498
+ let match;
13499
+ for (const [key, def] of directives) {
13500
+ if (key in value) {
13501
+ if (match) {
13502
+ throw new Error(`Ambiguous directive: object has multiple directive keys ("${match.name}" and "${key}")`);
13503
+ }
13504
+ match = def;
13505
+ }
13506
+ }
13507
+ return match;
13508
+ }
13509
+ function isStateExpression(value) {
13510
+ return typeof value === "object" && value !== null && "$state" in value && typeof value.$state === "string";
13511
+ }
13512
+ function isItemExpression(value) {
13513
+ return typeof value === "object" && value !== null && "$item" in value && typeof value.$item === "string";
13514
+ }
13515
+ function isIndexExpression(value) {
13516
+ return typeof value === "object" && value !== null && "$index" in value && value.$index === true;
13517
+ }
13518
+ function isBindStateExpression(value) {
13519
+ return typeof value === "object" && value !== null && "$bindState" in value && typeof value.$bindState === "string";
13520
+ }
13521
+ function isBindItemExpression(value) {
13522
+ return typeof value === "object" && value !== null && "$bindItem" in value && typeof value.$bindItem === "string";
13523
+ }
13524
+ function isCondExpression(value) {
13525
+ return typeof value === "object" && value !== null && "$cond" in value && "$then" in value && "$else" in value;
13526
+ }
13527
+ function isComputedExpression(value) {
13528
+ return typeof value === "object" && value !== null && "$computed" in value && typeof value.$computed === "string";
13529
+ }
13530
+ function isTemplateExpression(value) {
13531
+ return typeof value === "object" && value !== null && "$template" in value && typeof value.$template === "string";
13532
+ }
13533
+ function resolveBindItemPath(itemPath, ctx) {
13534
+ if (ctx.repeatBasePath == null) {
13535
+ console.warn(`$bindItem used outside repeat scope: "${itemPath}"`);
13536
+ return;
13537
+ }
13538
+ if (itemPath === "")
13539
+ return ctx.repeatBasePath;
13540
+ return ctx.repeatBasePath + "/" + itemPath;
13541
+ }
13542
+ function resolvePropValue(value, ctx) {
13543
+ if (value === null || value === undefined) {
13544
+ return value;
13545
+ }
13546
+ if (isStateExpression(value)) {
13547
+ return getByPath(ctx.stateModel, value.$state);
13548
+ }
13549
+ if (isItemExpression(value)) {
13550
+ if (ctx.repeatItem === undefined)
13551
+ return;
13552
+ return value.$item === "" ? ctx.repeatItem : getByPath(ctx.repeatItem, value.$item);
13553
+ }
13554
+ if (isIndexExpression(value)) {
13555
+ return ctx.repeatIndex;
13556
+ }
13557
+ if (isBindStateExpression(value)) {
13558
+ return getByPath(ctx.stateModel, value.$bindState);
13559
+ }
13560
+ if (isBindItemExpression(value)) {
13561
+ const resolvedPath = resolveBindItemPath(value.$bindItem, ctx);
13562
+ if (resolvedPath === undefined)
13563
+ return;
13564
+ return getByPath(ctx.stateModel, resolvedPath);
13565
+ }
13566
+ if (isCondExpression(value)) {
13567
+ const result = evaluateVisibility(value.$cond, ctx);
13568
+ return resolvePropValue(result ? value.$then : value.$else, ctx);
13569
+ }
13570
+ if (isComputedExpression(value)) {
13571
+ const fn = ctx.functions?.[value.$computed];
13572
+ if (!fn) {
13573
+ if (!warnedComputedFns.has(value.$computed)) {
13574
+ if (warnedComputedFns.size < WARNED_COMPUTED_MAX) {
13575
+ warnedComputedFns.add(value.$computed);
13576
+ }
13577
+ console.warn(`Unknown $computed function: "${value.$computed}"`);
13578
+ }
13579
+ return;
13580
+ }
13581
+ const resolvedArgs = {};
13582
+ if (value.args) {
13583
+ for (const [key, arg] of Object.entries(value.args)) {
13584
+ resolvedArgs[key] = resolvePropValue(arg, ctx);
13585
+ }
13586
+ }
13587
+ return fn(resolvedArgs);
13588
+ }
13589
+ if (isTemplateExpression(value)) {
13590
+ return value.$template.replace(/\$\{([^}]+)\}/g, (_match, rawPath) => {
13591
+ if (rawPath.startsWith("/")) {
13592
+ const resolved2 = getByPath(ctx.stateModel, rawPath);
13593
+ return resolved2 != null ? String(resolved2) : "";
13594
+ }
13595
+ if (ctx.repeatItem !== undefined) {
13596
+ const fromItem = getByPath(ctx.repeatItem, rawPath);
13597
+ if (fromItem != null)
13598
+ return String(fromItem);
13599
+ }
13600
+ const resolved = getByPath(ctx.stateModel, "/" + rawPath);
13601
+ return resolved != null ? String(resolved) : "";
13602
+ });
13603
+ }
13604
+ if (Array.isArray(value)) {
13605
+ return value.map((item) => resolvePropValue(item, ctx));
13606
+ }
13607
+ if (typeof value === "object") {
13608
+ const directive = findDirective(value, ctx.directives);
13609
+ if (directive) {
13610
+ return directive.resolve(value, ctx);
13611
+ }
13612
+ const resolved = {};
13613
+ for (const [key, val] of Object.entries(value)) {
13614
+ resolved[key] = resolvePropValue(val, ctx);
13615
+ }
13616
+ return resolved;
13617
+ }
13618
+ return value;
13619
+ }
13620
+ function resolveElementProps(props, ctx) {
13621
+ const resolved = {};
13622
+ for (const [key, value] of Object.entries(props)) {
13623
+ resolved[key] = resolvePropValue(value, ctx);
13624
+ }
13625
+ return resolved;
13626
+ }
13627
+ function normalizeModes(config) {
13628
+ if (!config?.modes?.length)
13629
+ return DEFAULT_MODES;
13630
+ return config.modes;
13631
+ }
13632
+ function jsonPatchInstructions() {
13633
+ return [
13634
+ "PATCH MODE (RFC 6902 JSON Patch):",
13635
+ "Output one JSON object per line. Each line is a patch operation.",
13636
+ '- Add: {"op":"add","path":"/elements/new-key","value":{...}}',
13637
+ '- Replace: {"op":"replace","path":"/elements/existing-key","value":{...}}',
13638
+ '- Remove: {"op":"remove","path":"/elements/old-key"}',
13639
+ "Only output patches for what needs to change."
13640
+ ].join(`
13641
+ `);
13642
+ }
13643
+ function jsonMergeInstructions() {
13644
+ return [
13645
+ "MERGE MODE (RFC 7396 JSON Merge Patch):",
13646
+ "Output a single JSON object on one line with __json_edit set to true.",
13647
+ "Include only the keys that changed. Unmentioned keys are preserved.",
13648
+ "Set a key to null to delete it.",
13649
+ "",
13650
+ "Example (update a title and add an element):",
13651
+ '{"__json_edit":true,"elements":{"main":{"props":{"title":"New Title"}},"new-el":{"type":"Card","props":{},"children":[]}}}',
13652
+ "",
13653
+ "Example (delete an element):",
13654
+ '{"__json_edit":true,"elements":{"old-widget":null}}'
13655
+ ].join(`
13656
+ `);
13657
+ }
13658
+ function jsonDiffInstructions() {
13659
+ return [
13660
+ "DIFF MODE (unified diff):",
13661
+ "Output a unified diff inside a ```diff code fence.",
13662
+ "The diff applies against the JSON-serialized current spec.",
13663
+ "",
13664
+ "Example:",
13665
+ "```diff",
13666
+ "--- a/spec.json",
13667
+ "+++ b/spec.json",
13668
+ "@@ -3,1 +3,1 @@",
13669
+ '- "title": "Login"',
13670
+ '+ "title": "Welcome Back"',
13671
+ "```"
13672
+ ].join(`
13673
+ `);
13674
+ }
13675
+ function yamlPatchInstructions() {
13676
+ return [
13677
+ "PATCH MODE (RFC 6902 JSON Patch):",
13678
+ "Output RFC 6902 JSON Patch lines inside a ```yaml-patch code fence.",
13679
+ "Each line is one JSON patch operation.",
13680
+ "",
13681
+ "Example:",
13682
+ "```yaml-patch",
13683
+ '{"op":"replace","path":"/elements/main/props/title","value":"New Title"}',
13684
+ '{"op":"add","path":"/elements/new-el","value":{"type":"Card","props":{},"children":[]}}',
13685
+ "```"
13686
+ ].join(`
13687
+ `);
13688
+ }
13689
+ function yamlMergeInstructions() {
13690
+ return [
13691
+ "MERGE MODE (RFC 7396 JSON Merge Patch):",
13692
+ "Output only the changed parts in a ```yaml-edit code fence.",
13693
+ "Uses deep merge semantics: only keys you include are updated. Unmentioned elements and props are preserved.",
13694
+ "Set a key to null to delete it.",
13695
+ "",
13696
+ "Example edit (update title, add a new element):",
13697
+ "```yaml-edit",
13698
+ "elements:",
13699
+ " main:",
13700
+ " props:",
13701
+ " title: Updated Title",
13702
+ " new-chart:",
13703
+ " type: Card",
13704
+ " props: {}",
13705
+ " children: []",
13706
+ "```",
13707
+ "",
13708
+ "Example deletion:",
13709
+ "```yaml-edit",
13710
+ "elements:",
13711
+ " old-widget: null",
13712
+ "```"
13713
+ ].join(`
13714
+ `);
13715
+ }
13716
+ function yamlDiffInstructions() {
13717
+ return [
13718
+ "DIFF MODE (unified diff):",
13719
+ "Output a unified diff inside a ```diff code fence.",
13720
+ "The diff applies against the YAML-serialized current spec.",
13721
+ "",
13722
+ "Example:",
13723
+ "```diff",
13724
+ "--- a/spec.yaml",
13725
+ "+++ b/spec.yaml",
13726
+ "@@ -6,1 +6,1 @@",
13727
+ "- title: Login",
13728
+ "+ title: Welcome Back",
13729
+ "```"
13730
+ ].join(`
13731
+ `);
13732
+ }
13733
+ function modeSelectionGuidance(modes) {
13734
+ if (modes.length === 1)
13735
+ return "";
13736
+ const parts = ["Choose the best edit strategy for the requested change:"];
13737
+ if (modes.includes("patch")) {
13738
+ parts.push("- PATCH: best for precise, targeted single-field updates");
13739
+ }
13740
+ if (modes.includes("merge")) {
13741
+ parts.push("- MERGE: best for structural changes (add/remove elements, reparent children, update multiple props at once)");
13742
+ }
13743
+ if (modes.includes("diff")) {
13744
+ parts.push("- DIFF: best for small text-level changes when you can see the exact lines to change");
13745
+ }
13746
+ return parts.join(`
13747
+ `);
13748
+ }
13749
+ function buildEditInstructions(config, format) {
13750
+ const modes = normalizeModes(config);
13751
+ const sections = [];
13752
+ sections.push("EDITING EXISTING SPECS:");
13753
+ sections.push("");
13754
+ const guidance = modeSelectionGuidance(modes);
13755
+ if (guidance) {
13756
+ sections.push(guidance);
13757
+ sections.push("");
13758
+ }
13759
+ for (const mode of modes) {
13760
+ if (format === "json") {
13761
+ switch (mode) {
13762
+ case "patch":
13763
+ sections.push(jsonPatchInstructions());
13764
+ break;
13765
+ case "merge":
13766
+ sections.push(jsonMergeInstructions());
13767
+ break;
13768
+ case "diff":
13769
+ sections.push(jsonDiffInstructions());
13770
+ break;
13771
+ }
13772
+ } else {
13773
+ switch (mode) {
13774
+ case "patch":
13775
+ sections.push(yamlPatchInstructions());
13776
+ break;
13777
+ case "merge":
13778
+ sections.push(yamlMergeInstructions());
13779
+ break;
13780
+ case "diff":
13781
+ sections.push(yamlDiffInstructions());
13782
+ break;
13783
+ }
13784
+ }
13785
+ sections.push("");
13786
+ }
13787
+ return sections.join(`
13788
+ `);
13789
+ }
13790
+ function createBuilder() {
13791
+ return {
13792
+ string: () => ({ kind: "string" }),
13793
+ number: () => ({ kind: "number" }),
13794
+ boolean: () => ({ kind: "boolean" }),
13795
+ array: (item) => ({ kind: "array", inner: item }),
13796
+ object: (shape) => ({ kind: "object", inner: shape }),
13797
+ record: (value) => ({ kind: "record", inner: value }),
13798
+ any: () => ({ kind: "any" }),
13799
+ zod: () => ({ kind: "zod" }),
13800
+ ref: (path) => ({ kind: "ref", inner: path }),
13801
+ propsOf: (path) => ({ kind: "propsOf", inner: path }),
13802
+ map: (entryShape) => ({ kind: "map", inner: entryShape }),
13803
+ optional: () => ({ optional: true })
13804
+ };
13805
+ }
13806
+ function defineSchema(builder, options) {
13807
+ const s = createBuilder();
13808
+ const definition = builder(s);
13809
+ return {
13810
+ definition,
13811
+ promptTemplate: options?.promptTemplate,
13812
+ defaultRules: options?.defaultRules,
13813
+ builtInActions: options?.builtInActions,
13814
+ createCatalog(catalog) {
13815
+ return createCatalogFromSchema(this, catalog);
13816
+ }
13817
+ };
13818
+ }
13819
+ function createCatalogFromSchema(schema, catalogData) {
13820
+ const components = catalogData.components;
13821
+ const actions = catalogData.actions;
13822
+ const componentNames = components ? Object.keys(components) : [];
13823
+ const actionNames = actions ? Object.keys(actions) : [];
13824
+ const zodSchema = buildZodSchemaFromDefinition(schema.definition, catalogData);
13825
+ return {
13826
+ schema,
13827
+ data: catalogData,
13828
+ componentNames,
13829
+ actionNames,
13830
+ prompt(options = {}) {
13831
+ return generatePrompt(this, options);
13832
+ },
13833
+ jsonSchema(options = {}) {
13834
+ return zodToJsonSchema(zodSchema, options.strict ?? false);
13835
+ },
13836
+ validate(spec) {
13837
+ const result = zodSchema.safeParse(spec);
13838
+ if (result.success) {
13839
+ return {
13840
+ success: true,
13841
+ data: result.data
13842
+ };
13843
+ }
13844
+ return { success: false, error: result.error };
13845
+ },
13846
+ zodSchema() {
13847
+ return zodSchema;
13848
+ },
13849
+ get _specType() {
13850
+ throw new Error("_specType is only for type inference");
13851
+ }
13852
+ };
13853
+ }
13854
+ function buildZodSchemaFromDefinition(definition, catalogData) {
13855
+ return buildZodType(definition.spec, catalogData);
13856
+ }
13857
+ function buildZodType(schemaType, catalogData) {
13858
+ switch (schemaType.kind) {
13859
+ case "string":
13860
+ return string2();
13861
+ case "number":
13862
+ return number2();
13863
+ case "boolean":
13864
+ return boolean();
13865
+ case "any":
13866
+ return any();
13867
+ case "array": {
13868
+ const inner = buildZodType(schemaType.inner, catalogData);
13869
+ return array2(inner);
13870
+ }
13871
+ case "object": {
13872
+ const shape = schemaType.inner;
13873
+ const zodShape = {};
13874
+ for (const [key, value] of Object.entries(shape)) {
13875
+ let zodType = buildZodType(value, catalogData);
13876
+ if (value.optional) {
13877
+ zodType = zodType.optional();
13878
+ }
13879
+ zodShape[key] = zodType;
13880
+ }
13881
+ return object2(zodShape);
13882
+ }
13883
+ case "record": {
13884
+ const inner = buildZodType(schemaType.inner, catalogData);
13885
+ return record2(string2(), inner);
13886
+ }
13887
+ case "ref": {
13888
+ const path = schemaType.inner;
13889
+ const keys = getKeysFromPath(path, catalogData);
13890
+ if (keys.length === 0) {
13891
+ return string2();
13892
+ }
13893
+ if (keys.length === 1) {
13894
+ return literal2(keys[0]);
13895
+ }
13896
+ return _enum2(keys);
13897
+ }
13898
+ case "propsOf": {
13899
+ const path = schemaType.inner;
13900
+ const propsSchemas = getPropsFromPath(path, catalogData);
13901
+ if (propsSchemas.length === 0) {
13902
+ return record2(string2(), unknown());
13903
+ }
13904
+ if (propsSchemas.length === 1) {
13905
+ return propsSchemas[0];
13906
+ }
13907
+ return record2(string2(), unknown());
13908
+ }
13909
+ default:
13910
+ return unknown();
13911
+ }
13912
+ }
13913
+ function getKeysFromPath(path, catalogData) {
13914
+ const parts = path.split(".");
13915
+ let current = { catalog: catalogData };
13916
+ for (const part of parts) {
13917
+ if (current && typeof current === "object") {
13918
+ current = current[part];
13919
+ } else {
13920
+ return [];
13921
+ }
13922
+ }
13923
+ if (current && typeof current === "object") {
13924
+ return Object.keys(current);
13925
+ }
13926
+ return [];
13927
+ }
13928
+ function getPropsFromPath(path, catalogData) {
13929
+ const parts = path.split(".");
13930
+ let current = { catalog: catalogData };
13931
+ for (const part of parts) {
13932
+ if (current && typeof current === "object") {
13933
+ current = current[part];
13934
+ } else {
13935
+ return [];
13936
+ }
13937
+ }
13938
+ if (current && typeof current === "object") {
13939
+ return Object.values(current).map((entry) => entry.props).filter((props) => props !== undefined);
13940
+ }
13941
+ return [];
13942
+ }
13943
+ function generatePrompt(catalog, options) {
13944
+ if (catalog.schema.promptTemplate) {
13945
+ const context = {
13946
+ catalog: catalog.data,
13947
+ componentNames: catalog.componentNames,
13948
+ actionNames: catalog.actionNames,
13949
+ options,
13950
+ formatZodType
13951
+ };
13952
+ return catalog.schema.promptTemplate(context);
13953
+ }
13954
+ const {
13955
+ system = "You are a UI generator that outputs JSON.",
13956
+ customRules = [],
13957
+ mode: rawMode = "standalone"
13958
+ } = options;
13959
+ 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;
13960
+ const lines = [];
13961
+ lines.push(system);
13962
+ lines.push("");
13963
+ if (mode === "inline") {
13964
+ lines.push("OUTPUT FORMAT (text + JSONL, RFC 6902 JSON Patch):");
13965
+ 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.");
13966
+ lines.push("The JSONL lines use RFC 6902 JSON Patch operations to build a UI tree. Always wrap them in a ```spec fence block:");
13967
+ lines.push(" ```spec");
13968
+ lines.push(' {"op":"add","path":"/root","value":"main"}');
13969
+ lines.push(' {"op":"add","path":"/elements/main","value":{"type":"Card","props":{"title":"Hello"},"children":[]}}');
13970
+ lines.push(" ```");
13971
+ 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.");
13972
+ } else {
13973
+ lines.push("OUTPUT FORMAT (JSONL, RFC 6902 JSON Patch):");
13974
+ lines.push("Output JSONL (one JSON object per line) using RFC 6902 JSON Patch operations to build a UI tree.");
13975
+ }
13976
+ 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.");
13977
+ lines.push("");
13978
+ lines.push("Example output (each line is a separate JSON object):");
13979
+ lines.push("");
13980
+ const allComponents = catalog.data.components;
13981
+ const specDefinition = catalog.schema.definition.spec;
13982
+ const specShape = specDefinition.kind === "object" ? specDefinition.inner : undefined;
13983
+ const elementsDefinition = specShape?.elements;
13984
+ const elementDefinition = elementsDefinition?.kind === "record" ? elementsDefinition.inner : undefined;
13985
+ const elementShape = elementDefinition?.kind === "object" ? elementDefinition.inner : undefined;
13986
+ const supportsNamedSlots = elementShape?.slots !== undefined;
13987
+ const cn = catalog.componentNames;
13988
+ const comp1 = cn[0] || "Component";
13989
+ const comp2 = cn.length > 1 ? cn[1] : comp1;
13990
+ const comp1Def = allComponents?.[comp1];
13991
+ const comp2Def = allComponents?.[comp2];
13992
+ const comp1Props = comp1Def ? getExampleProps(comp1Def) : {};
13993
+ const comp2Props = comp2Def ? getExampleProps(comp2Def) : {};
13994
+ const dynamicPropName = comp2Def?.props ? findFirstStringProp(comp2Def.props) : null;
13995
+ const dynamicProps = dynamicPropName ? { ...comp2Props, [dynamicPropName]: { $item: "title" } } : comp2Props;
13996
+ const exampleOutput = [
13997
+ JSON.stringify({ op: "add", path: "/root", value: "main" }),
13998
+ JSON.stringify({
13999
+ op: "add",
14000
+ path: "/elements/main",
14001
+ value: {
14002
+ type: comp1,
14003
+ props: comp1Props,
14004
+ children: ["child-1", "list"]
14005
+ }
14006
+ }),
14007
+ JSON.stringify({
14008
+ op: "add",
14009
+ path: "/elements/child-1",
14010
+ value: { type: comp2, props: comp2Props, children: [] }
14011
+ }),
14012
+ JSON.stringify({
14013
+ op: "add",
14014
+ path: "/elements/list",
14015
+ value: {
14016
+ type: comp1,
14017
+ props: comp1Props,
14018
+ repeat: { statePath: "/items", key: "id" },
14019
+ children: ["item"]
14020
+ }
14021
+ }),
14022
+ JSON.stringify({
14023
+ op: "add",
14024
+ path: "/elements/item",
14025
+ value: { type: comp2, props: dynamicProps, children: [] }
14026
+ }),
14027
+ JSON.stringify({ op: "add", path: "/state/items", value: [] }),
14028
+ JSON.stringify({
14029
+ op: "add",
14030
+ path: "/state/items/0",
14031
+ value: { id: "1", title: "First Item" }
14032
+ }),
14033
+ JSON.stringify({
14034
+ op: "add",
14035
+ path: "/state/items/1",
14036
+ value: { id: "2", title: "Second Item" }
14037
+ })
14038
+ ].join(`
14039
+ `);
14040
+ lines.push(`${exampleOutput}
14041
+
14042
+ 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.`);
14043
+ lines.push("");
14044
+ lines.push("INITIAL STATE:");
14045
+ 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.");
14046
+ 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.");
14047
+ lines.push("Output state patches right after the elements that reference them, so the UI fills in progressively as it streams.");
14048
+ lines.push("Stream state progressively - output one patch per array item instead of one giant blob:");
14049
+ lines.push(' For arrays: {"op":"add","path":"/state/posts/0","value":{"id":"1","title":"First Post",...}} then /state/posts/1, /state/posts/2, etc.');
14050
+ lines.push(' For scalars: {"op":"add","path":"/state/newTodoText","value":""}');
14051
+ lines.push(' Initialize the array first if needed: {"op":"add","path":"/state/posts","value":[]}');
14052
+ 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.');
14053
+ 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.");
14054
+ lines.push("");
14055
+ lines.push("DYNAMIC LISTS (repeat field):");
14056
+ 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" } }.');
14057
+ 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.');
14058
+ 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.');
14059
+ lines.push(`Example: ${JSON.stringify({ type: comp1, props: comp1Props, repeat: { statePath: "/todos", key: "id" }, children: ["todo-item"] })}`);
14060
+ 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.');
14061
+ lines.push("ALWAYS use the repeat field for lists backed by state arrays. NEVER hardcode individual elements for each array item.");
14062
+ lines.push('IMPORTANT: "repeat" is a top-level field on the element (sibling of type/props/children), NOT inside props.');
14063
+ lines.push("");
14064
+ lines.push("ARRAY STATE ACTIONS:");
14065
+ lines.push('Use action "pushState" to append items to arrays. Params: { statePath: "/arrayPath", value: { ...item }, clearStatePath: "/inputPath" }.');
14066
+ lines.push('Values inside pushState can contain { "$state": "/statePath" } references to read current state (e.g. the text from an input field).');
14067
+ lines.push('Use "$id" inside a pushState value to auto-generate a unique ID.');
14068
+ lines.push('Example: on: { "press": { "action": "pushState", "params": { "statePath": "/todos", "value": { "id": "$id", "title": { "$state": "/newTodoText" }, "completed": false }, "clearStatePath": "/newTodoText" } } }');
14069
+ 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.`);
14070
+ lines.push("For lists where users can add/remove items (todos, carts, etc.), use pushState and removeState instead of hardcoding with setState.");
14071
+ lines.push("");
14072
+ 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.');
14073
+ lines.push("");
14074
+ const components = allComponents;
14075
+ if (components) {
14076
+ lines.push(`AVAILABLE COMPONENTS (${catalog.componentNames.length}):`);
14077
+ lines.push("");
14078
+ for (const [name, def] of Object.entries(components)) {
14079
+ const propsStr = def.props ? formatZodType(def.props) : "{}";
14080
+ const slotNames = def.slots ?? [];
14081
+ const namedSlotNames = slotNames.filter((slot) => slot !== "default");
14082
+ const acceptsChildren = slotNames.includes("default");
14083
+ const slotsStr = supportsNamedSlots ? [
14084
+ acceptsChildren ? "accepts children" : "",
14085
+ namedSlotNames.length > 0 ? `slots: ${namedSlotNames.join(", ")}` : ""
14086
+ ].filter(Boolean).join("; ") : slotNames.length > 0 ? "accepts children" : "";
14087
+ const slotsSuffix = slotsStr ? ` [${slotsStr}]` : "";
14088
+ const eventsStr = def.events && def.events.length > 0 ? ` [events: ${def.events.join(", ")}]` : "";
14089
+ const descStr = def.description ? ` - ${def.description}` : "";
14090
+ lines.push(`- ${name}: ${propsStr}${descStr}${slotsSuffix}${eventsStr}`);
14091
+ }
14092
+ lines.push("");
14093
+ }
14094
+ const actions = catalog.data.actions;
14095
+ const builtInActions = catalog.schema.builtInActions ?? [];
14096
+ const hasCustomActions = actions && catalog.actionNames.length > 0;
14097
+ const hasBuiltInActions = builtInActions.length > 0;
14098
+ if (hasCustomActions || hasBuiltInActions) {
14099
+ lines.push("AVAILABLE ACTIONS:");
14100
+ lines.push("");
14101
+ for (const action2 of builtInActions) {
14102
+ lines.push(`- ${action2.name}: ${action2.description} [built-in]`);
14103
+ }
14104
+ if (hasCustomActions) {
14105
+ for (const [name, def] of Object.entries(actions)) {
14106
+ lines.push(`- ${name}${def.description ? `: ${def.description}` : ""}`);
14107
+ }
14108
+ }
14109
+ lines.push("");
14110
+ }
14111
+ lines.push("EVENTS (the `on` field):");
14112
+ 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.");
14113
+ 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": { ... } }`.');
14114
+ lines.push("");
14115
+ lines.push("Example:");
14116
+ lines.push(` ${JSON.stringify({ type: comp1, props: comp1Props, on: { press: { action: "setState", params: { statePath: "/saved", value: true } } }, children: [] })}`);
14117
+ lines.push("");
14118
+ lines.push('Action params can use dynamic references to read from state: { "$state": "/statePath" }.');
14119
+ lines.push("IMPORTANT: Do NOT put action/actionParams inside props. Always use the `on` field for event bindings.");
14120
+ lines.push("");
14121
+ lines.push("VISIBILITY CONDITIONS:");
14122
+ 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.");
14123
+ lines.push(`Correct: ${JSON.stringify({ type: comp1, props: comp1Props, visible: { $state: "/activeTab", eq: "home" }, children: ["..."] })}`);
14124
+ lines.push('- `{ "$state": "/path" }` - visible when state at path is truthy');
14125
+ lines.push('- `{ "$state": "/path", "not": true }` - visible when state at path is falsy');
14126
+ lines.push('- `{ "$state": "/path", "eq": "value" }` - visible when state equals value');
14127
+ lines.push('- `{ "$state": "/path", "neq": "value" }` - visible when state does not equal value');
14128
+ lines.push('- `{ "$state": "/path", "gt": N }` / `gte` / `lt` / `lte` - numeric comparisons');
14129
+ lines.push("- Use ONE operator per condition (eq, neq, gt, gte, lt, lte). Do not combine multiple operators.");
14130
+ lines.push('- Any condition can add `"not": true` to invert its result');
14131
+ lines.push("- `[condition, condition]` - all conditions must be true (implicit AND)");
14132
+ lines.push('- `{ "$and": [condition, condition] }` - explicit AND (use when nesting inside $or)');
14133
+ lines.push('- `{ "$or": [condition, condition] }` - at least one must be true (OR)');
14134
+ lines.push("- `true` / `false` - always visible/hidden");
14135
+ lines.push("");
14136
+ lines.push("Use a component with on.press bound to setState to update state and drive visibility.");
14137
+ 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.`);
14138
+ lines.push("");
14139
+ 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.');
14140
+ lines.push("");
14141
+ lines.push("DYNAMIC PROPS:");
14142
+ lines.push("Any prop value can be a dynamic expression that resolves based on state. Three forms are supported:");
14143
+ lines.push("");
14144
+ lines.push('1. Read-only state: `{ "$state": "/statePath" }` - resolves to the value at that state path (one-way read).');
14145
+ lines.push(' Example: `"color": { "$state": "/theme/primary" }` reads the color from state.');
14146
+ lines.push("");
14147
+ 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.).');
14148
+ lines.push(' Example: `"value": { "$bindState": "/form/email" }` binds the input value to /form/email.');
14149
+ lines.push(' Inside repeat scopes: `"checked": { "$bindItem": "completed" }` binds to the current item\'s completed field.');
14150
+ lines.push("");
14151
+ lines.push('3. Conditional: `{ "$cond": <condition>, "$then": <value>, "$else": <value> }` - evaluates the condition (same syntax as visibility conditions) and picks the matching value.');
14152
+ lines.push(' Example: `"color": { "$cond": { "$state": "/activeTab", "eq": "home" }, "$then": "#007AFF", "$else": "#8E8E93" }`');
14153
+ lines.push("");
14154
+ 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.");
14155
+ lines.push("");
14156
+ 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>`.');
14157
+ 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.');
14158
+ lines.push("");
14159
+ const catalogFunctions = catalog.data.functions;
14160
+ if (catalogFunctions && Object.keys(catalogFunctions).length > 0) {
14161
+ lines.push('5. Computed: `{ "$computed": "<functionName>", "args": { "key": <expression> } }` - calls a registered function with resolved args and returns the result.');
14162
+ lines.push(' Example: `"value": { "$computed": "fullName", "args": { "first": { "$state": "/form/firstName" }, "last": { "$state": "/form/lastName" } } }`');
14163
+ lines.push(" Available functions:");
14164
+ for (const name of Object.keys(catalogFunctions)) {
14165
+ lines.push(` - ${name}`);
14166
+ }
14167
+ lines.push("");
14168
+ }
14169
+ const directives = options.directives;
14170
+ if (directives && directives.length > 0) {
14171
+ lines.push("CUSTOM DYNAMIC VALUES:");
14172
+ lines.push("");
14173
+ for (const d of directives) {
14174
+ const desc = d.description ? ` (${d.description})` : "";
14175
+ lines.push(`- ${d.name}${desc}: ${formatZodType(d.schema)}`);
14176
+ }
14177
+ lines.push("");
14178
+ lines.push("Directives compose: any value field can contain another directive or a $state expression, resolved inside-out.");
14179
+ lines.push("");
14180
+ }
14181
+ const hasChecksComponents = allComponents ? Object.entries(allComponents).some(([, def]) => {
14182
+ if (!def.props)
14183
+ return false;
14184
+ const formatted = formatZodType(def.props);
14185
+ return formatted.includes("checks");
14186
+ }) : false;
14187
+ if (hasChecksComponents) {
14188
+ lines.push("VALIDATION:");
14189
+ lines.push("Form components that accept a `checks` prop support client-side validation.");
14190
+ lines.push('Each check is an object: { "type": "<name>", "message": "...", "args": { ... } }');
14191
+ lines.push("");
14192
+ lines.push("Built-in validation types:");
14193
+ lines.push(" - required — value must be non-empty");
14194
+ lines.push(" - email — valid email format");
14195
+ lines.push(' - minLength — minimum string length (args: { "min": N })');
14196
+ lines.push(' - maxLength — maximum string length (args: { "max": N })');
14197
+ lines.push(' - pattern — match a regex (args: { "pattern": "regex" })');
14198
+ lines.push(' - min — minimum numeric value (args: { "min": N })');
14199
+ lines.push(' - max — maximum numeric value (args: { "max": N })');
14200
+ lines.push(" - numeric — value must be a number");
14201
+ lines.push(" - url — valid URL format");
14202
+ lines.push(' - matches — must equal another field (args: { "other": { "$state": "/path" } })');
14203
+ lines.push(' - equalTo — alias for matches (args: { "other": { "$state": "/path" } })');
14204
+ lines.push(' - lessThan — value must be less than another field (args: { "other": { "$state": "/path" } })');
14205
+ lines.push(' - greaterThan — value must be greater than another field (args: { "other": { "$state": "/path" } })');
14206
+ lines.push(' - requiredIf — required only when another field is truthy (args: { "field": { "$state": "/path" } })');
14207
+ lines.push("");
14208
+ lines.push("Example:");
14209
+ lines.push(' "checks": [{ "type": "required", "message": "Email is required" }, { "type": "email", "message": "Invalid email" }]');
14210
+ lines.push("");
14211
+ lines.push("IMPORTANT: When using checks, the component must also have a { $bindState } or { $bindItem } on its value/checked prop for two-way binding.");
14212
+ lines.push("Always include validation checks on form inputs for a good user experience (e.g. required, email, minLength).");
14213
+ lines.push("");
14214
+ }
14215
+ if (hasCustomActions || hasBuiltInActions) {
14216
+ lines.push("STATE WATCHERS:");
14217
+ 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.");
14218
+ lines.push("Maps state paths (JSON Pointers) to action bindings. When the value at a watched path changes, the bound actions fire automatically.");
14219
+ lines.push("");
14220
+ lines.push("Example (cascading select — country changes trigger city loading):");
14221
+ 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: [] })}`);
14222
+ lines.push("");
14223
+ lines.push("Use `watch` for cascading dependencies where changing one field should trigger side effects (loading data, resetting dependent fields, computing derived values).");
14224
+ 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.");
14225
+ lines.push("");
14226
+ }
14227
+ const editModes = options.editModes;
14228
+ if (editModes && editModes.length > 0) {
14229
+ lines.push(buildEditInstructions({ modes: editModes }, "json"));
14230
+ }
14231
+ lines.push("RULES:");
14232
+ const baseRules = mode === "inline" ? [
14233
+ "When generating UI, wrap all JSONL patches in a ```spec code fence - one JSON object per line inside the fence",
14234
+ "Write a brief conversational response before any JSONL output",
14235
+ 'First set root: {"op":"add","path":"/root","value":"<root-key>"}',
14236
+ 'Then add each element: {"op":"add","path":"/elements/<key>","value":{...}}',
14237
+ "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.",
14238
+ "ONLY use components listed above",
14239
+ "Each element value needs: type, props, children (array of child keys)",
14240
+ "Use unique keys for the element map entries (e.g., 'header', 'metric-1', 'chart-revenue')"
14241
+ ] : [
14242
+ "Output ONLY JSONL patches - one JSON object per line, no markdown, no code fences",
14243
+ 'First set root: {"op":"add","path":"/root","value":"<root-key>"}',
14244
+ 'Then add each element: {"op":"add","path":"/elements/<key>","value":{...}}',
14245
+ "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.",
14246
+ "ONLY use components listed above",
14247
+ "Each element value needs: type, props, children (array of child keys)",
14248
+ "Use unique keys for the element map entries (e.g., 'header', 'metric-1', 'chart-revenue')"
14249
+ ];
14250
+ const schemaRules = catalog.schema.defaultRules ?? [];
14251
+ const allRules = [...baseRules, ...schemaRules, ...customRules];
14252
+ allRules.forEach((rule, i) => {
14253
+ lines.push(`${i + 1}. ${rule}`);
14254
+ });
14255
+ return lines.join(`
14256
+ `);
14257
+ }
14258
+ function getExampleProps(def) {
14259
+ if (def.example && Object.keys(def.example).length > 0) {
14260
+ return def.example;
14261
+ }
14262
+ if (def.props) {
14263
+ return generateExamplePropsFromZod(def.props);
14264
+ }
14265
+ return {};
14266
+ }
14267
+ function generateExamplePropsFromZod(schema) {
14268
+ if (!schema || !schema._def)
14269
+ return {};
14270
+ const def = schema._def;
14271
+ const typeName = getZodTypeName(schema);
14272
+ if (typeName !== "ZodObject" && typeName !== "object")
14273
+ return {};
14274
+ const shape = typeof def.shape === "function" ? def.shape() : def.shape;
14275
+ if (!shape)
14276
+ return {};
14277
+ const result = {};
14278
+ for (const [key, value] of Object.entries(shape)) {
14279
+ const innerTypeName = getZodTypeName(value);
14280
+ if (innerTypeName === "ZodOptional" || innerTypeName === "optional" || innerTypeName === "ZodNullable" || innerTypeName === "nullable") {
14281
+ continue;
14282
+ }
14283
+ result[key] = generateExampleValue(value);
14284
+ }
14285
+ return result;
14286
+ }
14287
+ function generateExampleValue(schema) {
14288
+ if (!schema || !schema._def)
14289
+ return "...";
14290
+ const def = schema._def;
14291
+ const typeName = getZodTypeName(schema);
14292
+ switch (typeName) {
14293
+ case "ZodString":
14294
+ case "string":
14295
+ return "example";
14296
+ case "ZodNumber":
14297
+ case "number":
14298
+ return 0;
14299
+ case "ZodBoolean":
14300
+ case "boolean":
14301
+ return true;
14302
+ case "ZodLiteral":
14303
+ case "literal":
14304
+ return def.value;
14305
+ case "ZodEnum":
14306
+ case "enum": {
14307
+ if (Array.isArray(def.values) && def.values.length > 0)
14308
+ return def.values[0];
14309
+ if (def.entries && typeof def.entries === "object") {
14310
+ const values = Object.values(def.entries);
14311
+ return values.length > 0 ? values[0] : "example";
14312
+ }
14313
+ return "example";
14314
+ }
14315
+ case "ZodOptional":
14316
+ case "optional":
14317
+ case "ZodNullable":
14318
+ case "nullable":
14319
+ case "ZodDefault":
14320
+ case "default": {
14321
+ const inner = def.innerType ?? def.wrapped;
14322
+ return inner ? generateExampleValue(inner) : null;
14323
+ }
14324
+ case "ZodArray":
14325
+ case "array":
14326
+ return [];
14327
+ case "ZodObject":
14328
+ case "object":
14329
+ return generateExamplePropsFromZod(schema);
14330
+ case "ZodUnion":
14331
+ case "union": {
14332
+ const options = def.options;
14333
+ return options && options.length > 0 ? generateExampleValue(options[0]) : "...";
14334
+ }
14335
+ default:
14336
+ return "...";
14337
+ }
14338
+ }
14339
+ function findFirstStringProp(schema) {
14340
+ if (!schema || !schema._def)
14341
+ return null;
14342
+ const def = schema._def;
14343
+ const typeName = getZodTypeName(schema);
14344
+ if (typeName !== "ZodObject" && typeName !== "object")
14345
+ return null;
14346
+ const shape = typeof def.shape === "function" ? def.shape() : def.shape;
14347
+ if (!shape)
14348
+ return null;
14349
+ for (const [key, value] of Object.entries(shape)) {
14350
+ const innerTypeName = getZodTypeName(value);
14351
+ if (innerTypeName === "ZodOptional" || innerTypeName === "optional" || innerTypeName === "ZodNullable" || innerTypeName === "nullable") {
14352
+ continue;
14353
+ }
14354
+ if (innerTypeName === "ZodString" || innerTypeName === "string") {
14355
+ return key;
14356
+ }
14357
+ }
14358
+ return null;
14359
+ }
14360
+ function getZodTypeName(schema) {
14361
+ if (!schema || !schema._def)
14362
+ return "";
14363
+ const def = schema._def;
14364
+ return def.typeName ?? def.type ?? "";
14365
+ }
14366
+ function formatZodType(schema) {
14367
+ if (!schema || !schema._def)
14368
+ return "unknown";
14369
+ const def = schema._def;
14370
+ const typeName = getZodTypeName(schema);
14371
+ switch (typeName) {
14372
+ case "ZodString":
14373
+ case "string":
14374
+ return "string";
14375
+ case "ZodNumber":
14376
+ case "number":
14377
+ return "number";
14378
+ case "ZodBoolean":
14379
+ case "boolean":
14380
+ return "boolean";
14381
+ case "ZodLiteral":
14382
+ case "literal": {
14383
+ const litValues = def.values;
14384
+ const litValue = litValues?.[0] ?? def.value;
14385
+ return JSON.stringify(litValue);
14386
+ }
14387
+ case "ZodEnum":
14388
+ case "enum": {
14389
+ let values;
14390
+ if (Array.isArray(def.values)) {
14391
+ values = def.values;
14392
+ } else if (def.entries && typeof def.entries === "object") {
14393
+ values = Object.values(def.entries);
14394
+ } else {
14395
+ return "enum";
14396
+ }
14397
+ return values.map((v) => `"${v}"`).join(" | ");
14398
+ }
14399
+ case "ZodArray":
14400
+ case "array": {
14401
+ const inner = typeof def.element === "object" ? def.element : typeof def.type === "object" ? def.type : undefined;
14402
+ return inner ? `Array<${formatZodType(inner)}>` : "Array<unknown>";
14403
+ }
14404
+ case "ZodObject":
14405
+ case "object": {
14406
+ const shape = typeof def.shape === "function" ? def.shape() : def.shape;
14407
+ if (!shape)
14408
+ return "object";
14409
+ const props = Object.entries(shape).map(([key, value]) => {
14410
+ const innerTypeName = getZodTypeName(value);
14411
+ const isOptional = innerTypeName === "ZodOptional" || innerTypeName === "ZodNullable" || innerTypeName === "optional" || innerTypeName === "nullable";
14412
+ return `${key}${isOptional ? "?" : ""}: ${formatZodType(value)}`;
14413
+ }).join(", ");
14414
+ return `{ ${props} }`;
14415
+ }
14416
+ case "ZodOptional":
14417
+ case "optional":
14418
+ case "ZodNullable":
14419
+ case "nullable": {
14420
+ const inner = def.innerType ?? def.wrapped;
14421
+ return inner ? formatZodType(inner) : "unknown";
14422
+ }
14423
+ case "ZodUnion":
14424
+ case "union": {
14425
+ const options = def.options;
14426
+ return options ? options.map((opt) => formatZodType(opt)).join(" | ") : "unknown";
14427
+ }
14428
+ case "ZodRecord":
14429
+ case "record": {
14430
+ const keyType = def.keyType ?? undefined;
14431
+ const valueType = def.valueType ?? def.element ?? undefined;
14432
+ const keyStr = keyType ? formatZodType(keyType) : "string";
14433
+ const valueStr = valueType ? formatZodType(valueType) : "unknown";
14434
+ return `Record<${keyStr}, ${valueStr}>`;
14435
+ }
14436
+ case "ZodDefault":
14437
+ case "default": {
14438
+ const inner = def.innerType ?? def.wrapped;
14439
+ return inner ? formatZodType(inner) : "unknown";
14440
+ }
14441
+ default:
14442
+ return "unknown";
14443
+ }
14444
+ }
14445
+ function zodTypeName(def) {
14446
+ if (typeof def.type === "string")
14447
+ return def.type;
14448
+ if (typeof def.typeName === "string")
14449
+ return def.typeName;
14450
+ return "";
14451
+ }
14452
+ function normalizeTypeName(raw) {
14453
+ if (raw.startsWith("Zod")) {
14454
+ return raw.slice(3).toLowerCase();
14455
+ }
14456
+ return raw.toLowerCase();
14457
+ }
14458
+ function zodToJsonSchema(schema, strict = false) {
14459
+ const def = schema._def;
14460
+ const kind = normalizeTypeName(zodTypeName(def));
14461
+ switch (kind) {
14462
+ case "string":
14463
+ return { type: "string" };
14464
+ case "number":
14465
+ return { type: "number" };
14466
+ case "boolean":
14467
+ return { type: "boolean" };
14468
+ case "literal": {
14469
+ const values = def.values;
14470
+ const value = values ? values[0] : def.value;
14471
+ return { const: value };
14472
+ }
14473
+ case "enum": {
14474
+ const entries = def.entries;
14475
+ const values = entries ? Object.values(entries) : def.values;
14476
+ return { enum: values ?? [] };
14477
+ }
14478
+ case "array": {
14479
+ const inner = def.element ?? def.type;
14480
+ return {
14481
+ type: "array",
14482
+ items: inner ? zodToJsonSchema(inner, strict) : {}
14483
+ };
14484
+ }
14485
+ case "object": {
14486
+ const rawShape = def.shape;
14487
+ const shape = typeof rawShape === "function" ? rawShape() : rawShape;
14488
+ if (!shape) {
14489
+ if (strict) {
14490
+ return {
14491
+ type: "object",
14492
+ properties: {},
14493
+ required: [],
14494
+ additionalProperties: false
14495
+ };
14496
+ }
14497
+ return { type: "object" };
14498
+ }
14499
+ const properties = {};
14500
+ const required = [];
14501
+ for (const [key, value] of Object.entries(shape)) {
14502
+ const innerDef = value._def;
14503
+ const innerKind = normalizeTypeName(zodTypeName(innerDef));
14504
+ const isOptional = innerKind === "optional" || innerKind === "nullable";
14505
+ if (strict) {
14506
+ required.push(key);
14507
+ if (isOptional) {
14508
+ const unwrapped = zodToJsonSchema(value, strict);
14509
+ properties[key] = { anyOf: [unwrapped, { type: "null" }] };
14510
+ } else {
14511
+ properties[key] = zodToJsonSchema(value, strict);
14512
+ }
14513
+ } else {
14514
+ properties[key] = zodToJsonSchema(value);
14515
+ if (!isOptional) {
14516
+ required.push(key);
14517
+ }
14518
+ }
14519
+ }
14520
+ return {
14521
+ type: "object",
14522
+ properties,
14523
+ required: required.length > 0 ? required : undefined,
14524
+ additionalProperties: false
14525
+ };
14526
+ }
14527
+ case "record": {
14528
+ const valueType = def.valueType;
14529
+ if (strict) {
14530
+ return {
14531
+ type: "object",
14532
+ properties: {},
14533
+ required: [],
14534
+ additionalProperties: false
14535
+ };
14536
+ }
14537
+ return {
14538
+ type: "object",
14539
+ additionalProperties: valueType ? zodToJsonSchema(valueType) : true
14540
+ };
14541
+ }
14542
+ case "optional":
14543
+ case "nullable": {
14544
+ const inner = def.innerType;
14545
+ return inner ? zodToJsonSchema(inner, strict) : {};
14546
+ }
14547
+ case "union": {
14548
+ const options = def.options;
14549
+ return options ? { anyOf: options.map((o) => zodToJsonSchema(o, strict)) } : {};
14550
+ }
14551
+ case "any":
14552
+ case "unknown":
14553
+ if (strict) {
14554
+ return {
14555
+ type: "object",
14556
+ properties: {},
14557
+ required: [],
14558
+ additionalProperties: false
14559
+ };
14560
+ }
14561
+ return {};
14562
+ default:
14563
+ return {};
14564
+ }
14565
+ }
14566
+ 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;
14567
+ var init_dist = __esm(() => {
14568
+ init_chunk_FVP4K5MD();
14569
+ init_zod();
14570
+ init_zod();
14571
+ init_zod();
14572
+ init_zod();
14573
+ init_zod();
14574
+ init_zod();
14575
+ init_zod();
14576
+ numericOrStateRef = union3([
14577
+ number2(),
14578
+ object2({ $state: string2() })
14579
+ ]);
14580
+ comparisonOps = {
14581
+ eq: unknown().optional(),
14582
+ neq: unknown().optional(),
14583
+ gt: numericOrStateRef.optional(),
14584
+ gte: numericOrStateRef.optional(),
14585
+ lt: numericOrStateRef.optional(),
14586
+ lte: numericOrStateRef.optional(),
14587
+ not: literal2(true).optional()
14588
+ };
14589
+ StateConditionSchema = object2({
14590
+ $state: string2(),
14591
+ ...comparisonOps
14592
+ });
14593
+ ItemConditionSchema = object2({
14594
+ $item: string2(),
14595
+ ...comparisonOps
14596
+ });
14597
+ IndexConditionSchema = object2({
14598
+ $index: literal2(true),
14599
+ ...comparisonOps
14600
+ });
14601
+ SingleConditionSchema = union3([
14602
+ StateConditionSchema,
14603
+ ItemConditionSchema,
14604
+ IndexConditionSchema
14605
+ ]);
14606
+ VisibilityConditionSchema = lazy(() => union3([
14607
+ boolean(),
14608
+ SingleConditionSchema,
14609
+ array2(SingleConditionSchema),
14610
+ object2({ $and: array2(VisibilityConditionSchema) }),
14611
+ object2({ $or: array2(VisibilityConditionSchema) })
14612
+ ]));
14613
+ StrictSingleConditionSchema = union3([
14614
+ strictObject2({ $state: string2(), ...comparisonOps }),
14615
+ strictObject2({ $item: string2(), ...comparisonOps }),
14616
+ strictObject2({ $index: literal2(true), ...comparisonOps })
14617
+ ]);
14618
+ VisibilityConditionStrictSchema = lazy(() => union3([
14619
+ boolean(),
14620
+ StrictSingleConditionSchema,
14621
+ array2(StrictSingleConditionSchema),
14622
+ strictObject2({ $and: array2(VisibilityConditionStrictSchema) }),
14623
+ strictObject2({ $or: array2(VisibilityConditionStrictSchema) })
14624
+ ]));
14625
+ warnedComputedFns = /* @__PURE__ */ new Set;
14626
+ ActionConfirmSchema = object2({
14627
+ title: string2(),
14628
+ message: string2(),
14629
+ confirmLabel: string2().optional(),
14630
+ cancelLabel: string2().optional(),
14631
+ variant: _enum2(["default", "danger"]).optional()
14632
+ });
14633
+ ActionOnSuccessSchema = union3([
14634
+ object2({ navigate: string2() }),
14635
+ object2({ set: record2(string2(), unknown()) }),
14636
+ object2({
14637
+ action: string2(),
14638
+ params: record2(string2(), DynamicValueSchema).optional()
14639
+ })
14640
+ ]);
14641
+ ActionOnErrorSchema = union3([
14642
+ object2({ set: record2(string2(), unknown()) }),
14643
+ object2({
14644
+ action: string2(),
14645
+ params: record2(string2(), DynamicValueSchema).optional()
14646
+ })
14647
+ ]);
14648
+ ActionBindingSchema = object2({
14649
+ action: string2(),
14650
+ params: record2(string2(), DynamicValueSchema).optional(),
14651
+ confirm: ActionConfirmSchema.optional(),
14652
+ onSuccess: ActionOnSuccessSchema.optional(),
14653
+ onError: ActionOnErrorSchema.optional(),
14654
+ preventDefault: boolean().optional()
14655
+ });
14656
+ ValidationCheckSchema = object2({
14657
+ type: string2(),
14658
+ args: record2(string2(), DynamicValueSchema).optional(),
14659
+ message: string2()
14660
+ });
14661
+ ValidationConfigSchema = object2({
14662
+ checks: array2(ValidationCheckSchema).optional(),
14663
+ validateOn: _enum2(["change", "blur", "submit"]).optional(),
14664
+ enabled: VisibilityConditionSchema.optional()
14665
+ });
14666
+ DEFAULT_MODES = ["patch"];
14667
+ seedSchema = object2({
14668
+ root: string2().min(1),
14669
+ elements: record2(string2(), object2({
14670
+ type: string2(),
14671
+ props: record2(string2(), unknown()),
14672
+ children: array2(string2()).optional(),
14673
+ slots: record2(string2(), array2(string2())).optional(),
14674
+ on: record2(string2(), unknown()).optional(),
14675
+ visible: unknown().optional()
14676
+ }).strict()),
14677
+ state: record2(string2(), unknown()).optional()
14678
+ }).strict();
14679
+ compositionActionSchema = ActionBindingSchema.extend({
14680
+ params: record2(string2(), unknown()).optional(),
14681
+ onSuccess: unknown().optional(),
14682
+ onError: unknown().optional()
14683
+ }).strict();
14684
+ probability = number2().min(0).max(1);
14685
+ responseSchema = object2({
14686
+ answers: record2(string2(), object2({ type: literal2("choice"), choice: string2() })),
14687
+ providerMetadata: object2({
14688
+ typesafe: object2({ confidence: record2(string2(), probability) }).optional()
14689
+ }).optional(),
14690
+ usage: object2({ inputTokens: number2().int().nonnegative().optional() }).optional()
14691
+ });
14692
+ });
14693
+
14694
+ // node_modules/@json-render/chat/dist/index.mjs
14695
+ function normalizeTableRows(props) {
14696
+ if (!Array.isArray(props.rows) || !Array.isArray(props.headers))
14697
+ return props;
14698
+ const headers = props.headers.map((h) => normalizeKey(String(h)));
14699
+ const rows = props.rows.map((row) => {
14700
+ if (!row || typeof row !== "object" || Array.isArray(row))
14701
+ return row;
14702
+ const entries = Object.entries(row).map(([k, v]) => [normalizeKey(k), v]);
14703
+ const byKey = new Map(entries);
14704
+ const unmatched = entries.filter(([k]) => !headers.includes(k));
14705
+ const rest = [
14706
+ ...unmatched.filter(([k]) => !ID_KEYS.has(k)),
14707
+ ...unmatched.filter(([k]) => ID_KEYS.has(k))
14708
+ ];
14709
+ return headers.map((h) => byKey.has(h) ? byKey.get(h) : rest.shift()?.[1]);
14710
+ });
14711
+ return { ...props, rows };
14712
+ }
14713
+ function validateProps(elements, defs) {
14714
+ const issues = [];
14715
+ for (const [key, el] of Object.entries(elements)) {
14716
+ const def = defs[el.type];
14717
+ if (!def) {
14718
+ issues.push(`${key}: unknown component "${el.type}"`);
14719
+ continue;
14720
+ }
14721
+ const props = el.type === "Table" ? normalizeTableRows(el.props ?? {}) : el.props ?? {};
14722
+ const parsed = def.props.safeParse(props);
14723
+ if (!parsed.success) {
14724
+ for (const issue of parsed.error.issues)
14725
+ issues.push(`${key}.props.${issue.path.join(".")}: ${issue.message}`);
14726
+ } else {
14727
+ el.props = parsed.data;
14728
+ }
14729
+ }
14730
+ return issues;
14731
+ }
14732
+ function validateStructure(spec, elements, defs) {
14733
+ const issues = [];
14734
+ const root = elements[spec.root];
14735
+ if (!root)
14736
+ issues.push(`root "${spec.root}" is not an element`);
14737
+ else if (root.type !== "Card")
14738
+ issues.push("root must be a Card");
14739
+ for (const [key, el] of Object.entries(elements)) {
14740
+ if (el.children.length && !defs[el.type]?.slots?.length)
14741
+ issues.push(`${key}: ${el.type} cannot have children`);
14742
+ for (const childKey of el.children) {
14743
+ const child = elements[childKey];
14744
+ if (!child) {
14745
+ issues.push(`${key}: missing child "${childKey}"`);
14746
+ continue;
14747
+ }
14748
+ if (el.type === "Fields" && child.type !== "Field")
14749
+ issues.push(`${key}: Fields only holds Field elements`);
14750
+ if (el.type === "Actions" && !["Button", "LinkButton"].includes(child.type))
14751
+ issues.push(`${key}: Actions only holds Button and LinkButton elements`);
14752
+ }
14753
+ if (el.type === "Table") {
14754
+ const width = el.props.headers.length;
14755
+ el.props.rows.forEach((row, i) => {
14756
+ if (row.length !== width)
14757
+ issues.push(`${key}: row ${i} has ${row.length} cells, expected ${width}`);
14758
+ });
14759
+ }
14760
+ if (el.type === "Chart" && el.props.chart.type !== "pie") {
14761
+ const count = el.props.chart.categories.length;
14762
+ for (const series of el.props.chart.series)
14763
+ if (series.values.length !== count)
14764
+ issues.push(`${key}: series "${series.name}" has ${series.values.length} values, expected ${count}`);
14765
+ }
14766
+ }
14767
+ return issues;
14768
+ }
14769
+ function validateLimits(elements, limits) {
14770
+ const issues = [];
14771
+ const all = Object.entries(elements);
14772
+ const count = (type) => all.filter(([, el]) => el.type === type).length;
14773
+ const over = (value, max) => max !== undefined && value > max;
14774
+ if (over(count("Table"), limits.tables))
14775
+ issues.push(`at most ${limits.tables} Table per message`);
14776
+ if (over(count("Chart"), limits.charts))
14777
+ issues.push(`at most ${limits.charts} Chart per message`);
14778
+ for (const [key, el] of all) {
14779
+ const p = el.props;
14780
+ if (el.type === "Fields" && over(el.children.length, limits.fields))
14781
+ issues.push(`${key}: at most ${limits.fields} fields`);
14782
+ if (el.type === "Table") {
14783
+ if (over(p.rows.length + 1, limits.tableRows))
14784
+ issues.push(`${key}: at most ${limits.tableRows} rows including the header`);
14785
+ if (over(p.headers.length, limits.tableColumns))
14786
+ issues.push(`${key}: at most ${limits.tableColumns} columns`);
14787
+ }
14788
+ if (el.type === "Chart") {
14789
+ const c = p.chart;
14790
+ if (over(p.title.length, limits.chartTitle))
14791
+ issues.push(`${key}: title longer than ${limits.chartTitle} characters`);
14792
+ const labels = c.type === "pie" ? c.segments.map((s) => s.label) : [...c.categories, ...c.series.map((s) => s.name)];
14793
+ for (const label of labels)
14794
+ if (over(label.length, limits.chartLabel))
14795
+ issues.push(`${key}: label "${label}" longer than ${limits.chartLabel} characters`);
14796
+ const groups = c.type === "pie" ? c.segments.length : c.series.length;
14797
+ if (over(groups, limits.chartSeries))
14798
+ issues.push(`${key}: at most ${limits.chartSeries} series or segments`);
14799
+ if (c.type !== "pie" && over(c.categories.length, limits.chartPoints))
14800
+ issues.push(`${key}: at most ${limits.chartPoints} categories`);
14801
+ }
14802
+ }
14803
+ return issues;
14804
+ }
14805
+ function toChild(key, elements) {
14806
+ const el = elements[key];
14807
+ const p = el.props;
14808
+ const children = () => el.children.map((k) => elements[k]);
14809
+ switch (el.type) {
14810
+ case "Section":
14811
+ return section(el.children.map((k) => toChild(k, elements)));
14812
+ case "Card":
14813
+ return section([
14814
+ ...p.title ? [text(p.title, "bold")] : [],
14815
+ ...p.subtitle ? [text(p.subtitle, "muted")] : [],
14816
+ ...el.children.map((k) => toChild(k, elements))
14817
+ ]);
14818
+ case "Text":
14819
+ return text(p.content, p.style ?? undefined);
14820
+ case "Divider":
14821
+ return divider();
14822
+ case "Image":
14823
+ return image(p.url, p.alt);
14824
+ case "Fields":
14825
+ return fields(children().map((f) => field(f.props.label, f.props.value)));
14826
+ case "Table":
14827
+ return table({
14828
+ headers: p.headers,
14829
+ rows: p.rows,
14830
+ align: p.align ?? undefined,
14831
+ caption: p.caption ?? undefined
14832
+ });
14833
+ case "Chart": {
14834
+ const c = p.chart;
14835
+ return chart({
14836
+ title: p.title,
14837
+ chart: c.type === "pie" ? { type: "pie", segments: c.segments } : {
14838
+ type: c.type,
14839
+ categories: c.categories,
14840
+ xLabel: c.xLabel ?? undefined,
14841
+ yLabel: c.yLabel ?? undefined,
14842
+ series: c.series.map((s) => ({
14843
+ name: s.name,
14844
+ data: s.values.map((value, i) => ({
14845
+ label: c.categories[i],
14846
+ value
14847
+ }))
14848
+ }))
14849
+ }
14850
+ });
14851
+ }
14852
+ case "Actions":
14853
+ return actions(children().map((b) => b.type === "LinkButton" ? linkButton({ label: b.props.label, url: b.props.url }) : button({
14854
+ id: b.props.id,
14855
+ label: b.props.label,
14856
+ style: b.props.style ?? undefined,
14857
+ value: b.props.value ?? undefined
14858
+ })));
14859
+ default:
14860
+ throw new CardSpecError([`${key}: ${el.type} cannot be nested here`]);
14861
+ }
14862
+ }
14863
+ function materialize(spec, maxElements) {
14864
+ const source = spec.elements ?? {};
14865
+ const stateModel = spec.state ?? {};
14866
+ const out = {};
14867
+ const missing = [];
14868
+ const seen = /* @__PURE__ */ new Set;
14869
+ let budget = maxElements;
14870
+ let overflow = false;
14871
+ const spend = () => {
14872
+ if (budget <= 0) {
14873
+ overflow = true;
14874
+ return false;
14875
+ }
14876
+ budget -= 1;
14877
+ return true;
14878
+ };
14879
+ const itemsAt = (repeat, ctx) => {
14880
+ const path = resolveRepeatStatePath(repeat.statePath, ctx.repeatBasePath);
14881
+ const items = path ? getByPath(stateModel, path) : undefined;
14882
+ return { path: path ?? "", items: Array.isArray(items) ? items : [] };
14883
+ };
14884
+ const itemContext = (path, item, index) => ({
14885
+ stateModel,
14886
+ repeatItem: item,
14887
+ repeatIndex: index,
14888
+ repeatBasePath: resolveRepeatItemStatePath(path, index)
14889
+ });
14890
+ const visit = (key, outKey, ctx) => {
14891
+ const el = source[key];
14892
+ if (!el?.type) {
14893
+ missing.push(key);
14894
+ return false;
14895
+ }
14896
+ if (seen.has(outKey))
14897
+ return false;
14898
+ const { container, itemFilter } = el.repeat && ctx.repeatIndex === undefined ? splitRepeatVisibility(el.visible) : { container: el.visible, itemFilter: undefined };
14899
+ if (container !== undefined && !evaluateVisibility(container, ctx))
14900
+ return false;
14901
+ if (!spend())
14902
+ return false;
14903
+ seen.add(outKey);
14904
+ const props = el.props ?? {};
14905
+ const childKeys = el.children ?? [];
14906
+ const children = [];
14907
+ const repeat = el.repeat;
14908
+ const keep = (path, item, index) => itemFilter === undefined || evaluateVisibility(itemFilter, itemContext(path, item, index));
14909
+ if (repeat && el.type === "Table" && Array.isArray(props.rows)) {
14910
+ const { path, items } = itemsAt(repeat, ctx);
14911
+ const rows = [];
14912
+ for (let index = 0;index < items.length && !overflow; index++) {
14913
+ if (!keep(path, items[index], index))
14914
+ continue;
14915
+ const itemCtx = itemContext(path, items[index], index);
14916
+ for (const row of props.rows) {
14917
+ if (!spend())
14918
+ break;
14919
+ rows.push(resolveElementProps({ row }, itemCtx).row);
14920
+ }
14921
+ }
14922
+ out[outKey] = {
14923
+ type: el.type,
14924
+ props: { ...resolveElementProps(props, ctx), rows },
14925
+ children: []
14926
+ };
14927
+ return true;
14928
+ }
14929
+ if (repeat) {
14930
+ const { path, items } = itemsAt(repeat, ctx);
14931
+ const scope = outKey === key ? "" : `${outKey}.`;
14932
+ for (let index = 0;index < items.length && !overflow; index++) {
14933
+ if (!keep(path, items[index], index))
14934
+ continue;
14935
+ const itemCtx = itemContext(path, items[index], index);
14936
+ for (const child of childKeys) {
14937
+ const childOut = `${child}#${scope}${index}`;
14938
+ if (visit(child, childOut, itemCtx))
14939
+ children.push(childOut);
14940
+ }
14941
+ }
14942
+ } else {
14943
+ const suffix = outKey.slice(key.length);
14944
+ for (const child of childKeys)
14945
+ if (visit(child, child + suffix, ctx))
14946
+ children.push(child + suffix);
14947
+ }
14948
+ out[outKey] = {
14949
+ type: el.type,
14950
+ props: resolveElementProps(props, ctx),
14951
+ children
14952
+ };
14953
+ return true;
14954
+ };
14955
+ if (spec.root)
14956
+ visit(spec.root, spec.root, { stateModel });
14957
+ return { elements: out, missing, overflow };
14958
+ }
14959
+ function prune(elements, rootKey) {
14960
+ const kept = /* @__PURE__ */ new Map;
14961
+ const visit = (key) => {
14962
+ const cached = kept.get(key);
14963
+ if (cached !== undefined)
14964
+ return cached;
14965
+ kept.set(key, false);
14966
+ const el = elements[key];
14967
+ if (!el)
14968
+ return false;
14969
+ const accepts = ACCEPTS[el.type];
14970
+ el.children = el.children.filter((child) => elements[child] !== undefined && (!accepts || accepts.includes(elements[child].type)) && visit(child));
14971
+ const keep = key === rootKey || (GROUPS.has(el.type) ? el.children.length > 0 : el.type !== "Card" || hasContent(el));
14972
+ kept.set(key, keep);
14973
+ return keep;
14974
+ };
14975
+ visit(rootKey);
14976
+ }
14977
+ function buildCard(root, elements, keys) {
14978
+ return card({
14979
+ title: root.props.title ?? undefined,
14980
+ subtitle: root.props.subtitle ?? undefined,
14981
+ imageUrl: root.props.imageUrl ?? undefined,
14982
+ children: keys.map((k) => toChild(k, elements))
14983
+ });
14984
+ }
14985
+ function toCard(spec, options = {}) {
14986
+ const defs = options.components ?? standardComponentDefinitions;
14987
+ if (!spec || typeof spec.root !== "string" || !spec.elements)
14988
+ throw new CardSpecError(["spec needs a root and elements"]);
14989
+ const maxElements = options.maxElements ?? DEFAULT_MAX_ELEMENTS;
14990
+ const { elements, missing, overflow } = materialize(spec, maxElements);
14991
+ if (overflow)
14992
+ throw new CardSpecError([
14993
+ `the spec expands to more than ${maxElements} elements and table rows`
14994
+ ]);
14995
+ let issues = validateProps(elements, defs);
14996
+ if (!issues.length)
14997
+ issues = [
14998
+ ...missing.map((key) => `missing element "${key}"`),
14999
+ ...validateStructure(spec, elements, defs)
15000
+ ];
15001
+ if (!issues.length) {
15002
+ prune(elements, spec.root);
15003
+ if (!hasContent(elements[spec.root]))
15004
+ issues.push("the Card needs a title, an image or at least one child");
15005
+ }
15006
+ if (!issues.length && options.limits)
15007
+ issues = validateLimits(elements, options.limits);
15008
+ if (issues.length)
15009
+ throw new CardSpecError(issues);
15010
+ const root = elements[spec.root];
15011
+ return buildCard(root, elements, root.children);
15012
+ }
15013
+ var schema, displayText, pieChart, seriesChart, standardComponentDefinitions, card = (options) => ({ type: "card", ...options }), text = (content, style) => ({ type: "text", content, style }), image = (url, alt) => ({
15014
+ type: "image",
15015
+ url,
15016
+ alt
15017
+ }), divider = () => ({ type: "divider" }), section = (children) => ({
15018
+ type: "section",
15019
+ children
15020
+ }), field = (label, value) => ({
15021
+ type: "field",
15022
+ label,
15023
+ value
15024
+ }), fields = (children) => ({
15025
+ type: "fields",
15026
+ children
15027
+ }), table = (options) => ({
15028
+ type: "table",
15029
+ ...options
15030
+ }), chart = (options) => ({
15031
+ type: "chart",
15032
+ ...options
15033
+ }), 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);
15034
+ var init_dist5 = __esm(() => {
15035
+ init_dist();
15036
+ init_zod();
15037
+ init_dist();
15038
+ init_dist();
15039
+ schema = defineSchema((s) => ({
15040
+ spec: s.object({
15041
+ root: s.string(),
15042
+ elements: s.record(s.object({
15043
+ type: s.ref("catalog.components"),
15044
+ props: s.propsOf("catalog.components"),
15045
+ children: s.array(s.string()),
15046
+ visible: { ...s.any(), ...s.optional() },
15047
+ repeat: { ...s.any(), ...s.optional() }
15048
+ }))
15049
+ }),
15050
+ catalog: s.object({
15051
+ components: s.map({
15052
+ props: s.zod(),
15053
+ slots: s.array(s.string()),
15054
+ description: s.string(),
15055
+ example: s.any()
15056
+ })
15057
+ })
15058
+ }), {
15059
+ defaultRules: [
15060
+ "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.",
15061
+ "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.",
15062
+ "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.",
15063
+ '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).',
15064
+ "Text content uses markdown: **bold**, _italic_, `code` and [label](https://url). Do not use headings inside Text.",
15065
+ "Field elements MUST be children of a Fields element. Button and LinkButton elements MUST be children of an Actions element.",
15066
+ "Every series in a bar, line or area Chart has exactly one value per category, in category order.",
15067
+ 'Every element MUST include a "children" array. Leaf elements use "children": [].'
15068
+ ]
15069
+ });
15070
+ displayText = union3([string2(), number2()]).transform(String);
15071
+ pieChart = object2({
15072
+ type: literal2("pie"),
15073
+ segments: array2(object2({ label: string2().min(1), value: number2().positive() })).min(1)
15074
+ });
15075
+ seriesChart = object2({
15076
+ type: _enum2(["bar", "line", "area"]),
15077
+ categories: array2(string2().min(1)).min(1),
15078
+ series: array2(object2({ name: string2().min(1), values: array2(number2()) })).min(1),
15079
+ xLabel: string2().nullish(),
15080
+ yLabel: string2().nullish()
15081
+ });
15082
+ standardComponentDefinitions = {
15083
+ Card: {
15084
+ props: object2({
15085
+ title: string2().nullish(),
15086
+ subtitle: string2().nullish(),
15087
+ imageUrl: string2().url().nullish()
15088
+ }),
15089
+ slots: ["default"],
15090
+ description: "Root of a message. Title renders as the card header, subtitle as secondary text.",
15091
+ example: { title: "Weekly deploys", subtitle: "Oct 27 to Nov 2" }
15092
+ },
15093
+ Section: {
15094
+ props: object2({}),
15095
+ slots: ["default"],
15096
+ description: "Groups related elements.",
15097
+ example: {}
15098
+ },
15099
+ Text: {
15100
+ props: object2({
15101
+ content: string2().min(1),
15102
+ style: _enum2(["plain", "bold", "muted"]).nullish()
15103
+ }),
15104
+ slots: [],
15105
+ description: "A paragraph of markdown text. Use muted for footnotes.",
15106
+ example: { content: "Deploys are **up 12%** week over week." }
15107
+ },
15108
+ Fields: {
15109
+ props: object2({}),
15110
+ slots: ["default"],
15111
+ description: "Grid of label and value pairs. Children are Field elements.",
15112
+ example: {}
15113
+ },
15114
+ Field: {
15115
+ props: object2({ label: string2().min(1), value: displayText }),
15116
+ slots: [],
15117
+ description: "One label and value pair inside Fields. Good for KPIs.",
15118
+ example: { label: "Deploys", value: "1,284" }
15119
+ },
15120
+ Table: {
15121
+ props: object2({
15122
+ headers: array2(string2()).min(1),
15123
+ rows: array2(array2(displayText)),
15124
+ align: array2(_enum2(["left", "center", "right"])).nullish(),
15125
+ caption: string2().nullish()
15126
+ }),
15127
+ slots: [],
15128
+ description: "Table for row data. Every row has one cell per header. Right-align numeric columns.",
15129
+ example: {
15130
+ headers: ["Project", "Deploys"],
15131
+ rows: [
15132
+ ["web", "412"],
15133
+ ["api", "203"]
15134
+ ],
15135
+ align: ["left", "right"]
15136
+ }
15137
+ },
15138
+ Chart: {
15139
+ props: object2({
15140
+ title: string2().min(1),
15141
+ chart: union3([pieChart, seriesChart])
15142
+ }),
15143
+ slots: [],
15144
+ description: "Chart. pie for shares of a whole, bar, line or area for series over categories.",
15145
+ example: {
15146
+ title: "Deploys per day",
15147
+ chart: {
15148
+ type: "bar",
15149
+ categories: ["Mon", "Tue", "Wed"],
15150
+ series: [{ name: "Deploys", values: [180, 210, 195] }]
15151
+ }
15152
+ }
15153
+ },
15154
+ Divider: {
15155
+ props: object2({}),
15156
+ slots: [],
15157
+ description: "Separator between groups.",
15158
+ example: {}
15159
+ },
15160
+ Image: {
15161
+ props: object2({ url: string2().url(), alt: string2().min(1) }),
15162
+ slots: [],
15163
+ description: "Image from a public https URL.",
15164
+ example: { url: "https://picsum.photos/600/300", alt: "Preview" }
15165
+ },
15166
+ Actions: {
15167
+ props: object2({}),
15168
+ slots: ["default"],
15169
+ description: "Row of Button and LinkButton elements.",
15170
+ example: {}
15171
+ },
15172
+ Button: {
15173
+ props: object2({
15174
+ id: string2().min(1),
15175
+ label: string2().min(1),
15176
+ style: _enum2(["primary", "danger", "default"]).nullish(),
15177
+ value: string2().nullish()
15178
+ }),
15179
+ slots: [],
15180
+ description: "Interactive button. id is the action id the bot handles with onAction.",
15181
+ example: { id: "approve", label: "Approve", style: "primary" }
15182
+ },
15183
+ LinkButton: {
15184
+ props: object2({ label: string2().min(1), url: string2().url() }),
15185
+ slots: [],
15186
+ description: "Button that opens a URL.",
15187
+ example: { label: "Open dashboard", url: "https://vercel.com" }
15188
+ }
15189
+ };
15190
+ CardSpecError = class extends Error {
15191
+ constructor(issues) {
15192
+ super(issues.join(`
15193
+ `));
15194
+ this.issues = issues;
15195
+ this.name = "CardSpecError";
15196
+ }
15197
+ };
15198
+ ID_KEYS = /* @__PURE__ */ new Set(["id", "key", "uuid"]);
15199
+ ACCEPTS = {
15200
+ Fields: ["Field"],
15201
+ Actions: ["Button", "LinkButton"]
15202
+ };
15203
+ GROUPS = /* @__PURE__ */ new Set(["Fields", "Actions", "Section"]);
15204
+ });
15205
+
15206
+ // src/utils/task-ui-spec.ts
15207
+ var UI_SPEC_MAX_BYTES = 32768, UI_SPEC_MAX_BLOCKS = 45, UI_SPEC_MAX_ACTIONS_ROW_ELEMENTS = 25, UI_SPEC_ACTION_PREFIX = "swarm_ui:", UI_SPEC_ACTION_ID, UI_SPEC_CARD_LIMITS;
15208
+ var init_task_ui_spec2 = __esm(() => {
15209
+ UI_SPEC_ACTION_ID = /^[a-z][a-z0-9_]{0,39}$/;
15210
+ UI_SPEC_CARD_LIMITS = {
15211
+ tables: 1,
15212
+ charts: 2,
15213
+ chartLabel: 20,
15214
+ chartTitle: 50,
15215
+ tableRows: 100,
15216
+ tableColumns: 20
15217
+ };
15218
+ });
15219
+
15220
+ // src/ui-spec/validate.ts
15221
+ function asElement(value) {
15222
+ return value !== null && typeof value === "object" ? value : null;
15223
+ }
15224
+ function elementProps(element) {
15225
+ const props = element.props;
15226
+ return props !== null && typeof props === "object" ? props : {};
15227
+ }
15228
+ function isHttpsUrl(value) {
15229
+ if (typeof value !== "string")
15230
+ return false;
15231
+ try {
15232
+ return new URL(value).protocol === "https:";
15233
+ } catch {
15234
+ return false;
15235
+ }
15236
+ }
15237
+ function renderTaskUiSpec(spec, taskId) {
15238
+ const renderCopy = structuredClone(spec);
15239
+ for (const value of Object.values(renderCopy.elements)) {
15240
+ const element = asElement(value);
15241
+ if (!element || element.type !== "Button")
15242
+ continue;
15243
+ const props = elementProps(element);
15244
+ element.props = { ...props, id: `${UI_SPEC_ACTION_PREFIX}${String(props.id)}`, value: taskId };
15245
+ }
15246
+ let card;
15247
+ try {
15248
+ card = toCard(renderCopy, { limits: UI_SPEC_CARD_LIMITS });
15249
+ } catch (error) {
15250
+ if (error instanceof CardSpecError)
15251
+ return { ok: false, issues: [...error.issues] };
15252
+ throw error;
15253
+ }
15254
+ const blocks = cardToBlockKit2(card);
15255
+ const issues = [];
15256
+ if (blocks.length > UI_SPEC_MAX_BLOCKS) {
15257
+ issues.push(`uiSpec renders as ${blocks.length} Slack blocks; the limit is ${UI_SPEC_MAX_BLOCKS}.`);
15258
+ }
15259
+ for (const block of blocks) {
15260
+ const count = block.elements?.length ?? 0;
15261
+ if (block.type === "actions" && count > UI_SPEC_MAX_ACTIONS_ROW_ELEMENTS) {
15262
+ issues.push(`An Actions row renders ${count} Slack elements; the limit is ${UI_SPEC_MAX_ACTIONS_ROW_ELEMENTS}.`);
15263
+ }
15264
+ }
15265
+ if (issues.length > 0)
15266
+ return { ok: false, issues };
15267
+ return { ok: true, blocks, fallbackText: cardToFallbackText2(card) };
15268
+ }
15269
+ function validateTaskUiSpec(input, { taskId, actionsEnabled }) {
15270
+ const issues = [];
15271
+ const bytes = new TextEncoder().encode(JSON.stringify(input.spec)).length;
15272
+ if (bytes > UI_SPEC_MAX_BYTES) {
15273
+ issues.push(`uiSpec is ${bytes} bytes; the limit is ${UI_SPEC_MAX_BYTES}.`);
15274
+ }
15275
+ for (const [elementId, value] of Object.entries(input.spec.elements)) {
15276
+ const element = asElement(value);
15277
+ if (!element)
15278
+ continue;
15279
+ const props = elementProps(element);
15280
+ const type = typeof element.type === "string" ? element.type : "";
15281
+ const urlProp = Object.hasOwn(URL_PROPS, type) ? URL_PROPS[type] : undefined;
15282
+ if (urlProp) {
15283
+ const url = props[urlProp];
15284
+ if (url !== undefined && url !== null && !isHttpsUrl(url)) {
15285
+ issues.push(`${elementId}.${urlProp} must be an https: URL.`);
15286
+ }
15287
+ }
15288
+ if (type === "Button") {
15289
+ if (!actionsEnabled) {
15290
+ issues.push(`Button ${elementId} needs UI_SPEC_ACTIONS_ENABLED=true; use LinkButton.`);
15291
+ continue;
15292
+ }
15293
+ const id = props.id;
15294
+ const declared = typeof id === "string" && UI_SPEC_ACTION_ID.test(id) && input.actions !== undefined && Object.hasOwn(input.actions, id);
15295
+ if (!declared) {
15296
+ issues.push(`Button ${elementId} names action "${String(id)}", which uiSpec.actions does not declare.`);
15297
+ }
15298
+ }
15299
+ }
15300
+ if (issues.length > 0)
15301
+ return { ok: false, issues };
15302
+ const rendered = renderTaskUiSpec(input.spec, taskId);
15303
+ if (!rendered.ok)
15304
+ return rendered;
15305
+ return {
15306
+ ok: true,
15307
+ spec: input.spec,
15308
+ actions: input.actions,
15309
+ blocks: rendered.blocks,
15310
+ fallbackText: rendered.fallbackText
15311
+ };
15312
+ }
15313
+ var URL_PROPS;
15314
+ var init_validate2 = __esm(() => {
15315
+ init_dist6();
15316
+ init_dist5();
15317
+ init_task_ui_spec2();
15318
+ URL_PROPS = {
15319
+ LinkButton: "url",
15320
+ Image: "url",
15321
+ Card: "imageUrl"
15322
+ };
15323
+ });
15324
+
15325
+ // src/ui-spec/slack.ts
15326
+ function taskUiSpecSlackBlocks(stored, taskId) {
15327
+ const rendered = renderTaskUiSpec(stored.spec, taskId);
15328
+ if (rendered.ok)
15329
+ return rendered.blocks;
15330
+ console.warn(`[ui-spec] stored spec for task ${taskId} no longer renders: ${rendered.issues.join(" | ")}`);
15331
+ return [];
15332
+ }
15333
+ var init_slack = __esm(() => {
15334
+ init_validate2();
15335
+ });
15336
+
15337
+ // node_modules/@desplega.ai/business-use/dist/index.js
15338
+ function initialize(options) {
15339
+ if (_state.initialized) {
15340
+ log2.warn("SDK already initialized");
15341
+ return;
15342
+ }
15343
+ try {
15344
+ const finalApiKey = options?.apiKey ?? process.env.BUSINESS_USE_API_KEY;
15345
+ if (!finalApiKey) {
15346
+ log2.error("API key not provided. Set apiKey parameter or BUSINESS_USE_API_KEY environment variable");
15347
+ return;
15348
+ }
15349
+ const finalUrl = options?.url ?? process.env.BUSINESS_USE_URL ?? "http://localhost:13370";
15350
+ const baseUrl = finalUrl.replace(/\/$/, "");
15351
+ const batchSize = options?.batchSize ?? 100;
15352
+ const batchInterval = options?.batchInterval ?? 5000;
15353
+ const maxQueueSize = options?.maxQueueSize ?? batchSize * 10;
15354
+ if (!_checkConnection(finalApiKey, baseUrl)) {
15355
+ log2.error("Connection check failed - SDK entering no-op mode");
15356
+ return;
15357
+ }
15358
+ _state.batchProcessor = new BatchProcessor({
15359
+ apiKey: finalApiKey,
15360
+ baseUrl,
15361
+ batchSize,
15362
+ batchInterval,
15363
+ maxQueueSize
15364
+ });
15365
+ _state.initialized = true;
15366
+ log2.info("Business-Use SDK initialized successfully");
15367
+ } catch (error) {
15368
+ log2.error(`Failed to initialize SDK: ${error}`);
15369
+ _state.initialized = false;
15370
+ }
15371
+ }
15372
+ function ensure2(options) {
15373
+ _enqueueEvent({
15374
+ type: options.validator ? "assert" : "act",
15375
+ id: options.id,
15376
+ flow: options.flow,
15377
+ runId: options.runId,
15378
+ data: options.data,
15379
+ filter: options.filter,
15380
+ depIds: options.depIds,
15381
+ description: options.description,
15382
+ validator: options.validator,
15383
+ conditions: options.conditions,
15384
+ additional_meta: options.additional_meta
15385
+ });
15386
+ }
15387
+ function _enqueueEvent(options) {
15388
+ if (!_state.initialized || !_state.batchProcessor) {
15389
+ return;
15390
+ }
15391
+ try {
15392
+ if (typeof options.runId === "function" && isAsyncFunction(options.runId)) {
15393
+ log2.error(`Event ${options.id}: runId cannot be an async function`);
15394
+ return;
15395
+ }
15396
+ if (options.filter !== undefined && typeof options.filter === "function" && isAsyncFunction(options.filter)) {
15397
+ log2.error(`Event ${options.id}: filter cannot be an async function`);
15398
+ return;
15399
+ }
15400
+ if (options.depIds !== undefined && typeof options.depIds === "function" && isAsyncFunction(options.depIds)) {
15401
+ log2.error(`Event ${options.id}: depIds cannot be an async function`);
15402
+ return;
15403
+ }
15404
+ if (options.validator !== undefined && isAsyncFunction(options.validator)) {
15405
+ log2.error(`Event ${options.id}: validator cannot be an async function`);
15406
+ return;
15407
+ }
15408
+ if (options.conditions !== undefined && typeof options.conditions === "function" && isAsyncFunction(options.conditions)) {
15409
+ log2.error(`Event ${options.id}: conditions cannot be an async function`);
15410
+ return;
15411
+ }
15412
+ const event = {
15413
+ type: options.type,
15414
+ id: options.id,
15415
+ flow: options.flow,
15416
+ run_id: options.runId,
15417
+ data: options.data,
15418
+ filter: options.filter,
15419
+ dep_ids: options.depIds,
15420
+ description: options.description,
15421
+ validator: options.validator,
15422
+ conditions: options.conditions,
15423
+ additional_meta: options.additional_meta
15424
+ };
15425
+ _state.batchProcessor.enqueue(event);
15426
+ } catch (error) {
15427
+ log2.error(`Failed to enqueue event ${options.id}: ${error}`);
15428
+ }
15429
+ }
15430
+ function _checkConnection(_apiKey, _baseUrl) {
15431
+ try {
15432
+ log2.info("Connection check successful (deferred to first batch)");
15433
+ return true;
15434
+ } catch (error) {
15435
+ log2.error(`Connection check failed: ${error}`);
15436
+ return false;
15437
+ }
15438
+ }
15439
+ function isAsyncFunction(fn) {
15440
+ return fn.constructor.name === "AsyncFunction";
15441
+ }
15442
+ var log, BatchProcessor = class {
15443
+ _apiKey;
15444
+ _baseUrl;
15445
+ _batchSize;
15446
+ _batchInterval;
15447
+ _maxQueueSize;
15448
+ _queue = [];
15449
+ _timer = null;
15450
+ _isShuttingDown = false;
15451
+ constructor(options) {
13113
15452
  this._apiKey = options.apiKey;
13114
15453
  this._baseUrl = options.baseUrl.replace(/\/$/, "");
13115
15454
  this._batchSize = options.batchSize;
@@ -13349,7 +15688,7 @@ var log, BatchProcessor = class {
13349
15688
  initialized = false;
13350
15689
  batchProcessor = null;
13351
15690
  }, _state, package_default, version;
13352
- var init_dist = __esm(() => {
15691
+ var init_dist2 = __esm(() => {
13353
15692
  log = {
13354
15693
  debug: (msg) => console.log(`[business-use] [${(/* @__PURE__ */ new Date()).toISOString()}] [DEBUG] ${msg}`),
13355
15694
  info: (msg) => console.log(`[business-use] [${(/* @__PURE__ */ new Date()).toISOString()}] [INFO] ${msg}`),
@@ -13442,9 +15781,9 @@ var ensure = (options) => {
13442
15781
  ensure2({ ...options, data: scrubObject(options.data) });
13443
15782
  };
13444
15783
  var init_business_use = __esm(() => {
13445
- init_dist();
15784
+ init_dist2();
13446
15785
  init_secret_scrubber();
13447
- init_dist();
15786
+ init_dist2();
13448
15787
  });
13449
15788
 
13450
15789
  // src/slack/closure.ts
@@ -13483,7 +15822,25 @@ function closureState(ask, closure, now, settleSec, timeoutMin) {
13483
15822
  return idleMin >= timeoutMin ? "timedOut" : "open";
13484
15823
  }
13485
15824
  var init_closure = __esm(() => {
13486
- init_types4();
15825
+ init_types5();
15826
+ });
15827
+
15828
+ // src/ui-spec/fallback.ts
15829
+ async function withUiSpecFallback(taskId, body) {
15830
+ if (!isEnvFlagEnabled("UI_SPEC_ENABLED", false))
15831
+ return body;
15832
+ const stored = await getTaskUiSpec(taskId);
15833
+ if (!stored?.fallbackText)
15834
+ return body;
15835
+ const fallbackText = scrubSecrets(stored.fallbackText);
15836
+ return body ? `${body}
15837
+
15838
+ ${fallbackText}` : fallbackText;
15839
+ }
15840
+ var init_fallback = __esm(() => {
15841
+ init_task_ui_spec();
15842
+ init_env_flag();
15843
+ init_secret_scrubber();
13487
15844
  });
13488
15845
 
13489
15846
  // src/slack/task-attachments.ts
@@ -13535,7 +15892,7 @@ async function sendInlineTaskOutput(task) {
13535
15892
  const chunks = formatInlineCompletionOutputChunks({
13536
15893
  agentName: agent.name,
13537
15894
  taskId: task.id,
13538
- output: slackTaskOutput(task) ?? ""
15895
+ output: await withUiSpecFallback(task.id, slackTaskOutput(task) ?? "")
13539
15896
  });
13540
15897
  try {
13541
15898
  for (let i = 0;i < chunks.length; i += MAX_INLINE_OUTPUT_BLOCKS_PER_MESSAGE) {
@@ -13579,7 +15936,7 @@ async function sendTaskResponse(task) {
13579
15936
  const agentName = agent.name;
13580
15937
  try {
13581
15938
  if (task.status === "completed") {
13582
- const output = slackTaskOutput(task) || "Task completed.";
15939
+ const output = await withUiSpecFallback(task.id, slackTaskOutput(task) || "Task completed.");
13583
15940
  const slackOutput = markdownToSlack(output);
13584
15941
  const attachmentsBlock = formatAttachmentsBlockForSlack(await getSlackOutputAttachments(task.id));
13585
15942
  const body = slackOutput + attachmentsBlock;
@@ -13825,6 +16182,7 @@ function getAgentEmoji(agent) {
13825
16182
  var isDev, MAX_INLINE_OUTPUT_BLOCKS_PER_MESSAGE = 10;
13826
16183
  var init_responses = __esm(() => {
13827
16184
  init_db4();
16185
+ init_fallback();
13828
16186
  init_app3();
13829
16187
  init_blocks();
13830
16188
  init_reaction_shortcode();
@@ -13860,12 +16218,12 @@ function withTimeout(promise, ms) {
13860
16218
  return Promise.race([promise, timeout]).finally(() => clearTimeout(timer));
13861
16219
  }
13862
16220
  function statusTransport(client) {
13863
- if (!(client instanceof import_bolt3.webApi.WebClient))
16221
+ if (!(client instanceof import_bolt5.webApi.WebClient))
13864
16222
  return client;
13865
16223
  let transport = transports.get(client);
13866
16224
  if (!transport) {
13867
16225
  const timeout = Math.max(callTimeoutMs - TRANSPORT_MARGIN_MS, 1);
13868
- transport = new import_bolt3.webApi.WebClient(client.token ?? process.env.SLACK_BOT_TOKEN, {
16226
+ transport = new import_bolt5.webApi.WebClient(client.token ?? process.env.SLACK_BOT_TOKEN, {
13869
16227
  slackApiUrl: client.slackApiUrl,
13870
16228
  retryConfig: { retries: 0 },
13871
16229
  rejectRateLimitedCalls: true,
@@ -14099,13 +16457,13 @@ function beginSlackStatusTick() {
14099
16457
  }
14100
16458
  };
14101
16459
  }
14102
- var import_bolt3, REFRESH_MS, DEFAULT_CALL_TIMEOUT_MS = 8000, TRANSPORT_MARGIN_MS = 500, callTimeoutMs, RETRY_BASE_MS = 30000, RETRY_MAX_MS, UNAVAILABLE_COOLDOWN_MS, CALLS_PER_TICK = 8, ORPHAN_GRACE_MS, WORKSPACE_ERRORS, TRANSIENT_ERRORS, threads, keyTails, warned, unavailableUntil = 0, CallTimeoutError, transports;
16460
+ var import_bolt5, REFRESH_MS, DEFAULT_CALL_TIMEOUT_MS = 8000, TRANSPORT_MARGIN_MS = 500, callTimeoutMs, RETRY_BASE_MS = 30000, RETRY_MAX_MS, UNAVAILABLE_COOLDOWN_MS, CALLS_PER_TICK = 8, ORPHAN_GRACE_MS, WORKSPACE_ERRORS, TRANSIENT_ERRORS, threads, keyTails, warned, unavailableUntil = 0, CallTimeoutError, transports;
14103
16461
  var init_session_status = __esm(() => {
14104
16462
  init_db4();
14105
- init_types4();
16463
+ init_types5();
14106
16464
  init_secret_scrubber();
14107
16465
  init_app3();
14108
- import_bolt3 = __toESM(require_dist5(), 1);
16466
+ import_bolt5 = __toESM(require_dist5(), 1);
14109
16467
  REFRESH_MS = 30 * 60000;
14110
16468
  callTimeoutMs = DEFAULT_CALL_TIMEOUT_MS;
14111
16469
  RETRY_MAX_MS = 10 * 60000;
@@ -14266,7 +16624,8 @@ async function clearAssistantStatus(client, channelId, threadTs, statusBudget) {
14266
16624
  });
14267
16625
  }
14268
16626
  function slackTreeStallMinutes() {
14269
- return Number(process.env.SLACK_TREE_STALL_MIN) || 15;
16627
+ const minutes = Number(process.env.SLACK_TREE_STALL_MIN);
16628
+ return Number.isFinite(minutes) && minutes > 0 ? minutes : 15;
14270
16629
  }
14271
16630
  function isStalledMember(task, now) {
14272
16631
  if (task.status !== "in_progress")
@@ -14863,6 +17222,34 @@ function attachmentCaption(attachments) {
14863
17222
  const destination = url.replace(/[\s\\<>|]/g, encodeURIComponent);
14864
17223
  return `\uD83D\uDCCE <${destination}|${label}>`;
14865
17224
  }
17225
+ async function outcomeUiSpec(task) {
17226
+ if (!isEnvFlagEnabled("UI_SPEC_ENABLED", false))
17227
+ return null;
17228
+ const stored = await getTaskUiSpec(task.id);
17229
+ if (!stored)
17230
+ return null;
17231
+ return { blocks: taskUiSpecSlackBlocks(stored, task.id), fallbackText: stored.fallbackText };
17232
+ }
17233
+ async function withUiSpecBlockFallback(uiSpec, taskId, send) {
17234
+ if (!uiSpec?.blocks.length)
17235
+ return await send(false);
17236
+ try {
17237
+ return await send(true);
17238
+ } catch (error) {
17239
+ const code = slackErrorCode2(error);
17240
+ if (!code || !UI_SPEC_BLOCK_REJECTION_CODES.has(code))
17241
+ throw error;
17242
+ console.warn(`[Slack] ${code} for the card of task ${taskId}; retrying with its fallback text`);
17243
+ return await send(false);
17244
+ }
17245
+ }
17246
+ function withUiSpecFallbackText(presentation, uiSpec, withCard) {
17247
+ if (!uiSpec || withCard || !uiSpec.fallbackText)
17248
+ return presentation;
17249
+ return `${presentation}
17250
+
17251
+ ${uiSpec.fallbackText}`;
17252
+ }
14866
17253
  async function outcomeCaptionBlocks(task, content) {
14867
17254
  const moreUrl = getTaskUrl(task.id);
14868
17255
  const sources = taskCitationSourceGroups(content, await getTaskCitations(task.id)).map((group) => buildCaptionBlock(group.items, { heading: group.heading, moreUrl }));
@@ -14972,6 +17359,8 @@ async function streamOutcomeCard(task, tree, options) {
14972
17359
  ...await outcomeCaptionBlocks(task, content),
14973
17360
  ...await outcomeFooter(task, tasks, duration)
14974
17361
  ];
17362
+ const uiSpec = await outcomeUiSpec(task);
17363
+ const blocksFor = (withCard) => withCard && uiSpec ? [...uiSpec.blocks, ...captions] : captions;
14975
17364
  const startPayload = {
14976
17365
  channel: task.slackChannelId,
14977
17366
  thread_ts: task.slackThreadTs,
@@ -15017,12 +17406,15 @@ async function streamOutcomeCard(task, tree, options) {
15017
17406
  started = await callSlackWithRetry2(app.client, "chat.startStream", startPayload);
15018
17407
  } catch (error) {
15019
17408
  console.error(`[Slack] chat.startStream failed for task ${task.id}; falling back to chat.postMessage:`, error);
15020
- started = await callSlackWithRetry2(app.client, "chat.postMessage", {
15021
- channel: task.slackChannelId,
15022
- thread_ts: task.slackThreadTs,
15023
- text: presentation,
15024
- blocks: [{ type: "markdown", text: presentation }, ...captions],
15025
- ...persona
17409
+ started = await withUiSpecBlockFallback(uiSpec, task.id, (withCard) => {
17410
+ const text = withUiSpecFallbackText(presentation, uiSpec, withCard);
17411
+ return callSlackWithRetry2(app.client, "chat.postMessage", {
17412
+ channel: task.slackChannelId,
17413
+ thread_ts: task.slackThreadTs,
17414
+ text,
17415
+ blocks: [{ type: "markdown", text }, ...blocksFor(withCard)],
17416
+ ...persona
17417
+ });
15026
17418
  });
15027
17419
  deliveredViaFallback = true;
15028
17420
  }
@@ -15039,21 +17431,27 @@ async function streamOutcomeCard(task, tree, options) {
15039
17431
  }
15040
17432
  if (!deliveredViaFallback) {
15041
17433
  try {
15042
- await callSlackWithRetry2(app.client, "chat.stopStream", {
17434
+ await withUiSpecBlockFallback(uiSpec, task.id, (withCard) => callSlackWithRetry2(app.client, "chat.stopStream", {
15043
17435
  channel: task.slackChannelId,
15044
17436
  ts: outcome.ts,
15045
- blocks: captions
15046
- });
17437
+ ...uiSpec?.fallbackText && !withCard ? { markdown_text: `
17438
+
17439
+ ${uiSpec.fallbackText}` } : {},
17440
+ blocks: blocksFor(withCard)
17441
+ }));
15047
17442
  } catch (error) {
15048
17443
  if (!isStreamAlreadyStopped(error))
15049
17444
  throw error;
15050
17445
  }
15051
17446
  if (!streamedFreshContent) {
15052
- await callSlackWithRetry2(app.client, "chat.update", {
15053
- channel: task.slackChannelId,
15054
- ts: outcome.ts,
15055
- text: presentation,
15056
- blocks: [{ type: "markdown", text: presentation }, ...captions]
17447
+ await withUiSpecBlockFallback(uiSpec, task.id, (withCard) => {
17448
+ const text = withUiSpecFallbackText(presentation, uiSpec, withCard);
17449
+ return callSlackWithRetry2(app.client, "chat.update", {
17450
+ channel: task.slackChannelId,
17451
+ ts: outcome.ts,
17452
+ text,
17453
+ blocks: [{ type: "markdown", text }, ...blocksFor(withCard)]
17454
+ });
15057
17455
  });
15058
17456
  }
15059
17457
  }
@@ -15074,7 +17472,15 @@ async function resolvedDeferralContent(wake) {
15074
17472
  const content = await outcomeContent(wake, wake.slackReplySent);
15075
17473
  const presentation = await outcomePresentation(wake, content);
15076
17474
  const captions = await outcomeCaptionBlocks(wake, content);
15077
- return { text: presentation, blocks: [{ type: "markdown", text: presentation }, ...captions] };
17475
+ const uiSpec = await outcomeUiSpec(wake);
17476
+ return {
17477
+ uiSpec,
17478
+ build: (withCard) => {
17479
+ const text = withUiSpecFallbackText(presentation, uiSpec, withCard);
17480
+ const card = withCard && uiSpec ? uiSpec.blocks : [];
17481
+ return { text, blocks: [{ type: "markdown", text }, ...card, ...captions] };
17482
+ }
17483
+ };
15078
17484
  }
15079
17485
  async function isAnsweredByDeferralCard(task, threadTasks) {
15080
17486
  const seen = new Set;
@@ -15125,11 +17531,11 @@ async function refreshResolvedDeferralCards() {
15125
17531
  if (!wake)
15126
17532
  continue;
15127
17533
  const content = await resolvedDeferralContent(wake);
15128
- await callSlackWithRetry2(app.client, "chat.update", {
17534
+ await withUiSpecBlockFallback(content.uiSpec, wake.id, (withCard) => callSlackWithRetry2(app.client, "chat.update", {
15129
17535
  channel: card.channelId,
15130
17536
  ts: card.ts,
15131
- ...content
15132
- });
17537
+ ...content.build(withCard)
17538
+ }));
15133
17539
  if (isDeferredTask(wake)) {
15134
17540
  await updateSlackMessageRecord2(card.id, {});
15135
17541
  } else {
@@ -15516,12 +17922,14 @@ async function renderDirtyThreads() {
15516
17922
  if (touched.wakeTouched)
15517
17923
  await refreshResolvedDeferralCards();
15518
17924
  }
15519
- var TREE_UPDATE_DEBOUNCE_MS = 500, TREE_UPDATE_MIN_INTERVAL_MS = 3000, MAX_SLACK_RETRIES = 3, MAX_RETRY_DELAY_MS = 30000, MAX_TITLE_LENGTH = 72, MAX_OUTCOME_MARKDOWN_LENGTH = 12000, MAX_TREE_NODE_LINE_LENGTH = 1000, MAX_TREE_PREFIX_LENGTH = 120, MAX_TREE_PROGRESS_LENGTH = 60, CHILD_CARDS_PER_TICK = 3, CHILD_CARDS_PER_ASK = 10, CONCLUSION_DIGEST_LENGTH = 300, TREE_INDENT, FIGURE_SPACE = " ", SLACK_RENDER_METADATA_EVENT = "agent_swarm_render_v2", treeCreationPromises, pendingTreeUpdates, treeUpdateTails, lastTreeText, lastTreeUpdateAt, cachedTeamId, OUTCOME_DELIVERY_MAX_ATTEMPTS = 5, OUTCOME_DELIVERY_BASE_DELAY_MS = 30000, OUTCOME_DELIVERY_MAX_DELAY_MS, outcomeDeliveryNextAttemptAt, outcomeReservedWithoutAttempt, LINE_START_BLOCK, TRANSIENT_SLACK_ERROR_CODES, DEFERRAL_REFRESH_MAX_ATTEMPTS = 5, deferralRefreshAttempts, SLACK_RENDER_TASK_EVENTS, DIRTY_FLUSH_DEBOUNCE_MS = 500, DIRTY_REVISIT_MS = 3000, dirtyTaskIds, dirtyThreads, renderInFlight = null, renderEventsSubscribed = false, dirtyFlushTimer = null, dirtyFlushAt = 0;
17925
+ var TREE_UPDATE_DEBOUNCE_MS = 500, TREE_UPDATE_MIN_INTERVAL_MS = 3000, MAX_SLACK_RETRIES = 3, MAX_RETRY_DELAY_MS = 30000, MAX_TITLE_LENGTH = 72, MAX_OUTCOME_MARKDOWN_LENGTH = 12000, MAX_TREE_NODE_LINE_LENGTH = 1000, MAX_TREE_PREFIX_LENGTH = 120, MAX_TREE_PROGRESS_LENGTH = 60, CHILD_CARDS_PER_TICK = 3, CHILD_CARDS_PER_ASK = 10, CONCLUSION_DIGEST_LENGTH = 300, TREE_INDENT, FIGURE_SPACE = " ", SLACK_RENDER_METADATA_EVENT = "agent_swarm_render_v2", treeCreationPromises, pendingTreeUpdates, treeUpdateTails, lastTreeText, lastTreeUpdateAt, cachedTeamId, OUTCOME_DELIVERY_MAX_ATTEMPTS = 5, OUTCOME_DELIVERY_BASE_DELAY_MS = 30000, OUTCOME_DELIVERY_MAX_DELAY_MS, outcomeDeliveryNextAttemptAt, outcomeReservedWithoutAttempt, LINE_START_BLOCK, UI_SPEC_BLOCK_REJECTION_CODES, TRANSIENT_SLACK_ERROR_CODES, DEFERRAL_REFRESH_MAX_ATTEMPTS = 5, deferralRefreshAttempts, SLACK_RENDER_TASK_EVENTS, DIRTY_FLUSH_DEBOUNCE_MS = 500, DIRTY_REVISIT_MS = 3000, dirtyTaskIds, dirtyThreads, renderInFlight = null, renderEventsSubscribed = false, dirtyFlushTimer = null, dirtyFlushAt = 0;
15520
17926
  var init_render_v2 = __esm(() => {
15521
17927
  init_db4();
15522
17928
  init_slack_trees();
15523
17929
  init_task_citations2();
17930
+ init_task_ui_spec();
15524
17931
  init_context_key();
17932
+ init_slack();
15525
17933
  init_business_use();
15526
17934
  init_env_flag();
15527
17935
  init_secret_scrubber();
@@ -15547,6 +17955,11 @@ var init_render_v2 = __esm(() => {
15547
17955
  outcomeDeliveryNextAttemptAt = new Map;
15548
17956
  outcomeReservedWithoutAttempt = new Set;
15549
17957
  LINE_START_BLOCK = /^(?:`{3}|~{3}|[-*+]\s|\d+[.)]\s|>|#{1,6}\s|\||(?:-{3,}|\*{3,}|_{3,})[ \t]*(?:\r?\n|$)|(?: {4}|\t))/;
17958
+ UI_SPEC_BLOCK_REJECTION_CODES = new Set([
17959
+ "invalid_blocks",
17960
+ "invalid_blocks_format",
17961
+ "msg_blocks_too_long"
17962
+ ]);
15550
17963
  TRANSIENT_SLACK_ERROR_CODES = new Set([
15551
17964
  "ratelimited",
15552
17965
  "rate_limited",
@@ -16285,6 +18698,9 @@ function stopSocketWatchdog() {
16285
18698
  function getSlackApp2() {
16286
18699
  return app;
16287
18700
  }
18701
+ function getSlackHttpReceiver2() {
18702
+ return httpReceiver;
18703
+ }
16288
18704
  async function initSlackApp2() {
16289
18705
  if (initialized2) {
16290
18706
  console.log("[Slack] Already initialized, skipping");
@@ -16303,61 +18719,76 @@ async function initSlackApp2() {
16303
18719
  console.log(`[Slack] Missing ${config.missingCredentials.join(" or ")} for ${config.mode} mode, Slack integration disabled`);
16304
18720
  return null;
16305
18721
  }
16306
- if (config.mode === "http") {
16307
- console.error("[Slack] HTTP mode is configured but unavailable until the HTTP receiver is installed");
16308
- return null;
16309
- }
16310
18722
  const botToken = process.env.SLACK_BOT_TOKEN;
16311
- const appToken = process.env.SLACK_APP_TOKEN;
16312
- const socketModeBlockReason = getSlackSocketModeBlockReason(process.env);
16313
- if (socketModeBlockReason) {
16314
- console.error(`[Slack] SOCKET MODE BLOCKED: ${socketModeBlockReason}. Set ${SLACK_DEV_SOCKET_MODE_OPT_IN}=true to opt in explicitly.`);
16315
- return null;
18723
+ if (config.mode === "socket") {
18724
+ const socketModeBlockReason = getSlackSocketModeBlockReason(process.env);
18725
+ if (socketModeBlockReason) {
18726
+ console.error(`[Slack] SOCKET MODE BLOCKED: ${socketModeBlockReason}. Set ${SLACK_DEV_SOCKET_MODE_OPT_IN}=true to opt in explicitly.`);
18727
+ return null;
18728
+ }
16316
18729
  }
16317
18730
  installSlackEgressScrub();
16318
18731
  installSlackExternalChannelGuard();
16319
18732
  const slackApiUrl = process.env.SLACK_API_URL;
16320
18733
  const clientOptions = slackApiUrl ? { slackApiUrl } : undefined;
16321
- const logLevel = getNodeEnv() === "development" ? import_bolt4.LogLevel.DEBUG : import_bolt4.LogLevel.INFO;
16322
- receiver = new import_bolt4.SocketModeReceiver({
16323
- appToken,
16324
- logLevel,
16325
- installerOptions: clientOptions ? { clientOptions } : {}
16326
- });
16327
- trackConnectionState(receiver);
16328
- socketFence = fenceSocketModeClient(receiver.client);
16329
- app = new import_bolt4.App({
16330
- token: botToken,
16331
- receiver,
16332
- socketMode: true,
16333
- logLevel,
16334
- deferInitialization: true,
16335
- ...clientOptions ? { clientOptions } : {}
16336
- });
16337
- inboundDrain = installSocketAckRecovery(receiver.client, app);
16338
- const authClient = app.client;
18734
+ const logLevel = getNodeEnv() === "development" ? import_bolt6.LogLevel.DEBUG : import_bolt6.LogLevel.INFO;
18735
+ if (config.mode === "http") {
18736
+ httpReceiver = new SwarmHttpReceiver(() => void inboundDrain?.wake());
18737
+ app = new import_bolt6.App({
18738
+ token: botToken,
18739
+ receiver: httpReceiver,
18740
+ logLevel,
18741
+ ignoreSelf: false,
18742
+ deferInitialization: true,
18743
+ ...clientOptions ? { clientOptions } : {}
18744
+ });
18745
+ inboundDrain = createBoltInboundDrain(app);
18746
+ } else {
18747
+ const appToken = process.env.SLACK_APP_TOKEN;
18748
+ receiver = new import_bolt6.SocketModeReceiver({
18749
+ appToken,
18750
+ logLevel,
18751
+ installerOptions: clientOptions ? { clientOptions } : {}
18752
+ });
18753
+ trackConnectionState(receiver);
18754
+ socketFence = fenceSocketModeClient(receiver.client);
18755
+ app = new import_bolt6.App({
18756
+ token: botToken,
18757
+ receiver,
18758
+ socketMode: true,
18759
+ logLevel,
18760
+ deferInitialization: true,
18761
+ ...clientOptions ? { clientOptions } : {}
18762
+ });
18763
+ inboundDrain = installSocketAckRecovery(receiver.client, app);
18764
+ }
18765
+ const created = app;
18766
+ const authClient = created.client;
16339
18767
  const enterpriseInstall = isSlackEnterpriseInstall();
16340
18768
  setSlackWorkspaceIdentitySource(() => resolveSlackIdentity(authClient, enterpriseInstall));
16341
- installSocketWorkspaceGate(receiver.client);
18769
+ if (receiver)
18770
+ installSocketWorkspaceGate(receiver.client);
16342
18771
  initialized2 = true;
16343
- app.use(slackInboundOutcomeMiddleware());
16344
- const { registerMessageHandler } = await import("./handlers-anrr3py9.js");
16345
- const { registerCommandHandler } = await import("./commands-wn9q06qr.js");
16346
- const { registerActionHandlers } = await import("./actions-ewz7bp4g.js");
16347
- const { registerWorkObjectHandlers } = await import("./work-objects-qcxzg61c.js");
16348
- registerMessageHandler(app);
16349
- registerCommandHandler(app);
16350
- registerActionHandlers(app);
16351
- registerWorkObjectHandlers(app);
16352
- const { createAssistant } = await import("./assistant-c47rfe77.js");
16353
- app.assistant(createAssistant());
16354
- const { isBlockExternalEnabled, scanExternalChannelsOnBoot } = await import("./external-channel-ts2fwqh0.js");
18772
+ created.use(slackInboundOutcomeMiddleware(config.mode === "http" ? "http" : "socket"));
18773
+ if (config.mode === "http")
18774
+ created.use(ignoreSelfAsIgnored);
18775
+ const { registerMessageHandler } = await import("./handlers-yzy0c87x.js");
18776
+ const { registerCommandHandler } = await import("./commands-gwea8z5p.js");
18777
+ const { registerActionHandlers } = await import("./actions-b9qgrmeq.js");
18778
+ const { registerWorkObjectHandlers } = await import("./work-objects-4aghh73z.js");
18779
+ registerMessageHandler(created);
18780
+ registerCommandHandler(created);
18781
+ registerActionHandlers(created);
18782
+ registerWorkObjectHandlers(created);
18783
+ const { createAssistant } = await import("./assistant-2cgfxsgk.js");
18784
+ created.assistant(createAssistant());
18785
+ const { isBlockExternalEnabled, scanExternalChannelsOnBoot } = await import("./external-channel-1ac6t56s.js");
16355
18786
  if (isBlockExternalEnabled()) {
16356
- scanExternalChannelsOnBoot(app.client).catch((error) => {
18787
+ scanExternalChannelsOnBoot(created.client).catch((error) => {
16357
18788
  console.error("[Slack] External channel boot scan failed:", error);
16358
18789
  });
16359
18790
  }
16360
- return app;
18791
+ return created;
16361
18792
  }
16362
18793
  async function startSlackApp2() {
16363
18794
  const generation = lifecycleGeneration;
@@ -16373,21 +18804,32 @@ async function startSlackApp2() {
16373
18804
  if (!verified) {
16374
18805
  const delay = scheduleStartRetry();
16375
18806
  setSlackConnectionState("disconnected");
16376
- console.error(`[Slack] Socket Mode not started: this swarm's workspace is unknown. Retrying in ${seconds(delay)}s`);
18807
+ console.error(`[Slack] ${httpReceiver ? "HTTP receiver" : "Socket Mode"} not started: this swarm's workspace is unknown. Retrying in ${seconds(delay)}s`);
16377
18808
  return false;
16378
18809
  }
16379
18810
  startRetryAttempt = 0;
16380
- startSocketWatchdog();
16381
- const { isSlackRenderV2Enabled } = await import("./render-v2-1gfpd8rj.js");
18811
+ if (!httpReceiver)
18812
+ startSocketWatchdog();
18813
+ const { isSlackRenderV2Enabled } = await import("./render-v2-nx20t3rb.js");
16382
18814
  if (isSlackRenderV2Enabled())
16383
18815
  await ensureSlackRenderV2Activation2();
16384
18816
  await recoverSlackInboundAfterRestart();
16385
18817
  if (generation !== lifecycleGeneration)
16386
18818
  return false;
18819
+ httpReceiver?.markReady();
16387
18820
  await current.start();
16388
18821
  if (generation !== lifecycleGeneration)
16389
18822
  return false;
16390
- console.log("[Slack] Bot connected via Socket Mode");
18823
+ if (httpReceiver) {
18824
+ setSlackConnectionState("connected");
18825
+ console.log("[Slack] Bot ready via HTTP receiver");
18826
+ } else {
18827
+ console.log("[Slack] Bot connected via Socket Mode");
18828
+ }
18829
+ const { restoreBufferedSlackMessages } = await import("./thread-buffer-a1re2r9r.js");
18830
+ await restoreBufferedSlackMessages().catch((error) => {
18831
+ console.error("[Slack] Failed to restore buffered thread messages:", error);
18832
+ });
16391
18833
  inboundDrain?.wake();
16392
18834
  await emitBuiltInIntegrationConnectedOnce2("slack");
16393
18835
  if (generation !== lifecycleGeneration)
@@ -16400,7 +18842,7 @@ async function startSlackApp2() {
16400
18842
  async function verifySlackIdentity(current) {
16401
18843
  if (!await getSlackWorkspaceIdentity())
16402
18844
  return false;
16403
- if (boltInitialized)
18845
+ if (boltInitializedApp === current)
16404
18846
  return true;
16405
18847
  try {
16406
18848
  await current.init();
@@ -16409,7 +18851,7 @@ async function verifySlackIdentity(current) {
16409
18851
  console.error(`[Slack] Bolt initialization failed: ${message}`);
16410
18852
  return false;
16411
18853
  }
16412
- boltInitialized = true;
18854
+ boltInitializedApp = current;
16413
18855
  return true;
16414
18856
  }
16415
18857
  function clearStartRetry() {
@@ -16478,20 +18920,21 @@ function detachSlackApp() {
16478
18920
  lifecycleGeneration += 1;
16479
18921
  clearStartRetry();
16480
18922
  startRetryAttempt = 0;
16481
- boltInitialized = false;
18923
+ boltInitializedApp = null;
16482
18924
  stopTaskWatcher();
16483
18925
  inboundDrain?.stop();
16484
18926
  inboundDrain = null;
16485
18927
  const detached = app;
16486
18928
  app = null;
16487
18929
  receiver = null;
18930
+ httpReceiver = null;
16488
18931
  setSlackWorkspaceIdentitySource(null);
16489
18932
  lastSocketActivityAt = null;
16490
18933
  setSlackConnectionState("disconnected");
16491
18934
  initialized2 = false;
16492
18935
  return detached;
16493
18936
  }
16494
- var import_bolt4, app = null, receiver = null, initialized2 = false, inboundDrain = null, socketFence = null, lifecycleGeneration = 0, lastSocketActivityAt = null, DEFAULT_START_RETRY_DELAYS_MS, startRetryDelaysMs, startRetryTimer = null, startRetryAttempt = 0, boltInitialized = false, SOCKET_EVENT_STATES, SLACK_SOCKET_WATCHDOG_DEFAULTS, watchdogTimer = null, watchdogOptions;
18937
+ var import_bolt6, app = null, receiver = null, httpReceiver = null, initialized2 = false, inboundDrain = null, socketFence = null, lifecycleGeneration = 0, lastSocketActivityAt = null, DEFAULT_START_RETRY_DELAYS_MS, startRetryDelaysMs, startRetryTimer = null, startRetryAttempt = 0, boltInitializedApp = null, SOCKET_EVENT_STATES, SLACK_SOCKET_WATCHDOG_DEFAULTS, watchdogTimer = null, watchdogOptions;
16495
18938
  var init_app3 = __esm(() => {
16496
18939
  init_db4();
16497
18940
  init_node_env();
@@ -16500,6 +18943,7 @@ var init_app3 = __esm(() => {
16500
18943
  init_connection_state();
16501
18944
  init_egress_scrub();
16502
18945
  init_external_channel_egress();
18946
+ init_http_receiver();
16503
18947
  init_inbound_dispatch();
16504
18948
  init_lifecycle_lock();
16505
18949
  init_socket_ack();
@@ -16507,7 +18951,7 @@ var init_app3 = __esm(() => {
16507
18951
  init_socket_mode_guard();
16508
18952
  init_watcher();
16509
18953
  init_workspace_guard();
16510
- import_bolt4 = __toESM(require_dist5(), 1);
18954
+ import_bolt6 = __toESM(require_dist5(), 1);
16511
18955
  DEFAULT_START_RETRY_DELAYS_MS = [5000, 15000, 30000, 60000, 120000, 300000];
16512
18956
  startRetryDelaysMs = DEFAULT_START_RETRY_DELAYS_MS;
16513
18957
  SOCKET_EVENT_STATES = {
@@ -16529,4 +18973,4 @@ var init_app3 = __esm(() => {
16529
18973
  watchdogOptions = SLACK_SOCKET_WATCHDOG_DEFAULTS;
16530
18974
  });
16531
18975
 
16532
- export { require_dist4, require_dist5, getSlackConnectionState, init_connection_state, noteSlackInboundSideEffect, ignoreSlackInbound, reportSlackInboundFailure, isAdmittedSlackDelivery, getSlackInboundDiagnostics, init_inbound_dispatch, runSlackLifecycleExclusive, init_lifecycle_lock, terminalReactionEvent, init_reaction_events, isPollTracingEnabled, initOtel, withSpan2, startSpan2, withSpanContext2, withRemoteContext2, injectTraceContext2, recordSessionCost2, recordDbRetentionSweep2, recordDbRetentionStatement2, init_otel, slackTaskOutput, init_task_output, ackSlackMessage, skipSlackMessageReaction, finalizeTerminalSlackReactions, init_ack, getTaskLink, getTaskUrl, markdownToSlack, buildMrkdwnSectionBlocks, buildCaptionBlock, buildCancelledBlocks, buildBufferFlushBlocks, buildTreeBlocks, init_blocks, taskCitationIssues, stripInvalidTaskCitations, taskCitationSourceGroups, renderTaskCitations, taskCitationWarnings, init_task_citations, MAX_TASK_CITATIONS, CitationInputSchema, TaskCitationSchema, upsertTaskCitations, getTaskCitations, getTaskCitationsForTasks, hasTaskCitationCheckRefusal, init_task_citations2, initialize, ensure, init_business_use, getAgentDisplayName, getAgentSlackIcon, init_responses, markSlackSessionProcessing, init_session_status, isSlackRenderV2Enabled2, callSlackWithRetry2, ensureSlackThreadTree2, slackErrorCode2, startSlackRenderV2Events2, stopSlackRenderV2Events2, processSlackRenderV22, init_render_v2, registerTreeMessage, init_watcher, getSlackApp2, initSlackApp2, startSlackApp2, stopSlackApp2, stopSlackAppUnderLifecycleLock2, init_app3 };
18976
+ export { require_dist4, require_dist5, getSlackConnectionState, init_connection_state, noteSlackInboundSideEffect, ignoreSlackInbound, reportSlackInboundFailure, isAdmittedSlackDelivery, getSlackInboundDiagnostics, init_inbound_dispatch, runSlackLifecycleExclusive, init_lifecycle_lock, terminalReactionEvent, init_reaction_events, isPollTracingEnabled, initOtel, withSpan2, startSpan2, withSpanContext2, withRemoteContext2, injectTraceContext2, recordSessionCost2, recordDbRetentionSweep2, recordDbRetentionStatement2, init_otel, slackTaskOutput, init_task_output, ackSlackMessage, skipSlackMessageReaction, finalizeTerminalSlackReactions, init_ack, getTaskLink, getTaskUrl, markdownToSlack, buildMrkdwnSectionBlocks, buildCaptionBlock, buildCancelledBlocks, buildBufferFlushBlocks, buildTreeBlocks, init_blocks, taskCitationIssues, stripInvalidTaskCitations, taskCitationSourceGroups, renderTaskCitations, taskCitationWarnings, init_task_citations, MAX_TASK_CITATIONS, CitationInputSchema, TaskCitationSchema, upsertTaskCitations, getTaskCitations, getTaskCitationsForTasks, hasTaskCitationCheckRefusal, init_task_citations2, TaskUiSpecSchema, getTaskUiSpec, getTaskUiSpecsForTasks, upsertTaskUiSpec, reserveTaskUiActionRun, releaseTaskUiActionRun, setTaskUiActionResult, hasTaskUiSpecCheckRefusal, init_task_ui_spec, standardComponentDefinitions, CardSpecError, toCard, init_dist5, UI_SPEC_ACTION_PREFIX, UI_SPEC_ACTION_ID, UI_SPEC_CARD_LIMITS, init_task_ui_spec2, validateTaskUiSpec, init_validate2, initialize, ensure, init_business_use, withUiSpecFallback, init_fallback, getAgentDisplayName, getAgentSlackIcon, init_responses, markSlackSessionProcessing, init_session_status, isSlackRenderV2Enabled2, callSlackWithRetry2, ensureSlackThreadTree2, slackErrorCode2, startSlackRenderV2Events2, stopSlackRenderV2Events2, processSlackRenderV22, init_render_v2, registerTreeMessage, init_watcher, getSlackApp2, getSlackHttpReceiver2, initSlackApp2, startSlackApp2, stopSlackApp2, stopSlackAppUnderLifecycleLock2, init_app3 };