@desplega.ai/agent-swarm 2.13.5 → 2.14.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 (414) hide show
  1. package/dist/acp-adapter-99n6z9ky.js +17 -0
  2. package/dist/{acp-targets-w8dbs4nr.js → acp-targets-23exz4z4.js} +10 -10
  3. package/dist/{actions-8zrcbjrx.js → actions-zcr25x27.js} +60 -39
  4. package/dist/{agent-fs-provision-cbt2ttds.js → agent-fs-provision-7fa9e12e.js} +4 -4
  5. package/dist/{amp-adapter-8x6zp8w4.js → amp-adapter-s7ytmv6b.js} +3 -3
  6. package/dist/{app-zfa9dwjw.js → app-5d3sz1hy.js} +7 -7
  7. package/dist/{approval-notifications-rv92zmza.js → approval-notifications-7qgkzkzx.js} +8 -8
  8. package/dist/{assistant-q7s7rm1q.js → assistant-p2yvhc3j.js} +37 -32
  9. package/dist/{boot-args-schema-g27kpzr1.js → boot-args-schema-ry6cb0p7.js} +1 -1
  10. package/dist/{boot-reembed-1mjs52nt.js → boot-reembed-2hkm3vz2.js} +1 -1
  11. package/dist/{boot-reembed-m62dpdkg.js → boot-reembed-c9643ms3.js} +1 -1
  12. package/dist/{boot-scrub-sweep-ss1vcamw.js → boot-scrub-sweep-3ycxr51t.js} +2 -2
  13. package/dist/{boot-seeds-hwnvgbb3.js → boot-seeds-2hzvvzg0.js} +4 -4
  14. package/dist/{boxd-y0szhp0g.js → boxd-9py3x0jb.js} +2 -2
  15. package/dist/{claude-adapter-0rjmbhjk.js → claude-adapter-dnkww93e.js} +9 -9
  16. package/dist/{claude-managed-adapter-6k032agg.js → claude-managed-adapter-yk0cr5x6.js} +4 -4
  17. package/dist/{claude-managed-setup-6czvve8q.js → claude-managed-setup-4byxpp47.js} +5 -5
  18. package/dist/{claude-sdk-session-pr0znb81.js → claude-sdk-session-4wf3dbvs.js} +12467 -12285
  19. package/dist/{cli-t0n9svkb.js → cli-096aftq6.js} +12 -7
  20. package/dist/{cli-2wzkvfgm.js → cli-0e914dp9.js} +3 -3
  21. package/dist/{cli-vcpyttcw.js → cli-0h6m6z5g.js} +1 -1
  22. package/dist/{cli-q41qar56.js → cli-0k7ppk9k.js} +130 -8
  23. package/dist/{cli-ks06cd0n.js → cli-1nfabrt4.js} +8 -8
  24. package/dist/{cli-ebpq3c5z.js → cli-2414h5r9.js} +8 -8
  25. package/dist/{cli-nrt048ys.js → cli-24wervhz.js} +37 -0
  26. package/dist/{cli-pedm2kht.js → cli-2ayk9gn8.js} +2 -2
  27. package/dist/{cli-kr0jpw9c.js → cli-2ckwgs7q.js} +1 -1
  28. package/dist/{cli-evy3egte.js → cli-2savn6mm.js} +11 -100
  29. package/dist/{cli-n79j1vxc.js → cli-2zjxake1.js} +4 -4
  30. package/dist/{cli-z3x7h79n.js → cli-37p61fcg.js} +9 -9
  31. package/dist/{cli-2vp0z049.js → cli-39t9d248.js} +1 -1
  32. package/dist/{cli-sa02jsqt.js → cli-3mhdmcd4.js} +1 -1
  33. package/dist/{cli-34fygf87.js → cli-3wsabyt0.js} +2 -2
  34. package/dist/{cli-grbngev5.js → cli-466jjrwe.js} +11 -2
  35. package/dist/{cli-zxa1vmx7.js → cli-6ajyhxh7.js} +2 -2
  36. package/dist/{cli-bvamr9g0.js → cli-6yy4fepf.js} +4 -4
  37. package/dist/{cli-3vw6dd4g.js → cli-73rmgm45.js} +2 -2
  38. package/dist/{cli-8b4rpnwj.js → cli-7ca8hczj.js} +1 -1
  39. package/dist/{cli-0h8skzss.js → cli-7g5qj2ca.js} +4 -3
  40. package/dist/{cli-srre41gb.js → cli-7w1fs01q.js} +2 -2
  41. package/dist/{cli-tgc1kgg3.js → cli-84wxwt3z.js} +1 -1
  42. package/dist/{cli-4gaf3tx5.js → cli-84xn7bgz.js} +1 -1
  43. package/dist/{cli-s8dhq7rj.js → cli-879txsac.js} +5 -5
  44. package/dist/{cli-9n6g14vs.js → cli-8vbxjzk0.js} +3 -3
  45. package/dist/{cli-cmbb2t8a.js → cli-91amj3md.js} +2 -2
  46. package/dist/{cli-ewk3sg68.js → cli-930zbczq.js} +3 -3
  47. package/dist/{cli-6msnpj1z.js → cli-9fwznq4p.js} +10 -10
  48. package/dist/{cli-qmx8bnt4.js → cli-9j1t3kf6.js} +2 -2
  49. package/dist/{cli-t879ww0y.js → cli-9j47sgzy.js} +2 -2
  50. package/dist/{cli-0qt3epg4.js → cli-ad00h1st.js} +7 -7
  51. package/dist/{cli-avax5mp9.js → cli-adzmmcvf.js} +19 -7
  52. package/dist/{cli-ffn0a515.js → cli-ayxxkk3p.js} +68 -25
  53. package/dist/{cli-4vynxtrb.js → cli-bqfx72e6.js} +10 -3
  54. package/dist/{cli-887vhew6.js → cli-cbg0j1yt.js} +2716 -2643
  55. package/dist/{cli-fw67mnyc.js → cli-cg1q8ymp.js} +1 -1
  56. package/dist/{cli-he5nxaa8.js → cli-dw9rtjm3.js} +1 -1
  57. package/dist/{cli-emdfd8fh.js → cli-dy754erz.js} +9 -1
  58. package/dist/{cli-3860pmrq.js → cli-edxfzgah.js} +4 -4
  59. package/dist/{cli-v09eza21.js → cli-ejnhs815.js} +15 -15
  60. package/dist/{cli-k0nebh10.js → cli-enavhq6r.js} +1 -1
  61. package/dist/{cli-b42yfn17.js → cli-f2rwt43y.js} +13 -13
  62. package/dist/{cli-tvyt8w6n.js → cli-f9g96z28.js} +8 -8
  63. package/dist/{cli-zbbtp02a.js → cli-fww016hh.js} +457 -70
  64. package/dist/{cli-vbge4rsp.js → cli-g6a696c0.js} +4 -4
  65. package/dist/{cli-z1vam71h.js → cli-gc6b94tj.js} +2 -2
  66. package/dist/{cli-5tq15aa7.js → cli-gcyws2bp.js} +2 -2
  67. package/dist/{cli-srktrbby.js → cli-hzhv7yac.js} +1 -1
  68. package/dist/{cli-cp163xga.js → cli-jcnc5ret.js} +44 -32
  69. package/dist/{cli-j69pzrrz.js → cli-jgq9xptq.js} +5 -5
  70. package/dist/{cli-kwj3131p.js → cli-jwnac23b.js} +1 -1
  71. package/dist/{cli-wzecestt.js → cli-kc7vd07m.js} +616 -289
  72. package/dist/{cli-8pd1t17c.js → cli-kg63yp1r.js} +14 -14
  73. package/dist/{cli-zzq96q57.js → cli-krk8y8c7.js} +727 -139
  74. package/dist/{cli-5web09sb.js → cli-m0ea8ggd.js} +8 -10
  75. package/dist/{cli-qrvk9nka.js → cli-md4tn21h.js} +13 -13
  76. package/dist/{cli-1jq2em7b.js → cli-mv8ft7b0.js} +10 -9
  77. package/dist/{cli-ryem5cfq.js → cli-mw1tmn3x.js} +217 -27
  78. package/dist/{cli-abby987g.js → cli-njvpngc6.js} +3 -3
  79. package/dist/{cli-55h8m1x3.js → cli-phe2vcw5.js} +6 -6
  80. package/dist/{cli-prz1p3ft.js → cli-pq0kv31y.js} +5 -5
  81. package/dist/{cli-q1h041y8.js → cli-q457ga28.js} +6 -6
  82. package/dist/{cli-z40t85ms.js → cli-q5n3deaf.js} +1 -1
  83. package/dist/{cli-7ypg8hka.js → cli-qkbevqer.js} +3 -3
  84. package/dist/{cli-f9xw9pr4.js → cli-qrwjk4xy.js} +5 -5
  85. package/dist/{cli-kezzteka.js → cli-r04ve9xw.js} +1 -1
  86. package/dist/{cli-zntvmqmm.js → cli-r495stwd.js} +2 -2
  87. package/dist/{cli-1kvcsd2f.js → cli-r9d2tya0.js} +71 -3
  88. package/dist/{cli-ybte1fqc.js → cli-rp1n2xpd.js} +1 -1
  89. package/dist/{cli-sejvnjvw.js → cli-rs1rzwp4.js} +1 -1
  90. package/dist/{cli-94mxerrp.js → cli-rzbsh6bw.js} +1 -1
  91. package/dist/{cli-94gx6ze9.js → cli-s4pccby1.js} +1 -1
  92. package/dist/{cli-hd5bm1e1.js → cli-shyhb4t5.js} +10 -10
  93. package/dist/{cli-r3dxpmyt.js → cli-srq69pn1.js} +1 -1
  94. package/dist/{cli-7r9tvk8v.js → cli-tc165vrb.js} +8 -3
  95. package/dist/{cli-ced4azn1.js → cli-v4z5v3jd.js} +298 -80
  96. package/dist/{cli-ehg90jd1.js → cli-vxmmttmt.js} +55 -50
  97. package/dist/{cli-tt7dkwjj.js → cli-w4bvtxet.js} +7 -7
  98. package/dist/{cli-x2adbg4j.js → cli-wd7b5hgc.js} +1 -1
  99. package/dist/{cli-htb5bpz2.js → cli-wvbaq052.js} +1 -1
  100. package/dist/{cli-ywy8yz6t.js → cli-wvgg7r4j.js} +2 -2
  101. package/dist/{cli-19d6v8er.js → cli-wym6rxgt.js} +165 -6
  102. package/dist/{cli-f7b9nyvk.js → cli-yd7e590v.js} +12 -12
  103. package/dist/{cli-69zzpjgh.js → cli-yjb3cddd.js} +1 -1
  104. package/dist/{cli-5n9w2xzx.js → cli-z8t4485r.js} +2 -2
  105. package/dist/{cli-jdq3jmny.js → cli-ze1ndjs4.js} +4 -6
  106. package/dist/cli.js +28 -28
  107. package/dist/{codex-adapter-bn7eaxk5.js → codex-adapter-eq61radw.js} +8 -8
  108. package/dist/{codex-hook-nnmezjg9.js → codex-hook-8nmepvz6.js} +3 -3
  109. package/dist/{codex-login-ktfg1cxk.js → codex-login-vbd9707w.js} +1 -1
  110. package/dist/{codex-session-runner-j1e9hffc.js → codex-session-runner-rfx355h4.js} +9 -9
  111. package/dist/{commands-amhpafrr.js → commands-d1z0sx62.js} +3 -3
  112. package/dist/{controller-tw7g10j2.js → controller-9hz6d8x3.js} +4 -4
  113. package/dist/{controllers-connect-2ssqz7f4.js → controllers-connect-tz07d2xr.js} +24 -25
  114. package/dist/core-dynsv289.js +41 -0
  115. package/dist/{cursor-adapter-d6knjmwa.js → cursor-adapter-ef22ze3j.js} +2 -2
  116. package/dist/{db-fd6xxm77.js → db-gd81d68c.js} +3 -3
  117. package/dist/{db-sc59379z.js → db-vrckks6q.js} +4 -2
  118. package/dist/{devin-adapter-3bp6rape.js → devin-adapter-kdt6a2bh.js} +1 -1
  119. package/dist/{dispatcher-a2gdqz8c.js → dispatcher-76as8w2t.js} +21 -22
  120. package/dist/{docker-a59g3ebm.js → docker-51ta7jsh.js} +2 -2
  121. package/dist/dsh-adapter-ypfvcdyz.js +11 -0
  122. package/dist/{e2b-cn7cvjqy.js → e2b-05kn3kpq.js} +16 -5
  123. package/dist/{e2b-qnxyfea6.js → e2b-dm9r8hpy.js} +3 -3
  124. package/dist/{easter-egg-3d-a0pphy71.js → easter-egg-3d-sg21j15g.js} +1 -1
  125. package/dist/{embedding-space-qepzrach.js → embedding-space-zsdw37bb.js} +13 -23
  126. package/dist/{embeddings-d7vr881x.js → embeddings-p4e3e1m6.js} +1 -1
  127. package/dist/{event-bus-7gbsr0g4.js → event-bus-tvf2grf4.js} +1 -1
  128. package/dist/{execute-6afts2bn.js → execute-nztd0af0.js} +1 -1
  129. package/dist/{external-channel-881zq1x4.js → external-channel-717yzn4d.js} +2 -2
  130. package/dist/fx-adapter-9k0hptnz.js +20 -0
  131. package/dist/grok-adapter-skdj2pce.js +20 -0
  132. package/dist/handlers-5btjqkz6.js +39 -0
  133. package/dist/{heartbeat-4c022m6a.js → heartbeat-vfb1gy84.js} +24 -25
  134. package/dist/{hook-a7eh6zty.js → hook-ctz0xmp3.js} +11 -11
  135. package/dist/{hook-4k84x499.js → hook-eh52p7yd.js} +6 -6
  136. package/dist/{http-6aw5wanc.js → http-zregegrx.js} +784 -166
  137. package/dist/{index-xhad0n8m.js → index-5kx15d19.js} +1 -1
  138. package/dist/index-7w8p6em0.js +41 -0
  139. package/dist/index-evay0xyk.js +17 -0
  140. package/dist/{index-yq9hhhhy.js → index-fdym6ryb.js} +25 -26
  141. package/dist/{index-3j803vnb.js → index-mtnbhe12.js} +20533 -19786
  142. package/dist/index-vz4semsx.js +38 -0
  143. package/dist/{index-z2g9469g.js → index-x9qf8dg7.js} +108 -28
  144. package/dist/index-y3s0xp2v.js +43 -0
  145. package/dist/{k8s-36gfn847.js → k8s-ejkk0aw7.js} +2 -2
  146. package/dist/{keepalive-zhbmztqw.js → keepalive-zdqay870.js} +4 -5
  147. package/dist/lead-6cscw8a5.js +82 -0
  148. package/dist/{maintenance-rsp0591h.js → maintenance-t5ndg11m.js} +1 -1
  149. package/dist/{node-rxte5hc6.js → node-jkdd5w7m.js} +1 -1
  150. package/dist/{oauth-refresh-sweep-w3cqmxq7.js → oauth-refresh-sweep-y9zyd7t6.js} +3 -4
  151. package/dist/{object-webhooks-331hay92.js → object-webhooks-mkca91s0.js} +7 -7
  152. package/dist/{onboard-n2w80m2n.js → onboard-ss995244.js} +11 -9
  153. package/dist/{opencode-adapter-z98127cz.js → opencode-adapter-mwpz0278.js} +8 -8
  154. package/dist/{otel-impl-xsk35tvf.js → otel-impl-6n6vva3x.js} +2 -2
  155. package/dist/{pending-2e6trkxd.js → pending-2sxh1t6j.js} +22 -23
  156. package/dist/{pi-mono-adapter-wh6yndtm.js → pi-mono-adapter-sfb7zy43.js} +13 -13
  157. package/dist/{pricing-refresh-9355dj1t.js → pricing-refresh-h79bg4cf.js} +2 -2
  158. package/dist/{rbac-roles-8eajw4s6.js → rbac-roles-ckq0czp4.js} +2 -2
  159. package/dist/{rbac-roles-58y3m912.js → rbac-roles-jg2e260w.js} +3 -3
  160. package/dist/{render-v2-7gskkmd4.js → render-v2-ymbshmn0.js} +7 -7
  161. package/dist/{resume-0drnmpja.js → resume-jdhnt4jk.js} +10 -10
  162. package/dist/{runtime-d2tcmqte.js → runtime-y28jhhnf.js} +1 -1
  163. package/dist/{session-access-0ztys6bd.js → session-access-k4ta5hvp.js} +5 -5
  164. package/dist/{session-source-backfill-cdm5s046.js → session-source-backfill-528j4s8j.js} +3 -3
  165. package/dist/{setup-pqwb9tcc.js → setup-d6pj82fr.js} +15 -6
  166. package/dist/thread-buffer-9w6x5zec.js +40 -0
  167. package/dist/{tree-visibility-rwz67mje.js → tree-visibility-kjxv3nxk.js} +2 -2
  168. package/dist/{user-merge-jobs-mxrhamwt.js → user-merge-jobs-rabbncf6.js} +3 -3
  169. package/dist/{virtual-modules-71y1gsmg.js → virtual-modules-22k51txd.js} +3 -3
  170. package/dist/{work-objects-3k4ykt9j.js → work-objects-xtjbar3r.js} +26 -30
  171. package/dist/{worker-follow-up-y0h64xpr.js → worker-follow-up-fg48vk6d.js} +21 -22
  172. package/dist/worker-g4aj93dt.js +82 -0
  173. package/dist/{x-d27jj7z7.js → x-vfsqypht.js} +2 -2
  174. package/openapi.json +247 -20
  175. package/package.json +10 -10
  176. package/src/apps/definition.ts +76 -24
  177. package/src/apps/row-store.ts +67 -0
  178. package/src/apps/script-types.ts +131 -21
  179. package/src/apps/store.ts +4 -1
  180. package/src/be/db/script-runs.ts +33 -0
  181. package/src/be/db/slack-card-groups.ts +147 -0
  182. package/src/be/db/slack-trees.ts +26 -0
  183. package/src/be/db/task-idempotency.ts +63 -0
  184. package/src/be/db/tasks/read.ts +2 -0
  185. package/src/be/db/tasks/write.ts +4 -2
  186. package/src/be/db/workflow-idempotency.ts +6 -1
  187. package/src/be/db/workflows/read.ts +79 -0
  188. package/src/be/db.ts +51 -147
  189. package/src/be/improvements.ts +24 -2
  190. package/src/be/mcp-proxy.ts +45 -11
  191. package/src/be/memory/embedding-space.ts +10 -20
  192. package/src/be/memory/index.ts +35 -0
  193. package/src/be/memory/providers/openai-embedding.ts +10 -0
  194. package/src/be/migrations/348_task_deferred_until.sql +4 -0
  195. package/src/be/migrations/354_durable_objects.sql +9 -0
  196. package/src/be/migrations/356_slack_outcome_card_groups.sql +14 -0
  197. package/src/be/migrations/357_task_idempotency_keys.sql +27 -0
  198. package/src/be/migrations/362_favorites_app.sql +36 -0
  199. package/src/be/repo-checked-update.ts +58 -5
  200. package/src/be/requester-timezone.ts +10 -0
  201. package/src/be/script-connections.ts +5 -1
  202. package/src/be/script-credential-broker.ts +29 -2
  203. package/src/be/scripts/durable.ts +204 -0
  204. package/src/be/scripts/extract-schema.ts +29 -4
  205. package/src/be/scripts/run-credential.ts +1 -8
  206. package/src/be/scripts/typecheck.ts +32 -7
  207. package/src/be/seed-scripts/catalog/memory-eval.ts +11 -2
  208. package/src/be/seed-scripts/catalog/tool-usage.ts +27 -8
  209. package/src/be/swarm-config-guard.ts +87 -7
  210. package/src/be/users.ts +33 -12
  211. package/src/comb/review-batch.ts +16 -5
  212. package/src/commands/context-preamble.ts +237 -0
  213. package/src/commands/e2b.ts +14 -0
  214. package/src/commands/entrypoint-mcp-config.ts +231 -0
  215. package/src/commands/onboard/agent-fs-version.ts +1 -1
  216. package/src/commands/onboard/compose-generator.ts +2 -1
  217. package/src/commands/onboard/env-generator.ts +16 -7
  218. package/src/commands/runner.ts +23 -7
  219. package/src/commands/setup.tsx +17 -3
  220. package/src/extensions/contract-types.generated.ts +1 -1
  221. package/src/hooks/hook.ts +8 -2
  222. package/src/hooks/native-tool-hooks.ts +4 -2
  223. package/src/http/apps.ts +82 -42
  224. package/src/http/comb.ts +21 -5
  225. package/src/http/config.ts +8 -4
  226. package/src/http/heartbeat.ts +5 -0
  227. package/src/http/index.ts +12 -6
  228. package/src/http/kv.ts +7 -5
  229. package/src/http/mcp-oauth.ts +16 -0
  230. package/src/http/mcp-servers.ts +43 -3
  231. package/src/http/memory.ts +28 -1
  232. package/src/http/metrics.ts +11 -4
  233. package/src/http/onboarding.ts +12 -1
  234. package/src/http/repos.ts +27 -11
  235. package/src/http/request-principal.ts +27 -1
  236. package/src/http/schedules.ts +36 -8
  237. package/src/http/script-connection-proxy.ts +3 -1
  238. package/src/http/script-runs.ts +21 -10
  239. package/src/http/scripts.ts +177 -26
  240. package/src/http/session-cost-recompute.ts +9 -4
  241. package/src/http/skills.ts +70 -0
  242. package/src/http/status.ts +2 -0
  243. package/src/http/tasks.ts +92 -14
  244. package/src/http/trackers/jira.ts +18 -3
  245. package/src/http/trackers/linear.ts +3 -0
  246. package/src/kv-limits.ts +2 -0
  247. package/src/kv-reserved-namespaces.ts +25 -2
  248. package/src/prompts/session-templates.ts +49 -0
  249. package/src/prompts/session-turns.ts +30 -0
  250. package/src/providers/amp-adapter.ts +1 -1
  251. package/src/providers/claude-managed-adapter.ts +14 -0
  252. package/src/providers/claude-sdk-session.ts +14 -1
  253. package/src/providers/cursor-adapter.ts +1 -1
  254. package/src/providers/dsh-adapter.ts +1 -1
  255. package/src/providers/opencode-adapter.ts +3 -5
  256. package/src/providers/runtime-dependencies.ts +11 -8
  257. package/src/rbac/legacy-policy.ts +7 -0
  258. package/src/rbac/permissions.ts +27 -0
  259. package/src/scheduler/scheduler.ts +36 -18
  260. package/src/script-workflows/executor.ts +37 -8
  261. package/src/script-workflows/supervisor.ts +14 -0
  262. package/src/scripts-runtime/ctx.ts +5 -1
  263. package/src/scripts-runtime/durable-object-base.ts +19 -0
  264. package/src/scripts-runtime/eval-harness.ts +46 -1
  265. package/src/scripts-runtime/executors/native.ts +13 -1
  266. package/src/scripts-runtime/executors/quickjs-bundle.ts +20 -1
  267. package/src/scripts-runtime/executors/quickjs-prelude.ts +40 -1
  268. package/src/scripts-runtime/executors/quickjs-runner.ts +26 -3
  269. package/src/scripts-runtime/executors/quickjs-worker.ts +2 -1
  270. package/src/scripts-runtime/executors/types.ts +26 -0
  271. package/src/scripts-runtime/extract-signature.ts +96 -1
  272. package/src/scripts-runtime/loader.ts +11 -5
  273. package/src/scripts-runtime/mcp-client.ts +1 -1
  274. package/src/scripts-runtime/sdk-allowlist.ts +1 -0
  275. package/src/scripts-runtime/swarm-config.ts +7 -0
  276. package/src/scripts-runtime/swarm-sdk.ts +4 -1
  277. package/src/scripts-runtime/types/stdlib.d.ts +19 -0
  278. package/src/scripts-runtime/types/swarm-extension.d.ts +1 -0
  279. package/src/scripts-runtime/types/swarm-sdk.d.ts +19 -0
  280. package/src/slack/actions.ts +24 -0
  281. package/src/slack/assistant.ts +8 -0
  282. package/src/slack/blocks.ts +35 -0
  283. package/src/slack/channel-activity.ts +7 -0
  284. package/src/slack/enrich.ts +46 -54
  285. package/src/slack/files.ts +173 -23
  286. package/src/slack/handlers.test.ts +17 -19
  287. package/src/slack/handlers.ts +15 -14
  288. package/src/slack/render-v2.ts +264 -19
  289. package/src/slack/responses.ts +61 -5
  290. package/src/slack/session-mirror.ts +10 -5
  291. package/src/slack/task-output.ts +25 -14
  292. package/src/slack/templates.ts +9 -0
  293. package/src/slack/thread-participants.ts +64 -24
  294. package/src/slack/watcher.ts +4 -4
  295. package/src/slack/work-objects.ts +1 -1
  296. package/src/stdio.ts +5 -0
  297. package/src/tests/agents-list-model-display.test.ts +4 -0
  298. package/src/tests/apps-script-types.test.ts +63 -16
  299. package/src/tests/apps-sort-order.test.ts +87 -0
  300. package/src/tests/bedrock-model-groups.test.ts +4 -0
  301. package/src/tests/channel-activity.test.ts +9 -0
  302. package/src/tests/chatgpt-subscription-model-groups.test.ts +4 -0
  303. package/src/tests/claude-hook-output.test.ts +2 -0
  304. package/src/tests/claude-managed-adapter.test.ts +15 -3
  305. package/src/tests/claude-sdk-stderr.test.ts +28 -0
  306. package/src/tests/codex-gpt6-release.test.ts +4 -0
  307. package/src/tests/comb-review-batch.test.ts +17 -4
  308. package/src/tests/comb-status.test.ts +1 -0
  309. package/src/tests/db-client.test.ts +11 -5
  310. package/src/tests/db-task-read-contract.test.ts +1 -0
  311. package/src/tests/db-task-write-contract.test.ts +2 -2
  312. package/src/tests/defer-task.test.ts +23 -1
  313. package/src/tests/dsh-adapter.test.ts +1 -1
  314. package/src/tests/e2b-dispatch.test.ts +13 -1
  315. package/src/tests/entrypoint-mcp-config.test.ts +642 -0
  316. package/src/tests/fixtures/onboard/content.env.txt +2 -2
  317. package/src/tests/fixtures/onboard/dev.env.txt +2 -2
  318. package/src/tests/fixtures/onboard/full-all.env.txt +2 -2
  319. package/src/tests/fixtures/onboard/full.env.txt +2 -2
  320. package/src/tests/fixtures/onboard/research.env.txt +2 -2
  321. package/src/tests/fixtures/onboard/solo.env.txt +2 -2
  322. package/src/tests/fixtures/runner-missing-dependency.ts +2 -1
  323. package/src/tests/fx-adapter.test.ts +4 -5
  324. package/src/tests/hook-mcp-config-precedence.test.ts +59 -0
  325. package/src/tests/hook-ping-me-order.test.ts +1 -0
  326. package/src/tests/hook-runtime-close.test.ts +1 -0
  327. package/src/tests/improvements-payload.test.ts +2 -2
  328. package/src/tests/model-groups-live-catalog.test.ts +4 -0
  329. package/src/tests/oauth-credential-bindings.test.ts +8 -3
  330. package/src/tests/oauth-refresh-failure.test.ts +15 -3
  331. package/src/tests/onboard-env.test.ts +1 -1
  332. package/src/tests/openai-compatible-providers.test.ts +5 -0
  333. package/src/tests/openapi-route-headers.test.ts +2 -1
  334. package/src/tests/opus-5-5-registry.test.ts +4 -0
  335. package/src/tests/provider-runtime-dependencies.test.ts +26 -15
  336. package/src/tests/routing-affinity-inventory.test.ts +11 -0
  337. package/src/tests/runner-context-preamble.test.ts +202 -0
  338. package/src/tests/runner-repo-clone-args.test.ts +116 -0
  339. package/src/tests/scheduler-occurrence.test.ts +60 -9
  340. package/src/tests/script-connections-mcp.test.ts +6 -3
  341. package/src/tests/script-connections.test.ts +4 -0
  342. package/src/tests/scripts-namespaces.test.ts +3 -1
  343. package/src/tests/secret-scrubber.test.ts +8 -2
  344. package/src/tests/session-cost-recompute-unit.test.ts +39 -0
  345. package/src/tests/session-costs-recompute-all-providers.test.ts +6 -3
  346. package/src/tests/session-route-posture.test.ts +7 -1
  347. package/src/tests/slack-file-tools-attachments.test.ts +14 -9
  348. package/src/tests/slack-identity-resolution.test.ts +10 -3
  349. package/src/tests/slack-inline-output.test.ts +10 -8
  350. package/src/tests/slack-render-v2.test.ts +9 -4
  351. package/src/tests/slack-steering.test.ts +8 -2
  352. package/src/tests/slack-thread-participants.test.ts +11 -1
  353. package/src/tests/sonnet-5-5-registry.test.ts +4 -0
  354. package/src/tests/swarm-config-encryption.test.ts +5 -8
  355. package/src/tests/ui-spec-script-actions-config.test.ts +7 -3
  356. package/src/tests/workflow-triggers-v2.test.ts +35 -11
  357. package/src/tools/app-patch.ts +6 -2
  358. package/src/tools/app-upsert.ts +8 -4
  359. package/src/tools/defer-task.ts +17 -77
  360. package/src/tools/kv/kv-get.ts +2 -0
  361. package/src/tools/kv/kv-list.ts +11 -5
  362. package/src/tools/kv/kv-set.ts +1 -3
  363. package/src/tools/repos/update-repo.ts +37 -19
  364. package/src/tools/schedules/run-schedule-now.ts +21 -1
  365. package/src/tools/script-apis.ts +9 -4
  366. package/src/tools/script-common.ts +2 -2
  367. package/src/tools/script-run.ts +8 -0
  368. package/src/tools/script-upsert.ts +1 -1
  369. package/src/tools/slack-download-file.ts +15 -12
  370. package/src/tools/slack-post.ts +7 -1
  371. package/src/tools/slack-read.ts +3 -1
  372. package/src/tools/slack-reply.ts +16 -0
  373. package/src/tools/slack-start-thread.ts +8 -1
  374. package/src/tools/slack-upload-file.ts +99 -96
  375. package/src/tools/swarm-config/set-config.ts +3 -1
  376. package/src/tools/swarm-x.ts +0 -2
  377. package/src/tools/utils.ts +3 -0
  378. package/src/types.ts +8 -2
  379. package/src/utils/constants.ts +20 -0
  380. package/src/utils/deferral-time.ts +61 -0
  381. package/src/utils/request-auth-context.ts +15 -16
  382. package/src/utils/secret-scrubber.ts +1 -1
  383. package/src/workflows/engine.ts +6 -11
  384. package/src/workflows/executors/swarm-script.ts +0 -2
  385. package/src/workflows/foreach-driver.ts +6 -12
  386. package/src/workflows/input.ts +24 -1
  387. package/src/workflows/node-timeout.ts +18 -0
  388. package/src/workflows/retry-poller.ts +2 -1
  389. package/src/workflows/triggers.ts +21 -11
  390. package/src/x/composio.ts +10 -1
  391. package/templates/skills/apps/SKILL.md +4 -2
  392. package/templates/skills/apps/content.md +4 -2
  393. package/templates/skills/code-quality/content.md +4 -4
  394. package/templates/skills/scheduled-task-resilience/SKILL.md +2 -0
  395. package/templates/skills/scheduled-task-resilience/content.md +2 -0
  396. package/templates/skills/swarm-docs/content.md +7 -0
  397. package/templates/skills/swarm-scripts/SKILL.md +44 -0
  398. package/templates/skills/swarm-scripts/content.md +44 -0
  399. package/dist/acp-adapter-tbt61zkm.js +0 -17
  400. package/dist/cli-b9ygp1kz.js +0 -459
  401. package/dist/cli-kj0hyr43.js +0 -51
  402. package/dist/cli-m8f4379k.js +0 -173
  403. package/dist/core-bwp98v4w.js +0 -42
  404. package/dist/dsh-adapter-43ygwqn7.js +0 -9
  405. package/dist/fx-adapter-cr2hq17y.js +0 -20
  406. package/dist/grok-adapter-ayddnbsc.js +0 -20
  407. package/dist/handlers-7ghs84x2.js +0 -41
  408. package/dist/index-dtt0d634.js +0 -44
  409. package/dist/index-hmszyqkk.js +0 -42
  410. package/dist/index-j6rm1rtn.js +0 -39
  411. package/dist/index-rwwhsmjg.js +0 -13
  412. package/dist/lead-g2j4q39z.js +0 -83
  413. package/dist/thread-buffer-epx3san4.js +0 -42
  414. package/dist/worker-09gqn9xy.js +0 -83
