@desplega.ai/agent-swarm 1.161.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.
- package/README.md +3 -2
- package/dist/{acp-adapter-xx489vvb.js → acp-adapter-74m73ae9.js} +1 -1
- package/dist/{actions-ykjkn0m9.js → actions-4sr14gnt.js} +34 -31
- package/dist/{anthropic-messages-5qx80j9k.js → anthropic-messages-8xxrzky9.js} +22 -26
- package/dist/{app-0hdqa4k1.js → app-pt68fbwp.js} +13 -11
- package/dist/{artifact-3v5t9jtg.js → artifact-fey7dvj9.js} +3 -2
- package/dist/{assistant-am2g5g8a.js → assistant-cv3jytks.js} +37 -34
- package/dist/{azure-openai-responses-fszbkp0e.js → azure-openai-responses-f5cqsyj8.js} +15 -10
- package/dist/{boot-reembed-xy9t7avg.js → boot-reembed-4ht4gqth.js} +13 -11
- package/dist/{boot-reembed-gt5gjkt4.js → boot-reembed-nxpcvpj9.js} +12 -10
- package/dist/{boot-scrub-logs-9x0985y5.js → boot-scrub-logs-k93kyw8k.js} +9 -7
- package/dist/{boot-seeds-trv0d4vg.js → boot-seeds-1skcrs0e.js} +13 -10
- package/dist/{claude-adapter-jb6e1e54.js → claude-adapter-r5g0tzge.js} +23 -20
- package/dist/{claude-managed-setup-d1q9hv2b.js → claude-managed-setup-pkyrgshb.js} +3 -2
- package/dist/{claude-sdk-session-zga700s2.js → claude-sdk-session-jxyxnrwd.js} +5565 -5512
- package/dist/{cli-we0q7t0e.js → cli-2zy95vhm.js} +137 -64
- package/dist/{cli-35pj2yva.js → cli-4cwxn7gp.js} +38 -11
- package/dist/{cli-ad4qxm6j.js → cli-4dcpaefp.js} +2 -2
- package/dist/{cli-82c1pacn.js → cli-4x0csdjq.js} +71 -37
- package/dist/{cli-sqm3r5ps.js → cli-5bcd7sfy.js} +14 -18
- package/dist/{cli-d56tgd45.js → cli-5k6k8ta3.js} +2 -2
- package/dist/{cli-1er0rhz8.js → cli-5xhpb3kv.js} +15 -15
- package/dist/{cli-yrg7c73k.js → cli-7af8yhav.js} +10 -183
- package/dist/{cli-r6fsxc76.js → cli-7tre70zp.js} +513 -961
- package/dist/{cli-bh7jed3k.js → cli-8ev9xqnx.js} +34 -18
- package/dist/cli-bsky8g7w.js +449 -0
- package/dist/{cli-hn04t9db.js → cli-cebmgwsc.js} +14 -10
- package/dist/{cli-cfkrztza.js → cli-cvatsam7.js} +2 -2
- package/dist/{cli-2658f6at.js → cli-cvk6yzw5.js} +6 -8
- package/dist/{cli-ptr8h7kp.js → cli-eg0b3p0k.js} +5 -218
- package/dist/{cli-zb6xbk61.js → cli-g739zqzt.js} +4 -4
- package/dist/{cli-dv6cdjs2.js → cli-gd4favx9.js} +28 -7
- package/dist/{cli-5p3x4zna.js → cli-gpqpmns7.js} +2 -2
- package/dist/{cli-5nbmpy8w.js → cli-hb5c2x5y.js} +1 -1
- package/dist/{cli-jpf7e1zq.js → cli-hmsw1gpy.js} +3 -3
- package/dist/{cli-1cz0c18q.js → cli-jf7wmv1r.js} +2521 -733
- package/dist/{cli-qwsnmjdd.js → cli-jxs2ygaw.js} +168 -61
- package/dist/cli-kdkwd3yr.js +615 -0
- package/dist/{cli-hgmnf38m.js → cli-kh04eqwe.js} +1 -1
- package/dist/{cli-0383bp7f.js → cli-kp42yek0.js} +425 -90
- package/dist/{cli-ybgv4kw2.js → cli-mbssg1xv.js} +9 -2
- package/dist/{cli-jsp14b6c.js → cli-mzfth0bp.js} +38 -1
- package/dist/{cli-8g6mc14k.js → cli-nq7yqw7b.js} +16 -5
- package/dist/{cli-ee8bc46j.js → cli-nt8hecg9.js} +33 -32
- package/dist/{cli-9s68w752.js → cli-p0r8sxj5.js} +1 -1
- package/dist/{cli-58e8yr0d.js → cli-pkd6s2wy.js} +4 -2
- package/dist/{cli-17xpf7cm.js → cli-q24re23n.js} +6 -4
- package/dist/cli-qjjvzwzd.js +222 -0
- package/dist/cli-qrgt5bqf.js +189 -0
- package/dist/{cli-et8m9xsv.js → cli-rfjw9jw2.js} +22 -10
- package/dist/{cli-798vkbks.js → cli-rj0gqwwp.js} +2 -2
- package/dist/{cli-121ph74b.js → cli-rnyzn44p.js} +1 -1
- package/dist/{cli-vnnz5ncg.js → cli-s3hwpt9v.js} +95 -16
- package/dist/{cli-7119ja3w.js → cli-sptrj5f5.js} +2 -2
- package/dist/{cli-a8c82p2t.js → cli-sqvfa090.js} +13 -6
- package/dist/{cli-phfg8vy8.js → cli-swfmp1fx.js} +26 -26
- package/dist/{cli-nsdxtcbg.js → cli-tcen9p5w.js} +8 -5
- package/dist/{cli-9m03pzga.js → cli-vc9bp061.js} +5 -5
- package/dist/{cli-rtx9dygp.js → cli-vxe6qa4h.js} +1 -1
- package/dist/{cli-ecfxwnyb.js → cli-vy3ed88x.js} +1 -1
- package/dist/{cli-0c7ata9h.js → cli-vyqs9ya8.js} +6 -6
- package/dist/cli-wbvnn6tk.js +861 -0
- package/dist/{cli-kgd3p0bm.js → cli-wjgs5wxe.js} +6 -6
- package/dist/cli-wxkkd0e0.js +33 -0
- package/dist/{cli-akfj32vj.js → cli-xqpk3rp7.js} +5 -4
- package/dist/cli-zp38xvtm.js +9487 -0
- package/dist/{cli-3zc55ctx.js → cli-zvhd3f64.js} +2 -2
- package/dist/{cli-ze1d3wzv.js → cli-zxqx25nz.js} +5 -5
- package/dist/cli.js +32 -25
- package/dist/{cloudflare-workers-ai-system-one-k6fbxw9d.js → cloudflare-workers-ai-system-one-k8ddqjkq.js} +8 -6
- package/dist/{codex-adapter-04v97vep.js → codex-adapter-esvmnhn7.js} +13 -13
- package/dist/{codex-hook-20me6byw.js → codex-hook-m73jmqgx.js} +19 -3
- package/dist/{codex-session-runner-ax69mqq3.js → codex-session-runner-ban9excr.js} +13 -13
- package/dist/{commands-18gy08n1.js → commands-75413p2n.js} +9 -7
- package/dist/{db-d2pvjpyt.js → db-7f5pecwg.js} +11 -7
- package/dist/{dispatcher-8wbwyzjg.js → dispatcher-fh9at8nz.js} +33 -30
- package/dist/{dsh-adapter-ysqk9snv.js → dsh-adapter-wpze65d4.js} +3 -3
- package/dist/{e2b-esmt1r16.js → e2b-gjgdjp91.js} +10 -9
- package/dist/{pi-logo-animation-e9a0t68z.js → easter-egg-3d-3w5c2n4c.js} +122 -68
- package/dist/{execute-cmagrbrz.js → execute-f50wg9nh.js} +29 -6
- package/dist/{google-generative-ai-k6n5nbpp.js → google-generative-ai-jxxpnegy.js} +2 -2
- package/dist/{google-vertex-44xxtcvp.js → google-vertex-x7q1angm.js} +5 -5
- package/dist/{handlers-6b69m5kp.js → handlers-w13787bb.js} +36 -33
- package/dist/{hook-srnkt0hb.js → hook-46g1jrvx.js} +28 -15
- package/dist/{hook-k3mydf2n.js → hook-4tpts2ry.js} +20 -17
- package/dist/{http-hrf80ca1.js → http-19pzbfrt.js} +964 -176
- package/dist/{index-9rxdvj6w.js → index-8fd4dm4h.js} +34 -31
- package/dist/{index-1asbaj62.js → index-dqmp15bq.js} +35 -32
- package/dist/{index-45evq4ee.js → index-qb4q1y3e.js} +33 -30
- package/dist/{index-k4nj18qs.js → index-s75wc4wd.js} +12 -10
- package/dist/{index-xmevk2b9.js → index-scptvdxg.js} +27 -25
- package/dist/{keepalive-sfdz6ksp.js → keepalive-xa5ts9cd.js} +11 -9
- package/dist/{lead-ej91e9hw.js → lead-qp4xkvjq.js} +45 -41
- package/dist/{maintenance-80dnd7ke.js → maintenance-rm5885hm.js} +13 -11
- package/dist/{mistral-conversations-pc3ntnxt.js → mistral-conversations-rw7fbt22.js} +4 -4
- package/dist/{node-a5e00qhp.js → node-8zkdq42h.js} +834 -833
- package/dist/{oauth-refresh-sweep-m1etk2mx.js → oauth-refresh-sweep-1csdfebf.js} +10 -8
- package/dist/{onboard-0q8sdfqc.js → onboard-r6b78cs4.js} +10 -10
- package/dist/{openai-codex-responses-n7n683p2.js → openai-codex-responses-efvrgrq3.js} +4 -4
- package/dist/{openai-completions-jpaj5g2b.js → openai-completions-bbbrrz4z.js} +12 -8
- package/dist/{openai-responses-9a3nme9j.js → openai-responses-9jjyrcm1.js} +15 -10
- package/dist/{opencode-adapter-4wcgmvgf.js → opencode-adapter-kb3g6pkf.js} +2 -2
- package/dist/{otel-impl-hnqm9mxq.js → otel-impl-0y9knpky.js} +5 -5
- package/dist/{pi-mono-adapter-d6sqm9wr.js → pi-mono-adapter-z6s1bme2.js} +100 -19
- package/dist/{pricing-refresh-y60z64pm.js → pricing-refresh-mth26tgp.js} +11 -9
- package/dist/{rbac-roles-8pa0754b.js → rbac-roles-kwntb23q.js} +13 -9
- package/dist/rbac-roles-vpk4ebm8.js +45 -0
- package/dist/{registry-v5wytg0s.js → registry-km6t1jd2.js} +1 -1
- package/dist/{render-v2-418s1vj7.js → render-v2-hcm7h00y.js} +13 -11
- package/dist/{runtime-3pknc168.js → runtime-vfjsfsc5.js} +4 -4
- package/dist/{setup-yghdkj4x.js → setup-hbyzd65h.js} +2 -2
- package/dist/{virtual-modules-jcceevt5.js → virtual-modules-9bv7ry91.js} +9 -8
- package/dist/{work-objects-j1sz20v9.js → work-objects-m09sxnhe.js} +36 -33
- package/dist/{worker-d4gcvkjt.js → worker-0h35rvk4.js} +45 -41
- package/openapi.json +491 -12
- package/package.json +13 -6
- package/src/be/api-drain.ts +184 -0
- package/src/be/db/tasks/read.ts +31 -6
- package/src/be/db/tasks/write.ts +5 -4
- package/src/be/db.ts +42 -18
- package/src/be/memory/link-resolver.ts +29 -3
- package/src/be/migrations/192_favorites_agent_fs_path.sql +36 -0
- package/src/be/onboarding.ts +7 -1
- package/src/be/seed-prompt-templates.ts +1 -0
- package/src/be/swarm-config-guard.ts +35 -16
- package/src/be/task-citations.ts +11 -5
- package/src/be/users.ts +3 -0
- package/src/cli.tsx +3 -2
- package/src/comb/agent-fs.ts +39 -0
- package/src/comb/config.ts +37 -0
- package/src/comb/markers.ts +37 -0
- package/src/comb/review-batch.ts +486 -0
- package/src/comb/templates.ts +88 -0
- package/src/commands/context-preamble.ts +4 -1
- package/src/commands/hook.ts +2 -1
- package/src/commands/runner.ts +262 -68
- package/src/commands/templates.ts +10 -0
- package/src/extensions/contract-types.generated.ts +1 -1
- package/src/fs/agent-fs-provider.ts +106 -2
- package/src/heartbeat/heartbeat.ts +4 -0
- package/src/hooks/codex-hook.ts +25 -1
- package/src/hooks/hook.ts +13 -0
- package/src/hooks/pr-body-guard.ts +983 -0
- package/src/http/all-routes.ts +1 -0
- package/src/http/assets.ts +5 -17
- package/src/http/comb.ts +131 -0
- package/src/http/core.ts +2 -1
- package/src/http/fs.ts +9 -17
- package/src/http/index.ts +23 -9
- package/src/http/onboarding.ts +21 -2
- package/src/http/poll.ts +30 -3
- package/src/http/realtime.ts +62 -0
- package/src/http/request-principal.ts +22 -0
- package/src/http/status.ts +34 -2
- package/src/kv-reserved-namespaces.ts +10 -5
- package/src/providers/dsh-adapter.ts +1 -1
- package/src/providers/pi-mono-adapter.ts +123 -0
- package/src/rbac/legacy-policy.ts +1 -0
- package/src/rbac/permissions.ts +4 -0
- package/src/realtime/auth.ts +63 -1
- package/src/realtime/tickets.ts +52 -0
- package/src/realtime/transport.ts +51 -22
- package/src/scripts-runtime/types/swarm-extension.d.ts +3 -1
- package/src/telemetry-context.ts +175 -0
- package/src/telemetry-contract/EVENTS.md +81 -0
- package/src/telemetry-contract/SOURCE.json +9 -0
- package/src/telemetry-contract/catalog.json +1335 -0
- package/src/telemetry-contract/index.ts +60 -0
- package/src/telemetry-contract/types.gen.ts +1971 -0
- package/src/telemetry-identity.ts +129 -0
- package/src/telemetry-snapshot.ts +211 -0
- package/src/telemetry-trigger.ts +125 -0
- package/src/telemetry-types.typetest.ts +40 -0
- package/src/telemetry.ts +271 -67
- package/src/tests/api-drain-e2e.test.ts +249 -0
- package/src/tests/api-drain-worker-e2e.test.ts +216 -0
- package/src/tests/api-drain.test.ts +351 -0
- package/src/tests/comb-config-guard.test.ts +38 -0
- package/src/tests/comb-links.test.ts +162 -0
- package/src/tests/comb-markers.test.ts +68 -0
- package/src/tests/comb-review-batch.test.ts +770 -0
- package/src/tests/comb-status.test.ts +152 -0
- package/src/tests/db-task-read-contract.test.ts +2 -0
- package/src/tests/db-task-write-contract.test.ts +1 -0
- package/src/tests/docs-index-footprint.test.js +3 -3
- package/src/tests/dsh-adapter.test.ts +1 -1
- package/src/tests/favorites-agent-fs-path.test.ts +226 -0
- package/src/tests/memory-link-resolver.test.ts +34 -0
- package/src/tests/onboarding.test.ts +108 -0
- package/src/tests/pi-mono-adapter.test.ts +265 -2
- package/src/tests/pr-body-leaks.test.ts +789 -0
- package/src/tests/preload.ts +8 -0
- package/src/tests/rbac-engine.test.ts +19 -0
- package/src/tests/realtime-room-auth.test.ts +104 -1
- package/src/tests/realtime-tickets.test.ts +74 -0
- package/src/tests/realtime-transport.test.ts +131 -4
- package/src/tests/runner-api-drain.test.ts +301 -0
- package/src/tests/runner-fallback-output.test.ts +61 -0
- package/src/tests/runner-fenced-json-output.test.ts +178 -0
- package/src/tests/script-connections.test.ts +2 -0
- package/src/tests/send-task-requested-by.test.ts +133 -15
- package/src/tests/task-lifecycle-telemetry.test.ts +8 -3
- package/src/tests/telemetry-context.test.ts +314 -0
- package/src/tests/telemetry-init.test.ts +51 -19
- package/src/tests/telemetry-snapshot.test.ts +229 -0
- package/src/tests/telemetry-trigger.test.ts +200 -0
- package/src/tests/template-registry-helpers.ts +1 -0
- package/src/tests/workflow-agent-task-retry.test.ts +363 -0
- package/src/tests/workflow-definition-telemetry.test.ts +4 -4
- package/src/tools/poll-task.ts +20 -1
- package/src/tools/send-task.ts +9 -1
- package/src/tools/task-action.ts +11 -0
- package/src/types.ts +2 -1
- package/src/utils/api-drain.ts +24 -0
- package/src/utils/constants.ts +57 -16
- package/src/utils/pr-body-leaks.ts +172 -0
- package/src/utils/task-attachment-links.ts +14 -8
- package/src/workflows/recovery.ts +26 -1
- package/src/workflows/resume.ts +31 -4
- package/src/workflows/task-step-routing.ts +75 -2
- package/tsconfig.json +3 -0
- package/dist/cli-tjf4cn8z.js +0 -9119
- package/dist/cli-tsk3nz8a.js +0 -582
- package/dist/{cli-t6v2ah3r.js → cli-twrh04ap.js} +3 -3
|
@@ -24,12 +24,12 @@ import {
|
|
|
24
24
|
import {
|
|
25
25
|
ensureAgentFsCredentialsForAgent,
|
|
26
26
|
inviteEmailToSharedOrg
|
|
27
|
-
} from "./cli-
|
|
27
|
+
} from "./cli-rj0gqwwp.js";
|
|
28
28
|
import {
|
|
29
29
|
checkHeartbeatChecklist,
|
|
30
30
|
runHeartbeatSweep,
|
|
31
31
|
stopHeartbeat
|
|
32
|
-
} from "./cli-
|
|
32
|
+
} from "./cli-q24re23n.js";
|
|
33
33
|
import {
|
|
34
34
|
Anthropic
|
|
35
35
|
} from "./cli-ma3zvh39.js";
|
|
@@ -100,6 +100,7 @@ import {
|
|
|
100
100
|
describeRequestRoute,
|
|
101
101
|
disableExtension,
|
|
102
102
|
dispatchScheduleTarget,
|
|
103
|
+
drainApi,
|
|
103
104
|
emitBudgetRefusalSideEffects,
|
|
104
105
|
enableExtension,
|
|
105
106
|
enforceContentLengthCap,
|
|
@@ -116,6 +117,7 @@ import {
|
|
|
116
117
|
flushAuditBuffer,
|
|
117
118
|
getAgentHarnessCliVersion,
|
|
118
119
|
getAutomationSetupStates,
|
|
120
|
+
getCombConfig,
|
|
119
121
|
getEnabledCapabilities,
|
|
120
122
|
getEventCountsFiltered,
|
|
121
123
|
getEventsFiltered,
|
|
@@ -178,6 +180,7 @@ import {
|
|
|
178
180
|
initWorkflows,
|
|
179
181
|
installExtensionWithAssets,
|
|
180
182
|
isAgentMailEnabled,
|
|
183
|
+
isApiDraining,
|
|
181
184
|
isAzureDevOpsEnabled,
|
|
182
185
|
isGitHubEnabled,
|
|
183
186
|
isGitLabEnabled,
|
|
@@ -314,7 +317,7 @@ import {
|
|
|
314
317
|
wireHttpSpanLifecycle,
|
|
315
318
|
workflowModelErrors,
|
|
316
319
|
workflowSaveWarnings
|
|
317
|
-
} from "./cli-
|
|
320
|
+
} from "./cli-kp42yek0.js";
|
|
318
321
|
import"./cli-cat6h73s.js";
|
|
319
322
|
import {
|
|
320
323
|
RATING_MODEL_MAX_LENGTH,
|
|
@@ -324,12 +327,16 @@ import {
|
|
|
324
327
|
import {
|
|
325
328
|
isMultiRuntimeEnabled
|
|
326
329
|
} from "./cli-re8z5p8p.js";
|
|
330
|
+
import"./cli-wxkkd0e0.js";
|
|
327
331
|
import {
|
|
328
332
|
deleteModelCatalogOverlay,
|
|
329
333
|
loadModelsCatalog,
|
|
330
334
|
requestModelCatalogRefresh,
|
|
331
335
|
upsertModelCatalogOverlay
|
|
332
|
-
} from "./cli-
|
|
336
|
+
} from "./cli-zvhd3f64.js";
|
|
337
|
+
import {
|
|
338
|
+
normalizeModelKey
|
|
339
|
+
} from "./cli-vy3ed88x.js";
|
|
333
340
|
import {
|
|
334
341
|
ConnectionAuthInputSchema,
|
|
335
342
|
MAX_SCRIPT_WALL_CLOCK_MS,
|
|
@@ -422,8 +429,11 @@ import {
|
|
|
422
429
|
upsertScriptByName,
|
|
423
430
|
upsertScriptConnection,
|
|
424
431
|
validateDefinition
|
|
425
|
-
} from "./cli-
|
|
432
|
+
} from "./cli-5xhpb3kv.js";
|
|
426
433
|
import"./cli-epan13p1.js";
|
|
434
|
+
import {
|
|
435
|
+
getApiKey
|
|
436
|
+
} from "./cli-f14fvzag.js";
|
|
427
437
|
import {
|
|
428
438
|
detachedProcessGroup,
|
|
429
439
|
forceTerminateProcessGroup,
|
|
@@ -431,10 +441,7 @@ import {
|
|
|
431
441
|
signalProcessGroup,
|
|
432
442
|
terminateProcessGroup
|
|
433
443
|
} from "./cli-y89t4nca.js";
|
|
434
|
-
import
|
|
435
|
-
getApiKey
|
|
436
|
-
} from "./cli-f14fvzag.js";
|
|
437
|
-
import"./cli-sqm3r5ps.js";
|
|
444
|
+
import"./cli-5bcd7sfy.js";
|
|
438
445
|
import {
|
|
439
446
|
CLIENT_ID,
|
|
440
447
|
MAX_CODEX_OAUTH_SLOT,
|
|
@@ -448,16 +455,32 @@ import {
|
|
|
448
455
|
} from "./cli-yy6dew39.js";
|
|
449
456
|
import"./cli-3dpj7atn.js";
|
|
450
457
|
import"./cli-2x0e561b.js";
|
|
451
|
-
import"./cli-
|
|
458
|
+
import"./cli-nt8hecg9.js";
|
|
452
459
|
import"./cli-rb9m6rpe.js";
|
|
453
460
|
import {
|
|
461
|
+
AgentFsProvider,
|
|
454
462
|
FilesError,
|
|
463
|
+
agentFsRequestTimeoutMs,
|
|
455
464
|
getFileStorageProvider,
|
|
456
465
|
normalizeFilesError
|
|
457
|
-
} from "./cli-
|
|
466
|
+
} from "./cli-mzfth0bp.js";
|
|
458
467
|
import {
|
|
459
468
|
searchScripts
|
|
460
|
-
} from "./cli-
|
|
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";
|
|
461
484
|
import {
|
|
462
485
|
acquireOAuthRefreshLock,
|
|
463
486
|
buildAuthorizationUrl,
|
|
@@ -481,36 +504,8 @@ import {
|
|
|
481
504
|
updateAuthorizationIdentity,
|
|
482
505
|
updateOAuthAppById,
|
|
483
506
|
upsertAuthorization
|
|
484
|
-
} from "./cli-
|
|
485
|
-
import {
|
|
486
|
-
getUserGrant
|
|
487
|
-
} from "./cli-we0q7t0e.js";
|
|
488
|
-
import {
|
|
489
|
-
LEGACY_RULES,
|
|
490
|
-
can,
|
|
491
|
-
clearAuditSink,
|
|
492
|
-
decideToolAdmission,
|
|
493
|
-
isRbacEnabled,
|
|
494
|
-
setAuditSink
|
|
495
|
-
} from "./cli-tsk3nz8a.js";
|
|
496
|
-
import {
|
|
497
|
-
normalizeModelKey
|
|
498
|
-
} from "./cli-ecfxwnyb.js";
|
|
507
|
+
} from "./cli-kh04eqwe.js";
|
|
499
508
|
import"./cli-fad8m16k.js";
|
|
500
|
-
import {
|
|
501
|
-
CANDIDATE_SET_MULTIPLIER,
|
|
502
|
-
EMBEDDING_DIMENSIONS,
|
|
503
|
-
MEMORY_KEY_MAX_LENGTH,
|
|
504
|
-
OpenAI,
|
|
505
|
-
getEmbeddingProvider,
|
|
506
|
-
getMemoryStore,
|
|
507
|
-
init_constants as init_constants2,
|
|
508
|
-
init_key_paths,
|
|
509
|
-
init_openai,
|
|
510
|
-
init_reranker,
|
|
511
|
-
rerank
|
|
512
|
-
} from "./cli-d56tgd45.js";
|
|
513
|
-
import"./cli-hn04t9db.js";
|
|
514
509
|
import"./cli-bsakbbkm.js";
|
|
515
510
|
import"./cli-trc24wk2.js";
|
|
516
511
|
import"./cli-51tf7ac3.js";
|
|
@@ -533,12 +528,49 @@ import {
|
|
|
533
528
|
withRemoteContext,
|
|
534
529
|
withSpan,
|
|
535
530
|
withSpanContext
|
|
536
|
-
} from "./cli-
|
|
531
|
+
} from "./cli-swfmp1fx.js";
|
|
537
532
|
import"./cli-q51yprfq.js";
|
|
538
533
|
import"./cli-3er6gcsn.js";
|
|
539
|
-
import"./cli-
|
|
534
|
+
import"./cli-cvk6yzw5.js";
|
|
540
535
|
import"./cli-yatxqynm.js";
|
|
541
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,
|
|
542
574
|
CODEX_AUTH_WATCH_NAMESPACE,
|
|
543
575
|
CredentialBindingSchema,
|
|
544
576
|
DB_RETENTION_TUNING_BOUNDS,
|
|
@@ -555,6 +587,7 @@ import {
|
|
|
555
587
|
agentContextKey,
|
|
556
588
|
auditAssetKeys,
|
|
557
589
|
backfillSupersedeTaskResumeTaskId,
|
|
590
|
+
cachedUserRole,
|
|
558
591
|
cancelTask,
|
|
559
592
|
checkoutPromptTemplate,
|
|
560
593
|
claimKv,
|
|
@@ -568,6 +601,7 @@ import {
|
|
|
568
601
|
codexAuthBenchMarkerKey,
|
|
569
602
|
completeTask,
|
|
570
603
|
computeContentHash,
|
|
604
|
+
configureOrgDomainPersistence,
|
|
571
605
|
countActiveScriptRuns,
|
|
572
606
|
countAllMetrics,
|
|
573
607
|
countAllPages,
|
|
@@ -617,6 +651,7 @@ import {
|
|
|
617
651
|
emitBuiltInIntegrationConnectedOnce,
|
|
618
652
|
emitIntegrationConnected,
|
|
619
653
|
emitMcpServerConnectedTelemetry,
|
|
654
|
+
emitTaskTelemetry,
|
|
620
655
|
encryptSecret,
|
|
621
656
|
extensionAgentAssignmentError,
|
|
622
657
|
failTask,
|
|
@@ -647,6 +682,7 @@ import {
|
|
|
647
682
|
getContextSnapshotsByTaskId,
|
|
648
683
|
getContextSummaryByTaskId,
|
|
649
684
|
getCurrentRequestAuth,
|
|
685
|
+
getCurrentRequestUserId,
|
|
650
686
|
getDashboardCostSummary,
|
|
651
687
|
getDb,
|
|
652
688
|
getDbClient,
|
|
@@ -729,6 +765,7 @@ import {
|
|
|
729
765
|
incrKv,
|
|
730
766
|
incrementPageViewCount,
|
|
731
767
|
initTelemetry,
|
|
768
|
+
init_api_drain,
|
|
732
769
|
init_asset_key_audit,
|
|
733
770
|
init_codex_auth_failure,
|
|
734
771
|
init_context_key,
|
|
@@ -740,11 +777,15 @@ import {
|
|
|
740
777
|
init_heartbeat_expiry,
|
|
741
778
|
init_human_free,
|
|
742
779
|
init_request_auth_context,
|
|
780
|
+
init_runtime,
|
|
743
781
|
init_steering,
|
|
744
782
|
init_swarm_config_guard,
|
|
745
783
|
init_task_tool_manifest,
|
|
746
784
|
init_telemetry,
|
|
785
|
+
init_telemetry_identity,
|
|
786
|
+
init_telemetry_trigger,
|
|
747
787
|
init_templates,
|
|
788
|
+
init_templates1 as init_templates2,
|
|
748
789
|
insertActiveSession,
|
|
749
790
|
insertPricingRow,
|
|
750
791
|
installMcpServer,
|
|
@@ -755,6 +796,7 @@ import {
|
|
|
755
796
|
isReservedConfigKey,
|
|
756
797
|
isSteeringEnabled as isSteeringEnabled2,
|
|
757
798
|
isTelemetryEnabled,
|
|
799
|
+
isTelemetryReady,
|
|
758
800
|
listAgentsWithCredStatusByProvider,
|
|
759
801
|
listAllMetrics,
|
|
760
802
|
listAllPages,
|
|
@@ -787,6 +829,7 @@ import {
|
|
|
787
829
|
pauseTask,
|
|
788
830
|
placeholderForConfigKey,
|
|
789
831
|
promoteDraftTask,
|
|
832
|
+
recomputeOrgDomain,
|
|
790
833
|
recordBudgetRefusalNotification,
|
|
791
834
|
recordInlineScriptRun,
|
|
792
835
|
recordKeyAuthFailure,
|
|
@@ -801,6 +844,7 @@ import {
|
|
|
801
844
|
resetPromptTemplateToDefault,
|
|
802
845
|
resolveApprovalRequest,
|
|
803
846
|
resolvePromptTemplate,
|
|
847
|
+
resolveTriggerSurface,
|
|
804
848
|
resumeTask,
|
|
805
849
|
searchSkills,
|
|
806
850
|
selectTaskTools,
|
|
@@ -810,6 +854,7 @@ import {
|
|
|
810
854
|
setFavorite,
|
|
811
855
|
setHumanFreeQueueListener,
|
|
812
856
|
setRequestAuth,
|
|
857
|
+
setTelemetryRoleResolver,
|
|
813
858
|
settleSupersededTaskDependents,
|
|
814
859
|
startTask,
|
|
815
860
|
supersedeTask,
|
|
@@ -854,8 +899,7 @@ import {
|
|
|
854
899
|
upsertSwarmConfig,
|
|
855
900
|
validateConfigValue,
|
|
856
901
|
withFavoriteFlags
|
|
857
|
-
} from "./cli-
|
|
858
|
-
import"./cli-3qhyh31j.js";
|
|
902
|
+
} from "./cli-jf7wmv1r.js";
|
|
859
903
|
import {
|
|
860
904
|
ActiveSessionSchema,
|
|
861
905
|
AgentAcpStatusSchema,
|
|
@@ -982,28 +1026,22 @@ import {
|
|
|
982
1026
|
isSafeBundlePath,
|
|
983
1027
|
isTerminalTaskStatus,
|
|
984
1028
|
splitLegacyModelAlias
|
|
985
|
-
} from "./cli-
|
|
1029
|
+
} from "./cli-xqpk3rp7.js";
|
|
1030
|
+
import"./cli-3qhyh31j.js";
|
|
986
1031
|
import {
|
|
987
1032
|
IDENTITY_FIELD_BUDGETS,
|
|
988
1033
|
IdentityFieldBudgetError,
|
|
989
1034
|
init_identity_field_budget
|
|
990
|
-
} from "./cli-
|
|
991
|
-
import {
|
|
992
|
-
getAllTemplateDefinitions,
|
|
993
|
-
getTemplateDefinition,
|
|
994
|
-
init_registry,
|
|
995
|
-
init_resolver,
|
|
996
|
-
init_steering_enabled,
|
|
997
|
-
init_template,
|
|
998
|
-
interpolate,
|
|
999
|
-
isSteeringEnabled,
|
|
1000
|
-
resolveTemplate
|
|
1001
|
-
} from "./cli-ptr8h7kp.js";
|
|
1002
|
-
import"./cli-xk79303e.js";
|
|
1035
|
+
} from "./cli-7af8yhav.js";
|
|
1003
1036
|
import {
|
|
1004
1037
|
getSlackConfiguration,
|
|
1005
1038
|
init_config
|
|
1006
1039
|
} from "./cli-n7h1kqpf.js";
|
|
1040
|
+
import {
|
|
1041
|
+
init_steering_enabled,
|
|
1042
|
+
isSteeringEnabled
|
|
1043
|
+
} from "./cli-eg0b3p0k.js";
|
|
1044
|
+
import"./cli-xk79303e.js";
|
|
1007
1045
|
import {
|
|
1008
1046
|
MODEL_SCOPED_WINDOWS,
|
|
1009
1047
|
activeModelBlocks,
|
|
@@ -1011,12 +1049,23 @@ import {
|
|
|
1011
1049
|
} from "./cli-ywybs5as.js";
|
|
1012
1050
|
import {
|
|
1013
1051
|
MAX_PROFILE_FILE_LENGTH,
|
|
1052
|
+
agentFsFileRoute,
|
|
1014
1053
|
getAppUrl,
|
|
1015
1054
|
getConfiguredAppUrls,
|
|
1016
1055
|
getMcpBaseUrl,
|
|
1017
1056
|
getPublicMcpBaseUrl,
|
|
1018
1057
|
init_constants
|
|
1019
|
-
} from "./cli-
|
|
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";
|
|
1020
1069
|
import {
|
|
1021
1070
|
SUBSCRIPTION_PLANS,
|
|
1022
1071
|
SUBSCRIPTION_PLANS_CHECKED_AT,
|
|
@@ -1049,36 +1098,13 @@ import {
|
|
|
1049
1098
|
import {
|
|
1050
1099
|
init_package,
|
|
1051
1100
|
package_default
|
|
1052
|
-
} from "./cli-
|
|
1101
|
+
} from "./cli-sqvfa090.js";
|
|
1053
1102
|
import {
|
|
1054
1103
|
init_secret_scrubber,
|
|
1055
1104
|
registerVolatileSecret,
|
|
1056
1105
|
scrubObject,
|
|
1057
1106
|
scrubSecrets
|
|
1058
1107
|
} from "./cli-nexqx4ve.js";
|
|
1059
|
-
import {
|
|
1060
|
-
bedrockProviderModule
|
|
1061
|
-
} from "./cli-et8m9xsv.js";
|
|
1062
|
-
import"./cli-yn0a417a.js";
|
|
1063
|
-
import"./cli-cgj4hc12.js";
|
|
1064
|
-
import"./cli-txgcknmy.js";
|
|
1065
|
-
import"./cli-6map995v.js";
|
|
1066
|
-
import"./cli-ybgv4kw2.js";
|
|
1067
|
-
import"./cli-y2apkfe2.js";
|
|
1068
|
-
import"./cli-7kyk9jr3.js";
|
|
1069
|
-
import {
|
|
1070
|
-
setBedrockProviderModule
|
|
1071
|
-
} from "./cli-13hw4z91.js";
|
|
1072
|
-
import"./cli-btbzvq95.js";
|
|
1073
|
-
import"./cli-1m2e086m.js";
|
|
1074
|
-
import"./cli-ykk5jaax.js";
|
|
1075
|
-
import"./cli-bzr0ftht.js";
|
|
1076
|
-
import"./cli-bd957dgb.js";
|
|
1077
|
-
import {
|
|
1078
|
-
import_websocket,
|
|
1079
|
-
import_websocket_server
|
|
1080
|
-
} from "./cli-76yrvwsa.js";
|
|
1081
|
-
import"./cli-pzxba7gw.js";
|
|
1082
1108
|
import {
|
|
1083
1109
|
init_event_bus,
|
|
1084
1110
|
workflowEventBus
|
|
@@ -1955,6 +1981,7 @@ function stopQueueStallAlarm() {
|
|
|
1955
1981
|
}
|
|
1956
1982
|
|
|
1957
1983
|
// src/http/index.ts
|
|
1984
|
+
init_rbac();
|
|
1958
1985
|
init_bus();
|
|
1959
1986
|
|
|
1960
1987
|
// src/realtime/transport.ts
|
|
@@ -1962,6 +1989,47 @@ init_zod();
|
|
|
1962
1989
|
init_db();
|
|
1963
1990
|
init_secret_scrubber();
|
|
1964
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
|
|
1965
2033
|
var nameSchema = exports_external.string().regex(/^[a-zA-Z0-9_-]{1,64}$/);
|
|
1966
2034
|
var messageSchema = exports_external.object({
|
|
1967
2035
|
id: exports_external.number().int().nonnegative(),
|
|
@@ -1989,8 +2057,33 @@ function header(req, name) {
|
|
|
1989
2057
|
const value = req.headers[name];
|
|
1990
2058
|
return Array.isArray(value) ? value[0] : value;
|
|
1991
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
|
+
}
|
|
1992
2078
|
async function authenticate(req) {
|
|
1993
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
|
+
}
|
|
1994
2087
|
const pageId = url.searchParams.get("pageId");
|
|
1995
2088
|
if (pageId) {
|
|
1996
2089
|
const origin = header(req, "origin");
|
|
@@ -2005,12 +2098,12 @@ async function authenticate(req) {
|
|
|
2005
2098
|
throw new Error("Page session required");
|
|
2006
2099
|
if (session?.uid && (await findUserById(session.uid))?.status !== "active")
|
|
2007
2100
|
throw new Error("Viewer is inactive");
|
|
2008
|
-
const
|
|
2101
|
+
const guestId = `guest-${crypto.randomUUID()}`;
|
|
2009
2102
|
return {
|
|
2010
2103
|
identity: { pageId, userId: session?.uid },
|
|
2011
2104
|
me: {
|
|
2012
|
-
userId: session?.uid ??
|
|
2013
|
-
name: session?.name ?? `Guest ${
|
|
2105
|
+
userId: session?.uid ?? guestId,
|
|
2106
|
+
name: session?.name ?? `Guest ${guestId.slice(-6)}`,
|
|
2014
2107
|
kind: session?.uid ? "user" : "guest"
|
|
2015
2108
|
},
|
|
2016
2109
|
expiresAt: session ? session.exp * 1000 : undefined
|
|
@@ -2019,22 +2112,7 @@ async function authenticate(req) {
|
|
|
2019
2112
|
const auth = await resolveHttpRequestAuth(req, getApiKey());
|
|
2020
2113
|
if (!auth)
|
|
2021
2114
|
throw new Error("Authentication required");
|
|
2022
|
-
|
|
2023
|
-
const guestId = `guest-${crypto.randomUUID()}`;
|
|
2024
|
-
return {
|
|
2025
|
-
identity: {
|
|
2026
|
-
agentId,
|
|
2027
|
-
sourceTaskId: header(req, "x-source-task-id"),
|
|
2028
|
-
userId: auth.kind === "user" ? auth.userId : undefined,
|
|
2029
|
-
isOperator: auth.kind === "operator"
|
|
2030
|
-
},
|
|
2031
|
-
me: {
|
|
2032
|
-
userId: auth.kind === "user" ? auth.userId : agentId ?? guestId,
|
|
2033
|
-
name: auth.kind === "user" ? auth.user.name : agentId ?? `Guest ${guestId.slice(-6)}`,
|
|
2034
|
-
kind: auth.kind === "user" ? "user" : agentId ? "agent" : "guest"
|
|
2035
|
-
},
|
|
2036
|
-
expiresAt: undefined
|
|
2037
|
-
};
|
|
2115
|
+
return identityFromHttpAuth(req, auth);
|
|
2038
2116
|
}
|
|
2039
2117
|
function channelTopic(namespace, name) {
|
|
2040
2118
|
return `channel:${JSON.stringify([namespace, name])}`;
|
|
@@ -2044,7 +2122,8 @@ function attachRealtimeTransport(server) {
|
|
|
2044
2122
|
let pendingUpgrades = 0;
|
|
2045
2123
|
let closing = false;
|
|
2046
2124
|
const onUpgrade = (req, socket, head) => {
|
|
2047
|
-
|
|
2125
|
+
const path = req.url?.split("?")[0];
|
|
2126
|
+
if (closing || path !== "/@swarm/realtime" && path !== "/api/realtime" || wss.clients.size + pendingUpgrades >= 1000) {
|
|
2048
2127
|
socket.destroy();
|
|
2049
2128
|
return;
|
|
2050
2129
|
}
|
|
@@ -2151,8 +2230,10 @@ function connect(ws, auth) {
|
|
|
2151
2230
|
if ("error" in resolved)
|
|
2152
2231
|
throw new Error(resolved.error);
|
|
2153
2232
|
const namespace = resolved.namespace;
|
|
2154
|
-
|
|
2155
|
-
|
|
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);
|
|
2156
2237
|
if (denied)
|
|
2157
2238
|
throw new Error(typeof denied === "string" ? denied : "Forbidden");
|
|
2158
2239
|
if (closed)
|
|
@@ -2185,7 +2266,7 @@ function connect(ws, auth) {
|
|
|
2185
2266
|
} catch (error) {
|
|
2186
2267
|
if (!(error instanceof Error) || error.message !== "room does not exist")
|
|
2187
2268
|
throw error;
|
|
2188
|
-
const creationDenied = await authorizeRoomNamespace(namespace, auth.identity, true);
|
|
2269
|
+
const creationDenied = await authorizeRoomNamespace(namespace, auth.identity, namespace.startsWith("presence:comb:") ? "join" : true);
|
|
2189
2270
|
if (creationDenied)
|
|
2190
2271
|
throw new Error(creationDenied);
|
|
2191
2272
|
if (closed)
|
|
@@ -3265,6 +3346,150 @@ function getServerSessionsProcessed() {
|
|
|
3265
3346
|
|
|
3266
3347
|
// src/http/index.ts
|
|
3267
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();
|
|
3268
3493
|
init_constants();
|
|
3269
3494
|
init_env_flag();
|
|
3270
3495
|
init_secret_scrubber();
|
|
@@ -5611,8 +5836,26 @@ async function approvalCancelPrincipal(req) {
|
|
|
5611
5836
|
init_zod();
|
|
5612
5837
|
init_asset_key_audit();
|
|
5613
5838
|
init_db();
|
|
5839
|
+
init_rbac();
|
|
5614
5840
|
init_types();
|
|
5615
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
|
|
5616
5859
|
var AssetKeyAuditIssueSchema = exports_external.object({
|
|
5617
5860
|
severity: exports_external.enum(["fatal", "warning"]),
|
|
5618
5861
|
code: exports_external.enum([
|
|
@@ -5744,17 +5987,6 @@ var moveAssetRoute = route({
|
|
|
5744
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"
|
|
5745
5988
|
}
|
|
5746
5989
|
});
|
|
5747
|
-
async function assetMovePrincipal(req, myAgentId) {
|
|
5748
|
-
const auth = getRequestAuth(req);
|
|
5749
|
-
if (auth?.kind === "operator")
|
|
5750
|
-
return { kind: "operator" };
|
|
5751
|
-
if (auth?.kind === "user")
|
|
5752
|
-
return { kind: "user", userId: auth.userId };
|
|
5753
|
-
if (!myAgentId)
|
|
5754
|
-
return null;
|
|
5755
|
-
const agent = await getAgentById(myAgentId);
|
|
5756
|
-
return { kind: "agent", agentId: myAgentId, isLead: agent?.isLead ?? false };
|
|
5757
|
-
}
|
|
5758
5990
|
async function canMutateTaskNamespace(task, myAgentId, req) {
|
|
5759
5991
|
const resource = {
|
|
5760
5992
|
kind: "task",
|
|
@@ -5762,17 +5994,17 @@ async function canMutateTaskNamespace(task, myAgentId, req) {
|
|
|
5762
5994
|
agentId: task.agentId,
|
|
5763
5995
|
creatorAgentId: task.creatorAgentId
|
|
5764
5996
|
};
|
|
5765
|
-
const principal = await
|
|
5997
|
+
const principal = await requestPrincipal(req, myAgentId);
|
|
5766
5998
|
if (!principal)
|
|
5767
5999
|
return false;
|
|
5768
6000
|
return can({ principal, verb: "task.fs.mutate", resource, source: "http" }).allow;
|
|
5769
6001
|
}
|
|
5770
6002
|
async function canManageAppNamespace(id, req, myAgentId) {
|
|
5771
|
-
const principal = await
|
|
6003
|
+
const principal = await requestPrincipal(req, myAgentId);
|
|
5772
6004
|
return !!principal && can({ principal, verb: "app.manage", resource: { kind: "app", appId: id }, source: "http" }).allow;
|
|
5773
6005
|
}
|
|
5774
6006
|
async function canManageScriptNamespace(script, req, myAgentId) {
|
|
5775
|
-
const principal = await
|
|
6007
|
+
const principal = await requestPrincipal(req, myAgentId);
|
|
5776
6008
|
if (!principal)
|
|
5777
6009
|
return false;
|
|
5778
6010
|
if (principal.kind === "operator")
|
|
@@ -6091,6 +6323,7 @@ init_db();
|
|
|
6091
6323
|
// src/be/onboarding.ts
|
|
6092
6324
|
init_telemetry();
|
|
6093
6325
|
init_types();
|
|
6326
|
+
init_request_auth_context();
|
|
6094
6327
|
init_zod_openapi();
|
|
6095
6328
|
init_db();
|
|
6096
6329
|
init_swarm_config_guard();
|
|
@@ -6110,6 +6343,7 @@ var OnboardingErrorClassSchema = exports_zod.enum([
|
|
|
6110
6343
|
"timeout",
|
|
6111
6344
|
"dimension",
|
|
6112
6345
|
"model",
|
|
6346
|
+
"endpoint",
|
|
6113
6347
|
"not_enabled",
|
|
6114
6348
|
"expired",
|
|
6115
6349
|
"unknown"
|
|
@@ -6132,6 +6366,7 @@ var OnboardingMemoryPresetSchema = exports_zod.enum([
|
|
|
6132
6366
|
"openai",
|
|
6133
6367
|
"openrouter",
|
|
6134
6368
|
"vercel",
|
|
6369
|
+
"azure",
|
|
6135
6370
|
"custom",
|
|
6136
6371
|
"existing"
|
|
6137
6372
|
]);
|
|
@@ -6337,8 +6572,9 @@ function addTelemetry(events, state, event, properties) {
|
|
|
6337
6572
|
});
|
|
6338
6573
|
}
|
|
6339
6574
|
function queueTelemetry(events) {
|
|
6575
|
+
const actor = { userId: getCurrentRequestUserId() ?? null };
|
|
6340
6576
|
for (const item of events) {
|
|
6341
|
-
getDbClient().afterCommit(() => telemetry.onboarding(item.event, item.properties));
|
|
6577
|
+
getDbClient().afterCommit(() => telemetry.onboarding(item.event, item.properties, actor));
|
|
6342
6578
|
}
|
|
6343
6579
|
}
|
|
6344
6580
|
async function isExistingInstall() {
|
|
@@ -6699,7 +6935,9 @@ init_secret_scrubber();
|
|
|
6699
6935
|
// src/http/config.ts
|
|
6700
6936
|
init_zod();
|
|
6701
6937
|
init_db();
|
|
6938
|
+
init_rbac_roles();
|
|
6702
6939
|
init_swarm_config_guard();
|
|
6940
|
+
init_rbac();
|
|
6703
6941
|
init_types();
|
|
6704
6942
|
init_request_auth_context();
|
|
6705
6943
|
init_secret_scrubber();
|
|
@@ -7431,6 +7669,449 @@ async function handleCodexOAuthKeepWarm(req, res, pathSegments) {
|
|
|
7431
7669
|
return true;
|
|
7432
7670
|
}
|
|
7433
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
|
+
}
|
|
8111
|
+
}
|
|
8112
|
+
return true;
|
|
8113
|
+
}
|
|
8114
|
+
|
|
7434
8115
|
// src/http/context.ts
|
|
7435
8116
|
init_zod();
|
|
7436
8117
|
init_db();
|
|
@@ -7714,8 +8395,8 @@ async function handleEvents(req, res, pathSegments, queryParams, _myAgentId) {
|
|
|
7714
8395
|
if (!parsed)
|
|
7715
8396
|
return true;
|
|
7716
8397
|
try {
|
|
7717
|
-
const
|
|
7718
|
-
createEventsBatchRoute.respond(res, 201, { success: true, count });
|
|
8398
|
+
const count2 = await createEventsBatch(parsed.body.events);
|
|
8399
|
+
createEventsBatchRoute.respond(res, 201, { success: true, count: count2 });
|
|
7719
8400
|
} catch (error) {
|
|
7720
8401
|
console.error("[HTTP] Failed to create events batch:", error);
|
|
7721
8402
|
jsonError(res, "Failed to store events batch", 500);
|
|
@@ -7818,6 +8499,7 @@ declare module "swarm-extension" {
|
|
|
7818
8499
|
| "system"
|
|
7819
8500
|
| "linear"
|
|
7820
8501
|
| "jira"
|
|
8502
|
+
| "comb"
|
|
7821
8503
|
| undefined;
|
|
7822
8504
|
routingReason?:
|
|
7823
8505
|
| "skill"
|
|
@@ -7927,7 +8609,8 @@ declare module "swarm-extension" {
|
|
|
7927
8609
|
| "azure-devops"
|
|
7928
8610
|
| "system"
|
|
7929
8611
|
| "linear"
|
|
7930
|
-
| "jira"
|
|
8612
|
+
| "jira"
|
|
8613
|
+
| "comb";
|
|
7931
8614
|
tags: string[];
|
|
7932
8615
|
priority: number;
|
|
7933
8616
|
dependsOn: string[];
|
|
@@ -9082,6 +9765,7 @@ function getCatalogEntry(name) {
|
|
|
9082
9765
|
}
|
|
9083
9766
|
|
|
9084
9767
|
// src/http/extensions.ts
|
|
9768
|
+
init_rbac();
|
|
9085
9769
|
init_types();
|
|
9086
9770
|
init_env_flag();
|
|
9087
9771
|
init_request_auth_context();
|
|
@@ -9808,6 +10492,7 @@ async function handleFavorites(req, res, pathSegments, queryParams, myAgentId) {
|
|
|
9808
10492
|
// src/http/fs.ts
|
|
9809
10493
|
init_zod();
|
|
9810
10494
|
init_db();
|
|
10495
|
+
init_rbac();
|
|
9811
10496
|
init_types();
|
|
9812
10497
|
|
|
9813
10498
|
// src/utils/content-disposition.ts
|
|
@@ -10247,18 +10932,9 @@ async function canMutateTask(task, myAgentId, req) {
|
|
|
10247
10932
|
agentId: task.agentId,
|
|
10248
10933
|
creatorAgentId: task.creatorAgentId
|
|
10249
10934
|
};
|
|
10250
|
-
const
|
|
10251
|
-
|
|
10252
|
-
|
|
10253
|
-
principal = { kind: "operator" };
|
|
10254
|
-
} else if (auth?.kind === "user") {
|
|
10255
|
-
principal = { kind: "user", userId: auth.userId };
|
|
10256
|
-
} else {
|
|
10257
|
-
if (!myAgentId)
|
|
10258
|
-
return false;
|
|
10259
|
-
const agent = await getAgentById(myAgentId);
|
|
10260
|
-
principal = { kind: "agent", agentId: myAgentId, isLead: agent?.isLead ?? false };
|
|
10261
|
-
}
|
|
10935
|
+
const principal = await requestPrincipal(req, myAgentId);
|
|
10936
|
+
if (!principal)
|
|
10937
|
+
return false;
|
|
10262
10938
|
return can({ principal, verb: "task.fs.mutate", resource, source: "http" }).allow;
|
|
10263
10939
|
}
|
|
10264
10940
|
async function readRawBody(req, maxBytes) {
|
|
@@ -10697,6 +11373,7 @@ var handleIntegrations = createIntegrationsHandler();
|
|
|
10697
11373
|
// src/http/kv.ts
|
|
10698
11374
|
init_zod();
|
|
10699
11375
|
init_db();
|
|
11376
|
+
init_rbac();
|
|
10700
11377
|
init_context_key();
|
|
10701
11378
|
init_types();
|
|
10702
11379
|
var MAX_KV_BODY_BYTES = 2 * 1024 * 1024;
|
|
@@ -13371,6 +14048,8 @@ async function handleMcpOAuth(req, res, pathSegments, queryParams) {
|
|
|
13371
14048
|
// src/http/mcp-servers.ts
|
|
13372
14049
|
init_zod();
|
|
13373
14050
|
init_db();
|
|
14051
|
+
init_rbac_roles();
|
|
14052
|
+
init_rbac();
|
|
13374
14053
|
init_types();
|
|
13375
14054
|
init_request_auth_context();
|
|
13376
14055
|
var McpServerWithOptionalSecretsSchema = McpServerWithInstallInfoSchema.extend({
|
|
@@ -13829,6 +14508,8 @@ import { randomUUID as randomUUID3 } from "node:crypto";
|
|
|
13829
14508
|
// src/server-user.ts
|
|
13830
14509
|
init_zod();
|
|
13831
14510
|
init_package();
|
|
14511
|
+
init_rbac_roles();
|
|
14512
|
+
init_rbac();
|
|
13832
14513
|
init_types();
|
|
13833
14514
|
init_steering_enabled();
|
|
13834
14515
|
var userSendTaskInputSchema = object({
|
|
@@ -14314,6 +14995,7 @@ function truncateUtf8(query, maxBytes) {
|
|
|
14314
14995
|
}
|
|
14315
14996
|
|
|
14316
14997
|
// src/http/memory.ts
|
|
14998
|
+
init_rbac();
|
|
14317
14999
|
init_types();
|
|
14318
15000
|
init_request_auth_context();
|
|
14319
15001
|
init_secret_scrubber();
|
|
@@ -15774,6 +16456,7 @@ async function handleMetrics(req, res, pathSegments, queryParams, myAgentId) {
|
|
|
15774
16456
|
// src/http/models-catalog.ts
|
|
15775
16457
|
init_zod();
|
|
15776
16458
|
init_db();
|
|
16459
|
+
init_rbac();
|
|
15777
16460
|
init_types();
|
|
15778
16461
|
init_request_auth_context();
|
|
15779
16462
|
var CatalogModelSchema = exports_external.object({
|
|
@@ -16670,6 +17353,14 @@ var StatusActivitySchema = exports_external.object({
|
|
|
16670
17353
|
leads_online: exports_external.number().int().nonnegative(),
|
|
16671
17354
|
recent_tasks_count: exports_external.number().int().nonnegative()
|
|
16672
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
|
+
});
|
|
16673
17364
|
var StatusTelemetrySchema = exports_external.object({
|
|
16674
17365
|
enabled: exports_external.boolean()
|
|
16675
17366
|
});
|
|
@@ -16677,7 +17368,8 @@ var StatusAgentFsSchema = exports_external.object({
|
|
|
16677
17368
|
configured: exports_external.boolean(),
|
|
16678
17369
|
base_url: exports_external.string().nullable(),
|
|
16679
17370
|
provider_id: exports_external.string(),
|
|
16680
|
-
capabilities: exports_external.record(exports_external.string(), exports_external.unknown())
|
|
17371
|
+
capabilities: exports_external.record(exports_external.string(), exports_external.unknown()),
|
|
17372
|
+
comb: StatusCombSchema
|
|
16681
17373
|
});
|
|
16682
17374
|
var AutomationStatusSchema = exports_external.object({
|
|
16683
17375
|
id: exports_external.string(),
|
|
@@ -17046,25 +17738,39 @@ function computeHealth(setup) {
|
|
|
17046
17738
|
return "ok";
|
|
17047
17739
|
}
|
|
17048
17740
|
async function buildStatusPayload() {
|
|
17741
|
+
const combServiceUserId = getCombConfig().enabled ? getCombServiceUserId() : Promise.resolve(null);
|
|
17049
17742
|
const automationSetup = await getAutomationSetupStates();
|
|
17050
17743
|
const setup = await buildSetup(automationSetup);
|
|
17051
17744
|
const automationInputs = await listEnabledAutomationPreflightInputs();
|
|
17052
17745
|
const toStatus = ({ failureReason: _, ...status }) => status;
|
|
17053
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();
|
|
17054
17748
|
return {
|
|
17055
17749
|
identity: buildIdentity(),
|
|
17056
17750
|
setup,
|
|
17057
|
-
activity
|
|
17751
|
+
activity,
|
|
17058
17752
|
agent_fs: {
|
|
17059
17753
|
configured: !!process.env.AGENT_FS_API_URL,
|
|
17060
17754
|
base_url: process.env.AGENT_FS_API_URL ?? null,
|
|
17061
|
-
...getAgentFsStatusProvider()
|
|
17755
|
+
...getAgentFsStatusProvider(),
|
|
17756
|
+
comb: getCombStatus(await combServiceUserId)
|
|
17062
17757
|
},
|
|
17063
17758
|
automations,
|
|
17064
17759
|
health: computeHealth(setup),
|
|
17065
17760
|
telemetry: { enabled: isTelemetryEnabled() }
|
|
17066
17761
|
};
|
|
17067
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
|
+
}
|
|
17068
17774
|
function getAgentFsStatusProvider() {
|
|
17069
17775
|
try {
|
|
17070
17776
|
const provider = getFileStorageProvider();
|
|
@@ -17084,7 +17790,7 @@ var getStatus = route({
|
|
|
17084
17790
|
path: "/status",
|
|
17085
17791
|
pattern: ["status"],
|
|
17086
17792
|
summary: "Identity + setup readiness + live activity for the swarm dashboard",
|
|
17087
|
-
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.",
|
|
17088
17794
|
tags: ["Status"],
|
|
17089
17795
|
responses: {
|
|
17090
17796
|
200: { description: "Status payload", schema: StatusResponseSchema },
|
|
@@ -17239,12 +17945,20 @@ function memoryErrorStatus(error) {
|
|
|
17239
17945
|
const status = typeof error === "object" && error !== null && "status" in error ? Number(error.status) : 0;
|
|
17240
17946
|
return Number.isInteger(status) && status >= 100 && status <= 599 ? status : undefined;
|
|
17241
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
|
+
}
|
|
17242
17956
|
function classifyMemoryError(error) {
|
|
17243
17957
|
const status = memoryErrorStatus(error);
|
|
17244
17958
|
if (status === 401 || status === 403)
|
|
17245
17959
|
return "auth";
|
|
17246
17960
|
if (status === 404)
|
|
17247
|
-
return "model";
|
|
17961
|
+
return notFoundNamesModel(error) ? "model" : "endpoint";
|
|
17248
17962
|
if (status === 408)
|
|
17249
17963
|
return "timeout";
|
|
17250
17964
|
const text = error instanceof Error ? `${error.name} ${error.message}`.toLowerCase() : String(error).toLowerCase();
|
|
@@ -17262,7 +17976,9 @@ function memoryErrorMessage(errorClass, status) {
|
|
|
17262
17976
|
case "auth":
|
|
17263
17977
|
return `The endpoint rejected the key${statusSuffix}.`;
|
|
17264
17978
|
case "model":
|
|
17265
|
-
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.`;
|
|
17266
17982
|
case "timeout":
|
|
17267
17983
|
return "The endpoint timed out.";
|
|
17268
17984
|
case "network":
|
|
@@ -18653,7 +19369,7 @@ async function fetchAllBotChannels(client) {
|
|
|
18653
19369
|
}
|
|
18654
19370
|
|
|
18655
19371
|
// src/http/poll.ts
|
|
18656
|
-
|
|
19372
|
+
init_telemetry_trigger();
|
|
18657
19373
|
init_types();
|
|
18658
19374
|
function buildBudgetRefusedTrigger(refusal) {
|
|
18659
19375
|
const trigger = {
|
|
@@ -18700,6 +19416,7 @@ var PollTaskOfferedTriggerSchema = exports_external.object({
|
|
|
18700
19416
|
var PollTaskAssignedTriggerSchema = exports_external.object({
|
|
18701
19417
|
type: exports_external.literal("task_assigned"),
|
|
18702
19418
|
taskId: exports_external.string(),
|
|
19419
|
+
triggerSurface: exports_external.string().optional(),
|
|
18703
19420
|
task: AgentTaskSchema.extend({
|
|
18704
19421
|
attachments: exports_external.array(PollTriggerAttachmentSchema)
|
|
18705
19422
|
}),
|
|
@@ -18737,6 +19454,7 @@ var pollTriggers = route({
|
|
|
18737
19454
|
path: "/api/poll",
|
|
18738
19455
|
pattern: ["api", "poll"],
|
|
18739
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.",
|
|
18740
19458
|
tags: ["Poll"],
|
|
18741
19459
|
auth: { apiKey: true, agentId: true },
|
|
18742
19460
|
headers: runtimeInstanceHeader("poll for work").extend({
|
|
@@ -18846,6 +19564,9 @@ async function handlePoll(req, res, pathSegments, queryParams, myAgentId) {
|
|
|
18846
19564
|
if (isMultiRuntimeEnabled() && !(runtimeInstanceId && await touchRuntimeInstance(runtimeInstanceId, agent.id))) {
|
|
18847
19565
|
return { trigger: null };
|
|
18848
19566
|
}
|
|
19567
|
+
if (isApiDraining()) {
|
|
19568
|
+
return { trigger: null };
|
|
19569
|
+
}
|
|
18849
19570
|
const offeredTasks = await hasCapacity(myAgentId) ? await getOfferedTasksForAgent(myAgentId) : [];
|
|
18850
19571
|
const firstOfferedTask = offeredTasks[0];
|
|
18851
19572
|
if (firstOfferedTask) {
|
|
@@ -18924,17 +19645,19 @@ async function handlePoll(req, res, pathSegments, queryParams, myAgentId) {
|
|
|
18924
19645
|
filter: ({}, ctx) => ctx.deps.length > 0,
|
|
18925
19646
|
conditions: [{ timeout_ms: 300000 }]
|
|
18926
19647
|
});
|
|
18927
|
-
|
|
19648
|
+
emitTaskTelemetry("started", {
|
|
18928
19649
|
taskId: pendingTask.id,
|
|
18929
19650
|
source: pendingTask.source,
|
|
18930
19651
|
agentId: myAgentId
|
|
18931
19652
|
});
|
|
18932
19653
|
});
|
|
18933
19654
|
const assignedRequestedBy = await buildTriggerRequestedBy(pendingTask);
|
|
19655
|
+
const assignedTriggerSurface = await resolveTriggerSurface(pendingTask.id, pendingTask.source);
|
|
18934
19656
|
return {
|
|
18935
19657
|
trigger: {
|
|
18936
19658
|
type: "task_assigned",
|
|
18937
19659
|
taskId: pendingTask.id,
|
|
19660
|
+
triggerSurface: assignedTriggerSurface,
|
|
18938
19661
|
task: {
|
|
18939
19662
|
...pendingTask,
|
|
18940
19663
|
...await claimModelFields(pendingTask, agent),
|
|
@@ -19012,17 +19735,19 @@ async function handlePoll(req, res, pathSegments, queryParams, myAgentId) {
|
|
|
19012
19735
|
if (claimed) {
|
|
19013
19736
|
await updateAgentStatusFromCapacity(myAgentId);
|
|
19014
19737
|
getDbClient().afterCommit(() => {
|
|
19015
|
-
|
|
19738
|
+
emitTaskTelemetry("claimed", {
|
|
19016
19739
|
taskId: claimed.id,
|
|
19017
19740
|
source: claimed.source,
|
|
19018
19741
|
agentId: myAgentId
|
|
19019
19742
|
});
|
|
19020
19743
|
});
|
|
19021
19744
|
const claimedRequestedBy = await buildTriggerRequestedBy(claimed);
|
|
19745
|
+
const claimedTriggerSurface = await resolveTriggerSurface(claimed.id, claimed.source);
|
|
19022
19746
|
return {
|
|
19023
19747
|
trigger: {
|
|
19024
19748
|
type: "task_assigned",
|
|
19025
19749
|
taskId: claimed.id,
|
|
19750
|
+
triggerSurface: claimedTriggerSurface,
|
|
19026
19751
|
task: {
|
|
19027
19752
|
...claimed,
|
|
19028
19753
|
...await claimModelFields(claimed, agent),
|
|
@@ -19049,7 +19774,7 @@ async function handlePoll(req, res, pathSegments, queryParams, myAgentId) {
|
|
|
19049
19774
|
if (result.refusalSideEffects) {
|
|
19050
19775
|
await emitBudgetRefusalSideEffects(result.refusalSideEffects.context, result.refusalSideEffects.inserted);
|
|
19051
19776
|
}
|
|
19052
|
-
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) {
|
|
19053
19778
|
const agent = await getAgentById(myAgentId);
|
|
19054
19779
|
if (agent?.isLead) {
|
|
19055
19780
|
lastChannelActivityCheckAt = Date.now();
|
|
@@ -19695,10 +20420,31 @@ ${templateBody}` : templateBody;
|
|
|
19695
20420
|
return false;
|
|
19696
20421
|
}
|
|
19697
20422
|
|
|
20423
|
+
// src/http/realtime.ts
|
|
20424
|
+
init_zod();
|
|
20425
|
+
init_rbac();
|
|
20426
|
+
|
|
19698
20427
|
// src/realtime/browser.generated.txt
|
|
19699
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";
|
|
19700
20429
|
|
|
19701
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
|
+
});
|
|
19702
20448
|
route({
|
|
19703
20449
|
method: "get",
|
|
19704
20450
|
path: "/@swarm/realtime.js",
|
|
@@ -19710,6 +20456,34 @@ route({
|
|
|
19710
20456
|
200: { description: "JavaScript module", unstructured: "Browser JavaScript bundle" }
|
|
19711
20457
|
}
|
|
19712
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
|
+
}
|
|
19713
20487
|
async function handleRealtimeAsset(req, res) {
|
|
19714
20488
|
if (req.method !== "GET" || req.url?.split("?")[0] !== "/@swarm/realtime.js")
|
|
19715
20489
|
return false;
|
|
@@ -20761,6 +21535,7 @@ async function handleSchedules(req, res, pathSegments, queryParams, myAgentId) {
|
|
|
20761
21535
|
// src/http/script-connection-proxy.ts
|
|
20762
21536
|
init_zod();
|
|
20763
21537
|
init_db();
|
|
21538
|
+
init_rbac();
|
|
20764
21539
|
var McpToolCallResultSchema = exports_external.object({
|
|
20765
21540
|
content: exports_external.array(exports_external.object({ type: exports_external.string(), text: exports_external.string().optional() })),
|
|
20766
21541
|
isError: exports_external.boolean().optional()
|
|
@@ -20869,6 +21644,7 @@ async function handleScriptConnectionProxy(req, res, pathSegments, queryParams,
|
|
|
20869
21644
|
init_zod();
|
|
20870
21645
|
init_date_utils();
|
|
20871
21646
|
init_db();
|
|
21647
|
+
init_rbac();
|
|
20872
21648
|
init_credential_broker();
|
|
20873
21649
|
init_telemetry();
|
|
20874
21650
|
init_request_auth_context();
|
|
@@ -23387,6 +24163,7 @@ async function handleScriptRuns(req, res, pathSegments, queryParams, agentId) {
|
|
|
23387
24163
|
// src/http/scripts.ts
|
|
23388
24164
|
init_zod();
|
|
23389
24165
|
init_db();
|
|
24166
|
+
init_rbac();
|
|
23390
24167
|
init_types();
|
|
23391
24168
|
init_secret_scrubber();
|
|
23392
24169
|
var scriptNameSchema = exports_external.string().min(1).max(200);
|
|
@@ -26040,6 +26817,7 @@ async function handleTaskTemplates(req, res, pathSegments, queryParams) {
|
|
|
26040
26817
|
init_zod();
|
|
26041
26818
|
init_db();
|
|
26042
26819
|
init_steering();
|
|
26820
|
+
init_rbac();
|
|
26043
26821
|
init_types();
|
|
26044
26822
|
init_request_auth_context();
|
|
26045
26823
|
init_secret_scrubber();
|
|
@@ -29017,7 +29795,7 @@ async function archiveInboundMessage(payload) {
|
|
|
29017
29795
|
// src/integrations/kapso/inbound.ts
|
|
29018
29796
|
init_resolver();
|
|
29019
29797
|
init_event_bus();
|
|
29020
|
-
|
|
29798
|
+
init_templates2();
|
|
29021
29799
|
var KAPSO_IDENTITY_KIND = "kapso";
|
|
29022
29800
|
var WHATSAPP_IDENTITY_KIND = "whatsapp";
|
|
29023
29801
|
function extractText(message) {
|
|
@@ -29371,13 +30149,13 @@ async function handleWebhooks(req, res, pathSegments) {
|
|
|
29371
30149
|
}
|
|
29372
30150
|
githubWebhook.respond(res, 200, result);
|
|
29373
30151
|
} catch (err) {
|
|
29374
|
-
const
|
|
29375
|
-
console.error(`[GitHub] Error handling ${eventType} event: ${
|
|
30152
|
+
const errorMessage2 = err instanceof Error ? err.message : String(err);
|
|
30153
|
+
console.error(`[GitHub] Error handling ${eventType} event: ${errorMessage2}`);
|
|
29376
30154
|
if (err instanceof Error && err.stack) {
|
|
29377
30155
|
console.error(err.stack);
|
|
29378
30156
|
}
|
|
29379
30157
|
res.writeHead(500, { "Content-Type": "application/json" });
|
|
29380
|
-
res.end(JSON.stringify({ error: "Internal server error", message:
|
|
30158
|
+
res.end(JSON.stringify({ error: "Internal server error", message: errorMessage2 }));
|
|
29381
30159
|
}
|
|
29382
30160
|
return true;
|
|
29383
30161
|
}
|
|
@@ -29474,8 +30252,8 @@ async function handleWebhooks(req, res, pathSegments) {
|
|
|
29474
30252
|
}
|
|
29475
30253
|
gitlabWebhook.respond(res, 200, result);
|
|
29476
30254
|
} catch (err) {
|
|
29477
|
-
const
|
|
29478
|
-
console.error(`[GitLab] Error handling ${objectKind} event: ${
|
|
30255
|
+
const errorMessage2 = err instanceof Error ? err.message : String(err);
|
|
30256
|
+
console.error(`[GitLab] Error handling ${objectKind} event: ${errorMessage2}`);
|
|
29479
30257
|
if (err instanceof Error && err.stack) {
|
|
29480
30258
|
console.error(err.stack);
|
|
29481
30259
|
}
|
|
@@ -29555,8 +30333,8 @@ async function handleWebhooks(req, res, pathSegments) {
|
|
|
29555
30333
|
}
|
|
29556
30334
|
azureDevOpsWebhook.respond(res, 200, result);
|
|
29557
30335
|
} catch (err) {
|
|
29558
|
-
const
|
|
29559
|
-
console.error(`[AzureDevOps] Error handling ${eventType} event: ${
|
|
30336
|
+
const errorMessage2 = err instanceof Error ? err.message : String(err);
|
|
30337
|
+
console.error(`[AzureDevOps] Error handling ${eventType} event: ${errorMessage2}`);
|
|
29560
30338
|
if (err instanceof Error && err.stack) {
|
|
29561
30339
|
console.error(err.stack);
|
|
29562
30340
|
}
|
|
@@ -29624,8 +30402,8 @@ async function handleWebhooks(req, res, pathSegments) {
|
|
|
29624
30402
|
console.log(`[AgentMail] Ignoring event type: ${payload.event_type}`);
|
|
29625
30403
|
}
|
|
29626
30404
|
} catch (err) {
|
|
29627
|
-
const
|
|
29628
|
-
console.error(`[AgentMail] Error handling ${payload.event_type} event: ${
|
|
30405
|
+
const errorMessage2 = err instanceof Error ? err.message : String(err);
|
|
30406
|
+
console.error(`[AgentMail] Error handling ${payload.event_type} event: ${errorMessage2}`);
|
|
29629
30407
|
if (err instanceof Error && err.stack) {
|
|
29630
30408
|
console.error(err.stack);
|
|
29631
30409
|
}
|
|
@@ -29685,11 +30463,11 @@ async function handleWebhooks(req, res, pathSegments) {
|
|
|
29685
30463
|
}
|
|
29686
30464
|
kapsoWebhook.respond(res, 200, { received: true, routing: routing.kind });
|
|
29687
30465
|
} catch (err) {
|
|
29688
|
-
const
|
|
30466
|
+
const errorMessage2 = err instanceof Error ? err.message : String(err);
|
|
29689
30467
|
if (err instanceof WebhookError) {
|
|
29690
|
-
console.warn(`[Kapso] Workflow dispatch rejected: ${
|
|
30468
|
+
console.warn(`[Kapso] Workflow dispatch rejected: ${errorMessage2}`);
|
|
29691
30469
|
} else {
|
|
29692
|
-
console.error(`[Kapso] Error handling inbound event: ${
|
|
30470
|
+
console.error(`[Kapso] Error handling inbound event: ${errorMessage2}`);
|
|
29693
30471
|
}
|
|
29694
30472
|
kapsoWebhook.respond(res, 200, { received: true, routing: "error" });
|
|
29695
30473
|
}
|
|
@@ -30850,6 +31628,8 @@ var httpServer = createHttpServer(async (req, res) => {
|
|
|
30850
31628
|
}
|
|
30851
31629
|
const handleRequest = async () => {
|
|
30852
31630
|
setCorsHeaders(req, res);
|
|
31631
|
+
if (isApiDraining())
|
|
31632
|
+
res.setHeader(API_DRAINING_HEADER, "1");
|
|
30853
31633
|
const queryParams = parseQueryParams(req.url || "");
|
|
30854
31634
|
const myAgentId = req.headers["x-agent-id"];
|
|
30855
31635
|
const handlers = [
|
|
@@ -30877,8 +31657,10 @@ var httpServer = createHttpServer(async (req, res) => {
|
|
|
30877
31657
|
() => handleApps(req, res, pathSegments, queryParams, myAgentId),
|
|
30878
31658
|
() => handleConfig(req, res, pathSegments, queryParams),
|
|
30879
31659
|
() => handleFs(req, res, pathSegments, queryParams, myAgentId),
|
|
31660
|
+
() => handleComb(req, res, pathSegments, queryParams, myAgentId),
|
|
30880
31661
|
() => handleKv(req, res, pathSegments, queryParams),
|
|
30881
31662
|
() => handleRooms(req, res, pathSegments, queryParams),
|
|
31663
|
+
() => handleRealtimeTicket(req, res, pathSegments, queryParams),
|
|
30882
31664
|
() => handleRealtimeAsset(req, res),
|
|
30883
31665
|
() => handleIntegrations(req, res, pathSegments, queryParams),
|
|
30884
31666
|
() => handlePromptTemplates(req, res, pathSegments, queryParams),
|
|
@@ -30971,15 +31753,16 @@ async function shutdown() {
|
|
|
30971
31753
|
sessionsProcessed: getServerSessionsProcessed()
|
|
30972
31754
|
});
|
|
30973
31755
|
if (hasCapability("scheduling")) {
|
|
30974
|
-
const { stopScheduler } = await import("./index-
|
|
31756
|
+
const { stopScheduler } = await import("./index-qb4q1y3e.js");
|
|
30975
31757
|
stopScheduler();
|
|
30976
31758
|
}
|
|
30977
31759
|
stopHeartbeat();
|
|
30978
31760
|
stopQueueStallAlarm();
|
|
31761
|
+
await drainApi();
|
|
30979
31762
|
await stopScriptRunSupervisor();
|
|
30980
31763
|
await stopSlackApp();
|
|
30981
31764
|
if (process.env.OAUTH_KEEPALIVE_DISABLE !== "true") {
|
|
30982
|
-
const { stopOAuthKeepalive } = await import("./keepalive-
|
|
31765
|
+
const { stopOAuthKeepalive } = await import("./keepalive-xa5ts9cd.js");
|
|
30983
31766
|
await stopOAuthKeepalive();
|
|
30984
31767
|
}
|
|
30985
31768
|
stopOAuthPendingGc();
|
|
@@ -31048,15 +31831,15 @@ try {
|
|
|
31048
31831
|
console.warn("[startup] CAPABILITIES upgrade seed failed (non-fatal):", err);
|
|
31049
31832
|
}
|
|
31050
31833
|
try {
|
|
31051
|
-
const { ensurePricingSeeded } = await import("./boot-seeds-
|
|
31834
|
+
const { ensurePricingSeeded } = await import("./boot-seeds-1skcrs0e.js");
|
|
31052
31835
|
ensurePricingSeeded();
|
|
31053
|
-
const { startPricingRefreshLoop } = await import("./pricing-refresh-
|
|
31836
|
+
const { startPricingRefreshLoop } = await import("./pricing-refresh-mth26tgp.js");
|
|
31054
31837
|
startPricingRefreshLoop();
|
|
31055
31838
|
} catch (err) {
|
|
31056
31839
|
console.error("[startup] Failed to seed pricing rows:", err);
|
|
31057
31840
|
}
|
|
31058
31841
|
try {
|
|
31059
|
-
const { ensureRbacSeeded } = await import("./boot-seeds-
|
|
31842
|
+
const { ensureRbacSeeded } = await import("./boot-seeds-1skcrs0e.js");
|
|
31060
31843
|
ensureRbacSeeded();
|
|
31061
31844
|
} catch (err) {
|
|
31062
31845
|
console.error("[startup] Failed to sync RBAC seed rows:", err);
|
|
@@ -31064,7 +31847,7 @@ try {
|
|
|
31064
31847
|
throw err;
|
|
31065
31848
|
}
|
|
31066
31849
|
try {
|
|
31067
|
-
const { runAllSeeders } = await import("./index-
|
|
31850
|
+
const { runAllSeeders } = await import("./index-scptvdxg.js");
|
|
31068
31851
|
await runAllSeeders({ scriptEmbeddingMode: "skip" });
|
|
31069
31852
|
} catch (err) {
|
|
31070
31853
|
console.error("[startup] Failed to seed built-in entities:", err);
|
|
@@ -31097,10 +31880,15 @@ httpServer.listen(port, async () => {
|
|
|
31097
31880
|
if (startupConfigsInjected.length > 0) {
|
|
31098
31881
|
console.log(`Injected ${startupConfigsInjected.length} swarm_config value(s) into process.env`);
|
|
31099
31882
|
}
|
|
31100
|
-
|
|
31883
|
+
const telemetryGetConfig = async (key) => (await getSwarmConfigs({ scope: "global", key }))?.[0]?.value;
|
|
31884
|
+
const telemetrySetConfig = async (key, value) => {
|
|
31101
31885
|
await upsertSwarmConfig({ scope: "global", key, value });
|
|
31102
|
-
}
|
|
31886
|
+
};
|
|
31887
|
+
await initTelemetry("api-server", telemetryGetConfig, telemetrySetConfig, {
|
|
31888
|
+
generateIfMissing: true
|
|
31889
|
+
});
|
|
31103
31890
|
telemetry.server("started", { port });
|
|
31891
|
+
startTelemetryTicker({ getConfig: telemetryGetConfig, setConfig: telemetrySetConfig });
|
|
31104
31892
|
if (process.env.GITHUB_TOKEN) {
|
|
31105
31893
|
await emitBuiltInIntegrationConnectedOnce("github");
|
|
31106
31894
|
}
|
|
@@ -31119,37 +31907,37 @@ httpServer.listen(port, async () => {
|
|
|
31119
31907
|
await initWorkflows();
|
|
31120
31908
|
await startScriptRunSupervisor(getMcpBaseUrl());
|
|
31121
31909
|
if (hasCapability("scheduling")) {
|
|
31122
|
-
const { startScheduler } = await import("./index-
|
|
31123
|
-
const { getExecutorRegistry: getExecutorRegistry2 } = await import("./index-
|
|
31910
|
+
const { startScheduler } = await import("./index-qb4q1y3e.js");
|
|
31911
|
+
const { getExecutorRegistry: getExecutorRegistry2 } = await import("./index-dqmp15bq.js");
|
|
31124
31912
|
const intervalMs = Number(process.env.SCHEDULER_INTERVAL_MS) || 1e4;
|
|
31125
31913
|
startScheduler(getExecutorRegistry2(), intervalMs, {
|
|
31126
31914
|
runId: globalState.__runId
|
|
31127
31915
|
});
|
|
31128
31916
|
}
|
|
31129
31917
|
if (!isEnvFlagEnabled("HEARTBEAT_DISABLE", false)) {
|
|
31130
|
-
const { startHeartbeat } = await import("./index-
|
|
31918
|
+
const { startHeartbeat } = await import("./index-8fd4dm4h.js");
|
|
31131
31919
|
const heartbeatMs = Number(process.env.HEARTBEAT_INTERVAL_MS) || 90000;
|
|
31132
31920
|
startHeartbeat(heartbeatMs);
|
|
31133
31921
|
}
|
|
31134
31922
|
if (process.env.OAUTH_KEEPALIVE_DISABLE !== "true") {
|
|
31135
|
-
const { startOAuthKeepalive } = await import("./keepalive-
|
|
31923
|
+
const { startOAuthKeepalive } = await import("./keepalive-xa5ts9cd.js");
|
|
31136
31924
|
startOAuthKeepalive();
|
|
31137
31925
|
}
|
|
31138
31926
|
if (process.env.OAUTH_REFRESH_SWEEP_DISABLE !== "true") {
|
|
31139
|
-
const { startOAuthRefreshSweep } = await import("./oauth-refresh-sweep-
|
|
31927
|
+
const { startOAuthRefreshSweep } = await import("./oauth-refresh-sweep-1csdfebf.js");
|
|
31140
31928
|
startOAuthRefreshSweep();
|
|
31141
31929
|
}
|
|
31142
31930
|
startOAuthPendingGc();
|
|
31143
31931
|
await startMemoryGc();
|
|
31144
31932
|
await startDbRetention();
|
|
31145
31933
|
startHumanFreeDrain();
|
|
31146
|
-
import("./boot-reembed-
|
|
31934
|
+
import("./boot-reembed-nxpcvpj9.js").then(({ runBootReembed }) => runBootReembed()).catch((err) => {
|
|
31147
31935
|
console.error("[boot-reembed] startup backfill failed (non-fatal):", err);
|
|
31148
31936
|
});
|
|
31149
|
-
import("./boot-reembed-
|
|
31937
|
+
import("./boot-reembed-4ht4gqth.js").then(({ runBootReembedScripts }) => runBootReembedScripts()).catch((err) => {
|
|
31150
31938
|
console.error("[boot-reembed-scripts] startup backfill failed (non-fatal):", err);
|
|
31151
31939
|
});
|
|
31152
|
-
import("./boot-scrub-logs-
|
|
31940
|
+
import("./boot-scrub-logs-k93kyw8k.js").then(({ runBootScrubLogs }) => runBootScrubLogs()).catch((err) => {
|
|
31153
31941
|
console.error("[boot-scrub-logs] startup scrub failed (non-fatal):", err);
|
|
31154
31942
|
});
|
|
31155
31943
|
}).on("error", (err) => {
|