@desplega.ai/agent-swarm 2.12.0 → 2.13.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (417) hide show
  1. package/dist/acp-adapter-xtj40wd8.js +17 -0
  2. package/dist/{acp-targets-311gcyvw.js → acp-targets-n7vm5atw.js} +10 -9
  3. package/dist/{actions-c4chgxp6.js → actions-hq6wp9xv.js} +28 -27
  4. package/dist/{agent-fs-provision-0b9awm5n.js → agent-fs-provision-y0qc1rdd.js} +4 -4
  5. package/dist/{amp-adapter-r0veq6x5.js → amp-adapter-1qqs6h91.js} +3 -3
  6. package/dist/{app-hn5fftf5.js → app-7m4z44rv.js} +10 -8
  7. package/dist/{approval-notifications-3g6yc8nv.js → approval-notifications-8sr41gjx.js} +11 -10
  8. package/dist/{assistant-cpjgpjvp.js → assistant-hkczwfv6.js} +29 -28
  9. package/dist/{boot-args-schema-hce1av1h.js → boot-args-schema-8025snev.js} +1 -1
  10. package/dist/{boot-reembed-bztbxc4z.js → boot-reembed-15m87nr1.js} +5 -2
  11. package/dist/{boot-reembed-d7xcym0j.js → boot-reembed-4bbpxjh1.js} +1 -1
  12. package/dist/{boot-scrub-sweep-mkmm16gk.js → boot-scrub-sweep-eajr97e9.js} +2 -2
  13. package/dist/{boot-seeds-arrkbe8t.js → boot-seeds-9cwy39jx.js} +4 -4
  14. package/dist/{boxd-68n75y1s.js → boxd-hr8rsxzq.js} +1 -1
  15. package/dist/{claude-adapter-ykpyr5p8.js → claude-adapter-g61wa4rt.js} +9 -8
  16. package/dist/{claude-managed-adapter-ssg6z4bt.js → claude-managed-adapter-znkk0prm.js} +4 -4
  17. package/dist/{claude-managed-setup-trd59v7b.js → claude-managed-setup-f1wndkr2.js} +7 -7
  18. package/dist/{claude-sdk-session-yjcze0j1.js → claude-sdk-session-687xzf21.js} +20763 -19380
  19. package/dist/{cli-ya3kf4gs.js → cli-04103ryh.js} +1 -1
  20. package/dist/{cli-55tc8cj4.js → cli-0a336ze7.js} +5 -5
  21. package/dist/{cli-q8tc22bj.js → cli-0fx95c06.js} +5 -5
  22. package/dist/{cli-mq2fbgva.js → cli-0m77n7ej.js} +3 -3
  23. package/dist/{cli-7yn42w6m.js → cli-0xwb7zpt.js} +2 -2
  24. package/dist/{cli-mcymtvwn.js → cli-13t0smbk.js} +1000 -28
  25. package/dist/{cli-c7j31hq9.js → cli-1b5axkt1.js} +4 -4
  26. package/dist/{cli-yegz2g06.js → cli-1carhg8g.js} +4 -4
  27. package/dist/{cli-j5gtytvg.js → cli-1dr5at77.js} +15 -12
  28. package/dist/cli-2v4xxnx2.js +148 -0
  29. package/dist/{cli-sv2r3bw8.js → cli-32xndx6b.js} +7 -7
  30. package/dist/{cli-h70a2mxy.js → cli-3m8vqehw.js} +53 -13
  31. package/dist/{cli-ercwc8xn.js → cli-3mf04tkh.js} +1 -1
  32. package/dist/{cli-52nfye5j.js → cli-3zyme1wt.js} +24 -16
  33. package/dist/{cli-s6zk31gr.js → cli-43dsqhcp.js} +4 -4
  34. package/dist/{cli-b93d81yg.js → cli-4h90xaet.js} +2 -2
  35. package/dist/{cli-5tg94mdw.js → cli-4mj5g29m.js} +9 -12
  36. package/dist/{cli-47hz21se.js → cli-4tbvndmm.js} +4 -5
  37. package/dist/{cli-r0mz92by.js → cli-50whymxq.js} +2 -2
  38. package/dist/{cli-js10kdk7.js → cli-5basv0e7.js} +19 -5
  39. package/dist/{cli-krbcr00p.js → cli-5v6b2am8.js} +59 -5
  40. package/dist/{cli-en6dmkxd.js → cli-6r1dwegd.js} +3 -3
  41. package/dist/{cli-9qe5y107.js → cli-7ewre3dm.js} +15 -6
  42. package/dist/{cli-n3qe7tyr.js → cli-84xtgbn6.js} +35 -2
  43. package/dist/{cli-xm34qj8m.js → cli-8cmjkbvj.js} +2 -2
  44. package/dist/{cli-2m6yaq6b.js → cli-8fj8yfmk.js} +1 -1
  45. package/dist/{cli-nja15knq.js → cli-8rbkw18r.js} +3 -3
  46. package/dist/{cli-x05p2d05.js → cli-9tevdxyf.js} +1 -1
  47. package/dist/{cli-hhc47ack.js → cli-9xx36trj.js} +4 -4
  48. package/dist/{cli-39qm0rtm.js → cli-a8ts6x1n.js} +29 -150
  49. package/dist/{cli-bp6k9acz.js → cli-aebswqmz.js} +18 -18
  50. package/dist/{cli-ex1y88j3.js → cli-at67kvnp.js} +1 -1
  51. package/dist/{cli-q2dywc8h.js → cli-bjmq14k9.js} +4 -4
  52. package/dist/{cli-v9ya390t.js → cli-byxsctca.js} +12 -12
  53. package/dist/{cli-bz97ff9n.js → cli-c0tyzt73.js} +152 -12
  54. package/dist/{cli-fyaq4zdv.js → cli-c8kqmzzf.js} +9 -9
  55. package/dist/{cli-t75xngj1.js → cli-cd9acnvd.js} +12 -12
  56. package/dist/{cli-eqq0hwvx.js → cli-cmgdptmx.js} +3 -3
  57. package/dist/{cli-r14ac1y0.js → cli-cn6fpa1p.js} +1 -1
  58. package/dist/{cli-0k1a0sde.js → cli-cp0m07wb.js} +10 -10
  59. package/dist/{cli-3p288654.js → cli-cpkxh68d.js} +2 -2
  60. package/dist/{cli-fxd1mwtr.js → cli-cqxwjb93.js} +2 -2
  61. package/dist/{cli-8hp56wat.js → cli-d2epqm0y.js} +1 -1
  62. package/dist/{cli-73q4g5nx.js → cli-dd57p1gd.js} +21 -21
  63. package/dist/{cli-5z0g0e8v.js → cli-f8rcvf2x.js} +49 -13
  64. package/dist/{cli-wvjqaqcp.js → cli-fn8aj7gb.js} +1330 -249
  65. package/dist/{cli-bpje8n65.js → cli-fp65jdp2.js} +31 -6
  66. package/dist/{cli-0pp1yjg2.js → cli-gedf48yw.js} +11 -11
  67. package/dist/{cli-m5qtmrbc.js → cli-gq6qhmrr.js} +2 -2
  68. package/dist/{cli-5x03v6en.js → cli-grcc2h2g.js} +8 -8
  69. package/dist/{cli-01tvvtad.js → cli-h03j6je3.js} +4 -4
  70. package/dist/{cli-mbwmqb5w.js → cli-h0ewec3d.js} +1 -1
  71. package/dist/{cli-12vek61e.js → cli-h9bejmkf.js} +535 -146
  72. package/dist/{cli-gfy6hbd9.js → cli-hs3mqswp.js} +18 -11
  73. package/dist/{cli-tdk7jtka.js → cli-hv3820ez.js} +1 -1
  74. package/dist/{cli-pqfecppn.js → cli-je587f74.js} +1 -1
  75. package/dist/{cli-cjqyse9q.js → cli-jhtvt7gn.js} +3 -3
  76. package/dist/{cli-dkvtfgn4.js → cli-mmw2sjaf.js} +76 -17
  77. package/dist/{cli-2z2c4k6q.js → cli-mwxez0pz.js} +22 -0
  78. package/dist/{cli-yfpc6qy9.js → cli-nk8swfpx.js} +47 -16
  79. package/dist/{cli-eq4kew31.js → cli-p7g7wd9n.js} +26 -13
  80. package/dist/{cli-bhgrhedp.js → cli-q8aq48v1.js} +1 -1
  81. package/dist/{cli-dd2k2mcd.js → cli-qn79645p.js} +1 -1
  82. package/dist/{cli-ma9ys8rt.js → cli-qx1dwrr5.js} +7 -4
  83. package/dist/{cli-tm60vtax.js → cli-rfejbpe1.js} +1 -1
  84. package/dist/{cli-agjbj5x0.js → cli-s6fhqbz1.js} +38 -20
  85. package/dist/{cli-kwr5qv5g.js → cli-sfajkbd7.js} +2 -2
  86. package/dist/{cli-9y4tgrkf.js → cli-skd2c4ej.js} +2 -1
  87. package/dist/{cli-e8n0hdzd.js → cli-snypfjgj.js} +1 -1
  88. package/dist/{cli-n8f0fs3c.js → cli-t25rq8mg.js} +11 -11
  89. package/dist/{cli-72yms3ey.js → cli-t90k0phh.js} +201 -21
  90. package/dist/{cli-xf4z5bdn.js → cli-tzzas8rb.js} +4 -4
  91. package/dist/{cli-rtmqzat7.js → cli-vdfngx2g.js} +2 -2
  92. package/dist/{cli-9w8712tq.js → cli-vr4eyq6p.js} +43 -14
  93. package/dist/{cli-z4f346g5.js → cli-vx9acp12.js} +1 -1
  94. package/dist/{cli-2amwhyv2.js → cli-w24f3j49.js} +13 -11
  95. package/dist/cli-w41bvvms.js +148 -0
  96. package/dist/{cli-04zc3f7b.js → cli-w6c6dj91.js} +1 -1
  97. package/dist/{cli-fy4gb74g.js → cli-x5yb8zc8.js} +2 -2
  98. package/dist/{cli-2tw284hj.js → cli-xhkek467.js} +3 -3
  99. package/dist/{cli-5r95eqbh.js → cli-y260hgep.js} +1 -1
  100. package/dist/{cli-hbvgzjq4.js → cli-y6qqbpwc.js} +3 -3
  101. package/dist/{cli-7wy8gbwb.js → cli-ya1cj689.js} +1 -1
  102. package/dist/{cli-1htmtqc2.js → cli-yeh3g1q6.js} +620 -95
  103. package/dist/{cli-0vcqcwfn.js → cli-yfvhvw8m.js} +2 -0
  104. package/dist/{cli-k5jx8jya.js → cli-z6m6xzxt.js} +2 -2
  105. package/dist/{cli-pe3yxedk.js → cli-zaate0rd.js} +3 -3
  106. package/dist/{cli-n85m2wkq.js → cli-zkbz8m2q.js} +3 -2
  107. package/dist/{cli-e3ahxq5y.js → cli-zvpkrgsc.js} +6 -6
  108. package/dist/cli.js +30 -28
  109. package/dist/{codex-adapter-wc6e4wct.js → codex-adapter-ysfg6ty3.js} +8 -8
  110. package/dist/{codex-hook-aqtj17yr.js → codex-hook-c0nvm30r.js} +73 -2
  111. package/dist/{codex-login-1ven7yje.js → codex-login-ven5cz5j.js} +1 -1
  112. package/dist/{codex-session-runner-ppfgjd97.js → codex-session-runner-823scr6g.js} +9 -9
  113. package/dist/{commands-tsv2vx5b.js → commands-5rbm07fz.js} +3 -3
  114. package/dist/{controller-ye4sdwsy.js → controller-wn3vd217.js} +4 -4
  115. package/dist/{controllers-connect-zn4dg69h.js → controllers-connect-34jzhfft.js} +29 -28
  116. package/dist/core-kdehq26g.js +42 -0
  117. package/dist/{cursor-adapter-q2g9vwts.js → cursor-adapter-w1681kp1.js} +2 -2
  118. package/dist/{db-g111qn9j.js → db-6bkgbfwk.js} +3 -3
  119. package/dist/{db-3r1fyr2n.js → db-hcj16x7z.js} +4 -2
  120. package/dist/{devin-adapter-t8d86q9x.js → devin-adapter-fs90ab4v.js} +1 -1
  121. package/dist/{dispatcher-4q8s0mx8.js → dispatcher-jgjqrfzv.js} +28 -25
  122. package/dist/{docker-1b41eysj.js → docker-1h33jvh9.js} +2 -2
  123. package/dist/{dsh-adapter-mmcw1z5s.js → dsh-adapter-g9yqv09y.js} +2 -2
  124. package/dist/{e2b-xm60c8ad.js → e2b-jnk0yeva.js} +2 -2
  125. package/dist/{e2b-ew8c5j5v.js → e2b-y7e5kmzf.js} +2 -2
  126. package/dist/{easter-egg-3d-04ke6hcp.js → easter-egg-3d-w17nsny6.js} +1 -1
  127. package/dist/{embedding-space-kcdn52vz.js → embedding-space-v06fwy7b.js} +6 -6
  128. package/dist/{embeddings-jnzcd91a.js → embeddings-g50dxea4.js} +1 -1
  129. package/dist/{event-bus-v4ywhc2p.js → event-bus-08t2b4y2.js} +1 -1
  130. package/dist/{execute-74amghty.js → execute-1n36haw1.js} +1 -1
  131. package/dist/{external-channel-v9zgxnxz.js → external-channel-43tv8pg6.js} +2 -2
  132. package/dist/fx-adapter-bvh05t4a.js +20 -0
  133. package/dist/grok-adapter-my5j8mdf.js +20 -0
  134. package/dist/handlers-wyymeeqh.js +41 -0
  135. package/dist/heartbeat-sf3nk937.js +50 -0
  136. package/dist/{hook-p5reemds.js → hook-dqph1e05.js} +77 -18
  137. package/dist/{hook-k1h73zd7.js → hook-m1m9dm6w.js} +6 -5
  138. package/dist/{http-ms1z5xxy.js → http-w0th1cz9.js} +888 -226
  139. package/dist/index-22khdtby.js +44 -0
  140. package/dist/{index-76zzxtzf.js → index-c0e8en64.js} +1 -1
  141. package/dist/{index-620y7jzq.js → index-e8pz8qdg.js} +3 -3
  142. package/dist/{index-8p0j4h4j.js → index-ez823q84.js} +94 -89
  143. package/dist/{index-fbkqhvvj.js → index-ffba0z8q.js} +217 -165
  144. package/dist/{index-gjn6qfgn.js → index-gkpfgpg7.js} +1 -1
  145. package/dist/{index-4k7m5dgj.js → index-k8ajc0g0.js} +143 -103
  146. package/dist/index-np0582ac.js +40 -0
  147. package/dist/{index-kn63q1gr.js → index-pb03vans.js} +33 -32
  148. package/dist/index-vgkrj1jt.js +39 -0
  149. package/dist/{index-pe3d8jfy.js → index-whysn1wf.js} +1 -1
  150. package/dist/{index-0h6qd4p1.js → index-y4vd4mhn.js} +3 -4
  151. package/dist/{k8s-fy8hbhkg.js → k8s-8326q0rq.js} +2 -2
  152. package/dist/{keepalive-031js8jz.js → keepalive-2v06q2e8.js} +5 -4
  153. package/dist/lead-55z813ng.js +79 -0
  154. package/dist/{maintenance-sq9v3qx9.js → maintenance-vx7vjhhy.js} +1 -1
  155. package/dist/{oauth-refresh-sweep-zqmnyvs8.js → oauth-refresh-sweep-g06k4bza.js} +4 -3
  156. package/dist/{object-webhooks-r24wwb5y.js → object-webhooks-3dzdq4fm.js} +7 -7
  157. package/dist/{onboard-p25yhh7t.js → onboard-232pazny.js} +4 -4
  158. package/dist/{opencode-adapter-wcjc4zdk.js → opencode-adapter-t0paqbh8.js} +8 -7
  159. package/dist/{otel-impl-ff1gf20m.js → otel-impl-kmpkyp4y.js} +2 -2
  160. package/dist/{pending-hxj5yatb.js → pending-x0z3vx1x.js} +27 -26
  161. package/dist/{pi-mono-adapter-vkp4zz7p.js → pi-mono-adapter-7pmypn6d.js} +93 -22
  162. package/dist/{pricing-refresh-9w7gx41w.js → pricing-refresh-ytjmtyd7.js} +2 -2
  163. package/dist/{rbac-roles-84aw10nz.js → rbac-roles-fgm5mxr2.js} +3 -3
  164. package/dist/{rbac-roles-hz74vckp.js → rbac-roles-xyaxekh3.js} +7 -4
  165. package/dist/{registry-eeyx1201.js → registry-zv0zvxsx.js} +1 -1
  166. package/dist/{render-v2-nrdkg9gf.js → render-v2-ws972g4r.js} +12 -8
  167. package/dist/{resume-s6ey36rh.js → resume-m6mjzhkp.js} +13 -12
  168. package/dist/{runtime-x0b4pyam.js → runtime-zzpc0c8a.js} +1 -1
  169. package/dist/{session-access-xv49tk14.js → session-access-vp35xs91.js} +5 -4
  170. package/dist/{session-source-backfill-r5j988ah.js → session-source-backfill-p73e8zbe.js} +3 -3
  171. package/dist/{setup-mj0krk1p.js → setup-r4kd7rxg.js} +1 -1
  172. package/dist/thread-buffer-cm2nzq6t.js +42 -0
  173. package/dist/{tree-visibility-cbrsfaar.js → tree-visibility-07h2tbs2.js} +2 -2
  174. package/dist/{user-merge-jobs-f9d8nwnw.js → user-merge-jobs-96vg9rpe.js} +3 -3
  175. package/dist/{virtual-modules-ns0ryw05.js → virtual-modules-vgn3f2x4.js} +3 -3
  176. package/dist/{work-objects-pydhzast.js → work-objects-74hbcx3e.js} +31 -29
  177. package/dist/worker-5pn2vzx6.js +79 -0
  178. package/dist/{worker-follow-up-9z2xec5e.js → worker-follow-up-ezavwn5d.js} +26 -25
  179. package/dist/{x-3dtaf2r9.js → x-asbrnafg.js} +2 -2
  180. package/dist/xlsx-9acfmxr1.js +31534 -0
  181. package/openapi.json +2816 -1464
  182. package/package.json +13 -11
  183. package/src/agentmail/handlers.ts +26 -19
  184. package/src/apps/catalog.generated.json +757 -0
  185. package/src/apps/definition.ts +24 -7
  186. package/src/apps/page-validator.ts +225 -3
  187. package/src/apps/row-store.ts +37 -14
  188. package/src/azure-devops/handlers.ts +2 -0
  189. package/src/be/audit-user.ts +46 -6
  190. package/src/be/db/kv-windows.ts +22 -0
  191. package/src/be/db/session-moves.ts +3 -3
  192. package/src/be/db/session-tree.ts +52 -5
  193. package/src/be/db/skill-audit.ts +17 -0
  194. package/src/be/db/tasks/write.ts +18 -3
  195. package/src/be/db.ts +152 -33
  196. package/src/be/extensions/assets.ts +11 -7
  197. package/src/be/mcp-proxy.ts +5 -4
  198. package/src/be/memory/demotion-evidence.ts +2 -2
  199. package/src/be/memory/providers/sqlite-store.ts +151 -18
  200. package/src/be/memory/search-read-worker.ts +60 -0
  201. package/src/be/memory/search-reader.ts +223 -0
  202. package/src/be/migrations/337_favorites_session_hidden_key.sql +39 -0
  203. package/src/be/migrations/338_audit_agent_columns.sql +30 -0
  204. package/src/be/migrations/339_deferred_event_waits.sql +26 -0
  205. package/src/be/migrations/340_api_key_spend_cap.sql +5 -0
  206. package/src/be/model-tier-resolution.ts +18 -1
  207. package/src/be/multi-runtime.ts +17 -0
  208. package/src/be/primitives/object-embed.ts +250 -0
  209. package/src/be/primitives/objects.ts +29 -9
  210. package/src/be/primitives/sheets/service.ts +138 -6
  211. package/src/be/primitives/sheets/xlsx.ts +367 -0
  212. package/src/be/rbac-roles.ts +3 -0
  213. package/src/be/repo-checked-update.ts +4 -4
  214. package/src/be/repo-merge-policy.ts +26 -9
  215. package/src/be/schedules/validate.ts +26 -0
  216. package/src/be/scripts/boot-reembed.ts +6 -0
  217. package/src/be/scripts/db.ts +17 -5
  218. package/src/be/scripts/embeddings.ts +6 -0
  219. package/src/be/scripts/typecheck.ts +43 -2
  220. package/src/be/seed/schedules-seeder.ts +9 -1
  221. package/src/be/seed/workflows-seeder.ts +9 -1
  222. package/src/be/seed-scripts/index.ts +2 -0
  223. package/src/be/seed-skills/index.ts +12 -0
  224. package/src/be/swarm-config-guard.ts +5 -0
  225. package/src/be/unmapped-identities.ts +95 -1
  226. package/src/bitbucket/handlers.ts +2 -0
  227. package/src/commands/credential-outcome-report.ts +5 -2
  228. package/src/commands/onboard/agent-fs-version.ts +1 -1
  229. package/src/commands/provider-credentials.ts +19 -0
  230. package/src/commands/provider-error-class.ts +4 -1
  231. package/src/commands/rate-limit-outcome.ts +48 -3
  232. package/src/commands/runner.ts +113 -55
  233. package/src/commands/worktree-reaper.ts +600 -0
  234. package/src/event-waits/github.ts +43 -0
  235. package/src/event-waits/index.ts +29 -0
  236. package/src/event-waits/types.ts +51 -0
  237. package/src/extensions/contract-types.generated.ts +1 -1
  238. package/src/extensions/dispatcher.ts +9 -0
  239. package/src/fs/agent-fs-provider.ts +4 -1
  240. package/src/github/handlers.ts +3 -1
  241. package/src/github/pull-request-state.ts +34 -0
  242. package/src/gitlab/handlers.ts +12 -7
  243. package/src/hooks/codex-hook.ts +99 -1
  244. package/src/hooks/hook.ts +85 -11
  245. package/src/hooks/native-tool-hooks.ts +245 -0
  246. package/src/http/agents.ts +4 -0
  247. package/src/http/all-routes.ts +1 -0
  248. package/src/http/api-keys.ts +27 -3
  249. package/src/http/assets.ts +4 -3
  250. package/src/http/comb.ts +2 -2
  251. package/src/http/favorite-owner.ts +2 -2
  252. package/src/http/favorites.ts +3 -2
  253. package/src/http/fs.ts +13 -4
  254. package/src/http/index.ts +2 -0
  255. package/src/http/mcp-bridge.ts +4 -0
  256. package/src/http/objects.ts +265 -0
  257. package/src/http/pages-public.ts +40 -4
  258. package/src/http/pages.ts +3 -3
  259. package/src/http/poll.ts +43 -12
  260. package/src/http/pool-keys.ts +21 -2
  261. package/src/http/repos.ts +7 -6
  262. package/src/http/schedules.ts +38 -9
  263. package/src/http/script-connections.ts +14 -6
  264. package/src/http/script-runs.ts +12 -3
  265. package/src/http/scripts.ts +9 -0
  266. package/src/http/sessions.ts +30 -12
  267. package/src/http/skills.ts +17 -0
  268. package/src/http/task-requester.ts +2 -2
  269. package/src/http/tasks.ts +18 -12
  270. package/src/http/tool-hooks.ts +24 -2
  271. package/src/http/trackers/authorize-gate.ts +2 -2
  272. package/src/http/users.ts +136 -1
  273. package/src/http/workflow-events.ts +13 -0
  274. package/src/http/workflows.ts +21 -11
  275. package/src/linear/sync.ts +3 -1
  276. package/src/mcp-client/http-client.ts +3 -1
  277. package/src/oauth/identity-capture.ts +6 -1
  278. package/src/oauth/mcp-wrapper.ts +10 -3
  279. package/src/oauth/wrapper.ts +15 -3
  280. package/src/prompts/base-prompt.ts +35 -13
  281. package/src/prompts/session-templates.ts +26 -0
  282. package/src/providers/acp-targets.ts +2 -2
  283. package/src/providers/amp-adapter.ts +1 -1
  284. package/src/providers/dsh-adapter.ts +1 -1
  285. package/src/providers/opencode-adapter.ts +1 -0
  286. package/src/providers/opencode-swarm-plugin.ts +50 -1
  287. package/src/providers/pi-mono-adapter.ts +143 -11
  288. package/src/providers/pi-mono-extension.ts +69 -0
  289. package/src/providers/runtime-dependencies.ts +1 -1
  290. package/src/rbac/legacy-policy.ts +5 -0
  291. package/src/rbac/permissions.ts +16 -1
  292. package/src/scheduler/deferred-task-waits.ts +170 -13
  293. package/src/scripts-runtime/executors/types.ts +5 -0
  294. package/src/scripts-runtime/loader.ts +8 -0
  295. package/src/scripts-runtime/mcp-client.ts +4 -0
  296. package/src/scripts-runtime/sdk-allowlist.ts +14 -1
  297. package/src/scripts-runtime/swarm-config.ts +8 -0
  298. package/src/scripts-runtime/swarm-sdk.ts +4 -0
  299. package/src/scripts-runtime/types/stdlib.d.ts +47 -4
  300. package/src/scripts-runtime/types/swarm-extension.d.ts +8 -7
  301. package/src/scripts-runtime/types/swarm-sdk.d.ts +47 -4
  302. package/src/server.ts +4 -0
  303. package/src/slack/enrich.ts +94 -31
  304. package/src/slack/handlers.test.ts +55 -2
  305. package/src/slack/handlers.ts +38 -3
  306. package/src/slack/render-v2.ts +19 -0
  307. package/src/slack/session-mirror.ts +208 -0
  308. package/src/slack/thread-participants.ts +0 -5
  309. package/src/slack/watcher.ts +3 -0
  310. package/src/slack/work-objects.test.ts +2 -1
  311. package/src/slack/work-objects.ts +7 -2
  312. package/src/tests/agentmail-filters.test.ts +4 -3
  313. package/src/tests/agents-list-model-display.test.ts +23 -0
  314. package/src/tests/apps-spike2.test.ts +35 -0
  315. package/src/tests/audit-agent-person.test.ts +825 -0
  316. package/src/tests/audit-updated-by.test.ts +19 -12
  317. package/src/tests/base-prompt.test.ts +1 -0
  318. package/src/tests/claude-hook-output.test.ts +107 -2
  319. package/src/tests/claude-managed-setup.test.ts +1 -1
  320. package/src/tests/codex-adapter.test.ts +6 -6
  321. package/src/tests/codex-gpt6-release.test.ts +4 -4
  322. package/src/tests/db-task-read-contract.test.ts +1 -0
  323. package/src/tests/db-task-write-contract.test.ts +1 -0
  324. package/src/tests/deploy-guard.test.ts +24 -0
  325. package/src/tests/dsh-adapter.test.ts +1 -1
  326. package/src/tests/ensure-token.test.ts +2 -2
  327. package/src/tests/entrypoint-repo-autoclone-args.test.ts +202 -0
  328. package/src/tests/extensions-catalog.test.ts +33 -25
  329. package/src/tests/fake-dns.ts +47 -0
  330. package/src/tests/fixtures/base-prompt-baseline.json +12 -12
  331. package/src/tests/fixtures/sheets/eocd-count-mismatch.xlsx +0 -0
  332. package/src/tests/fixtures/sheets/rich-budget.xlsx +0 -0
  333. package/src/tests/fixtures/sheets/tracker-export.xlsx +0 -0
  334. package/src/tests/kv-storage.test.ts +3 -0
  335. package/src/tests/latest-model-report.test.ts +138 -0
  336. package/src/tests/mcp-oauth-dcr-reuse.test.ts +5 -2
  337. package/src/tests/mcp-oauth-ensure-token.test.ts +3 -2
  338. package/src/tests/mcp-oauth-manual-client.test.ts +6 -1
  339. package/src/tests/mcp-oauth-wrapper.test.ts +20 -4
  340. package/src/tests/mcp-outbound-fetch-guard.test.ts +169 -0
  341. package/src/tests/mcp-server-ssrf.test.ts +2 -0
  342. package/src/tests/memory-search-reader.test.ts +258 -0
  343. package/src/tests/memory-search-stall.test.ts +202 -20
  344. package/src/tests/model-control.test.ts +4 -4
  345. package/src/tests/model-tier-resolution.test.ts +2 -2
  346. package/src/tests/multi-runtime-registration.test.ts +8 -2
  347. package/src/tests/native-tool-hooks.test.ts +188 -0
  348. package/src/tests/oauth-connection-fetch-guard.test.ts +162 -0
  349. package/src/tests/oauth-token-endpoint-fetch-guard.test.ts +121 -0
  350. package/src/tests/oauth-wrapper.test.ts +1 -2
  351. package/src/tests/opencode-swarm-plugin.test.ts +6 -1
  352. package/src/tests/pages-head-v2.test.ts +2 -1
  353. package/src/tests/pi-provider-runtime-keys.test.ts +163 -0
  354. package/src/tests/poll-probe-readonly.test.ts +108 -0
  355. package/src/tests/primitives-sheets-xlsx.test.ts +549 -0
  356. package/src/tests/prompt-template-session.test.ts +3 -2
  357. package/src/tests/rbac-roles.test.ts +3 -0
  358. package/src/tests/script-connections-http.test.ts +8 -3
  359. package/src/tests/script-connections.test.ts +6 -0
  360. package/src/tests/seed-model-profiles.test.ts +1 -1
  361. package/src/tests/sessions-tree.test.ts +10 -2
  362. package/src/tests/slack-thread-participants.test.ts +77 -4
  363. package/src/tests/spend-cap-credentials.test.ts +34 -0
  364. package/src/tests/spend-cap-outcome.test.ts +67 -0
  365. package/src/tests/subscription-first.test.ts +119 -0
  366. package/src/tests/tool-registrar-no-input.test.ts +1 -0
  367. package/src/tests/worktree-reaper.test.ts +424 -0
  368. package/src/tools/defer-task.ts +154 -12
  369. package/src/tools/get-task-details.ts +247 -5
  370. package/src/tools/objects.ts +10 -5
  371. package/src/tools/repos/update-repo.ts +6 -6
  372. package/src/tools/schedules/create-schedule.ts +1 -0
  373. package/src/tools/schedules/list-schedules.ts +3 -0
  374. package/src/tools/schedules/patch-schedule.ts +38 -4
  375. package/src/tools/schedules/update-schedule.ts +40 -5
  376. package/src/tools/sheets.ts +66 -0
  377. package/src/tools/skills/skill-create.ts +6 -0
  378. package/src/tools/skills/skill-install-remote.ts +6 -0
  379. package/src/tools/skills/skill-sync-remote.ts +9 -0
  380. package/src/tools/skills/skill-update.ts +9 -1
  381. package/src/tools/tool-config.ts +3 -1
  382. package/src/tools/utils.ts +15 -0
  383. package/src/tools/workflows/create-workflow.ts +9 -4
  384. package/src/tools/workflows/patch-workflow-node.ts +1 -1
  385. package/src/tools/workflows/patch-workflow.ts +5 -2
  386. package/src/tools/workflows/update-workflow.ts +13 -7
  387. package/src/types.ts +96 -12
  388. package/src/utils/credentials.ts +36 -1
  389. package/src/utils/egress-guard.ts +40 -10
  390. package/src/utils/error-tracker.ts +17 -0
  391. package/src/workflows/input.ts +12 -5
  392. package/src/workflows/patch-definition.ts +13 -5
  393. package/src/workflows/triggers.ts +11 -6
  394. package/src/workflows/version.ts +7 -1
  395. package/templates/skills/apps/SKILL.md +191 -2
  396. package/templates/skills/apps/content.md +191 -2
  397. package/templates/skills/boards-and-sheets/config.json +14 -0
  398. package/templates/skills/boards-and-sheets/content.md +174 -0
  399. package/templates/skills/pages/content.md +11 -0
  400. package/templates/skills/swarm-docs/content.md +11 -0
  401. package/templates/skills/swarm-scripts/SKILL.md +1 -0
  402. package/templates/skills/swarm-scripts/content.md +1 -0
  403. package/templates/workflows/ralph-loop/content.md +6 -6
  404. package/dist/acp-adapter-11m13kx4.js +0 -16
  405. package/dist/cli-pr0eze3x.js +0 -149
  406. package/dist/core-dxcy02sc.js +0 -41
  407. package/dist/fx-adapter-0ar6pqm3.js +0 -19
  408. package/dist/grok-adapter-t6m74fb1.js +0 -19
  409. package/dist/handlers-9kwcrc4k.js +0 -38
  410. package/dist/heartbeat-p8pk1msj.js +0 -49
  411. package/dist/index-23cdfzr6.js +0 -39
  412. package/dist/index-g7kkjs5b.js +0 -38
  413. package/dist/index-stk36pa5.js +0 -43
  414. package/dist/lead-mfggjtfk.js +0 -77
  415. package/dist/thread-buffer-temgaqsy.js +0 -41
  416. package/dist/worker-efcemc22.js +0 -77
  417. /package/dist/{cli-cah298e5.js → cli-m4ejz4nj.js} +0 -0