@@ -2,6 +2,8 @@ import {
2
2
  CredentialBindingSchema,
3
3
  placeholderForConfigKey,
4
4
  assertUrlSafe,
5
+ createSsrfGuardedFetch,
6
+ init_egress_guard,
5
7
  init_credential_broker,
6
8
  withLoopPath,
7
9
  bindLoopPath,
@@ -73,6 +75,8 @@ import {
73
75
  init_script_allowlist,
74
76
  API_DRAIN_MAX_MS_LIMIT,
75
77
  init_api_drain2,
78
+ formatDeferralDateTime,
79
+ init_deferral_time,
76
80
  parseEnabledTools,
77
81
  init_enabled_tools,
78
82
  parseFollowUpGateScheduleIds,
@@ -121,6 +125,8 @@ import {
121
125
  getRunningSubWorkflowSteps,
122
126
  getSettledChildRunParentSteps,
123
127
  init_workflow_runs,
128
+ publicEndpointSsrfOptions,
129
+ init_mcp_wrapper,
124
130
  LEARNING_TTL_DAYS,
125
131
  LEARNING_DUPLICATE_MIN_SIMILARITY,
126
132
  CANDIDATE_SET_MULTIPLIER,
@@ -180,6 +186,7 @@ import {
180
186
  init_model_catalog_store,
181
187
  explicitModelErrorForAgent,
182
188
  init_model_validation2,
189
+ vcsRepoId,
183
190
  configPools,
184
191
  checkProfileForAgent,
185
192
  init_model_profile_check,
@@ -249,6 +256,7 @@ import {
249
256
  recordAcceptedWorkflowOperation,
250
257
  init_workflow_idempotency,
251
258
  getRunWorkflow2,
259
+ getWorkflowsByEventName2,
252
260
  recordSlackMessage2,
253
261
  getSlackTreeMessageByThread2,
254
262
  markTaskSlackReplySent2,
@@ -386,6 +394,7 @@ import {
386
394
  createUser2,
387
395
  updateUser2,
388
396
  deleteUser2,
397
+ withFavoriteFlags2,
389
398
  getRootTaskChain2,
390
399
  getBudget2,
391
400
  getActivePricingRow2,
@@ -407,27 +416,27 @@ import {
407
416
  recordInlineScriptRun2,
408
417
  exports_db,
409
418
  init_db4
410
- } from "./cli-zzq96q57.js";
419
+ } from "./cli-krk8y8c7.js";
411
420
  import {
412
421
  assertMayActOnOperatorGrantedTarget2,
413
422
  getUserGrant2,
414
423
  init_rbac_roles
415
- } from "./cli-34fygf87.js";
424
+ } from "./cli-3wsabyt0.js";
416
425
  import {
417
426
  ensurePricingSeeded2,
418
427
  ensureRbacSeeded2,
419
428
  ensureModelProfilesSeeded2,
420
429
  init_boot_seeds
421
- } from "./cli-7ypg8hka.js";
430
+ } from "./cli-qkbevqer.js";
422
431
  import {
423
432
  requestModelCatalogRefresh2,
424
433
  startPricingRefreshLoop2,
425
434
  init_pricing_refresh
426
- } from "./cli-pedm2kht.js";
435
+ } from "./cli-2ayk9gn8.js";
427
436
  import {
428
437
  workflowEventBus2,
429
438
  init_event_bus
430
- } from "./cli-ybte1fqc.js";
439
+ } from "./cli-rp1n2xpd.js";
431
440
  import {
432
441
  slackCode,
433
442
  slackMissingScopeMessage,
@@ -436,7 +445,7 @@ import {
436
445
  externalChannelToolError2,
437
446
  getChannelBlockReason2,
438
447
  init_external_channel
439
- } from "./cli-5n9w2xzx.js";
448
+ } from "./cli-z8t4485r.js";
440
449
  import {
441
450
  tableToAscii2,
442
451
  init_dist8
@@ -450,11 +459,20 @@ import {
450
459
  init_reaction_events,
451
460
  withSpan2,
452
461
  init_otel,
462
+ resolveRequesterTimezone,
463
+ init_requester_timezone,
453
464
  finalizeTerminalSlackReactions,
454
465
  init_ack,
466
+ UI_SPEC_MAX_ACTIONS,
467
+ TASK_UI_SPEC_UPDATED_EVENT,
468
+ UI_SPEC_ACTION_ID,
469
+ UI_SPEC_CARD_LIMITS,
470
+ UI_SPEC_SCRIPT_ARGS_MAX_BYTES,
471
+ init_task_ui_spec,
455
472
  getTaskLink,
456
473
  getTaskUrl,
457
474
  markdownToSlack,
475
+ findReservedActionId,
458
476
  buildMrkdwnSectionBlocks,
459
477
  buildCaptionBlock,
460
478
  init_blocks,
@@ -475,17 +493,11 @@ import {
475
493
  acquireTaskUiScriptActionRun,
476
494
  finishTaskUiScriptActionRun,
477
495
  hasTaskUiSpecCheckRefusal,
478
- init_task_ui_spec,
496
+ init_task_ui_spec2,
479
497
  standardComponentDefinitions,
480
498
  CardSpecError,
481
499
  toCard,
482
500
  init_dist5,
483
- UI_SPEC_MAX_ACTIONS,
484
- TASK_UI_SPEC_UPDATED_EVENT,
485
- UI_SPEC_ACTION_ID,
486
- UI_SPEC_CARD_LIMITS,
487
- UI_SPEC_SCRIPT_ARGS_MAX_BYTES,
488
- init_task_ui_spec2,
489
501
  validateTaskUiSpec,
490
502
  init_validate2,
491
503
  ensure,
@@ -499,7 +511,7 @@ import {
499
511
  startSlackApp2,
500
512
  stopSlackAppUnderLifecycleLock2,
501
513
  init_app4
502
- } from "./cli-zbbtp02a.js";
514
+ } from "./cli-fww016hh.js";
503
515
  import {
504
516
  AGENT_MAX_TASKS_CONFIG_KEY,
505
517
  resetAgentMaxTasksMirror,
@@ -520,7 +532,7 @@ import {
520
532
  postApprovalCancellationUpdates2,
521
533
  createApprovalFollowUpTask2,
522
534
  init_approval_notifications
523
- } from "./cli-evy3egte.js";
535
+ } from "./cli-2savn6mm.js";
524
536
  import {
525
537
  shapeApprovalResolution,
526
538
  init_approval_resolution,
@@ -544,7 +556,7 @@ import {
544
556
  resumeFromChildRun2,
545
557
  initWaitBusSubscriptions2,
546
558
  init_resume
547
- } from "./cli-55h8m1x3.js";
559
+ } from "./cli-phe2vcw5.js";
548
560
  import {
549
561
  getFileStorageProvider2,
550
562
  init_registry2
@@ -552,7 +564,7 @@ import {
552
564
  import {
553
565
  getRuntimePool2,
554
566
  init_db2
555
- } from "./cli-f9xw9pr4.js";
567
+ } from "./cli-qrwjk4xy.js";
556
568
  import {
557
569
  duplicateGuardedQueryKey,
558
570
  parseQueryParams,
@@ -585,13 +597,13 @@ import {
585
597
  findRoute,
586
598
  route,
587
599
  init_route_def
588
- } from "./cli-tt7dkwjj.js";
600
+ } from "./cli-w4bvtxet.js";
589
601
  import {
590
602
  COMPOSIO_HTTP_METHODS,
591
603
  executeComposioRequest,
592
604
  composioArgsFromParts,
593
605
  init_composio
594
- } from "./cli-4vynxtrb.js";
606
+ } from "./cli-bqfx72e6.js";
595
607
  import {
596
608
  object,
597
609
  init_v4_mini
@@ -650,6 +662,8 @@ import {
650
662
  init_run_credential,
651
663
  seededWorkflowState,
652
664
  init_workflows_seeder,
665
+ DURABLE_OBJECT_BASE_JS,
666
+ init_durable_object_base,
653
667
  extractScriptSignature,
654
668
  init_extract_signature,
655
669
  extractArgsJsonSchema,
@@ -683,11 +697,13 @@ import {
683
697
  updateApp,
684
698
  deleteApp,
685
699
  init_store2,
700
+ appWriteTypesWarnings,
701
+ init_script_types,
686
702
  typecheckScript,
687
703
  init_typecheck,
688
704
  parseSkillContent,
689
705
  init_skill_parser
690
- } from "./cli-ced4azn1.js";
706
+ } from "./cli-v4z5v3jd.js";
691
707
  import {
692
708
  detachedProcessGroup,
693
709
  registerProcessGroup,
@@ -702,7 +718,7 @@ import {
702
718
  ensureToken,
703
719
  ensureTokenOrThrow,
704
720
  init_ensure_token
705
- } from "./cli-5web09sb.js";
721
+ } from "./cli-m0ea8ggd.js";
706
722
  import {
707
723
  A1Error,
708
724
  colName,
@@ -737,11 +753,11 @@ import {
737
753
  listObjects,
738
754
  reindexObjects,
739
755
  init_objects
740
- } from "./cli-j69pzrrz.js";
756
+ } from "./cli-jgq9xptq.js";
741
757
  import {
742
758
  agentFsClientFor,
743
759
  init_agent_fs_identity
744
- } from "./cli-zxa1vmx7.js";
760
+ } from "./cli-6ajyhxh7.js";
745
761
  import {
746
762
  FilesError,
747
763
  providerPath,
@@ -755,7 +771,7 @@ import {
755
771
  isSlackLeaveThreadDisabled,
756
772
  leaveSlackThread,
757
773
  init_left_threads
758
- } from "./cli-r3dxpmyt.js";
774
+ } from "./cli-srq69pn1.js";
759
775
  import {
760
776
  require_fast_deep_equal
761
777
  } from "./cli-bhp11egn.js";
@@ -802,6 +818,8 @@ import {
802
818
  validateJsonSchema,
803
819
  findJsonSchemaShapeErrors,
804
820
  init_json_schema_validator,
821
+ runWithNodeDeadline,
822
+ init_node_timeout,
805
823
  workflowSaveWarnings,
806
824
  withSaveWarnings,
807
825
  init_readiness,
@@ -840,7 +858,7 @@ import {
840
858
  validateDefinition,
841
859
  applyDefinitionPatch,
842
860
  init_definition2
843
- } from "./cli-cp163xga.js";
861
+ } from "./cli-jcnc5ret.js";
844
862
  import {
845
863
  isMultiRuntimeEnabled,
846
864
  init_multi_runtime2
@@ -863,16 +881,12 @@ import {
863
881
  import {
864
882
  canProvisionKind,
865
883
  init_runtime_providers
866
- } from "./cli-n79j1vxc.js";
884
+ } from "./cli-2zjxake1.js";
867
885
  import {
868
886
  getSessionRoot,
869
887
  sessionAccessForRoot,
870
888
  init_session_shares
871
- } from "./cli-kwj3131p.js";
872
- import {
873
- publicEndpointSsrfOptions,
874
- init_mcp_wrapper
875
- } from "./cli-b9ygp1kz.js";
889
+ } from "./cli-jwnac23b.js";
876
890
  import {
877
891
  findUserById,
878
892
  findUserByExternalId,
@@ -887,13 +901,13 @@ import {
887
901
  resolveSessionToken,
888
902
  fingerprintApiKey,
889
903
  init_users
890
- } from "./cli-avax5mp9.js";
904
+ } from "./cli-adzmmcvf.js";
891
905
  import {
892
906
  AMP_ESTIMATE_MODELS,
893
907
  ampBillsCacheWrites,
894
908
  resolveAmpModel,
895
909
  init_amp_models
896
- } from "./cli-htb5bpz2.js";
910
+ } from "./cli-wvbaq052.js";
897
911
  import {
898
912
  resolveGitHubHost,
899
913
  getGitHubLinkConfig,
@@ -911,7 +925,7 @@ import {
911
925
  init_task_attachment_links,
912
926
  contentSha256,
913
927
  init_profile_sync
914
- } from "./cli-19d6v8er.js";
928
+ } from "./cli-wym6rxgt.js";
915
929
  import {
916
930
  getSlackConfiguration,
917
931
  isSlackConfigured,
@@ -929,7 +943,7 @@ import {
929
943
  splitCredentialPool,
930
944
  selectCredential,
931
945
  init_credentials2
932
- } from "./cli-x2adbg4j.js";
946
+ } from "./cli-wd7b5hgc.js";
933
947
  import {
934
948
  findInterpolationTokens,
935
949
  interpolate,
@@ -939,7 +953,7 @@ import {
939
953
  init_registry3,
940
954
  resolveTemplate,
941
955
  init_resolver
942
- } from "./cli-nrt048ys.js";
956
+ } from "./cli-24wervhz.js";
943
957
  import {
944
958
  normalizeAssetKey,
945
959
  defaultAssetKey,
@@ -1018,7 +1032,7 @@ import {
1018
1032
  KvNamespaceSchema,
1019
1033
  KvKeySchema,
1020
1034
  init_types5
1021
- } from "./cli-7r9tvk8v.js";
1035
+ } from "./cli-tc165vrb.js";
1022
1036
  import {
1023
1037
  init_zod
1024
1038
  } from "./cli-96234j5w.js";
@@ -1055,6 +1069,7 @@ import {
1055
1069
  getConfiguredAppUrls,
1056
1070
  getAppUrl,
1057
1071
  getMcpBaseUrl,
1072
+ getScriptApiBaseUrl,
1058
1073
  getPublicMcpBaseUrl,
1059
1074
  getAgentFsLiveUrl,
1060
1075
  getAgentFsDefaultOrgId,
@@ -1063,7 +1078,7 @@ import {
1063
1078
  getCombState,
1064
1079
  isAgentFsProxyEnabled,
1065
1080
  init_constants3
1066
- } from "./cli-grbngev5.js";
1081
+ } from "./cli-466jjrwe.js";
1067
1082
  import {
1068
1083
  parseEnvFlag,
1069
1084
  isEnvFlagEnabled,
@@ -1072,7 +1087,7 @@ import {
1072
1087
  import {
1073
1088
  init_package,
1074
1089
  package_default
1075
- } from "./cli-hd5bm1e1.js";
1090
+ } from "./cli-shyhb4t5.js";
1076
1091
  import {
1077
1092
  getNodeEnv,
1078
1093
  isDevOrTestNodeEnv,
@@ -1092,7 +1107,7 @@ import {
1092
1107
  registerVolatileSecret,
1093
1108
  registerSensitiveKeyName,
1094
1109
  init_secret_scrubber
1095
- } from "./cli-1kvcsd2f.js";
1110
+ } from "./cli-r9d2tya0.js";
1096
1111
  import {
1097
1112
  __toESM,
1098
1113
  __commonJS,
@@ -20550,7 +20565,7 @@ function startRetryPoller(registry, intervalMs = 5000) {
20550
20565
  inputCtx
20551
20566
  };
20552
20567
  try {
20553
- const result = await executor.run({
20568
+ const result = await runWithNodeDeadline(node, executor, {
20554
20569
  config: interpolatedConfig,
20555
20570
  context: ctx,
20556
20571
  meta
@@ -20578,7 +20593,7 @@ function startRetryPoller(registry, intervalMs = 5000) {
20578
20593
  if (!waiting)
20579
20594
  continue;
20580
20595
  if (result.waitFor === "workflow.child.finished") {
20581
- const { resumeFromChildRun } = await import("./resume-0drnmpja.js");
20596
+ const { resumeFromChildRun } = await import("./resume-jdhnt4jk.js");
20582
20597
  await resumeFromChildRun(step.id, registry);
20583
20598
  }
20584
20599
  } else {
@@ -20698,6 +20713,7 @@ var init_retry_poller = __esm(() => {
20698
20713
  init_engine();
20699
20714
  init_foreach_driver();
20700
20715
  init_foreach_join();
20716
+ init_node_timeout();
20701
20717
  init_step_input();
20702
20718
  init_successor_routing();
20703
20719
  init_validation();
@@ -20973,13 +20989,17 @@ async function logOpenWebhookTriggers() {
20973
20989
  }
20974
20990
  }
20975
20991
  async function handleEventTrigger(eventName, payload, registry) {
20976
- const workflows = (await listWorkflows2({ enabled: true })).filter((workflow) => workflow.triggers.some((trigger) => trigger.type === "event" && trigger.eventName === eventName));
20992
+ const workflows = await getWorkflowsByEventName2(eventName);
20977
20993
  const runIds = [];
20978
20994
  for (const workflow of workflows) {
20979
- const runId = await startWorkflowExecution2(workflow, payload, registry, {
20980
- triggerType: "event"
20981
- });
20982
- runIds.push(runId);
20995
+ try {
20996
+ const runId = await startWorkflowExecution2(workflow, payload, registry, {
20997
+ triggerType: "event"
20998
+ });
20999
+ runIds.push(runId);
21000
+ } catch (err) {
21001
+ console.error(`[workflows] Failed to start workflow ${workflow.id} for ${eventName} event trigger:`, scrubSecrets(err instanceof Error ? err.message : String(err)));
21002
+ }
20983
21003
  }
20984
21004
  return runIds;
20985
21005
  }
@@ -21099,6 +21119,7 @@ function timingSafeEqualHex(providedHex, expected) {
21099
21119
  var DEFAULT_HMAC_HEADER = "X-Hub-Signature-256", FALLBACK_HMAC_HEADERS, STANDARD_WEBHOOK_SECRET_PREFIX = "whsec_", WebhookError;
21100
21120
  var init_triggers = __esm(() => {
21101
21121
  init_db4();
21122
+ init_secret_scrubber();
21102
21123
  init_engine();
21103
21124
  init_input();
21104
21125
  init_webhook_filter();
@@ -21466,7 +21487,7 @@ var init_notify = __esm(() => {
21466
21487
  }
21467
21488
  }
21468
21489
  case "slack": {
21469
- const { getSlackApp } = await import("./app-zfa9dwjw.js");
21490
+ const { getSlackApp } = await import("./app-5d3sz1hy.js");
21470
21491
  let app = getSlackApp();
21471
21492
  if (!app) {
21472
21493
  if (!isSlackConfigured()) {
@@ -21952,7 +21973,6 @@ var init_swarm_script = __esm(() => {
21952
21973
  init_db3();
21953
21974
  init_run_credential();
21954
21975
  init_types3();
21955
- init_constants3();
21956
21976
  init_template2();
21957
21977
  init_base();
21958
21978
  SWARM_SCRIPT_DEFAULT_TIMEOUT_MS = DEFAULT_SCRIPT_RESOURCES.wallClockMs;
@@ -22017,7 +22037,6 @@ var init_swarm_script = __esm(() => {
22017
22037
  fsMode: "none",
22018
22038
  executor: resolved.script.executor,
22019
22039
  agentId: agentId ?? "workflow",
22020
- mcpBaseUrl: getMcpBaseUrl(),
22021
22040
  egressSecrets: credentials.egressSecrets,
22022
22041
  failedBindings: credentials.failedBindings,
22023
22042
  userConfig: credentials.userConfig,
@@ -23120,11 +23139,15 @@ async function throwIfWorkflowNeedsSetup(scheduleId, runIds) {
23120
23139
  throw new AutomationNeedsSetupError(run.error);
23121
23140
  }
23122
23141
  }
23123
- async function claimScheduleOccurrence(snapshot, extraTags) {
23142
+ async function claimScheduleOccurrence(snapshot, extraTags, signal) {
23143
+ if (signal?.aborted)
23144
+ return null;
23124
23145
  const preparedWait = await prepareDeferredTaskWait(snapshot.id, "ceiling", extraTags);
23146
+ if (signal?.aborted)
23147
+ return null;
23125
23148
  return getDbClient2().transaction(async () => {
23126
23149
  const current = await getScheduledTaskById2(snapshot.id);
23127
- if (!current?.enabled || !current.nextRunAt || current.nextRunAt !== snapshot.nextRunAt) {
23150
+ if (signal?.aborted || !current?.enabled || !current.nextRunAt || current.nextRunAt !== snapshot.nextRunAt) {
23128
23151
  return null;
23129
23152
  }
23130
23153
  const schedule = renderScheduledTaskParams(current);
@@ -23154,17 +23177,19 @@ async function updateClaimedSchedule(claimed, updates) {
23154
23177
  await updateScheduledTask2(claimed.id, updates);
23155
23178
  });
23156
23179
  }
23157
- async function recoverMissedSchedules() {
23180
+ async function recoverMissedSchedules(signal) {
23158
23181
  const now = Date.now();
23159
23182
  const dueSchedules = await getDueScheduledTasks2();
23160
23183
  for (const schedule of dueSchedules) {
23184
+ if (signal.aborted)
23185
+ return;
23161
23186
  if (!schedule.nextRunAt)
23162
23187
  continue;
23163
23188
  const missedBy = now - new Date(schedule.nextRunAt).getTime();
23164
23189
  if (missedBy < 15000)
23165
23190
  continue;
23166
23191
  console.log(`[Scheduler] Recovering missed schedule "${schedule.name}" ` + `(was due ${Math.round(missedBy / 1000)}s ago)`);
23167
- await executeSchedule(schedule, ["recovered"]);
23192
+ await executeSchedule(schedule, ["recovered"], signal);
23168
23193
  }
23169
23194
  }
23170
23195
  function calculateNextRun2(schedule, fromTime = new Date) {
@@ -23189,12 +23214,12 @@ function getBackoffMs(consecutiveErrors) {
23189
23214
  const idx = Math.min(consecutiveErrors - 1, ERROR_BACKOFF_MS.length - 1);
23190
23215
  return ERROR_BACKOFF_MS[Math.max(0, idx)] ?? ERROR_BACKOFF_MS[0];
23191
23216
  }
23192
- async function executeSchedule(schedule, extraTags = []) {
23193
- let claimed = schedule;
23217
+ async function executeSchedule(schedule, extraTags = [], signal) {
23218
+ let claimed;
23194
23219
  let triggeredWorkflows = false;
23195
23220
  const wasRecovered = extraTags.includes("recovered");
23196
23221
  try {
23197
- const occurrence = await claimScheduleOccurrence(schedule, extraTags);
23222
+ const occurrence = await claimScheduleOccurrence(schedule, extraTags, signal);
23198
23223
  if (!occurrence)
23199
23224
  return;
23200
23225
  ({ schedule, claimed } = occurrence);
@@ -23211,6 +23236,8 @@ async function executeSchedule(schedule, extraTags = []) {
23211
23236
  wasRecovered
23212
23237
  });
23213
23238
  } catch (err) {
23239
+ if (signal?.aborted && !claimed)
23240
+ return;
23214
23241
  if (err instanceof AutomationNeedsSetupError) {
23215
23242
  telemetry.schedule("error", {
23216
23243
  scheduleType: schedule.scheduleType,
@@ -23241,7 +23268,7 @@ async function executeSchedule(schedule, extraTags = []) {
23241
23268
  updates.nextRunAt = new Date(now.getTime() + backoff).toISOString();
23242
23269
  console.log(`[Scheduler] Backing off "${schedule.name}" for ${backoff / 1000}s`);
23243
23270
  }
23244
- await updateClaimedSchedule(claimed, updates);
23271
+ await updateClaimedSchedule(claimed ?? schedule, updates);
23245
23272
  telemetry.schedule("error", {
23246
23273
  scheduleType: schedule.scheduleType,
23247
23274
  triggeredWorkflows,
@@ -23260,17 +23287,18 @@ function startScheduler2(registry, intervalMs = DEFAULT_SCHEDULER_INTERVAL_MS, o
23260
23287
  console.log("[Scheduler] Already running");
23261
23288
  return;
23262
23289
  }
23263
- const run = {};
23290
+ const run = new AbortController;
23264
23291
  schedulerRun = run;
23292
+ const { signal } = run;
23265
23293
  executorRegistry = registry;
23266
23294
  console.log(`[Scheduler] Starting with ${intervalMs}ms polling interval`);
23267
- initDeferredTaskWaits().then(() => schedulerRun === run ? recoverMissedSchedules() : undefined).catch((err) => console.error("[Scheduler] Recovery failed:", err)).then(async () => {
23268
- if (schedulerRun !== run)
23295
+ initDeferredTaskWaits().then(() => signal.aborted ? undefined : recoverMissedSchedules(signal)).catch((err) => console.error("[Scheduler] Recovery failed:", err)).then(async () => {
23296
+ if (signal.aborted)
23269
23297
  return;
23270
23298
  schedulerInterval = setInterval(() => {
23271
- withLoopPath("scheduler.poll", () => processSchedules()).catch((err) => console.error("[Scheduler] Poll failed:", err));
23299
+ withLoopPath("scheduler.poll", () => processSchedules(signal)).catch((err) => console.error("[Scheduler] Poll failed:", err));
23272
23300
  }, intervalMs);
23273
- await processSchedules();
23301
+ await processSchedules(signal);
23274
23302
  }).catch((err) => console.error("[Scheduler] Poll failed:", err));
23275
23303
  ensure({
23276
23304
  id: "scheduler_started",
@@ -23289,21 +23317,25 @@ function startScheduler2(registry, intervalMs = DEFAULT_SCHEDULER_INTERVAL_MS, o
23289
23317
  conditions: [{ timeout_ms: 1e4 }]
23290
23318
  });
23291
23319
  }
23292
- async function processSchedules() {
23293
- if (isProcessing)
23320
+ async function processSchedules(signal) {
23321
+ if (signal.aborted || isProcessing)
23294
23322
  return;
23295
23323
  isProcessing = true;
23296
23324
  try {
23297
23325
  await reconcileDeferredTaskWaits();
23326
+ if (signal.aborted)
23327
+ return;
23298
23328
  const dueSchedules = await getDueScheduledTasks2();
23299
23329
  for (const schedule of dueSchedules) {
23330
+ if (signal.aborted)
23331
+ return;
23300
23332
  try {
23301
- await executeSchedule(schedule);
23333
+ await executeSchedule(schedule, [], signal);
23302
23334
  } catch (err) {
23303
23335
  console.error(`[Scheduler] Error executing "${schedule.name}":`, err);
23304
23336
  }
23305
23337
  }
23306
- if (Date.now() - lastDeferredReapAt >= DEFERRED_REAP_INTERVAL_MS) {
23338
+ if (!signal.aborted && Date.now() - lastDeferredReapAt >= DEFERRED_REAP_INTERVAL_MS) {
23307
23339
  lastDeferredReapAt = Date.now();
23308
23340
  try {
23309
23341
  const reaped = await reapSpentDeferredSchedules();
@@ -23318,6 +23350,7 @@ async function processSchedules() {
23318
23350
  }
23319
23351
  }
23320
23352
  function stopScheduler2() {
23353
+ schedulerRun?.abort();
23321
23354
  schedulerRun = null;
23322
23355
  stopDeferredTaskWaits();
23323
23356
  if (schedulerInterval) {
@@ -25202,7 +25235,7 @@ function setPreloadedTools(server, names) {
25202
25235
  async function applyPreToolCall(name, args, requestInfo, inputSchema) {
25203
25236
  if (requestInfo.callOrigin !== "mcp")
25204
25237
  return { args };
25205
- const dispatcher = await import("./dispatcher-a2gdqz8c.js");
25238
+ const dispatcher = await import("./dispatcher-76as8w2t.js");
25206
25239
  const result = await dispatcher.dispatchPre("pre.tool.call", { tool: name, args, requestInfo }, inputSchema ? {
25207
25240
  validateModify: async (data) => {
25208
25241
  const schema = normalizeObjectSchema(inputSchema) ?? inputSchema;
@@ -25296,6 +25329,9 @@ var scriptSdkRequestOrigins, extensionRequestOrigins, getRequestInfo = (req) =>
25296
25329
  };
25297
25330
  }, PREVIEW_LIMIT = 500, toolOk = (message, extras = {}) => ({ ok: true, message, ...extras }), toolErr = (message, extras = {}) => ({ ok: false, message, ...extras }), swarmToolTruncationSchema, swarmToolEnvelopeShape, swarmToolOutputSchema = (dataShape) => looseObject({ ...swarmToolEnvelopeShape, ...dataShape ?? {} }), SCRIPT_AUTHORING_NUDGE = "Scripts must `export default async function (args, ctx)` — args FIRST, ctx second; run script-query-types (no name) for the full ctx/SDK type surface, and see the `swarm-scripts` skill for authoring patterns.", SCRIPT_RUN_TIMEOUT_NUDGE = "This one-off script timed out; use `launch-script-run` with bounded journaled steps for a durable run instead.", WORKFLOW_LONG_SCRIPT_TIMEOUT_NUDGE = "This workflow keeps a script node blocking for over two minutes; use `launch-script-run` with bounded journaled steps for durable one-off work instead.", scriptAuthoringNudge = (r) => !r.ok && /Typecheck failed:|Script run .*failed/.test(r.message) ? SCRIPT_AUTHORING_NUDGE : undefined, scriptRunNudge = (r) => {
25298
25331
  const body = r.data?.data;
25332
+ if (!r.ok && body?.error === "object busy") {
25333
+ return "object busy: retry the call later, do not loop.";
25334
+ }
25299
25335
  return !r.ok && body?.error === "timeout" ? SCRIPT_RUN_TIMEOUT_NUDGE : scriptAuthoringNudge(r);
25300
25336
  }, SLACK_API_DISK_NUDGE = "That path is on the API server's disk, not in your container — call this from a task you own (or pass its taskId) to get the file as a task attachment with a fetchCommand.", slackDownloadFileNudge = (r) => r.ok && r.data?.savedPath ? SLACK_API_DISK_NUDGE : undefined, slackReadNudge = (r) => {
25301
25337
  if (!r.ok)
@@ -25737,6 +25773,7 @@ class SwarmConfig {
25737
25773
  apiKey;
25738
25774
  agentId;
25739
25775
  mcpBaseUrl;
25776
+ sdkBaseUrl;
25740
25777
  runtimeInstanceId;
25741
25778
  auditSourceTaskId;
25742
25779
  extensionToken;
@@ -25754,6 +25791,11 @@ class SwarmConfig {
25754
25791
  type: "system",
25755
25792
  isSecret: payload.system.mcpBaseUrl.isSecret
25756
25793
  });
25794
+ const sdkBaseUrl = payload.system.sdkBaseUrl ?? payload.system.mcpBaseUrl;
25795
+ this.sdkBaseUrl = Redacted.make(sdkBaseUrl.value, {
25796
+ type: "system",
25797
+ isSecret: sdkBaseUrl.isSecret
25798
+ });
25757
25799
  this.runtimeInstanceId = payload.system.runtimeInstanceId ? Redacted.make(payload.system.runtimeInstanceId.value, {
25758
25800
  type: "system",
25759
25801
  isSecret: payload.system.runtimeInstanceId.isSecret
@@ -26433,7 +26475,7 @@ async function bridgeFetch(url, init, { repeatSafe, readOnly }, signal) {
26433
26475
  }
26434
26476
  }
26435
26477
  async function callBridgeApi(name, args, config, options = {}) {
26436
- const baseUrl = Redacted.value(config.mcpBaseUrl).replace(/\/$/, "");
26478
+ const baseUrl = Redacted.value(config.sdkBaseUrl).replace(/\/$/, "");
26437
26479
  const request = bridgeRequestFor(name, args);
26438
26480
  if (!request) {
26439
26481
  const mcpToolName = mcpToolNameForSdkMethod(name);
@@ -26516,13 +26558,15 @@ function createSwarmSdk(config, options = {}) {
26516
26558
  }
26517
26559
  });
26518
26560
  }
26519
- var BRIDGE_MAX_RETRIES = 3, BRIDGE_MIN_DELAY_MS = 250, BRIDGE_MAX_DELAY_MS = 2000, BRIDGE_RETRY_BUDGET_MS = 5000, READ_RETRY_STATUSES, READ_TOOL_PATTERN, READ_TOOLS, NON_READ_GET_METHODS;
26561
+ var DurableObject, BRIDGE_MAX_RETRIES = 3, BRIDGE_MIN_DELAY_MS = 250, BRIDGE_MAX_DELAY_MS = 2000, BRIDGE_RETRY_BUDGET_MS = 5000, READ_RETRY_STATUSES, READ_TOOL_PATTERN, READ_TOOLS, NON_READ_GET_METHODS;
26520
26562
  var init_swarm_sdk = __esm(() => {
26521
26563
  init_secret_scrubber();
26564
+ init_durable_object_base();
26522
26565
  init_redacted();
26523
26566
  init_response_limit();
26524
26567
  init_sdk_allowlist();
26525
26568
  init_retry();
26569
+ DurableObject = new Function(`${DURABLE_OBJECT_BASE_JS}; return DurableObject;`)();
26526
26570
  READ_RETRY_STATUSES = new Set([502, 503, 504]);
26527
26571
  READ_TOOL_PATTERN = /^(get|list)-|-(get|list|search)$/;
26528
26572
  READ_TOOLS = new Set([
@@ -36067,12 +36111,12 @@ var RELAY_GIVE_UP_AFTER_MS, SWEEP_EVERY_N_TICKS = 20, EARLY_TICK_DEBOUNCE_MS = 2
36067
36111
  var init_relay = __esm(() => {
36068
36112
  init_dist5();
36069
36113
  init_db4();
36070
- init_task_ui_spec();
36114
+ init_task_ui_spec2();
36071
36115
  init_reaction_events();
36072
36116
  init_context_key();
36073
36117
  init_env_flag();
36074
36118
  init_secret_scrubber();
36075
- init_task_ui_spec2();
36119
+ init_task_ui_spec();
36076
36120
  init_event_bus();
36077
36121
  init_commands();
36078
36122
  init_limits();
@@ -37106,7 +37150,7 @@ async function notifySlack(text) {
37106
37150
  return;
37107
37151
  }
37108
37152
  try {
37109
- const { getSlackApp } = await import("./app-zfa9dwjw.js");
37153
+ const { getSlackApp } = await import("./app-5d3sz1hy.js");
37110
37154
  const app = getSlackApp();
37111
37155
  if (!app) {
37112
37156
  console.warn("[Jira webhook keepalive] Slack not available, cannot send notification");
@@ -37177,7 +37221,7 @@ async function deleteJiraWebhook(webhookId) {
37177
37221
  console.log(`[Jira webhook keepalive] Deleted webhook id=${webhookId}`);
37178
37222
  }
37179
37223
  async function overwriteWebhookIds(next) {
37180
- const { getDbClient } = await import("./db-sc59379z.js");
37224
+ const { getDbClient } = await import("./db-vrckks6q.js");
37181
37225
  await getDbClient().transaction(async (tx) => {
37182
37226
  const row = await tx.get("SELECT metadata FROM oauth_apps WHERE provider = 'jira'");
37183
37227
  if (!row) {
@@ -109980,9 +110024,9 @@ var init_linear = __esm(() => {
109980
110024
  });
109981
110025
 
109982
110026
  // src/slack/files.ts
109983
- import { createWriteStream } from "node:fs";
109984
- import { mkdir } from "node:fs/promises";
109985
- import { dirname as dirname2 } from "node:path";
110027
+ import { constants } from "node:fs";
110028
+ import { lstat, mkdir, open, realpath, stat } from "node:fs/promises";
110029
+ import { basename, dirname as dirname2, isAbsolute as isAbsolute2, relative as relative2, resolve as resolve2, sep as sep2 } from "node:path";
109986
110030
  async function uploadFile(client, options) {
109987
110031
  const { file, filename, channelId, threadTs, initialComment, title } = options;
109988
110032
  try {
@@ -110037,8 +110081,88 @@ async function uploadFile(client, options) {
110037
110081
  };
110038
110082
  }
110039
110083
  }
110084
+ async function openFileInside(path, roots) {
110085
+ const outside = {
110086
+ success: false,
110087
+ notFound: false,
110088
+ error: `${path} must be a regular file inside ${roots.join(" or ")}.`
110089
+ };
110090
+ const inRoots = (real) => realRoots.some((root) => isInside(root, real));
110091
+ const realRoots = [];
110092
+ for (const root of roots) {
110093
+ const real = await realpath(root).catch(() => {
110094
+ return;
110095
+ });
110096
+ if (real && real !== "/")
110097
+ realRoots.push(real);
110098
+ }
110099
+ const real = await realpath(path).catch(() => {
110100
+ return;
110101
+ });
110102
+ if (!real)
110103
+ return { success: false, notFound: true, error: `File not found: ${path}` };
110104
+ if (!inRoots(real))
110105
+ return outside;
110106
+ let handle;
110107
+ try {
110108
+ handle = await open(real, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
110109
+ } catch {
110110
+ return { success: false, notFound: false, error: `Cannot read file: ${path}` };
110111
+ }
110112
+ try {
110113
+ const info = await handle.stat();
110114
+ const again = await realpath(real).catch(() => {
110115
+ return;
110116
+ });
110117
+ const now = again ? await stat(again).catch(() => {
110118
+ return;
110119
+ }) : undefined;
110120
+ if (!info.isFile() || !again || !inRoots(again) || now?.dev !== info.dev || now?.ino !== info.ino) {
110121
+ await handle.close();
110122
+ return outside;
110123
+ }
110124
+ if (info.size > MAX_FILE_SIZE) {
110125
+ await handle.close();
110126
+ const sizeMB = Math.round(info.size / 1024 / 1024);
110127
+ return {
110128
+ success: false,
110129
+ notFound: false,
110130
+ error: `File too large: ${sizeMB} MB. Maximum is 1 GB.`
110131
+ };
110132
+ }
110133
+ return { success: true, file: { handle, size: info.size } };
110134
+ } catch (error) {
110135
+ await handle.close();
110136
+ throw error;
110137
+ }
110138
+ }
110139
+ async function uploadOpenFile(client, file, options) {
110140
+ const { filename, channelId, threadTs, initialComment, title } = options;
110141
+ try {
110142
+ const ticket = await client.files.getUploadURLExternal({ filename, length: file.size });
110143
+ if (!ticket.upload_url || !ticket.file_id) {
110144
+ return { success: false, error: "Slack returned no upload URL" };
110145
+ }
110146
+ const sent = await fetch(ticket.upload_url, {
110147
+ method: "POST",
110148
+ body: Bun.file(file.handle.fd).slice(0, file.size)
110149
+ });
110150
+ if (!sent.ok) {
110151
+ return { success: false, error: `Upload failed with HTTP ${sent.status}` };
110152
+ }
110153
+ await client.files.completeUploadExternal({
110154
+ files: [{ id: ticket.file_id, title: title || filename }],
110155
+ channel_id: channelId,
110156
+ ...threadTs ? { thread_ts: threadTs } : {},
110157
+ ...initialComment ? { initial_comment: initialComment } : {}
110158
+ });
110159
+ return { success: true, fileId: ticket.file_id };
110160
+ } catch (error) {
110161
+ return { success: false, error: error instanceof Error ? error.message : String(error) };
110162
+ }
110163
+ }
110040
110164
  async function downloadFile(options) {
110041
- const { file, savePath, token } = options;
110165
+ const { file, savePath, token, root } = options;
110042
110166
  try {
110043
110167
  const downloadUrl = typeof file === "string" ? file : file.url_private_download;
110044
110168
  if (!downloadUrl) {
@@ -110047,11 +110171,26 @@ async function downloadFile(options) {
110047
110171
  error: "No download URL available for this file"
110048
110172
  };
110049
110173
  }
110174
+ if (!isSlackFileUrl(downloadUrl)) {
110175
+ return { success: false, error: "The download URL is not a Slack file URL" };
110176
+ }
110050
110177
  let finalPath = savePath;
110051
110178
  if (typeof file !== "string" && (savePath.endsWith("/") || !savePath.includes("."))) {
110052
- finalPath = savePath.endsWith("/") ? `${savePath}${file.name}` : `${savePath}/${file.name}`;
110179
+ const name = basename(file.name);
110180
+ finalPath = savePath.endsWith("/") ? `${savePath}${name}` : `${savePath}/${name}`;
110181
+ }
110182
+ finalPath = resolve2(root, finalPath);
110183
+ if (!isInside(resolve2(root), finalPath)) {
110184
+ return { success: false, error: `The save path must be inside ${root}` };
110185
+ }
110186
+ await mkdir(root, { recursive: true });
110187
+ if ((await lstat(root)).isSymbolicLink()) {
110188
+ return { success: false, error: `${root} must not be a symlink` };
110053
110189
  }
110054
110190
  await mkdir(dirname2(finalPath), { recursive: true });
110191
+ if (!isInside(await realpath(root), await realpath(dirname2(finalPath)))) {
110192
+ return { success: false, error: `The save path must be inside ${root}` };
110193
+ }
110055
110194
  const response = await fetch(downloadUrl, {
110056
110195
  headers: {
110057
110196
  Authorization: `Bearer ${token}`
@@ -110070,23 +110209,14 @@ async function downloadFile(options) {
110070
110209
  error: "No response body"
110071
110210
  };
110072
110211
  }
110073
- const writer = createWriteStream(finalPath);
110074
- const reader = body.getReader();
110212
+ const handle = await open(finalPath, constants.O_WRONLY | constants.O_CREAT | constants.O_TRUNC | constants.O_NOFOLLOW);
110075
110213
  try {
110076
- while (true) {
110077
- const { done, value } = await reader.read();
110078
- if (done)
110079
- break;
110080
- writer.write(value);
110214
+ for await (const chunk of body) {
110215
+ await handle.write(chunk);
110081
110216
  }
110082
- writer.end();
110083
110217
  } finally {
110084
- reader.releaseLock();
110218
+ await handle.close();
110085
110219
  }
110086
- await new Promise((resolve, reject) => {
110087
- writer.on("finish", resolve);
110088
- writer.on("error", reject);
110089
- });
110090
110220
  return {
110091
110221
  success: true,
110092
110222
  savedPath: finalPath
@@ -110099,6 +110229,25 @@ async function downloadFile(options) {
110099
110229
  };
110100
110230
  }
110101
110231
  }
110232
+ function isInside(parent, child) {
110233
+ const rel = relative2(parent, child);
110234
+ return rel !== ".." && !rel.startsWith(`..${sep2}`) && !isAbsolute2(rel);
110235
+ }
110236
+ function isSlackFileUrl(url) {
110237
+ let parsed;
110238
+ try {
110239
+ parsed = new URL(url);
110240
+ } catch {
110241
+ return false;
110242
+ }
110243
+ const apiUrl = process.env.SLACK_API_URL;
110244
+ if (apiUrl && URL.canParse(apiUrl) && new URL(apiUrl).origin === parsed.origin)
110245
+ return true;
110246
+ if (parsed.protocol !== "https:")
110247
+ return false;
110248
+ const host = parsed.hostname;
110249
+ return ["slack.com", "slack-gov.com"].some((domain) => host === domain || host.endsWith(`.${domain}`));
110250
+ }
110102
110251
  async function getFileInfo(client, fileId) {
110103
110252
  try {
110104
110253
  const result = await client.files.info({ file: fileId });
@@ -110127,9 +110276,9 @@ async function getFileInfo(client, fileId) {
110127
110276
  return null;
110128
110277
  }
110129
110278
  }
110130
- var MAX_FILE_SIZE = 1073741824, DEFAULT_DOWNLOAD_DIR;
110279
+ var MAX_FILE_SIZE = 1073741824, DOWNLOAD_ROOT = "/workspace/shared/downloads", DEFAULT_DOWNLOAD_DIR;
110131
110280
  var init_files = __esm(() => {
110132
- DEFAULT_DOWNLOAD_DIR = `/workspace/shared/downloads/${process.env.AGENT_ID || "default"}/slack`;
110281
+ DEFAULT_DOWNLOAD_DIR = `${DOWNLOAD_ROOT}/${process.env.AGENT_ID || "default"}/slack`;
110133
110282
  });
110134
110283
 
110135
110284
  // src/slack/router.ts
@@ -110673,7 +110822,7 @@ async function loadGlobalConfigsIntoEnv2(override = false) {
110673
110822
  if (updated.length > 0) {
110674
110823
  refreshSecretScrubberCache();
110675
110824
  }
110676
- const { syncSlackTreeVisibility } = await import("./tree-visibility-rwz67mje.js");
110825
+ const { syncSlackTreeVisibility } = await import("./tree-visibility-kjxv3nxk.js");
110677
110826
  await syncSlackTreeVisibility();
110678
110827
  return updated;
110679
110828
  }
@@ -110681,7 +110830,7 @@ async function reloadGlobalConfigsAndIntegrations2() {
110681
110830
  return runWithoutRequestAuth(() => runSlackLifecycleExclusive(() => reloadGlobalConfigsAndIntegrationsInner()));
110682
110831
  }
110683
110832
  async function reloadGlobalConfigsAndIntegrationsInner() {
110684
- const { getEmbeddingProvider, resetEmbeddingProvider } = await import("./index-rwwhsmjg.js");
110833
+ const { getEmbeddingProvider, resetEmbeddingProvider } = await import("./index-evay0xyk.js");
110685
110834
  const wasEmbeddingsConfigured = getEmbeddingProvider().isConfigured();
110686
110835
  const updated = await loadGlobalConfigsIntoEnv2(true);
110687
110836
  await syncTelemetryEnabled("settings").catch((err) => {
@@ -110697,7 +110846,7 @@ async function reloadGlobalConfigsAndIntegrationsInner() {
110697
110846
  integrations.push("embeddings");
110698
110847
  }
110699
110848
  if (isEmbeddingsConfigured) {
110700
- import("./embedding-space-qepzrach.js").then(({ runEmbeddingMaintenance }) => runEmbeddingMaintenance({ backfill: !wasEmbeddingsConfigured })).catch((err) => {
110849
+ import("./embedding-space-zsdw37bb.js").then(({ runEmbeddingMaintenance }) => runEmbeddingMaintenance({ backfill: !wasEmbeddingsConfigured })).catch((err) => {
110701
110850
  console.error("[config-reload] embedding maintenance failed (non-fatal):", err);
110702
110851
  });
110703
110852
  }
@@ -111483,9 +111632,55 @@ async function getAppRow(appId, model, rowId) {
111483
111632
  }
111484
111633
  return entry.value;
111485
111634
  }
111486
- async function listAppRows(appId, model, equals = []) {
111635
+ async function indexedRowIds(namespace, model, columns, equals) {
111636
+ let best = null;
111637
+ for (const { column, value } of equals) {
111638
+ if (typeof value === "number" || column.includes("/"))
111639
+ continue;
111640
+ const definition = Object.hasOwn(columns, column) ? columns[column] : undefined;
111641
+ if (!definition || !isIndexed(definition))
111642
+ continue;
111643
+ const prefix = appIndexKey(model, column, value, "");
111644
+ const keys = await getDbClient2().query(`SELECT key FROM kv_entries
111645
+ WHERE namespace = ? AND key >= ? AND key < ?
111646
+ AND (expires_at IS NULL OR expires_at > ?)
111647
+ ORDER BY key
111648
+ LIMIT ?`, [namespace, prefix, kvPrefixUpperBound2(prefix), Date.now(), INDEX_LIST_MAX_KEYS + 1]);
111649
+ if (keys.length > INDEX_LIST_MAX_KEYS)
111650
+ continue;
111651
+ if (best === null || keys.length < best.length) {
111652
+ best = keys.map((entry) => entry.key.slice(entry.key.lastIndexOf("/") + 1));
111653
+ }
111654
+ }
111655
+ return best;
111656
+ }
111657
+ async function listAppRows(appId, model, equals = [], columns) {
111487
111658
  const namespace = appsNamespace(appId);
111488
111659
  const prefix = `${model}/row/`;
111660
+ const ids = columns ? await indexedRowIds(namespace, model, columns, equals) : null;
111661
+ if (ids) {
111662
+ const rows = [];
111663
+ for (let start = 0;start < ids.length; start += INDEX_FETCH_BATCH) {
111664
+ const batch = ids.slice(start, start + INDEX_FETCH_BATCH);
111665
+ const entries = await getDbClient2().query(`SELECT value, value_type FROM kv_entries
111666
+ WHERE namespace = ? AND key IN (${batch.map(() => "?").join(",")})
111667
+ AND (expires_at IS NULL OR expires_at > ?)
111668
+ ORDER BY key`, [namespace, ...batch.map((id) => rowKey(model, id)), Date.now()]);
111669
+ for (const entry of entries) {
111670
+ if (entry.value_type !== "json")
111671
+ continue;
111672
+ try {
111673
+ const value = JSON.parse(entry.value);
111674
+ if (typeof value === "object" && value !== null && !Array.isArray(value)) {
111675
+ rows.push(value);
111676
+ }
111677
+ } catch {}
111678
+ }
111679
+ if (!isInTransaction())
111680
+ await yieldToEventLoop();
111681
+ }
111682
+ return rows;
111683
+ }
111489
111684
  const upper = kvPrefixUpperBound2(prefix);
111490
111685
  const jsonFieldEquals = equals.filter((filter) => !/["\\]/.test(filter.column)).map((filter) => ({ field: filter.column, value: filter.value }));
111491
111686
  const rows = [];
@@ -111664,7 +111859,7 @@ function purgeAppRows(appId, models, afterPurge) {
111664
111859
  };
111665
111860
  return acquire(0);
111666
111861
  }
111667
- var AppRowValidationError, AppRowAppNotFoundError, mutationChains, lastCreatedAtMs = 0, LIST_SCAN_WINDOW = 2000, LIST_ROW_CAP = 1e5, MIGRATION_KV_BATCH_SIZE = 1000, PURGE_BATCH_SIZE = 1000;
111862
+ var AppRowValidationError, AppRowAppNotFoundError, mutationChains, lastCreatedAtMs = 0, LIST_SCAN_WINDOW = 2000, LIST_ROW_CAP = 1e5, INDEX_LIST_MAX_KEYS = 20000, INDEX_FETCH_BATCH = 500, MIGRATION_KV_BATCH_SIZE = 1000, PURGE_BATCH_SIZE = 1000;
111668
111863
  var init_row_store = __esm(() => {
111669
111864
  init_db4();
111670
111865
  init_kv_windows();
@@ -113642,8 +113837,25 @@ function rejectGuest(req, res) {
113642
113837
  jsonError(res, "Forbidden", 403);
113643
113838
  return true;
113644
113839
  }
113840
+ async function refuseAgentTokenWithout(req, res, verb, resource = { kind: "none" }) {
113841
+ const auth = getRequestAuth(req);
113842
+ if (auth?.kind !== "agent")
113843
+ return false;
113844
+ const agent = await getAgentById2(auth.agentId);
113845
+ const decision = can({
113846
+ principal: { kind: "agent", agentId: auth.agentId, isLead: agent?.isLead === true },
113847
+ verb,
113848
+ resource,
113849
+ source: "http"
113850
+ });
113851
+ if (decision.allow)
113852
+ return false;
113853
+ jsonError(res, `Forbidden: ${decision.reason}`, 403);
113854
+ return true;
113855
+ }
113645
113856
  var init_request_principal = __esm(() => {
113646
113857
  init_db4();
113858
+ init_rbac();
113647
113859
  init_request_auth_context();
113648
113860
  init_utils2();
113649
113861
  });
@@ -113863,7 +114075,7 @@ function filtersFromQuery(queryParams, model) {
113863
114075
  }
113864
114076
  return { filters, issues };
113865
114077
  }
113866
- function compareValues(left, right, direction, dateValues = false) {
114078
+ function compareValues(left, right, direction) {
113867
114079
  if (left === right)
113868
114080
  return 0;
113869
114081
  if (left === undefined || left === null)
@@ -113871,9 +114083,7 @@ function compareValues(left, right, direction, dateValues = false) {
113871
114083
  if (right === undefined || right === null)
113872
114084
  return -1;
113873
114085
  let result;
113874
- if (dateValues && typeof left === "string" && typeof right === "string") {
113875
- result = Date.parse(left) - Date.parse(right);
113876
- } else if (typeof left === "number" && typeof right === "number") {
114086
+ if (typeof left === "number" && typeof right === "number") {
113877
114087
  result = left - right;
113878
114088
  } else if (typeof left === "boolean" && typeof right === "boolean") {
113879
114089
  result = Number(left) - Number(right);
@@ -113885,6 +114095,22 @@ function compareValues(left, right, direction, dateValues = false) {
113885
114095
  function rowValue(row, column) {
113886
114096
  return Object.hasOwn(row, column) ? row[column] : undefined;
113887
114097
  }
114098
+ function sortRowsByColumn(rows, column, dir, dateValues) {
114099
+ const keyed = rows.map((row) => {
114100
+ const value = rowValue(row, column);
114101
+ return { row, value, ts: dateValues && typeof value === "string" ? Date.parse(value) : 0 };
114102
+ });
114103
+ keyed.sort((a, b) => {
114104
+ if (dateValues && typeof a.value === "string" && typeof b.value === "string") {
114105
+ if (a.value === b.value)
114106
+ return 0;
114107
+ const result = a.ts - b.ts;
114108
+ return dir === "asc" ? result : -result;
114109
+ }
114110
+ return compareValues(a.value, b.value, dir);
114111
+ });
114112
+ return keyed.map((k) => k.row);
114113
+ }
113888
114114
  function rowMatchesFilters(row, filters) {
113889
114115
  return filters.every((filter) => rowValue(row, filter.column) === filter.value);
113890
114116
  }
@@ -113893,10 +114119,7 @@ function applyQuery(rows, query, model, params = {}, queryName = "<unnamed>") {
113893
114119
  let selected = rows.filter((row) => filters.every(([column, value]) => rowValue(row, column) === value));
113894
114120
  const sort = query.sort;
113895
114121
  if (sort) {
113896
- selected = [...selected].sort((a, b) => {
113897
- const result = compareValues(rowValue(a, sort.column), rowValue(b, sort.column), sort.dir, SORTABLE_SYSTEM_DATE_COLUMNS.has(sort.column) || Object.hasOwn(model.columns, sort.column) && model.columns[sort.column].kind === "date");
113898
- return result;
113899
- });
114122
+ selected = sortRowsByColumn(selected, sort.column, sort.dir, SORTABLE_SYSTEM_DATE_COLUMNS.has(sort.column) || Object.hasOwn(model.columns, sort.column) && model.columns[sort.column].kind === "date");
113900
114123
  }
113901
114124
  return selected.slice(0, query.limit ?? 200);
113902
114125
  }
@@ -113904,7 +114127,7 @@ async function selectAppRows(appId, modelName, model, filters, sortRaw, limit =
113904
114127
  const jsonFilterIssues = filters.flatMap((filter) => Object.hasOwn(model.columns, filter.column) && model.columns[filter.column].kind === "json" ? [{ path: `filter.${filter.column}`, message: "json columns cannot be filtered" }] : []);
113905
114128
  if (jsonFilterIssues.length > 0)
113906
114129
  throw new AppRowValidationError(jsonFilterIssues);
113907
- const rows = (await listAppRows(appId, modelName, filters.flatMap((filter) => typeof filter.value === "string" || typeof filter.value === "number" || typeof filter.value === "boolean" ? [{ column: filter.column, value: filter.value }] : []))).filter((row) => rowMatchesFilters(row, filters));
114130
+ let rows = (await listAppRows(appId, modelName, filters.flatMap((filter) => typeof filter.value === "string" || typeof filter.value === "number" || typeof filter.value === "boolean" ? [{ column: filter.column, value: filter.value }] : []), model.columns)).filter((row) => rowMatchesFilters(row, filters));
113908
114131
  if (sortRaw) {
113909
114132
  const [column, dir, extra] = sortRaw.split(":");
113910
114133
  if (extra !== undefined || !column || dir !== "asc" && dir !== "desc" || !SORTABLE_SYSTEM_DATE_COLUMNS.has(column) && !(systemColumns && Object.hasOwn(SYSTEM_COLUMN_KINDS, column)) && (!Object.hasOwn(model.columns, column) || model.columns[column].hidden === true)) {
@@ -113915,10 +114138,7 @@ async function selectAppRows(appId, modelName, model, filters, sortRaw, limit =
113915
114138
  if (model.columns[column]?.kind === "json") {
113916
114139
  throw new AppRowValidationError([{ path: "sort", message: "json columns cannot be sorted" }]);
113917
114140
  }
113918
- rows.sort((a, b) => {
113919
- const result = compareValues(rowValue(a, column), rowValue(b, column), dir, SORTABLE_SYSTEM_DATE_COLUMNS.has(column) || Object.hasOwn(model.columns, column) && model.columns[column].kind === "date");
113920
- return result;
113921
- });
114141
+ rows = sortRowsByColumn(rows, column, dir, SORTABLE_SYSTEM_DATE_COLUMNS.has(column) || Object.hasOwn(model.columns, column) && model.columns[column].kind === "date");
113922
114142
  }
113923
114143
  const total = rows.length;
113924
114144
  return { rows: rows.slice(0, limit), total };
@@ -113945,13 +114165,17 @@ async function handleApps(req, res, pathSegments, queryParams, myAgentId) {
113945
114165
  invalidDefinition(res, definition.issues);
113946
114166
  return true;
113947
114167
  }
113948
- const warnings = await scriptCompatWarnings(definition.definition);
114168
+ const app = await createApp({
114169
+ name: parsed.body.name,
114170
+ description: parsed.body.description,
114171
+ definition: definition.definition
114172
+ });
114173
+ const warnings = [
114174
+ ...await scriptCompatWarnings(definition.definition),
114175
+ ...await appWriteTypesWarnings(app.id)
114176
+ ];
113949
114177
  createAppRoute.respond(res, 201, {
113950
- app: await createApp({
113951
- name: parsed.body.name,
113952
- description: parsed.body.description,
113953
- definition: definition.definition
113954
- }),
114178
+ app,
113955
114179
  ...warnings.length > 0 ? { warnings } : {}
113956
114180
  });
113957
114181
  return true;
@@ -113960,8 +114184,9 @@ async function handleApps(req, res, pathSegments, queryParams, myAgentId) {
113960
114184
  const parsed = await listAppsRoute.parse(req, res, pathSegments, queryParams);
113961
114185
  if (!parsed)
113962
114186
  return true;
114187
+ const favoriteScope = (await resolveHttpFavoriteOwner(req, myAgentId))?.scope;
113963
114188
  listAppsRoute.respond(res, 200, {
113964
- apps: await listApps({ q: parsed.query.q, limit: parsed.query.limit })
114189
+ apps: await withFavoriteFlags2(await listApps({ q: parsed.query.q, limit: parsed.query.limit }), { favoriteScope, itemType: "app" })
113965
114190
  });
113966
114191
  return true;
113967
114192
  }
@@ -114379,7 +114604,10 @@ async function handleApps(req, res, pathSegments, queryParams, myAgentId) {
114379
114604
  jsonError(res, "app not found", 404);
114380
114605
  return true;
114381
114606
  }
114382
- const warnings = writtenDefinition === undefined ? [] : await scriptCompatWarnings(writtenDefinition);
114607
+ const warnings = writtenDefinition === undefined ? [] : [
114608
+ ...await scriptCompatWarnings(writtenDefinition),
114609
+ ...await appWriteTypesWarnings(parsed.params.id)
114610
+ ];
114383
114611
  patchAppRoute.respond(res, 200, {
114384
114612
  app,
114385
114613
  migration,
@@ -114472,7 +114700,10 @@ async function handleApps(req, res, pathSegments, queryParams, myAgentId) {
114472
114700
  jsonError(res, "app not found", 404);
114473
114701
  return true;
114474
114702
  }
114475
- const warnings = writtenDefinition === undefined ? [] : await scriptCompatWarnings(writtenDefinition);
114703
+ const warnings = writtenDefinition === undefined ? [] : [
114704
+ ...await scriptCompatWarnings(writtenDefinition),
114705
+ ...await appWriteTypesWarnings(parsed.params.id)
114706
+ ];
114476
114707
  updateAppRoute.respond(res, 200, {
114477
114708
  app,
114478
114709
  migration,
@@ -114592,6 +114823,7 @@ var init_apps = __esm(() => {
114592
114823
  init_definition();
114593
114824
  init_row_store();
114594
114825
  init_schema_migrate();
114826
+ init_script_types();
114595
114827
  init_store2();
114596
114828
  init_sync3();
114597
114829
  init_user_config();
@@ -114650,7 +114882,8 @@ var init_apps = __esm(() => {
114650
114882
  description: string2().optional(),
114651
114883
  icon: AppIconSchema.optional(),
114652
114884
  createdAt: string2(),
114653
- updatedAt: string2()
114885
+ updatedAt: string2(),
114886
+ favorite: boolean()
114654
114887
  });
114655
114888
  AppVersionSchema = object2({
114656
114889
  id: string2(),
@@ -114703,7 +114936,7 @@ var init_apps = __esm(() => {
114703
114936
  label: string2().optional()
114704
114937
  });
114705
114938
  AppUserConfigSchema = record2(AppNameSchema, AppUserConfigFieldSchema);
114706
- compatWarningsSchema = array2(string2()).optional().describe("Advisory quickjs-executor compatibility findings for the app's scripts.");
114939
+ compatWarningsSchema = array2(string2()).optional().describe("Advisory findings: quickjs-executor compatibility of the app's scripts, and whether the app lost its generated script types to the type budget.");
114707
114940
  appWriteResponseSchema = object2({
114708
114941
  app: AppRecordSchema,
114709
114942
  migration: AppMigrationReportSchema,
@@ -115371,6 +115604,7 @@ var registerAppPatchTool = (server) => {
115371
115604
  url: string2().optional(),
115372
115605
  app: unknown().optional(),
115373
115606
  migration: AppMigrationReportOutputSchema.optional(),
115607
+ warnings: array2(string2()).optional(),
115374
115608
  issues: array2(looseObject({ path: string2().optional(), message: string2().optional() })).optional()
115375
115609
  })
115376
115610
  }, async (input, requestInfo) => {
@@ -115463,9 +115697,11 @@ var registerAppPatchTool = (server) => {
115463
115697
  if (!app)
115464
115698
  return toolErr(`App ${input.appId} not found.`);
115465
115699
  const url = `/apps/${app.id}`;
115700
+ const warnings = await appWriteTypesWarnings(app.id);
115701
+ const extra = warnings.length > 0 ? { warnings } : {};
115466
115702
  return toolOk(`App "${app.name}" patched.`, {
115467
- details: JSON.stringify({ appId: app.id, url, app, migration }, null, 2),
115468
- data: { appId: app.id, url, app, migration }
115703
+ details: JSON.stringify({ appId: app.id, url, app, migration, ...extra }, null, 2),
115704
+ data: { appId: app.id, url, app, migration, ...extra }
115469
115705
  });
115470
115706
  });
115471
115707
  });
@@ -115474,6 +115710,7 @@ var init_app_patch = __esm(() => {
115474
115710
  init_zod();
115475
115711
  init_definition();
115476
115712
  init_schema_migrate();
115713
+ init_script_types();
115477
115714
  init_store2();
115478
115715
  init_version4();
115479
115716
  init_db4();
@@ -115821,6 +116058,7 @@ var registerAppUpsertTool = (server) => {
115821
116058
  appId: string2().optional(),
115822
116059
  url: string2().optional(),
115823
116060
  migration: AppMigrationReportOutputSchema.optional(),
116061
+ warnings: array2(string2()).optional(),
115824
116062
  issues: array2(looseObject({ path: string2().optional(), message: string2().optional() })).optional()
115825
116063
  })
115826
116064
  }, async (input, requestInfo) => {
@@ -115909,9 +116147,11 @@ var registerAppUpsertTool = (server) => {
115909
116147
  if (!app)
115910
116148
  return toolErr("Failed to save app.");
115911
116149
  const url = `/apps/${app.id}`;
116150
+ const warnings = await appWriteTypesWarnings(app.id);
115912
116151
  return toolOk(`App "${app.name}" saved.`, {
115913
- details: `App: ${url}`,
115914
- data: { appId: app.id, url, migration }
116152
+ details: [`App: ${url}`, ...warnings].join(`
116153
+ `),
116154
+ data: { appId: app.id, url, migration, ...warnings.length > 0 ? { warnings } : {} }
115915
116155
  });
115916
116156
  });
115917
116157
  }
@@ -115937,9 +116177,11 @@ var registerAppUpsertTool = (server) => {
115937
116177
  if (!app)
115938
116178
  return toolErr("Failed to save app.");
115939
116179
  const url = `/apps/${app.id}`;
116180
+ const warnings = await appWriteTypesWarnings(app.id);
115940
116181
  return toolOk(`App "${app.name}" saved.`, {
115941
- details: `App: ${url}`,
115942
- data: { appId: app.id, url }
116182
+ details: [`App: ${url}`, ...warnings].join(`
116183
+ `),
116184
+ data: { appId: app.id, url, ...warnings.length > 0 ? { warnings } : {} }
115943
116185
  });
115944
116186
  });
115945
116187
  };
@@ -115947,6 +116189,7 @@ var init_app_upsert = __esm(() => {
115947
116189
  init_zod();
115948
116190
  init_definition();
115949
116191
  init_schema_migrate();
116192
+ init_script_types();
115950
116193
  init_store2();
115951
116194
  init_version4();
115952
116195
  init_db4();
@@ -123943,63 +124186,17 @@ Checks:
123943
124186
  ${checks.map((c) => `- ${c}`).join(`
123944
124187
  `)}`;
123945
124188
  }
123946
- function partsInTz(date, tz) {
123947
- const fmt = new Intl.DateTimeFormat("en-US", {
123948
- timeZone: tz,
123949
- year: "numeric",
123950
- month: "2-digit",
123951
- day: "2-digit",
123952
- hour: "2-digit",
123953
- minute: "2-digit",
123954
- second: "2-digit",
123955
- hour12: false
123956
- });
123957
- const parts = Object.fromEntries(fmt.formatToParts(date).map((p) => [p.type, p.value]));
123958
- const hour = parts.hour === "24" ? "00" : parts.hour;
123959
- return {
123960
- year: parts.year,
123961
- month: parts.month,
123962
- day: parts.day,
123963
- hour,
123964
- minute: parts.minute,
123965
- second: parts.second
123966
- };
123967
- }
123968
- function formatDeferralDateTime(target, now, tz) {
123969
- let zone = tz;
123970
- try {
123971
- Intl.DateTimeFormat("en-US", { timeZone: zone });
123972
- } catch {
123973
- zone = "UTC";
123974
- }
123975
- const t = partsInTz(target, zone);
123976
- const time = `${t.hour}:${t.minute}`;
123977
- const n = partsInTz(now, zone);
123978
- if (t.year === n.year && t.month === n.month && t.day === n.day)
123979
- return { date: "today", time };
123980
- const tm = partsInTz(new Date(now.getTime() + 86400000), zone);
123981
- if (t.year === tm.year && t.month === tm.month && t.day === tm.day) {
123982
- return { date: "tomorrow", time };
123983
- }
123984
- return { date: `${t.month}-${t.day}`, time };
123985
- }
123986
- async function resolveRequesterTimezone(requestedByUserId) {
123987
- if (requestedByUserId) {
123988
- const user = await getUserById2(requestedByUserId);
123989
- if (user?.timezone)
123990
- return { tz: user.timezone, isFallback: false };
123991
- }
123992
- return { tz: "UTC", isFallback: true };
123993
- }
123994
124189
  function joinNames(names) {
123995
124190
  if (names.length < 2)
123996
124191
  return names[0] ?? "";
123997
124192
  return `${names.slice(0, -1).join(", ")} and ${names[names.length - 1]}`;
123998
124193
  }
123999
- function renderWaitingOn(agentNames, watchedCount) {
124194
+ function renderWaitingOn(agentNames, watchedCount, titles = []) {
124000
124195
  const named = joinNames([...new Set(agentNames.filter((name) => name.trim()))]);
124001
124196
  if (named)
124002
124197
  return named;
124198
+ if (watchedCount === 1 && titles[0]?.trim())
124199
+ return titles[0].trim();
124003
124200
  return `${watchedCount} task${watchedCount === 1 ? "" : "s"}`;
124004
124201
  }
124005
124202
  function renderWhen(nextRunAt, tz, isFallbackTz) {
@@ -124123,6 +124320,7 @@ var isExternalEvent = (event) => EXTERNAL_EVENT_NAMES.includes(event), DeferAbor
124123
124320
  }
124124
124321
  }
124125
124322
  const watchedAgentNames = [];
124323
+ const watchedTitles = [];
124126
124324
  for (const watchedId of watchedTaskIds) {
124127
124325
  if (watchedId === taskId)
124128
124326
  throw new DeferAbortedError("Cannot wake on the task being deferred.");
@@ -124134,6 +124332,8 @@ var isExternalEvent = (event) => EXTERNAL_EVENT_NAMES.includes(event), DeferAbor
124134
124332
  const watchedAgent = watched.agentId ? await getAgentById2(watched.agentId) : null;
124135
124333
  if (watchedAgent?.name)
124136
124334
  watchedAgentNames.push(watchedAgent.name);
124335
+ if (watched.title)
124336
+ watchedTitles.push(watched.title);
124137
124337
  }
124138
124338
  const schedule = await createScheduledTask2({
124139
124339
  name: `deferred-${taskId.slice(0, 8)}-${Date.now()}-${crypto.randomUUID()}`,
@@ -124187,10 +124387,11 @@ var isExternalEvent = (event) => EXTERNAL_EVENT_NAMES.includes(event), DeferAbor
124187
124387
  const deferralDetails = `${summary}
124188
124388
 
124189
124389
  Deferred until ${nextRunAt} (schedule ${schedule.id}). Pending: ${note}${checksBlock}`;
124190
- const terminalOutput = task.outputSchema ? output : renderHumanFacingDeferral(nextRunAt, requesterTz, isFallbackTz, admitted && eventWait ? describeEventWait(admitted.adapter.source, eventWait.event, admitted.match) : wakeOn ? renderWaitingOn(watchedAgentNames, watchedTaskIds.length) : undefined);
124390
+ const terminalOutput = task.outputSchema ? output : renderHumanFacingDeferral(nextRunAt, requesterTz, isFallbackTz, admitted && eventWait ? describeEventWait(admitted.adapter.source, eventWait.event, admitted.match) : wakeOn ? renderWaitingOn(watchedAgentNames, watchedTaskIds.length, watchedTitles) : undefined);
124191
124391
  const completed = await completeTask2(taskId, terminalOutput, {
124192
124392
  addTags: ["deferred"],
124193
124393
  deferredAt: new Date().toISOString(),
124394
+ deferredUntil: nextRunAt,
124194
124395
  statusKind: "deferred"
124195
124396
  });
124196
124397
  if (!completed) {
@@ -124250,6 +124451,7 @@ var init_defer_task = __esm(() => {
124250
124451
  init_zod();
124251
124452
  init_audit_user();
124252
124453
  init_db4();
124454
+ init_requester_timezone();
124253
124455
  init_event_waits();
124254
124456
  init_deferred_task_waits();
124255
124457
  init_task_terminal_effects();
@@ -124257,6 +124459,7 @@ var init_defer_task = __esm(() => {
124257
124459
  init_task_tool_ctx();
124258
124460
  init_utils();
124259
124461
  init_types5();
124462
+ init_deferral_time();
124260
124463
  init_business_use();
124261
124464
  init_request_auth_context();
124262
124465
  DeferAbortedError = class DeferAbortedError extends Error {
@@ -124517,7 +124720,7 @@ function isRecord(value) {
124517
124720
  return typeof value === "object" && value !== null && !Array.isArray(value);
124518
124721
  }
124519
124722
  function apiBaseUrl() {
124520
- return getMcpBaseUrl();
124723
+ return getScriptApiBaseUrl();
124521
124724
  }
124522
124725
  function renderIssue(issue) {
124523
124726
  if (typeof issue === "string")
@@ -125453,7 +125656,11 @@ function requiresLeadToWrite(namespace) {
125453
125656
  return LEAD_ONLY_FAMILIES.has(namespace.split(":", 1)[0] ?? "");
125454
125657
  }
125455
125658
  function reservedNamespaceError(namespace) {
125456
- return RESERVED_FAMILIES.get(namespace.split(":", 1)[0] ?? "") ?? null;
125659
+ for (const [family, error] of RESERVED_FAMILIES) {
125660
+ if (namespace === family || namespace.startsWith(`${family}:`))
125661
+ return error;
125662
+ }
125663
+ return null;
125457
125664
  }
125458
125665
  function privateNamespaceError(namespace) {
125459
125666
  return PRIVATE_FAMILIES.has(namespace.split(":", 1)[0] ?? "") ? reservedNamespaceError(namespace) : null;
@@ -125461,9 +125668,14 @@ function privateNamespaceError(namespace) {
125461
125668
  function reservedRoomKeyError(key) {
125462
125669
  return key.startsWith("_room/") ? "room snapshot keys are reserved; use the room endpoints" : null;
125463
125670
  }
125671
+ function scrubReservedRead(namespace, value) {
125672
+ return namespace.split(":", 1)[0] === "durable" ? scrubObject(value) : value;
125673
+ }
125464
125674
  var RESERVED_FAMILIES, PRIVATE_FAMILIES, LEAD_ONLY_FAMILIES;
125465
125675
  var init_kv_reserved_namespaces = __esm(() => {
125676
+ init_secret_scrubber();
125466
125677
  RESERVED_FAMILIES = new Map([
125678
+ ["durable", "namespace holds durable object state; it is written only by object calls"],
125467
125679
  ["apps", "namespace is reserved for swarm apps; use the app row endpoints"],
125468
125680
  ["comb", "namespace is reserved for Comb; use POST /api/comb/review-batches"],
125469
125681
  [
@@ -125478,6 +125690,14 @@ var init_kv_reserved_namespaces = __esm(() => {
125478
125690
  [
125479
125691
  "session-labels",
125480
125692
  "namespace is reserved for session source labels; GET /api/session-tree returns them"
125693
+ ],
125694
+ [
125695
+ "integration:user-enrichment",
125696
+ "namespace is reserved for integration profile enrichment; the API writes it from the provider"
125697
+ ],
125698
+ [
125699
+ "integrations:kapso",
125700
+ "namespace is reserved for Kapso routing; use register-kapso-number or unregister-kapso-number"
125481
125701
  ]
125482
125702
  ]);
125483
125703
  PRIVATE_FAMILIES = new Set(["session-labels", "slack-thread-buffer"]);
@@ -125705,6 +125925,8 @@ var kvEntryOutputSchema, kvViewOutputSchema, registerKvGetTool = (server) => {
125705
125925
  });
125706
125926
  }
125707
125927
  const entry = await getKv2(resolved.namespace, key);
125928
+ if (entry)
125929
+ entry.value = scrubReservedRead(resolved.namespace, entry.value);
125708
125930
  if (entry && hasKvViewArgs({ path, offset, limit })) {
125709
125931
  return boundedView(entry, requestInfo.agentId, { path, offset, limit });
125710
125932
  }
@@ -125721,6 +125943,7 @@ var kvEntryOutputSchema, kvViewOutputSchema, registerKvGetTool = (server) => {
125721
125943
  var init_kv_get = __esm(() => {
125722
125944
  init_zod();
125723
125945
  init_db4();
125946
+ init_kv_reserved_namespaces();
125724
125947
  init_kv_view();
125725
125948
  init_utils();
125726
125949
  init_types5();
@@ -125848,11 +126071,14 @@ var MAX_KV_LIST_LIMIT = 1000, kvEntryOutputSchema3, registerKvListTool = (server
125848
126071
  }
125849
126072
  const effectiveLimit = Math.min(limit ?? 100, MAX_KV_LIST_LIMIT);
125850
126073
  const effectivePrefix = prefix && prefix.length > 0 ? prefix : undefined;
125851
- const entries = await listKv2(resolved.namespace, {
126074
+ const entries = (await listKv2(resolved.namespace, {
125852
126075
  prefix: effectivePrefix,
125853
126076
  limit: effectiveLimit,
125854
126077
  offset: offset ?? 0
125855
- });
126078
+ })).map((entry) => ({
126079
+ ...entry,
126080
+ value: scrubReservedRead(resolved.namespace, entry.value)
126081
+ }));
125856
126082
  const total = await countKv2(resolved.namespace, { prefix: effectivePrefix });
125857
126083
  return toolOk(entries.length === 0 ? `No entries in "${resolved.namespace}".` : `Found ${entries.length} of ${total} entries in "${resolved.namespace}".`, {
125858
126084
  details: renderKvEntries(entries),
@@ -125868,6 +126094,7 @@ var MAX_KV_LIST_LIMIT = 1000, kvEntryOutputSchema3, registerKvListTool = (server
125868
126094
  var init_kv_list = __esm(() => {
125869
126095
  init_zod();
125870
126096
  init_db4();
126097
+ init_kv_reserved_namespaces();
125871
126098
  init_utils();
125872
126099
  init_types5();
125873
126100
  init_kv_read_auth();
@@ -125883,8 +126110,14 @@ var init_kv_list = __esm(() => {
125883
126110
  });
125884
126111
  });
125885
126112
 
126113
+ // src/kv-limits.ts
126114
+ var MAX_KV_BODY_BYTES;
126115
+ var init_kv_limits = __esm(() => {
126116
+ MAX_KV_BODY_BYTES = 2 * 1024 * 1024;
126117
+ });
126118
+
125886
126119
  // src/tools/kv/kv-set.ts
125887
- var MAX_KV_BODY_BYTES, kvEntryOutputSchema4, registerKvSetTool = (server) => {
126120
+ var kvEntryOutputSchema4, registerKvSetTool = (server) => {
125888
126121
  createToolRegistrar(server)("kv-set", {
125889
126122
  title: "KV Set",
125890
126123
  description: "Write a key in the swarm KV store. Each replacement is atomic but unconditional: there is no compare-and-swap, so concurrent read-modify-write callers can lose updates. Namespace defaults to your current context. Use `expiresInSec` for opt-in TTL (default: never expires). 2 MiB body cap.",
@@ -125974,11 +126207,11 @@ var MAX_KV_BODY_BYTES, kvEntryOutputSchema4, registerKvSetTool = (server) => {
125974
126207
  var init_kv_set = __esm(() => {
125975
126208
  init_zod();
125976
126209
  init_db4();
126210
+ init_kv_limits();
125977
126211
  init_utils();
125978
126212
  init_types5();
125979
126213
  init_kv_write_auth();
125980
126214
  init_resolve_namespace();
125981
- MAX_KV_BODY_BYTES = 2 * 1024 * 1024;
125982
126215
  kvEntryOutputSchema4 = looseObject({
125983
126216
  namespace: string2().optional(),
125984
126217
  key: string2().optional(),
@@ -129426,21 +129659,48 @@ var init_repo_merge_policy = __esm(() => {
129426
129659
  });
129427
129660
 
129428
129661
  // src/be/repo-checked-update.ts
129429
- async function updateSwarmRepoChecked(id, updates, authorize) {
129662
+ function changesExecConfig(existing, updates) {
129663
+ return updates.url !== undefined && updates.url !== existing.url || updates.clonePath !== undefined && updates.clonePath !== existing.clonePath || updates.hooks !== undefined && updates.hooks?.enabled === true !== (existing.hooks?.enabled === true);
129664
+ }
129665
+ async function execConfigRefusal(auth, source) {
129666
+ if (auth?.page) {
129667
+ return "Forbidden: a page session cannot change a repo's url, clonePath or hooks.";
129668
+ }
129669
+ if (auth?.kind !== "agent")
129670
+ return null;
129671
+ const agent = await getAgentById2(auth.agentId);
129672
+ const decision = can({
129673
+ principal: { kind: "agent", agentId: auth.agentId, isLead: agent?.isLead === true },
129674
+ verb: "repo.exec-config.write",
129675
+ resource: { kind: "none" },
129676
+ source
129677
+ });
129678
+ if (decision.allow)
129679
+ return null;
129680
+ return `Forbidden: ${decision.reason}. Only the lead, the operator or a user can change a repo's url, clonePath or hooks.`;
129681
+ }
129682
+ async function updateSwarmRepoChecked(id, updates, authorize, authorizeExecConfig) {
129430
129683
  return await getDbClient2().transaction(async () => {
129431
- if (updates.guidelines !== undefined) {
129684
+ const touchesExecConfig = updates.url !== undefined || updates.clonePath !== undefined || updates.hooks !== undefined;
129685
+ if (updates.guidelines !== undefined || touchesExecConfig) {
129432
129686
  const existing = await getSwarmRepoById2(id);
129433
129687
  if (existing && changesMergePolicy(existing.guidelines, updates.guidelines)) {
129434
129688
  const refusal = await authorize(existing);
129435
129689
  if (refusal !== null)
129436
129690
  return { kind: "refused", refusal };
129437
129691
  }
129692
+ if (existing && changesExecConfig(existing, updates)) {
129693
+ const refusal = await authorizeExecConfig(existing);
129694
+ if (refusal !== null)
129695
+ return { kind: "refused", refusal };
129696
+ }
129438
129697
  }
129439
129698
  const repo = await updateSwarmRepo2(id, updates);
129440
129699
  return repo ? { kind: "updated", repo } : { kind: "not-found" };
129441
129700
  });
129442
129701
  }
129443
129702
  var init_repo_checked_update = __esm(() => {
129703
+ init_rbac();
129444
129704
  init_db4();
129445
129705
  init_repo_merge_policy();
129446
129706
  });
@@ -129449,14 +129709,14 @@ var init_repo_checked_update = __esm(() => {
129449
129709
  var swarmRepoOutputShape2, registerUpdateRepoTool = (server) => {
129450
129710
  createToolRegistrar(server)("update-repo", {
129451
129711
  title: "Update Repo",
129452
- description: "Update a repo's configuration including guidelines (PR checks, merge policy, review guidance). The lead uses this to set guidelines after asking the user. Pass null for guidelines to clear them. Only the lead can change allowMerge or mergePolicy: resend their current values to edit other guidelines.",
129712
+ description: "Update a repo's configuration including guidelines (PR checks, merge policy, review guidance). The lead uses this to set guidelines after asking the user. Pass null for guidelines to clear them. Only the lead can change allowMerge or mergePolicy: resend their current values to edit other guidelines. An agent session token also needs the lead role to change url, clonePath or hooks.",
129453
129713
  annotations: { readOnlyHint: false },
129454
129714
  inputSchema: object2({
129455
129715
  id: string2().uuid().describe("The repo ID to update."),
129456
- url: string2().optional().describe("New repo URL."),
129716
+ url: string2().refine((value) => !value.startsWith("-"), 'url must not start with "-"').optional().describe("New repo URL."),
129457
129717
  name: string2().optional().describe("New repo name."),
129458
- clonePath: string2().optional().describe("New clone path."),
129459
- defaultBranch: string2().optional().describe("New default branch."),
129718
+ clonePath: string2().refine((value) => !value.startsWith("-"), 'clonePath must not start with "-"').optional().describe("New clone path."),
129719
+ defaultBranch: string2().refine((value) => !value.startsWith("-"), 'defaultBranch must not start with "-"').optional().describe("New default branch."),
129460
129720
  autoClone: boolean().optional().describe("Whether to auto-clone."),
129461
129721
  hooks: RepoHooksSchema.nullable().optional().describe("Repository hook install config. Best-effort worker hook installation is enabled by default for new repos. Disable it with { enabled: false } (or null), or turn it back on with { enabled: true }."),
129462
129722
  guidelines: RepoGuidelinesInputSchema.nullable().optional().describe("Repository guidelines: prChecks (commands before PR), mergeChecks (conditions before merge), allowMerge (default false), review (guidance for reviewers), mergePolicy (per-repo merge policy record: autoMerge, agentsMayMerge, notify). Pass null to clear.")
@@ -129477,7 +129737,7 @@ var swarmRepoOutputShape2, registerUpdateRepoTool = (server) => {
129477
129737
  return null;
129478
129738
  const current = agentsMayMerge(existing.guidelines);
129479
129739
  return `Only lead agents can change allowMerge or mergePolicy (agents may merge: ${current}). Resend the current allowMerge and mergePolicy to keep them while you edit the other guidelines.`;
129480
- });
129740
+ }, () => execConfigRefusal(getCurrentRequestAuth(), "mcp"));
129481
129741
  if (result.kind === "refused") {
129482
129742
  return toolErr(result.refusal, { data: { repo: null } });
129483
129743
  }
@@ -129498,6 +129758,7 @@ var init_update_repo = __esm(() => {
129498
129758
  init_rbac();
129499
129759
  init_utils();
129500
129760
  init_types5();
129761
+ init_request_auth_context();
129501
129762
  swarmRepoOutputShape2 = looseObject({
129502
129763
  id: string2().optional(),
129503
129764
  url: string2().optional(),
@@ -135945,7 +136206,7 @@ var init_rooms = __esm(() => {
135945
136206
  });
135946
136207
 
135947
136208
  // src/tools/rooms.ts
135948
- async function resolve2(namespace, requestInfo, write) {
136209
+ async function resolve3(namespace, requestInfo, write) {
135949
136210
  const resolved = await resolveRoomNamespace(namespace, requestInfo);
135950
136211
  if ("error" in resolved)
135951
136212
  return resolved;
@@ -135963,7 +136224,7 @@ var roomInput, roomOutput, decodedRoomOutput, registerRoomGetTool = (server) =>
135963
136224
  yourAgentId: string2().optional()
135964
136225
  })
135965
136226
  }, async ({ name, namespace, schemaVersion }, requestInfo) => {
135966
- const resolved = await resolve2(namespace, requestInfo, false);
136227
+ const resolved = await resolve3(namespace, requestInfo, false);
135967
136228
  if ("error" in resolved)
135968
136229
  return toolErr(resolved.error, { data: { yourAgentId: requestInfo.agentId } });
135969
136230
  try {
@@ -135990,7 +136251,7 @@ var roomInput, roomOutput, decodedRoomOutput, registerRoomGetTool = (server) =>
135990
136251
  }),
135991
136252
  rbac: { permission: "kv.write.any" }
135992
136253
  }, async ({ name, namespace, schemaVersion, operations }, requestInfo) => {
135993
- const resolved = await resolve2(namespace, requestInfo, true);
136254
+ const resolved = await resolve3(namespace, requestInfo, true);
135994
136255
  if ("error" in resolved)
135995
136256
  return toolErr(resolved.error, { data: { yourAgentId: requestInfo.agentId } });
135996
136257
  try {
@@ -136016,7 +136277,7 @@ var roomInput, roomOutput, decodedRoomOutput, registerRoomGetTool = (server) =>
136016
136277
  }),
136017
136278
  rbac: { permission: "kv.write.any" }
136018
136279
  }, async ({ name, namespace, schemaVersion, state }, requestInfo) => {
136019
- const resolved = await resolve2(namespace, requestInfo, true);
136280
+ const resolved = await resolve3(namespace, requestInfo, true);
136020
136281
  if ("error" in resolved)
136021
136282
  return toolErr(resolved.error, { data: { yourAgentId: requestInfo.agentId } });
136022
136283
  try {
@@ -137494,6 +137755,19 @@ var registerRunScheduleNowTool = (server) => {
137494
137755
  if (!schedule) {
137495
137756
  return toolErr("Schedule not found.");
137496
137757
  }
137758
+ const auth = getCurrentRequestAuth();
137759
+ if (auth?.kind === "agent") {
137760
+ const caller = await getAgentById2(auth.agentId);
137761
+ const decision = can({
137762
+ principal: { kind: "agent", agentId: auth.agentId, isLead: caller?.isLead === true },
137763
+ verb: "schedule.run.any",
137764
+ resource: { kind: "owned", ownerAgentId: schedule.createdByAgentId },
137765
+ source: "mcp"
137766
+ });
137767
+ if (!decision.allow) {
137768
+ return toolErr(`Schedule "${schedule.name}" runs as the agent that created it. Only that agent or a lead can run it.`);
137769
+ }
137770
+ }
137497
137771
  if (!schedule.enabled) {
137498
137772
  return toolErr(`Schedule "${schedule.name}" is disabled.`, {
137499
137773
  details: "Enable it first or use it as a template."
@@ -137524,8 +137798,10 @@ var registerRunScheduleNowTool = (server) => {
137524
137798
  var init_run_schedule_now = __esm(() => {
137525
137799
  init_zod();
137526
137800
  init_db4();
137801
+ init_rbac();
137527
137802
  init_scheduler2();
137528
137803
  init_utils();
137804
+ init_request_auth_context();
137529
137805
  });
137530
137806
 
137531
137807
  // src/tools/schedules/update-schedule.ts
@@ -137970,7 +138246,7 @@ ${warnings.join(`
137970
138246
  return denied;
137971
138247
  const result = await proxyScriptsApi({
137972
138248
  method: "POST",
137973
- path: `/api/scripts/${args.scriptId}/apis/${args.endpointId}/rotate`,
138249
+ path: `/api/scripts/${args.scriptId}/apis/${encodeURIComponent(args.endpointId)}/rotate`,
137974
138250
  requestInfo,
137975
138251
  successMessage: () => "Token rotated.",
137976
138252
  successDetails: (data) => {
@@ -137994,7 +138270,7 @@ ${warnings.join(`
137994
138270
  return denied;
137995
138271
  return proxyScriptsApi({
137996
138272
  method: "PATCH",
137997
- path: `/api/scripts/${args.scriptId}/apis/${args.endpointId}`,
138273
+ path: `/api/scripts/${args.scriptId}/apis/${encodeURIComponent(args.endpointId)}`,
137998
138274
  body: { enabled: args.enabled, label: args.label },
137999
138275
  requestInfo,
138000
138276
  successMessage: () => "Endpoint updated."
@@ -138008,7 +138284,7 @@ ${warnings.join(`
138008
138284
  return denied;
138009
138285
  return proxyScriptsApi({
138010
138286
  method: "DELETE",
138011
- path: `/api/scripts/${args.scriptId}/apis/${args.endpointId}`,
138287
+ path: `/api/scripts/${args.scriptId}/apis/${encodeURIComponent(args.endpointId)}`,
138012
138288
  requestInfo,
138013
138289
  successMessage: () => "Endpoint deleted."
138014
138290
  });
@@ -138026,7 +138302,7 @@ var init_script_apis = __esm(() => {
138026
138302
  scriptApisInputSchema = object2({
138027
138303
  action: _enum2(["list", "create", "update", "rotate", "delete"]).describe("list: endpoints for a script, tokens masked unless includeSecrets=true. create: expose the script as a new endpoint (returns the plaintext token once). update: enable/disable or relabel an endpoint. rotate: issue a new token (returns it once). delete: remove an endpoint."),
138028
138304
  scriptId: string2().uuid().describe("The script the endpoint(s) belong to."),
138029
- endpointId: string2().optional().describe("Required for update, rotate, and delete."),
138305
+ endpointId: string2().regex(/^[A-Za-z0-9_-]+$/, "endpointId must be an endpoint id").optional().describe("Required for update, rotate, and delete."),
138030
138306
  authMode: _enum2(["none", "bearer"]).optional().describe("For create: 'bearer' (default, auto-generated token) or 'none' (no auth)."),
138031
138307
  label: string2().max(200).nullable().optional().describe("For create/update."),
138032
138308
  agentId: string2().optional().describe("For create: the agent the endpoint runs as (its egress secrets + API connections apply). Defaults to the script's owning agent; required if the script has none."),
@@ -138405,6 +138681,9 @@ ${body.stdout.trim()}`);
138405
138681
  const notes = [];
138406
138682
  if (typeof body.durationMs === "number")
138407
138683
  notes.push(`${body.durationMs}ms`);
138684
+ if (typeof body.object?.stateVersion === "number") {
138685
+ notes.push(`object.stateVersion: ${body.object.stateVersion}`);
138686
+ }
138408
138687
  if (body.truncated?.stdout || body.truncated?.stderr) {
138409
138688
  notes.push("output truncated by the runtime");
138410
138689
  }
@@ -138426,6 +138705,7 @@ var SCRIPT_RUN_DESCRIPTION = "Run a named swarm-shared script (callable across a
138426
138705
  annotations: { openWorldHint: true },
138427
138706
  inputSchema: object2({
138428
138707
  name: scriptNameSchema.optional().describe("Name of a reusable script to run."),
138708
+ object: object2({ id: string2().min(1).max(256), method: string2().min(1).max(128) }).optional().describe("Call this object ID and method on the named global DurableObject script."),
138429
138709
  source: string2().min(1).optional().describe('Inline TypeScript source to run without a compile-time typecheck. Must `export default async function (args, ctx)` — args FIRST, ctx second. Import `ScriptContext` from "swarm-sdk" for promotion-safe typing.'),
138430
138710
  args: unknown().optional().describe("JSON-serializable script arguments."),
138431
138711
  intent: string2().default("").describe("Why this script is being run."),
@@ -138639,7 +138919,7 @@ var SCRIPT_UPSERT_DESCRIPTION = 'Typecheck and persist a TypeScript script to th
138639
138919
  annotations: { openWorldHint: false },
138640
138920
  inputSchema: object2({
138641
138921
  name: scriptNameSchema.describe("Stable script name within the selected scope."),
138642
- source: string2().min(1).describe('TypeScript source, typechecked before saving. Must `export default async function (args, ctx)` — args FIRST, ctx second. Import `ScriptContext` from "swarm-sdk" to type `ctx`. Schemas can import "zod" or "zod/mini"; Mini uses functional forms such as z.optional(z.string()).'),
138922
+ source: string2().min(1).describe('TypeScript source, typechecked before saving. Must `export default async function (args, ctx)` — args FIRST, ctx second. Import `ScriptContext` from "swarm-sdk" to type `ctx`. Schemas can import "zod" or "zod/mini"; Mini uses functional forms such as z.optional(z.string()). A global script can instead `export default class X extends DurableObject<State>` (import `DurableObject` from "swarm-sdk").'),
138643
138923
  description: string2().default("").describe("Human-readable script description."),
138644
138924
  intent: string2().default("").describe("Why this script exists."),
138645
138925
  scope: scriptScopeSchema.default("agent").describe("Persist under agent or global scope."),
@@ -141874,6 +142154,13 @@ var init_templates = __esm(() => {
141874
142154
  variables: [],
141875
142155
  category: "system"
141876
142156
  });
142157
+ registerTemplate({
142158
+ eventType: "slack.message.thread_context_other_bot",
142159
+ header: "",
142160
+ defaultBody: "[Bot {{bot_id}}] (untrusted)",
142161
+ variables: [{ name: "bot_id", description: "Slack bot ID of the bot or app that posted" }],
142162
+ category: "system"
142163
+ });
141877
142164
  });
141878
142165
 
141879
142166
  // src/slack/inbound-files.ts
@@ -142179,19 +142466,20 @@ var init_inbound_files = __esm(() => {
142179
142466
  });
142180
142467
 
142181
142468
  // src/tools/slack-download-file.ts
142469
+ import { basename as basename2 } from "node:path";
142182
142470
  function fileIdFromUrl(url) {
142183
142471
  return /\/files-pri\/[A-Z0-9]+-([A-Z0-9]+)\//.exec(url)?.[1];
142184
142472
  }
142185
142473
  var registerSlackDownloadFileTool = (server) => {
142186
142474
  createToolRegistrar(server)("slack-download-file", {
142187
142475
  title: "Download file from Slack",
142188
- description: "Download a file from Slack by file ID or URL. From a task, the file is stored as an attachment of that task and the result carries a ready-to-run `fetchCommand` to get the bytes into your container. Without a task, the file is saved on the API server's disk, which your container usually can't read.",
142476
+ description: "Download a file from Slack by file ID or Slack file URL. From a task, the file is stored as an attachment of that task and the result carries a ready-to-run `fetchCommand` to get the bytes into your container. Without a task, the file is saved under /workspace/shared/downloads/ on the API server's disk, which your container usually can't read.",
142189
142477
  annotations: { readOnlyHint: false, openWorldHint: true },
142190
142478
  inputSchema: object2({
142191
142479
  fileId: string2().optional().describe("The Slack file ID to download (e.g., 'F0RDC39U1')."),
142192
- url: string2().url().optional().describe("Direct URL to download (url_private_download from a file object)."),
142480
+ url: string2().url().optional().describe("Slack file URL (url_private_download or url_private from a file object). The file ID in it is looked up in Slack."),
142193
142481
  taskId: uuid().optional().describe("Task to attach the file to. Defaults to the task you are working on; must be a task you own or created."),
142194
- savePath: string2().optional().describe("Only without a task: where to save the file on the API server (directory or full path). Defaults to /workspace/shared/downloads/{agentId}/slack/."),
142482
+ savePath: string2().optional().describe("Only without a task: where to save the file on the API server (directory or full path). Must be inside /workspace/shared/downloads/; a relative path resolves from there. Defaults to /workspace/shared/downloads/{agentId}/slack/."),
142195
142483
  filename: string2().optional().describe("Filename to use when saving. Only used if savePath is a directory.")
142196
142484
  }),
142197
142485
  outputSchema: swarmToolOutputSchema({
@@ -142235,11 +142523,11 @@ var registerSlackDownloadFileTool = (server) => {
142235
142523
  if (fileId && !info) {
142236
142524
  return toolErr(`File not found: ${fileId}`);
142237
142525
  }
142238
- const fileInfo = info ? { id: info.id, name: info.name, mimetype: info.mimetype, size: info.size } : undefined;
142526
+ if (!info) {
142527
+ return toolErr("Could not identify the Slack file in that URL; pass fileId instead.");
142528
+ }
142529
+ const fileInfo = { id: info.id, name: info.name, mimetype: info.mimetype, size: info.size };
142239
142530
  if (task) {
142240
- if (!info) {
142241
- return toolErr("Could not identify the Slack file in that URL; pass fileId instead.");
142242
- }
142243
142531
  const outcome = (await attachSlackFilesForAgent(app.client, task, [info], agent.id)).get(info.id);
142244
142532
  if (!outcome || "reason" in outcome) {
142245
142533
  return toolErr(`Failed to attach file: ${outcome?.reason ?? "unknown error"}`);
@@ -142251,18 +142539,19 @@ ${fetchCommand}`,
142251
142539
  data: { taskId: task.id, attachmentId: attachment.id, fetchCommand, fileInfo }
142252
142540
  });
142253
142541
  }
142254
- const downloadUrl = info?.url_private_download ?? url;
142542
+ const downloadUrl = info.url_private_download;
142255
142543
  if (!downloadUrl) {
142256
142544
  return toolErr("No download URL available.");
142257
142545
  }
142258
142546
  let finalSavePath = savePath || DEFAULT_DOWNLOAD_DIR;
142259
142547
  if (finalSavePath.endsWith("/") || !finalSavePath.includes(".")) {
142260
- const actualFilename = filename || fileInfo?.name || `file_${Date.now()}`;
142548
+ const actualFilename = basename2(filename || info.name || `file_${Date.now()}`);
142261
142549
  finalSavePath = finalSavePath.endsWith("/") ? `${finalSavePath}${actualFilename}` : `${finalSavePath}/${actualFilename}`;
142262
142550
  }
142263
142551
  const result = await downloadFile({
142264
142552
  file: downloadUrl,
142265
142553
  savePath: finalSavePath,
142554
+ root: DOWNLOAD_ROOT,
142266
142555
  token
142267
142556
  });
142268
142557
  if (!result.success) {
@@ -142553,6 +142842,10 @@ var registerSlackPostTool = (server) => {
142553
142842
  }
142554
142843
  if (blocks && card)
142555
142844
  return toolErr("Provide either blocks or card, not both.");
142845
+ const reservedActionId = findReservedActionId(blocks);
142846
+ if (reservedActionId) {
142847
+ return toolErr(`blocks use the action_id "${reservedActionId}", which the swarm reserves for its own buttons. Use another action_id.`);
142848
+ }
142556
142849
  if (!message && !card)
142557
142850
  return toolErr("Provide a message or a card.");
142558
142851
  let cardSlack;
@@ -142651,6 +142944,7 @@ var init_slack_post = __esm(() => {
142651
142944
  });
142652
142945
 
142653
142946
  // src/tools/slack-read.ts
142947
+ import { basename as basename3 } from "node:path";
142654
142948
  var AUTO_DOWNLOAD_DIR = "/app/shared/downloads/slack", USERS_INFO_CONCURRENCY = 4, SlackFileSchema, SlackMessageSchema, registerSlackReadTool = (server) => {
142655
142949
  createToolRegistrar(server)("slack-read", {
142656
142950
  title: "Read Slack thread/channel history",
@@ -142811,11 +143105,12 @@ var AUTO_DOWNLOAD_DIR = "/app/shared/downloads/slack", USERS_INFO_CONCURRENCY =
142811
143105
  if (attachTo) {
142812
143106
  toAttach.push({ raw: f, info: fileInfo });
142813
143107
  } else if (token && f.url_private_download) {
142814
- const savePath = `${AUTO_DOWNLOAD_DIR}/${f.id}_${f.name}`;
142815
143108
  try {
143109
+ const savePath = `${AUTO_DOWNLOAD_DIR}/${f.id}_${basename3(f.name)}`;
142816
143110
  const downloadResult = await downloadFile({
142817
143111
  file: f.url_private_download,
142818
143112
  savePath,
143113
+ root: AUTO_DOWNLOAD_DIR,
142819
143114
  token
142820
143115
  });
142821
143116
  if (downloadResult.success && downloadResult.savedPath) {
@@ -143055,6 +143350,14 @@ ${JSON.stringify(cardSlack.blocks)}` : blocks ? JSON.stringify(blocks) : message
143055
143350
  await markTaskSlackReplySent2(taskId);
143056
143351
  console.log(`[Slack] Marked slackReplySent=1 for task ${taskId}`);
143057
143352
  }
143353
+ const sourceTaskId = requestInfo.sourceTaskId;
143354
+ if (sourceTaskId && sourceTaskId !== taskId) {
143355
+ const sourceTask = await getTaskById2(sourceTaskId);
143356
+ if (sourceTask?.agentId === agent.id && sourceTask.slackChannelId === slackChannelId && sourceTask.slackThreadTs === slackThreadTs) {
143357
+ await markTaskSlackReplySent2(sourceTaskId);
143358
+ console.log(`[Slack] Marked slackReplySent=1 for source task ${sourceTaskId}`);
143359
+ }
143360
+ }
143058
143361
  return toolOk("Reply sent successfully.", {
143059
143362
  details: messageTs ? `Message timestamp: ${messageTs}` : undefined,
143060
143363
  data: { messageTs }
@@ -143111,6 +143414,10 @@ var registerSlackStartThreadTool = (server) => {
143111
143414
  if (!decision.allow) {
143112
143415
  return toolErr("Posting to Slack channels requires lead privileges.");
143113
143416
  }
143417
+ const reservedActionId = findReservedActionId(blocks);
143418
+ if (reservedActionId) {
143419
+ return toolErr(`blocks use the action_id "${reservedActionId}", which the swarm reserves for its own buttons. Use another action_id.`);
143420
+ }
143114
143421
  const app = getSlackApp2();
143115
143422
  if (!app) {
143116
143423
  return toolErr("Slack not configured.");
@@ -143279,46 +143586,50 @@ function resolveTaskUploadThreadTs(task) {
143279
143586
  }
143280
143587
  return task.slackThreadTs;
143281
143588
  }
143282
- async function resolveAndValidateFilePath(filePath) {
143283
- const triedPaths = [];
143284
- const fileExists = async (path) => {
143285
- try {
143286
- const bunFile = Bun.file(path);
143287
- return await bunFile.exists();
143288
- } catch {
143289
- return false;
143290
- }
143291
- };
143292
- if (!filePath.startsWith("/")) {
143293
- const absolutePath = `${WORKSPACE_DIR}/${filePath}`;
143294
- triedPaths.push(absolutePath);
143295
- if (await fileExists(absolutePath)) {
143296
- return { success: true, resolvedPath: absolutePath };
143297
- }
143298
- return {
143299
- success: false,
143300
- error: `File not found. Relative paths are resolved from ${WORKSPACE_DIR}.`,
143301
- triedPaths
143302
- };
143303
- }
143304
- triedPaths.push(filePath);
143305
- if (await fileExists(filePath)) {
143306
- return { success: true, resolvedPath: filePath };
143307
- }
143308
- if (!filePath.startsWith(WORKSPACE_DIR)) {
143309
- const relativePath = filePath.slice(1);
143310
- const workspacePath = `${WORKSPACE_DIR}/${relativePath}`;
143311
- triedPaths.push(workspacePath);
143312
- if (await fileExists(workspacePath)) {
143313
- return { success: true, resolvedPath: workspacePath };
143314
- }
143315
- }
143589
+ async function uploadRoots(agentId, taskIds) {
143590
+ const roots = [WORKSPACE_DIR];
143591
+ for (const id of new Set(taskIds.filter((t) => !!t))) {
143592
+ const task = await getTaskById2(id);
143593
+ if (!task || task.agentId !== agentId && task.creatorAgentId !== agentId)
143594
+ continue;
143595
+ if (task.dir)
143596
+ roots.push(task.dir);
143597
+ const repoId = await vcsRepoId(task.vcsRepo);
143598
+ const repo = repoId ? await getSwarmRepoById2(repoId) : null;
143599
+ if (repo)
143600
+ roots.push(repo.clonePath);
143601
+ }
143602
+ return roots;
143603
+ }
143604
+ async function openUploadFile(filePath, roots) {
143605
+ const triedPaths = filePath.startsWith("/") ? [
143606
+ filePath,
143607
+ ...filePath.startsWith(`${WORKSPACE_DIR}/`) ? [] : [`${WORKSPACE_DIR}${filePath}`]
143608
+ ] : [`${WORKSPACE_DIR}/${filePath}`];
143609
+ let refusal;
143610
+ for (const candidate of triedPaths) {
143611
+ const opened = await openFileInside(candidate, roots);
143612
+ if (opened.success)
143613
+ return { success: true, file: opened.file, resolvedPath: candidate };
143614
+ if (!opened.notFound)
143615
+ refusal ??= opened.error;
143616
+ }
143617
+ if (refusal)
143618
+ return { success: false, notFound: false, error: refusal, triedPaths };
143316
143619
  return {
143317
143620
  success: false,
143318
- error: `File not found at any of the attempted locations.`,
143621
+ notFound: true,
143622
+ error: filePath.startsWith("/") ? "File not found at any of the attempted locations." : `File not found. Relative paths are resolved from ${WORKSPACE_DIR}.`,
143319
143623
  triedPaths
143320
143624
  };
143321
143625
  }
143626
+ function uploadResult(result) {
143627
+ if (!result.success) {
143628
+ return toolErr(`Failed to upload file: ${result.error}`);
143629
+ }
143630
+ const successMsg = `File uploaded successfully${result.fileId ? ` (ID: ${result.fileId})` : ""}.`;
143631
+ return toolOk(successMsg, { data: { fileId: result.fileId } });
143632
+ }
143322
143633
  var WORKSPACE_DIR = "/workspace", registerSlackUploadFileTool = (server) => {
143323
143634
  createToolRegistrar(server)("slack-upload-file", {
143324
143635
  title: "Upload file to Slack",
@@ -143329,7 +143640,7 @@ var WORKSPACE_DIR = "/workspace", registerSlackUploadFileTool = (server) => {
143329
143640
  taskId: uuid().optional().describe("The task ID with Slack context (for task-related threads)."),
143330
143641
  channelId: string2().optional().describe("Direct channel ID to upload to (requires lead privileges)."),
143331
143642
  threadTs: string2().optional().describe("Thread timestamp to upload as a thread reply (used with channelId)."),
143332
- filePath: string2().min(1).optional().describe("Path to the file to upload. Either filePath OR content must be provided. " + "IMPORTANT: the file is read on the API server's filesystem (where this tool runs), NOT on the caller's. " + "Worker/lead containers do NOT share /tmp or /workspace/personal/ with the API server — the only shared volume is /workspace/shared/. " + "Use /workspace/shared/<agent-id>/file.png (or a relative path like 'shared/<agent-id>/file.png'). " + "For files that only live on the caller (e.g. /tmp), pass them inline via `content` (base64) instead."),
143643
+ filePath: string2().min(1).optional().describe("Path to the file to upload. Either filePath OR content must be provided. " + "IMPORTANT: the file is read on the API server's filesystem (where this tool runs), NOT on the caller's. " + "Worker/lead containers do NOT share /tmp or /workspace/personal/ with the API server — the only shared volume is /workspace/shared/. " + "The file must be a regular file inside /workspace or the working directory of your current task. " + "Use /workspace/shared/<agent-id>/file.png (or a relative path like 'shared/<agent-id>/file.png'). " + "For files that only live on the caller (e.g. /tmp), pass them inline via `content` (base64) instead."),
143333
143644
  content: string2().optional().describe("Base64-encoded file content. Use this when the file lives on the caller's filesystem and isn't reachable by the API server " + "(e.g. anything under /tmp on a worker/lead container). Either filePath OR content must be provided."),
143334
143645
  filename: string2().optional().describe("Name to give the file in Slack. Required when using content, defaults to original filename when using filePath."),
143335
143646
  initialComment: string2().max(4000).optional().describe("Optional message to post with the file.")
@@ -143402,11 +143713,12 @@ var WORKSPACE_DIR = "/workspace", registerSlackUploadFileTool = (server) => {
143402
143713
  if (content && !filename) {
143403
143714
  return toolErr("filename is required when using base64 content upload.");
143404
143715
  }
143405
- let fileToUpload;
143406
- let actualFilename;
143407
143716
  if (filePath) {
143408
- const pathResult = await resolveAndValidateFilePath(filePath);
143717
+ const roots = await uploadRoots(agent.id, [taskId, requestInfo.sourceTaskId]);
143718
+ const pathResult = await openUploadFile(filePath, roots);
143409
143719
  if (!pathResult.success) {
143720
+ if (!pathResult.notFound)
143721
+ return toolErr(pathResult.error);
143410
143722
  const triedPathsList = pathResult.triedPaths.map((p) => ` - ${p}`).join(`
143411
143723
  `);
143412
143724
  const errorMsg = `${pathResult.error}
@@ -143421,40 +143733,35 @@ ${triedPathsList}
143421
143733
  ` + `- Or pass the file inline via the \`content\` arg as base64 (with \`filename\`) so no shared-mount round-trip is needed.`;
143422
143734
  return toolErr(errorMsg);
143423
143735
  }
143424
- const resolvedPath = pathResult.resolvedPath;
143425
- const bunFile = Bun.file(resolvedPath);
143426
- const fileSize = bunFile.size;
143427
- if (fileSize > MAX_FILE_SIZE) {
143428
- const sizeMB = Math.round(fileSize / 1024 / 1024);
143429
- return toolErr(`File too large: ${sizeMB} MB. Maximum is 1 GB.`);
143430
- }
143431
- fileToUpload = resolvedPath;
143432
- actualFilename = filename || resolvedPath.split("/").pop() || "file";
143433
- } else {
143434
143736
  try {
143435
- fileToUpload = Buffer.from(content, "base64");
143436
- } catch {
143437
- return toolErr("Invalid base64 content.");
143438
- }
143439
- if (fileToUpload.length > MAX_FILE_SIZE) {
143440
- const sizeMB = Math.round(fileToUpload.length / 1024 / 1024);
143441
- return toolErr(`File too large: ${sizeMB} MB. Maximum is 1 GB.`);
143737
+ return uploadResult(await uploadOpenFile(app.client, pathResult.file, {
143738
+ filename: filename || pathResult.resolvedPath.split("/").pop() || "file",
143739
+ channelId: slackChannelId,
143740
+ threadTs: slackThreadTs,
143741
+ initialComment
143742
+ }));
143743
+ } finally {
143744
+ await pathResult.file.handle.close();
143442
143745
  }
143443
- actualFilename = filename;
143746
+ }
143747
+ let fileToUpload;
143748
+ try {
143749
+ fileToUpload = Buffer.from(content, "base64");
143750
+ } catch {
143751
+ return toolErr("Invalid base64 content.");
143752
+ }
143753
+ if (fileToUpload.length > MAX_FILE_SIZE) {
143754
+ const sizeMB = Math.round(fileToUpload.length / 1024 / 1024);
143755
+ return toolErr(`File too large: ${sizeMB} MB. Maximum is 1 GB.`);
143444
143756
  }
143445
143757
  try {
143446
- const result = await uploadFile(app.client, {
143758
+ return uploadResult(await uploadFile(app.client, {
143447
143759
  file: fileToUpload,
143448
- filename: actualFilename,
143760
+ filename,
143449
143761
  channelId: slackChannelId,
143450
143762
  threadTs: slackThreadTs,
143451
143763
  initialComment
143452
- });
143453
- if (!result.success) {
143454
- return toolErr(`Failed to upload file: ${result.error}`);
143455
- }
143456
- const successMsg = `File uploaded successfully${result.fileId ? ` (ID: ${result.fileId})` : ""}.`;
143457
- return toolOk(successMsg, { data: { fileId: result.fileId } });
143764
+ }));
143458
143765
  } catch (error) {
143459
143766
  const errorMsg = error instanceof Error ? error.message : String(error);
143460
143767
  return toolErr(`Failed to upload file: ${errorMsg}`);
@@ -143464,6 +143771,7 @@ ${triedPathsList}
143464
143771
  var init_slack_upload_file = __esm(() => {
143465
143772
  init_zod();
143466
143773
  init_db4();
143774
+ init_model_profile_check();
143467
143775
  init_rbac();
143468
143776
  init_app4();
143469
143777
  init_external_channel();
@@ -143760,7 +144068,7 @@ var init_task_skip = __esm(() => {
143760
144068
  var TaskUiSpecActionInputSchema, TaskUiSpecInputSchema;
143761
144069
  var init_schema2 = __esm(() => {
143762
144070
  init_zod();
143763
- init_task_ui_spec2();
144071
+ init_task_ui_spec();
143764
144072
  TaskUiSpecActionInputSchema = discriminatedUnion("kind", [
143765
144073
  object2({ kind: literal2("follow_up"), prompt: string2().min(1).max(4000) }),
143766
144074
  object2({
@@ -143786,7 +144094,7 @@ async function readScriptActionAllowlist() {
143786
144094
  const [row] = await getSwarmConfigs2({ scope: "global", key: UI_SPEC_SCRIPT_ACTIONS_KEY });
143787
144095
  if (row)
143788
144096
  return row.value;
143789
- const { getDeploymentEnvValue } = await import("./core-bwp98v4w.js");
144097
+ const { getDeploymentEnvValue } = await import("./core-dynsv289.js");
143790
144098
  return getDeploymentEnvValue(UI_SPEC_SCRIPT_ACTIONS_KEY);
143791
144099
  }
143792
144100
  async function loadScriptActionLookups() {
@@ -143997,10 +144305,10 @@ var init_script_actions = __esm(() => {
143997
144305
  init_db4();
143998
144306
  init_db3();
143999
144307
  init_run_saved();
144000
- init_task_ui_spec();
144308
+ init_task_ui_spec2();
144001
144309
  init_env_flag();
144002
144310
  init_secret_scrubber();
144003
- init_task_ui_spec2();
144311
+ init_task_ui_spec();
144004
144312
  init_event_bus();
144005
144313
  init_json_schema_validator();
144006
144314
  init_schema2();
@@ -144461,7 +144769,7 @@ var init_store_progress = __esm(() => {
144461
144769
  init_constants2();
144462
144770
  init_task_learning();
144463
144771
  init_task_citations2();
144464
- init_task_ui_spec();
144772
+ init_task_ui_spec2();
144465
144773
  init_agent_fs_provider();
144466
144774
  init_rbac();
144467
144775
  init_task_skip();
@@ -144624,14 +144932,14 @@ async function approveAndSend(id, approval) {
144624
144932
  let proxyId = null;
144625
144933
  let proxyError = null;
144626
144934
  try {
144627
- const response = await fetch(approval.endpoint, {
144935
+ const response = await createSsrfGuardedFetch(publicEndpointSsrfOptions())(approval.endpoint, {
144628
144936
  method: "POST",
144629
144937
  headers: { "Content-Type": "application/json" },
144630
144938
  body: JSON.stringify(payload),
144631
144939
  signal: AbortSignal.timeout(SEND_TIMEOUT_MS)
144632
144940
  });
144633
144941
  proxyStatus = response.status;
144634
- const body = await response.text().catch(() => "");
144942
+ const body = await readBodyPrefix(response, PROXY_ERROR_MAX).catch(() => "");
144635
144943
  if (response.ok) {
144636
144944
  try {
144637
144945
  const parsed = JSON.parse(body);
@@ -144663,6 +144971,25 @@ async function approveAndSend(id, approval) {
144663
144971
  throw new Error(`Improvement ${id} vanished after send`);
144664
144972
  return finished;
144665
144973
  }
144974
+ async function readBodyPrefix(response, maxBytes) {
144975
+ const reader = response.body?.getReader();
144976
+ if (!reader)
144977
+ return "";
144978
+ const chunks = [];
144979
+ let size = 0;
144980
+ try {
144981
+ while (size < maxBytes) {
144982
+ const { done, value } = await reader.read();
144983
+ if (done)
144984
+ break;
144985
+ chunks.push(value);
144986
+ size += value.byteLength;
144987
+ }
144988
+ } finally {
144989
+ await reader.cancel().catch(() => {});
144990
+ }
144991
+ return new TextDecoder().decode(Buffer.concat(chunks).subarray(0, maxBytes));
144992
+ }
144666
144993
  async function discardImprovement(id, options) {
144667
144994
  await assertEnabled();
144668
144995
  const now = new Date().toISOString();
@@ -144736,6 +145063,8 @@ async function improvementLeakHints(text) {
144736
145063
  }
144737
145064
  var IMPROVEMENTS_ENABLED_KEY = "IMPROVEMENTS_ENABLED", IMPROVEMENT_TEXT_MAX = 4000, SEND_TIMEOUT_MS = 1e4, PROXY_ERROR_MAX = 1024, LEAK_HINTS_MAX = 50, INSTALL_ID_KEY = "telemetry_installation_id", EMAIL_MAX = 320, VALID_EMAIL_RE, IMPROVEMENT_STATUSES, IMPROVEMENT_SOURCES, ImprovementError, URL_RE, EMAIL_RE;
144738
145065
  var init_improvements = __esm(() => {
145066
+ init_mcp_wrapper();
145067
+ init_egress_guard();
144739
145068
  init_env_flag();
144740
145069
  init_secret_scrubber();
144741
145070
  init_db4();
@@ -145099,7 +145428,7 @@ var configEntryShape3, registerSetConfigTool = (server) => {
145099
145428
  key: string2().min(1).max(255).describe("Configuration key (e.g., 'AGENTMAIL_WEBHOOK_SECRET')."),
145100
145429
  value: string2().describe("Configuration value."),
145101
145430
  isSecret: boolean().optional().describe("If true, value is masked in API responses (default: false)."),
145102
- envPath: string2().optional().describe("Optional: file path to write the value as KEY=VALUE in a .env file."),
145431
+ envPath: string2().optional().describe("Optional: a path stored with the row as metadata. The server does not write files."),
145103
145432
  description: string2().optional().describe("Optional human-readable description of this config entry."),
145104
145433
  exportToEnv: boolean().optional().describe("Export this row into agent process env (default true on create, false for a few server-side secrets; omitted on update keeps the stored flag). Rejected as true for keys only the API server reads.")
145105
145434
  }),
@@ -145224,7 +145553,6 @@ var primitiveQueryValueSchema, registerSwarmXTool = (server) => {
145224
145553
  body: unknown().optional().describe("Optional JSON request body."),
145225
145554
  query: record2(string2(), primitiveQueryValueSchema).optional().describe("Optional query parameters appended to the Composio path."),
145226
145555
  headers: record2(string2(), string2()).optional().describe("Optional extra headers. Auth headers are injected by the server."),
145227
- baseUrl: string2().url().optional().describe("Optional Composio API base URL override."),
145228
145556
  useOrgKey: boolean().default(false).describe("Use COMPOSIO_ORG_API_KEY/x-org-api-key instead of COMPOSIO_API_KEY/x-api-key."),
145229
145557
  raw: boolean().default(false).describe("Return raw text instead of JSON-pretty output text.")
145230
145558
  }),
@@ -145242,7 +145570,6 @@ var primitiveQueryValueSchema, registerSwarmXTool = (server) => {
145242
145570
  let result;
145243
145571
  try {
145244
145572
  result = await executeComposioRequest(composioArgsFromParts({
145245
- baseUrl: input.baseUrl,
145246
145573
  body: input.body,
145247
145574
  endpoint: input.path,
145248
145575
  headers: input.headers,
@@ -145307,7 +145634,7 @@ async function priceModel(provider, usage, split, atEpochMs, lookupRate) {
145307
145634
  if (inputRate == null || outputRate == null)
145308
145635
  return null;
145309
145636
  const cacheReadRate = await lookupRate(provider, lookupModel, "cached_input", atEpochMs) ?? 0;
145310
- const uncachedInputTokens = INCLUSIVE_INPUT_PROVIDERS.has(provider) ? Math.max(0, usage.inputTokens - usage.cacheReadTokens) : usage.inputTokens;
145637
+ const uncachedInputTokens = INCLUSIVE_INPUT_PROVIDERS.has(provider) ? Math.max(0, usage.inputTokens - usage.cacheReadTokens - usage.cacheWriteTokens) : usage.inputTokens;
145311
145638
  let cacheWriteCostUnits = 0;
145312
145639
  if (split) {
145313
145640
  const fiveMinuteTokens = usage.cacheWriteTokens * split.fiveMinuteRatio;
@@ -145675,7 +146002,7 @@ async function emitBudgetRefusalSideEffects(ctx, inserted) {
145675
146002
  console.warn(`[budget-refusal-notify] Failed to create follow-up task for budget refusal (task=${ctx.task.id.slice(0, 8)}): ${err}`);
145676
146003
  }
145677
146004
  }
145678
- import("./event-bus-7gbsr0g4.js").then(({ workflowEventBus }) => {
146005
+ import("./event-bus-tvf2grf4.js").then(({ workflowEventBus }) => {
145679
146006
  workflowEventBus.emit("task.budget_refused", {
145680
146007
  taskId: ctx.task.id,
145681
146008
  agentId: ctx.agentId,
@@ -148274,4 +148601,4 @@ var init_server = __esm(() => {
148274
148601
  loggedToolAllowlistWarnings = new Set;
148275
148602
  });
148276
148603
 
148277
- export { safeParse, getObjectShape, getLiteralValue, init_zod_compat, LATEST_PROTOCOL_VERSION, DEFAULT_NEGOTIATED_PROTOCOL_VERSION, SUPPORTED_PROTOCOL_VERSIONS, isJSONRPCRequest, isJSONRPCResultResponse, ErrorCode, isJSONRPCErrorResponse, JSONRPCMessageSchema, EmptyResultSchema, isInitializeRequest, InitializeResultSchema, CreateTaskResultSchema, ListResourcesResultSchema, ListResourceTemplatesResultSchema, ReadResourceResultSchema, ResourceListChangedNotificationSchema, ListPromptsResultSchema, GetPromptResultSchema, PromptListChangedNotificationSchema, ListToolsResultSchema, CallToolResultSchema, ToolListChangedNotificationSchema, ListChangedOptionsBaseSchema, CreateMessageRequestSchema, CreateMessageResultSchema, CreateMessageResultWithToolsSchema, ElicitRequestSchema, ElicitResultSchema, CompleteResultSchema, McpError, init_types, Protocol, mergeCapabilities, init_protocol, AjvJsonSchemaValidator, init_ajv_provider, assertToolsCallTaskCapability, assertClientRequestTaskCapability, init_helpers, McpServer, init_mcp, referencedBundlePaths, skillDirs, init_manifest_format, recoverIncompleteRuns, init_recovery, handleWebhookTrigger, verifyHmacSignature, decodeStandardWebhookSecret, verifyStandardWebhookSignature, verifyTokenEquality, WebhookError, init_triggers, snapshotAndUpdateWorkflow, init_version, applyPreTaskCreate, init_apply_task_create, RawLlmConfigSchema, RawLlmOutputSchema, executeRawLlm, init_raw_llm, getExecutorRegistry2, initWorkflows2, init_workflows, isGitHubEnabled, initGitHub, verifyWebhookSignature, getWorkerInstallationToken, init_app, isReservedProviderEvent, init_event_waits, stripSiblingBlock, init_sibling_block, createTaskWithSiblingAwareness, init_sibling_awareness, hasPendingEventWait, init_deferred_task_waits, dispatchScheduleTarget, calculateNextRun2, parseSchedulerIntervalMs2, startScheduler2, stopScheduler2, runScheduleNow2, init_scheduler, ExtensionAssetConflictError, hashOf, scriptHash, liveScriptSpec, liveWorkflowSpec, skillSpecOf, liveSkillSpec, skillHash, init_assets, ExtensionOwnershipError, getExtensionFiles, getExtensionById, getExtensionByName, listExtensions, listExtensionVersions, updateExtensionMeta, listExtensionRuns, init_db, SDK_ALLOWLIST, mcpToolNameForSdkMethod, init_sdk_allowlist, MCP_OVERFLOW_NAMESPACE, mcpOverflowAuthError, init_kv_overflow, hasKvViewArgs, resolveKvView, init_kv_view, COLOR_LITERAL_THRESHOLD, countColorLiterals, init_color_literals, toolErr, createToolRegistrar, init_utils, handleMcpBridge, init_mcp_bridge, Redacted, init_redacted, SCRIPT_SDK_RESPONSE_LIMIT_BYTES, readScriptSdkJsonResponse, init_response_limit, retry, init_retry, ExtensionConfigError, init_loader, ExtensionLifecycleError, setExtensionLoopbackBaseUrl, enableExtension, disableExtension, activateVersion, ExtensionAssetsInvalidError, installExtensionWithAssets, uninstallExtension, reloadExtension, loadEnabledExtensions, stopExtensionRuntime, init_lifecycle, ExtensionAbortedError2, isRegistered2, isExtensionAgentId2, getExtensionBridgeToken2, resolveBridgeCallOrigin2, extensionIdForAgent2, runContext2, registerLoaded2, unregister2, hasNativeToolHandlers2, listRegistered2, dispatchPre2, dispatchPost2, init_dispatcher, resolveIdentity, renderIdentity, init_identity, dismissedNamespace, dismissUnmappedIdentity, restoreUnmappedIdentity, recordUnmappedIdentity, init_unmapped_identities, getDeliveredSlackMessageTs, foldIntoPendingSlackTask, init_slack_fold, MAX_TASK_ATTACHMENT_BYTES, recordTaskAttachmentUpload, scopeFromAttachment, backingProviderId, init_task_attachment_store, transcribeAudioNotes, init_transcription, init_templates, buildEffectiveText, bufferedFileFailures, fetchSlackFiles, createSlackTaskWithFiles, attachSlackFilesToDraft, notifySlackFileFailures, init_inbound_files, pendingWorkForAgent, countPoolRuntimes, computeDesired, init_demand, isRuntimePoolWakeable, isAgentReachable, isAgentOnDemand, init_reachability, isAddressedToOtherUser, broadcastMatches, routeMessage, extractTaskFromMessage, init_router, extractSlackMessageText, slackInboundMessageText, collectSlackMessageFiles, init_message_text, createAdditiveBuffer, init_additive_buffer, isAgentMailEnabled, initAgentMail, verifyAgentMailWebhook, isInboxAllowed, isSenderAllowed, handleMessageReceived, init_agentmail, isAzureDevOpsEnabled, initAzureDevOps, verifyAzureDevOpsWebhook, repointTrackerSyncBySwarmId, init_tracker, isAzureDevOpsUrl, canonicalAzureDevOpsRepoUrl, parseAzureDevOpsRepoUrl, init_azure_devops, createdPullRequestOf, commentedPayloadOf, handlePullRequestCreated, handlePullRequestCommented, handleWorkItemCreated, handleWorkItemUpdated, handleWorkItemCommented, handleWorkItemDeleted, handleWorkItemRestored, initAzureDevOpsOutbound, init_azure_devops2, enqueueAuditRow, enqueueAdmissionRow, flushAuditBuffer, startAuditWriter, stopAuditWriter, startAuditGc, stopAuditGc, init_rbac_audit, getTelemetryIngestAnchor, init_telemetry_ingest_anchor, initApiTelemetry, syncTelemetryEnabled, init_telemetry_enable, isBitbucketEnabled, initBitbucket, verifyBitbucketWebhook, isDuplicateDelivery, markDeliveryProcessed, pullRequestEventOf, pullRequestCommentEventOf, handlePullRequestCreated2, handlePullRequestCommentCreated, handlePullRequestClosed, init_bitbucket, handlePullRequest, handleIssue, handleComment, handlePullRequestReview, handleCheckRun, handleCheckSuite, handleWorkflowRun, init_github, isGitLabEnabled, initGitLab, verifyGitLabWebhook, handleMergeRequest, handleIssue2, handleNote, handlePipeline, init_gitlab, isChatSdkEnabled, getChatSdkConfig, init_config2, errorMessage, init_logger, resolveAdapterApiUrl, init_adapters, trackBackground, init_background, TelegramBotApiError, callTelegramBotApi, init_telegram_api, isTrustedTeamsServiceUrl, init_teams_origin, getSessionLabels, rememberSessionLabel, getResourceSessionLabels, init_session_labels, isChatSdkStopping, startChatSdk, getChatInstance, isChatAdapterConfigured, getChatSdkHealth, stopChatSdk, init_runtime, getJiraMetadata, updateJiraMetadata, clearJiraMetadata, init_metadata, registerJiraWebhook, deleteJiraWebhook, init_webhook_lifecycle, isJiraEnabled, initJira, init_app2, handleJiraWebhook, init_webhook, init_jira, handleAgentSessionEvent, handleIssueUpdate, handleIssueDelete, handleAgentSessionPrompted, init_sync, isLinearEnabled, initLinear, init_app3, init_linear, init_slack, verifyPageSession, LEGACY_PAGE_SESSION_COOKIE, isCookieSafePageId, extractPageSession, extractLegacyPageSession, extractAndVerifyCookie, isLocalDevPageRequest, pageSessionSetCookies, init_page_session, resolveHttpRequestAuth, init_auth, getDeploymentEnvValue2, loadGlobalConfigsIntoEnv2, reloadGlobalConfigsAndIntegrations2, scheduleIntegrationsReload2, handleCore2, init_core, runTaskUiScriptAction, init_script_actions, cancelApprovalRequest, cancelApprovalRequestAndRun, init_approval_cancel, resolveRequestPrincipal, requestPrincipal, agentFirstPrincipal, requireAuthKind, rejectGuest, init_request_principal, REBOOT_RETRY_PIN_TAG2, getPinCandidateAgent2, resolveLeadOnlyRecoveryAssignment2, getResumeGeneration2, getNextResumeGeneration2, inheritedModelSelection2, nextFallback2, createWorkerTaskFollowUp2, createResumeFollowUp2, createRerouteDecisionTask2, createPoolStarvationDecisionTask2, init_worker_follow_up, MCP_MAX_TOOL_INPUT_ELEMENTS, MCP_MAX_REQUEST_BODY_BYTES, init_mcp_limits, userCtx, init_task_tool_ctx, resolveTaskRequester, init_task_requester, handleApps, init_apps, parseScene, init_elements, MAX_OBJECT_BYTES, init_write_object, getUserCommsPrefs, init_requester_comms, getTaskDetailsInputSchema, getTaskDetailsOutputSchema, getTaskDetailsHandler, init_get_task_details, cancelTaskInputSchema, cancelTaskOutputSchema, cancelTaskHandler, init_cancel_task, DbQueryTimeoutError, DbQueryConcurrencyCapError, executeReadOnlyQuery, getDbQueryHttpBudgetMs, init_db_query_shared, assertSelectOnlyQuery, executeReadOnlyQueryGated, handleDbQuery, init_db_query, snapshotMetric, init_version2, AssetKeyAuthorizationError, authorizeAssetKeyWrite, init_asset_key_auth, getPageEditCounter, init_page_versions, DEFAULT_THEME_ID, THEME_PRESET_IDS, getThemePreset, init_presets, DesignSystemError, buildDesignSystem, init_design_system, getDesignSystem, getActiveDesignSystem, saveDesignSystem, init_design_system2, snapshotPage, init_version3, readThemeFields, init_page_fields, assertOAuthAppUrlsSafe, assertOAuthEgressUrlSafe, init_app_validation, listOAuthPresets, listOAuthPresetIds, getOAuthPreset, hydrateOAuthAppFromPreset, init_presets2, scopedResourceScopeIdSchema, resolveScopedResourceId, init_scoped_resource, MemoryKeyError, init_key_guard, refreshLinks, init_link_resolver, indexMemoryContent, init_index_content, dedupeMemoryDocumentIds, recordMemoryAccesses, recordRetrievals, init_retrieval, ExplicitSelfDuplicateError, applyRating, init_store, shouldPersistAutomaticTaskMemory, init_automatic_task_gate, guardTerminalTaskResultWrite, init_terminal_result_guard, scriptNameSchema, scriptToolOutputSchema, scriptsApiToolResult, init_script_common, getTasksInputSchema, getTasksOutputSchema, getTasksHandler, init_get_tasks, requiresLeadToWrite, reservedNamespaceError, privateNamespaceError, reservedRoomKeyError, init_kv_reserved_namespaces, updateMcpServerChecked, init_mcp_server_checked_update, updateTouchesStdioExecution, init_mcp_server_stdio_gate, canReadMemory, init_access, getLinksForMemory, init_links_store, attachDemotionEvidence, init_demotion_evidence, expandCandidatesWithGraph, init_graph_expansion, isApiDraining, drainApi, init_api_drain, markKapsoMessageRead, sendKapsoReaction, init_client, getKapsoConfig, getKapsoNumberMapping, markKapsoMessageSeen, init_config3, changesMergePolicy, init_repo_merge_policy, updateSwarmRepoChecked, init_repo_checked_update, getCombConfig, init_config4, resolveRoomNamespace, roomRequestInfo, authorizeRoomNamespace, sessionAccessTopic, sessionPresenceRoot, init_auth2, RoomOperationSchema, init_document, removeAwarenessStates, init_awareness, roomTopic, decodeRoomSnapshot, roomView, getRoom, changeRoom, applyRoomUpdate, resetRoom, sweepRooms, closeRooms, removeNamespaceRooms, init_rooms, init_scheduler2, MEMORY_KEYS_DEFAULT_PREFIX, MEMORY_KEYS_MAX_LIMIT, estimateTokens, posteriorMean, listMemoryKeys, checkChunkIntegrity, getMemoryChunks, getPosteriorsByIds, init_key_browser, createEvent, createEventsBatch, getEventCountsFiltered, getEventsFiltered, init_events, mergeScheduleTiming, validateRecurringTiming, changesScheduleTarget, init_validate, renderTypeBlobs, init_script_query_types, renderRunOutput, init_script_run, renderSearchResults, searchSuccessMessage, init_script_search, followUpThreadForSourceTask, evaluateFollowUpRedelegation, init_follow_up_redelegation_guard, checkOutputSchemaShape, sendTaskOutputSchema, sendTaskHandler, init_send_task, setSheetRange, appendSheetRows, clearSheetRange, init_service, steerTaskUserInputSchema, steerTaskOutputSchema, steerTaskHandler, init_steer_task, skipReasonFrom, finalizeSkippedTaskReaction, init_task_skip, IMPROVEMENT_TEXT_MAX, IMPROVEMENT_STATUSES, IMPROVEMENT_SOURCES, ImprovementError, isImprovementsEnabled, getImprovement, listImprovements, createImprovement, approveAndSend, discardImprovement, improvementLeakHints, init_improvements, recomputeSessionCost, init_session_cost_recompute, canClaim, init_budget_admission, emitBudgetRefusalSideEffects, init_budget_refusal_notify, workflowModelErrors, init_model_validation, patchWorkflowDefinition, init_patch_definition, idempotencyKeyHeader, readIdempotencyKey, replayAcceptedOperation, init_idempotency_key, resolveScriptsOnlyMode, init_scripts_only_mode, ALL_CAPABILITIES, hasCapability, getEnabledCapabilities, createServer, init_server };
148604
+ export { safeParse, getObjectShape, getLiteralValue, init_zod_compat, LATEST_PROTOCOL_VERSION, DEFAULT_NEGOTIATED_PROTOCOL_VERSION, SUPPORTED_PROTOCOL_VERSIONS, isJSONRPCRequest, isJSONRPCResultResponse, ErrorCode, isJSONRPCErrorResponse, JSONRPCMessageSchema, EmptyResultSchema, isInitializeRequest, InitializeResultSchema, CreateTaskResultSchema, ListResourcesResultSchema, ListResourceTemplatesResultSchema, ReadResourceResultSchema, ResourceListChangedNotificationSchema, ListPromptsResultSchema, GetPromptResultSchema, PromptListChangedNotificationSchema, ListToolsResultSchema, CallToolResultSchema, ToolListChangedNotificationSchema, ListChangedOptionsBaseSchema, CreateMessageRequestSchema, CreateMessageResultSchema, CreateMessageResultWithToolsSchema, ElicitRequestSchema, ElicitResultSchema, CompleteResultSchema, McpError, init_types, Protocol, mergeCapabilities, init_protocol, AjvJsonSchemaValidator, init_ajv_provider, assertToolsCallTaskCapability, assertClientRequestTaskCapability, init_helpers, McpServer, init_mcp, referencedBundlePaths, skillDirs, init_manifest_format, recoverIncompleteRuns, init_recovery, handleWebhookTrigger, verifyHmacSignature, decodeStandardWebhookSecret, verifyStandardWebhookSignature, verifyTokenEquality, WebhookError, init_triggers, snapshotAndUpdateWorkflow, init_version, applyPreTaskCreate, init_apply_task_create, RawLlmConfigSchema, RawLlmOutputSchema, executeRawLlm, init_raw_llm, getExecutorRegistry2, initWorkflows2, init_workflows, isGitHubEnabled, initGitHub, verifyWebhookSignature, getWorkerInstallationToken, init_app, isReservedProviderEvent, init_event_waits, stripSiblingBlock, init_sibling_block, prepareTaskWithSiblingAwareness, createTaskWithSiblingAwareness, init_sibling_awareness, hasPendingEventWait, init_deferred_task_waits, dispatchScheduleTarget, calculateNextRun2, parseSchedulerIntervalMs2, startScheduler2, stopScheduler2, runScheduleNow2, init_scheduler, ExtensionAssetConflictError, hashOf, scriptHash, liveScriptSpec, liveWorkflowSpec, skillSpecOf, liveSkillSpec, skillHash, init_assets, ExtensionOwnershipError, getExtensionFiles, getExtensionById, getExtensionByName, listExtensions, listExtensionVersions, updateExtensionMeta, listExtensionRuns, init_db, SDK_ALLOWLIST, mcpToolNameForSdkMethod, init_sdk_allowlist, MCP_OVERFLOW_NAMESPACE, mcpOverflowAuthError, init_kv_overflow, hasKvViewArgs, resolveKvView, init_kv_view, COLOR_LITERAL_THRESHOLD, countColorLiterals, init_color_literals, toolErr, createToolRegistrar, init_utils, handleMcpBridge, init_mcp_bridge, Redacted, init_redacted, SCRIPT_SDK_RESPONSE_LIMIT_BYTES, readScriptSdkJsonResponse, init_response_limit, retry, init_retry, ExtensionConfigError, init_loader, ExtensionLifecycleError, setExtensionLoopbackBaseUrl, enableExtension, disableExtension, activateVersion, ExtensionAssetsInvalidError, installExtensionWithAssets, uninstallExtension, reloadExtension, loadEnabledExtensions, stopExtensionRuntime, init_lifecycle, ExtensionAbortedError2, isRegistered2, isExtensionAgentId2, getExtensionBridgeToken2, resolveBridgeCallOrigin2, extensionIdForAgent2, runContext2, registerLoaded2, unregister2, hasNativeToolHandlers2, listRegistered2, dispatchPre2, dispatchPost2, init_dispatcher, resolveIdentity, renderIdentity, init_identity, dismissedNamespace, dismissUnmappedIdentity, restoreUnmappedIdentity, recordUnmappedIdentity, init_unmapped_identities, getDeliveredSlackMessageTs, foldIntoPendingSlackTask, init_slack_fold, MAX_TASK_ATTACHMENT_BYTES, recordTaskAttachmentUpload, scopeFromAttachment, backingProviderId, init_task_attachment_store, transcribeAudioNotes, init_transcription, init_templates, buildEffectiveText, bufferedFileFailures, fetchSlackFiles, createSlackTaskWithFiles, attachSlackFilesToDraft, notifySlackFileFailures, init_inbound_files, pendingWorkForAgent, countPoolRuntimes, computeDesired, init_demand, isRuntimePoolWakeable, isAgentReachable, isAgentOnDemand, init_reachability, isAddressedToOtherUser, broadcastMatches, routeMessage, extractTaskFromMessage, init_router, extractSlackMessageText, slackInboundMessageText, collectSlackMessageFiles, init_message_text, createAdditiveBuffer, init_additive_buffer, isAgentMailEnabled, initAgentMail, verifyAgentMailWebhook, isInboxAllowed, isSenderAllowed, handleMessageReceived, init_agentmail, isAzureDevOpsEnabled, initAzureDevOps, verifyAzureDevOpsWebhook, repointTrackerSyncBySwarmId, init_tracker, isAzureDevOpsUrl, canonicalAzureDevOpsRepoUrl, parseAzureDevOpsRepoUrl, init_azure_devops, createdPullRequestOf, commentedPayloadOf, handlePullRequestCreated, handlePullRequestCommented, handleWorkItemCreated, handleWorkItemUpdated, handleWorkItemCommented, handleWorkItemDeleted, handleWorkItemRestored, initAzureDevOpsOutbound, init_azure_devops2, enqueueAuditRow, enqueueAdmissionRow, flushAuditBuffer, startAuditWriter, stopAuditWriter, startAuditGc, stopAuditGc, init_rbac_audit, getTelemetryIngestAnchor, init_telemetry_ingest_anchor, initApiTelemetry, syncTelemetryEnabled, init_telemetry_enable, isBitbucketEnabled, initBitbucket, verifyBitbucketWebhook, isDuplicateDelivery, markDeliveryProcessed, pullRequestEventOf, pullRequestCommentEventOf, handlePullRequestCreated2, handlePullRequestCommentCreated, handlePullRequestClosed, init_bitbucket, handlePullRequest, handleIssue, handleComment, handlePullRequestReview, handleCheckRun, handleCheckSuite, handleWorkflowRun, init_github, isGitLabEnabled, initGitLab, verifyGitLabWebhook, handleMergeRequest, handleIssue2, handleNote, handlePipeline, init_gitlab, isChatSdkEnabled, getChatSdkConfig, init_config2, errorMessage, init_logger, resolveAdapterApiUrl, init_adapters, trackBackground, init_background, TelegramBotApiError, callTelegramBotApi, init_telegram_api, isTrustedTeamsServiceUrl, init_teams_origin, getSessionLabels, rememberSessionLabel, getResourceSessionLabels, init_session_labels, isChatSdkStopping, startChatSdk, getChatInstance, isChatAdapterConfigured, getChatSdkHealth, stopChatSdk, init_runtime, getJiraMetadata, updateJiraMetadata, clearJiraMetadata, init_metadata, registerJiraWebhook, deleteJiraWebhook, init_webhook_lifecycle, isJiraEnabled, initJira, init_app2, handleJiraWebhook, init_webhook, init_jira, handleAgentSessionEvent, handleIssueUpdate, handleIssueDelete, handleAgentSessionPrompted, init_sync, isLinearEnabled, initLinear, init_app3, init_linear, init_slack, verifyPageSession, LEGACY_PAGE_SESSION_COOKIE, isCookieSafePageId, extractPageSession, extractLegacyPageSession, extractAndVerifyCookie, isLocalDevPageRequest, pageSessionSetCookies, init_page_session, resolveHttpRequestAuth, init_auth, getDeploymentEnvValue2, loadGlobalConfigsIntoEnv2, reloadGlobalConfigsAndIntegrations2, scheduleIntegrationsReload2, handleCore2, init_core, runTaskUiScriptAction, init_script_actions, cancelApprovalRequest, cancelApprovalRequestAndRun, init_approval_cancel, resolveRequestPrincipal, requestPrincipal, agentFirstPrincipal, requireAuthKind, rejectGuest, refuseAgentTokenWithout, init_request_principal, REBOOT_RETRY_PIN_TAG2, getPinCandidateAgent2, resolveLeadOnlyRecoveryAssignment2, getResumeGeneration2, getNextResumeGeneration2, inheritedModelSelection2, nextFallback2, createWorkerTaskFollowUp2, createResumeFollowUp2, createRerouteDecisionTask2, createPoolStarvationDecisionTask2, init_worker_follow_up, MCP_MAX_TOOL_INPUT_ELEMENTS, MCP_MAX_REQUEST_BODY_BYTES, init_mcp_limits, userCtx, init_task_tool_ctx, resolveTaskRequester, init_task_requester, handleApps, init_apps, parseScene, init_elements, MAX_OBJECT_BYTES, init_write_object, getUserCommsPrefs, init_requester_comms, getTaskDetailsInputSchema, getTaskDetailsOutputSchema, getTaskDetailsHandler, init_get_task_details, cancelTaskInputSchema, cancelTaskOutputSchema, cancelTaskHandler, init_cancel_task, DbQueryTimeoutError, DbQueryConcurrencyCapError, executeReadOnlyQuery, getDbQueryHttpBudgetMs, init_db_query_shared, assertSelectOnlyQuery, executeReadOnlyQueryGated, handleDbQuery, init_db_query, snapshotMetric, init_version2, AssetKeyAuthorizationError, authorizeAssetKeyWrite, init_asset_key_auth, getPageEditCounter, init_page_versions, DEFAULT_THEME_ID, THEME_PRESET_IDS, getThemePreset, init_presets, DesignSystemError, buildDesignSystem, init_design_system, getDesignSystem, getActiveDesignSystem, saveDesignSystem, init_design_system2, snapshotPage, init_version3, readThemeFields, init_page_fields, assertOAuthAppUrlsSafe, assertOAuthEgressUrlSafe, init_app_validation, listOAuthPresets, listOAuthPresetIds, getOAuthPreset, hydrateOAuthAppFromPreset, init_presets2, scopedResourceScopeIdSchema, resolveScopedResourceId, init_scoped_resource, MemoryKeyError, init_key_guard, refreshLinks, init_link_resolver, indexMemoryContent, init_index_content, dedupeMemoryDocumentIds, recordMemoryAccesses, recordRetrievals, init_retrieval, ExplicitSelfDuplicateError, applyRating, init_store, shouldPersistAutomaticTaskMemory, init_automatic_task_gate, guardTerminalTaskResultWrite, init_terminal_result_guard, scriptNameSchema, scriptToolOutputSchema, scriptsApiToolResult, init_script_common, getTasksInputSchema, getTasksOutputSchema, getTasksHandler, init_get_tasks, requiresLeadToWrite, reservedNamespaceError, privateNamespaceError, reservedRoomKeyError, scrubReservedRead, init_kv_reserved_namespaces, MAX_KV_BODY_BYTES, init_kv_limits, updateMcpServerChecked, init_mcp_server_checked_update, updateTouchesStdioExecution, init_mcp_server_stdio_gate, canReadMemory, init_access, getLinksForMemory, init_links_store, attachDemotionEvidence, init_demotion_evidence, expandCandidatesWithGraph, init_graph_expansion, isApiDraining, drainApi, init_api_drain, markKapsoMessageRead, sendKapsoReaction, init_client, getKapsoConfig, getKapsoNumberMapping, markKapsoMessageSeen, init_config3, changesMergePolicy, init_repo_merge_policy, execConfigRefusal, updateSwarmRepoChecked, init_repo_checked_update, getCombConfig, init_config4, resolveRoomNamespace, roomRequestInfo, authorizeRoomNamespace, sessionAccessTopic, sessionPresenceRoot, init_auth2, RoomOperationSchema, init_document, removeAwarenessStates, init_awareness, roomTopic, decodeRoomSnapshot, roomView, getRoom, changeRoom, applyRoomUpdate, resetRoom, sweepRooms, closeRooms, removeNamespaceRooms, init_rooms, init_scheduler2, MEMORY_KEYS_DEFAULT_PREFIX, MEMORY_KEYS_MAX_LIMIT, estimateTokens, posteriorMean, listMemoryKeys, checkChunkIntegrity, getMemoryChunks, getPosteriorsByIds, init_key_browser, createEvent, createEventsBatch, getEventCountsFiltered, getEventsFiltered, init_events, mergeScheduleTiming, validateRecurringTiming, changesScheduleTarget, init_validate, renderTypeBlobs, init_script_query_types, renderRunOutput, init_script_run, renderSearchResults, searchSuccessMessage, init_script_search, followUpThreadForSourceTask, evaluateFollowUpRedelegation, init_follow_up_redelegation_guard, checkOutputSchemaShape, sendTaskOutputSchema, sendTaskHandler, init_send_task, setSheetRange, appendSheetRows, clearSheetRange, init_service, steerTaskUserInputSchema, steerTaskOutputSchema, steerTaskHandler, init_steer_task, skipReasonFrom, finalizeSkippedTaskReaction, init_task_skip, IMPROVEMENT_TEXT_MAX, IMPROVEMENT_STATUSES, IMPROVEMENT_SOURCES, ImprovementError, isImprovementsEnabled, getImprovement, listImprovements, createImprovement, approveAndSend, discardImprovement, improvementLeakHints, init_improvements, recomputeSessionCost, init_session_cost_recompute, canClaim, init_budget_admission, emitBudgetRefusalSideEffects, init_budget_refusal_notify, workflowModelErrors, init_model_validation, patchWorkflowDefinition, init_patch_definition, IDEMPOTENT_REPLAYED_HEADER, idempotencyKeyHeader, readIdempotencyKey, replayAcceptedOperation, init_idempotency_key, resolveScriptsOnlyMode, init_scripts_only_mode, ALL_CAPABILITIES, hasCapability, getEnabledCapabilities, createServer, init_server };