@desplega.ai/agent-swarm 2.8.2 → 2.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (558) hide show
  1. package/dist/acp-adapter-jqn86aam.js +16 -0
  2. package/dist/acp-targets-swxq55dr.js +23 -0
  3. package/dist/{actions-kxek041g.js → actions-pb678g3e.js} +22 -20
  4. package/dist/agent-fs-provision-dmhnc38q.js +27 -0
  5. package/dist/{amp-adapter-ce7jjke4.js → amp-adapter-3pa66q27.js} +3 -3
  6. package/dist/{anthropic-messages-jkva0zps.js → anthropic-messages-x2cp5fvf.js} +41 -41
  7. package/dist/{app-v6zz8yh0.js → app-17d12ev4.js} +6 -4
  8. package/dist/approval-notifications-h7vd9pmg.js +20 -0
  9. package/dist/{assistant-m0sw9xx2.js → assistant-t7k39ree.js} +56 -34
  10. package/dist/{azure-openai-responses-wgtqkbr3.js → azure-openai-responses-590s1eea.js} +10 -10
  11. package/dist/{boot-args-schema-66bk37wv.js → boot-args-schema-0gqmkfbe.js} +1 -1
  12. package/dist/{boot-reembed-edjpwsc1.js → boot-reembed-f064w382.js} +1 -1
  13. package/dist/{boot-reembed-y27n09tz.js → boot-reembed-n6anc01d.js} +1 -1
  14. package/dist/{boot-scrub-sweep-1xc35965.js → boot-scrub-sweep-ejd5dnrz.js} +84 -13
  15. package/dist/{boot-seeds-7hjj91qj.js → boot-seeds-f99fjs5q.js} +4 -4
  16. package/dist/{boxd-ent8ch04.js → boxd-wn235q80.js} +7 -7
  17. package/dist/claude-adapter-gvznwxgc.js +28 -0
  18. package/dist/{claude-managed-adapter-jh6c523j.js → claude-managed-adapter-pbrbvc64.js} +4 -4
  19. package/dist/{claude-managed-setup-y6z2perp.js → claude-managed-setup-kdxttvc3.js} +11 -11
  20. package/dist/{claude-sdk-session-vvya8wqk.js → claude-sdk-session-0t2teq6n.js} +9386 -9197
  21. package/dist/{cli-yjdgea32.js → cli-1jx0srjt.js} +17 -17
  22. package/dist/{cli-rmzsadkf.js → cli-1tvdx9t5.js} +2 -2
  23. package/dist/{cli-3vmb0n58.js → cli-25nstr34.js} +1 -1
  24. package/dist/{cli-959kp5h2.js → cli-2kg31ted.js} +45 -38
  25. package/dist/{cli-4vzgeta4.js → cli-2tnbc3gw.js} +375 -127
  26. package/dist/{cli-tekytdq9.js → cli-3zxdz9r7.js} +9 -9
  27. package/dist/{cli-bsywb58a.js → cli-4ghh072d.js} +16 -16
  28. package/dist/{cli-9mb2q6pb.js → cli-57pvhnyt.js} +4 -4
  29. package/dist/{cli-d84byzn8.js → cli-5a6pqy45.js} +441 -53
  30. package/dist/{cli-jrzkw01m.js → cli-5gpqgs8b.js} +2 -2
  31. package/dist/{cli-0cq8y6m7.js → cli-5gygrr67.js} +9 -9
  32. package/dist/{cli-z1w943va.js → cli-5kcmxwxv.js} +3 -3
  33. package/dist/{cli-3e875j5p.js → cli-5ntc4we6.js} +3189 -328
  34. package/dist/{cli-bst1vp7e.js → cli-5y2fvw4z.js} +13 -5
  35. package/dist/{cli-mrt48bx7.js → cli-6237rnyr.js} +1 -1
  36. package/dist/cli-6dp0jkfj.js +754 -0
  37. package/dist/{cli-b98a65ed.js → cli-7831nhaw.js} +5 -5
  38. package/dist/{cli-kjtwrhea.js → cli-7cgf614g.js} +10 -10
  39. package/dist/{cli-fwy8kfd6.js → cli-7fx9jyfs.js} +942 -63
  40. package/dist/{cli-28fq781p.js → cli-7zm3b3f5.js} +1 -1
  41. package/dist/{cli-v1dv1r37.js → cli-812paz57.js} +143 -9
  42. package/dist/{cli-837vfs2x.js → cli-8axx8vnw.js} +4 -4
  43. package/dist/cli-8x8y70av.js +103 -0
  44. package/dist/{cli-vj75tyaw.js → cli-95930z69.js} +15 -7
  45. package/dist/{cli-j24zbska.js → cli-9a2rtd77.js} +16 -14
  46. package/dist/cli-9ttx00s3.js +137 -0
  47. package/dist/{cli-6ek0hff4.js → cli-a9hfzg2r.js} +3 -3
  48. package/dist/{cli-dzpc6en0.js → cli-aa8s22gn.js} +19 -14
  49. package/dist/{cli-x1wa213s.js → cli-bk9v1xrv.js} +21 -21
  50. package/dist/{cli-a0z912j7.js → cli-c07v0qfa.js} +194 -75
  51. package/dist/{cli-1qkz151v.js → cli-c5cspahx.js} +28 -36
  52. package/dist/{cli-vdektqgf.js → cli-cw7mc1je.js} +4 -4
  53. package/dist/{cli-n6vtrcht.js → cli-dd37e0cm.js} +2 -2
  54. package/dist/cli-dqgnbnxs.js +132 -0
  55. package/dist/{cli-kc7v1nfv.js → cli-dx439zpg.js} +1 -1
  56. package/dist/{cli-q6mfk1ej.js → cli-dzzh58sy.js} +2 -2
  57. package/dist/{cli-f6bahpn5.js → cli-e9973bf0.js} +8 -6
  58. package/dist/{cli-2znm3dzj.js → cli-eds5xnsz.js} +2 -2
  59. package/dist/{cli-6rc5frdm.js → cli-eepnpee7.js} +34 -37
  60. package/dist/{cli-rvhdmjvt.js → cli-eg437b5p.js} +1 -1
  61. package/dist/cli-faf46gdq.js +714 -0
  62. package/dist/{cli-f4r3g076.js → cli-fgphc007.js} +2 -2
  63. package/dist/{cli-5y340nzn.js → cli-fnh4b12r.js} +24 -18
  64. package/dist/{cli-fsgttth8.js → cli-g0vv9dg4.js} +13 -13
  65. package/dist/{cli-e1p3n5gq.js → cli-g3zzby8t.js} +13 -13
  66. package/dist/{cli-3vjhs18n.js → cli-gabsjg8x.js} +3 -1
  67. package/dist/{cli-1pz0330a.js → cli-gddgcnav.js} +3 -3
  68. package/dist/{cli-97ae65rz.js → cli-h474mvp5.js} +11 -11
  69. package/dist/{cli-m88rpzkh.js → cli-hnamkvnc.js} +2 -2
  70. package/dist/{cli-8bpgbr8k.js → cli-j49yqpvh.js} +6 -6
  71. package/dist/{cli-w401b9tq.js → cli-jd3kxppb.js} +1 -1
  72. package/dist/{cli-m9s2qff2.js → cli-jg5txpm6.js} +187 -93
  73. package/dist/{cli-8aes17e4.js → cli-js8zrfyg.js} +3 -3
  74. package/dist/{cli-pfs8adn4.js → cli-k09cxm6m.js} +9 -7
  75. package/dist/{cli-q24n86d2.js → cli-k7pt28ad.js} +10 -3
  76. package/dist/{cli-zh9rsbqf.js → cli-kaa4bd7x.js} +11 -8
  77. package/dist/cli-kj0hyr43.js +51 -0
  78. package/dist/{cli-g70vxtjh.js → cli-kmvcm34h.js} +2 -2
  79. package/dist/{cli-t2tma8gb.js → cli-kqh27v2y.js} +2 -2
  80. package/dist/{cli-mxn1qvbn.js → cli-m1fbz2wj.js} +32 -57
  81. package/dist/{cli-2kvhc7x8.js → cli-mc1fx4xd.js} +51 -90
  82. package/dist/{cli-pchypa1s.js → cli-me4maa4j.js} +61 -6
  83. package/dist/{cli-504akrp9.js → cli-meydjstb.js} +3 -3
  84. package/dist/{cli-n30e0hcp.js → cli-mna6pmfx.js} +2 -2
  85. package/dist/cli-nhq5js1b.js +142 -0
  86. package/dist/cli-nmcpzbty.js +296 -0
  87. package/dist/cli-nr46j5pw.js +78 -0
  88. package/dist/{cli-5mrq3ake.js → cli-pn1v1pb0.js} +1 -1
  89. package/dist/{cli-f4e8r23x.js → cli-pwsax0vp.js} +11 -6
  90. package/dist/{cli-gyt3zydq.js → cli-pz1c00aa.js} +9 -754
  91. package/dist/{cli-eddnyg3t.js → cli-q2d3e1k1.js} +1 -1
  92. package/dist/{cli-fpjmegdb.js → cli-q8cfh1t9.js} +2 -2
  93. package/dist/{cli-vqva1teb.js → cli-qe909n63.js} +2 -2
  94. package/dist/{cli-2r0jcc3k.js → cli-qj39vrc6.js} +1 -1
  95. package/dist/{cli-0agcv1v5.js → cli-rqx70rcz.js} +2 -2
  96. package/dist/{cli-0jzra9ad.js → cli-rts1qvb4.js} +2 -2
  97. package/dist/{cli-3rkdne1h.js → cli-sn4pc4qx.js} +2 -2
  98. package/dist/{cli-98rwmcyc.js → cli-snxhtehz.js} +3 -3
  99. package/dist/{cli-d829z3xc.js → cli-spfz393q.js} +6 -6
  100. package/dist/{cli-6wj7p986.js → cli-spzkdgtg.js} +3 -3
  101. package/dist/{cli-m2z8jagn.js → cli-srtkr1h2.js} +18 -18
  102. package/dist/{cli-2gxeg5gr.js → cli-ssvdrk4y.js} +1 -1
  103. package/dist/{cli-jdknh18m.js → cli-svc803vq.js} +69 -816
  104. package/dist/{cli-7349va39.js → cli-t9ga4qmb.js} +935 -445
  105. package/dist/{cli-m5akxq8q.js → cli-vs9vdpy0.js} +1 -1
  106. package/dist/{cli-26ctbcdp.js → cli-vvgaz8t6.js} +93 -44
  107. package/dist/{cli-3sy2xags.js → cli-vw5x18yj.js} +39 -69
  108. package/dist/{cli-kchjb7qy.js → cli-w16kwbzw.js} +1 -1
  109. package/dist/cli-w7dxb2fj.js +921 -0
  110. package/dist/{cli-x6t50dmw.js → cli-wr1h0k28.js} +3 -3
  111. package/dist/{cli-d6521kb5.js → cli-x40a0w9j.js} +1 -1
  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-rcecc3yq.js → cli-ymct0ycy.js} +321 -111
  115. package/dist/{cli-xzm9vcfg.js → cli-zg3z63x3.js} +2 -2
  116. package/dist/cli.js +29 -26
  117. package/dist/{codex-adapter-zerf5qsp.js → codex-adapter-44yq2fkn.js} +9 -9
  118. package/dist/{codex-hook-30gyhzxe.js → codex-hook-h1zb7cfk.js} +6 -6
  119. package/dist/{codex-login-bcda78ge.js → codex-login-cdyrr5y1.js} +1 -1
  120. package/dist/{codex-session-runner-89s304py.js → codex-session-runner-zbh26gbw.js} +10 -10
  121. package/dist/{commands-jeh1b51j.js → commands-54f02v5b.js} +3 -3
  122. package/dist/{controller-mctfbrse.js → controller-9gpwcdek.js} +6 -6
  123. package/dist/{controllers-connect-nxa1ddwn.js → controllers-connect-61re6k1n.js} +26 -25
  124. package/dist/{cursor-adapter-qj8vehv6.js → cursor-adapter-7e4g81vd.js} +2 -2
  125. package/dist/{db-b36qn6k3.js → db-dg2gc7fd.js} +17 -13
  126. package/dist/{db-2dvay0es.js → db-wnh0qjy1.js} +3 -3
  127. package/dist/{devin-adapter-xedz98zv.js → devin-adapter-zp4tqq53.js} +1 -1
  128. package/dist/{dispatcher-gndbta01.js → dispatcher-jrm24r43.js} +19 -18
  129. package/dist/{docker-866qpzt9.js → docker-9aq30pp2.js} +5 -5
  130. package/dist/{dsh-adapter-f75sz821.js → dsh-adapter-1yqk267c.js} +2 -2
  131. package/dist/{e2b-3gpc2n3w.js → e2b-3v1e745x.js} +6 -6
  132. package/dist/{e2b-jbm7mj93.js → e2b-sm28k0k3.js} +6 -6
  133. package/dist/{easter-egg-3d-533knw22.js → easter-egg-3d-r4h9cs9m.js} +1 -1
  134. package/dist/{embedding-space-4p05vb2x.js → embedding-space-bafjr5f7.js} +6 -6
  135. package/dist/{embeddings-m6768mgh.js → embeddings-7xmgqe0e.js} +1 -1
  136. package/dist/{event-bus-e66gh7cc.js → event-bus-xr83x566.js} +1 -1
  137. package/dist/{execute-b3mrb1mv.js → execute-d6jg5ns0.js} +1 -1
  138. package/dist/{external-channel-gjv3jne3.js → external-channel-frq1xvq2.js} +2 -2
  139. package/dist/fx-adapter-0zrkfbkd.js +19 -0
  140. package/dist/{getMachineId-bsd-nfgrzarv.js → getMachineId-bsd-637a7rbk.js} +3 -3
  141. package/dist/{getMachineId-darwin-wz886dsk.js → getMachineId-darwin-9vytrcnn.js} +3 -3
  142. package/dist/{getMachineId-linux-1nng3p1p.js → getMachineId-linux-mkzsvyyz.js} +3 -3
  143. package/dist/{getMachineId-unsupported-a0428vw9.js → getMachineId-unsupported-4cfs2n11.js} +3 -3
  144. package/dist/{getMachineId-win-h45922nq.js → getMachineId-win-154s3qma.js} +3 -3
  145. package/dist/{google-generative-ai-h7s3e9kk.js → google-generative-ai-hh7strj3.js} +1 -1
  146. package/dist/{google-vertex-fhxaafzw.js → google-vertex-fy5bw2pm.js} +5 -5
  147. package/dist/grok-adapter-3db1c538.js +19 -0
  148. package/dist/handlers-k22n8mnn.js +33 -0
  149. package/dist/{heartbeat-a1tv60gt.js → heartbeat-6bpa611t.js} +22 -21
  150. package/dist/{hook-8h5dzcgq.js → hook-hvm5nf46.js} +5 -5
  151. package/dist/{hook-cyaps9ba.js → hook-w12k146y.js} +14 -14
  152. package/dist/{http-t15mhbd9.js → http-43tthdvs.js} +5838 -2600
  153. package/dist/{index-d6wkh8ar.js → index-1f0vypbg.js} +2 -2
  154. package/dist/{index-enn321kd.js → index-42jq9yy3.js} +3 -3
  155. package/dist/{index-khe3gp0k.js → index-4b1q8kan.js} +20 -20
  156. package/dist/{index-hjhfk3ra.js → index-585gyczt.js} +1 -1
  157. package/dist/index-8xcyd3mc.js +33 -0
  158. package/dist/index-9sy2bh6n.js +38 -0
  159. package/dist/{index-2skqtd76.js → index-b24j7t2m.js} +30 -28
  160. package/dist/{index-gjwaqaq8.js → index-cret47a5.js} +6 -6
  161. package/dist/{index-qwj6ntem.js → index-e3krvkh2.js} +4 -4
  162. package/dist/{index-w1zqf680.js → index-fn054vsf.js} +1 -1
  163. package/dist/{index-qav6455f.js → index-ftywhyr0.js} +214 -152
  164. package/dist/{index-tvfafeyy.js → index-mhq4sh5w.js} +1 -1
  165. package/dist/index-tx9mc2ap.js +570 -0
  166. package/dist/index-wjd56k1v.js +34 -0
  167. package/dist/{keepalive-91s7hzrb.js → keepalive-rk0j0jvh.js} +4 -4
  168. package/dist/lead-atxf3q6e.js +72 -0
  169. package/dist/{maintenance-7pjmy5xy.js → maintenance-g6z6kaxw.js} +1 -1
  170. package/dist/{node-4c5jqxr3.js → node-7qsx5kvm.js} +1 -1
  171. package/dist/{node-252anz2h.js → node-jftbyawr.js} +4 -4
  172. package/dist/{node-ray25snp.js → node-zd6shky9.js} +3 -3
  173. package/dist/{oauth-refresh-sweep-rzqfm94j.js → oauth-refresh-sweep-2k3g2q4w.js} +3 -3
  174. package/dist/{onboard-74st7pag.js → onboard-6fdbvh3v.js} +8 -8
  175. package/dist/{openai-codex-responses-k9gapdze.js → openai-codex-responses-bkcd8pjj.js} +9 -9
  176. package/dist/{openai-responses-4d5dx3c7.js → openai-responses-gbh0wfqe.js} +13 -13
  177. package/dist/{opencode-adapter-arn7gm8q.js → opencode-adapter-fdbsvts7.js} +7 -7
  178. package/dist/{otel-impl-rnzey8cb.js → otel-impl-rvwtc09q.js} +110 -110
  179. package/dist/pending-sqkrb836.js +80 -0
  180. package/dist/{pi-mono-adapter-6mkwq64n.js → pi-mono-adapter-asqayqcg.js} +13 -13
  181. package/dist/{pricing-refresh-ha21jhk7.js → pricing-refresh-f5tkgmw2.js} +2 -2
  182. package/dist/{rbac-roles-wqhma4dr.js → rbac-roles-06s555fa.js} +3 -3
  183. package/dist/{rbac-roles-59dxachk.js → rbac-roles-szxsg8t1.js} +10 -3
  184. package/dist/{render-v2-14kpzx12.js → render-v2-103p266q.js} +4 -4
  185. package/dist/{resume-gsa5fb5f.js → resume-v7kjewt9.js} +8 -7
  186. package/dist/{runtime-1hv06jsn.js → runtime-f1gmk0b7.js} +1 -1
  187. package/dist/{session-access-skm7bnp6.js → session-access-6shev8ts.js} +4 -4
  188. package/dist/{session-source-backfill-pbqzbncv.js → session-source-backfill-bd7spzjd.js} +3 -3
  189. package/dist/{setup-5yermsem.js → setup-kmxmztdb.js} +1 -1
  190. package/dist/thread-buffer-4yz236d0.js +36 -0
  191. package/dist/{virtual-modules-gazyapte.js → virtual-modules-57eje5wy.js} +5 -5
  192. package/dist/{work-objects-xj0ck0w4.js → work-objects-zr47ygmf.js} +23 -21
  193. package/dist/{worker-follow-up-911xc0b8.js → worker-follow-up-grrr3fda.js} +19 -18
  194. package/dist/worker-p4hbtcy3.js +72 -0
  195. package/dist/{x-2fyrt5pp.js → x-wg164ss9.js} +2 -2
  196. package/openapi.json +4518 -2356
  197. package/package.json +11 -8
  198. package/plugin/commands/create-pr.md +1 -1
  199. package/plugin/pi-skills/create-pr/SKILL.md +1 -1
  200. package/src/apps/action-runner.ts +21 -1
  201. package/src/apps/catalog.generated.json +626 -17
  202. package/src/apps/page-validator.ts +314 -8
  203. package/src/assets/key.ts +6 -0
  204. package/src/be/agent-fs-user-keys.ts +186 -0
  205. package/src/be/audit-user.ts +27 -13
  206. package/src/be/automation-preflight.test.ts +14 -14
  207. package/src/be/automation-preflight.ts +24 -16
  208. package/src/be/boot-scrub-sweep.ts +143 -14
  209. package/src/be/caller-session-group.ts +86 -0
  210. package/src/be/checklist.ts +375 -0
  211. package/src/be/db/agents.ts +12 -1
  212. package/src/be/db/approvals.ts +26 -0
  213. package/src/be/db/session-moves.ts +23 -0
  214. package/src/be/db/session-tree.ts +78 -19
  215. package/src/be/db/tasks/eligibility-scan.ts +14 -0
  216. package/src/be/db/tasks/read.ts +33 -0
  217. package/src/be/db/tasks/slack-fold.ts +116 -0
  218. package/src/be/db/tasks/write.ts +34 -0
  219. package/src/be/db-queries/mcp-servers.ts +13 -0
  220. package/src/be/db-queries/oauth.ts +6 -0
  221. package/src/be/db-queries/task-artifacts.ts +10 -8
  222. package/src/be/db.ts +74 -22
  223. package/src/be/extensions/assets.ts +17 -13
  224. package/src/be/import/config.ts +54 -0
  225. package/src/be/import/dir-source.ts +372 -0
  226. package/src/be/import/index.ts +149 -0
  227. package/src/be/import/pending.ts +71 -0
  228. package/src/be/import/schema.ts +137 -0
  229. package/src/be/import/seeders.ts +462 -0
  230. package/src/be/migrations/289_automation_savings_daily.sql +47 -0
  231. package/src/be/migrations/291_task_slack_participants.sql +4 -0
  232. package/src/be/migrations/293_savings_component_links.sql +58 -0
  233. package/src/be/migrations/296_automation_savings_daily_read_index.sql +6 -0
  234. package/src/be/migrations/297_import_ownership.sql +34 -0
  235. package/src/be/migrations/301_favorites_key_type.sql +36 -0
  236. package/src/be/migrations/302_checklist_items.sql +23 -0
  237. package/src/be/model-profile-check.ts +10 -2
  238. package/src/be/multi-runtime.ts +8 -1
  239. package/src/be/rbac-roles.ts +8 -1
  240. package/src/be/runtime-pools/demand.ts +20 -2
  241. package/src/be/runtime-pools/reachability.ts +31 -0
  242. package/src/be/runtime-pools/routing.ts +8 -1
  243. package/src/be/runtime-pools/supervisor.ts +6 -7
  244. package/src/be/savings/compute.ts +511 -16
  245. package/src/be/savings/model.ts +282 -14
  246. package/src/be/savings/read.ts +1502 -0
  247. package/src/be/savings/rollup.ts +571 -0
  248. package/src/be/script-credential-broker.ts +2 -2
  249. package/src/be/scripts/run-credential.ts +15 -3
  250. package/src/be/scripts/typecheck.ts +90 -8
  251. package/src/be/seed/agent-fs-provision.ts +104 -19
  252. package/src/be/seed/index.ts +1 -1
  253. package/src/be/seed/registry.ts +27 -8
  254. package/src/be/seed/runner.ts +1 -1
  255. package/src/be/seed/schedules-seeder.ts +24 -6
  256. package/src/be/seed/seed-toggle.ts +32 -0
  257. package/src/be/seed/types.ts +6 -0
  258. package/src/be/seed-scripts/catalog/dreaming-gather.ts +2 -2
  259. package/src/be/seed-scripts/catalog/dreaming-learnings.ts +10 -2
  260. package/src/be/seed-scripts/catalog/dreaming-memtax-create.ts +70 -4
  261. package/src/be/steering.ts +27 -4
  262. package/src/be/swarm-config-guard.ts +38 -0
  263. package/src/be/task-citations.ts +8 -5
  264. package/src/be/users.ts +29 -2
  265. package/src/commands/onboard/agent-fs-version.ts +1 -1
  266. package/src/commands/runner.ts +219 -42
  267. package/src/e2b/env.ts +2 -0
  268. package/src/extensions/catalog.generated.json +17 -0
  269. package/src/extensions/contract-types.generated.ts +1 -1
  270. package/src/github/app.ts +10 -1
  271. package/src/github/handlers.ts +6 -3
  272. package/src/github/reactions.ts +12 -14
  273. package/src/heartbeat/heartbeat.ts +14 -4
  274. package/src/http/agents.ts +19 -10
  275. package/src/http/all-routes.ts +2 -0
  276. package/src/http/approval-requests.ts +24 -4
  277. package/src/http/apps.ts +69 -5
  278. package/src/http/checklist.ts +176 -0
  279. package/src/http/db-query-bounded.ts +256 -11
  280. package/src/http/db-query-shared.ts +9 -0
  281. package/src/http/favorites.ts +14 -2
  282. package/src/http/fs.ts +346 -1
  283. package/src/http/index.ts +37 -2
  284. package/src/http/kv.ts +13 -0
  285. package/src/http/mcp-oauth.ts +1 -1
  286. package/src/http/mcp-servers.ts +15 -2
  287. package/src/http/onboarding.ts +2 -9
  288. package/src/http/poll.ts +59 -1
  289. package/src/http/requested-by.ts +97 -1
  290. package/src/http/savings.ts +676 -190
  291. package/src/http/script-connections.ts +1 -0
  292. package/src/http/scripts.ts +26 -15
  293. package/src/http/sessions.ts +17 -0
  294. package/src/http/slack-events.ts +101 -0
  295. package/src/http/status.ts +25 -7
  296. package/src/http/task-requester.ts +46 -0
  297. package/src/http/tasks.ts +107 -42
  298. package/src/http/users.ts +14 -0
  299. package/src/http/webhooks.ts +15 -0
  300. package/src/integrations/cards/index.ts +151 -0
  301. package/src/integrations/chat-sdk/outbound.ts +39 -13
  302. package/src/integrations/chat-sdk/runtime.ts +7 -1
  303. package/src/integrations/chat-sdk/status.ts +17 -0
  304. package/src/integrations/chat-sdk/telegram-api.ts +6 -1
  305. package/src/kv-reserved-namespaces.ts +17 -2
  306. package/src/oauth/presets.ts +29 -2
  307. package/src/prompts/base-prompt.ts +17 -4
  308. package/src/prompts/session-templates.ts +163 -9
  309. package/src/providers/acp-targets.ts +2 -2
  310. package/src/providers/amp-adapter.ts +1 -1
  311. package/src/providers/claude-adapter.ts +0 -20
  312. package/src/providers/claude-flag-settings.ts +12 -10
  313. package/src/providers/claude-managed-adapter.ts +5 -1
  314. package/src/providers/codex-adapter.ts +10 -35
  315. package/src/providers/codex-app-server.ts +2 -11
  316. package/src/providers/opencode-adapter.ts +41 -31
  317. package/src/providers/runtime-dependencies.ts +158 -0
  318. package/src/rbac/legacy-policy.ts +2 -0
  319. package/src/rbac/permissions.ts +10 -1
  320. package/src/scheduler/scheduler.ts +20 -14
  321. package/src/scripts-runtime/credential-broker/default-bindings.ts +19 -11
  322. package/src/scripts-runtime/credential-broker/index.ts +1 -1
  323. package/src/scripts-runtime/ctx.ts +1 -1
  324. package/src/scripts-runtime/egress-secrets.ts +2 -2
  325. package/src/scripts-runtime/executors/quickjs-bundle.ts +1 -0
  326. package/src/scripts-runtime/executors/quickjs-prelude.ts +162 -2
  327. package/src/scripts-runtime/executors/quickjs-runner.ts +4 -1
  328. package/src/scripts-runtime/stdlib/fetch.ts +113 -15
  329. package/src/scripts-runtime/stdlib/index.ts +3 -1
  330. package/src/scripts-runtime/stdlib/retry.ts +174 -0
  331. package/src/scripts-runtime/swarm-sdk.ts +187 -17
  332. package/src/scripts-runtime/types/stdlib.d.ts +97 -8
  333. package/src/scripts-runtime/types/swarm-extension.d.ts +27 -1
  334. package/src/scripts-runtime/types/swarm-sdk.d.ts +71 -6
  335. package/src/server.ts +4 -4
  336. package/src/slack/actions.ts +1 -0
  337. package/src/slack/app.ts +87 -46
  338. package/src/slack/assistant.ts +35 -7
  339. package/src/slack/enrich.ts +144 -50
  340. package/src/slack/handlers.ts +43 -99
  341. package/src/slack/http-receiver.ts +284 -0
  342. package/src/slack/inbound-dispatch.ts +43 -7
  343. package/src/slack/inbound-files.ts +33 -14
  344. package/src/slack/message-text.ts +47 -4
  345. package/src/slack/render-v2.ts +2 -1
  346. package/src/slack/socket-ack.ts +17 -10
  347. package/src/slack/steering.ts +5 -0
  348. package/src/slack/templates.ts +9 -0
  349. package/src/slack/thread-buffer-store.ts +58 -0
  350. package/src/slack/thread-buffer.ts +367 -109
  351. package/src/slack/thread-participants.ts +187 -0
  352. package/src/tasks/context-key.ts +24 -0
  353. package/src/tasks/sibling-awareness.ts +13 -1
  354. package/src/tests/agent-fs-live-url.test.ts +15 -0
  355. package/src/tests/agent-fs-provision-seeder.test.ts +140 -0
  356. package/src/tests/agent-fs-user-keys.test.ts +483 -0
  357. package/src/tests/agentfs-proxy.test.ts +8 -8
  358. package/src/tests/approval-card-resolution.test.ts +396 -0
  359. package/src/tests/approval-requests-notifications.test.ts +1 -1
  360. package/src/tests/approval-respond-auth.test.ts +28 -0
  361. package/src/tests/apps-action-parent-task.test.ts +140 -0
  362. package/src/tests/apps-catalog-additions.test.ts +315 -0
  363. package/src/tests/apps-catalog-files.test.ts +114 -0
  364. package/src/tests/apps-catalog-hitl.test.ts +117 -0
  365. package/src/tests/apps-catalog-inputs.test.ts +86 -0
  366. package/src/tests/apps-catalog-table.test.ts +47 -0
  367. package/src/tests/apps-chart-shell.test.ts +1 -1
  368. package/src/tests/apps-element-assembly.test.ts +52 -3
  369. package/src/tests/apps-session-thread.test.ts +182 -0
  370. package/src/tests/asset-key-invariants.test.ts +14 -0
  371. package/src/tests/base-prompt.test.ts +108 -23
  372. package/src/tests/boot-scrub-sweep.test.ts +172 -0
  373. package/src/tests/caller-session-group.test.ts +199 -0
  374. package/src/tests/cards.test.ts +169 -0
  375. package/src/tests/chat-sdk-status-route.test.ts +16 -3
  376. package/src/tests/chat-sdk-telegram-token.test.ts +76 -0
  377. package/src/tests/chat-sdk-tools.test.ts +147 -0
  378. package/src/tests/checklist-nudge.test.ts +208 -0
  379. package/src/tests/checklist.test.ts +686 -0
  380. package/src/tests/claude-adapter-binary.test.ts +7 -1
  381. package/src/tests/claude-adapter.test.ts +10 -64
  382. package/src/tests/claude-flag-settings.test.ts +15 -11
  383. package/src/tests/claude-hook-credentials.test.ts +0 -1
  384. package/src/tests/claude-sdk-lifecycle.test.ts +5 -1
  385. package/src/tests/codex-adapter.test.ts +17 -78
  386. package/src/tests/codex-app-server.test.ts +16 -0
  387. package/src/tests/comb-config-guard.test.ts +21 -0
  388. package/src/tests/comb-default.test.ts +59 -97
  389. package/src/tests/comb-links.test.ts +86 -16
  390. package/src/tests/comb-status.test.ts +24 -27
  391. package/src/tests/create-page-tool.test.ts +101 -1
  392. package/src/tests/create-schedule-key.test.ts +105 -0
  393. package/src/tests/create-task-vcs-repo.test.ts +136 -0
  394. package/src/tests/credential-broker.test.ts +2 -2
  395. package/src/tests/db-query.test.ts +87 -1
  396. package/src/tests/db-task-read-contract.test.ts +3 -0
  397. package/src/tests/db-task-write-contract.test.ts +3 -1
  398. package/src/tests/docs-index-footprint.test.js +3 -3
  399. package/src/tests/dreaming-learnings.test.ts +104 -0
  400. package/src/tests/entrypoint-github-enterprise.test.ts +158 -0
  401. package/src/tests/extensions-assets.test.ts +7 -3
  402. package/src/tests/extensions-catalog.test.ts +1 -0
  403. package/src/tests/extensions-example-sql-admin-only.test.ts +198 -0
  404. package/src/tests/extensions-pre-task.test.ts +7 -5
  405. package/src/tests/extensions-steering.test.ts +14 -2
  406. package/src/tests/favorites-agent-fs-path.test.ts +124 -0
  407. package/src/tests/fetch-resolved-env.test.ts +115 -1
  408. package/src/tests/fixtures/import-package.ts +32 -0
  409. package/src/tests/fixtures/runner-missing-dependency.ts +129 -0
  410. package/src/tests/fs-routes.test.ts +505 -2
  411. package/src/tests/github-ghes-mock.test.ts +196 -0
  412. package/src/tests/github-host.test.ts +285 -0
  413. package/src/tests/heartbeat-supersede-resume.test.ts +73 -0
  414. package/src/tests/heartbeat.test.ts +56 -0
  415. package/src/tests/import-config.test.ts +209 -0
  416. package/src/tests/import.test.ts +464 -0
  417. package/src/tests/invites-http.test.ts +144 -1
  418. package/src/tests/kv-http.test.ts +11 -0
  419. package/src/tests/literal-matcher.test.ts +58 -0
  420. package/src/tests/mcp-oauth-manual-client.test.ts +1 -1
  421. package/src/tests/oauth-presets.test.ts +12 -0
  422. package/src/tests/opencode-adapter.test.ts +53 -6
  423. package/src/tests/pool-affinity.test.ts +50 -0
  424. package/src/tests/prompt-template-session.test.ts +69 -6
  425. package/src/tests/provider-registration.test.ts +2 -55
  426. package/src/tests/provider-runtime-dependencies.test.ts +212 -0
  427. package/src/tests/rbac-admission.test.ts +19 -0
  428. package/src/tests/rbac-charact-misc-tools.test.ts +31 -0
  429. package/src/tests/rbac-engine.test.ts +2 -0
  430. package/src/tests/rbac-roles.test.ts +2 -0
  431. package/src/tests/runner-missing-dependency.test.ts +61 -0
  432. package/src/tests/runner-requester-profile.test.ts +139 -1
  433. package/src/tests/runtime-pool-reachability.test.ts +135 -1
  434. package/src/tests/runtime-pool-routing.test.ts +52 -0
  435. package/src/tests/runtime-stale-threshold.test.ts +40 -0
  436. package/src/tests/savings-compound.test.ts +774 -0
  437. package/src/tests/savings-compute.test.ts +7 -198
  438. package/src/tests/savings-fleet-latency.test.ts +143 -0
  439. package/src/tests/savings-fleet-read.test.ts +195 -0
  440. package/src/tests/savings-fleet-scale.test.ts +222 -0
  441. package/src/tests/savings-fleet-slices.test.ts +122 -0
  442. package/src/tests/savings-model.test.ts +212 -0
  443. package/src/tests/savings-read.test.ts +408 -0
  444. package/src/tests/savings-rollup.test.ts +766 -0
  445. package/src/tests/savings-scripts.test.ts +617 -0
  446. package/src/tests/script-connections.test.ts +4 -0
  447. package/src/tests/script-executor-conformance.test.ts +481 -0
  448. package/src/tests/scripts-http.test.ts +55 -0
  449. package/src/tests/scripts-runtime-fetch.test.ts +2 -2
  450. package/src/tests/secret-rules.test.ts +124 -1
  451. package/src/tests/secret-scrub-gate.test.ts +257 -0
  452. package/src/tests/secret-scrubber.test.ts +1 -1
  453. package/src/tests/seed-registry.test.ts +142 -9
  454. package/src/tests/session-source-keys.test.ts +42 -1
  455. package/src/tests/sessions-move.test.ts +70 -0
  456. package/src/tests/sessions-tree.test.ts +98 -0
  457. package/src/tests/sessions.test.ts +69 -0
  458. package/src/tests/slack-config.test.ts +4 -18
  459. package/src/tests/slack-dm-implicit-mention.test.ts +20 -1
  460. package/src/tests/slack-http-receiver.test.ts +472 -0
  461. package/src/tests/slack-identity-resolution.test.ts +23 -0
  462. package/src/tests/slack-inbound-files.test.ts +2 -1
  463. package/src/tests/slack-inbound-logging.test.ts +64 -0
  464. package/src/tests/slack-leave-thread.test.ts +1 -1
  465. package/src/tests/slack-message-text.test.ts +104 -0
  466. package/src/tests/slack-mode-lifecycle.test.ts +6 -4
  467. package/src/tests/slack-render-v2.test.ts +48 -0
  468. package/src/tests/slack-skip-reaction.test.ts +2 -2
  469. package/src/tests/slack-steering.test.ts +22 -10
  470. package/src/tests/slack-thread-buffer-context.test.ts +1 -1
  471. package/src/tests/slack-thread-buffer-fold.test.ts +417 -0
  472. package/src/tests/slack-thread-buffer-restore.test.ts +198 -0
  473. package/src/tests/slack-thread-buffer-startup-restore.test.ts +86 -0
  474. package/src/tests/slack-thread-buffer.test.ts +34 -34
  475. package/src/tests/slack-thread-participants.test.ts +447 -0
  476. package/src/tests/slack-tool-blocks.test.ts +167 -0
  477. package/src/tests/status.test.ts +32 -6
  478. package/src/tests/steering-core.test.ts +13 -0
  479. package/src/tests/steering-enabled.test.ts +7 -1
  480. package/src/tests/steering-promotion.test.ts +24 -0
  481. package/src/tests/swarm-config-reserved-keys.test.ts +17 -0
  482. package/src/tests/system-one-hosts-ui-mirror.test.ts +67 -0
  483. package/src/tests/task-artifacts.test.ts +50 -0
  484. package/src/tests/task-session-prompts.test.ts +95 -1
  485. package/src/tests/tool-annotations.test.ts +30 -0
  486. package/src/tests/workflow-system-one-extraction.test.ts +149 -1
  487. package/src/tools/chat-post.ts +19 -4
  488. package/src/tools/chat-reply.ts +20 -4
  489. package/src/tools/create-page.ts +21 -4
  490. package/src/tools/get-swarm.ts +18 -2
  491. package/src/tools/join-swarm.ts +2 -1
  492. package/src/tools/kv/kv-write-auth.ts +17 -1
  493. package/src/tools/schedules/create-schedule.ts +22 -4
  494. package/src/tools/slack-post.ts +40 -7
  495. package/src/tools/slack-reply.ts +50 -14
  496. package/src/types.ts +74 -2
  497. package/src/utils/constants.ts +60 -138
  498. package/src/utils/github-host.ts +217 -0
  499. package/src/utils/github-pull-request.ts +8 -5
  500. package/src/utils/literal-matcher.ts +118 -0
  501. package/src/utils/mcp-server-fetcher.test.ts +89 -0
  502. package/src/utils/mcp-server-fetcher.ts +13 -5
  503. package/src/utils/request-auth-context.ts +24 -0
  504. package/src/utils/secret-rules.generated.ts +1 -1
  505. package/src/utils/secret-scrubber.ts +485 -54
  506. package/src/utils/task-attachment-links.ts +9 -12
  507. package/src/vcs/index.ts +3 -0
  508. package/src/workflows/approval-notifications.ts +188 -12
  509. package/src/workflows/executors/swarm-script.ts +23 -19
  510. package/src/workflows/executors/system-one-extraction.ts +14 -7
  511. package/src/workflows/executors/system-one-providers.ts +22 -1
  512. package/templates/community/open-prompt-showreel/PLAYBOOK.md +1 -1
  513. package/templates/community/open-prompt-showreel/skills/open-prompt-showreel/SKILL.md +1 -1
  514. package/templates/extensions/README.md +1 -0
  515. package/templates/extensions/sql-admin-only/README.md +19 -0
  516. package/templates/extensions/sql-admin-only/hooks.ts +96 -0
  517. package/templates/extensions/sql-admin-only/manifest.json +8 -0
  518. package/templates/import/manifest.schema.json +136 -0
  519. package/templates/import/sources.schema.json +44 -0
  520. package/templates/skills/agent-browser/SKILL.md +1 -1
  521. package/templates/skills/agent-browser/content.md +1 -1
  522. package/templates/skills/apps/SKILL.md +122 -12
  523. package/templates/skills/apps/content.md +122 -12
  524. package/templates/skills/asset-namespaces/content.md +2 -1
  525. package/templates/skills/chat-sdk/content.md +17 -0
  526. package/templates/skills/db-query-guidance/content.md +2 -1
  527. package/templates/skills/scheduling/content.md +27 -0
  528. package/templates/skills/slack-interaction/content.md +12 -2
  529. package/templates/skills/swarm-docs/content.md +1 -0
  530. package/templates/skills/swarm-extensions/config.json +1 -1
  531. package/templates/skills/swarm-extensions/content.md +33 -23
  532. package/templates/skills/swarm-scripts/SKILL.md +18 -4
  533. package/templates/skills/swarm-scripts/content.md +18 -4
  534. package/templates/skills/work-on-task/SKILL.md +1 -1
  535. package/templates/skills/work-on-task/content.md +1 -1
  536. package/templates/skills/workflow-iterate/content.md +4 -7
  537. package/templates/workflows/dreaming/content.md +3 -3
  538. package/dist/acp-adapter-fqzkxyra.js +0 -15
  539. package/dist/claude-adapter-stw7jdcf.js +0 -25
  540. package/dist/cli-4bd1rck6.js +0 -4
  541. package/dist/cli-dns0y538.js +0 -194
  542. package/dist/cli-g5mtmf6t.js +0 -432
  543. package/dist/cli-xf3qw745.js +0 -104
  544. package/dist/fx-adapter-rpsgb1tw.js +0 -18
  545. package/dist/grok-adapter-n2m3zjg1.js +0 -18
  546. package/dist/handlers-nv8edn19.js +0 -32
  547. package/dist/index-ksmyd6kc.js +0 -37
  548. package/dist/index-rjnrje98.js +0 -32
  549. package/dist/index-tv3413wy.js +0 -33
  550. package/dist/lead-3hmddvrm.js +0 -70
  551. package/dist/worker-qgg0m2gw.js +0 -70
  552. package/src/providers/ctx-mode-env.ts +0 -10
  553. package/src/tests/entrypoint-acp-target-binary.test.ts +0 -439
  554. package/dist/{cli-4caa1x7d.js → cli-tsa40663.js} +4 -4
  555. package/dist/{index-0rvk3vd4.js → index-bs7gw5fd.js} +3 -3
  556. package/dist/{mistral-conversations-a45tx39a.js → mistral-conversations-0c30em7t.js} +4 -4
  557. package/dist/{openai-completions-xd579js7.js → openai-completions-f3n69rep.js} +18 -18
  558. package/dist/{pi-messages-hjbv8v10.js → pi-messages-zebyt7gb.js} +5 -5
@@ -1,9 +1,9 @@
1
1
  import {
2
2
  getDbClient2,
3
- computeContentHash2,
4
3
  upsertScriptByName,
5
4
  getScript,
6
5
  init_db3,
6
+ computeContentHash2,
7
7
  getScheduledTaskByName2,
8
8
  createScheduledTask2,
9
9
  updateScheduledTask2,
@@ -17,25 +17,28 @@ import {
17
17
  deleteSkill2,
18
18
  getSkillByName2,
19
19
  init_db4
20
- } from "./cli-rcecc3yq.js";
21
- import"./cli-q24n86d2.js";
20
+ } from "./cli-ymct0ycy.js";
21
+ import"./cli-k7pt28ad.js";
22
22
  import {
23
- agentFsProvisionSeeder
24
- } from "./cli-26ctbcdp.js";
25
- import"./cli-fpjmegdb.js";
26
- import"./cli-eddnyg3t.js";
27
- import"./cli-4vzgeta4.js";
23
+ agentFsProvisionSeeder2
24
+ } from "./cli-vvgaz8t6.js";
25
+ import {
26
+ runSeeders
27
+ } from "./cli-nr46j5pw.js";
28
+ import"./cli-q8cfh1t9.js";
29
+ import"./cli-q2d3e1k1.js";
30
+ import"./cli-2tnbc3gw.js";
31
+ import"./cli-w7dxb2fj.js";
28
32
  import {
29
33
  buildSkillContent
30
34
  } from "./cli-691vz9mk.js";
31
35
  import {
32
- require_dist2,
36
+ require_dist,
33
37
  validateScriptImports,
34
38
  init_import_allowlist,
35
39
  resolveSeededEnabled,
36
40
  init_automation_toggle,
37
41
  getSeedState,
38
- recordSeedState,
39
42
  deleteSeedState,
40
43
  init_state_db,
41
44
  canonicalJson,
@@ -49,11 +52,15 @@ import {
49
52
  init_typecheck,
50
53
  parseSkillContent,
51
54
  init_skill_parser
52
- } from "./cli-fwy8kfd6.js";
53
- import"./cli-rmzsadkf.js";
54
- import"./cli-jdknh18m.js";
55
- import"./cli-n6vtrcht.js";
56
- import"./cli-f4e8r23x.js";
55
+ } from "./cli-7fx9jyfs.js";
56
+ import"./cli-1tvdx9t5.js";
57
+ import"./cli-svc803vq.js";
58
+ import"./cli-dd37e0cm.js";
59
+ import"./cli-pwsax0vp.js";
60
+ import {
61
+ isEnvFlagEnabled,
62
+ init_env_flag
63
+ } from "./cli-cebvbc9t.js";
57
64
  import {
58
65
  __toESM
59
66
  } from "./cli-242037k3.js";
@@ -3084,8 +3091,8 @@ const CAPS = {
3084
3091
  memoryStore: 5,
3085
3092
  memoryEdit: 5,
3086
3093
  memoryDelete: 10,
3087
- skillCreate: 1,
3088
- skillUpdate: 3,
3094
+ skillCreate: 2,
3095
+ skillUpdate: 6,
3089
3096
  scriptSpecs: 2,
3090
3097
  scriptBuilds: 2,
3091
3098
  };
@@ -5365,6 +5372,13 @@ export function reuseWatermark(o: { from: Cursor; at: string; reuseRan: boolean;
5365
5372
 
5366
5373
  const esc = (s: string, n: number) => String(s ?? "").replace(/\\s+/g, " ").replace(/\\|/g, "\\\\|").slice(0, n);
5367
5374
 
5375
+ /** Measured triage cost: "this run" only when every triage task has a session_costs row; rows land late, so a short count is "partial". */
5376
+ export function measuredCost(row: { tasks?: unknown; usd?: unknown } | undefined, taskCount: number): { usd: number; basis: string } | null {
5377
+ const tasks = Number(row?.tasks ?? 0);
5378
+ if (!row || row.usd === null || row.usd === undefined || tasks === 0) return null;
5379
+ return { usd: Number(row.usd), basis: tasks >= taskCount ? "this run" : \`partial: \${tasks} of \${taskCount} tasks\` };
5380
+ }
5381
+
5368
5382
  export function renderSection(r: { skipReason?: string | null; read: number; planned: number; newRead: number; reuseRead: number; batches: number; okBatches: number; failedBatches: Array<{ batchId: string; status: string }>; promoted: number; kept: number; keptHowto: number; dropped: number; dropWhy: Record<string, number>; guards: Record<string, number>; invalid: Record<string, number>; missing: number; left: number | null; cursor: { from: string; to: string } | null; cost: { usd: number | null; basis: string }; samples: TriageRow[]; names: Record<string, string> }): string {
5369
5383
  const L: string[] = [HEADING];
5370
5384
  if (r.skipReason) {
@@ -5593,8 +5607,9 @@ export default async function (args: unknown, ctx: ScriptContext) {
5593
5607
  const taskIds = parsed.map((x) => x.taskId).filter(Boolean) as string[];
5594
5608
  let cost: { usd: number | null; basis: string } = { usd: null, basis: "no tasks" };
5595
5609
  if (taskIds.length) {
5596
- const c = (await q("cost", \`SELECT SUM(totalCostUsd) usd FROM session_costs WHERE taskId IN (\${taskIds.map(() => "?").join(",")})\`, taskIds))[0];
5597
- if (c && c.usd !== null && c.usd !== undefined) cost = { usd: Number(c.usd), basis: "this run" };
5610
+ const c = (await q("cost", \`SELECT COUNT(DISTINCT taskId) tasks, SUM(totalCostUsd) usd FROM session_costs WHERE taskId IN (\${taskIds.map(() => "?").join(",")})\`, taskIds))[0];
5611
+ const measured = measuredCost(c, new Set(taskIds).size);
5612
+ if (measured) cost = measured;
5598
5613
  else {
5599
5614
  const prior = (await q("cost-prior", \`SELECT COUNT(*) tasks, AVG(s.usd) usd FROM (SELECT sc.taskId, SUM(sc.totalCostUsd) usd FROM session_costs sc JOIN agent_tasks t ON t.id = sc.taskId WHERE t.tags LIKE '%dreaming-v2-learnings%' AND t.status = 'completed' AND sc.createdAt >= datetime('now','-7 days') GROUP BY sc.taskId) s\`))[0];
5600
5615
  cost = prior && Number(prior.tasks) > 0 && prior.usd !== null ? { usd: Number(prior.usd) * taskIds.length, basis: \`estimate: mean of \${prior.tasks} triage tasks in 7 days\` } : { usd: null, basis: "session_costs lands after the triage tasks finish" };
@@ -6943,6 +6958,45 @@ export function handoffRow(path: string, r: Route, texts: string[], scripts: Ski
6943
6958
  memberIds,
6944
6959
  };
6945
6960
  }
6961
+ // Synthesize turns only a few routes into actions a night (shared skill caps), so :latest carries every route it did
6962
+ // not act on. A route is consumed when an approved synthesize action cites the handoff KV and one of its members.
6963
+ export const ROUTES_KV_REF = "memtax-create:skill-routes";
6964
+ export function consumedMembers(synth: unknown): Set<string> {
6965
+ const s: any = parse(synth);
6966
+ const out = new Set<string>();
6967
+ for (const x of Array.isArray(s?.actions) ? s.actions : []) {
6968
+ const ev: string[] = Array.isArray(x?.evidence) ? x.evidence.map(String) : [];
6969
+ if (!ev.some((e) => e.includes(ROUTES_KV_REF))) continue;
6970
+ for (const e of ev) if (e.startsWith("memory:")) out.add(e.slice("memory:".length));
6971
+ }
6972
+ return out;
6973
+ }
6974
+ /** Stored routes minus consumed ones, merged by slug with tonight's (union memberIds, tonight's fields win), members
6975
+ * whose rows are gone dropped (\`live\` null = unknown, keep all), largest first. */
6976
+ export function carryRoutes(tonight: any[], stored: any[], consumed: Set<string>, live: Set<string> | null) {
6977
+ const slugOf = (r: any) => String(r?.slug || String(r?.path ?? "").split("/").pop() || "");
6978
+ const namesOf = (r: any) => Object.fromEntries((r?.memberIds ?? []).map((id: string, i: number) => [id, String(r?.memberNames?.[i] ?? "")]));
6979
+ const kept = stored.filter((r) => slugOf(r) && !(r.memberIds ?? []).some((id: string) => consumed.has(id)));
6980
+ const tonightSlugs = new Set(tonight.map(slugOf));
6981
+ const bySlug = new Map<string, any>();
6982
+ const names: Record<string, string> = {};
6983
+ for (const r of [...kept, ...tonight]) {
6984
+ const slug = slugOf(r);
6985
+ if (!slug) continue;
6986
+ Object.assign(names, Object.fromEntries(Object.entries(namesOf(r)).filter(([, n]) => n)));
6987
+ const prev = bySlug.get(slug);
6988
+ bySlug.set(slug, { ...prev, ...r, slug, memberIds: [...new Set([...(prev?.memberIds ?? []), ...(r.memberIds ?? []).map(String)])] });
6989
+ }
6990
+ const routes: any[] = [];
6991
+ let gone = 0;
6992
+ for (const r of bySlug.values()) {
6993
+ const memberIds = live ? r.memberIds.filter((id: string) => live.has(id)) : r.memberIds;
6994
+ if (!memberIds.length) gone++;
6995
+ else routes.push({ ...r, memberIds, memberNames: memberIds.map((id: string) => names[id] ?? "") });
6996
+ }
6997
+ routes.sort((x, y) => y.memberIds.length - x.memberIds.length);
6998
+ return { routes, carried: routes.filter((r) => !tonightSlugs.has(r.slug)).length, consumed: stored.length - kept.length, gone };
6999
+ }
6946
7000
  export const scriptHint = (texts: string[]) => texts.some((t) => /\\b(GET|POST|PUT|PATCH|DELETE) \\/|\\bcurl\\b|\\bendpoint\\b|https?:\\/\\/[^\\s]*\\/(v\\d|api)\\b|x-api-key|Bearer\\b/i.test(String(t ?? "")));
6947
7001
 
6948
7002
  const KIND_OF_ROOT = (root: string) =>
@@ -7681,10 +7735,33 @@ async function runScript(args: unknown, ctx: ScriptContext) {
7681
7735
  let handoff = runDry ? "dry run, not written" : "none";
7682
7736
  if (!runDry) {
7683
7737
  try {
7684
- const value = { runId, at: new Date().toISOString(), routes: skillRoutes.map((r) => ({ ...r, memberNames: (r.memberIds ?? []).map((id: string) => memberNames[id] ?? "") })) };
7685
- await ctx.swarm.kv_set({ namespace: NS, key: \`memtax-create:skill-routes:\${runId}\`, value: value as any });
7686
- await ctx.swarm.kv_set({ namespace: NS, key: "memtax-create:skill-routes:latest", value: value as any });
7687
- handoff = \`KV memtax-create:skill-routes:latest (\${skillRoutes.length} routes)\`;
7738
+ const tonight = skillRoutes.map((r) => ({ ...r, memberNames: (r.memberIds ?? []).map((id: string) => memberNames[id] ?? "") }));
7739
+ await ctx.swarm.kv_set({ namespace: NS, key: \`memtax-create:skill-routes:\${runId}\`, value: { runId, at: new Date().toISOString(), routes: tonight } as any });
7740
+ // Tonight's synthesize already read the stored set: drop what it acted on, carry the rest forward.
7741
+ const stored: any = (await ctx.swarm.kv_getOrNull({ namespace: NS, key: "memtax-create:skill-routes:latest" }))?.value;
7742
+ const prior: any[] = Array.isArray(stored?.routes) ? stored.routes : [];
7743
+ let consumed = new Set<string>();
7744
+ try {
7745
+ for (const r of await qStrict(\`SELECT json_extract(output, '$.taskOutput') v FROM workflow_run_steps WHERE runId = ? AND nodeId = 'synthesize'\`, [runId])) for (const id of consumedMembers(r.v)) consumed.add(id);
7746
+ } catch (e: any) {
7747
+ consumed = new Set();
7748
+ errors.push(\`handoff: synthesize step unreadable, nothing marked consumed: \${String(e?.message ?? e).slice(0, 200)}\`);
7749
+ }
7750
+ const ids = [...new Set([...prior, ...tonight].flatMap((r: any) => (r?.memberIds ?? []).map(String)))];
7751
+ let live: Set<string> | null = null;
7752
+ try {
7753
+ live = new Set<string>();
7754
+ for (let i = 0; i < ids.length; i += 500) {
7755
+ const part = ids.slice(i, i + 500);
7756
+ for (const r of await qStrict(\`SELECT DISTINCT id FROM agent_memory WHERE id IN (\${part.map(() => "?").join(",")}) AND (expiresAt IS NULL OR expiresAt > ?)\`, [...part, new Date().toISOString()])) live.add(String(r.id));
7757
+ }
7758
+ } catch (e: any) {
7759
+ live = null;
7760
+ errors.push(\`handoff: member check failed, kept every member: \${String(e?.message ?? e).slice(0, 200)}\`);
7761
+ }
7762
+ const carry = carryRoutes(tonight, prior, consumed, live);
7763
+ await ctx.swarm.kv_set({ namespace: NS, key: "memtax-create:skill-routes:latest", value: { runId, at: new Date().toISOString(), routes: carry.routes } as any });
7764
+ handoff = \`KV memtax-create:skill-routes:latest (\${carry.routes.length} routes: \${tonight.length} tonight, \${carry.carried} carried, \${carry.consumed} consumed, \${carry.gone} with no live members)\`;
7688
7765
  } catch (e: any) {
7689
7766
  errors.push(\`handoff: \${String(e?.message ?? e).slice(0, 200)}\`);
7690
7767
  handoff = "failed";
@@ -8035,6 +8112,10 @@ async function runScript(args: unknown, ctx: ScriptContext) {
8035
8112
  t("handoff: covered how-to -> skill-refactor skill-update, no script", h2.lane === "skill-refactor" && h2.op === "skill-update" && h2.skill === "agentmail-sending" && h2.scriptLane === null, h2);
8036
8113
  const h3 = handoffRow("/howto/bluesky", routeCluster("/howto/bluesky", sk), ["POST /xrpc/com.atproto.repo.createRecord with Bearer token"], scr, ["d4", "d5"]);
8037
8114
  t("handoff: API how-to with no script -> script candidate", h3.scriptExisting === null && h3.script === true && h3.scriptLane === "scriptify", h3);
8115
+ const cm = consumedMembers(JSON.stringify({ actions: [{ evidence: ["memory:m1", "kv:dreaming-v2/memtax-create:skill-routes:latest"] }, { evidence: ["memory:m9"] }] }));
8116
+ t("carry: only an action citing the handoff KV consumes its members", cm.has("m1") && !cm.has("m9"), [...cm]);
8117
+ const cr = carryRoutes([{ slug: "b", memberIds: ["m4"], memberNames: ["n4"], route: "skill-new" }], [{ slug: "a", memberIds: ["m1"] }, { slug: "b", memberIds: ["m2", "m3"], memberNames: ["n2", "n3"], route: "skill-update" }, { slug: "c", memberIds: ["m5"] }], cm, new Set(["m1", "m2", "m4"]));
8118
+ t("carry: consumed dropped, merged by slug (union), dead members and empty routes dropped, largest first", cr.routes.length === 1 && cr.routes[0].slug === "b" && cr.routes[0].route === "skill-new" && cr.routes[0].memberIds.join() === "m2,m4" && cr.routes[0].memberNames.join() === "n2,n4" && cr.consumed === 1 && cr.gone === 1, cr);
8038
8119
  // Near-duplicate guard. Vectors with a known cosine: [1, 0] vs [c, sqrt(1 - c^2)].
8039
8120
  const at = (c: number) => [c, Math.sqrt(1 - c * c)];
8040
8121
  const o = { nearDupCos: 0.8, twinCos: 0.95 };
@@ -14843,7 +14924,7 @@ var config_default = `{
14843
14924
  `;
14844
14925
 
14845
14926
  // templates/skills/agent-browser/content.md
14846
- var content_default = '# agent-browser\n\n`agent-browser` (vercel-labs) is the swarm\'s browser-automation CLI. It drives a headless Chromium over CDP and returns accessibility-tree snapshots with compact `@eN` refs. Use it for any browser task: verify a UI change, take a screenshot, walk a page, fill a form, extract page text, reproduce a frontend bug, or attach UI evidence to a PR, issue, Linear comment, or Slack thread.\n\nDo not use `qa-use`. It is not installed in the worker image any more.\n\n## Step 0: check that the CLI is present\n\nThe full worker image (`agent-swarm-worker:latest`) ships `agent-browser` and a headless Chromium. The slim image (`:slim`) has neither. The first command of any browser work is:\n\n```bash\ncommand -v agent-browser\n```\n\nIf it prints nothing, you are on the slim image. Say so in your progress report ("agent-browser is not available on this worker image") and fall back to manual QA: write the exact steps a human should run and mark the browser test cases as **Blocked**, not failed. Do not install a browser or the CLI yourself.\n\n## Step 1: load the version-matched guide\n\nThe CLI bundles its own usage guide. Load it once per task before the first browser command. Do not guess flags from memory.\n\n```bash\nagent-browser skills get core # overview + common patterns\nagent-browser skills get core --full # adds the full command reference\nagent-browser skills list # specialized guides (dogfood, electron, slack, ...)\n```\n\n## Step 2: the core loop\n\n```bash\nagent-browser open <url>\nagent-browser snapshot -i # accessibility tree, interactive elements only, @eN refs\nagent-browser click @e12 # act on refs from the snapshot\nagent-browser fill @e7 "text"\nagent-browser screenshot /tmp/<name>.png\nagent-browser close\n```\n\n- Re-run `snapshot` after every navigation or state change. Refs are only valid for the snapshot that produced them.\n- Run one browser session at a time. Call `store-progress` between page batches so the heartbeat watchdog sees you.\n- The browser is headless. Local servers inside the worker container are reachable at `http://localhost:<port>`.\n- The image launches Chromium with `--no-sandbox,--disable-dev-shm-usage` through `AGENT_BROWSER_ARGS`. If you pass your own `--args`, include `--no-sandbox` again or Chrome will not start.\n\n## Recording\n\nPass `record start` an absolute path (`/tmp/<topic>/raw.webm`). A relative path resolves against the agent-browser daemon\'s cwd, not yours, and fails with `ffmpeg write failed: Broken pipe` while `doctor` stays green.\n\nDefault: record with `--cursor`, drive every supported pointer action (`click`, `mouse move`, `drag`) with `--human`, and ship the **1.5x video**. Keep the 1x original only if a reviewer asks for it. Human pointer movement follows an eased curve; use `--seed <n>` on `mouse move` to make the take reproducible instead of using a bare move.\n\nOpen the page first, then record the interaction:\n\n```bash\nagent-browser record start ./in.mp4 --cursor\nagent-browser snapshot -i\nagent-browser mouse move 600 400 --human --seed 42 --duration 1400\nagent-browser click @e3 --human # use a ref from the current snapshot\n# Perform the remaining QA steps; use --human for drag actions too.\nagent-browser record stop\nffmpeg -y -i in.mp4 -filter:v "setpts=PTS/1.5,fps=30" -an \\\n -c:v libx264 -preset veryfast -crf 23 -pix_fmt yuv420p out-1.5x.mp4\n```\n\nSpeed-up is a post-process step: `record start` has no speed or human flag. Keep `fps=30` to preserve a steady 30 fps output rather than uneven frame drops at an inferred rate. `-an` disables audio because agent-browser recordings carry no audio track. The worker ships only `ffmpeg`, not `ffprobe`; inspect duration with `ffmpeg -i out-1.5x.mp4 2>&1 | grep Duration`.\n\nAdd `--contact-sheet` to the start command for a timestamped PNG summary of visual changes. Recording needs `ffmpeg` on PATH; check `agent-browser doctor` before starting. Stop the recording before closing the browser so the video is saved. Keep the 1.5x file on the same agent-fs QA path as screenshots below. In a PR, upload it as a GitHub user attachment and put the URL on its own line, so GitHub plays it inline.\n\n## Step 3: share the screenshot through agent-fs\n\nScreenshots on the worker disk disappear with the task. Upload them to agent-fs under the qa path convention: that copy is the durable original. A person opens it through the live app link `${AGENT_FS_LIVE_URL}/file/~/<org>/<drive>/<path>`. `--file` is binary-safe. `--content` is text-only and mangles PNGs.\n\n```bash\nagent-fs write thoughts/<agent-id>/qa/<topic>-screenshots/<name>.png \\\n --file /tmp/<name>.png -m "<what it shows>"\nagent-fs stat thoughts/<agent-id>/qa/<topic>-screenshots/<name>.png --json # confirm size > 0\n```\n\n- **GitHub PR body or comment**: upload the PNG, GIF or mp4 as a GitHub user attachment with the `github-attach` skill and embed `![caption](https://github.com/user-attachments/assets/<uuid>)`. Attachments never expire and mp4s play inline. A UI PR puts a before (main) and after pair in the `## Before / after` table. Fallback for images only, when the GitHub token is an App token (`ghu_`/`ghs_`): `agent-fs signed-url <path> --inline --json` (expires in 7 days). Never a presigned URL for an mp4 or a doc: it downloads.\n- **Linear comment or Slack message**: paste the live app link.\n- In `store-progress`, list the upload in the `attachments` field with `kind: "agent-fs"` and the path, and paste the live app link for people who need to open the file.\n- Make an `agent-fs share-create <path> --json` link only when the requester asks for one or the reader has no agent-fs login (customer, public post, email, named outsider). Never make one in case the file gets forwarded.\n- If `agent-fs auth whoami` fails, report the local path, say the upload was skipped, and continue.\n\nThe `agent-fs` skill holds the full agent-fs recipe.\n\n## Gotchas\n\n- `wait <selector>` waits for a VISIBLE match. When the first match is hidden it times out (about 25 s) even though the element exists. Wait on rendered text instead: `wait --text "<rendered text>"`.\n- Never run `pkill -f <pattern>` inside a Bash call: the pattern also matches the calling shell\'s command line and kills it. Record the PID when you start a background server (`echo $!`) and `kill <pid>`.\n';
14927
+ var content_default = '# agent-browser\n\n`agent-browser` (vercel-labs) is the swarm\'s browser-automation CLI. It drives a headless Chromium over CDP and returns accessibility-tree snapshots with compact `@eN` refs. Use it for any browser task: verify a UI change, take a screenshot, walk a page, fill a form, extract page text, reproduce a frontend bug, or attach UI evidence to a PR, issue, Linear comment, or Slack thread.\n\nDo not use `qa-use`. It is not installed in the worker image any more.\n\n## Step 0: check that the CLI is present\n\nThe full worker image (`agent-swarm-worker:latest`) ships `agent-browser` and a headless Chromium. The slim image (`:slim`) has neither. The first command of any browser work is:\n\n```bash\ncommand -v agent-browser\n```\n\nIf it prints nothing, you are on the slim image. Say so in your progress report ("agent-browser is not available on this worker image") and fall back to manual QA: write the exact steps a human should run and mark the browser test cases as **Blocked**, not failed. Do not install a browser or the CLI yourself.\n\n## Step 1: load the version-matched guide\n\nThe CLI bundles its own usage guide. Load it once per task before the first browser command. Do not guess flags from memory.\n\n```bash\nagent-browser skills get core # overview + common patterns\nagent-browser skills get core --full # adds the full command reference\nagent-browser skills list # specialized guides (dogfood, electron, slack, ...)\n```\n\n## Step 2: the core loop\n\n```bash\nagent-browser open <url>\nagent-browser snapshot -i # accessibility tree, interactive elements only, @eN refs\nagent-browser click @e12 # act on refs from the snapshot\nagent-browser fill @e7 "text"\nagent-browser screenshot /tmp/<name>.png\nagent-browser close\n```\n\n- Re-run `snapshot` after every navigation or state change. Refs are only valid for the snapshot that produced them.\n- Run one browser session at a time. Call `store-progress` between page batches so the heartbeat watchdog sees you.\n- The browser is headless. Local servers inside the worker container are reachable at `http://localhost:<port>`.\n- The image launches Chromium with `--no-sandbox,--disable-dev-shm-usage` through `AGENT_BROWSER_ARGS`. If you pass your own `--args`, include `--no-sandbox` again or Chrome will not start.\n\n## Recording\n\nPass `record start` an absolute path (`/tmp/<topic>/raw.webm`). A relative path resolves against the agent-browser daemon\'s cwd, not yours, and fails with `ffmpeg write failed: Broken pipe` while `doctor` stays green.\n\nDefault: record with `--cursor`, drive every supported pointer action (`click`, `mouse move`, `drag`) with `--human`, and ship the **1.5x video**. Keep the 1x original only if a reviewer asks for it. Human pointer movement follows an eased curve; use `--seed <n>` on `mouse move` to make the take reproducible instead of using a bare move.\n\nOpen the page first, then record the interaction:\n\n```bash\nagent-browser record start ./in.mp4 --cursor\nagent-browser snapshot -i\nagent-browser mouse move 600 400 --human --seed 42 --duration 1400\nagent-browser click @e3 --human # use a ref from the current snapshot\n# Perform the remaining QA steps; use --human for drag actions too.\nagent-browser record stop\nffmpeg -y -i in.mp4 -filter:v "setpts=PTS/1.5,fps=30" -an \\\n -c:v libx264 -preset veryfast -crf 23 -pix_fmt yuv420p out-1.5x.mp4\n```\n\nSpeed-up is a post-process step: `record start` has no speed or human flag. Keep `fps=30` to preserve a steady 30 fps output rather than uneven frame drops at an inferred rate. `-an` disables audio because agent-browser recordings carry no audio track. The worker ships only `ffmpeg`, not `ffprobe`; inspect duration with `ffmpeg -i out-1.5x.mp4 2>&1 | grep Duration`.\n\nAdd `--contact-sheet` to the start command for a timestamped PNG summary of visual changes. Recording needs `ffmpeg` on PATH; check `agent-browser doctor` before starting. Stop the recording before closing the browser so the video is saved. Keep the 1.5x file on the same agent-fs QA path as screenshots below. In a PR, upload it as a GitHub user attachment and put the URL on its own line, so GitHub plays it inline.\n\n## Step 3: share the screenshot through agent-fs\n\nScreenshots on the worker disk disappear with the task. Upload them to agent-fs under the qa path convention: that copy is the durable original. A person opens it through the file link from the Outputs section of your system prompt (the dashboard when configured). `--file` is binary-safe. `--content` is text-only and mangles PNGs.\n\n```bash\nagent-fs write thoughts/<agent-id>/qa/<topic>-screenshots/<name>.png \\\n --file /tmp/<name>.png -m "<what it shows>"\nagent-fs stat thoughts/<agent-id>/qa/<topic>-screenshots/<name>.png --json # confirm size > 0\n```\n\n- **GitHub PR body or comment**: upload the PNG, GIF or mp4 as a GitHub user attachment with the `github-attach` skill and embed `![caption](https://github.com/user-attachments/assets/<uuid>)`. Attachments never expire and mp4s play inline. A UI PR puts a before (main) and after pair in the `## Before / after` table. Fallback for images only, when the GitHub token is an App token (`ghu_`/`ghs_`): `agent-fs signed-url <path> --inline --json` (expires in 7 days). Never a presigned URL for an mp4 or a doc: it downloads.\n- **Linear comment or Slack message**: paste the live app link.\n- In `store-progress`, list the upload in the `attachments` field with `kind: "agent-fs"` and the path, and paste the live app link for people who need to open the file.\n- Make an `agent-fs share-create <path> --json` link only when the requester asks for one or the reader has no agent-fs login (customer, public post, email, named outsider). Never make one in case the file gets forwarded.\n- If `agent-fs auth whoami` fails, report the local path, say the upload was skipped, and continue.\n\nThe `agent-fs` skill holds the full agent-fs recipe.\n\n## Gotchas\n\n- `wait <selector>` waits for a VISIBLE match. When the first match is hidden it times out (about 25 s) even though the element exists. Wait on rendered text instead: `wait --text "<rendered text>"`.\n- Never run `pkill -f <pattern>` inside a Bash call: the pattern also matches the calling shell\'s command line and kills it. Record the PID when you start a background server (`echo $!`) and `kill <pid>`.\n';
14847
14928
 
14848
14929
  // templates/skills/apps/config.json
14849
14930
  var config_default2 = `{
@@ -14863,7 +14944,7 @@ var config_default2 = `{
14863
14944
  `;
14864
14945
 
14865
14946
  // templates/skills/apps/content.md
14866
- var content_default2 = "# Swarm Apps\n\nSwarm Apps are persistent, agent-authored internal applications: a schema-backed row store, named queries, custom script/task actions, and a validated json-render interface served at `/apps/<id>`. Use an app when people need to view and change live records; use `create_page` for a static snapshot.\n\n> **Capability gate**: app tools are available when the server's `CAPABILITIES` includes `pages` (for example `CAPABILITIES=core,task-pool,pages`). There is no separate `apps` capability. If these tools are absent from your MCP list, this is why.\n\n## Tools and iteration loop\n\n| Tool | Use it for |\n|---|---|\n| `app-list` | Discover apps by id, name, description, and timestamps. Definitions are omitted. |\n| `app-get` | Read one complete stored definition before changing it. |\n| `app-upsert` | Create an app, or replace an existing app's entire definition when you intentionally have the full desired state. |\n| `app-patch` | Make a focused change while preserving everything not mentioned in the patch. Prefer this for iteration. |\n| `app-query` | Run one declared named query and return its rows. Use this when an agent or saved script needs to consume app data rather than render the app UI. |\n| `app-rows-list` | List rows with typed equality filters, sorting, and a limit. Returns `{ rows, total }`. |\n| `app-row-get` | Read a row by `rowId`. Returns `{ row }`. |\n| `app-row-create` | Create a row from `values`. Returns `{ row }`. |\n| `app-rows-create` | Create 1 to 500 rows from a `rows: values[]` array, within 10 MiB. Returns `{ rows }`. |\n| `app-row-patch` | Patch a row by `rowId` with `values`. Returns `{ row }`. |\n| `app-row-delete` | Delete a row by `rowId`. Returns `{ ok: true }`. |\n| `app-rows-delete` | Delete matching rows with a non-empty `equals` filter. Returns `{ deleted }`. |\n| `app-action-run` | Run a declared script, task, or sync action with `{ appId, action, input? }`. Agents can invoke it through MCP only. |\n| `app-history` | List definition snapshots and their compact model/column digests before choosing a restore point. |\n| `app-diff` | Show a unified definition diff; defaults to newest snapshot → CURRENT. |\n| `app-rollback` | Restore a snapshot through the normal schema-migration engine. |\n\nFor every edit: `app-get` -> modify the smallest coherent subtree -> `app-patch` -> if rejected, fix every returned `issues[]` entry (`path` + `message`) and retry. Validation happens before storage, so a rejected update leaves the saved app unchanged. Do not guess at the current definition or use `app-upsert` with a partial definition.\n\n`app-patch` can also change `name`; omit `description` to preserve it or pass `description: null` to clear it.\n\n### Reading an app's callable surface\n\nOne `app-get` returns everything needed to drive an app you did not write: `definition.queries` are runnable with `app-query` (supply every `$param` the query references), and `definition.actions` are invocable with `app-action-run` or `POST /api/apps/<id>/actions/<name>` (a `script` action runs its script, a `task` action spawns a task, a `sync` action refreshes sources). Read the query parameters and action arguments from the definition before invocation. Do not guess parameter names.\n\n### Verified action caller\n\nScript actions receive `caller` as a reserved, server-stamped argument. The server overwrites `caller` from definition defaults and request input.\n\n```typescript\ntype AppActionCaller = {\n kind: \"user\" | \"agent\" | \"operator\" | \"guest\";\n id: string | null;\n name?: string;\n pageId?: string;\n};\n```\n\nThe caller identifies the authenticated user or agent. Operator and guest callers have `id: null`. A signed page session adds `pageId`.\nWith the swarm key, a registered `X-Agent-ID` produces an agent caller and `agent:<id>` row provenance. Missing or unknown agent IDs remain operator callers.\nTask actions include the same caller as server-verified JSON in the task prompt. Script execution still uses the saved script owner's bindings.\n\n### Verified action caller\n\nScript actions receive `caller` as a reserved, server-stamped argument. The server overwrites `caller` from definition defaults and request input.\n\n```typescript\ntype AppActionCaller = {\n kind: \"user\" | \"agent\" | \"operator\" | \"guest\";\n id: string | null;\n name?: string;\n pageId?: string;\n};\n```\n\nThe caller identifies the authenticated user or agent. Operator and guest callers have `id: null`. A signed page session adds `pageId`.\nWith the swarm key, a registered `X-Agent-ID` produces an agent caller and `agent:<id>` row provenance. Missing or unknown agent IDs remain operator callers.\nTask actions include the same caller as server-verified JSON in the task prompt. Script execution still uses the saved script owner's bindings.\n\n## Safe schema evolution and rollback\n\nPrefer **hiding** a column over deleting it. A hidden column's values stay on every existing row, so an unhide or rollback can make it visible again. Hiding is metadata-only: hidden columns cannot be used in queries, page bindings, `app.mutate` values, or new row writes, and `required` is ignored while hidden. Row GETs still expose the historical value for backward compatibility.\n\nDo not reuse a hidden column name. The name remains held until you either unhide it or explicitly purge its stored values. To permanently remove a column, delete its declaration with `null` and include `{ \"columnName\": { \"purge\": true } }` in the same `migration` object. That is deliberately one-shot and irreversible for row data.\n\nSchema-changing writes can carry this sibling `migration` object:\n\n```json\n{\n \"migration\": {\n \"priority\": { \"from\": \"flag\", \"map\": { \"urgent\": \"high\", \"watch\": \"low\" }, \"else\": \"none\" },\n \"status\": { \"from\": \"flag\", \"map\": { \"watch\": \"watching\", \"done\": \"done\" }, \"else\": \"open\" },\n \"oldColumn\": { \"purge\": true },\n \"count\": { \"coerce\": true, \"else\": 0 },\n \"owner\": { \"set\": \"unassigned\" }\n }\n}\n```\n\nUse `set` to backfill a changed column, `from` with optional `map`/`else` to derive it from one existing (including hidden) column, `coerce` for a kind change, and `purge` only for explicit destruction. Non-purge directives target a column changed in that same write. The server fails loudly before writing when a lossy change needs a directive: inspect every returned `issues[]` item, including its per-value row counts, then choose an explicit policy and retry. Never guess a migration just to get a 200.\n\n**Source lifecycle** rides the same engine with the same all-or-nothing guarantees. Free: adding a source, adding a NEW column with a `source` binding, binding an existing column that holds zero values, changing a binding's `field`/`transform`, and changing a source's `args`/`config`/`connection`/`scriptId` (window changes churn staleness on the next pass — expect `stale` flips when narrowing). Rejected with a path-bearing issue: changing `joinKey` (immutable — remove the source and add it again), changing `connector` while the source owns rows (row count in the message), and binding an existing column that already holds values (purge it — or add a fresh column — and bind that instead; a sync pass would otherwise overwrite the data). Removing a source **detaches** its rows: values survive as ordinary columns, the `source`/`syncedAt`/`stale` envelope is stripped, and the report counts them in `detachedRows`. A patch removing a source must drop its column bindings in the same call — a dangling `source.of` is rejected before anything is written.\n\nSync never adopts rows it does not own: a pulled record whose join key matches an unowned row creates a second, source-owned row. Adding a source over a join-key column that already holds values therefore duplicates those records on the first pass — and remove-source → re-add duplicates for the same reason, because detached rows keep their values. To convert a hand-maintained model into a synced one, purge the old rows first or use a fresh join-key column.\n\nFor example, split a legacy `flag` into `priority` and `status` without losing data in one patch: add the two columns, map both from `flag`, update every affected query/page binding, then hide `flag`.\n\n```json\n{\n \"appId\": \"<app-id>\",\n \"definition\": {\n \"models\": {\n \"ticket\": {\n \"columns\": {\n \"priority\": { \"kind\": \"enum\", \"enum\": [\"none\", \"low\", \"high\"] },\n \"status\": { \"kind\": \"enum\", \"enum\": [\"open\", \"watching\", \"done\"] },\n \"flag\": { \"kind\": \"string\", \"hidden\": true }\n }\n }\n }\n },\n \"migration\": {\n \"priority\": { \"from\": \"flag\", \"map\": { \"urgent\": \"high\", \"watch\": \"low\" }, \"else\": \"none\" },\n \"status\": { \"from\": \"flag\", \"map\": { \"watch\": \"watching\", \"done\": \"done\" }, \"else\": \"open\" }\n }\n}\n```\n\nEvery schema migration returns `{ scanned, backfilled, coerced, mapped, elsed, purgedValues, idxRebuilt, detachedRows, orphanFields }`. Read `orphanFields`: it reports extra row fields that predate or no longer appear in the definition; they are preserved until an explicit purge. `schemaVersion` is server-managed: never set it in an input patch or try to use it as application data.\n\nEvery successful definition write snapshots the previous definition. Use `app-history` to select a version, `app-diff({ appId, from: <version> })` to inspect it against CURRENT, then `app-rollback({ appId, version: <version>, migration? })` to restore it. Rollback is a forward migration over live rows, not row-level time travel: it creates a new pre-rollback snapshot and may reject a lossy restore with the same migration directives and counts. A rejected rollback changes nothing.\n\n### Per-user configuration\n\n`userConfig` declares up to 20 typed settings in the versioned definition; its values are deliberately stored outside the definition, separately for each user (and the operator dashboard). Each field is `{ \"kind\": \"string\" | \"number\" | \"boolean\" | \"date\" | \"enum\", \"default\"?: ..., \"enum\"?: [...], \"label\"?: \"...\" }`. Defaults follow column rules, including enum membership; `required` is not allowed. A missing or obsolete stored value reads as its default, or `null` when no default is declared.\n\nUse `{ \"$state\": \"/user/<field>\" }` on a page for the read-only current-user binding; the field must be declared and the path cannot continue below it. Pure and bound reusable elements cannot bind `/user` directly — pass the value through an element prop from the consuming page. An agent acting on an owned user-requested task reads and edits that requester's preferences. `userConfig` schema changes are always migration-compatible and appear in migration reports; no migration directives are needed. Rollback restores the historical schema but never alters saved per-user values, so values can resurface when a field returns.\n\n### Theming\n\nAn optional top-level `\"theme\"` sets the preset the dashboard applies to the app's rendered canvas: a lowercase slug validated by shape only. The preset catalog ships with the dashboard and lives in `src/themes/presets.ts` and `src/themes/classics.ts`. Update this list and the `app-upsert` tool description when it changes. Current ids: `hive` (the stock look), the accent/field presets `meadow`, `iris`, `rose`, `cobalt`, `ember`, `carbon`, `paper` (the warm editorial paper look), and the classic editor/platform presets `github`, `vscode`, `material`, `solarized`, `tokyo`, `monokai`, `gruvbox`, `catppuccin`. Action and destructive tones are never themed; status tones are themed ONLY by the classic presets (their identity includes a status palette: hue semantics stay fixed, success reads green and error reads red everywhere). An id the viewer's dashboard build does not know degrades to the dashboard's own theme, so unknown slugs are safe but pointless. Omit `theme` to inherit whatever theme the viewer runs; `\"hive\"` is an explicit reset to the stock look even inside a themed dashboard.\n\nViewers can override the preset per app from the app's settings drawer; the override rides the reserved `$theme` key of the user-config values (accepted on every app, even without a declared `userConfig` schema, and never visible at `/user/...`). A present override always beats the definition's `theme` — even an unrecognized one, which degrades to the dashboard theme — so treat `theme` as the app's default styling, not a guarantee.\n\nAn optional top-level `\"icon\"` sets the app's icon on the dashboard Apps page. It takes one of three shapes:\n\n- `{ \"type\": \"lucide\", \"icon\": \"<kebab-case lucide name>\", \"color\": \"#RRGGBB\" }` (`color` optional). The dashboard looks the name up in its curated icon catalog and shows a generic grid icon for an unknown name.\n- `{ \"type\": \"url\", \"url\": \"https://...\" }`: an https image link, at most 2048 characters, no credentials.\n- `{ \"type\": \"agent-fs\", \"path\": \"/apps/<appId>/icon.png\" }`: an image on the swarm's agent-fs drive. Add both `orgId` and `driveId` for another drive; never just one.\n\nThe server validates shape only. The dashboard shows the grid glyph while an image loads, when it fails to load, and when the viewer has no agent-fs connected, so omitting `icon` is always safe. `app-patch` replaces `icon` whole, so switching shapes leaves no keys from the old one.\n\n\nDistinguish the two rollback 400s. A lossy-migration 400 is fixable: copy the required `migration` entries from the message and retry. A target-snapshot validation 400 explicitly says that directives cannot repair that historical definition; use `app-history` and choose a different version.\n\nWhen a schema patch reports stale page/query bindings, repair them in that same patch. Page elements are atomic: replace the complete `pages.<page>.elements.<id>` declaration, removing any reference to a hidden or deleted column, instead of sending only the changed nested prop. This is also the repair move for older apps whose stored page already references an undeclared column; full-definition validation otherwise blocks every patch.\n\n## Definition reference\n\n```json\n{\n \"models\": {\n \"modelName\": {\n \"columns\": {\n \"externalId\": { \"kind\": \"string\" },\n \"title\": { \"kind\": \"string\" }\n }\n }\n },\n \"queries\": { \"queryName\": { \"model\": \"modelName\" } },\n \"actions\": { \"actionName\": { \"kind\": \"task\", \"prompt\": \"Review the current rows and report\" } },\n \"pages\": {\n \"main\": {\n \"root\": \"root\",\n \"elements\": { \"root\": { \"type\": \"Container\", \"props\": {} } }\n }\n },\n \"defaultPage\": \"main\",\n \"theme\": \"ember\"\n}\n```\n\nOptional top-level `layout: \"sidebar\"` turns on the app shell (see Pages, routes, and page trees). Without it every page renders on the plain canvas, exactly as before.\n\nModel, reusable-element, element-prop, query, action, column, page, and page-param names start with a lowercase letter, contain only letters, numbers, or underscores, and are at most 40 characters. A definition has 0-10 models and at most 20 reusable elements; each declared model has 1-40 columns. Zero-model apps are valid for pure UI utilities as long as their pages and reusable elements validate.\n\n### Reusable elements\n\nTop-level `elements` are versioned inside the app definition and can be reused from the app's own pages or, when explicitly exported, from another app. They are private by default. Each entry declares a `mode`, optional typed `props`, one `root`, and a flat `elements` node map using the same validated tree vocabulary as a page:\n\n```json\n{\n \"elements\": {\n \"statCard\": {\n \"mode\": \"pure\",\n \"export\": true,\n \"props\": {\n \"label\": { \"kind\": \"string\", \"required\": true },\n \"value\": { \"kind\": \"number\", \"default\": 0 }\n },\n \"root\": \"card\",\n \"elements\": {\n \"card\": { \"type\": \"Card\", \"props\": {}, \"children\": [\"label\", \"slot\"] },\n \"label\": { \"type\": \"Metric\", \"props\": { \"label\": { \"$state\": \"/props/label\" }, \"value\": { \"$state\": \"/props/value\" } } },\n \"slot\": { \"type\": \"ElementSlot\", \"props\": {} }\n }\n }\n }\n}\n```\n\n- `pure` elements may read only their declared `/props/<name>` state; `$item` and `$index` are also legal inside repeated nodes. They cannot invoke any action step. A pure tree may contain at most one leaf `ElementSlot` where consumer children are inserted.\n- `bound` elements may additionally read the defining app's declared queries and actions and use its models. Those references are validated against the defining app, including hidden-column rules. Exported bound elements cannot use `app.navigate`; private bound elements may navigate within their defining app.\n- Prop kinds are `string`, `number`, `boolean`, `date`, or `enum`. An enum prop requires a non-empty `enum: [\"value\", ...]` values array. A literal default and each literal consumer value must match the kind and, for enums, be one of those values. A required prop without a default must be supplied.\n\nReference an element with an `ElementRef` node. Omit `app` for same-app reuse; cross-app references name the defining app id and require `export: true`. `instanceKey` is optional. Consumer `children` are accepted only when the target has an `ElementSlot`:\n\n```json\n{\n \"type\": \"ElementRef\",\n \"props\": {\n \"app\": \"<defining-app-id>\",\n \"element\": \"statCard\",\n \"props\": { \"label\": \"Open issues\", \"value\": 12 },\n \"instanceKey\": \"openIssues\"\n },\n \"children\": [\"details\"]\n}\n```\n\nElement references float to the defining app's current definition. `app` and `element` must be literal strings; dynamic references are not supported. The server rejects reference cycles and expansion deeper than five, missing/private targets, invalid props, and a breaking write to an exported element that other apps reference. Removing or unexporting an exported element, changing its mode, removing a declared prop, changing a prop kind, or adding a required prop without a default is breaking; publish the new contract under a new element name. If consumers are abandoned intentionally, retry the PUT, PATCH, or rollback with `\"forceElementBreak\": [\"elementName\"]`. The named consumers will then render an error once element rendering is available; deleting an entire app is deliberately not compatibility-gated.\n\n### Models\n\nEach column is `{ \"kind\": ..., \"required\"?: boolean, \"default\"?: ..., \"index\"?: boolean, \"enum\"?: string[], \"hidden\"?: boolean }`.\n\n| `kind` | Values and indexing |\n|---|---|\n| `string` | String value; set `index: true` only when equality lookups need it. |\n| `number` | Finite number; never indexed. |\n| `boolean` | Boolean; set `index: true` only when equality lookups need it. |\n| `date` | ISO-8601 string; never indexed. |\n| `enum` | String from the non-empty unique `enum` list; always indexed, without `index: true`. |\n| `json` | Any JSON value (object, array, nested) up to 256 KB serialized by default (`APPS_JSON_COLUMN_MAX_BYTES`); never indexed, and a named query cannot `filter` or `sort` on it. Not allowed for `userConfig` fields or element props. |\n\n`default` must match the column kind (and be one of the enum values). `required: true` rejects missing/null values unless a default supplies the value. `id`, `createdAt`, `updatedAt`, `createdBy`, `updatedBy` — and the sync envelope `source`, `syncedAt`, `stale` — are system columns and reserved names. An app created before the sync envelope that declared ordinary columns with these names surfaces `definitionError` after upgrade until they are renamed: patch in a fresh column with a `{from}` migration directive, then purge the old one. Rows always expose `id`/`createdAt`/`updatedAt`; `createdBy`/`updatedBy` record the acting principal (`user:<id>`, `agent:<id>`, `operator`, or `sync:<source>` for engine writes) and are system-managed on every row write.\n\n### Sources and sync\n\nA model may declare up to 4 named `sources` — one-way inbound projections of an external system into its rows. The `script` connector is THE way to bring external data in (GitHub, Linear, any API): a saved script owns the fetch, its auth placeholders, and its paging. `swarm-tasks` is the one native connector, projecting this swarm's own task pool (`config`: `status`/`tags` comma-lists, `agentId`, `assetKey` namespace prefix, `limit` up to 200 — default 100, `includeHeartbeat`). Synced rows are readable by EVERY principal with `app.use` on the app; an unscoped `swarm-tasks` source publishes task prompts (truncated, secret-scrubbed) to all of them, so scope it with `config.assetKey`/`config.agentId` unless that exposure is intended. A user-invoked sync only ever pulls the invoking user's own requested tasks. Script sources run with their run-as identity's credentials — an agent-owned script runs as its owner and only the owner may wire it; an owner-less catalog (global) script runs as the LEAD, so only the lead or the operator can wire or alter such a source (stored references stay valid with their args and connection pinned).\n\n```json\n{\n \"models\": {\n \"issue\": {\n \"columns\": {\n \"issueKey\": { \"kind\": \"string\" },\n \"title\": { \"kind\": \"string\", \"source\": { \"of\": \"gh\", \"field\": \"title\" } },\n \"openedAt\": { \"kind\": \"date\", \"source\": { \"of\": \"gh\", \"field\": \"created_at\", \"transform\": \"date-parse\" } },\n \"note\": { \"kind\": \"string\" }\n },\n \"sources\": {\n \"gh\": { \"connector\": \"script\", \"scriptId\": \"<script-uuid>\", \"joinKey\": \"issueKey\", \"args\": { \"repo\": \"owner/name\" }, \"connection\": \"github\" }\n }\n }\n }\n}\n```\n\n- **Join key**: each source names a `joinKey` — an owned, non-hidden `string` column carrying the external identity. It must not be `required`, must not declare a `default`, and cannot itself be source-bound. A row belongs to at most ONE source (`row.source`).\n- **Column bindings**: `{ \"of\": \"<sourceName>\", \"field\": \"user.login\", \"transform\"? }` projects a (dotted-path) field of the pulled record into the column on every pass. Transforms and their required column kinds: `slug`/`lower`/`upper` → `string`, `cents` → `number` (×100, rounded), `date-parse` → `date` (ISO). A failed transform nulls that one column and warns; it never fails the pass.\n- **Read-only contract**: source-bound columns and the join key reject every direct write (row create/patch/bulk) with a path-bearing issue — mutate them via the source or a sync refresh. Owned columns on the same model stay writable. Every `required` owned column on a sourced model must declare a `default`, because sync-created rows cannot supply it.\n- **Provenance**: synced rows carry `source` (owner), `syncedAt` (last confirmed presence — sortable), and `stale` (true when a complete pull no longer returned the record; clears on reappearance). `syncedAt` advances on every confirmed row WITHOUT touching `updatedAt`; `updatedAt` moves only when projected data actually changed.\n- **`connection`** (optional, script sources): names a connections-system slug the source depends on. It buys write-time validation plus a preflight before every pull; it does not by itself gate egress. Credentials resolve for the sync run-as identity — the script's owner when it has one, else the lead agent — so global connections always work and agent-scoped ones need matching script ownership. The slug is injected into the script's args as `connection`, letting one generic script serve N connections.\n\n**The canonical sync-script contract** (every sync script, always):\n\n```ts\nexport default async function run(args, ctx) {\n // args = { ...source.args, app: { id }, model: \"<model>\", source: \"<sourceName>\", connection?: \"<slug>\" }\n const records = [{ key: \"42\", fields: { title: \"…\", created_at: \"…\" } }];\n return { records, complete: true }; // or return the bare array — a bare array IS a complete snapshot\n}\n```\n\nReturn `Array<{ key, fields }>` or `{ records, complete? }`. `key` is the external identity the engine joins on `joinKey` (numbers are coerced to strings); `fields` is the bag bindings project from. Return `complete: false` whenever the pull window may have missed records — a paged fetch, a hit `limit`, or client-side filtering of a full page. An incomplete pull skips the stale sweep, so rows outside a narrow window are not falsely marked stale; compute `complete` BEFORE any client-side filtering. Hard cap 500 records per pull (over-cap pulls truncate and count as incomplete). An invalid return shape, thrown error, or non-zero exit fails the pass with zero row churn.\n\nThe seeded catalog script `github-issues-pull` is the worked example (placeholder auth via `[REDACTED:GITHUB_TOKEN]`, PR filtering, `complete` computed before filtering). For scheduled refreshes, point a `targetType: \"script\"` schedule at the seeded `app-sync-run` with `scriptArgs: { \"appId\": \"<id>\", \"model\"?, \"source\"? }`.\n\n**Three refresh doors, one engine**: `POST /api/apps/<id>/sync` (body `{ \"model\"?, \"source\"? }`), a `sync` action kind, and the `app-sync` MCP tool (`ctx.swarm.app_sync` from scripts). `{model?, source?}` fans out to every matching (model × source) pair; each pass reports `{ pulled, created, updated, refreshed, unchanged, markedStale, warnings }`. A pair already syncing in this API process short-circuits with `alreadyRunning: true` instead of pulling twice. Each pair's last-pass status (`lastFinishedAt`, counts, `error?`) comes back as `syncStatus` — keyed `\"<model>:<source>\"` — on `GET /api/apps/<id>` and in `app-get` data, so UI and agents can render \"last synced / last error\" without extra calls.\n\n### Freshness and the refresh button\n\nFreshness renders with the existing column kinds — no special components. Give the table `{ \"key\": \"syncedAt\", \"kind\": \"date\" }` and `{ \"key\": \"stale\", \"kind\": \"badge\", \"tones\": { \"true\": \"warning\" } }` columns, declare a `sync` action, and wire a Button to it:\n\n```json\n{\n \"actions\": { \"refresh\": { \"kind\": \"sync\" } },\n \"pages\": {\n \"main\": {\n \"root\": \"root\",\n \"elements\": {\n \"root\": { \"type\": \"Container\", \"props\": {}, \"children\": [\"refreshBtn\", \"issuesTable\"] },\n \"refreshBtn\": {\n \"type\": \"Button\",\n \"props\": { \"label\": \"Refresh\" },\n \"on\": { \"press\": [{ \"action\": \"app.action\", \"params\": { \"name\": \"refresh\" } }] }\n },\n \"issuesTable\": {\n \"type\": \"Table\",\n \"props\": {\n \"data\": { \"$state\": \"/queries/allIssues/data\" },\n \"columns\": [\n { \"key\": \"title\", \"label\": \"Issue\" },\n { \"key\": \"syncedAt\", \"label\": \"Synced\", \"kind\": \"date\" },\n { \"key\": \"stale\", \"label\": \"Stale\", \"kind\": \"badge\", \"tones\": { \"true\": \"warning\" } }\n ]\n }\n }\n }\n }\n }\n}\n```\n\nA `sync` action answers the script-action state shape (`/actions/refresh` → `running` → `ok`/`error`, result under `result.passes`), so the page's queries refetch when it completes. Use `app-query` to READ rows (named queries may filter on `stale`/`source` and sort by `syncedAt`); use `app-sync` to REFRESH sources; never poll a sync door in a loop — schedule it or give people the button.\n\n### Queries\n\nA named query is:\n\n```json\n{\n \"model\": \"idea\",\n \"filter\": { \"status\": \"open\" },\n \"sort\": { \"column\": \"createdAt\", \"dir\": \"desc\" },\n \"limit\": 100\n}\n```\n\n`filter` is a strict AND of equality checks. A filter may target a declared model column or a system column (`id`, `createdAt`, `updatedAt`, `createdBy`, `updatedBy`, and on synced models `source`, `syncedAt`, `stale`) — filtering on `id` is the universal way to select one row for a detail view, and `{ \"stale\": true }` selects rows a complete pull stopped confirming. A literal value must match the column's kind; date filters compare the stored raw ISO string, not parsed instants. Omit `limit` for the default 200 rows, or set an integer from 1 through 1000. `sort.column` is a non-`json` model column, `createdAt`, `updatedAt`, or `syncedAt`; `dir` is `asc` or `desc`. Query runtime state is `{ data, loading, error }` under `/queries/<queryName>`.\n\nA filter value may instead be exactly `{ \"$param\": \"<name>\" }`. At execution, the caller supplies that name and the server coerces its value to the filtered column's kind before equality matching:\n\n```json\n{\n \"queries\": {\n \"issueDetail\": { \"model\": \"issue\", \"filter\": { \"issueId\": { \"$param\": \"issueId\" } }, \"limit\": 1 }\n }\n}\n```\n\nThe placeholder object must contain only `$param`. Missing caller values fail loudly rather than returning unfiltered rows: HTTP reports 400 and `app-query` returns a tool error listing every missing name. Supplying a param name the query does not reference is also an error. The app UI supplies current declared route params automatically. Direct calls use `app-query({ appId, query: \"issueDetail\", params: { issueId: 42 } })` or `ctx.swarm.app_query({ appId, query: \"issueDetail\", params: { issueId: 42 } })`.\n\n### Custom actions\n\nActions are optional (maximum 20) and are invoked from the page with the `app.action` runtime action.\n\n```json\n{\n \"actions\": {\n \"recalculate\": {\n \"kind\": \"script\",\n \"scriptId\": \"00000000-0000-4000-8000-000000000000\",\n \"args\": { \"mode\": \"fast\" }\n },\n \"triage\": {\n \"kind\": \"task\",\n \"prompt\": \"Triage this idea and report a recommendation\"\n }\n }\n}\n```\n\n| Kind | Contract |\n|---|---|\n| `script` | `scriptId` must identify an existing script; optional `args` are defaults. Invocation input overrides same-named defaults, and the runtime also supplies `app: { id }`. |\n| `task` | `prompt` must be non-empty; omit `agentId` to use default (lead) assignment. Only set `agentId` to a real agent UUID. Invocation `input` is included as context for the task prompt. Spawned tasks carry asset key `shared/app:<appId>/action:<name>/`, so a `swarm-tasks` source with `config.assetKey: \"shared/app:<appId>/\"` pulls back the tasks this app spawned. |\n| `sync` | Optional `model` and `source` narrow which (model × source) pairs refresh; omitting both syncs every pair the app declares. At least one pair must exist. Answers the script-kind state shape with per-pass results under `result.passes`. |\n\n- Invocation state lands at `/actions/<name>` as `{ status, result?, error?, taskId?, taskStatus? }`, where `status` is `\"running\"`, `\"ok\"`, or `\"error\"`.\n\nUse a task action named Tackle when a person should hand one issue row to the swarm. Pass the complete current row under `input.issue`; `{ \"$row\": \"\" }` resolves to the whole row and that context lands in the task prompt.\n\n```json\n{\n \"actions\": {\n \"tackle\": { \"kind\": \"task\", \"prompt\": \"Tackle this issue. Inspect the supplied issue context, do the work, and report the outcome.\" }\n },\n \"pages\": {\n \"main\": {\n \"root\": \"issuesTable\",\n \"elements\": {\n \"issuesTable\": {\n \"type\": \"Table\",\n \"props\": {\n \"data\": { \"$state\": \"/queries/allIssues/data\" },\n \"columns\": [{ \"key\": \"title\", \"label\": \"Issue\" }],\n \"rowActions\": [{\n \"label\": \"Tackle\",\n \"actions\": [{\n \"action\": \"app.action\",\n \"params\": { \"name\": \"tackle\", \"input\": { \"issue\": { \"$row\": \"\" } } }\n }]\n }]\n }\n }\n }\n }\n },\n \"defaultPage\": \"main\"\n}\n```\n\nFor direct MCP calls, `app-query` accepts `{ appId, query, params? }` and returns rows from that declared named query; every supplied param must be referenced by a `$param` filter in that query. Use it when an agent needs to read app state without scraping the UI.\n\nSaved scripts use the generated SDK name `ctx.swarm.app_query({ appId, query, params? })`. Use `app_query` in scripts or workflows that turn current app rows into reports, digests, or follow-up work. Saved scripts also get generated per-app types automatically: each app contributes an `App_<Name>` namespace with one row interface per model (enum columns as literal unions) and a typed `app_query` overload per named query, all visible via `script-query-types`. Scripts can create, list, get, patch, and delete rows with the seven row tools. Actions remain REST/MCP-only and have no script SDK method.\n\n### Pages, routes, and page trees\n\n`pages` is a map of independently validated page trees and `defaultPage` must name one entry. Each page may also declare a display `title` and typed route `params`. On every non-default page the runtime automatically renders breadcrumbs (`<default page title> › <current page title>`, first crumb navigates back) — including in chromeless embeds — so a detail page does NOT need its own back button; give pages good `title`s instead. This complete pattern connects a table row to a typed detail route and its parameterized query:\n\n```json\n{\n \"models\": {\n \"issue\": {\n \"columns\": {\n \"issueId\": { \"kind\": \"number\" },\n \"title\": { \"kind\": \"string\" },\n \"status\": { \"kind\": \"string\" }\n }\n }\n },\n \"queries\": {\n \"allIssues\": { \"model\": \"issue\" },\n \"issueDetail\": {\n \"model\": \"issue\",\n \"filter\": { \"issueId\": { \"$param\": \"issueId\" } },\n \"limit\": 1\n }\n },\n \"pages\": {\n \"issues\": {\n \"title\": \"Issues\",\n \"root\": \"issuesTable\",\n \"elements\": {\n \"issuesTable\": {\n \"type\": \"Table\",\n \"props\": {\n \"data\": { \"$state\": \"/queries/allIssues/data\" },\n \"columns\": [\n { \"key\": \"title\", \"label\": \"Issue\" },\n { \"key\": \"status\", \"label\": \"Status\", \"kind\": \"badge\" }\n ],\n \"rowActions\": [{\n \"label\": \"Open\",\n \"actions\": [{\n \"action\": \"app.navigate\",\n \"params\": {\n \"page\": \"detail\",\n \"params\": { \"issueId\": { \"$row\": \"issueId\" } }\n }\n }]\n }]\n }\n }\n }\n },\n \"detail\": {\n \"title\": \"Issue detail\",\n \"params\": { \"issueId\": { \"kind\": \"number\", \"required\": true } },\n \"root\": \"detail\",\n \"elements\": {\n \"detail\": {\n \"type\": \"DetailList\",\n \"props\": {\n \"data\": { \"$state\": \"/queries/issueDetail/data/0\" },\n \"fields\": [{ \"key\": \"title\", \"label\": \"Issue\" }]\n }\n }\n }\n }\n },\n \"defaultPage\": \"issues\"\n}\n```\n\nDrawer variant: declare a route param on the containing page, set the Drawer `props.param` to that literal param name, and use the same `app.navigate` shape targeting that page with the row id assigned to the Drawer's param. The Drawer then opens from route state without a separate action contract.\n\nApp shell (`layout: \"sidebar\"` at the top level of the definition): every page renders inside a left sidebar that lists the app's pages and a sticky page header. Per page:\n\n- `title`: the sidebar label and the header heading (defaults to the page name).\n- `icon`: one catalog icon name (the list under Component catalog) before the sidebar label; unknown names are rejected.\n- `description`: one line under the header title (at most 280 characters).\n- `headerActions`: the key of one element of this page, rendered in the header's actions slot (right side), e.g. a Refresh `Button` with `on.press: [{ \"action\": \"app.refresh\" }]` or a row `Stack` of buttons. It is a second root: it must exist in the page's `elements` and must NOT also be reachable from `root`. It shares the page's state and actions.\n- `nav: false`: leave the page out of the sidebar. Pages with a `required` param never list (they cannot open without it); open them with `app.navigate`.\n\nThe sidebar lists pages in definition order and marks the current one. Below 768px it folds into a menu button at the left of the header. Crumbs back to the default page show in the header only on pages the sidebar does not list. The shell renders in every view mode: inside the bordered canvas (default view, under the dashboard header that names the app), under the slim bar in `?mode=full`, and as the whole viewport in `?mode=chromeless`, where the sidebar also shows the app name (it is the only navigation inside an iframe). `headerActions` and `nav` without `layout: \"sidebar\"` are rejected; `icon` and `description` are accepted and unused.\n\n```json\n{\n \"layout\": \"sidebar\",\n \"defaultPage\": \"overview\",\n \"pages\": {\n \"overview\": {\n \"title\": \"Overview\",\n \"icon\": \"activity\",\n \"description\": \"Deploys and spend, last 14 days.\",\n \"headerActions\": \"refresh\",\n \"root\": \"root\",\n \"elements\": {\n \"root\": { \"type\": \"Stack\", \"props\": {}, \"children\": [\"spend\"] },\n \"spend\": {\n \"type\": \"Chart\",\n \"props\": {\n \"kind\": \"area\",\n \"data\": { \"$state\": \"/queries/days/data\" },\n \"loading\": { \"$state\": \"/queries/days/loading\" },\n \"x\": \"date\",\n \"xType\": \"time\",\n \"format\": \"currency\",\n \"series\": [{ \"key\": \"spend\", \"label\": \"Spend\" }]\n }\n },\n \"refresh\": {\n \"type\": \"Button\",\n \"props\": { \"label\": \"Refresh\", \"icon\": \"refresh-cw\", \"variant\": \"outline\", \"size\": \"sm\" },\n \"on\": { \"press\": [{ \"action\": \"app.refresh\" }] }\n }\n }\n },\n \"settings\": { \"title\": \"Settings\", \"icon\": \"pencil\", \"root\": \"root\", \"elements\": { \"root\": { \"type\": \"Text\", \"props\": { \"content\": \"…\" } } } }\n }\n}\n```\n\nParam `kind` is `string` by default, or `number` / `boolean`; `required` defaults to false. The names `mode`, `apiUrl`, `apiKey`, `email`, and `name` are reserved. `/apps/<id>` renders `defaultPage`; `/apps/<id>/p/<page>?issueId=42` is the shareable deep link for another page. Browser navigation is client-side, so app state and polled data stay warm across page changes.\n\nWithin each page, `root` names one entry in its non-empty `elements` map. Elements are a flat, single-parent tree: ids are map keys, `children` contains ids (not nested elements), all elements must be reachable from `root`, and cycles, missing children, or shared children are invalid. Element and Form/UI ids are page-local. Element keys are `type`, `props`, `children`, `on`, `visible`, `repeat`, and `watch`; only components with a `default` child slot accept `children` (Stack, Grid, Split, Tabs, Container, Card, Section, and Drawer). `watch` maps state paths to an action step or chain.\n\n## Component catalog (all 35)\n\nProps reject unknown keys. A `{\"$state\":\"...\"}` binding may replace a literal prop value at any depth.\n\nIcons: every `icon` prop (and the `Icon` block) takes one name from a curated lucide set: `plus`, `refresh-cw`, `search`, `filter`, `download`, `upload`, `external-link`, `copy`, `check`, `x`, `trash-2`, `pencil`, `eye`, `calendar`, `clock`, `user`, `users`, `bot`, `git-pull-request`, `git-branch`, `github`, `slack`, `mail`, `link`, `file-text`, `folder`, `database`, `zap`, `sparkles`, `flag`, `star`, `tag`, `alert-triangle`, `info`, `circle-check`, `trending-up`, `trending-down`, `dollar-sign`, `activity`, `rocket`. Any other name is rejected.\n\nTones: Badge, Metric and Progress `tone` take `neutral`, `success`, `active`, `error`, `info`, `pending`, `warning`, or `paused`.\n\n| Component | Required props | Optional props / values |\n|---|---|---|\n| `Stack` | none | Primary layout; `direction: \"column\", \"row\"`, `gap`, `padding: \"none\", \"xs\", \"sm\", \"md\", \"lg\", \"xl\"`; `align: \"start\", \"center\", \"end\", \"stretch\"`, `justify: \"start\", \"center\", \"end\", \"between\"`, `wrap`; `motion: \"rise\"` (default), `\"fade\"`, or `\"none\"` (see Motion below); `fill` (grow to fill a `fill`-aware parent; see Layout below); has the `default` child slot. |\n| `Grid` | none | Responsive `columns`: integer 1 through 6, or `{ base, sm, md, lg }` counts 1 through 6; `gap` uses the Stack spacing values; has the `default` child slot. |\n| `Split` | none | `ratio: \"1-1\", \"1-2\", \"2-1\", \"1-3\", \"3-1\"`, `gap`, `collapseBelow: \"sm\", \"md\", \"lg\"`, `reverse`, `fill` (same contract as Stack); has the positional `default` child slot. |\n| `Divider` | none | `label`; no children. |\n| `Tabs` | `id`, `tabs` | `tabs` entries are `{ key, label?, icon?, count? }` (`count` is a number shown as a small pill); `defaultTab`; `variant: \"line\"` (default) or `\"segmented\"` (a compact segmented control, same state and warm panels); has the positional `default` child slot. |\n| `Container` | none | Legacy layout primitive; prefer Stack. `direction: \"row\", \"column\"`, `gap: \"none\", \"sm\", \"md\", \"lg\"`; has the `default` child slot. |\n| `Card` | none | `title`, `description`; has the `default` child slot. |\n| `Heading` | `text` | `level: \"h1\", \"h2\", or \"h3\"`. |\n| `Text` | `content` | `tone: \"default\" or \"muted\"`. |\n| `Markdown` | `content` | Rendered Markdown for help, instructions, and rich prose; no children. A link to a GitHub PR, issue, commit or repo, a dashboard task, agent, session or app, or an agent-fs file renders as a chip (icon plus short label), like agent output in a session; `[text](url)` keeps its text. |\n| `SearchInput` | `id` | `placeholder`, `label`, `shortcut` (one key, usually `\"/\"`: shows a keycap and focuses the field); writes debounced text to `/ui/<id>/value`; no children. |\n| `Select` | `id`, `options` | `options` are strings or `{ value, label?, icon?, hint? }`; `placeholder`, `label`, `clearable`, `searchable` (type to filter; on by default past 8 options), `searchPlaceholder`, `multiple`, `defaultValue` (seeds `/ui/<id>/value` once, before any interaction; a one-entry array with `multiple`); writes a string or null to `/ui/<id>/value`, or with `multiple` a string array (empty = nothing picked); no children. |\n| `NumberInput` | `id` | `label`, `placeholder`, `min`, `max`; a text field with a decimal keyboard that writes the parsed number to `/ui/<id>/value` on every change (no debounce), or null when the field is empty; non-numeric text (a bare `-` mid-edit, letters) leaves the stored value untouched; `min`/`max` clamp the stored value and the visible text snaps to it when the field loses focus; no children. |\n| `Chips` | `id`, `options` | Toggle chips for quick filters. `options` are strings or `{ value, label?, icon? }`; `multiple`; `label` (group name for screen readers). Writes a string or null to `/ui/<id>/value`, or a string array with `multiple`; pressing the selected chip clears it. |\n| `Button` | `label` | `variant: \"default\", \"secondary\", \"outline\", \"ghost\", \"destructive\", or \"destructive-outline\"` (use `destructive-outline` for standalone deletes); `disabled` (constant or bound boolean); `busyWith: \"<actionName>\"` swaps the label for a spinner while that custom action's `/actions/<name>/status` is `\"running\"` (presses are ignored), then shows a check and `successLabel` for about 1.5s when it turns `\"ok\"`; `icon`, `iconPosition: \"start\" or \"end\"`; `size: \"sm\", \"default\", or \"lg\"`; `shortcut` (one key, shown as a keycap, presses the button); `hint` (tooltip); dispatch with element-level `on.press`. |\n| `Metric` | `label`, `value` | The dashboard stat tile. `value` is string or number (empty renders an em dash); bind `loading` to `/queries/<name>/loading` for a skeleton while the query loads; `icon` with `tone` tinting its tile; `detail` (a line under the value); `trend: { direction: \"up\", \"down\", or \"flat\", label }`; `info` (explanation tooltip next to the label). `sparkline`: a small trend line under the value in the `tone` color, from an array of numbers (`null` is a gap) or from rows (bind `/queries/<name>/data`) read through `sparklineKey`; fewer than two points draws nothing. |\n| `Chart` | `kind`, `x`, `series` | `kind: \"line\", \"area\", or \"bar\"`; bind `data` / `loading` / `error` to a named query like Table. `x` is the row field on the x axis; `xType: \"category\"` (default, row order) or `\"time\"` (ISO date or epoch ms, sorted, date ticks; rows whose `x` does not parse are dropped). `series`: 1-8 `{ key, label?, color? }`, `color` one of `chart-1`..`chart-5`, `primary`, `success`, `warning`, `error`, `info`, `muted` (default palette, in order: `primary`, `chart-2`..`chart-5`). `stacked` stacks area and bar series (lines never stack). `format: \"number\"` (default), `\"currency\"` (with `currency`, an ISO code, default `USD`) or `\"percent\"` (values are ratios: 0.42 is 42%). Tooltip on hover; the legend shows with two or more series (`legend` forces it on or off). `height` 120-640 px (default 240); `emptyMessage` (default \"No data yet\"). `x` and every `series[].key` must be columns of the bound query's model. Wrap it in a `Card` for a title. |\n| `Alert` | `message` | `title`, `tone: \"info\", \"success\", \"warning\", or \"error\"`, `icon` (overrides the tone icon), `actionLabel` (a button inside the callout that emits `press`; wire it with `on.press`). |\n| `Badge` | `text` | `text` is string or number; `tone`; `icon` replaces the dot; `variant: \"tag\"` (default uppercase chip), `\"status\"` (sentence-case pill), `\"count\"` (numeric pill), or `\"beta\"` (the BETA tag); `status` (a lifecycle value renders the dashboard status chip); `hint` (tooltip; the beta tag's explanation). |\n| `Icon` | `name` | `size: \"sm\", \"md\", or \"lg\"`, `tone: \"default\", \"muted\", \"success\", \"warning\", \"error\", or \"info\"`, `label` (accessible name; decorative without it). |\n| `Progress` | `value` | `max` (default 100), `tone`, `label`, `variant: \"bar\"` (default) or `\"ring\"` (the dashboard progress ring; ignores `tone`), `showValue` (default true: percent for a bar, `value / max` for a ring). |\n| `EmptyState` | `title` | `icon` (default inbox), `body`, `actionLabel` (a button that emits `press`; wire it with `on.press`). |\n| `CopyButton` | `value` | `value` is string or number; `label` is the visible text, icon-only without it. Renders nothing for an empty value. |\n| `Kbd` | `keys` | Keycaps, one per string (`[\"⌘\", \"K\"]`). Display only. |\n| `Skeleton` | `shape` | `shape: \"line\", \"block\", \"rows\", \"metric\", or \"card\"`; `count` (1-20: lines, rows, tiles, or cards); `height` (px, `block` only, default 128). Show it with `visible` bound to a query's `loading`. |\n| `Spinner` | none | `variant: \"ring\", \"ellipsis\", or \"bars\"` (default: the dashboard spinner), `size: \"sm\" or \"md\"`, `label` (visible text and accessible name). |\n| `AvatarStack` | `users` | `users` are display names (initials avatars); `max` (default 4) before a `+N` count. Hover lists every name. |\n| `Section` | `title` | `description`, `collapsible`, `defaultOpen` (default true); has the `default` child slot. |\n| `Table` | `columns` | `data`, `loading`, `refreshing`, `error`, `emptyMessage`, `emptyState`, `rowActions`, `id`, `selectable`, `bulkActions`, `filterable`, `clearState`, `onRetry`, `onRowClick`, `selectedId`, `rowId`, `mobile`, `mobileFields`, `search`, `filters`; see below. |\n| `Form` | `id`, `fields`, `onSubmit` | `title`, `submitLabel`; see below. |\n| `Drawer` | `param` | `title`, `description`, `side: \"right\" or \"left\"`, `size: \"sm\", \"md\" (default), \"lg\", or \"xl\"` (about 480/660/900/1010px at 1440px; grows with the viewport up to 640/960/1280/1600px; full width on phones), `actions` (sticky footer buttons; see below); has the `default` child slot. |\n| `DetailList` | `fields` | `data`, `emptyMessage`, `columns: 1 or 2`, `loading` (bind `/queries/<name>/loading` for skeleton fields while loading); renders one record without edit controls; see below for field kinds. |\n| `CardGrid` | `titleKey` | `data`, `loading`, `error`, `emptyMessage`, `imageKey`, `fields`, `columns`, `onClick`; one card per row for record browsers; see below. |\n| `Kanban` | `columnField`, `columns`, `titleField` | `data`, `loading`, `cardFields`, `idField` (default `id`), `onMove`, `onCardClick`; see below. |\n| `Calendar` | `startField`, `titleField` | `data`, `loading`, `endField`, `idField`, `onSelect`; read-only month grid; see below. |\n| `ContributionGraph` | none | `data`, `loading`, `dateField` (default `date`), `countField`, `days` (7-730, default 365); read-only activity heatmap. |\n| `Tree` | `id`, `nodes` | `label`, `maxHeight` (default `480px`), `fill`; collapsible outline of a doc-shaped value that writes the clicked node key to `/ui/<id>/value`; see below. |\n| `SchemaForm` | `id`, `schema` | `value`, `baseDoc`, `nodeKey`, `onChange`, `fill`; form generated from a JSON schema's `properties`, mirrored to `/ui/<id>/value`; see below. |\n\nTable details:\n\n- `columns[]`: `{ key, label?, kind?, tones?: {value: badgeTone}, width?: number, pinned?: \"left\" or \"right\", align?: \"start\" or \"end\", truncate?: \"end\" or \"middle\", icon?, tooltip?: \"<row field>\", hint?: string, popover?: { title?, fields, trigger? }, href?: \"<row field>\", linkLabel?: \"<template>\", max?: number, format?: \"<template>\", onChange?: chain, filter?: \"values\" or \"text\" or false, muted?: string[] }`. `kind` is `text`, `string`, `enum`, `number`, `boolean`, `date`, `badge`, `status`, `user`, `agent`, `relative`, `duration`, `progress`, `copy`, `switch`, `checkbox`, `link`, or `json`; `string` and `enum` render as text, and `json` renders a truncated single-line `JSON.stringify` preview. Pin id/actions columns so they survive horizontal scroll on narrow viewports.\n - `status`: lifecycle values (`pending`, `in_progress`, `running`, `completed`, `failed`, `cancelled`, `paused`, `reviewing`, ...) render the dashboard status chip with its icon; other values use `tones` like `badge`.\n - `user` / `agent`: avatar plus name. `relative` (and `date`): smart time, exact time on hover. `duration`: milliseconds as `1m 23s`. `progress`: a bar against `max` (default 100). `copy`: the value plus a copy button. `link`: a smart link (see Smart links, tooltips and popovers below); any other http(s) URL opens in a new tab and other values render as text.\n - `switch` / `checkbox`: a toggle or a checkbox bound to a boolean column. `onChange` runs with `$row` = the row with this column already set to the new value, e.g. `[{ \"action\": \"app.mutate\", \"params\": { \"model\": \"m\", \"op\": \"update\", \"rowId\": { \"$row\": \"id\" }, \"values\": { \"enabled\": { \"$row\": \"enabled\" } } } }]`. Without `onChange` the control is read-only. Each toggle is a model write, so to pick rows for a bulk action use `selectable` (below), not a boolean column.\n - Numbers, durations and progress right-align by default. `truncate: \"middle\"` keeps both ends of ids and paths. `icon` shows in the header; `tooltip` names a row field shown in a styled tooltip on the cell (when the cell is plain text that gets cut off, the tooltip shows its full text without any config).\n - `format`: a `{{field}}` template that combines several row fields into one cell, e.g. `\"{{name}} ({{status}})\"`. Placeholder names match `[\\w.]+` (letters, digits, `_` and `.`; no hyphens or spaces). Each placeholder reads that row field as-is (a dotted name such as `{{owner.name}}` is a literal column name, not a nested path); a missing or null field becomes an empty string and an object or array becomes a JSON preview cut to 120 characters. The whole cell is capped at 500 characters. A templated column ignores `kind`, shows the same text in the phone list, and sorts by the composed text. `search` and `filters` still read the column's `key`.\n - `muted: [\"none\", \"no\"]`: those cell values (matched case-insensitively) render as a quiet `—` instead of a pill or text, for columns that are mostly `none` / `no`. The value stays in the data, in the filter list, as a hover title and for screen readers; the phone list leaves it out. Not applied to `switch` / `checkbox` cells.\n- `selectable` + `id`: a leading pinned checkbox column. The header checkbox selects every row left after `search` / `filters` (checked, unchecked or indeterminate; clicking it again clears those rows), and shift-click selects a range in the order shown. The selection is client state at `{ \"$state\": \"/ui/<id>/selected\" }`, an array of row ids (the `rowId` field, default `id`, as strings). It is never a model write and is not shared with other viewers. `id` is a literal like `SearchInput.id`, and the validator requires it with `selectable` or `bulkActions`. Selected rows that disappear from the data drop out of the selection.\n- `bulkActions[]`: `{ label, variant?, icon?, confirm?, actions }`, the `rowActions` shape without `placement`; a non-empty list implies `selectable`. A bar under the table shows `N selected`, the buttons and Clear while the selection is non-empty. Chains have no `$row`; pass the ids with `{ \"$state\": \"/ui/<id>/selected\" }`, e.g. `{ \"action\": \"app.action\", \"params\": { \"name\": \"enqueue\", \"input\": { \"prs\": { \"$state\": \"/ui/prTable/selected\" } } } }`. Confirm rules match `rowActions`; the dialog always adds the selection size (`Applies to 3 selected rows.`). The selection is locked while the chain runs. It clears (only the rows the chain acted on) once every step succeeded, waiting for a task-backed `app.action` to finish; a failed `app.mutate` or a failed task stops the chain and keeps the selection for a retry.\n- `filterable: true` + `id`: built-in column filters. Each filterable column gets a filter button in its header: `badge`, `status`, `enum`, `boolean`, `user` and `agent` columns open a checkbox list of the distinct values with row counts (the counts follow the other active filters, so a second tick shows what it adds); a column with no kind (or `text` / `string`) opens a contains-text field; numbers, dates, links and `format` columns get none. `columns[].filter` overrides per column: `\"values\"` or `\"text\"` (works without `filterable`, and is how a `format` column opts in), or `false` to opt out. Active filters show as removable pills above the table with Clear all. The state is client state at `{ \"$state\": \"/ui/<id>/filters\" }`, an object with one entry per column (`/ui/<id>/filters/<column>`): a string array for a list, a string for text; other elements can read it. It composes with `search` and `filters`: a row must pass all three. Below 768px the header menus become one Filters button above the card list. `id` is required (the validator checks it).\n- `clearState`: state paths the Table's Clear filters button and the pills' Clear all also reset, e.g. `[\"/ui/prSearch/value\"]` for the `SearchInput` feeding `search`. Only `/ui/<id>/...` paths of controls on the page. Without it, those controls keep their value and the no-match state only offers Clear filters for the built-in filters.\n- Loading and errors: the first load (no rows yet) shows a skeleton shaped like the table, with its header labels. `loading` (`/queries/<name>/loading`) is the first load only. Bind `refreshing` to `{ \"$state\": \"/queries/<name>/fetching\" }` (true during any fetch, including the 5s poll and `app.refresh`) and a refetch with rows showing runs a slim bar along the top edge, on phones too, and never dims, covers or blanks a row. A failed query shows the error callout with a Retry button; `onRetry` is the chain it runs (default `[{ \"action\": \"app.refresh\" }]`, which re-runs every query on the page). With rows already loaded the callout sits above the stale rows; with none, it is the whole state (no empty message). A search or filter that hides every row shows \"No rows match\" with a Clear filters button; with header filters the table stays in place (header and open filter input included) and the button sits under it.\n- Smart links, tooltips and popovers (Table, DetailList, CardGrid, Markdown):\n - A `link` cell (Table `kind: \"link\"`, DetailList and CardGrid `kind: \"link\"`) shows a chip with an icon and a short label when its value is a GitHub PR, issue, commit or repo URL (`agent-swarm#2605`, `agent-swarm@a1b2c3d`, `owner/repo`), the GitHub shorthand `owner/repo#N` or `owner/repo@sha`, a dashboard task, agent, session, app, page or workflow URL (shown by its name once the dashboard knows it, else `Task 1f6feea0`), or an agent-fs file. GitHub links open in a new tab; dashboard links stay in the app. Any other http(s) URL is a plain external link, and any other value is text. Only `github.com` links are GitHub links.\n - `href: \"<row field>\"` (Table column, DetailList or CardGrid field) takes the URL from another row field, so a cell can show one field and link with another: `{ \"key\": \"number\", \"label\": \"PR\", \"format\": \"{{repo}}#{{number}}\", \"href\": \"url\" }` shows `agent-swarm#2605` as a PR chip. With `href` the cell's own text (or `format`) is the label. `linkLabel: \"<template>\"` (same `{{field}}` rules as `format`) sets the label instead, e.g. `\"Lead review\"` on a `kind: \"link\"` column.\n - `hint: \"<text>\"` on a column adds a header tooltip. A header cut off by the column width also shows its full label in the tooltip, with no config.\n - `popover: { title?: \"<template>\", fields: [...], trigger?: \"hover\" | \"click\" }` on a Table column opens a popover from the cell that lists up to 12 fields of the row, in the DetailList field shape (`{ key, label?, kind?, tones?, href?, linkLabel? }`, any DetailList kind). It opens on hover or keyboard focus by default and lets the pointer move into it; `trigger: \"click\"` toggles it from the cell; on a cell with its own controls (link, copy, switch) it opens from a separate Details button beside the content. In the phone list, link columns render as chips under the row and each popover column gets a Details button that opens on tap. Use it for detail that does not fit a column, such as a merge reason or CI status. `key` and `href` must name model columns.\n- `onRowClick`: action chain with `$row` / `$rowIndex`, run when a row is clicked (or Enter on a focused cell). Pair it with `app.navigate` that sets a Drawer param, and bind `selectedId` to `{ \"$state\": \"/route/params/<param>\" }` so the open row stays highlighted. `rowId` names the id field (default `id`).\n- Phones (below 768px): the table renders as a card list. `mobileFields: { title, subtitle?, meta?: string or string[], status? }` picks the columns; by default the first text column is the title and the first `status`/`badge` column the chip. `mobile: \"scroll\"` keeps the grid; it is the default when the table has `rowActions` but no `onRowClick`. With `selectable`, each phone card gets a checkbox beside it and a Select all row sits above the list. An editable `checkbox` / `switch` column (one with `onChange`) becomes a real control beside the card, not a line of text.\n- `emptyState: { icon?, title, body? }` replaces the plain empty message. A search or filter that hides every row shows its own \"No rows match\" state.\n- `pagination`: boolean; defaults to auto-enabling past 200 rows (set `false` to force one scroll region). `density: \"compact\"` tightens row height for dense readouts.\n- `rowActions[]`: `{ label, variant?, icon?, placement?: \"inline\" or \"menu\", confirm?, actions }`. `placement: \"menu\"` moves the action into the row's More menu. Variants add `destructive-outline` to the Button variants. `destructive` and `destructive-outline` confirm by default; customize with `{ \"title\": ..., \"description\": ..., \"confirmLabel\": ... }`, or use a bare `confirm` string as the dialog description (use `confirm: false` only for a reversible action).\n- `search`: optional string; case-insensitive substring matching across the listed string and number columns. Bind a SearchInput value for client-side search.\n- `filters`: optional record of per-column string, number, boolean, null, or array values. An array means \"the cell is one of these\" (what a `multiple` Chips or Select writes). Null, empty strings, empty arrays, or absent values disable one filter. Bind Select or Chips values for client-side filters.\n\nKanban details:\n\n- One card per `data` row, grouped by the row's `columnField` value. `columns[]` are plain strings or `{ id, label? }`, in display order; rows matching no column are hidden.\n- `cardFields[]` uses the DetailList field shape (`{ key, label?, kind?, tones? }`, same kinds) for extra lines under the title.\n- `onMove` is an action chain run when a card is dropped in another column. `$row` is the moved row with `columnField` already set to the new column: `[{ \"action\": \"app.mutate\", \"params\": { \"model\": \"deal\", \"op\": \"update\", \"rowId\": { \"$row\": \"id\" }, \"values\": { \"stage\": { \"$row\": \"stage\" } } } }]`. Without `onMove`, cards cannot be dragged.\n- `onCardClick` is an action chain with `$row`; pair it with `app.navigate` and a `Drawer` to open a card.\n\nCalendar details:\n\n- `startField` / `endField` hold ISO dates, ISO datetimes, or epoch ms. An event shows on every day from start to end; without `endField` it shows on its start day.\n- Each Calendar keeps its own visible month (prev/next controls in its header). `onSelect` is an action chain with `$row`, run when an event is clicked.\n\nContributionGraph details:\n\n- Buckets `data` rows by the calendar day of `dateField` over the trailing `days`. Each row counts 1, or adds its numeric `countField` when set.\n\nTree details:\n\n- `nodes` is a doc-shaped value: `{ root: string | string[], elements: { <key>: { type, children?: string[] } } }`, the json-render flat element map. Usually bind it to a json column: `{ \"$state\": \"/queries/<name>/data/0/<column>\" }`. A malformed or absent value renders an empty state; a `children` key missing from `elements` shows as `key — ?`. Outlines are cut at 2,000 rows with a notice; branches deeper than 32 levels keep a disabled chevron.\n- Each row shows `key — type`. Clicking a row writes its key to `/ui/<id>/value`, and the row bound to that path renders selected; read the selection with `{ \"$state\": \"/ui/<id>/value\" }`. The Tree never writes `null`: when the selected key leaves the doc (a refetch, an edit) the stored key stays and no row renders selected. Selection and collapse are keyed by node key, so a key reachable through two parents selects and collapses in both places.\n- Rows scroll inside `maxHeight` (default `480px`). Set `fill: true` inside a `fill` Stack or Split pane to grow to that height instead and scroll within it (ignores `maxHeight`).\n\nSchemaForm details:\n\n- `schema` is a JSON schema object held in state (usually `{ \"$state\": ... }`). Each entry of `properties` becomes one control: `type: \"boolean\"` a switch, `enum` of strings a select, `type: \"number\"` or `\"integer\"` a number input, anything else a text input. `description` is the tooltip. Fields seed from `value[key]`, else the property `default`. At most 100 fields and 200 enum options render. `id` must match `[A-Za-z0-9_-]+`. Rebinding `schema` resets the form.\n- Typing updates `/ui/<id>/value` with the draft object; switches and selects commit at once and text and number inputs commit on blur. Each commit runs `onChange` with `$form` = the draft.\n- Nested document editing: bind `baseDoc` to a doc-shaped value (`{ root, elements }`) and `nodeKey` to an element key, such as a Tree's `{ \"$state\": \"/ui/<tree>/value\" }`. The form then edits `baseDoc.elements[nodeKey].props`, and `/ui/<id>/value` holds the whole doc with the edit merged in, so one `app.mutate` with `values: { <jsonColumn>: { \"$state\": \"/ui/<id>/value\" } }` persists it. Props the schema does not list are kept. Edits the query has not returned yet stay applied, so two quick edits on different nodes both survive. A `nodeKey` that is not a key of `elements` falls back to plain mode, and a `baseDoc` over 5,000 elements is not editable. Typing writes `/ui/<id>/value` on every keystroke, before the commit on blur, so another component's `app.mutate` that reads that path can persist half-typed text; persist from the SchemaForm's own `onChange`.\n\nForm details:\n\n- `fields[]`: `{ name, label?, kind?, options?: string[], placeholder?, required? }`; `kind` is `string`, `text`, `number`, `boolean`, `date`, or `enum`, and enum fields need `options`.\n- Values live at `/forms/<formId>/<fieldName>`. `onSubmit` is an action chain.\n- The submit button shows a pending spinner while the chain runs, and `app.mutate` failures in the chain render inline under the fields (not the page banner) — no extra wiring needed.\n\nDrawer details:\n\n- `param` must name a param declared on the containing page. The drawer is open exactly when `/route/params/<param>` has a non-empty value, so its open state survives refresh and is shareable. Its children mount only while open; closing it clears that param with history replacement.\n- `actions[]`: `{ label, variant?, icon?, confirm?, actions }`, rendered as buttons in a sticky footer under the scrolling body. Confirmation follows Table `rowActions`: destructive variants confirm by default, and a chain with an `app.mutate` delete always confirms. Chains have no `$row`; address the open record with `{ \"$state\": \"/route/params/<param>\" }`, for example `{ \"action\": \"app.mutate\", \"params\": { \"model\": \"order\", \"op\": \"delete\", \"rowId\": { \"$state\": \"/route/params/panel\" } } }`. Prev/next record navigation is not available.\n\nDetailList details:\n\n- `fields[]`: `{ key, label?, kind?, tones? }`. Kinds reuse Table formatting (`text`, `string`, `number`, `boolean`, `date`, `badge`, `enum`) and the Table cell renderers (`status`: lifecycle chip or `tones` pill; `user`: avatar plus name; `relative`: smart time, exact on hover; `copy`: value plus copy button; `link`: a smart link from the value, or from the row field named by `href`, with `linkLabel` as an optional label template), and add `code` for a monospace block and `json` for a collapsible JSON tree (objects, or a string holding JSON). Bind `data` to one record, commonly `/queries/<detailQuery>/data/0`.\n\nMotion details:\n\n- Every `Stack` fades its direct children in and lifts them 4px over 200ms on first paint, staggered 30ms (capped at the 10th child). It never replays on the 5s data poll. A Stack nested inside another one does not add its own entrance. `motion: \"fade\"` drops the lift; `motion: \"none\"` turns it off. Viewers with reduced motion get a 150ms fade.\n\nCardGrid details — the visual counterpart to Table for record browsers (projects, documents, media):\n\n- `titleKey` (required) picks the row field shown as the card title (an object value shows a JSON preview; titles are capped at 500 characters).\n- `imageKey` (optional) picks a row field holding an absolute http(s) image URL and adds an image tile to every card. When it is set, a non-URL value, a missing value, or a failed load shows a placeholder tile. Omit it for text-only cards with no tile.\n- `fields[]`: `{ key, kind?, tones?, href?, linkLabel? }`. `kind` is `text`, `string`, `enum`, `number`, `boolean`, `date`, `badge` (with `tones`), `link` (a smart link, with `href` / `linkLabel`), or `json` (no `label`, no `format`). A field with no `kind` whose value is an object renders like `json`. They render as an unlabeled `·`-joined meta line under the title, e.g. a `date` field for \"created\" and a `text` field for the author.\n- `columns`: same responsive shorthand as `Grid.columns` (default `{ \"base\": 1, \"sm\": 2, \"md\": 3 }`).\n- `onClick`: an action chain with `$row` / `$rowIndex`, run when a card is clicked or activated with Enter or Space. Commonly `app.navigate` into a detail page, the CardGrid equivalent of Table's `onRowClick`.\n- Bind `data` / `loading` / `error` to a named query like Table. Loading shows skeleton cards, an error shows a callout, and no rows shows `emptyMessage`.\n- It renders 200 cards at a time with a Show more button below the grid that reveals the next 200.\n\nShortcut details:\n\n- `Button.shortcut` and `SearchInput.shortcut` are one key. Letters and digits match without Shift; symbols such as `/` and `?` match as typed. They do nothing while focus is in a text field, while Ctrl, Cmd, or Alt is held, or while a dialog or menu is open (unless the control is inside it, such as a Button in an open Drawer).\n\n## Layout & interactivity\n\nFor a multi-page app that should feel like a product (a sidebar of pages, a sticky title bar with actions), set `layout: \"sidebar\"` (see Pages, routes, and page trees) instead of building navigation out of Tabs or button rows. Pair `Metric` tiles (with `sparkline`) in a `Grid` with `Chart`s inside `Card`s for dashboards.\n\nUse `Stack` as the primary page and section layout; `Container` is the legacy two-prop primitive retained for existing pages. Stack supports vertical or horizontal flow, shared spacing, alignment, justification, wrapping, and padding; row Stacks (filter bars, button rows) should set `collapseBelow: \"sm\"|\"md\"|\"lg\"` so they stack vertically on phones. Use `Grid` for responsive card or metric strips: a bare column count is responsive shorthand (1 column on phones, 2 from `sm`, the count from `md` up), or pin breakpoints explicitly with `{ \"base\": 1, \"md\": 2, \"lg\": 3 }`. `Grid` and `Split` also accept `padding` on the shared spacing scale.\n\n`Stack` and `Split` size to their content by default, so a page scrolls as a whole. Set `fill: true` to make one grow to fill the remaining height of a `fill`-aware parent (another `fill` Stack or Split) instead; chain it from the page root down through every container on the path to the element that should scroll, and that element scrolls within whatever height is left while the page itself does not. A non-`fill` sibling (a toolbar, a header) keeps its natural height and the `fill` sibling absorbs the rest. A `fill` Split stretches both panes to the full row height, so nesting a `fill` Split inside one pane of another `fill` Split is the way to build a three-or-more column viewport-height layout (`ratio` is only ever two panes).\n\n`Split` and `Tabs` children are positional. For Split, `children[0]` is the first pane, `children[1]` is the second, and extra children append inside the second pane. Below `collapseBelow`, panes stack; `reverse` changes only that narrow-layout stacking order. For Tabs, `children[i]` is the body for `tabs[i]`; keep both arrays in the same order and with the same count. Inactive tab children stay mounted but hidden, so Tables keep polling. Use `Divider` to separate sections and `Markdown` for richer explanatory content.\n\nSearchInput, Select, NumberInput, Chips, and Tree are client-side controls: each needs a literal `id` and writes state under `/ui/<id>/value` (Tree writes the clicked node key; a `selectable` Table writes its selected row ids to `/ui/<id>/selected`); Tabs writes its active key to `/ui/<id>/tab`. Bind those values into a Table's `search` and `filters` props. This filters already-polled rows locally; it does not alter or re-run the named query.\n\n```json\n{\n \"filters\": { \"type\": \"Stack\", \"props\": { \"gap\": \"sm\" }, \"children\": [\"query\", \"status\"] },\n \"query\": { \"type\": \"SearchInput\", \"props\": { \"id\": \"ideaSearch\", \"placeholder\": \"Search ideas\" } },\n \"status\": { \"type\": \"Select\", \"props\": { \"id\": \"ideaStatus\", \"options\": [\"open\", \"done\"] } },\n \"ideas\": {\n \"type\": \"Table\",\n \"props\": {\n \"data\": { \"$state\": \"/queries/allIdeas/data\" },\n \"columns\": [{ \"key\": \"title\" }, { \"key\": \"status\" }],\n \"search\": { \"$state\": \"/ui/ideaSearch/value\" },\n \"filters\": { \"status\": { \"$state\": \"/ui/ideaStatus/value\" } }\n }\n }\n}\n```\n\n`visible` accepts a boolean, a `$state` truthiness binding, comparisons, and logical groups. Put exactly one comparison key in each condition object. The renderer evaluates the first matching key in fixed priority order (`eq`, `neq`, `gt`, `gte`, `lt`, `lte`; otherwise truthiness), so additional comparison keys in the same object are ignored. Use `$and` / `$or` arrays to combine conditions. `not` is a negation FLAG inside a condition object (`\"not\": true`), never a wrapper around one — `{ \"not\": { \"$state\": … } }` is invalid and the validator rejects it. The absent-record pattern (e.g. an alert when a detail query matched nothing) is `{ \"$state\": \"/queries/<q>/data/0/id\", \"not\": true }`:\n\n```json\n[\n { \"$state\": \"/route/params/issueId\", \"gt\": 0 },\n {\n \"$and\": [\n { \"$state\": \"/route/page\", \"eq\": \"detail\" },\n { \"$state\": \"/route/params/panel\", \"neq\": \"hidden\" }\n ]\n }\n]\n```\n\n## Bindings, sentinels, and action chains\n\nUse this exact query binding shape; do not invent `$query`, `$item`, or template strings:\n\n```json\n{\n \"data\": { \"$state\": \"/queries/allIdeas/data\" },\n \"loading\": { \"$state\": \"/queries/allIdeas/loading\" },\n \"error\": { \"$state\": \"/queries/allIdeas/error\" }\n}\n```\n\nValid `$state` roots are:\n\n- `/queries/<declaredQuery>/...`\n- `/forms/<formId>/...`, where a `Form` element has that literal `props.id`\n- `/ui/<id>/...`, where a SearchInput, Select, Chips, or Tabs element has that literal `props.id` (SearchInput, Select, and Chips use `/value`; Tabs uses `/tab`)\n- `/actions/<declaredAction>/...`\n- `/route/page` for the active page name\n- `/route/params/<declaredParam>` for a param declared on the current page\n\n`/route` is mirrored as `{ page, params }`. Only declared params appear. Values are coerced by their declared kind: `number` becomes a number when possible; boolean strings `true`/`1` become true; failed number coercion remains the raw string.\n\nOnly inside action-chain `params` (`on.<event>`, `Table.rowActions[].actions`, `Table.bulkActions[].actions`, or `Form.onSubmit`) these scoped sentinels are valid, recursively inside objects and arrays:\n\n| Sentinel | Resolves to |\n|---|---|\n| `{ \"$row\": \"id\" }` | Current Table row's `id`; another column name selects that field. |\n| `{ \"$row\": \"\" }` | Entire current Table row. |\n| `{ \"$rowIndex\": true }` | Current Table row index. |\n| `{ \"$form\": \"title\" }` | One current Form value. |\n| `{ \"$form\": \"\" }` | All current Form values. |\n| `{ \"$state\": \"/queries/allIdeas/data\" }` | Current value at a valid app state path, including action state such as `/actions/refreshIssues/status`. |\n| `{ \"$chain\": \"leafTaskId\" }` | One chain-scope value, published by a component that runs a task chain; it carries `leafTaskId` and `newTaskId`. Where no chain scope is published, the sentinel is left in place and the action fails instead of silently dropping the parent. |\n| `{ \"$chain\": \"\" }` | The whole chain scope. |\n\nEach sentinel object must contain exactly the single key shown.\n\nAn action-chain step is `{ \"action\": \"<type>\", \"params\": {...} }`. Available action types:\n\n- `app.mutate`: `{ model, op, rowId?, values?, formId? }`, where `op` is `\"create\"`, `\"update\"`, or `\"delete\"`. `update`/`delete` require `rowId` (usually `{ \"$row\": \"id\" }`, or `{ \"$state\": \"/route/params/<param>\" }` in a Drawer footer); literal `values` keys must be model columns. Successful mutation refetches all queries on that model.\n- `app.refresh`: `{ query? }`; omit `query` to refetch all, or name a declared query.\n- `app.action`: `{ name, input?, parentTaskId? }`; `name` must be declared in definition `actions`. For a task-kind row action, pass whole-row context with `input: { issue: { \"$row\": \"\" } }`. `parentTaskId` chains the created task under an existing one for task-kind actions (typically `{ \"$chain\": \"leafTaskId\" }`; a literal or `$state` task id also works); a script or sync action rejects it with 400.\n- `app.navigate`: `{ page, params? }`; `page` must be declared, supplied keys must be params of the target page, and every required target param must be supplied. `params` replace the current route params wholesale and may contain action sentinels. Navigation pushes history, so browser Back returns to the previous page/params; only `mode` is preserved automatically.\n- `ui.toast`: `{ message, description?, tone?, undo? }`, where `tone` is `\"success\"`, `\"error\"`, `\"info\"` (default), or `\"warning\"`. `undo: { label?, actions }` adds an Undo button (default label `Undo`) that runs `actions` as a chain; its steps are validated like any chain. Put it after the step it confirms, e.g. a row delete followed by `{ \"action\": \"ui.toast\", \"params\": { \"message\": \"Order deleted\", \"undo\": { \"actions\": [{ \"action\": \"app.mutate\", \"params\": { \"model\": \"order\", \"op\": \"create\", \"values\": { \"title\": { \"$row\": \"title\" } } } }] } } }`. Undo params resolve `$state` when Undo is pressed; `$row` / `$form` resolve when the toast is shown.\n- `swarm.sdk`: `{ sdk, args? }`; invokes a catalog-supported Swarm browser SDK method with the viewer's bearer.\n- `swarm.call`: `{ method, endpoint: \"/api/...\", body? }`, where `method` is `\"GET\"`, `\"POST\"`, `\"PUT\"`, `\"DELETE\"`, or `\"PATCH\"`; raw authenticated API call.\n\n## Patch semantics\n\n`app-patch.definition` is RFC 7396 JSON Merge Patch applied to the stored definition:\n\n- omitted keys stay unchanged;\n- object keys merge recursively;\n- arrays and scalar values replace;\n- `null` deletes a key;\n- reusable-element disambiguation: a patch value for `elements.<name>` containing ONLY the `elements` key merges node-by-node; any other key present (`mode`, `root`, `props`, or `export`) makes it a full element replace — restate every field you want kept. In that node-by-node form, `elements.<name>.elements.<id>: null` deletes one node. Literal null nodes are rejected in a full element replace so they cannot be mistaken for deletions.\n- otherwise every supplied `pages.<page>.elements.<id>`, `pages.<page>.params.<param>`, `actions.<name>`, `models.<name>.columns.<col>`, and `models.<name>.sources.<src>` value is atomic and replaces that complete declaration; `null` deletes it (deleting a source detaches its rows — see the source lifecycle above).\n\n`pages.<page>: null` deletes a page, except the current `defaultPage` cannot be deleted. `root`, `title`, and top-level `defaultPage` use ordinary merge semantics. A top-level `page` patch is rejected with guidance to patch `pages.<name>` instead.\n\nBecause elements, param declarations, actions, and columns are atomic, include the complete desired object when changing one. For example, changing only a Table's `emptyMessage` requires sending its full `{ \"type\": \"Table\", \"props\": ... }` element. The merged result is validated as a whole; on failure, read `issues[]`, correct the paths, and retry without assuming anything was written.\n\n```json\n{\n \"appId\": \"<app-id>\",\n \"description\": null,\n \"definition\": {\n \"models\": {\n \"idea\": {\n \"columns\": {\n \"priority\": { \"kind\": \"enum\", \"enum\": [\"low\", \"high\"], \"default\": \"low\" }\n }\n }\n },\n \"queries\": { \"openIdeas\": null },\n \"pages\": {\n \"main\": {\n \"elements\": {\n \"title\": { \"type\": \"Heading\", \"props\": { \"text\": \"Prioritized ideas\", \"level\": \"h1\" } }\n }\n }\n }\n }\n}\n```\n\n## Worked example: ideas tracker\n\nCreate this with `app-upsert`:\n\n```json\n{\n \"name\": \"Ideas Tracker\",\n \"description\": \"Collect and manage product ideas\",\n \"definition\": {\n \"models\": {\n \"idea\": {\n \"columns\": {\n \"title\": { \"kind\": \"string\", \"required\": true },\n \"status\": { \"kind\": \"enum\", \"enum\": [\"open\", \"done\"], \"default\": \"open\" }\n }\n }\n },\n \"queries\": {\n \"allIdeas\": { \"model\": \"idea\", \"sort\": { \"column\": \"createdAt\", \"dir\": \"desc\" } }\n },\n \"actions\": {\n \"triage\": { \"kind\": \"task\", \"prompt\": \"Review current ideas and recommend the next one to pursue\" }\n },\n \"pages\": {\n \"main\": {\n \"root\": \"root\",\n \"elements\": {\n \"root\": {\n \"type\": \"Container\",\n \"props\": { \"direction\": \"column\", \"gap\": \"lg\" },\n \"children\": [\"heading\", \"formCard\", \"ideasCard\", \"triage\"]\n },\n \"heading\": { \"type\": \"Heading\", \"props\": { \"text\": \"Ideas\", \"level\": \"h1\" } },\n \"formCard\": {\n \"type\": \"Card\",\n \"props\": { \"title\": \"Add an idea\" },\n \"children\": [\"ideaForm\"]\n },\n \"ideaForm\": {\n \"type\": \"Form\",\n \"props\": {\n \"id\": \"newIdea\",\n \"fields\": [{ \"name\": \"title\", \"label\": \"Title\", \"required\": true }],\n \"submitLabel\": \"Add\",\n \"onSubmit\": [{\n \"action\": \"app.mutate\",\n \"params\": { \"model\": \"idea\", \"op\": \"create\", \"values\": { \"$form\": \"\" } }\n }]\n }\n },\n \"ideasCard\": {\n \"type\": \"Card\",\n \"props\": { \"title\": \"All ideas\" },\n \"children\": [\"ideasTable\"]\n },\n \"ideasTable\": {\n \"type\": \"Table\",\n \"props\": {\n \"data\": { \"$state\": \"/queries/allIdeas/data\" },\n \"loading\": { \"$state\": \"/queries/allIdeas/loading\" },\n \"error\": { \"$state\": \"/queries/allIdeas/error\" },\n \"columns\": [\n { \"key\": \"title\", \"label\": \"Title\" },\n { \"key\": \"status\", \"label\": \"Status\", \"kind\": \"badge\", \"tones\": { \"open\": \"info\", \"done\": \"success\" } }\n ],\n \"rowActions\": [{\n \"label\": \"Delete\",\n \"variant\": \"destructive-outline\",\n \"actions\": [{ \"action\": \"app.mutate\", \"params\": { \"model\": \"idea\", \"op\": \"delete\", \"rowId\": { \"$row\": \"id\" } } }]\n }]\n }\n },\n \"triage\": {\n \"type\": \"Button\",\n \"props\": { \"label\": \"Ask swarm to triage\", \"variant\": \"secondary\" },\n \"on\": { \"press\": [{ \"action\": \"app.action\", \"params\": { \"name\": \"triage\" } }] }\n }\n }\n }\n },\n \"defaultPage\": \"main\"\n }\n}\n```\n\nThe tool returns `{ appId, url: \"/apps/<id>\" }`. Open that URL to verify the live UI, then continue with the read-patch-validate loop above.\n\n## View and screenshot a live app\n\n- An app renders at `<dashboard>/apps/<id>`. Two view modes are set by query string: `?mode=full` (full-viewport overlay with a slim header) and `?mode=chromeless` (only the rendered page, the embed surface). `app.navigate` keeps only `?mode`.\n- Logged-in browser: a fresh dashboard has no connection and redirects to /setup. Seed the localStorage key `agent-swarm-connections` with `{connections:[{id,name,apiUrl,apiKey}],activeId}`. Build the value from an env var and pipe it to `agent-browser eval --stdin`, so the key never reaches a command line. Reload, then pick a user in the \"Who are you?\" dialog.\n- Apps scroll inside an inner canvas, so a full-page screenshot captures only the viewport. Scroll the canvas or raise the viewport height. For mobile, set a 375px-wide viewport before the screenshot.\n- App definitions: `GET /api/apps` and `GET /api/apps/<id>` with the API key as Bearer.\n- Follow-up edit to a live app: list in the brief the control numbers the edit must not move, and assert them from the backing script before publishing. Take a signed-in screenshot of each changed selector at 1440px wide, save the shots to agent-fs, critique, and repeat at least 3 times. If the backing script caches results, bump its version or force a fresh run so the shots show new data.\n\n\n### Rows from agents and scripts\n\nEvery row tool requires `appId` and `model`. Scripts use underscore names, such as `ctx.swarm.app_row_create` and `ctx.swarm.app_rows_list`.\nResults use the usual `data` wrapper, so scripts read `res?.data ?? res`. Rows contain system fields and declared columns at the top level.\nWrites record `agent:<agentId>` in `createdBy` and `updatedBy`. Source projections and join keys remain read-only. Each row input must fit within 1 MiB.\n\n`app-rows-list` accepts `equals`, `sort: \"<column>:asc|desc\"`, and `limit` from 1 to 1000 (default 200).\nEquality filters accept declared columns and system columns. Filter values must match the column kind and use strict equality.\n`app-rows-delete` requires at least one equality filter and accepts a limit from 1 to 1000 (default 1000).\n\n`app-action-run` returns the REST action body under `data`. Script actions run with the script owner's identity and receive the verified invoking agent as `caller`.\nScripts and extensions cannot invoke `app-action-run`.\n";
14947
+ var content_default2 = "# Swarm Apps\n\nSwarm Apps are persistent, agent-authored internal applications: a schema-backed row store, named queries, custom script/task actions, and a validated json-render interface served at `/apps/<id>`. Use an app when people need to view and change live records; use `create_page` for a static snapshot.\n\n> **Capability gate**: app tools are available when the server's `CAPABILITIES` includes `pages` (for example `CAPABILITIES=core,task-pool,pages`). There is no separate `apps` capability. If these tools are absent from your MCP list, this is why.\n\n## Tools and iteration loop\n\n| Tool | Use it for |\n|---|---|\n| `app-list` | Discover apps by id, name, description, and timestamps. Definitions are omitted. |\n| `app-get` | Read one complete stored definition before changing it. |\n| `app-upsert` | Create an app, or replace an existing app's entire definition when you intentionally have the full desired state. |\n| `app-patch` | Make a focused change while preserving everything not mentioned in the patch. Prefer this for iteration. |\n| `app-query` | Run one declared named query and return its rows. Use this when an agent or saved script needs to consume app data rather than render the app UI. |\n| `app-rows-list` | List rows with typed equality filters, sorting, and a limit. Returns `{ rows, total }`. |\n| `app-row-get` | Read a row by `rowId`. Returns `{ row }`. |\n| `app-row-create` | Create a row from `values`. Returns `{ row }`. |\n| `app-rows-create` | Create 1 to 500 rows from a `rows: values[]` array, within 10 MiB. Returns `{ rows }`. |\n| `app-row-patch` | Patch a row by `rowId` with `values`. Returns `{ row }`. |\n| `app-row-delete` | Delete a row by `rowId`. Returns `{ ok: true }`. |\n| `app-rows-delete` | Delete matching rows with a non-empty `equals` filter. Returns `{ deleted }`. |\n| `app-action-run` | Run a declared script, task, or sync action with `{ appId, action, input? }`. Agents can invoke it through MCP only. |\n| `app-history` | List definition snapshots and their compact model/column digests before choosing a restore point. |\n| `app-diff` | Show a unified definition diff; defaults to newest snapshot → CURRENT. |\n| `app-rollback` | Restore a snapshot through the normal schema-migration engine. |\n\nFor every edit: `app-get` -> modify the smallest coherent subtree -> `app-patch` -> if rejected, fix every returned `issues[]` entry (`path` + `message`) and retry. Validation happens before storage, so a rejected update leaves the saved app unchanged. Do not guess at the current definition or use `app-upsert` with a partial definition.\n\n`app-patch` can also change `name`; omit `description` to preserve it or pass `description: null` to clear it.\n\n### Reading an app's callable surface\n\nOne `app-get` returns everything needed to drive an app you did not write: `definition.queries` are runnable with `app-query` (supply every `$param` the query references), and `definition.actions` are invocable with `app-action-run` or `POST /api/apps/<id>/actions/<name>` (a `script` action runs its script, a `task` action spawns a task, a `sync` action refreshes sources). Read the query parameters and action arguments from the definition before invocation. Do not guess parameter names.\n\n### Verified action caller\n\nScript actions receive `caller` as a reserved, server-stamped argument. The server overwrites `caller` from definition defaults and request input.\n\n```typescript\ntype AppActionCaller = {\n kind: \"user\" | \"agent\" | \"operator\" | \"guest\";\n id: string | null;\n name?: string;\n pageId?: string;\n};\n```\n\nThe caller identifies the authenticated user or agent. Operator and guest callers have `id: null`. A signed page session adds `pageId`.\nWith the swarm key, a registered `X-Agent-ID` produces an agent caller and `agent:<id>` row provenance. Missing or unknown agent IDs remain operator callers.\nTask actions include the same caller as server-verified JSON in the task prompt. Script execution still uses the saved script owner's bindings.\n\n### Verified action caller\n\nScript actions receive `caller` as a reserved, server-stamped argument. The server overwrites `caller` from definition defaults and request input.\n\n```typescript\ntype AppActionCaller = {\n kind: \"user\" | \"agent\" | \"operator\" | \"guest\";\n id: string | null;\n name?: string;\n pageId?: string;\n};\n```\n\nThe caller identifies the authenticated user or agent. Operator and guest callers have `id: null`. A signed page session adds `pageId`.\nWith the swarm key, a registered `X-Agent-ID` produces an agent caller and `agent:<id>` row provenance. Missing or unknown agent IDs remain operator callers.\nTask actions include the same caller as server-verified JSON in the task prompt. Script execution still uses the saved script owner's bindings.\n\n## Safe schema evolution and rollback\n\nPrefer **hiding** a column over deleting it. A hidden column's values stay on every existing row, so an unhide or rollback can make it visible again. Hiding is metadata-only: hidden columns cannot be used in queries, page bindings, `app.mutate` values, or new row writes, and `required` is ignored while hidden. Row GETs still expose the historical value for backward compatibility.\n\nDo not reuse a hidden column name. The name remains held until you either unhide it or explicitly purge its stored values. To permanently remove a column, delete its declaration with `null` and include `{ \"columnName\": { \"purge\": true } }` in the same `migration` object. That is deliberately one-shot and irreversible for row data.\n\nSchema-changing writes can carry this sibling `migration` object:\n\n```json\n{\n \"migration\": {\n \"priority\": { \"from\": \"flag\", \"map\": { \"urgent\": \"high\", \"watch\": \"low\" }, \"else\": \"none\" },\n \"status\": { \"from\": \"flag\", \"map\": { \"watch\": \"watching\", \"done\": \"done\" }, \"else\": \"open\" },\n \"oldColumn\": { \"purge\": true },\n \"count\": { \"coerce\": true, \"else\": 0 },\n \"owner\": { \"set\": \"unassigned\" }\n }\n}\n```\n\nUse `set` to backfill a changed column, `from` with optional `map`/`else` to derive it from one existing (including hidden) column, `coerce` for a kind change, and `purge` only for explicit destruction. Non-purge directives target a column changed in that same write. The server fails loudly before writing when a lossy change needs a directive: inspect every returned `issues[]` item, including its per-value row counts, then choose an explicit policy and retry. Never guess a migration just to get a 200.\n\n**Source lifecycle** rides the same engine with the same all-or-nothing guarantees. Free: adding a source, adding a NEW column with a `source` binding, binding an existing column that holds zero values, changing a binding's `field`/`transform`, and changing a source's `args`/`config`/`connection`/`scriptId` (window changes churn staleness on the next pass — expect `stale` flips when narrowing). Rejected with a path-bearing issue: changing `joinKey` (immutable — remove the source and add it again), changing `connector` while the source owns rows (row count in the message), and binding an existing column that already holds values (purge it — or add a fresh column — and bind that instead; a sync pass would otherwise overwrite the data). Removing a source **detaches** its rows: values survive as ordinary columns, the `source`/`syncedAt`/`stale` envelope is stripped, and the report counts them in `detachedRows`. A patch removing a source must drop its column bindings in the same call — a dangling `source.of` is rejected before anything is written.\n\nSync never adopts rows it does not own: a pulled record whose join key matches an unowned row creates a second, source-owned row. Adding a source over a join-key column that already holds values therefore duplicates those records on the first pass — and remove-source → re-add duplicates for the same reason, because detached rows keep their values. To convert a hand-maintained model into a synced one, purge the old rows first or use a fresh join-key column.\n\nFor example, split a legacy `flag` into `priority` and `status` without losing data in one patch: add the two columns, map both from `flag`, update every affected query/page binding, then hide `flag`.\n\n```json\n{\n \"appId\": \"<app-id>\",\n \"definition\": {\n \"models\": {\n \"ticket\": {\n \"columns\": {\n \"priority\": { \"kind\": \"enum\", \"enum\": [\"none\", \"low\", \"high\"] },\n \"status\": { \"kind\": \"enum\", \"enum\": [\"open\", \"watching\", \"done\"] },\n \"flag\": { \"kind\": \"string\", \"hidden\": true }\n }\n }\n }\n },\n \"migration\": {\n \"priority\": { \"from\": \"flag\", \"map\": { \"urgent\": \"high\", \"watch\": \"low\" }, \"else\": \"none\" },\n \"status\": { \"from\": \"flag\", \"map\": { \"watch\": \"watching\", \"done\": \"done\" }, \"else\": \"open\" }\n }\n}\n```\n\nEvery schema migration returns `{ scanned, backfilled, coerced, mapped, elsed, purgedValues, idxRebuilt, detachedRows, orphanFields }`. Read `orphanFields`: it reports extra row fields that predate or no longer appear in the definition; they are preserved until an explicit purge. `schemaVersion` is server-managed: never set it in an input patch or try to use it as application data.\n\nEvery successful definition write snapshots the previous definition. Use `app-history` to select a version, `app-diff({ appId, from: <version> })` to inspect it against CURRENT, then `app-rollback({ appId, version: <version>, migration? })` to restore it. Rollback is a forward migration over live rows, not row-level time travel: it creates a new pre-rollback snapshot and may reject a lossy restore with the same migration directives and counts. A rejected rollback changes nothing.\n\n### Per-user configuration\n\n`userConfig` declares up to 20 typed settings in the versioned definition; its values are deliberately stored outside the definition, separately for each user (and the operator dashboard). Each field is `{ \"kind\": \"string\" | \"number\" | \"boolean\" | \"date\" | \"enum\", \"default\"?: ..., \"enum\"?: [...], \"label\"?: \"...\" }`. Defaults follow column rules, including enum membership; `required` is not allowed. A missing or obsolete stored value reads as its default, or `null` when no default is declared.\n\nUse `{ \"$state\": \"/user/<field>\" }` on a page for the read-only current-user binding; the field must be declared and the path cannot continue below it. Pure and bound reusable elements cannot bind `/user` directly — pass the value through an element prop from the consuming page. An agent acting on an owned user-requested task reads and edits that requester's preferences. `userConfig` schema changes are always migration-compatible and appear in migration reports; no migration directives are needed. Rollback restores the historical schema but never alters saved per-user values, so values can resurface when a field returns.\n\n### Theming\n\nAn optional top-level `\"theme\"` sets the preset the dashboard applies to the app's rendered canvas: a lowercase slug validated by shape only. The preset catalog ships with the dashboard and lives in `src/themes/presets.ts` and `src/themes/classics.ts`. Update this list and the `app-upsert` tool description when it changes. Current ids: `hive` (the stock look), the accent/field presets `meadow`, `iris`, `rose`, `cobalt`, `ember`, `carbon`, `paper` (the warm editorial paper look), and the classic editor/platform presets `github`, `vscode`, `material`, `solarized`, `tokyo`, `monokai`, `gruvbox`, `catppuccin`. Action and destructive tones are never themed; status tones are themed ONLY by the classic presets (their identity includes a status palette: hue semantics stay fixed, success reads green and error reads red everywhere). An id the viewer's dashboard build does not know degrades to the dashboard's own theme, so unknown slugs are safe but pointless. Omit `theme` to inherit whatever theme the viewer runs; `\"hive\"` is an explicit reset to the stock look even inside a themed dashboard.\n\nViewers can override the preset per app from the app's settings drawer; the override rides the reserved `$theme` key of the user-config values (accepted on every app, even without a declared `userConfig` schema, and never visible at `/user/...`). A present override always beats the definition's `theme` — even an unrecognized one, which degrades to the dashboard theme — so treat `theme` as the app's default styling, not a guarantee.\n\nAn optional top-level `\"icon\"` sets the app's icon on the dashboard Apps page. It takes one of three shapes:\n\n- `{ \"type\": \"lucide\", \"icon\": \"<kebab-case lucide name>\", \"color\": \"#RRGGBB\" }` (`color` optional). The dashboard looks the name up in its curated icon catalog and shows a generic grid icon for an unknown name.\n- `{ \"type\": \"url\", \"url\": \"https://...\" }`: an https image link, at most 2048 characters, no credentials.\n- `{ \"type\": \"agent-fs\", \"path\": \"/apps/<appId>/icon.png\" }`: an image on the swarm's agent-fs drive. Add both `orgId` and `driveId` for another drive; never just one.\n\nThe server validates shape only. The dashboard shows the grid glyph while an image loads, when it fails to load, and when the viewer has no agent-fs connected, so omitting `icon` is always safe. `app-patch` replaces `icon` whole, so switching shapes leaves no keys from the old one.\n\n\nDistinguish the two rollback 400s. A lossy-migration 400 is fixable: copy the required `migration` entries from the message and retry. A target-snapshot validation 400 explicitly says that directives cannot repair that historical definition; use `app-history` and choose a different version.\n\nWhen a schema patch reports stale page/query bindings, repair them in that same patch. Page elements are atomic: replace the complete `pages.<page>.elements.<id>` declaration, removing any reference to a hidden or deleted column, instead of sending only the changed nested prop. This is also the repair move for older apps whose stored page already references an undeclared column; full-definition validation otherwise blocks every patch.\n\n## Definition reference\n\n```json\n{\n \"models\": {\n \"modelName\": {\n \"columns\": {\n \"externalId\": { \"kind\": \"string\" },\n \"title\": { \"kind\": \"string\" }\n }\n }\n },\n \"queries\": { \"queryName\": { \"model\": \"modelName\" } },\n \"actions\": { \"actionName\": { \"kind\": \"task\", \"prompt\": \"Review the current rows and report\" } },\n \"pages\": {\n \"main\": {\n \"root\": \"root\",\n \"elements\": { \"root\": { \"type\": \"Container\", \"props\": {} } }\n }\n },\n \"defaultPage\": \"main\",\n \"theme\": \"ember\"\n}\n```\n\nOptional top-level `layout: \"sidebar\"` turns on the app shell (see Pages, routes, and page trees). Without it every page renders on the plain canvas, exactly as before.\n\nModel, reusable-element, element-prop, query, action, column, page, and page-param names start with a lowercase letter, contain only letters, numbers, or underscores, and are at most 40 characters. A definition has 0-10 models and at most 20 reusable elements; each declared model has 1-40 columns. Zero-model apps are valid for pure UI utilities as long as their pages and reusable elements validate.\n\n### Reusable elements\n\nTop-level `elements` are versioned inside the app definition and can be reused from the app's own pages or, when explicitly exported, from another app. They are private by default. Each entry declares a `mode`, optional typed `props`, one `root`, and a flat `elements` node map using the same validated tree vocabulary as a page:\n\n```json\n{\n \"elements\": {\n \"statCard\": {\n \"mode\": \"pure\",\n \"export\": true,\n \"props\": {\n \"label\": { \"kind\": \"string\", \"required\": true },\n \"value\": { \"kind\": \"number\", \"default\": 0 }\n },\n \"root\": \"card\",\n \"elements\": {\n \"card\": { \"type\": \"Card\", \"props\": {}, \"children\": [\"label\", \"slot\"] },\n \"label\": { \"type\": \"Metric\", \"props\": { \"label\": { \"$state\": \"/props/label\" }, \"value\": { \"$state\": \"/props/value\" } } },\n \"slot\": { \"type\": \"ElementSlot\", \"props\": {} }\n }\n }\n }\n}\n```\n\n- `pure` elements may read only their declared `/props/<name>` state; `$item` and `$index` are also legal inside repeated nodes. They cannot invoke any action step. A pure tree may contain at most one leaf `ElementSlot` where consumer children are inserted.\n- `bound` elements may additionally read the defining app's declared queries and actions and use its models. Those references are validated against the defining app, including hidden-column rules. Exported bound elements cannot use `app.navigate`; private bound elements may navigate within their defining app.\n- Prop kinds are `string`, `number`, `boolean`, `date`, or `enum`. An enum prop requires a non-empty `enum: [\"value\", ...]` values array. A literal default and each literal consumer value must match the kind and, for enums, be one of those values. A required prop without a default must be supplied.\n\nReference an element with an `ElementRef` node. Omit `app` for same-app reuse; cross-app references name the defining app id and require `export: true`. `instanceKey` is optional. Consumer `children` are accepted only when the target has an `ElementSlot`:\n\n```json\n{\n \"type\": \"ElementRef\",\n \"props\": {\n \"app\": \"<defining-app-id>\",\n \"element\": \"statCard\",\n \"props\": { \"label\": \"Open issues\", \"value\": 12 },\n \"instanceKey\": \"openIssues\"\n },\n \"children\": [\"details\"]\n}\n```\n\nElement references float to the defining app's current definition. `app` and `element` must be literal strings; dynamic references are not supported. The server rejects reference cycles and expansion deeper than five, missing/private targets, invalid props, and a breaking write to an exported element that other apps reference. Removing or unexporting an exported element, changing its mode, removing a declared prop, changing a prop kind, or adding a required prop without a default is breaking; publish the new contract under a new element name. If consumers are abandoned intentionally, retry the PUT, PATCH, or rollback with `\"forceElementBreak\": [\"elementName\"]`. The named consumers will then render an error once element rendering is available; deleting an entire app is deliberately not compatibility-gated.\n\n### Models\n\nEach column is `{ \"kind\": ..., \"required\"?: boolean, \"default\"?: ..., \"index\"?: boolean, \"enum\"?: string[], \"hidden\"?: boolean }`.\n\n| `kind` | Values and indexing |\n|---|---|\n| `string` | String value; set `index: true` only when equality lookups need it. |\n| `number` | Finite number; never indexed. |\n| `boolean` | Boolean; set `index: true` only when equality lookups need it. |\n| `date` | ISO-8601 string; never indexed. |\n| `enum` | String from the non-empty unique `enum` list; always indexed, without `index: true`. |\n| `json` | Any JSON value (object, array, nested) up to 256 KB serialized by default (`APPS_JSON_COLUMN_MAX_BYTES`); never indexed, and a named query cannot `filter` or `sort` on it. Not allowed for `userConfig` fields or element props. |\n\n`default` must match the column kind (and be one of the enum values). `required: true` rejects missing/null values unless a default supplies the value. `id`, `createdAt`, `updatedAt`, `createdBy`, `updatedBy` — and the sync envelope `source`, `syncedAt`, `stale` — are system columns and reserved names. An app created before the sync envelope that declared ordinary columns with these names surfaces `definitionError` after upgrade until they are renamed: patch in a fresh column with a `{from}` migration directive, then purge the old one. Rows always expose `id`/`createdAt`/`updatedAt`; `createdBy`/`updatedBy` record the acting principal (`user:<id>`, `agent:<id>`, `operator`, or `sync:<source>` for engine writes) and are system-managed on every row write.\n\n### Sources and sync\n\nA model may declare up to 4 named `sources` — one-way inbound projections of an external system into its rows. The `script` connector is THE way to bring external data in (GitHub, Linear, any API): a saved script owns the fetch, its auth placeholders, and its paging. `swarm-tasks` is the one native connector, projecting this swarm's own task pool (`config`: `status`/`tags` comma-lists, `agentId`, `assetKey` namespace prefix, `limit` up to 200 — default 100, `includeHeartbeat`). Synced rows are readable by EVERY principal with `app.use` on the app; an unscoped `swarm-tasks` source publishes task prompts (truncated, secret-scrubbed) to all of them, so scope it with `config.assetKey`/`config.agentId` unless that exposure is intended. A user-invoked sync only ever pulls the invoking user's own requested tasks. Script sources run with their run-as identity's credentials — an agent-owned script runs as its owner and only the owner may wire it; an owner-less catalog (global) script runs as the LEAD, so only the lead or the operator can wire or alter such a source (stored references stay valid with their args and connection pinned).\n\n```json\n{\n \"models\": {\n \"issue\": {\n \"columns\": {\n \"issueKey\": { \"kind\": \"string\" },\n \"title\": { \"kind\": \"string\", \"source\": { \"of\": \"gh\", \"field\": \"title\" } },\n \"openedAt\": { \"kind\": \"date\", \"source\": { \"of\": \"gh\", \"field\": \"created_at\", \"transform\": \"date-parse\" } },\n \"note\": { \"kind\": \"string\" }\n },\n \"sources\": {\n \"gh\": { \"connector\": \"script\", \"scriptId\": \"<script-uuid>\", \"joinKey\": \"issueKey\", \"args\": { \"repo\": \"owner/name\" }, \"connection\": \"github\" }\n }\n }\n }\n}\n```\n\n- **Join key**: each source names a `joinKey` — an owned, non-hidden `string` column carrying the external identity. It must not be `required`, must not declare a `default`, and cannot itself be source-bound. A row belongs to at most ONE source (`row.source`).\n- **Column bindings**: `{ \"of\": \"<sourceName>\", \"field\": \"user.login\", \"transform\"? }` projects a (dotted-path) field of the pulled record into the column on every pass. Transforms and their required column kinds: `slug`/`lower`/`upper` → `string`, `cents` → `number` (×100, rounded), `date-parse` → `date` (ISO). A failed transform nulls that one column and warns; it never fails the pass.\n- **Read-only contract**: source-bound columns and the join key reject every direct write (row create/patch/bulk) with a path-bearing issue — mutate them via the source or a sync refresh. Owned columns on the same model stay writable. Every `required` owned column on a sourced model must declare a `default`, because sync-created rows cannot supply it.\n- **Provenance**: synced rows carry `source` (owner), `syncedAt` (last confirmed presence — sortable), and `stale` (true when a complete pull no longer returned the record; clears on reappearance). `syncedAt` advances on every confirmed row WITHOUT touching `updatedAt`; `updatedAt` moves only when projected data actually changed.\n- **`connection`** (optional, script sources): names a connections-system slug the source depends on. It buys write-time validation plus a preflight before every pull; it does not by itself gate egress. Credentials resolve for the sync run-as identity — the script's owner when it has one, else the lead agent — so global connections always work and agent-scoped ones need matching script ownership. The slug is injected into the script's args as `connection`, letting one generic script serve N connections.\n\n**The canonical sync-script contract** (every sync script, always):\n\n```ts\nexport default async function run(args, ctx) {\n // args = { ...source.args, app: { id }, model: \"<model>\", source: \"<sourceName>\", connection?: \"<slug>\" }\n const records = [{ key: \"42\", fields: { title: \"…\", created_at: \"…\" } }];\n return { records, complete: true }; // or return the bare array — a bare array IS a complete snapshot\n}\n```\n\nReturn `Array<{ key, fields }>` or `{ records, complete? }`. `key` is the external identity the engine joins on `joinKey` (numbers are coerced to strings); `fields` is the bag bindings project from. Return `complete: false` whenever the pull window may have missed records — a paged fetch, a hit `limit`, or client-side filtering of a full page. An incomplete pull skips the stale sweep, so rows outside a narrow window are not falsely marked stale; compute `complete` BEFORE any client-side filtering. Hard cap 500 records per pull (over-cap pulls truncate and count as incomplete). An invalid return shape, thrown error, or non-zero exit fails the pass with zero row churn.\n\nThe seeded catalog script `github-issues-pull` is the worked example (placeholder auth via `[REDACTED:GITHUB_TOKEN]`, PR filtering, `complete` computed before filtering). For scheduled refreshes, point a `targetType: \"script\"` schedule at the seeded `app-sync-run` with `scriptArgs: { \"appId\": \"<id>\", \"model\"?, \"source\"? }`.\n\n**Three refresh doors, one engine**: `POST /api/apps/<id>/sync` (body `{ \"model\"?, \"source\"? }`), a `sync` action kind, and the `app-sync` MCP tool (`ctx.swarm.app_sync` from scripts). `{model?, source?}` fans out to every matching (model × source) pair; each pass reports `{ pulled, created, updated, refreshed, unchanged, markedStale, warnings }`. A pair already syncing in this API process short-circuits with `alreadyRunning: true` instead of pulling twice. Each pair's last-pass status (`lastFinishedAt`, counts, `error?`) comes back as `syncStatus` — keyed `\"<model>:<source>\"` — on `GET /api/apps/<id>` and in `app-get` data, so UI and agents can render \"last synced / last error\" without extra calls.\n\n### Freshness and the refresh button\n\nFreshness renders with the existing column kinds — no special components. Give the table `{ \"key\": \"syncedAt\", \"kind\": \"date\" }` and `{ \"key\": \"stale\", \"kind\": \"badge\", \"tones\": { \"true\": \"warning\" } }` columns, declare a `sync` action, and wire a Button to it:\n\n```json\n{\n \"actions\": { \"refresh\": { \"kind\": \"sync\" } },\n \"pages\": {\n \"main\": {\n \"root\": \"root\",\n \"elements\": {\n \"root\": { \"type\": \"Container\", \"props\": {}, \"children\": [\"refreshBtn\", \"issuesTable\"] },\n \"refreshBtn\": {\n \"type\": \"Button\",\n \"props\": { \"label\": \"Refresh\" },\n \"on\": { \"press\": [{ \"action\": \"app.action\", \"params\": { \"name\": \"refresh\" } }] }\n },\n \"issuesTable\": {\n \"type\": \"Table\",\n \"props\": {\n \"data\": { \"$state\": \"/queries/allIssues/data\" },\n \"columns\": [\n { \"key\": \"title\", \"label\": \"Issue\" },\n { \"key\": \"syncedAt\", \"label\": \"Synced\", \"kind\": \"date\" },\n { \"key\": \"stale\", \"label\": \"Stale\", \"kind\": \"badge\", \"tones\": { \"true\": \"warning\" } }\n ]\n }\n }\n }\n }\n }\n}\n```\n\nA `sync` action answers the script-action state shape (`/actions/refresh` → `running` → `ok`/`error`, result under `result.passes`), so the page's queries refetch when it completes. Use `app-query` to READ rows (named queries may filter on `stale`/`source` and sort by `syncedAt`); use `app-sync` to REFRESH sources; never poll a sync door in a loop — schedule it or give people the button.\n\n### Queries\n\nA named query is:\n\n```json\n{\n \"model\": \"idea\",\n \"filter\": { \"status\": \"open\" },\n \"sort\": { \"column\": \"createdAt\", \"dir\": \"desc\" },\n \"limit\": 100\n}\n```\n\n`filter` is a strict AND of equality checks. A filter may target a declared model column or a system column (`id`, `createdAt`, `updatedAt`, `createdBy`, `updatedBy`, and on synced models `source`, `syncedAt`, `stale`) — filtering on `id` is the universal way to select one row for a detail view, and `{ \"stale\": true }` selects rows a complete pull stopped confirming. A literal value must match the column's kind; date filters compare the stored raw ISO string, not parsed instants. Omit `limit` for the default 200 rows, or set an integer from 1 through 1000. `sort.column` is a non-`json` model column, `createdAt`, `updatedAt`, or `syncedAt`; `dir` is `asc` or `desc`. Query runtime state is `{ data, loading, error }` under `/queries/<queryName>`.\n\nA filter value may instead be exactly `{ \"$param\": \"<name>\" }`. At execution, the caller supplies that name and the server coerces its value to the filtered column's kind before equality matching:\n\n```json\n{\n \"queries\": {\n \"issueDetail\": { \"model\": \"issue\", \"filter\": { \"issueId\": { \"$param\": \"issueId\" } }, \"limit\": 1 }\n }\n}\n```\n\nThe placeholder object must contain only `$param`. Missing caller values fail loudly rather than returning unfiltered rows: HTTP reports 400 and `app-query` returns a tool error listing every missing name. Supplying a param name the query does not reference is also an error. The app UI supplies current declared route params automatically. Direct calls use `app-query({ appId, query: \"issueDetail\", params: { issueId: 42 } })` or `ctx.swarm.app_query({ appId, query: \"issueDetail\", params: { issueId: 42 } })`.\n\n### Custom actions\n\nActions are optional (maximum 20) and are invoked from the page with the `app.action` runtime action.\n\n```json\n{\n \"actions\": {\n \"recalculate\": {\n \"kind\": \"script\",\n \"scriptId\": \"00000000-0000-4000-8000-000000000000\",\n \"args\": { \"mode\": \"fast\" }\n },\n \"triage\": {\n \"kind\": \"task\",\n \"prompt\": \"Triage this idea and report a recommendation\"\n }\n }\n}\n```\n\n| Kind | Contract |\n|---|---|\n| `script` | `scriptId` must identify an existing script; optional `args` are defaults. Invocation input overrides same-named defaults, and the runtime also supplies `app: { id }`. |\n| `task` | `prompt` must be non-empty; omit `agentId` to use default (lead) assignment. Only set `agentId` to a real agent UUID. Invocation `input` is included as context for the task prompt. Spawned tasks carry asset key `shared/app:<appId>/action:<name>/`, so a `swarm-tasks` source with `config.assetKey: \"shared/app:<appId>/\"` pulls back the tasks this app spawned. |\n| `sync` | Optional `model` and `source` narrow which (model × source) pairs refresh; omitting both syncs every pair the app declares. At least one pair must exist. Answers the script-kind state shape with per-pass results under `result.passes`. |\n\n- Invocation state lands at `/actions/<name>` as `{ status, result?, error?, taskId?, taskStatus? }`, where `status` is `\"running\"`, `\"ok\"`, or `\"error\"`.\n\nUse a task action named Tackle when a person should hand one issue row to the swarm. Pass the complete current row under `input.issue`; `{ \"$row\": \"\" }` resolves to the whole row and that context lands in the task prompt.\n\n```json\n{\n \"actions\": {\n \"tackle\": { \"kind\": \"task\", \"prompt\": \"Tackle this issue. Inspect the supplied issue context, do the work, and report the outcome.\" }\n },\n \"pages\": {\n \"main\": {\n \"root\": \"issuesTable\",\n \"elements\": {\n \"issuesTable\": {\n \"type\": \"Table\",\n \"props\": {\n \"data\": { \"$state\": \"/queries/allIssues/data\" },\n \"columns\": [{ \"key\": \"title\", \"label\": \"Issue\" }],\n \"rowActions\": [{\n \"label\": \"Tackle\",\n \"actions\": [{\n \"action\": \"app.action\",\n \"params\": { \"name\": \"tackle\", \"input\": { \"issue\": { \"$row\": \"\" } } }\n }]\n }]\n }\n }\n }\n }\n },\n \"defaultPage\": \"main\"\n}\n```\n\nFor direct MCP calls, `app-query` accepts `{ appId, query, params? }` and returns rows from that declared named query; every supplied param must be referenced by a `$param` filter in that query. Use it when an agent needs to read app state without scraping the UI.\n\nSaved scripts use the generated SDK name `ctx.swarm.app_query({ appId, query, params? })`. Use `app_query` in scripts or workflows that turn current app rows into reports, digests, or follow-up work. Saved scripts also get generated per-app types automatically: each app contributes an `App_<Name>` namespace with one row interface per model (enum columns as literal unions) and a typed `app_query` overload per named query, all visible via `script-query-types`. Scripts can create, list, get, patch, and delete rows with the seven row tools. Actions remain REST/MCP-only and have no script SDK method.\n\n### Pages, routes, and page trees\n\n`pages` is a map of independently validated page trees and `defaultPage` must name one entry. Each page may also declare a display `title` and typed route `params`. On every non-default page the runtime automatically renders breadcrumbs (`<default page title> › <current page title>`, first crumb navigates back) — including in chromeless embeds — so a detail page does NOT need its own back button; give pages good `title`s instead. This complete pattern connects a table row to a typed detail route and its parameterized query:\n\n```json\n{\n \"models\": {\n \"issue\": {\n \"columns\": {\n \"issueId\": { \"kind\": \"number\" },\n \"title\": { \"kind\": \"string\" },\n \"status\": { \"kind\": \"string\" }\n }\n }\n },\n \"queries\": {\n \"allIssues\": { \"model\": \"issue\" },\n \"issueDetail\": {\n \"model\": \"issue\",\n \"filter\": { \"issueId\": { \"$param\": \"issueId\" } },\n \"limit\": 1\n }\n },\n \"pages\": {\n \"issues\": {\n \"title\": \"Issues\",\n \"root\": \"issuesTable\",\n \"elements\": {\n \"issuesTable\": {\n \"type\": \"Table\",\n \"props\": {\n \"data\": { \"$state\": \"/queries/allIssues/data\" },\n \"columns\": [\n { \"key\": \"title\", \"label\": \"Issue\" },\n { \"key\": \"status\", \"label\": \"Status\", \"kind\": \"badge\" }\n ],\n \"rowActions\": [{\n \"label\": \"Open\",\n \"actions\": [{\n \"action\": \"app.navigate\",\n \"params\": {\n \"page\": \"detail\",\n \"params\": { \"issueId\": { \"$row\": \"issueId\" } }\n }\n }]\n }]\n }\n }\n }\n },\n \"detail\": {\n \"title\": \"Issue detail\",\n \"params\": { \"issueId\": { \"kind\": \"number\", \"required\": true } },\n \"root\": \"detail\",\n \"elements\": {\n \"detail\": {\n \"type\": \"DetailList\",\n \"props\": {\n \"data\": { \"$state\": \"/queries/issueDetail/data/0\" },\n \"fields\": [{ \"key\": \"title\", \"label\": \"Issue\" }]\n }\n }\n }\n }\n },\n \"defaultPage\": \"issues\"\n}\n```\n\nDrawer variant: declare a route param on the containing page, set the Drawer `props.param` to that literal param name, and use the same `app.navigate` shape targeting that page with the row id assigned to the Drawer's param. The Drawer then opens from route state without a separate action contract.\n\nApp shell (`layout: \"sidebar\"` at the top level of the definition): every page renders inside a left sidebar that lists the app's pages and a sticky page header. Per page:\n\n- `title`: the sidebar label and the header heading (defaults to the page name).\n- `icon`: one catalog icon name (the list under Component catalog) before the sidebar label; unknown names are rejected.\n- `description`: one line under the header title (at most 280 characters).\n- `headerActions`: the key of one element of this page, rendered in the header's actions slot (right side), e.g. a Refresh `Button` with `on.press: [{ \"action\": \"app.refresh\" }]` or a row `Stack` of buttons. It is a second root: it must exist in the page's `elements` and must NOT also be reachable from `root`. It shares the page's state and actions.\n- `nav: false`: leave the page out of the sidebar. Pages with a `required` param never list (they cannot open without it); open them with `app.navigate`.\n\nThe sidebar lists pages in definition order and marks the current one. Below 768px it folds into a menu button at the left of the header. Crumbs back to the default page show in the header only on pages the sidebar does not list. The shell renders in every view mode: inside the bordered canvas (default view, under the dashboard header that names the app), under the slim bar in `?mode=full`, and as the whole viewport in `?mode=chromeless`, where the sidebar also shows the app name (it is the only navigation inside an iframe). `headerActions` and `nav` without `layout: \"sidebar\"` are rejected; `icon` and `description` are accepted and unused.\n\n```json\n{\n \"layout\": \"sidebar\",\n \"defaultPage\": \"overview\",\n \"pages\": {\n \"overview\": {\n \"title\": \"Overview\",\n \"icon\": \"activity\",\n \"description\": \"Deploys and spend, last 14 days.\",\n \"headerActions\": \"refresh\",\n \"root\": \"root\",\n \"elements\": {\n \"root\": { \"type\": \"Stack\", \"props\": {}, \"children\": [\"spend\"] },\n \"spend\": {\n \"type\": \"Chart\",\n \"props\": {\n \"kind\": \"area\",\n \"data\": { \"$state\": \"/queries/days/data\" },\n \"loading\": { \"$state\": \"/queries/days/loading\" },\n \"x\": \"date\",\n \"xType\": \"time\",\n \"format\": \"currency\",\n \"series\": [{ \"key\": \"spend\", \"label\": \"Spend\" }]\n }\n },\n \"refresh\": {\n \"type\": \"Button\",\n \"props\": { \"label\": \"Refresh\", \"icon\": \"refresh-cw\", \"variant\": \"outline\", \"size\": \"sm\" },\n \"on\": { \"press\": [{ \"action\": \"app.refresh\" }] }\n }\n }\n },\n \"settings\": { \"title\": \"Settings\", \"icon\": \"pencil\", \"root\": \"root\", \"elements\": { \"root\": { \"type\": \"Text\", \"props\": { \"content\": \"…\" } } } }\n }\n}\n```\n\nParam `kind` is `string` by default, or `number` / `boolean`; `required` defaults to false. The names `mode`, `apiUrl`, `apiKey`, `email`, and `name` are reserved. `/apps/<id>` renders `defaultPage`; `/apps/<id>/p/<page>?issueId=42` is the shareable deep link for another page. Browser navigation is client-side, so app state and polled data stay warm across page changes.\n\nWithin each page, `root` names one entry in its non-empty `elements` map. Elements are a flat, single-parent tree: ids are map keys, `children` contains ids (not nested elements), all elements must be reachable from `root`, and cycles, missing children, or shared children are invalid. Element and Form/UI ids are page-local. Element keys are `type`, `props`, `children`, `on`, `visible`, `repeat`, and `watch`; only components with a `default` child slot accept `children` (Stack, Grid, Split, Tabs, Accordion, Container, Card, Section, Drawer, and Dialog). `watch` maps state paths to an action step or chain.\n\n## Component catalog (all 45)\n\nProps reject unknown keys. A `{\"$state\":\"...\"}` binding may replace a literal prop value at any depth.\n\nIcons: every `icon` prop (and the `Icon` block) takes one name from a curated lucide set: `plus`, `refresh-cw`, `search`, `filter`, `download`, `upload`, `external-link`, `copy`, `check`, `x`, `trash-2`, `pencil`, `eye`, `calendar`, `clock`, `user`, `users`, `bot`, `git-pull-request`, `git-branch`, `github`, `slack`, `mail`, `link`, `file-text`, `folder`, `database`, `zap`, `sparkles`, `flag`, `star`, `tag`, `alert-triangle`, `info`, `circle-check`, `trending-up`, `trending-down`, `dollar-sign`, `activity`, `rocket`. Any other name is rejected.\n\nTones: Badge, Metric and Progress `tone` take `neutral`, `success`, `active`, `error`, `info`, `pending`, `warning`, or `paused`.\n\n| Component | Required props | Optional props / values |\n|---|---|---|\n| `Stack` | none | Primary layout; `direction: \"column\", \"row\"`, `gap`, `padding: \"none\", \"xs\", \"sm\", \"md\", \"lg\", \"xl\"`; `align: \"start\", \"center\", \"end\", \"stretch\"`, `justify: \"start\", \"center\", \"end\", \"between\"`, `wrap`; `motion: \"rise\"` (default), `\"fade\"`, or `\"none\"` (see Motion below); `fill` (grow to fill a `fill`-aware parent; see Layout below); has the `default` child slot. |\n| `Grid` | none | Responsive `columns`: integer 1 through 6, or `{ base, sm, md, lg }` counts 1 through 6; `gap` uses the Stack spacing values; has the `default` child slot. |\n| `Split` | none | `ratio: \"1-1\", \"1-2\", \"2-1\", \"1-3\", \"3-1\"`, `gap`, `collapseBelow: \"sm\", \"md\", \"lg\"`, `reverse`, `fill` (same contract as Stack); has the positional `default` child slot. |\n| `Divider` | none | `label`, `orientation: \"horizontal\"` (default) or `\"vertical\"` (a rule between the items of a row `Stack`, as tall as the row); no children. |\n| `Tabs` | `id`, `tabs` | `tabs` entries are `{ key, label?, icon?, count? }` (`count` is a number shown as a small pill); `defaultTab`; `variant: \"line\"` (default) or `\"segmented\"` (a compact segmented control, same state and warm panels); has the positional `default` child slot. |\n| `Accordion` | `id`, `items` | Grouped collapsible sections. `items` entries are `{ key, title, description?, icon? }`; children are positional like Tabs (`children[i]` is the body of `items[i]`, same count, validated). `type: \"single\"` (default: opening one closes the others, and the open one can close) or `\"multiple\"`. Open keys are client state at `{ \"$state\": \"/ui/<id>/open\" }`, always an array; `defaultOpen` lists the keys open on first render. Bodies mount only while open. `Section collapsible` stays the one-item form. |\n| `Container` | none | Legacy layout primitive; prefer Stack. `direction: \"row\", \"column\"`, `gap: \"none\", \"sm\", \"md\", \"lg\"`; has the `default` child slot. |\n| `Card` | none | `title`, `description`; has the `default` child slot. |\n| `Heading` | `text` | `level: \"h1\", \"h2\", or \"h3\"`. |\n| `Text` | `content` | `tone: \"default\" or \"muted\"`. |\n| `Markdown` | `content` | Rendered Markdown for help, instructions, and rich prose; no children. A link to a GitHub PR, issue, commit or repo, a dashboard task, agent, session or app, or an agent-fs file renders as a chip (icon plus short label), like agent output in a session; `[text](url)` keeps its text. |\n| `SearchInput` | `id` | `placeholder`, `label`, `shortcut` (one key, usually `\"/\"`: shows a keycap and focuses the field); writes debounced text to `/ui/<id>/value`; no children. |\n| `Select` | `id`, `options` | `options` are strings or `{ value, label?, icon?, hint? }`; `placeholder`, `label`, `clearable`, `searchable` (type to filter; on by default past 8 options), `searchPlaceholder`, `multiple`, `defaultValue` (seeds `/ui/<id>/value` once, before any interaction; a one-entry array with `multiple`); writes a string or null to `/ui/<id>/value`, or with `multiple` a string array (empty = nothing picked); no children. |\n| `NumberInput` | `id` | `label`, `placeholder`, `min`, `max`; a text field with a decimal keyboard that writes the parsed number to `/ui/<id>/value` on every change (no debounce), or null when the field is empty; non-numeric text (a bare `-` mid-edit, letters) leaves the stored value untouched; `min`/`max` clamp the stored value and the visible text snaps to it when the field loses focus; no children. |\n| `Chips` | `id`, `options` | Toggle chips for quick filters. `options` are strings or `{ value, label?, icon? }`; `multiple`; `label` (group name for screen readers). Writes a string or null to `/ui/<id>/value`, or a string array with `multiple`; pressing the selected chip clears it. |\n| `Button` | `label` | `variant: \"default\", \"secondary\", \"outline\", \"ghost\", \"destructive\", or \"destructive-outline\"` (use `destructive-outline` for standalone deletes); `disabled` (constant or bound boolean); `busyWith: \"<actionName>\"` swaps the label for a spinner while that custom action's `/actions/<name>/status` is `\"running\"` (presses are ignored), then shows a check and `successLabel` for about 1.5s when it turns `\"ok\"`; `icon`, `iconPosition: \"start\" or \"end\"`; `size: \"sm\", \"default\", or \"lg\"`; `shortcut` (one key, shown as a keycap, presses the button); `hint` (tooltip); dispatch with element-level `on.press`. |\n| `Metric` | `label`, `value` | The dashboard stat tile. `value` is string or number (empty renders an em dash); bind `loading` to `/queries/<name>/loading` for a skeleton while the query loads; `icon` with `tone` tinting its tile; `detail` (a line under the value); `trend: { direction: \"up\", \"down\", or \"flat\", label }`; `info` (explanation tooltip next to the label). `sparkline`: a small trend line under the value in the `tone` color, from an array of numbers (`null` is a gap) or from rows (bind `/queries/<name>/data`) read through `sparklineKey`; fewer than two points draws nothing. `format: \"number\"`, `\"currency\"` (with `currency`, an ISO code, default `USD`) or `\"percent\"` (a ratio: 0.42 is 42%) formats a numeric `value`, like Chart; a string value shows as is. |\n| `Chart` | `kind`, `x`, `series` | `kind: \"line\", \"area\", \"bar\", \"pie\" or \"donut\"`; bind `data` / `loading` / `error` to a named query like Table. `x` is the row field on the x axis; `xType: \"category\"` (default, row order) or `\"time\"` (ISO date or epoch ms, sorted, date ticks; rows whose `x` does not parse are dropped). `series`: 1-8 `{ key, label?, color? }`, `color` one of `chart-1`..`chart-5`, `primary`, `success`, `warning`, `error`, `info`, `muted` (default palette, in order: `primary`, `chart-2`..`chart-5`). `stacked` stacks area and bar series (lines never stack). `format: \"number\"` (default), `\"currency\"` (with `currency`, an ISO code, default `USD`) or `\"percent\"` (values are ratios: 0.42 is 42%). Tooltip on hover; the legend shows with two or more series (`legend` forces it on or off). `height` 120-640 px (default 240); `emptyMessage` (default \"No data yet\"). `x` and every `series[].key` must be columns of the bound query's model. `pie` and `donut` take exactly one series: `x` is the slice label, each row with a positive value is a slice labelled with its share, the tooltip adds the share to the formatted value, and the legend defaults on (`xType` and `stacked` do not apply). Wrap it in a `Card` for a title. |\n| `Alert` | `message` | `title`, `tone: \"info\", \"success\", \"warning\", or \"error\"`, `icon` (overrides the tone icon), `actionLabel` (a button inside the callout that emits `press`; wire it with `on.press`). |\n| `Badge` | `text` | `text` is string or number; `tone`; `icon` replaces the dot; `variant: \"tag\"` (default uppercase chip), `\"status\"` (sentence-case pill), `\"count\"` (numeric pill), or `\"beta\"` (the BETA tag); `status` (a lifecycle value renders the dashboard status chip); `hint` (tooltip; the beta tag's explanation). |\n| `Icon` | `name` | `size: \"sm\", \"md\", or \"lg\"`, `tone: \"default\", \"muted\", \"success\", \"warning\", \"error\", or \"info\"`, `label` (accessible name; decorative without it). |\n| `Progress` | `value` | `max` (default 100), `tone`, `label`, `variant: \"bar\"` (default) or `\"ring\"` (the dashboard progress ring; ignores `tone`), `showValue` (default true: percent for a bar, `value / max` for a ring). |\n| `EmptyState` | `title` | `icon` (default inbox), `body`, `actionLabel` (a button that emits `press`; wire it with `on.press`). |\n| `CopyButton` | `value` | `value` is string or number; `label` is the visible text, icon-only without it. Renders nothing for an empty value. |\n| `Kbd` | `keys` | Keycaps, one per string (`[\"⌘\", \"K\"]`). Display only. |\n| `Skeleton` | `shape` | `shape: \"line\", \"block\", \"rows\", \"metric\", or \"card\"`; `count` (1-20: lines, rows, tiles, or cards); `height` (px, `block` only, default 128). Show it with `visible` bound to a query's `loading`. |\n| `Spinner` | none | `variant: \"ring\", \"ellipsis\", or \"bars\"` (default: the dashboard spinner), `size: \"sm\" or \"md\"`, `label` (visible text and accessible name). |\n| `AvatarStack` | `users` | `users` are display names (initials avatars); `max` (default 4) before a `+N` count. Hover lists every name. |\n| `Section` | `title` | `description`, `collapsible`, `defaultOpen` (default true); has the `default` child slot. |\n| `Table` | `columns` | `data`, `loading`, `refreshing`, `error`, `emptyMessage`, `emptyState`, `rowActions`, `id`, `selectable`, `bulkActions`, `filterable`, `clearState`, `onRetry`, `onRowClick`, `selectedId`, `rowId`, `mobile`, `mobileFields`, `search`, `filters`; see below. |\n| `Form` | `id`, `fields`, `onSubmit` | `title`, `submitLabel`; see below. |\n| `Drawer` | `param` | `title`, `description`, `side: \"right\" or \"left\"`, `size: \"sm\", \"md\" (default), \"lg\", or \"xl\"` (about 480/660/900/1010px at 1440px; grows with the viewport up to 640/960/1280/1600px; full width on phones), `actions` (sticky footer buttons; see below), `presentation: \"sheet\"` (default) or `\"split\"` (an inline right pane beside the page; see below); has the `default` child slot. |\n| `Dialog` | `param` | A centered modal with the Drawer route contract: open exactly while the page param named by `param` is set; Escape, the X or a click outside clears it. `title`, `description`, `size: \"sm\", \"md\" (default), or \"lg\"`, `actions` (footer buttons, Drawer rules). Use it for a short form opened from `headerActions`; after the write, an `app.navigate` without the param closes it. Has the `default` child slot. |\n| `DetailList` | `fields` | `data`, `emptyMessage`, `columns: 1 or 2`, `loading` (bind `/queries/<name>/loading` for skeleton fields while loading); renders one record without edit controls; see below for field kinds. |\n| `CardGrid` | `titleKey` | `data`, `loading`, `error`, `emptyMessage`, `imageKey`, `fields`, `columns`, `onClick`; one card per row for record browsers; see below. |\n| `Kanban` | `columnField`, `columns`, `titleField` | `data`, `loading`, `cardFields`, `idField` (default `id`), `onMove`, `onCardClick`; see below. |\n| `Calendar` | `startField`, `titleField` | `data`, `loading`, `endField`, `idField`, `onSelect`; read-only month grid; see below. |\n| `ContributionGraph` | none | `data`, `loading`, `dateField` (default `date`), `countField`, `days` (7-730, default 365); read-only activity heatmap. |\n| `Tree` | `id`, `nodes` | `label`, `maxHeight` (default `480px`), `fill`; collapsible outline of a doc-shaped value that writes the clicked node key to `/ui/<id>/value`; see below. |\n| `Files` | `path` | `mode: \"list\"` (default) or `\"browser\"`, `selectedPath`, `emptyMessage`, `maxHeight` (default `480px`), `fill`, `onSelect`, `upload`; an agent-fs folder listing read as the viewer; see below. |\n| `File` | `path` | `height`, `fill`; one agent-fs file (Markdown, image, PDF, text) read as the viewer; see below. |\n| `DateRange` | `id` | `presets` (any of `7d`, `30d`, `90d`, `mtd`, `custom`; default all five), `defaultPreset` (default the first), `label`; writes `/ui/<id>/from` and `/ui/<id>/to`; see below. |\n| `Timeline` | `timeField`, `titleField` | `data`, `loading`, `descriptionField`, `statusField`, `tones`, `icon`, `emptyMessage`, `onSelect`; vertical event list, newest first, grouped by day; see below. |\n| `SchemaForm` | `id`, `schema` | `value`, `baseDoc`, `nodeKey`, `onChange`, `fill`; form generated from a JSON schema's `properties`, mirrored to `/ui/<id>/value`; see below. |\n| `Approval` | `requestId` | `showResolved` (default true), `compact`, `onResolved`; one approval request answered in place by the viewer; see below. |\n| `SessionThread` | `id`, `sessionKey` | `scope`, `placeholder`, `onDispatch`, `fill`; the dashboard's session conversation (the \"Session about this page\" panel) for one session per viewer and key, with a composer that steers or chains tasks; the draft is mirrored to `/ui/<id>/value`; see below. |\n\nTable details:\n\n- `columns[]`: `{ key, label?, kind?, tones?: {value: badgeTone}, width?: number, pinned?: \"left\" or \"right\", align?: \"start\" or \"end\", truncate?: \"end\" or \"middle\", icon?, tooltip?: \"<row field>\", hint?: string, popover?: { title?, fields, trigger? }, href?: \"<row field>\", linkLabel?: \"<template>\", max?: number, format?: \"<template>\", currency?: \"<ISO 4217>\", onChange?: chain, filter?: \"values\" or \"text\" or false, muted?: string[] }`. `kind` is `text`, `string`, `enum`, `number`, `boolean`, `date`, `badge`, `status`, `user`, `agent`, `relative`, `duration`, `progress`, `copy`, `switch`, `checkbox`, `link`, `json`, `currency`, or `percent`; `string` and `enum` render as text, and `json` renders a truncated single-line `JSON.stringify` preview. `currency` shows a number as money in the column's `currency` (an uppercase ISO 4217 code, default `USD`): `1234.5` is `$1,234.50`. `percent` reads a ratio: `0.42` is `42%`. Both right-align and show a non-numeric value as is. Pin id/actions columns so they survive horizontal scroll on narrow viewports.\n - `status`: lifecycle values (`pending`, `in_progress`, `running`, `completed`, `failed`, `cancelled`, `paused`, `reviewing`, ...) render the dashboard status chip with its icon; other values use `tones` like `badge`.\n - `user` / `agent`: avatar plus name. `relative` (and `date`): smart time, exact time on hover. `duration`: milliseconds as `1m 23s`. `progress`: a bar against `max` (default 100). `copy`: the value plus a copy button. `link`: a smart link (see Smart links, tooltips and popovers below); any other http(s) URL opens in a new tab and other values render as text.\n - `switch` / `checkbox`: a toggle or a checkbox bound to a boolean column. `onChange` runs with `$row` = the row with this column already set to the new value, e.g. `[{ \"action\": \"app.mutate\", \"params\": { \"model\": \"m\", \"op\": \"update\", \"rowId\": { \"$row\": \"id\" }, \"values\": { \"enabled\": { \"$row\": \"enabled\" } } } }]`. Without `onChange` the control is read-only. Each toggle is a model write, so to pick rows for a bulk action use `selectable` (below), not a boolean column.\n - Numbers, durations and progress right-align by default. `truncate: \"middle\"` keeps both ends of ids and paths. `icon` shows in the header; `tooltip` names a row field shown in a styled tooltip on the cell (when the cell is plain text that gets cut off, the tooltip shows its full text without any config).\n - `format`: a `{{field}}` template that combines several row fields into one cell, e.g. `\"{{name}} ({{status}})\"`. Placeholder names match `[\\w.]+` (letters, digits, `_` and `.`; no hyphens or spaces). Each placeholder reads that row field as-is (a dotted name such as `{{owner.name}}` is a literal column name, not a nested path); a missing or null field becomes an empty string and an object or array becomes a JSON preview cut to 120 characters. The whole cell is capped at 500 characters. A templated column ignores `kind`, shows the same text in the phone list, and sorts by the composed text. `search` and `filters` still read the column's `key`.\n - `muted: [\"none\", \"no\"]`: those cell values (matched case-insensitively) render as a quiet `—` instead of a pill or text, for columns that are mostly `none` / `no`. The value stays in the data, in the filter list, as a hover title and for screen readers; the phone list leaves it out. Not applied to `switch` / `checkbox` cells.\n- `selectable` + `id`: a leading pinned checkbox column. The header checkbox selects every row left after `search` / `filters` (checked, unchecked or indeterminate; clicking it again clears those rows), and shift-click selects a range in the order shown. The selection is client state at `{ \"$state\": \"/ui/<id>/selected\" }`, an array of row ids (the `rowId` field, default `id`, as strings). It is never a model write and is not shared with other viewers. `id` is a literal like `SearchInput.id`, and the validator requires it with `selectable` or `bulkActions`. Selected rows that disappear from the data drop out of the selection.\n- `bulkActions[]`: `{ label, variant?, icon?, confirm?, actions }`, the `rowActions` shape without `placement`; a non-empty list implies `selectable`. A bar under the table shows `N selected`, the buttons and Clear while the selection is non-empty. Chains have no `$row`; pass the ids with `{ \"$state\": \"/ui/<id>/selected\" }`, e.g. `{ \"action\": \"app.action\", \"params\": { \"name\": \"enqueue\", \"input\": { \"prs\": { \"$state\": \"/ui/prTable/selected\" } } } }`. Confirm rules match `rowActions`; the dialog always adds the selection size (`Applies to 3 selected rows.`). The selection is locked while the chain runs. It clears (only the rows the chain acted on) once every step succeeded, waiting for a task-backed `app.action` to finish; a failed `app.mutate` or a failed task stops the chain and keeps the selection for a retry.\n- `filterable: true` + `id`: built-in column filters. Each filterable column gets a filter button in its header: `badge`, `status`, `enum`, `boolean`, `user` and `agent` columns open a checkbox list of the distinct values with row counts (the counts follow the other active filters, so a second tick shows what it adds); a column with no kind (or `text` / `string`) opens a contains-text field; numbers, dates, links and `format` columns get none. `columns[].filter` overrides per column: `\"values\"` or `\"text\"` (works without `filterable`, and is how a `format` column opts in), or `false` to opt out. Active filters show as removable pills above the table with Clear all. The state is client state at `{ \"$state\": \"/ui/<id>/filters\" }`, an object with one entry per column (`/ui/<id>/filters/<column>`): a string array for a list, a string for text; other elements can read it. It composes with `search` and `filters`: a row must pass all three. Below 768px the header menus become one Filters button above the card list. `id` is required (the validator checks it).\n- `clearState`: state paths the Table's Clear filters button and the pills' Clear all also reset, e.g. `[\"/ui/prSearch/value\"]` for the `SearchInput` feeding `search`. Only `/ui/<id>/...` paths of controls on the page. Without it, those controls keep their value and the no-match state only offers Clear filters for the built-in filters.\n- Loading and errors: the first load (no rows yet) shows a skeleton shaped like the table, with its header labels. `loading` (`/queries/<name>/loading`) is the first load only. Bind `refreshing` to `{ \"$state\": \"/queries/<name>/fetching\" }` (true during any fetch, including the 5s poll and `app.refresh`) and a refetch with rows showing runs a slim bar along the top edge, on phones too, and never dims, covers or blanks a row. A failed query shows the error callout with a Retry button; `onRetry` is the chain it runs (default `[{ \"action\": \"app.refresh\" }]`, which re-runs every query on the page). With rows already loaded the callout sits above the stale rows; with none, it is the whole state (no empty message). A search or filter that hides every row shows \"No rows match\" with a Clear filters button; with header filters the table stays in place (header and open filter input included) and the button sits under it.\n- Smart links, tooltips and popovers (Table, DetailList, CardGrid, Markdown):\n - A `link` cell (Table `kind: \"link\"`, DetailList and CardGrid `kind: \"link\"`) shows a chip with an icon and a short label when its value is a GitHub PR, issue, commit or repo URL (`agent-swarm#2605`, `agent-swarm@a1b2c3d`, `owner/repo`), the GitHub shorthand `owner/repo#N` or `owner/repo@sha`, a dashboard task, agent, session, app, page or workflow URL (shown by its name once the dashboard knows it, else `Task 1f6feea0`), or an agent-fs file. GitHub links open in a new tab; dashboard links stay in the app. Any other http(s) URL is a plain external link, and any other value is text. Only `github.com` links are GitHub links.\n - `href: \"<row field>\"` (Table column, DetailList or CardGrid field) takes the URL from another row field, so a cell can show one field and link with another: `{ \"key\": \"number\", \"label\": \"PR\", \"format\": \"{{repo}}#{{number}}\", \"href\": \"url\" }` shows `agent-swarm#2605` as a PR chip. With `href` the cell's own text (or `format`) is the label. `linkLabel: \"<template>\"` (same `{{field}}` rules as `format`) sets the label instead, e.g. `\"Lead review\"` on a `kind: \"link\"` column.\n - `hint: \"<text>\"` on a column adds a header tooltip. A header cut off by the column width also shows its full label in the tooltip, with no config.\n - `popover: { title?: \"<template>\", fields: [...], trigger?: \"hover\" | \"click\" }` on a Table column opens a popover from the cell that lists up to 12 fields of the row, in the DetailList field shape (`{ key, label?, kind?, tones?, href?, linkLabel? }`, any DetailList kind). It opens on hover or keyboard focus by default and lets the pointer move into it; `trigger: \"click\"` toggles it from the cell; on a cell with its own controls (link, copy, switch) it opens from a separate Details button beside the content. In the phone list, link columns render as chips under the row and each popover column gets a Details button that opens on tap. Use it for detail that does not fit a column, such as a merge reason or CI status. `key` and `href` must name model columns.\n- `onRowClick`: action chain with `$row` / `$rowIndex`, run when a row is clicked (or Enter on a focused cell). Pair it with `app.navigate` that sets a Drawer param, and bind `selectedId` to `{ \"$state\": \"/route/params/<param>\" }` so the open row stays highlighted. `rowId` names the id field (default `id`).\n- Phones (below 768px): the table renders as a card list. `mobileFields: { title, subtitle?, meta?: string or string[], status? }` picks the columns; by default the first text column is the title and the first `status`/`badge` column the chip. `mobile: \"scroll\"` keeps the grid; it is the default when the table has `rowActions` but no `onRowClick`. With `selectable`, each phone card gets a checkbox beside it and a Select all row sits above the list. An editable `checkbox` / `switch` column (one with `onChange`) becomes a real control beside the card, not a line of text.\n- `emptyState: { icon?, title, body? }` replaces the plain empty message. A search or filter that hides every row shows its own \"No rows match\" state.\n- `pagination`: boolean; defaults to auto-enabling past 200 rows (set `false` to force one scroll region). `density: \"compact\"` tightens row height for dense readouts.\n- `rowActions[]`: `{ label, variant?, icon?, placement?: \"inline\" or \"menu\", confirm?, actions }`. `placement: \"menu\"` moves the action into the row's More menu. Variants add `destructive-outline` to the Button variants. `destructive` and `destructive-outline` confirm by default; customize with `{ \"title\": ..., \"description\": ..., \"confirmLabel\": ... }`, or use a bare `confirm` string as the dialog description (use `confirm: false` only for a reversible action).\n- `search`: optional string; case-insensitive substring matching across the listed string and number columns. Bind a SearchInput value for client-side search.\n- `filters`: optional record of per-column string, number, boolean, null, or array values. An array means \"the cell is one of these\" (what a `multiple` Chips or Select writes). Null, empty strings, empty arrays, or absent values disable one filter. Bind Select or Chips values for client-side filters.\n\nKanban details:\n\n- One card per `data` row, grouped by the row's `columnField` value. `columns[]` are plain strings or `{ id, label? }`, in display order; rows matching no column are hidden.\n- `cardFields[]` uses the DetailList field shape (`{ key, label?, kind?, tones? }`, same kinds) for extra lines under the title.\n- `onMove` is an action chain run when a card is dropped in another column. `$row` is the moved row with `columnField` already set to the new column: `[{ \"action\": \"app.mutate\", \"params\": { \"model\": \"deal\", \"op\": \"update\", \"rowId\": { \"$row\": \"id\" }, \"values\": { \"stage\": { \"$row\": \"stage\" } } } }]`. Without `onMove`, cards cannot be dragged.\n- `onCardClick` is an action chain with `$row`; pair it with `app.navigate` and a `Drawer` to open a card.\n\nCalendar details:\n\n- `startField` / `endField` hold ISO dates, ISO datetimes, or epoch ms. An event shows on every day from start to end; without `endField` it shows on its start day.\n- Each Calendar keeps its own visible month (prev/next controls in its header). `onSelect` is an action chain with `$row`, run when an event is clicked.\n\nContributionGraph details:\n\n- Buckets `data` rows by the calendar day of `dateField` over the trailing `days`. Each row counts 1, or adds its numeric `countField` when set.\n\nTree details:\n\n- `nodes` is a doc-shaped value: `{ root: string | string[], elements: { <key>: { type, children?: string[] } } }`, the json-render flat element map. Usually bind it to a json column: `{ \"$state\": \"/queries/<name>/data/0/<column>\" }`. A malformed or absent value renders an empty state; a `children` key missing from `elements` shows as `key — ?`. Outlines are cut at 2,000 rows with a notice; branches deeper than 32 levels keep a disabled chevron.\n- Each row shows `key — type`. Clicking a row writes its key to `/ui/<id>/value`, and the row bound to that path renders selected; read the selection with `{ \"$state\": \"/ui/<id>/value\" }`. The Tree never writes `null`: when the selected key leaves the doc (a refetch, an edit) the stored key stays and no row renders selected. Selection and collapse are keyed by node key, so a key reachable through two parents selects and collapses in both places.\n- Rows scroll inside `maxHeight` (default `480px`). Set `fill: true` inside a `fill` Stack or Split pane to grow to that height instead and scroll within it (ignores `maxHeight`).\n\nFiles and File details:\n\n- Both read agent-fs as the viewer, with the viewer's own agent-fs key (the one Comb saves in their browser), from the swarm's default drive (`agent_fs.comb` in `/status`). There is no `drive` prop yet. The swarm key never reaches agent-fs, and the viewer sees only what their drive membership allows; an app cannot widen it.\n- A viewer who has not connected agent-fs sees a \"Connect agent-fs\" card that opens Comb's connect flow. In a `?mode=chromeless` iframe the card links to the app in the dashboard instead, because the iframe has no saved key.\n- `path` is absolute. A literal path must not contain `..`; bind it with `$state` to follow a route param. A folder that does not exist yet lists as empty (`emptyMessage`).\n- `Files` sorts folders first. `mode: \"browser\"` opens subfolders in place, with crumbs that never go above `path`, and reopens on the folder holding `selectedPath`. A file click (in list mode, any row) runs `onSelect` with `$row` = `{ path, name, type, size, modifiedAt }`; `type` is `file` or `directory`, and a folder's `path` ends with `/`. Usually: `[{ \"action\": \"app.navigate\", \"params\": { \"page\": \"docs\", \"params\": { \"file\": { \"$row\": \"path\" } } } }]`, plus `\"selectedPath\": { \"$state\": \"/route/params/file\" }`.\n- `File` renders Markdown with raw HTML shown as text, images as `<img>` (SVG too, so its scripts never run), PDFs in the browser's viewer, video and audio in a player, CSV as a table, and text files (HTML as source) as lines. Other types show Download and \"Open in agent-fs\". An empty `path` shows \"No file selected\".\n- List and view: a `Split` with `Files` in the left pane and `File` with `\"path\": { \"$state\": \"/route/params/file\" }` in the right; declare `file` in the page's `params`.\n- `upload: true` adds an Upload button and a drop zone over the list. Files upload with the viewer's key into the folder on screen (the opened subfolder in browser mode), create-only: a taken name asks Keep both or Skip. The list refreshes when a file lands. agent-fs's own upload limit applies.\n- Scripts: an `app.action` script runs as its owner agent, so `ctx.fs` `/afs` reads that agent's default drive, not the viewer's. It sees the same files only when the agent's default drive is the swarm's comb drive.\n\nDateRange and Timeline details:\n\n- `DateRange` writes inclusive `YYYY-MM-DD` dates (the viewer's local calendar) to `/ui/<id>/from` and `/ui/<id>/to`, and the active preset to `/ui/<id>/preset`. On first load it writes `defaultPreset` unless the state already holds a range. Bind query params with `{ \"$state\": \"/ui/<id>/from\" }` so the query refetches when the range changes. `7d` is today and the six days before it; `mtd` starts on the 1st. `custom` opens two date inputs in a popover; Apply needs both dates, from not after to. `id` must match `[A-Za-z0-9_-]+`, and `defaultPreset` must be one of `presets`.\n- `Timeline` reads `timeField` as an ISO date or epoch ms (rows that do not parse are left out), sorts newest first and groups under day headings: Today, Yesterday, then the date. Each event shows `titleField`, the time, `descriptionField` (two lines at most) and a `statusField` pill (`tones` maps value to tone; lifecycle values get the status chip). `icon` replaces the marker dot. `onSelect` runs with `$row` (the row) and `$rowIndex` (its index in `data`); without it events are not clickable.\n\nSchemaForm details:\n\n- `schema` is a JSON schema object held in state (usually `{ \"$state\": ... }`). Each entry of `properties` becomes one control: `type: \"boolean\"` a switch, `enum` of strings a select, `type: \"number\"` or `\"integer\"` a number input, anything else a text input. `description` is the tooltip. Fields seed from `value[key]`, else the property `default`. At most 100 fields and 200 enum options render. `id` must match `[A-Za-z0-9_-]+`. Rebinding `schema` resets the form.\n- Typing updates `/ui/<id>/value` with the draft object; switches and selects commit at once and text and number inputs commit on blur. Each commit runs `onChange` with `$form` = the draft.\n- Nested document editing: bind `baseDoc` to a doc-shaped value (`{ root, elements }`) and `nodeKey` to an element key, such as a Tree's `{ \"$state\": \"/ui/<tree>/value\" }`. The form then edits `baseDoc.elements[nodeKey].props`, and `/ui/<id>/value` holds the whole doc with the edit merged in, so one `app.mutate` with `values: { <jsonColumn>: { \"$state\": \"/ui/<id>/value\" } }` persists it. Props the schema does not list are kept. Edits the query has not returned yet stay applied, so two quick edits on different nodes both survive. A `nodeKey` that is not a key of `elements` falls back to plain mode, and a `baseDoc` over 5,000 elements is not editable. Typing writes `/ui/<id>/value` on every keystroke, before the commit on blur, so another component's `app.mutate` that reads that path can persist half-typed text; persist from the SchemaForm's own `onChange`.\n\nApproval details (human-in-the-loop):\n\n- `requestId` names one approval request, usually the id an `app.action` script returned: `{ \"$state\": \"/actions/<name>/result/requestId\" }`. An empty value renders nothing, so the element can sit on the page before the request exists.\n- While the request is pending, the card shows its questions with the dashboard's answer flow and polls every 5s; polling stops once it resolves. The viewer answers with their own credential, so the server records them and enforces the approvers list and RBAC.\n- A viewer whose role cannot answer, or whose answer the server refuses (not an approver), sees a read-only card with an \"Open in dashboard\" link. If the request was answered or expired meanwhile, the card refetches and shows that state instead of an error. With an `all` or `{ min: N }` policy, an answer that does not resolve it shows \"Your answer is recorded\".\n- `showResolved: false` shows only the outcome line after resolution, not the answers. `compact: true` drops the card chrome.\n- `onResolved` is an action chain run once, when the page sees the request leave `pending`. Its params may read `{ \"$chain\": \"status\" }` (`approved`, `rejected`, `timeout`, `cancelled`), `{ \"$chain\": \"responses\" }` (answers keyed by question id; `{ \"$chain\": \"responses/<questionId>\" }` reads one), and `{ \"$chain\": \"resolvedBy\" }`. A request that was already resolved when the page loaded does not run it, so a reload never repeats the follow-up. Use `onResolved`, not `on.resolved`: the validator rejects the latter.\n\nIn-session wait: the follow-up runs in the viewer's browser, so if they close the tab before the answer, nothing continues. The script behind the action creates the request detached and returns its id:\n\n```ts\nexport default async function run(args, ctx) {\n const res: any = await ctx.swarm.request_humanInput({\n title: `Deploy ${args.service}?`,\n questions: [{ id: \"go\", type: \"approval\", label: \"Ship it to production?\" }],\n detached: true,\n });\n return { requestId: res?.data?.requestId ?? res?.requestId };\n}\n```\n\n```json\n{\n \"askBtn\": { \"type\": \"Button\", \"props\": { \"label\": \"Request deploy\", \"busyWith\": \"requestDeploy\" },\n \"on\": { \"press\": { \"action\": \"app.action\", \"params\": { \"name\": \"requestDeploy\", \"input\": { \"service\": \"api\" } } } } },\n \"approve\": {\n \"type\": \"Approval\",\n \"props\": {\n \"requestId\": { \"$state\": \"/actions/requestDeploy/result/requestId\" },\n \"onResolved\": [\n { \"action\": \"app.action\", \"params\": { \"name\": \"applyDecision\",\n \"input\": { \"status\": { \"$chain\": \"status\" }, \"responses\": { \"$chain\": \"responses\" } } } },\n { \"action\": \"ui.toast\", \"params\": { \"message\": \"Decision applied\", \"tone\": \"success\" } }\n ]\n }\n }\n}\n```\n\nDurable wait: when the follow-up must run even if nobody watches the page, put it in a workflow whose human-in-the-loop node waits server-side, and use `Approval` only to answer. A script action starts the run with `ctx.swarm.workflow_trigger({ id, triggerData, wait: false })` and returns `runId`. The request appears once the run reaches its human-in-the-loop node, so a second script action (pressed from the page, or retried) finds it and returns its id: `ctx.swarm.db_query({ sql: \"SELECT id FROM approval_requests WHERE workflowRunId = ? AND status = 'pending' ORDER BY createdAt DESC LIMIT 1\", params: [args.runId] })`, then `{ requestId: res.data.rows[0]?.[0] }`. Bind `Approval.requestId` to that action's result. The workflow resumes on the answer whether or not the page is open.\n\nSessionThread details — a chat on an app page, one session per viewer and `sessionKey`:\n\n- `sessionKey` names the session, a plain token (`^[A-Za-z0-9_-]{1,128}$`): a literal such as `\"main\"`, or a `$state` binding to a token such as a route param or row id (`{ \"$state\": \"/route/params/itemId\" }`) for one session per item. No row stores the session: the server keys every task the thread's `app.action` creates as `task:app:<appId>:<sessionKey>:user:<viewer>`, and the thread shows the viewer's newest session with that key. A page can only write sessions of its own app.\n- `scope` is `\"user\"` (the default): each viewer has their own session per key. The viewer needs an identity; with none picked the composer is disabled. `scope: \"shared\"` (one session everyone on the page writes to) comes in a follow-up PR: the validator rejects it today. The planned design adds an everyone:write session share on the root when the server creates it.\n- It renders the same conversation as the dashboard's \"Session about this page\" panel: the session turn timeline (each person message with the sender's name, the swarm's replies with a live Queued / Working status, worker steps, approvals) and the shared composer. A person bubble shows the `message` of an app-action input instead of the whole agent prompt, cut at 4,000 characters. The composer's attachments and mic are off: a message is text only.\n- Sending a message takes one of three routes:\n 1. No session yet → run `onDispatch` with `$form = { message }` and `$chain = { leafTaskId: null, newTaskId: null }`. Its `app.action` creates the session's root task.\n 2. A task in the session is not finished → the composer steers the newest such task, on any agent, with `source: \"app-page\"`. It offers Queue, and Interrupt where the harness supports it. The server promotes a steer it cannot deliver into a follow-up task (source `ui`), and a toast says so.\n 3. Every task is finished (completed, failed, cancelled, superseded, skipped, or draft) → run `onDispatch` again with `$chain.leafTaskId` set to the newest task id, so `\"parentTaskId\": { \"$chain\": \"leafTaskId\" }` chains the new task under it. The follow-up keeps the session's key.\n- Each `app.action` step of `onDispatch` is sent with the session (`{ key, scope }`) and with `followUp: false` unless the step sets `followUp` itself, so the Lead adds no review task to the chain and each message stays one task. A Lead review that is in the chain anyway (a steer the server promoted to a task) is never steered or chained under.\n- \"New session\" (shown once a session exists) starts over: the next message creates a new root, and the thread shows only sessions created after the current one. Nothing is deleted; older sessions stay in the dashboard's Sessions list.\n- While the session loads, the composer is disabled with a loading notice. A session whose chain cannot be found blocks sending. After a send, the composer stays busy until the new task shows up, for at most 30 seconds.\n- Without `fill` the thread is 420 px tall; `fill: true` fills a `fill`-aware parent. Inside an element instance, `id` is namespaced per instance, so two instances keep separate drafts.\n\n```json\n{ \"type\": \"SessionThread\", \"props\": {\n \"id\": \"chat\",\n \"sessionKey\": { \"$state\": \"/route/params/screenId\" },\n \"onDispatch\": [{ \"action\": \"app.action\", \"params\": {\n \"name\": \"editScreen\", \"input\": { \"$form\": \"\" }, \"parentTaskId\": { \"$chain\": \"leafTaskId\" } } }]\n} }\n```\n\nForm details:\n\n- `fields[]`: `{ name, label?, kind?, options?: string[], placeholder?, required? }`; `kind` is `string`, `text`, `number`, `boolean`, `date`, `enum`, or `file`, and enum fields need `options`.\n- `kind: \"file\"` adds `dir`, `accept` (e.g. `[\".pdf\", \"image/*\"]`), `multiple` and `source`: `\"upload\"` (default) chooses local files, `\"pick\"` opens a browser of `dir` (or `/`) to attach a file that already exists in agent-fs, `\"both\"` offers both. `dir` is an absolute agent-fs folder, required unless `source` is `\"pick\"`. Files use the viewer's own agent-fs key on the swarm's default drive, like `Files`.\n- On submit, chosen files upload first, create-only, to `<dir>/<timestamp>-<id>-<n>-<sanitized name>`: a random id per submit and a counter across all fields, so two fields or two submits never write the same path; then the chain runs. `$form.<name>` is the stored path, or an array of paths with `multiple: true`. An upload failure (the error shows agent-fs's text, e.g. its size limit) stops the chain and keeps the form's values. Without an agent-fs connection the field shows a \"Connect agent-fs\" card, and a required file field disables submit.\n- Values live at `/forms/<formId>/<fieldName>`. `onSubmit` is an action chain.\n- The submit button shows a pending spinner while the chain runs, and `app.mutate` failures in the chain render inline under the fields (not the page banner) — no extra wiring needed.\n\nDrawer details:\n\n- `param` must name a param declared on the containing page. The drawer is open exactly when `/route/params/<param>` has a non-empty value, so its open state survives refresh and is shareable. Its children mount only while open; closing it clears that param with history replacement.\n- `actions[]`: `{ label, variant?, icon?, confirm?, actions }`, rendered as buttons in a sticky footer under the scrolling body. Confirmation follows Table `rowActions`: destructive variants confirm by default, and a chain with an `app.mutate` delete always confirms. Chains have no `$row`; address the open record with `{ \"$state\": \"/route/params/<param>\" }`, for example `{ \"action\": \"app.mutate\", \"params\": { \"model\": \"order\", \"op\": \"delete\", \"rowId\": { \"$state\": \"/route/params/panel\" } } }`. Prev/next record navigation is not available.\n- `presentation: \"split\"` renders the Drawer as an inline right pane beside the page instead of a sheet over it. The page canvas shrinks while it is open; the pane has a draggable left edge (arrow keys, Shift for big steps, Home/End for the min/max, double-click or Enter to reset) and the viewer's width is kept per app in the browser. `size` sets its starting width (360/480/640/800px). Opening, closing, refresh and shared links work exactly as for the sheet. Below 768px it falls back to the sheet. At most one split Drawer per page; `side` does not apply.\n\nList + detail recipe (a row click opens the record beside the table):\n\n```json\n\"params\": { \"issue\": { \"kind\": \"string\" } },\n\"elements\": {\n \"root\": { \"type\": \"Stack\", \"props\": {}, \"children\": [\"table\", \"issue\"] },\n \"table\": { \"type\": \"Table\", \"props\": {\n \"data\": { \"$state\": \"/queries/issues/data\" },\n \"columns\": [{ \"key\": \"title\" }, { \"key\": \"status\", \"kind\": \"status\" }],\n \"selectedId\": { \"$state\": \"/route/params/issue\" },\n \"onRowClick\": [{ \"action\": \"app.navigate\", \"params\": { \"page\": \"main\", \"params\": { \"issue\": { \"$row\": \"id\" } } } }] } },\n \"issue\": { \"type\": \"Drawer\", \"props\": { \"param\": \"issue\", \"presentation\": \"split\", \"size\": \"md\", \"title\": \"Issue\" },\n \"children\": [\"issueDetail\"] },\n \"issueDetail\": { \"type\": \"DetailList\", \"props\": { \"data\": { \"$state\": \"/queries/issue/data/0\" }, \"fields\": [{ \"key\": \"title\" }] } }\n}\n```\n\nDetailList details:\n\n- `fields[]`: `{ key, label?, kind?, tones? }`. Kinds reuse Table formatting (`text`, `string`, `number`, `boolean`, `date`, `badge`, `enum`) and the Table cell renderers (`status`: lifecycle chip or `tones` pill; `user`: avatar plus name; `relative`: smart time, exact on hover; `copy`: value plus copy button; `link`: a smart link from the value, or from the row field named by `href`, with `linkLabel` as an optional label template), and add `code` for a monospace block and `json` for a collapsible JSON tree (objects, or a string holding JSON). `currency` and `percent` (with `currency?: \"<ISO 4217>\"`) format numbers like the Table kinds. Bind `data` to one record, commonly `/queries/<detailQuery>/data/0`.\n\nMotion details:\n\n- Every `Stack` fades its direct children in and lifts them 4px over 200ms on first paint, staggered 30ms (capped at the 10th child). It never replays on the 5s data poll. A Stack nested inside another one does not add its own entrance. `motion: \"fade\"` drops the lift; `motion: \"none\"` turns it off. Viewers with reduced motion get a 150ms fade.\n\nCardGrid details — the visual counterpart to Table for record browsers (projects, documents, media):\n\n- `titleKey` (required) picks the row field shown as the card title (an object value shows a JSON preview; titles are capped at 500 characters).\n- `imageKey` (optional) picks a row field holding an absolute http(s) image URL and adds an image tile to every card. When it is set, a non-URL value, a missing value, or a failed load shows a placeholder tile. Omit it for text-only cards with no tile.\n- `fields[]`: `{ key, kind?, tones?, href?, linkLabel? }`. `kind` is `text`, `string`, `enum`, `number`, `boolean`, `date`, `badge` (with `tones`), `link` (a smart link, with `href` / `linkLabel`), or `json` (no `label`, no `format`). A field with no `kind` whose value is an object renders like `json`. They render as an unlabeled `·`-joined meta line under the title, e.g. a `date` field for \"created\" and a `text` field for the author.\n- `columns`: same responsive shorthand as `Grid.columns` (default `{ \"base\": 1, \"sm\": 2, \"md\": 3 }`).\n- `onClick`: an action chain with `$row` / `$rowIndex`, run when a card is clicked or activated with Enter or Space. Commonly `app.navigate` into a detail page, the CardGrid equivalent of Table's `onRowClick`.\n- Bind `data` / `loading` / `error` to a named query like Table. Loading shows skeleton cards, an error shows a callout, and no rows shows `emptyMessage`.\n- It renders 200 cards at a time with a Show more button below the grid that reveals the next 200.\n\nShortcut details:\n\n- `Button.shortcut` and `SearchInput.shortcut` are one key. Letters and digits match without Shift; symbols such as `/` and `?` match as typed. They do nothing while focus is in a text field, while Ctrl, Cmd, or Alt is held, or while a dialog or menu is open (unless the control is inside it, such as a Button in an open Drawer).\n\n## Layout & interactivity\n\nFor a multi-page app that should feel like a product (a sidebar of pages, a sticky title bar with actions), set `layout: \"sidebar\"` (see Pages, routes, and page trees) instead of building navigation out of Tabs or button rows. Pair `Metric` tiles (with `sparkline`) in a `Grid` with `Chart`s inside `Card`s for dashboards.\n\nUse `Stack` as the primary page and section layout; `Container` is the legacy two-prop primitive retained for existing pages. Stack supports vertical or horizontal flow, shared spacing, alignment, justification, wrapping, and padding; row Stacks (filter bars, button rows) should set `collapseBelow: \"sm\"|\"md\"|\"lg\"` so they stack vertically on phones. Use `Grid` for responsive card or metric strips: a bare column count is responsive shorthand (1 column on phones, 2 from `sm`, the count from `md` up), or pin breakpoints explicitly with `{ \"base\": 1, \"md\": 2, \"lg\": 3 }`. `Grid` and `Split` also accept `padding` on the shared spacing scale.\n\n`Stack` and `Split` size to their content by default, so a page scrolls as a whole. Set `fill: true` to make one grow to fill the remaining height of a `fill`-aware parent (another `fill` Stack or Split) instead; chain it from the page root down through every container on the path to the element that should scroll, and that element scrolls within whatever height is left while the page itself does not. A non-`fill` sibling (a toolbar, a header) keeps its natural height and the `fill` sibling absorbs the rest. A `fill` Split stretches both panes to the full row height, so nesting a `fill` Split inside one pane of another `fill` Split is the way to build a three-or-more column viewport-height layout (`ratio` is only ever two panes).\n\n`Split` and `Tabs` children are positional. For Split, `children[0]` is the first pane, `children[1]` is the second, and extra children append inside the second pane. Below `collapseBelow`, panes stack; `reverse` changes only that narrow-layout stacking order. For Tabs, `children[i]` is the body for `tabs[i]`; keep both arrays in the same order and with the same count. Inactive tab children stay mounted but hidden, so Tables keep polling. Use `Divider` to separate sections and `Markdown` for richer explanatory content.\n\nSearchInput, Select, NumberInput, Chips, and Tree are client-side controls: each needs a literal `id` and writes state under `/ui/<id>/value` (Tree writes the clicked node key; a `selectable` Table writes its selected row ids to `/ui/<id>/selected`); Tabs writes its active key to `/ui/<id>/tab`. Bind those values into a Table's `search` and `filters` props. This filters already-polled rows locally; it does not alter or re-run the named query.\n\n```json\n{\n \"filters\": { \"type\": \"Stack\", \"props\": { \"gap\": \"sm\" }, \"children\": [\"query\", \"status\"] },\n \"query\": { \"type\": \"SearchInput\", \"props\": { \"id\": \"ideaSearch\", \"placeholder\": \"Search ideas\" } },\n \"status\": { \"type\": \"Select\", \"props\": { \"id\": \"ideaStatus\", \"options\": [\"open\", \"done\"] } },\n \"ideas\": {\n \"type\": \"Table\",\n \"props\": {\n \"data\": { \"$state\": \"/queries/allIdeas/data\" },\n \"columns\": [{ \"key\": \"title\" }, { \"key\": \"status\" }],\n \"search\": { \"$state\": \"/ui/ideaSearch/value\" },\n \"filters\": { \"status\": { \"$state\": \"/ui/ideaStatus/value\" } }\n }\n }\n}\n```\n\n`visible` accepts a boolean, a `$state` truthiness binding, comparisons, and logical groups. Put exactly one comparison key in each condition object. The renderer evaluates the first matching key in fixed priority order (`eq`, `neq`, `gt`, `gte`, `lt`, `lte`; otherwise truthiness), so additional comparison keys in the same object are ignored. Use `$and` / `$or` arrays to combine conditions. `not` is a negation FLAG inside a condition object (`\"not\": true`), never a wrapper around one — `{ \"not\": { \"$state\": … } }` is invalid and the validator rejects it. The absent-record pattern (e.g. an alert when a detail query matched nothing) is `{ \"$state\": \"/queries/<q>/data/0/id\", \"not\": true }`:\n\n```json\n[\n { \"$state\": \"/route/params/issueId\", \"gt\": 0 },\n {\n \"$and\": [\n { \"$state\": \"/route/page\", \"eq\": \"detail\" },\n { \"$state\": \"/route/params/panel\", \"neq\": \"hidden\" }\n ]\n }\n]\n```\n\n## Bindings, sentinels, and action chains\n\nUse this exact query binding shape; do not invent `$query`, `$item`, or template strings:\n\n```json\n{\n \"data\": { \"$state\": \"/queries/allIdeas/data\" },\n \"loading\": { \"$state\": \"/queries/allIdeas/loading\" },\n \"error\": { \"$state\": \"/queries/allIdeas/error\" }\n}\n```\n\nValid `$state` roots are:\n\n- `/queries/<declaredQuery>/...`\n- `/forms/<formId>/...`, where a `Form` element has that literal `props.id`\n- `/ui/<id>/...`, where a SearchInput, Select, Chips, or Tabs element has that literal `props.id` (SearchInput, Select, and Chips use `/value`; Tabs uses `/tab`)\n- `/actions/<declaredAction>/...`\n- `/route/page` for the active page name\n- `/route/params/<declaredParam>` for a param declared on the current page\n\n`/route` is mirrored as `{ page, params }`. Only declared params appear. Values are coerced by their declared kind: `number` becomes a number when possible; boolean strings `true`/`1` become true; failed number coercion remains the raw string.\n\nOnly inside action-chain `params` (`on.<event>`, `Table.rowActions[].actions`, `Table.bulkActions[].actions`, `Form.onSubmit`, or a component chain prop such as `Approval.onResolved` or `SessionThread.onDispatch`) these scoped sentinels are valid, recursively inside objects and arrays:\n\n| Sentinel | Resolves to |\n|---|---|\n| `{ \"$row\": \"id\" }` | Current Table row's `id`; another column name selects that field. |\n| `{ \"$row\": \"\" }` | Entire current Table row. |\n| `{ \"$rowIndex\": true }` | Current Table row index. |\n| `{ \"$form\": \"title\" }` | One current Form value. |\n| `{ \"$form\": \"\" }` | All current Form values. |\n| `{ \"$state\": \"/queries/allIdeas/data\" }` | Current value at a valid app state path, including action state such as `/actions/refreshIssues/status`. |\n| `{ \"$chain\": \"leafTaskId\" }` | One chain-scope value, published by the component that runs the chain: a task chain (`SessionThread`) carries `leafTaskId` and `newTaskId`; `Approval.onResolved` carries `status`, `responses` and `resolvedBy`. The component publishes every key, `null` when it has no value yet; a `null` key resolves to nothing and its param is dropped (a `parentTaskId` bound to a `null` `leafTaskId` creates a root task). Where no chain scope is published (Table, Form), or the key is not one the scope carries (a typo), the sentinel is left in place and the action fails instead of silently dropping the parent. An empty string is not \"no parent\": a `$state` slot meaning \"no parent yet\" must hold `null`. |\n| `{ \"$chain\": \"\" }` | The whole chain scope. |\n\nEach sentinel object must contain exactly the single key shown.\n\nAn action-chain step is `{ \"action\": \"<type>\", \"params\": {...} }`. Available action types:\n\n- `app.mutate`: `{ model, op, rowId?, values?, formId? }`, where `op` is `\"create\"`, `\"update\"`, or `\"delete\"`. `update`/`delete` require `rowId` (usually `{ \"$row\": \"id\" }`, or `{ \"$state\": \"/route/params/<param>\" }` in a Drawer footer); literal `values` keys must be model columns. Successful mutation refetches all queries on that model.\n- `app.refresh`: `{ query? }`; omit `query` to refetch all, or name a declared query.\n- `app.action`: `{ name, input?, parentTaskId?, followUp? }`; `name` must be declared in definition `actions`. For a task-kind row action, pass whole-row context with `input: { issue: { \"$row\": \"\" } }`. `parentTaskId` chains the created task under an existing one for task-kind actions (typically `{ \"$chain\": \"leafTaskId\" }`; a literal or `$state` task id also works); a script or sync action rejects it with 400. `followUp: false` creates the task with no Lead follow-up (the review task the Lead adds when a worker task finishes); script and sync actions ignore it. A task an action creates is attributed to the viewer's identity. `session: { key, scope }` (SessionThread sets it) keys a task-kind action's task into the viewer's session; the server builds the key, never the page.\n- `app.navigate`: `{ page, params? }`; `page` must be declared, supplied keys must be params of the target page, and every required target param must be supplied. `params` replace the current route params wholesale and may contain action sentinels. Navigation pushes history, so browser Back returns to the previous page/params; only `mode` is preserved automatically.\n- `ui.toast`: `{ message, description?, tone?, undo? }`, where `tone` is `\"success\"`, `\"error\"`, `\"info\"` (default), or `\"warning\"`. `undo: { label?, actions }` adds an Undo button (default label `Undo`) that runs `actions` as a chain; its steps are validated like any chain. Put it after the step it confirms, e.g. a row delete followed by `{ \"action\": \"ui.toast\", \"params\": { \"message\": \"Order deleted\", \"undo\": { \"actions\": [{ \"action\": \"app.mutate\", \"params\": { \"model\": \"order\", \"op\": \"create\", \"values\": { \"title\": { \"$row\": \"title\" } } } }] } } }`. Undo params resolve `$state` when Undo is pressed; `$row` / `$form` resolve when the toast is shown.\n- `swarm.sdk`: `{ sdk, args? }`; invokes a catalog-supported Swarm browser SDK method with the viewer's bearer.\n- `swarm.call`: `{ method, endpoint: \"/api/...\", body? }`, where `method` is `\"GET\"`, `\"POST\"`, `\"PUT\"`, `\"DELETE\"`, or `\"PATCH\"`; raw authenticated API call.\n\nA failed step halts its chain: when `app.action`, `app.mutate`, `swarm.sdk` or `swarm.call` fails (a thrown error, a script action that returns `ok: false`, a non-2xx `swarm.call`), the steps after it do not run and the error shows as an error toast. A step's `onError` (`{ set }` or `{ action }`) runs first, and the chain still halts. So a `ui.toast` after a write is a real success message. A `Form`'s failed `app.mutate` shows inline under the fields instead of a toast. A task-backed `app.action` succeeds once the task is created; the task's own failure shows in the page banner and does not halt the chain. A Table bulk action reads each step's own outcome, as before.\n\n## Patch semantics\n\n`app-patch.definition` is RFC 7396 JSON Merge Patch applied to the stored definition:\n\n- omitted keys stay unchanged;\n- object keys merge recursively;\n- arrays and scalar values replace;\n- `null` deletes a key;\n- reusable-element disambiguation: a patch value for `elements.<name>` containing ONLY the `elements` key merges node-by-node; any other key present (`mode`, `root`, `props`, or `export`) makes it a full element replace — restate every field you want kept. In that node-by-node form, `elements.<name>.elements.<id>: null` deletes one node. Literal null nodes are rejected in a full element replace so they cannot be mistaken for deletions.\n- otherwise every supplied `pages.<page>.elements.<id>`, `pages.<page>.params.<param>`, `actions.<name>`, `models.<name>.columns.<col>`, and `models.<name>.sources.<src>` value is atomic and replaces that complete declaration; `null` deletes it (deleting a source detaches its rows — see the source lifecycle above).\n\n`pages.<page>: null` deletes a page, except the current `defaultPage` cannot be deleted. `root`, `title`, and top-level `defaultPage` use ordinary merge semantics. A top-level `page` patch is rejected with guidance to patch `pages.<name>` instead.\n\nBecause elements, param declarations, actions, and columns are atomic, include the complete desired object when changing one. For example, changing only a Table's `emptyMessage` requires sending its full `{ \"type\": \"Table\", \"props\": ... }` element. The merged result is validated as a whole; on failure, read `issues[]`, correct the paths, and retry without assuming anything was written.\n\n```json\n{\n \"appId\": \"<app-id>\",\n \"description\": null,\n \"definition\": {\n \"models\": {\n \"idea\": {\n \"columns\": {\n \"priority\": { \"kind\": \"enum\", \"enum\": [\"low\", \"high\"], \"default\": \"low\" }\n }\n }\n },\n \"queries\": { \"openIdeas\": null },\n \"pages\": {\n \"main\": {\n \"elements\": {\n \"title\": { \"type\": \"Heading\", \"props\": { \"text\": \"Prioritized ideas\", \"level\": \"h1\" } }\n }\n }\n }\n }\n}\n```\n\n## Worked example: ideas tracker\n\nCreate this with `app-upsert`:\n\n```json\n{\n \"name\": \"Ideas Tracker\",\n \"description\": \"Collect and manage product ideas\",\n \"definition\": {\n \"models\": {\n \"idea\": {\n \"columns\": {\n \"title\": { \"kind\": \"string\", \"required\": true },\n \"status\": { \"kind\": \"enum\", \"enum\": [\"open\", \"done\"], \"default\": \"open\" }\n }\n }\n },\n \"queries\": {\n \"allIdeas\": { \"model\": \"idea\", \"sort\": { \"column\": \"createdAt\", \"dir\": \"desc\" } }\n },\n \"actions\": {\n \"triage\": { \"kind\": \"task\", \"prompt\": \"Review current ideas and recommend the next one to pursue\" }\n },\n \"pages\": {\n \"main\": {\n \"root\": \"root\",\n \"elements\": {\n \"root\": {\n \"type\": \"Container\",\n \"props\": { \"direction\": \"column\", \"gap\": \"lg\" },\n \"children\": [\"heading\", \"formCard\", \"ideasCard\", \"triage\"]\n },\n \"heading\": { \"type\": \"Heading\", \"props\": { \"text\": \"Ideas\", \"level\": \"h1\" } },\n \"formCard\": {\n \"type\": \"Card\",\n \"props\": { \"title\": \"Add an idea\" },\n \"children\": [\"ideaForm\"]\n },\n \"ideaForm\": {\n \"type\": \"Form\",\n \"props\": {\n \"id\": \"newIdea\",\n \"fields\": [{ \"name\": \"title\", \"label\": \"Title\", \"required\": true }],\n \"submitLabel\": \"Add\",\n \"onSubmit\": [{\n \"action\": \"app.mutate\",\n \"params\": { \"model\": \"idea\", \"op\": \"create\", \"values\": { \"$form\": \"\" } }\n }]\n }\n },\n \"ideasCard\": {\n \"type\": \"Card\",\n \"props\": { \"title\": \"All ideas\" },\n \"children\": [\"ideasTable\"]\n },\n \"ideasTable\": {\n \"type\": \"Table\",\n \"props\": {\n \"data\": { \"$state\": \"/queries/allIdeas/data\" },\n \"loading\": { \"$state\": \"/queries/allIdeas/loading\" },\n \"error\": { \"$state\": \"/queries/allIdeas/error\" },\n \"columns\": [\n { \"key\": \"title\", \"label\": \"Title\" },\n { \"key\": \"status\", \"label\": \"Status\", \"kind\": \"badge\", \"tones\": { \"open\": \"info\", \"done\": \"success\" } }\n ],\n \"rowActions\": [{\n \"label\": \"Delete\",\n \"variant\": \"destructive-outline\",\n \"actions\": [{ \"action\": \"app.mutate\", \"params\": { \"model\": \"idea\", \"op\": \"delete\", \"rowId\": { \"$row\": \"id\" } } }]\n }]\n }\n },\n \"triage\": {\n \"type\": \"Button\",\n \"props\": { \"label\": \"Ask swarm to triage\", \"variant\": \"secondary\" },\n \"on\": { \"press\": [{ \"action\": \"app.action\", \"params\": { \"name\": \"triage\" } }] }\n }\n }\n }\n },\n \"defaultPage\": \"main\"\n }\n}\n```\n\nThe tool returns `{ appId, url: \"/apps/<id>\" }`. Open that URL to verify the live UI, then continue with the read-patch-validate loop above.\n\n## View and screenshot a live app\n\n- An app renders at `<dashboard>/apps/<id>`. Two view modes are set by query string: `?mode=full` (full-viewport overlay with a slim header) and `?mode=chromeless` (only the rendered page, the embed surface). `app.navigate` keeps only `?mode`.\n- Logged-in browser: a fresh dashboard has no connection and redirects to /setup. Seed the localStorage key `agent-swarm-connections` with `{connections:[{id,name,apiUrl,apiKey}],activeId}`. Build the value from an env var and pipe it to `agent-browser eval --stdin`, so the key never reaches a command line. Reload, then pick a user in the \"Who are you?\" dialog.\n- Apps scroll inside an inner canvas, so a full-page screenshot captures only the viewport. Scroll the canvas or raise the viewport height. For mobile, set a 375px-wide viewport before the screenshot.\n- App definitions: `GET /api/apps` and `GET /api/apps/<id>` with the API key as Bearer.\n- Follow-up edit to a live app: list in the brief the control numbers the edit must not move, and assert them from the backing script before publishing. Take a signed-in screenshot of each changed selector at 1440px wide, save the shots to agent-fs, critique, and repeat at least 3 times. If the backing script caches results, bump its version or force a fresh run so the shots show new data.\n\n\n### Rows from agents and scripts\n\nEvery row tool requires `appId` and `model`. Scripts use underscore names, such as `ctx.swarm.app_row_create` and `ctx.swarm.app_rows_list`.\nResults use the usual `data` wrapper, so scripts read `res?.data ?? res`. Rows contain system fields and declared columns at the top level.\nWrites record `agent:<agentId>` in `createdBy` and `updatedBy`. Source projections and join keys remain read-only. Each row input must fit within 1 MiB.\n\n`app-rows-list` accepts `equals`, `sort: \"<column>:asc|desc\"`, and `limit` from 1 to 1000 (default 200).\nEquality filters accept declared columns and system columns. Filter values must match the column kind and use strict equality.\n`app-rows-delete` requires at least one equality filter and accepts a limit from 1 to 1000 (default 1000).\n\n`app-action-run` returns the REST action body under `data`. Script actions run with the script owner's identity and receive the verified invoking agent as `caller`.\nScripts and extensions cannot invoke `app-action-run`.\n";
14867
14948
 
14868
14949
  // templates/skills/ask-user/config.json
14869
14950
  var config_default3 = `{
@@ -14980,7 +15061,7 @@ var config_default4 = `{
14980
15061
  `;
14981
15062
 
14982
15063
  // templates/skills/asset-namespaces/content.md
14983
- var content_default4 = "# Asset Namespaces\n\nUse an asset `key` as directory-like grouping metadata across tasks, workflows, schedules, pages, apps, scripts, and mapped provider files. Keep identity separate: entity IDs remain authoritative, task `contextKey` remains routing context, and many assets may intentionally share one key.\n\n## Choose a namespace\n\n- Use `shared/` for general work and stable descendants such as `shared/releases/` or `shared/platform/migrations/` for team-visible groupings.\n- Use `personal/<user-id>/` or a descendant only for work owned by the trusted resolved user in the current request or task context.\n- Prefer durable organizational paths over temporary status labels. Put lifecycle state in task or workflow status fields, not paths such as `shared/in-progress/`.\n- Supply canonical values: lowercase relative paths, forward slashes, and a trailing slash. The server trims, Unicode-normalizes, lowercases, and adds the trailing slash, but rejects empty segments, `.`, `..`, backslashes, absolute paths, NUL bytes, unknown roots, and values longer than 255 characters.\n\n`personal/` is a write-ownership convention, **not** a privacy or read-visibility boundary. Continue to rely on each entity's authorization rules, and never place sensitive data under `personal/` merely because of the key.\n\n## Set and inherit keys\n\nPass `key` when creating a task, workflow, schedule, or page. Omitting it creates a deterministic shared resource key such as `shared/task:<id>/`, `shared/workflow:<id>/`, `shared/schedule:<id>/`, `shared/page:<id>/`, or `shared/fs:agent-fs:<id>/`.\n\n- Tasks sent from another task inherit the source task's key unless explicitly overridden.\n- Tasks launched by a workflow inherit the workflow key unless the agent-task node supplies a key.\n- Tasks launched by a schedule inherit the schedule key.\n- Agent-fs task attachments receive logical file mappings and inherit their task key.\n\nUse only a canonical user-registry ID in `personal/<user-id>/`. Do not substitute an agent ID, email address, Slack ID, or unverified caller-provided value. The API authorizes the destination against trusted request/task context and rejects mismatches.\n\n## Find and manage assets\n\nUse entity list tools with `key` for an exact namespace or `keyPrefix` for a subtree where those filters are exposed. For a lightweight cross-entity view, use `GET /api/assets` or the public page SDK:\n\n```js\nconst result = await window.swarmSdk.assets.list({\n keyPrefix: \"shared/releases/\",\n types: \"task,workflow,schedule,page,app,script,file\",\n limit: 100,\n});\n```\n\nMove an asset logically without changing its ID:\n\n```js\nawait window.swarmSdk.assets.move(\"workflow\", workflowId, \"shared/platform/\");\n```\n\nThe full `swarmSdk.assets` domain is:\n\n| Method | Purpose |\n|---|---|\n| `list(filters?)` | Return lightweight cross-entity summaries. |\n| `move(entityType, id, key)` | Change local namespace metadata. |\n| `registerMapping(body)` | Operator-only registration of a provider object under a logical key. |\n| `audit()` | Operator-only structural and mapping-drift audit. |\n\nProvider-backed moves are metadata-only: do not claim that a provider file, drive object, or agent-fs path was renamed or moved remotely. Repair audit warnings before retrying a blocked move.\n\n## Before writing\n\n1. Confirm whether the grouping is shared or owned by a resolved user.\n2. Keep the key non-unique and separate from entity identity or routing context.\n3. Pass the key at the highest-level parent so descendants inherit it.\n4. Use exact and prefix filters instead of scanning unrelated records.\n5. Treat personal namespaces and provider mappings according to their real authorization and remote-move limits.\n";
15064
+ var content_default4 = "# Asset Namespaces\n\nUse an asset `key` as directory-like grouping metadata across tasks, workflows, schedules, pages, apps, scripts, and mapped provider files. Keep identity separate: entity IDs remain authoritative, task `contextKey` remains routing context, and many assets may intentionally share one key.\n\n## Choose a namespace\n\n- Use `shared/` for general work and stable descendants such as `shared/releases/` or `shared/platform/migrations/` for team-visible groupings.\n- Use `personal/<user-id>/` or a descendant only for work owned by the trusted resolved user in the current request or task context.\n- Prefer durable organizational paths over temporary status labels. Put lifecycle state in task or workflow status fields, not paths such as `shared/in-progress/`.\n- Supply canonical values: lowercase relative paths, forward slashes, and a trailing slash. The server trims, Unicode-normalizes, lowercases, and adds the trailing slash, but rejects empty segments, `.`, `..`, backslashes, absolute paths, NUL bytes, unknown roots, and values longer than 255 characters.\n\n`personal/` is a write-ownership convention, **not** a privacy or read-visibility boundary. Continue to rely on each entity's authorization rules, and never place sensitive data under `personal/` merely because of the key.\n\n## Set and inherit keys\n\nPass `key` when creating a task, workflow, schedule, or page. Without inheritance, omitting it creates a deterministic shared resource key such as `shared/task:<id>/`, `shared/workflow:<id>/`, `shared/schedule:<id>/`, `shared/page:<id>/`, or `shared/fs:agent-fs:<id>/`.\n\n- Tasks sent from another task inherit the source task's key unless explicitly overridden.\n- Tasks launched by a workflow inherit the workflow key unless the agent-task node supplies a key.\n- Tasks launched by a schedule inherit the schedule key.\n- The `create-schedule` and `create_page` tools default to the calling task's group key, excluding namespace roots and resource leaves.\n- Agent-fs task attachments receive logical file mappings and inherit their task key.\n\nUse only a canonical user-registry ID in `personal/<user-id>/`. Do not substitute an agent ID, email address, Slack ID, or unverified caller-provided value. The API authorizes the destination against trusted request/task context and rejects mismatches.\n\n## Find and manage assets\n\nUse entity list tools with `key` for an exact namespace or `keyPrefix` for a subtree where those filters are exposed. For a lightweight cross-entity view, use `GET /api/assets` or the public page SDK:\n\n```js\nconst result = await window.swarmSdk.assets.list({\n keyPrefix: \"shared/releases/\",\n types: \"task,workflow,schedule,page,app,script,file\",\n limit: 100,\n});\n```\n\nMove an asset logically without changing its ID:\n\n```js\nawait window.swarmSdk.assets.move(\"workflow\", workflowId, \"shared/platform/\");\n```\n\nThe full `swarmSdk.assets` domain is:\n\n| Method | Purpose |\n|---|---|\n| `list(filters?)` | Return lightweight cross-entity summaries. |\n| `move(entityType, id, key)` | Change local namespace metadata. |\n| `registerMapping(body)` | Operator-only registration of a provider object under a logical key. |\n| `audit()` | Operator-only structural and mapping-drift audit. |\n\nProvider-backed moves are metadata-only: do not claim that a provider file, drive object, or agent-fs path was renamed or moved remotely. Repair audit warnings before retrying a blocked move.\n\n## Before writing\n\n1. Confirm whether the grouping is shared or owned by a resolved user.\n2. Keep the key non-unique and separate from entity identity or routing context.\n3. Pass the key at the highest-level parent so descendants inherit it.\n4. Use exact and prefix filters instead of scanning unrelated records.\n5. Treat personal namespaces and provider mappings according to their real authorization and remote-move limits.\n";
14984
15065
 
14985
15066
  // templates/skills/attio-interaction/config.json
14986
15067
  var config_default5 = `{
@@ -15185,7 +15266,7 @@ var config_default7 = `{
15185
15266
  `;
15186
15267
 
15187
15268
  // templates/skills/chat-sdk/content.md
15188
- var content_default7 = "# Chat SDK\n\nThe swarm receives messages from Telegram, Slack, Discord, and Microsoft Teams through the Chat SDK channel. A person mentions the bot or sends it a direct message, and the swarm creates a task for it. This skill tells you how to work on such a task.\n\n## How you know you are on a chat task\n\n- The task has `source: \"chat\"`, or it is a lead follow-up of one.\n- The task `contextKey` starts with `task:chat-sdk:`. The full form is `task:chat-sdk:<adapter>:<encoded thread id>`, for example `task:chat-sdk:telegram:555001`.\n- The task text holds the user's message. Later replies in the same thread arrive as follow-up tasks with the same `contextKey`, or as steering messages on your running task.\n- The user has four slash commands that never reach you as a task: `/help`, `/status`, `/cancel` and `/reset`. `/cancel` ends the thread's active tasks, yours included, with status `cancelled`. After `/reset` the next task has no parent task and no earlier thread context, so treat it as a new conversation.\n\nUse `get-task-details` to read the `contextKey` when you are not sure.\n\n## Reply with `chat-reply`\n\n`chat-reply { text }` posts to the thread your current task came from. It finds the thread from your task, so you do not pass ids.\n\n- Use it to ask the user a question you cannot answer yourself. Ask once, with all your questions together.\n- Use it for one short progress note when work takes more than a few minutes, such as \"Started. This takes about 10 minutes.\"\n- Do not use it for receipts (\"Got it\", \"On it\"), and do not send many progress notes.\n- It works only on a task with a `task:chat-sdk:` contextKey. A session bound to a non-chat task does not see `chat-reply` at all, because the tool is left out of its tool list.\n\n## The final summary is posted automatically\n\nWhen your task ends, the swarm posts the task output to the thread:\n\n- Completed: your `store-progress` output.\n- Failed: a \"Task failed.\" line, then the failure reason.\n- Cancelled: a \"Task cancelled.\" line, then the reason when there is one.\n\nDo not post your final answer with `chat-reply` as well. The user would get it twice. Put the answer in the `store-progress` output and stop.\n\nThe post is durable. If the platform is down, the swarm retries with backoff for up to 24 hours.\n\n## Markdown per platform\n\nWrite plain, short markdown: bold, italic, inline code, code blocks, bullet lists, and links. Avoid tables, nested lists, and HTML.\n\n| Platform | What renders | Limit per message |\n|---|---|---|\n| Telegram | Bold, italic, code, code blocks, links, lists. No tables. | 4096 characters |\n| Discord | Bold, italic, code, code blocks, lists, headings, links. No tables. | 2000 characters |\n| Slack | Converted to Slack mrkdwn: bold, italic, code, lists, links. Tables do not render well. | 4000 characters |\n| Teams | Basic markdown: bold, italic, code, lists, links. | 20000 characters |\n\nThe swarm splits longer text into several messages at line breaks. Long answers are hard to read in chat, so keep the answer short and put long material in an artifact or page, then post the link.\n\n## Attachments\n\nFiles and images the user sends in the thread are stored as attachments of the task. The task text names them. Download them with the `download-task-attachment` skill. Voice notes and audio files come with a `[Transcript of <file>]` block in the task text when the swarm has transcription configured; answer from the transcript and download the audio only when you need it. A file over the inbound limit (20 MB on Telegram) never reaches you: the task text says so and the user was already told.\n\nTo send files back, pass `attachments` to `chat-reply` (or `chat-post`): up to 10 attachment ids of your task, or agent-fs paths such as `thoughts/<agent-id>/report.pdf`. The files go out after the text. On Telegram, JPEG and PNG show as photos, MP4 as video, MP3 and M4A as audio, and anything else as a document. When a task's final output is relayed to the thread, the files attached to that task go with it, so do not send them twice.\n\nThe upload limit is 50 MB per file on Telegram and 10 MB on Discord. A larger file is not sent: the thread gets a note naming it, and the tool result lists it in `unsentFiles`. Share a link for big files.\n\n## `chat-read-thread` limits per platform\n\n`chat-read-thread { threadId, limit? }` returns the most recent messages of a thread, oldest first. The thread id is the adapter name plus the URI-decoded remainder of the contextKey. Telegram ids have no escaping, so `telegram:555001` stays as it is. Slack, Discord, and Teams ids contain `%3A` in the contextKey, so do not build the id by hand. `chat-reply` resolves the thread itself. For `chat-read-thread`, use the thread id returned by `chat-reply`, `chat-post`, or `chat-open-dm`. You can read the thread of your current task. Any other thread needs lead privileges.\n\n- Telegram has no history API. The SDK keeps the Telegram thread history it saw in the swarm database, capped at 100 messages and 7 days.\n- Teams needs the `Chat.Read.*` Graph permission on the bot. Without it, the call fails.\n- Slack and Discord return the platform history.\n\nThe task text already holds the earlier swarm messages of the thread, so read the thread only when you need more.\n\n## Other tools\n\n- `chat-post { adapter, threadId | channelId, text }` posts outside your task's thread. Lead only. Use it only when the task asks you to message another thread or channel.\n- `chat-open-dm { adapter, userId }` returns the direct-message thread id for a user. Lead only. Then post to it with `chat-post`.\n\n## Leads: `register-chat-channel`\n\nBy default every message addressed to the swarm goes to the lead. A lead can route one channel to a fixed agent or workflow:\n\n```\nregister-chat-channel { adapter: \"telegram\", channelId: \"telegram:-100123\", agentId: \"<agent id>\" }\nregister-chat-channel { adapter: \"slack\", channelId: \"slack:C123\", workflowId: \"<workflow id>\" }\nunregister-chat-channel { adapter: \"telegram\", channelId: \"telegram:-100123\" }\n```\n\nGive exactly one of `agentId` or `workflowId`. A `swarm#<agentId>` token in a message still wins over the route. A workflow mapping fires only for a bot mention or a DM; a plain reply in the subscribed thread does not start another run. Only the lead can call these tools.\n\n## Etiquette\n\n- Keep messages short. Chat is read on phones.\n- Never post secrets, tokens, internal URLs with credentials, or private data from other users. The swarm scrubs known secrets, but do not depend on it.\n- When you ask a question in a group, start with the user's name so they see it.\n- One question message is better than several.\n";
15269
+ var content_default7 = "# Chat SDK\n\nThe swarm receives messages from Telegram, Slack, Discord, and Microsoft Teams through the Chat SDK channel. A person mentions the bot or sends it a direct message, and the swarm creates a task for it. This skill tells you how to work on such a task.\n\n## How you know you are on a chat task\n\n- The task has `source: \"chat\"`, or it is a lead follow-up of one.\n- The task `contextKey` starts with `task:chat-sdk:`. The full form is `task:chat-sdk:<adapter>:<encoded thread id>`, for example `task:chat-sdk:telegram:555001`.\n- The task text holds the user's message. Later replies in the same thread arrive as follow-up tasks with the same `contextKey`, or as steering messages on your running task.\n- The user has four slash commands that never reach you as a task: `/help`, `/status`, `/cancel` and `/reset`. `/cancel` ends the thread's active tasks, yours included, with status `cancelled`. After `/reset` the next task has no parent task and no earlier thread context, so treat it as a new conversation.\n\nUse `get-task-details` to read the `contextKey` when you are not sure.\n\n## Reply with `chat-reply`\n\n`chat-reply { text }` posts to the thread your current task came from. It finds the thread from your task, so you do not pass ids.\n\n- Use it to ask the user a question you cannot answer yourself. Ask once, with all your questions together.\n- Use it for one short progress note when work takes more than a few minutes, such as \"Started. This takes about 10 minutes.\"\n- Do not use it for receipts (\"Got it\", \"On it\"), and do not send many progress notes.\n- It works only on a task with a `task:chat-sdk:` contextKey. A session bound to a non-chat task does not see `chat-reply` at all, because the tool is left out of its tool list.\n\n## The final summary is posted automatically\n\nWhen your task ends, the swarm posts the task output to the thread:\n\n- Completed: your `store-progress` output.\n- Failed: a \"Task failed.\" line, then the failure reason.\n- Cancelled: a \"Task cancelled.\" line, then the reason when there is one.\n\nDo not post your final answer with `chat-reply` as well. The user would get it twice. Put the answer in the `store-progress` output and stop.\n\nThe post is durable. If the platform is down, the swarm retries with backoff for up to 24 hours.\n\n## Markdown per platform\n\nWrite plain, short markdown: bold, italic, inline code, code blocks, bullet lists, and links. Avoid tables, nested lists, and HTML.\n\n| Platform | What renders | Limit per message |\n|---|---|---|\n| Telegram | Bold, italic, code, code blocks, links, lists. No tables. | 4096 characters |\n| Discord | Bold, italic, code, code blocks, lists, headings, links. No tables. | 2000 characters |\n| Slack | Converted to Slack mrkdwn: bold, italic, code, lists, links. Tables do not render well. | 4000 characters |\n| Teams | Basic markdown: bold, italic, code, lists, links. | 20000 characters |\n\nTables and charts go in a `card` on `chat-reply`, not in the markdown text. It posts after the text, as its own message. When the card is the answer, keep the task `output` to one line pointing at it, because the swarm posts `output` too. What a card becomes:\n\n- Slack: native Block Kit tables and charts. A spec Slack cannot draw natively is rejected, so fix it and retry.\n- Teams: an Adaptive Card with native tables and fields. Charts fall back to text.\n- Discord: an embed. Tables become pipe-delimited text rows, and charts fall back to text.\n- Telegram: formatted text with link buttons as inline buttons. Tables and charts fall back to text.\n\nThe swarm splits longer text into several messages at line breaks. Long answers are hard to read in chat, so keep the answer short and put long material in an artifact or page, then post the link.\n\n## Attachments\n\nFiles and images the user sends in the thread are stored as attachments of the task. The task text names them. Download them with the `download-task-attachment` skill. Voice notes and audio files come with a `[Transcript of <file>]` block in the task text when the swarm has transcription configured; answer from the transcript and download the audio only when you need it. A file over the inbound limit (20 MB on Telegram) never reaches you: the task text says so and the user was already told.\n\nTo send files back, pass `attachments` to `chat-reply` (or `chat-post`): up to 10 attachment ids of your task, or agent-fs paths such as `thoughts/<agent-id>/report.pdf`. The files go out after the text. On Telegram, JPEG and PNG show as photos, MP4 as video, MP3 and M4A as audio, and anything else as a document. When a task's final output is relayed to the thread, the files attached to that task go with it, so do not send them twice.\n\nThe upload limit is 50 MB per file on Telegram and 10 MB on Discord. A larger file is not sent: the thread gets a note naming it, and the tool result lists it in `unsentFiles`. Share a link for big files.\n\n## `chat-read-thread` limits per platform\n\n`chat-read-thread { threadId, limit? }` returns the most recent messages of a thread, oldest first. The thread id is the adapter name plus the URI-decoded remainder of the contextKey. Telegram ids have no escaping, so `telegram:555001` stays as it is. Slack, Discord, and Teams ids contain `%3A` in the contextKey, so do not build the id by hand. `chat-reply` resolves the thread itself. For `chat-read-thread`, use the thread id returned by `chat-reply`, `chat-post`, or `chat-open-dm`. You can read the thread of your current task. Any other thread needs lead privileges.\n\n- Telegram has no history API. The SDK keeps the Telegram thread history it saw in the swarm database, capped at 100 messages and 7 days.\n- Teams needs the `Chat.Read.*` Graph permission on the bot. Without it, the call fails.\n- Slack and Discord return the platform history.\n\nThe task text already holds the earlier swarm messages of the thread, so read the thread only when you need more.\n\n## Other tools\n\n- `chat-post { adapter, threadId | channelId, text }` posts outside your task's thread. Lead only. Use it only when the task asks you to message another thread or channel.\n- `chat-open-dm { adapter, userId }` returns the direct-message thread id for a user. Lead only. Then post to it with `chat-post`.\n\n## Leads: use-case thread\n\nA use case (a schedule and its runs under one key, see the `scheduling` skill) can post a summary of each run to one chat thread.\n\n1. When you handle the follow-up of the first run (the planning session has usually ended by then), read `kv-get { namespace: \"usecase:<key>\", key: \"thread\" }`. A stored value means that you offered before: do not offer again.\n2. Offer once: \"Do you want a summary of each run in a chat channel? Tell me the channel.\"\n3. On no: `kv-set { namespace: \"usecase:<key>\", key: \"thread\", value: { declined: true } }`.\n4. On yes: `chat-post { adapter, channelId, text }` with a one-line title, for example \"Competitor watch: one summary per run\". Then `kv-set { namespace: \"usecase:<key>\", key: \"thread\", value: { adapter, channelId, threadId: \"<threadId from chat-post>\" } }`.\n5. When you finish or review a run of the use case (the run itself, or the follow-up of a worker's run): `kv-get` the thread. When it has a `threadId`, `chat-post { adapter, threadId, text }` with the run summary and the link to its result file.\n\n## Leads: `register-chat-channel`\n\nBy default every message addressed to the swarm goes to the lead. A lead can route one channel to a fixed agent or workflow:\n\n```\nregister-chat-channel { adapter: \"telegram\", channelId: \"telegram:-100123\", agentId: \"<agent id>\" }\nregister-chat-channel { adapter: \"slack\", channelId: \"slack:C123\", workflowId: \"<workflow id>\" }\nunregister-chat-channel { adapter: \"telegram\", channelId: \"telegram:-100123\" }\n```\n\nGive exactly one of `agentId` or `workflowId`. A `swarm#<agentId>` token in a message still wins over the route. A workflow mapping fires only for a bot mention or a DM; a plain reply in the subscribed thread does not start another run. Only the lead can call these tools.\n\n## Etiquette\n\n- Keep messages short. Chat is read on phones.\n- Never post secrets, tokens, internal URLs with credentials, or private data from other users. The swarm scrubs known secrets, but do not depend on it.\n- When you ask a question in a group, start with the user's name so they see it.\n- One question message is better than several.\n";
15189
15270
 
15190
15271
  // templates/skills/code-quality/config.json
15191
15272
  var config_default8 = `{
@@ -15778,7 +15859,7 @@ Run \`SELECT name FROM pragma_table_info('<table>')\` before you guess a column.
15778
15859
 
15779
15860
  - \`agent_tasks\`: no cost column and no \`metadata\` column. Cost is \`session_costs.totalCostUsd\`, joined on \`taskId\`. Assignee \`agentId\`, creator \`creatorAgentId\`, model \`model\`, \`resolvedModel\`, \`modelSource\`. \`parentTaskId\` is the only SQL child finder, because \`key\` is unique per task.
15780
15861
  - \`scripts\`: the owner is \`createdByAgentId\`; there is no \`agentId\`. \`isScratch = 1\` marks inline \`script-run\` bodies (\`scratch-*\` names), and they outnumber named scripts many times over. Add \`isScratch = 0\` to catalog audits. To find a script's callers, group by \`isScratch\` instead of dropping scratch rows: inline runs are often the negative tests.
15781
- - \`script_runs\`: \`scriptName\`, \`agentId\`, \`status\`, \`startedAt\`, \`finishedAt\`, \`error\`. There is no duration column: use \`(julianday(finishedAt) - julianday(startedAt)) * 86400\`.
15862
+ - \`script_runs\`: \`scriptName\`, \`sourceTaskId\`, \`agentId\`, \`status\`, \`startedAt\`, \`finishedAt\`, \`error\`. There is no \`scriptId\` (the name column is \`scriptName\`) and no \`taskId\` (the task column is \`sourceTaskId\`). There is no duration column: use \`(julianday(finishedAt) - julianday(startedAt)) * 86400\`. Filter on \`scriptName\` plus a narrow \`startedAt\` window; a \`GROUP BY agentId\` over a wide window can run past the MCP budget.
15782
15863
  - \`session_costs\`: \`taskId\`, \`agentId\`, \`totalCostUsd\`, \`model\`, the token columns, \`createdAt\`.
15783
15864
 
15784
15865
  ## Operator config knobs
@@ -15790,6 +15871,7 @@ effect on the next request, no restart) and surfaced on the dashboard's
15790
15871
  | Env var | Default | Controls |
15791
15872
  |---|---|---|
15792
15873
  | \`DB_QUERY_BOUNDED_ENABLED\` | \`true\` | Master kill switch for the bounded child-process path. \`false\` restores the pre-fix synchronous, unbounded path and logs a one-time startup-class warning. |
15874
+ | \`DB_QUERY_WORKER_POOL_ENABLED\` | \`true\` | Reuse long-lived child processes for bounded queries. \`false\` spawns a fresh child per query. |
15793
15875
  | \`DB_QUERY_HTTP_BUDGET_MS\` | \`10000\` | Wall-clock budget for \`/api/db-query\` before its child process is killed. |
15794
15876
  | \`DB_QUERY_HTTP_MAX_ROWS\` | \`1000\` | Row cap for \`/api/db-query\`, regardless of how many rows the query matched. |
15795
15877
  | \`DB_QUERY_MCP_BUDGET_MS\` | \`5000\` | Wall-clock budget for the MCP \`db-query\` tool. |
@@ -20219,7 +20301,7 @@ var config_default39 = `{
20219
20301
  `;
20220
20302
 
20221
20303
  // templates/skills/scheduling/content.md
20222
- var content_default39 = '# Scheduling\n\nUse a schedule when work repeats on a clock, or when it must run once at a later time. On each tick the schedule creates one run. The run is a workflow, a catalog script, or an agent task.\n\n## Tools\n\n`list-schedules`, `create-schedule`, `update-schedule`, `patch-schedule`, `delete-schedule`, `run-schedule-now`. They are deferred. Load them with your harness tool search before the first call.\n\n## Pick the target type\n\n| The tick should | `targetType` | Required fields |\n|---|---|---|\n| Start a workflow | `workflow` | `workflowId` |\n| Run a catalog script | `script` | `scriptName`, optional `scriptArgs` |\n| Put a reasoning agent in the loop | `agent-task` (default) | `taskTemplate` |\n\nChoose `agent-task` only when the run needs judgment, open-ended work, or tool orchestration that no workflow or script covers. An `agent-task` whose template says "trigger workflow X" or "run script Y" is wrong: use the direct target instead.\n\nThe agent-task fields `targetAgentId`, `profile`, `model`, `modelTier`, `taskTemplate`, `priority`, and `tags` do not apply to workflow or script targets. Workflow cooldowns still gate workflow targets.\n\n## Pick the timing\n\n| Shape | Fields |\n|---|---|\n| Recurring on a cron | `scheduleType: "recurring"`, `cronExpression` (for example `0 9 * * 1-5`), `timezone` (default `UTC`) |\n| Recurring on an interval | `scheduleType: "recurring"`, `intervalMs` (for example `3600000` for hourly) |\n| Once, at a time | `scheduleType: "one_time"`, `runAt` (ISO datetime) |\n| Once, after a delay | `scheduleType: "one_time"`, `delayMs` |\n\nGive the schedule a unique `name` and a one-line `description` that says what a human gets from it.\n\n## Write the task template (agent-task target)\n\nThe template is the whole task the agent receives. It must state:\n\n- the goal and the inputs (IDs, repo, channel),\n- where the result goes (a page, agent-fs, a Slack thread, a task output),\n- what done looks like.\n\n`targetAgentId` pins the task to one agent. Omit it to use the pool. `profile` is the preferred way to pick a model: a named harness + model + effort (see `list-model-profiles`). With `targetAgentId`, the agent must pass the profile check (`check-model-profile`), or the save is refused. `model` is a provider-specific override. `modelTier` is deprecated: pass `profile: "<harness>-<tier>"` for the same model. `profile` is exclusive with `model` and `modelTier`; on update, setting one clears the other.\n\nTasks created by a schedule are automatic tasks. Their completed output is not stored as memory unless the agent calls `store-progress` with `persistMemory: true`.\n\n## Check back later\n\nA task whose answer needs time (a build, a deploy, a reply) calls `defer-task` with `delayMs` or `runAt`, a `summary` of what you did so far, and a `note` that says what is pending. The tool completes the task and creates the one-off schedule for you. The task reaches its final state (`completed`) on this call, and the `summary` becomes its output. The wake-up task carries the deferred task as its parent, so you receive that task\'s context. Add `checks` to list what to verify on wake-up. Do not hand-roll this with `create-schedule`.\n\nWhen waiting on tasks, include `wakeOn:{event:"settled",taskIds:["<id>"],mode:"all"}` alongside `delayMs` or `runAt`. The displayed time is a ceiling; matching task outcomes wake you sooner. The task whose outcome wakes you creates no separate follow-up for you; the wake-up task is where you review it. In `mode:"all"`, a member that settles while others are pending still creates its follow-up.\n\n## Secrets\n\nA `taskTemplate` and `scriptArgs` are stored as plain text and replayed on every run. They must not contain a token, password, or key. Call the external API from a script through a registered connection or a credential binding instead. See the `swarm-scripts` skill, section Secrets.\n\n## Verify before you leave\n\n1. `run-schedule-now` once and read the run result.\n2. `list-schedules` with `name` to confirm `nextRunAt` and `enabled`.\n3. For a script target, the script must exist at global scope: `script-search` by name.\n\n## Repair a failing schedule\n\nSchedules fail in two places. A schedule whose spawned tasks fail: `get-tasks` with `scheduleId` and `status: "failed"`. A schedule the scheduler could not dispatch at all: `list-schedules` with `lastRunStatus: "failed"` or `consecutiveErrorsMin: 1`; these errors back off and auto-disable after 5. The `list-schedules` filters never see spawned-task failures. Fix the cause, then `run-schedule-now` to confirm. A schedule you cannot fix now: `patch-schedule` with `enabled: false` and say so in your task output. A second schedule next to a broken one is not a fix.\n\n## Related skills\n\n- `scheduled-task-resilience`: waiting on CI, builds, deploys, or other slow jobs inside a scheduled task.\n- `swarm-scripts`: writing the script a `script` target runs.\n- `workflow-iterate`: building and testing the workflow a `workflow` target starts.\n';
20304
+ var content_default39 = '# Scheduling\n\nUse a schedule when work repeats on a clock, or when it must run once at a later time. On each tick the schedule creates one run. The run is a workflow, a catalog script, or an agent task.\n\n## Tools\n\n`list-schedules`, `create-schedule`, `update-schedule`, `patch-schedule`, `delete-schedule`, `run-schedule-now`. They are deferred. Load them with your harness tool search before the first call.\n\n## Pick the target type\n\n| The tick should | `targetType` | Required fields |\n|---|---|---|\n| Start a workflow | `workflow` | `workflowId` |\n| Run a catalog script | `script` | `scriptName`, optional `scriptArgs` |\n| Put a reasoning agent in the loop | `agent-task` (default) | `taskTemplate` |\n\nChoose `agent-task` only when the run needs judgment, open-ended work, or tool orchestration that no workflow or script covers. An `agent-task` whose template says "trigger workflow X" or "run script Y" is wrong: use the direct target instead.\n\nThe agent-task fields `targetAgentId`, `profile`, `model`, `modelTier`, `taskTemplate`, `priority`, and `tags` do not apply to workflow or script targets. Workflow cooldowns still gate workflow targets.\n\n## Pick the timing\n\n| Shape | Fields |\n|---|---|\n| Recurring on a cron | `scheduleType: "recurring"`, `cronExpression` (for example `0 9 * * 1-5`), `timezone` (default `UTC`) |\n| Recurring on an interval | `scheduleType: "recurring"`, `intervalMs` (for example `3600000` for hourly) |\n| Once, at a time | `scheduleType: "one_time"`, `runAt` (ISO datetime) |\n| Once, after a delay | `scheduleType: "one_time"`, `delayMs` |\n\nGive the schedule a unique `name` and a one-line `description` that says what a human gets from it.\n\n## Write the task template (agent-task target)\n\nThe template is the whole task the agent receives. It must state:\n\n- the goal and the inputs (IDs, repo, channel),\n- where the result goes (a page, agent-fs, a Slack thread, a task output),\n- what done looks like.\n\n`targetAgentId` pins the task to one agent. Omit it to use the pool. `profile` is the preferred way to pick a model: a named harness + model + effort (see `list-model-profiles`). With `targetAgentId`, the agent must pass the profile check (`check-model-profile`), or the save is refused. `model` is a provider-specific override. `modelTier` is deprecated: pass `profile: "<harness>-<tier>"` for the same model. `profile` is exclusive with `model` and `modelTier`; on update, setting one clears the other.\n\nTasks created by a schedule are automatic tasks. Their completed output is not stored as memory unless the agent calls `store-progress` with `persistMemory: true`.\n\n## Use cases: one key for the schedule and its results\n\nA recurring job that a person comes back to is a use case. Its planning session, the schedule, the runs, pages, and result files share one asset key, so the dashboard shows them as one Sessions group.\n\n- The key is `shared/<slug>/`, or `personal/<user>/<slug>/` for private work. Agree the short slug with the requester, for example `shared/competitor-watch/`.\n- `create-schedule` and `create-page` use the key of the calling task when that key is a use-case group. Otherwise pass `key` explicitly. Runs get the schedule\'s key.\n- The task template tells each run to write its result under the key in the shared drive, for example `shared/competitor-watch/report-<YYYY-MM-DD>.md`, and to compare with the earlier reports in that folder.\n- End the planning reply with the "lives in" line: `This use case lives in Sessions → competitor-watch: <APP_URL>/sessions?view=shared/competitor-watch/`.\n\n### One-time ask or lasting change\n\nIn a use-case session, decide what the request changes:\n\n- A request for one time only ("also check Acme today"): a normal task in the key. Do not change the schedule.\n- A request that changes the future runs ("from now on also include pricing"): change the schedule. Read the current template with `list-schedules` (`key` is the use-case key), then call `update-schedule` with the full new `taskTemplate`:\n\n```\nupdate-schedule { scheduleId: "<id>", taskTemplate: "Research the 5 competitors in shared/competitor-watch/competitors.md. Include their pricing. Write shared/competitor-watch/report-<YYYY-MM-DD>.md and compare with the previous report." }\n```\n\nThen show the change as a `diff` block in your reply, and ask the requester to confirm it:\n\n```diff\n- Research the 5 competitors in shared/competitor-watch/competitors.md. Write shared/competitor-watch/report-<YYYY-MM-DD>.md and compare with the previous report.\n+ Research the 5 competitors in shared/competitor-watch/competitors.md. Include their pricing. Write shared/competitor-watch/report-<YYYY-MM-DD>.md and compare with the previous report.\n```\n\n## Check back later\n\nA task whose answer needs time (a build, a deploy, a reply) calls `defer-task` with `delayMs` or `runAt`, a `summary` of what you did so far, and a `note` that says what is pending. The tool completes the task and creates the one-off schedule for you. The task reaches its final state (`completed`) on this call, and the `summary` becomes its output. The wake-up task carries the deferred task as its parent, so you receive that task\'s context. Add `checks` to list what to verify on wake-up. Do not hand-roll this with `create-schedule`.\n\nWhen waiting on tasks, include `wakeOn:{event:"settled",taskIds:["<id>"],mode:"all"}` alongside `delayMs` or `runAt`. The displayed time is a ceiling; matching task outcomes wake you sooner. The task whose outcome wakes you creates no separate follow-up for you; the wake-up task is where you review it. In `mode:"all"`, a member that settles while others are pending still creates its follow-up.\n\n## Secrets\n\nA `taskTemplate` and `scriptArgs` are stored as plain text and replayed on every run. They must not contain a token, password, or key. Call the external API from a script through a registered connection or a credential binding instead. See the `swarm-scripts` skill, section Secrets.\n\n## Verify before you leave\n\n1. `run-schedule-now` once and read the run result.\n2. `list-schedules` with `name` to confirm `nextRunAt` and `enabled`.\n3. For a script target, the script must exist at global scope: `script-search` by name.\n\n## Repair a failing schedule\n\nSchedules fail in two places. A schedule whose spawned tasks fail: `get-tasks` with `scheduleId` and `status: "failed"`. A schedule the scheduler could not dispatch at all: `list-schedules` with `lastRunStatus: "failed"` or `consecutiveErrorsMin: 1`; these errors back off and auto-disable after 5. The `list-schedules` filters never see spawned-task failures. Fix the cause, then `run-schedule-now` to confirm. A schedule you cannot fix now: `patch-schedule` with `enabled: false` and say so in your task output. A second schedule next to a broken one is not a fix.\n\n## Related skills\n\n- `scheduled-task-resilience`: waiting on CI, builds, deploys, or other slow jobs inside a scheduled task.\n- `swarm-scripts`: writing the script a `script` target runs.\n- `workflow-iterate`: building and testing the workflow a `workflow` target starts.\n';
20223
20305
 
20224
20306
  // templates/skills/script-builder/config.json
20225
20307
  var config_default40 = `{
@@ -20269,7 +20351,7 @@ var content_default41 = "Use this skill when a user asks to launch, monitor, ins
20269
20351
  var config_default42 = '{\n "kind": "skill",\n "name": "slack-interaction",\n "displayName": "Slack Interaction",\n "slug": "slack-interaction",\n "title": "Slack Interaction",\n "description": "Slack: reply, post, read, upload, and the thread rules. What the engine already posts, the one-message rule, `slack-reply`, `slack-post`, `slack-start-thread`, `slack-read`, `slack-upload-file`, `slack-download-file`, `slack-list-channels`, `slack-update`, `slack-delete`, unknown-user registration with `manage-user`, and Slack standing orders. Use before any Slack message.",\n "version": "1.0.0",\n "category": "skills",\n "placeholders": [],\n "runAllSeedersCandidate": true,\n "systemDefault": true,\n "tags": ["slack", "communication"]\n}\n';
20270
20352
 
20271
20353
  // templates/skills/slack-interaction/content.md
20272
- var content_default42 = '# Slack interaction\n\n## What the engine posts\n\nFor every task that came from Slack, the engine owns the thread tree and the top-level outcome card. It posts the start, the completion, and the failure. You do not.\n\n## Your one message\n\n- At most one message per task, and only when the outcome card will not carry it: a question, a decision the requester must make, a link to a page or file with one line of context.\n- Progress, receipts, acknowledgments, and relayed worker output stay out of Slack.\n- Concrete content. The length matches what the requester asked for.\n- The "How you write" rules of your system prompt apply. Slack renders mrkdwn: `*bold*`, `_italic_`, `` `code` ``, `<url|text>` for links. Markdown headings and tables do not render.\n\n## Where to post\n\nThe task carries `slackChannelId` and `slackThreadTs` in its metadata. A follow-up task with `parentTaskId` inherits them.\n\n- Reply in the task\'s thread: `slack-reply` with `taskId` and `message`.\n- Reply to an inbox message: `slack-reply` with `inboxMessageId`.\n- New top-level message in a channel (lead): `slack-start-thread` with `channelId`, then `slack-post` with the returned `ts` as `threadTs` for replies under it.\n- Fix your own message: `slack-update` (text) or `slack-delete` (lead). Both work only on messages this bot authored.\n\n## Tools\n\n| Tool | Use |\n|---|---|\n| `slack-reply` | reply in a thread by `taskId` or `inboxMessageId` |\n| `slack-post` | post to a channel, optional `threadTs` (lead) |\n| `slack-start-thread` | post a top-level message and get its `ts` (lead) |\n| `slack-read` | read a thread by `taskId` or `inboxMessageId`, or a channel by `channelId` (lead) |\n| `slack-list-channels` | channels the bot is a member of |\n| `slack-upload-file` | upload a file to a thread or channel, up to 1 GB |\n| `slack-download-file` | attach a Slack file (by ID or URL) to your task; run the `fetchCommand` it returns to get the bytes |\n| `slack-update` | edit your own message |\n| `slack-delete` | delete your own message (lead) |\n| `slack-create-channel`, `slack-invite-to-channel`, `slack-archive-channel` | channel lifecycle (lead) |\n\nFiles attached to your task already come with download commands in the task message. Use those before `slack-download-file`. `slack-read` on your task also attaches the files in the thread and gives each one a `fetchCommand`. Don\'t look for Slack files under `/app/shared` or `/workspace/shared/downloads`: those paths are the API server\'s disk.\n\n## Message limits\n\n- Text sent without `blocks` is split into sections under Slack\'s 3,000-character section limit for you. With explicit `blocks`, keep each section\'s text at or under 3,000 characters yourself.\n- Truncate user text by code point (`Array.from(s).slice(0, n).join("")`), never with `s.slice(0, n)`: cutting an emoji in half leaves a lone UTF-16 surrogate, and Slack rejects the blocks with `invalid_blocks_format`.\n\n## Unknown user\n\nA task without `requestedByUserId` came from a Slack user the swarm does not know. Register them with `manage-user`, using the Slack user ID and display name from the task metadata, then continue. When you learn a requester\'s stable preferences (language, tone, verbosity), the lead stores them in the user\'s `comms` field with `manage-user`.\n\n## Lead standing orders\n\nWhen your heartbeat runbook says so, check for unaddressed requests older than one hour: `slack-list-channels`, then `slack-read` per channel, then create a task for each open request.\n\n## Scripts-only mode\n\nThe named Slack tools are not registered. Use `script-run` with inline source: `ctx.swarm.slack_reply({ taskId, message })`. The task ID carries the thread context.\n\n## Status and blocker questions\n\nAnswer for the scope of the place the question was asked. In a customer or project channel or thread, "current blockers" or "what\'s the status" means that customer\'s or project\'s work: its tracker, its PRs, its open asks. Answer swarm-wide only in a DM or an ops channel, or when the person asks for it. Name the scope you used in the first line.\n';
20354
+ var content_default42 = '# Slack interaction\n\n## What the engine posts\n\nFor every task that came from Slack, the engine owns the thread tree and the top-level outcome card. It posts the start, the completion, and the failure. You do not.\n\n## Your one message\n\n- At most one message per task, and only when the outcome card will not carry it: a question, a decision the requester must make, a link to a page or file with one line of context, or a table, chart or key figures. Send the last as a `slack-reply` `card` and keep the task `output` to one line pointing at it: the outcome card posts `output` too.\n- Progress, receipts, acknowledgments, and relayed worker output stay out of Slack.\n- Concrete content. The length matches what the requester asked for.\n- The "How you write" rules of your system prompt apply. Slack renders mrkdwn: `*bold*`, `_italic_`, `` `code` ``, `<url|text>` for links. Markdown headings and tables do not render. For a table or chart, send a `card`.\n\n## Where to post\n\nThe task carries `slackChannelId` and `slackThreadTs` in its metadata. A follow-up task with `parentTaskId` inherits them.\n\n- Reply in the task\'s thread: `slack-reply` with `taskId` and `message`.\n- Reply to an inbox message: `slack-reply` with `inboxMessageId`.\n- New top-level message in a channel (lead): `slack-start-thread` with `channelId`, then `slack-post` with the returned `ts` as `threadTs` for replies under it.\n- Fix your own message: `slack-update` (text) or `slack-delete` (lead). Both work only on messages this bot authored.\n\n## Tools\n\n| Tool | Use |\n|---|---|\n| `slack-reply` | reply in a thread by `taskId` or `inboxMessageId` |\n| `slack-post` | post to a channel, optional `threadTs` (lead) |\n| `slack-start-thread` | post a top-level message and get its `ts` (lead) |\n| `slack-read` | read a thread by `taskId` or `inboxMessageId`, or a channel by `channelId` (lead) |\n| `slack-list-channels` | channels the bot is a member of |\n| `slack-upload-file` | upload a file to a thread or channel, up to 1 GB |\n| `slack-download-file` | attach a Slack file (by ID or URL) to your task; run the `fetchCommand` it returns to get the bytes |\n| `slack-update` | edit your own message |\n| `slack-delete` | delete your own message (lead) |\n| `slack-create-channel`, `slack-invite-to-channel`, `slack-archive-channel` | channel lifecycle (lead) |\n\nFiles attached to your task already come with download commands in the task message. Use those before `slack-download-file`. `slack-read` on your task also attaches the files in the thread and gives each one a `fetchCommand`. Don\'t look for Slack files under `/app/shared` or `/workspace/shared/downloads`: those paths are the API server\'s disk.\n\n## Message limits\n\n- Text sent without `blocks` is split into sections under Slack\'s 3,000-character section limit for you. With explicit `blocks`, keep each section\'s text at or under 3,000 characters yourself.\n- Truncate user text by code point (`Array.from(s).slice(0, n).join("")`), never with `s.slice(0, n)`: cutting an emoji in half leaves a lone UTF-16 surrogate, and Slack rejects the blocks with `invalid_blocks_format`.\n\n## Unknown user\n\nA task without `requestedByUserId` came from a Slack user the swarm does not know. Register them with `manage-user`, using the Slack user ID and display name from the task metadata, then continue. When you learn a requester\'s stable preferences (language, tone, verbosity), the lead stores them in the user\'s `comms` field with `manage-user`.\n\n## Use-case thread (lead)\n\nA use case (a schedule and its runs under one key, see the `scheduling` skill) can post a summary of each run to one Slack thread.\n\n1. When you handle the follow-up of the first run (the planning session has usually ended by then), read `kv-get { namespace: "usecase:<key>", key: "thread" }`. A stored value means that you offered before: do not offer again.\n2. Offer once: "Do you want a summary of each run in a Slack channel? Tell me the channel."\n3. On no: `kv-set { namespace: "usecase:<key>", key: "thread", value: { declined: true } }`.\n4. On yes: `slack-start-thread { channelId, message }` with a one-line title, for example "Competitor watch: one summary per run". Then `kv-set { namespace: "usecase:<key>", key: "thread", value: { adapter: "slack", channelId, threadTs: "<ts from slack-start-thread>" } }`.\n5. When you finish or review a run of the use case (the run itself, or the follow-up of a worker\'s run): `kv-get` the thread. When it has a `threadTs`, `slack-post { channelId, threadTs, message }` with the run summary and the link to its result file.\n\n## Lead standing orders\n\nWhen your heartbeat runbook says so, check for unaddressed requests older than one hour: `slack-list-channels`, then `slack-read` per channel, then create a task for each open request.\n\n## Scripts-only mode\n\nThe named Slack tools are not registered. Use `script-run` with inline source: `ctx.swarm.slack_reply({ taskId, message })`. The task ID carries the thread context.\n\n## Status and blocker questions\n\nAnswer for the scope of the place the question was asked. In a customer or project channel or thread, "current blockers" or "what\'s the status" means that customer\'s or project\'s work: its tracker, its PRs, its open asks. Answer swarm-wide only in a DM or an ops channel, or when the person asks for it. Name the scope you used in the first line.\n';
20273
20355
 
20274
20356
  // templates/skills/step-running/config.json
20275
20357
  var config_default43 = `{
@@ -20401,6 +20483,7 @@ Fetch the page as markdown: \`curl -fsSL https://docs.agent-swarm.dev/llms.mdx/d
20401
20483
  - [Performance & Resource Sizing](https://docs.agent-swarm.dev/docs/guides/performance-resource-sizing). Reference.
20402
20484
  - [Cost & context computation](https://docs.agent-swarm.dev/docs/guides/cost-and-context-computation). Reference.
20403
20485
  - [Extensions](https://docs.agent-swarm.dev/docs/guides/extensions). Reference.
20486
+ - [File import](https://docs.agent-swarm.dev/docs/guides/file-import). Reference.
20404
20487
  - [Scripts runtime](https://docs.agent-swarm.dev/docs/guides/scripts-runtime). Reference.
20405
20488
  - [Agent capabilities and tool allowlist](https://docs.agent-swarm.dev/docs/guides/agent-capabilities). Reference.
20406
20489
  - [Scripts-only mode (code-mode)](https://docs.agent-swarm.dev/docs/guides/scripts-only-mode). Reference.
@@ -20477,7 +20560,7 @@ var config_default45 = `{
20477
20560
  "displayName": "Swarm Extensions",
20478
20561
  "slug": "swarm-extensions",
20479
20562
  "title": "Swarm Extensions",
20480
- "description": "Write, install, and manage swarm extensions: TypeScript hook bundles that block, modify, or observe task creation, follow-ups, Slack routing, heartbeat remediation, and tool calls. Covers installing predefined catalog extensions (templates/extensions, YAML or JSON manifests) by name and, when EXTENSION_ALLOW_INLINE_INSTALL is on, installing an inline manifest plus files as a lead, plus the scripts, schedules, workflows and skills extensions ship, the hook contract, where to fetch swarm-extension.d.ts, the extension-catalog, extension-install and extension-list tools, config schemas, and the operator enable step.",
20563
+ "description": "Write, install, and manage swarm extensions: TypeScript hook bundles that block, modify, or observe task creation, follow-ups, Slack routing, heartbeat remediation, and tool calls. Defaults to building and using inline bundles on the current swarm, with worker handoff to a lead or operator and catalog promotion only when a human asks. Covers inline install configuration, catalog installs by name, plus the scripts, schedules, workflows and skills extensions ship, the hook contract, where to fetch swarm-extension.d.ts, the extension-catalog, extension-install and extension-list tools, config schemas, and the operator enable step.",
20481
20564
  "version": "1.0.0",
20482
20565
  "category": "skills",
20483
20566
  "placeholders": [],
@@ -20494,10 +20577,14 @@ An extension is a trusted TypeScript hook bundle that runs inside the swarm API
20494
20577
 
20495
20578
  Do not use an extension for work that one task, one script, or one schedule can do.
20496
20579
 
20497
- ## Two ways to install
20580
+ ## Build and use it on this swarm first
20581
+
20582
+ For a new or custom extension, write an inline bundle (manifest plus every referenced file), install it on the swarm you are on, enable it, and use it. No PR or deploy is needed. Extensions are custom swarm behavior first; promoting one for other deployments comes later.
20498
20583
 
20499
- - **Catalog** (always on): a predefined extension in the repo (\`templates/extensions/<name>/\`), installed by name. Any authenticated agent can do it. To ship a catalog extension, open a PR that adds a template directory (see Bundle shape below); it becomes installable once that build is deployed.
20500
- - **Inline** (opt-in): a \`manifest\` plus a \`files\` map in the install request, with no PR and no deploy. It is off unless an operator sets \`EXTENSION_ALLOW_INLINE_INSTALL=true\` (dashboard Settings > Configuration > Security & access, or the API environment). With the flag off the install fails with \`inline_install_disabled\`. With it on, only a lead, operator, or dashboard user may send an inline bundle; a worker gets 403 and stays catalog-only. An inline bundle runs as code in the API process once enabled, so write it as carefully as a catalog one.
20584
+ - **Inline (default authoring path):** send \`manifest\` plus a \`files\` map. This requires \`EXTENSION_ALLOW_INLINE_INSTALL=true\` and a lead, operator, or dashboard user. An inline bundle runs as code in the API process once enabled, so write it as carefully as a catalog one.
20585
+ - **Worker handoff:** workers cannot send inline bundles (403). Stage the full bundle, including the manifest and every file, where a lead can read it, such as \`/workspace/shared/extensions/<name>/\` or agent-fs. Hand the location and install/enable steps to a lead or operator; do not open a catalog PR to work around worker permissions.
20586
+ - **Flag off:** ask an operator to turn on \`EXTENSION_ALLOW_INLINE_INSTALL\` (Settings > Configuration > Security & access, or the API environment). Inline requests otherwise fail with \`inline_install_disabled\`. A catalog template PR is a fallback only if the operator will not enable inline installs and a human asks to promote the extension.
20587
+ - **Catalog (promotion):** an existing predefined extension can be installed by name by any authenticated agent. A PR adding \`templates/extensions/<name>/\` promotes a proven extension to every deployment once that build ships. Open one only when a human asks for promotion.
20501
20588
 
20502
20589
  Both paths run the same validation and both land disabled.
20503
20590
 
@@ -20552,6 +20639,29 @@ curl -s "$MCP_BASE_URL/api/extensions/type-defs" \\
20552
20639
 
20553
20640
  ## Bundle shape
20554
20641
 
20642
+ Only \`runtime: "api"\` is supported. Inline and catalog bundles use the same manifest and referenced files.
20643
+
20644
+ ### Inline bundle
20645
+
20646
+ An inline install sends the same manifest as a JSON object, plus every file it references in \`files\`, keyed by bundle path:
20647
+
20648
+ \`\`\`json
20649
+ {
20650
+ "manifest": {
20651
+ "name": "require-ticket-ref",
20652
+ "description": "Blocks REST and MCP tasks that do not name a ticket",
20653
+ "version": "1.0.0",
20654
+ "runtime": "api",
20655
+ "assets": { "hooks": "hooks.ts" }
20656
+ },
20657
+ "files": { "hooks.ts": "import { block, type SwarmExtension } from \\"swarm-extension\\";\\n..." }
20658
+ }
20659
+ \`\`\`
20660
+
20661
+ \`files\` must hold \`assets.hooks\`, each script \`file\`, each workflow \`file\`, and for each skill \`dir\` its \`SKILL.md\` plus any \`files/**\`. A file the manifest does not reference is rejected. Naming rules (\`<name>-\` prefixes, schedule scripts declared in \`assets.scripts\`) are the same as for a template. To change an inline extension, send the full bundle again under the same name; it adds a new version.
20662
+
20663
+ ### Catalog template reference (promotion only)
20664
+
20555
20665
  A predefined extension is a directory \`templates/extensions/<name>/\` with exactly one manifest, \`manifest.yaml\`, \`manifest.yml\` or \`manifest.json\`, plus the files it references and a \`README.md\`. Only \`runtime: "api"\` is supported. Type the manifest with the generated JSON Schema, \`templates/extensions/manifest.schema.json\`:
20556
20666
 
20557
20667
  \`\`\`yaml
@@ -20581,24 +20691,7 @@ A workflow file holds \`name\`, optional \`description\`, \`definition\`, and op
20581
20691
 
20582
20692
  A JSON manifest carries \`"$schema": "../manifest.schema.json"\` instead. After changing a template, run \`bun run build:extension-catalog\` and commit \`src/extensions/catalog.generated.json\`.
20583
20693
 
20584
- ### Inline bundle
20585
-
20586
- An inline install sends the same manifest as a JSON object, plus every file it references in \`files\`, keyed by bundle path:
20587
-
20588
- \`\`\`json
20589
- {
20590
- "manifest": {
20591
- "name": "require-ticket-ref",
20592
- "description": "Blocks REST and MCP tasks that do not name a ticket",
20593
- "version": "1.0.0",
20594
- "runtime": "api",
20595
- "assets": { "hooks": "hooks.ts" }
20596
- },
20597
- "files": { "hooks.ts": "import { block, type SwarmExtension } from \\"swarm-extension\\";\\n..." }
20598
- }
20599
- \`\`\`
20600
-
20601
- \`files\` must hold \`assets.hooks\`, each script \`file\`, each workflow \`file\`, and for each skill \`dir\` its \`SKILL.md\` plus any \`files/**\`. A file the manifest does not reference is rejected. Naming rules (\`<name>-\` prefixes, schedule scripts declared in \`assets.scripts\`) are the same as for a template. To change an inline extension, send the full bundle again under the same name; it adds a new version.
20694
+ ### Hook rules (all bundles)
20602
20695
 
20603
20696
  Rules for \`hooks.ts\`:
20604
20697
 
@@ -20652,7 +20745,7 @@ export default extension;
20652
20745
  ## Verify
20653
20746
 
20654
20747
  1. Call \`extension-list\` and confirm the name, version, and \`enabled: false\`. The install response lists the assets it created.
20655
- 2. Report the enable step. After a lead or operator enables it, the dashboard run log shows every dispatch with its result (\`continue\`, \`modify\`, \`block\`, or \`error\`).
20748
+ 2. Enable it as a lead or operator, or hand off the enable step to one. After it is enabled, the dashboard run log shows every dispatch with its result (\`continue\`, \`modify\`, \`block\`, or \`error\`).
20656
20749
  3. Trigger the event once and confirm the effect (for example, a blocked REST task returns HTTP 422 with your reason).
20657
20750
 
20658
20751
  ## Common mistakes
@@ -20663,7 +20756,7 @@ export default extension;
20663
20756
  - Modifying fields the event does not allow. Read the \`*Modify\` type for that event.
20664
20757
  - Expecting the extension to run after install. Its hooks, schedules, workflows, and skills are off until a lead or operator enables it.
20665
20758
  - Expecting agents to see an extension skill after enable. Install it on each agent with \`skill-install\`.
20666
- - Sending an inline \`manifest\`/\`files\` bundle as a worker, or without \`EXTENSION_ALLOW_INLINE_INSTALL\` on. Workers use a catalog \`template\`; with the flag off ask an operator to turn it on, or ship a catalog template.
20759
+ - Sending an inline \`manifest\`/\`files\` bundle as a worker, or without \`EXTENSION_ALLOW_INLINE_INSTALL\` on. Workers stage the full inline bundle for a lead or operator. With the flag off, ask an operator to turn it on; a catalog PR requires a human promotion request and is a fallback only if the operator will not enable inline installs.
20667
20760
  - Sending both \`template\` and \`manifest\`/\`files\`. Pick one.
20668
20761
  - Blocking tasks from every origin. Check \`event.origin\` so schedules, workflows, and follow-ups keep working unless you mean to block them.
20669
20762
  `;
@@ -20682,8 +20775,8 @@ A swarm script is TypeScript that runs out of process with a typed Swarm SDK. On
20682
20775
  |---|---|
20683
20776
  | 1 to 9 SDK calls, result fits in context | Direct tool calls. |
20684
20777
  | 10 or more similar calls, bulk or fan-out | Script. Inline \`script-run\` for a one-off, a named script for reuse. |
20685
- | Fetch, parse, and transform heavy data | Script, or \`ctx_*\` (context-mode) when your harness has it. |
20686
- | One large web fetch | \`ctx_fetch_and_index\` (context-mode). |
20778
+ | Fetch, parse, and transform heavy data | Script. |
20779
+ | One large web fetch | Script with \`ctx.stdlib.fetch\`. Return only the part you need. |
20687
20780
  | A schedule, workflow, or API script that reads or writes drive files | Script with \`ctx.fs\` and \`ctx.sh\`. |
20688
20781
  | Multi-agent fan-out, parallel work, deterministic pipeline | Workflow. See \`workflow-iterate\`. |
20689
20782
  | Work that repeats on a clock | Schedule. See \`scheduling\`. |
@@ -20737,13 +20830,26 @@ export default async function (args: z.infer<typeof argsSchema>, ctx: ScriptCont
20737
20830
  - \`args\` can be \`undefined\` when a caller passes none. Guard with \`argsSchema.safeParse(args ?? {})\` or optional chaining.
20738
20831
  - Export a Zod \`argsSchema\` from every named script. \`script-upsert\` converts it to JSON Schema, so callers, schedules, and workflows see the input contract.
20739
20832
  - Both \`zod\` and \`zod/mini\` imports work. Use \`import * as z from "zod/mini"\` for smaller QuickJS bundles. Mini uses functional forms: \`z.optional(z.string())\`, \`z._default(z.number(), 10)\`, and \`z.string().check(z.minLength(1))\`; its schemas still have \`.parse()\` and \`.safeParse()\`.
20740
- - Inline source through \`script-run\` runs without a typecheck. \`script-upsert\` typechecks before it saves. Import \`ScriptContext\` from \`"swarm-sdk"\` in inline code too, so promotion to a named script works.
20833
+ - Inline source through \`script-run\` runs without a typecheck. \`script-upsert\` typechecks before it saves. Import \`ScriptContext\` from \`"swarm-sdk"\` in inline code too, so promotion to a named script works. A worker's \`script-upsert\` saves at agent scope; a global-scope upsert is rejected unless you are the lead. To share a script, send the lead its name and \`contentHash\` to promote.
20741
20834
  - SDK methods return \`Promise<unknown>\`. Responses are usually wrapped: read \`res?.data ?? res\`. Exception: \`app_query\` with a literal \`appId\` and \`query\` returns rows typed from the app's columns.
20742
20835
  - \`agentId\` is propagated through the \`X-Agent-ID\` header, so SDK calls run as you. \`taskId\` is not ambient: pass it in \`args\` when the script calls \`task_storeProgress\`.
20743
20836
  - A script invoked from a workflow node may run under a workflow identity. The node may also supply arguments the script needs: when you run that script directly, pass the same arguments the node maps. A script without a strict \`argsSchema\` then fails deeper in, often as a not-found or resource error instead of a validation error.
20744
20837
  - Return compact structured data. Raw logs, full HTML, big JSON arrays, and file contents stay inside the script.
20745
20838
  - Limits: about 30 s wall clock (up to 5 minutes where the tool exposes it), 1 MB stdout. Never sleep or loop past about 25 s. Chain \`wait-for-task\` calls instead. The cap also applies to a script called through \`ctx.step.swarmScript\`; the step's \`timeoutMs\` does not extend it. A long LLM call, such as a 2,000-word draft, goes in a \`ctx.step.rawLlm\` step inside \`launch-script-run\`, never in a called script. A \`targetType: "script"\` schedule gets 60 s; a manual \`script-run\` gets 30 s, so a candidate that finishes well under 30 s by hand has margin on the schedule. A nested \`ctx.swarm.script_run\` gets its own 30 s but runs inside its caller's remaining time: run slow children as sibling calls from the outer script, not deeper in the chain. The run ends when your default export resolves. A call you did not await gets about 2 s more and is then stopped (\`quickjs\` aborts it at once), so await every write that must land. That makes a \`Promise.race\` deadline bound the run; a nested \`script_run\` that lost the race keeps running on the server under its own 30 s.
20746
20839
 
20840
+ ### Upserting a large source
20841
+
20842
+ A large source pasted inline into a \`script-upsert\` tool call overflows the call. Write the source to a local file, then send it from bash through the same route, \`POST $MCP_BASE_URL/api/scripts/upsert\`. The body is JSON (\`name\`, \`source\`, optional \`description\`, \`intent\`, \`scope\`), so wrap the file instead of sending it raw:
20843
+
20844
+ \`\`\`bash
20845
+ jq -n --arg name my-script --rawfile source ./my-script.ts '{name: $name, source: $source}' \\
20846
+ | curl -sS -X POST "$MCP_BASE_URL/api/scripts/upsert" \\
20847
+ -H "Authorization: Bearer $API_KEY" -H "X-Agent-ID: $AGENT_ID" \\
20848
+ -H "Content-Type: application/json" --data-binary @-
20849
+ \`\`\`
20850
+
20851
+ The route runs the same typecheck and scope rules as the tool.
20852
+
20747
20853
  ### What \`ctx\` holds
20748
20854
 
20749
20855
  - \`ctx.swarm.*\`: the swarm SDK. \`task_get\`, \`task_send\`, \`task_storeProgress\`, \`task_action\`, \`task_list\`, \`slack_reply\`, \`memory_search\`, \`memory_store\`, \`kv_get\`, \`kv_getOrNull\`, \`kv_set\`, \`kv_delete\`, \`kv_incr\`, \`kv_list\`, \`swarm_get\`, \`agent_info\`, \`db_query\`, and more. \`kv_getOrNull\` returns the entry, \`null\` on a missing key, and throws on other errors.
@@ -20751,7 +20857,8 @@ export default async function (args: z.infer<typeof argsSchema>, ctx: ScriptCont
20751
20857
  - \`ctx.swarm.config\`: \`apiKey\`, \`agentId\`, \`mcpBaseUrl\`, and \`ctx.swarm.config.get("KEY")\` for swarm config values, resolved for the agent running the script (agent scope over global, the same rows \`get-config\` returns for that agent). A key that is not set returns \`undefined\`, so \`config.get("KEY") ?? fallback\` works. All are \`Redacted\` wrappers that stringify to \`<redacted>\`. Never unwrap one into a return value, a log line, or a request body you build by hand.
20752
20858
  - \`ctx.api.<slug>\` and \`ctx.mcp.<slug>\`: typed clients for registered connections. They exist only for registered connections. Introspect with \`Object.keys(ctx.api ?? {})\` and \`Object.keys(ctx.mcp ?? {})\`.
20753
20859
  - \`ctx.fs\` and \`ctx.sh\`: files and bash. See "Files and shell" below.
20754
- - \`ctx.stdlib\`: \`fetch\`, \`fetchJson\` (retries, 30 s timeout), \`grep\`, \`glob\`, \`table\`, \`Redacted\`.
20860
+ - \`ctx.stdlib\`: \`fetch\`, \`fetchJson\` (retries, 30 s timeout), \`grep\`, \`glob\`, \`table\`, \`retry\`, \`Redacted\`.
20861
+ - Retries: \`ctx.swarm\` calls retry a 429 on any call, and a 502/503/504 or network error on reads and on writes that send an idempotency key (such as \`workflow_trigger\` with \`idempotencyKey\`), within about 5 s. \`ctx.stdlib.fetch\` retries a 429 on any method and a 502/503/504 or network error on GET, HEAD, OPTIONS, PUT and DELETE. A POST or PATCH retries those only with an \`Idempotency-Key\` header: pass \`retry: { idempotencyKey: true }\` to send one UUID on every attempt. The key prevents a duplicate only when the server dedupes by it. \`retry: false\` makes one attempt. Wrap anything else, sync or async, in \`ctx.stdlib.retry(fn, { retries, minDelayMs, maxDelayMs, budgetMs, retryOn })\`; it rethrows the last error or returns the last result when attempts run out.
20755
20862
  - \`ctx.logger\`: \`log\`, \`warn\`, \`error\`. Keep logs short.
20756
20863
 
20757
20864
  ### Files and shell
@@ -21722,7 +21829,7 @@ var config_default53 = `{
21722
21829
  `;
21723
21830
 
21724
21831
  // templates/skills/work-on-task/content.md
21725
- var content_default53 = '# Working on a task\n\nThe taskId follows the command. Without one, call `get-tasks` with `mineOnly: true` and take your `pending` or `in_progress` task. If there is none, say so and stop.\n\nThis message carries the task text, its attachments, its output format, and memories from past sessions. If it does not (you invoked this command yourself, or the context was compacted), run the `task-context-gathering` script with the taskId.\n\nWhen the task names a skill (`researching`, `planning`, `implementing`), use it. Otherwise work directly.\n\nFinish the task with one of the four endings in your operating contract: `completed`, `defer-task`, `request-human-input`, or `failed`. Then stop.\n\nA lesson that would change how the next agent works goes in `learning` on that last `store-progress` call: line 1 a title, line 2 the rule ("When X, do Y"), then evidence. Leave it out for a status line, a restatement of the output, or text already in a skill.\n\nResuming (a resume task, or work cut by a graceful shutdown): read the parent\'s last progress line, then re-read live state once (PR state and head SHA, branch, `git status`) before new work. Re-run controls only if the head moved. Never redo a pushed commit or open a second PR for the same branch. Store a progress line with branch, PR number and head SHA each time you push. A document task has no branch: its live state is the brief\'s agent-fs output path and the task attachments. Read the parent task\'s output and any agent-fs draft path it names before rewriting. Run `agent-fs ls` on that path, download any partial and extend it; a superseded parent with empty output and no draft means a rebuild, not an extension. Then list the task\'s local work directory: a shutdown can leave the newest draft only there, or leave cache files half-written. Parse every cache file, delete the ones that fail, and re-run only the stages whose output is missing. Never re-run collection steps that already produced artifacts. A render task (video, image, generated page) has no branch either: its live state is the local project directory plus the brief\'s agent-fs output. List both; timestamps are hints only. Before reusing an output, verify that it exists, is complete and valid, and corresponds to the current sources and render settings (for example, using recorded input/settings hashes). Download remote output and verify its bytes and provenance; agent-fs listing dates alone do not establish freshness. Re-render missing, invalid, incomplete or stale output. Hand over the live app link `${AGENT_FS_LIVE_URL}/file/~/<org>/<drive>/<path>` by default. Use a share link only when the requester asked for one or the reader has no agent-fs login: then reuse a usable one, and create a missing one or replace an expired, revoked or view-exhausted one without re-rendering a valid unchanged output. A task that covers several PRs re-reads every PR in scope (state, mergedAt, head SHA), not only the first: a PR that merged during the shutdown takes no more pushes. If your task\'s `model` differs from the parent\'s, say so in the output, because the result\'s provenance changed.\n\nWrite times in replies, outputs and defer notes in the requester\'s timezone when the Requester Profile names one, never raw UTC.\n\nIf the user interrupts, follow their instructions. To resume, call `/work-on-task <taskId>` again.\n';
21832
+ var content_default53 = '# Working on a task\n\nThe taskId follows the command. Without one, call `get-tasks` with `mineOnly: true` and take your `pending` or `in_progress` task. If there is none, say so and stop.\n\nThis message carries the task text, its attachments, its output format, and memories from past sessions. If it does not (you invoked this command yourself, or the context was compacted), run the `task-context-gathering` script with the taskId.\n\nWhen the task names a skill (`researching`, `planning`, `implementing`), use it. Otherwise work directly.\n\nFinish the task with one of the four endings in your operating contract: `completed`, `defer-task`, `request-human-input`, or `failed`. Then stop.\n\nA lesson that would change how the next agent works goes in `learning` on that last `store-progress` call: line 1 a title, line 2 the rule ("When X, do Y"), then evidence. Leave it out for a status line, a restatement of the output, or text already in a skill.\n\nResuming (a resume task, or work cut by a graceful shutdown): read the parent\'s last progress line, then re-read live state once (PR state and head SHA, branch, `git status`) before new work. Re-run controls only if the head moved. Never redo a pushed commit or open a second PR for the same branch. Store a progress line with branch, PR number and head SHA each time you push. A document task has no branch: its live state is the brief\'s agent-fs output path and the task attachments. Read the parent task\'s output and any agent-fs draft path it names before rewriting. Run `agent-fs ls` on that path, download any partial and extend it; a superseded parent with empty output and no draft means a rebuild, not an extension. Then list the task\'s local work directory: a shutdown can leave the newest draft only there, or leave cache files half-written. Parse every cache file, delete the ones that fail, and re-run only the stages whose output is missing. Before re-running a collection, call `list-script-runs` with your `agentId` and reuse the output (`get-script-run`) of each completed run that started after the parent task started. Never re-run collection steps that already produced artifacts. A render task (video, image, generated page) has no branch either: its live state is the local project directory plus the brief\'s agent-fs output. List both; timestamps are hints only. Before reusing an output, verify that it exists, is complete and valid, and corresponds to the current sources and render settings (for example, using recorded input/settings hashes). Download remote output and verify its bytes and provenance; agent-fs listing dates alone do not establish freshness. Re-render missing, invalid, incomplete or stale output. Hand over the file link from the Outputs section of your system prompt (the dashboard when configured) by default. Use a share link only when the requester asked for one or the reader has no agent-fs login: then reuse a usable one, and create a missing one or replace an expired, revoked or view-exhausted one without re-rendering a valid unchanged output. A task that covers several PRs re-reads every PR in scope (state, mergedAt, head SHA), not only the first: a PR that merged during the shutdown takes no more pushes. If your task\'s `model` differs from the parent\'s, say so in the output, because the result\'s provenance changed.\n\nWrite times in replies, outputs and defer notes in the requester\'s timezone when the Requester Profile names one, never raw UTC.\n\nIf the user interrupts, follow their instructions. To resume, call `/work-on-task <taskId>` again.\n';
21726
21833
 
21727
21834
  // templates/skills/workflow-iterate/config.json
21728
21835
  var config_default54 = `{
@@ -21857,9 +21964,9 @@ Use these shapes as a starting point, then confirm them against the current exec
21857
21964
 
21858
21965
  **Before you add the first \`system-one-decision\` node to a workflow, confirm its key works.** A node with no working key fails its whole run, and a save only warns. Do these in order and stop at the first failure:
21859
21966
 
21860
- 1. Pick the provider. \`typesafe\` (the default) needs the global secret \`TYPESAFE_API_KEY\`. \`openrouter\` needs \`OPENROUTER_API_KEY\`. \`laya\` needs the global secret \`LAYA_API_KEY\` and the global config \`LAYA_URL\`, the base URL of its server. \`openai\` needs \`OPENAI_DECISIONS_API_KEY\` (never \`OPENAI_API_KEY\`). \`cloudflare\` needs the global secret \`CLOUDFLARE_API_TOKEN\` and the global config \`CLOUDFLARE_ACCOUNT_ID\`. Use the provider the requester named. If they named none, use \`typesafe\`. If its key is missing but another provider's key exists, ask which to use rather than switching, because the accounts bill separately.
21967
+ 1. Pick the provider. \`typesafe\` needs the global secret \`TYPESAFE_API_KEY\`. \`openrouter\` needs \`OPENROUTER_API_KEY\`. \`laya\` needs the global secret \`LAYA_API_KEY\` and the global config \`LAYA_URL\`, the base URL of its server. \`openai\` needs \`OPENAI_DECISIONS_API_KEY\` (never \`OPENAI_API_KEY\`). \`cloudflare\` needs the global secret \`CLOUDFLARE_API_TOKEN\` and the global config \`CLOUDFLARE_ACCOUNT_ID\`. Use the provider the requester named. If they named none, omit \`provider\` to follow \`SYSTEM_ONE_DEFAULT_PROVIDER\`: the global config row takes precedence over the environment value, with \`typesafe\` as the fallback when neither names a valid decision provider. Check that setting before choosing the key to verify. If its key is missing but another provider's key exists, ask which to use rather than switching, because the accounts bill separately.
21861
21968
  2. Check the key is set: \`get-config\` with \`key\` set to that name and no \`includeSecrets\`. A masked value (\`********\`) means a value exists. No entry means it is missing. Never pass \`includeSecrets\`, and never read the value. For \`laya\`, check \`LAYA_URL\` the same way, and for \`cloudflare\`, \`CLOUDFLARE_ACCOUNT_ID\`; neither is secret, so the value shows.
21862
- 3. Confirm it works with one cheap call. Create a throwaway one-node workflow, trigger it, read the run, then \`delete-workflow\` it:
21969
+ 3. Confirm the selected provider works with one cheap call. If the requester explicitly selected a provider, set \`config.provider\` to that same literal in both the ping node and the actual workflow node. For example, an explicit TypeSafe request needs \`"provider": "typesafe"\` in the ping even when the configured default is OpenRouter. Omit \`provider\` in both nodes only when inheriting configuration; the example below uses that inherited configuration. Create a throwaway one-node workflow, trigger it, read the run, then \`delete-workflow\` it:
21863
21970
 
21864
21971
  \`\`\`json
21865
21972
  {
@@ -21868,7 +21975,6 @@ Use these shapes as a starting point, then confirm them against the current exec
21868
21975
  "id": "ping",
21869
21976
  "type": "system-one-decision",
21870
21977
  "config": {
21871
- "provider": "typesafe",
21872
21978
  "state": "ping",
21873
21979
  "questions": { "ping": { "type": "noul", "instructions": "Is the state the word ping?" } },
21874
21980
  "returns": { "ping": { "type": "noul" } },
@@ -21880,7 +21986,7 @@ Use these shapes as a starting point, then confirm them against the current exec
21880
21986
  }
21881
21987
  \`\`\`
21882
21988
 
21883
- A \`completed\` run means the key works. A \`failed\` run carries the reason: \`<KEY> is not configured\` (missing; for \`laya\` it can name \`LAYA_URL\` or \`LAYA_API_KEY\`, or both), or \`<KEY> was rejected by <host> (HTTP 401)\` (present but refused). To probe \`laya\`, set \`"provider": "laya"\` in the ping node. If \`create-workflow\` says \`system-one-decision\` is an unregistered executor type, the node is not deployed on this swarm yet: stop and say so.
21989
+ A \`completed\` run means the key works. A \`failed\` run carries the reason: \`<KEY> is not configured\` (missing; for \`laya\` it can name \`LAYA_URL\` or \`LAYA_API_KEY\`, or both), or \`<KEY> was rejected by <host> (HTTP 401)\` (present but refused). A successful ping verifies only the provider it ran against; it does not verify another provider's credential. If \`create-workflow\` says \`system-one-decision\` is an unregistered executor type, the node is not deployed on this swarm yet: stop and say so.
21884
21990
  4. If the key is missing or was rejected, **do not build the node.** Ask a human for it with a \`request-human-input\` question of type \`config\`, one question per key, and share the returned URL in the thread:
21885
21991
 
21886
21992
  \`\`\`json
@@ -21896,8 +22002,6 @@ Afterwards, a \`warnings\` entry on \`create-workflow\` or a patch tool means th
21896
22002
  "type": "system-one-decision",
21897
22003
  "inputs": { "pr": "trigger.pullRequest" },
21898
22004
  "config": {
21899
- "provider": "typesafe",
21900
- "model": "jev-1.13.0",
21901
22005
  "state": "{{pr}}",
21902
22006
  "questions": {
21903
22007
  "ready": {
@@ -21917,7 +22021,7 @@ Afterwards, a \`warnings\` entry on \`create-workflow\` or a patch tool means th
21917
22021
  }
21918
22022
  \`\`\`
21919
22023
 
21920
- - \`provider\` is \`typesafe\` (default), \`openrouter\`, \`laya\`, \`openai\`, or \`cloudflare\`, and must be a literal, not a \`{{token}}\`. \`model\` is that provider's own id (\`jev-1.13.0\` on \`typesafe\`, \`typesafe/jev-1.13\` on \`openrouter\`, a checkpoint name such as \`multilingual\` on \`laya\`); \`gpt-6-luna\` on \`openai\`, \`clef\` (default) or \`clef-flash\` on \`cloudflare\`, which accepts no other id; leave it unset for the provider's default. \`laya\` has no default and sends no \`model\`, because it silently ignores one it does not know: leave it unset unless you mean a specific checkpoint. Every provider returns the same output; \`openai\` gets a translated request, and an OpenAI refusal of any question fails the step. \`cloudflare\` takes at most 64 questions. There is no fallback between them. Never use OpenRouter's \`typesafe/jev-router\`, which is a chat router that hands the request to another model.
22024
+ - \`provider\` is optional. Set it when the requester explicitly selects a provider, using the same literal verified by the ping. Omit it only when inheriting configuration to follow \`SYSTEM_ONE_DEFAULT_PROVIDER\` at run time (global config row, then environment, then \`typesafe\`). An explicit provider is \`typesafe\`, \`openrouter\`, \`laya\`, \`openai\`, or \`cloudflare\`, and must be a literal, not a \`{{token}}\`. \`model\` is that provider's own id (\`jev-1.13.0\` on \`typesafe\`, \`typesafe/jev-1.13\` on \`openrouter\`, a checkpoint name such as \`multilingual\` on \`laya\`); \`gpt-6-luna\` on \`openai\`, \`clef\` (default) or \`clef-flash\` on \`cloudflare\`, which accepts no other id; leave it unset for the provider's default. \`laya\` has no default and sends no \`model\`, because it silently ignores one it does not know: leave it unset unless you mean a specific checkpoint. Every provider returns the same output; \`openai\` gets a translated request, and an OpenAI refusal of any question fails the step. \`cloudflare\` takes at most 64 questions. There is no fallback between them. Never use OpenRouter's \`typesafe/jev-router\`, which is a chat router that hands the request to another model.
21921
22025
  - \`state\` is required: text, a string array, or a JSON object. An exact \`{{token}}\` keeps the upstream JSON type. Every question in one call shares the state and cannot see the other answers, so a dependent judgment needs its own node.
21922
22026
  - Each question is \`noul\` (probability that a claim is true; optional \`criteria: { true, false }\`), \`choice\` (2 to 255 options; \`criteria: { option: description }\`), or \`score\` (2 to 10 ordered levels; \`criteria: [level, ...]\`).
21923
22027
  - \`returns\` repeats every question id and its type. A mismatch is rejected when the workflow is saved.
@@ -25237,79 +25341,8 @@ var skillsSeeder = {
25237
25341
  retire: () => retireSeedSkills()
25238
25342
  };
25239
25343
 
25240
- // src/be/seed/runner.ts
25241
- init_state_db();
25242
- async function runSeeder(seeder, opts) {
25243
- const result = {
25244
- kind: seeder.kind,
25245
- created: 0,
25246
- updated: 0,
25247
- skippedUnchanged: 0,
25248
- skippedUserModified: 0,
25249
- retired: 0,
25250
- failed: []
25251
- };
25252
- const items = await seeder.items();
25253
- for (const item of items) {
25254
- try {
25255
- const upstream = await seeder.upstreamHash(item);
25256
- if (upstream === null) {
25257
- await seeder.apply(item, "create", opts);
25258
- await recordSeedState(seeder.kind, item.key, item.contentHash);
25259
- result.created += 1;
25260
- continue;
25261
- }
25262
- const state = await getSeedState(seeder.kind, item.key);
25263
- if (upstream === item.contentHash) {
25264
- if (state?.seededHash !== item.contentHash) {
25265
- await recordSeedState(seeder.kind, item.key, item.contentHash);
25266
- }
25267
- result.skippedUnchanged += 1;
25268
- continue;
25269
- }
25270
- const pristine = state ? upstream === state.seededHash : false;
25271
- if (!pristine) {
25272
- result.skippedUserModified += 1;
25273
- continue;
25274
- }
25275
- await seeder.apply(item, "update", opts);
25276
- await recordSeedState(seeder.kind, item.key, item.contentHash);
25277
- result.updated += 1;
25278
- } catch (err) {
25279
- result.failed.push({
25280
- key: item.key,
25281
- error: err instanceof Error ? err.message : String(err)
25282
- });
25283
- }
25284
- }
25285
- if (seeder.retire) {
25286
- try {
25287
- result.retired = (await seeder.retire()).length;
25288
- } catch (err) {
25289
- result.failed.push({
25290
- key: "(retire)",
25291
- error: err instanceof Error ? err.message : String(err)
25292
- });
25293
- }
25294
- }
25295
- if (!opts?.quiet) {
25296
- console.log(`[seed:${result.kind}] created=${result.created} updated=${result.updated} ` + `unchanged=${result.skippedUnchanged} preserved=${result.skippedUserModified} ` + `retired=${result.retired} failed=${result.failed.length}`);
25297
- for (const f of result.failed) {
25298
- console.error(`[seed:${result.kind}] FAILED ${f.key}: ${f.error}`);
25299
- }
25300
- }
25301
- return result;
25302
- }
25303
- async function runSeeders(seeders, opts) {
25304
- const results = [];
25305
- for (const seeder of seeders) {
25306
- results.push(await runSeeder(seeder, opts));
25307
- }
25308
- return results;
25309
- }
25310
-
25311
25344
  // src/be/seed/schedules-seeder.ts
25312
- var import_cron_parser = __toESM(require_dist2(), 1);
25345
+ var import_cron_parser = __toESM(require_dist(), 1);
25313
25346
 
25314
25347
  // templates/schedules/daily-blocker-digest/config.json
25315
25348
  var config_default57 = `{
@@ -26502,6 +26535,23 @@ var content_default67 = '# Weekly Harness Upgrade Check\n\nThis is a topology-pr
26502
26535
  init_db4();
26503
26536
  init_db3();
26504
26537
  init_automation_toggle();
26538
+
26539
+ // src/be/seed/seed-toggle.ts
26540
+ init_env_flag();
26541
+ function isSeedScriptsEnabled(env = process.env) {
26542
+ return isEnvFlagEnabled("SEED_SCRIPTS_ENABLED", true, env);
26543
+ }
26544
+ function isSeedSkillsEnabled(env = process.env) {
26545
+ return isEnvFlagEnabled("SEED_SKILLS_ENABLED", true, env);
26546
+ }
26547
+ function isSeedWorkflowsEnabled(env = process.env) {
26548
+ return isEnvFlagEnabled("SEED_WORKFLOWS_ENABLED", true, env);
26549
+ }
26550
+ function isSeedSchedulesEnabled(env = process.env) {
26551
+ return isEnvFlagEnabled("SEED_SCHEDULES_ENABLED", true, env);
26552
+ }
26553
+
26554
+ // src/be/seed/schedules-seeder.ts
26505
26555
  init_workflows_seeder();
26506
26556
  var TARGET_TYPES = ["agent-task", "workflow", "script"];
26507
26557
  var asText2 = (value) => value;
@@ -26694,16 +26744,22 @@ function nextRunAt(schedule) {
26694
26744
  throw new Error(`Invalid cron expression: ${message}`);
26695
26745
  }
26696
26746
  }
26697
- function createSchedulesSeeder(sources = BUILT_IN_SCHEDULE_SOURCES) {
26747
+ function createSchedulesSeeder(sources = BUILT_IN_SCHEDULE_SOURCES, env = process.env) {
26698
26748
  const schedules = loadSeedSchedules(sources);
26749
+ const scriptsEnabled = isSeedScriptsEnabled(env);
26750
+ const workflowsEnabled = isSeedWorkflowsEnabled(env);
26699
26751
  return {
26700
26752
  kind: "schedule",
26701
- items() {
26702
- return schedules.map((schedule) => ({
26703
- key: schedule.name,
26704
- contentHash: scheduleSeedHash(schedule),
26705
- schedule
26706
- }));
26753
+ async items() {
26754
+ const items = [];
26755
+ for (const schedule of schedules) {
26756
+ if (schedule.targetType === "script" && !scriptsEnabled && !await getScript({ name: schedule.scriptName, scope: "global" }))
26757
+ continue;
26758
+ if (schedule.targetType === "workflow" && !workflowsEnabled && !(await listWorkflows2()).some((workflow) => workflow.name === schedule.workflow))
26759
+ continue;
26760
+ items.push({ key: schedule.name, contentHash: scheduleSeedHash(schedule), schedule });
26761
+ }
26762
+ return items;
26707
26763
  },
26708
26764
  async upstreamHash(item) {
26709
26765
  const existing = await getScheduledTaskByName2(item.key);
@@ -26745,13 +26801,19 @@ var schedulesSeeder = createSchedulesSeeder();
26745
26801
 
26746
26802
  // src/be/seed/registry.ts
26747
26803
  init_workflows_seeder();
26748
- var SEEDERS = [
26749
- agentFsProvisionSeeder,
26750
- scriptsSeeder,
26751
- skillsSeeder,
26752
- workflowsSeeder,
26753
- schedulesSeeder
26754
- ];
26804
+ function buildSeeders(env = process.env) {
26805
+ const seeders = [agentFsProvisionSeeder2];
26806
+ if (isSeedScriptsEnabled(env))
26807
+ seeders.push(scriptsSeeder);
26808
+ if (isSeedSkillsEnabled(env))
26809
+ seeders.push(skillsSeeder);
26810
+ if (isSeedWorkflowsEnabled(env))
26811
+ seeders.push(workflowsSeeder);
26812
+ if (isSeedSchedulesEnabled(env))
26813
+ seeders.push(createSchedulesSeeder(undefined, env));
26814
+ return seeders;
26815
+ }
26816
+ var SEEDERS = buildSeeders();
26755
26817
  function runAllSeeders(opts) {
26756
26818
  return runSeeders(SEEDERS, opts);
26757
26819
  }