@@ -44,6 +44,7 @@ import {
44
44
  beginRequestAuthScope,
45
45
  setRequestAuth,
46
46
  getRequestAuth,
47
+ getCurrentRequestAuth,
47
48
  runWithoutRequestAuth,
48
49
  authUserId,
49
50
  authUser,
@@ -143,6 +144,8 @@ import {
143
144
  init_review_recall_filter,
144
145
  searchMemoryCandidates,
145
146
  init_search_candidates,
147
+ memorySearchReader,
148
+ init_search_reader,
146
149
  rowToCandidate,
147
150
  init_sqlite_store,
148
151
  getEmbeddingProvider2,
@@ -403,27 +406,27 @@ import {
403
406
  recordInlineScriptRun2,
404
407
  exports_db,
405
408
  init_db4
406
- } from "./cli-12vek61e.js";
409
+ } from "./cli-h9bejmkf.js";
407
410
  import {
408
411
  assertMayActOnOperatorGrantedTarget2,
409
412
  getUserGrant2,
410
413
  init_rbac_roles
411
- } from "./cli-ma9ys8rt.js";
414
+ } from "./cli-qx1dwrr5.js";
412
415
  import {
413
416
  ensurePricingSeeded2,
414
417
  ensureRbacSeeded2,
415
418
  ensureModelProfilesSeeded2,
416
419
  init_boot_seeds
417
- } from "./cli-nja15knq.js";
420
+ } from "./cli-8rbkw18r.js";
418
421
  import {
419
422
  requestModelCatalogRefresh2,
420
423
  startPricingRefreshLoop2,
421
424
  init_pricing_refresh
422
- } from "./cli-b93d81yg.js";
425
+ } from "./cli-4h90xaet.js";
423
426
  import {
424
427
  workflowEventBus2,
425
428
  init_event_bus
426
- } from "./cli-z4f346g5.js";
429
+ } from "./cli-vx9acp12.js";
427
430
  import {
428
431
  slackCode,
429
432
  slackMissingScopeMessage,
@@ -432,11 +435,11 @@ import {
432
435
  externalChannelToolError2,
433
436
  getChannelBlockReason2,
434
437
  init_external_channel
435
- } from "./cli-fxd1mwtr.js";
438
+ } from "./cli-cqxwjb93.js";
436
439
  import {
437
440
  tableToAscii2,
438
441
  init_dist8
439
- } from "./cli-9w8712tq.js";
442
+ } from "./cli-vr4eyq6p.js";
440
443
  import {
441
444
  noteSlackInboundSideEffect,
442
445
  init_inbound_dispatch,
@@ -495,7 +498,7 @@ import {
495
498
  startSlackApp2,
496
499
  stopSlackAppUnderLifecycleLock2,
497
500
  init_app4
498
- } from "./cli-72yms3ey.js";
501
+ } from "./cli-t90k0phh.js";
499
502
  import {
500
503
  AGENT_MAX_TASKS_CONFIG_KEY,
501
504
  resetAgentMaxTasksMirror,
@@ -516,7 +519,7 @@ import {
516
519
  postApprovalCancellationUpdates2,
517
520
  createApprovalFollowUpTask2,
518
521
  init_approval_notifications
519
- } from "./cli-gfy6hbd9.js";
522
+ } from "./cli-hs3mqswp.js";
520
523
  import {
521
524
  shapeApprovalResolution,
522
525
  init_approval_resolution,
@@ -540,15 +543,15 @@ import {
540
543
  resumeFromChildRun2,
541
544
  initWaitBusSubscriptions2,
542
545
  init_resume
543
- } from "./cli-e3ahxq5y.js";
546
+ } from "./cli-zvpkrgsc.js";
544
547
  import {
545
548
  getFileStorageProvider2,
546
549
  init_registry2
547
- } from "./cli-5r95eqbh.js";
550
+ } from "./cli-y260hgep.js";
548
551
  import {
549
552
  getRuntimePool2,
550
553
  init_db2
551
- } from "./cli-q8tc22bj.js";
554
+ } from "./cli-0fx95c06.js";
552
555
  import {
553
556
  duplicateGuardedQueryKey,
554
557
  parseQueryParams,
@@ -559,13 +562,10 @@ import {
559
562
  json,
560
563
  jsonError,
561
564
  init_utils2,
562
- getSessionRoot,
563
- sessionAccessForRoot,
564
- init_session_shares,
565
565
  resolveCallerTask,
566
566
  resolveTaskGroupKey,
567
567
  resolveTaskAuditUserId,
568
- resolveHttpAuditUserId,
568
+ resolveHttpRequesterUserId,
569
569
  init_audit_user,
570
570
  resolveHttpFavoriteOwner,
571
571
  init_favorite_owner,
@@ -584,13 +584,13 @@ import {
584
584
  findRoute,
585
585
  route,
586
586
  init_route_def
587
- } from "./cli-39qm0rtm.js";
587
+ } from "./cli-a8ts6x1n.js";
588
588
  import {
589
589
  COMPOSIO_HTTP_METHODS,
590
590
  executeComposioRequest,
591
591
  composioArgsFromParts,
592
592
  init_composio
593
- } from "./cli-ercwc8xn.js";
593
+ } from "./cli-3mf04tkh.js";
594
594
  import {
595
595
  object,
596
596
  init_v4_mini
@@ -686,7 +686,7 @@ import {
686
686
  init_typecheck,
687
687
  parseSkillContent,
688
688
  init_skill_parser
689
- } from "./cli-mcymtvwn.js";
689
+ } from "./cli-13t0smbk.js";
690
690
  import {
691
691
  detachedProcessGroup,
692
692
  registerProcessGroup,
@@ -701,9 +701,10 @@ import {
701
701
  ensureToken,
702
702
  ensureTokenOrThrow,
703
703
  init_ensure_token
704
- } from "./cli-9qe5y107.js";
704
+ } from "./cli-7ewre3dm.js";
705
705
  import {
706
706
  A1Error,
707
+ colName,
707
708
  refOf,
708
709
  parseCell,
709
710
  parseRange,
@@ -719,6 +720,7 @@ import {
719
720
  SheetDocSchema,
720
721
  checkTabName,
721
722
  newTab,
723
+ emptySheet,
722
724
  usedExtent,
723
725
  constantInput,
724
726
  init_format,
@@ -727,17 +729,18 @@ import {
727
729
  ObjectsError,
728
730
  NO_AGENT_FS_IDENTITY,
729
731
  clientFor,
732
+ normalizePath,
730
733
  createObject,
731
734
  getObject,
732
735
  recordObjectVersion,
733
736
  listObjects,
734
737
  reindexObjects,
735
738
  init_objects
736
- } from "./cli-52nfye5j.js";
739
+ } from "./cli-3zyme1wt.js";
737
740
  import {
738
741
  agentFsClientFor,
739
742
  init_agent_fs_identity
740
- } from "./cli-hbvgzjq4.js";
743
+ } from "./cli-y6qqbpwc.js";
741
744
  import {
742
745
  FilesError,
743
746
  providerPath,
@@ -745,13 +748,13 @@ import {
745
748
  init_provider,
746
749
  AgentFsProvider,
747
750
  init_agent_fs_provider
748
- } from "./cli-9y4tgrkf.js";
751
+ } from "./cli-skd2c4ej.js";
749
752
  import {
750
753
  SLACK_LEAVE_THREAD_DISABLE,
751
754
  isSlackLeaveThreadDisabled,
752
755
  leaveSlackThread,
753
756
  init_left_threads
754
- } from "./cli-r14ac1y0.js";
757
+ } from "./cli-cn6fpa1p.js";
755
758
  import {
756
759
  require_fast_deep_equal
757
760
  } from "./cli-bhp11egn.js";
