@desplega.ai/agent-swarm 2.11.0 → 2.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (382) hide show
  1. package/dist/acp-adapter-11m13kx4.js +16 -0
  2. package/dist/{acp-targets-5wyy2b9m.js → acp-targets-311gcyvw.js} +9 -9
  3. package/dist/{actions-4nxq386s.js → actions-c4chgxp6.js} +24 -22
  4. package/dist/{agent-fs-provision-v6enh76w.js → agent-fs-provision-0b9awm5n.js} +10 -5
  5. package/dist/{amp-adapter-ze3x22qn.js → amp-adapter-r0veq6x5.js} +3 -3
  6. package/dist/{app-kyqt8ehw.js → app-hn5fftf5.js} +5 -5
  7. package/dist/{approval-notifications-a0db0esw.js → approval-notifications-3g6yc8nv.js} +7 -7
  8. package/dist/{assistant-9g5jzq25.js → assistant-cpjgpjvp.js} +24 -22
  9. package/dist/{boot-args-schema-d7fme4q1.js → boot-args-schema-hce1av1h.js} +1 -1
  10. package/dist/{boot-reembed-jrwxeye2.js → boot-reembed-bztbxc4z.js} +1 -1
  11. package/dist/{boot-reembed-6wpazmpw.js → boot-reembed-d7xcym0j.js} +1 -1
  12. package/dist/{boot-scrub-sweep-52h7yntp.js → boot-scrub-sweep-mkmm16gk.js} +2 -2
  13. package/dist/{boot-seeds-kb3dxjex.js → boot-seeds-arrkbe8t.js} +4 -4
  14. package/dist/{boxd-jrrmkv3w.js → boxd-68n75y1s.js} +1 -1
  15. package/dist/{claude-adapter-0c0y8fqp.js → claude-adapter-ykpyr5p8.js} +8 -8
  16. package/dist/{claude-managed-adapter-w2es07qq.js → claude-managed-adapter-ssg6z4bt.js} +4 -4
  17. package/dist/{claude-managed-setup-9ssb7ct4.js → claude-managed-setup-trd59v7b.js} +4 -4
  18. package/dist/{claude-sdk-session-p6t0gyse.js → claude-sdk-session-yjcze0j1.js} +10 -10
  19. package/dist/{cli-2gvdvsxj.js → cli-01tvvtad.js} +63 -60
  20. package/dist/{cli-rhsc2zyx.js → cli-04zc3f7b.js} +1 -1
  21. package/dist/{cli-p1a4khta.js → cli-0k1a0sde.js} +6 -6
  22. package/dist/{cli-atm0hkes.js → cli-0pp1yjg2.js} +4 -4
  23. package/dist/{cli-0b4zam62.js → cli-0vcqcwfn.js} +18 -0
  24. package/dist/{cli-zhn4r1rz.js → cli-12vek61e.js} +72 -49
  25. package/dist/{cli-j2r1apqm.js → cli-1htmtqc2.js} +45 -44
  26. package/dist/{cli-a6q6x15h.js → cli-2amwhyv2.js} +8 -5
  27. package/dist/{cli-w5dar1bk.js → cli-2m6yaq6b.js} +1 -1
  28. package/dist/{cli-a02habn6.js → cli-2tw284hj.js} +2 -2
  29. package/dist/{cli-nc39ym5q.js → cli-39qm0rtm.js} +6 -6
  30. package/dist/{cli-6c9ve77f.js → cli-3p288654.js} +2 -2
  31. package/dist/cli-52nfye5j.js +673 -0
  32. package/dist/cli-55tc8cj4.js +252 -0
  33. package/dist/cli-5r95eqbh.js +186 -0
  34. package/dist/{cli-892y3vfp.js → cli-5tg94mdw.js} +7 -7
  35. package/dist/{cli-ynph3b70.js → cli-5x03v6en.js} +8 -8
  36. package/dist/{cli-1h4njv9y.js → cli-5z0g0e8v.js} +11 -2
  37. package/dist/{cli-6a3j25xd.js → cli-72yms3ey.js} +16 -16
  38. package/dist/{cli-h2qtafm4.js → cli-73q4g5nx.js} +17 -17
  39. package/dist/{cli-k3c13za2.js → cli-7wy8gbwb.js} +1 -1
  40. package/dist/{cli-9g12h1aq.js → cli-7yn42w6m.js} +1 -1
  41. package/dist/{cli-g56fxddf.js → cli-8hp56wat.js} +3 -2
  42. package/dist/{cli-4aswccje.js → cli-9qe5y107.js} +2 -2
  43. package/dist/{cli-7cp6aa1q.js → cli-9y4tgrkf.js} +23 -177
  44. package/dist/{cli-mhrr4d5b.js → cli-agjbj5x0.js} +1 -1
  45. package/dist/{cli-hnh8erra.js → cli-b93d81yg.js} +2 -2
  46. package/dist/{cli-9yjhshah.js → cli-bhgrhedp.js} +1 -1
  47. package/dist/{cli-b82a13ga.js → cli-bp6k9acz.js} +17 -21
  48. package/dist/{cli-7e8sxqv5.js → cli-bpje8n65.js} +30 -3
  49. package/dist/{cli-t2s7j5cy.js → cli-bz97ff9n.js} +2 -2
  50. package/dist/{cli-0bgj4rh5.js → cli-c7j31hq9.js} +3 -3
  51. package/dist/{cli-p8zqbbt1.js → cli-cah298e5.js} +1 -1
  52. package/dist/{cli-9knhkkgr.js → cli-cjqyse9q.js} +3 -3
  53. package/dist/{cli-tb4j757d.js → cli-dkvtfgn4.js} +6 -6
  54. package/dist/{cli-14xdms9a.js → cli-e3ahxq5y.js} +6 -6
  55. package/dist/{cli-6n7y5ypy.js → cli-e8n0hdzd.js} +1 -1
  56. package/dist/{cli-q71g5q39.js → cli-en6dmkxd.js} +3 -3
  57. package/dist/{cli-xqbqwpxr.js → cli-eq4kew31.js} +9 -9
  58. package/dist/{cli-4kzp7r0q.js → cli-eqq0hwvx.js} +3 -3
  59. package/dist/{cli-bf0t77nf.js → cli-ercwc8xn.js} +1 -1
  60. package/dist/{cli-qncx2r0s.js → cli-ex1y88j3.js} +1 -1
  61. package/dist/{cli-bq97k63w.js → cli-fxd1mwtr.js} +2 -2
  62. package/dist/{cli-kbm659dk.js → cli-fy4gb74g.js} +2 -2
  63. package/dist/{cli-djt6wmrc.js → cli-fyaq4zdv.js} +6 -6
  64. package/dist/{cli-raqw9fw9.js → cli-gfy6hbd9.js} +6 -6
  65. package/dist/{cli-s9twe4x0.js → cli-h70a2mxy.js} +13 -8
  66. package/dist/cli-hbvgzjq4.js +69 -0
  67. package/dist/{cli-vy3fn0mz.js → cli-hhc47ack.js} +4 -4
  68. package/dist/{cli-m00c47q6.js → cli-j5gtytvg.js} +54 -24
  69. package/dist/{cli-ha4ek2nb.js → cli-js10kdk7.js} +1 -1
  70. package/dist/{cli-yzxqwcvq.js → cli-k5jx8jya.js} +10 -3
  71. package/dist/{cli-rytq7dm2.js → cli-krbcr00p.js} +3 -3
  72. package/dist/{cli-453497a0.js → cli-kwr5qv5g.js} +2 -2
  73. package/dist/{cli-czvvnfr9.js → cli-m5qtmrbc.js} +2 -2
  74. package/dist/{cli-cstggwq7.js → cli-ma9ys8rt.js} +2 -2
  75. package/dist/{cli-htymm48w.js → cli-mbwmqb5w.js} +1 -1
  76. package/dist/{cli-wz4e5am2.js → cli-mcymtvwn.js} +320 -70
  77. package/dist/{cli-2aacfdcn.js → cli-mq2fbgva.js} +64 -3
  78. package/dist/{cli-ramn8jae.js → cli-n85m2wkq.js} +1 -1
  79. package/dist/{cli-k4r5sfaj.js → cli-n8f0fs3c.js} +4 -4
  80. package/dist/{cli-f8yhybxr.js → cli-nja15knq.js} +3 -3
  81. package/dist/{cli-6tvh1fwq.js → cli-pe3yxedk.js} +3 -3
  82. package/dist/{cli-3bpr3wks.js → cli-pqfecppn.js} +1 -1
  83. package/dist/{cli-n6ygvrrm.js → cli-q2dywc8h.js} +4 -4
  84. package/dist/{cli-8zmpwe79.js → cli-q8tc22bj.js} +5 -5
  85. package/dist/{cli-yvzxbztc.js → cli-r0mz92by.js} +2 -2
  86. package/dist/{cli-v3zcnr8g.js → cli-r14ac1y0.js} +1 -1
  87. package/dist/{cli-fwjwkw66.js → cli-rtmqzat7.js} +2 -2
  88. package/dist/{cli-zqq57pgx.js → cli-s6zk31gr.js} +4 -4
  89. package/dist/{cli-27fat7st.js → cli-sv2r3bw8.js} +7 -7
  90. package/dist/{cli-zb1hff00.js → cli-t75xngj1.js} +9 -9
  91. package/dist/{cli-r813c7rb.js → cli-tdk7jtka.js} +1 -1
  92. package/dist/{cli-5ptj757f.js → cli-tm60vtax.js} +1 -1
  93. package/dist/{cli-rpmw4fsv.js → cli-v9ya390t.js} +12 -12
  94. package/dist/{cli-075ccjh6.js → cli-wvjqaqcp.js} +2607 -65
  95. package/dist/{cli-2jtfm8kh.js → cli-xf4z5bdn.js} +4 -4
  96. package/dist/{cli-4g323fjh.js → cli-xm34qj8m.js} +2 -2
  97. package/dist/{cli-f7dhm7hh.js → cli-ya3kf4gs.js} +1 -1
  98. package/dist/{cli-rwgwen5v.js → cli-yegz2g06.js} +4 -4
  99. package/dist/{cli-nbakg5xh.js → cli-yfpc6qy9.js} +3 -3
  100. package/dist/{cli-thd3005a.js → cli-z4f346g5.js} +1 -1
  101. package/dist/cli.js +24 -21
  102. package/dist/{codex-adapter-ssahg4h4.js → codex-adapter-wc6e4wct.js} +8 -8
  103. package/dist/{codex-login-9c7aggxe.js → codex-login-1ven7yje.js} +1 -1
  104. package/dist/{codex-session-runner-xn63q3h7.js → codex-session-runner-ppfgjd97.js} +9 -9
  105. package/dist/{commands-ctey7tr5.js → commands-tsv2vx5b.js} +3 -3
  106. package/dist/{controller-rqhbppg9.js → controller-ye4sdwsy.js} +4 -4
  107. package/dist/{controllers-connect-w3qbpbt1.js → controllers-connect-zn4dg69h.js} +25 -23
  108. package/dist/core-dxcy02sc.js +41 -0
  109. package/dist/{cursor-adapter-r819hf1a.js → cursor-adapter-q2g9vwts.js} +2 -2
  110. package/dist/{db-2ah39cyx.js → db-3r1fyr2n.js} +6 -2
  111. package/dist/{db-p5drc1d1.js → db-g111qn9j.js} +3 -3
  112. package/dist/{devin-adapter-bc6g0x29.js → devin-adapter-t8d86q9x.js} +1 -1
  113. package/dist/{dispatcher-x6w14pde.js → dispatcher-4q8s0mx8.js} +22 -20
  114. package/dist/{docker-6c4reetq.js → docker-1b41eysj.js} +2 -2
  115. package/dist/{dsh-adapter-h8qn14n4.js → dsh-adapter-mmcw1z5s.js} +2 -2
  116. package/dist/{e2b-z4ec0qve.js → e2b-ew8c5j5v.js} +2 -2
  117. package/dist/{e2b-jg7kyyef.js → e2b-xm60c8ad.js} +2 -2
  118. package/dist/{easter-egg-3d-1y6r9gxy.js → easter-egg-3d-04ke6hcp.js} +1 -1
  119. package/dist/{embedding-space-z6ptw3jk.js → embedding-space-kcdn52vz.js} +6 -6
  120. package/dist/{embeddings-0sxb1d2h.js → embeddings-jnzcd91a.js} +1 -1
  121. package/dist/{event-bus-swr88jg5.js → event-bus-v4ywhc2p.js} +1 -1
  122. package/dist/{execute-6m1ex8ce.js → execute-74amghty.js} +1 -1
  123. package/dist/{external-channel-ezer7pk0.js → external-channel-v9zgxnxz.js} +2 -2
  124. package/dist/fx-adapter-0ar6pqm3.js +19 -0
  125. package/dist/grok-adapter-t6m74fb1.js +19 -0
  126. package/dist/handlers-9kwcrc4k.js +38 -0
  127. package/dist/{heartbeat-6c4fr49t.js → heartbeat-p8pk1msj.js} +25 -23
  128. package/dist/{hook-t1c5avbv.js → hook-k1h73zd7.js} +5 -5
  129. package/dist/{hook-02rt5tvq.js → hook-p5reemds.js} +7 -7
  130. package/dist/{http-qa3h32a1.js → http-ms1z5xxy.js} +565 -141
  131. package/dist/index-23cdfzr6.js +39 -0
  132. package/dist/{index-kqv9ebfj.js → index-76zzxtzf.js} +1 -1
  133. package/dist/{index-e42j998x.js → index-fbkqhvvj.js} +38 -19
  134. package/dist/index-g7kkjs5b.js +38 -0
  135. package/dist/{index-qpjk2hxk.js → index-gjn6qfgn.js} +1 -1
  136. package/dist/{index-akbgsdhh.js → index-kn63q1gr.js} +26 -24
  137. package/dist/index-stk36pa5.js +43 -0
  138. package/dist/{k8s-7jrh5va2.js → k8s-fy8hbhkg.js} +2 -2
  139. package/dist/{keepalive-jmf6pn8c.js → keepalive-031js8jz.js} +4 -4
  140. package/dist/lead-mfggjtfk.js +77 -0
  141. package/dist/{maintenance-g7v15tj1.js → maintenance-sq9v3qx9.js} +1 -1
  142. package/dist/{oauth-refresh-sweep-ywgf8tbr.js → oauth-refresh-sweep-zqmnyvs8.js} +3 -3
  143. package/dist/object-webhooks-r24wwb5y.js +21 -0
  144. package/dist/{onboard-m3fedypq.js → onboard-p25yhh7t.js} +5 -5
  145. package/dist/{opencode-adapter-19ktcbb9.js → opencode-adapter-wcjc4zdk.js} +7 -7
  146. package/dist/{otel-impl-3ehm1hgc.js → otel-impl-ff1gf20m.js} +2 -2
  147. package/dist/{pending-fwj2fatd.js → pending-hxj5yatb.js} +23 -21
  148. package/dist/{pi-mono-adapter-xdeesvc4.js → pi-mono-adapter-vkp4zz7p.js} +12 -12
  149. package/dist/{pricing-refresh-4j8dzvxg.js → pricing-refresh-9w7gx41w.js} +2 -2
  150. package/dist/{rbac-roles-8msjr07m.js → rbac-roles-84aw10nz.js} +3 -3
  151. package/dist/{rbac-roles-n7t2acv8.js → rbac-roles-hz74vckp.js} +2 -2
  152. package/dist/{registry-32b1mft6.js → registry-eeyx1201.js} +1 -1
  153. package/dist/{render-v2-j7qggj8h.js → render-v2-nrdkg9gf.js} +5 -5
  154. package/dist/{resume-hj1mn65y.js → resume-s6ey36rh.js} +9 -9
  155. package/dist/{runtime-z31mdsgv.js → runtime-x0b4pyam.js} +1 -1
  156. package/dist/{session-access-w38fh09a.js → session-access-xv49tk14.js} +4 -4
  157. package/dist/{session-source-backfill-ax6qxv20.js → session-source-backfill-r5j988ah.js} +3 -3
  158. package/dist/{setup-dsqmpfcr.js → setup-mj0krk1p.js} +1 -1
  159. package/dist/thread-buffer-temgaqsy.js +41 -0
  160. package/dist/{tree-visibility-6vqmnr71.js → tree-visibility-cbrsfaar.js} +2 -2
  161. package/dist/{user-merge-jobs-mvheb3ed.js → user-merge-jobs-f9d8nwnw.js} +3 -3
  162. package/dist/{virtual-modules-w2qk2wew.js → virtual-modules-ns0ryw05.js} +3 -3
  163. package/dist/{work-objects-4ahy5es5.js → work-objects-pydhzast.js} +25 -23
  164. package/dist/worker-efcemc22.js +77 -0
  165. package/dist/{worker-follow-up-1gs4aw7y.js → worker-follow-up-9z2xec5e.js} +22 -20
  166. package/dist/{x-3wr8c5sh.js → x-3dtaf2r9.js} +2 -2
  167. package/openapi.json +788 -253
  168. package/package.json +8 -5
  169. package/src/azure-devops/auth.ts +2 -3
  170. package/src/be/agent-fs-identity.ts +46 -0
  171. package/src/be/agent-history.ts +215 -0
  172. package/src/be/db/agents.ts +34 -12
  173. package/src/be/db/tasks/write.ts +2 -2
  174. package/src/be/db.ts +2 -0
  175. package/src/be/migrations/332_primitive_objects.sql +31 -0
  176. package/src/be/migrations/334_agent_history.sql +23 -0
  177. package/src/be/migrations/335_primitive_object_webhooks.sql +36 -0
  178. package/src/be/primitives/boards/elements.ts +717 -0
  179. package/src/be/primitives/boards/excalifont-metrics.json +516 -0
  180. package/src/be/primitives/boards/service.ts +121 -0
  181. package/src/be/primitives/object-webhooks.ts +348 -0
  182. package/src/be/primitives/objects.ts +686 -0
  183. package/src/be/primitives/sheets/a1.ts +136 -0
  184. package/src/be/primitives/sheets/engine-worker.ts +194 -0
  185. package/src/be/primitives/sheets/engine.ts +199 -0
  186. package/src/be/primitives/sheets/format.ts +106 -0
  187. package/src/be/primitives/sheets/service.ts +415 -0
  188. package/src/be/primitives/write-object.ts +83 -0
  189. package/src/be/script-credential-broker.ts +8 -27
  190. package/src/be/scripts/typecheck.ts +216 -0
  191. package/src/be/seed/agent-fs-provision.ts +18 -0
  192. package/src/be/users.ts +19 -0
  193. package/src/commands/onboard/agent-fs-version.ts +1 -1
  194. package/src/commands/onboard/steps/harness.tsx +1 -1
  195. package/src/commands/provider-credentials.ts +1 -0
  196. package/src/e2b/env.ts +3 -1
  197. package/src/fs/agent-fs-provider.ts +33 -2
  198. package/src/gitlab/auth.ts +3 -4
  199. package/src/heartbeat/heartbeat.ts +11 -11
  200. package/src/http/agent-lifecycle.ts +152 -0
  201. package/src/http/agents.ts +12 -0
  202. package/src/http/all-routes.ts +2 -0
  203. package/src/http/auth.ts +2 -1
  204. package/src/http/index.ts +15 -0
  205. package/src/http/object-webhooks.ts +101 -0
  206. package/src/http/operator-actor.ts +2 -1
  207. package/src/http/sessions.ts +7 -0
  208. package/src/http/workflows.ts +32 -0
  209. package/src/integrations/chat-sdk/outbound-files.ts +3 -2
  210. package/src/providers/acp-targets.ts +2 -2
  211. package/src/providers/amp-adapter.ts +1 -1
  212. package/src/providers/opencode-adapter.ts +4 -1
  213. package/src/rbac/legacy-policy.ts +2 -0
  214. package/src/rbac/permissions.ts +5 -0
  215. package/src/script-workflows/guest-ctx.ts +32 -0
  216. package/src/script-workflows/workflow-ctx.ts +2 -0
  217. package/src/scripts-runtime/ctx.ts +9 -1
  218. package/src/scripts-runtime/executors/native.ts +106 -21
  219. package/src/scripts-runtime/executors/quickjs-prelude.ts +9 -2
  220. package/src/scripts-runtime/executors/quickjs-runner.ts +12 -1
  221. package/src/scripts-runtime/sdk-allowlist.ts +88 -0
  222. package/src/scripts-runtime/swarm-sdk.ts +51 -3
  223. package/src/scripts-runtime/types/stdlib.d.ts +267 -0
  224. package/src/scripts-runtime/types/swarm-sdk.d.ts +267 -0
  225. package/src/server.ts +48 -0
  226. package/src/tests/agent-history.test.ts +313 -0
  227. package/src/tests/azure-devops-auth.test.ts +6 -0
  228. package/src/tests/chat-sdk-outbound-files.test.ts +3 -1
  229. package/src/tests/check-unit-test-allowlist.test.ts +193 -0
  230. package/src/tests/credential-check.test.ts +12 -0
  231. package/src/tests/db-task-read-contract.test.ts +2 -0
  232. package/src/tests/db-task-write-contract.test.ts +2 -0
  233. package/src/tests/e2e-coverage-contract.test.ts +6 -2
  234. package/src/tests/e2e-diff-coverage.test.ts +154 -0
  235. package/src/tests/e2e-rerun-quarantine.test.ts +180 -0
  236. package/src/tests/e2e-shards.test.ts +137 -0
  237. package/src/tests/e2e-tracker-ingest.test.ts +266 -0
  238. package/src/tests/extensions-heartbeat.test.ts +34 -0
  239. package/src/tests/gitlab-auth.test.ts +10 -0
  240. package/src/tests/heartbeat.test.ts +38 -0
  241. package/src/tests/http-api-integration.test.ts +0 -6
  242. package/src/tests/opencode-adapter.test.ts +11 -0
  243. package/src/tests/primitives-boards.test.ts +686 -0
  244. package/src/tests/primitives-object-webhooks.test.ts +642 -0
  245. package/src/tests/primitives-objects.test.ts +248 -0
  246. package/src/tests/reasoning-kind-ui-parity.test.ts +112 -0
  247. package/src/tests/script-native-sandbox-identity.test.ts +264 -0
  248. package/src/tests/scripts-namespaces.test.ts +211 -0
  249. package/src/tests/secret-scrub-gate.test.ts +1 -0
  250. package/src/tests/secret-scrubber-convex.test.ts +168 -0
  251. package/src/tests/secret-scrubber.test.ts +1 -1
  252. package/src/tests/session-tokens.test.ts +27 -0
  253. package/src/tests/sheet-engine.test.ts +58 -0
  254. package/src/tests/slack-file-tools-attachments.test.ts +74 -6
  255. package/src/tests/slack-read-boundaries.test.ts +4 -2
  256. package/src/tests/task-start-after-commit.test.ts +82 -0
  257. package/src/tests/ui-logs-parser.test.ts +67 -0
  258. package/src/tests/workflow-retry-v2.test.ts +101 -0
  259. package/src/tests/workflow-tla-races.test.ts +29 -0
  260. package/src/tools/boards.ts +260 -0
  261. package/src/tools/objects.ts +191 -0
  262. package/src/tools/sheets.ts +312 -0
  263. package/src/tools/slack-read.ts +10 -3
  264. package/src/tools/tool-config.ts +23 -0
  265. package/src/tools/workflows/create-workflow.ts +11 -1
  266. package/src/tools/workflows/patch-workflow-node.ts +4 -0
  267. package/src/tools/workflows/patch-workflow.ts +4 -0
  268. package/src/tools/workflows/update-workflow.ts +17 -0
  269. package/src/types.ts +16 -0
  270. package/src/utils/sandboxed-process.ts +47 -2
  271. package/src/utils/secret-scrubber.ts +61 -6
  272. package/src/workflows/engine.ts +35 -21
  273. package/src/workflows/input.ts +29 -1
  274. package/src/workflows/patch-definition.ts +15 -1
  275. package/src/workflows/retry-poller.ts +15 -2
  276. package/src/workflows/validation.ts +10 -0
  277. package/templates/ai-toolbox.manifest.json +1 -1
  278. package/templates/skills/agent-browser/SKILL.md +1 -0
  279. package/templates/skills/agent-browser/content.md +1 -0
  280. package/templates/skills/pages/content.md +5 -0
  281. package/templates/skills/swarm-docs/content.md +6 -1
  282. package/templates/skills/swarm-scripts/SKILL.md +1 -0
  283. package/templates/skills/swarm-scripts/content.md +1 -0
  284. package/templates/skills/tdd-planning/content.md +5 -2
  285. package/dist/acp-adapter-weaaxey3.js +0 -16
  286. package/dist/core-df1n049h.js +0 -39
  287. package/dist/fx-adapter-zwmps9re.js +0 -19
  288. package/dist/grok-adapter-q0avf919.js +0 -19
  289. package/dist/handlers-g5jq0e4q.js +0 -36
  290. package/dist/index-1f6m47mq.js +0 -37
  291. package/dist/index-1p1mpqda.js +0 -36
  292. package/dist/index-tnkd410q.js +0 -41
  293. package/dist/lead-m5e7xt93.js +0 -75
  294. package/dist/thread-buffer-nf55vwx3.js +0 -39
  295. package/dist/worker-ews1nyhw.js +0 -75
  296. package/src/slack/socket-mode-guard.test.ts +0 -25
  297. package/src/tests/agent-activity.test.ts +0 -247
  298. package/src/tests/agent-fs-live-url.test.ts +0 -55
  299. package/src/tests/agentmail-inbox-mapping.test.ts +0 -73
  300. package/src/tests/approval-sweeps-config.test.ts +0 -47
  301. package/src/tests/cards.test.ts +0 -169
  302. package/src/tests/chat-sdk-facts.test.ts +0 -23
  303. package/src/tests/config-env-export-chat-sdk.test.ts +0 -11
  304. package/src/tests/core-auth.test.ts +0 -156
  305. package/src/tests/date-utils.test.ts +0 -48
  306. package/src/tests/db-context-versions.test.ts +0 -37
  307. package/src/tests/db-runtime.test.ts +0 -132
  308. package/src/tests/enabled-capabilities.test.ts +0 -20
  309. package/src/tests/extensions-example-mcp-install.test.ts +0 -67
  310. package/src/tests/extensions-lead-equivalence.test.ts +0 -70
  311. package/src/tests/get-workflow-run-tool.test.ts +0 -98
  312. package/src/tests/github-event-labels.test.ts +0 -24
  313. package/src/tests/haiku-5-5-pricing.test.ts +0 -38
  314. package/src/tests/http-log-scrubbing.test.ts +0 -123
  315. package/src/tests/http-semconv-attributes.test.ts +0 -92
  316. package/src/tests/identity.test.ts +0 -117
  317. package/src/tests/inbox-state.test.ts +0 -167
  318. package/src/tests/internal-ai/models.test.ts +0 -54
  319. package/src/tests/launch-password-rejection.test.ts +0 -140
  320. package/src/tests/list-total-cache.test.ts +0 -88
  321. package/src/tests/match-route.test.ts +0 -187
  322. package/src/tests/memory-feature-flags.test.ts +0 -45
  323. package/src/tests/memory-get-tool.test.ts +0 -269
  324. package/src/tests/memory-health-endpoint.test.ts +0 -78
  325. package/src/tests/memory-http-access.test.ts +0 -221
  326. package/src/tests/memory-retrieval-purge.test.ts +0 -99
  327. package/src/tests/multi-runtime-enabled-stats.test.ts +0 -229
  328. package/src/tests/openai-embedding-provider.test.ts +0 -159
  329. package/src/tests/org-identity.test.ts +0 -44
  330. package/src/tests/pages-actions-endpoint.test.ts +0 -103
  331. package/src/tests/pages-browser-sdk.test.ts +0 -76
  332. package/src/tests/pages-feedback-keys.test.ts +0 -121
  333. package/src/tests/pages-frame-ancestors.test.ts +0 -189
  334. package/src/tests/pages-list-endpoint.test.ts +0 -148
  335. package/src/tests/pages-password-mode.test.ts +0 -266
  336. package/src/tests/pages-public-authed-401.test.ts +0 -103
  337. package/src/tests/pages-public-html.test.ts +0 -297
  338. package/src/tests/pages-public-json-redirect.test.ts +0 -122
  339. package/src/tests/pages-view-count.test.ts +0 -245
  340. package/src/tests/prompt-templates-db.test.ts +0 -616
  341. package/src/tests/rbac-engine.test.ts +0 -742
  342. package/src/tests/repo-allow-merge-gate.test.ts +0 -389
  343. package/src/tests/route-def-find-route.test.ts +0 -192
  344. package/src/tests/runtime-stale-threshold.test.ts +0 -40
  345. package/src/tests/schedule-validation-helper.test.ts +0 -51
  346. package/src/tests/scheduled-tasks-api.test.ts +0 -355
  347. package/src/tests/scheduler-backoff.test.ts +0 -166
  348. package/src/tests/script-run-token.test.ts +0 -75
  349. package/src/tests/scripts-extract-signature.test.ts +0 -47
  350. package/src/tests/scripts-sdk-bridge-tool-failure.test.ts +0 -141
  351. package/src/tests/seed-workflow-dreaming.test.ts +0 -117
  352. package/src/tests/short-id.test.ts +0 -23
  353. package/src/tests/skill-files-http.test.ts +0 -222
  354. package/src/tests/skill-get-file-tool.test.ts +0 -110
  355. package/src/tests/skill-script-refs.test.ts +0 -63
  356. package/src/tests/skill-update-scope.test.ts +0 -252
  357. package/src/tests/skills-bundle.test.ts +0 -99
  358. package/src/tests/slack-app-icon.test.ts +0 -94
  359. package/src/tests/slack-assistant-comention.test.ts +0 -139
  360. package/src/tests/slack-delete.test.ts +0 -157
  361. package/src/tests/slack-inbound-diagnostics-auth.test.ts +0 -93
  362. package/src/tests/slack-manifest.test.ts +0 -23
  363. package/src/tests/slack-task-output.test.ts +0 -90
  364. package/src/tests/store-progress-output-guidance.test.ts +0 -34
  365. package/src/tests/swarm-diff.test.ts +0 -728
  366. package/src/tests/task-lifecycle-events.test.ts +0 -53
  367. package/src/tests/template-asset-config.test.ts +0 -18
  368. package/src/tests/template-fetch.test.ts +0 -490
  369. package/src/tests/themes-page-theme.test.ts +0 -155
  370. package/src/tests/tool-annotations.test.ts +0 -442
  371. package/src/tests/tool-output-agent-id.test.ts +0 -202
  372. package/src/tests/update-profile-agentid.test.ts +0 -248
  373. package/src/tests/whoami-route.test.ts +0 -162
  374. package/src/tests/workflow-definition-telemetry.test.ts +0 -144
  375. package/src/tests/workflow-patch.test.ts +0 -169
  376. package/src/tests/workflow-run-steps-index.test.ts +0 -65
  377. package/src/tests/workflow-schedule-trigger.test.ts +0 -104
  378. package/src/tests/workflow-step-claims.test.ts +0 -152
  379. package/src/tests/workflow-step-order.test.ts +0 -92
  380. package/src/tests/workflow-trigger-schema.test.ts +0 -359
  381. package/src/tests/workflow-versions.test.ts +0 -240
  382. package/src/tests/workflow-wait.test.ts +0 -26
