@crewx/sdk 0.9.0-rc.22 → 0.9.0-rc.221
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 +1 -1
- package/dist/account/auth-client.d.ts +61 -0
- package/dist/account/auth-json-v2.d.ts +1 -0
- package/dist/account/auth-json.d.ts +30 -0
- package/dist/account/config.d.ts +37 -0
- package/dist/account/env-bootstrap.d.ts +11 -0
- package/dist/account/errors.d.ts +24 -0
- package/dist/account/index.d.ts +12 -0
- package/dist/account/index.js +2 -0
- package/dist/account/session-manager.d.ts +47 -0
- package/dist/activity-log/builder.d.ts +59 -6
- package/dist/agent/agent-list-view.d.ts +19 -0
- package/dist/agent-interceptor/chain.d.ts +25 -0
- package/dist/agent-interceptor/index.d.ts +6 -0
- package/dist/agent-interceptor/model-runner.d.ts +19 -0
- package/dist/agent-interceptor/program-runner.d.ts +13 -0
- package/dist/agent-interceptor/protocol.d.ts +68 -0
- package/dist/agent-interceptor/run-stop.d.ts +3 -0
- package/dist/agent-interceptor/schema.d.ts +267 -0
- package/dist/agent-interceptor/types.d.ts +88 -0
- package/dist/app/app-files/args.d.ts +12 -0
- package/dist/app/app-files/errors.d.ts +6 -0
- package/dist/app/app-files/index.d.ts +35 -0
- package/dist/app/app-files/lock.d.ts +26 -0
- package/dist/app/app-files/root.d.ts +22 -0
- package/dist/app/app-files/store.d.ts +48 -0
- package/dist/app/app-files/write.child.d.ts +1 -0
- package/dist/app/app.d.ts +168 -0
- package/dist/app/backend-env.d.ts +3 -0
- package/dist/app/content-media-types.d.ts +2 -0
- package/dist/app/context.d.ts +2 -0
- package/dist/app/entry.d.ts +9 -0
- package/dist/app/frame.d.ts +55 -0
- package/dist/app/index.d.ts +20 -0
- package/dist/app/index.js +13 -0
- package/dist/app/job-bridge.child.d.ts +1 -0
- package/dist/app/job-bridge.d.ts +67 -0
- package/dist/app/job-bridge.drain.child.d.ts +1 -0
- package/dist/app/job-bridge.example.d.ts +11 -0
- package/dist/app/job-contract.d.ts +40 -0
- package/dist/app/job-wire.d.ts +149 -0
- package/dist/app/protocol.d.ts +9 -0
- package/dist/app/runtime.d.ts +23 -0
- package/dist/app/schedule-contract.d.ts +59 -0
- package/dist/app/tool-mode.d.ts +3 -0
- package/dist/app-artifact-policy/check.d.ts +2 -0
- package/dist/app-artifact-policy/contract.d.ts +54 -0
- package/dist/app-artifact-policy/helper.d.ts +15 -0
- package/dist/app-artifact-policy/index.d.ts +3 -0
- package/dist/app-artifact-policy/index.js +18 -0
- package/dist/app-artifact-policy/paths.d.ts +24 -0
- package/dist/app-artifact-policy/scan.d.ts +47 -0
- package/dist/app-sync/continuation.d.ts +67 -0
- package/dist/app-sync/coordinator.d.ts +92 -0
- package/dist/app-sync/create-ledger.d.ts +27 -0
- package/dist/app-sync/index.d.ts +9 -0
- package/dist/app-sync/index.js +390 -0
- package/dist/app-sync/scope.d.ts +35 -0
- package/dist/app-sync/session-fence.d.ts +26 -0
- package/dist/app-sync/sqlite-store.d.ts +237 -0
- package/dist/app-sync/types.d.ts +855 -0
- package/dist/app-ui/index.d.ts +95 -0
- package/dist/app-ui/index.js +1 -0
- package/dist/attachment-receive/index.d.ts +76 -0
- package/dist/attachment-receive/index.js +2 -0
- package/dist/boxing/box.types.d.ts +4 -0
- package/dist/config/canonicalize-agent-options.d.ts +2 -0
- package/dist/config/default-agent-models.d.ts +11 -0
- package/dist/config/global-settings.d.ts +33 -0
- package/dist/config/migrate-grok-mode.d.ts +6 -0
- package/dist/config/model-compat.d.ts +31 -0
- package/dist/config/models.generated.d.ts +38 -0
- package/dist/config/models.remote.d.ts +1 -0
- package/dist/config/overdrive.d.ts +7 -0
- package/dist/config/pricing.d.ts +6 -3
- package/dist/config/pricing.generated.d.ts +4 -0
- package/dist/config/pricing.types.d.ts +4 -0
- package/dist/config/timeout.config.d.ts +4 -0
- package/dist/config/wi-boards.d.ts +19 -0
- package/dist/context/GoalLoader.d.ts +6 -0
- package/dist/context-budget/continuity.d.ts +64 -0
- package/dist/context-budget/fixed-slot-shrink.d.ts +97 -0
- package/dist/context-budget/index.d.ts +168 -0
- package/dist/conversation/index.d.ts +1 -1
- package/dist/conversation/sqlite-provider.d.ts +6 -3
- package/dist/conversation/to-template-messages.d.ts +9 -0
- package/dist/conversation/types.d.ts +86 -1
- package/dist/desktop/command-runner.d.ts +4 -0
- package/dist/desktop/default-adapters.d.ts +4 -0
- package/dist/desktop/global-install.d.ts +19 -0
- package/dist/desktop/index.d.ts +3 -0
- package/dist/desktop/index.js +3 -0
- package/dist/desktop/install.d.ts +5 -0
- package/dist/desktop/lnk.d.ts +22 -0
- package/dist/desktop/manifest.d.ts +21 -0
- package/dist/desktop/types.d.ts +67 -0
- package/dist/desktop/version.d.ts +1 -0
- package/dist/desktop/windows-paths.d.ts +21 -0
- package/dist/desktop/wrapper.d.ts +18 -0
- package/dist/esm/account/index.js +2 -0
- package/dist/esm/app/index.js +13 -0
- package/dist/esm/app-artifact-policy/index.js +18 -0
- package/dist/esm/app-sync/index.js +390 -0
- package/dist/esm/attachment-receive/index.js +2 -0
- package/dist/esm/desktop/index.js +3 -0
- package/dist/esm/history-snapshot/index.js +16 -0
- package/dist/esm/index.js +1394 -224
- package/dist/esm/node/index.js +2 -0
- package/dist/esm/plugins/index.js +569 -219
- package/dist/esm/process/index.js +1 -0
- package/dist/esm/publish/index.js +2 -0
- package/dist/esm/repository/index.js +828 -211
- package/dist/esm/skills/index.js +2 -0
- package/dist/esm/testing/index.js +1 -1
- package/dist/events/types.d.ts +44 -0
- package/dist/facade/Crewx.d.ts +107 -5
- package/dist/facade/task-ticket.d.ts +14 -0
- package/dist/highlight/thread-highlight-prompt.d.ts +2 -0
- package/dist/highlight/thread-highlighter.d.ts +326 -0
- package/dist/history-snapshot/index.d.ts +83 -0
- package/dist/history-snapshot/index.js +16 -0
- package/dist/index.browser.d.ts +26 -1
- package/dist/index.browser.js +6 -2
- package/dist/index.d.ts +169 -19
- package/dist/index.js +1394 -224
- package/dist/internal/console-decoder.d.ts +38 -0
- package/dist/internal/windows-spawn.d.ts +10 -0
- package/dist/layout/types.d.ts +18 -1
- package/dist/lifecycle/process-lease.d.ts +80 -0
- package/dist/lifecycle/process-owner.d.ts +20 -0
- package/dist/lifecycle/task-heartbeat.d.ts +41 -0
- package/dist/lifecycle/task-stop.d.ts +112 -0
- package/dist/lifecycle/update-admission.d.ts +45 -0
- package/dist/local-server/base-url.d.ts +18 -0
- package/dist/local-server/index.d.ts +8 -0
- package/dist/local-server/opencode.d.ts +8 -0
- package/dist/local-server/probe.d.ts +3 -0
- package/dist/local-server/runtime.d.ts +26 -0
- package/dist/local-server/types.d.ts +43 -0
- package/dist/mcp-app/agent-access.d.ts +33 -0
- package/dist/mcp-app/app-handoff.d.ts +109 -0
- package/dist/mcp-app/app-icon-read.d.ts +7 -0
- package/dist/mcp-app/app-job-bridge.d.ts +30 -0
- package/dist/mcp-app/app-job-bridge.example.d.ts +36 -0
- package/dist/mcp-app/app-job.d.ts +168 -0
- package/dist/mcp-app/app-schedule.d.ts +85 -0
- package/dist/mcp-app/apps-context.d.ts +32 -0
- package/dist/mcp-app/bundle-provenance.d.ts +3 -0
- package/dist/mcp-app/candidate-registration.d.ts +4 -0
- package/dist/mcp-app/card-handler.d.ts +7 -0
- package/dist/mcp-app/catalog.d.ts +7 -0
- package/dist/mcp-app/content-channel.d.ts +86 -0
- package/dist/mcp-app/content-declarations.d.ts +31 -0
- package/dist/mcp-app/dev-checks.d.ts +31 -0
- package/dist/mcp-app/diagnostic-reason.d.ts +3 -0
- package/dist/mcp-app/discovery.d.ts +164 -0
- package/dist/mcp-app/errors.d.ts +7 -0
- package/dist/mcp-app/index.d.ts +46 -0
- package/dist/mcp-app/installed-app-ref.d.ts +25 -0
- package/dist/mcp-app/model-context.d.ts +29 -0
- package/dist/mcp-app/node-app-discovery-fs.d.ts +23 -0
- package/dist/mcp-app/product-bundle-assets.d.ts +27 -0
- package/dist/mcp-app/product-bundle-loader.d.ts +53 -0
- package/dist/mcp-app/projection.d.ts +14 -0
- package/dist/mcp-app/prompt-cards.d.ts +28 -0
- package/dist/mcp-app/registry.d.ts +28 -0
- package/dist/mcp-app/skill-backend.d.ts +141 -0
- package/dist/mcp-app/state-set.d.ts +9 -0
- package/dist/mcp-app/types.d.ts +501 -0
- package/dist/mcp-app/view-call.d.ts +7 -0
- package/dist/mcp-app/workspace-app-assets.d.ts +42 -0
- package/dist/mcp-app/workspace-app-scan-cache.d.ts +27 -0
- package/dist/mcp-app/workspace-snapshot.d.ts +81 -0
- package/dist/migrations/0011_far_black_tarantula.sql +1 -0
- package/dist/migrations/0012_blue_turbo.sql +23 -0
- package/dist/migrations/0013_hesitant_adam_destine.sql +15 -0
- package/dist/migrations/0014_organic_mongu.sql +73 -0
- package/dist/migrations/0015_panoramic_gorilla_man.sql +71 -0
- package/dist/migrations/0016_fuzzy_hemingway.sql +14 -0
- package/dist/migrations/0017_project_stage_sdk_migration.sql +29 -0
- package/dist/migrations/0018_bored_jackal.sql +33 -0
- package/dist/migrations/0019_backfill_task_thread_ids.sql +74 -0
- package/dist/migrations/0020_useful_iron_lad.sql +55 -0
- package/dist/migrations/0021_dashing_peter_quill.sql +51 -0
- package/dist/migrations/0022_wandering_bucky.sql +1 -0
- package/dist/migrations/0023_red_payback.sql +1 -0
- package/dist/migrations/0024_storage_metadata.sql +262 -0
- package/dist/migrations/0025_task_heartbeat.sql +8 -0
- package/dist/migrations/0025_thread_app_instance_ledger.sql +2 -0
- package/dist/migrations/0026_mcp_action_source.sql +47 -0
- package/dist/migrations/0027_task_stop_scope_cleanup.sql +5 -0
- package/dist/migrations/0027_ui_instance_active_unique.sql +2 -0
- package/dist/migrations/0029_nice_rhino.sql +1 -0
- package/dist/migrations/0031_petite_arclight.sql +6 -0
- package/dist/migrations/0032_ui_instance_opened_by.sql +1 -0
- package/dist/migrations/0033_thread_creator_boundary_guard.sql +38 -0
- package/dist/migrations/0034_keen_fallen_one.sql +36 -0
- package/dist/migrations/0035_request_log_daily.sql +11 -0
- package/dist/migrations/0036_ui_definition_archive.sql +8 -0
- package/dist/migrations/0037_ui_instance_agent_open_request.sql +1 -0
- package/dist/migrations/0038_task_rating.sql +3 -0
- package/dist/migrations/0039_aspiring_purifiers.sql +9 -0
- package/dist/migrations/0040_task_provider_inputs.sql +53 -0
- package/dist/migrations/0041_tranquil_vivisector.sql +54 -0
- package/dist/migrations/0042_breezy_blue_shield.sql +31 -0
- package/dist/migrations/0043_nervous_darkstar.sql +1 -0
- package/dist/migrations/0044_military_galactus.sql +8 -0
- package/dist/migrations/0045_task_pid_started_at.sql +1 -0
- package/dist/migrations/0046_acoustic_karnak.sql +49 -0
- package/dist/migrations/0047_doc_sync_connect_requests.sql +18 -0
- package/dist/migrations/0048_smart_gertrude_yorkes.sql +47 -0
- package/dist/migrations/0049_blue_sleepwalker.sql +25 -0
- package/dist/migrations/0050_rapid_black_cat.sql +89 -0
- package/dist/migrations/0051_lying_sinister_six.sql +1 -0
- package/dist/migrations/0052_lying_gambit.sql +33 -0
- package/dist/migrations/0053_smart_shriek.sql +172 -0
- package/dist/migrations/0054_lying_surge.sql +63 -0
- package/dist/migrations/0055_curious_talkback.sql +92 -0
- package/dist/migrations/0056_stale_menace.sql +14 -0
- package/dist/migrations/0057_eager_captain_flint.sql +18 -0
- package/dist/migrations/meta/0011_snapshot.json +1342 -0
- package/dist/migrations/meta/0012_snapshot.json +1494 -0
- package/dist/migrations/meta/0013_snapshot.json +1592 -0
- package/dist/migrations/meta/0014_snapshot.json +1975 -0
- package/dist/migrations/meta/0015_snapshot.json +2315 -0
- package/dist/migrations/meta/0016_snapshot.json +2419 -0
- package/dist/migrations/meta/0017_snapshot.json +2419 -0
- package/dist/migrations/meta/0018_snapshot.json +2570 -0
- package/dist/migrations/meta/0020_snapshot.json +2895 -0
- package/dist/migrations/meta/0021_snapshot.json +3031 -0
- package/dist/migrations/meta/0022_snapshot.json +3039 -0
- package/dist/migrations/meta/0023_snapshot.json +3047 -0
- package/dist/migrations/meta/0029_snapshot.json +3206 -0
- package/dist/migrations/meta/0031_snapshot.json +3251 -0
- package/dist/migrations/meta/0034_snapshot.json +3473 -0
- package/dist/migrations/meta/0035_snapshot.json +3547 -0
- package/dist/migrations/meta/0036_snapshot.json +3591 -0
- package/dist/migrations/meta/0037_snapshot.json +3598 -0
- package/dist/migrations/meta/0038_snapshot.json +3626 -0
- package/dist/migrations/meta/0039_snapshot.json +3684 -0
- package/dist/migrations/meta/0040_snapshot.json +3759 -0
- package/dist/migrations/meta/0041_snapshot.json +4156 -0
- package/dist/migrations/meta/0042_snapshot.json +4383 -0
- package/dist/migrations/meta/0043_snapshot.json +4390 -0
- package/dist/migrations/meta/0044_snapshot.json +4435 -0
- package/dist/migrations/meta/0045_snapshot.json +4442 -0
- package/dist/migrations/meta/0046_snapshot.json +4733 -0
- package/dist/migrations/meta/0047_snapshot.json +4832 -0
- package/dist/migrations/meta/0048_snapshot.json +5128 -0
- package/dist/migrations/meta/0049_snapshot.json +5165 -0
- package/dist/migrations/meta/0050_snapshot.json +5717 -0
- package/dist/migrations/meta/0051_snapshot.json +5725 -0
- package/dist/migrations/meta/0052_snapshot.json +5930 -0
- package/dist/migrations/meta/0053_snapshot.json +6780 -0
- package/dist/migrations/meta/0054_snapshot.json +6784 -0
- package/dist/migrations/meta/0055_snapshot.json +6896 -0
- package/dist/migrations/meta/0056_snapshot.json +6971 -0
- package/dist/migrations/meta/0057_snapshot.json +6971 -0
- package/dist/migrations/meta/_journal.json +329 -0
- package/dist/node/index.d.ts +1 -0
- package/dist/node/index.js +2 -0
- package/dist/paths.d.ts +1 -0
- package/dist/plugin/types.d.ts +1 -0
- package/dist/plugins/index.d.ts +1 -1
- package/dist/plugins/index.js +569 -219
- package/dist/plugins/sqlite-tracing.d.ts +46 -0
- package/dist/process/index.d.ts +2 -0
- package/dist/process/index.js +1 -0
- package/dist/process/process-control.d.ts +74 -0
- package/dist/prompt/tag-names.d.ts +22 -0
- package/dist/provider/acp/adapter.d.ts +37 -2
- package/dist/provider/acp/adapters/antigravity-account.d.ts +4 -0
- package/dist/provider/acp/completion-observer.d.ts +24 -0
- package/dist/provider/acp/connection.d.ts +69 -3
- package/dist/provider/acp/index.d.ts +3 -3
- package/dist/provider/acp/meta.d.ts +11 -0
- package/dist/provider/acp/register.d.ts +1 -0
- package/dist/provider/acp/runtime.d.ts +1 -0
- package/dist/provider/acp/types.d.ts +31 -4
- package/dist/provider/bridge.browser.d.ts +3 -0
- package/dist/provider/bridge.d.ts +28 -4
- package/dist/provider/classify-task-error.d.ts +2 -0
- package/dist/provider/claude-agent-env.d.ts +1 -0
- package/dist/provider/cli/adapter.types.d.ts +35 -7
- package/dist/provider/cli/adapters/agent-call.util.d.ts +1 -1
- package/dist/provider/cli/adapters/antigravity-stream.d.ts +27 -0
- package/dist/provider/cli/adapters/antigravity.d.ts +1 -0
- package/dist/provider/cli/adapters/cli-knob.util.d.ts +7 -0
- package/dist/provider/cli/adapters/codex-item.d.ts +1 -0
- package/dist/provider/cli/adapters/event-timestamp.util.d.ts +1 -0
- package/dist/provider/cli/adapters/grok.d.ts +2 -0
- package/dist/provider/cli/adapters/index.d.ts +5 -0
- package/dist/provider/cli/adapters/opencode-data-dir.d.ts +17 -0
- package/dist/provider/cli/adapters/opencode.d.ts +1 -0
- package/dist/provider/cli/builtin-allow.d.ts +6 -0
- package/dist/provider/cli/index.d.ts +3 -2
- package/dist/provider/cli/meta.d.ts +18 -1
- package/dist/provider/cli/protocol-envelope.d.ts +3 -0
- package/dist/provider/errors.d.ts +11 -1
- package/dist/provider/idle-watchdog.d.ts +19 -0
- package/dist/provider/model-ladder.d.ts +8 -0
- package/dist/provider/models.d.ts +17 -12
- package/dist/provider/order.d.ts +1 -1
- package/dist/provider/parse-usage.d.ts +6 -0
- package/dist/provider/provider-selection.d.ts +8 -0
- package/dist/provider/redact-technical-message.d.ts +1 -0
- package/dist/provider/safe-opencode-text.d.ts +2 -0
- package/dist/provider/task-error.types.d.ts +20 -0
- package/dist/provider-account/accounts.d.ts +15 -0
- package/dist/provider-account/antigravity-acp/auth.d.ts +29 -0
- package/dist/provider-account/antigravity-acp/browser.d.ts +4 -0
- package/dist/provider-account/antigravity-acp/install.d.ts +42 -0
- package/dist/provider-account/antigravity-acp/lease.d.ts +23 -0
- package/dist/provider-account/antigravity-acp/lifecycle.d.ts +76 -0
- package/dist/provider-account/antigravity-acp/manifest.d.ts +76 -0
- package/dist/provider-account/antigravity-acp/profile.d.ts +4 -0
- package/dist/provider-account/capabilities.d.ts +6 -0
- package/dist/provider-account/index.d.ts +13 -0
- package/dist/provider-account/registry.d.ts +30 -0
- package/dist/provider-account/types.d.ts +47 -0
- package/dist/publish/constants.d.ts +6 -0
- package/dist/publish/errors.d.ts +7 -0
- package/dist/publish/index.d.ts +55 -0
- package/dist/publish/index.js +2 -0
- package/dist/publish/manifest.d.ts +47 -0
- package/dist/publish/marketplace-api.constants.d.ts +1 -0
- package/dist/publish/pack.d.ts +6 -0
- package/dist/publish/scan.d.ts +10 -0
- package/dist/publish/secrets.d.ts +6 -0
- package/dist/publish/upload.d.ts +19 -0
- package/dist/remote/execution-profile.d.ts +9 -0
- package/dist/remote/index.d.ts +1 -0
- package/dist/remote/types.d.ts +28 -0
- package/dist/repository/agent-send-history.repository.d.ts +23 -0
- package/dist/repository/agent-suggestion.repository.d.ts +34 -0
- package/dist/repository/base-sqlite-repository.d.ts +1 -0
- package/dist/repository/common-code.repository.d.ts +45 -0
- package/dist/repository/db.d.ts +13 -1
- package/dist/repository/index.d.ts +62 -6
- package/dist/repository/index.js +828 -211
- package/dist/repository/logs-db.d.ts +12 -0
- package/dist/repository/notification.repository.d.ts +58 -0
- package/dist/repository/project.repository.d.ts +90 -0
- package/dist/repository/public-task-answer.d.ts +24 -0
- package/dist/repository/request-log-mover.d.ts +70 -0
- package/dist/repository/request-log.repository.d.ts +7 -3
- package/dist/repository/run-columns.d.ts +10 -0
- package/dist/repository/run-history.repository.d.ts +112 -0
- package/dist/repository/schedule-run.repository.d.ts +103 -0
- package/dist/repository/sidebar-tab.repository.d.ts +86 -0
- package/dist/repository/storage-metadata.repository.d.ts +64 -0
- package/dist/repository/task-log-migration.d.ts +74 -0
- package/dist/repository/task-log.repository.d.ts +47 -0
- package/dist/repository/task-status.d.ts +21 -0
- package/dist/repository/task.repository.d.ts +329 -8
- package/dist/repository/thread-history.repository.d.ts +193 -0
- package/dist/repository/thread-origin-verdict.d.ts +27 -0
- package/dist/repository/thread-title.types.d.ts +29 -0
- package/dist/repository/thread.repository.d.ts +134 -5
- package/dist/repository/usage-backfill.d.ts +62 -0
- package/dist/repository/usage-from-logs.d.ts +22 -0
- package/dist/repository/workflow-anchor-kinds.d.ts +4 -0
- package/dist/repository/workspace.repository.d.ts +3 -0
- package/dist/route/decide.d.ts +56 -0
- package/dist/route/eligibility.d.ts +11 -0
- package/dist/route/errors.d.ts +11 -0
- package/dist/route/index.d.ts +14 -0
- package/dist/route/runner.d.ts +15 -0
- package/dist/route/sqlite-store.d.ts +18 -0
- package/dist/route/store.d.ts +48 -0
- package/dist/route/strategies.d.ts +4 -0
- package/dist/route/types.d.ts +325 -0
- package/dist/schema/agent-send-history.d.ts +85 -0
- package/dist/schema/agent-suggestions.d.ts +199 -0
- package/dist/schema/app-sync.d.ts +2533 -0
- package/dist/schema/common-codes.d.ts +216 -0
- package/dist/schema/doc-create-dispatches.d.ts +101 -0
- package/dist/schema/doc-sync-connect-requests.d.ts +140 -0
- package/dist/schema/doc-sync-links.d.ts +556 -0
- package/dist/schema/index.d.ts +23 -0
- package/dist/schema/model-routes.d.ts +638 -0
- package/dist/schema/notifications.d.ts +303 -0
- package/dist/schema/projects.d.ts +610 -0
- package/dist/schema/request-log-daily.d.ts +151 -0
- package/dist/schema/run-column-backfill.d.ts +81 -0
- package/dist/schema/schedule-runs.d.ts +451 -0
- package/dist/schema/sidebar-tabs.d.ts +466 -0
- package/dist/schema/storage-metadata.d.ts +181 -0
- package/dist/schema/task-log-events.d.ts +119 -0
- package/dist/schema/task-provider-inputs.d.ts +100 -0
- package/dist/schema/tasks.d.ts +1172 -1
- package/dist/schema/thread-creator-unverified.d.ts +45 -0
- package/dist/schema/thread-history.d.ts +734 -0
- package/dist/schema/threads.d.ts +59 -0
- package/dist/schema/ui-action-receipts.d.ts +358 -0
- package/dist/schema/ui-definition-archive.d.ts +63 -0
- package/dist/schema/ui-instance-repins.d.ts +222 -0
- package/dist/schema/ui-instances.d.ts +324 -0
- package/dist/schema/workspaces.d.ts +17 -0
- package/dist/skills/index.d.ts +15 -0
- package/dist/skills/index.js +2 -0
- package/dist/skills/types.d.ts +18 -0
- package/dist/task-log/anchor-child-tasks.d.ts +7 -0
- package/dist/task-log/delegation-trailer.d.ts +34 -0
- package/dist/template/engine.d.ts +2 -2
- package/dist/template/helpers/exec.browser.d.ts +4 -3
- package/dist/template/helpers/exec.d.ts +4 -3
- package/dist/template/helpers/format-conversation.d.ts +1 -0
- package/dist/template/types.d.ts +20 -0
- package/dist/testing/index.js +1 -1
- package/dist/types/index.d.ts +3285 -84
- package/dist/types/task-log.types.d.ts +6 -1
- package/dist/ui-card/index.d.ts +2 -0
- package/dist/ui-card/legacy-card-parser.d.ts +11 -0
- package/dist/ui-instance/definition.d.ts +6 -0
- package/dist/ui-instance/errors.d.ts +18 -0
- package/dist/ui-instance/index.d.ts +11 -0
- package/dist/ui-instance/json.d.ts +19 -0
- package/dist/ui-instance/lineage.d.ts +24 -0
- package/dist/ui-instance/runtime.d.ts +19 -0
- package/dist/ui-instance/store.d.ts +216 -0
- package/dist/ui-instance/types.d.ts +384 -0
- package/dist/ui-plugin/app-icon.d.ts +50 -0
- package/dist/ui-plugin/app-manifest.d.ts +64 -0
- package/dist/ui-plugin/csp.d.ts +28 -0
- package/dist/ui-plugin/index.d.ts +8 -0
- package/dist/ui-plugin/limits.d.ts +27 -0
- package/dist/ui-plugin/manifest.d.ts +3 -0
- package/dist/ui-plugin/types.d.ts +220 -0
- package/dist/ui-plugin/validator.d.ts +18 -0
- package/dist/utils/crewx-executable.d.ts +76 -0
- package/dist/utils/crewx-home.d.ts +1 -0
- package/dist/utils/env-defaults.d.ts +3 -0
- package/dist/utils/id.d.ts +1 -1
- package/dist/utils/local-identity.d.ts +2 -0
- package/dist/utils/runner-env.d.ts +3 -0
- package/dist/utils/timestamp.d.ts +1 -0
- package/dist/utils/workspace.d.ts +1 -0
- package/dist/wi/create.d.ts +48 -0
- package/dist/wi/select.d.ts +20 -0
- package/package.json +90 -3
- package/templates/agents/default.yaml +311 -128
- package/templates/documents/crewx-manual.md +138 -138
- package/templates/documents/crewx-quick-guide.md +8 -7
- package/templates/workflows/wi-default-flow.yaml +65 -0
- package/templates/workflows/wi-plan-flow.yaml +140 -0
|
@@ -0,0 +1,390 @@
|
|
|
1
|
+
'use strict';var fs$1=require('fs'),ee=require('path'),Bo=require('os'),crypto=require('crypto'),sqliteCore=require('drizzle-orm/sqlite-core'),drizzleOrm=require('drizzle-orm'),child_process=require('child_process');require('string_decoder'),require('fs/promises');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var ee__default=/*#__PURE__*/_interopDefault(ee);var Bo__default=/*#__PURE__*/_interopDefault(Bo);var vt=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,n)=>(typeof require<"u"?require:e)[n]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var k=(t,e)=>()=>(t&&(e=t(t=0)),e);var d=k(()=>{});function $o(t){if(t===":memory:")return t;let e=ee.resolve(t),n=e,r=[];for(;!fs$1.existsSync(n);){let s=ee.dirname(n);if(s===n)return e;r.unshift(n.slice(s.length+1)),n=s;}let o=fs$1.realpathSync(n);for(let s of r)o=ee.join(o,s);return ee.resolve(o)}function nd(t,e){let n=$o(t),r=$o(e);return process.platform==="win32"?n.toLowerCase()===r.toLowerCase():n===r}function Xe(t){if((process.env.NODE_ENV==="test"||process.env.VITEST!==void 0)&&rd.some(e=>nd(t,ee.join(Bo__default.default.homedir(),".crewx",e))))throw new Error(`${td}: ${t}. Set CREWX_DB to an isolated temporary path or :memory:.`);return t}var td,rd,D,P=k(()=>{d();td="[crewx] Refusing to open the real CrewX database from a test process";rd=["crewx.db","logs.db"];D=class{resolveDbPath(){if(process.env.CREWX_TRACES_DB!==void 0)throw new Error(`CREWX_TRACES_DB is removed. Use CREWX_DB instead. (got: ${process.env.CREWX_TRACES_DB})`);let e=process.env.CREWX_DB||ee.join(Bo__default.default.homedir(),".crewx","crewx.db");return Xe(e)}resolveDbPaths(){return [this.resolveDbPath()]}isMissingTableError(e){return e instanceof Error&&/no such table:/i.test(e.message)}dbExists(e){return fs$1.existsSync(e??this.resolveDbPath())}};});var M=k(()=>{d();});function x(t,e={}){let n=Xe(t),r=vt("better-sqlite3"),{drizzle:o}=vt("drizzle-orm/better-sqlite3"),s=e.readOnly?new r(n,{readonly:true,fileMustExist:true}):new r(n);return e.readOnly||(s.exec("PRAGMA journal_mode = WAL"),s.exec(`PRAGMA journal_size_limit = ${ln}`),s.exec("PRAGMA busy_timeout = 5000"),s.exec("PRAGMA foreign_keys = ON"),s.exec("PRAGMA analysis_limit = 400")),{db:o(s),sqlite:s,runRaw:(i,a=[])=>s.prepare(i).run(...a),close:()=>s.close()}}var ln,F=k(()=>{d();P();ln=32*1024*1024;});function gt(t,e){return (t.get(`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='${e}'`)?.cnt??0)>0}function id(t,e){if(e>0||!gt(t,"tasks"))return;let n=t.all("PRAGMA table_info(tasks)"),r=new Set(n.map(o=>o.name));for(let[o,s]of Object.entries(sd))r.has(o)||t.run(`ALTER TABLE tasks ADD COLUMN ${o} ${s}`);}function dd(t,e,n){if(!gt(t,"__drizzle_migrations")||!gt(t,"tasks"))return;let r=t.all(n`SELECT hash FROM __drizzle_migrations`),o=new Set(r.map(i=>i.hash)),s=JSON.parse(fs$1.readFileSync(ee__default.default.join(e,"meta/_journal.json"),"utf-8"));for(let i of s.entries){let a=ad[i.tag];if(!a)continue;let c=ee__default.default.join(e,`${i.tag}.sql`);if(!fs$1.existsSync(c))continue;let u=fs$1.readFileSync(c,"utf-8"),p=crypto.createHash("sha256").update(u).digest("hex");if(o.has(p))continue;let g=t.all("PRAGMA table_info(tasks)"),_=new Set(g.map(S=>S.name));for(let[S,w]of Object.entries(a))_.has(S)||(t.run(`ALTER TABLE tasks ADD COLUMN ${S} ${w}`),_.add(S));}}function Wo(t){let e=t.trim().replace(/;+\s*$/,"").trim(),n=e.match(/^ALTER\s+TABLE\s+[`"]?([A-Za-z_][\w$]*)[`"]?\s+ADD\s+(?:COLUMN\s+)?[`"]?([A-Za-z_][\w$]*)[`"]?/i);if(n)return {kind:"add-column",table:n[1],column:n[2]};let r=e.match(/^CREATE\s+(?:UNIQUE\s+)?INDEX(?:\s+IF\s+NOT\s+EXISTS)?\s+[`"]?([A-Za-z_][\w$]*)[`"]?\s+ON\s+/i);if(r)return {kind:"create-index",name:r[1]};let o=e.match(/^DROP\s+INDEX\s+IF\s+EXISTS\s+[`"]?([A-Za-z_][\w$]*)[`"]?/i);if(o)return {kind:"drop-index",name:o[1]}}function Ko(t){return t.split(/-->\s*statement-breakpoint/).map(e=>e.trim()).filter(Boolean)}function cd(t,e,n){return t.all(`PRAGMA table_info("${e}")`).some(s=>s.name===n)}function ud(t,e){return t.all(`SELECT name FROM sqlite_master WHERE type = 'index' AND name = '${e}'`).length>0}function pn(t,e){return e.kind==="add-column"?cd(t,e.table,e.column):ud(t,e.name)}function Vo(t,e,n){let r=t;for(let o of Ko(e)){let s=Wo(o);s?.kind==="add-column"&&pn(r,s)||s?.kind==="create-index"&&pn(r,s)||s?.kind==="drop-index"&&!pn(r,s)||r.run(n.raw(o));}}function ld(t,e,n){let r=t.all(n`SELECT hash FROM __drizzle_migrations`),o=new Set(r.map(i=>i.hash)),s=JSON.parse(fs$1.readFileSync(ee__default.default.join(e,"meta/_journal.json"),"utf-8"));for(let i of s.entries){let a=ee__default.default.join(e,`${i.tag}.sql`);if(!fs$1.existsSync(a))continue;let c=fs$1.readFileSync(a,"utf-8"),u=crypto.createHash("sha256").update(c).digest("hex");if(o.has(u))continue;let g=Ko(c).map(Wo);if(g.some(S=>!S))continue;let _=g;_.some(S=>S.kind==="add-column")&&_.some(S=>pn(t,S))&&(t.transaction(S=>{Vo(S,c,n),S.run(n`INSERT INTO __drizzle_migrations (hash, created_at) VALUES (${u}, ${i.when})`);},{behavior:"immediate"}),o.add(u),console.error(`[crewx] Reconciled additive migration ${i.tag} from existing schema objects.`));}}function pd(t,e){let{sql:n}=vt("drizzle-orm"),r=JSON.parse(fs$1.readFileSync(ee__default.default.join(e,"meta/_journal.json"),"utf-8")),s=["0025_task_heartbeat","0025_thread_app_instance_ledger","0026_mcp_action_source","0027_ui_instance_active_unique"].map(i=>{let a=r.entries.find(u=>u.tag===i);if(!a)throw new Error(`Missing release/App compatibility migration: ${i}`);let c=fs$1.readFileSync(ee__default.default.join(e,`${i}.sql`),"utf-8");return {entry:a,content:c,hash:crypto.createHash("sha256").update(c).digest("hex")}});t.transaction(i=>{let a=new Set(i.all(n`SELECT hash FROM __drizzle_migrations`).map(c=>c.hash));if(a.has(s[0].hash))for(let c of s.slice(1))a.has(c.hash)||(Vo(i,c.content,n),i.run(n`INSERT INTO __drizzle_migrations (hash, created_at) VALUES (${c.hash}, ${c.entry.when})`),a.add(c.hash),console.error(`[crewx] Replayed release/App migration ${c.entry.tag} safely.`));},{behavior:"immediate"});}function hd(t,e,n,r){let s=JSON.parse(fs$1.readFileSync(ee__default.default.join(e,"meta/_journal.json"),"utf-8")).entries.find(({tag:g})=>g===_d);if(!s)return;let i=ee__default.default.join(e,`${s.tag}.sql`);if(!fs$1.existsSync(i))return;let a=crypto.createHash("sha256").update(fs$1.readFileSync(i,"utf-8")).digest("hex");if(r&&t.all(n`SELECT hash FROM __drizzle_migrations`).some(_=>_.hash===a))return;if(!gt(t,"tasks"))return {hash:a,affectedRows:0};let c=t.all("PRAGMA table_info(tasks)"),u=new Set(c.map(g=>g.name));if(!u.has("stop_requested_at")||!u.has("stop_requested_epoch"))return {hash:a,affectedRows:0};let p=t.get(n`
|
|
2
|
+
SELECT count(*) AS count
|
|
3
|
+
FROM tasks
|
|
4
|
+
WHERE status IN ('success', 'failed')
|
|
5
|
+
AND (stop_requested_at IS NOT NULL OR stop_requested_epoch IS NOT NULL)
|
|
6
|
+
`);return {hash:a,affectedRows:p?.count??0}}function md(t,e,n,r){let s=JSON.parse(fs$1.readFileSync(ee__default.default.join(e,"meta/_journal.json"),"utf-8")).entries.find(({tag:g})=>g===gd);if(!s)return;let i=ee__default.default.join(e,`${s.tag}.sql`);if(!fs$1.existsSync(i))return;let a=crypto.createHash("sha256").update(fs$1.readFileSync(i,"utf-8")).digest("hex");if(r&&t.all(n`SELECT hash FROM __drizzle_migrations`).some(_=>_.hash===a))return;if(!gt(t,"threads"))return {hash:a,markedPointers:0};if(!t.all("PRAGMA table_info(threads)").some(g=>g.name==="created_by_task_id"))return {hash:a,markedPointers:0};let u=gt(t,jo)?`AND NOT EXISTS (
|
|
7
|
+
SELECT 1
|
|
8
|
+
FROM ${jo} AS marked
|
|
9
|
+
WHERE marked.thread_id = current.id
|
|
10
|
+
AND marked.created_by_task_id = current.created_by_task_id
|
|
11
|
+
)`:"",p=t.get(`SELECT count(*) AS count
|
|
12
|
+
FROM threads AS current
|
|
13
|
+
WHERE current.created_by_task_id IS NOT NULL
|
|
14
|
+
AND NOT EXISTS (
|
|
15
|
+
SELECT 1
|
|
16
|
+
FROM sqlite_master
|
|
17
|
+
WHERE type = 'trigger'
|
|
18
|
+
AND name = '${fd}'
|
|
19
|
+
)
|
|
20
|
+
${u}`);return {hash:a,markedPointers:p?.count??0}}function _n(t){let{migrate:e}=vt("drizzle-orm/better-sqlite3/migrator"),{sql:n}=vt("drizzle-orm"),r=[ee__default.default.join(__dirname,"../migrations"),ee__default.default.join(__dirname,"migrations"),ee__default.default.join(__dirname,"../../../../drizzle/migrations"),ee__default.default.join(process.cwd(),"drizzle/migrations")],o=r.find(g=>fs$1.existsSync(ee__default.default.join(g,"meta/_journal.json")));if(!o)throw new Error(`migrations folder not found. Searched:
|
|
21
|
+
${r.join(`
|
|
22
|
+
`)}`);let s=t.get(n`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='__drizzle_migrations'`),i=0;s?.cnt&&(i=t.get(n`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0),id(t,i),s?.cnt&&(pd(t,o),ld(t,o,n),dd(t,o,n));let a=hd(t,o,n,!!s?.cnt),c=md(t,o,n,!!s?.cnt);e(t,{migrationsFolder:o});let p=(t.get(n`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0)-i;if(p>0){let g=s?.cnt?"Database migrated":"Database initialized";console.error(`[crewx] ${g} (${p} migration${p>1?"s":""} applied).`);}a&&t.all(n`SELECT hash FROM __drizzle_migrations`).some(_=>_.hash===a.hash)&&console.error(`[crewx] Task stop-marker cleanup (${a.affectedRows} success/failed row(s) affected).`),c&&t.all(n`SELECT hash FROM __drizzle_migrations`).some(_=>_.hash===c.hash)&&console.error(`[crewx] Thread creator pointer migration (${c.markedPointers} pointer(s) marked unverified).`);}function H(t,e){Go.has(e)||(_n(t),Go.add(e));}var Go,sd,ad,_d,gd,fd,jo,q=k(()=>{d();Go=new Set,sd={agent_id:"TEXT",status:"TEXT DEFAULT 'running'",started_at:"TEXT",trace_id:"TEXT",parent_task_id:"TEXT",crewx_version:"TEXT",pid:"INTEGER",thread_id:"TEXT",workspace_id:"TEXT",workspace_ref:"TEXT",workspace_name:"TEXT",project_id:"TEXT",project_name:"TEXT",command:"TEXT",metadata:"TEXT"};ad={"0002_normalize_task_names":{workspace_name:"TEXT",project_name:"TEXT"},"0015_panoramic_gorilla_man":{project_id:"TEXT",workspace_id:"TEXT"},"0019_backfill_task_thread_ids":{command:"TEXT",thread_id:"TEXT"},"0024_storage_metadata":{prompt:"TEXT",rendered_prompt:"TEXT",result:"TEXT",input_tokens:"INTEGER DEFAULT 0",output_tokens:"INTEGER DEFAULT 0",cost_usd:"REAL DEFAULT 0"},"0044_clammy_bruce_banner":{metadata:"TEXT"}};_d="0027_task_stop_scope_cleanup",gd="0033_thread_creator_boundary_guard",fd="trg_threads_creator_late_fill_guard",jo="thread_creator_unverified";});var ke,gn=k(()=>{d();ke=sqliteCore.sqliteTable("workspaces",{id:sqliteCore.text("id").primaryKey(),slug:sqliteCore.text("slug").notNull().unique(),name:sqliteCore.text("name").notNull(),workspace_path:sqliteCore.text("workspace_path"),description:sqliteCore.text("description"),is_active:sqliteCore.integer("is_active").notNull().default(1),created_at:sqliteCore.text("created_at").notNull(),updated_at:sqliteCore.text("updated_at").notNull(),starred:sqliteCore.integer("starred").notNull().default(0)});});var z,m_,y_,ft=k(()=>{d();z=sqliteCore.sqliteTable("tasks",{id:sqliteCore.text("id").primaryKey(),agent_id:sqliteCore.text("agent_id").notNull(),user_id:sqliteCore.text("user_id"),actor_kind:sqliteCore.text("actor_kind",{enum:["human","agent","system","unknown"]}),actor_id:sqliteCore.text("actor_id"),prompt:sqliteCore.text("prompt").notNull(),mode:sqliteCore.text("mode").notNull().default("execute"),status:sqliteCore.text("status").notNull().default("running"),result:sqliteCore.text("result"),error:sqliteCore.text("error"),started_at:sqliteCore.text("started_at").notNull(),completed_at:sqliteCore.text("completed_at"),duration_ms:sqliteCore.integer("duration_ms"),metadata:sqliteCore.text("metadata"),workspace_id:sqliteCore.text("workspace_id"),trace_id:sqliteCore.text("trace_id"),parent_task_id:sqliteCore.text("parent_task_id"),caller_agent_id:sqliteCore.text("caller_agent_id"),model:sqliteCore.text("model"),platform:sqliteCore.text("platform").default("cli"),crewx_version:sqliteCore.text("crewx_version"),input_tokens:sqliteCore.integer("input_tokens").default(0),output_tokens:sqliteCore.integer("output_tokens").default(0),cost_usd:sqliteCore.real("cost_usd").default(0),pid:sqliteCore.integer("pid"),pid_started_at:sqliteCore.text("pid_started_at"),heartbeat_at:sqliteCore.text("heartbeat_at"),stop_requested_at:sqliteCore.text("stop_requested_at"),stop_requested_epoch:sqliteCore.integer("stop_requested_epoch"),rendered_prompt:sqliteCore.text("rendered_prompt"),security_key:sqliteCore.text("security_key"),command:sqliteCore.text("command"),coding_agent_command:sqliteCore.text("coding_agent_command"),exit_code:sqliteCore.integer("exit_code"),logs:sqliteCore.text("logs"),log_storage:sqliteCore.text("log_storage",{enum:["blob","events"]}).notNull().default("blob"),last_log_seq:sqliteCore.integer("last_log_seq").notNull().default(0),log_revision:sqliteCore.integer("log_revision").notNull().default(0),thread_id:sqliteCore.text("thread_id"),workspace_ref:sqliteCore.text("workspace_ref"),cwd:sqliteCore.text("cwd"),project_id:sqliteCore.text("project_id"),project_ref:sqliteCore.text("project_ref"),cached_input_tokens:sqliteCore.integer("cached_input_tokens").default(0),run_epoch:sqliteCore.integer("run_epoch").default(0),rating:sqliteCore.text("rating",{enum:["up","down"]}),rated_at:sqliteCore.text("rated_at"),workflow_run_id:sqliteCore.text("workflow_run_id"),schedule_id:sqliteCore.text("schedule_id")},t=>({log_storage_check:sqliteCore.check("tasks_log_storage_ck",drizzleOrm.sql`${t.log_storage} IN ('blob', 'events')`),rating_check:sqliteCore.check("tasks_rating_ck",drizzleOrm.sql`${t.rating} IN ('up', 'down')`),idx_tasks_agent_id:sqliteCore.index("idx_tasks_agent_id").on(t.agent_id),idx_tasks_status:sqliteCore.index("idx_tasks_status").on(t.status),idx_tasks_started_at:sqliteCore.index("idx_tasks_started_at").on(t.started_at),idx_tasks_trace_id:sqliteCore.index("idx_tasks_trace_id").on(t.trace_id),idx_tasks_parent_task_id:sqliteCore.index("idx_tasks_parent_task_id").on(t.parent_task_id),idx_tasks_crewx_version:sqliteCore.index("idx_tasks_crewx_version").on(t.crewx_version),idx_tasks_pid:sqliteCore.index("idx_tasks_pid").on(t.pid),idx_tasks_status_heartbeat:sqliteCore.index("idx_tasks_status_heartbeat").on(t.status,t.heartbeat_at),idx_tasks_thread_id:sqliteCore.index("idx_tasks_thread_id").on(t.thread_id),idx_tasks_thread_creator:sqliteCore.index("idx_tasks_thread_creator").on(t.id,t.thread_id,t.actor_kind,t.actor_id),idx_tasks_workspace_id:sqliteCore.index("idx_tasks_workspace_id").on(t.workspace_id),idx_tasks_workspace_ref:sqliteCore.index("idx_tasks_workspace_ref").on(t.workspace_ref),idx_tasks_project_id:sqliteCore.index("idx_tasks_project_id").on(t.project_id),idx_tasks_ws_started:sqliteCore.index("idx_tasks_ws_started").on(t.workspace_id,t.started_at),idx_tasks_ws_rated:sqliteCore.index("idx_tasks_ws_rated").on(t.workspace_id,t.rating,t.rated_at).where(drizzleOrm.sql`${t.rating} IS NOT NULL`)})),{security_key:m_,...y_}=drizzleOrm.getTableColumns(z);});var Xo=k(()=>{d();ft();sqliteCore.sqliteTable("task_provider_inputs",{task_id:sqliteCore.text("task_id").notNull().references(()=>z.id,{onDelete:"cascade"}),run_epoch:sqliteCore.integer("run_epoch").notNull(),input:sqliteCore.text("input").notNull(),key_wrap_skipped:sqliteCore.integer("key_wrap_skipped").notNull().default(0),recorded_at:sqliteCore.text("recorded_at").notNull()},t=>({pk:sqliteCore.primaryKey({columns:[t.task_id,t.run_epoch]})}));});var Zo=k(()=>{d();ft();sqliteCore.sqliteTable("task_log_events",{id:sqliteCore.integer("id").primaryKey(),task_id:sqliteCore.text("task_id").notNull().references(()=>z.id,{onDelete:"cascade"}),seq:sqliteCore.integer("seq").notNull(),timestamp:sqliteCore.text("timestamp").notNull(),level:sqliteCore.text("level").notNull(),message:sqliteCore.text("message").notNull()},t=>({taskSeqUnique:sqliteCore.uniqueIndex("task_log_events_task_seq_uq").on(t.task_id,t.seq),timestampIdIndex:sqliteCore.index("task_log_events_timestamp_id_idx").on(t.timestamp,t.id)}));});var Od,vd,ne,$t=k(()=>{d();gn();Od="json_extract(metadata, '$.threadTitle.state')",vd="json_extract(metadata, '$.threadTitle.priority')",ne=sqliteCore.sqliteTable("threads",{id:sqliteCore.text("id").primaryKey(),workspace_id:sqliteCore.text("workspace_id").references(()=>ke.id,{onDelete:"set null"}),created_by_kind:sqliteCore.text("created_by_kind",{enum:["human","agent","system","unknown"]}),created_by_id:sqliteCore.text("created_by_id"),created_by_task_id:sqliteCore.text("created_by_task_id"),platform:sqliteCore.text("platform").notNull().default("cli"),title:sqliteCore.text("title"),first_message:sqliteCore.text("first_message"),last_message:sqliteCore.text("last_message"),message_count:sqliteCore.integer("message_count").notNull().default(0),created_at:sqliteCore.text("created_at").notNull(),updated_at:sqliteCore.text("updated_at").notNull(),metadata:sqliteCore.text("metadata"),title_locked:sqliteCore.integer("title_locked").notNull().default(0),pinned:sqliteCore.integer("pinned").notNull().default(0),starred:sqliteCore.integer("starred").notNull().default(0)},t=>({idx_threads_updated_at:sqliteCore.index("idx_threads_updated_at").on(t.updated_at),idx_threads_workspace_id:sqliteCore.index("idx_threads_workspace_id").on(t.workspace_id),idx_threads_ws_updated:sqliteCore.index("idx_threads_ws_updated").on(t.workspace_id,t.updated_at),idx_threads_workspace_created_by_kind_updated_at:sqliteCore.index("idx_threads_workspace_created_by_kind_updated_at").on(t.workspace_id,t.created_by_kind,t.updated_at),idx_threads_title:sqliteCore.index("idx_threads_title").on(t.title),idx_threads_workspace_thread_state:sqliteCore.index("idx_threads_workspace_thread_state").on(t.workspace_id,drizzleOrm.sql.raw(Od)),idx_threads_workspace_thread_priority:sqliteCore.index("idx_threads_workspace_thread_priority").on(t.workspace_id,drizzleOrm.sql.raw(vd))}));});var ns=k(()=>{d();sqliteCore.sqliteTable("thread_creator_unverified",{thread_id:sqliteCore.text("thread_id").notNull(),created_by_task_id:sqliteCore.text("created_by_task_id").notNull()},t=>({pk:sqliteCore.primaryKey({columns:[t.thread_id,t.created_by_task_id]})}));});var ur,os=k(()=>{d();ft();ur=sqliteCore.sqliteTable("spans",{id:sqliteCore.text("id").primaryKey(),task_id:sqliteCore.text("task_id").references(()=>z.id,{onDelete:"set null"}),parent_span_id:sqliteCore.text("parent_span_id").references(()=>ur.id,{onDelete:"set null"}),name:sqliteCore.text("name").notNull(),kind:sqliteCore.text("kind").notNull().default("internal"),status:sqliteCore.text("status").notNull().default("ok"),started_at:sqliteCore.text("started_at").notNull(),completed_at:sqliteCore.text("completed_at"),duration_ms:sqliteCore.integer("duration_ms"),input:sqliteCore.text("input"),output:sqliteCore.text("output"),error:sqliteCore.text("error"),attributes:sqliteCore.text("attributes")},t=>({idx_spans_task_id:sqliteCore.index("idx_spans_task_id").on(t.task_id),idx_spans_parent_span_id:sqliteCore.index("idx_spans_parent_span_id").on(t.parent_span_id)}));});var is=k(()=>{d();ft();sqliteCore.sqliteTable("tool_calls",{id:sqliteCore.text("id").primaryKey(),task_id:sqliteCore.text("task_id").references(()=>z.id,{onDelete:"cascade"}),session_id:sqliteCore.text("session_id"),tool_name:sqliteCore.text("tool_name").notNull(),files:sqliteCore.text("files"),input:sqliteCore.text("input"),output:sqliteCore.text("output"),duration_ms:sqliteCore.integer("duration_ms"),timestamp:sqliteCore.text("timestamp").notNull()},t=>({idx_tool_calls_task_id:sqliteCore.index("idx_tool_calls_task_id").on(t.task_id),idx_tool_calls_tool_name:sqliteCore.index("idx_tool_calls_tool_name").on(t.tool_name),idx_tool_calls_timestamp:sqliteCore.index("idx_tool_calls_timestamp").on(t.timestamp)}));});var cs=k(()=>{d();$t();sqliteCore.sqliteTable("thread_boxes",{id:sqliteCore.text("id").primaryKey(),thread_id:sqliteCore.text("thread_id").notNull().references(()=>ne.id,{onDelete:"cascade"}),seq:sqliteCore.integer("seq").notNull(),first_task_id:sqliteCore.text("first_task_id").notNull(),mid_task_id:sqliteCore.text("mid_task_id").notNull(),last_task_id:sqliteCore.text("last_task_id").notNull(),task_count:sqliteCore.integer("task_count").notNull(),summary:sqliteCore.text("summary"),source_tokens:sqliteCore.integer("source_tokens").notNull(),summary_tokens:sqliteCore.integer("summary_tokens"),created_at:sqliteCore.text("created_at").notNull()},t=>({idx_thread_boxes_thread_id:sqliteCore.index("idx_thread_boxes_thread_id").on(t.thread_id),idx_thread_boxes_seq:sqliteCore.index("idx_thread_boxes_seq").on(t.thread_id,t.seq),uniq_thread_boxes_thread_seq:sqliteCore.unique().on(t.thread_id,t.seq)}));});var ls=k(()=>{d();sqliteCore.sqliteTable("request_logs",{id:sqliteCore.text("id").primaryKey(),path:sqliteCore.text("path").notNull(),method:sqliteCore.text("method").notNull(),status_code:sqliteCore.integer("status_code").notNull(),duration_ms:sqliteCore.integer("duration_ms").notNull(),ip:sqliteCore.text("ip"),request_headers:sqliteCore.text("request_headers"),response_headers:sqliteCore.text("response_headers"),request_body:sqliteCore.text("request_body"),response_body:sqliteCore.text("response_body"),query:sqliteCore.text("query"),user_id:sqliteCore.text("user_id"),project_id:sqliteCore.text("project_id"),partition_key:sqliteCore.text("partition_key").notNull(),timestamp:sqliteCore.text("timestamp").notNull().default(drizzleOrm.sql`(datetime('now'))`),metadata:sqliteCore.text("metadata")},t=>({idx_request_logs_timestamp:sqliteCore.index("idx_request_logs_timestamp").on(t.timestamp),idx_request_logs_path:sqliteCore.index("idx_request_logs_path").on(t.path),idx_request_logs_status_code:sqliteCore.index("idx_request_logs_status_code").on(t.status_code),idx_request_logs_partition_key:sqliteCore.index("idx_request_logs_partition_key").on(t.partition_key)}));});var ps=k(()=>{d();sqliteCore.sqliteTable("request_log_daily",{day:sqliteCore.text("day").notNull(),scope:sqliteCore.text("scope").notNull(),ok:sqliteCore.integer("ok").notNull(),client:sqliteCore.integer("client").notNull(),server:sqliteCore.integer("server").notNull(),p50_ms:sqliteCore.integer("p50_ms"),p95_ms:sqliteCore.integer("p95_ms"),computed_at:sqliteCore.text("computed_at").notNull()},t=>({pk:sqliteCore.primaryKey({columns:[t.day,t.scope]})}));});var fs=k(()=>{d();sqliteCore.sqliteTable("usage_limit_snapshots",{id:sqliteCore.text("id").primaryKey(),provider:sqliteCore.text("provider").notNull(),account_ref:sqliteCore.text("account_ref").notNull().default("default"),limit_window:sqliteCore.text("limit_window").notNull(),bucket_start:sqliteCore.text("bucket_start").notNull(),captured_at:sqliteCore.text("captured_at").notNull(),used_percent:sqliteCore.integer("used_percent").notNull(),remaining_percent:sqliteCore.integer("remaining_percent").notNull(),resets_at:sqliteCore.text("resets_at"),source:sqliteCore.text("source").notNull(),metadata:sqliteCore.text("metadata")},t=>({uniq_usage_limit_snapshots_bucket:sqliteCore.uniqueIndex("uniq_usage_limit_snapshots_bucket").on(t.provider,t.account_ref,t.limit_window,t.bucket_start),idx_usage_limit_snapshots_window_bucket:sqliteCore.index("idx_usage_limit_snapshots_window_bucket").on(t.limit_window,t.bucket_start),idx_usage_limit_snapshots_provider_window_bucket:sqliteCore.index("idx_usage_limit_snapshots_provider_window_bucket").on(t.provider,t.limit_window,t.bucket_start)}));});var hs=k(()=>{d();sqliteCore.sqliteTable("usage_reports",{id:sqliteCore.text("id").primaryKey(),workspace_id:sqliteCore.text("workspace_id").notNull(),month:sqliteCore.text("month").notNull(),generated_at:sqliteCore.text("generated_at").notNull(),source_range:sqliteCore.text("source_range").notNull(),tier:sqliteCore.text("tier").notNull(),total_tokens:sqliteCore.integer("total_tokens").notNull(),total_cost_usd:sqliteCore.real("total_cost_usd").notNull(),payload:sqliteCore.text("payload").notNull(),payload_hash:sqliteCore.text("payload_hash"),signature:sqliteCore.text("signature"),signed_at:sqliteCore.text("signed_at"),issuer:sqliteCore.text("issuer")},t=>({uniq_usage_reports_ws_month:sqliteCore.uniqueIndex("uniq_usage_reports_ws_month").on(t.workspace_id,t.month)}));});var ys=k(()=>{d();sqliteCore.sqliteTable("notifications",{id:sqliteCore.text("id").primaryKey(),workspace_id:sqliteCore.text("workspace_id").notNull(),agent_id:sqliteCore.text("agent_id"),task_id:sqliteCore.text("task_id"),thread_id:sqliteCore.text("thread_id"),source:sqliteCore.text("source").notNull().default("agent"),level:sqliteCore.text("level").notNull().default("info"),title:sqliteCore.text("title").notNull(),body:sqliteCore.text("body"),target_user_id:sqliteCore.text("target_user_id"),created_at:sqliteCore.text("created_at").notNull(),metadata:sqliteCore.text("metadata")},t=>({idx_notifications_ws_created:sqliteCore.index("idx_notifications_ws_created").on(t.workspace_id,drizzleOrm.sql`${t.created_at} DESC`)})),sqliteCore.sqliteTable("notification_reads",{notification_id:sqliteCore.text("notification_id").notNull(),user_id:sqliteCore.text("user_id").notNull(),read_at:sqliteCore.text("read_at").notNull()},t=>({pk:sqliteCore.primaryKey({columns:[t.notification_id,t.user_id]})}));});var Ss=k(()=>{d();sqliteCore.sqliteTable("agent_suggestions",{id:sqliteCore.text("id").primaryKey(),workspace_id:sqliteCore.text("workspace_id").notNull(),agent_id:sqliteCore.text("agent_id").notNull(),task_id:sqliteCore.text("task_id"),type:sqliteCore.text("type").notNull(),status:sqliteCore.text("status").notNull().default("pending"),payload:sqliteCore.text("payload").notNull(),applied_commit_sha:sqliteCore.text("applied_commit_sha"),created_at:sqliteCore.text("created_at").notNull(),updated_at:sqliteCore.text("updated_at").notNull()},t=>({idx_agent_suggestions_ws_agent:sqliteCore.index("idx_agent_suggestions_ws_agent").on(t.workspace_id,t.agent_id),idx_agent_suggestions_ws_created:sqliteCore.index("idx_agent_suggestions_ws_created").on(t.workspace_id,t.created_at)}));});var ws=k(()=>{d();sqliteCore.sqliteTable("ui_instances",{id:sqliteCore.text("id").primaryKey().notNull(),definition_id:sqliteCore.text("definition_id").notNull(),definition_version:sqliteCore.integer("definition_version").notNull(),definition_hash:sqliteCore.text("definition_hash").notNull(),workspace_id:sqliteCore.text("workspace_id").notNull(),thread_id:sqliteCore.text("thread_id").notNull(),app_id:sqliteCore.text("app_id"),anchor_task_id:sqliteCore.text("anchor_task_id"),domain_ref_json:sqliteCore.text("domain_ref_json").notNull(),state_json:sqliteCore.text("state_json").notNull(),revision:sqliteCore.integer("revision").notNull().default(0),status:sqliteCore.text("status").notNull().default("active"),granted_capabilities_json:sqliteCore.text("granted_capabilities_json").notNull().default("[]"),opened_by_json:sqliteCore.text("opened_by_json"),agent_open_request_json:sqliteCore.text("agent_open_request_json"),created_at:sqliteCore.integer("created_at").notNull(),updated_at:sqliteCore.integer("updated_at").notNull()},t=>({idCheck:sqliteCore.check("ui_instances_id_ck",drizzleOrm.sql`length(${t.id}) BETWEEN 5 AND 128 AND ${t.id} GLOB 'uic_*'`),definitionIdCheck:sqliteCore.check("ui_instances_definition_id_ck",drizzleOrm.sql`length(${t.definition_id}) BETWEEN 1 AND 128`),definitionVersionCheck:sqliteCore.check("ui_instances_definition_version_ck",drizzleOrm.sql`${t.definition_version} >= 1`),definitionHashCheck:sqliteCore.check("ui_instances_definition_hash_ck",drizzleOrm.sql`length(${t.definition_hash}) = 64 AND ${t.definition_hash} NOT GLOB '*[^0-9a-f]*'`),workspaceIdCheck:sqliteCore.check("ui_instances_workspace_id_ck",drizzleOrm.sql`length(${t.workspace_id}) BETWEEN 1 AND 256`),threadIdCheck:sqliteCore.check("ui_instances_thread_id_ck",drizzleOrm.sql`length(${t.thread_id}) BETWEEN 1 AND 256`),appIdCheck:sqliteCore.check("ui_instances_app_id_ck",drizzleOrm.sql`${t.app_id} IS NULL OR length(${t.app_id}) BETWEEN 1 AND 128`),domainRefJsonCheck:sqliteCore.check("ui_instances_domain_ref_json_ck",drizzleOrm.sql`json_valid(${t.domain_ref_json}) AND json_type(${t.domain_ref_json}) = 'object'`),stateJsonCheck:sqliteCore.check("ui_instances_state_json_ck",drizzleOrm.sql`json_valid(${t.state_json}) AND json_type(${t.state_json}) = 'object'`),revisionCheck:sqliteCore.check("ui_instances_revision_ck",drizzleOrm.sql`${t.revision} >= 0`),statusCheck:sqliteCore.check("ui_instances_status_ck",drizzleOrm.sql`${t.status} IN ('active', 'completed', 'expired', 'revoked', 'unsupported')`),grantedCapabilitiesJsonCheck:sqliteCore.check("ui_instances_granted_capabilities_json_ck",drizzleOrm.sql`json_valid(${t.granted_capabilities_json}) AND json_type(${t.granted_capabilities_json}) = 'array'`),openedByJsonCheck:sqliteCore.check("ui_instances_opened_by_json_ck",drizzleOrm.sql`${t.opened_by_json} IS NULL OR (json_valid(${t.opened_by_json}) AND json_type(${t.opened_by_json}) = 'object')`),createdAtCheck:sqliteCore.check("ui_instances_created_at_ck",drizzleOrm.sql`${t.created_at} >= 0`),updatedAtCheck:sqliteCore.check("ui_instances_updated_at_ck",drizzleOrm.sql`${t.updated_at} >= ${t.created_at}`),workspaceThreadIdx:sqliteCore.index("ui_instances_workspace_thread_idx").on(t.workspace_id,t.thread_id),workspaceThreadAppUnique:sqliteCore.uniqueIndex("ui_instances_workspace_thread_app_uq").on(t.workspace_id,t.thread_id,t.app_id).where(drizzleOrm.sql`${t.status} = 'active'`)}));});var Rs=k(()=>{d();sqliteCore.sqliteTable("ui_action_receipts",{id:sqliteCore.text("id").primaryKey().notNull(),instance_id:sqliteCore.text("instance_id").notNull(),definition_id:sqliteCore.text("definition_id"),definition_version:sqliteCore.integer("definition_version"),definition_hash:sqliteCore.text("definition_hash"),request_id:sqliteCore.text("request_id").notNull(),action_id:sqliteCore.text("action_id").notNull(),actor_json:sqliteCore.text("actor_json").notNull(),source:sqliteCore.text("source").notNull(),expected_revision:sqliteCore.integer("expected_revision").notNull(),before_revision:sqliteCore.integer("before_revision").notNull(),after_revision:sqliteCore.integer("after_revision"),status:sqliteCore.text("status").notNull(),outcome:sqliteCore.text("outcome"),input_json:sqliteCore.text("input_json").notNull(),result_json:sqliteCore.text("result_json"),error_code:sqliteCore.text("error_code"),requested_at:sqliteCore.integer("requested_at").notNull(),settled_at:sqliteCore.integer("settled_at")},t=>({idCheck:sqliteCore.check("ui_action_receipts_id_ck",drizzleOrm.sql`length(${t.id}) BETWEEN 5 AND 128`),instanceIdCheck:sqliteCore.check("ui_action_receipts_instance_id_ck",drizzleOrm.sql`length(${t.instance_id}) BETWEEN 1 AND 128`),requestIdCheck:sqliteCore.check("ui_action_receipts_request_id_ck",drizzleOrm.sql`length(${t.request_id}) BETWEEN 1 AND 128`),actionIdCheck:sqliteCore.check("ui_action_receipts_action_id_ck",drizzleOrm.sql`length(${t.action_id}) BETWEEN 1 AND 128`),actorJsonCheck:sqliteCore.check("ui_action_receipts_actor_json_ck",drizzleOrm.sql`json_valid(${t.actor_json}) AND json_type(${t.actor_json}) = 'object'`),sourceCheck:sqliteCore.check("ui_action_receipts_source_ck",drizzleOrm.sql`${t.source} IN ('ui_host', 'cli', 'system', 'mcp')`),expectedRevisionCheck:sqliteCore.check("ui_action_receipts_expected_revision_ck",drizzleOrm.sql`${t.expected_revision} >= 0`),beforeRevisionCheck:sqliteCore.check("ui_action_receipts_before_revision_ck",drizzleOrm.sql`${t.before_revision} >= 0`),afterRevisionCheck:sqliteCore.check("ui_action_receipts_after_revision_ck",drizzleOrm.sql`${t.after_revision} IS NULL OR ${t.after_revision} >= 0`),statusCheck:sqliteCore.check("ui_action_receipts_status_ck",drizzleOrm.sql`${t.status} IN ('requested', 'settled')`),outcomeCheck:sqliteCore.check("ui_action_receipts_outcome_ck",drizzleOrm.sql`${t.outcome} IS NULL OR ${t.outcome} IN ('succeeded', 'rejected', 'failed', 'conflicted', 'expired')`),inputJsonCheck:sqliteCore.check("ui_action_receipts_input_json_ck",drizzleOrm.sql`json_valid(${t.input_json}) AND json_type(${t.input_json}) = 'object'`),resultJsonCheck:sqliteCore.check("ui_action_receipts_result_json_ck",drizzleOrm.sql`${t.result_json} IS NULL OR (json_valid(${t.result_json}) AND json_type(${t.result_json}) = 'object')`),requestedAtCheck:sqliteCore.check("ui_action_receipts_requested_at_ck",drizzleOrm.sql`${t.requested_at} >= 0`),settledAtCheck:sqliteCore.check("ui_action_receipts_settled_at_ck",drizzleOrm.sql`${t.settled_at} IS NULL OR ${t.settled_at} >= ${t.requested_at}`),statusTransitionCheck:sqliteCore.check("ui_action_receipts_status_transition_ck",drizzleOrm.sql`(
|
|
23
|
+
(${t.status} = 'requested' AND ${t.after_revision} IS NULL AND ${t.outcome} IS NULL AND ${t.settled_at} IS NULL)
|
|
24
|
+
OR
|
|
25
|
+
(${t.status} = 'settled' AND ${t.after_revision} IS NOT NULL AND ${t.outcome} IS NOT NULL AND ${t.settled_at} IS NOT NULL)
|
|
26
|
+
)`),instanceRequestUnique:sqliteCore.uniqueIndex("ui_action_receipts_instance_request_uq").on(t.instance_id,t.request_id),instanceIdIdx:sqliteCore.index("ui_action_receipts_instance_id_idx").on(t.instance_id),requestedAtIdx:sqliteCore.index("ui_action_receipts_requested_at_idx").on(t.requested_at)}));});var Ts=k(()=>{d();sqliteCore.sqliteTable("ui_instance_repins",{instance_id:sqliteCore.text("instance_id").notNull(),from_version:sqliteCore.integer("from_version").notNull(),from_hash:sqliteCore.text("from_hash").notNull(),to_version:sqliteCore.integer("to_version").notNull(),to_hash:sqliteCore.text("to_hash").notNull(),from_revision:sqliteCore.integer("from_revision").notNull(),to_revision:sqliteCore.integer("to_revision"),status:sqliteCore.text("status").notNull(),code:sqliteCore.text("code"),attempts:sqliteCore.integer("attempts").notNull().default(1),first_at:sqliteCore.integer("first_at").notNull(),last_at:sqliteCore.integer("last_at").notNull()},t=>({pk:sqliteCore.primaryKey({columns:[t.instance_id,t.to_hash],name:"ui_instance_repins_pk"}),instanceIdCheck:sqliteCore.check("ui_instance_repins_instance_id_ck",drizzleOrm.sql`length(${t.instance_id}) BETWEEN 5 AND 128 AND ${t.instance_id} GLOB 'uic_*'`),fromVersionCheck:sqliteCore.check("ui_instance_repins_from_version_ck",drizzleOrm.sql`${t.from_version} >= 1`),toVersionCheck:sqliteCore.check("ui_instance_repins_to_version_ck",drizzleOrm.sql`${t.to_version} >= 1`),fromHashCheck:sqliteCore.check("ui_instance_repins_from_hash_ck",drizzleOrm.sql`length(${t.from_hash}) = 64 AND ${t.from_hash} NOT GLOB '*[^0-9a-f]*'`),toHashCheck:sqliteCore.check("ui_instance_repins_to_hash_ck",drizzleOrm.sql`length(${t.to_hash}) = 64 AND ${t.to_hash} NOT GLOB '*[^0-9a-f]*'`),fromRevisionCheck:sqliteCore.check("ui_instance_repins_from_revision_ck",drizzleOrm.sql`${t.from_revision} >= 0`),toRevisionCheck:sqliteCore.check("ui_instance_repins_to_revision_ck",drizzleOrm.sql`${t.to_revision} IS NULL OR ${t.to_revision} >= 0`),statusCheck:sqliteCore.check("ui_instance_repins_status_ck",drizzleOrm.sql`${t.status} IN ('applied', 'deferred', 'failed')`),attemptsCheck:sqliteCore.check("ui_instance_repins_attempts_ck",drizzleOrm.sql`${t.attempts} >= 1`),datesCheck:sqliteCore.check("ui_instance_repins_dates_ck",drizzleOrm.sql`${t.first_at} >= 0 AND ${t.last_at} >= ${t.first_at}`),resultCheck:sqliteCore.check("ui_instance_repins_result_ck",drizzleOrm.sql`(
|
|
27
|
+
(${t.status} = 'applied' AND ${t.code} IS NULL
|
|
28
|
+
AND ${t.to_revision} = ${t.from_revision} + 1)
|
|
29
|
+
OR
|
|
30
|
+
(${t.status} IN ('deferred', 'failed') AND ${t.code} IS NOT NULL
|
|
31
|
+
AND ${t.to_revision} IS NULL)
|
|
32
|
+
)`)}));});var Is=k(()=>{d();sqliteCore.sqliteTable("ui_definition_archive",{definition_hash:sqliteCore.text("definition_hash").primaryKey().notNull(),definition_json:sqliteCore.text("definition_json").notNull(),created_at:sqliteCore.integer("created_at").notNull()},t=>({definitionHashCheck:sqliteCore.check("ui_definition_archive_definition_hash_ck",drizzleOrm.sql`length(${t.definition_hash}) = 64 AND ${t.definition_hash} NOT GLOB '*[^0-9a-f]*'`),definitionJsonCheck:sqliteCore.check("ui_definition_archive_definition_json_ck",drizzleOrm.sql`json_valid(${t.definition_json}) AND json_type(${t.definition_json}) = 'object'`),createdAtCheck:sqliteCore.check("ui_definition_archive_created_at_ck",drizzleOrm.sql`${t.created_at} >= 0`)}));});var mr,Cs=k(()=>{d();mr=sqliteCore.sqliteTable("projects",{id:sqliteCore.text("id").primaryKey().notNull(),workspace_id:sqliteCore.text("workspace_id").notNull(),name:sqliteCore.text("name").notNull(),outcome:sqliteCore.text("outcome").notNull(),due_date:sqliteCore.text("due_date"),scene:sqliteCore.text("scene").notNull().default("planning"),stages_json:sqliteCore.text("stages_json").notNull(),stage_index:sqliteCore.integer("stage_index").notNull(),created_at:sqliteCore.text("created_at").notNull(),updated_at:sqliteCore.text("updated_at").notNull(),accepted_at:sqliteCore.text("accepted_at"),archived_at:sqliteCore.text("archived_at")},t=>({idCheck:sqliteCore.check("projects_id_ck",drizzleOrm.sql`${t.id} GLOB 'prj_*'`),sceneCheck:sqliteCore.check("projects_scene_ck",drizzleOrm.sql`${t.scene} IN ('planning', 'plan_review', 'running', 'human_wait', 'limit_wait', 'failed_stop', 'analyzing_feedback', 'replanned', 'awaiting_review', 'accepted')`),stagesJsonCheck:sqliteCore.check("projects_stages_json_ck",drizzleOrm.sql`json_valid(${t.stages_json}) AND json_type(${t.stages_json}) = 'array'`),stageIndexCheck:sqliteCore.check("projects_stage_index_ck",drizzleOrm.sql`${t.stage_index} >= 1`)})),sqliteCore.sqliteTable("project_criteria",{id:sqliteCore.text("id").primaryKey().notNull(),project_id:sqliteCore.text("project_id").notNull().references(()=>mr.id,{onDelete:"cascade"}),position:sqliteCore.integer("position").notNull(),statement:sqliteCore.text("statement").notNull(),verify_status:sqliteCore.text("verify_status").notNull().default("pending"),verified_at:sqliteCore.text("verified_at"),evidence_json:sqliteCore.text("evidence_json").notNull().default("[]"),created_at:sqliteCore.text("created_at").notNull(),updated_at:sqliteCore.text("updated_at").notNull()},t=>({idCheck:sqliteCore.check("project_criteria_id_ck",drizzleOrm.sql`${t.id} GLOB 'pjc_*'`),verifyStatusCheck:sqliteCore.check("project_criteria_verify_status_ck",drizzleOrm.sql`${t.verify_status} IN ('pending', 'verifying', 'passed', 'failed')`),evidenceJsonCheck:sqliteCore.check("project_criteria_evidence_json_ck",drizzleOrm.sql`json_valid(${t.evidence_json}) AND json_type(${t.evidence_json}) = 'array'`),projectPositionUnique:sqliteCore.uniqueIndex("project_criteria_project_position_uq").on(t.project_id,t.position)})),sqliteCore.sqliteTable("project_events",{id:sqliteCore.text("id").primaryKey().notNull(),project_id:sqliteCore.text("project_id").notNull().references(()=>mr.id,{onDelete:"restrict"}),seq:sqliteCore.integer("seq").notNull(),actor_type:sqliteCore.text("actor_type").notNull(),actor_id:sqliteCore.text("actor_id"),type:sqliteCore.text("type").notNull(),title:sqliteCore.text("title").notNull(),summary:sqliteCore.text("summary"),payload_json:sqliteCore.text("payload_json").notNull().default("{}"),created_at:sqliteCore.text("created_at").notNull()},t=>({idCheck:sqliteCore.check("project_events_id_ck",drizzleOrm.sql`${t.id} GLOB 'pje_*'`),actorTypeCheck:sqliteCore.check("project_events_actor_type_ck",drizzleOrm.sql`${t.actor_type} IN ('user', 'project_manager', 'system')`),payloadJsonCheck:sqliteCore.check("project_events_payload_json_ck",drizzleOrm.sql`json_valid(${t.payload_json}) AND json_type(${t.payload_json}) = 'object'`),projectSeqUnique:sqliteCore.uniqueIndex("project_events_project_seq_uq").on(t.project_id,t.seq)}));});var wr=k(()=>{d();sqliteCore.sqliteTable("common_codes",{code_group:sqliteCore.text("code_group").notNull(),code:sqliteCore.text("code").notNull(),code_name:sqliteCore.text("code_name"),color:sqliteCore.text("color").notNull().default("gray"),sort_order:sqliteCore.integer("sort_order").notNull(),workspace_id:sqliteCore.text("workspace_id"),is_builtin:sqliteCore.integer("is_builtin").notNull().default(0),is_archived:sqliteCore.integer("is_archived").notNull().default(0),metadata:sqliteCore.text("metadata"),created_at:sqliteCore.text("created_at").notNull(),updated_at:sqliteCore.text("updated_at").notNull()},t=>({pk:sqliteCore.primaryKey({columns:[t.code_group,t.code]}),metadataCheck:sqliteCore.check("common_codes_metadata_ck",drizzleOrm.sql`${t.metadata} IS NULL OR (json_valid(${t.metadata}) AND json_type(${t.metadata}) = 'object')`),builtinCheck:sqliteCore.check("common_codes_builtin_ck",drizzleOrm.sql`${t.is_builtin} IN (0, 1)`),archivedCheck:sqliteCore.check("common_codes_archived_ck",drizzleOrm.sql`${t.is_archived} IN (0, 1)`),idxCommonCodesSelection:sqliteCore.index("idx_common_codes_group_archived_order").on(t.code_group,t.is_archived,t.sort_order)}));});var Ns,Os,vs,Ds,Ps,xs=k(()=>{d();$t();Ns=["thread.snapshot.imported","thread.title.changed","thread.priority.changed","thread.state.changed","thread.highlight.created","thread.highlight.updated","thread.highlight.deleted","thread.highlights.regenerated"],Os=["user","agent","system"],vs=["auto","manual"],Ds=["decision","judgment","issue","result","pivot"],Ps=["queued","running","completed","failed"],sqliteCore.sqliteTable("thread_events",{id:sqliteCore.text("id").primaryKey().notNull(),thread_id:sqliteCore.text("thread_id").notNull().references(()=>ne.id,{onDelete:"cascade"}),seq:sqliteCore.integer("seq").notNull(),type:sqliteCore.text("type").notNull(),actor_type:sqliteCore.text("actor_type").notNull(),payload_json:sqliteCore.text("payload_json").notNull(),created_at:sqliteCore.text("created_at").notNull(),actor_id:sqliteCore.text("actor_id"),task_id:sqliteCore.text("task_id"),highlight_id:sqliteCore.text("highlight_id")},t=>({typeCheck:sqliteCore.check("thread_events_type_ck",drizzleOrm.sql`${t.type} IN ('thread.snapshot.imported', 'thread.title.changed', 'thread.priority.changed', 'thread.state.changed', 'thread.highlight.created', 'thread.highlight.updated', 'thread.highlight.deleted', 'thread.highlights.regenerated')`),actorTypeCheck:sqliteCore.check("thread_events_actor_type_ck",drizzleOrm.sql`${t.actor_type} IN ('user', 'agent', 'system')`),payloadJsonCheck:sqliteCore.check("thread_events_payload_json_ck",drizzleOrm.sql`json_valid(${t.payload_json}) AND json_type(${t.payload_json}) = 'object'`),threadSeqIndex:sqliteCore.index("idx_thread_events_thread_seq").on(t.thread_id,t.seq),threadCreatedIndex:sqliteCore.index("idx_thread_events_thread_created").on(t.thread_id,t.created_at),threadSeqUnique:sqliteCore.uniqueIndex("thread_events_thread_seq_uq").on(t.thread_id,t.seq)})),sqliteCore.sqliteTable("thread_highlight_runs",{id:sqliteCore.text("id").primaryKey().notNull(),thread_id:sqliteCore.text("thread_id").notNull().references(()=>ne.id,{onDelete:"cascade"}),request_id:sqliteCore.text("request_id").notNull(),status:sqliteCore.text("status").notNull(),detector_version:sqliteCore.text("detector_version").notNull(),requested_at:sqliteCore.text("requested_at").notNull(),started_at:sqliteCore.text("started_at"),completed_at:sqliteCore.text("completed_at"),error_code:sqliteCore.text("error_code"),previous_auto_count:sqliteCore.integer("previous_auto_count"),new_auto_count:sqliteCore.integer("new_auto_count")},t=>({statusCheck:sqliteCore.check("thread_highlight_runs_status_ck",drizzleOrm.sql`${t.status} IN ('queued', 'running', 'completed', 'failed')`),countCheck:sqliteCore.check("thread_highlight_runs_counts_ck",drizzleOrm.sql`(${t.previous_auto_count} IS NULL OR ${t.previous_auto_count} >= 0) AND (${t.new_auto_count} IS NULL OR ${t.new_auto_count} >= 0)`),threadRequestUnique:sqliteCore.uniqueIndex("thread_highlight_runs_thread_request_uq").on(t.thread_id,t.request_id),inProgressThreadUnique:sqliteCore.uniqueIndex("thread_highlight_runs_in_progress_thread_uq").on(t.thread_id).where(drizzleOrm.sql`${t.status} IN ('queued', 'running')`),threadStatusRequestedIndex:sqliteCore.index("idx_thread_highlight_runs_thread_status_requested").on(t.thread_id,t.status,t.requested_at)})),sqliteCore.sqliteTable("thread_highlights",{id:sqliteCore.text("id").primaryKey().notNull(),thread_id:sqliteCore.text("thread_id").notNull().references(()=>ne.id,{onDelete:"cascade"}),source:sqliteCore.text("source").notNull(),kind:sqliteCore.text("kind").notNull(),status:sqliteCore.text("status").notNull().default("active"),text:sqliteCore.text("text"),covers_from_task_id:sqliteCore.text("covers_from_task_id").notNull(),covers_to_task_id:sqliteCore.text("covers_to_task_id").notNull(),revision:sqliteCore.integer("revision").notNull().default(0),created_at:sqliteCore.text("created_at").notNull(),updated_at:sqliteCore.text("updated_at").notNull(),agent_id:sqliteCore.text("agent_id"),source_task_id:sqliteCore.text("source_task_id"),detector_version:sqliteCore.text("detector_version"),content_fingerprint:sqliteCore.text("content_fingerprint"),dismissed_at:sqliteCore.text("dismissed_at")},t=>({sourceCheck:sqliteCore.check("thread_highlights_source_ck",drizzleOrm.sql`${t.source} IN ('auto', 'manual')`),kindCheck:sqliteCore.check("thread_highlights_kind_ck",drizzleOrm.sql`${t.kind} IN ('decision', 'judgment', 'issue', 'result', 'pivot')`),statusCheck:sqliteCore.check("thread_highlights_status_ck",drizzleOrm.sql`${t.status} IN ('active', 'dismissed')`),activeTextCheck:sqliteCore.check("thread_highlights_active_text_ck",drizzleOrm.sql`${t.status} = 'dismissed' OR (${t.text} IS NOT NULL AND length(${t.text}) > 0)`),coversCheck:sqliteCore.check("thread_highlights_covers_ck",drizzleOrm.sql`length(${t.covers_from_task_id}) > 0 AND length(${t.covers_to_task_id}) > 0`),autoKeyCheck:sqliteCore.check("thread_highlights_auto_key_ck",drizzleOrm.sql`${t.source} = 'manual' OR (${t.source} = 'auto' AND ${t.source_task_id} IS NOT NULL AND ${t.detector_version} IS NOT NULL AND ${t.content_fingerprint} IS NOT NULL AND length(${t.source_task_id}) > 0 AND length(${t.detector_version}) > 0 AND length(${t.content_fingerprint}) > 0)`),threadStatusCreatedIndex:sqliteCore.index("idx_thread_highlights_thread_status_created").on(t.thread_id,t.status,t.created_at),threadCoversIndex:sqliteCore.index("idx_thread_highlights_thread_covers").on(t.thread_id,t.covers_from_task_id,t.covers_to_task_id),autoIdempotencyUnique:sqliteCore.uniqueIndex("thread_highlights_auto_idempotency_uq").on(t.thread_id,t.source_task_id,t.detector_version,t.content_fingerprint).where(drizzleOrm.sql`${t.source} = 'auto'`)}));});var Ms=k(()=>{d();sqliteCore.sqliteTable("storage_metadata",{source_kind:sqliteCore.text("source_kind").notNull(),source_id:sqliteCore.text("source_id").notNull(),utc_ts:sqliteCore.text("utc_ts"),bytes:sqliteCore.integer("bytes").notNull()},t=>({pk:sqliteCore.primaryKey({columns:[t.source_kind,t.source_id]}),kindTimestampBytesIndex:sqliteCore.index("idx_storage_metadata_kind_ts_bytes").on(t.source_kind,t.utc_ts,t.bytes)})),sqliteCore.sqliteTable("storage_metadata_state",{unit:sqliteCore.text("unit").primaryKey().notNull(),cursor_rowid:sqliteCore.integer("cursor_rowid").notNull().default(0),end_rowid:sqliteCore.integer("end_rowid"),complete:sqliteCore.integer("complete").notNull().default(0),updated_at:sqliteCore.text("updated_at").notNull()});});var Us=k(()=>{d();sqliteCore.sqliteTable("agent_send_history",{workspace_id:sqliteCore.text("workspace_id").notNull(),actor_id:sqliteCore.text("actor_id").notNull(),agent_id:sqliteCore.text("agent_id").notNull(),last_accepted_at:sqliteCore.text("last_accepted_at").notNull()},t=>({pk:sqliteCore.primaryKey({columns:[t.workspace_id,t.actor_id,t.agent_id]}),recentIndex:sqliteCore.index("idx_agent_send_history_recent").on(t.workspace_id,t.actor_id,t.last_accepted_at,t.agent_id)}));});var Ar,Hs=k(()=>{d();$t();gn();sqliteCore.sqliteTable("sidebar_states",{workspace_id:sqliteCore.text("workspace_id").primaryKey().references(()=>ke.id,{onDelete:"cascade"}),revision:sqliteCore.integer("revision").notNull().default(0),rail_collapsed:sqliteCore.integer("rail_collapsed").notNull().default(0),seeded_at:sqliteCore.text("seeded_at").notNull()},t=>({railCollapsedCheck:sqliteCore.check("sidebar_states_rail_collapsed_ck",drizzleOrm.sql`${t.rail_collapsed} IN (0, 1)`)})),Ar=sqliteCore.sqliteTable("sidebar_groups",{id:sqliteCore.text("id").primaryKey(),workspace_id:sqliteCore.text("workspace_id").notNull().references(()=>ke.id,{onDelete:"cascade"}),name:sqliteCore.text("name").notNull(),color:sqliteCore.text("color").notNull(),collapsed:sqliteCore.integer("collapsed").notNull().default(0),position:sqliteCore.integer("position").notNull()},t=>({colorCheck:sqliteCore.check("sidebar_groups_color_ck",drizzleOrm.sql`${t.color} IN ('cyan', 'orange', 'purple', 'blue', 'green', 'lime', 'yellow', 'coral', 'pink', 'indigo', 'sand', 'gray')`),collapsedCheck:sqliteCore.check("sidebar_groups_collapsed_ck",drizzleOrm.sql`${t.collapsed} IN (0, 1)`),idxSidebarGroupsWorkspacePosition:sqliteCore.index("idx_sidebar_groups_workspace_position").on(t.workspace_id,t.position)})),sqliteCore.sqliteTable("sidebar_tabs",{workspace_id:sqliteCore.text("workspace_id").notNull().references(()=>ke.id,{onDelete:"cascade"}),thread_id:sqliteCore.text("thread_id").notNull().references(()=>ne.id,{onDelete:"cascade"}),group_id:sqliteCore.text("group_id").references(()=>Ar.id,{onDelete:"set null"}),position:sqliteCore.integer("position").notNull()},t=>({pk:sqliteCore.primaryKey({columns:[t.workspace_id,t.thread_id]})})),sqliteCore.sqliteTable("sidebar_closed_tabs",{id:sqliteCore.integer("id").primaryKey({autoIncrement:true}),workspace_id:sqliteCore.text("workspace_id").notNull().references(()=>ke.id,{onDelete:"cascade"}),thread_id:sqliteCore.text("thread_id").notNull().references(()=>ne.id,{onDelete:"cascade"}),group_id:sqliteCore.text("group_id").references(()=>Ar.id,{onDelete:"set null"}),position:sqliteCore.integer("position").notNull(),closed_at:sqliteCore.text("closed_at").notNull()},t=>({idxSidebarClosedTabsWorkspaceId:sqliteCore.index("idx_sidebar_closed_tabs_workspace_id").on(t.workspace_id,t.id)})),sqliteCore.sqliteTable("thread_reads",{workspace_id:sqliteCore.text("workspace_id").notNull().references(()=>ke.id,{onDelete:"cascade"}),thread_id:sqliteCore.text("thread_id").notNull().references(()=>ne.id,{onDelete:"cascade"}),read_through_at:sqliteCore.text("read_through_at").notNull()},t=>({pk:sqliteCore.primaryKey({columns:[t.workspace_id,t.thread_id]})}));});var Bs=k(()=>{d();sqliteCore.sqliteTable("schedule_runs",{id:sqliteCore.text("id").primaryKey(),schedule_id:sqliteCore.text("schedule_id").notNull(),workspace_id:sqliteCore.text("workspace_id").notNull(),mode:sqliteCore.text("mode").notNull(),trigger:sqliteCore.text("trigger").notNull(),occurrence_key:sqliteCore.text("occurrence_key"),task_id:sqliteCore.text("task_id"),app_id:sqliteCore.text("app_id"),schedule_name:sqliteCore.text("schedule_name"),builtin_id:sqliteCore.text("builtin_id"),command:sqliteCore.text("command"),high_frequency:sqliteCore.integer("high_frequency").notNull().default(0),status:sqliteCore.text("status").notNull(),error_code:sqliteCore.text("error_code"),exit_code:sqliteCore.integer("exit_code"),signal:sqliteCore.text("signal"),started_at:sqliteCore.text("started_at").notNull(),finished_at:sqliteCore.text("finished_at"),duration_ms:sqliteCore.integer("duration_ms"),pid:sqliteCore.integer("pid"),host_pid:sqliteCore.integer("host_pid"),output_tail:sqliteCore.text("output_tail"),output_bytes:sqliteCore.integer("output_bytes"),output_truncated:sqliteCore.integer("output_truncated").notNull().default(0)},t=>({idx_schedule_runs_workspace_started:sqliteCore.index("idx_schedule_runs_workspace_started").on(t.workspace_id,drizzleOrm.sql`${t.started_at} DESC`),idx_schedule_runs_schedule_started:sqliteCore.index("idx_schedule_runs_schedule_started").on(t.schedule_id,drizzleOrm.sql`${t.started_at} DESC`),idx_schedule_runs_task_id:sqliteCore.index("idx_schedule_runs_task_id").on(t.task_id),idx_schedule_runs_running:sqliteCore.index("idx_schedule_runs_running").on(t.workspace_id,t.started_at).where(drizzleOrm.sql`${t.status} = 'running'`)}));});var Gs=k(()=>{d();sqliteCore.sqliteTable("run_column_backfill",{name:sqliteCore.text("name").primaryKey(),cursor:sqliteCore.integer("cursor"),anchor_id:sqliteCore.text("anchor_id"),completed_at:sqliteCore.text("completed_at")});});var js=k(()=>{d();sqliteCore.sqliteTable("doc_sync_connect_requests",{request_id:sqliteCore.text("request_id").primaryKey().notNull(),account_key:sqliteCore.text("account_key").notNull(),workspace_id:sqliteCore.text("workspace_id").notNull(),app_id:sqliteCore.text("app_id").notNull(),ref:sqliteCore.text("ref").notNull(),sent_hash:sqliteCore.text("sent_hash").notNull(),created_at:sqliteCore.integer("created_at").notNull()},t=>({requestIdCheck:sqliteCore.check("doc_sync_connect_requests_request_id_ck",drizzleOrm.sql`length(${t.request_id}) = 36`),accountKeyCheck:sqliteCore.check("doc_sync_connect_requests_account_key_ck",drizzleOrm.sql`length(${t.account_key}) = 64 AND ${t.account_key} NOT GLOB '*[^0-9a-f]*'`),workspaceIdCheck:sqliteCore.check("doc_sync_connect_requests_workspace_id_ck",drizzleOrm.sql`length(${t.workspace_id}) BETWEEN 1 AND 256`),appIdCheck:sqliteCore.check("doc_sync_connect_requests_app_id_ck",drizzleOrm.sql`length(${t.app_id}) BETWEEN 1 AND 128`),refCheck:sqliteCore.check("doc_sync_connect_requests_ref_ck",drizzleOrm.sql`length(${t.ref}) BETWEEN 1 AND 256`),sentHashCheck:sqliteCore.check("doc_sync_connect_requests_sent_hash_ck",drizzleOrm.sql`length(${t.sent_hash}) = 71 AND substr(${t.sent_hash}, 1, 7) = 'sha256:' AND substr(${t.sent_hash}, 8) NOT GLOB '*[^0-9a-f]*'`),createdAtCheck:sqliteCore.check("doc_sync_connect_requests_created_at_ck",drizzleOrm.sql`${t.created_at} >= 0`),connectUnique:sqliteCore.uniqueIndex("doc_sync_connect_requests_connect_uq").on(t.account_key,t.workspace_id,t.app_id,t.ref)}));});var Ws=k(()=>{d();sqliteCore.sqliteTable("doc_sync_links",{doc_id:sqliteCore.text("doc_id").primaryKey().notNull(),account_key:sqliteCore.text("account_key").notNull(),workspace_id:sqliteCore.text("workspace_id").notNull(),app_id:sqliteCore.text("app_id").notNull(),root_segments:sqliteCore.text("root_segments").notNull(),ref:sqliteCore.text("ref").notNull(),cloud_ref:sqliteCore.text("cloud_ref").notNull(),connection_kind:sqliteCore.text("connection_kind").$type().notNull().default("document"),app_grant_id:sqliteCore.text("app_grant_id"),app_grant_generation:sqliteCore.integer("app_grant_generation"),app_scope_version:sqliteCore.text("app_scope_version"),origin:sqliteCore.text("origin").notNull().default("own"),sync_state:sqliteCore.text("sync_state").notNull().default("ok"),end_reason:sqliteCore.text("end_reason"),file_state:sqliteCore.text("file_state").notNull().default("present"),synced_revision:sqliteCore.integer("synced_revision").notNull(),synced_hash:sqliteCore.text("synced_hash").notNull(),synced_at:sqliteCore.integer("synced_at").notNull(),file_dev_ino:sqliteCore.text("file_dev_ino"),conflict_revision:sqliteCore.integer("conflict_revision"),conflict_hash:sqliteCore.text("conflict_hash"),conflict_at:sqliteCore.integer("conflict_at"),remote_revision:sqliteCore.integer("remote_revision"),remote_checked_at:sqliteCore.integer("remote_checked_at"),published_revision:sqliteCore.integer("published_revision"),bundle_sha256:sqliteCore.text("bundle_sha256"),missing_since:sqliteCore.integer("missing_since"),connected_at:sqliteCore.integer("connected_at").notNull(),created_at:sqliteCore.integer("created_at").notNull(),updated_at:sqliteCore.integer("updated_at").notNull()},t=>({docIdCheck:sqliteCore.check("doc_sync_links_doc_id_ck",drizzleOrm.sql`length(${t.doc_id}) BETWEEN 1 AND 128`),accountKeyCheck:sqliteCore.check("doc_sync_links_account_key_ck",drizzleOrm.sql`length(${t.account_key}) = 64 AND ${t.account_key} NOT GLOB '*[^0-9a-f]*'`),workspaceIdCheck:sqliteCore.check("doc_sync_links_workspace_id_ck",drizzleOrm.sql`length(${t.workspace_id}) BETWEEN 1 AND 256`),appIdCheck:sqliteCore.check("doc_sync_links_app_id_ck",drizzleOrm.sql`length(${t.app_id}) BETWEEN 1 AND 128`),rootSegmentsCheck:sqliteCore.check("doc_sync_links_root_segments_ck",drizzleOrm.sql`json_valid(${t.root_segments}) AND json_type(${t.root_segments}) = 'array'`),refCheck:sqliteCore.check("doc_sync_links_ref_ck",drizzleOrm.sql`length(${t.ref}) BETWEEN 1 AND 256`),cloudRefCheck:sqliteCore.check("doc_sync_links_cloud_ref_ck",drizzleOrm.sql`length(${t.cloud_ref}) BETWEEN 1 AND 256`),originCheck:sqliteCore.check("doc_sync_links_origin_ck",drizzleOrm.sql`${t.origin} IN ('own', 'received')`),syncStateCheck:sqliteCore.check("doc_sync_links_sync_state_ck",drizzleOrm.sql`${t.sync_state} IN ('ok', 'conflict', 'ended')`),endReasonCheck:sqliteCore.check("doc_sync_links_end_reason_ck",drizzleOrm.sql`${t.end_reason} IS NULL OR ${t.end_reason} IN ('disconnected', 'cloud_deleted')`),endedMatchesReasonCheck:sqliteCore.check("doc_sync_links_ended_reason_ck",drizzleOrm.sql`(${t.sync_state} = 'ended') = (${t.end_reason} IS NOT NULL)`),fileStateCheck:sqliteCore.check("doc_sync_links_file_state_ck",drizzleOrm.sql`${t.file_state} IN ('present', 'missing', 'root_unavailable')`),syncedRevisionCheck:sqliteCore.check("doc_sync_links_synced_revision_ck",drizzleOrm.sql`${t.synced_revision} >= 0`),syncedHashCheck:sqliteCore.check("doc_sync_links_synced_hash_ck",drizzleOrm.sql`length(${t.synced_hash}) = 71 AND substr(${t.synced_hash}, 1, 7) = 'sha256:' AND substr(${t.synced_hash}, 8) NOT GLOB '*[^0-9a-f]*'`),connectedAtCheck:sqliteCore.check("doc_sync_links_connected_at_ck",drizzleOrm.sql`${t.connected_at} >= 0`),createdAtCheck:sqliteCore.check("doc_sync_links_created_at_ck",drizzleOrm.sql`${t.created_at} >= 0`),updatedAtCheck:sqliteCore.check("doc_sync_links_updated_at_ck",drizzleOrm.sql`${t.updated_at} >= ${t.created_at}`),liveRefUnique:sqliteCore.uniqueIndex("doc_sync_links_live_ref_uq").on(t.workspace_id,t.app_id,t.ref).where(drizzleOrm.sql`${t.sync_state} <> 'ended'`),accountStateIdx:sqliteCore.index("doc_sync_links_account_state_idx").on(t.account_key,t.sync_state),workspaceAppIdx:sqliteCore.index("doc_sync_links_workspace_app_idx").on(t.workspace_id,t.app_id),connectionKindAccountIdx:sqliteCore.index("doc_sync_links_connection_account_idx").on(t.account_key,t.connection_kind,t.app_id)}));});var Ks=k(()=>{d();sqliteCore.sqliteTable("doc_create_dispatches",{dispatch_id:sqliteCore.text("dispatch_id").primaryKey().notNull(),request_id:sqliteCore.text("request_id").notNull(),account_key:sqliteCore.text("account_key").notNull(),source:sqliteCore.text("source").$type().notNull(),dispatched_at:sqliteCore.integer("dispatched_at").notNull()},t=>({dispatchIdCheck:sqliteCore.check("doc_create_dispatches_id_ck",drizzleOrm.sql`length(${t.dispatch_id}) BETWEEN 1 AND 128`),requestIdCheck:sqliteCore.check("doc_create_dispatches_request_id_ck",drizzleOrm.sql`length(${t.request_id}) BETWEEN 1 AND 128`),accountKeyCheck:sqliteCore.check("doc_create_dispatches_account_key_ck",drizzleOrm.sql`length(${t.account_key}) = 64 AND ${t.account_key} NOT GLOB '*[^0-9a-f]*'`),sourceCheck:sqliteCore.check("doc_create_dispatches_source_ck",drizzleOrm.sql`${t.source} IN ('human', 'app_create', 'app_reattach')`),timestampCheck:sqliteCore.check("doc_create_dispatches_time_ck",drizzleOrm.sql`${t.dispatched_at} >= 0`),accountDispatchedIndex:sqliteCore.index("doc_create_dispatches_account_time_idx").on(t.account_key,t.dispatched_at)}));});var yt,Yc,Vs=k(()=>{d();yt=sqliteCore.sqliteTable("app_sync_bindings",{binding_id:sqliteCore.text("binding_id").primaryKey().notNull(),account_key:sqliteCore.text("account_key").notNull(),workspace_id:sqliteCore.text("workspace_id").notNull(),app_id:sqliteCore.text("app_id").notNull(),root_segments:sqliteCore.text("root_segments").notNull(),grant_id:sqliteCore.text("grant_id"),grant_generation:sqliteCore.integer("grant_generation"),scope_version:sqliteCore.text("scope_version"),status:sqliteCore.text("status").notNull().default("local_only"),created_at:sqliteCore.integer("created_at").notNull(),updated_at:sqliteCore.integer("updated_at").notNull()},t=>({bindingIdCheck:sqliteCore.check("app_sync_bindings_binding_id_ck",drizzleOrm.sql`length(${t.binding_id}) BETWEEN 1 AND 128`),accountKeyCheck:sqliteCore.check("app_sync_bindings_account_key_ck",drizzleOrm.sql`length(${t.account_key}) = 64 AND ${t.account_key} NOT GLOB '*[^0-9a-f]*'`),workspaceIdCheck:sqliteCore.check("app_sync_bindings_workspace_id_ck",drizzleOrm.sql`length(${t.workspace_id}) BETWEEN 1 AND 256`),appIdCheck:sqliteCore.check("app_sync_bindings_app_id_ck",drizzleOrm.sql`${t.app_id} = 'workout-log'`),rootSegmentsCheck:sqliteCore.check("app_sync_bindings_root_segments_ck",drizzleOrm.sql`json_valid(${t.root_segments}) AND json_type(${t.root_segments}) = 'array'`),grantGenerationCheck:sqliteCore.check("app_sync_bindings_generation_ck",drizzleOrm.sql`${t.grant_generation} IS NULL OR ${t.grant_generation} >= 1`),statusCheck:sqliteCore.check("app_sync_bindings_status_ck",drizzleOrm.sql`${t.status} IN ('local_only', 'consent_required', 'checking', 'syncing', 'synced', 'partial', 'offline', 'revoked', 'unavailable', 'stopping')`),timestampsCheck:sqliteCore.check("app_sync_bindings_timestamps_ck",drizzleOrm.sql`${t.updated_at} >= ${t.created_at}`),ownerAppUnique:sqliteCore.uniqueIndex("app_sync_bindings_owner_app_uq").on(t.account_key,t.app_id)})),sqliteCore.sqliteTable("app_sync_creation_jobs",{job_id:sqliteCore.text("job_id").primaryKey().notNull(),binding_id:sqliteCore.text("binding_id").notNull(),account_key:sqliteCore.text("account_key").notNull(),grant_id:sqliteCore.text("grant_id").notNull(),grant_generation:sqliteCore.integer("grant_generation").notNull(),ref:sqliteCore.text("ref").notNull(),request_id:sqliteCore.text("request_id").notNull(),fingerprint:sqliteCore.text("fingerprint").notNull(),operation_kind:sqliteCore.text("operation_kind").$type().notNull().default("create"),document_id:sqliteCore.text("document_id"),status:sqliteCore.text("status").notNull().default("waiting"),attempts:sqliteCore.integer("attempts").notNull().default(0),next_attempt_at:sqliteCore.integer("next_attempt_at").notNull().default(0),created_at:sqliteCore.integer("created_at").notNull(),updated_at:sqliteCore.integer("updated_at").notNull()},t=>({jobIdCheck:sqliteCore.check("app_sync_creation_jobs_job_id_ck",drizzleOrm.sql`length(${t.job_id}) BETWEEN 1 AND 128`),accountKeyCheck:sqliteCore.check("app_sync_creation_jobs_account_key_ck",drizzleOrm.sql`length(${t.account_key}) = 64 AND ${t.account_key} NOT GLOB '*[^0-9a-f]*'`),generationCheck:sqliteCore.check("app_sync_creation_jobs_generation_ck",drizzleOrm.sql`${t.grant_generation} >= 1`),refCheck:sqliteCore.check("app_sync_creation_jobs_ref_ck",drizzleOrm.sql`length(${t.ref}) BETWEEN 1 AND 256`),documentIdCheck:sqliteCore.check("app_sync_creation_jobs_document_id_ck",drizzleOrm.sql`${t.document_id} IS NULL OR length(${t.document_id}) BETWEEN 1 AND 128`),operationKindCheck:sqliteCore.check("app_sync_creation_jobs_operation_kind_ck",drizzleOrm.sql`${t.operation_kind} IN ('create', 'reattach')`),reattachDocumentCheck:sqliteCore.check("app_sync_creation_jobs_reattach_document_ck",drizzleOrm.sql`${t.operation_kind} != 'reattach' OR ${t.document_id} IS NOT NULL`),fingerprintCheck:sqliteCore.check("app_sync_creation_jobs_fingerprint_ck",drizzleOrm.sql`length(${t.fingerprint}) = 71 AND substr(${t.fingerprint}, 1, 7) = 'sha256:' AND substr(${t.fingerprint}, 8) NOT GLOB '*[^0-9a-f]*'`),statusCheck:sqliteCore.check("app_sync_creation_jobs_status_ck",drizzleOrm.sql`${t.status} IN ('waiting', 'processing', 'completed', 'failed', 'conflict', 'blocked', 'invalidated', 'deleted')`),attemptsCheck:sqliteCore.check("app_sync_creation_jobs_attempts_ck",drizzleOrm.sql`${t.attempts} >= 0`),timestampsCheck:sqliteCore.check("app_sync_creation_jobs_timestamps_ck",drizzleOrm.sql`${t.updated_at} >= ${t.created_at}`),bindingFk:sqliteCore.foreignKey({columns:[t.binding_id],foreignColumns:[yt.binding_id]}).onDelete("cascade"),requestIdUnique:sqliteCore.uniqueIndex("app_sync_creation_jobs_request_id_uq").on(t.request_id),activeFingerprintUnique:sqliteCore.uniqueIndex("app_sync_creation_jobs_active_identity_uq").on(t.binding_id,t.grant_id,t.grant_generation,t.ref,t.fingerprint,t.operation_kind).where(drizzleOrm.sql`${t.status} IN ('waiting', 'processing')`),runnableIndex:sqliteCore.index("app_sync_creation_jobs_runnable_idx").on(t.binding_id,t.status,t.next_attempt_at),accountIndex:sqliteCore.index("app_sync_creation_jobs_account_idx").on(t.account_key,t.status)})),sqliteCore.sqliteTable("app_sync_results",{binding_id:sqliteCore.text("binding_id").notNull(),account_key:sqliteCore.text("account_key").notNull(),ref:sqliteCore.text("ref").notNull(),grant_id:sqliteCore.text("grant_id").notNull(),grant_generation:sqliteCore.integer("grant_generation").notNull(),source_fingerprint:sqliteCore.text("source_fingerprint"),synced_fingerprint:sqliteCore.text("synced_fingerprint"),document_id:sqliteCore.text("document_id"),status:sqliteCore.text("status").notNull(),error_code:sqliteCore.text("error_code"),next_attempt_at:sqliteCore.integer("next_attempt_at").notNull().default(0),attempts:sqliteCore.integer("attempts").notNull().default(0),updated_at:sqliteCore.integer("updated_at").notNull()},t=>({resultAccountCheck:sqliteCore.check("app_sync_results_account_key_ck",drizzleOrm.sql`length(${t.account_key}) = 64 AND ${t.account_key} NOT GLOB '*[^0-9a-f]*'`),resultRefCheck:sqliteCore.check("app_sync_results_ref_ck",drizzleOrm.sql`length(${t.ref}) BETWEEN 1 AND 256`),resultGenerationCheck:sqliteCore.check("app_sync_results_generation_ck",drizzleOrm.sql`${t.grant_generation} >= 1`),resultStatusCheck:sqliteCore.check("app_sync_results_status_ck",drizzleOrm.sql`${t.status} IN ('waiting', 'processing', 'synced', 'failed', 'conflict', 'blocked', 'excluded', 'deleted')`),resultAttemptsCheck:sqliteCore.check("app_sync_results_attempts_ck",drizzleOrm.sql`${t.attempts} >= 0`),resultBindingFk:sqliteCore.foreignKey({columns:[t.binding_id],foreignColumns:[yt.binding_id]}).onDelete("cascade"),resultIdentityUnique:sqliteCore.uniqueIndex("app_sync_results_binding_ref_uq").on(t.binding_id,t.ref),resultAccountIndex:sqliteCore.index("app_sync_results_account_status_idx").on(t.account_key,t.status)})),sqliteCore.sqliteTable("app_sync_control_requests",{request_id:sqliteCore.text("request_id").primaryKey().notNull(),binding_id:sqliteCore.text("binding_id").notNull(),account_key:sqliteCore.text("account_key").notNull(),app_id:sqliteCore.text("app_id").notNull(),workspace_id:sqliteCore.text("workspace_id").notNull(),root_fingerprint:sqliteCore.text("root_fingerprint").notNull(),kind:sqliteCore.text("kind").notNull(),state:sqliteCore.text("state").notNull().default("pending"),grant_id:sqliteCore.text("grant_id"),generation:sqliteCore.integer("generation"),created_at:sqliteCore.integer("created_at").notNull(),updated_at:sqliteCore.integer("updated_at").notNull(),resolved_at:sqliteCore.integer("resolved_at"),resolution:sqliteCore.text("resolution"),resolution_id:sqliteCore.text("resolution_id")},t=>({requestIdCheck:sqliteCore.check("app_sync_control_requests_request_id_ck",drizzleOrm.sql`length(${t.request_id}) BETWEEN 1 AND 128`),requestAccountCheck:sqliteCore.check("app_sync_control_requests_account_key_ck",drizzleOrm.sql`length(${t.account_key}) = 64 AND ${t.account_key} NOT GLOB '*[^0-9a-f]*'`),requestAppCheck:sqliteCore.check("app_sync_control_requests_app_id_ck",drizzleOrm.sql`${t.app_id} = 'workout-log'`),requestWorkspaceCheck:sqliteCore.check("app_sync_control_requests_workspace_id_ck",drizzleOrm.sql`length(${t.workspace_id}) BETWEEN 1 AND 256`),rootFingerprintCheck:sqliteCore.check("app_sync_control_requests_root_fingerprint_ck",drizzleOrm.sql`length(${t.root_fingerprint}) = 64 AND ${t.root_fingerprint} NOT GLOB '*[^0-9a-f]*'`),requestKindCheck:sqliteCore.check("app_sync_control_requests_kind_ck",drizzleOrm.sql`${t.kind} IN ('connect', 'revoke')`),requestStateCheck:sqliteCore.check("app_sync_control_requests_state_ck",drizzleOrm.sql`${t.state} IN ('pending', 'unknown', 'confirmed', 'failed')`),revokeGrantCheck:sqliteCore.check("app_sync_control_requests_revoke_grant_ck",drizzleOrm.sql`${t.kind} != 'revoke' OR (${t.grant_id} IS NOT NULL AND ${t.generation} >= 1)`),requestResolutionCheck:sqliteCore.check("app_sync_control_requests_resolution_ck",drizzleOrm.sql`(${t.state} IN ('pending', 'unknown') AND ${t.resolved_at} IS NULL AND ${t.resolution} IS NULL AND ${t.resolution_id} IS NULL) OR (${t.state} IN ('confirmed', 'failed') AND ${t.resolved_at} IS NOT NULL AND ${t.resolution} IN ('remote', 'human') AND length(${t.resolution_id}) BETWEEN 1 AND 128)`),generationCheck:sqliteCore.check("app_sync_control_requests_generation_ck",drizzleOrm.sql`${t.generation} IS NULL OR ${t.generation} >= 1`),timestampsCheck:sqliteCore.check("app_sync_control_requests_timestamps_ck",drizzleOrm.sql`${t.updated_at} >= ${t.created_at}`),bindingFk:sqliteCore.foreignKey({columns:[t.binding_id],foreignColumns:[yt.binding_id]}).onDelete("cascade"),unresolvedPerBinding:sqliteCore.uniqueIndex("app_sync_control_requests_one_pending_uq").on(t.binding_id).where(drizzleOrm.sql`${t.state} IN ('pending', 'unknown')`),accountLookup:sqliteCore.index("app_sync_control_requests_account_idx").on(t.account_key,t.app_id,t.state)})),sqliteCore.sqliteTable("app_sync_deleted_refs",{account_key:sqliteCore.text("account_key").notNull(),app_id:sqliteCore.text("app_id").notNull(),ref_sha256:sqliteCore.text("ref_sha256").notNull(),created_at:sqliteCore.integer("created_at").notNull()},t=>({deletedAccountCheck:sqliteCore.check("app_sync_deleted_refs_account_key_ck",drizzleOrm.sql`length(${t.account_key}) = 64 AND ${t.account_key} NOT GLOB '*[^0-9a-f]*'`),deletedAppCheck:sqliteCore.check("app_sync_deleted_refs_app_id_ck",drizzleOrm.sql`${t.app_id} = 'workout-log'`),deletedHashCheck:sqliteCore.check("app_sync_deleted_refs_hash_ck",drizzleOrm.sql`length(${t.ref_sha256}) = 64 AND ${t.ref_sha256} NOT GLOB '*[^0-9a-f]*'`),deletedIdentityUnique:sqliteCore.uniqueIndex("app_sync_deleted_refs_identity_uq").on(t.account_key,t.app_id,t.ref_sha256)})),sqliteCore.sqliteTable("app_sync_discovery_checkpoints",{binding_id:sqliteCore.text("binding_id").primaryKey().notNull(),account_key:sqliteCore.text("account_key").notNull(),workspace_id:sqliteCore.text("workspace_id").notNull(),root_fingerprint:sqliteCore.text("root_fingerprint").notNull(),grant_id:sqliteCore.text("grant_id").notNull(),grant_generation:sqliteCore.integer("grant_generation").notNull(),scope_version:sqliteCore.text("scope_version").notNull(),last_cycle_started_at:sqliteCore.integer("last_cycle_started_at"),cycle_started_at:sqliteCore.integer("cycle_started_at"),docs_cursor:sqliteCore.text("docs_cursor"),docs_complete:sqliteCore.integer("docs_complete").notNull().default(0),deleted_cursor:sqliteCore.text("deleted_cursor"),deleted_complete:sqliteCore.integer("deleted_complete").notNull().default(0),updated_at:sqliteCore.integer("updated_at").notNull()},t=>({checkpointAccountCheck:sqliteCore.check("app_sync_discovery_checkpoints_account_key_ck",drizzleOrm.sql`length(${t.account_key}) = 64 AND ${t.account_key} NOT GLOB '*[^0-9a-f]*'`),checkpointRootCheck:sqliteCore.check("app_sync_discovery_checkpoints_root_fingerprint_ck",drizzleOrm.sql`length(${t.root_fingerprint}) = 64 AND ${t.root_fingerprint} NOT GLOB '*[^0-9a-f]*'`),checkpointGenerationCheck:sqliteCore.check("app_sync_discovery_checkpoints_generation_ck",drizzleOrm.sql`${t.grant_generation} >= 1`),checkpointScopeCheck:sqliteCore.check("app_sync_discovery_checkpoints_scope_ck",drizzleOrm.sql`${t.scope_version} = 'workout-log.records.v1'`),checkpointDocsCompleteCheck:sqliteCore.check("app_sync_discovery_checkpoints_docs_complete_ck",drizzleOrm.sql`${t.docs_complete} IN (0, 1)`),checkpointDeletedCompleteCheck:sqliteCore.check("app_sync_discovery_checkpoints_deleted_complete_ck",drizzleOrm.sql`${t.deleted_complete} IN (0, 1)`),checkpointTimeCheck:sqliteCore.check("app_sync_discovery_checkpoints_time_ck",drizzleOrm.sql`${t.updated_at} >= 0 AND (${t.last_cycle_started_at} IS NULL OR ${t.last_cycle_started_at} >= 0) AND (${t.cycle_started_at} IS NULL OR ${t.cycle_started_at} >= 0)`),checkpointBindingFk:sqliteCore.foreignKey({columns:[t.binding_id],foreignColumns:[yt.binding_id]}).onDelete("cascade"),checkpointAccountIndex:sqliteCore.index("app_sync_discovery_checkpoints_account_idx").on(t.account_key,t.grant_id,t.grant_generation)})),sqliteCore.sqliteTable("app_sync_pending_discoveries",{binding_id:sqliteCore.text("binding_id").notNull(),account_key:sqliteCore.text("account_key").notNull(),grant_id:sqliteCore.text("grant_id").notNull(),grant_generation:sqliteCore.integer("grant_generation").notNull(),ref:sqliteCore.text("ref").notNull(),doc_id:sqliteCore.text("doc_id").notNull(),listed_revision:sqliteCore.integer("listed_revision").notNull(),listed_fingerprint:sqliteCore.text("listed_fingerprint").notNull(),app_grant_generation:sqliteCore.integer("app_grant_generation").notNull(),needs_reattach:sqliteCore.integer("needs_reattach").notNull().default(0),needs_reconcile:sqliteCore.integer("needs_reconcile").notNull().default(0),status:sqliteCore.text("status").notNull().default("waiting"),error_code:sqliteCore.text("error_code"),attempts:sqliteCore.integer("attempts").notNull().default(0),updated_at:sqliteCore.integer("updated_at").notNull()},t=>({pendingAccountCheck:sqliteCore.check("app_sync_pending_discoveries_account_key_ck",drizzleOrm.sql`length(${t.account_key}) = 64 AND ${t.account_key} NOT GLOB '*[^0-9a-f]*'`),pendingRefCheck:sqliteCore.check("app_sync_pending_discoveries_ref_ck",drizzleOrm.sql`length(${t.ref}) BETWEEN 1 AND 256`),pendingDocCheck:sqliteCore.check("app_sync_pending_discoveries_doc_id_ck",drizzleOrm.sql`length(${t.doc_id}) BETWEEN 1 AND 128`),pendingRevisionCheck:sqliteCore.check("app_sync_pending_discoveries_revision_ck",drizzleOrm.sql`${t.listed_revision} >= 0`),pendingFingerprintCheck:sqliteCore.check("app_sync_pending_discoveries_fingerprint_ck",drizzleOrm.sql`length(${t.listed_fingerprint}) = 71 AND substr(${t.listed_fingerprint}, 1, 7) = 'sha256:' AND substr(${t.listed_fingerprint}, 8) NOT GLOB '*[^0-9a-f]*'`),pendingGenerationCheck:sqliteCore.check("app_sync_pending_discoveries_generation_ck",drizzleOrm.sql`${t.grant_generation} >= 1 AND ${t.app_grant_generation} >= 1`),pendingFlagsCheck:sqliteCore.check("app_sync_pending_discoveries_flags_ck",drizzleOrm.sql`${t.needs_reattach} IN (0, 1) AND ${t.needs_reconcile} IN (0, 1)`),pendingStatusCheck:sqliteCore.check("app_sync_pending_discoveries_status_ck",drizzleOrm.sql`${t.status} IN ('waiting', 'processing', 'failed', 'invalidated')`),pendingAttemptsCheck:sqliteCore.check("app_sync_pending_discoveries_attempts_ck",drizzleOrm.sql`${t.attempts} >= 0 AND ${t.updated_at} >= 0`),pendingBindingFk:sqliteCore.foreignKey({columns:[t.binding_id],foreignColumns:[yt.binding_id]}).onDelete("cascade"),pendingIdentityUnique:sqliteCore.uniqueIndex("app_sync_pending_discoveries_identity_uq").on(t.binding_id,t.grant_id,t.grant_generation,t.ref),pendingRunnableIdx:sqliteCore.index("app_sync_pending_discoveries_runnable_idx").on(t.binding_id,t.grant_id,t.grant_generation,t.status,t.ref)})),Yc=sqliteCore.sqliteTable("app_sync_conflicts",{conflict_id:sqliteCore.text("conflict_id").primaryKey().notNull(),binding_id:sqliteCore.text("binding_id").notNull(),account_key:sqliteCore.text("account_key").notNull(),workspace_id:sqliteCore.text("workspace_id").notNull(),root_fingerprint:sqliteCore.text("root_fingerprint").notNull(),grant_id:sqliteCore.text("grant_id").notNull(),grant_generation:sqliteCore.integer("grant_generation").notNull(),scope_version:sqliteCore.text("scope_version").notNull(),ref:sqliteCore.text("ref").notNull(),doc_id:sqliteCore.text("doc_id").notNull(),local_version:sqliteCore.text("local_version").notNull(),local_fingerprint:sqliteCore.text("local_fingerprint").notNull(),baseline_revision:sqliteCore.integer("baseline_revision"),baseline_fingerprint:sqliteCore.text("baseline_fingerprint"),remote_revision:sqliteCore.integer("remote_revision").notNull(),remote_fingerprint:sqliteCore.text("remote_fingerprint").notNull(),needs_reattach:sqliteCore.integer("needs_reattach").notNull().default(0),vault_handle:sqliteCore.text("vault_handle"),preservation_status:sqliteCore.text("preservation_status").notNull().default("pending"),state:sqliteCore.text("state").notNull().default("open"),superseded_by:sqliteCore.text("superseded_by"),resolution_request_id:sqliteCore.text("resolution_request_id"),resolution_choice:sqliteCore.text("resolution_choice"),cleanup_pending:sqliteCore.integer("cleanup_pending").notNull().default(0),created_at:sqliteCore.integer("created_at").notNull(),updated_at:sqliteCore.integer("updated_at").notNull()},t=>({conflictIdCheck:sqliteCore.check("app_sync_conflicts_id_ck",drizzleOrm.sql`length(${t.conflict_id}) BETWEEN 1 AND 128`),conflictAccountCheck:sqliteCore.check("app_sync_conflicts_account_key_ck",drizzleOrm.sql`length(${t.account_key}) = 64 AND ${t.account_key} NOT GLOB '*[^0-9a-f]*'`),conflictRootCheck:sqliteCore.check("app_sync_conflicts_root_fingerprint_ck",drizzleOrm.sql`length(${t.root_fingerprint}) = 64 AND ${t.root_fingerprint} NOT GLOB '*[^0-9a-f]*'`),conflictGenerationCheck:sqliteCore.check("app_sync_conflicts_generation_ck",drizzleOrm.sql`${t.grant_generation} >= 1`),conflictScopeCheck:sqliteCore.check("app_sync_conflicts_scope_ck",drizzleOrm.sql`${t.scope_version} = 'workout-log.records.v1'`),conflictRefCheck:sqliteCore.check("app_sync_conflicts_ref_ck",drizzleOrm.sql`length(${t.ref}) BETWEEN 1 AND 256`),conflictDocCheck:sqliteCore.check("app_sync_conflicts_doc_id_ck",drizzleOrm.sql`length(${t.doc_id}) BETWEEN 1 AND 128`),conflictLocalVersionCheck:sqliteCore.check("app_sync_conflicts_local_version_ck",drizzleOrm.sql`length(${t.local_version}) BETWEEN 1 AND 256 AND instr(${t.local_version}, '/') = 0 AND instr(${t.local_version}, char(92)) = 0`),conflictLocalFingerprintCheck:sqliteCore.check("app_sync_conflicts_local_fingerprint_ck",drizzleOrm.sql`length(${t.local_fingerprint}) = 71 AND substr(${t.local_fingerprint}, 1, 7) = 'sha256:' AND substr(${t.local_fingerprint}, 8) NOT GLOB '*[^0-9a-f]*'`),conflictBaselineCheck:sqliteCore.check("app_sync_conflicts_baseline_ck",drizzleOrm.sql`(${t.baseline_revision} IS NULL) = (${t.baseline_fingerprint} IS NULL) AND (${t.baseline_revision} IS NULL OR (${t.baseline_revision} >= 0 AND length(${t.baseline_fingerprint}) = 71 AND substr(${t.baseline_fingerprint}, 1, 7) = 'sha256:' AND substr(${t.baseline_fingerprint}, 8) NOT GLOB '*[^0-9a-f]*'))`),conflictRemoteCheck:sqliteCore.check("app_sync_conflicts_remote_ck",drizzleOrm.sql`${t.remote_revision} >= 0 AND length(${t.remote_fingerprint}) = 71 AND substr(${t.remote_fingerprint}, 1, 7) = 'sha256:' AND substr(${t.remote_fingerprint}, 8) NOT GLOB '*[^0-9a-f]*'`),conflictFlagsCheck:sqliteCore.check("app_sync_conflicts_flags_ck",drizzleOrm.sql`${t.needs_reattach} IN (0, 1) AND ${t.cleanup_pending} IN (0, 1)`),conflictHandleCheck:sqliteCore.check("app_sync_conflicts_handle_ck",drizzleOrm.sql`${t.vault_handle} IS NULL OR (length(${t.vault_handle}) BETWEEN 1 AND 256 AND instr(${t.vault_handle}, '/') = 0 AND instr(${t.vault_handle}, char(92)) = 0)`),conflictPreservationCheck:sqliteCore.check("app_sync_conflicts_preservation_ck",drizzleOrm.sql`${t.preservation_status} IN ('pending', 'ready', 'failed')`),conflictStateCheck:sqliteCore.check("app_sync_conflicts_state_ck",drizzleOrm.sql`${t.state} IN ('open', 'resolving', 'superseded', 'resolved', 'kept_both', 'purging')`),conflictArchiveLifecycleCheck:sqliteCore.check("app_sync_conflicts_archive_lifecycle_ck",drizzleOrm.sql`(
|
|
33
|
+
(${t.preservation_status} IN ('pending', 'failed') AND ${t.vault_handle} IS NULL
|
|
34
|
+
AND ${t.state} IN ('open', 'purging') AND ${t.cleanup_pending} = 0
|
|
35
|
+
AND (${t.state} = 'purging' OR ${t.superseded_by} IS NULL))
|
|
36
|
+
OR (${t.preservation_status} = 'ready' AND (
|
|
37
|
+
(${t.state} IN ('open', 'resolving', 'superseded') AND ${t.vault_handle} IS NOT NULL AND ${t.cleanup_pending} = 0)
|
|
38
|
+
OR (${t.state} = 'kept_both' AND ${t.resolution_request_id} IS NOT NULL
|
|
39
|
+
AND ${t.vault_handle} IS NOT NULL AND ${t.cleanup_pending} = 0)
|
|
40
|
+
OR (${t.state} = 'purging' AND ${t.cleanup_pending} = 0)
|
|
41
|
+
OR (${t.state} = 'resolved' AND ${t.resolution_request_id} IS NOT NULL
|
|
42
|
+
AND ((${t.cleanup_pending} = 1 AND ${t.vault_handle} IS NOT NULL)
|
|
43
|
+
OR (${t.cleanup_pending} = 0 AND ${t.vault_handle} IS NULL)))
|
|
44
|
+
))
|
|
45
|
+
)`),conflictSupersededCheck:sqliteCore.check("app_sync_conflicts_superseded_ck",drizzleOrm.sql`${t.state} != 'superseded' OR ${t.superseded_by} IS NOT NULL`),conflictResolutionCheck:sqliteCore.check("app_sync_conflicts_resolution_ck",drizzleOrm.sql`(${t.resolution_request_id} IS NULL AND ${t.resolution_choice} IS NULL) OR (length(${t.resolution_request_id}) BETWEEN 1 AND 128 AND ${t.resolution_choice} IN ('keep_local', 'use_cloud', 'keep_both'))`),conflictTimeCheck:sqliteCore.check("app_sync_conflicts_time_ck",drizzleOrm.sql`${t.updated_at} >= ${t.created_at}`),conflictBindingFk:sqliteCore.foreignKey({columns:[t.binding_id],foreignColumns:[yt.binding_id]}).onDelete("cascade"),conflictIdentityUnique:sqliteCore.uniqueIndex("app_sync_conflicts_identity_uq").on(t.binding_id,t.grant_id,t.grant_generation,t.ref,t.local_version,t.remote_revision,t.remote_fingerprint),conflictLookup:sqliteCore.index("app_sync_conflicts_lookup_idx").on(t.account_key,t.binding_id,t.state,t.updated_at)})),sqliteCore.sqliteTable("app_sync_conflict_resolutions",{request_id:sqliteCore.text("request_id").primaryKey().notNull(),conflict_id:sqliteCore.text("conflict_id").notNull(),account_key:sqliteCore.text("account_key").notNull(),human_identity:sqliteCore.text("human_identity").notNull(),choice:sqliteCore.text("choice").notNull(),expected_local_version:sqliteCore.text("expected_local_version").notNull(),expected_remote_revision:sqliteCore.integer("expected_remote_revision").notNull(),expected_remote_fingerprint:sqliteCore.text("expected_remote_fingerprint").notNull(),state:sqliteCore.text("state").notNull().default("pending"),error_code:sqliteCore.text("error_code"),created_at:sqliteCore.integer("created_at").notNull(),updated_at:sqliteCore.integer("updated_at").notNull()},t=>({resolutionRequestIdCheck:sqliteCore.check("app_sync_conflict_resolutions_request_id_ck",drizzleOrm.sql`length(${t.request_id}) BETWEEN 1 AND 128`),resolutionAccountCheck:sqliteCore.check("app_sync_conflict_resolutions_account_key_ck",drizzleOrm.sql`length(${t.account_key}) = 64 AND ${t.account_key} NOT GLOB '*[^0-9a-f]*'`),resolutionIdentityCheck:sqliteCore.check("app_sync_conflict_resolutions_human_identity_ck",drizzleOrm.sql`length(${t.human_identity}) = 64 AND ${t.human_identity} NOT GLOB '*[^0-9a-f]*'`),resolutionChoiceCheck:sqliteCore.check("app_sync_conflict_resolutions_choice_ck",drizzleOrm.sql`${t.choice} IN ('keep_local', 'use_cloud', 'keep_both')`),resolutionLocalVersionCheck:sqliteCore.check("app_sync_conflict_resolutions_local_version_ck",drizzleOrm.sql`length(${t.expected_local_version}) BETWEEN 1 AND 256 AND instr(${t.expected_local_version}, '/') = 0 AND instr(${t.expected_local_version}, char(92)) = 0`),resolutionRemoteCheck:sqliteCore.check("app_sync_conflict_resolutions_remote_ck",drizzleOrm.sql`${t.expected_remote_revision} >= 0 AND length(${t.expected_remote_fingerprint}) = 71 AND substr(${t.expected_remote_fingerprint}, 1, 7) = 'sha256:' AND substr(${t.expected_remote_fingerprint}, 8) NOT GLOB '*[^0-9a-f]*'`),resolutionStateCheck:sqliteCore.check("app_sync_conflict_resolutions_state_ck",drizzleOrm.sql`${t.state} IN ('pending', 'unknown', 'resolved', 'stale', 'failed')`),resolutionTimeCheck:sqliteCore.check("app_sync_conflict_resolutions_time_ck",drizzleOrm.sql`${t.updated_at} >= ${t.created_at}`),resolutionConflictFk:sqliteCore.foreignKey({columns:[t.conflict_id],foreignColumns:[Yc.conflict_id]}).onDelete("cascade"),resolutionConflictIdx:sqliteCore.index("app_sync_conflict_resolutions_conflict_idx").on(t.conflict_id,t.created_at),resolutionActiveUnique:sqliteCore.uniqueIndex("app_sync_conflict_resolutions_one_active_uq").on(t.conflict_id).where(drizzleOrm.sql`${t.state} IN ('pending', 'unknown')`)})),sqliteCore.sqliteTable("app_sync_account_data_purges",{request_id:sqliteCore.text("request_id").primaryKey().notNull(),binding_id:sqliteCore.text("binding_id").notNull(),account_key:sqliteCore.text("account_key").notNull(),workspace_id:sqliteCore.text("workspace_id").notNull(),root_fingerprint:sqliteCore.text("root_fingerprint").notNull(),human_identity:sqliteCore.text("human_identity").notNull(),state:sqliteCore.text("state").notNull().default("pending"),created_at:sqliteCore.integer("created_at").notNull(),updated_at:sqliteCore.integer("updated_at").notNull()},t=>({purgeRequestIdCheck:sqliteCore.check("app_sync_account_data_purges_request_id_ck",drizzleOrm.sql`length(${t.request_id}) BETWEEN 1 AND 128`),purgeAccountCheck:sqliteCore.check("app_sync_account_data_purges_account_key_ck",drizzleOrm.sql`length(${t.account_key}) = 64 AND ${t.account_key} NOT GLOB '*[^0-9a-f]*'`),purgeWorkspaceCheck:sqliteCore.check("app_sync_account_data_purges_workspace_id_ck",drizzleOrm.sql`length(${t.workspace_id}) BETWEEN 1 AND 256`),purgeRootCheck:sqliteCore.check("app_sync_account_data_purges_root_fingerprint_ck",drizzleOrm.sql`length(${t.root_fingerprint}) = 64 AND ${t.root_fingerprint} NOT GLOB '*[^0-9a-f]*'`),purgeHumanIdentityCheck:sqliteCore.check("app_sync_account_data_purges_human_identity_ck",drizzleOrm.sql`length(${t.human_identity}) = 64 AND ${t.human_identity} NOT GLOB '*[^0-9a-f]*'`),purgeStateCheck:sqliteCore.check("app_sync_account_data_purges_state_ck",drizzleOrm.sql`${t.state} IN ('pending', 'complete')`),purgeTimeCheck:sqliteCore.check("app_sync_account_data_purges_time_ck",drizzleOrm.sql`${t.updated_at} >= ${t.created_at}`),purgeAccountIndex:sqliteCore.index("app_sync_account_data_purges_account_idx").on(t.account_key,t.state,t.updated_at)}));});var Ys=k(()=>{d();sqliteCore.sqliteTable("route_states",{workspace_key:sqliteCore.text("workspace_key").notNull().default("legacy"),route_id:sqliteCore.text("route_id").notNull(),config_revision:sqliteCore.text("config_revision").notNull(),state_json:sqliteCore.text("state_json").notNull(),revision:sqliteCore.integer("revision").notNull().default(0),updated_at:sqliteCore.text("updated_at").notNull()},t=>({pk_route_state_workspace:sqliteCore.primaryKey({columns:[t.workspace_key,t.route_id]})})),sqliteCore.sqliteTable("route_sticky_bindings",{workspace_key:sqliteCore.text("workspace_key").notNull().default("legacy"),route_id:sqliteCore.text("route_id").notNull(),thread_id:sqliteCore.text("thread_id").notNull(),candidate_id:sqliteCore.text("candidate_id").notNull(),updated_at:sqliteCore.text("updated_at").notNull()},t=>({uniq_route_sticky_thread:sqliteCore.uniqueIndex("uniq_route_sticky_thread").on(t.workspace_key,t.route_id,t.thread_id),idx_route_sticky_candidate:sqliteCore.index("idx_route_sticky_candidate").on(t.workspace_key,t.route_id,t.candidate_id)})),sqliteCore.sqliteTable("route_decisions",{id:sqliteCore.text("id").primaryKey(),workspace_key:sqliteCore.text("workspace_key").notNull().default("legacy"),route_id:sqliteCore.text("route_id").notNull(),task_id:sqliteCore.text("task_id").notNull(),config_revision:sqliteCore.text("config_revision").notNull(),candidate_id:sqliteCore.text("candidate_id").notNull(),provider:sqliteCore.text("provider").notNull(),model:sqliteCore.text("model").notNull(),reason:sqliteCore.text("reason").notNull(),eligible_ids:sqliteCore.text("eligible_ids").notNull(),blocked_causes:sqliteCore.text("blocked_causes").notNull(),link_errors:sqliteCore.text("link_errors").notNull(),created_at:sqliteCore.text("created_at").notNull()},t=>({uniq_route_task_decision:sqliteCore.uniqueIndex("uniq_route_task_decision").on(t.workspace_key,t.route_id,t.task_id),idx_route_decisions_workspace_created:sqliteCore.index("idx_route_decisions_workspace_created").on(t.workspace_key,t.route_id,t.created_at)})),sqliteCore.sqliteTable("route_quota_observations",{id:sqliteCore.text("id").primaryKey(),provider:sqliteCore.text("provider").notNull(),account_ref:sqliteCore.text("account_ref").notNull().default("default"),model:sqliteCore.text("model"),status:sqliteCore.text("status",{enum:["ok","blocked"]}).notNull(),source:sqliteCore.text("source").notNull(),reset_at:sqliteCore.text("reset_at"),observed_at:sqliteCore.text("observed_at").notNull()},t=>({uniq_route_quota_observation:sqliteCore.uniqueIndex("uniq_route_quota_observation").on(t.provider,t.account_ref,t.model,t.source),idx_route_quota_observations_reset:sqliteCore.index("idx_route_quota_observations_reset").on(t.reset_at)}));});var U=k(()=>{d();gn();ft();Xo();Zo();$t();ns();os();is();cs();ls();ps();fs();hs();ys();Ss();ws();Rs();Ts();Is();Cs();wr();xs();Ms();Us();Hs();Bs();Gs();js();Ws();Ks();Vs();Ys();});var vr=k(()=>{d();P();F();q();M();U();});var kt,St=k(()=>{d();kt=["workflow_card","workflow_ui_instance","workflow_run"];});var xr=k(()=>{d();});var bn=k(()=>{d();xr();xr();});var Lr=k(()=>{d();});var Mr=k(()=>{d();});var Cn=k(()=>{d();P();F();q();M();U();});var ei=k(()=>{d();});var nu,G,Ke=k(()=>{d();nu=new Set(["ACCOUNT_SETTING_REQUIRED","MODEL_RETIRED","SUBSCRIPTION_REQUIRED"]),G=class extends Error{constructor(n,r,o){super(n);this.providerStr=r;this.name="ProviderError",this.code=o?.code??"UNKNOWN",this.kind=nu.has(this.code)?"config":o?.kind??(this.code==="UNKNOWN"?"transient":void 0),this.retryAfterMs=o?.retryAfterMs,this.settingReason=o?.settingReason,this.replacementModel=o?.replacementModel,this.providerReason=o?.providerReason;}providerStr;code;kind;retryAfterMs;settingReason;replacementModel;providerReason;stdout};});var Yt,Fr=k(()=>{d();Ke();Yt=class extends G{name="RateLimitError";constructor(e,n="cli/claude"){super(e,n,{code:"QUOTA_EXHAUSTED",kind:"transient"});}};});function Nn(t){if(typeof t!="string")return;let e=t.trim();if(e)return e=e.replace(/^\s*at\s+[^\r\n]+(?:\r?\n|$)/gim,""),e=e.replace(/(^|[\r\n])\s*(?:authorization|proxy-authorization|x-api-key|x-goog-api-key|x-auth-token|cookie|set-cookie)\s*:\s*[^\r\n]*/gim,`$1[HTTP HEADER ${se}]`),e=ou(e),e=e.replace(/\b(?:Bearer|Basic)\s+[A-Za-z0-9._~+\-/]+=*/gi,`${se}`),e=e.replace(/\bsk-[A-Za-z0-9][A-Za-z0-9_-]*/g,se),e=e.replace(/\bghp_[A-Za-z0-9][A-Za-z0-9_-]*/g,se),e=e.replace(/\bxoxb-[A-Za-z0-9-]+/g,se),e=e.replace(/\bxoxp-[A-Za-z0-9-]+/g,se),e=e.replace(/\bAKIA[0-9A-Z]{12,}\b/g,se),e=e.replace(/\bgithub_pat_[A-Za-z0-9_]+/g,se),e=e.replace(/\bgho_[A-Za-z0-9_]+/g,se),e=e.replace(/\bAIza[A-Za-z0-9_-]{20,}\b/g,se),e=e.replace(/\beyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\b/g,se),e=e.replace(/\b(?:authorization|api[_ -]?key|access[_ -]?token|auth[_ -]?token|refresh[_ -]?token|token|secret|password)\s*([:=])\s*["']?[^\s,;&"']+/gi,(n,r)=>`${se}${r}${se}`),e=e.replace(/([?&](?:api[_-]?key|access[_-]?token|token)=)[^&\s]+/gi,`$1${se}`),e=e.replace(/(?:\/(?:Users|home|private|var\/folders|tmp|workspace|workspaces|Volumes|opt|etc|srv|Applications)\/[^\s"'`),;]+)/g,ti),e=e.replace(/\b[A-Z]:\\(?:Users|home|Windows|Program Files|workspace|workspaces)\\[^\s"'`),;]*/gi,ti),e=e.replace(/[\r\n]{3,}/g,`
|
|
46
|
+
|
|
47
|
+
`).trim(),ru(e,1024)||void 0}function ru(t,e){let n=new TextEncoder;if(n.encode(t).byteLength<=e)return t;let r="",o=0;for(let s of t){let i=n.encode(s).byteLength;if(o+i>e)break;r+=s,o+=i;}return r}function ou(t){let e=/\b(?:request|response|http)?\s*body\s*[:=]\s*/gim,n="",r=0,o;for(;(o=e.exec(t))!==null;){if(o.index<r)continue;let s=o.index+o[0].length,i=su(t,s),a=i>=0?i:t.indexOf(`
|
|
48
|
+
`,s)>=0?t.indexOf(`
|
|
49
|
+
`,s):t.length;n+=t.slice(r,o.index),n+=`[HTTP BODY ${se}]`,r=a;}return n+t.slice(r)}function su(t,e){let n=t[e];if(n==='"'||n==="'")return iu(t,e,n);if(n!=="{"&&n!=="[")return -1;let r=[],o,s=false;for(let i=e;i<t.length;i+=1){let a=t[i];if(o){s?s=false:a==="\\"?s=true:a===o&&(o=void 0);continue}if(a==='"'||a==="'"){o=a;continue}if(a==="{"||a==="["){r.push(a);continue}if(a!=="}"&&a!=="]")continue;let c=r.pop();if(a==="}"&&c!=="{"||a==="]"&&c!=="[")return -1;if(r.length===0)return i+1}return -1}function iu(t,e,n){let r=false;for(let o=e+1;o<t.length;o+=1){let s=t[o];if(r)r=false;else if(s==="\\")r=true;else if(s===n)return o+1}return -1}var se,ti,Ur=k(()=>{d();se="[REDACTED]",ti="[PATH]";});function $r(t){if(!On(t)||t.type!=="item.started"||!ri(t)||!ni(t))return false;let e=t.item;return !On(e)||!ri(e)||!ni(e)||!qr(e.id)?false:e.type==="web_search"?e.query===""&&On(e.action)&&e.action.type==="other":e.type==="file_change"?e.status!=="in_progress"||!Array.isArray(e.changes)||e.changes.length===0?false:e.changes.every(n=>On(n)&&qr(n.path)&&qr(n.kind)):false}function On(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function oi(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function qr(t){return typeof t=="string"&&t.trim().length>0}function ni(t){return !oi(t,"status")||t.status==="in_progress"}function ri(t){for(let e of ["error","errors","isError","is_error"])if(oi(t,e))return false;return true}var Hr=k(()=>{d();});function wt(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Et(t){return typeof t=="string"&&t.trim().length>0}function Br(t){return typeof t=="string"?t.trim().length>0:wt(t)?Et(t.code)||Et(t.message)||Et(t.error)||Et(t.reason):false}function zt(t){let e;try{e=JSON.parse(t);}catch{return}if(wt(e))switch(e.event){case "init":return wt(e.init)?{kind:"init",envelope:e,init:e.init}:void 0;case "step_update":{if(!wt(e.step_update))return;let n=e.step_update;return !Et(n.conversation_id)||!Number.isSafeInteger(n.step_index)||n.state!=="ACTIVE"&&n.state!=="DONE"&&!(n.state==="ERROR"&&n.step_type==="tool")||!Et(n.step_type)?void 0:{kind:"step_update",envelope:e,step:n}}case "result":return wt(e.result)?{kind:"result",envelope:e,result:e.result}:void 0;case "AGY_ERROR":{let n=Br(e)?e:e.error;return Br(n)?{kind:"agy_error",envelope:e,error:n}:void 0}default:return (e.status==="SUCCESS"||e.status==="ERROR")&&typeof e.response=="string"&&(typeof e.conversation_id=="string"||Br(e.error)||wt(e.usage))?{kind:"legacy_result",envelope:e,result:e}:void 0}}function si(t){return zt(t)!==void 0}function Rt(t){let e=[];for(let n of t.split(/\r?\n/)){if(!n.trim())continue;let r=zt(n);r&&e.push(r);}return e}var vn=k(()=>{d();});function au(t,e){let n=t.trimStart();if(!n.startsWith("{"))return false;let r;try{r=JSON.parse(n);}catch{return false}let o=typeof r.type=="string"?r.type:"",s=e?fu[e]:void 0;return s?s(r,o):o?Object.values(ai).some(i=>i(r,o)):false}function at(t,e){let n=t.split(`
|
|
50
|
+
`).filter(r=>r.trim());return n.length===0?false:n.every(r=>au(r,e))}function de(t){return typeof t=="object"&&t!==null}function ii(t,e){if(e==="assistant"||e==="user"){let n=t.message;return de(n)&&Array.isArray(n.content)}return e==="system"?typeof t.subtype=="string"||typeof t.session_id=="string":e==="result"?typeof t.result=="string"||de(t.usage)||typeof t.total_cost_usd=="number"||typeof t.is_error=="boolean":e==="rate_limit_event"?de(t.rate_limit_info):e==="tool_progress"?t.heartbeat===true&&typeof t.tool_use_id=="string":false}function du(t,e){return typeof t.session_id=="string"||typeof t.uuid=="string"?true:ii(t,e)}function cu(t,e){if(e==="error")return typeof t.message=="string"||typeof t.errorMessage=="string"||typeof t.error=="string"||de(t.error);if(e==="item.updated"||e.startsWith("thread.")||e.startsWith("turn."))return true;if(e==="item.started"||e==="item.completed"){let n=t.item;return de(n)&&typeof n.type=="string"}return false}function uu(t,e){if(e==="step_start"||e==="step_finish")return typeof t.stepID=="string"||typeof t.sessionID=="string"||de(t.part);if(e==="text"||e==="tool_use")return de(t.part);if(e==="error"){let n=t.error;return de(n)&&typeof n.type=="string"&&typeof n.message=="string"}return e==="result"?typeof t.result=="string":false}function lu(t,e){return !!(typeof t.stepID=="string"||typeof t.sessionID=="string"||de(t.part)||e==="result"&&typeof t.result=="string")}function pu(t,e){return e.startsWith("assistant.")||e.startsWith("tool.execution")||e==="user.message"?de(t.data):e==="result"?typeof t.result=="string":false}function _u(t,e){return e==="message"?typeof t.role=="string":e==="tool_use"?typeof t.tool_name=="string"||typeof t.tool_id=="string":e==="tool_result"?typeof t.tool_id=="string"||typeof t.status=="string":false}function gu(t,e){return e==="available_commands"?de(t.tools)||de(t.commands):e==="usage"?de(t.usage):e==="end"?typeof t.sessionId=="string"||typeof t.stopReason=="string"||de(t.usage):e==="tool_call_update"?typeof t.toolCallId=="string"||typeof t.status=="string":false}var ai,fu,Jt=k(()=>{d();Hr();vn();ai={claude:ii,codex:cu,opencode:uu,copilot:pu,gemini:_u},fu={...ai,claude:du,opencode:lu,grok:gu,antigravity:t=>si(JSON.stringify(t))};});function De(t){return /crewx\s+(q|query|x|execute)\s/.test(t)}function Pe(t,e,n){let r=e.match(/@(\S+)/);return {timestamp:t,type:"agent_call",targetAgent:r?.[1]?.replace(/["']/g,""),toolInput:e,...typeof n=="string"&&n.length>0?{toolUseId:n}:{}}}var Tt=k(()=>{d();});function yu(t){let e=ku(t),n=e.map((s,i)=>({line:s,index:i})).filter(({line:s})=>wu(s.value)),r=Su(e);return {result:n.length===1&&n[0].index===r?Eu(n[0].line.value):null,resultPreview:Au(e,n),hasReservedLine:n.length>0}}function xe(t,e){let n=yu(t);return {resultPreview:n.resultPreview,isError:e||n.result?.isError===true,...n.hasReservedLine?{delegationResult:n.result}:{}}}function ku(t){let e=[],n=0;for(let r=0;r<t.length;r++){let o=t[r];if(o!==`
|
|
51
|
+
`&&o!=="\r")continue;let s=o==="\r"&&t[r+1]===`
|
|
52
|
+
`?`\r
|
|
53
|
+
`:o;e.push({value:t.slice(n,r),separator:s}),r+=s.length-1,n=r+1;}return e.push({value:t.slice(n),separator:""}),e}function Su(t){for(let e=t.length-1;e>=0;e--)if(t[e].value.trim())return e;return -1}function wu(t){return t.trimStart().startsWith(hu)}function Eu(t){let e=t.trim();if(!e.startsWith(di)||!e.endsWith("]]"))return null;let n=e.slice(di.length,-2);if(!n)return null;try{return Ru(JSON.parse(n))}catch{return null}}function Ru(t){return Tu(t)?Object.prototype.hasOwnProperty.call(t,"taskId")?{schema:1,taskId:t.taskId,agentId:t.agentId,isError:t.isError}:{schema:1,isError:true}:null}function Tu(t){if(!Iu(t)||Object.keys(t).some(r=>!mu.has(r))||t.schema!==1||typeof t.isError!="boolean")return false;let e=Object.prototype.hasOwnProperty.call(t,"taskId"),n=Object.prototype.hasOwnProperty.call(t,"agentId");return e!==n?false:e?ci(t.taskId)&&ci(t.agentId):t.isError===true}function Au(t,e){if(e.length===0)return t.map(r=>r.value+r.separator).join("");let n=new Set(e.map(({index:r})=>r));return t.map((r,o)=>n.has(o)?"":r.value+r.separator).join("")}function ci(t){return typeof t=="string"&&t.trim().length>0}function Iu(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var di,hu,mu,At=k(()=>{d();di="[[crewx:delegation-result ",hu="[[crewx:delegation-result",mu=new Set(["schema","taskId","agentId","isError"]);});function Le(t){if(typeof t=="string")return t;if(!t||typeof t!="object")return JSON.stringify(t??{});let e=t;return typeof e.command=="string"?e.command:typeof e.file_path=="string"?e.file_path:typeof e.filePath=="string"?e.filePath:typeof e.path=="string"?e.path:typeof e.query=="string"?e.query:typeof e.pattern=="string"?e.pattern:typeof e.url=="string"?e.url:typeof e.prompt=="string"?e.prompt.length>200?e.prompt.slice(0,200)+"\u2026":e.prompt:typeof e.description=="string"?e.description:JSON.stringify(e)}var It=k(()=>{d();});var ui,Dn,Gr,Pn=k(()=>{d();ui=["none","minimal","low","medium","high","xhigh","max","ultra"],Dn={claude:["low","medium","high","xhigh","max"],codex:["none","minimal","low","medium","high","xhigh","max","ultra"],opencode:[],copilot:["none","low","medium","high","xhigh","max"],antigravity:["low","medium","high"],grok:["low","medium","high","xhigh"]},Gr={claude:{models:[{id:"claude-fable-5-1",name:"Claude Fable 5.1",contextWindowTokens:1e6,tier:"flagship",recommended:true},{id:"claude-fable-5",name:"Claude Fable 5",contextWindowTokens:1e6,tier:"flagship"},{id:"claude-opus-5-5",name:"Claude Opus 5.5",contextWindowTokens:1e6,tier:"flagship",recommended:true},{id:"claude-opus-5",name:"Claude Opus 5",contextWindowTokens:1e6,tier:"flagship"},{id:"claude-sonnet-5-5",name:"Claude Sonnet 5.5",contextWindowTokens:1e6,tier:"balanced",recommended:true},{id:"claude-sonnet-5",name:"Claude Sonnet 5",contextWindowTokens:1e6,tier:"balanced"},{id:"claude-opus-4-8[1m]",name:"Claude Opus 4.8",contextWindowTokens:1e6,tier:"flagship"},{id:"claude-opus-4-7[1m]",name:"Claude Opus 4.7",contextWindowTokens:1e6,tier:"flagship"},{id:"claude-opus-4-6[1m]",name:"Claude Opus 4.6",contextWindowTokens:1e6,tier:"flagship"},{id:"claude-sonnet-4-6[1m]",name:"Claude Sonnet 4.6",contextWindowTokens:1e6,tier:"balanced"},{id:"claude-haiku-5-5",name:"Claude Haiku 5.5",contextWindowTokens:1e6,tier:"speed"},{id:"claude-haiku-4-5",name:"Claude Haiku 4.5",contextWindowTokens:2e5,tier:"speed"}],modes:[{id:"default",name:"Default",description:"Uses Claude's default permission handling with normal approval prompts."},{id:"acceptEdits",name:"Accept Edits",description:"Allows file edits without approval; other permission checks remain in place."},{id:"plan",name:"Plan",description:"Keeps Claude in plan mode so it can inspect and propose changes without applying them."},{id:"dontAsk",name:"Don't Ask",description:"Does not ask for permissions; only pre-approved tool actions can proceed."},{id:"bypassPermissions",name:"Bypass Permissions",description:"Bypasses Claude permission checks so tools can run without approval prompts."}],effort:["low","medium","high"],modelOverrides:{"claude-fable-5-1":{effort:["low","medium","high","xhigh","max"],defaultEffort:"high"},"claude-fable-5":{effort:["low","medium","high","xhigh","max"],defaultEffort:"high"},"claude-opus-5-5":{effort:["low","medium","high","xhigh","max"],defaultEffort:"medium"},"claude-opus-5":{effort:["low","medium","high","xhigh","max"],defaultEffort:"high"},"claude-sonnet-5-5":{effort:["low","medium","high","xhigh","max"],defaultEffort:"high"},"claude-sonnet-5":{effort:["low","medium","high","xhigh","max"],defaultEffort:"high"},"claude-opus-4-8[1m]":{effort:["low","medium","high","xhigh","max"],defaultEffort:"high"},"claude-opus-4-7[1m]":{effort:["low","medium","high","xhigh","max"],defaultEffort:"high"},"claude-opus-4-6[1m]":{effort:["low","medium","high","max"],defaultEffort:"high"},"claude-sonnet-4-6[1m]":{effort:["low","medium","high","max"],defaultEffort:"high"},"claude-haiku-5-5":{effort:["low","medium","high","xhigh","max"],defaultEffort:"medium"},"claude-haiku-4-5":{effort:[]}},providerOptions:[]},codex:{models:[{id:"gpt-6-astra",name:"GPT-6 Astra",contextWindowTokens:105e4,tier:"flagship"},{id:"gpt-6.1-sol",name:"GPT-6.1 Sol",contextWindowTokens:105e4,tier:"balanced",recommended:true},{id:"gpt-6.1-terra",name:"GPT-6.1 Terra",contextWindowTokens:5e5,tier:"balanced"},{id:"gpt-6-sol",name:"GPT-6 Sol",contextWindowTokens:105e4,tier:"balanced"},{id:"gpt-6-luna",name:"GPT-6 Luna",contextWindowTokens:105e4,tier:"speed",recommended:true},{id:"gpt-5.6-sol",name:"GPT-5.6 Sol",contextWindowTokens:105e4,tier:"flagship"},{id:"gpt-5.6-terra",name:"GPT-5.6 Terra",contextWindowTokens:105e4,tier:"balanced"},{id:"gpt-5.6-luna",name:"GPT-5.6 Luna",contextWindowTokens:105e4,tier:"speed"}],modes:[{id:"agent",name:"Agent",description:"Uses the workspace-write sandbox; can read and modify workspace files without full machine access."},{id:"read-only",name:"Read Only",description:"Uses the read-only sandbox; can inspect files but cannot write to the workspace."},{id:"plan",name:"Plan",description:"Uses the read-only sandbox for planning and inspection; cannot write to the workspace."},{id:"agent-full-access",name:"Agent Full Access",description:"Bypasses approvals and the sandbox; can access and modify files beyond the workspace."},{id:"yolo",name:"YOLO",description:"Bypasses approvals and the sandbox for unrestricted execution and full filesystem access."}],effort:["minimal","low","medium","high"],modelOverrides:{"gpt-6-astra":{effort:["low","medium","high","xhigh","max"],defaultEffort:"xhigh"},"gpt-6.1-sol":{effort:["low","medium","high","xhigh","max"],defaultEffort:"high"},"gpt-6.1-terra":{effort:["low","medium","high","xhigh","max","ultra"],defaultEffort:"max"},"gpt-6-sol":{effort:["none","low","medium","high","xhigh","max"],defaultEffort:"max"},"gpt-6-luna":{effort:["none","low","medium","high","xhigh","max"],defaultEffort:"medium"},"gpt-5.6-sol":{effort:["low","medium","high","xhigh","max","ultra"],defaultEffort:"xhigh"},"gpt-5.6-terra":{effort:["low","medium","high","xhigh","max","ultra"],defaultEffort:"high"},"gpt-5.6-luna":{effort:["low","medium","high","xhigh","max"],defaultEffort:"high"},"gpt-5.5":{effort:["low","medium","high","xhigh"],defaultEffort:"high"}},providerOptions:[]},opencode:{models:[],suggestedModels:[{id:"opencode-go/glm-5.3-flash",name:"GLM-5.3 Flash",contextWindowTokens:1e6,tier:"speed",recommended:true},{id:"opencode-go/qwen3.8-flash",name:"Qwen3.8 Flash",contextWindowTokens:1e6,tier:"speed",recommended:true},{id:"opencode-go/minimax-m3",name:"MiniMax M3",contextWindowTokens:1e6,tier:"balanced",recommended:true},{id:"opencode-go/kimi-k2.7-code",name:"Kimi K2.7 Code",contextWindowTokens:262144,tier:"balanced",recommended:true}],modes:[{id:"plan",name:"Plan",description:"Uses the plan agent without --auto; planning follows standard approval behavior."},{id:"plan-auto",name:"Plan \xB7 Auto",description:"Uses the plan agent with --auto; planning uses automatic approvals."},{id:"build",name:"Build",description:"Uses the build agent without --auto; work follows standard approval behavior."},{id:"build-auto",name:"Build \xB7 Auto",description:"Uses the build agent with --auto; work uses automatic approvals."}],effort:[],modelOverrides:{},providerOptions:[]},copilot:{models:[{id:"auto",name:"Auto"},{id:"claude-sonnet-5",name:"Claude Sonnet 5",contextWindowTokens:1e6,tier:"balanced"}],modes:[{id:"interactive",name:"Interactive",description:"Passes --mode interactive; tool access follows Copilot's interactive mode behavior."},{id:"plan",name:"Plan",description:"Passes --mode plan; planning and permission behavior follow Copilot's plan mode."},{id:"autopilot",name:"Autopilot",description:"Passes --mode autopilot; execution behavior follows Copilot's autonomous mode."}],effort:["none","low","medium","high","xhigh","max"],modelOverrides:{},providerOptions:[]},antigravity:{models:[{id:"gemini-3.8-flash",name:"Gemini 3.8 Flash",tier:"balanced"},{id:"gemini-3.7-flash",name:"Gemini 3.7 Flash",contextWindowTokens:1048576,tier:"balanced"},{id:"gemini-3.6-flash",name:"Gemini 3.6 Flash",contextWindowTokens:1048576,tier:"balanced"},{id:"gemini-3.1-pro",name:"Gemini 3.1 Pro",contextWindowTokens:1048576,tier:"flagship"},{id:"claude-sonnet-5-5-medium",name:"Claude Sonnet 5.5",tier:"balanced"},{id:"claude-opus-5-5-medium",name:"Claude Opus 5.5",tier:"flagship"},{id:"gemini-4-argon",name:"Gemini 4 Argon",tier:"flagship"}],modes:[{id:"default",name:"Default",description:"Uses Antigravity's default permission handling. No extra permission flags are passed."},{id:"plan",name:"Plan",description:"Passes --mode plan. This turns on /plan; it is not a Claude-style permission mode."},{id:"acceptEdits",name:"Accept Edits",description:"Passes --mode accept-edits."},{id:"bypassPermissions",name:"Bypass Permissions",description:"Passes --dangerously-skip-permissions so tools can run without approval prompts."}],effort:["low","medium","high"],modelOverrides:{"gemini-3.8-flash":{effort:["low","medium","high"],defaultEffort:"medium"},"gemini-3.7-flash":{effort:["low","medium","high"],defaultEffort:"medium"},"gemini-3.6-flash":{effort:["low","medium","high"],defaultEffort:"medium"},"gemini-3.5-flash":{effort:["low","medium","high"],defaultEffort:"medium"},"gemini-3.1-pro":{effort:["low","high"],defaultEffort:"high"},"claude-sonnet-5-5-medium":{effort:["low","medium","high"],defaultEffort:"medium"},"claude-opus-5-5-medium":{effort:["low","medium","high"],defaultEffort:"medium"},"gemini-4-argon":{effort:["low","medium","high"],defaultEffort:"high"},"claude-sonnet-4-6":{effort:[]},"claude-opus-4-6-thinking":{effort:[]},"gpt-oss-120b":{effort:["medium"],defaultEffort:"medium"}},providerOptions:[]},grok:{models:[{id:"grok-4.7",name:"Grok 4.7",contextWindowTokens:5e5,tier:"flagship",recommended:true},{id:"grok-4.6",name:"Grok 4.6",contextWindowTokens:5e5,tier:"flagship"},{id:"grok-4.5",name:"Grok 4.5",contextWindowTokens:5e5,tier:"flagship"}],modes:[{id:"default",name:"Default",description:"Uses Grok's default permission handling."},{id:"acceptEdits",name:"Accept Edits",description:"Allows file edits without changing the selected sandbox profile."},{id:"auto",name:"Auto",description:"Uses Grok automatic permission handling."},{id:"dontAsk",name:"Don't Ask",description:"Does not ask for permission before tool execution."},{id:"bypassPermissions",name:"Bypass Permissions",description:"Bypasses Grok permission checks for tool execution."},{id:"plan",name:"Plan",description:"Keeps Grok in planning mode without applying changes."}],effort:["low","medium","high"],modelOverrides:{"grok-4.7":{effort:["low","medium","high","xhigh"],defaultEffort:"high"},"grok-4.6":{effort:["low","medium","high","xhigh"],defaultEffort:"high"},"grok-4.5":{effort:["low","medium","high"],defaultEffort:"high"}},providerOptions:[{key:"alwaysApprove",type:"boolean"},{key:"sandbox",type:"enum",values:["workspace","read-only","off"]}]}},Object.fromEntries(Object.entries(Gr).map(([t,e])=>[t,e.models]));});function jr(t){return Cu[t]??t}function Ou(t){return Nu.get(t)??t}function Wr(t){if(!t)return {};let e=Du.get(t);return e?{...e}:{model:t}}function Kr(t,e){return t==="antigravity"||t==="cli/antigravity"?Wr(e):e===void 0?{}:{model:Ou(e)}}var bu,Cu,Nu,vu,Du,Xt=k(()=>{d();bu=[{baseModelId:"claude-opus-4-8",catalogModelId:"claude-opus-4-8[1m]"},{baseModelId:"claude-opus-4-7",catalogModelId:"claude-opus-4-7[1m]"},{baseModelId:"claude-opus-4-6",catalogModelId:"claude-opus-4-6[1m]"},{baseModelId:"claude-sonnet-4-6",catalogModelId:"claude-sonnet-4-6[1m]"}],Cu={"accept-edits":"acceptEdits",yolo:"bypassPermissions","agent-full-access":"bypassPermissions"};Nu=new Map(bu.map(({baseModelId:t,catalogModelId:e})=>[t,e]));vu=[{legacyId:"Gemini 3.7 Flash (High)",model:"gemini-3.7-flash",effort:"high"},{legacyId:"Gemini 3.7 Flash (Medium)",model:"gemini-3.7-flash",effort:"medium"},{legacyId:"Gemini 3.7 Flash (Low)",model:"gemini-3.7-flash",effort:"low"},{legacyId:"Gemini 3.6 Flash (High)",model:"gemini-3.6-flash",effort:"high"},{legacyId:"Gemini 3.6 Flash (Medium)",model:"gemini-3.6-flash",effort:"medium"},{legacyId:"Gemini 3.6 Flash (Low)",model:"gemini-3.6-flash",effort:"low"},{legacyId:"Gemini 3.5 Flash (Medium)",model:"gemini-3.5-flash",effort:"medium"},{legacyId:"Gemini 3.5 Flash (High)",model:"gemini-3.5-flash",effort:"high"},{legacyId:"Gemini 3.5 Flash (Low)",model:"gemini-3.5-flash",effort:"low"},{legacyId:"Gemini 3.1 Pro (Low)",model:"gemini-3.1-pro",effort:"low"},{legacyId:"Gemini 3.1 Pro (High)",model:"gemini-3.1-pro",effort:"high"},{legacyId:"Claude Sonnet 4.6 (Thinking)",model:"claude-sonnet-4-6"},{legacyId:"Claude Opus 4.6 (Thinking)",model:"claude-opus-4-6-thinking"},{legacyId:"GPT-OSS 120B (Medium)",model:"gpt-oss-120b",effort:"medium"},{legacyId:"gemini-3.7-flash-high",model:"gemini-3.7-flash",effort:"high"},{legacyId:"gemini-3.7-flash-medium",model:"gemini-3.7-flash",effort:"medium"},{legacyId:"gemini-3.7-flash-low",model:"gemini-3.7-flash",effort:"low"},{legacyId:"gemini-3.6-flash-high",model:"gemini-3.6-flash",effort:"high"},{legacyId:"gemini-3.6-flash-medium",model:"gemini-3.6-flash",effort:"medium"},{legacyId:"gemini-3.6-flash-low",model:"gemini-3.6-flash",effort:"low"},{legacyId:"gemini-3.5-flash-high",model:"gemini-3.5-flash",effort:"high"},{legacyId:"gemini-3.5-flash-medium",model:"gemini-3.5-flash",effort:"medium"},{legacyId:"gemini-3.5-flash-low",model:"gemini-3.5-flash",effort:"low"},{legacyId:"gemini-3.1-pro-high",model:"gemini-3.1-pro",effort:"high"},{legacyId:"gemini-3.1-pro-low",model:"gemini-3.1-pro",effort:"low"},{legacyId:"gpt-oss-120b-medium",model:"gpt-oss-120b",effort:"medium"}],Du=new Map(vu.map(({legacyId:t,model:e,effort:n})=>[t,n===void 0?{model:e}:{model:e,effort:n}]));});function xu(){return {models:[],modes:[],effort:[],modelOverrides:{},providerOptions:[]}}function Ve(t){return Qt(t).models}function Qt(t){let e=Pu[t],n=Gr[t];return e?e.suggestedModels!==void 0||n?.suggestedModels===void 0?e:{...e,suggestedModels:n.suggestedModels}:n??xu()}function Zt(t,e){let n=Qt(t);if(e){if(Object.prototype.hasOwnProperty.call(n.modelOverrides,e))return n.modelOverrides[e]?.effort??n.effort;let r=Kr(t,e);return r.model===void 0?n.effort:n.modelOverrides[r.model]?.effort??n.effort}return n.effort}function Vr(t){return Qt(t).modelOverrides}function li(){return Ve("claude")}function pi(){return Ve("codex")}function _i(){return Ve("copilot")}function gi(){return Ve("antigravity")}var Pu,Ye=k(()=>{d();Pn();bn();Xt();Pu={};});function fi(t){return Mu[t]??t}var Mu,hi=k(()=>{d();Ye();Xt();Mu={auto:"default"};});function Yr(t,e){return (Dn[t]??[]).includes(e)}function dt(t){if(!t)return {};let e=t.match(/^(.+?)\[([^\]]+)\]$/);if(e){let n=e[2].toLowerCase();return Fu.has(n)?{model:e[1],effort:n}:{model:t}}return {model:t}}function mi(t){switch(t){case "agent-full-access":case "yolo":return ["--dangerously-bypass-approvals-and-sandbox"];case "read-only":case "plan":return ["--sandbox","read-only"];case "agent":return ["-c","sandbox_mode=workspace-write"];default:return []}}function yi(t){switch(t){case "agent-full-access":case "yolo":return ["--dangerously-bypass-approvals-and-sandbox"];case "read-only":case "plan":return ["-c","sandbox_mode=read-only"];case "agent":return ["-c","sandbox_mode=workspace-write"];default:return []}}function ki(t){return !t||!Yr("codex",t)?[]:["-c",`model_reasoning_effort=${t}`]}function Si(t){if(!t)return [];let e=new Set(["acceptEdits","bypassPermissions","default","delegate","dontAsk","plan"]),n=fi(t);return e.has(n)?["--permission-mode",n]:[]}function wi(t){return t?Yr("claude",t)?["--effort",t]:[]:[]}function Ei(t){if(!t)return [];switch(jr(t)){case "default":return [];case "plan":return ["--mode","plan"];case "acceptEdits":return ["--mode","accept-edits"];case "bypassPermissions":return ["--dangerously-skip-permissions"];default:return []}}function Ri(t){return t?Yr("antigravity",t)?["--effort",t]:[]:[]}var Fu,en=k(()=>{d();hi();Xt();Pn();Fu=new Set(ui);});function Uu(t){if(t.type!=="usage"||!("input_tokens"in t))return null;let e=Number(t.input_tokens??0),n=Number(t.output_tokens??0),o="cache_read_input_tokens"in t?Number(t.cache_read_input_tokens):void 0,s="cached_input_tokens"in t?Number(t.cached_input_tokens):void 0,i=o!==void 0?o:s??0;return {inputTokens:o!==void 0?e+o:e,outputTokens:n,cachedInputTokens:i}}function qu(t){let e=t.usage;if(!e||typeof e!="object"||Array.isArray(e))return null;let n=e;if(!("input_tokens"in n))return null;let r=Number(n.input_tokens??0),o=Number(n.output_tokens??0),i="cache_read_input_tokens"in n?Number(n.cache_read_input_tokens):void 0,a="cached_input_tokens"in n?Number(n.cached_input_tokens):void 0,c=i!==void 0?i:a??0;return {inputTokens:i!==void 0?r+i:r,outputTokens:o,cachedInputTokens:c}}function $u(t){if(t.type!=="step_finish")return null;let n=t.part?.tokens;if(!n)return null;let r=Number(n.input??0),o=Number(n.output??0)+Number(n.reasoning??0),s=n.cache,i=s?Number(s.read??0):0;return {inputTokens:r+i,outputTokens:o,cachedInputTokens:i}}function Ti(t){let e=new Map,n;for(let s of t.split(`
|
|
54
|
+
`))if(s.trim())try{let i=JSON.parse(s);if(i.type!=="assistant")continue;let a=i.message,c=a?.id,u=a?.usage;if(typeof c!="string"||!u)continue;let p=Number(u.input_tokens??0),g=Number(u.cache_read_input_tokens??0);e.set(c,{inputTokens:p+g,cachedInputTokens:g});let _=a?.model;typeof _=="string"&&_&&(n=_);}catch{}if(e.size===0)return;let r=0,o=0;for(let s of e.values())r+=s.inputTokens,o+=s.cachedInputTokens;return {inputTokens:r,cachedInputTokens:o,model:n}}function tn(t){if(!t||!t.trim())return;let e=null,n=null;for(let r of t.split(`
|
|
55
|
+
`))if(r.trim())try{let o=JSON.parse(r),s=$u(o);if(s){n||(n={inputTokens:0,outputTokens:0,cachedInputTokens:0}),n.inputTokens+=s.inputTokens,n.outputTokens+=s.outputTokens,n.cachedInputTokens+=s.cachedInputTokens;continue}let i=Uu(o)??qu(o);i&&(e=i);}catch{}return n||(e??void 0)}var nn=k(()=>{d();});function He(t,e){if(typeof t!="object"||t===null||Array.isArray(t))return e;let n=t.timestamp;return typeof n!="string"||!Number.isFinite(Date.parse(n))?e:new Date(n).toISOString()}var ct=k(()=>{d();});var xn,Ai=k(()=>{d();xn=Object.freeze({CLAUDE_CODE_DISABLE_AUTO_MEMORY:"1"});});function bi(t){return t==="all"?[...Ii,...Hu]:Ii}function Ci(t){return bi(t).map(e=>`Bash(${e} *)`)}function Ni(t){return bi(t).map(e=>`command(${e})`)}var Ii,Hu,zr=k(()=>{d();Ii=["crewx memory","crewx search","crewx doc","crewx notify"],Hu=["crewx q","crewx query","crewx x","crewx execute","crewx cron","crewx wbs","crewx wi","crewx workflow","crewx app","crewx skill"];});function Oi(t){let e=t.split(`
|
|
56
|
+
`).filter(o=>o.trim()),n=[],r=null;for(let o of e)try{let s=JSON.parse(o);if(s.type==="assistant"&&Array.isArray(s.message?.content))for(let i of s.message.content)i.type==="text"&&typeof i.text=="string"&&i.text.trim()&&n.push(i.text.trim());s.type==="result"&&typeof s.result=="string"&&(r=s.result);}catch{}if(n.length>0)return n[n.length-1];if(r)return r}function vi(t){let e=t.split(`
|
|
57
|
+
`).filter(n=>n.trim());for(let n of e.reverse())try{let r=JSON.parse(n);if(typeof r=="object"&&r!==null&&r.type==="result")return r}catch{}}function bt(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:void 0}function Mi(t){let e=bt(t.rate_limit_info);if(t.type==="rate_limit_event"&&e?.status==="rejected")return `Claude rate limit: ${typeof e.rateLimitType=="string"?e.rateLimitType:"unknown"} (status: rejected)`;if(t.error==="rate_limit"){let n=Vu(t);return n?`Claude rate limit: ${n}`:"Claude rate limit"}if(t.type==="result"&&t.is_error===true){let n=typeof t.result=="string"?t.result:"";if(Yu(n))return `Claude rate limit: ${n}`}}function ju(t){for(let e of t.split(`
|
|
58
|
+
`)){let n=e.trim();if(n){if(n.startsWith("Not logged in"))return n;try{let r=bt(JSON.parse(n));if(r?.type==="result"&&r.is_error===!0&&typeof r.result=="string"&&r.result.startsWith("Not logged in"))return r.result}catch{}}}}function Wu(t){let e=bt(t);if(e?.type!=="rate_limit_event")return;let n=bt(bt(e.rate_limit_info)?.unifiedWindows);if(!n)return;let r=Di(n.five_hour),o=Di(n.seven_day);if(!(!r&&!o))return {...r?{five_hour:r}:{},...o?{seven_day:o}:{}}}function Di(t){let e=bt(t);if(!(typeof e?.utilization!="number"||typeof e.resetsAt!="number"))return {utilization:e.utilization,resetsAt:e.resetsAt}}function Pi(t){if(t?.is_error===true)return Nn(t.result)}function Ku(t){let e=Mi(t);if(e)return e;if(t.type!=="result"||t.is_error!==true)return;let n=typeof t.result=="string"?t.result:"";if(n.trim())return n;let r=typeof t.subtype=="string"?t.subtype:"unknown",o=typeof t.terminal_reason=="string"?t.terminal_reason:"unknown";return `Claude ended without an answer (subtype=${r}, terminal_reason=${o})`}function Vu(t){let n=t.message?.content;return Array.isArray(n)?n.map(r=>typeof r.text=="string"?r.text.trim():"").filter(Boolean).join(`
|
|
59
|
+
|
|
60
|
+
`):""}function Yu(t){let e=t.toLowerCase();return e.includes("out of extra usage")||e.includes("rate limit")||e.includes("quota")}function Li(t){return t.replace(/\s+/g," ").trim()}function zu(t,e){let n=t?.description;if(typeof n!="string")return;let r=Li(n);if(!r||r===Li(e))return;if(r.length<=xi)return r;let o=r.slice(0,xi-1);return /[\uD800-\uDBFF]$/.test(o)&&(o=o.slice(0,-1)),`${o}\u2026`}function Ju(t,e){let n=e.type;if(n==="text"){let r=String(e.text||"");return r?{timestamp:t,type:"text",content:r}:null}if(n==="thinking"){let r=typeof e.thinking=="string"?e.thinking.trim():"";return r?{timestamp:t,type:"thinking",content:r}:null}if(n==="tool_use"){let r=String(e.name||""),o=e.id,s=e.input,i=Le(s);if(r==="Bash"&&De(i))return Pe(t,i,o);let a=zu(s,i);return {timestamp:t,type:"tool_use",toolUseId:o,toolName:r,toolInput:i,...a?{toolTitle:a}:{}}}if(n==="tool_result"){let r=!!e.is_error,o=e.tool_use_id,s=e.output??e.content??"",i;return typeof s=="string"?i=s:Array.isArray(s)?i=s.filter(a=>a.type==="text"&&typeof a.text=="string").map(a=>a.text).join(`
|
|
61
|
+
`):i=JSON.stringify(s),{timestamp:t,type:"tool_result",toolUseId:o,...xe(i,r)}}return null}var Bu,Gu,Jr,xi,Xr=k(()=>{d();Fr();Ke();Ur();Jt();Tt();At();It();en();Ye();nn();ct();Ai();zr();Bu=new Set(["tool_progress"]),Gu="cli/claude";Jr={command:"claude",meta:{displayName:"Claude",models:li(),capabilities:{resume:true}},buildArgs(t,e,n){let{model:r,effort:o}=dt(e.model),s=e.effort??o,i=Si(e.mode),a=wi(s),c=r?["--model",r]:[],u=e.mode==="bypassPermissions"?[]:["--allowedTools",...Ci(e.builtinAllow)],p=e.resumeSessionId?["--resume",e.resumeSessionId]:[];if(e.additionalArgs!==void 0){let _=[...e.additionalArgs];return _.indexOf("-p")!==-1?{args:["--output-format","stream-json","--verbose",...p,...i,...a,...c,...u,..._],stdinMessage:t,env:xn}:{args:["--output-format","stream-json","--verbose",...p,...i,...a,...c,...u,..._],stdinMessage:t,env:xn}}return {args:["-p","--output-format","stream-json","--verbose",...p,...i,...a,...c,...u],stdinMessage:t,env:xn}},extractText(t){let e=vi(t);if(e?.is_error===true){let o=Jr.extractFailure(JSON.stringify(e));if(o)throw o;let s=typeof e.subtype=="string"?e.subtype:"unknown",i=typeof e.terminal_reason=="string"?e.terminal_reason:"unknown";throw new G(Pi(e)??`Claude ended without an answer (subtype=${s}, terminal_reason=${i})`,Gu,{code:"EMPTY_OUTPUT",kind:"permanent"})}let n=Oi(t);if(n)return n;let r=t.trim();return at(r,"claude")?"":r},extractPartialText(t){return Oi(t)},extractFailure(t){try{let e=JSON.parse(t),n=Mi(e);if(n)return new Yt(n)}catch{}return null},interpretExit(t,e,n){let r=ju(n??"");if(r)return new G(`Claude is not logged in (exit ${t}): ${r}. Sign in to this account with the official "claude auth login".`,"cli/claude",{code:"AUTH_REQUIRED",kind:"config"});let o=Pi(vi(n??""));return o?new G(o,"cli/claude"):null},observeRateLimit(t){try{let e=JSON.parse(t);return Wu(e)}catch{return}},parseResultMeta(t){let e=t.split(`
|
|
62
|
+
`);for(let r of e)if(r.trim())try{let o=JSON.parse(r);if(o.type==="result"){let s=o.usage,i=s?{inputTokens:Number(s.input_tokens??0)+Number(s.cache_read_input_tokens??0),outputTokens:Number(s.output_tokens??0),cachedInputTokens:Number(s.cache_read_input_tokens??0),costUsd:Number(o.total_cost_usd??0)}:null,a=o.modelUsage,c=a?Object.keys(a)[0]??null:null;return {usage:i,model:c}}}catch{}let n=Ti(t);return n?{usage:{inputTokens:n.inputTokens,outputTokens:0,cachedInputTokens:n.cachedInputTokens,costUsd:0},model:n.model??null}:{usage:null,model:null}},parseEvent(t,e){let n;try{n=JSON.parse(t);}catch{return []}let r=n.type;if(!r)return [];let o=He(n,e??new Date().toISOString()),s=Ku(n);if(s)return [{timestamp:o,type:"error",content:s,errorMessage:s}];let i=n.output_file,a=n.summary;if(r==="system"&&n.subtype==="task_notification"&&n.status==="completed"&&typeof i=="string"&&i.trim().length>0&&typeof a=="string"&&a.trim().length>0)return [{timestamp:o,type:"text",content:a}];if(r!=="assistant"&&r!=="user")return [];let u=n.message?.content;if(!Array.isArray(u))return [];let p=[];for(let g of u){let _=Ju(o,g);_&&p.push(_);}return p},suppressOutputLine(t){let e=t.trim();if(!e.startsWith("{")||!e.endsWith("}"))return false;try{let r=JSON.parse(e).type;return r?Bu.has(r):!1}catch{return false}}};xi=200;});function Fi(t){let e=t.split(`
|
|
63
|
+
`).filter(o=>o.trim()),n=[],r=null;for(let o of e)try{let s=JSON.parse(o);if(s.type==="assistant.message"&&typeof s.data?.content=="string"){let i=s.data.content;i.trim()&&n.push(i.trim());}s.type==="result"&&typeof s.result=="string"&&(r=s.result);}catch{}if(n.length>0)return n[n.length-1];if(r)return r}var Xu,Qr=k(()=>{d();Jt();nn();Tt();It();At();Ye();Pn();ct();Xu=new Set(["interactive","plan","autopilot"]);({command:"copilot",meta:{displayName:"Copilot",models:_i()},buildArgs(t,e,n){let r=e.additionalArgs?[...e.additionalArgs]:[];return e.model&&r.push("--model",e.model),e.mode&&Xu.has(e.mode)&&r.push("--mode",e.mode),e.effort&&(Dn.copilot??[]).includes(e.effort)&&r.push("--effort",e.effort),{args:r,stdinMessage:t}},extractText(t){let e=Fi(t);if(e)return e;let n=t.trim();return at(n,"copilot")?"":n},extractPartialText(t){return Fi(t)},parseResultMeta(t){let e=tn(t);return e?{usage:{inputTokens:e.inputTokens,outputTokens:e.outputTokens,cachedInputTokens:e.cachedInputTokens,costUsd:0},model:null}:{usage:null,model:null}},parseEvent(t,e){let n;try{n=JSON.parse(t);}catch{return []}let r=n.type;if(!r)return [];if(!r.startsWith("tool.execution")&&!r.startsWith("assistant.")&&r!=="user.message")return [];let o=n.data;if(!o)return [];let s=He(n,e??new Date().toISOString()),i=o.toolCallId;if(r==="tool.execution_start"){let a=String(o.toolName||""),c=o.arguments,u=Le(c);return (a==="bash"||a==="Bash")&&De(u)?[Pe(s,u,i)]:[{timestamp:s,type:"tool_use",toolName:a,toolInput:u,...i&&{toolUseId:i}}]}if(r==="tool.execution_complete"){let a=o.error;if(a)return [{timestamp:s,type:"tool_result",...i&&{toolUseId:i},...xe(String(a.message||""),true)}];let c=o.result,u=String(c?.content||"");return [{timestamp:s,type:"tool_result",...i&&{toolUseId:i},...xe(u,false)}]}if(r==="assistant.message"){let a=String(o.content||"");return a?[{timestamp:s,type:"text",content:a}]:[]}return []}});});function el(t){let e=[],n=0,r=false,o=false,s=0;for(let a=0;a<t.length;a++){let c=t[a];if(o){o=false;continue}if(c==="\\"&&r){o=true;continue}if(c==='"'){r=!r;continue}if(!r){if(c==="{")n++;else if(c==="}"&&(n--,n===0)){let u=t.slice(s,a+1).trim();u&&e.push(u),s=a+1;}}}let i=t.slice(s).trim();return i&&e.push(i),e}function tl(t){return t[0]==="exec"?t.slice(1):t}function qi(t){let e=t.split(`
|
|
64
|
+
`).map(o=>o.trim()).filter(Boolean),n=[],r=null;for(let o of e)try{let s=JSON.parse(o);if(s.type==="item.completed"&&(s.item?.type==="message"||s.item?.type==="agent_message")&&typeof s.item?.text=="string"){let i=s.item.text;i.trim()&&n.push(i.trim());}s.type==="result"&&typeof s.result=="string"&&(r=s.result);}catch{}if(n.length>0)return n[n.length-1];if(r)return r}function ze(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Hi(t){return t.type==="turn.failed"?true:t.type!=="error"?false:typeof t.message=="string"||typeof t.errorMessage=="string"||typeof t.error=="string"||ze(t.error)}function Bi(t){let e=ze(t.error)?t.error:void 0,n=[t.message,t.errorMessage,e?.message,e?.detail,typeof t.error=="string"?t.error:void 0];for(let r of n)if(typeof r=="string"&&r.trim())return r;return t.type==="turn.failed"?"Codex turn failed.":"Codex CLI reported an error."}function nl(t){for(let e of t.split(/\r?\n/)){if(!e.trim())continue;let n;try{n=JSON.parse(e);}catch{continue}if(ze(n)&&Hi(n))return Bi(n)}}function $i(t,e,n,r){if(!n||t.type!=="command_execution"&&t.type!=="mcp_tool_call"||typeof t.id!="string"||!t.id.trim()||t.type==="mcp_tool_call"&&e==="item.started"&&(typeof t.server!="string"||typeof t.tool!="string"))return;let o=n.state.get("codex.pending");o||(o=new Map,n.state.set("codex.pending",o));let s=JSON.stringify([t.type,t.id]);if(e==="item.started"){let c=`codex:${JSON.stringify(t.id)}#${n.rowIndex}:${r}`,u=o.get(s)??[];return u.push(c),o.set(s,u),c}let i=o.get(s),a=i?.pop();return i?.length||o.delete(s),a}function rl(t,e,n){let r=e.type;if(r==="command_execution"){let o=String(e.command||"");return De(o)?[Pe(t,o,n)]:[{timestamp:t,type:"tool_use",toolName:"Bash",toolInput:o,...n?{toolUseId:n}:{}}]}return r==="mcp_tool_call"?typeof e.server!="string"||typeof e.tool!="string"?[]:[{timestamp:t,type:"tool_use",toolName:`${e.server}/${e.tool}`,toolInput:Le(e.arguments),...n?{toolUseId:n}:{}}]:[]}function ol(t,e,n){let r=e.type;if(r==="message"||r==="text"){let o=e.content;if(Array.isArray(o))for(let s of o){let i=sl(t,s);if(i)return i}if(typeof e.text=="string")return {timestamp:t,type:"text",content:e.text}}if(r==="agent_message"&&typeof e.text=="string")return {timestamp:t,type:"text",content:e.text};if(r==="reasoning"){let o=typeof e.text=="string"?e.text.trim():"";return o?{timestamp:t,type:"thinking",content:o}:null}if(r==="command_execution"){let o=String(e.aggregated_output||e.output||""),s=!!e.is_error;return {timestamp:t,type:"tool_result",...xe(o,s),...n?{toolUseId:n}:{}}}if(r==="mcp_tool_call"){let o=ze(e.result)?e.result:void 0,i=(Array.isArray(o?.content)?o.content:[]).filter(c=>ze(c)&&c.type==="text"&&typeof c.text=="string").map(c=>c.text).join(`
|
|
65
|
+
`),a=typeof e.error=="string"?e.error:ze(e.error)&&typeof e.error.message=="string"?e.error.message:"";return {timestamp:t,type:"tool_result",resultPreview:i||a,isError:e.status==="failed"||e.status==="error"||e.is_error===true||e.error!=null,...n?{toolUseId:n}:{}}}if(r==="tool_use"){let o=String(e.name||e.tool_name||""),s=e.input,i=Le(s);return o==="Bash"&&De(i)?Pe(t,i):{timestamp:t,type:"tool_use",toolName:o,toolInput:i}}if(r==="tool_result"){let o=!!e.is_error,s=String(e.output||e.content||"");return {timestamp:t,type:"tool_result",...xe(s,o)}}if(r==="web_search"){let o=e.action,s;if(o?.type==="search"){let i=o.queries;s=String(o.query||"")||(i?.length?i.join(", "):"")||String(e.query||"");}else s=e.query?"open: "+String(e.query):"";return !s&&!(ze(o)&&o.type==="other"&&e.query==="")?null:{timestamp:t,type:"tool_use",toolName:"WebSearch",toolInput:s}}if(r==="file_change"){let o=e.changes;if(!Array.isArray(o)||o.length===0)return null;let s=o.map(a=>String(a.path||"")).filter(Boolean);if(s.length===0)return null;let i=s.length===1?s[0]:`${s.slice(0,2).join(", ")}${s.length>2?` (+${s.length-2})`:""}`;return {timestamp:t,type:"tool_use",toolName:"Edit",toolInput:i}}return null}function sl(t,e){let n=e.type;if(n==="text")return {timestamp:t,type:"text",content:String(e.text||"")};if(n==="tool_use"){let r=String(e.name||""),o=e.input,s=Le(o);return r==="Bash"&&De(s)?Pe(t,s):{timestamp:t,type:"tool_use",toolName:r,toolInput:s}}return null}var Qu,Zu,Zr=k(()=>{d();Ke();Jt();nn();Tt();It();Hr();At();en();Ye();ct();Qu=new Set(["turn.started","turn.completed","item.updated"]),Zu="cli/codex";({command:"codex",meta:{displayName:"Codex",models:pi(),capabilities:{resume:true}},buildArgs(t,e,n){let{model:r,effort:o}=dt(e.model),s=e.effort??o,i=e.resumeSessionId?yi(e.mode):mi(e.mode),a=ki(s),c=r?["-m",r]:[],u=tl(e.additionalArgs??[]),g=u.includes("--json")||u.includes("--experimental-json")?[]:["--json"];return e.resumeSessionId?{args:["exec","resume",...g,...i,...a,...c,...u,e.resumeSessionId,"-"],stdinMessage:t}:{args:["exec",...g,...i,...a,...c,...u],stdinMessage:t}},extractText(t){let e=nl(t);if(e)throw new G(e,Zu);let n=qi(t);if(n)return n;let r=t.trim();return at(r,"codex")?"":r},extractPartialText(t){return qi(t)},parseResultMeta(t){let e=tn(t);return e?{usage:{inputTokens:e.inputTokens,outputTokens:e.outputTokens,cachedInputTokens:e.cachedInputTokens,costUsd:0},model:null}:{usage:null,model:null}},parseEvent(t,e,n){let r=e??new Date().toISOString(),o=[],s;try{JSON.parse(t),s=[t];}catch{s=el(t),s.length>1&&console.warn("[codex] parseEvent: falling back to concatenated-JSON split for a malformed line");}for(let[i,a]of s.entries()){let c;try{c=JSON.parse(a);}catch{continue}if(!ze(c))continue;let u=c.type;if(!u)continue;let p=He(c,r);if(Hi(c)){let _=Bi(c);o.push({timestamp:p,type:"error",content:_,errorMessage:_});continue}if(!u.startsWith("item.")&&!u.startsWith("turn.")&&!u.startsWith("thread.")||$r(c))continue;u==="thread.started"&&n&&n.state.delete("codex.pending");let g=c.item;if(g){if(u==="item.started"){o.push(...rl(p,g,$i(g,u,n,i)));continue}if(u==="item.completed"){let _=ol(p,g,$i(g,u,n,i));_&&o.push(_);continue}}}return o},suppressOutputLine(t){let e=t.trim();if(!e.startsWith("{")||!e.endsWith("}"))return false;try{let r=JSON.parse(e).type;return r?Qu.has(r):!1}catch{return false}}});});var ji=k(()=>{d();});var Wi=k(()=>{d();});function al(t){let e=t.match(/(?:^|[^0-9])([0-9]{1,5})(?![0-9])/);if(!e)return null;let n=Number(e[1]);return Number.isInteger(n)&&n>0&&n<=65535?n:null}function dl(){return new Promise(t=>{let e=false,n,r=o=>{e||(e=true,n&&clearTimeout(n),t(o));};n=setTimeout(()=>r(null),Ki),n.unref();try{child_process.execFile("chcp.com",[],{encoding:"ascii",timeout:Ki,windowsHide:!0},(s,i)=>{if(s){r(null);return}r(al(String(i)));}).once("error",()=>r(null));}catch{r(null);}})}function cl(){return process.platform!=="win32"?Promise.resolve(null):(Ln||(Ln=dl(),Ln.then(t=>{},()=>{})),Ln)}function ul(){process.platform==="win32"&&cl();}var Ki,Ln,Yi=k(()=>{d();Ki=1e3;ul();});var eo=k(()=>{d();});var zi=k(()=>{d();});var to=k(()=>{d();Ke();eo();zi();});var Ji=k(()=>{d();no();Wi();Yi();eo();to();Ye();});var ro=k(()=>{d();Ke();ji();nn();It();ct();Ji();to();});var Xi=k(()=>{d();});function Ct(t,e){return t.some(n=>n===e||n.startsWith(`${e}=`))}function Sl(t,e){return t&&Qi.has(t)||Ct(e,"--dangerously-skip-permissions")?true:e.some((n,r)=>{let o=n==="--mode"?e[r+1]:n.startsWith("--mode=")?n.slice(7):void 0;return typeof o=="string"&&Qi.has(o)})}function wl(t,e){let n=[];for(let r=0;r<t.length;r+=1){let o=t[r],s=[...e].find(i=>o===i||o.startsWith(`${i}=`));s?o===s&&r+1<t.length&&(r+=1):n.push(o);}return n}function El(t){let e=[];for(let n=0;n<t.length;n+=1){let r=t[n],o=r.indexOf("="),s=o>0?r.slice(0,o):r;if(!yl.has(s)){e.push(r);continue}r===s&&n+1<t.length&&!t[n+1].startsWith("-")&&(n+=1);}return e}function he(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Rl(t,e){if(!(t?ml.has(t)||Ve(oo).some(s=>s.id===t):false)||!t)return e;let r=Zt(oo,t),o=Vr(oo)[t]?.defaultEffort;if(r.length!==0)return e?r.includes(e)?e:o&&r.includes(o)?o:void 0:o}function Be(t){return typeof t=="number"&&Number.isSafeInteger(t)&&t>=0?t:void 0}function ao(t){return t.kind==="step_update"?typeof t.step.conversation_id=="string"?t.step.conversation_id:void 0:typeof t.envelope.conversation_id=="string"?t.envelope.conversation_id:void 0}function co(t){return t.step.step_index}function $(t){if(typeof t!="string")return;let e=t.split(/\r?\n/,1)[0]?.trim();return e&&Nn(e)?.slice(0,500).trim()||void 0}function Tl(t,e){let n=(t??"").trim().toUpperCase().replace(/[^A-Z0-9]+/g,"_");if(n!=="UNKNOWN"&&kl.has(n))return n;let r=`${n} ${e??""}`.toLowerCase();return /quota|resource_exhausted|usage[ _-]?limit|credits?.{0,20}exhaust/.test(r)?"QUOTA_EXHAUSTED":/rate[ _-]?limit|throttl/.test(r)?"RATE_LIMITED":/auth|sign[ _-]?in|log(?:ged)?[ _-]?in|unauthori[sz]ed|credential/.test(r)?"AUTH_REQUIRED":[/unknown (?:flag|option)/,/flag provided but not defined/,/unrecognized (?:flag|option)/,/invalid value for (?:flag|option)/,/invalid (?:flag|option)/].some(s=>s.test(r))?"INVALID_PROVIDER_FORMAT":/invalid.{0,24}model|model.{0,24}(unknown|unavailable|not found|not recognized)|config/.test(r)?"MODEL_UNAVAILABLE":"UNKNOWN"}function Al(t){return t==="AUTH_REQUIRED"||t==="TIMEOUT_IDLE"||t==="TIMEOUT_TOTAL"||t==="TIMEOUT_RESUME"||t==="PROVIDER_CRASHED"?"permanent":t==="MODEL_UNAVAILABLE"||t==="INVALID_PROVIDER_FORMAT"||t==="PROVIDER_NOT_FOUND"?"config":"transient"}function ta(t){let e=he(t)?t:void 0,n=e&&he(e.error)?e.error:void 0,r=e?$(e.code)??$(e.error_code)??$(n?.code)??$(n?.error_code):void 0,o=typeof t=="string"?$(t):e?$(e.message)??$(e.error)??$(e.reason)??$(n?.message)??$(n?.error)??$(n?.reason):void 0,s=Tl(r,o),i=e?Be(e.retry_after_ms)??Be(e.retryAfterMs)??Be(n?.retry_after_ms)??Be(n?.retryAfterMs):void 0;return {code:s,kind:Al(s),message:o??"Antigravity reported a terminal error.",...i===void 0?{}:{retryAfterMs:i}}}function Fn(t){let e=ta(t);return new G(e.message,"cli/antigravity",{code:e.code,kind:e.kind,...e.retryAfterMs===void 0?{}:{retryAfterMs:e.retryAfterMs}})}function uo(t){return new G(t,"cli/antigravity",{code:"INVALID_PROVIDER_FORMAT",kind:"config"})}function Il(t){let e=new TextEncoder().encode(t).byteLength;if(!(e<=io))throw new G(`Input is too large: final provider initial input is ${e} UTF-8 bytes; budget is ${io} bytes.`,"cli/antigravity",{code:"UNKNOWN",kind:"config"})}function so(){return new G("Antigravity CLI returned empty output with exit code 0. agy may have hidden an auth/quota/model error in its log file; inspect ~/.gemini/antigravity-cli/log for details.","cli/antigravity",{code:"EMPTY_OUTPUT",kind:"transient"})}function Un(t){if(t.kind==="result"||t.kind==="legacy_result")return t.result}function qn(t){for(let e=t.length-1;e>=0;e-=1){let n=t[e];if(n&&(n.kind==="result"||n.kind==="legacy_result"||n.kind==="agy_error"))return {event:n,index:e}}}function bl(t){let e=qn(t);if(!e||e.event.kind==="agy_error"||e.index!==t.length-1||Un(e.event)?.status!=="SUCCESS"||Mn(t))return false;let r=new Map;for(let o of t){if(o.kind!=="step_update"||o.step.step_type!=="agent_response")continue;let s=ao(o),i=co(o);!s||!Number.isSafeInteger(i)||r.set(JSON.stringify([s,i]),o.step);}if(r.size===0)return false;for(let o of r.values())if(o.state!=="DONE"||!he(o.usage)||Be(o.usage.input_tokens)===void 0||Be(o.usage.output_tokens)===void 0)return false;return true}function Cl(t,e){for(let n=e-1;n>=0;n-=1){let r=t[n];if(r?.kind==="agy_error")return r.error}}function Nl(t,e){return he(t)&&he(e)?{...e,...t}:he(t)&&typeof e=="string"?{...t,message:e}:typeof t=="string"&&he(e)?{...e,message:t}:t??e}function Ol(t){let e=Array.isArray(t.denied_actions)?t.denied_actions:[],n=[];for(let i of e){let a=he(i)?i:void 0,c=typeof i=="string"?$(i):$(a?.display_name)??$(a?.action);c&&!n.includes(c)&&n.length<5&&n.push(c.slice(0,80));}let r=Math.max(0,e.length-n.length),o=n.length>0?` (${n.join(", ")}${r>0?`, +${r} more`:""})`:"",s=`Permission denied: Antigravity blocked ${e.length} requested action${e.length===1?"":"s"}${o}.`;return new G("\uAD8C\uD55C \uB54C\uBB38\uC5D0 \uC2E4\uD589\uD558\uC9C0 \uBABB\uD588\uC5B4\uC694","cli/antigravity",{code:"UNKNOWN",kind:"permanent",providerReason:s})}function Mn(t){let e=qn(t);if(!e)return;if(e.event.kind==="agy_error")return Fn(e.event.error);let n=Un(e.event);if(!n)return;if(Array.isArray(n.denied_actions)&&n.denied_actions.length>0)return Ol(n);if(n.status==="SUCCESS")return;if(n.status!=="ERROR")return uo("Antigravity returned a result with an unsupported status.");let r=n.error,o=Nl(r==null||r===""?n:r,Cl(t,e.index));return Fn(o)}function na(t){if(typeof t=="string")return t;if(t!=null)try{return JSON.stringify(t)}catch{return}}function vl(t){return `agy:${String(t.conversation_id)}:${String(t.step_index)}`}function Dl(t,e){let n=typeof e?.name=="string"?e.name:t.tool_name;return typeof n=="string"&&n.trim()?n:void 0}function ra(t){let e=na(t);if(e)return e.length<=2e3?e:`${e.slice(0,1999)}\u2026`}function Pl(t){let e=he(t)?t:void 0,n=e&&he(e.error)?e.error:void 0,r=typeof t=="string"?t.trim().match(/^([A-Z][A-Z0-9_]*)(?:[:\s]|$)/)?.[1]:void 0,o=($(e?.type)??$(e?.code)??$(e?.error_type)??$(n?.type)??$(n?.code)??$(n?.error_type)??$(r)??"TOOL_ERROR").slice(0,60),s=ta(t).message.slice(0,250);return ra({type:o,message:s})??"Antigravity reported a tool error."}function Zi(t,e){return t?t.state.has(e)?true:(t.state.set(e,true),false):false}function ea(t,e){return {timestamp:t,type:"error",content:e.message,errorMessage:e.message,isError:true}}var oo,ml,yl,Qi,io,kl,lo=k(()=>{d();Ke();Xi();Ur();Xt();Ye();en();vn();zr();oo="antigravity",ml=new Set(["claude-sonnet-4-6","claude-opus-4-6-thinking","gpt-oss-120b"]),yl=new Set(["--conversation","--resume","--continue"]),Qi=new Set(["bypassPermissions","agent-full-access","yolo"]),io=18e4,kl=new Set(["QUOTA_EXHAUSTED","RATE_LIMITED","EMPTY_OUTPUT","AUTH_REQUIRED","MODEL_UNAVAILABLE","TIMEOUT_IDLE","TIMEOUT_TOTAL","TIMEOUT_RESUME","PROVIDER_NOT_FOUND","INVALID_PROVIDER_FORMAT","PROVIDER_CRASHED","UNKNOWN"]);({command:"agy",maxInitialInputBytes:io,meta:{displayName:"Antigravity",models:gi(),defaultIdleMs:6e5,capabilities:{resume:true,usageCompleteness:true}},extractSessionId(t){let e=zt(t);if(e?.kind!=="init")return null;let n=e.envelope.conversation_id;return typeof n=="string"&&n.trim().length>0?n.trim():null},buildArgs(t,e,n){Il(t);let{model:r,effort:o}=dt(e.model),s=Wr(r),i=s.model,a=e.effort??o??s.effort,c=Rl(i,a),u=e.additionalArgs??[],p=El(wl(u,new Set(["--input-format","--output-format"]))),g=i&&!Ct(u,"--model")?["--model",i]:[],_=Ct(u,"--effort")?[]:Ri(c),S=Ct(u,"--mode")||Ct(u,"--dangerously-skip-permissions")?[]:Ei(e.mode),w=Sl(e.mode,u)||Ct(u,"--settings")?[]:["--settings",JSON.stringify({permissions:{allow:Ni(e.builtinAllow)}})],R=typeof e.resumeSessionId=="string"&&e.resumeSessionId.trim().length>0?["--conversation",e.resumeSessionId]:[];return {args:["--input-format","stream-json","--output-format","stream-json",...g,..._,...S,...R,...w,...p],stdinMessage:`${JSON.stringify({event:"user",message:{content:t}})}
|
|
66
|
+
`,env:{AGY_CLI_DISABLE_AUTO_UPDATE:"true"}}},extractText(t){let e=Rt(t),n=qn(e)?.event,r=Mn(e);if(r)throw r;let o=n?Un(n):void 0;if(o){if(o.status!=="SUCCESS")throw uo("Antigravity returned a result with an unsupported status.");if(typeof o.response!="string")throw uo("Antigravity returned a successful result without a response string.");if(!o.response.trim())throw so();return o.response}if(e.length>0)throw so();let s=t.trim();if(!s)throw so();return s},extractPartialText(t){let e=Rt(t),n=qn(e)?.event;if(!n||n.kind==="agy_error")return;let r=Un(n);return r&&typeof r.response=="string"&&r.response.trim()?r.response:void 0},interpretExit(t,e,n){let r=Rt(n??""),o=Mn(r);return o||(t!==0&&e.trim()?Fn(e):null)},parseResultMeta(t){let e=Rt(t),n=0,r=0,o=0,s=0,i=new Set;for(let c of e){if(c.kind!=="step_update"||c.step.state!=="DONE"||!he(c.step.usage))continue;let u=ao(c),p=co(c);if(!u||!Number.isSafeInteger(p))continue;let g=JSON.stringify([u,p]);if(i.has(g))continue;let _=c.step.usage,S=Be(_.input_tokens),w=Be(_.output_tokens);if(S===void 0||w===void 0)continue;i.add(g);let R=Be(_.cache_read_tokens)??0;n+=S+R,r+=w,o+=R,s+=1;}return {usage:s===0?null:{inputTokens:n,outputTokens:r,cachedInputTokens:o,costUsd:0,complete:bl(e)},model:null}},parseEvent(t,e,n){let r=zt(t);if(!r)return [];let o=e??new Date().toISOString();if(r.kind==="agy_error")return [ea(o,Fn(r.error))];if(r.kind==="legacy_result"||r.kind==="result"){let S=Mn([r]);return S?[ea(o,S)]:[]}if(r.kind!=="step_update")return [];let{step:s}=r,i=ao(r)??"unknown",a=co(r),c=`${i}:${a}`;if((s.state==="DONE"||s.state==="ERROR")&&Zi(n,`antigravity:terminal:${c}`))return [];if(s.step_type==="agent_response")return typeof s.text_delta=="string"&&s.text_delta.length>0?[{timestamp:o,type:"text",content:s.text_delta}]:[];if(s.step_type!=="tool")return [];let u=he(s.tool_info)?s.tool_info:void 0,p=Dl(s,u);if(!p)return [];let g=vl(s);if(s.state==="ACTIVE"){if(Zi(n,`antigravity:active:${c}`))return [];let S=na(u?.parameters);return [{timestamp:o,type:"tool_use",toolName:p,toolUseId:g,...S===void 0?{}:{toolInput:S}}]}let _=s.state==="ERROR"?Pl(u?.error):ra(u?.output);return [{timestamp:o,type:"tool_result",toolName:p,toolUseId:g,..._===void 0?{}:{resultPreview:_},...s.state==="ERROR"?{isError:true}:{}}]}});});var sa=k(()=>{d();Tt();It();At();ct();});var po=k(()=>{d();Ke();Fr();Ye();At();en();ct();});var no=k(()=>{d();Xr();Qr();Zr();ro();lo();sa();po();Xr();Qr();Zr();ro();lo();po();Tt();});var ia=k(()=>{d();ei();no();});var _o=k(()=>{d();ia();bn();});var rn,Nt=k(()=>{d();rn=["success","completed","done","failed","error","stopped","runner_lost"];});var on=k(()=>{d();});var fo=k(()=>{d();Mr();on();});var Yl,Ot=k(()=>{d();P();F();q();M();U();St();bn();Lr();Mr();Cn();vr();_o();Nt();on();fo();on();St();Yl="0.8.9-rc.13",parseInt(Yl.split("rc.")[1]),new Set(rn);});d();d();d();var T="workout-log",Je="workout-log.records.v1",ut=500,Bn=100,Gn=4096,Dt=6e4,jn=200,Pt=20,sn=6e4;d();var xt=class{epoch=0;activeSession=null;grantControllers=new Map;get activeAccountKey(){return this.activeSession?.accountKey??null}get activeSessionEpoch(){let e=this.activeSession;return e&&!e.controller.signal.aborted?e.epoch:null}currentToken(e){let n=this.activeSession;return !n||n.accountKey!==e||n.controller.signal.aborted?null:this.toSessionToken(n)}activate(e){if(!/^[0-9a-f]{64}$/.test(e))throw new Error("INVALID_ACCOUNT_KEY");if(this.activeSession?.accountKey===e&&!this.activeSession.controller.signal.aborted)return this.toSessionToken(this.activeSession);this.abortActiveSession();let n={accountKey:e,epoch:++this.epoch,controller:new AbortController};return this.activeSession=n,this.toSessionToken(n)}captureGrant(e,n,r){if(!this.isCurrent(e))throw new Error("APP_SYNC_SESSION_STALE");if(!n||!Number.isSafeInteger(r)||r<1)throw new Error("INVALID_GRANT_FENCE");let o=new AbortController,s=this.grantKey(e.accountKey,n,r),i=()=>o.abort(e.signal.reason);e.signal.aborted?i():e.signal.addEventListener("abort",i,{once:true});let a=this.grantControllers.get(s)??new Set;return a.add({controller:o,sessionSignal:e.signal,onSessionAbort:i}),this.grantControllers.set(s,a),{accountKey:e.accountKey,epoch:e.epoch,grantId:n,generation:r,signal:o.signal}}isCurrent(e){let n=this.activeSession;return n!==null&&n.accountKey===e.accountKey&&n.epoch===e.epoch&&!n.controller.signal.aborted&&!e.signal.aborted}release(e){let n=this.grantKey(e.accountKey,e.grantId,e.generation),r=this.grantControllers.get(n);if(r){for(let o of r)o.controller.signal===e.signal&&(o.sessionSignal.removeEventListener("abort",o.onSessionAbort),r.delete(o));r.size===0&&this.grantControllers.delete(n);}}cancelGrant(e,n,r){let o=this.grantKey(e,n,r),s=this.grantControllers.get(o);if(s){for(let i of s)i.sessionSignal.removeEventListener("abort",i.onSessionAbort),i.controller.abort("grant_invalidated");this.grantControllers.delete(o);}}suspend(e){this.activeSession&&(e===void 0||this.activeSession.accountKey===e)&&(this.abortActiveSession(),this.epoch+=1);}toSessionToken(e){return {accountKey:e.accountKey,epoch:e.epoch,signal:e.controller.signal}}abortActiveSession(){let e=this.activeSession;if(e){e.controller.abort("session_suspended");for(let[n,r]of this.grantControllers)if(n.startsWith(`${e.accountKey}:${e.epoch}:`)){for(let o of r)o.sessionSignal.removeEventListener("abort",o.onSessionAbort),o.controller.abort("session_suspended");this.grantControllers.delete(n);}this.activeSession=null;}}grantKey(e,n,r){return `${e}:${this.activeSession?.epoch??this.epoch}:${n}:${r}`}};d();var Aa=Je,pe=Object.freeze({root:"docs/apps/workout-log",include:Object.freeze(["exercises.md","routines/<id>.md","workouts/<YYYY-MM-DD>-<id>.md"]),idPattern:"^[A-Za-z0-9_-]{1,40}$",exclude:Object.freeze(["migration/**","*.json","app-state/**",".*","*~","*.tmp","*.swp","*.part",".env*","auth.json","*.key","*.pem"])}),Wn=Object.freeze({exactFiles:Object.freeze(["exercises.md"]),directFolders:Object.freeze(["routines","workouts"]),suffix:".md",maxDepth:1}),Ia=/^[A-Za-z0-9_-]{1,40}$/,Ao=["root","include","idPattern","exclude"];function Io(t,e){return Array.isArray(t)&&t.length===e.length&&t.every((n,r)=>n===e[r])}function ba(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Ca(t){if(t==="exercises.md")return "exercises";if(/^routines\/[A-Za-z0-9_-]{1,40}\.md$/.test(t))return "routine";let e=/^workouts\/(\d{4})-(\d{2})-(\d{2})-([A-Za-z0-9_-]{1,40})\.md$/.exec(t);if(!e||!Ia.test(e[4]))return null;let[,n,r,o]=e,s=Number(n),i=Number(r),a=Number(o);if(s<1||i<1||i>12||a<1||a>31)return null;let c=new Date(0);return c.setUTCHours(0,0,0,0),c.setUTCFullYear(s,i-1,a),c.getUTCFullYear()!==s||c.getUTCMonth()!==i-1||c.getUTCDate()!==a?null:"workout"}function Na(t){let n=t.trim().replace(/[ \t]+#.*$/,"").trim();return /^[A-Za-z0-9_-]+$/.test(n)?n:/^"[A-Za-z0-9_-]+"$/.test(n)||/^'[A-Za-z0-9_-]+'$/.test(n)?n.slice(1,-1):null}function Oa(t){if(typeof t!="string")return null;let e=t.indexOf(`
|
|
67
|
+
`);if((e<0?t:t.slice(0,e)).replace(/\r$/,"")!=="---")return null;let r=new Map,o=e<0?t.length:e+1;for(;o<=t.length;){let s=t.indexOf(`
|
|
68
|
+
`,o),i=s<0?t.length:s,a=t.slice(o,i);a.endsWith("\r")&&(a=a.slice(0,-1));let c=s<0?i:s+1;if(Buffer.byteLength(t.slice(0,c),"utf8")>4096)return null;if(a==="---")return r.has("crewx_app")&&r.has("kind")?r:null;let u=/^(crewx_app|kind):[ \t]*(.*)$/.exec(a);if(u){let p=u[1];if(r.has(p))return null;let g=Na(u[2]);if(g===null)return null;r.set(p,g);}if(s<0)break;o=s+1;}return null}var Lt=class{scopeVersion=Je;definition=pe;matchesDefinition(e,n){return e!==Aa||!ba(n)||Object.keys(n).length!==Ao.length||!Ao.every(r=>Object.hasOwn(n,r))?false:n.root===pe.root&&n.idPattern===pe.idPattern&&Io(n.include,pe.include)&&Io(n.exclude,pe.exclude)}validateRef(e){if(typeof e!="string"||e.length===0||e.length>256)return {valid:false,reason:"out_of_scope"};if(e.includes("\0")||e.includes("\\")||e.startsWith("/")||e.startsWith("~"))return {valid:false,reason:"out_of_scope"};if(e.split("/").some(o=>o===""||o==="."||o===".."))return {valid:false,reason:"out_of_scope"};if(e.startsWith(".")||/(?:^|\/)\./.test(e)||/(?:^|\/)[^/]*(?:~|\.tmp|\.swp|\.part)$/.test(e))return {valid:false,reason:"out_of_scope"};if(/(?:^|\/)(?:auth\.json|[^/]*\.key|[^/]*\.pem)$/.test(e)||/\.env[^/]*$/.test(e))return {valid:false,reason:"out_of_scope"};let r=Ca(e);return r===null?{valid:false,reason:"out_of_scope"}:{valid:true,kind:r}}validateFrontMatter(e,n){let r=this.validateRef(e);if(!r.valid)return {valid:false,reason:"invalid_front_matter"};let o=Oa(n);return o?o.get("crewx_app")!==T?{valid:false,reason:"app_mismatch"}:o.get("kind")!==r.kind?{valid:false,reason:"kind_mismatch"}:{valid:true,kind:r.kind}:{valid:false,reason:"invalid_front_matter"}}};function L(t){return `sha256:${crypto.createHash("sha256").update(t,"utf8").digest("hex")}`}function lt(t){if(!Array.isArray(t)||t.length===0||t.length>64)return null;let e=[];for(let n of t){if(typeof n!="string"||n.length===0)return null;let r=n.normalize("NFC");if(r==="."||r===".."||r.includes("/")||r.includes("\\")||r.includes("\0")||/^[A-Za-z]:$/.test(r)||r.startsWith("~"))return null;e.push(r);}return e}d();d();var Da=10*6e4,Pa=5e3,Ge=class extends Error{constructor(n){if(!Number.isSafeInteger(n)||n<0)throw new Error("INVALID_APP_SYNC_BUDGET_RETRY_AT");super("APP_SYNC_BUDGET_DEFERRED");this.retryAt=n;this.name="AppSyncBudgetDeferredError";}retryAt;code="APP_SYNC_BUDGET_DEFERRED"},Kn=class{constructor(e){this.sqlite=e;if(!e||typeof e.prepare!="function"||typeof e.transaction!="function")throw new Error("INVALID_DOC_CREATE_LEDGER_DATABASE")}sqlite;peek(e,n){Vn(e),an(n),this.deleteExpired(n);let r=this.readWindow(e,n);return r.count<20?{available:true,remaining:20-r.count}:{available:false,retryAt:bo(r,n)}}reserve(e){return Co(e),this.sqlite.transaction(r=>{this.deleteExpired(r.now);let o=this.readWindow(r.accountKey,r.now);return o.count>=20?{ok:false,retryAt:bo(o,r.now)}:(this.insert(r),{ok:true})}).immediate(e)}reserveForced(e){Co(e),this.deleteExpired(e.now),this.insert(e);}prune(e){return an(e),this.deleteExpired(e)}readWindow(e,n){let r=this.sqlite.prepare(`
|
|
69
|
+
SELECT COUNT(*) AS count, MIN(dispatched_at) AS oldest
|
|
70
|
+
FROM doc_create_dispatches
|
|
71
|
+
WHERE account_key = ? AND dispatched_at > ?
|
|
72
|
+
`).get(e,n-6e4);if(!r||!Number.isSafeInteger(r.count)||r.count<0||r.oldest!==null&&!Number.isSafeInteger(r.oldest))throw new Error("DOC_CREATE_LEDGER_READ_INVALID");return r}insert(e){this.sqlite.prepare(`
|
|
73
|
+
INSERT INTO doc_create_dispatches (dispatch_id, request_id, account_key, source, dispatched_at)
|
|
74
|
+
VALUES (?, ?, ?, ?, ?)
|
|
75
|
+
`).run(crypto.randomUUID(),e.requestId,e.accountKey,e.source,e.now);}deleteExpired(e){return this.sqlite.prepare("DELETE FROM doc_create_dispatches WHERE dispatched_at <= ?").run(e-Da).changes}};function Mt(t){if(Vn(t.accountKey),No(t.requestId),Oo(t.source),typeof t.now!="function"||typeof t.ledger?.peek!="function"||typeof t.ledger.reserve!="function"||typeof t.ledger.reserveForced!="function"||typeof t.ledger.prune!="function"||t.guard!==void 0&&typeof t.guard!="function")throw new Error("INVALID_DOC_CREATE_DISPATCH_GATE");let e=0,n=(()=>{e+=1;let r=t.guard?.();if(r!=null&&typeof r.then=="function")throw Promise.resolve(r).catch(()=>{}),new Error("APP_SYNC_DISPATCH_GUARD_MUST_BE_SYNCHRONOUS");let o=t.now();an(o);try{let s=t.ledger.reserve({accountKey:t.accountKey,requestId:t.requestId,source:t.source,now:o});if(s.ok===!0||s.ok===!1&&Number.isSafeInteger(s.retryAt)&&s.retryAt>=0)return s;throw new Error("DOC_CREATE_LEDGER_DECISION_INVALID")}catch{throw new Ge(o+Pa)}});return Object.defineProperty(n,"calls",{enumerable:true,get:()=>e}),n}function bo(t,e){if(t.oldest===null)throw new Error("DOC_CREATE_LEDGER_WINDOW_EMPTY");let n=t.oldest+6e4;if(!Number.isSafeInteger(n)||n<e)throw new Error("DOC_CREATE_LEDGER_RETRY_AT_INVALID");return n}function Co(t){if(!t||typeof t!="object")throw new Error("INVALID_DOC_CREATE_DISPATCH_INPUT");Vn(t.accountKey),No(t.requestId),Oo(t.source),an(t.now);}function Vn(t){if(typeof t!="string"||!/^[0-9a-f]{64}$/.test(t))throw new Error("INVALID_DOC_CREATE_LEDGER_ACCOUNT_KEY")}function No(t){if(typeof t!="string"||t.length<1||t.length>128)throw new Error("INVALID_DOC_CREATE_LEDGER_REQUEST_ID")}function Oo(t){if(t!=="human"&&t!=="app_create"&&t!=="app_reattach")throw new Error("INVALID_DOC_CREATE_LEDGER_SOURCE")}function an(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("INVALID_DOC_CREATE_LEDGER_TIME")}var vo=1e4,La=12e4,cn=class{constructor(e,n,r,o,s,i){this.dependencies=e;this.scopeRegistry=n;this.sessionFence=r;this.now=o;this.createId=s;this.hasPendingRevoke=i;if(!e.continuation)throw new Error("APP_SYNC_CONTINUATION_CAPABILITY_REQUIRED");if(!e.remote.listGrantDocs||!e.remote.listDeletedRefs||!e.documents.inspectContinuation||!e.documents.applyContinuation)throw new Error("APP_SYNC_CONTINUATION_PORT_REQUIRED");this.continuation=e.continuation,this.continuationStore=e.continuation.store;let a=e.continuation.pageSize??100;if(!Number.isSafeInteger(a)||a<1)throw new Error("APP_SYNC_CONTINUATION_PAGE_SIZE_INVALID");this.pageSize=Math.min(a,200);}dependencies;scopeRegistry;sessionFence;now;createId;hasPendingRevoke;continuation;continuationStore;pageSize;async tick(e,n,r,o,s){let i=this.createFenceContext(e,n,r,o);i.fence.assertCurrent(),!(this.continuationStore.beginDiscoveryCycle({binding:e,fence:i.fence,now:this.now()})&&!await this.traverseWithCursorRecovery(i))&&(i.fence.assertCurrent(),await this.processPendingDiscoveries(i));}listConflicts(e){let n=this.dependencies.store.getBinding(e.bindingId);if(!n||!e.session.authenticated||e.session.accountKey!==n.accountKey||n.workspaceId!==e.workspaceId||!Do(n.rootSegments,e.resolvedRootSegments))return [];let r=this.sessionFence.currentToken(n.accountKey);return !r||this.sessionFence.activeAccountKey!==n.accountKey||this.hasPendingRevoke(n.bindingId)?[]:this.continuationStore.listConflicts(n.bindingId).map(({vaultHandle:o,...s})=>({...s,sessionEpoch:r.epoch}))}assertHumanBindingIdentity(e,n){if(Fa({bindingId:n.bindingId,session:n.session,workspaceId:n.workspaceId,resolvedRootSegments:n.resolvedRootSegments}),!n.session?.authenticated||n.session.accountKey!==e.accountKey||n.workspaceId!==e.workspaceId||!Do(e.rootSegments,n.resolvedRootSegments))throw new f("APP_SYNC_CONFLICT_BINDING_MISMATCH",404)}requireCurrentSession(e,n){if(!Number.isSafeInteger(n)||n<1)throw new f("APP_SYNC_SESSION_STALE");let r=this.sessionFence.currentToken(e.accountKey);if(!r||this.sessionFence.activeAccountKey!==e.accountKey||r.epoch!==n)throw new f("APP_SYNC_SESSION_STALE");return r}requireHumanOperationBinding(e){let n=this.dependencies.store.getBinding(e.bindingId);if(!n)throw new f("APP_SYNC_CONFLICT_BINDING_MISMATCH",404);return this.assertHumanBindingIdentity(n,e),n}async readConflictArchive(e){let n=this.requireHumanOperationBinding(e),r=this.requireCurrentSession(n,e.expectedSessionEpoch);if(!Po(e.eligibility)||!Yn(n.status))throw new f("DOC_APP_GRANT_REQUIRED",409);let o=this.continuationStore.getConflict(e.conflictId);if(!o)throw new f("APP_SYNC_CONFLICT_NOT_FOUND",404);if(xo(o,n),o.preservationStatus!=="ready"||!o.vaultHandle||o.state==="purging")throw new f("APP_SYNC_CONFLICT_NOT_PRESERVED",409);let s=this.archiveFenceGrant(n,o),i=this.createArchiveFenceContext(n,s,r);try{i.fence.assertCurrent();let a=await this.readVerifiedArchive(o,i);return {conflictId:o.conflictId,localVersion:o.localVersion,localFingerprint:o.localFingerprint,remoteRevision:o.remoteRevision,remoteFingerprint:o.remoteFingerprint,markdown:a}}finally{this.sessionFence.release(i.grantToken);}}async purgeAccountData(e){Ua(e);let n=this.sessionFence.currentToken(e.session.accountKey);if(!n||n.epoch!==e.expectedSessionEpoch||this.sessionFence.activeAccountKey!==e.session.accountKey)throw new f("APP_SYNC_SESSION_STALE");let r=ie(JSON.stringify(e.resolvedRootSegments)),o=this.continuationStore.getAccountDataPurge(e.requestId);if(o&&(o.bindingId!==e.bindingId||o.accountKey!==e.session.accountKey||o.workspaceId!==e.workspaceId||o.rootFingerprint!==r||o.humanIdentity!==e.humanIdentity))throw new f("APP_SYNC_PURGE_REQUEST_ID_REUSED",409);let s=this.dependencies.store.getBinding(e.bindingId);if(!s){if(o?.state==="complete")return {requestId:e.requestId,status:"purged",remainingArchiveCount:0};throw new f("APP_SYNC_CONFLICT_BINDING_MISMATCH",404)}this.assertHumanBindingIdentity(s,e);let i=this.requireCurrentSession(s,e.expectedSessionEpoch);if(this.hasPendingRevoke(s.bindingId))throw new f("APP_SYNC_REVOKE_PENDING",409);let a=this.purgeFenceGrant(s),c={allowNonTransferStatus:true,purgeRequestId:e.requestId},u=this.createArchiveFenceContext(s,a,i,c),p=u;try{this.continuationStore.beginAccountDataPurge({requestId:e.requestId,binding:s,humanIdentity:e.humanIdentity,fence:u.fence,now:this.now()}),s.grantId&&s.grantGeneration&&this.sessionFence.cancelGrant(s.accountKey,s.grantId,s.grantGeneration),this.sessionFence.release(u.grantToken),p=this.createArchiveFenceContext(s,a,i,c);let g=this.continuationStore.listConflicts(s.bindingId);for(let _ of g)try{p.fence.assertCurrent();let S=_.state==="purging"?_:this.continuationStore.markConflictPurging({conflictId:_.conflictId,fence:p.fence,now:this.now()});S.vaultHandle&&(await this.continuation.conflictVault.remove({accountKey:s.accountKey,handle:S.vaultHandle,fence:p.fence}),p.fence.assertCurrent()),this.continuationStore.deletePurgedConflict({conflictId:S.conflictId,expectedVaultHandle:S.vaultHandle,fence:p.fence,now:this.now()});}catch(S){if(!this.isFenceCurrent(p))throw S;let w=this.continuationStore.listConflicts(s.bindingId).length;return {requestId:e.requestId,status:"cleanup_pending",remainingArchiveCount:w}}return this.continuationStore.finishAccountDataPurge({requestId:e.requestId,binding:s,fence:p.fence,now:this.now()}),{requestId:e.requestId,status:"purged",remainingArchiveCount:0}}finally{this.sessionFence.release(u.grantToken),p!==u&&this.sessionFence.release(p.grantToken);}}async resolveConflict(e){qa(e);let n=this.dependencies.store.getBinding(e.bindingId);if(!n)throw new f("APP_SYNC_CONFLICT_BINDING_MISMATCH");this.assertHumanBindingIdentity(n,e);let r=this.requireCurrentSession(n,e.expectedSessionEpoch);if(!Po(e.eligibility)||!Yn(n.status))throw new f("DOC_APP_GRANT_REQUIRED",409);if(!n.grantId||!n.grantGeneration||!n.scopeVersion||n.status==="revoked"||n.status==="stopping"||n.status==="unavailable")throw new f("DOC_APP_GRANT_REQUIRED",409);if(this.hasPendingRevoke(n.bindingId))throw new f("APP_SYNC_REVOKE_PENDING");let o=Jn(n);if(r.epoch!==e.expectedSessionEpoch||this.sessionFence.activeAccountKey!==n.accountKey)throw new f("APP_SYNC_SESSION_STALE");let s=this.sessionFence.captureGrant(r,o.grantId,o.generation),i=this.createFenceContext(n,o,r,s);try{i.fence.assertCurrent();let a=this.continuationStore.getConflict(e.conflictId);if(!a)throw new f("APP_SYNC_CONFLICT_NOT_FOUND",404);if(xo(a,n),a.state==="purging")throw new f("APP_SYNC_CONFLICT_PURGING",409);if(!(a.state==="superseded"&&e.choice==="keep_both")&&!await this.readActiveGrant(i))throw new f("DOC_APP_GRANT_STALE",409);if(a.state==="resolved"||a.state==="kept_both"){if(a.resolutionRequestId!==e.requestId||a.resolutionChoice!==e.choice)throw new f("APP_SYNC_CONFLICT_ALREADY_RESOLVED",409);return this.cleanupResolvedConflict(a,i)}if(a.preservationStatus!=="ready"||!a.vaultHandle)throw new f("APP_SYNC_CONFLICT_NOT_PRESERVED",409);this.continuationStore.beginConflictResolution({conflictId:a.conflictId,requestId:e.requestId,humanIdentity:e.humanIdentity,choice:e.choice,expectedLocalVersion:e.expectedLocalVersion,expectedRemoteRevision:e.expectedRemoteRevision,expectedRemoteFingerprint:e.expectedRemoteFingerprint,fence:i.fence,now:this.now()});let u=await this.applyHumanResolution(e,a,i);if(u.status==="stale")throw this.continuationStore.abortConflictResolution({conflictId:a.conflictId,requestId:e.requestId,state:"stale",errorCode:"APP_SYNC_CONFLICT_STALE",fence:i.fence,now:this.now()}),u.refreshed?await this.preserveConflict(Xn(i,a.ref,u.refreshed.remote.docId,u.refreshed.remote),u.refreshed.local,u.refreshed.remote,i):await this.refreshConflictAfterStale(a,i),new f("APP_SYNC_CONFLICT_STALE",409);let p=this.continuationStore.finishConflictResolution({conflictId:a.conflictId,requestId:e.requestId,choice:e.choice,fence:i.fence,now:this.now()});return this.cleanupResolvedConflict(p,i)}catch(a){if(this.isFenceCurrent(i)){let c=this.continuationStore.getConflict(e.conflictId);c?.state==="resolving"&&c.resolutionRequestId===e.requestId&&(Me(a)==="APP_SYNC_CONFLICT_RESOLUTION_UNKNOWN"?this.continuationStore.markConflictResolutionUnknown({conflictId:e.conflictId,requestId:e.requestId,fence:i.fence,now:this.now()}):$a(a)||this.continuationStore.abortConflictResolution({conflictId:e.conflictId,requestId:e.requestId,state:"failed",errorCode:zn(a),fence:i.fence,now:this.now()}));}throw a}finally{this.sessionFence.release(s);}}async dispatchReattachCreation(e,n,r,o,s){if(!o.documentId||o.operationKind!=="reattach"||o.bindingId!==e.bindingId||o.accountKey!==e.accountKey||o.grantId!==n.grantId||o.grantGeneration!==n.generation){this.dependencies.store.updateCreation(o.jobId,{status:"invalidated",nextAttemptAt:0,now:this.now()});return}if(this.hasPendingRevoke(e.bindingId)||!this.sessionFence.isCurrent(r))return;if(this.dependencies.createLedger)try{let u=this.dependencies.createLedger.peek(e.accountKey,this.now());if(!u.available||u.remaining<1)return}catch(u){this.dependencies.onAdapterError?.(u);return}let i=this.dependencies.store.claimCreation(o.jobId,this.now(),La);if(!i)return;let a=this.sessionFence.captureGrant(r,n.grantId,n.generation),c=this.createFenceContext(e,n,r,a);try{if(this.dependencies.store.hasDeletedRef(e.accountKey,T,ie(o.ref))){this.dependencies.store.updateCreation(o.jobId,{status:"deleted",nextAttemptAt:0,now:this.now()});return}let u=await this.readRemoteDocument(o.documentId,c);if(L(u.markdown)!==o.fingerprint||u.markdownVersion!==o.fingerprint||!this.scopeRegistry.validateFrontMatter(o.ref,u.markdown).valid){this.dependencies.store.updateCreation(o.jobId,{status:"conflict",nextAttemptAt:0,now:this.now()}),this.markPendingForReconcile(e,n,o.ref,c,"DOC_SYNC_REMOTE_STATE_MISMATCH");return}if(u.appGrantId===n.grantId&&u.appGrantGeneration===n.generation){this.dependencies.store.updateCreation(o.jobId,{status:"completed",nextAttemptAt:0,now:this.now()}),this.markReattached(e,n,o.ref,c);return}let p=await this.dependencies.creationBudget.runCreate({accountKey:e.accountKey,signal:a.signal,dispatch:async()=>{c.fence.assertCurrent();let S=await this.readRemoteDocument(o.documentId,c);if(L(S.markdown)!==o.fingerprint||S.markdownVersion!==o.fingerprint||!this.scopeRegistry.validateFrontMatter(o.ref,S.markdown).valid)return {kind:"changed"};let w=this.dependencies.createLedger?Mt({ledger:this.dependencies.createLedger,accountKey:e.accountKey,requestId:o.requestId,source:"app_reattach",now:this.now,guard:()=>{if(c.fence.assertCurrent(),this.hasPendingRevoke(e.bindingId))throw new f("APP_SYNC_REVOKE_PENDING")}}):void 0,R;try{R=await this.dependencies.remote.createGrantedDocument({accountKey:e.accountKey,appId:T,ref:o.ref,requestId:o.requestId,markdown:S.markdown,appVersion:s.appVersion,appGrant:{grantId:n.grantId,generation:n.generation},signal:a.signal,fence:c.fence,...w?{dispatchGate:w}:{}});}catch(E){if(E instanceof Ge)return {kind:"budget_deferred",retryAt:E.retryAt};throw E}if(w&&w.calls===0){let E=new f("APP_SYNC_DISPATCH_GATE_NOT_CALLED");try{this.dependencies.createLedger.reserveForced({accountKey:e.accountKey,requestId:o.requestId,source:"app_reattach",now:this.now()});}catch(I){this.dependencies.onAdapterError?.(I);}throw this.dependencies.onAdapterError?.(E),E}return c.fence.assertCurrent(),{kind:"created",created:R}}});if(c.fence.assertCurrent(),p.status==="deferred"){let S=this.now();return this.deferClaim(i,p.retryAt,S),void 0}if(p.value.kind==="budget_deferred"){let S=this.now();return this.deferClaim(i,p.value.retryAt,S),void 0}if(p.value.kind==="changed"){this.dependencies.store.updateCreation(o.jobId,{status:"conflict",nextAttemptAt:0,now:this.now()}),this.markPendingForReconcile(e,n,o.ref,c,"DOC_SYNC_REMOTE_STATE_MISMATCH");return}let g=p.value.created;if(g.docId!==o.documentId||g.appGrantId!==n.grantId||g.appGrantGeneration!==n.generation||g.markdownVersion!==o.fingerprint){this.dependencies.store.updateCreation(o.jobId,{status:"conflict",nextAttemptAt:0,now:this.now()}),this.markPendingForReconcile(e,n,o.ref,c,"DOC_SYNC_REMOTE_STATE_MISMATCH");return}let _=await this.readRemoteDocument(o.documentId,c);if(_.appGrantId!==n.grantId||_.appGrantGeneration!==n.generation||_.markdownVersion!==o.fingerprint||L(_.markdown)!==o.fingerprint){this.dependencies.store.updateCreation(o.jobId,{status:"conflict",nextAttemptAt:0,now:this.now()}),this.markPendingForReconcile(e,n,o.ref,c,"DOC_SYNC_REMOTE_STATE_MISMATCH");return}this.dependencies.store.updateCreation(o.jobId,{status:"completed",nextAttemptAt:0,now:this.now()}),this.markReattached(e,n,o.ref,c);}catch(u){if(!this.isFenceCurrent(c))return;if(pt(u)){this.dependencies.store.updateCreation(o.jobId,{status:"waiting",nextAttemptAt:this.now()+6e4,now:this.now()});return}let p=Ha(u);this.dependencies.store.updateCreation(o.jobId,{status:p?"waiting":"failed",nextAttemptAt:p?this.now()+Math.min(1e3*2**Math.min(i.attempts,10),3e5):0,now:this.now()}),p&&this.markPendingForReconcile(e,n,o.ref,c,"APP_SYNC_REATTACH_RESPONSE_UNKNOWN");}finally{this.sessionFence.release(a);}}deferClaim(e,n,r){let o=this.dependencies.store;if(this.dependencies.createLedger){if(!o.deferCreation)throw new Error("APP_SYNC_DISPATCH_LEDGER_STORE_UNSUPPORTED");return o.deferCreation(e,n,r)}return o.updateCreation(e.jobId,{status:"waiting",nextAttemptAt:n,now:r}),true}async traverseWithCursorRecovery(e){let n=0;for(;;)try{return await this.traverseGrantDocs(e),await this.traverseDeletedRefs(e),!0}catch(r){if(!Ba(r))throw r;let o=await this.readActiveGrant(e);if(this.continuationStore.resetDiscoveryCycle({binding:e.binding,fence:e.fence,now:this.now()}),!o)return false;if(n+=1,n>1)throw r}}async traverseGrantDocs(e){let n=this.dependencies.remote.listGrantDocs;if(!n)throw new Error("APP_SYNC_CONTINUATION_PORT_REQUIRED");let r=new Set,o=0;for(;;){e.fence.assertCurrent();let s=this.continuationStore.getDiscoveryCheckpoint(e.binding.bindingId);if(!s||s.docsComplete)return;let i=s.docsCursor;if(i!==null){if(r.has(i))throw new f("DOC_APP_CURSOR_INVALID",400);r.add(i);}let a=await n.call(this.dependencies.remote,{accountKey:e.binding.accountKey,appId:T,grantId:e.grant.grantId,generation:e.grant.generation,cursor:i,limit:this.pageSize,signal:e.fence.signal,fence:e.fence});if(e.fence.assertCurrent(),this.validateGrantDocsPage(a,e),a.items.length>this.pageSize)throw new f("APP_SYNC_DOCS_PAGE_INVALID");if(a.nextCursor!==null&&r.has(a.nextCursor))throw new f("DOC_APP_CURSOR_INVALID",400);if(o+=1,o>vo)throw new f("APP_SYNC_DOCS_TRAVERSAL_LIMIT");this.continuationStore.commitGrantDocsPage({binding:e.binding,fence:e.fence,items:a.items,expectedCursor:i,nextCursor:a.nextCursor,now:this.now()});}}async traverseDeletedRefs(e){let n=this.dependencies.remote.listDeletedRefs;if(!n)throw new Error("APP_SYNC_CONTINUATION_PORT_REQUIRED");let r=new Set,o=0;for(;;){e.fence.assertCurrent();let s=this.continuationStore.getDiscoveryCheckpoint(e.binding.bindingId);if(!s||s.deletedComplete)return;let i=s.deletedCursor;if(i!==null){if(r.has(i))throw new f("DOC_APP_CURSOR_INVALID",400);r.add(i);}let a=await n.call(this.dependencies.remote,{accountKey:e.binding.accountKey,appId:T,grantId:e.grant.grantId,generation:e.grant.generation,cursor:i,limit:this.pageSize,signal:e.fence.signal,fence:e.fence});if(e.fence.assertCurrent(),this.validateDeletedRefsPage(a,e),a.items.length>this.pageSize)throw new f("APP_SYNC_DELETED_REFS_PAGE_INVALID");if(a.nextCursor!==null&&r.has(a.nextCursor))throw new f("DOC_APP_CURSOR_INVALID",400);if(o+=1,o>vo)throw new f("APP_SYNC_DELETED_REFS_TRAVERSAL_LIMIT");this.continuationStore.commitDeletedRefsPage({binding:e.binding,fence:e.fence,items:a.items,expectedCursor:i,nextCursor:a.nextCursor,now:this.now()});}}validateGrantDocsPage(e,n){if(!e||e.appId!==T||e.grantId!==n.grant.grantId||e.generation!==n.grant.generation||e.scopeVersion!==n.grant.scopeVersion||!dn(e.listedAt)||!Array.isArray(e.items)||!(e.nextCursor===null||typeof e.nextCursor=="string"&&e.nextCursor.length<=512))throw new f("APP_SYNC_DOCS_PAGE_INVALID");let r=new Set;for(let o of e.items){if(!Y(o.docId,128)||!Y(o.title,80)||!Number.isSafeInteger(o.currentRevision)||o.currentRevision<0||!/^sha256:[0-9a-f]{64}$/.test(o.markdownVersion)||!Number.isSafeInteger(o.appGrantGeneration)||o.appGrantGeneration<1||o.appGrantGeneration>n.grant.generation||typeof o.needsReattach!="boolean"||!dn(o.updatedAt)||!this.scopeRegistry.validateRef(o.ref).valid||r.has(o.ref))throw new f("APP_SYNC_DOCS_PAGE_INVALID");if(!o.needsReattach&&o.appGrantGeneration!==n.grant.generation)throw new f("APP_SYNC_DOCS_PAGE_INVALID");r.add(o.ref);}}validateDeletedRefsPage(e,n){if(!e||e.appId!==T||e.grantId!==n.grant.grantId||e.generation!==n.grant.generation||!dn(e.listedAt)||!Array.isArray(e.items)||!(e.nextCursor===null||typeof e.nextCursor=="string"&&e.nextCursor.length<=512))throw new f("APP_SYNC_DELETED_REFS_PAGE_INVALID");let r=new Set;for(let o of e.items){if(!/^[0-9a-f]{64}$/.test(o.refHash)||!dn(o.deletedAt)||r.has(o.refHash))throw new f("APP_SYNC_DELETED_REFS_PAGE_INVALID");r.add(o.refHash);}}async readActiveGrant(e){e.fence.assertCurrent();let n=await this.dependencies.remote.readGrant({accountKey:e.binding.accountKey,appId:T,signal:e.fence.signal,fence:e.fence});return e.fence.assertCurrent(),n.appId!==T||n.available!==true||n.status!=="active"||!n.grant?false:n.grant.grantId===e.grant.grantId&&n.grant.generation===e.grant.generation&&n.grant.scopeVersion===e.grant.scopeVersion&&this.scopeRegistry.matchesDefinition(n.grant.scopeVersion,n.grant.scope)}async processPendingDiscoveries(e){let n=this.continuationStore.listPendingDiscoveries(e.binding.bindingId,e.grant.grantId,e.grant.generation,500);for(let r of n){if(!this.isFenceCurrent(e))return;try{this.continuationStore.updatePendingDiscovery({bindingId:r.bindingId,grantId:r.grantId,generation:r.grantGeneration,ref:r.ref,fence:e.fence,patch:{status:"processing",errorCode:null},now:this.now()});let o=await this.reconcileDiscoveredDocument(r,e);if(o==="complete")this.continuationStore.completePendingDiscovery({bindingId:r.bindingId,grantId:r.grantId,generation:r.grantGeneration,ref:r.ref,fence:e.fence});else if(o==="retry")this.continuationStore.updatePendingDiscovery({bindingId:r.bindingId,grantId:r.grantId,generation:r.grantGeneration,ref:r.ref,fence:e.fence,patch:{status:"waiting",attempts:r.attempts+1},now:this.now()});else {this.continuationStore.updatePendingDiscovery({bindingId:r.bindingId,grantId:r.grantId,generation:r.grantGeneration,ref:r.ref,fence:e.fence,patch:{status:"waiting",errorCode:"DOC_APP_GRANT_REQUIRED"},now:this.now()});return}}catch(o){if(!this.isFenceCurrent(e))return;if(pt(o)){this.continuationStore.updatePendingDiscovery({bindingId:r.bindingId,grantId:r.grantId,generation:r.grantGeneration,ref:r.ref,fence:e.fence,patch:{status:"waiting",errorCode:zn(o)},now:this.now()});return}this.continuationStore.updatePendingDiscovery({bindingId:r.bindingId,grantId:r.grantId,generation:r.grantGeneration,ref:r.ref,fence:e.fence,patch:{status:"waiting",errorCode:zn(o),needsReconcile:true,attempts:r.attempts+1},now:this.now()});}}}async reconcileDiscoveredDocument(e,n){if(n.fence.assertCurrent(),this.dependencies.store.hasDeletedRef(n.binding.accountKey,T,ie(e.ref)))return "complete";let r=await this.inspectLocal(e.ref,n),o=this.continuationStore.listConflicts(n.binding.bindingId).filter(R=>R.accountKey===n.binding.accountKey&&R.ref===e.ref);if(r.exists){if(o.some(I=>I.state==="kept_both"&&I.localVersion===r.localVersion&&I.localFingerprint===r.localFingerprint))return "complete";let E=o.find(I=>(I.state==="open"||I.state==="resolving")&&I.preservationStatus==="ready"&&I.vaultHandle!==null&&I.localVersion===r.localVersion&&I.localFingerprint===r.localFingerprint&&I.documentId===e.docId&&I.remoteRevision===e.listedRevision&&I.remoteFingerprint===e.listedFingerprint);if(E)return E.state==="open"&&(E.grantId!==n.grant.grantId||E.grantGeneration!==n.grant.generation||E.needsReattach!==e.needsReattach)&&this.continuationStore.rebindConflict({conflictId:E.conflictId,grant:n.grant,needsReattach:e.needsReattach,fence:n.fence,now:this.now()}),"complete"}let s=r.baseline,i=s!==null&&r.exists&&r.localFingerprint!==s.markdownVersion,a=s!==null&&(e.listedRevision!==s.revision||e.listedFingerprint!==s.markdownVersion);if(s&&!e.needsReconcile&&!e.needsReattach&&r.exists&&!a&&!i)return "complete";if(s&&!e.needsReconcile&&!e.needsReattach&&r.exists&&!a&&i)return this.applyConditionalSave(e.ref,e.docId,r,e.listedRevision,e.listedFingerprint,false,n);let c=await this.readPendingDocument(e,n);if(!c)return "complete";let u=c,p=e;if(e.needsReattach){let R=await this.queueOrConfirmReattachment(e,c,n);if(!R)return "retry";u=R.document,p=R.pending;}let g=await this.inspectLocal(e.ref,n);if(g.exists&&g.localFingerprint===u.markdownVersion){let R={kind:"attach_equal",binding:n.binding,grant:n.grant,ref:e.ref,document:u,expectedLocalVersion:g.localVersion,expectedLocalFingerprint:g.localFingerprint,fence:n.fence},E=await this.applyEffect(R,n);if(E.status==="applied")return this.recordOutcome(n,e.ref,g.localFingerprint,u.markdownVersion,u.docId,"synced",null),"complete";if(E.status==="stale_local")return this.reconcileAfterLocalRace(p,u,n);if(E.status==="conflict")return this.preserveConflict(p,await this.inspectLocal(e.ref,n),u,n);if(E.status==="deferred"||E.status==="failed")return "retry"}let _=g.baseline??s;if(!g.exists){let R={kind:"create_absent",binding:n.binding,grant:n.grant,ref:e.ref,document:u,expectedLocalVersion:null,fence:n.fence},E=await this.applyEffect(R,n);return E.status==="applied"?(this.recordOutcome(n,e.ref,u.markdownVersion,u.markdownVersion,u.docId,"synced",null),"complete"):E.status==="stale_local"?this.reconcileAfterLocalRace(p,u,n):E.status==="conflict"?this.preserveConflict(p,await this.inspectLocal(e.ref,n),u,n):"retry"}if(!_)return this.preserveConflict(p,g,u,n);let S=g.localFingerprint!==_.markdownVersion,w=u.currentRevision!==_.revision||u.markdownVersion!==_.markdownVersion;if(S&&w)return this.preserveConflict(p,g,u,n);if(w&&!S){let R={kind:"cas_pull",binding:n.binding,grant:n.grant,ref:e.ref,document:u,expectedLocalVersion:g.localVersion,fence:n.fence},E=await this.applyEffect(R,n);return E.status==="applied"?(this.recordOutcome(n,e.ref,u.markdownVersion,u.markdownVersion,u.docId,"synced",null),"complete"):E.status==="stale_local"?this.reconcileAfterLocalRace(p,u,n):E.status==="conflict"?this.preserveConflict(p,await this.inspectLocal(e.ref,n),u,n):"retry"}return S&&!w?this.applyConditionalSave(e.ref,u.docId,g,u.currentRevision,u.markdownVersion,p.needsReattach,n):"complete"}async inspectLocal(e,n){n.fence.assertCurrent();let r=this.dependencies.documents.inspectContinuation;if(!r)throw new Error("APP_SYNC_CONTINUATION_PORT_REQUIRED");let o=await r({binding:n.binding,grant:n.grant,ref:e,fence:n.fence});if(n.fence.assertCurrent(),!o||typeof o.exists!="boolean")throw new f("APP_SYNC_LOCAL_INSPECTION_INVALID");if(o.exists){if(!Qn(o.localVersion)||!/^sha256:[0-9a-f]{64}$/.test(o.localFingerprint)||L(o.markdown)!==o.localFingerprint||!this.scopeRegistry.validateFrontMatter(e,o.markdown).valid)throw new f("APP_SYNC_LOCAL_STATE_INVALID")}else if(o.localVersion!==null||o.localFingerprint!==null||o.markdown!==null)throw new f("APP_SYNC_LOCAL_INSPECTION_INVALID");if(o.baseline&&(!Number.isSafeInteger(o.baseline.revision)||o.baseline.revision<0||!/^sha256:[0-9a-f]{64}$/.test(o.baseline.markdownVersion)))throw new f("APP_SYNC_BASELINE_INVALID");return o}async readPendingDocument(e,n){n.fence.assertCurrent();try{let r=await this.dependencies.remote.readDocument({accountKey:n.binding.accountKey,docId:e.docId,signal:n.fence.signal,fence:n.fence});return n.fence.assertCurrent(),this.validateRemoteDocument(r,e,n),r}catch(r){if(n.fence.assertCurrent(),Me(r)==="DOC_NOT_FOUND"&&Lo(r)===404)return this.continuationStore.recordKnownDeletion({binding:n.binding,grant:n.grant,ref:e.ref,refHash:ie(e.ref),documentId:e.docId,fence:n.fence,now:this.now()}),null;throw r}}validateRemoteDocument(e,n,r){if(!e||e.docId!==n.docId||!Number.isSafeInteger(e.currentRevision)||e.currentRevision<0||!/^sha256:[0-9a-f]{64}$/.test(e.markdownVersion)||L(e.markdown)!==e.markdownVersion||!Y(e.appGrantId,128)||!Number.isSafeInteger(e.appGrantGeneration)||e.appGrantGeneration<1||!this.scopeRegistry.validateFrontMatter(n.ref,e.markdown).valid)throw new f("DOC_SYNC_REMOTE_STATE_MISMATCH",409);let o=e.appGrantId===r.grant.grantId&&e.appGrantGeneration===r.grant.generation,s=e.appGrantGeneration===n.appGrantGeneration&&e.appGrantGeneration<=r.grant.generation;if(!o&&!(n.needsReattach&&s))throw new f("DOC_APP_GRANT_STALE",409)}async queueOrConfirmReattachment(e,n,r){if(n.appGrantId===r.grant.grantId&&n.appGrantGeneration===r.grant.generation){this.markReattached(r.binding,r.grant,e.ref,r,n);let a=this.continuationStore.getPendingDiscovery(e.bindingId,e.grantId,e.grantGeneration,e.ref)??{...e,needsReattach:false,appGrantGeneration:r.grant.generation};return {document:n,pending:a}}if(this.continuationStore.enqueueReattachJob({binding:r.binding,grant:r.grant,ref:e.ref,documentId:n.docId,fingerprint:n.markdownVersion,requestId:this.createId(),jobId:this.createId(),now:this.now(),fence:r.fence}).status!=="completed")return this.continuationStore.updatePendingDiscovery({bindingId:e.bindingId,grantId:e.grantId,generation:e.grantGeneration,ref:e.ref,fence:r.fence,patch:{status:"waiting",errorCode:"APP_SYNC_REATTACH_PENDING",needsReconcile:true},now:this.now()}),null;let s=await this.readRemoteDocument(n.docId,r);if(s.appGrantId!==r.grant.grantId||s.appGrantGeneration!==r.grant.generation)return null;if(L(s.markdown)!==s.markdownVersion||!this.scopeRegistry.validateFrontMatter(e.ref,s.markdown).valid)throw new f("DOC_SYNC_REMOTE_STATE_MISMATCH",409);this.markReattached(r.binding,r.grant,e.ref,r,s);let i=this.continuationStore.getPendingDiscovery(e.bindingId,e.grantId,e.grantGeneration,e.ref)??{...e,needsReattach:false,appGrantGeneration:r.grant.generation};return {document:s,pending:i}}markReattached(e,n,r,o,s){this.continuationStore.getPendingDiscovery(e.bindingId,n.grantId,n.generation,r)&&this.continuationStore.updatePendingDiscovery({bindingId:e.bindingId,grantId:n.grantId,generation:n.generation,ref:r,fence:o.fence,patch:{needsReattach:false,needsReconcile:true,...s?{listedRevision:s.currentRevision,listedFingerprint:s.markdownVersion}:{},appGrantGeneration:n.generation,status:"waiting",errorCode:null},now:this.now()});}markPendingForReconcile(e,n,r,o,s){!this.continuationStore.getPendingDiscovery(e.bindingId,n.grantId,n.generation,r)||!this.isFenceCurrent(o)||this.continuationStore.updatePendingDiscovery({bindingId:e.bindingId,grantId:n.grantId,generation:n.generation,ref:r,fence:o.fence,patch:{status:"waiting",needsReconcile:true,errorCode:s},now:this.now()});}async applyConditionalSave(e,n,r,o,s,i,a){let c={kind:"conditional_save",binding:a.binding,grant:a.grant,ref:e,documentId:n,expectedLocalVersion:r.localVersion,expectedRemoteRevision:o,expectedRemoteFingerprint:s,markdown:r.markdown,markdownFingerprint:r.localFingerprint,needsReattach:i,fence:a.fence,beforeDispatch:async()=>{if(a.fence.assertCurrent(),this.dependencies.store.hasDeletedRef(a.binding.accountKey,T,ie(e)))return {ok:false,reason:"deleted"};let S=await this.inspectLocal(e,a);return !S.exists||S.localVersion!==r.localVersion||S.localFingerprint!==r.localFingerprint?{ok:false,reason:"stale"}:(a.fence.assertCurrent(),{ok:true,localVersion:S.localVersion,markdown:S.markdown,fingerprint:S.localFingerprint})}},u;try{u=await this.applyEffect(c,a);}catch(S){throw this.isFenceCurrent(a)&&!pt(S)&&this.markPendingForReconcile(a.binding,a.grant,e,a,"APP_SYNC_SAVE_RESPONSE_UNKNOWN"),S}if(u.status==="applied")return this.recordOutcome(a,e,r.localFingerprint,r.localFingerprint,n,"synced",null),"complete";if(u.status==="deferred"||u.status==="failed")return u.dispatch==="attempted"&&this.markPendingForReconcile(a.binding,a.grant,e,a,"APP_SYNC_SAVE_RESPONSE_UNKNOWN"),"retry";let p=this.continuationStore.getPendingDiscovery(a.binding.bindingId,a.grant.grantId,a.grant.generation,e),g=await this.readRemoteById(n,p,a);if(!g)return "complete";let _=await this.inspectLocal(e,a);if(u.status==="conflict"||_.exists&&_.localFingerprint!==g.markdownVersion)return this.preserveConflict(p??Xn(a,e,n,g),_,g,a);if(_.exists&&_.localFingerprint===g.markdownVersion){let S={kind:"attach_equal",binding:a.binding,grant:a.grant,ref:e,document:g,expectedLocalVersion:_.localVersion,expectedLocalFingerprint:_.localFingerprint,fence:a.fence};return (await this.applyEffect(S,a)).status==="applied"?(this.recordOutcome(a,e,_.localFingerprint,g.markdownVersion,n,"synced",null),"complete"):"retry"}return "retry"}async applyEffect(e,n){n.fence.assertCurrent();let r=this.dependencies.documents.applyContinuation;if(!r)throw new Error("APP_SYNC_CONTINUATION_PORT_REQUIRED");let o=false,s;if(e.kind==="conditional_save"){let i={...e,beforeDispatch:async()=>{o=true;let a=await e.beforeDispatch();return n.fence.assertCurrent(),a}};if(s=await r(i),s.dispatch==="attempted"&&!o)throw new f("APP_SYNC_ADAPTER_DID_NOT_REVALIDATE");if((s.status==="applied"||s.status==="conflict")&&s.dispatch!=="attempted")throw new f("APP_SYNC_ADAPTER_DID_NOT_DISPATCH")}else s=await r(e);return n.fence.assertCurrent(),s}async reconcileAfterLocalRace(e,n,r){let o=await this.inspectLocal(e.ref,r);if(!o.exists){let s={kind:"create_absent",binding:r.binding,grant:r.grant,ref:e.ref,document:n,expectedLocalVersion:null,fence:r.fence};return (await this.applyEffect(s,r)).status==="applied"?(this.recordOutcome(r,e.ref,n.markdownVersion,n.markdownVersion,n.docId,"synced",null),"complete"):"retry"}if(o.localFingerprint===n.markdownVersion){let s={kind:"attach_equal",binding:r.binding,grant:r.grant,ref:e.ref,document:n,expectedLocalVersion:o.localVersion,expectedLocalFingerprint:o.localFingerprint,fence:r.fence};return (await this.applyEffect(s,r)).status==="applied"?(this.recordOutcome(r,e.ref,o.localFingerprint,n.markdownVersion,n.docId,"synced",null),"complete"):"retry"}return this.preserveConflict(e,o,n,r)}async preserveConflict(e,n,r,o){if(!n.exists)return "retry";let s=o.fence.rootFingerprint,i=`c_${ie(JSON.stringify([o.binding.bindingId,o.grant.grantId,o.grant.generation,e.ref,n.localVersion,r.currentRevision,r.markdownVersion]))}`,a={conflictId:i,bindingId:o.binding.bindingId,accountKey:o.binding.accountKey,workspaceId:o.binding.workspaceId,rootFingerprint:s,grantId:o.grant.grantId,grantGeneration:o.grant.generation,scopeVersion:o.grant.scopeVersion,ref:e.ref,documentId:r.docId,localVersion:n.localVersion,localFingerprint:n.localFingerprint,baselineRevision:n.baseline?.revision??null,baselineFingerprint:n.baseline?.markdownVersion??null,remoteRevision:r.currentRevision,remoteFingerprint:r.markdownVersion,needsReattach:e.needsReattach,vaultHandle:null,preservationStatus:"pending",state:"open",supersededBy:null,resolutionRequestId:null,resolutionChoice:null,cleanupPending:false,createdAt:this.now(),updatedAt:this.now()},c=this.continuationStore.putConflict({conflict:a,fence:o.fence});if(this.recordOutcome(o,e.ref,n.localFingerprint,n.baseline?.markdownVersion??null,r.docId,"conflict","APP_SYNC_CONFLICT"),c.preservationStatus==="ready"&&c.vaultHandle)return this.continuationStore.supersedeOpenConflicts({bindingId:o.binding.bindingId,ref:e.ref,supersededBy:i,fence:o.fence,now:this.now()}),"complete";try{o.fence.assertCurrent();let u=await this.continuation.conflictVault.preserve({accountKey:o.binding.accountKey,conflictId:i,markdown:r.markdown,fingerprint:r.markdownVersion,fence:o.fence});if(o.fence.assertCurrent(),!Qn(u.handle)||u.fingerprint!==r.markdownVersion||L(r.markdown)!==u.fingerprint)throw new f("APP_SYNC_CONFLICT_ARCHIVE_VERIFY_FAILED");return c=this.continuationStore.putConflict({conflict:{...a,vaultHandle:u.handle,preservationStatus:"ready",updatedAt:this.now()},fence:o.fence}),c.preservationStatus==="ready"&&this.continuationStore.supersedeOpenConflicts({bindingId:o.binding.bindingId,ref:e.ref,supersededBy:i,fence:o.fence,now:this.now()}),c.preservationStatus==="ready"?"complete":"retry"}catch(u){if(!this.isFenceCurrent(o))throw u;return this.continuationStore.putConflict({conflict:{...a,preservationStatus:"failed",updatedAt:this.now()},fence:o.fence}),this.markPendingForReconcile(o.binding,o.grant,e.ref,o,"APP_SYNC_CONFLICT_ARCHIVE_FAILED"),"retry"}}recordOutcome(e,n,r,o,s,i,a){this.continuationStore.recordContinuationOutcome({binding:e.binding,grant:e.grant,ref:n,sourceFingerprint:r,syncedFingerprint:o,documentId:s,status:i,errorCode:a,fence:e.fence,now:this.now()});}async readRemoteById(e,n,r){return n?this.readPendingDocument(n,r):this.readRemoteDocument(e,r)}async readRemoteDocument(e,n){n.fence.assertCurrent();let r=await this.dependencies.remote.readDocument({accountKey:n.binding.accountKey,docId:e,signal:n.fence.signal,fence:n.fence});if(n.fence.assertCurrent(),!r||r.docId!==e||L(r.markdown)!==r.markdownVersion)throw new f("DOC_SYNC_REMOTE_STATE_MISMATCH",409);return r}async applyHumanResolution(e,n,r){if(r.fence.assertCurrent(),n.state==="superseded"&&e.choice==="keep_both"){let R=await this.inspectLocal(n.ref,r);return !R.exists||R.localVersion!==e.expectedLocalVersion||R.localFingerprint!==n.localFingerprint?{status:"stale"}:(await this.readVerifiedArchive(n,r),{status:"resolved"})}let o=await this.readRemoteDocument(n.documentId,r);if(!this.scopeRegistry.validateFrontMatter(n.ref,o.markdown).valid)throw new f("DOC_SYNC_REMOTE_STATE_MISMATCH",409);let s=o.appGrantId===r.grant.grantId&&o.appGrantGeneration===r.grant.generation;if(!s&&(!n.needsReattach||o.appGrantGeneration>=r.grant.generation))throw new f("DOC_APP_GRANT_STALE",409);let i=await this.inspectLocal(n.ref,r);if(!i.exists)return {status:"stale"};let a=o.currentRevision===e.expectedRemoteRevision&&o.markdownVersion===e.expectedRemoteFingerprint,c=o.currentRevision===n.remoteRevision&&o.markdownVersion===n.remoteFingerprint;if(!a||!c)return i.localFingerprint===o.markdownVersion&&e.choice!=="keep_both"?{status:"resolved"}:{status:"stale",refreshed:{local:i,remote:o}};if(!(i.localVersion===e.expectedLocalVersion&&i.localFingerprint===n.localFingerprint))return i.localFingerprint===o.markdownVersion&&e.choice!=="keep_both"?{status:"resolved"}:{status:"stale",refreshed:{local:i,remote:o}};let p=await this.readVerifiedArchive(n,r);if(e.choice==="keep_both")return {status:"resolved"};if(e.choice==="use_cloud"){let R={kind:"cas_pull",binding:r.binding,grant:r.grant,ref:n.ref,document:{...o,markdown:p},expectedLocalVersion:e.expectedLocalVersion,fence:r.fence},E;try{E=await this.applyEffect(R,r);}catch(I){throw pt(I)?I:new f("APP_SYNC_CONFLICT_RESOLUTION_UNKNOWN")}if(E.status==="applied")return {status:"resolved"};if(E.status==="stale_local")return i=await this.inspectLocal(n.ref,r),i.exists&&i.localFingerprint===o.markdownVersion?{status:"resolved"}:{status:"stale",...i.exists?{refreshed:{local:i,remote:o}}:{}};if(E.status==="conflict"){let I=await this.readRemoteDocument(n.documentId,r),Te=await this.inspectLocal(n.ref,r);return {status:"stale",...Te.exists?{refreshed:{local:Te,remote:I}}:{}}}if(E.status==="failed"||E.status==="deferred")throw E.dispatch==="attempted"?new f("APP_SYNC_CONFLICT_RESOLUTION_UNKNOWN"):new f(E.errorCode??"APP_SYNC_CONFLICT_RESOLUTION_FAILED");return {status:"stale",refreshed:{local:i,remote:o}}}if(n.needsReattach||!s){let R=this.continuationStore.enqueueReattachJob({binding:r.binding,grant:r.grant,ref:n.ref,documentId:n.documentId,fingerprint:o.markdownVersion,requestId:this.createId(),jobId:this.createId(),now:this.now(),fence:r.fence}),E={session:e.session,eligibility:e.eligibility,appVersion:e.appVersion};R.status!=="completed"&&await this.dispatchReattachCreation(r.binding,r.grant,r.session,R,E);let I=await this.readRemoteDocument(n.documentId,r);if(I.appGrantId!==r.grant.grantId||I.appGrantGeneration!==r.grant.generation||I.currentRevision!==o.currentRevision||I.markdownVersion!==o.markdownVersion){let Te=await this.inspectLocal(n.ref,r);if(I.currentRevision!==o.currentRevision||I.markdownVersion!==o.markdownVersion)return {status:"stale",...Te.exists?{refreshed:{local:Te,remote:I}}:{}};throw new f("APP_SYNC_REATTACH_PENDING")}}let _=false,S={kind:"conditional_save",binding:r.binding,grant:r.grant,ref:n.ref,documentId:n.documentId,expectedLocalVersion:e.expectedLocalVersion,expectedRemoteRevision:e.expectedRemoteRevision,expectedRemoteFingerprint:e.expectedRemoteFingerprint,markdown:i.markdown,markdownFingerprint:i.localFingerprint,needsReattach:false,fence:r.fence,beforeDispatch:async()=>{_=true,r.fence.assertCurrent();let R=await this.inspectLocal(n.ref,r);return !R.exists||R.localVersion!==e.expectedLocalVersion||R.localFingerprint!==n.localFingerprint?{ok:false,reason:"stale"}:{ok:true,localVersion:R.localVersion,markdown:R.markdown,fingerprint:R.localFingerprint}}},w;try{w=await this.applyEffect(S,r);}catch(R){throw pt(R)?R:_?new f("APP_SYNC_CONFLICT_RESOLUTION_UNKNOWN"):R}if(w.status==="applied")return {status:"resolved"};if(w.status==="conflict"){let R=await this.readRemoteDocument(n.documentId,r),E=await this.inspectLocal(n.ref,r);return {status:"stale",...E.exists?{refreshed:{local:E,remote:R}}:{}}}if(w.status==="stale_local"){let R=await this.readRemoteDocument(n.documentId,r),E=await this.inspectLocal(n.ref,r);return E.exists&&E.localFingerprint===R.markdownVersion?{status:"resolved"}:{status:"stale",...E.exists?{refreshed:{local:E,remote:R}}:{}}}if(w.status==="failed"||w.status==="deferred")throw w.dispatch==="attempted"?new f("APP_SYNC_CONFLICT_RESOLUTION_UNKNOWN"):new f(w.errorCode??"APP_SYNC_CONFLICT_RESOLUTION_FAILED");return {status:"stale",refreshed:{local:i,remote:o}}}async cleanupResolvedConflict(e,n){let r=e;if(this.recordOutcome(n,r.ref,r.resolutionChoice==="use_cloud"?r.remoteFingerprint:r.localFingerprint,r.state==="kept_both"?r.baselineFingerprint:r.resolutionChoice==="use_cloud"?r.remoteFingerprint:r.localFingerprint,r.documentId,r.state==="kept_both"?"conflict":"synced",r.state==="kept_both"?"APP_SYNC_CONFLICT_KEPT_BOTH":null),r.cleanupPending&&r.vaultHandle)try{n.fence.assertCurrent(),await this.continuation.conflictVault.remove({accountKey:n.binding.accountKey,handle:r.vaultHandle,fence:n.fence}),n.fence.assertCurrent(),this.continuationStore.finishConflictArchiveCleanup({conflictId:r.conflictId,fence:n.fence,now:this.now()}),r=this.continuationStore.getConflict(r.conflictId)??r;}catch{}let{vaultHandle:o,...s}=r;return {status:r.state==="kept_both"?"kept_both":"resolved",conflict:{...s,sessionEpoch:n.session.epoch},cleanupPending:r.cleanupPending}}async readVerifiedArchive(e,n){if(e.preservationStatus!=="ready"||!e.vaultHandle)throw new f("APP_SYNC_CONFLICT_NOT_PRESERVED",409);n.fence.assertCurrent();let r=await this.continuation.conflictVault.read({accountKey:n.binding.accountKey,handle:e.vaultHandle,expectedFingerprint:e.remoteFingerprint,fence:n.fence});if(n.fence.assertCurrent(),r.fingerprint!==e.remoteFingerprint||L(r.markdown)!==e.remoteFingerprint||!this.scopeRegistry.validateFrontMatter(e.ref,r.markdown).valid)throw new f("APP_SYNC_CONFLICT_ARCHIVE_VERIFY_FAILED");return r.markdown}async refreshConflictAfterStale(e,n){n.fence.assertCurrent();let r=await this.inspectLocal(e.ref,n),o=await this.readRemoteDocument(e.documentId,n);r.exists&&(r.localVersion===e.localVersion&&r.localFingerprint===e.localFingerprint&&o.docId===e.documentId&&o.currentRevision===e.remoteRevision&&o.markdownVersion===e.remoteFingerprint||await this.preserveConflict(Xn(n,e.ref,o.docId,o),r,o,n));}archiveFenceGrant(e,n){return e.grantId&&e.grantGeneration&&e.scopeVersion===this.scopeRegistry.scopeVersion?Jn(e):{grantId:n.grantId,appId:T,generation:n.grantGeneration,scopeVersion:n.scopeVersion,scope:pe}}purgeFenceGrant(e){if(e.grantId&&e.grantGeneration&&e.scopeVersion===this.scopeRegistry.scopeVersion)return Jn(e);let n=this.continuationStore.listConflicts(e.bindingId)[0];return {grantId:n?.grantId??"account-data-purge",appId:T,generation:n?.grantGeneration??1,scopeVersion:this.scopeRegistry.scopeVersion,scope:pe}}createArchiveFenceContext(e,n,r,o={}){if(n.scopeVersion!==this.scopeRegistry.scopeVersion||!this.sessionFence.isCurrent(r)||r.accountKey!==e.accountKey)throw new f("APP_SYNC_SESSION_STALE");let s=this.sessionFence.captureGrant(r,n.grantId,n.generation),i=ie(JSON.stringify(e.rootSegments)),a;a=Object.freeze({accountKey:e.accountKey,sessionEpoch:r.epoch,bindingId:e.bindingId,workspaceId:e.workspaceId,rootFingerprint:i,grantId:n.grantId,grantGeneration:n.generation,scopeVersion:n.scopeVersion,signal:s.signal,assertCurrent:()=>this.assertArchiveFenceCurrent(e,n,r,s,o)});let c={binding:e,grant:n,session:r,grantToken:s,fence:a};return a.assertCurrent(),c}assertArchiveFenceCurrent(e,n,r,o,s){if(!this.sessionFence.isCurrent(r)||!this.sessionFence.isCurrent(o)||this.sessionFence.activeAccountKey!==e.accountKey||this.sessionFence.activeSessionEpoch!==r.epoch||o.accountKey!==e.accountKey||o.grantId!==n.grantId||o.generation!==n.generation)throw new f("APP_SYNC_SESSION_STALE");if(this.hasPendingRevoke(e.bindingId))throw new f("APP_SYNC_REVOKE_PENDING");let i=this.dependencies.store.getBinding(e.bindingId);if(!i){let a=s.purgeRequestId?this.continuationStore.getAccountDataPurge(s.purgeRequestId):void 0;if(a?.state==="complete"&&a.bindingId===e.bindingId&&a.accountKey===e.accountKey&&a.workspaceId===e.workspaceId&&a.rootFingerprint===ie(JSON.stringify(e.rootSegments)))return;throw new f("APP_SYNC_ROOT_STALE")}if(i.accountKey!==e.accountKey||i.workspaceId!==e.workspaceId||ie(JSON.stringify(i.rootSegments))!==ie(JSON.stringify(e.rootSegments)))throw new f("APP_SYNC_ROOT_STALE");if(i.grantId!==e.grantId||i.grantGeneration!==e.grantGeneration||i.scopeVersion!==e.scopeVersion)throw new f("DOC_APP_GRANT_STALE",409);if(i.status==="stopping")throw new f("APP_SYNC_REVOKE_PENDING",409);if(!s.allowNonTransferStatus&&!Yn(i.status))throw new f("DOC_APP_GRANT_REQUIRED",409);if(i.grantId&&(i.grantId!==n.grantId||i.grantGeneration!==n.generation||i.scopeVersion!==n.scopeVersion))throw new f("DOC_APP_GRANT_STALE",409)}createFenceContext(e,n,r,o){if(!e.grantId||!e.grantGeneration||!e.scopeVersion||e.grantId!==n.grantId||e.grantGeneration!==n.generation||e.scopeVersion!==n.scopeVersion||n.scopeVersion!==this.scopeRegistry.scopeVersion)throw new f("DOC_APP_GRANT_STALE",409);let s=ie(JSON.stringify(e.rootSegments)),i;i=Object.freeze({accountKey:e.accountKey,sessionEpoch:r.epoch,bindingId:e.bindingId,workspaceId:e.workspaceId,rootFingerprint:s,grantId:n.grantId,grantGeneration:n.generation,scopeVersion:n.scopeVersion,signal:o.signal,assertCurrent:()=>this.assertFenceCurrent(e,n,r,o)});let a={binding:e,grant:n,session:r,grantToken:o,fence:i};return i.assertCurrent(),a}assertFenceCurrent(e,n,r,o){if(!this.sessionFence.isCurrent(r)||!this.sessionFence.isCurrent(o)||o.grantId!==n.grantId||o.generation!==n.generation||o.accountKey!==e.accountKey)throw new f("APP_SYNC_SESSION_STALE");if(this.hasPendingRevoke(e.bindingId))throw new f("APP_SYNC_REVOKE_PENDING");let s=this.dependencies.store.getBinding(e.bindingId);if(!s||s.accountKey!==e.accountKey||s.workspaceId!==e.workspaceId||ie(JSON.stringify(s.rootSegments))!==ie(JSON.stringify(e.rootSegments)))throw new f("APP_SYNC_ROOT_STALE");if(s.grantId!==n.grantId||s.grantGeneration!==n.generation||s.scopeVersion!==n.scopeVersion)throw new f("DOC_APP_GRANT_STALE",409);if(s.status==="revoked"||s.status==="stopping"||s.status==="unavailable")throw new f(s.status==="stopping"?"APP_SYNC_REVOKE_PENDING":"DOC_APP_GRANT_REQUIRED",409)}isFenceCurrent(e){try{return e.fence.assertCurrent(),!0}catch{return false}}},Ma=new Set(["AUTH_REQUIRED","UNAUTHENTICATED","TOKEN_EXPIRED","DOC_SCOPE_REQUIRED","DOC_PILOT_NOT_ALLOWED","DOC_APP_GRANT_REQUIRED","DOC_APP_GRANT_STALE","DOC_APP_GRANT_NOT_AVAILABLE","DOC_APP_SCOPE_INVALID","DOC_APP_GRANT_SCOPE_MISMATCH","APP_SYNC_SESSION_STALE","APP_SYNC_ROOT_STALE","APP_SYNC_REVOKE_PENDING"]);function ie(t){return crypto.createHash("sha256").update(t,"utf8").digest("hex")}function Do(t,e){return t.length===e.length&&t.every((n,r)=>n===e[r])}function Y(t,e){return typeof t=="string"&&t.length>0&&t.length<=e&&!t.includes("\0")}function dn(t){if(typeof t!="string"||t.length>40)return false;let e=Date.parse(t);return Number.isFinite(e)&&new Date(e).toISOString()===t}function Qn(t){return typeof t=="string"&&t.length>=1&&t.length<=256&&!t.includes("/")&&!t.includes("\\")&&!t.includes("\0")&&!t.startsWith("~")&&!/^[A-Za-z]:/.test(t)}function Po(t){return t?.featureEnabled===true&&t.ownerAllowlisted===true}function Yn(t){return t==="checking"||t==="syncing"||t==="synced"||t==="partial"}function Fa(t){if(!t||!Y(t.bindingId,128)||!t.session?.authenticated||!t.session.accountKey||!/^[0-9a-f]{64}$/.test(t.session.accountKey)||!Y(t.workspaceId,256)||!Array.isArray(t.resolvedRootSegments)||t.resolvedRootSegments.length<1||t.resolvedRootSegments.length>32||t.resolvedRootSegments.some(e=>!Y(e,128)||e==="."||e===".."||e.includes("/")||e.includes("\\")))throw new f("APP_SYNC_CONFLICT_BINDING_MISMATCH",404)}function Ua(t){if(!t||t.intent!=="device_account_data_deleted"||!Y(t.bindingId,128)||!t.session?.authenticated||!t.session.accountKey||!/^[0-9a-f]{64}$/.test(t.session.accountKey)||!Number.isSafeInteger(t.expectedSessionEpoch)||t.expectedSessionEpoch<1||!Y(t.workspaceId,256)||!Array.isArray(t.resolvedRootSegments)||t.resolvedRootSegments.length<1||t.resolvedRootSegments.length>32||t.resolvedRootSegments.some(e=>!Y(e,128)||e==="."||e===".."||e.includes("/")||e.includes("\\"))||!Y(t.requestId,128)||!/^[0-9a-f]{64}$/.test(t.humanIdentity))throw new f("APP_SYNC_ACCOUNT_DATA_PURGE_INPUT_INVALID",400)}function qa(t){if(!t||!t.session||!Y(t.bindingId,128)||!t.session.authenticated||!t.session.accountKey||!/^[0-9a-f]{64}$/.test(t.session.accountKey)||!Y(t.workspaceId,256)||!Array.isArray(t.resolvedRootSegments)||t.resolvedRootSegments.some(e=>!Y(e,128)||e==="."||e===".."||e.includes("/")||e.includes("\\"))||!Y(t.conflictId,128)||!Y(t.requestId,128)||!/^[0-9a-f]{64}$/.test(t.humanIdentity)||!Y(t.appVersion,128)||!Number.isSafeInteger(t.expectedSessionEpoch)||t.expectedSessionEpoch<1||!["keep_local","use_cloud","keep_both"].includes(t.choice)||!Qn(t.expectedLocalVersion)||!Number.isSafeInteger(t.expectedRemoteRevision)||t.expectedRemoteRevision<0||!/^sha256:[0-9a-f]{64}$/.test(t.expectedRemoteFingerprint))throw new f("APP_SYNC_CONFLICT_RESOLUTION_INPUT_INVALID",400)}function Me(t){return t&&typeof t=="object"&&"code"in t&&typeof t.code=="string"?t.code:t instanceof Error&&/^[A-Z0-9_:-]{1,128}$/.test(t.message)?t.message:"APP_SYNC_OPERATION_FAILED"}function Lo(t){if(t&&typeof t=="object"&&"status"in t&&typeof t.status=="number")return t.status}function pt(t){return Ma.has(Me(t))}function $a(t){return Me(t)==="APP_SYNC_CONFLICT_RESOLUTION_UNKNOWN"||Me(t)==="APP_SYNC_REATTACH_PENDING"}function zn(t){let e=Me(t);return /^[A-Z0-9_:-]{1,128}$/.test(e)?e:"APP_SYNC_OPERATION_FAILED"}function Ha(t){if(pt(t))return false;let e=Lo(t);return e===408||e===409||e===429||e!==void 0&&e>=500||new Set(["ECONNRESET","ECONNREFUSED","ETIMEDOUT","EAI_AGAIN","ENETUNREACH","EHOSTUNREACH","EPIPE","UND_ERR_CONNECT_TIMEOUT","UND_ERR_HEADERS_TIMEOUT","UND_ERR_SOCKET","APP_SYNC_REATTACH_RESPONSE_UNKNOWN","APP_SYNC_SAVE_RESPONSE_UNKNOWN"]).has(Me(t))}function Ba(t){return Me(t)==="DOC_APP_GRANT_STALE"||Me(t)==="DOC_APP_CURSOR_INVALID"}function Jn(t){if(!t.grantId||!t.grantGeneration||!t.scopeVersion)throw new f("DOC_APP_GRANT_REQUIRED",409);return {grantId:t.grantId,appId:T,generation:t.grantGeneration,scopeVersion:t.scopeVersion,scope:pe}}function xo(t,e){if(t.bindingId!==e.bindingId||t.accountKey!==e.accountKey||t.workspaceId!==e.workspaceId||t.rootFingerprint!==ie(JSON.stringify(e.rootSegments))||t.scopeVersion!==Je)throw new f("APP_SYNC_CONFLICT_BINDING_MISMATCH",404)}function Xn(t,e,n,r){return {bindingId:t.binding.bindingId,accountKey:t.binding.accountKey,grantId:t.grant.grantId,grantGeneration:t.grant.generation,ref:e,docId:n,listedRevision:r.currentRevision,listedFingerprint:r.markdownVersion,appGrantGeneration:r.appGrantGeneration,needsReattach:r.appGrantId!==t.grant.grantId||r.appGrantGeneration!==t.grant.generation,needsReconcile:true,status:"waiting",errorCode:null,attempts:0,updatedAt:Date.now()}}var ja=12e4,Wa=1e4,Ka=1e3,Va=15*6e4,Ya=4,Zn=new Set(["DOC_STORAGE_LIMIT_REACHED","DOC_SYNC_LIMIT","DOC_PILOT_NOT_ALLOWED"]),Ft=new Set(["DOC_APP_GRANT_NOT_AVAILABLE","DOC_APP_SCOPE_INVALID","DOC_APP_GRANT_SCOPE_MISMATCH"]),er=new Set(["DOC_APP_GRANT_REQUIRED","DOC_APP_GRANT_STALE"]),un=new Set(["AUTH_REQUIRED","UNAUTHENTICATED","DOC_SCOPE_REQUIRED","TOKEN_EXPIRED"]),za=new Set(["ECONNRESET","ECONNREFUSED","ETIMEDOUT","EAI_AGAIN","ENETUNREACH","EHOSTUNREACH","EPIPE","UND_ERR_CONNECT_TIMEOUT","UND_ERR_HEADERS_TIMEOUT","UND_ERR_SOCKET"]),f=class extends Error{constructor(n,r,o){super(n);this.code=n;this.status=r;this.retryAfterMs=o;this.name="AppSyncRemoteError";}code;status;retryAfterMs},rr=class{constructor(e){this.dependencies=e;if(e.continuation&&e.continuation.store!==e.store)throw new Error("APP_SYNC_CONTINUATION_STORE_MISMATCH");if(e.createLedger&&e.remote.capabilities?.dispatchGate!==true)throw new Error("APP_SYNC_DISPATCH_GATE_UNSUPPORTED");if(e.createLedger&&!e.store.deferCreation)throw new Error("APP_SYNC_DISPATCH_LEDGER_STORE_UNSUPPORTED");this.scopeRegistry=e.scopeRegistry??new Lt,this.sessionFence=e.sessionFence??new xt,this.now=e.now??Date.now,this.createId=e.createId??crypto.randomUUID,this.continuationRuntime=e.continuation?new cn(e,this.scopeRegistry,this.sessionFence,this.now,this.createId,n=>this.hasPendingRevoke(n)):null;}dependencies;scopeRegistry;sessionFence;now;createId;scanRuns=new Map;tickRuns=new Map;remoteReadSemaphore=new sr(Ya);continuationRuntime;scanEpoch=0;get activeSessionEpoch(){return this.sessionFence.activeSessionEpoch}async bind(e){let n=this.requireAuthenticatedAccount(e.session),r=lt(e.resolvedRootSegments);if(!r)throw new Error("APP_SYNC_ROOT_INVALID");if(typeof e.workspaceId!="string"||e.workspaceId.trim().length===0||e.workspaceId.length>256)throw new Error("APP_SYNC_WORKSPACE_INVALID");let o=this.sessionFence.activeAccountKey,s=this.sessionFence.activate(n);o&&o!==n&&await this.suspendBindingsForAccount(o,"account_switch");let i=this.dependencies.store.bind({bindingId:this.createId(),accountKey:n,workspaceId:e.workspaceId,appId:T,rootSegments:r,now:this.now()});return this.isCurrent(s)?(this.hasPendingRevoke(i.bindingId)?await this.holdPendingRevoke(i):this.isEligible(e.eligibility)?this.dependencies.store.updateBinding(i.bindingId,{status:"checking"},this.now()):(this.dependencies.store.updateBinding(i.bindingId,{status:"unavailable"},this.now()),this.sessionFence.suspend(n),await this.dependencies.documents.suspendBinding({binding:i,grantId:i.grantId,generation:i.grantGeneration,reason:"ineligible"})),this.dependencies.store.getBinding(i.bindingId)??i):i}scan(e,n){let r=this.dependencies.store.getBinding(e),o=r!==void 0&&(!n.session.authenticated||!n.session.accountKey||n.session.accountKey!==r.accountKey||!this.isEligible(n.eligibility));o&&(this.scanEpoch+=1,this.sessionFence.suspend(r.accountKey));let s=`${e}:${n.session.accountKey??"signed-out"}:${this.scanEpoch}:${n.eligibility?.featureEnabled===true?1:0}:${n.eligibility?.ownerAllowlisted===true?1:0}`,i=o?void 0:this.scanRuns.get(s);if(i)return i;let a=this.performScan(e,n).finally(()=>{this.scanRuns.get(s)===a&&this.scanRuns.delete(s);});return o||this.scanRuns.set(s,a),a}tick(e,n){let r=this.dependencies.store.getBinding(e);r&&(!n.session.authenticated||n.session.accountKey!==r.accountKey||!this.isEligible(n.eligibility))&&this.sessionFence.suspend(r.accountKey);let o=this.tickRuns.get(e),i=(o?o.catch(()=>{}):Promise.resolve()).then(()=>this.performTick(e,n)).finally(()=>{this.tickRuns.get(e)===i&&this.tickRuns.delete(e);});return this.tickRuns.set(e,i),i}async performTick(e,n){let r=await this.scan(e,n),o=this.dependencies.store.getBinding(e);if(o&&this.hasPendingRevoke(e))return await this.holdPendingRevoke(o),this.snapshot(e);if(!r.binding||!this.isTransferStatus(r.status))return r;let s=this.dependencies.store.getBinding(e);if(!s?.grantId||!s.grantGeneration||!s.scopeVersion)return this.snapshot(e);let i=await this.activateSession(s.accountKey);if(!i||!this.isCurrent(i))return this.snapshot(e);let a=this.grantFromBinding(s),c=this.sessionFence.captureGrant(i,a.grantId,a.generation);try{if(this.continuationRuntime&&await this.continuationRuntime.tick(s,a,i,c,n),this.hasPendingRevoke(e)){let _=this.dependencies.store.getBinding(e);return _&&await this.holdPendingRevoke(_),this.snapshot(e)}if(!this.isCurrent(i)||!this.isCurrent(c))return this.snapshot(e);let u=this.dependencies.store.listResults(e),p=this.dependencies.store.listRunnableCreations(e,a.grantId,a.generation,this.now()),g=this.limitCreationClaims(s.accountKey,p);if(await Promise.all([...u.filter(_=>!this.continuationRuntime&&this.shouldReconcile(_,a)).map(_=>this.reconcileExisting(s,a,c,_)),...g.map(_=>this.dispatchCreation(s,a,i,_,n))]),this.hasPendingRevoke(e)){let _=this.dependencies.store.getBinding(e);return _&&await this.holdPendingRevoke(_),this.snapshot(e)}return !this.isCurrent(i)||!this.isCurrent(c)?this.snapshot(e):(this.refreshBindingStatus(e),this.snapshot(e))}finally{this.sessionFence.release(c);}}limitCreationClaims(e,n){let r=this.dependencies.createLedger;if(!r)return n;try{let o=r.peek(e,this.now());return o.available?n.slice(0,o.remaining):[]}catch(o){return this.dependencies.onAdapterError?.(o),[]}}makeDispatchGate(e){let n=this.dependencies.createLedger;if(n)return Mt({ledger:n,accountKey:e.accountKey,requestId:e.requestId,source:e.source,now:this.now,guard:()=>{if(e.token.signal.aborted||!this.isCurrent(e.token)||!this.bindingHasGrant(e.bindingId,e.grant))throw new f("APP_SYNC_SESSION_STALE");if(this.hasPendingRevoke(e.bindingId))throw new f("APP_SYNC_REVOKE_PENDING")}})}deferClaim(e,n,r){let o=this.dependencies.store;if(this.dependencies.createLedger){if(!o.deferCreation)throw new Error("APP_SYNC_DISPATCH_LEDGER_STORE_UNSUPPORTED");return o.deferCreation(e,n,r)}return o.updateCreation(e.jobId,{status:"waiting",nextAttemptAt:n,now:r}),true}recordMissingDispatchGate(e){let n=new f("APP_SYNC_DISPATCH_GATE_NOT_CALLED");try{this.dependencies.createLedger?.reserveForced({...e,now:this.now()});}catch(r){this.dependencies.onAdapterError?.(r);}return this.dependencies.onAdapterError?.(n),n}async suspendAccount(e){/^[0-9a-f]{64}$/.test(e)&&(this.scanEpoch+=1,this.sessionFence.suspend(e),await this.suspendBindingsForAccount(e,"logout"));}async invalidateGrant(e){let n=this.dependencies.store.getBinding(e.bindingId),r=e.session.accountKey;!n||!e.session.authenticated||!r||n.accountKey!==r||n.grantId!==e.grantId||n.grantGeneration!==e.generation||(this.scanEpoch+=1,this.sessionFence.suspend(r),this.sessionFence.cancelGrant(r,e.grantId,e.generation),this.dependencies.store.invalidateGrantJobs(n.bindingId,e.grantId,e.generation,this.now()),this.dependencies.store.updateBinding(n.bindingId,{status:this.hasPendingRevoke(n.bindingId)?"stopping":"revoked"},this.now()),await this.dependencies.documents.suspendBinding({binding:n,grantId:e.grantId,generation:e.generation,reason:"revoked"}));}async beginControlRequest(e){let{binding:n,accountKey:r,rootFingerprint:o}=this.validateControlIdentity(e),s=e.requestId;if(typeof s!="string"||s.length<1||s.length>128||s.includes("\0"))throw new Error("APP_SYNC_REQUEST_ID_INVALID");if(e.kind!=="connect"&&e.kind!=="revoke")throw new Error("APP_SYNC_CONTROL_REQUEST_KIND_INVALID");if(e.kind==="connect"&&n.grantId&&n.grantGeneration){let p=this.dependencies.store.getConfirmedRevoke(n.bindingId,n.grantId,n.grantGeneration);if(!(n.status==="revoked"||p!==void 0)&&!this.dependencies.store.getControlRequest(s))throw new Error("APP_SYNC_CONTROL_REQUEST_ALREADY_GRANTED")}let i=e.kind==="revoke"?e.grantId??null:null,a=e.kind==="revoke"?e.generation??null:null;if(e.kind==="revoke"&&(!i||!Number.isSafeInteger(a)||a<1||i!==n.grantId||a!==n.grantGeneration))throw new Error("APP_SYNC_CONTROL_REQUEST_GRANT_MISMATCH");if(e.kind==="connect"&&(e.grantId!=null||e.generation!=null))throw new Error("APP_SYNC_CONTROL_REQUEST_GRANT_MISMATCH");let c=this.now(),u=this.dependencies.store.beginControlRequest({requestId:s,bindingId:n.bindingId,accountKey:r,appId:T,workspaceId:n.workspaceId,rootFingerprint:o,kind:e.kind,state:"pending",grantId:i,generation:a,createdAt:c,updatedAt:c,resolvedAt:null,resolution:null,resolutionId:null});return u.kind==="revoke"&&(u.state==="pending"||u.state==="unknown")&&await this.holdPendingRevoke(n),u}getControlRequest(e){let{rootFingerprint:n}=this.validateControlIdentity(e),r=this.dependencies.store.getControlRequest(e.requestId);if(r&&!Xa(r,e,n))throw new Error("APP_SYNC_CONTROL_REQUEST_IDENTITY_MISMATCH");return r}getPendingControlRequest(e){let{binding:n}=this.validateControlIdentity(e);return this.dependencies.store.getPendingControlRequest(n.bindingId)}async markControlRequestUnknown(e){let n=this.getControlRequest(e);if(!n)throw new Error("APP_SYNC_CONTROL_REQUEST_NOT_FOUND");if(n.state==="unknown")return n;if(n.state!=="pending")throw new Error("APP_SYNC_CONTROL_REQUEST_ALREADY_RESOLVED");let r=this.dependencies.store.updateControlRequest(n.requestId,{state:"unknown",grantId:n.grantId,generation:n.generation,resolution:null,resolutionId:null,resolvedAt:null,now:this.now()});if(r.kind==="revoke"){let o=this.dependencies.store.getBinding(r.bindingId);o&&await this.holdPendingRevoke(o);}return r}async resolveControlRequest(e){let n=this.getControlRequest(e);if(!n)throw new Error("APP_SYNC_CONTROL_REQUEST_NOT_FOUND");if(e.outcome!=="confirmed"&&e.outcome!=="failed")throw new Error("APP_SYNC_CONTROL_REQUEST_OUTCOME_INVALID");if(e.resolution!=="remote"&&e.resolution!=="human")throw new Error("APP_SYNC_CONTROL_REQUEST_RESOLUTION_INVALID");if(typeof e.resolutionId!="string"||e.resolutionId.length<1||e.resolutionId.length>128||e.resolutionId.includes("\0"))throw new Error("APP_SYNC_CONTROL_REQUEST_RESOLUTION_ID_INVALID");if(n.state==="confirmed"||n.state==="failed"){if(n.state===e.outcome&&n.resolution===e.resolution&&n.resolutionId===e.resolutionId)return n;throw new Error("APP_SYNC_CONTROL_REQUEST_ALREADY_RESOLVED")}let r=n.grantId,o=n.generation;if(n.kind==="connect"&&e.outcome==="confirmed"){let c=e.observedGrant;if(!c||c.appId!==T||!c.grantId||!Number.isSafeInteger(c.generation)||c.generation<1||!this.scopeRegistry.matchesDefinition(c.scopeVersion,c.scope))throw new Error("APP_SYNC_CONTROL_REQUEST_GRANT_INVALID");r=c.grantId,o=c.generation;}let s=this.now(),i=this.dependencies.store.updateControlRequest(n.requestId,{state:e.outcome,grantId:r,generation:o,resolution:e.resolution,resolutionId:e.resolutionId,resolvedAt:s,now:s}),a=this.dependencies.store.getBinding(i.bindingId);return a&&n.kind==="revoke"?e.outcome==="confirmed"?(n.grantId&&n.generation&&(this.sessionFence.cancelGrant(a.accountKey,n.grantId,n.generation),this.dependencies.store.invalidateGrantJobs(a.bindingId,n.grantId,n.generation,s)),this.dependencies.store.updateBinding(a.bindingId,{status:"revoked"},s),await this.suspendDocumentBinding(a,"revoked")):this.dependencies.store.updateBinding(a.bindingId,{status:"checking"},s):a&&n.kind==="connect"&&e.outcome==="confirmed"&&r&&o&&this.dependencies.store.updateBinding(a.bindingId,{grantId:r,grantGeneration:o,scopeVersion:this.scopeRegistry.scopeVersion,status:"checking"},s),i}async snapshot(e){let n=this.dependencies.store.getBinding(e)??null;if(!n)return {binding:null,status:"local_only",counts:or(),results:[]};let r=this.dependencies.store.listResults(e),o=Mo(r,this.dependencies.store.countDeletedRefs(n.accountKey,T));return {binding:n,status:n.status,counts:o,results:r}}async performScan(e,n){let r=this.dependencies.store.getBinding(e);if(!r)throw new Error("APP_SYNC_BINDING_NOT_FOUND");let o=this.dependencies.store.getPendingControlRequest(e);if(o?.kind==="revoke")return await this.holdPendingRevoke(r),this.snapshot(e);if(!n.session.authenticated||!n.session.accountKey)return await this.suspendAccount(r.accountKey),this.snapshot(e);if(n.session.accountKey!==r.accountKey)return this.sessionFence.suspend(r.accountKey),await this.suspendBindingsForAccount(r.accountKey,"account_switch"),this.snapshot(e);if(!this.isEligible(n.eligibility))return await this.pauseUnavailableBinding(r,"ineligible"),this.snapshot(e);let s=await this.activateSession(r.accountKey);if(!s)return this.snapshot(e);if(this.hasPendingRevoke(e))return await this.holdPendingRevoke(r),this.snapshot(e);this.dependencies.store.updateBinding(e,{status:"checking"},this.now());let i;try{i=await this.dependencies.remote.readGrant({accountKey:r.accountKey,appId:T,signal:s.signal});}catch(u){if(this.hasPendingRevoke(e))return await this.holdPendingRevoke(r),this.snapshot(e);if(!this.isCurrent(s))return this.snapshot(e);let p=_t(u);return tr(u)&&!Ft.has(p)&&!Zn.has(p)?await this.pauseAuthentication(r):Ft.has(p)||Qa(u)?await this.pauseUnavailableBinding(r,p==="DOC_APP_GRANT_NOT_AVAILABLE"?"ineligible":"scope_mismatch"):er.has(p)?(r.grantId&&r.grantGeneration&&await this.invalidateStoredGeneration(r,"revoked"),this.dependencies.store.updateBinding(e,{status:"revoked"},this.now())):nr(u)?this.dependencies.store.updateBinding(e,{status:"offline"},this.now()):await this.pauseUnavailableBinding(r,"ineligible"),this.snapshot(e)}if(this.hasPendingRevoke(e))return await this.holdPendingRevoke(r),this.snapshot(e);if(!this.isCurrent(s))return this.snapshot(e);if(i.appId!==T||i.available!==true)return await this.pauseUnavailableBinding(r,i.available===true?"scope_mismatch":"ineligible"),this.snapshot(e);if(i.status==="none")return r.grantId&&r.grantGeneration?(await this.invalidateStoredGeneration(r,"revoked"),r=this.dependencies.store.getBinding(e)??r,this.dependencies.store.updateBinding(e,{status:"revoked"},this.now())):this.dependencies.store.updateBinding(e,{status:"consent_required"},this.now()),this.snapshot(e);if(i.status==="revoked")return r.grantId&&r.grantGeneration&&await this.invalidateStoredGeneration(r,"revoked"),this.dependencies.store.updateBinding(e,{status:"revoked"},this.now()),this.snapshot(e);if(i.status!=="active")return await this.pauseUnavailableBinding(r,"scope_mismatch"),this.snapshot(e);let a=i.grant;if(!a||a.appId!==T||!a.grantId||!Number.isSafeInteger(a.generation)||a.generation<1||!this.scopeRegistry.matchesDefinition(a.scopeVersion,a.scope))return await this.pauseUnavailableBinding(r,"scope_mismatch"),this.snapshot(e);if(this.hasPendingRevoke(e))return await this.holdPendingRevoke(r),this.snapshot(e);if(this.dependencies.store.getConfirmedRevoke(e,a.grantId,a.generation))return this.sessionFence.suspend(r.accountKey),this.dependencies.store.updateBinding(e,{status:"revoked"},this.now()),await this.suspendDocumentBinding(r,"revoked"),this.snapshot(e);o?.kind==="connect"&&this.dependencies.store.updateControlRequest(o.requestId,{state:"confirmed",grantId:a.grantId,generation:a.generation,resolution:"remote",resolutionId:"doc023-active",resolvedAt:this.now(),now:this.now()}),(r.grantId!==a.grantId||r.grantGeneration!==a.generation)&&r.grantId&&r.grantGeneration&&(this.sessionFence.cancelGrant(r.accountKey,r.grantId,r.grantGeneration),this.dependencies.store.invalidateGrantJobs(e,r.grantId,r.grantGeneration,this.now()),await this.dependencies.documents.suspendBinding({binding:r,grantId:r.grantId,generation:r.grantGeneration,reason:"regranted"})),this.dependencies.store.updateBinding(e,{grantId:a.grantId,grantGeneration:a.generation,scopeVersion:a.scopeVersion,status:"checking"},this.now()),r=this.dependencies.store.getBinding(e)??r;try{let u=await this.listAllowedRefs(r,s);if(this.hasPendingRevoke(e))return await this.holdPendingRevoke(r),this.snapshot(e);if(!this.isCurrent(s))return this.snapshot(e);let p=new Set(u.map(g=>g.ref));for(let g of this.dependencies.store.listResults(e))!p.has(g.ref)&&g.status!=="deleted"&&this.writeResult(r,a,g.ref,{sourceFingerprint:null,syncedFingerprint:g.syncedFingerprint,documentId:g.documentId,status:"excluded",errorCode:"APP_FILE_MISSING_OR_OUT_OF_SCOPE"});u.sort((g,_)=>g.ref.localeCompare(_.ref));for(let[g,_]of u.entries()){if(this.hasPendingRevoke(e))return await this.holdPendingRevoke(r),this.snapshot(e);if(!this.isCurrent(s))return this.snapshot(e);let S=crypto.createHash("sha256").update(_.ref,"utf8").digest("hex");if(this.dependencies.store.hasDeletedRef(r.accountKey,T,S)){let ye=this.dependencies.store.getResult(e,_.ref);this.writeResult(r,a,_.ref,{sourceFingerprint:null,syncedFingerprint:ye?.syncedFingerprint??null,documentId:ye?.documentId??null,status:"deleted",errorCode:"DOC_APP_REF_DELETED"});continue}let w=this.dependencies.store.getResult(e,_.ref);if(g>=500){this.writeResult(r,a,_.ref,{sourceFingerprint:null,syncedFingerprint:w?.syncedFingerprint??null,documentId:w?.documentId??null,status:"blocked",errorCode:"APP_LOCAL_QUOTA"});continue}let R=await this.readEligibleFile(r,_.ref,s.signal);if(this.hasPendingRevoke(e))return await this.holdPendingRevoke(r),this.snapshot(e);if(!this.isCurrent(s))return this.snapshot(e);if(R.status==="unsafe"||R.status==="missing"){this.writeResult(r,a,_.ref,{sourceFingerprint:null,syncedFingerprint:w?.syncedFingerprint??null,documentId:w?.documentId??null,status:"excluded",errorCode:R.status==="unsafe"?"APP_FILE_UNSAFE":"APP_FILE_MISSING"});continue}if(R.status==="read_error"){this.writeResult(r,a,_.ref,{sourceFingerprint:null,syncedFingerprint:w?.syncedFingerprint??null,documentId:w?.documentId??null,status:"failed",errorCode:"APP_FILE_READ_FAILED"});continue}let E=this.scopeRegistry.validateFrontMatter(_.ref,R.markdown),I=L(R.markdown);if(!E.valid){this.writeResult(r,a,_.ref,{sourceFingerprint:I,syncedFingerprint:w?.syncedFingerprint??null,documentId:w?.documentId??null,status:"excluded",errorCode:"DOC_APP_BODY_OUT_OF_SCOPE"});continue}if(w?.status==="conflict"&&w.grantGeneration===a.generation)continue;if(w?.documentId&&w.grantGeneration===a.generation){if(w.status==="synced"&&w.syncedFingerprint===I)continue;let ye=w?.sourceFingerprint===I;this.writeResult(r,a,_.ref,{sourceFingerprint:I,syncedFingerprint:w.syncedFingerprint,documentId:w.documentId,status:ye?w.status:"waiting",errorCode:ye?w.errorCode:null,nextAttemptAt:ye?w.nextAttemptAt:0});continue}if(w?.status==="failed"&&w.grantGeneration===a.generation&&w.sourceFingerprint===I&&!un.has(w.errorCode??"")||w?.status==="blocked"&&w.errorCode!=="APP_LOCAL_QUOTA"&&w.grantGeneration===a.generation&&w.sourceFingerprint===I)continue;let Te=this.dependencies.store.enqueueCreation({jobId:this.createId(),requestId:this.createId(),bindingId:e,accountKey:r.accountKey,grantId:a.grantId,grantGeneration:a.generation,ref:_.ref,fingerprint:I,now:this.now()}),O=w?.sourceFingerprint===I,Ae=w?.status==="failed"&&un.has(w.errorCode??"");this.writeResult(r,a,_.ref,{sourceFingerprint:I,syncedFingerprint:w?.syncedFingerprint??null,documentId:w?.documentId??null,status:Te.status==="completed"?"processing":"waiting",errorCode:O&&!Ae?w.errorCode:null,nextAttemptAt:O&&!Ae?w.nextAttemptAt:0});}return this.refreshBindingStatus(e),this.snapshot(e)}catch{return this.isCurrent(s)?(await this.pauseUnavailableBinding(r,"ineligible"),this.snapshot(e)):this.snapshot(e)}}async listAllowedRefs(e,n){let r=new Map,o=new Set,s=null;for(let i=0;i<Wa;i+=1){if(this.hasPendingRevoke(e.bindingId))return [];let a=await this.dependencies.workspace.listAllowedFiles({rootSegments:e.rootSegments,selectors:Wn,cursor:s,pageSize:100,signal:n.signal});if(this.hasPendingRevoke(e.bindingId))return [];if(!this.isCurrent(n))return [];for(let c of a.entries)c.isSymlink||!c.staysWithinRoot||this.scopeRegistry.validateRef(c.ref).valid&&r.set(c.ref,{ref:c.ref});if(a.nextCursor===null)return [...r.values()];if(o.has(a.nextCursor))throw new Error("APP_SYNC_PAGE_CURSOR_REPEATED");o.add(a.nextCursor),s=a.nextCursor;}throw new Error("APP_SYNC_PAGE_LIMIT_REACHED")}async readEligibleFile(e,n,r){if(!this.scopeRegistry.validateRef(n).valid)return {status:"unsafe"};try{let o=await this.dependencies.workspace.readFile({rootSegments:e.rootSegments,ref:n,signal:r});return o.isSymlink||!o.staysWithinRoot?{status:"unsafe"}:{status:"ok",markdown:o.markdown}}catch(o){let s=_t(o);return s==="ENOENT"||s==="APP_FILE_MISSING"?{status:"missing"}:{status:"read_error"}}}async beforeDocumentDispatch(e,n,r,o){if(!this.isCurrent(r))return {ok:false,reason:"session_stale"};if(!this.bindingHasGrant(e.bindingId,n))return {ok:false,reason:"grant_stale"};if(this.hasPendingRevoke(e.bindingId))return {ok:false,reason:"control_request_pending"};if(this.dependencies.store.hasDeletedRef(e.accountKey,T,Fe(o)))return {ok:false,reason:"deleted"};let s=await this.readEligibleFile(e,o,r.signal);return this.isCurrent(r)?this.hasPendingRevoke(e.bindingId)?{ok:false,reason:"control_request_pending"}:this.bindingHasGrant(e.bindingId,n)?this.dependencies.store.hasDeletedRef(e.accountKey,T,Fe(o))?{ok:false,reason:"deleted"}:s.status!=="ok"?{ok:false,reason:s.status}:this.scopeRegistry.validateFrontMatter(o,s.markdown).valid?{ok:true,markdown:s.markdown,fingerprint:L(s.markdown)}:{ok:false,reason:"out_of_scope"}:{ok:false,reason:"grant_stale"}:{ok:false,reason:"session_stale"}}async readRemoteDocument(e){return this.remoteReadSemaphore.run(e.signal,()=>this.dependencies.remote.readDocument(e))}async dispatchCreation(e,n,r,o,s){if(this.hasPendingRevoke(e.bindingId)){await this.holdPendingRevoke(e);return}if(o.accountKey!==e.accountKey||o.bindingId!==e.bindingId||o.grantId!==n.grantId||o.grantGeneration!==n.generation||e.grantId!==n.grantId||e.grantGeneration!==n.generation){this.dependencies.store.updateCreation(o.jobId,{status:"invalidated",nextAttemptAt:0,now:this.now()});return}if(!this.isCurrent(r))return;if(o.operationKind==="reattach"){this.continuationRuntime?await this.continuationRuntime.dispatchReattachCreation(e,n,r,o,s):this.dependencies.store.updateCreation(o.jobId,{status:"waiting",nextAttemptAt:this.now()+6e4,now:this.now()});return}let i=this.dependencies.store.claimCreation(o.jobId,this.now(),ja);if(!i)return;let a=this.sessionFence.captureGrant(r,n.grantId,n.generation),c=this.dependencies.store.getResult(e.bindingId,i.ref);try{if(this.dependencies.store.hasDeletedRef(e.accountKey,T,Fe(i.ref))){await this.markDeleted(e,n,i,c);return}let u=await this.readEligibleFile(e,i.ref,a.signal);if(this.hasPendingRevoke(e.bindingId)){await this.holdPendingRevoke(e);return}if(!this.isCurrent(a))return;if(u.status!=="ok"){this.writeResult(e,n,i.ref,{sourceFingerprint:null,syncedFingerprint:c?.syncedFingerprint??null,documentId:c?.documentId??null,status:u.status==="read_error"?"failed":"excluded",errorCode:u.status==="unsafe"?"APP_FILE_UNSAFE":u.status==="missing"?"APP_FILE_MISSING":"APP_FILE_READ_FAILED"}),this.dependencies.store.updateCreation(i.jobId,{status:u.status==="read_error"?"failed":"completed",nextAttemptAt:0,now:this.now()});return}if(!this.scopeRegistry.validateFrontMatter(i.ref,u.markdown).valid){this.writeResult(e,n,i.ref,{sourceFingerprint:L(u.markdown),syncedFingerprint:c?.syncedFingerprint??null,documentId:c?.documentId??null,status:"excluded",errorCode:"DOC_APP_BODY_OUT_OF_SCOPE"}),this.dependencies.store.updateCreation(i.jobId,{status:"completed",nextAttemptAt:0,now:this.now()});return}if(L(u.markdown)!==i.fingerprint){this.dependencies.store.updateCreation(i.jobId,{status:"completed",nextAttemptAt:0,now:this.now()});return}this.writeResult(e,n,i.ref,{sourceFingerprint:i.fingerprint,syncedFingerprint:c?.syncedFingerprint??null,documentId:c?.documentId??null,status:"processing",errorCode:null});let _=await this.dependencies.creationBudget.runCreate({accountKey:i.accountKey,signal:a.signal,dispatch:async()=>{if(this.hasPendingRevoke(e.bindingId))return {kind:"control_pending"};let O=await this.readEligibleFile(e,i.ref,a.signal);if(!this.isCurrent(a))throw new f("APP_SYNC_SESSION_STALE");if(this.dependencies.store.hasDeletedRef(e.accountKey,T,Fe(i.ref)))return {kind:"deleted"};if(O.status!=="ok")return {kind:"local_file",status:O.status};if(!this.scopeRegistry.validateFrontMatter(i.ref,O.markdown).valid)return {kind:"out_of_scope"};let Ae=L(O.markdown);if(Ae!==i.fingerprint)return {kind:"source_changed",fingerprint:Ae};let ye=this.makeDispatchGate({bindingId:e.bindingId,accountKey:i.accountKey,grant:n,token:a,requestId:i.requestId,source:"app_create"}),To;try{To=await this.dependencies.remote.createGrantedDocument({accountKey:i.accountKey,appId:T,ref:i.ref,requestId:i.requestId,markdown:O.markdown,appVersion:s.appVersion,appGrant:{grantId:i.grantId,generation:i.grantGeneration},signal:a.signal,...ye?{dispatchGate:ye}:{}});}catch(Hn){if(Hn instanceof Ge)return {kind:"budget_deferred",retryAt:Hn.retryAt};throw Hn}if(ye&&ye.calls===0)throw this.recordMissingDispatchGate({accountKey:i.accountKey,requestId:i.requestId,source:"app_create"});return {kind:"created",result:To}}});if(this.hasPendingRevoke(e.bindingId)){await this.holdPendingRevoke(e);return}if(!this.isCurrent(a))return;if(_.status==="deferred"){let O=this.now();if(!this.deferClaim(i,_.retryAt,O))return;this.writeResult(e,n,i.ref,{sourceFingerprint:i.fingerprint,syncedFingerprint:c?.syncedFingerprint??null,documentId:c?.documentId??null,status:"waiting",errorCode:null,nextAttemptAt:_.retryAt});return}if(_.value.kind==="budget_deferred"){let O=this.now();if(!this.deferClaim(i,_.value.retryAt,O))return;this.writeResult(e,n,i.ref,{sourceFingerprint:i.fingerprint,syncedFingerprint:c?.syncedFingerprint??null,documentId:c?.documentId??null,status:"waiting",errorCode:null,nextAttemptAt:_.value.retryAt});return}if(_.value.kind!=="created"){let O=_.value;if(O.kind==="control_pending"){this.dependencies.store.updateCreation(i.jobId,{status:"waiting",nextAttemptAt:this.now(),now:this.now()}),this.writeResult(e,n,i.ref,{sourceFingerprint:i.fingerprint,syncedFingerprint:c?.syncedFingerprint??null,documentId:c?.documentId??null,status:"waiting",errorCode:"APP_SYNC_REVOKE_PENDING",nextAttemptAt:this.now()}),this.dependencies.store.updateBinding(e.bindingId,{status:"stopping"},this.now());return}if(O.kind==="deleted"){await this.markDeleted(e,n,i,c);return}if(O.kind==="source_changed"){this.writeResult(e,n,i.ref,{sourceFingerprint:O.fingerprint,syncedFingerprint:c?.syncedFingerprint??null,documentId:c?.documentId??null,status:"waiting",errorCode:null}),this.dependencies.store.updateCreation(i.jobId,{status:"completed",nextAttemptAt:0,now:this.now()});return}let Ae=O.kind==="local_file"?O.status:"unsafe";this.writeResult(e,n,i.ref,{sourceFingerprint:null,syncedFingerprint:c?.syncedFingerprint??null,documentId:c?.documentId??null,status:Ae==="read_error"?"failed":"excluded",errorCode:O.kind==="out_of_scope"?"DOC_APP_BODY_OUT_OF_SCOPE":Ae==="unsafe"?"APP_FILE_UNSAFE":Ae==="missing"?"APP_FILE_MISSING":"APP_FILE_READ_FAILED"}),this.dependencies.store.updateCreation(i.jobId,{status:Ae==="read_error"?"failed":"completed",nextAttemptAt:0,now:this.now()});return}let S=_.value.result;if(S.appGrantId!==n.grantId||S.appGrantGeneration!==n.generation)throw new f("DOC_APP_GRANT_STALE",409);let w=await this.readRemoteDocument({accountKey:i.accountKey,docId:S.docId,signal:a.signal});if(this.hasPendingRevoke(e.bindingId)){await this.holdPendingRevoke(e);return}if(!this.isCurrent(a))return;if(!this.validRemoteDocument(w,S,n)){this.recordOutcome(e,n,i.ref,i.fingerprint,c,S.docId,{status:"conflict",errorCode:"DOC_SYNC_REMOTE_STATE_MISMATCH",dispatch:"none"}),this.dependencies.store.updateCreation(i.jobId,{status:"conflict",nextAttemptAt:0,now:this.now()});return}let R=L(w.markdown),E,I=i.fingerprint;if(!S.replayed&&!S.reattached&&R===i.fingerprint&&w.markdownVersion===i.fingerprint)E=await this.dependencies.documents.attachCreated({binding:e,grant:n,ref:i.ref,document:w,localMarkdown:u.markdown,sourceFingerprint:i.fingerprint,signal:a.signal});else {let O;if(E=await this.dependencies.documents.reconcileExisting({binding:e,grant:n,ref:i.ref,document:w,localMarkdown:u.markdown,sourceFingerprint:i.fingerprint,signal:a.signal,beforeDispatch:async()=>(O=await this.beforeDocumentDispatch(e,n,a,i.ref),O)}),!O&&E.dispatch!=="none")throw new f("APP_SYNC_ADAPTER_DID_NOT_REVALIDATE");if(E.dispatch==="attempted"&&!O)throw new f("APP_SYNC_ADAPTER_DID_NOT_REVALIDATE");if(O&&!O.ok){this.recordBeforeDispatchFailure(e,n,i.ref,c,O,i);return}O?.ok&&E.dispatch!=="none"&&(I=O.fingerprint);}if(!this.isCurrent(a)||!this.bindingHasGrant(e.bindingId,n))return;let Te=this.recordOutcome(e,n,i.ref,I,c,S.docId,E);this.dependencies.store.updateCreation(i.jobId,{status:Te==="conflict"?"conflict":Te==="failed"?"failed":E.status==="failed"&&E.retryAt!==void 0?"waiting":"completed",nextAttemptAt:E.status==="failed"&&E.retryAt!==void 0?this.retryAt(i.attempts+1,E.retryAt):0,now:this.now()});}catch(u){if(this.hasPendingRevoke(e.bindingId)){await this.holdPendingRevoke(e);return}if(!this.isCurrent(a)||!this.bindingHasGrant(e.bindingId,n))return;await this.handleCreationError(e,n,i,c,u);}finally{this.sessionFence.release(a);}}async reconcileExisting(e,n,r,o){if(this.hasPendingRevoke(e.bindingId)){await this.holdPendingRevoke(e);return}if(!o.documentId||o.accountKey!==e.accountKey||o.grantId!==n.grantId||o.grantGeneration!==n.generation||o.status==="conflict"||o.status==="excluded"||o.status==="deleted"||!this.isCurrent(r))return;let s=await this.readEligibleFile(e,o.ref,r.signal);if(this.hasPendingRevoke(e.bindingId)){await this.holdPendingRevoke(e);return}if(!this.isCurrent(r))return;if(s.status!=="ok"){this.writeResult(e,n,o.ref,{sourceFingerprint:null,syncedFingerprint:o.syncedFingerprint,documentId:o.documentId,status:s.status==="read_error"?"failed":"excluded",errorCode:s.status==="unsafe"?"APP_FILE_UNSAFE":s.status==="missing"?"APP_FILE_MISSING":"APP_FILE_READ_FAILED"});return}if(!this.scopeRegistry.validateFrontMatter(o.ref,s.markdown).valid){this.writeResult(e,n,o.ref,{sourceFingerprint:L(s.markdown),syncedFingerprint:o.syncedFingerprint,documentId:o.documentId,status:"failed",errorCode:"DOC_APP_BODY_OUT_OF_SCOPE"});return}let a=L(s.markdown);if(this.dependencies.store.hasDeletedRef(e.accountKey,T,Fe(o.ref))){this.writeResult(e,n,o.ref,{sourceFingerprint:null,syncedFingerprint:o.syncedFingerprint,documentId:o.documentId,status:"deleted",errorCode:"DOC_APP_REF_DELETED"});return}let u;try{u=await this.readRemoteDocument({accountKey:e.accountKey,docId:o.documentId,signal:r.signal});}catch(p){if(this.hasPendingRevoke(e.bindingId)){await this.holdPendingRevoke(e);return}if(!this.isCurrent(r))return;await this.handleExistingError(e,n,o,a,p);return}if(this.hasPendingRevoke(e.bindingId)){await this.holdPendingRevoke(e);return}if(this.isCurrent(r)){if(u.appGrantId!==n.grantId||u.appGrantGeneration!==n.generation||L(u.markdown)!==u.markdownVersion){this.writeResult(e,n,o.ref,{sourceFingerprint:a,syncedFingerprint:o.syncedFingerprint,documentId:o.documentId,status:"conflict",errorCode:"DOC_SYNC_REMOTE_STATE_MISMATCH"});return}this.writeResult(e,n,o.ref,{sourceFingerprint:a,syncedFingerprint:o.syncedFingerprint,documentId:o.documentId,status:"processing",errorCode:null});try{let p,g=await this.dependencies.documents.reconcileExisting({binding:e,grant:n,ref:o.ref,document:u,localMarkdown:s.markdown,sourceFingerprint:a,signal:r.signal,beforeDispatch:async()=>(p=await this.beforeDocumentDispatch(e,n,r,o.ref),p)});if(this.hasPendingRevoke(e.bindingId)){await this.holdPendingRevoke(e);return}if(!this.isCurrent(r)||!this.bindingHasGrant(e.bindingId,n))return;if(!p&&g.dispatch!=="none"){await this.handleExistingError(e,n,o,a,new f("APP_SYNC_ADAPTER_DID_NOT_REVALIDATE"));return}if(g.dispatch==="attempted"&&!p){await this.handleExistingError(e,n,o,a,new f("APP_SYNC_ADAPTER_DID_NOT_REVALIDATE"));return}if(p&&!p.ok){this.recordBeforeDispatchFailure(e,n,o.ref,o,p);return}let _=p?.ok&&g.dispatch!=="none"?p.fingerprint:a;this.recordOutcome(e,n,o.ref,_,o,o.documentId,g);}catch(p){if(!this.isCurrent(r))return;await this.handleExistingError(e,n,o,a,p);}}}async handleCreationError(e,n,r,o,s){let i=_t(s);if(i==="DOC_APP_REF_DELETED"){await this.markDeleted(e,n,r,o);return}if(i==="DOC_APP_REF_OUT_OF_SCOPE"){this.writeResult(e,n,r.ref,{sourceFingerprint:r.fingerprint,syncedFingerprint:o?.syncedFingerprint??null,documentId:o?.documentId??null,status:"excluded",errorCode:i}),this.dependencies.store.updateCreation(r.jobId,{status:"completed",nextAttemptAt:0,now:this.now()});return}if(Ft.has(i)){await this.pauseUnavailableBinding(e,i==="DOC_APP_GRANT_NOT_AVAILABLE"?"ineligible":"scope_mismatch"),this.writeResult(e,n,r.ref,{sourceFingerprint:r.fingerprint,syncedFingerprint:o?.syncedFingerprint??null,documentId:o?.documentId??null,status:"waiting",errorCode:i}),this.dependencies.store.updateCreation(r.jobId,{status:"waiting",nextAttemptAt:this.now(),now:this.now()});return}if(er.has(i)){this.sessionFence.cancelGrant(e.accountKey,n.grantId,n.generation),this.dependencies.store.invalidateGrantJobs(e.bindingId,n.grantId,n.generation,this.now()),this.dependencies.store.updateBinding(e.bindingId,{status:"revoked"},this.now()),await this.dependencies.documents.suspendBinding({binding:e,grantId:n.grantId,generation:n.generation,reason:"revoked"});return}if(i==="DOC_APP_BODY_OUT_OF_SCOPE"){this.writeResult(e,n,r.ref,{sourceFingerprint:r.fingerprint,syncedFingerprint:o?.syncedFingerprint??null,documentId:o?.documentId??null,status:"failed",errorCode:i}),this.dependencies.store.updateCreation(r.jobId,{status:"failed",nextAttemptAt:0,now:this.now()});return}if(Zn.has(i)){this.writeResult(e,n,r.ref,{sourceFingerprint:r.fingerprint,syncedFingerprint:o?.syncedFingerprint??null,documentId:o?.documentId??null,status:"blocked",errorCode:i}),this.dependencies.store.updateCreation(r.jobId,{status:"blocked",nextAttemptAt:0,now:this.now()});return}if(tr(s)){await this.pauseAuthentication(e),this.writeResult(e,n,r.ref,{sourceFingerprint:r.fingerprint,syncedFingerprint:o?.syncedFingerprint??null,documentId:o?.documentId??null,status:"waiting",errorCode:"AUTH_REQUIRED",nextAttemptAt:this.now()});return}let a=this.retryAt(r.attempts,Fo(s,this.now())),c=nr(s);this.writeResult(e,n,r.ref,{sourceFingerprint:r.fingerprint,syncedFingerprint:o?.syncedFingerprint??null,documentId:o?.documentId??null,status:c?"waiting":"failed",errorCode:i||"APP_SYNC_CREATE_FAILED",nextAttemptAt:c?a:0}),this.dependencies.store.updateCreation(r.jobId,{status:c?"waiting":"failed",nextAttemptAt:c?a:0,now:this.now()}),c&&this.dependencies.store.updateBinding(e.bindingId,{status:"offline"},this.now());}async handleExistingError(e,n,r,o,s){let i=_t(s);if(i==="DOC_APP_REF_DELETED"){this.dependencies.store.suppressDeletedRef(e.accountKey,T,Fe(r.ref),this.now()),this.writeResult(e,n,r.ref,{sourceFingerprint:null,syncedFingerprint:r.syncedFingerprint,documentId:r.documentId,status:"deleted",errorCode:i});return}if(er.has(i)){this.sessionFence.cancelGrant(e.accountKey,n.grantId,n.generation),this.dependencies.store.invalidateGrantJobs(e.bindingId,n.grantId,n.generation,this.now()),this.dependencies.store.updateBinding(e.bindingId,{status:"revoked"},this.now()),await this.dependencies.documents.suspendBinding({binding:e,grantId:n.grantId,generation:n.generation,reason:"revoked"});return}if(Ft.has(i)){await this.pauseUnavailableBinding(e,i==="DOC_APP_GRANT_NOT_AVAILABLE"?"ineligible":"scope_mismatch"),this.writeResult(e,n,r.ref,{sourceFingerprint:o,syncedFingerprint:r.syncedFingerprint,documentId:r.documentId,status:"waiting",errorCode:i,nextAttemptAt:this.now()});return}if(Zn.has(i)){i==="DOC_PILOT_NOT_ALLOWED"&&await this.pauseUnavailableBinding(e,"ineligible"),this.writeResult(e,n,r.ref,{sourceFingerprint:o,syncedFingerprint:r.syncedFingerprint,documentId:r.documentId,status:"blocked",errorCode:i});return}if(tr(s)){await this.pauseAuthentication(e),this.writeResult(e,n,r.ref,{sourceFingerprint:o,syncedFingerprint:r.syncedFingerprint,documentId:r.documentId,status:"waiting",errorCode:"AUTH_REQUIRED",nextAttemptAt:this.now()});return}let a=nr(s),c=r.sourceFingerprint===o?r.attempts+1:1,u=a?this.retryAt(c,Fo(s,this.now())):0;this.writeResult(e,n,r.ref,{sourceFingerprint:o,syncedFingerprint:r.syncedFingerprint,documentId:r.documentId,status:a?"waiting":"failed",errorCode:i||"APP_SYNC_RECONCILE_FAILED",nextAttemptAt:u,attempts:a?c:0}),a&&this.dependencies.store.updateBinding(e.bindingId,{status:"offline"},this.now());}async markDeleted(e,n,r,o){this.dependencies.store.suppressDeletedRef(e.accountKey,T,Fe(r.ref),this.now()),this.writeResult(e,n,r.ref,{sourceFingerprint:null,syncedFingerprint:o?.syncedFingerprint??null,documentId:o?.documentId??null,status:"deleted",errorCode:"DOC_APP_REF_DELETED"}),this.dependencies.store.updateCreation(r.jobId,{status:"deleted",nextAttemptAt:0,now:this.now()});}recordOutcome(e,n,r,o,s,i,a){let c=a.status==="synced"&&a.syncedFingerprint===o?o:s?.syncedFingerprint??null,u=a.status==="synced"&&c!==o?"conflict":(a.status==="failed"||a.status==="waiting")&&a.retryAt!==void 0?"waiting":a.status,p=u==="waiting"&&a.retryAt!==void 0?s?.sourceFingerprint===o?s.attempts+1:1:u==="synced"||u==="conflict"?0:s?.sourceFingerprint===o?s.attempts:0;return this.writeResult(e,n,r,{sourceFingerprint:o,syncedFingerprint:c,documentId:i,status:u,errorCode:u==="conflict"&&a.status==="synced"?"DOC_SYNC_ACK_MISMATCH":a.errorCode??null,nextAttemptAt:u==="waiting"&&a.retryAt!==void 0?this.retryAt(p,a.retryAt):0,attempts:p}),u}recordBeforeDispatchFailure(e,n,r,o,s,i){if(s.reason==="session_stale"||s.reason==="grant_stale")return;if(s.reason==="deleted"){this.dependencies.store.suppressDeletedRef(e.accountKey,T,Fe(r),this.now()),this.writeResult(e,n,r,{sourceFingerprint:null,syncedFingerprint:o?.syncedFingerprint??null,documentId:o?.documentId??null,status:"deleted",errorCode:"DOC_APP_REF_DELETED"}),i&&this.dependencies.store.updateCreation(i.jobId,{status:"deleted",nextAttemptAt:0,now:this.now()});return}if(s.reason==="control_request_pending"){this.writeResult(e,n,r,{sourceFingerprint:o?.sourceFingerprint??null,syncedFingerprint:o?.syncedFingerprint??null,documentId:o?.documentId??null,status:"waiting",errorCode:"APP_SYNC_REVOKE_PENDING",nextAttemptAt:this.now()}),this.dependencies.store.updateBinding(e.bindingId,{status:"stopping"},this.now()),i&&this.dependencies.store.updateCreation(i.jobId,{status:"waiting",nextAttemptAt:this.now(),now:this.now()});return}let a=s.reason==="read_error"?"failed":"excluded",c=s.reason==="out_of_scope"?"DOC_APP_BODY_OUT_OF_SCOPE":s.reason==="unsafe"?"APP_FILE_UNSAFE":s.reason==="missing"?"APP_FILE_MISSING":"APP_FILE_READ_FAILED";this.writeResult(e,n,r,{sourceFingerprint:null,syncedFingerprint:o?.syncedFingerprint??null,documentId:o?.documentId??null,status:a,errorCode:c,nextAttemptAt:0}),i&&this.dependencies.store.updateCreation(i.jobId,{status:s.reason==="read_error"?"failed":"completed",nextAttemptAt:0,now:this.now()});}writeResult(e,n,r,o){let s=this.dependencies.store.getResult(e.bindingId,r),i=o.attempts??(s?.sourceFingerprint===o.sourceFingerprint?s.attempts:0);this.dependencies.store.upsertResult({bindingId:e.bindingId,accountKey:e.accountKey,ref:r,grantId:n.grantId,grantGeneration:n.generation,...o,nextAttemptAt:o.nextAttemptAt??0,attempts:i,updatedAt:this.now()});}validateControlIdentity(e){let n=this.requireAuthenticatedAccount(e.session),r=this.dependencies.store.getBinding(e.bindingId);if(!r||r.accountKey!==n)throw new Error("APP_SYNC_CONTROL_REQUEST_BINDING_MISMATCH");let o=lt(e.resolvedRootSegments);if(!o||r.workspaceId!==e.workspaceId||!Ja(r.rootSegments,o))throw new Error("APP_SYNC_CONTROL_REQUEST_IDENTITY_MISMATCH");return {binding:r,accountKey:n,rootFingerprint:Fe(JSON.stringify(o))}}hasPendingRevoke(e){let n=this.dependencies.store.getPendingControlRequest(e);return n?.kind==="revoke"&&(n.state==="pending"||n.state==="unknown")}async holdPendingRevoke(e){this.scanEpoch+=1,this.sessionFence.suspend(e.accountKey),e.grantId&&e.grantGeneration&&(this.sessionFence.cancelGrant(e.accountKey,e.grantId,e.grantGeneration),this.dependencies.store.releaseProcessingCreations(e.bindingId,e.grantId,e.grantGeneration,this.now()),this.returnProcessingResultsToWaiting(e,e.grantId,e.grantGeneration,"APP_SYNC_REVOKE_PENDING")),this.dependencies.store.updateBinding(e.bindingId,{status:"stopping"},this.now()),await this.suspendDocumentBinding(e,"revoke_pending");}async invalidateStoredGeneration(e,n){!e.grantId||!e.grantGeneration||(this.sessionFence.cancelGrant(e.accountKey,e.grantId,e.grantGeneration),this.dependencies.store.invalidateGrantJobs(e.bindingId,e.grantId,e.grantGeneration,this.now()),await this.dependencies.documents.suspendBinding({binding:e,grantId:e.grantId,generation:e.grantGeneration,reason:n}));}async pauseUnavailableBinding(e,n){this.scanEpoch+=1,this.sessionFence.suspend(e.accountKey),e.grantId&&e.grantGeneration&&(this.sessionFence.cancelGrant(e.accountKey,e.grantId,e.grantGeneration),this.dependencies.store.releaseProcessingCreations(e.bindingId,e.grantId,e.grantGeneration,this.now()),this.returnProcessingResultsToWaiting(e,e.grantId,e.grantGeneration,"APP_SYNC_UNAVAILABLE")),this.dependencies.store.updateBinding(e.bindingId,{status:"unavailable"},this.now()),await this.suspendDocumentBinding(e,n);}async pauseAuthentication(e){this.scanEpoch+=1,this.sessionFence.suspend(e.accountKey),e.grantId&&e.grantGeneration&&(this.sessionFence.cancelGrant(e.accountKey,e.grantId,e.grantGeneration),this.dependencies.store.releaseProcessingCreations(e.bindingId,e.grantId,e.grantGeneration,this.now()),this.returnProcessingResultsToWaiting(e,e.grantId,e.grantGeneration,"AUTH_REQUIRED",true)),this.dependencies.store.updateBinding(e.bindingId,{status:"unavailable"},this.now()),await this.suspendDocumentBinding(e,"auth_required");}returnProcessingResultsToWaiting(e,n,r,o,s=false){for(let i of this.dependencies.store.listResults(e.bindingId)){let a=i.status==="processing",c=s&&i.status==="failed"&&un.has(i.errorCode??"");i.grantId!==n||i.grantGeneration!==r||!a&&!c||this.dependencies.store.upsertResult({...i,status:"waiting",errorCode:o,nextAttemptAt:this.now(),updatedAt:this.now()});}}async suspendDocumentBinding(e,n){try{await this.dependencies.documents.suspendBinding({binding:e,grantId:e.grantId,generation:e.grantGeneration,reason:n});}catch(r){this.reportAdapterError(r);}}reportAdapterError(e){try{this.dependencies.onAdapterError?.(e);}catch{}}async activateSession(e){let n=this.sessionFence.activeAccountKey,r=this.sessionFence.activate(e);return n&&n!==e&&await this.suspendBindingsForAccount(n,"account_switch"),r}async suspendBindingsForAccount(e,n){for(let r of this.dependencies.store.listBindingsForAccount(e)){this.dependencies.store.updateBinding(r.bindingId,{status:"stopping"},this.now());try{await this.dependencies.documents.suspendBinding({binding:r,grantId:r.grantId,generation:r.grantGeneration,reason:n});}catch(o){this.reportAdapterError(o);}finally{try{this.dependencies.store.updateBinding(r.bindingId,{status:this.hasPendingRevoke(r.bindingId)?"stopping":"local_only"},this.now());}catch(o){this.reportAdapterError(o);}}}}shouldReconcile(e,n){return e.documentId!==null&&e.grantId===n.grantId&&e.grantGeneration===n.generation&&(e.status==="processing"||e.status==="waiting"&&e.nextAttemptAt<=this.now())}validRemoteDocument(e,n,r){return e.docId===n.docId&&e.appGrantId===r.grantId&&e.appGrantGeneration===r.generation&&n.appGrantId===r.grantId&&n.appGrantGeneration===r.generation&&n.markdownVersion===e.markdownVersion&&L(e.markdown)===e.markdownVersion}grantFromBinding(e){if(!e.grantId||!e.grantGeneration||e.scopeVersion!==this.scopeRegistry.scopeVersion)throw new Error("APP_SYNC_BINDING_GRANT_INVALID");return {grantId:e.grantId,appId:T,generation:e.grantGeneration,scopeVersion:e.scopeVersion,scope:pe}}bindingHasGrant(e,n){let r=this.dependencies.store.getBinding(e);return r?.grantId===n.grantId&&r.grantGeneration===n.generation}isTransferStatus(e){return e==="checking"||e==="syncing"||e==="synced"||e==="partial"}isEligible(e){return e?.featureEnabled===true&&e?.ownerAllowlisted===true}requireAuthenticatedAccount(e){if(!e||e.authenticated!==true||typeof e.accountKey!="string"||!/^[0-9a-f]{64}$/.test(e.accountKey))throw new Error("APP_SYNC_SESSION_REQUIRED");return e.accountKey}isCurrent(e){return this.sessionFence.isCurrent(e)}refreshBindingStatus(e){let n=this.snapshotNow(e);if(!n.binding||["offline","unavailable","revoked","stopping","local_only","consent_required"].includes(n.binding.status))return;let r=n.counts,o=r.P+r.I>0?"syncing":r.F+r.C+r.B>0?"partial":"synced";this.dependencies.store.updateBinding(e,{status:o},this.now());}snapshotNow(e){let n=this.dependencies.store.getBinding(e)??null;if(!n)return {binding:null,status:"local_only",counts:or(),results:[]};let r=this.dependencies.store.listResults(e);return {binding:n,status:n.status,counts:Mo(r,this.dependencies.store.countDeletedRefs(n.accountKey,T)),results:r}}listConflicts(e){return this.continuationRuntime?this.continuationRuntime.listConflicts(e):[]}readConflictArchive(e){return this.continuationRuntime?this.continuationRuntime.readConflictArchive(e):Promise.reject(new Error("APP_SYNC_CONTINUATION_DISABLED"))}resolveConflict(e){return this.continuationRuntime?this.continuationRuntime.resolveConflict(e):Promise.reject(new Error("APP_SYNC_CONTINUATION_DISABLED"))}purgeAccountData(e){return this.continuationRuntime?this.continuationRuntime.purgeAccountData(e):Promise.reject(new Error("APP_SYNC_CONTINUATION_DISABLED"))}retryAt(e,n){if(n!==void 0&&Number.isFinite(n))return Math.max(this.now(),n);let r=Math.min(Math.max(e-1,0),10);return this.now()+Math.min(Ka*2**r,Va)}};function or(){return {N:0,S:0,P:0,I:0,F:0,C:0,B:0,D:0}}function Mo(t,e){let n=or(),r=n;for(let o of t)switch(o.status){case "synced":r.S+=1;break;case "waiting":r.P+=1;break;case "processing":r.I+=1;break;case "failed":r.F+=1;break;case "conflict":r.C+=1;break;case "blocked":r.B+=1;break;}return r.N=r.S+r.P+r.I+r.F+r.C+r.B,r.D=e,n}function Ja(t,e){return t.length===e.length&&t.every((n,r)=>n===e[r])}function Xa(t,e,n){return t.bindingId===e.bindingId&&t.accountKey===e.session.accountKey&&t.workspaceId===e.workspaceId&&t.rootFingerprint===n&&t.appId===T}function Fe(t){return crypto.createHash("sha256").update(t,"utf8").digest("hex")}function _t(t){return t instanceof f||t&&typeof t=="object"&&"code"in t&&typeof t.code=="string"?t.code:t instanceof Error?t.message:""}function Fo(t,e){if(t instanceof f&&t.retryAfterMs!==void 0||t&&typeof t=="object"&&"retryAfterMs"in t&&typeof t.retryAfterMs=="number")return e+Math.max(t.retryAfterMs,0)}function ir(t){return t instanceof f||t&&typeof t=="object"&&"status"in t&&typeof t.status=="number"?t.status:void 0}function tr(t){let e=_t(t);if(Ft.has(e))return false;let n=ir(t);return un.has(e)||n===401||n===403}function Qa(t){let e=ir(t);return e!==void 0&&e>=400&&e<500}function nr(t){let e=ir(t);return e!==void 0?e===408||e===425||e===429||e>=500:za.has(_t(t))}var sr=class{constructor(e){this.limit=e;if(!Number.isSafeInteger(e)||e<1)throw new Error("INVALID_SEMAPHORE_LIMIT")}limit;active=0;waiters=[];async run(e,n){await this.acquire(e);try{return await n()}finally{this.release();}}acquire(e){return e.aborted?Promise.reject(this.abortError()):this.active<this.limit?(this.active+=1,Promise.resolve()):new Promise((n,r)=>{let o={signal:e,resolve:()=>{e.removeEventListener("abort",o.onAbort),n();},reject:s=>{e.removeEventListener("abort",o.onAbort),r(s);},onAbort:()=>{let s=this.waiters.indexOf(o);s>=0&&this.waiters.splice(s,1),o.reject(this.abortError());}};this.waiters.push(o),e.addEventListener("abort",o.onAbort,{once:true}),e.aborted&&o.onAbort();})}release(){for(;this.waiters.length>0;){let e=this.waiters.shift();if(e.signal.aborted){e.reject(this.abortError());continue}e.resolve();return}this.active=Math.max(0,this.active-1);}abortError(){return Object.assign(new Error("APP_SYNC_SESSION_STALE"),{code:"APP_SYNC_SESSION_STALE"})}};d();P();d();P();M();d();P();F();q();M();U();wr();d();P();F();q();M();U();d();vr();d();P();F();q();M();d();U();var Pr=["outcome_plan","contract_check","feature_link","use_verify","result_review"];new Set(Pr);F();q();d();q();U();U();U();U();Ot();Ot();fo();on();Nt();Ot();Ot();St();d();P();d();var ga=["success","failed","completed"];new Set(ga);Cn();Ot();_o();vn();var tp=[{key:"usageBackfill",field:"metadata.usageBackfill",before:"before_usage_backfill",after:"after_usage_backfill"},{key:"usageAccounting",field:"metadata.usageAccounting",before:"before_usage_accounting",after:"after_usage_accounting"},{key:"usageAccountingReason",field:"metadata.usageAccountingReason",before:"before_usage_accounting_reason",after:"after_usage_accounting_reason"},{key:"usageByEpoch",field:"metadata.usageByEpoch",before:"before_usage_by_epoch",after:"after_usage_by_epoch"},{key:"usageIncomplete",field:"metadata.usageIncomplete",before:"before_usage_incomplete",after:"after_usage_incomplete"}];["run_epoch","completed_at","input_tokens","output_tokens","cached_input_tokens","cost_usd","model",...tp.map(t=>t.field)];Cn();d();P();F();q();M();U();St();Nt();d();d();Jt();d();P();F();q();M();U();d();P();F();q();M();U();d();var fa=["urgent","high","medium","low"],ha=["investigating","in-progress","in-review","on-hold","done"];new Set(fa);new Set(ha);Nt();new Set(Os);new Set(Ns);new Set(vs);new Set(Ds);new Set(Ps);d();P();F();q();M();U();d();P();F();q();M();U();d();P();F();q();M();U();d();P();d();P();F();M();M();d();P();F();M();d();P();F();q();M();U();d();P();F();q();M();U();d();P();F();q();M();U();d();P();F();q();M();U();d();P();F();q();M();U();d();P();F();q();Nt();St();Lr();kt.map(t=>`'${t}'`).join(", ");var Eo=class extends D{handle;sqlite;constructor(e){super();let n=e??this.resolveDbPath();this.handle=x(n),this.sqlite=this.handle.sqlite,H(this.handle.db,n);}close(){this.handle.close();}bind(e){if(this.assertAccountKey(e.accountKey),this.assertText(e.bindingId,"bindingId",128),this.assertText(e.workspaceId,"workspaceId",256),e.appId!==T)throw new Error("APP_SYNC_APP_UNSUPPORTED");let n=lt(e.rootSegments);if(!n)throw new Error("APP_SYNC_ROOT_INVALID");let r=this.getBindingForAccountApp(e.accountKey,e.appId);if(r){if(r.workspaceId!==e.workspaceId||!Ra(r.rootSegments,n))throw new Error("APP_SYNC_ROOT_ALREADY_BOUND");return r}try{this.sqlite.prepare(`
|
|
76
|
+
INSERT INTO app_sync_bindings (
|
|
77
|
+
binding_id, account_key, workspace_id, app_id, root_segments,
|
|
78
|
+
grant_id, grant_generation, scope_version, status, created_at, updated_at
|
|
79
|
+
) VALUES (?, ?, ?, ?, ?, NULL, NULL, NULL, 'local_only', ?, ?)
|
|
80
|
+
`).run(e.bindingId,e.accountKey,e.workspaceId,e.appId,JSON.stringify(n),e.now,e.now);}catch(s){let i=this.getBindingForAccountApp(e.accountKey,e.appId);if(i){if(i.workspaceId===e.workspaceId&&Ra(i.rootSegments,n))return i;throw new Error("APP_SYNC_ROOT_ALREADY_BOUND")}throw kp(s)?new Error("APP_SYNC_BINDING_ID_CONFLICT"):s}let o=this.getBinding(e.bindingId);if(!o)throw new Error("APP_SYNC_BINDING_WRITE_FAILED");return o}getBinding(e){let n=this.sqlite.prepare("SELECT * FROM app_sync_bindings WHERE binding_id = ?").get(e);return n?yo(n):void 0}getBindingForAccountApp(e,n){let r=this.sqlite.prepare("SELECT * FROM app_sync_bindings WHERE account_key = ? AND app_id = ?").get(e,n);return r?yo(r):void 0}beginControlRequest(e){let n=this.getBinding(e.bindingId);if(!n||n.accountKey!==e.accountKey||n.appId!==e.appId||n.workspaceId!==e.workspaceId||me(JSON.stringify(n.rootSegments))!==e.rootFingerprint)throw new Error("APP_SYNC_CONTROL_REQUEST_BINDING_MISMATCH");if(this.assertAccountKey(e.accountKey),this.assertText(e.requestId,"requestId",128),this.assertText(e.workspaceId,"workspaceId",256),e.state!=="pending"||e.resolvedAt!==null||e.resolution!==null||e.resolutionId!==null)throw new Error("APP_SYNC_CONTROL_REQUEST_INITIAL_STATE_INVALID");if(!/^[0-9a-f]{64}$/.test(e.rootFingerprint))throw new Error("APP_SYNC_ROOT_FINGERPRINT_INVALID");if(e.kind==="revoke"&&(e.grantId!==n.grantId||e.generation!==n.grantGeneration||!e.grantId||!e.generation))throw new Error("APP_SYNC_CONTROL_REQUEST_GRANT_MISMATCH");let r=this.getControlRequest(e.requestId);if(r){if(!Ea(r,e))throw new Error("APP_SYNC_CONTROL_REQUEST_ID_REUSED");return r}try{this.sqlite.prepare(`
|
|
81
|
+
INSERT INTO app_sync_control_requests (
|
|
82
|
+
request_id, binding_id, account_key, app_id, workspace_id, root_fingerprint,
|
|
83
|
+
kind, state, grant_id, generation, created_at, updated_at, resolved_at, resolution, resolution_id
|
|
84
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
85
|
+
`).run(e.requestId,e.bindingId,e.accountKey,e.appId,e.workspaceId,e.rootFingerprint,e.kind,e.state,e.grantId,e.generation,e.createdAt,e.updatedAt,e.resolvedAt,e.resolution,e.resolutionId);}catch(s){let i=this.getControlRequest(e.requestId);if(i){if(!Ea(i,e))throw new Error("APP_SYNC_CONTROL_REQUEST_ID_REUSED");return i}throw this.getPendingControlRequest(e.bindingId)?new Error("APP_SYNC_CONTROL_REQUEST_PENDING"):s}let o=this.getControlRequest(e.requestId);if(!o)throw new Error("APP_SYNC_CONTROL_REQUEST_WRITE_FAILED");return o}getControlRequest(e){let n=this.sqlite.prepare("SELECT * FROM app_sync_control_requests WHERE request_id = ?").get(e);return n?wo(n):void 0}getPendingControlRequest(e){let n=this.sqlite.prepare(`
|
|
86
|
+
SELECT * FROM app_sync_control_requests
|
|
87
|
+
WHERE binding_id = ? AND state IN ('pending', 'unknown')
|
|
88
|
+
ORDER BY created_at, request_id LIMIT 1
|
|
89
|
+
`).get(e);return n?wo(n):void 0}getConfirmedRevoke(e,n,r){let o=this.sqlite.prepare(`
|
|
90
|
+
SELECT * FROM app_sync_control_requests
|
|
91
|
+
WHERE binding_id = ? AND kind = 'revoke' AND state = 'confirmed'
|
|
92
|
+
AND grant_id = ? AND generation = ?
|
|
93
|
+
ORDER BY resolved_at DESC, request_id LIMIT 1
|
|
94
|
+
`).get(e,n,r);return o?wo(o):void 0}updateControlRequest(e,n){let r=this.getControlRequest(e);if(!r)throw new Error("APP_SYNC_CONTROL_REQUEST_NOT_FOUND");if(r.state==="confirmed"||r.state==="failed"){if(r.state===n.state&&r.grantId===n.grantId&&r.generation===n.generation&&r.resolution===n.resolution&&r.resolutionId===n.resolutionId&&r.resolvedAt===n.resolvedAt)return r;throw new Error("APP_SYNC_CONTROL_REQUEST_ALREADY_RESOLVED")}if(n.state==="pending")throw new Error("APP_SYNC_CONTROL_REQUEST_STATE_TRANSITION_INVALID");if(n.state==="unknown"&&r.state!=="pending")throw new Error("APP_SYNC_CONTROL_REQUEST_STATE_TRANSITION_INVALID");if(this.sqlite.prepare(`
|
|
95
|
+
UPDATE app_sync_control_requests
|
|
96
|
+
SET state = ?, grant_id = ?, generation = ?, resolution = ?, resolution_id = ?, resolved_at = ?, updated_at = ?
|
|
97
|
+
WHERE request_id = ? AND state IN ('pending', 'unknown')
|
|
98
|
+
`).run(n.state,n.grantId,n.generation,n.resolution,n.resolutionId,n.resolvedAt,n.now,e).changes===0)throw new Error("APP_SYNC_CONTROL_REQUEST_STATE_TRANSITION_INVALID");let s=this.getControlRequest(e);if(!s)throw new Error("APP_SYNC_CONTROL_REQUEST_NOT_FOUND");return s}updateBinding(e,n,r){let o=this.getBinding(e);if(!o)throw new Error("APP_SYNC_BINDING_NOT_FOUND");let s=n.grantId===void 0?o.grantId:n.grantId,i=n.grantGeneration===void 0?o.grantGeneration:n.grantGeneration,a=n.scopeVersion===void 0?o.scopeVersion:n.scopeVersion,c=n.status===void 0?o.status:n.status;this.sqlite.prepare(`
|
|
99
|
+
UPDATE app_sync_bindings
|
|
100
|
+
SET grant_id = ?, grant_generation = ?, scope_version = ?, status = ?, updated_at = ?
|
|
101
|
+
WHERE binding_id = ?
|
|
102
|
+
`).run(s,i,a,c,r,e);}enqueueCreation(e){let n=this.getBinding(e.bindingId);if(!n||n.accountKey!==e.accountKey)throw new Error("APP_SYNC_BINDING_ACCOUNT_MISMATCH");if(n.grantId!==e.grantId||n.grantGeneration!==e.grantGeneration)throw new Error("APP_SYNC_GRANT_STALE");if(this.assertText(e.jobId,"jobId",128),this.assertText(e.requestId,"requestId",128),this.assertText(e.ref,"ref",256),!/^sha256:[0-9a-f]{64}$/.test(e.fingerprint))throw new Error("APP_SYNC_FINGERPRINT_INVALID");let r=()=>this.sqlite.prepare(`
|
|
103
|
+
SELECT * FROM app_sync_creation_jobs
|
|
104
|
+
WHERE binding_id = ? AND grant_id = ? AND grant_generation = ? AND ref = ? AND fingerprint = ?
|
|
105
|
+
AND operation_kind = 'create' AND status IN ('waiting', 'processing')
|
|
106
|
+
ORDER BY created_at, job_id LIMIT 1
|
|
107
|
+
`).get(e.bindingId,e.grantId,e.grantGeneration,e.ref,e.fingerprint),o=r();if(!o){let s=this.sqlite.prepare(`
|
|
108
|
+
SELECT job_id FROM app_sync_creation_jobs
|
|
109
|
+
WHERE binding_id = ? AND grant_id = ? AND grant_generation = ? AND ref = ? AND fingerprint = ?
|
|
110
|
+
AND operation_kind = 'create' AND status = 'failed'
|
|
111
|
+
ORDER BY created_at DESC, job_id DESC LIMIT 1
|
|
112
|
+
`).get(e.bindingId,e.grantId,e.grantGeneration,e.ref,e.fingerprint);s&&(this.sqlite.prepare(`
|
|
113
|
+
UPDATE app_sync_creation_jobs
|
|
114
|
+
SET status = 'waiting', next_attempt_at = 0, updated_at = ?
|
|
115
|
+
WHERE job_id = ? AND status = 'failed'
|
|
116
|
+
`).run(e.now,s.job_id),o=r());}if(o||(this.sqlite.prepare(`
|
|
117
|
+
INSERT OR IGNORE INTO app_sync_creation_jobs (
|
|
118
|
+
job_id, binding_id, account_key, grant_id, grant_generation, ref, request_id,
|
|
119
|
+
fingerprint, operation_kind, document_id, status, attempts, next_attempt_at, created_at, updated_at
|
|
120
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'create', NULL, 'waiting', 0, 0, ?, ?)
|
|
121
|
+
`).run(e.jobId,e.bindingId,e.accountKey,e.grantId,e.grantGeneration,e.ref,e.requestId,e.fingerprint,e.now,e.now),o=r()),!o)throw new Error("APP_SYNC_JOB_WRITE_FAILED");return $n(o)}listRunnableCreations(e,n,r,o){return this.sqlite.prepare(`
|
|
122
|
+
SELECT * FROM app_sync_creation_jobs
|
|
123
|
+
WHERE binding_id = ? AND grant_id = ? AND grant_generation = ?
|
|
124
|
+
AND status IN ('waiting', 'processing') AND next_attempt_at <= ?
|
|
125
|
+
ORDER BY created_at, ref, job_id
|
|
126
|
+
`).all(e,n,r,o).map($n)}claimCreation(e,n,r){if(this.sqlite.prepare(`
|
|
127
|
+
UPDATE app_sync_creation_jobs
|
|
128
|
+
SET status = 'processing', attempts = attempts + 1, next_attempt_at = ?, updated_at = ?
|
|
129
|
+
WHERE job_id = ? AND status IN ('waiting', 'processing') AND next_attempt_at <= ?
|
|
130
|
+
`).run(n+Math.max(r,1),n,e,n).changes===0)return;let s=this.sqlite.prepare("SELECT * FROM app_sync_creation_jobs WHERE job_id = ?").get(e);return s?$n(s):void 0}deferCreation(e,n,r){if(!e||typeof e.jobId!="string"||!Number.isSafeInteger(e.attempts)||e.attempts<1||!Number.isSafeInteger(e.nextAttemptAt)||!Number.isSafeInteger(n)||n<0||!Number.isSafeInteger(r)||r<0)throw new Error("INVALID_APP_SYNC_CREATION_CLAIM");return this.sqlite.prepare(`
|
|
131
|
+
UPDATE app_sync_creation_jobs
|
|
132
|
+
SET status = 'waiting', attempts = CASE WHEN attempts > 0 THEN attempts - 1 ELSE 0 END,
|
|
133
|
+
next_attempt_at = ?, updated_at = ?
|
|
134
|
+
WHERE job_id = ? AND status = 'processing' AND attempts = ? AND next_attempt_at = ?
|
|
135
|
+
`).run(n,r,e.jobId,e.attempts,e.nextAttemptAt).changes===1}updateCreation(e,n){this.sqlite.prepare(`
|
|
136
|
+
UPDATE app_sync_creation_jobs SET status = ?, next_attempt_at = ?, updated_at = ? WHERE job_id = ?
|
|
137
|
+
`).run(n.status,n.nextAttemptAt,n.now,e);}releaseProcessingCreations(e,n,r,o){this.sqlite.prepare(`
|
|
138
|
+
UPDATE app_sync_creation_jobs
|
|
139
|
+
SET status = 'waiting', next_attempt_at = ?, updated_at = ?
|
|
140
|
+
WHERE binding_id = ? AND grant_id = ? AND grant_generation = ? AND status = 'processing'
|
|
141
|
+
`).run(o,o,e,n,r);}invalidateGrantJobs(e,n,r,o){this.sqlite.prepare(`
|
|
142
|
+
UPDATE app_sync_creation_jobs
|
|
143
|
+
SET status = 'invalidated', next_attempt_at = 0, updated_at = ?
|
|
144
|
+
WHERE binding_id = ? AND grant_id = ? AND grant_generation = ? AND status IN ('waiting', 'processing')
|
|
145
|
+
`).run(o,e,n,r);}upsertResult(e){let n=e.attempts??this.getResult(e.bindingId,e.ref)?.attempts??0;this.sqlite.prepare(`
|
|
146
|
+
INSERT INTO app_sync_results (
|
|
147
|
+
binding_id, account_key, ref, grant_id, grant_generation, source_fingerprint,
|
|
148
|
+
synced_fingerprint, document_id, status, error_code, next_attempt_at, attempts, updated_at
|
|
149
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
150
|
+
ON CONFLICT(binding_id, ref) DO UPDATE SET
|
|
151
|
+
account_key = excluded.account_key,
|
|
152
|
+
grant_id = excluded.grant_id,
|
|
153
|
+
grant_generation = excluded.grant_generation,
|
|
154
|
+
source_fingerprint = excluded.source_fingerprint,
|
|
155
|
+
synced_fingerprint = excluded.synced_fingerprint,
|
|
156
|
+
document_id = excluded.document_id,
|
|
157
|
+
status = excluded.status,
|
|
158
|
+
error_code = excluded.error_code,
|
|
159
|
+
next_attempt_at = excluded.next_attempt_at,
|
|
160
|
+
attempts = excluded.attempts,
|
|
161
|
+
updated_at = excluded.updated_at
|
|
162
|
+
`).run(e.bindingId,e.accountKey,e.ref,e.grantId,e.grantGeneration,e.sourceFingerprint,e.syncedFingerprint,e.documentId,e.status,e.errorCode,e.nextAttemptAt??0,n,e.updatedAt);}getResult(e,n){let r=this.sqlite.prepare("SELECT * FROM app_sync_results WHERE binding_id = ? AND ref = ?").get(e,n);return r?wa(r):void 0}listResults(e){return this.sqlite.prepare("SELECT * FROM app_sync_results WHERE binding_id = ? ORDER BY ref").all(e).map(wa)}hasDeletedRef(e,n,r){return this.sqlite.prepare(`
|
|
163
|
+
SELECT 1 AS found FROM app_sync_deleted_refs WHERE account_key = ? AND app_id = ? AND ref_sha256 = ?
|
|
164
|
+
`).get(e,n,r)!==void 0}suppressDeletedRef(e,n,r,o){if(this.assertAccountKey(e),!/^[0-9a-f]{64}$/.test(r))throw new Error("APP_SYNC_REF_HASH_INVALID");this.sqlite.prepare(`
|
|
165
|
+
INSERT OR IGNORE INTO app_sync_deleted_refs (account_key, app_id, ref_sha256, created_at)
|
|
166
|
+
VALUES (?, ?, ?, ?)
|
|
167
|
+
`).run(e,n,r,o);}countDeletedRefs(e,n){return this.sqlite.prepare(`
|
|
168
|
+
SELECT count(*) AS count FROM app_sync_deleted_refs WHERE account_key = ? AND app_id = ?
|
|
169
|
+
`).get(e,n).count}listBindingsForAccount(e){return this.sqlite.prepare("SELECT * FROM app_sync_bindings WHERE account_key = ? ORDER BY created_at, binding_id").all(e).map(yo)}getDiscoveryCheckpoint(e){let n=this.sqlite.prepare("SELECT * FROM app_sync_discovery_checkpoints WHERE binding_id = ?").get(e);return n?ko(n):void 0}beginDiscoveryCycle(e){return this.sqlite.transaction(()=>{this.assertContinuationFence(e.fence);let{binding:r,now:o}=e,s=me(JSON.stringify(r.rootSegments)),i=this.sqlite.prepare("SELECT * FROM app_sync_discovery_checkpoints WHERE binding_id = ?").get(r.bindingId);if(i){if(i.account_key!==r.accountKey||i.workspace_id!==r.workspaceId||i.root_fingerprint!==s)throw new Error("APP_SYNC_ROOT_ALREADY_BOUND");let c=i.grant_id===r.grantId&&i.grant_generation===r.grantGeneration&&i.scope_version===r.scopeVersion,u=i.cycle_started_at!==null&&!(i.docs_complete===1&&i.deleted_complete===1);if(c&&u)return ko(i);if(c&&i.last_cycle_started_at!==null&&o-i.last_cycle_started_at<6e4)return null;c||this.sqlite.prepare(`
|
|
170
|
+
UPDATE app_sync_pending_discoveries
|
|
171
|
+
SET status = 'invalidated', error_code = 'DOC_APP_GRANT_STALE', updated_at = ?
|
|
172
|
+
WHERE binding_id = ? AND status IN ('waiting', 'processing')
|
|
173
|
+
`).run(o,r.bindingId);}this.sqlite.prepare(`
|
|
174
|
+
INSERT INTO app_sync_discovery_checkpoints (
|
|
175
|
+
binding_id, account_key, workspace_id, root_fingerprint, grant_id, grant_generation, scope_version,
|
|
176
|
+
last_cycle_started_at, cycle_started_at, docs_cursor, docs_complete, deleted_cursor, deleted_complete, updated_at
|
|
177
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, NULL, 0, NULL, 0, ?)
|
|
178
|
+
ON CONFLICT(binding_id) DO UPDATE SET
|
|
179
|
+
account_key = excluded.account_key,
|
|
180
|
+
workspace_id = excluded.workspace_id,
|
|
181
|
+
root_fingerprint = excluded.root_fingerprint,
|
|
182
|
+
grant_id = excluded.grant_id,
|
|
183
|
+
grant_generation = excluded.grant_generation,
|
|
184
|
+
scope_version = excluded.scope_version,
|
|
185
|
+
last_cycle_started_at = excluded.last_cycle_started_at,
|
|
186
|
+
cycle_started_at = excluded.cycle_started_at,
|
|
187
|
+
docs_cursor = NULL,
|
|
188
|
+
docs_complete = 0,
|
|
189
|
+
deleted_cursor = NULL,
|
|
190
|
+
deleted_complete = 0,
|
|
191
|
+
updated_at = excluded.updated_at
|
|
192
|
+
`).run(r.bindingId,r.accountKey,r.workspaceId,s,r.grantId,r.grantGeneration,r.scopeVersion,o,o,o),this.assertContinuationFence(e.fence);let a=this.sqlite.prepare("SELECT * FROM app_sync_discovery_checkpoints WHERE binding_id = ?").get(r.bindingId);if(!a)throw new Error("APP_SYNC_DISCOVERY_CHECKPOINT_WRITE_FAILED");return ko(a)})()}resetDiscoveryCycle(e){this.sqlite.transaction(()=>{this.assertContinuationFence(e.fence);let r=me(JSON.stringify(e.binding.rootSegments));if(this.sqlite.prepare(`
|
|
193
|
+
UPDATE app_sync_discovery_checkpoints
|
|
194
|
+
SET last_cycle_started_at = ?, cycle_started_at = ?, docs_cursor = NULL, docs_complete = 0,
|
|
195
|
+
deleted_cursor = NULL, deleted_complete = 0, updated_at = ?
|
|
196
|
+
WHERE binding_id = ? AND account_key = ? AND workspace_id = ? AND root_fingerprint = ?
|
|
197
|
+
AND grant_id = ? AND grant_generation = ? AND scope_version = ?
|
|
198
|
+
`).run(e.now,e.now,e.now,e.binding.bindingId,e.binding.accountKey,e.binding.workspaceId,r,e.binding.grantId,e.binding.grantGeneration,e.binding.scopeVersion).changes===0)throw new Error("APP_SYNC_DISCOVERY_CHECKPOINT_STALE");this.assertContinuationFence(e.fence);})();}commitGrantDocsPage(e){this.sqlite.transaction(()=>{if(this.assertContinuationFence(e.fence),this.assertCheckpointCursor(e.binding,"docs_cursor","docs_complete",e.expectedCursor),e.nextCursor!==null&&e.nextCursor===e.expectedCursor)throw new Error("APP_SYNC_REMOTE_CURSOR_LOOP");let r=this.sqlite.prepare(`
|
|
199
|
+
INSERT INTO app_sync_pending_discoveries (
|
|
200
|
+
binding_id, account_key, grant_id, grant_generation, ref, doc_id, listed_revision, listed_fingerprint,
|
|
201
|
+
app_grant_generation, needs_reattach, needs_reconcile, status, error_code, attempts, updated_at
|
|
202
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 0, 'waiting', NULL, 0, ?)
|
|
203
|
+
ON CONFLICT(binding_id, grant_id, grant_generation, ref) DO UPDATE SET
|
|
204
|
+
needs_reconcile = CASE
|
|
205
|
+
WHEN listed_revision != excluded.listed_revision OR listed_fingerprint != excluded.listed_fingerprint
|
|
206
|
+
OR doc_id != excluded.doc_id THEN 1 ELSE needs_reconcile END,
|
|
207
|
+
doc_id = excluded.doc_id,
|
|
208
|
+
listed_revision = excluded.listed_revision,
|
|
209
|
+
listed_fingerprint = excluded.listed_fingerprint,
|
|
210
|
+
app_grant_generation = excluded.app_grant_generation,
|
|
211
|
+
needs_reattach = excluded.needs_reattach,
|
|
212
|
+
status = CASE WHEN status = 'invalidated' THEN 'waiting' ELSE status END,
|
|
213
|
+
error_code = NULL,
|
|
214
|
+
updated_at = excluded.updated_at
|
|
215
|
+
`);for(let o of e.items){let s=me(o.ref);if(this.hasDeletedRef(e.binding.accountKey,T,s)){this.markResultDeleted(e.binding,o.ref,o.docId,e.now);continue}r.run(e.binding.bindingId,e.binding.accountKey,e.binding.grantId,e.binding.grantGeneration,o.ref,o.docId,o.currentRevision,o.markdownVersion,o.appGrantGeneration,o.needsReattach?1:0,e.now);}this.sqlite.prepare(`
|
|
216
|
+
UPDATE app_sync_discovery_checkpoints
|
|
217
|
+
SET docs_cursor = ?, docs_complete = ?,
|
|
218
|
+
cycle_started_at = CASE WHEN ? = 1 AND deleted_complete = 1 THEN NULL ELSE cycle_started_at END,
|
|
219
|
+
updated_at = ?
|
|
220
|
+
WHERE binding_id = ? AND docs_cursor IS ? AND docs_complete = 0
|
|
221
|
+
`).run(e.nextCursor,e.nextCursor===null?1:0,e.nextCursor===null?1:0,e.now,e.binding.bindingId,e.expectedCursor),this.assertContinuationFence(e.fence);})();}commitDeletedRefsPage(e){this.sqlite.transaction(()=>{if(this.assertContinuationFence(e.fence),this.assertCheckpointCursor(e.binding,"deleted_cursor","deleted_complete",e.expectedCursor),e.nextCursor!==null&&e.nextCursor===e.expectedCursor)throw new Error("APP_SYNC_REMOTE_CURSOR_LOOP");for(let r of e.items){if(!/^[0-9a-f]{64}$/.test(r.refHash))throw new Error("APP_SYNC_REF_HASH_INVALID");this.sqlite.prepare(`
|
|
222
|
+
INSERT OR IGNORE INTO app_sync_deleted_refs (account_key, app_id, ref_sha256, created_at)
|
|
223
|
+
VALUES (?, ?, ?, ?)
|
|
224
|
+
`).run(e.binding.accountKey,T,r.refHash,e.now);let o=this.sqlite.prepare(`
|
|
225
|
+
SELECT ref FROM app_sync_results WHERE binding_id = ? AND account_key = ?
|
|
226
|
+
`).all(e.binding.bindingId,e.binding.accountKey);for(let a of o)me(a.ref)===r.refHash&&this.markResultDeleted(e.binding,a.ref,void 0,e.now);let s=this.sqlite.prepare(`
|
|
227
|
+
SELECT job_id, ref FROM app_sync_creation_jobs
|
|
228
|
+
WHERE binding_id = ? AND account_key = ? AND status IN ('waiting', 'processing')
|
|
229
|
+
`).all(e.binding.bindingId,e.binding.accountKey);for(let a of s)me(a.ref)===r.refHash&&this.sqlite.prepare(`
|
|
230
|
+
UPDATE app_sync_creation_jobs SET status = 'deleted', next_attempt_at = 0, updated_at = ?
|
|
231
|
+
WHERE job_id = ? AND status IN ('waiting', 'processing')
|
|
232
|
+
`).run(e.now,a.job_id);let i=this.sqlite.prepare(`
|
|
233
|
+
SELECT ref FROM app_sync_pending_discoveries WHERE binding_id = ? AND account_key = ?
|
|
234
|
+
`).all(e.binding.bindingId,e.binding.accountKey);for(let a of i)me(a.ref)===r.refHash&&this.sqlite.prepare("DELETE FROM app_sync_pending_discoveries WHERE binding_id = ? AND ref = ?").run(e.binding.bindingId,a.ref);}this.sqlite.prepare(`
|
|
235
|
+
UPDATE app_sync_discovery_checkpoints
|
|
236
|
+
SET deleted_cursor = ?, deleted_complete = ?,
|
|
237
|
+
cycle_started_at = CASE WHEN ? = 1 AND docs_complete = 1 THEN NULL ELSE cycle_started_at END,
|
|
238
|
+
updated_at = ?
|
|
239
|
+
WHERE binding_id = ? AND deleted_cursor IS ? AND deleted_complete = 0
|
|
240
|
+
`).run(e.nextCursor,e.nextCursor===null?1:0,e.nextCursor===null?1:0,e.now,e.binding.bindingId,e.expectedCursor),this.assertContinuationFence(e.fence);})();}listPendingDiscoveries(e,n,r,o=500){let s=Math.min(Math.max(Math.trunc(o),1),500);return this.sqlite.prepare(`
|
|
241
|
+
SELECT * FROM app_sync_pending_discoveries
|
|
242
|
+
WHERE binding_id = ? AND grant_id = ? AND grant_generation = ? AND status IN ('waiting', 'processing')
|
|
243
|
+
ORDER BY ref LIMIT ?
|
|
244
|
+
`).all(e,n,r,s).map(So)}getPendingDiscovery(e,n,r,o){let s=this.sqlite.prepare(`
|
|
245
|
+
SELECT * FROM app_sync_pending_discoveries
|
|
246
|
+
WHERE binding_id = ? AND grant_id = ? AND grant_generation = ? AND ref = ?
|
|
247
|
+
`).get(e,n,r,o);return s?So(s):void 0}updatePendingDiscovery(e){this.sqlite.transaction(()=>{this.assertContinuationFence(e.fence);let r=this.sqlite.prepare(`
|
|
248
|
+
SELECT * FROM app_sync_pending_discoveries
|
|
249
|
+
WHERE binding_id = ? AND grant_id = ? AND grant_generation = ? AND ref = ?
|
|
250
|
+
`).get(e.bindingId,e.grantId,e.generation,e.ref);if(!r)return;let o={...So(r),...e.patch};gp(o),this.sqlite.prepare(`
|
|
251
|
+
UPDATE app_sync_pending_discoveries
|
|
252
|
+
SET doc_id = ?, listed_revision = ?, listed_fingerprint = ?, app_grant_generation = ?,
|
|
253
|
+
needs_reattach = ?, needs_reconcile = ?, status = ?, error_code = ?, attempts = ?, updated_at = ?
|
|
254
|
+
WHERE binding_id = ? AND grant_id = ? AND grant_generation = ? AND ref = ?
|
|
255
|
+
`).run(o.docId,o.listedRevision,o.listedFingerprint,o.appGrantGeneration,o.needsReattach?1:0,o.needsReconcile?1:0,o.status,o.errorCode,o.attempts,e.now,e.bindingId,e.grantId,e.generation,e.ref),this.assertContinuationFence(e.fence);})();}completePendingDiscovery(e){this.sqlite.transaction(()=>{this.assertContinuationFence(e.fence),this.sqlite.prepare(`
|
|
256
|
+
DELETE FROM app_sync_pending_discoveries
|
|
257
|
+
WHERE binding_id = ? AND grant_id = ? AND grant_generation = ? AND ref = ?
|
|
258
|
+
`).run(e.bindingId,e.grantId,e.generation,e.ref),this.assertContinuationFence(e.fence);})();}recordKnownDeletion(e){if(me(e.ref)!==e.refHash)throw new Error("APP_SYNC_REF_HASH_INVALID");this.sqlite.transaction(()=>{this.assertContinuationFence(e.fence),this.sqlite.prepare(`
|
|
259
|
+
INSERT OR IGNORE INTO app_sync_deleted_refs (account_key, app_id, ref_sha256, created_at)
|
|
260
|
+
VALUES (?, ?, ?, ?)
|
|
261
|
+
`).run(e.binding.accountKey,T,e.refHash,e.now),this.markResultDeleted(e.binding,e.ref,e.documentId,e.now),this.sqlite.prepare(`
|
|
262
|
+
UPDATE app_sync_creation_jobs SET status = 'deleted', next_attempt_at = 0, updated_at = ?
|
|
263
|
+
WHERE binding_id = ? AND ref = ? AND status IN ('waiting', 'processing')
|
|
264
|
+
`).run(e.now,e.binding.bindingId,e.ref),this.sqlite.prepare(`
|
|
265
|
+
DELETE FROM app_sync_pending_discoveries WHERE binding_id = ? AND ref = ?
|
|
266
|
+
`).run(e.binding.bindingId,e.ref),this.assertContinuationFence(e.fence);})();}recordContinuationOutcome(e){if(e.sourceFingerprint!==null&&!/^sha256:[0-9a-f]{64}$/.test(e.sourceFingerprint))throw new Error("APP_SYNC_FINGERPRINT_INVALID");if(e.syncedFingerprint!==null&&!/^sha256:[0-9a-f]{64}$/.test(e.syncedFingerprint))throw new Error("APP_SYNC_FINGERPRINT_INVALID");if(e.errorCode!==null&&!/^[A-Z0-9_:-]{1,128}$/.test(e.errorCode))throw new Error("APP_SYNC_RESULT_ERROR_CODE_INVALID");this.sqlite.transaction(()=>{this.assertContinuationFence(e.fence),this.sqlite.prepare(`
|
|
267
|
+
INSERT INTO app_sync_results (
|
|
268
|
+
binding_id, account_key, ref, grant_id, grant_generation, source_fingerprint, synced_fingerprint,
|
|
269
|
+
document_id, status, error_code, next_attempt_at, attempts, updated_at
|
|
270
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 0, 0, ?)
|
|
271
|
+
ON CONFLICT(binding_id, ref) DO UPDATE SET
|
|
272
|
+
account_key = excluded.account_key,
|
|
273
|
+
grant_id = excluded.grant_id,
|
|
274
|
+
grant_generation = excluded.grant_generation,
|
|
275
|
+
source_fingerprint = excluded.source_fingerprint,
|
|
276
|
+
synced_fingerprint = excluded.synced_fingerprint,
|
|
277
|
+
document_id = excluded.document_id,
|
|
278
|
+
status = excluded.status,
|
|
279
|
+
error_code = excluded.error_code,
|
|
280
|
+
next_attempt_at = 0,
|
|
281
|
+
attempts = 0,
|
|
282
|
+
updated_at = excluded.updated_at
|
|
283
|
+
`).run(e.binding.bindingId,e.binding.accountKey,e.ref,e.grant.grantId,e.grant.generation,e.sourceFingerprint,e.syncedFingerprint,e.documentId,e.status,e.errorCode,e.now),this.assertContinuationFence(e.fence);})();}enqueueReattachJob(e){return this.sqlite.transaction(()=>{if(this.assertContinuationFence(e.fence),this.assertText(e.requestId,"requestId",128),this.assertText(e.jobId,"jobId",128),this.assertText(e.ref,"ref",256),this.assertText(e.documentId,"documentId",128),!/^sha256:[0-9a-f]{64}$/.test(e.fingerprint))throw new Error("APP_SYNC_FINGERPRINT_INVALID");if(e.binding.grantId!==e.grant.grantId||e.binding.grantGeneration!==e.grant.generation)throw new Error("DOC_APP_GRANT_STALE");let r=this.sqlite.prepare(`
|
|
284
|
+
SELECT * FROM app_sync_creation_jobs
|
|
285
|
+
WHERE binding_id = ? AND grant_id = ? AND grant_generation = ? AND ref = ? AND fingerprint = ?
|
|
286
|
+
AND operation_kind = 'reattach' AND document_id = ?
|
|
287
|
+
ORDER BY created_at DESC, job_id DESC LIMIT 1
|
|
288
|
+
`).get(e.binding.bindingId,e.grant.grantId,e.grant.generation,e.ref,e.fingerprint,e.documentId);if(r&&(r.status==="failed"||r.status==="conflict")&&(this.sqlite.prepare(`
|
|
289
|
+
UPDATE app_sync_creation_jobs SET status = 'waiting', next_attempt_at = 0, updated_at = ?
|
|
290
|
+
WHERE job_id = ?
|
|
291
|
+
`).run(e.now,r.job_id),r=this.sqlite.prepare("SELECT * FROM app_sync_creation_jobs WHERE job_id = ?").get(r.job_id)),r||(this.sqlite.prepare(`
|
|
292
|
+
INSERT OR IGNORE INTO app_sync_creation_jobs (
|
|
293
|
+
job_id, binding_id, account_key, grant_id, grant_generation, ref, request_id,
|
|
294
|
+
fingerprint, operation_kind, document_id, status, attempts, next_attempt_at, created_at, updated_at
|
|
295
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'reattach', ?, 'waiting', 0, 0, ?, ?)
|
|
296
|
+
`).run(e.jobId,e.binding.bindingId,e.binding.accountKey,e.grant.grantId,e.grant.generation,e.ref,e.requestId,e.fingerprint,e.documentId,e.now,e.now),r=this.sqlite.prepare(`
|
|
297
|
+
SELECT * FROM app_sync_creation_jobs
|
|
298
|
+
WHERE binding_id = ? AND grant_id = ? AND grant_generation = ? AND ref = ? AND fingerprint = ?
|
|
299
|
+
AND operation_kind = 'reattach' AND document_id = ?
|
|
300
|
+
ORDER BY created_at DESC, job_id DESC LIMIT 1
|
|
301
|
+
`).get(e.binding.bindingId,e.grant.grantId,e.grant.generation,e.ref,e.fingerprint,e.documentId)),!r)throw new Error("APP_SYNC_REATTACH_JOB_WRITE_FAILED");return this.assertContinuationFence(e.fence),$n(r)})()}putConflict(e){return fp(e.conflict),this.sqlite.transaction(()=>{this.assertContinuationFence(e.fence),mp(e.conflict,e.fence);let r=this.getConflict(e.conflict.conflictId);if(r&&!yp(r,e.conflict))throw new Error("APP_SYNC_CONFLICT_IDENTITY_MISMATCH");if(r?.state==="resolved"||r?.state==="kept_both")return r;let o=r?.preservationStatus==="ready"?"ready":e.conflict.preservationStatus,s=r?.vaultHandle??e.conflict.vaultHandle,i={...e.conflict,preservationStatus:o,vaultHandle:s};this.sqlite.prepare(`
|
|
302
|
+
INSERT INTO app_sync_conflicts (
|
|
303
|
+
conflict_id, binding_id, account_key, workspace_id, root_fingerprint, grant_id, grant_generation,
|
|
304
|
+
scope_version, ref, doc_id, local_version, local_fingerprint, baseline_revision, baseline_fingerprint,
|
|
305
|
+
remote_revision, remote_fingerprint, needs_reattach, vault_handle, preservation_status, state, superseded_by,
|
|
306
|
+
resolution_request_id, resolution_choice, cleanup_pending, created_at, updated_at
|
|
307
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
308
|
+
ON CONFLICT(conflict_id) DO UPDATE SET
|
|
309
|
+
vault_handle = excluded.vault_handle,
|
|
310
|
+
preservation_status = excluded.preservation_status,
|
|
311
|
+
updated_at = excluded.updated_at
|
|
312
|
+
`).run(i.conflictId,i.bindingId,i.accountKey,i.workspaceId,i.rootFingerprint,i.grantId,i.grantGeneration,i.scopeVersion,i.ref,i.documentId,i.localVersion,i.localFingerprint,i.baselineRevision,i.baselineFingerprint,i.remoteRevision,i.remoteFingerprint,i.needsReattach?1:0,i.vaultHandle,i.preservationStatus,i.state,i.supersededBy,i.resolutionRequestId,i.resolutionChoice,i.cleanupPending?1:0,i.createdAt,i.updatedAt),i.preservationStatus==="ready"&&i.vaultHandle&&this.sqlite.prepare(`
|
|
313
|
+
UPDATE app_sync_conflicts
|
|
314
|
+
SET state = 'superseded', superseded_by = ?, updated_at = ?
|
|
315
|
+
WHERE binding_id = ? AND ref = ? AND conflict_id <> ? AND state = 'open'
|
|
316
|
+
AND preservation_status = 'ready' AND vault_handle IS NOT NULL
|
|
317
|
+
`).run(i.conflictId,e.conflict.updatedAt,i.bindingId,i.ref,i.conflictId),this.assertContinuationFence(e.fence);let a=this.getConflict(i.conflictId);if(!a)throw new Error("APP_SYNC_CONFLICT_WRITE_FAILED");return a})()}rebindConflict(e){return this.sqlite.transaction(()=>{this.assertContinuationFence(e.fence);let r=this.getConflict(e.conflictId);if(!r||r.bindingId!==e.fence.bindingId||r.state!=="open"||r.preservationStatus!=="ready"||!r.vaultHandle)throw new Error("APP_SYNC_CONFLICT_REBIND_INVALID");if(e.grant.grantId!==e.fence.grantId||e.grant.generation!==e.fence.grantGeneration||e.grant.scopeVersion!==e.fence.scopeVersion)throw new Error("DOC_APP_GRANT_STALE");this.sqlite.prepare(`
|
|
318
|
+
UPDATE app_sync_conflicts
|
|
319
|
+
SET grant_id = ?, grant_generation = ?, scope_version = ?, needs_reattach = ?, updated_at = ?
|
|
320
|
+
WHERE conflict_id = ? AND state = 'open' AND preservation_status = 'ready'
|
|
321
|
+
`).run(e.grant.grantId,e.grant.generation,e.grant.scopeVersion,e.needsReattach?1:0,e.now,e.conflictId),this.assertContinuationFence(e.fence);let o=this.getConflict(e.conflictId);if(!o)throw new Error("APP_SYNC_CONFLICT_NOT_FOUND");return o})()}supersedeOpenConflicts(e){this.sqlite.transaction(()=>{this.assertContinuationFence(e.fence),this.sqlite.prepare(`
|
|
322
|
+
UPDATE app_sync_conflicts
|
|
323
|
+
SET state = 'superseded', superseded_by = ?, updated_at = ?
|
|
324
|
+
WHERE binding_id = ? AND ref = ? AND conflict_id <> ? AND state = 'open'
|
|
325
|
+
AND preservation_status = 'ready' AND vault_handle IS NOT NULL
|
|
326
|
+
`).run(e.supersededBy,e.now,e.bindingId,e.ref,e.supersededBy),this.assertContinuationFence(e.fence);})();}getConflict(e){let n=this.sqlite.prepare("SELECT * FROM app_sync_conflicts WHERE conflict_id = ?").get(e);return n?Sa(n):void 0}listConflicts(e){return this.sqlite.prepare(`
|
|
327
|
+
SELECT * FROM app_sync_conflicts WHERE binding_id = ? ORDER BY created_at, conflict_id
|
|
328
|
+
`).all(e).map(Sa)}beginConflictResolution(e){hp(e),this.sqlite.transaction(()=>{this.assertContinuationFence(e.fence);let r=this.getConflict(e.conflictId);if(!r||r.bindingId!==e.fence.bindingId||r.accountKey!==e.fence.accountKey)throw new Error("APP_SYNC_CONFLICT_NOT_FOUND");if(r.preservationStatus!=="ready"||!r.vaultHandle)throw new Error("APP_SYNC_CONFLICT_NOT_PRESERVED");if(r.localVersion!==e.expectedLocalVersion||r.remoteRevision!==e.expectedRemoteRevision||r.remoteFingerprint!==e.expectedRemoteFingerprint)throw new Error("APP_SYNC_CONFLICT_STALE");if(r.state==="superseded"&&e.choice!=="keep_both")throw new Error("APP_SYNC_CONFLICT_SUPERSEDED");let o=this.sqlite.prepare("SELECT * FROM app_sync_conflict_resolutions WHERE request_id = ?").get(e.requestId);if(o){if(!(o.conflict_id===e.conflictId&&o.account_key===e.fence.accountKey&&o.human_identity===e.humanIdentity&&o.choice===e.choice&&o.expected_local_version===e.expectedLocalVersion&&o.expected_remote_revision===e.expectedRemoteRevision&&o.expected_remote_fingerprint===e.expectedRemoteFingerprint))throw new Error("APP_SYNC_REQUEST_ID_REUSED");if(o.state==="stale"||o.state==="failed")throw new Error("APP_SYNC_CONFLICT_RESOLUTION_ALREADY_ENDED");if(r.state==="resolved"||r.state==="kept_both"||r.state==="resolving"&&r.resolutionRequestId===e.requestId)return;throw new Error("APP_SYNC_CONFLICT_RESOLUTION_IN_PROGRESS")}if(r.state!=="open"&&!(r.state==="superseded"&&e.choice==="keep_both"))throw new Error("APP_SYNC_CONFLICT_RESOLUTION_IN_PROGRESS");this.sqlite.prepare(`
|
|
329
|
+
INSERT INTO app_sync_conflict_resolutions (
|
|
330
|
+
request_id, conflict_id, account_key, human_identity, choice, expected_local_version,
|
|
331
|
+
expected_remote_revision, expected_remote_fingerprint, state, error_code, created_at, updated_at
|
|
332
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'pending', NULL, ?, ?)
|
|
333
|
+
`).run(e.requestId,e.conflictId,e.fence.accountKey,e.humanIdentity,e.choice,e.expectedLocalVersion,e.expectedRemoteRevision,e.expectedRemoteFingerprint,e.now,e.now),this.sqlite.prepare(`
|
|
334
|
+
UPDATE app_sync_conflicts SET state = 'resolving', resolution_request_id = ?, resolution_choice = ?, updated_at = ?
|
|
335
|
+
WHERE conflict_id = ? AND state IN ('open', 'superseded')
|
|
336
|
+
`).run(e.requestId,e.choice,e.now,e.conflictId),this.assertContinuationFence(e.fence);})();}finishConflictResolution(e){return this.sqlite.transaction(()=>{this.assertContinuationFence(e.fence);let r=this.getConflict(e.conflictId);if(!r||r.bindingId!==e.fence.bindingId)throw new Error("APP_SYNC_CONFLICT_NOT_FOUND");if(r.resolutionRequestId===e.requestId&&r.state===(e.choice==="keep_both"?"kept_both":"resolved"))return r;if(this.sqlite.prepare(`
|
|
337
|
+
UPDATE app_sync_conflict_resolutions SET state = 'resolved', error_code = NULL, updated_at = ?
|
|
338
|
+
WHERE request_id = ? AND conflict_id = ? AND state IN ('pending', 'unknown')
|
|
339
|
+
`).run(e.now,e.requestId,e.conflictId).changes===0)throw new Error("APP_SYNC_CONFLICT_RESOLUTION_INTENT_MISSING");this.sqlite.prepare(`
|
|
340
|
+
UPDATE app_sync_conflicts SET state = ?, resolution_request_id = ?, resolution_choice = ?,
|
|
341
|
+
cleanup_pending = CASE WHEN ? = 'keep_both' OR vault_handle IS NULL THEN 0 ELSE 1 END, updated_at = ?
|
|
342
|
+
WHERE conflict_id = ? AND state = 'resolving' AND resolution_request_id = ?
|
|
343
|
+
`).run(e.choice==="keep_both"?"kept_both":"resolved",e.requestId,e.choice,e.choice,e.now,e.conflictId,e.requestId),this.assertContinuationFence(e.fence);let s=this.getConflict(e.conflictId);if(!s)throw new Error("APP_SYNC_CONFLICT_NOT_FOUND");return s})()}abortConflictResolution(e){this.sqlite.transaction(()=>{this.assertContinuationFence(e.fence),this.sqlite.prepare(`
|
|
344
|
+
UPDATE app_sync_conflict_resolutions SET state = ?, error_code = ?, updated_at = ?
|
|
345
|
+
WHERE request_id = ? AND conflict_id = ? AND state IN ('pending', 'unknown')
|
|
346
|
+
`).run(e.state,e.errorCode,e.now,e.requestId,e.conflictId),this.sqlite.prepare(`
|
|
347
|
+
UPDATE app_sync_conflicts
|
|
348
|
+
SET state = CASE WHEN superseded_by IS NULL THEN 'open' ELSE 'superseded' END,
|
|
349
|
+
resolution_request_id = NULL, resolution_choice = NULL, updated_at = ?
|
|
350
|
+
WHERE conflict_id = ? AND resolution_request_id = ? AND state = 'resolving'
|
|
351
|
+
`).run(e.now,e.conflictId,e.requestId),this.assertContinuationFence(e.fence);})();}markConflictResolutionUnknown(e){this.sqlite.transaction(()=>{this.assertContinuationFence(e.fence);let r=this.getConflict(e.conflictId);if(!r||r.bindingId!==e.fence.bindingId||r.state!=="resolving"||r.resolutionRequestId!==e.requestId)throw new Error("APP_SYNC_CONFLICT_RESOLUTION_INTENT_MISSING");this.sqlite.prepare(`
|
|
352
|
+
UPDATE app_sync_conflict_resolutions SET state = 'unknown', updated_at = ?
|
|
353
|
+
WHERE request_id = ? AND conflict_id = ? AND state IN ('pending', 'unknown')
|
|
354
|
+
`).run(e.now,e.requestId,e.conflictId),this.assertContinuationFence(e.fence);})();}finishConflictArchiveCleanup(e){this.sqlite.transaction(()=>{this.assertContinuationFence(e.fence),this.sqlite.prepare(`
|
|
355
|
+
UPDATE app_sync_conflicts SET vault_handle = NULL, cleanup_pending = 0, updated_at = ?
|
|
356
|
+
WHERE conflict_id = ? AND binding_id = ? AND state = 'resolved'
|
|
357
|
+
`).run(e.now,e.conflictId,e.fence.bindingId),this.assertContinuationFence(e.fence);})();}markConflictPurging(e){return this.sqlite.transaction(()=>{this.assertPurgeFence(e.fence);let r=this.getConflict(e.conflictId);if(!r||r.bindingId!==e.fence.bindingId||r.accountKey!==e.fence.accountKey)throw new Error("APP_SYNC_CONFLICT_NOT_FOUND");r.state!=="purging"&&this.sqlite.prepare(`
|
|
358
|
+
UPDATE app_sync_conflicts SET state = 'purging', cleanup_pending = 0, updated_at = ?
|
|
359
|
+
WHERE conflict_id = ? AND state IN ('open', 'resolving', 'superseded', 'resolved', 'kept_both')
|
|
360
|
+
`).run(e.now,e.conflictId),this.assertPurgeFence(e.fence);let o=this.getConflict(e.conflictId);if(!o||o.state!=="purging")throw new Error("APP_SYNC_CONFLICT_PURGE_STATE_INVALID");return o})()}deletePurgedConflict(e){this.sqlite.transaction(()=>{this.assertPurgeFence(e.fence);let r=this.getConflict(e.conflictId);if(!r||r.bindingId!==e.fence.bindingId||r.state!=="purging"||r.vaultHandle!==e.expectedVaultHandle)throw new Error("APP_SYNC_CONFLICT_PURGE_STATE_INVALID");this.sqlite.prepare(`
|
|
361
|
+
DELETE FROM app_sync_conflicts WHERE conflict_id = ? AND binding_id = ? AND state = 'purging'
|
|
362
|
+
AND vault_handle IS ?
|
|
363
|
+
`).run(e.conflictId,e.fence.bindingId,e.expectedVaultHandle),this.assertPurgeFence(e.fence);})();}beginAccountDataPurge(e){this.sqlite.transaction(()=>{if(this.assertPurgeFence(e.fence),this.assertText(e.requestId,"requestId",128),!/^[0-9a-f]{64}$/.test(e.humanIdentity))throw new Error("APP_SYNC_HUMAN_IDENTITY_INVALID");let r=me(JSON.stringify(e.binding.rootSegments));if(e.binding.bindingId!==e.fence.bindingId||e.binding.accountKey!==e.fence.accountKey||e.binding.workspaceId!==e.fence.workspaceId||r!==e.fence.rootFingerprint)throw new Error("APP_SYNC_CONFLICT_BINDING_MISMATCH");let o=this.getAccountDataPurge(e.requestId);if(o){if(o.bindingId!==e.binding.bindingId||o.accountKey!==e.binding.accountKey||o.workspaceId!==e.binding.workspaceId||o.rootFingerprint!==r||o.humanIdentity!==e.humanIdentity)throw new Error("APP_SYNC_PURGE_REQUEST_ID_REUSED");return}if(this.sqlite.prepare(`
|
|
364
|
+
SELECT request_id FROM app_sync_account_data_purges
|
|
365
|
+
WHERE binding_id = ? AND state = 'pending' LIMIT 1
|
|
366
|
+
`).get(e.binding.bindingId))throw new Error("APP_SYNC_ACCOUNT_DATA_PURGE_IN_PROGRESS");this.sqlite.prepare(`
|
|
367
|
+
INSERT INTO app_sync_account_data_purges (
|
|
368
|
+
request_id, binding_id, account_key, workspace_id, root_fingerprint, human_identity, state, created_at, updated_at
|
|
369
|
+
) VALUES (?, ?, ?, ?, ?, ?, 'pending', ?, ?)
|
|
370
|
+
`).run(e.requestId,e.binding.bindingId,e.binding.accountKey,e.binding.workspaceId,r,e.humanIdentity,e.now,e.now),this.assertPurgeFence(e.fence);})();}getAccountDataPurge(e){let n=this.sqlite.prepare("SELECT * FROM app_sync_account_data_purges WHERE request_id = ?").get(e);if(n)return {requestId:n.request_id,bindingId:n.binding_id,accountKey:n.account_key,workspaceId:n.workspace_id,rootFingerprint:n.root_fingerprint,humanIdentity:n.human_identity,state:n.state}}finishAccountDataPurge(e){this.sqlite.transaction(()=>{this.assertPurgeFence(e.fence);let r=this.getAccountDataPurge(e.requestId),o=me(JSON.stringify(e.binding.rootSegments));if(!r||r.bindingId!==e.binding.bindingId||r.accountKey!==e.binding.accountKey||r.workspaceId!==e.binding.workspaceId||r.rootFingerprint!==o)throw new Error("APP_SYNC_PURGE_REQUEST_NOT_FOUND");if(r.state==="complete")return;if(this.sqlite.prepare("SELECT count(*) AS count FROM app_sync_conflicts WHERE binding_id = ?").get(e.binding.bindingId).count!==0)throw new Error("APP_SYNC_PURGE_ARCHIVES_REMAIN");if(this.sqlite.prepare(`
|
|
371
|
+
DELETE FROM doc_sync_links
|
|
372
|
+
WHERE account_key = ? AND workspace_id = ? AND app_id = ? AND root_segments = ? AND connection_kind = 'app_grant'
|
|
373
|
+
`).run(e.binding.accountKey,e.binding.workspaceId,T,JSON.stringify(e.binding.rootSegments)),this.sqlite.prepare("DELETE FROM app_sync_deleted_refs WHERE account_key = ? AND app_id = ?").run(e.binding.accountKey,T),this.sqlite.prepare("DELETE FROM app_sync_bindings WHERE binding_id = ? AND account_key = ?").run(e.binding.bindingId,e.binding.accountKey).changes!==1)throw new Error("APP_SYNC_PURGE_BINDING_DELETE_FAILED");this.sqlite.prepare(`
|
|
374
|
+
UPDATE app_sync_account_data_purges SET state = 'complete', updated_at = ?
|
|
375
|
+
WHERE request_id = ? AND state = 'pending'
|
|
376
|
+
`).run(e.now,e.requestId),e.fence.assertCurrent();})();}assertCheckpointCursor(e,n,r,o){let s=this.sqlite.prepare("SELECT * FROM app_sync_discovery_checkpoints WHERE binding_id = ?").get(e.bindingId);if(!s||s.grant_id!==e.grantId||s.grant_generation!==e.grantGeneration||s.scope_version!==e.scopeVersion||s[n]!==o||s[r]!==0)throw new Error("APP_SYNC_DISCOVERY_CURSOR_RACE")}markResultDeleted(e,n,r,o){this.sqlite.prepare("SELECT * FROM app_sync_results WHERE binding_id = ? AND ref = ?").get(e.bindingId,n)&&this.sqlite.prepare(`
|
|
377
|
+
UPDATE app_sync_results SET account_key = ?, grant_id = ?, grant_generation = ?,
|
|
378
|
+
document_id = COALESCE(?, document_id), status = 'deleted', error_code = 'DOC_APP_REF_DELETED',
|
|
379
|
+
next_attempt_at = 0, updated_at = ?
|
|
380
|
+
WHERE binding_id = ? AND ref = ?
|
|
381
|
+
`).run(e.accountKey,e.grantId,e.grantGeneration,r??null,o,e.bindingId,n);}assertContinuationFence(e){e.assertCurrent();let n=this.getBinding(e.bindingId);if(!n||n.accountKey!==e.accountKey||n.workspaceId!==e.workspaceId||me(JSON.stringify(n.rootSegments))!==e.rootFingerprint)throw new Error("APP_SYNC_ROOT_STALE");if(n.grantId!==e.grantId||n.grantGeneration!==e.grantGeneration||n.scopeVersion!==e.scopeVersion)throw new Error("DOC_APP_GRANT_STALE");if(n.status==="revoked"||n.status==="stopping"||n.status==="unavailable")throw new Error(n.status==="stopping"?"APP_SYNC_REVOKE_PENDING":"DOC_APP_GRANT_REQUIRED");if(this.sqlite.prepare(`
|
|
382
|
+
SELECT 1 AS found FROM app_sync_control_requests
|
|
383
|
+
WHERE binding_id = ? AND kind = 'revoke' AND state IN ('pending', 'unknown') LIMIT 1
|
|
384
|
+
`).get(n.bindingId))throw new Error("APP_SYNC_REVOKE_PENDING");if(this.sqlite.prepare(`
|
|
385
|
+
SELECT 1 AS found FROM app_sync_account_data_purges
|
|
386
|
+
WHERE binding_id = ? AND state = 'pending' LIMIT 1
|
|
387
|
+
`).get(n.bindingId))throw new Error("APP_SYNC_ACCOUNT_DATA_PURGE_PENDING");e.assertCurrent();}assertPurgeFence(e){e.assertCurrent();let n=this.getBinding(e.bindingId);if(!n||n.accountKey!==e.accountKey||n.workspaceId!==e.workspaceId||me(JSON.stringify(n.rootSegments))!==e.rootFingerprint)throw new Error("APP_SYNC_ROOT_STALE");if(n.grantId&&(n.grantId!==e.grantId||n.grantGeneration!==e.grantGeneration))throw new Error("DOC_APP_GRANT_STALE");if(n.status==="stopping")throw new Error("APP_SYNC_REVOKE_PENDING");if(this.sqlite.prepare(`
|
|
388
|
+
SELECT 1 AS found FROM app_sync_control_requests
|
|
389
|
+
WHERE binding_id = ? AND kind = 'revoke' AND state IN ('pending', 'unknown') LIMIT 1
|
|
390
|
+
`).get(n.bindingId))throw new Error("APP_SYNC_REVOKE_PENDING");e.assertCurrent();}assertAccountKey(e){if(!/^[0-9a-f]{64}$/.test(e))throw new Error("APP_SYNC_ACCOUNT_KEY_INVALID")}assertText(e,n,r){if(typeof e!="string"||e.length===0||e.length>r||e.includes("\0"))throw new Error(`APP_SYNC_${n.toUpperCase()}_INVALID`)}};function yo(t){let e;try{e=JSON.parse(t.root_segments);}catch{throw new Error("APP_SYNC_ROOT_STORAGE_INVALID")}if(!Array.isArray(e)||e.some(n=>typeof n!="string"))throw new Error("APP_SYNC_ROOT_STORAGE_INVALID");return {bindingId:t.binding_id,accountKey:t.account_key,workspaceId:t.workspace_id,appId:T,rootSegments:e,grantId:t.grant_id,grantGeneration:t.grant_generation,scopeVersion:t.scope_version,status:t.status,createdAt:t.created_at,updatedAt:t.updated_at}}function $n(t){return {jobId:t.job_id,bindingId:t.binding_id,accountKey:t.account_key,grantId:t.grant_id,grantGeneration:t.grant_generation,ref:t.ref,requestId:t.request_id,fingerprint:t.fingerprint,operationKind:t.operation_kind==="reattach"?"reattach":"create",documentId:t.document_id,status:t.status,attempts:t.attempts,nextAttemptAt:t.next_attempt_at,createdAt:t.created_at,updatedAt:t.updated_at}}function ko(t){return {bindingId:t.binding_id,accountKey:t.account_key,workspaceId:t.workspace_id,rootFingerprint:t.root_fingerprint,grantId:t.grant_id,grantGeneration:t.grant_generation,scopeVersion:t.scope_version,lastCycleStartedAt:t.last_cycle_started_at,cycleStartedAt:t.cycle_started_at,docsCursor:t.docs_cursor,docsComplete:t.docs_complete===1,deletedCursor:t.deleted_cursor,deletedComplete:t.deleted_complete===1,updatedAt:t.updated_at}}function So(t){return {bindingId:t.binding_id,accountKey:t.account_key,grantId:t.grant_id,grantGeneration:t.grant_generation,ref:t.ref,docId:t.doc_id,listedRevision:t.listed_revision,listedFingerprint:t.listed_fingerprint,appGrantGeneration:t.app_grant_generation,needsReattach:t.needs_reattach===1,needsReconcile:t.needs_reconcile===1,status:t.status,errorCode:t.error_code,attempts:t.attempts,updatedAt:t.updated_at}}function Sa(t){return {conflictId:t.conflict_id,bindingId:t.binding_id,accountKey:t.account_key,workspaceId:t.workspace_id,rootFingerprint:t.root_fingerprint,grantId:t.grant_id,grantGeneration:t.grant_generation,scopeVersion:t.scope_version,ref:t.ref,documentId:t.doc_id,localVersion:t.local_version,localFingerprint:t.local_fingerprint,baselineRevision:t.baseline_revision,baselineFingerprint:t.baseline_fingerprint,remoteRevision:t.remote_revision,remoteFingerprint:t.remote_fingerprint,needsReattach:t.needs_reattach===1,vaultHandle:t.vault_handle,preservationStatus:t.preservation_status,state:t.state,supersededBy:t.superseded_by,resolutionRequestId:t.resolution_request_id,resolutionChoice:t.resolution_choice,cleanupPending:t.cleanup_pending===1,createdAt:t.created_at,updatedAt:t.updated_at}}function gp(t){if(!/^[0-9a-f]{64}$/.test(t.accountKey)||typeof t.ref!="string"||t.ref.length<1||t.ref.length>256||typeof t.docId!="string"||t.docId.length<1||t.docId.length>128||!Number.isSafeInteger(t.listedRevision)||t.listedRevision<0||!/^sha256:[0-9a-f]{64}$/.test(t.listedFingerprint)||!Number.isSafeInteger(t.grantGeneration)||t.grantGeneration<1||!Number.isSafeInteger(t.appGrantGeneration)||t.appGrantGeneration<1||!Number.isSafeInteger(t.attempts)||t.attempts<0||!["waiting","processing","failed","invalidated"].includes(t.status))throw new Error("APP_SYNC_PENDING_DISCOVERY_INVALID");if(t.errorCode!==null&&!/^[A-Z0-9_:-]{1,128}$/.test(t.errorCode))throw new Error("APP_SYNC_PENDING_DISCOVERY_METADATA_INVALID")}function fp(t){if(!/^[A-Za-z0-9_-]{1,128}$/.test(t.conflictId)||!/^[0-9a-f]{64}$/.test(t.accountKey)||!/^[0-9a-f]{64}$/.test(t.rootFingerprint)||typeof t.workspaceId!="string"||t.workspaceId.length<1||t.workspaceId.length>256||typeof t.ref!="string"||t.ref.length<1||t.ref.length>256||typeof t.documentId!="string"||t.documentId.length<1||t.documentId.length>128||!Ro(t.localVersion)||!/^sha256:[0-9a-f]{64}$/.test(t.localFingerprint)||!Number.isSafeInteger(t.remoteRevision)||t.remoteRevision<0||!/^sha256:[0-9a-f]{64}$/.test(t.remoteFingerprint)||!["pending","ready","failed"].includes(t.preservationStatus)||!["open","resolving","superseded","resolved","kept_both","purging"].includes(t.state)||t.supersededBy!==null&&!/^[A-Za-z0-9_-]{1,128}$/.test(t.supersededBy)||t.state==="superseded"&&t.supersededBy===null||!Number.isSafeInteger(t.createdAt)||!Number.isSafeInteger(t.updatedAt)||t.updatedAt<t.createdAt)throw new Error("APP_SYNC_CONFLICT_METADATA_INVALID");if(t.baselineRevision===null!=(t.baselineFingerprint===null))throw new Error("APP_SYNC_CONFLICT_BASELINE_INVALID");if(t.baselineRevision!==null&&(!Number.isSafeInteger(t.baselineRevision)||t.baselineRevision<0||!/^sha256:[0-9a-f]{64}$/.test(t.baselineFingerprint??"")))throw new Error("APP_SYNC_CONFLICT_BASELINE_INVALID");if(t.vaultHandle!==null&&!Ro(t.vaultHandle))throw new Error("APP_SYNC_CONFLICT_HANDLE_INVALID");if(!(t.state==="open"?t.preservationStatus==="ready"&&t.vaultHandle!==null&&!t.cleanupPending||t.preservationStatus!=="ready"&&t.vaultHandle===null&&!t.cleanupPending:t.state==="resolving"||t.state==="superseded"?t.preservationStatus==="ready"&&t.vaultHandle!==null&&!t.cleanupPending:t.state==="purging"?!t.cleanupPending:t.state==="kept_both"?t.preservationStatus==="ready"&&t.resolutionRequestId!==null&&t.resolutionChoice==="keep_both"&&t.vaultHandle!==null&&!t.cleanupPending:t.preservationStatus==="ready"&&t.resolutionRequestId!==null&&(t.cleanupPending?t.vaultHandle!==null:t.vaultHandle===null)))throw new Error("APP_SYNC_CONFLICT_PRESERVATION_INVALID");if(t.resolutionRequestId===null!=(t.resolutionChoice===null))throw new Error("APP_SYNC_CONFLICT_RESOLUTION_INVALID")}function hp(t){if(typeof t.requestId!="string"||t.requestId.length<1||t.requestId.length>128||t.requestId.includes("\0")||!/^[0-9a-f]{64}$/.test(t.humanIdentity)||!["keep_local","use_cloud","keep_both"].includes(t.choice)||!Ro(t.expectedLocalVersion)||!Number.isSafeInteger(t.expectedRemoteRevision)||t.expectedRemoteRevision<0||!/^sha256:[0-9a-f]{64}$/.test(t.expectedRemoteFingerprint))throw new Error("APP_SYNC_CONFLICT_RESOLUTION_INPUT_INVALID")}function mp(t,e){if(t.bindingId!==e.bindingId||t.accountKey!==e.accountKey||t.workspaceId!==e.workspaceId||t.rootFingerprint!==e.rootFingerprint||t.grantId!==e.grantId||t.grantGeneration!==e.grantGeneration||t.scopeVersion!==e.scopeVersion)throw new Error("APP_SYNC_CONFLICT_BINDING_MISMATCH")}function yp(t,e){return t.bindingId===e.bindingId&&t.accountKey===e.accountKey&&t.workspaceId===e.workspaceId&&t.rootFingerprint===e.rootFingerprint&&t.grantId===e.grantId&&t.grantGeneration===e.grantGeneration&&t.ref===e.ref&&t.documentId===e.documentId&&t.localVersion===e.localVersion&&t.localFingerprint===e.localFingerprint&&t.remoteRevision===e.remoteRevision&&t.remoteFingerprint===e.remoteFingerprint}function Ro(t){return typeof t=="string"&&t.length>=1&&t.length<=256&&!t.includes("/")&&!t.includes("\\")&&!t.includes("\0")&&!t.startsWith("~")&&!/^[A-Za-z]:/.test(t)}function wa(t){return {bindingId:t.binding_id,accountKey:t.account_key,ref:t.ref,grantId:t.grant_id,grantGeneration:t.grant_generation,sourceFingerprint:t.source_fingerprint,syncedFingerprint:t.synced_fingerprint,documentId:t.document_id,status:t.status,errorCode:t.error_code,nextAttemptAt:t.next_attempt_at,attempts:t.attempts,updatedAt:t.updated_at}}function wo(t){return {requestId:t.request_id,bindingId:t.binding_id,accountKey:t.account_key,appId:T,workspaceId:t.workspace_id,rootFingerprint:t.root_fingerprint,kind:t.kind,state:t.state,grantId:t.grant_id,generation:t.generation,createdAt:t.created_at,updatedAt:t.updated_at,resolvedAt:t.resolved_at,resolution:t.resolution,resolutionId:t.resolution_id}}function Ea(t,e){return t.requestId===e.requestId&&t.bindingId===e.bindingId&&t.accountKey===e.accountKey&&t.appId===e.appId&&t.workspaceId===e.workspaceId&&t.rootFingerprint===e.rootFingerprint&&t.kind===e.kind&&(t.kind==="connect"||t.grantId===e.grantId&&t.generation===e.generation)}function me(t){return crypto.createHash("sha256").update(t,"utf8").digest("hex")}function Ra(t,e){return t.length===e.length&&t.every((n,r)=>n===e[r])}function kp(t){return t instanceof Error&&t.code==="SQLITE_CONSTRAINT_UNIQUE"}exports.APP_SYNC_APP_ID=T;exports.APP_SYNC_CONTINUATION_MAX_PAGE_SIZE=jn;exports.APP_SYNC_CONTINUATION_MIN_INTERVAL_MS=Dt;exports.APP_SYNC_FRONT_MATTER_MAX_BYTES=Gn;exports.APP_SYNC_LOCAL_RECORD_LIMIT=ut;exports.APP_SYNC_PAGE_SIZE=Bn;exports.APP_SYNC_SCOPE_DEFINITION=pe;exports.APP_SYNC_SCOPE_SELECTORS=Wn;exports.APP_SYNC_SCOPE_VERSION=Je;exports.AppSyncBudgetDeferredError=Ge;exports.AppSyncCoordinator=rr;exports.AppSyncRemoteError=f;exports.AppSyncScopeRegistry=Lt;exports.AppSyncSessionFence=xt;exports.DOC001_CREATE_LIMIT_PER_WINDOW=Pt;exports.DOC001_CREATE_WINDOW_MS=sn;exports.SqliteAppSyncStore=Eo;exports.SqliteDocCreateLedger=Kn;exports.createDispatchGate=Mt;exports.fingerprintMarkdown=L;exports.normalizeResolvedRootSegments=lt;
|