@@ -836,7 +839,7 @@ import {
836
839
  validateDefinition,
837
840
  applyDefinitionPatch,
838
841
  init_definition2
839
- } from "./cli-j5gtytvg.js";
842
+ } from "./cli-1dr5at77.js";
840
843
  import {
841
844
  isMultiRuntimeEnabled,
842
845
  init_multi_runtime2
@@ -859,11 +862,16 @@ import {
859
862
  import {
860
863
  canProvisionKind,
861
864
  init_runtime_providers
862
- } from "./cli-s6zk31gr.js";
865
+ } from "./cli-43dsqhcp.js";
866
+ import {
867
+ getSessionRoot,
868
+ sessionAccessForRoot,
869
+ init_session_shares
870
+ } from "./cli-w41bvvms.js";
863
871
  import {
864
872
  publicEndpointSsrfOptions,
865
873
  init_mcp_wrapper
866
- } from "./cli-bz97ff9n.js";
874
+ } from "./cli-c0tyzt73.js";
867
875
  import {
868
876
  findUserById,
869
877
  findUserByExternalId,
@@ -878,7 +886,7 @@ import {
878
886
  resolveSessionToken,
879
887
  fingerprintApiKey,
880
888
  init_users
881
- } from "./cli-k5jx8jya.js";
889
+ } from "./cli-z6m6xzxt.js";
882
890
  import {
883
891
  resolveGitHubHost,
884
892
  getGitHubLinkConfig,
@@ -891,7 +899,46 @@ import {
891
899
  ampBillsCacheWrites,
892
900
  resolveAmpModel,
893
901
  init_amp_models
894
- } from "./cli-tm60vtax.js";
902
+ } from "./cli-rfejbpe1.js";
903
+ import {
904
+ generateDefaultClaudeMd2,
905
+ generateDefaultSoulMd2,
906
+ generateDefaultIdentityMd2,
907
+ init_defaults,
908
+ taskAttachmentFetchCommand,
909
+ taskAttachmentDisplayUrl,
910
+ init_task_attachment_links,
911
+ contentSha256,
912
+ init_profile_sync
913
+ } from "./cli-s6fhqbz1.js";
914
+ import {
915
+ getSlackConfiguration,
916
+ isSlackConfigured,
917
+ init_config4
918
+ } from "./cli-eetzmsy5.js";
919
+ import {
920
+ isSteeringEnabled2,
921
+ init_steering_enabled
922
+ } from "./cli-4sydckyj.js";
923
+ import {
924
+ modelFamilyOf,
925
+ windowForModelFamily,
926
+ init_model_rate_limit_windows,
927
+ keySuffix,
928
+ splitCredentialPool,
929
+ selectCredential,
930
+ init_credentials2
931
+ } from "./cli-5basv0e7.js";
932
+ import {
933
+ findInterpolationTokens,
934
+ interpolate,
935
+ init_template2,
936
+ registerTemplate,
937
+ getTemplateDefinition,
938
+ init_registry3,
939
+ resolveTemplate,
940
+ init_resolver
941
+ } from "./cli-mwxez0pz.js";
895
942
  import {
896
943
  normalizeAssetKey,
897
944
  defaultAssetKey,
@@ -936,6 +983,7 @@ import {
936
983
  ScheduledTaskTargetTypeSchema,
937
984
  SwarmConfigScopeSchema,
938
985
  RepoGuidelinesInputSchema,
986
+ agentsMayMerge,
939
987
  RepoHooksSchema,
940
988
  AgentMemoryScopeSchema,
941
989
  AgentMemorySourceSchema,
@@ -965,46 +1013,7 @@ import {
965
1013
  KvNamespaceSchema,
966
1014
  KvKeySchema,
967
1015
  init_types5
968
- } from "./cli-5z0g0e8v.js";
969
- import {
970
- generateDefaultClaudeMd2,
971
- generateDefaultSoulMd2,
972
- generateDefaultIdentityMd2,
973
- init_defaults,
974
- taskAttachmentFetchCommand,
975
- taskAttachmentDisplayUrl,
976
- init_task_attachment_links,
977
- contentSha256,
978
- init_profile_sync
979
- } from "./cli-agjbj5x0.js";
980
- import {
981
- isSteeringEnabled2,
982
- init_steering_enabled
983
- } from "./cli-4sydckyj.js";
984
- import {
985
- getSlackConfiguration,
986
- isSlackConfigured,
987
- init_config4
988
- } from "./cli-eetzmsy5.js";
989
- import {
990
- modelFamilyOf,
991
- windowForModelFamily,
992
- init_model_rate_limit_windows,
993
- keySuffix,
994
- splitCredentialPool,
995
- selectCredential,
996
- init_credentials2
997
- } from "./cli-js10kdk7.js";
998
- import {
999
- findInterpolationTokens,
1000
- interpolate,
1001
- init_template2,
1002
- registerTemplate,
1003
- getTemplateDefinition,
1004
- init_registry3,
1005
- resolveTemplate,
1006
- init_resolver
1007
- } from "./cli-2z2c4k6q.js";
1016
+ } from "./cli-f8rcvf2x.js";
1008
1017
  import {
1009
1018
  init_zod
1010
1019
  } from "./cli-96234j5w.js";
@@ -1045,6 +1054,7 @@ import {
1045
1054
  getAgentFsLiveUrl,
1046
1055
  getAgentFsDefaultOrgId,
1047
1056
  getAgentFsDefaultDriveId,
1057
+ buildAgentFsLiveUrl,
1048
1058
  getCombState,
1049
1059
  isAgentFsProxyEnabled,
1050
1060
  init_constants3
@@ -1057,7 +1067,7 @@ import {
1057
1067
  import {
1058
1068
  init_package,
1059
1069
  package_default
1060
- } from "./cli-2amwhyv2.js";
1070
+ } from "./cli-w24f3j49.js";
1061
1071
  import {
1062
1072
  getNodeEnv,
1063
1073
  isDevOrTestNodeEnv,
@@ -1077,7 +1087,7 @@ import {
1077
1087
  registerVolatileSecret,
1078
1088
  registerSensitiveKeyName,
1079
1089
  init_secret_scrubber
1080
- } from "./cli-bpje8n65.js";
1090
+ } from "./cli-fp65jdp2.js";
1081
1091
  import {
1082
1092
  __toESM,
1083
1093
  __commonJS,
@@ -20459,7 +20469,7 @@ function startRetryPoller(registry, intervalMs = 5000) {
20459
20469
  if (!waiting)
20460
20470
  continue;
20461
20471
  if (result.waitFor === "workflow.child.finished") {
20462
- const { resumeFromChildRun } = await import("./resume-s6ey36rh.js");
20472
+ const { resumeFromChildRun } = await import("./resume-m6mjzhkp.js");
20463
20473
  await resumeFromChildRun(step.id, registry);
20464
20474
  }
20465
20475
  } else {
@@ -20785,6 +20795,9 @@ async function verifyWebhookRequest(trigger, rawBody, headers) {
20785
20795
  case "hmac-sha256":
20786
20796
  isValid = verifyHmacSignature(secret, rawBody, signature);
20787
20797
  break;
20798
+ case "hmac-sha1":
20799
+ isValid = verifyHmacSignature(secret, rawBody, signature, "sha1");
20800
+ break;
20788
20801
  case "timestamped-hmac-sha256":
20789
20802
  isValid = verifyTimestampedHmacSignature(secret, rawBody, signature, {
20790
20803
  timestampKey: verification.timestampKey,
@@ -20882,11 +20895,12 @@ async function handleScheduleTrigger(scheduleId, schedule, registry) {
20882
20895
  }
20883
20896
  return runIds;
20884
20897
  }
20885
- function verifyHmacSignature(secret, body, providedSignature) {
20886
- const hmac = crypto2.createHmac("sha256", secret);
20898
+ function verifyHmacSignature(secret, body, providedSignature, algorithm = "sha256") {
20899
+ const hmac = crypto2.createHmac(algorithm, secret);
20887
20900
  hmac.update(body);
20888
20901
  const expectedHex = hmac.digest("hex");
20889
- const normalizedProvided = providedSignature.startsWith("sha256=") ? providedSignature.slice(7) : providedSignature;
20902
+ const prefix = `${algorithm}=`;
20903
+ const normalizedProvided = providedSignature.startsWith(prefix) ? providedSignature.slice(prefix.length) : providedSignature;
20890
20904
  try {
20891
20905
  return crypto2.timingSafeEqual(Buffer.from(normalizedProvided, "hex"), Buffer.from(expectedHex, "hex"));
20892
20906
  } catch {
@@ -21031,7 +21045,11 @@ async function snapshotAndUpdateWorkflow(workflowId, updates, opts = {}) {
21031
21045
  } else {
21032
21046
  version = await snapshotWorkflow(workflowId, opts.changedByAgentId);
21033
21047
  }
21034
- const workflow = await updateWorkflow2(workflowId, updates);
21048
+ const workflow = await updateWorkflow2(workflowId, {
21049
+ ...updates,
21050
+ updatedBy: updates.updatedBy ?? null,
21051
+ updatedByAgentId: opts.changedByAgentId ?? null
21052
+ });
21035
21053
  return { workflow, version };
21036
21054
  });
21037
21055
  }
@@ -21330,7 +21348,7 @@ var init_notify = __esm(() => {
21330
21348
  }
21331
21349
  }
21332
21350
  case "slack": {
21333
- const { getSlackApp } = await import("./app-hn5fftf5.js");
21351
+ const { getSlackApp } = await import("./app-7m4z44rv.js");
21334
21352
  let app = getSlackApp();
21335
21353
  if (!app) {
21336
21354
  if (!isSlackConfigured()) {
@@ -22278,6 +22296,93 @@ var init_workflows = __esm(() => {
22278
22296
  ];
22279
22297
  });
22280
22298
 
22299
+ // src/github/pull-request-state.ts
22300
+ async function fetchPullRequestState(repo, number) {
22301
+ const auth = await getWorkerInstallationToken();
22302
+ const response = await fetch(githubApiUrl(`/repos/${repo}/pulls/${number}`), {
22303
+ headers: {
22304
+ Accept: "application/vnd.github+json",
22305
+ "X-GitHub-Api-Version": "2022-11-28",
22306
+ ...auth.status === "ok" ? { Authorization: `Bearer ${auth.token}` } : {}
22307
+ },
22308
+ signal: AbortSignal.timeout(1e4)
22309
+ });
22310
+ if (!response.ok)
22311
+ throw new Error(`GitHub returned ${response.status} for ${repo}#${number}`);
22312
+ const pr = await response.json();
22313
+ return {
22314
+ merged: pr.merged === true,
22315
+ state: pr.state === "open" ? "open" : "closed"
22316
+ };
22317
+ }
22318
+ var init_pull_request_state = __esm(() => {
22319
+ init_github_host();
22320
+ init_app();
22321
+ });
22322
+
22323
+ // src/event-waits/github.ts
22324
+ function prMatch(repo, number) {
22325
+ return { repo: repo.toLowerCase(), number };
22326
+ }
22327
+ var PrMatch, githubAdapter;
22328
+ var init_github2 = __esm(() => {
22329
+ init_zod();
22330
+ init_app();
22331
+ init_pull_request_state();
22332
+ PrMatch = object2({ repo: string2().regex(/^[\w.-]+\/[\w.-]+$/), number: number2().int().positive() }).strict();
22333
+ githubAdapter = {
22334
+ source: "github",
22335
+ events: ["vcs.pr.merged"],
22336
+ matchHint: "repo (owner/name), number",
22337
+ busPrefix: "github.pull_request.",
22338
+ readsWithServerCredentials: true,
22339
+ isEnabled: isGitHubEnabled,
22340
+ parseMatch(_event, match) {
22341
+ const parsed = PrMatch.safeParse(match);
22342
+ if (!parsed.success) {
22343
+ throw new Error("match for a github PR event takes repo (owner/name) and number only.");
22344
+ }
22345
+ return prMatch(parsed.data.repo, parsed.data.number);
22346
+ },
22347
+ fromBusEvent(busEvent, payload) {
22348
+ const pr = payload;
22349
+ if (busEvent !== "github.pull_request.closed" || pr?.merged !== true || typeof pr.repo !== "string" || typeof pr.number !== "number")
22350
+ return [];
22351
+ return [{ event: "vcs.pr.merged", match: prMatch(pr.repo, pr.number) }];
22352
+ },
22353
+ async confirm(_event, match) {
22354
+ return (await fetchPullRequestState(String(match.repo), Number(match.number))).merged;
22355
+ }
22356
+ };
22357
+ });
22358
+
22359
+ // src/event-waits/types.ts
22360
+ function matchKeyOf(match) {
22361
+ return JSON.stringify(Object.entries(match).sort(([a], [b]) => a < b ? -1 : 1));
22362
+ }
22363
+ function describeEventWait(source, event, match) {
22364
+ const target = Object.entries(match).map(([key, value]) => `${key}=${value}`).join(", ");
22365
+ return `${event} on ${source} (${target})`;
22366
+ }
22367
+ var init_types4 = () => {};
22368
+
22369
+ // src/event-waits/index.ts
22370
+ function getExternalEventAdapter(source) {
22371
+ return EXTERNAL_EVENT_ADAPTERS.find((adapter) => adapter.source === source);
22372
+ }
22373
+ function isReservedProviderEvent(name) {
22374
+ return EXTERNAL_EVENT_ADAPTERS.some((adapter) => name.startsWith(adapter.busPrefix));
22375
+ }
22376
+ var EXTERNAL_EVENT_ADAPTERS, EXTERNAL_EVENT_NAMES, EXTERNAL_EVENTS_DOC = 'vcs.pr.merged with source "github" and match {repo (owner/name), number}';
22377
+ var init_event_waits = __esm(() => {
22378
+ init_github2();
22379
+ init_types4();
22380
+ EXTERNAL_EVENT_ADAPTERS = [githubAdapter];
22381
+ EXTERNAL_EVENT_NAMES = [
22382
+ ...new Set(EXTERNAL_EVENT_ADAPTERS.flatMap((adapter) => adapter.events))
22383
+ ];
22384
+ });
22385
+
22281
22386
  // src/scheduler/schedule-task.ts
22282
22387
  async function answersInChat(task) {
22283
22388
  if (task.source === "chat")
@@ -22344,15 +22449,37 @@ var init_schedule_task = __esm(() => {
22344
22449
  });
22345
22450
 
22346
22451
  // src/scheduler/deferred-task-waits.ts
22452
+ function externalWakeReason(source, event) {
22453
+ return `external:${source}:${event}`;
22454
+ }
22347
22455
  async function resolveWaitCause(scheduleId, reason) {
22348
22456
  const client = getDbClient2();
22349
22457
  const wait = await client.get("SELECT * FROM deferred_task_waits WHERE scheduleId = ?", [scheduleId]);
22350
- if (!wait || wait.status !== "pending")
22458
+ if (!wait) {
22459
+ const eventWait = await client.get("SELECT * FROM deferred_event_waits WHERE scheduleId = ?", [scheduleId]);
22460
+ if (!eventWait || eventWait.status !== "pending")
22461
+ return;
22462
+ if (reason === "ceiling")
22463
+ return { table: "deferred_event_waits", cause: "ceiling expired", matchedTaskIds: [] };
22464
+ if (reason !== externalWakeReason(eventWait.source, eventWait.event))
22465
+ return;
22466
+ return {
22467
+ table: "deferred_event_waits",
22468
+ cause: describeEventWait(eventWait.source, eventWait.event, JSON.parse(eventWait.matchJson)),
22469
+ matchedTaskIds: []
22470
+ };
22471
+ }
22472
+ if (wait.status !== "pending")
22351
22473
  return;
22352
22474
  if (reason !== "ceiling" && wait.eventName !== "settled" && wait.eventName !== reason)
22353
22475
  return;
22354
22476
  if (reason === "ceiling")
22355
- return { wait, cause: "ceiling expired", matchedTaskIds: [] };
22477
+ return {
22478
+ table: "deferred_task_waits",
22479
+ mode: wait.mode,
22480
+ cause: "ceiling expired",
22481
+ matchedTaskIds: []
22482
+ };
22356
22483
  const members = await client.query(`SELECT m.taskId, ${WAIT_MEMBER_STATUS_SQL} AS taskStatus, EXISTS (
22357
22484
  SELECT 1 FROM scheduled_tasks d
22358
22485
  WHERE d.parentTaskId = t.id AND d.taskType = 'deferred' AND d.enabled = 1
@@ -22363,7 +22490,12 @@ async function resolveWaitCause(scheduleId, reason) {
22363
22490
  if (!matched.length || wait.mode === "all" && matched.length !== members.length)
22364
22491
  return;
22365
22492
  const cause = members.length === 1 ? `task.${matched[0].taskStatus} for task ${matched[0].taskId}` : `${wait.mode} tasks matched ${wait.eventName}: ${matched.map((member) => `${member.taskId} (${member.taskStatus})`).join(", ")}`;
22366
- return { wait, cause, matchedTaskIds: matched.map((member) => member.taskId) };
22493
+ return {
22494
+ table: "deferred_task_waits",
22495
+ mode: wait.mode,
22496
+ cause,
22497
+ matchedTaskIds: matched.map((member) => member.taskId)
22498
+ };
22367
22499
  }
22368
22500
  function wakeSchedule(schedule, cause) {
22369
22501
  return { ...schedule, taskTemplate: `${schedule.taskTemplate}
@@ -22386,9 +22518,8 @@ async function prepareDeferredWakeTask(scheduleId, reason, extraTags) {
22386
22518
  }
22387
22519
  async function prepareDeferredTaskWait(scheduleId, reason, extraTags = []) {
22388
22520
  const client = getDbClient2();
22389
- if (!await client.get("SELECT * FROM deferred_task_waits WHERE scheduleId = ?", [
22390
- scheduleId
22391
- ]))
22521
+ if (!await client.get(`SELECT 1 AS found FROM deferred_task_waits WHERE scheduleId = ?
22522
+ UNION ALL SELECT 1 FROM deferred_event_waits WHERE scheduleId = ?`, [scheduleId, scheduleId]))
22392
22523
  return;
22393
22524
  return { task: await prepareDeferredWakeTask(scheduleId, reason, extraTags) };
22394
22525
  }
@@ -22408,7 +22539,7 @@ async function dispatchDeferredTaskWait(scheduleId, reason, extraTags = [], trig
22408
22539
  if (!schedule?.enabled)
22409
22540
  return {};
22410
22541
  const now = new Date().toISOString();
22411
- const claimed = await client.run("UPDATE deferred_task_waits SET status = 'fired', firedBy = ?, resolvedAt = ?, updated_at = ? WHERE scheduleId = ? AND status = 'pending'", [reason, now, now, scheduleId]);
22542
+ const claimed = await client.run(`UPDATE ${resolved.table} SET status = 'fired', firedBy = ?, resolvedAt = ?, updated_at = ? WHERE scheduleId = ? AND status = 'pending'`, [reason, now, now, scheduleId]);
22412
22543
  if (!claimed.changes)
22413
22544
  return {};
22414
22545
  if (schedule.createdBy && !await getUserById2(schedule.createdBy)) {
@@ -22417,7 +22548,7 @@ async function dispatchDeferredTaskWait(scheduleId, reason, extraTags = [], trig
22417
22548
  if (!schedule.taskTemplate)
22418
22549
  throw new Error(`Schedule "${schedule.name}" has no taskTemplate`);
22419
22550
  const task = await createStandaloneScheduleTask(wakeSchedule(schedule, resolved.cause), extraTags, preparedForWait);
22420
- await client.run("UPDATE deferred_task_waits SET childTaskId = ? WHERE scheduleId = ?", [
22551
+ await client.run(`UPDATE ${resolved.table} SET childTaskId = ? WHERE scheduleId = ?`, [
22421
22552
  task.id,
22422
22553
  scheduleId
22423
22554
  ]);
@@ -22431,7 +22562,7 @@ async function dispatchDeferredTaskWait(scheduleId, reason, extraTags = [], trig
22431
22562
  waiterTaskId: schedule.parentTaskId ?? null,
22432
22563
  wakeTaskId: task.id,
22433
22564
  wakeAgentId: task.agentId ?? null,
22434
- mode: resolved.wait.mode
22565
+ mode: resolved.mode
22435
22566
  }
22436
22567
  });
22437
22568
  }
@@ -22498,9 +22629,50 @@ async function reapSpentDeferredSchedules(now = new Date) {
22498
22629
  AND NOT EXISTS (
22499
22630
  SELECT 1 FROM deferred_task_waits w
22500
22631
  WHERE w.scheduleId = scheduled_tasks.id AND w.status = 'pending'
22632
+ )
22633
+ AND NOT EXISTS (
22634
+ SELECT 1 FROM deferred_event_waits e
22635
+ WHERE e.scheduleId = scheduled_tasks.id AND e.status = 'pending'
22501
22636
  )`, [cutoff]);
22502
22637
  return result.changes;
22503
22638
  }
22639
+ async function reconcileDeferredEventWaits(only, trustEvent = false) {
22640
+ const waits = await getDbClient2().query(`SELECT w.scheduleId, w.source, w.event, w.matchKey, w.matchJson FROM deferred_event_waits w
22641
+ JOIN scheduled_tasks s ON s.id = w.scheduleId
22642
+ WHERE w.status = 'pending' AND s.enabled = 1
22643
+ ${only ? "AND w.source = ? AND w.event = ? AND w.matchKey = ?" : ""}`, only ? [only.source, only.event, only.matchKey] : []);
22644
+ const satisfied = new Map;
22645
+ for (const wait of waits) {
22646
+ const adapter = getExternalEventAdapter(wait.source);
22647
+ if (!adapter || !adapter.confirm && !trustEvent)
22648
+ continue;
22649
+ const key = `${wait.source}|${wait.event}|${wait.matchKey}`;
22650
+ try {
22651
+ if (!satisfied.has(key))
22652
+ satisfied.set(key, adapter.confirm ? await adapter.confirm(wait.event, JSON.parse(wait.matchJson)) : true);
22653
+ if (satisfied.get(key))
22654
+ await dispatchDeferredTaskWait(wait.scheduleId, externalWakeReason(wait.source, wait.event));
22655
+ } catch (err) {
22656
+ console.error(`[Scheduler] External event wake failed for ${wait.scheduleId}:`, err);
22657
+ }
22658
+ }
22659
+ }
22660
+ function externalEventListener(adapter) {
22661
+ return (busEvent, payload) => {
22662
+ let events;
22663
+ try {
22664
+ events = adapter.fromBusEvent(busEvent, payload);
22665
+ } catch (err) {
22666
+ console.error(`[Scheduler] ${adapter.source} adapter failed to read ${busEvent}:`, err);
22667
+ return;
22668
+ }
22669
+ for (const { event, match } of events) {
22670
+ reconcileDeferredEventWaits({ source: adapter.source, event, matchKey: matchKeyOf(match) }, true).catch((err) => {
22671
+ console.error("[Scheduler] External event wake failed:", err);
22672
+ });
22673
+ }
22674
+ };
22675
+ }
22504
22676
  function onTaskEvent(payload) {
22505
22677
  if (!payload || typeof payload !== "object" || !("taskId" in payload) || typeof payload.taskId !== "string")
22506
22678
  return;
@@ -22516,7 +22688,15 @@ async function initDeferredTaskWaits() {
22516
22688
  workflowEventBus2.on("task.skipped", onTaskEvent);
22517
22689
  workflowEventBus2.on("task.superseded", onTaskEvent);
22518
22690
  workflowEventBus2.on("task.created", onTaskEvent);
22691
+ for (const adapter of EXTERNAL_EVENT_ADAPTERS) {
22692
+ const listener = externalEventListener(adapter);
22693
+ externalEventListeners.set(adapter, listener);
22694
+ workflowEventBus2.onPrefix(adapter.busPrefix, listener);
22695
+ }
22519
22696
  await reconcileDeferredTaskWaits();
22697
+ reconcileDeferredEventWaits().catch((err) => {
22698
+ console.error("[Scheduler] External event boot reconcile failed:", err);
22699
+ });
22520
22700
  }
22521
22701
  function stopDeferredTaskWaits() {
22522
22702
  workflowEventBus2.off("task.completed", onTaskEvent);
@@ -22525,10 +22705,15 @@ function stopDeferredTaskWaits() {
22525
22705
  workflowEventBus2.off("task.skipped", onTaskEvent);
22526
22706
  workflowEventBus2.off("task.superseded", onTaskEvent);
22527
22707
  workflowEventBus2.off("task.created", onTaskEvent);
22708
+ for (const [adapter, listener] of externalEventListeners) {
22709
+ workflowEventBus2.offPrefix(adapter.busPrefix, listener);
22710
+ }
22711
+ externalEventListeners.clear();
22528
22712
  }
22529
- var WAIT_MEMBER_STATUS_SQL, DEFERRED_WAIT_WOKE_EVENT = "task_deferred_wait_woke", SPENT_DEFERRED_SCHEDULE_RETENTION_MS;
22713
+ var MAX_PENDING_EVENT_WAITS_PER_AGENT = 20, WAIT_MEMBER_STATUS_SQL, DEFERRED_WAIT_WOKE_EVENT = "task_deferred_wait_woke", SPENT_DEFERRED_SCHEDULE_RETENTION_MS, externalEventListeners;
22530
22714
  var init_deferred_task_waits = __esm(() => {
22531
22715
  init_db4();
22716
+ init_event_waits();
22532
22717
  init_types5();
22533
22718
  init_event_bus();
22534
22719
  init_schedule_task();
@@ -22536,6 +22721,7 @@ var init_deferred_task_waits = __esm(() => {
22536
22721
  WHEN t.status = 'superseded' AND t.failureReason = '${SUPERSEDED_WORKFLOW_TASK_REASON}' THEN 'failed'
22537
22722
  ELSE t.status END`;
22538
22723
  SPENT_DEFERRED_SCHEDULE_RETENTION_MS = 30 * 24 * 60 * 60 * 1000;
22724
+ externalEventListeners = new Map;
22539
22725
  });
22540
22726
 
22541
22727
  // src/scheduler/scheduler.ts
@@ -23475,7 +23661,7 @@ var init_assets = __esm(() => {
23475
23661
  });
23476
23662
  return schedule.id;
23477
23663
  },
23478
- async update(plan, id, _agentId, actor) {
23664
+ async update(plan, id, agentId, actor) {
23479
23665
  const live = await getScheduledTaskById2(id);
23480
23666
  if (!live)
23481
23667
  return;
@@ -23489,7 +23675,8 @@ var init_assets = __esm(() => {
23489
23675
  scriptName: spec.scriptName,
23490
23676
  scriptArgs: spec.scriptArgs,
23491
23677
  ...live.enabled && timingChanged ? { nextRunAt: calculateNextRun2(timingOf(spec)) } : {},
23492
- ...actor ? { updatedBy: actor } : {}
23678
+ updatedBy: actor,
23679
+ updatedByAgentId: agentId
23493
23680
  });
23494
23681
  },
23495
23682
  async remove(row) {
@@ -23531,7 +23718,7 @@ var init_assets = __esm(() => {
23531
23718
  });
23532
23719
  return workflow.id;
23533
23720
  },
23534
- async update(plan, id, _agentId, actor) {
23721
+ async update(plan, id, agentId, actor) {
23535
23722
  await updateWorkflow2(id, {
23536
23723
  description: plan.spec.description ?? "",
23537
23724
  definition: plan.spec.definition,
@@ -23539,7 +23726,8 @@ var init_assets = __esm(() => {
23539
23726
  cooldown: plan.spec.cooldown ?? null,
23540
23727
  input: plan.spec.input ?? null,
23541
23728
  triggerSchema: plan.spec.triggerSchema ?? null,
23542
- ...actor ? { updatedBy: actor } : {}
23729
+ updatedBy: actor,
23730
+ updatedByAgentId: agentId
23543
23731
  });
23544
23732
  },
23545
23733
  async remove(row) {
@@ -23565,7 +23753,7 @@ var init_assets = __esm(() => {
23565
23753
  }));
23566
23754
  return { id: skill.id, hash: skillHash(liveSkillSpec(skill), files) };
23567
23755
  },
23568
- async create(plan, agentId) {
23756
+ async create(plan, agentId, actor) {
23569
23757
  const { spec } = plan;
23570
23758
  const skill = await createSkill2({
23571
23759
  ...spec,
@@ -23580,13 +23768,15 @@ var init_assets = __esm(() => {
23580
23768
  sourceHash: spec.sourceHash ?? undefined,
23581
23769
  type: "personal",
23582
23770
  ownerAgentId: agentId,
23583
- isEnabled: false
23771
+ isEnabled: false,
23772
+ createdByAgentId: agentId,
23773
+ createdBy: actor
23584
23774
  });
23585
23775
  await upsertSkillFiles2(skill.id, plan.files);
23586
23776
  return skill.id;
23587
23777
  },
23588
- async update(plan, id) {
23589
- await updateSkill2(id, plan.spec);
23778
+ async update(plan, id, agentId, actor) {
23779
+ await updateSkill2(id, { ...plan.spec, updatedBy: actor, updatedByAgentId: agentId });
23590
23780
  const wanted = new Set(plan.files.map((file) => file.path));
23591
23781
  for (const file of await getSkillFiles2(id)) {
23592
23782
  if (!wanted.has(file.path))
@@ -23996,6 +24186,8 @@ var init_sdk_allowlist = __esm(() => {
23996
24186
  sheets_appendRows: "sheet-append-rows",
23997
24187
  sheets_clearRange: "sheet-clear-range",
23998
24188
  sheets_addTab: "sheet-add-tab",
24189
+ sheets_importXlsx: "sheet-import-xlsx",
24190
+ sheets_exportXlsx: "sheet-export-xlsx",
23999
24191
  boards_create: "board-create",
24000
24192
  boards_get: "board-get",
24001
24193
  boards_list: "board-list",
@@ -24137,7 +24329,18 @@ var init_sdk_allowlist = __esm(() => {
24137
24329
  REST_ONLY_SDK_METHODS = ["savings_calibrationGet", "savings_calibrationRun"];
24138
24330
  SDK_NAMESPACES = Object.freeze({
24139
24331
  objects: ["create", "get", "list", "reindex"],
24140
- sheets: ["create", "get", "list", "getRange", "setRange", "appendRows", "clearRange", "addTab"],
24332
+ sheets: [
24333
+ "create",
24334
+ "get",
24335
+ "list",
24336
+ "getRange",
24337
+ "setRange",
24338
+ "appendRows",
24339
+ "clearRange",
24340
+ "addTab",
24341
+ "importXlsx",
24342
+ "exportXlsx"
24343
+ ],
24141
24344
  boards: ["create", "get", "list", "addElements", "updateElements", "removeElements"]
24142
24345
  });
24143
24346
  });
@@ -24782,7 +24985,7 @@ function setPreloadedTools(server, names) {
24782
24985
  async function applyPreToolCall(name, args, requestInfo, inputSchema) {
24783
24986
  if (requestInfo.callOrigin !== "mcp")
24784
24987
  return { args };
24785
- const dispatcher = await import("./dispatcher-4q8s0mx8.js");
24988
+ const dispatcher = await import("./dispatcher-jgjqrfzv.js");
24786
24989
  const result = await dispatcher.dispatchPre("pre.tool.call", { tool: name, args, requestInfo }, inputSchema ? {
24787
24990
  validateModify: async (data) => {
24788
24991
  const schema = normalizeObjectSchema(inputSchema) ?? inputSchema;
@@ -24831,6 +25034,7 @@ function dispatchPostToolCall(dispatcher, name, args, outcome, requestInfo, dura
24831
25034
  var scriptSdkRequestOrigins, extensionRequestOrigins, getRequestInfo = (req) => {
24832
25035
  const agentIdHeader = req.requestInfo?.headers?.["x-agent-id"];
24833
25036
  const sourceTaskIdHeader = req.requestInfo?.headers?.["x-source-task-id"];
25037
+ const auditSourceTaskIdHeader = req.requestInfo?.headers?.["x-audit-source-task-id"];
24834
25038
  const contextKeyHeader = req.requestInfo?.headers?.["x-context-key"];
24835
25039
  const runtimeHeader = req.requestInfo?.headers?.["x-runtime-instance-id"];
24836
25040
  const runtimeInstanceId = Array.isArray(runtimeHeader) ? runtimeHeader[0] : runtimeHeader;
@@ -24857,6 +25061,7 @@ var scriptSdkRequestOrigins, extensionRequestOrigins, getRequestInfo = (req) =>
24857
25061
  agentId,
24858
25062
  runtimeInstanceId: typeof runtimeInstanceId === "string" ? runtimeInstanceId : undefined,
24859
25063
  sourceTaskId,
25064
+ auditSourceTaskId: sourceTaskId ?? (Array.isArray(auditSourceTaskIdHeader) ? auditSourceTaskIdHeader[0] : typeof auditSourceTaskIdHeader === "string" ? auditSourceTaskIdHeader : undefined),
24860
25065
  contextKey,
24861
25066
  callOrigin: extensionRequestOrigins.has(req) ? "extension" : scriptSdkRequestOrigins.has(req) ? "script-sdk" : "mcp"
24862
25067
  };
@@ -25152,6 +25357,7 @@ async function invokeToolInProcess(args) {
25152
25357
  headers: {
25153
25358
  "x-agent-id": args.agentId ?? "",
25154
25359
  ...args.sourceTaskId ? { "x-source-task-id": args.sourceTaskId } : {},
25360
+ ...args.auditSourceTaskId ? { "x-audit-source-task-id": args.auditSourceTaskId } : {},
25155
25361
  ...args.runtimeInstanceId ? { "x-runtime-instance-id": args.runtimeInstanceId } : {}
25156
25362
  }
25157
25363
  }
@@ -25188,6 +25394,7 @@ async function handleMcpBridge(req, res, pathSegments, _queryParams, myAgentId)
25188
25394
  args,
25189
25395
  agentId: myAgentId,
25190
25396
  sourceTaskId,
25397
+ auditSourceTaskId: headerValue2(req, "x-audit-source-task-id"),
25191
25398
  runtimeInstanceId,
25192
25399
  callOrigin: resolveBridgeCallOrigin2(myAgentId, headerValue2(req, "x-extension-token"))
25193
25400
  });
@@ -25297,6 +25504,7 @@ class SwarmConfig {
25297
25504
  agentId;
25298
25505
  mcpBaseUrl;
25299
25506
  runtimeInstanceId;
25507
+ auditSourceTaskId;
25300
25508
  extensionToken;
25301
25509
  userValues;
25302
25510
  constructor(payload) {
@@ -25316,6 +25524,10 @@ class SwarmConfig {
25316
25524
  type: "system",
25317
25525
  isSecret: payload.system.runtimeInstanceId.isSecret
25318
25526
  }) : undefined;
25527
+ this.auditSourceTaskId = payload.system.auditSourceTaskId ? Redacted.make(payload.system.auditSourceTaskId.value, {
25528
+ type: "system",
25529
+ isSecret: payload.system.auditSourceTaskId.isSecret
25530
+ }) : undefined;
25319
25531
  this.extensionToken = payload.system.extensionToken ? Redacted.make(payload.system.extensionToken.value, {
25320
25532
  type: "system",
25321
25533
  isSecret: payload.system.extensionToken.isSecret
@@ -25496,6 +25708,7 @@ function headers(config) {
25496
25708
  Authorization: `Bearer ${Redacted.value(config.apiKey)}`,
25497
25709
  "X-Agent-ID": Redacted.value(config.agentId),
25498
25710
  ...config.runtimeInstanceId ? { "X-Runtime-Instance-ID": Redacted.value(config.runtimeInstanceId) } : {},
25711
+ ...config.auditSourceTaskId ? { "X-Audit-Source-Task-Id": Redacted.value(config.auditSourceTaskId) } : {},
25499
25712
  ...config.extensionToken ? { "X-Extension-Token": Redacted.value(config.extensionToken) } : {},
25500
25713
  "Content-Type": "application/json"
25501
25714
  };
@@ -27288,6 +27501,9 @@ function unregister2(extensionId) {
27288
27501
  }
27289
27502
  return loaded;
27290
27503
  }
27504
+ function hasNativeToolHandlers2() {
27505
+ return [...registry2.values()].some((loaded) => (loaded.manifest.toolSources ?? ["mcp"]).includes("native") && loaded.handlers.some((h) => h.event === "pre.tool.call" || h.event === "post.tool.call"));
27506
+ }
27291
27507
  function listRegistered2() {
27292
27508
  return [...registry2.values()];
27293
27509
  }
@@ -27840,9 +28056,11 @@ Thread: {{thread_id}}
27840
28056
 
27841
28057
  // src/agentmail/handlers.ts
27842
28058
  function extractEmailFromField(from) {
27843
- const angleMatch = from.match(/<([^>]+@[^>]+)>/);
28059
+ const angleMatch = from.match(/<([^<>]+@[^<>]+)>\s*$/);
27844
28060
  if (angleMatch?.[1])
27845
- return angleMatch[1].toLowerCase();
28061
+ return angleMatch[1].trim().toLowerCase();
28062
+ if (from.includes("<"))
28063
+ return;
27846
28064
  const bareMatch = from.match(/[\w.+-]+@[\w.-]+\.\w+/);
27847
28065
  return bareMatch?.[0]?.toLowerCase();
27848
28066
  }
@@ -27866,11 +28084,8 @@ function isInboxAllowed(inboxId, filter) {
27866
28084
  function isSenderAllowed(from, filter) {
27867
28085
  if (!filter)
27868
28086
  return true;
27869
- const fromAddresses = Array.isArray(from) ? from : [from || ""];
27870
- return fromAddresses.some((addr) => {
27871
- const emailMatch = addr.match(/<([^>]+)>/);
27872
- return matchesAddressFilter(emailMatch?.[1] ?? addr, filter);
27873
- });
28087
+ const email = extractEmailFromField((Array.isArray(from) ? from[0] : from) ?? "");
28088
+ return email !== undefined && matchesAddressFilter(email, filter);
27874
28089
  }
27875
28090
  function isDuplicate(eventKey) {
27876
28091
  const now = Date.now();
@@ -27906,14 +28121,16 @@ async function handleMessageReceived(payload) {
27906
28121
  const from = (Array.isArray(message.from_) ? message.from_.join(", ") : message.from_) || "unknown";
27907
28122
  const subject = message.subject || "(no subject)";
27908
28123
  const body = message.text || message.html || "";
27909
- const senderEmail = extractEmailFromField(from);
27910
- const senderName = extractNameFromField(from);
28124
+ const senderEntry = (Array.isArray(message.from_) ? message.from_[0] : message.from_) ?? "";
28125
+ const senderEmail = extractEmailFromField(senderEntry);
28126
+ const senderName = extractNameFromField(senderEntry);
28127
+ const senderAuthenticated = payload.event_type !== "message.received.unauthenticated" && !message.labels?.includes("unauthenticated");
27911
28128
  let requestedByUserId;
27912
- if (senderEmail) {
28129
+ if (senderEmail && senderAuthenticated) {
27913
28130
  const { user } = await findOrCreateUserByEmail(senderEmail, { name: senderName ?? undefined }, { kind: "system", id: "webhook:agentmail" });
27914
28131
  requestedByUserId = user.id;
27915
28132
  }
27916
- const senderDisplay = senderEmail ? renderIdentity(await resolveIdentityByEmail(senderEmail)) : renderIdentity({ status: "unknown", kind: "email", externalId: "unknown" });
28133
+ const senderDisplay = renderIdentity(senderEmail && senderAuthenticated ? await resolveIdentityByEmail(senderEmail) : { status: "unknown", kind: "email", externalId: senderEmail ?? "unknown" });
27917
28134
  const preview = body.length > 500 ? `${body.substring(0, 500)}...` : body;
27918
28135
  workflowEventBus2.emit("agentmail.message.received", {
27919
28136
  inboxId: inbox_id,
@@ -28470,6 +28687,103 @@ var init_tracker = __esm(() => {
28470
28687
  init_db4();
28471
28688
  });
28472
28689
 
28690
+ // src/be/unmapped-identities.ts
28691
+ function dismissedNamespace(kind) {
28692
+ return `integration:unmapped-dismissed:${kind}`;
28693
+ }
28694
+ async function isUnmappedIdentityDismissed(kind, externalId) {
28695
+ return await getKv2(dismissedNamespace(kind), externalId) !== null;
28696
+ }
28697
+ async function dismissUnmappedIdentity(kind, externalId, dismissedBy) {
28698
+ const ns = namespace(kind);
28699
+ await getDbClient2().transaction(async () => {
28700
+ const meta = await getKv2(ns, `${externalId}:meta`);
28701
+ const count = await getKv2(ns, `${externalId}:count`);
28702
+ const prior = (await getKv2(dismissedNamespace(kind), externalId))?.value;
28703
+ if (prior && !meta && !count)
28704
+ return;
28705
+ await upsertKv2({
28706
+ namespace: dismissedNamespace(kind),
28707
+ key: externalId,
28708
+ value: {
28709
+ dismissedAt: prior?.dismissedAt ?? new Date().toISOString(),
28710
+ dismissedBy: prior?.dismissedBy ?? dismissedBy,
28711
+ meta: meta?.value ?? prior?.meta ?? null,
28712
+ count: Number(prior?.count ?? 0) + Number(count?.value ?? 0)
28713
+ },
28714
+ valueType: "json"
28715
+ });
28716
+ await deleteKv2(ns, `${externalId}:meta`);
28717
+ await deleteKv2(ns, `${externalId}:count`);
28718
+ });
28719
+ }
28720
+ async function restoreUnmappedIdentity(kind, externalId) {
28721
+ const ns = namespace(kind);
28722
+ return getDbClient2().transaction(async () => {
28723
+ const row = await getKv2(dismissedNamespace(kind), externalId);
28724
+ if (!row)
28725
+ return false;
28726
+ await deleteKv2(dismissedNamespace(kind), externalId);
28727
+ const saved = row.value;
28728
+ const expiresAt = Date.now() + TTL_MS;
28729
+ if (saved?.meta && typeof saved.meta === "object") {
28730
+ await upsertKv2({
28731
+ namespace: ns,
28732
+ key: `${externalId}:meta`,
28733
+ value: saved.meta,
28734
+ valueType: "json",
28735
+ expiresAt
28736
+ });
28737
+ await upsertKv2({
28738
+ namespace: ns,
28739
+ key: `${externalId}:count`,
28740
+ value: Number(saved.count ?? 0),
28741
+ valueType: "integer",
28742
+ expiresAt
28743
+ });
28744
+ }
28745
+ return true;
28746
+ });
28747
+ }
28748
+ function namespace(kind) {
28749
+ return `integration:unmapped:${kind}`;
28750
+ }
28751
+ async function recordUnmappedIdentity(kind, externalId, meta) {
28752
+ if (await isUnmappedIdentityDismissed(kind, externalId))
28753
+ return;
28754
+ const ns = namespace(kind);
28755
+ const now = new Date().toISOString();
28756
+ const expiresAt = Date.now() + TTL_MS;
28757
+ const countKey = `${externalId}:count`;
28758
+ const countBefore = await getKv2(ns, countKey);
28759
+ await upsertKv2({
28760
+ namespace: ns,
28761
+ key: `${externalId}:meta`,
28762
+ value: {
28763
+ lastSeenAt: now,
28764
+ sampleEventType: meta.sampleEventType,
28765
+ sampleContext: meta.sampleContext.slice(0, 100)
28766
+ },
28767
+ valueType: "json",
28768
+ expiresAt
28769
+ });
28770
+ const incremented = await incrKv2(ns, countKey, 1);
28771
+ if (countBefore === null) {
28772
+ await upsertKv2({
28773
+ namespace: ns,
28774
+ key: countKey,
28775
+ value: Number(incremented.value),
28776
+ valueType: "integer",
28777
+ expiresAt
28778
+ });
28779
+ }
28780
+ }
28781
+ var TTL_MS;
28782
+ var init_unmapped_identities = __esm(() => {
28783
+ init_db4();
28784
+ TTL_MS = 30 * 24 * 60 * 60 * 1000;
28785
+ });
28786
+
28473
28787
  // src/vcs/azure-devops.ts
28474
28788
  function isAzureDevOpsUrl(url) {
28475
28789
  return /(^|[/@.])dev\.azure\.com[/:]|\.visualstudio\.com[/:]/i.test(url);
@@ -28773,6 +29087,8 @@ async function resolveAzureDevOpsSender(identity, sampleEventType, sampleContext
28773
29087
  return;
28774
29088
  }
28775
29089
  async function recordUnmappedIdentity2(externalId, sampleEventType, sampleContext) {
29090
+ if (await isUnmappedIdentityDismissed("azure-devops", externalId))
29091
+ return;
28776
29092
  await upsertKv2({
28777
29093
  namespace: UNMAPPED_NAMESPACE,
28778
29094
  key: `${externalId}:meta`,
@@ -28952,6 +29268,7 @@ var processedEvents2, DEDUP_TTL_MS = 60000, UNMAPPED_NAMESPACE = "integration:un
28952
29268
  var init_handlers2 = __esm(() => {
28953
29269
  init_db4();
28954
29270
  init_identity();
29271
+ init_unmapped_identities();
28955
29272
  init_users();
28956
29273
  init_resolver();
28957
29274
  init_context_key();
@@ -30097,6 +30414,8 @@ async function resolveBitbucketSender(account, sampleEventType, sampleContext) {
30097
30414
  const existing = await findUserByExternalId("bitbucket", externalId);
30098
30415
  if (existing)
30099
30416
  return existing.id;
30417
+ if (await isUnmappedIdentityDismissed("bitbucket", externalId))
30418
+ return;
30100
30419
  await upsertKv2({
30101
30420
  namespace: UNMAPPED_NAMESPACE2,
30102
30421
  key: `${externalId}:meta`,
@@ -30258,6 +30577,7 @@ var DEDUP_TTL_MS2 = 60000, processedEvents3, processedDeliveries, UNMAPPED_NAMES
30258
30577
  var init_handlers3 = __esm(() => {
30259
30578
  init_db4();
30260
30579
  init_identity();
30580
+ init_unmapped_identities();
30261
30581
  init_users();
30262
30582
  init_resolver();
30263
30583
  init_context_key();
@@ -30811,6 +31131,8 @@ async function resolveGitHubSender(login, sampleEventType, sampleContext) {
30811
31131
  const existing = await findUserByExternalId("github", login);
30812
31132
  if (existing)
30813
31133
  return existing.id;
31134
+ if (await isUnmappedIdentityDismissed("github", login))
31135
+ return;
30814
31136
  await upsertKv2({
30815
31137
  namespace: UNMAPPED_NAMESPACE3,
30816
31138
  key: `${login}:meta`,
@@ -31623,6 +31945,7 @@ var processedEvents4, EVENT_TTL2 = 60000, cancelOnUnassignEnabled = () => cancel
31623
31945
  var init_handlers4 = __esm(() => {
31624
31946
  init_db4();
31625
31947
  init_identity();
31948
+ init_unmapped_identities();
31626
31949
  init_users();
31627
31950
  init_resolver();
31628
31951
  init_context_key();
@@ -31894,11 +32217,13 @@ async function resolveGitLabSender(user, sampleEventType, sampleContext) {
31894
32217
  if (existing)
31895
32218
  return existing.id;
31896
32219
  const inlineEmail = typeof user.email === "string" ? user.email.trim() : "";
31897
- if (inlineEmail !== "") {
32220
+ if (EMAIL_ADDRESS_RE.test(inlineEmail)) {
31898
32221
  const { user: linked } = await findOrCreateUserByEmail(inlineEmail, { name: user.name }, GITLAB_WEBHOOK_ACTOR);
31899
32222
  await linkIdentity(linked.id, "gitlab", user.username, GITLAB_WEBHOOK_ACTOR);
31900
32223
  return linked.id;
31901
32224
  }
32225
+ if (await isUnmappedIdentityDismissed("gitlab", user.username))
32226
+ return;
31902
32227
  await upsertKv2({
31903
32228
  namespace: UNMAPPED_NAMESPACE4,
31904
32229
  key: `${user.username}:meta`,
@@ -32211,10 +32536,11 @@ async function handlePipeline(event) {
32211
32536
  }, { origin: "webhook" });
32212
32537
  return { created: true, taskId: task.id };
32213
32538
  }
32214
- var processedEvents5, DEDUP_TTL_MS3 = 60000, LEGACY_SCOPE, UNMAPPED_NAMESPACE4 = "integration:unmapped:gitlab", UNMAPPED_TTL_MS4, GITLAB_WEBHOOK_ACTOR;
32539
+ var processedEvents5, DEDUP_TTL_MS3 = 60000, LEGACY_SCOPE, UNMAPPED_NAMESPACE4 = "integration:unmapped:gitlab", UNMAPPED_TTL_MS4, GITLAB_WEBHOOK_ACTOR, EMAIL_ADDRESS_RE;
32215
32540
  var init_handlers5 = __esm(() => {
32216
32541
  init_db4();
32217
32542
  init_identity();
32543
+ init_unmapped_identities();
32218
32544
  init_users();
32219
32545
  init_resolver();
32220
32546
  init_context_key();
@@ -32235,6 +32561,7 @@ var init_handlers5 = __esm(() => {
32235
32561
  };
32236
32562
  UNMAPPED_TTL_MS4 = 30 * 24 * 60 * 60 * 1000;
32237
32563
  GITLAB_WEBHOOK_ACTOR = { kind: "system", id: "webhook:gitlab" };
32564
+ EMAIL_ADDRESS_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
32238
32565
  });
32239
32566
 
32240
32567
  // src/gitlab/index.ts
@@ -32563,7 +32890,7 @@ async function loadAdapter(name, config, logger) {
32563
32890
  const base = { ...config, apiUrl, logger };
32564
32891
  switch (name) {
32565
32892
  case "telegram": {
32566
- const { TelegramAdapter } = await import("./index-8p0j4h4j.js");
32893
+ const { TelegramAdapter } = await import("./index-ez823q84.js");
32567
32894
 
32568
32895
  class SwarmTelegramAdapter extends TelegramAdapter {
32569
32896
  isBotMentioned(message, text) {
@@ -32577,7 +32904,7 @@ async function loadAdapter(name, config, logger) {
32577
32904
  });
32578
32905
  }
32579
32906
  case "slack": {
32580
- const { createSlackAdapter } = await import("./index-620y7jzq.js");
32907
+ const { createSlackAdapter } = await import("./index-e8pz8qdg.js");
32581
32908
  return createSlackAdapter({
32582
32909
  ...base,
32583
32910
  signingSecret: config.signingSecret ?? "",
@@ -32587,7 +32914,7 @@ async function loadAdapter(name, config, logger) {
32587
32914
  });
32588
32915
  }
32589
32916
  case "discord": {
32590
- const { createDiscordAdapter } = await import("./index-0h6qd4p1.js");
32917
+ const { createDiscordAdapter } = await import("./index-y4vd4mhn.js");
32591
32918
  return createDiscordAdapter({
32592
32919
  ...base,
32593
32920
  logger: withInfoFilter(logger, keepDiscordInfoLine),
@@ -32596,7 +32923,7 @@ async function loadAdapter(name, config, logger) {
32596
32923
  });
32597
32924
  }
32598
32925
  case "teams": {
32599
- const { createTeamsAdapter } = await import("./index-4k7m5dgj.js");
32926
+ const { createTeamsAdapter } = await import("./index-k8ajc0g0.js");
32600
32927
  const { teamsWebhookVerifier, teamsToken } = getChatSdkTestHooks();
32601
32928
  return createTeamsAdapter({
32602
32929
  ...base,
@@ -32805,7 +33132,7 @@ async function readPersistedThreadHistory(threadId) {
32805
33132
  const rows = await new SqliteChatState().getList(`${SDK_THREAD_HISTORY_PREFIX}${threadId}`);
32806
33133
  if (rows.length === 0)
32807
33134
  return [];
32808
- const { Message: MessageClass } = await import("./index-pe3d8jfy.js");
33135
+ const { Message: MessageClass } = await import("./index-whysn1wf.js");
32809
33136
  return rows.map((row) => MessageClass.fromJSON(row));
32810
33137
  }
32811
33138
  var SDK_THREAD_HISTORY_PREFIX = "msg-history:";
@@ -33351,44 +33678,6 @@ var init_session_labels = __esm(() => {
33351
33678
  };
33352
33679
  });
33353
33680
 
33354
- // src/be/unmapped-identities.ts
33355
- function namespace(kind) {
33356
- return `integration:unmapped:${kind}`;
33357
- }
33358
- async function recordUnmappedIdentity(kind, externalId, meta) {
33359
- const ns = namespace(kind);
33360
- const now = new Date().toISOString();
33361
- const expiresAt = Date.now() + TTL_MS;
33362
- const countKey = `${externalId}:count`;
33363
- const countBefore = await getKv2(ns, countKey);
33364
- await upsertKv2({
33365
- namespace: ns,
33366
- key: `${externalId}:meta`,
33367
- value: {
33368
- lastSeenAt: now,
33369
- sampleEventType: meta.sampleEventType,
33370
- sampleContext: meta.sampleContext.slice(0, 100)
33371
- },
33372
- valueType: "json",
33373
- expiresAt
33374
- });
33375
- const incremented = await incrKv2(ns, countKey, 1);
33376
- if (countBefore === null) {
33377
- await upsertKv2({
33378
- namespace: ns,
33379
- key: countKey,
33380
- value: Number(incremented.value),
33381
- valueType: "integer",
33382
- expiresAt
33383
- });
33384
- }
33385
- }
33386
- var TTL_MS;
33387
- var init_unmapped_identities = __esm(() => {
33388
- init_db4();
33389
- TTL_MS = 30 * 24 * 60 * 60 * 1000;
33390
- });
33391
-
33392
33681
  // src/be/task-attachment-store.ts
33393
33682
  async function recordTaskAttachmentUpload(input) {
33394
33683
  const { provider, scope, uploaded, contentType } = input;
@@ -35499,7 +35788,7 @@ async function startChatSdk() {
35499
35788
  for (const [name, reason] of Object.entries(config.incomplete ?? {})) {
35500
35789
  console.warn(`[chat-sdk] ${name} not started, incomplete: ${scrubSecrets(reason)}`);
35501
35790
  }
35502
- const { Chat: ChatClass } = await import("./index-pe3d8jfy.js");
35791
+ const { Chat: ChatClass } = await import("./index-whysn1wf.js");
35503
35792
  const state = new SqliteChatState;
35504
35793
  startChatRelayWatcher();
35505
35794
  await Promise.all(CHAT_SDK_ADAPTER_NAMES.map(async (name) => {
@@ -36408,7 +36697,7 @@ async function notifySlack(text) {
36408
36697
  return;
36409
36698
  }
36410
36699
  try {
36411
- const { getSlackApp } = await import("./app-hn5fftf5.js");
36700
+ const { getSlackApp } = await import("./app-7m4z44rv.js");
36412
36701
  const app = getSlackApp();
36413
36702
  if (!app) {
36414
36703
  console.warn("[Jira webhook keepalive] Slack not available, cannot send notification");
@@ -36479,7 +36768,7 @@ async function deleteJiraWebhook(webhookId) {
36479
36768
  console.log(`[Jira webhook keepalive] Deleted webhook id=${webhookId}`);
36480
36769
  }
36481
36770
  async function overwriteWebhookIds(next) {
36482
- const { getDbClient } = await import("./db-3r1fyr2n.js");
36771
+ const { getDbClient } = await import("./db-hcj16x7z.js");
36483
36772
  await getDbClient().transaction(async (tx) => {
36484
36773
  const row = await tx.get("SELECT metadata FROM oauth_apps WHERE provider = 'jira'");
36485
36774
  if (!row) {
@@ -108544,6 +108833,8 @@ async function resolveLinearActor(linearUserId, email, name, workspaceId, sample
108544
108833
  await linkIdentity(linked.id, "linear", linearUserId, LINEAR_WEBHOOK_ACTOR);
108545
108834
  return linked.id;
108546
108835
  }
108836
+ if (await isUnmappedIdentityDismissed("linear", linearUserId))
108837
+ return;
108547
108838
  await upsertKv2({
108548
108839
  namespace: UNMAPPED_NAMESPACE5,
108549
108840
  key: `${linearUserId}:meta`,
@@ -108970,6 +109261,7 @@ var init_sync = __esm(() => {
108970
109261
  init_db4();
108971
109262
  init_oauth();
108972
109263
  init_tracker();
109264
+ init_unmapped_identities();
108973
109265
  init_users();
108974
109266
  init_ensure_token();
108975
109267
  init_resolver();
@@ -109970,7 +110262,7 @@ async function loadGlobalConfigsIntoEnv2(override = false) {
109970
110262
  if (updated.length > 0) {
109971
110263
  refreshSecretScrubberCache();
109972
110264
  }
109973
- const { syncSlackTreeVisibility } = await import("./tree-visibility-cbrsfaar.js");
110265
+ const { syncSlackTreeVisibility } = await import("./tree-visibility-07h2tbs2.js");
109974
110266
  await syncSlackTreeVisibility();
109975
110267
  return updated;
109976
110268
  }
@@ -109978,14 +110270,14 @@ async function reloadGlobalConfigsAndIntegrations2() {
109978
110270
  return runWithoutRequestAuth(() => runSlackLifecycleExclusive(() => reloadGlobalConfigsAndIntegrationsInner()));
109979
110271
  }
109980
110272
  async function reloadGlobalConfigsAndIntegrationsInner() {
109981
- const { getEmbeddingProvider, resetEmbeddingProvider } = await import("./index-76zzxtzf.js");
110273
+ const { getEmbeddingProvider, resetEmbeddingProvider } = await import("./index-c0e8en64.js");
109982
110274
  const wasEmbeddingsConfigured = getEmbeddingProvider().isConfigured();
109983
110275
  const updated = await loadGlobalConfigsIntoEnv2(true);
109984
110276
  await syncTelemetryEnabled("settings").catch((err) => {
109985
110277
  console.error("[config-reload] telemetry re-init failed (non-fatal):", err);
109986
110278
  });
109987
110279
  await stopSlackAppUnderLifecycleLock2();
109988
- const { resetFileStorageProvider } = await import("./registry-eeyx1201.js");
110280
+ const { resetFileStorageProvider } = await import("./registry-zv0zvxsx.js");
109989
110281
  resetFileStorageProvider();
109990
110282
  resetEmbeddingProvider();
109991
110283
  const isEmbeddingsConfigured = getEmbeddingProvider().isConfigured();
@@ -109994,7 +110286,7 @@ async function reloadGlobalConfigsAndIntegrationsInner() {
109994
110286
  integrations.push("embeddings");
109995
110287
  }
109996
110288
  if (isEmbeddingsConfigured) {
109997
- import("./embedding-space-kcdn52vz.js").then(({ runEmbeddingMaintenance }) => runEmbeddingMaintenance({ backfill: !wasEmbeddingsConfigured })).catch((err) => {
110289
+ import("./embedding-space-v06fwy7b.js").then(({ runEmbeddingMaintenance }) => runEmbeddingMaintenance({ backfill: !wasEmbeddingsConfigured })).catch((err) => {
109998
110290
  console.error("[config-reload] embedding maintenance failed (non-fatal):", err);
109999
110291
  });
110000
110292
  }
@@ -110566,6 +110858,18 @@ var init_accept_steer = __esm(() => {
110566
110858
  });
110567
110859
  });
110568
110860
 
110861
+ // src/be/db/kv-windows.ts
110862
+ async function kvKeyAfter(namespace, prefixUpper, afterKey, offset) {
110863
+ const row = await getDbClient2().get(`SELECT key FROM kv_entries
110864
+ WHERE namespace = ? AND key > ? AND key < ?
110865
+ ORDER BY key
110866
+ LIMIT 1 OFFSET ?`, [namespace, afterKey, prefixUpper, offset]);
110867
+ return row?.key ?? null;
110868
+ }
110869
+ var init_kv_windows = __esm(() => {
110870
+ init_runtime2();
110871
+ });
110872
+
110569
110873
  // src/apps/row-store.ts
110570
110874
  function yieldToEventLoop() {
110571
110875
  return new Promise((resolve) => setImmediate(resolve));
@@ -110769,13 +111073,34 @@ async function getAppRow(appId, model, rowId) {
110769
111073
  return entry.value;
110770
111074
  }
110771
111075
  async function listAppRows(appId, model, equals = []) {
110772
- const entries = await listKv2(appsNamespace(appId), {
110773
- prefix: `${model}/row/`,
110774
- limit: 1e5,
110775
- offset: 0,
110776
- jsonFieldEquals: equals.filter((filter) => !/["\\]/.test(filter.column)).map((filter) => ({ field: filter.column, value: filter.value }))
110777
- });
110778
- return entries.map((entry) => entry.value).filter((value) => typeof value === "object" && value !== null && !Array.isArray(value));
111076
+ const namespace = appsNamespace(appId);
111077
+ const prefix = `${model}/row/`;
111078
+ const upper = kvPrefixUpperBound2(prefix);
111079
+ const jsonFieldEquals = equals.filter((filter) => !/["\\]/.test(filter.column)).map((filter) => ({ field: filter.column, value: filter.value }));
111080
+ const rows = [];
111081
+ let afterKey = prefix;
111082
+ while (rows.length < LIST_ROW_CAP) {
111083
+ const through = await kvKeyAfter(namespace, upper, afterKey, LIST_SCAN_WINDOW - 1);
111084
+ const entries = await listKv2(namespace, {
111085
+ prefix,
111086
+ limit: LIST_ROW_CAP - rows.length,
111087
+ offset: 0,
111088
+ jsonFieldEquals,
111089
+ keyAfter: afterKey,
111090
+ keyThrough: through ?? undefined
111091
+ });
111092
+ for (const { value } of entries) {
111093
+ if (typeof value === "object" && value !== null && !Array.isArray(value)) {
111094
+ rows.push(value);
111095
+ }
111096
+ }
111097
+ if (through === null)
111098
+ break;
111099
+ afterKey = through;
111100
+ if (!isInTransaction())
111101
+ await yieldToEventLoop();
111102
+ }
111103
+ return rows;
110779
111104
  }
110780
111105
  async function listAllAppRowsForMigrationUnlocked(appId, model) {
110781
111106
  const rows = [];
@@ -110928,9 +111253,10 @@ function purgeAppRows(appId, models, afterPurge) {
110928
111253
  };
110929
111254
  return acquire(0);
110930
111255
  }
110931
- var AppRowValidationError, AppRowAppNotFoundError, mutationChains, lastCreatedAtMs = 0, MIGRATION_KV_BATCH_SIZE = 1000, PURGE_BATCH_SIZE = 1000;
111256
+ var AppRowValidationError, AppRowAppNotFoundError, mutationChains, lastCreatedAtMs = 0, LIST_SCAN_WINDOW = 2000, LIST_ROW_CAP = 1e5, MIGRATION_KV_BATCH_SIZE = 1000, PURGE_BATCH_SIZE = 1000;
110932
111257
  var init_row_store = __esm(() => {
110933
111258
  init_db4();
111259
+ init_kv_windows();
110934
111260
  init_db_client();
110935
111261
  init_definition();
110936
111262
  init_format_upgrades();
@@ -112904,7 +113230,7 @@ var init_request_principal = __esm(() => {
112904
113230
 
112905
113231
  // src/http/task-requester.ts
112906
113232
  async function resolveTaskRequester(req, myAgentId, bodyUserId, trustedUserId) {
112907
- const trusted = trustedUserId === undefined ? await resolveHttpAuditUserId(req, myAgentId) : trustedUserId;
113233
+ const trusted = trustedUserId === undefined ? await resolveHttpRequesterUserId(req, myAgentId) : trustedUserId;
112908
113234
  if (trusted)
112909
113235
  return trusted;
112910
113236
  if (process.env.TRUST_BODY_REQUESTED_BY_USER_ID === "false" || !bodyUserId)
@@ -116653,7 +116979,7 @@ var ref = (input) => {
116653
116979
  throw new ObjectsError("pass `id` or `path`");
116654
116980
  return { agentId: input.agentId, id: input.id, path: input.path, kind: "board" };
116655
116981
  };
116656
- var init_service = __esm(() => {
116982
+ var init_service2 = __esm(() => {
116657
116983
  init_objects();
116658
116984
  init_write_object();
116659
116985
  init_elements();
@@ -116753,8 +117079,12 @@ var objectOutputSchema, KindSchema, summary = (o) => `${o.kind} ${o.id} at ${o.p
116753
117079
  createToolRegistrar(server)("object-reindex", {
116754
117080
  title: "Reindex primitive objects",
116755
117081
  annotations: { readOnlyHint: false, idempotentHint: true },
116756
- description: "Rebuild the object index from the files on your default agent-fs drive. Keeps each file's embedded id; a file with no id (for example a stock Excalidraw save) keeps the id of the row at its path, else gets a new one written back. Rows whose file is gone are reported as `missing`, never deleted. Files whose version matches the index are checked, not re-read (`unchanged`); one call reads at most 50 changed files, 16 MiB, or 20 seconds of work, so run it again while `truncated` is true (`cutBy` names the limit). agent-fs file.changed webhooks keep the index current between runs when the swarm can register them.",
116757
- inputSchema: object2({ kind: KindSchema.optional() }),
117082
+ description: "Rebuild the object index from the files on your default agent-fs drive. Keeps each file's embedded id; a file with no id (for example a stock Excalidraw save) keeps the id of the row at its path, else gets a new one written back. Rows whose file is gone are reported as `missing`, never deleted. Without `prefix` it touches every id-less file of the kind on the drive, including files other people put there: pass `prefix` (same path-prefix match as object-list; end it with `/` for one folder, or give one file's path) to limit it, and `dryRun: true` to get the same report with nothing written. Files whose version matches the index are checked, not re-read (`unchanged`); one call reads at most 50 changed files, 16 MiB, or 20 seconds of work, so run it again while `truncated` is true (`cutBy` names the limit). agent-fs file.changed webhooks keep the index current between runs when the swarm can register them.",
117083
+ inputSchema: object2({
117084
+ kind: KindSchema.optional(),
117085
+ prefix: string2().optional(),
117086
+ dryRun: boolean().optional()
117087
+ }),
116758
117088
  outputSchema: swarmToolOutputSchema({
116759
117089
  yourAgentId: string2().optional(),
116760
117090
  scanned: number2().optional(),
@@ -116764,14 +117094,15 @@ var objectOutputSchema, KindSchema, summary = (o) => `${o.kind} ${o.id} at ${o.p
116764
117094
  missing: array2(string2()).optional(),
116765
117095
  conflicts: array2(looseObject({ path: string2(), reason: string2() })).optional(),
116766
117096
  truncated: boolean().optional(),
116767
- cutBy: _enum2(["files", "reads", "time", "bytes"]).nullable().optional()
117097
+ cutBy: _enum2(["files", "reads", "time", "bytes"]).nullable().optional(),
117098
+ dryRun: boolean().optional()
116768
117099
  })
116769
- }, async ({ kind }, requestInfo) => {
116770
- const result = await refusing(requestInfo.agentId, () => reindexObjects({ agentId: requestInfo.agentId, kind }));
117100
+ }, async ({ kind, prefix, dryRun }, requestInfo) => {
117101
+ const result = await refusing(requestInfo.agentId, () => reindexObjects({ agentId: requestInfo.agentId, kind, prefix, dryRun }));
116771
117102
  if ("error" in result)
116772
117103
  return result.error;
116773
117104
  const report = result.value;
116774
- return toolOk(`Scanned ${report.scanned} files: ${report.unchanged} unchanged, ${report.adopted.length} adopted, ${report.restored.length} restored, ${report.missing.length} missing, ${report.conflicts.length} skipped${report.truncated ? ` (truncated: ${report.cutBy} limit)` : ""}.`, { data: { yourAgentId: requestInfo.agentId, ...report } });
117105
+ return toolOk(`${report.dryRun ? "Dry run, nothing written. " : ""}Scanned ${report.scanned} files: ${report.unchanged} unchanged, ${report.adopted.length} adopted, ${report.restored.length} restored, ${report.missing.length} missing, ${report.conflicts.length} skipped${report.truncated ? ` (truncated: ${report.cutBy} limit)` : ""}.`, { data: { yourAgentId: requestInfo.agentId, ...report } });
116775
117106
  });
116776
117107
  };
116777
117108
  var init_objects2 = __esm(() => {
@@ -116939,7 +117270,7 @@ var Coord, Size, Color, ShapeSchema, ArrowSchema, Shapes, Arrows, LayoutSchema,
116939
117270
  var init_boards = __esm(() => {
116940
117271
  init_zod();
116941
117272
  init_elements();
116942
- init_service();
117273
+ init_service2();
116943
117274
  init_objects2();
116944
117275
  init_utils();
116945
117276
  Coord = number2().min(-1e6).max(1e6);
@@ -117149,7 +117480,139 @@ function getUserCommsPrefs(user) {
117149
117480
  var init_requester_comms = () => {};
117150
117481
 
117151
117482
  // src/tools/get-task-details.ts
117152
- async function getTaskDetailsHandler(ctx, { taskId }) {
117483
+ function head(value, chars) {
117484
+ const code = value.charCodeAt(chars - 1);
117485
+ return value.slice(0, code >= 55296 && code <= 56319 ? chars - 1 : chars);
117486
+ }
117487
+ function fitToBudget(full, include) {
117488
+ if (jsonBytes(full) <= FIT_BUDGET_BYTES)
117489
+ return full;
117490
+ const fitted = { budgetBytes: FIT_BUDGET_BYTES };
117491
+ const reduced = [];
117492
+ let task = full.task;
117493
+ let requestedBy = full.requestedBy;
117494
+ let logs = full.logs;
117495
+ const view = () => ({
117496
+ ...full,
117497
+ task,
117498
+ requestedBy,
117499
+ logs,
117500
+ fitted: { ...fitted, include: reduced }
117501
+ });
117502
+ const fits = () => jsonBytes(view()) <= FIT_BUDGET_BYTES;
117503
+ if (!include.has("logs")) {
117504
+ reduced.push("logs");
117505
+ const taskAgentId = full.task.agentId;
117506
+ const compact = full.logs.map(({ taskId: _sameTask, agentId, ...rest }) => agentId && agentId !== taskAgentId ? { ...rest, agentId } : rest);
117507
+ logs = compact;
117508
+ fitted.logs = {
117509
+ compacted: "Log rows omit taskId (always this task) and agentId where it equals task.agentId."
117510
+ };
117511
+ if (!fits()) {
117512
+ let newestProgress = -1;
117513
+ compact.forEach((log, i) => {
117514
+ if (log.eventType === "task_progress")
117515
+ newestProgress = i;
117516
+ });
117517
+ const droppable = compact.map((_log, i) => i).filter((i) => i !== newestProgress && !LIFECYCLE_EVENTS.has(compact[i]?.eventType ?? ""));
117518
+ const { compacted } = fitted.logs;
117519
+ const without = (count) => {
117520
+ const drop = new Set(droppable.slice(0, count));
117521
+ const byEventType = {};
117522
+ for (const i of drop) {
117523
+ const type = compact[i]?.eventType ?? "unknown";
117524
+ byEventType[type] = (byEventType[type] ?? 0) + 1;
117525
+ }
117526
+ fitted.logs = count > 0 ? { compacted, omitted: count, omittedByEventType: byEventType } : { compacted };
117527
+ return compact.filter((_, i) => !drop.has(i));
117528
+ };
117529
+ let low = 1;
117530
+ let high = droppable.length;
117531
+ while (low < high) {
117532
+ const mid = Math.floor((low + high) / 2);
117533
+ logs = without(mid);
117534
+ if (fits())
117535
+ high = mid;
117536
+ else
117537
+ low = mid + 1;
117538
+ }
117539
+ const dropped = Math.min(low, droppable.length);
117540
+ logs = without(dropped);
117541
+ }
117542
+ }
117543
+ if (!fits() && !include.has("text")) {
117544
+ reduced.push("text");
117545
+ fitted.text = [];
117546
+ task = { ...task };
117547
+ if (requestedBy) {
117548
+ const comms = requestedBy.comms;
117549
+ requestedBy = {
117550
+ ...requestedBy,
117551
+ ...comms && typeof comms === "object" ? { comms: { ...comms } } : {}
117552
+ };
117553
+ }
117554
+ const shortenLogs = !include.has("logs");
117555
+ if (shortenLogs)
117556
+ logs = logs.map((log) => ({ ...log }));
117557
+ const slots = () => {
117558
+ const out = [];
117559
+ const mutableTask = task;
117560
+ for (const key of TASK_TEXT_FIELDS) {
117561
+ const value = mutableTask[key];
117562
+ if (typeof value === "string") {
117563
+ out.push({ field: `task.${key}`, value, set: (next) => mutableTask[key] = next });
117564
+ }
117565
+ }
117566
+ const owner = requestedBy;
117567
+ const comms = owner?.comms;
117568
+ for (const [prefix, record] of [
117569
+ ["requestedBy", owner],
117570
+ ["requestedBy.comms", comms]
117571
+ ]) {
117572
+ if (!record)
117573
+ continue;
117574
+ for (const [key, value] of Object.entries(record)) {
117575
+ if (typeof value === "string" && key !== "name" && key !== "email" && key !== "role") {
117576
+ out.push({ field: `${prefix}.${key}`, value, set: (next) => record[key] = next });
117577
+ }
117578
+ }
117579
+ }
117580
+ if (shortenLogs) {
117581
+ logs.forEach((log, i) => {
117582
+ for (const key of ["newValue", "oldValue", "metadata"]) {
117583
+ const value = log[key];
117584
+ if (typeof value === "string") {
117585
+ out.push({ field: `logs[${i}].${key}`, value, set: (next) => log[key] = next });
117586
+ }
117587
+ }
117588
+ });
117589
+ }
117590
+ return out;
117591
+ };
117592
+ const original = new Map;
117593
+ for (let round = 0;round < 40 && !fits(); round++) {
117594
+ const over = jsonBytes(view()) - FIT_BUDGET_BYTES;
117595
+ const longest = slots().reduce((best, slot) => !best || slot.value.length > best.value.length ? slot : best, undefined);
117596
+ if (!longest || longest.value.length <= MIN_TEXT_CHARS + 120)
117597
+ break;
117598
+ const first = original.get(longest.field) ?? longest.value.length;
117599
+ original.set(longest.field, first);
117600
+ const keep = Math.max(MIN_TEXT_CHARS, longest.value.length - over - 120);
117601
+ longest.set(`${head(longest.value, keep)}… [cut, ${first} chars in full; include "text" for all]`);
117602
+ const existing = fitted.text.find((entry) => entry.field === longest.field);
117603
+ if (existing)
117604
+ existing.keptChars = keep;
117605
+ else
117606
+ fitted.text.push({ field: longest.field, originalChars: first, keptChars: keep });
117607
+ }
117608
+ if (fitted.text.length === 0) {
117609
+ delete fitted.text;
117610
+ reduced.pop();
117611
+ }
117612
+ }
117613
+ return view();
117614
+ }
117615
+ async function getTaskDetailsHandler(ctx, { taskId, include }) {
117153
117616
  const task = await getTaskById2(taskId);
117154
117617
  const agentId = ctx.kind === "owner" ? ctx.agentId : undefined;
117155
117618
  if (!task) {
@@ -117168,22 +117631,26 @@ async function getTaskDetailsHandler(ctx, { taskId }) {
117168
117631
  notes: requestedByUser.notes,
117169
117632
  comms: getUserCommsPrefs(requestedByUser)
117170
117633
  } : undefined;
117171
- const data = {
117634
+ const full = {
117172
117635
  yourAgentId: agentId,
117173
117636
  task,
117174
117637
  requestedBy,
117175
117638
  logs,
117176
117639
  attachments
117177
117640
  };
117178
- return toolOk(`Task "${taskId}" (${task.status}) details retrieved.`, {
117641
+ const origin = ctx.kind === "owner" ? ctx.requestInfo?.callOrigin : undefined;
117642
+ const data = origin === "script-sdk" || origin === "extension" ? full : fitToBudget(full, new Set(include ?? []));
117643
+ const reducedParts = data.fitted?.include ?? [];
117644
+ const fitNote = reducedParts.length ? ` Fitted to the size budget; include ${JSON.stringify(reducedParts)} for the rest.` : "";
117645
+ return toolOk(`Task "${taskId}" (${task.status}) details retrieved.${fitNote}`, {
117179
117646
  details: JSON.stringify(data),
117180
117647
  data
117181
117648
  });
117182
117649
  }
117183
- var getTaskDetailsInputSchema, looseFollowUpConfigSchema, looseRoutingAffinitySchema, looseAgentTaskOutputSchema, looseAgentLogSchema, looseTaskAttachmentSchema, getTaskDetailsOutputSchema, registerGetTaskDetailsTool = (server) => {
117650
+ var GET_TASK_DETAILS_INCLUDE, getTaskDetailsInputSchema, looseFollowUpConfigSchema, looseRoutingAffinitySchema, looseAgentTaskOutputSchema, looseAgentLogSchema, looseTaskAttachmentSchema, getTaskDetailsOutputSchema, FIT_BUDGET_BYTES = 9000, LIFECYCLE_EVENTS, MIN_TEXT_CHARS = 280, TASK_TEXT_FIELDS, jsonBytes = (value) => Buffer.byteLength(JSON.stringify(value), "utf8"), registerGetTaskDetailsTool = (server) => {
117184
117651
  createToolRegistrar(server)("get-task-details", {
117185
117652
  title: "Get task details",
117186
- description: "Returns detailed information about a specific task, including output, failure reason, and log history.",
117653
+ description: 'Returns detailed information about a specific task, including output, failure reason, attachments and log history. A response over the size budget is fitted with the least loss: log rows drop fields that repeat the task, then the oldest non-lifecycle rows, then the longest text is cut. `fitted` lists each reduction; include ["logs", "text"] returns the rest.',
117187
117654
  annotations: { readOnlyHint: true },
117188
117655
  inputSchema: getTaskDetailsInputSchema,
117189
117656
  outputSchema: getTaskDetailsOutputSchema
@@ -117196,8 +117663,10 @@ var init_get_task_details = __esm(() => {
117196
117663
  init_utils();
117197
117664
  init_types5();
117198
117665
  init_requester_comms();
117666
+ GET_TASK_DETAILS_INCLUDE = ["logs", "text"];
117199
117667
  getTaskDetailsInputSchema = object2({
117200
- taskId: uuid().describe("The ID of the task to get details for.")
117668
+ taskId: uuid().describe("The ID of the task to get details for."),
117669
+ include: array2(_enum2(GET_TASK_DETAILS_INCLUDE)).optional().describe('Opt out of the size fit. A response that fits the budget is never reduced. One that does not is reduced only as far as needed, and `fitted` lists what changed. "logs": every log row verbatim. "text": every text field (task, output, progress, failureReason, requester notes, log values) uncut. A result over the wire limit still spills to KV.')
117201
117670
  });
117202
117671
  looseFollowUpConfigSchema = looseObject({
117203
117672
  disabled: boolean().optional(),
@@ -117332,8 +117801,24 @@ var init_get_task_details = __esm(() => {
117332
117801
  }).optional()
117333
117802
  }).optional().describe("Resolved user who requested this task, with role/notes and structured communication preferences (users.metadata.comms) when set"),
117334
117803
  logs: array2(looseAgentLogSchema).optional(),
117335
- attachments: array2(looseTaskAttachmentSchema).optional().describe("Pointer-based artifacts attached to this task via store-progress, ordered by created_at.")
117804
+ attachments: array2(looseTaskAttachmentSchema).optional().describe("Pointer-based artifacts attached to this task via store-progress, ordered by created_at."),
117805
+ fitted: looseObject({
117806
+ budgetBytes: number2().optional(),
117807
+ logs: looseObject({
117808
+ compacted: string2().optional(),
117809
+ omitted: number2().optional(),
117810
+ omittedByEventType: record2(string2(), number2()).optional()
117811
+ }).optional(),
117812
+ text: array2(looseObject({
117813
+ field: string2().optional(),
117814
+ originalChars: number2().optional(),
117815
+ keptChars: number2().optional()
117816
+ })).optional(),
117817
+ include: array2(string2()).optional()
117818
+ }).optional().describe("Present only when the full response passed the size budget: what was reduced to fit, and the include values that return it.")
117336
117819
  });
117820
+ LIFECYCLE_EVENTS = new Set(["task_created", "task_status_change"]);
117821
+ TASK_TEXT_FIELDS = ["task", "output", "progress", "failureReason"];
117337
117822
  });
117338
117823
 
117339
117824
  // src/tools/cancel-task.ts
@@ -117567,7 +118052,7 @@ ${issues.map((issue) => `- ${issue}`).join(`
117567
118052
  `)}`;
117568
118053
  }
117569
118054
  async function cardToSlack(card) {
117570
- const { cardToBlockKit, cardToFallbackText } = await import("./index-620y7jzq.js");
118055
+ const { cardToBlockKit, cardToFallbackText } = await import("./index-e8pz8qdg.js");
117571
118056
  const issues = cardChildren(card).flatMap((child) => {
117572
118057
  const native = NATIVE_SLACK_BLOCKS[child.type];
117573
118058
  if (!native)
@@ -122822,6 +123307,45 @@ var init_terminal_result_guard = __esm(() => {
122822
123307
  });
122823
123308
 
122824
123309
  // src/tools/defer-task.ts
123310
+ async function admitExternalWait(event, source, rawMatch) {
123311
+ const adapter = getExternalEventAdapter(source);
123312
+ if (!adapter?.events.includes(event)) {
123313
+ const served = EXTERNAL_EVENT_ADAPTERS.filter((a) => a.events.includes(event)).map((a) => a.source);
123314
+ return {
123315
+ error: `Source "${source}" does not serve ${event}; use one of: ${served.join(", ")}.`
123316
+ };
123317
+ }
123318
+ let match;
123319
+ try {
123320
+ match = adapter.parseMatch(event, rawMatch);
123321
+ } catch (error) {
123322
+ return { error: error instanceof Error ? error.message : "Invalid match." };
123323
+ }
123324
+ const target = describeEventWait(source, event, match);
123325
+ const auth = getCurrentRequestAuth();
123326
+ if (adapter.readsWithServerCredentials && auth?.kind === "agent" && auth.tokenKind === "task") {
123327
+ return {
123328
+ error: "A task-scoped token cannot defer on an external event; defer on a timer instead."
123329
+ };
123330
+ }
123331
+ if (!adapter.isEnabled()) {
123332
+ return {
123333
+ error: `The ${source} integration is off, so no event can wake you; defer on a timer instead.`
123334
+ };
123335
+ }
123336
+ if (adapter.confirm) {
123337
+ try {
123338
+ if (await adapter.confirm(event, match)) {
123339
+ return { error: `${target} already happened; read its result instead of deferring.` };
123340
+ }
123341
+ } catch (error) {
123342
+ return {
123343
+ error: `Could not read ${target} from ${source} (${error instanceof Error ? error.message : "unknown error"}); defer on a timer instead.`
123344
+ };
123345
+ }
123346
+ }
123347
+ return { adapter, match };
123348
+ }
122825
123349
  function renderChecks(checks) {
122826
123350
  if (!checks || checks.length === 0)
122827
123351
  return "";
@@ -122900,25 +123424,27 @@ function renderHumanFacingDeferral(nextRunAt, tz, isFallbackTz, waitingOn) {
122900
123424
  const when = renderWhen(nextRunAt, tz, isFallbackTz);
122901
123425
  return waitingOn ? `Waiting on ${waitingOn} — or ${when} at the latest` : `Checking back ${when}`;
122902
123426
  }
122903
- var DeferAbortedError, registerDeferTaskTool = (server) => {
123427
+ var isExternalEvent = (event) => EXTERNAL_EVENT_NAMES.includes(event), DeferAbortedError, registerDeferTaskTool = (server) => {
122904
123428
  createToolRegistrar(server)("defer-task", {
122905
123429
  title: "Defer Task",
122906
123430
  annotations: { destructiveHint: false, idempotentHint: false },
122907
- description: "Completes this task now with status `completed` and books a wake-up for you. Use when the result needs time: a build, a deploy, a reply. The task reaches its final state on this call; the lead sees your summary as its output unless the task has an outputSchema. For a task with an outputSchema, provide output as a JSON string matching that schema; it is stored verbatim as terminal output, while deferral details remain visible in the task log. A one-off schedule wakes you up later with a child task that carries this task as its parent. Optionally provide wakeOn with taskId or taskIds to wake early on task outcomes; mode defaults to all, or use any for the first match. delayMs or runAt remains required as the ceiling for the whole set. Provide delayMs or runAt, a summary of what you did, and a note that says what is pending and what to check.",
123431
+ description: 'Completes this task now with status `completed` and books a wake-up for you. Use when the result needs time: a build, a deploy, a reply. The task reaches its final state on this call; the lead sees your summary as its output unless the task has an outputSchema. For a task with an outputSchema, provide output as a JSON string matching that schema; it is stored verbatim as terminal output, while deferral details remain visible in the task log. A one-off schedule wakes you up later with a child task that carries this task as its parent. Optionally provide wakeOn with taskId or taskIds to wake early on task outcomes; mode defaults to all, or use any for the first match. Or provide wakeOn {event, source, match} to wake on an external event, e.g. {event: "vcs.pr.merged", source: "github", match: {repo, number}}. delayMs or runAt remains required as the ceiling for the whole set. Provide delayMs or runAt, a summary of what you did, and a note that says what is pending and what to check.',
122908
123432
  inputSchema: object2({
122909
123433
  taskId: string2().describe("The ID of the task you are working on."),
122910
123434
  delayMs: number2().int().positive().optional().describe("Wake up after this many milliseconds (e.g. 1800000 for 30 min)."),
122911
123435
  runAt: string2().datetime().optional().describe("Wake up at this ISO datetime (e.g. '2026-03-06T15:00:00Z'). Must be future."),
122912
123436
  wakeOn: object2({
122913
- event: _enum2(["task.completed", "task.failed", "settled"]),
123437
+ event: _enum2(["task.completed", "task.failed", "settled", ...EXTERNAL_EVENT_NAMES]),
122914
123438
  taskId: string2().min(1).optional(),
122915
123439
  taskIds: array2(string2().min(1)).min(1).optional(),
122916
- mode: _enum2(["all", "any"]).optional()
122917
- }).strict().refine((wake) => wake.taskId !== undefined !== (wake.taskIds !== undefined), {
122918
- message: "Provide exactly one of wakeOn.taskId or wakeOn.taskIds."
123440
+ mode: _enum2(["all", "any"]).optional(),
123441
+ source: string2().min(1).optional(),
123442
+ match: record2(string2(), union3([string2(), number2()])).optional()
123443
+ }).strict().refine((wake) => isExternalEvent(wake.event) || wake.taskId !== undefined !== (wake.taskIds !== undefined), { message: "Provide exactly one of wakeOn.taskId or wakeOn.taskIds." }).refine((wake) => isExternalEvent(wake.event) ? wake.source !== undefined && wake.match !== undefined && wake.taskId === undefined && wake.taskIds === undefined && wake.mode === undefined : wake.source === undefined && wake.match === undefined, {
123444
+ message: "External events (e.g. vcs.pr.merged) take source and match only; task events take no source or match."
122919
123445
  }).refine((wake) => !wake.taskIds || new Set(wake.taskIds).size === wake.taskIds.length, {
122920
123446
  message: "wakeOn.taskIds must not contain duplicates."
122921
- }).optional().describe("Wake early on a task event. Provide taskId or nonempty, unique taskIds. mode defaults to all (every member must match); any wakes on the first match. settled covers completed, failed, cancelled, or skipped. Deferred and superseded members follow their continuations; a superseded member without a resume child holds to the ceiling, except a workflow step superseded by its queued retry, which counts as failed. Any already-terminal member rejects the request; one delayMs/runAt ceiling is still required for the whole set. The member whose settlement wakes you creates no separate lead follow-up for your agent unless its followUpConfig sets onCompleted/onFailed; an all-mode member that settles while others are pending still does."),
123447
+ }).optional().describe(`Wake early on a task event. Provide taskId or nonempty, unique taskIds. mode defaults to all (every member must match); any wakes on the first match. settled covers completed, failed, cancelled, or skipped. Deferred and superseded members follow their continuations; a superseded member without a resume child holds to the ceiling, except a workflow step superseded by its queued retry, which counts as failed. Any already-terminal member rejects the request; one delayMs/runAt ceiling is still required for the whole set. External events: ${EXTERNAL_EVENTS_DOC}. They are rejected when the event already happened, the provider cannot be read, or its integration is off; an agent holds at most ${MAX_PENDING_EVENT_WAITS_PER_AGENT} pending external waits. The member whose settlement wakes you creates no separate lead follow-up for your agent unless its followUpConfig sets onCompleted/onFailed; an all-mode member that settles while others are pending still does.`),
122922
123448
  summary: string2().min(1).max(4000).describe("What you did so far and where things stand. Stored in the task log for tasks with an outputSchema; otherwise becomes the task's output."),
122923
123449
  output: string2().optional().describe("Required when the task has an outputSchema: a JSON string matching that schema, stored verbatim as terminal output. Ignored for tasks without an outputSchema."),
122924
123450
  note: string2().min(1).max(2000).describe("What is pending, and what to check on wake-up."),
@@ -122966,7 +123492,8 @@ var DeferAbortedError, registerDeferTaskTool = (server) => {
122966
123492
  const nextRunAt = delayMs ? new Date(Date.now() + delayMs).toISOString() : runAt;
122967
123493
  const watchedTaskIds = wakeOn?.taskIds ?? (wakeOn?.taskId ? [wakeOn.taskId] : []);
122968
123494
  const wakeMode = wakeOn?.mode ?? "all";
122969
- const wakeDescription = wakeOn ? `on ${wakeOn.event} for ${wakeMode} of tasks ${watchedTaskIds.join(", ")}, or by ${nextRunAt}` : `at ${nextRunAt}`;
123495
+ const eventWait = wakeOn && isExternalEvent(wakeOn.event) ? wakeOn : undefined;
123496
+ const wakeDescription = eventWait ? `on ${eventWait.event} from ${eventWait.source}, or by ${nextRunAt}` : wakeOn ? `on ${wakeOn.event} for ${wakeMode} of tasks ${watchedTaskIds.join(", ")}, or by ${nextRunAt}` : `at ${nextRunAt}`;
122970
123497
  const checksBlock = renderChecks(checks);
122971
123498
  const taskTemplate = `Resume task ${taskId}: ${note}${checksBlock}`;
122972
123499
  const createdBy = await resolveTaskAuditUserId(requestInfo.sourceTaskId, requestInfo.agentId) ?? undefined;
@@ -122979,8 +123506,23 @@ var DeferAbortedError, registerDeferTaskTool = (server) => {
122979
123506
  return toolErr(outputValidationError);
122980
123507
  }
122981
123508
  const { tz: requesterTz, isFallback: isFallbackTz } = await resolveRequesterTimezone(task.requestedByUserId);
123509
+ let admitted;
123510
+ if (eventWait) {
123511
+ const result = await admitExternalWait(eventWait.event, eventWait.source, eventWait.match);
123512
+ if ("error" in result)
123513
+ return toolErr(result.error);
123514
+ admitted = result;
123515
+ }
122982
123516
  try {
122983
123517
  const committed = await getDbClient2().transaction(async () => {
123518
+ if (admitted) {
123519
+ const pending = await getDbClient2().get(`SELECT COUNT(*) AS n FROM deferred_event_waits w
123520
+ JOIN scheduled_tasks s ON s.id = w.scheduleId
123521
+ WHERE w.status = 'pending' AND s.enabled = 1 AND s.targetAgentId = ?`, [agent.id]);
123522
+ if ((pending?.n ?? 0) >= MAX_PENDING_EVENT_WAITS_PER_AGENT) {
123523
+ throw new DeferAbortedError(`You already hold ${MAX_PENDING_EVENT_WAITS_PER_AGENT} pending external event waits; wait for one to fire.`);
123524
+ }
123525
+ }
122984
123526
  if (watchedTaskIds.length) {
122985
123527
  const existing = await getDbClient2().get(`SELECT w.scheduleId, s.parentTaskId FROM deferred_task_waits w
122986
123528
  JOIN scheduled_tasks s ON s.id = w.scheduleId
@@ -123023,7 +123565,27 @@ var DeferAbortedError, registerDeferTaskTool = (server) => {
123023
123565
  parentTaskId: taskId,
123024
123566
  createdBy
123025
123567
  });
123026
- if (wakeOn) {
123568
+ if (admitted && eventWait) {
123569
+ const matchKey = matchKeyOf(admitted.match);
123570
+ await getDbClient2().run("INSERT INTO deferred_event_waits (scheduleId, source, event, matchKey, matchJson, created_by, updated_by) VALUES (?, ?, ?, ?, ?, ?, ?)", [
123571
+ schedule.id,
123572
+ admitted.adapter.source,
123573
+ eventWait.event,
123574
+ matchKey,
123575
+ JSON.stringify(admitted.match),
123576
+ createdBy ?? null,
123577
+ createdBy ?? null
123578
+ ]);
123579
+ getDbClient2().afterCommit(() => {
123580
+ reconcileDeferredEventWaits({
123581
+ source: admitted.adapter.source,
123582
+ event: eventWait.event,
123583
+ matchKey
123584
+ }).catch((err) => {
123585
+ console.error("[defer-task] external event wake reconciliation failed:", err);
123586
+ });
123587
+ });
123588
+ } else if (wakeOn) {
123027
123589
  await getDbClient2().run("INSERT INTO deferred_task_waits (scheduleId, eventName, mode, created_by, updated_by) VALUES (?, ?, ?, ?, ?)", [schedule.id, wakeOn.event, wakeMode, createdBy ?? null, createdBy ?? null]);
123028
123590
  for (const watchedId of watchedTaskIds) {
123029
123591
  await getDbClient2().run("INSERT INTO deferred_task_wait_members (scheduleId, taskId, created_by, updated_by) VALUES (?, ?, ?, ?)", [schedule.id, watchedId, createdBy ?? null, createdBy ?? null]);
@@ -123037,7 +123599,7 @@ var DeferAbortedError, registerDeferTaskTool = (server) => {
123037
123599
  const deferralDetails = `${summary}
123038
123600
 
123039
123601
  Deferred until ${nextRunAt} (schedule ${schedule.id}). Pending: ${note}${checksBlock}`;
123040
- const terminalOutput = task.outputSchema ? output : renderHumanFacingDeferral(nextRunAt, requesterTz, isFallbackTz, wakeOn ? renderWaitingOn(watchedAgentNames, watchedTaskIds.length) : undefined);
123602
+ 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);
123041
123603
  const completed = await completeTask2(taskId, terminalOutput, {
123042
123604
  addTags: ["deferred"],
123043
123605
  deferredAt: new Date().toISOString()
@@ -123099,6 +123661,7 @@ var init_defer_task = __esm(() => {
123099
123661
  init_zod();
123100
123662
  init_audit_user();
123101
123663
  init_db4();
123664
+ init_event_waits();
123102
123665
  init_deferred_task_waits();
123103
123666
  init_task_terminal_effects();
123104
123667
  init_terminal_result_guard();
@@ -123106,6 +123669,7 @@ var init_defer_task = __esm(() => {
123106
123669
  init_utils();
123107
123670
  init_types5();
123108
123671
  init_business_use();
123672
+ init_request_auth_context();
123109
123673
  DeferAbortedError = class DeferAbortedError extends Error {
123110
123674
  };
123111
123675
  });
@@ -126066,7 +126630,7 @@ async function attachDemotionEvidence(candidates) {
126066
126630
  const ids = [...new Set(candidates.filter((c) => c.beta > c.alpha).map((c) => c.id))];
126067
126631
  if (ids.length === 0)
126068
126632
  return candidates;
126069
- const rows = await getDbClient2().query(`SELECT memoryId,
126633
+ const rows = await memorySearchReader.query(`SELECT memoryId,
126070
126634
  SUM(CASE WHEN source = 'explicit-self' AND signal > 0 THEN signal * weight ELSE 0 END) AS selfAlpha,
126071
126635
  SUM(CASE WHEN source = 'explicit-self' AND signal < 0 THEN -signal * weight ELSE 0 END) AS selfBeta,
126072
126636
  SUM(CASE WHEN source = 'llm' AND signal > 0 THEN signal * weight ELSE 0 END) AS llmAlpha,
@@ -126084,7 +126648,7 @@ async function attachDemotionEvidence(candidates) {
126084
126648
  });
126085
126649
  }
126086
126650
  var init_demotion_evidence = __esm(() => {
126087
- init_db4();
126651
+ init_search_reader();
126088
126652
  });
126089
126653
 
126090
126654
  // src/be/memory/graph-expansion.ts
@@ -128159,19 +128723,24 @@ var init_get_repos = __esm(() => {
128159
128723
  });
128160
128724
 
128161
128725
  // src/be/repo-merge-policy.ts
128162
- function changesAllowMerge(current, incoming) {
128726
+ function canonical(value) {
128727
+ return JSON.stringify(value ?? null, (_key, v) => v && typeof v === "object" && !Array.isArray(v) ? Object.fromEntries(Object.entries(v).sort(([a], [b]) => a < b ? -1 : 1)) : v);
128728
+ }
128729
+ function changesMergePolicy(current, incoming) {
128163
128730
  if (incoming === undefined)
128164
128731
  return false;
128165
- return incoming?.allowMerge === true !== (current?.allowMerge === true);
128732
+ return current?.allowMerge === true !== (incoming?.allowMerge === true) || agentsMayMerge(current) !== agentsMayMerge(incoming) || canonical(current?.mergePolicy) !== canonical(incoming?.mergePolicy);
128166
128733
  }
128167
- var init_repo_merge_policy = () => {};
128734
+ var init_repo_merge_policy = __esm(() => {
128735
+ init_types5();
128736
+ });
128168
128737
 
128169
128738
  // src/be/repo-checked-update.ts
128170
128739
  async function updateSwarmRepoChecked(id, updates, authorize) {
128171
128740
  return await getDbClient2().transaction(async () => {
128172
128741
  if (updates.guidelines !== undefined) {
128173
128742
  const existing = await getSwarmRepoById2(id);
128174
- if (existing && changesAllowMerge(existing.guidelines, updates.guidelines)) {
128743
+ if (existing && changesMergePolicy(existing.guidelines, updates.guidelines)) {
128175
128744
  const refusal = await authorize(existing);
128176
128745
  if (refusal !== null)
128177
128746
  return { kind: "refused", refusal };
@@ -128190,7 +128759,7 @@ var init_repo_checked_update = __esm(() => {
128190
128759
  var swarmRepoOutputShape2, registerUpdateRepoTool = (server) => {
128191
128760
  createToolRegistrar(server)("update-repo", {
128192
128761
  title: "Update Repo",
128193
- 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: resend its current value to edit other guidelines.",
128762
+ 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.",
128194
128763
  annotations: { readOnlyHint: false },
128195
128764
  inputSchema: object2({
128196
128765
  id: string2().uuid().describe("The repo ID to update."),
@@ -128200,7 +128769,7 @@ var swarmRepoOutputShape2, registerUpdateRepoTool = (server) => {
128200
128769
  defaultBranch: string2().optional().describe("New default branch."),
128201
128770
  autoClone: boolean().optional().describe("Whether to auto-clone."),
128202
128771
  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 }."),
128203
- guidelines: RepoGuidelinesInputSchema.nullable().optional().describe("Repository guidelines: prChecks (commands before PR), mergeChecks (conditions before merge), allowMerge (default false), review (guidance for reviewers). Pass null to clear.")
128772
+ 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.")
128204
128773
  }),
128205
128774
  outputSchema: swarmToolOutputSchema({
128206
128775
  repo: swarmRepoOutputShape2.nullable().optional()
@@ -128216,8 +128785,8 @@ var swarmRepoOutputShape2, registerUpdateRepoTool = (server) => {
128216
128785
  });
128217
128786
  if (decision.allow)
128218
128787
  return null;
128219
- const current = existing.guidelines?.allowMerge === true;
128220
- return `Only lead agents can change allowMerge (it is currently ${current}). Resend ${current} to keep it while you edit the other guidelines.`;
128788
+ const current = agentsMayMerge(existing.guidelines);
128789
+ 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.`;
128221
128790
  });
128222
128791
  if (result.kind === "refused") {
128223
128792
  return toolErr(result.refusal, { data: { repo: null } });
@@ -135850,6 +136419,9 @@ var init_list_schedules = __esm(() => {
135850
136419
  lastRunAt: string2().optional(),
135851
136420
  nextRunAt: string2().optional(),
135852
136421
  createdByAgentId: string2().optional(),
136422
+ updatedByAgentId: string2().optional(),
136423
+ createdBy: string2().optional(),
136424
+ updatedBy: string2().optional(),
135853
136425
  parentTaskId: string2().optional(),
135854
136426
  timezone: string2().optional(),
135855
136427
  consecutiveErrors: number2().optional(),
@@ -135874,7 +136446,20 @@ function validateRecurringTiming(merged) {
135874
136446
  }
135875
136447
  return null;
135876
136448
  }
135877
- var init_validate = () => {};
136449
+ function changesScheduleTarget(existing, patch) {
136450
+ return SCHEDULE_TARGET_FIELDS.some((field) => patch[field] !== undefined && !Bun.deepEquals(patch[field] ?? null, existing[field] ?? null));
136451
+ }
136452
+ var SCHEDULE_TARGET_FIELDS;
136453
+ var init_validate = __esm(() => {
136454
+ SCHEDULE_TARGET_FIELDS = [
136455
+ "targetType",
136456
+ "taskTemplate",
136457
+ "workflowId",
136458
+ "scriptName",
136459
+ "scriptArgs",
136460
+ "params"
136461
+ ];
136462
+ });
135878
136463
 
135879
136464
  // src/tools/schedules/patch-schedule.ts
135880
136465
  var import_cron_parser3, patchScheduleInputSchema, scheduleDataShape2, registerPatchScheduleTool = (server) => {
@@ -135931,6 +136516,20 @@ var import_cron_parser3, patchScheduleInputSchema, scheduleDataShape2, registerP
135931
136516
  }).allow) {
135932
136517
  return toolErr(`Schedule "${schedule.name}" defers another agent's task. Only that agent or a lead can change it.`);
135933
136518
  }
136519
+ if (changesScheduleTarget(schedule, {
136520
+ targetType,
136521
+ taskTemplate,
136522
+ workflowId,
136523
+ scriptName,
136524
+ scriptArgs
136525
+ }) && !can({
136526
+ principal: { kind: "agent", agentId: caller.id, isLead: caller.isLead },
136527
+ verb: "schedule.target.update.any",
136528
+ resource: { kind: "owned", ownerAgentId: schedule.createdByAgentId },
136529
+ source: "mcp"
136530
+ }).allow) {
136531
+ return toolErr(`Schedule "${schedule.name}" runs as the agent that created it. Only that agent or a lead can change its targetType, taskTemplate, workflowId, scriptName or scriptArgs.`);
136532
+ }
135934
136533
  if (schedule.scheduleType === "one_time" && !schedule.enabled && schedule.lastRunAt) {
135935
136534
  return toolErr(`One-time schedule "${schedule.name}" has already executed. Create a new one instead.`);
135936
136535
  }
@@ -136074,10 +136673,15 @@ var import_cron_parser3, patchScheduleInputSchema, scheduleDataShape2, registerP
136074
136673
  updateData.nextRunAt = null;
136075
136674
  }
136076
136675
  }
136077
- const updatedBy = await resolveTaskAuditUserId(requestInfo.sourceTaskId, requestInfo.agentId) ?? undefined;
136078
- if (key !== undefined)
136079
- updateData.key = await authorizeAssetKeyWrite(key, updatedBy);
136080
- const updated = await updateScheduledTask2(schedule.id, { ...updateData, updatedBy });
136676
+ const updatedBy = await resolveTaskAuditUserId(requestInfo.auditSourceTaskId, requestInfo.agentId) ?? undefined;
136677
+ if (key !== undefined) {
136678
+ updateData.key = await authorizeAssetKeyWrite(key, await resolveTaskAuditUserId(requestInfo.sourceTaskId, requestInfo.agentId));
136679
+ }
136680
+ const updated = await updateScheduledTask2(schedule.id, {
136681
+ ...updateData,
136682
+ updatedBy: updatedBy ?? null,
136683
+ updatedByAgentId: requestInfo.agentId ?? null
136684
+ });
136081
136685
  if (!updated) {
136082
136686
  return toolErr("Failed to update schedule.");
136083
136687
  }
@@ -136239,7 +136843,7 @@ var import_cron_parser4, updateScheduleInputSchema, scheduleDataShape3, register
136239
136843
  createToolRegistrar(server)("update-schedule", {
136240
136844
  title: "Update Scheduled Task",
136241
136845
  annotations: { idempotentHint: true },
136242
- description: "Update an existing scheduled task. Any registered agent can update schedules.",
136846
+ description: "Update an existing scheduled task. Any registered agent can update schedules; only the creator or a lead can change what one runs (targetType, taskTemplate, workflowId, scriptName, scriptArgs).",
136243
136847
  inputSchema: updateScheduleInputSchema,
136244
136848
  outputSchema: swarmToolOutputSchema({
136245
136849
  yourAgentId: string2().optional(),
@@ -136289,6 +136893,20 @@ var import_cron_parser4, updateScheduleInputSchema, scheduleDataShape3, register
136289
136893
  }).allow) {
136290
136894
  return toolErr(`Schedule "${schedule.name}" defers another agent's task. Only that agent or a lead can change it.`);
136291
136895
  }
136896
+ if (changesScheduleTarget(schedule, {
136897
+ targetType,
136898
+ taskTemplate,
136899
+ workflowId,
136900
+ scriptName,
136901
+ scriptArgs
136902
+ }) && !can({
136903
+ principal: { kind: "agent", agentId: caller.id, isLead: caller.isLead },
136904
+ verb: "schedule.target.update.any",
136905
+ resource: { kind: "owned", ownerAgentId: schedule.createdByAgentId },
136906
+ source: "mcp"
136907
+ }).allow) {
136908
+ return toolErr(`Schedule "${schedule.name}" runs as the agent that created it. Only that agent or a lead can change its targetType, taskTemplate, workflowId, scriptName or scriptArgs.`);
136909
+ }
136292
136910
  if (schedule.scheduleType === "one_time" && !schedule.enabled && schedule.lastRunAt) {
136293
136911
  return toolErr(`One-time schedule "${schedule.name}" has already executed. Create a new one instead.`);
136294
136912
  }
@@ -136432,10 +137050,15 @@ var import_cron_parser4, updateScheduleInputSchema, scheduleDataShape3, register
136432
137050
  updateData.nextRunAt = null;
136433
137051
  }
136434
137052
  }
136435
- const updatedBy = await resolveTaskAuditUserId(requestInfo.sourceTaskId, requestInfo.agentId) ?? undefined;
136436
- if (key !== undefined)
136437
- updateData.key = await authorizeAssetKeyWrite(key, updatedBy);
136438
- const updated = await updateScheduledTask2(schedule.id, { ...updateData, updatedBy });
137053
+ const updatedBy = await resolveTaskAuditUserId(requestInfo.auditSourceTaskId, requestInfo.agentId) ?? undefined;
137054
+ if (key !== undefined) {
137055
+ updateData.key = await authorizeAssetKeyWrite(key, await resolveTaskAuditUserId(requestInfo.sourceTaskId, requestInfo.agentId));
137056
+ }
137057
+ const updated = await updateScheduledTask2(schedule.id, {
137058
+ ...updateData,
137059
+ updatedBy: updatedBy ?? null,
137060
+ updatedByAgentId: requestInfo.agentId ?? null
137061
+ });
136439
137062
  if (!updated) {
136440
137063
  return toolErr("Failed to update schedule.");
136441
137064
  }
@@ -138088,7 +138711,321 @@ var init_engine2 = __esm(() => {
138088
138711
  ARRAY_SIZE = /\b(?:SEQUENCE|RANDARRAY|MAKEARRAY)\(\s*(\d+(?:\.\d+)?)\s*(?:,\s*(\d+(?:\.\d+)?)\s*[,)])?/gi;
138089
138712
  });
138090
138713
 
138714
+ // src/be/primitives/sheets/xlsx.ts
138715
+ import { inflateRawSync } from "node:zlib";
138716
+ function hasZip64Extra(view, from, length) {
138717
+ for (let at = from;at + 4 <= from + length; ) {
138718
+ if (view.getUint16(at, true) === 1)
138719
+ return true;
138720
+ at += 4 + view.getUint16(at + 2, true);
138721
+ }
138722
+ return false;
138723
+ }
138724
+ function checkedZipParts(bytes) {
138725
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
138726
+ const names = new Set;
138727
+ try {
138728
+ let eocd = bytes.length - 4;
138729
+ while (eocd >= 0 && view.getUint32(eocd, true) !== 101010256)
138730
+ eocd--;
138731
+ if (eocd < 0)
138732
+ throw notXlsx("not a zip archive (no end-of-directory record)");
138733
+ const count = view.getUint16(eocd + 8, true);
138734
+ const dirSize = view.getUint32(eocd + 12, true);
138735
+ const dirStart = view.getUint32(eocd + 16, true);
138736
+ if (view.getUint16(eocd + 4, true) !== 0 || view.getUint16(eocd + 6, true) !== 0 || count !== view.getUint16(eocd + 10, true) || count === 65535 || dirSize === 4294967295 || dirStart === 4294967295) {
138737
+ throw refuse("the zip end record has split-disk, inconsistent or ZIP64 counts");
138738
+ }
138739
+ if (dirStart + dirSize !== eocd)
138740
+ throw refuse("the zip directory does not end at the end record");
138741
+ let at = dirStart;
138742
+ let inflated = 0;
138743
+ for (let n = 0;n < count; n++) {
138744
+ if (view.getUint32(at, true) !== 33639248)
138745
+ throw notXlsx("broken zip directory");
138746
+ const method = view.getUint16(at + 10, true);
138747
+ const size = view.getUint32(at + 20, true);
138748
+ const fullSize = view.getUint32(at + 24, true);
138749
+ const nameLen = view.getUint16(at + 28, true);
138750
+ const extraLen = view.getUint16(at + 30, true);
138751
+ const next = at + 46 + nameLen + extraLen + view.getUint16(at + 32, true);
138752
+ const local = view.getUint32(at + 42, true);
138753
+ const name = bytes.subarray(at + 46, at + 46 + nameLen);
138754
+ names.add(new TextDecoder().decode(name));
138755
+ inflated += fullSize;
138756
+ if (inflated > MAX_INFLATED_BYTES) {
138757
+ throw new ObjectsError(`the workbook inflates to more than ${MAX_INFLATED_BYTES} bytes (16 MiB); refusing it`);
138758
+ }
138759
+ if (size === 4294967295 || fullSize === 4294967295 || hasZip64Extra(view, at + 46 + nameLen, extraLen)) {
138760
+ throw refuse("a zip part uses ZIP64 sizes");
138761
+ }
138762
+ if (view.getUint32(local, true) !== 67324752)
138763
+ throw notXlsx("broken zip local header");
138764
+ const localNameLen = view.getUint16(local + 26, true);
138765
+ const localExtraLen = view.getUint16(local + 28, true);
138766
+ const sameSize = (value, declared) => value === declared || value === 0;
138767
+ if (view.getUint16(local + 8, true) !== method || !sameSize(view.getUint32(local + 18, true), size) || !sameSize(view.getUint32(local + 22, true), fullSize) || localNameLen !== nameLen || Buffer.compare(bytes.subarray(local + 30, local + 30 + localNameLen), name) !== 0 || hasZip64Extra(view, local + 30 + localNameLen, localExtraLen)) {
138768
+ throw refuse("a zip part's local header disagrees with the directory");
138769
+ }
138770
+ const start = local + 30 + localNameLen + localExtraLen;
138771
+ const data = bytes.subarray(start, start + size);
138772
+ let actual;
138773
+ if (method === 0)
138774
+ actual = data.length;
138775
+ else if (method === 8)
138776
+ actual = inflateRawSync(data, { maxOutputLength: Math.max(fullSize, 1) }).length;
138777
+ else
138778
+ throw notXlsx(`unsupported zip compression method ${method}`);
138779
+ if (actual !== fullSize)
138780
+ throw notXlsx("a zip part does not match its declared size");
138781
+ at = next;
138782
+ }
138783
+ if (at !== eocd)
138784
+ throw refuse("the zip directory has bytes the entry count does not cover");
138785
+ } catch (error) {
138786
+ if (error instanceof ObjectsError)
138787
+ throw error;
138788
+ throw notXlsx(`corrupt zip archive (${error.message})`);
138789
+ }
138790
+ return names;
138791
+ }
138792
+ function hasTagWith(xml, tag, attr) {
138793
+ for (let at = xml.indexOf(tag);at !== -1; at = xml.indexOf(tag, at)) {
138794
+ const end = xml.indexOf(">", at);
138795
+ if (end === -1)
138796
+ return false;
138797
+ if (xml.slice(at, end).includes(attr))
138798
+ return true;
138799
+ at = end + 1;
138800
+ }
138801
+ return false;
138802
+ }
138803
+ function hasBoldFont(styles) {
138804
+ for (let at = styles.indexOf("<font>");at !== -1; at = styles.indexOf("<font>", at)) {
138805
+ const end = styles.indexOf("</font>", at);
138806
+ if (end === -1)
138807
+ return false;
138808
+ if (styles.slice(at, end).includes("<b/>"))
138809
+ return true;
138810
+ at = end + 7;
138811
+ }
138812
+ return false;
138813
+ }
138814
+ function lostFeatures(names, files, definedNames) {
138815
+ const found = new Set;
138816
+ const text = (name) => {
138817
+ const content = files[name]?.content;
138818
+ return typeof content === "string" ? content : content ? new TextDecoder().decode(content) : "";
138819
+ };
138820
+ const has = (prefix) => [...names].some((name) => name.startsWith(prefix));
138821
+ if (has("xl/charts/"))
138822
+ found.add("charts");
138823
+ if (has("xl/media/"))
138824
+ found.add("images");
138825
+ if (has("xl/comments") || has("xl/threadedComments"))
138826
+ found.add("comments");
138827
+ if (has("xl/pivot"))
138828
+ found.add("pivot tables");
138829
+ if (has("xl/tables/"))
138830
+ found.add("Excel tables");
138831
+ if (names.has("xl/vbaProject.bin"))
138832
+ found.add("macros");
138833
+ for (const name of names) {
138834
+ if (!/^xl\/worksheets\/[^/]+\.xml$/.test(name))
138835
+ continue;
138836
+ const xml = text(name);
138837
+ if (xml.includes("<conditionalFormatting"))
138838
+ found.add("conditional formatting");
138839
+ if (xml.includes("<dataValidation"))
138840
+ found.add("data validation");
138841
+ if (xml.includes("<autoFilter"))
138842
+ found.add("autofilter");
138843
+ if (xml.includes("<hyperlink "))
138844
+ found.add("hyperlinks");
138845
+ if (xml.includes("<sheetProtection"))
138846
+ found.add("sheet protection");
138847
+ if (hasTagWith(xml, "<pane ", 'state="frozen"'))
138848
+ found.add("frozen panes");
138849
+ }
138850
+ const styles = text("xl/styles.xml");
138851
+ if (/<patternFill patternType="solid"/.test(styles) || hasBoldFont(styles) || /<(left|right|top|bottom) style="/.test(styles)) {
138852
+ found.add("cell styling (fills, bold, borders)");
138853
+ }
138854
+ if (definedNames)
138855
+ found.add("defined names");
138856
+ return [...found];
138857
+ }
138858
+ async function parseXlsx(bytes) {
138859
+ const names = checkedZipParts(bytes);
138860
+ if (!names.has("xl/workbook.xml"))
138861
+ throw notXlsx("the archive has no xl/workbook.xml");
138862
+ const XLSX = await import("./xlsx-9acfmxr1.js");
138863
+ let wb;
138864
+ try {
138865
+ wb = XLSX.read(bytes, {
138866
+ type: "array",
138867
+ cellFormula: true,
138868
+ cellNF: true,
138869
+ cellStyles: true,
138870
+ xlfn: true,
138871
+ sheetStubs: true,
138872
+ bookFiles: true
138873
+ });
138874
+ } catch (error) {
138875
+ throw notXlsx(error.message);
138876
+ }
138877
+ if (wb.SheetNames.length > MAX_TABS) {
138878
+ throw new ObjectsError(`the workbook has ${wb.SheetNames.length} tabs; the limit is ${MAX_TABS}`);
138879
+ }
138880
+ const dropped = new Set;
138881
+ let cellTotal = 0;
138882
+ const tabs = wb.SheetNames.map((name) => {
138883
+ const ws = wb.Sheets[name];
138884
+ const cells = {};
138885
+ for (const [ref, entry] of Object.entries(ws)) {
138886
+ if (ref.startsWith("!"))
138887
+ continue;
138888
+ const cell = entry;
138889
+ const out = {};
138890
+ if (typeof cell.f === "string" && cell.f !== "") {
138891
+ if (cell.F?.includes(":"))
138892
+ dropped.add("array formulas (kept as values)");
138893
+ else
138894
+ out.f = `=${outsideQuotes(cell.f, (code) => code.replace(XLPREFIX, ""))}`;
138895
+ }
138896
+ if (out.f === undefined) {
138897
+ if (cell.t === "n" || cell.t === "s")
138898
+ out.v = cell.v;
138899
+ else if (cell.t === "b")
138900
+ out.v = !!cell.v;
138901
+ else if (cell.t === "e") {
138902
+ out.v = cell.w ?? "#VALUE!";
138903
+ dropped.add("error constants (kept as text)");
138904
+ }
138905
+ }
138906
+ if (out.f === undefined && out.v === undefined)
138907
+ continue;
138908
+ if (typeof cell.z === "string" && cell.z !== "General")
138909
+ out.nf = cell.z;
138910
+ cells[ref] = out;
138911
+ if (++cellTotal > MAX_CELLS) {
138912
+ throw new ObjectsError(`the workbook has more than ${MAX_CELLS} cells; the limit is ${MAX_CELLS}`);
138913
+ }
138914
+ }
138915
+ const tab = { name, cells };
138916
+ const widths = {};
138917
+ (ws["!cols"] ?? []).forEach((col, i) => {
138918
+ const px = col?.wpx ?? (col?.wch ? Math.round(col.wch * 7 + 5) : 0);
138919
+ if (px)
138920
+ widths[colName(i + 1)] = px;
138921
+ });
138922
+ if (Object.keys(widths).length)
138923
+ tab.colWidths = widths;
138924
+ if (ws["!merges"]?.length)
138925
+ tab.merges = ws["!merges"].map((range) => XLSX.utils.encode_range(range));
138926
+ return tab;
138927
+ });
138928
+ const definedNames = !!wb.Workbook?.Names?.some((n) => !String(n.Name).startsWith("_xlnm"));
138929
+ for (const feature of lostFeatures(names, wb.files ?? {}, definedNames)) {
138930
+ dropped.add(feature);
138931
+ }
138932
+ return { tabs, dropped: [...dropped] };
138933
+ }
138934
+ async function buildXlsx(tabs) {
138935
+ const XLSX = await import("./xlsx-9acfmxr1.js");
138936
+ const wb = XLSX.utils.book_new();
138937
+ const dropped = new Set;
138938
+ for (const tab of tabs) {
138939
+ const ws = {};
138940
+ let rows = 0;
138941
+ let cols = 0;
138942
+ for (const [ref, c] of Object.entries(tab.cells)) {
138943
+ const at = parseCell(ref);
138944
+ rows = Math.max(rows, at.row);
138945
+ cols = Math.max(cols, at.col);
138946
+ let cell;
138947
+ if (c.e) {
138948
+ const text = String(c.v);
138949
+ cell = { t: "e", v: ERROR_CODES[text] ?? ERROR_CODES["#VALUE!"], w: text };
138950
+ } else if (typeof c.v === "number")
138951
+ cell = { t: "n", v: c.v };
138952
+ else if (typeof c.v === "boolean")
138953
+ cell = { t: "b", v: c.v };
138954
+ else if (typeof c.v === "string")
138955
+ cell = { t: "s", v: c.v };
138956
+ else
138957
+ cell = { t: "z" };
138958
+ if (c.f)
138959
+ cell.f = toXlsxFormula(c.f);
138960
+ if (c.nf)
138961
+ cell.z = c.nf;
138962
+ if (c.s)
138963
+ dropped.add("spilled array cells (written as values; the anchor keeps its formula)");
138964
+ ws[ref] = cell;
138965
+ }
138966
+ ws["!ref"] = rows ? `A1:${refOf(rows, cols)}` : "A1";
138967
+ if (tab.colWidths) {
138968
+ ws["!cols"] = Array.from({ length: cols }, (_, i) => {
138969
+ const px = tab.colWidths?.[colName(i + 1)];
138970
+ return px ? { wpx: px } : {};
138971
+ });
138972
+ }
138973
+ if (tab.merges)
138974
+ ws["!merges"] = tab.merges.map((range) => XLSX.utils.decode_range(range));
138975
+ if (tab.freezeRows)
138976
+ dropped.add("frozen panes");
138977
+ try {
138978
+ XLSX.utils.book_append_sheet(wb, ws, tab.name);
138979
+ } catch (error) {
138980
+ throw new ObjectsError(`cannot export tab '${tab.name}': ${error.message}`);
138981
+ }
138982
+ }
138983
+ const out = XLSX.write(wb, { type: "array", bookType: "xlsx", compression: true });
138984
+ return { bytes: new Uint8Array(out), dropped: [...dropped] };
138985
+ }
138986
+ var XLSX_MIME = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", MAX_XLSX_BYTES, MAX_INFLATED_BYTES, notXlsx = (why) => new ObjectsError(`not an xlsx workbook: ${why}`), refuse = (why) => notXlsx(`${why}; refusing it`), outsideQuotes = (formula, fn) => formula.split(/("(?:[^"]|"")*"|'(?:[^']|'')*')/).map((part, i) => i % 2 ? part : fn(part)).join(""), XLPREFIX, XLFN_FUNCTIONS, XLWS_FUNCTIONS, prefixFunctions = (formula, names, prefix) => names.reduce((f, name) => f.replace(new RegExp(`(?<![\\w.])${name.replace(".", "\\.")}\\(`, "gi"), `${prefix}${name}(`), formula), toXlsxFormula = (formula) => outsideQuotes(formula.slice(1), (code) => prefixFunctions(prefixFunctions(code, XLFN_FUNCTIONS, "_xlfn."), XLWS_FUNCTIONS, "_xlfn._xlws.")), ERROR_CODES;
138987
+ var init_xlsx = __esm(() => {
138988
+ init_objects();
138989
+ init_a1();
138990
+ init_format();
138991
+ MAX_XLSX_BYTES = MAX_FILE_BYTES;
138992
+ MAX_INFLATED_BYTES = 16 * 1024 * 1024;
138993
+ XLPREFIX = /_xl(?:fn|ws)\./g;
138994
+ XLFN_FUNCTIONS = [
138995
+ "CONCAT",
138996
+ "IFNA",
138997
+ "IFS",
138998
+ "MAXIFS",
138999
+ "MINIFS",
139000
+ "SEQUENCE",
139001
+ "STDEV.P",
139002
+ "STDEV.S",
139003
+ "SWITCH",
139004
+ "TEXTJOIN",
139005
+ "UNIQUE",
139006
+ "VAR.P",
139007
+ "VAR.S",
139008
+ "XLOOKUP",
139009
+ "XMATCH"
139010
+ ];
139011
+ XLWS_FUNCTIONS = ["FILTER", "SORT"];
139012
+ ERROR_CODES = {
139013
+ "#NULL!": 0,
139014
+ "#DIV/0!": 7,
139015
+ "#VALUE!": 15,
139016
+ "#REF!": 23,
139017
+ "#NAME?": 29,
139018
+ "#NUM!": 36,
139019
+ "#N/A": 42
139020
+ };
139021
+ });
139022
+
138091
139023
  // src/be/primitives/sheets/service.ts
139024
+ function embeddedId(content) {
139025
+ const { swarm } = content;
139026
+ const id = swarm && typeof swarm === "object" ? swarm.id : undefined;
139027
+ return typeof id === "string" && id.length > 0 ? id : undefined;
139028
+ }
138092
139029
  async function load(target) {
138093
139030
  const { object, missing, content } = await getObject({ ...target, includeContent: true });
138094
139031
  if (object.kind !== "sheet") {
@@ -138099,7 +139036,11 @@ async function load(target) {
138099
139036
  }
138100
139037
  const parsed = SheetDocSchema.safeParse(content);
138101
139038
  if (!parsed.success) {
138102
- const issue = parsed.error.issues[0];
139039
+ const { issues } = parsed.error;
139040
+ if (issues.every((i) => i.path[0] === "swarm") && !embeddedId(content)) {
139041
+ throw new ObjectsError(`${object.path} has no embedded swarm.id, so a save outside the sheet tools dropped it; run object-reindex (ctx.objects.reindex) with prefix '${object.path}' to write the id back, then retry`);
139042
+ }
139043
+ const issue = issues[0];
138103
139044
  throw new ObjectsError(`${object.path} is not a valid swarm-sheet/1 workbook: ${issue?.path.join(".") || "document"}: ${issue?.message}`);
138104
139045
  }
138105
139046
  if (object.fileVersion === null) {
@@ -138107,11 +139048,15 @@ async function load(target) {
138107
139048
  }
138108
139049
  return { object, version: object.fileVersion, doc: parsed.data };
138109
139050
  }
138110
- async function save(agentId, object, doc, version, op) {
139051
+ function sheetBody(doc) {
138111
139052
  const body = JSON.stringify(doc, null, 2);
138112
139053
  if (Buffer.byteLength(body) > MAX_FILE_BYTES) {
138113
139054
  throw new ObjectsError(`the sheet would exceed ${MAX_FILE_BYTES} bytes (5 MiB)`);
138114
139055
  }
139056
+ return body;
139057
+ }
139058
+ async function save(agentId, object, doc, version, op) {
139059
+ const body = sheetBody(doc);
138115
139060
  const client = agentId ? await agentFsClientFor(agentId) : undefined;
138116
139061
  if (!client)
138117
139062
  throw new ObjectsError(NO_AGENT_FS_IDENTITY);
@@ -138175,7 +139120,7 @@ function checkArea(range, what) {
138175
139120
  async function createSheet(input) {
138176
139121
  const { tabs } = input;
138177
139122
  if (tabs) {
138178
- refuse(() => {
139123
+ refuse2(() => {
138179
139124
  if (tabs.length === 0 || tabs.length > MAX_TABS)
138180
139125
  throw new A1Error(`tabs: 1-${MAX_TABS} tabs`);
138181
139126
  const seen = new Set;
@@ -138223,7 +139168,7 @@ async function getSheet(target) {
138223
139168
  }
138224
139169
  async function getSheetRange(target) {
138225
139170
  const { version, doc } = await load(target);
138226
- const spec = refuse(() => parseRange(target.range));
139171
+ const spec = refuse2(() => parseRange(target.range));
138227
139172
  const tab = findTab(doc, spec.tab);
138228
139173
  const range = capToUsed(spec, usedExtent(tab));
138229
139174
  if (!range)
@@ -138255,7 +139200,7 @@ async function getSheetRange(target) {
138255
139200
  };
138256
139201
  }
138257
139202
  async function setSheetRange(target) {
138258
- const spec = refuse(() => parseRange(target.range));
139203
+ const spec = refuse2(() => parseRange(target.range));
138259
139204
  if (spec.open)
138260
139205
  throw new ObjectsError("setRange needs a bounded range such as 'Tab!B2:C3', not a whole column or row");
138261
139206
  const rows = target.values.length;
@@ -138271,7 +139216,7 @@ async function setSheetRange(target) {
138271
139216
  if (height !== rows || width !== cols) {
138272
139217
  throw new ObjectsError(`values is ${rows}x${cols} but the range is ${height}x${width}`);
138273
139218
  }
138274
- refuse(() => assertInBounds(range));
139219
+ refuse2(() => assertInBounds(range));
138275
139220
  checkArea(range, "the range");
138276
139221
  const { version, result } = await mutate(target, "set range", async (doc) => {
138277
139222
  const tab = findTab(doc, spec.tab);
@@ -138310,7 +139255,7 @@ async function appendSheetRows(target) {
138310
139255
  const first = usedExtent(tab).rows + 1;
138311
139256
  const cols = Math.max(...target.rows.map((row) => row.length));
138312
139257
  const range = { r1: first, c1: 1, r2: first + target.rows.length - 1, c2: cols };
138313
- refuse(() => assertInBounds(range));
139258
+ refuse2(() => assertInBounds(range));
138314
139259
  const patches = target.rows.flatMap((row, i) => row.flatMap((value, j) => value === null ? [] : [{ tab: tab.name, row: first + i, col: j + 1, input: inputFor(value) }]));
138315
139260
  const changed = await recalc(target.agentId, doc, patches);
138316
139261
  return {
@@ -138321,7 +139266,7 @@ async function appendSheetRows(target) {
138321
139266
  return { ...result, version };
138322
139267
  }
138323
139268
  async function clearSheetRange(target) {
138324
- const spec = refuse(() => parseRange(target.range));
139269
+ const spec = refuse2(() => parseRange(target.range));
138325
139270
  const { version, result } = await mutate(target, "clear range", async (doc) => {
138326
139271
  const tab = findTab(doc, spec.tab);
138327
139272
  const range = capToUsed(spec, usedExtent(tab));
@@ -138344,7 +139289,7 @@ async function clearSheetRange(target) {
138344
139289
  }
138345
139290
  async function addSheetTab(target) {
138346
139291
  const { version, result } = await mutate(target, "add tab", async (doc) => {
138347
- refuse(() => checkTabName(target.name));
139292
+ refuse2(() => checkTabName(target.name));
138348
139293
  if (doc.tabs.some((t) => t.name.toLowerCase() === target.name.toLowerCase())) {
138349
139294
  throw new ObjectsError(`a tab named '${target.name}' already exists`);
138350
139295
  }
@@ -138356,7 +139301,80 @@ async function addSheetTab(target) {
138356
139301
  });
138357
139302
  return { ...result, version };
138358
139303
  }
138359
- var MAX_ATTEMPTS = 4, refuse = (run) => {
139304
+ async function readXlsx(agentId, sourcePath) {
139305
+ if (!/\.xlsx$/i.test(sourcePath))
139306
+ throw new ObjectsError("sourcePath must end in .xlsx");
139307
+ const { provider, scope } = await clientFor(agentId);
139308
+ const source = normalizePath(sourcePath);
139309
+ let response;
139310
+ try {
139311
+ response = await provider.download(scope(source));
139312
+ } catch (error) {
139313
+ if (error instanceof FilesError && error.code === "NotFound") {
139314
+ throw new ObjectsError(`no file at '${source}' on this drive`);
139315
+ }
139316
+ throw error;
139317
+ }
139318
+ const tooBig = () => new ObjectsError(`${source} is over the ${MAX_XLSX_BYTES} byte limit (5 MiB) for an xlsx`);
139319
+ if (Number(response.headers.get("content-length")) > MAX_XLSX_BYTES) {
139320
+ await response.body?.cancel();
139321
+ throw tooBig();
139322
+ }
139323
+ const bytes = new Uint8Array(await response.arrayBuffer());
139324
+ if (bytes.length > MAX_XLSX_BYTES)
139325
+ throw tooBig();
139326
+ return bytes;
139327
+ }
139328
+ async function importSheetXlsx(input) {
139329
+ if (!input.path.endsWith(".sheet.json")) {
139330
+ throw new ObjectsError("a sheet path must end with '.sheet.json'");
139331
+ }
139332
+ const bytes = await readXlsx(input.agentId, input.sourcePath);
139333
+ const { tabs, dropped } = await parseXlsx(bytes);
139334
+ const draft = { tabs };
139335
+ await recalc(input.agentId, draft, []);
139336
+ sheetBody({ ...emptySheet(crypto.randomUUID(), input.title), tabs: draft.tabs });
139337
+ const created = await createObject({
139338
+ agentId: input.agentId,
139339
+ kind: "sheet",
139340
+ path: input.path,
139341
+ title: input.title
139342
+ });
139343
+ try {
139344
+ const { version } = await mutate({ agentId: input.agentId, id: created.id }, "import xlsx", async (doc) => {
139345
+ doc.tabs = draft.tabs;
139346
+ return { doc, result: null };
139347
+ });
139348
+ return { object: { ...created, fileVersion: version }, link: created.link, dropped };
139349
+ } catch (error) {
139350
+ if (error instanceof ObjectsError) {
139351
+ throw new ObjectsError(`created ${created.path} (id ${created.id}) but could not write the imported tabs: ${error.message}`);
139352
+ }
139353
+ throw error;
139354
+ }
139355
+ }
139356
+ async function exportSheetXlsx(target) {
139357
+ if (!/\.xlsx$/i.test(target.targetPath))
139358
+ throw new ObjectsError("targetPath must end in .xlsx");
139359
+ const { object, doc } = await load(target);
139360
+ const { bytes, dropped } = await buildXlsx(doc.tabs);
139361
+ const { provider, orgId, driveId, scope } = await clientFor(target.agentId);
139362
+ const path = normalizePath(target.targetPath);
139363
+ try {
139364
+ await provider.upload(scope(path), bytes, {
139365
+ contentType: XLSX_MIME,
139366
+ ifNoneMatch: target.overwrite ? undefined : "*",
139367
+ message: `export ${object.path}`
139368
+ });
139369
+ } catch (error) {
139370
+ if (error instanceof FilesError && error.code === "Conflict") {
139371
+ throw new ObjectsError(`a file already exists at '${path}'; pass overwrite: true to replace it`);
139372
+ }
139373
+ throw error;
139374
+ }
139375
+ return { path, link: buildAgentFsLiveUrl({ orgId, driveId, path }), dropped };
139376
+ }
139377
+ var MAX_ATTEMPTS = 4, refuse2 = (run) => {
138360
139378
  try {
138361
139379
  return run();
138362
139380
  } catch (error) {
@@ -138368,14 +139386,16 @@ var MAX_ATTEMPTS = 4, refuse = (run) => {
138368
139386
  const { rows, cols } = usedExtent(tab);
138369
139387
  return { name: tab.name, rows, cols, freezeRows: tab.freezeRows ?? 0 };
138370
139388
  }, listSheets = (input) => listObjects({ ...input, kind: "sheet" });
138371
- var init_service2 = __esm(() => {
139389
+ var init_service = __esm(() => {
138372
139390
  init_provider();
139391
+ init_constants3();
138373
139392
  init_agent_fs_identity();
138374
139393
  init_db4();
138375
139394
  init_objects();
138376
139395
  init_a1();
138377
139396
  init_engine2();
138378
139397
  init_format();
139398
+ init_xlsx();
138379
139399
  });
138380
139400
 
138381
139401
  // src/tools/sheets.ts
@@ -138549,11 +139569,48 @@ var objectOutputSchema2, CellValue, Grid, RANGE_HELP = "A1 range such as `Tasks!
138549
139569
  data: { yourAgentId: requestInfo.agentId, ...result.value }
138550
139570
  });
138551
139571
  });
139572
+ }, dropMessage = (dropped) => dropped.length ? `Dropped: ${dropped.join(", ")}.` : "Nothing dropped.", registerSheetImportXlsxTool = (server) => {
139573
+ createToolRegistrar(server)("sheet-import-xlsx", {
139574
+ title: "Import xlsx as sheet",
139575
+ annotations: WRITE,
139576
+ description: "Import an `.xlsx` file from your default agent-fs drive as a new sheet, as your own agent-fs identity. Create-only: refuses when the sheet path exists. Keeps tabs, values, formulas (recomputed), number formats, column widths and merges. `dropped` lists what the file had that a sheet cannot hold (styles, charts, comments, frozen panes, and so on). Limits: 5 MiB file, 20 tabs, 50,000 cells; nothing is created when a limit refuses.",
139577
+ inputSchema: object2({
139578
+ sourcePath: string2().min(1).describe("Drive path of the `.xlsx` file to import."),
139579
+ path: string2().min(1).describe("Drive path for the new sheet, ending in `.sheet.json`."),
139580
+ title: string2().max(200).optional()
139581
+ }),
139582
+ outputSchema
139583
+ }, async ({ sourcePath, path, title }, requestInfo) => {
139584
+ const result = await refusing2(requestInfo.agentId, () => importSheetXlsx({ agentId: requestInfo.agentId, sourcePath, path, title }));
139585
+ if ("error" in result)
139586
+ return result.error;
139587
+ const { object, link, dropped } = result.value;
139588
+ return toolOk(`Imported ${sourcePath} as sheet ${object.id} at ${object.path}${link ? ` (${link})` : ""}. ${dropMessage(dropped)}`, { data: { yourAgentId: requestInfo.agentId, ...result.value } });
139589
+ });
139590
+ }, registerSheetExportXlsxTool = (server) => {
139591
+ createToolRegistrar(server)("sheet-export-xlsx", {
139592
+ title: "Export sheet as xlsx",
139593
+ annotations: WRITE,
139594
+ description: "Export a sheet to an `.xlsx` file on your default agent-fs drive. Writes formulas with their cached values, number formats, column widths and merges. `dropped` lists what the file cannot carry (frozen panes, spilled array cells). Create-only: refuses when `targetPath` exists unless `overwrite` is true.",
139595
+ inputSchema: object2({
139596
+ id: string2().min(1).optional().describe(ID2),
139597
+ path: string2().min(1).optional().describe(PATH),
139598
+ targetPath: string2().min(1).describe("Drive path for the new file, ending in `.xlsx`."),
139599
+ overwrite: boolean().optional().describe("Replace `targetPath` when it exists.")
139600
+ }),
139601
+ outputSchema
139602
+ }, async ({ id, path, targetPath, overwrite }, requestInfo) => {
139603
+ const result = await refusing2(requestInfo.agentId, () => exportSheetXlsx({ agentId: requestInfo.agentId, id, path, targetPath, overwrite }));
139604
+ if ("error" in result)
139605
+ return result.error;
139606
+ const r = result.value;
139607
+ return toolOk(`Exported to ${r.path}${r.link ? ` (${r.link})` : ""}. ${dropMessage(r.dropped)}`, { data: { yourAgentId: requestInfo.agentId, ...r } });
139608
+ });
138552
139609
  };
138553
139610
  var init_sheets = __esm(() => {
138554
139611
  init_zod();
138555
139612
  init_objects();
138556
- init_service2();
139613
+ init_service();
138557
139614
  init_provider();
138558
139615
  init_utils();
138559
139616
  objectOutputSchema2 = looseObject({
@@ -138579,7 +139636,9 @@ var init_sheets = __esm(() => {
138579
139636
  formulas: array2(array2(unknown())).optional(),
138580
139637
  changed: number2().optional(),
138581
139638
  recalculated: number2().optional(),
138582
- cleared: number2().optional()
139639
+ cleared: number2().optional(),
139640
+ path: string2().optional(),
139641
+ dropped: array2(string2()).optional()
138583
139642
  };
138584
139643
  outputSchema = swarmToolOutputSchema(dataShape);
138585
139644
  WRITE = { readOnlyHint: false, idempotentHint: false };
@@ -138637,7 +139696,9 @@ var registerSkillCreateTool = (server) => {
138637
139696
  context: parsed.context,
138638
139697
  agent: parsed.agent,
138639
139698
  disableModelInvocation: parsed.disableModelInvocation,
138640
- userInvocable: parsed.userInvocable
139699
+ userInvocable: parsed.userInvocable,
139700
+ createdByAgentId: requestInfo.agentId,
139701
+ createdBy: await resolveTaskAuditUserId(requestInfo.auditSourceTaskId, requestInfo.agentId)
138641
139702
  });
138642
139703
  await installSkill2(requestInfo.agentId, skill.id);
138643
139704
  return toolOk(`Created and installed skill "${skill.name}".`, {
@@ -138653,6 +139714,7 @@ var registerSkillCreateTool = (server) => {
138653
139714
  };
138654
139715
  var init_skill_create = __esm(() => {
138655
139716
  init_zod();
139717
+ init_audit_user();
138656
139718
  init_db4();
138657
139719
  init_skill_parser();
138658
139720
  init_rbac();
@@ -138974,7 +140036,9 @@ var registerSkillInstallRemoteTool = (server) => {
138974
140036
  context: parsedMeta.context,
138975
140037
  agent: parsedMeta.agent,
138976
140038
  disableModelInvocation: parsedMeta.disableModelInvocation,
138977
- userInvocable: parsedMeta.userInvocable
140039
+ userInvocable: parsedMeta.userInvocable,
140040
+ createdByAgentId: requestInfo.agentId,
140041
+ createdBy: await resolveTaskAuditUserId(requestInfo.auditSourceTaskId, requestInfo.agentId)
138978
140042
  });
138979
140043
  return toolOk(`Installed remote skill "${skill.name}".`, {
138980
140044
  details: `Installed remote skill "${skill.name}" from ${args.sourceRepo}`,
@@ -138988,6 +140052,7 @@ var registerSkillInstallRemoteTool = (server) => {
138988
140052
  };
138989
140053
  var init_skill_install_remote = __esm(() => {
138990
140054
  init_zod();
140055
+ init_audit_user();
138991
140056
  init_db4();
138992
140057
  init_skill_parser();
138993
140058
  init_rbac();
@@ -139191,6 +140256,7 @@ var registerSkillSyncRemoteTool = (server) => {
139191
140256
  })() : await listSkills2({ type: "remote" });
139192
140257
  let updated = 0;
139193
140258
  const errors = [];
140259
+ const updatedBy = await resolveTaskAuditUserId(requestInfo.auditSourceTaskId, requestInfo.agentId);
139194
140260
  for (const skill of skills) {
139195
140261
  if (skill.isComplex)
139196
140262
  continue;
@@ -139221,7 +140287,9 @@ var registerSkillSyncRemoteTool = (server) => {
139221
140287
  disableModelInvocation: parsed.disableModelInvocation,
139222
140288
  userInvocable: parsed.userInvocable,
139223
140289
  sourceHash: newHash,
139224
- lastFetchedAt: now
140290
+ lastFetchedAt: now,
140291
+ updatedByAgentId: requestInfo.agentId ?? null,
140292
+ updatedBy
139225
140293
  });
139226
140294
  updated++;
139227
140295
  } else {
@@ -139255,6 +140323,7 @@ var registerSkillSyncRemoteTool = (server) => {
139255
140323
  };
139256
140324
  var init_skill_sync_remote = __esm(() => {
139257
140325
  init_zod();
140326
+ init_audit_user();
139258
140327
  init_db4();
139259
140328
  init_skill_parser();
139260
140329
  init_utils();
@@ -139392,7 +140461,11 @@ var SYSTEM_DEFAULT_SKILL_LOCKED_MESSAGE2 = "This skill is system-managed and can
139392
140461
  }
139393
140462
  updates.scope = args.scope;
139394
140463
  }
139395
- const skill = await updateSkill2(args.skillId, updates);
140464
+ const skill = await updateSkill2(args.skillId, {
140465
+ ...updates,
140466
+ updatedByAgentId: requestInfo.agentId,
140467
+ updatedBy: await resolveTaskAuditUserId(requestInfo.auditSourceTaskId, requestInfo.agentId)
140468
+ });
139396
140469
  if (!skill) {
139397
140470
  return toolErr("Update failed.", {
139398
140471
  details: "Failed to update skill.",
@@ -139410,6 +140483,7 @@ var SYSTEM_DEFAULT_SKILL_LOCKED_MESSAGE2 = "This skill is system-managed and can
139410
140483
  };
139411
140484
  var init_skill_update = __esm(() => {
139412
140485
  init_zod();
140486
+ init_audit_user();
139413
140487
  init_db4();
139414
140488
  init_skill_parser();
139415
140489
  init_rbac();
@@ -142021,7 +143095,7 @@ async function readScriptActionAllowlist() {
142021
143095
  const [row] = await getSwarmConfigs2({ scope: "global", key: UI_SPEC_SCRIPT_ACTIONS_KEY });
142022
143096
  if (row)
142023
143097
  return row.value;
142024
- const { getDeploymentEnvValue } = await import("./core-dxcy02sc.js");
143098
+ const { getDeploymentEnvValue } = await import("./core-kdehq26g.js");
142025
143099
  return getDeploymentEnvValue(UI_SPEC_SCRIPT_ACTIONS_KEY);
142026
143100
  }
142027
143101
  async function loadScriptActionLookups() {
@@ -143908,7 +144982,7 @@ async function emitBudgetRefusalSideEffects(ctx, inserted) {
143908
144982
  console.warn(`[budget-refusal-notify] Failed to create follow-up task for budget refusal (task=${ctx.task.id.slice(0, 8)}): ${err}`);
143909
144983
  }
143910
144984
  }
143911
- import("./event-bus-v4ywhc2p.js").then(({ workflowEventBus }) => {
144985
+ import("./event-bus-08t2b4y2.js").then(({ workflowEventBus }) => {
143912
144986
  workflowEventBus.emit("task.budget_refused", {
143913
144987
  taskId: ctx.task.id,
143914
144988
  agentId: ctx.agentId,
@@ -145050,7 +146124,7 @@ var registerCreateWorkflowTool = (server) => {
145050
146124
  ` + `- Agent-task config: { template, outputSchema?, agentId?, tags?, priority?, dir?, vcsRepo?, model? }.
145051
146125
  ` + "- FOREACH NODE: type 'foreach' runs its body once per item. Config: " + "{ over: <array or exact {{input}} token>, itemKey: <property name>, body: { type: <any executor except foreach>, config: {...} }, " + "concurrency?: <integer >= 1, items in flight; unbounded when absent>, failurePolicy?: 'fail-fast' | 'collect-outcomes' }. " + "The body config is interpolated once per item with {{item.*}} and {{index}}. Child steps use synthetic IDs " + "'<foreachNodeId>#<itemKey>'; the parent waits for every child and exposes one aggregate result to successors. " + "failurePolicy defaults from onNodeFailure ('continue' = collect-outcomes, else fail-fast); fail-fast cancels queued items. " + `retry-workflow-run on a failed fan-out reruns only failed and cancelled items.
145052
146126
  ` + "- TRIGGER SCHEMA: Optional 'triggerSchema' is a JSON-Schema object that validates incoming trigger payloads. " + "Supported keywords: type, required, properties, enum, const, items (recursive into arrays). " + `Other JSON-Schema keywords (oneOf/anyOf/$ref/pattern/format/additionalProperties) are silently ignored.
145053
- ` + "- WEBHOOK VERIFICATION: Webhook triggers use hmacSecret for all verification formats. " + "Omit verification for legacy HMAC-SHA256 over the raw body with fallback header scanning; " + "or set verification to { format: 'hmac-sha256', header }, { format: 'timestamped-hmac-sha256', header, toleranceSeconds? }, " + "{ format: 'token-equality', header }, or { format: 'standard-webhooks', toleranceSeconds? } " + "(standardwebhooks.com: webhook-id/webhook-timestamp/webhook-signature headers, hmacSecret is the whsec_ signing secret). Example: { type: 'webhook', hmacSecret: 'secret.SUPERAGENT_WEBHOOK_SECRET', " + `verification: { format: 'timestamped-hmac-sha256', header: 'X-Superagent-Signature', toleranceSeconds: 300 } }.
146127
+ ` + "- WEBHOOK VERIFICATION: Webhook triggers use hmacSecret for all verification formats. " + "Omit verification for legacy HMAC-SHA256 over the raw body with fallback header scanning; " + "or set verification to { format: 'hmac-sha256', header }, { format: 'hmac-sha1', header }, { format: 'timestamped-hmac-sha256', header, toleranceSeconds? }, " + "{ format: 'token-equality', header }, or { format: 'standard-webhooks', toleranceSeconds? } " + "(standardwebhooks.com: webhook-id/webhook-timestamp/webhook-signature headers, hmacSecret is the whsec_ signing secret). Example: { type: 'webhook', hmacSecret: 'secret.SUPERAGENT_WEBHOOK_SECRET', " + `verification: { format: 'timestamped-hmac-sha256', header: 'X-Superagent-Signature', toleranceSeconds: 300 } }.
145054
146128
  ` + "- WEBHOOK DELIVERY FILTER: optional filter on a webhook trigger drops deliveries after signature verification and before any run is saved " + "(200 { skipped: true, reason }). filter.headers and filter.body are allowlists (a string or an array of scalars); every field must match. " + "Header names are case-insensitive; values and JSON paths are exact, with no type coercion. " + 'preset "github" | "gitlab" | "standard-webhooks" selects where the deprecated events allowlist is read ' + "(X-GitHub-Event, X-Gitlab-Event, or JSON body type). events and eventHeader still work and are AND-ed with filter; eventHeader overrides preset. " + `Omit filter and events to accept every delivery.
145055
146129
  ` + "- WAIT NODE: type 'wait' pauses a workflow for a duration or until a named workflowEventBus event arrives. " + "See runbooks/workflows.md#wait-nodes for config shapes, ordering caveats, and built-in event names.",
145056
146130
  inputSchema: object2({
@@ -145058,7 +146132,7 @@ var registerCreateWorkflowTool = (server) => {
145058
146132
  key: AssetKeySchema.optional().describe("Logical namespace. Defaults to a shared/workflow:<id>/ resource key."),
145059
146133
  description: string2().optional().describe("Description of what this workflow does"),
145060
146134
  definition: WorkflowDefinitionSchema.describe("The workflow definition with nodes (each node has id, type, config, and optional next/retry/validation)"),
145061
- triggers: array2(TriggerConfigSchema).optional().describe("Optional trigger configurations (webhook, schedule, event). A webhook trigger accepts filter (headers and body allowlists) and preset (github, gitlab, standard-webhooks). events and eventHeader remain a deprecated alias of one filter clause. Verification formats: legacy omitted verification, hmac-sha256, timestamped-hmac-sha256, token-equality, standard-webhooks."),
146135
+ triggers: array2(TriggerConfigSchema).optional().describe("Optional trigger configurations (webhook, schedule, event). A webhook trigger accepts filter (headers and body allowlists) and preset (github, gitlab, standard-webhooks). events and eventHeader remain a deprecated alias of one filter clause. Verification formats: legacy omitted verification, hmac-sha256, hmac-sha1, timestamped-hmac-sha256, token-equality, standard-webhooks."),
145062
146136
  cooldown: CooldownConfigSchema.optional().describe("Optional cooldown configuration to prevent re-triggering too frequently"),
145063
146137
  input: record2(string2(), InputValueSchema).optional().describe("Optional input values resolved at execution time (env vars like VAR_NAME, secrets secret.NAME, or literals). Env var and secret references require config.read.secrets (the lead agent)."),
145064
146138
  dir: string2().min(1).startsWith("/").optional().describe("Default working directory for all agent-task nodes (absolute path, e.g. /tmp/workspace)"),
@@ -145098,8 +146172,8 @@ var registerCreateWorkflowTool = (server) => {
145098
146172
  if (refKeys.length > 0 && !await agentMaySetServerRefInput(requestInfo.agentId)) {
145099
146173
  return toolErr(serverRefInputDeniedMessage(refKeys));
145100
146174
  }
145101
- const createdBy = await resolveTaskAuditUserId(requestInfo.sourceTaskId, requestInfo.agentId) ?? undefined;
145102
- const assetKey = key ? await authorizeAssetKeyWrite(key, createdBy) : undefined;
146175
+ const createdBy = await resolveTaskAuditUserId(requestInfo.auditSourceTaskId, requestInfo.agentId) ?? undefined;
146176
+ const assetKey = key ? await authorizeAssetKeyWrite(key, await resolveTaskAuditUserId(requestInfo.sourceTaskId, requestInfo.agentId)) : undefined;
145103
146177
  const workflow = await createWorkflow2({
145104
146178
  key: assetKey,
145105
146179
  name,
@@ -145398,7 +146472,7 @@ async function patchWorkflowDefinition(options) {
145398
146472
  if (!existing)
145399
146473
  return { ok: false, reason: "not_found" };
145400
146474
  if (options.serverRefInputAllowed === false) {
145401
- const refKeys = serverRefInputKeys(existing.input);
146475
+ const refKeys = serverRefInputKeys(existing.input, updates?.params ?? existing.params);
145402
146476
  if (refKeys.length > 0) {
145403
146477
  return { ok: false, reason: "forbidden", errors: [serverRefInputDeniedMessage(refKeys)] };
145404
146478
  }
@@ -145427,7 +146501,12 @@ async function patchWorkflowDefinition(options) {
145427
146501
  } else {
145428
146502
  version = (await snapshotWorkflow(id, snapshotAgentId)).version;
145429
146503
  }
145430
- const workflow = await updateWorkflow2(id, { ...updates, definition: patchResult.definition });
146504
+ const workflow = await updateWorkflow2(id, {
146505
+ ...updates,
146506
+ definition: patchResult.definition,
146507
+ updatedBy: updates?.updatedBy ?? null,
146508
+ updatedByAgentId: snapshotAgentId ?? null
146509
+ });
145431
146510
  if (!workflow)
145432
146511
  return { ok: false, reason: "not_found" };
145433
146512
  return { ok: true, workflow, version, definition: patchResult.definition };
@@ -145476,10 +146555,10 @@ var registerPatchWorkflowTool = (server) => {
145476
146555
  })
145477
146556
  }, async ({ id, key, update, delete: del, create, onNodeFailure, triggerSchema }, requestInfo) => {
145478
146557
  try {
145479
- const updatedBy = await resolveTaskAuditUserId(requestInfo.sourceTaskId, requestInfo.agentId) ?? undefined;
146558
+ const updatedBy = await resolveTaskAuditUserId(requestInfo.auditSourceTaskId, requestInfo.agentId) ?? undefined;
145480
146559
  const updates = {};
145481
146560
  if (key !== undefined) {
145482
- updates.key = await authorizeAssetKeyWrite(key, updatedBy);
146561
+ updates.key = await authorizeAssetKeyWrite(key, await resolveTaskAuditUserId(requestInfo.sourceTaskId, requestInfo.agentId));
145483
146562
  }
145484
146563
  if (triggerSchema !== undefined) {
145485
146564
  updates.triggerSchema = triggerSchema;
@@ -145568,7 +146647,7 @@ var registerPatchWorkflowNodeTool = (server) => {
145568
146647
  })
145569
146648
  }, async ({ id, nodeId, ...nodeFields }, requestInfo) => {
145570
146649
  try {
145571
- const updatedBy = await resolveTaskAuditUserId(requestInfo.sourceTaskId, requestInfo.agentId) ?? undefined;
146650
+ const updatedBy = await resolveTaskAuditUserId(requestInfo.auditSourceTaskId, requestInfo.agentId) ?? undefined;
145572
146651
  const result = await patchWorkflowDefinition({
145573
146652
  id,
145574
146653
  patch: { update: [{ nodeId, node: nodeFields }] },
@@ -145843,14 +146922,14 @@ var registerUpdateWorkflowTool = (server) => {
145843
146922
  createToolRegistrar(server)("update-workflow", {
145844
146923
  title: "Update Workflow",
145845
146924
  annotations: { destructiveHint: false },
145846
- description: "Update an existing workflow's name, description, definition, triggers, cooldown, input, triggerSchema, or enabled state. " + "Creates a version snapshot before applying changes. " + "TRIGGER SCHEMA: pass 'triggerSchema' as a JSON-Schema object to set/replace, or 'null' to clear. " + "Supported JSON-Schema keywords: type, required, properties, enum, const, items (recursive into arrays). " + "Other JSON-Schema keywords (oneOf/anyOf/$ref/pattern/format/additionalProperties) are silently ignored. " + "WEBHOOK VERIFICATION: webhook triggers use hmacSecret for all verification formats. " + "Omit verification for legacy HMAC-SHA256 over the raw body with fallback header scanning; " + "or set verification to { format: 'hmac-sha256', header }, { format: 'timestamped-hmac-sha256', header, toleranceSeconds? }, " + "{ format: 'token-equality', header }, or { format: 'standard-webhooks', toleranceSeconds? } " + "(standardwebhooks.com: webhook-id/webhook-timestamp/webhook-signature headers, hmacSecret is the whsec_ signing secret). " + "WEBHOOK DELIVERY FILTER: optional filter on a webhook trigger drops deliveries after signature verification and before any run is saved " + "(200 { skipped: true, reason }). filter.headers and filter.body are allowlists (a string or an array of scalars); every field must match. " + "Header names are case-insensitive; values and JSON paths are exact, with no type coercion. " + 'preset "github" | "gitlab" | "standard-webhooks" selects where the deprecated events allowlist is read ' + "(X-GitHub-Event, X-Gitlab-Event, or JSON body type). events and eventHeader still work and are AND-ed with filter; eventHeader overrides preset. " + "Omit filter and events to accept every delivery.",
146925
+ description: "Update an existing workflow's name, description, definition, triggers, cooldown, input, triggerSchema, or enabled state. " + "Creates a version snapshot before applying changes. " + "TRIGGER SCHEMA: pass 'triggerSchema' as a JSON-Schema object to set/replace, or 'null' to clear. " + "Supported JSON-Schema keywords: type, required, properties, enum, const, items (recursive into arrays). " + "Other JSON-Schema keywords (oneOf/anyOf/$ref/pattern/format/additionalProperties) are silently ignored. " + "WEBHOOK VERIFICATION: webhook triggers use hmacSecret for all verification formats. " + "Omit verification for legacy HMAC-SHA256 over the raw body with fallback header scanning; " + "or set verification to { format: 'hmac-sha256', header }, { format: 'hmac-sha1', header }, { format: 'timestamped-hmac-sha256', header, toleranceSeconds? }, " + "{ format: 'token-equality', header }, or { format: 'standard-webhooks', toleranceSeconds? } " + "(standardwebhooks.com: webhook-id/webhook-timestamp/webhook-signature headers, hmacSecret is the whsec_ signing secret). " + "WEBHOOK DELIVERY FILTER: optional filter on a webhook trigger drops deliveries after signature verification and before any run is saved " + "(200 { skipped: true, reason }). filter.headers and filter.body are allowlists (a string or an array of scalars); every field must match. " + "Header names are case-insensitive; values and JSON paths are exact, with no type coercion. " + 'preset "github" | "gitlab" | "standard-webhooks" selects where the deprecated events allowlist is read ' + "(X-GitHub-Event, X-Gitlab-Event, or JSON body type). events and eventHeader still work and are AND-ed with filter; eventHeader overrides preset. " + "Omit filter and events to accept every delivery.",
145847
146926
  inputSchema: object2({
145848
146927
  id: string2().uuid().describe("Workflow ID to update"),
145849
146928
  key: AssetKeySchema.optional().describe("Move to a logical namespace."),
145850
146929
  name: string2().optional().describe("New name for the workflow"),
145851
146930
  description: string2().optional().describe("New description"),
145852
146931
  definition: WorkflowDefinitionSchema.optional().describe("New workflow definition"),
145853
- triggers: array2(TriggerConfigSchema).optional().describe("Replacement trigger list. A webhook trigger accepts filter (headers and body allowlists) and preset (github, gitlab, standard-webhooks). events and eventHeader remain a deprecated alias of one filter clause. Verification formats: legacy omitted verification, hmac-sha256, timestamped-hmac-sha256, token-equality, standard-webhooks."),
146932
+ triggers: array2(TriggerConfigSchema).optional().describe("Replacement trigger list. A webhook trigger accepts filter (headers and body allowlists) and preset (github, gitlab, standard-webhooks). events and eventHeader remain a deprecated alias of one filter clause. Verification formats: legacy omitted verification, hmac-sha256, hmac-sha1, timestamped-hmac-sha256, token-equality, standard-webhooks."),
145854
146933
  cooldown: CooldownConfigSchema.optional().nullable().describe("New cooldown configuration (null to remove)"),
145855
146934
  input: record2(string2(), InputValueSchema).optional().nullable().describe("New input values (null to remove)"),
145856
146935
  dir: string2().min(1).startsWith("/").optional().nullable().describe("Default working directory for all agent-task nodes (null to remove)"),
@@ -145900,12 +146979,12 @@ var registerUpdateWorkflowTool = (server) => {
145900
146979
  return toolErr(`Invalid definition: ${modelErrors.join("; ")}`);
145901
146980
  }
145902
146981
  }
145903
- const refKeys = serverRefInputKeys(input !== undefined ? input : definition ? existing.input : undefined);
146982
+ const refKeys = input !== undefined || definition ? serverRefInputKeys(input !== undefined ? input : existing.input, existing.params) : [];
145904
146983
  if (refKeys.length > 0 && !(requestInfo.agentId && await agentMaySetServerRefInput(requestInfo.agentId))) {
145905
146984
  return toolErr(serverRefInputDeniedMessage(refKeys));
145906
146985
  }
145907
- const updatedBy = await resolveTaskAuditUserId(requestInfo.sourceTaskId, requestInfo.agentId) ?? undefined;
145908
- const assetKey = key === undefined ? undefined : await authorizeAssetKeyWrite(key, updatedBy);
146986
+ const updatedBy = await resolveTaskAuditUserId(requestInfo.auditSourceTaskId, requestInfo.agentId) ?? undefined;
146987
+ const assetKey = key === undefined ? undefined : await authorizeAssetKeyWrite(key, await resolveTaskAuditUserId(requestInfo.sourceTaskId, requestInfo.agentId));
145909
146988
  const { workflow, version } = await snapshotAndUpdateWorkflow(id, {
145910
146989
  key: assetKey,
145911
146990
  name,
@@ -146256,6 +147335,8 @@ async function createServer(opts = {}) {
146256
147335
  registerSheetAppendRowsTool(server);
146257
147336
  registerSheetClearRangeTool(server);
146258
147337
  registerSheetAddTabTool(server);
147338
+ registerSheetImportXlsxTool(server);
147339
+ registerSheetExportXlsxTool(server);
146259
147340
  registerBoardCreateTool(server);
146260
147341
  registerBoardGetTool(server);
146261
147342
  registerBoardListTool(server);
@@ -146498,4 +147579,4 @@ var init_server = __esm(() => {
146498
147579
  loggedToolAllowlistWarnings = new Set;
146499
147580
  });
146500
147581
 
146501
- 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, stripSiblingBlock, init_sibling_block, createTaskWithSiblingAwareness, init_sibling_awareness, dispatchScheduleTarget, calculateNextRun2, startScheduler2, stopScheduler2, runScheduleNow2, init_scheduler, ExtensionAssetConflictError, hashOf, scriptHash, liveScriptSpec, liveWorkflowSpec, skillSpecOf, liveSkillSpec, skillHash, init_assets, ExtensionOwnershipError, getExtensionFiles, getExtensionById, getExtensionByName, listExtensions, listExtensionVersions, updateExtensionMeta, listExtensionRuns, init_db, SDK_ALLOWLIST, mcpToolNameForSdkMethod, init_sdk_allowlist, MCP_OVERFLOW_NAMESPACE, mcpOverflowAuthError, init_kv_overflow, hasKvViewArgs, resolveKvView, init_kv_view, COLOR_LITERAL_THRESHOLD, countColorLiterals, init_color_literals, toolErr, createToolRegistrar, init_utils, handleMcpBridge, init_mcp_bridge, Redacted, init_redacted, SCRIPT_SDK_RESPONSE_LIMIT_BYTES, readScriptSdkJsonResponse, init_response_limit, retry, init_retry, ExtensionConfigError, init_loader, ExtensionLifecycleError, setExtensionLoopbackBaseUrl, enableExtension, disableExtension, activateVersion, ExtensionAssetsInvalidError, installExtensionWithAssets, uninstallExtension, reloadExtension, loadEnabledExtensions, stopExtensionRuntime, init_lifecycle, ExtensionAbortedError2, isRegistered2, isExtensionAgentId2, getExtensionBridgeToken2, resolveBridgeCallOrigin2, extensionIdForAgent2, runContext2, registerLoaded2, unregister2, listRegistered2, dispatchPre2, dispatchPost2, init_dispatcher, resolveIdentity, renderIdentity, init_identity, recordUnmappedIdentity, init_unmapped_identities, getDeliveredSlackMessageTs, foldIntoPendingSlackTask, init_slack_fold, MAX_TASK_ATTACHMENT_BYTES, recordTaskAttachmentUpload, scopeFromAttachment, backingProviderId, init_task_attachment_store, transcribeAudioNotes, init_transcription, init_templates, buildEffectiveText, bufferedFileFailures, fetchSlackFiles, createSlackTaskWithFiles, attachSlackFilesToDraft, notifySlackFileFailures, init_inbound_files, pendingWorkForAgent, countPoolRuntimes, computeDesired, init_demand, isRuntimePoolWakeable, isAgentReachable, isAgentOnDemand, init_reachability, isAddressedToOtherUser, broadcastMatches, routeMessage, extractTaskFromMessage, init_router, extractSlackMessageText, slackInboundMessageText, collectSlackMessageFiles, init_message_text, createAdditiveBuffer, init_additive_buffer, 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, isGitHubEnabled, initGitHub, verifyWebhookSignature, getWorkerInstallationToken, init_app, handlePullRequest, handleIssue, handleComment, handlePullRequestReview, handleCheckRun, handleCheckSuite, handleWorkflowRun, init_github, isGitLabEnabled, initGitLab, verifyGitLabWebhook, handleMergeRequest, handleIssue2, handleNote, handlePipeline, init_gitlab, isChatSdkEnabled, getChatSdkConfig, init_config, errorMessage, init_logger, resolveAdapterApiUrl, init_adapters, trackBackground, init_background, TelegramBotApiError, callTelegramBotApi, init_telegram_api, isTrustedTeamsServiceUrl, init_teams_origin, getSessionLabels, rememberSessionLabel, getResourceSessionLabels, init_session_labels, isChatSdkStopping, startChatSdk, getChatInstance, isChatAdapterConfigured, getChatSdkHealth, stopChatSdk, init_runtime, getJiraMetadata, updateJiraMetadata, clearJiraMetadata, init_metadata, registerJiraWebhook, deleteJiraWebhook, init_webhook_lifecycle, isJiraEnabled, initJira, init_app2, handleJiraWebhook, init_webhook, init_jira, handleAgentSessionEvent, handleIssueUpdate, handleIssueDelete, handleAgentSessionPrompted, init_sync, isLinearEnabled, initLinear, init_app3, init_linear, init_slack, verifyPageSession, LEGACY_PAGE_SESSION_COOKIE, isCookieSafePageId, extractPageSession, extractLegacyPageSession, extractAndVerifyCookie, isLocalDevPageRequest, pageSessionSetCookies, init_page_session, resolveHttpRequestAuth, init_auth, getDeploymentEnvValue2, loadGlobalConfigsIntoEnv2, reloadGlobalConfigsAndIntegrations2, scheduleIntegrationsReload2, handleCore2, init_core, runTaskUiScriptAction, init_script_actions, REBOOT_RETRY_PIN_TAG2, getPinCandidateAgent2, resolveLeadOnlyRecoveryAssignment2, getResumeGeneration2, getNextResumeGeneration2, inheritedModelSelection2, nextFallback2, createWorkerTaskFollowUp2, createResumeFollowUp2, createRerouteDecisionTask2, createPoolStarvationDecisionTask2, init_worker_follow_up, MCP_MAX_TOOL_INPUT_ELEMENTS, MCP_MAX_REQUEST_BODY_BYTES, init_mcp_limits, userCtx, init_task_tool_ctx, resolveRequestPrincipal, requestPrincipal, agentFirstPrincipal, requireAuthKind, rejectGuest, init_request_principal, resolveTaskRequester, init_task_requester, handleApps, init_apps, cancelApprovalRequest, cancelApprovalRequestAndRun, init_approval_cancel, getUserCommsPrefs, init_requester_comms, getTaskDetailsInputSchema, getTaskDetailsOutputSchema, getTaskDetailsHandler, init_get_task_details, cancelTaskInputSchema, cancelTaskOutputSchema, cancelTaskHandler, init_cancel_task, DbQueryTimeoutError, DbQueryConcurrencyCapError, executeReadOnlyQuery, getDbQueryHttpBudgetMs, init_db_query_shared, assertSelectOnlyQuery, executeReadOnlyQueryGated, handleDbQuery, init_db_query, snapshotMetric, init_version2, AssetKeyAuthorizationError, authorizeAssetKeyWrite, init_asset_key_auth, getPageEditCounter, init_page_versions, snapshotPage, init_version3, DEFAULT_THEME_ID, THEME_PRESET_IDS, getThemePreset, init_presets, readThemeFields, init_page_fields, assertOAuthAppUrlsSafe, assertOAuthEgressUrlSafe, init_app_validation, listOAuthPresets, listOAuthPresetIds, getOAuthPreset, hydrateOAuthAppFromPreset, init_presets2, scopedResourceScopeIdSchema, resolveScopedResourceId, init_scoped_resource, MemoryKeyError, init_key_guard, refreshLinks, init_link_resolver, indexMemoryContent, init_index_content, dedupeMemoryDocumentIds, recordMemoryAccesses, recordRetrievals, init_retrieval, ExplicitSelfDuplicateError, applyRating, init_store, shouldPersistAutomaticTaskMemory, init_automatic_task_gate, guardTerminalTaskResultWrite, init_terminal_result_guard, getTasksInputSchema, getTasksOutputSchema, getTasksHandler, init_get_tasks, requiresLeadToWrite, reservedNamespaceError, privateNamespaceError, reservedRoomKeyError, init_kv_reserved_namespaces, updateMcpServerChecked, init_mcp_server_checked_update, updateTouchesStdioExecution, init_mcp_server_stdio_gate, canReadMemory, init_access, getLinksForMemory, init_links_store, attachDemotionEvidence, init_demotion_evidence, expandCandidatesWithGraph, init_graph_expansion, isApiDraining, drainApi, init_api_drain, markKapsoMessageRead, sendKapsoReaction, init_client, getKapsoConfig, getKapsoNumberMapping, markKapsoMessageSeen, init_config2, changesAllowMerge, init_repo_merge_policy, updateSwarmRepoChecked, init_repo_checked_update, getCombConfig, init_config3, resolveRoomNamespace, roomRequestInfo, authorizeRoomNamespace, sessionAccessTopic, sessionPresenceRoot, init_auth2, RoomOperationSchema, init_document, removeAwarenessStates, init_awareness, roomTopic, decodeRoomSnapshot, roomView, getRoom, changeRoom, applyRoomUpdate, resetRoom, sweepRooms, closeRooms, removeNamespaceRooms, init_rooms, init_scheduler2, MEMORY_KEYS_DEFAULT_PREFIX, MEMORY_KEYS_MAX_LIMIT, estimateTokens, posteriorMean, listMemoryKeys, checkChunkIntegrity, getMemoryChunks, getPosteriorsByIds, init_key_browser, createEvent, createEventsBatch, getEventCountsFiltered, getEventsFiltered, init_events, mergeScheduleTiming, validateRecurringTiming, init_validate, followUpThreadForSourceTask, evaluateFollowUpRedelegation, init_follow_up_redelegation_guard, checkOutputSchemaShape, sendTaskOutputSchema, sendTaskHandler, init_send_task, steerTaskUserInputSchema, steerTaskOutputSchema, steerTaskHandler, init_steer_task, skipReasonFrom, finalizeSkippedTaskReaction, init_task_skip, IMPROVEMENT_TEXT_MAX, IMPROVEMENT_STATUSES, IMPROVEMENT_SOURCES, ImprovementError, isImprovementsEnabled, getImprovement, listImprovements, createImprovement, approveAndSend, discardImprovement, improvementLeakHints, init_improvements, 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 };
147582
+ export { safeParse, getObjectShape, getLiteralValue, init_zod_compat, LATEST_PROTOCOL_VERSION, DEFAULT_NEGOTIATED_PROTOCOL_VERSION, SUPPORTED_PROTOCOL_VERSIONS, isJSONRPCRequest, isJSONRPCResultResponse, ErrorCode, isJSONRPCErrorResponse, JSONRPCMessageSchema, EmptyResultSchema, isInitializeRequest, InitializeResultSchema, CreateTaskResultSchema, ListResourcesResultSchema, ListResourceTemplatesResultSchema, ReadResourceResultSchema, ResourceListChangedNotificationSchema, ListPromptsResultSchema, GetPromptResultSchema, PromptListChangedNotificationSchema, ListToolsResultSchema, CallToolResultSchema, ToolListChangedNotificationSchema, ListChangedOptionsBaseSchema, CreateMessageRequestSchema, CreateMessageResultSchema, CreateMessageResultWithToolsSchema, ElicitRequestSchema, ElicitResultSchema, CompleteResultSchema, McpError, init_types, Protocol, mergeCapabilities, init_protocol, AjvJsonSchemaValidator, init_ajv_provider, assertToolsCallTaskCapability, assertClientRequestTaskCapability, init_helpers, McpServer, init_mcp, referencedBundlePaths, skillDirs, init_manifest_format, recoverIncompleteRuns, init_recovery, handleWebhookTrigger, verifyHmacSignature, decodeStandardWebhookSecret, verifyStandardWebhookSignature, verifyTokenEquality, WebhookError, init_triggers, snapshotAndUpdateWorkflow, init_version, applyPreTaskCreate, init_apply_task_create, RawLlmConfigSchema, RawLlmOutputSchema, executeRawLlm, init_raw_llm, getExecutorRegistry2, initWorkflows2, init_workflows, isGitHubEnabled, initGitHub, verifyWebhookSignature, getWorkerInstallationToken, init_app, isReservedProviderEvent, init_event_waits, stripSiblingBlock, init_sibling_block, createTaskWithSiblingAwareness, init_sibling_awareness, dispatchScheduleTarget, calculateNextRun2, startScheduler2, stopScheduler2, runScheduleNow2, init_scheduler, ExtensionAssetConflictError, hashOf, scriptHash, liveScriptSpec, liveWorkflowSpec, skillSpecOf, liveSkillSpec, skillHash, init_assets, ExtensionOwnershipError, getExtensionFiles, getExtensionById, getExtensionByName, listExtensions, listExtensionVersions, updateExtensionMeta, listExtensionRuns, init_db, SDK_ALLOWLIST, mcpToolNameForSdkMethod, init_sdk_allowlist, MCP_OVERFLOW_NAMESPACE, mcpOverflowAuthError, init_kv_overflow, hasKvViewArgs, resolveKvView, init_kv_view, COLOR_LITERAL_THRESHOLD, countColorLiterals, init_color_literals, toolErr, createToolRegistrar, init_utils, handleMcpBridge, init_mcp_bridge, Redacted, init_redacted, SCRIPT_SDK_RESPONSE_LIMIT_BYTES, readScriptSdkJsonResponse, init_response_limit, retry, init_retry, ExtensionConfigError, init_loader, ExtensionLifecycleError, setExtensionLoopbackBaseUrl, enableExtension, disableExtension, activateVersion, ExtensionAssetsInvalidError, installExtensionWithAssets, uninstallExtension, reloadExtension, loadEnabledExtensions, stopExtensionRuntime, init_lifecycle, ExtensionAbortedError2, isRegistered2, isExtensionAgentId2, getExtensionBridgeToken2, resolveBridgeCallOrigin2, extensionIdForAgent2, runContext2, registerLoaded2, unregister2, hasNativeToolHandlers2, listRegistered2, dispatchPre2, dispatchPost2, init_dispatcher, resolveIdentity, renderIdentity, init_identity, dismissedNamespace, dismissUnmappedIdentity, restoreUnmappedIdentity, recordUnmappedIdentity, init_unmapped_identities, getDeliveredSlackMessageTs, foldIntoPendingSlackTask, init_slack_fold, MAX_TASK_ATTACHMENT_BYTES, recordTaskAttachmentUpload, scopeFromAttachment, backingProviderId, init_task_attachment_store, transcribeAudioNotes, init_transcription, init_templates, buildEffectiveText, bufferedFileFailures, fetchSlackFiles, createSlackTaskWithFiles, attachSlackFilesToDraft, notifySlackFileFailures, init_inbound_files, pendingWorkForAgent, countPoolRuntimes, computeDesired, init_demand, isRuntimePoolWakeable, isAgentReachable, isAgentOnDemand, init_reachability, isAddressedToOtherUser, broadcastMatches, routeMessage, extractTaskFromMessage, init_router, extractSlackMessageText, slackInboundMessageText, collectSlackMessageFiles, init_message_text, createAdditiveBuffer, init_additive_buffer, isAgentMailEnabled, initAgentMail, verifyAgentMailWebhook, isInboxAllowed, isSenderAllowed, handleMessageReceived, init_agentmail, isAzureDevOpsEnabled, initAzureDevOps, verifyAzureDevOpsWebhook, repointTrackerSyncBySwarmId, init_tracker, isAzureDevOpsUrl, canonicalAzureDevOpsRepoUrl, parseAzureDevOpsRepoUrl, init_azure_devops, createdPullRequestOf, commentedPayloadOf, handlePullRequestCreated, handlePullRequestCommented, handleWorkItemCreated, handleWorkItemUpdated, handleWorkItemCommented, handleWorkItemDeleted, handleWorkItemRestored, initAzureDevOpsOutbound, init_azure_devops2, enqueueAuditRow, enqueueAdmissionRow, flushAuditBuffer, startAuditWriter, stopAuditWriter, startAuditGc, stopAuditGc, init_rbac_audit, getTelemetryIngestAnchor, init_telemetry_ingest_anchor, initApiTelemetry, syncTelemetryEnabled, init_telemetry_enable, isBitbucketEnabled, initBitbucket, verifyBitbucketWebhook, isDuplicateDelivery, markDeliveryProcessed, pullRequestEventOf, pullRequestCommentEventOf, handlePullRequestCreated2, handlePullRequestCommentCreated, handlePullRequestClosed, init_bitbucket, handlePullRequest, handleIssue, handleComment, handlePullRequestReview, handleCheckRun, handleCheckSuite, handleWorkflowRun, init_github, isGitLabEnabled, initGitLab, verifyGitLabWebhook, handleMergeRequest, handleIssue2, handleNote, handlePipeline, init_gitlab, isChatSdkEnabled, getChatSdkConfig, init_config, errorMessage, init_logger, resolveAdapterApiUrl, init_adapters, trackBackground, init_background, TelegramBotApiError, callTelegramBotApi, init_telegram_api, isTrustedTeamsServiceUrl, init_teams_origin, getSessionLabels, rememberSessionLabel, getResourceSessionLabels, init_session_labels, isChatSdkStopping, startChatSdk, getChatInstance, isChatAdapterConfigured, getChatSdkHealth, stopChatSdk, init_runtime, getJiraMetadata, updateJiraMetadata, clearJiraMetadata, init_metadata, registerJiraWebhook, deleteJiraWebhook, init_webhook_lifecycle, isJiraEnabled, initJira, init_app2, handleJiraWebhook, init_webhook, init_jira, handleAgentSessionEvent, handleIssueUpdate, handleIssueDelete, handleAgentSessionPrompted, init_sync, isLinearEnabled, initLinear, init_app3, init_linear, init_slack, verifyPageSession, LEGACY_PAGE_SESSION_COOKIE, isCookieSafePageId, extractPageSession, extractLegacyPageSession, extractAndVerifyCookie, isLocalDevPageRequest, pageSessionSetCookies, init_page_session, resolveHttpRequestAuth, init_auth, getDeploymentEnvValue2, loadGlobalConfigsIntoEnv2, reloadGlobalConfigsAndIntegrations2, scheduleIntegrationsReload2, handleCore2, init_core, runTaskUiScriptAction, init_script_actions, REBOOT_RETRY_PIN_TAG2, getPinCandidateAgent2, resolveLeadOnlyRecoveryAssignment2, getResumeGeneration2, getNextResumeGeneration2, inheritedModelSelection2, nextFallback2, createWorkerTaskFollowUp2, createResumeFollowUp2, createRerouteDecisionTask2, createPoolStarvationDecisionTask2, init_worker_follow_up, MCP_MAX_TOOL_INPUT_ELEMENTS, MCP_MAX_REQUEST_BODY_BYTES, init_mcp_limits, userCtx, init_task_tool_ctx, resolveRequestPrincipal, requestPrincipal, agentFirstPrincipal, requireAuthKind, rejectGuest, init_request_principal, resolveTaskRequester, init_task_requester, handleApps, init_apps, parseScene, init_elements, MAX_OBJECT_BYTES, init_write_object, cancelApprovalRequest, cancelApprovalRequestAndRun, init_approval_cancel, getUserCommsPrefs, init_requester_comms, getTaskDetailsInputSchema, getTaskDetailsOutputSchema, getTaskDetailsHandler, init_get_task_details, cancelTaskInputSchema, cancelTaskOutputSchema, cancelTaskHandler, init_cancel_task, DbQueryTimeoutError, DbQueryConcurrencyCapError, executeReadOnlyQuery, getDbQueryHttpBudgetMs, init_db_query_shared, assertSelectOnlyQuery, executeReadOnlyQueryGated, handleDbQuery, init_db_query, snapshotMetric, init_version2, AssetKeyAuthorizationError, authorizeAssetKeyWrite, init_asset_key_auth, getPageEditCounter, init_page_versions, snapshotPage, init_version3, DEFAULT_THEME_ID, THEME_PRESET_IDS, getThemePreset, init_presets, readThemeFields, init_page_fields, assertOAuthAppUrlsSafe, assertOAuthEgressUrlSafe, init_app_validation, listOAuthPresets, listOAuthPresetIds, getOAuthPreset, hydrateOAuthAppFromPreset, init_presets2, scopedResourceScopeIdSchema, resolveScopedResourceId, init_scoped_resource, MemoryKeyError, init_key_guard, refreshLinks, init_link_resolver, indexMemoryContent, init_index_content, dedupeMemoryDocumentIds, recordMemoryAccesses, recordRetrievals, init_retrieval, ExplicitSelfDuplicateError, applyRating, init_store, shouldPersistAutomaticTaskMemory, init_automatic_task_gate, guardTerminalTaskResultWrite, init_terminal_result_guard, getTasksInputSchema, getTasksOutputSchema, getTasksHandler, init_get_tasks, requiresLeadToWrite, reservedNamespaceError, privateNamespaceError, reservedRoomKeyError, init_kv_reserved_namespaces, updateMcpServerChecked, init_mcp_server_checked_update, updateTouchesStdioExecution, init_mcp_server_stdio_gate, canReadMemory, init_access, getLinksForMemory, init_links_store, attachDemotionEvidence, init_demotion_evidence, expandCandidatesWithGraph, init_graph_expansion, isApiDraining, drainApi, init_api_drain, markKapsoMessageRead, sendKapsoReaction, init_client, getKapsoConfig, getKapsoNumberMapping, markKapsoMessageSeen, init_config2, changesMergePolicy, init_repo_merge_policy, updateSwarmRepoChecked, init_repo_checked_update, getCombConfig, init_config3, resolveRoomNamespace, roomRequestInfo, authorizeRoomNamespace, sessionAccessTopic, sessionPresenceRoot, init_auth2, RoomOperationSchema, init_document, removeAwarenessStates, init_awareness, roomTopic, decodeRoomSnapshot, roomView, getRoom, changeRoom, applyRoomUpdate, resetRoom, sweepRooms, closeRooms, removeNamespaceRooms, init_rooms, init_scheduler2, MEMORY_KEYS_DEFAULT_PREFIX, MEMORY_KEYS_MAX_LIMIT, estimateTokens, posteriorMean, listMemoryKeys, checkChunkIntegrity, getMemoryChunks, getPosteriorsByIds, init_key_browser, createEvent, createEventsBatch, getEventCountsFiltered, getEventsFiltered, init_events, mergeScheduleTiming, validateRecurringTiming, changesScheduleTarget, init_validate, 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 };