@@ -0,0 +1,686 @@
1
+ import { type FileScope, FilesError, normalizeStoredKey } from "@/fs/provider";
2
+ import { buildAgentFsLiveUrl } from "@/utils/constants";
3
+ import { scrubSecrets } from "@/utils/secret-scrubber";
4
+ import { agentFsClientFor } from "../agent-fs-identity";
5
+ import { getDbClient } from "../db";
6
+ import { emptySheet } from "./sheets/format";
7
+
8
+ /**
9
+ * Primitive objects: agent-fs files that back a primitive, each with a stable
10
+ * id. The file is the source of truth and embeds the id; `primitive_objects`
11
+ * is a cache that `reindexObjects` rebuilds from the drive.
12
+ */
13
+
14
+ type Json = Record<string, unknown>;
15
+
16
+ type PrimitiveKind = {
17
+ suffix: string;
18
+ glob: string;
19
+ contentType: string;
20
+ empty: (id: string, title?: string) => Json;
21
+ readId: (json: Json) => string | undefined;
22
+ withId: (json: Json, id: string) => Json;
23
+ };
24
+
25
+ const swarmBlock = (json: Json): Json =>
26
+ json.swarm && typeof json.swarm === "object" ? (json.swarm as Json) : {};
27
+
28
+ export const PRIMITIVE_KINDS: Readonly<Record<string, PrimitiveKind>> = {
29
+ // An Excalidraw scene. A stock Excalidraw save drops `swarm`; reindex then
30
+ // recovers the id from the row at the same path and writes it back.
31
+ board: {
32
+ suffix: ".excalidraw",
33
+ glob: "**/*.excalidraw",
34
+ contentType: "application/json",
35
+ empty: (id, title) => ({
36
+ type: "excalidraw",
37
+ version: 2,
38
+ source: "agent-swarm",
39
+ elements: [],
40
+ appState: {},
41
+ files: {},
42
+ swarm: { id, kind: "board", ...(title ? { title } : {}) },
43
+ }),
44
+ readId: (json) => {
45
+ const id = swarmBlock(json).id;
46
+ return typeof id === "string" && id.length > 0 ? id : undefined;
47
+ },
48
+ withId: (json, id) => ({ ...json, swarm: { ...swarmBlock(json), id, kind: "board" } }),
49
+ },
50
+ // A `swarm-sheet/1` workbook (src/be/primitives/sheets/format.ts).
51
+ sheet: {
52
+ suffix: ".sheet.json",
53
+ glob: "**/*.sheet.json",
54
+ contentType: "application/json",
55
+ empty: (id, title) => emptySheet(id, title),
56
+ readId: (json) => {
57
+ const id = swarmBlock(json).id;
58
+ return typeof id === "string" && id.length > 0 ? id : undefined;
59
+ },
60
+ withId: (json, id) => ({ ...json, swarm: { ...swarmBlock(json), id, kind: "sheet" } }),
61
+ },
62
+ };
63
+
64
+ export const PRIMITIVE_KIND_NAMES = Object.keys(PRIMITIVE_KINDS) as [string, ...string[]];
65
+
66
+ /** A refusal the tool layer returns as `toolErr`, not a server error. */
67
+ export class ObjectsError extends Error {}
68
+
69
+ export const NO_AGENT_FS_IDENTITY =
70
+ "agent-fs is not configured for this agent: objects need the agent's own AGENT_FS_API_KEY (agent-scoped config) plus AGENT_FS_API_URL, AGENT_FS_DEFAULT_ORG_ID and AGENT_FS_DEFAULT_DRIVE_ID";
71
+
72
+ type ObjectRow = {
73
+ id: string;
74
+ kind: string;
75
+ orgId: string;
76
+ driveId: string;
77
+ path: string;
78
+ title: string | null;
79
+ fileVersion: number | null;
80
+ ownerAgentId: string | null;
81
+ /** Set when agent-fs reported the file deleted; object-list hides the row. */
82
+ deletedAt: string | null;
83
+ createdAt: string;
84
+ updatedAt: string;
85
+ };
86
+
87
+ export type PrimitiveObject = ObjectRow & { link: string | null };
88
+
89
+ const MAX_LIST_LIMIT = 200;
90
+ // shortcut: one reindex call considers at most this many files; page by kind or add a cursor when a drive outgrows it.
91
+ const MAX_REINDEX_FILES = 500;
92
+ // Full downloads per reindex call. Unchanged files cost one `stat` and no read,
93
+ // so repeated calls converge: each one reads at most this many changed files.
94
+ const MAX_REINDEX_READS = 50;
95
+ // Wall-clock and downloaded-byte budget per reindex call, so one call stays bounded
96
+ // even when every file is large or agent-fs is slow. The byte check runs before each
97
+ // read, so a call can overshoot by at most one file.
98
+ const MAX_REINDEX_MS = 20_000;
99
+ const MAX_REINDEX_BYTES = 16 * 1024 * 1024;
100
+
101
+ export type ReindexLimits = { reads: number; ms: number; bytes: number };
102
+ const REINDEX_LIMITS: ReindexLimits = {
103
+ reads: MAX_REINDEX_READS,
104
+ ms: MAX_REINDEX_MS,
105
+ bytes: MAX_REINDEX_BYTES,
106
+ };
107
+ // shortcut: in-process only; two API replicas can still reindex one drive at once (each pass is safe, just duplicated work).
108
+ const reindexing = new Set<string>();
109
+
110
+ const withLink = (row: ObjectRow): PrimitiveObject => ({ ...row, link: buildAgentFsLiveUrl(row) });
111
+
112
+ export async function clientFor(agentId: string | undefined) {
113
+ const client = agentId ? await agentFsClientFor(agentId) : undefined;
114
+ if (!client) throw new ObjectsError(NO_AGENT_FS_IDENTITY);
115
+ const { orgId, driveId } = client.identity;
116
+ const scope = (path: string): FileScope => ({ taskId: "", name: "", key: path, orgId, driveId });
117
+ return { provider: client.provider, orgId, driveId, scope };
118
+ }
119
+
120
+ function kindFor(kind: string): PrimitiveKind {
121
+ const def = Object.hasOwn(PRIMITIVE_KINDS, kind) ? PRIMITIVE_KINDS[kind] : undefined;
122
+ if (!def)
123
+ throw new ObjectsError(`unknown kind '${kind}' (known: ${PRIMITIVE_KIND_NAMES.join(", ")})`);
124
+ return def;
125
+ }
126
+
127
+ function normalizePath(path: string): string {
128
+ try {
129
+ return normalizeStoredKey(path);
130
+ } catch (error) {
131
+ throw new ObjectsError(`invalid path '${path}': ${(error as Error).message}`);
132
+ }
133
+ }
134
+
135
+ const versionOf = (value: string | null | undefined): number | null =>
136
+ value && Number.isFinite(Number(value)) ? Number(value) : null;
137
+
138
+ /**
139
+ * Point the row with `id` at `path`. A row at the same path with another id is
140
+ * replaced: the file there now carries `id`, and the file wins.
141
+ */
142
+ async function saveRow(
143
+ row: Omit<ObjectRow, "createdAt" | "updatedAt" | "deletedAt">,
144
+ opts: { onlyNewer?: boolean } = {},
145
+ ): Promise<ObjectRow> {
146
+ const now = new Date().toISOString();
147
+ return getDbClient().transaction(async (tx) => {
148
+ await tx.run(
149
+ "DELETE FROM primitive_objects WHERE orgId = ? AND driveId = ? AND path = ? AND id <> ?",
150
+ [row.orgId, row.driveId, row.path, row.id],
151
+ );
152
+ await tx.run(
153
+ `INSERT INTO primitive_objects
154
+ (id, kind, orgId, driveId, path, title, fileVersion, ownerAgentId, createdAt, updatedAt)
155
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
156
+ ON CONFLICT(id) DO UPDATE SET
157
+ kind = excluded.kind, orgId = excluded.orgId, driveId = excluded.driveId,
158
+ path = excluded.path, title = COALESCE(excluded.title, primitive_objects.title),
159
+ fileVersion = excluded.fileVersion, deletedAt = NULL, updatedAt = excluded.updatedAt
160
+ WHERE ? = 0 OR primitive_objects.path <> excluded.path
161
+ OR primitive_objects.fileVersion IS NULL
162
+ OR primitive_objects.fileVersion < excluded.fileVersion`,
163
+ [
164
+ row.id,
165
+ row.kind,
166
+ row.orgId,
167
+ row.driveId,
168
+ row.path,
169
+ // The only writer of `title` (.text-columns.json: scrubbed).
170
+ row.title === null ? null : scrubSecrets(row.title),
171
+ row.fileVersion,
172
+ row.ownerAgentId,
173
+ now,
174
+ now,
175
+ // Concurrent events for one path: an older read must not overwrite a newer one.
176
+ opts.onlyNewer ? 1 : 0,
177
+ ],
178
+ );
179
+ const saved = await tx.get<ObjectRow>("SELECT * FROM primitive_objects WHERE id = ?", [row.id]);
180
+ if (!saved) throw new Error(`primitive object ${row.id} vanished after save`);
181
+ return saved;
182
+ });
183
+ }
184
+
185
+ export async function createObject(input: {
186
+ agentId: string | undefined;
187
+ kind: string;
188
+ path: string;
189
+ title?: string;
190
+ /** Fill the new file (for example a board with shapes). Runs before the upload. */
191
+ build?: (empty: Json) => Json;
192
+ }): Promise<PrimitiveObject> {
193
+ const kind = kindFor(input.kind);
194
+ const path = normalizePath(input.path);
195
+ if (!path.endsWith(kind.suffix)) {
196
+ throw new ObjectsError(`a ${input.kind} path must end with '${kind.suffix}'`);
197
+ }
198
+ const { provider, orgId, driveId, scope } = await clientFor(input.agentId);
199
+ const id = crypto.randomUUID();
200
+ const empty = kind.empty(id, input.title);
201
+ const content = input.build ? input.build(empty) : empty;
202
+ let version: string | undefined;
203
+ try {
204
+ ({ version } = await provider.upload(scope(path), JSON.stringify(content, null, 2), {
205
+ contentType: kind.contentType,
206
+ ifNoneMatch: "*",
207
+ message: `create ${input.kind}`,
208
+ }));
209
+ } catch (error) {
210
+ if (error instanceof FilesError && error.code === "Conflict") {
211
+ throw new ObjectsError(`a file already exists at '${path}'; run object-reindex to adopt it`);
212
+ }
213
+ throw error;
214
+ }
215
+ // After the upload, never inside a transaction around it.
216
+ const row = await saveRow({
217
+ id,
218
+ kind: input.kind,
219
+ orgId,
220
+ driveId,
221
+ path,
222
+ title: input.title ?? null,
223
+ fileVersion: versionOf(version),
224
+ ownerAgentId: input.agentId ?? null,
225
+ });
226
+ watchDrive(orgId, driveId);
227
+ return withLink(row);
228
+ }
229
+
230
+ /**
231
+ * Best-effort: make sure agent-fs tells the swarm about changes on this drive
232
+ * (object-webhooks.ts). Not awaited, never throws: object tools work without it.
233
+ */
234
+ function watchDrive(orgId: string, driveId: string): void {
235
+ void import("./object-webhooks")
236
+ .then(({ ensureObjectWebhook }) => ensureObjectWebhook(orgId, driveId))
237
+ .catch(() => undefined);
238
+ }
239
+
240
+ export async function getObject(input: {
241
+ agentId: string | undefined;
242
+ id?: string;
243
+ path?: string;
244
+ includeContent?: boolean;
245
+ }): Promise<{ object: PrimitiveObject; missing: boolean; content?: unknown }> {
246
+ if (!input.id && !input.path) throw new ObjectsError("pass `id` or `path`");
247
+ const { provider, orgId, driveId, scope } = await clientFor(input.agentId);
248
+ const row = input.id
249
+ ? await getDbClient().get<ObjectRow>(
250
+ "SELECT * FROM primitive_objects WHERE id = ? AND orgId = ? AND driveId = ?",
251
+ [input.id, orgId, driveId],
252
+ )
253
+ : await getDbClient().get<ObjectRow>(
254
+ "SELECT * FROM primitive_objects WHERE path = ? AND orgId = ? AND driveId = ?",
255
+ [normalizePath(input.path ?? ""), orgId, driveId],
256
+ );
257
+ if (!row) {
258
+ throw new ObjectsError(
259
+ `no object ${input.id ? `with id '${input.id}'` : `at '${input.path}'`} on this drive; run object-reindex if the file exists`,
260
+ );
261
+ }
262
+ let response: Response;
263
+ try {
264
+ response = await provider.download(scope(row.path));
265
+ } catch (error) {
266
+ // Keep the row: the file may come back, and reindex reports it as missing.
267
+ if (error instanceof FilesError && error.code === "NotFound") {
268
+ return { object: withLink(row), missing: true };
269
+ }
270
+ throw error;
271
+ }
272
+ const object = withLink({
273
+ ...row,
274
+ fileVersion: versionOf(response.headers.get("x-agent-fs-version")) ?? row.fileVersion,
275
+ });
276
+ if (!input.includeContent) {
277
+ await response.body?.cancel();
278
+ return { object, missing: false };
279
+ }
280
+ const text = await response.text();
281
+ let content: unknown = text;
282
+ try {
283
+ content = JSON.parse(text);
284
+ } catch {
285
+ // Not JSON (a hand-edited file): return the raw text.
286
+ }
287
+ return { object, missing: false, content };
288
+ }
289
+
290
+ /** Record the file version a content write produced (board and sheet services). */
291
+ export async function recordObjectVersion(id: string, fileVersion: number | null): Promise<void> {
292
+ await getDbClient().run(
293
+ "UPDATE primitive_objects SET fileVersion = ?, updatedAt = ? WHERE id = ?",
294
+ [fileVersion, new Date().toISOString(), id],
295
+ );
296
+ }
297
+
298
+ export async function listObjects(input: {
299
+ agentId: string | undefined;
300
+ kind?: string;
301
+ prefix?: string;
302
+ limit?: number;
303
+ offset?: number;
304
+ }): Promise<{ objects: PrimitiveObject[]; total: number }> {
305
+ if (input.kind) kindFor(input.kind);
306
+ const { orgId, driveId } = await clientFor(input.agentId);
307
+ const where = ["orgId = ?", "driveId = ?", "deletedAt IS NULL"];
308
+ const params: string[] = [orgId, driveId];
309
+ if (input.kind) {
310
+ where.push("kind = ?");
311
+ params.push(input.kind);
312
+ }
313
+ if (input.prefix) {
314
+ // instr, not LIKE: a path may hold % or _.
315
+ where.push("instr(path, ?) = 1");
316
+ params.push(input.prefix.replace(/^\/+/, ""));
317
+ }
318
+ const limit = Math.min(Math.max(input.limit ?? 50, 1), MAX_LIST_LIMIT);
319
+ const offset = Math.max(input.offset ?? 0, 0);
320
+ const db = getDbClient();
321
+ const rows = await db.query<ObjectRow>(
322
+ `SELECT * FROM primitive_objects WHERE ${where.join(" AND ")} ORDER BY updatedAt DESC, id LIMIT ? OFFSET ?`,
323
+ [...params, limit, offset],
324
+ );
325
+ const count = await db.get<{ n: number }>(
326
+ `SELECT COUNT(*) AS n FROM primitive_objects WHERE ${where.join(" AND ")}`,
327
+ params,
328
+ );
329
+ return { objects: rows.map(withLink), total: count?.n ?? 0 };
330
+ }
331
+
332
+ export type ReindexReport = {
333
+ scanned: number;
334
+ /** Files whose version matches the row's: checked with `stat`, not read. */
335
+ unchanged: number;
336
+ /** Files with no embedded id that got one written back. */
337
+ adopted: string[];
338
+ /** Files whose embedded id had no row on this drive. */
339
+ restored: string[];
340
+ /** Rows whose file is gone. Reported, never deleted. */
341
+ missing: string[];
342
+ /** Files skipped: changed during write-back, or not valid JSON. */
343
+ conflicts: Array<{ path: string; reason: string }>;
344
+ /** More files remain: a cap or budget cut this call short. Run again to continue. */
345
+ truncated: boolean;
346
+ /** Which limit cut this call short; null when the pass finished. */
347
+ cutBy: "files" | "reads" | "time" | "bytes" | null;
348
+ };
349
+
350
+ export async function reindexObjects(input: {
351
+ agentId: string | undefined;
352
+ kind?: string;
353
+ /** Override the per-call budget (tests). */
354
+ limits?: Partial<ReindexLimits>;
355
+ }): Promise<ReindexReport> {
356
+ const kinds = input.kind ? [input.kind] : PRIMITIVE_KIND_NAMES;
357
+ for (const kind of kinds) kindFor(kind);
358
+ const client = await clientFor(input.agentId);
359
+ const lock = `${client.orgId}\u0000${client.driveId}`;
360
+ if (reindexing.has(lock)) {
361
+ throw new ObjectsError(
362
+ "object-reindex is already running on this drive; run it again when it finishes",
363
+ );
364
+ }
365
+ reindexing.add(lock);
366
+ try {
367
+ const report = await reindexDrive(client, kinds, input.agentId, {
368
+ ...REINDEX_LIMITS,
369
+ ...input.limits,
370
+ });
371
+ watchDrive(client.orgId, client.driveId);
372
+ return report;
373
+ } finally {
374
+ reindexing.delete(lock);
375
+ }
376
+ }
377
+
378
+ async function reindexDrive(
379
+ { provider, orgId, driveId, scope }: Awaited<ReturnType<typeof clientFor>>,
380
+ kinds: string[],
381
+ agentId: string | undefined,
382
+ limits: ReindexLimits,
383
+ ): Promise<ReindexReport> {
384
+ const db = getDbClient();
385
+ const report: ReindexReport = {
386
+ scanned: 0,
387
+ unchanged: 0,
388
+ adopted: [],
389
+ restored: [],
390
+ missing: [],
391
+ conflicts: [],
392
+ truncated: false,
393
+ cutBy: null,
394
+ };
395
+ const startedAt = Date.now();
396
+ let reads = 0;
397
+ let bytes = 0;
398
+ const cut = (by: NonNullable<ReindexReport["cutBy"]>) => {
399
+ report.truncated = true;
400
+ report.cutBy = by;
401
+ };
402
+
403
+ for (const kindName of kinds) {
404
+ if (report.truncated) break;
405
+ const kind = kindFor(kindName);
406
+ const all = (await provider.glob(kind.glob)).map((p) => p.replace(/^\/+/, ""));
407
+ const paths = all.slice(0, MAX_REINDEX_FILES - report.scanned);
408
+ if (paths.length < all.length) cut("files");
409
+ const onDrive = new Set(all);
410
+ // Ids already given to a file in this pass: a copied file must not steal one.
411
+ const claimed = new Map<string, string>();
412
+
413
+ for (const path of paths) {
414
+ if (Date.now() - startedAt >= limits.ms) {
415
+ cut("time");
416
+ break;
417
+ }
418
+ const atPath = await db.get<ObjectRow>(
419
+ "SELECT * FROM primitive_objects WHERE orgId = ? AND driveId = ? AND path = ?",
420
+ [orgId, driveId, path],
421
+ );
422
+ if (atPath && !atPath.deletedAt && atPath.fileVersion !== null) {
423
+ let current: number | null = null;
424
+ try {
425
+ current = await provider.currentVersion(scope(path));
426
+ } catch (error) {
427
+ if (error instanceof FilesError && error.code === "Unauthorized") throw error;
428
+ // No stat (older agent-fs, a flaky call): fall through to a full read.
429
+ }
430
+ if (current === atPath.fileVersion) {
431
+ report.scanned += 1;
432
+ report.unchanged += 1;
433
+ claimed.set(atPath.id, path);
434
+ continue;
435
+ }
436
+ }
437
+ if (reads >= limits.reads || bytes >= limits.bytes) {
438
+ cut(reads >= limits.reads ? "reads" : "bytes");
439
+ break;
440
+ }
441
+ reads += 1;
442
+ report.scanned += 1;
443
+
444
+ let json: Json;
445
+ let version: string | null;
446
+ try {
447
+ const response = await provider.download(scope(path));
448
+ version = response.headers.get("x-agent-fs-version");
449
+ const text = await response.text();
450
+ bytes += Buffer.byteLength(text);
451
+ const parsed = JSON.parse(text) as unknown;
452
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
453
+ throw new Error("not an object");
454
+ json = parsed as Json;
455
+ } catch (error) {
456
+ // A bad key fails the whole pass; a vanished or broken file skips this one.
457
+ if (error instanceof FilesError && error.code === "Unauthorized") throw error;
458
+ report.conflicts.push({ path, reason: `unreadable: ${(error as Error).message}` });
459
+ continue;
460
+ }
461
+
462
+ let id = kind.readId(json);
463
+ if (id) {
464
+ const byId = await db.get<ObjectRow>("SELECT * FROM primitive_objects WHERE id = ?", [id]);
465
+ const otherDrive = byId && (byId.orgId !== orgId || byId.driveId !== driveId);
466
+ const copied = byId && byId.path !== path && onDrive.has(byId.path);
467
+ const claimedElsewhere = claimed.has(id) && claimed.get(id) !== path;
468
+ if (otherDrive || copied || claimedElsewhere) id = undefined;
469
+ else if (!byId) report.restored.push(path);
470
+ }
471
+
472
+ if (!id) {
473
+ // Stock Excalidraw save (id dropped) or a copy: keep the path's id, else a new one.
474
+ const embedded = kind.readId(json);
475
+ id = atPath && atPath.id !== embedded ? atPath.id : crypto.randomUUID();
476
+ try {
477
+ ({ version = null } = await provider.upload(
478
+ scope(path),
479
+ JSON.stringify(kind.withId(json, id), null, 2),
480
+ {
481
+ contentType: kind.contentType,
482
+ ...(version ? { ifMatch: version } : {}),
483
+ message: `adopt ${kindName} id`,
484
+ },
485
+ ));
486
+ } catch (error) {
487
+ if (error instanceof FilesError && error.code === "Conflict") {
488
+ report.conflicts.push({ path, reason: "file changed during write-back; run again" });
489
+ continue;
490
+ }
491
+ throw error;
492
+ }
493
+ report.adopted.push(path);
494
+ }
495
+
496
+ claimed.set(id, path);
497
+ const title = swarmBlock(json).title;
498
+ await saveRow({
499
+ id,
500
+ kind: kindName,
501
+ orgId,
502
+ driveId,
503
+ path,
504
+ title: typeof title === "string" ? title : (atPath?.title ?? null),
505
+ fileVersion: versionOf(version),
506
+ ownerAgentId: atPath?.ownerAgentId ?? agentId ?? null,
507
+ });
508
+ }
509
+
510
+ if (!report.truncated) {
511
+ const rows = await db.query<{ path: string }>(
512
+ "SELECT path FROM primitive_objects WHERE orgId = ? AND driveId = ? AND kind = ? ORDER BY path",
513
+ [orgId, driveId, kindName],
514
+ );
515
+ report.missing.push(...rows.map((r) => r.path).filter((p) => !onDrive.has(p)));
516
+ }
517
+ }
518
+ return report;
519
+ }
520
+
521
+ /** One `file.changed` event from agent-fs: metadata only, never content. */
522
+ export type FileChange = {
523
+ orgId: string;
524
+ driveId: string;
525
+ path: string;
526
+ version: number;
527
+ operation: string;
528
+ };
529
+
530
+ /** Reads the changed file's drive. The webhook path never writes to agent-fs. */
531
+ export type FileChangeReader = {
532
+ download(path: string): Promise<Response>;
533
+ exists(path: string): Promise<boolean>;
534
+ };
535
+
536
+ export type FileChangeResult = {
537
+ action: "updated" | "tombstoned" | "restored" | "moved" | "ignored";
538
+ path: string;
539
+ id?: string;
540
+ reason?: string;
541
+ };
542
+
543
+ /** Read the file an event names; a gone or non-JSON file yields the reason to ignore it. */
544
+ async function readChangedFile(
545
+ reader: FileChangeReader,
546
+ path: string,
547
+ ): Promise<{ json: Json; fileVersion: number | null } | { reason: string }> {
548
+ try {
549
+ const response = await reader.download(path);
550
+ const fileVersion = versionOf(response.headers.get("x-agent-fs-version"));
551
+ const parsed = JSON.parse(await response.text()) as unknown;
552
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
553
+ throw new Error("not an object");
554
+ return { json: parsed as Json, fileVersion };
555
+ } catch (error) {
556
+ if (error instanceof FilesError && error.code === "NotFound") {
557
+ return { reason: "file is already gone" };
558
+ }
559
+ if (error instanceof FilesError) throw error;
560
+ return { reason: "not a JSON object; object-reindex reports it" };
561
+ }
562
+ }
563
+
564
+ /**
565
+ * Apply one agent-fs `file.changed` event to the pointer rows. Idempotent and
566
+ * order-safe: an event at or below the row's `fileVersion` is a no-op, so a
567
+ * replayed or late delivery changes nothing. Never writes to agent-fs (that
568
+ * would emit another event); a file with no id, or a copy, is left for
569
+ * object-reindex, and its event does not move `fileVersion` so reindex reads it.
570
+ */
571
+ export async function applyFileChange(
572
+ change: FileChange,
573
+ reader: FileChangeReader,
574
+ ): Promise<FileChangeResult> {
575
+ const path = change.path.replace(/^\/+/, "");
576
+ const [kindName, kind] =
577
+ Object.entries(PRIMITIVE_KINDS).find(([, k]) => path.endsWith(k.suffix)) ?? [];
578
+ if (!kindName || !kind) return { action: "ignored", path, reason: "not an object path" };
579
+ const db = getDbClient();
580
+ const { orgId, driveId, version } = change;
581
+ const now = new Date().toISOString();
582
+ const atPath = await db.get<ObjectRow>(
583
+ "SELECT * FROM primitive_objects WHERE orgId = ? AND driveId = ? AND path = ?",
584
+ [orgId, driveId, path],
585
+ );
586
+ const stale = (row: ObjectRow) => row.fileVersion !== null && version <= row.fileVersion;
587
+
588
+ if (change.operation === "delete") {
589
+ if (!atPath) return { action: "ignored", path, reason: "no object at this path" };
590
+ if (stale(atPath)) return { action: "ignored", path, id: atPath.id, reason: "stale event" };
591
+ // agent-fs delivers a batch concurrently, so the version check lives in the UPDATE.
592
+ // Versions count per path: a row that moved meanwhile is not this event's.
593
+ const { changes } = await db.run(
594
+ `UPDATE primitive_objects SET deletedAt = ?, fileVersion = ?, updatedAt = ?
595
+ WHERE id = ? AND path = ? AND (fileVersion IS NULL OR fileVersion < ?)`,
596
+ [now, version, now, atPath.id, path, version],
597
+ );
598
+ if (changes === 0) return { action: "ignored", path, id: atPath.id, reason: "stale event" };
599
+ return { action: "tombstoned", path, id: atPath.id };
600
+ }
601
+
602
+ if (atPath) {
603
+ if (stale(atPath)) return { action: "ignored", path, id: atPath.id, reason: "stale event" };
604
+ const file = await readChangedFile(reader, path);
605
+ if ("reason" in file) return { action: "ignored", path, id: atPath.id, reason: file.reason };
606
+ // object-reindex skips a file whose stat version equals fileVersion, so only a file that
607
+ // still carries this row's id moves it. An id-less save (stock Excalidraw) stays visible.
608
+ const embedded = kind.readId(file.json);
609
+ const read = file.fileVersion ?? version;
610
+ // A read older than the event is not the content the event announced.
611
+ const owned = embedded === atPath.id && read >= version;
612
+ const { changes } = await db.run(
613
+ `UPDATE primitive_objects
614
+ SET deletedAt = NULL, updatedAt = ?, fileVersion = CASE WHEN ? THEN ? ELSE fileVersion END
615
+ WHERE id = ? AND path = ? AND (fileVersion IS NULL OR fileVersion < ?)`,
616
+ [now, owned ? 1 : 0, read, atPath.id, path, version],
617
+ );
618
+ if (changes === 0) return { action: "ignored", path, id: atPath.id, reason: "stale event" };
619
+ if (owned) return { action: "updated", path, id: atPath.id };
620
+ return {
621
+ action: "updated",
622
+ path,
623
+ id: atPath.id,
624
+ reason: !embedded
625
+ ? "no embedded id; object-reindex adopts it"
626
+ : embedded === atPath.id
627
+ ? "read an older version than the event; object-reindex reads it again"
628
+ : "the file carries another id; object-reindex reconciles it",
629
+ };
630
+ }
631
+
632
+ // A file with no row: a move target, a restored file, or a new or copied one.
633
+ const file = await readChangedFile(reader, path);
634
+ if ("reason" in file) return { action: "ignored", path, reason: file.reason };
635
+ const { json, fileVersion } = file;
636
+ const id = kind.readId(json);
637
+ if (!id) return { action: "ignored", path, reason: "no embedded id; object-reindex adopts it" };
638
+ const byId = await db.get<ObjectRow>("SELECT * FROM primitive_objects WHERE id = ?", [id]);
639
+ if (byId && (byId.orgId !== orgId || byId.driveId !== driveId)) {
640
+ return { action: "ignored", path, id, reason: "the id belongs to another drive" };
641
+ }
642
+ if (byId && !byId.deletedAt && (await reader.exists(byId.path))) {
643
+ return {
644
+ action: "ignored",
645
+ path,
646
+ id,
647
+ reason: `copy of ${byId.path}; object-reindex gives it a new id`,
648
+ };
649
+ }
650
+ const title = swarmBlock(json).title;
651
+ const savedVersion = fileVersion ?? version;
652
+ const saved = await saveRow(
653
+ {
654
+ id,
655
+ kind: kindName,
656
+ orgId,
657
+ driveId,
658
+ path,
659
+ title: typeof title === "string" ? title : (byId?.title ?? null),
660
+ fileVersion: savedVersion,
661
+ ownerAgentId: byId?.ownerAgentId ?? null,
662
+ },
663
+ { onlyNewer: true },
664
+ );
665
+ const action = byId ? "moved" : "restored";
666
+ if (saved.path !== path || saved.fileVersion !== savedVersion || saved.deletedAt) {
667
+ return { action, path, id };
668
+ }
669
+ // A delete event for this path that ran before the save found no row and was dropped.
670
+ // agent-fs sends events after the change, so a file gone now was deleted in that window.
671
+ let present = true;
672
+ try {
673
+ present = await reader.exists(path);
674
+ } catch {
675
+ // shortcut: a failed check keeps the row live (a retry would see a stale event);
676
+ // add a per-path delete marker if agent-fs read failures show up here.
677
+ }
678
+ if (present) return { action, path, id };
679
+ const { changes } = await db.run(
680
+ `UPDATE primitive_objects SET deletedAt = ?, updatedAt = ?
681
+ WHERE id = ? AND path = ? AND fileVersion = ? AND deletedAt IS NULL`,
682
+ [now, now, id, path, savedVersion],
683
+ );
684
+ if (changes === 0) return { action, path, id };
685
+ return { action: "tombstoned", path, id, reason: "the file was deleted while it was saved" };
686
+ }