@desplega.ai/agent-swarm 1.160.0 → 1.162.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 (398) hide show
  1. package/README.md +4 -3
  2. package/dist/{acp-adapter-2mjwcsfh.js → acp-adapter-74m73ae9.js} +163 -49
  3. package/dist/{actions-e43rxskr.js → actions-4sr14gnt.js} +42 -38
  4. package/dist/{anthropic-messages-5qx80j9k.js → anthropic-messages-8xxrzky9.js} +22 -26
  5. package/dist/{app-mc7xfagn.js → app-pt68fbwp.js} +17 -14
  6. package/dist/{artifact-3v5t9jtg.js → artifact-fey7dvj9.js} +3 -2
  7. package/dist/{assistant-sedkzv3b.js → assistant-cv3jytks.js} +43 -39
  8. package/dist/{azure-openai-responses-nfb21z9a.js → azure-openai-responses-f5cqsyj8.js} +15 -10
  9. package/dist/{boot-reembed-m3656j2n.js → boot-reembed-4ht4gqth.js} +17 -14
  10. package/dist/{boot-reembed-cqz9swn5.js → boot-reembed-nxpcvpj9.js} +16 -13
  11. package/dist/{boot-scrub-logs-xbxf5d7w.js → boot-scrub-logs-k93kyw8k.js} +13 -10
  12. package/dist/boot-seeds-1skcrs0e.js +32 -0
  13. package/dist/{claude-adapter-dc6289mc.js → claude-adapter-r5g0tzge.js} +39 -30
  14. package/dist/{claude-managed-adapter-naaw51me.js → claude-managed-adapter-yxkfxg8j.js} +6 -5
  15. package/dist/{claude-managed-setup-eacvchx0.js → claude-managed-setup-pkyrgshb.js} +27 -27
  16. package/dist/{claude-sdk-session-bqp2xvym.js → claude-sdk-session-jxyxnrwd.js} +8041 -7910
  17. package/dist/{cli-4derpgyk.js → cli-2hhfhfq5.js} +6 -1
  18. package/dist/{cli-rykfmgwg.js → cli-2x0e561b.js} +1 -1
  19. package/dist/{cli-tzx2ke1v.js → cli-2zy95vhm.js} +137 -64
  20. package/dist/{cli-0x01kwrd.js → cli-4cwxn7gp.js} +47 -186
  21. package/dist/{cli-xjcywfsf.js → cli-4dcpaefp.js} +12 -11
  22. package/dist/{cli-v7fn5gms.js → cli-4x0csdjq.js} +164 -76
  23. package/dist/{cli-12tszpk9.js → cli-5bcd7sfy.js} +91 -29
  24. package/dist/{cli-jz4w45qt.js → cli-5k6k8ta3.js} +190 -50
  25. package/dist/{cli-tpq83z89.js → cli-5xhpb3kv.js} +20 -19
  26. package/dist/{cli-r1mxd1xh.js → cli-7af8yhav.js} +6 -179
  27. package/dist/{cli-jajnsm8q.js → cli-7tre70zp.js} +18160 -31345
  28. package/dist/{cli-447dt1h3.js → cli-8ev9xqnx.js} +218 -25
  29. package/dist/cli-bsky8g7w.js +449 -0
  30. package/dist/{cli-0z2v4nhw.js → cli-cat6h73s.js} +1 -1
  31. package/dist/{cli-25fcq4b4.js → cli-cebmgwsc.js} +15 -11
  32. package/dist/{cli-shkxm1vn.js → cli-cvatsam7.js} +189 -13
  33. package/dist/{cli-2658f6at.js → cli-cvk6yzw5.js} +6 -8
  34. package/dist/cli-dbmwby6a.js +9 -0
  35. package/dist/{cli-ptr8h7kp.js → cli-eg0b3p0k.js} +5 -218
  36. package/dist/cli-f9w1semm.js +413 -0
  37. package/dist/{cli-523679eh.js → cli-g739zqzt.js} +6 -5
  38. package/dist/{cli-dv6cdjs2.js → cli-gd4favx9.js} +28 -7
  39. package/dist/{cli-c8a36vcc.js → cli-gpqpmns7.js} +2 -2
  40. package/dist/{cli-5nbmpy8w.js → cli-hb5c2x5y.js} +1 -1
  41. package/dist/{cli-741yb0xx.js → cli-hmsw1gpy.js} +55 -169
  42. package/dist/{cli-qydf22qq.js → cli-jf7wmv1r.js} +2562 -735
  43. package/dist/{cli-mfe5btp9.js → cli-jxs2ygaw.js} +317 -121
  44. package/dist/{cli-kmcpfwn2.js → cli-jyy6pm2f.js} +19 -3
  45. package/dist/cli-kdkwd3yr.js +615 -0
  46. package/dist/{cli-6cs6wzxt.js → cli-kh04eqwe.js} +2 -2
  47. package/dist/{cli-9hsgwz4w.js → cli-kp42yek0.js} +1309 -391
  48. package/dist/cli-ma3zvh39.js +10404 -0
  49. package/dist/{cli-ybgv4kw2.js → cli-mbssg1xv.js} +9 -2
  50. package/dist/{cli-jsp14b6c.js → cli-mzfth0bp.js} +38 -1
  51. package/dist/{cli-r2ap2czm.js → cli-nexqx4ve.js} +6 -0
  52. package/dist/{cli-f8gy6r2r.js → cli-nq7yqw7b.js} +19 -8
  53. package/dist/{cli-10nhj6xq.js → cli-nt8hecg9.js} +34 -33
  54. package/dist/cli-p0r8sxj5.js +303 -0
  55. package/dist/{cli-58e8yr0d.js → cli-pkd6s2wy.js} +4 -2
  56. package/dist/{cli-a8dvhzrt.js → cli-q24re23n.js} +7 -5
  57. package/dist/cli-qjjvzwzd.js +222 -0
  58. package/dist/cli-qrgt5bqf.js +189 -0
  59. package/dist/{cli-et8m9xsv.js → cli-rfjw9jw2.js} +22 -10
  60. package/dist/{cli-7e398j1h.js → cli-rj0gqwwp.js} +3 -3
  61. package/dist/{cli-btfv8y88.js → cli-rnyzn44p.js} +2 -2
  62. package/dist/{cli-d5czme6m.js → cli-s3hwpt9v.js} +4754 -4945
  63. package/dist/{cli-0jwe9034.js → cli-sptrj5f5.js} +3 -3
  64. package/dist/{cli-0q3avq3s.js → cli-sqvfa090.js} +19 -11
  65. package/dist/{cli-azhgzetg.js → cli-swfmp1fx.js} +27 -27
  66. package/dist/{cli-jyk0ynw2.js → cli-t845n9xk.js} +23 -10
  67. package/dist/{cli-zpep9q5e.js → cli-tcen9p5w.js} +20 -15
  68. package/dist/{cli-74h9hscv.js → cli-tre4bdgq.js} +1 -1
  69. package/dist/{cli-pm1rst0h.js → cli-twrh04ap.js} +30 -15
  70. package/dist/{cli-phsaj4xq.js → cli-v0pvvhfq.js} +1 -1
  71. package/dist/{cli-ydmcgve1.js → cli-vc9bp061.js} +5 -5
  72. package/dist/{cli-g2whhdrf.js → cli-vxe6qa4h.js} +1 -1
  73. package/dist/{cli-vctdqs5h.js → cli-vy3ed88x.js} +15 -2
  74. package/dist/{cli-br0qdrnp.js → cli-vyqs9ya8.js} +18 -18
  75. package/dist/{cli-cpvsaqsw.js → cli-w0bwte75.js} +8 -5
  76. package/dist/cli-wbvnn6tk.js +861 -0
  77. package/dist/{cli-r94z9p1z.js → cli-wgbezhw2.js} +3 -0
  78. package/dist/{cli-evvtk35y.js → cli-wjgs5wxe.js} +7 -7
  79. package/dist/cli-wxkkd0e0.js +33 -0
  80. package/dist/{cli-0wgxmwf6.js → cli-xk79303e.js} +20 -7
  81. package/dist/{cli-ktmyrtpn.js → cli-xqpk3rp7.js} +33 -10
  82. package/dist/{cli-ygwm91nt.js → cli-yy6dew39.js} +1 -1
  83. package/dist/cli-zp38xvtm.js +9487 -0
  84. package/dist/{cli-tfky2838.js → cli-zvhd3f64.js} +4 -4
  85. package/dist/{cli-jayjpjmb.js → cli-zxqx25nz.js} +66 -23
  86. package/dist/cli.js +40 -32
  87. package/dist/{cloudflare-workers-ai-system-one-k6fbxw9d.js → cloudflare-workers-ai-system-one-k8ddqjkq.js} +8 -6
  88. package/dist/{codex-adapter-nmxcatww.js → codex-adapter-esvmnhn7.js} +24 -23
  89. package/dist/{codex-hook-20me6byw.js → codex-hook-m73jmqgx.js} +19 -3
  90. package/dist/{codex-login-w6fz4xbz.js → codex-login-cf7mzsgg.js} +2 -2
  91. package/dist/{codex-session-runner-90aa80ev.js → codex-session-runner-ban9excr.js} +24 -23
  92. package/dist/{commands-8wcq1kn7.js → commands-75413p2n.js} +13 -10
  93. package/dist/{db-j40kc4se.js → db-7f5pecwg.js} +17 -10
  94. package/dist/{dispatcher-4zqy768d.js → dispatcher-fh9at8nz.js} +41 -37
  95. package/dist/dsh-adapter-wpze65d4.js +24 -0
  96. package/dist/{e2b-ez07znam.js → e2b-gjgdjp91.js} +12 -9
  97. package/dist/easter-egg-3d-3w5c2n4c.js +1057 -0
  98. package/dist/{execute-6e7qeyk4.js → execute-f50wg9nh.js} +203 -49
  99. package/dist/{google-generative-ai-k6n5nbpp.js → google-generative-ai-jxxpnegy.js} +2 -2
  100. package/dist/{google-vertex-44xxtcvp.js → google-vertex-x7q1angm.js} +5 -5
  101. package/dist/{handlers-kjdce1w5.js → handlers-w13787bb.js} +44 -40
  102. package/dist/{hook-r2t4bqfg.js → hook-46g1jrvx.js} +34 -20
  103. package/dist/{hook-czx13n12.js → hook-4tpts2ry.js} +25 -21
  104. package/dist/{http-3bbb19be.js → http-19pzbfrt.js} +1440 -283
  105. package/dist/{index-668me3f0.js → index-8fd4dm4h.js} +42 -38
  106. package/dist/{index-fg0dsp6c.js → index-dqmp15bq.js} +41 -37
  107. package/dist/{index-kkv84jq9.js → index-qb4q1y3e.js} +41 -37
  108. package/dist/index-s75wc4wd.js +33 -0
  109. package/dist/{index-zg7vp46x.js → index-scptvdxg.js} +64 -38
  110. package/dist/{keepalive-yra8dy57.js → keepalive-xa5ts9cd.js} +15 -12
  111. package/dist/{lead-va0pad2c.js → lead-qp4xkvjq.js} +59 -54
  112. package/dist/{maintenance-hqewtmyg.js → maintenance-rm5885hm.js} +17 -14
  113. package/dist/{mistral-conversations-pc3ntnxt.js → mistral-conversations-rw7fbt22.js} +4 -4
  114. package/dist/{node-a5e00qhp.js → node-8zkdq42h.js} +834 -833
  115. package/dist/node-f0ykebbv.js +2107 -0
  116. package/dist/node-wyamey5r.js +19 -0
  117. package/dist/{oauth-refresh-sweep-7rdt1m9n.js → oauth-refresh-sweep-1csdfebf.js} +14 -11
  118. package/dist/{onboard-j6ms6d0x.js → onboard-r6b78cs4.js} +10 -10
  119. package/dist/{openai-codex-responses-bbancrr0.js → openai-codex-responses-efvrgrq3.js} +4 -4
  120. package/dist/{openai-completions-jpaj5g2b.js → openai-completions-bbbrrz4z.js} +12 -8
  121. package/dist/{openai-responses-200k1wx4.js → openai-responses-9jjyrcm1.js} +15 -10
  122. package/dist/{opencode-adapter-89rabkw2.js → opencode-adapter-kb3g6pkf.js} +12 -9
  123. package/dist/{otel-impl-a792rjz0.js → otel-impl-0y9knpky.js} +6 -6
  124. package/dist/{pi-mono-adapter-g7qzvr3v.js → pi-mono-adapter-z6s1bme2.js} +128 -37
  125. package/dist/{pricing-refresh-wx0tp7cb.js → pricing-refresh-mth26tgp.js} +15 -12
  126. package/dist/{rbac-roles-8tzawacv.js → rbac-roles-kwntb23q.js} +17 -12
  127. package/dist/rbac-roles-vpk4ebm8.js +45 -0
  128. package/dist/{registry-v5wytg0s.js → registry-km6t1jd2.js} +1 -1
  129. package/dist/{render-v2-mm7zswb8.js → render-v2-hcm7h00y.js} +17 -14
  130. package/dist/{runtime-zyssgse0.js → runtime-vfjsfsc5.js} +5 -4
  131. package/dist/{setup-8y70ys6t.js → setup-hbyzd65h.js} +2 -2
  132. package/dist/{virtual-modules-6nmk7h3n.js → virtual-modules-9bv7ry91.js} +9 -7
  133. package/dist/{work-objects-fg6xkb0n.js → work-objects-m09sxnhe.js} +44 -40
  134. package/dist/{worker-wmwhxsph.js → worker-0h35rvk4.js} +59 -54
  135. package/dist/{x-n3e0v3xa.js → x-f1gt1pz3.js} +2 -2
  136. package/openapi.json +699 -26
  137. package/package.json +19 -11
  138. package/src/azure-devops/api.ts +121 -0
  139. package/src/azure-devops/auth.ts +78 -0
  140. package/src/azure-devops/handlers.ts +413 -0
  141. package/src/azure-devops/index.ts +27 -0
  142. package/src/azure-devops/templates.ts +108 -0
  143. package/src/azure-devops/types.ts +90 -0
  144. package/src/be/api-drain.ts +184 -0
  145. package/src/be/db/tasks/read.ts +32 -7
  146. package/src/be/db/tasks/write.ts +21 -4
  147. package/src/be/db-client.ts +11 -2
  148. package/src/be/db-retention.ts +95 -32
  149. package/src/be/db.ts +44 -19
  150. package/src/be/memory/constants.ts +16 -0
  151. package/src/be/memory/graph-expansion.ts +8 -1
  152. package/src/be/memory/index-content.ts +20 -1
  153. package/src/be/memory/key-guard.ts +93 -0
  154. package/src/be/memory/key-paths.ts +103 -0
  155. package/src/be/memory/link-resolver.ts +29 -3
  156. package/src/be/memory/providers/sqlite-store.ts +152 -45
  157. package/src/be/memory/raters/llm-summarizer.ts +10 -4
  158. package/src/be/memory/raters/llm.ts +15 -5
  159. package/src/be/memory/raters/store.ts +6 -3
  160. package/src/be/memory/raters/types.ts +11 -0
  161. package/src/be/memory/reranker.ts +38 -7
  162. package/src/be/memory/types.ts +12 -1
  163. package/src/be/migrations/190_memory_rating_model.sql +7 -0
  164. package/src/be/migrations/191_context_versions_previous_index.sql +8 -0
  165. package/src/be/migrations/192_favorites_agent_fs_path.sql +36 -0
  166. package/src/be/onboarding.ts +7 -1
  167. package/src/be/pricing-normalize.ts +4 -2
  168. package/src/be/scripts/typecheck.ts +4 -3
  169. package/src/be/seed-pricing.ts +16 -0
  170. package/src/be/seed-prompt-templates.ts +1 -0
  171. package/src/be/swarm-config-guard.ts +46 -17
  172. package/src/be/task-citations.ts +11 -5
  173. package/src/be/users.ts +3 -0
  174. package/src/cli.tsx +3 -2
  175. package/src/comb/agent-fs.ts +39 -0
  176. package/src/comb/config.ts +37 -0
  177. package/src/comb/markers.ts +37 -0
  178. package/src/comb/review-batch.ts +486 -0
  179. package/src/comb/templates.ts +88 -0
  180. package/src/commands/claude-managed-setup.ts +33 -31
  181. package/src/commands/context-preamble.ts +4 -1
  182. package/src/commands/hook.ts +2 -1
  183. package/src/commands/provider-credentials.ts +28 -15
  184. package/src/commands/runner.ts +458 -110
  185. package/src/commands/templates.ts +10 -0
  186. package/src/e2b/env.ts +2 -0
  187. package/src/extensions/catalog.generated.json +17 -0
  188. package/src/extensions/contract-types.generated.ts +1 -1
  189. package/src/fs/agent-fs-provider.ts +106 -2
  190. package/src/github/handlers.ts +10 -74
  191. package/src/github/reactions.ts +119 -138
  192. package/src/github/task-reactions.ts +34 -11
  193. package/src/heartbeat/heartbeat.ts +4 -0
  194. package/src/hooks/codex-hook.ts +25 -1
  195. package/src/hooks/hook.ts +14 -1
  196. package/src/hooks/pr-body-guard.ts +983 -0
  197. package/src/http/agents.ts +1 -1
  198. package/src/http/all-routes.ts +1 -0
  199. package/src/http/assets.ts +5 -17
  200. package/src/http/comb.ts +131 -0
  201. package/src/http/core.ts +14 -1
  202. package/src/http/extensions.ts +51 -27
  203. package/src/http/fs.ts +9 -17
  204. package/src/http/index.ts +27 -9
  205. package/src/http/mcp-user.ts +8 -13
  206. package/src/http/mcp.ts +19 -12
  207. package/src/http/memory.ts +80 -14
  208. package/src/http/onboarding.ts +21 -2
  209. package/src/http/poll.ts +30 -3
  210. package/src/http/realtime.ts +62 -0
  211. package/src/http/request-principal.ts +22 -0
  212. package/src/http/session-data.ts +6 -4
  213. package/src/http/stats.ts +1 -0
  214. package/src/http/status.ts +34 -2
  215. package/src/http/tasks.ts +17 -3
  216. package/src/http/users.ts +1 -1
  217. package/src/http/webhooks.ts +120 -2
  218. package/src/kv-reserved-namespaces.ts +10 -5
  219. package/src/providers/claude-adapter.ts +84 -16
  220. package/src/providers/claude-managed-adapter.ts +29 -2
  221. package/src/providers/codex-adapter.ts +1 -1
  222. package/src/providers/codex-skill-resolver.ts +6 -0
  223. package/src/providers/dsh-adapter.ts +204 -7
  224. package/src/providers/opencode-adapter.ts +24 -3
  225. package/src/providers/pi-mono-adapter.ts +154 -5
  226. package/src/providers/pi-mono-extension.ts +1 -1
  227. package/src/providers/pricing-sources.md +5 -1
  228. package/src/providers/reasoning-effort.ts +10 -2
  229. package/src/providers/types.ts +1 -1
  230. package/src/rbac/legacy-policy.ts +3 -0
  231. package/src/rbac/permissions.ts +14 -0
  232. package/src/realtime/auth.ts +63 -1
  233. package/src/realtime/tickets.ts +52 -0
  234. package/src/realtime/transport.ts +51 -22
  235. package/src/scripts-runtime/types/stdlib.d.ts +13 -5
  236. package/src/scripts-runtime/types/swarm-extension.d.ts +7 -3
  237. package/src/scripts-runtime/types/swarm-sdk.d.ts +13 -5
  238. package/src/tasks/context-key.ts +38 -1
  239. package/src/telemetry-context.ts +175 -0
  240. package/src/telemetry-contract/EVENTS.md +81 -0
  241. package/src/telemetry-contract/SOURCE.json +9 -0
  242. package/src/telemetry-contract/catalog.json +1335 -0
  243. package/src/telemetry-contract/index.ts +60 -0
  244. package/src/telemetry-contract/types.gen.ts +1971 -0
  245. package/src/telemetry-identity.ts +129 -0
  246. package/src/telemetry-snapshot.ts +211 -0
  247. package/src/telemetry-trigger.ts +125 -0
  248. package/src/telemetry-types.typetest.ts +40 -0
  249. package/src/telemetry.ts +271 -67
  250. package/src/tests/api-drain-e2e.test.ts +249 -0
  251. package/src/tests/api-drain-worker-e2e.test.ts +216 -0
  252. package/src/tests/api-drain.test.ts +351 -0
  253. package/src/tests/azure-devops-auth.test.ts +100 -0
  254. package/src/tests/azure-devops-handlers.test.ts +324 -0
  255. package/src/tests/azure-devops-webhook-malformed.test.ts +96 -0
  256. package/src/tests/claude-default-route.test.ts +260 -0
  257. package/src/tests/claude-managed-adapter.test.ts +47 -0
  258. package/src/tests/claude-managed-setup.test.ts +48 -0
  259. package/src/tests/claude-prompt-body-once.test.ts +117 -0
  260. package/src/tests/claude-routes-e2e.test.ts +316 -0
  261. package/src/tests/comb-config-guard.test.ts +38 -0
  262. package/src/tests/comb-links.test.ts +162 -0
  263. package/src/tests/comb-markers.test.ts +68 -0
  264. package/src/tests/comb-review-batch.test.ts +770 -0
  265. package/src/tests/comb-status.test.ts +152 -0
  266. package/src/tests/context-versions-retention.test.ts +314 -0
  267. package/src/tests/core-auth.test.ts +7 -0
  268. package/src/tests/db-retention.test.ts +14 -14
  269. package/src/tests/db-task-read-contract.test.ts +3 -0
  270. package/src/tests/db-task-write-contract.test.ts +3 -0
  271. package/src/tests/docs-index-footprint.test.js +3 -3
  272. package/src/tests/dsh-adapter.test.ts +134 -2
  273. package/src/tests/dsh-usage.test.ts +153 -0
  274. package/src/tests/extensions-catalog.test.ts +1 -0
  275. package/src/tests/extensions-example-deploy-awareness.test.ts +301 -0
  276. package/src/tests/extensions-http.test.ts +137 -10
  277. package/src/tests/extensions-mcp-tools.test.ts +28 -0
  278. package/src/tests/favorites-agent-fs-path.test.ts +226 -0
  279. package/src/tests/fetch-resolved-env.test.ts +24 -0
  280. package/src/tests/fixtures/azure-devops/pull-request-commented.json +129 -0
  281. package/src/tests/fixtures/azure-devops/pull-request-created.json +88 -0
  282. package/src/tests/fixtures/fake-claude-routes.ts +229 -0
  283. package/src/tests/github-handlers-reactions.test.ts +486 -0
  284. package/src/tests/github-reactions.test.ts +280 -0
  285. package/src/tests/harness-cli-version.test.ts +62 -0
  286. package/src/tests/http-api-integration.test.ts +21 -0
  287. package/src/tests/http-task-write-ownership.test.ts +24 -1
  288. package/src/tests/internal-ai/complete-structured.test.ts +94 -0
  289. package/src/tests/internal-ai/credentials.test.ts +22 -0
  290. package/src/tests/internal-ai/models.test.ts +36 -2
  291. package/src/tests/internal-ai/schema-parity.test.ts +25 -1
  292. package/src/tests/internal-ai/summarize-session.test.ts +23 -7
  293. package/src/tests/mcp-user-route.test.ts +133 -0
  294. package/src/tests/memory-key-paths.test.ts +1055 -0
  295. package/src/tests/memory-link-resolver.test.ts +34 -0
  296. package/src/tests/memory-rate-endpoint.test.ts +66 -0
  297. package/src/tests/memory-rater-llm-summarizer.test.ts +2 -1
  298. package/src/tests/memory-rater-llm.test.ts +73 -0
  299. package/src/tests/memory-rater-store.test.ts +31 -0
  300. package/src/tests/memory-reranker.test.ts +40 -0
  301. package/src/tests/onboarding.test.ts +108 -0
  302. package/src/tests/opencode-adapter.test.ts +57 -0
  303. package/src/tests/opencode-plugin.test.ts +4 -0
  304. package/src/tests/pi-codemode.test.ts +82 -4
  305. package/src/tests/pi-mono-adapter.test.ts +265 -2
  306. package/src/tests/pr-body-leaks.test.ts +789 -0
  307. package/src/tests/preload.ts +14 -0
  308. package/src/tests/provider-registration.test.ts +0 -2
  309. package/src/tests/providers/pi-cost.test.ts +190 -4
  310. package/src/tests/rbac-engine.test.ts +25 -1
  311. package/src/tests/realtime-room-auth.test.ts +104 -1
  312. package/src/tests/realtime-tickets.test.ts +74 -0
  313. package/src/tests/realtime-transport.test.ts +131 -4
  314. package/src/tests/runner-api-drain.test.ts +301 -0
  315. package/src/tests/runner-fallback-output.test.ts +61 -0
  316. package/src/tests/runner-fenced-json-output.test.ts +178 -0
  317. package/src/tests/runner-slot-reconcile.test.ts +199 -0
  318. package/src/tests/script-connections.test.ts +6 -0
  319. package/src/tests/send-task-requested-by.test.ts +133 -15
  320. package/src/tests/session-costs-recompute-all-providers.test.ts +23 -0
  321. package/src/tests/task-lifecycle-telemetry.test.ts +8 -3
  322. package/src/tests/task-reactions.test.ts +29 -6
  323. package/src/tests/telemetry-context.test.ts +314 -0
  324. package/src/tests/telemetry-init.test.ts +51 -19
  325. package/src/tests/telemetry-snapshot.test.ts +229 -0
  326. package/src/tests/telemetry-trigger.test.ts +200 -0
  327. package/src/tests/template-registry-helpers.ts +1 -0
  328. package/src/tests/vcs-azure-devops.test.ts +73 -0
  329. package/src/tests/webhooks-task-blocked.test.ts +23 -0
  330. package/src/tests/workflow-agent-task-retry.test.ts +363 -0
  331. package/src/tests/workflow-definition-telemetry.test.ts +4 -4
  332. package/src/tests/workflow-llm.test.ts +14 -0
  333. package/src/tools/context-diff.ts +20 -0
  334. package/src/tools/extension-install.ts +27 -16
  335. package/src/tools/memory-edit.ts +47 -3
  336. package/src/tools/memory-search.ts +13 -1
  337. package/src/tools/memory-store.ts +55 -3
  338. package/src/tools/poll-task.ts +20 -1
  339. package/src/tools/send-task.ts +9 -1
  340. package/src/tools/task-action.ts +11 -0
  341. package/src/types.ts +45 -8
  342. package/src/utils/api-drain.ts +24 -0
  343. package/src/utils/constants.ts +57 -16
  344. package/src/utils/credentials.test.ts +31 -1
  345. package/src/utils/credentials.ts +20 -9
  346. package/src/utils/dsh-usage.ts +53 -0
  347. package/src/utils/harness-cli-version.ts +6 -4
  348. package/src/utils/internal-ai/complete-structured.ts +26 -3
  349. package/src/utils/internal-ai/credentials.ts +23 -9
  350. package/src/utils/internal-ai/index.ts +8 -1
  351. package/src/utils/internal-ai/models.ts +34 -8
  352. package/src/utils/internal-ai/summarize-session.ts +22 -8
  353. package/src/utils/pr-body-leaks.ts +172 -0
  354. package/src/utils/secret-scrubber.ts +8 -0
  355. package/src/utils/task-attachment-links.ts +14 -8
  356. package/src/vcs/azure-devops.ts +80 -0
  357. package/src/vcs/index.ts +5 -1
  358. package/src/vcs/types.ts +2 -2
  359. package/src/workflows/recovery.ts +26 -1
  360. package/src/workflows/resume.ts +31 -4
  361. package/src/workflows/task-step-routing.ts +75 -2
  362. package/templates/community/open-prompt-showreel/PLAYBOOK.md +336 -0
  363. package/templates/community/open-prompt-showreel/README.md +33 -0
  364. package/templates/community/open-prompt-showreel/example/tla-races/facts.ts +145 -0
  365. package/templates/community/open-prompt-showreel/example/tla-races/facts.v3.json +140 -0
  366. package/templates/community/open-prompt-showreel/example/tla-races/music.mist-city.json +8 -0
  367. package/templates/community/open-prompt-showreel/example/tla-races/reel.html +805 -0
  368. package/templates/community/open-prompt-showreel/example/tla-races/smoke.sh +48 -0
  369. package/templates/community/open-prompt-showreel/lead-prompt.md +89 -0
  370. package/templates/community/open-prompt-showreel/setup.sh +167 -0
  371. package/templates/community/open-prompt-showreel/skills/motion-design-replication/SKILL.md +85 -0
  372. package/templates/community/open-prompt-showreel/skills/motion-design-video-analysis/SKILL.md +115 -0
  373. package/templates/community/open-prompt-showreel/skills/open-prompt-showreel/SKILL.md +147 -0
  374. package/templates/community/open-prompt-showreel/skills/video-generation/SKILL.md +195 -0
  375. package/templates/community/open-prompt-showreel/tools/fetch-music.sh +65 -0
  376. package/templates/community/open-prompt-showreel/tools/music-analyze.py +69 -0
  377. package/templates/community/open-prompt-showreel/tools/music-current.sh +34 -0
  378. package/templates/community/open-prompt-showreel/tools/music-cut.sh +36 -0
  379. package/templates/community/open-prompt-showreel/tools/music-refine.py +39 -0
  380. package/templates/community/open-prompt-showreel/tools/render.mjs +157 -0
  381. package/templates/community/open-prompt-showreel/tools/sheet.sh +44 -0
  382. package/templates/community/open-prompt-showreel/tools/web-compress.sh +17 -0
  383. package/templates/community/open-prompt-showreel/tools/x-reencode.sh +21 -0
  384. package/templates/extensions/README.md +1 -0
  385. package/templates/extensions/deploy-awareness/README.md +28 -0
  386. package/templates/extensions/deploy-awareness/hooks.ts +152 -0
  387. package/templates/extensions/deploy-awareness/manifest.json +8 -0
  388. package/templates/skills/memory/config.json +2 -2
  389. package/templates/skills/memory/content.md +59 -5
  390. package/templates/skills/swarm-extensions/config.json +1 -1
  391. package/templates/skills/swarm-extensions/content.md +28 -5
  392. package/tsconfig.json +3 -0
  393. package/dist/boot-seeds-gsetbs5y.js +0 -28
  394. package/dist/cli-j490egb5.js +0 -5632
  395. package/dist/cli-tjf4cn8z.js +0 -9119
  396. package/dist/cli-tmqt7dpj.js +0 -572
  397. package/dist/dsh-adapter-mpnzgztj.js +0 -19
  398. package/dist/index-7aj368tw.js +0 -30
@@ -10,15 +10,7 @@ import {
10
10
  isUnknownModelError,
11
11
  memoryRelevance,
12
12
  writeSkillsToFilesystem
13
- } from "./cli-phsaj4xq.js";
14
- import {
15
- Anthropic
16
- } from "./cli-j490egb5.js";
17
- import {
18
- checkHeartbeatChecklist,
19
- runHeartbeatSweep,
20
- stopHeartbeat
21
- } from "./cli-a8dvhzrt.js";
13
+ } from "./cli-v0pvvhfq.js";
22
14
  import {
23
15
  isClaudeBridgeEffective,
24
16
  resolveClaudeTransport
@@ -28,11 +20,19 @@ import {
28
20
  } from "./cli-2pdaysab.js";
29
21
  import {
30
22
  reasoningCapability
31
- } from "./cli-4derpgyk.js";
23
+ } from "./cli-2hhfhfq5.js";
32
24
  import {
33
25
  ensureAgentFsCredentialsForAgent,
34
26
  inviteEmailToSharedOrg
35
- } from "./cli-7e398j1h.js";
27
+ } from "./cli-rj0gqwwp.js";
28
+ import {
29
+ checkHeartbeatChecklist,
30
+ runHeartbeatSweep,
31
+ stopHeartbeat
32
+ } from "./cli-q24re23n.js";
33
+ import {
34
+ Anthropic
35
+ } from "./cli-ma3zvh39.js";
36
36
  import {
37
37
  AGENT_MAX_TASKS_CONFIG_KEY,
38
38
  ALL_CAPABILITIES,
@@ -48,6 +48,7 @@ import {
48
48
  JSONRPCMessageSchema,
49
49
  MAX_TASK_ATTACHMENT_BYTES,
50
50
  McpServer,
51
+ MemoryKeyError,
51
52
  RawLlmConfigSchema,
52
53
  RawLlmOutputSchema,
53
54
  Redacted,
@@ -78,10 +79,12 @@ import {
78
79
  cancelTaskInputSchema,
79
80
  cancelTaskOutputSchema,
80
81
  cancelWorkflowRun,
82
+ canonicalAzureDevOpsRepoUrl,
81
83
  changeRoom,
82
84
  checkOutputSchemaShape,
83
85
  clearJiraMetadata,
84
86
  closeRooms,
87
+ commentedPayloadOf,
85
88
  createEvent,
86
89
  createEventsBatch,
87
90
  createResumeFollowUp,
@@ -89,6 +92,7 @@ import {
89
92
  createTaskWithSiblingAwareness,
90
93
  createToolRegistrar,
91
94
  createWorkerTaskFollowUp,
95
+ createdPullRequestOf,
92
96
  decodeRoomSnapshot,
93
97
  dedupeMemoryDocumentIds,
94
98
  deleteJiraWebhook,
@@ -96,6 +100,7 @@ import {
96
100
  describeRequestRoute,
97
101
  disableExtension,
98
102
  dispatchScheduleTarget,
103
+ drainApi,
99
104
  emitBudgetRefusalSideEffects,
100
105
  enableExtension,
101
106
  enforceContentLengthCap,
@@ -112,6 +117,7 @@ import {
112
117
  flushAuditBuffer,
113
118
  getAgentHarnessCliVersion,
114
119
  getAutomationSetupStates,
120
+ getCombConfig,
115
121
  getEnabledCapabilities,
116
122
  getEventCountsFiltered,
117
123
  getEventsFiltered,
@@ -155,6 +161,8 @@ import {
155
161
  handleNote,
156
162
  handlePipeline,
157
163
  handlePullRequest,
164
+ handlePullRequestCommented,
165
+ handlePullRequestCreated,
158
166
  handlePullRequestReview,
159
167
  handleWebhookTrigger,
160
168
  handleWorkflowRun,
@@ -164,6 +172,7 @@ import {
164
172
  hydrateOAuthAppFromPreset,
165
173
  indexMemoryContent,
166
174
  initAgentMail,
175
+ initAzureDevOps,
167
176
  initGitHub,
168
177
  initGitLab,
169
178
  initJira,
@@ -171,6 +180,8 @@ import {
171
180
  initWorkflows,
172
181
  installExtensionWithAssets,
173
182
  isAgentMailEnabled,
183
+ isApiDraining,
184
+ isAzureDevOpsEnabled,
174
185
  isGitHubEnabled,
175
186
  isGitLabEnabled,
176
187
  isInboxAllowed,
@@ -298,6 +309,7 @@ import {
298
309
  validateJsonSchema,
299
310
  validateRecurringTiming,
300
311
  verifyAgentMailWebhook,
312
+ verifyAzureDevOpsWebhook,
301
313
  verifyGitLabWebhook,
302
314
  verifyHmacSignature,
303
315
  verifyWebhookSignature,
@@ -305,40 +317,26 @@ import {
305
317
  wireHttpSpanLifecycle,
306
318
  workflowModelErrors,
307
319
  workflowSaveWarnings
308
- } from "./cli-9hsgwz4w.js";
309
- import"./cli-0z2v4nhw.js";
320
+ } from "./cli-kp42yek0.js";
321
+ import"./cli-cat6h73s.js";
310
322
  import {
323
+ RATING_MODEL_MAX_LENGTH,
311
324
  REFERENCES_SOURCE_MAX_LENGTH,
312
325
  sanitizeReferencesSource
313
- } from "./cli-cpvsaqsw.js";
326
+ } from "./cli-w0bwte75.js";
314
327
  import {
315
328
  isMultiRuntimeEnabled
316
329
  } from "./cli-re8z5p8p.js";
317
- import {
318
- FilesError,
319
- getFileStorageProvider,
320
- normalizeFilesError
321
- } from "./cli-jsp14b6c.js";
322
- import {
323
- getUserGrant
324
- } from "./cli-tzx2ke1v.js";
325
- import {
326
- LEGACY_RULES,
327
- can,
328
- clearAuditSink,
329
- decideToolAdmission,
330
- isRbacEnabled,
331
- setAuditSink
332
- } from "./cli-tmqt7dpj.js";
330
+ import"./cli-wxkkd0e0.js";
333
331
  import {
334
332
  deleteModelCatalogOverlay,
335
333
  loadModelsCatalog,
336
334
  requestModelCatalogRefresh,
337
335
  upsertModelCatalogOverlay
338
- } from "./cli-tfky2838.js";
336
+ } from "./cli-zvhd3f64.js";
339
337
  import {
340
338
  normalizeModelKey
341
- } from "./cli-vctdqs5h.js";
339
+ } from "./cli-vy3ed88x.js";
342
340
  import {
343
341
  ConnectionAuthInputSchema,
344
342
  MAX_SCRIPT_WALL_CLOCK_MS,
@@ -431,8 +429,11 @@ import {
431
429
  upsertScriptByName,
432
430
  upsertScriptConnection,
433
431
  validateDefinition
434
- } from "./cli-tpq83z89.js";
432
+ } from "./cli-5xhpb3kv.js";
435
433
  import"./cli-epan13p1.js";
434
+ import {
435
+ getApiKey
436
+ } from "./cli-f14fvzag.js";
436
437
  import {
437
438
  detachedProcessGroup,
438
439
  forceTerminateProcessGroup,
@@ -440,10 +441,7 @@ import {
440
441
  signalProcessGroup,
441
442
  terminateProcessGroup
442
443
  } from "./cli-y89t4nca.js";
443
- import {
444
- getApiKey
445
- } from "./cli-f14fvzag.js";
446
- import"./cli-12tszpk9.js";
444
+ import"./cli-5bcd7sfy.js";
447
445
  import {
448
446
  CLIENT_ID,
449
447
  MAX_CODEX_OAUTH_SLOT,
@@ -454,14 +452,35 @@ import {
454
452
  getAccountId,
455
453
  getValidCodexOAuth,
456
454
  loadAllCodexOAuthSlots
457
- } from "./cli-ygwm91nt.js";
455
+ } from "./cli-yy6dew39.js";
458
456
  import"./cli-3dpj7atn.js";
459
- import"./cli-10nhj6xq.js";
457
+ import"./cli-2x0e561b.js";
458
+ import"./cli-nt8hecg9.js";
460
459
  import"./cli-rb9m6rpe.js";
461
- import"./cli-rykfmgwg.js";
460
+ import {
461
+ AgentFsProvider,
462
+ FilesError,
463
+ agentFsRequestTimeoutMs,
464
+ getFileStorageProvider,
465
+ normalizeFilesError
466
+ } from "./cli-mzfth0bp.js";
462
467
  import {
463
468
  searchScripts
464
- } from "./cli-0jwe9034.js";
469
+ } from "./cli-sptrj5f5.js";
470
+ import {
471
+ CANDIDATE_SET_MULTIPLIER,
472
+ EMBEDDING_DIMENSIONS,
473
+ MEMORY_KEY_MAX_LENGTH,
474
+ OpenAI,
475
+ getEmbeddingProvider,
476
+ getMemoryStore,
477
+ init_constants as init_constants2,
478
+ init_key_paths,
479
+ init_openai,
480
+ init_reranker,
481
+ rerank
482
+ } from "./cli-5k6k8ta3.js";
483
+ import"./cli-cebmgwsc.js";
465
484
  import {
466
485
  acquireOAuthRefreshLock,
467
486
  buildAuthorizationUrl,
@@ -485,20 +504,8 @@ import {
485
504
  updateAuthorizationIdentity,
486
505
  updateOAuthAppById,
487
506
  upsertAuthorization
488
- } from "./cli-6cs6wzxt.js";
507
+ } from "./cli-kh04eqwe.js";
489
508
  import"./cli-fad8m16k.js";
490
- import {
491
- CANDIDATE_SET_MULTIPLIER,
492
- EMBEDDING_DIMENSIONS,
493
- OpenAI,
494
- getEmbeddingProvider,
495
- getMemoryStore,
496
- init_constants as init_constants2,
497
- init_openai,
498
- init_reranker,
499
- rerank
500
- } from "./cli-jz4w45qt.js";
501
- import"./cli-25fcq4b4.js";
502
509
  import"./cli-bsakbbkm.js";
503
510
  import"./cli-trc24wk2.js";
504
511
  import"./cli-51tf7ac3.js";
@@ -521,12 +528,49 @@ import {
521
528
  withRemoteContext,
522
529
  withSpan,
523
530
  withSpanContext
524
- } from "./cli-azhgzetg.js";
531
+ } from "./cli-swfmp1fx.js";
525
532
  import"./cli-q51yprfq.js";
526
533
  import"./cli-3er6gcsn.js";
527
- import"./cli-2658f6at.js";
534
+ import"./cli-cvk6yzw5.js";
528
535
  import"./cli-yatxqynm.js";
529
536
  import {
537
+ bedrockProviderModule
538
+ } from "./cli-rfjw9jw2.js";
539
+ import"./cli-yn0a417a.js";
540
+ import"./cli-cgj4hc12.js";
541
+ import"./cli-txgcknmy.js";
542
+ import"./cli-6map995v.js";
543
+ import"./cli-mbssg1xv.js";
544
+ import"./cli-y2apkfe2.js";
545
+ import"./cli-7kyk9jr3.js";
546
+ import {
547
+ setBedrockProviderModule
548
+ } from "./cli-13hw4z91.js";
549
+ import"./cli-ykk5jaax.js";
550
+ import"./cli-btbzvq95.js";
551
+ import"./cli-1m2e086m.js";
552
+ import"./cli-bzr0ftht.js";
553
+ import"./cli-bd957dgb.js";
554
+ import {
555
+ import_websocket,
556
+ import_websocket_server
557
+ } from "./cli-76yrvwsa.js";
558
+ import"./cli-pzxba7gw.js";
559
+ import {
560
+ getUserGrant,
561
+ init_rbac_roles
562
+ } from "./cli-2zy95vhm.js";
563
+ import {
564
+ LEGACY_RULES,
565
+ can,
566
+ clearAuditSink,
567
+ decideToolAdmission,
568
+ init_rbac,
569
+ isRbacEnabled,
570
+ setAuditSink
571
+ } from "./cli-kdkwd3yr.js";
572
+ import {
573
+ API_DRAINING_HEADER,
530
574
  CODEX_AUTH_WATCH_NAMESPACE,
531
575
  CredentialBindingSchema,
532
576
  DB_RETENTION_TUNING_BOUNDS,
@@ -543,6 +587,7 @@ import {
543
587
  agentContextKey,
544
588
  auditAssetKeys,
545
589
  backfillSupersedeTaskResumeTaskId,
590
+ cachedUserRole,
546
591
  cancelTask,
547
592
  checkoutPromptTemplate,
548
593
  claimKv,
@@ -556,6 +601,7 @@ import {
556
601
  codexAuthBenchMarkerKey,
557
602
  completeTask,
558
603
  computeContentHash,
604
+ configureOrgDomainPersistence,
559
605
  countActiveScriptRuns,
560
606
  countAllMetrics,
561
607
  countAllPages,
@@ -605,6 +651,7 @@ import {
605
651
  emitBuiltInIntegrationConnectedOnce,
606
652
  emitIntegrationConnected,
607
653
  emitMcpServerConnectedTelemetry,
654
+ emitTaskTelemetry,
608
655
  encryptSecret,
609
656
  extensionAgentAssignmentError,
610
657
  failTask,
@@ -635,6 +682,7 @@ import {
635
682
  getContextSnapshotsByTaskId,
636
683
  getContextSummaryByTaskId,
637
684
  getCurrentRequestAuth,
685
+ getCurrentRequestUserId,
638
686
  getDashboardCostSummary,
639
687
  getDb,
640
688
  getDbClient,
@@ -717,6 +765,7 @@ import {
717
765
  incrKv,
718
766
  incrementPageViewCount,
719
767
  initTelemetry,
768
+ init_api_drain,
720
769
  init_asset_key_audit,
721
770
  init_codex_auth_failure,
722
771
  init_context_key,
@@ -728,11 +777,15 @@ import {
728
777
  init_heartbeat_expiry,
729
778
  init_human_free,
730
779
  init_request_auth_context,
780
+ init_runtime,
731
781
  init_steering,
732
782
  init_swarm_config_guard,
733
783
  init_task_tool_manifest,
734
784
  init_telemetry,
785
+ init_telemetry_identity,
786
+ init_telemetry_trigger,
735
787
  init_templates,
788
+ init_templates1 as init_templates2,
736
789
  insertActiveSession,
737
790
  insertPricingRow,
738
791
  installMcpServer,
@@ -743,6 +796,7 @@ import {
743
796
  isReservedConfigKey,
744
797
  isSteeringEnabled as isSteeringEnabled2,
745
798
  isTelemetryEnabled,
799
+ isTelemetryReady,
746
800
  listAgentsWithCredStatusByProvider,
747
801
  listAllMetrics,
748
802
  listAllPages,
@@ -775,12 +829,14 @@ import {
775
829
  pauseTask,
776
830
  placeholderForConfigKey,
777
831
  promoteDraftTask,
832
+ recomputeOrgDomain,
778
833
  recordBudgetRefusalNotification,
779
834
  recordInlineScriptRun,
780
835
  recordKeyAuthFailure,
781
836
  recordKeyRateLimitWindows,
782
837
  recordKeySeatMismatch,
783
838
  recordKeyUsage,
839
+ recordTaskProviderIfUnset,
784
840
  requestSteering,
785
841
  reservedKeyError,
786
842
  resetEmptyPollCount,
@@ -788,6 +844,7 @@ import {
788
844
  resetPromptTemplateToDefault,
789
845
  resolveApprovalRequest,
790
846
  resolvePromptTemplate,
847
+ resolveTriggerSurface,
791
848
  resumeTask,
792
849
  searchSkills,
793
850
  selectTaskTools,
@@ -797,6 +854,7 @@ import {
797
854
  setFavorite,
798
855
  setHumanFreeQueueListener,
799
856
  setRequestAuth,
857
+ setTelemetryRoleResolver,
800
858
  settleSupersededTaskDependents,
801
859
  startTask,
802
860
  supersedeTask,
@@ -841,8 +899,7 @@ import {
841
899
  upsertSwarmConfig,
842
900
  validateConfigValue,
843
901
  withFavoriteFlags
844
- } from "./cli-qydf22qq.js";
845
- import"./cli-3qhyh31j.js";
902
+ } from "./cli-jf7wmv1r.js";
846
903
  import {
847
904
  ActiveSessionSchema,
848
905
  AgentAcpStatusSchema,
@@ -969,47 +1026,53 @@ import {
969
1026
  isSafeBundlePath,
970
1027
  isTerminalTaskStatus,
971
1028
  splitLegacyModelAlias
972
- } from "./cli-ktmyrtpn.js";
1029
+ } from "./cli-xqpk3rp7.js";
1030
+ import"./cli-3qhyh31j.js";
973
1031
  import {
974
1032
  IDENTITY_FIELD_BUDGETS,
975
1033
  IdentityFieldBudgetError,
976
1034
  init_identity_field_budget
977
- } from "./cli-r1mxd1xh.js";
1035
+ } from "./cli-7af8yhav.js";
978
1036
  import {
979
1037
  getSlackConfiguration,
980
1038
  init_config
981
1039
  } from "./cli-n7h1kqpf.js";
982
1040
  import {
983
- getAllTemplateDefinitions,
984
- getTemplateDefinition,
985
- init_registry,
986
- init_resolver,
987
1041
  init_steering_enabled,
988
- init_template,
989
- interpolate,
990
- isSteeringEnabled,
991
- resolveTemplate
992
- } from "./cli-ptr8h7kp.js";
1042
+ isSteeringEnabled
1043
+ } from "./cli-eg0b3p0k.js";
1044
+ import"./cli-xk79303e.js";
1045
+ import {
1046
+ MODEL_SCOPED_WINDOWS,
1047
+ activeModelBlocks,
1048
+ init_model_rate_limit_windows
1049
+ } from "./cli-ywybs5as.js";
993
1050
  import {
994
1051
  MAX_PROFILE_FILE_LENGTH,
1052
+ agentFsFileRoute,
995
1053
  getAppUrl,
996
1054
  getConfiguredAppUrls,
997
1055
  getMcpBaseUrl,
998
1056
  getPublicMcpBaseUrl,
999
1057
  init_constants
1000
- } from "./cli-dv6cdjs2.js";
1058
+ } from "./cli-gd4favx9.js";
1059
+ import"./cli-qrgt5bqf.js";
1060
+ import {
1061
+ getAllTemplateDefinitions,
1062
+ getTemplateDefinition,
1063
+ init_registry,
1064
+ init_resolver,
1065
+ init_template,
1066
+ interpolate,
1067
+ resolveTemplate
1068
+ } from "./cli-qjjvzwzd.js";
1001
1069
  import {
1002
1070
  SUBSCRIPTION_PLANS,
1003
1071
  SUBSCRIPTION_PLANS_CHECKED_AT,
1004
1072
  init_subscription_plans,
1005
1073
  isSubscriptionPlanId
1006
1074
  } from "./cli-1a2j50m0.js";
1007
- import"./cli-0wgxmwf6.js";
1008
- import {
1009
- MODEL_SCOPED_WINDOWS,
1010
- activeModelBlocks,
1011
- init_model_rate_limit_windows
1012
- } from "./cli-ywybs5as.js";
1075
+ import"./cli-f9w1semm.js";
1013
1076
  import {
1014
1077
  init_env_flag,
1015
1078
  isEnvFlagEnabled,
@@ -1018,7 +1081,7 @@ import {
1018
1081
  import {
1019
1082
  init_src,
1020
1083
  isAlias
1021
- } from "./cli-kmcpfwn2.js";
1084
+ } from "./cli-jyy6pm2f.js";
1022
1085
  import {
1023
1086
  exports_zod,
1024
1087
  init_zod
@@ -1035,36 +1098,13 @@ import {
1035
1098
  import {
1036
1099
  init_package,
1037
1100
  package_default
1038
- } from "./cli-0q3avq3s.js";
1101
+ } from "./cli-sqvfa090.js";
1039
1102
  import {
1040
1103
  init_secret_scrubber,
1041
1104
  registerVolatileSecret,
1042
1105
  scrubObject,
1043
1106
  scrubSecrets
1044
- } from "./cli-r2ap2czm.js";
1045
- import {
1046
- bedrockProviderModule
1047
- } from "./cli-et8m9xsv.js";
1048
- import"./cli-yn0a417a.js";
1049
- import"./cli-cgj4hc12.js";
1050
- import"./cli-txgcknmy.js";
1051
- import"./cli-6map995v.js";
1052
- import"./cli-ybgv4kw2.js";
1053
- import"./cli-y2apkfe2.js";
1054
- import"./cli-7kyk9jr3.js";
1055
- import {
1056
- setBedrockProviderModule
1057
- } from "./cli-13hw4z91.js";
1058
- import"./cli-btbzvq95.js";
1059
- import"./cli-1m2e086m.js";
1060
- import"./cli-ykk5jaax.js";
1061
- import"./cli-bzr0ftht.js";
1062
- import"./cli-bd957dgb.js";
1063
- import {
1064
- import_websocket,
1065
- import_websocket_server
1066
- } from "./cli-76yrvwsa.js";
1067
- import"./cli-pzxba7gw.js";
1107
+ } from "./cli-nexqx4ve.js";
1068
1108
  import {
1069
1109
  init_event_bus,
1070
1110
  workflowEventBus
@@ -1105,21 +1145,34 @@ var YIELD_MS = 25;
1105
1145
  var DB_RETENTION_TABLES = [
1106
1146
  {
1107
1147
  table: "session_logs",
1148
+ policy: "age",
1108
1149
  timeColumn: "createdAt",
1109
1150
  envKey: "SESSION_LOG_RETENTION_DAYS",
1110
1151
  metricsKey: "sessionLogs"
1111
1152
  },
1112
1153
  {
1113
1154
  table: "agent_log",
1155
+ policy: "age",
1114
1156
  timeColumn: "createdAt",
1115
1157
  envKey: "AGENT_LOG_RETENTION_DAYS",
1116
1158
  metricsKey: "agentLog"
1117
1159
  },
1118
1160
  {
1119
1161
  table: "events",
1162
+ policy: "age",
1120
1163
  timeColumn: "createdAt",
1121
1164
  envKey: "EVENTS_RETENTION_DAYS",
1122
1165
  metricsKey: "events"
1166
+ },
1167
+ {
1168
+ table: "context_versions",
1169
+ policy: "keepLatest",
1170
+ partitionBy: "agentId, field",
1171
+ rankBy: "version",
1172
+ envKey: "CONTEXT_VERSIONS_KEEP_LATEST",
1173
+ metricsKey: "contextVersions",
1174
+ initialBatchSize: 50,
1175
+ maxBatchSize: 100
1123
1176
  }
1124
1177
  ];
1125
1178
 
@@ -1233,42 +1286,67 @@ function readTuningEnv(key, fallback) {
1233
1286
  function yieldTick() {
1234
1287
  return new Promise((resolve) => setTimeout(resolve, YIELD_MS));
1235
1288
  }
1236
- function retentionDays(table) {
1289
+ function retentionValue(table) {
1237
1290
  return readPositiveIntEnv(table.envKey);
1238
1291
  }
1292
+ function initialBatchSize(table) {
1293
+ return "initialBatchSize" in table ? table.initialBatchSize : DEFAULT_BATCH_SIZE;
1294
+ }
1295
+ function maxBatchSize(table) {
1296
+ return "maxBatchSize" in table ? table.maxBatchSize : MAX_BATCH_SIZE;
1297
+ }
1298
+ function sweepStatements(table, value, now) {
1299
+ if (table.policy === "keepLatest") {
1300
+ const ranked = `SELECT rowid AS rid, ROW_NUMBER() OVER (PARTITION BY ${table.partitionBy} ORDER BY ${table.rankBy} DESC) AS rn FROM ${table.table}`;
1301
+ return {
1302
+ backlogSql: `SELECT COUNT(*) AS n FROM (${ranked}) WHERE rn > ?`,
1303
+ deleteSql: `DELETE FROM ${table.table} WHERE rowid IN (
1304
+ SELECT rid FROM (${ranked}) WHERE rn > ? ORDER BY rn DESC LIMIT ?
1305
+ )`,
1306
+ params: [value]
1307
+ };
1308
+ }
1309
+ const cutoff = new Date(now.getTime() - value * DAY_MS).toISOString();
1310
+ return {
1311
+ backlogSql: `SELECT COUNT(*) AS n FROM ${table.table} WHERE ${table.timeColumn} < ?`,
1312
+ deleteSql: `DELETE FROM ${table.table} WHERE rowid IN (
1313
+ SELECT rowid FROM ${table.table} WHERE ${table.timeColumn} < ? ORDER BY ${table.timeColumn} LIMIT ?
1314
+ )`,
1315
+ params: [cutoff]
1316
+ };
1317
+ }
1239
1318
  function dryRunEnabled(env = process.env) {
1240
1319
  const raw = env.DB_RETENTION_DRY_RUN;
1241
1320
  if (raw === undefined || raw.trim() === "")
1242
1321
  return false;
1243
1322
  return isEnvFlagEnabled("DB_RETENTION_DRY_RUN", true, env);
1244
1323
  }
1245
- async function indexedBacklogCount(table, cutoff) {
1246
- const row = await getDbClient().get(`SELECT COUNT(*) AS n FROM ${table.table} WHERE ${table.timeColumn} < ?`, [cutoff]);
1324
+ async function indexedBacklogCount(statements) {
1325
+ const row = await getDbClient().get(statements.backlogSql, statements.params);
1247
1326
  return row?.n ?? 0;
1248
1327
  }
1249
- async function sweepTable(table, cutoff, dryRun, deadline, signal, maxStatementMs) {
1328
+ async function sweepTable(table, statements, dryRun, deadline, signal, maxStatementMs) {
1250
1329
  const client = getDbClient();
1251
1330
  if (dryRun) {
1252
- const backlogRemaining = await indexedBacklogCount(table, cutoff);
1331
+ const backlogRemaining = await indexedBacklogCount(statements);
1253
1332
  return {
1254
1333
  rowsDeleted: 0,
1255
1334
  batches: 0,
1256
1335
  backlogRemaining,
1257
1336
  drained: backlogRemaining === 0,
1258
1337
  slowestStatementMs: 0,
1259
- batchSize: batchSizeByTable[table.metricsKey] ?? DEFAULT_BATCH_SIZE
1338
+ batchSize: batchSizeByTable[table.metricsKey] ?? initialBatchSize(table)
1260
1339
  };
1261
1340
  }
1262
1341
  let rowsDeleted = 0;
1263
1342
  let batches = 0;
1264
1343
  let slowestStatementMs = 0;
1265
- let size = batchSizeByTable[table.metricsKey] ?? DEFAULT_BATCH_SIZE;
1344
+ let size = batchSizeByTable[table.metricsKey] ?? initialBatchSize(table);
1345
+ const ceiling = maxBatchSize(table);
1266
1346
  try {
1267
1347
  while (!signal.aborted && Date.now() < deadline) {
1268
1348
  const limitUsed = size;
1269
- const result = await client.runTimed(`DELETE FROM ${table.table} WHERE rowid IN (
1270
- SELECT rowid FROM ${table.table} WHERE ${table.timeColumn} < ? ORDER BY ${table.timeColumn} LIMIT ?
1271
- )`, [cutoff, limitUsed]);
1349
+ const result = await client.runTimed(statements.deleteSql, [...statements.params, limitUsed]);
1272
1350
  const elapsed = result.executionMs;
1273
1351
  bestEffortRecordStatement(table.table, dryRun, elapsed);
1274
1352
  slowestStatementMs = Math.max(slowestStatementMs, elapsed);
@@ -1277,7 +1355,7 @@ async function sweepTable(table, cutoff, dryRun, deadline, signal, maxStatementM
1277
1355
  if (elapsed > maxStatementMs) {
1278
1356
  size = Math.max(MIN_BATCH_SIZE, Math.floor(size / 2));
1279
1357
  } else if (elapsed < maxStatementMs / 5) {
1280
- size = Math.min(MAX_BATCH_SIZE, size * 2);
1358
+ size = Math.min(ceiling, size * 2);
1281
1359
  }
1282
1360
  if (result.changes < limitUsed)
1283
1361
  break;
@@ -1285,7 +1363,7 @@ async function sweepTable(table, cutoff, dryRun, deadline, signal, maxStatementM
1285
1363
  break;
1286
1364
  await yieldTick();
1287
1365
  }
1288
- const backlogRemaining = await indexedBacklogCount(table, cutoff);
1366
+ const backlogRemaining = await indexedBacklogCount(statements);
1289
1367
  return {
1290
1368
  rowsDeleted,
1291
1369
  batches,
@@ -1327,7 +1405,7 @@ function runDbRetentionTick(options = {}) {
1327
1405
  const sweepAllTables = async (rawTickSpan) => {
1328
1406
  const tickSpan = bestEffortSpan(rawTickSpan);
1329
1407
  const tickDeadline = tickStartedAt + budget;
1330
- const enabled = DB_RETENTION_TABLES.filter((table) => retentionDays(table) !== null);
1408
+ const enabled = DB_RETENTION_TABLES.filter((table) => retentionValue(table) !== null);
1331
1409
  if (enabled.length === 0) {
1332
1410
  lastSweepOrder = [];
1333
1411
  tickSpan.setAttributes({
@@ -1346,8 +1424,8 @@ function runDbRetentionTick(options = {}) {
1346
1424
  let anyError = false;
1347
1425
  const undrained = new Set;
1348
1426
  const sweepOne = async (table, tableDeadline) => {
1349
- const days = retentionDays(table);
1350
- if (days === null)
1427
+ const value = retentionValue(table);
1428
+ if (value === null)
1351
1429
  return;
1352
1430
  const startedAt = Date.now();
1353
1431
  const previous = retentionStats[table.metricsKey];
@@ -1355,8 +1433,7 @@ function runDbRetentionTick(options = {}) {
1355
1433
  "agentswarm.retention.table": table.table
1356
1434
  });
1357
1435
  try {
1358
- const cutoff = new Date(cutoffBase.getTime() - days * DAY_MS).toISOString();
1359
- const result = await sweepTable(table, cutoff, dryRun, tableDeadline, abortController.signal, maxStatementMs);
1436
+ const result = await sweepTable(table, sweepStatements(table, value, cutoffBase), dryRun, tableDeadline, abortController.signal, maxStatementMs);
1360
1437
  deletedAny ||= !dryRun && result.rowsDeleted > 0;
1361
1438
  const cumulative = (cumulativeRowsDeleted[table.metricsKey] ?? 0) + (dryRun ? 0 : result.rowsDeleted);
1362
1439
  cumulativeRowsDeleted[table.metricsKey] = cumulative;
@@ -1418,7 +1495,7 @@ function runDbRetentionTick(options = {}) {
1418
1495
  const backlogRemaining = previous?.backlogRemaining ?? 0;
1419
1496
  const batches = partial?.progress.batches ?? 0;
1420
1497
  const slowestStatementMs = partial?.progress.slowestStatementMs ?? 0;
1421
- const batchSize = partial?.progress.batchSize ?? previous?.batchSize ?? batchSizeByTable[table.metricsKey] ?? DEFAULT_BATCH_SIZE;
1498
+ const batchSize = partial?.progress.batchSize ?? previous?.batchSize ?? batchSizeByTable[table.metricsKey] ?? initialBatchSize(table);
1422
1499
  const cumulative = (cumulativeRowsDeleted[table.metricsKey] ?? 0) + rowsDeleted;
1423
1500
  cumulativeRowsDeleted[table.metricsKey] = cumulative;
1424
1501
  deletedAny ||= rowsDeleted > 0;
@@ -1528,7 +1605,7 @@ function getDbRetentionStats() {
1528
1605
  async function startDbRetention(intervalMs = RETENTION_INTERVAL_MS) {
1529
1606
  if (retentionTimer)
1530
1607
  return;
1531
- const configured = DB_RETENTION_TABLES.map((table) => `${table.table}=${retentionDays(table) ?? "disabled"}`).join(", ");
1608
+ const configured = DB_RETENTION_TABLES.map((table) => `${table.table}=${retentionValue(table) ?? "disabled"}`).join(", ");
1532
1609
  console.log(`[db-retention] starting (${configured}, dryRun=${dryRunEnabled()})`);
1533
1610
  retentionTimer = scheduleContextFree(() => setInterval(() => void runDbRetentionTick(), intervalMs));
1534
1611
  if (typeof retentionTimer.unref === "function")
@@ -1904,6 +1981,7 @@ function stopQueueStallAlarm() {
1904
1981
  }
1905
1982
 
1906
1983
  // src/http/index.ts
1984
+ init_rbac();
1907
1985
  init_bus();
1908
1986
 
1909
1987
  // src/realtime/transport.ts
@@ -1911,6 +1989,47 @@ init_zod();
1911
1989
  init_db();
1912
1990
  init_secret_scrubber();
1913
1991
  init_bus();
1992
+
1993
+ // src/realtime/tickets.ts
1994
+ var REALTIME_TICKET_TTL_MS = 60000;
1995
+ var REALTIME_TICKET_CAPACITY = 1e4;
1996
+ var tickets = new Map;
1997
+ function sweepRealtimeTickets(now = Date.now()) {
1998
+ let removed = 0;
1999
+ for (const [ticket, entry] of tickets) {
2000
+ if (entry.expiresAt > now)
2001
+ continue;
2002
+ tickets.delete(ticket);
2003
+ removed++;
2004
+ }
2005
+ return removed;
2006
+ }
2007
+ function issueRealtimeTicket(auth, now = Date.now()) {
2008
+ sweepRealtimeTickets(now);
2009
+ while (tickets.size >= REALTIME_TICKET_CAPACITY) {
2010
+ const oldest = tickets.keys().next().value;
2011
+ if (oldest === undefined)
2012
+ break;
2013
+ tickets.delete(oldest);
2014
+ }
2015
+ let ticket;
2016
+ do {
2017
+ const bytes = crypto.getRandomValues(new Uint8Array(24));
2018
+ ticket = Buffer.from(bytes).toString("base64url");
2019
+ } while (tickets.has(ticket));
2020
+ const expiresAt = now + REALTIME_TICKET_TTL_MS;
2021
+ tickets.set(ticket, { auth, expiresAt });
2022
+ return { ticket, expiresAt };
2023
+ }
2024
+ function redeemRealtimeTicket(ticket, now = Date.now()) {
2025
+ const entry = tickets.get(ticket);
2026
+ if (!entry)
2027
+ return null;
2028
+ tickets.delete(ticket);
2029
+ return entry.expiresAt > now ? entry.auth : null;
2030
+ }
2031
+
2032
+ // src/realtime/transport.ts
1914
2033
  var nameSchema = exports_external.string().regex(/^[a-zA-Z0-9_-]{1,64}$/);
1915
2034
  var messageSchema = exports_external.object({
1916
2035
  id: exports_external.number().int().nonnegative(),
@@ -1938,8 +2057,33 @@ function header(req, name) {
1938
2057
  const value = req.headers[name];
1939
2058
  return Array.isArray(value) ? value[0] : value;
1940
2059
  }
2060
+ function identityFromHttpAuth(req, auth) {
2061
+ const agentId = auth.kind === "operator" ? header(req, "x-agent-id") : undefined;
2062
+ const guestId = `guest-${crypto.randomUUID()}`;
2063
+ return {
2064
+ identity: {
2065
+ agentId,
2066
+ sourceTaskId: header(req, "x-source-task-id"),
2067
+ userId: auth.kind === "user" ? auth.userId : undefined,
2068
+ isOperator: auth.kind === "operator"
2069
+ },
2070
+ me: {
2071
+ userId: auth.kind === "user" ? auth.userId : agentId ?? guestId,
2072
+ name: auth.kind === "user" ? auth.user.name : agentId ?? `Guest ${guestId.slice(-6)}`,
2073
+ kind: auth.kind === "user" ? "user" : agentId ? "agent" : "guest"
2074
+ },
2075
+ expiresAt: undefined
2076
+ };
2077
+ }
1941
2078
  async function authenticate(req) {
1942
2079
  const url = new URL(req.url ?? "/", "http://localhost");
2080
+ const ticket = url.searchParams.get("ticket");
2081
+ if (ticket) {
2082
+ const auth2 = redeemRealtimeTicket(ticket);
2083
+ if (!auth2)
2084
+ throw new Error("Authentication required");
2085
+ return identityFromHttpAuth(req, auth2);
2086
+ }
1943
2087
  const pageId = url.searchParams.get("pageId");
1944
2088
  if (pageId) {
1945
2089
  const origin = header(req, "origin");
@@ -1954,12 +2098,12 @@ async function authenticate(req) {
1954
2098
  throw new Error("Page session required");
1955
2099
  if (session?.uid && (await findUserById(session.uid))?.status !== "active")
1956
2100
  throw new Error("Viewer is inactive");
1957
- const guestId2 = `guest-${crypto.randomUUID()}`;
2101
+ const guestId = `guest-${crypto.randomUUID()}`;
1958
2102
  return {
1959
2103
  identity: { pageId, userId: session?.uid },
1960
2104
  me: {
1961
- userId: session?.uid ?? guestId2,
1962
- name: session?.name ?? `Guest ${guestId2.slice(-6)}`,
2105
+ userId: session?.uid ?? guestId,
2106
+ name: session?.name ?? `Guest ${guestId.slice(-6)}`,
1963
2107
  kind: session?.uid ? "user" : "guest"
1964
2108
  },
1965
2109
  expiresAt: session ? session.exp * 1000 : undefined
@@ -1968,22 +2112,7 @@ async function authenticate(req) {
1968
2112
  const auth = await resolveHttpRequestAuth(req, getApiKey());
1969
2113
  if (!auth)
1970
2114
  throw new Error("Authentication required");
1971
- const agentId = auth.kind === "operator" ? header(req, "x-agent-id") : undefined;
1972
- const guestId = `guest-${crypto.randomUUID()}`;
1973
- return {
1974
- identity: {
1975
- agentId,
1976
- sourceTaskId: header(req, "x-source-task-id"),
1977
- userId: auth.kind === "user" ? auth.userId : undefined,
1978
- isOperator: auth.kind === "operator"
1979
- },
1980
- me: {
1981
- userId: auth.kind === "user" ? auth.userId : agentId ?? guestId,
1982
- name: auth.kind === "user" ? auth.user.name : agentId ?? `Guest ${guestId.slice(-6)}`,
1983
- kind: auth.kind === "user" ? "user" : agentId ? "agent" : "guest"
1984
- },
1985
- expiresAt: undefined
1986
- };
2115
+ return identityFromHttpAuth(req, auth);
1987
2116
  }
1988
2117
  function channelTopic(namespace, name) {
1989
2118
  return `channel:${JSON.stringify([namespace, name])}`;
@@ -1993,7 +2122,8 @@ function attachRealtimeTransport(server) {
1993
2122
  let pendingUpgrades = 0;
1994
2123
  let closing = false;
1995
2124
  const onUpgrade = (req, socket, head) => {
1996
- if (closing || req.url?.split("?")[0] !== "/@swarm/realtime" || wss.clients.size + pendingUpgrades >= 1000) {
2125
+ const path = req.url?.split("?")[0];
2126
+ if (closing || path !== "/@swarm/realtime" && path !== "/api/realtime" || wss.clients.size + pendingUpgrades >= 1000) {
1997
2127
  socket.destroy();
1998
2128
  return;
1999
2129
  }
@@ -2100,8 +2230,10 @@ function connect(ws, auth) {
2100
2230
  if ("error" in resolved)
2101
2231
  throw new Error(resolved.error);
2102
2232
  const namespace = resolved.namespace;
2103
- const write = ["update", "change", "reset", "presence", "publish"].includes(msg.op);
2104
- const denied = await authorizeRoomNamespace(namespace, auth.identity, write);
2233
+ if (namespace.startsWith("presence:comb:") && msg.name !== "default") {
2234
+ throw new Error("Comb presence uses the default room");
2235
+ }
2236
+ const denied = await authorizeRoomNamespace(namespace, auth.identity, msg.op);
2105
2237
  if (denied)
2106
2238
  throw new Error(typeof denied === "string" ? denied : "Forbidden");
2107
2239
  if (closed)
@@ -2134,7 +2266,7 @@ function connect(ws, auth) {
2134
2266
  } catch (error) {
2135
2267
  if (!(error instanceof Error) || error.message !== "room does not exist")
2136
2268
  throw error;
2137
- const creationDenied = await authorizeRoomNamespace(namespace, auth.identity, true);
2269
+ const creationDenied = await authorizeRoomNamespace(namespace, auth.identity, namespace.startsWith("presence:comb:") ? "join" : true);
2138
2270
  if (creationDenied)
2139
2271
  throw new Error(creationDenied);
2140
2272
  if (closed)
@@ -3214,6 +3346,150 @@ function getServerSessionsProcessed() {
3214
3346
 
3215
3347
  // src/http/index.ts
3216
3348
  init_telemetry();
3349
+
3350
+ // src/telemetry-snapshot.ts
3351
+ init_runtime();
3352
+ init_telemetry();
3353
+ init_telemetry_identity();
3354
+ init_secret_scrubber();
3355
+ var LAST_SNAPSHOT_KEY = "telemetry_last_snapshot_at";
3356
+ var ORG_DOMAIN_KEY = "telemetry_org_domain";
3357
+ var FIRST_SNAPSHOT_DELAY_MS = 60000;
3358
+ var TICK_INTERVAL_MS = 60 * 60000;
3359
+ var SNAPSHOT_INTERVAL_MS = 24 * 60 * 60000;
3360
+ var ACTIVE_WINDOW_MS = 7 * 24 * 60 * 60000;
3361
+ var NAMED_LINK_KINDS = ["slack", "github", "gitlab", "linear", "jira"];
3362
+ async function count(sql, params = []) {
3363
+ const row = await getDbClient().get(sql, params);
3364
+ return Number(row?.n ?? 0);
3365
+ }
3366
+ async function collectOrgSnapshot(now = Date.now()) {
3367
+ const linked = async (kind) => count(`SELECT COUNT(DISTINCT x.userId) AS n
3368
+ FROM user_external_ids x JOIN users u ON u.id = x.userId
3369
+ WHERE u.status = 'active' AND x.kind = ?`, [kind]);
3370
+ const since = new Date(now - ACTIVE_WINDOW_MS).toISOString();
3371
+ const [
3372
+ usersTotal,
3373
+ usersSuspended,
3374
+ usersAdmin,
3375
+ usersWithLogin,
3376
+ slack,
3377
+ github,
3378
+ gitlab,
3379
+ linear,
3380
+ jira,
3381
+ other,
3382
+ usersActive7d,
3383
+ agentsTotal
3384
+ ] = await Promise.all([
3385
+ count(`SELECT COUNT(*) AS n FROM users WHERE status = 'active'`),
3386
+ count(`SELECT COUNT(*) AS n FROM users WHERE status = 'suspended'`),
3387
+ count(`SELECT COUNT(DISTINCT u.id) AS n
3388
+ FROM users u
3389
+ JOIN principal_roles pr ON pr.principalType = 'user' AND pr.principalId = u.id
3390
+ JOIN roles r ON r.id = pr.roleId
3391
+ WHERE u.status = 'active' AND r.grantsAll = 1`),
3392
+ count(`SELECT COUNT(*) AS n
3393
+ FROM users u
3394
+ WHERE u.status = 'active'
3395
+ AND ((u.email IS NOT NULL AND TRIM(u.email) <> '')
3396
+ OR EXISTS (SELECT 1 FROM user_tokens t WHERE t.userId = u.id AND t.revokedAt IS NULL))`),
3397
+ linked("slack"),
3398
+ linked("github"),
3399
+ linked("gitlab"),
3400
+ linked("linear"),
3401
+ linked("jira"),
3402
+ count(`SELECT COUNT(DISTINCT x.userId) AS n
3403
+ FROM user_external_ids x JOIN users u ON u.id = x.userId
3404
+ WHERE u.status = 'active' AND x.kind NOT IN (${NAMED_LINK_KINDS.map(() => "?").join(", ")})`, [...NAMED_LINK_KINDS]),
3405
+ count(`SELECT COUNT(DISTINCT requestedByUserId) AS n
3406
+ FROM agent_tasks
3407
+ WHERE requestedByUserId IS NOT NULL AND createdAt >= ?`, [since]),
3408
+ count(`SELECT COUNT(*) AS n FROM agents`)
3409
+ ]);
3410
+ return {
3411
+ users_total: usersTotal,
3412
+ users_suspended: usersSuspended,
3413
+ users_admin: usersAdmin,
3414
+ users_with_login: usersWithLogin,
3415
+ users_linked_slack: slack,
3416
+ users_linked_github: github,
3417
+ users_linked_gitlab: gitlab,
3418
+ users_linked_linear: linear,
3419
+ users_linked_jira: jira,
3420
+ users_linked_other: other,
3421
+ users_active_7d: usersActive7d,
3422
+ agents_total: agentsTotal
3423
+ };
3424
+ }
3425
+ var inFlight = null;
3426
+ function emitOrgSnapshotIfDue(deps) {
3427
+ if (inFlight)
3428
+ return inFlight;
3429
+ inFlight = (async () => {
3430
+ try {
3431
+ if (!isTelemetryReady())
3432
+ return false;
3433
+ const now = (deps.now ?? Date.now)();
3434
+ const lastRaw = await deps.getConfig(LAST_SNAPSHOT_KEY);
3435
+ const last = lastRaw ? Date.parse(lastRaw) : Number.NaN;
3436
+ if (Number.isFinite(last) && now - last < SNAPSHOT_INTERVAL_MS)
3437
+ return false;
3438
+ const snapshot = await collectOrgSnapshot(now);
3439
+ await deps.setConfig(LAST_SNAPSHOT_KEY, new Date(now).toISOString());
3440
+ telemetry.org("snapshot", snapshot);
3441
+ return true;
3442
+ } catch (err) {
3443
+ console.error("[telemetry] org.snapshot failed:", scrubSecrets(err instanceof Error ? err.message : String(err)));
3444
+ return false;
3445
+ } finally {
3446
+ inFlight = null;
3447
+ }
3448
+ })();
3449
+ return inFlight;
3450
+ }
3451
+ var tickTimer = null;
3452
+ var firstTimer = null;
3453
+ function startTelemetryTicker(deps) {
3454
+ if (!isTelemetryReady())
3455
+ return;
3456
+ stopTelemetryTicker();
3457
+ setTelemetryRoleResolver(cachedUserRole);
3458
+ const tick = async () => {
3459
+ try {
3460
+ await recomputeOrgDomain();
3461
+ } catch (err) {
3462
+ console.error("[telemetry] org domain recompute failed:", scrubSecrets(err instanceof Error ? err.message : String(err)));
3463
+ }
3464
+ await emitOrgSnapshotIfDue(deps);
3465
+ };
3466
+ Promise.resolve(deps.getConfig(ORG_DOMAIN_KEY)).then((stored) => {
3467
+ configureOrgDomainPersistence(async (domain) => {
3468
+ await deps.setConfig(ORG_DOMAIN_KEY, domain ?? "");
3469
+ }, stored || undefined);
3470
+ return recomputeOrgDomain();
3471
+ }).catch(() => {});
3472
+ firstTimer = setTimeout(() => {
3473
+ firstTimer = null;
3474
+ emitOrgSnapshotIfDue(deps);
3475
+ }, FIRST_SNAPSHOT_DELAY_MS);
3476
+ firstTimer.unref?.();
3477
+ tickTimer = setInterval(() => void tick(), TICK_INTERVAL_MS);
3478
+ tickTimer.unref?.();
3479
+ }
3480
+ function stopTelemetryTicker() {
3481
+ if (tickTimer)
3482
+ clearInterval(tickTimer);
3483
+ if (firstTimer)
3484
+ clearTimeout(firstTimer);
3485
+ tickTimer = null;
3486
+ firstTimer = null;
3487
+ setTelemetryRoleResolver(null);
3488
+ configureOrgDomainPersistence(null);
3489
+ }
3490
+
3491
+ // src/http/index.ts
3492
+ init_api_drain();
3217
3493
  init_constants();
3218
3494
  init_env_flag();
3219
3495
  init_secret_scrubber();
@@ -4213,7 +4489,7 @@ async function handleAgentsRest(req, res, pathSegments, queryParams, _myAgentId)
4213
4489
  scopeId: parsed.params.id,
4214
4490
  key: "MODEL_OVERRIDE"
4215
4491
  }))[0]?.value ?? "";
4216
- const allowedLevels = harness_provider === "acp" || harness_provider === "dsh" ? [] : reasoningCapability(harness_provider, modelForValidation ?? "").levels;
4492
+ const allowedLevels = harness_provider === "acp" ? [] : reasoningCapability(harness_provider, modelForValidation ?? "").levels;
4217
4493
  if (!allowedLevels.includes(reasoning_effort)) {
4218
4494
  json(res, {
4219
4495
  error: "Unsupported reasoning_effort for this harness/model",
@@ -5560,8 +5836,26 @@ async function approvalCancelPrincipal(req) {
5560
5836
  init_zod();
5561
5837
  init_asset_key_audit();
5562
5838
  init_db();
5839
+ init_rbac();
5563
5840
  init_types();
5564
5841
  init_request_auth_context();
5842
+
5843
+ // src/http/request-principal.ts
5844
+ init_db();
5845
+ init_request_auth_context();
5846
+ async function requestPrincipal(req, myAgentId) {
5847
+ const auth = getRequestAuth(req);
5848
+ if (auth?.kind === "operator")
5849
+ return { kind: "operator" };
5850
+ if (auth?.kind === "user")
5851
+ return { kind: "user", userId: auth.userId };
5852
+ if (!myAgentId)
5853
+ return null;
5854
+ const agent = await getAgentById(myAgentId);
5855
+ return { kind: "agent", agentId: myAgentId, isLead: agent?.isLead ?? false };
5856
+ }
5857
+
5858
+ // src/http/assets.ts
5565
5859
  var AssetKeyAuditIssueSchema = exports_external.object({
5566
5860
  severity: exports_external.enum(["fatal", "warning"]),
5567
5861
  code: exports_external.enum([
@@ -5693,17 +5987,6 @@ var moveAssetRoute = route({
5693
5987
  ungated: "preserves each entity's current mutation posture; task moves use task.fs.mutate, app moves use app.manage, scripts preserve agent ownership/global-lead rules, file moves require operator authentication, and personal destinations require a matching trusted user"
5694
5988
  }
5695
5989
  });
5696
- async function assetMovePrincipal(req, myAgentId) {
5697
- const auth = getRequestAuth(req);
5698
- if (auth?.kind === "operator")
5699
- return { kind: "operator" };
5700
- if (auth?.kind === "user")
5701
- return { kind: "user", userId: auth.userId };
5702
- if (!myAgentId)
5703
- return null;
5704
- const agent = await getAgentById(myAgentId);
5705
- return { kind: "agent", agentId: myAgentId, isLead: agent?.isLead ?? false };
5706
- }
5707
5990
  async function canMutateTaskNamespace(task, myAgentId, req) {
5708
5991
  const resource = {
5709
5992
  kind: "task",
@@ -5711,17 +5994,17 @@ async function canMutateTaskNamespace(task, myAgentId, req) {
5711
5994
  agentId: task.agentId,
5712
5995
  creatorAgentId: task.creatorAgentId
5713
5996
  };
5714
- const principal = await assetMovePrincipal(req, myAgentId);
5997
+ const principal = await requestPrincipal(req, myAgentId);
5715
5998
  if (!principal)
5716
5999
  return false;
5717
6000
  return can({ principal, verb: "task.fs.mutate", resource, source: "http" }).allow;
5718
6001
  }
5719
6002
  async function canManageAppNamespace(id, req, myAgentId) {
5720
- const principal = await assetMovePrincipal(req, myAgentId);
6003
+ const principal = await requestPrincipal(req, myAgentId);
5721
6004
  return !!principal && can({ principal, verb: "app.manage", resource: { kind: "app", appId: id }, source: "http" }).allow;
5722
6005
  }
5723
6006
  async function canManageScriptNamespace(script, req, myAgentId) {
5724
- const principal = await assetMovePrincipal(req, myAgentId);
6007
+ const principal = await requestPrincipal(req, myAgentId);
5725
6008
  if (!principal)
5726
6009
  return false;
5727
6010
  if (principal.kind === "operator")
@@ -6040,6 +6323,7 @@ init_db();
6040
6323
  // src/be/onboarding.ts
6041
6324
  init_telemetry();
6042
6325
  init_types();
6326
+ init_request_auth_context();
6043
6327
  init_zod_openapi();
6044
6328
  init_db();
6045
6329
  init_swarm_config_guard();
@@ -6059,6 +6343,7 @@ var OnboardingErrorClassSchema = exports_zod.enum([
6059
6343
  "timeout",
6060
6344
  "dimension",
6061
6345
  "model",
6346
+ "endpoint",
6062
6347
  "not_enabled",
6063
6348
  "expired",
6064
6349
  "unknown"
@@ -6081,6 +6366,7 @@ var OnboardingMemoryPresetSchema = exports_zod.enum([
6081
6366
  "openai",
6082
6367
  "openrouter",
6083
6368
  "vercel",
6369
+ "azure",
6084
6370
  "custom",
6085
6371
  "existing"
6086
6372
  ]);
@@ -6286,8 +6572,9 @@ function addTelemetry(events, state, event, properties) {
6286
6572
  });
6287
6573
  }
6288
6574
  function queueTelemetry(events) {
6575
+ const actor = { userId: getCurrentRequestUserId() ?? null };
6289
6576
  for (const item of events) {
6290
- getDbClient().afterCommit(() => telemetry.onboarding(item.event, item.properties));
6577
+ getDbClient().afterCommit(() => telemetry.onboarding(item.event, item.properties, actor));
6291
6578
  }
6292
6579
  }
6293
6580
  async function isExistingInstall() {
@@ -6648,7 +6935,9 @@ init_secret_scrubber();
6648
6935
  // src/http/config.ts
6649
6936
  init_zod();
6650
6937
  init_db();
6938
+ init_rbac_roles();
6651
6939
  init_swarm_config_guard();
6940
+ init_rbac();
6652
6941
  init_types();
6653
6942
  init_request_auth_context();
6654
6943
  init_secret_scrubber();
@@ -7374,9 +7663,452 @@ async function handleCodexOAuthKeepWarm(req, res, pathSegments) {
7374
7663
  const reason = err instanceof Error ? err.message : String(err);
7375
7664
  results.push({ slot, keySuffix, outcome: "failed", reason });
7376
7665
  }
7377
- await new Promise((resolve2) => setTimeout(resolve2, 100 + Math.random() * 200));
7666
+ await new Promise((resolve2) => setTimeout(resolve2, 100 + Math.random() * 200));
7667
+ }
7668
+ keepWarmRoute.respond(res, 200, { results });
7669
+ return true;
7670
+ }
7671
+
7672
+ // src/http/comb.ts
7673
+ init_zod();
7674
+
7675
+ // src/comb/review-batch.ts
7676
+ init_db();
7677
+ init_resolver();
7678
+ init_constants();
7679
+ init_secret_scrubber();
7680
+
7681
+ // src/comb/agent-fs.ts
7682
+ function combAgentFs() {
7683
+ try {
7684
+ const provider = getFileStorageProvider();
7685
+ return provider instanceof AgentFsProvider ? provider : null;
7686
+ } catch {
7687
+ return null;
7688
+ }
7689
+ }
7690
+ var STATUS_LOOKUP_WAIT_MS = 2000;
7691
+ async function getCombServiceUserId() {
7692
+ const agentFs = combAgentFs();
7693
+ if (!agentFs)
7694
+ return null;
7695
+ let timer;
7696
+ const timeout = new Promise((resolve2) => {
7697
+ timer = setTimeout(resolve2, STATUS_LOOKUP_WAIT_MS, null);
7698
+ });
7699
+ try {
7700
+ return await Promise.race([agentFs.getServiceUserId().catch(() => null), timeout]);
7701
+ } finally {
7702
+ clearTimeout(timer);
7703
+ }
7704
+ }
7705
+
7706
+ // src/comb/markers.ts
7707
+ var SENT_MARKER_PREFIX = "[comb:sent task=";
7708
+ var SENT_MARKER_RE = /^\[comb:sent task=([0-9a-f-]{36})\]/;
7709
+ function sentMarker(taskId) {
7710
+ return `${SENT_MARKER_PREFIX}${taskId}]`;
7711
+ }
7712
+ function sentTaskId(thread, replies, serviceUserId) {
7713
+ for (const reply of replies) {
7714
+ const bySwarm = serviceUserId ? reply.author === serviceUserId : reply.author !== thread.author;
7715
+ const taskId = bySwarm ? SENT_MARKER_RE.exec(reply.body)?.[1] : undefined;
7716
+ if (taskId)
7717
+ return taskId;
7718
+ }
7719
+ return null;
7720
+ }
7721
+
7722
+ // src/comb/review-batch.ts
7723
+ init_templates();
7724
+ var REVIEW_BATCH_MAX = 50;
7725
+ var REVIEW_BATCH_READ_CONCURRENCY = 5;
7726
+ var SENT_KV_NAMESPACE = "comb:sent";
7727
+ var PENDING_CLAIM_MS = 5 * 60000;
7728
+ var SENT_CLAIM_MS = 30 * 24 * 60 * 60000;
7729
+ var REPLY_MARGIN_MS = 5000;
7730
+
7731
+ class ReviewBatchError extends Error {
7732
+ status;
7733
+ skipped;
7734
+ constructor(status, message, skipped = []) {
7735
+ super(message);
7736
+ this.status = status;
7737
+ this.skipped = skipped;
7738
+ this.name = "ReviewBatchError";
7739
+ }
7740
+ }
7741
+ async function sendReviewBatch(input, deps = {}) {
7742
+ const comb = getCombConfig();
7743
+ if (!comb.enabled)
7744
+ throw new ReviewBatchError(404, "Comb is not enabled");
7745
+ if (!comb.orgId || !comb.driveId) {
7746
+ throw new ReviewBatchError(503, "The swarm has no agent-fs drive yet");
7747
+ }
7748
+ if (input.orgId !== comb.orgId || input.driveId !== comb.driveId) {
7749
+ throw new ReviewBatchError(400, "Comb sends comments from the swarm drive only");
7750
+ }
7751
+ const ids = [...new Set(input.commentIds)];
7752
+ if (ids.length === 0 || ids.length > REVIEW_BATCH_MAX) {
7753
+ throw new ReviewBatchError(400, `Send between 1 and ${REVIEW_BATCH_MAX} comments`);
7754
+ }
7755
+ const agentFs = combAgentFs();
7756
+ if (!agentFs)
7757
+ throw new ReviewBatchError(503, "agent-fs is not set up for this swarm");
7758
+ const drive = { orgId: input.orgId, driveId: input.driveId };
7759
+ const createTask = deps.createTask ?? createTaskWithSiblingAwareness;
7760
+ const readStartedAt = Date.now();
7761
+ const versionOf = fileVersionLookup(agentFs, drive);
7762
+ const [serviceUserId, reads] = await Promise.all([
7763
+ agentFs.getServiceUserId().catch(() => null),
7764
+ mapLimited(ids, REVIEW_BATCH_READ_CONCURRENCY, (id) => readComment(agentFs, drive, versionOf, id))
7765
+ ]);
7766
+ const skipped = [];
7767
+ const candidates = [];
7768
+ for (const read of reads) {
7769
+ const skip = skipOf(read, serviceUserId);
7770
+ if (skip)
7771
+ skipped.push(skip);
7772
+ else
7773
+ candidates.push(read);
7774
+ }
7775
+ const claim = crypto.randomUUID();
7776
+ const { won, lost } = await claimComments(candidates, claim);
7777
+ const repairs = [];
7778
+ for (const { id, entry } of lost) {
7779
+ const taskId2 = sentClaimTaskId(entry);
7780
+ if (taskId2 && entry && entry.updatedAt + replyWindowMs() < readStartedAt) {
7781
+ repairs.push({ id, taskId: taskId2 });
7782
+ } else {
7783
+ skipped.push(alreadySent(id, taskId2));
7784
+ }
7785
+ }
7786
+ const wonIds = won.map((read) => read.id);
7787
+ let taskId = null;
7788
+ if (won.length > 0) {
7789
+ try {
7790
+ const text = await renderTaskText(input, won);
7791
+ if (text === null) {
7792
+ throw new ReviewBatchError(503, "The Comb review template is disabled", [
7793
+ ...skipped,
7794
+ ...repairs.map((repair) => alreadySent(repair.id, repair.taskId))
7795
+ ]);
7796
+ }
7797
+ const lead = await getLeadAgent();
7798
+ const task = await createTask(text, {
7799
+ agentId: lead?.id ?? "",
7800
+ routingReason: lead ? "skill" : undefined,
7801
+ routingSource: lead ? "engine_default" : undefined,
7802
+ source: "comb",
7803
+ taskType: "comb-review",
7804
+ tags: ["comb"],
7805
+ requestedByUserId: input.requestedByUserId ?? undefined
7806
+ }, { origin: "rest" });
7807
+ taskId = task.id;
7808
+ } catch (error) {
7809
+ await settleClaims(wonIds, claim, null);
7810
+ throw error;
7811
+ }
7812
+ await settleClaims(wonIds, claim, { status: "sent", taskId });
7813
+ }
7814
+ const targets = [
7815
+ ...wonIds.map((id) => ({ id, taskId })),
7816
+ ...repairs
7817
+ ];
7818
+ const replies = await Promise.allSettled(targets.map((target) => agentFs.replyToComment(drive, target.id, sentReply(target.taskId))));
7819
+ const repaired = [];
7820
+ replies.forEach((reply, index) => {
7821
+ const target = targets[index];
7822
+ const isRepair = index >= wonIds.length;
7823
+ if (reply.status === "rejected") {
7824
+ console.warn(scrubSecrets(`[comb] sent reply failed comment=${target.id} task=${target.taskId}: ${errorMessage(reply.reason)}`));
7825
+ if (isRepair)
7826
+ skipped.push(alreadySent(target.id, target.taskId));
7827
+ } else if (isRepair) {
7828
+ repaired.push(target);
7829
+ }
7830
+ });
7831
+ if (taskId === null && repaired.length === 0) {
7832
+ throw new ReviewBatchError(409, "Nothing to send", skipped);
7833
+ }
7834
+ return { taskId, sent: wonIds, skipped, repaired };
7835
+ }
7836
+ async function mapLimited(items, limit, fn) {
7837
+ const results = new Array(items.length);
7838
+ let next = 0;
7839
+ const worker = async () => {
7840
+ while (next < items.length) {
7841
+ const index = next++;
7842
+ results[index] = await fn(items[index]);
7843
+ }
7844
+ };
7845
+ await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
7846
+ return results;
7847
+ }
7848
+ async function readComment(agentFs, drive, versionOf, id) {
7849
+ let thread;
7850
+ try {
7851
+ thread = await agentFs.getComment(drive, id);
7852
+ } catch (error) {
7853
+ if (error instanceof FilesError && error.code === "NotFound")
7854
+ return { id, thread: null };
7855
+ throw new ReviewBatchError(502, scrubSecrets(`agent-fs could not read comment ${id}: ${errorMessage(error)}`));
7856
+ }
7857
+ const { comment } = thread;
7858
+ const version = comment.fileVersion ?? (comment.parentId ? undefined : await versionOf(comment));
7859
+ return { id, thread, version };
7860
+ }
7861
+ function skipOf({ id, thread }, serviceUserId) {
7862
+ if (!thread)
7863
+ return { id, reason: "not-found" };
7864
+ if (thread.comment.parentId)
7865
+ return { id, reason: "reply" };
7866
+ if (thread.comment.resolved)
7867
+ return { id, reason: "resolved" };
7868
+ const taskId = sentTaskId(thread.comment, thread.replies, serviceUserId);
7869
+ return taskId ? alreadySent(id, taskId) : null;
7870
+ }
7871
+ function alreadySent(id, taskId) {
7872
+ return taskId ? { id, reason: "already-sent", taskId } : { id, reason: "already-sent" };
7873
+ }
7874
+ async function claimComments(candidates, claim) {
7875
+ return await getDbClient().transaction(async () => {
7876
+ const won = [];
7877
+ const lost = [];
7878
+ for (const read of candidates) {
7879
+ const claimed = await claimKv({
7880
+ namespace: SENT_KV_NAMESPACE,
7881
+ key: read.id,
7882
+ value: { status: "pending", claim },
7883
+ valueType: "json",
7884
+ expiresAt: Date.now() + PENDING_CLAIM_MS
7885
+ });
7886
+ if (claimed)
7887
+ won.push(read);
7888
+ else
7889
+ lost.push({ id: read.id, entry: await getKv(SENT_KV_NAMESPACE, read.id) });
7890
+ }
7891
+ return { won, lost };
7892
+ });
7893
+ }
7894
+ async function settleClaims(ids, claim, next) {
7895
+ const settled = await Promise.allSettled(ids.map((id) => getDbClient().transaction(async () => {
7896
+ const entry = await getKv(SENT_KV_NAMESPACE, id);
7897
+ if (entry && claimToken(entry) !== claim)
7898
+ return false;
7899
+ if (next) {
7900
+ await upsertKv({
7901
+ namespace: SENT_KV_NAMESPACE,
7902
+ key: id,
7903
+ value: next,
7904
+ valueType: "json",
7905
+ expiresAt: Date.now() + SENT_CLAIM_MS
7906
+ });
7907
+ } else if (entry) {
7908
+ await deleteKv(SENT_KV_NAMESPACE, id);
7909
+ }
7910
+ return true;
7911
+ })));
7912
+ settled.forEach((result, index) => {
7913
+ if (result.status === "fulfilled" && result.value)
7914
+ return;
7915
+ const why = result.status === "rejected" ? errorMessage(result.reason) : "another send holds the claim";
7916
+ console.warn(scrubSecrets(`[comb] could not ${next ? "record" : "release"} the claim on comment=${ids[index]}: ${why}`));
7917
+ });
7918
+ }
7919
+ function claimToken(entry) {
7920
+ return entry.value?.claim;
7921
+ }
7922
+ function sentClaimTaskId(entry) {
7923
+ const value = entry?.value;
7924
+ return value?.status === "sent" && typeof value.taskId === "string" ? value.taskId : null;
7925
+ }
7926
+ function replyWindowMs() {
7927
+ return agentFsRequestTimeoutMs() + REPLY_MARGIN_MS;
7928
+ }
7929
+ function sentReply(taskId) {
7930
+ return `${sentMarker(taskId)} Sent to the swarm: ${getAppUrl()}/tasks/${taskId}`;
7931
+ }
7932
+ function fileVersionLookup(agentFs, drive) {
7933
+ const logs = new Map;
7934
+ return async (comment) => {
7935
+ const path = combPath(comment.path);
7936
+ let log = logs.get(path);
7937
+ if (!log) {
7938
+ log = Promise.all([path.slice(1), path].map((form) => agentFs.getFileVersions(drive, form).catch(() => []))).then((lists) => lists.flat());
7939
+ logs.set(path, log);
7940
+ }
7941
+ const at = Date.parse(comment.createdAt);
7942
+ let found;
7943
+ for (const entry of await log) {
7944
+ if (Date.parse(entry.createdAt) <= at && (found === undefined || entry.version > found)) {
7945
+ found = entry.version;
7946
+ }
7947
+ }
7948
+ return found;
7949
+ };
7950
+ }
7951
+ async function renderTaskText(input, reads) {
7952
+ const blocks = [];
7953
+ for (const { thread, version } of reads) {
7954
+ const comment = thread.comment;
7955
+ const path = combPath(comment.path);
7956
+ const quote = comment.quote?.exact ?? comment.quotedContent;
7957
+ const block = resolveTemplate("comb.review.comment", {
7958
+ comment_id: comment.id,
7959
+ author: comment.authorDisplayName ? `${oneLine(comment.authorDisplayName)} (agent-fs user ${comment.author})` : `agent-fs user ${comment.author}`,
7960
+ path: oneLine(path),
7961
+ file_version: version ?? "unknown",
7962
+ line_range: lineRange(comment),
7963
+ quote: quote ? fenced(quote) : indent("(none)"),
7964
+ body: fenced(comment.body),
7965
+ comment_url: combUrl(input, path, comment.id)
7966
+ });
7967
+ if (block.skipped)
7968
+ return null;
7969
+ blocks.push(block.text);
7970
+ }
7971
+ const scopePath = combPath(input.scopePath);
7972
+ const batch = resolveTemplate("comb.review.batch", {
7973
+ comment_count: reads.length,
7974
+ scope_path: scopePath,
7975
+ scope_url: combUrl(input, scopePath),
7976
+ requested_by: await requesterLabel(input.requestedByUserId),
7977
+ org_id: input.orgId,
7978
+ drive_id: input.driveId,
7979
+ comments_block: blocks.join(`
7980
+ `)
7981
+ });
7982
+ return batch.skipped ? null : batch.text;
7983
+ }
7984
+ function combPath(path) {
7985
+ return `/${path.replace(/^\/+/, "")}`;
7986
+ }
7987
+ function lineRange(comment) {
7988
+ if (comment.lineStart == null)
7989
+ return "whole file";
7990
+ const end = comment.lineEnd ?? comment.lineStart;
7991
+ return end === comment.lineStart ? `line ${comment.lineStart}` : `lines ${comment.lineStart}-${end}`;
7992
+ }
7993
+ function fenced(text) {
7994
+ const longest = (text.match(/`+/g) ?? []).reduce((max, run) => Math.max(max, run.length), 0);
7995
+ const fence = "`".repeat(Math.max(3, longest + 1));
7996
+ return indent(`${fence}
7997
+ ${text}
7998
+ ${fence}`);
7999
+ }
8000
+ function indent(text) {
8001
+ return text.replace(/^/gm, " ");
8002
+ }
8003
+ function oneLine(text) {
8004
+ return text.replace(/\s+/g, " ").trim();
8005
+ }
8006
+ function combUrl(input, path, commentId) {
8007
+ const route2 = agentFsFileRoute({ path, orgId: input.orgId, driveId: input.driveId }) ?? `${input.orgId}/${input.driveId}/`;
8008
+ const url = `${getAppUrl()}/file/~/${route2}`;
8009
+ return commentId ? `${url}?comment=${encodeURIComponent(commentId)}` : url;
8010
+ }
8011
+ async function requesterLabel(userId) {
8012
+ const user = userId ? await findUserById(userId) : null;
8013
+ if (!user)
8014
+ return "an operator (swarm API key)";
8015
+ return user.email ? `${user.name} <${user.email}>` : user.name;
8016
+ }
8017
+ function errorMessage(error) {
8018
+ return error instanceof Error ? error.message : String(error);
8019
+ }
8020
+
8021
+ // src/http/comb.ts
8022
+ init_rbac();
8023
+ init_secret_scrubber();
8024
+ var skippedSchema = exports_external.object({
8025
+ id: exports_external.string(),
8026
+ reason: exports_external.enum(["not-found", "reply", "resolved", "already-sent"]),
8027
+ taskId: exports_external.string().optional()
8028
+ });
8029
+ var resultSchema = exports_external.object({
8030
+ taskId: exports_external.string().nullable(),
8031
+ sent: exports_external.array(exports_external.string()),
8032
+ skipped: exports_external.array(skippedSchema),
8033
+ repaired: exports_external.array(exports_external.object({ id: exports_external.string(), taskId: exports_external.string() }))
8034
+ });
8035
+ var batchErrorSchema = exports_external.object({ error: exports_external.string(), skipped: exports_external.array(skippedSchema) });
8036
+ function isDrivePath(path) {
8037
+ return path.startsWith("/") && !path.split("/").some((segment) => segment === "." || segment === "..");
8038
+ }
8039
+ var reviewBatchRoute = route({
8040
+ method: "post",
8041
+ path: "/api/comb/review-batches",
8042
+ pattern: ["api", "comb", "review-batches"],
8043
+ summary: "Send agent-fs comments to the swarm as one lead task",
8044
+ description: "Comb's 'Send to swarm'. The server reads each comment again from agent-fs with its bootstrap key, skips replies, resolved comments, and comments already sent, and creates ONE task for the lead. Each sent comment gets a `[comb:sent task=<id>]` reply from the swarm service account. A comment is sent at most once. When an earlier send lost its reply, the batch posts that reply again (`repaired`). Answers 404 while COMB_ENABLED is off.",
8045
+ tags: ["Comb"],
8046
+ body: exports_external.object({
8047
+ orgId: exports_external.string().min(1),
8048
+ driveId: exports_external.string().min(1),
8049
+ commentIds: exports_external.array(exports_external.uuid()).min(1).max(REVIEW_BATCH_MAX),
8050
+ scopePath: exports_external.string().min(1).max(1024).refine(isDrivePath, "scopePath must start with '/' and have no '.' or '..' segment")
8051
+ }),
8052
+ responses: {
8053
+ 200: {
8054
+ description: "No new task: the batch only posted missing 'sent' replies again",
8055
+ schema: resultSchema
8056
+ },
8057
+ 201: { description: "Task created", schema: resultSchema },
8058
+ 400: { description: "Invalid body, or not the swarm drive" },
8059
+ 403: { description: "Caller cannot create tasks" },
8060
+ 404: { description: "Comb is not enabled" },
8061
+ 409: {
8062
+ description: "Nothing to send (every comment was skipped)",
8063
+ schema: batchErrorSchema
8064
+ },
8065
+ 422: { description: "Task creation blocked by an extension" },
8066
+ 502: { description: "agent-fs could not read a comment" },
8067
+ 503: {
8068
+ description: "agent-fs or the swarm drive is not set up, or an operator disabled a Comb review template",
8069
+ schema: batchErrorSchema
8070
+ }
8071
+ },
8072
+ rbac: { permission: "task.create.own" }
8073
+ });
8074
+ async function handleComb(req, res, pathSegments, queryParams, myAgentId) {
8075
+ if (!reviewBatchRoute.match(req.method, pathSegments))
8076
+ return false;
8077
+ if (!getCombConfig().enabled) {
8078
+ jsonError(res, "Comb is not enabled", 404);
8079
+ return true;
8080
+ }
8081
+ const parsed = await reviewBatchRoute.parse(req, res, pathSegments, queryParams);
8082
+ if (!parsed)
8083
+ return true;
8084
+ const principal = await requestPrincipal(req, myAgentId);
8085
+ if (!principal || !can({ principal, verb: "task.create.own", resource: { kind: "none" }, source: "http" }).allow) {
8086
+ jsonError(res, "Not authorized to create tasks", 403);
8087
+ return true;
8088
+ }
8089
+ try {
8090
+ const result = await sendReviewBatch({
8091
+ ...parsed.body,
8092
+ requestedByUserId: await resolveHttpAuditUserId(req, myAgentId)
8093
+ });
8094
+ reviewBatchRoute.respond(res, result.taskId === null ? 200 : 201, result);
8095
+ } catch (error) {
8096
+ if (error instanceof ReviewBatchError) {
8097
+ if (error.status === 409 || error.status === 503) {
8098
+ reviewBatchRoute.respond(res, error.status, {
8099
+ error: error.message,
8100
+ skipped: error.skipped
8101
+ });
8102
+ } else {
8103
+ jsonError(res, error.message, error.status);
8104
+ }
8105
+ } else if (error instanceof TaskCreationBlockedError) {
8106
+ jsonError(res, error.reason, 422);
8107
+ } else {
8108
+ const message = error instanceof Error ? error.message : String(error);
8109
+ jsonError(res, scrubSecrets(`Failed to send comments to the swarm: ${message}`), 500);
8110
+ }
7378
8111
  }
7379
- keepWarmRoute.respond(res, 200, { results });
7380
8112
  return true;
7381
8113
  }
7382
8114
 
@@ -7663,8 +8395,8 @@ async function handleEvents(req, res, pathSegments, queryParams, _myAgentId) {
7663
8395
  if (!parsed)
7664
8396
  return true;
7665
8397
  try {
7666
- const count = await createEventsBatch(parsed.body.events);
7667
- createEventsBatchRoute.respond(res, 201, { success: true, count });
8398
+ const count2 = await createEventsBatch(parsed.body.events);
8399
+ createEventsBatchRoute.respond(res, 201, { success: true, count: count2 });
7668
8400
  } catch (error) {
7669
8401
  console.error("[HTTP] Failed to create events batch:", error);
7670
8402
  jsonError(res, "Failed to store events batch", 500);
@@ -7763,9 +8495,11 @@ declare module "swarm-extension" {
7763
8495
  | "ui"
7764
8496
  | "github"
7765
8497
  | "gitlab"
8498
+ | "azure-devops"
7766
8499
  | "system"
7767
8500
  | "linear"
7768
8501
  | "jira"
8502
+ | "comb"
7769
8503
  | undefined;
7770
8504
  routingReason?:
7771
8505
  | "skill"
@@ -7787,7 +8521,7 @@ declare module "swarm-extension" {
7787
8521
  slackTriggerMessageTs?: string | undefined;
7788
8522
  slackUserId?: string | undefined;
7789
8523
  overrideSlackContext?: boolean | undefined;
7790
- vcsProvider?: "github" | "gitlab" | undefined;
8524
+ vcsProvider?: "github" | "gitlab" | "azure-devops" | undefined;
7791
8525
  vcsRepo?: string | undefined;
7792
8526
  vcsEventType?: string | undefined;
7793
8527
  vcsNumber?: number | undefined;
@@ -7872,9 +8606,11 @@ declare module "swarm-extension" {
7872
8606
  | "ui"
7873
8607
  | "github"
7874
8608
  | "gitlab"
8609
+ | "azure-devops"
7875
8610
  | "system"
7876
8611
  | "linear"
7877
- | "jira";
8612
+ | "jira"
8613
+ | "comb";
7878
8614
  tags: string[];
7879
8615
  priority: number;
7880
8616
  dependsOn: string[];
@@ -7909,7 +8645,7 @@ declare module "swarm-extension" {
7909
8645
  slackUserId?: string | undefined;
7910
8646
  slackProgressMessageTs?: string | undefined;
7911
8647
  slackTreeRootMessageTs?: string | undefined;
7912
- vcsProvider?: "github" | "gitlab" | undefined;
8648
+ vcsProvider?: "github" | "gitlab" | "azure-devops" | undefined;
7913
8649
  vcsRepo?: string | undefined;
7914
8650
  vcsEventType?: string | undefined;
7915
8651
  vcsNumber?: number | undefined;
@@ -8433,6 +9169,175 @@ void _configIsValid;
8433
9169
 
8434
9170
  // src/extensions/catalog.generated.json
8435
9171
  var catalog_generated_default = {
9172
+ "deploy-awareness": {
9173
+ manifestFile: "manifest.json",
9174
+ manifest: {
9175
+ $schema: "../manifest.schema.json",
9176
+ name: "deploy-awareness",
9177
+ description: "Appends a one-line note to new tasks while a Dokploy compose deploy is in progress",
9178
+ version: "1.0.0",
9179
+ runtime: "api",
9180
+ assets: {
9181
+ hooks: "hooks.ts"
9182
+ }
9183
+ },
9184
+ files: {
9185
+ "hooks.ts": `import { type CtxFor, modify, type SwarmExtension } from "swarm-extension";
9186
+ import { z } from "zod";
9187
+
9188
+ // The Dokploy URL and API key are deliberately not config. Extension config is writable by a
9189
+ // lead, so a key name or a host here would let it point the API process at any env secret and
9190
+ // any host. Both come from the API process environment instead (see readApiKey, readBaseUrl).
9191
+ export const config = z.object({
9192
+ composeId: z.string().min(1),
9193
+ label: z.string().min(1).default("prod"),
9194
+ cacheTtlMs: z.number().int().min(0).default(120_000),
9195
+ // Stays under the 5s handler limit, which also covers the secret read and the cache writes.
9196
+ timeoutMs: z.number().int().min(100).max(4_000).default(2_000),
9197
+ // A "running" deployment older than this is a stuck record, not a live deploy.
9198
+ staleAfterMs: z.number().int().min(60_000).default(1_800_000),
9199
+ });
9200
+
9201
+ const manifest = {
9202
+ name: "deploy-awareness",
9203
+ description: "Appends a one-line note to new tasks while a Dokploy compose deploy is in progress",
9204
+ version: "1.0.0",
9205
+ runtime: "api",
9206
+ assets: { hooks: "hooks.ts" },
9207
+ config,
9208
+ } as const;
9209
+
9210
+ type Ctx = CtxFor<typeof manifest>;
9211
+
9212
+ type Snapshot = {
9213
+ checkedAt: number;
9214
+ /** ISO start of the deployment in progress, or null. */
9215
+ runningSince: string | null;
9216
+ failed?: true;
9217
+ };
9218
+
9219
+ type Deployment = { status?: unknown; createdAt?: unknown; startedAt?: unknown };
9220
+
9221
+ const API_KEY_ENV = "DOKPLOY_API_KEY";
9222
+ const BASE_URL_ENV = "DOKPLOY_BASE_URL";
9223
+ const DEFAULT_BASE_URL = "https://app.dokploy.com";
9224
+ const CACHE_KEY = "deploy-status";
9225
+ // The tail of the note. It does not change with the label or the time, so it marks a task
9226
+ // that already carries the note (a resume or a follow-up).
9227
+ const ADVICE =
9228
+ "your worker may restart in the next few minutes. Checkpoint with store-progress before long steps.";
9229
+
9230
+ // One check at a time per process, so tasks created together share a single Dokploy call.
9231
+ let inflight: Promise<Snapshot> | undefined;
9232
+
9233
+ function errorText(error: unknown): string {
9234
+ return error instanceof Error ? error.message : String(error);
9235
+ }
9236
+
9237
+ // The API process hydrates global swarm_config rows into process.env at boot and on config
9238
+ // reload. ctx.swarm.config_get cannot serve this: the SDK scrubs every response, so a secret
9239
+ // comes back as "[REDACTED:<name>]".
9240
+ function readApiKey(): string {
9241
+ const value = process.env[API_KEY_ENV];
9242
+ if (!value) throw new Error(\`\${API_KEY_ENV} is not set in the API process environment\`);
9243
+ return value;
9244
+ }
9245
+
9246
+ // The key goes out in a request header, so the host must be reached over TLS. The value is not
9247
+ // echoed: a URL can carry credentials.
9248
+ function readBaseUrl(): string {
9249
+ const raw = process.env[BASE_URL_ENV] || DEFAULT_BASE_URL;
9250
+ let url: URL;
9251
+ try {
9252
+ url = new URL(raw);
9253
+ } catch {
9254
+ throw new Error(\`\${BASE_URL_ENV} is not a valid URL\`);
9255
+ }
9256
+ if (url.protocol !== "https:") throw new Error(\`\${BASE_URL_ENV} must be an https URL\`);
9257
+ return raw.replace(/\\/+$/, "");
9258
+ }
9259
+
9260
+ /** The start of the newest deployment when it is still running, else null. */
9261
+ function runningSince(deployments: Deployment[], staleAfterMs: number): string | null {
9262
+ let latest: { at: number; deployment: Deployment } | undefined;
9263
+ for (const deployment of deployments) {
9264
+ const at = Date.parse(String(deployment.createdAt));
9265
+ // The list is not chronological (compose.one is not), so compare timestamps, not positions.
9266
+ if (!Number.isNaN(at) && (!latest || at > latest.at)) latest = { at, deployment };
9267
+ }
9268
+ if (latest?.deployment.status !== "running") return null;
9269
+ const started = Date.parse(String(latest.deployment.startedAt ?? latest.deployment.createdAt));
9270
+ const since = Number.isNaN(started) ? latest.at : started;
9271
+ return Date.now() - since > staleAfterMs ? null : new Date(since).toISOString();
9272
+ }
9273
+
9274
+ async function fetchRunningSince(ctx: Ctx): Promise<string | null> {
9275
+ const apiKey = readApiKey();
9276
+ const base = readBaseUrl();
9277
+ const response = await fetch(
9278
+ \`\${base}/api/deployment.allByCompose?composeId=\${encodeURIComponent(ctx.config.composeId)}\`,
9279
+ {
9280
+ headers: { "x-api-key": apiKey },
9281
+ signal: AbortSignal.any([ctx.signal, AbortSignal.timeout(ctx.config.timeoutMs)]),
9282
+ },
9283
+ );
9284
+ if (!response.ok) throw new Error(\`Dokploy answered \${response.status}\`);
9285
+ const body: unknown = await response.json();
9286
+ if (!Array.isArray(body)) throw new Error("Dokploy returned no deployment list");
9287
+ return runningSince(body as Deployment[], ctx.config.staleAfterMs);
9288
+ }
9289
+
9290
+ async function refresh(ctx: Ctx): Promise<Snapshot> {
9291
+ let snapshot: Snapshot;
9292
+ try {
9293
+ snapshot = { checkedAt: Date.now(), runningSince: await fetchRunningSince(ctx) };
9294
+ } catch (error) {
9295
+ // Cached like a result, so an outage costs one attempt per window.
9296
+ ctx.log.warn(\`deploy status check failed, tasks proceed without the note: \${errorText(error)}\`);
9297
+ snapshot = { checkedAt: Date.now(), runningSince: null, failed: true };
9298
+ }
9299
+ try {
9300
+ await ctx.state.set(CACHE_KEY, snapshot);
9301
+ } catch (error) {
9302
+ ctx.log.warn(\`deploy status cache write failed: \${errorText(error)}\`);
9303
+ }
9304
+ return snapshot;
9305
+ }
9306
+
9307
+ /** Never throws: a throw counts toward auto-disable, and a status check must not block tasks. */
9308
+ async function deployStartedAt(ctx: Ctx): Promise<string | null> {
9309
+ try {
9310
+ const cached = await ctx.state.get<Snapshot>(CACHE_KEY);
9311
+ if (cached && Date.now() - cached.checkedAt < ctx.config.cacheTtlMs) {
9312
+ return cached.runningSince;
9313
+ }
9314
+ inflight ??= refresh(ctx).finally(() => {
9315
+ inflight = undefined;
9316
+ });
9317
+ return (await inflight).runningSince;
9318
+ } catch (error) {
9319
+ ctx.log.warn(\`deploy status unavailable, tasks proceed without the note: \${errorText(error)}\`);
9320
+ return null;
9321
+ }
9322
+ }
9323
+
9324
+ const extension: SwarmExtension<typeof manifest> = (api) => {
9325
+ api.on("pre.task.create", async (event, ctx) => {
9326
+ if (event.description.includes(ADVICE)) return;
9327
+ const startedAt = await deployStartedAt(ctx);
9328
+ if (!startedAt) return;
9329
+ const time = startedAt.slice(11, 16);
9330
+ return modify({
9331
+ description: \`\${event.description}\\n\\nNote: a \${ctx.config.label} deploy started at \${time} UTC is in progress; \${ADVICE}\`,
9332
+ });
9333
+ });
9334
+ };
9335
+
9336
+ export default extension;
9337
+ `
9338
+ },
9339
+ readme: '# deploy-awareness\n\nAppends one line to a new task\'s description while a Dokploy compose deploy is in progress, so the worker knows it may restart soon:\n\n```\nNote: a prod deploy started at 14:05 UTC is in progress; your worker may restart in the next few minutes. Checkpoint with store-progress before long steps.\n```\n\nInstall config:\n\n```json\n{ "composeId": "<compose id>" }\n```\n\nOptional keys: `label` (the environment word in the note, default `prod`), `cacheTtlMs` (how long a check result, a failure included, is reused, default 120000), `timeoutMs` (caps the Dokploy call, default 2000), `staleAfterMs` (a deployment still `running` after this long is a stuck record and is ignored, default 1800000).\n\nThe Dokploy API key and URL are not extension config. Config is writable by a lead, and a key name or a host there would let it point the API process at any env secret and any host. They come from the API process environment:\n\n- `DOKPLOY_API_KEY`: required. A global `swarm_config` secret. The API process loads global rows into `process.env` at boot and on config reload. `ctx.swarm.config_get` cannot serve this, because the SDK scrubs every response and a secret comes back as `[REDACTED:<name>]`.\n- `DOKPLOY_BASE_URL`: optional, default `https://app.dokploy.com`. It must be an `https` URL. Anything else, including an unparseable value, sends no request and logs a warning that names the variable and not its value.\n\nThe key is never written to config, state, logs, or a description.\n\nHow it decides: it calls `GET /api/deployment.allByCompose?composeId=...`, takes the deployment with the newest `createdAt`, and counts a deploy as in progress when that deployment\'s `status` is `running`. Dokploy statuses are `running`, `done`, `error`, and `cancelled`.\n\nFail open: a missing key, a non-https `DOKPLOY_BASE_URL`, a Dokploy error, a bad response, or a timeout adds no line, and the task is created as usual. The handler never throws, so an outage cannot auto-disable the extension. A task whose description already carries the note (a resume or a follow-up) is left alone.\n\nAt most one Dokploy call runs per `cacheTtlMs` window. The cache lives in `ctx.state`, so API replicas share it, and tasks created at the same moment share one in-flight check.\n'
9340
+ },
8436
9341
  "github-sender-allowlist": {
8437
9342
  manifestFile: "manifest.json",
8438
9343
  manifest: {
@@ -8860,16 +9765,18 @@ function getCatalogEntry(name) {
8860
9765
  }
8861
9766
 
8862
9767
  // src/http/extensions.ts
9768
+ init_rbac();
8863
9769
  init_types();
9770
+ init_env_flag();
8864
9771
  init_request_auth_context();
8865
9772
  init_secret_scrubber();
8866
9773
  var idParamsSchema = exports_external.object({ id: exports_external.string().min(1) });
8867
9774
 
8868
9775
  class InlineInstallDisabledError extends Error {
8869
9776
  }
8870
- function rejectInlineInstall(body) {
8871
- if (typeof body === "object" && body !== null && (("manifest" in body) || ("files" in body))) {
8872
- throw new InlineInstallDisabledError('Inline extension bundles are disabled. Install a predefined extension by name: {"template": "<name>"} (see GET /api/extensions/catalog).');
9777
+ function gateInlineInstall(body) {
9778
+ if (typeof body === "object" && body !== null && (("manifest" in body) || ("files" in body)) && !isEnvFlagEnabled("EXTENSION_ALLOW_INLINE_INSTALL", false)) {
9779
+ throw new InlineInstallDisabledError('Inline extension bundles are disabled (EXTENSION_ALLOW_INLINE_INSTALL is off). Install a predefined extension by name: {"template": "<name>"} (see GET /api/extensions/catalog).');
8873
9780
  }
8874
9781
  return body;
8875
9782
  }
@@ -8889,10 +9796,10 @@ var installRoute = route({
8889
9796
  path: "/api/extensions/install",
8890
9797
  pattern: ["api", "extensions", "install"],
8891
9798
  operationId: "extensions_install",
8892
- summary: "Install a predefined extension from the catalog",
8893
- description: "Installs the named template from `GET /api/extensions/catalog`. Inline bundles (`manifest`/`files`) are rejected with `inline_install_disabled`. Any authenticated agent can install a disabled draft owned by its agent ID. Workers can update only their own bundles; activation remains lead/operator-only.",
9799
+ summary: "Install an extension from the catalog or an inline bundle",
9800
+ description: "Installs the named `template` from `GET /api/extensions/catalog`, or an inline `manifest` plus `files`. Inline bundles are rejected with `inline_install_disabled` unless `EXTENSION_ALLOW_INLINE_INSTALL` is on, and then only lead, operator, and dashboard-user callers may send them (workers get 403). Any authenticated agent can install a catalog draft owned by its agent ID. Workers can update only their own bundles. A new extension is always disabled; activation remains lead/operator-only.",
8894
9801
  tags: ["Extensions"],
8895
- body: exports_external.preprocess(rejectInlineInstall, ExtensionInstallBodySchema),
9802
+ body: exports_external.preprocess(gateInlineInstall, ExtensionInstallBodySchema),
8896
9803
  responses: {
8897
9804
  200: {
8898
9805
  description: "Installed extension",
@@ -8903,8 +9810,10 @@ var installRoute = route({
8903
9810
  assets: ExtensionAssetsReconcileSchema.nullable()
8904
9811
  })
8905
9812
  },
8906
- 400: { description: "Inline bundle rejected or bundle validation failed" },
8907
- 403: { description: "Permission denied" },
9813
+ 400: {
9814
+ description: "Inline install disabled, invalid body (template and manifest/files are mutually exclusive), or bundle validation failed"
9815
+ },
9816
+ 403: { description: "Permission denied, including inline bundles from workers" },
8908
9817
  404: { description: "Template not found in the catalog" }
8909
9818
  },
8910
9819
  rbac: { permission: "extension.write" }
@@ -9189,15 +10098,24 @@ async function handleExtensions(req, res, pathSegments, queryParams, agentId) {
9189
10098
  }
9190
10099
  if (!parsed)
9191
10100
  return true;
9192
- const template = getCatalogEntry(parsed.body.template);
9193
- if (!template) {
9194
- json(res, {
9195
- error: "extension_template_not_found",
9196
- message: `No predefined extension named "${parsed.body.template}"`
9197
- }, 404);
9198
- return true;
10101
+ const { template: templateName, manifest: inlineManifest, files: inlineFiles } = parsed.body;
10102
+ let source;
10103
+ if (inlineManifest !== undefined && inlineFiles !== undefined) {
10104
+ if (!await requirePermission(req, res, agentId, "extension.install.inline"))
10105
+ return true;
10106
+ source = { manifest: inlineManifest, files: inlineFiles };
10107
+ } else {
10108
+ const template = getCatalogEntry(templateName ?? "");
10109
+ if (!template) {
10110
+ json(res, {
10111
+ error: "extension_template_not_found",
10112
+ message: `No predefined extension named "${templateName}"`
10113
+ }, 404);
10114
+ return true;
10115
+ }
10116
+ source = { manifest: template.manifest, files: template.files };
9199
10117
  }
9200
- const existing = await getExtensionByName(template.manifest.name);
10118
+ const existing = await getExtensionByName(source.manifest.name);
9201
10119
  const principal = await requirePermission(req, res, agentId, "extension.write", {
9202
10120
  kind: "extension",
9203
10121
  extensionId: existing?.id,
@@ -9205,10 +10123,7 @@ async function handleExtensions(req, res, pathSegments, queryParams, agentId) {
9205
10123
  });
9206
10124
  if (!principal)
9207
10125
  return true;
9208
- const validation = await validateBundle({
9209
- manifest: template.manifest,
9210
- files: template.files
9211
- });
10126
+ const validation = await validateBundle(source);
9212
10127
  if (!validation.ok) {
9213
10128
  json(res, { error: "extension_validation_failed", diagnostics: validation.diagnostics }, 400);
9214
10129
  return true;
@@ -9221,7 +10136,7 @@ async function handleExtensions(req, res, pathSegments, queryParams, agentId) {
9221
10136
  try {
9222
10137
  result = await installExtensionWithAssets({
9223
10138
  manifest: validation.manifest,
9224
- files: template.files,
10139
+ files: source.files,
9225
10140
  priority: parsed.body.priority,
9226
10141
  config: parsed.body.config,
9227
10142
  agentId: writerAgentId,
@@ -9577,6 +10492,7 @@ async function handleFavorites(req, res, pathSegments, queryParams, myAgentId) {
9577
10492
  // src/http/fs.ts
9578
10493
  init_zod();
9579
10494
  init_db();
10495
+ init_rbac();
9580
10496
  init_types();
9581
10497
 
9582
10498
  // src/utils/content-disposition.ts
@@ -10016,18 +10932,9 @@ async function canMutateTask(task, myAgentId, req) {
10016
10932
  agentId: task.agentId,
10017
10933
  creatorAgentId: task.creatorAgentId
10018
10934
  };
10019
- const auth = getRequestAuth(req);
10020
- let principal;
10021
- if (auth?.kind === "operator") {
10022
- principal = { kind: "operator" };
10023
- } else if (auth?.kind === "user") {
10024
- principal = { kind: "user", userId: auth.userId };
10025
- } else {
10026
- if (!myAgentId)
10027
- return false;
10028
- const agent = await getAgentById(myAgentId);
10029
- principal = { kind: "agent", agentId: myAgentId, isLead: agent?.isLead ?? false };
10030
- }
10935
+ const principal = await requestPrincipal(req, myAgentId);
10936
+ if (!principal)
10937
+ return false;
10031
10938
  return can({ principal, verb: "task.fs.mutate", resource, source: "http" }).allow;
10032
10939
  }
10033
10940
  async function readRawBody(req, maxBytes) {
@@ -10466,6 +11373,7 @@ var handleIntegrations = createIntegrationsHandler();
10466
11373
  // src/http/kv.ts
10467
11374
  init_zod();
10468
11375
  init_db();
11376
+ init_rbac();
10469
11377
  init_context_key();
10470
11378
  init_types();
10471
11379
  var MAX_KV_BODY_BYTES = 2 * 1024 * 1024;
@@ -12207,6 +13115,16 @@ init_env_flag();
12207
13115
  init_request_auth_context();
12208
13116
  init_task_tool_manifest();
12209
13117
  var DEFAULT_MCP_TRANSPORT_IDLE_TIMEOUT_MS = 2 * 60 * 60 * 1000;
13118
+ function respondNoMcpSession(res, sessionId) {
13119
+ const notFound2 = Boolean(sessionId);
13120
+ res.writeHead(notFound2 ? 404 : 400, { "Content-Type": "application/json" });
13121
+ res.end(JSON.stringify({
13122
+ jsonrpc: "2.0",
13123
+ error: notFound2 ? { code: -32001, message: "Session not found" } : { code: -32000, message: "Bad Request: No valid session ID provided" },
13124
+ id: null
13125
+ }));
13126
+ return true;
13127
+ }
12210
13128
  function markMcpTransportActivity(sessionActivity, sessionId, now = Date.now()) {
12211
13129
  if (sessionId) {
12212
13130
  sessionActivity[sessionId] = now;
@@ -12366,13 +13284,7 @@ async function handleMcp(req, res, transports, sessionActivity = {}, sessionAgen
12366
13284
  });
12367
13285
  await server.connect(transport);
12368
13286
  } else {
12369
- res.writeHead(400, { "Content-Type": "application/json" });
12370
- res.end(JSON.stringify({
12371
- jsonrpc: "2.0",
12372
- error: { code: -32000, message: "Invalid session" },
12373
- id: null
12374
- }));
12375
- return true;
13287
+ return respondNoMcpSession(res, sessionId);
12376
13288
  }
12377
13289
  await transport.handleRequest(req, res, body);
12378
13290
  markMcpTransportActivity(sessionActivity, transport.sessionId);
@@ -12384,9 +13296,7 @@ async function handleMcp(req, res, transports, sessionActivity = {}, sessionAgen
12384
13296
  await transports[sessionId].handleRequest(req, res);
12385
13297
  return true;
12386
13298
  }
12387
- res.writeHead(400);
12388
- res.end("Invalid session");
12389
- return true;
13299
+ return respondNoMcpSession(res, sessionId);
12390
13300
  }
12391
13301
  res.writeHead(405);
12392
13302
  res.end("Method not allowed");
@@ -13138,6 +14048,8 @@ async function handleMcpOAuth(req, res, pathSegments, queryParams) {
13138
14048
  // src/http/mcp-servers.ts
13139
14049
  init_zod();
13140
14050
  init_db();
14051
+ init_rbac_roles();
14052
+ init_rbac();
13141
14053
  init_types();
13142
14054
  init_request_auth_context();
13143
14055
  var McpServerWithOptionalSecretsSchema = McpServerWithInstallInfoSchema.extend({
@@ -13596,6 +14508,8 @@ import { randomUUID as randomUUID3 } from "node:crypto";
13596
14508
  // src/server-user.ts
13597
14509
  init_zod();
13598
14510
  init_package();
14511
+ init_rbac_roles();
14512
+ init_rbac();
13599
14513
  init_types();
13600
14514
  init_steering_enabled();
13601
14515
  var userSendTaskInputSchema = object({
@@ -13803,13 +14717,7 @@ async function handleMcpUser(req, res, transports, sessionUsers, sessionActivity
13803
14717
  const server = createUserServer(user);
13804
14718
  await server.connect(transport);
13805
14719
  } else {
13806
- res.writeHead(400, { "Content-Type": "application/json" });
13807
- res.end(JSON.stringify({
13808
- jsonrpc: "2.0",
13809
- error: { code: -32000, message: "Invalid session" },
13810
- id: null
13811
- }));
13812
- return true;
14720
+ return respondNoMcpSession(res, sessionId);
13813
14721
  }
13814
14722
  await transport.handleRequest(req, res, body);
13815
14723
  markMcpTransportActivity(sessionActivity, transport.sessionId);
@@ -13821,9 +14729,7 @@ async function handleMcpUser(req, res, transports, sessionUsers, sessionActivity
13821
14729
  await transports[sessionId].handleRequest(req, res);
13822
14730
  return true;
13823
14731
  }
13824
- res.writeHead(400);
13825
- res.end("Invalid session");
13826
- return true;
14732
+ return respondNoMcpSession(res, sessionId);
13827
14733
  }
13828
14734
  res.writeHead(405);
13829
14735
  res.end("Method not allowed");
@@ -13877,6 +14783,7 @@ function clampUsefulness(alpha, beta) {
13877
14783
  }
13878
14784
 
13879
14785
  // src/http/memory.ts
14786
+ init_key_paths();
13880
14787
  init_reranker();
13881
14788
 
13882
14789
  // src/be/memory/retrieval-store.ts
@@ -14088,6 +14995,7 @@ function truncateUtf8(query, maxBytes) {
14088
14995
  }
14089
14996
 
14090
14997
  // src/http/memory.ts
14998
+ init_rbac();
14091
14999
  init_types();
14092
15000
  init_request_auth_context();
14093
15001
  init_secret_scrubber();
@@ -14104,6 +15012,7 @@ var indexMemory = route({
14104
15012
  pattern: ["api", "memory", "index"],
14105
15013
  summary: "Ingest content into memory system (async embedding)",
14106
15014
  tags: ["Memory"],
15015
+ rbac: { permission: "memory.write.consolidated" },
14107
15016
  body: exports_external.object({
14108
15017
  agentId: exports_external.string().optional(),
14109
15018
  content: exports_external.string().min(1),
@@ -14118,7 +15027,12 @@ var indexMemory = route({
14118
15027
  }),
14119
15028
  responses: {
14120
15029
  202: { description: "Content queued for embedding", schema: IndexMemoryResponseSchema },
14121
- 400: { description: "Validation error" }
15030
+ 400: {
15031
+ description: "Validation error, or a sourcePath under /longterm that is not an allowed memory key"
15032
+ },
15033
+ 403: {
15034
+ description: "sourcePath is under a lead-only /longterm root and the caller is not the lead"
15035
+ }
14122
15036
  }
14123
15037
  });
14124
15038
  var MemorySearchResultItemSchema = exports_external.object({
@@ -14146,7 +15060,8 @@ var searchMemory = route({
14146
15060
  intent: exports_external.string().min(1).optional().describe("Why you are searching. Required for agent recall-edge tracking; omit for UI browse/search calls."),
14147
15061
  limit: exports_external.number().int().min(1).max(20).default(5),
14148
15062
  scope: exports_external.enum(["agent", "swarm", "all"]).default("all"),
14149
- source: exports_external.enum(["manual", "file_index", "session_summary", "task_completion"]).optional()
15063
+ source: exports_external.enum(["manual", "file_index", "session_summary", "task_completion"]).optional(),
15064
+ keyPrefix: exports_external.string().min(1).max(MEMORY_KEY_MAX_LENGTH).optional().describe("Only return memories whose key starts with this text (literal, case-sensitive), for example '/longterm/facts/'.")
14150
15065
  }),
14151
15066
  responses: {
14152
15067
  200: {
@@ -14443,7 +15358,8 @@ var RateEventSchema = exports_external.object({
14443
15358
  source: exports_external.enum(["llm", "explicit-self"]),
14444
15359
  reasoning: exports_external.string().max(500).optional(),
14445
15360
  taskId: exports_external.string().uuid().optional(),
14446
- referencesSource: ReferencesSourceSchema.optional()
15361
+ referencesSource: ReferencesSourceSchema.optional(),
15362
+ model: exports_external.string().trim().min(1).max(RATING_MODEL_MAX_LENGTH).optional().describe('Optional. Model that produced an `llm` rating, as "<provider>/<model-id>" (e.g. "openrouter/deepseek/deepseek-v4.1-flash"). Stored in memory_rating.model for `llm` events and ignored for `explicit-self`.')
14447
15363
  });
14448
15364
  var rateMemory = route({
14449
15365
  method: "post",
@@ -14525,6 +15441,19 @@ var getMemoryEdges = route({
14525
15441
  400: { description: "Missing memoryId or X-Agent-ID" }
14526
15442
  }
14527
15443
  });
15444
+ async function ingestPrincipal(req, agentIdHeader) {
15445
+ const auth = getRequestAuth(req);
15446
+ if (auth?.kind === "user")
15447
+ return { kind: "user", userId: auth.userId };
15448
+ const agentId = auth?.kind === "agent" ? auth.agentId : agentIdHeader;
15449
+ if (agentId) {
15450
+ const agent = await getAgentById(agentId);
15451
+ return { kind: "agent", agentId, isLead: agent?.isLead ?? false };
15452
+ }
15453
+ if (auth?.kind === "operator")
15454
+ return { kind: "operator" };
15455
+ return { kind: "agent", agentId: "", isLead: false };
15456
+ }
14528
15457
  async function handleMemory(req, res, pathSegments, callerAgentId) {
14529
15458
  const myAgentId = getRequestAuth(req)?.page?.executionAgentId ?? callerAgentId;
14530
15459
  if (indexMemory.match(req.method, pathSegments)) {
@@ -14557,17 +15486,28 @@ async function handleMemory(req, res, pathSegments, callerAgentId) {
14557
15486
  }
14558
15487
  const headerContextKey = req.headers["x-context-key"];
14559
15488
  const resolvedContextKey = contextKey ?? (Array.isArray(headerContextKey) ? headerContextKey[0] : headerContextKey) ?? undefined;
14560
- const { queued, memoryIds, edited } = await indexMemoryContent({
14561
- agentId: memoryAgentId,
14562
- content,
14563
- name,
14564
- scope,
14565
- source,
14566
- sourceTaskId,
14567
- sourcePath,
14568
- tags,
14569
- contextKey: resolvedContextKey
14570
- });
15489
+ let result;
15490
+ try {
15491
+ result = await indexMemoryContent({
15492
+ agentId: memoryAgentId,
15493
+ content,
15494
+ name,
15495
+ scope,
15496
+ source,
15497
+ sourceTaskId,
15498
+ sourcePath,
15499
+ tags,
15500
+ contextKey: resolvedContextKey,
15501
+ writer: { principal: await ingestPrincipal(req, myAgentId), source: "http" }
15502
+ });
15503
+ } catch (err) {
15504
+ if (err instanceof MemoryKeyError) {
15505
+ jsonError(res, err.message, err.reason === "forbidden" ? 403 : 400);
15506
+ return true;
15507
+ }
15508
+ throw err;
15509
+ }
15510
+ const { queued, memoryIds, edited } = result;
14571
15511
  indexMemory.respond(res, 202, {
14572
15512
  queued,
14573
15513
  memoryIds,
@@ -14583,7 +15523,7 @@ async function handleMemory(req, res, pathSegments, callerAgentId) {
14583
15523
  const parsed = await searchMemory.parse(req, res, pathSegments, new URLSearchParams);
14584
15524
  if (!parsed)
14585
15525
  return true;
14586
- const { query: originalQuery, intent, limit, scope, source } = parsed.body;
15526
+ const { query: originalQuery, intent, limit, scope, source, keyPrefix } = parsed.body;
14587
15527
  const consumptionHeader = req.headers["x-memory-consumption"];
14588
15528
  const consumptionMode = Array.isArray(consumptionHeader) ? consumptionHeader[0] : consumptionHeader;
14589
15529
  const query = consumptionMode === "prompt" ? buildRecallQuery(originalQuery) : originalQuery;
@@ -14601,11 +15541,13 @@ async function handleMemory(req, res, pathSegments, callerAgentId) {
14601
15541
  limit: candidateLimit,
14602
15542
  source,
14603
15543
  isLead: false,
14604
- queryText: query
15544
+ queryText: query,
15545
+ keyPrefix
14605
15546
  });
14606
15547
  const expanded = await expandCandidatesWithGraph(candidates, myAgentId, {
14607
15548
  scope,
14608
15549
  source,
15550
+ keyPrefix,
14609
15551
  isLead: false
14610
15552
  });
14611
15553
  const resultLimit = Math.min(limit, 20);
@@ -14921,7 +15863,8 @@ async function handleMemory(req, res, pathSegments, callerAgentId) {
14921
15863
  weight: e.weight,
14922
15864
  source: e.source,
14923
15865
  reasoning: e.reasoning,
14924
- ...e.referencesSource !== undefined ? { referencesSource: e.referencesSource } : {}
15866
+ ...e.referencesSource !== undefined ? { referencesSource: e.referencesSource } : {},
15867
+ ...e.model !== undefined ? { model: e.model } : {}
14925
15868
  }));
14926
15869
  const rateContextKeyHeader = req.headers["x-context-key"];
14927
15870
  const rateContextKey = Array.isArray(rateContextKeyHeader) ? rateContextKeyHeader[0] : rateContextKeyHeader;
@@ -15513,6 +16456,7 @@ async function handleMetrics(req, res, pathSegments, queryParams, myAgentId) {
15513
16456
  // src/http/models-catalog.ts
15514
16457
  init_zod();
15515
16458
  init_db();
16459
+ init_rbac();
15516
16460
  init_types();
15517
16461
  init_request_auth_context();
15518
16462
  var CatalogModelSchema = exports_external.object({
@@ -16409,6 +17353,14 @@ var StatusActivitySchema = exports_external.object({
16409
17353
  leads_online: exports_external.number().int().nonnegative(),
16410
17354
  recent_tasks_count: exports_external.number().int().nonnegative()
16411
17355
  });
17356
+ var StatusCombSchema = exports_external.object({
17357
+ enabled: exports_external.boolean(),
17358
+ api_url: exports_external.string().nullable(),
17359
+ live_url: exports_external.string(),
17360
+ org_id: exports_external.string().nullable(),
17361
+ drive_id: exports_external.string().nullable(),
17362
+ service_user_id: exports_external.string().nullable()
17363
+ });
16412
17364
  var StatusTelemetrySchema = exports_external.object({
16413
17365
  enabled: exports_external.boolean()
16414
17366
  });
@@ -16416,7 +17368,8 @@ var StatusAgentFsSchema = exports_external.object({
16416
17368
  configured: exports_external.boolean(),
16417
17369
  base_url: exports_external.string().nullable(),
16418
17370
  provider_id: exports_external.string(),
16419
- capabilities: exports_external.record(exports_external.string(), exports_external.unknown())
17371
+ capabilities: exports_external.record(exports_external.string(), exports_external.unknown()),
17372
+ comb: StatusCombSchema
16420
17373
  });
16421
17374
  var AutomationStatusSchema = exports_external.object({
16422
17375
  id: exports_external.string(),
@@ -16785,25 +17738,39 @@ function computeHealth(setup) {
16785
17738
  return "ok";
16786
17739
  }
16787
17740
  async function buildStatusPayload() {
17741
+ const combServiceUserId = getCombConfig().enabled ? getCombServiceUserId() : Promise.resolve(null);
16788
17742
  const automationSetup = await getAutomationSetupStates();
16789
17743
  const setup = await buildSetup(automationSetup);
16790
17744
  const automationInputs = await listEnabledAutomationPreflightInputs();
16791
17745
  const toStatus = ({ failureReason: _, ...status }) => status;
16792
17746
  const automations = automationInputs.map((automation) => toStatus(preflightAutomation(automation, automationSetup))).sort((a, b) => a.name.localeCompare(b.name) || a.kind.localeCompare(b.kind));
17747
+ const activity = await getInstanceActivity();
16793
17748
  return {
16794
17749
  identity: buildIdentity(),
16795
17750
  setup,
16796
- activity: await getInstanceActivity(),
17751
+ activity,
16797
17752
  agent_fs: {
16798
17753
  configured: !!process.env.AGENT_FS_API_URL,
16799
17754
  base_url: process.env.AGENT_FS_API_URL ?? null,
16800
- ...getAgentFsStatusProvider()
17755
+ ...getAgentFsStatusProvider(),
17756
+ comb: getCombStatus(await combServiceUserId)
16801
17757
  },
16802
17758
  automations,
16803
17759
  health: computeHealth(setup),
16804
17760
  telemetry: { enabled: isTelemetryEnabled() }
16805
17761
  };
16806
17762
  }
17763
+ function getCombStatus(serviceUserId) {
17764
+ const comb = getCombConfig();
17765
+ return {
17766
+ enabled: comb.enabled,
17767
+ api_url: comb.apiUrl,
17768
+ live_url: comb.liveUrl,
17769
+ org_id: comb.orgId,
17770
+ drive_id: comb.driveId,
17771
+ service_user_id: comb.enabled ? serviceUserId : null
17772
+ };
17773
+ }
16807
17774
  function getAgentFsStatusProvider() {
16808
17775
  try {
16809
17776
  const provider = getFileStorageProvider();
@@ -16823,7 +17790,7 @@ var getStatus = route({
16823
17790
  path: "/status",
16824
17791
  pattern: ["status"],
16825
17792
  summary: "Identity + setup readiness + live activity for the swarm dashboard",
16826
- description: "Single source of truth consumed by the UI home page. Identity comes from SWARM_* envs; setup milestones each emit `unverified | configured | verified`; automations report `running | needs_setup` from the same runtime preflight used at dispatch; activity counts agents alive in the last 5 min and tasks created in the last 24h; agent_fs reports whether AGENT_FS_API_URL is set; telemetry reports the effective ANONYMIZED_TELEMETRY opt-out state.",
17793
+ description: "Single source of truth consumed by the UI home page. Identity comes from SWARM_* envs; setup milestones each emit `unverified | configured | verified`; automations report `running | needs_setup` from the same runtime preflight used at dispatch; activity counts agents alive in the last 5 min and tasks created in the last 24h; agent_fs reports whether AGENT_FS_API_URL is set, plus the Comb settings (COMB_ENABLED, the browser-facing agent-fs URL, the shared org and drive ids, and the agent-fs user id of the swarm service account); telemetry reports the effective ANONYMIZED_TELEMETRY opt-out state.",
16827
17794
  tags: ["Status"],
16828
17795
  responses: {
16829
17796
  200: { description: "Status payload", schema: StatusResponseSchema },
@@ -16978,12 +17945,20 @@ function memoryErrorStatus(error) {
16978
17945
  const status = typeof error === "object" && error !== null && "status" in error ? Number(error.status) : 0;
16979
17946
  return Number.isInteger(status) && status >= 100 && status <= 599 ? status : undefined;
16980
17947
  }
17948
+ function notFoundNamesModel(error) {
17949
+ if (typeof error !== "object" || error === null)
17950
+ return false;
17951
+ const { code, type, error: body } = error;
17952
+ const bodyMessage = typeof body === "object" && body !== null ? body.message : undefined;
17953
+ const text = [code, type, bodyMessage].filter((part) => typeof part === "string").join(" ").toLowerCase();
17954
+ return text.includes("model") || text.includes("deployment");
17955
+ }
16981
17956
  function classifyMemoryError(error) {
16982
17957
  const status = memoryErrorStatus(error);
16983
17958
  if (status === 401 || status === 403)
16984
17959
  return "auth";
16985
17960
  if (status === 404)
16986
- return "model";
17961
+ return notFoundNamesModel(error) ? "model" : "endpoint";
16987
17962
  if (status === 408)
16988
17963
  return "timeout";
16989
17964
  const text = error instanceof Error ? `${error.name} ${error.message}`.toLowerCase() : String(error).toLowerCase();
@@ -17001,7 +17976,9 @@ function memoryErrorMessage(errorClass, status) {
17001
17976
  case "auth":
17002
17977
  return `The endpoint rejected the key${statusSuffix}.`;
17003
17978
  case "model":
17004
- return `The endpoint could not find the embedding model${statusSuffix}.`;
17979
+ return `The endpoint could not find the embedding model or deployment${statusSuffix}.`;
17980
+ case "endpoint":
17981
+ return `The endpoint path was not found${statusSuffix}. Check the base URL.`;
17005
17982
  case "timeout":
17006
17983
  return "The endpoint timed out.";
17007
17984
  case "network":
@@ -18392,7 +19369,7 @@ async function fetchAllBotChannels(client) {
18392
19369
  }
18393
19370
 
18394
19371
  // src/http/poll.ts
18395
- init_telemetry();
19372
+ init_telemetry_trigger();
18396
19373
  init_types();
18397
19374
  function buildBudgetRefusedTrigger(refusal) {
18398
19375
  const trigger = {
@@ -18439,6 +19416,7 @@ var PollTaskOfferedTriggerSchema = exports_external.object({
18439
19416
  var PollTaskAssignedTriggerSchema = exports_external.object({
18440
19417
  type: exports_external.literal("task_assigned"),
18441
19418
  taskId: exports_external.string(),
19419
+ triggerSurface: exports_external.string().optional(),
18442
19420
  task: AgentTaskSchema.extend({
18443
19421
  attachments: exports_external.array(PollTriggerAttachmentSchema)
18444
19422
  }),
@@ -18476,6 +19454,7 @@ var pollTriggers = route({
18476
19454
  path: "/api/poll",
18477
19455
  pattern: ["api", "poll"],
18478
19456
  summary: "Poll for triggers (tasks, mentions)",
19457
+ description: "While the API is draining after SIGTERM it dispatches nothing: the answer is `{ trigger: null }` " + "and carries `X-Swarm-Draining: 1`, the signal for a worker to hand off in-flight tasks.",
18479
19458
  tags: ["Poll"],
18480
19459
  auth: { apiKey: true, agentId: true },
18481
19460
  headers: runtimeInstanceHeader("poll for work").extend({
@@ -18585,6 +19564,9 @@ async function handlePoll(req, res, pathSegments, queryParams, myAgentId) {
18585
19564
  if (isMultiRuntimeEnabled() && !(runtimeInstanceId && await touchRuntimeInstance(runtimeInstanceId, agent.id))) {
18586
19565
  return { trigger: null };
18587
19566
  }
19567
+ if (isApiDraining()) {
19568
+ return { trigger: null };
19569
+ }
18588
19570
  const offeredTasks = await hasCapacity(myAgentId) ? await getOfferedTasksForAgent(myAgentId) : [];
18589
19571
  const firstOfferedTask = offeredTasks[0];
18590
19572
  if (firstOfferedTask) {
@@ -18663,17 +19645,19 @@ async function handlePoll(req, res, pathSegments, queryParams, myAgentId) {
18663
19645
  filter: ({}, ctx) => ctx.deps.length > 0,
18664
19646
  conditions: [{ timeout_ms: 300000 }]
18665
19647
  });
18666
- telemetry.taskEvent("started", {
19648
+ emitTaskTelemetry("started", {
18667
19649
  taskId: pendingTask.id,
18668
19650
  source: pendingTask.source,
18669
19651
  agentId: myAgentId
18670
19652
  });
18671
19653
  });
18672
19654
  const assignedRequestedBy = await buildTriggerRequestedBy(pendingTask);
19655
+ const assignedTriggerSurface = await resolveTriggerSurface(pendingTask.id, pendingTask.source);
18673
19656
  return {
18674
19657
  trigger: {
18675
19658
  type: "task_assigned",
18676
19659
  taskId: pendingTask.id,
19660
+ triggerSurface: assignedTriggerSurface,
18677
19661
  task: {
18678
19662
  ...pendingTask,
18679
19663
  ...await claimModelFields(pendingTask, agent),
@@ -18751,17 +19735,19 @@ async function handlePoll(req, res, pathSegments, queryParams, myAgentId) {
18751
19735
  if (claimed) {
18752
19736
  await updateAgentStatusFromCapacity(myAgentId);
18753
19737
  getDbClient().afterCommit(() => {
18754
- telemetry.taskEvent("claimed", {
19738
+ emitTaskTelemetry("claimed", {
18755
19739
  taskId: claimed.id,
18756
19740
  source: claimed.source,
18757
19741
  agentId: myAgentId
18758
19742
  });
18759
19743
  });
18760
19744
  const claimedRequestedBy = await buildTriggerRequestedBy(claimed);
19745
+ const claimedTriggerSurface = await resolveTriggerSurface(claimed.id, claimed.source);
18761
19746
  return {
18762
19747
  trigger: {
18763
19748
  type: "task_assigned",
18764
19749
  taskId: claimed.id,
19750
+ triggerSurface: claimedTriggerSurface,
18765
19751
  task: {
18766
19752
  ...claimed,
18767
19753
  ...await claimModelFields(claimed, agent),
@@ -18788,7 +19774,7 @@ async function handlePoll(req, res, pathSegments, queryParams, myAgentId) {
18788
19774
  if (result.refusalSideEffects) {
18789
19775
  await emitBudgetRefusalSideEffects(result.refusalSideEffects.context, result.refusalSideEffects.inserted);
18790
19776
  }
18791
- if (result.trigger === null && process.env.LEAD_MONITOR_CHANNELS === "true" && Date.now() - lastChannelActivityCheckAt >= CHANNEL_ACTIVITY_INTERVAL_MS) {
19777
+ if (result.trigger === null && !isApiDraining() && process.env.LEAD_MONITOR_CHANNELS === "true" && Date.now() - lastChannelActivityCheckAt >= CHANNEL_ACTIVITY_INTERVAL_MS) {
18792
19778
  const agent = await getAgentById(myAgentId);
18793
19779
  if (agent?.isLead) {
18794
19780
  lastChannelActivityCheckAt = Date.now();
@@ -19434,10 +20420,31 @@ ${templateBody}` : templateBody;
19434
20420
  return false;
19435
20421
  }
19436
20422
 
20423
+ // src/http/realtime.ts
20424
+ init_zod();
20425
+ init_rbac();
20426
+
19437
20427
  // src/realtime/browser.generated.txt
19438
20428
  var browser_generated_default = "var Tp=Object.defineProperty;var Ap=(e)=>e;function Op(e,t){this[e]=Ap.bind(null,t)}var Zp=(e,t)=>{for(var r in t)Tp(e,r,{get:t[r],enumerable:!0,configurable:!0,set:Op.bind(t,r)})};var J=()=>new Map,yr=(e)=>{let t=J();return e.forEach((r,n)=>{t.set(n,r)}),t},ue=(e,t,r)=>{let n=e.get(t);if(n===void 0)e.set(t,n=r());return n},As=(e,t)=>{let r=[];for(let[n,o]of e)r.push(t(o,n));return r},Os=(e,t)=>{for(let[r,n]of e)if(t(n,r))return!0;return!1};var _e=()=>new Set;var _r=(e)=>e[e.length-1];var Zs=(e,t)=>{for(let r=0;r<t.length;r++)e.push(t[r])},le=Array.from,wr=(e,t)=>{for(let r=0;r<e.length;r++)if(!t(e[r],r,e))return!1;return!0},br=(e,t)=>{for(let r=0;r<e.length;r++)if(t(e[r],r,e))return!0;return!1};var Ps=(e,t)=>{let r=Array(e);for(let n=0;n<e;n++)r[n]=t(n,r);return r};var Ce=Array.isArray;class Ln{constructor(){this._observers=J()}on(e,t){return ue(this._observers,e,_e).add(t),t}once(e,t){let r=(...n)=>{this.off(e,r),t(...n)};this.on(e,r)}off(e,t){let r=this._observers.get(e);if(r!==void 0){if(r.delete(t),r.size===0)this._observers.delete(e)}}emit(e,t){return le((this._observers.get(e)||J()).values()).forEach((r)=>r(...t))}destroy(){this._observers=J()}}var q=Math.floor;var Ne=Math.abs;var kr=(e,t)=>e<t?e:t,we=(e,t)=>e>t?e:t;var vr=(e)=>e!==0?e<0:1/e<0;var Bn=1,Mn=2,zr=4,$r=8;var He=32,oe=64,M=128;var Tt=31,At=63,be=127;var Cs=2147483647;var{MAX_SAFE_INTEGER:Ye,MIN_SAFE_INTEGER:Fn}=Number;var Ns=Number.isInteger||((e)=>typeof e===\"number\"&&isFinite(e)&&q(e)===e);var{fromCharCode:qn,fromCodePoint:Pp}=String,cg=qn(65535),Cp=(e)=>e.toLowerCase(),Np=/^\\s*/g,Up=(e)=>e.replace(Np,\"\"),Dp=/([A-Z])/g,Gn=(e,t)=>Up(e.replace(Dp,(r)=>`${t}${Cp(r)}`));var Rp=(e)=>{let t=unescape(encodeURIComponent(e)),r=t.length,n=new Uint8Array(r);for(let o=0;o<r;o++)n[o]=t.codePointAt(o);return n},Qe=typeof TextEncoder<\"u\"?new TextEncoder:null,jp=(e)=>Qe.encode(e),Us=Qe?jp:Rp;var Xe=typeof TextDecoder>\"u\"?null:new TextDecoder(\"utf-8\",{fatal:!0,ignoreBOM:!0});if(Xe&&Xe.decode(new Uint8Array).length===1)Xe=null;var Ds=(e,t)=>Ps(t,()=>e).join(\"\");class tt{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}}var Ot=()=>new tt;var Lp=(e)=>{let t=e.cpos;for(let r=0;r<e.bufs.length;r++)t+=e.bufs[r].length;return t};var se=(e)=>{let t=new Uint8Array(Lp(e)),r=0;for(let n=0;n<e.bufs.length;n++){let o=e.bufs[n];t.set(o,r),r+=o.length}return t.set(new Uint8Array(e.cbuf.buffer,0,e.cpos),r),t},Bp=(e,t)=>{let r=e.cbuf.length;if(r-e.cpos<t)e.bufs.push(new Uint8Array(e.cbuf.buffer,0,e.cpos)),e.cbuf=new Uint8Array(we(r,t)*2),e.cpos=0},N=(e,t)=>{let r=e.cbuf.length;if(e.cpos===r)e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(r*2),e.cpos=0;e.cbuf[e.cpos++]=t};var Er=N;var y=(e,t)=>{while(t>be)N(e,M|be&t),t=q(t/128);N(e,be&t)},Ir=(e,t)=>{let r=vr(t);if(r)t=-t;N(e,(t>At?M:0)|(r?oe:0)|At&t),t=q(t/64);while(t>0)N(e,(t>be?M:0)|be&t),t=q(t/128)},Wn=new Uint8Array(30000),Mp=Wn.length/3,Vp=(e,t)=>{if(t.length<Mp){let r=Qe.encodeInto(t,Wn).written||0;y(e,r);for(let n=0;n<r;n++)N(e,Wn[n])}else K(e,Us(t))},Fp=(e,t)=>{let r=unescape(encodeURIComponent(t)),n=r.length;y(e,n);for(let o=0;o<n;o++)N(e,r.codePointAt(o))},Ue=Qe&&Qe.encodeInto?Vp:Fp;var Zt=(e,t)=>{let r=e.cbuf.length,n=e.cpos,o=kr(r-n,t.length),s=t.length-o;if(e.cbuf.set(t.subarray(0,o),n),e.cpos+=o,s>0)e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(we(r*2,s)),e.cbuf.set(t.subarray(o)),e.cpos=s},K=(e,t)=>{y(e,t.byteLength),Zt(e,t)},Kn=(e,t)=>{Bp(e,t);let r=new DataView(e.cbuf.buffer,e.cpos,t);return e.cpos+=t,r},Jp=(e,t)=>Kn(e,4).setFloat32(0,t,!1),qp=(e,t)=>Kn(e,8).setFloat64(0,t,!1),Gp=(e,t)=>Kn(e,8).setBigInt64(0,t,!1);var Rs=new DataView(new ArrayBuffer(4)),Wp=(e)=>(Rs.setFloat32(0,e),Rs.getFloat32(0)===e),et=(e,t)=>{switch(typeof t){case\"string\":N(e,119),Ue(e,t);break;case\"number\":if(Ns(t)&&Ne(t)<=Cs)N(e,125),Ir(e,t);else if(Wp(t))N(e,124),Jp(e,t);else N(e,123),qp(e,t);break;case\"bigint\":N(e,122),Gp(e,t);break;case\"object\":if(t===null)N(e,126);else if(Ce(t)){N(e,117),y(e,t.length);for(let r=0;r<t.length;r++)et(e,t[r])}else if(t instanceof Uint8Array)N(e,116),K(e,t);else{N(e,118);let r=Object.keys(t);y(e,r.length);for(let n=0;n<r.length;n++){let o=r[n];Ue(e,o),et(e,t[o])}}break;case\"boolean\":N(e,t?120:121);break;default:N(e,127)}};class Tr extends tt{constructor(e){super();this.w=e,this.s=null,this.count=0}write(e){if(this.s===e)this.count++;else{if(this.count>0)y(this,this.count-1);this.count=1,this.w(this,e),this.s=e}}}var js=(e)=>{if(e.count>0){if(Ir(e.encoder,e.count===1?e.s:-e.s),e.count>1)y(e.encoder,e.count-2)}};class rt{constructor(){this.encoder=new tt,this.s=0,this.count=0}write(e){if(this.s===e)this.count++;else js(this),this.count=1,this.s=e}toUint8Array(){return js(this),se(this.encoder)}}var Ls=(e)=>{if(e.count>0){let t=e.diff*2+(e.count===1?0:1);if(Ir(e.encoder,t),e.count>1)y(e.encoder,e.count-2)}};class Pt{constructor(){this.encoder=new tt,this.s=0,this.count=0,this.diff=0}write(e){if(this.diff===e-this.s)this.s=e,this.count++;else Ls(this),this.count=1,this.diff=e-this.s,this.s=e}toUint8Array(){return Ls(this),se(this.encoder)}}class Hn{constructor(){this.sarr=[],this.s=\"\",this.lensE=new rt}write(e){if(this.s+=e,this.s.length>19)this.sarr.push(this.s),this.s=\"\";this.lensE.write(e.length)}toUint8Array(){let e=new tt;return this.sarr.push(this.s),this.s=\"\",Ue(e,this.sarr.join(\"\")),Zt(e,this.lensE.toUint8Array()),se(e)}}var X=(e)=>Error(e),Q=()=>{throw X(\"Method unimplemented\")},H=()=>{throw X(\"Unexpected case\")};var Bs=X(\"Unexpected end of array\"),Ms=X(\"Integer out of Range\");class Ct{constructor(e){this.arr=e,this.pos=0}}var je=(e)=>new Ct(e),Vs=(e)=>e.pos!==e.arr.length;var Hp=(e,t)=>{let r=new Uint8Array(e.arr.buffer,e.pos+e.arr.byteOffset,t);return e.pos+=t,r},Y=(e)=>Hp(e,x(e));var De=(e)=>e.arr[e.pos++];var x=(e)=>{let t=0,r=1,n=e.arr.length;while(e.pos<n){let o=e.arr[e.pos++];if(t=t+(o&be)*r,r*=128,o<M)return t;if(t>Ye)throw Ms}throw Bs},Ar=(e)=>{let t=e.arr[e.pos++],r=t&At,n=64,o=(t&oe)>0?-1:1;if((t&M)===0)return o*r;let s=e.arr.length;while(e.pos<s){if(t=e.arr[e.pos++],r=r+(t&be)*n,n*=128,t<M)return o*r;if(r>Ye)throw Ms}throw Bs};var Yp=(e)=>{let t=x(e);if(t===0)return\"\";else{let r=String.fromCodePoint(De(e));if(--t<100)while(t--)r+=String.fromCodePoint(De(e));else while(t>0){let n=t<1e4?t:1e4,o=e.arr.subarray(e.pos,e.pos+n);e.pos+=n,r+=String.fromCodePoint.apply(null,o),t-=n}return decodeURIComponent(escape(r))}},Xp=(e)=>Xe.decode(Y(e)),Re=Xe?Xp:Yp;var Xn=(e,t)=>{let r=new DataView(e.arr.buffer,e.arr.byteOffset+e.pos,t);return e.pos+=t,r},Qp=(e)=>Xn(e,4).getFloat32(0,!1),eh=(e)=>Xn(e,8).getFloat64(0,!1),th=(e)=>Xn(e,8).getBigInt64(0,!1);var rh=[(e)=>{return},(e)=>null,Ar,Qp,eh,th,(e)=>!1,(e)=>!0,Re,(e)=>{let t=x(e),r={};for(let n=0;n<t;n++){let o=Re(e);r[o]=nt(e)}return r},(e)=>{let t=x(e),r=[];for(let n=0;n<t;n++)r.push(nt(e));return r},Y],nt=(e)=>rh[127-De(e)](e);class Or extends Ct{constructor(e,t){super(e);this.reader=t,this.s=null,this.count=0}read(){if(this.count===0)if(this.s=this.reader(this),Vs(this))this.count=x(this)+1;else this.count=-1;return this.count--,this.s}}class ot extends Ct{constructor(e){super(e);this.s=0,this.count=0}read(){if(this.count===0){this.s=Ar(this);let e=vr(this.s);if(this.count=1,e)this.s=-this.s,this.count=x(this)+2}return this.count--,this.s}}class Nt extends Ct{constructor(e){super(e);this.s=0,this.count=0,this.diff=0}read(){if(this.count===0){let e=Ar(this),t=e&1;if(this.diff=q(e/2),this.count=1,t)this.count=x(this)+2}return this.s+=this.diff,this.count--,this.s}}class Qn{constructor(e){this.decoder=new ot(e),this.str=Re(this.decoder),this.spos=0}read(){let e=this.spos+this.decoder.read(),t=this.str.slice(this.spos,e);return this.spos=e,t}}var lg=crypto.subtle,Fs=crypto.getRandomValues.bind(crypto);var eo=()=>Fs(new Uint32Array(1))[0];var oh=[1e7]+-1000+-4000+-8000+-100000000000,Js=()=>oh.replace(/[018]/g,(e)=>(e^eo()&15>>e/4).toString(16));var qs=Date.now;var to=(e)=>new Promise(e);var dg=Promise.all.bind(Promise);var ro=(e)=>e===void 0?null:e;class Gs{constructor(){this.map=new Map}setItem(e,t){this.map.set(e,t)}getItem(e){return this.map.get(e)}}var Ws=new Gs,uh=!0;try{if(typeof localStorage<\"u\"&&localStorage)Ws=localStorage,uh=!1}catch(e){}var Ks=Ws;var Le=Symbol(\"Equality\"),Zr=(e,t)=>e===t||!!e?.[Le]?.(t)||!1;var Hs=(e)=>typeof e===\"object\",Ys=Object.assign,ph=Object.keys;var Xs=(e,t)=>{for(let r in e)t(e[r],r)};var Ut=(e)=>ph(e).length;var Qs=(e)=>{for(let t in e)return!1;return!0},st=(e,t)=>{for(let r in e)if(!t(e[r],r))return!1;return!0},Dt=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),oo=(e,t)=>e===t||Ut(e)===Ut(t)&&st(e,(r,n)=>(r!==void 0||Dt(t,n))&&Zr(t[n],r)),hh=Object.freeze,so=(e)=>{for(let t in e){let r=e[t];if(typeof r===\"object\"||typeof r===\"function\")so(e[t])}return hh(e)};var jt=(e,t,r=0)=>{try{for(;r<e.length;r++)e[r](...t)}finally{if(r<e.length)jt(e,t,r+1)}};var ei=(e)=>e;var Rt=(e,t)=>{if(e===t)return!0;if(e==null||t==null||e.constructor!==t.constructor&&(e.constructor||Object)!==(t.constructor||Object))return!1;if(e[Le]!=null)return e[Le](t);switch(e.constructor){case ArrayBuffer:e=new Uint8Array(e),t=new Uint8Array(t);case Uint8Array:{if(e.byteLength!==t.byteLength)return!1;for(let r=0;r<e.length;r++)if(e[r]!==t[r])return!1;break}case Set:{if(e.size!==t.size)return!1;for(let r of e)if(!t.has(r))return!1;break}case Map:{if(e.size!==t.size)return!1;for(let r of e.keys())if(!t.has(r)||!Rt(e.get(r),t.get(r)))return!1;break}case void 0:case Object:if(Ut(e)!==Ut(t))return!1;for(let r in e)if(!Dt(e,r)||!Rt(e[r],t[r]))return!1;break;case Array:if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!Rt(e[r],t[r]))return!1;break;default:return!1}return!0},ti=(e,t)=>t.includes(e);var Lt=typeof process<\"u\"&&process.release&&/node|io\\.js/.test(process.release.name)&&Object.prototype.toString.call(typeof process<\"u\"?process:0)===\"[object process]\";var fg=typeof navigator<\"u\"?/Mac/.test(navigator.platform):!1,pe,dh=[],fh=()=>{if(pe===void 0)if(Lt){pe=J();let e=process.argv,t=null;for(let r=0;r<e.length;r++){let n=e[r];if(n[0]===\"-\"){if(t!==null)pe.set(t,\"\");t=n}else if(t!==null)pe.set(t,n),t=null;else dh.push(n)}if(t!==null)pe.set(t,\"\")}else if(typeof location===\"object\")pe=J(),(location.search||\"?\").slice(1).split(\"&\").forEach((e)=>{if(e.length!==0){let[t,r]=e.split(\"=\");pe.set(`--${Gn(t,\"-\")}`,r),pe.set(`-${Gn(t,\"-\")}`,r)}});else pe=J();return pe},ao=(e)=>fh().has(e);var Bt=(e)=>Lt?ro(process.env[e.toUpperCase().replaceAll(\"-\",\"_\")]):ro(Ks.getItem(e));var ri=(e)=>ao(\"--\"+e)||Bt(e)!==null,ni=ri(\"production\"),mh=Lt&&ti(process.env.FORCE_COLOR,[\"true\",\"1\",\"2\"]),oi=mh||!ao(\"--no-colors\")&&!ri(\"no-color\")&&(!Lt||process.stdout.isTTY)&&(!Lt||ao(\"--color\")||Bt(\"COLORTERM\")!==null||(Bt(\"TERM\")||\"\").includes(\"color\"));var gh=(e)=>new Uint8Array(e);var si=(e)=>{let t=gh(e.byteLength);return t.set(e),t};class ii{constructor(e,t){this.left=e,this.right=t}}var he=(e,t)=>new ii(e,t);var lo=(e)=>e.next()>=0.5,Pr=(e,t,r)=>q(e.next()*(r+1-t)+t);var po=(e,t,r)=>q(e.next()*(r+1-t)+t);var ho=(e,t,r)=>po(e,t,r);var _h=(e)=>qn(ho(e,97,122)),ci=(e,t=0,r=20)=>{let n=ho(e,t,r),o=\"\";for(let s=0;s<n;s++)o+=_h(e);return o};var Cr=(e,t)=>t[ho(e,0,t.length-1)];var bh=Symbol(\"0schema\");class ui{constructor(){this._rerrs=[]}extend(e,t,r,n=null){this._rerrs.push({path:e,expected:t,has:r,message:n})}toString(){let e=[];for(let t=this._rerrs.length-1;t>0;t--){let r=this._rerrs[t];e.push(Ds(\" \",(this._rerrs.length-t)*2)+`${r.path!=null?`[${r.path}] `:\"\"}${r.has} doesn't match ${r.expected}. ${r.message}`)}return e.join(`\n`)}}var fo=(e,t)=>{if(e===t)return!0;if(e==null||t==null||e.constructor!==t.constructor)return!1;if(e[Le])return Zr(e,t);if(Ce(e))return wr(e,(r)=>br(t,(n)=>fo(r,n)));else if(Hs(e))return st(e,(r,n)=>fo(r,t[n]));return!1};class V{static _dilutes=!1;extends(e){let[t,r]=[this.shape,e.shape];if(this.constructor._dilutes)[r,t]=[t,r];return fo(t,r)}equals(e){return this.constructor===e.constructor&&Rt(this.shape,e.shape)}[bh](){return!0}[Le](e){return this.equals(e)}validate(e){return this.check(e)}check(e,t){Q()}get nullable(){return ut(this,Vr)}get optional(){return new mo(this)}cast(e){return ai(e,this),e}expect(e){return ai(e,this),e}}class Dr extends V{constructor(e,t){super();this.shape=e,this._c=t}check(e,t=void 0){let r=e?.constructor===this.shape&&(this._c==null||this._c(e));return!r&&t?.extend(null,this.shape.name,e?.constructor.name,e?.constructor!==this.shape?\"Constructor match failed\":\"Check failed\"),r}}var O=(e,t=null)=>new Dr(e,t),gg=O(Dr);class Rr extends V{constructor(e){super();this.shape=e}check(e,t){let r=this.shape(e);return!r&&t?.extend(null,\"custom prop\",e?.constructor.name,\"failed to check custom prop\"),r}}var Z=(e)=>new Rr(e),xg=O(Rr);class Vt extends V{constructor(e){super();this.shape=e}check(e,t){let r=this.shape.some((n)=>n===e);return!r&&t?.extend(null,this.shape.join(\" | \"),e.toString()),r}}var jr=(...e)=>new Vt(e),li=O(Vt),kh=RegExp.escape||((e)=>e.replace(/[().|&,$^[\\]]/g,(t)=>\"\\\\\"+t)),pi=(e)=>{if(at.check(e))return[kh(e)];if(li.check(e))return e.shape.map((t)=>t+\"\");if(_i.check(e))return[\"[+-]?\\\\d+.?\\\\d*\"];if(wi.check(e))return[\".*\"];if(Nr.check(e))return e.shape.map(pi).flat(1);H()};class hi extends V{constructor(e){super();this.shape=e,this._r=new RegExp(\"^\"+e.map(pi).map((t)=>`(${t.join(\"|\")})`).join(\"\")+\"$\")}check(e,t){let r=this._r.exec(e)!=null;return!r&&t?.extend(null,this._r.toString(),e.toString(),\"String doesn't match string template.\"),r}}var yg=O(hi),vh=Symbol(\"optional\");class mo extends V{constructor(e){super();this.shape=e}check(e,t){let r=e===void 0||this.shape.check(e);return!r&&t?.extend(null,\"undefined (optional)\",\"()\"),r}get[vh](){return!0}}var zh=O(mo);class go extends V{check(e,t){return t?.extend(null,\"never\",typeof e),!1}}var _g=new go,wg=O(go);class Lr extends V{constructor(e,t=!1){super();this.shape=e,this._isPartial=t}static _dilutes=!0;get partial(){return new Lr(this.shape,!0)}check(e,t){if(e==null)return t?.extend(null,\"object\",\"null\"),!1;return st(this.shape,(r,n)=>{let o=this._isPartial&&!Dt(e,n)||r.check(e[n],t);return!o&&t?.extend(n.toString(),r.toString(),typeof e[n],\"Object property does not match\"),o})}}var $h=(e)=>new Lr(e),Sh=O(Lr),Eh=Z((e)=>e!=null&&(e.constructor===Object||e.constructor==null));class xo extends V{constructor(e,t){super();this.shape={keys:e,values:t}}check(e,t){return e!=null&&st(e,(r,n)=>{let o=this.shape.keys.check(n,t);return!o&&t?.extend(n+\"\",\"Record\",typeof e,o?\"Key doesn't match schema\":\"Value doesn't match value\"),o&&this.shape.values.check(r,t)})}}var di=(e,t)=>new xo(e,t),Ih=O(xo);class yo extends V{constructor(e){super();this.shape=e}check(e,t){return e!=null&&st(this.shape,(r,n)=>{let o=r.check(e[n],t);return!o&&t?.extend(n.toString(),\"Tuple\",typeof r),o})}}var Th=(...e)=>new yo(e),bg=O(yo);class _o extends V{constructor(e){super();this.shape=e.length===1?e[0]:new Br(e)}check(e,t){let r=Ce(e)&&wr(e,(n)=>this.shape.check(n));return!r&&t?.extend(null,\"Array\",\"\"),r}}var fi=(...e)=>new _o(e),Ah=O(_o),Oh=Z((e)=>Ce(e));class wo extends V{constructor(e,t){super();this.shape=e,this._c=t}check(e,t){let r=e instanceof this.shape&&(this._c==null||this._c(e));return!r&&t?.extend(null,this.shape.name,e?.constructor.name),r}}var Zh=(e,t=null)=>new wo(e,t),kg=O(wo),Ph=Zh(V);class mi extends V{constructor(e){super();this.len=e.length-1,this.args=Th(...e.slice(-1)),this.res=e[this.len]}check(e,t){let r=e.constructor===Function&&e.length<=this.len;return!r&&t?.extend(null,\"function\",typeof e),r}}var Ch=O(mi),Nh=Z((e)=>typeof e===\"function\");class gi extends V{constructor(e){super();this.shape=e}check(e,t){let r=wr(this.shape,(n)=>n.check(e,t));return!r&&t?.extend(null,\"Intersectinon\",typeof e),r}}var vg=O(gi,(e)=>e.shape.length>0);class Br extends V{static _dilutes=!0;constructor(e){super();this.shape=e}check(e,t){let r=br(this.shape,(n)=>n.check(e,t));return t?.extend(null,\"Union\",typeof e),r}}var ut=(...e)=>e.findIndex((t)=>Nr.check(t))>=0?ut(...e.map((t)=>Mt(t)).map((t)=>Nr.check(t)?t.shape:[t]).flat(1)):e.length===1?e[0]:new Br(e),Nr=O(Br),xi=()=>!0,Ur=Z(xi),Uh=O(Rr,(e)=>e.shape===xi),bo=Z((e)=>typeof e===\"bigint\"),Dh=Z((e)=>e===bo),yi=Z((e)=>typeof e===\"symbol\"),zg=Z((e)=>e===yi),ct=Z((e)=>typeof e===\"number\"),_i=Z((e)=>e===ct),at=Z((e)=>typeof e===\"string\"),wi=Z((e)=>e===at),Mr=Z((e)=>typeof e===\"boolean\"),Rh=Z((e)=>e===Mr),bi=jr(void 0),$g=O(Vt,(e)=>e.shape.length===1&&e.shape[0]===void 0),Sg=jr(void 0);var Vr=jr(null),jh=O(Vt,(e)=>e.shape.length===1&&e.shape[0]===null),Eg=O(Uint8Array),Ig=O(Dr,(e)=>e.shape===Uint8Array),Lh=ut(ct,at,Vr,bi,bo,Mr,yi),Tg=(()=>{let e=fi(Ur),t=di(at,Ur),r=ut(ct,at,Vr,Mr,e,t);return e.shape=r,t.shape.values=r,r})(),Mt=(e)=>{if(Ph.check(e))return e;else if(Eh.check(e)){let t={};for(let r in e)t[r]=Mt(e[r]);return $h(t)}else if(Oh.check(e))return ut(...e.map(Mt));else if(Lh.check(e))return jr(e);else if(Nh.check(e))return O(e);H()},ai=ni?()=>{}:(e,t)=>{let r=new ui;if(!t.check(e,r))throw X(`Expected value to be of type ${t.constructor.name}.\n${r.toString()}`)};class ki{constructor(e){this.patterns=[],this.$state=e}if(e,t){return this.patterns.push({if:Mt(e),h:t}),this}else(e){return this.if(Ur,e)}done(){return(e,t)=>{for(let r=0;r<this.patterns.length;r++){let n=this.patterns[r];if(n.if.check(e))return n.h(e,t)}throw X(\"Unhandled pattern\")}}}var Bh=(e)=>new ki(e),vi=Bh(Ur).if(_i,(e,t)=>Pr(t,Fn,Ye)).if(wi,(e,t)=>ci(t)).if(Rh,(e,t)=>lo(t)).if(Dh,(e,t)=>BigInt(Pr(t,Fn,Ye))).if(Nr,(e,t)=>it(t,Cr(t,e.shape))).if(Sh,(e,t)=>{let r={};for(let n in e.shape){let o=e.shape[n];if(zh.check(o)){if(lo(t))continue;o=o.shape}r[n]=vi(o,t)}return r}).if(Ah,(e,t)=>{let r=[],n=po(t,0,42);for(let o=0;o<n;o++)r.push(it(t,e.shape));return r}).if(li,(e,t)=>Cr(t,e.shape)).if(jh,(e,t)=>null).if(Ch,(e,t)=>{let r=it(t,e.res);return()=>r}).if(Uh,(e,t)=>it(t,Cr(t,[ct,at,Vr,bi,bo,Mr,fi(ct),di(ut(\"a\",\"b\",\"c\"),ct)]))).if(Ih,(e,t)=>{let r={},n=Pr(t,0,3);for(let o=0;o<n;o++){let s=it(t,e.shape.keys),i=it(t,e.shape.values);r[s]=i}return r}).done(),it=(e,t)=>vi(Mt(t),e);var Be=typeof document<\"u\"?document:{};var Ag=Z((e)=>e.nodeType===qh);var Og=typeof DOMParser<\"u\"?new DOMParser:null;var Zg=Z((e)=>e.nodeType===Vh);var Pg=Z((e)=>e.nodeType===Fh);var zi=(e)=>As(e,(t,r)=>`${r}:${t};`).join(\"\");var{ELEMENT_NODE:Vh,TEXT_NODE:Fh,CDATA_SECTION_NODE:Cg,COMMENT_NODE:Ng,DOCUMENT_NODE:Jh,DOCUMENT_TYPE_NODE:Ug,DOCUMENT_FRAGMENT_NODE:qh}=Be,Dg=Z((e)=>e.nodeType===Jh);var de=Symbol;var Ft=de(),Jt=de(),ko=de(),vo=de(),zo=de(),qt=de(),$o=de(),lt=de(),So=de(),$i=(e)=>{if(e.length===1&&e[0]?.constructor===Function)e=e[0]();let t=[],r=[],n=0;for(;n<e.length;n++){let o=e[n];if(o===void 0)break;else if(o.constructor===String||o.constructor===Number)t.push(o);else if(o.constructor===Object)break}if(n>0)r.push(t.join(\"\"));for(;n<e.length;n++){let o=e[n];if(!(o instanceof Symbol))r.push(o)}return r};var Rg=qs();var Hh={[Ft]:he(\"font-weight\",\"bold\"),[Jt]:he(\"font-weight\",\"normal\"),[ko]:he(\"color\",\"blue\"),[zo]:he(\"color\",\"green\"),[vo]:he(\"color\",\"grey\"),[qt]:he(\"color\",\"red\"),[$o]:he(\"color\",\"purple\"),[lt]:he(\"color\",\"orange\"),[So]:he(\"color\",\"black\")},Yh=(e)=>{if(e.length===1&&e[0]?.constructor===Function)e=e[0]();let t=[],r=[],n=J(),o=[],s=0;for(;s<e.length;s++){let i=e[s],c=Hh[i];if(c!==void 0)n.set(c.left,c.right);else{if(i===void 0)break;if(i.constructor===String||i.constructor===Number){let a=zi(n);if(s>0||a.length>0)t.push(\"%c\"+i),r.push(a);else t.push(i)}else break}}if(s>0)o=r,o.unshift(t.join(\"\"));for(;s<e.length;s++){let i=e[s];if(!(i instanceof Symbol))o.push(i)}return o},Si=oi?Yh:$i,Ei=(...e)=>{console.log(...Si(e)),Ti.forEach((t)=>t.print(e))},Ii=(...e)=>{console.warn(...Si(e)),e.unshift(lt),Ti.forEach((t)=>t.print(e))};var Ti=_e();var Ai=(e)=>({[Symbol.iterator](){return this},next:e}),Oi=(e,t)=>Ai(()=>{let r;do r=e.next();while(!r.done&&!t(r.value));return r}),Fr=(e,t)=>Ai(()=>{let{done:r,value:n}=e.next();return{done:r,value:r?void 0:t(n)}});class Ht{constructor(e,t){this.clock=e,this.len=t}}class dt{constructor(){this.clients=new Map}}var Vi=(e,t,r)=>t.clients.forEach((n,o)=>{let s=e.doc.store.clients.get(o);if(s!=null){let i=s[s.length-1],c=i.id.clock+i.length;for(let a=0,l=n[a];a<n.length&&l.clock<c;l=n[++a])rc(e,s,l.clock,l.len,r)}}),ed=(e,t)=>{let r=0,n=e.length-1;while(r<=n){let o=q((r+n)/2),s=e[o],i=s.clock;if(i<=t){if(t<i+s.len)return o;r=o+1}else n=o-1}return null},Fi=(e,t)=>{let r=e.clients.get(t.client);return r!==void 0&&ed(r,t.clock)!==null},Oo=(e)=>{e.clients.forEach((t)=>{t.sort((o,s)=>o.clock-s.clock);let r,n;for(r=1,n=1;r<t.length;r++){let o=t[n-1],s=t[r];if(o.clock+o.len>=s.clock)t[n-1]=new Ht(o.clock,we(o.len,s.clock+s.len-o.clock));else{if(n<r)t[n]=s;n++}}t.length=n})},td=(e)=>{let t=new dt;for(let r=0;r<e.length;r++)e[r].clients.forEach((n,o)=>{if(!t.clients.has(o)){let s=n.slice();for(let i=r+1;i<e.length;i++)Zs(s,e[i].clients.get(o)||[]);t.clients.set(o,s)}});return Oo(t),t},Hr=(e,t,r,n)=>{ue(e.clients,t,()=>[]).push(new Ht(r,n))},Ji=()=>new dt,rd=(e)=>{let t=Ji();return e.clients.forEach((r,n)=>{let o=[];for(let s=0;s<r.length;s++){let i=r[s];if(i.deleted){let c=i.id.clock,a=i.length;if(s+1<r.length)for(let l=r[s+1];s+1<r.length&&l.deleted;l=r[++s+1])a+=l.length;o.push(new Ht(c,a))}}if(o.length>0)t.clients.set(n,o)}),t},ft=(e,t)=>{y(e.restEncoder,t.clients.size),le(t.clients.entries()).sort((r,n)=>n[0]-r[0]).forEach(([r,n])=>{e.resetDsCurVal(),y(e.restEncoder,r);let o=n.length;y(e.restEncoder,o);for(let s=0;s<o;s++){let i=n[s];e.writeDsClock(i.clock),e.writeDsLen(i.len)}})},Zo=(e)=>{let t=new dt,r=x(e.restDecoder);for(let n=0;n<r;n++){e.resetDsCurVal();let o=x(e.restDecoder),s=x(e.restDecoder);if(s>0){let i=ue(t.clients,o,()=>[]);for(let c=0;c<s;c++)i.push(new Ht(e.readDsClock(),e.readDsLen()))}}return t},Zi=(e,t,r)=>{let n=new dt,o=x(e.restDecoder);for(let s=0;s<o;s++){e.resetDsCurVal();let i=x(e.restDecoder),c=x(e.restDecoder),a=r.clients.get(i)||[],l=U(r,i);for(let u=0;u<c;u++){let h=e.readDsClock(),p=h+e.readDsLen();if(h<l){if(l<p)Hr(n,i,l,p-l);let f=fe(a,h),m=a[f];if(!m.deleted&&m.id.clock<h)a.splice(f+1,0,on(t,m,h-m.id.clock)),f++;while(f<a.length)if(m=a[f++],m.id.clock<p){if(!m.deleted){if(p<m.id.clock+m.length)a.splice(f,0,on(t,m,p-m.id.clock));m.delete(t)}}else break}else Hr(n,i,h,p-h)}}if(n.clients.size>0){let s=new Te;return y(s.restEncoder,0),ft(s,n),s.toUint8Array()}return null};var qi=eo;class ge extends Ln{constructor({guid:e=Js(),collectionid:t=null,gc:r=!0,gcFilter:n=()=>!0,meta:o=null,autoLoad:s=!1,shouldLoad:i=!0}={}){super();this.gc=r,this.gcFilter=n,this.clientID=qi(),this.guid=e,this.collectionid=t,this.share=new Map,this.store=new Ro,this._transaction=null,this._transactionCleanups=[],this.subdocs=new Set,this._item=null,this.shouldLoad=i,this.autoLoad=s,this.meta=o,this.isLoaded=!1,this.isSynced=!1,this.isDestroyed=!1,this.whenLoaded=to((a)=>{this.on(\"load\",()=>{this.isLoaded=!0,a(this)})});let c=()=>to((a)=>{let l=(u)=>{if(u===void 0||u===!0)this.off(\"sync\",l),a()};this.on(\"sync\",l)});this.on(\"sync\",(a)=>{if(a===!1&&this.isSynced)this.whenSynced=c();if(this.isSynced=a===void 0||a===!0,this.isSynced&&!this.isLoaded)this.emit(\"load\",[this])}),this.whenSynced=c()}load(){let e=this._item;if(e!==null&&!this.shouldLoad)v(e.parent.doc,(t)=>{t.subdocsLoaded.add(this)},null,!0);this.shouldLoad=!0}getSubdocs(){return this.subdocs}getSubdocGuids(){return new Set(le(this.subdocs).map((e)=>e.guid))}transact(e,t=null){return v(this,e,t)}get(e,t=D){let r=ue(this.share,e,()=>{let o=new t;return o._integrate(this,null),o}),n=r.constructor;if(t!==D&&n!==t)if(n===D){let o=new t;o._map=r._map,r._map.forEach((s)=>{for(;s!==null;s=s.left)s.parent=o}),o._start=r._start;for(let s=o._start;s!==null;s=s.right)s.parent=o;return o._length=r._length,this.share.set(e,o),o._integrate(this,null),o}else throw Error(`Type with the name ${e} has already been defined with a different constructor`);return r}getArray(e=\"\"){return this.get(e,re)}getText(e=\"\"){return this.get(e,ie)}getMap(e=\"\"){return this.get(e,G)}getXmlElement(e=\"\"){return this.get(e,ht)}getXmlFragment(e=\"\"){return this.get(e,Fe)}toJSON(){let e={};return this.share.forEach((t,r)=>{e[r]=t.toJSON()}),e}destroy(){this.isDestroyed=!0,le(this.subdocs).forEach((t)=>t.destroy());let e=this._item;if(e!==null){this._item=null;let t=e.content;t.doc=new ge({guid:this.guid,...t.opts,shouldLoad:!1}),t.doc._item=e,v(e.parent.doc,(r)=>{let n=t.doc;if(!e.deleted)r.subdocsAdded.add(n);r.subdocsRemoved.add(this)},null,!0)}this.emit(\"destroyed\",[!0]),this.emit(\"destroy\",[this]),super.destroy()}}class Po{constructor(e){this.restDecoder=e}resetDsCurVal(){}readDsClock(){return x(this.restDecoder)}readDsLen(){return x(this.restDecoder)}}class Co extends Po{readLeftID(){return _(x(this.restDecoder),x(this.restDecoder))}readRightID(){return _(x(this.restDecoder),x(this.restDecoder))}readClient(){return x(this.restDecoder)}readInfo(){return De(this.restDecoder)}readString(){return Re(this.restDecoder)}readParentInfo(){return x(this.restDecoder)===1}readTypeRef(){return x(this.restDecoder)}readLen(){return x(this.restDecoder)}readAny(){return nt(this.restDecoder)}readBuf(){return si(Y(this.restDecoder))}readJSON(){return JSON.parse(Re(this.restDecoder))}readKey(){return Re(this.restDecoder)}}class Gi{constructor(e){this.dsCurrVal=0,this.restDecoder=e}resetDsCurVal(){this.dsCurrVal=0}readDsClock(){return this.dsCurrVal+=x(this.restDecoder),this.dsCurrVal}readDsLen(){let e=x(this.restDecoder)+1;return this.dsCurrVal+=e,e}}class Ve extends Gi{constructor(e){super(e);this.keys=[],x(e),this.keyClockDecoder=new Nt(Y(e)),this.clientDecoder=new ot(Y(e)),this.leftClockDecoder=new Nt(Y(e)),this.rightClockDecoder=new Nt(Y(e)),this.infoDecoder=new Or(Y(e),De),this.stringDecoder=new Qn(Y(e)),this.parentInfoDecoder=new Or(Y(e),De),this.typeRefDecoder=new ot(Y(e)),this.lenDecoder=new ot(Y(e))}readLeftID(){return new Me(this.clientDecoder.read(),this.leftClockDecoder.read())}readRightID(){return new Me(this.clientDecoder.read(),this.rightClockDecoder.read())}readClient(){return this.clientDecoder.read()}readInfo(){return this.infoDecoder.read()}readString(){return this.stringDecoder.read()}readParentInfo(){return this.parentInfoDecoder.read()===1}readTypeRef(){return this.typeRefDecoder.read()}readLen(){return this.lenDecoder.read()}readAny(){return nt(this.restDecoder)}readBuf(){return Y(this.restDecoder)}readJSON(){return nt(this.restDecoder)}readKey(){let e=this.keyClockDecoder.read();if(e<this.keys.length)return this.keys[e];else{let t=this.stringDecoder.read();return this.keys.push(t),t}}}class No{constructor(){this.restEncoder=Ot()}toUint8Array(){return se(this.restEncoder)}resetDsCurVal(){}writeDsClock(e){y(this.restEncoder,e)}writeDsLen(e){y(this.restEncoder,e)}}class mt extends No{writeLeftID(e){y(this.restEncoder,e.client),y(this.restEncoder,e.clock)}writeRightID(e){y(this.restEncoder,e.client),y(this.restEncoder,e.clock)}writeClient(e){y(this.restEncoder,e)}writeInfo(e){Er(this.restEncoder,e)}writeString(e){Ue(this.restEncoder,e)}writeParentInfo(e){y(this.restEncoder,e?1:0)}writeTypeRef(e){y(this.restEncoder,e)}writeLen(e){y(this.restEncoder,e)}writeAny(e){et(this.restEncoder,e)}writeBuf(e){K(this.restEncoder,e)}writeJSON(e){Ue(this.restEncoder,JSON.stringify(e))}writeKey(e){Ue(this.restEncoder,e)}}class Uo{constructor(){this.restEncoder=Ot(),this.dsCurrVal=0}toUint8Array(){return se(this.restEncoder)}resetDsCurVal(){this.dsCurrVal=0}writeDsClock(e){let t=e-this.dsCurrVal;this.dsCurrVal=e,y(this.restEncoder,t)}writeDsLen(e){if(e===0)H();y(this.restEncoder,e-1),this.dsCurrVal+=e}}class Te extends Uo{constructor(){super();this.keyMap=new Map,this.keyClock=0,this.keyClockEncoder=new Pt,this.clientEncoder=new rt,this.leftClockEncoder=new Pt,this.rightClockEncoder=new Pt,this.infoEncoder=new Tr(Er),this.stringEncoder=new Hn,this.parentInfoEncoder=new Tr(Er),this.typeRefEncoder=new rt,this.lenEncoder=new rt}toUint8Array(){let e=Ot();return y(e,0),K(e,this.keyClockEncoder.toUint8Array()),K(e,this.clientEncoder.toUint8Array()),K(e,this.leftClockEncoder.toUint8Array()),K(e,this.rightClockEncoder.toUint8Array()),K(e,se(this.infoEncoder)),K(e,this.stringEncoder.toUint8Array()),K(e,se(this.parentInfoEncoder)),K(e,this.typeRefEncoder.toUint8Array()),K(e,this.lenEncoder.toUint8Array()),Zt(e,se(this.restEncoder)),se(e)}writeLeftID(e){this.clientEncoder.write(e.client),this.leftClockEncoder.write(e.clock)}writeRightID(e){this.clientEncoder.write(e.client),this.rightClockEncoder.write(e.clock)}writeClient(e){this.clientEncoder.write(e)}writeInfo(e){this.infoEncoder.write(e)}writeString(e){this.stringEncoder.write(e)}writeParentInfo(e){this.parentInfoEncoder.write(e?1:0)}writeTypeRef(e){this.typeRefEncoder.write(e)}writeLen(e){this.lenEncoder.write(e)}writeAny(e){et(this.restEncoder,e)}writeBuf(e){K(this.restEncoder,e)}writeJSON(e){et(this.restEncoder,e)}writeKey(e){let t=this.keyMap.get(e);if(t===void 0)this.keyClockEncoder.write(this.keyClock++),this.stringEncoder.write(e);else this.keyClockEncoder.write(t)}}var nd=(e,t,r,n)=>{n=we(n,t[0].id.clock);let o=fe(t,n);y(e.restEncoder,t.length-o),e.writeClient(r),y(e.restEncoder,n);let s=t[o];s.write(e,n-s.id.clock);for(let i=o+1;i<t.length;i++)t[i].write(e,0)},Do=(e,t,r)=>{let n=new Map;r.forEach((o,s)=>{if(U(t,s)>o)n.set(s,o)}),cn(t).forEach((o,s)=>{if(!r.has(s))n.set(s,0)}),y(e.restEncoder,n.size),le(n.entries()).sort((o,s)=>s[0]-o[0]).forEach(([o,s])=>{nd(e,t.clients.get(o),o,s)})},od=(e,t)=>{let r=J(),n=x(e.restDecoder);for(let o=0;o<n;o++){let s=x(e.restDecoder),i=Array(s),c=e.readClient(),a=x(e.restDecoder);r.set(c,{i:0,refs:i});for(let l=0;l<s;l++){let u=e.readInfo();switch(Tt&u){case 0:{let h=e.readLen();i[l]=new ee(_(c,a),h),a+=h;break}case 10:{let h=x(e.restDecoder);i[l]=new te(_(c,a),h),a+=h;break}default:{let h=(u&(oe|M))===0,p=new P(_(c,a),null,(u&M)===M?e.readLeftID():null,null,(u&oe)===oe?e.readRightID():null,h?e.readParentInfo()?t.get(e.readString()):e.readLeftID():null,h&&(u&He)===He?e.readString():null,Ec(e,u));i[l]=p,a+=p.length}}}}return r},sd=(e,t,r)=>{let n=[],o=le(r.keys()).sort((f,m)=>f-m);if(o.length===0)return null;let s=()=>{if(o.length===0)return null;let f=r.get(o[o.length-1]);while(f.refs.length===f.i)if(o.pop(),o.length>0)f=r.get(o[o.length-1]);else return null;return f},i=s();if(i===null)return null;let c=new Ro,a=new Map,l=(f,m)=>{let k=a.get(f);if(k==null||k>m)a.set(f,m)},u=i.refs[i.i++],h=new Map,p=()=>{for(let f of n){let m=f.id.client,k=r.get(m);if(k)k.i--,c.clients.set(m,k.refs.slice(k.i)),r.delete(m),k.i=0,k.refs=[];else c.clients.set(m,[f]);o=o.filter((z)=>z!==m)}n.length=0};while(!0){if(u.constructor!==te){let m=ue(h,u.id.client,()=>U(t,u.id.client))-u.id.clock;if(m<0)n.push(u),l(u.id.client,u.id.clock-1),p();else{let k=u.getMissing(e,t);if(k!==null){n.push(u);let z=r.get(k)||{refs:[],i:0};if(z.refs.length===z.i)l(k,U(t,k)),p();else{u=z.refs[z.i++];continue}}else if(m===0||m<u.length)u.integrate(e,m),h.set(u.id.client,u.id.clock+u.length)}}if(n.length>0)u=n.pop();else if(i!==null&&i.i<i.refs.length)u=i.refs[i.i++];else if(i=s(),i===null)break;else u=i.refs[i.i++]}if(c.clients.size>0){let f=new Te;return Do(f,c,new Map),y(f.restEncoder,0),{missing:a,update:f.toUint8Array()}}return null},id=(e,t)=>Do(e,t.doc.store,t.beforeState),cd=(e,t,r,n=new Ve(e))=>v(t,(o)=>{o.local=!1;let s=!1,i=o.doc,c=i.store,a=od(n,i),l=sd(o,c,a),u=c.pendingStructs;if(u){for(let[p,f]of u.missing)if(f<U(c,p)){s=!0;break}if(l){for(let[p,f]of l.missing){let m=u.missing.get(p);if(m==null||m>f)u.missing.set(p,f)}u.update=Yr([u.update,l.update])}}else c.pendingStructs=l;let h=Zi(n,o,c);if(c.pendingDs){let p=new Ve(je(c.pendingDs));x(p.restDecoder);let f=Zi(p,o,c);if(h&&f)c.pendingDs=Yr([h,f]);else c.pendingDs=h||f}else c.pendingDs=h;if(s){let p=c.pendingStructs.update;c.pendingStructs=null,Wi(o.doc,p)}},r,!1);var Wi=(e,t,r,n=Ve)=>{let o=je(t);cd(o,e,r,new n(o))},sn=(e,t,r)=>Wi(e,t,r,Co),ad=(e,t,r=new Map)=>{Do(e,t.store,r),ft(e,rd(t.store))},ud=(e,t=new Uint8Array([0]),r=new Te)=>{let n=Ki(t);ad(r,e,n);let o=[r.toUint8Array()];if(e.store.pendingDs)o.push(e.store.pendingDs);if(e.store.pendingStructs)o.push(kd(e.store.pendingStructs.update,t));if(o.length>1){if(r.constructor===mt)return wd(o.map((s,i)=>i===0?s:zd(s)));else if(r.constructor===Te)return Yr(o)}return o[0]},gt=(e,t)=>ud(e,t,new mt),ld=(e)=>{let t=new Map,r=x(e.restDecoder);for(let n=0;n<r;n++){let o=x(e.restDecoder),s=x(e.restDecoder);t.set(o,s)}return t},Ki=(e)=>ld(new Po(je(e))),Hi=(e,t)=>(y(e.restEncoder,t.size),le(t.entries()).sort((r,n)=>n[0]-r[0]).forEach(([r,n])=>{y(e.restEncoder,r),y(e.restEncoder,n)}),e),pd=(e,t)=>Hi(e,cn(t.store)),hd=(e,t=new Uo)=>{if(e instanceof Map)Hi(t,e);else pd(t,e);return t.toUint8Array()},Yi=(e)=>hd(e,new No);class Xi{constructor(){this.l=[]}}var Pi=()=>new Xi,Ci=(e,t)=>e.l.push(t),Ni=(e,t)=>{let r=e.l,n=r.length;if(e.l=r.filter((o)=>t!==o),n===e.l.length)console.error(\"[yjs] Tried to remove event handler that doesn't exist.\")},Qi=(e,t,r)=>jt(e.l,[t,r]);class Me{constructor(e,t){this.client=e,this.clock=t}}var Jr=(e,t)=>e===t||e!==null&&t!==null&&e.client===t.client&&e.clock===t.clock,_=(e,t)=>new Me(e,t);var dd=(e)=>{for(let[t,r]of e.doc.share.entries())if(r===e)return t;throw H()};class ec{constructor(e,t){this.ds=e,this.sv=t}}var fd=(e,t)=>new ec(e,t),Kg=fd(Ji(),new Map);var pt=(e,t)=>t===void 0?!e.deleted:t.sv.has(e.id.client)&&(t.sv.get(e.id.client)||0)>e.id.clock&&!Fi(t.ds,e.id),To=(e,t)=>{let r=ue(e.meta,To,_e),n=e.doc.store;if(!r.has(t))t.sv.forEach((o,s)=>{if(o<U(n,s))Ae(e,_(s,o))}),Vi(e,t.ds,(o)=>{}),r.add(t)};class Ro{constructor(){this.clients=new Map,this.pendingStructs=null,this.pendingDs=null}}var cn=(e)=>{let t=new Map;return e.clients.forEach((r,n)=>{let o=r[r.length-1];t.set(n,o.id.clock+o.length)}),t},U=(e,t)=>{let r=e.clients.get(t);if(r===void 0)return 0;let n=r[r.length-1];return n.id.clock+n.length},tc=(e,t)=>{let r=e.clients.get(t.id.client);if(r===void 0)r=[],e.clients.set(t.id.client,r);else{let n=r[r.length-1];if(n.id.clock+n.length!==t.id.clock)throw H()}r.push(t)},fe=(e,t)=>{let r=0,n=e.length-1,o=e[n],s=o.id.clock;if(s===t)return n;let i=q(t/(s+o.length-1)*n);while(r<=n){if(o=e[i],s=o.id.clock,s<=t){if(t<s+o.length)return i;r=i+1}else n=i-1;i=q((r+n)/2)}throw H()},md=(e,t)=>{let r=e.clients.get(t.client);return r[fe(r,t.clock)]},Eo=md,Ao=(e,t,r)=>{let n=fe(t,r),o=t[n];if(o.id.clock<r&&o instanceof P)return t.splice(n+1,0,on(e,o,r-o.id.clock)),n+1;return n},Ae=(e,t)=>{let r=e.doc.store.clients.get(t.client);return r[Ao(e,r,t.clock)]},Ui=(e,t,r)=>{let n=t.clients.get(r.client),o=fe(n,r.clock),s=n[o];if(r.clock!==s.id.clock+s.length-1&&s.constructor!==ee)n.splice(o+1,0,on(e,s,r.clock-s.id.clock+1));return s},gd=(e,t,r)=>{let n=e.clients.get(t.id.client);n[fe(n,t.id.clock)]=r},rc=(e,t,r,n,o)=>{if(n===0)return;let s=r+n,i=Ao(e,t,r),c;do{if(c=t[i++],s<c.id.clock+c.length)Ao(e,t,s);o(c)}while(i<t.length&&t[i].id.clock<s)};class nc{constructor(e,t,r){this.doc=e,this.deleteSet=new dt,this.beforeState=cn(e.store),this.afterState=new Map,this.changed=new Map,this.changedParentTypes=new Map,this._mergeStructs=[],this.origin=t,this.meta=new Map,this.local=r,this.subdocsAdded=new Set,this.subdocsRemoved=new Set,this.subdocsLoaded=new Set,this._needFormattingCleanup=!1}}var Di=(e,t)=>{if(t.deleteSet.clients.size===0&&!Os(t.afterState,(r,n)=>t.beforeState.get(n)!==r))return!1;return Oo(t.deleteSet),id(e,t),ft(e,t.deleteSet),!0},Ri=(e,t,r)=>{let n=t._item;if(n===null||n.id.clock<(e.beforeState.get(n.id.client)||0)&&!n.deleted)ue(e.changed,t,_e).add(r)},Wr=(e,t)=>{let r=e[t],n=e[t-1],o=t;for(;o>0;r=n,n=e[--o-1]){if(n.deleted===r.deleted&&n.constructor===r.constructor){if(n.mergeWith(r)){if(r instanceof P&&r.parentSub!==null&&r.parent._map.get(r.parentSub)===r)r.parent._map.set(r.parentSub,n);continue}}break}let s=t-o;if(s)e.splice(t+1-s,s);return s},xd=(e,t,r)=>{for(let[n,o]of e.clients.entries()){let s=t.clients.get(n);for(let i=o.length-1;i>=0;i--){let c=o[i],a=c.clock+c.len;for(let l=fe(s,c.clock),u=s[l];l<s.length&&u.id.clock<a;u=s[++l]){let h=s[l];if(c.clock+c.len<=h.id.clock)break;if(h instanceof P&&h.deleted&&!h.keep&&r(h))h.gc(t,!1)}}}},yd=(e,t)=>{e.clients.forEach((r,n)=>{let o=t.clients.get(n);for(let s=r.length-1;s>=0;s--){let i=r[s],c=kr(o.length-1,1+fe(o,i.clock+i.len-1));for(let a=c,l=o[a];a>0&&l.id.clock>=i.clock;l=o[a])a-=1+Wr(o,a)}})};var oc=(e,t)=>{if(t<e.length){let r=e[t],n=r.doc,o=n.store,s=r.deleteSet,i=r._mergeStructs;try{Oo(s),r.afterState=cn(r.doc.store),n.emit(\"beforeObserverCalls\",[r,n]);let c=[];r.changed.forEach((a,l)=>c.push(()=>{if(l._item===null||!l._item.deleted)l._callObserver(r,a)})),c.push(()=>{r.changedParentTypes.forEach((a,l)=>{if(l._dEH.l.length>0&&(l._item===null||!l._item.deleted))a=a.filter((u)=>u.target._item===null||!u.target._item.deleted),a.forEach((u)=>{u.currentTarget=l,u._path=null}),a.sort((u,h)=>u.path.length-h.path.length),c.push(()=>{Qi(l._dEH,a,r)})}),c.push(()=>n.emit(\"afterTransaction\",[r,n])),c.push(()=>{if(r._needFormattingCleanup)Nd(r)})}),jt(c,[])}finally{if(n.gc)xd(s,o,n.gcFilter);yd(s,o),r.afterState.forEach((u,h)=>{let p=r.beforeState.get(h)||0;if(p!==u){let f=o.clients.get(h),m=we(fe(f,p),1);for(let k=f.length-1;k>=m;)k-=1+Wr(f,k)}});for(let u=i.length-1;u>=0;u--){let{client:h,clock:p}=i[u].id,f=o.clients.get(h),m=fe(f,p);if(m+1<f.length){if(Wr(f,m+1)>1)continue}if(m>0)Wr(f,m)}if(!r.local&&r.afterState.get(n.clientID)!==r.beforeState.get(n.clientID))Ei(lt,Ft,\"[yjs] \",Jt,qt,\"Changed the client-id because another client seems to be using it.\"),n.clientID=qi();if(n.emit(\"afterTransactionCleanup\",[r,n]),n._observers.has(\"update\")){let u=new mt;if(Di(u,r))n.emit(\"update\",[u.toUint8Array(),r.origin,n,r])}if(n._observers.has(\"updateV2\")){let u=new Te;if(Di(u,r))n.emit(\"updateV2\",[u.toUint8Array(),r.origin,n,r])}let{subdocsAdded:c,subdocsLoaded:a,subdocsRemoved:l}=r;if(c.size>0||l.size>0||a.size>0)c.forEach((u)=>{if(u.clientID=n.clientID,u.collectionid==null)u.collectionid=n.collectionid;n.subdocs.add(u)}),l.forEach((u)=>n.subdocs.delete(u)),n.emit(\"subdocs\",[{loaded:a,added:c,removed:l},n,r]),l.forEach((u)=>u.destroy());if(e.length<=t+1)n._transactionCleanups=[],n.emit(\"afterAllTransactions\",[n,e]);else oc(e,t+1)}}},v=(e,t,r=null,n=!0)=>{let o=e._transactionCleanups,s=!1,i=null;if(e._transaction===null){if(s=!0,e._transaction=new nc(e,r,n),o.push(e._transaction),o.length===1)e.emit(\"beforeAllTransactions\",[e]);e.emit(\"beforeTransaction\",[e._transaction,e])}try{i=t(e._transaction)}finally{if(s){let c=e._transaction===o[0];if(e._transaction=null,c)oc(o,0)}}return i};function*_d(e){let t=x(e.restDecoder);for(let r=0;r<t;r++){let n=x(e.restDecoder),o=e.readClient(),s=x(e.restDecoder);for(let i=0;i<n;i++){let c=e.readInfo();if(c===10){let a=x(e.restDecoder);yield new te(_(o,s),a),s+=a}else if((Tt&c)!==0){let a=(c&(oe|M))===0,l=new P(_(o,s),null,(c&M)===M?e.readLeftID():null,null,(c&oe)===oe?e.readRightID():null,a?e.readParentInfo()?e.readString():e.readLeftID():null,a&&(c&He)===He?e.readString():null,Ec(e,c));yield l,s+=l.length}else{let a=e.readLen();yield new ee(_(o,s),a),s+=a}}}}class an{constructor(e,t){this.gen=_d(e),this.curr=null,this.done=!1,this.filterSkips=t,this.next()}next(){do this.curr=this.gen.next().value||null;while(this.filterSkips&&this.curr!==null&&this.curr.constructor===te);return this.curr}}class un{constructor(e){this.currClient=0,this.startClock=0,this.written=0,this.encoder=e,this.clientStructs=[]}}var wd=(e)=>Yr(e,Co,mt);var bd=(e,t)=>{if(e.constructor===ee){let{client:r,clock:n}=e.id;return new ee(_(r,n+t),e.length-t)}else if(e.constructor===te){let{client:r,clock:n}=e.id;return new te(_(r,n+t),e.length-t)}else{let r=e,{client:n,clock:o}=r.id;return new P(_(n,o+t),null,_(n,o+t-1),null,r.rightOrigin,r.parent,r.parentSub,r.content.splice(t))}},Yr=(e,t=Ve,r=Te)=>{if(e.length===1)return e[0];let n=e.map((u)=>new t(je(u))),o=n.map((u)=>new an(u,!0)),s=null,i=new r,c=new un(i);while(!0){if(o=o.filter((p)=>p.curr!==null),o.sort((p,f)=>{if(p.curr.id.client===f.curr.id.client){let m=p.curr.id.clock-f.curr.id.clock;if(m===0)return p.curr.constructor===f.curr.constructor?0:p.curr.constructor===te?1:-1;else return m}else return f.curr.id.client-p.curr.id.client}),o.length===0)break;let u=o[0],h=u.curr.id.client;if(s!==null){let p=u.curr,f=!1;while(p!==null&&p.id.clock+p.length<=s.struct.id.clock+s.struct.length&&p.id.client>=s.struct.id.client)p=u.next(),f=!0;if(p===null||p.id.client!==h||f&&p.id.clock>s.struct.id.clock+s.struct.length)continue;if(h!==s.struct.id.client)Ee(c,s.struct,s.offset),s={struct:p,offset:0},u.next();else if(s.struct.id.clock+s.struct.length<p.id.clock)if(s.struct.constructor===te)s.struct.length=p.id.clock+p.length-s.struct.id.clock;else{Ee(c,s.struct,s.offset);let m=p.id.clock-s.struct.id.clock-s.struct.length;s={struct:new te(_(h,s.struct.id.clock+s.struct.length),m),offset:0}}else{let m=s.struct.id.clock+s.struct.length-p.id.clock;if(m>0)if(s.struct.constructor===te)s.struct.length-=m;else p=bd(p,m);if(!s.struct.mergeWith(p))Ee(c,s.struct,s.offset),s={struct:p,offset:0},u.next()}}else s={struct:u.curr,offset:0},u.next();for(let p=u.curr;p!==null&&p.id.client===h&&p.id.clock===s.struct.id.clock+s.struct.length&&p.constructor!==te;p=u.next())Ee(c,s.struct,s.offset),s={struct:p,offset:0}}if(s!==null)Ee(c,s.struct,s.offset),s=null;jo(c);let a=n.map((u)=>Zo(u)),l=td(a);return ft(i,l),i.toUint8Array()},kd=(e,t,r=Ve,n=Te)=>{let o=Ki(t),s=new n,i=new un(s),c=new r(je(e)),a=new an(c,!1);while(a.curr){let u=a.curr,h=u.id.client,p=o.get(h)||0;if(a.curr.constructor===te){a.next();continue}if(u.id.clock+u.length>p){Ee(i,u,we(p-u.id.clock,0)),a.next();while(a.curr&&a.curr.id.client===h)Ee(i,a.curr,0),a.next()}else while(a.curr&&a.curr.id.client===h&&a.curr.id.clock+a.curr.length<=p)a.next()}jo(i);let l=Zo(c);return ft(s,l),s.toUint8Array()};var sc=(e)=>{if(e.written>0)e.clientStructs.push({written:e.written,restEncoder:se(e.encoder.restEncoder)}),e.encoder.restEncoder=Ot(),e.written=0},Ee=(e,t,r)=>{if(e.written>0&&e.currClient!==t.id.client)sc(e);if(e.written===0)e.currClient=t.id.client,e.encoder.writeClient(t.id.client),y(e.encoder.restEncoder,t.id.clock+r);t.write(e.encoder,r),e.written++},jo=(e)=>{sc(e);let t=e.encoder.restEncoder;y(t,e.clientStructs.length);for(let r=0;r<e.clientStructs.length;r++){let n=e.clientStructs[r];y(t,n.written),Zt(t,n.restEncoder)}},vd=(e,t,r,n)=>{let o=new r(je(e)),s=new an(o,!1),i=new n,c=new un(i);for(let l=s.curr;l!==null;l=s.next())Ee(c,t(l),0);jo(c);let a=Zo(o);return ft(i,a),i.toUint8Array()};var zd=(e)=>vd(e,ei,Ve,mt),ji=\"You must not compute changes after the event-handler fired.\";class Yt{constructor(e,t){this.target=e,this.currentTarget=e,this.transaction=t,this._changes=null,this._keys=null,this._delta=null,this._path=null}get path(){return this._path||(this._path=$d(this.currentTarget,this.target))}deletes(e){return Fi(this.transaction.deleteSet,e.id)}get keys(){if(this._keys===null){if(this.transaction.doc._transactionCleanups.length===0)throw X(ji);let e=new Map,t=this.target;this.transaction.changed.get(t).forEach((n)=>{if(n!==null){let o=t._map.get(n),s,i;if(this.adds(o)){let c=o.left;while(c!==null&&this.adds(c))c=c.left;if(this.deletes(o))if(c!==null&&this.deletes(c))s=\"delete\",i=_r(c.content.getContent());else return;else if(c!==null&&this.deletes(c))s=\"update\",i=_r(c.content.getContent());else s=\"add\",i=void 0}else if(this.deletes(o))s=\"delete\",i=_r(o.content.getContent());else return;e.set(n,{action:s,oldValue:i})}}),this._keys=e}return this._keys}get delta(){return this.changes.delta}adds(e){return e.id.clock>=(this.transaction.beforeState.get(e.id.client)||0)}get changes(){let e=this._changes;if(e===null){if(this.transaction.doc._transactionCleanups.length===0)throw X(ji);let t=this.target,r=_e(),n=_e(),o=[];if(e={added:r,deleted:n,delta:o,keys:this.keys},this.transaction.changed.get(t).has(null)){let i=null,c=()=>{if(i)o.push(i)};for(let a=t._start;a!==null;a=a.right)if(a.deleted){if(this.deletes(a)&&!this.adds(a)){if(i===null||i.delete===void 0)c(),i={delete:0};i.delete+=a.length,n.add(a)}}else if(this.adds(a)){if(i===null||i.insert===void 0)c(),i={insert:[]};i.insert=i.insert.concat(a.content.getContent()),r.add(a)}else{if(i===null||i.retain===void 0)c(),i={retain:0};i.retain+=a.length}if(i!==null&&i.retain===void 0)c()}this._changes=e}return e}}var $d=(e,t)=>{let r=[];while(t._item!==null&&t!==e){if(t._item.parentSub!==null)r.unshift(t._item.parentSub);else{let n=0,o=t._item.parent._start;while(o!==t._item&&o!==null){if(!o.deleted&&o.countable)n+=o.length;o=o.right}r.unshift(n)}t=t._item.parent}return r},F=()=>{Ii(\"Invalid access: Add Yjs type to a document before reading data.\")},ic=80,Lo=0;class cc{constructor(e,t){e.marker=!0,this.p=e,this.index=t,this.timestamp=Lo++}}var Sd=(e)=>{e.timestamp=Lo++},ac=(e,t,r)=>{e.p.marker=!1,e.p=t,t.marker=!0,e.index=r,e.timestamp=Lo++},Ed=(e,t,r)=>{if(e.length>=ic){let n=e.reduce((o,s)=>o.timestamp<s.timestamp?o:s);return ac(n,t,r),n}else{let n=new cc(t,r);return e.push(n),n}},ln=(e,t)=>{if(e._start===null||t===0||e._searchMarker===null)return null;let r=e._searchMarker.length===0?null:e._searchMarker.reduce((s,i)=>Ne(t-s.index)<Ne(t-i.index)?s:i),n=e._start,o=0;if(r!==null)n=r.p,o=r.index,Sd(r);while(n.right!==null&&o<t){if(!n.deleted&&n.countable){if(t<o+n.length)break;o+=n.length}n=n.right}while(n.left!==null&&o>t)if(n=n.left,!n.deleted&&n.countable)o-=n.length;while(n.left!==null&&n.left.id.client===n.id.client&&n.left.id.clock+n.left.length===n.id.clock)if(n=n.left,!n.deleted&&n.countable)o-=n.length;if(r!==null&&Ne(r.index-o)<n.parent.length/ic)return ac(r,n,o),r;else return Ed(e._searchMarker,n,o)},Gt=(e,t,r)=>{for(let n=e.length-1;n>=0;n--){let o=e[n];if(r>0){let s=o.p;s.marker=!1;while(s&&(s.deleted||!s.countable))if(s=s.left,s&&!s.deleted&&s.countable)o.index-=s.length;if(s===null||s.marker===!0){e.splice(n,1);continue}o.p=s,s.marker=!0}if(t<o.index||r>0&&t===o.index)o.index=we(t,o.index+r)}};var pn=(e,t,r)=>{let n=e,o=t.changedParentTypes;while(!0){if(ue(o,e,()=>[]).push(r),e._item===null)break;e=e._item.parent}Qi(n._eH,r,t)};class D{constructor(){this._item=null,this._map=new Map,this._start=null,this.doc=null,this._length=0,this._eH=Pi(),this._dEH=Pi(),this._searchMarker=null}get parent(){return this._item?this._item.parent:null}_integrate(e,t){this.doc=e,this._item=t}_copy(){throw Q()}clone(){throw Q()}_write(e){}get _first(){let e=this._start;while(e!==null&&e.deleted)e=e.right;return e}_callObserver(e,t){if(!e.local&&this._searchMarker)this._searchMarker.length=0}observe(e){Ci(this._eH,e)}observeDeep(e){Ci(this._dEH,e)}unobserve(e){Ni(this._eH,e)}unobserveDeep(e){Ni(this._dEH,e)}toJSON(){}}var uc=(e,t,r)=>{if(e.doc??F(),t<0)t=e._length+t;if(r<0)r=e._length+r;let n=r-t,o=[],s=e._start;while(s!==null&&n>0){if(s.countable&&!s.deleted){let i=s.content.getContent();if(i.length<=t)t-=i.length;else{for(let c=t;c<i.length&&n>0;c++)o.push(i[c]),n--;t=0}}s=s.right}return o},lc=(e)=>{e.doc??F();let t=[],r=e._start;while(r!==null){if(r.countable&&!r.deleted){let n=r.content.getContent();for(let o=0;o<n.length;o++)t.push(n[o])}r=r.right}return t};var Wt=(e,t)=>{let r=0,n=e._start;e.doc??F();while(n!==null){if(n.countable&&!n.deleted){let o=n.content.getContent();for(let s=0;s<o.length;s++)t(o[s],r++,e)}n=n.right}},pc=(e,t)=>{let r=[];return Wt(e,(n,o)=>{r.push(t(n,o,e))}),r},Id=(e)=>{let t=e._start,r=null,n=0;return{[Symbol.iterator](){return this},next:()=>{if(r===null){while(t!==null&&t.deleted)t=t.right;if(t===null)return{done:!0,value:void 0};r=t.content.getContent(),n=0,t=t.right}let o=r[n++];if(r.length<=n)r=null;return{done:!1,value:o}}}},hc=(e,t)=>{e.doc??F();let r=ln(e,t),n=e._start;if(r!==null)n=r.p,t-=r.index;for(;n!==null;n=n.right)if(!n.deleted&&n.countable){if(t<n.length)return n.content.getContent()[t];t-=n.length}},Xr=(e,t,r,n)=>{let o=r,s=e.doc,i=s.clientID,c=s.store,a=r===null?t._start:r.right,l=[],u=()=>{if(l.length>0)o=new P(_(i,U(c,i)),o,o&&o.lastId,a,a&&a.id,t,null,new Je(l)),o.integrate(e,0),l=[]};n.forEach((h)=>{if(h===null)l.push(h);else switch(h.constructor){case Number:case Object:case Boolean:case Array:case String:l.push(h);break;default:switch(u(),h.constructor){case Uint8Array:case ArrayBuffer:o=new P(_(i,U(c,i)),o,o&&o.lastId,a,a&&a.id,t,null,new Xt(new Uint8Array(h))),o.integrate(e,0);break;case ge:o=new P(_(i,U(c,i)),o,o&&o.lastId,a,a&&a.id,t,null,new Qt(h)),o.integrate(e,0);break;default:if(h instanceof D)o=new P(_(i,U(c,i)),o,o&&o.lastId,a,a&&a.id,t,null,new ke(h)),o.integrate(e,0);else throw Error(\"Unexpected content type in insert operation\")}}}),u()},dc=()=>X(\"Length exceeded!\"),fc=(e,t,r,n)=>{if(r>t._length)throw dc();if(r===0){if(t._searchMarker)Gt(t._searchMarker,r,n.length);return Xr(e,t,null,n)}let o=r,s=ln(t,r),i=t._start;if(s!==null){if(i=s.p,r-=s.index,r===0)i=i.prev,r+=i&&i.countable&&!i.deleted?i.length:0}for(;i!==null;i=i.right)if(!i.deleted&&i.countable){if(r<=i.length){if(r<i.length)Ae(e,_(i.id.client,i.id.clock+r));break}r-=i.length}if(t._searchMarker)Gt(t._searchMarker,o,n.length);return Xr(e,t,i,n)},Td=(e,t,r)=>{let o=(t._searchMarker||[]).reduce((s,i)=>i.index>s.index?i:s,{index:0,p:t._start}).p;if(o)while(o.right)o=o.right;return Xr(e,t,o,r)},mc=(e,t,r,n)=>{if(n===0)return;let o=r,s=n,i=ln(t,r),c=t._start;if(i!==null)c=i.p,r-=i.index;for(;c!==null&&r>0;c=c.right)if(!c.deleted&&c.countable){if(r<c.length)Ae(e,_(c.id.client,c.id.clock+r));r-=c.length}while(n>0&&c!==null){if(!c.deleted){if(n<c.length)Ae(e,_(c.id.client,c.id.clock+n));c.delete(e),n-=c.length}c=c.right}if(n>0)throw dc();if(t._searchMarker)Gt(t._searchMarker,o,-s+n)},Qr=(e,t,r)=>{let n=t._map.get(r);if(n!==void 0)n.delete(e)},Bo=(e,t,r,n)=>{let o=t._map.get(r)||null,s=e.doc,i=s.clientID,c;if(n==null)c=new Je([n]);else switch(n.constructor){case Number:case Object:case Boolean:case Array:case String:case Date:case BigInt:c=new Je([n]);break;case Uint8Array:c=new Xt(n);break;case ge:c=new Qt(n);break;default:if(n instanceof D)c=new ke(n);else throw Error(\"Unexpected content type\")}new P(_(i,U(s.store,i)),o,o&&o.lastId,null,null,t,r,c).integrate(e,0)},Mo=(e,t)=>{e.doc??F();let r=e._map.get(t);return r!==void 0&&!r.deleted?r.content.getContent()[r.length-1]:void 0},gc=(e)=>{let t={};return e.doc??F(),e._map.forEach((r,n)=>{if(!r.deleted)t[n]=r.content.getContent()[r.length-1]}),t},xc=(e,t)=>{e.doc??F();let r=e._map.get(t);return r!==void 0&&!r.deleted};var Ad=(e,t)=>{let r={};return e._map.forEach((n,o)=>{let s=n;while(s!==null&&(!t.sv.has(s.id.client)||s.id.clock>=(t.sv.get(s.id.client)||0)))s=s.left;if(s!==null&&pt(s,t))r[o]=s.content.getContent()[s.length-1]}),r},qr=(e)=>(e.doc??F(),Oi(e._map.entries(),(t)=>!t[1].deleted));class yc extends Yt{}class re extends D{constructor(){super();this._prelimContent=[],this._searchMarker=[]}static from(e){let t=new re;return t.push(e),t}_integrate(e,t){super._integrate(e,t),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new re}clone(){let e=new re;return e.insert(0,this.toArray().map((t)=>t instanceof D?t.clone():t)),e}get length(){return this.doc??F(),this._length}_callObserver(e,t){super._callObserver(e,t),pn(this,e,new yc(this,e))}insert(e,t){if(this.doc!==null)v(this.doc,(r)=>{fc(r,this,e,t)});else this._prelimContent.splice(e,0,...t)}push(e){if(this.doc!==null)v(this.doc,(t)=>{Td(t,this,e)});else this._prelimContent.push(...e)}unshift(e){this.insert(0,e)}delete(e,t=1){if(this.doc!==null)v(this.doc,(r)=>{mc(r,this,e,t)});else this._prelimContent.splice(e,t)}get(e){return hc(this,e)}toArray(){return lc(this)}slice(e=0,t=this.length){return uc(this,e,t)}toJSON(){return this.map((e)=>e instanceof D?e.toJSON():e)}map(e){return pc(this,e)}forEach(e){Wt(this,e)}[Symbol.iterator](){return Id(this)}_write(e){e.writeTypeRef(Xd)}}var Od=(e)=>new re;class _c extends Yt{constructor(e,t,r){super(e,t);this.keysChanged=r}}class G extends D{constructor(e){super();if(this._prelimContent=null,e===void 0)this._prelimContent=new Map;else this._prelimContent=new Map(e)}_integrate(e,t){super._integrate(e,t),this._prelimContent.forEach((r,n)=>{this.set(n,r)}),this._prelimContent=null}_copy(){return new G}clone(){let e=new G;return this.forEach((t,r)=>{e.set(r,t instanceof D?t.clone():t)}),e}_callObserver(e,t){pn(this,e,new _c(this,e,t))}toJSON(){this.doc??F();let e={};return this._map.forEach((t,r)=>{if(!t.deleted){let n=t.content.getContent()[t.length-1];e[r]=n instanceof D?n.toJSON():n}}),e}get size(){return[...qr(this)].length}keys(){return Fr(qr(this),(e)=>e[0])}values(){return Fr(qr(this),(e)=>e[1].content.getContent()[e[1].length-1])}entries(){return Fr(qr(this),(e)=>[e[0],e[1].content.getContent()[e[1].length-1]])}forEach(e){this.doc??F(),this._map.forEach((t,r)=>{if(!t.deleted)e(t.content.getContent()[t.length-1],r,this)})}[Symbol.iterator](){return this.entries()}delete(e){if(this.doc!==null)v(this.doc,(t)=>{Qr(t,this,e)});else this._prelimContent.delete(e)}set(e,t){if(this.doc!==null)v(this.doc,(r)=>{Bo(r,this,e,t)});else this._prelimContent.set(e,t);return t}get(e){return Mo(this,e)}has(e){return xc(this,e)}clear(){if(this.doc!==null)v(this.doc,(e)=>{this.forEach(function(t,r,n){Qr(e,n,r)})});else this._prelimContent.clear()}_write(e){e.writeTypeRef(Qd)}}var Zd=(e)=>new G,Ie=(e,t)=>e===t||typeof e===\"object\"&&typeof t===\"object\"&&e&&t&&oo(e,t);class en{constructor(e,t,r,n){this.left=e,this.right=t,this.index=r,this.currentAttributes=n}forward(){if(this.right===null)H();switch(this.right.content.constructor){case C:if(!this.right.deleted)xt(this.currentAttributes,this.right.content);break;default:if(!this.right.deleted)this.index+=this.right.length;break}this.left=this.right,this.right=this.right.right}}var Li=(e,t,r)=>{while(t.right!==null&&r>0){switch(t.right.content.constructor){case C:if(!t.right.deleted)xt(t.currentAttributes,t.right.content);break;default:if(!t.right.deleted){if(r<t.right.length)Ae(e,_(t.right.id.client,t.right.id.clock+r));t.index+=t.right.length,r-=t.right.length}break}t.left=t.right,t.right=t.right.right}return t},Gr=(e,t,r,n)=>{let o=new Map,s=n?ln(t,r):null;if(s){let i=new en(s.p.left,s.p,s.index,o);return Li(e,i,r-s.index)}else{let i=new en(null,t._start,0,o);return Li(e,i,r)}},wc=(e,t,r,n)=>{while(r.right!==null&&(r.right.deleted===!0||r.right.content.constructor===C&&Ie(n.get(r.right.content.key),r.right.content.value))){if(!r.right.deleted)n.delete(r.right.content.key);r.forward()}let o=e.doc,s=o.clientID;n.forEach((i,c)=>{let{left:a,right:l}=r,u=new P(_(s,U(o.store,s)),a,a&&a.lastId,l,l&&l.id,t,null,new C(c,i));u.integrate(e,0),r.right=u,r.forward()})},xt=(e,t)=>{let{key:r,value:n}=t;if(n===null)e.delete(r);else e.set(r,n)},bc=(e,t)=>{while(!0){if(e.right===null)break;else if(e.right.deleted||e.right.content.constructor===C&&Ie(t[e.right.content.key]??null,e.right.content.value));else break;e.forward()}},kc=(e,t,r,n)=>{let o=e.doc,s=o.clientID,i=new Map;for(let c in n){let a=n[c],l=r.currentAttributes.get(c)??null;if(!Ie(l,a)){i.set(c,l);let{left:u,right:h}=r;r.right=new P(_(s,U(o.store,s)),u,u&&u.lastId,h,h&&h.id,t,null,new C(c,a)),r.right.integrate(e,0),r.forward()}}return i},Io=(e,t,r,n,o)=>{r.currentAttributes.forEach((p,f)=>{if(o[f]===void 0)o[f]=null});let s=e.doc,i=s.clientID;bc(r,o);let c=kc(e,t,r,o),a=n.constructor===String?new me(n):n instanceof D?new ke(n):new qe(n),{left:l,right:u,index:h}=r;if(t._searchMarker)Gt(t._searchMarker,r.index,a.getLength());u=new P(_(i,U(s.store,i)),l,l&&l.lastId,u,u&&u.id,t,null,a),u.integrate(e,0),r.right=u,r.index=h,r.forward(),wc(e,t,r,c)},Bi=(e,t,r,n,o)=>{let s=e.doc,i=s.clientID;bc(r,o);let c=kc(e,t,r,o);e:while(r.right!==null&&(n>0||c.size>0&&(r.right.deleted||r.right.content.constructor===C))){if(!r.right.deleted)switch(r.right.content.constructor){case C:{let{key:a,value:l}=r.right.content,u=o[a];if(u!==void 0){if(Ie(u,l))c.delete(a);else{if(n===0)break e;c.set(a,l)}r.right.delete(e)}else r.currentAttributes.set(a,l);break}default:if(n<r.right.length)Ae(e,_(r.right.id.client,r.right.id.clock+n));n-=r.right.length;break}r.forward()}if(n>0){let a=\"\";for(;n>0;n--)a+=`\n`;r.right=new P(_(i,U(s.store,i)),r.left,r.left&&r.left.lastId,r.right,r.right&&r.right.id,t,null,new me(a)),r.right.integrate(e,0),r.forward()}wc(e,t,r,c)},vc=(e,t,r,n,o)=>{let s=t,i=J();while(s&&(!s.countable||s.deleted)){if(!s.deleted&&s.content.constructor===C){let l=s.content;i.set(l.key,l)}s=s.right}let c=0,a=!1;while(t!==s){if(r===t)a=!0;if(!t.deleted){let l=t.content;switch(l.constructor){case C:{let{key:u,value:h}=l,p=n.get(u)??null;if(i.get(u)!==l||p===h){if(t.delete(e),c++,!a&&(o.get(u)??null)===h&&p!==h)if(p===null)o.delete(u);else o.set(u,p)}if(!a&&!t.deleted)xt(o,l);break}}}t=t.right}return c},Pd=(e,t)=>{while(t&&t.right&&(t.right.deleted||!t.right.countable))t=t.right;let r=new Set;while(t&&(t.deleted||!t.countable)){if(!t.deleted&&t.content.constructor===C){let n=t.content.key;if(r.has(n))t.delete(e);else r.add(n)}t=t.left}},Cd=(e)=>{let t=0;return v(e.doc,(r)=>{let{_start:n,_start:o}=e,s=J(),i=yr(s);while(o){if(o.deleted===!1)switch(o.content.constructor){case C:xt(i,o.content);break;default:t+=vc(r,n,o,s,i),s=yr(i),n=o;break}o=o.right}}),t},Nd=(e)=>{let t=new Set,r=e.doc;for(let[n,o]of e.afterState.entries()){let s=e.beforeState.get(n)||0;if(o===s)continue;rc(e,r.store.clients.get(n),s,o,(i)=>{if(!i.deleted&&i.content.constructor===C&&i.constructor!==ee)t.add(i.parent)})}v(r,(n)=>{Vi(e,e.deleteSet,(o)=>{if(o instanceof ee||!o.parent._hasFormatting||t.has(o.parent))return;let s=o.parent;if(o.content.constructor===C)t.add(s);else Pd(n,o)});for(let o of t)Cd(o)})},Mi=(e,t,r)=>{let n=r,o=yr(t.currentAttributes),s=t.right;while(r>0&&t.right!==null){if(t.right.deleted===!1)switch(t.right.content.constructor){case ke:case qe:case me:if(r<t.right.length)Ae(e,_(t.right.id.client,t.right.id.clock+r));r-=t.right.length,t.right.delete(e);break}t.forward()}if(s)vc(e,s,t.right,o,t.currentAttributes);let i=(t.left||t.right).parent;if(i._searchMarker)Gt(i._searchMarker,t.index,-n+r);return t};class zc extends Yt{constructor(e,t,r){super(e,t);this.childListChanged=!1,this.keysChanged=new Set,r.forEach((n)=>{if(n===null)this.childListChanged=!0;else this.keysChanged.add(n)})}get changes(){if(this._changes===null){let e={keys:this.keys,delta:this.delta,added:new Set,deleted:new Set};this._changes=e}return this._changes}get delta(){if(this._delta===null){let e=this.target.doc,t=[];v(e,(r)=>{let n=new Map,o=new Map,s=this.target._start,i=null,c={},a=\"\",l=0,u=0,h=()=>{if(i!==null){let p=null;switch(i){case\"delete\":if(u>0)p={delete:u};u=0;break;case\"insert\":if(typeof a===\"object\"||a.length>0){if(p={insert:a},n.size>0)p.attributes={},n.forEach((f,m)=>{if(f!==null)p.attributes[m]=f})}a=\"\";break;case\"retain\":if(l>0){if(p={retain:l},!Qs(c))p.attributes=Ys({},c)}l=0;break}if(p)t.push(p);i=null}};while(s!==null){switch(s.content.constructor){case ke:case qe:if(this.adds(s)){if(!this.deletes(s))h(),i=\"insert\",a=s.content.getContent()[0],h()}else if(this.deletes(s)){if(i!==\"delete\")h(),i=\"delete\";u+=1}else if(!s.deleted){if(i!==\"retain\")h(),i=\"retain\";l+=1}break;case me:if(this.adds(s)){if(!this.deletes(s)){if(i!==\"insert\")h(),i=\"insert\";a+=s.content.str}}else if(this.deletes(s)){if(i!==\"delete\")h(),i=\"delete\";u+=s.length}else if(!s.deleted){if(i!==\"retain\")h(),i=\"retain\";l+=s.length}break;case C:{let{key:p,value:f}=s.content;if(this.adds(s)){if(!this.deletes(s)){let m=n.get(p)??null;if(!Ie(m,f)){if(i===\"retain\")h();if(Ie(f,o.get(p)??null))delete c[p];else c[p]=f}else if(f!==null)s.delete(r)}}else if(this.deletes(s)){o.set(p,f);let m=n.get(p)??null;if(!Ie(m,f)){if(i===\"retain\")h();c[p]=m}}else if(!s.deleted){o.set(p,f);let m=c[p];if(m!==void 0){if(!Ie(m,f)){if(i===\"retain\")h();if(f===null)delete c[p];else c[p]=f}else if(m!==null)s.delete(r)}}if(!s.deleted){if(i===\"insert\")h();xt(n,s.content)}break}}s=s.right}h();while(t.length>0){let p=t[t.length-1];if(p.retain!==void 0&&p.attributes===void 0)t.pop();else break}}),this._delta=t}return this._delta}}class ie extends D{constructor(e){super();this._pending=e!==void 0?[()=>this.insert(0,e)]:[],this._searchMarker=[],this._hasFormatting=!1}get length(){return this.doc??F(),this._length}_integrate(e,t){super._integrate(e,t);try{this._pending.forEach((r)=>r())}catch(r){console.error(r)}this._pending=null}_copy(){return new ie}clone(){let e=new ie;return e.applyDelta(this.toDelta()),e}_callObserver(e,t){super._callObserver(e,t);let r=new zc(this,e,t);if(pn(this,e,r),!e.local&&this._hasFormatting)e._needFormattingCleanup=!0}toString(){this.doc??F();let e=\"\",t=this._start;while(t!==null){if(!t.deleted&&t.countable&&t.content.constructor===me)e+=t.content.str;t=t.right}return e}toJSON(){return this.toString()}applyDelta(e,{sanitize:t=!0}={}){if(this.doc!==null)v(this.doc,(r)=>{let n=new en(null,this._start,0,new Map);for(let o=0;o<e.length;o++){let s=e[o];if(s.insert!==void 0){let i=!t&&typeof s.insert===\"string\"&&o===e.length-1&&n.right===null&&s.insert.slice(-1)===`\n`?s.insert.slice(0,-1):s.insert;if(typeof i!==\"string\"||i.length>0)Io(r,this,n,i,s.attributes||{})}else if(s.retain!==void 0)Bi(r,this,n,s.retain,s.attributes||{});else if(s.delete!==void 0)Mi(r,n,s.delete)}});else this._pending.push(()=>this.applyDelta(e))}toDelta(e,t,r){this.doc??F();let n=[],o=new Map,s=this.doc,i=\"\",c=this._start;function a(){if(i.length>0){let u={},h=!1;o.forEach((f,m)=>{h=!0,u[m]=f});let p={insert:i};if(h)p.attributes=u;n.push(p),i=\"\"}}let l=()=>{while(c!==null){if(pt(c,e)||t!==void 0&&pt(c,t))switch(c.content.constructor){case me:{let u=o.get(\"ychange\");if(e!==void 0&&!pt(c,e)){if(u===void 0||u.user!==c.id.client||u.type!==\"removed\")a(),o.set(\"ychange\",r?r(\"removed\",c.id):{type:\"removed\"})}else if(t!==void 0&&!pt(c,t)){if(u===void 0||u.user!==c.id.client||u.type!==\"added\")a(),o.set(\"ychange\",r?r(\"added\",c.id):{type:\"added\"})}else if(u!==void 0)a(),o.delete(\"ychange\");i+=c.content.str;break}case ke:case qe:{a();let u={insert:c.content.getContent()[0]};if(o.size>0){let h={};u.attributes=h,o.forEach((p,f)=>{h[f]=p})}n.push(u);break}case C:if(pt(c,e))a(),xt(o,c.content);break}c=c.right}a()};if(e||t)v(s,(u)=>{if(e)To(u,e);if(t)To(u,t);l()},\"cleanup\");else l();return n}insert(e,t,r){if(t.length<=0)return;let n=this.doc;if(n!==null)v(n,(o)=>{let s=Gr(o,this,e,!r);if(!r)r={},s.currentAttributes.forEach((i,c)=>{r[c]=i});Io(o,this,s,t,r)});else this._pending.push(()=>this.insert(e,t,r))}insertEmbed(e,t,r){let n=this.doc;if(n!==null)v(n,(o)=>{let s=Gr(o,this,e,!r);Io(o,this,s,t,r||{})});else this._pending.push(()=>this.insertEmbed(e,t,r||{}))}delete(e,t){if(t===0)return;let r=this.doc;if(r!==null)v(r,(n)=>{Mi(n,Gr(n,this,e,!0),t)});else this._pending.push(()=>this.delete(e,t))}format(e,t,r){if(t===0)return;let n=this.doc;if(n!==null)v(n,(o)=>{let s=Gr(o,this,e,!1);if(s.right===null)return;Bi(o,this,s,t,r)});else this._pending.push(()=>this.format(e,t,r))}removeAttribute(e){if(this.doc!==null)v(this.doc,(t)=>{Qr(t,this,e)});else this._pending.push(()=>this.removeAttribute(e))}setAttribute(e,t){if(this.doc!==null)v(this.doc,(r)=>{Bo(r,this,e,t)});else this._pending.push(()=>this.setAttribute(e,t))}getAttribute(e){return Mo(this,e)}getAttributes(){return gc(this)}_write(e){e.writeTypeRef(ef)}}var Ud=(e)=>new ie;class Kr{constructor(e,t=()=>!0){this._filter=t,this._root=e,this._currentNode=e._start,this._firstCall=!0,e.doc??F()}[Symbol.iterator](){return this}next(){let e=this._currentNode,t=e&&e.content&&e.content.type;if(e!==null&&(!this._firstCall||e.deleted||!this._filter(t)))do if(t=e.content.type,!e.deleted&&(t.constructor===ht||t.constructor===Fe)&&t._start!==null)e=t._start;else while(e!==null){let r=e.next;if(r!==null){e=r;break}else if(e.parent===this._root)e=null;else e=e.parent._item}while(e!==null&&(e.deleted||!this._filter(e.content.type)));if(this._firstCall=!1,e===null)return{value:void 0,done:!0};return this._currentNode=e,{value:e.content.type,done:!1}}}class Fe extends D{constructor(){super();this._prelimContent=[]}get firstChild(){let e=this._first;return e?e.content.getContent()[0]:null}_integrate(e,t){super._integrate(e,t),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new Fe}clone(){let e=new Fe;return e.insert(0,this.toArray().map((t)=>t instanceof D?t.clone():t)),e}get length(){return this.doc??F(),this._prelimContent===null?this._length:this._prelimContent.length}createTreeWalker(e){return new Kr(this,e)}querySelector(e){e=e.toUpperCase();let r=new Kr(this,(n)=>n.nodeName&&n.nodeName.toUpperCase()===e).next();if(r.done)return null;else return r.value}querySelectorAll(e){return e=e.toUpperCase(),le(new Kr(this,(t)=>t.nodeName&&t.nodeName.toUpperCase()===e))}_callObserver(e,t){pn(this,e,new $c(this,t,e))}toString(){return pc(this,(e)=>e.toString()).join(\"\")}toJSON(){return this.toString()}toDOM(e=document,t={},r){let n=e.createDocumentFragment();if(r!==void 0)r._createAssociation(n,this);return Wt(this,(o)=>{n.insertBefore(o.toDOM(e,t,r),null)}),n}insert(e,t){if(this.doc!==null)v(this.doc,(r)=>{fc(r,this,e,t)});else this._prelimContent.splice(e,0,...t)}insertAfter(e,t){if(this.doc!==null)v(this.doc,(r)=>{let n=e&&e instanceof D?e._item:e;Xr(r,this,n,t)});else{let r=this._prelimContent,n=e===null?0:r.findIndex((o)=>o===e)+1;if(n===0&&e!==null)throw X(\"Reference item not found\");r.splice(n,0,...t)}}delete(e,t=1){if(this.doc!==null)v(this.doc,(r)=>{mc(r,this,e,t)});else this._prelimContent.splice(e,t)}toArray(){return lc(this)}push(e){this.insert(this.length,e)}unshift(e){this.insert(0,e)}get(e){return hc(this,e)}slice(e=0,t=this.length){return uc(this,e,t)}forEach(e){Wt(this,e)}_write(e){e.writeTypeRef(rf)}}var Dd=(e)=>new Fe;class ht extends Fe{constructor(e=\"UNDEFINED\"){super();this.nodeName=e,this._prelimAttrs=new Map}get nextSibling(){let e=this._item?this._item.next:null;return e?e.content.type:null}get prevSibling(){let e=this._item?this._item.prev:null;return e?e.content.type:null}_integrate(e,t){super._integrate(e,t),this._prelimAttrs.forEach((r,n)=>{this.setAttribute(n,r)}),this._prelimAttrs=null}_copy(){return new ht(this.nodeName)}clone(){let e=new ht(this.nodeName),t=this.getAttributes();return Xs(t,(r,n)=>{e.setAttribute(n,r)}),e.insert(0,this.toArray().map((r)=>r instanceof D?r.clone():r)),e}toString(){let e=this.getAttributes(),t=[],r=[];for(let i in e)r.push(i);r.sort();let n=r.length;for(let i=0;i<n;i++){let c=r[i];t.push(c+'=\"'+e[c]+'\"')}let o=this.nodeName.toLocaleLowerCase(),s=t.length>0?\" \"+t.join(\" \"):\"\";return`<${o}${s}>${super.toString()}</${o}>`}removeAttribute(e){if(this.doc!==null)v(this.doc,(t)=>{Qr(t,this,e)});else this._prelimAttrs.delete(e)}setAttribute(e,t){if(this.doc!==null)v(this.doc,(r)=>{Bo(r,this,e,t)});else this._prelimAttrs.set(e,t)}getAttribute(e){return Mo(this,e)}hasAttribute(e){return xc(this,e)}getAttributes(e){return e?Ad(this,e):gc(this)}toDOM(e=document,t={},r){let n=e.createElement(this.nodeName),o=this.getAttributes();for(let s in o){let i=o[s];if(typeof i===\"string\")n.setAttribute(s,i)}if(Wt(this,(s)=>{n.appendChild(s.toDOM(e,t,r))}),r!==void 0)r._createAssociation(n,this);return n}_write(e){e.writeTypeRef(tf),e.writeKey(this.nodeName)}}var Rd=(e)=>new ht(e.readKey());class $c extends Yt{constructor(e,t,r){super(e,r);this.childListChanged=!1,this.attributesChanged=new Set,t.forEach((n)=>{if(n===null)this.childListChanged=!0;else this.attributesChanged.add(n)})}}class tn extends G{constructor(e){super();this.hookName=e}_copy(){return new tn(this.hookName)}clone(){let e=new tn(this.hookName);return this.forEach((t,r)=>{e.set(r,t)}),e}toDOM(e=document,t={},r){let n=t[this.hookName],o;if(n!==void 0)o=n.createDom(this);else o=document.createElement(this.hookName);if(o.setAttribute(\"data-yjs-hook\",this.hookName),r!==void 0)r._createAssociation(o,this);return o}_write(e){e.writeTypeRef(nf),e.writeKey(this.hookName)}}var jd=(e)=>new tn(e.readKey());class rn extends ie{get nextSibling(){let e=this._item?this._item.next:null;return e?e.content.type:null}get prevSibling(){let e=this._item?this._item.prev:null;return e?e.content.type:null}_copy(){return new rn}clone(){let e=new rn;return e.applyDelta(this.toDelta()),e}toDOM(e=document,t,r){let n=e.createTextNode(this.toString());if(r!==void 0)r._createAssociation(n,this);return n}toString(){return this.toDelta().map((e)=>{let t=[];for(let n in e.attributes){let o=[];for(let s in e.attributes[n])o.push({key:s,value:e.attributes[n][s]});o.sort((s,i)=>s.key<i.key?-1:1),t.push({nodeName:n,attrs:o})}t.sort((n,o)=>n.nodeName<o.nodeName?-1:1);let r=\"\";for(let n=0;n<t.length;n++){let o=t[n];r+=`<${o.nodeName}`;for(let s=0;s<o.attrs.length;s++){let i=o.attrs[s];r+=` ${i.key}=\"${i.value}\"`}r+=\">\"}r+=e.insert;for(let n=t.length-1;n>=0;n--)r+=`</${t[n].nodeName}>`;return r}).join(\"\")}toJSON(){return this.toString()}_write(e){e.writeTypeRef(of)}}var Ld=(e)=>new rn;class hn{constructor(e,t){this.id=e,this.length=t}get deleted(){throw Q()}mergeWith(e){return!1}write(e,t,r){throw Q()}integrate(e,t){throw Q()}}var Bd=0;class ee extends hn{get deleted(){return!0}delete(){}mergeWith(e){if(this.constructor!==e.constructor)return!1;return this.length+=e.length,!0}integrate(e,t){if(t>0)this.id.clock+=t,this.length-=t;tc(e.doc.store,this)}write(e,t){e.writeInfo(Bd),e.writeLen(this.length-t)}getMissing(e,t){return null}}class Xt{constructor(e){this.content=e}getLength(){return 1}getContent(){return[this.content]}isCountable(){return!0}copy(){return new Xt(this.content)}splice(e){throw Q()}mergeWith(e){return!1}integrate(e,t){}delete(e){}gc(e){}write(e,t){e.writeBuf(this.content)}getRef(){return 3}}var Md=(e)=>new Xt(e.readBuf());class Kt{constructor(e){this.len=e}getLength(){return this.len}getContent(){return[]}isCountable(){return!1}copy(){return new Kt(this.len)}splice(e){let t=new Kt(this.len-e);return this.len=e,t}mergeWith(e){return this.len+=e.len,!0}integrate(e,t){Hr(e.deleteSet,t.id.client,t.id.clock,this.len),t.markDeleted()}delete(e){}gc(e){}write(e,t){e.writeLen(this.len-t)}getRef(){return 1}}var Vd=(e)=>new Kt(e.readLen()),Sc=(e,t)=>new ge({guid:e,...t,shouldLoad:t.shouldLoad||t.autoLoad||!1});class Qt{constructor(e){if(e._item)console.error(\"This document was already integrated as a sub-document. You should create a second instance instead with the same guid.\");this.doc=e;let t={};if(this.opts=t,!e.gc)t.gc=!1;if(e.autoLoad)t.autoLoad=!0;if(e.meta!==null)t.meta=e.meta}getLength(){return 1}getContent(){return[this.doc]}isCountable(){return!0}copy(){return new Qt(Sc(this.doc.guid,this.opts))}splice(e){throw Q()}mergeWith(e){return!1}integrate(e,t){if(this.doc._item=t,e.subdocsAdded.add(this.doc),this.doc.shouldLoad)e.subdocsLoaded.add(this.doc)}delete(e){if(e.subdocsAdded.has(this.doc))e.subdocsAdded.delete(this.doc);else e.subdocsRemoved.add(this.doc)}gc(e){}write(e,t){e.writeString(this.doc.guid),e.writeAny(this.opts)}getRef(){return 9}}var Fd=(e)=>new Qt(Sc(e.readString(),e.readAny()));class qe{constructor(e){this.embed=e}getLength(){return 1}getContent(){return[this.embed]}isCountable(){return!0}copy(){return new qe(this.embed)}splice(e){throw Q()}mergeWith(e){return!1}integrate(e,t){}delete(e){}gc(e){}write(e,t){e.writeJSON(this.embed)}getRef(){return 5}}var Jd=(e)=>new qe(e.readJSON());class C{constructor(e,t){this.key=e,this.value=t}getLength(){return 1}getContent(){return[]}isCountable(){return!1}copy(){return new C(this.key,this.value)}splice(e){throw Q()}mergeWith(e){return!1}integrate(e,t){let r=t.parent;r._searchMarker=null,r._hasFormatting=!0}delete(e){}gc(e){}write(e,t){e.writeKey(this.key),e.writeJSON(this.value)}getRef(){return 6}}var qd=(e)=>new C(e.readKey(),e.readJSON());class nn{constructor(e){this.arr=e}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new nn(this.arr)}splice(e){let t=new nn(this.arr.slice(e));return this.arr=this.arr.slice(0,e),t}mergeWith(e){return this.arr=this.arr.concat(e.arr),!0}integrate(e,t){}delete(e){}gc(e){}write(e,t){let r=this.arr.length;e.writeLen(r-t);for(let n=t;n<r;n++){let o=this.arr[n];e.writeString(o===void 0?\"undefined\":JSON.stringify(o))}}getRef(){return 2}}var Gd=(e)=>{let t=e.readLen(),r=[];for(let n=0;n<t;n++){let o=e.readString();if(o===\"undefined\")r.push(void 0);else r.push(JSON.parse(o))}return new nn(r)},Wd=Bt(\"node_env\")===\"development\";class Je{constructor(e){this.arr=e,Wd&&so(e)}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new Je(this.arr)}splice(e){let t=new Je(this.arr.slice(e));return this.arr=this.arr.slice(0,e),t}mergeWith(e){return this.arr=this.arr.concat(e.arr),!0}integrate(e,t){}delete(e){}gc(e){}write(e,t){let r=this.arr.length;e.writeLen(r-t);for(let n=t;n<r;n++){let o=this.arr[n];e.writeAny(o)}}getRef(){return 8}}var Kd=(e)=>{let t=e.readLen(),r=[];for(let n=0;n<t;n++)r.push(e.readAny());return new Je(r)};class me{constructor(e){this.str=e}getLength(){return this.str.length}getContent(){return this.str.split(\"\")}isCountable(){return!0}copy(){return new me(this.str)}splice(e){let t=new me(this.str.slice(e));this.str=this.str.slice(0,e);let r=this.str.charCodeAt(e-1);if(r>=55296&&r<=56319)this.str=this.str.slice(0,e-1)+\"�\",t.str=\"�\"+t.str.slice(1);return t}mergeWith(e){return this.str+=e.str,!0}integrate(e,t){}delete(e){}gc(e){}write(e,t){e.writeString(t===0?this.str:this.str.slice(t))}getRef(){return 4}}var Hd=(e)=>new me(e.readString()),Yd=[Od,Zd,Ud,Rd,Dd,jd,Ld],Xd=0,Qd=1,ef=2,tf=3,rf=4,nf=5,of=6;class ke{constructor(e){this.type=e}getLength(){return 1}getContent(){return[this.type]}isCountable(){return!0}copy(){return new ke(this.type._copy())}splice(e){throw Q()}mergeWith(e){return!1}integrate(e,t){this.type._integrate(e.doc,t)}delete(e){let t=this.type._start;while(t!==null){if(!t.deleted)t.delete(e);else if(t.id.clock<(e.beforeState.get(t.id.client)||0))e._mergeStructs.push(t);t=t.right}this.type._map.forEach((r)=>{if(!r.deleted)r.delete(e);else if(r.id.clock<(e.beforeState.get(r.id.client)||0))e._mergeStructs.push(r)}),e.changed.delete(this.type)}gc(e){let t=this.type._start;while(t!==null)t.gc(e,!0),t=t.right;this.type._start=null,this.type._map.forEach((r)=>{while(r!==null)r.gc(e,!0),r=r.left}),this.type._map=new Map}write(e,t){this.type._write(e)}getRef(){return 7}}var sf=(e)=>new ke(Yd[e.readTypeRef()](e));var on=(e,t,r)=>{let{client:n,clock:o}=t.id,s=new P(_(n,o+r),t,_(n,o+r-1),t.right,t.rightOrigin,t.parent,t.parentSub,t.content.splice(r));if(t.deleted)s.markDeleted();if(t.keep)s.keep=!0;if(t.redone!==null)s.redone=_(t.redone.client,t.redone.clock+r);if(t.right=s,s.right!==null)s.right.left=s;if(e._mergeStructs.push(s),s.parentSub!==null&&s.right===null)s.parent._map.set(s.parentSub,s);return t.length=r,s};class P extends hn{constructor(e,t,r,n,o,s,i,c){super(e,c.getLength());this.origin=r,this.left=t,this.right=n,this.rightOrigin=o,this.parent=s,this.parentSub=i,this.redone=null,this.content=c,this.info=this.content.isCountable()?Mn:0}set marker(e){if((this.info&$r)>0!==e)this.info^=$r}get marker(){return(this.info&$r)>0}get keep(){return(this.info&Bn)>0}set keep(e){if(this.keep!==e)this.info^=Bn}get countable(){return(this.info&Mn)>0}get deleted(){return(this.info&zr)>0}set deleted(e){if(this.deleted!==e)this.info^=zr}markDeleted(){this.info|=zr}getMissing(e,t){if(this.origin&&this.origin.client!==this.id.client&&this.origin.clock>=U(t,this.origin.client))return this.origin.client;if(this.rightOrigin&&this.rightOrigin.client!==this.id.client&&this.rightOrigin.clock>=U(t,this.rightOrigin.client))return this.rightOrigin.client;if(this.parent&&this.parent.constructor===Me&&this.id.client!==this.parent.client&&this.parent.clock>=U(t,this.parent.client))return this.parent.client;if(this.origin)this.left=Ui(e,t,this.origin),this.origin=this.left.lastId;if(this.rightOrigin)this.right=Ae(e,this.rightOrigin),this.rightOrigin=this.right.id;if(this.left&&this.left.constructor===ee||this.right&&this.right.constructor===ee)this.parent=null;else if(!this.parent){if(this.left&&this.left.constructor===P)this.parent=this.left.parent,this.parentSub=this.left.parentSub;else if(this.right&&this.right.constructor===P)this.parent=this.right.parent,this.parentSub=this.right.parentSub}else if(this.parent.constructor===Me){let r=Eo(t,this.parent);if(r.constructor===ee)this.parent=null;else this.parent=r.content.type}return null}integrate(e,t){if(t>0)this.id.clock+=t,this.left=Ui(e,e.doc.store,_(this.id.client,this.id.clock-1)),this.origin=this.left.lastId,this.content=this.content.splice(t),this.length-=t;if(this.parent){if(!this.left&&(!this.right||this.right.left!==null)||this.left&&this.left.right!==this.right){let r=this.left,n;if(r!==null)n=r.right;else if(this.parentSub!==null){n=this.parent._map.get(this.parentSub)||null;while(n!==null&&n.left!==null)n=n.left}else n=this.parent._start;let o=new Set,s=new Set;while(n!==null&&n!==this.right){if(s.add(n),o.add(n),Jr(this.origin,n.origin)){if(n.id.client<this.id.client)r=n,o.clear();else if(Jr(this.rightOrigin,n.rightOrigin))break}else if(n.origin!==null&&s.has(Eo(e.doc.store,n.origin))){if(!o.has(Eo(e.doc.store,n.origin)))r=n,o.clear()}else break;n=n.right}this.left=r}if(this.left!==null){let r=this.left.right;this.right=r,this.left.right=this}else{let r;if(this.parentSub!==null){r=this.parent._map.get(this.parentSub)||null;while(r!==null&&r.left!==null)r=r.left}else r=this.parent._start,this.parent._start=this;this.right=r}if(this.right!==null)this.right.left=this;else if(this.parentSub!==null){if(this.parent._map.set(this.parentSub,this),this.left!==null)this.left.delete(e)}if(this.parentSub===null&&this.countable&&!this.deleted)this.parent._length+=this.length;if(tc(e.doc.store,this),this.content.integrate(e,this),Ri(e,this.parent,this.parentSub),this.parent._item!==null&&this.parent._item.deleted||this.parentSub!==null&&this.right!==null)this.delete(e)}else new ee(this.id,this.length).integrate(e,0)}get next(){let e=this.right;while(e!==null&&e.deleted)e=e.right;return e}get prev(){let e=this.left;while(e!==null&&e.deleted)e=e.left;return e}get lastId(){return this.length===1?this.id:_(this.id.client,this.id.clock+this.length-1)}mergeWith(e){if(this.constructor===e.constructor&&Jr(e.origin,this.lastId)&&this.right===e&&Jr(this.rightOrigin,e.rightOrigin)&&this.id.client===e.id.client&&this.id.clock+this.length===e.id.clock&&this.deleted===e.deleted&&this.redone===null&&e.redone===null&&this.content.constructor===e.content.constructor&&this.content.mergeWith(e.content)){let t=this.parent._searchMarker;if(t)t.forEach((r)=>{if(r.p===e){if(r.p=this,!this.deleted&&this.countable)r.index-=this.length}});if(e.keep)this.keep=!0;if(this.right=e.right,this.right!==null)this.right.left=this;return this.length+=e.length,!0}return!1}delete(e){if(!this.deleted){let t=this.parent;if(this.countable&&this.parentSub===null)t._length-=this.length;this.markDeleted(),Hr(e.deleteSet,this.id.client,this.id.clock,this.length),Ri(e,t,this.parentSub),this.content.delete(e)}}gc(e,t){if(!this.deleted)throw H();if(this.content.gc(e),t)gd(e,this,new ee(this.id,this.length));else this.content=new Kt(this.length)}write(e,t){let r=t>0?_(this.id.client,this.id.clock+t-1):this.origin,n=this.rightOrigin,o=this.parentSub,s=this.content.getRef()&Tt|(r===null?0:M)|(n===null?0:oe)|(o===null?0:He);if(e.writeInfo(s),r!==null)e.writeLeftID(r);if(n!==null)e.writeRightID(n);if(r===null&&n===null){let i=this.parent;if(i._item!==void 0){let c=i._item;if(c===null){let a=dd(i);e.writeParentInfo(!0),e.writeString(a)}else e.writeParentInfo(!1),e.writeLeftID(c.id)}else if(i.constructor===String)e.writeParentInfo(!0),e.writeString(i);else if(i.constructor===Me)e.writeParentInfo(!1),e.writeLeftID(i);else H();if(o!==null)e.writeString(o)}this.content.write(e,t)}}var Ec=(e,t)=>cf[t&Tt](e),cf=[()=>{H()},Vd,Gd,Md,Hd,Jd,qd,sf,Kd,Fd,()=>{H()}],af=10;class te extends hn{get deleted(){return!0}delete(){}mergeWith(e){if(this.constructor!==e.constructor)return!1;return this.length+=e.length,!0}integrate(e,t){H()}write(e,t){e.writeInfo(af),y(e.restEncoder,this.length-t)}getMissing(e,t){return null}}var Ic=typeof globalThis<\"u\"?globalThis:typeof window<\"u\"?window:typeof global<\"u\"?global:{},Tc=\"__ $YJS$ __\";if(Ic[Tc]===!0)console.error(\"Yjs was already imported. This breaks constructor checks and will lead to issues! - https://github.com/yjs/yjs/issues/438\");Ic[Tc]=!0;var Oc;function d(e,t,r){function n(c,a){if(!c._zod)Object.defineProperty(c,\"_zod\",{value:{def:a,constr:i,traits:new Set},enumerable:!1});if(c._zod.traits.has(e))return;c._zod.traits.add(e),t(c,a);let l=i.prototype,u=Object.keys(l);for(let h=0;h<u.length;h++){let p=u[h];if(!(p in c))c[p]=l[p].bind(c)}}let o=r?.Parent??Object;class s extends o{}Object.defineProperty(s,\"name\",{value:e});function i(c){var a;let l=r?.Parent?new s:this;n(l,c),(a=l._zod).deferred??(a.deferred=[]);for(let u of l._zod.deferred)u();return l}return Object.defineProperty(i,\"init\",{value:n}),Object.defineProperty(i,Symbol.hasInstance,{value:(c)=>{if(r?.Parent&&c instanceof r.Parent)return!0;return c?._zod?.traits?.has(e)}}),Object.defineProperty(i,\"name\",{value:e}),i}var Hg=Symbol(\"zod_brand\");class ve extends Error{constructor(){super(\"Encountered Promise during synchronous parse. Use .parseAsync() instead.\")}}class er extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`);this.name=\"ZodEncodeError\"}}(Oc=globalThis).__zod_globalConfig??(Oc.__zod_globalConfig={});var yt=globalThis.__zod_globalConfig;function ze(e){if(e)Object.assign(yt,e);return yt}var b={};Zp(b,{BIGINT_FORMAT_RANGES:()=>Uc,Class:()=>Lc,NUMBER_FORMAT_RANGES:()=>Ko,aborted:()=>Ze,allowsEval:()=>qo,assert:()=>df,assertEqual:()=>uf,assertIs:()=>pf,assertNever:()=>hf,assertNotEqual:()=>lf,assignProp:()=>Oe,base64ToUint8Array:()=>Rc,base64urlToUint8Array:()=>Zf,cached:()=>wt,captureStackTrace:()=>fn,cleanEnum:()=>Of,cleanRegex:()=>or,clone:()=>ce,cloneDef:()=>gf,createTransparentProxy:()=>kf,defineLazy:()=>w,esc:()=>dn,escapeRegex:()=>Se,explicitlyAborted:()=>Ho,extend:()=>$f,finalizeIssue:()=>xe,floatSafeRemainder:()=>Fo,getElementAtPath:()=>xf,getEnumValues:()=>rr,getLengthableOrigin:()=>ir,getParsedType:()=>bf,getSizableOrigin:()=>Dc,hexToUint8Array:()=>Cf,isObject:()=>Ge,isPlainObject:()=>We,issue:()=>bt,joinValues:()=>ff,jsonStringifyReplacer:()=>_t,merge:()=>Ef,mergeDefs:()=>$e,normalizeParams:()=>g,nullish:()=>nr,numKeys:()=>wf,objectClone:()=>mf,omit:()=>zf,optionalKeys:()=>Wo,parsedType:()=>Af,partial:()=>If,pick:()=>vf,prefixIssues:()=>sr,primitiveTypes:()=>Cc,promiseAllObject:()=>yf,propertyKeyTypes:()=>Go,randomString:()=>_f,required:()=>Tf,safeExtend:()=>Sf,shallowClone:()=>Pc,slugify:()=>Jo,stringifyPrimitive:()=>Nc,uint8ArrayToBase64:()=>jc,uint8ArrayToBase64url:()=>Pf,uint8ArrayToHex:()=>Nf,unwrapMessage:()=>tr});function uf(e){return e}function lf(e){return e}function pf(e){}function hf(e){throw Error(\"Unexpected value in exhaustive check\")}function df(e){}function rr(e){let t=Object.values(e).filter((n)=>typeof n===\"number\");return Object.entries(e).filter(([n,o])=>t.indexOf(+n)===-1).map(([n,o])=>o)}function ff(e,t=\"|\"){return e.map((r)=>Nc(r)).join(t)}function _t(e,t){if(typeof t===\"bigint\")return t.toString();return t}function wt(e){return{get value(){{let r=e();return Object.defineProperty(this,\"value\",{value:r}),r}throw Error(\"cached value already set\")}}}function nr(e){return e===null||e===void 0}function or(e){let t=e.startsWith(\"^\")?1:0,r=e.endsWith(\"$\")?e.length-1:e.length;return e.slice(t,r)}function Fo(e,t){let r=e/t,n=Math.round(r),o=Number.EPSILON*Math.max(Math.abs(r),1);if(Math.abs(r-n)<o)return 0;return r-n}var Zc=Symbol(\"evaluating\");function w(e,t,r){let n=void 0;Object.defineProperty(e,t,{get(){if(n===Zc)return;if(n===void 0)n=Zc,n=r();return n},set(o){Object.defineProperty(e,t,{value:o})},configurable:!0})}function mf(e){return Object.create(Object.getPrototypeOf(e),Object.getOwnPropertyDescriptors(e))}function Oe(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function $e(...e){let t={};for(let r of e){let n=Object.getOwnPropertyDescriptors(r);Object.assign(t,n)}return Object.defineProperties({},t)}function gf(e){return $e(e._zod.def)}function xf(e,t){if(!t)return e;return t.reduce((r,n)=>r?.[n],e)}function yf(e){let t=Object.keys(e),r=t.map((n)=>e[n]);return Promise.all(r).then((n)=>{let o={};for(let s=0;s<t.length;s++)o[t[s]]=n[s];return o})}function _f(e=10){let r=\"\";for(let n=0;n<e;n++)r+=\"abcdefghijklmnopqrstuvwxyz\"[Math.floor(Math.random()*26)];return r}function dn(e){return JSON.stringify(e)}function Jo(e){return e.toLowerCase().trim().replace(/[^\\w\\s-]/g,\"\").replace(/[\\s_-]+/g,\"-\").replace(/^-+|-+$/g,\"\")}var fn=\"captureStackTrace\"in Error?Error.captureStackTrace:(...e)=>{};function Ge(e){return typeof e===\"object\"&&e!==null&&!Array.isArray(e)}var qo=wt(()=>{if(yt.jitless)return!1;if(typeof navigator<\"u\"&&navigator?.userAgent?.includes(\"Cloudflare\"))return!1;try{return new Function(\"\"),!0}catch(e){return!1}});function We(e){if(Ge(e)===!1)return!1;let t=e.constructor;if(t===void 0)return!0;if(typeof t!==\"function\")return!0;let r=t.prototype;if(Ge(r)===!1)return!1;if(Object.prototype.hasOwnProperty.call(r,\"isPrototypeOf\")===!1)return!1;return!0}function Pc(e){if(We(e))return{...e};if(Array.isArray(e))return[...e];if(e instanceof Map)return new Map(e);if(e instanceof Set)return new Set(e);return e}function wf(e){let t=0;for(let r in e)if(Object.prototype.hasOwnProperty.call(e,r))t++;return t}var bf=(e)=>{let t=typeof e;switch(t){case\"undefined\":return\"undefined\";case\"string\":return\"string\";case\"number\":return Number.isNaN(e)?\"nan\":\"number\";case\"boolean\":return\"boolean\";case\"function\":return\"function\";case\"bigint\":return\"bigint\";case\"symbol\":return\"symbol\";case\"object\":if(Array.isArray(e))return\"array\";if(e===null)return\"null\";if(e.then&&typeof e.then===\"function\"&&e.catch&&typeof e.catch===\"function\")return\"promise\";if(typeof Map<\"u\"&&e instanceof Map)return\"map\";if(typeof Set<\"u\"&&e instanceof Set)return\"set\";if(typeof Date<\"u\"&&e instanceof Date)return\"date\";if(typeof File<\"u\"&&e instanceof File)return\"file\";return\"object\";default:throw Error(`Unknown data type: ${t}`)}},Go=new Set([\"string\",\"number\",\"symbol\"]),Cc=new Set([\"string\",\"number\",\"bigint\",\"boolean\",\"symbol\",\"undefined\"]);function Se(e){return e.replace(/[.*+?^${}()|[\\]\\\\]/g,\"\\\\$&\")}function ce(e,t,r){let n=new e._zod.constr(t??e._zod.def);if(!t||r?.parent)n._zod.parent=e;return n}function g(e){let t=e;if(!t)return{};if(typeof t===\"string\")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw Error(\"Cannot specify both `message` and `error` params\");t.error=t.message}if(delete t.message,typeof t.error===\"string\")return{...t,error:()=>t.error};return t}function kf(e){let t;return new Proxy({},{get(r,n,o){return t??(t=e()),Reflect.get(t,n,o)},set(r,n,o,s){return t??(t=e()),Reflect.set(t,n,o,s)},has(r,n){return t??(t=e()),Reflect.has(t,n)},deleteProperty(r,n){return t??(t=e()),Reflect.deleteProperty(t,n)},ownKeys(r){return t??(t=e()),Reflect.ownKeys(t)},getOwnPropertyDescriptor(r,n){return t??(t=e()),Reflect.getOwnPropertyDescriptor(t,n)},defineProperty(r,n,o){return t??(t=e()),Reflect.defineProperty(t,n,o)}})}function Nc(e){if(typeof e===\"bigint\")return e.toString()+\"n\";if(typeof e===\"string\")return`\"${e}\"`;return`${e}`}function Wo(e){return Object.keys(e).filter((t)=>e[t]._zod.optin===\"optional\"&&e[t]._zod.optout===\"optional\")}var Ko={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-340282346638528860000000000000000000000,340282346638528860000000000000000000000],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},Uc={int64:[BigInt(\"-9223372036854775808\"),BigInt(\"9223372036854775807\")],uint64:[BigInt(0),BigInt(\"18446744073709551615\")]};function vf(e,t){let r=e._zod.def,n=r.checks;if(n&&n.length>0)throw Error(\".pick() cannot be used on object schemas containing refinements\");let s=$e(e._zod.def,{get shape(){let i={};for(let c in t){if(!(c in r.shape))throw Error(`Unrecognized key: \"${c}\"`);if(!t[c])continue;i[c]=r.shape[c]}return Oe(this,\"shape\",i),i},checks:[]});return ce(e,s)}function zf(e,t){let r=e._zod.def,n=r.checks;if(n&&n.length>0)throw Error(\".omit() cannot be used on object schemas containing refinements\");let s=$e(e._zod.def,{get shape(){let i={...e._zod.def.shape};for(let c in t){if(!(c in r.shape))throw Error(`Unrecognized key: \"${c}\"`);if(!t[c])continue;delete i[c]}return Oe(this,\"shape\",i),i},checks:[]});return ce(e,s)}function $f(e,t){if(!We(t))throw Error(\"Invalid input to extend: expected a plain object\");let r=e._zod.def.checks;if(r&&r.length>0){let s=e._zod.def.shape;for(let i in t)if(Object.getOwnPropertyDescriptor(s,i)!==void 0)throw Error(\"Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.\")}let o=$e(e._zod.def,{get shape(){let s={...e._zod.def.shape,...t};return Oe(this,\"shape\",s),s}});return ce(e,o)}function Sf(e,t){if(!We(t))throw Error(\"Invalid input to safeExtend: expected a plain object\");let r=$e(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t};return Oe(this,\"shape\",n),n}});return ce(e,r)}function Ef(e,t){if(e._zod.def.checks?.length)throw Error(\".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.\");let r=$e(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t._zod.def.shape};return Oe(this,\"shape\",n),n},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return ce(e,r)}function If(e,t,r){let o=t._zod.def.checks;if(o&&o.length>0)throw Error(\".partial() cannot be used on object schemas containing refinements\");let i=$e(t._zod.def,{get shape(){let c=t._zod.def.shape,a={...c};if(r)for(let l in r){if(!(l in c))throw Error(`Unrecognized key: \"${l}\"`);if(!r[l])continue;a[l]=e?new e({type:\"optional\",innerType:c[l]}):c[l]}else for(let l in c)a[l]=e?new e({type:\"optional\",innerType:c[l]}):c[l];return Oe(this,\"shape\",a),a},checks:[]});return ce(t,i)}function Tf(e,t,r){let n=$e(t._zod.def,{get shape(){let o=t._zod.def.shape,s={...o};if(r)for(let i in r){if(!(i in s))throw Error(`Unrecognized key: \"${i}\"`);if(!r[i])continue;s[i]=new e({type:\"nonoptional\",innerType:o[i]})}else for(let i in o)s[i]=new e({type:\"nonoptional\",innerType:o[i]});return Oe(this,\"shape\",s),s}});return ce(t,n)}function Ze(e,t=0){if(e.aborted===!0)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function Ho(e,t=0){if(e.aborted===!0)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue===!1)return!0;return!1}function sr(e,t){return t.map((r)=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(e),r})}function tr(e){return typeof e===\"string\"?e:e?.message}function xe(e,t,r){let n=e.message?e.message:tr(e.inst?._zod.def?.error?.(e))??tr(t?.error?.(e))??tr(r.customError?.(e))??tr(r.localeError?.(e))??\"Invalid input\",{inst:o,continue:s,input:i,...c}=e;if(c.path??(c.path=[]),c.message=n,t?.reportInput)c.input=i;return c}function Dc(e){if(e instanceof Set)return\"set\";if(e instanceof Map)return\"map\";if(e instanceof File)return\"file\";return\"unknown\"}function ir(e){if(Array.isArray(e))return\"array\";if(typeof e===\"string\")return\"string\";return\"unknown\"}function Af(e){let t=typeof e;switch(t){case\"number\":return Number.isNaN(e)?\"nan\":\"number\";case\"object\":{if(e===null)return\"null\";if(Array.isArray(e))return\"array\";let r=e;if(r&&Object.getPrototypeOf(r)!==Object.prototype&&\"constructor\"in r&&r.constructor)return r.constructor.name}}return t}function bt(...e){let[t,r,n]=e;if(typeof t===\"string\")return{message:t,code:\"custom\",input:r,inst:n};return{...t}}function Of(e){return Object.entries(e).filter(([t,r])=>Number.isNaN(Number.parseInt(t,10))).map((t)=>t[1])}function Rc(e){let t=atob(e),r=new Uint8Array(t.length);for(let n=0;n<t.length;n++)r[n]=t.charCodeAt(n);return r}function jc(e){let t=\"\";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return btoa(t)}function Zf(e){let t=e.replace(/-/g,\"+\").replace(/_/g,\"/\"),r=\"=\".repeat((4-t.length%4)%4);return Rc(t+r)}function Pf(e){return jc(e).replace(/\\+/g,\"-\").replace(/\\//g,\"_\").replace(/=/g,\"\")}function Cf(e){let t=e.replace(/^0x/,\"\");if(t.length%2!==0)throw Error(\"Invalid hex string length\");let r=new Uint8Array(t.length/2);for(let n=0;n<t.length;n+=2)r[n/2]=Number.parseInt(t.slice(n,n+2),16);return r}function Nf(e){return Array.from(e).map((t)=>t.toString(16).padStart(2,\"0\")).join(\"\")}class Lc{constructor(...e){}}var Bc=(e,t)=>{e.name=\"$ZodError\",Object.defineProperty(e,\"_zod\",{value:e._zod,enumerable:!1}),Object.defineProperty(e,\"issues\",{value:t,enumerable:!1}),e.message=JSON.stringify(t,_t,2),Object.defineProperty(e,\"toString\",{value:()=>e.message,enumerable:!1})},mn=d(\"$ZodError\",Bc),Yo=d(\"$ZodError\",Bc,{Parent:Error});function Mc(e,t=(r)=>r.message){let r={},n=[];for(let o of e.issues)if(o.path.length>0)r[o.path[0]]=r[o.path[0]]||[],r[o.path[0]].push(t(o));else n.push(t(o));return{formErrors:n,fieldErrors:r}}function Vc(e,t=(r)=>r.message){let r={_errors:[]},n=(o,s=[])=>{for(let i of o.issues)if(i.code===\"invalid_union\"&&i.errors.length)i.errors.map((c)=>n({issues:c},[...s,...i.path]));else if(i.code===\"invalid_key\")n({issues:i.issues},[...s,...i.path]);else if(i.code===\"invalid_element\")n({issues:i.issues},[...s,...i.path]);else{let c=[...s,...i.path];if(c.length===0)r._errors.push(t(i));else{let a=r,l=0;while(l<c.length){let u=c[l];if(l!==c.length-1)a[u]=a[u]||{_errors:[]};else a[u]=a[u]||{_errors:[]},a[u]._errors.push(t(i));a=a[u],l++}}}};return n(e),r}var gn=(e)=>(t,r,n,o)=>{let s=n?{...n,async:!1}:{async:!1},i=t._zod.run({value:r,issues:[]},s);if(i instanceof Promise)throw new ve;if(i.issues.length){let c=new(o?.Err??e)(i.issues.map((a)=>xe(a,s,ze())));throw fn(c,o?.callee),c}return i.value};var xn=(e)=>async(t,r,n,o)=>{let s=n?{...n,async:!0}:{async:!0},i=t._zod.run({value:r,issues:[]},s);if(i instanceof Promise)i=await i;if(i.issues.length){let c=new(o?.Err??e)(i.issues.map((a)=>xe(a,s,ze())));throw fn(c,o?.callee),c}return i.value};var cr=(e)=>(t,r,n)=>{let o=n?{...n,async:!1}:{async:!1},s=t._zod.run({value:r,issues:[]},o);if(s instanceof Promise)throw new ve;return s.issues.length?{success:!1,error:new(e??mn)(s.issues.map((i)=>xe(i,o,ze())))}:{success:!0,data:s.value}},Fc=cr(Yo),ar=(e)=>async(t,r,n)=>{let o=n?{...n,async:!0}:{async:!0},s=t._zod.run({value:r,issues:[]},o);if(s instanceof Promise)s=await s;return s.issues.length?{success:!1,error:new e(s.issues.map((i)=>xe(i,o,ze())))}:{success:!0,data:s.value}},Jc=ar(Yo),qc=(e)=>(t,r,n)=>{let o=n?{...n,direction:\"backward\"}:{direction:\"backward\"};return gn(e)(t,r,o)};var Gc=(e)=>(t,r,n)=>gn(e)(t,r,n);var Wc=(e)=>async(t,r,n)=>{let o=n?{...n,direction:\"backward\"}:{direction:\"backward\"};return xn(e)(t,r,o)};var Kc=(e)=>async(t,r,n)=>xn(e)(t,r,n);var Hc=(e)=>(t,r,n)=>{let o=n?{...n,direction:\"backward\"}:{direction:\"backward\"};return cr(e)(t,r,o)};var Yc=(e)=>(t,r,n)=>cr(e)(t,r,n);var Xc=(e)=>async(t,r,n)=>{let o=n?{...n,direction:\"backward\"}:{direction:\"backward\"};return ar(e)(t,r,o)};var Qc=(e)=>async(t,r,n)=>ar(e)(t,r,n);var ea=/^[cC][0-9a-z]{6,}$/,ta=/^[0-9a-z]+$/,ra=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,na=/^[0-9a-vA-V]{20}$/,oa=/^[A-Za-z0-9]{27}$/,sa=/^[a-zA-Z0-9_-]{21}$/,ia=/^P(?:(\\d+W)|(?!.*W)(?=\\d|T\\d)(\\d+Y)?(\\d+M)?(\\d+D)?(T(?=\\d)(\\d+H)?(\\d+M)?(\\d+([.,]\\d+)?S)?)?)$/;var ca=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,Xo=(e)=>{if(!e)return/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`)};var aa=/^(?!\\.)(?!.*\\.\\.)([A-Za-z0-9_'+\\-\\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\\-]*\\.)+[A-Za-z]{2,}$/;var Df=\"^(\\\\p{Extended_Pictographic}|\\\\p{Emoji_Component})+$\";function ua(){return new RegExp(Df,\"u\")}var la=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,pa=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/;var ha=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\/([0-9]|[1-2][0-9]|3[0-2])$/,da=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,fa=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Qo=/^[A-Za-z0-9_-]*$/;var ma=/^https?$/,ga=/^\\+[1-9]\\d{6,14}$/,xa=\"(?:(?:\\\\d\\\\d[2468][048]|\\\\d\\\\d[13579][26]|\\\\d\\\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\\\d|30)|(?:02)-(?:0[1-9]|1\\\\d|2[0-8])))\",ya=new RegExp(`^${xa}$`);function _a(e){return typeof e.precision===\"number\"?e.precision===-1?\"(?:[01]\\\\d|2[0-3]):[0-5]\\\\d\":e.precision===0?\"(?:[01]\\\\d|2[0-3]):[0-5]\\\\d:[0-5]\\\\d\":`(?:[01]\\\\d|2[0-3]):[0-5]\\\\d:[0-5]\\\\d\\\\.\\\\d{${e.precision}}`:\"(?:[01]\\\\d|2[0-3]):[0-5]\\\\d(?::[0-5]\\\\d(?:\\\\.\\\\d+)?)?\"}function wa(e){return new RegExp(`^${_a(e)}$`)}function ba(e){let t=_a({precision:e.precision}),r=[\"Z\"];if(e.local)r.push(\"\");if(e.offset)r.push(\"([+-](?:[01]\\\\d|2[0-3]):[0-5]\\\\d)\");let n=`${t}(?:${r.join(\"|\")})`;return new RegExp(`^${xa}T(?:${n})$`)}var ka=(e)=>{let t=e?`[\\\\s\\\\S]{${e?.minimum??0},${e?.maximum??\"\"}}`:\"[\\\\s\\\\S]*\";return new RegExp(`^${t}$`)};var va=/^-?\\d+$/,za=/^-?\\d+(?:\\.\\d+)?$/;var $a=/^[^A-Z]*$/,Sa=/^[^a-z]*$/;var L=d(\"$ZodCheck\",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),Ea={number:\"number\",bigint:\"bigint\",object:\"date\"},es=d(\"$ZodCheckLessThan\",(e,t)=>{L.init(e,t);let r=Ea[typeof t.value];e._zod.onattach.push((n)=>{let o=n._zod.bag,s=(t.inclusive?o.maximum:o.exclusiveMaximum)??Number.POSITIVE_INFINITY;if(t.value<s)if(t.inclusive)o.maximum=t.value;else o.exclusiveMaximum=t.value}),e._zod.check=(n)=>{if(t.inclusive?n.value<=t.value:n.value<t.value)return;n.issues.push({origin:r,code:\"too_big\",maximum:typeof t.value===\"object\"?t.value.getTime():t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),ts=d(\"$ZodCheckGreaterThan\",(e,t)=>{L.init(e,t);let r=Ea[typeof t.value];e._zod.onattach.push((n)=>{let o=n._zod.bag,s=(t.inclusive?o.minimum:o.exclusiveMinimum)??Number.NEGATIVE_INFINITY;if(t.value>s)if(t.inclusive)o.minimum=t.value;else o.exclusiveMinimum=t.value}),e._zod.check=(n)=>{if(t.inclusive?n.value>=t.value:n.value>t.value)return;n.issues.push({origin:r,code:\"too_small\",minimum:typeof t.value===\"object\"?t.value.getTime():t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Ia=d(\"$ZodCheckMultipleOf\",(e,t)=>{L.init(e,t),e._zod.onattach.push((r)=>{var n;(n=r._zod.bag).multipleOf??(n.multipleOf=t.value)}),e._zod.check=(r)=>{if(typeof r.value!==typeof t.value)throw Error(\"Cannot mix number and bigint in multiple_of check.\");if(typeof r.value===\"bigint\"?r.value%t.value===BigInt(0):Fo(r.value,t.value)===0)return;r.issues.push({origin:typeof r.value,code:\"not_multiple_of\",divisor:t.value,input:r.value,inst:e,continue:!t.abort})}}),Ta=d(\"$ZodCheckNumberFormat\",(e,t)=>{L.init(e,t),t.format=t.format||\"float64\";let r=t.format?.includes(\"int\"),n=r?\"int\":\"number\",[o,s]=Ko[t.format];e._zod.onattach.push((i)=>{let c=i._zod.bag;if(c.format=t.format,c.minimum=o,c.maximum=s,r)c.pattern=va}),e._zod.check=(i)=>{let c=i.value;if(r){if(!Number.isInteger(c)){i.issues.push({expected:n,format:t.format,code:\"invalid_type\",continue:!1,input:c,inst:e});return}if(!Number.isSafeInteger(c)){if(c>0)i.issues.push({input:c,code:\"too_big\",maximum:Number.MAX_SAFE_INTEGER,note:\"Integers must be within the safe integer range.\",inst:e,origin:n,inclusive:!0,continue:!t.abort});else i.issues.push({input:c,code:\"too_small\",minimum:Number.MIN_SAFE_INTEGER,note:\"Integers must be within the safe integer range.\",inst:e,origin:n,inclusive:!0,continue:!t.abort});return}}if(c<o)i.issues.push({origin:\"number\",input:c,code:\"too_small\",minimum:o,inclusive:!0,inst:e,continue:!t.abort});if(c>s)i.issues.push({origin:\"number\",input:c,code:\"too_big\",maximum:s,inclusive:!0,inst:e,continue:!t.abort})}});var Aa=d(\"$ZodCheckMaxLength\",(e,t)=>{var r;L.init(e,t),(r=e._zod.def).when??(r.when=(n)=>{let o=n.value;return!nr(o)&&o.length!==void 0}),e._zod.onattach.push((n)=>{let o=n._zod.bag.maximum??Number.POSITIVE_INFINITY;if(t.maximum<o)n._zod.bag.maximum=t.maximum}),e._zod.check=(n)=>{let o=n.value;if(o.length<=t.maximum)return;let i=ir(o);n.issues.push({origin:i,code:\"too_big\",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),Oa=d(\"$ZodCheckMinLength\",(e,t)=>{var r;L.init(e,t),(r=e._zod.def).when??(r.when=(n)=>{let o=n.value;return!nr(o)&&o.length!==void 0}),e._zod.onattach.push((n)=>{let o=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(t.minimum>o)n._zod.bag.minimum=t.minimum}),e._zod.check=(n)=>{let o=n.value;if(o.length>=t.minimum)return;let i=ir(o);n.issues.push({origin:i,code:\"too_small\",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),Za=d(\"$ZodCheckLengthEquals\",(e,t)=>{var r;L.init(e,t),(r=e._zod.def).when??(r.when=(n)=>{let o=n.value;return!nr(o)&&o.length!==void 0}),e._zod.onattach.push((n)=>{let o=n._zod.bag;o.minimum=t.length,o.maximum=t.length,o.length=t.length}),e._zod.check=(n)=>{let o=n.value,s=o.length;if(s===t.length)return;let i=ir(o),c=s>t.length;n.issues.push({origin:i,...c?{code:\"too_big\",maximum:t.length}:{code:\"too_small\",minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),ur=d(\"$ZodCheckStringFormat\",(e,t)=>{var r,n;if(L.init(e,t),e._zod.onattach.push((o)=>{let s=o._zod.bag;if(s.format=t.format,t.pattern)s.patterns??(s.patterns=new Set),s.patterns.add(t.pattern)}),t.pattern)(r=e._zod).check??(r.check=(o)=>{if(t.pattern.lastIndex=0,t.pattern.test(o.value))return;o.issues.push({origin:\"string\",code:\"invalid_format\",format:t.format,input:o.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})});else(n=e._zod).check??(n.check=()=>{})}),Pa=d(\"$ZodCheckRegex\",(e,t)=>{ur.init(e,t),e._zod.check=(r)=>{if(t.pattern.lastIndex=0,t.pattern.test(r.value))return;r.issues.push({origin:\"string\",code:\"invalid_format\",format:\"regex\",input:r.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),Ca=d(\"$ZodCheckLowerCase\",(e,t)=>{t.pattern??(t.pattern=$a),ur.init(e,t)}),Na=d(\"$ZodCheckUpperCase\",(e,t)=>{t.pattern??(t.pattern=Sa),ur.init(e,t)}),Ua=d(\"$ZodCheckIncludes\",(e,t)=>{L.init(e,t);let r=Se(t.includes),n=new RegExp(typeof t.position===\"number\"?`^.{${t.position}}${r}`:r);t.pattern=n,e._zod.onattach.push((o)=>{let s=o._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(n)}),e._zod.check=(o)=>{if(o.value.includes(t.includes,t.position))return;o.issues.push({origin:\"string\",code:\"invalid_format\",format:\"includes\",includes:t.includes,input:o.value,inst:e,continue:!t.abort})}}),Da=d(\"$ZodCheckStartsWith\",(e,t)=>{L.init(e,t);let r=new RegExp(`^${Se(t.prefix)}.*`);t.pattern??(t.pattern=r),e._zod.onattach.push((n)=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),e._zod.check=(n)=>{if(n.value.startsWith(t.prefix))return;n.issues.push({origin:\"string\",code:\"invalid_format\",format:\"starts_with\",prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),Ra=d(\"$ZodCheckEndsWith\",(e,t)=>{L.init(e,t);let r=new RegExp(`.*${Se(t.suffix)}$`);t.pattern??(t.pattern=r),e._zod.onattach.push((n)=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),e._zod.check=(n)=>{if(n.value.endsWith(t.suffix))return;n.issues.push({origin:\"string\",code:\"invalid_format\",format:\"ends_with\",suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}});var ja=d(\"$ZodCheckOverwrite\",(e,t)=>{L.init(e,t),e._zod.check=(r)=>{r.value=t.tx(r.value)}});class rs{constructor(e=[]){if(this.content=[],this.indent=0,this)this.args=e}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e===\"function\"){e(this,{execution:\"sync\"}),e(this,{execution:\"async\"});return}let r=e.split(`\n`).filter((s)=>s),n=Math.min(...r.map((s)=>s.length-s.trimStart().length)),o=r.map((s)=>s.slice(n)).map((s)=>\" \".repeat(this.indent*2)+s);for(let s of o)this.content.push(s)}compile(){let e=Function,t=this?.args,n=[...(this?.content??[\"\"]).map((o)=>` ${o}`)];return new e(...t,n.join(`\n`))}}var Ba={major:4,minor:4,patch:3};var T=d(\"$ZodType\",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Ba;let n=[...e._zod.def.checks??[]];if(e._zod.traits.has(\"$ZodCheck\"))n.unshift(e);for(let o of n)for(let s of o._zod.onattach)s(e);if(n.length===0)(r=e._zod).deferred??(r.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let o=(i,c,a)=>{let l=Ze(i),u;for(let h of c){if(h._zod.def.when){if(Ho(i))continue;if(!h._zod.def.when(i))continue}else if(l)continue;let p=i.issues.length,f=h._zod.check(i);if(f instanceof Promise&&a?.async===!1)throw new ve;if(u||f instanceof Promise)u=(u??Promise.resolve()).then(async()=>{if(await f,i.issues.length===p)return;if(!l)l=Ze(i,p)});else{if(i.issues.length===p)continue;if(!l)l=Ze(i,p)}}if(u)return u.then(()=>i);return i},s=(i,c,a)=>{if(Ze(i))return i.aborted=!0,i;let l=o(c,n,a);if(l instanceof Promise){if(a.async===!1)throw new ve;return l.then((u)=>e._zod.parse(u,a))}return e._zod.parse(l,a)};e._zod.run=(i,c)=>{if(c.skipChecks)return e._zod.parse(i,c);if(c.direction===\"backward\"){let l=e._zod.parse({value:i.value,issues:[]},{...c,skipChecks:!0});if(l instanceof Promise)return l.then((u)=>s(u,i,c));return s(l,i,c)}let a=e._zod.parse(i,c);if(a instanceof Promise){if(c.async===!1)throw new ve;return a.then((l)=>o(l,n,c))}return o(a,n,c)}}w(e,\"~standard\",()=>({validate:(o)=>{try{let s=Fc(e,o);return s.success?{value:s.data}:{issues:s.error?.issues}}catch(s){return Jc(e,o).then((i)=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:\"zod\",version:1}))}),bn=d(\"$ZodString\",(e,t)=>{T.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??ka(e._zod.bag),e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=String(r.value)}catch(o){}if(typeof r.value===\"string\")return r;return r.issues.push({expected:\"string\",code:\"invalid_type\",input:r.value,inst:e}),r}}),S=d(\"$ZodStringFormat\",(e,t)=>{ur.init(e,t),bn.init(e,t)}),Ha=d(\"$ZodGUID\",(e,t)=>{t.pattern??(t.pattern=ca),S.init(e,t)}),Ya=d(\"$ZodUUID\",(e,t)=>{if(t.version){let n={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(n===void 0)throw Error(`Invalid UUID version: \"${t.version}\"`);t.pattern??(t.pattern=Xo(n))}else t.pattern??(t.pattern=Xo());S.init(e,t)}),Xa=d(\"$ZodEmail\",(e,t)=>{t.pattern??(t.pattern=aa),S.init(e,t)}),Qa=d(\"$ZodURL\",(e,t)=>{S.init(e,t),e._zod.check=(r)=>{try{let n=r.value.trim();if(!t.normalize&&t.protocol?.source===ma.source){if(!/^https?:\\/\\//i.test(n)){r.issues.push({code:\"invalid_format\",format:\"url\",note:\"Invalid URL format\",input:r.value,inst:e,continue:!t.abort});return}}let o=new URL(n);if(t.hostname){if(t.hostname.lastIndex=0,!t.hostname.test(o.hostname))r.issues.push({code:\"invalid_format\",format:\"url\",note:\"Invalid hostname\",pattern:t.hostname.source,input:r.value,inst:e,continue:!t.abort})}if(t.protocol){if(t.protocol.lastIndex=0,!t.protocol.test(o.protocol.endsWith(\":\")?o.protocol.slice(0,-1):o.protocol))r.issues.push({code:\"invalid_format\",format:\"url\",note:\"Invalid protocol\",pattern:t.protocol.source,input:r.value,inst:e,continue:!t.abort})}if(t.normalize)r.value=o.href;else r.value=n;return}catch(n){r.issues.push({code:\"invalid_format\",format:\"url\",input:r.value,inst:e,continue:!t.abort})}}}),eu=d(\"$ZodEmoji\",(e,t)=>{t.pattern??(t.pattern=ua()),S.init(e,t)}),tu=d(\"$ZodNanoID\",(e,t)=>{t.pattern??(t.pattern=sa),S.init(e,t)}),ru=d(\"$ZodCUID\",(e,t)=>{t.pattern??(t.pattern=ea),S.init(e,t)}),nu=d(\"$ZodCUID2\",(e,t)=>{t.pattern??(t.pattern=ta),S.init(e,t)}),ou=d(\"$ZodULID\",(e,t)=>{t.pattern??(t.pattern=ra),S.init(e,t)}),su=d(\"$ZodXID\",(e,t)=>{t.pattern??(t.pattern=na),S.init(e,t)}),iu=d(\"$ZodKSUID\",(e,t)=>{t.pattern??(t.pattern=oa),S.init(e,t)}),cu=d(\"$ZodISODateTime\",(e,t)=>{t.pattern??(t.pattern=ba(t)),S.init(e,t)}),au=d(\"$ZodISODate\",(e,t)=>{t.pattern??(t.pattern=ya),S.init(e,t)}),uu=d(\"$ZodISOTime\",(e,t)=>{t.pattern??(t.pattern=wa(t)),S.init(e,t)}),lu=d(\"$ZodISODuration\",(e,t)=>{t.pattern??(t.pattern=ia),S.init(e,t)}),pu=d(\"$ZodIPv4\",(e,t)=>{t.pattern??(t.pattern=la),S.init(e,t),e._zod.bag.format=\"ipv4\"}),hu=d(\"$ZodIPv6\",(e,t)=>{t.pattern??(t.pattern=pa),S.init(e,t),e._zod.bag.format=\"ipv6\",e._zod.check=(r)=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:\"invalid_format\",format:\"ipv6\",input:r.value,inst:e,continue:!t.abort})}}});var du=d(\"$ZodCIDRv4\",(e,t)=>{t.pattern??(t.pattern=ha),S.init(e,t)}),fu=d(\"$ZodCIDRv6\",(e,t)=>{t.pattern??(t.pattern=da),S.init(e,t),e._zod.check=(r)=>{let n=r.value.split(\"/\");try{if(n.length!==2)throw Error();let[o,s]=n;if(!s)throw Error();let i=Number(s);if(`${i}`!==s)throw Error();if(i<0||i>128)throw Error();new URL(`http://[${o}]`)}catch{r.issues.push({code:\"invalid_format\",format:\"cidrv6\",input:r.value,inst:e,continue:!t.abort})}}});function mu(e){if(e===\"\")return!0;if(/\\s/.test(e))return!1;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}var gu=d(\"$ZodBase64\",(e,t)=>{t.pattern??(t.pattern=fa),S.init(e,t),e._zod.bag.contentEncoding=\"base64\",e._zod.check=(r)=>{if(mu(r.value))return;r.issues.push({code:\"invalid_format\",format:\"base64\",input:r.value,inst:e,continue:!t.abort})}});function Rf(e){if(!Qo.test(e))return!1;let t=e.replace(/[-_]/g,(n)=>n===\"-\"?\"+\":\"/\"),r=t.padEnd(Math.ceil(t.length/4)*4,\"=\");return mu(r)}var xu=d(\"$ZodBase64URL\",(e,t)=>{t.pattern??(t.pattern=Qo),S.init(e,t),e._zod.bag.contentEncoding=\"base64url\",e._zod.check=(r)=>{if(Rf(r.value))return;r.issues.push({code:\"invalid_format\",format:\"base64url\",input:r.value,inst:e,continue:!t.abort})}}),yu=d(\"$ZodE164\",(e,t)=>{t.pattern??(t.pattern=ga),S.init(e,t)});function jf(e,t=null){try{let r=e.split(\".\");if(r.length!==3)return!1;let[n]=r;if(!n)return!1;let o=JSON.parse(atob(n));if(\"typ\"in o&&o?.typ!==\"JWT\")return!1;if(!o.alg)return!1;if(t&&(!(\"alg\"in o)||o.alg!==t))return!1;return!0}catch{return!1}}var _u=d(\"$ZodJWT\",(e,t)=>{S.init(e,t),e._zod.check=(r)=>{if(jf(r.value,t.alg))return;r.issues.push({code:\"invalid_format\",format:\"jwt\",input:r.value,inst:e,continue:!t.abort})}});var os=d(\"$ZodNumber\",(e,t)=>{T.init(e,t),e._zod.pattern=e._zod.bag.pattern??za,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=Number(r.value)}catch(i){}let o=r.value;if(typeof o===\"number\"&&!Number.isNaN(o)&&Number.isFinite(o))return r;let s=typeof o===\"number\"?Number.isNaN(o)?\"NaN\":!Number.isFinite(o)?\"Infinity\":void 0:void 0;return r.issues.push({expected:\"number\",code:\"invalid_type\",input:o,inst:e,...s?{received:s}:{}}),r}}),wu=d(\"$ZodNumberFormat\",(e,t)=>{Ta.init(e,t),os.init(e,t)});var bu=d(\"$ZodUnknown\",(e,t)=>{T.init(e,t),e._zod.parse=(r)=>r}),ku=d(\"$ZodNever\",(e,t)=>{T.init(e,t),e._zod.parse=(r,n)=>(r.issues.push({expected:\"never\",code:\"invalid_type\",input:r.value,inst:e}),r)});function Ma(e,t,r){if(e.issues.length)t.issues.push(...sr(r,e.issues));t.value[r]=e.value}var vu=d(\"$ZodArray\",(e,t)=>{T.init(e,t),e._zod.parse=(r,n)=>{let o=r.value;if(!Array.isArray(o))return r.issues.push({expected:\"array\",code:\"invalid_type\",input:o,inst:e}),r;r.value=Array(o.length);let s=[];for(let i=0;i<o.length;i++){let c=o[i],a=t.element._zod.run({value:c,issues:[]},n);if(a instanceof Promise)s.push(a.then((l)=>Ma(l,r,i)));else Ma(a,r,i)}if(s.length)return Promise.all(s).then(()=>r);return r}});function wn(e,t,r,n,o,s){let i=r in n;if(e.issues.length){if(o&&s&&!i)return;t.issues.push(...sr(r,e.issues))}if(!i&&!o){if(!e.issues.length)t.issues.push({code:\"invalid_type\",expected:\"nonoptional\",input:void 0,path:[r]});return}if(e.value===void 0){if(i)t.value[r]=void 0}else t.value[r]=e.value}function zu(e){let t=Object.keys(e.shape);for(let n of t)if(!e.shape?.[n]?._zod?.traits?.has(\"$ZodType\"))throw Error(`Invalid element at key \"${n}\": expected a Zod schema`);let r=Wo(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(r)}}function $u(e,t,r,n,o,s){let i=[],c=o.keySet,a=o.catchall._zod,l=a.def.type,u=a.optin===\"optional\",h=a.optout===\"optional\";for(let p in t){if(p===\"__proto__\")continue;if(c.has(p))continue;if(l===\"never\"){i.push(p);continue}let f=a.run({value:t[p],issues:[]},n);if(f instanceof Promise)e.push(f.then((m)=>wn(m,r,p,t,u,h)));else wn(f,r,p,t,u,h)}if(i.length)r.issues.push({code:\"unrecognized_keys\",keys:i,input:t,inst:s});if(!e.length)return r;return Promise.all(e).then(()=>r)}var Lf=d(\"$ZodObject\",(e,t)=>{if(T.init(e,t),!Object.getOwnPropertyDescriptor(t,\"shape\")?.get){let c=t.shape;Object.defineProperty(t,\"shape\",{get:()=>{let a={...c};return Object.defineProperty(t,\"shape\",{value:a}),a}})}let n=wt(()=>zu(t));w(e._zod,\"propValues\",()=>{let c=t.shape,a={};for(let l in c){let u=c[l]._zod;if(u.values){a[l]??(a[l]=new Set);for(let h of u.values)a[l].add(h)}}return a});let o=Ge,s=t.catchall,i;e._zod.parse=(c,a)=>{i??(i=n.value);let l=c.value;if(!o(l))return c.issues.push({expected:\"object\",code:\"invalid_type\",input:l,inst:e}),c;c.value={};let u=[],h=i.shape;for(let p of i.keys){let f=h[p],m=f._zod.optin===\"optional\",k=f._zod.optout===\"optional\",z=f._zod.run({value:l[p],issues:[]},a);if(z instanceof Promise)u.push(z.then((Rn)=>wn(Rn,c,p,l,m,k)));else wn(z,c,p,l,m,k)}if(!s)return u.length?Promise.all(u).then(()=>c):c;return $u(u,l,c,a,n.value,e)}}),Su=d(\"$ZodObjectJIT\",(e,t)=>{Lf.init(e,t);let r=e._zod.parse,n=wt(()=>zu(t)),o=(p)=>{let f=new rs([\"shape\",\"payload\",\"ctx\"]),m=n.value,k=(ae)=>{let I=dn(ae);return`shape[${I}]._zod.run({ value: input[${I}], issues: [] }, ctx)`};f.write(\"const input = payload.value;\");let z=Object.create(null),Rn=0;for(let ae of m.keys)z[ae]=`key_${Rn++}`;f.write(\"const newResult = {};\");for(let ae of m.keys){let I=z[ae],j=dn(ae),Is=p[ae],Ts=Is?._zod?.optin===\"optional\",Ip=Is?._zod?.optout===\"optional\";if(f.write(`const ${I} = ${k(ae)};`),Ts&&Ip)f.write(`\n if (${I}.issues.length) {\n if (${j} in input) {\n payload.issues = payload.issues.concat(${I}.issues.map(iss => ({\n ...iss,\n path: iss.path ? [${j}, ...iss.path] : [${j}]\n })));\n }\n }\n \n if (${I}.value === undefined) {\n if (${j} in input) {\n newResult[${j}] = undefined;\n }\n } else {\n newResult[${j}] = ${I}.value;\n }\n \n `);else if(!Ts)f.write(`\n const ${I}_present = ${j} in input;\n if (${I}.issues.length) {\n payload.issues = payload.issues.concat(${I}.issues.map(iss => ({\n ...iss,\n path: iss.path ? [${j}, ...iss.path] : [${j}]\n })));\n }\n if (!${I}_present && !${I}.issues.length) {\n payload.issues.push({\n code: \"invalid_type\",\n expected: \"nonoptional\",\n input: undefined,\n path: [${j}]\n });\n }\n\n if (${I}_present) {\n if (${I}.value === undefined) {\n newResult[${j}] = undefined;\n } else {\n newResult[${j}] = ${I}.value;\n }\n }\n\n `);else f.write(`\n if (${I}.issues.length) {\n payload.issues = payload.issues.concat(${I}.issues.map(iss => ({\n ...iss,\n path: iss.path ? [${j}, ...iss.path] : [${j}]\n })));\n }\n \n if (${I}.value === undefined) {\n if (${j} in input) {\n newResult[${j}] = undefined;\n }\n } else {\n newResult[${j}] = ${I}.value;\n }\n \n `)}f.write(\"payload.value = newResult;\"),f.write(\"return payload;\");let Ep=f.compile();return(ae,I)=>Ep(p,ae,I)},s,i=Ge,c=!yt.jitless,l=c&&qo.value,u=t.catchall,h;e._zod.parse=(p,f)=>{h??(h=n.value);let m=p.value;if(!i(m))return p.issues.push({expected:\"object\",code:\"invalid_type\",input:m,inst:e}),p;if(c&&l&&f?.async===!1&&f.jitless!==!0){if(!s)s=o(t.shape);if(p=s(p,f),!u)return p;return $u([],m,p,f,h,e)}return r(p,f)}});function Va(e,t,r,n){for(let s of e)if(s.issues.length===0)return t.value=s.value,t;let o=e.filter((s)=>!Ze(s));if(o.length===1)return t.value=o[0].value,o[0];return t.issues.push({code:\"invalid_union\",input:t.value,inst:r,errors:e.map((s)=>s.issues.map((i)=>xe(i,n,ze())))}),t}var ss=d(\"$ZodUnion\",(e,t)=>{T.init(e,t),w(e._zod,\"optin\",()=>t.options.some((n)=>n._zod.optin===\"optional\")?\"optional\":void 0),w(e._zod,\"optout\",()=>t.options.some((n)=>n._zod.optout===\"optional\")?\"optional\":void 0),w(e._zod,\"values\",()=>{if(t.options.every((n)=>n._zod.values))return new Set(t.options.flatMap((n)=>Array.from(n._zod.values)));return}),w(e._zod,\"pattern\",()=>{if(t.options.every((n)=>n._zod.pattern)){let n=t.options.map((o)=>o._zod.pattern);return new RegExp(`^(${n.map((o)=>or(o.source)).join(\"|\")})$`)}return});let r=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(n,o)=>{if(r)return r(n,o);let s=!1,i=[];for(let c of t.options){let a=c._zod.run({value:n.value,issues:[]},o);if(a instanceof Promise)i.push(a),s=!0;else{if(a.issues.length===0)return a;i.push(a)}}if(!s)return Va(i,n,e,o);return Promise.all(i).then((c)=>Va(c,n,e,o))}});var Eu=d(\"$ZodDiscriminatedUnion\",(e,t)=>{t.inclusive=!1,ss.init(e,t);let r=e._zod.parse;w(e._zod,\"propValues\",()=>{let o={};for(let s of t.options){let i=s._zod.propValues;if(!i||Object.keys(i).length===0)throw Error(`Invalid discriminated union option at index \"${t.options.indexOf(s)}\"`);for(let[c,a]of Object.entries(i)){if(!o[c])o[c]=new Set;for(let l of a)o[c].add(l)}}return o});let n=wt(()=>{let o=t.options,s=new Map;for(let i of o){let c=i._zod.propValues?.[t.discriminator];if(!c||c.size===0)throw Error(`Invalid discriminated union option at index \"${t.options.indexOf(i)}\"`);for(let a of c){if(s.has(a))throw Error(`Duplicate discriminator value \"${String(a)}\"`);s.set(a,i)}}return s});e._zod.parse=(o,s)=>{let i=o.value;if(!Ge(i))return o.issues.push({code:\"invalid_type\",expected:\"object\",input:i,inst:e}),o;let c=n.value.get(i?.[t.discriminator]);if(c)return c._zod.run(o,s);if(t.unionFallback||s.direction===\"backward\")return r(o,s);return o.issues.push({code:\"invalid_union\",errors:[],note:\"No matching discriminator\",discriminator:t.discriminator,options:Array.from(n.value.keys()),input:i,path:[t.discriminator],inst:e}),o}}),Iu=d(\"$ZodIntersection\",(e,t)=>{T.init(e,t),e._zod.parse=(r,n)=>{let o=r.value,s=t.left._zod.run({value:o,issues:[]},n),i=t.right._zod.run({value:o,issues:[]},n);if(s instanceof Promise||i instanceof Promise)return Promise.all([s,i]).then(([a,l])=>Fa(r,a,l));return Fa(r,s,i)}});function ns(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e===+t)return{valid:!0,data:e};if(We(e)&&We(t)){let r=Object.keys(t),n=Object.keys(e).filter((s)=>r.indexOf(s)!==-1),o={...e,...t};for(let s of n){let i=ns(e[s],t[s]);if(!i.valid)return{valid:!1,mergeErrorPath:[s,...i.mergeErrorPath]};o[s]=i.data}return{valid:!0,data:o}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let r=[];for(let n=0;n<e.length;n++){let o=e[n],s=t[n],i=ns(o,s);if(!i.valid)return{valid:!1,mergeErrorPath:[n,...i.mergeErrorPath]};r.push(i.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function Fa(e,t,r){let n=new Map,o;for(let c of t.issues)if(c.code===\"unrecognized_keys\"){o??(o=c);for(let a of c.keys){if(!n.has(a))n.set(a,{});n.get(a).l=!0}}else e.issues.push(c);for(let c of r.issues)if(c.code===\"unrecognized_keys\")for(let a of c.keys){if(!n.has(a))n.set(a,{});n.get(a).r=!0}else e.issues.push(c);let s=[...n].filter(([,c])=>c.l&&c.r).map(([c])=>c);if(s.length&&o)e.issues.push({...o,keys:s});if(Ze(e))return e;let i=ns(t.value,r.value);if(!i.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(i.mergeErrorPath)}`);return e.value=i.data,e}var Tu=d(\"$ZodEnum\",(e,t)=>{T.init(e,t);let r=rr(t.entries),n=new Set(r);e._zod.values=n,e._zod.pattern=new RegExp(`^(${r.filter((o)=>Go.has(typeof o)).map((o)=>typeof o===\"string\"?Se(o):o.toString()).join(\"|\")})$`),e._zod.parse=(o,s)=>{let i=o.value;if(n.has(i))return o;return o.issues.push({code:\"invalid_value\",values:r,input:i,inst:e}),o}}),Au=d(\"$ZodLiteral\",(e,t)=>{if(T.init(e,t),t.values.length===0)throw Error(\"Cannot create literal schema with no valid values\");let r=new Set(t.values);e._zod.values=r,e._zod.pattern=new RegExp(`^(${t.values.map((n)=>typeof n===\"string\"?Se(n):n?Se(n.toString()):String(n)).join(\"|\")})$`),e._zod.parse=(n,o)=>{let s=n.value;if(r.has(s))return n;return n.issues.push({code:\"invalid_value\",values:t.values,input:s,inst:e}),n}});var Ou=d(\"$ZodTransform\",(e,t)=>{T.init(e,t),e._zod.optin=\"optional\",e._zod.parse=(r,n)=>{if(n.direction===\"backward\")throw new er(e.constructor.name);let o=t.transform(r.value,r);if(n.async)return(o instanceof Promise?o:Promise.resolve(o)).then((i)=>(r.value=i,r.fallback=!0,r));if(o instanceof Promise)throw new ve;return r.value=o,r.fallback=!0,r}});function Ja(e,t){if(t===void 0&&(e.issues.length||e.fallback))return{issues:[],value:void 0};return e}var is=d(\"$ZodOptional\",(e,t)=>{T.init(e,t),e._zod.optin=\"optional\",e._zod.optout=\"optional\",w(e._zod,\"values\",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),w(e._zod,\"pattern\",()=>{let r=t.innerType._zod.pattern;return r?new RegExp(`^(${or(r.source)})?$`):void 0}),e._zod.parse=(r,n)=>{if(t.innerType._zod.optin===\"optional\"){let o=r.value,s=t.innerType._zod.run(r,n);if(s instanceof Promise)return s.then((i)=>Ja(i,o));return Ja(s,o)}if(r.value===void 0)return r;return t.innerType._zod.run(r,n)}}),Zu=d(\"$ZodExactOptional\",(e,t)=>{is.init(e,t),w(e._zod,\"values\",()=>t.innerType._zod.values),w(e._zod,\"pattern\",()=>t.innerType._zod.pattern),e._zod.parse=(r,n)=>t.innerType._zod.run(r,n)}),Pu=d(\"$ZodNullable\",(e,t)=>{T.init(e,t),w(e._zod,\"optin\",()=>t.innerType._zod.optin),w(e._zod,\"optout\",()=>t.innerType._zod.optout),w(e._zod,\"pattern\",()=>{let r=t.innerType._zod.pattern;return r?new RegExp(`^(${or(r.source)}|null)$`):void 0}),w(e._zod,\"values\",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(r,n)=>{if(r.value===null)return r;return t.innerType._zod.run(r,n)}}),Cu=d(\"$ZodDefault\",(e,t)=>{T.init(e,t),e._zod.optin=\"optional\",w(e._zod,\"values\",()=>t.innerType._zod.values),e._zod.parse=(r,n)=>{if(n.direction===\"backward\")return t.innerType._zod.run(r,n);if(r.value===void 0)return r.value=t.defaultValue,r;let o=t.innerType._zod.run(r,n);if(o instanceof Promise)return o.then((s)=>qa(s,t));return qa(o,t)}});function qa(e,t){if(e.value===void 0)e.value=t.defaultValue;return e}var Nu=d(\"$ZodPrefault\",(e,t)=>{T.init(e,t),e._zod.optin=\"optional\",w(e._zod,\"values\",()=>t.innerType._zod.values),e._zod.parse=(r,n)=>{if(n.direction===\"backward\")return t.innerType._zod.run(r,n);if(r.value===void 0)r.value=t.defaultValue;return t.innerType._zod.run(r,n)}}),Uu=d(\"$ZodNonOptional\",(e,t)=>{T.init(e,t),w(e._zod,\"values\",()=>{let r=t.innerType._zod.values;return r?new Set([...r].filter((n)=>n!==void 0)):void 0}),e._zod.parse=(r,n)=>{let o=t.innerType._zod.run(r,n);if(o instanceof Promise)return o.then((s)=>Ga(s,e));return Ga(o,e)}});function Ga(e,t){if(!e.issues.length&&e.value===void 0)e.issues.push({code:\"invalid_type\",expected:\"nonoptional\",input:e.value,inst:t});return e}var Du=d(\"$ZodCatch\",(e,t)=>{T.init(e,t),e._zod.optin=\"optional\",w(e._zod,\"optout\",()=>t.innerType._zod.optout),w(e._zod,\"values\",()=>t.innerType._zod.values),e._zod.parse=(r,n)=>{if(n.direction===\"backward\")return t.innerType._zod.run(r,n);let o=t.innerType._zod.run(r,n);if(o instanceof Promise)return o.then((s)=>{if(r.value=s.value,s.issues.length)r.value=t.catchValue({...r,error:{issues:s.issues.map((i)=>xe(i,n,ze()))},input:r.value}),r.issues=[],r.fallback=!0;return r});if(r.value=o.value,o.issues.length)r.value=t.catchValue({...r,error:{issues:o.issues.map((s)=>xe(s,n,ze()))},input:r.value}),r.issues=[],r.fallback=!0;return r}});var Ru=d(\"$ZodPipe\",(e,t)=>{T.init(e,t),w(e._zod,\"values\",()=>t.in._zod.values),w(e._zod,\"optin\",()=>t.in._zod.optin),w(e._zod,\"optout\",()=>t.out._zod.optout),w(e._zod,\"propValues\",()=>t.in._zod.propValues),e._zod.parse=(r,n)=>{if(n.direction===\"backward\"){let s=t.out._zod.run(r,n);if(s instanceof Promise)return s.then((i)=>_n(i,t.in,n));return _n(s,t.in,n)}let o=t.in._zod.run(r,n);if(o instanceof Promise)return o.then((s)=>_n(s,t.out,n));return _n(o,t.out,n)}});function _n(e,t,r){if(e.issues.length)return e.aborted=!0,e;return t._zod.run({value:e.value,issues:e.issues,fallback:e.fallback},r)}var ju=d(\"$ZodReadonly\",(e,t)=>{T.init(e,t),w(e._zod,\"propValues\",()=>t.innerType._zod.propValues),w(e._zod,\"values\",()=>t.innerType._zod.values),w(e._zod,\"optin\",()=>t.innerType?._zod?.optin),w(e._zod,\"optout\",()=>t.innerType?._zod?.optout),e._zod.parse=(r,n)=>{if(n.direction===\"backward\")return t.innerType._zod.run(r,n);let o=t.innerType._zod.run(r,n);if(o instanceof Promise)return o.then(Wa);return Wa(o)}});function Wa(e){return e.value=Object.freeze(e.value),e}var Lu=d(\"$ZodCustom\",(e,t)=>{L.init(e,t),T.init(e,t),e._zod.parse=(r,n)=>r,e._zod.check=(r)=>{let n=r.value,o=t.fn(n);if(o instanceof Promise)return o.then((s)=>Ka(s,r,n,e));Ka(o,r,n,e);return}});function Ka(e,t,r,n){if(!e){let o={code:\"custom\",input:r,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};if(n._zod.def.params)o.params=n._zod.def.params;t.issues.push(bt(o))}}var Bu,mx=Symbol(\"ZodOutput\"),gx=Symbol(\"ZodInput\");class Mu{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){let r=t[0];if(this._map.set(e,r),r&&typeof r===\"object\"&&\"id\"in r)this._idmap.set(r.id,e);return this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){let t=this._map.get(e);if(t&&typeof t===\"object\"&&\"id\"in t)this._idmap.delete(t.id);return this._map.delete(e),this}get(e){let t=e._zod.parent;if(t){let r={...this.get(t)??{}};delete r.id;let n={...r,...this._map.get(e)};return Object.keys(n).length?n:void 0}return this._map.get(e)}has(e){return this._map.has(e)}}function Bf(){return new Mu}(Bu=globalThis).__zod_globalRegistry??(Bu.__zod_globalRegistry=Bf());var Ke=globalThis.__zod_globalRegistry;function Vu(e,t){return new e({type:\"string\",...g(t)})}function Fu(e,t){return new e({type:\"string\",format:\"email\",check:\"string_format\",abort:!1,...g(t)})}function cs(e,t){return new e({type:\"string\",format:\"guid\",check:\"string_format\",abort:!1,...g(t)})}function Ju(e,t){return new e({type:\"string\",format:\"uuid\",check:\"string_format\",abort:!1,...g(t)})}function qu(e,t){return new e({type:\"string\",format:\"uuid\",check:\"string_format\",abort:!1,version:\"v4\",...g(t)})}function Gu(e,t){return new e({type:\"string\",format:\"uuid\",check:\"string_format\",abort:!1,version:\"v6\",...g(t)})}function Wu(e,t){return new e({type:\"string\",format:\"uuid\",check:\"string_format\",abort:!1,version:\"v7\",...g(t)})}function Ku(e,t){return new e({type:\"string\",format:\"url\",check:\"string_format\",abort:!1,...g(t)})}function Hu(e,t){return new e({type:\"string\",format:\"emoji\",check:\"string_format\",abort:!1,...g(t)})}function Yu(e,t){return new e({type:\"string\",format:\"nanoid\",check:\"string_format\",abort:!1,...g(t)})}function Xu(e,t){return new e({type:\"string\",format:\"cuid\",check:\"string_format\",abort:!1,...g(t)})}function Qu(e,t){return new e({type:\"string\",format:\"cuid2\",check:\"string_format\",abort:!1,...g(t)})}function el(e,t){return new e({type:\"string\",format:\"ulid\",check:\"string_format\",abort:!1,...g(t)})}function tl(e,t){return new e({type:\"string\",format:\"xid\",check:\"string_format\",abort:!1,...g(t)})}function rl(e,t){return new e({type:\"string\",format:\"ksuid\",check:\"string_format\",abort:!1,...g(t)})}function nl(e,t){return new e({type:\"string\",format:\"ipv4\",check:\"string_format\",abort:!1,...g(t)})}function ol(e,t){return new e({type:\"string\",format:\"ipv6\",check:\"string_format\",abort:!1,...g(t)})}function sl(e,t){return new e({type:\"string\",format:\"cidrv4\",check:\"string_format\",abort:!1,...g(t)})}function il(e,t){return new e({type:\"string\",format:\"cidrv6\",check:\"string_format\",abort:!1,...g(t)})}function cl(e,t){return new e({type:\"string\",format:\"base64\",check:\"string_format\",abort:!1,...g(t)})}function al(e,t){return new e({type:\"string\",format:\"base64url\",check:\"string_format\",abort:!1,...g(t)})}function ul(e,t){return new e({type:\"string\",format:\"e164\",check:\"string_format\",abort:!1,...g(t)})}function ll(e,t){return new e({type:\"string\",format:\"jwt\",check:\"string_format\",abort:!1,...g(t)})}function pl(e,t){return new e({type:\"string\",format:\"datetime\",check:\"string_format\",offset:!1,local:!1,precision:null,...g(t)})}function hl(e,t){return new e({type:\"string\",format:\"date\",check:\"string_format\",...g(t)})}function dl(e,t){return new e({type:\"string\",format:\"time\",check:\"string_format\",precision:null,...g(t)})}function fl(e,t){return new e({type:\"string\",format:\"duration\",check:\"string_format\",...g(t)})}function ml(e,t){return new e({type:\"number\",checks:[],...g(t)})}function gl(e,t){return new e({type:\"number\",check:\"number_format\",abort:!1,format:\"safeint\",...g(t)})}function xl(e){return new e({type:\"unknown\"})}function yl(e,t){return new e({type:\"never\",...g(t)})}function kn(e,t){return new es({check:\"less_than\",...g(t),value:e,inclusive:!1})}function lr(e,t){return new es({check:\"less_than\",...g(t),value:e,inclusive:!0})}function vn(e,t){return new ts({check:\"greater_than\",...g(t),value:e,inclusive:!1})}function pr(e,t){return new ts({check:\"greater_than\",...g(t),value:e,inclusive:!0})}function zn(e,t){return new Ia({check:\"multiple_of\",...g(t),value:e})}function $n(e,t){return new Aa({check:\"max_length\",...g(t),maximum:e})}function kt(e,t){return new Oa({check:\"min_length\",...g(t),minimum:e})}function Sn(e,t){return new Za({check:\"length_equals\",...g(t),length:e})}function as(e,t){return new Pa({check:\"string_format\",format:\"regex\",...g(t),pattern:e})}function us(e){return new Ca({check:\"string_format\",format:\"lowercase\",...g(e)})}function ls(e){return new Na({check:\"string_format\",format:\"uppercase\",...g(e)})}function ps(e,t){return new Ua({check:\"string_format\",format:\"includes\",...g(t),includes:e})}function hs(e,t){return new Da({check:\"string_format\",format:\"starts_with\",...g(t),prefix:e})}function ds(e,t){return new Ra({check:\"string_format\",format:\"ends_with\",...g(t),suffix:e})}function Pe(e){return new ja({check:\"overwrite\",tx:e})}function fs(e){return Pe((t)=>t.normalize(e))}function ms(){return Pe((e)=>e.trim())}function gs(){return Pe((e)=>e.toLowerCase())}function xs(){return Pe((e)=>e.toUpperCase())}function ys(){return Pe((e)=>Jo(e))}function _l(e,t,r){return new e({type:\"array\",element:t,...g(r)})}function wl(e,t,r){return new e({type:\"custom\",check:\"custom\",fn:t,...g(r)})}function bl(e,t){let r=Mf((n)=>(n.addIssue=(o)=>{if(typeof o===\"string\")n.issues.push(bt(o,n.value,r._zod.def));else{let s=o;if(s.fatal)s.continue=!1;s.code??(s.code=\"custom\"),s.input??(s.input=n.value),s.inst??(s.inst=r),s.continue??(s.continue=!r._zod.def.abort),n.issues.push(bt(s))}},e(n.value,n)),t);return r}function Mf(e,t){let r=new L({check:\"custom\",...g(t)});return r._zod.check=e,r}function _s(e){let t=e?.target??\"draft-2020-12\";if(t===\"draft-4\")t=\"draft-04\";if(t===\"draft-7\")t=\"draft-07\";return{processors:e.processors??{},metadataRegistry:e?.metadata??Ke,target:t,unrepresentable:e?.unrepresentable??\"throw\",override:e?.override??(()=>{}),io:e?.io??\"output\",counter:0,seen:new Map,cycles:e?.cycles??\"ref\",reused:e?.reused??\"inline\",external:e?.external??void 0}}function R(e,t,r={path:[],schemaPath:[]}){var n;let o=e._zod.def,s=t.seen.get(e);if(s){if(s.count++,r.schemaPath.includes(e))s.cycle=r.path;return s.schema}let i={schema:{},count:1,cycle:void 0,path:r.path};t.seen.set(e,i);let c=e._zod.toJSONSchema?.();if(c)i.schema=c;else{let u={...r,schemaPath:[...r.schemaPath,e],path:r.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,i.schema,u);else{let p=i.schema,f=t.processors[o.type];if(!f)throw Error(`[toJSONSchema]: Non-representable type encountered: ${o.type}`);f(e,t,p,u)}let h=e._zod.parent;if(h){if(!i.ref)i.ref=h;R(h,t,u),t.seen.get(h).isParent=!0}}let a=t.metadataRegistry.get(e);if(a)Object.assign(i.schema,a);if(t.io===\"input\"&&W(e))delete i.schema.examples,delete i.schema.default;if(t.io===\"input\"&&\"_prefault\"in i.schema)(n=i.schema).default??(n.default=i.schema._prefault);return delete i.schema._prefault,t.seen.get(e).schema}function ws(e,t){let r=e.seen.get(t);if(!r)throw Error(\"Unprocessed schema. This is a bug in Zod.\");let n=new Map;for(let i of e.seen.entries()){let c=e.metadataRegistry.get(i[0])?.id;if(c){let a=n.get(c);if(a&&a!==i[0])throw Error(`Duplicate schema id \"${c}\" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);n.set(c,i[0])}}let o=(i)=>{let c=e.target===\"draft-2020-12\"?\"$defs\":\"definitions\";if(e.external){let h=e.external.registry.get(i[0])?.id,p=e.external.uri??((m)=>m);if(h)return{ref:p(h)};let f=i[1].defId??i[1].schema.id??`schema${e.counter++}`;return i[1].defId=f,{defId:f,ref:`${p(\"__shared\")}#/${c}/${f}`}}if(i[1]===r)return{ref:\"#\"};let l=`${\"#\"}/${c}/`,u=i[1].schema.id??`__schema${e.counter++}`;return{defId:u,ref:l+u}},s=(i)=>{if(i[1].schema.$ref)return;let c=i[1],{ref:a,defId:l}=o(i);if(c.def={...c.schema},l)c.defId=l;let u=c.schema;for(let h in u)delete u[h];u.$ref=a};if(e.cycles===\"throw\")for(let i of e.seen.entries()){let c=i[1];if(c.cycle)throw Error(`Cycle detected: #/${c.cycle?.join(\"/\")}/<root>\n\nSet the \\`cycles\\` parameter to \\`\"ref\"\\` to resolve cyclical schemas with defs.`)}for(let i of e.seen.entries()){let c=i[1];if(t===i[0]){s(i);continue}if(e.external){let l=e.external.registry.get(i[0])?.id;if(t!==i[0]&&l){s(i);continue}}if(e.metadataRegistry.get(i[0])?.id){s(i);continue}if(c.cycle){s(i);continue}if(c.count>1){if(e.reused===\"ref\"){s(i);continue}}}}function bs(e,t){let r=e.seen.get(t);if(!r)throw Error(\"Unprocessed schema. This is a bug in Zod.\");let n=(c)=>{let a=e.seen.get(c);if(a.ref===null)return;let l=a.def??a.schema,u={...l},h=a.ref;if(a.ref=null,h){n(h);let f=e.seen.get(h),m=f.schema;if(m.$ref&&(e.target===\"draft-07\"||e.target===\"draft-04\"||e.target===\"openapi-3.0\"))l.allOf=l.allOf??[],l.allOf.push(m);else Object.assign(l,m);if(Object.assign(l,u),c._zod.parent===h)for(let z in l){if(z===\"$ref\"||z===\"allOf\")continue;if(!(z in u))delete l[z]}if(m.$ref&&f.def)for(let z in l){if(z===\"$ref\"||z===\"allOf\")continue;if(z in f.def&&JSON.stringify(l[z])===JSON.stringify(f.def[z]))delete l[z]}}let p=c._zod.parent;if(p&&p!==h){n(p);let f=e.seen.get(p);if(f?.schema.$ref){if(l.$ref=f.schema.$ref,f.def)for(let m in l){if(m===\"$ref\"||m===\"allOf\")continue;if(m in f.def&&JSON.stringify(l[m])===JSON.stringify(f.def[m]))delete l[m]}}}e.override({zodSchema:c,jsonSchema:l,path:a.path??[]})};for(let c of[...e.seen.entries()].reverse())n(c[0]);let o={};if(e.target===\"draft-2020-12\")o.$schema=\"https://json-schema.org/draft/2020-12/schema\";else if(e.target===\"draft-07\")o.$schema=\"http://json-schema.org/draft-07/schema#\";else if(e.target===\"draft-04\")o.$schema=\"http://json-schema.org/draft-04/schema#\";else if(e.target===\"openapi-3.0\");if(e.external?.uri){let c=e.external.registry.get(t)?.id;if(!c)throw Error(\"Schema is missing an `id` property\");o.$id=e.external.uri(c)}Object.assign(o,r.def??r.schema);let s=e.metadataRegistry.get(t)?.id;if(s!==void 0&&o.id===s)delete o.id;let i=e.external?.defs??{};for(let c of e.seen.entries()){let a=c[1];if(a.def&&a.defId){if(a.def.id===a.defId)delete a.def.id;i[a.defId]=a.def}}if(e.external);else if(Object.keys(i).length>0)if(e.target===\"draft-2020-12\")o.$defs=i;else o.definitions=i;try{let c=JSON.parse(JSON.stringify(o));return Object.defineProperty(c,\"~standard\",{value:{...t[\"~standard\"],jsonSchema:{input:hr(t,\"input\",e.processors),output:hr(t,\"output\",e.processors)}},enumerable:!1,writable:!1}),c}catch(c){throw Error(\"Error converting schema to JSON.\")}}function W(e,t){let r=t??{seen:new Set};if(r.seen.has(e))return!1;r.seen.add(e);let n=e._zod.def;if(n.type===\"transform\")return!0;if(n.type===\"array\")return W(n.element,r);if(n.type===\"set\")return W(n.valueType,r);if(n.type===\"lazy\")return W(n.getter(),r);if(n.type===\"promise\"||n.type===\"optional\"||n.type===\"nonoptional\"||n.type===\"nullable\"||n.type===\"readonly\"||n.type===\"default\"||n.type===\"prefault\")return W(n.innerType,r);if(n.type===\"intersection\")return W(n.left,r)||W(n.right,r);if(n.type===\"record\"||n.type===\"map\")return W(n.keyType,r)||W(n.valueType,r);if(n.type===\"pipe\"){if(e._zod.traits.has(\"$ZodCodec\"))return!0;return W(n.in,r)||W(n.out,r)}if(n.type===\"object\"){for(let o in n.shape)if(W(n.shape[o],r))return!0;return!1}if(n.type===\"union\"){for(let o of n.options)if(W(o,r))return!0;return!1}if(n.type===\"tuple\"){for(let o of n.items)if(W(o,r))return!0;if(n.rest&&W(n.rest,r))return!0;return!1}return!1}var kl=(e,t={})=>(r)=>{let n=_s({...r,processors:t});return R(e,n),ws(n,e),bs(n,e)},hr=(e,t,r={})=>(n)=>{let{libraryOptions:o,target:s}=n??{},i=_s({...o??{},target:s,io:t,processors:r});return R(e,i),ws(i,e),bs(i,e)};var Vf={guid:\"uuid\",url:\"uri\",datetime:\"date-time\",json_string:\"json-string\",regex:\"\"},vl=(e,t,r,n)=>{let o=r;o.type=\"string\";let{minimum:s,maximum:i,format:c,patterns:a,contentEncoding:l}=e._zod.bag;if(typeof s===\"number\")o.minLength=s;if(typeof i===\"number\")o.maxLength=i;if(c){if(o.format=Vf[c]??c,o.format===\"\")delete o.format;if(c===\"time\")delete o.format}if(l)o.contentEncoding=l;if(a&&a.size>0){let u=[...a];if(u.length===1)o.pattern=u[0].source;else if(u.length>1)o.allOf=[...u.map((h)=>({...t.target===\"draft-07\"||t.target===\"draft-04\"||t.target===\"openapi-3.0\"?{type:\"string\"}:{},pattern:h.source}))]}},zl=(e,t,r,n)=>{let o=r,{minimum:s,maximum:i,format:c,multipleOf:a,exclusiveMaximum:l,exclusiveMinimum:u}=e._zod.bag;if(typeof c===\"string\"&&c.includes(\"int\"))o.type=\"integer\";else o.type=\"number\";let h=typeof u===\"number\"&&u>=(s??Number.NEGATIVE_INFINITY),p=typeof l===\"number\"&&l<=(i??Number.POSITIVE_INFINITY),f=t.target===\"draft-04\"||t.target===\"openapi-3.0\";if(h)if(f)o.minimum=u,o.exclusiveMinimum=!0;else o.exclusiveMinimum=u;else if(typeof s===\"number\")o.minimum=s;if(p)if(f)o.maximum=l,o.exclusiveMaximum=!0;else o.exclusiveMaximum=l;else if(typeof i===\"number\")o.maximum=i;if(typeof a===\"number\")o.multipleOf=a};var $l=(e,t,r,n)=>{r.not={}};var Sl=(e,t,r,n)=>{};var El=(e,t,r,n)=>{let o=e._zod.def,s=rr(o.entries);if(s.every((i)=>typeof i===\"number\"))r.type=\"number\";if(s.every((i)=>typeof i===\"string\"))r.type=\"string\";r.enum=s},Il=(e,t,r,n)=>{let o=e._zod.def,s=[];for(let i of o.values)if(i===void 0){if(t.unrepresentable===\"throw\")throw Error(\"Literal `undefined` cannot be represented in JSON Schema\")}else if(typeof i===\"bigint\")if(t.unrepresentable===\"throw\")throw Error(\"BigInt literals cannot be represented in JSON Schema\");else s.push(Number(i));else s.push(i);if(s.length===0);else if(s.length===1){let i=s[0];if(r.type=i===null?\"null\":typeof i,t.target===\"draft-04\"||t.target===\"openapi-3.0\")r.enum=[i];else r.const=i}else{if(s.every((i)=>typeof i===\"number\"))r.type=\"number\";if(s.every((i)=>typeof i===\"string\"))r.type=\"string\";if(s.every((i)=>typeof i===\"boolean\"))r.type=\"boolean\";if(s.every((i)=>i===null))r.type=\"null\";r.enum=s}};var Tl=(e,t,r,n)=>{if(t.unrepresentable===\"throw\")throw Error(\"Custom types cannot be represented in JSON Schema\")};var Al=(e,t,r,n)=>{if(t.unrepresentable===\"throw\")throw Error(\"Transforms cannot be represented in JSON Schema\")};var Ol=(e,t,r,n)=>{let o=r,s=e._zod.def,{minimum:i,maximum:c}=e._zod.bag;if(typeof i===\"number\")o.minItems=i;if(typeof c===\"number\")o.maxItems=c;o.type=\"array\",o.items=R(s.element,t,{...n,path:[...n.path,\"items\"]})},Zl=(e,t,r,n)=>{let o=r,s=e._zod.def;o.type=\"object\",o.properties={};let i=s.shape;for(let l in i)o.properties[l]=R(i[l],t,{...n,path:[...n.path,\"properties\",l]});let c=new Set(Object.keys(i)),a=new Set([...c].filter((l)=>{let u=s.shape[l]._zod;if(t.io===\"input\")return u.optin===void 0;else return u.optout===void 0}));if(a.size>0)o.required=Array.from(a);if(s.catchall?._zod.def.type===\"never\")o.additionalProperties=!1;else if(!s.catchall){if(t.io===\"output\")o.additionalProperties=!1}else if(s.catchall)o.additionalProperties=R(s.catchall,t,{...n,path:[...n.path,\"additionalProperties\"]})},Pl=(e,t,r,n)=>{let o=e._zod.def,s=o.inclusive===!1,i=o.options.map((c,a)=>R(c,t,{...n,path:[...n.path,s?\"oneOf\":\"anyOf\",a]}));if(s)r.oneOf=i;else r.anyOf=i},Cl=(e,t,r,n)=>{let o=e._zod.def,s=R(o.left,t,{...n,path:[...n.path,\"allOf\",0]}),i=R(o.right,t,{...n,path:[...n.path,\"allOf\",1]}),c=(l)=>(\"allOf\"in l)&&Object.keys(l).length===1,a=[...c(s)?s.allOf:[s],...c(i)?i.allOf:[i]];r.allOf=a};var Nl=(e,t,r,n)=>{let o=e._zod.def,s=R(o.innerType,t,n),i=t.seen.get(e);if(t.target===\"openapi-3.0\")i.ref=o.innerType,r.nullable=!0;else r.anyOf=[s,{type:\"null\"}]},Ul=(e,t,r,n)=>{let o=e._zod.def;R(o.innerType,t,n);let s=t.seen.get(e);s.ref=o.innerType},Dl=(e,t,r,n)=>{let o=e._zod.def;R(o.innerType,t,n);let s=t.seen.get(e);s.ref=o.innerType,r.default=JSON.parse(JSON.stringify(o.defaultValue))},Rl=(e,t,r,n)=>{let o=e._zod.def;R(o.innerType,t,n);let s=t.seen.get(e);if(s.ref=o.innerType,t.io===\"input\")r._prefault=JSON.parse(JSON.stringify(o.defaultValue))},jl=(e,t,r,n)=>{let o=e._zod.def;R(o.innerType,t,n);let s=t.seen.get(e);s.ref=o.innerType;let i;try{i=o.catchValue(void 0)}catch{throw Error(\"Dynamic catch values are not supported in JSON Schema\")}r.default=i},Ll=(e,t,r,n)=>{let o=e._zod.def,s=o.in._zod.traits.has(\"$ZodTransform\"),i=t.io===\"input\"?s?o.out:o.in:o.out;R(i,t,n);let c=t.seen.get(e);c.ref=i},Bl=(e,t,r,n)=>{let o=e._zod.def;R(o.innerType,t,n);let s=t.seen.get(e);s.ref=o.innerType,r.readOnly=!0};var ks=(e,t,r,n)=>{let o=e._zod.def;R(o.innerType,t,n);let s=t.seen.get(e);s.ref=o.innerType};var Hf=d(\"ZodISODateTime\",(e,t)=>{cu.init(e,t),E.init(e,t)});function Ml(e){return pl(Hf,e)}var Yf=d(\"ZodISODate\",(e,t)=>{au.init(e,t),E.init(e,t)});function Vl(e){return hl(Yf,e)}var Xf=d(\"ZodISOTime\",(e,t)=>{uu.init(e,t),E.init(e,t)});function Fl(e){return dl(Xf,e)}var Qf=d(\"ZodISODuration\",(e,t)=>{lu.init(e,t),E.init(e,t)});function Jl(e){return fl(Qf,e)}var rm=(e,t)=>{mn.init(e,t),e.name=\"ZodError\",Object.defineProperties(e,{format:{value:(r)=>Vc(e,r)},flatten:{value:(r)=>Mc(e,r)},addIssue:{value:(r)=>{e.issues.push(r),e.message=JSON.stringify(e.issues,_t,2)}},addIssues:{value:(r)=>{e.issues.push(...r),e.message=JSON.stringify(e.issues,_t,2)}},isEmpty:{get(){return e.issues.length===0}}})};var ne=d(\"ZodError\",rm,{Parent:Error});var ql=gn(ne),Gl=xn(ne),Wl=cr(ne),Kl=ar(ne),Hl=qc(ne),Yl=Gc(ne),Xl=Wc(ne),Ql=Kc(ne),ep=Hc(ne),tp=Yc(ne),rp=Xc(ne),np=Qc(ne);var op=new WeakMap;function dr(e,t,r){let n=Object.getPrototypeOf(e),o=op.get(n);if(!o)o=new Set,op.set(n,o);if(o.has(t))return;o.add(t);for(let s in r){let i=r[s];Object.defineProperty(n,s,{configurable:!0,enumerable:!1,get(){let c=i.bind(this);return Object.defineProperty(this,s,{configurable:!0,writable:!0,enumerable:!0,value:c}),c},set(c){Object.defineProperty(this,s,{configurable:!0,writable:!0,enumerable:!0,value:c})}})}}var A=d(\"ZodType\",(e,t)=>(T.init(e,t),Object.assign(e[\"~standard\"],{jsonSchema:{input:hr(e,\"input\"),output:hr(e,\"output\")}}),e.toJSONSchema=kl(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,\"_def\",{value:t}),e.parse=(r,n)=>ql(e,r,n,{callee:e.parse}),e.safeParse=(r,n)=>Wl(e,r,n),e.parseAsync=async(r,n)=>Gl(e,r,n,{callee:e.parseAsync}),e.safeParseAsync=async(r,n)=>Kl(e,r,n),e.spa=e.safeParseAsync,e.encode=(r,n)=>Hl(e,r,n),e.decode=(r,n)=>Yl(e,r,n),e.encodeAsync=async(r,n)=>Xl(e,r,n),e.decodeAsync=async(r,n)=>Ql(e,r,n),e.safeEncode=(r,n)=>ep(e,r,n),e.safeDecode=(r,n)=>tp(e,r,n),e.safeEncodeAsync=async(r,n)=>rp(e,r,n),e.safeDecodeAsync=async(r,n)=>np(e,r,n),dr(e,\"ZodType\",{check(...r){let n=this.def;return this.clone(b.mergeDefs(n,{checks:[...n.checks??[],...r.map((o)=>typeof o===\"function\"?{_zod:{check:o,def:{check:\"custom\"},onattach:[]}}:o)]}),{parent:!0})},with(...r){return this.check(...r)},clone(r,n){return ce(this,r,n)},brand(){return this},register(r,n){return r.add(this,n),this},refine(r,n){return this.check(Km(r,n))},superRefine(r,n){return this.check(Hm(r,n))},overwrite(r){return this.check(Pe(r))},optional(){return cp(this)},exactOptional(){return Um(this)},nullable(){return ap(this)},nullish(){return cp(ap(this))},nonoptional(r){return Mm(this,r)},array(){return fr(this)},or(r){return $s([this,r])},and(r){return Am(this,r)},transform(r){return up(this,Cm(r))},default(r){return jm(this,r)},prefault(r){return Bm(this,r)},catch(r){return Fm(this,r)},pipe(r){return up(this,r)},readonly(){return Gm(this)},describe(r){let n=this.clone();return Ke.add(n,{description:r}),n},meta(...r){if(r.length===0)return Ke.get(this);let n=this.clone();return Ke.add(n,r[0]),n},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(r){return r(this)}}),Object.defineProperty(e,\"description\",{get(){return Ke.get(e)?.description},configurable:!0}),e)),lp=d(\"_ZodString\",(e,t)=>{bn.init(e,t),A.init(e,t),e._zod.processJSONSchema=(n,o,s)=>vl(e,n,o,s);let r=e._zod.bag;e.format=r.format??null,e.minLength=r.minimum??null,e.maxLength=r.maximum??null,dr(e,\"_ZodString\",{regex(...n){return this.check(as(...n))},includes(...n){return this.check(ps(...n))},startsWith(...n){return this.check(hs(...n))},endsWith(...n){return this.check(ds(...n))},min(...n){return this.check(kt(...n))},max(...n){return this.check($n(...n))},length(...n){return this.check(Sn(...n))},nonempty(...n){return this.check(kt(1,...n))},lowercase(n){return this.check(us(n))},uppercase(n){return this.check(ls(n))},trim(){return this.check(ms())},normalize(...n){return this.check(fs(...n))},toLowerCase(){return this.check(gs())},toUpperCase(){return this.check(xs())},slugify(){return this.check(ys())}})}),om=d(\"ZodString\",(e,t)=>{bn.init(e,t),lp.init(e,t),e.email=(r)=>e.check(Fu(sm,r)),e.url=(r)=>e.check(Ku(im,r)),e.jwt=(r)=>e.check(ll(bm,r)),e.emoji=(r)=>e.check(Hu(cm,r)),e.guid=(r)=>e.check(cs(sp,r)),e.uuid=(r)=>e.check(Ju(In,r)),e.uuidv4=(r)=>e.check(qu(In,r)),e.uuidv6=(r)=>e.check(Gu(In,r)),e.uuidv7=(r)=>e.check(Wu(In,r)),e.nanoid=(r)=>e.check(Yu(am,r)),e.guid=(r)=>e.check(cs(sp,r)),e.cuid=(r)=>e.check(Xu(um,r)),e.cuid2=(r)=>e.check(Qu(lm,r)),e.ulid=(r)=>e.check(el(pm,r)),e.base64=(r)=>e.check(cl(ym,r)),e.base64url=(r)=>e.check(al(_m,r)),e.xid=(r)=>e.check(tl(hm,r)),e.ksuid=(r)=>e.check(rl(dm,r)),e.ipv4=(r)=>e.check(nl(fm,r)),e.ipv6=(r)=>e.check(ol(mm,r)),e.cidrv4=(r)=>e.check(sl(gm,r)),e.cidrv6=(r)=>e.check(il(xm,r)),e.e164=(r)=>e.check(ul(wm,r)),e.datetime=(r)=>e.check(Ml(r)),e.date=(r)=>e.check(Vl(r)),e.time=(r)=>e.check(Fl(r)),e.duration=(r)=>e.check(Jl(r))});function zs(e){return Vu(om,e)}var E=d(\"ZodStringFormat\",(e,t)=>{S.init(e,t),lp.init(e,t)}),sm=d(\"ZodEmail\",(e,t)=>{Xa.init(e,t),E.init(e,t)});var sp=d(\"ZodGUID\",(e,t)=>{Ha.init(e,t),E.init(e,t)});var In=d(\"ZodUUID\",(e,t)=>{Ya.init(e,t),E.init(e,t)});var im=d(\"ZodURL\",(e,t)=>{Qa.init(e,t),E.init(e,t)});var cm=d(\"ZodEmoji\",(e,t)=>{eu.init(e,t),E.init(e,t)});var am=d(\"ZodNanoID\",(e,t)=>{tu.init(e,t),E.init(e,t)});var um=d(\"ZodCUID\",(e,t)=>{ru.init(e,t),E.init(e,t)});var lm=d(\"ZodCUID2\",(e,t)=>{nu.init(e,t),E.init(e,t)});var pm=d(\"ZodULID\",(e,t)=>{ou.init(e,t),E.init(e,t)});var hm=d(\"ZodXID\",(e,t)=>{su.init(e,t),E.init(e,t)});var dm=d(\"ZodKSUID\",(e,t)=>{iu.init(e,t),E.init(e,t)});var fm=d(\"ZodIPv4\",(e,t)=>{pu.init(e,t),E.init(e,t)});var mm=d(\"ZodIPv6\",(e,t)=>{hu.init(e,t),E.init(e,t)});var gm=d(\"ZodCIDRv4\",(e,t)=>{du.init(e,t),E.init(e,t)});var xm=d(\"ZodCIDRv6\",(e,t)=>{fu.init(e,t),E.init(e,t)});var ym=d(\"ZodBase64\",(e,t)=>{gu.init(e,t),E.init(e,t)});var _m=d(\"ZodBase64URL\",(e,t)=>{xu.init(e,t),E.init(e,t)});var wm=d(\"ZodE164\",(e,t)=>{yu.init(e,t),E.init(e,t)});var bm=d(\"ZodJWT\",(e,t)=>{_u.init(e,t),E.init(e,t)});var pp=d(\"ZodNumber\",(e,t)=>{os.init(e,t),A.init(e,t),e._zod.processJSONSchema=(n,o,s)=>zl(e,n,o,s),dr(e,\"ZodNumber\",{gt(n,o){return this.check(vn(n,o))},gte(n,o){return this.check(pr(n,o))},min(n,o){return this.check(pr(n,o))},lt(n,o){return this.check(kn(n,o))},lte(n,o){return this.check(lr(n,o))},max(n,o){return this.check(lr(n,o))},int(n){return this.check(ip(n))},safe(n){return this.check(ip(n))},positive(n){return this.check(vn(0,n))},nonnegative(n){return this.check(pr(0,n))},negative(n){return this.check(kn(0,n))},nonpositive(n){return this.check(lr(0,n))},multipleOf(n,o){return this.check(zn(n,o))},step(n,o){return this.check(zn(n,o))},finite(){return this}});let r=e._zod.bag;e.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(r.format??\"\").includes(\"int\")||Number.isSafeInteger(r.multipleOf??0.5),e.isFinite=!0,e.format=r.format??null});function vt(e){return ml(pp,e)}var km=d(\"ZodNumberFormat\",(e,t)=>{wu.init(e,t),pp.init(e,t)});function ip(e){return gl(km,e)}var vm=d(\"ZodUnknown\",(e,t)=>{bu.init(e,t),A.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Sl(e,r,n,o)});function Tn(){return xl(vm)}var zm=d(\"ZodNever\",(e,t)=>{ku.init(e,t),A.init(e,t),e._zod.processJSONSchema=(r,n,o)=>$l(e,r,n,o)});function $m(e){return yl(zm,e)}var Sm=d(\"ZodArray\",(e,t)=>{vu.init(e,t),A.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Ol(e,r,n,o),e.element=t.element,dr(e,\"ZodArray\",{min(r,n){return this.check(kt(r,n))},nonempty(r){return this.check(kt(1,r))},max(r,n){return this.check($n(r,n))},length(r,n){return this.check(Sn(r,n))},unwrap(){return this.element}})});function fr(e,t){return _l(Sm,e,t)}var Em=d(\"ZodObject\",(e,t)=>{Su.init(e,t),A.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Zl(e,r,n,o),b.defineLazy(e,\"shape\",()=>t.shape),dr(e,\"ZodObject\",{keyof(){return Om(Object.keys(this._zod.def.shape))},catchall(r){return this.clone({...this._zod.def,catchall:r})},passthrough(){return this.clone({...this._zod.def,catchall:Tn()})},loose(){return this.clone({...this._zod.def,catchall:Tn()})},strict(){return this.clone({...this._zod.def,catchall:$m()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(r){return b.extend(this,r)},safeExtend(r){return b.safeExtend(this,r)},merge(r){return b.merge(this,r)},pick(r){return b.pick(this,r)},omit(r){return b.omit(this,r)},partial(...r){return b.partial(fp,this,r[0])},required(...r){return b.required(mp,this,r[0])}})});function zt(e,t){let r={type:\"object\",shape:e??{},...b.normalizeParams(t)};return new Em(r)}var hp=d(\"ZodUnion\",(e,t)=>{ss.init(e,t),A.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Pl(e,r,n,o),e.options=t.options});function $s(e,t){return new hp({type:\"union\",options:e,...b.normalizeParams(t)})}var Im=d(\"ZodDiscriminatedUnion\",(e,t)=>{hp.init(e,t),Eu.init(e,t)});function dp(e,t,r){return new Im({type:\"union\",options:t,discriminator:e,...b.normalizeParams(r)})}var Tm=d(\"ZodIntersection\",(e,t)=>{Iu.init(e,t),A.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Cl(e,r,n,o)});function Am(e,t){return new Tm({type:\"intersection\",left:e,right:t})}var vs=d(\"ZodEnum\",(e,t)=>{Tu.init(e,t),A.init(e,t),e._zod.processJSONSchema=(n,o,s)=>El(e,n,o,s),e.enum=t.entries,e.options=Object.values(t.entries);let r=new Set(Object.keys(t.entries));e.extract=(n,o)=>{let s={};for(let i of n)if(r.has(i))s[i]=t.entries[i];else throw Error(`Key ${i} not found in enum`);return new vs({...t,checks:[],...b.normalizeParams(o),entries:s})},e.exclude=(n,o)=>{let s={...t.entries};for(let i of n)if(r.has(i))delete s[i];else throw Error(`Key ${i} not found in enum`);return new vs({...t,checks:[],...b.normalizeParams(o),entries:s})}});function Om(e,t){let r=Array.isArray(e)?Object.fromEntries(e.map((n)=>[n,n])):e;return new vs({type:\"enum\",entries:r,...b.normalizeParams(t)})}var Zm=d(\"ZodLiteral\",(e,t)=>{Au.init(e,t),A.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Il(e,r,n,o),e.values=new Set(t.values),Object.defineProperty(e,\"value\",{get(){if(t.values.length>1)throw Error(\"This schema contains multiple valid literal values. Use `.values` instead.\");return t.values[0]}})});function $t(e,t){return new Zm({type:\"literal\",values:Array.isArray(e)?e:[e],...b.normalizeParams(t)})}var Pm=d(\"ZodTransform\",(e,t)=>{Ou.init(e,t),A.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Al(e,r,n,o),e._zod.parse=(r,n)=>{if(n.direction===\"backward\")throw new er(e.constructor.name);r.addIssue=(s)=>{if(typeof s===\"string\")r.issues.push(b.issue(s,r.value,t));else{let i=s;if(i.fatal)i.continue=!1;i.code??(i.code=\"custom\"),i.input??(i.input=r.value),i.inst??(i.inst=e),r.issues.push(b.issue(i))}};let o=t.transform(r.value,r);if(o instanceof Promise)return o.then((s)=>(r.value=s,r.fallback=!0,r));return r.value=o,r.fallback=!0,r}});function Cm(e){return new Pm({type:\"transform\",transform:e})}var fp=d(\"ZodOptional\",(e,t)=>{is.init(e,t),A.init(e,t),e._zod.processJSONSchema=(r,n,o)=>ks(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});function cp(e){return new fp({type:\"optional\",innerType:e})}var Nm=d(\"ZodExactOptional\",(e,t)=>{Zu.init(e,t),A.init(e,t),e._zod.processJSONSchema=(r,n,o)=>ks(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});function Um(e){return new Nm({type:\"optional\",innerType:e})}var Dm=d(\"ZodNullable\",(e,t)=>{Pu.init(e,t),A.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Nl(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});function ap(e){return new Dm({type:\"nullable\",innerType:e})}var Rm=d(\"ZodDefault\",(e,t)=>{Cu.init(e,t),A.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Dl(e,r,n,o),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function jm(e,t){return new Rm({type:\"default\",innerType:e,get defaultValue(){return typeof t===\"function\"?t():b.shallowClone(t)}})}var Lm=d(\"ZodPrefault\",(e,t)=>{Nu.init(e,t),A.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Rl(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});function Bm(e,t){return new Lm({type:\"prefault\",innerType:e,get defaultValue(){return typeof t===\"function\"?t():b.shallowClone(t)}})}var mp=d(\"ZodNonOptional\",(e,t)=>{Uu.init(e,t),A.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Ul(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});function Mm(e,t){return new mp({type:\"nonoptional\",innerType:e,...b.normalizeParams(t)})}var Vm=d(\"ZodCatch\",(e,t)=>{Du.init(e,t),A.init(e,t),e._zod.processJSONSchema=(r,n,o)=>jl(e,r,n,o),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Fm(e,t){return new Vm({type:\"catch\",innerType:e,catchValue:typeof t===\"function\"?t:()=>t})}var Jm=d(\"ZodPipe\",(e,t)=>{Ru.init(e,t),A.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Ll(e,r,n,o),e.in=t.in,e.out=t.out});function up(e,t){return new Jm({type:\"pipe\",in:e,out:t})}var qm=d(\"ZodReadonly\",(e,t)=>{ju.init(e,t),A.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Bl(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});function Gm(e){return new qm({type:\"readonly\",innerType:e})}var Wm=d(\"ZodCustom\",(e,t)=>{Lu.init(e,t),A.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Tl(e,r,n,o)});function Km(e,t={}){return wl(Wm,e,t)}function Hm(e,t){return bl(e,t)}var gr=32,Cn=new Set([\"__proto__\",\"constructor\",\"prototype\"]),Ym=$s([zs().min(1).max(512).refine((e)=>!Cn.has(e),\"unsafe path key\"),vt().int().nonnegative()]),mr=fr(Ym).min(1).max(gr);function xr(e,t=0){if(t>gr)return!1;if(e===null||typeof e===\"boolean\"||typeof e===\"string\")return!0;if(typeof e===\"number\")return Number.isFinite(e);if(Array.isArray(e))return e.every((n)=>xr(n,t+1));if(typeof e!==\"object\")return!1;let r=Object.getPrototypeOf(e);if(r!==Object.prototype&&r!==null)return!1;return Object.entries(e).every(([n,o])=>!Cn.has(n)&&xr(o,t+1))}var gp=Tn().refine(xr,\"value must be safe JSON\"),Xm=dp(\"type\",[zt({type:$t(\"set\"),path:mr,value:gp}),zt({type:$t(\"delete\"),path:mr}),zt({type:$t(\"insert\"),path:mr,index:vt().int().nonnegative(),values:fr(gp).min(1)}),zt({type:$t(\"increment\"),path:mr,by:vt().finite()}),zt({type:$t(\"text\"),path:mr,index:vt().int().nonnegative(),deleteCount:vt().int().nonnegative().optional(),insert:zs().optional()})]).superRefine((e,t)=>{if(e.type===\"text\"&&(e.deleteCount??0)===0&&(e.insert??\"\").length===0)t.addIssue({code:\"custom\",message:\"text operation must insert or delete content\"})});function Zn(e){if(Array.isArray(e)){let t=new re;return t.insert(0,e.map(Zn)),t}if(e!==null&&typeof e===\"object\"){let t=new G;for(let[r,n]of Object.entries(e))t.set(r,Zn(n));return t}return e}function Ss(e,t=0){if(t>gr)throw Error(\"room document exceeds the maximum nesting depth\");if(e instanceof G){let r=Object.create(null);for(let[n,o]of e.entries()){if(Cn.has(n))throw Error(`room document contains unsafe key \"${n}\"`);r[n]=Ss(o,t+1)}return r}if(e instanceof re)return e.toArray().map((r)=>Ss(r,t+1));if(e instanceof ie)return e.toString();if(!xr(e))throw Error(\"room document contains a non-JSON value\");return e}function Nn(e){return Ss(e.getMap(\"root\"))}function B(e){return e.map(String).join(\".\")}function wp(e){if(e.length===0||e.length>gr)throw Error(`room path must contain 1 to ${gr} segments`);for(let t of e)if(typeof t===\"string\"){if(t.length===0||t.length>512||Cn.has(t))throw Error(`invalid room path segment \"${t}\"`)}else if(!Number.isInteger(t)||t<0)throw Error(`invalid room array index ${String(t)}`)}function bp(e,t,r){if(e instanceof G){if(typeof t!==\"string\")throw Error(`expected an object key at \"${B(r)}\"`);if(!e.has(t))throw Error(`room path does not exist: \"${B(r)}\"`);return e.get(t)}if(typeof t!==\"number\"||t>=e.length)throw Error(`invalid array index at \"${B(r)}\"`);return e.get(t)}function Un(e,t){wp(t);let r=e.getMap(\"root\");for(let n=0;n<t.length-1;n+=1){if(!(r instanceof G)&&!(r instanceof re))throw Error(`room path crosses a scalar at \"${B(t.slice(0,n+1))}\"`);r=bp(r,t[n],t.slice(0,n+1))}if(!(r instanceof G)&&!(r instanceof re))throw Error(`room path parent is not a container: \"${B(t)}\"`);return{parent:r,key:t[t.length-1]}}function An(e,t){let{parent:r,key:n}=Un(e,t);return bp(r,n,t)}function xp(e,t,r){let{parent:n,key:o}=Un(e,t),s=Zn(r);if(n instanceof G){if(typeof o!==\"string\")throw Error(`expected an object key at \"${B(t)}\"`);n.set(o,s);return}if(typeof o!==\"number\"||o>=n.length)throw Error(`invalid array index at \"${B(t)}\"`);n.delete(o,1),n.insert(o,[s])}function Qm(e,t){let{parent:r,key:n}=Un(e,t);if(r instanceof G){if(typeof n!==\"string\")throw Error(`expected an object key at \"${B(t)}\"`);if(!r.has(n))throw Error(`room path does not exist: \"${B(t)}\"`);r.delete(n);return}if(typeof n!==\"number\"||n>=r.length)throw Error(`invalid array index at \"${B(t)}\"`);r.delete(n,1)}function yp(e,t){e.transact(()=>{for(let r of t)switch(r.type){case\"set\":xp(e,r.path,r.value);break;case\"delete\":Qm(e,r.path);break;case\"insert\":{wp(r.path);let n=An(e,r.path);if(!(n instanceof re))throw Error(`insert target is not an array: \"${B(r.path)}\"`);if(r.index>n.length)throw Error(`insert index is outside the array: \"${B(r.path)}\"`);n.insert(r.index,r.values.map(Zn));break}case\"increment\":{let n=An(e,r.path);if(typeof n!==\"number\"||!Number.isFinite(n))throw Error(`increment target is not a finite number: \"${B(r.path)}\"`);let o=n+r.by;if(!Number.isFinite(o))throw Error(`increment result is not finite: \"${B(r.path)}\"`);xp(e,r.path,o);break}case\"text\":{let n=An(e,r.path),o;if(n instanceof ie)o=n;else if(typeof n===\"string\"){o=new ie(n);let{parent:i,key:c}=Un(e,r.path);if(i instanceof G&&typeof c===\"string\")i.set(c,o);else if(i instanceof re&&typeof c===\"number\"&&c<i.length)i.delete(c,1),i.insert(c,[o]);else throw Error(`invalid text path: \"${B(r.path)}\"`)}else throw Error(`text target is not a string: \"${B(r.path)}\"`);let s=r.deleteCount??0;if(r.index>o.length||r.index+s>o.length)throw Error(`text range is outside the string: \"${B(r.path)}\"`);if(s>0)o.delete(r.index,s);if(r.insert)o.insert(r.index,r.insert);break}}})}function eg(e,t){let r=fr(Xm).min(1).parse(t),n=new ge({gc:!0});try{sn(n,gt(e)),yp(n,r),Nn(n)}finally{n.destroy()}let o=Yi(e);return yp(e,r),gt(e,o)}function Pn(e,t){if(Object.is(e,t))return!0;if(Array.isArray(e)||Array.isArray(t))return Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((o,s)=>Pn(o,t[s]));if(e===null||t===null||typeof e!==\"object\"||typeof t!==\"object\")return!1;let r=Object.keys(e),n=Object.keys(t);return r.length===n.length&&r.every((o)=>Object.hasOwn(t,o)&&Pn(e[o],t[o]))}function tg(e,t){if(Pn(e,t))return!0;if(e!==null&&t!==null&&!Array.isArray(e)&&!Array.isArray(t)&&typeof e===\"object\"&&typeof t===\"object\"&&Object.hasOwn(e,\"id\")&&Object.hasOwn(t,\"id\")){let r=e.id;return(typeof r===\"string\"||typeof r===\"number\")&&Object.is(r,t.id)}return!1}function Es(e){if(e!==null&&!Array.isArray(e)&&typeof e===\"object\"&&(typeof e.id===\"string\"||typeof e.id===\"number\"))return`id:${typeof e.id}:${String(e.id)}`;return`value:${JSON.stringify(e)}`}function _p(e){let t=[],r=new Set;for(let n of e){if(n===null||Array.isArray(n)||typeof n!==\"object\"||typeof n.id!==\"string\"&&typeof n.id!==\"number\")return null;let o=Es(n);if(r.has(o))return null;r.add(o),t.push(o)}return t}function rg(e,t){let r=new Map;for(let s=0;s<t.length;s+=1){let i=Es(t[s]),c=r.get(i);if(c)c.push(s);else r.set(i,[s])}let n=[],o=-1;for(let s=0;s<e.length;s+=1){let i=r.get(Es(e[s]));while(i?.length&&i[0]<=o)i.shift();let c=i?.shift();if(c===void 0)continue;if(!tg(e[s],t[c]))continue;n.push([s,c]),o=c}return n}function ng(e,t){try{return An(e,t)}catch{return}}function On(e,t,r,n,o){if(Pn(t,r))return;if(t!==null&&r!==null&&!Array.isArray(t)&&!Array.isArray(r)&&typeof t===\"object\"&&typeof r===\"object\"){for(let s of Object.keys(t))if(!Object.hasOwn(r,s))o.push({type:\"delete\",path:[...n,s]});for(let[s,i]of Object.entries(r))if(!Object.hasOwn(t,s))o.push({type:\"set\",path:[...n,s],value:i});else On(e,t[s],i,[...n,s],o);return}if(Array.isArray(t)&&Array.isArray(r)){let s=_p(t),i=_p(r),c=s!==null&&i!==null&&(s.length!==i.length||s.some((h,p)=>h!==i[p]));if(t.length===r.length&&!c){for(let h=0;h<r.length;h+=1)On(e,t[h],r[h],[...n,h],o);return}let a=0,l=0,u=0;for(let[h,p]of[...rg(t,r),[t.length,r.length]]){let f=h-a;for(let k=0;k<f;k+=1)o.push({type:\"delete\",path:[...n,u]});let m=r.slice(l,p);if(m.length>0)o.push({type:\"insert\",path:n,index:u,values:m}),u+=m.length;if(h<t.length&&p<r.length)On(e,t[h],r[p],[...n,u],o),u+=1;a=h+1,l=p+1}return}if(typeof t===\"string\"&&typeof r===\"string\"&&ng(e,n)instanceof ie){let s=0;while(s<t.length&&s<r.length&&t[s]===r[s])s+=1;let i=0;while(i<t.length-s&&i<r.length-s&&t[t.length-1-i]===r[r.length-1-i])i+=1;o.push({type:\"text\",path:n,index:s,deleteCount:t.length-s-i,insert:r.slice(s,r.length-i)});return}o.push({type:\"set\",path:n,value:r})}function kp(e,t){let r=Nn(e),n=structuredClone(r),o=t(n);if(o!==null&&(typeof o===\"object\"||typeof o===\"function\")&&typeof o.then===\"function\")throw Error(\"room change callback must be synchronous\");if(!xr(n)||Array.isArray(n))throw Error(\"room state must be a safe JSON object\");let s=[];if(On(e,r,n,[],s),s.length>0)eg(e,s);return s}function vp(e){let t=\"\";for(let r=0;r<e.length;r+=8192)t+=String.fromCharCode(...e.subarray(r,r+8192));return btoa(t)}function og(e){return Uint8Array.from(atob(e),(t)=>t.charCodeAt(0))}class Dn{handlers=new Map;on(e,t){let r=this.handlers.get(e)??new Set;return r.add(t),this.handlers.set(e,r),()=>r.delete(t)}emit(e,t){for(let r of this.handlers.get(e)??[])r(t)}}class zp extends Dn{socket;rooms=new Map;channels=new Map;pending=new Map;nextId=0;opening;retry;stopped=!1;me;async open(){if(this.socket?.readyState===WebSocket.OPEN)return;if(this.opening)return this.opening;let e=location.pathname.match(/^\\/p\\/([^/.]+)/);if(!e)throw Error(\"Realtime rooms require a Swarm page\");let t=new URL(\"/@swarm/realtime\",location.href);return t.protocol=location.protocol===\"https:\"?\"wss:\":\"ws:\",t.searchParams.set(\"pageId\",decodeURIComponent(e[1])),this.opening=new Promise((r,n)=>{let o=new WebSocket(t);this.socket=o,o.onopen=()=>{this.opening=void 0,r()},o.onerror=()=>n(Error(\"Realtime connection failed\")),o.onmessage=(s)=>{let i=JSON.parse(s.data);if(i.seq)o.send(JSON.stringify({ack:i.seq}));if(i.type===\"hello\")this.me=i.me;if(i.type===\"room\")this.rooms.get(i.name??\"\")?.receive(i);if(i.type===\"presence\")this.rooms.get(i.name??\"\")?.receivePresence(i.peers);if(i.type===\"channel\")this.channels.get(i.name??\"\")?.emit(\"message\",i.data);if(i.type===\"deleted\")this.rooms.get(i.name??\"\")?.deleted();if(i.id!==void 0){let c=this.pending.get(i.id);if(c)if(clearTimeout(c.timer),this.pending.delete(i.id),i.type===\"error\")c.reject(Error(i.error));else c.resolve(i)}},o.onclose=()=>{this.opening=void 0,n(Error(\"Realtime connection closed\"));for(let s of this.pending.values())clearTimeout(s.timer),s.reject(Error(\"Realtime connection closed\"));if(this.pending.clear(),!this.stopped)this.retry=setTimeout(()=>{this.reconnect()},1000)}}),this.opening}async reconnect(){try{await this.open();for(let e of this.rooms.values())await e.join(!0);for(let e of this.channels.keys())await this.request({op:\"subscribe\",name:e})}catch(e){for(let t of this.rooms.values())t.emit(\"error\",e)}}async request(e){await this.open();let t=++this.nextId;return new Promise((r,n)=>{let o=setTimeout(()=>{this.pending.delete(t),n(Error(\"Realtime request timed out\"))},15000);this.pending.set(t,{resolve:r,reject:n,timer:o}),this.socket.send(JSON.stringify({...e,id:t}))})}close(){this.stopped=!0,clearTimeout(this.retry),this.socket?.close()}}class $p extends Dn{connection;name;ydoc=new ge({gc:!0});generation=\"\";stale=!1;bytes=0;me;ready;writes=Promise.resolve();lastWrite=Promise.resolve();peers=[];presenceData={};presenceTimer;closed=!1;schemaVersion;presence;constructor(e,t,r){super();this.connection=e;this.name=t;this.schemaVersion=r.schemaVersion??1;let n=this;this.presence={set(o){if(n.presenceData=structuredClone(o),!n.presenceTimer)n.presenceTimer=setTimeout(()=>{n.presenceTimer=void 0,e.request({op:\"presence\",name:t,data:n.presenceData}).catch((s)=>n.emit(\"error\",s))},50)},get peers(){return n.peers}},this.observe()}get state(){return Nn(this.ydoc)}observe(){this.ydoc.on(\"update\",(e,t)=>{if(this.emit(\"change\",this.state),t===\"remote\"||!this.generation||this.closed)return;if(this.connection.socket?.readyState!==WebSocket.OPEN)return;let r=vp(gt(this.ydoc)),n=this.generation,o=this.writes.then(async()=>{try{let s=await this.connection.request({op:\"update\",name:this.name,generation:n,schemaVersion:this.schemaVersion,snapshot:r});if(s.room)this.receive(s.room)}catch(s){if(this.connection.socket?.readyState===WebSocket.OPEN){let i=await this.connection.request({op:\"join\",name:this.name,schemaVersion:this.schemaVersion});this.receive(i.room,!0)}throw this.emit(\"error\",s),s}});this.lastWrite=o,this.writes=o.catch(()=>{})})}async join(e=!1){if(this.ready&&!e)return this.ready;return this.ready=(async()=>{let t=this.generation,r=await this.connection.request({op:\"join\",name:this.name,schemaVersion:this.schemaVersion});if(this.me=r.me,this.receive(r.room),this.receivePresence(r.peers),e&&t===this.generation&&!this.stale){let n=await this.connection.request({op:\"update\",name:this.name,schemaVersion:this.schemaVersion,generation:t,snapshot:vp(gt(this.ydoc))});this.receive(n.room)}if(e)this.presence.set(this.presenceData)})(),this.ready}receive(e,t=!1){if(this.closed||!e)return;let r=t||this.generation!==\"\"&&e.generation!==this.generation;if(this.generation=e.generation,this.stale=e.schemaVersion!==this.schemaVersion,this.bytes=e.bytes,r)this.ydoc.destroy(),this.ydoc=new ge({gc:!0}),this.observe();if(sn(this.ydoc,og(e.snapshot),\"remote\"),r)this.emit(\"reset\",this.state)}receivePresence(e=[]){this.peers=e,this.emit(\"presence\",e)}deleted(){this.closed=!0,this.emit(\"error\",Error(\"Room owner was deleted\")),this.ydoc.destroy()}async change(e){if(this.closed)throw Error(\"Room is closed\");if(this.stale)throw Error(\"Room schema is stale. Read the state and reset explicitly.\");if(kp(this.ydoc,e).length>0)await this.lastWrite}async apply(e){if(this.closed||this.stale)throw Error(\"Room is closed or stale\");await this.writes;let t=await this.connection.request({op:\"change\",name:this.name,generation:this.generation,schemaVersion:this.schemaVersion,operations:e});this.receive(t.room)}async reset(e={}){if(this.closed)throw Error(\"Room is closed\");await this.writes;let t=await this.connection.request({op:\"reset\",name:this.name,schemaVersion:this.schemaVersion,state:e});this.receive(t.room)}async close(){this.closed=!0,clearTimeout(this.presenceTimer),this.connection.rooms.delete(this.name);try{await this.connection.request({op:\"leave\",name:this.name})}finally{this.ydoc.destroy()}}}class Sp extends Dn{connection;name;constructor(e,t){super();this.connection=e;this.name=t}async publish(e){await this.connection.request({op:\"publish\",name:this.name,data:e})}async close(){this.connection.channels.delete(this.name),await this.connection.request({op:\"unsubscribe\",name:this.name})}}var ye=new zp;window.addEventListener(\"pagehide\",()=>ye.close());async function h_(e=\"default\",t={}){if(!/^[a-zA-Z0-9_-]{1,64}$/.test(e))throw Error(\"Invalid room name\");let r=ye.rooms.get(e);if(r&&r.schemaVersion!==(t.schemaVersion??1))throw Error(\"Room already opened with a different schema version\");if(!r)r=new $p(ye,e,t),ye.rooms.set(e,r);try{await r.join()}catch(n){throw ye.rooms.delete(e),n}return r}async function d_(e){if(!/^[a-zA-Z0-9_-]{1,64}$/.test(e))throw Error(\"Invalid channel name\");let t=ye.channels.get(e);if(t)return t;let r=new Sp(ye,e);ye.channels.set(e,r);try{await ye.request({op:\"subscribe\",name:e})}catch(n){throw ye.channels.delete(e),n}return r}export{d_ as channel,h_ as room};\n\n";
19439
20429
 
19440
20430
  // src/http/realtime.ts
20431
+ init_request_auth_context();
20432
+ var realtimeTicketRoute = route({
20433
+ method: "post",
20434
+ path: "/api/realtime/ticket",
20435
+ pattern: ["api", "realtime", "ticket"],
20436
+ summary: "Issue a one-shot dashboard realtime ticket",
20437
+ tags: ["Rooms"],
20438
+ rbac: { permission: "comb.presence" },
20439
+ responses: {
20440
+ 200: {
20441
+ description: "One-shot realtime ticket",
20442
+ schema: exports_external.object({ ticket: exports_external.string(), expiresAt: exports_external.number().int() })
20443
+ },
20444
+ 403: { description: "Comb presence is not allowed" },
20445
+ 404: { description: "Comb is not enabled" }
20446
+ }
20447
+ });
19441
20448
  route({
19442
20449
  method: "get",
19443
20450
  path: "/@swarm/realtime.js",
@@ -19449,6 +20456,34 @@ route({
19449
20456
  200: { description: "JavaScript module", unstructured: "Browser JavaScript bundle" }
19450
20457
  }
19451
20458
  });
20459
+ async function handleRealtimeTicket(req, res, pathSegments, queryParams) {
20460
+ if (!realtimeTicketRoute.match(req.method, pathSegments))
20461
+ return false;
20462
+ if (!getCombConfig().enabled) {
20463
+ jsonError(res, "Comb is not enabled", 404);
20464
+ return true;
20465
+ }
20466
+ const parsed = await realtimeTicketRoute.parse(req, res, pathSegments, queryParams);
20467
+ if (!parsed)
20468
+ return true;
20469
+ const auth = getRequestAuth(req);
20470
+ if (!auth || auth.kind === "agent") {
20471
+ jsonError(res, "Comb presence requires dashboard authentication", 403);
20472
+ return true;
20473
+ }
20474
+ const principal = auth.kind === "operator" ? { kind: "operator" } : { kind: "user", userId: auth.userId };
20475
+ if (!can({
20476
+ principal,
20477
+ verb: "comb.presence",
20478
+ resource: { kind: "none" },
20479
+ source: "http"
20480
+ }).allow) {
20481
+ jsonError(res, "Comb presence requires the comb.presence permission", 403);
20482
+ return true;
20483
+ }
20484
+ realtimeTicketRoute.respond(res, 200, issueRealtimeTicket(auth));
20485
+ return true;
20486
+ }
19452
20487
  async function handleRealtimeAsset(req, res) {
19453
20488
  if (req.method !== "GET" || req.url?.split("?")[0] !== "/@swarm/realtime.js")
19454
20489
  return false;
@@ -20500,6 +21535,7 @@ async function handleSchedules(req, res, pathSegments, queryParams, myAgentId) {
20500
21535
  // src/http/script-connection-proxy.ts
20501
21536
  init_zod();
20502
21537
  init_db();
21538
+ init_rbac();
20503
21539
  var McpToolCallResultSchema = exports_external.object({
20504
21540
  content: exports_external.array(exports_external.object({ type: exports_external.string(), text: exports_external.string().optional() })),
20505
21541
  isError: exports_external.boolean().optional()
@@ -20608,6 +21644,7 @@ async function handleScriptConnectionProxy(req, res, pathSegments, queryParams,
20608
21644
  init_zod();
20609
21645
  init_date_utils();
20610
21646
  init_db();
21647
+ init_rbac();
20611
21648
  init_credential_broker();
20612
21649
  init_telemetry();
20613
21650
  init_request_auth_context();
@@ -23126,6 +24163,7 @@ async function handleScriptRuns(req, res, pathSegments, queryParams, agentId) {
23126
24163
  // src/http/scripts.ts
23127
24164
  init_zod();
23128
24165
  init_db();
24166
+ init_rbac();
23129
24167
  init_types();
23130
24168
  init_secret_scrubber();
23131
24169
  var scriptNameSchema = exports_external.string().min(1).max(200);
@@ -24355,11 +25393,11 @@ async function handleSessionData(req, res, pathSegments, queryParams, _myAgentId
24355
25393
  const rowOutputTokens = bodyModels ? bodyModels.reduce((sum, m) => sum + m.outputTokens, 0) : outputTokens;
24356
25394
  const rowCacheReadTokens = bodyModels ? bodyModels.reduce((sum, m) => sum + m.cacheReadTokens, 0) : cachedInputTokens;
24357
25395
  const rowCacheWriteTokens = bodyModels ? bodyModels.reduce((sum, m) => sum + m.cacheWriteTokens, 0) : parsed.body.cacheWriteTokens ?? 0;
24358
- const harnessCostUsd = parsed.body.totalCostUsd;
25396
+ const harnessCostUsd = parsed.body.totalCostUsd > 0 ? parsed.body.totalCostUsd : null;
24359
25397
  const recomputed = await recomputeSessionCost({
24360
25398
  provider: parsed.body.provider,
24361
25399
  model,
24362
- harnessCostUsd,
25400
+ harnessCostUsd: parsed.body.totalCostUsd,
24363
25401
  inputTokens,
24364
25402
  outputTokens,
24365
25403
  cacheReadTokens: cachedInputTokens,
@@ -24394,7 +25432,7 @@ async function handleSessionData(req, res, pathSegments, queryParams, _myAgentId
24394
25432
  });
24395
25433
  recordSessionCost({
24396
25434
  totalCostUsd,
24397
- harnessCostUsd,
25435
+ harnessCostUsd: harnessCostUsd ?? undefined,
24398
25436
  harness: parsed.body.provider ?? "unknown",
24399
25437
  model,
24400
25438
  costSource,
@@ -25528,7 +26566,8 @@ var SwarmMetricsSchema = exports_external.object({
25528
26566
  retention: exports_external.object({
25529
26567
  sessionLogs: RetentionTableStatsSchema.optional(),
25530
26568
  agentLog: RetentionTableStatsSchema.optional(),
25531
- events: RetentionTableStatsSchema.optional()
26569
+ events: RetentionTableStatsSchema.optional(),
26570
+ contextVersions: RetentionTableStatsSchema.optional()
25532
26571
  })
25533
26572
  });
25534
26573
  var ConcurrentContextSchema = exports_external.object({
@@ -25778,6 +26817,7 @@ async function handleTaskTemplates(req, res, pathSegments, queryParams) {
25778
26817
  init_zod();
25779
26818
  init_db();
25780
26819
  init_steering();
26820
+ init_rbac();
25781
26821
  init_types();
25782
26822
  init_request_auth_context();
25783
26823
  init_secret_scrubber();
@@ -26162,7 +27202,10 @@ var updateTaskProgressRoute = route({
26162
27202
  params: exports_external.object({ id: exports_external.string() }),
26163
27203
  body: exports_external.object({ progress: exports_external.string().min(1) }),
26164
27204
  responses: {
26165
- 200: { description: "Progress updated", schema: exports_external.object({ success: exports_external.literal(true) }) },
27205
+ 200: {
27206
+ description: "Progress updated; a no-op once the task is terminal",
27207
+ schema: exports_external.object({ success: exports_external.literal(true) })
27208
+ },
26166
27209
  403: { description: "Task is assigned to another agent" },
26167
27210
  404: { description: "Task not found" }
26168
27211
  }
@@ -26178,7 +27221,8 @@ var finishTask = route({
26178
27221
  status: exports_external.enum(["completed", "failed"]),
26179
27222
  output: exports_external.string().optional(),
26180
27223
  failureReason: exports_external.string().optional(),
26181
- force: exports_external.boolean().optional()
27224
+ force: exports_external.boolean().optional(),
27225
+ provider: ProviderNameSchema.optional()
26182
27226
  }),
26183
27227
  auth: { apiKey: true, agentId: true },
26184
27228
  responses: {
@@ -26264,7 +27308,7 @@ var updateTaskVcsRoute = route({
26264
27308
  tags: ["Tasks"],
26265
27309
  params: exports_external.object({ id: exports_external.string() }),
26266
27310
  body: exports_external.object({
26267
- vcsProvider: exports_external.enum(["github", "gitlab"]),
27311
+ vcsProvider: exports_external.enum(["github", "gitlab", "azure-devops"]),
26268
27312
  vcsRepo: exports_external.string(),
26269
27313
  vcsNumber: exports_external.number().int().positive(),
26270
27314
  vcsUrl: exports_external.string().url()
@@ -26855,7 +27899,9 @@ async function handleTasks(req, res, pathSegments, queryParams, myAgentId) {
26855
27899
  });
26856
27900
  if (!decision.allow)
26857
27901
  return 403;
26858
- await updateTaskProgress(parsed.params.id, parsed.body.progress);
27902
+ if (!isTerminalTaskStatus(task.status)) {
27903
+ await updateTaskProgress(parsed.params.id, parsed.body.progress);
27904
+ }
26859
27905
  return 200;
26860
27906
  });
26861
27907
  if (status === 404) {
@@ -26897,6 +27943,9 @@ async function handleTasks(req, res, pathSegments, queryParams, myAgentId) {
26897
27943
  return { success: true, task, alreadyFinished: true };
26898
27944
  }
26899
27945
  const wasPaused = task.wasPaused;
27946
+ if (parsed.body.provider && !task.provider) {
27947
+ await recordTaskProviderIfUnset(parsed.params.id, parsed.body.provider);
27948
+ }
26900
27949
  let updatedTask;
26901
27950
  if (parsed.body.status === "completed") {
26902
27951
  const result2 = await completeTask(parsed.params.id, parsed.body.output || "Completed by runner wrapper (no explicit output)");
@@ -28247,7 +29296,7 @@ var deleteIdentityRoute = route({
28247
29296
  },
28248
29297
  auth: { apiKey: true }
28249
29298
  });
28250
- var UNMAPPED_KINDS = ["slack", "github", "gitlab", "linear", "kapso"];
29299
+ var UNMAPPED_KINDS = ["slack", "github", "gitlab", "azure-devops", "linear", "kapso"];
28251
29300
  async function collectUnmappedForKind(kind, limit) {
28252
29301
  const namespace = `integration:unmapped:${kind}`;
28253
29302
  const rows = await listKv(namespace, { limit: Math.min(limit * 2, 1000), offset: 0 });
@@ -28746,7 +29795,7 @@ async function archiveInboundMessage(payload) {
28746
29795
  // src/integrations/kapso/inbound.ts
28747
29796
  init_resolver();
28748
29797
  init_event_bus();
28749
- init_templates();
29798
+ init_templates2();
28750
29799
  var KAPSO_IDENTITY_KIND = "kapso";
28751
29800
  var WHATSAPP_IDENTITY_KIND = "whatsapp";
28752
29801
  function extractText(message) {
@@ -28895,6 +29944,22 @@ var gitlabWebhook = route({
28895
29944
  503: { description: "GitLab integration not configured" }
28896
29945
  }
28897
29946
  });
29947
+ var azureDevOpsWebhook = route({
29948
+ method: "post",
29949
+ path: "/api/azure-devops/webhook",
29950
+ pattern: ["api", "azure-devops", "webhook"],
29951
+ summary: "Handle Azure DevOps service-hook events",
29952
+ tags: ["Webhooks"],
29953
+ auth: { apiKey: false },
29954
+ rbac: {
29955
+ ungated: "provider webhook: authenticated by the service-hook Basic auth secret, not a swarm principal"
29956
+ },
29957
+ responses: {
29958
+ 200: { description: "Event processed", schema: WebhookDispatchResultSchema },
29959
+ 401: { description: "Invalid Basic auth credentials" },
29960
+ 503: { description: "Azure DevOps integration not configured" }
29961
+ }
29962
+ });
28898
29963
  var agentmailWebhook = route({
28899
29964
  method: "post",
28900
29965
  path: "/api/agentmail/webhook",
@@ -29084,13 +30149,13 @@ async function handleWebhooks(req, res, pathSegments) {
29084
30149
  }
29085
30150
  githubWebhook.respond(res, 200, result);
29086
30151
  } catch (err) {
29087
- const errorMessage = err instanceof Error ? err.message : String(err);
29088
- console.error(`[GitHub] Error handling ${eventType} event: ${errorMessage}`);
30152
+ const errorMessage2 = err instanceof Error ? err.message : String(err);
30153
+ console.error(`[GitHub] Error handling ${eventType} event: ${errorMessage2}`);
29089
30154
  if (err instanceof Error && err.stack) {
29090
30155
  console.error(err.stack);
29091
30156
  }
29092
30157
  res.writeHead(500, { "Content-Type": "application/json" });
29093
- res.end(JSON.stringify({ error: "Internal server error", message: errorMessage }));
30158
+ res.end(JSON.stringify({ error: "Internal server error", message: errorMessage2 }));
29094
30159
  }
29095
30160
  return true;
29096
30161
  }
@@ -29187,8 +30252,89 @@ async function handleWebhooks(req, res, pathSegments) {
29187
30252
  }
29188
30253
  gitlabWebhook.respond(res, 200, result);
29189
30254
  } catch (err) {
29190
- const errorMessage = err instanceof Error ? err.message : String(err);
29191
- console.error(`[GitLab] Error handling ${objectKind} event: ${errorMessage}`);
30255
+ const errorMessage2 = err instanceof Error ? err.message : String(err);
30256
+ console.error(`[GitLab] Error handling ${objectKind} event: ${errorMessage2}`);
30257
+ if (err instanceof Error && err.stack) {
30258
+ console.error(err.stack);
30259
+ }
30260
+ res.writeHead(500, { "Content-Type": "application/json" });
30261
+ res.end(JSON.stringify({ error: "Internal server error" }));
30262
+ }
30263
+ return true;
30264
+ }
30265
+ if (azureDevOpsWebhook.match(req.method, pathSegments)) {
30266
+ if (!isAzureDevOpsEnabled()) {
30267
+ res.writeHead(503, { "Content-Type": "application/json" });
30268
+ res.end(JSON.stringify({ error: "Azure DevOps integration not configured" }));
30269
+ return true;
30270
+ }
30271
+ if (!verifyAzureDevOpsWebhook(req.headers.authorization)) {
30272
+ console.log("[AzureDevOps] Invalid webhook credentials");
30273
+ res.writeHead(401, { "Content-Type": "application/json" });
30274
+ res.end(JSON.stringify({ error: "Invalid credentials" }));
30275
+ return true;
30276
+ }
30277
+ const chunks = [];
30278
+ for await (const chunk of req) {
30279
+ chunks.push(chunk);
30280
+ }
30281
+ const rawBody = Buffer.concat(chunks).toString();
30282
+ let body;
30283
+ try {
30284
+ body = JSON.parse(rawBody);
30285
+ } catch {
30286
+ res.writeHead(400, { "Content-Type": "application/json" });
30287
+ res.end(JSON.stringify({ error: "Invalid JSON body" }));
30288
+ return true;
30289
+ }
30290
+ const eventType = body.eventType;
30291
+ console.log(`[AzureDevOps] Received ${eventType} event`);
30292
+ let result = { created: false };
30293
+ try {
30294
+ result = await runBlockableHandler("AzureDevOps", async () => {
30295
+ switch (eventType) {
30296
+ case "git.pullrequest.created":
30297
+ return await handlePullRequestCreated(body);
30298
+ case "ms.vss-code.git-pullrequest-comment-event":
30299
+ return await handlePullRequestCommented(body);
30300
+ default:
30301
+ console.log(`[AzureDevOps] Ignoring unsupported event type: ${eventType}`);
30302
+ return { created: false };
30303
+ }
30304
+ });
30305
+ switch (eventType) {
30306
+ case "git.pullrequest.created": {
30307
+ const pr = createdPullRequestOf(body);
30308
+ if (!pr)
30309
+ break;
30310
+ workflowEventBus.emit("azure-devops.pull_request.created", {
30311
+ repo: canonicalAzureDevOpsRepoUrl(pr.repository.remoteUrl),
30312
+ number: pr.pullRequestId,
30313
+ title: pr.title,
30314
+ body: pr.description,
30315
+ action: "created",
30316
+ user_login: pr.createdBy.uniqueName ?? pr.createdBy.id
30317
+ });
30318
+ break;
30319
+ }
30320
+ case "ms.vss-code.git-pullrequest-comment-event": {
30321
+ const payload = commentedPayloadOf(body);
30322
+ if (!payload)
30323
+ break;
30324
+ const { pullRequest: pr, comment } = payload;
30325
+ workflowEventBus.emit("azure-devops.pull_request.commented", {
30326
+ repo: canonicalAzureDevOpsRepoUrl(pr.repository.remoteUrl),
30327
+ number: pr.pullRequestId,
30328
+ action: "commented",
30329
+ user_login: comment.author.uniqueName ?? comment.author.id
30330
+ });
30331
+ break;
30332
+ }
30333
+ }
30334
+ azureDevOpsWebhook.respond(res, 200, result);
30335
+ } catch (err) {
30336
+ const errorMessage2 = err instanceof Error ? err.message : String(err);
30337
+ console.error(`[AzureDevOps] Error handling ${eventType} event: ${errorMessage2}`);
29192
30338
  if (err instanceof Error && err.stack) {
29193
30339
  console.error(err.stack);
29194
30340
  }
@@ -29256,8 +30402,8 @@ async function handleWebhooks(req, res, pathSegments) {
29256
30402
  console.log(`[AgentMail] Ignoring event type: ${payload.event_type}`);
29257
30403
  }
29258
30404
  } catch (err) {
29259
- const errorMessage = err instanceof Error ? err.message : String(err);
29260
- console.error(`[AgentMail] Error handling ${payload.event_type} event: ${errorMessage}`);
30405
+ const errorMessage2 = err instanceof Error ? err.message : String(err);
30406
+ console.error(`[AgentMail] Error handling ${payload.event_type} event: ${errorMessage2}`);
29261
30407
  if (err instanceof Error && err.stack) {
29262
30408
  console.error(err.stack);
29263
30409
  }
@@ -29317,11 +30463,11 @@ async function handleWebhooks(req, res, pathSegments) {
29317
30463
  }
29318
30464
  kapsoWebhook.respond(res, 200, { received: true, routing: routing.kind });
29319
30465
  } catch (err) {
29320
- const errorMessage = err instanceof Error ? err.message : String(err);
30466
+ const errorMessage2 = err instanceof Error ? err.message : String(err);
29321
30467
  if (err instanceof WebhookError) {
29322
- console.warn(`[Kapso] Workflow dispatch rejected: ${errorMessage}`);
30468
+ console.warn(`[Kapso] Workflow dispatch rejected: ${errorMessage2}`);
29323
30469
  } else {
29324
- console.error(`[Kapso] Error handling inbound event: ${errorMessage}`);
30470
+ console.error(`[Kapso] Error handling inbound event: ${errorMessage2}`);
29325
30471
  }
29326
30472
  kapsoWebhook.respond(res, 200, { received: true, routing: "error" });
29327
30473
  }
@@ -30482,6 +31628,8 @@ var httpServer = createHttpServer(async (req, res) => {
30482
31628
  }
30483
31629
  const handleRequest = async () => {
30484
31630
  setCorsHeaders(req, res);
31631
+ if (isApiDraining())
31632
+ res.setHeader(API_DRAINING_HEADER, "1");
30485
31633
  const queryParams = parseQueryParams(req.url || "");
30486
31634
  const myAgentId = req.headers["x-agent-id"];
30487
31635
  const handlers = [
@@ -30509,8 +31657,10 @@ var httpServer = createHttpServer(async (req, res) => {
30509
31657
  () => handleApps(req, res, pathSegments, queryParams, myAgentId),
30510
31658
  () => handleConfig(req, res, pathSegments, queryParams),
30511
31659
  () => handleFs(req, res, pathSegments, queryParams, myAgentId),
31660
+ () => handleComb(req, res, pathSegments, queryParams, myAgentId),
30512
31661
  () => handleKv(req, res, pathSegments, queryParams),
30513
31662
  () => handleRooms(req, res, pathSegments, queryParams),
31663
+ () => handleRealtimeTicket(req, res, pathSegments, queryParams),
30514
31664
  () => handleRealtimeAsset(req, res),
30515
31665
  () => handleIntegrations(req, res, pathSegments, queryParams),
30516
31666
  () => handlePromptTemplates(req, res, pathSegments, queryParams),
@@ -30603,15 +31753,16 @@ async function shutdown() {
30603
31753
  sessionsProcessed: getServerSessionsProcessed()
30604
31754
  });
30605
31755
  if (hasCapability("scheduling")) {
30606
- const { stopScheduler } = await import("./index-kkv84jq9.js");
31756
+ const { stopScheduler } = await import("./index-qb4q1y3e.js");
30607
31757
  stopScheduler();
30608
31758
  }
30609
31759
  stopHeartbeat();
30610
31760
  stopQueueStallAlarm();
31761
+ await drainApi();
30611
31762
  await stopScriptRunSupervisor();
30612
31763
  await stopSlackApp();
30613
31764
  if (process.env.OAUTH_KEEPALIVE_DISABLE !== "true") {
30614
- const { stopOAuthKeepalive } = await import("./keepalive-yra8dy57.js");
31765
+ const { stopOAuthKeepalive } = await import("./keepalive-xa5ts9cd.js");
30615
31766
  await stopOAuthKeepalive();
30616
31767
  }
30617
31768
  stopOAuthPendingGc();
@@ -30680,15 +31831,15 @@ try {
30680
31831
  console.warn("[startup] CAPABILITIES upgrade seed failed (non-fatal):", err);
30681
31832
  }
30682
31833
  try {
30683
- const { ensurePricingSeeded } = await import("./boot-seeds-gsetbs5y.js");
31834
+ const { ensurePricingSeeded } = await import("./boot-seeds-1skcrs0e.js");
30684
31835
  ensurePricingSeeded();
30685
- const { startPricingRefreshLoop } = await import("./pricing-refresh-wx0tp7cb.js");
31836
+ const { startPricingRefreshLoop } = await import("./pricing-refresh-mth26tgp.js");
30686
31837
  startPricingRefreshLoop();
30687
31838
  } catch (err) {
30688
31839
  console.error("[startup] Failed to seed pricing rows:", err);
30689
31840
  }
30690
31841
  try {
30691
- const { ensureRbacSeeded } = await import("./boot-seeds-gsetbs5y.js");
31842
+ const { ensureRbacSeeded } = await import("./boot-seeds-1skcrs0e.js");
30692
31843
  ensureRbacSeeded();
30693
31844
  } catch (err) {
30694
31845
  console.error("[startup] Failed to sync RBAC seed rows:", err);
@@ -30696,7 +31847,7 @@ try {
30696
31847
  throw err;
30697
31848
  }
30698
31849
  try {
30699
- const { runAllSeeders } = await import("./index-zg7vp46x.js");
31850
+ const { runAllSeeders } = await import("./index-scptvdxg.js");
30700
31851
  await runAllSeeders({ scriptEmbeddingMode: "skip" });
30701
31852
  } catch (err) {
30702
31853
  console.error("[startup] Failed to seed built-in entities:", err);
@@ -30729,10 +31880,15 @@ httpServer.listen(port, async () => {
30729
31880
  if (startupConfigsInjected.length > 0) {
30730
31881
  console.log(`Injected ${startupConfigsInjected.length} swarm_config value(s) into process.env`);
30731
31882
  }
30732
- await initTelemetry("api-server", async (key) => (await getSwarmConfigs({ scope: "global", key }))?.[0]?.value, async (key, value) => {
31883
+ const telemetryGetConfig = async (key) => (await getSwarmConfigs({ scope: "global", key }))?.[0]?.value;
31884
+ const telemetrySetConfig = async (key, value) => {
30733
31885
  await upsertSwarmConfig({ scope: "global", key, value });
30734
- }, { generateIfMissing: true });
31886
+ };
31887
+ await initTelemetry("api-server", telemetryGetConfig, telemetrySetConfig, {
31888
+ generateIfMissing: true
31889
+ });
30735
31890
  telemetry.server("started", { port });
31891
+ startTelemetryTicker({ getConfig: telemetryGetConfig, setConfig: telemetrySetConfig });
30736
31892
  if (process.env.GITHUB_TOKEN) {
30737
31893
  await emitBuiltInIntegrationConnectedOnce("github");
30738
31894
  }
@@ -30744,43 +31900,44 @@ httpServer.listen(port, async () => {
30744
31900
  startQueueStallAlarm();
30745
31901
  initGitHub();
30746
31902
  initGitLab();
31903
+ initAzureDevOps();
30747
31904
  initAgentMail();
30748
31905
  await initLinear();
30749
31906
  await initJira();
30750
31907
  await initWorkflows();
30751
31908
  await startScriptRunSupervisor(getMcpBaseUrl());
30752
31909
  if (hasCapability("scheduling")) {
30753
- const { startScheduler } = await import("./index-kkv84jq9.js");
30754
- const { getExecutorRegistry: getExecutorRegistry2 } = await import("./index-fg0dsp6c.js");
31910
+ const { startScheduler } = await import("./index-qb4q1y3e.js");
31911
+ const { getExecutorRegistry: getExecutorRegistry2 } = await import("./index-dqmp15bq.js");
30755
31912
  const intervalMs = Number(process.env.SCHEDULER_INTERVAL_MS) || 1e4;
30756
31913
  startScheduler(getExecutorRegistry2(), intervalMs, {
30757
31914
  runId: globalState.__runId
30758
31915
  });
30759
31916
  }
30760
31917
  if (!isEnvFlagEnabled("HEARTBEAT_DISABLE", false)) {
30761
- const { startHeartbeat } = await import("./index-668me3f0.js");
31918
+ const { startHeartbeat } = await import("./index-8fd4dm4h.js");
30762
31919
  const heartbeatMs = Number(process.env.HEARTBEAT_INTERVAL_MS) || 90000;
30763
31920
  startHeartbeat(heartbeatMs);
30764
31921
  }
30765
31922
  if (process.env.OAUTH_KEEPALIVE_DISABLE !== "true") {
30766
- const { startOAuthKeepalive } = await import("./keepalive-yra8dy57.js");
31923
+ const { startOAuthKeepalive } = await import("./keepalive-xa5ts9cd.js");
30767
31924
  startOAuthKeepalive();
30768
31925
  }
30769
31926
  if (process.env.OAUTH_REFRESH_SWEEP_DISABLE !== "true") {
30770
- const { startOAuthRefreshSweep } = await import("./oauth-refresh-sweep-7rdt1m9n.js");
31927
+ const { startOAuthRefreshSweep } = await import("./oauth-refresh-sweep-1csdfebf.js");
30771
31928
  startOAuthRefreshSweep();
30772
31929
  }
30773
31930
  startOAuthPendingGc();
30774
31931
  await startMemoryGc();
30775
31932
  await startDbRetention();
30776
31933
  startHumanFreeDrain();
30777
- import("./boot-reembed-cqz9swn5.js").then(({ runBootReembed }) => runBootReembed()).catch((err) => {
31934
+ import("./boot-reembed-nxpcvpj9.js").then(({ runBootReembed }) => runBootReembed()).catch((err) => {
30778
31935
  console.error("[boot-reembed] startup backfill failed (non-fatal):", err);
30779
31936
  });
30780
- import("./boot-reembed-m3656j2n.js").then(({ runBootReembedScripts }) => runBootReembedScripts()).catch((err) => {
31937
+ import("./boot-reembed-4ht4gqth.js").then(({ runBootReembedScripts }) => runBootReembedScripts()).catch((err) => {
30781
31938
  console.error("[boot-reembed-scripts] startup backfill failed (non-fatal):", err);
30782
31939
  });
30783
- import("./boot-scrub-logs-xbxf5d7w.js").then(({ runBootScrubLogs }) => runBootScrubLogs()).catch((err) => {
31940
+ import("./boot-scrub-logs-k93kyw8k.js").then(({ runBootScrubLogs }) => runBootScrubLogs()).catch((err) => {
30784
31941
  console.error("[boot-scrub-logs] startup scrub failed (non-fatal):", err);
30785
31942
  });
30786
31943
  }).on("error", (err) => {